config-template / tests / worker.test.mjsmain at 3b8ad1b
// tests/worker.test.mjs — the mind's wiring (../worker.ts): which hostname goes where and who is
// let in, what a mail and a publish do. The class is the real one, loaded as the mind loads it
// (testing/mind-loader.mjs of /repos/stdlib), with a fake `itx` that records what it is asked.
// Run it from the repo's root with `node --test "tests/*.test.mjs"`.
import "@repos/stdlib/testing/mind-loader.mjs";
import assert from "node:assert/strict";
import { existsSync, readFileSync } from "node:fs";
import { test } from "node:test";
const { default: Config } = await import("../worker.ts");
const repoFile = (path) => new URL(`../${path}`, import.meta.url);
for (const app of ["dash", "docs", "tasks", "onboarding"])
test(`${app}.<domain>: the app's name and icon are for anyone, and everything else is for members`, async () => {
const mind = mindAt("example.com");
const ask = (path) => mind.config.fetch(new Request(`https://${app}.example.com${path}`));
const described = await ask("/.well-known/iterate-app");
assert.equal(described.status, 200);
assert.equal((await described.json()).for, "members");
const icon = await ask("/icon.svg");
assert.equal(icon.headers.get("content-type"), "image/svg+xml");
assert.equal(await icon.text(), readFileSync(repoFile("profile/icon.svg"), "utf8"));
// nobody is signed in: the page and its files answer the sign-in
for (const path of ["/", "/app.js", "/theme.css", "/board.json", "/steps.json"])
assert.equal((await ask(path)).status, 401, path);
// a member: the guard lets them in
mind.config.auth = { ...mind.config.auth, require: () => null };
const page = await ask("/");
assert.equal(page.headers.get("content-type"), "text/html; charset=utf-8");
assert.equal(
await page.text(),
readFileSync(repoFile(`../${app}/index.html`), "utf8"),
);
// every app serves the one theme, which is /repos/stdlib's
assert.equal(
await (await ask("/theme.css")).text(),
readFileSync(repoFile("../stdlib/theme.css"), "utf8"),
);
});
test("a press of an onboarding step from another origin is refused even with a member's session: no cross-site disconnect", async () => {
const mind = mindAt("example.com");
mind.config.getItx = () => {
throw new Error("the guard let a request through to the mind");
};
const press = (headers) =>
mind.config.fetch(
new Request("https://onboarding.example.com/steps/connect-iterate-cloud/disconnect", {
method: "POST",
headers: {
"x-itx-principal": JSON.stringify({ actor: "user-1", email: "owner@example.org" }),
...headers,
},
}),
);
const sameSite = await press({ origin: "https://blog.example.com", "sec-fetch-site": "same-site" });
assert.equal(sameSite.status, 403);
const crossSite = await press({ origin: "https://evil.example", "sec-fetch-site": "cross-site" });
assert.equal(crossSite.status, 403);
});
test("an onboarding hook that fails does not stop the hooks that look at every event, and the failure is thrown after them", async () => {
const mind = mindAt("example.com");
// the onboarding step cannot read the mind: its hook fails on a publish
mind.itx.whoami = async () => {
throw new Error("the mind did not answer");
};
// a context that the table of context descriptions names, with no description yet
mind.itx.contexts = { list: async () => [{ path: "/secrets/openai", description: "" }] };
await assert.rejects(
mind.config.processEvent({
event: { type: "events.iterate.com/mind/worker-updated", path: "/", offset: 9, payload: {} },
itx: mind.itx,
}),
/the mind did not answer/,
);
// the hook of every event still described the context (its description, then its title)
assert.deepEqual(
mind.appended.filter(({ path }) => path === "/secrets/openai").map(({ event }) => event.type),
["events.iterate.com/itx/described", "events.iterate.com/itx/described"],
);
});
test("tasks.<domain> tells its page which repo the board shows: /repos/task-board", async () => {
const mind = mindAt("example.com");
mind.config.auth = { ...mind.config.auth, require: () => null };
const board = await mind.config.fetch(new Request("https://tasks.example.com/board.json"));
assert.deepEqual(await board.json(), { repo: "/repos/task-board", retiredAgents: [] });
});
test("git.<domain> is the git app's, with no guard before it: it serves its own files to anyone, and no repo, since none is public", async () => {
const mind = mindAt("example.com");
const ask = (path) => mind.config.fetch(new Request(`https://git.example.com${path}`));
const list = await ask("/");
assert.equal(list.status, 200);
const html = await list.text();
assert.ok(html.includes("The repos of example.com"));
assert.ok(!html.includes("git clone"));
assert.ok(html.includes(`<a href="/sign-in">Sign in</a>`));
// the mind's icon and the one theme, as every app serves them
assert.equal(
await (await ask("/icon.svg")).text(),
readFileSync(repoFile("profile/icon.svg"), "utf8"),
);
assert.equal(
await (await ask("/theme.css")).text(),
readFileSync(repoFile("../stdlib/theme.css"), "utf8"),
);
// nobody is signed in: every repo answers the sign-in
for (const name of ["config", "stdlib", "kernel"])
assert.equal((await ask(`/repos/${name}`)).status, 401, name);
});
test("any other hostname is the public website, for anyone: the profile, the icon, the homepage, and nothing else", async () => {
const mind = mindAt("example.com");
const ask = (path, method = "GET") =>
mind.config.fetch(new Request(`https://example.com${path}`, { method }));
const profile = await ask("/.well-known/iterate-profile");
assert.deepEqual(
{
status: profile.status,
cors: profile.headers.get("access-control-allow-origin"),
cache: profile.headers.get("cache-control"),
body: await profile.json(),
},
{
status: 200,
cors: "*",
cache: "public, max-age=300",
body: { name: "example.com", description: "", icon: "https://example.com/favicon.svg" },
},
);
for (const path of ["/favicon.svg", "/favicon.ico"]) {
const icon = await ask(path);
assert.deepEqual(
{
type: icon.headers.get("content-type"),
policy: icon.headers.get("content-security-policy"),
body: await icon.text(),
},
{
type: "image/svg+xml",
policy: "default-src 'none'; style-src 'unsafe-inline'; sandbox",
body: readFileSync(repoFile("profile/icon.svg"), "utf8"),
},
);
}
const html = await (await ask("/")).text();
assert.match(html, /<title>example\.com<\/title>/);
assert.match(html, /<h1>example\.com<\/h1>/);
assert.match(html, /<a href="https:\/\/dash\.example\.com\/">Open Dash<\/a>/);
// a name that is no app's gets the same website
const elsewhere = await mind.config.fetch(new Request("https://www.example.com/"));
assert.equal(await elsewhere.text(), html);
assert.deepEqual(
{
head: (await ask("/.well-known/iterate-profile", "HEAD")).status,
post: (await ask("/.well-known/iterate-profile", "POST")).status,
postHome: (await ask("/", "POST")).status,
anyOtherPath: (await ask("/else")).status,
theFolder: (await ask("/profile/profile.json")).status,
// the old template's page for who is signed in is not here
me: (await ask("/me")).status,
},
{ head: 200, post: 405, postHome: 404, anyOtherPath: 404, theFolder: 404, me: 404 },
);
assert.deepEqual(await mind.config.profile(), {
name: "example.com",
description: "",
icon: "https://example.com/favicon.svg",
problem: undefined,
});
});
test("a publish installs the agents from stdlib's module, tells the Dash which file of this repo holds the kind, and makes the repo whose tasks the board shows", async () => {
const mind = mindAt("example.com");
await mind.config.processEvent({
event: { type: "events.iterate.com/mind/worker-updated", path: "/", offset: 9, payload: {} },
itx: mind.itx,
});
assert.deepEqual(
mind.enabled.map(({ path, name, spec }) => ({ path, name, mainModule: spec.mainModule })),
[{ path: "/agents", name: "agents", mainModule: "stdlib/agents.ts" }],
);
const kinds = JSON.parse(mind.kv["agent-kinds"]);
assert.deepEqual(kinds, { agent: "agent-kinds/agent.ts" });
// the Dash reads the file from /repos/config by this path
assert.equal(existsSync(repoFile(kinds.agent)), true);
// a mind born from this config has no such repo yet: it is made empty, and making it again is nothing
assert.deepEqual(mind.made, ["/repos/task-board"]);
// the onboarding app's step read the new mind, and wrote what it found on its own log
assert.deepEqual(
mind.appended
.filter(({ path }) => path === "/apps/onboarding")
.map(({ event }) => ({ type: event.type, payload: event.payload })),
[
{
type: "onboarding/step-checked",
payload: {
step: "connect-iterate-cloud",
facts: { canSign: false, meld: false, openai: "unset", exa: "unset" },
},
},
],
);
});
test("another mind's event goes to the onboarding app alone, and one that is not iterate's does nothing", async () => {
const mind = mindAt("example.com");
await mind.config.processMindEvent({
event: {
type: "events.iterate.com/cloud/enrolled",
path: "/minds/someone-else/cloud",
offset: 3,
payload: {},
source: { signer: { principal: { kind: "mind", actor: "someone-else" } } },
},
mind: "someone-else",
itx: mind.itx,
});
assert.deepEqual(mind.appended, []);
});
test("an event that is no case's still reaches the hooks that look at every event", async () => {
const mind = mindAt("example.com");
// a context is born that the table of context descriptions names
await mind.config.processEvent({
event: { type: "events.iterate.com/itx/created", path: "/secrets/openai", offset: 1 },
itx: mind.itx,
});
assert.deepEqual(
mind.appended.map(({ path, event }) => ({ path, type: event.type, payload: event.payload })),
[
{
path: "/secrets/openai",
type: "events.iterate.com/itx/described",
payload: {
description:
"The secret openai: its value stays in the vault, and this log records when it was set, refreshed and used.",
},
},
],
);
});
// ── the fixture ──
/** The mind's worker with a mind behind it at `zone`: a fake `itx` that records each append, each
* processor it is told to enable, and what its kv holds. Nobody is signed in. */
function mindAt(zone) {
const appended = [];
const enabled = [];
const kv = {};
const made = [];
const context = (path) => ({
append: async (...events) => {
appended.push(...events.map((event) => ({ path, event })));
return events.map((event, index) => ({ ...event, offset: appended.length - events.length + index + 1 }));
},
// every log is empty, and no rule is set: a new mind
readEvents: async () => ({ events: [], atHead: true, scannedThroughOffset: 0 }),
rewriteRules: { get: async () => null, list: async () => [] },
processors: {
enable: async (name, spec) => void enabled.push({ path, name, spec }),
disable: async () => {},
list: async () => [],
},
});
const itx = {
...context("/"),
cd: context,
url: async () => `https://${zone}/`,
whoami: async () => ({ mindSlug: `iterate.${zone}` }),
// what the onboarding step's check reads of a new mind: a stack that publishes no key to sign
// with, and a vault with no secret
fetch: async () => new Response("Not found\n", { status: 404 }),
secrets: { describe: async () => ({ set: false }), list: async () => [] },
kv: {
get: async (key) => kv[key] || null,
put: async (key, value) => {
kv[key] = value;
return { ok: true };
},
},
contexts: { list: async () => [] },
repos: { create: async (path) => (made.push(path), { path }) },
[Symbol.dispose]() {},
};
const config = new Config({ waitUntil() {} }, { ITX: {} });
config.getItx = () => itx;
return { config, itx, appended, enabled, kv, made };
}