@adobe/aio-commerce-lib-auth 0.4.0 → 0.6.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @adobe/aio-commerce-lib-auth
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#118](https://github.com/adobe/aio-commerce-sdk/pull/118) [`9079402`](https://github.com/adobe/aio-commerce-sdk/commit/90794023b30ba749e2a1e8278584e4804ad45e1e) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Add new `isImsAuthProvider` and `isIntegrationAuthProvider` helpers to distinguish between different auth providers
8
+
9
+ - [#117](https://github.com/adobe/aio-commerce-sdk/pull/117) [`fd6a1b5`](https://github.com/adobe/aio-commerce-sdk/commit/fd6a1b531aaea399fea875c8e1e03002790cb1f4) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Adds a new `resolveAuthParams` utility to all auth providers that automatically creates valid authentication param containers from the given unknown runtime action params.
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [[`176bd0f`](https://github.com/adobe/aio-commerce-sdk/commit/176bd0f793de8dbd11b1704a82dd722158f48e81), [`176bd0f`](https://github.com/adobe/aio-commerce-sdk/commit/176bd0f793de8dbd11b1704a82dd722158f48e81), [`493da95`](https://github.com/adobe/aio-commerce-sdk/commit/493da9595c06de304ecddbbc8295db124cb6fcba)]:
14
+ - @adobe/aio-commerce-lib-core@0.5.0
15
+
16
+ ## 0.5.0
17
+
18
+ ### Minor Changes
19
+
20
+ - [#95](https://github.com/adobe/aio-commerce-sdk/pull/95) [`abd5012`](https://github.com/adobe/aio-commerce-sdk/commit/abd5012e5680f97abd150de6036b2225c7dc0277) Thanks [@iivvaannxx](https://github.com/apps/renovate)! - [Breaking] Ensure `UrlSchema` is used when validating the input URL of Commerce Integration Auth. Now, if the input URL is not in the expected format it will throw.
21
+
3
22
  ## 0.4.0
4
23
 
5
24
  ### Minor Changes
@@ -11,4 +11,4 @@
11
11
  * OF ANY KIND, either express or implied. See the License for the specific language
12
12
  * governing permissions and limitations under the License.
13
13
  */
14
- var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__copyProps=(to,from,except,desc)=>{if(from&&typeof from==`object`||typeof from==`function`)for(var keys=__getOwnPropNames(from),i=0,n=keys.length,key;i<n;i++)key=keys[i],!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:(k=>from[k]).bind(null,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=mod==null?{}:__create(__getProtoOf(mod)),__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,`default`,{value:mod,enumerable:!0}):target,mod));let __adobe_aio_commerce_lib_core_error=require(`@adobe/aio-commerce-lib-core/error`);__adobe_aio_commerce_lib_core_error=__toESM(__adobe_aio_commerce_lib_core_error);let __adobe_aio_lib_ims=require(`@adobe/aio-lib-ims`);__adobe_aio_lib_ims=__toESM(__adobe_aio_lib_ims);let valibot=require(`valibot`);valibot=__toESM(valibot);let crypto=require(`crypto`);crypto=__toESM(crypto);let oauth_1_0a=require(`oauth-1.0a`);oauth_1_0a=__toESM(oauth_1_0a);const imsAuthParameter=name=>(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the IMS auth parameter ${name}`),(0,valibot.nonEmpty)(`Expected a non-empty string value for the IMS auth parameter ${name}`)),stringArray=name=>(0,valibot.pipe)((0,valibot.array)((0,valibot.string)(),`Expected a string array value for the IMS auth parameter ${name}`)),ImsAuthEnvSchema=(0,valibot.picklist)([`prod`,`stage`]),ImsAuthParamsSchema=(0,valibot.object)({clientId:imsAuthParameter(`clientId`),clientSecrets:(0,valibot.pipe)(stringArray(`clientSecrets`),(0,valibot.minLength)(1,`Expected at least one client secret for IMS auth`)),technicalAccountId:imsAuthParameter(`technicalAccountId`),technicalAccountEmail:(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the IMS auth parameter technicalAccountEmail`),(0,valibot.email)(`Expected a valid email format for technicalAccountEmail`)),imsOrgId:imsAuthParameter(`imsOrgId`),environment:(0,valibot.pipe)((0,valibot.optional)(ImsAuthEnvSchema)),context:(0,valibot.pipe)((0,valibot.optional)((0,valibot.string)())),scopes:(0,valibot.pipe)(stringArray(`scopes`),(0,valibot.minLength)(1,`Expected at least one scope for IMS auth`))}),{context,getToken}=__adobe_aio_lib_ims.default;function toImsAuthConfig(config){return{scopes:config.scopes,env:config?.environment??`prod`,context:config.context??`aio-commerce-lib-auth-creds`,client_id:config.clientId,client_secrets:config.clientSecrets,technical_account_id:config.technicalAccountId,technical_account_email:config.technicalAccountEmail,ims_org_id:config.imsOrgId}}function assertImsAuthParams(config){let result=(0,valibot.safeParse)(ImsAuthParamsSchema,config);if(!result.success)throw new __adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues})}function getImsAuthProvider(authParams){let getAccessToken=async()=>{let imsAuthConfig=toImsAuthConfig(authParams);return await context.set(imsAuthConfig.context,imsAuthConfig),getToken(imsAuthConfig.context,{})};return{getAccessToken,getHeaders:async()=>({Authorization:`Bearer ${await getAccessToken()}`,"x-api-key":authParams.clientId})}}const integrationAuthParameter=name=>(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the Commerce Integration parameter ${name}`),(0,valibot.nonEmpty)(`Expected a non-empty string value for the Commerce Integration parameter ${name}`)),BaseUrlSchema=(0,valibot.pipe)((0,valibot.string)(`Expected a string for the Adobe Commerce endpoint`),(0,valibot.nonEmpty)(`Expected a non-empty string for the Adobe Commerce endpoint`),(0,valibot.url)(`Expected a valid url for the Adobe Commerce endpoint`)),UrlSchema=(0,valibot.pipe)((0,valibot.union)([BaseUrlSchema,(0,valibot.instance)(URL)]),(0,valibot.transform)(url=>url instanceof URL?url.toString():url)),IntegrationAuthParamsSchema=(0,valibot.nonOptional)((0,valibot.object)({consumerKey:integrationAuthParameter(`consumerKey`),consumerSecret:integrationAuthParameter(`consumerSecret`),accessToken:integrationAuthParameter(`accessToken`),accessTokenSecret:integrationAuthParameter(`accessTokenSecret`)}));function assertIntegrationAuthParams(config){let result=(0,valibot.safeParse)(IntegrationAuthParamsSchema,config);if(!result.success)throw new __adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid IntegrationAuthProvider configuration`,{issues:result.issues})}function getIntegrationAuthProvider(authParams){let oauth=new oauth_1_0a.default({consumer:{key:authParams.consumerKey,secret:authParams.consumerSecret},signature_method:`HMAC-SHA256`,hash_function:(baseString,key)=>crypto.default.createHmac(`sha256`,key).update(baseString).digest(`base64`)}),oauthToken={key:authParams.accessToken,secret:authParams.accessTokenSecret};return{getHeaders:(method,url)=>{let urlString=url instanceof URL?url.toString():url;return oauth.toHeader(oauth.authorize({url:urlString,method},oauthToken))}}}exports.assertImsAuthParams=assertImsAuthParams,exports.assertIntegrationAuthParams=assertIntegrationAuthParams,exports.getImsAuthProvider=getImsAuthProvider,exports.getIntegrationAuthProvider=getIntegrationAuthProvider;
14
+ var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__copyProps=(to,from,except,desc)=>{if(from&&typeof from==`object`||typeof from==`function`)for(var keys=__getOwnPropNames(from),i=0,n=keys.length,key;i<n;i++)key=keys[i],!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:(k=>from[k]).bind(null,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=mod==null?{}:__create(__getProtoOf(mod)),__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,`default`,{value:mod,enumerable:!0}):target,mod));let __adobe_aio_lib_ims=require(`@adobe/aio-lib-ims`);__adobe_aio_lib_ims=__toESM(__adobe_aio_lib_ims);let __adobe_aio_commerce_lib_core_error=require(`@adobe/aio-commerce-lib-core/error`);__adobe_aio_commerce_lib_core_error=__toESM(__adobe_aio_commerce_lib_core_error);let valibot=require(`valibot`);valibot=__toESM(valibot);let crypto=require(`crypto`);crypto=__toESM(crypto);let oauth_1_0a=require(`oauth-1.0a`);oauth_1_0a=__toESM(oauth_1_0a);let __adobe_aio_commerce_lib_core_params=require(`@adobe/aio-commerce-lib-core/params`);__adobe_aio_commerce_lib_core_params=__toESM(__adobe_aio_commerce_lib_core_params);const{context,getToken}=__adobe_aio_lib_ims.default;function toImsAuthConfig(config){return{scopes:config.scopes,env:config?.environment??`prod`,context:config.context??`aio-commerce-lib-auth-creds`,client_id:config.clientId,client_secrets:config.clientSecrets,technical_account_id:config.technicalAccountId,technical_account_email:config.technicalAccountEmail,ims_org_id:config.imsOrgId}}function isImsAuthProvider(provider){return typeof provider==`object`&&!!provider&&`getAccessToken`in provider&&`getHeaders`in provider&&typeof provider.getAccessToken==`function`&&typeof provider.getHeaders==`function`}function getImsAuthProvider(authParams){let getAccessToken=async()=>{let imsAuthConfig=toImsAuthConfig(authParams);return await context.set(imsAuthConfig.context,imsAuthConfig),getToken(imsAuthConfig.context,{})};return{getAccessToken,getHeaders:async()=>({Authorization:`Bearer ${await getAccessToken()}`,"x-api-key":authParams.clientId})}}const imsAuthParameter=name=>(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the IMS auth parameter ${name}`),(0,valibot.nonEmpty)(`Expected a non-empty string value for the IMS auth parameter ${name}`)),stringArray=name=>(0,valibot.pipe)((0,valibot.array)((0,valibot.string)(),`Expected a string array value for the IMS auth parameter ${name}`)),ImsAuthEnvSchema=(0,valibot.picklist)([`prod`,`stage`]),ImsAuthParamsSchema=(0,valibot.object)({clientId:imsAuthParameter(`clientId`),clientSecrets:(0,valibot.pipe)(stringArray(`clientSecrets`),(0,valibot.minLength)(1,`Expected at least one client secret for IMS auth`)),technicalAccountId:imsAuthParameter(`technicalAccountId`),technicalAccountEmail:(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the IMS auth parameter technicalAccountEmail`),(0,valibot.email)(`Expected a valid email format for technicalAccountEmail`)),imsOrgId:imsAuthParameter(`imsOrgId`),environment:(0,valibot.pipe)((0,valibot.optional)(ImsAuthEnvSchema)),context:(0,valibot.pipe)((0,valibot.optional)((0,valibot.string)())),scopes:(0,valibot.pipe)(stringArray(`scopes`),(0,valibot.minLength)(1,`Expected at least one scope for IMS auth`))});function assertImsAuthParams(config){let result=(0,valibot.safeParse)(ImsAuthParamsSchema,config);if(!result.success)throw new __adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues})}function resolveImsAuthParams(params){let resolvedParams={clientId:params.AIO_COMMERCE_AUTH_IMS_CLIENT_ID,clientSecrets:params.AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS,technicalAccountId:params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID,technicalAccountEmail:params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL,imsOrgId:params.AIO_COMMERCE_AUTH_IMS_ORG_ID,scopes:params.AIO_COMMERCE_AUTH_IMS_SCOPES,environment:params.AIO_COMMERCE_AUTH_IMS_ENVIRONMENT,context:params.AIO_COMMERCE_AUTH_IMS_CONTEXT};return assertImsAuthParams(resolvedParams),resolvedParams}const integrationAuthParameter=name=>(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the Commerce Integration parameter ${name}`),(0,valibot.nonEmpty)(`Expected a non-empty string value for the Commerce Integration parameter ${name}`)),BaseUrlSchema=(0,valibot.pipe)((0,valibot.string)(`Expected a string for the Adobe Commerce endpoint`),(0,valibot.nonEmpty)(`Expected a non-empty string for the Adobe Commerce endpoint`),(0,valibot.url)(`Expected a valid url for the Adobe Commerce endpoint`)),UrlSchema=(0,valibot.pipe)((0,valibot.union)([BaseUrlSchema,(0,valibot.instance)(URL)]),(0,valibot.transform)(url=>url instanceof URL?url.toString():url)),IntegrationAuthParamsSchema=(0,valibot.nonOptional)((0,valibot.object)({consumerKey:integrationAuthParameter(`consumerKey`),consumerSecret:integrationAuthParameter(`consumerSecret`),accessToken:integrationAuthParameter(`accessToken`),accessTokenSecret:integrationAuthParameter(`accessTokenSecret`)}));function isIntegrationAuthProvider(provider){return typeof provider==`object`&&!!provider&&`getHeaders`in provider&&typeof provider.getHeaders==`function`}function getIntegrationAuthProvider(authParams){let oauth=new oauth_1_0a.default({consumer:{key:authParams.consumerKey,secret:authParams.consumerSecret},signature_method:`HMAC-SHA256`,hash_function:(baseString,key)=>crypto.default.createHmac(`sha256`,key).update(baseString).digest(`base64`)}),oauthToken={key:authParams.accessToken,secret:authParams.accessTokenSecret};return{getHeaders:(method,url)=>{let urlString=(0,valibot.parse)(UrlSchema,url);return oauth.toHeader(oauth.authorize({url:urlString,method},oauthToken))}}}function assertIntegrationAuthParams(config){let result=(0,valibot.safeParse)(IntegrationAuthParamsSchema,config);if(!result.success)throw new __adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid IntegrationAuthProvider configuration`,{issues:result.issues})}function resolveIntegrationAuthParams(params){let resolvedParams={consumerKey:params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY,consumerSecret:params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET,accessToken:params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN,accessTokenSecret:params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET};return assertIntegrationAuthParams(resolvedParams),resolvedParams}const IMS_AUTH_PARAMS=[`AIO_COMMERCE_AUTH_IMS_CLIENT_ID`,`AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS`,`AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID`,`AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL`,`AIO_COMMERCE_AUTH_IMS_ORG_ID`,`AIO_COMMERCE_AUTH_IMS_SCOPES`],INTEGRATION_AUTH_PARAMS=[`AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY`,`AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET`,`AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN`,`AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET`];function resolveAuthParams(params){if((0,__adobe_aio_commerce_lib_core_params.allNonEmpty)(params,IMS_AUTH_PARAMS))return Object.assign(resolveImsAuthParams(params),{strategy:`ims`});if((0,__adobe_aio_commerce_lib_core_params.allNonEmpty)(params,INTEGRATION_AUTH_PARAMS))return Object.assign(resolveIntegrationAuthParams(params),{strategy:`integration`});throw Error(`Can't resolve authentication options for the given params. Please provide either IMS options (${IMS_AUTH_PARAMS.join(`, `)}) or Commerce integration options (${INTEGRATION_AUTH_PARAMS.join(`, `)}).`)}exports.assertImsAuthParams=assertImsAuthParams,exports.assertIntegrationAuthParams=assertIntegrationAuthParams,exports.getImsAuthProvider=getImsAuthProvider,exports.getIntegrationAuthProvider=getIntegrationAuthProvider,exports.isImsAuthProvider=isImsAuthProvider,exports.isIntegrationAuthProvider=isIntegrationAuthProvider,exports.resolveAuthParams=resolveAuthParams;
@@ -45,40 +45,25 @@ type ImsAuthProvider = {
45
45
  getHeaders: () => Promise<ImsAuthHeaders>;
46
46
  };
