cloudrop 0.2.0 → 0.3.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","names":["utf8","memoryStore","createMemoryStore"],"sources":["../src/storage/xml.ts","../src/checksum.ts","../src/rules.ts","../src/storage/sigv4.ts","../src/testing/fake-r2/responses.ts","../src/testing/fake-r2/bucket.ts","../src/testing/fake-r2/copy.ts","../src/testing/fake-r2/multipart.ts","../src/testing/fake-r2/objects.ts","../src/testing/fake-r2/signature.ts","../src/testing/fake-r2.ts","../src/testing/memory-store-reads.ts","../src/testing/memory-store-methods.ts","../src/testing/memory-store.ts","../src/testing.ts"],"sourcesContent":["// S3 responses are small, flat XML documents. A tag-based reader covers every response cloudrop parses and keeps the\n// package free of an XML dependency.\n\nconst ENTITIES: Record<string, string> = { amp: \"&\", lt: \"<\", gt: \">\", quot: '\"', apos: \"'\" };\nconst ESCAPES: Record<string, string> = { \"<\": \"&lt;\", \">\": \"&gt;\", \"&\": \"&amp;\", '\"': \"&quot;\", \"'\": \"&apos;\" };\n\nfunction decodeXml(text: string): string {\n return text.replace(/&(#x[0-9a-fA-F]+|#\\d+|amp|lt|gt|quot|apos);/g, (match, entity: string) => {\n if (!entity.startsWith(\"#\")) return ENTITIES[entity] ?? \"\";\n const codePoint = entity[1] === \"x\" ? Number.parseInt(entity.slice(2), 16) : Number.parseInt(entity.slice(1), 10);\n // Out-of-range references stay as written: a malformed body must never make a public call throw.\n return Number.isFinite(codePoint) && codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : match;\n });\n}\n\n/**\n * Inner XML of every `<tag>…</tag>` element, in document order. `tag` is an internal constant, never user input, so it\n * is not escaped into the pattern; response bodies are bounded by the caller. Self-closing `<tag />` has no content and\n * is skipped.\n */\nexport function xmlBlocks(xml: string, tag: string): string[] {\n const pattern = new RegExp(`<${tag}(?:\\\\s[^>]*)?(?<!/)>([\\\\s\\\\S]*?)</${tag}>`, \"g\");\n return Array.from(xml.matchAll(pattern), (match) => match[1] ?? \"\");\n}\n\n/**\n * Decoded text of the first `<tag>` element exactly as sent, or undefined when absent. For keys, upload IDs,\n * continuation tokens and prefixes: whitespace at their edges is part of the value (\"users/42/a \" is its own key).\n */\nexport function xmlText(xml: string, tag: string): string | undefined {\n const block = xmlBlocks(xml, tag)[0];\n return block === undefined ? undefined : decodeXml(block);\n}\n\n/** Like xmlText, trimmed: for numbers, dates, booleans, codes and ETags, whose edge whitespace means nothing. */\nexport function xmlValue(xml: string, tag: string): string | undefined {\n return xmlText(xml, tag)?.trim();\n}\n\n/** Trimmed text of every `<tag>` element, in document order: for lists of origins, methods and header names. */\nexport function xmlValues(xml: string, tag: string): string[] {\n return xmlBlocks(xml, tag).map((block) => decodeXml(block).trim());\n}\n\nexport function stripQuotes(value: string): string {\n return value.replaceAll('\"', \"\");\n}\n\nexport function escapeXml(value: string): string {\n return value.replace(/[<>&\"']/g, (char) => ESCAPES[char] ?? char);\n}\n","// CRC32C (Castagnoli), the per-part checksum R2 validates when it is a signed header (spike Q5). It runs over every\n// uploaded byte, so it uses slicing-by-8 with tables built at load time (8 KiB of memory, no table literal in the\n// bundle). Measured on Node 26, 64 MiB buffer, median of 5: plain `for...of` + `?? 0` 150 MiB/s, indexed byte loop\n// 659 MiB/s, this slicing-by-8 2172 MiB/s (about 18 times a 1 Gbps uplink). Spec §11.1 gates WebAssembly behind a\n// benchmark; this clears the bar without it.\n\nconst POLYNOMIAL = 0x82f63b78;\n\n// TABLES[k * 256 + b] is the CRC of byte `b` followed by `k` zero bytes; row 0 is the classic byte-at-a-time table.\nconst TABLES: Uint32Array = (() => {\n const tables = new Uint32Array(8 * 256);\n for (let index = 0; index < 256; index++) {\n let value = index;\n for (let bit = 0; bit < 8; bit++) value = value & 1 ? (value >>> 1) ^ POLYNOMIAL : value >>> 1;\n tables[index] = value >>> 0;\n }\n for (let index = 0; index < 256; index++) {\n let value = tables[index] as number;\n for (let row = 1; row < 8; row++) {\n value = (tables[value & 0xff] as number) ^ (value >>> 8);\n tables[row * 256 + index] = value >>> 0;\n }\n }\n return tables;\n})();\n\n/** CRC32C of `bytes`. Pass the previous result as `previous` to continue a checksum across chunks. */\nexport function crc32c(bytes: Uint8Array, previous = 0): number {\n // `as number` below: every index is in bounds by construction, and `?? 0` cost 4x in this loop (measured).\n let crc = ~previous >>> 0;\n let index = 0;\n const blockEnd = bytes.length - 8;\n for (; index <= blockEnd; index += 8) {\n const low =\n crc ^\n (bytes[index] as number) ^\n ((bytes[index + 1] as number) << 8) ^\n ((bytes[index + 2] as number) << 16) ^\n ((bytes[index + 3] as number) << 24);\n crc =\n ((TABLES[1792 + (low & 0xff)] as number) ^\n (TABLES[1536 + ((low >>> 8) & 0xff)] as number) ^\n (TABLES[1280 + ((low >>> 16) & 0xff)] as number) ^\n (TABLES[1024 + (low >>> 24)] as number) ^\n (TABLES[768 + (bytes[index + 4] as number)] as number) ^\n (TABLES[512 + (bytes[index + 5] as number)] as number) ^\n (TABLES[256 + (bytes[index + 6] as number)] as number) ^\n (TABLES[bytes[index + 7] as number] as number)) >>>\n 0;\n }\n for (; index < bytes.length; index++) {\n crc = (TABLES[(crc ^ (bytes[index] as number)) & 0xff] as number) ^ (crc >>> 8);\n }\n return ~crc >>> 0;\n}\n\n/** The `x-amz-checksum-crc32c` header value: base64 of the big-endian CRC32C. `btoa` is a web-platform global (no\n * `Buffer`), and four binary characters are all it ever sees. */\nexport function crc32cBase64(bytes: Uint8Array): string {\n const value = crc32c(bytes);\n return btoa(String.fromCharCode(value >>> 24, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff));\n}\n","export const MiB: number = 1024 * 1024;\nexport const GiB: number = 1024 * MiB;\nconst TiB: number = 1024 * GiB;\n\n/** Limits of a storage backend, in bytes and seconds. */\nexport interface StorageRules {\n minPartSize: number;\n maxPartSize: number;\n maxParts: number;\n maxSinglePutSize: number;\n maxObjectSize: number;\n maxPresignSeconds: number;\n}\n\nexport const R2_RULES: StorageRules = {\n // Every limit below: https://developers.cloudflare.com/r2/platform/limits/ unless noted.\n // Minimum part size, except for the last part. Spike Q4 confirmed EntityTooSmall below it.\n minPartSize: 5 * MiB,\n // Docs: 5 GiB per part, capped at 4.995 GiB by the upload limit (research doc section C.1).\n maxPartSize: 5 * GiB - 5 * MiB,\n // Maximum parts in one multipart upload.\n maxParts: 10_000,\n // Single PUT: \"5 MiB less than 5 GiB, so 4.995 GiB\".\n maxSinglePutSize: 5 * GiB - 5 * MiB,\n // Multipart object: 4.995 TiB (5 TiB minus 5 GiB).\n maxObjectSize: 5 * TiB - 5 * GiB,\n // Presigned URL expiry: 604,800 s accepted, 604,801 rejected (spike finding Q7).\n maxPresignSeconds: 604_800,\n};\n\nexport const S3_RULES: StorageRules = {\n // https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html\n minPartSize: 5 * MiB,\n maxPartSize: 5 * GiB,\n maxParts: 10_000,\n // Largest single PUT.\n maxSinglePutSize: 5 * GiB,\n // \"Maximum object size: 48.8 TiB\" = 10,000 parts x 5 GiB (https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html).\n maxObjectSize: 10_000 * 5 * GiB,\n // SigV4 presigned URLs live at most 7 days.\n maxPresignSeconds: 604_800,\n};\n","// AWS Signature Version 4 for S3, on WebCrypto, so it runs in browsers, Workers, Deno, Bun and Node.\n// Presigned URLs sign exactly the headers the client will send: R2 enforces signed content-length, content-type and\n// checksum headers, and ignores checksum values passed as query parameters (docs/research/r2-spike-findings.md).\n\nconst encoder = new TextEncoder();\n\nexport const UNSIGNED_PAYLOAD = \"UNSIGNED-PAYLOAD\";\nexport const EMPTY_SHA256 = \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\";\n\nexport interface Credentials {\n accessKeyId: string;\n secretAccessKey: string;\n}\n\nexport interface SigningInput {\n method: string;\n url: URL;\n /** Headers to sign. `host` is always signed and taken from `url`. */\n headers?: Record<string, string>;\n credentials: Credentials;\n region: string;\n date: Date;\n}\n\nexport function toHex(bytes: ArrayBuffer | Uint8Array): string {\n const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);\n return Array.from(view, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function sha256Hex(data: string | Uint8Array<ArrayBuffer>): Promise<string> {\n const bytes = typeof data === \"string\" ? encoder.encode(data) : data;\n return toHex(await crypto.subtle.digest(\"SHA-256\", bytes));\n}\n\nfunction importHmacKey(raw: Uint8Array<ArrayBuffer>): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"raw\", raw, { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n}\n\nasync function hmac(key: CryptoKey, data: string): Promise<Uint8Array<ArrayBuffer>> {\n return new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(data)));\n}\n\nasync function deriveSigningKey(secretAccessKey: string, day: string, region: string): Promise<CryptoKey> {\n let raw = await hmac(await importHmacKey(encoder.encode(`AWS4${secretAccessKey}`)), day);\n for (const part of [region, \"s3\", \"aws4_request\"]) raw = await hmac(await importHmacKey(raw), part);\n return importHmacKey(raw);\n}\n\n// The signing key only changes with the UTC day, region or secret, so a multipart upload derives it once instead of\n// once per part. Measured on Bun, 5000 presigns: 25.8 us each reusing one credentials object, 53.2 us with a new one\n// per call (an earlier run: 23.6 vs 54.9). The cache hangs off the caller's credentials object, so it dies with it and\n// no module-wide map ever holds a secret; the secret it was derived from is kept beside the keys only to notice a\n// secret changed in place.\ninterface CachedKeys {\n secretAccessKey: string;\n byScope: Map<string, Promise<CryptoKey>>;\n}\nconst signingKeys = new WeakMap<Credentials, CachedKeys>();\n// A presigned GET may be signed at an earlier time (api.getUrl rounds it down to its window), so a long-lived\n// credentials object would otherwise keep a key for every day and region it ever signed for. Eight covers the current\n// day and the few days such windows reach; dropping them all when full leaves a cache hit untouched.\nconst MAX_CACHED_SCOPES = 8;\n\nfunction signingKey(credentials: Credentials, day: string, region: string): Promise<CryptoKey> {\n let cached = signingKeys.get(credentials);\n if (cached?.secretAccessKey !== credentials.secretAccessKey) {\n cached = { secretAccessKey: credentials.secretAccessKey, byScope: new Map() };\n signingKeys.set(credentials, cached);\n }\n const scope = `${day}/${region}`;\n let derived = cached.byScope.get(scope);\n if (!derived) {\n const { byScope } = cached;\n if (byScope.size >= MAX_CACHED_SCOPES) byScope.clear();\n derived = deriveSigningKey(credentials.secretAccessKey, day, region);\n derived.catch(() => byScope.delete(scope));\n byScope.set(scope, derived);\n }\n return derived;\n}\n\nexport function encodeRfc3986(value: string): string {\n return encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);\n}\n\n/**\n * Encodes an object key for a URL path: each segment RFC 3986-encoded, slashes kept.\n * Throws `URIError` for a key that is not well-formed Unicode (a lone surrogate); key validation rejects those first.\n */\nexport function encodeKeyPath(key: string): string {\n return key.split(\"/\").map(encodeRfc3986).join(\"/\");\n}\n\nfunction toAmzDate(date: Date): string {\n return date.toISOString().replace(/[-:]|\\.\\d{3}/g, \"\");\n}\n\n// `URL` leaves `!'()*+` and similar characters raw in the path, but S3 signs the RFC 3986 form of every segment\n// (encoded once, never twice), so decode and encode again. Precondition: segments are RFC 3986-encoded, as\n// `encodeKeyPath` produces; a bare `%` or an escape that is not valid UTF-8 throws `URIError` (createS3Driver checks the endpoint path for both), and a raw `+` is signed as `%2B`.\nfunction canonicalPath(url: URL): string {\n return url.pathname\n .split(\"/\")\n .map((segment) => encodeRfc3986(decodeURIComponent(segment)))\n .join(\"/\");\n}\n\n// Sorts by encoded name, then encoded value, as SigV4 requires; repeated names are ordered by their encoded values.\nexport function canonicalQuery(params: URLSearchParams): string {\n return Array.from(params, ([name, value]) => [encodeRfc3986(name), encodeRfc3986(value)] as const)\n .sort(([aName, aValue], [bName, bValue]) => {\n if (aName !== bName) return aName < bName ? -1 : 1;\n if (aValue === bValue) return 0;\n return aValue < bValue ? -1 : 1;\n })\n .map(([name, value]) => `${name}=${value}`)\n .join(\"&\");\n}\n\nfunction canonicalHeaders(url: URL, headers: Record<string, string>): { canonical: string; signedHeaders: string } {\n const all: Record<string, string> = { host: url.host };\n for (const [name, value] of Object.entries(headers)) all[name.toLowerCase()] = value.trim().replace(/\\s+/g, \" \");\n const names = Object.keys(all).sort();\n return { canonical: names.map((name) => `${name}:${all[name]}\\n`).join(\"\"), signedHeaders: names.join(\";\") };\n}\n\nasync function sign(input: SigningInput, amzDate: string, scope: string, canonicalRequest: string): Promise<string> {\n const stringToSign = [\"AWS4-HMAC-SHA256\", amzDate, scope, await sha256Hex(canonicalRequest)].join(\"\\n\");\n const key = await signingKey(input.credentials, amzDate.slice(0, 8), input.region);\n return toHex(await hmac(key, stringToSign));\n}\n\nexport async function presignUrl(input: SigningInput & { expiresIn: number }): Promise<URL> {\n const amzDate = toAmzDate(input.date);\n const scope = `${amzDate.slice(0, 8)}/${input.region}/s3/aws4_request`;\n const { canonical, signedHeaders } = canonicalHeaders(input.url, input.headers ?? {});\n const url = new URL(input.url);\n url.searchParams.set(\"X-Amz-Algorithm\", \"AWS4-HMAC-SHA256\");\n url.searchParams.set(\"X-Amz-Credential\", `${input.credentials.accessKeyId}/${scope}`);\n url.searchParams.set(\"X-Amz-Date\", amzDate);\n url.searchParams.set(\"X-Amz-Expires\", String(input.expiresIn));\n url.searchParams.set(\"X-Amz-SignedHeaders\", signedHeaders);\n const query = canonicalQuery(url.searchParams);\n const request = [input.method, canonicalPath(url), query, canonical, signedHeaders, UNSIGNED_PAYLOAD].join(\"\\n\");\n url.search = `${query}&X-Amz-Signature=${await sign(input, amzDate, scope, request)}`;\n return url;\n}\n\nexport async function signRequest(input: SigningInput & { payloadHash: string }): Promise<Record<string, string>> {\n const amzDate = toAmzDate(input.date);\n const scope = `${amzDate.slice(0, 8)}/${input.region}/s3/aws4_request`;\n const headers = { ...input.headers, \"x-amz-content-sha256\": input.payloadHash, \"x-amz-date\": amzDate };\n const { canonical, signedHeaders } = canonicalHeaders(input.url, headers);\n const request = [\n input.method,\n canonicalPath(input.url),\n canonicalQuery(input.url.searchParams),\n canonical,\n signedHeaders,\n input.payloadHash,\n ].join(\"\\n\");\n const signature = await sign(input, amzDate, scope, request);\n return {\n ...headers,\n authorization: `AWS4-HMAC-SHA256 Credential=${input.credentials.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,\n };\n}\n","// The XML answers the fake R2 sends, in the shape of S3's documented responses.\n\nimport { escapeXml } from \"../../storage/xml.ts\";\n\nconst XML_HEADERS = { \"content-type\": \"application/xml\" };\n\nexport function xmlResponse(body: string, status = 200): Response {\n return new Response(`<?xml version=\"1.0\" encoding=\"UTF-8\"?>${body}`, { status, headers: XML_HEADERS });\n}\n\nexport function errorResponse(status: number, code: string, message: string): Response {\n return xmlResponse(`<Error><Code>${code}</Code><Message>${escapeXml(message)}</Message></Error>`, status);\n}\n\nexport const noSuchUpload = (): Response =>\n errorResponse(404, \"NoSuchUpload\", \"The specified multipart upload does not exist.\");\nexport const clockSkewed = (): Response =>\n errorResponse(\n 403,\n \"RequestTimeTooSkewed\",\n \"The difference between the request time and the server time is too large.\",\n );\nexport const preconditionFailed = (): Response =>\n errorResponse(412, \"PreconditionFailed\", \"At least one of the pre-conditions you specified did not hold.\");\n","// The fake bucket's state and the helpers every operation shares.\n\nimport { crc32cBase64 } from \"../../checksum.ts\";\nimport { R2_RULES } from \"../../rules.ts\";\nimport { type Credentials, sha256Hex } from \"../../storage/sigv4.ts\";\nimport { errorResponse } from \"./responses.ts\";\n\nexport type Bytes = Uint8Array<ArrayBuffer>;\n\nexport interface StoredHeaders {\n type: string | undefined;\n disposition: string | undefined;\n metadata: Record<string, string>;\n}\n\nexport interface StoredObject {\n body: Bytes;\n headers: StoredHeaders;\n etag: string;\n uploadedAt: Date;\n partCount?: number;\n}\n\nexport interface StoredPart {\n body: Bytes;\n etag: string;\n checksumCrc32c: string | undefined;\n uploadedAt: Date;\n}\n\nexport interface PendingUpload {\n key: string;\n headers: StoredHeaders;\n parts: Map<number, StoredPart>;\n}\n\n/** One bucket: its configuration, the clock it trusts, and everything stored in it. */\nexport interface FakeBucket {\n readonly name: string;\n readonly credentials: Credentials;\n readonly now: () => Date;\n readonly config: { cors?: string; lifecycle?: string } | undefined;\n readonly objects: Map<string, StoredObject>;\n readonly uploads: Map<string, PendingUpload>;\n readonly listTokens: Map<string, string>;\n uploadCounter: number;\n}\n\n/** A request whose signature has been verified, addressed to one key of the bucket. */\nexport interface FakeRequest {\n method: string;\n key: string;\n query: URLSearchParams;\n headers: Headers;\n body: Bytes;\n}\n\nexport const META_PREFIX = \"x-amz-meta-\";\nexport const MAX_LIST_PAGE = 1000;\n\nexport async function etagOf(body: Bytes): Promise<string> {\n return (await sha256Hex(body)).slice(0, 32);\n}\n\nexport function readHeaders(headers: Headers): StoredHeaders {\n const metadata: Record<string, string> = {};\n headers.forEach((value, name) => {\n if (name.startsWith(META_PREFIX)) metadata[name.slice(META_PREFIX.length)] = value;\n });\n return {\n type: headers.get(\"content-type\") ?? undefined,\n disposition: headers.get(\"content-disposition\") ?? undefined,\n metadata,\n };\n}\n\nexport function checksumMismatch(headers: Headers, body: Bytes): Response | null {\n const expected = headers.get(\"x-amz-checksum-crc32c\");\n if (expected === null || expected === crc32cBase64(body)) return null;\n return errorResponse(400, \"BadDigest\", \"The CRC32C you specified did not match the calculated checksum.\");\n}\n\nexport function findUpload(bucket: FakeBucket, key: string, query: URLSearchParams): PendingUpload | undefined {\n const upload = bucket.uploads.get(query.get(\"uploadId\") ?? \"\");\n return upload && upload.key === key ? upload : undefined;\n}\n\nexport function readPartNumber(query: URLSearchParams): number | Response {\n const partNumber = Number(query.get(\"partNumber\"));\n if (Number.isInteger(partNumber) && partNumber >= 1 && partNumber <= R2_RULES.maxParts) return partNumber;\n return errorResponse(400, \"InvalidArgument\", \"Part number must be an integer between 1 and 10000.\");\n}\n","// CopyObject, UploadPartCopy and the bucket-configuration reads and writes of the fake R2.\n\nimport { stripQuotes, xmlBlocks } from \"../../storage/xml.ts\";\nimport {\n type Bytes,\n etagOf,\n type FakeBucket,\n type FakeRequest,\n findUpload,\n readHeaders,\n readPartNumber,\n type StoredObject,\n} from \"./bucket.ts\";\nimport { errorResponse, noSuchUpload, preconditionFailed, xmlResponse } from \"./responses.ts\";\n\nfunction copySource(bucket: FakeBucket, headers: Headers): StoredObject | Response {\n const [sourceBucket = \"\", ...sourceSegments] = (headers.get(\"x-amz-copy-source\") ?? \"\").replace(/^\\//, \"\").split(\"/\");\n const source =\n decodeURIComponent(sourceBucket) === bucket.name\n ? bucket.objects.get(sourceSegments.map(decodeURIComponent).join(\"/\"))\n : undefined;\n if (!source) return errorResponse(404, \"NoSuchKey\", \"The copy source does not exist.\");\n // Modelled on S3's documented CopyObject and UploadPartCopy precondition.\n const ifMatch = headers.get(\"x-amz-copy-source-if-match\");\n if (ifMatch !== null && stripQuotes(ifMatch) !== source.etag) return preconditionFailed();\n return source;\n}\n\nfunction copiedRange(source: StoredObject, rangeHeader: string | null): Bytes | Response {\n if (rangeHeader === null) return source.body;\n const range = /^bytes=(\\d+)-(\\d+)$/.exec(rangeHeader);\n const [start, end] = [Number(range?.[1]), Number(range?.[2])];\n if (!range || start > end || end >= source.body.length) {\n return errorResponse(400, \"InvalidArgument\", \"The copy source range is malformed or outside the source object.\");\n }\n return source.body.subarray(start, end + 1);\n}\n\nasync function copyPart(\n bucket: FakeBucket,\n { key, query, headers }: FakeRequest,\n source: StoredObject,\n): Promise<Response> {\n const upload = findUpload(bucket, key, query);\n if (!upload) return noSuchUpload();\n const partNumber = readPartNumber(query);\n if (partNumber instanceof Response) return partNumber;\n const body = copiedRange(source, headers.get(\"x-amz-copy-source-range\"));\n if (body instanceof Response) return body;\n const etag = await etagOf(body);\n upload.parts.set(partNumber, { body, etag, checksumCrc32c: undefined, uploadedAt: bucket.now() });\n return xmlResponse(`<CopyPartResult><ETag>\"${etag}\"</ETag></CopyPartResult>`);\n}\n\nasync function copyObject(bucket: FakeBucket, { key, headers }: FakeRequest, source: StoredObject): Promise<Response> {\n // R2 keeps type, disposition and metadata by default and drops what a REPLACE does not resend (spike Q14).\n const replaced = headers.get(\"x-amz-metadata-directive\") === \"REPLACE\";\n // R2 also rewrites a multipart object's ETag to the plain content hash on copy (spike Q14).\n const etag = await etagOf(source.body);\n bucket.objects.set(key, {\n body: source.body,\n headers: replaced ? readHeaders(headers) : source.headers,\n etag,\n uploadedAt: bucket.now(),\n });\n return xmlResponse(`<CopyObjectResult><ETag>\"${etag}\"</ETag></CopyObjectResult>`);\n}\n\n/** A PUT with `x-amz-copy-source`: UploadPartCopy when it names an upload, CopyObject otherwise. */\nexport async function copy(bucket: FakeBucket, request: FakeRequest): Promise<Response> {\n const source = copySource(bucket, request.headers);\n if (source instanceof Response) return source;\n return request.query.has(\"uploadId\") ? copyPart(bucket, request, source) : copyObject(bucket, request, source);\n}\n\nexport function bucketConfig(bucket: FakeBucket, name: \"cors\" | \"lifecycle\"): Response {\n if (!bucket.config) return errorResponse(403, \"AccessDenied\", \"Access Denied\");\n const xml = bucket.config[name];\n if (xml !== undefined) return xmlResponse(xml);\n const code = name === \"cors\" ? \"NoSuchCORSConfiguration\" : \"NoSuchLifecycleConfiguration\";\n return errorResponse(404, code, \"The bucket has no such configuration.\");\n}\n\n// What S3 requires of each rule in the body: a CORS rule allows at least one origin and one method; a lifecycle rule\n// has a status and a scope.\nconst SHAPES = {\n cors: { root: \"CORSConfiguration\", rule: \"CORSRule\", needs: [[\"AllowedOrigin\"], [\"AllowedMethod\"]] },\n lifecycle: { root: \"LifecycleConfiguration\", rule: \"Rule\", needs: [[\"Status\"], [\"Filter\", \"Prefix\"]] },\n} as const;\n\nfunction wellFormed(xml: string, name: \"cors\" | \"lifecycle\"): boolean {\n const { root, rule, needs } = SHAPES[name];\n const rules = xmlBlocks(xmlBlocks(xml, root)[0] ?? \"\", rule);\n return rules.length > 0 && rules.every((each) => needs.every((tags) => tags.some((tag) => each.includes(`<${tag}`))));\n}\n\n/**\n * PutBucketCors and PutBucketLifecycleConfiguration: the body replaces the whole configuration, as S3 documents. Refused\n * like the reads when the bucket models an object token (no `bucketConfig`). S3 requires an integrity checksum on both\n * (Content-MD5 or x-amz-checksum-*); R2's answer without one is unmeasured, so the fake follows S3 and checks SHA-256.\n */\nexport async function putBucketConfig(\n bucket: FakeBucket,\n name: \"cors\" | \"lifecycle\",\n { headers, body }: FakeRequest,\n): Promise<Response> {\n if (!bucket.config) return errorResponse(403, \"AccessDenied\", \"Access Denied\");\n const sha256 = headers.get(\"x-amz-checksum-sha256\");\n if (sha256 === null) {\n return errorResponse(400, \"InvalidRequest\", \"Missing required header for this request: Content-MD5\");\n }\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", body));\n if (sha256 !== btoa(String.fromCharCode(...digest))) {\n return errorResponse(400, \"BadDigest\", \"The SHA256 you specified did not match the calculated checksum.\");\n }\n const xml = new TextDecoder().decode(body).replace(/^<\\?xml[^>]*\\?>/, \"\");\n if (!wellFormed(xml, name)) return errorResponse(400, \"MalformedXML\", \"The XML you provided was not well-formed.\");\n bucket.config[name] = xml;\n return new Response(null, { status: 200 });\n}\n","// Multipart upload operations of the fake R2: create, upload a part, list parts, complete and abort.\n\nimport { R2_RULES } from \"../../rules.ts\";\nimport { escapeXml, stripQuotes, xmlBlocks, xmlText } from \"../../storage/xml.ts\";\nimport {\n type Bytes,\n checksumMismatch,\n etagOf,\n type FakeBucket,\n type FakeRequest,\n findUpload,\n MAX_LIST_PAGE,\n type PendingUpload,\n readHeaders,\n readPartNumber,\n type StoredPart,\n} from \"./bucket.ts\";\nimport { errorResponse, noSuchUpload, preconditionFailed, xmlResponse } from \"./responses.ts\";\n\nconst utf8 = new TextEncoder();\n\nfunction concat(chunks: Bytes[]): Bytes {\n const out = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.length;\n }\n return out;\n}\n\nexport function createUpload(bucket: FakeBucket, { key, headers }: FakeRequest): Response {\n bucket.uploadCounter += 1;\n // Real upload IDs are opaque; this one needs URL encoding, so a client that forgets it fails here.\n const uploadId = `fake/upload+${bucket.uploadCounter}==`;\n bucket.uploads.set(uploadId, { key, headers: readHeaders(headers), parts: new Map() });\n return xmlResponse(\n `<InitiateMultipartUploadResult><Bucket>${escapeXml(bucket.name)}</Bucket><Key>${escapeXml(key)}</Key><UploadId>${escapeXml(uploadId)}</UploadId></InitiateMultipartUploadResult>`,\n );\n}\n\nexport async function uploadPart(bucket: FakeBucket, { key, query, headers, body }: FakeRequest): Promise<Response> {\n const upload = findUpload(bucket, key, query);\n if (!upload) return noSuchUpload();\n const badChecksum = checksumMismatch(headers, body);\n if (badChecksum) return badChecksum;\n const partNumber = readPartNumber(query);\n if (partNumber instanceof Response) return partNumber;\n const etag = await etagOf(body);\n upload.parts.set(partNumber, {\n body,\n etag,\n checksumCrc32c: headers.get(\"x-amz-checksum-crc32c\") ?? undefined,\n uploadedAt: bucket.now(),\n });\n return new Response(null, { status: 200, headers: { etag: `\"${etag}\"` } });\n}\n\n// The part-size rules are checked only here, never at UploadPart, and a failure keeps the upload alive (spike Q4).\nfunction partSizeFailure(parts: StoredPart[]): Response | null {\n const firstSize = parts[0]?.body.length ?? 0;\n for (const [index, part] of parts.entries()) {\n const isLast = index === parts.length - 1;\n if (!isLast && part.body.length < R2_RULES.minPartSize) {\n return errorResponse(\n 400,\n \"EntityTooSmall\",\n \"Your proposed upload is smaller than the minimum allowed object size.\",\n );\n }\n // Every part but the last must equal the first; the last may be smaller, never larger (spike Q4).\n if (isLast ? part.body.length > firstSize : part.body.length !== firstSize) {\n return errorResponse(400, \"InvalidPart\", \"All non-trailing parts must have the same length.\");\n }\n }\n return null;\n}\n\n// The stored parts the CompleteMultipartUpload body names, in its order.\nfunction requestedParts(upload: PendingUpload, body: Bytes): StoredPart[] | Response {\n const requested = xmlBlocks(new TextDecoder().decode(body), \"Part\").map((block) => ({\n partNumber: Number(xmlText(block, \"PartNumber\")),\n etag: stripQuotes(xmlText(block, \"ETag\") ?? \"\"),\n }));\n if (requested.length === 0) return errorResponse(400, \"MalformedXML\", \"The request lists no parts.\");\n const parts: StoredPart[] = [];\n let previousNumber = 0;\n for (const item of requested) {\n if (item.partNumber <= previousNumber) {\n return errorResponse(400, \"InvalidPartOrder\", \"Parts must be listed in ascending order.\");\n }\n previousNumber = item.partNumber;\n const part = upload.parts.get(item.partNumber);\n if (!part || part.etag !== item.etag) {\n return errorResponse(400, \"InvalidPart\", `Part ${item.partNumber} was not found or its ETag does not match.`);\n }\n parts.push(part);\n }\n return parts;\n}\n\nexport async function completeUpload(\n bucket: FakeBucket,\n { key, query, headers, body }: FakeRequest,\n): Promise<Response> {\n const uploadId = query.get(\"uploadId\") ?? \"\";\n const upload = findUpload(bucket, key, query);\n if (!upload) return noSuchUpload();\n const parts = requestedParts(upload, body);\n if (parts instanceof Response) return parts;\n const sizeFailure = partSizeFailure(parts);\n if (sizeFailure) return sizeFailure;\n // A failed conditional Complete discards the upload (spike Q3).\n if (headers.get(\"if-none-match\") === \"*\" && bucket.objects.has(key)) {\n bucket.uploads.delete(uploadId);\n return preconditionFailed();\n }\n const etag = `${await etagOf(utf8.encode(parts.map((part) => part.etag).join(\"\")))}-${parts.length}`;\n bucket.objects.set(key, {\n body: concat(parts.map((part) => part.body)),\n headers: upload.headers,\n etag,\n uploadedAt: bucket.now(),\n partCount: parts.length,\n });\n bucket.uploads.delete(uploadId);\n return xmlResponse(\n `<CompleteMultipartUploadResult><Bucket>${escapeXml(bucket.name)}</Bucket><Key>${escapeXml(key)}</Key><ETag>\"${etag}\"</ETag></CompleteMultipartUploadResult>`,\n );\n}\n\nexport function listParts(bucket: FakeBucket, { key, query }: FakeRequest): Response {\n const upload = findUpload(bucket, key, query);\n if (!upload) return noSuchUpload();\n const max = Math.min(Number(query.get(\"max-parts\") ?? MAX_LIST_PAGE), MAX_LIST_PAGE);\n const marker = Number(query.get(\"part-number-marker\") ?? 0);\n const remaining = Array.from(upload.parts)\n .filter(([number]) => number > marker)\n .sort(([a], [b]) => a - b);\n const page = remaining.slice(0, max);\n const truncated = remaining.length > max;\n const parts = page\n .map(([number, part]) => {\n const checksum = part.checksumCrc32c ? `<ChecksumCRC32C>${part.checksumCrc32c}</ChecksumCRC32C>` : \"\";\n return `<Part><PartNumber>${number}</PartNumber><ETag>\"${part.etag}\"</ETag><Size>${part.body.length}</Size><LastModified>${part.uploadedAt.toISOString()}</LastModified>${checksum}</Part>`;\n })\n .join(\"\");\n const next = truncated ? `<NextPartNumberMarker>${page.at(-1)?.[0] ?? marker}</NextPartNumberMarker>` : \"\";\n return xmlResponse(`<ListPartsResult><IsTruncated>${truncated}</IsTruncated>${next}${parts}</ListPartsResult>`);\n}\n\nexport function abortUpload(bucket: FakeBucket, { key, query }: FakeRequest): Response {\n // Real R2 answers 204 even after the upload completed (spike Q11), where AWS S3 answers 404.\n if (findUpload(bucket, key, query)) bucket.uploads.delete(query.get(\"uploadId\") ?? \"\");\n return new Response(null, { status: 204 });\n}\n","// Single-object operations and ListObjectsV2 of the fake R2.\n\nimport { escapeXml } from \"../../storage/xml.ts\";\nimport {\n checksumMismatch,\n etagOf,\n type FakeBucket,\n type FakeRequest,\n MAX_LIST_PAGE,\n META_PREFIX,\n readHeaders,\n type StoredObject,\n} from \"./bucket.ts\";\nimport { errorResponse, preconditionFailed, xmlResponse } from \"./responses.ts\";\n\nconst utf8 = new TextEncoder();\n\n// S3 lists keys in UTF-8 byte order, which differs from JavaScript's UTF-16 order for astral characters.\nfunction compareKeys(a: string, b: string): number {\n const left = utf8.encode(a);\n const right = utf8.encode(b);\n for (let index = 0; index < Math.min(left.length, right.length); index++) {\n if (left[index] !== right[index]) return (left[index] as number) - (right[index] as number);\n }\n return left.length - right.length;\n}\n\nexport async function putObject(bucket: FakeBucket, { key, headers, body }: FakeRequest): Promise<Response> {\n const badChecksum = checksumMismatch(headers, body);\n if (badChecksum) return badChecksum;\n // Honoured even when unsigned (spike Q3).\n if (headers.get(\"if-none-match\") === \"*\" && bucket.objects.has(key)) return preconditionFailed();\n const etag = await etagOf(body);\n bucket.objects.set(key, { body, headers: readHeaders(headers), etag, uploadedAt: bucket.now() });\n return new Response(null, { status: 200, headers: { etag: `\"${etag}\"` } });\n}\n\nfunction objectHeaders(object: StoredObject): Headers {\n const headers = new Headers({\n etag: `\"${object.etag}\"`,\n \"last-modified\": object.uploadedAt.toUTCString(),\n \"content-length\": String(object.body.length),\n });\n if (object.headers.type) headers.set(\"content-type\", object.headers.type);\n if (object.headers.disposition) headers.set(\"content-disposition\", object.headers.disposition);\n for (const [name, value] of Object.entries(object.headers.metadata)) {\n headers.set(`${META_PREFIX}${name}`, value);\n }\n if (object.partCount) headers.set(\"x-amz-mp-parts-count\", String(object.partCount));\n return headers;\n}\n\n// The types R2 compressed in \"HEAD and compression\" (r2-spike-findings.md). Every other type is left alone, as the\n// measured binary types and text/csv were.\nconst COMPRESSED_TYPES = new Set([\n \"text/plain\",\n \"text/html\",\n \"text/markdown\",\n \"application/json\",\n \"application/javascript\",\n \"application/xml\",\n \"image/svg+xml\",\n \"font/ttf\",\n \"application/wasm\",\n]);\nconst SMALLEST_COMPRESSED = 50;\n\n/**\n * R2 answers HEAD of a compressible object of 50 bytes or more with `content-encoding: gzip` and no `content-length`\n * unless the request asks for `identity`. A request without the header counts as offering gzip, as it reaches R2 from\n * Node's and Bun's fetch, which add `accept-encoding: gzip, …` when the caller sets none.\n */\nfunction compressedHead(object: StoredObject, request: Headers, headers: Headers): Headers {\n const type = object.headers.type?.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n const wanted = request.get(\"accept-encoding\")?.trim().toLowerCase();\n if (!COMPRESSED_TYPES.has(type) || object.body.length < SMALLEST_COMPRESSED || wanted === \"identity\") return headers;\n headers.delete(\"content-length\");\n headers.set(\"content-encoding\", \"gzip\");\n return headers;\n}\n\nfunction bodyResponse(object: StoredObject, rangeHeader: string | null, headers: Headers): Response {\n // Only closed ranges (bytes=a-b) are served. Open-ended and suffix forms are ignored and answer the whole object,\n // which RFC 9110 allows; the driver validates and sends closed ranges only.\n const range = /^bytes=(\\d+)-(\\d+)$/.exec(rangeHeader ?? \"\");\n if (!range) return new Response(object.body, { status: 200, headers });\n const start = Number(range[1]);\n if (start >= object.body.length || Number(range[2]) < start) {\n return errorResponse(416, \"InvalidRange\", \"The requested range is not satisfiable.\");\n }\n const end = Math.min(Number(range[2]), object.body.length - 1);\n const slice = object.body.subarray(start, end + 1);\n headers.set(\"content-range\", `bytes ${start}-${end}/${object.body.length}`);\n headers.set(\"content-length\", String(slice.length));\n return new Response(slice, { status: 206, headers });\n}\n\nexport function getObject(bucket: FakeBucket, { key, method, headers, query }: FakeRequest): Response {\n const object = bucket.objects.get(key);\n if (!object) {\n return method === \"HEAD\"\n ? new Response(null, { status: 404 })\n : errorResponse(404, \"NoSuchKey\", \"The specified key does not exist.\");\n }\n const responseHeaders = objectHeaders(object);\n if (method === \"HEAD\") {\n return new Response(null, { status: 200, headers: compressedHead(object, headers, responseHeaders) });\n }\n // S3's documented GetObject override; real R2 is checked by the contract suite on every backend.\n const disposition = query.get(\"response-content-disposition\");\n if (disposition !== null) responseHeaders.set(\"content-disposition\", disposition);\n return bodyResponse(object, headers.get(\"range\"), responseHeaders);\n}\n\nexport function deleteObject(bucket: FakeBucket, { key }: FakeRequest): Response {\n bucket.objects.delete(key);\n return new Response(null, { status: 204 });\n}\n\nexport function listObjects(bucket: FakeBucket, { query }: FakeRequest): Response {\n const prefix = query.get(\"prefix\") ?? \"\";\n const token = query.get(\"continuation-token\");\n const after = token === null ? \"\" : bucket.listTokens.get(token);\n if (after === undefined) return errorResponse(400, \"InvalidArgument\", \"The continuation token is not valid.\");\n const max = Math.min(Number(query.get(\"max-keys\") ?? MAX_LIST_PAGE), MAX_LIST_PAGE);\n const matching = Array.from(bucket.objects)\n .filter(([key]) => key.startsWith(prefix) && (after === \"\" || compareKeys(key, after) > 0))\n .sort(([a], [b]) => compareKeys(a, b));\n const page = matching.slice(0, max);\n const truncated = matching.length > max;\n const contents = page\n .map(\n ([key, object]) =>\n `<Contents><Key>${escapeXml(key)}</Key><Size>${object.body.length}</Size><ETag>\"${object.etag}\"</ETag><LastModified>${object.uploadedAt.toISOString()}</LastModified></Contents>`,\n )\n .join(\"\");\n const nextToken = `fake-token-${bucket.listTokens.size + 1}`;\n if (truncated) bucket.listTokens.set(nextToken, page.at(-1)?.[0] ?? \"\");\n const next = truncated ? `<NextContinuationToken>${nextToken}</NextContinuationToken>` : \"\";\n return xmlResponse(`<ListBucketResult><IsTruncated>${truncated}</IsTruncated>${next}${contents}</ListBucketResult>`);\n}\n","// Signature checks of the fake R2. They re-sign each request with cloudrop's own signer, so they prove R2's rules\n// (signed headers, expiry, clock skew), never the signer itself.\n\nimport { R2_RULES } from \"../../rules.ts\";\nimport { presignUrl, sha256Hex, signRequest, UNSIGNED_PAYLOAD } from \"../../storage/sigv4.ts\";\nimport { type Bytes, type FakeBucket, META_PREFIX } from \"./bucket.ts\";\nimport { clockSkewed, errorResponse } from \"./responses.ts\";\n\n// S3 rejects a request dated further ahead than this; the spike measured 30 minutes ahead (Q7).\nconst MAX_CLOCK_SKEW_MS = 15 * 60 * 1000;\n// Headers the signer adds itself, so they are not read back from the request.\nconst PRESIGNED_SKIPPED = [\"host\"];\nconst HEADER_SIGNED_SKIPPED = [\"host\", \"x-amz-date\", \"x-amz-content-sha256\"];\n\nconst signatureMismatch = (): Response =>\n errorResponse(403, \"SignatureDoesNotMatch\", \"The request signature does not match.\");\n\nfunction parseAmzDate(value: string): Date {\n return new Date(\n `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}T${value.slice(9, 11)}:${value.slice(11, 13)}:${value.slice(13, 15)}Z`,\n );\n}\n\n// The signer canonicalises from URLSearchParams, which reads \"+\" as a space. S3 reads the query as written, where \"+\"\n// is a literal plus, so a request whose query differs from the signed one only in encoding must fail the signature.\n// Rebuilding the pairs with decodeURIComponent alone makes the signer see the query the way S3 does.\nfunction queryAsWritten(url: URL): URL {\n const params = new URLSearchParams();\n for (const pair of url.search.slice(1).split(\"&\")) {\n if (pair === \"\") continue;\n const at = pair.indexOf(\"=\");\n params.append(\n decodeURIComponent(at < 0 ? pair : pair.slice(0, at)),\n at < 0 ? \"\" : decodeURIComponent(pair.slice(at + 1)),\n );\n }\n const rebuilt = new URL(url);\n rebuilt.search = params.toString();\n return rebuilt;\n}\n\n// A signed content-length is the body's real length: fetch derives the header from the body, so the fake does too.\nfunction signedHeaderValue(request: Request, name: string, body: Bytes): string | null {\n return name === \"content-length\" ? String(body.length) : request.headers.get(name);\n}\n\nfunction collectSignedHeaders(\n request: Request,\n names: string[],\n body: Bytes,\n skipped: string[],\n): Record<string, string> | Response {\n const headers: Record<string, string> = {};\n for (const name of names) {\n if (skipped.includes(name)) continue;\n const value = signedHeaderValue(request, name, body);\n if (value === null) return errorResponse(403, \"SignatureDoesNotMatch\", `Signed header ${name} is missing.`);\n headers[name] = value;\n }\n return headers;\n}\n\nfunction presignedWindow(query: URLSearchParams, now: () => Date): { signedAt: Date; expires: number } | Response {\n const signedAt = parseAmzDate(query.get(\"X-Amz-Date\") ?? \"\");\n const expires = Number(query.get(\"X-Amz-Expires\"));\n if (Number.isNaN(signedAt.getTime())) {\n return errorResponse(400, \"AuthorizationQueryParametersError\", \"X-Amz-Date is missing or malformed.\");\n }\n if (!Number.isInteger(expires) || expires < 1 || expires > R2_RULES.maxPresignSeconds) {\n return errorResponse(400, \"InvalidArgument\", \"X-Amz-Expires must be between 1 and 604800 seconds.\");\n }\n if (signedAt.getTime() - now().getTime() > MAX_CLOCK_SKEW_MS) return clockSkewed();\n if (now().getTime() > signedAt.getTime() + expires * 1000) {\n return errorResponse(403, \"ExpiredRequest\", \"Request has expired.\");\n }\n return { signedAt, expires };\n}\n\n// Measured on real R2 for a presigned PUT only (live lane, 2026-11-15, spike row 18): an x-amz-meta-* header the\n// URL did not sign fails the signature. Other methods were not measured, so the fake does not assert it for them.\nfunction unsignedMetadata(request: Request, signedNames: string[]): Response | null {\n if (request.method !== \"PUT\") return null;\n const name = [...request.headers.keys()].find(\n (header) => header.startsWith(META_PREFIX) && !signedNames.includes(header),\n );\n return name ? errorResponse(403, \"SignatureDoesNotMatch\", `Header ${name} is not signed.`) : null;\n}\n\nfunction withoutSignature(url: URL): URL {\n const unsigned = new URL(url);\n for (const name of Array.from(unsigned.searchParams.keys())) {\n if (name.startsWith(\"X-Amz-\")) unsigned.searchParams.delete(name);\n }\n return unsigned;\n}\n\nasync function verifyPresigned(bucket: FakeBucket, request: Request, url: URL, body: Bytes): Promise<Response | null> {\n const query = url.searchParams;\n const window = presignedWindow(query, bucket.now);\n if (window instanceof Response) return window;\n const signedNames = (query.get(\"X-Amz-SignedHeaders\") ?? \"\").split(\";\");\n const headers = collectSignedHeaders(request, signedNames, body, PRESIGNED_SKIPPED);\n if (headers instanceof Response) return headers;\n const unsigned = unsignedMetadata(request, signedNames);\n if (unsigned) return unsigned;\n const expected = await presignUrl({\n method: request.method,\n url: withoutSignature(url),\n headers,\n credentials: bucket.credentials,\n region: (query.get(\"X-Amz-Credential\") ?? \"\").split(\"/\")[2] ?? \"\",\n date: window.signedAt,\n expiresIn: window.expires,\n });\n return expected.searchParams.get(\"X-Amz-Signature\") === query.get(\"X-Amz-Signature\") ? null : signatureMismatch();\n}\n\nasync function verifyHeaderSigned(\n bucket: FakeBucket,\n request: Request,\n url: URL,\n body: Bytes,\n): Promise<Response | null> {\n const authorization = request.headers.get(\"authorization\");\n if (!authorization) return errorResponse(403, \"AccessDenied\", \"The request is not signed.\");\n const signedAt = parseAmzDate(request.headers.get(\"x-amz-date\") ?? \"\");\n if (Number.isNaN(signedAt.getTime())) {\n return errorResponse(403, \"SignatureDoesNotMatch\", \"X-Amz-Date is missing or malformed.\");\n }\n // A header-signed request has no expiry, so both a stale and a future date are skew.\n if (Math.abs(signedAt.getTime() - bucket.now().getTime()) > MAX_CLOCK_SKEW_MS) return clockSkewed();\n const payloadHash = request.headers.get(\"x-amz-content-sha256\") ?? \"\";\n if (payloadHash !== UNSIGNED_PAYLOAD && payloadHash !== (await sha256Hex(body))) {\n return errorResponse(400, \"XAmzContentSHA256Mismatch\", \"The payload hash does not match the body.\");\n }\n const signedNames = /SignedHeaders=([^,]+)/.exec(authorization)?.[1]?.split(\";\") ?? [];\n const headers = collectSignedHeaders(request, signedNames, body, HEADER_SIGNED_SKIPPED);\n if (headers instanceof Response) return headers;\n const expected = await signRequest({\n method: request.method,\n url,\n headers,\n credentials: bucket.credentials,\n region: /Credential=[^/]+\\/\\d{8}\\/([^/]+)\\//.exec(authorization)?.[1] ?? \"\",\n date: signedAt,\n payloadHash,\n });\n return expected.authorization === authorization ? null : signatureMismatch();\n}\n\n/** Checks a presigned or header-signed request the way R2 does; `null` means it may proceed. */\nexport async function verifySignature(\n bucket: FakeBucket,\n request: Request,\n url: URL,\n body: Bytes,\n): Promise<Response | null> {\n let writtenUrl: URL;\n try {\n writtenUrl = queryAsWritten(url);\n } catch {\n return errorResponse(400, \"InvalidURI\", \"The query string is not valid percent-encoding.\");\n }\n return url.searchParams.has(\"X-Amz-Signature\")\n ? verifyPresigned(bucket, request, writtenUrl, body)\n : verifyHeaderSigned(bucket, request, writtenUrl, body);\n}\n","// In-process fake of the R2 S3 API with the behaviour measured on real R2 (docs/research/r2-spike-findings.md).\n// It re-signs requests with cloudrop's own signer, so it proves R2's rules (signed headers, expiry, part sizes),\n// never the signer itself: sigv4.test.ts (AWS vectors, aws4fetch) and the RustFS, Wrangler and R2 lanes do that.\n\nimport type { FetchLike } from \"../storage/driver.ts\";\nimport type { Credentials } from \"../storage/sigv4.ts\";\nimport type { Bytes, FakeBucket, FakeRequest, StoredObject } from \"./fake-r2/bucket.ts\";\nimport { bucketConfig, copy, putBucketConfig } from \"./fake-r2/copy.ts\";\nimport { abortUpload, completeUpload, createUpload, listParts, uploadPart } from \"./fake-r2/multipart.ts\";\nimport { deleteObject, getObject, listObjects, putObject } from \"./fake-r2/objects.ts\";\nimport { errorResponse } from \"./fake-r2/responses.ts\";\nimport { verifySignature } from \"./fake-r2/signature.ts\";\n\nexport interface FakeR2Options {\n bucket: string;\n credentials: Credentials;\n now?: () => Date;\n /**\n * The CORS and lifecycle XML the bucket serves; a missing entry answers 404 as a bucket without that configuration.\n * Without this option, both reads answer 403 AccessDenied, as they do for an R2 object token (spike Q8), and so do\n * both writes. A write replaces the fake's copy of the entry, never the object passed here.\n */\n bucketConfig?: { cors?: string; lifecycle?: string };\n}\n\nexport interface FakeR2 {\n fetch: FetchLike;\n /** Multipart uploads created and neither completed nor aborted. */\n pendingUploads(): number;\n /** The object stored under `key`, as the bucket holds it: read it, never change it. */\n object(key: string): StoredObject | undefined;\n /** Every stored key, sorted. */\n keys(): string[];\n}\n\ninterface Route {\n matches(request: FakeRequest): boolean;\n run(bucket: FakeBucket, request: FakeRequest): Response | Promise<Response>;\n}\n\nconst isBucketGet = (request: FakeRequest): boolean => request.method === \"GET\" && request.key === \"\";\nconst isBucketPut = (request: FakeRequest): boolean => request.method === \"PUT\" && request.key === \"\";\n\n// The first route that matches answers, so the order is part of the behaviour: a PUT with x-amz-copy-source is a copy\n// before it is a part or an object, and a request naming an upload is a multipart call before it is an object call.\nconst ROUTES: Route[] = [\n { matches: (r) => isBucketGet(r) && r.query.get(\"list-type\") === \"2\", run: listObjects },\n { matches: (r) => isBucketGet(r) && r.query.has(\"cors\"), run: (bucket) => bucketConfig(bucket, \"cors\") },\n { matches: (r) => isBucketGet(r) && r.query.has(\"lifecycle\"), run: (bucket) => bucketConfig(bucket, \"lifecycle\") },\n { matches: (r) => isBucketPut(r) && r.query.has(\"cors\"), run: (bucket, r) => putBucketConfig(bucket, \"cors\", r) },\n {\n matches: (r) => isBucketPut(r) && r.query.has(\"lifecycle\"),\n run: (bucket, r) => putBucketConfig(bucket, \"lifecycle\", r),\n },\n { matches: (r) => r.method === \"POST\" && r.query.has(\"uploads\"), run: createUpload },\n { matches: (r) => r.method === \"PUT\" && r.headers.has(\"x-amz-copy-source\"), run: copy },\n { matches: (r) => r.method === \"PUT\" && r.query.has(\"uploadId\"), run: uploadPart },\n { matches: (r) => r.method === \"POST\" && r.query.has(\"uploadId\"), run: completeUpload },\n { matches: (r) => r.method === \"GET\" && r.query.has(\"uploadId\"), run: listParts },\n { matches: (r) => r.method === \"DELETE\" && r.query.has(\"uploadId\"), run: abortUpload },\n { matches: (r) => r.method === \"PUT\", run: putObject },\n { matches: (r) => r.method === \"GET\" || r.method === \"HEAD\", run: getObject },\n { matches: (r) => r.method === \"DELETE\", run: deleteObject },\n];\n\nexport function createFakeR2(options: FakeR2Options): FakeR2 {\n const bucket: FakeBucket = {\n name: options.bucket,\n credentials: options.credentials,\n now: options.now ?? (() => new Date()),\n config: options.bucketConfig && { ...options.bucketConfig },\n objects: new Map(),\n uploads: new Map(),\n listTokens: new Map(),\n uploadCounter: 0,\n };\n\n async function handle(request: Request): Promise<Response> {\n const answer = await route(request);\n // R2 dates every answer, and an answer to HEAD has no body, so a refused HEAD carries no S3 error code (measured\n // 2026-11-21: r2-spike-findings.md, \"Upload protocol edge cases\").\n const headers = new Headers(answer.headers);\n headers.set(\"date\", bucket.now().toUTCString());\n return new Response(request.method === \"HEAD\" ? null : answer.body, { status: answer.status, headers });\n }\n\n async function route(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const [, bucketSegment = \"\", ...keySegments] = url.pathname.split(\"/\");\n if (decodeURIComponent(bucketSegment) !== bucket.name) {\n return errorResponse(404, \"NoSuchBucket\", \"The specified bucket does not exist.\");\n }\n const key = keySegments.map(decodeURIComponent).join(\"/\");\n const body: Bytes = new Uint8Array(await request.arrayBuffer());\n const denied = await verifySignature(bucket, request, url, body);\n if (denied) return denied;\n\n const verified: FakeRequest = {\n method: request.method,\n key,\n query: url.searchParams,\n headers: request.headers,\n body,\n };\n const matched = ROUTES.find((candidate) => candidate.matches(verified));\n if (matched) return matched.run(bucket, verified);\n return errorResponse(501, \"NotImplemented\", `${request.method} is not implemented by the fake.`);\n }\n\n return {\n fetch: (input, init) => handle(new Request(input, init)),\n pendingUploads: () => bucket.uploads.size,\n object: (key) => bucket.objects.get(key),\n keys: () => [...bucket.objects.keys()].sort(),\n };\n}\n","// The memory store's methods that only read: rows as records, and the keyset pages of `stale`, `list` and `owners`.\n\nimport type { CloudropStore, FileRecord, FileStatus } from \"../server/store.ts\";\nimport type { MemoryTables } from \"./memory-store-methods.ts\";\nimport type { RawFileRow } from \"./store-rows.ts\";\n\ntype ReadMethods = Pick<CloudropStore<never>, \"get\" | \"stale\" | \"list\" | \"owners\">;\n\nconst CLEANUP: ReadonlySet<FileStatus> = new Set([\"aborted\", \"rejected\", \"failed\", \"expired\", \"deleted\"]);\n\nexport function toRecord(row: RawFileRow): FileRecord {\n const { claim: _claim, updatedAt: _updatedAt, requestKey: _requestKey, ...record } = structuredClone(row);\n return record;\n}\n\n/** A keyset page of `rows`, already sorted by `sortKey`: the rows after `cursor`, and the cursor of the next page. */\nfunction page<T>(rows: T[], sortKey: (row: T) => string, cursor: string | null, limit: number) {\n const after = cursor === null ? rows : rows.filter((row) => sortKey(row) > cursor);\n const records = after.slice(0, limit);\n const last = records.at(-1);\n return { records, cursor: after.length > limit && last ? sortKey(last) : null };\n}\n\n// Fixed-width milliseconds, so the cursor's string order is the time order (until the year 2286).\nconst timeKey = (time: Date | null, id: string): string => `${String(time?.getTime() ?? 0).padStart(13, \"0\")}:${id}`;\n\n/** Newest first: `created_at`, then id, both descending. */\nconst newestFirst = (a: RawFileRow, b: RawFileRow): number =>\n b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);\n\n/** Rows strictly after a `list` cursor, `<milliseconds>:<id>`, in newest-first order. */\nfunction listedAfter(cursor: string): (row: RawFileRow) => boolean {\n const split = cursor.indexOf(\":\");\n const time = Number(cursor.slice(0, split));\n const id = cursor.slice(split + 1);\n return (row) => row.createdAt.getTime() < time || (row.createdAt.getTime() === time && row.id < id);\n}\n\nexport function readMethods({ files, usage }: MemoryTables): ReadMethods {\n return {\n get: async (id) => {\n const row = files.get(id);\n return row ? toRecord(row) : null;\n },\n\n stale: async ({ kind, before, claimedBefore, limit, cursor }) => {\n const cutoff = before.getTime();\n const isWork =\n kind === \"expire\"\n ? (row: RawFileRow) =>\n row.expiresAt.getTime() < cutoff &&\n (row.status === \"pending\" ||\n (row.status === \"completing\" && (row.claimedAt?.getTime() ?? 0) < claimedBefore.getTime()))\n : (row: RawFileRow) =>\n CLEANUP.has(row.status) && row.cleanedAt === null && (row.endedAt?.getTime() ?? 0) < cutoff;\n const sortKey = (row: RawFileRow) => timeKey(kind === \"expire\" ? row.expiresAt : row.endedAt, row.id);\n const rows = [...files.values()].filter(isWork).sort((a, b) => (sortKey(a) < sortKey(b) ? -1 : 1));\n const found = page(rows, sortKey, cursor, limit);\n return { records: found.records.map(toRecord), cursor: found.cursor };\n },\n\n list: async ({ owner, statuses, route, limit, cursor }) => {\n const after = cursor === null ? () => true : listedAfter(cursor);\n const rows = [...files.values()]\n .filter(\n (row) => row.owner === owner && statuses.includes(row.status) && (route === null || row.route === route),\n )\n .filter(after)\n .sort(newestFirst);\n const kept = rows.slice(0, limit);\n const last = kept.at(-1);\n const next = rows.length > limit && last ? `${last.createdAt.getTime()}:${last.id}` : null;\n return { records: kept.map(toRecord), cursor: next };\n },\n\n owners: async (cursor, limit) => {\n const found = page([...usage.keys()].sort(), (owner) => owner, cursor, limit);\n return { owners: found.records, cursor: found.cursor };\n },\n };\n}\n","// The memory store's methods over its two maps, one per table. Each writing method runs inside `atomic`, which records\n// every row it writes so a failure can undo them (memory-store.ts).\n\nimport type { ClaimOutcome, CloudropStore, Completion, FileStatus, OwnerUsage, Transition } from \"../server/store.ts\";\nimport { readMethods, toRecord } from \"./memory-store-reads.ts\";\nimport type { RawFileRow, RawUsageRow } from \"./store-rows.ts\";\n\nexport interface MemoryTables {\n files: Map<string, RawFileRow>;\n usage: Map<string, RawUsageRow>;\n}\n\nexport interface Write {\n file(row: RawFileRow): void;\n usage(row: RawUsageRow): void;\n}\n\ntype Atomic = <T>(method: string, body: (write: Write) => T) => Promise<T>;\ntype Methods = Omit<CloudropStore<never>, \"transaction\">;\n\nconst ZERO: OwnerUsage = { reservedBytes: 0, activeBytes: 0, files: 0 };\nconst RESERVING: ReadonlySet<FileStatus> = new Set([\"pending\", \"completing\"]);\n\n/** An owner's counters as its rows say they should be. */\nfunction countRows(rows: Iterable<RawFileRow>, owner: string): OwnerUsage {\n const counted = { ...ZERO };\n for (const row of rows) {\n if (row.owner !== owner) continue;\n if (RESERVING.has(row.status)) counted.reservedBytes += row.size;\n if (row.status === \"completed\") {\n counted.activeBytes += row.size;\n counted.files += 1;\n }\n }\n return counted;\n}\n\nexport function storeMethods(tables: MemoryTables, atomic: Atomic): Methods {\n const { files, usage } = tables;\n const countsOf = (owner: string): OwnerUsage => {\n const row = usage.get(owner);\n return row ? { reservedBytes: row.reservedBytes, activeBytes: row.activeBytes, files: row.files } : { ...ZERO };\n };\n\n /** Adds `delta` to an owner's counters in the same unit as the status change; rows without an owner count nowhere. */\n function adjust(write: Write, owner: string | null, delta: Partial<OwnerUsage>, now: Date): void {\n // Nothing to move (an owner-less row, or leaving an ended status): the usage row is not written at all.\n if (owner === null || Object.keys(delta).length === 0) return;\n const counts = countsOf(owner);\n write.usage({\n owner,\n reservedBytes: counts.reservedBytes + (delta.reservedBytes ?? 0),\n activeBytes: counts.activeBytes + (delta.activeBytes ?? 0),\n files: counts.files + (delta.files ?? 0),\n updatedAt: now,\n });\n }\n\n /** What leaving `from` takes off the owner's counters. */\n const releaseFrom = (from: FileStatus, size: number): Partial<OwnerUsage> => {\n if (RESERVING.has(from)) return { reservedBytes: -size };\n return from === \"completed\" ? { activeBytes: -size, files: -1 } : {};\n };\n\n const unchanged = (id: string): Transition => {\n const row = files.get(id);\n return { changed: false, record: row ? toRecord(row) : null };\n };\n\n return {\n ...readMethods(tables),\n reserve: ({ owner, limit, expiresAt, requestKey, files: accepted }, now) =>\n atomic(\"reserve\", (write) => {\n if (accepted.length === 0) return [];\n // A retry of a request whose answer was lost: its earlier attempt's pending rows end first, freeing their\n // bytes.\n const routes = new Set(accepted.map((file) => file.route));\n const superseded =\n requestKey === null\n ? []\n : [...files.values()].filter(\n (row) =>\n row.requestKey === requestKey &&\n row.owner === owner &&\n routes.has(row.route) &&\n row.status === \"pending\",\n );\n for (const row of superseded) {\n write.file({ ...row, status: \"aborted\", endedAt: now, updatedAt: now });\n adjust(write, owner, { reservedBytes: -row.size }, now);\n }\n return accepted.map((file) => {\n if (owner !== null && limit !== null) {\n const { reservedBytes, activeBytes } = countsOf(owner);\n if (reservedBytes + activeBytes + file.size > limit) return \"over-quota\";\n }\n if (files.has(file.id)) throw new Error(`A file row with the id \"${file.id}\" already exists.`);\n write.file({\n ...file,\n owner,\n status: \"pending\",\n uploadId: null,\n result: null,\n claim: null,\n claimedAt: null,\n expiresAt,\n createdAt: now,\n updatedAt: now,\n completedAt: null,\n endedAt: null,\n cleanedAt: null,\n requestKey,\n });\n adjust(write, owner, { reservedBytes: file.size }, now);\n return \"reserved\";\n });\n }),\n\n attach: (id, uploadId, now) =>\n atomic(\"attach\", (write) => {\n const row = files.get(id);\n if (row?.status !== \"pending\" || (row.uploadId !== null && row.uploadId !== uploadId)) return false;\n write.file({ ...row, uploadId, updatedAt: now });\n return true;\n }),\n\n claim: (id, claim, now, leaseMs) =>\n atomic(\"claim\", (write): ClaimOutcome => {\n const row = files.get(id);\n if (!row) return { kind: \"missing\" };\n if (row.status === \"completed\") return { kind: \"completed\", record: toRecord(row) };\n const leaseOver = (row.claimedAt?.getTime() ?? 0) < now.getTime() - leaseMs;\n if (row.status === \"pending\" || (row.status === \"completing\" && leaseOver)) {\n write.file({ ...row, status: \"completing\", claim, claimedAt: now, updatedAt: now });\n return { kind: \"claimed\" };\n }\n return row.status === \"completing\" ? { kind: \"busy\" } : { kind: \"ended\", record: toRecord(row) };\n }),\n\n release: (id, claim, now) =>\n atomic(\"release\", (write) => {\n const row = files.get(id);\n if (row?.status !== \"completing\" || row.claim !== claim) return false;\n write.file({ ...row, status: \"pending\", claim: null, claimedAt: null, updatedAt: now });\n return true;\n }),\n\n complete: (id, claim, result, now, options) =>\n atomic(\"complete\", (write): Completion => {\n const row = files.get(id);\n if (row?.status !== \"completing\" || row.claim !== claim) return { ...unchanged(id), replaced: [] };\n const replaced =\n options?.replace && row.owner !== null\n ? [...files.values()].filter(\n (other) =>\n other.owner === row.owner &&\n other.route === row.route &&\n other.status === \"completed\" &&\n other.id !== id,\n )\n : [];\n const deleted = replaced.map(\n (other): RawFileRow => ({ ...other, status: \"deleted\", endedAt: now, updatedAt: now }),\n );\n for (const other of deleted) write.file(other);\n const done: RawFileRow = { ...row, status: \"completed\", result, completedAt: now, updatedAt: now };\n write.file(done);\n const freed = replaced.reduce((sum, other) => sum + other.size, 0);\n const delta = { reservedBytes: -row.size, activeBytes: row.size - freed, files: 1 - replaced.length };\n adjust(write, row.owner, delta, now);\n return { changed: true, record: toRecord(done), replaced: deleted.map(toRecord) };\n }),\n\n end: (id, from, to, now, options) =>\n atomic(\"end\", (write): Transition => {\n const row = files.get(id);\n if (row?.status !== from) return unchanged(id);\n const cleanedAt = options?.cleaned ? now : row.cleanedAt;\n const ended: RawFileRow = { ...row, status: to, endedAt: now, cleanedAt, updatedAt: now };\n write.file(ended);\n adjust(write, row.owner, releaseFrom(from, row.size), now);\n return { changed: true, record: toRecord(ended) };\n }),\n\n revoke: (owner, now) =>\n atomic(\"revoke\", (write) => {\n const revoked = [...files.values()].filter((row) => row.owner === owner && row.status === \"pending\");\n for (const row of revoked) {\n write.file({ ...row, status: \"aborted\", endedAt: now, updatedAt: now });\n adjust(write, owner, { reservedBytes: -row.size }, now);\n }\n return revoked.length;\n }),\n\n cleaned: (id, now) =>\n atomic(\"cleaned\", (write) => {\n const row = files.get(id);\n if (row && row.cleanedAt === null) write.file({ ...row, cleanedAt: now, updatedAt: now });\n }),\n\n usage: async (owner) => countsOf(owner),\n\n reconcile: (owner) =>\n atomic(\"reconcile\", (write) => {\n const counted = countRows(files.values(), owner);\n const current = countsOf(owner);\n const same = (Object.keys(ZERO) as (keyof OwnerUsage)[]).every((name) => counted[name] === current[name]);\n // The interface passes no time, so the store's own clock stamps the row (fake timers move it in tests).\n if (!same) write.usage({ owner, ...counted, updatedAt: new Date() });\n return !same;\n }),\n };\n}\n","// An in-memory CloudropStore with the semantics the store contract demands of a database (spec M5 §4), so the handler's\n// store paths, its transactional one included, run in the unit lane. Each method runs synchronously between awaits, so\n// nothing interleaves inside it, and keeps an undo list so a failure, injected or real, leaves nothing written.\n\nimport type { CloudropStore } from \"../server/store.ts\";\nimport { type MemoryTables, storeMethods, type Write } from \"./memory-store-methods.ts\";\nimport type { RawFileRow, RawTables, RawUsageRow } from \"./store-rows.ts\";\n\n/** The transaction handle the memory store passes to `onComplete`. */\nexport interface MemoryTx {\n /** The store methods called through the transaction's store, in order. */\n readonly calls: readonly string[];\n /** Writes one app row (an entry of `appRows()`), rolled back with the transaction: an app's own table, through `tx`. */\n write(entry: string): void;\n}\n\n/** The writing methods a failure can be injected into. */\nexport type MemoryWrite =\n | \"reserve\"\n | \"attach\"\n | \"claim\"\n | \"release\"\n | \"complete\"\n | \"end\"\n | \"revoke\"\n | \"cleaned\"\n | \"reconcile\";\n\nexport interface MemoryStore extends CloudropStore<MemoryTx> {\n transaction: NonNullable<CloudropStore<MemoryTx>[\"transaction\"]>;\n /** The tables, read past the store. */\n readonly raw: RawTables;\n /**\n * Makes the next call of `method` throw once `afterWrites` of its row writes have been made (0: before any). The call\n * then undoes those writes, as a database rolls back a failed statement; later calls run normally.\n */\n injectFailure(method: MemoryWrite, afterWrites: number): void;\n /**\n * Makes the next write to the usage table fail, whichever method makes it; the call undoes what it wrote before. The\n * store contract's `injectFailure`, which a SQL lane implements with a one-shot trigger.\n */\n failNextUsageWrite(): void;\n /** The app rows committed through `tx.write`, in order. */\n appRows(): string[];\n}\n\ntype Undo = () => void;\n\nconst COUNTERS = [\"reservedBytes\", \"activeBytes\", \"files\"] as const;\n\n/**\n * Takes back one write to a usage row. A row nothing has rewritten since is restored as it was. A row a call outside\n * the transaction rewrote meanwhile keeps that call's change and loses only this write's: under a database the two\n * would have been ordered by the row's lock, and both of their changes would count.\n */\nfunction undoUsage(usage: Map<string, RawUsageRow>, stored: RawUsageRow, before: RawUsageRow | undefined): void {\n const current = usage.get(stored.owner);\n if (current === stored || current === undefined) {\n if (before) usage.set(stored.owner, before);\n else usage.delete(stored.owner);\n return;\n }\n const taken = { ...current };\n for (const counter of COUNTERS) taken[counter] -= stored[counter] - (before?.[counter] ?? 0);\n usage.set(stored.owner, taken);\n}\n\nexport function memoryStore(): MemoryStore {\n const tables: MemoryTables = { files: new Map(), usage: new Map() };\n const app: { entry: string }[] = [];\n let fault: { method: string; afterWrites: number } | null = null;\n let usageFault = false;\n\n /**\n * Runs one method as an atomic unit. Its writes are recorded in an undo list: on a throw they are undone; on success\n * they join `journal` when the call runs inside a transaction, so its rollback can undo them too.\n */\n function atomic<T>(method: string, journal: Undo[] | null, body: (write: Write) => T): Promise<T> {\n const armed = fault?.method === method ? fault : null;\n if (armed) fault = null;\n const undo: Undo[] = [];\n const checkFault = () => {\n if (armed && undo.length === armed.afterWrites) {\n throw new Error(`Injected failure in ${method} after ${armed.afterWrites} writes.`);\n }\n };\n const write: Write = {\n file(row) {\n checkFault();\n const before = tables.files.get(row.id);\n undo.push(() => (before ? tables.files.set(row.id, before) : tables.files.delete(row.id)));\n // A copy, so a caller that later changes the object or a Date it passed cannot change the stored row.\n tables.files.set(row.id, structuredClone(row));\n },\n usage(row) {\n if (usageFault) {\n usageFault = false;\n throw new Error(\"Injected failure writing the usage table.\");\n }\n checkFault();\n const before = tables.usage.get(row.owner);\n const stored = structuredClone(row);\n tables.usage.set(row.owner, stored);\n undo.push(() => undoUsage(tables.usage, stored, before));\n },\n };\n try {\n const result = body(write);\n journal?.push(...undo);\n return Promise.resolve(result);\n } catch (error) {\n for (const step of undo.toReversed()) step();\n return Promise.reject(error);\n }\n }\n\n const store = storeMethods(tables, (method, body) => atomic(method, null, body));\n\n async function transaction<T>(\n run: (tx: MemoryTx, store: Omit<CloudropStore<MemoryTx>, \"transaction\">) => Promise<T>,\n ): Promise<T> {\n const journal: Undo[] = [];\n const calls: string[] = [];\n const tx: MemoryTx = {\n calls,\n write(entry) {\n const row = { entry };\n app.push(row);\n journal.push(() => app.splice(app.indexOf(row), 1));\n },\n };\n const inner = storeMethods(tables, (method, body) => atomic(method, journal, body));\n // A recording view: each method's name, then the method. `get`, `usage` and the other reads are recorded too.\n const recorded = Object.fromEntries(\n Object.entries(inner).map(([name, method]) => [\n name,\n (...args: unknown[]) => {\n calls.push(name);\n return (method as (...args: unknown[]) => unknown)(...args);\n },\n ]),\n ) as typeof inner;\n try {\n return await run(tx, recorded);\n } catch (error) {\n // Undoes this transaction's writes row by row, newest first: writes made outside it to other rows survive, as\n // under a database, and so do outside changes to a usage row it also wrote (undoUsage). An outside write to a\n // files row it wrote would have waited for its lock instead; the rollback overwrites it.\n for (const step of journal.toReversed()) step();\n throw error;\n }\n }\n\n const sorted = <V>(map: Map<string, V>): V[] =>\n [...map.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([, row]) => structuredClone(row));\n\n return {\n ...store,\n transaction,\n raw: {\n files: async (): Promise<RawFileRow[]> => sorted(tables.files),\n usage: async (): Promise<RawUsageRow[]> => sorted(tables.usage),\n putUsage: async (row) => void tables.usage.set(row.owner, structuredClone(row)),\n deleteUsage: async (owner) => void tables.usage.delete(owner),\n },\n injectFailure(method, afterWrites) {\n fault = { method, afterWrites };\n },\n failNextUsageWrite() {\n usageFault = true;\n },\n appRows: () => app.map((row) => row.entry),\n };\n}\n","// The cloudrop/testing entry: an app tests its routes, its store and a whole upload in its own test runner, with no\n// bucket, browser or network (M9-T1). The build keeps the imports of ./index.ts and ./client.ts as imports of the\n// published entries (tsdown.config.ts), so this entry shares their code and classes and adds none to them (M9-T2).\n\nimport { type ClientOptions, type CloudropClient, createCloudropClient } from \"./client.ts\";\nimport {\n type Cloudrop,\n CloudropError,\n type CloudropStore,\n type FetchLike,\n type InferableCloudrop,\n type RouteCallbacks,\n type RouteFunction,\n r2,\n route,\n type StorageDriver,\n type TransactionalStore,\n} from \"./index.ts\";\nimport { createFakeR2 } from \"./testing/fake-r2.ts\";\nimport { memoryStore as createMemoryStore } from \"./testing/memory-store.ts\";\n\nexport interface TestBucketOptions {\n /** Where the bucket is served publicly, such as \"https://cdn.example.com\", as in `r2({ publicUrl })`. Default none. */\n publicUrl?: string;\n /**\n * The bucket's CORS configuration as S3 XML, for tests of `api.checkBucket`. Once `cors` or `lifecycle` is given, the\n * other one reads as not configured; with neither, both read as refused, as with an R2 object token (M9-T6).\n */\n cors?: string;\n /** The bucket's lifecycle configuration as S3 XML, for tests of `api.checkBucket`. */\n lifecycle?: string;\n}\n\n/** An object as the test bucket stores it. */\nexport interface TestObject {\n key: string;\n size: number;\n /** The stored Content-Type, or null. */\n type: string | null;\n /** The stored Content-Disposition, or null. */\n disposition: string | null;\n /** The `x-amz-meta-*` headers, without the prefix: `cloudrop-id` is the file's id. */\n metadata: Record<string, string>;\n /** How many parts a multipart upload stored it in; null for a single PUT. */\n parts: number | null;\n /** A copy of the stored bytes. */\n body: Uint8Array;\n uploadedAt: Date;\n}\n\n/** An in-process bucket that keeps R2's measured rules and checks every request's signature. */\nexport interface TestBucket {\n /** The driver to pass to `createCloudrop({ storage })`: `r2()` pointed at this bucket. */\n readonly storage: StorageDriver;\n /**\n * Reaches the bucket with a signed request, such as a URL from `api.getUrl`. A `publicUrl` is not served: read a\n * public file with `object(key)`.\n */\n readonly fetch: FetchLike;\n /** The object stored under `key`, or null. */\n object(key: string): TestObject | null;\n /** Every stored key, sorted. */\n keys(): string[];\n /** Multipart uploads started and neither completed nor aborted. */\n pendingUploads(): number;\n}\n\nexport interface TestClientOptions {\n /** The test bucket the server stores in: the client's presigned PUTs go there. */\n bucket: TestBucket;\n /**\n * Headers for every request to the server, never to the bucket: the session a browser's cookies would carry, such as\n * `{ cookie: \"session=alice\" }`, or a function that returns them before each request. `origin` is always the page's\n * own, `http://localhost`, as a browser sends it.\n */\n headers?: ClientOptions[\"headers\"];\n /** The server's `basePath`, a path without a trailing slash. Default \"/api/cloudrop\". */\n basePath?: string;\n}\n\n/** The bucket checks every signature with these, so they only need to agree with the driver's. */\nconst CREDENTIALS = { accessKeyId: \"cloudrop-test-key\", secretAccessKey: \"cloudrop-test-secret\" };\n/** The origin of the page the test client runs on, and of the server it reaches (M9-T4). */\nconst PAGE_ORIGIN = \"http://localhost\";\n// The brand createCloudrop reads to tie a route to its store; Symbol.for, so copies of cloudrop agree (server/route.ts).\nconst STORE = Symbol.for(\"cloudrop.store\");\n/** A path such as /api/cloudrop: no origin, trailing slash, query or fragment. */\nconst PATH = /^(?:\\/[^/?#\\s]+)+$/;\n\n/** A bucket for tests, with no network: pass `bucket.storage` to `createCloudrop`, then read what landed. */\nexport function testBucket(options?: TestBucketOptions | null): TestBucket {\n // null counts as no options, as createCloudrop reads its own.\n const { publicUrl, cors, lifecycle } = options ?? {};\n const bucketConfig = cors === undefined && lifecycle === undefined ? undefined : { cors, lifecycle };\n const fake = createFakeR2({ bucket: \"uploads\", credentials: CREDENTIALS, bucketConfig });\n return {\n storage: r2({ bucket: \"uploads\", accountId: \"0\".repeat(32), ...CREDENTIALS, publicUrl, fetch: fake.fetch }),\n fetch: fake.fetch,\n object(key) {\n const stored = fake.object(key);\n if (!stored) return null;\n const { body, headers } = stored;\n return {\n key,\n size: body.byteLength,\n type: headers.type ?? null,\n disposition: headers.disposition ?? null,\n metadata: { ...headers.metadata },\n parts: stored.partCount ?? null,\n body: body.slice(),\n uploadedAt: new Date(stored.uploadedAt),\n };\n },\n keys: fake.keys,\n pendingUploads: fake.pendingUploads,\n };\n}\n\n/**\n * The real `cloudrop/client` client, wired to `cloudrop.handler` and the test bucket in-process. Requests to the server\n * arrive as a same-origin page sends them; bucket PUTs go through fetch, never XMLHttpRequest, and nothing is kept\n * for resuming after a reload (M9-T4, M9-T5). Throws INVALID_CONFIG without a bucket or with a basePath that is not\n * a path.\n */\nexport function testClient<TCloudrop extends InferableCloudrop>(\n cloudrop: TCloudrop & Pick<Cloudrop, \"handler\">,\n options: TestClientOptions,\n): CloudropClient<TCloudrop> {\n const { bucket, headers, basePath = \"/api/cloudrop\" } = options ?? {};\n if (!bucket) {\n throw new CloudropError(\n \"INVALID_CONFIG\",\n \"testClient needs the test bucket the server stores in: testClient(cloudrop, { bucket }).\",\n );\n }\n if (typeof basePath !== \"string\" || !PATH.test(basePath)) {\n throw new CloudropError(\n \"INVALID_CONFIG\",\n 'basePath must be the path the server is mounted at, such as \"/api/cloudrop\", with no origin and no trailing slash.',\n );\n }\n const server = `${PAGE_ORIGIN}${basePath}`;\n const fetch = (url: string, init: RequestInit): Promise<Response> => {\n if (!url.startsWith(`${server}/`)) return bucket.fetch(url, init);\n // A browser sets Origin itself on every POST, and a page cannot change it.\n const sent = new Headers(init.headers);\n sent.set(\"origin\", PAGE_ORIGIN);\n return cloudrop.handler(new Request(url, { method: init.method, headers: sent, body: init.body }));\n };\n return createCloudropClient<TCloudrop>({ basePath: server, headers, fetch, persist: false });\n}\n\n/**\n * An in-memory database store with the guarantees of the shipped adapters, for tests of an app that uses `store`:\n * owners, `quota`, `afterComplete`, `replace` and the store's file API. With `{ transaction: true }` it has\n * `transaction` and `store.route`, like `sqlStore(executor, { transaction: true })`; its `tx` is undefined, since\n * there is no database to write through (M9-T7).\n */\nexport function memoryStore(options: { transaction: true }): TransactionalStore<undefined>;\nexport function memoryStore(options?: { transaction?: false } | null): CloudropStore;\nexport function memoryStore(options?: { transaction?: boolean } | null): CloudropStore<undefined>;\nexport function memoryStore(options?: { transaction?: boolean } | null): CloudropStore<undefined> {\n // The repository's own tests reach past the store (raw tables, injected failures); an app's test gets the store only.\n const {\n transaction,\n raw: _raw,\n injectFailure: _inject,\n failNextUsageWrite: _fail,\n appRows: _rows,\n ...methods\n } = createMemoryStore();\n if (!options?.transaction) return methods;\n const store = {\n ...methods,\n transaction: (run) => transaction((_tx, inner) => run(undefined, inner)),\n } as TransactionalStore<undefined>;\n // What routeFor (server/route.ts) does for the adapters, over the public route().\n store.route = ((policy, callbacks) => ({\n definition: { ...route(policy, callbacks as RouteCallbacks<object, unknown, unknown>).definition, [STORE]: store },\n })) as RouteFunction<{ tx: undefined }>;\n return store;\n}\n"],"mappings":";;;AAGA,MAAM,WAAmC;CAAE,KAAK;CAAK,IAAI;CAAK,IAAI;CAAK,MAAM;CAAK,MAAM;AAAI;AAC5F,MAAM,UAAkC;CAAE,KAAK;CAAQ,KAAK;CAAQ,KAAK;CAAS,MAAK;CAAU,KAAK;AAAS;AAE/G,SAAS,UAAU,MAAsB;CACvC,OAAO,KAAK,QAAQ,iDAAiD,OAAO,WAAmB;EAC7F,IAAI,CAAC,OAAO,WAAW,GAAG,GAAG,OAAO,SAAS,WAAW;EACxD,MAAM,YAAY,OAAO,OAAO,MAAM,OAAO,SAAS,OAAO,MAAM,CAAC,GAAG,EAAE,IAAI,OAAO,SAAS,OAAO,MAAM,CAAC,GAAG,EAAE;EAEhH,OAAO,OAAO,SAAS,SAAS,KAAK,aAAa,UAAW,OAAO,cAAc,SAAS,IAAI;CACjG,CAAC;AACH;AAOA,SAAgB,UAAU,KAAa,KAAuB;CAC5D,MAAM,UAAU,IAAI,OAAO,IAAI,IAAI,oCAAoC,IAAI,IAAI,GAAG;CAClF,OAAO,MAAM,KAAK,IAAI,SAAS,OAAO,IAAI,UAAU,MAAM,MAAM,EAAE;AACpE;AAMA,SAAgB,QAAQ,KAAa,KAAiC;CACpE,MAAM,QAAQ,UAAU,KAAK,GAAG,CAAC,CAAC;CAClC,OAAO,UAAU,KAAA,IAAY,KAAA,IAAY,UAAU,KAAK;AAC1D;AAYA,SAAgB,YAAY,OAAuB;CACjD,OAAO,MAAM,WAAW,MAAK,EAAE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S,KAAa,SAAyC;EACnE,IAAI,CAAC,IAAI,WAAW,GAAG,OAAO,EAAE,GAAG,OAAO,OAAO,MAAM,KAAK,IAAI;EAEhE,MAAM,OAAO,IAAI,QAAQ,KAAK,OAAO;EACrC,KAAK,IAAI,UAAU,WAAW;EAC9B,OAAO,SAAS,QAAQ,IAAI,QAAQ,KAAK;GAAE,QAAQ,KAAK;GAAQ,SAAS;GAAM,MAAM,KAAK;EAAK,CAAC,CAAC;CACnG;CACA,OAAO,qBAAgC;EAAE,UAAU;EAAQ;EAAS;EAAO,SAAS;CAAM,CAAC;AAC7F;AAWA,SAAgB,YAAY,SAAsE;CAEhG,MAAM,EACJ,aACA,KAAK,MACL,eAAe,SACf,oBAAoB,OACpB,SAAS,OACT,GAAG,YACDC,cAAkB;CACtB,IAAI,CAAC,SAAS,aAAa,OAAO;CAClC,MAAM,QAAQ;EACZ,GAAG;EACH,cAAc,QAAQ,aAAa,KAAK,UAAU,IAAI,KAAA,GAAW,KAAK,CAAC;CACzE;CAEA,MAAM,UAAU,QAAQ,eAAe,EACrC,YAAY;EAAE,GAAG,MAAM,QAAQ,SAAqD,CAAC,CAAC;GAAa,QAAQ;CAAM,EACnH;CACA,OAAO;AACT"}
package/docs/README.md ADDED
@@ -0,0 +1,30 @@
1
+ # cloudrop documentation
2
+
3
+ The guides for this version of cloudrop, as published. The project's history (decisions, research, plans) is in the
4
+ repository: https://github.com/vcode-sh/cloudrop/blob/main/docs/README.md.
5
+
6
+ ## Guides
7
+
8
+ For developers adding uploads to an app, in reading order:
9
+
10
+ 1. [Server](server.md): `createCloudrop`, storage drivers, routes and who may use them, the upload token,
11
+ mounting the handler in your framework, origins, and the `cloudrop.api` file operations.
12
+ 2. [Bucket setup](bucket-setup.md): the CORS and lifecycle rules for R2 and S3, credentials and permissions,
13
+ and what `checkBucket` reports. [The cloudrop command](command.md) checks the settings and the bucket
14
+ (`cloudrop doctor`) and adds the rules (`cloudrop setup`).
15
+ 3. [Client](client.md): `cloudrop/client` without React: uploading, progress, pause, retry, concurrency and
16
+ offline.
17
+ 4. [React](react.md): `useUpload` and `useResumable`, and how to build an upload UI on them.
18
+ 5. [Resume after reload](resume.md): how a large upload survives a reload or a closed tab.
19
+ 6. [Database store](store.md): a row per upload in your database, `onComplete` once, quotas, revocation and the
20
+ sweep.
21
+ 7. [Deployment](deployment.md): same-origin and cross-origin setups, cookies, proxies, building without secrets,
22
+ Cloudflare Workers.
23
+ 8. [Hono with better-auth and Drizzle](hono.md): a complete app, step by step, with a Vite SPA on another origin.
24
+ 9. [Testing your app](testing-your-app.md): `cloudrop/testing`, your routes, store and a whole upload in your
25
+ own tests, with no bucket, browser or network.
26
+
27
+ When something goes wrong:
28
+
29
+ - [Errors](errors.md): every error code, where it comes from and what to do.
30
+ - [Troubleshooting](troubleshooting.md): symptoms and their usual causes.
@@ -0,0 +1,226 @@
1
+ # Bucket setup
2
+
3
+ This page is for whoever sets up the bucket and its credentials. It covers what your bucket needs before browsers can
4
+ upload to it: the CORS rule, in R2's format and in the S3 format, the lifecycle rule that cleans up abandoned uploads,
5
+ the Wrangler commands that set both on R2 and the AWS CLI commands for any S3-compatible service, which credentials and
6
+ permissions cloudrop needs, and what `checkBucket` can and cannot report about all of this.
7
+
8
+ The [cloudrop command](command.md) does most of this for you: `npx cloudrop setup --origin <origin>` prints these rules
9
+ and commands for your origins, `--apply` adds the rules to the bucket and keeps every other rule, and
10
+ `npx cloudrop doctor --origin <origin>` checks the settings, the bucket and its rules.
11
+
12
+ The rule lists the origin of the **page** that uploads, not the origin of your API: the browser sends the bytes from
13
+ the page. With the page and the API on different origins, see [Deployment](deployment.md).
14
+
15
+ ## What any bucket needs
16
+
17
+ | Setting | Why |
18
+ | --- | --- |
19
+ | A CORS rule allowing `PUT` from your page's origin | Browsers upload to the bucket directly, from your page's origin. Without the rule, the browser blocks every upload. |
20
+ | The four headers cloudrop signs, in the rule's allowed headers | `content-type`, `content-disposition`, `if-none-match` and `x-amz-meta-cloudrop-id`. A preflight fails if one is missing. |
21
+ | `ETag` in the exposed headers | Only `checkBucket` needs it: its CORS check reports a problem without it. The client never reads `ETag`; the server gets part ETags from the bucket when it completes an upload. |
22
+ | `Retry-After` in the exposed headers (recommended) | Lets the client wait as long as the bucket asks after a `429` or `503`. |
23
+ | A lifecycle rule that aborts incomplete multipart uploads | Parts of an upload that never finished are removed instead of staying stored. |
24
+
25
+ Add your production origin and, for development, your local origin such as `http://localhost:5173`. `GET` and `HEAD`
26
+ in the examples below are for reading files back from a page; uploads need only `PUT`.
27
+
28
+ ### Why expose Retry-After
29
+
30
+ A browser hides every answer header the CORS rule does not expose. With `Retry-After` exposed, a retry after a `429` or
31
+ `503` waits at least as long as the bucket asks (at most 20 s). Without it, the client cannot read the header and waits
32
+ its own backoff alone: a random wait up to 0.5 s, then 1 s, 2 s and so on. R2 answers concurrent writes to one key with
33
+ `429` and `Retry-After: 5`, which a page cannot read when the rule omits it (measured 2026-11-16,
34
+ [findings](https://github.com/vcode-sh/cloudrop/blob/main/docs/research/r2-spike-findings.md#bad-checksum-gone-upload-and-throttling-from-a-browser-2026-11-16)).
35
+ Uploads work without it, and `checkBucket` does not ask for it.
36
+
37
+ ### Checksum headers
38
+
39
+ If you add a checksum header to uploads, such as `x-amz-checksum-crc32c`, add it to the allowed headers too. A rule that
40
+ misses any header a `PUT` carries blocks that `PUT`.
41
+
42
+ ## Set the CORS rule on R2
43
+
44
+ Setting CORS replaces the bucket's whole policy. Read the current rules first and keep any you still need (or let
45
+ `cloudrop setup --apply` merge them):
46
+
47
+ ```bash
48
+ wrangler r2 bucket cors list <bucket>
49
+ ```
50
+
51
+ Write the rules to `cors.json` in R2's format, a `rules` array:
52
+
53
+ ```json
54
+ {
55
+ "rules": [
56
+ {
57
+ "allowed": {
58
+ "origins": ["https://app.example.com", "http://localhost:5173"],
59
+ "methods": ["PUT", "GET", "HEAD"],
60
+ "headers": ["content-type", "content-disposition", "if-none-match", "x-amz-meta-cloudrop-id"]
61
+ },
62
+ "exposeHeaders": ["ETag", "Retry-After"],
63
+ "maxAgeSeconds": 3600
64
+ }
65
+ ]
66
+ }
67
+ ```
68
+
69
+ Then apply it:
70
+
71
+ ```bash
72
+ wrangler r2 bucket cors set <bucket> --file cors.json
73
+ ```
74
+
75
+ Wrangler needs to be signed in to your Cloudflare account. Pass `--jurisdiction eu` (or `fedramp`) for a bucket in a
76
+ jurisdiction. A change can take up to 30 seconds to apply, in rare cases.
77
+
78
+ ## Set the CORS rule on S3 and other services
79
+
80
+ The S3 format is a list of rules. It is the shape `examples/next` and cloudrop's R2 measurements use:
81
+
82
+ ```json
83
+ [
84
+ {
85
+ "AllowedOrigins": ["https://app.example.com", "http://localhost:5173"],
86
+ "AllowedMethods": ["PUT", "GET", "HEAD"],
87
+ "AllowedHeaders": ["content-type", "content-disposition", "if-none-match", "x-amz-meta-cloudrop-id"],
88
+ "ExposeHeaders": ["ETag", "Retry-After"],
89
+ "MaxAgeSeconds": 3600
90
+ }
91
+ ]
92
+ ```
93
+
94
+ AWS's `PutBucketCors` API and the AWS CLI wrap that list in `CORSRules`:
95
+
96
+ ```json
97
+ {
98
+ "CORSRules": [
99
+ {
100
+ "AllowedOrigins": ["https://app.example.com"],
101
+ "AllowedMethods": ["PUT", "GET", "HEAD"],
102
+ "AllowedHeaders": ["content-type", "content-disposition", "if-none-match", "x-amz-meta-cloudrop-id"],
103
+ "ExposeHeaders": ["ETag", "Retry-After"],
104
+ "MaxAgeSeconds": 3600
105
+ }
106
+ ]
107
+ }
108
+ ```
109
+
110
+ Wrangler refuses this `CORSRules` format: convert it to the `rules` format above for `wrangler r2 bucket cors set`.
111
+ To apply it with the AWS CLI, see [the next section](#set-both-rules-with-the-aws-cli).
112
+
113
+ ## Set both rules with the AWS CLI
114
+
115
+ The AWS CLI sets the CORS rule and the lifecycle rule on AWS S3 and on S3-compatible services that implement these S3
116
+ calls (checked on RustFS). For a service other than AWS, point it at the service with `--endpoint-url`. Save the
117
+ `CORSRules` document above as `cors-s3.json` (not the R2 `cors.json`, whose format differs), and this as
118
+ `lifecycle.json`:
119
+
120
+ ```json
121
+ {
122
+ "Rules": [
123
+ {
124
+ "ID": "abort-incomplete-uploads",
125
+ "Status": "Enabled",
126
+ "Filter": { "Prefix": "" },
127
+ "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 1 }
128
+ }
129
+ ]
130
+ }
131
+ ```
132
+
133
+ The empty prefix makes the rule apply to the whole bucket, which `checkBucket` requires. Then apply both:
134
+
135
+ ```bash
136
+ # AWS CLI v2 reads AWS_REGION; v1 reads only AWS_DEFAULT_REGION, so set both.
137
+ export AWS_ACCESS_KEY_ID=<access key id> AWS_SECRET_ACCESS_KEY=<secret access key>
138
+ export AWS_REGION=us-east-1 AWS_DEFAULT_REGION=us-east-1
139
+ ENDPOINT=http://127.0.0.1:9000 # your service's S3 endpoint; leave out --endpoint-url for AWS S3
140
+
141
+ aws s3api put-bucket-cors --bucket <bucket> --cors-configuration file://cors-s3.json --endpoint-url "$ENDPOINT"
142
+ aws s3api put-bucket-lifecycle-configuration --bucket <bucket> \
143
+ --lifecycle-configuration file://lifecycle.json --endpoint-url "$ENDPOINT"
144
+
145
+ # Read them back
146
+ aws s3api get-bucket-cors --bucket <bucket> --endpoint-url "$ENDPOINT"
147
+ aws s3api get-bucket-lifecycle-configuration --bucket <bucket> --endpoint-url "$ENDPOINT"
148
+ ```
149
+
150
+ Both commands replace the bucket's whole CORS or lifecycle configuration, so merge in any rules it already has. The
151
+ credentials need permission to change bucket settings, which upload credentials often lack. Use an admin key for this
152
+ step, not the key you give cloudrop. These commands were checked against RustFS, with `checkBucket` reporting both rules
153
+ `ok` afterwards.
154
+
155
+ ## Add the lifecycle rule
156
+
157
+ An upload that is never completed or aborted leaves its parts in the bucket. The client sends `/abort` when it can, but
158
+ a closed tab or a crash can leave parts behind, and so can an upload whose 24-hour token expired. A lifecycle rule that
159
+ aborts incomplete multipart uploads removes them.
160
+
161
+ On R2, new buckets get a 7-day rule by default. Check what yours has:
162
+
163
+ ```bash
164
+ wrangler r2 bucket lifecycle list <bucket>
165
+ ```
166
+
167
+ Add one if it is missing, for the whole bucket:
168
+
169
+ ```bash
170
+ wrangler r2 bucket lifecycle add <bucket> abort-incomplete-uploads --abort-multipart-days 1
171
+ ```
172
+
173
+ On S3 and other services, set it with [the AWS CLI](#set-both-rules-with-the-aws-cli).
174
+
175
+ `checkBucket` accepts any enabled rule that applies to the whole bucket (no prefix) and aborts incomplete multipart
176
+ uploads, whatever its number of days. The example's RustFS setup uses one day.
177
+
178
+ ## Credentials and permissions
179
+
180
+ The server needs credentials that can, in the bucket:
181
+
182
+ - write objects and run multipart uploads (create, upload parts, list parts, complete, abort), and sign upload URLs for
183
+ them;
184
+ - read object metadata (`HEAD`) and objects (for `api.getUrl`);
185
+ - delete objects (rejected and aborted uploads, `api.delete`, `api.deletePrefix`);
186
+ - list objects (`api.deletePrefix`).
187
+
188
+ On R2, an API token with **Object Read & Write** permission on the bucket does all of this; cloudrop's live tests run
189
+ with one. Create it in the Cloudflare dashboard under R2, then pass its access key ID and secret access key to `r2()` or
190
+ set `CLOUDROP_R2_ACCESS_KEY_ID` and `CLOUDROP_R2_SECRET_ACCESS_KEY`.
191
+
192
+ An Object Read & Write token cannot read the bucket's CORS or lifecycle settings (R2 answers `403 AccessDenied`), so
193
+ `checkBucket` reports those as `unknown`. Check them with Wrangler or in the dashboard instead.
194
+
195
+ The browser never sees any of these credentials: it gets only presigned URLs, each for one object, one method and 15
196
+ minutes.
197
+
198
+ ## What checkBucket can tell you
199
+
200
+ ```ts
201
+ const { data: report, error } = await cloudrop.api.checkBucket({ origins: ["https://app.example.com"] });
202
+ ```
203
+
204
+ | Check | `ok` when | Reported `unknown` when |
205
+ | --- | --- | --- |
206
+ | `cors` | Every origin may `PUT` with the four signed headers, and `ETag` is exposed. | The credentials may not read CORS (R2 object tokens), the storage cannot report it (Wrangler's local R2 answers `501`), or no origin was given. |
207
+ | `lifecycle` | An enabled rule for the whole bucket aborts incomplete multipart uploads. | The credentials may not read lifecycle rules, or the storage cannot report them. Origins do not matter here. |
208
+ | `publicAccess` | No private route stores files on a bucket with a `publicUrl`. | Never: this check reads only your configuration. |
209
+
210
+ What it does not check:
211
+
212
+ - `Retry-After` in the exposed headers;
213
+ - checksum headers you add;
214
+ - what an R2 admin read token would show: R2's answers to one have not been measured yet.
215
+
216
+ Any other storage failure fails the call with an error instead of a report.
217
+
218
+ In development (`NODE_ENV=development`, exactly), the handler's first request runs `checkBucket` once in the background
219
+ for its own origin and `trustedOrigins`, and logs a warning for each problem.
220
+
221
+ ## Local development
222
+
223
+ - **RustFS:** `bun run setup:rustfs` in [`examples/next`](https://github.com/vcode-sh/cloudrop/blob/main/examples/next/README.md#run-with-rustfs-the-default)
224
+ creates a bucket with the CORS rule and the lifecycle rule.
225
+ - **Wrangler's local R2:** needs no CORS rule (it lets any `localhost` page upload), and cannot complete multipart
226
+ uploads. See [Troubleshooting](troubleshooting.md#multipart-uploads-fail-on-wranglers-local-r2).