Skip to content

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

test(server): share the plugin, workflow and Skill suites' apps (#930)

Yaowei Zheng548bea9bf1f5
diff --git a/packages/server/test/asset-archives.test.ts b/packages/server/test/asset-archives.test.ts
index 52977549..6b574427 100644
--- a/packages/server/test/asset-archives.test.ts
+++ b/packages/server/test/asset-archives.test.ts
@@ -1,12 +1,17 @@
/**
* Pushed assets travel as archives: the deploy packs each package into one deterministic
- * `.tgz` (the same files give the same bytes, so an unchanged package is an unchanged blob), and
- * the platform unpacks `archives/` once into `.unpacked/` before resolving from it.
+ * `.tgz`, and the platform unpacks `archives/` once into `.unpacked/` before resolving from it.
+ *
+ * - The same files give the same bytes whatever their order, their mtimes on disk and the
+ * clock at packing time, so an unchanged package is an unchanged blob; a scoped package's
+ * archive is named flat.
+ * - Unpacking happens once (a marker records completion), keeps exec bits, is redone from
+ * scratch after a crash mid-extraction, and leaves a directory without archives alone.
*/
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { UNPACKED_DIR, unpackedAssetsDir } from "../src/hmr/asset-archives.js";
// @ts-expect-error — a plain .mjs build script, no declarations.
import { archiveName, packArchive } from "../../../scripts/asset-archives.mjs";
@@ -40,9 +45,16 @@ describe("asset archives", () => {
"node_modules/a/package.json": "{}",
});
const first = (await packArchive(entries)) as Buffer;
- await new Promise((r) => setTimeout(r, 1100)); // a later mtime on disk must not show
- const second = (await packArchive([...entries].reverse())) as Buffer;
- expect(first.equals(second)).toBe(true);
+ // An hour later, on disk and on the clock: neither may show in the bytes.
+ const later = new Date(Date.now() + 3_600_000);
+ for (const entry of entries) await fs.utimes(entry.abs, later, later);
+ vi.useFakeTimers({ toFake: ["Date"], now: later });
+ try {
+ const second = (await packArchive([...entries].reverse())) as Buffer;
+ expect(first.equals(second)).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
expect(archiveName("plugins.", "@scope/name")).toBe("plugins.scope__name.tgz");
});
diff --git a/packages/server/test/directory-skills.test.ts b/packages/server/test/directory-skills.test.ts
index 22a3c299..9ae1e56f 100644
--- a/packages/server/test/directory-skills.test.ts
+++ b/packages/server/test/directory-skills.test.ts
@@ -1,22 +1,30 @@
/**
- * Integration tests for importing Skills from a directory the user picked: discovery under
- * `.agents/skills` / `.claude/skills`, the `.claude`-is-a-symlink-to-`.agents` case that would
- * otherwise offer everything twice, which layout wins a name collision, what is passed over rather
- * than offered (no frontmatter, a symlinked Skill directory, an unsafe name), the empty directory
- * being a normal answer, path and authorization rejections, and Agent creation installing the
- * picked names — including a directory Skill shadowing a library Skill of the same name.
+ * Importing Skills from a directory the user picked.
*
- * It also pins the read discipline the module promises: `SKILL.md` and `icon.svg` are read only
- * when they are regular files the Skill directory owns, so a symlink cannot hand back a file
- * outside it; and one Skill that cannot be read does not take the rest of the directory with it.
+ * - Discovery reads `.agents/skills` and `.claude/skills` and says which layout each Skill came
+ * from; a `.claude` that is a symlink to `.agents` offers nothing twice; `.agents` wins a
+ * name both layouts carry.
+ * - Passed over rather than offered: a Skill with no frontmatter, a symlinked Skill directory,
+ * an unsafe name, one past the size caps. `SKILL.md` and `icon.svg` are read only when they
+ * are regular files the Skill directory owns, so a symlink cannot hand back a file outside
+ * it, and one unreadable Skill does not take the rest of the directory with it.
+ * - An empty directory is an empty list; a relative path, a missing directory and an outsider
+ * are refused.
+ * - Creating an Agent installs the picked names, files and icon included, a directory Skill
+ * shadowing a library Skill of the same name; a picked Skill that is gone is a 404 with no
+ * Agent created; a relative skillsDirectory and half of the directory pair are refused.
+ *
+ * One app and one Project for the file; every case works in a scratch directory and Agents of
+ * its own.
*/
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { skillsDir, librarySkill } from "@prismshadow/penguin-core";
import type {
AgentCreateResponse,
+ AgentsResponse,
AgentSkillsResponse,
DirectorySkillsResponse,
ProjectCreateResponse,
@@ -57,12 +65,20 @@ describe("directory skills api", () => {
}
};
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
const a = await provisionUser(t.app, "owner_d");
const b = await provisionUser(t.app, "outsider_d");
owner = apiClient(t.app, a.cookie);
outsider = apiClient(t.app, b.cookie);
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+
+ // Every case picks a directory of its own and installs into the one Project, in Agents that
+ // go with the case (a retry finds their names free).
+ beforeAll(async () => {
const created = (await (
await owner.post("/api/projects", {
projectId: "owner_d-dirskills",
@@ -70,18 +86,22 @@ describe("directory skills api", () => {
})
).json()) as ProjectCreateResponse;
projectId = created.project.projectId;
+ });
+ beforeEach(async () => {
dir = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-dirskills-"));
});
-
afterEach(async () => {
- // The app teardown must run even if the scratch checkout resists removal: a throw here would
- // skip `t.cleanup()`, leaking the db/hmr host into every later file in this worker — the
- // ci-windows cascade helpers.ts documents. Same maxRetries discipline, same reason.
- try {
- await fs.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
- } finally {
- await t.cleanup();
+ const listed = (await (
+ await owner.get(`/api/projects/${projectId}/agents`)
+ ).json()) as AgentsResponse;
+ for (const { agentId } of listed.agents) {
+ if (agentId !== "default_agent") {
+ await owner.delete(`/api/projects/${projectId}/agents/${agentId}`);
+ }
}
+ // A scratch checkout can resist removal on Windows for a moment; same retry discipline as
+ // helpers.ts.
+ await fs.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
});
it("finds Skills in both layouts and says which one each came from", async () => {
diff --git a/packages/server/test/hmr-network-gate.test.ts b/packages/server/test/hmr-network-gate.test.ts
index 9b26aab5..721815ff 100644
--- a/packages/server/test/hmr-network-gate.test.ts
+++ b/packages/server/test/hmr-network-gate.test.ts
@@ -5,56 +5,64 @@
* exactly the case the gate exists to block. It is honored only when the deployment
* explicitly opts in (`trustProxy` / PENGUIN_TRUST_PROXY=1), same as a real reverse-proxy
* setup requires.
+ *
+ * - On a non-loopback bind a spoofed `x-forwarded-proto` is refused by default, while real
+ * HTTPS on the request URL passes whatever trustProxy says.
+ * - With trustProxy on, plain HTTP without the header is still refused, and the header is
+ * honored.
+ * - A loopback bind needs neither HTTPS nor the header.
+ *
+ * A request past the gate meets the cookie check instead, so its 401 is the proof the gate let
+ * it through.
*/
-import { afterEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createTestApp } from "./helpers.js";
-import type { TestApp } from "./helpers.js";
+import type { TestApp, TestAppOptions } from "./helpers.js";
-describe("hmr network gate: non-loopback binds require real HTTPS", () => {
- let t: TestApp | undefined;
- afterEach(async () => {
- if (t) await t.cleanup();
- t = undefined;
+/** One app per bind configuration: the gate reads only the request, so the cases share it. */
+function bound(opts: TestAppOptions) {
+ const app = { t: undefined as TestApp | undefined };
+ beforeAll(async () => {
+ app.t = await createTestApp(opts);
});
+ afterAll(async () => {
+ await app.t?.cleanup();
+ });
+ return (url: string, headers: Record<string, string> = {}) =>
+ app.t!.app.request(url, { method: "POST", headers });
+}
+
+describe("hmr network gate: a non-loopback bind, trustProxy off (the default)", () => {
+ const upgrade = bound({ config: { host: "0.0.0.0" } });
- it("rejects a spoofed x-forwarded-proto header by default (trustProxy off)", async () => {
- t = await createTestApp({ config: { host: "0.0.0.0" } });
- const res = await t.app.request("/api/hmr/upgrade", {
- method: "POST",
- headers: { "x-forwarded-proto": "https" },
- });
+ it("rejects a spoofed x-forwarded-proto header", async () => {
+ const res = await upgrade("/api/hmr/upgrade", { "x-forwarded-proto": "https" });
expect(res.status).toBe(403);
const body = (await res.json()) as { error: { code: string } };
expect(body.error.code).toBe("hmr_disabled");
});
- it("real HTTPS on the request URL itself passes the gate regardless of trustProxy", async () => {
- t = await createTestApp({ config: { host: "0.0.0.0" } });
- const res = await t.app.request("https://example.test/api/hmr/upgrade", { method: "POST" });
- // Past the network gate now — falls through to cookie auth, which rejects with 401
- // (no cookie sent), proving the gate itself let the request through.
- expect(res.status).toBe(401);
+ it("lets real HTTPS on the request URL itself through", async () => {
+ expect((await upgrade("https://example.test/api/hmr/upgrade")).status).toBe(401);
});
+});
- it("plain HTTP on the request URL is still refused when trustProxy is on (no header sent)", async () => {
- t = await createTestApp({ config: { host: "0.0.0.0", trustProxy: true } });
- const res = await t.app.request("/api/hmr/upgrade", { method: "POST" });
- expect(res.status).toBe(403);
+describe("hmr network gate: a non-loopback bind with trustProxy on", () => {
+ const upgrade = bound({ config: { host: "0.0.0.0", trustProxy: true } });
+
+ it("still refuses plain HTTP when no header is sent", async () => {
+ expect((await upgrade("/api/hmr/upgrade")).status).toBe(403);
});
- it("honors x-forwarded-proto once trustProxy is explicitly enabled", async () => {
- t = await createTestApp({ config: { host: "0.0.0.0", trustProxy: true } });
- const res = await t.app.request("/api/hmr/upgrade", {
- method: "POST",
- headers: { "x-forwarded-proto": "https" },
- });
- // Past the network gate — rejected by the (missing) cookie instead.
- expect(res.status).toBe(401);
+ it("honors x-forwarded-proto", async () => {
+ expect((await upgrade("/api/hmr/upgrade", { "x-forwarded-proto": "https" })).status).toBe(401);
});
+});
+
+describe("hmr network gate: a loopback bind", () => {
+ const upgrade = bound({}); // the default test config binds 127.0.0.1
- it("a loopback bind needs neither HTTPS nor the header", async () => {
- t = await createTestApp(); // default test config binds 127.0.0.1
- const res = await t.app.request("/api/hmr/upgrade", { method: "POST" });
- expect(res.status).toBe(401); // past the gate, rejected only by the missing cookie
+ it("needs neither HTTPS nor the header", async () => {
+ expect((await upgrade("/api/hmr/upgrade")).status).toBe(401);
});
});
diff --git a/packages/server/test/plugin-registry.test.ts b/packages/server/test/plugin-registry.test.ts
index e4122803..c8d24a14 100644
--- a/packages/server/test/plugin-registry.test.ts
+++ b/packages/server/test/plugin-registry.test.ts
@@ -1,25 +1,33 @@
/**
- * Plugin registry tests: the shared index format (strict whole-document validation —
- * one malformed row fails the artifact, unlike a plugin list's per-entry tolerance),
- * the builtin registry serving the embedded four sandbox backends (readmes read from the
- * packages as npm shipped them), the HTTP registry
- * running a fetched document through the same validator (fetch stubbed, no network),
- * and GET /api/plugins behind the auth gate.
+ * The plugin registry: the catalogue a Project's plugin list is picked from.
+ *
+ * - The shared index format is validated whole: a flat array of per-version entries in order;
+ * a non-array or one malformed entry fails the document, naming the source or the position
+ * (unlike a plugin list's per-entry tolerance).
+ * - The builtin catalogue lists the sandbox backends that live in plugins/, each named,
+ * versioned, described and licensed as the package names itself, and serves each one's own
+ * shipped README.md; a listed package not on this machine, a name it does not list and a
+ * remote registry have no readme.
+ * - The HTTP registry fetches its index URL and runs the document through the same validator;
+ * an HTTP error, non-JSON and a malformed document fail it. No network: fetch is the suite's
+ * fetch fake.
+ * - GET /api/plugins/registry and its readme route need a session; the readme route refuses a
+ * name the deployment does not list and needs the name.
*/
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
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 type { PluginIndexEntry, PluginIndexResponse } from "../src/api/types.js";
import type { PluginBase } from "../src/plugin/loader.js";
import {
- BUILTIN_REGISTRY_SOURCE,
builtinPluginRegistry,
httpPluginRegistry,
parsePluginIndex,
} from "../src/plugin/registry.js";
+import { fakeFetch, jsonResponse } from "./fixtures/fetch.js";
import { apiClient, createTestApp, loginAdmin } from "./helpers.js";
import type { TestApp } from "./helpers.js";
@@ -62,46 +70,19 @@ describe("parsePluginIndex", () => {
});
});
-describe("builtinPluginRegistry", () => {
- it("serves the four sandbox backends, valid under the shared format", async () => {
- const registry = builtinPluginRegistry();
- expect(registry.source).toBe(BUILTIN_REGISTRY_SOURCE);
- const entries = await registry.index();
- expect(entries.map((e) => e.name)).toEqual([
- "@prismshadow/penguin-plugin-sandbox-bwrap",
- "@prismshadow/penguin-plugin-sandbox-seatbelt",
- "@prismshadow/penguin-plugin-sandbox-wsl",
- "@prismshadow/penguin-plugin-sandbox-dsh",
- ]);
- for (const entry of entries) {
- expect(entry.categories).toEqual(["sandbox"]);
- expect(entry.license).toBe("Apache-2.0");
- }
- });
-});
-
describe("httpPluginRegistry", () => {
const url = "https://registry.example/index.json";
it("fetches the index URL and validates the document with the shared parser", async () => {
- const seen: string[] = [];
- const fetchImpl: typeof fetch = async (input) => {
- seen.push(String(input));
- return new Response(JSON.stringify([VALID_ENTRY]), {
- status: 200,
- headers: { "content-type": "application/json" },
- });
- };
- const entries = await httpPluginRegistry(url, fetchImpl).index();
- expect(seen).toEqual([url]);
+ const registry = fakeFetch(() => jsonResponse([VALID_ENTRY]));
+ const entries = await httpPluginRegistry(url, registry.fetch).index();
+ expect(registry.calls.map((call) => call.url)).toEqual([url]);
expect(entries).toEqual([VALID_ENTRY]);
});
it("fails on an HTTP error status, on non-JSON, and on a malformed document", async () => {
- const respond =
- (body: string, status = 200) =>
- async () =>
- new Response(body, { status });
+ const respond = (body: string, status = 200) =>
+ fakeFetch(() => new Response(body, { status })).fetch;
await expect(httpPluginRegistry(url, respond("[]", 503)).index()).rejects.toThrow(/HTTP 503/);
await expect(httpPluginRegistry(url, respond("not json")).index()).rejects.toThrow(
/not valid JSON/,
@@ -112,27 +93,6 @@ describe("httpPluginRegistry", () => {
});
});
-describe("GET /api/plugins/registry", () => {
- let t: TestApp;
- beforeEach(async () => {
- t = await createTestApp();
- });
- afterEach(async () => {
- await t.cleanup();
- });
-
- it("requires auth, then serves the builtin index", async () => {
- expect((await t.app.request("/api/plugins/registry")).status).toBe(401);
-
- const admin = await loginAdmin(t.app);
- const res = await apiClient(t.app, admin.cookie).get("/api/plugins/registry");
- expect(res.status).toBe(200);
- const body = (await res.json()) as PluginIndexResponse;
- expect(body.plugins).toHaveLength(4);
- expect(body.plugins.every((p) => p.name.startsWith("@prismshadow/penguin-plugin-"))).toBe(true);
- });
-});
-
/**
* The index asserts a name, version, description and license for four packages that live
* beside it in this workspace, and their readmes are those packages' own README.md files.
@@ -222,10 +182,15 @@ describe("plugin readmes", () => {
});
describe("the builtin catalogue and the packages it lists", () => {
- it("names each package as that package names itself", async () => {
- for (const entry of await builtinPluginRegistry().index()) {
+ it("lists sandbox backends that live in plugins/, each named as that package names itself", async () => {
+ const index = await builtinPluginRegistry().index();
+ // Valid under the format every registry is held to.
+ expect(parsePluginIndex(index, "builtin")).toEqual(index);
+ expect(index.length).toBeGreaterThan(0);
+ for (const entry of index) {
const pkg = packages.get(entry.name);
expect(pkg, `${entry.name} is listed but is no package in plugins/`).toBeDefined();
+ expect(entry.categories, entry.name).toEqual(["sandbox"]);
expect(pkg!.manifest.version, entry.name).toBe(entry.version);
expect(pkg!.manifest.description, entry.name).toBe(entry.description);
expect(pkg!.manifest.license, entry.name).toBe(entry.license);
@@ -251,15 +216,25 @@ describe("the builtin catalogue and the packages it lists", () => {
});
});
-describe("GET /api/plugins/registry/readme", () => {
+describe("the registry routes", () => {
let t: TestApp;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
+ it("requires auth, then serves the builtin index", async () => {
+ expect((await t.app.request("/api/plugins/registry")).status).toBe(401);
+
+ const admin = await loginAdmin(t.app);
+ const res = await apiClient(t.app, admin.cookie).get("/api/plugins/registry");
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as PluginIndexResponse;
+ expect(body.plugins).toEqual(await builtinPluginRegistry().index());
+ });
+
it("requires auth, then serves a listed entry's readme from the package on this machine", async () => {
const name = "@prismshadow/penguin-plugin-sandbox-bwrap";
const url = `/api/plugins/registry/readme?name=${encodeURIComponent(name)}`;
diff --git a/packages/server/test/skills.test.ts b/packages/server/test/skills.test.ts
index 0bc598bb..2a1ee9b7 100644
--- a/packages/server/test/skills.test.ts
+++ b/packages/server/test/skills.test.ts
@@ -1,19 +1,30 @@
/**
- * Integration tests for the Skill routes: library catalog structure (any logged-in user), member
- * install/uninstall with 404 for outsiders, 404 for unknown skills, installed
- * files matching the library content, idempotent update on reinstall, the
- * directory disappearing after uninstall, default_agent starting with the
- * preinstalled library set (preinstall: false skills stay manual-install)
- * while a newly created plain Agent has none, Agent creation seeding the Skills picked in the
- * create dialog (unknown name = 404 with no Agent created), and the zip
- * archive install/export (layouts, zip-slip and limit rejections, 409
- * skill_exists + overwrite replace, byte-identical export round-trip), and the Agent list's
- * `pluginUpdates` — the Skill-library badge gate, which rides along on that list.
+ * The Skill routes: the library catalogue, installs into an Agent, zip archives and the Agent
+ * list's update badge.
+ *
+ * - Any signed-in user reads the catalogue (categories with plugin metadata, skills and hook
+ * points, no bodies) and what a plugin ships, keyed by path.
+ * - Members install and uninstall; installs land verbatim, the directory goes on uninstall, and
+ * a reinstall restores hand-edited content. An unknown skill is a 404 with nothing half
+ * installed, a malformed body a 400; outsiders and a missing Agent get 404.
+ * - default_agent starts with the preinstalled library set (preinstall: false skills stay
+ * manual); a new plain Agent has none; creating an Agent seeds the picked skills, refuses an
+ * unknown one without creating the Agent, and refuses a non-array field.
+ * - An archive installs in the nested or the root layout (the directory name winning over the
+ * frontmatter), refuses zip-slip, invalid names, malformed bodies and anything past the
+ * uncompressed caps (read off the central directory), answers 409 skill_exists unless told
+ * to overwrite, and exports byte-identically.
+ * - The Agent list's pluginUpdates names a Skill once the library moves past it (the legacy
+ * version spelling reading as the same version), never one the library does not carry, and
+ * never a directory with no readable SKILL.md.
+ *
+ * One app and one Project for the file; every case works in plain Agents of its own (removed
+ * after it), and the case about default_agent's own set in a Project of its own.
*/
import fs from "node:fs/promises";
import path from "node:path";
import { strToU8, unzipSync, zipSync } from "fflate";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { skillsDir, librarySkill, loadPreinstalledPlugins } from "@prismshadow/penguin-core";
import type {
AgentCreateResponse,
@@ -42,7 +53,7 @@ describe("skills api", () => {
.flatMap((p) => p.skills.map((s) => s.name))
.sort();
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
const a = await provisionUser(t.app, "owner_s");
const b = await provisionUser(t.app, "member_s");
@@ -50,16 +61,50 @@ describe("skills api", () => {
owner = apiClient(t.app, a.cookie);
member = apiClient(t.app, b.cookie);
outsider = apiClient(t.app, c.cookie);
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+
+ let projects = 0;
+ /** A Project of the owner's with the member added. */
+ const newProject = async (): Promise<string> => {
+ projects += 1;
const created = (await (
- await owner.post("/api/projects", { projectId: "owner_s-skills", name: "skills project" })
+ await owner.post("/api/projects", {
+ projectId: `owner_s-skills_${projects}`,
+ name: "skills project",
+ })
).json()) as ProjectCreateResponse;
- projectId = created.project.projectId;
expect(
- (await owner.post(`/api/projects/${projectId}/members`, { userId: "member_s" })).status,
+ (
+ await owner.post(`/api/projects/${created.project.projectId}/members`, {
+ userId: "member_s",
+ })
+ ).status,
).toBe(201);
+ return created.project.projectId;
+ };
+
+ // The cases share one Project and work in plain Agents of their own, which go with the case
+ // (a retry finds their names free). The one case about default_agent's own set takes a
+ // Project of its own.
+ let shared: string;
+ beforeAll(async () => {
+ shared = await newProject();
+ });
+ beforeEach(() => {
+ projectId = shared;
});
afterEach(async () => {
- await t.cleanup();
+ const listed = (await (
+ await owner.get(`/api/projects/${projectId}/agents`)
+ ).json()) as AgentsResponse;
+ for (const { agentId } of listed.agents) {
+ if (agentId !== "default_agent") {
+ await owner.delete(`/api/projects/${projectId}/agents/${agentId}`);
+ }
+ }
});
/** Creates a plain Agent with no Skills preinstalled. */
@@ -249,6 +294,7 @@ describe("skills api", () => {
});
it("default_agent starts with the preinstalled library set; preinstall:false skills stay manual-install", async () => {
+ projectId = await newProject();
const res = await member.get(base("default_agent"));
expect(res.status).toBe(200);
const body = (await res.json()) as AgentSkillsResponse;
diff --git a/packages/server/test/workflows.test.ts b/packages/server/test/workflows.test.ts
index b65f3ab1..3b011d2c 100644
--- a/packages/server/test/workflows.test.ts
+++ b/packages/server/test/workflows.test.ts
@@ -1,10 +1,36 @@
/**
- * Workflows: an Agent's own plugin package booted as a module tree — TypeScript the server
- * checks and transpiles, interfaces compared with the version the workflow installed,
- * tabs it contributes, loaded by content, versioned on every successful load, restorable,
- * and never taken down by a broken edit.
+ * Workflows: an Agent's own plugin package booted as a module tree.
+ *
+ * A loaded workflow:
+ * - Its TypeScript is checked and transpiled into a dot-directory beside a status file the
+ * Agent can read, its types written once from this harness; the tree boots, serves its UI
+ * under ui/ (no default document, nothing outside it) and dispatches to its handler, and its
+ * state persists on disk across a reload.
+ * - Its own state write is not an edit: the revision holds and nothing is left staged.
+ * - It opens and runs Sessions the SDK's way, inside its own Project only.
+ * - A handler takes any body (a form only from the app's own pages) and sends back any
+ * content type, a stream as it is produced and a redirect relative to its mount, never the
+ * app's cookies; JSON stays the default.
+ * - It is scoped to the Project's users.
+ * - An Agent's first workflow, made with nothing but file tools, is noticed without a list.
+ * - A workflow written in JavaScript is refused with the rename it needs.
+ *
+ * An edited workflow:
+ * - A file that disappears mid-read is a change, not a failed request.
+ * - An edited folder is re-imported, every version recorded and any restorable.
+ * - An edit that does not load leaves the previous instance serving and names the problem:
+ * source that does not type-check (with the compiler's file, line and reason, untyped code
+ * included), a type table that no longer fits this platform either way (an addition on the
+ * platform's side breaks nothing; an unreadable table is a problem, never a pass).
+ * - Tabs come from contributions: several per workflow, pages under ui/, open slots only; a
+ * workflow with pages and no tab gets a hint.
+ * - Removing a workflow removes its folder and recorded versions.
+ *
+ * Every load runs the TypeScript compiler, so the loaded-once group shares one app and one
+ * compile; each editing case needs a folder of its own to break, which it gets in an Agent of
+ * its own within the editing group's one app.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import fs from "node:fs/promises";
import path from "node:path";
import { agentDir } from "@prismshadow/penguin-core";
@@ -116,40 +142,56 @@ async function writtenAgainst(dir: string, edit: (table: IfaceTable) => void): P
await fs.writeFile(file, JSON.stringify(table));
}
+/** Writes the demo workflow into `dir`: its manifest, its handler and its one page. */
+async function writeDemo(dir: string): Promise<void> {
+ await fs.mkdir(path.join(dir, "ui"), { recursive: true });
+ await fs.writeFile(path.join(dir, "package.json"), packageJson());
+ await fs.writeFile(path.join(dir, "index.ts"), indexSource("hello"));
+ await fs.writeFile(path.join(dir, "ui", "index.html"), "<h1>demo v1</h1>");
+}
+
+/** An app with the owner's Project and the demo workflow written into its default Agent. */
+async function workflowApp() {
+ const t = await createTestApp();
+ const a = await provisionUser(t.app, "owner");
+ const owner = apiClient(t.app, a.cookie);
+ const created = await owner.post("/api/projects", { projectId: PROJECT, name: "wf" });
+ expect(created.status, await created.text()).toBe(201);
+ const dir = path.join(agentDir(t.root, PROJECT, AGENT), "workflows", "demo");
+ await writeDemo(dir);
+ return { t, owner, ownerCookie: a.cookie, dir };
+}
+
+async function listOf(owner: ReturnType<typeof apiClient>, base = BASE): Promise<WorkflowInfo[]> {
+ const res = await owner.get(base);
+ expect(res.status).toBe(200);
+ return ((await res.json()) as { workflows: WorkflowInfo[] }).workflows;
+}
+
// Most of these run the TypeScript compiler, several times each: on a CI runner a single test
// can pass 5s, the default POSIX limit, without anything being wrong.
-describe("workflows", { timeout: 30_000 }, () => {
+describe("a loaded workflow", { timeout: 30_000 }, () => {
let t: TestApp;
let owner: ReturnType<typeof apiClient>;
let ownerCookie: string;
let dir: string;
+ /** The demo as its one load left it. */
+ let wf: WorkflowInfo;
- beforeEach(async () => {
- t = await createTestApp();
- const a = await provisionUser(t.app, "owner");
- owner = apiClient(t.app, a.cookie);
- ownerCookie = a.cookie;
- const created = await owner.post("/api/projects", { projectId: PROJECT, name: "wf" });
- expect(created.status, await created.text()).toBe(201);
- dir = path.join(agentDir(t.root, PROJECT, AGENT), "workflows", "demo");
- await fs.mkdir(path.join(dir, "ui"), { recursive: true });
- await fs.writeFile(path.join(dir, "package.json"), packageJson());
- await fs.writeFile(path.join(dir, "index.ts"), indexSource("hello"));
- await fs.writeFile(path.join(dir, "ui", "index.html"), "<h1>demo v1</h1>");
+ beforeAll(async () => {
+ ({ t, owner, ownerCookie, dir } = await workflowApp());
+ [wf] = (await listOf(owner)) as [WorkflowInfo];
});
-
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
- async function list(): Promise<WorkflowInfo[]> {
- const res = await owner.get(BASE);
- expect(res.status).toBe(200);
- return ((await res.json()) as { workflows: WorkflowInfo[] }).workflows;
- }
+ const list = () => listOf(owner);
+ /** The count after one more POST: the handler's state as it now stands. */
+ const count = async (): Promise<number> =>
+ ((await (await owner.post(`${BASE}/demo/api/count`, {})).json()) as { count: number }).count;
it("checks and transpiles the TypeScript, boots the tree, serves its UI and dispatches to its handler", async () => {
- const [wf] = await list();
expect(wf).toMatchObject({ id: "demo", name: "Demo", version: "1.0.0", error: null });
expect(wf!.uiRev).toMatch(/^[0-9a-f]{12}$/);
// The tab is the contribution, its page path turned into the URL it is served from.
@@ -195,11 +237,11 @@ describe("workflows", { timeout: 30_000 }, () => {
expect(await res.json()).toEqual({ greeting: "hello", path: "/greet", q: { x: "1" } });
// Host state persists on disk across a reload.
- expect(await (await owner.post(`${BASE}/demo/api/count`, {})).json()).toEqual({ count: 1 });
+ const before = await count();
expect((await owner.post(`${BASE}/demo/reload`)).status).toBe(200);
- expect(await (await owner.post(`${BASE}/demo/api/count`, {})).json()).toEqual({ count: 2 });
+ expect(await count()).toBe(before + 1);
expect(JSON.parse(await fs.readFile(path.join(dir, "state.json"), "utf8"))).toEqual({
- count: 2,
+ count: before + 1,
});
});
@@ -208,7 +250,7 @@ describe("workflows", { timeout: 30_000 }, () => {
// Writing state used to leave a `state.json.tmp` behind, which the watcher read as an
// edit (recompiling the workflow and tearing down the tree that had just written it) and
// the revision hash read as content.
- expect(await (await owner.post(`${BASE}/demo/api/count`, {})).json()).toEqual({ count: 1 });
+ await count();
const [after] = await list();
expect(after!.revision).toBe(before!.revision);
expect(after!.loadedAt).toBe(before!.loadedAt);
@@ -216,6 +258,190 @@ describe("workflows", { timeout: 30_000 }, () => {
expect(left).toEqual([]);
});
+ it("opens and runs Sessions the SDK's way, inside its own Project only", async () => {
+ const res = await owner.get(`${BASE}/demo/api/open?agent=nobody&session=not-a-session`);
+ expect(await res.json()).toEqual({
+ opened: "createSession: this Project has no Agent 'nobody'",
+ ran: "run: this Project has no Session 'not-a-session'",
+ agents: [AGENT],
+ });
+ const own = await (await owner.get(`${BASE}/demo/api/open`)).json();
+ // Its own Agent passes the Project check and reaches the session runtime, which in this
+ // fixture has no model key to open a Session with.
+ expect(own).toMatchObject({ opened: expect.stringContaining("API key") });
+ });
+
+ it("hands a handler any body and sends back any content type; JSON stays the default", async () => {
+ // An upload: not JSON, so the handler gets the bytes as sent — and never the app's cookie.
+ const sent = new Uint8Array([0, 1, 2, 250, 251, 255]);
+ const upload = await t.app.request(`${BASE}/demo/api/upload`, {
+ method: "POST",
+ headers: { cookie: ownerCookie, "content-type": "application/x-demo" },
+ body: sent,
+ });
+ expect(upload.status).toBe(201);
+ expect(upload.headers.get("content-type")).toBe("application/x-demo");
+ expect(upload.headers.get("x-saw-cookie")).toBe("false");
+ expect(upload.headers.get("x-json-body")).toBe("null");
+ expect(new Uint8Array(await upload.arrayBuffer())).toEqual(sent);
+ // A form is what another site can make a browser send with the cookie attached, so on this
+ // mount the browser's own account of the request's origin is the defense: a form from one
+ // of the app's pages passes, the same form from anywhere else does not.
+ const form = (site: string) =>
+ t.app.request(`${BASE}/demo/api/upload`, {
+ method: "POST",
+ headers: {
+ cookie: ownerCookie,
+ "content-type": "application/x-www-form-urlencoded",
+ "sec-fetch-site": site,
+ },
+ body: "a=1",
+ });
+ expect((await form("same-origin")).status).toBe(201);
+ const forged = await form("cross-site");
+ expect(forged.status).toBe(403);
+ expect(((await forged.json()) as { error: { code: string } }).error.code).toBe(
+ "cross_origin_write",
+ );
+ // Everywhere else a form is still refused outright.
+ const elsewhere = await t.app.request(`${BASE}/demo/reload`, {
+ method: "POST",
+ headers: {
+ cookie: ownerCookie,
+ "content-type": "text/plain",
+ "sec-fetch-site": "same-origin",
+ },
+ body: "x",
+ });
+ expect(elsewhere.status).toBe(415);
+ // A page: the handler names the content type, the string goes out as written, and a
+ // workflow does not get to set the app's cookies.
+ const page = await owner.get(`${BASE}/demo/api/page`);
+ expect(page.headers.get("content-type")).toBe("text/html; charset=utf-8");
+ expect(page.headers.get("set-cookie")).toBeNull();
+ expect(await page.text()).toBe("<h1>proxied</h1>");
+ // A stream: the first chunk is in the client's hands while the handler is still producing
+ // the second — nothing is held back until the end.
+ const events = await owner.get(`${BASE}/demo/api/events`);
+ expect(events.headers.get("content-type")).toBe("text/event-stream");
+ const reader = events.body!.getReader();
+ const startedAt = Date.now();
+ const first = await reader.read();
+ expect(new TextDecoder().decode(first.value)).toBe("data: one\n\n");
+ expect(Date.now() - startedAt).toBeLessThan(300);
+ const second = await reader.read();
+ expect(new TextDecoder().decode(second.value)).toBe("data: two\n\n");
+ expect((await reader.read()).done).toBe(true);
+ // A redirect, relative to the api mount.
+ const moved = await owner.get(`${BASE}/demo/api/moved`);
+ expect(moved.status).toBe(302);
+ expect(moved.headers.get("location")).toBe("page");
+ // And what every existing workflow does is unchanged: JSON in, JSON out.
+ const json = await owner.post(`${BASE}/demo/api/count`, {});
+ expect(json.headers.get("content-type")).toContain("application/json");
+ expect(await json.json()).toEqual({ count: expect.any(Number) });
+ });
+
+ it("is scoped to the Project's users", async () => {
+ const other = apiClient(t.app, (await provisionUser(t.app, "other")).cookie);
+ expect((await other.get(BASE)).status).toBe(404);
+ expect((await other.get(`${BASE}/demo/ui/index.html`)).status).toBe(404);
+ expect((await other.delete(`${BASE}/demo`)).status).toBe(404);
+ expect((await owner.get(`${BASE}/demo/ui/index.html`)).status).toBe(200);
+ expect((await owner.get(`${BASE}/nope/ui/index.html`)).status).toBe(404);
+ expect((await owner.get(`${BASE}/nope/api/`)).status).toBe(404);
+ });
+
+ it("notices an Agent's FIRST workflow, made with nothing but its file tools", async () => {
+ // Another Agent of the Project, with no workflows/ folder when its list is first read.
+ const made = await owner.post(`/api/projects/${PROJECT}/agents`, { agentId: "builder" });
+ expect(made.status, await made.text()).toBe(201);
+ const base = `/api/projects/${PROJECT}/agents/builder/workflows`;
+ expect(((await (await owner.get(base)).json()) as { workflows: unknown[] }).workflows).toEqual(
+ [],
+ );
+
+ const first = path.join(agentDir(t.root, PROJECT, "builder"), "workflows", "first");
+ await fs.mkdir(path.join(first, "ui"), { recursive: true });
+ await fs.writeFile(path.join(first, "package.json"), packageJson());
+ await fs.writeFile(path.join(first, "index.ts"), indexSource("first"));
+ await fs.writeFile(path.join(first, "ui", "index.html"), "<h1>first</h1>");
+
+ // Nobody lists again: the server has to see the folder appear and load it on its own.
+ const statusFile = path.join(first, ".build", "status.json");
+ let status: { ok?: boolean } = {};
+ for (let i = 0; i < 100 && status.ok === undefined; i++) {
+ await new Promise((r) => setTimeout(r, 100));
+ status = await fs.readFile(statusFile, "utf8").then(
+ (text) => JSON.parse(text) as { ok: boolean },
+ () => ({}),
+ );
+ }
+ expect(status).toMatchObject({ ok: true, error: null, tabs: ["board"] });
+ });
+
+ it("refuses a workflow written in JavaScript, naming the rename it needs", async () => {
+ // An Agent of its own, so the demo's list stays the demo alone.
+ const made = await owner.post(`/api/projects/${PROJECT}/agents`, { agentId: "scripter" });
+ expect(made.status, await made.text()).toBe(201);
+ const scripted = path.join(agentDir(t.root, PROJECT, "scripter"), "workflows", "demo");
+ await writeDemo(scripted);
+ await fs.rename(path.join(scripted, "index.ts"), path.join(scripted, "index.mjs"));
+ const [refused] = await listOf(owner, `/api/projects/${PROJECT}/agents/scripter/workflows`);
+ expect(refused!.error).toContain(
+ "a workflow is written in TypeScript: rename index.mjs to index.ts",
+ );
+ });
+});
+
+describe("editing a workflow", { timeout: 30_000 }, () => {
+ let t: TestApp;
+ let owner: ReturnType<typeof apiClient>;
+ /** The case's own Agent's workflows, and the demo folder in it the case edits. */
+ let base: string;
+ let dir: string;
+ let editors = 0;
+
+ beforeAll(async () => {
+ t = await createTestApp();
+ owner = apiClient(t.app, (await provisionUser(t.app, "owner")).cookie);
+ const created = await owner.post("/api/projects", { projectId: PROJECT, name: "wf" });
+ expect(created.status, await created.text()).toBe(201);
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+ // A plain Agent per case, so each has a demo of its own to break. The Agents stay until the
+ // app goes: a loaded workflow's folder is watched, and a watched folder can refuse removal
+ // on Windows.
+ beforeEach(async () => {
+ editors += 1;
+ const agentId = `editor_${editors}`;
+ const made = await owner.post(`/api/projects/${PROJECT}/agents`, { agentId });
+ expect(made.status, await made.text()).toBe(201);
+ base = `/api/projects/${PROJECT}/agents/${agentId}/workflows`;
+ dir = path.join(agentDir(t.root, PROJECT, agentId), "workflows", "demo");
+ await writeDemo(dir);
+ });
+
+ const list = () => listOf(owner, base);
+
+ async function reload(): Promise<WorkflowInfo> {
+ const res = await owner.post(`${base}/demo/reload`);
+ expect(res.status).toBe(200);
+ return ((await res.json()) as { workflow: WorkflowInfo }).workflow;
+ }
+
+ async function reloadError(): Promise<string> {
+ const workflow = await reload();
+ // Whatever went wrong, the instance that loaded keeps answering, with its tabs.
+ expect(workflow.tabs).toHaveLength(1);
+ expect(await (await owner.get(`${base}/demo/api/`)).json()).toMatchObject({
+ greeting: "hello",
+ });
+ return workflow.error ?? "";
+ }
+
it("a folder file that disappears mid-read is a change, not a failed request", async () => {
// `walk` lists the files, then each is read: one that goes away in between (an editor's
// scratch file, the Agent deleting one) used to reject the read and answer 500 although
@@ -224,7 +450,7 @@ describe("workflows", { timeout: 30_000 }, () => {
const [listed] = await list();
expect(listed!.error).toBe(null);
await fs.rm(path.join(dir, "notes.md"));
- const res = await owner.get(`${BASE}/demo/api/greet`);
+ const res = await owner.get(`${base}/demo/api/greet`);
expect(res.status, await res.text()).toBe(200);
});
@@ -232,43 +458,43 @@ describe("workflows", { timeout: 30_000 }, () => {
const [v1] = await list();
await fs.writeFile(path.join(dir, "index.ts"), indexSource("bonjour"));
await fs.writeFile(path.join(dir, "ui", "index.html"), "<h1>demo v2</h1>");
- const reload = await owner.post(`${BASE}/demo/reload`);
+ const reload = await owner.post(`${base}/demo/reload`);
const v2 = ((await reload.json()) as { workflow: WorkflowInfo }).workflow;
expect(v2.revision).not.toBe(v1!.revision);
expect(v2.uiRev).not.toBe(v1!.uiRev);
expect(
- (await (await owner.get(`${BASE}/demo/api/`)).json()) as { greeting: string },
+ (await (await owner.get(`${base}/demo/api/`)).json()) as { greeting: string },
).toMatchObject({
greeting: "bonjour",
});
- const history = (await (await owner.get(`${BASE}/demo/history`)).json()) as {
+ const history = (await (await owner.get(`${base}/demo/history`)).json()) as {
versions: WorkflowVersion[];
};
expect(history.versions.map((v) => v.revision)).toEqual([v2.revision, v1!.revision]);
expect(history.versions[1]!.files).toContain("ui/index.html");
- const back = await owner.post(`${BASE}/demo/rollback`, { revision: v1!.revision });
+ const back = await owner.post(`${base}/demo/rollback`, { revision: v1!.revision });
expect(back.status).toBe(200);
expect(((await back.json()) as { workflow: WorkflowInfo }).workflow.revision).toBe(
v1!.revision,
);
- expect(await (await owner.get(`${BASE}/demo/ui/index.html`)).text()).toBe("<h1>demo v1</h1>");
+ expect(await (await owner.get(`${base}/demo/ui/index.html`)).text()).toBe("<h1>demo v1</h1>");
// Only the serving revision keeps its emitted code.
expect((await fs.readdir(path.join(dir, ".build"))).sort()).toEqual(
[v1!.revision, "status.json"].sort(),
);
expect(
- (await (await owner.get(`${BASE}/demo/api/`)).json()) as { greeting: string },
+ (await (await owner.get(`${base}/demo/api/`)).json()) as { greeting: string },
).toMatchObject({
greeting: "hello",
});
// The rolled-back revision is now the newest entry, once.
- const after = (await (await owner.get(`${BASE}/demo/history`)).json()) as {
+ const after = (await (await owner.get(`${base}/demo/history`)).json()) as {
versions: WorkflowVersion[];
};
expect(after.versions.map((v) => v.revision)).toEqual([v1!.revision, v2.revision]);
- expect((await owner.post(`${BASE}/demo/rollback`, { revision: "000000000000" })).status).toBe(
+ expect((await owner.post(`${base}/demo/rollback`, { revision: "000000000000" })).status).toBe(
404,
);
});
@@ -284,36 +510,20 @@ describe("workflows", { timeout: 30_000 }, () => {
},
]),
);
- const res = await owner.post(`${BASE}/demo/reload`);
+ const res = await owner.post(`${base}/demo/reload`);
const broken = ((await res.json()) as { workflow: WorkflowInfo }).workflow;
// Named before anything runs: the host gave this workflow no types for that interface.
expect(broken.error).toContain(
"requires.host '@prismshadow/penguin-server#Workflows': not among the types this workflow was written against",
);
- expect(await (await owner.get(`${BASE}/demo/api/`)).json()).toMatchObject({
+ expect(await (await owner.get(`${base}/demo/api/`)).json()).toMatchObject({
greeting: "hello",
});
- expect(await (await owner.get(`${BASE}/demo/history`)).json()).toMatchObject({
+ expect(await (await owner.get(`${base}/demo/history`)).json()).toMatchObject({
versions: [{ name: "Demo" }],
});
});
- async function reload(): Promise<WorkflowInfo> {
- const res = await owner.post(`${BASE}/demo/reload`);
- expect(res.status).toBe(200);
- return ((await res.json()) as { workflow: WorkflowInfo }).workflow;
- }
-
- async function reloadError(): Promise<string> {
- const workflow = await reload();
- // Whatever went wrong, the instance that loaded keeps answering, with its tabs.
- expect(workflow.tabs).toHaveLength(1);
- expect(await (await owner.get(`${BASE}/demo/api/`)).json()).toMatchObject({
- greeting: "hello",
- });
- return workflow.error ?? "";
- }
-
it("refuses source that does not type-check, with the compiler's file, line and reason", async () => {
await list();
await fs.writeFile(
@@ -350,56 +560,6 @@ describe("workflows", { timeout: 30_000 }, () => {
expect(await reloadError()).toContain("TS7031");
});
- it("opens and runs Sessions the SDK's way, inside its own Project only", async () => {
- await list();
- const res = await owner.get(`${BASE}/demo/api/open?agent=nobody&session=not-a-session`);
- expect(await res.json()).toEqual({
- opened: "createSession: this Project has no Agent 'nobody'",
- ran: "run: this Project has no Session 'not-a-session'",
- agents: [AGENT],
- });
- const own = await (await owner.get(`${BASE}/demo/api/open`)).json();
- // Its own Agent passes the Project check and reaches the session runtime, which in this
- // fixture has no model key to open a Session with.
- expect(own).toMatchObject({ opened: expect.stringContaining("API key") });
- });
-
- it("notices an Agent's FIRST workflow, made with nothing but its file tools", async () => {
- // Another Agent of the Project, with no workflows/ folder when its list is first read.
- const made = await owner.post(`/api/projects/${PROJECT}/agents`, { agentId: "builder" });
- expect(made.status, await made.text()).toBe(201);
- const base = `/api/projects/${PROJECT}/agents/builder/workflows`;
- expect(((await (await owner.get(base)).json()) as { workflows: unknown[] }).workflows).toEqual(
- [],
- );
-
- const first = path.join(agentDir(t.root, PROJECT, "builder"), "workflows", "first");
- await fs.mkdir(path.join(first, "ui"), { recursive: true });
- await fs.writeFile(path.join(first, "package.json"), packageJson());
- await fs.writeFile(path.join(first, "index.ts"), indexSource("first"));
- await fs.writeFile(path.join(first, "ui", "index.html"), "<h1>first</h1>");
-
- // Nobody lists again: the server has to see the folder appear and load it on its own.
- const statusFile = path.join(first, ".build", "status.json");
- let status: { ok?: boolean } = {};
- for (let i = 0; i < 100 && status.ok === undefined; i++) {
- await new Promise((r) => setTimeout(r, 100));
- status = await fs.readFile(statusFile, "utf8").then(
- (text) => JSON.parse(text) as { ok: boolean },
- () => ({}),
- );
- }
- expect(status).toMatchObject({ ok: true, error: null, tabs: ["board"] });
- });
-
- it("refuses JavaScript", async () => {
- await list();
- await fs.rename(path.join(dir, "index.ts"), path.join(dir, "index.mjs"));
- expect(await reloadError()).toContain(
- "a workflow is written in TypeScript: rename index.mjs to index.ts",
- );
- });
-
it("compares the types the workflow was written against with this platform's, both ways", async () => {
await list();
// requires: it was written when the host had a method this platform lacks.
@@ -491,98 +651,16 @@ describe("workflows", { timeout: 30_000 }, () => {
expect(((await reload()) as { hints: string[] }).hints).toEqual([]);
});
- it("hands a handler any body and sends back any content type; JSON stays the default", async () => {
- await list();
- // An upload: not JSON, so the handler gets the bytes as sent — and never the app's cookie.
- const sent = new Uint8Array([0, 1, 2, 250, 251, 255]);
- const upload = await t.app.request(`${BASE}/demo/api/upload`, {
- method: "POST",
- headers: { cookie: ownerCookie, "content-type": "application/x-demo" },
- body: sent,
- });
- expect(upload.status).toBe(201);
- expect(upload.headers.get("content-type")).toBe("application/x-demo");
- expect(upload.headers.get("x-saw-cookie")).toBe("false");
- expect(upload.headers.get("x-json-body")).toBe("null");
- expect(new Uint8Array(await upload.arrayBuffer())).toEqual(sent);
- // A form is what another site can make a browser send with the cookie attached, so on this
- // mount the browser's own account of the request's origin is the defense: a form from one
- // of the app's pages passes, the same form from anywhere else does not.
- const form = (site: string) =>
- t.app.request(`${BASE}/demo/api/upload`, {
- method: "POST",
- headers: {
- cookie: ownerCookie,
- "content-type": "application/x-www-form-urlencoded",
- "sec-fetch-site": site,
- },
- body: "a=1",
- });
- expect((await form("same-origin")).status).toBe(201);
- const forged = await form("cross-site");
- expect(forged.status).toBe(403);
- expect(((await forged.json()) as { error: { code: string } }).error.code).toBe(
- "cross_origin_write",
- );
- // Everywhere else a form is still refused outright.
- const elsewhere = await t.app.request(`${BASE}/demo/reload`, {
- method: "POST",
- headers: {
- cookie: ownerCookie,
- "content-type": "text/plain",
- "sec-fetch-site": "same-origin",
- },
- body: "x",
- });
- expect(elsewhere.status).toBe(415);
- // A page: the handler names the content type, the string goes out as written, and a
- // workflow does not get to set the app's cookies.
- const page = await owner.get(`${BASE}/demo/api/page`);
- expect(page.headers.get("content-type")).toBe("text/html; charset=utf-8");
- expect(page.headers.get("set-cookie")).toBeNull();
- expect(await page.text()).toBe("<h1>proxied</h1>");
- // A stream: the first chunk is in the client's hands while the handler is still producing
- // the second — nothing is held back until the end.
- const events = await owner.get(`${BASE}/demo/api/events`);
- expect(events.headers.get("content-type")).toBe("text/event-stream");
- const reader = events.body!.getReader();
- const startedAt = Date.now();
- const first = await reader.read();
- expect(new TextDecoder().decode(first.value)).toBe("data: one\n\n");
- expect(Date.now() - startedAt).toBeLessThan(300);
- const second = await reader.read();
- expect(new TextDecoder().decode(second.value)).toBe("data: two\n\n");
- expect((await reader.read()).done).toBe(true);
- // A redirect, relative to the api mount.
- const moved = await owner.get(`${BASE}/demo/api/moved`);
- expect(moved.status).toBe(302);
- expect(moved.headers.get("location")).toBe("page");
- // And what every existing workflow does is unchanged: JSON in, JSON out.
- const json = await owner.post(`${BASE}/demo/api/count`, {});
- expect(json.headers.get("content-type")).toContain("application/json");
- expect(await json.json()).toEqual({ count: 1 });
- });
-
it("removes the folder and its recorded versions on request", async () => {
await list();
- expect((await owner.delete(`${BASE}/demo`)).status).toBe(204);
+ expect((await owner.delete(`${base}/demo`)).status).toBe(204);
expect(await list()).toEqual([]);
await expect(fs.stat(dir)).rejects.toThrow();
- expect((await owner.get(`${BASE}/demo/api/`)).status).toBe(404);
- expect((await owner.delete(`${BASE}/demo`)).status).toBe(404);
- const history = (await (await owner.get(`${BASE}/demo/history`)).json()) as {
+ expect((await owner.get(`${base}/demo/api/`)).status).toBe(404);
+ expect((await owner.delete(`${base}/demo`)).status).toBe(404);
+ const history = (await (await owner.get(`${base}/demo/history`)).json()) as {
versions: WorkflowVersion[];
};
expect(history.versions).toEqual([]);
});
-
- it("is scoped to the Project's users", async () => {
- const other = apiClient(t.app, (await provisionUser(t.app, "other")).cookie);
- expect((await other.get(BASE)).status).toBe(404);
- expect((await other.get(`${BASE}/demo/ui/index.html`)).status).toBe(404);
- expect((await other.delete(`${BASE}/demo`)).status).toBe(404);
- expect((await owner.get(`${BASE}/demo/ui/index.html`)).status).toBe(200);
- expect((await owner.get(`${BASE}/nope/ui/index.html`)).status).toBe(404);
- expect((await owner.get(`${BASE}/nope/api/`)).status).toBe(404);
- });
});