47
47
  /**
48
- * Asserts the provided configuration for an {@link ImsAuthProvider}.
49
- * @param config The configuration to validate.
50
- * @throws {CommerceSdkValidationError} If the configuration is invalid.
51
- * @example
52
- * ```typescript
53
- * const config = {
54
- * clientId: "your-client-id",
55
- * clientSecrets: ["your-client-secret"],
56
- * technicalAccountId: "your-technical-account-id",
57
- * technicalAccountEmail: "your-account@example.com",
58
- * imsOrgId: "your-ims-org-id@AdobeOrg",
59
- * scopes: ["AdobeID", "openid"],
60
- * environment: "prod", // or "stage"
61
- * context: "my-app-context"
62
- * };
48
+ * Type guard to check if a value is an ImsAuthProvider instance.
49
+ *
50
+ * @param provider The value to check.
51
+ * @returns `true` if the value is an ImsAuthProvider, `false` otherwise.
63
52
  *
64
- * // This will validate the config and throw if invalid
65
- * assertImsAuthParams(config);
66
- *```
67
53
  * @example
68
54
  * ```typescript
69
- * // Example of a failing assert:
70
- * try {
71
- * assertImsAuthParams({
72
- * clientId: "valid-client-id",
73
- * // Missing required fields like clientSecrets, technicalAccountId, etc.
74
- * });
75
- * } catch (error) {
76
- * console.error(error.message); // "Invalid ImsAuthProvider configuration"
77
- * console.error(error.issues); // Array of validation issues
55
+ * import { getImsAuthProvider, isImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
56
+ *
57
+ * // Imagine you have an object that it's not strictly typed as ImsAuthProvider.
58
+ * const provider = getImsAuthProvider({ ... }) as unknown;
59
+ *
60
+ * if (isImsAuthProvider(provider)) {
61
+ * // TypeScript knows provider is ImsAuthProvider
62
+ * const token = await provider.getAccessToken();
78
63
  * }
79
64
  * ```
80
65
  */
