Skip to content
40 linesCodeBlameRaw

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Chat and workspace agents: channels, DMs and named agents you talk to1import { env } from "cloudflare:workers";
2
3import { CHAT_VIEWER_HEADER } from "@g1t/contracts";
4
5import type { Route } from "./+types/live";
6import { getViewer, roleIn } from "../../../lib/session.server";
7
8/**
9 * A conversation's live socket: `wss://<site>/<workspace>/-/chat/live?channel=<id>`.
10 * The site checks the session and that the page asking is the site's own,
11 * then hands the upgrade to the chat service with the viewer, which checks
12 * they may read the channel and keeps the socket (one Durable Object per
13 * channel, hibernating while nothing happens).
14 */
15export async function loader({ params, context, request }: Route.LoaderArgs) {
16 const viewer = getViewer(context);
17 if (!viewer) return new Response("Sign in to use chat.", { status: 401 });
18 if (!roleIn(viewer, params.owner)) return new Response("Not found", { status: 404 });
19 if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") {
20 return new Response("This address takes a WebSocket.", { status: 426, headers: { upgrade: "websocket" } });
21 }
22 // Only the site's own pages may open it: a page elsewhere carries the
23 // cookie too, so the origin is what tells them apart.
24 const origin = request.headers.get("origin");
25 if (origin && origin !== new URL(request.url).origin) return new Response("Cross-origin socket refused", { status: 403 });
26 const channel = new URL(request.url).searchParams.get("channel");
27 if (!channel) return new Response("Which channel?", { status: 400 });
28 const headers = new Headers(request.headers);
29 // Neither the session nor anything else of the browser's goes on.
30 headers.delete("cookie");
31 headers.set(CHAT_VIEWER_HEADER, JSON.stringify(viewer));
32 headers.set("x-g1t-workspace", params.owner.toLowerCase());
33 const target = `https://chat/live?channel=${encodeURIComponent(channel)}&workspace=${encodeURIComponent(params.owner.toLowerCase())}`;
34 try {
35 return await env.CHAT.fetch(new Request(target, { method: "GET", headers }));
36 } catch (error) {
37 console.error("chat: the live socket could not be handed over", error);
38 return new Response("Chat didn't answer.", { status: 503 });
39 }
40}