The best way to control Claude Code, Codex and more from any computer or phone

main
ts 366 lines 13.7 KB
Raw
1 import {
2 GUEST_ATTACHMENT_ROUTE,
3 GUEST_COMMAND_OUTPUT_ROUTE,
4 GUEST_HISTORY_ROUTE,
5 GUEST_ITEM_ROUTE,
6 GUEST_MEDIA_ROUTE,
7 GUEST_RENDER_ROUTE,
8 GUEST_ROUTE_PREFIX,
9 GUEST_SHARE_PARAM,
10 GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,
11 GUEST_MESSAGE_MAX_ATTACHMENTS,
12 GUEST_SHARE_TTL_MS,
13 GuestRedeemRequest,
14 GuestStreamEvent,
15 GuestSubmitRequest,
16 guestSessionCookieName,
17 isProviderSendTurnSupportedImageMimeType,
18 OrchestrationV2CommandOutputFrame,
19 OrchestrationV2GetTurnItemResult,
20 OrchestrationV2ThreadHistoryPage,
21 } from "@t3tools/contracts";
22 import * as ByteSize from "effect/ByteSize";
23 import * as Duration from "effect/Duration";
24 import * as Effect from "effect/Effect";
25 import * as Layer from "effect/Layer";
26 import * as Schema from "effect/Schema";
27 import { HttpRouter, HttpServerRequest, HttpServerResponse, Multipart } from "effect/http";
28 import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage";
29
30 import { htmlRenderFileName } from "@t3tools/shared/htmlRender";
31
32 import { eventStreamResponse } from "../eventStreamResponse.ts";
33 import { assetFileResponse, downloadContentDisposition } from "../http.ts";
34 import type { GuestUpload } from "./guestAttachments.ts";
35 import { GuestShareAccessError, GuestShareService } from "./GuestShareService.ts";
36
37 const NO_STORE = { "cache-control": "no-store" };
38 // A file never runs as a page on this origin, whatever its bytes.
39 const FILE_HEADERS = {
40 ...NO_STORE,
41 "x-content-type-options": "nosniff",
42 "content-security-policy": "default-src 'none'; sandbox",
43 };
44
45 const decodeRedeem = Schema.decodeUnknownEffect(GuestRedeemRequest);
46 const decodeSubmit = Schema.decodeUnknownEffect(GuestSubmitRequest);
47 // The owner's thread types hold DateTime values; the JSON codec writes them as strings.
48 const encodeStreamEvent = Schema.encodeEffect(
49 Schema.fromJsonString(Schema.toCodecJson(GuestStreamEvent)),
50 );
51 const encodeOutputFrame = Schema.encodeEffect(
52 Schema.fromJsonString(OrchestrationV2CommandOutputFrame),
53 );
54 const encodeItem = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));
55 const encodeHistoryPage = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage));
56
57 const errorResponse = (error: GuestShareAccessError) =>
58 HttpServerResponse.json(
59 { reason: error.reason, message: error.message },
60 {
61 status:
62 error.reason === "invalid" || error.reason === "inactive" || error.reason === "unavailable"
63 ? 403
64 : error.reason === "empty" ||
65 error.reason === "too_many_files" ||
66 error.reason === "too_large" ||
67 error.reason === "unsupported_file"
68 ? 400
69 : 409,
70 headers: NO_STORE,
71 },
72 );
73
74 const badRequest = HttpServerResponse.json(
75 { reason: "invalid", message: "The request was not valid." },
76 { status: 400, headers: NO_STORE },
77 );
78
79 const sessionFor = (request: HttpServerRequest.HttpServerRequest, shareId: string | null) =>
80 shareId === null ? "" : (request.cookies[guestSessionCookieName(shareId)] ?? "");
81
82 const requestedShareId = (request: HttpServerRequest.HttpServerRequest) =>
83 new URLSearchParams(request.url.split("?", 2)[1] ?? "").get(GUEST_SHARE_PARAM);
84
85 /** The session for the share the request names in `?share=`. */
86 const sessionToken = Effect.map(HttpServerRequest.HttpServerRequest, (request) =>
87 sessionFor(request, requestedShareId(request)),
88 );
89
90 /** The `?item=` a per-item route names. */
91 const itemParam = Effect.map(HttpServerRequest.HttpServerRequest, (request) =>
92 new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("item"),
93 );
94
95 // Guest JSON bodies are a name or one message; anyone who can reach the tunnel can post them.
96 const JSON_MAX_BODY_BYTES = 64 * 1024;
97 const readJson = Effect.gen(function* () {
98 const request = yield* HttpServerRequest.HttpServerRequest;
99 // A declared length over the cap is refused before reading; chunked bodies hit the reader cap.
100 if (Number(request.headers["content-length"] ?? "0") > JSON_MAX_BODY_BYTES) {
101 return yield* new GuestShareAccessError({ reason: "too_large" });
102 }
103 return yield* request.json.pipe(
104 Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(JSON_MAX_BODY_BYTES)),
105 );
106 });
107
108 const redeemRoute = HttpRouter.add(
109 "POST",
110 `${GUEST_ROUTE_PREFIX}/redeem`,
111 Effect.gen(function* () {
112 const body = yield* readJson.pipe(Effect.flatMap(decodeRedeem), Effect.option);
113 if (body._tag === "None") return yield* badRequest;
114 const guestShares = yield* GuestShareService;
115 return yield* guestShares.redeem(body.value).pipe(
116 Effect.flatMap(({ token, shareId }) =>
117 HttpServerResponse.empty({ status: 204, headers: NO_STORE }).pipe(
118 HttpServerResponse.setCookie(guestSessionCookieName(shareId), token, {
119 httpOnly: true,
120 secure: true,
121 sameSite: "strict",
122 path: GUEST_ROUTE_PREFIX,
123 maxAge: Duration.millis(GUEST_SHARE_TTL_MS),
124 }),
125 ),
126 ),
127 Effect.catchTags({ GuestShareAccessError: errorResponse }),
128 );
129 }),
130 );
131
132 // The parser stops a request with too many parts or bytes before it reaches the disk; the
133 // service checks the exact limits and types.
134 const UPLOAD_LIMITS = Multipart.limitsServices({
135 maxParts: GUEST_MESSAGE_MAX_ATTACHMENTS + 4,
136 maxFileSize: GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,
137 maxTotalSize: GUEST_MESSAGE_MAX_ATTACHMENT_BYTES + 64 * 1024,
138 // By default a JSON part is read as a field, which would drop a guest's `.json` file.
139 fieldMimeTypes: [],
140 });
141
142 /** A message as JSON (text only), or as multipart form data with `file` parts. */
143 export const readSubmission = Effect.gen(function* () {
144 const request = yield* HttpServerRequest.HttpServerRequest;
145 if (!request.headers["content-type"]?.startsWith("multipart/form-data")) {
146 const body = yield* readJson.pipe(Effect.flatMap(decodeSubmit), Effect.option);
147 return body._tag === "None" ? null : { fields: body.value, uploads: [] };
148 }
149 const parts = yield* request.multipart.pipe(
150 Effect.provideContext(UPLOAD_LIMITS),
151 Effect.mapError(
152 (error) =>
153 new GuestShareAccessError({
154 reason:
155 error.reason._tag === "TooManyParts"
156 ? "too_many_files"
157 : error.reason._tag === "Parse"
158 ? "rejected"
159 : "too_large",
160 }),
161 ),
162 );
163 const text = parts.text ?? "";
164 const fields = yield* decodeSubmit({
165 shareId: parts.shareId,
166 // Form data sends every line break as CRLF; the textarea gave the guest LF.
167 text: typeof text === "string" ? text.replaceAll("\r\n", "\n") : text,
168 }).pipe(Effect.option);
169 if (fields._tag === "None") return null;
170 const files = parts.file;
171 const uploads: ReadonlyArray<GuestUpload> = Array.isArray(files)
172 ? files.filter(Multipart.isPersistedFile).map(({ name, contentType, path }) => ({
173 name,
174 contentType,
175 path,
176 }))
177 : [];
178 return { fields: fields.value, uploads };
179 });
180
181 const submitRoute = HttpRouter.add(
182 "POST",
183 `${GUEST_ROUTE_PREFIX}/messages`,
184 Effect.gen(function* () {
185 const request = yield* HttpServerRequest.HttpServerRequest;
186 const guestShares = yield* GuestShareService;
187 // The session is checked before the body is read, so only a guest can make the server parse
188 // and store up to 10 MB.
189 const shareId = requestedShareId(request);
190 const session = sessionFor(request, shareId);
191 yield* guestShares.check(session);
192 const submission = yield* readSubmission;
193 if (submission === null || submission.fields.shareId !== shareId) return yield* badRequest;
194 yield* guestShares.submit(session, submission.fields, submission.uploads);
195 return HttpServerResponse.empty({ status: 204, headers: NO_STORE });
196 }).pipe(
197 Effect.catchTags({ GuestShareAccessError: errorResponse }),
198 // The parser's temporary files are removed once the response is ready.
199 Effect.scoped,
200 ),
201 );
202
203 const streamRoute = HttpRouter.add(
204 "GET",
205 `${GUEST_ROUTE_PREFIX}/stream`,
206 Effect.gen(function* () {
207 const guestShares = yield* GuestShareService;
208 return yield* guestShares.stream(yield* sessionToken).pipe(
209 Effect.map((events) => eventStreamResponse(events, encodeStreamEvent)),
210 Effect.catchTags({ GuestShareAccessError: errorResponse }),
211 );
212 }),
213 );
214
215 // Lets a returning guest skip the name form when this browser already joined the share.
216 const sessionRoute = HttpRouter.add(
217 "GET",
218 `${GUEST_ROUTE_PREFIX}/session`,
219 Effect.gen(function* () {
220 const guestShares = yield* GuestShareService;
221 return yield* guestShares
222 .check(yield* sessionToken)
223 .pipe(
224 Effect.as(HttpServerResponse.empty({ status: 204, headers: NO_STORE })),
225 Effect.catchTags({ GuestShareAccessError: errorResponse }),
226 );
227 }),
228 );
229
230 // The response carries the asset route's sandbox CSP: the page gets an opaque origin, so its
231 // scripts cannot send the guest cookie or call these routes as the guest.
232 const renderRoute = HttpRouter.add(
233 "GET",
234 GUEST_RENDER_ROUTE,
235 Effect.gen(function* () {
236 const itemId = yield* itemParam;
237 if (!itemId) return yield* badRequest;
238 const guestShares = yield* GuestShareService;
239 return yield* guestShares.render(yield* sessionToken, itemId).pipe(
240 Effect.flatMap(({ path, title }) =>
241 assetFileResponse({ path, mimeType: "text/html", fileName: htmlRenderFileName(title) }),
242 ),
243 // Each load re-checks the share, so a closed, replaced, or expired link stops it at once.
244 Effect.map((response) => HttpServerResponse.setHeaders(response, NO_STORE)),
245 Effect.catchTags({ GuestShareAccessError: errorResponse }),
246 );
247 }),
248 );
249
250 const itemRoute = HttpRouter.add(
251 "GET",
252 GUEST_ITEM_ROUTE,
253 Effect.gen(function* () {
254 const itemId = yield* itemParam;
255 if (!itemId) return yield* badRequest;
256 const guestShares = yield* GuestShareService;
257 return yield* guestShares.item(yield* sessionToken, itemId).pipe(
258 Effect.flatMap((result) =>
259 encodeItem(result).pipe(
260 Effect.mapError(() => new GuestShareAccessError({ reason: "unavailable" })),
261 ),
262 ),
263 Effect.map((body) => HttpServerResponse.jsonUnsafe(body, { headers: NO_STORE })),
264 Effect.catchTags({ GuestShareAccessError: errorResponse }),
265 );
266 }),
267 );
268
269 const historyRoute = HttpRouter.add(
270 "GET",
271 GUEST_HISTORY_ROUTE,
272 Effect.gen(function* () {
273 const request = yield* HttpServerRequest.HttpServerRequest;
274 const cursor = new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("cursor");
275 if (!cursor) return yield* badRequest;
276 const guestShares = yield* GuestShareService;
277 return yield* guestShares.history(yield* sessionToken, cursor).pipe(
278 Effect.flatMap((page) =>
279 encodeHistoryPage(page).pipe(
280 Effect.mapError(() => new GuestShareAccessError({ reason: "unavailable" })),
281 ),
282 ),
283 Effect.map((body) => HttpServerResponse.jsonUnsafe(body, { headers: NO_STORE })),
284 Effect.catchTags({ GuestShareAccessError: errorResponse }),
285 );
286 }),
287 );
288
289 // Ends when the command settles; the page closes its EventSource on that last frame, so the
290 // browser does not reconnect.
291 const commandOutputRoute = HttpRouter.add(
292 "GET",
293 GUEST_COMMAND_OUTPUT_ROUTE,
294 Effect.gen(function* () {
295 const itemId = yield* itemParam;
296 if (!itemId) return yield* badRequest;
297 const guestShares = yield* GuestShareService;
298 return yield* guestShares.commandOutput(yield* sessionToken, itemId).pipe(
299 Effect.map((frames) => eventStreamResponse(frames, encodeOutputFrame)),
300 Effect.catchTags({ GuestShareAccessError: errorResponse }),
301 );
302 }),
303 );
304
305 // Images of the four checked types load inline; anything else downloads as bytes, so a guest's
306 // HTML or SVG never renders as a page on this origin.
307 const attachmentRoute = HttpRouter.add(
308 "GET",
309 GUEST_ATTACHMENT_ROUTE,
310 Effect.gen(function* () {
311 const request = yield* HttpServerRequest.HttpServerRequest;
312 const attachmentId = new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("id");
313 if (!attachmentId) return yield* badRequest;
314 const guestShares = yield* GuestShareService;
315 return yield* guestShares.attachment(yield* sessionToken, attachmentId).pipe(
316 Effect.flatMap(({ path, attachment }) =>
317 HttpServerResponse.file(path, {
318 headers: {
319 ...FILE_HEADERS,
320 ...(attachment.type === "image" &&
321 isProviderSendTurnSupportedImageMimeType(attachment.mimeType)
322 ? { "content-type": attachment.mimeType }
323 : {
324 "content-type": "application/octet-stream",
325 "content-disposition": downloadContentDisposition(attachment.name),
326 }),
327 },
328 }),
329 ),
330 Effect.catchTags({ GuestShareAccessError: errorResponse }),
331 Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 500, headers: NO_STORE })),
332 );
333 }),
334 );
335
336 // Only an image an agent reply shows loads; anything else on the host is refused.
337 const mediaRoute = HttpRouter.add(
338 "GET",
339 GUEST_MEDIA_ROUTE,
340 Effect.gen(function* () {
341 const request = yield* HttpServerRequest.HttpServerRequest;
342 const path = new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("path");
343 if (!path) return yield* badRequest;
344 const guestShares = yield* GuestShareService;
345 return yield* guestShares.media(yield* sessionToken, path).pipe(
346 Effect.flatMap(({ path, mimeType }) =>
347 HttpServerResponse.file(path, { headers: { ...FILE_HEADERS, "content-type": mimeType } }),
348 ),
349 Effect.catchTags({ GuestShareAccessError: errorResponse }),
350 Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 500, headers: NO_STORE })),
351 );
352 }),
353 );
354
355 export const layer = Layer.mergeAll(
356 redeemRoute,
357 sessionRoute,
358 submitRoute,
359 streamRoute,
360 renderRoute,
361 itemRoute,
362 historyRoute,
363 commandOutputRoute,
364 attachmentRoute,
365 mediaRoute,
366 );