/** * A shared space's door on the open host (src/open.ts hands it every `/v1/spaces`, `/v1/spaces/…`, `/v1/space-link/…` * and `/v1/space-media/…` request; `/v1/space` and `/v1/space/…` are the person's own space for files, src/space.ts). * It settles WHO is asking and hands the space's object that and nothing more; the object's one gate decides what * they may do (src/space/space.ts). * * - A person: the bearer is a device credential (`ctd_<database id>_…`); the person's own object vouches it and says * their number (`spaceCaller`), kept in this isolate for VOUCH_MS so a page of thumbnails is not a page of asks. The * database id is the credential's own: a membership is bound to it, never to the number. * - A link holder: the bearer is the link's auth token (derived in the browser from the secret after the `#`, which * never reaches the server); only the link routes take it. * - Media: a signed URL is the whole grant, answered here straight from R2, never through any object. */importtype { Env } from"../env.ts";import { answerRefusal, json, readJson, refuse } from"../http.ts";import { MEDIA_MAX_BYTES, rangeOf, SEALED_FILE_TYPE } from"../media.ts";import { isSpacePath, routeOf } from"./routes.ts";import { admit, fileAt, MEDIA_PATH } from"./signed.ts";import { freshId, spaceObject, typeAnswer, typeCaller } from"./space.ts";/** A device credential, which names its database. MCP tokens are not taken: a space is a phone's. */const DEVICE_CREDENTIAL = /^ctd_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})_./;const LINK_TOKEN = /^[A-Za-z0-9_-]{43}$/;/** A vouch kept in this isolate: short, so an ended sign-in stops opening spaces within half a minute. */const VOUCH_MS = 30 * 1000;const vouched = newMap<string, { number: string; slug: string; database: string; until: number }>();/** What the person's object answers the door (src/business.ts). */interfaceVoucher { spaceCaller(token: string): Promise<{ number: string } | null>; spacesIn(): Promise<{ space: string; at: number; app: string }[]>;}exportinterfaceDoorHost { token: string | null;/** The slug of a database's object, from the directory. */ objectOf(databaseId: string): Promise<string | null>;}/** The space's answer, or null when the path is not a space's. */exportasyncfunction door(request: Request, env: Env, url: URL, host: DoorHost): Promise<Response | null> {const path = url.pathname;const media = MEDIA_PATH.exec(path);if (media) {try {returnawait mediaAtDoor(request, env, media[1]!, media[2]!, media[3]!); } catch (error) {// A refused upload's body is let go, not left half read.if (request.body && !request.bodyUsed) await request.body.cancel().catch(() => undefined);return withCors(answerRefusal(error)); } }if (!isSpacePath(path)) returnnull;const matched = routeOf(request.method, path);if (!matched) return json({ code: "not_found", message: "no such route" }, 404);const { route, space, link } = matched;let caller: Caller;if (route.need === "link") {if (!host.token || !LINK_TOKEN.test(host.token)) return json({ code: "no_space", message: "That is not there." }, 404); caller = { kind: "link", link: link!, auth: host.token }; } else {const person = await vouch(env, host);if (!person) return json({ code: "sign_in", message: "a shared space is opened from a signed-in phone" }, 401); caller = { kind: "person", number: person.number, slug: person.slug, database: person.database }; }if (route.name === "spaces.list") {const slug = (caller asExtract<Caller, { kind: "person" }>).slug;const voucher = env.BUSINESS.get(env.BUSINESS.idFromName(slug), { locationHint: "apac" }) as unknown asVoucher;return json({ spaces: await voucher.spacesIn() }); }const body = request.method === "POST" ? await readJson(request).catch(() => ({}) asRecord<string, unknown>) : {};const id = route.name === "spaces.found" ? freshId() : space!;const query = Object.fromEntries(url.searchParams.entries());const answer = (await spaceObject(env, id).handle(caller, { route: route.name as never, space: id, link, query, body, base: url.origin })) as unknown asAnswer;return json(answer.body, answer.status);}asyncfunction vouch(env: Env, host: DoorHost): Promise<{ number: string; slug: string; database: string } | null> {const token = host.token;const named = token ? DEVICE_CREDENTIAL.exec(token) : null;if (!token || !named) returnnull;const held = vouched.get(token);if (held && held.until > Date.now()) return held;const slug = await host.objectOf(named[1]!);if (!slug) returnnull;const voucher = env.BUSINESS.get(env.BUSINESS.idFromName(slug), { locationHint: "apac" }) as unknown asVoucher;const who = await voucher.spaceCaller(token);if (!who) { vouched.delete(token);returnnull; }const person = { number: who.number, slug, database: named[1]!, until: Date.now() + VOUCH_MS };if (vouched.size > 10_000) vouched.clear(); vouched.set(token, person);return person;}/** Forget every vouch this isolate holds (tests that end a sign-in). */exportfunction forgetVouches(): void { vouched.clear();}const CORS: Record<string, string> = {"access-control-allow-origin": "*","access-control-expose-headers": "content-length, content-range, accept-ranges, etag",};function withCors(response: Response): Response {const opened = newResponse(response.body, response);for (const [k, v] ofObject.entries(CORS)) opened.headers.set(k, v);return opened;}/** `GET|HEAD|PUT /v1/space-media/<token>/<space>/<file>`: by the signed URL alone, straight to and from R2. */asyncfunction mediaAtDoor(request: Request, env: Env, token: string, space: string, file: string): Promise<Response> {const method = request.method;if (method === "OPTIONS") {returnnewResponse(null, { status: 204, headers: { ...CORS, "access-control-allow-methods": "GET, HEAD, PUT", "access-control-allow-headers": "range, content-type", "access-control-max-age": "86400" } }); }const grant = await admit(env, token, space, file);const at = fileAt(space, file);if (method === "PUT") {if (grant.op !== "w" || grant.size === null) refuse(403, "bad_media_token", "this URL reads; it does not write");const length = Number(request.headers.get("content-length") ?? NaN);if (length !== grant.size || length > MEDIA_MAX_BYTES) refuse(400, "bad_length", "send exactly the length the upload was granted for");// Single use: the space hands out the one PUT for a file it granted and has not had yet, before a byte is written.const object = spaceObject(env, space);if (!(await object.claim(file, grant.size))) refuse(409, "upload_used", "this upload URL has been used, or its upload is gone; ask for a new one");const put = await env.MEDIA.put(at, request.body, { httpMetadata: { contentType: SEALED_FILE_TYPE } });if (!put || put.size !== grant.size || !(await object.landed(file, put.size))) {await env.MEDIA.delete(at); refuse(400, "bad_length", "the upload was not the length granted"); }return withCors(json({ ok: true, file, bytes: put.size })); }if (method !== "GET" && method !== "HEAD") refuse(405, "method_not_allowed", "a space's file takes GET, HEAD and PUT");if (grant.op !== "r") refuse(403, "bad_media_token", "this URL writes; it does not read");const held = await env.MEDIA.head(at);if (!held) refuse(404, "not_found", "no such file");const headers = newHeaders({ ...CORS, "content-type": SEALED_FILE_TYPE, "cache-control": "private, max-age=900", "accept-ranges": "bytes", etag: held.httpEtag });const range = rangeOf(request.headers.get("range"), held.size);if (range === "unsatisfiable") { headers.set("content-range", `bytes */${held.size}`);returnnewResponse(null, { status: 416, headers }); }if (range) { headers.set("content-range", `bytes ${range.offset}-${range.offset + range.length - 1}/${held.size}`); headers.set("content-length", String(range.length)); } else { headers.set("content-length", String(held.size)); }const status = range ? 206 : 200;if (method === "HEAD") returnnewResponse(null, { status, headers });const object = await env.MEDIA.get(at, range ? { range } : {});if (!object) refuse(404, "not_found", "no such file");returnnewResponse(object.body, { status, headers });}