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

app.ts

685 lines23.2 KB

1import { Hono } from "hono";
2import { bodyLimit } from "hono/body-limit";
3import { secureHeaders } from "hono/secure-headers";
4import { streamSSE } from "hono/streaming";
5import { z } from "zod";
6import { createHash, timingSafeEqual } from "node:crypto";
7import {
8 S3Client,
9 PutObjectCommand,
10 GetObjectCommand,
11} from "@aws-sdk/client-s3";
12import {
13 APIError,
14 batchSchema,
15 detailChangeSchema,
16 commandSchema,
17 uuid,
18 digest,
19} from "./protocol.js";
20import { ingest, claim, shareDetails, type Database } from "./database.js";
21import type { Config } from "./config.js";
22import type { Authenticate, Identity } from "./auth.js";
23import {
24 liveQueries,
25 devicesQuery,
26 entriesQuery,
27 expeditionsQuery,
28 expeditionQuery,
29 entryColumns,
30 entryAssetsJoin,
31 commandsQuery,
32 commandInboxQuery,
33} from "./live.js";
34​
35type Dependencies = {
36 db: Database;
37 config: Config;
38 authenticate: Authenticate;
39 assets?: Record<string, { body: Uint8Array; type: string }>;
40};
41export function createApp({
42 db,
43 config,
44 authenticate,
45 assets = {},
46}: Dependencies) {
47 const app = new Hono<{ Variables: { identity: Identity } }>();
48 const live = liveQueries(config);
49 // Start's prerendered shell carries static hydration scripts.
50 const shell = assets["/"]?.body;
51 const scripts = shell
52 ? [
53 ...new TextDecoder()
54 .decode(shell)
55 .matchAll(/<script\b[^>]*>([^]*?)<\/script>/g),
56 ]
57 .map((match) => match[1])
58 .filter(Boolean)
59 .map(
60 (script) =>
61 "'sha256-" +
62 createHash("sha256").update(script).digest("base64") +
63 "'",
64 )
65 : [];
66 const s3 = config.photoBucket
67 ? new S3Client({
68 forcePathStyle: true,
69 endpoint: process.env.AWS_ENDPOINT_URL_S3,
70 })
71 : undefined;
72 app.use(
73 "*",
74 secureHeaders({
75 contentSecurityPolicy: {
76 defaultSrc: ["'self'"],
77 scriptSrc: ["'self'", ...scripts],
78 styleSrc: ["'self'"],
79 fontSrc: ["'self'"],
80 imgSrc: ["'self'", "blob:"],
81 connectSrc: [
82 "'self'",
83 new URL(config.authURL).origin,
84 ...(config.realtimeURL
85 ? [
86 new URL(config.realtimeURL).origin,
87 new URL(config.realtimeURL).origin.replace(/^https:/, "wss:"),
88 ]
89 : []),
90 ],
91 frameSrc: [new URL(config.authURL).origin],
92 objectSrc: ["'none'"],
93 baseUri: ["'none'"],
94 frameAncestors: ["'none'"],
95 },
96 crossOriginResourcePolicy: "same-origin",
97 crossOriginOpenerPolicy: "same-origin-allow-popups",
98 }),
99 );
100 app.onError((e, c) => {
101 if (e instanceof APIError)
102 return c.json({ error: e.message }, e.status as 400);
103 if (e instanceof z.ZodError)
104 return c.json(
105 {
106 error: "Invalid request",
107 issues: e.issues.map((i) => ({ path: i.path, message: i.message })),
108 },
109 400,
110 );
111 console.error(
112 "JOL request failed",
113 e instanceof Error ? e.name : "unknown",
114 );
115 return c.json({ error: "JOL could not complete this request" }, 500);
116 });
117 app.get("/.well-known/jerry-online", (c) =>
118 c.json({
119 version: 1,
120 instanceID: config.instanceID,
121 name: config.name,
122 origin: config.origin,
123 auth: {
124 issuer: config.authURL,
125 clientID: config.clientID,
126 resource: `${config.origin}/api`,
127 redirectURI: "http://127.0.0.1:49381/jol/callback",
128 },
129 capabilities: {
130 journal: true,
131 commands: true,
132 photos: !!s3,
133 photosBackfill: !!s3,
134 realtime: !!live,
135 detailsBackfill: true,
136 },
137 realtimeURL: config.realtimeURL ?? null,
138 }),
139 );
140 app.get("/health", (c) => c.json({ ok: true, protocol: 1 }));
141 // Managed Auth currently returns a JSON redirect even for a browser authorize
142 // request. Turn that response into navigation without proxying session cookies.
143 app.get("/authorize", async (c) => {
144 const query = z
145 .object({
146 response_type: z.literal("code"),
147 client_id: z.literal(config.clientID),
148 redirect_uri: z.literal("http://127.0.0.1:49381/jol/callback"),
149 resource: z.literal(config.origin + "/api"),
150 scope: z.literal("openid offline_access"),
151 state: z.string().min(32).max(128),
152 code_challenge: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
153 code_challenge_method: z.literal("S256"),
154 })
155 .parse(c.req.query());
156 const upstream = await fetch(
157 config.authURL + "/oauth2/authorize?" + new URLSearchParams(query),
158 { redirect: "manual", headers: { Accept: "application/json" } },
159 );
160 let target = upstream.headers.get("location");
161 if (!target) {
162 const result = (await upstream.json()) as { url?: string };
163 target = result.url ?? null;
164 }
165 if (!target)
166 throw new APIError(
167 502,
168 "The sign-in service did not return a destination",
169 );
170 const url = new URL(target);
171 if (
172 url.origin !== config.origin ||
173 !["/login", "/consent"].includes(url.pathname)
174 )
175 throw new APIError(
176 502,
177 "The sign-in service returned an unexpected destination",
178 );
179 c.header("Cache-Control", "no-store");
180 return c.redirect(url.href, 302);
181 });
182 app.use("/api/*", async (c, next) => {
183 c.header("Cache-Control", "no-store");
184 const origin = c.req.header("Origin");
185 if (origin && origin !== config.origin)
186 throw new APIError(403, "This origin is not allowed");
187 const identity = await authenticate(c.req.raw);
188 if (
189 c.req.header("X-JOL-Expected-User") &&
190 c.req.header("X-JOL-Expected-User") !== identity.id
191 )
192 throw new APIError(409, "Account changed; reload JOL");
193 c.set("identity", identity);
194 await next();
195 });
196 app.use(
197 "/api/*",
198 bodyLimit({
199 maxSize: 4 * 1024 * 1024,
200 onError: (c) => c.json({ error: "Request too large" }, 413),
201 }),
202 );
203 const owner = async (id: string, user: string) => {
204 const d = (
205 await db.query("SELECT * FROM jol_devices WHERE id=$1 AND owner_id=$2", [
206 id,
207 user,
208 ])
209 ).rows[0];
210 if (!d) throw new APIError(404, "Mac not found");
211 return d;
212 };
213 const device = async (id: string, user: string, request: Request) => {
214 const d = await owner(id, user);
215 if (d.revoked) throw new APIError(404, "Mac disconnected");
216 const supplied = digest(request.headers.get("X-JOL-Device") ?? "");
217 if (!timingSafeEqual(Buffer.from(supplied), Buffer.from(d.credential_hash)))
218 throw new APIError(403, "This connection is not the enrolled Mac");
219 return d;
220 };
221 app.get("/api/me", (c) =>
222 c.json({ id: c.get("identity").id, instanceID: config.instanceID }),
223 );
224 app.post("/api/devices", async (c) => {
225 const { id, name, credential } = z
226 .object({
227 id: uuid,
228 name: z.string().trim().min(1).max(80),
229 credential: z.string().min(40).max(100),
230 })
231 .parse(await c.req.json());
232 const who = c.get("identity").id,
233 hash = digest(credential);
234 // Retry enrollment with the same device credential; never rotate on an arbitrary browser request.
235 const d = (
236 await db.query(
237 "INSERT INTO jol_devices(id,owner_id,name,credential_hash) VALUES($1,$2,$3,$4) ON CONFLICT(id) DO NOTHING RETURNING id",
238 [id, who, name, hash],
239 )
240 ).rows[0];
241 if (!d) {
242 const prior = await owner(id, who);
243 if (prior.credential_hash !== hash)
244 throw new APIError(409, "Mac is already enrolled");
245 }
246 return c.json({ id });
247 });
248 app.get("/api/devices", async (c) =>
249 c.json(
250 (
251 await db.query(
252 "SELECT id,name,remote_enabled,last_seen FROM jol_devices WHERE owner_id=$1 ORDER BY created_at",
253 [c.get("identity").id],
254 )
255 ).rows,
256 ),
257 );
258 app.post("/api/devices/:device/heartbeat", async (c) => {
259 const id = uuid.parse(c.req.param("device"));
260 await device(id, c.get("identity").id, c.req.raw);
261 const { remoteEnabled } = z
262 .object({ remoteEnabled: z.boolean() })
263 .parse(await c.req.json());
264 await db.query(
265 "UPDATE jol_devices SET last_seen=now(),remote_enabled=$2 WHERE id=$1",
266 [id, remoteEnabled],
267 );
268 return c.json({ ok: true });
269 });
270 app.post("/api/devices/:device/revoke", async (c) => {
271 const id = uuid.parse(c.req.param("device"));
272 await owner(id, c.get("identity").id);
273 await db.transaction(async (q) => {
274 await q.query(
275 "UPDATE jol_devices SET revoked=true,remote_enabled=false WHERE id=$1",
276 [id],
277 );
278 await q.query(
279 "UPDATE jol_commands SET status='cancelled',result='Mac disconnected' WHERE device_id=$1 AND status IN ('queued','received')",
280 [id],
281 );
282 });
283 return c.json({ ok: true });
284 });
285 app.patch(
286 "/api/devices/:device/expeditions/:expedition/details",
287 async (c) => {
288 const d = uuid.parse(c.req.param("device")),
289 e = uuid.parse(c.req.param("expedition"));
290 await device(d, c.get("identity").id, c.req.raw);
291 const changes = z
292 .array(detailChangeSchema)
293 .min(1)
294 .max(100)
295 .parse(await c.req.json());
296 await shareDetails(db, d, e, changes);
297 return c.json({ ok: true });
298 },
299 );
300 app.post(
301 "/api/devices/:device/expeditions/:expedition/batches",
302 async (c) => {
303 const d = uuid.parse(c.req.param("device")),
304 e = uuid.parse(c.req.param("expedition"));
305 await device(d, c.get("identity").id, c.req.raw);
306 const batch = batchSchema.parse(await c.req.json());
307 const cursor = await ingest(db, d, e, batch.start, batch.records);
308 return c.json({ cursor });
309 },
310 );
311 app.get("/api/expeditions", async (c) => {
312 const before = c.req.query("before");
313 const params: unknown[] = [c.get("identity").id];
314 if (before) {
315 params.push(
316 z.iso.datetime({ offset: true }).parse(before),
317 uuid.parse(c.req.query("device")),
318 uuid.parse(c.req.query("expedition")),
319 );
320 }
321 return c.json(
322 (
323 await db.query(
324 `SELECT e.* FROM jol_expeditions e JOIN jol_devices d ON d.id=e.device_id
325 WHERE d.owner_id=$1 ${before ? "AND (e.created_at,e.device_id,e.id)<($2::timestamptz,$3::uuid,$4::uuid)" : ""}
326 ORDER BY e.created_at DESC,e.device_id DESC,e.id DESC LIMIT 100`,
327 params,
328 )
329 ).rows,
330 );
331 });
332 app.get("/api/devices/:device/expeditions/:expedition", async (c) => {
333 const d = uuid.parse(c.req.param("device")),
334 e = uuid.parse(c.req.param("expedition"));
335 await owner(d, c.get("identity").id);
336 return c.json(
337 (
338 await db.query(
339 "SELECT * FROM jol_expeditions WHERE device_id=$1 AND id=$2",
340 [d, e],
341 )
342 ).rows,
343 );
344 });
345 app.get("/api/devices/:device/expeditions/:expedition/entries", async (c) => {
346 const d = uuid.parse(c.req.param("device")),
347 e = uuid.parse(c.req.param("expedition"));
348 await owner(d, c.get("identity").id);
349 const before = z.coerce
350 .number()
351 .int()
352 .min(1)
353 .parse(c.req.query("before") ?? 2147483647);
354 return c.json(
355 (
356 await db.query(
357 `SELECT ${entryColumns} FROM jol_entries e ${entryAssetsJoin} WHERE e.device_id=$1 AND e.expedition_id=$2 AND e.position<$3 ORDER BY e.position DESC LIMIT 200`,
358 [d, e, before],
359 )
360 ).rows.reverse(),
361 );
362 });
363 app.post("/api/live", async (c) => {
364 if (!live) throw new APIError(503, "Live updates are not configured");
365 const x = z
366 .object({
367 kind: z.enum([
368 "devices",
369 "expeditions",
370 "expedition",
371 "entries",
372 "commands",
373 ]),
374 deviceID: uuid.optional(),
375 expeditionID: uuid.optional(),
376 after: z.number().int().min(0).default(0),
377 })
378 .parse(await c.req.json());
379 const user = c.get("identity").id;
380 if (x.deviceID) await owner(x.deviceID, user);
381 const query =
382 x.kind === "devices"
383 ? devicesQuery(user)
384 : x.kind === "expeditions"
385 ? expeditionsQuery(user)
386 : x.kind === "commands" && x.deviceID
387 ? commandsQuery(user, x.deviceID)
388 : x.kind === "entries" && x.deviceID && x.expeditionID
389 ? entriesQuery(user, x.deviceID, x.expeditionID, x.after)
390 : x.kind === "expedition" && x.deviceID && x.expeditionID
391 ? expeditionQuery(user, x.deviceID, x.expeditionID)
392 : undefined;
393 if (!query) throw new APIError(400, "Choose a Mac and expedition");
394 return c.json(await live.seal({ query }));
395 });
396 app.post("/api/commands", async (c) => {
397 const x = commandSchema.parse(await c.req.json()),
398 who = c.get("identity").id;
399 await owner(x.deviceID, who);
400 const accepted = await db.transaction(async (q) => {
401 const current = (
402 await q.query(
403 "SELECT remote_enabled,revoked FROM jol_devices WHERE id=$1 AND owner_id=$2 FOR UPDATE",
404 [x.deviceID, who],
405 )
406 ).rows[0];
407 const prior = (
408 await q.query("SELECT * FROM jol_commands WHERE id=$1", [x.id])
409 ).rows[0];
410 if (prior) {
411 if (
412 prior.owner_id !== who ||
413 prior.device_id !== x.deviceID ||
414 prior.kind !== x.kind ||
415 prior.prompt !== x.prompt ||
416 prior.expedition_id !== (x.expeditionID ?? null)
417 )
418 throw new APIError(409, "Conflicting command ID");
419 return { command: prior, created: false };
420 }
421 if (!current?.remote_enabled || current.revoked)
422 throw new APIError(409, "Enable remote missions on this Mac first");
423 if (x.expeditionID) {
424 const e = (
425 await q.query(
426 "SELECT is_finished FROM jol_expeditions WHERE device_id=$1 AND id=$2",
427 [x.deviceID, x.expeditionID],
428 )
429 ).rows[0];
430 if (!e || (e.is_finished && x.kind === "continue"))
431 throw new APIError(409, "Choose an unfinished expedition");
432 }
433 if (x.kind === "stop")
434 await q.query(
435 "UPDATE jol_commands SET status='cancelled',result='Superseded by your stop request' WHERE device_id=$1 AND expedition_id=$2 AND kind='continue' AND status='queued'",
436 [x.deviceID, x.expeditionID],
437 );
438 const outstanding = (
439 await q.query(
440 "SELECT count(*)::int AS count FROM jol_commands WHERE device_id=$1 AND status IN ('queued','received','started')",
441 [x.deviceID],
442 )
443 ).rows[0].count;
444 if (outstanding >= 50)
445 throw new APIError(
446 429,
447 "This Mac already has too many waiting directions",
448 );
449 const command = (
450 await q.query(
451 "INSERT INTO jol_commands(id,owner_id,device_id,expedition_id,kind,prompt,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7) RETURNING *",
452 [
453 x.id,
454 who,
455 x.deviceID,
456 x.expeditionID ?? null,
457 x.kind,
458 x.prompt,
459 new Date(Date.now() + x.ttlMinutes * 60_000),
460 ],
461 )
462 ).rows[0];
463 return { command, created: true };
464 });
465 return c.json(accepted.command, accepted.created ? 201 : 200);
466 });
467 app.get("/api/devices/:device/commands", async (c) => {
468 const d = uuid.parse(c.req.param("device"));
469 await owner(d, c.get("identity").id);
470 return c.json(
471 (
472 await db.query(
473 "SELECT id,kind,prompt,status,result,expedition_id,created_at,expires_at FROM jol_commands WHERE device_id=$1 ORDER BY created_at DESC LIMIT 50",
474 [d],
475 )
476 ).rows,
477 );
478 });
479 app.post("/api/commands/:id/cancel", async (c) => {
480 const id = uuid.parse(c.req.param("id"));
481 const result = await db.query(
482 "UPDATE jol_commands SET status='cancelled' WHERE id=$1 AND owner_id=$2 AND status='queued' RETURNING id",
483 [id, c.get("identity").id],
484 );
485 if (!result.rows.length)
486 throw new APIError(409, "This direction is no longer queued");
487 return c.json({ ok: true });
488 });
489 app.post("/api/devices/:device/commands/claim", async (c) => {
490 const d = uuid.parse(c.req.param("device"));
491 await device(d, c.get("identity").id, c.req.raw);
492 const { busy } = z.object({ busy: z.boolean() }).parse(await c.req.json());
493 return c.json({ command: await claim(db, d, c.get("identity").id, busy) });
494 });
495 app.post("/api/devices/:device/commands/:id/ack", async (c) => {
496 const d = uuid.parse(c.req.param("device")),
497 id = uuid.parse(c.req.param("id"));
498 await device(d, c.get("identity").id, c.req.raw);
499 const x = z
500 .object({
501 fence: z.number().int().min(1),
502 status: z.enum(["started", "finished", "failed", "uncertain"]),
503 result: z.string().max(1000).default(""),
504 })
505 .parse(await c.req.json());
506 const result = await db.query(
507 `UPDATE jol_commands SET status=$4,result=$5,lease_until=now()+interval '90 seconds' WHERE device_id=$1 AND id=$2 AND fence=$3 AND (($4='started' AND lease_until>now() AND status IN ('received','started')) OR ($4<>'started' AND status IN ('received','started','uncertain',$4))) RETURNING id`,
508 [d, id, x.fence, x.status, x.result],
509 );
510 if (!result.rows.length)
511 throw new APIError(
512 409,
513 "Command lease changed; do not repeat the action",
514 );
515 return c.json({ ok: true });
516 });
517 app.get("/api/devices/:device/events", async (c) => {
518 const d = uuid.parse(c.req.param("device")),
519 user = c.get("identity");
520 await device(d, user.id, c.req.raw);
521 if (!live) throw new APIError(503, "Live directions are unavailable");
522 const subscribe = () => live.subscribe(commandInboxQuery(user.id, d));
523 return streamSSE(c, async (stream) => {
524 let closed = false;
525 let subscription: Awaited<ReturnType<typeof subscribe>> | undefined;
526 stream.onAbort(() => {
527 closed = true;
528 subscription?.unsubscribe();
529 });
530 try {
531 subscription = await subscribe();
532 if (closed) return;
533 await subscription.awaitRows(() => true, 10_000);
534 if (closed) return;
535 subscription.onChange(() => {
536 void stream
537 .writeSSE({ event: "commands_changed", data: "{}" })
538 .catch(() => {
539 closed = true;
540 });
541 });
542 subscription.onStateChange((s) => {
543 if (s.status === "error" || s.status === "stale") closed = true;
544 });
545 await stream.writeSSE({ event: "connected", data: "{}" });
546 await stream.writeSSE({ event: "live", data: "{}" });
547 const deadline = Math.min(user.expires - 5000, Date.now() + 40_000);
548 while (!closed && Date.now() < deadline) {
549 await stream.sleep(10_000);
550 if (closed || Date.now() >= deadline) break;
551 const current = (
552 await db.query("SELECT revoked FROM jol_devices WHERE id=$1", [d])
553 ).rows[0];
554 if (!current || current.revoked) break;
555 await stream.writeSSE({ event: "heartbeat", data: "{}" });
556 }
557 } catch {
558 // The Mac reconciles the durable queue while the stream reconnects.
559 } finally {
560 subscription?.unsubscribe();
561 }
562 });
563 });
564 app.put(
565 "/api/devices/:device/expeditions/:expedition/photos/:filename",
566 async (c) => {
567 if (!s3) throw new APIError(503, "Photo sharing is unavailable");
568 const d = uuid.parse(c.req.param("device")),
569 e = uuid.parse(c.req.param("expedition")),
570 filename = z
571 .string()
572 .regex(/^[a-f0-9-]{36}\.jpg$/i)
573 .parse(c.req.param("filename"))
574 .toLowerCase();
575 const entry = uuid.optional().parse(c.req.query("entry"));
576 await device(d, c.get("identity").id, c.req.raw);
577 if (
578 !(
579 await db.query(
580 "SELECT id FROM jol_expeditions WHERE device_id=$1 AND id=$2",
581 [d, e],
582 )
583 ).rows.length
584 )
585 throw new APIError(404, "Expedition not found");
586 if (entry) {
587 const row = (
588 await db.query(
589 "SELECT photo FROM jol_entries WHERE device_id=$1 AND expedition_id=$2 AND id=$3",
590 [d, e, entry],
591 )
592 ).rows[0];
593 if (!row) throw new APIError(404, "Journal entry not found");
594 if (row.photo && row.photo.toLowerCase() !== filename)
595 throw new APIError(
596 409,
597 "This journal entry already has a different photograph",
598 );
599 }
600 const body = new Uint8Array(await c.req.arrayBuffer());
601 if (
602 body.length > 4_000_000 ||
603 body.length < 3 ||
604 body[0] !== 255 ||
605 body[1] !== 216 ||
606 body[2] !== 255
607 )
608 throw new APIError(400, "Expected a JPEG photograph up to 4 MB");
609 const key = `${config.instanceID}/${d}/${e}/${filename}`;
610 await s3.send(
611 new PutObjectCommand({
612 Bucket: config.photoBucket,
613 Key: key,
614 Body: body,
615 ContentType: "image/jpeg",
616 CacheControl: "private, no-store",
617 }),
618 );
619 await db.transaction(async (q) => {
620 if (entry) {
621 // Attach the photograph without changing the accepted journal event.
622 const result = await q.query(
623 "UPDATE jol_entries SET photo=COALESCE(photo,$4) WHERE device_id=$1 AND expedition_id=$2 AND id=$3 AND (photo IS NULL OR lower(photo)=$4) RETURNING id",
624 [d, e, entry, filename],
625 );
626 if (!result.rows.length)
627 throw new APIError(
628 409,
629 "The journal photograph changed during upload",
630 );
631 }
632 await q.query(
633 "INSERT INTO jol_assets(device_id,expedition_id,filename,object_key) VALUES($1,$2,$3,$4) ON CONFLICT DO NOTHING",
634 [d, e, filename, key],
635 );
636 });
637 return c.json({ ok: true, ...(entry ? { entryLinked: true } : {}) });
638 },
639 );
640 app.get(
641 "/api/devices/:device/expeditions/:expedition/photos/:filename",
642 async (c) => {
643 if (!s3) throw new APIError(503, "Photos unavailable");
644 const d = uuid.parse(c.req.param("device")),
645 e = uuid.parse(c.req.param("expedition"));
646 await owner(d, c.get("identity").id);
647 const a = (
648 await db.query(
649 "SELECT object_key FROM jol_assets WHERE device_id=$1 AND expedition_id=$2 AND filename=$3",
650 [d, e, c.req.param("filename").toLowerCase()],
651 )
652 ).rows[0];
653 if (!a) throw new APIError(404, "This photo has not arrived yet");
654 const image = await s3.send(
655 new GetObjectCommand({ Bucket: config.photoBucket, Key: a.object_key }),
656 );
657 const bytes = await image.Body!.transformToByteArray();
658 const exact = new Uint8Array(bytes.byteLength);
659 exact.set(bytes);
660 return c.body(exact.buffer, 200, {
661 "Content-Type": "image/jpeg",
662 "Cache-Control": "private, no-store",
663 });
664 },
665 );
666 for (const [path, asset] of Object.entries(assets))
667 app.get(path, (c) =>
668 c.body(asset.body as any, 200, {
669 "Content-Type": asset.type,
670 "Cache-Control": path.startsWith("/assets/")
671 ? "public, max-age=31536000, immutable"
672 : "no-cache",
673 }),
674 );
675 app.get("/public-config", (c) =>
676 c.json({
677 authURL: config.authURL,
678 origin: config.origin,
679 realtimeURL: config.realtimeURL ?? null,
680 name: config.name,
681 }),
682 );
683 app.notFound((c) => c.json({ error: "Not found" }, 404));
684 return app;