@aws-lambda-powertools/signer 0.0.0 → 2.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +146 -4
  2. package/lib/cjs/Sha256.d.ts +21 -0
  3. package/lib/cjs/Sha256.d.ts.map +1 -0
  4. package/lib/cjs/Sha256.js +54 -0
  5. package/lib/cjs/SigV4Signer.d.ts +24 -0
  6. package/lib/cjs/SigV4Signer.d.ts.map +1 -0
  7. package/lib/cjs/SigV4Signer.js +154 -0
  8. package/lib/cjs/errors.d.ts +30 -0
  9. package/lib/cjs/errors.d.ts.map +1 -0
  10. package/lib/cjs/errors.js +46 -0
  11. package/lib/cjs/fetch.d.ts +27 -0
  12. package/lib/cjs/fetch.d.ts.map +1 -0
  13. package/lib/cjs/fetch.js +33 -0
  14. package/lib/cjs/package.json +1 -0
  15. package/lib/cjs/sigv4.d.ts +3 -0
  16. package/lib/cjs/sigv4.d.ts.map +1 -0
  17. package/lib/cjs/sigv4.js +5 -0
  18. package/lib/cjs/types/index.d.ts +60 -0
  19. package/lib/cjs/types/index.d.ts.map +1 -0
  20. package/lib/cjs/types/index.js +2 -0
  21. package/lib/esm/Sha256.d.ts +21 -0
  22. package/lib/esm/Sha256.d.ts.map +1 -0
  23. package/lib/esm/Sha256.js +51 -0
  24. package/lib/esm/SigV4Signer.d.ts +24 -0
  25. package/lib/esm/SigV4Signer.d.ts.map +1 -0
  26. package/lib/esm/SigV4Signer.js +151 -0
  27. package/lib/esm/errors.d.ts +30 -0
  28. package/lib/esm/errors.d.ts.map +1 -0
  29. package/lib/esm/errors.js +41 -0
  30. package/lib/esm/fetch.d.ts +27 -0
  31. package/lib/esm/fetch.d.ts.map +1 -0
  32. package/lib/esm/fetch.js +30 -0
  33. package/lib/esm/package.json +1 -0
  34. package/lib/esm/sigv4.d.ts +3 -0
  35. package/lib/esm/sigv4.d.ts.map +1 -0
  36. package/lib/esm/sigv4.js +1 -0
  37. package/lib/esm/types/index.d.ts +60 -0
  38. package/lib/esm/types/index.d.ts.map +1 -0
  39. package/package.json +94 -13
  40. package/lib/index.js +0 -3
  41. /package/lib/{index.d.ts → esm/types/index.js} +0 -0
package/README.md CHANGED
@@ -1,6 +1,148 @@
1
- # Powertools for AWS Lambda (TypeScript) - Signer Utility
1
+ # Powertools for AWS Lambda (TypeScript) - Signer Utility <!-- omit in toc -->
2
2
 
