Skip to content
38 linesCodeBlameRaw
1import { env } from "cloudflare:workers";
2
3import { DOCS_VIEWER_HEADER } from "@g1t/contracts";
4
5import type { Route } from "./+types/live";
6import { roleIn } from "../../../lib/session.server";
7import { socketViewer } from "../../../lib/socket-ticket.server";
8
9/**
10 * An artifact's live socket: `wss://<site>/<workspace>/-/artifacts/live?folio=<id>`.
11 * The site checks the session and that the page asking is the site's own,
12 * then hands the upgrade to the artifacts service with the viewer, which checks
13 * their role in the folio and gives the socket to its room (one Durable
14 * Object per folio, any kind), which enforces that role.
15 */
16export async function loader({ params, context, request }: Route.LoaderArgs) {
17 // A session, or a page opened with a token by its socket ticket.
18 const viewer = await socketViewer(context, request);
19 if (!viewer) return new Response("Sign in to use Artifacts.", { status: 401 });
20 if (!roleIn(viewer, params.owner)) return new Response("Not found", { status: 404 });
21 if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") {
22 return new Response("This address takes a WebSocket.", { status: 426, headers: { upgrade: "websocket" } });
23 }
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 folio = new URL(request.url).searchParams.get("folio");
27 if (!folio) return new Response("Which artifact?", { status: 400 });
28 const headers = new Headers(request.headers);
29 headers.delete("cookie");
30 headers.set(DOCS_VIEWER_HEADER, JSON.stringify(viewer));
31 const target = `https://docs/live?folio=${encodeURIComponent(folio)}&workspace=${encodeURIComponent(params.owner.toLowerCase())}`;
32 try {
33 return await env.ARTIFACTS.fetch(new Request(target, { method: "GET", headers }));
34 } catch (error) {
35 console.error("artifacts: the live socket could not be handed over", error);
36 return new Response("Artifacts didn't answer.", { status: 503 });
37 }
38}