gemi 0.242.0 → 0.242.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-093j5rh8.js.map +1 -1
- package/dist/{chunk-daw2xr2v.js → chunk-1dc3kxdd.js} +2 -2
- package/dist/{chunk-daw2xr2v.js.map → chunk-1dc3kxdd.js.map} +3 -3
- package/dist/{chunk-0sr3cfex.js → chunk-8gc7rygz.js} +1 -1
- package/dist/{chunk-7gqq3834.js → chunk-d8aegerq.js} +1 -1
- package/dist/{chunk-evx7nxad.js → chunk-j26v29x8.js} +1 -1
- package/dist/{chunk-xt4ssej8.js → chunk-zd73z5av.js} +2 -2
- package/dist/{chunk-xt4ssej8.js.map → chunk-zd73z5av.js.map} +2 -2
- package/dist/facades/Storage.d.ts +2 -2
- package/dist/facades/Storage.d.ts.map +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/image-optimization/drivers/SharpDriver.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +6 -0
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/package.json +2 -2
- /package/dist/{chunk-0sr3cfex.js.map → chunk-8gc7rygz.js.map} +0 -0
- /package/dist/{chunk-7gqq3834.js.map → chunk-d8aegerq.js.map} +0 -0
- /package/dist/{chunk-evx7nxad.js.map → chunk-j26v29x8.js.map} +0 -0
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"/**\n * IP addresses as bytes, and which of them are not on the public internet.\n *\n * Everything here works on parsed bytes, never on strings: an address is\n * classified the same way however it was written (`127.0.0.1`, `2130706433`,\n * `0x7f.1`, `0177.0.0.1`, `::ffff:127.0.0.1`, `::ffff:7f00:1`).\n */\n\nexport type ParsedAddress =\n | { family: 4; bytes: Uint8Array }\n | { family: 6; bytes: Uint8Array };\n\n/**\n * Why an address is refused. `null` from `classifyAddress` means the address\n * is publicly routable.\n */\nexport type AddressRange =\n | \"unspecified\"\n | \"loopback\"\n | \"private\"\n | \"link-local\"\n | \"shared\"\n | \"metadata\"\n | \"multicast\"\n | \"broadcast\"\n | \"documentation\"\n | \"benchmarking\"\n | \"unique-local\"\n | \"reserved\";\n\n/**\n * Parses an IPv4 address the way a URL host parser (and `inet_aton`) does: one\n * to four parts, each decimal, octal (leading `0`) or hex (`0x`), the last part\n * filling the remaining bytes. `\"2130706433\"`, `\"0x7f.1\"` and `\"0177.0.0.1\"`\n * all parse to 127.0.0.1. Returns `null` for anything that is not an address.\n */\nexport function parseIPv4(input: string): Uint8Array | null {\n if (input === \"\") return null;\n const parts = input.split(\".\");\n // One trailing dot is allowed (\"127.0.0.1.\"), as in a URL host.\n if (parts.length > 1 && parts[parts.length - 1] === \"\") parts.pop();\n if (parts.length === 0 || parts.length > 4) return null;\n const numbers: number[] = [];\n for (const part of parts) {\n const value = parseIPv4Part(part);\n if (value === null) return null;\n numbers.push(value);\n }\n const last = numbers.pop()!;\n for (const value of numbers) if (value > 255) return null;\n if (last >= 256 ** (4 - numbers.length)) return null;\n let total = last;\n numbers.forEach((value, index) => {\n total += value * 256 ** (3 - index);\n });\n return new Uint8Array([\n Math.floor(total / 2 ** 24) & 255,\n Math.floor(total / 2 ** 16) & 255,\n Math.floor(total / 2 ** 8) & 255,\n total & 255,\n ]);\n}\n\nfunction parseIPv4Part(part: string): number | null {\n if (part === \"\") return null;\n let digits = part;\n let radix = 10;\n if (/^0x/i.test(digits)) {\n digits = digits.slice(2);\n radix = 16;\n if (digits === \"\") return 0;\n } else if (digits.length > 1 && digits.startsWith(\"0\")) {\n digits = digits.slice(1);\n radix = 8;\n }\n const pattern =\n radix === 16 ? /^[0-9a-f]+$/i : radix === 8 ? /^[0-7]+$/ : /^[0-9]+$/;\n if (!pattern.test(digits)) return null;\n const value = parseInt(digits, radix);\n return Number.isSafeInteger(value) ? value : null;\n}\n\n/**\n * Parses an IPv6 address, with or without brackets and a zone (`fe80::1%en0`),\n * including a dotted IPv4 tail (`::ffff:10.0.0.1`).\n */\nexport function parseIPv6(input: string): Uint8Array | null {\n let text = input;\n if (text.startsWith(\"[\") && text.endsWith(\"]\")) text = text.slice(1, -1);\n const zone = text.indexOf(\"%\");\n if (zone !== -1) text = text.slice(0, zone);\n if (!text.includes(\":\")) return null;\n\n const halves = text.split(\"::\");\n if (halves.length > 2) return null;\n const parseGroups = (half: string, lastHalf: boolean): number[] | null => {\n if (half === \"\") return [];\n const groups: number[] = [];\n const pieces = half.split(\":\");\n for (let index = 0; index < pieces.length; index++) {\n const piece = pieces[index];\n if (lastHalf && index === pieces.length - 1 && piece.includes(\".\")) {\n if (!/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(piece)) return null;\n const v4 = piece.split(\".\").map(Number);\n if (v4.some((byte) => byte > 255)) return null;\n groups.push((v4[0] << 8) | v4[1], (v4[2] << 8) | v4[3]);\n continue;\n }\n if (!/^[0-9a-f]{1,4}$/i.test(piece)) return null;\n groups.push(parseInt(piece, 16));\n }\n return groups;\n };\n const head = parseGroups(halves[0], halves.length === 1);\n const tail = halves.length === 2 ? parseGroups(halves[1], true) : [];\n if (!head || !tail) return null;\n let groups: number[];\n if (halves.length === 2) {\n const missing = 8 - head.length - tail.length;\n if (missing < 1) return null;\n groups = [...head, ...Array.from({ length: missing }, () => 0), ...tail];\n } else {\n groups = head;\n }\n if (groups.length !== 8) return null;\n const bytes = new Uint8Array(16);\n groups.forEach((group, index) => {\n bytes[index * 2] = group >> 8;\n bytes[index * 2 + 1] = group & 255;\n });\n return bytes;\n}\n\n/** Parses an IPv4 (in any notation) or IPv6 address. */\nexport function parseAddress(input: string): ParsedAddress | null {\n const v6 = parseIPv6(input);\n if (v6) return { family: 6, bytes: v6 };\n const v4 = parseIPv4(input);\n if (v4) return { family: 4, bytes: v4 };\n return null;\n}\n\n/**\n * The IPv4 address an IPv6 address stands for when it is IPv4-mapped\n * (`::ffff:a.b.c.d`), so the two forms are one address everywhere.\n */\nexport function unmap(address: ParsedAddress): ParsedAddress {\n if (address.family === 6 && isMapped(address.bytes)) {\n return { family: 4, bytes: address.bytes.slice(12) };\n }\n return address;\n}\n\nfunction isMapped(bytes: Uint8Array) {\n for (let index = 0; index < 10; index++) if (bytes[index] !== 0) return false;\n return bytes[10] === 0xff && bytes[11] === 0xff;\n}\n\nexport function formatAddress(address: ParsedAddress): string {\n if (address.family === 4) return Array.from(address.bytes).join(\".\");\n const groups: string[] = [];\n for (let index = 0; index < 16; index += 2) {\n groups.push(\n ((address.bytes[index] << 8) | address.bytes[index + 1]).toString(16),\n );\n }\n return groups.join(\":\");\n}\n\nexport type Cidr = { family: 4 | 6; bytes: Uint8Array; prefix: number };\n\n/** Parses `10.0.0.0/8`, `fc00::/7`, or a bare address (a /32 or /128). */\nexport function parseCidr(input: string): Cidr | null {\n const slash = input.lastIndexOf(\"/\");\n const addressText = slash === -1 ? input : input.slice(0, slash);\n // CIDRs are configuration, written by hand: only the plain notations.\n const address = /^[0-9.]+$/.test(addressText)\n ? strictIPv4(addressText)\n : parseIPv6(addressText);\n if (!address) return null;\n const parsed = unmap(\n address.length === 4\n ? { family: 4, bytes: address }\n : { family: 6, bytes: address },\n );\n const max = parsed.family === 4 ? 32 : 128;\n let prefix = max;\n if (slash !== -1) {\n const prefixText = input.slice(slash + 1);\n if (!/^\\d{1,3}$/.test(prefixText)) return null;\n prefix = Number(prefixText);\n // A mapped CIDR (`::ffff:10.0.0.0/104`) is narrowed to its IPv4 prefix.\n if (address.length === 16 && parsed.family === 4) prefix -= 96;\n if (prefix < 0 || prefix > max) return null;\n }\n return { family: parsed.family, bytes: parsed.bytes, prefix };\n}\n\nfunction strictIPv4(text: string) {\n return /^\\d{1,3}(\\.\\d{1,3}){3}$/.test(text) &&\n text.split(\".\").every((part) => Number(part) <= 255)\n ? new Uint8Array(text.split(\".\").map(Number))\n : null;\n}\n\nexport function inCidr(address: ParsedAddress, cidr: Cidr): boolean {\n const plain = unmap(address);\n if (plain.family !== cidr.family) return false;\n let remaining = cidr.prefix;\n for (let index = 0; remaining > 0; index++) {\n const bits = Math.min(8, remaining);\n const mask = (0xff << (8 - bits)) & 0xff;\n if ((plain.bytes[index] & mask) !== (cidr.bytes[index] & mask))\n return false;\n remaining -= bits;\n }\n return true;\n}\n\nconst range = (cidr: string, kind: AddressRange) => ({\n cidr: parseCidr(cidr)!,\n kind,\n text: cidr,\n});\n\n// IANA's IPv4 special-purpose registry, the entries that are not globally\n// reachable, plus the cloud metadata endpoints that are not in it. Order\n// matters only for the label: the first match names the reason.\nconst IPV4_RANGES = [\n range(\"0.0.0.0/8\", \"unspecified\"),\n range(\"10.0.0.0/8\", \"private\"),\n range(\"100.64.0.0/10\", \"shared\"),\n range(\"127.0.0.0/8\", \"loopback\"),\n range(\"169.254.169.254/32\", \"metadata\"),\n range(\"169.254.0.0/16\", \"link-local\"),\n range(\"168.63.129.16/32\", \"metadata\"),\n range(\"172.16.0.0/12\", \"private\"),\n range(\"192.0.0.0/24\", \"reserved\"),\n range(\"192.0.2.0/24\", \"documentation\"),\n range(\"192.88.99.0/24\", \"reserved\"),\n range(\"192.168.0.0/16\", \"private\"),\n range(\"198.18.0.0/15\", \"benchmarking\"),\n range(\"198.51.100.0/24\", \"documentation\"),\n range(\"203.0.113.0/24\", \"documentation\"),\n range(\"224.0.0.0/4\", \"multicast\"),\n range(\"255.255.255.255/32\", \"broadcast\"),\n range(\"240.0.0.0/4\", \"reserved\"),\n];\n\nconst IPV6_RANGES = [\n range(\"::/128\", \"unspecified\"),\n range(\"::1/128\", \"loopback\"),\n range(\"64:ff9b:1::/48\", \"private\"),\n // IPv4-compatible and the rest of the reserved ::/8.\n range(\"::/8\", \"reserved\"),\n range(\"100::/64\", \"reserved\"),\n range(\"2001:db8::/32\", \"documentation\"),\n // IETF protocol assignments, Teredo (an IPv4 address hidden in the bits).\n range(\"2001::/23\", \"reserved\"),\n range(\"3fff::/20\", \"documentation\"),\n range(\"fd00:ec2::254/128\", \"metadata\"),\n range(\"fc00::/7\", \"unique-local\"),\n range(\"fe80::/10\", \"link-local\"),\n range(\"fec0::/10\", \"private\"),\n range(\"ff00::/8\", \"multicast\"),\n];\n\nconst NAT64 = parseCidr(\"64:ff9b::/96\")!;\nconst SIX_TO_FOUR = parseCidr(\"2002::/16\")!;\nconst GLOBAL_UNICAST = parseCidr(\"2000::/3\")!;\n\nexport type Classification = { kind: AddressRange; range: string };\n\n/**\n * Which non-public range an address is in, or `null` when it is publicly\n * routable. IPv6 forms that carry an IPv4 address (mapped, NAT64, 6to4) are\n * judged by the IPv4 address they carry.\n */\nexport function classifyAddress(\n input: string | ParsedAddress,\n): Classification | null {\n const parsed = typeof input === \"string\" ? parseAddress(input) : input;\n if (!parsed) return { kind: \"reserved\", range: \"not an IP address\" };\n const address = unmap(parsed);\n if (address.family === 4) {\n const match = IPV4_RANGES.find((entry) => inCidr(address, entry.cidr));\n return match ? { kind: match.kind, range: match.text } : null;\n }\n if (inCidr(address, NAT64)) {\n return classifyAddress({ family: 4, bytes: address.bytes.slice(12) });\n }\n if (inCidr(address, SIX_TO_FOUR)) {\n return classifyAddress({ family: 4, bytes: address.bytes.slice(2, 6) });\n }\n const match = IPV6_RANGES.find((entry) => inCidr(address, entry.cidr));\n if (match) return { kind: match.kind, range: match.text };\n // Only 2000::/3 is allocated as global unicast; everything else is reserved.\n return inCidr(address, GLOBAL_UNICAST)\n ? null\n : { kind: \"reserved\", range: \"outside 2000::/3\" };\n}\n\n/** Two addresses are the same once mapped IPv6 is folded into IPv4. */\nexport function sameAddress(a: ParsedAddress, b: ParsedAddress) {\n const left = unmap(a);\n const right = unmap(b);\n return (\n left.family === right.family &&\n left.bytes.every((byte, index) => byte === right.bytes[index])\n );\n}\n",
|
|
26
26
|
"import { lookup as dnsLookup } from \"node:dns/promises\";\nimport * as http from \"node:http\";\nimport * as https from \"node:https\";\nimport type { Socket } from \"node:net\";\nimport type { Readable } from \"node:stream\";\nimport * as zlib from \"node:zlib\";\n\nimport {\n classifyAddress,\n formatAddress,\n inCidr,\n parseAddress,\n parseCidr,\n sameAddress,\n unmap,\n type Cidr,\n type ParsedAddress,\n} from \"./addresses\";\nimport {\n BlockedAddressError,\n BlockedHostError,\n ContentTypeError,\n DnsError,\n InvalidUrlError,\n NetworkError,\n SafeFetchError,\n TimeoutError,\n TooLargeError,\n TooManyRedirectsError,\n} from \"./errors\";\n\nexport type SafeFetchOptions = {\n method?: string;\n headers?: HeadersInit;\n /** Anything `fetch` takes as a body; it is read into memory before sending. */\n body?: BodyInit | null;\n /** Aborting it rejects (or errors the body stream) with the signal's reason. */\n signal?: AbortSignal;\n /** The whole request in ms: every redirect hop and reading the body. Default 30 000. */\n timeout?: number;\n /**\n * Resolving and connecting (TCP and TLS), per hop, in ms. Default 10 000.\n * On Bun before 1.4, whose node:http doesn't report the connection, it runs\n * until the response headers arrive instead.\n */\n connectTimeout?: number;\n /** Largest response body accepted, in bytes after decompression. Default 10 MiB. */\n maxSize?: number;\n /** Redirects followed before `TooManyRedirectsError`. Default 5. */\n maxRedirects?: number;\n /** `\"manual\"` returns a redirect response as it is, without following it. Default `\"follow\"`. */\n redirect?: \"follow\" | \"manual\";\n /**\n * Media types the final response may have, e.g. `[\"text/html\", \"image/*\"]`.\n * Anything else rejects with `ContentTypeError` before the body is read.\n */\n contentTypes?: readonly string[];\n /** Ports a URL may use. Default `[80, 443]`; `\"any\"` allows every port. */\n ports?: readonly number[] | \"any\";\n /**\n * When set, only these may be reached: host names (`\"example.com\"`, or\n * `\"*.example.com\"` for its subdomains) and IP ranges (`\"203.0.113.0/24\"`),\n * which every address the host resolves to must be in. An allowed host is\n * still refused when it resolves to a private address.\n */\n allow?: readonly string[];\n /** Host names and IP ranges never reached, in the same notation as `allow`. Wins over `allow`. */\n deny?: readonly string[];\n /**\n * Lets private, loopback and other non-public addresses through: `true` for\n * all of them (tests, local development), or a list of ranges\n * (`[\"10.20.0.0/16\"]`) for an internal service. Never set it from user input.\n */\n allowPrivate?: boolean | readonly string[];\n /**\n * Resolves a host name to its addresses. Defaults to the system resolver\n * (`dns.lookup`, so `/etc/hosts` applies). The connection is made to the\n * addresses returned here, after they are checked; nothing resolves the\n * name again.\n */\n resolve?: (hostname: string) => Promise<readonly string[]>;\n};\n\n/**\n * The response of `safeFetch`: a standard `Response`, with `url` and\n * `redirected` filled in as `fetch` does, and the address it connected to.\n */\nexport class SafeResponse extends Response {\n readonly #url: string;\n readonly #redirected: boolean;\n /**\n * The IP address the response came from, or `null` when the runtime doesn't\n * report it (Bun before 1.4).\n */\n readonly address: string | null;\n\n constructor(\n body: ReadableStream<Uint8Array> | null,\n init: ResponseInit,\n meta: { url: string; redirected: boolean; address: string | null },\n ) {\n super(body, init);\n this.#url = meta.url;\n this.#redirected = meta.redirected;\n this.address = meta.address;\n }\n\n override get url() {\n return this.#url;\n }\n\n override get redirected() {\n return this.#redirected;\n }\n}\n\nconst DEFAULTS = {\n timeout: 30_000,\n connectTimeout: 10_000,\n maxSize: 10 * 1024 * 1024,\n maxRedirects: 5,\n ports: [80, 443] as readonly number[],\n};\n\nconst REDIRECTS = new Set([301, 302, 303, 307, 308]);\nconst NULL_BODY = new Set([101, 103, 204, 205, 304]);\n// What the caller can't set: the connection is ours to describe.\nconst FORBIDDEN_HEADERS = [\n \"host\",\n \"connection\",\n \"content-length\",\n \"transfer-encoding\",\n \"keep-alive\",\n \"upgrade\",\n];\n// Dropped when a redirect leaves the origin, as `fetch` does.\nconst CREDENTIAL_HEADERS = [\"authorization\", \"cookie\", \"proxy-authorization\"];\n\ntype Rules = { hosts: string[]; ranges: Cidr[] };\n\ntype Policy = {\n timeout: number;\n connectTimeout: number;\n maxSize: number;\n maxRedirects: number;\n ports: readonly number[] | \"any\";\n allow: Rules | null;\n deny: Rules;\n allowPrivate: true | Cidr[];\n contentTypes: readonly string[] | null;\n resolve: (hostname: string) => Promise<readonly string[]>;\n};\n\n/**\n * `fetch` for URLs that come from users. It refuses anything but http(s) on\n * the allowed ports, resolves the host itself, refuses non-public addresses,\n * then connects to the address it checked (the host name is still sent as\n * `Host` and TLS SNI, and the certificate is verified against it), so a DNS\n * answer that changes between the check and the connection can't reach\n * inside. Each redirect is checked the same way.\n *\n * Throws `SafeFetchError` subclasses; see `errors.ts`.\n */\nexport async function safeFetch(\n input: string | URL,\n options: SafeFetchOptions = {},\n): Promise<SafeResponse> {\n const policy = compilePolicy(options);\n const outer = options.signal;\n outer?.throwIfAborted();\n\n const controller = new AbortController();\n const signal = controller.signal;\n let currentUrl = String(input);\n const abortWith = (reason: unknown) => {\n if (!signal.aborted) controller.abort(reason);\n };\n const totalTimer = setTimeout(\n () => abortWith(new TimeoutError(currentUrl, \"total\", policy.timeout)),\n policy.timeout,\n );\n const onOuterAbort = () => abortWith(outer!.reason);\n outer?.addEventListener(\"abort\", onOuterAbort, { once: true });\n const release = () => {\n clearTimeout(totalTimer);\n outer?.removeEventListener(\"abort\", onOuterAbort);\n };\n\n try {\n let url = parseUrl(currentUrl, policy);\n let method = (options.method ?? \"GET\").toUpperCase();\n const headers = new Headers(options.headers);\n for (const name of FORBIDDEN_HEADERS) headers.delete(name);\n if (!headers.has(\"accept\")) headers.set(\"accept\", \"*/*\");\n // Some sites refuse a request without one, as `fetch` would always send.\n if (!headers.has(\"user-agent\")) headers.set(\"user-agent\", \"gemi\");\n if (!headers.has(\"accept-encoding\"))\n headers.set(\"accept-encoding\", \"gzip, deflate, br\");\n let body = await readBody(method, options.body, headers);\n\n for (let hop = 0; ; hop++) {\n currentUrl = url.href;\n const { request, response, address } = await send(\n url,\n method,\n headers,\n body,\n policy,\n signal,\n );\n const status = response.statusCode ?? 0;\n const location = response.headers.location;\n\n if (REDIRECTS.has(status) && location && options.redirect !== \"manual\") {\n request.destroy();\n if (hop >= policy.maxRedirects) {\n throw new TooManyRedirectsError(url.href, policy.maxRedirects);\n }\n let next: URL;\n try {\n next = new URL(location, url);\n } catch {\n throw new InvalidUrlError(\n location,\n \"malformed\",\n `The redirect to \"${location}\" is not a URL.`,\n );\n }\n if (\n status === 303\n ? method !== \"HEAD\"\n : (status === 301 || status === 302) && method === \"POST\"\n ) {\n method = \"GET\";\n body = null;\n const bodyHeaders: string[] = [];\n headers.forEach((_, name) => {\n if (name.startsWith(\"content-\")) bodyHeaders.push(name);\n });\n for (const name of bodyHeaders) headers.delete(name);\n }\n if (next.origin !== url.origin)\n for (const name of CREDENTIAL_HEADERS) headers.delete(name);\n url = parseUrl(next.href, policy);\n continue;\n }\n\n return toResponse({\n url,\n hop,\n method,\n request,\n response,\n address,\n policy,\n signal,\n release,\n });\n }\n } catch (error) {\n release();\n throw signal.aborted ? signal.reason : error;\n }\n}\n\nfunction compilePolicy(options: SafeFetchOptions): Policy {\n const rules = (list: readonly string[], option: string): Rules => {\n const result: Rules = { hosts: [], ranges: [] };\n for (const entry of list) {\n // Anything shaped like an address or a range must be a valid one: a\n // typo such as \"10.0.0/8\" must not quietly become a host name.\n const addressLike =\n entry.includes(\"/\") || entry.includes(\":\") || /^[\\d.]+$/.test(entry);\n const cidr = addressLike ? parseCidr(entry) : null;\n if (cidr) result.ranges.push(cidr);\n else if (\n !addressLike &&\n /^(\\*\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)*\\.?$/i.test(entry)\n ) {\n result.hosts.push(normalizeHost(entry));\n } else {\n throw new TypeError(\n `safeFetch: \"${entry}\" in ${option} is not a host name or an IP range.`,\n );\n }\n }\n return result;\n };\n const allowPrivate = options.allowPrivate;\n return {\n timeout: options.timeout ?? DEFAULTS.timeout,\n connectTimeout: options.connectTimeout ?? DEFAULTS.connectTimeout,\n maxSize: options.maxSize ?? DEFAULTS.maxSize,\n maxRedirects: options.maxRedirects ?? DEFAULTS.maxRedirects,\n ports: options.ports ?? DEFAULTS.ports,\n allow:\n options.allow && options.allow.length > 0\n ? rules(options.allow, \"allow\")\n : null,\n deny: rules(options.deny ?? [], \"deny\"),\n allowPrivate:\n allowPrivate === true\n ? true\n : rules(allowPrivate || [], \"allowPrivate\").ranges,\n contentTypes: options.contentTypes?.length ? options.contentTypes : null,\n resolve: options.resolve ?? systemResolve,\n };\n}\n\nasync function systemResolve(hostname: string) {\n const answers = await dnsLookup(hostname, { all: true, verbatim: true });\n return answers.map((answer) => answer.address);\n}\n\nfunction normalizeHost(host: string) {\n return host.toLowerCase().replace(/\\.$/, \"\");\n}\n\nfunction matchesHost(host: string, patterns: string[]) {\n return patterns.some((pattern) =>\n pattern.startsWith(\"*.\")\n ? host.endsWith(pattern.slice(1))\n : host === pattern,\n );\n}\n\nfunction parseUrl(text: string, policy: Policy): URL {\n let url: URL;\n try {\n url = new URL(text);\n } catch {\n throw new InvalidUrlError(text, \"malformed\", `\"${text}\" is not a URL.`);\n }\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n throw new InvalidUrlError(\n url.href,\n \"scheme\",\n `Only http and https URLs can be fetched, not ${url.protocol.slice(0, -1)}.`,\n );\n }\n if (url.username || url.password) {\n throw new InvalidUrlError(\n url.href,\n \"credentials\",\n \"The URL has a username or password in it.\",\n );\n }\n const port = effectivePort(url);\n if (policy.ports !== \"any\" && !policy.ports.includes(port)) {\n throw new InvalidUrlError(url.href, \"port\", `Port ${port} is not allowed.`);\n }\n return url;\n}\n\nfunction effectivePort(url: URL) {\n return url.port ? Number(url.port) : url.protocol === \"https:\" ? 443 : 80;\n}\n\n/** The URL's host name without brackets, and its addresses once checked. */\nasync function vet(url: URL, policy: Policy, signal: AbortSignal) {\n // The WHATWG parser has already turned `0x7f.1`, `2130706433` and the like\n // into dotted quads, and lower-cased the name.\n const host = normalizeHost(url.hostname.replace(/^\\[(.*)\\]$/, \"$1\"));\n const literal = parseAddress(host);\n // A literal is judged as the URL parser canonicalised it; a name that only\n // looks numeric to us still goes to the resolver below.\n const isLiteral =\n literal !== null &&\n (host.includes(\":\") || /^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(host));\n\n if (!isLiteral && matchesHost(host, policy.deny.hosts)) {\n throw new BlockedHostError(url.href, host, \"denied\");\n }\n const allowedByName =\n !isLiteral &&\n policy.allow !== null &&\n matchesHost(host, policy.allow.hosts);\n if (policy.allow && !allowedByName && policy.allow.ranges.length === 0) {\n throw new BlockedHostError(url.href, host, \"not-allowed\");\n }\n\n let addresses: ParsedAddress[];\n if (isLiteral) {\n addresses = [literal];\n } else {\n let answers: readonly string[];\n try {\n answers = await abortable(policy.resolve(host), signal);\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n throw new DnsError(url.href, host, error);\n }\n addresses = answers\n .map((answer) => parseAddress(answer))\n .filter((answer) => answer !== null);\n if (addresses.length === 0) throw new DnsError(url.href, host);\n }\n\n // Every address must pass, not just the first: the connection may use any.\n for (const address of addresses) {\n const text = formatAddress(address);\n if (policy.deny.ranges.some((range) => inCidr(address, range))) {\n throw new BlockedAddressError(url.href, host, text, \"denied\");\n }\n if (\n policy.allow &&\n !allowedByName &&\n !policy.allow.ranges.some((range) => inCidr(address, range))\n ) {\n throw new BlockedAddressError(url.href, host, text, \"not-allowed\");\n }\n const blocked = classifyAddress(address);\n if (\n blocked &&\n policy.allowPrivate !== true &&\n !policy.allowPrivate.some((range) => inCidr(address, range))\n ) {\n throw new BlockedAddressError(url.href, host, text, blocked.kind);\n }\n }\n return { host, addresses, isLiteral };\n}\n\nfunction abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n },\n );\n });\n}\n\nasync function readBody(\n method: string,\n body: BodyInit | null | undefined,\n headers: Headers,\n) {\n if (body === undefined || body === null) return null;\n if (method === \"GET\" || method === \"HEAD\") {\n throw new TypeError(`safeFetch: a ${method} request can't have a body.`);\n }\n // `Request` turns every BodyInit into bytes and knows its content type\n // (a FormData boundary, URLSearchParams, a Blob's type).\n const request = new Request(\"http://body.invalid/\", { method: \"POST\", body });\n const type = request.headers.get(\"content-type\");\n if (type && !headers.has(\"content-type\")) headers.set(\"content-type\", type);\n return new Uint8Array(await request.arrayBuffer());\n}\n\ntype Sent = {\n request: http.ClientRequest;\n response: http.IncomingMessage;\n address: string | null;\n};\n\n/** One hop: check the URL's host, connect to the checked address, send. */\nasync function send(\n url: URL,\n method: string,\n headers: Headers,\n body: Uint8Array | null,\n policy: Policy,\n signal: AbortSignal,\n): Promise<Sent> {\n const connectController = new AbortController();\n const connectTimer = setTimeout(\n () =>\n connectController.abort(\n new TimeoutError(url.href, \"connect\", policy.connectTimeout),\n ),\n policy.connectTimeout,\n );\n const connectSignal = AbortSignal.any([signal, connectController.signal]);\n try {\n const { host, addresses, isLiteral } = await vet(\n url,\n policy,\n connectSignal,\n );\n const secure = url.protocol === \"https:\";\n const outgoing: Record<string, string> = {};\n headers.forEach((value, name) => {\n outgoing[name] = value;\n });\n if (body) outgoing[\"content-length\"] = String(body.byteLength);\n\n return await new Promise<Sent>((resolve, reject) => {\n const options: https.RequestOptions = {\n method,\n host,\n port: effectivePort(url),\n path: `${url.pathname}${url.search}`,\n headers: outgoing,\n // No pooling: a pooled socket was connected for some earlier hop, and\n // reusing it would skip the lookup below.\n agent: false,\n // The only resolution the connection sees: the addresses just checked.\n lookup: ((\n _hostname: string,\n lookupOptions: { all?: boolean; family?: number },\n callback: (...args: unknown[]) => void,\n ) => {\n const family = lookupOptions?.family;\n const candidates = addresses.filter(\n (address) => !family || address.family === family,\n );\n if (candidates.length === 0) {\n callback(\n Object.assign(new Error(`No IPv${family} address for ${host}`), {\n code: \"ENOTFOUND\",\n }),\n );\n } else if (lookupOptions?.all) {\n callback(\n null,\n candidates.map((address) => ({\n address: formatAddress(address),\n family: address.family,\n })),\n );\n } else {\n callback(null, formatAddress(candidates[0]), candidates[0].family);\n }\n }) as never,\n };\n if (secure && !isLiteral) options.servername = host;\n\n const request = (secure ? https : http).request(options);\n let connectedTo: string | null = null;\n const fail = (error: unknown) => {\n connectSignal.removeEventListener(\"abort\", onAbort);\n request.destroy();\n reject(error);\n };\n const onAbort = () =>\n fail(connectSignal.aborted ? connectSignal.reason : signal.reason);\n connectSignal.addEventListener(\"abort\", onAbort, { once: true });\n\n // Belt and braces: the socket must be at an address that was checked.\n // The lookup above is what guarantees it; this catches a runtime that\n // ever connects without it. Bun before 1.4 doesn't report the remote\n // address (or a connect event) from node:http, so there it can't run.\n const verify = (socket: Socket | null | undefined) => {\n const reported = socket?.remoteAddress;\n if (!reported || connectedTo !== null) return true;\n const remote = parseAddress(reported);\n if (\n !remote ||\n !addresses.some((address) => sameAddress(address, remote))\n ) {\n fail(\n new BlockedAddressError(url.href, host, reported, \"not-allowed\"),\n );\n return false;\n }\n connectedTo = formatAddress(unmap(remote));\n return true;\n };\n\n request.once(\"socket\", (socket: Socket) => {\n const connected = () => {\n if (verify(socket) && !secure) clearTimeout(connectTimer);\n };\n if (socket.connecting) socket.once(\"connect\", connected);\n else connected();\n if (secure)\n socket.once(\"secureConnect\", () => clearTimeout(connectTimer));\n });\n request.once(\"response\", (response) => {\n clearTimeout(connectTimer);\n // Destroying the request (a redirect, a refusal) can error the response.\n response.on(\"error\", () => {});\n if (!verify(response.socket)) return;\n connectSignal.removeEventListener(\"abort\", onAbort);\n // The total timeout and the caller's signal still apply to the body.\n resolve({ request, response, address: connectedTo });\n });\n // `on`, not `once`: a destroyed request can emit more than one error.\n request.on(\"error\", (error) => {\n if (connectSignal.aborted) return fail(connectSignal.reason);\n fail(\n error instanceof SafeFetchError\n ? error\n : new NetworkError(url.href, error),\n );\n });\n request.end(body ?? undefined);\n });\n } finally {\n clearTimeout(connectTimer);\n }\n}\n\nfunction toResponse({\n url,\n hop,\n method,\n request,\n response,\n address,\n policy,\n signal,\n release,\n}: {\n url: URL;\n hop: number;\n method: string;\n request: http.ClientRequest;\n response: http.IncomingMessage;\n address: string | null;\n policy: Policy;\n signal: AbortSignal;\n release: () => void;\n}): SafeResponse {\n const status = response.statusCode ?? 0;\n if (status < 200 || status > 599) {\n request.destroy();\n throw new NetworkError(url.href, new Error(`Unexpected status ${status}`));\n }\n\n const headers = new Headers();\n const raw = response.rawHeaders;\n for (let index = 0; index < raw.length; index += 2)\n headers.append(raw[index], raw[index + 1]);\n\n if (policy.contentTypes) {\n const type =\n headers.get(\"content-type\")?.split(\";\")[0].trim().toLowerCase() ?? null;\n if (\n !type ||\n !policy.contentTypes.some((allowed) => matchesMediaType(type, allowed))\n ) {\n request.destroy();\n throw new ContentTypeError(url.href, type, policy.contentTypes);\n }\n }\n\n const meta = { url: url.href, redirected: hop > 0, address };\n const init = { status, statusText: response.statusMessage ?? \"\", headers };\n if (method === \"HEAD\" || NULL_BODY.has(status)) {\n request.destroy();\n release();\n return new SafeResponse(null, init, meta);\n }\n\n const encoding = headers.get(\"content-encoding\")?.trim().toLowerCase();\n const decoder =\n encoding === \"gzip\" || encoding === \"x-gzip\"\n ? zlib.createGunzip()\n : encoding === \"deflate\"\n ? zlib.createInflate()\n : encoding === \"br\"\n ? zlib.createBrotliDecompress()\n : null;\n const declared = Number(headers.get(\"content-length\"));\n if (!decoder && Number.isFinite(declared) && declared > policy.maxSize) {\n request.destroy();\n throw new TooLargeError(url.href, policy.maxSize);\n }\n if (decoder) {\n headers.delete(\"content-encoding\");\n headers.delete(\"content-length\");\n }\n\n const source: Readable = decoder ? response.pipe(decoder) : response;\n let received = 0;\n let finished = false;\n let onAbort = () => {};\n const settle = () => {\n finished = true;\n signal.removeEventListener(\"abort\", onAbort);\n release();\n };\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n const finish = (error?: unknown) => {\n if (finished) return;\n settle();\n if (error === undefined) {\n controller.close();\n } else {\n request.destroy();\n decoder?.destroy();\n controller.error(error);\n }\n };\n onAbort = () => finish(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n if (signal.aborted) return onAbort();\n\n source.on(\"data\", (chunk: Buffer) => {\n if (finished) return;\n received += chunk.byteLength;\n if (received > policy.maxSize)\n return finish(new TooLargeError(url.href, policy.maxSize));\n controller.enqueue(new Uint8Array(chunk));\n if ((controller.desiredSize ?? 1) <= 0) source.pause();\n });\n source.once(\"end\", () => finish());\n const onError = (error: Error) =>\n finish(\n error instanceof SafeFetchError\n ? error\n : new NetworkError(url.href, error),\n );\n source.on(\"error\", onError);\n if (decoder) response.on(\"error\", onError);\n response.once(\"aborted\", () =>\n finish(\n new NetworkError(url.href, new Error(\"The response was cut off.\")),\n ),\n );\n },\n pull() {\n source.resume();\n },\n cancel() {\n if (finished) return;\n settle();\n request.destroy();\n decoder?.destroy();\n },\n });\n return new SafeResponse(stream, init, meta);\n}\n\nfunction matchesMediaType(type: string, allowed: string) {\n const pattern = allowed.toLowerCase();\n return pattern.endsWith(\"/*\")\n ? type.startsWith(pattern.slice(0, -1))\n : type === pattern;\n}\n",
|
|
27
27
|
"/**\n * The media type of a file, read from its first bytes rather than from a name\n * or a `Content-Type` header someone else chose.\n *\n * Recognizes the common image, audio, video, font, document and archive\n * formats by their signatures, SVG, HTML and XML by their markup, and\n * otherwise answers `text/plain` for bytes that decode as UTF-8 text with no\n * control characters, and `application/octet-stream` for anything else.\n * Formats that are text underneath (JSON, CSV, JavaScript, CSS) can't be told\n * apart from their bytes and come out as `text/plain`.\n *\n * A few kilobytes are enough: `SNIFF_BYTES` is what `Storage.putFromUrl()`\n * reads before deciding.\n */\nexport function sniffContentType(bytes: Uint8Array): string {\n return binaryType(bytes) ?? markupType(bytes) ?? textOrBinary(bytes);\n}\n\n/** How many leading bytes `sniffContentType` looks at, at most. */\nexport const SNIFF_BYTES = 4096;\n\nconst EXTENSIONS: Record<string, string> = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpg\",\n \"image/gif\": \"gif\",\n \"image/webp\": \"webp\",\n \"image/avif\": \"avif\",\n \"image/heic\": \"heic\",\n \"image/heif\": \"heif\",\n \"image/bmp\": \"bmp\",\n \"image/tiff\": \"tiff\",\n \"image/x-icon\": \"ico\",\n \"image/svg+xml\": \"svg\",\n \"audio/mpeg\": \"mp3\",\n \"audio/aac\": \"aac\",\n \"audio/mp4\": \"m4a\",\n \"audio/ogg\": \"ogg\",\n \"audio/flac\": \"flac\",\n \"audio/wav\": \"wav\",\n \"video/mp4\": \"mp4\",\n \"video/quicktime\": \"mov\",\n \"video/webm\": \"webm\",\n \"video/x-matroska\": \"mkv\",\n \"video/x-msvideo\": \"avi\",\n \"font/woff\": \"woff\",\n \"font/woff2\": \"woff2\",\n \"font/ttf\": \"ttf\",\n \"font/otf\": \"otf\",\n \"application/pdf\": \"pdf\",\n \"application/zip\": \"zip\",\n \"application/gzip\": \"gz\",\n \"application/xml\": \"xml\",\n \"text/html\": \"html\",\n \"text/plain\": \"txt\",\n \"application/octet-stream\": \"bin\",\n};\n\n/** The file extension `putFromUrl` names an object of this type with. */\nexport function extensionFor(contentType: string): string {\n return EXTENSIONS[contentType] ?? \"bin\";\n}\n\nfunction startsWith(bytes: Uint8Array, signature: readonly number[], offset = 0) {\n if (bytes.length < offset + signature.length) return false;\n return signature.every((byte, index) => bytes[offset + index] === byte);\n}\n\nfunction ascii(bytes: Uint8Array, start: number, end: number) {\n return String.fromCharCode(...bytes.subarray(start, end));\n}\n\nconst FTYP_BRANDS: Record<string, string> = {\n avif: \"image/avif\",\n avis: \"image/avif\",\n heic: \"image/heic\",\n heix: \"image/heic\",\n hevc: \"image/heic\",\n hevx: \"image/heic\",\n heim: \"image/heic\",\n heis: \"image/heic\",\n mif1: \"image/heif\",\n msf1: \"image/heif\",\n \"qt \": \"video/quicktime\",\n \"M4A \": \"audio/mp4\",\n \"M4B \": \"audio/mp4\",\n};\n\nfunction binaryType(b: Uint8Array): string | null {\n if (startsWith(b, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return \"image/png\";\n if (startsWith(b, [0xff, 0xd8, 0xff])) return \"image/jpeg\";\n if (b.length >= 6 && (ascii(b, 0, 6) === \"GIF87a\" || ascii(b, 0, 6) === \"GIF89a\")) {\n return \"image/gif\";\n }\n if (b.length >= 12 && ascii(b, 0, 4) === \"RIFF\") {\n const kind = ascii(b, 8, 12);\n if (kind === \"WEBP\") return \"image/webp\";\n if (kind === \"WAVE\") return \"audio/wav\";\n if (kind === \"AVI \") return \"video/x-msvideo\";\n }\n if (b.length >= 12 && ascii(b, 4, 8) === \"ftyp\") {\n const brand = ascii(b, 8, 12);\n return FTYP_BRANDS[brand] ?? \"video/mp4\";\n }\n if (startsWith(b, [0x49, 0x49, 0x2a, 0x00]) || startsWith(b, [0x4d, 0x4d, 0x00, 0x2a])) {\n return \"image/tiff\";\n }\n // \"BM\", then four bytes of file size and four reserved zero bytes.\n if (startsWith(b, [0x42, 0x4d]) && startsWith(b, [0, 0, 0, 0], 6)) return \"image/bmp\";\n if (startsWith(b, [0x00, 0x00, 0x01, 0x00]) && b.length >= 6 && b[4]! > 0) {\n return \"image/x-icon\";\n }\n if (startsWith(b, [0x25, 0x50, 0x44, 0x46, 0x2d])) return \"application/pdf\";\n if (startsWith(b, [0x50, 0x4b, 0x03, 0x04])) return \"application/zip\";\n if (startsWith(b, [0x1f, 0x8b])) return \"application/gzip\";\n if (startsWith(b, [0x1a, 0x45, 0xdf, 0xa3])) {\n return ascii(b, 0, Math.min(b.length, 64)).includes(\"webm\")\n ? \"video/webm\"\n : \"video/x-matroska\";\n }\n if (b.length >= 4) {\n const magic = ascii(b, 0, 4);\n if (magic === \"OggS\") return \"audio/ogg\";\n if (magic === \"fLaC\") return \"audio/flac\";\n if (magic === \"wOFF\") return \"font/woff\";\n if (magic === \"wOF2\") return \"font/woff2\";\n if (magic === \"OTTO\") return \"font/otf\";\n }\n if (startsWith(b, [0x00, 0x01, 0x00, 0x00, 0x00])) return \"font/ttf\";\n if (b.length >= 3 && ascii(b, 0, 3) === \"ID3\") return \"audio/mpeg\";\n if (b.length >= 2 && b[0] === 0xff) {\n // MPEG audio frame sync: 11 set bits. Layer bits 00 are ADTS (AAC).\n if ((b[1]! & 0xf6) === 0xf0) return \"audio/aac\";\n if ((b[1]! & 0xe0) === 0xe0 && (b[1]! & 0x06) !== 0) return \"audio/mpeg\";\n }\n return null;\n}\n\n// The tags the WHATWG MIME sniffing standard treats as an HTML document.\nconst HTML_TAGS = [\n \"!doctype html\",\n \"html\",\n \"head\",\n \"script\",\n \"iframe\",\n \"h1\",\n \"div\",\n \"font\",\n \"table\",\n \"a\",\n \"style\",\n \"title\",\n \"b\",\n \"body\",\n \"br\",\n \"p\",\n \"!--\",\n];\n\nfunction markupType(b: Uint8Array): string | null {\n let text = new TextDecoder(\"utf-8\", { fatal: false }).decode(b);\n if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);\n text = text.trimStart();\n if (!text.startsWith(\"<\")) return null;\n const lower = text.toLowerCase();\n\n // An SVG may open with an XML declaration, comments, processing\n // instructions and a doctype before its root element.\n let rest = lower;\n for (;;) {\n rest = rest.trimStart();\n const skip = /^(<\\?[\\s\\S]*?\\?>|<!--[\\s\\S]*?-->|<!doctype[^>]*>)/.exec(rest);\n if (!skip) break;\n rest = rest.slice(skip[0].length);\n }\n if (/^<svg[\\s>/]/.test(rest)) return \"image/svg+xml\";\n\n for (const tag of HTML_TAGS) {\n if (!lower.startsWith(`<${tag}`)) continue;\n // The tag has to end there: `<a` is HTML, `<abc` is not.\n if (/^[\\s>]/.test(lower.charAt(tag.length + 1))) return \"text/html\";\n }\n // Markup after a leading comment or doctype is HTML too, once one of the\n // tags above follows.\n if (/^<(html|head|body)[\\s>]/.test(rest)) return \"text/html\";\n if (lower.startsWith(\"<?xml\")) return \"application/xml\";\n return null;\n}\n\nfunction textOrBinary(b: Uint8Array): string {\n if (b.length === 0) return \"application/octet-stream\";\n for (const byte of b) {\n // Control characters other than tab, newline, form feed, carriage return\n // and escape mean binary.\n if (byte < 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0c && byte !== 0x0d && byte !== 0x1b) {\n return \"application/octet-stream\";\n }\n }\n try {\n // `stream: true` lets a multi-byte character cut off at the end of the\n // window through.\n new TextDecoder(\"utf-8\", { fatal: true }).decode(b, { stream: true });\n return \"text/plain\";\n } catch {\n return \"application/octet-stream\";\n }\n}\n\n// Types a browser treats as active content: HTML, SVG and XML can carry\n// script. A wildcard such as `image/*`, `text/*` or `*/*` never lets them\n// through, and `putFromUrl` without `contentTypes` refuses them; they have to\n// be listed by name.\nconst ACTIVE_TYPES = new Set([\n \"text/html\",\n \"application/xhtml+xml\",\n \"image/svg+xml\",\n \"text/xml\",\n \"application/xml\",\n \"text/xsl\",\n \"application/xslt+xml\",\n]);\n\n/**\n * Whether a media type is active content a browser may run script from:\n * HTML, XHTML, SVG and XML, including any `+xml` type (`image/svg+xml`,\n * `application/atom+xml`, ...).\n */\nexport function isActiveContentType(type: string): boolean {\n const essence = type.split(\";\")[0]!.trim().toLowerCase();\n return ACTIVE_TYPES.has(essence) || essence.endsWith(\"+xml\");\n}\n\n/**\n * Whether a sniffed type is in an allow-list of media types such as\n * `[\"image/*\", \"application/pdf\"]`. A wildcard never covers HTML, SVG or XML\n * (see `isActiveContentType`), which can carry script; name them explicitly\n * to accept them.\n */\nexport function isAllowedContentType(type: string, allowed: readonly string[]): boolean {\n const essence = type.split(\";\")[0]!.trim().toLowerCase();\n return allowed.some((entry) => {\n const pattern = entry.split(\";\")[0]!.trim().toLowerCase();\n if (pattern === \"*/*\" || pattern === \"*\") return !isActiveContentType(essence);\n if (pattern.endsWith(\"/*\")) {\n return essence.startsWith(pattern.slice(0, -1)) && !isActiveContentType(essence);\n }\n return essence === pattern;\n });\n}\n",
|
|
28
|
-
"//@ts-ignore - type-only; the module itself is loaded on first use by `metadata()`.\nimport type
|
|
28
|
+
"//@ts-ignore - type-only; the module itself is loaded on first use by `metadata()`.\nimport type { Metadata as SharpMetadata } from \"sharp\";\n\nimport { Buffer } from \"node:buffer\";\nimport { loadSharp } from \"../support/sharp\";\nimport type { Prettify } from \"../utils/type\";\n\nimport { RequestContext } from \"../http/requestContext\";\nimport type { ByteRange } from \"../http/range\";\nimport type {\n DeleteFileParams,\n DeletePrefixOptions,\n FetchFileOptions,\n ListObjectsOptions,\n PutFileOptions,\n PutFileParams,\n ReadFileParams,\n ReadResult,\n StoredObject,\n} from \"../services/file-storage/drivers/types\";\nimport { FilesystemManager } from \"../services/file-storage/FilesystemManager\";\nimport { fetchWithTimeouts } from \"../services/file-storage/fetchTimeouts\";\nimport { DEFAULT_FETCH_TIMEOUT_MS } from \"../services/file-storage/config\";\nimport {\n putFromUrl,\n type PutFromUrlOptions,\n type PutFromUrlResult,\n} from \"../services/file-storage/putFromUrl\";\nimport { Facade } from \"./Facade\";\n\ntype Metadata = Prettify<SharpMetadata>;\n\nexport class Storage extends Facade {\n static getFacadeAccessor() {\n return FilesystemManager;\n }\n\n /**\n * Stores a file and returns its object name. Pass `{ signal }` to cancel the\n * upload, e.g. with the incoming request's signal or `AbortSignal.timeout()`.\n */\n static async put(params: PutFileParams | Blob, options: PutFileOptions = {}) {\n return this.getFacadeRoot().driver.put(params, options);\n }\n\n /**\n * Downloads a remote file and stores it, for URLs that come from users or\n * other services: an image link, a provider's signed download URL.\n *\n * ```ts\n * const { name, contentType, size } = await Storage.putFromUrl(url, {\n * directory: `sites/${site.id}`,\n * contentTypes: [\"image/*\"],\n * maxSize: 10 * 1024 * 1024,\n * signal: req.rawRequest.signal,\n * });\n * ```\n *\n * The download goes through `safeFetch`, so private and internal addresses,\n * other ports and too many redirects are refused, and `maxSize` and\n * `timeout` hold while the body streams in. The stored type is sniffed from\n * the file's first bytes, never taken from the `Content-Type` header, and is\n * checked against `contentTypes` before anything is stored. HTML, SVG and\n * XML, which can carry script, are refused unless `contentTypes` lists them\n * by name, also when `contentTypes` is left out. A download\n * that fails or grows past `maxSize` halfway stores nothing.\n *\n * Rejects with `safeFetch`'s errors (`SafeFetchError` subclasses):\n * `HttpStatusError` for a non-2xx answer, `ContentTypeError` for a type not\n * in `contentTypes` (or unlisted active content), `TooLargeError`, `TimeoutError`, `BlockedAddressError`\n * and so on; an abort rejects with the signal's reason.\n */\n static async putFromUrl(\n url: string | URL,\n options: PutFromUrlOptions = {},\n ): Promise<PutFromUrlResult> {\n return putFromUrl(this.getFacadeRoot().driver, url, options);\n }\n\n static async metadata(obj: Blob | File): Promise<Partial<Metadata>> {\n const buffer = Buffer.from(await obj.arrayBuffer());\n // Outside the catch: the empty object below means \"this blob is not an\n // image sharp can read\", and a missing `sharp` install must not be able to\n // hide behind it.\n const sharp = await loadSharp(\"Storage.metadata()\");\n try {\n return await sharp(buffer).metadata();\n } catch {\n return {};\n }\n }\n\n /**\n * Reads an object as a streamed `Response`. Pass `{ signal }` to cancel the\n * read, e.g. with the incoming request's signal or `AbortSignal.timeout()`:\n * an abort rejects `fetch()` itself, or errors the body if it lands after\n * `fetch()` resolved.\n *\n * Without a `signal`, two default limits apply (`fetchTimeoutMs` and\n * `fetchIdleTimeoutMs` on the `filesystem` config, 30s each): no response\n * in time rejects `fetch()`, and a body that sends nothing for that long\n * while it is read errors. Both reject with `StorageFetchTimeoutError` and\n * abort the request. A caller's own `signal` turns both off.\n */\n static async fetch(\n params: ReadFileParams | string,\n options: FetchFileOptions = {},\n ) {\n // Checked here too, so a custom driver that predates the option still\n // refuses an already-aborted read.\n options.signal?.throwIfAborted();\n // `??` too: a manager an app rebound itself may not carry the fields.\n const manager: Partial<FilesystemManager> &\n Pick<FilesystemManager, \"driver\"> = this.getFacadeRoot();\n return fetchWithTimeouts(manager.driver, params, options, {\n fetchTimeoutMs: manager.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,\n fetchIdleTimeoutMs:\n manager.fetchIdleTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,\n });\n }\n\n /**\n * Reads an object as bytes plus metadata, pushing any byte range down to the\n * storage backend so a seek transfers one window rather than the whole file.\n *\n * The range is resolved in this order: an explicit `options.range`, then a\n * `range` on `params`, then the in-flight request's `Range` header when this\n * is called inside a `this.stream()` route. Pass `{ range: null }` to force a\n * full read inside a stream route.\n */\n static async read(\n params: ReadFileParams | string,\n options: { range?: ByteRange | null } = {},\n ): Promise<ReadResult> {\n const base: ReadFileParams =\n typeof params === \"string\" ? { name: params } : { ...params };\n\n const range =\n \"range\" in options\n ? (options.range ?? null)\n : base.range !== undefined\n ? base.range\n : (RequestContext.getStore()?.rangeRequest ?? null);\n\n return this.getFacadeRoot().driver.read({\n ...base,\n range,\n });\n }\n /**\n * @deprecated The result's shape depends on the driver. Use `objects()`.\n */\n static list(folder: string) {\n return this.getFacadeRoot().driver.list(folder);\n }\n\n /**\n * Every object whose name starts with `prefix`, at any depth, as\n * `{ name, size, lastModified }`, on every driver. Pagination happens under\n * the hood, so iterate with `for await`:\n *\n * ```ts\n * for await (const object of Storage.objects(\"logs/\")) {\n * if (object.lastModified < cutoff) await Storage.delete(object.name);\n * }\n * ```\n *\n * Plain string-prefix matching, as in S3: `pages/1` also matches\n * `pages/10/…`. End the prefix with `/` to stay inside one folder.\n */\n static objects(\n prefix: string,\n options: ListObjectsOptions = {},\n ): AsyncIterable<StoredObject> {\n return this.getFacadeRoot().driver.objects(prefix, options);\n }\n\n /**\n * Deletes every object under `prefix` and resolves with how many were\n * deleted. Refuses an empty or root prefix (`\"\"`, `\"/\"`, `\".\"`), so a\n * purge built from a missing id cannot empty the store.\n */\n static async deletePrefix(\n prefix: string,\n options: DeletePrefixOptions = {},\n ): Promise<number> {\n return this.getFacadeRoot().driver.deletePrefix(prefix, options);\n }\n\n /**\n * Removes a stored object. Deleting one that does not exist resolves without\n * throwing, so a cleanup path can retry safely.\n */\n static async delete(params: DeleteFileParams | string): Promise<void> {\n return this.getFacadeRoot().driver.delete(params);\n }\n}\n",
|
|
29
29
|
"// @ts-ignore - `sharp` is a peer dependency; only its types are wanted here.\nimport type sharpNamespace from \"sharp\";\n\n/**\n * `sharp`, imported on first use rather than at module load.\n *\n * Three modules need it — the `Sharp` optimization driver, the `Storage` facade\n * and the OG-image branch of `ViewRouteDispatcher` — and all three are reachable\n * from the `gemi/services` and `gemi/facades` barrels, which are also the only\n * door an application has to `CronJob`, `Job`, `DB` and `Lang`. A static import\n * made every one of those imports load a native binary (#403).\n *\n * `sharp` is the only one of the four that can be genuinely absent — it is a\n * peer dependency, so an install can skip its platform binary — which is why\n * the failure gets a message naming the caller rather than a bare resolution\n * error. `usedBy` is that name, written as the caller reads in a stack trace.\n *\n * No memo: the module registry already caches a resolved `import()`, and\n * caching the *failure* would make every later call report the first call's\n * stack instead of its own.\n */\nexport async function loadSharp(usedBy: string): Promise<typeof sharpNamespace> {\n try {\n // @ts-ignore - peer dependency, resolved out of the application's own tree\n return (await import(\"sharp\")).default;\n } catch (error) {\n throw new Error(\n `${usedBy} requires the 'sharp' package. Install it with \\`bun add sharp\\`.`,\n { cause: error },\n );\n }\n}\n",
|
|
30
30
|
"import {\n ContentTypeError,\n HttpStatusError,\n} from \"../../http/safeFetch/errors\";\nimport {\n safeFetch,\n type SafeFetchOptions,\n} from \"../../http/safeFetch/safeFetch\";\nimport type { IFileStorageDriver, PutStreamParams } from \"./drivers/types\";\nimport { FileStorageDriver } from \"./drivers/FileStorageDriver\";\nimport {\n SNIFF_BYTES,\n extensionFor,\n isAllowedContentType,\n sniffContentType,\n} from \"./sniffContentType\";\n\nexport interface PutFromUrlOptions {\n /**\n * The object name to store under, e.g. `\"sites/42/logo.png\"`. Without it\n * the name is generated: `<directory>/<uuid v7>.<extension of the sniffed\n * type>`. Pass `name` or `directory`, not both.\n */\n name?: string;\n /** The folder a generated name goes in, e.g. `\"sites/42\"`. */\n directory?: string;\n /** Bucket or container. Defaults as in `put()`. */\n bucket?: string;\n /**\n * Largest file accepted, in bytes (after decompression). Checked against\n * `Content-Length` up front and again while the body streams in. Default\n * 10 MiB, as in `safeFetch`.\n */\n maxSize?: number;\n /** The whole download in ms, redirects and body included. Default 30 000. */\n timeout?: number;\n /**\n * Media types the file may be, e.g. `[\"image/*\", \"application/pdf\"]`,\n * checked against the type sniffed from the file's first bytes, not the\n * `Content-Type` header. A wildcard never covers `image/svg+xml`,\n * `text/html` or XML, which can carry script: list them by name to accept\n * them. Anything else rejects with `ContentTypeError` before anything is\n * stored. Default: any type except active content (HTML, XHTML, SVG and\n * XML), which is refused unless listed here by name.\n */\n contentTypes?: readonly string[];\n /** Cancels the download and the upload. */\n signal?: AbortSignal;\n /**\n * Other `safeFetch` options: `headers`, `allow`, `deny`, `ports`,\n * `allowPrivate`, `maxRedirects`, `connectTimeout`, `resolve`. Never build\n * `allowPrivate` from user input.\n */\n fetch?: Omit<\n SafeFetchOptions,\n | \"method\"\n | \"body\"\n | \"signal\"\n | \"timeout\"\n | \"maxSize\"\n | \"contentTypes\"\n | \"redirect\"\n >;\n}\n\nexport interface PutFromUrlResult {\n /** The stored object's name, to persist and later pass to `fetch()`/`read()`. */\n name: string;\n /** Sniffed from the file's bytes; the type the object is stored with. */\n contentType: string;\n /** Bytes stored. */\n size: number;\n /** The URL the file was finally downloaded from, after redirects. */\n url: string;\n}\n\n/**\n * Downloads `url` through `safeFetch` and stores it with `driver`. The\n * implementation behind `Storage.putFromUrl()`.\n */\nexport async function putFromUrl(\n driver: IFileStorageDriver,\n url: string | URL,\n options: PutFromUrlOptions = {},\n): Promise<PutFromUrlResult> {\n const { name, directory, bucket, maxSize, timeout, contentTypes, signal } =\n options;\n if (name !== undefined && directory !== undefined) {\n throw new TypeError(\n \"Storage.putFromUrl(): pass `name` or `directory`, not both.\",\n );\n }\n if (name !== undefined && !name) {\n throw new TypeError(\"Storage.putFromUrl(): `name` is empty.\");\n }\n\n const response = await safeFetch(url, {\n ...options.fetch,\n method: \"GET\",\n redirect: \"follow\",\n // Checked against the sniffed bytes below, never against the header.\n contentTypes: undefined,\n signal,\n timeout,\n maxSize,\n });\n\n if (!response.ok) {\n await response.body?.cancel().catch(() => {});\n throw new HttpStatusError(response.url, response.status);\n }\n\n const reader = (response.body ?? new Response(new Uint8Array()).body!).getReader();\n const fail = async (error: unknown): Promise<never> => {\n await reader.cancel(error).catch(() => {});\n throw error;\n };\n\n // Read just enough to tell what the file is. Size limits, the timeout and\n // the signal already apply: they error this stream.\n const head: Uint8Array[] = [];\n let headSize = 0;\n let ended = false;\n while (headSize < SNIFF_BYTES) {\n const { done, value } = await reader.read();\n if (done) {\n ended = true;\n break;\n }\n head.push(value);\n headSize += value.byteLength;\n }\n const headBytes = concat(head, headSize);\n const contentType = sniffContentType(\n headBytes.subarray(0, Math.min(headSize, SNIFF_BYTES)),\n );\n\n // Without `contentTypes`, anything but active content: an HTML or SVG file\n // served back from the app's own origin could run script there.\n const allowed = contentTypes?.length ? contentTypes : [\"*/*\"];\n if (!isAllowedContentType(contentType, allowed)) {\n await fail(new ContentTypeError(response.url, contentType, allowed));\n }\n\n const objectName =\n name ??\n [\n (directory ?? \"\").replace(/\\/+$/, \"\"),\n `${Bun.randomUUIDv7()}.${extensionFor(contentType)}`,\n ]\n .filter(Boolean)\n .join(\"/\");\n\n let size = headSize;\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n if (headSize > 0) controller.enqueue(headBytes);\n if (ended) controller.close();\n },\n async pull(controller) {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n size += value.byteLength;\n controller.enqueue(value);\n },\n cancel(reason) {\n return reader.cancel(reason);\n },\n });\n\n const params: PutStreamParams = {\n name: objectName,\n bucket,\n body,\n contentType,\n };\n let stored: string;\n try {\n stored = driver.putStream\n ? await driver.putStream(params, { signal })\n : // A driver that implements the interface without extending\n // `FileStorageDriver`: buffer through the base class's default.\n await FileStorageDriver.prototype.putStream.call(driver, params, {\n signal,\n });\n } catch (error) {\n // A driver that failed before reading the body to its end must not keep\n // the download open until the timeout.\n await fail(error);\n throw error;\n }\n\n return { name: stored, contentType, size, url: response.url };\n}\n\nfunction concat(chunks: Uint8Array[], length: number) {\n if (chunks.length === 1) return chunks[0]!;\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n",
|
|
31
31
|
"import type { RedisClient, RedisOptions } from \"bun\";\nimport type { RedisConfig } from \"./config\";\n\n/**\n * The constructor `Bun.RedisClient` is, described structurally.\n *\n * Reached through the `Bun` global rather than `import { RedisClient } from\n * \"bun\"`, which is what this module used to do. That was a **value** import of\n * a specifier only the Bun runtime can resolve, and this class is re-exported\n * from `gemi/services` and reached from `gemi/facades` through the `Redis`\n * facade — the two barrels that are also the only door to `CronJob`, `Job`,\n * `DB` and `Lang`. So the specifier landed in the graph of every app and every\n * test that imported either one, and under a browser-targeted runner the whole\n * barrel simply failed to resolve (#396, #403).\n *\n * The global carries no specifier for a bundler or a test runner to resolve, so\n * the cost is paid only by code that actually asks for a client.\n */\ntype RedisClientConstructor = new (\n url?: string,\n options?: RedisOptions,\n) => RedisClient;\n\n/** First wait before replacing a client that is down. */\nconst REPLACE_MIN_DELAY_MS = 500;\n/** Longest wait between two replacements while Redis stays down. */\nconst REPLACE_MAX_DELAY_MS = 10_000;\n/** How long past its `connectionTimeout` a connect may stay pending before it counts as failed. */\nconst CONNECT_GRACE_MS = 5_000;\n/** Bun's default `connectionTimeout`. */\nconst DEFAULT_CONNECTION_TIMEOUT_MS = 10_000;\n\nexport class RedisManager {\n static token = \"redis\";\n\n private instance: RedisClient | null = null;\n\n /** When the connect the manager started on `instance` began, while it is pending. */\n private connectingSince: number | null = null;\n /** When `instance` was first seen down, after its connect settled. */\n private downSince: number | null = null;\n /** How long a client must be down before it is replaced. */\n private replaceDelay = REPLACE_MIN_DELAY_MS;\n\n constructor(public config: RedisConfig = {}) {}\n\n /**\n * Bun's Redis client. Built on first access and memoized; building it starts\n * the connection, which the first command would do anyway.\n *\n * Once Bun's client gives up on a connection (a connect timeout, or\n * `maxRetries` reconnects in a row) it never connects again, and every later\n * command fails at once with `Connection has failed`, even after Redis is\n * back (#982); calling its `connect()` again can hang. So an access that\n * finds the client down replaces it: the old one is closed and a new one\n * built. A client is down when it is not connected and no connect the\n * manager started on it is still pending. It gets a grace period first, so a\n * blip that Bun's own reconnect covers costs nothing: 0.5 s, doubling with\n * each replacement that does not connect, up to 10 s, and back to 0.5 s once\n * one connects. So a Redis that stays down is tried at most every 10 s.\n *\n * Read `client` each time rather than keeping it: a kept reference can be a\n * client that was replaced and closed.\n */\n get client(): RedisClient {\n if (this.instance === null) return this.build();\n\n const client = this.instance;\n if (this.isDown(client, Date.now())) {\n this.instance = null;\n try {\n client.close();\n } catch {}\n return this.build();\n }\n return client;\n }\n\n /**\n * `client` was a plain public property before it was a getter, and\n * overwriting a manager's client is how this repo fakes one —\n * `S3Driver.test.ts` does exactly that, and the `S3Driver` half of #403 kept\n * that seam working on purpose. An accessor with no setter would have turned\n * `manager.client = fake` into `TypeError: Attempted to assign to readonly\n * property` instead, which is not a change this was meant to make.\n */\n set client(client: RedisClient) {\n this.instance = client;\n this.connectingSince = null;\n this.downSince = null;\n this.replaceDelay = REPLACE_MIN_DELAY_MS;\n }\n\n /**\n * Closes the client, when one was built; a later `client` builds a new one.\n * Does not build one to close it.\n */\n close(): void {\n const client = this.instance;\n this.instance = null;\n this.connectingSince = null;\n this.downSince = null;\n this.replaceDelay = REPLACE_MIN_DELAY_MS;\n client?.close();\n }\n\n private build(): RedisClient {\n const client = new (redisClientConstructor())(\n this.config.url,\n this.config.options,\n );\n this.instance = client;\n this.downSince = null;\n this.connectingSince = null;\n\n // Only Bun's client can say whether it connected; a stand-in without\n // `connect()` is never replaced.\n if (typeof client.connect === \"function\") {\n this.connectingSince = Date.now();\n let connecting: Promise<unknown>;\n try {\n connecting = Promise.resolve(client.connect());\n } catch (error) {\n connecting = Promise.reject(error);\n }\n connecting.then(\n () => {\n if (this.instance !== client) return;\n this.connectingSince = null;\n this.replaceDelay = REPLACE_MIN_DELAY_MS;\n },\n () => {\n // The commands waiting on this connection report the failure to\n // their callers; here it only makes the client a candidate for\n // replacement.\n if (this.instance !== client) return;\n this.connectingSince = null;\n },\n );\n }\n return client;\n }\n\n private isDown(client: RedisClient, now: number): boolean {\n if (client.connected !== false || typeof client.connect !== \"function\") {\n this.downSince = null;\n return false;\n }\n\n if (this.connectingSince !== null) {\n const limit =\n (this.config.options?.connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT_MS) +\n CONNECT_GRACE_MS;\n if (now - this.connectingSince < limit) return false;\n // A connect that outlived its own timeout is not coming back.\n this.connectingSince = null;\n }\n\n this.downSince ??= now;\n if (now - this.downSince < this.replaceDelay) return false;\n\n this.replaceDelay = Math.min(this.replaceDelay * 2, REPLACE_MAX_DELAY_MS);\n return true;\n }\n}\n\nfunction redisClientConstructor(): RedisClientConstructor {\n const ctor = (globalThis as any).Bun?.RedisClient as\n | RedisClientConstructor\n | undefined;\n\n if (typeof ctor !== \"function\") {\n throw new Error(\n \"Redis requires Bun's built-in Redis client, which this runtime does not provide. Run the app under Bun, or bind your own client for the 'redis' token.\",\n );\n }\n\n return ctor;\n}\n"
|