81
- declare function assertImsAuthParams(config: Record<PropertyKey, unknown>): asserts config is ImsAuthParams;
66
+ declare function isImsAuthProvider(provider: unknown): provider is ImsAuthProvider;
82
67
  /**
83
68
  * Creates an {@link ImsAuthProvider} based on the provided configuration.
84
69
  * @param authParams An {@link ImsAuthParams} parameter that contains the configuration for the {@link ImsAuthProvider}.
@@ -124,14 +109,49 @@ declare function getImsAuthProvider(authParams: ImsAuthParams): {
124
109
  }>;
125
110
  };
126
111
  //#endregion
112
+ //#region source/lib/ims-auth/utils.d.ts
113
+ /**
114
+ * Asserts the provided configuration for an {@link ImsAuthProvider}.
115
+ * @param config The configuration to validate.
116
+ * @throws {CommerceSdkValidationError} If the configuration is invalid.
117
+ * @example
118
+ * ```typescript
119
+ * const config = {
120
+ * clientId: "your-client-id",
121
+ * clientSecrets: ["your-client-secret"],
122
+ * technicalAccountId: "your-technical-account-id",
123
+ * technicalAccountEmail: "your-account@example.com",
124
+ * imsOrgId: "your-ims-org-id@AdobeOrg",
125
+ * scopes: ["AdobeID", "openid"],
126
+ * environment: "prod", // or "stage"
127
+ * context: "my-app-context"
128
+ * };
129
+ *
130
+ * // This will validate the config and throw if invalid
131
+ * assertImsAuthParams(config);
132
+ *```
133
+ * @example
134
+ * ```typescript
135
+ * // Example of a failing assert:
136
+ * try {
137
+ * assertImsAuthParams({
138
+ * clientId: "valid-client-id",
139
+ * // Missing required fields like clientSecrets, technicalAccountId, etc.
140
+ * });
141
+ * } catch (error) {
142
+ * console.error(error.message); // "Invalid ImsAuthProvider configuration"
143
+ * console.error(error.issues); // Array of validation issues
144
+ * }
145
+ * ```
146
+ */
147
+ declare function assertImsAuthParams(config: Record<PropertyKey, unknown>): asserts config is ImsAuthParams;
148
+ //#endregion
127
149
  //#region source/lib/integration-auth/schema.d.ts
128
150
  /**
129
151
  * The HTTP methods supported by Commerce.
130
152
  * This is used to determine which headers to include in the signing of the authorization header.
131
153
  */
132
154
  type HttpMethodInput = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
