/** * Minimal AWS Signature Version 4 S3 client for Cloudflare R2 (zero external dependencies). * Supports HEAD, GET, and PUT against R2's path-style S3 endpoint. */ import { createHash, createHmac } from 'node:crypto'; export interface R2ClientConfig { /** Account S3 API endpoint, e.g. `https://.r2.cloudflarestorage.com`. */ readonly endpoint: string; readonly bucket: string; readonly accessKeyId: string; readonly secretAccessKey: string; readonly region?: string; } export interface R2HeadResult { readonly exists: boolean; readonly contentLength: number | null; readonly sha256Meta: string | null; } export interface R2PutOptions { readonly key: string; readonly body: Uint8Array; readonly contentType: string; readonly cacheControl: string; readonly sha256Hex?: string; } const EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'; export class R2Client { readonly #endpoint: URL; readonly #bucket: string; readonly #accessKeyId: string; readonly #secretAccessKey: string; readonly #region: string; constructor(config: R2ClientConfig) { const endpoint = new URL(config.endpoint); if (endpoint.protocol !== 'https:') throw new Error('R2_ENDPOINT must be an https:// URL.'); this.#endpoint = endpoint; this.#bucket = config.bucket; this.#accessKeyId = config.accessKeyId; this.#secretAccessKey = config.secretAccessKey; this.#region = config.region ?? 'auto'; } async headObject(key: string): Promise { const response = await this.#send('HEAD', key, undefined, {}); if (response.status === 404) return { exists: false, contentLength: null, sha256Meta: null }; if (!response.ok) throw new Error(`R2 HEAD ${key} failed with HTTP ${response.status}.`); const lengthHeader = response.headers.get('content-length'); const contentLength = lengthHeader !== null && /^\d+$/.test(lengthHeader) ? Number(lengthHeader) : null; return { exists: true, contentLength, sha256Meta: response.headers.get('x-amz-meta-sha256'), }; } async getObjectText(key: string): Promise { const response = await this.#send('GET', key, undefined, {}); if (response.status === 404) return null; if (!response.ok) throw new Error(`R2 GET ${key} failed with HTTP ${response.status}: ${await response.text()}`); return response.text(); } async putObject(options: R2PutOptions): Promise { const sha256Hex = options.sha256Hex ?? sha256(options.body); const extraHeaders: Record = { 'content-type': options.contentType, 'cache-control': options.cacheControl, 'x-amz-meta-sha256': sha256Hex, }; const response = await this.#send('PUT', options.key, options.body, extraHeaders, sha256Hex); if (!response.ok) { throw new Error(`R2 PUT ${options.key} failed with HTTP ${response.status}: ${await response.text()}`); } } async #send( method: 'HEAD' | 'GET' | 'PUT', key: string, body: Uint8Array | undefined, extraHeaders: Record, payloadHash = EMPTY_SHA256, ): Promise { const normalizedKey = key.replace(/^\/+/, ''); const canonicalUri = `/${encodeSegment(this.#bucket)}/${normalizedKey.split('/').map(encodeSegment).join('/')}`; const url = new URL(canonicalUri, this.#endpoint); const now = new Date(); const amzDate = formatAmzDate(now); const dateStamp = amzDate.slice(0, 8); const signedEntries: [string, string][] = [ ['host', url.host], ['x-amz-content-sha256', payloadHash], ['x-amz-date', amzDate], ]; for (const [name, value] of Object.entries(extraHeaders)) { const lower = name.toLowerCase(); if (lower.startsWith('x-amz-')) signedEntries.push([lower, value.trim()]); } signedEntries.sort((a, b) => a[0].localeCompare(b[0])); const canonicalHeaders = signedEntries.map(([k, v]) => `${k}:${v}\n`).join(''); const signedHeaders = signedEntries.map(([k]) => k).join(';'); const canonicalRequest = [method, canonicalUri, '', canonicalHeaders, signedHeaders, payloadHash].join('\n'); const credentialScope = `${dateStamp}/${this.#region}/s3/aws4_request`; const stringToSign = ['AWS4-HMAC-SHA256', amzDate, credentialScope, sha256(canonicalRequest)].join('\n'); const signingKey = deriveSigningKey(this.#secretAccessKey, dateStamp, this.#region, 's3'); const signature = hmacHex(signingKey, stringToSign); const authorization = `AWS4-HMAC-SHA256 Credential=${this.#accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; const headers: Record = { ...extraHeaders, 'x-amz-date': amzDate, 'x-amz-content-sha256': payloadHash, authorization, }; return fetch(url, { method, headers, ...(body ? { body: Buffer.from(body.buffer, body.byteOffset, body.byteLength) } : {}), }); } } export function sha256(data: string | Uint8Array): string { return createHash('sha256').update(data).digest('hex'); } function hmac(key: string | Buffer, data: string): Buffer { return createHmac('sha256', key).update(data, 'utf8').digest(); } function hmacHex(key: Buffer, data: string): string { return createHmac('sha256', key).update(data, 'utf8').digest('hex'); } function deriveSigningKey(secretKey: string, dateStamp: string, region: string, service: string): Buffer { const kDate = hmac(`AWS4${secretKey}`, dateStamp); const kRegion = hmac(kDate, region); const kService = hmac(kRegion, service); return hmac(kService, 'aws4_request'); } function formatAmzDate(date: Date): string { return date.toISOString().replace(/[:-]|\.\d{3}/g, ''); } function encodeSegment(segment: string): string { return encodeURIComponent(segment).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`); }