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