133
- /** Validation schema that accepts either a URL string or URL instance and normalizes to string. */
134
-
135
155
  /**
136
156
  * The schema for the Commerce Integration parameters.
137
157
  * This is used to validate the parameters passed to the Commerce Integration provider.
@@ -156,6 +176,53 @@ type AdobeCommerceUrl = string | URL;
156
176
  type IntegrationAuthProvider = {
157
177
  getHeaders: (method: HttpMethodInput, url: AdobeCommerceUrl) => IntegrationAuthHeaders;
158
178
  };
179
+ /**
180
+ * Type guard to check if a value is an IntegrationAuthProvider instance.
181
+ *
182
+ * @param provider The value to check.
183
+ * @returns `true` if the value is an IntegrationAuthProvider, `false` otherwise.
184
+ *
185
+ * @example
186
+ * ```typescript
187
+ * import { getIntegrationAuthProvider, isIntegrationAuthProvider } from "@adobe/aio-commerce-lib-auth";
188
+ *
189
+ * // Imagine you have an object that it's not strictly typed as IntegrationAuthProvider.
190
+ * const provider = getIntegrationAuthProvider({ ... }) as unknown;
191
+ *
192
+ * if (isIntegrationAuthProvider(provider)) {
193
+ * // TypeScript knows provider is IntegrationAuthProvider
194
+ * const headers = provider.getHeaders("GET", "https://api.example.com");
195
+ * }
196
+ * ```
197
+ */
198
+ declare function isIntegrationAuthProvider(provider: unknown): provider is IntegrationAuthProvider;
199
+ /**
200
+ * Creates an {@link IntegrationAuthProvider} based on the provided configuration.
201
+ * @param authParams The configuration for the integration.
202
+ * @returns An {@link IntegrationAuthProvider} instance that can be used to get auth headers.
203
+ * @example
204
+ * ```typescript
205
+ * const config = {
206
+ * consumerKey: "your-consumer-key",
207
+ * consumerSecret: "your-consumer-secret",
208
+ * accessToken: "your-access-token",
209
+ * accessTokenSecret: "your-access-token-secret"
210
+ * };
211
+ *
212
+ * const authProvider = getIntegrationAuthProvider(config);
213
+ *
214
+ * // Get OAuth headers for a REST API call
215
+ * const headers = authProvider.getHeaders("GET", "https://your-store.com/rest/V1/products");
216
+ * console.log(headers); // { Authorization: "OAuth oauth_consumer_key=..., oauth_signature=..." }
217
+ *
218
+ * // Can also be used with URL objects
219
+ * const url = new URL("https://your-store.com/rest/V1/customers");
220
+ * const postHeaders = authProvider.getHeaders("POST", url);
221
+ * ```
222
+ */
223
+ declare function getIntegrationAuthProvider(authParams: IntegrationAuthParams): IntegrationAuthProvider;
224
+ //#endregion
225
+ //#region source/lib/integration-auth/utils.d.ts
159
226
  /**
160
227
  * Asserts the provided configuration for an Adobe Commerce {@link IntegrationAuthProvider}.
161
228
  * @param config The configuration to validate.
@@ -187,30 +254,42 @@ type IntegrationAuthProvider = {
187
254
  * ```
188
255
  */
189
256
  declare function assertIntegrationAuthParams(config: Record<PropertyKey, unknown>): asserts config is IntegrationAuthParams;
257
+ //#endregion
258
+ //#region source/lib/utils.d.ts
190
259
  /**
191
- * Creates an {@link IntegrationAuthProvider} based on the provided configuration.
192
- * @param authParams The configuration for the integration.
193
- * @returns An {@link IntegrationAuthProvider} instance that can be used to get auth headers.
260
+ * Automatically detects and resolves authentication parameters from App Builder action inputs.
261
+ * Attempts to resolve IMS authentication first, then falls back to Integration authentication.
262
+ *
263
+ * @param params The App Builder action inputs containing authentication parameters.
264
+ * @throws {CommerceSdkValidationError} If the parameters are invalid.
265
+ * @throws {Error} If neither IMS nor Integration authentication parameters can be resolved.
194
266
  * @example
195
267
  * ```typescript
196
- * const config = {
197
- * consumerKey: "your-consumer-key",
198
- * consumerSecret: "your-consumer-secret",
199
- * accessToken: "your-access-token",
200
- * accessTokenSecret: "your-access-token-secret"
201
- * };
202
- *
203
- * const authProvider = getIntegrationAuthProvider(config);
204
- *
205
- * // Get OAuth headers for a REST API call
206
- * const headers = authProvider.getHeaders("GET", "https://your-store.com/rest/V1/products");
207
- * console.log(headers); // { Authorization: "OAuth oauth_consumer_key=..., oauth_signature=..." }
208
- *
209
- * // Can also be used with URL objects
210
- * const url = new URL("https://your-store.com/rest/V1/customers");
211
- * const postHeaders = authProvider.getHeaders("POST", url);
268
+ * // Automatic detection (will use IMS if IMS params are present, otherwise Integration)
269
+ * export function main(params) {
270
+ * const authProvider = resolveAuthParams(params);
271
+ * console.log(authProvider.strategy); // "ims" or "integration"
272
+ * }
212
273
  * ```
213
274
  */
214
- declare function getIntegrationAuthProvider(authParams: IntegrationAuthParams): IntegrationAuthProvider;
275
+ declare function resolveAuthParams(params: Record<string, unknown>): ({
276
+ clientId: string;
277
+ clientSecrets: string[];
278
+ technicalAccountId: string;
279
+ technicalAccountEmail: string;
280
+ imsOrgId: string;
281
+ environment?: "prod" | "stage" | undefined;
282
+ context?: string | undefined;
283
+ scopes: string[];
284
+ } & {
285
+ readonly strategy: "ims";
286
+ }) | ({
287
+ consumerKey: string;
288
+ consumerSecret: string;
289
+ accessToken: string;
290
+ accessTokenSecret: string;
291
+ } & {
292
+ readonly strategy: "integration";
293
+ });
215
294
  //#endregion
216
- export { type ImsAuthEnv, type ImsAuthParams, type ImsAuthProvider, type IntegrationAuthParams, type IntegrationAuthProvider, assertImsAuthParams, assertIntegrationAuthParams, getImsAuthProvider, getIntegrationAuthProvider };
295
+ export { type ImsAuthEnv, type ImsAuthParams, type ImsAuthProvider, type IntegrationAuthParams, type IntegrationAuthProvider, assertImsAuthParams, assertIntegrationAuthParams, getImsAuthProvider, getIntegrationAuthProvider, isImsAuthProvider, isIntegrationAuthProvider, resolveAuthParams };
@@ -12,22 +12,22 @@
12
12
  * governing permissions and limitations under the License.
13
13
  */
14
14
 
15
- import * as valibot21 from "valibot";
15
+ import * as valibot0 from "valibot";
16
16
  import { InferOutput } from "valibot";
17
17
 
18
18
  //#region source/lib/ims-auth/schema.d.ts
19
19
  /** Validation schema for IMS auth environment values. */
20
- declare const ImsAuthEnvSchema: valibot21.PicklistSchema<["prod", "stage"], undefined>;
20
+ declare const ImsAuthEnvSchema: valibot0.PicklistSchema<["prod", "stage"], undefined>;
21
21
  /** Defines the schema to validate the necessary parameters for the IMS auth service. */
