import { exactInteger } from '../exact-json.ts'; // S3'S WIRE — the XML bodies S3 answers and reads, a bucket's CORS and lifecycle documents, a delete batch, an object's // ETag, and a request's body kept as its bytes (docs/contributing/architecture.md, "Other wires": S3's wire is a kernel // library, as Redis's command core is). Every vendor that speaks S3's API speaks this wire: AWS S3 itself, Cloudflare // R2, and the S3-compatible stores that follow. What differs between them (where a request's account and bucket are, // what they refuse, what they implement) is each pack's own. Moved here from the cloudflare pack's R2 lane, which had it // ported from the aws pack's S3 code; a pack may import neither (B4). Importing this module does nothing. import { createHash } from 'node:crypto'; const wireInteger = (text: string): number | string => /^[+-]?\d+$/.test(text) ? exactInteger(text) : Number(text); // ── XML ────────────────────────────────────────────────────────────────────────────────────── const DECL = ''; const NS = 'http://s3.amazonaws.com/doc/2006-03-01/'; export function esc(s: string | number): string { return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); } /** An element and its children or text. */ export const x = (tag: string, inner: string | number | string[]): string => `<${tag}>${Array.isArray(inner) ? inner.join('') : esc(inner)}`; export const doc = (root: string, inner: string[]): string => `${DECL}<${root} xmlns="${NS}">${inner.join('')}`; export const xmlAnswer = (body: string, status = 200, headers: Record = {}): Response => new Response(body, { status, headers: { 'content-type': 'application/xml', ...headers } }); export function unesc(s: string): string { return s.replace(/&(?:lt|gt|quot|apos|amp|#\d+|#x[0-9a-fA-F]+);/g, decodeEntity); } /** One XML entity, named or numeric, as its character. */ function decodeEntity(m: string): string { const named: Record = { '<': '<', '>': '>', '"': '"', ''': "'", '&': '&' }; if (named[m]) return named[m]!; const body = m.slice(2, -1); const code = body[0] === 'x' ? Number.parseInt(body.slice(1), 16) : Number(body); return Number.isInteger(code) && code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m; } /** Every element of a tag's text in an XML body, unescaped. */ export const allOf = (xml: string, tag: string): string[] => [...xml.matchAll(new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`, 'g'))].map((m) => unesc(m[1]!.trim())); /** The first. */ export const oneOf = (xml: string, tag: string): string | undefined => allOf(xml, tag)[0]; // ── CORS (https://developers.cloudflare.com/r2/buckets/cors/) ────────────────────────────────── export type CorsRule = { id?: string; allowedOrigins: string[]; allowedMethods: string[]; allowedHeaders: string[]; exposeHeaders: string[]; maxAgeSeconds?: number | string }; export function parseCors(xml: string): CorsRule[] { return [...xml.matchAll(/([\s\S]*?)<\/CORSRule>/g)].map((m) => { const b = m[1]!; const id = oneOf(b, 'ID'); const age = oneOf(b, 'MaxAgeSeconds'); return { ...(id ? { id } : {}), allowedOrigins: allOf(b, 'AllowedOrigin'), allowedMethods: allOf(b, 'AllowedMethod'), allowedHeaders: allOf(b, 'AllowedHeader'), exposeHeaders: allOf(b, 'ExposeHeader'), ...(age ? { maxAgeSeconds: wireInteger(age) } : {}) }; }); } export function corsXml(rules: CorsRule[]): string { return doc('CORSConfiguration', rules.map((r) => x('CORSRule', [ ...(r.id ? [x('ID', r.id)] : []), ...r.allowedOrigins.map((o) => x('AllowedOrigin', o)), ...r.allowedMethods.map((m) => x('AllowedMethod', m)), ...r.allowedHeaders.map((h) => x('AllowedHeader', h)), ...r.exposeHeaders.map((h) => x('ExposeHeader', h)), ...(r.maxAgeSeconds !== undefined ? [x('MaxAgeSeconds', r.maxAgeSeconds)] : []), ]))); } function wildMatch(pattern: string, value: string, fold: boolean): boolean { const p = fold ? pattern.toLowerCase() : pattern; const v = fold ? value.toLowerCase() : value; const star = p.indexOf('*'); if (star < 0) return p === v; return v.length >= p.length - 1 && v.startsWith(p.slice(0, star)) && v.endsWith(p.slice(star + 1)); } /** The first rule that allows the origin, the method and the headers a preflight asks for. */ export function corsRuleFor(rules: CorsRule[], origin: string, method: string, requested: string[]): CorsRule | undefined { return rules.find((r) => r.allowedOrigins.some((o) => wildMatch(o, origin, false)) && r.allowedMethods.some((m) => m === '*' || m.toUpperCase() === method.toUpperCase()) && requested.every((h) => r.allowedHeaders.some((a) => wildMatch(a, h, true)))); } /** The Access-Control-* headers a matching rule gives an answer ("AllowedOrigins: Specifies the value for the * Access-Control-Allow-Origin header", and likewise for the methods, headers, exposed headers and max age). */ export function corsHeaders(rule: CorsRule, origin: string, requested: string[], preflight: boolean): Record { return { 'access-control-allow-origin': origin, 'access-control-allow-methods': rule.allowedMethods.join(', '), vary: 'Origin, Access-Control-Request-Headers, Access-Control-Request-Method', ...(preflight && requested.length ? { 'access-control-allow-headers': requested.join(', ') } : {}), ...(preflight && rule.maxAgeSeconds !== undefined ? { 'access-control-max-age': String(rule.maxAgeSeconds) } : {}), ...(rule.exposeHeaders.length ? { 'access-control-expose-headers': rule.exposeHeaders.join(', ') } : {}), }; } export const requestedHeaders = (request: Request): string[] => (request.headers.get('access-control-request-headers') ?? '').split(',').map((h) => h.trim()).filter(Boolean); // ── lifecycle (https://developers.cloudflare.com/r2/buckets/object-lifecycles/) ────────────────── /** A rule's prefix is sent in its Filter or, in S3's older form, on the rule itself, or not at all (R2's lifecycle page * sends a transition rule with neither, for the whole bucket); it is answered as it was sent. A * transition moves an object to Infrequent Access (Object lifecycles: "transition objects to Infrequent Access storage * after 30 days", its example `Transitions: [{ Days: 30, StorageClass: "STANDARD_IA" }]`). */ export type LifecycleRule = { id: string; enabled: boolean; prefix: string; prefixOnRule?: boolean; noPrefix?: boolean; expireDays?: number | string; expireDate?: string; abortMultipartDays?: number | string; transitions?: Array<{ days?: number | string; date?: string; storageClass: string }> }; export function parseLifecycle(xml: string): LifecycleRule[] { return [...xml.matchAll(/([\s\S]*?)<\/Rule>/g)].map((m) => { const b = m[1]!; const expiration = /([\s\S]*?)<\/Expiration>/.exec(b)?.[1]; const abort = /([\s\S]*?)<\/AbortIncompleteMultipartUpload>/.exec(b)?.[1]; const days = expiration ? oneOf(expiration, 'Days') : undefined; const date = expiration ? oneOf(expiration, 'Date') : undefined; const after = abort ? oneOf(abort, 'DaysAfterInitiation') : undefined; const transitions = [...b.matchAll(/([\s\S]*?)<\/Transition>/g)].map((x) => { const d = oneOf(x[1]!, 'Days'); const on = oneOf(x[1]!, 'Date'); return { ...(d !== undefined ? { days: wireInteger(d) } : {}), ...(on !== undefined ? { date: on } : {}), storageClass: oneOf(x[1]!, 'StorageClass') ?? '' }; }); return { id: oneOf(b, 'ID') ?? '', enabled: (oneOf(b, 'Status') ?? 'Enabled') === 'Enabled', prefix: oneOf(b, 'Prefix') ?? '', ...(//.test(b) ? {} : //.test(b) ? { prefixOnRule: true } : { noPrefix: true }), ...(days ? { expireDays: wireInteger(days) } : {}), ...(date ? { expireDate: date } : {}), ...(after ? { abortMultipartDays: wireInteger(after) } : {}), ...(transitions.length ? { transitions } : {}), }; }); } export function lifecycleXml(rules: LifecycleRule[]): string { return doc('LifecycleConfiguration', rules.map((r) => x('Rule', [ x('ID', r.id), ...(r.noPrefix ? [] : [r.prefixOnRule ? x('Prefix', r.prefix) : x('Filter', [x('Prefix', r.prefix)])]), x('Status', r.enabled ? 'Enabled' : 'Disabled'), ...(r.transitions ?? []).map((tr) => x('Transition', [...(tr.date !== undefined ? [x('Date', tr.date)] : [x('Days', tr.days ?? 0)]), x('StorageClass', tr.storageClass)])), ...(r.expireDays !== undefined ? [x('Expiration', [x('Days', r.expireDays)])] : r.expireDate !== undefined ? [x('Expiration', [x('Date', r.expireDate)])] : []), ...(r.abortMultipartDays !== undefined ? [x('AbortIncompleteMultipartUpload', [x('DaysAfterInitiation', r.abortMultipartDays)])] : []), ]))); } // ── bodies ─────────────────────────────────────────────────────────────────────────────────── export function parseDelete(xml: string): { keys: string[]; quiet: boolean } { return { keys: [...xml.matchAll(/([\s\S]*?)<\/Object>/g)].map((m) => oneOf(m[1]!, 'Key') ?? ''), quiet: /\s*true\s*<\/Quiet>/i.test(xml) }; } export const locationConstraintOf = (xml: string): string | undefined => oneOf(xml, 'LocationConstraint'); export const md5Etag = (bytes: Uint8Array): string => `"${createHash('md5').update(bytes).digest('hex')}"`; /** A request's body as the bytes it carried. The derived dispatch reads a body as text to find its parameters, which no * binary object survives, so the lane's fetch reads the bytes first and keeps them here for the handler. */ const BODIES = new WeakMap(); export async function withBytes(request: Request): Promise { if (request.method === 'GET' || request.method === 'HEAD' || request.method === 'OPTIONS') return request; const bytes = new Uint8Array(await request.arrayBuffer()); const kept = new Request(request.url, { method: request.method, headers: request.headers, body: bytes }); BODIES.set(kept, bytes); return kept; } export const bytesOf = (request: Request): Uint8Array => BODIES.get(request) ?? new Uint8Array(0); /** Concatenate exact wire bytes; no text conversion is involved in multipart assembly. */ export function concatBytes(parts: readonly Uint8Array[]): Uint8Array { const out = new Uint8Array(parts.reduce((size, part) => size + part.byteLength, 0)); let offset = 0; for (const part of parts) { out.set(part, offset); offset += part.byteLength; } return out; } export type ChecksumAlgorithm = 'MD5' | 'SHA1' | 'SHA256' | 'CRC32' | 'CRC32C' | 'CRC64NVME'; /** S3's base64 digest; CRC bytes are big-endian on the wire. No streaming framing is decoded here. */ export function checksum(algorithm: ChecksumAlgorithm, bytes: Uint8Array): string { if (algorithm === 'MD5' || algorithm === 'SHA1' || algorithm === 'SHA256') { return createHash(algorithm.toLowerCase()).update(bytes).digest('base64'); } if (algorithm === 'CRC64NVME') { // AWS's reflected NVME polynomial: aws-checksums/tests/crc64_test.c. let crc = 0xffffffffffffffffn; for (const byte of bytes) { crc ^= BigInt(byte); for (let bit = 0; bit < 8; bit++) crc = (crc >> 1n) ^ (crc & 1n ? 0x9a6c9329ac4bc9b5n : 0n); } const out = new Uint8Array(8); new DataView(out.buffer).setBigUint64(0, crc ^ 0xffffffffffffffffn, false); return Buffer.from(out).toString('base64'); } const polynomial = algorithm === 'CRC32C' ? 0x82f63b78 : 0xedb88320; let crc = 0xffffffff; for (const byte of bytes) { crc ^= byte; for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ (crc & 1 ? polynomial : 0); } const out = new Uint8Array(4); new DataView(out.buffer).setUint32(0, (crc ^ 0xffffffff) >>> 0, false); return Buffer.from(out).toString('base64'); }