UNPKG

@commercelayer/js-auth

Version:

A JavaScript library designed to simplify authentication when interacting with the Commerce Layer API.

2 lines 4.28 kB
function y(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function l(e,t){return Object.keys(e).reduce((n,r)=>{let o=t(r);return n[o]=e[r],n},{})}function T(e){return e.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}async function x(e,{domain:t="commercelayer.io",headers:n,...r}){let o=l({grant_type:e,...r},y),c=await(await fetch(`https://auth.${t}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n},body:JSON.stringify(o)})).json();return c.errors==null&&(c.expires=new Date(Date.now()+c.expires_in*1e3)),l(c,T)}var s=class extends Error{constructor(t){super(t),this.name="TokenError"}};var a=class extends s{constructor(t){super(t),this.name="InvalidTokenError"}};function f(e,t){if(typeof btoa<"u"){let n=e;if(t==="utf-8"){let r=new TextEncoder().encode(e);n=String.fromCharCode(...r)}return btoa(n).replaceAll("=","").replaceAll("+","-").replaceAll("/","_")}return Buffer.from(e,t).toString("base64url")}function u(e,t){if(typeof atob<"u"){let n=atob(e.replaceAll("-","+").replaceAll("_","/").padEnd(e.length+(4-e.length%4)%4,"="));if(t==="utf-8"){let r=new Uint8Array([...n].map(o=>o.charCodeAt(0)));return new TextDecoder().decode(r)}return n}return Buffer.from(e,"base64url").toString(t)}function i(e){let[t,n,r]=`${e}`.split(".");if(t==null||n==null||r==null)throw new a("Invalid token format");return{header:JSON.parse(u(t,"binary")),payload:JSON.parse(u(n,"utf-8")),signature:r}}function C(e){return e.application.kind==="user"}function J(e){return e.application.kind==="dashboard"}function b(e){return e.application.kind==="integration"}function S(e){return e.application.kind==="sales_channel"}function W(e){return e.application.kind==="webapp"}function d(e){return e?.payload?.iss?.startsWith("https://auth.")?e.payload.iss:"https://auth.commercelayer.io"}async function A(e){let t=l(e,y),n=i(e.token),r=d(n);return await(await fetch(`${r}/oauth/revoke`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)})).json()}var m=class extends s{constructor(){super("Token expired"),this.name="TokenExpiredError"}};async function j(e,{ignoreExpiration:t=!1,jwk:n}={}){let r=i(e),o=n??await R(r);if(o==null||o.kid!==r.header.kid)throw new a('Invalid token "kid"');if(!t&&Date.now()>=r.payload.exp*1e3)throw new m;let p={name:"RSASSA-PKCS1-v1_5",hash:"SHA-512"},c=await crypto.subtle.importKey("jwk",o,p,!0,["verify"]),w=new Uint8Array(Array.from(u(r.signature,"binary"),k=>k.charCodeAt(0))),h=new TextEncoder().encode(e.split(".").slice(0,2).join("."));if(!await crypto.subtle.verify(p,c,w,h))throw new a("Invalid signature");return r}var g={};async function R(e){let{kid:t}=e.header;if(g[t]!=null)return g[t];let n=await I(e);return g[t]=n.find(r=>r.kid===t),g[t]}async function I(e){let t=`${d(e)}/.well-known/jwks.json`,n=await fetch(t).then(async r=>await r.json());if(n.keys==null)throw new s(`Invalid jwks response from "${t}": ${JSON.stringify(n)}`);return n.keys}async function P({payload:e}){return await v(e,"cl")}async function v(e,t){let r=f(JSON.stringify({alg:"HS512",typ:"JWT"}),"binary"),o=f(JSON.stringify({...e,iat:Math.floor(new Date().getTime()/1e3)}),"utf-8"),p=`${r}.${o}`,c=await E(p,t);return`${p}.${c}`}async function E(e,t){let n=new TextEncoder,r={name:"HMAC",hash:"SHA-512"},o=await crypto.subtle.importKey("raw",n.encode(t),r,!1,["sign","verify"]),p=await crypto.subtle.sign(r.name,o,n.encode(e));return f(String.fromCharCode(...new Uint8Array(p)),"binary")}function O(e,t={}){let{shouldThrow:n=!0}=t,r=i(e);if(!("organization"in r.payload)){if(n)throw new a("Invalid token format");return null}return d(r).replace("auth",r.payload.organization.slug)}function L(e,t={}){let{shouldThrow:n=!0}=t,r=i(e);if(!r?.payload?.scope?.includes("provisioning-api")){if(n)throw new a("Invalid token format");return null}return d(r).replace("auth","provisioning")}export{a as InvalidTokenError,s as TokenError,m as TokenExpiredError,x as authenticate,P as createAssertion,O as getCoreApiBaseEndpoint,L as getProvisioningApiBaseEndpoint,i as jwtDecode,J as jwtIsDashboard,b as jwtIsIntegration,S as jwtIsSalesChannel,C as jwtIsUser,W as jwtIsWebApp,j as jwtVerify,A as revoke}; //# sourceMappingURL=index.js.map