@niwa-labs/web 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,282 @@
1
+ // The web surface serves the cockpit app and the client modules of the plugins.
2
+ //
3
+ // 1. `/` and every address of the app is the app's page, with the import map first and a policy that names its script
4
+ // 2. the app's files are served with their types; nothing outside the folder, and nothing that is not there, is
5
+ // 3. the catalogue names the modules the host lists, and a module is served only under the id and hash it is listed by
6
+ // 4. a module is built for the browser with the shared modules left as imports the import map resolves
7
+ // 5. a changed module is a new address, and the old one is gone
8
+ // 6. the address is the hash of the bytes served, so other shared modules mean another address
9
+ // 7. without an app the surface serves its pages and no module
10
+
11
+ import { afterEach, expect, test } from "bun:test";
12
+ import { createHash } from "node:crypto";
13
+ import { mkdir, symlink, writeFile } from "node:fs/promises";
14
+ import { join } from "node:path";
15
+
16
+ import { COCKPIT_MODULE, createNiwa, loginWeb, plugin, tempHome, webFetch } from "@niwa-labs/testing";
17
+ import type { WebApp, WebServer } from "../src/index.ts";
18
+
19
+ import { serveWebPages } from "./fixtures/serve-web.ts";
20
+
21
+ const cleanups: Array<() => Promise<void>> = [];
22
+ afterEach(async () => {
23
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
24
+ });
25
+
26
+ const IMPORTS = { react: "/assets/react-abc.js", "react/jsx-runtime": "/assets/jsx-abc.js", "@niwa-labs/cockpit-sdk": "/assets/sdk-abc.js" };
27
+
28
+ type Setup = { web: WebServer; dir: string; app: WebApp };
29
+
30
+ async function setup(options: { app?: boolean; root?: (dir: string) => Promise<string> } = {}): Promise<Setup> {
31
+ const home = await tempHome();
32
+ const dir = join(home.path, "site");
33
+ await mkdir(join(dir, "assets"), { recursive: true });
34
+ await writeFile(join(dir, "index.html"), `<!doctype html><html><head><meta charset="utf-8"><title>niwa</title><script type="module" src="/assets/app.js"></script></head><body><div id="root"></div></body></html>`);
35
+ await writeFile(join(dir, "assets", "app.js"), `console.log("app");`);
36
+ await writeFile(join(dir, "assets", "app.css"), `body { margin: 0 }`);
37
+ await writeFile(join(home.path, "secret.txt"), "secret");
38
+ const module = join(home.path, "module");
39
+ await mkdir(module, { recursive: true });
40
+ await writeFile(join(module, "index.tsx"), `import { definePlugin } from "@niwa-labs/cockpit-sdk";\nimport { helper } from "./helper.ts";\nexport default definePlugin({ id: "demo", setup() { helper(<b>hi</b>); } });\n`);
41
+ await writeFile(join(module, "helper.ts"), `export function helper(value: unknown): unknown { return value; }\n`);
42
+ await writeFile(join(module, "demo.css"), `.demo { color: red }`);
43
+ const host = createNiwa({ home: home.path });
44
+ host.use(plugin("offers", (api) => api.offer(COCKPIT_MODULE, { id: "demo", entry: join(module, "index.tsx"), styles: [join(module, "demo.css")] })));
45
+ await host.serve();
46
+ const app: WebApp = { root: options.root === undefined ? dir : await options.root(dir), imports: IMPORTS };
47
+ const web = await serveWebPages({ home: home.path, port: 0, speaksFor: "owner", ...(options.app === false ? {} : { app }) });
48
+ await loginWeb(web);
49
+ cleanups.push(async () => {
50
+ await web.close();
51
+ await host.close();
52
+ await home.cleanup();
53
+ });
54
+ return { web, dir: module, app };
55
+ }
56
+
57
+ const sha = (text: string): string => `'sha256-${createHash("sha256").update(text).digest("base64")}'`;
58
+
59
+ test("the app's page has the import map before its scripts and a policy that names the map's script", async () => {
60
+ const { web } = await setup();
61
+ for (const path of ["/", "/runs/run-1", "/sessions/s-1/transcript"]) {
62
+ const page = await webFetch(`${web.url}${path}`);
63
+ expect(page.status).toBe(200);
64
+ expect(page.headers.get("content-type")).toBe("text/html; charset=utf-8");
65
+ const body = await page.text();
66
+ const map = /<script type="importmap">(.*?)<\/script>/.exec(body);
67
+ expect(map).not.toBeNull();
68
+ expect(JSON.parse(map![1]!)).toEqual({ imports: IMPORTS });
69
+ expect(body.indexOf('type="importmap"')).toBeLessThan(body.indexOf('type="module"'));
70
+ const policy = page.headers.get("content-security-policy") ?? "";
71
+ expect(policy).toContain(`script-src 'self' ${sha(map![1]!)}`);
72
+ expect(policy).not.toContain("script-src 'unsafe-inline'");
73
+ expect(policy).toContain("connect-src 'self'");
74
+ }
75
+ });
76
+
77
+ test("the app's files are served with their types, and nothing outside the folder is", async () => {
78
+ const { web } = await setup();
79
+ const script = await webFetch(`${web.url}/assets/app.js`);
80
+ expect(script.status).toBe(200);
81
+ expect(script.headers.get("content-type")).toBe("text/javascript; charset=utf-8");
82
+ expect(script.headers.get("x-content-type-options")).toBe("nosniff");
83
+ expect(script.headers.get("cache-control")).toContain("immutable");
84
+ expect(await script.text()).toBe(`console.log("app");`);
85
+ expect((await webFetch(`${web.url}/assets/app.css`)).headers.get("content-type")).toBe("text/css; charset=utf-8");
86
+
87
+ expect((await webFetch(`${web.url}/assets/missing.js`)).status).toBe(404);
88
+ expect((await webFetch(`${web.url}/assets/%2e%2e/index.html`)).status).toBe(404);
89
+ expect((await webFetch(`${web.url}/assets/..%2f..%2fsecret.txt`)).status).toBe(404);
90
+ expect((await webFetch(`${web.url}/assets/%00`)).status).toBe(404);
91
+ // A file that is not there is not a page of the app.
92
+ expect((await webFetch(`${web.url}/favicon.ico`)).status).toBe(404);
93
+ expect((await webFetch(`${web.url}/api/nothing`)).status).toBe(404);
94
+ expect((await webFetch(`${web.url}/runs/run-1`, { method: "POST" })).status).toBe(405);
95
+ // Without the cookie nothing is served.
96
+ expect((await fetch(`${web.url}/assets/app.js`)).status).toBe(401);
97
+ });
98
+
99
+ test("a link inside the folder does not lead out of it, and one that stays inside is a file of the app", async () => {
100
+ const { web, app } = await setup();
101
+ await symlink(join(app.root, "..", "secret.txt"), join(app.root, "assets", "leak.txt"));
102
+ await symlink(join(app.root, "assets", "app.js"), join(app.root, "assets", "alias.js"));
103
+ expect((await webFetch(`${web.url}/assets/leak.txt`)).status).toBe(404);
104
+ expect(await (await webFetch(`${web.url}/assets/alias.js`)).text()).toBe(`console.log("app");`);
105
+ });
106
+
107
+ test("the folder of the app may be named with a trailing slash or through a link", async () => {
108
+ const named = [
109
+ async (site: string) => `${site}/`,
110
+ async (site: string) => {
111
+ await symlink(site, `${site}-link`);
112
+ return `${site}-link`;
113
+ },
114
+ ];
115
+ for (const root of named) {
116
+ const { web } = await setup({ root });
117
+ expect(await (await webFetch(`${web.url}/assets/app.js`)).text()).toBe(`console.log("app");`);
118
+ expect((await webFetch(`${web.url}/assets/../index.html`)).status).toBe(404);
119
+ }
120
+ });
121
+
122
+ type Catalogue = { modules: Array<{ id: string; package: string; version: string; entry: string; hash: string; styles?: string[] }> };
123
+
124
+ test("the catalogue names the host's modules and a module is served only under the id and hash it is listed by", async () => {
125
+ const { web } = await setup();
126
+ const catalogue = (await (await webFetch(`${web.url}/api/catalogue`)).json()) as Catalogue;
127
+ expect(catalogue.modules).toHaveLength(1);
128
+ const [module] = catalogue.modules;
129
+ expect(module).toMatchObject({ id: "demo", package: "offers" });
130
+ expect(module?.hash).toMatch(/^[0-9a-f]{64}$/);
131
+ expect(module?.entry).toBe(`/modules/demo/${module!.hash}/index.js`);
132
+ expect(module?.styles).toHaveLength(1);
133
+
134
+ const code = await webFetch(`${web.url}${module!.entry}`);
135
+ expect(code.status).toBe(200);
136
+ expect(code.headers.get("content-type")).toBe("text/javascript; charset=utf-8");
137
+ const style = await webFetch(`${web.url}${module!.styles![0]}`);
138
+ expect(style.status).toBe(200);
139
+ expect(style.headers.get("content-type")).toBe("text/css; charset=utf-8");
140
+ expect(await style.text()).toBe(".demo { color: red }");
141
+
142
+ const other = "0".repeat(64);
143
+ for (const path of [
144
+ `/modules/demo/${other}/index.js`,
145
+ `/modules/other/${module!.hash}/index.js`,
146
+ `/modules/demo/${module!.hash}/helper.ts`,
147
+ `/modules/demo/${module!.hash}/../../index.js`,
148
+ `/modules/demo/${module!.hash}/style-0-000000000000.css`,
149
+ `/modules/demo/${module!.hash}/style-7-${module!.styles![0]!.match(/-([0-9a-f]{12})\.css$/)![1]!}.css`,
150
+ `/modules/demo`,
151
+ ]) {
152
+ expect((await webFetch(`${web.url}${path}`)).status, path).toBe(404);
153
+ }
154
+ });
155
+
156
+ /** The names a module imports that are not relative paths. */
157
+ function bareImports(code: string): string[] {
158
+ return [...new Bun.Transpiler({ loader: "js" }).scanImports(code).map((entry) => entry.path)].filter((path) => !path.startsWith(".") && !path.startsWith("/"));
159
+ }
160
+
161
+ test("a module is built for the browser with the shared modules left as imports and its own files inlined", async () => {
162
+ const { web } = await setup();
163
+ const [module] = ((await (await webFetch(`${web.url}/api/catalogue`)).json()) as Catalogue).modules;
164
+ const code = await (await webFetch(`${web.url}${module!.entry}`)).text();
165
+ const bare = bareImports(code);
166
+ expect(bare).toContain("@niwa-labs/cockpit-sdk");
167
+ expect(bare).toContain("react/jsx-runtime");
168
+ // Every import the import map has to resolve is one of its names, so the page needs nothing else.
169
+ for (const name of bare) expect(Object.keys(IMPORTS), name).toContain(name);
170
+ // No development runtime, which the production React of the app does not have, and no node module.
171
+ expect(code).not.toContain("jsx-dev-runtime");
172
+ expect(code).not.toMatch(/["'](node|bun):/);
173
+ // The JSX of the entry is compiled to the production runtime, and the file it imports is part of the module.
174
+ expect(code).toContain('"b"');
175
+ expect(code).not.toContain("./helper");
176
+ });
177
+
178
+ test("the address of a module is the hash of the bytes served there, and so is the address of its sheet", async () => {
179
+ const { web } = await setup();
180
+ const [module] = ((await (await webFetch(`${web.url}/api/catalogue`)).json()) as Catalogue).modules;
181
+ const code = await (await webFetch(`${web.url}${module!.entry}`)).text();
182
+ expect(module!.hash).toBe(createHash("sha256").update(code).digest("hex"));
183
+ const style = await (await webFetch(`${web.url}${module!.styles![0]}`)).text();
184
+ expect(module!.styles![0]).toBe(`/modules/demo/${module!.hash}/style-0-${createHash("sha256").update(style).digest("hex").slice(0, 12)}.css`);
185
+ });
186
+
187
+ test("the same source built against other shared modules is served at another address", async () => {
188
+ const { web, dir, app } = await setup();
189
+ await mkdir(join(dir, "node_modules", "tinydep"), { recursive: true });
190
+ await writeFile(join(dir, "node_modules", "tinydep", "package.json"), `{ "name": "tinydep", "type": "module", "main": "index.js" }`);
191
+ await writeFile(join(dir, "node_modules", "tinydep", "index.js"), `export const tiny = "${"x".repeat(2_000)}";\n`);
192
+ await writeFile(join(dir, "helper.ts"), `import { tiny } from "tinydep";\nexport function helper(value: unknown): unknown { return [value, tiny]; }\n`);
193
+
194
+ // One page shares `tinydep` and leaves it an import; the other carries its own copy of it.
195
+ const sharing = await serveWebPages({ home: join(app.root, ".."), port: 0, speaksFor: "owner", app: { root: app.root, imports: { ...IMPORTS, tinydep: "/assets/tinydep.js" } } });
196
+ cleanups.push(() => sharing.close());
197
+ await loginWeb(sharing);
198
+
199
+ const [bundled] = ((await (await webFetch(`${web.url}/api/catalogue`)).json()) as Catalogue).modules;
200
+ const [shared] = ((await (await webFetch(`${sharing.url}/api/catalogue`)).json()) as Catalogue).modules;
201
+ const bundledCode = await (await webFetch(`${web.url}${bundled!.entry}`)).text();
202
+ const sharedCode = await (await webFetch(`${sharing.url}${shared!.entry}`)).text();
203
+ expect(bundledCode).not.toBe(sharedCode);
204
+ expect(bundledCode.length).toBeGreaterThan(sharedCode.length);
205
+ // Other bytes, other name: a browser that kept one of them is not served the other under its address.
206
+ expect(bundled!.entry).not.toBe(shared!.entry);
207
+ });
208
+
209
+ test("a changed module is a new address, and the old address is gone", async () => {
210
+ const { web, dir } = await setup();
211
+ const [before] = ((await (await webFetch(`${web.url}/api/catalogue`)).json()) as Catalogue).modules;
212
+ expect((await webFetch(`${web.url}${before!.entry}`)).status).toBe(200);
213
+
214
+ await writeFile(join(dir, "helper.ts"), `export function helper(value: unknown): unknown { return [value, "changed"]; }\n`);
215
+ const [after] = ((await (await webFetch(`${web.url}/api/catalogue`)).json()) as Catalogue).modules;
216
+ expect(after?.hash).not.toBe(before?.hash);
217
+ expect((await webFetch(`${web.url}${before!.entry}`)).status).toBe(404);
218
+ const code = await (await webFetch(`${web.url}${after!.entry}`)).text();
219
+ expect(code).toContain("changed");
220
+ });
221
+
222
+ test("a module that cannot be built is a server error that says why", async () => {
223
+ const { web, dir } = await setup();
224
+ await writeFile(join(dir, "helper.ts"), `export function helper( {\n`);
225
+ const [broken] = ((await (await webFetch(`${web.url}/api/catalogue`)).json()) as Catalogue).modules;
226
+ const failed = await webFetch(`${web.url}${broken!.entry}`);
227
+ expect(failed.status).toBe(500);
228
+ expect(await failed.text()).toContain("could not be built");
229
+ });
230
+
231
+ test("without an app the surface serves its pages and no module", async () => {
232
+ const { web } = await setup({ app: false });
233
+ const page = await webFetch(web.url);
234
+ expect(page.status).toBe(200);
235
+ expect(await page.text()).toContain("EventSource");
236
+ const [module] = ((await (await webFetch(`${web.url}/api/catalogue`)).json()) as Catalogue).modules;
237
+ expect((await webFetch(`${web.url}${module!.entry}`)).status).toBe(404);
238
+ expect((await webFetch(`${web.url}/assets/app.js`)).status).toBe(404);
239
+ });
240
+
241
+ test("a module that imports a subpath of a shared package the page does not map is refused at its build", async () => {
242
+ const { web, dir } = await setup();
243
+ // The page's map has `react` and `react/jsx-runtime`; `react/compiler-runtime` is not in it.
244
+ await writeFile(join(dir, "helper.ts"), `import { c } from "react/compiler-runtime";\nexport function helper(value: unknown): unknown { return [c, value]; }\n`);
245
+ const [module] = ((await (await webFetch(`${web.url}/api/catalogue`)).json()) as Catalogue).modules;
246
+ const failed = await webFetch(`${web.url}${module!.entry}`);
247
+ expect(failed.status).toBe(500);
248
+ const body = await failed.text();
249
+ expect(body).toContain("react/compiler-runtime is not shared by the cockpit");
250
+ expect(body).toContain("react/jsx-runtime");
251
+ });
252
+
253
+ test("a page of the app whose address ends like a file name is the app's page for a browser, and a missing file for anything else", async () => {
254
+ const { web } = await setup();
255
+ const opening = { headers: { accept: "text/html,application/xhtml+xml,*/*;q=0.8" } };
256
+ for (const path of ["/reports/v1.2", "/runs/run-1.5", "/notes.md"]) {
257
+ const page = await webFetch(`${web.url}${path}`, opening);
258
+ expect(page.status, path).toBe(200);
259
+ expect(await page.text(), path).toContain('type="importmap"');
260
+ expect((await webFetch(`${web.url}${path}`)).status, path).toBe(404);
261
+ }
262
+ // An asset is never the page, whatever is accepted.
263
+ expect((await webFetch(`${web.url}/assets/missing.js`, opening)).status).toBe(404);
264
+ });
265
+
266
+ // What the server answers itself, by the first segment of the address. The cockpit refuses a module page at any of these first
267
+ // segments, so an address the app routes is never also one of these; the SDK's tests pin the same list.
268
+ const ENDPOINTS: Record<string, string[]> = {
269
+ exact: ["/login", "/events", "/feed", "/resolve", "/answer"],
270
+ under: ["/api/x", "/assets/x", "/modules/x", "/trace/x", "/trace-data/x"],
271
+ };
272
+
273
+ test("the addresses the cockpit reserves for the server are answered by the server, and the cockpit's own journal is the app's page", async () => {
274
+ const { web } = await setup();
275
+ const opening = { headers: { accept: "text/html" }, redirect: "manual" as const };
276
+ for (const path of [...ENDPOINTS.exact!, ...ENDPOINTS.under!]) {
277
+ const answer = await webFetch(`${web.url}${path}`, opening);
278
+ expect(answer.headers.get("content-type"), path).not.toContain("text/html");
279
+ await answer.body?.cancel();
280
+ }
281
+ expect(await (await webFetch(`${web.url}/journal`, opening)).text()).toContain('type="importmap"');
282
+ });
@@ -0,0 +1,245 @@
1
+ // What a page may call is the grant's matter, not a list of the web surface.
2
+ //
3
+ // 1. a page that speaks for the owner calls any action the host declares, not only the ones a list knew
4
+ // 2. a plain client's call is decided by its grant: allowed under a rule, refused with 403 without one
5
+ // 3. the viewer says who is looking and which actions the grant lets through; the info lists the same actions
6
+ // 4. a name that is no action name is a bad request, and an action nobody declared is the host's refusal
7
+ // 5. the journal feed starts after a position the page chooses, from the end the info names
8
+ // 6. the input of a call is any JSON value: its shape is the action's schema to judge
9
+ // 7. a connection that may not read the journal is refused 403 by the history and the stream, and a stream opens only once accepted
10
+
11
+ import { afterEach, expect, test } from "bun:test";
12
+
13
+ import { action, actionName, record } from "@niwa-labs/core";
14
+ import { connectAsOwner, createNiwa, loginWeb, plugin, tempHome, webFetch } from "@niwa-labs/testing";
15
+ import type { WebOptions, WebServer } from "../src/index.ts";
16
+ import { z } from "zod";
17
+
18
+ import { serveWebPages } from "./fixtures/serve-web.ts";
19
+
20
+ const cleanups: Array<() => Promise<void>> = [];
21
+ afterEach(async () => {
22
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
23
+ });
24
+
25
+ const Empty = z.object({});
26
+ const Ok = z.object({ ok: z.boolean() });
27
+ // An output schema that does something to what it checks: running it twice is not running it once.
28
+ const Next = z.number().transform((n) => n + 1);
29
+ const When = z.object({ at: z.date() });
30
+
31
+ const Note = record("demo.note", z.object({ n: z.number() }), { open: true });
32
+ const Other = record("demo.other", z.object({ n: z.number() }), { open: true });
33
+
34
+ const demo = plugin("demo", (api) => {
35
+ api.declare(Note);
36
+ api.declare(Other);
37
+ api.action(action("demo.next", { description: "Counts.", input: Empty, output: Next, recovery: "repeat", effect: "read", run: () => 1 }));
38
+ api.action(action("demo.when", { description: "Dates.", input: Empty, output: When, recovery: "repeat", effect: "read", run: () => ({ at: new Date("2026-11-21T10:00:00Z") }) }));
39
+ api.action(action("demo.read", { description: "Reads.", input: Empty, output: Ok, recovery: "repeat", effect: "read", run: () => ({ ok: true }) }));
40
+ api.action(action("demo.echo", { description: "Echoes a text.", input: z.string(), output: z.string(), recovery: "repeat", effect: "read", run: (text: string) => text }));
41
+ api.action(action("demo.write", { description: "Writes.", input: Empty, output: Ok, recovery: "do-not-repeat", effect: "write", run: () => ({ ok: true }) }));
42
+ });
43
+
44
+ async function hosted(): Promise<string> {
45
+ const home = await tempHome();
46
+ const host = createNiwa({ home: home.path });
47
+ host.use(demo);
48
+ await host.serve();
49
+ cleanups.push(async () => {
50
+ await host.close();
51
+ await home.cleanup();
52
+ });
53
+ return home.path;
54
+ }
55
+
56
+ async function served(home: string, speaksFor?: "owner", ownerActions?: NonNullable<WebOptions["ownerActions"]>): Promise<WebServer> {
57
+ const web = await serveWebPages({ home, port: 0, ...(speaksFor === undefined ? {} : { speaksFor }), ...(ownerActions === undefined ? {} : { ownerActions }) });
58
+ cleanups.push(() => web.close());
59
+ await loginWeb(web);
60
+ return web;
61
+ }
62
+
63
+ const call = (web: WebServer, action: string, input: unknown = {}): Promise<Response> =>
64
+ webFetch(`${web.url}/api/call`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ action, input }) });
65
+
66
+ /** The default grant: what a client that has no token of its own may do. */
67
+ async function grantDefault(home: string, rules: string[]): Promise<void> {
68
+ const owner = await connectAsOwner(home);
69
+ try {
70
+ await owner.call("access.profile.set" as never, { name: "default", rules } as never);
71
+ } finally {
72
+ await owner.close();
73
+ }
74
+ }
75
+
76
+ test("a page that speaks for the owner calls an action no list ever named", async () => {
77
+ const web = await served(await hosted(), "owner");
78
+ const answer = await call(web, "demo.write");
79
+ expect(answer.status).toBe(200);
80
+ expect(await answer.json()).toEqual({ ok: true });
81
+ });
82
+
83
+ test("a call carries any JSON value as its input, and the action's schema decides whether it fits", async () => {
84
+ const web = await served(await hosted(), "owner");
85
+ const echoed = await call(web, "demo.echo", "hello");
86
+ expect(echoed.status).toBe(200);
87
+ expect(await echoed.json()).toBe("hello");
88
+ // A value the schema refuses is the host's refusal of the call, not a malformed request.
89
+ expect((await call(web, "demo.echo", { text: "hello" })).status).toBe(409);
90
+ });
91
+
92
+ test("a plain client's call is allowed by a rule of its grant and refused with 403 without one", async () => {
93
+ const home = await hosted();
94
+ const web = await served(home);
95
+ const refused = await call(web, "demo.read");
96
+ expect(refused.status).toBe(403);
97
+ expect(await refused.text()).toContain("not in the grant");
98
+
99
+ await grantDefault(home, ["demo.read"]);
100
+ expect((await call(web, "demo.read")).status).toBe(200);
101
+ expect((await call(web, "demo.write")).status).toBe(403);
102
+ });
103
+
104
+ test("a name that is no action name is a bad request, and an action nobody declared is refused by the host", async () => {
105
+ const web = await served(await hosted(), "owner");
106
+ expect((await call(web, "Not An Action!")).status).toBe(400);
107
+ expect((await call(web, "")).status).toBe(400);
108
+ const unknown = await call(web, "demo.nothing");
109
+ expect(unknown.status).toBe(409);
110
+ });
111
+
112
+ test("the viewer is the owner with every action, or a client with the actions its grant lets through", async () => {
113
+ const home = await hosted();
114
+ const ownerWeb = await served(home, "owner");
115
+ const owner = (await (await webFetch(`${ownerWeb.url}/api/viewer`)).json()) as { id: string; owner: boolean; actions: string[] };
116
+ expect(owner).toMatchObject({ id: "owner", owner: true });
117
+ expect(owner.actions).toEqual(expect.arrayContaining(["demo.read", "demo.write", "niwa.cockpit.catalog"]));
118
+
119
+ const plainWeb = await served(home);
120
+ // A client that may not read its own rules is told apart from one that may call nothing only by what it can see.
121
+ const blind = (await (await webFetch(`${plainWeb.url}/api/viewer`)).json()) as { owner: boolean; actions: string[] };
122
+ expect(blind).toEqual({ id: "web", owner: false, actions: [] });
123
+
124
+ await grantDefault(home, ["access.mine", "demo.read"]);
125
+ const limited = (await (await webFetch(`${plainWeb.url}/api/viewer`)).json()) as { id: string; owner: boolean; actions: string[] };
126
+ expect(limited.owner).toBe(false);
127
+ expect(limited.id).toStartWith("web");
128
+ expect(limited.actions).toEqual(["access.mine", "demo.read"]);
129
+ const info = (await (await webFetch(`${plainWeb.url}/api/info`)).json()) as { actions: string[] };
130
+ expect(info.actions).toEqual(limited.actions);
131
+ });
132
+
133
+ /** The records an event stream sends, up to the first `count`, as the page's `fetch` reads them. */
134
+ async function eventsOf(url: string, count: number, headers: Record<string, string> = {}): Promise<Array<{ eventId: number; seq: number; type: string }>> {
135
+ const abort = new AbortController();
136
+ const response = await webFetch(url, { headers: { accept: "text/event-stream", ...headers }, signal: abort.signal });
137
+ expect(response.status).toBe(200);
138
+ const reader = response.body!.getReader();
139
+ const decoder = new TextDecoder();
140
+ const found: Array<{ eventId: number; seq: number; type: string }> = [];
141
+ let buffer = "";
142
+ while (found.length < count) {
143
+ const { done, value } = await reader.read();
144
+ if (done) break;
145
+ buffer += decoder.decode(value, { stream: true });
146
+ for (let end = buffer.indexOf("\n\n"); end >= 0; end = buffer.indexOf("\n\n")) {
147
+ const block = buffer.slice(0, end);
148
+ buffer = buffer.slice(end + 2);
149
+ const data = /^data: (.*)$/m.exec(block)?.[1];
150
+ const id = /^id: (\d+)$/m.exec(block)?.[1];
151
+ if (data !== undefined && id !== undefined) found.push({ eventId: Number(id), ...(JSON.parse(data) as { seq: number; type: string }) });
152
+ }
153
+ }
154
+ abort.abort();
155
+ return found;
156
+ }
157
+
158
+ test("the journal feed starts after the position the page names, and the info says where the journal ends", async () => {
159
+ const home = await hosted();
160
+ const web = await served(home, "owner");
161
+ const owner = await connectAsOwner(home);
162
+ cleanups.push(() => owner.close());
163
+ for (let n = 0; n < 3; n += 1) await owner.emit(Note, { n });
164
+
165
+ const end = ((await (await webFetch(`${web.url}/api/info`)).json()) as { seq: number }).seq;
166
+ expect(end).toBeGreaterThan(3);
167
+
168
+ const all = await eventsOf(`${web.url}/api/events?after=0`, end);
169
+ expect(all.map((record) => record.seq)).toEqual(Array.from({ length: end }, (_, index) => index + 1));
170
+ expect(all.every((record) => record.eventId === record.seq)).toBe(true);
171
+
172
+ const after = end - 2;
173
+ expect((await eventsOf(`${web.url}/api/events?after=${String(after)}`, 2)).map((record) => record.seq)).toEqual([end - 1, end]);
174
+ // A reconnecting page resumes from the id of the last record it saw; that wins over the query.
175
+ expect((await eventsOf(`${web.url}/api/events?after=0`, 1, { "last-event-id": String(end - 1) })).map((record) => record.seq)).toEqual([end]);
176
+
177
+ const history = (await (await webFetch(`${web.url}/api/history?after=${String(after)}`)).json()) as Array<{ seq: number }>;
178
+ expect(history.map((record) => record.seq)).toEqual([end - 1, end]);
179
+ expect((await webFetch(`${web.url}/api/events?after=-1`)).status).toBe(400);
180
+ expect((await webFetch(`${web.url}/api/events?after=x`)).status).toBe(400);
181
+ });
182
+
183
+ test("a connection the grant does not let read the journal is refused 403 by the history and by the stream, before it opens", async () => {
184
+ const home = await hosted();
185
+ const web = await served(home);
186
+ await grantDefault(home, ["access.mine", "niwa.describe"]);
187
+ expect((await webFetch(`${web.url}/api/history?after=0`)).status).toBe(403);
188
+ const stream = await webFetch(`${web.url}/api/events?after=0`, { headers: { accept: "text/event-stream" } });
189
+ expect(stream.status).toBe(403);
190
+ expect(stream.headers.get("content-type")).not.toContain("text/event-stream");
191
+
192
+ // Once the grant lets the connection read, the stream opens, and it does so on a journal with nothing after the position.
193
+ await grantDefault(home, ["niwa.records.read"]);
194
+ const abort = new AbortController();
195
+ const open = await webFetch(`${web.url}/api/events?after=999999`, { headers: { accept: "text/event-stream" }, signal: abort.signal });
196
+ try {
197
+ expect(open.status).toBe(200);
198
+ expect(open.headers.get("content-type")).toContain("text/event-stream");
199
+ } finally {
200
+ abort.abort();
201
+ }
202
+ });
203
+
204
+ test("a page asks for history and its live continuation with one query", async () => {
205
+ const home = await hosted();
206
+ const web = await served(home, "owner");
207
+ const owner = await connectAsOwner(home);
208
+ cleanups.push(() => owner.close());
209
+ await owner.emit(Note, { n: 1 });
210
+ await owner.emit(Other, { n: 2 });
211
+ await owner.emit(Note, { n: 3 });
212
+
213
+ const ask = (params: Record<string, string>): string => `?${new URLSearchParams(params).toString()}`;
214
+ const notes = JSON.stringify({ types: ["demo.note"] });
215
+ const history = (await (await webFetch(`${web.url}/api/history${ask({ after: "0", query: notes })}`)).json()) as Array<{ type: string; data: { n: number } }>;
216
+ expect(history.map((record) => [record.type, record.data.n])).toEqual([["demo.note", 1], ["demo.note", 3]]);
217
+
218
+ const byData = JSON.stringify({ types: ["demo.*"], filter: { n: 2 } });
219
+ const filtered = (await (await webFetch(`${web.url}/api/history${ask({ after: "0", query: byData })}`)).json()) as Array<{ type: string }>;
220
+ expect(filtered.map((record) => record.type)).toEqual(["demo.other"]);
221
+
222
+ // The live continuation answers the same query: the other type never arrives.
223
+ const feed = await eventsOf(`${web.url}/api/events${ask({ after: "0", query: notes })}`, 2);
224
+ expect(feed.map((record) => record.type)).toEqual(["demo.note", "demo.note"]);
225
+
226
+ for (const bad of ["{", JSON.stringify({ types: ["!demo.note"] }), JSON.stringify({ from: 3 }), JSON.stringify({ nope: 1 })]) {
227
+ expect((await webFetch(`${web.url}/api/history${ask({ after: "0", query: bad })}`)).status).toBe(400);
228
+ expect((await webFetch(`${web.url}/api/events${ask({ after: "0", query: bad })}`)).status).toBe(400);
229
+ }
230
+ });
231
+
232
+ test("a call answers with the result the host returned, whether or not the page has a hook for the action", async () => {
233
+ const home = await hosted();
234
+ const hooked = (name: string, output: z.ZodType) => ({ ref: { name: actionName(name), input: Empty, output } });
235
+ const hooks = await served(home, "owner", [hooked("demo.next", Next), hooked("demo.when", When)]);
236
+ const plain = await served(home, "owner");
237
+ for (const web of [hooks, plain]) {
238
+ // The host's result is 2; the transform is not run again on its way to the page.
239
+ expect(await (await call(web, "demo.next")).json()).toBe(2);
240
+ // A date is its text on the wire; a hook's schema, which wants a date, does not refuse what the host made of it.
241
+ const when = await call(web, "demo.when");
242
+ expect(when.status).toBe(200);
243
+ expect(await when.json()).toEqual({ at: "2026-11-21T10:00:00.000Z" });
244
+ }
245
+ });
@@ -0,0 +1,57 @@
1
+ // A refusal by the host is told as one, whichever route met it.
2
+ //
3
+ // 1. with the switch of access off, a plain client's call is refused with 403 although no grant is named
4
+ // 2. the answer and the resolve of a page that is refused are 403 too, and so are the feed and the history
5
+
6
+ import { afterEach, expect, test } from "bun:test";
7
+
8
+ import { connectAsOwner, createNiwa, loginWeb, requests, tempHome, webFetch } from "@niwa-labs/testing";
9
+ import type { WebServer } from "../src/index.ts";
10
+
11
+ import { serveWebPages } from "./fixtures/serve-web.ts";
12
+
13
+ const cleanups: Array<() => Promise<void>> = [];
14
+ afterEach(async () => {
15
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
16
+ });
17
+
18
+ const JSON_HEADERS = { "content-type": "application/json" };
19
+
20
+ async function plainWeb(): Promise<{ home: string; web: WebServer }> {
21
+ const home = await tempHome();
22
+ const host = createNiwa({ home: home.path });
23
+ host.use(requests());
24
+ await host.serve();
25
+ const web = await serveWebPages({ home: home.path, port: 0 });
26
+ cleanups.push(async () => {
27
+ await web.close();
28
+ await host.close();
29
+ await home.cleanup();
30
+ });
31
+ await loginWeb(web);
32
+ return { home: home.path, web };
33
+ }
34
+
35
+ async function switchOff(home: string): Promise<void> {
36
+ const owner = await connectAsOwner(home);
37
+ try {
38
+ await owner.call("access.switch" as never, { all: "off" } as never);
39
+ } finally {
40
+ await owner.close();
41
+ }
42
+ }
43
+
44
+ const post = (web: WebServer, path: string, body: unknown): Promise<Response> =>
45
+ webFetch(`${web.url}${path}`, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body) });
46
+
47
+ test("with the switch off every route answers a plain client's call with 403, not with a conflict or a failure", async () => {
48
+ const { home, web } = await plainWeb();
49
+ await switchOff(home);
50
+
51
+ expect((await post(web, "/api/call", { action: "niwa.describe", input: {} })).status).toBe(403);
52
+ expect((await post(web, "/answer", { request: "req-1", answer: { ids: ["yes"] } })).status).toBe(403);
53
+ expect((await post(web, "/resolve", { invocation: "inv-1", choice: "retry" })).status).toBe(403);
54
+ expect((await webFetch(`${web.url}/feed`)).status).toBe(403);
55
+ expect((await webFetch(`${web.url}/events`)).status).toBe(403);
56
+ expect((await webFetch(`${web.url}/api/history?after=0`)).status).toBe(403);
57
+ });