UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

124 lines (122 loc) • 5.74 kB
import { assert } from "./assertions.js"; import { fetch } from "./fetch.js"; import { asSignedOutVisitor } from "./auth/session.js"; import { getRecord } from "./datasource/record.js"; import { recordIdFromSlug } from "./record-url.js"; import { z } from "zod"; //#region src/record-image.ts /** App workers cannot use the default cache, so the record images have a named cache of their own. */ const CACHE_NAME = "softr-record-images"; /** How long an image stays cached. A photo that changes shows within this time. */ const IMAGE_SECONDS = 1440 * 60; /** How long a 404 stays cached. Long enough for a bot that asks again, short enough for a photo added later. */ const MISSING_SECONDS = 3600; /** The largest image the route sends. Link previews take less, and a larger one would fill the cache. */ const MAX_BYTES = 5 * 1024 * 1024; /** How many redirects a download may follow. */ const MAX_REDIRECTS = 3; /** * Answers an app route with the image in one field of one record, for link * previews and search engines. An attachment URL stops working within hours, * and they keep an image URL for weeks. So a page's `og:image` and structured * data point to this route, while the page's own `<img>` keeps the URL its * loader read. * * The route's one path parameter is the record id, plain or as `recordSlug` * made it. The handler reads the record as a signed-out visitor and sends the * large thumbnail of the field's first image, else the image itself. It keeps * the image for a day. It answers 404 when the query is not open to signed-out * visitors, when they cannot read the record, when the field has no image, for * an image over 5 MB, and for an image that is not on a public host over HTTPS. * It keeps a 404 for an hour. * * @example * // src/routes/images/bikes/$bikeId.ts * export const Route = createFileRoute("/images/bikes/$bikeId")({ * server: { handlers: { GET: recordImage({ query: bikesQuery, field: "photo" }) } }, * }) */ function recordImage(source) { const { query, field } = source; return async ({ request, params }) => { const segments = Object.values(params); assert(segments.length === 1, `An image route has one path parameter, the record id. This one has ${segments.length}.`); if (!query.permissions.userGroupTypes.includes("NON_LOGGED_IN_USERS")) return new Response("Not found", { status: 404 }); const id = recordIdFromSlug(segments[0]); const cache = typeof caches !== "undefined" ? await caches.open(CACHE_NAME) : null; const build = typeof __SOFTR_BUILD_ID__ === "undefined" ? "dev" : __SOFTR_BUILD_ID__; const key = new Request(`${new URL(request.url).origin}/.softr-record-image?${new URLSearchParams({ query: query.id, field, id, build })}`); const stored = await cache?.match(key); if (stored !== void 0) return new Response(stored.body, stored); const response = await readImage(query, field, id); if (cache !== null) await cache.put(key, response.clone()); return response; }; } const ATTACHMENT = z.object({ url: z.string(), type: z.string().nullish(), thumbnails: z.array(z.object({ size: z.string(), url: z.string() })).optional() }); /** The image of one record as a response to keep, or a 404 to keep for a shorter time. */ async function readImage(query, field, id) { const missing = new Response("Not found", { status: 404, headers: { "Cache-Control": `max-age=${MISSING_SECONDS}` } }); const value = (await asSignedOutVisitor(() => getRecord(query, { id })))?.fields[field]; const image = (Array.isArray(value) ? value : [value]).map((item) => ATTACHMENT.safeParse(item)).flatMap((parsed) => parsed.success ? [parsed.data] : []).find(({ type: type$1 }) => type$1 == null || type$1.startsWith("image/")); if (image === void 0) return missing; const download = await downloadFromPublicHost(image.thumbnails?.find(({ size: size$1 }) => size$1 === "large")?.url ?? image.url); if (download === null) return missing; const sent = download.headers.get("Content-Type") ?? ""; const type = sent.startsWith("image/") ? sent : sent === "" || sent.startsWith("application/octet-stream") ? image.type ?? "" : ""; if (!download.ok || download.body === null || !type.startsWith("image/") || Number(download.headers.get("Content-Length")) > MAX_BYTES) { await download.body?.cancel(); return missing; } const reader = download.body.getReader(); const chunks = []; let size = 0; for (let read = await reader.read(); !read.done; read = await reader.read()) { size += read.value.byteLength; if (size > MAX_BYTES) { await reader.cancel(); return missing; } chunks.push(read.value); } return new Response(new Blob(chunks), { headers: { "Content-Type": type, "Cache-Control": `max-age=${IMAGE_SECONDS}` } }); } /** * Downloads `href` when it, and each address it redirects to, is on a public host over HTTPS. Null otherwise. An * attachment URL is record data, so this keeps it from reaching the app server's own network, such as a cloud's * metadata address. */ async function downloadFromPublicHost(href) { let url = URL.parse(href); for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) { if (url === null) return null; const host = url.hostname.replace(/\.$/, ""); if (!(url.protocol === "https:" && host.includes(".") && !/^[\d.]+$/.test(host) && !host.startsWith("[") && !/\.(?:local|localhost|internal|lan|home\.arpa)$/.test(host))) return null; const response = await fetch(url, { redirect: "manual" }); const location = response.headers.get("Location"); if (response.status < 300 || response.status > 399 || location === null) return response; await response.body?.cancel(); url = URL.parse(location, url); } return null; } //#endregion export { recordImage };