Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/cloudflare

Cloudflare helpers: API v4, static site publishing to Pages, analytics, WAF rules, logs, and docs.

FollowFork

Files

r2-source.ts

70 lines · 2.4 KB · TypeScript
/** Deliberately bounded single PUT. Larger objects need a separate multipart workflow. */
export const R2_SINGLE_PUT_MAX_BYTES = 8 * 1024 * 1024
export async function readR2Source(
	url: string,
	expectedSha256?: string,
	sourceFetch: typeof fetch = fetch,
): Promise<Uint8Array> {
	if (expectedSha256 !== undefined && !/^[a-f0-9]{64}$/.test(expectedSha256))
		throw new Error('expectedSha256 must be lowercase SHA-256 hex')
	let parsed: URL
	try {
		parsed = new URL(url)
	} catch {
		throw new Error('HTTPS source URL required')
	}
	if (parsed.protocol !== 'https:') throw new Error('HTTPS source URL required')
	if (url.includes('{{')) throw new Error('Source URL must not contain secret placeholders')
	let response: Response
	try {
		response = await sourceFetch(url, { redirect: 'manual' })
	} catch {
		throw new Error('Source read failed; no destination request was sent')
	}
	const etag = response.headers.get('etag')
	if (
		!response.ok ||
		(!expectedSha256 && (!etag || !/^"[^"\r\n]*"$/.test(etag) || etag.startsWith('W/')))
	) {
		await response.body?.cancel()
		throw new Error('Source requires a successful response and strong ETag or expectedSha256')
	}
	const length = response.headers.get('content-length')
	if (length !== null && (!/^\d+$/.test(length) || Number(length) > R2_SINGLE_PUT_MAX_BYTES)) {
		await response.body?.cancel()
		throw new Error(
			'Source exceeds 8 MiB single-PUT limit; multipart uploads are not supported here',
		)
	}
	const parts: Uint8Array[] = []
	let count = 0
	const reader = response.body?.getReader()
	if (!reader) throw new Error('Source body missing')
	try {
		for (;;) {
			const r = await reader.read()
			if (r.done) break
			count += r.value.length
			if (count > R2_SINGLE_PUT_MAX_BYTES) throw new Error('Source exceeds 8 MiB single-PUT limit')
			parts.push(r.value)
		}
		if (length !== null && count !== Number(length)) throw new Error('Source body is partial')
	} finally {
		await reader.cancel().catch(() => {})
		reader.releaseLock()
	}
	const bytes = new Uint8Array(count)
	let at = 0
	for (const part of parts) {
		bytes.set(part, at)
		at += part.length
	}
	if (expectedSha256) {
		const digest = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (x) =>
			x.toString(16).padStart(2, '0'),
		).join('')
		if (digest !== expectedSha256)
			throw new Error('Source SHA-256 mismatch; no destination request was sent')
	}
	return bytes
}