const REGION = 'us-east-1' const SERVICE = 's3' export interface SignedHeaders { Authorization: string 'X-Amz-Date': string 'X-Amz-Content-Sha256': string } export async function signS3Get(path: string, accessKey: string, secretKey: string): Promise { return signS3('GET', path, await sha256Hex(''), accessKey, secretKey) } export async function signS3Put(path: string, accessKey: string, secretKey: string): Promise { return signS3('PUT', path, 'UNSIGNED-PAYLOAD', accessKey, secretKey) } export async function signS3Delete(path: string, accessKey: string, secretKey: string): Promise { return signS3('DELETE', path, await sha256Hex(''), accessKey, secretKey) } async function signS3(method: string, path: string, payloadHash: string, accessKey: string, secretKey: string): Promise { const amzDate = toAmzDate(new Date()) const dateStamp = amzDate.slice(0, 8) const signedHeaderValues: Record = { 'x-amz-content-sha256': payloadHash, 'x-amz-date': amzDate, } const signedHeaders = Object.keys(signedHeaderValues).join(';') const canonicalHeaders = Object.entries(signedHeaderValues) .map(([name, value]) => `${name}:${value}\n`) .join('') const canonicalRequest = [method, encodeCanonicalPath(path), '', canonicalHeaders, signedHeaders, payloadHash].join('\n') const credentialScope = `${dateStamp}/${REGION}/${SERVICE}/aws4_request` const stringToSign = [ 'AWS4-HMAC-SHA256', amzDate, credentialScope, await sha256Hex(canonicalRequest), ].join('\n') const key = await deriveSigningKey(secretKey, dateStamp) const signature = bufferToHex(await hmac(key, stringToSign)) return { Authorization: `AWS4-HMAC-SHA256 Credential=${accessKey}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`, 'X-Amz-Date': amzDate, 'X-Amz-Content-Sha256': payloadHash, } } function toAmzDate(date: Date): string { return date.toISOString().replace(/[:-]|\.\d{3}/g, '') } function isUnreservedByte(byte: number): boolean { return (byte >= 0x41 && byte <= 0x5a) // A-Z || (byte >= 0x61 && byte <= 0x7a) // a-z || (byte >= 0x30 && byte <= 0x39) // 0-9 || byte === 0x2d || byte === 0x5f || byte === 0x2e || byte === 0x7e // - _ . ~ } export function encodeCanonicalPath(path: string): string { return path .split('/') .map((segment) => Array.from(new TextEncoder().encode(segment)) .map((byte) => (isUnreservedByte(byte) ? String.fromCharCode(byte) : `%${byte.toString(16).toUpperCase().padStart(2, '0')}`)) .join('')) .join('/') } async function deriveSigningKey(secretKey: string, dateStamp: string): Promise { const kDate = await hmac(new TextEncoder().encode(`AWS4${secretKey}`), dateStamp) const kRegion = await hmac(kDate, REGION) const kService = await hmac(kRegion, SERVICE) return hmac(kService, 'aws4_request') } async function hmac(key: BufferSource, data: string): Promise { const cryptoKey = await crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']) return crypto.subtle.sign('HMAC', cryptoKey, new TextEncoder().encode(data)) } async function sha256Hex(data: string): Promise { const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data)) return bufferToHex(digest) } function bufferToHex(buffer: ArrayBuffer): string { return Array.from(new Uint8Array(buffer)) .map((byte) => byte.toString(16).padStart(2, '0')) .join('') }