@adobe/aio-commerce-lib-auth 0.6.1 → 0.7.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 +17 -0
- package/dist/cjs/index.cjs +1 -14
- package/dist/cjs/index.d.cts +145 -51
- package/dist/es/{index.d.ts → index.d.mts} +146 -51
- package/dist/es/index.mjs +1 -0
- package/package.json +12 -6
- package/dist/es/index.js +0 -14
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# @adobe/aio-commerce-lib-auth
|
|
2
2
|
|
|
3
|
+
## 0.7.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#224](https://github.com/adobe/aio-commerce-sdk/pull/224) [`ac46985`](https://github.com/adobe/aio-commerce-sdk/commit/ac46985186961c65eddc6be3200dbe1e00369055) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Implement token forwarding utilities
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [[`f2b6f34`](https://github.com/adobe/aio-commerce-sdk/commit/f2b6f34709a5adcca93b852b5855cb6b1c852312), [`f2b6f34`](https://github.com/adobe/aio-commerce-sdk/commit/f2b6f34709a5adcca93b852b5855cb6b1c852312)]:
|
|
12
|
+
- @adobe/aio-commerce-lib-core@0.6.0
|
|
13
|
+
|
|
14
|
+
## 0.6.2
|
|
15
|
+
|
|
16
|
+
### Patch Changes
|
|
17
|
+
|
|
18
|
+
- [#153](https://github.com/adobe/aio-commerce-sdk/pull/153) [`3c88b74`](https://github.com/adobe/aio-commerce-sdk/commit/3c88b74ccfea0df06514b696ce8797c95e1acc4f) Thanks [@iivvaannxx](https://github.com/iivvaannxx)! - Parse IMS scopes from potential string arrays, when resolving from a params object.
|
|
19
|
+
|
|
3
20
|
## 0.6.1
|
|
4
21
|
|
|
5
22
|
### Patch Changes
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,14 +1 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @license
|
|
3
|
-
*
|
|
4
|
-
* Copyright 2025 Adobe. All rights reserved.
|
|
5
|
-
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License. You may obtain a copy
|
|
7
|
-
* of the License at http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
-
*
|
|
9
|
-
* Unless required by applicable law or agreed to in writing, software distributed under
|
|
10
|
-
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
|
|
11
|
-
* OF ANY KIND, either express or implied. See the License for the specific language
|
|
12
|
-
* governing permissions and limitations under the License.
|
|
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_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,minimumLength)=>(0,valibot.pipe)((0,valibot.array)((0,valibot.string)(),`Expected a string array value for the IMS auth parameter ${name}`),(0,valibot.minLength)(minimumLength,`Expected at least ${minimumLength} items for the IMS auth parameter ${name}`)),maybeJsonStringArray=name=>(0,valibot.pipe)(imsAuthParameter(name),(0,valibot.rawTransform)(({dataset:{value:v},addIssue,NEVER})=>{if(v.startsWith(`[`)&&v.endsWith(`]`))try{return JSON.parse(v)}catch(error){let errorMessage=error.message;return addIssue({received:v,message:`Expected a valid JSON array for the IMS auth parameter "${name}": ${errorMessage}`}),NEVER}return[v]})),ImsAuthEnvSchema=(0,valibot.picklist)([`prod`,`stage`]),ImsAuthParamsSchema=(0,valibot.object)({clientId:imsAuthParameter(`clientId`),clientSecrets:(0,valibot.pipe)((0,valibot.union)([maybeJsonStringArray(`clientSecrets`),stringArray(`clientSecrets`,1)]),stringArray(`clientSecrets`,1)),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:stringArray(`scopes`,1)});function __parseImsAuthParams(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});return result.output}function assertImsAuthParams(config){__parseImsAuthParams(config)}function resolveImsAuthParams(params){return __parseImsAuthParams({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})}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 __parseIntegrationAuthParams(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});return result.output}function assertIntegrationAuthParams(config){__parseIntegrationAuthParams(config)}function resolveIntegrationAuthParams(params){return __parseIntegrationAuthParams({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})}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;
|
|
1
|
+
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_headers=require(`@adobe/aio-commerce-lib-core/headers`),valibot=require(`valibot`);valibot=__toESM(valibot);let _adobe_aio_commerce_lib_core_error=require(`@adobe/aio-commerce-lib-core/error`),_adobe_aio_lib_ims=require(`@adobe/aio-lib-ims`);_adobe_aio_lib_ims=__toESM(_adobe_aio_lib_ims);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`);function stringValueSchema(propertyName){return valibot.string(`Expected a string value for property '${propertyName}'`)}function parseOrThrow(schema,input,message){let result=valibot.safeParse(schema,input);if(!result.success)throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(message??`Invalid input`,{issues:result.issues});return result.output}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,minimumLength)=>(0,valibot.pipe)((0,valibot.array)((0,valibot.string)(),`Expected a string array value for the IMS auth parameter ${name}`),(0,valibot.minLength)(minimumLength,`Expected at least ${minimumLength} items for the IMS auth parameter ${name}`)),StringArrayTransformSchema=name=>(0,valibot.pipe)((0,valibot.union)([stringArray(name,1),(0,valibot.pipe)((0,valibot.string)(),(0,valibot.rawTransform)(({dataset:{value:v},addIssue,NEVER})=>{if(v.startsWith(`[`)&&v.endsWith(`]`))try{let parsed=JSON.parse(v);return Array.isArray(parsed)?parsed:(addIssue({received:v,message:`Expected a valid JSON array for the IMS auth parameter ${name}: ${v}`}),NEVER)}catch(error){let errorMessage=error.message;return addIssue({received:v,message:`Expected a valid JSON array for the IMS auth parameter ${name}: ${errorMessage}`}),NEVER}return[v]}))]),stringArray(`value`,1)),ImsAuthEnvSchema=(0,valibot.picklist)([`prod`,`stage`]),ImsAuthParamsSchema=(0,valibot.object)({clientId:imsAuthParameter(`clientId`),clientSecrets:stringArray(`clientSecrets`,1),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:stringArray(`scopes`,1)});function __transformStringArray(name,value){if(value===void 0)return;let result=(0,valibot.safeParse)(StringArrayTransformSchema(name),value);if(!result.success)throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues});return result.output}function __parseImsAuthParams(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});return result.output}function assertImsAuthParams(config){__parseImsAuthParams(config)}function resolveImsAuthParams(params){return __parseImsAuthParams({clientId:params.AIO_COMMERCE_AUTH_IMS_CLIENT_ID,clientSecrets:__transformStringArray(`AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS`,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:__transformStringArray(`AIO_COMMERCE_AUTH_IMS_SCOPES`,params.AIO_COMMERCE_AUTH_IMS_SCOPES),environment:params.AIO_COMMERCE_AUTH_IMS_ENVIRONMENT,context:params.AIO_COMMERCE_AUTH_IMS_CONTEXT})}function buildImsHeaders(accessToken,apiKey){let imsHeaders={Authorization:`Bearer ${accessToken}`};return apiKey&&(imsHeaders[`x-api-key`]=apiKey),imsHeaders}const IMS_AUTH_TOKEN_PARAM=`AIO_COMMERCE_AUTH_IMS_TOKEN`,IMS_AUTH_API_KEY_PARAM=`AIO_COMMERCE_AUTH_IMS_API_KEY`,ImsAuthParamsInputSchema=valibot.looseObject({[IMS_AUTH_TOKEN_PARAM]:stringValueSchema(IMS_AUTH_TOKEN_PARAM),[IMS_AUTH_API_KEY_PARAM]:valibot.optional(stringValueSchema(IMS_AUTH_API_KEY_PARAM))}),ForwardedImsAuthSourceSchema=valibot.variant(`from`,[valibot.object({from:valibot.literal(`headers`),headers:valibot.record(valibot.string(),valibot.optional(valibot.string()))}),valibot.object({from:valibot.literal(`getter`),getHeaders:valibot.custom(input=>typeof input==`function`,`Expected a function for getHeaders`)}),valibot.object({from:valibot.literal(`params`),params:ImsAuthParamsInputSchema})]);function getForwardedImsAuthProvider(source){let validatedSource=parseOrThrow(ForwardedImsAuthSourceSchema,source,`Invalid forwarded IMS auth source`);switch(validatedSource.from){case`headers`:{let{authorization}=(0,_adobe_aio_commerce_lib_core_headers.createHeaderAccessor)(validatedSource.headers,[`Authorization`]),apiKey=(0,_adobe_aio_commerce_lib_core_headers.getHeader)(validatedSource.headers,`x-api-key`),{token}=(0,_adobe_aio_commerce_lib_core_headers.parseBearerToken)(authorization);return{getAccessToken:()=>token,getHeaders:()=>buildImsHeaders(token,apiKey)}}case`getter`:return{getHeaders:validatedSource.getHeaders,getAccessToken:async()=>{let{token}=(0,_adobe_aio_commerce_lib_core_headers.parseBearerToken)((await validatedSource.getHeaders()).Authorization);return token}};case`params`:{let{params}=validatedSource,accessToken=params[IMS_AUTH_TOKEN_PARAM],apiKey=params[IMS_AUTH_API_KEY_PARAM];return{getAccessToken:()=>accessToken,getHeaders:()=>buildImsHeaders(accessToken,apiKey)}}}}function forwardImsAuthProviderFromRequest(params){return getForwardedImsAuthProvider({from:`headers`,headers:(0,_adobe_aio_commerce_lib_core_headers.getHeadersFromParams)(params)})}function forwardImsAuthProviderFromParams(params){return getForwardedImsAuthProvider({from:`params`,params:parseOrThrow(ImsAuthParamsInputSchema,params,`Missing AIO_COMMERCE_AUTH_IMS_TOKEN in params`)})}function forwardImsAuthProvider(params){try{return forwardImsAuthProviderFromParams(params)}catch{}try{return forwardImsAuthProviderFromRequest(params)}catch{}throw Error(`Can't forward IMS authentication from the given params. Make sure your params contain an AIO_COMMERCE_AUTH_IMS_TOKEN input or an Authorization header with an IMS token.`)}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()=>buildImsHeaders(await getAccessToken(),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 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 __parseIntegrationAuthParams(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});return result.output}function assertIntegrationAuthParams(config){__parseIntegrationAuthParams(config)}function resolveIntegrationAuthParams(params){return __parseIntegrationAuthParams({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})}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{...resolveImsAuthParams(params),strategy:`ims`};if((0,_adobe_aio_commerce_lib_core_params.allNonEmpty)(params,INTEGRATION_AUTH_PARAMS))return{...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.forwardImsAuthProvider=forwardImsAuthProvider,exports.getForwardedImsAuthProvider=getForwardedImsAuthProvider,exports.getImsAuthProvider=getImsAuthProvider,exports.getIntegrationAuthProvider=getIntegrationAuthProvider,exports.isImsAuthProvider=isImsAuthProvider,exports.isIntegrationAuthProvider=isIntegrationAuthProvider,exports.resolveAuthParams=resolveAuthParams;
|
package/dist/cjs/index.d.cts
CHANGED
|
@@ -1,33 +1,141 @@
|
|
|
1
|
-
|
|
2
|
-
* @license
|
|
3
|
-
*
|
|
4
|
-
* Copyright 2025 Adobe. All rights reserved.
|
|
5
|
-
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License. You may obtain a copy
|
|
7
|
-
* of the License at http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
-
*
|
|
9
|
-
* Unless required by applicable law or agreed to in writing, software distributed under
|
|
10
|
-
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
|
|
11
|
-
* OF ANY KIND, either express or implied. See the License for the specific language
|
|
12
|
-
* governing permissions and limitations under the License.
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import * as valibot21 from "valibot";
|
|
1
|
+
import * as v from "valibot";
|
|
16
2
|
import { InferOutput } from "valibot";
|
|
17
3
|
|
|
4
|
+
//#region source/lib/ims-auth/types.d.ts
|
|
5
|
+
/** Defines the headers required for IMS authentication. */
|
|
6
|
+
type ImsAuthHeaders = {
|
|
7
|
+
Authorization: string;
|
|
8
|
+
"x-api-key"?: string;
|
|
9
|
+
};
|
|
10
|
+
/** Defines an authentication provider for Adobe IMS. */
|
|
11
|
+
type ImsAuthProvider = {
|
|
12
|
+
getAccessToken: () => Promise<string> | string;
|
|
13
|
+
getHeaders: () => Promise<ImsAuthHeaders> | ImsAuthHeaders;
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region source/lib/ims-auth/forwarding.d.ts
|
|
17
|
+
declare const ForwardedImsAuthSourceSchema: v.VariantSchema<"from", [v.ObjectSchema<{
|
|
18
|
+
readonly from: v.LiteralSchema<"headers", undefined>;
|
|
19
|
+
readonly headers: v.RecordSchema<v.StringSchema<undefined>, v.OptionalSchema<v.StringSchema<undefined>, undefined>, undefined>;
|
|
20
|
+
}, undefined>, v.ObjectSchema<{
|
|
21
|
+
readonly from: v.LiteralSchema<"getter", undefined>;
|
|
22
|
+
readonly getHeaders: v.CustomSchema<() => ImsAuthHeaders | Promise<ImsAuthHeaders>, v.ErrorMessage<v.CustomIssue> | undefined>;
|
|
23
|
+
}, undefined>, v.ObjectSchema<{
|
|
24
|
+
readonly from: v.LiteralSchema<"params", undefined>;
|
|
25
|
+
readonly params: v.LooseObjectSchema<{
|
|
26
|
+
readonly AIO_COMMERCE_AUTH_IMS_TOKEN: v.StringSchema<`Expected a string value for property '${string}'`>;
|
|
27
|
+
readonly AIO_COMMERCE_AUTH_IMS_API_KEY: v.OptionalSchema<v.StringSchema<`Expected a string value for property '${string}'`>, undefined>;
|
|
28
|
+
}, undefined>;
|
|
29
|
+
}, undefined>], undefined>;
|
|
30
|
+
/**
|
|
31
|
+
* Discriminated union for different sources of forwarded IMS auth credentials.
|
|
32
|
+
*
|
|
33
|
+
* - `headers`: Extract credentials from a raw headers object (e.g. an HTTP request).
|
|
34
|
+
* - `getter`: Use a function that returns IMS auth headers (sync or async).
|
|
35
|
+
* - `params`: Read credentials from a params object using `AIO_COMMERCE_AUTH_IMS_TOKEN` and `AIO_COMMERCE_AUTH_IMS_API_KEY` keys.
|
|
36
|
+
*/
|
|
37
|
+
type ForwardedImsAuthSource = v.InferOutput<typeof ForwardedImsAuthSourceSchema>;
|
|
38
|
+
/**
|
|
39
|
+
* Creates an {@link ImsAuthProvider} by forwarding authentication credentials from various sources.
|
|
40
|
+
*
|
|
41
|
+
* @param source The source of the credentials to forward, as a {@link ForwardedImsAuthSource}.
|
|
42
|
+
* @returns An {@link ImsAuthProvider} instance that returns the forwarded access token and headers.
|
|
43
|
+
*
|
|
44
|
+
* @throws {CommerceSdkValidationError} If the source object is invalid.
|
|
45
|
+
* @throws {CommerceSdkValidationError} If `from: "headers"` is used and the `Authorization` header is missing.
|
|
46
|
+
* @throws {CommerceSdkValidationError} If `from: "headers"` is used and the `Authorization` header is not in Bearer token format.
|
|
47
|
+
* @throws {CommerceSdkValidationError} If `from: "params"` is used and `AIO_COMMERCE_AUTH_IMS_TOKEN` is missing or empty.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```typescript
|
|
51
|
+
* import { getForwardedImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
|
|
52
|
+
*
|
|
53
|
+
* // From raw headers (e.g. from an HTTP request).
|
|
54
|
+
* const provider1 = getForwardedImsAuthProvider({
|
|
55
|
+
* from: "headers",
|
|
56
|
+
* headers: params.__ow_headers,
|
|
57
|
+
* });
|
|
58
|
+
*
|
|
59
|
+
* // From async getter (e.g. fetch from secret manager)
|
|
60
|
+
* const provider2 = getForwardedImsAuthProvider({
|
|
61
|
+
* from: "getter",
|
|
62
|
+
* getHeaders: async () => {
|
|
63
|
+
* const token = await secretManager.getSecret("ims-token");
|
|
64
|
+
* return { Authorization: `Bearer ${token}` };
|
|
65
|
+
* },
|
|
66
|
+
* });
|
|
67
|
+
*
|
|
68
|
+
* // From a params object (using AIO_COMMERCE_AUTH_IMS_TOKEN and AIO_COMMERCE_AUTH_IMS_API_KEY keys)
|
|
69
|
+
* const provider3 = getForwardedImsAuthProvider({
|
|
70
|
+
* from: "params",
|
|
71
|
+
* params: actionParams,
|
|
72
|
+
* });
|
|
73
|
+
*
|
|
74
|
+
* // Use the provider
|
|
75
|
+
* const token = await provider1.getAccessToken();
|
|
76
|
+
* const headers = await provider1.getHeaders();
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
declare function getForwardedImsAuthProvider(source: v.InferInput<typeof ForwardedImsAuthSourceSchema>): ImsAuthProvider;
|
|
80
|
+
/**
|
|
81
|
+
* Creates an {@link ImsAuthProvider} by forwarding authentication credentials from runtime action parameters.
|
|
82
|
+
*
|
|
83
|
+
* This function automatically detects the source of credentials by trying multiple strategies in order:
|
|
84
|
+
* 1. **Params token** - Looks for `AIO_COMMERCE_AUTH_IMS_TOKEN` (and optionally `AIO_COMMERCE_AUTH_IMS_API_KEY`) in the params object
|
|
85
|
+
* 2. **HTTP headers** - Falls back to extracting the `Authorization` header from `__ow_headers`
|
|
86
|
+
*
|
|
87
|
+
* Use this function when building actions that receive authenticated requests and need to forward
|
|
88
|
+
* those credentials to downstream services (proxy pattern).
|
|
89
|
+
*
|
|
90
|
+
* @param params The runtime action parameters object. Can contain either:
|
|
91
|
+
* - `AIO_COMMERCE_AUTH_IMS_TOKEN` and optionally `AIO_COMMERCE_AUTH_IMS_API_KEY` for direct token forwarding
|
|
92
|
+
* - `__ow_headers` with an `Authorization` header for HTTP request forwarding
|
|
93
|
+
* @returns An {@link ImsAuthProvider} instance that returns the forwarded access token and headers.
|
|
94
|
+
*
|
|
95
|
+
* @throws {Error} If neither a valid token param nor Authorization header is found.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```typescript
|
|
99
|
+
* import { forwardImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
|
|
100
|
+
*
|
|
101
|
+
* export async function main(params: Record<string, unknown>) {
|
|
102
|
+
* // Automatically detects credentials from params or headers
|
|
103
|
+
* const authProvider = forwardImsAuthProvider(params);
|
|
104
|
+
*
|
|
105
|
+
* // Get the access token
|
|
106
|
+
* const token = await authProvider.getAccessToken();
|
|
107
|
+
*
|
|
108
|
+
* // Get headers for downstream API requests
|
|
109
|
+
* const headers = await authProvider.getHeaders();
|
|
110
|
+
* // {
|
|
111
|
+
* // Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
|
|
112
|
+
* // "x-api-key": "my-api-key" // Only if available
|
|
113
|
+
* // }
|
|
114
|
+
*
|
|
115
|
+
* // Use the forwarded credentials in downstream API calls
|
|
116
|
+
* const response = await fetch("https://api.adobe.io/some-endpoint", {
|
|
117
|
+
* headers,
|
|
118
|
+
* });
|
|
119
|
+
*
|
|
120
|
+
* return { statusCode: 200, body: await response.json() };
|
|
121
|
+
* }
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
declare function forwardImsAuthProvider(params: Record<string, unknown>): ImsAuthProvider;
|
|
125
|
+
//#endregion
|
|
18
126
|
//#region source/lib/ims-auth/schema.d.ts
|
|
19
127
|
/** Validation schema for IMS auth environment values. */
|
|
20
|
-
declare const ImsAuthEnvSchema:
|
|
128
|
+
declare const ImsAuthEnvSchema: v.PicklistSchema<["prod", "stage"], undefined>;
|
|
21
129
|
/** Defines the schema to validate the necessary parameters for the IMS auth service. */
|
|
22
|
-
declare const ImsAuthParamsSchema:
|
|
23
|
-
readonly clientId:
|
|
24
|
-
readonly clientSecrets:
|
|
25
|
-
readonly technicalAccountId:
|
|
26
|
-
readonly technicalAccountEmail:
|
|
27
|
-
readonly imsOrgId:
|
|
28
|
-
readonly environment:
|
|
29
|
-
readonly context:
|
|
30
|
-
readonly scopes:
|
|
130
|
+
declare const ImsAuthParamsSchema: v.ObjectSchema<{
|
|
131
|
+
readonly clientId: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
|
|
132
|
+
readonly clientSecrets: v.SchemaWithPipe<readonly [v.ArraySchema<v.StringSchema<undefined>, `Expected a string array value for the IMS auth parameter ${string}`>, v.MinLengthAction<string[], number, `Expected at least ${number} items for the IMS auth parameter ${string}`>]>;
|
|
133
|
+
readonly technicalAccountId: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
|
|
134
|
+
readonly technicalAccountEmail: v.SchemaWithPipe<readonly [v.StringSchema<"Expected a string value for the IMS auth parameter technicalAccountEmail">, v.EmailAction<string, "Expected a valid email format for technicalAccountEmail">]>;
|
|
135
|
+
readonly imsOrgId: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
|
|
136
|
+
readonly environment: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<["prod", "stage"], undefined>, undefined>]>;
|
|
137
|
+
readonly context: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, undefined>]>;
|
|
138
|
+
readonly scopes: v.SchemaWithPipe<readonly [v.ArraySchema<v.StringSchema<undefined>, `Expected a string array value for the IMS auth parameter ${string}`>, v.MinLengthAction<string[], number, `Expected at least ${number} items for the IMS auth parameter ${string}`>]>;
|
|
31
139
|
}, undefined>;
|
|
32
140
|
/** Defines the parameters for the IMS auth service. */
|
|
33
141
|
type ImsAuthParams = InferOutput<typeof ImsAuthParamsSchema>;
|
|
@@ -35,15 +143,6 @@ type ImsAuthParams = InferOutput<typeof ImsAuthParamsSchema>;
|
|
|
35
143
|
type ImsAuthEnv = InferOutput<typeof ImsAuthEnvSchema>;
|
|
36
144
|
//#endregion
|
|
37
145
|
//#region source/lib/ims-auth/provider.d.ts
|
|
38
|
-
/** Defines the header keys used for IMS authentication. */
|
|
39
|
-
type ImsAuthHeader = "Authorization" | "x-api-key";
|
|
40
|
-
/** Defines the headers required for IMS authentication. */
|
|
41
|
-
type ImsAuthHeaders = Record<ImsAuthHeader, string>;
|
|
42
|
-
/** Defines an authentication provider for Adobe IMS. */
|
|
43
|
-
type ImsAuthProvider = {
|
|
44
|
-
getAccessToken: () => Promise<string>;
|
|
45
|
-
getHeaders: () => Promise<ImsAuthHeaders>;
|
|
46
|
-
};
|
|
47
146
|
/**
|
|
48
147
|
* Type guard to check if a value is an ImsAuthProvider instance.
|
|
49
148
|
*
|
|
@@ -103,10 +202,7 @@ declare function isImsAuthProvider(provider: unknown): provider is ImsAuthProvid
|
|
|
103
202
|
*/
|
|
104
203
|
declare function getImsAuthProvider(authParams: ImsAuthParams): {
|
|
105
204
|
getAccessToken: () => Promise<string>;
|
|
106
|
-
getHeaders: () => Promise<
|
|
107
|
-
Authorization: string;
|
|
108
|
-
"x-api-key": string;
|
|
109
|
-
}>;
|
|
205
|
+
getHeaders: () => Promise<ImsAuthHeaders>;
|
|
110
206
|
};
|
|
111
207
|
//#endregion
|
|
112
208
|
//#region source/lib/ims-auth/utils.d.ts
|
|
@@ -156,11 +252,11 @@ type HttpMethodInput = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
|
156
252
|
* The schema for the Commerce Integration parameters.
|
|
157
253
|
* This is used to validate the parameters passed to the Commerce Integration provider.
|
|
158
254
|
*/
|
|
159
|
-
declare const IntegrationAuthParamsSchema:
|
|
160
|
-
readonly consumerKey:
|
|
161
|
-
readonly consumerSecret:
|
|
162
|
-
readonly accessToken:
|
|
163
|
-
readonly accessTokenSecret:
|
|
255
|
+
declare const IntegrationAuthParamsSchema: v.NonOptionalSchema<v.ObjectSchema<{
|
|
256
|
+
readonly consumerKey: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
|
|
257
|
+
readonly consumerSecret: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
|
|
258
|
+
readonly accessToken: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
|
|
259
|
+
readonly accessTokenSecret: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
|
|
164
260
|
}, undefined>, undefined>;
|
|
165
261
|
/** Defines the parameters required for Commerce Integration authentication. */
|
|
166
262
|
type IntegrationAuthParams = InferOutput<typeof IntegrationAuthParamsSchema>;
|
|
@@ -272,7 +368,8 @@ declare function assertIntegrationAuthParams(config: Record<PropertyKey, unknown
|
|
|
272
368
|
* }
|
|
273
369
|
* ```
|
|
274
370
|
*/
|
|
275
|
-
declare function resolveAuthParams(params: Record<string, unknown>):
|
|
371
|
+
declare function resolveAuthParams(params: Record<string, unknown>): {
|
|
372
|
+
strategy: "ims";
|
|
276
373
|
clientId: string;
|
|
277
374
|
clientSecrets: string[];
|
|
278
375
|
technicalAccountId: string;
|
|
@@ -281,15 +378,12 @@ declare function resolveAuthParams(params: Record<string, unknown>): ({
|
|
|
281
378
|
environment?: "prod" | "stage" | undefined;
|
|
282
379
|
context?: string | undefined;
|
|
283
380
|
scopes: string[];
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
}) | ({
|
|
381
|
+
} | {
|
|
382
|
+
strategy: "integration";
|
|
287
383
|
consumerKey: string;
|
|
288
384
|
consumerSecret: string;
|
|
289
385
|
accessToken: string;
|
|
290
386
|
accessTokenSecret: string;
|
|
291
|
-
}
|
|
292
|
-
readonly strategy: "integration";
|
|
293
|
-
});
|
|
387
|
+
};
|
|
294
388
|
//#endregion
|
|
295
|
-
export { type ImsAuthEnv, type ImsAuthParams, type ImsAuthProvider, type IntegrationAuthParams, type IntegrationAuthProvider, assertImsAuthParams, assertIntegrationAuthParams, getImsAuthProvider, getIntegrationAuthProvider, isImsAuthProvider, isIntegrationAuthProvider, resolveAuthParams };
|
|
389
|
+
export { type ForwardedImsAuthSource, type ImsAuthEnv, type ImsAuthHeaders, type ImsAuthParams, type ImsAuthProvider, type IntegrationAuthParams, type IntegrationAuthProvider, assertImsAuthParams, assertIntegrationAuthParams, forwardImsAuthProvider, getForwardedImsAuthProvider, getImsAuthProvider, getIntegrationAuthProvider, isImsAuthProvider, isIntegrationAuthProvider, resolveAuthParams };
|
|
@@ -1,33 +1,142 @@
|
|
|
1
|
-
|
|
2
|
-
* @license
|
|
3
|
-
*
|
|
4
|
-
* Copyright 2025 Adobe. All rights reserved.
|
|
5
|
-
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License. You may obtain a copy
|
|
7
|
-
* of the License at http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
-
*
|
|
9
|
-
* Unless required by applicable law or agreed to in writing, software distributed under
|
|
10
|
-
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
|
|
11
|
-
* OF ANY KIND, either express or implied. See the License for the specific language
|
|
12
|
-
* governing permissions and limitations under the License.
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import * as valibot21 from "valibot";
|
|
1
|
+
import * as v from "valibot";
|
|
16
2
|
import { InferOutput } from "valibot";
|
|
3
|
+
import "@adobe/aio-commerce-lib-core/params";
|
|
17
4
|
|
|
5
|
+
//#region source/lib/ims-auth/types.d.ts
|
|
6
|
+
/** Defines the headers required for IMS authentication. */
|
|
7
|
+
type ImsAuthHeaders = {
|
|
8
|
+
Authorization: string;
|
|
9
|
+
"x-api-key"?: string;
|
|
10
|
+
};
|
|
11
|
+
/** Defines an authentication provider for Adobe IMS. */
|
|
12
|
+
type ImsAuthProvider = {
|
|
13
|
+
getAccessToken: () => Promise<string> | string;
|
|
14
|
+
getHeaders: () => Promise<ImsAuthHeaders> | ImsAuthHeaders;
|
|
15
|
+
};
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region source/lib/ims-auth/forwarding.d.ts
|
|
18
|
+
declare const ForwardedImsAuthSourceSchema: v.VariantSchema<"from", [v.ObjectSchema<{
|
|
19
|
+
readonly from: v.LiteralSchema<"headers", undefined>;
|
|
20
|
+
readonly headers: v.RecordSchema<v.StringSchema<undefined>, v.OptionalSchema<v.StringSchema<undefined>, undefined>, undefined>;
|
|
21
|
+
}, undefined>, v.ObjectSchema<{
|
|
22
|
+
readonly from: v.LiteralSchema<"getter", undefined>;
|
|
23
|
+
readonly getHeaders: v.CustomSchema<() => ImsAuthHeaders | Promise<ImsAuthHeaders>, v.ErrorMessage<v.CustomIssue> | undefined>;
|
|
24
|
+
}, undefined>, v.ObjectSchema<{
|
|
25
|
+
readonly from: v.LiteralSchema<"params", undefined>;
|
|
26
|
+
readonly params: v.LooseObjectSchema<{
|
|
27
|
+
readonly AIO_COMMERCE_AUTH_IMS_TOKEN: v.StringSchema<`Expected a string value for property '${string}'`>;
|
|
28
|
+
readonly AIO_COMMERCE_AUTH_IMS_API_KEY: v.OptionalSchema<v.StringSchema<`Expected a string value for property '${string}'`>, undefined>;
|
|
29
|
+
}, undefined>;
|
|
30
|
+
}, undefined>], undefined>;
|
|
31
|
+
/**
|
|
32
|
+
* Discriminated union for different sources of forwarded IMS auth credentials.
|
|
33
|
+
*
|
|
34
|
+
* - `headers`: Extract credentials from a raw headers object (e.g. an HTTP request).
|
|
35
|
+
* - `getter`: Use a function that returns IMS auth headers (sync or async).
|
|
36
|
+
* - `params`: Read credentials from a params object using `AIO_COMMERCE_AUTH_IMS_TOKEN` and `AIO_COMMERCE_AUTH_IMS_API_KEY` keys.
|
|
37
|
+
*/
|
|
38
|
+
type ForwardedImsAuthSource = v.InferOutput<typeof ForwardedImsAuthSourceSchema>;
|
|
39
|
+
/**
|
|
40
|
+
* Creates an {@link ImsAuthProvider} by forwarding authentication credentials from various sources.
|
|
41
|
+
*
|
|
42
|
+
* @param source The source of the credentials to forward, as a {@link ForwardedImsAuthSource}.
|
|
43
|
+
* @returns An {@link ImsAuthProvider} instance that returns the forwarded access token and headers.
|
|
44
|
+
*
|
|
45
|
+
* @throws {CommerceSdkValidationError} If the source object is invalid.
|
|
46
|
+
* @throws {CommerceSdkValidationError} If `from: "headers"` is used and the `Authorization` header is missing.
|
|
47
|
+
* @throws {CommerceSdkValidationError} If `from: "headers"` is used and the `Authorization` header is not in Bearer token format.
|
|
48
|
+
* @throws {CommerceSdkValidationError} If `from: "params"` is used and `AIO_COMMERCE_AUTH_IMS_TOKEN` is missing or empty.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```typescript
|
|
52
|
+
* import { getForwardedImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
|
|
53
|
+
*
|
|
54
|
+
* // From raw headers (e.g. from an HTTP request).
|
|
55
|
+
* const provider1 = getForwardedImsAuthProvider({
|
|
56
|
+
* from: "headers",
|
|
57
|
+
* headers: params.__ow_headers,
|
|
58
|
+
* });
|
|
59
|
+
*
|
|
60
|
+
* // From async getter (e.g. fetch from secret manager)
|
|
61
|
+
* const provider2 = getForwardedImsAuthProvider({
|
|
62
|
+
* from: "getter",
|
|
63
|
+
* getHeaders: async () => {
|
|
64
|
+
* const token = await secretManager.getSecret("ims-token");
|
|
65
|
+
* return { Authorization: `Bearer ${token}` };
|
|
66
|
+
* },
|
|
67
|
+
* });
|
|
68
|
+
*
|
|
69
|
+
* // From a params object (using AIO_COMMERCE_AUTH_IMS_TOKEN and AIO_COMMERCE_AUTH_IMS_API_KEY keys)
|
|
70
|
+
* const provider3 = getForwardedImsAuthProvider({
|
|
71
|
+
* from: "params",
|
|
72
|
+
* params: actionParams,
|
|
73
|
+
* });
|
|
74
|
+
*
|
|
75
|
+
* // Use the provider
|
|
76
|
+
* const token = await provider1.getAccessToken();
|
|
77
|
+
* const headers = await provider1.getHeaders();
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
declare function getForwardedImsAuthProvider(source: v.InferInput<typeof ForwardedImsAuthSourceSchema>): ImsAuthProvider;
|
|
81
|
+
/**
|
|
82
|
+
* Creates an {@link ImsAuthProvider} by forwarding authentication credentials from runtime action parameters.
|
|
83
|
+
*
|
|
84
|
+
* This function automatically detects the source of credentials by trying multiple strategies in order:
|
|
85
|
+
* 1. **Params token** - Looks for `AIO_COMMERCE_AUTH_IMS_TOKEN` (and optionally `AIO_COMMERCE_AUTH_IMS_API_KEY`) in the params object
|
|
86
|
+
* 2. **HTTP headers** - Falls back to extracting the `Authorization` header from `__ow_headers`
|
|
87
|
+
*
|
|
88
|
+
* Use this function when building actions that receive authenticated requests and need to forward
|
|
89
|
+
* those credentials to downstream services (proxy pattern).
|
|
90
|
+
*
|
|
91
|
+
* @param params The runtime action parameters object. Can contain either:
|
|
92
|
+
* - `AIO_COMMERCE_AUTH_IMS_TOKEN` and optionally `AIO_COMMERCE_AUTH_IMS_API_KEY` for direct token forwarding
|
|
93
|
+
* - `__ow_headers` with an `Authorization` header for HTTP request forwarding
|
|
94
|
+
* @returns An {@link ImsAuthProvider} instance that returns the forwarded access token and headers.
|
|
95
|
+
*
|
|
96
|
+
* @throws {Error} If neither a valid token param nor Authorization header is found.
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* ```typescript
|
|
100
|
+
* import { forwardImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
|
|
101
|
+
*
|
|
102
|
+
* export async function main(params: Record<string, unknown>) {
|
|
103
|
+
* // Automatically detects credentials from params or headers
|
|
104
|
+
* const authProvider = forwardImsAuthProvider(params);
|
|
105
|
+
*
|
|
106
|
+
* // Get the access token
|
|
107
|
+
* const token = await authProvider.getAccessToken();
|
|
108
|
+
*
|
|
109
|
+
* // Get headers for downstream API requests
|
|
110
|
+
* const headers = await authProvider.getHeaders();
|
|
111
|
+
* // {
|
|
112
|
+
* // Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
|
|
113
|
+
* // "x-api-key": "my-api-key" // Only if available
|
|
114
|
+
* // }
|
|
115
|
+
*
|
|
116
|
+
* // Use the forwarded credentials in downstream API calls
|
|
117
|
+
* const response = await fetch("https://api.adobe.io/some-endpoint", {
|
|
118
|
+
* headers,
|
|
119
|
+
* });
|
|
120
|
+
*
|
|
121
|
+
* return { statusCode: 200, body: await response.json() };
|
|
122
|
+
* }
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
declare function forwardImsAuthProvider(params: Record<string, unknown>): ImsAuthProvider;
|
|
126
|
+
//#endregion
|
|
18
127
|
//#region source/lib/ims-auth/schema.d.ts
|
|
19
128
|
/** Validation schema for IMS auth environment values. */
|
|
20
|
-
declare const ImsAuthEnvSchema:
|
|
129
|
+
declare const ImsAuthEnvSchema: v.PicklistSchema<["prod", "stage"], undefined>;
|
|
21
130
|
/** Defines the schema to validate the necessary parameters for the IMS auth service. */
|
|
22
|
-
declare const ImsAuthParamsSchema:
|
|
23
|
-
readonly clientId:
|
|
24
|
-
readonly clientSecrets:
|
|
25
|
-
readonly technicalAccountId:
|
|
26
|
-
readonly technicalAccountEmail:
|
|
27
|
-
readonly imsOrgId:
|
|
28
|
-
readonly environment:
|
|
29
|
-
readonly context:
|
|
30
|
-
readonly scopes:
|
|
131
|
+
declare const ImsAuthParamsSchema: v.ObjectSchema<{
|
|
132
|
+
readonly clientId: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
|
|
133
|
+
readonly clientSecrets: v.SchemaWithPipe<readonly [v.ArraySchema<v.StringSchema<undefined>, `Expected a string array value for the IMS auth parameter ${string}`>, v.MinLengthAction<string[], number, `Expected at least ${number} items for the IMS auth parameter ${string}`>]>;
|
|
134
|
+
readonly technicalAccountId: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
|
|
135
|
+
readonly technicalAccountEmail: v.SchemaWithPipe<readonly [v.StringSchema<"Expected a string value for the IMS auth parameter technicalAccountEmail">, v.EmailAction<string, "Expected a valid email format for technicalAccountEmail">]>;
|
|
136
|
+
readonly imsOrgId: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the IMS auth parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the IMS auth parameter ${string}`>]>;
|
|
137
|
+
readonly environment: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<["prod", "stage"], undefined>, undefined>]>;
|
|
138
|
+
readonly context: v.SchemaWithPipe<readonly [v.OptionalSchema<v.StringSchema<undefined>, undefined>]>;
|
|
139
|
+
readonly scopes: v.SchemaWithPipe<readonly [v.ArraySchema<v.StringSchema<undefined>, `Expected a string array value for the IMS auth parameter ${string}`>, v.MinLengthAction<string[], number, `Expected at least ${number} items for the IMS auth parameter ${string}`>]>;
|
|
31
140
|
}, undefined>;
|
|
32
141
|
/** Defines the parameters for the IMS auth service. */
|
|
33
142
|
type ImsAuthParams = InferOutput<typeof ImsAuthParamsSchema>;
|
|
@@ -35,15 +144,6 @@ type ImsAuthParams = InferOutput<typeof ImsAuthParamsSchema>;
|
|
|
35
144
|
type ImsAuthEnv = InferOutput<typeof ImsAuthEnvSchema>;
|
|
36
145
|
//#endregion
|
|
37
146
|
//#region source/lib/ims-auth/provider.d.ts
|
|
38
|
-
/** Defines the header keys used for IMS authentication. */
|
|
39
|
-
type ImsAuthHeader = "Authorization" | "x-api-key";
|
|
40
|
-
/** Defines the headers required for IMS authentication. */
|
|
41
|
-
type ImsAuthHeaders = Record<ImsAuthHeader, string>;
|
|
42
|
-
/** Defines an authentication provider for Adobe IMS. */
|
|
43
|
-
type ImsAuthProvider = {
|
|
44
|
-
getAccessToken: () => Promise<string>;
|
|
45
|
-
getHeaders: () => Promise<ImsAuthHeaders>;
|
|
46
|
-
};
|
|
47
147
|
/**
|
|
48
148
|
* Type guard to check if a value is an ImsAuthProvider instance.
|
|
49
149
|
*
|
|
@@ -103,10 +203,7 @@ declare function isImsAuthProvider(provider: unknown): provider is ImsAuthProvid
|
|
|
103
203
|
*/
|
|
104
204
|
declare function getImsAuthProvider(authParams: ImsAuthParams): {
|
|
105
205
|
getAccessToken: () => Promise<string>;
|
|
106
|
-
getHeaders: () => Promise<
|
|
107
|
-
Authorization: string;
|
|
108
|
-
"x-api-key": string;
|
|
109
|
-
}>;
|
|
206
|
+
getHeaders: () => Promise<ImsAuthHeaders>;
|
|
110
207
|
};
|
|
111
208
|
//#endregion
|
|
112
209
|
//#region source/lib/ims-auth/utils.d.ts
|
|
@@ -156,11 +253,11 @@ type HttpMethodInput = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
|
156
253
|
* The schema for the Commerce Integration parameters.
|
|
157
254
|
* This is used to validate the parameters passed to the Commerce Integration provider.
|
|
158
255
|
*/
|
|
159
|
-
declare const IntegrationAuthParamsSchema:
|
|
160
|
-
readonly consumerKey:
|
|
161
|
-
readonly consumerSecret:
|
|
162
|
-
readonly accessToken:
|
|
163
|
-
readonly accessTokenSecret:
|
|
256
|
+
declare const IntegrationAuthParamsSchema: v.NonOptionalSchema<v.ObjectSchema<{
|
|
257
|
+
readonly consumerKey: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
|
|
258
|
+
readonly consumerSecret: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
|
|
259
|
+
readonly accessToken: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
|
|
260
|
+
readonly accessTokenSecret: v.SchemaWithPipe<readonly [v.StringSchema<`Expected a string value for the Commerce Integration parameter ${string}`>, v.NonEmptyAction<string, `Expected a non-empty string value for the Commerce Integration parameter ${string}`>]>;
|
|
164
261
|
}, undefined>, undefined>;
|
|
165
262
|
/** Defines the parameters required for Commerce Integration authentication. */
|
|
166
263
|
type IntegrationAuthParams = InferOutput<typeof IntegrationAuthParamsSchema>;
|
|
@@ -272,7 +369,8 @@ declare function assertIntegrationAuthParams(config: Record<PropertyKey, unknown
|
|
|
272
369
|
* }
|
|
273
370
|
* ```
|
|
274
371
|
*/
|
|
275
|
-
declare function resolveAuthParams(params: Record<string, unknown>):
|
|
372
|
+
declare function resolveAuthParams(params: Record<string, unknown>): {
|
|
373
|
+
strategy: "ims";
|
|
276
374
|
clientId: string;
|
|
277
375
|
clientSecrets: string[];
|
|
278
376
|
technicalAccountId: string;
|
|
@@ -281,15 +379,12 @@ declare function resolveAuthParams(params: Record<string, unknown>): ({
|
|
|
281
379
|
environment?: "prod" | "stage" | undefined;
|
|
282
380
|
context?: string | undefined;
|
|
283
381
|
scopes: string[];
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
}) | ({
|
|
382
|
+
} | {
|
|
383
|
+
strategy: "integration";
|
|
287
384
|
consumerKey: string;
|
|
288
385
|
consumerSecret: string;
|
|
289
386
|
accessToken: string;
|
|
290
387
|
accessTokenSecret: string;
|
|
291
|
-
}
|
|
292
|
-
readonly strategy: "integration";
|
|
293
|
-
});
|
|
388
|
+
};
|
|
294
389
|
//#endregion
|
|
295
|
-
export { type ImsAuthEnv, type ImsAuthParams, type ImsAuthProvider, type IntegrationAuthParams, type IntegrationAuthProvider, assertImsAuthParams, assertIntegrationAuthParams, getImsAuthProvider, getIntegrationAuthProvider, isImsAuthProvider, isIntegrationAuthProvider, resolveAuthParams };
|
|
390
|
+
export { type ForwardedImsAuthSource, type ImsAuthEnv, type ImsAuthHeaders, type ImsAuthParams, type ImsAuthProvider, type IntegrationAuthParams, type IntegrationAuthProvider, assertImsAuthParams, assertIntegrationAuthParams, forwardImsAuthProvider, getForwardedImsAuthProvider, getImsAuthProvider, getIntegrationAuthProvider, isImsAuthProvider, isIntegrationAuthProvider, resolveAuthParams };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHeaderAccessor,getHeader,getHeadersFromParams,parseBearerToken}from"@adobe/aio-commerce-lib-core/headers";import*as v from"valibot";import{array,email,instance,minLength,nonEmpty,nonOptional,object,optional,parse,picklist,pipe,rawTransform,safeParse,string,transform,union,url}from"valibot";import{CommerceSdkValidationError}from"@adobe/aio-commerce-lib-core/error";import aioLibIms from"@adobe/aio-lib-ims";import crypto from"crypto";import OAuth1a from"oauth-1.0a";import{allNonEmpty}from"@adobe/aio-commerce-lib-core/params";function stringValueSchema(propertyName){return v.string(`Expected a string value for property '${propertyName}'`)}function parseOrThrow(schema,input,message){let result=v.safeParse(schema,input);if(!result.success)throw new CommerceSdkValidationError(message??`Invalid input`,{issues:result.issues});return result.output}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,minimumLength)=>pipe(array(string(),`Expected a string array value for the IMS auth parameter ${name}`),minLength(minimumLength,`Expected at least ${minimumLength} items for the IMS auth parameter ${name}`)),StringArrayTransformSchema=name=>pipe(union([stringArray(name,1),pipe(string(),rawTransform(({dataset:{value:v$1},addIssue,NEVER})=>{if(v$1.startsWith(`[`)&&v$1.endsWith(`]`))try{let parsed=JSON.parse(v$1);return Array.isArray(parsed)?parsed:(addIssue({received:v$1,message:`Expected a valid JSON array for the IMS auth parameter ${name}: ${v$1}`}),NEVER)}catch(error){let errorMessage=error.message;return addIssue({received:v$1,message:`Expected a valid JSON array for the IMS auth parameter ${name}: ${errorMessage}`}),NEVER}return[v$1]}))]),stringArray(`value`,1)),ImsAuthEnvSchema=picklist([`prod`,`stage`]),ImsAuthParamsSchema=object({clientId:imsAuthParameter(`clientId`),clientSecrets:stringArray(`clientSecrets`,1),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:stringArray(`scopes`,1)});function __transformStringArray(name,value){if(value===void 0)return;let result=safeParse(StringArrayTransformSchema(name),value);if(!result.success)throw new CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues});return result.output}function __parseImsAuthParams(config){let result=safeParse(ImsAuthParamsSchema,config);if(!result.success)throw new CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues});return result.output}function assertImsAuthParams(config){__parseImsAuthParams(config)}function resolveImsAuthParams(params){return __parseImsAuthParams({clientId:params.AIO_COMMERCE_AUTH_IMS_CLIENT_ID,clientSecrets:__transformStringArray(`AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS`,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:__transformStringArray(`AIO_COMMERCE_AUTH_IMS_SCOPES`,params.AIO_COMMERCE_AUTH_IMS_SCOPES),environment:params.AIO_COMMERCE_AUTH_IMS_ENVIRONMENT,context:params.AIO_COMMERCE_AUTH_IMS_CONTEXT})}function buildImsHeaders(accessToken,apiKey){let imsHeaders={Authorization:`Bearer ${accessToken}`};return apiKey&&(imsHeaders[`x-api-key`]=apiKey),imsHeaders}const IMS_AUTH_TOKEN_PARAM=`AIO_COMMERCE_AUTH_IMS_TOKEN`,IMS_AUTH_API_KEY_PARAM=`AIO_COMMERCE_AUTH_IMS_API_KEY`,ImsAuthParamsInputSchema=v.looseObject({[IMS_AUTH_TOKEN_PARAM]:stringValueSchema(IMS_AUTH_TOKEN_PARAM),[IMS_AUTH_API_KEY_PARAM]:v.optional(stringValueSchema(IMS_AUTH_API_KEY_PARAM))}),ForwardedImsAuthSourceSchema=v.variant(`from`,[v.object({from:v.literal(`headers`),headers:v.record(v.string(),v.optional(v.string()))}),v.object({from:v.literal(`getter`),getHeaders:v.custom(input=>typeof input==`function`,`Expected a function for getHeaders`)}),v.object({from:v.literal(`params`),params:ImsAuthParamsInputSchema})]);function getForwardedImsAuthProvider(source){let validatedSource=parseOrThrow(ForwardedImsAuthSourceSchema,source,`Invalid forwarded IMS auth source`);switch(validatedSource.from){case`headers`:{let{authorization}=createHeaderAccessor(validatedSource.headers,[`Authorization`]),apiKey=getHeader(validatedSource.headers,`x-api-key`),{token}=parseBearerToken(authorization);return{getAccessToken:()=>token,getHeaders:()=>buildImsHeaders(token,apiKey)}}case`getter`:return{getHeaders:validatedSource.getHeaders,getAccessToken:async()=>{let{token}=parseBearerToken((await validatedSource.getHeaders()).Authorization);return token}};case`params`:{let{params}=validatedSource,accessToken=params[IMS_AUTH_TOKEN_PARAM],apiKey=params[IMS_AUTH_API_KEY_PARAM];return{getAccessToken:()=>accessToken,getHeaders:()=>buildImsHeaders(accessToken,apiKey)}}}}function forwardImsAuthProviderFromRequest(params){return getForwardedImsAuthProvider({from:`headers`,headers:getHeadersFromParams(params)})}function forwardImsAuthProviderFromParams(params){return getForwardedImsAuthProvider({from:`params`,params:parseOrThrow(ImsAuthParamsInputSchema,params,`Missing AIO_COMMERCE_AUTH_IMS_TOKEN in params`)})}function forwardImsAuthProvider(params){try{return forwardImsAuthProviderFromParams(params)}catch{}try{return forwardImsAuthProviderFromRequest(params)}catch{}throw Error(`Can't forward IMS authentication from the given params. Make sure your params contain an AIO_COMMERCE_AUTH_IMS_TOKEN input or an Authorization header with an IMS token.`)}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()=>buildImsHeaders(await getAccessToken(),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}`)),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 __parseIntegrationAuthParams(config){let result=safeParse(IntegrationAuthParamsSchema,config);if(!result.success)throw new CommerceSdkValidationError(`Invalid IntegrationAuthProvider configuration`,{issues:result.issues});return result.output}function assertIntegrationAuthParams(config){__parseIntegrationAuthParams(config)}function resolveIntegrationAuthParams(params){return __parseIntegrationAuthParams({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})}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{...resolveImsAuthParams(params),strategy:`ims`};if(allNonEmpty(params,INTEGRATION_AUTH_PARAMS))return{...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,forwardImsAuthProvider,getForwardedImsAuthProvider,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.
|
|
5
|
+
"version": "0.7.0",
|
|
6
6
|
"private": false,
|
|
7
7
|
"engines": {
|
|
8
8
|
"node": ">=20 <=24"
|
|
@@ -25,13 +25,13 @@
|
|
|
25
25
|
"directory": "packages/aio-commerce-lib-auth"
|
|
26
26
|
},
|
|
27
27
|
"main": "./dist/cjs/index.cjs",
|
|
28
|
-
"module": "./dist/es/index.
|
|
28
|
+
"module": "./dist/es/index.mjs",
|
|
29
29
|
"types": "./dist/cjs/index.d.cts",
|
|
30
30
|
"exports": {
|
|
31
31
|
".": {
|
|
32
32
|
"import": {
|
|
33
|
-
"types": "./dist/es/index.d.
|
|
34
|
-
"default": "./dist/es/index.
|
|
33
|
+
"types": "./dist/es/index.d.mts",
|
|
34
|
+
"default": "./dist/es/index.mjs"
|
|
35
35
|
},
|
|
36
36
|
"require": {
|
|
37
37
|
"types": "./dist/cjs/index.d.cts",
|
|
@@ -40,6 +40,10 @@
|
|
|
40
40
|
},
|
|
41
41
|
"./package.json": "./package.json"
|
|
42
42
|
},
|
|
43
|
+
"imports": {
|
|
44
|
+
"#*": "./source/*.ts",
|
|
45
|
+
"#test*": "./test/*.ts"
|
|
46
|
+
},
|
|
43
47
|
"files": [
|
|
44
48
|
"dist",
|
|
45
49
|
"package.json",
|
|
@@ -51,17 +55,19 @@
|
|
|
51
55
|
"ansis": "^4.1.0",
|
|
52
56
|
"oauth-1.0a": "^2.2.6",
|
|
53
57
|
"valibot": "^1.1.0",
|
|
54
|
-
"@adobe/aio-commerce-lib-core": "0.
|
|
58
|
+
"@adobe/aio-commerce-lib-core": "0.6.0"
|
|
55
59
|
},
|
|
56
60
|
"devDependencies": {
|
|
57
61
|
"@aio-commerce-sdk/config-tsdown": "1.0.0",
|
|
62
|
+
"@aio-commerce-sdk/config-typedoc": "1.0.0",
|
|
58
63
|
"@aio-commerce-sdk/config-typescript": "1.0.0",
|
|
59
64
|
"@aio-commerce-sdk/config-vitest": "1.0.0",
|
|
60
|
-
"@aio-commerce-sdk/
|
|
65
|
+
"@aio-commerce-sdk/common-utils": "0.0.2"
|
|
61
66
|
},
|
|
62
67
|
"sideEffects": false,
|
|
63
68
|
"scripts": {
|
|
64
69
|
"build": "tsdown",
|
|
70
|
+
"publint": "publint",
|
|
65
71
|
"docs": "typedoc && prettier --write '**/*.md'",
|
|
66
72
|
"assist": "biome check --formatter-enabled=false --linter-enabled=false --assist-enabled=true --no-errors-on-unmatched",
|
|
67
73
|
"assist:apply": "biome check --write --formatter-enabled=false --linter-enabled=false --assist-enabled=true --no-errors-on-unmatched",
|
package/dist/es/index.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @license
|
|
3
|
-
*
|
|
4
|
-
* Copyright 2025 Adobe. All rights reserved.
|
|
5
|
-
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License. You may obtain a copy
|
|
7
|
-
* of the License at http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
-
*
|
|
9
|
-
* Unless required by applicable law or agreed to in writing, software distributed under
|
|
10
|
-
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
|
|
11
|
-
* OF ANY KIND, either express or implied. See the License for the specific language
|
|
12
|
-
* governing permissions and limitations under the License.
|
|
13
|
-
*/
|
|
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,rawTransform,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,minimumLength)=>pipe(array(string(),`Expected a string array value for the IMS auth parameter ${name}`),minLength(minimumLength,`Expected at least ${minimumLength} items for the IMS auth parameter ${name}`)),maybeJsonStringArray=name=>pipe(imsAuthParameter(name),rawTransform(({dataset:{value:v},addIssue,NEVER})=>{if(v.startsWith(`[`)&&v.endsWith(`]`))try{return JSON.parse(v)}catch(error){let errorMessage=error.message;return addIssue({received:v,message:`Expected a valid JSON array for the IMS auth parameter "${name}": ${errorMessage}`}),NEVER}return[v]})),ImsAuthEnvSchema=picklist([`prod`,`stage`]),ImsAuthParamsSchema=object({clientId:imsAuthParameter(`clientId`),clientSecrets:pipe(union([maybeJsonStringArray(`clientSecrets`),stringArray(`clientSecrets`,1)]),stringArray(`clientSecrets`,1)),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:stringArray(`scopes`,1)});function __parseImsAuthParams(config){let result=safeParse(ImsAuthParamsSchema,config);if(!result.success)throw new CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues});return result.output}function assertImsAuthParams(config){__parseImsAuthParams(config)}function resolveImsAuthParams(params){return __parseImsAuthParams({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})}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 __parseIntegrationAuthParams(config){let result=safeParse(IntegrationAuthParamsSchema,config);if(!result.success)throw new CommerceSdkValidationError(`Invalid IntegrationAuthProvider configuration`,{issues:result.issues});return result.output}function assertIntegrationAuthParams(config){__parseIntegrationAuthParams(config)}function resolveIntegrationAuthParams(params){return __parseIntegrationAuthParams({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})}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};
|