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