3
- > [!Warning]
4
- > This is a placeholder package used to reserve the package name ahead of the first release of the `signer` utility. **Do not use this in production yet.**
3
+ Powertools for AWS Lambda (TypeScript) is a developer toolkit to implement Serverless [best practices and increase developer velocity](https://docs.aws.amazon.com/powertools/typescript/latest/#features).
5
4
 
6
- The first working version of this package will be published as part of an upcoming Powertools for AWS Lambda (TypeScript) release. Until then, please refer to the [Powertools for AWS Lambda (TypeScript) documentation](https://docs.powertools.aws.dev/lambda/typescript/latest/) and the [GitHub repository](https://github.com/aws-powertools/powertools-lambda-typescript) for updates.
5
+ - [Intro](#intro)
6
+ - [Key features](#key-features)
7
+ - [Usage](#usage)
8
+ - [Signing a request](#signing-a-request)
9
+ - [Sending signed requests](#sending-signed-requests)
10
+ - [Using other HTTP clients](#using-other-http-clients)
11
+ - [Contribute](#contribute)
12
+ - [Roadmap](#roadmap)
13
+ - [Connect](#connect)
14
+ - [How to support Powertools for AWS Lambda (TypeScript)?](#how-to-support-powertools-for-aws-lambda-typescript)
15
+ - [Becoming a reference customer](#becoming-a-reference-customer)
16
+ - [Sharing your work](#sharing-your-work)
17
+ - [Using Lambda Layer](#using-lambda-layer)
18
+ - [License](#license)
19
+
20
+ ## Intro
21
+
22
+ This utility provides a way to sign HTTP requests to AWS services using the [AWS Signature Version 4 (SigV4)](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv4_signing.html) signing process, so you can call IAM-authenticated endpoints such as Amazon API Gateway, AWS Lambda function URLs, or AWS AppSync from within your Lambda functions.
23
+
24
+ ## Key features
25
+
26
+ - Sign web-standard `Request` objects with AWS Signature Version 4
27
+ - Drop-in signed `fetch` for sending signed requests in one step
28
+ - Works with any HTTP client by exposing the signed request and headers
29
+ - Reads credentials and region from the Lambda runtime by default, with no extra dependencies
30
+
31
+ ## Usage
32
+
33
+ To get started, install the library by running:
34
+
35
+ ```sh
36
+ npm install @aws-lambda-powertools/signer
37
+ ```
38
+
39
+ ### Signing a request
40
+
41
+ The signer takes a web-standard `Request` (or anything you can pass to `fetch`, like a URL string) and returns a new, signed `Request` with the SigV4 headers added. It performs no network I/O, so you stay in control of how the request is sent.
42
+
43
+ ```typescript
44
+ import { SigV4Signer } from '@aws-lambda-powertools/signer/sigv4';
45
+
46
+ const signer = new SigV4Signer({ service: 'execute-api' });
47
+
48
+ export const handler = async () => {
49
+ const signed = await signer.sign(
50
+ 'https://example.execute-api.us-east-1.amazonaws.com/items'
51
+ );
52
+
53
+ const response = await fetch(signed);
54
+ await response.json();
55
+ };
56
+ ```
57
+
58
+ By default, the signer reads the AWS credentials and region from the environment variables that the Lambda runtime always provides, so no additional configuration is required when running in Lambda.
59
+
60
+ ### Sending signed requests
61
+
62
+ If all you want is to sign and immediately send the request, use `createSignedFetcher`. It consumes a signer instance and returns a function with the same signature as the global `fetch`, signing each request before sending it.
63
+
64
+ ```typescript
65
+ import { createSignedFetcher } from '@aws-lambda-powertools/signer/fetch';
66
+ import { SigV4Signer } from '@aws-lambda-powertools/signer/sigv4';
67
+
68
+ const signer = new SigV4Signer({ service: 'execute-api' });
69
+ const signedFetch = createSignedFetcher(signer);
70
+
71
+ export const handler = async () => {
72
+ const response = await signedFetch(
73
+ 'https://example.execute-api.us-east-1.amazonaws.com/items',
74
+ {
75
+ method: 'POST',
76
+ body: JSON.stringify({ name: 'powertools' }),
77
+ }
78
+ );
79
+
80
+ await response.json();
81
+ };
82
+ ```
83
+
84
+ ### Using other HTTP clients
85
+
86
+ Signing and sending are deliberately kept separate, so you can use the signed request with any HTTP client (for example `axios`, `got`, a generated SDK client, or a request interceptor). Call `sign()` to obtain a signed `Request`, then read its `url`, `method`, and `headers`.
87
+
88
+ See the [documentation](https://docs.aws.amazon.com/powertools/typescript/latest/features/signer/) for more details on configuring credentials and region, handling errors, and using other HTTP clients.
89
+
90
+ ## Contribute
91
+
92
+ If you are interested in contributing to this project, please refer to our [Contributing Guidelines](https://github.com/aws-powertools/powertools-lambda-typescript/blob/main/CONTRIBUTING.md).
93
+
94
+ ## Roadmap
95
+
96
+ The roadmap of Powertools for AWS Lambda (TypeScript) is driven by customers’ demand.
97
+ Help us prioritize upcoming functionalities or utilities by [upvoting existing RFCs and feature requests](https://github.com/aws-powertools/powertools-lambda-typescript/issues), or [creating new ones](https://github.com/aws-powertools/powertools-lambda-typescript/issues/new/choose), in this GitHub repository.
98
+
99
+ ## Connect
100
+
101
+ - **Powertools for AWS Lambda on Discord**: `#typescript` - **[Invite link](https://discord.gg/B8zZKbbyET)**
102
+ - **Email**: <aws-lambda-powertools-feedback@amazon.com>
103
+
104
+ ## How to support Powertools for AWS Lambda (TypeScript)?
105
+
106
+ ### Becoming a reference customer
107
+
108
+ Knowing which companies are using this library is important to help prioritize the project internally. If your company
109
+ is using Powertools for AWS Lambda (TypeScript), you can request to have your name and logo added to the README file by
110
+ raising a [Support Powertools for AWS Lambda (TypeScript) (become a reference)](https://s12d.com/become-reference-pt-ts)
111
+ issue.
112
+
113
+ The following companies, among others, use Powertools:
114
+
115
+ - [Alma Media](https://www.almamedia.fi)
116
+ - [AppYourself](https://appyourself.net)
117
+ - [Bailey Nelson](https://www.baileynelson.com.au)
118
+ - [Banxware](https://www.banxware.com)
119
+ - [Caylent](https://caylent.com/)
120
+ - [Certible](https://www.certible.com/)
121
+ - [Codeac](https://www.codeac.io/)
122
+ - [EF Education First](https://www.ef.com/)
123
+ - [Elva](https://elva-group.com)
124
+ - [Flyweight](https://flyweight.io/)
125
+ - [FraudFalcon](https://fraudfalcon.app)
126
+ - [globaldatanet](https://globaldatanet.com/)
127
+ - [Guild](https://guild.com)
128
+ - [Hashnode](https://hashnode.com/)
129
+ - [Instil](https://instil.co/)
130
+ - [LocalStack](https://localstack.cloud/)
131
+ - [Ours Privacy](https://oursprivacy.com/)
132
+ - [Perfect Post](https://www.perfectpost.fr)
133
+ - [Sennder](https://sennder.com/)
134
+ - [tecRacer GmbH & Co. KG](https://www.tecracer.com/)
135
+ - [Trek10](https://www.trek10.com/)
136
+ - [WeSchool](https://www.weschool.com)
137
+
138
+ ### Sharing your work
139
+
140
+ Share what you did with Powertools for AWS Lambda (TypeScript) 💞💞. Blog post, workshops, presentation, sample apps and others. Check out what the community has [already shared](https://docs.aws.amazon.com/powertools/typescript/latest/we_made_this) about Powertools for AWS Lambda (TypeScript).
141
+
142
+ ### Using Lambda Layer
143
+
144
+ This helps us understand who uses Powertools for AWS Lambda (TypeScript) in a non-intrusive way, and helps us gain future investments for other Powertools for AWS Lambda languages. When [using Layers](https://docs.aws.amazon.com/powertools/typescript/latest/getting-started/lambda-layers/), you can add Powertools as a dev dependency to not impact the development process.
145
+
146
+ ## License
147
+
148
+ This library is licensed under the MIT-0 License. See the LICENSE file.
@@ -0,0 +1,21 @@
1
+ import type { Checksum, SourceData } from '@smithy/types';
2
+ /**
3
+ * A {@link Checksum | `Checksum`} implementation backed by `node:crypto`.
4
+ *
5
+ * The underlying signing process expects a hash constructor that supports both
6
+ * plain SHA-256 (for hashing payloads) and HMAC-SHA256 with a secret (for
7
+ * deriving the signing key). Using `node:crypto` avoids pulling in a
8
+ * third-party crypto dependency, relying instead on the Node.js runtime that
9
+ * AWS Lambda provides.
10
+ *
11
+ * @internal
12
+ */
13
+ declare class Sha256 implements Checksum {
14
+ #private;
15
+ constructor(secret?: SourceData);
16
+ update(data: SourceData): void;
17
+ digest(): Promise<Uint8Array>;
18
+ reset(): void;
19
+ }
20
+ export { Sha256 };
21
+ //# sourceMappingURL=Sha256.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Sha256.d.ts","sourceRoot":"","sources":["../../src/Sha256.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAsB1D;;;;;;;;;;GAUG;AACH,cAAM,MAAO,YAAW,QAAQ;;gBAGX,MAAM,CAAC,EAAE,UAAU;IAO/B,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,IAAI;IAIxB,MAAM,IAAI,OAAO,CAAC,UAAU,CAAC;IAInC,KAAK,IAAI,IAAI;CAIrB;AAED,OAAO,EAAE,MAAM,EAAE,CAAC"}
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Sha256 = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ /**
6
+ * Convert smithy's {@link SourceData | `SourceData`} into a value accepted by
7
+ * `node:crypto`.
8
+ *
9
+ * `SourceData` is `string | ArrayBuffer | ArrayBufferView`, while `node:crypto`
10
+ * accepts `string | NodeJS.ArrayBufferView` - it rejects a bare `ArrayBuffer`
11
+ * at runtime, and TypeScript's structural `ArrayBufferView` is not assignable
12
+ * to Node's concrete union of typed arrays. Wrapping non-string inputs in a
13
+ * `Uint8Array` bridges both gaps without copying the underlying bytes.
14
+ */
15
+ const toBinary = (data) => {
16
+ if (typeof data === 'string') {
17
+ return data;
18
+ }
19
+ if (ArrayBuffer.isView(data)) {
20
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
21
+ }
22
+ return new Uint8Array(data);
23
+ };
24
+ /**
25
+ * A {@link Checksum | `Checksum`} implementation backed by `node:crypto`.
26
+ *
27
+ * The underlying signing process expects a hash constructor that supports both
28
+ * plain SHA-256 (for hashing payloads) and HMAC-SHA256 with a secret (for
29
+ * deriving the signing key). Using `node:crypto` avoids pulling in a
30
+ * third-party crypto dependency, relying instead on the Node.js runtime that
31
+ * AWS Lambda provides.
32
+ *
33
+ * @internal
34
+ */
35
+ class Sha256 {
36
+ #hash;
37
+ constructor(secret) {
38
+ this.#hash =
39
+ secret === undefined
40
+ ? (0, node_crypto_1.createHash)('sha256')
41
+ : (0, node_crypto_1.createHmac)('sha256', toBinary(secret));
42
+ }
43
+ update(data) {
44
+ this.#hash.update(toBinary(data));
45
+ }
46
+ async digest() {
47
+ return new Uint8Array(this.#hash.digest());
48
+ }
49
+ reset() {
50
+ // `node:crypto` hashes are single-use; reset is a no-op because a new
51
+ // instance is created per hashing operation by the signing process.
52
+ }
53
+ }
54
+ exports.Sha256 = Sha256;
@@ -0,0 +1,24 @@
1
+ import type { Signer, SigV4SignerOptions } from './types/index.js';
2
+ /**
3
+ * A {@link Signer | `Signer`} that signs requests using the AWS Signature
4
+ * Version 4 (SigV4) signing process.
5
+ *
6
+ * The signer takes and returns web-standard {@link Request | `Request`}
7
+ * objects and performs no network I/O. To send signed requests, pass an
8
+ * instance to `createSignedFetcher` from `@aws-lambda-powertools/signer/fetch`.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { SigV4Signer } from '@aws-lambda-powertools/signer/sigv4';
13
+ *
14
+ * const signer = new SigV4Signer({ service: 'execute-api' });
15
+ * const signed = await signer.sign('https://example.execute-api.us-east-1.amazonaws.com/items');
16
+ * ```
17
+ */
18
+ declare class SigV4Signer implements Signer {
19
+ #private;
20
+ constructor(options: SigV4SignerOptions);
21
+ sign(input: string | URL | Request, init?: RequestInit): Promise<Request>;
22
+ }
23
+ export { SigV4Signer };
24
+ //# sourceMappingURL=SigV4Signer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SigV4Signer.d.ts","sourceRoot":"","sources":["../../src/SigV4Signer.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAyBnE;;;;;;;;;;;;;;;GAeG;AACH,cAAM,WAAY,YAAW,MAAM;;gBAKd,OAAO,EAAE,kBAAkB;IAcjC,IAAI,CACf,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,EAC7B,IAAI,CAAC,EAAE,WAAW,GACjB,OAAO,CAAC,OAAO,CAAC;CAgHpB;AAED,OAAO,EAAE,WAAW,EAAE,CAAC"}
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SigV4Signer = void 0;
4
+ const signature_v4_1 = require("@smithy/signature-v4");
5
+ const errors_js_1 = require("./errors.js");
6
+ const Sha256_js_1 = require("./Sha256.js");
7
+ /**
8
+ * Credential provider that reads AWS credentials from the standard environment
9
+ * variables that the AWS Lambda runtime always injects.
10
+ *
11
+ * Throws a {@link SignerConfigError | `SignerConfigError`} when the required
12
+ * variables are not present, e.g. when running outside of Lambda.
13
+ */
14
+ const credentialsFromEnv = async () => {
15
+ const accessKeyId = process.env.AWS_ACCESS_KEY_ID;
16
+ const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
17
+ if (accessKeyId === undefined || secretAccessKey === undefined) {
18
+ throw new errors_js_1.SignerConfigError('Unable to resolve AWS credentials to sign the request with. Ensure the standard AWS credentials environment variables are set, or pass the `credentials` option.');
19
+ }
20
+ return {
21
+ accessKeyId,
22
+ secretAccessKey,
23
+ sessionToken: process.env.AWS_SESSION_TOKEN,
24
+ };
25
+ };
26
+ /**
27
+ * A {@link Signer | `Signer`} that signs requests using the AWS Signature
28
+ * Version 4 (SigV4) signing process.
29
+ *
30
+ * The signer takes and returns web-standard {@link Request | `Request`}
31
+ * objects and performs no network I/O. To send signed requests, pass an
32
+ * instance to `createSignedFetcher` from `@aws-lambda-powertools/signer/fetch`.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * import { SigV4Signer } from '@aws-lambda-powertools/signer/sigv4';
37
+ *
38
+ * const signer = new SigV4Signer({ service: 'execute-api' });
39
+ * const signed = await signer.sign('https://example.execute-api.us-east-1.amazonaws.com/items');
40
+ * ```
41
+ */
42
+ class SigV4Signer {
43
+ #service;
44
+ #region;
45
+ #credentials;
46
+ constructor(options) {
47
+ this.#service = options.service;
48
+ const region = options.region ?? process.env.AWS_REGION;
49
+ if (region === undefined || region === '') {
50
+ throw new errors_js_1.SignerConfigError('Unable to determine the AWS region to sign the request with. Set the `region` option or the `AWS_REGION` environment variable.');
51
+ }
52
+ this.#region = region;
53
+ this.#credentials = options.credentials ?? credentialsFromEnv;
54
+ }
55
+ async sign(input, init) {
56
+ const request = new Request(input, init);
57
+ const credentials = await this.#resolveCredentials();
58
+ const httpRequest = await this.#toHttpRequest(request);
59
+ const signer = new signature_v4_1.SignatureV4({
60
+ service: this.#service,
61
+ region: this.#region,
62
+ credentials,
63
+ sha256: Sha256_js_1.Sha256,
64
+ });
65
+ let signed;
66
+ try {
67
+ signed = (await signer.sign(httpRequest));
68
+ }
69
+ catch (error) {
70
+ throw new errors_js_1.RequestSigningError('Failed to sign the request', {
71
+ cause: error,
72
+ });
73
+ }
74
+ return this.#toRequest(signed, request);
75
+ }
76
+ /**
77
+ * Resolve the configured credentials, supporting both static values and
78
+ * async providers. The default env-var provider throws a configuration error
79
+ * when no credentials are available.
80
+ */
81
+ async #resolveCredentials() {
82
+ return typeof this.#credentials === 'function'
83
+ ? await this.#credentials()
84
+ : this.#credentials;
85
+ }
86
+ /**
87
+ * Adapt a web-standard `Request` into the `HttpRequest` shape expected by the
88
+ * underlying signing process, buffering the body so it can be hashed.
89
+ *
90
+ * The signing process accepts a plain object matching the `HttpRequest`
91
+ * interface, so we avoid depending on `@smithy/protocol-http` just to
92
+ * construct one.
93
+ */
94
+ async #toHttpRequest(request) {
95
+ const url = new URL(request.url);
96
+ const headers = {};
97
+ for (const [key, value] of request.headers) {
98
+ headers[key] = value;
99
+ }
100
+ headers.host = url.host;
101
+ const query = {};
102
+ for (const [key, value] of url.searchParams) {
103
+ query[key] = value;
104
+ }
105
+ const body = await this.#readBody(request);
106
+ return {
107
+ method: request.method,
108
+ protocol: url.protocol,
109
+ hostname: url.hostname,
110
+ port: url.port ? Number(url.port) : undefined,
111
+ path: url.pathname,
112
+ query,
113
+ headers,
114
+ body,
115
+ };
116
+ }
117
+ /**
118
+ * Buffer the request body so it can be both hashed for signing and replayed
119
+ * when the signed request is sent.
120
+ *
121
+ * Most bodies (strings, buffers, and finite streams) are buffered
122
+ * transparently. A body that cannot be read or replayed — for example a
123
+ * stream that errors mid-read — cannot be signed and results in a
124
+ * {@link RequestSigningError | `RequestSigningError`}.
125
+ */
126
+ async #readBody(request) {
127
+ if (request.body === null || request.body === undefined) {
128
+ return undefined;
129
+ }
130
+ try {
131
+ const buffer = await request.clone().arrayBuffer();
132
+ return buffer.byteLength === 0 ? undefined : new Uint8Array(buffer);
133
+ }
134
+ catch (error) {
135
+ throw new errors_js_1.RequestSigningError('Unable to read the request body to sign it. The body could not be buffered, for example because it is a stream that cannot be replayed.', { cause: error });
136
+ }
137
+ }
138
+ /**
139
+ * Adapt a signed `HttpRequest` back into a web-standard `Request`, carrying
140
+ * over the signed headers and the original (buffered) body.
141
+ */
142
+ #toRequest(signed, original) {
143
+ const headers = new Headers();
144
+ for (const [key, value] of Object.entries(signed.headers)) {
145
+ headers.set(key, value);
146
+ }
147
+ return new Request(original.url, {
148
+ method: signed.method,
149
+ headers,
150
+ body: signed.body,
151
+ });
152
+ }
153
+ }
154
+ exports.SigV4Signer = SigV4Signer;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Base error for all errors thrown by the signer utility.
3
+ *
4
+ * Generally this error should not be thrown directly; prefer the more specific
5
+ * {@link SignerConfigError | `SignerConfigError`} and
6
+ * {@link RequestSigningError | `RequestSigningError`} subclasses.
7
+ */
8
+ declare class SignerError extends Error {
9
+ constructor(message: string, options?: ErrorOptions);
10
+ }
11
+ /**
12
+ * Error thrown when the signer is misconfigured.
13
+ *
14
+ * This is thrown eagerly at construction when the region cannot be determined,
15
+ * and lazily during signing when credentials are missing or cannot be resolved.
16
+ */
17
+ declare class SignerConfigError extends SignerError {
18
+ constructor(message: string, options?: ErrorOptions);
19
+ }
20
+ /**
21
+ * Error thrown when signing a request fails.
22
+ *
23
+ * This wraps errors thrown by the underlying signing process. The original
24
+ * error, when available, is preserved on the `cause` property.
25
+ */
26
+ declare class RequestSigningError extends SignerError {
27
+ constructor(message: string, options?: ErrorOptions);
28
+ }
29
+ export { RequestSigningError, SignerConfigError, SignerError };
30
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,cAAM,WAAY,SAAQ,KAAK;gBACV,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAI3D;AAED;;;;;GAKG;AACH,cAAM,iBAAkB,SAAQ,WAAW;gBACtB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAI3D;AAED;;;;;GAKG;AACH,cAAM,mBAAoB,SAAQ,WAAW;gBACxB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAQ3D;AAED,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,WAAW,EAAE,CAAC"}
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SignerError = exports.SignerConfigError = exports.RequestSigningError = void 0;
4
+ /**
5
+ * Base error for all errors thrown by the signer utility.
6
+ *
7
+ * Generally this error should not be thrown directly; prefer the more specific
8
+ * {@link SignerConfigError | `SignerConfigError`} and
9
+ * {@link RequestSigningError | `RequestSigningError`} subclasses.
10
+ */
11
+ class SignerError extends Error {
12
+ constructor(message, options) {
13
+ super(message, options);
14
+ this.name = 'SignerError';
15
+ }
16
+ }
17
+ exports.SignerError = SignerError;
18
+ /**
19
+ * Error thrown when the signer is misconfigured.
20
+ *
21
+ * This is thrown eagerly at construction when the region cannot be determined,
22
+ * and lazily during signing when credentials are missing or cannot be resolved.
23
+ */
24
+ class SignerConfigError extends SignerError {
25
+ constructor(message, options) {
26
+ super(message, options);
27
+ this.name = 'SignerConfigError';
28
+ }
29
+ }
30
+ exports.SignerConfigError = SignerConfigError;
31
+ /**
32
+ * Error thrown when signing a request fails.
33
+ *
34
+ * This wraps errors thrown by the underlying signing process. The original
35
+ * error, when available, is preserved on the `cause` property.
36
+ */
37
+ class RequestSigningError extends SignerError {
38
+ constructor(message, options) {
39
+ const errorMessage = options?.cause instanceof Error
40
+ ? `${message}. This error was caused by: ${options.cause.message}.`
41
+ : message;
42
+ super(errorMessage, options);
43
+ this.name = 'RequestSigningError';
44
+ }
45
+ }
46
+ exports.RequestSigningError = RequestSigningError;
@@ -0,0 +1,27 @@
1
+ import type { SignedFetcherOptions, Signer } from './types/index.js';
2
+ /**
3
+ * Create a drop-in `fetch` function that signs every request with the given
4
+ * {@link Signer | `Signer`} before sending it.
5
+ *
6
+ * The returned function has the same signature as the global `fetch`, so it can
7
+ * be passed to libraries that accept a custom `fetch` implementation, or used
8
+ * directly.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { SigV4Signer } from '@aws-lambda-powertools/signer/sigv4';
13
+ * import { createSignedFetcher } from '@aws-lambda-powertools/signer/fetch';
14
+ *
15
+ * const signer = new SigV4Signer({ service: 'execute-api' });
16
+ * const signedFetch = createSignedFetcher(signer);
17
+ *
18
+ * const response = await signedFetch('https://example.execute-api.us-east-1.amazonaws.com/items');
19
+ * ```
20
+ *
21
+ * @param signer - The signer used to sign each request before it is sent.
22
+ * @param options - Optional configuration, e.g. a custom `fetch` implementation.
23
+ */
24
+ declare const createSignedFetcher: (signer: Signer, options?: SignedFetcherOptions) => typeof fetch;
25
+ export type { SignedFetcherOptions, Signer } from './types/index.js';
26
+ export { createSignedFetcher };
27
+ //# sourceMappingURL=fetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAErE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,QAAA,MAAM,mBAAmB,GACvB,QAAQ,MAAM,EACd,UAAS,oBAAyB,KACjC,OAAO,KAOT,CAAC;AAEF,YAAY,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAAE,mBAAmB,EAAE,CAAC"}
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSignedFetcher = void 0;
4
+ /**
5
+ * Create a drop-in `fetch` function that signs every request with the given
6
+ * {@link Signer | `Signer`} before sending it.
7
+ *
8
+ * The returned function has the same signature as the global `fetch`, so it can
9
+ * be passed to libraries that accept a custom `fetch` implementation, or used
10
+ * directly.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { SigV4Signer } from '@aws-lambda-powertools/signer/sigv4';
15
+ * import { createSignedFetcher } from '@aws-lambda-powertools/signer/fetch';
16
+ *
17
+ * const signer = new SigV4Signer({ service: 'execute-api' });
18
+ * const signedFetch = createSignedFetcher(signer);
19
+ *
20
+ * const response = await signedFetch('https://example.execute-api.us-east-1.amazonaws.com/items');
21
+ * ```
22
+ *
23
+ * @param signer - The signer used to sign each request before it is sent.
24
+ * @param options - Optional configuration, e.g. a custom `fetch` implementation.
25
+ */
26
+ const createSignedFetcher = (signer, options = {}) => {
27
+ const fetchImpl = options.fetch ?? fetch;
28
+ return async (input, init) => {
29
+ const signed = await signer.sign(input, init);
30
+ return fetchImpl(signed);
31
+ };
32
+ };
33
+ exports.createSignedFetcher = createSignedFetcher;
@@ -0,0 +1 @@
1
+ { "type": "commonjs" }
@@ -0,0 +1,3 @@
1
+ export { SigV4Signer } from './SigV4Signer.js';
2
+ export type { Signer, SigV4SignerOptions } from './types/index.js';
3
+ //# sourceMappingURL=sigv4.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sigv4.d.ts","sourceRoot":"","sources":["../../src/sigv4.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,YAAY,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SigV4Signer = void 0;
4
+ var SigV4Signer_js_1 = require("./SigV4Signer.js");
5
+ Object.defineProperty(exports, "SigV4Signer", { enumerable: true, get: function () { return SigV4Signer_js_1.SigV4Signer; } });
@@ -0,0 +1,60 @@
1
+ import type { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@smithy/types';
2
+ /**
3
+ * A request signer.
4
+ *
5
+ * This is the structural contract that every signing variant (e.g. SigV4, and
6
+ * future variants such as SigV4a) implements, and the contract that the
7
+ * `createSignedFetcher` factory depends on.
8
+ *
9
+ * Implementations take a web-standard request and return a signed
10
+ * web-standard {@link Request | `Request`}, performing no network I/O.
11
+ */
12
+ interface Signer {
13
+ /**
14
+ * Sign a request and return a new, signed {@link Request | `Request`}.
15
+ *
16
+ * @param input - The resource to sign, as a URL string, {@link URL | `URL`}, or {@link Request | `Request`}.
17
+ * @param init - Optional request options, matching the `fetch` `init` argument.
18
+ */
19
+ sign(input: string | URL | Request, init?: RequestInit): Promise<Request>;
20
+ }
21
+ /**
22
+ * Options for constructing a {@link Signer | `Signer`} that uses the AWS
23
+ * Signature Version 4 signing process.
24
+ */
25
+ interface SigV4SignerOptions {
26
+ /**
27
+ * The service name to use when signing the request, e.g. `execute-api`,
28
+ * `lambda`, or `appsync`.
29
+ *
30
+ * This value cannot be reliably derived at runtime (custom domains and
31
+ * CloudFront hide the underlying service), so it is required.
32
+ */
33
+ service: string;
34
+ /**
35
+ * The AWS region to use when signing the request.
36
+ *
37
+ * @default process.env.AWS_REGION
38
+ */
39
+ region?: string;
40
+ /**
41
+ * The credentials to use when signing the request, either as a static
42
+ * value or as a provider that resolves them.
43
+ *
44
+ * @default credentials read from the standard Lambda environment variables
45
+ */
46
+ credentials?: AwsCredentialIdentity | AwsCredentialIdentityProvider;
47
+ }
48
+ /**
49
+ * Options for the `createSignedFetcher` factory.
50
+ */
51
+ interface SignedFetcherOptions {
52
+ /**
53
+ * The `fetch` implementation to use when sending the signed request.
54
+ *
55
+ * @default the global `fetch`
56
+ */
57
+ fetch?: typeof fetch;
58
+ }
59
+ export type { SignedFetcherOptions, Signer, SigV4SignerOptions };
60
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qBAAqB,EACrB,6BAA6B,EAC9B,MAAM,eAAe,CAAC;AAEvB;;;;;;;;;GASG;AACH,UAAU,MAAM;IACd;;;;;OAKG;IACH,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3E;AAED;;;GAGG;AACH,UAAU,kBAAkB;IAC1B;;;;;;OAMG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,qBAAqB,GAAG,6BAA6B,CAAC;CACrE;AAED;;GAEG;AACH,UAAU,oBAAoB;IAC5B;;;;OAIG;IACH,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,YAAY,EAAE,oBAAoB,EAAE,MAAM,EAAE,kBAAkB,EAAE,CAAC"}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,21 @@
1
+ import type { Checksum, SourceData } from '@smithy/types';
2
+ /**
3
+ * A {@link Checksum | `Checksum`} implementation backed by `node:crypto`.
4
+ *
5
+ * The underlying signing process expects a hash constructor that supports both
6
+ * plain SHA-256 (for hashing payloads) and HMAC-SHA256 with a secret (for
7
+ * deriving the signing key). Using `node:crypto` avoids pulling in a
8
+ * third-party crypto dependency, relying instead on the Node.js runtime that
9
+ * AWS Lambda provides.
10
+ *
11
+ * @internal
12
+ */
13
+ declare class Sha256 implements Checksum {
14
+ #private;
15
+ constructor(secret?: SourceData);
16
+ update(data: SourceData): void;
17
+ digest(): Promise<Uint8Array>;
18
+ reset(): void;
19
+ }
20
+ export { Sha256 };
21
+ //# sourceMappingURL=Sha256.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Sha256.d.ts","sourceRoot":"","sources":["../../src/Sha256.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAsB1D;;;;;;;;;;GAUG;AACH,cAAM,MAAO,YAAW,QAAQ;;gBAGX,MAAM,CAAC,EAAE,UAAU;IAO/B,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,IAAI;IAIxB,MAAM,IAAI,OAAO,CAAC,UAAU,CAAC;IAInC,KAAK,IAAI,IAAI;CAIrB;AAED,OAAO,EAAE,MAAM,EAAE,CAAC"}
@@ -0,0 +1,51 @@
1
+ import { createHash, createHmac } from 'node:crypto';
2
+ /**
3
+ * Convert smithy's {@link SourceData | `SourceData`} into a value accepted by
4
+ * `node:crypto`.
5
+ *
6
+ * `SourceData` is `string | ArrayBuffer | ArrayBufferView`, while `node:crypto`
7
+ * accepts `string | NodeJS.ArrayBufferView` - it rejects a bare `ArrayBuffer`
8
+ * at runtime, and TypeScript's structural `ArrayBufferView` is not assignable
9
+ * to Node's concrete union of typed arrays. Wrapping non-string inputs in a
10
+ * `Uint8Array` bridges both gaps without copying the underlying bytes.
11
+ */
12
+ const toBinary = (data) => {
13
+ if (typeof data === 'string') {
14
+ return data;
15
+ }
16
+ if (ArrayBuffer.isView(data)) {
17
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
18
+ }
19
+ return new Uint8Array(data);
20
+ };
21
+ /**
22
+ * A {@link Checksum | `Checksum`} implementation backed by `node:crypto`.
23
+ *
24
+ * The underlying signing process expects a hash constructor that supports both
25
+ * plain SHA-256 (for hashing payloads) and HMAC-SHA256 with a secret (for
26
+ * deriving the signing key). Using `node:crypto` avoids pulling in a
27
+ * third-party crypto dependency, relying instead on the Node.js runtime that
28
+ * AWS Lambda provides.
29
+ *
30
+ * @internal
31
+ */
32
+ class Sha256 {
33
+ #hash;
34
+ constructor(secret) {
35
+ this.#hash =
36
+ secret === undefined
37
+ ? createHash('sha256')
38
+ : createHmac('sha256', toBinary(secret));
39
+ }
40
+ update(data) {
41
+ this.#hash.update(toBinary(data));
42
+ }
43
+ async digest() {
44
+ return new Uint8Array(this.#hash.digest());
45
+ }
46
+ reset() {
47
+ // `node:crypto` hashes are single-use; reset is a no-op because a new
48
+ // instance is created per hashing operation by the signing process.
49
+ }
50
+ }
51
+ export { Sha256 };
@@ -0,0 +1,24 @@
1
+ import type { Signer, SigV4SignerOptions } from './types/index.js';
2
+ /**
3
+ * A {@link Signer | `Signer`} that signs requests using the AWS Signature
4
+ * Version 4 (SigV4) signing process.
5
+ *
6
+ * The signer takes and returns web-standard {@link Request | `Request`}
7
+ * objects and performs no network I/O. To send signed requests, pass an
8
+ * instance to `createSignedFetcher` from `@aws-lambda-powertools/signer/fetch`.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { SigV4Signer } from '@aws-lambda-powertools/signer/sigv4';
13
+ *
14
+ * const signer = new SigV4Signer({ service: 'execute-api' });
15
+ * const signed = await signer.sign('https://example.execute-api.us-east-1.amazonaws.com/items');
16
+ * ```
17
+ */
18
+ declare class SigV4Signer implements Signer {
19
+ #private;
20
+ constructor(options: SigV4SignerOptions);
21
+ sign(input: string | URL | Request, init?: RequestInit): Promise<Request>;
22
+ }
23
+ export { SigV4Signer };
24
+ //# sourceMappingURL=SigV4Signer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SigV4Signer.d.ts","sourceRoot":"","sources":["../../src/SigV4Signer.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAyBnE;;;;;;;;;;;;;;;GAeG;AACH,cAAM,WAAY,YAAW,MAAM;;gBAKd,OAAO,EAAE,kBAAkB;IAcjC,IAAI,CACf,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,EAC7B,IAAI,CAAC,EAAE,WAAW,GACjB,OAAO,CAAC,OAAO,CAAC;CAgHpB;AAED,OAAO,EAAE,WAAW,EAAE,CAAC"}
@@ -0,0 +1,151 @@
1
+ import { SignatureV4 } from '@smithy/signature-v4';
2
+ import { RequestSigningError, SignerConfigError } from './errors.js';
3
+ import { Sha256 } from './Sha256.js';
4
+ /**
5
+ * Credential provider that reads AWS credentials from the standard environment
6
+ * variables that the AWS Lambda runtime always injects.
7
+ *
8
+ * Throws a {@link SignerConfigError | `SignerConfigError`} when the required
9
+ * variables are not present, e.g. when running outside of Lambda.
10
+ */
11
+ const credentialsFromEnv = async () => {
12
+ const accessKeyId = process.env.AWS_ACCESS_KEY_ID;
13
+ const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
14
+ if (accessKeyId === undefined || secretAccessKey === undefined) {
15
+ throw new SignerConfigError('Unable to resolve AWS credentials to sign the request with. Ensure the standard AWS credentials environment variables are set, or pass the `credentials` option.');
16
+ }
17
+ return {
18
+ accessKeyId,
19
+ secretAccessKey,
20
+ sessionToken: process.env.AWS_SESSION_TOKEN,
21
+ };
22
+ };
23
+ /**
24
+ * A {@link Signer | `Signer`} that signs requests using the AWS Signature
25
+ * Version 4 (SigV4) signing process.
26
+ *
27
+ * The signer takes and returns web-standard {@link Request | `Request`}
28
+ * objects and performs no network I/O. To send signed requests, pass an
29
+ * instance to `createSignedFetcher` from `@aws-lambda-powertools/signer/fetch`.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * import { SigV4Signer } from '@aws-lambda-powertools/signer/sigv4';
34
+ *
35
+ * const signer = new SigV4Signer({ service: 'execute-api' });
36
+ * const signed = await signer.sign('https://example.execute-api.us-east-1.amazonaws.com/items');
37
+ * ```
38
+ */
39
+ class SigV4Signer {
40
+ #service;
41
+ #region;
42
+ #credentials;
43
+ constructor(options) {
44
+ this.#service = options.service;
45
+ const region = options.region ?? process.env.AWS_REGION;
46
+ if (region === undefined || region === '') {
47
+ throw new SignerConfigError('Unable to determine the AWS region to sign the request with. Set the `region` option or the `AWS_REGION` environment variable.');
48
+ }
49
+ this.#region = region;
50
+ this.#credentials = options.credentials ?? credentialsFromEnv;
51
+ }
52
+ async sign(input, init) {
53
+ const request = new Request(input, init);
54
+ const credentials = await this.#resolveCredentials();
55
+ const httpRequest = await this.#toHttpRequest(request);
56
+ const signer = new SignatureV4({
57
+ service: this.#service,
58
+ region: this.#region,
59
+ credentials,
60
+ sha256: Sha256,
61
+ });
62
+ let signed;
63
+ try {
64
+ signed = (await signer.sign(httpRequest));
65
+ }
66
+ catch (error) {
67
+ throw new RequestSigningError('Failed to sign the request', {
68
+ cause: error,
69
+ });
70
+ }
71
+ return this.#toRequest(signed, request);
72
+ }
73
+ /**
74
+ * Resolve the configured credentials, supporting both static values and
75
+ * async providers. The default env-var provider throws a configuration error
76
+ * when no credentials are available.
77
+ */
78
+ async #resolveCredentials() {
79
+ return typeof this.#credentials === 'function'
80
+ ? await this.#credentials()
81
+ : this.#credentials;
82
+ }
83
+ /**
84
+ * Adapt a web-standard `Request` into the `HttpRequest` shape expected by the
85
+ * underlying signing process, buffering the body so it can be hashed.
86
+ *
87
+ * The signing process accepts a plain object matching the `HttpRequest`
88
+ * interface, so we avoid depending on `@smithy/protocol-http` just to
89
+ * construct one.
90
+ */
91
+ async #toHttpRequest(request) {
92
+ const url = new URL(request.url);
93
+ const headers = {};
94
+ for (const [key, value] of request.headers) {
95
+ headers[key] = value;
96
+ }
97
+ headers.host = url.host;
98
+ const query = {};
99
+ for (const [key, value] of url.searchParams) {
100
+ query[key] = value;
101
+ }
102
+ const body = await this.#readBody(request);
103
+ return {
104
+ method: request.method,
105
+ protocol: url.protocol,
106
+ hostname: url.hostname,
107
+ port: url.port ? Number(url.port) : undefined,
108
+ path: url.pathname,
109
+ query,
110
+ headers,
111
+ body,
112
+ };
113
+ }
114
+ /**
115
+ * Buffer the request body so it can be both hashed for signing and replayed
116
+ * when the signed request is sent.
117
+ *
118
+ * Most bodies (strings, buffers, and finite streams) are buffered
119
+ * transparently. A body that cannot be read or replayed — for example a
120
+ * stream that errors mid-read — cannot be signed and results in a
121
+ * {@link RequestSigningError | `RequestSigningError`}.
122
+ */
123
+ async #readBody(request) {
124
+ if (request.body === null || request.body === undefined) {
125
+ return undefined;
126
+ }
127
+ try {
128
+ const buffer = await request.clone().arrayBuffer();
129
+ return buffer.byteLength === 0 ? undefined : new Uint8Array(buffer);
130
+ }
131
+ catch (error) {
132
+ throw new RequestSigningError('Unable to read the request body to sign it. The body could not be buffered, for example because it is a stream that cannot be replayed.', { cause: error });
133
+ }
134
+ }
135
+ /**
136
+ * Adapt a signed `HttpRequest` back into a web-standard `Request`, carrying
137
+ * over the signed headers and the original (buffered) body.
138
+ */
139
+ #toRequest(signed, original) {
140
+ const headers = new Headers();
141
+ for (const [key, value] of Object.entries(signed.headers)) {
142
+ headers.set(key, value);
143
+ }
144
+ return new Request(original.url, {
145
+ method: signed.method,
146
+ headers,
147
+ body: signed.body,
148
+ });
149
+ }
150
+ }
151
+ export { SigV4Signer };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Base error for all errors thrown by the signer utility.
3
+ *
4
+ * Generally this error should not be thrown directly; prefer the more specific
5
+ * {@link SignerConfigError | `SignerConfigError`} and
6
+ * {@link RequestSigningError | `RequestSigningError`} subclasses.
7
+ */
8
+ declare class SignerError extends Error {
9
+ constructor(message: string, options?: ErrorOptions);
10
+ }
11
+ /**
12
+ * Error thrown when the signer is misconfigured.
13
+ *
14
+ * This is thrown eagerly at construction when the region cannot be determined,
15
+ * and lazily during signing when credentials are missing or cannot be resolved.
16
+ */
17
+ declare class SignerConfigError extends SignerError {
18
+ constructor(message: string, options?: ErrorOptions);
19
+ }
20
+ /**
21
+ * Error thrown when signing a request fails.
22
+ *
23
+ * This wraps errors thrown by the underlying signing process. The original
24
+ * error, when available, is preserved on the `cause` property.
25
+ */
26
+ declare class RequestSigningError extends SignerError {
27
+ constructor(message: string, options?: ErrorOptions);
28
+ }
29
+ export { RequestSigningError, SignerConfigError, SignerError };
30
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,cAAM,WAAY,SAAQ,KAAK;gBACV,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAI3D;AAED;;;;;GAKG;AACH,cAAM,iBAAkB,SAAQ,WAAW;gBACtB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAI3D;AAED;;;;;GAKG;AACH,cAAM,mBAAoB,SAAQ,WAAW;gBACxB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAQ3D;AAED,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,WAAW,EAAE,CAAC"}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Base error for all errors thrown by the signer utility.
3
+ *
4
+ * Generally this error should not be thrown directly; prefer the more specific
5
+ * {@link SignerConfigError | `SignerConfigError`} and
6
+ * {@link RequestSigningError | `RequestSigningError`} subclasses.
7
+ */
8
+ class SignerError extends Error {
9
+ constructor(message, options) {
10
+ super(message, options);
11
+ this.name = 'SignerError';
12
+ }
13
+ }
14
+ /**
15
+ * Error thrown when the signer is misconfigured.
16
+ *
17
+ * This is thrown eagerly at construction when the region cannot be determined,
18
+ * and lazily during signing when credentials are missing or cannot be resolved.
19
+ */
20
+ class SignerConfigError extends SignerError {
21
+ constructor(message, options) {
22
+ super(message, options);
23
+ this.name = 'SignerConfigError';
24
+ }
25
+ }
26
+ /**
27
+ * Error thrown when signing a request fails.
28
+ *
29
+ * This wraps errors thrown by the underlying signing process. The original
30
+ * error, when available, is preserved on the `cause` property.
31
+ */
32
+ class RequestSigningError extends SignerError {
33
+ constructor(message, options) {
34
+ const errorMessage = options?.cause instanceof Error
35
+ ? `${message}. This error was caused by: ${options.cause.message}.`
36
+ : message;
37
+ super(errorMessage, options);
38
+ this.name = 'RequestSigningError';
39
+ }
40
+ }
41
+ export { RequestSigningError, SignerConfigError, SignerError };
@@ -0,0 +1,27 @@
1
+ import type { SignedFetcherOptions, Signer } from './types/index.js';
2
+ /**
3
+ * Create a drop-in `fetch` function that signs every request with the given
4
+ * {@link Signer | `Signer`} before sending it.
5
+ *
6
+ * The returned function has the same signature as the global `fetch`, so it can
7
+ * be passed to libraries that accept a custom `fetch` implementation, or used
8
+ * directly.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { SigV4Signer } from '@aws-lambda-powertools/signer/sigv4';
13
+ * import { createSignedFetcher } from '@aws-lambda-powertools/signer/fetch';
14
+ *
15
+ * const signer = new SigV4Signer({ service: 'execute-api' });
16
+ * const signedFetch = createSignedFetcher(signer);
17
+ *
18
+ * const response = await signedFetch('https://example.execute-api.us-east-1.amazonaws.com/items');
19
+ * ```
20
+ *
21
+ * @param signer - The signer used to sign each request before it is sent.
22
+ * @param options - Optional configuration, e.g. a custom `fetch` implementation.
23
+ */
24
+ declare const createSignedFetcher: (signer: Signer, options?: SignedFetcherOptions) => typeof fetch;
25
+ export type { SignedFetcherOptions, Signer } from './types/index.js';
26
+ export { createSignedFetcher };
27
+ //# sourceMappingURL=fetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAErE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,QAAA,MAAM,mBAAmB,GACvB,QAAQ,MAAM,EACd,UAAS,oBAAyB,KACjC,OAAO,KAOT,CAAC;AAEF,YAAY,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAAE,mBAAmB,EAAE,CAAC"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Create a drop-in `fetch` function that signs every request with the given
3
+ * {@link Signer | `Signer`} before sending it.
4
+ *
5
+ * The returned function has the same signature as the global `fetch`, so it can
6
+ * be passed to libraries that accept a custom `fetch` implementation, or used
7
+ * directly.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { SigV4Signer } from '@aws-lambda-powertools/signer/sigv4';
12
+ * import { createSignedFetcher } from '@aws-lambda-powertools/signer/fetch';
13
+ *
14
+ * const signer = new SigV4Signer({ service: 'execute-api' });
15
+ * const signedFetch = createSignedFetcher(signer);
16
+ *
17
+ * const response = await signedFetch('https://example.execute-api.us-east-1.amazonaws.com/items');
18
+ * ```
19
+ *
20
+ * @param signer - The signer used to sign each request before it is sent.
21
+ * @param options - Optional configuration, e.g. a custom `fetch` implementation.
22
+ */
23
+ const createSignedFetcher = (signer, options = {}) => {
24
+ const fetchImpl = options.fetch ?? fetch;
25
+ return async (input, init) => {
26
+ const signed = await signer.sign(input, init);
27
+ return fetchImpl(signed);
28
+ };
29
+ };
30
+ export { createSignedFetcher };
@@ -0,0 +1 @@
1
+ { "type": "module" }
@@ -0,0 +1,3 @@
1
+ export { SigV4Signer } from './SigV4Signer.js';
2
+ export type { Signer, SigV4SignerOptions } from './types/index.js';
3
+ //# sourceMappingURL=sigv4.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sigv4.d.ts","sourceRoot":"","sources":["../../src/sigv4.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,YAAY,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1 @@
1
+ export { SigV4Signer } from './SigV4Signer.js';
@@ -0,0 +1,60 @@
1
+ import type { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@smithy/types';
2
+ /**
3
+ * A request signer.
4
+ *
5
+ * This is the structural contract that every signing variant (e.g. SigV4, and
6
+ * future variants such as SigV4a) implements, and the contract that the
7
+ * `createSignedFetcher` factory depends on.
8
+ *
9
+ * Implementations take a web-standard request and return a signed
10
+ * web-standard {@link Request | `Request`}, performing no network I/O.
11
+ */
12
+ interface Signer {
13
+ /**
14
+ * Sign a request and return a new, signed {@link Request | `Request`}.
15
+ *
16
+ * @param input - The resource to sign, as a URL string, {@link URL | `URL`}, or {@link Request | `Request`}.
17
+ * @param init - Optional request options, matching the `fetch` `init` argument.
18
+ */
19
+ sign(input: string | URL | Request, init?: RequestInit): Promise<Request>;
20
+ }
21
+ /**
22
+ * Options for constructing a {@link Signer | `Signer`} that uses the AWS
23
+ * Signature Version 4 signing process.
24
+ */
25
+ interface SigV4SignerOptions {
26
+ /**
27
+ * The service name to use when signing the request, e.g. `execute-api`,
28
+ * `lambda`, or `appsync`.
29
+ *
30
+ * This value cannot be reliably derived at runtime (custom domains and
31
+ * CloudFront hide the underlying service), so it is required.
32
+ */
33
+ service: string;
34
+ /**
35
+ * The AWS region to use when signing the request.
36
+ *
37
+ * @default process.env.AWS_REGION
38
+ */
39
+ region?: string;
40
+ /**
41
+ * The credentials to use when signing the request, either as a static
42
+ * value or as a provider that resolves them.
43
+ *
44
+ * @default credentials read from the standard Lambda environment variables
45
+ */
46
+ credentials?: AwsCredentialIdentity | AwsCredentialIdentityProvider;
47
+ }
48
+ /**
49
+ * Options for the `createSignedFetcher` factory.
50
+ */
51
+ interface SignedFetcherOptions {
52
+ /**
53
+ * The `fetch` implementation to use when sending the signed request.
54
+ *
55
+ * @default the global `fetch`
56
+ */
57
+ fetch?: typeof fetch;
58
+ }
59
+ export type { SignedFetcherOptions, Signer, SigV4SignerOptions };
60
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qBAAqB,EACrB,6BAA6B,EAC9B,MAAM,eAAe,CAAC;AAEvB;;;;;;;;;GASG;AACH,UAAU,MAAM;IACd;;;;;OAKG;IACH,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3E;AAED;;;GAGG;AACH,UAAU,kBAAkB;IAC1B;;;;;;OAMG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,qBAAqB,GAAG,6BAA6B,CAAC;CACrE;AAED;;GAEG;AACH,UAAU,oBAAoB;IAC5B;;;;OAIG;IACH,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,YAAY,EAAE,oBAAoB,EAAE,MAAM,EAAE,kBAAkB,EAAE,CAAC"}
package/package.json CHANGED
@@ -1,20 +1,101 @@
1
1
  {
2
2
  "name": "@aws-lambda-powertools/signer",
3
- "version": "0.0.0",
4
- "description": "The signer package for the Powertools for AWS Lambda (TypeScript) library",
5
- "author": { "name": "Amazon Web Services", "url": "https://aws.amazon.com" },
6
- "publishConfig": { "access": "public" },
7
- "homepage": "https://github.com/aws-powertools/powertools-lambda-typescript",
3
+ "version": "2.34.0",
4
+ "description": "The signer package for the Powertools for AWS Lambda (TypeScript) library.",
5
+ "author": {
6
+ "name": "Amazon Web Services",
7
+ "url": "https://aws.amazon.com"
8
+ },
8
9
  "license": "MIT-0",
9
- "main": "./lib/index.js",
10
- "types": "./lib/index.d.ts",
11
- "files": ["lib"],
10
+ "homepage": "https://github.com/aws-powertools/powertools-lambda-typescript/tree/main/packages/signer#readme",
12
11
  "repository": {
13
12
  "type": "git",
14
13
  "url": "git+https://github.com/aws-powertools/powertools-lambda-typescript.git"
15
14
  },
16
- "bugs": { "url": "https://github.com/aws-powertools/powertools-lambda-typescript/issues" },
17
- "dependencies": {},
18
- "keywords": ["aws", "lambda", "powertools", "handler", "nodejs", "serverless"],
19
- "devDependencies": {}
20
- }
15
+ "bugs": {
16
+ "url": "https://github.com/aws-powertools/powertools-lambda-typescript/issues"
17
+ },
18
+ "keywords": [
19
+ "aws",
20
+ "lambda",
21
+ "powertools",
22
+ "signer",
23
+ "sigv4",
24
+ "signature-v4",
25
+ "iam",
26
+ "fetch",
27
+ "serverless",
28
+ "typescript",
29
+ "nodejs"
30
+ ],
31
+ "dependencies": {
32
+ "@smithy/signature-v4": "^5.4.6",
33
+ "@smithy/types": "^4.14.3"
34
+ },
35
+ "files": [
36
+ "lib"
37
+ ],
38
+ "type": "module",
39
+ "exports": {
40
+ "./sigv4": {
41
+ "require": {
42
+ "types": "./lib/cjs/sigv4.d.ts",
43
+ "default": "./lib/cjs/sigv4.js"
44
+ },
45
+ "import": {
46
+ "types": "./lib/esm/sigv4.d.ts",
47
+ "default": "./lib/esm/sigv4.js"
48
+ }
49
+ },
50
+ "./fetch": {
51
+ "require": {
52
+ "types": "./lib/cjs/fetch.d.ts",
53
+ "default": "./lib/cjs/fetch.js"
54
+ },
55
+ "import": {
56
+ "types": "./lib/esm/fetch.d.ts",
57
+ "default": "./lib/esm/fetch.js"
58
+ }
59
+ },
60
+ "./errors": {
61
+ "require": {
62
+ "types": "./lib/cjs/errors.d.ts",
63
+ "default": "./lib/cjs/errors.js"
64
+ },
65
+ "import": {
66
+ "types": "./lib/esm/errors.d.ts",
67
+ "default": "./lib/esm/errors.js"
68
+ }
69
+ },
70
+ "./types": {
71
+ "require": {
72
+ "types": "./lib/cjs/types/index.d.ts",
73
+ "default": "./lib/cjs/types/index.js"
74
+ },
75
+ "import": {
76
+ "types": "./lib/esm/types/index.d.ts",
77
+ "default": "./lib/esm/types/index.js"
78
+ }
79
+ }
80
+ },
81
+ "typesVersions": {
82
+ "*": {
83
+ "sigv4": [
84
+ "lib/cjs/sigv4.d.ts",
85
+ "lib/esm/sigv4.d.ts"
86
+ ],
87
+ "fetch": [
88
+ "lib/cjs/fetch.d.ts",
89
+ "lib/esm/fetch.d.ts"
90
+ ],
91
+ "errors": [
92
+ "lib/cjs/errors.d.ts",
93
+ "lib/esm/errors.d.ts"
94
+ ],
95
+ "types": [
96
+ "lib/cjs/types/index.d.ts",
97
+ "lib/esm/types/index.d.ts"
98
+ ]
99
+ }
100
+ }
101
+ }
package/lib/index.js DELETED
@@ -1,3 +0,0 @@
1
- console.log(
2
- 'This is a placeholder package used to reserve the @aws-lambda-powertools/signer package name, please do not use it.'
3
- );
File without changes