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

check-hosted.ts

415 lines12.8 KB

1// Explicit, opt-in integration checks against the dedicated development server.
2// Uses only a synthetic account/notes/assets, never the Mac's journal or keys.
3import { readFile, writeFile, mkdir } from "node:fs/promises";
4import { randomUUID, randomBytes, createHash } from "node:crypto";
5import { createAuthClient } from "@neon/auth";
6import { createRealtimeClient } from "@neon/realtime/client";
7import { realtimeCollectionOptions } from "@neon/realtime-tanstack";
8import { createCollection } from "@tanstack/react-db";
9import assert from "node:assert/strict";
10const origin = process.env.JOL_ORIGIN!,
11 issuer = process.env.NEON_AUTH_BASE_URL!,
12 clientID = process.env.JOL_OAUTH_CLIENT_ID!;
13assert.ok(origin?.startsWith("https://"));
14assert.ok(issuer?.startsWith("https://"));
15const fixtureFile = ".data/hosted-fixture.json";
16await mkdir(".data", { recursive: true, mode: 0o700 });
17let fixture: Record<string, any>;
18try {
19 fixture = JSON.parse(await readFile(fixtureFile, "utf8"));
20 assert.equal(fixture.origin, origin);
21} catch {
22 const account = {
23 email: `jol-fixture-${randomUUID()}@example.invalid`,
24 password: randomBytes(32).toString("base64url"),
25 name: "JOL integration fixture",
26 };
27 const r = await fetch(issuer + "/sign-up/email", {
28 method: "POST",
29 headers: { "Content-Type": "application/json", Origin: origin },
30 body: JSON.stringify(account),
31 });
32 assert.equal(r.status, 200, "fixture sign-up");
33 fixture = {
34 ...account,
35 origin,
36 cookies: r.headers
37 .getSetCookie()
38 .map((x) => x.split(";")[0])
39 .join("; "),
40 };
42const signIn = await fetch(issuer + "/sign-in/email", {
43 method: "POST",
44 headers: { "Content-Type": "application/json", Origin: origin },
45 body: JSON.stringify({ email: fixture.email, password: fixture.password }),
46});
47assert.equal(signIn.status, 200, "fixture sign-in");
48fixture.cookies = signIn.headers
49 .getSetCookie()
50 .map((x) => x.split(";")[0])
51 .join("; ");
52const browserAuth = createAuthClient(issuer);
53const sessionOptions = {
54 fetchOptions: { headers: { Cookie: fixture.cookies, Origin: origin } },
55};
56for (const phase of ["restored", "cached"]) {
57 const { data, error } = await browserAuth.getSession(sessionOptions);
58 assert.ok(!error && data?.session?.token, `${phase} browser session JWT`);
59 const me = await fetch(origin + "/api/me", {
60 headers: { Authorization: "Bearer " + data.session.token },
61 });
62 assert.equal(me.status, 200, `${phase} browser session opens the journal`);
64console.log("PASS hosted restored and cached browser session");
65const verifier = randomBytes(32).toString("base64url"),
66 state = randomBytes(32).toString("base64url"),
67 redirect = "http://127.0.0.1:49381/jol/callback";
68const params = new URLSearchParams({
69 response_type: "code",
70 client_id: clientID,
71 redirect_uri: redirect,
72 scope: "openid offline_access",
73 state,
74 code_challenge: createHash("sha256").update(verifier).digest("base64url"),
75 code_challenge_method: "S256",
76 resource: origin + "/api",
77});
78const browserEntry = await fetch(origin + "/authorize?" + params, {
79 redirect: "manual",
80});
81assert.equal(
82 browserEntry.status,
83 302,
84 "native browser entry must navigate, not display JSON",
85);
86const loginURL = new URL(browserEntry.headers.get("location")!);
87assert.equal(loginURL.pathname, "/login");
88console.log("PASS hosted browser authorization entry");
89const authorization = await fetch(issuer + "/oauth2/continue", {
90 method: "POST",
91 headers: {
92 Cookie: fixture.cookies,
93 Origin: origin,
94 "Content-Type": "application/json",
95 },
96 body: JSON.stringify({
97 selected: true,
98 oauth_query: loginURL.search.slice(1),
99 }),
100 redirect: "manual",
101});
102assert.equal(authorization.status, 200, "hosted signed login continuation");
103const consentURL =
104 authorization.headers.get("location") ??
105 ((await authorization.json()) as { url: string }).url;
106let callback = new URL(consentURL);
107if (callback.pathname !== "/jol/callback") {
108 assert.equal(
109 callback.pathname,
110 "/consent",
111 "signed-in fixture goes to consent",
112 );
113 const consent = await fetch(issuer + "/oauth2/consent", {
114 method: "POST",
115 headers: {
116 Cookie: fixture.cookies,
117 Origin: origin,
118 "Content-Type": "application/json",
119 },
120 body: JSON.stringify({
121 accept: true,
122 oauth_query: callback.search.slice(1),
123 }),
124 });
125 assert.equal(consent.status, 200, "hosted consent");
126 callback = new URL(((await consent.json()) as { url: string }).url);
128assert.equal(callback.searchParams.get("state"), state);
129const tokenRequest = await fetch(issuer + "/oauth2/token", {
130 method: "POST",
131 headers: { "Content-Type": "application/x-www-form-urlencoded" },
132 body: new URLSearchParams({
133 grant_type: "authorization_code",
134 client_id: clientID,
135 redirect_uri: redirect,
136 code: callback.searchParams.get("code")!,
137 code_verifier: verifier,
138 resource: origin + "/api",
139 }),
140});
141assert.equal(tokenRequest.status, 200, "PKCE exchange");
142const tokens = (await tokenRequest.json()) as Record<string, any>;
143assert.ok(tokens.refresh_token);
144fixture.oauth = tokens;
145await writeFile(fixtureFile, JSON.stringify(fixture), { mode: 0o600 });
146console.log("PASS hosted PKCE and native resource token");
147const device = randomUUID(),
148 credential = randomBytes(32).toString("base64url"),
149 exp = randomUUID(),
150 entry = randomUUID(),
151 photo = randomUUID() + ".jpg";
152async function api(
153 path: string,
154 body?: unknown,
155 native = false,
156 method = body === undefined ? "GET" : "POST",
157) {
158 const r = await fetch(origin + "/api" + path, {
159 method,
160 headers: {
161 Authorization: "Bearer " + tokens.access_token,
162 ...(native ? { "X-JOL-Device": credential } : {}),
163 ...(body === undefined ? {} : { "Content-Type": "application/json" }),
164 },
165 body: body === undefined ? undefined : JSON.stringify(body),
166 });
167 assert.ok(r.ok, `${method} ${path}: ${r.status}`);
168 return r.json();
170const me = await api("/me");
171assert.ok(
172 me.id.endsWith(
173 "|" +
174 JSON.parse(
175 Buffer.from(tokens.access_token.split(".")[1], "base64url").toString(),
176 ).sub,
177 ),
178);
179await api("/devices", {
180 id: device,
181 name: "Hosted integration fixture",
182 credential,
183});
184await api(`/devices/${device}/heartbeat`, { remoteEnabled: true }, true);
185const created = {
186 version: 1,
187 id: randomUUID(),
188 date: Date.now(),
189 event: "created",
190 expedition: { id: exp, date: Date.now(), title: "The Hosted Paper Trail" },
191};
192const note = {
193 version: 1,
194 id: randomUUID(),
195 date: Date.now(),
196 event: "entry",
197 entry: {
198 id: entry,
199 date: Date.now(),
200 kind: "response",
201 text: "A live field note",
202 details: "",
203 },
204};
205await api(
206 `/devices/${device}/expeditions/${exp}/batches`,
207 { start: 1, records: [created, note] },
208 true,
209);
210console.log("PASS hosted Mac enrollment and journal upload");
211const realtime = createRealtimeClient({ url: process.env.NEON_REALTIME_URL! });
212const photoPath = `/devices/${device}/expeditions/${exp}/photos/${photo}`;
213const image = await readFile(".data/fixture.jpg");
214try {
215 const sealed = await api("/live", {
216 kind: "entries",
217 deviceID: device,
218 expeditionID: exp,
219 after: 0,
220 });
221 type Note = {
222 id: string;
223 text: string;
224 details: string;
225 photo: string | null;
226 photo_ready: boolean;
227 };
228 const subscription = realtime.subscribe<Note>(sealed);
229 const collection = createCollection(
230 realtimeCollectionOptions<Note>({
231 client: realtime,
232 query: sealed,
233 getKey: (row) => row.id,
234 }),
235 );
236 await subscription.awaitRows(
237 (rows) =>
238 rows.some((r) => r.id === entry && r.text === "A live field note"),
239 20_000,
240 );
241 await collection.preload();
242 assert.equal(collection.get(entry)?.text, "A live field note");
243 await api(
244 `/devices/${device}/expeditions/${exp}/batches`,
245 {
246 start: 3,
247 records: [
248 {
249 version: 1,
250 id: randomUUID(),
251 date: Date.now(),
252 event: "textAppended",
253 entryID: entry,
254 text: " from the summit.",
255 },
256 ],
257 },
258 true,
259 );
260 await subscription.awaitRows(
261 (rows) =>
262 rows.some((r) => r.id === entry && r.text.endsWith("from the summit.")),
263 20_000,
264 );
265 const detail = [
266 {
267 sequence: 2,
268 id: note.id,
269 date: note.date,
270 event: "entry",
271 entryID: entry,
272 text: "Synthetic technical detail.",
273 },
274 ];
275 await api(
276 `/devices/${device}/expeditions/${exp}/details`,
277 detail,
278 true,
279 "PATCH",
280 );
281 await subscription.awaitRows(
282 (rows) => rows.some((r) => r.id === entry && r.details === detail[0].text),
283 20_000,
284 );
285 const upload = await fetch(origin + "/api" + photoPath + "?entry=" + entry, {
286 method: "PUT",
287 headers: {
288 Authorization: "Bearer " + tokens.access_token,
289 "X-JOL-Device": credential,
290 "Content-Type": "image/jpeg",
291 },
292 body: image,
293 });
294 assert.equal(upload.status, 200, "private photo backfill");
295 assert.equal((await upload.json()).entryLinked, true);
296 await subscription.awaitRows(
297 (rows) => rows.some((r) => r.id === entry && r.photo_ready),
298 20_000,
299 );
300 const published = await new Promise<Note>((resolve, reject) => {
301 let listener: ReturnType<typeof collection.subscribeChanges>;
302 const timer = setTimeout(() => {
303 listener.unsubscribe();
304 reject(new Error("TanStack DB did not receive the live photo update"));
305 }, 10_000);
306 const check = () => {
307 const row = collection.get(entry);
308 if (row?.photo_ready) {
309 clearTimeout(timer);
310 listener.unsubscribe();
311 resolve(row);
312 }
313 };
314 listener = collection.subscribeChanges(check);
315 check();
316 });
317 assert.equal(published.details, detail[0].text);
318 assert.equal(published.photo, photo);
319 await api(
320 `/devices/${device}/expeditions/${exp}/batches`,
321 { start: 1, records: [created, note] },
322 true,
323 );
324 await collection.cleanup();
325 subscription.unsubscribe();
326 console.log(
327 "PASS hosted Neon Realtime and TanStack DB journal, detail and photo changes",
328 );
329} finally {
330 realtime.close();
332const commandID = randomUUID();
333const stream = await fetch(origin + `/api/devices/${device}/events`, {
334 signal: AbortSignal.timeout(30_000),
335 headers: {
336 Authorization: "Bearer " + tokens.access_token,
337 "X-JOL-Device": credential,
338 },
339});
340assert.equal(stream.status, 200);
341const reader = stream.body!.getReader();
342const decoder = new TextDecoder();
343let events = "";
344async function waitForEvent(name: string) {
345 const marker = `event: ${name}\n`;
346 while (!events.includes(marker)) {
347 const chunk = await reader.read();
348 assert.ok(!chunk.done, `stream closed before ${name}`);
349 events += decoder.decode(chunk.value, { stream: true });
350 }
351 events = events.slice(events.indexOf(marker) + marker.length);
353await waitForEvent("live");
354await api("/commands", {
355 id: commandID,
356 deviceID: device,
357 expeditionID: exp,
358 kind: "continue",
359 prompt: "Write another synthetic field note",
360});
361await waitForEvent("commands_changed");
362await reader.cancel();
363console.log("PASS hosted Neon Realtime wakes the native command stream");
364assert.equal(
365 (await api(`/devices/${device}/commands/claim`, { busy: true }, true))
366 .command,
367 null,
368);
369const command = (
370 await api(`/devices/${device}/commands/claim`, { busy: false }, true)
371).command;
372assert.equal(command.id, commandID);
373await api(
374 `/devices/${device}/commands/${commandID}/ack`,
375 { fence: command.fence, status: "started" },
376 true,
377);
378await api(
379 `/devices/${device}/commands/${commandID}/ack`,
380 {
381 fence: command.fence,
382 status: "finished",
383 result: "Synthetic command acknowledged; no computer input was performed",
384 },
385 true,
386);
387assert.equal((await api(`/devices/${device}/commands`))[0].status, "finished");
388console.log("PASS hosted durable command delivery and acknowledgement");
389const download = await fetch(origin + "/api" + photoPath, {
390 headers: { Authorization: "Bearer " + tokens.access_token },
391});
392assert.equal(download.status, 200);
393assert.deepEqual(Buffer.from(await download.arrayBuffer()), image);
394console.log("PASS hosted private photograph round trip");
395const refresh = await fetch(issuer + "/oauth2/token", {
396 method: "POST",
397 headers: { "Content-Type": "application/x-www-form-urlencoded" },
398 body: new URLSearchParams({
399 grant_type: "refresh_token",
400 client_id: clientID,
401 refresh_token: tokens.refresh_token,
402 resource: origin + "/api",
403 }),
404});
405assert.equal(refresh.status, 200);
406fixture.oauth = await refresh.json();
407await writeFile(fixtureFile, JSON.stringify(fixture), { mode: 0o600 });
408console.log("PASS hosted rotating refresh token");
409await api(`/devices/${device}/revoke`, {});
410// This is a one-shot probe. The managed SDK/HTTP pool can retain background
411// handles after close; all writes and device revocation are acknowledged above.
412process.stdout.write(
413 "Hosted checks complete. Only synthetic fixture records were written.\n",
414 () => process.exit(0),
415);