@adobe/aio-commerce-lib-auth 0.1.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.
@@ -0,0 +1,18 @@
1
+
2
+ > @adobe/aio-commerce-lib-auth@0.1.0 build /home/runner/work/aio-commerce-sdk/aio-commerce-sdk/packages/aio-commerce-lib-auth
3
+ > tsdown
4
+
5
+ ℹ tsdown v0.12.9 powered by rolldown v1.0.0-beta.21
6
+ ℹ Using tsdown config: /home/runner/work/aio-commerce-sdk/aio-commerce-sdk/packages/aio-commerce-lib-auth/tsdown.config.ts
7
+ ℹ entry: source/index.ts
8
+ ℹ target: node22.0.0
9
+ ℹ tsconfig: tsconfig.json
10
+ ℹ Build start
11
+ ℹ [CJS] dist/cjs/index.cjs 4.81 kB │ gzip: 1.71 kB
12
+ ℹ [CJS] 1 files, total: 4.81 kB
13
+ ℹ [CJS] dist/index.d.cts 2.33 kB │ gzip: 0.69 kB
14
+ ℹ [CJS] 1 files, total: 2.33 kB
15
+ ℹ [ESM] dist/es/index.js 3.63 kB │ gzip: 1.27 kB
16
+ ℹ [ESM] dist/es/index.d.ts 2.33 kB │ gzip: 0.69 kB
17
+ ℹ [ESM] 2 files, total: 5.97 kB
18
+ ✔ Build complete in 1768ms
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @adobe/aio-commerce-lib-auth
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#11](https://github.com/adobe/aio-commerce-sdk/pull/11) [`97e031f`](https://github.com/adobe/aio-commerce-sdk/commit/97e031ffc19d882293653c5bbbb0210a6d0199b2) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Initial alpha release. This release is not yet ready for use yet. You may be able to install it, but if you do, expect breaking changes.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Adobe
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # `@adobe/aio-commerce-lib-auth`
2
+
3
+ > [!WARNING]
4
+ > This package is a work in progress and is not yet ready for use yet. You may be able to install it, but if you do, expect breaking changes.
5
+
6
+ Authentication utilities for Adobe Commerce apps deployed in Adobe App Builder.
7
+
8
+ This library provides a unified interface for authentication in Adobe Commerce App Builder applications, supporting multiple authentication mechanisms required for different integration scenarios.
9
+
10
+ ## Overview
11
+
12
+ The library supports two main authentication providers:
13
+
14
+ - **IMS Provider**: For authenticating users or services via Adobe Identity Management System (IMS) using OAuth2
15
+ - **Integrations Provider**: For authenticating with Adobe Commerce integrations using OAuth 1.0a
16
+
17
+ These providers abstract the complexity of authentication, making it easy to obtain and use access tokens in your App Builder applications.
18
+
19
+ ## Installation
20
+
21
+ ```shell
22
+ pnpm install @adobe/aio-commerce-lib-auth
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ In your App Builder application, you can use the library to authenticate users or services and obtain access tokens.
28
+
29
+ ### IMS Provider
30
+
31
+ In the runtime action you can generate an access token using the IMS Provider:
32
+
33
+ ```typescript
34
+ import { getImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
35
+
36
+ export const main = async function (params: Record<string, unknown>) {
37
+ // Generate the needed headers for API requests
38
+ const imsAuth = getImsAuthProvider(params);
39
+ const headers = await imsAuth.getHeaders();
40
+
41
+ return { statusCode: 200 };
42
+ };
43
+ ```
44
+
45
+ ### Integrations Provider
46
+
47
+ In the runtime action you can generate an access token using the Integrations Provider:
48
+
49
+ ```typescript
50
+ import { getIntegrationsAuthProvider } from "@adobe/aio-commerce-lib-auth";
51
+
52
+ export const main = async function (params: Record<string, unknown>) {
53
+ // Generate the needed headers for API requests
54
+ const integrationsAuth = getIntegrationsAuthProvider(params);
55
+ const headers = integrationsAuth.getHeaders(
56
+ "GET",
57
+ "http://localhost/rest/V1/orders",
58
+ );
59
+
60
+ return { statusCode: 200 };
61
+ };
62
+ ```
63
+
64
+ ## Contributing
65
+
66
+ This package is part of the Adobe Commerce SDK monorepo. See the [Contributing Guide](../../.github/CONTRIBUTING.md) and [Development Guide](../../.github/DEVELOPMENT.md) for development setup and guidelines.
@@ -0,0 +1,135 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+ const __adobe_aio_lib_ims = __toESM(require("@adobe/aio-lib-ims"));
25
+ const node_crypto = __toESM(require("node:crypto"));
26
+ const oauth_1_0a = __toESM(require("oauth-1.0a"));
27
+
28
+ //#region source/lib/params.ts
29
+ /**
30
+ * Checks if the given value is non-empty.
31
+ *
32
+ * @param name of the parameter. Required because of `aio app dev` compatibility: inputs mapped to undefined env vars come as $<input_name> in dev mode, but as '' in prod mode.
33
+ * @param value of the parameter.
34
+ */
35
+ function nonEmpty(name, value) {
36
+ const v = value?.trim();
37
+ return v !== void 0 && v !== `$${name}`;
38
+ }
39
+ /**
40
+ * Checks if all required parameters are non-empty.
41
+ * @param params action input parameters.
42
+ * @param required list of required parameter names.
43
+ */
44
+ function allNonEmpty(params, required) {
45
+ return required.every((name) => nonEmpty(name, params[name]));
46
+ }
47
+
48
+ //#endregion
49
+ //#region source/lib/ims-auth.ts
50
+ /**
51
+ * If the required IMS parameters are present, this function returns an {@link ImsAuthProvider}.
52
+ * @param params includes IMS parameters
53
+ */
54
+ async function getImsAuthProvider(params) {
55
+ const config = resolveImsConfig(params);
56
+ if (config) {
57
+ const contextName = params.AIO_COMMERCE_IMS_CTX ?? "aio-commerce-sdk-creds";
58
+ await __adobe_aio_lib_ims.context.set(contextName, config);
59
+ return {
60
+ getAccessToken: async () => (0, __adobe_aio_lib_ims.getToken)(contextName, {}),
61
+ getHeaders: async () => {
62
+ const accessToken = await (0, __adobe_aio_lib_ims.getToken)(contextName, {});
63
+ return {
64
+ Authorization: `Bearer ${accessToken}`,
65
+ "x-api-key": config.client_id
66
+ };
67
+ }
68
+ };
69
+ }
70
+ }
71
+ function resolveImsConfig(params) {
72
+ if (allNonEmpty(params, [
73
+ "AIO_COMMERCE_IMS_CLIENT_ID",
74
+ "AIO_COMMERCE_IMS_CLIENT_SECRETS",
75
+ "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_ID",
76
+ "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_EMAIL",
77
+ "AIO_COMMERCE_IMS_IMS_ORG_ID",
78
+ "AIO_COMMERCE_IMS_SCOPES"
79
+ ])) return {
80
+ client_id: params.AIO_COMMERCE_IMS_CLIENT_ID,
81
+ client_secrets: JSON.parse(params.AIO_COMMERCE_IMS_CLIENT_SECRETS ?? "[]"),
82
+ technical_account_id: params.AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_ID,
83
+ technical_account_email: params.AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_EMAIL,
84
+ ims_org_id: params.AIO_COMMERCE_IMS_IMS_ORG_ID,
85
+ scopes: JSON.parse(params.AIO_COMMERCE_IMS_SCOPES ?? "[]"),
86
+ environment: params.AIO_COMMERCE_IMS_ENV ?? "prod"
87
+ };
88
+ }
89
+
90
+ //#endregion
91
+ //#region source/lib/integration-auth.ts
92
+ /**
93
+ * If the required integration parameters are present, this function returns an {@link IntegrationAuthProvider}.
94
+ * @param params includes integration parameters
95
+ */
96
+ function getIntegrationAuthProvider(params) {
97
+ const config = resolveIntegrationConfig(params);
98
+ if (config) {
99
+ const oauth = new oauth_1_0a.default({
100
+ consumer: {
101
+ key: config.consumerKey,
102
+ secret: config.consumerSecret
103
+ },
104
+ signature_method: "HMAC-SHA256",
105
+ hash_function: (baseString, key) => node_crypto.default.createHmac("sha256", key).update(baseString).digest("base64")
106
+ });
107
+ const oauthToken = {
108
+ key: config.accessToken,
109
+ secret: config.accessTokenSecret
110
+ };
111
+ return { getHeaders(method, url) {
112
+ return oauth.toHeader(oauth.authorize({
113
+ url,
114
+ method
115
+ }, oauthToken));
116
+ } };
117
+ }
118
+ }
119
+ function resolveIntegrationConfig(params) {
120
+ if (allNonEmpty(params, [
121
+ "AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY",
122
+ "AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET",
123
+ "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN",
124
+ "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET"
125
+ ])) return {
126
+ consumerKey: params.AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY,
127
+ consumerSecret: params.AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET,
128
+ accessToken: params.AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN,
129
+ accessTokenSecret: params.AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET
130
+ };
131
+ }
132
+
133
+ //#endregion
134
+ exports.getImsAuthProvider = getImsAuthProvider;
135
+ exports.getIntegrationAuthProvider = getIntegrationAuthProvider;
@@ -0,0 +1,39 @@
1
+ import OAuth1a from "oauth-1.0a";
2
+
3
+ //#region source/lib/ims-auth.d.ts
4
+ declare const IMS_AUTH_HEADERS: readonly ["Authorization", "x-api-key"];
5
+ declare const IMS_AUTH_PARAMS: readonly ["AIO_COMMERCE_IMS_CLIENT_ID", "AIO_COMMERCE_IMS_CLIENT_SECRETS", "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_ID", "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_EMAIL", "AIO_COMMERCE_IMS_IMS_ORG_ID", "AIO_COMMERCE_IMS_SCOPES", "AIO_COMMERCE_IMS_ENV", "AIO_COMMERCE_IMS_CTX"];
6
+ type ImsAuthParam = (typeof IMS_AUTH_PARAMS)[number];
7
+ type ImsAuthParams = Partial<Record<ImsAuthParam, string>>;
8
+ type ImsAuthHeader = (typeof IMS_AUTH_HEADERS)[number];
9
+ type ImsAuthHeaders = Record<ImsAuthHeader, string>;
10
+ type ImsAccessToken = string;
11
+ interface ImsAuthProvider {
12
+ getHeaders: () => Promise<ImsAuthHeaders>;
13
+ getAccessToken: () => Promise<ImsAccessToken>;
14
+ }
15
+ declare function getImsAuthProvider(params: ImsAuthParams): Promise<{
16
+ getAccessToken: () => Promise<string>;
17
+ getHeaders: () => Promise<{
18
+ Authorization: string;
19
+ "x-api-key": string;
20
+ }>;
21
+ } | undefined>;
22
+ //#endregion
23
+ //#region source/lib/integration-auth.d.ts
24
+ declare const HTTP_METHODS: readonly ["GET", "POST", "PUT", "PATCH", "DELETE"];
25
+ declare const INTEGRATION_AUTH_HEADERS: readonly ["Authorization"];
26
+ declare const INTEGRATION_AUTH_PARAMS: readonly ["AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY", "AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET", "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN", "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET"];
27
+ type IntegrationAuthParam = (typeof INTEGRATION_AUTH_PARAMS)[number];
28
+ type IntegrationAuthParams = Partial<Record<IntegrationAuthParam, string>>;
29
+ type IntegrationAuthHeader = (typeof INTEGRATION_AUTH_HEADERS)[number];
30
+ type IntegrationAuthHeaders = Record<IntegrationAuthHeader, string>;
31
+ type HttpMethod = (typeof HTTP_METHODS)[number];
32
+ interface IntegrationAuthProvider {
33
+ getHeaders: (method: HttpMethod, url: string) => IntegrationAuthHeaders;
34
+ }
35
+ declare function getIntegrationAuthProvider(params: IntegrationAuthParams): {
36
+ getHeaders(method: HttpMethod, url: string): OAuth1a.Header;
37
+ } | undefined;
38
+ //#endregion
39
+ export { ImsAuthHeader, ImsAuthHeaders, ImsAuthParam, ImsAuthParams, ImsAuthProvider, IntegrationAuthHeader, IntegrationAuthHeaders, IntegrationAuthParam, IntegrationAuthParams, IntegrationAuthProvider, getImsAuthProvider, getIntegrationAuthProvider };
@@ -0,0 +1,39 @@
1
+ import OAuth1a from "oauth-1.0a";
2
+
3
+ //#region source/lib/ims-auth.d.ts
4
+ declare const IMS_AUTH_HEADERS: readonly ["Authorization", "x-api-key"];
5
+ declare const IMS_AUTH_PARAMS: readonly ["AIO_COMMERCE_IMS_CLIENT_ID", "AIO_COMMERCE_IMS_CLIENT_SECRETS", "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_ID", "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_EMAIL", "AIO_COMMERCE_IMS_IMS_ORG_ID", "AIO_COMMERCE_IMS_SCOPES", "AIO_COMMERCE_IMS_ENV", "AIO_COMMERCE_IMS_CTX"];
6
+ type ImsAuthParam = (typeof IMS_AUTH_PARAMS)[number];
7
+ type ImsAuthParams = Partial<Record<ImsAuthParam, string>>;
8
+ type ImsAuthHeader = (typeof IMS_AUTH_HEADERS)[number];
9
+ type ImsAuthHeaders = Record<ImsAuthHeader, string>;
10
+ type ImsAccessToken = string;
11
+ interface ImsAuthProvider {
12
+ getHeaders: () => Promise<ImsAuthHeaders>;
13
+ getAccessToken: () => Promise<ImsAccessToken>;
14
+ }
15
+ declare function getImsAuthProvider(params: ImsAuthParams): Promise<{
16
+ getAccessToken: () => Promise<string>;
17
+ getHeaders: () => Promise<{
18
+ Authorization: string;
19
+ "x-api-key": string;
20
+ }>;
21
+ } | undefined>;
22
+ //#endregion
23
+ //#region source/lib/integration-auth.d.ts
24
+ declare const HTTP_METHODS: readonly ["GET", "POST", "PUT", "PATCH", "DELETE"];
25
+ declare const INTEGRATION_AUTH_HEADERS: readonly ["Authorization"];
26
+ declare const INTEGRATION_AUTH_PARAMS: readonly ["AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY", "AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET", "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN", "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET"];
27
+ type IntegrationAuthParam = (typeof INTEGRATION_AUTH_PARAMS)[number];
28
+ type IntegrationAuthParams = Partial<Record<IntegrationAuthParam, string>>;
29
+ type IntegrationAuthHeader = (typeof INTEGRATION_AUTH_HEADERS)[number];
30
+ type IntegrationAuthHeaders = Record<IntegrationAuthHeader, string>;
31
+ type HttpMethod = (typeof HTTP_METHODS)[number];
32
+ interface IntegrationAuthProvider {
33
+ getHeaders: (method: HttpMethod, url: string) => IntegrationAuthHeaders;
34
+ }
35
+ declare function getIntegrationAuthProvider(params: IntegrationAuthParams): {
36
+ getHeaders(method: HttpMethod, url: string): OAuth1a.Header;
37
+ } | undefined;
38
+ //#endregion
39
+ export { ImsAuthHeader, ImsAuthHeaders, ImsAuthParam, ImsAuthParams, ImsAuthProvider, IntegrationAuthHeader, IntegrationAuthHeaders, IntegrationAuthParam, IntegrationAuthParams, IntegrationAuthProvider, getImsAuthProvider, getIntegrationAuthProvider };
@@ -0,0 +1,111 @@
1
+ import { context, getToken } from "@adobe/aio-lib-ims";
2
+ import crypto from "node:crypto";
3
+ import OAuth1a from "oauth-1.0a";
4
+
5
+ //#region source/lib/params.ts
6
+ /**
7
+ * Checks if the given value is non-empty.
8
+ *
9
+ * @param name of the parameter. Required because of `aio app dev` compatibility: inputs mapped to undefined env vars come as $<input_name> in dev mode, but as '' in prod mode.
10
+ * @param value of the parameter.
11
+ */
12
+ function nonEmpty(name, value) {
13
+ const v = value?.trim();
14
+ return v !== void 0 && v !== `$${name}`;
15
+ }
16
+ /**
17
+ * Checks if all required parameters are non-empty.
18
+ * @param params action input parameters.
19
+ * @param required list of required parameter names.
20
+ */
21
+ function allNonEmpty(params, required) {
22
+ return required.every((name) => nonEmpty(name, params[name]));
23
+ }
24
+
25
+ //#endregion
26
+ //#region source/lib/ims-auth.ts
27
+ /**
28
+ * If the required IMS parameters are present, this function returns an {@link ImsAuthProvider}.
29
+ * @param params includes IMS parameters
30
+ */
31
+ async function getImsAuthProvider(params) {
32
+ const config = resolveImsConfig(params);
33
+ if (config) {
34
+ const contextName = params.AIO_COMMERCE_IMS_CTX ?? "aio-commerce-sdk-creds";
35
+ await context.set(contextName, config);
36
+ return {
37
+ getAccessToken: async () => getToken(contextName, {}),
38
+ getHeaders: async () => {
39
+ const accessToken = await getToken(contextName, {});
40
+ return {
41
+ Authorization: `Bearer ${accessToken}`,
42
+ "x-api-key": config.client_id
43
+ };
44
+ }
45
+ };
46
+ }
47
+ }
48
+ function resolveImsConfig(params) {
49
+ if (allNonEmpty(params, [
50
+ "AIO_COMMERCE_IMS_CLIENT_ID",
51
+ "AIO_COMMERCE_IMS_CLIENT_SECRETS",
52
+ "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_ID",
53
+ "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_EMAIL",
54
+ "AIO_COMMERCE_IMS_IMS_ORG_ID",
55
+ "AIO_COMMERCE_IMS_SCOPES"
56
+ ])) return {
57
+ client_id: params.AIO_COMMERCE_IMS_CLIENT_ID,
58
+ client_secrets: JSON.parse(params.AIO_COMMERCE_IMS_CLIENT_SECRETS ?? "[]"),
59
+ technical_account_id: params.AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_ID,
60
+ technical_account_email: params.AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_EMAIL,
61
+ ims_org_id: params.AIO_COMMERCE_IMS_IMS_ORG_ID,
62
+ scopes: JSON.parse(params.AIO_COMMERCE_IMS_SCOPES ?? "[]"),
63
+ environment: params.AIO_COMMERCE_IMS_ENV ?? "prod"
64
+ };
65
+ }
66
+
67
+ //#endregion
68
+ //#region source/lib/integration-auth.ts
69
+ /**
70
+ * If the required integration parameters are present, this function returns an {@link IntegrationAuthProvider}.
71
+ * @param params includes integration parameters
72
+ */
73
+ function getIntegrationAuthProvider(params) {
74
+ const config = resolveIntegrationConfig(params);
75
+ if (config) {
76
+ const oauth = new OAuth1a({
77
+ consumer: {
78
+ key: config.consumerKey,
79
+ secret: config.consumerSecret
80
+ },
81
+ signature_method: "HMAC-SHA256",
82
+ hash_function: (baseString, key) => crypto.createHmac("sha256", key).update(baseString).digest("base64")
83
+ });
84
+ const oauthToken = {
85
+ key: config.accessToken,
86
+ secret: config.accessTokenSecret
87
+ };
88
+ return { getHeaders(method, url) {
89
+ return oauth.toHeader(oauth.authorize({
90
+ url,
91
+ method
92
+ }, oauthToken));
93
+ } };
94
+ }
95
+ }
96
+ function resolveIntegrationConfig(params) {
97
+ if (allNonEmpty(params, [
98
+ "AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY",
99
+ "AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET",
100
+ "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN",
101
+ "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET"
102
+ ])) return {
103
+ consumerKey: params.AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY,
104
+ consumerSecret: params.AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET,
105
+ accessToken: params.AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN,
106
+ accessTokenSecret: params.AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET
107
+ };
108
+ }
109
+
110
+ //#endregion
111
+ export { getImsAuthProvider, getIntegrationAuthProvider };
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@adobe/aio-commerce-lib-auth",
3
+ "type": "module",
4
+ "version": "0.1.0",
5
+ "private": false,
6
+ "author": "Adobe Inc.",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
10
+ "license": "Apache-2.0",
11
+ "description": "Authentication utilities for Adobe Commerce apps deployed in Adobe App Builder.",
12
+ "keywords": [
13
+ "aio",
14
+ "adobe-io",
15
+ "commerce",
16
+ "adobe-commerce",
17
+ "adobe-ims"
18
+ ],
19
+ "bugs": {
20
+ "url": "https://github.com/adobe/aio-commerce-sdk/issues"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/adobe/aio-commerce-sdk.git",
25
+ "directory": "packages/aio-commerce-lib-auth"
26
+ },
27
+ "main": "./dist/cjs/index.cjs",
28
+ "module": "./dist/es/index.js",
29
+ "types": "./dist/es/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "import": {
33
+ "types": "./dist/es/index.d.ts",
34
+ "default": "./dist/es/index.js"
35
+ },
36
+ "require": {
37
+ "types": "./dist/cjs/index.d.cts",
38
+ "default": "./dist/cjs/index.cjs"
39
+ }
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "dependencies": {
44
+ "@adobe/aio-lib-ims": "^8.1.0",
45
+ "oauth-1.0a": "^2.2.6"
46
+ },
47
+ "devDependencies": {
48
+ "vitest": "^3.2.4",
49
+ "@aio-commerce-sdk/config-typescript": "1.0.0",
50
+ "@aio-commerce-sdk/config-tsdown": "1.0.0"
51
+ },
52
+ "sideEffects": false,
53
+ "scripts": {
54
+ "build": "tsdown",
55
+ "assist": "pnpm -w assist .",
56
+ "assist:apply": "pnpm -w assist:apply .",
57
+ "check:ci": "pnpm -w check:ci .",
58
+ "format": "pnpm -w format .",
59
+ "format:check": "pnpm -w format:check .",
60
+ "lint": "pnpm -w lint .",
61
+ "lint:fix": "pnpm -w lint:fix .",
62
+ "typecheck": "tsc --noEmit && echo '✅ No type errors found.'",
63
+ "test": "vitest run",
64
+ "test:watch": "vitest"
65
+ }
66
+ }
@@ -0,0 +1,14 @@
1
+ /*
2
+ * Copyright 2025 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ export * from "./lib/ims-auth";
14
+ export * from "./lib/integration-auth";
@@ -0,0 +1,95 @@
1
+ /*
2
+ * Copyright 2025 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import { context, getToken } from "@adobe/aio-lib-ims";
14
+ import { allNonEmpty } from "./params";
15
+
16
+ const IMS_AUTH_HEADERS = ["Authorization", "x-api-key"] as const;
17
+ const IMS_AUTH_PARAMS = [
18
+ "AIO_COMMERCE_IMS_CLIENT_ID",
19
+ "AIO_COMMERCE_IMS_CLIENT_SECRETS",
20
+ "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_ID",
21
+ "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_EMAIL",
22
+ "AIO_COMMERCE_IMS_IMS_ORG_ID",
23
+ "AIO_COMMERCE_IMS_SCOPES",
24
+ "AIO_COMMERCE_IMS_ENV",
25
+ "AIO_COMMERCE_IMS_CTX",
26
+ ] as const;
27
+
28
+ /** Defines a union of allowed IMS authentication parameters. */
29
+ export type ImsAuthParam = (typeof IMS_AUTH_PARAMS)[number];
30
+
31
+ /** Defines a key-value map of IMS authentication parameters. */
32
+ export type ImsAuthParams = Partial<Record<ImsAuthParam, string>>;
33
+
34
+ /** Defines a union of allowed IMS authentication headers. */
35
+ export type ImsAuthHeader = (typeof IMS_AUTH_HEADERS)[number];
36
+
37
+ /** Defines a key-value map of IMS authentication headers. */
38
+ export type ImsAuthHeaders = Record<ImsAuthHeader, string>;
39
+
40
+ type ImsAccessToken = string;
41
+
42
+ /** Defines an authentication provider for Adobe IMS. */
43
+ export interface ImsAuthProvider {
44
+ getHeaders: () => Promise<ImsAuthHeaders>;
45
+ getAccessToken: () => Promise<ImsAccessToken>;
46
+ }
47
+
48
+ /**
49
+ * If the required IMS parameters are present, this function returns an {@link ImsAuthProvider}.
50
+ * @param params includes IMS parameters
51
+ */
52
+ export async function getImsAuthProvider(params: ImsAuthParams) {
53
+ const config = resolveImsConfig(params);
54
+
55
+ if (config) {
56
+ const contextName = params.AIO_COMMERCE_IMS_CTX ?? "aio-commerce-sdk-creds";
57
+ await context.set(contextName, config);
58
+
59
+ return {
60
+ getAccessToken: async () => getToken(contextName, {}),
61
+ getHeaders: async () => {
62
+ const accessToken = await getToken(contextName, {});
63
+ return {
64
+ Authorization: `Bearer ${accessToken}`,
65
+ "x-api-key": config.client_id,
66
+ };
67
+ },
68
+ } satisfies ImsAuthProvider;
69
+ }
70
+ }
71
+
72
+ function resolveImsConfig(params: ImsAuthParams) {
73
+ if (
74
+ allNonEmpty(params, [
75
+ "AIO_COMMERCE_IMS_CLIENT_ID",
76
+ "AIO_COMMERCE_IMS_CLIENT_SECRETS",
77
+ "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_ID",
78
+ "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_EMAIL",
79
+ "AIO_COMMERCE_IMS_IMS_ORG_ID",
80
+ "AIO_COMMERCE_IMS_SCOPES",
81
+ ])
82
+ ) {
83
+ return {
84
+ client_id: params.AIO_COMMERCE_IMS_CLIENT_ID,
85
+ client_secrets: JSON.parse(
86
+ params.AIO_COMMERCE_IMS_CLIENT_SECRETS ?? "[]",
87
+ ) as string[],
88
+ technical_account_id: params.AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_ID,
89
+ technical_account_email: params.AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_EMAIL,
90
+ ims_org_id: params.AIO_COMMERCE_IMS_IMS_ORG_ID,
91
+ scopes: JSON.parse(params.AIO_COMMERCE_IMS_SCOPES ?? "[]") as string[],
92
+ environment: params.AIO_COMMERCE_IMS_ENV ?? "prod",
93
+ };
94
+ }
95
+ }
@@ -0,0 +1,95 @@
1
+ /*
2
+ * Copyright 2025 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import crypto from "node:crypto";
14
+ import OAuth1a from "oauth-1.0a";
15
+
16
+ import { allNonEmpty } from "./params";
17
+
18
+ const HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const;
19
+ const INTEGRATION_AUTH_HEADERS = ["Authorization"] as const;
20
+ const INTEGRATION_AUTH_PARAMS = [
21
+ "AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY",
22
+ "AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET",
23
+ "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN",
24
+ "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET",
25
+ ] as const;
26
+
27
+ /** Defines a union of allowed integration authentication parameters. */
28
+ export type IntegrationAuthParam = (typeof INTEGRATION_AUTH_PARAMS)[number];
29
+
30
+ /** Defines a key-value map of integration authentication parameters. */
31
+ export type IntegrationAuthParams = Partial<
32
+ Record<IntegrationAuthParam, string>
33
+ >;
34
+
35
+ /** Defines a union of allowed integration authentication headers. */
36
+ export type IntegrationAuthHeader = (typeof INTEGRATION_AUTH_HEADERS)[number];
37
+
38
+ /** Defines a key-value map of integration authentication headers. */
39
+ export type IntegrationAuthHeaders = Record<IntegrationAuthHeader, string>;
40
+
41
+ type HttpMethod = (typeof HTTP_METHODS)[number];
42
+
43
+ /** Defines an authentication provider for integration authentication. */
44
+ export interface IntegrationAuthProvider {
45
+ getHeaders: (method: HttpMethod, url: string) => IntegrationAuthHeaders;
46
+ }
47
+
48
+ /**
49
+ * If the required integration parameters are present, this function returns an {@link IntegrationAuthProvider}.
50
+ * @param params includes integration parameters
51
+ */
52
+ export function getIntegrationAuthProvider(params: IntegrationAuthParams) {
53
+ const config = resolveIntegrationConfig(params);
54
+
55
+ if (config) {
56
+ const oauth = new OAuth1a({
57
+ consumer: {
58
+ key: config.consumerKey,
59
+ secret: config.consumerSecret,
60
+ },
61
+ signature_method: "HMAC-SHA256",
62
+ hash_function: (baseString, key) =>
63
+ crypto.createHmac("sha256", key).update(baseString).digest("base64"),
64
+ });
65
+
66
+ const oauthToken = {
67
+ key: config.accessToken,
68
+ secret: config.accessTokenSecret,
69
+ };
70
+
71
+ return {
72
+ getHeaders(method: HttpMethod, url: string) {
73
+ return oauth.toHeader(oauth.authorize({ url, method }, oauthToken));
74
+ },
75
+ } satisfies IntegrationAuthProvider;
76
+ }
77
+ }
78
+
79
+ function resolveIntegrationConfig(params: IntegrationAuthParams) {
80
+ if (
81
+ allNonEmpty(params, [
82
+ "AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY",
83
+ "AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET",
84
+ "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN",
85
+ "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET",
86
+ ])
87
+ ) {
88
+ return {
89
+ consumerKey: params.AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY,
90
+ consumerSecret: params.AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET,
91
+ accessToken: params.AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN,
92
+ accessTokenSecret: params.AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET,
93
+ };
94
+ }
95
+ }
@@ -0,0 +1,34 @@
1
+ /*
2
+ * Copyright 2025 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ /**
14
+ * Checks if the given value is non-empty.
15
+ *
16
+ * @param name of the parameter. Required because of `aio app dev` compatibility: inputs mapped to undefined env vars come as $<input_name> in dev mode, but as '' in prod mode.
17
+ * @param value of the parameter.
18
+ */
19
+ export function nonEmpty(name: string, value: string | undefined) {
20
+ const v = value?.trim();
21
+ return v !== undefined && v !== `$${name}`;
22
+ }
23
+
24
+ /**
25
+ * Checks if all required parameters are non-empty.
26
+ * @param params action input parameters.
27
+ * @param required list of required parameter names.
28
+ */
29
+ export function allNonEmpty<const T extends string>(
30
+ params: Record<string, string | undefined>,
31
+ required: T[],
32
+ ): params is Required<Record<T, string> & Record<string, string>> {
33
+ return required.every((name) => nonEmpty(name, params[name]));
34
+ }
@@ -0,0 +1,69 @@
1
+ /*
2
+ * Copyright 2025 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import { getToken } from "@adobe/aio-lib-ims";
14
+ import { describe, expect, test, vi } from "vitest";
15
+
16
+ import { getImsAuthProvider, type ImsAuthParams } from "~/lib/ims-auth";
17
+
18
+ vi.mock("@adobe/aio-lib-ims", async () => ({
19
+ context: (await vi.importActual("@adobe/aio-lib-ims")).context,
20
+ getToken: vi.fn(),
21
+ }));
22
+
23
+ describe("getImsAuthProvider", () => {
24
+ const params: ImsAuthParams = {
25
+ AIO_COMMERCE_IMS_CLIENT_ID: "test-client-id",
26
+ AIO_COMMERCE_IMS_CLIENT_SECRETS: JSON.stringify(["supersecret"]),
27
+ AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_ID: "test-technical-account-id",
28
+ AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_EMAIL: "test-email@example.com",
29
+ AIO_COMMERCE_IMS_IMS_ORG_ID: "test-org-id",
30
+ AIO_COMMERCE_IMS_SCOPES: JSON.stringify(["scope1", "scope2"]),
31
+ };
32
+
33
+ test("should export token when all required params are provided", async () => {
34
+ const authToken = "supersecrettoken";
35
+ vi.mocked(getToken).mockResolvedValue(authToken);
36
+
37
+ const imsProvider = await getImsAuthProvider(params);
38
+ expect(imsProvider).toBeDefined();
39
+
40
+ const retrievedToken = await imsProvider?.getAccessToken();
41
+ expect(retrievedToken).toEqual(authToken);
42
+
43
+ const headers = await imsProvider?.getHeaders();
44
+ expect(headers).toHaveProperty("Authorization", `Bearer ${authToken}`);
45
+ expect(headers).toHaveProperty(
46
+ "x-api-key",
47
+ params.AIO_COMMERCE_IMS_CLIENT_ID,
48
+ );
49
+ });
50
+
51
+ for (const param of [
52
+ "AIO_COMMERCE_IMS_CLIENT_ID",
53
+ "AIO_COMMERCE_IMS_CLIENT_SECRETS",
54
+ "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_ID",
55
+ "AIO_COMMERCE_IMS_TECHNICAL_ACCOUNT_EMAIL",
56
+ "AIO_COMMERCE_IMS_IMS_ORG_ID",
57
+ "AIO_COMMERCE_IMS_SCOPES",
58
+ ]) {
59
+ test(`should return undefined when ${param} is missing`, async () => {
60
+ const incompleteParams = {
61
+ ...params,
62
+ [param]: undefined,
63
+ };
64
+
65
+ const imsProvider = await getImsAuthProvider(incompleteParams);
66
+ expect(imsProvider).toBeUndefined();
67
+ });
68
+ }
69
+ });
@@ -0,0 +1,61 @@
1
+ /*
2
+ * Copyright 2025 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import { describe, expect, test } from "vitest";
14
+ import {
15
+ getIntegrationAuthProvider,
16
+ type IntegrationAuthParams,
17
+ } from "~/lib/integration-auth";
18
+
19
+ /** Regex to match the OAuth 1.0a header format. */
20
+ const OAUTH1_REGEX =
21
+ /^OAuth oauth_consumer_key="[^"]+", oauth_nonce="[^"]+", oauth_signature="[^"]+", oauth_signature_method="HMAC-SHA256", oauth_timestamp="[^"]+", oauth_token="[^"]+", oauth_version="1\.0"$/;
22
+
23
+ describe("getIntegrationAuthProvider", () => {
24
+ const params: IntegrationAuthParams = {
25
+ AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY: "test-consumer-key",
26
+ AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET: "test-consumer-secret",
27
+ AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN: "test-access-token",
28
+ AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET: "test-access-token-secret",
29
+ };
30
+
31
+ test("should export getIntegrationAccessToken", () => {
32
+ const integrationProvider = getIntegrationAuthProvider(params);
33
+ expect(integrationProvider).toBeDefined();
34
+
35
+ const headers = integrationProvider?.getHeaders(
36
+ "GET",
37
+ "http://localhost/test",
38
+ );
39
+ expect(headers).toHaveProperty(
40
+ "Authorization",
41
+ expect.stringMatching(OAUTH1_REGEX),
42
+ );
43
+ });
44
+
45
+ for (const param of [
46
+ "AIO_COMMERCE_INTEGRATIONS_CONSUMER_KEY",
47
+ "AIO_COMMERCE_INTEGRATIONS_CONSUMER_SECRET",
48
+ "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN",
49
+ "AIO_COMMERCE_INTEGRATIONS_ACCESS_TOKEN_SECRET",
50
+ ]) {
51
+ test(`should return undefined when ${param} is missing`, () => {
52
+ const incompleteParams = {
53
+ ...params,
54
+ [param]: undefined,
55
+ };
56
+
57
+ const integrationProvider = getIntegrationAuthProvider(incompleteParams);
58
+ expect(integrationProvider).toBeUndefined();
59
+ });
60
+ }
61
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "extends": "@aio-commerce-sdk/config-typescript/tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "baseUrl": ".",
5
+ "rootDir": ".",
6
+ "outDir": "./dist",
7
+
8
+ "paths": {
9
+ "~/*": ["./source/*"],
10
+ "~~/*": ["./*"]
11
+ }
12
+ },
13
+
14
+ "include": ["tsdown.config.ts", "source/**/*", "test/**/*"]
15
+ }
@@ -0,0 +1,7 @@
1
+ import { baseConfig } from "@aio-commerce-sdk/config-tsdown/tsdown.config.base";
2
+ import { defineConfig } from "tsdown";
3
+
4
+ export default defineConfig({
5
+ ...baseConfig,
6
+ entry: ["./source/index.ts"],
7
+ });
@@ -0,0 +1,16 @@
1
+ import { resolve } from "node:path";
2
+ import { defineConfig } from "vitest/config";
3
+
4
+ export default defineConfig({
5
+ resolve: {
6
+ alias: {
7
+ "~": resolve(__dirname, "./source"),
8
+ "~~": resolve(__dirname, "./"),
9
+ },
10
+ },
11
+
12
+ test: {
13
+ globals: true,
14
+ environment: "node",
15
+ },
16
+ });