### Deploy Cloudflare Worker Source: https://github.com/mhart/aws4fetch/blob/master/example/README.md These commands are used to install the necessary dependencies for the Cloudflare Worker project and then deploy it to Cloudflare using the `wrangler` CLI tool. ```console npm install npx wrangler deploy ``` -------------------------------- ### Install aws4fetch via npm Source: https://github.com/mhart/aws4fetch/blob/master/README.md Provides the command to install the `aws4fetch` library using npm, the Node.js package manager. ```Shell npm install aws4fetch ``` -------------------------------- ### Initialize AWS Client and Invoke Lambda Function in Cloudflare Worker Source: https://github.com/mhart/aws4fetch/blob/master/example/README.md This snippet demonstrates how to initialize the `AwsClient` from `aws4fetch` using environment variables for AWS credentials and then use it to make a signed `fetch` request to an AWS Lambda invocation URL. This setup is suitable for Cloudflare Workers. ```JavaScript import { AwsClient } from 'aws4fetch' // ... // Assume AWS_* vars have added to your environment // https://developers.cloudflare.com/workers/reference/apis/environment-variables/#secrets aws = new AwsClient({ accessKeyId: env.AWS_ACCESS_KEY_ID, secretAccessKey: env.AWS_SECRET_ACCESS_KEY, }) // https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html const LAMBDA_INVOKE_URL = `https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/${LAMBDA_FN}/invocations` const lambdaResponse = await aws.fetch(LAMBDA_INVOKE_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(await toLambdaEvent(request)), }) ``` -------------------------------- ### Invoke AWS Lambda Function using aws4fetch Source: https://github.com/mhart/aws4fetch/blob/master/README.md This example demonstrates how to use `aws4fetch` to invoke an AWS Lambda function. It initializes an `AwsClient` with AWS credentials and then uses its `fetch` method to send a request to the Lambda API endpoint, handling the response as a standard `Response` object. ```js import { AwsClient } from 'aws4fetch' const aws = new AwsClient({ accessKeyId: MY_ACCESS_KEY, secretAccessKey: MY_SECRET_KEY }) // https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html const LAMBDA_FN_API = 'https://lambda.us-east-1.amazonaws.com/2015-03-31/functions' async function invokeMyLambda(event) { const res = await aws.fetch(`${LAMBDA_FN_API}/my-lambda/invocations`, { body: JSON.stringify(event) }) // `res` is a standard Response object: https://developer.mozilla.org/en-US/docs/Web/API/Response return res.json() } invokeMyLambda({my: 'event'}).then(json => console.log(json)) ``` -------------------------------- ### Transform Cloudflare Request to API Gateway-style Lambda Event Source: https://github.com/mhart/aws4fetch/blob/master/example/README.md This asynchronous function converts an incoming Cloudflare `Request` object into a structured event object that mimics the format of an API Gateway proxy event, suitable for consumption by an AWS Lambda function. It handles HTTP method, path, query parameters, headers, and body. ```JavaScript async function toLambdaEvent(request) { const url = new URL(request.url) return { httpMethod: request.method, path: url.pathname, queryStringParameters: Object.fromEntries([...url.searchParams]), headers: Object.fromEntries([...request.headers]), body: ['GET', 'HEAD'].includes(request.method) ? undefined : await request.text(), } } ``` -------------------------------- ### Handle AWS Lambda Response in Cloudflare Worker Source: https://github.com/mhart/aws4fetch/blob/master/example/README.md This code block demonstrates how to process the response received from an AWS Lambda invocation. It includes error checking for non-OK responses, logging errors, and transforming the Lambda's JSON response (containing status, headers, and body) into a standard Cloudflare `Response` object to be returned by the worker. ```JavaScript const lambdaResponse = await aws.fetch(LAMBDA_INVOKE_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(await toLambdaEvent(request)), }) if (!lambdaResponse.ok) { console.error(await lambdaResponse.text()) return Response.json({ error: `Lambda API returned ${lambdaResponse.status}` }, { status: 500 }) } const { statusCode: status, headers, body } = await lambdaResponse.json() return new Response(body, { status, headers }) ``` -------------------------------- ### Initialize AwsV4Signer for Raw AWS4 Signing Source: https://github.com/mhart/aws4fetch/blob/master/README.md Explains how to instantiate `AwsV4Signer` for direct AWS4 signing operations. This class is used when you need fine-grained control over the signing process, providing raw signed method, URL, headers, and body. It details all available constructor options. ```APIDOC new AwsV4Signer(options) options: object - Configuration options for the signer. url: string - Required. The AWS endpoint to sign. accessKeyId: string - Required. AWS access key ID. secretAccessKey: string - Required. AWS secret access key. sessionToken: string - Optional. AWS session token for temporary credentials. method: string - Optional. HTTP method (defaults to 'POST' if body, else 'GET'). headers: object | Headers - Optional. Standard JS object literal or Headers instance. body: string | ArrayBuffer | ArrayBufferView - Optional. Request body (remember to stringify JSON). signQuery: boolean - Optional. Set to true to sign the query string instead of the Authorization header. service: string - Optional. AWS service (by default parsed at fetch time). region: string - Optional. AWS region (by default parsed at fetch time). cache: Map - Optional. Credential cache (defaults to new Map()). datetime: string - Optional. Override signing datetime (e.g., '20150830T123600Z'). appendSessionToken: boolean - Optional. Add X-Amz-Security-Token after signing (defaults to true for IoT). allHeaders: boolean - Optional. Force all headers to be signed instead of defaults. singleEncode: boolean - Optional. Only encode %2F once (usually for testing). ``` ```JavaScript import { AwsV4Signer } from 'aws4fetch' const signer = new AwsV4Signer({ url, // required, the AWS endpoint to sign accessKeyId, // required, akin to AWS_ACCESS_KEY_ID secretAccessKey, // required, akin to AWS_SECRET_ACCESS_KEY sessionToken, // akin to AWS_SESSION_TOKEN if using temp credentials method, // if not supplied, will default to 'POST' if there's a body, otherwise 'GET' headers, // standard JS object literal, or Headers instance body, // optional, String or ArrayBuffer/ArrayBufferView – ie, remember to stringify your JSON signQuery, // set to true to sign the query string instead of the Authorization header service, // AWS service, by default parsed at fetch time region, // AWS region, by default parsed at fetch time cache, // credential cache, defaults to `new Map()` datetime, // defaults to now, to override use the form '20150830T123600Z' appendSessionToken, // set to true to add X-Amz-Security-Token after signing, defaults to true for iot allHeaders, // set to true to force all headers to be signed instead of the defaults singleEncode, // set to true to only encode %2F once (usually only needed for testing) }) ``` -------------------------------- ### AwsClient Class Constructor API Reference Source: https://github.com/mhart/aws4fetch/blob/master/README.md Documents the constructor for the `AwsClient` class, which initializes the AWS client with credentials and configuration options. It supports various parameters like `accessKeyId`, `secretAccessKey`, `sessionToken`, `service`, `region`, `cache`, `retries`, and `initRetryMs` to control authentication, service targeting, caching, and retry behavior. ```APIDOC new AwsClient(options) options: Object accessKeyId: string (required) - akin to AWS_ACCESS_KEY_ID secretAccessKey: string (required) - akin to AWS_SECRET_ACCESS_KEY sessionToken: string (optional) - akin to AWS_SESSION_TOKEN if using temp credentials service: string (optional) - AWS service, by default parsed at fetch time region: string (optional) - AWS region, by default parsed at fetch time cache: Map (optional) - credential cache, defaults to `new Map()` retries: number (optional) - number of retries before giving up, defaults to 10, set to 0 for no retrying initRetryMs: number (optional) - defaults to 50 – timeout doubles each retry ``` -------------------------------- ### Perform AWS4 Signing with AwsV4Signer Source: https://github.com/mhart/aws4fetch/blob/master/README.md Illustrates how to call the `signer.sign()` method on an `AwsV4Signer` instance to perform the actual AWS4 signing. It resolves to an object containing the signed method, URL, headers, and body, which can then be used for custom request construction. ```APIDOC Promise<{ method, url, headers, body }> signer.sign() Returns: Promise - A Promise that resolves to an object containing the signed request components. method: string - The signed HTTP method. url: URL - An instance of URL representing the signed URL. headers: Headers - An instance of Headers representing the signed headers. body: string | ArrayBuffer | ArrayBufferView - The request body (unchanged from constructor argument). ``` ```JavaScript import { AwsV4Signer } from 'aws4fetch' const signer = new AwsV4Signer(opts) async function sign() { const { method, url, headers, body } = await signer.sign() console.log(method, url, [...headers], body) } ``` -------------------------------- ### AwsClient.fetch Method API Reference Source: https://github.com/mhart/aws4fetch/blob/master/README.md Documents the `fetch` method of the `AwsClient` instance, which has the same signature as the global `fetch` function. It allows making AWS service calls with automatic AWS Signature Version 4 signing, supporting standard `fetch` options and additional `aws` specific options for fine-grained control over signing and service parameters. ```APIDOC Promise aws.fetch(input, [init]) input: RequestInfo | URL | string - Same as global fetch input init: RequestInit (optional) - Same as global fetch init, plus 'aws' property method: string (optional) - defaults to 'POST' if body, otherwise 'GET' headers: Object | Headers (optional) - standard JS object literal, or Headers instance body: String | ArrayBuffer | ArrayBufferView (optional) - remember to stringify JSON aws: Object (optional) - overrides options in the AwsClient instance signQuery: boolean (optional) - set to true to sign the query string instead of the Authorization header accessKeyId: string (optional) - same as in AwsClient constructor secretAccessKey: string (optional) - same as in AwsClient constructor sessionToken: string (optional) - same as in AwsClient constructor service: string (optional) - same as in AwsClient constructor region: string (optional) - same as in AwsClient constructor cache: Map (optional) - same as in AwsClient constructor datetime: string (optional) - defaults to now, format 'YYYYMMDDTHHMMSSZ' appendSessionToken: boolean (optional) - set to true to add X-Amz-Security-Token after signing, defaults to true for iot allHeaders: boolean (optional) - set to true to force all headers to be signed instead of the defaults singleEncode: boolean (optional) - set to true to only encode %2F once (usually only needed for testing) Returns: Promise - A standard Response object ``` -------------------------------- ### Sign AWS Requests with AwsClient for Fetch Source: https://github.com/mhart/aws4fetch/blob/master/README.md Demonstrates how to use `aws.sign` from `aws4fetch` to sign a `Request` object for AWS Signature Version 4. This signed request can then be used with the standard `fetch()` API. It covers various options for method, headers, body, and AWS-specific signing parameters. ```APIDOC Promise aws.sign(input[, init]) input: string | Request - The URL or a Request object to sign. init: object - Optional. Standard fetch options and AWS-specific signing parameters. method: string - HTTP method (defaults to 'POST' if body, else 'GET'). headers: object | Headers - Standard JS object literal or Headers instance. body: string | ArrayBuffer | ArrayBufferView - Optional request body (remember to stringify JSON). aws: object - AWS-specific signing options. signQuery: boolean - Set to true to sign the query string instead of the Authorization header. accessKeyId: string - AWS access key ID. secretAccessKey: string - AWS secret access key. sessionToken: string - AWS session token for temporary credentials. service: string - AWS service name. region: string - AWS region. cache: any - Credential cache. datetime: string - Override signing datetime (e.g., '20150830T123600Z'). appendSessionToken: boolean - Add X-Amz-Security-Token after signing (defaults to true for IoT). allHeaders: boolean - Force all headers to be signed. singleEncode: boolean - Only encode %2F once (usually for testing). Returns: Promise - A Promise that resolves to an AWS4 signed Request object. ``` ```JavaScript import { AwsClient } from 'aws4fetch' const aws = new AwsClient(opts) async function doFetch() { const request = await aws.sign(url, { method, // if not supplied, will default to 'POST' if there's a body, otherwise 'GET' headers, // standard JS object literal, or Headers instance body, // optional, String or ArrayBuffer/ArrayBufferView – ie, remember to stringify your JSON // and any other standard fetch options, eg keepalive, etc // optional, largely if you want to override options in the AwsClient instance aws: { signQuery, // set to true to sign the query string instead of the Authorization header accessKeyId, // same as in AwsClient constructor above secretAccessKey, // same as in AwsClient constructor above sessionToken, // same as in AwsClient constructor above service, // same as in AwsClient constructor above region, // same as in AwsClient constructor above cache, // same as in AwsClient constructor above datetime, // defaults to now, to override use the form '20150830T123600Z' appendSessionToken, // set to true to add X-Amz-Security-Token after signing, defaults to true for iot allHeaders, // set to true to force all headers to be signed instead of the defaults singleEncode, // set to true to only encode %2F once (usually only needed for testing) }, }) const response = await fetch(request) console.log(await response.json()) } ``` -------------------------------- ### AWS STS: X-Amz-Security-Token Header Reference Source: https://github.com/mhart/aws4fetch/blob/master/test/aws-sig-v4-test-suite/post-sts-token/readme.txt Details the usage and characteristics of the X-Amz-Security-Token header for temporary AWS security credentials, including its value, type, and placement considerations during request signing. ```APIDOC X-Amz-Security-Token: Type: HTTP Header or Query String Parameter Description: The security token required when using temporary security credentials obtained from AWS Security Token Service (AWS STS). Value: The session token string provided by AWS STS. Usage: - Required for signing requests with temporary credentials. - Placement in request varies by service: - Some services: Must be included in the canonical (signed) request (e.g., 'post-sts-header-before' test case). - Other services: Can be added to the request after signature calculation (e.g., 'post-sts-header-after' test case). - Refer to specific service API documentation for exact requirements. Example Value: AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA== ``` -------------------------------- ### Retrieve AWS4 Hex Signature Source: https://github.com/mhart/aws4fetch/blob/master/README.md Documents the `signer.signature()` method, which returns a Promise resolving to the raw hex signature. Similar to `authHeader()`, this is an internal method primarily used by `signer.sign()` but exposed for advanced use cases. ```APIDOC Promise signer.signature() Returns: Promise - A Promise that resolves to the hex signature. ``` -------------------------------- ### Retrieve AWS4 Authorization Header String Source: https://github.com/mhart/aws4fetch/blob/master/README.md Documents the `signer.authHeader()` method, which returns a Promise resolving to the signed string suitable for the `Authorization` header. This method is typically used internally by `signer.sign()` but can be accessed directly for custom request building. ```APIDOC Promise signer.authHeader() Returns: Promise - A Promise that resolves to the signed string for the Authorization header. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.