Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

test(server): slim the identity and HTTP-surface suites to behaviour tests (#922)

Yaowei Zheng7da441a3f53e
diff --git a/packages/server/package.json b/packages/server/package.json
index 58241f96..ed0ae8b5 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -92,6 +92,7 @@
"@types/mdast": "^4.0.4",
"@types/node": "^24.0.0",
"@types/ws": "^8.18.1",
+ "@vitest/coverage-v8": "^3.2.6",
"tsup": "^8.3.0",
"tsx": "^4.20.0",
"vitest": "^3.2.6"
diff --git a/packages/server/test/admin-settings.test.ts b/packages/server/test/admin-settings.test.ts
index d41160df..cbf05140 100644
--- a/packages/server/test/admin-settings.test.ts
+++ b/packages/server/test/admin-settings.test.ts
@@ -1,25 +1,38 @@
/**
- * Admin server-settings route tests: permission boundary (non-admin 403), the defaults
- * (absent rows read as both proxy switches on with no explicit address, and company mode
- * off), adoption of the legacy single-switch key, PUT persistence and validation
- * (proxy-address normalization and rejection), and merge semantics (an omitted field keeps
- * its current value; a rejected PUT writes nothing).
+ * Admin server settings, as the admin page reads and writes them through /api/admin/settings,
+ * and the proxy reachability probe that rides the same route.
*
- * The upload limits ride the same route and are covered here too: their defaults, the bounded
- * range (the reason "100GB" is a clear refusal rather than an accepted number), the relation
- * between the two — the total may not sit below the per-file cap, checked against the EFFECTIVE
- * post-write pair so a one-field PUT cannot create an unsendable configuration — and the same
- * atomicity guarantee the proxy fields have.
+ * - Given a non-admin, every settings and probe route answers 403, and nothing is written.
+ * - Given no stored rows, the settings read as their defaults: both proxy switches on, no
+ * explicit address, company mode off, the default upload limits.
+ * - Given the legacy single proxy switch stored off, both switches read off, and setting one
+ * of them writes only its own key.
+ * - A PUT persists each proxy switch independently and echoes the full settings.
+ * - A PUT changes only the fields it names; an empty PUT changes nothing.
+ * - A PUT carrying any invalid field is refused and writes none of its fields (the PUT is
+ * atomic across the switches, the address and the upload limits).
+ * - The proxy address is stored and echoed in its normalized form; a bad one is refused as
+ * `invalid_proxy_url`; empty, blank and null clear it back to the environment.
+ * - Upload limits: a valid pair persists and is what the server reads per request; a value
+ * outside the range is refused as `invalid_attachment_limit`; the range's extremes are
+ * accepted; the total may not sit below the per-file cap, checked against the effective
+ * pair after the write.
+ * - A probe outcome is named by what came back: any HTTP answer is reachable, a transport
+ * failure is named by the errno underneath it, and a proxy refusing the CONNECT tunnel is
+ * not a timeout.
+ * - Probing each listed target makes one credential-free request to exactly the listed URL,
+ * and each answer is reported on its own.
+ * - A provider id outside the fixed list is a 404 that reaches no network.
*
- * The reachability probe rides the same route too: the rule that decides reachable from
- * unreachable, and the endpoint around it. Its fetch is always stubbed — a test that reached a
- * real provider would fail on an offline machine and turn CI into a network monitor.
+ * One app serves the file: every case starts from an empty settings table. The probe's fetch
+ * is always the fake, so no case depends on the network.
*/
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type {
ProxyProbeDto,
ProxyProbeResponse,
ProxyProbeTargetsResponse,
+ ServerSettings,
ServerSettingsResponse,
} from "../src/api/types.js";
import { classifyProxyProbe } from "../src/services/proxy-probe.js";
@@ -29,6 +42,7 @@ import {
MAX_ATTACHMENT_MB,
MIN_ATTACHMENT_MB,
} from "../src/services/attachment-limits.js";
+import { fetchFailed, stubFetch } from "./fixtures/fetch.js";
import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
@@ -36,322 +50,240 @@ describe("admin server settings", () => {
let t: TestApp;
let admin: ReturnType<typeof apiClient>;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
});
- afterEach(async () => {
+ afterAll(async () => {
+ await t.cleanup();
+ });
+ beforeEach(() => {
+ t.deps.db.exec("DELETE FROM server_settings");
+ });
+ afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
- await t.cleanup();
});
- const getSettings = async (api: ReturnType<typeof apiClient> = admin) => {
- const res = await api.get("/api/admin/settings");
+ const getSettings = async (): Promise<ServerSettings> => {
+ const res = await admin.get("/api/admin/settings");
expect(res.status).toBe(200);
- return (await res.json()) as ServerSettingsResponse;
+ return ((await res.json()) as ServerSettingsResponse).settings;
};
+ const put = (body: unknown) => admin.put("/api/admin/settings", body);
+ const errorCode = async (res: Response) =>
+ ((await res.json()) as { error: { code: string } }).error.code;
- it("non-admin access is always 403", async () => {
+ it("a non-admin gets 403 from every settings and probe route, and writes nothing", async () => {
const { cookie } = await provisionUser(t.app, "norm");
const api = apiClient(t.app, cookie);
expect((await api.get("/api/admin/settings")).status).toBe(403);
expect((await api.put("/api/admin/settings", { proxyForApp: false })).status).toBe(403);
+ expect((await api.put("/api/admin/settings", { attachmentMaxMb: 1 })).status).toBe(403);
// The probe reaches the network on the server's behalf, so it sits behind the same gate,
// and so does the list of what it would reach.
expect((await api.get("/api/admin/settings/proxy-probe")).status).toBe(403);
expect((await api.post("/api/admin/settings/proxy-probe/openai")).status).toBe(403);
- // The failed PUT changed nothing.
- expect((await getSettings()).settings.proxyForApp).toBe(true);
+ const settings = await getSettings();
+ expect(settings.proxyForApp).toBe(true);
+ expect(settings.attachmentMaxMb).toBe(DEFAULT_ATTACHMENT_MAX_MB);
});
- it("defaults while no rows exist: both proxy switches on, company mode off, no explicit address", async () => {
- expect(t.deps.db.prepare("SELECT COUNT(*) AS n FROM server_settings").get()).toMatchObject({
- n: 0,
+ it("with no stored rows, the settings read as their defaults", async () => {
+ expect(await getSettings()).toMatchObject({
+ proxyForApp: true,
+ proxyForAgent: true,
+ proxyUrl: null,
+ // Company mode is the one switch that starts off: an admin opts the server into it.
+ companyMode: false,
+ attachmentMaxMb: DEFAULT_ATTACHMENT_MAX_MB,
+ attachmentTotalMb: DEFAULT_ATTACHMENT_TOTAL_MB,
});
- const { settings } = await getSettings();
- expect(settings.proxyForApp).toBe(true);
- expect(settings.proxyForAgent).toBe(true);
- expect(settings.proxyUrl).toBeNull();
- // Company mode is the one switch that starts off: an admin opts the server into it.
- expect(settings.companyMode).toBe(false);
});
- it("adopts the legacy use_system_proxy row as the default for BOTH switches", async () => {
+ it("a legacy single proxy switch set off turns both switches off until each is set", async () => {
// The single switch shipped only on unreleased main (#225): a deployment that had
- // toggled it off must keep that choice for both new switches, with no migration —
- // the legacy key is read as a fallback, never rewritten.
+ // toggled it off keeps that choice for both new switches, with no migration — the legacy
+ // key is read as a fallback, never rewritten.
t.deps.serverSettingsRepo.set("use_system_proxy", "false");
- let { settings } = await getSettings();
- expect(settings.proxyForApp).toBe(false);
- expect(settings.proxyForAgent).toBe(false);
- // Setting one NEW switch writes only its own key: the other still follows legacy.
- await admin.put("/api/admin/settings", { proxyForApp: true });
- ({ settings } = await getSettings());
- expect(settings.proxyForApp).toBe(true);
- expect(settings.proxyForAgent).toBe(false);
- // The legacy row itself was never touched.
+ expect(await getSettings()).toMatchObject({ proxyForApp: false, proxyForAgent: false });
+ // Setting one new switch writes only its own key: the other still follows the legacy one.
+ await put({ proxyForApp: true });
+ expect(await getSettings()).toMatchObject({ proxyForApp: true, proxyForAgent: false });
expect(t.deps.serverSettingsRepo.get("use_system_proxy")).toBe("false");
});
- it("PUT persists the switches independently and echoes the full settings", async () => {
- const appOff = await admin.put("/api/admin/settings", { proxyForApp: false });
+ it("a PUT persists each proxy switch independently and echoes the full settings", async () => {
+ const appOff = await put({ proxyForApp: false });
expect(appOff.status).toBe(200);
- const afterAppOff = ((await appOff.json()) as ServerSettingsResponse).settings;
- expect(afterAppOff.proxyForApp).toBe(false);
- expect(afterAppOff.proxyForAgent).toBe(true);
- // Round-trips through the repo (the DB rows, not process state, are what GET serves).
- expect(t.deps.serverSettingsRepo.getProxyForApp()).toBe(false);
- expect(t.deps.serverSettingsRepo.getProxyForAgent()).toBe(true);
-
- const agentOff = await admin.put("/api/admin/settings", { proxyForAgent: false });
- expect(agentOff.status).toBe(200);
- const { settings } = await getSettings();
- expect(settings.proxyForApp).toBe(false);
- expect(settings.proxyForAgent).toBe(false);
+ expect(((await appOff.json()) as ServerSettingsResponse).settings).toMatchObject({
+ proxyForApp: false,
+ proxyForAgent: true,
+ });
+ expect((await put({ proxyForAgent: false })).status).toBe(200);
+ expect(await getSettings()).toMatchObject({ proxyForApp: false, proxyForAgent: false });
});
- it("an omitted field keeps its current value; a non-boolean is 400", async () => {
- await admin.put("/api/admin/settings", { proxyForApp: false });
- // Empty PUT: no-op, still returns the current settings.
- const noop = await admin.put("/api/admin/settings", {});
+ it("a PUT changes only the fields it names", async () => {
+ await put({ proxyForApp: false, proxyForAgent: false });
+ // An empty PUT is a no-op that still answers with the current settings.
+ const noop = await put({});
expect(noop.status).toBe(200);
expect(((await noop.json()) as ServerSettingsResponse).settings.proxyForApp).toBe(false);
- // Type check: only booleans are accepted, and a rejected write changes nothing.
- expect((await admin.put("/api/admin/settings", { proxyForApp: "on" })).status).toBe(400);
- expect((await admin.put("/api/admin/settings", { proxyForAgent: 1 })).status).toBe(400);
- const { settings } = await getSettings();
- expect(settings.proxyForApp).toBe(false);
- expect(settings.proxyForAgent).toBe(true);
+ // Address only: the switches keep their values…
+ await put({ proxyUrl: "proxy.corp.example:8080" });
+ expect(await getSettings()).toMatchObject({
+ proxyForApp: false,
+ proxyForAgent: false,
+ proxyUrl: "http://proxy.corp.example:8080",
+ });
+ // …and switches only: the address keeps its value.
+ await put({ proxyForApp: true, proxyForAgent: true });
+ expect(await getSettings()).toMatchObject({
+ proxyForApp: true,
+ proxyForAgent: true,
+ proxyUrl: "http://proxy.corp.example:8080",
+ });
});
- const putProxyUrl = async (proxyUrl: unknown) => admin.put("/api/admin/settings", { proxyUrl });
+ it.each([
+ ["a non-boolean app switch", { proxyForApp: "on" }],
+ ["a non-boolean agent switch", { proxyForAgent: 1 }],
+ [
+ "a bad address beside valid switches",
+ { proxyForApp: false, proxyForAgent: false, proxyUrl: "not a proxy" },
+ ],
+ ["a bad upload limit beside a valid switch", { proxyForApp: false, attachmentMaxMb: 999999 }],
+ ])("a PUT carrying %s is refused and writes none of its fields", async (_case, body) => {
+ const before = await getSettings();
+ expect((await put(body)).status).toBe(400);
+ expect(await getSettings()).toEqual(before);
+ });
- it("PUT normalizes the proxy address and stores/echoes only the normalized form", async () => {
- // Bare host[:port] shorthand → http://.
- const bare = await putProxyUrl("proxy.corp.example:8080");
- expect(bare.status).toBe(200);
- expect(((await bare.json()) as ServerSettingsResponse).settings.proxyUrl).toBe(
+ it("stores and echoes the proxy address in its normalized form", async () => {
+ // Bare host[:port] shorthand is read as http://; the unit suite covers the rest of the forms.
+ const res = await put({ proxyUrl: " proxy.corp.example:8080 " });
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as ServerSettingsResponse).settings.proxyUrl).toBe(
"http://proxy.corp.example:8080",
);
- expect((await getSettings()).settings.proxyUrl).toBe("http://proxy.corp.example:8080");
- expect(t.deps.serverSettingsRepo.getProxyUrl()).toBe("http://proxy.corp.example:8080");
- // https passes through; surrounding whitespace is trimmed.
- const https = await putProxyUrl(" https://proxy.corp.example:3128 ");
- expect(https.status).toBe(200);
- expect(((await https.json()) as ServerSettingsResponse).settings.proxyUrl).toBe(
- "https://proxy.corp.example:3128",
- );
- // socks5 rides through to undici's dispatcher untouched.
- const socks = await putProxyUrl("socks5://proxy.corp.example:1080");
- expect(socks.status).toBe(200);
- expect(((await socks.json()) as ServerSettingsResponse).settings.proxyUrl).toBe(
- "socks5://proxy.corp.example:1080",
- );
+ expect((await getSettings()).proxyUrl).toBe("http://proxy.corp.example:8080");
});
- it("PUT rejects a bad proxy address with invalid_proxy_url and stores nothing", async () => {
- await putProxyUrl("http://proxy.corp.example:8080");
+ it("refuses a bad proxy address as invalid_proxy_url and keeps the stored one", async () => {
+ await put({ proxyUrl: "http://proxy.corp.example:8080" });
// socks4 parses as a URL but undici's dispatcher refuses to construct from it.
for (const bad of ["socks4://proxy.corp.example:1080", "not a proxy", 42]) {
- const res = await putProxyUrl(bad);
- expect(res.status).toBe(400);
- const body = (await res.json()) as { error: { code: string } };
- expect(body.error.code).toBe("invalid_proxy_url");
+ const res = await put({ proxyUrl: bad });
+ expect(res.status, String(bad)).toBe(400);
+ expect(await errorCode(res)).toBe("invalid_proxy_url");
}
- expect((await getSettings()).settings.proxyUrl).toBe("http://proxy.corp.example:8080");
- });
-
- it("a rejected combined PUT leaves the other fields untouched too", async () => {
- // Validation happens before any write: the valid switch halves of a PUT whose
- // proxyUrl is garbage must not land either — the PUT is atomic.
- const res = await admin.put("/api/admin/settings", {
- proxyForApp: false,
- proxyForAgent: false,
- proxyUrl: "not a proxy",
- });
- expect(res.status).toBe(400);
- const { settings } = await getSettings();
- expect(settings.proxyForApp).toBe(true);
- expect(settings.proxyForAgent).toBe(true);
- expect(settings.proxyUrl).toBeNull();
+ expect((await getSettings()).proxyUrl).toBe("http://proxy.corp.example:8080");
});
- it("empty string and null both clear the address back to follow-the-environment", async () => {
+ it("clears the address back to the environment with an empty, blank or null value", async () => {
for (const clear of ["", " ", null]) {
- await putProxyUrl("http://proxy.corp.example:8080");
- const res = await putProxyUrl(clear);
+ await put({ proxyUrl: "http://proxy.corp.example:8080" });
+ const res = await put({ proxyUrl: clear });
expect(res.status).toBe(200);
expect(((await res.json()) as ServerSettingsResponse).settings.proxyUrl).toBeNull();
- expect(t.deps.serverSettingsRepo.getProxyUrl()).toBeNull();
+ expect((await getSettings()).proxyUrl).toBeNull();
}
});
- it("partial PUTs keep the other fields: address-only keeps the switches and vice versa", async () => {
- await admin.put("/api/admin/settings", { proxyForApp: false, proxyForAgent: false });
- await putProxyUrl("proxy.corp.example:8080");
- let { settings } = await getSettings();
- expect(settings.proxyForApp).toBe(false);
- expect(settings.proxyForAgent).toBe(false);
- expect(settings.proxyUrl).toBe("http://proxy.corp.example:8080");
- await admin.put("/api/admin/settings", { proxyForApp: true, proxyForAgent: true });
- ({ settings } = await getSettings());
- expect(settings.proxyForApp).toBe(true);
- expect(settings.proxyForAgent).toBe(true);
- expect(settings.proxyUrl).toBe("http://proxy.corp.example:8080");
- });
-
- it("upload limits: defaults with no rows, and a 403 for a non-admin on both verbs", async () => {
- const { settings } = await getSettings();
- expect(settings.attachmentMaxMb).toBe(DEFAULT_ATTACHMENT_MAX_MB);
- expect(settings.attachmentTotalMb).toBe(DEFAULT_ATTACHMENT_TOTAL_MB);
- const { cookie } = await provisionUser(t.app, "limitless");
- const api = apiClient(t.app, cookie);
- expect((await api.get("/api/admin/settings")).status).toBe(403);
- expect((await api.put("/api/admin/settings", { attachmentMaxMb: 1 })).status).toBe(403);
- // The refused PUT wrote nothing.
- expect(t.deps.serverSettingsRepo.getAttachmentMaxMb()).toBe(DEFAULT_ATTACHMENT_MAX_MB);
- });
-
- it("upload limits: a valid PUT persists, echoes, and needs no restart to take effect", async () => {
- const res = await admin.put("/api/admin/settings", {
+ it("a valid pair of upload limits persists and is what the server reads per request", async () => {
+ const res = await put({ attachmentMaxMb: 25, attachmentTotalMb: 40 });
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as ServerSettingsResponse).settings).toMatchObject({
attachmentMaxMb: 25,
attachmentTotalMb: 40,
});
- expect(res.status).toBe(200);
- const echoed = ((await res.json()) as ServerSettingsResponse).settings;
- expect(echoed.attachmentMaxMb).toBe(25);
- expect(echoed.attachmentTotalMb).toBe(40);
- // Round-trip through the repo, which is what the validators and the body cap read per
- // request — the response echoing the right number would not prove the server uses it.
+ // The repo is what the validators and the body cap read per request: the response echoing
+ // the right number would not prove the server uses it.
expect(t.deps.serverSettingsRepo.getAttachmentLimitsMb()).toEqual({
attachmentMaxMb: 25,
attachmentTotalMb: 40,
});
});
- it("upload limits: out-of-range values are refused with invalid_attachment_limit", async () => {
- // 102400 is "100GB" typed into a MB field — the case the bounds exist for. Zero, a negative,
- // a fraction and a string are the other ways a form can produce nonsense.
+ it("refuses an upload limit outside the range as invalid_attachment_limit", async () => {
+ // 102400 is "100GB" typed into a MB field — the case the bounds exist for. Zero, a
+ // negative, a fraction and a string are the other ways a form can produce nonsense.
for (const bad of [102400, MAX_ATTACHMENT_MB + 1, 0, -5, 1.5, "100", null]) {
- const res = await admin.put("/api/admin/settings", { attachmentMaxMb: bad });
+ const res = await put({ attachmentMaxMb: bad });
expect(res.status, JSON.stringify(bad)).toBe(400);
- expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
- "invalid_attachment_limit",
- );
+ expect(await errorCode(res)).toBe("invalid_attachment_limit");
}
- // Nothing was written by any of them.
- expect(t.deps.serverSettingsRepo.getAttachmentMaxMb()).toBe(DEFAULT_ATTACHMENT_MAX_MB);
- });
-
- it("upload limits: the extremes of the allowed range are accepted", async () => {
- const res = await admin.put("/api/admin/settings", {
- attachmentMaxMb: MIN_ATTACHMENT_MB,
- attachmentTotalMb: MIN_ATTACHMENT_MB,
- });
- expect(res.status).toBe(200);
- const max = await admin.put("/api/admin/settings", {
- attachmentMaxMb: MAX_ATTACHMENT_MB,
- attachmentTotalMb: MAX_ATTACHMENT_MB,
- });
- expect(max.status).toBe(200);
- expect(t.deps.serverSettingsRepo.getAttachmentMaxMb()).toBe(MAX_ATTACHMENT_MB);
- });
-
- it("upload limits: the total may not sit below the per-file cap", async () => {
- const both = await admin.put("/api/admin/settings", {
- attachmentMaxMb: 50,
- attachmentTotalMb: 20,
- });
- expect(both.status).toBe(400);
- expect(((await both.json()) as { error: { code: string } }).error.code).toBe(
- "invalid_attachment_limit",
- );
- expect(t.deps.serverSettingsRepo.getAttachmentMaxMb()).toBe(DEFAULT_ATTACHMENT_MAX_MB);
+ expect((await getSettings()).attachmentMaxMb).toBe(DEFAULT_ATTACHMENT_MAX_MB);
});
- it("upload limits: the relation is checked against the effective pair, not just the body", async () => {
- await admin.put("/api/admin/settings", { attachmentMaxMb: 10, attachmentTotalMb: 12 });
- // Raising ONLY the per-file cap past the stored total would leave a legal single attachment
- // unsendable, so it is refused even though the body carries no total at all.
- const raise = await admin.put("/api/admin/settings", { attachmentMaxMb: 100 });
- expect(raise.status).toBe(400);
- // Lowering ONLY the total below the stored per-file cap is the same fault from the other side.
- const lower = await admin.put("/api/admin/settings", { attachmentTotalMb: 5 });
- expect(lower.status).toBe(400);
- // Neither attempt changed anything.
- expect(t.deps.serverSettingsRepo.getAttachmentLimitsMb()).toEqual({
- attachmentMaxMb: 10,
- attachmentTotalMb: 12,
- });
+ it("accepts both extremes of the upload-limit range", async () => {
+ expect(
+ (await put({ attachmentMaxMb: MIN_ATTACHMENT_MB, attachmentTotalMb: MIN_ATTACHMENT_MB }))
+ .status,
+ ).toBe(200);
+ expect(
+ (await put({ attachmentMaxMb: MAX_ATTACHMENT_MB, attachmentTotalMb: MAX_ATTACHMENT_MB }))
+ .status,
+ ).toBe(200);
+ expect((await getSettings()).attachmentMaxMb).toBe(MAX_ATTACHMENT_MB);
});
- it("upload limits: a PUT mixing a good proxy field with a bad limit writes neither", async () => {
- const res = await admin.put("/api/admin/settings", {
- proxyForApp: false,
- attachmentMaxMb: 999999,
- });
+ // Raising only the per-file cap past the stored total, or lowering only the total below the
+ // stored cap, would leave a legal single attachment unsendable: the check reads the pair the
+ // write would leave, not just the body.
+ it.each([
+ ["the body pairs a total below its cap", null, { attachmentMaxMb: 50, attachmentTotalMb: 20 }],
+ ["the cap rises past the stored total", [10, 12], { attachmentMaxMb: 100 }],
+ ["the total drops below the stored cap", [10, 12], { attachmentTotalMb: 5 }],
+ ] as const)("refuses a total below the per-file cap when %s", async (_case, stored, body) => {
+ if (stored !== null) await put({ attachmentMaxMb: stored[0], attachmentTotalMb: stored[1] });
+ const before = await getSettings();
+ const res = await put(body);
expect(res.status).toBe(400);
- const { settings } = await getSettings();
- expect(settings.proxyForApp).toBe(true);
- expect(settings.attachmentMaxMb).toBe(DEFAULT_ATTACHMENT_MAX_MB);
+ expect(await errorCode(res)).toBe("invalid_attachment_limit");
+ expect(await getSettings()).toEqual(before);
});
+
// —— reachability probe ——
- /** undici's shape for a transport failure: `TypeError: fetch failed` over the real error. */
- const fetchFailed = (code: string) =>
- new TypeError("fetch failed", { cause: Object.assign(new Error(code), { code }) });
+ const timedOut = Object.assign(new Error("aborted due to timeout"), { name: "TimeoutError" });
+ // A proxy that refuses the CONNECT tunnel arrives as an AbortError NESTED under "fetch
+ // failed": a refusal to carry the request, not a host that took too long.
+ const tunnelRefused = new TypeError("fetch failed", {
+ cause: Object.assign(new Error("Proxy response (403) !== 200 when HTTP Tunneling"), {
+ name: "AbortError",
+ code: "UND_ERR_ABORTED",
+ }),
+ });
- it("probe classification: any HTTP answer is reachable", () => {
+ it("names a probe outcome by what came back", () => {
// The probe carries no credential, so a rejection is the expected answer — and an answer
// is the whole proof: the name resolved, TCP connected, TLS completed, the host replied.
- expect(classifyProxyProbe({ status: 401 })).toBe("reachable");
- expect(classifyProxyProbe({ status: 403 })).toBe("reachable");
- expect(classifyProxyProbe({ status: 404 })).toBe("reachable");
- expect(classifyProxyProbe({ status: 200 })).toBe("reachable");
- expect(classifyProxyProbe({ status: 503 })).toBe("reachable");
- });
-
- it("probe classification: a transport failure is named by the cause underneath it", () => {
- const timedOut = Object.assign(new Error("aborted due to timeout"), { name: "TimeoutError" });
- expect(classifyProxyProbe({ error: timedOut })).toBe("timeout");
- expect(classifyProxyProbe({ error: fetchFailed("ENOTFOUND") })).toBe("dns");
- expect(classifyProxyProbe({ error: fetchFailed("ECONNREFUSED") })).toBe("refused");
- expect(classifyProxyProbe({ error: fetchFailed("DEPTH_ZERO_SELF_SIGNED_CERT") })).toBe("tls");
- expect(classifyProxyProbe({ error: fetchFailed("ERR_TLS_CERT_ALTNAME_INVALID") })).toBe("tls");
- expect(classifyProxyProbe({ error: fetchFailed("ENETUNREACH") })).toBe("network");
- // A proxy that refuses the CONNECT tunnel arrives as an AbortError NESTED under "fetch
- // failed". That is a refusal to carry the request, not a host that took too long, so only
- // an abort on the outermost error may read as a timeout.
- const tunnelRefused = new TypeError("fetch failed", {
- cause: Object.assign(new Error("Proxy response (403) !== 200 when HTTP Tunneling"), {
- name: "AbortError",
- code: "UND_ERR_ABORTED",
- }),
- });
- expect(classifyProxyProbe({ error: tunnelRefused })).not.toBe("timeout");
+ const cases = [
+ ["an HTTP 401", { status: 401 }, "reachable"],
+ ["an HTTP 503", { status: 503 }, "reachable"],
+ ["our own timeout", { error: timedOut }, "timeout"],
+ ["ENOTFOUND", { error: fetchFailed("ENOTFOUND") }, "dns"],
+ ["ECONNREFUSED", { error: fetchFailed("ECONNREFUSED") }, "refused"],
+ ["a self-signed cert", { error: fetchFailed("DEPTH_ZERO_SELF_SIGNED_CERT") }, "tls"],
+ ["a cert name mismatch", { error: fetchFailed("ERR_TLS_CERT_ALTNAME_INVALID") }, "tls"],
+ ["ENETUNREACH", { error: fetchFailed("ENETUNREACH") }, "network"],
+ ["a refused CONNECT tunnel", { error: tunnelRefused }, "network"],
+ ] as const;
+ for (const [label, attempt, outcome] of cases) {
+ expect(classifyProxyProbe(attempt), label).toBe(outcome);
+ }
});
- it("one request per target: each is reported on its own, with no credential and the listed URL", async () => {
- // The page lists these before anyone presses the button, so they must be the very URLs
- // the probes then request — asserted together at the end of this test.
+ it("probes each listed target once, without a credential, at exactly the listed URL", async () => {
const listed = (await (
await admin.get("/api/admin/settings/proxy-probe")
).json()) as ProxyProbeTargetsResponse;
- expect(listed.targets.map((t) => t.provider)).toEqual([
- "openai",
- "anthropic",
- "gemini",
- "deepseek",
- // GLM is two hosts, not one: a proxy can carry the global endpoint and not the mainland
- // one, which is the difference an admin choosing between the two keys needs to see.
- "zai",
- "bigmodel",
- ]);
+ expect(listed.targets.map((target) => target.provider)).toContain("deepseek");
// Every provider key the process could reach for is present, so "no credential is sent"
- // is a claim about the code rather than about an empty environment: a probe that fell
- // back to these the way protocol detection does would now be caught.
+ // is a claim about the code rather than about an empty environment.
for (const key of [
"OPENAI_API_KEY",
"ANTHROPIC_API_KEY",
@@ -361,24 +293,13 @@ describe("admin server settings", () => {
]) {
vi.stubEnv(key, `secret-${key}`);
}
+ const fake = stubFetch((call) => {
+ // One dead target proves the others are reported independently rather than as a batch.
+ if (call.url.includes("deepseek")) throw fetchFailed("ECONNREFUSED");
+ return new Response("{}", { status: 401 });
+ });
- const requests: Array<{ url: string; init: RequestInit }> = [];
- vi.stubGlobal(
- "fetch",
- vi.fn(async (url: string, init: RequestInit) => {
- requests.push({ url, init });
- // One dead target proves the others are reported independently rather than as a batch
- // that fails whole.
- if (url.includes("deepseek")) throw fetchFailed("ECONNREFUSED");
- // A 5xx is still an answer, so it is still reachable — the rule protocol detection
- // next door deliberately does NOT share, since it reads the response and this does not.
- if (url.includes("googleapis")) return new Response("nope", { status: 503 });
- return new Response("{}", { status: 401 });
- }),
- );
-
- // One call per provider, the way the page fires them — it renders each answer as it
- // lands rather than waiting for a response carrying all of them.
+ // One call per provider, the way the page fires them: each answer renders as it lands.
const probes: ProxyProbeDto[] = [];
for (const target of listed.targets) {
const res = await admin.post(`/api/admin/settings/proxy-probe/${target.provider}`);
@@ -387,42 +308,34 @@ describe("admin server settings", () => {
}
// Each answer names its own target, so a row cannot be filled from another's result.
- expect(probes.map((p) => p.provider)).toEqual(listed.targets.map((t) => t.provider));
- expect(probes.map((p) => p.url)).toEqual(listed.targets.map((t) => t.url));
- expect(probes.filter((p) => p.outcome === "reachable").map((p) => p.status)).toEqual([
- 401, 401, 503, 401, 401,
- ]);
- expect(probes.find((p) => p.provider === "deepseek")).toMatchObject({ outcome: "refused" });
- // Every result is timed, the failed one included.
- for (const probe of probes) expect(probe.ms).toBeGreaterThanOrEqual(0);
- // What was listed is exactly what was fetched: a page that advertises one URL and probes
- // another would be lying about what "no API key" applies to.
- expect(requests.map((r) => r.url)).toEqual(listed.targets.map((t) => t.url));
- // Hard-coded https targets, and not one credential on any of them — the process
- // environment's provider keys must not leak into an unauthenticated probe.
- expect(requests).toHaveLength(listed.targets.length);
- for (const { url, init } of requests) {
- expect(url.startsWith("https://")).toBe(true);
- const headers = new Headers(init.headers);
- expect(headers.get("authorization")).toBeNull();
- expect(headers.get("x-api-key")).toBeNull();
- // Not under any other header name either, and not smuggled into the query string.
- const sent = `${url} ${[...headers].map(([k, v]) => `${k}: ${v}`).join(" ")}`;
+ expect(probes.map((p) => [p.provider, p.url])).toEqual(
+ listed.targets.map((target) => [target.provider, target.url]),
+ );
+ for (const probe of probes) {
+ expect(probe.outcome).toBe(probe.provider === "deepseek" ? "refused" : "reachable");
+ expect(probe.ms).toBeGreaterThanOrEqual(0);
+ }
+ // What was listed is exactly what was fetched, over https, and not one credential rides
+ // along under any header name or in the query string.
+ expect(fake.calls.map((call) => call.url)).toEqual(listed.targets.map((target) => target.url));
+ for (const call of fake.calls) {
+ expect(call.url.startsWith("https://")).toBe(true);
+ const sent = `${call.url} ${[...call.headers].map(([k, v]) => `${k}: ${v}`).join(" ")}`;
expect(sent).not.toContain("secret-");
+ expect(call.headers.get("authorization")).toBeNull();
}
});
- it("a provider id outside the fixed list is a 404 that reaches no network at all", async () => {
- const fetchSpy = vi.fn(async () => new Response("{}", { status: 200 }));
- vi.stubGlobal("fetch", fetchSpy);
+ it("answers 404 to a provider id outside the fixed list, and reaches no network", async () => {
+ const fake = stubFetch(() => new Response("{}", { status: 200 }));
// The route takes an id and never a URL, so an id nobody put in the list must not become
- // a fetch of anything — that is the whole reason this endpoint has no request body.
+ // a fetch of anything — which is why this endpoint has no request body.
for (const provider of ["evil", "openai/../evil", "https://evil.example", "OPENAI", ""]) {
const res = await admin.post(
`/api/admin/settings/proxy-probe/${encodeURIComponent(provider)}`,
);
- expect(res.status).toBe(404);
+ expect(res.status, provider).toBe(404);
}
- expect(fetchSpy).not.toHaveBeenCalled();
+ expect(fake.calls).toEqual([]);
});
});
diff --git a/packages/server/test/api-token.test.ts b/packages/server/test/api-token.test.ts
index 25cb4ae6..5ffe4874 100644
--- a/packages/server/test/api-token.test.ts
+++ b/packages/server/test/api-token.test.ts
@@ -1,29 +1,38 @@
/**
- * Local API token: minted per boot, persisted at <root>/api-token (0600), and accepted
- * by authMiddleware as `Authorization: Bearer` — authenticating as the built-in admin on
- * every protected route, SSE endpoints included (the CLI consumes SSE via fetch with
+ * The local API token: minted per boot, persisted at <root>/api-token (owner-only), and
+ * accepted by authMiddleware as `Authorization: Bearer` — authenticating as the built-in admin
+ * on every protected route, SSE endpoints included (the CLI consumes SSE via fetch with
* headers, so header auth must reach them).
+ *
+ * - A boot persists the token at <root>/api-token with owner-only permissions.
+ * - A valid Bearer authenticates as the admin (sessionVia "token") with no cookie at all.
+ * - A wrong Bearer is 401, even beside a valid cookie: no silent fallback to the cookie.
+ * - A Bearer works on writes (the JSON-only CSRF guard still applies) and on SSE streams.
+ * - The hot-update APIs take the Bearer as the admin credential.
+ * - The next boot's token overwrites the file atomically, owner-only, leaving no temp file.
+ * - An absent or empty token file reads as no token.
+ * - The comparison is constant-time and length-aware, and only a Bearer header shape parses.
*/
import fs from "node:fs";
import path from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { MeResponse, SessionCreateResponse } from "../src/api/types.js";
import { apiTokenPath, readApiToken, storeApiToken, tokensEqual } from "../src/auth/api-token.js";
import { bearerToken } from "../src/auth/middleware.js";
-import { createTestApp } from "./helpers.js";
+import { createTestApp, loginAdmin, makeTempRoot } from "./helpers.js";
import type { TestApp } from "./helpers.js";
describe("local API token", () => {
let t: TestApp;
let token: string;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
const stored = readApiToken(t.root);
expect(stored).not.toBeNull();
token = stored!;
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
@@ -56,7 +65,6 @@ describe("local API token", () => {
it("a wrong Bearer is 401 — even alongside a valid cookie (no silent fallback)", async () => {
expect((await bearer("not-the-token")).status).toBe(401);
- const { loginAdmin } = await import("./helpers.js");
const { cookie } = await loginAdmin(t.app);
const res = await t.app.request("/api/me", {
headers: { authorization: "Bearer not-the-token", cookie },
@@ -123,16 +131,20 @@ describe("local API token", () => {
expect(res.status).not.toBe(403);
});
- it("storeApiToken overwrites the previous boot's file (per-boot rotation)", () => {
- storeApiToken(t.root, "next-boot-token");
- expect(readApiToken(t.root)).toBe("next-boot-token");
- if (process.platform !== "win32") {
- const mode = fs.statSync(apiTokenPath(t.root)).mode & 0o777;
- expect(mode).toBe(0o600);
+ it("overwrites the previous boot's file on the next boot, atomically", async () => {
+ const root = await makeTempRoot();
+ try {
+ storeApiToken(root, "first-boot-token");
+ storeApiToken(root, "next-boot-token");
+ expect(readApiToken(root)).toBe("next-boot-token");
+ if (process.platform !== "win32") {
+ expect(fs.statSync(apiTokenPath(root)).mode & 0o777).toBe(0o600);
+ }
+ // No tmp file left behind by the atomic write.
+ expect(fs.readdirSync(root).filter((f) => f.startsWith("api-token."))).toEqual([]);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
}
- // No tmp file left behind by the atomic write.
- const leftovers = fs.readdirSync(t.root).filter((f) => f.startsWith("api-token."));
- expect(leftovers).toEqual([]);
});
it("tokensEqual: constant-time compare semantics (equal / different / different length)", () => {
@@ -151,9 +163,14 @@ describe("local API token", () => {
expect(bearerToken("Bearer")).toBeNull();
});
- it("readApiToken: absent or empty file reads as null", () => {
+ it("reads an absent or empty token file as no token", async () => {
expect(readApiToken(path.join(t.root, "no-such-subdir"))).toBeNull();
- fs.writeFileSync(apiTokenPath(t.root), "\n");
- expect(readApiToken(t.root)).toBeNull();
+ const root = await makeTempRoot();
+ try {
+ fs.writeFileSync(apiTokenPath(root), "\n");
+ expect(readApiToken(root)).toBeNull();
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
});
});
diff --git a/packages/server/test/auth-sessions.test.ts b/packages/server/test/auth-sessions.test.ts
index 27a75c8c..ee1e0704 100644
--- a/packages/server/test/auth-sessions.test.ts
+++ b/packages/server/test/auth-sessions.test.ts
@@ -1,9 +1,15 @@
/**
- * Sessions as rows in auth_sessions (auth/service.ts): the cookie carries a random token, the
- * row stores its sha256. Every property the row model is chosen FOR is pinned here — a session
- * survives a restart (it is on disk), logout deletes the row, an admin reset deletes the
- * user's rows, and sliding renewal tops the expiry up IN PLACE so the cookie value never
- * changes and a short minted token never stretches into a long one.
+ * Sessions as rows in auth_sessions (auth/service.ts): the cookie carries a random token and
+ * the row stores its sha256. Each property the row model is chosen for is pinned here; an
+ * admin's password reset deleting a user's rows is covered with the reset route in
+ * admin-users.test.ts.
+ *
+ * - Given a v0.2.0 database whose auth_sessions lacks `via`, a boot adds it and login works.
+ * - A session survives a restart, because it is a row on disk.
+ * - Logout deletes the row, and it stays deleted across a restart.
+ * - Expired rows are swept on the next login.
+ * - A long session slides in place: the expiry is topped up and the cookie value never changes.
+ * - A short cli token expires at its hour instead of renewing into a long one.
*/
import path from "node:path";
import { describe, expect, it } from "vitest";
@@ -104,26 +110,6 @@ describe("auth sessions", () => {
}
});
- it("an admin password reset deletes the user's sessions", async () => {
- const t = await createTestApp();
- try {
- const admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
- await admin.post("/api/admin/users", { userId: "alice", password: "alice-pass-1" });
- const login = await t.app.request("/api/auth/login", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ userId: "alice", password: "alice-pass-1" }),
- });
- const aliceCookie = cookieFrom(login);
- expect((await apiClient(t.app, aliceCookie).get("/api/me")).status).toBe(200);
-
- await t.deps.adminService.resetPassword("alice", "fresh-pass-1");
- expect((await apiClient(t.app, aliceCookie).get("/api/me")).status).toBe(401);
- } finally {
- await t.cleanup();
- }
- });
-
it("slides a long session in place, so the cookie value never changes", async () => {
let nowMs = Date.now();
const t = await createTestApp({ now: () => new Date(nowMs) });
diff --git a/packages/server/test/auth-token.test.ts b/packages/server/test/auth-token.test.ts
index 6d6aec6f..6d57ec36 100644
--- a/packages/server/test/auth-token.test.ts
+++ b/packages/server/test/auth-token.test.ts
@@ -1,17 +1,27 @@
/**
- * Minting an API session from the data root (auth-token.ts).
+ * Minting an API session from the data root (auth-token.ts): what `penguin auth token` and the
+ * desktop shell run to sign in without a password.
*
* A session is a row in web.db, so minting opens the database and inserts one — no running
* server, no owner token, no loopback. Reading the root already reaches every credential the
- * token could, so the write adds no authority; the row is a `cli` session the server honors
- * on its next request, or a `desktop` one when the caller is the shell signing its own window
- * in.
+ * token could, so the write adds no authority.
+ *
+ * - Given a root with no web.db, the mint reports no_server.
+ * - Given a server's database, the minted row is a session the server then authenticates.
+ * - A caller's TTL is clamped to the ordinary session ceiling, so a leaked token cannot live
+ * (and slide) forever.
+ * - The session records how it was established: a cli mint reads back as an ordinary password
+ * session, a desktop mint as the shell's own.
+ * - An account that does not exist is refused.
+ * - A database this OS account cannot open fails cleanly, pointing at `penguin auth login`.
*/
import path from "node:path";
-import { describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { CLI_TOKEN_MAX_TTL_MS, mintApiToken } from "../src/auth-token.js";
+import type { MintTokenResult } from "../src/auth-token.js";
import { SESSION_COOKIE } from "../src/auth/middleware.js";
import { apiClient, createTestApp, makeTempRoot } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
describe("minting an API session", () => {
it("reports no_server when the root has no web.db", async () => {
@@ -21,25 +31,6 @@ describe("minting an API session", () => {
});
});
- it("inserts a session row the server then authenticates", async () => {
- const root = await makeTempRoot();
- const dbPath = path.join(root, "web.db");
- // Seed the account by booting an app on this file, then mint against the same file as the
- // CLI would — the app and the mint share one on-disk database, no cross-process hop.
- const t = await createTestApp({ config: { root, dbPath } });
- try {
- const minted = mintApiToken(root, { dbPath, ttlMs: 60_000 });
- expect(minted.outcome).toBe("minted");
- if (minted.outcome !== "minted") return;
- expect(minted.userId).toBe("admin");
- expect(
- (await apiClient(t.app, `${SESSION_COOKIE}=${minted.token}`).get("/api/me")).status,
- ).toBe(200);
- } finally {
- await t.cleanup();
- }
- });
-
/**
* The multi-user case: web.db exists but belongs to another OS account (the one running the
* server), and this caller cannot open it. That must come back as a failed outcome pointing
@@ -65,65 +56,65 @@ describe("minting an API session", () => {
}
},
);
+});
+
+describe("minting against a server's database", () => {
+ let t: TestApp;
+ let root: string;
+ let dbPath: string;
+
+ // The app seeds the account on this file, then each case mints against the same file as the
+ // CLI would: the app and the mint share one on-disk database, no cross-process hop.
+ beforeAll(async () => {
+ root = await makeTempRoot();
+ dbPath = path.join(root, "web.db");
+ t = await createTestApp({ config: { root, dbPath } });
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+
+ const minted = (r: MintTokenResult) => {
+ expect(r.outcome).toBe("minted");
+ if (r.outcome !== "minted") throw new Error(`not minted: ${JSON.stringify(r)}`);
+ return r;
+ };
+ const me = async (token: string) => apiClient(t.app, `${SESSION_COOKIE}=${token}`).get("/api/me");
+
+ it("inserts a session row the server then authenticates", async () => {
+ const r = minted(mintApiToken(root, { dbPath, ttlMs: 60_000 }));
+ expect(r.userId).toBe("admin");
+ expect((await me(r.token)).status).toBe(200);
+ });
/**
- * A caller-supplied lifetime must not exceed an ordinary session's. `--ttl-seconds` only
- * rejects values <= 0, so without the clamp `penguin auth token --ttl-seconds 315360000`
- * writes a ten-year row — and because its span passes the renewal window it would slide
- * forever, turning a leaked cli-session.json into a permanent credential.
+ * `--ttl-seconds` only rejects values <= 0, so without the clamp `penguin auth token
+ * --ttl-seconds 315360000` writes a ten-year row — and because its span passes the renewal
+ * window it would slide forever, turning a leaked cli-session.json into a permanent
+ * credential.
*/
- it("clamps a caller's TTL to the session ceiling", async () => {
- const root = await makeTempRoot();
- const dbPath = path.join(root, "web.db");
- const t = await createTestApp({ config: { root, dbPath } });
- try {
- const now = new Date();
- const r = mintApiToken(root, { dbPath, ttlMs: 10 * 365 * 24 * 60 * 60_000, now });
- expect(r.outcome).toBe("minted");
- if (r.outcome !== "minted") return;
- expect(Date.parse(r.expiresAt)).toBe(now.getTime() + CLI_TOKEN_MAX_TTL_MS);
- } finally {
- await t.cleanup();
- }
+ it("clamps a caller's TTL to the session ceiling", () => {
+ const now = new Date();
+ const r = minted(mintApiToken(root, { dbPath, ttlMs: 10 * 365 * 24 * 60 * 60_000, now }));
+ expect(Date.parse(r.expiresAt)).toBe(now.getTime() + CLI_TOKEN_MAX_TTL_MS);
});
/**
* The desktop shell mints with `via: "desktop"` when it signs its own window in against a
* server it did not spawn, and the session has to read back as that kind — it is what the
* App reads to leave the current-password field out of a form whose account has a password
- * nobody was ever shown. A `cli` mint must keep reading back as an ordinary password
- * session, which is what `penguin auth token` has always produced.
+ * nobody was ever shown. A `cli` mint keeps reading back as an ordinary password session.
*/
it("records how the session was established, defaulting to cli", async () => {
- const root = await makeTempRoot();
- const dbPath = path.join(root, "web.db");
- const t = await createTestApp({ config: { root, dbPath } });
- try {
- const asCli = mintApiToken(root, { dbPath });
- const asDesktop = mintApiToken(root, { dbPath, via: "desktop" });
- expect(asCli.outcome).toBe("minted");
- expect(asDesktop.outcome).toBe("minted");
- if (asCli.outcome !== "minted" || asDesktop.outcome !== "minted") return;
- const viaOf = async (token: string) => {
- const res = await apiClient(t.app, `${SESSION_COOKIE}=${token}`).get("/api/me");
- return ((await res.json()) as { sessionVia: string }).sessionVia;
- };
- expect(await viaOf(asCli.token)).toBe("password");
- expect(await viaOf(asDesktop.token)).toBe("desktop");
- } finally {
- await t.cleanup();
- }
+ const viaOf = async (token: string) =>
+ ((await (await me(token)).json()) as { sessionVia: string }).sessionVia;
+ expect(await viaOf(minted(mintApiToken(root, { dbPath })).token)).toBe("password");
+ expect(await viaOf(minted(mintApiToken(root, { dbPath, via: "desktop" })).token)).toBe(
+ "desktop",
+ );
});
- it("refuses an account that does not exist", async () => {
- const root = await makeTempRoot();
- const dbPath = path.join(root, "web.db");
- const t = await createTestApp({ config: { root, dbPath } });
- try {
- const r = mintApiToken(root, { dbPath, userId: "ghost" });
- expect(r.outcome).toBe("failed");
- } finally {
- await t.cleanup();
- }
+ it("refuses an account that does not exist", () => {
+ expect(mintApiToken(root, { dbPath, userId: "ghost" }).outcome).toBe("failed");
});
});
diff --git a/packages/server/test/auth.test.ts b/packages/server/test/auth.test.ts
index 9c4e2698..1f339762 100644
--- a/packages/server/test/auth.test.ts
+++ b/packages/server/test/auth.test.ts
@@ -1,6 +1,24 @@
/**
- * Auth flow integration tests (via app.request() injection): admin seeding / login /
- * logout / password change / session / initial Project.
+ * The auth flow through the routes: admin seeding, login, logout, password change, the session
+ * cookie, the initial Project and the account's UI preferences.
+ *
+ * - A protected API answers 401 without a session; registration does not exist.
+ * - The seeded admin owns default_project with its default Agent, carries the initial-password
+ * flag, and a second seed neither duplicates the account nor rerolls its password.
+ * - An admin-created account gets `<userId>-default_project`, named after the user, with the
+ * preset default model.
+ * - Login, /api/me and logout round-trip; a wrong password is 401.
+ * - Changing one's own password checks the old one and the policy, keeps the current session,
+ * clears the initial flag, and retires the old password.
+ * - The Secure cookie flag follows x-forwarded-proto only when the proxy is trusted.
+ * - A write with a non-JSON Content-Type is refused (CSRF defense).
+ * - A seed password below the policy is refused before any account is created.
+ * - Login failures back off per username, unknown usernames identically, and a success resets
+ * the counter; an unknown username, a wrong password and an uncheckable hash answer alike.
+ * - An unknown username is checked against one dummy hash, made once by the server's hasher.
+ * - The admin-password check reads the stored hash, not the configured pin.
+ * - Generated initial passwords are 24 base64url characters and never repeat.
+ * - Preferences start empty, and each PUT merges without clobbering another writer's fields.
*/
import fs from "node:fs/promises";
import path from "node:path";
@@ -191,18 +209,6 @@ describe("auth", () => {
expect(res.status).toBe(415);
});
- it("ui prefs read/write", async () => {
- const { cookie } = await provisionUser(t.app, "erin");
- const api = apiClient(t.app, cookie);
- const empty = (await (await api.get("/api/me/prefs")).json()) as { prefs: unknown };
- expect(empty.prefs).toEqual({});
- await api.put("/api/me/prefs", { theme: "dark", lastProjectId: "default_project" });
- const got = (await (await api.get("/api/me/prefs")).json()) as {
- prefs: { theme: string };
- };
- expect(got.prefs.theme).toBe("dark");
- });
-
it("seedAdmin rejects an override below the password policy before creating the account", async () => {
const root = await makeTempRoot();
const deps = flattenForTests(
@@ -356,22 +362,19 @@ describe("auth", () => {
expect(seen.size).toBe(64);
});
- it("PUT prefs shallow-merges without clobbering other writers' fields", async () => {
+ it("starts preferences empty, and merges each PUT without clobbering other writers", async () => {
const { cookie } = await provisionUser(t.app, "fred");
const api = apiClient(t.app, cookie);
- // Simulate two independent writers: switching Project writes lastProjectId, and onboarding writes credentialGuideSeen.
+ const prefs = async () =>
+ ((await (await api.get("/api/me/prefs")).json()) as { prefs: unknown }).prefs;
+ expect(await prefs()).toEqual({});
+ // Two independent writers: switching Project writes lastProjectId, onboarding writes
+ // credentialGuideSeen. The second write must not erase the first's field (a full replace
+ // would drop lastProjectId and bring onboarding back again and again).
await api.put("/api/me/prefs", { lastProjectId: "p-1" });
await api.put("/api/me/prefs", { credentialGuideSeen: true });
- const one = (await (await api.get("/api/me/prefs")).json()) as {
- prefs: { lastProjectId?: string; credentialGuideSeen?: boolean };
- };
- // The second write must not erase the fields from the first (a prior full replace would drop lastProjectId, causing onboarding to reappear repeatedly).
- expect(one.prefs).toEqual({ lastProjectId: "p-1", credentialGuideSeen: true });
- // Switch Project again: credentialGuideSeen is still present.
+ expect(await prefs()).toEqual({ lastProjectId: "p-1", credentialGuideSeen: true });
await api.put("/api/me/prefs", { lastProjectId: "p-2" });
- const two = (await (await api.get("/api/me/prefs")).json()) as {
- prefs: { lastProjectId?: string; credentialGuideSeen?: boolean };
- };
- expect(two.prefs).toEqual({ lastProjectId: "p-2", credentialGuideSeen: true });
+ expect(await prefs()).toEqual({ lastProjectId: "p-2", credentialGuideSeen: true });
});
});
diff --git a/packages/server/test/config.test.ts b/packages/server/test/config.test.ts
index ebe46704..70b44995 100644
--- a/packages/server/test/config.test.ts
+++ b/packages/server/test/config.test.ts
@@ -1,12 +1,17 @@
/**
- * resolveServerConfig parsing tests.
+ * resolveServerConfig: how the server reads its environment.
*
- * PORT: both the default (missing) and empty string (the common `PORT=` empty value in
- * `.env`) fall back to 7364 — Number("") === 0 used to make the empty string pass range
- * validation and bind to a random port; explicit "0" is preserved (explicit semantics
- * for a random available port); invalid values throw. This matches the CLI's
- * resolvePort semantics (packages/cli serve).
- * PENGUIN_SEED_ADMIN_PASSWORD: unset/empty/whitespace → null (random seed password).
+ * - An empty PORT (the common `PORT=` line in `.env`) reads as unset, never as port 0; an
+ * explicit value takes effect and an explicit "0" is kept (bind a random free port); a
+ * non-integer or out-of-range value throws. This matches the CLI's resolvePort.
+ * - PENGUIN_SEED_ADMIN_PASSWORD: unset, empty or blank leaves the seed unpinned (null, so the
+ * seed generates its own); a value is kept trimmed; desktop mode changes neither.
+ * - PENGUIN_CLI_ENTRY: a value is kept trimmed; a blank one falls through to the checkout
+ * lookup like an unset one.
+ * - PENGUIN_GO_ORIGIN accepts a loopback HTTP origin for integration work and refuses anything
+ * that is not a bare origin, or plaintext HTTP to another host.
+ * - MODELSCOPE_BRIDGE_URL may carry a path prefix but refuses plaintext HTTP, credentials, a
+ * query and a fragment.
*/
import { describe, expect, it } from "vitest";
import path from "node:path";
@@ -15,72 +20,59 @@ import { resolveServerConfig } from "../src/config.js";
const base = { PENGUIN_HOME: "/tmp/penguin-config-test" };
describe("resolveServerConfig: PORT parsing", () => {
- it("defaults to 7364; empty string treated as unset (does not fall to port 0)", () => {
- expect(resolveServerConfig({ ...base }).port).toBe(7364);
- expect(resolveServerConfig({ ...base, PORT: "" }).port).toBe(7364);
+ it("reads an empty PORT as unset, not as port 0", () => {
+ const unset = resolveServerConfig({ ...base }).port;
+ expect(unset).not.toBe(0);
+ expect(resolveServerConfig({ ...base, PORT: "" }).port).toBe(unset);
});
- it('explicit value takes effect; "0" is preserved (binds a random available port)', () => {
+ it('takes an explicit value, and keeps "0" (binds a random available port)', () => {
expect(resolveServerConfig({ ...base, PORT: "8930" }).port).toBe(8930);
expect(resolveServerConfig({ ...base, PORT: "0" }).port).toBe(0);
});
- it("non-integer or out-of-range values throw", () => {
+ it("throws on a non-integer or out-of-range value", () => {
for (const bad of ["abc", "3.14", "-1", "65536"]) {
expect(() => resolveServerConfig({ ...base, PORT: bad }), bad).toThrow(/Invalid port/);
}
});
});
-describe("resolveServerConfig: desktop-mode seed password", () => {
- it("desktop mode leaves the seed unpinned, exactly like every other mode", () => {
- // Nothing pins it: the password the seed generates on its own is already unguessable, so
- // supplying one here would just be a second way to say the same thing.
- expect(
- resolveServerConfig({ ...base, PENGUIN_DESKTOP_TOKEN: "tok" }).seedAdminPassword,
- ).toBeNull();
- });
-
- it("an explicit PENGUIN_SEED_ADMIN_PASSWORD still wins in desktop mode", () => {
- expect(
- resolveServerConfig({
- ...base,
- PENGUIN_DESKTOP_TOKEN: "tok",
- PENGUIN_SEED_ADMIN_PASSWORD: "penguin-2026",
- }).seedAdminPassword,
- ).toBe("penguin-2026");
- });
-
- it("outside desktop mode the unpinned value stays null (the seed generates one)", () => {
- expect(resolveServerConfig({ ...base }).seedAdminPassword).toBeNull();
- });
-});
-
-describe("resolveServerConfig: PENGUIN_SEED_ADMIN_PASSWORD parsing", () => {
- it("unset/empty/whitespace → null; a value is kept trimmed", () => {
+describe("resolveServerConfig: seed password", () => {
+ it("leaves the seed unpinned when unset, empty or blank, and keeps a value trimmed", () => {
expect(resolveServerConfig({ ...base }).seedAdminPassword).toBeNull();
- expect(
- resolveServerConfig({ ...base, PENGUIN_SEED_ADMIN_PASSWORD: "" }).seedAdminPassword,
- ).toBeNull();
- expect(
- resolveServerConfig({ ...base, PENGUIN_SEED_ADMIN_PASSWORD: " " }).seedAdminPassword,
- ).toBeNull();
+ for (const blank of ["", " "]) {
+ expect(
+ resolveServerConfig({ ...base, PENGUIN_SEED_ADMIN_PASSWORD: blank }).seedAdminPassword,
+ ).toBeNull();
+ }
expect(
resolveServerConfig({ ...base, PENGUIN_SEED_ADMIN_PASSWORD: " penguin-9999 " })
.seedAdminPassword,
).toBe("penguin-9999");
});
+
+ it("desktop mode leaves the seed unpinned, and an explicit value still wins there", () => {
+ // Nothing pins it: the password the seed generates on its own is already unguessable, so
+ // supplying one here would just be a second way to say the same thing.
+ const desktop = { ...base, PENGUIN_DESKTOP_TOKEN: "tok" };
+ expect(resolveServerConfig(desktop).seedAdminPassword).toBeNull();
+ expect(
+ resolveServerConfig({ ...desktop, PENGUIN_SEED_ADMIN_PASSWORD: "penguin-2026" })
+ .seedAdminPassword,
+ ).toBe("penguin-2026");
+ });
});
describe("resolveServerConfig: PENGUIN_CLI_ENTRY parsing", () => {
- it("a value is kept trimmed — it is what the <root>/bin/penguin shim execs", () => {
+ it("keeps a value trimmed — it is what the <root>/bin/penguin shim execs", () => {
expect(
resolveServerConfig({ ...base, PENGUIN_CLI_ENTRY: " /opt/penguin/dist/penguin.js " })
.cliEntry,
).toBe("/opt/penguin/dist/penguin.js");
});
- it("empty/whitespace falls through to the checkout lookup, like unset", () => {
+ it("falls through to the checkout lookup on a blank value, like unset", () => {
// What the lookup finds depends on whether this checkout has built its CLI, so the
// claim here is only that a blank value is not treated as an entry (see cli-shim.test.ts
// for checkoutCliEntry itself).
@@ -91,15 +83,14 @@ describe("resolveServerConfig: PENGUIN_CLI_ENTRY parsing", () => {
});
describe("resolveServerConfig: PENGUIN_GO_ORIGIN parsing", () => {
- it("defaults to the production HTTPS origin and accepts loopback HTTP for integration", () => {
- expect(resolveServerConfig({ ...base }).penguinGoOrigin).toBe("https://token.penguin.ooo");
+ it("accepts a loopback HTTP origin for integration work, trimmed", () => {
expect(
resolveServerConfig({ ...base, PENGUIN_GO_ORIGIN: " http://127.0.0.1:3000 " })
.penguinGoOrigin,
).toBe("http://127.0.0.1:3000");
});
- it("rejects non-origin input and non-loopback plaintext HTTP", () => {
+ it("refuses anything but a bare origin, and plaintext HTTP to another host", () => {
for (const bad of [
"http://token.penguin.ooo",
"https://token.penguin.ooo/path",
@@ -114,20 +105,16 @@ describe("resolveServerConfig: PENGUIN_GO_ORIGIN parsing", () => {
});
describe("resolveServerConfig: MODELSCOPE_BRIDGE_URL parsing", () => {
- it("defaults to the production bridge URL", () => {
- expect(resolveServerConfig({ ...base }).modelscopeBridgeUrl).toBe(
- "https://go.penguin.ooo/modelscope",
- );
- });
-
- it("allows a path prefix but rejects plaintext HTTP, credentials, query and fragment", () => {
+ it("allows a path prefix, trimmed of its surrounding space and trailing slash", () => {
expect(
resolveServerConfig({
...base,
MODELSCOPE_BRIDGE_URL: " https://go.penguin.ooo/modelscope/ ",
}).modelscopeBridgeUrl,
).toBe("https://go.penguin.ooo/modelscope");
+ });
+ it("refuses plaintext HTTP, credentials, a query and a fragment", () => {
for (const bad of [
"http://go.penguin.ooo/modelscope",
"https://user:[email protected]/modelscope",
diff --git a/packages/server/test/desktop-tray.test.ts b/packages/server/test/desktop-tray.test.ts
index d6483063..10527ec3 100644
--- a/packages/server/test/desktop-tray.test.ts
+++ b/packages/server/test/desktop-tray.test.ts
@@ -1,11 +1,16 @@
/**
- * The tray-icon preference relay: the /api/desktop/tray routes (shell-window sessions
- * only), the DesktopService store/forward pair behind them, and the message-port glue.
+ * The tray-icon preference relay: the /api/desktop/tray routes (the shell window's sessions
+ * only), and the shell port they ride.
*
- * The session gate is pinned in both directions like the client update's next door: the
- * shell's own window may read and write, a password-via session against the same
- * desktop-mode server gets 403 — its holder may be on another machine and must not reach
- * into the chrome of a window it is not looking at.
+ * - The tray state reads as null before the shell's first push, then as what it pushed.
+ * - A PUT forwards the switch to the shell and answers 202; a field it cannot read, or a
+ * request that asks for nothing, is refused and reaches no shell.
+ * - A password session against the same desktop server gets 403 (its holder may be on another
+ * machine, and must not reach into the chrome of a window it is not looking at); with no
+ * shell wired the PUT answers 503; a plain server has no such route.
+ * - Only a well-formed tray frame is read, defaulting a missing or unknown language to English;
+ * the updater's frames on the same port are not tray frames.
+ * - Tray pushes and tray commands share one port with the updater's, neither disturbing the other.
*/
import { describe, expect, it } from "vitest";
import { createDesktopApp, createTestApp, desktopLoginCookie, loginAdmin } from "./helpers.js";
@@ -15,7 +20,7 @@ import {
parseTrayStatusMessage,
wireShellUpdatePort,
} from "../src/services/desktop-update-port.js";
-import type { ShellPort } from "../src/services/desktop-update-port.js";
+import { FakePort } from "./builtin-browser/fake-shell.js";
const put = (cookie: string, body: string) => ({
method: "PUT",
@@ -170,32 +175,17 @@ describe("the tray half of the shell port", () => {
it("stores tray pushes and posts tray commands beside the updater's, on one port", () => {
const desktop = new DesktopService("t");
- const posted: unknown[] = [];
- let onMessage: ((e: { data: unknown }) => void) | undefined;
- const port: ShellPort = {
- on: (_event, listener) => {
- onMessage = listener;
- },
- postMessage: (message) => posted.push(message),
- };
+ const port = new FakePort();
wireShellUpdatePort(desktop, port);
- onMessage!({
- data: { type: "desktop-tray-status", status: { showTrayIcon: false, locale: "zh" } },
- });
+ port.emit({ type: "desktop-tray-status", status: { showTrayIcon: false, locale: "zh" } });
expect(desktop.getTrayStatus()).toEqual({ showTrayIcon: false, locale: "zh" });
// An updater frame on the same port leaves the tray state alone, and vice versa.
- onMessage!({
- data: { type: "desktop-updater-status", status: { appVersion: "1", state: "idle" } },
- });
+ port.emit({ type: "desktop-updater-status", status: { appVersion: "1", state: "idle" } });
expect(desktop.getTrayStatus()).toEqual({ showTrayIcon: false, locale: "zh" });
expect(desktop.getUpdateStatus()).toEqual({ appVersion: "1", state: "idle" });
expect(desktop.requestTrayCommand({ showTrayIcon: true })).toBe(true);
- expect(posted).toEqual([{ type: "desktop-tray-command", showTrayIcon: true }]);
- });
-
- it("reports no sender before a port is wired", () => {
- expect(new DesktopService("t").requestTrayCommand({ showTrayIcon: false })).toBe(false);
+ expect(port.sent).toEqual([{ type: "desktop-tray-command", showTrayIcon: true }]);
});
});
diff --git a/packages/server/test/desktop-update.test.ts b/packages/server/test/desktop-update.test.ts
index 1d23b48d..cd0aede5 100644
--- a/packages/server/test/desktop-update.test.ts
+++ b/packages/server/test/desktop-update.test.ts
@@ -1,11 +1,15 @@
/**
- * Client-update relay: the /api/desktop/update routes (shell-window sessions only), the
- * DesktopService store/forward pair behind them, and the message-port glue.
+ * The client-update relay: the /api/desktop/update routes (the shell window's sessions only),
+ * and the shell port they ride.
*
- * The session gate is pinned in both directions like the change-password one it
- * mirrors: a desktop-via session may read and command, a password-via session against
- * the same desktop-mode server gets 403 — its holder may be on another machine and
- * must not restart this one's GUI app.
+ * - The update status reads as null before the shell's first push, then as the pushed snapshot.
+ * - check / download / install are forwarded to the shell and answered 202.
+ * - A password session against the same desktop server gets 403, an anonymous caller 401, and
+ * nothing reaches the shell (install replaces the running app, so its gate is pinned every
+ * way); a plain server has no such routes; with no shell wired a command answers 503.
+ * - Only a well-formed updater frame is read.
+ * - A wired port stores pushed frames, ignores garbage, and carries commands out.
+ * - A plain Node process has no shell port to wire.
*/
import { describe, expect, it } from "vitest";
import { createDesktopApp, createTestApp, desktopLoginCookie, loginAdmin } from "./helpers.js";
@@ -20,7 +24,7 @@ import {
shellPortOf,
wireShellUpdatePort,
} from "../src/services/desktop-update-port.js";
-import type { ShellPort } from "../src/services/desktop-update-port.js";
+import { FakePort } from "./builtin-browser/fake-shell.js";
const STATUS: DesktopUpdateStatus = {
appVersion: "0.2.3",
@@ -82,24 +86,14 @@ describe("POST /api/desktop/update/{check,download,install}", () => {
const actions: string[] = [];
t.deps.desktop!.onUpdateCommand((action) => actions.push(action));
- const check = await t.app.request("/api/desktop/update/check", {
- method: "POST",
- headers: { cookie, "content-type": "application/json" },
- body: "{}",
- });
- expect(check.status).toBe(202);
- const download = await t.app.request("/api/desktop/update/download", {
- method: "POST",
- headers: { cookie, "content-type": "application/json" },
- body: "{}",
- });
- expect(download.status).toBe(202);
- const install = await t.app.request("/api/desktop/update/install", {
- method: "POST",
- headers: { cookie, "content-type": "application/json" },
- body: "{}",
- });
- expect(install.status).toBe(202);
+ for (const action of ["check", "download", "install"]) {
+ const res = await t.app.request(`/api/desktop/update/${action}`, {
+ method: "POST",
+ headers: { cookie, "content-type": "application/json" },
+ body: "{}",
+ });
+ expect(res.status, action).toBe(202);
+ }
expect(actions).toEqual(["check", "download", "install"]);
} finally {
await t.cleanup();
@@ -195,23 +189,16 @@ describe("desktop-update-port", () => {
it("stores pushed frames and posts commands through a wired port", () => {
const desktop = new DesktopService("t");
- const posted: unknown[] = [];
- let onMessage: ((e: { data: unknown }) => void) | undefined;
- const port: ShellPort = {
- on: (_event, listener) => {
- onMessage = listener;
- },
- postMessage: (message) => posted.push(message),
- };
+ const port = new FakePort();
wireShellUpdatePort(desktop, port);
- onMessage!({ data: { type: "desktop-updater-status", status: STATUS } });
+ port.emit({ type: "desktop-updater-status", status: STATUS });
expect(desktop.getUpdateStatus()).toEqual(STATUS);
- onMessage!({ data: { garbage: true } });
+ port.emit({ garbage: true });
expect(desktop.getUpdateStatus()).toEqual(STATUS);
expect(desktop.requestUpdateCommand("check")).toBe(true);
- expect(posted).toEqual([{ type: "desktop-updater-command", action: "check" }]);
+ expect(port.sent).toEqual([{ type: "desktop-updater-command", action: "check" }]);
});
it("finds no shell port on a plain Node process without parentPort", () => {
diff --git a/packages/server/test/desktop.test.ts b/packages/server/test/desktop.test.ts
index 101e8547..5a19f23f 100644
--- a/packages/server/test/desktop.test.ts
+++ b/packages/server/test/desktop.test.ts
@@ -1,7 +1,16 @@
/**
- * Desktop mode: the one-shot desktop claim, Bearer-token shutdown, desktopMode in /api/me,
- * the desktop-session password change without oldPassword, and the single-user guard
- * closing the user-management and Project-member surfaces.
+ * Desktop mode: a server the desktop shell spawned with a one-shot token.
+ *
+ * - The shell's token redeems once for a cookie session in desktop mode; a replay, a wrong or a
+ * missing token goes back to the login page without spending the real one.
+ * - Outside desktop mode the claim route refuses a shell token, and /api/me says so.
+ * - The shutdown endpoint takes the token as a Bearer, repeatedly, and runs the registered
+ * handler after answering; a wrong or missing token is 401, and a plain server has no such
+ * route.
+ * - The single-user guard closes the user-management surface and the Project-member surface,
+ * even to a fully authorized admin session, and creates nobody.
+ * - The shell's own session may set the password without the old one, but an old one it does
+ * give is still checked; a password session in desktop mode keeps needing it.
*/
import { describe, expect, it } from "vitest";
import {
@@ -80,16 +89,19 @@ describe("desktop shutdown endpoint", () => {
const t = await createDesktopApp();
try {
let requested = 0;
+ let shutdownRequested!: () => void;
+ const handled = new Promise<void>((resolve) => (shutdownRequested = resolve));
t.deps.desktop!.onShutdownRequest(() => {
requested += 1;
+ shutdownRequested();
});
const res = await t.app.request("/api/desktop/shutdown", {
method: "POST",
headers: { authorization: `Bearer ${TEST_DESKTOP_TOKEN}` },
});
expect(res.status).toBe(202);
- // The route defers the trigger so the 202 can flush first.
- await new Promise((r) => setTimeout(r, 80));
+ // The route defers the trigger so the 202 can flush first: the handler runs after it.
+ await handled;
expect(requested).toBe(1);
// Unlike the login token, the shutdown credential is NOT one-shot.
@@ -139,11 +151,11 @@ describe("desktop single-user mode", () => {
expect(body.error.code).toBe("desktop_single_user");
}
- it("rejects the whole admin-users surface with desktop_single_user", async () => {
+ it("closes user management and Project members to even a full admin session", async () => {
const t = await createDesktopApp();
try {
- // The seeded admin signed in through the regular login form: even a fully
- // authorized admin session gets the dedicated 403, not admin_required.
+ // The seeded admin signed in through the regular login form: even a fully authorized
+ // admin session gets the dedicated 403, not admin_required.
const admin = await loginAdmin(t.app);
const api = apiClient(t.app, admin.cookie);
await expectSingleUser403(await api.get("/api/admin/users"));
@@ -153,48 +165,14 @@ describe("desktop single-user mode", () => {
await expectSingleUser403(
await api.post("/api/admin/users/admin/password", { password: "password-456" }),
);
- await expectSingleUser403(
- await t.app.request("/api/admin/users/eve", {
- method: "DELETE",
- headers: { cookie: admin.cookie },
- }),
- );
- // No user was created by the rejected POST.
- expect(t.deps.db.prepare("SELECT COUNT(*) AS n FROM users").get()?.n).toBe(1);
- } finally {
- await t.cleanup();
- }
- });
-
- it("rejects Project member management (reads and writes) with desktop_single_user", async () => {
- const t = await createDesktopApp();
- try {
- const admin = await loginAdmin(t.app);
- const api = apiClient(t.app, admin.cookie);
+ await expectSingleUser403(await api.delete("/api/admin/users/eve"));
await expectSingleUser403(await api.get("/api/projects/default_project/members"));
await expectSingleUser403(
await api.post("/api/projects/default_project/members", { userId: "eve" }),
);
- await expectSingleUser403(
- await t.app.request("/api/projects/default_project/members/eve", {
- method: "DELETE",
- headers: { cookie: admin.cookie },
- }),
- );
- } finally {
- await t.cleanup();
- }
- });
-
- it("leaves both surfaces working on a normal multi-user server", async () => {
- const t = await createTestApp();
- try {
- const admin = await loginAdmin(t.app);
- const api = apiClient(t.app, admin.cookie);
- const users = await api.get("/api/admin/users");
- expect(users.status).toBe(200);
- const members = await api.get("/api/projects/default_project/members");
- expect(members.status).toBe(200);
+ await expectSingleUser403(await api.delete("/api/projects/default_project/members/eve"));
+ // No user was created by the rejected POST.
+ expect(t.deps.db.prepare("SELECT COUNT(*) AS n FROM users").get()?.n).toBe(1);
} finally {
await t.cleanup();
}
diff --git a/packages/server/test/dirs-access.test.ts b/packages/server/test/dirs-access.test.ts
index 23e9193b..4b03de56 100644
--- a/packages/server/test/dirs-access.test.ts
+++ b/packages/server/test/dirs-access.test.ts
@@ -1,16 +1,26 @@
/**
* The Workspace picker's macOS folder access, server side. POST /api/projects/:p/dirs/access
* relays a refused folder to the desktop shell, whose main process reads it in the app's own
- * name, and answers what that read came to — 503 `shell_unreachable` when this server has no
- * shell to ask. POST /api/desktop/privacy-settings has the shell open a Privacy & Security
- * pane, under the same gate as the other page-facing desktop routes. The port glue pairs each
- * shell reply with the request it answers, and a reply that comes after its request gave up
- * is dropped.
+ * name, and answers what that read came to. POST /api/desktop/privacy-settings has the shell
+ * open a Privacy & Security pane, under the same gate as the other page-facing desktop routes.
*
- * The route tests drive the real port glue against a fake shell on the far side of the port,
+ * - The shell reads the folder and the route answers what the read came to (granted or not,
+ * packaged or not), each request carrying its own id; the errno stays in the shell's log.
+ * - A path that is not absolute is refused before the shell is asked.
+ * - Anything but the desktop app's own window is refused: a plain server's session, and a
+ * password session on the desktop app's own server.
+ * - With no shell to ask the route answers 503; with a shell that does not answer in time, 504.
+ * - The Project stays the authorization anchor: a Project the caller cannot reach is a 404.
+ * - The privacy pane is relayed to the shell and answered 202; an unknown pane is refused;
+ * only the shell's own window may ask; with no shell wired it is 503, and a plain server has
+ * no such route.
+ * - The port pairs each reply with the request it answers, reads only well-formed replies, and
+ * drops a reply that arrives after its request gave up.
+ *
+ * The route cases drive the real port glue against a fake shell on the far side of the port,
* so the frames themselves are exercised, not just the service's seam.
*/
-import { describe, expect, it, vi } from "vitest";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import type {
DesktopFolderAccessResult,
DesktopPrivacyPane,
@@ -23,7 +33,7 @@ import {
parseFolderAccessResultMessage,
wireShellUpdatePort,
} from "../src/services/desktop-update-port.js";
-import type { ShellPort } from "../src/services/desktop-update-port.js";
+import { FakePort } from "./builtin-browser/fake-shell.js";
import {
apiClient,
createDesktopApp,
@@ -31,6 +41,7 @@ import {
desktopLoginCookie,
loginAdmin,
} from "./helpers.js";
+import type { TestApp } from "./helpers.js";
const DOWNLOADS = "/Users/me/Downloads";
const ACCESS = "/api/projects/default_project/dirs/access";
@@ -38,307 +49,250 @@ const SETTINGS = "/api/desktop/privacy-settings";
/**
* A shell on the far side of the port: every folder-access request is answered, a tick later,
- * the way `answer` says; every frame the server posts is kept.
+ * the way `answer` says; every frame the server posts is kept in `port.sent`.
*/
-function fakeShell(answer: (path: string) => DesktopFolderAccessResult) {
- const posted: Record<string, unknown>[] = [];
- let listener: ((e: { data: unknown }) => void) | undefined;
- const port: ShellPort = {
- on: (_event, l) => {
- listener = l;
- },
- postMessage: (message) => {
- const frame = message as Record<string, unknown>;
- posted.push(frame);
- if (frame.type !== "desktop-folder-access") return;
- setTimeout(() =>
- listener?.({
- data: {
- type: "desktop-folder-access-result",
- id: frame.id,
- ...answer(frame.path as string),
- },
- }),
- );
- },
+function fakeShell(answer: (path: string) => DesktopFolderAccessResult): FakePort {
+ const port = new FakePort();
+ port.onPost = (message) => {
+ const frame = message as Record<string, unknown>;
+ if (frame.type !== "desktop-folder-access") return;
+ setTimeout(() =>
+ port.emit({
+ type: "desktop-folder-access-result",
+ id: frame.id,
+ ...answer(String(frame.path)),
+ }),
+ );
};
- return { port, posted };
+ return port;
}
const errorCode = async (res: Response): Promise<string> =>
((await res.json()) as ErrorBody).error.code;
+/** A desktop-mode app with the shell window's own session, shared by a describe. */
+function desktopApp() {
+ const state = {} as { t: TestApp; api: ReturnType<typeof apiClient>; cookie: string };
+ beforeAll(async () => {
+ state.t = await createDesktopApp();
+ state.cookie = await desktopLoginCookie(state.t.app);
+ state.api = apiClient(state.t.app, state.cookie);
+ });
+ afterAll(async () => {
+ await state.t.cleanup();
+ });
+ return state;
+}
+
+/** A fresh desktop app with no shell wired, for the cases about its absence. */
+async function withUnwiredDesktop(run: (api: ReturnType<typeof apiClient>) => Promise<void>) {
+ const t = await createDesktopApp();
+ try {
+ await run(apiClient(t.app, await desktopLoginCookie(t.app)));
+ } finally {
+ await t.cleanup();
+ }
+}
+
+/** A plain (non-desktop) server's admin session. */
+async function withPlainServer(run: (api: ReturnType<typeof apiClient>) => Promise<void>) {
+ const plain = await createTestApp();
+ try {
+ await run(apiClient(plain.app, (await loginAdmin(plain.app)).cookie));
+ } finally {
+ await plain.cleanup();
+ }
+}
+
describe("POST /api/projects/:projectId/dirs/access", () => {
+ const app = desktopApp();
+
it("has the shell read the folder and answers what the read came to", async () => {
- const t = await createDesktopApp();
- try {
- const api = apiClient(t.app, await desktopLoginCookie(t.app));
- let granted = false;
- const shell = fakeShell(() => ({
- granted,
- ...(granted ? {} : { code: "EPERM" }),
- packaged: true,
- }));
- wireShellUpdatePort(t.deps.desktop!, shell.port);
+ let granted = false;
+ const shell = fakeShell(() => ({
+ granted,
+ ...(granted ? {} : { code: "EPERM" }),
+ packaged: true,
+ }));
+ wireShellUpdatePort(app.t.deps.desktop!, shell);
- const refused = await api.post(ACCESS, { path: DOWNLOADS });
- expect(refused.status).toBe(200);
- // The errno stays in the shell's log: the page acts on the two booleans alone.
- expect((await refused.json()) as DirAccessResponse).toEqual({
- granted: false,
- packaged: true,
- });
- expect(shell.posted).toEqual([
- { type: "desktop-folder-access", id: expect.any(String), path: DOWNLOADS },
- ]);
+ const refused = await app.api.post(ACCESS, { path: DOWNLOADS });
+ expect(refused.status).toBe(200);
+ // The errno stays in the shell's log: the page acts on the two booleans alone.
+ expect((await refused.json()) as DirAccessResponse).toEqual({ granted: false, packaged: true });
+ expect(shell.sent).toEqual([
+ { type: "desktop-folder-access", id: expect.any(String), path: DOWNLOADS },
+ ]);
- granted = true;
- const allowed = await api.post(ACCESS, { path: DOWNLOADS });
- expect((await allowed.json()) as DirAccessResponse).toEqual({
- granted: true,
- packaged: true,
- });
- // Every request carries its own id, so a reply can only settle the one it answers.
- expect(shell.posted[1]!.id).not.toBe(shell.posted[0]!.id);
- } finally {
- await t.cleanup();
- }
+ granted = true;
+ const allowed = await app.api.post(ACCESS, { path: DOWNLOADS });
+ expect((await allowed.json()) as DirAccessResponse).toEqual({ granted: true, packaged: true });
+ // Every request carries its own id, so a reply can only settle the one it answers.
+ const ids = (shell.sent as Array<{ id: string }>).map((frame) => frame.id);
+ expect(ids[1]).not.toBe(ids[0]);
});
it("reports an unpackaged app, whose reads macOS charges to the terminal", async () => {
- const t = await createDesktopApp();
- try {
- const api = apiClient(t.app, await desktopLoginCookie(t.app));
- wireShellUpdatePort(
- t.deps.desktop!,
- fakeShell(() => ({ granted: false, code: "EPERM", packaged: false })).port,
- );
- const res = await api.post(ACCESS, { path: DOWNLOADS });
- expect((await res.json()) as DirAccessResponse).toEqual({ granted: false, packaged: false });
- } finally {
- await t.cleanup();
- }
+ wireShellUpdatePort(
+ app.t.deps.desktop!,
+ fakeShell(() => ({ granted: false, code: "EPERM", packaged: false })),
+ );
+ const res = await app.api.post(ACCESS, { path: DOWNLOADS });
+ expect((await res.json()) as DirAccessResponse).toEqual({ granted: false, packaged: false });
});
it("refuses a path that is not absolute before asking the shell", async () => {
- const t = await createDesktopApp();
- try {
- const cookie = await desktopLoginCookie(t.app);
- const asked: string[] = [];
- t.deps.desktop!.onFolderAccessRequest(async (path) => {
- asked.push(path);
- return { granted: true, packaged: true };
+ const asked: string[] = [];
+ app.t.deps.desktop!.onFolderAccessRequest(async (path) => {
+ asked.push(path);
+ return { granted: true, packaged: true };
+ });
+ for (const body of ['{"path":"Downloads"}', '{"path":""}', '{"path":7}', "{}", "not json"]) {
+ const res = await app.t.app.request(ACCESS, {
+ method: "POST",
+ headers: { cookie: app.cookie, "content-type": "application/json" },
+ body,
});
- for (const body of ['{"path":"Downloads"}', '{"path":""}', '{"path":7}', "{}", "not json"]) {
- const res = await t.app.request(ACCESS, {
- method: "POST",
- headers: { cookie, "content-type": "application/json" },
- body,
- });
- expect(res.status, body).toBe(400);
- expect(await errorCode(res), body).toBe("dir_not_absolute");
- }
- expect(asked).toEqual([]);
- } finally {
- await t.cleanup();
+ expect(res.status, body).toBe(400);
+ expect(await errorCode(res), body).toBe("dir_not_absolute");
}
+ expect(asked).toEqual([]);
});
it("is refused to anything but the desktop app's own window", async () => {
// A plain server's password session: no window of the shell's at all.
- const plain = await createTestApp();
- try {
- const admin = await loginAdmin(plain.app);
- const res = await apiClient(plain.app, admin.cookie).post(ACCESS, { path: DOWNLOADS });
+ await withPlainServer(async (api) => {
+ const res = await api.post(ACCESS, { path: DOWNLOADS });
expect(res.status).toBe(403);
expect(await errorCode(res)).toBe("desktop_shell_only");
- } finally {
- await plain.cleanup();
- }
+ });
// A browser tab signed in with the password on the desktop app's own server.
- const t = await createDesktopApp();
- try {
- let asked = 0;
- t.deps.desktop!.onFolderAccessRequest(async () => {
- asked += 1;
- return { granted: true, packaged: true };
- });
- const admin = await loginAdmin(t.app);
- const res = await apiClient(t.app, admin.cookie).post(ACCESS, { path: DOWNLOADS });
- expect(res.status).toBe(403);
- expect(await errorCode(res)).toBe("desktop_shell_only");
- expect(asked).toBe(0);
- } finally {
- await t.cleanup();
- }
+ let asked = 0;
+ app.t.deps.desktop!.onFolderAccessRequest(async () => {
+ asked += 1;
+ return { granted: true, packaged: true };
+ });
+ const admin = apiClient(app.t.app, (await loginAdmin(app.t.app)).cookie);
+ const res = await admin.post(ACCESS, { path: DOWNLOADS });
+ expect(res.status).toBe(403);
+ expect(await errorCode(res)).toBe("desktop_shell_only");
+ expect(asked).toBe(0);
});
it("answers 503 shell_unreachable with no shell to ask", async () => {
- // Desktop mode, but no port wired.
- const t = await createDesktopApp();
- try {
- const api = apiClient(t.app, await desktopLoginCookie(t.app));
+ await withUnwiredDesktop(async (api) => {
const res = await api.post(ACCESS, { path: DOWNLOADS });
expect(res.status).toBe(503);
expect(await errorCode(res)).toBe("shell_unreachable");
- } finally {
- await t.cleanup();
- }
+ });
});
it("answers 504 timeout when the shell does not answer in time", async () => {
- const t = await createDesktopApp();
- try {
- const api = apiClient(t.app, await desktopLoginCookie(t.app));
- t.deps.desktop!.onFolderAccessRequest(async () => null);
- const res = await api.post(ACCESS, { path: DOWNLOADS });
- expect(res.status).toBe(504);
- expect(await errorCode(res)).toBe("timeout");
- } finally {
- await t.cleanup();
- }
+ app.t.deps.desktop!.onFolderAccessRequest(async () => null);
+ const res = await app.api.post(ACCESS, { path: DOWNLOADS });
+ expect(res.status).toBe(504);
+ expect(await errorCode(res)).toBe("timeout");
});
it("keeps the Project as the authorization anchor", async () => {
- const t = await createDesktopApp();
- try {
- const api = apiClient(t.app, await desktopLoginCookie(t.app));
- const asked: string[] = [];
- t.deps.desktop!.onFolderAccessRequest(async (path) => {
- asked.push(path);
- return { granted: true, packaged: true };
- });
- const res = await api.post("/api/projects/nobody_s_project/dirs/access", {
- path: DOWNLOADS,
- });
- expect(res.status).toBe(404);
- expect(await errorCode(res)).toBe("project_not_found");
- expect(asked).toEqual([]);
- } finally {
- await t.cleanup();
- }
+ const asked: string[] = [];
+ app.t.deps.desktop!.onFolderAccessRequest(async (path) => {
+ asked.push(path);
+ return { granted: true, packaged: true };
+ });
+ const res = await app.api.post("/api/projects/nobody_s_project/dirs/access", {
+ path: DOWNLOADS,
+ });
+ expect(res.status).toBe(404);
+ expect(await errorCode(res)).toBe("project_not_found");
+ expect(asked).toEqual([]);
});
});
describe("POST /api/desktop/privacy-settings", () => {
+ const app = desktopApp();
+
it("relays the pane to the shell and answers 202", async () => {
- const t = await createDesktopApp();
- try {
- const api = apiClient(t.app, await desktopLoginCookie(t.app));
- const shell = fakeShell(() => ({ granted: true, packaged: true }));
- wireShellUpdatePort(t.deps.desktop!, shell.port);
- for (const pane of ["files", "fullDisk"] satisfies DesktopPrivacyPane[]) {
- const res = await api.post(SETTINGS, { pane });
- expect(res.status, pane).toBe(202);
- }
- expect(shell.posted).toEqual([
- { type: "desktop-open-privacy-settings", pane: "files" },
- { type: "desktop-open-privacy-settings", pane: "fullDisk" },
- ]);
- } finally {
- await t.cleanup();
+ const shell = fakeShell(() => ({ granted: true, packaged: true }));
+ wireShellUpdatePort(app.t.deps.desktop!, shell);
+ for (const pane of ["files", "fullDisk"] satisfies DesktopPrivacyPane[]) {
+ const res = await app.api.post(SETTINGS, { pane });
+ expect(res.status, pane).toBe(202);
}
+ expect(shell.sent).toEqual([
+ { type: "desktop-open-privacy-settings", pane: "files" },
+ { type: "desktop-open-privacy-settings", pane: "fullDisk" },
+ ]);
});
it("refuses a pane it does not know", async () => {
- const t = await createDesktopApp();
- try {
- const cookie = await desktopLoginCookie(t.app);
- const sent: DesktopPrivacyPane[] = [];
- t.deps.desktop!.onPrivacySettingsCommand((pane) => sent.push(pane));
- for (const body of ['{"pane":"camera"}', '{"pane":true}', "{}", "not json"]) {
- const res = await t.app.request(SETTINGS, {
- method: "POST",
- headers: { cookie, "content-type": "application/json" },
- body,
- });
- expect(res.status, body).toBe(400);
- expect(await errorCode(res), body).toBe("invalid_privacy_pane");
- }
- expect(sent).toEqual([]);
- } finally {
- await t.cleanup();
+ const sent: DesktopPrivacyPane[] = [];
+ app.t.deps.desktop!.onPrivacySettingsCommand((pane) => sent.push(pane));
+ for (const body of ['{"pane":"camera"}', '{"pane":true}', "{}", "not json"]) {
+ const res = await app.t.app.request(SETTINGS, {
+ method: "POST",
+ headers: { cookie: app.cookie, "content-type": "application/json" },
+ body,
+ });
+ expect(res.status, body).toBe(400);
+ expect(await errorCode(res), body).toBe("invalid_privacy_pane");
}
+ expect(sent).toEqual([]);
});
it("answers only the shell's own window, like the other desktop routes", async () => {
- const t = await createDesktopApp();
- try {
- const sent: DesktopPrivacyPane[] = [];
- t.deps.desktop!.onPrivacySettingsCommand((pane) => sent.push(pane));
- // A password session against the same server may be on another machine: System
- // Settings springing open on this one means nothing there.
- const admin = await loginAdmin(t.app);
- const forbidden = await apiClient(t.app, admin.cookie).post(SETTINGS, { pane: "files" });
- expect(forbidden.status).toBe(403);
- expect(await errorCode(forbidden)).toBe("desktop_shell_only");
- const anonymous = await t.app.request(SETTINGS, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: '{"pane":"files"}',
- });
- expect(anonymous.status).toBe(401);
- expect(sent).toEqual([]);
- } finally {
- await t.cleanup();
- }
+ const sent: DesktopPrivacyPane[] = [];
+ app.t.deps.desktop!.onPrivacySettingsCommand((pane) => sent.push(pane));
+ // A password session against the same server may be on another machine: System Settings
+ // springing open on this one means nothing there.
+ const admin = apiClient(app.t.app, (await loginAdmin(app.t.app)).cookie);
+ const forbidden = await admin.post(SETTINGS, { pane: "files" });
+ expect(forbidden.status).toBe(403);
+ expect(await errorCode(forbidden)).toBe("desktop_shell_only");
+ const anonymous = await app.t.app.request(SETTINGS, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: '{"pane":"files"}',
+ });
+ expect(anonymous.status).toBe(401);
+ expect(sent).toEqual([]);
});
- it("answers 503 shell_unreachable while no port is wired, and does not exist outside desktop mode", async () => {
- const t = await createDesktopApp();
- try {
- const api = apiClient(t.app, await desktopLoginCookie(t.app));
+ it("answers 503 while no port is wired, and does not exist outside desktop mode", async () => {
+ await withUnwiredDesktop(async (api) => {
const res = await api.post(SETTINGS, { pane: "files" });
expect(res.status).toBe(503);
expect(await errorCode(res)).toBe("shell_unreachable");
- } finally {
- await t.cleanup();
- }
- const plain = await createTestApp();
- try {
- const admin = await loginAdmin(plain.app);
- const res = await apiClient(plain.app, admin.cookie).post(SETTINGS, { pane: "files" });
- expect(res.status).toBe(404);
- } finally {
- await plain.cleanup();
- }
+ });
+ await withPlainServer(async (api) => {
+ expect((await api.post(SETTINGS, { pane: "files" })).status).toBe(404);
+ });
});
});
describe("the folder-access half of the shell port", () => {
+ const reply = (fields: Record<string, unknown>) => ({
+ type: "desktop-folder-access-result",
+ ...fields,
+ });
+
it("parses only well-formed replies", () => {
expect(
- parseFolderAccessResultMessage({
- type: "desktop-folder-access-result",
- id: "a",
- granted: false,
- code: "EPERM",
- packaged: true,
- }),
- ).toEqual({
- type: "desktop-folder-access-result",
- id: "a",
- granted: false,
- code: "EPERM",
- packaged: true,
- });
+ parseFolderAccessResultMessage(
+ reply({ id: "a", granted: false, code: "EPERM", packaged: true }),
+ ),
+ ).toEqual(reply({ id: "a", granted: false, code: "EPERM", packaged: true }));
// A code that is not a string is left out rather than failing the whole reply.
expect(
- parseFolderAccessResultMessage({
- type: "desktop-folder-access-result",
- id: "a",
- granted: true,
- code: 1,
- packaged: false,
- }),
- ).toEqual({ type: "desktop-folder-access-result", id: "a", granted: true, packaged: false });
+ parseFolderAccessResultMessage(reply({ id: "a", granted: true, code: 1, packaged: false })),
+ ).toEqual(reply({ id: "a", granted: true, packaged: false }));
for (const data of [
null,
{},
- { type: "desktop-folder-access-result", granted: true, packaged: true },
- { type: "desktop-folder-access-result", id: "a", packaged: true },
- { type: "desktop-folder-access-result", id: "a", granted: "yes", packaged: true },
- { type: "desktop-folder-access-result", id: "a", granted: true },
+ reply({ granted: true, packaged: true }),
+ reply({ id: "a", packaged: true }),
+ reply({ id: "a", granted: "yes", packaged: true }),
+ reply({ id: "a", granted: true }),
// The request's own shape, and the other frames on the same port, are not replies.
{ type: "desktop-folder-access", id: "a", path: DOWNLOADS },
{ type: "desktop-tray-status", status: { showTrayIcon: true, locale: "en" } },
@@ -349,40 +303,19 @@ describe("the folder-access half of the shell port", () => {
it("settles a request only with the reply carrying its id", async () => {
const desktop = new DesktopService("t");
- const posted: Record<string, unknown>[] = [];
- let onMessage: ((e: { data: unknown }) => void) | undefined;
- wireShellUpdatePort(desktop, {
- on: (_event, listener) => {
- onMessage = listener;
- },
- postMessage: (message) => posted.push(message as Record<string, unknown>),
- });
+ const port = new FakePort();
+ wireShellUpdatePort(desktop, port);
const pending = desktop.requestFolderAccess(DOWNLOADS);
expect(pending).not.toBeNull();
- const id = posted[0]!.id as string;
+ const id = (port.sent[0] as { id: string }).id;
let settled = false;
void pending!.then(() => {
settled = true;
});
- onMessage!({
- data: {
- type: "desktop-folder-access-result",
- id: `${id}-other`,
- granted: true,
- packaged: true,
- },
- });
+ port.emit(reply({ id: `${id}-other`, granted: true, packaged: true }));
await Promise.resolve();
expect(settled).toBe(false);
- onMessage!({
- data: {
- type: "desktop-folder-access-result",
- id,
- granted: false,
- code: "EPERM",
- packaged: true,
- },
- });
+ port.emit(reply({ id, granted: false, code: "EPERM", packaged: true }));
await expect(pending).resolves.toEqual({ granted: false, code: "EPERM", packaged: true });
});
@@ -390,14 +323,8 @@ describe("the folder-access half of the shell port", () => {
vi.useFakeTimers();
try {
const desktop = new DesktopService("t");
- const posted: Record<string, unknown>[] = [];
- let onMessage: ((e: { data: unknown }) => void) | undefined;
- wireShellUpdatePort(desktop, {
- on: (_event, listener) => {
- onMessage = listener;
- },
- postMessage: (message) => posted.push(message as Record<string, unknown>),
- });
+ const port = new FakePort();
+ wireShellUpdatePort(desktop, port);
const pending = desktop.requestFolderAccess(DOWNLOADS)!;
vi.advanceTimersByTime(FOLDER_ACCESS_TIMEOUT_MS - 1);
let settled = false;
@@ -409,24 +336,10 @@ describe("the folder-access half of the shell port", () => {
vi.advanceTimersByTime(1);
await expect(pending).resolves.toBeNull();
// Nobody waits for it any more: the late reply is dropped without a trace.
- expect(() =>
- onMessage!({
- data: {
- type: "desktop-folder-access-result",
- id: posted[0]!.id,
- granted: true,
- packaged: true,
- },
- }),
- ).not.toThrow();
+ const { id } = port.sent[0] as { id: string };
+ expect(() => port.emit(reply({ id, granted: true, packaged: true }))).not.toThrow();
} finally {
vi.useRealTimers();
}
});
-
- it("reports no shell before a port is wired", () => {
- const desktop = new DesktopService("t");
- expect(desktop.requestFolderAccess(DOWNLOADS)).toBeNull();
- expect(desktop.requestPrivacySettings("files")).toBe(false);
- });
});
diff --git a/packages/server/test/errors.test.ts b/packages/server/test/errors.test.ts
index 22a7559a..a5d9ad3a 100644
--- a/packages/server/test/errors.test.ts
+++ b/packages/server/test/errors.test.ts
@@ -1,14 +1,46 @@
/**
- * Error-record persistence unit and integration tests: ErrorsRepo's aggregation semantics (including cross-tenant isolation
- * where unattributed errors are **visible only to admins**) and its row-cap eviction
- * (evicts the oldest by id, without misfiring on id gaps left by deleteByProject);
- * ErrorRecorder's expected/unexpected determination (explicit kind takes priority, HTTP
- * infers from HttpError), short-window deduplication (storm protection), and the
- * "never throws itself" guarantee; StreamErrorWatcher picking up LLM / Environment
- * errors from the message stream (attributed to **the Session that actually produced
- * the error**: a child Session's failure is attributed to the child Agent / child
- * Session); HTTP onError actually persisting records; cascading cleanup on Project
- * deletion.
+ * Error records, from where they are caught to the cost center that shows them.
+ *
+ * The log (ErrorsRepo):
+ * - A summary counts every row and the unexpected ones; the top code groups by source, code and
+ * kind (none in range reads as nothing); dates and an Agent narrow every read.
+ * - The recent list folds a day's repeats of one error into one row with its count and its
+ * first and last time, the day being the viewer's when the read carries an offset; a page
+ * and the row count are rows, the summary still counts records.
+ * - A clear follows the caller's read: a member's leaves the unattributed rows, an admin's
+ * takes them; another Project's rows are out of reach either way.
+ * - Past its cap the log evicts its oldest rows by count, never misled by id gaps.
+ *
+ * The recorder (ErrorRecorder):
+ * - An HttpError is expected; any other failure is unexpected, an explicit kind wins over both,
+ * and a gateway close is filed by its own verdict.
+ * - A non-Error is stringified and an overlong message truncated; the recorder never throws.
+ * - The same error for the same Project persists once per short window, then resumes; source,
+ * code and Project each keep their own window; a full dedup table still records every
+ * distinct error and still collapses a burst.
+ *
+ * The stream watcher (LLM, tool and compaction failures in a Session's messages):
+ * - An LLM failure the retry ladder carried is expected under its own code; an exhausted or
+ * fatal one is unexpected, worded from the abort reason, the request's own detail or the
+ * status text in that order; a user's Stop and a completion are not errors.
+ * - A command tool's ordinary non-zero exit is information, not an error; a signal, a spawn
+ * failure, a timeout or a missing session manager are recorded; any other tool failure is
+ * expected under the tool's name, legacy spellings included.
+ * - Parallel and nested (child Session) calls never swap names or reasons, and a child's
+ * failures are attributed to the child Agent and Session.
+ * - An abandoned compaction is one unexpected row carrying its attempts and error.
+ *
+ * Through HTTP (onError):
+ * - A business error is expected, an internal one unexpected with a 500, each attributed to
+ * the Project only when the requester has access to it (unauthenticated and non-member
+ * failures stay unattributed, and a throwing access check degrades to unattributed).
+ * - The usage endpoint shows a Project's own errors; unattributed ones only to the admin.
+ * - The paged error route pages within the caller's tenant, narrows to one kind on request,
+ * and refuses a page it cannot serve; it and the dashboard fold by the viewer's day, and an
+ * offset no clock uses is a 400.
+ * - Clearing takes exactly the filter or trailing window on screen, never an unbounded range;
+ * a member may not clear; an admin's clear takes the unattributed rows it showed.
+ * - Deleting a Project deletes its error records and nobody else's.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { DatabaseSync } from "node:sqlite";
@@ -76,33 +108,6 @@ describe("errors-repo", () => {
expect(repo.summary("p1")).toEqual({ total: 3, unexpected: 1 });
});
- it("unattributed errors (login failure / crash) are admin-only, invisible to members", () => {
- const global = { projectId: null, source: "process", code: "uncaught_exception" };
- repo.insert(row("2026-07-06", global)); // Unattributed: another tenant's login failure / process crash
- repo.insert(row("2026-07-06", global));
- repo.insert(row("2026-07-06", { projectId: "p-other" })); // Another Project: invisible to everyone
- repo.insert(row("2026-07-06", { kind: "expected", code: "not_found", status: 404 })); // This Project
-
- // Regular member (default includeGlobal=false): all three queries see only the row for this Project.
- expect(repo.summary("p1")).toEqual({ total: 1, unexpected: 0 });
- expect(repo.topCode("p1")).toMatchObject({ code: "not_found", count: 1 });
- expect(repo.recent("p1").map((r) => r.code)).toEqual(["not_found"]);
-
- // Admin: this Project + unattributed (still can't see another Project's rows).
- const admin = { includeGlobal: true };
- expect(repo.summary("p1", admin)).toEqual({ total: 3, unexpected: 2 });
- expect(repo.topCode("p1", admin)).toMatchObject({ code: "uncaught_exception", count: 2 });
- // The two unattributed records are the same error on the same day, so they share a row.
- expect(repo.recent("p1", admin).map((r) => [r.code, r.count])).toEqual([
- ["not_found", 1],
- ["uncaught_exception", 2],
- ]);
-
- // A member of another Project likewise only sees their own row: unattributed errors never land in any regular member's view.
- expect(repo.summary("p-other")).toEqual({ total: 1, unexpected: 1 });
- expect(repo.recent("p-other").map((r) => r.code)).toEqual(["internal"]);
- });
-
it("top error code: grouped by source+code+kind, takes the highest count", () => {
for (let i = 0; i < 3; i++) repo.insert(row("2026-07-06", { code: "internal" }));
repo.insert(row("2026-07-06", { source: "session", code: "session_run_failed" }));
@@ -132,31 +137,6 @@ describe("errors-repo", () => {
expect(repo.recent("p1", { agentId: "a1" })).toHaveLength(1);
});
- it("a trailing window narrows the dates to instants, both ends inclusive, for reads and the clear alike", () => {
- const window = {
- from: "2026-07-06",
- to: "2026-07-06",
- fromTs: "2026-07-06T10:00:00.000Z",
- toTs: "2026-07-06T11:00:00.000Z",
- };
- for (const [time, message] of [
- ["09:59:59.999", "just before"],
- ["10:00:00.000", "at from"],
- ["10:30:00.000", "inside"],
- ["11:00:00.000", "at to"],
- ["11:00:00.001", "just after"],
- ] as const) {
- repo.insert(row("2026-07-06", { ts: `2026-07-06T${time}Z`, message }));
- }
- // A row stamped exactly on either bound is inside the window …
- expect(repo.summary("p1", window)).toEqual({ total: 3, unexpected: 3 });
- expect(repo.recent("p1", window).map((r) => r.message)).toEqual(["at to", "inside", "at from"]);
- // … and the clear of the same window takes exactly those, sparing the same day's rows a
- // millisecond outside it.
- expect(repo.deleteFiltered("p1", window)).toBe(3);
- expect(repo.recent("p1").map((r) => r.message)).toEqual(["just after", "just before"]);
- });
-
it("recent folds a day's repeats into one row, with how many and the first and last time", () => {
// A connection that drops and recovers all afternoon files the same record again and again;
// the table reads it as one line saying how often. Anything that differs keeps its own row:
@@ -242,44 +222,6 @@ describe("errors-repo", () => {
expect(repo.rowCount("p1", {}, 0)).toBe(2);
});
- it("recent errors: newest first, top limit rows", () => {
- repo.insert(row("2026-07-05", { message: "old" }));
- repo.insert(row("2026-07-06", { message: "new" }));
- const recent = repo.recent("p1", {}, 1);
- expect(recent).toHaveLength(1);
- expect(recent[0]!.message).toBe("new");
- });
-
- it("deleteByProject: deletes only that Project's rows, unattributed errors remain", () => {
- repo.insert(row("2026-07-06"));
- repo.insert(row("2026-07-06", { projectId: null }));
- repo.deleteByProject("p1");
- const rows = db.prepare("SELECT project_id FROM error_records").all();
- expect(rows).toHaveLength(1);
- expect(rows[0]!.project_id).toBeNull();
- });
-
- it("deleteFiltered: takes exactly the rows the same filter would have read", () => {
- repo.insert(row("2026-07-05", { message: "before-range" }));
- repo.insert(row("2026-07-06", { agentId: "a1", message: "in-range-a1" }));
- repo.insert(row("2026-07-06", { agentId: "a2", message: "in-range-a2" }));
- repo.insert(row("2026-07-07", { message: "after-range" }));
-
- // Narrowed to one Agent inside the range: everything the reader could not see survives.
- expect(repo.deleteFiltered("p1", { from: "2026-07-06", to: "2026-07-06", agentId: "a1" })).toBe(
- 1,
- );
- expect(repo.recent("p1").map((r) => r.message)).toEqual([
- "after-range",
- "in-range-a2",
- "before-range",
- ]);
-
- // The range alone still spares the dates outside it.
- expect(repo.deleteFiltered("p1", { from: "2026-07-06", to: "2026-07-06" })).toBe(1);
- expect(repo.recent("p1").map((r) => r.message)).toEqual(["after-range", "before-range"]);
- });
-
it("deleteFiltered follows the caller's includeGlobal: a member's clear leaves unattributed rows, an admin's takes them", () => {
// Unattributed rows appear in every Project's admin view and in no member's. The clear
// reaches exactly what the caller's read reaches, so only a read that includes them
@@ -343,42 +285,22 @@ describe("error-recorder", () => {
});
afterEach(() => db.close());
- it("HttpError → expected (keeps code and status)", () => {
+ it("a non-HTTP failure is unexpected, with no status and the attribution it was given", () => {
wire(ErrorRecorder, { errors: repo, clock: { now: now } }).record({
- source: "http",
- err: new HttpError(
- 404,
- "session_not_found",
- "Session does not exist or you do not have access.",
- ),
- ctx: { projectId: "p1" },
- });
- const r = db.prepare("SELECT * FROM error_records").get()!;
- expect(r.kind).toBe("expected");
- expect(r.code).toBe("session_not_found");
- expect(r.status).toBe(404);
- expect(r.project_id).toBe("p1");
- expect(r.date).toBe("2026-07-06");
- });
-
- it("non-HttpError → unexpected; HTTP source converges to 500, non-HTTP status is NULL", () => {
- const rec = wire(ErrorRecorder, { errors: repo, clock: { now: now } });
- rec.record({ source: "http", err: new Error("boom") });
- rec.record({
source: "session",
err: new Error("drive crashed"),
ctx: { projectId: "p1", agentId: "a1", sessionId: "s1" },
code: "session_run_failed",
});
- const rows = db.prepare("SELECT * FROM error_records ORDER BY id").all();
- expect(rows[0]!.kind).toBe("unexpected");
- expect(rows[0]!.code).toBe("internal"); // Matches the same code convention as handleError's external-facing code
- expect(rows[0]!.status).toBe(500);
- expect(rows[0]!.project_id).toBeNull();
- expect(rows[1]!.code).toBe("session_run_failed");
- expect(rows[1]!.status).toBeNull();
- expect(rows[1]!.agent_id).toBe("a1");
- expect(rows[1]!.session_id).toBe("s1");
+ expect(db.prepare("SELECT * FROM error_records").get()).toMatchObject({
+ kind: "unexpected",
+ code: "session_run_failed",
+ status: null,
+ project_id: "p1",
+ agent_id: "a1",
+ session_id: "s1",
+ date: "2026-07-06",
+ });
});
it("non-Error throwables and overlong messages: stringified and truncated to the cap", () => {
@@ -445,9 +367,6 @@ describe("error-recorder", () => {
const count = () =>
db.prepare("SELECT COUNT(*) AS n FROM error_records").get()!.n as unknown as number;
- /** Dedup table (private): asserts the hard requirement that it stays "bounded". */
- const lastSeen = (rec: ErrorRecorder) =>
- (rec as unknown as { lastSeen: Map<string, number> }).lastSeen;
it("short-window dedup: same-kind errors persist once per window, then resume", () => {
let t = Date.parse("2026-07-06T10:00:00Z");
@@ -484,27 +403,29 @@ describe("error-recorder", () => {
expect(count()).toBe(5);
});
- it("bounded dedup table: expired entries cleaned first, else wiped; works afterward", () => {
+ it("keeps recording and deduplicating after its table fills, expires and is wiped", () => {
+ // The table is bounded: past DEDUP_KEYS_MAX keys it drops the expired ones, or all of them
+ // when none has expired. Either way no distinct error may be lost and a burst of one error
+ // must still collapse to one row.
let t = Date.parse("2026-07-06T10:00:00Z");
const rec = wire(ErrorRecorder, { errors: repo, clock: { now: () => new Date(t) } });
const boom = (code: string) =>
rec.record({ source: "http", err: "boom", ctx: { projectId: "p1" }, code });
- for (let i = 0; i < DEDUP_KEYS_MAX; i++) boom(`c${i}`); // fill it up (one key per code)
- expect(lastSeen(rec).size).toBe(DEDUP_KEYS_MAX);
+ for (let i = 0; i < DEDUP_KEYS_MAX; i++) boom(`c${i}`); // one key per code: the table is full
+ expect(count()).toBe(DEDUP_KEYS_MAX);
- t += DEDUP_WINDOW_MS; // all old keys expired: the next entry triggers cleanup, leaving only the newly registered one
+ t += DEDUP_WINDOW_MS; // every key has expired, so the next one cleans them out
boom("after-window");
- expect(lastSeen(rec).size).toBe(1);
+ boom("after-window");
+ expect(count()).toBe(DEDUP_KEYS_MAX + 1);
- for (let i = 0; i < DEDUP_KEYS_MAX; i++) boom(`d${i}`); // all within the same window: nothing to clean → wipe the whole table
- expect(lastSeen(rec).size).toBeLessThanOrEqual(DEDUP_KEYS_MAX);
+ for (let i = 0; i < DEDUP_KEYS_MAX; i++) boom(`d${i}`); // one window, nothing expired: wiped
+ expect(count()).toBe(2 * DEDUP_KEYS_MAX + 1);
- // Works normally after being wiped: new errors are still recorded, and duplicates within the window are still discarded.
- const before = count();
boom("tail");
boom("tail");
- expect(count()).toBe(before + 1);
+ expect(count()).toBe(2 * DEDUP_KEYS_MAX + 2);
});
});
@@ -694,39 +615,6 @@ describe("stream-error-watcher (LLM / Environment errors)", () => {
]);
});
- it("a retried failure keeps its real detail: request_end(retryable).message lands in the record", () => {
- // The retry path: the engine reconnects (request_begin) and eventually succeeds, so no
- // abort ever arrives for the staged failure — the request_end's own failure detail
- // (LLMOutcome.errorMessage, e.g. a rate-limit code) is the message of record, not the
- // generic status text. This is what the Cost center shows for a retried 429.
- const got = feed([
- requestBegin(),
- requestEnd("retryable", {
- errorMessage: "429 rate limited (slow down)",
- }),
- requestBegin(),
- requestEnd("completed"),
- ]);
- expect(got).toHaveLength(1);
- expect(got[0]).toMatchObject({
- source: "llm",
- kind: "expected",
- code: "llm_retried",
- message: "429 rate limited (slow down)",
- });
- });
-
- it("an abort reason still outranks the staged request_end detail (fatal exit path)", () => {
- const got = feed([
- requestBegin(),
- requestEnd("fatal", { errorMessage: "401 invalid x-api-key (invalid_api_key)" }),
- legacyAbort("llm request error: 401 invalid x-api-key (invalid_api_key)"),
- ]);
- expect(got).toHaveLength(1);
- // The abort's prose (with core's "llm request error" framing) wins over the raw detail.
- expect(got[0]!.message).toBe("llm request error: 401 invalid x-api-key (invalid_api_key)");
- });
-
it("interrupt during backoff with a staged detail: the detail wins over the status text", () => {
// The interrupt message is distrusted (not the failure's reason), but the staged
// request_end detail IS the failure's reason — prefer it over the generic status text.
@@ -1562,13 +1450,19 @@ describe("HTTP onError persistence (integration)", () => {
expect(errorRows().filter((r) => r.project_id === null)).toHaveLength(0);
});
- it("Project deletion cascade-cleans that Project's error records", async () => {
+ it("deleting a Project deletes its error records and nobody else's", async () => {
await api.get(`/api/projects/${projectId}/agents/agent-nope/sessions`);
expect(errorRows().filter((r) => r.project_id === projectId)).toHaveLength(1);
+ // An unattributed row (a failed login) belongs to no Project and must outlive this one.
+ await t.app.request("/api/auth/login", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ userId: "err_user", password: "wrong-password" }),
+ });
const del = await api.delete(`/api/projects/${projectId}`);
expect(del.status).toBe(204);
- expect(errorRows().filter((r) => r.project_id === projectId)).toHaveLength(0);
+ expect(errorRows().map((r) => r.project_id)).toEqual([null]);
});
});
diff --git a/packages/server/test/first-login.test.ts b/packages/server/test/first-login.test.ts
index 3f18c5a9..1831511e 100644
--- a/packages/server/test/first-login.test.ts
+++ b/packages/server/test/first-login.test.ts
@@ -1,14 +1,25 @@
/**
- * The first-login proof of the claim route (auth/service.ts, routes/auth.ts) — the other one,
- * the desktop shell's token, is covered in desktop.test.ts.
+ * The first-login link: the claim route's proof for a server nobody has signed in to yet
+ * (auth/service.ts, routes/auth.ts). The desktop shell's token, the route's other proof, is
+ * covered in desktop.test.ts.
*
- * What is peculiar to this proof is that the link CARRIES a session rather than a secret
- * redeemed for one. That buys simplicity and costs a hazard the desktop token does not have:
- * an endpoint that made a cookie out of any valid token would let one person sign another
- * into their own account. So the printed value is compared, not merely verified — and it stops
- * working the moment a password exists, since a console scrollback must not stay a way in.
+ * The link CARRIES a session rather than a secret redeemed for one. That buys simplicity and
+ * costs a hazard the desktop token does not have: an endpoint that made a cookie out of any
+ * valid token would let one person sign another into their own account. So the printed value
+ * is compared, not merely verified, and it stops working the moment a password exists.
+ *
+ * - Given an unclaimed server, the printed link signs the browser in with a `setup` session
+ * that may set a password without an old one; once one is set, the link is refused.
+ * - Any token but the printed one is refused exactly as a spent link is.
+ * - The link is not single-use before the claim: opening it twice lands in one session.
+ * - A password set through the ordinary change-password door (a pinned seed) ends the link.
+ * - Claiming hands the claimer a working password session back, and the link's own cookie dies.
+ * - A setup session left over from an earlier boot dies with the claim too.
+ * - A rejected password keeps the link alive.
+ * - The claimer is signed in even while a guessing spree has the login throttled.
+ * - A link older than the session lifetime is re-minted rather than handed out dead.
+ * - A claimed server mints no link, so a restart offers none.
*/
-import fs from "node:fs";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { SESSION_COOKIE } from "../src/auth/middleware.js";
@@ -102,24 +113,19 @@ describe("the first-login link", () => {
/**
* The one reachable way to set a password WITHOUT going through setInitialPassword's
- * revocation: a pinned seed (PENGUIN_SEED_ADMIN_PASSWORD) makes the current password
- * knowable, so the ordinary change-password door opens. The link must die there too —
- * the invariant is "any password set on the admin ends the link", not "the door we
- * expected ends it".
+ * revocation: a pinned seed (PENGUIN_SEED_ADMIN_PASSWORD, which every test app has) makes
+ * the current password knowable, so the ordinary change-password door opens. The link must
+ * die there too — the invariant is "any password set on the admin ends the link", not "the
+ * door we expected ends it".
*/
it("dies when the admin sets a password through the ordinary door (pinned seed)", async () => {
- const pinned = await createTestApp();
- try {
- const pinnedLink = pinned.deps.authService.mintFirstLogin()!;
- const { cookie } = await loginAdmin(pinned.app);
- await apiClient(pinned.app, cookie).put("/api/me/password", {
- oldPassword: pinned.adminPassword,
- newPassword: "chosen-password-1",
- });
- expect(pinned.deps.authService.redeemFirstLogin(pinnedLink)).toBeNull();
- } finally {
- await pinned.cleanup();
- }
+ const { cookie } = await loginAdmin(t.app);
+ await apiClient(t.app, cookie).put("/api/me/password", {
+ oldPassword: t.adminPassword,
+ newPassword: "chosen-password-1",
+ });
+ expect(t.deps.authService.redeemFirstLogin(link)).toBeNull();
+ expectRefusal(await redeem(link));
});
/**
@@ -178,12 +184,6 @@ describe("the first-login link", () => {
}
});
- /**
- * The setup session renews in place (the row's expiry is topped up, the cookie value is
- * unchanged), so it survives well past the printed link's original 30-day mark. Setting a
- * password deletes that row, and the link goes dead — no surviving setup session, whether
- * or not it was renewed first.
- */
/**
* The revocation fires only after the password actually updates: a rejected attempt must
* leave the link alive, or a typo (or anyone poking the endpoint with a bad value) burns
@@ -296,17 +296,4 @@ describe("the first-login link", () => {
await second.cleanup();
}
});
-
- /**
- * A minted token that is never delivered is a feature nobody can reach, and every test
- * above mints its own — so none of them would notice. The entrypoint runs main() on import
- * and exports nothing, which leaves reading it the way to check that what it mints actually
- * reaches a console.
- */
- it("is printed by the entrypoint, not merely minted", () => {
- const entrypoint = fs.readFileSync(new URL("../src/index.ts", import.meta.url), "utf8");
- expect(entrypoint).toMatch(/renderFirstLoginNotice\(/);
- expect(entrypoint).toMatch(/mintFirstLogin\(/);
- expect(entrypoint).toMatch(/\/api\/auth\/claim\?token=/);
- });
});
diff --git a/packages/server/test/fixtures/fetch.ts b/packages/server/test/fixtures/fetch.ts
new file mode 100644
index 00000000..e724f730
--- /dev/null
+++ b/packages/server/test/fixtures/fetch.ts
@@ -0,0 +1,74 @@
+/**
+ * The suite's one fetch fake. Every outbound HTTP request a test causes is recorded, and each
+ * is answered by the test's script: a Response, or a throw that plays a transport failure.
+ * Hand `fake.fetch` to a service that takes a fetch, or stand it in for the global one with
+ * {@link stubFetch} and restore the real one with `vi.unstubAllGlobals()` in `afterEach`.
+ * Nothing here reaches the network.
+ */
+import { vi } from "vitest";
+
+/** One request, as the fake received it. */
+export interface FetchCall {
+ /** The URL exactly as the caller passed it. */
+ url: string;
+ method: string;
+ headers: Headers;
+ /** The body read as text; "" when there is none. */
+ body: string;
+ /** The body's bytes; empty when there is none. */
+ bytes: Uint8Array;
+ /** The caller's `init`, as passed (its `redirect`, its `signal`). */
+ init: RequestInit | undefined;
+}
+
+/** Answers the `index`-th call (0-based): a Response, or a throw. */
+export type FetchScript = (call: FetchCall, index: number) => Response | Promise<Response>;
+
+export interface FetchFake {
+ /** The fetch to hand to a service, or to install with {@link stubFetch}. */
+ readonly fetch: typeof fetch;
+ /** Every call, in arrival order. */
+ readonly calls: FetchCall[];
+}
+
+export function fakeFetch(script: FetchScript): FetchFake {
+ const calls: FetchCall[] = [];
+ const impl = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
+ const request = new Request(input, init);
+ const bytes = new Uint8Array(await request.arrayBuffer());
+ const call: FetchCall = {
+ url: input instanceof Request ? input.url : String(input),
+ method: request.method,
+ headers: request.headers,
+ body: new TextDecoder().decode(bytes),
+ bytes,
+ init,
+ };
+ calls.push(call);
+ return script(call, calls.length - 1);
+ };
+ return { fetch: impl as typeof fetch, calls };
+}
+
+/** Installs a {@link fakeFetch} as the global fetch; the caller restores it after the test. */
+export function stubFetch(script: FetchScript): FetchFake {
+ const fake = fakeFetch(script);
+ vi.stubGlobal("fetch", fake.fetch);
+ return fake;
+}
+
+export function jsonResponse(
+ body: unknown,
+ status = 200,
+ headers: Record<string, string> = {},
+): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json", ...headers },
+ });
+}
+
+/** A transport failure the way undici reports one: `TypeError: fetch failed` over the errno. */
+export function fetchFailed(code: string): TypeError {
+ return new TypeError("fetch failed", { cause: Object.assign(new Error(code), { code }) });
+}
diff --git a/packages/server/test/id-validation.test.ts b/packages/server/test/id-validation.test.ts
index 19564b77..014a3150 100644
--- a/packages/server/test/id-validation.test.ts
+++ b/packages/server/test/id-validation.test.ts
@@ -1,15 +1,22 @@
/**
- * Integration tests for path-parameter id validation (FD-4, path
- * traversal prevention): Hono decodes URL-encoded `%2F` into a single path
- * parameter — a traversal-style agentId (`../<victim>/...`), if passed through
- * to path construction unchanged, would let an attacker read/write another
- * user's Agent config and Trace across Projects.
- * Every route that takes :agentId (config / traces / sessions / trace detail)
- * must return 404.
+ * Path-parameter id validation (FD-4, path traversal): Hono decodes a URL-encoded `%2F` into a
+ * single path parameter, so a traversal-style agentId (`../<victim>/...`) passed through to
+ * path construction unchanged would let an attacker read or write another user's Agent config
+ * and Traces across Projects.
+ *
+ * Given an attacker with a Project of their own and a victim with another:
+ * - Reading the victim's Agent config through a traversal agentId is a 404 that leaks nothing,
+ * while the attacker's own Agent config still reads.
+ * - Writing it the same way is a 404 that leaves the victim's file untouched.
+ * - The traces and sessions routes answer a traversal agentId with 404.
+ * - The Trace detail routes answer a traversal sessionId or agentId with 404.
+ * - A traversal or invalid-character projectId is a 404 on every Project route.
+ *
+ * Every case is a refused request, so one app serves them all.
*/
import fs from "node:fs/promises";
import path from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { ProjectCreateResponse } from "../src/api/types.js";
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
@@ -24,7 +31,7 @@ describe("id-validation", () => {
const traversal = () => `..%2F${victimProject}%2Fdefault_agent`;
const agentBase = () => `/api/projects/${attackerProject}/agents`;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
const a = await provisionUser(t.app, "attacker");
const v = await provisionUser(t.app, "victim");
@@ -39,7 +46,7 @@ describe("id-validation", () => {
).json()) as ProjectCreateResponse;
victimProject = victimCreated.project.projectId;
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
diff --git a/packages/server/test/password.test.ts b/packages/server/test/password.test.ts
index 1b9618f4..d5a12a4e 100644
--- a/packages/server/test/password.test.ts
+++ b/packages/server/test/password.test.ts
@@ -1,9 +1,17 @@
/**
- * Unit tests for scrypt password hashing: format, verification, salt randomness,
- * and fallback behavior for invalid stored strings. The `password` cases call `hashPassword`
- * without a cost argument, so they are the one place the production work factor is exercised.
- * The account-check cases hash at a token cost: they count derivations through an injected
- * check, never time them.
+ * Password hashing (auth/password.ts) and the account check the login route runs on it.
+ *
+ * - A hash made without a cost argument is stored as `scrypt$N$r$p$salt$hash` at the
+ * production work factor; it verifies its own password and fails any other.
+ * - The same password hashed twice differs (random salt), and both verify.
+ * - A stored string that is not a checkable hash verifies as false instead of throwing.
+ * - The check tells a mismatch apart from a hash it cannot check.
+ * - An unknown username is checked against the dummy hash, once, and never signs anyone in.
+ * - A real account is checked against its own hash, once, without the dummy.
+ * - An account whose stored hash cannot be checked still spends its one derivation, on the dummy.
+ *
+ * The `password` cases hash at the production work factor: they are the one place it runs.
+ * The account-check cases hash at a token cost and count derivations, never time them.
*/
import { describe, expect, it, vi } from "vitest";
import {
@@ -16,20 +24,15 @@ import {
import type { PasswordCheck } from "../src/auth/password.js";
describe("password", () => {
- it("hash format is scrypt$N$r$p$salt$hash and verifies", async () => {
+ it("stores an unparameterized hash at the production cost, verifying only its own password", async () => {
const stored = await hashPassword("hello-world-123");
const parts = stored.split("$");
expect(parts).toHaveLength(6);
expect(parts[0]).toBe("scrypt");
- // The default work factor is what production hashes at; `hashPassword`'s cost argument
- // exists for the test suite and must never lower what an unparameterized call writes.
- expect(SCRYPT_COST).toBe(16384);
+ // `hashPassword`'s cost argument exists for the test suite and must never lower what an
+ // unparameterized call writes.
expect(Number(parts[1])).toBe(SCRYPT_COST);
await expect(verifyPassword("hello-world-123", stored)).resolves.toBe(true);
- });
-
- it("a wrong password fails verification", async () => {
- const stored = await hashPassword("correct-password");
await expect(verifyPassword("wrong-password", stored)).resolves.toBe(false);
});
diff --git a/packages/server/test/platform-auth.test.ts b/packages/server/test/platform-auth.test.ts
index 17c2e19f..ecc3079c 100644
--- a/packages/server/test/platform-auth.test.ts
+++ b/packages/server/test/platform-auth.test.ts
@@ -1,3 +1,21 @@
+/**
+ * Penguin Go key delivery: the platform's device authorization, as the models page drives it
+ * through /api/projects/:p/platform-auth, and the catalog sync that follows.
+ *
+ * - A delivery is accepted only for this client with a connection API key; its models are
+ * normalized to their list price with the promotion stored beside it, and a delivery with a
+ * malformed model (no output length, a negative or non-USD price) is refused.
+ * - Given a Project whose Penguin Go group has no key, the owner's authorization writes the
+ * delivered key and catalog into it (a member is refused, and a sync before any key asks for
+ * reauthorization); nothing of the account or the key itself is ever answered back.
+ * - A later sync applies the platform's repricing, a promotion-only change (web.db alone), and
+ * a newly listed model, reporting what it added and updated.
+ * - The platform's start backoff reaches the caller as a 429 with Retry-After.
+ * - A stored key the platform rejects asks for reauthorization and applies nothing.
+ * - A failed write retries with the key already claimed, without polling the platform again.
+ * - A rate-limited poll stays pending and polls again only after the platform's backoff.
+ * - A flow the user cancels while a poll is in flight applies nothing.
+ */
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type {
ModelsResponse,
@@ -7,15 +25,11 @@ import type {
ProjectCreateResponse,
} from "../src/api/types.js";
import { PlatformAuthService, platformConnection } from "../src/services/platform-auth-service.js";
+import { fakeFetch, jsonResponse, stubFetch } from "./fixtures/fetch.js";
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-function json(status: number, body: unknown): Response {
- return new Response(JSON.stringify(body), {
- status,
- headers: { "content-type": "application/json" },
- });
-}
+const json = (status: number, body: unknown): Response => jsonResponse(body, status);
const deliveryBody = {
status: "claimed",
@@ -198,37 +212,31 @@ describe("Penguin Go key authorization routes", () => {
pollCount = 0;
currentCatalogModels = [...deliveryBody.connection.models];
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
- const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
- if (url.pathname === "/api/auth/desktop/start") {
- const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
- expect(body.client).toEqual({ id: "penguin-harness" });
- expect(String(body.code)).toMatch(/^[A-Za-z0-9_-]{43}$/);
- expect(String(body.deviceSecret)).toMatch(/^[A-Za-z0-9_-]{43}$/);
- return json(201, { expiresAt: new Date(Date.now() + 10 * 60_000).toISOString() });
- }
- if (url.pathname === "/api/auth/desktop/poll") {
- pollCount += 1;
- return pollCount === 1
- ? json(200, { status: "pending", expiresInSeconds: 500 })
- : json(200, deliveryBody);
- }
- if (url.pathname === "/api/client/models") {
- expect(new Headers(init?.headers).get("authorization")).toBe(
- "Bearer sk-penguin-go-secret-0001",
- );
- return json(200, syncCatalog(currentCatalogModels));
- }
- throw new Error(`Unexpected platform request: ${url.pathname}`);
- }),
- );
+ stubFetch((call) => {
+ const { pathname } = new URL(call.url);
+ if (pathname === "/api/auth/desktop/start") {
+ const body = JSON.parse(call.body) as Record<string, unknown>;
+ expect(body.client).toEqual({ id: "penguin-harness" });
+ expect(String(body.code)).toMatch(/^[A-Za-z0-9_-]{43}$/);
+ expect(String(body.deviceSecret)).toMatch(/^[A-Za-z0-9_-]{43}$/);
+ return json(201, { expiresAt: new Date(Date.now() + 10 * 60_000).toISOString() });
+ }
+ if (pathname === "/api/auth/desktop/poll") {
+ pollCount += 1;
+ return pollCount === 1
+ ? json(200, { status: "pending", expiresInSeconds: 500 })
+ : json(200, deliveryBody);
+ }
+ if (pathname === "/api/client/models") {
+ expect(call.headers.get("authorization")).toBe("Bearer sk-penguin-go-secret-0001");
+ return json(200, syncCatalog(currentCatalogModels));
+ }
+ throw new Error(`Unexpected platform request: ${pathname}`);
+ });
});
afterEach(async () => {
vi.unstubAllGlobals();
- vi.restoreAllMocks();
await t.cleanup();
});
@@ -240,17 +248,13 @@ describe("Penguin Go key authorization routes", () => {
const initialPenguinGoModels = initial.models.filter(
(model) => model.provider === "penguin-go",
);
- expect(initialPenguinGoModels.map((model) => model.modelId)).toEqual([
- "gemini-3.8-flash",
- "gemini-3.7-flash",
- "gemini-3.6-flash",
- "gemini-3.5-flash",
- "gemini-3.5-flash-lite",
- "gemini-3.1-flash-lite",
- "gemini-3.1-pro-preview",
- "deepseek-flash",
- "deepseek-v4-pro",
- ]);
+ // The preset group is there before any authorization, keyless, on the platform's endpoint.
+ // The delivery lands on top of it: the group ends up with the preset's models and the
+ // delivered ones, whichever the preset already carried.
+ const deliveredCount = new Set([
+ ...initialPenguinGoModels.map((model) => model.modelId),
+ ...deliveryBody.connection.models.map((model) => model.modelId),
+ ]).size;
expect(
initialPenguinGoModels.every(
(model) => model.credential?.baseUrl === "https://token.penguin.ooo/api",
@@ -282,14 +286,14 @@ describe("Penguin Go key authorization routes", () => {
const done = (await (
await owner.get(`${base}/${started.flowId}/status`)
).json()) as PlatformAuthFlowStatusResponse;
- expect(done).toEqual({ status: "completed", applied: 10 });
+ expect(done).toEqual({ status: "completed", applied: deliveredCount });
expect(JSON.stringify(done)).not.toContain("sk-penguin");
const models = (await (
await owner.get(`/api/projects/${projectId}/models`)
).json()) as ModelsResponse;
const penguinGoModels = models.models.filter((model) => model.provider === "penguin-go");
- expect(penguinGoModels).toHaveLength(10);
+ expect(penguinGoModels).toHaveLength(deliveredCount);
const deepseekFuture = penguinGoModels.find((model) => model.modelId === "deepseek-future");
expect(deepseekFuture).toMatchObject({
displayName: "DeepSeek Future",
@@ -343,7 +347,9 @@ describe("Penguin Go key authorization routes", () => {
).json()) as PlatformModelSyncResponse;
expect(synced).toMatchObject({ added: 0, updated: 0 });
expect(synced.updatedAt).toBe(models.updatedAt);
- expect(synced.models.filter((model) => model.provider === "penguin-go")).toHaveLength(10);
+ expect(synced.models.filter((model) => model.provider === "penguin-go")).toHaveLength(
+ deliveredCount,
+ );
const patchGemini = (patch: Record<string, unknown>) => {
currentCatalogModels = currentCatalogModels.map((model) =>
@@ -434,10 +440,7 @@ describe("Penguin Go key authorization routes", () => {
});
it("preserves the platform start backoff as HTTP 429 with Retry-After", async () => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async () => json(429, { error: "rate_limited", retryAfterSeconds: 7 })),
- );
+ stubFetch(() => json(429, { error: "rate_limited", retryAfterSeconds: 7 }));
const response = await owner.post(`/api/projects/${projectId}/platform-auth/start`, {});
expect(response.status).toBe(429);
@@ -453,7 +456,7 @@ describe("single-delivery local retry", () => {
origin: "https://token.penguin.ooo",
getKey: async () => "revoked-key",
applyCatalog,
- fetchImpl: async () => json(401, { error: "Invalid API key" }),
+ fetchImpl: fakeFetch(() => json(401, { error: "Invalid API key" })).fetch,
});
await expect(service.sync("p1")).rejects.toMatchObject({
@@ -463,9 +466,24 @@ describe("single-delivery local retry", () => {
expect(applyCatalog).not.toHaveBeenCalled();
});
+ /** The platform's two device-flow endpoints: `start` succeeds, `poll` answers as told. */
+ const platform = (poll: (n: number) => Response | Promise<Response>, now = () => Date.now()) => {
+ let polls = 0;
+ const fake = fakeFetch((call) => {
+ if (new URL(call.url).pathname.endsWith("/start")) {
+ return json(201, { expiresAt: new Date(now() + 60_000).toISOString() });
+ }
+ // The claim is read from the answer itself: a redirect must never be followed to it.
+ expect(call.init?.redirect).toBe("manual");
+ polls += 1;
+ return poll(polls);
+ });
+ return { fetch: fake.fetch, polls: () => polls };
+ };
+
it("reuses the key after a failed write without polling the platform again", async () => {
let applies = 0;
- let polls = 0;
+ const flow = platform(() => json(200, deliveryBody));
const service = new PlatformAuthService({
origin: "https://token.penguin.ooo",
getKey: async () => undefined,
@@ -474,15 +492,7 @@ describe("single-delivery local retry", () => {
if (applies === 1) throw new Error("disk busy");
return { added: 0, updated: 0, applied: 5 };
},
- fetchImpl: async (input, init) => {
- const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
- if (url.pathname.endsWith("/start")) {
- return json(201, { expiresAt: new Date(Date.now() + 60_000).toISOString() });
- }
- expect(init?.redirect).toBe("manual");
- polls += 1;
- return json(200, deliveryBody);
- },
+ fetchImpl: flow.fetch,
});
const started = await service.start({ projectId: "p1", userId: "u1" });
expect(
@@ -491,28 +501,25 @@ describe("single-delivery local retry", () => {
expect(
await service.retryApply({ flowId: started.flowId, projectId: "p1", userId: "u1" }),
).toMatchObject({ status: "completed", applied: 5, changed: true });
- expect(polls).toBe(1);
+ expect(flow.polls()).toBe(1);
expect(applies).toBe(2);
});
it("keeps a rate-limited poll pending and retries after the platform backoff", async () => {
let now = 1_000;
- let polls = 0;
+ const flow = platform(
+ (n) =>
+ n === 1
+ ? json(429, { error: "rate_limited", retryAfterSeconds: 2 })
+ : json(200, deliveryBody),
+ () => now,
+ );
const service = new PlatformAuthService({
origin: "https://token.penguin.ooo",
now: () => now,
getKey: async () => undefined,
applyCatalog: async () => ({ added: 0, updated: 0, applied: 5 }),
- fetchImpl: async (input) => {
- const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
- if (url.pathname.endsWith("/start")) {
- return json(201, { expiresAt: new Date(now + 60_000).toISOString() });
- }
- polls += 1;
- return polls === 1
- ? json(429, { error: "rate_limited", retryAfterSeconds: 2 })
- : json(200, deliveryBody);
- },
+ fetchImpl: flow.fetch,
});
const started = await service.start({ projectId: "p1", userId: "u1" });
@@ -523,13 +530,13 @@ describe("single-delivery local retry", () => {
expect(await service.status({ flowId: started.flowId, projectId: "p1", userId: "u1" })).toEqual(
{ status: "pending" },
);
- expect(polls).toBe(1);
+ expect(flow.polls()).toBe(1);
now += 1;
expect(
await service.status({ flowId: started.flowId, projectId: "p1", userId: "u1" }),
).toMatchObject({ status: "completed", applied: 5, changed: true });
- expect(polls).toBe(2);
+ expect(flow.polls()).toBe(2);
});
it("does not apply a claimed key when the user cancels while polling", async () => {
@@ -543,16 +550,12 @@ describe("single-delivery local retry", () => {
origin: "https://token.penguin.ooo",
getKey: async () => undefined,
applyCatalog,
- fetchImpl: async (input) => {
- const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
- if (url.pathname.endsWith("/start")) {
- return json(201, { expiresAt: new Date(Date.now() + 60_000).toISOString() });
- }
+ fetchImpl: platform(() => {
markPollStarted();
return new Promise<Response>((resolve) => {
releasePoll = resolve;
});
- },
+ }).fetch,
});
const started = await service.start({ projectId: "p1", userId: "u1" });
const status = service.status({ flowId: started.flowId, projectId: "p1", userId: "u1" });
diff --git a/packages/server/test/semantic-id.test.ts b/packages/server/test/semantic-id.test.ts
index 13864b93..d562b7a8 100644
--- a/packages/server/test/semantic-id.test.ts
+++ b/packages/server/test/semantic-id.test.ts
@@ -1,3 +1,20 @@
+/**
+ * Semantic ids (services/semantic-id.ts): how a create dialog's name becomes the id of an
+ * organization, a channel, a Project, an Agent or a Benchmark, when the model is not asked or
+ * its answer is unusable.
+ *
+ * - A name folds to a lowercase id behind the kind's prefix: diacritics folded, words joined,
+ * the prefix never doubled; a name with no ASCII letter or digit yields nothing; the ASCII
+ * part of a mixed name is kept.
+ * - An id is capped at 64 characters with its prefix kept, never ending in a separator, and a
+ * taken id gets a numeric suffix (compared after prefixing) that stays inside the cap.
+ * - A model's answer is read from its first non-empty line, quotes and code marks stripped,
+ * prefixed once; an answer with no ASCII yields nothing.
+ * - A placeholder is a valid, dated, obviously temporary id that avoids the taken ones.
+ * - Projects and Agents take a bare snake_case id, repaired behind the noun when it would start
+ * with a digit or be one letter; a Benchmark takes a kebab-case id; a non-admin's Project
+ * lives in the owner's namespace; every kind accepts its own placeholder.
+ */
import { describe, expect, it } from "vitest";
import {
SEMANTIC_ID_RULES,
@@ -9,107 +26,80 @@ import {
uniqueSemanticId,
} from "../src/services/semantic-id.js";
-describe("fallbackSemanticId", () => {
- it("lowercases, folds diacritics, joins words with underscores and prefixes by kind", () => {
- expect(fallbackSemanticId("Plugin Marketplace", SEMANTIC_ID_RULES.org)).toBe(
- "co_plugin_marketplace",
- );
- expect(fallbackSemanticId(" Café--Site!! ", SEMANTIC_ID_RULES.channel)).toBe("ch_cafe_site");
- });
-
- it("the prefix is what makes a name starting with a digit a valid id", () => {
- expect(fallbackSemanticId("2026 plan", SEMANTIC_ID_RULES.org)).toBe("co_2026_plan");
- expect(fallbackSemanticId("3d", SEMANTIC_ID_RULES.channel)).toBe("ch_3d");
- });
-
- it("a one-character name is already long enough once prefixed", () => {
- expect(fallbackSemanticId("x", SEMANTIC_ID_RULES.org)).toBe("co_x");
- });
+const { org, channel } = SEMANTIC_ID_RULES;
- it("does not prefix a core that already carries the prefix", () => {
- expect(fallbackSemanticId("co_acme", SEMANTIC_ID_RULES.org)).toBe("co_acme");
- expect(fallbackSemanticId("Ch Site", SEMANTIC_ID_RULES.channel)).toBe("ch_site");
- });
-
- it("yields null for a name with no ASCII letters or digits", () => {
- expect(fallbackSemanticId("科研公司", SEMANTIC_ID_RULES.org)).toBeNull();
- expect(fallbackSemanticId(" ", SEMANTIC_ID_RULES.org)).toBeNull();
- expect(fallbackSemanticId("!!!", SEMANTIC_ID_RULES.channel)).toBeNull();
- });
-
- it("keeps the ASCII part of a mixed name", () => {
- expect(fallbackSemanticId("科研 Lab 2", SEMANTIC_ID_RULES.org)).toBe("co_lab_2");
+describe("fallbackSemanticId", () => {
+ it("folds a name to a lowercase id behind the kind's prefix", () => {
+ const cases = [
+ ["Plugin Marketplace", org, "co_plugin_marketplace"],
+ // Diacritics fold, and punctuation runs collapse to one separator.
+ [" Café--Site!! ", channel, "ch_cafe_site"],
+ // The prefix is what makes a name starting with a digit a valid id…
+ ["2026 plan", org, "co_2026_plan"],
+ ["3d", channel, "ch_3d"],
+ // …and what makes a one-character name long enough.
+ ["x", org, "co_x"],
+ // A core that already carries the prefix is not prefixed twice.
+ ["co_acme", org, "co_acme"],
+ ["Ch Site", channel, "ch_site"],
+ // The ASCII part of a mixed name is kept.
+ ["科研 Lab 2", org, "co_lab_2"],
+ ] as const;
+ for (const [name, rule, id] of cases) expect(fallbackSemanticId(name, rule), name).toBe(id);
+ });
+
+ it("yields nothing for a name with no ASCII letters or digits", () => {
+ for (const name of ["科研公司", " ", "!!!"]) {
+ expect(fallbackSemanticId(name, org), name).toBeNull();
+ }
});
it("caps the length at 64 with the prefix kept, and never ends in an underscore", () => {
- expect(fallbackSemanticId("a".repeat(70) + " tail words", SEMANTIC_ID_RULES.org)).toBe(
- `co_${"a".repeat(61)}`,
- );
+ expect(fallbackSemanticId("a".repeat(70) + " tail words", org)).toBe(`co_${"a".repeat(61)}`);
});
it("avoids taken ids with a numeric suffix, compared after prefixing", () => {
- expect(fallbackSemanticId("Site", SEMANTIC_ID_RULES.channel, ["ch_site"])).toBe("ch_site_2");
- expect(fallbackSemanticId("Site", SEMANTIC_ID_RULES.channel, ["ch_site", "ch_site_2"])).toBe(
- "ch_site_3",
- );
+ expect(fallbackSemanticId("Site", channel, ["ch_site"])).toBe("ch_site_2");
+ expect(fallbackSemanticId("Site", channel, ["ch_site", "ch_site_2"])).toBe("ch_site_3");
// The bare core is not the id, so holding it takes nothing.
- expect(fallbackSemanticId("Site", SEMANTIC_ID_RULES.channel, ["site"])).toBe("ch_site");
+ expect(fallbackSemanticId("Site", channel, ["site"])).toBe("ch_site");
+ // The suffix stays inside the length cap.
+ expect(uniqueSemanticId("b".repeat(64), ["b".repeat(64)], "_", 64)).toBe("b".repeat(62) + "_2");
});
});
describe("prefixSemanticId", () => {
it("puts the kind's prefix in front exactly once", () => {
- expect(prefixSemanticId("marketing", SEMANTIC_ID_RULES.channel)).toBe("ch_marketing");
- expect(prefixSemanticId("ch_marketing", SEMANTIC_ID_RULES.channel)).toBe("ch_marketing");
- expect(prefixSemanticId("marketing", SEMANTIC_ID_RULES.org)).toBe("co_marketing");
- });
-});
-
-describe("uniqueSemanticId", () => {
- it("keeps the suffix inside the length cap", () => {
- const base = "b".repeat(64);
- expect(uniqueSemanticId(base, [base], "_", 64)).toBe("b".repeat(62) + "_2");
+ expect(prefixSemanticId("marketing", channel)).toBe("ch_marketing");
+ expect(prefixSemanticId("ch_marketing", channel)).toBe("ch_marketing");
+ expect(prefixSemanticId("marketing", org)).toBe("co_marketing");
});
});
describe("sanitizeSuggestedId", () => {
- it("takes the first non-empty line, strips quotes and code marks, and prefixes it", () => {
- expect(sanitizeSuggestedId("\n`research_lab`\n", SEMANTIC_ID_RULES.org)).toBe(
- "co_research_lab",
- );
- expect(sanitizeSuggestedId('"Research Lab".', SEMANTIC_ID_RULES.org)).toBe("co_research_lab");
- });
-
- it("does not double a prefix the model added itself", () => {
- expect(sanitizeSuggestedId("co_research_lab", SEMANTIC_ID_RULES.org)).toBe("co_research_lab");
- });
-
- it("returns null for an answer that carries no ASCII", () => {
- expect(sanitizeSuggestedId("科研实验室", SEMANTIC_ID_RULES.org)).toBeNull();
+ it("reads the first non-empty line, strips quotes and code marks, and prefixes it once", () => {
+ expect(sanitizeSuggestedId("\n`research_lab`\n", org)).toBe("co_research_lab");
+ expect(sanitizeSuggestedId('"Research Lab".', org)).toBe("co_research_lab");
+ expect(sanitizeSuggestedId("co_research_lab", org)).toBe("co_research_lab");
+ // An answer with no ASCII names nothing.
+ expect(sanitizeSuggestedId("科研实验室", org)).toBeNull();
});
});
describe("placeholderSemanticId", () => {
const day = new Date(2026, 8, 9); // 2026-09-09, local — the stamp is the host's own date.
- it("is a valid, dated, obviously-temporary id, prefixed by kind", () => {
- expect(placeholderSemanticId(SEMANTIC_ID_RULES.org, [], day)).toBe("co_org_20260909");
- expect(placeholderSemanticId(SEMANTIC_ID_RULES.channel, [], day)).toBe("ch_channel_20260909");
- });
-
- it("pads a single-digit month and day", () => {
- expect(placeholderSemanticId(SEMANTIC_ID_RULES.org, [], new Date(2026, 0, 3))).toBe(
- "co_org_20260103",
- );
+ it("is a valid, dated, obviously-temporary id, prefixed by kind, with a padded date", () => {
+ expect(placeholderSemanticId(org, [], day)).toBe("co_org_20260909");
+ expect(placeholderSemanticId(channel, [], day)).toBe("ch_channel_20260909");
+ expect(placeholderSemanticId(org, [], new Date(2026, 0, 3))).toBe("co_org_20260103");
});
it("avoids the ids already taken, so pressing the button twice gives two ids", () => {
- expect(placeholderSemanticId(SEMANTIC_ID_RULES.org, ["co_org_20260909"], day)).toBe(
- "co_org_20260909_2",
+ expect(placeholderSemanticId(org, ["co_org_20260909"], day)).toBe("co_org_20260909_2");
+ expect(placeholderSemanticId(org, ["co_org_20260909", "co_org_20260909_2"], day)).toBe(
+ "co_org_20260909_3",
);
- expect(
- placeholderSemanticId(SEMANTIC_ID_RULES.org, ["co_org_20260909", "co_org_20260909_2"], day),
- ).toBe("co_org_20260909_3");
});
});
@@ -127,7 +117,6 @@ describe("the kind table", () => {
expect(fallbackSemanticId("2026 Plan", SEMANTIC_ID_RULES.project)).toBe("project_2026_plan");
expect(fallbackSemanticId("报告写手", SEMANTIC_ID_RULES.agent)).toBeNull();
for (const kind of ["project", "agent"] as const) {
- expect(SEMANTIC_ID_RULES[kind].prefix).toBe("");
expect(SEMANTIC_ID_RULES[kind].accepts("report_writer")).toBe(true);
expect(SEMANTIC_ID_RULES[kind].accepts("2026_plan")).toBe(false);
}
diff --git a/packages/server/test/semantic-ids.test.ts b/packages/server/test/semantic-ids.test.ts
index 7a306a93..44a917a9 100644
--- a/packages/server/test/semantic-ids.test.ts
+++ b/packages/server/test/semantic-ids.test.ts
@@ -1,15 +1,22 @@
/**
- * Integration tests for semantic ids: Project / Agent id
- * is chosen by the creator — must start with a lowercase letter and contain
- * only lowercase letters, digits, and underscores; checked for collisions
- * against both the DB and the directory (including built-in reserved ids),
- * returning 409 when taken.
- * The hyphen is a reserved separator: a non-admin's Project id is forced to
- * "<username>-<suffix>"; the admin's Project id contains no hyphen.
+ * Semantic ids through the create routes: a Project or Agent id is chosen by its creator —
+ * a lowercase letter first, then lowercase letters, digits and underscores — and checked for
+ * collisions against the DB and the directory (built-in reserved ids included). The hyphen is
+ * a reserved separator: a non-admin's Project id is "<username>-<suffix>", an admin's has none.
+ *
+ * - An admin creates a Project under a valid id (its display name defaulting to the id) and is
+ * refused an invalid one; a DB-taken, directory-only-taken or reserved id is a 409.
+ * - A non-admin's Project id must carry their own prefix and a valid suffix.
+ * - A Project creation that fails midway rolls back its row and directory, so the same id can
+ * be retried; an Agent creation that fails midway rolls back its directory the same way.
+ * - An Agent id is validated the same way, initializes the Agent, collides within its Project
+ * (built-ins included) but not across Projects, and its display name is free-form.
+ *
+ * Every case creates distinct ids, so one app serves them all.
*/
import fs from "node:fs/promises";
import path from "node:path";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import type { AgentCreateResponse, ProjectCreateResponse } from "../src/api/types.js";
import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
@@ -22,16 +29,16 @@ describe("semantic ids", () => {
let admin: ReturnType<typeof apiClient>;
let api: ReturnType<typeof apiClient>;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
api = apiClient(t.app, (await provisionUser(t.app, "ida")).cookie);
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
- it("create Project (admin: no prefix, no hyphen): invalid ids 400; a valid id lands a directory; display name defaults to the id", async () => {
+ it("gives an admin's Project a valid bare id, its name defaulting to the id, and refuses an invalid one", async () => {
for (const bad of BAD_IDS) {
const res = await admin.post("/api/projects", { projectId: bad, name: "x" });
expect(res.status, `projectId=${bad}`).toBe(400);
@@ -45,7 +52,7 @@ describe("semantic ids", () => {
await expect(fs.access(path.join(t.root, "my_proj_2"))).resolves.toBeUndefined();
});
- it("create Project: DB-taken, directory-only-taken, and reserved ids are all 409", async () => {
+ it("refuses a DB-taken, directory-only or reserved Project id as taken", async () => {
expect((await admin.post("/api/projects", { projectId: "taken", name: "a" })).status).toBe(201);
expect((await admin.post("/api/projects", { projectId: "taken", name: "b" })).status).toBe(409);
// A directory that exists but isn't tracked (e.g. created by the CLI) is also considered taken.
@@ -59,7 +66,7 @@ describe("semantic ids", () => {
).toBe(409);
});
- it("non-admin Project creation: id forced to <username>-<suffix>; the suffix allows only lowercase letters, digits, underscores", async () => {
+ it("makes a non-admin's Project id carry their own prefix and a valid suffix", async () => {
// No prefix / prefix only / suffix with a hyphen or an invalid character: 400.
for (const bad of ["blog", "ida", "ida-", "idablog", "proj_ida", "ida-sub-x", "ida-Bad"]) {
const res = await api.post("/api/projects", { projectId: bad, name: "x" });
@@ -73,46 +80,51 @@ describe("semantic ids", () => {
await expect(fs.access(path.join(t.root, "ida-blog"))).resolves.toBeUndefined();
});
- it("mid-flight Project creation failure: the DB row and directory roll back; retrying the same id succeeds", async () => {
- // Inject a config write failure (handleError logs the stack trace: silence it so it doesn't clutter output).
- const spy = vi.spyOn(console, "error").mockImplementation(() => {});
- const original = t.deps.projectConfigService.writeInitialConfig.bind(
- t.deps.projectConfigService,
- );
+ it("rolls back a Project creation that fails midway, so the same id can be retried", async () => {
+ // Inject a config write failure (handleError logs the stack trace: silence it so it doesn't
+ // clutter output). The app is shared, so the real writer goes back whatever happens.
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const original = t.deps.projectConfigService.writeInitialConfig;
t.deps.projectConfigService.writeInitialConfig = async () => {
throw new Error("config write blew up");
};
- expect((await admin.post("/api/projects", { projectId: "flaky", name: "x" })).status).toBe(500);
- spy.mockRestore();
+ try {
+ expect((await admin.post("/api/projects", { projectId: "flaky", name: "x" })).status).toBe(
+ 500,
+ );
+ } finally {
+ t.deps.projectConfigService.writeInitialConfig = original;
+ }
// No leftovers: neither the directory nor the DB row exist, so the id isn't held by an orphaned directory.
await expect(fs.access(path.join(t.root, "flaky"))).rejects.toThrow();
expect(
t.deps.db.prepare("SELECT 1 AS x FROM projects WHERE project_id = ?").get("flaky"),
).toBeUndefined();
- t.deps.projectConfigService.writeInitialConfig = original;
expect((await admin.post("/api/projects", { projectId: "flaky", name: "x" })).status).toBe(201);
});
- it("mid-flight Agent creation failure: the directory rolls back; retrying the same id succeeds", async () => {
- const spy = vi.spyOn(console, "error").mockImplementation(() => {});
- const original = t.deps.agentConfigService.updateConfig.bind(t.deps.agentConfigService);
+ it("rolls back an Agent creation that fails midway, so the same id can be retried", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const original = t.deps.agentConfigService.updateConfig;
t.deps.agentConfigService.updateConfig = async () => {
throw new Error("config write blew up");
};
- expect(
- (await api.post("/api/projects/ida-default_project/agents", { agentId: "flaky" })).status,
- ).toBe(500);
- spy.mockRestore();
+ try {
+ expect(
+ (await api.post("/api/projects/ida-default_project/agents", { agentId: "flaky" })).status,
+ ).toBe(500);
+ } finally {
+ t.deps.agentConfigService.updateConfig = original;
+ }
await expect(
fs.access(path.join(t.root, "ida-default_project", "agents", "flaky")),
).rejects.toThrow();
- t.deps.agentConfigService.updateConfig = original;
expect(
(await api.post("/api/projects/ida-default_project/agents", { agentId: "flaky" })).status,
).toBe(201);
});
- it("create Agent: invalid ids 400; a valid id initializes; duplicates and built-in ids 409; no conflicts across Projects", async () => {
+ it("validates an Agent id, initializes the Agent, and checks collisions within its Project only", async () => {
for (const bad of BAD_IDS) {
const res = await api.post("/api/projects/ida-default_project/agents", {
agentId: bad,
diff --git a/packages/server/test/update-job.test.ts b/packages/server/test/update-job.test.ts
index b6989274..e1b8126e 100644
--- a/packages/server/test/update-job.test.ts
+++ b/packages/server/test/update-job.test.ts
@@ -1,6 +1,18 @@
/**
- * update-job.ts unit tests: the progress read off the CLI's output, and the job's lifecycle
- * over a scripted runner (nothing is ever spawned here).
+ * The update job behind POST /api/version/update (services/update-job.ts): the progress it
+ * reads off the CLI's output, its lifecycle over a scripted runner (nothing is ever spawned
+ * here), and how a finished run is classified.
+ *
+ * - Progress stays "resolving" with no percentage until the installer announces the download;
+ * then it follows curl's bar (freshest value, clamped and rounded), and turns "installing"
+ * once the bundle verifies, ignoring later percentages.
+ * - A job starts idle, runs the CLI entry once however often it is started while running,
+ * tracks progress, and ends updated with a restart needed.
+ * - A refusal ends unsupported; a failure, a timeout and a spawn error end failed, and a failed
+ * run can be started again.
+ * - With no CLI to run, the job ends at once as unsupported.
+ * - The CLI's own refusal copy reads as unsupported, and any other clean exit — "already on the
+ * latest version" included — as updated with a restart needed.
*/
import { describe, expect, it } from "vitest";
import { wire } from "@prismshadow/penguin-core/kernel";
@@ -167,10 +179,35 @@ describe("UpdateJobService", () => {
});
expect(script.entries).toEqual([]);
});
+});
- it("classifyUpdateRun keeps its three verdicts", () => {
- expect(classifyUpdateRun(1, "x").status).toBe("failed");
- expect(classifyUpdateRun(0, "does not run on Windows").status).toBe("unsupported");
- expect(classifyUpdateRun(0, "installed").needsRestart).toBe(true);
+describe("classifyUpdateRun", () => {
+ it("reads the CLI's refusal copy as unsupported, and any other clean exit as updated", () => {
+ // Literal CLI copy (packages/cli/src/i18n.ts, the update refusals): the classifier matches
+ // fragments of these exact strings, so a reworded refusal must fail here.
+ for (const refusal of [
+ "This penguin runs from a source checkout, so there is nothing to download — update it with `git pull` and rebuild (`pnpm install && pnpm -r build`).",
+ "Cannot tell how this penguin was installed (running from /opt/penguin/cli.js), so it will not be replaced. Re-install with the official installer, or upgrade with the package manager you used.",
+ "This is a global install under /usr/lib/node_modules, but the package manager that owns it could not be identified. Upgrade it yourself with that manager, e.g. `npm install -g @prismshadow/[email protected]`.",
+ "The official installer is a POSIX shell script and does not run on Windows. Re-install from the GitHub Releases page, or use a global npm install instead.",
+ "On Windows, penguin cannot run your package manager for you: Node will not execute an npm/pnpm/yarn `.cmd` shim without a shell.",
+ ]) {
+ expect(classifyUpdateRun(0, refusal), refusal).toMatchObject({
+ status: "unsupported",
+ needsRestart: false,
+ });
+ }
+ // "Already on the latest version" means the INSTALL is current: only this older, in-memory
+ // process is missing a restart.
+ for (const output of [
+ "Upgrade 0.1.2 -> 0.1.3\nPenguinHarness 0.1.3 installed. Run `penguin --version` in a new shell to confirm.",
+ "Already on the latest version (0.1.3); nothing to do.",
+ ]) {
+ expect(classifyUpdateRun(0, output)).toEqual({
+ status: "updated",
+ output,
+ needsRestart: true,
+ });
+ }
});
});
diff --git a/packages/server/test/usage.test.ts b/packages/server/test/usage.test.ts
index b068d886..cdda58c0 100644
--- a/packages/server/test/usage.test.ts
+++ b/packages/server/test/usage.test.ts
@@ -1,10 +1,30 @@
/**
- * Unit tests for usage persistence and statistics: origin→model attribution,
- * summary buckets and group aggregation, cost computed **on the fly** (only
- * Tokens are persisted; cost is priced against current pricing at query time,
- * no pricing → NULL + hasUncosted; a later price update is reflected
- * immediately), and the status → success-rate pipeline that rides on the time
- * series (aborted doesn't count as a model failure).
+ * Usage persistence and statistics behind the cost center. Only Tokens are persisted; cost is
+ * priced against the current pricing at query time.
+ *
+ * Recording:
+ * - A token_usage message is one row of Tokens (never a cost); anything else writes nothing.
+ * - A sub-session's usage is attributed to its own model through its session_meta, and falls
+ * back to the main Session's model when that mapping is missing or was evicted past its cap.
+ *
+ * Querying:
+ * - A scheduled model is priced per record by the tier its request ran in, each seller by its
+ * own windows, so a finished period's total never moves with the clock.
+ * - The summary cards cover today, the last 7 days and everything; a model without pricing is
+ * flagged, and a price added later prices past records at once; only the references the
+ * response prices are looked up.
+ * - Groups aggregate by date (newest first), Agent, model and Session, folded across models and
+ * narrowed by Agent and range.
+ * - Success counts completed requests over every non-aborted one: a user's Stop is not a model
+ * failure.
+ * - Model totals sum every record a model ever wrote, per paired reference, per Project.
+ * - Series are zero-filled buckets by minute, hour (local clock), day, ISO week or month, with
+ * per-Agent and per-model series aligned to them; a minute series needs a timestamp window,
+ * the range defaults to 30 days, and an oversized series is refused.
+ * - Bucket enumeration stays unique and ascending across DST transitions.
+ * - The error table filters before it pages, so a later page never slides onto excluded rows,
+ * and pages through rows rather than records once a day's repeats fold (paging itself is
+ * covered through its route in errors.test.ts).
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { sessionMeta, tokenUsage, withOrigin } from "@prismshadow/penguin-core";
@@ -741,32 +761,6 @@ describe("usage-service.queryErrors (error table paging)", () => {
});
afterEach(() => db.close());
- it("pages newest-first and reports the filtered total, so the caller knows where the end is", () => {
- const first = service.queryErrors("p1", { offset: 0, limit: 20 });
- expect(first.total).toBe(25);
- // Every record here is a different error, so each is its own row.
- expect(first.rows).toBe(25);
- expect(first.items).toHaveLength(20);
- expect(first.items[0]!.code).toBe("code_24"); // newest
- const second = service.queryErrors("p1", { offset: 20, limit: 20 });
- expect(second.total).toBe(25);
- // The tail is the five oldest, still descending, with no overlap against page one.
- expect(second.items.map((e) => e.code)).toEqual([
- "code_4",
- "code_3",
- "code_2",
- "code_1",
- "code_0",
- ]);
- });
-
- it("past the end is empty rather than an error, and total stays the full count", () => {
- const page = service.queryErrors("p1", { offset: 100, limit: 20 });
- expect(page.items).toEqual([]);
- expect(page.total).toBe(25);
- expect(page.rows).toBe(25);
- });
-
it("pages through rows, not records, once a day's repeats fold", () => {
// Ten more of one error on the same day: one more row, ten more records.
for (let i = 0; i < 10; i += 1) {
diff --git a/packages/server/test/validate.test.ts b/packages/server/test/validate.test.ts
index 071cee08..cd31c54e 100644
--- a/packages/server/test/validate.test.ts
+++ b/packages/server/test/validate.test.ts
@@ -1,8 +1,18 @@
/**
- * Request-validation helper unit tests: positiveIntParam and the two paging helpers reject
- * trailing garbage, optionalDateParam rejects impossible calendar dates (shape-only checks
- * let these through), and optionalNumber enforces the agent runtime-parameter rule
- * (integer, > 0 or exactly -1) used for max_turns and friends.
+ * The request-validation helpers every route parses its parameters with (http/validate.ts).
+ *
+ * - A positive-integer path parameter parses a plain positive integer and refuses everything
+ * else, trailing garbage included (parseInt would accept it), and an index past the safe
+ * integers.
+ * - An optional date is absent for missing or empty input, accepts a real calendar date (a
+ * leap day included), and refuses a malformed shape or an impossible date the shape check
+ * alone would let through.
+ * - A runtime parameter (max_turns and friends) is a positive integer or the -1 "unlimited"
+ * sentinel; an absent key is left untouched; anything else is refused.
+ * - Paging defaults to offset 0 / limit 200, parses plain integers, and refuses trailing
+ * garbage, exponents and a limit outside 1..1000.
+ * - Optional paging is absent when neither parameter is given, defaults a missing offset, and
+ * refuses an offset without a limit and the same malformed values.
*/
import { describe, expect, it } from "vitest";
import type { Context } from "hono";
@@ -20,56 +30,48 @@ function ctxWithParam(name: string, value: string | undefined): Context {
return { req: { param: (n: string) => (n === name ? value : undefined) } } as unknown as Context;
}
+/** Minimal Context stub exposing query parameters. */
+function ctxWithQuery(query: Record<string, string>): Context {
+ return { req: { query: (n: string) => query[n] } } as unknown as Context;
+}
+
describe("positiveIntParam", () => {
it("parses a plain positive integer", () => {
expect(positiveIntParam(ctxWithParam("idx", "12"), "idx")).toBe(12);
});
- it("rejects trailing garbage (parseInt would accept it)", () => {
- expect(() => positiveIntParam(ctxWithParam("idx", "12abc"), "idx")).toThrow(HttpError);
- });
-
- it("rejects a leading sign, whitespace, and non-digits", () => {
- for (const bad of ["+1", " 1", "1 ", "1.5", "0x10"]) {
- expect(() => positiveIntParam(ctxWithParam("idx", bad), "idx")).toThrow(HttpError);
+ it("refuses anything but a plain positive integer", () => {
+ // "12abc" is what parseInt would accept; "9"×20 parses to an imprecise 1e20 that
+ // isSafeInteger rejects and isInteger would not; the empty and missing values are the
+ // ones pathParam normally stops first.
+ for (const bad of ["12abc", "+1", " 1", "1 ", "1.5", "0x10", "0", "9".repeat(20), ""]) {
+ expect(() => positiveIntParam(ctxWithParam("idx", bad), "idx"), bad).toThrow(HttpError);
}
- });
-
- it("rejects zero (must be >= 1)", () => {
- expect(() => positiveIntParam(ctxWithParam("idx", "0"), "idx")).toThrow(HttpError);
- });
-
- it("rejects overlong indices that would parse to an imprecise float", () => {
- // "99999999999999999999" parses to 1e20 — isSafeInteger rejects it, isInteger would not.
- expect(() => positiveIntParam(ctxWithParam("idx", "9".repeat(20)), "idx")).toThrow(HttpError);
- });
-
- it("an empty/missing path param is rejected upstream by pathParam (404), not the digits guard", () => {
- expect(() => positiveIntParam(ctxWithParam("idx", ""), "idx")).toThrow(HttpError);
expect(() => positiveIntParam(ctxWithParam("idx", undefined), "idx")).toThrow(HttpError);
});
});
describe("optionalDateParam", () => {
- it("returns undefined for missing or empty input", () => {
+ it("is absent for missing or empty input, and accepts a real calendar date", () => {
expect(optionalDateParam(undefined, "from")).toBeUndefined();
expect(optionalDateParam("", "from")).toBeUndefined();
- });
-
- it("accepts a real calendar date", () => {
expect(optionalDateParam("2026-07-20", "from")).toBe("2026-07-20");
expect(optionalDateParam("2024-02-29", "from")).toBe("2024-02-29"); // leap day
});
- it("rejects malformed shapes", () => {
- for (const bad of ["2026/07/20", "20260720", "2026-7-20", "not-a-date"]) {
- expect(() => optionalDateParam(bad, "from")).toThrow(HttpError);
- }
- });
-
- it("rejects impossible dates that pass the shape check", () => {
- for (const bad of ["2026-13-40", "2026-02-30", "2026-00-10", "2026-01-00", "2025-02-29"]) {
- expect(() => optionalDateParam(bad, "from")).toThrow(HttpError);
+ it("refuses a malformed shape, and an impossible date that passes the shape check", () => {
+ for (const bad of [
+ "2026/07/20",
+ "20260720",
+ "2026-7-20",
+ "not-a-date",
+ "2026-13-40",
+ "2026-02-30",
+ "2026-00-10",
+ "2026-01-00",
+ "2025-02-29",
+ ]) {
+ expect(() => optionalDateParam(bad, "from"), bad).toThrow(HttpError);
}
});
});
@@ -79,79 +81,56 @@ describe("optionalNumber with the agent runtime-parameter rule (integer, > 0 or
// -1 is the documented "unlimited" sentinel; every other non-positive value is rejected.
const rule = { integer: true, positiveOrMinusOne: true } as const;
- it("accepts positive integers and the -1 unlimited sentinel", () => {
+ it("accepts positive integers and the -1 sentinel, and leaves an absent key untouched", () => {
expect(optionalNumber({ maxTurns: 1 }, "maxTurns", rule)).toBe(1);
expect(optionalNumber({ maxTurns: 100 }, "maxTurns", rule)).toBe(100);
expect(optionalNumber({ maxTurns: -1 }, "maxTurns", rule)).toBe(-1);
- });
-
- it("returns undefined when the key is absent (PUT subsets leave it untouched)", () => {
expect(optionalNumber({}, "maxTurns", rule)).toBeUndefined();
});
- it("rejects zero and negatives other than -1", () => {
- for (const bad of [0, -2, -100]) {
- expect(() => optionalNumber({ maxTurns: bad }, "maxTurns", rule)).toThrow(HttpError);
- }
- });
-
- it("rejects non-integers and non-finite or non-number values", () => {
- for (const bad of [1.5, -1.5, Number.NaN, Number.POSITIVE_INFINITY, "100", true, null]) {
- expect(() => optionalNumber({ maxTurns: bad }, "maxTurns", rule)).toThrow(HttpError);
+ it("refuses zero, other negatives, fractions and anything that is not a finite number", () => {
+ for (const bad of [0, -2, -100, 1.5, -1.5, Number.NaN, Number.POSITIVE_INFINITY, "100", true]) {
+ expect(() => optionalNumber({ maxTurns: bad }, "maxTurns", rule), String(bad)).toThrow(
+ HttpError,
+ );
}
+ expect(() => optionalNumber({ maxTurns: null }, "maxTurns", rule)).toThrow(HttpError);
});
});
-/** Minimal Context stub exposing query parameters. */
-function ctxWithQuery(query: Record<string, string>): Context {
- return { req: { query: (n: string) => query[n] } } as unknown as Context;
-}
-
describe("paginationQuery", () => {
- it("defaults to offset 0 / limit 200", () => {
+ it("defaults to offset 0 / limit 200 and parses plain integers up to 1000", () => {
expect(paginationQuery(ctxWithQuery({}))).toEqual({ offset: 0, limit: 200 });
- });
-
- it("parses plain integers", () => {
expect(paginationQuery(ctxWithQuery({ offset: "40", limit: "20" }))).toEqual({
offset: 40,
limit: 20,
});
+ expect(paginationQuery(ctxWithQuery({ limit: "1000" })).limit).toBe(1000);
});
- it("rejects trailing garbage and exponent notation (parseInt would accept both)", () => {
+ it("refuses trailing garbage, exponents and a limit outside the range", () => {
// "200abc" parsed to 200 and "1e3" to 1, both landing inside the range check.
for (const bad of ["200abc", "1e3", "0x10", " 20", "20 ", "1.5", "+20", "-1"]) {
- expect(() => paginationQuery(ctxWithQuery({ limit: bad }))).toThrow(HttpError);
- expect(() => paginationQuery(ctxWithQuery({ offset: bad }))).toThrow(HttpError);
+ expect(() => paginationQuery(ctxWithQuery({ limit: bad })), bad).toThrow(HttpError);
+ expect(() => paginationQuery(ctxWithQuery({ offset: bad })), bad).toThrow(HttpError);
}
- });
-
- it("enforces the limit range", () => {
for (const bad of ["0", "1001"]) {
- expect(() => paginationQuery(ctxWithQuery({ limit: bad }))).toThrow(HttpError);
+ expect(() => paginationQuery(ctxWithQuery({ limit: bad })), bad).toThrow(HttpError);
}
- expect(paginationQuery(ctxWithQuery({ limit: "1000" })).limit).toBe(1000);
});
});
describe("optionalPagingQuery", () => {
- it("returns null when neither param is present", () => {
+ it("is absent without either parameter, and defaults a missing offset", () => {
expect(optionalPagingQuery(ctxWithQuery({}))).toBeNull();
- });
-
- it("requires limit when only offset is given", () => {
- expect(() => optionalPagingQuery(ctxWithQuery({ offset: "10" }))).toThrow(HttpError);
- });
-
- it("defaults offset to 0 when only limit is given", () => {
expect(optionalPagingQuery(ctxWithQuery({ limit: "50" }))).toEqual({ offset: 0, limit: 50 });
});
- it("rejects trailing garbage and exponent notation (parseInt would accept both)", () => {
+ it("refuses an offset without a limit, and malformed values in either", () => {
+ expect(() => optionalPagingQuery(ctxWithQuery({ offset: "10" }))).toThrow(HttpError);
for (const bad of ["50abc", "1e3", "0x10", "1.5", "-1"]) {
- expect(() => optionalPagingQuery(ctxWithQuery({ limit: bad }))).toThrow(HttpError);
- expect(() => optionalPagingQuery(ctxWithQuery({ limit: "50", offset: bad }))).toThrow(
+ expect(() => optionalPagingQuery(ctxWithQuery({ limit: bad })), bad).toThrow(HttpError);
+ expect(() => optionalPagingQuery(ctxWithQuery({ limit: "50", offset: bad })), bad).toThrow(
HttpError,
);
}
diff --git a/packages/server/test/version.test.ts b/packages/server/test/version.test.ts
index d7b258c3..1f49b61c 100644
--- a/packages/server/test/version.test.ts
+++ b/packages/server/test/version.test.ts
@@ -1,10 +1,21 @@
/**
- * Version routes and update-check service tests: response shapes, the fail-soft
- * contract of /api/version/update-check (always 200, error field instead of 5xx),
- * cache TTLs with an injected clock, the PENGUIN_UPDATE_CHECK=off opt-out, and the
- * admin gate of POST /api/version/update. Nothing here touches the network or spawns
- * a process: fetch is stubbed, and the update run is exercised only through its pure
- * classifier and the "not launched via the CLI" early exit.
+ * The version routes and the update check behind the About page.
+ *
+ * - GET /api/version needs a session and serves exactly the report `penguin version --json`
+ * prints; a root with nothing pushed reports no harness, and a pushed one reports its store.
+ * - The update check reports a newer release with its URL and date; an unreachable endpoint
+ * is still a 200, carrying `error: network` instead of a 5xx.
+ * - A plain check is answered from the cache; `?force=1` (the manual check) bypasses it and
+ * the fresh outcome is what later plain checks see.
+ * - A rate-limit answer reads as rate_limited, any other bad status or body as bad_response;
+ * a latest release that is not newer is no update.
+ * - PENGUIN_UPDATE_CHECK=off answers disabled and never dials out, forced or not.
+ * - A success is cached for an hour and a failure for ten minutes.
+ * - The update job is admin-only; before any run it is idle, and a server not launched through
+ * the CLI finishes it at once as unsupported, readable afterwards.
+ * - A restart is admin-only and refused when nothing supervises the process.
+ *
+ * Nothing here touches the network or spawns a process: the release lookup is the fetch fake.
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import fs from "node:fs/promises";
@@ -23,24 +34,12 @@ import {
SUCCESS_TTL_MS,
UpdateCheckService,
} from "../src/services/update-check-service.js";
-import { classifyUpdateRun } from "../src/http/routes/version.js";
+import { fakeFetch } from "./fixtures/fetch.js";
+import type { FetchScript } from "./fixtures/fetch.js";
import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
import { wire } from "@prismshadow/penguin-core/kernel";
-/** Counting fetch stub; the handler decides the outcome per call. */
-function makeFetch(handler: () => Response | Promise<Response>): {
- impl: typeof fetch;
- state: { calls: number };
-} {
- const state = { calls: 0 };
- const impl: typeof fetch = async () => {
- state.calls += 1;
- return handler();
- };
- return { impl, state };
-}
-
function releaseResponse(tag: string): Response {
return new Response(
JSON.stringify({
@@ -52,6 +51,21 @@ function releaseResponse(tag: string): Response {
);
}
+/** An update-check service over the fetch fake; `calls` counts the lookups that reached it. */
+function updateCheck(
+ script: FetchScript,
+ env: Record<string, string> = {},
+ now: () => Date = () => new Date(),
+) {
+ const releases = fakeFetch(script);
+ const service = wire(UpdateCheckService, {
+ http: { fetch: releases.fetch },
+ env,
+ clock: { now },
+ });
+ return { service, calls: () => releases.calls.length };
+}
+
describe("GET /api/version", () => {
let t: TestApp;
beforeEach(async () => {
@@ -118,14 +132,7 @@ describe("GET /api/version/update-check", () => {
});
it("reports a newer release with its URL and publish date", async () => {
- const { impl } = makeFetch(() => releaseResponse("v99.0.0"));
- t = await createTestApp({
- updateCheck: wire(UpdateCheckService, {
- http: { fetch: impl },
- env: {},
- clock: { now: () => new Date() },
- }),
- });
+ t = await createTestApp({ updateCheck: updateCheck(() => releaseResponse("v99.0.0")).service });
const admin = await loginAdmin(t.app);
const res = await apiClient(t.app, admin.cookie).get("/api/version/update-check");
expect(res.status).toBe(200);
@@ -141,17 +148,11 @@ describe("GET /api/version/update-check", () => {
expect(body.disabled).toBeUndefined();
});
- it("fail-soft: an unreachable endpoint is HTTP 200 with error=network, not a 5xx", async () => {
- const { impl } = makeFetch(() => {
+ it("answers an unreachable endpoint with a 200 carrying error=network, not a 5xx", async () => {
+ const { service } = updateCheck(() => {
throw new Error("getaddrinfo ENOTFOUND api.github.com");
});
- t = await createTestApp({
- updateCheck: wire(UpdateCheckService, {
- http: { fetch: impl },
- env: {},
- clock: { now: () => new Date() },
- }),
- });
+ t = await createTestApp({ updateCheck: service });
const admin = await loginAdmin(t.app);
const res = await apiClient(t.app, admin.cookie).get("/api/version/update-check");
expect(res.status).toBe(200);
@@ -162,32 +163,32 @@ describe("GET /api/version/update-check", () => {
expect(body.releaseUrl).toBeNull();
});
- it("?force=1 (the manual check) reaches the service as a cache bypass", async () => {
- const { impl, state } = makeFetch(() => releaseResponse("v99.0.0"));
- t = await createTestApp({
- updateCheck: wire(UpdateCheckService, {
- http: { fetch: impl },
- env: {},
- clock: { now: () => new Date() },
- }),
- });
+ it("answers a plain check from the cache, and ?force=1 refetches and recaches", async () => {
+ let tag = "v99.0.0";
+ const check = updateCheck(() => releaseResponse(tag));
+ t = await createTestApp({ updateCheck: check.service });
const admin = await loginAdmin(t.app);
const client = apiClient(t.app, admin.cookie);
+ const latest = async (url: string) =>
+ ((await (await client.get(url)).json()) as UpdateCheckResponse).latestVersion;
// Warm the cache, then confirm a plain GET serves from it.
- expect((await client.get("/api/version/update-check")).status).toBe(200);
- expect((await client.get("/api/version/update-check")).status).toBe(200);
- expect(state.calls).toBe(1);
+ expect(await latest("/api/version/update-check")).toBe("99.0.0");
+ expect(await latest("/api/version/update-check")).toBe("99.0.0");
+ expect(check.calls()).toBe(1);
- const forced = await client.get("/api/version/update-check?force=1");
- expect(forced.status).toBe(200);
- expect(((await forced.json()) as UpdateCheckResponse).latestVersion).toBe("99.0.0");
- expect(state.calls).toBe(2);
+ // The manual check refetches despite the fresh cache…
+ tag = "v100.0.0";
+ expect(await latest("/api/version/update-check?force=1")).toBe("100.0.0");
+ expect(check.calls()).toBe(2);
+ // …and stores what it found: the next plain check reuses it without a call.
+ expect(await latest("/api/version/update-check")).toBe("100.0.0");
+ expect(check.calls()).toBe(2);
});
});
describe("UpdateCheckService", () => {
- it("maps 403/429 to rate_limited and other bad statuses/bodies to bad_response", async () => {
+ it("reads 403/429 as rate_limited and any other bad status or body as bad_response", async () => {
for (const [make, expected] of [
[() => new Response("limited", { status: 403 }), "rate_limited"],
[() => new Response("limited", { status: 429 }), "rate_limited"],
@@ -195,122 +196,72 @@ describe("UpdateCheckService", () => {
[() => new Response("not json", { status: 200 }), "bad_response"],
[() => new Response(JSON.stringify({ name: "no tag" }), { status: 200 }), "bad_response"],
] as const) {
- const service = wire(UpdateCheckService, {
- http: { fetch: makeFetch(make).impl },
- env: {},
- clock: { now: () => new Date() },
- });
- const result = await service.check();
+ const result = await updateCheck(make).service.check();
expect(result.error).toBe(expected);
expect(result.updateAvailable).toBe(false);
expect(result.latestVersion).toBeNull();
}
});
- it("updateAvailable is false when the latest release is not newer", async () => {
- const { impl } = makeFetch(() => releaseResponse(`v${VERSION}`));
- const service = wire(UpdateCheckService, {
- http: { fetch: impl },
- env: {},
- clock: { now: () => new Date() },
- });
- const result = await service.check();
+ it("reports no update when the latest release is not newer", async () => {
+ const result = await updateCheck(() => releaseResponse(`v${VERSION}`)).service.check();
expect(result.error).toBeUndefined();
expect(result.latestVersion).toBe(VERSION);
expect(result.updateAvailable).toBe(false);
});
- it("PENGUIN_UPDATE_CHECK=off disables the lookup without any network call", async () => {
- const { impl, state } = makeFetch(() => releaseResponse("v99.0.0"));
- const service = wire(UpdateCheckService, {
- http: { fetch: impl },
- env: { PENGUIN_UPDATE_CHECK: "off" },
- clock: { now: () => new Date() },
- });
- const result = await service.check();
- expect(result.disabled).toBe(true);
- expect(result.updateAvailable).toBe(false);
- expect(result.latestVersion).toBeNull();
- expect(state.calls).toBe(0);
+ it("never dials out under PENGUIN_UPDATE_CHECK=off, forced or not", async () => {
+ const check = updateCheck(() => releaseResponse("v99.0.0"), { PENGUIN_UPDATE_CHECK: "off" });
+ for (const force of [false, true]) {
+ const result = await check.service.check(force);
+ expect(result.disabled).toBe(true);
+ expect(result.updateAvailable).toBe(false);
+ expect(result.latestVersion).toBeNull();
+ }
+ expect(check.calls()).toBe(0);
});
it("caches a success for an hour and a failure for ten minutes", async () => {
let nowMs = 1_000_000_000;
let fail = false;
- const { impl, state } = makeFetch(() => {
- if (fail) throw new Error("down");
- return releaseResponse("v99.0.0");
- });
- const service = wire(UpdateCheckService, {
- http: { fetch: impl },
- env: {},
- clock: { now: () => new Date(nowMs) },
- });
+ const check = updateCheck(
+ () => {
+ if (fail) throw new Error("down");
+ return releaseResponse("v99.0.0");
+ },
+ {},
+ () => new Date(nowMs),
+ );
+ const service = check.service;
const first = await service.check();
expect(first.latestVersion).toBe("99.0.0");
- expect(state.calls).toBe(1);
+ expect(check.calls()).toBe(1);
// Within the success TTL: served from cache, original checkedAt preserved.
nowMs += SUCCESS_TTL_MS - 1;
const cached = await service.check();
- expect(state.calls).toBe(1);
+ expect(check.calls()).toBe(1);
expect(cached.checkedAt).toBe(first.checkedAt);
// Past the success TTL: refetched; the failure is itself cached, but only briefly.
nowMs += 2;
fail = true;
const failed = await service.check();
- expect(state.calls).toBe(2);
+ expect(check.calls()).toBe(2);
expect(failed.error).toBe("network");
nowMs += FAILURE_TTL_MS - 1;
expect((await service.check()).error).toBe("network");
- expect(state.calls).toBe(2);
+ expect(check.calls()).toBe(2);
nowMs += 2;
fail = false;
const healed = await service.check();
- expect(state.calls).toBe(3);
+ expect(check.calls()).toBe(3);
expect(healed.error).toBeUndefined();
expect(healed.latestVersion).toBe("99.0.0");
});
-
- it("force bypasses a warm cache and recaches the fresh outcome", async () => {
- let tag = "v99.0.0";
- const { impl, state } = makeFetch(() => releaseResponse(tag));
- const service = wire(UpdateCheckService, {
- http: { fetch: impl },
- env: {},
- clock: { now: () => new Date() },
- });
-
- // Warm the cache; a passive check is then served from it.
- expect((await service.check()).latestVersion).toBe("99.0.0");
- expect((await service.check()).latestVersion).toBe("99.0.0");
- expect(state.calls).toBe(1);
-
- // A forced check refetches despite the fresh cache…
- tag = "v100.0.0";
- expect((await service.check(true)).latestVersion).toBe("100.0.0");
- expect(state.calls).toBe(2);
-
- // …and stores the outcome: the next passive check reuses it without a call.
- expect((await service.check()).latestVersion).toBe("100.0.0");
- expect(state.calls).toBe(2);
- });
-
- it("force never dials out when PENGUIN_UPDATE_CHECK=off (the opt-out stays authoritative)", async () => {
- const { impl, state } = makeFetch(() => releaseResponse("v99.0.0"));
- const service = wire(UpdateCheckService, {
- http: { fetch: impl },
- env: { PENGUIN_UPDATE_CHECK: "off" },
- clock: { now: () => new Date() },
- });
- const result = await service.check(true);
- expect(result.disabled).toBe(true);
- expect(state.calls).toBe(0);
- });
});
describe("POST /api/version/update", () => {
@@ -327,10 +278,18 @@ describe("POST /api/version/update", () => {
await t.cleanup();
});
- it("is admin-only", async () => {
- const user = await provisionUser(t.app, "regular_user");
- const res = await apiClient(t.app, user.cookie).post("/api/version/update", {});
- expect(res.status).toBe(403);
+ it("is admin-only both ways, and idle before any run", async () => {
+ const user = apiClient(t.app, (await provisionUser(t.app, "regular_user")).cookie);
+ expect((await user.post("/api/version/update", {})).status).toBe(403);
+ expect((await user.get("/api/version/update")).status).toBe(403);
+ const admin = await loginAdmin(t.app);
+ const res = await apiClient(t.app, admin.cookie).get("/api/version/update");
+ expect(res.status).toBe(200);
+ expect((await res.json()) as UpdateJobStatus).toEqual({
+ state: "idle",
+ targetVersion: null,
+ output: "",
+ });
});
it("reports unsupported when the server was not launched via the CLI", async () => {
@@ -349,19 +308,6 @@ describe("POST /api/version/update", () => {
const again = await apiClient(t.app, admin.cookie).get("/api/version/update");
expect(((await again.json()) as UpdateJobStatus).result?.status).toBe("unsupported");
});
-
- it("GET /api/version/update is admin-only and idle before any run", async () => {
- const user = await provisionUser(t.app, "regular_user");
- expect((await apiClient(t.app, user.cookie).get("/api/version/update")).status).toBe(403);
- const admin = await loginAdmin(t.app);
- const res = await apiClient(t.app, admin.cookie).get("/api/version/update");
- expect(res.status).toBe(200);
- expect((await res.json()) as UpdateJobStatus).toEqual({
- state: "idle",
- targetVersion: null,
- output: "",
- });
- });
});
describe("POST /api/version/restart", () => {
@@ -386,34 +332,3 @@ describe("POST /api/version/restart", () => {
}
});
});
-
-describe("classifyUpdateRun", () => {
- it("a non-zero exit is a failed upgrade attempt", () => {
- const r = classifyUpdateRun(1, "Upgrade failed; the previous install was left in place.");
- expect(r.status).toBe("failed");
- expect(r.needsRestart).toBe(false);
- });
-
- it("a refusal (exit 0 with the CLI's refusal message) is unsupported", () => {
- // Literal CLI copy (packages/cli/src/i18n.ts update.sourceCheckout / unknownInstall):
- // the classifier matches fragments of these exact strings.
- const source =
- "This penguin runs from a source checkout, so there is nothing to download — update it with `git pull` and rebuild (`pnpm install && pnpm -r build`).";
- expect(classifyUpdateRun(0, source).status).toBe("unsupported");
- const unknown =
- "Cannot tell how this penguin was installed (running from /opt/penguin/cli.js), so it will not be replaced. Re-install with the official installer, or upgrade with the package manager you used.";
- expect(classifyUpdateRun(0, unknown).status).toBe("unsupported");
- });
-
- it("a clean exit without a refusal is updated and needs a restart (up-to-date included)", () => {
- const done =
- "Upgrade 0.1.2 -> 0.1.3\nPenguinHarness 0.1.3 installed. Run `penguin --version` in a new shell to confirm.";
- expect(classifyUpdateRun(0, done)).toEqual({
- status: "updated",
- output: done,
- needsRestart: true,
- });
- const upToDate = "Already on the latest version (0.1.3); nothing to do.";
- expect(classifyUpdateRun(0, upToDate).status).toBe("updated");
- });
-});
diff --git a/packages/server/test/web-static-caching.test.ts b/packages/server/test/web-static-caching.test.ts
index 86ace5ae..9eda9ce5 100644
--- a/packages/server/test/web-static-caching.test.ts
+++ b/packages/server/test/web-static-caching.test.ts
@@ -1,14 +1,21 @@
/**
- * The SPA's caching contract — the piece that makes a hot-pushed web VISIBLE: without it,
- * whether a returning client ever saw a new push was left to browser heuristics. index.html
- * (and every SPA-fallback answer) must revalidate per navigation and flip on a push;
- * content-hashed assets must cache forever.
+ * The SPA's caching contract — what makes a hot-pushed web VISIBLE: without it, whether a
+ * returning client ever saw a new push was left to browser heuristics.
+ *
+ * - index.html, and every SPA-fallback answer, revalidates per navigation (`no-cache` plus an
+ * ETag); content-hashed assets cache forever.
+ * - A matching If-None-Match answers 304 with no body and the same contract; a match is found
+ * in a list of tags, through a proxy's weak `W/` downgrade, and for `*`; an unrelated tag is
+ * a miss.
+ * - A new push changes the ETag, so the next navigation gets the new app.
+ * - Served from disk (the packaged install) the same contract holds, with a weak size+mtime
+ * validator that moves when the file changes.
*/
import zlib from "node:zlib";
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createTestApp, loginAdmin, makeTempRoot } from "./helpers.js";
import type { TestApp } from "./helpers.js";
@@ -42,21 +49,23 @@ async function pushWeb(t: TestApp, cookie: string, marker: string) {
});
}
-describe("web static caching", () => {
+describe("web static caching, from a pushed web", () => {
let t: TestApp;
let cookie: string;
- beforeEach(async () => {
+ // One push serves the read-only cases; the last case pushes again.
+ beforeAll(async () => {
t = await createTestApp();
cookie = (await loginAdmin(t.app)).cookie;
+ expect((await pushWeb(t, cookie, "v1")).status).toBe(200);
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
- it("index.html revalidates per navigation; hashed assets cache forever", async () => {
- expect((await pushWeb(t, cookie, "v1")).status).toBe(200);
+ const etagOfIndex = async () => (await t.app.request("/")).headers.get("etag")!;
+ it("revalidates index.html per navigation, and caches hashed assets forever", async () => {
const index = await t.app.request("/");
expect(index.status).toBe(200);
expect(index.headers.get("cache-control")).toBe("no-cache");
@@ -73,45 +82,16 @@ describe("web static caching", () => {
expect(asset.headers.get("cache-control")).toBe("public, max-age=31536000, immutable");
});
- it("a matching ETag answers 304 with no body", async () => {
- expect((await pushWeb(t, cookie, "v1")).status).toBe(200);
- const first = await t.app.request("/");
- const etag = first.headers.get("etag")!;
- const revalidated = await t.app.request("/", { headers: { "if-none-match": etag } });
+ it("answers a matching ETag with a bodiless 304 that keeps the contract", async () => {
+ const revalidated = await t.app.request("/", {
+ headers: { "if-none-match": await etagOfIndex() },
+ });
expect(revalidated.status).toBe(304);
expect(await revalidated.text()).toBe("");
// Still carries the contract, so the client keeps revalidating next time.
expect(revalidated.headers.get("cache-control")).toBe("no-cache");
});
- it("a new push changes the ETag, so the next navigation gets the new app", async () => {
- expect((await pushWeb(t, cookie, "v1")).status).toBe(200);
- const v1 = await t.app.request("/");
- const v1Etag = v1.headers.get("etag")!;
-
- expect((await pushWeb(t, cookie, "v2")).status).toBe(200);
- // The old ETag no longer matches: full 200 with the new bytes, not a 304.
- const after = await t.app.request("/", { headers: { "if-none-match": v1Etag } });
- expect(after.status).toBe(200);
- expect(await after.text()).toContain("v2");
- expect(after.headers.get("etag")).not.toBe(v1Etag);
- });
-});
-
-describe("If-None-Match, as clients and proxies actually send it", () => {
- let t: TestApp;
-
- beforeEach(async () => {
- t = await createTestApp();
- const cookie = (await loginAdmin(t.app)).cookie;
- expect((await pushWeb(t, cookie, "v1")).status).toBe(200);
- });
- afterEach(async () => {
- await t.cleanup();
- });
-
- const etagOfIndex = async () => (await t.app.request("/")).headers.get("etag")!;
-
it("matches one tag out of a list", async () => {
// RFC 9110 allows a list, and a client holding several validators sends one.
const etag = await etagOfIndex();
@@ -125,8 +105,9 @@ describe("If-None-Match, as clients and proxies actually send it", () => {
// A re-encoding proxy (nginx's gzip module is the usual one) turns a strong ETag weak on
// the way out; the client returns what it was given. A string compare misses this and
// silently re-downloads the app on every navigation.
- const etag = await etagOfIndex();
- const res = await t.app.request("/", { headers: { "if-none-match": `W/${etag}` } });
+ const res = await t.app.request("/", {
+ headers: { "if-none-match": `W/${await etagOfIndex()}` },
+ });
expect(res.status).toBe(304);
});
@@ -134,6 +115,16 @@ describe("If-None-Match, as clients and proxies actually send it", () => {
expect((await t.app.request("/", { headers: { "if-none-match": "*" } })).status).toBe(304);
expect((await t.app.request("/", { headers: { "if-none-match": '"nope"' } })).status).toBe(200);
});
+
+ it("changes the ETag on a new push, so the next navigation gets the new app", async () => {
+ const v1Etag = await etagOfIndex();
+ expect((await pushWeb(t, cookie, "v2")).status).toBe(200);
+ // The old ETag no longer matches: full 200 with the new bytes, not a 304.
+ const after = await t.app.request("/", { headers: { "if-none-match": v1Etag } });
+ expect(after.status).toBe(200);
+ expect(await after.text()).toContain("v2");
+ expect(after.headers.get("etag")).not.toBe(v1Etag);
+ });
});
describe("web static caching, served from disk", () => {
@@ -143,15 +134,17 @@ describe("web static caching, served from disk", () => {
let t: TestApp;
let webDist: string;
- beforeEach(async () => {
+ // The last case rewrites index.html; the others only read.
+ beforeAll(async () => {
webDist = path.join(await makeTempRoot(), "web");
await fs.mkdir(path.join(webDist, "assets"), { recursive: true });
await fs.writeFile(path.join(webDist, "index.html"), "<html>disk v1</html>");
await fs.writeFile(path.join(webDist, "assets", "index-abc123.js"), 'console.log("v1")');
t = await createTestApp({ config: { webDist } });
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
+ await fs.rm(path.dirname(webDist), { recursive: true, force: true });
});
it("applies the same contract, with a weak validator", async () => {
diff --git a/packages/server/vitest.config.ts b/packages/server/vitest.config.ts
index 446409f3..aedb91bd 100644
--- a/packages/server/vitest.config.ts
+++ b/packages/server/vitest.config.ts
@@ -47,5 +47,10 @@ export default defineConfig({
testTimeout: process.platform === "win32" ? 30_000 : 5_000,
hookTimeout: process.platform === "win32" ? 30_000 : 10_000,
retry: process.platform === "win32" ? 2 : process.platform === "darwin" ? 1 : 0,
+ // `vitest run --coverage` maps every file under src/, loaded by a test or not.
+ coverage: {
+ provider: "v8",
+ include: ["src/**"],
+ },
},
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 735e763b..44af2039 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -472,6 +472,9 @@ importers:
'@types/ws':
specifier: ^8.18.1
version: 8.18.1
+ '@vitest/coverage-v8':
+ specifier: ^3.2.6
tsup:
specifier: ^8.3.0
@@ -768,6 +771,10 @@ importers:
packages:
+ '@ampproject/[email protected]':
+ resolution: {integrity: sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==}
+ engines: {node: '>=6.0.0'}
+
'@anthropic-ai/[email protected]':
resolution: {integrity: sha512-0Z2NY3T2wnzT9esRit6BiWpQXvL+F2b3z3Z9in3mXh7MDf122rVi2bcPowQHmo9ITXAPJmv/3H3t0V1z3Fugfw==}
@@ -1001,6 +1008,10 @@ packages:
resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==}
engines: {node: '>=6.9.0'}
+ resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
+ engines: {node: '>=18'}
+
'@deepseek-ai/[email protected]':
resolution: {integrity: sha512-YBdskTU2Po1kru3GgcUWUbkTsPMA9LkSQDAY8rBkFJeajdgcQad3QPJZE26JyK99Xb6HaASvoXg2DSUTeN/0Nw==}
hasBin: true
@@ -1343,10 +1354,18 @@ packages:
peerDependencies:
hono: ^4
+ '@isaacs/[email protected]':
+ resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}
+ engines: {node: '>=12'}
+
'@isaacs/[email protected]':
resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==}
engines: {node: '>=18.0.0'}
+ '@istanbuljs/[email protected]':
+ resolution: {integrity: sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==}
+ engines: {node: '>=8'}
+
'@jridgewell/[email protected]':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@@ -1660,6 +1679,10 @@ packages:
'@penguinharness/use-firecrawl@file:plugins/use-firecrawl':
resolution: {directory: plugins/use-firecrawl, type: directory}
+ '@pkgjs/[email protected]':
+ resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
+ engines: {node: '>=14'}
+
'@playwright/[email protected]':
resolution: {integrity: sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==}
engines: {node: '>=18'}
@@ -2231,6 +2254,15 @@ packages:
peerDependencies:
vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-NEGWJS2XNu2PfRLQwOO3CTKj1tTETxNBdk454vDxVBhxJYhPaA/eS0nAI0c+1El1P7a60z8+i+ZrQoGESweGKg==}
+ peerDependencies:
+ '@vitest/browser': 3.2.7
+ vitest: 3.2.7
+ peerDependenciesMeta:
+ '@vitest/browser':
+ optional: true
+
'@vitest/[email protected]':
resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==}
@@ -2359,6 +2391,9 @@ packages:
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-BRRC8VRZY2R4Z4lFIL35MwNXmwVqBityvOIwETtsCSwvjl0IdgFsy9NhdaA6j74nUdtJJlIypeRhpDam19Wq3g==}
+
resolution: {integrity: sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==}
engines: {node: '>=0.12.0'}
@@ -2726,6 +2761,9 @@ packages:
resolution: {integrity: sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==}
+ resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
+
resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==}
@@ -2769,6 +2807,9 @@ packages:
resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
+ resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}
+
resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==}
engines: {node: '>= 0.8'}
@@ -2917,6 +2958,10 @@ packages:
debug:
optional: true
+ resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==}
+ engines: {node: '>=14'}
+
resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}
engines: {node: '>= 6'}
@@ -3005,6 +3050,11 @@ packages:
resolution: {integrity: sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}
+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
+ hasBin: true
+
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
@@ -3102,6 +3152,9 @@ packages:
resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
+
resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
@@ -3191,6 +3244,25 @@ packages:
resolution: {integrity: sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==}
engines: {node: '>=20'}
+ resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==}
+
resolution: {integrity: sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==}
engines: {node: '>=10'}
@@ -3210,6 +3282,9 @@ packages:
resolution: {integrity: sha512-uwYQp+VJ38FVvtim6qNbit6e9uT6dwWQ4Y1+H9TxhW5hcHjpHwoxlR0nMpqUmIFOmu4VqMxwdJA88gIVuZJQ/g==}
+ resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}
+
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
@@ -3388,6 +3463,9 @@ packages:
resolution: {integrity: sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}
+
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
@@ -3398,6 +3476,13 @@ packages:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+ resolution: {integrity: sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==}
+
+ resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}
@@ -3736,6 +3821,9 @@ packages:
resolution: {integrity: sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==}
+
resolution: {integrity: sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==}
@@ -3758,6 +3846,10 @@ packages:
resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==}
+ engines: {node: '>=16 || 14 >=14.18'}
+
resolution: {integrity: sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==}
@@ -4109,6 +4201,10 @@ packages:
resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}
+ resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
+ engines: {node: '>=14'}
+
resolution: {integrity: sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==}
engines: {node: '>=10'}
@@ -4156,6 +4252,10 @@ packages:
resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==}
engines: {node: '>=18'}
@@ -4221,6 +4321,10 @@ packages:
resolution: {integrity: sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==}
engines: {node: '>=6.0.0'}
+ resolution: {integrity: sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==}
engines: {node: '>=0.8'}
@@ -4521,6 +4625,10 @@ packages:
resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==}
engines: {node: '>=18'}
@@ -4613,6 +4721,11 @@ packages:
snapshots:
+ '@ampproject/[email protected]':
+ dependencies:
+ '@jridgewell/gen-mapping': 0.3.13
+ '@jridgewell/trace-mapping': 0.3.31
+
dependencies:
'@anthropic-ai/sdk': 0.91.1([email protected])
@@ -5047,6 +5160,8 @@ snapshots:
'@babel/helper-string-parser': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
+ '@bcoe/[email protected]': {}
+
'@deepseek-ai/[email protected]':
dependencies:
'@deepseek-ai/cosmokit': 1.8.2
@@ -5340,10 +5455,21 @@ snapshots:
dependencies:
hono: 4.12.34
+ '@isaacs/[email protected]':
+ dependencies:
+ string-width: 5.1.2
+ string-width-cjs: [email protected]
+ strip-ansi: 7.2.0
+ strip-ansi-cjs: [email protected]
+ wrap-ansi: 8.1.0
+ wrap-ansi-cjs: [email protected]
+
'@isaacs/[email protected]':
dependencies:
minipass: 7.1.3
+ '@istanbuljs/[email protected]': {}
+
'@jridgewell/[email protected]':
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -5575,6 +5701,9 @@ snapshots:
'@penguinharness/use-firecrawl@file:plugins/use-firecrawl': {}
+ '@pkgjs/[email protected]':
+ optional: true
+
'@playwright/[email protected]':
dependencies:
playwright: 1.61.1
@@ -6316,6 +6445,25 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@ampproject/remapping': 2.3.0
+ '@bcoe/v8-coverage': 1.0.2
+ ast-v8-to-istanbul: 0.3.12
+ debug: 4.4.3([email protected])
+ istanbul-lib-coverage: 3.2.2
+ istanbul-lib-report: 3.0.1
+ istanbul-lib-source-maps: 5.0.6([email protected])
+ istanbul-reports: 3.2.0
+ magic-string: 0.30.21
+ magicast: 0.3.5
+ std-env: 3.10.0
+ test-exclude: 7.0.2
+ tinyrainbow: 2.0.0
+ transitivePeerDependencies:
+ - supports-color
+
'@vitest/[email protected]':
dependencies:
'@types/chai': 5.2.3
@@ -6485,6 +6633,12 @@ snapshots:
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.31
+ estree-walker: 3.0.3
+ js-tokens: 10.0.0
+
@@ -6841,6 +6995,8 @@ snapshots:
dependencies:
readable-stream: 2.3.8
+
dependencies:
safe-buffer: 5.2.1
@@ -6929,6 +7085,8 @@ snapshots:
+
@@ -7115,6 +7273,11 @@ snapshots:
optionalDependencies:
debug: 4.4.3([email protected])
+ dependencies:
+ cross-spawn: 7.0.6
+ signal-exit: 4.1.0
+
dependencies:
asynckit: 0.4.0
@@ -7222,6 +7385,15 @@ snapshots:
dependencies:
pump: 3.0.4
+ dependencies:
+ foreground-child: 3.3.1
+ jackspeak: 3.4.3
+ minimatch: 9.0.9
+ minipass: 7.1.3
+ package-json-from-dist: 1.0.1
+ path-scurry: 1.11.1
+
dependencies:
fs.realpath: 1.0.0
@@ -7421,6 +7593,8 @@ snapshots:
dependencies:
lru-cache: 6.0.0
+
@@ -7503,6 +7677,33 @@ snapshots:
+
+ dependencies:
+ istanbul-lib-coverage: 3.2.2
+ make-dir: 4.0.0
+ supports-color: 7.2.0
+
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.31
+ debug: 4.4.3([email protected])
+ istanbul-lib-coverage: 3.2.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ html-escaper: 2.0.2
+ istanbul-lib-report: 3.0.1
+
+ dependencies:
+ '@isaacs/cliui': 8.0.2
+ optionalDependencies:
+ '@pkgjs/parseargs': 0.11.0
+
dependencies:
async: 3.2.6
@@ -7517,6 +7718,8 @@ snapshots:
+
@@ -7669,6 +7872,8 @@ snapshots:
+
dependencies:
yallist: 3.1.1
@@ -7681,6 +7886,16 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
+ dependencies:
+ '@babel/parser': 7.29.7
+ '@babel/types': 7.29.7
+ source-map-js: 1.2.1
+
+ dependencies:
+ semver: 7.8.5
+
@@ -8231,6 +8446,8 @@ snapshots:
'@types/retry': 0.12.0
retry: 0.13.1
+
dependencies:
'@types/unist': 2.0.11
@@ -8253,6 +8470,11 @@ snapshots:
+ dependencies:
+ lru-cache: 10.4.3
+ minipass: 7.1.3
+
@@ -8686,6 +8908,8 @@ snapshots:
+
dependencies:
semver: 7.8.5
@@ -8722,6 +8946,12 @@ snapshots:
is-fullwidth-code-point: 3.0.0
strip-ansi: 6.0.1
+ dependencies:
+ eastasianwidth: 0.2.0
+ emoji-regex: 9.2.2
+ strip-ansi: 7.2.0
+
dependencies:
emoji-regex: 10.6.0
@@ -8805,6 +9035,12 @@ snapshots:
mkdirp: 0.5.6
rimraf: 2.6.3
+ dependencies:
+ '@istanbuljs/schema': 0.1.6
+ glob: 10.5.0
+ minimatch: 10.2.6
+
dependencies:
thenify: 3.3.1
@@ -9114,6 +9350,12 @@ snapshots:
string-width: 4.2.3
strip-ansi: 6.0.1
+ dependencies:
+ ansi-styles: 6.2.3
+ string-width: 5.1.2
+ strip-ansi: 7.2.0
+
dependencies:
ansi-styles: 6.2.3