Skip to content
Source
Sign inSign up
samwillis/neonbricks
Open History to see the last commit

test-access.ts

286 lines8.5 KB

1import assert from "node:assert/strict";
2import "./node-websocket";
3import { randomUUID } from "node:crypto";
4import {
5 createRealtimeClient,
6 type SealedLiveQuery,
7} from "@neon/realtime/client";
8import { pool } from "../src/server/db";
9import type { SceneRow, Receipt } from "../src/shared/types";
10const base = (process.env.TEST_API_URL || process.env.VITE_API_URL!).replace(
11 /\/$/,
12 "",
13);
14async function request(
15 token: string,
16 path: string,
17 body?: unknown,
18 method?: string,
19) {
20 const response = await fetch(`${base}/api${path}`, {
21 method: method || (body === undefined ? "GET" : "POST"),
22 headers: {
23 "Content-Type": "application/json",
24 ...(token ? { Authorization: `Bearer ${token}` } : {}),
25 },
26 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
27 });
28 return { status: response.status, data: await response.json() };
30async function ok(token: string, path: string, body?: unknown) {
31 const r = await request(token, path, body);
32 assert.ok(r.status < 300, `${r.status}: ${r.data.error}`);
33 return r.data;
35const session = async () =>
36 (await ok("", "/session", { name: "Access qualification", color: "#289b74" }))
37 .token;
38const p = () => ({
39 id: randomUUID(),
40 key: "brick-1x1",
41 color: "#289b74",
42 position: { x: 0, y: 0, z: 0 },
43 rotation: 0,
44});
45const clients: ReturnType<typeof createRealtimeClient>[] = [],
46 timers: ReturnType<typeof setInterval>[] = [];
47try {
48 const [a, b] = await Promise.all([session(), session()]);
49 const world = await ok(a, "/worlds", {
50 title: "Access qualification — disposable",
51 starter: "empty",
52 });
53 const [ja, jb] = await Promise.all([
54 ok(a, `/worlds/${world.slug}/join`, {}),
55 ok(b, `/worlds/${world.slug}/join`, {}),
56 ]);
57 const client = createRealtimeClient({
58 url: process.env.VITE_NEON_REALTIME_URL!,
59 });
60 clients.push(client);
61 const subscriptions = [];
62 for (const kind of ["scene", "presence", "history"]) {
63 const seal = () => ok(b, `/worlds/${world.id}/live/${kind}`),
64 sub = client.subscribe(await seal());
65 await sub.awaitRows((r) => r.length > 0, 10000);
66 subscriptions.push(sub);
67 timers.push(
68 setInterval(() => {
69 void seal()
70 .then((q) => sub.renew(q))
71 .catch(() => {});
72 }, 35000),
73 );
74 }
75 const edit = (token: string, generation: number, part: any) =>
76 ok(token, `/worlds/${world.id}/edit`, {
77 operationId: randomUUID(),
78 generation,
79 action: "edit",
80 changes: [part],
81 connections: [],
82 });
83 const first = p(),
84 id = randomUUID(),
85 original = {
86 operationId: id,
87 generation: 1,
88 action: "edit",
89 changes: [first],
90 connections: [],
91 };
92 const accepted = await ok(a, `/worlds/${world.id}/edit`, original);
93 assert.ok(accepted.accepted);
94 assert.equal(
95 (
96 await request(a, `/worlds/${world.id}/edit`, {
97 ...original,
98 changes: [{ ...first, color: "#d9594e" }],
99 })
100 ).status,
101 409,
102 );
103 assert.equal(
104 (await request(b, `/worlds/${world.id}/operations/${id}`)).status,
105 404,
106 );
107 const bulk = [p(), p()].map((x) => ({
108 ...x,
109 position: { x: 30, y: 0, z: 0 },
110 }));
111 assert.equal((await edit(a, 1, bulk[0])).accepted, true);
112 const invalid = await ok(a, `/worlds/${world.id}/edit`, {
113 operationId: randomUUID(),
114 generation: 1,
115 action: "edit",
116 changes: [p(), p()].map((x) => ({ ...x, position: { x: 60, y: 0, z: 0 } })),
117 connections: [],
118 });
119 assert.equal(invalid.accepted, false);
120 const presence = (seq: number, preview: any, sample = true) =>
121 request(b, `/worlds/${world.id}/presence`, {
122 viewer: jb.viewer,
123 sequence: seq,
124 generation: 1,
125 selection: [],
126 preview,
127 sample,
128 });
129 await presence(1, {
130 key: "brick-1x1",
131 color: "#289b74",
132 position: { x: 0, y: 0, z: 0 },
133 rotation: 0,
134 });
135 await presence(3, {
136 key: "brick-1x1",
137 color: "#d9594e",
138 position: { x: 12, y: 0, z: 0 },
139 rotation: 0,
140 });
141 await presence(2, null);
142 const before = await pool.query(
143 "SELECT sequence,preview,preview_at FROM viewer_sessions WHERE id=$1",
144 [jb.viewer],
145 );
146 assert.equal(before.rows[0].sequence, 3);
147 assert.equal(before.rows[0].preview.position.x, 12);
148 await presence(4, null, false);
149 const after = await pool.query(
150 "SELECT preview_at FROM viewer_sessions WHERE id=$1",
151 [jb.viewer],
152 );
153 assert.equal(
154 after.rows[0].preview_at.valueOf(),
155 before.rows[0].preview_at.valueOf(),
156 );
157 await request(
158 b,
159 `/worlds/${world.id}/viewers/${jb.viewer}`,
160 undefined,
161 "DELETE",
162 );
163 assert.equal((await presence(5, null)).status, 410);
164 assert.equal(
165 (
166 await pool.query("SELECT id FROM viewer_sessions WHERE id=$1", [
167 jb.viewer,
168 ])
169 ).rowCount,
170 0,
171 );
172 assert.equal((await request("", "/cleanup", {})).status, 401);
173 assert.equal((await request("", "/ai/reconcile", {})).status, 401);
174 await pool.query(
175 "UPDATE world_memberships SET role='viewer' WHERE world=$1 AND guest=$2",
176 [world.id, jb.guest],
177 );
178 assert.equal(
179 (
180 await request(b, `/worlds/${world.id}/edit`, {
181 operationId: randomUUID(),
182 generation: 1,
183 action: "edit",
184 changes: [p()],
185 })
186 ).status,
187 403,
188 );
189 await pool.query(
190 "UPDATE world_memberships SET active=0 WHERE world=$1 AND guest=$2",
191 [world.id, jb.guest],
192 );
193 for (const sub of subscriptions)
194 await sub.awaitRows((rows) => rows.length === 0, 10000);
195 assert.equal(
196 (await request(b, `/worlds/${world.slug}/join`, {})).status,
197 403,
198 );
199 console.log(
200 "PASS capability admission, dynamic membership withdrawal, roles, foreign receipts, presence ordering, leave, cleanup authentication, bulk rollback",
201 );
202 let generation = 1;
203 for (let i = 0; i < 100; i++) {
204 const changes = [
205 {
206 ...p(),
207 position: {
208 x: 36 + (i % 4) * 12,
209 y: 0,
210 z: 36 + (Math.floor(i / 4) % 4) * 12,
211 },
212 },
213 ];
214 const [closed, edited] = await Promise.all([
215 ok(a, `/worlds/${world.id}/lifecycle`, { generation, status: "closed" }),
216 request(a, `/worlds/${world.id}/edit`, {
217 operationId: randomUUID(),
218 generation,
219 action: "edit",
220 changes,
221 connections: [],
222 }),
223 ]);
224 assert.equal(closed.generation, generation + 1);
225 assert.ok(edited.status === 410 || edited.status === 200);
226 assert.equal(
227 (
228 await request(a, `/worlds/${world.id}/edit`, {
229 operationId: randomUUID(),
230 generation: generation + 1,
231 action: "edit",
232 changes: [p()],
233 })
234 ).status,
235 410,
236 );
237 generation = (
238 await ok(a, `/worlds/${world.id}/lifecycle`, {
239 generation: generation + 1,
240 status: "open",
241 })
242 ).generation;
243 generation = (
244 await ok(a, `/worlds/${world.id}/reset`, { generation, starter: "empty" })
245 ).generation;
246 }
247 console.log("PASS 100 closure versus edit trials and creator reopen/reset");
248 const c = await session(),
249 jc = await ok(c, `/worlds/${world.slug}/join`, {}),
250 liveClient = createRealtimeClient({
251 url: process.env.VITE_NEON_REALTIME_URL!,
252 });
253 clients.push(liveClient);
254 const cap = await ok(c, `/worlds/${world.id}/live/scene`),
255 sub = liveClient.subscribe<SceneRow>(cap);
256 await sub.awaitRows((rows) => rows.length > 0, 10000);
257 await pool.query(
258 "UPDATE guest_sessions SET expires_at=clock_timestamp()-interval '1 second' WHERE id=(SELECT session FROM viewer_sessions WHERE id=$1)",
259 [jc.viewer],
260 );
261 assert.equal((await request(c, "/session/renew", {})).status, 401);
262 assert.equal(
263 (await request(c, `/worlds/${world.id}/live/scene`)).status,
264 401,
265 );
266 await new Promise((resolve) =>
267 setTimeout(resolve, Math.max(0, cap.expiresAt - Date.now() + 1500)),
268 );
269 assert.notEqual(sub.getSnapshot().status, "live");
270 console.log(
271 "PASS expired session denies renewal; existing capability ceases to be live at its 60-second boundary",
272 );
273 const d = await session(),
274 jd = await ok(d, `/worlds/${world.slug}/join`, {}),
275 sealed = await ok(d, `/worlds/${world.id}/live/scene`),
276 ds = liveClient.subscribe<SceneRow>(sealed);
277 await ds.awaitRows((rows) => rows.length > 0, 10000);
278 await ok(d, "/session/revoke", {});
279 await ds.awaitRows((rows) => rows.length === 0, 10000);
280 assert.equal((await request(d, "/session/renew", {})).status, 401);
281 console.log("PASS committed session revocation withdraws live rows");
282} finally {
283 timers.forEach(clearInterval);
284 clients.forEach((c) => c.close());
285 await pool.end();