/** * A download query's route — the same `GET /_x/query/` every read answers on, so the typed * client, `x routes`, the manifest and OpenAPI need no second URL rule. Without `_token` it MINTS * (`{ url, expiresAt }`, the policy deciding as for any read); with one it SERVES the file: bytes, * `content-disposition`, one `Range:` window, and `no-store` — the bytes are one actor's. */ import { assert, queryPath, recordDeprecatedCall, useContext } from '@ultimat3/core'; import type { RateLimitDecision, Route, RouteMeta, UltimateRequest } from '@ultimat3/http'; import { byteWindow, jsonResponse, type ObjectRequest, objectResponse, publishRateLimit, type RequestedRange, } from '@ultimat3/http'; import { policyCapability } from '@ultimat3/policy'; import { coerceQuery } from '@ultimat3/schema'; import type { DownloadFile } from './download'; import { mintDownloadUrl, serveDownloadFile } from './download'; import { DOWNLOAD_GRANT_PARAM } from './download-token'; import { QueryInputInvalidError } from './errors'; import { rateLimitedByHandler } from './http'; import { absentArraysOf } from './input-shape'; import { pageControlsOf } from './page-controls'; import type { AnyQuery } from './query'; /** The route for `target`, whose `download` is declared. `sunsetting` is `toQueryRoute`'s. */ export function toDownloadRoute( target: AnyQuery, name: string, sunsetting: Readonly> | undefined, ): Route { const handler = async (request: UltimateRequest): Promise => { if (sunsetting !== undefined) { for (const [header, value] of Object.entries(sunsetting)) { request.ctx.headers.set(header, value); } } const { values, token } = tokenOf(name, request.queryRaw()); // A page of a file is not a thing: `_first`/`_after` are refused as on a single read. const { input: rest, page } = pageControlsOf(name, values); if (page !== undefined) { throw new QueryInputInvalidError(name, 'a download answers one file — it takes no _first'); } const input = absentArraysOf(target.input, coerceQuery(target.input, rest)); if (token === undefined) { // The MINT is the call a caller makes; a serve is a player's fetch, often many `Range:` // windows, of a URL this already counted — so only the mint counts, as a rows read does. if (sunsetting !== undefined) recordDeprecatedCall('query', name); const minted = await mintDownloadUrl(target, input, { surface: 'http', clientAddress: request.ctx.ip, onRateLimit: (decision: RateLimitDecision) => publishRateLimit(request.ctx, decision, useContext().now().getTime()), }); return jsonResponse(minted); } const file = await serveDownloadFile(target, input, token, { surface: 'http' }); return fileResponse(request, file); }; const meta: RouteMeta = { name, // PUBLIC, and not unguarded: the mint runs this read's policy inside the handler like every // read (`enforcedBy`), and a serve is authorized by the sealed token the policy minted — the // reason a URL works in a `