@adobe/aio-commerce-lib-auth
Version:
Authentication utilities for Adobe Commerce apps deployed in Adobe App Builder.
14 lines • 9.8 kB
JavaScript
/**
* @license
*
* Copyright 2025 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
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}`)),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})}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;