@paschendale/r2-presigned-url
Version:
Generate presigned URLs for Cloudflare R2 storage using AWS Signature Version 4 - Compatible with Cloudflare Workers
88 lines (87 loc) • 2.69 kB
TypeScript
/**
* R2 Presigned URL Generator
*
* A lightweight, zero-dependency library for generating presigned URLs for Cloudflare R2 storage
* using AWS Signature Version 4. Compatible with Cloudflare Workers and Node.js environments.
*
* @packageDocumentation
*/
export interface R2Credentials {
/** Cloudflare R2 Access Key ID */
R2_ACCESS_KEY_ID: string;
/** Cloudflare R2 Secret Access Key */
R2_SECRET_ACCESS_KEY: string;
/** Cloudflare Account ID */
R2_ACCOUNT_ID: string;
/** R2 Bucket name (optional, defaults to 'development') */
R2_BUCKET?: string;
}
export interface PresignedUrlOptions {
/** The object key (path) in the R2 bucket */
key: string;
/** MIME type of the file being uploaded */
contentType: string;
/** URL expiration time in seconds (max 604800 = 7 days) */
expiresIn: number;
/** HTTP method for the presigned URL (default: 'PUT') */
method?: "PUT" | "GET" | "POST";
}
export interface TestResult {
success: boolean;
url?: string;
error?: string;
debug?: {
canonicalRequest: string;
stringToSign: string;
signature: string;
};
}
/**
* Generate a presigned URL for R2 uploads using AWS Signature Version 4
* Compatible with Cloudflare Workers (no Node.js dependencies)
*
* @param options - Configuration options for the presigned URL
* @param credentials - R2 credentials
* @returns Promise<string> - The presigned URL
*
* @example
* ```typescript
* import { generateR2PresignedUrl } from 'r2-presigned-url';
*
* const credentials = {
* R2_ACCESS_KEY_ID: 'your-access-key',
* R2_SECRET_ACCESS_KEY: 'your-secret-key',
* R2_ACCOUNT_ID: 'your-account-id',
* R2_BUCKET: 'my-bucket'
* };
*
* const url = await generateR2PresignedUrl(
* {
* key: 'uploads/file.jpg',
* contentType: 'image/jpeg',
* expiresIn: 3600
* },
* credentials
* );
* ```
*/
export declare function generateR2PresignedUrl(options: PresignedUrlOptions, credentials: R2Credentials): Promise<string>;
/**
* Test function to validate presigned URL generation
* This can be used for debugging purposes
*
* @param credentials - R2 credentials to test with
* @returns Promise<TestResult> - Test results with success status and debug info
*
* @example
* ```typescript
* const result = await testPresignedUrlGeneration(credentials);
* if (result.success) {
* console.log('Test passed:', result.url);
* console.log('Signature:', result.debug?.signature);
* } else {
* console.error('Test failed:', result.error);
* }
* ```
*/
export declare function testPresignedUrlGeneration(credentials: R2Credentials): Promise<TestResult>;