UNPKG

@adobe/aio-commerce-lib-auth

Version:

Authentication utilities for Adobe Commerce apps deployed in Adobe App Builder.

14 lines 7.89 kB
/** * @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. */ 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}`)),StringArrayTransformSchema=name=>pipe(union([stringArray(name,1),pipe(string(),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=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})}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};