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

jol.test.ts

523 lines13.3 KB

1import { test, before, after } from "node:test";
2import assert from "node:assert/strict";
3import { randomUUID } from "node:crypto";
4import { readFile } from "node:fs/promises";
5import { PGlite } from "@electric-sql/pglite";
6import { createApp } from "../src/app.js";
7import type { Database } from "../src/database.js";
8import { APIError } from "../src/protocol.js";
9import type { Config } from "../src/config.js";
10​
11const store = new PGlite();
12const db: Database = {
13 query: async (s, v) => store.query(s, v),
14 transaction: (fn) =>
15 store.transaction((q) => fn({ query: async (s, v) => q.query(s, v) })),
16};
17const cfg: Config = {
18 origin: "https://jol.example.test",
19 instanceID: randomUUID(),
20 name: "JOL",
21 authURL: "https://auth.example.test/neondb/auth",
22 jwksURL: "https://auth.example.test/jwks",
23 clientID: "native",
24 databaseName: "postgres",
25};
26const app = createApp({
27 db,
28 config: cfg,
29 authenticate: async (r) => {
30 const user = r.headers.get("x-test-user");
31 if (!user) throw new APIError(401, "Sign in");
32 return { id: user, expires: Date.now() + 60_000 };
33 },
34});
35const device = randomUUID(),
36 expedition = randomUUID(),
37 entry = randomUUID(),
38 credential = "x".repeat(43);
39const created = {
40 version: 1,
41 id: randomUUID(),
42 date: 1000,
43 event: "created",
44 expedition: { id: expedition, date: 1000, title: "The Great Paper Trail" },
45};
46const note = {
47 version: 1,
48 id: randomUUID(),
49 date: 1001,
50 event: "entry",
51 entry: {
52 id: entry,
53 date: 1001,
54 kind: "response",
55 text: "I found ",
56 details: "",
57 },
58};
59const delta = {
60 version: 1,
61 id: randomUUID(),
62 date: 1002,
63 event: "textAppended",
64 entryID: entry,
65 text: "a way.",
66};
67async function call(
68 path: string,
69 body?: unknown,
70 user = "alice",
71 native = false,
72 method?: string,
73) {
74 return app.request("https://jol.example.test" + path, {
75 method: method ?? (body === undefined ? "GET" : "POST"),
76 headers: {
77 "x-test-user": user,
78 ...(native ? { "X-JOL-Device": credential } : {}),
79 "Content-Type": "application/json",
80 },
81 body: body === undefined ? undefined : JSON.stringify(body),
82 });
84before(async () => {
85 await store.exec(await readFile("migrations/001_jol.sql", "utf8"));
86});
87after(async () => {
88 await store.close();
89});
90test("discovery is public and contains no secret", async () => {
91 const r = await app.request(
92 "https://jol.example.test/.well-known/jerry-online",
93 );
94 assert.equal(r.status, 200);
95 const body = await r.json();
96 assert.equal(body.auth.resource, cfg.origin + "/api");
97 assert.equal(body.version, 1);
98 assert.ok(!JSON.stringify(body).includes(credential));
99});
100test("protected routes require sign-in and reject a foreign browser origin", async () => {
101 assert.equal(
102 (await app.request("https://jol.example.test/api/devices")).status,
103 401,
104 );
105 assert.equal(
106 (
107 await app.request("https://jol.example.test/api/devices", {
108 headers: { "x-test-user": "alice", Origin: "https://evil.test" },
109 })
110 ).status,
111 403,
112 );
113});
114test("enrollment is idempotent but another account cannot replace it", async () => {
115 assert.equal(
116 (await call("/api/devices", { id: device, name: "Test Mac", credential }))
117 .status,
118 200,
119 );
120 assert.equal(
121 (await call("/api/devices", { id: device, name: "Test Mac", credential }))
122 .status,
123 200,
124 );
125 assert.equal(
126 (
127 await call(
128 "/api/devices",
129 { id: device, name: "Other Mac", credential },
130 "bob",
131 )
132 ).status,
133 404,
134 );
135 assert.equal(
136 (
137 await call("/api/devices", {
138 id: device,
139 name: "Test Mac",
140 credential: "y".repeat(43),
141 })
142 ).status,
143 409,
144 );
145});
146const batches = `/api/devices/${device}/expeditions/${expedition}/batches`;
147test("browser sessions cannot upload journals without Mac possession", async () => {
148 assert.equal(
149 (await call(batches, { start: 1, records: [created] })).status,
150 403,
151 );
152 assert.equal(
153 (await call(batches, { start: 1, records: [created] }, "bob", true)).status,
154 404,
155 );
156});
157test("gaps and incomplete creation are rejected without partial writes", async () => {
158 assert.equal(
159 (await call(batches, { start: 2, records: [created] }, "alice", true))
160 .status,
161 409,
162 );
163 assert.equal(
164 (await call(batches, { start: 1, records: [note] }, "alice", true)).status,
165 409,
166 );
167 assert.equal(
168 (await db.query("SELECT * FROM jol_expeditions")).rows.length,
169 0,
170 );
171});
172test("ordered batches and retry after lost acknowledgement append text only once", async () => {
173 const batch = { start: 1, records: [created, note, delta] };
174 const first = await call(batches, batch, "alice", true);
175 assert.equal(first.status, 200);
176 assert.equal((await first.json()).cursor, 3);
177 assert.equal((await call(batches, batch, "alice", true)).status, 200);
178 const rows = (await db.query("SELECT text FROM jol_entries")).rows;
179 assert.equal(rows[0].text, "I found a way.");
180 assert.equal((await db.query("SELECT * FROM jol_events")).rows.length, 3);
181});
182test("conflicting accepted sequence or reused event ID cannot corrupt a journal", async () => {
183 assert.equal(
184 (
185 await call(
186 batches,
187 { start: 3, records: [{ ...delta, text: "different" }] },
188 "alice",
189 true,
190 )
191 ).status,
192 409,
193 );
194 assert.equal(
195 (await call(batches, { start: 4, records: [delta] }, "alice", true)).status,
196 409,
197 );
198 assert.equal(
199 (await db.query("SELECT text FROM jol_entries")).rows[0].text,
200 "I found a way.",
201 );
202});
203test("a later gap rolls back the entire batch and keeps its cursor", async () => {
204 assert.equal(
205 (
206 await call(
207 batches,
208 { start: 5, records: [{ ...delta, id: randomUUID() }] },
209 "alice",
210 true,
211 )
212 ).status,
213 409,
214 );
215 assert.equal(
216 (await db.query("SELECT cursor FROM jol_expeditions")).rows[0].cursor,
217 3,
218 );
219});
220test("text revisions, redacted details and title changes project correctly", async () => {
221 const records = [
222 {
223 ...delta,
224 id: randomUUID(),
225 event: "textReplaced",
226 text: "I crossed the paper cliffs.",
227 },
228 { version: 1, id: randomUUID(), date: 1003, event: "redacted" },
229 {
230 version: 1,
231 id: randomUUID(),
232 date: 1004,
233 event: "titleChanged",
234 text: "Paper Cliffs and Small Victories",
235 },
236 ];
237 assert.equal(
238 (await call(batches, { start: 4, records }, "alice", true)).status,
239 200,
240 );
241 assert.equal(
242 (await db.query("SELECT text,details FROM jol_entries")).rows[0].text,
243 "I crossed the paper cliffs.",
244 );
245 assert.equal(
246 (await db.query("SELECT details FROM jol_entries")).rows[0].details,
247 "",
248 );
249 assert.equal(
250 (await db.query("SELECT title FROM jol_expeditions")).rows[0].title,
251 "Paper Cliffs and Small Victories",
252 );
253});
254test("sharing redacted details is device-scoped, retry-safe and leaves the journal cursor alone", async () => {
255 const path = batches.replace(/batches$/, "details");
256 const redaction = (
257 await db.query("SELECT payload FROM jol_events WHERE sequence=5")
258 ).rows[0].payload;
259 const changes = [
260 {
261 sequence: 2,
262 id: note.id,
263 date: note.date,
264 event: "entry",
265 entryID: entry,
266 text: "First detail.",
267 },
268 {
269 sequence: 5,
270 id: redaction.id,
271 date: redaction.date,
272 event: "detailsAppended",
273 entryID: entry,
274 text: " Another detail.",
275 },
276 ];
277 assert.equal(
278 (await call(path, changes, "alice", false, "PATCH")).status,
279 403,
280 );
281 assert.equal((await call(path, changes, "bob", true, "PATCH")).status, 404);
282 for (let retry = 0; retry < 2; retry++) {
283 assert.equal(
284 (await call(path, changes, "alice", true, "PATCH")).status,
285 200,
286 );
287 }
288 assert.equal(
289 (await call(batches, { start: 2, records: [note] }, "alice", true)).status,
290 200,
291 );
292 assert.equal(
293 (await call(batches, { start: 5, records: [redaction] }, "alice", true))
294 .status,
295 200,
296 );
297 assert.equal(
298 (await db.query("SELECT details FROM jol_entries")).rows[0].details,
299 "First detail. Another detail.",
300 );
301 assert.equal(
302 (await db.query("SELECT cursor FROM jol_expeditions")).rows[0].cursor,
303 6,
304 );
305});
306test("private journal, assets and named queries cannot be read across accounts", async () => {
307 assert.equal(
308 (await (await call("/api/expeditions", undefined, "bob")).json()).length,
309 0,
310 );
311 assert.equal(
312 (
313 await call(
314 `/api/devices/${device}/expeditions/${expedition}/entries`,
315 undefined,
316 "bob",
317 )
318 ).status,
319 404,
320 );
321 assert.equal(
322 (await call(`/api/devices/${device}/commands`, undefined, "bob")).status,
323 404,
324 );
325 assert.equal(
326 (
327 await call("/api/live", {
328 kind: "anything",
329 sql: "SELECT * FROM jol_entries",
330 })
331 ).status,
332 503,
333 );
334});
335const commandID = randomUUID();
336test("remote commands start disabled and only the Mac can arm them", async () => {
337 const command = {
338 id: commandID,
339 deviceID: device,
340 kind: "continue",
341 expeditionID: expedition,
342 prompt: "Explore further",
343 };
344 assert.equal((await call("/api/commands", command)).status, 409);
345 assert.equal(
346 (await call(`/api/devices/${device}/heartbeat`, { remoteEnabled: true }))
347 .status,
348 403,
349 );
350 assert.equal(
351 (
352 await call(
353 `/api/devices/${device}/heartbeat`,
354 { remoteEnabled: true },
355 "alice",
356 true,
357 )
358 ).status,
359 200,
360 );
361 assert.equal((await call("/api/commands", command)).status, 201);
362 assert.equal((await call("/api/commands", command)).status, 200);
363 assert.equal(
364 (await call("/api/commands", { ...command, prompt: "replace" })).status,
365 409,
366 );
367});
368test("busy Macs leave routine prompts queued", async () => {
369 const r = await call(
370 `/api/devices/${device}/commands/claim`,
371 { busy: true },
372 "alice",
373 true,
374 );
375 assert.equal((await r.json()).command, null);
376});
377let fence = 0;
378test("claiming work increments a fence; stale acknowledgements are rejected", async () => {
379 const r = await call(
380 `/api/devices/${device}/commands/claim`,
381 { busy: false },
382 "alice",
383 true,
384 );
385 const c = (await r.json()).command;
386 assert.equal(c.id, commandID);
387 fence = c.fence;
388 assert.equal(c.status, "received");
389 const ack = `/api/devices/${device}/commands/${commandID}/ack`;
390 assert.equal(
391 (await call(ack, { fence: fence + 1, status: "started" }, "alice", true))
392 .status,
393 409,
394 );
395 assert.equal(
396 (await call(ack, { fence, status: "started" }, "alice", true)).status,
397 200,
398 );
399});
400test("a crash after starting never automatically requeues physical actions", async () => {
401 await db.query(
402 "UPDATE jol_commands SET lease_until=now()-interval '1 second' WHERE id=$1",
403 [commandID],
404 );
405 assert.equal(
406 (
407 await (
408 await call(
409 `/api/devices/${device}/commands/claim`,
410 { busy: false },
411 "alice",
412 true,
413 )
414 ).json()
415 ).command,
416 null,
417 );
418 assert.equal(
419 (await db.query("SELECT status FROM jol_commands WHERE id=$1", [commandID]))
420 .rows[0].status,
421 "uncertain",
422 );
423});
424test("stop targets a specific expedition and can pass the routine queue", async () => {
425 assert.equal(
426 (
427 await call("/api/commands", {
428 id: randomUUID(),
429 deviceID: device,
430 kind: "stop",
431 })
432 ).status,
433 400,
434 );
435 const id = randomUUID();
436 assert.equal(
437 (
438 await call("/api/commands", {
439 id,
440 deviceID: device,
441 expeditionID: expedition,
442 kind: "stop",
443 })
444 ).status,
445 201,
446 );
447 const command = (
448 await (
449 await call(
450 `/api/devices/${device}/commands/claim`,
451 { busy: true },
452 "alice",
453 true,
454 )
455 ).json()
456 ).command;
457 assert.equal(command.id, id);
458 await call(
459 `/api/devices/${device}/commands/${id}/ack`,
460 { fence: command.fence, status: "finished" },
461 "alice",
462 true,
463 );
464});
465test("queued requests can be cancelled and expired work cannot be claimed", async () => {
466 const id = randomUUID(),
467 expired = randomUUID();
468 for (const key of [id, expired])
469 await call("/api/commands", {
470 id: key,
471 deviceID: device,
472 kind: "start",
473 prompt: "A small adventure",
474 });
475 assert.equal((await call(`/api/commands/${id}/cancel`, {})).status, 200);
476 await db.query(
477 "UPDATE jol_commands SET expires_at=now()-interval '1 second' WHERE id=$1",
478 [expired],
479 );
480 assert.equal(
481 (
482 await (
483 await call(
484 `/api/devices/${device}/commands/claim`,
485 { busy: false },
486 "alice",
487 true,
488 )
489 ).json()
490 ).command,
491 null,
492 );
493 assert.equal(
494 (await db.query("SELECT status FROM jol_commands WHERE id=$1", [expired]))
495 .rows[0].status,
496 "expired",
497 );
498});
499test("device revocation blocks its old connection and remote execution", async () => {
500 assert.equal((await call(`/api/devices/${device}/revoke`, {})).status, 200);
501 assert.equal(
502 (
503 await call(
504 batches,
505 { start: 7, records: [{ ...delta, id: randomUUID() }] },
506 "alice",
507 true,
508 )
509 ).status,
510 404,
511 );
512 assert.equal(
513 (
514 await call(
515 `/api/devices/${device}/commands/claim`,
516 { busy: false },
517 "alice",
518 true,
519 )
520 ).status,
521 404,
522 );
523});