22
- declare const ImsAuthParamsSchema: valibot21.ObjectSchema<{
23
- readonly clientId: valibot21.SchemaWithPipe<readonly [valibot21.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, valibot21.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
24
- readonly clientSecrets: valibot21.SchemaWithPipe<readonly [valibot21.SchemaWithPipe<readonly [valibot21.ArraySchema<valibot21.StringSchema<undefined>, `Expected a string array value for the IMS auth parameter ${string}`>]>, valibot21.MinLengthAction<string[], 1, "Expected at least one client secret for IMS auth">]>;
25
- readonly technicalAccountId: valibot21.SchemaWithPipe<readonly [valibot21.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, valibot21.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
26
- readonly technicalAccountEmail: valibot21.SchemaWithPipe<readonly [valibot21.StringSchema<"Expected a string value for the IMS auth parameter technicalAccountEmail">, valibot21.EmailAction<string, "Expected a valid email format for technicalAccountEmail">]>;
27
- readonly imsOrgId: valibot21.SchemaWithPipe<readonly [valibot21.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, valibot21.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
28
- readonly environment: valibot21.SchemaWithPipe<readonly [valibot21.OptionalSchema<valibot21.PicklistSchema<["prod", "stage"], undefined>, undefined>]>;
29
- readonly context: valibot21.SchemaWithPipe<readonly [valibot21.OptionalSchema<valibot21.StringSchema<undefined>, undefined>]>;
30
- readonly scopes: valibot21.SchemaWithPipe<readonly [valibot21.SchemaWithPipe<readonly [valibot21.ArraySchema<valibot21.StringSchema<undefined>, `Expected a string array value for the IMS auth parameter ${string}`>]>, valibot21.MinLengthAction<string[], 1, "Expected at least one scope for IMS auth">]>;
22
+ declare const ImsAuthParamsSchema: valibot0.ObjectSchema<{
23
+ readonly clientId: valibot0.SchemaWithPipe<readonly [valibot0.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, valibot0.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
24
+ readonly clientSecrets: valibot0.SchemaWithPipe<readonly [valibot0.SchemaWithPipe<readonly [valibot0.ArraySchema<valibot0.StringSchema<undefined>, `Expected a string array value for the IMS auth parameter ${string}`>]>, valibot0.MinLengthAction<string[], 1, "Expected at least one client secret for IMS auth">]>;
25
+ readonly technicalAccountId: valibot0.SchemaWithPipe<readonly [valibot0.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, valibot0.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
26
+ readonly technicalAccountEmail: valibot0.SchemaWithPipe<readonly [valibot0.StringSchema<"Expected a string value for the IMS auth parameter technicalAccountEmail">, valibot0.EmailAction<string, "Expected a valid email format for technicalAccountEmail">]>;
27
+ readonly imsOrgId: valibot0.SchemaWithPipe<readonly [valibot0.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, valibot0.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
28
+ readonly environment: valibot0.SchemaWithPipe<readonly [valibot0.OptionalSchema<valibot0.PicklistSchema<["prod", "stage"], undefined>, undefined>]>;
29
+ readonly context: valibot0.SchemaWithPipe<readonly [valibot0.OptionalSchema<valibot0.StringSchema<undefined>, undefined>]>;
30
+ readonly scopes: valibot0.SchemaWithPipe<readonly [valibot0.SchemaWithPipe<readonly [valibot0.ArraySchema<valibot0.StringSchema<undefined>, `Expected a string array value for the IMS auth parameter ${string}`>]>, valibot0.MinLengthAction<string[], 1, "Expected at least one scope for IMS auth">]>;
31
31
  }, undefined>;
32
32
  /** Defines the parameters for the IMS auth service. */
33
33
  type ImsAuthParams = InferOutput<typeof ImsAuthParamsSchema>;
@@ -45,40 +45,25 @@ type ImsAuthProvider = {
45
45
  getHeaders: () => Promise<ImsAuthHeaders>;
46
46
  };
47
47
  /**
48
- * Asserts the provided configuration for an {@link ImsAuthProvider}.
49
- * @param config The configuration to validate.
50
- * @throws {CommerceSdkValidationError} If the configuration is invalid.
51
- * @example
52
- * ```typescript
53
- * const config = {
54
- * clientId: "your-client-id",
55
- * clientSecrets: ["your-client-secret"],
56
- * technicalAccountId: "your-technical-account-id",
57
- * technicalAccountEmail: "your-account@example.com",
58
- * imsOrgId: "your-ims-org-id@AdobeOrg",
59
- * scopes: ["AdobeID", "openid"],
60
- * environment: "prod", // or "stage"
61
- * context: "my-app-context"
62
- * };
48
+ * Type guard to check if a value is an ImsAuthProvider instance.
49
+ *
50
+ * @param provider The value to check.
51
+ * @returns `true` if the value is an ImsAuthProvider, `false` otherwise.
63
52
  *
64
- * // This will validate the config and throw if invalid
65
- * assertImsAuthParams(config);
66
- *```
67
53
  * @example
68
54
  * ```typescript
69
- * // Example of a failing assert:
70
- * try {
71
- * assertImsAuthParams({
72
- * clientId: "valid-client-id",
73
- * // Missing required fields like clientSecrets, technicalAccountId, etc.
74
- * });
75
- * } catch (error) {
76
- * console.error(error.message); // "Invalid ImsAuthProvider configuration"
77
- * console.error(error.issues); // Array of validation issues
55
+ * import { getImsAuthProvider, isImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
56
+ *
57
+ * // Imagine you have an object that it's not strictly typed as ImsAuthProvider.
58
+ * const provider = getImsAuthProvider({ ... }) as unknown;
59
+ *
60
+ * if (isImsAuthProvider(provider)) {
61
+ * // TypeScript knows provider is ImsAuthProvider
62
+ * const token = await provider.getAccessToken();
78
63
  * }
79
64
  * ```
80
65
  */
81
- declare function assertImsAuthParams(config: Record<PropertyKey, unknown>): asserts config is ImsAuthParams;
66
+ declare function isImsAuthProvider(provider: unknown): provider is ImsAuthProvider;
82
67
  /**
83
68
  * Creates an {@link ImsAuthProvider} based on the provided configuration.
84
69
  * @param authParams An {@link ImsAuthParams} parameter that contains the configuration for the {@link ImsAuthProvider}.
@@ -124,23 +109,58 @@ declare function getImsAuthProvider(authParams: ImsAuthParams): {
124
109
  }>;
125
110
  };
126
111
  //#endregion
112
+ //#region source/lib/ims-auth/utils.d.ts
113
+ /**
114
+ * Asserts the provided configuration for an {@link ImsAuthProvider}.
115
+ * @param config The configuration to validate.
116
+ * @throws {CommerceSdkValidationError} If the configuration is invalid.
117
+ * @example
118
+ * ```typescript
119
+ * const config = {
120
+ * clientId: "your-client-id",
121
+ * clientSecrets: ["your-client-secret"],
122
+ * technicalAccountId: "your-technical-account-id",
123
+ * technicalAccountEmail: "your-account@example.com",
124
+ * imsOrgId: "your-ims-org-id@AdobeOrg",
125
+ * scopes: ["AdobeID", "openid"],
126
+ * environment: "prod", // or "stage"
127
+ * context: "my-app-context"
128
+ * };
129
+ *
130
+ * // This will validate the config and throw if invalid
131
+ * assertImsAuthParams(config);
132
+ *```
133
+ * @example
134
+ * ```typescript
135
+ * // Example of a failing assert:
136
+ * try {
137
+ * assertImsAuthParams({
138
+ * clientId: "valid-client-id",
139
+ * // Missing required fields like clientSecrets, technicalAccountId, etc.
140
+ * });
141
+ * } catch (error) {
142
+ * console.error(error.message); // "Invalid ImsAuthProvider configuration"
143
+ * console.error(error.issues); // Array of validation issues
144
+ * }
145
+ * ```
146
+ */
147
+ declare function assertImsAuthParams(config: Record<PropertyKey, unknown>): asserts config is ImsAuthParams;
148
+ //#endregion
127
149
  //#region source/lib/integration-auth/schema.d.ts
128
150
  /**
129
151
  * The HTTP methods supported by Commerce.
130
152
  * This is used to determine which headers to include in the signing of the authorization header.
131
153
  */
132
154
  type HttpMethodInput = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
133
- /** Validation schema that accepts either a URL string or URL instance and normalizes to string. */
134
-
135
155
  /**
136
156
  * The schema for the Commerce Integration parameters.
137
157
  * This is used to validate the parameters passed to the Commerce Integration provider.
138
158
  */
139
- declare const IntegrationAuthParamsSchema: valibot21.NonOptionalSchema<valibot21.ObjectSchema<{
140
- readonly consumerKey: valibot21.SchemaWithPipe<readonly [valibot21.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, valibot21.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
141
- readonly consumerSecret: valibot21.SchemaWithPipe<readonly [valibot21.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, valibot21.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
142
- readonly accessToken: valibot21.SchemaWithPipe<readonly [valibot21.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, valibot21.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
143
- readonly accessTokenSecret: valibot21.SchemaWithPipe<readonly [valibot21.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, valibot21.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
159
+ declare const IntegrationAuthParamsSchema: valibot0.NonOptionalSchema<valibot0.ObjectSchema<{
160
+ readonly consumerKey: valibot0.SchemaWithPipe<readonly [valibot0.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, valibot0.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
161
+ readonly consumerSecret: valibot0.SchemaWithPipe<readonly [valibot0.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, valibot0.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
162
+ readonly accessToken: valibot0.SchemaWithPipe<readonly [valibot0.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, valibot0.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
163
+ readonly accessTokenSecret: valibot0.SchemaWithPipe<readonly [valibot0.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, valibot0.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
144
164
  }, undefined>, undefined>;
145
165
  /** Defines the parameters required for Commerce Integration authentication. */
146
166
  type IntegrationAuthParams = InferOutput<typeof IntegrationAuthParamsSchema>;
@@ -156,6 +176,53 @@ type AdobeCommerceUrl = string | URL;
156
176
  type IntegrationAuthProvider = {
157
177
  getHeaders: (method: HttpMethodInput, url: AdobeCommerceUrl) => IntegrationAuthHeaders;
158
178
  };
179
+ /**
180
+ * Type guard to check if a value is an IntegrationAuthProvider instance.
181
+ *
182
+ * @param provider The value to check.
183
+ * @returns `true` if the value is an IntegrationAuthProvider, `false` otherwise.
184
+ *
185
+ * @example
186
+ * ```typescript
187
+ * import { getIntegrationAuthProvider, isIntegrationAuthProvider } from "@adobe/aio-commerce-lib-auth";
188
+ *
189
+ * // Imagine you have an object that it's not strictly typed as IntegrationAuthProvider.
190
+ * const provider = getIntegrationAuthProvider({ ... }) as unknown;
191
+ *
192
+ * if (isIntegrationAuthProvider(provider)) {
193
+ * // TypeScript knows provider is IntegrationAuthProvider
194
+ * const headers = provider.getHeaders("GET", "https://api.example.com");
195
+ * }
196
+ * ```
197
+ */
198
+ declare function isIntegrationAuthProvider(provider: unknown): provider is IntegrationAuthProvider;
199
+ /**
200
+ * Creates an {@link IntegrationAuthProvider} based on the provided configuration.
201
+ * @param authParams The configuration for the integration.
202
+ * @returns An {@link IntegrationAuthProvider} instance that can be used to get auth headers.
203
+ * @example
204
+ * ```typescript
205
+ * const config = {
206
+ * consumerKey: "your-consumer-key",
207
+ * consumerSecret: "your-consumer-secret",
208
+ * accessToken: "your-access-token",
209
+ * accessTokenSecret: "your-access-token-secret"
210
+ * };
211
+ *
212
+ * const authProvider = getIntegrationAuthProvider(config);
213
+ *
214
+ * // Get OAuth headers for a REST API call
215
+ * const headers = authProvider.getHeaders("GET", "https://your-store.com/rest/V1/products");
216
+ * console.log(headers); // { Authorization: "OAuth oauth_consumer_key=..., oauth_signature=..." }
217
+ *
218
+ * // Can also be used with URL objects
219
+ * const url = new URL("https://your-store.com/rest/V1/customers");
220
+ * const postHeaders = authProvider.getHeaders("POST", url);
221
+ * ```
222
+ */
223
+ declare function getIntegrationAuthProvider(authParams: IntegrationAuthParams): IntegrationAuthProvider;
224
+ //#endregion
225
+ //#region source/lib/integration-auth/utils.d.ts
159
226
  /**
160
227
  * Asserts the provided configuration for an Adobe Commerce {@link IntegrationAuthProvider}.
161
228
  * @param config The configuration to validate.
@@ -187,30 +254,42 @@ type IntegrationAuthProvider = {
187
254
  * ```
188
255
  */
189
256
  declare function assertIntegrationAuthParams(config: Record<PropertyKey, unknown>): asserts config is IntegrationAuthParams;
257
+ //#endregion
258
+ //#region source/lib/utils.d.ts
190
259
  /**
191
- * Creates an {@link IntegrationAuthProvider} based on the provided configuration.
192
- * @param authParams The configuration for the integration.
193
- * @returns An {@link IntegrationAuthProvider} instance that can be used to get auth headers.
260
+ * Automatically detects and resolves authentication parameters from App Builder action inputs.
261
+ * Attempts to resolve IMS authentication first, then falls back to Integration authentication.
262
+ *
263
+ * @param params The App Builder action inputs containing authentication parameters.
264
+ * @throws {CommerceSdkValidationError} If the parameters are invalid.
265
+ * @throws {Error} If neither IMS nor Integration authentication parameters can be resolved.
194
266
  * @example
195
267
  * ```typescript
196
- * const config = {
197
- * consumerKey: "your-consumer-key",
198
- * consumerSecret: "your-consumer-secret",
199
- * accessToken: "your-access-token",
200
- * accessTokenSecret: "your-access-token-secret"
201
- * };
202
- *
203
- * const authProvider = getIntegrationAuthProvider(config);
204
- *
205
- * // Get OAuth headers for a REST API call
206
- * const headers = authProvider.getHeaders("GET", "https://your-store.com/rest/V1/products");
207
- * console.log(headers); // { Authorization: "OAuth oauth_consumer_key=..., oauth_signature=..." }
208
- *
209
- * // Can also be used with URL objects
210
- * const url = new URL("https://your-store.com/rest/V1/customers");
211
- * const postHeaders = authProvider.getHeaders("POST", url);
268
+ * // Automatic detection (will use IMS if IMS params are present, otherwise Integration)
269
+ * export function main(params) {
270
+ * const authProvider = resolveAuthParams(params);
271
+ * console.log(authProvider.strategy); // "ims" or "integration"
272
+ * }
212
273
  * ```
213
274
  */
214
- declare function getIntegrationAuthProvider(authParams: IntegrationAuthParams): IntegrationAuthProvider;
275
+ declare function resolveAuthParams(params: Record<string, unknown>): ({
276
+ clientId: string;
277
+ clientSecrets: string[];
278
+ technicalAccountId: string;
279
+ technicalAccountEmail: string;
280
+ imsOrgId: string;
281
+ environment?: "prod" | "stage" | undefined;
282
+ context?: string | undefined;
283
+ scopes: string[];
284
+ } & {
285
+ readonly strategy: "ims";
286
+ }) | ({
287
+ consumerKey: string;
288
+ consumerSecret: string;
289
+ accessToken: string;
290
+ accessTokenSecret: string;
291
+ } & {
292
+ readonly strategy: "integration";
293
+ });
215
294
  //#endregion
216
- export { type ImsAuthEnv, type ImsAuthParams, type ImsAuthProvider, type IntegrationAuthParams, type IntegrationAuthProvider, assertImsAuthParams, assertIntegrationAuthParams, getImsAuthProvider, getIntegrationAuthProvider };
295
+ export { type ImsAuthEnv, type ImsAuthParams, type ImsAuthProvider, type IntegrationAuthParams, type IntegrationAuthProvider, assertImsAuthParams, assertIntegrationAuthParams, getImsAuthProvider, getIntegrationAuthProvider, isImsAuthProvider, isIntegrationAuthProvider, resolveAuthParams };
package/dist/es/index.js CHANGED
@@ -11,4 +11,4 @@
11
11
  * OF ANY KIND, either express or implied. See the License for the specific language
12
12
  * governing permissions and limitations under the License.
13
13
  */
14
- import{CommerceSdkValidationError}from"@adobe/aio-commerce-lib-core/error";import aioLibIms from"@adobe/aio-lib-ims";import{array,email,instance,minLength,nonEmpty,nonOptional,object,optional,picklist,pipe,safeParse,string,transform,union,url}from"valibot";import crypto from"crypto";import OAuth1a from"oauth-1.0a";const imsAuthParameter=name=>pipe(string(`Expected a string value for the IMS auth parameter ${name}`),nonEmpty(`Expected a non-empty string value for the IMS auth parameter ${name}`)),stringArray=name=>pipe(array(string(),`Expected a string array value for the IMS auth parameter ${name}`)),ImsAuthEnvSchema=picklist([`prod`,`stage`]),ImsAuthParamsSchema=object({clientId:imsAuthParameter(`clientId`),clientSecrets:pipe(stringArray(`clientSecrets`),minLength(1,`Expected at least one client secret for IMS auth`)),technicalAccountId:imsAuthParameter(`technicalAccountId`),technicalAccountEmail:pipe(string(`Expected a string value for the IMS auth parameter technicalAccountEmail`),email(`Expected a valid email format for technicalAccountEmail`)),imsOrgId:imsAuthParameter(`imsOrgId`),environment:pipe(optional(ImsAuthEnvSchema)),context:pipe(optional(string())),scopes:pipe(stringArray(`scopes`),minLength(1,`Expected at least one scope for IMS auth`))}),{context,getToken}=aioLibIms;function toImsAuthConfig(config){return{scopes:config.scopes,env:config?.environment??`prod`,context:config.context??`aio-commerce-lib-auth-creds`,client_id:config.clientId,client_secrets:config.clientSecrets,technical_account_id:config.technicalAccountId,technical_account_email:config.technicalAccountEmail,ims_org_id:config.imsOrgId}}function assertImsAuthParams(config){let result=safeParse(ImsAuthParamsSchema,config);if(!result.success)throw new CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues})}function getImsAuthProvider(authParams){let getAccessToken=async()=>{let imsAuthConfig=toImsAuthConfig(authParams);return await context.set(imsAuthConfig.context,imsAuthConfig),getToken(imsAuthConfig.context,{})};return{getAccessToken,getHeaders:async()=>({Authorization:`Bearer ${await getAccessToken()}`,"x-api-key":authParams.clientId})}}const integrationAuthParameter=name=>pipe(string(`Expected a string value for the Commerce Integration parameter ${name}`),nonEmpty(`Expected a non-empty string value for the Commerce Integration parameter ${name}`)),BaseUrlSchema=pipe(string(`Expected a string for the Adobe Commerce endpoint`),nonEmpty(`Expected a non-empty string for the Adobe Commerce endpoint`),url(`Expected a valid url for the Adobe Commerce endpoint`));pipe(union([BaseUrlSchema,instance(URL)]),transform(url$1=>url$1 instanceof URL?url$1.toString():url$1));const IntegrationAuthParamsSchema=nonOptional(object({consumerKey:integrationAuthParameter(`consumerKey`),consumerSecret:integrationAuthParameter(`consumerSecret`),accessToken:integrationAuthParameter(`accessToken`),accessTokenSecret:integrationAuthParameter(`accessTokenSecret`)}));function assertIntegrationAuthParams(config){let result=safeParse(IntegrationAuthParamsSchema,config);if(!result.success)throw new CommerceSdkValidationError(`Invalid IntegrationAuthProvider configuration`,{issues:result.issues})}function getIntegrationAuthProvider(authParams){let oauth=new OAuth1a({consumer:{key:authParams.consumerKey,secret:authParams.consumerSecret},signature_method:`HMAC-SHA256`,hash_function:(baseString,key)=>crypto.createHmac(`sha256`,key).update(baseString).digest(`base64`)}),oauthToken={key:authParams.accessToken,secret:authParams.accessTokenSecret};return{getHeaders:(method,url$1)=>{let urlString=url$1 instanceof URL?url$1.toString():url$1;return oauth.toHeader(oauth.authorize({url:urlString,method},oauthToken))}}}export{assertImsAuthParams,assertIntegrationAuthParams,getImsAuthProvider,getIntegrationAuthProvider};
14
+ import aioLibIms from"@adobe/aio-lib-ims";import{CommerceSdkValidationError}from"@adobe/aio-commerce-lib-core/error";import{array,email,instance,minLength,nonEmpty,nonOptional,object,optional,parse,picklist,pipe,safeParse,string,transform,union,url}from"valibot";import crypto from"crypto";import OAuth1a from"oauth-1.0a";import{allNonEmpty}from"@adobe/aio-commerce-lib-core/params";const{context,getToken}=aioLibIms;function toImsAuthConfig(config){return{scopes:config.scopes,env:config?.environment??`prod`,context:config.context??`aio-commerce-lib-auth-creds`,client_id:config.clientId,client_secrets:config.clientSecrets,technical_account_id:config.technicalAccountId,technical_account_email:config.technicalAccountEmail,ims_org_id:config.imsOrgId}}function isImsAuthProvider(provider){return typeof provider==`object`&&!!provider&&`getAccessToken`in provider&&`getHeaders`in provider&&typeof provider.getAccessToken==`function`&&typeof provider.getHeaders==`function`}function getImsAuthProvider(authParams){let getAccessToken=async()=>{let imsAuthConfig=toImsAuthConfig(authParams);return await context.set(imsAuthConfig.context,imsAuthConfig),getToken(imsAuthConfig.context,{})};return{getAccessToken,getHeaders:async()=>({Authorization:`Bearer ${await getAccessToken()}`,"x-api-key":authParams.clientId})}}const imsAuthParameter=name=>pipe(string(`Expected a string value for the IMS auth parameter ${name}`),nonEmpty(`Expected a non-empty string value for the IMS auth parameter ${name}`)),stringArray=name=>pipe(array(string(),`Expected a string array value for the IMS auth parameter ${name}`)),ImsAuthEnvSchema=picklist([`prod`,`stage`]),ImsAuthParamsSchema=object({clientId:imsAuthParameter(`clientId`),clientSecrets:pipe(stringArray(`clientSecrets`),minLength(1,`Expected at least one client secret for IMS auth`)),technicalAccountId:imsAuthParameter(`technicalAccountId`),technicalAccountEmail:pipe(string(`Expected a string value for the IMS auth parameter technicalAccountEmail`),email(`Expected a valid email format for technicalAccountEmail`)),imsOrgId:imsAuthParameter(`imsOrgId`),environment:pipe(optional(ImsAuthEnvSchema)),context:pipe(optional(string())),scopes:pipe(stringArray(`scopes`),minLength(1,`Expected at least one scope for IMS auth`))});function assertImsAuthParams(config){let result=safeParse(ImsAuthParamsSchema,config);if(!result.success)throw new CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues})}function resolveImsAuthParams(params){let resolvedParams={clientId:params.AIO_COMMERCE_AUTH_IMS_CLIENT_ID,clientSecrets:params.AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS,technicalAccountId:params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID,technicalAccountEmail:params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL,imsOrgId:params.AIO_COMMERCE_AUTH_IMS_ORG_ID,scopes:params.AIO_COMMERCE_AUTH_IMS_SCOPES,environment:params.AIO_COMMERCE_AUTH_IMS_ENVIRONMENT,context:params.AIO_COMMERCE_AUTH_IMS_CONTEXT};return assertImsAuthParams(resolvedParams),resolvedParams}const integrationAuthParameter=name=>pipe(string(`Expected a string value for the Commerce Integration parameter ${name}`),nonEmpty(`Expected a non-empty string value for the Commerce Integration parameter ${name}`)),UrlSchema=pipe(union([pipe(string(`Expected a string for the Adobe Commerce endpoint`),nonEmpty(`Expected a non-empty string for the Adobe Commerce endpoint`),url(`Expected a valid url for the Adobe Commerce endpoint`)),instance(URL)]),transform(url$1=>url$1 instanceof URL?url$1.toString():url$1)),IntegrationAuthParamsSchema=nonOptional(object({consumerKey:integrationAuthParameter(`consumerKey`),consumerSecret:integrationAuthParameter(`consumerSecret`),accessToken:integrationAuthParameter(`accessToken`),accessTokenSecret:integrationAuthParameter(`accessTokenSecret`)}));function isIntegrationAuthProvider(provider){return typeof provider==`object`&&!!provider&&`getHeaders`in provider&&typeof provider.getHeaders==`function`}function getIntegrationAuthProvider(authParams){let oauth=new OAuth1a({consumer:{key:authParams.consumerKey,secret:authParams.consumerSecret},signature_method:`HMAC-SHA256`,hash_function:(baseString,key)=>crypto.createHmac(`sha256`,key).update(baseString).digest(`base64`)}),oauthToken={key:authParams.accessToken,secret:authParams.accessTokenSecret};return{getHeaders:(method,url$1)=>{let urlString=parse(UrlSchema,url$1);return oauth.toHeader(oauth.authorize({url:urlString,method},oauthToken))}}}function assertIntegrationAuthParams(config){let result=safeParse(IntegrationAuthParamsSchema,config);if(!result.success)throw new CommerceSdkValidationError(`Invalid IntegrationAuthProvider configuration`,{issues:result.issues})}function resolveIntegrationAuthParams(params){let resolvedParams={consumerKey:params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY,consumerSecret:params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET,accessToken:params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN,accessTokenSecret:params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET};return assertIntegrationAuthParams(resolvedParams),resolvedParams}const IMS_AUTH_PARAMS=[`AIO_COMMERCE_AUTH_IMS_CLIENT_ID`,`AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS`,`AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID`,`AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL`,`AIO_COMMERCE_AUTH_IMS_ORG_ID`,`AIO_COMMERCE_AUTH_IMS_SCOPES`],INTEGRATION_AUTH_PARAMS=[`AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY`,`AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET`,`AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN`,`AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET`];function resolveAuthParams(params){if(allNonEmpty(params,IMS_AUTH_PARAMS))return Object.assign(resolveImsAuthParams(params),{strategy:`ims`});if(allNonEmpty(params,INTEGRATION_AUTH_PARAMS))return Object.assign(resolveIntegrationAuthParams(params),{strategy:`integration`});throw Error(`Can't resolve authentication options for the given params. Please provide either IMS options (${IMS_AUTH_PARAMS.join(`, `)}) or Commerce integration options (${INTEGRATION_AUTH_PARAMS.join(`, `)}).`)}export{assertImsAuthParams,assertIntegrationAuthParams,getImsAuthProvider,getIntegrationAuthProvider,isImsAuthProvider,isIntegrationAuthProvider,resolveAuthParams};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@adobe/aio-commerce-lib-auth",
3
3
  "type": "module",
4
4
  "author": "Adobe Inc.",
5
- "version": "0.4.0",
5
+ "version": "0.6.0",
6
6
  "private": false,
7
7
  "engines": {
8
8
  "node": ">=20 <=24"
@@ -51,12 +51,12 @@
51
51
  "ansis": "^4.1.0",
52
52
  "oauth-1.0a": "^2.2.6",
53
53
  "valibot": "^1.1.0",
54
- "@adobe/aio-commerce-lib-core": "0.4.1"
54
+ "@adobe/aio-commerce-lib-core": "0.5.0"
55
55
  },
56
56
  "devDependencies": {
57
+ "@aio-commerce-sdk/config-tsdown": "1.0.0",
57
58
  "@aio-commerce-sdk/config-typedoc": "1.0.0",
58
59
  "@aio-commerce-sdk/config-typescript": "1.0.0",
59
- "@aio-commerce-sdk/config-tsdown": "1.0.0",
60
60
  "@aio-commerce-sdk/config-vitest": "1.0.0"
61
61
  },
62
62
  "sideEffects": false,