@commercelayer/js-auth
Advanced tools
Comparing version 6.4.0 to 6.5.0
@@ -471,2 +471,15 @@ interface TBaseOptions { | ||
/** | ||
* Derive the [Core API base endpoint](https://docs.commercelayer.io/core/api-specification#base-endpoint) given a valid access token. | ||
* | ||
* @example | ||
* ```ts | ||
* getCoreApiBaseEndpoint('eyJhbGciOiJS...') //= "https://yourdomain.commercelayer.io" | ||
* ``` | ||
* | ||
* The method requires a valid access token with an `organization` in the payload. | ||
* When the organization is not set (e.g., provisioning token), it throws an `InvalidTokenError` exception. | ||
*/ | ||
declare function getCoreApiBaseEndpoint(accessToken: string): string; | ||
/** | ||
* A token error occurred. | ||
@@ -492,2 +505,2 @@ */ | ||
export { type AuthenticateOptions, type AuthenticateReturn, type GrantType, InvalidTokenError, type JWTDashboard, type JWTIntegration, type JWTSalesChannel, type JWTUser, type JWTWebApp, type RevokeOptions, type RevokeReturn, TokenError, TokenExpiredError, authenticate, createAssertion, jwtDecode, jwtIsDashboard, jwtIsIntegration, jwtIsSalesChannel, jwtIsUser, jwtIsWebApp, jwtVerify, revoke }; | ||
export { type AuthenticateOptions, type AuthenticateReturn, type GrantType, InvalidTokenError, type JWTDashboard, type JWTIntegration, type JWTSalesChannel, type JWTUser, type JWTWebApp, type RevokeOptions, type RevokeReturn, TokenError, TokenExpiredError, authenticate, createAssertion, getCoreApiBaseEndpoint, jwtDecode, jwtIsDashboard, jwtIsIntegration, jwtIsSalesChannel, jwtIsUser, jwtIsWebApp, jwtVerify, revoke }; |
@@ -1,2 +0,2 @@ | ||
function y(e){return e.replace(/[A-Z]/g,function(n){return"_"+n.toLowerCase()})}function c(e,n){return Object.keys(e).reduce((t,r)=>{let o=n(r);return t[o]=e[r],t},{})}function g(e){return e.replace(/([-_][a-z])/g,n=>n.toUpperCase().replace("-","").replace("_",""))}async function h(e,{domain:n="commercelayer.io",headers:t,...r}){let o=c({grant_type:e,...r},y),s=await(await fetch(`https://auth.${n}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...t},body:JSON.stringify(o)})).json();return s.errors==null&&(s.expires=new Date(Date.now()+s.expires_in*1e3)),c(s,g)}async function x({domain:e="commercelayer.io",...n}){let t=c(n,y);return await(await fetch(`https://auth.${e}/oauth/revoke`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)})).json()}var i=class extends Error{constructor(n){super(n),this.name="TokenError"}};var p=class extends i{constructor(n){super(n),this.name="InvalidTokenError"}};function u(e){return typeof btoa<"u"?btoa(e).replaceAll("=","").replaceAll("+","-").replaceAll("/","_"):Buffer.from(e,"binary").toString("base64url")}function l(e){return typeof atob<"u"?atob(e.replaceAll("-","+").replaceAll("_","/")):Buffer.from(e,"base64url").toString("binary")}function f(e){let[n,t,r]=`${e}`.split(".");if(n==null||t==null||r==null)throw new p("Invalid token format");return{header:JSON.parse(l(n)),payload:JSON.parse(l(t)),signature:r}}function J(e){return e.application.kind==="user"}function S(e){return e.application.kind==="dashboard"}function b(e){return e.application.kind==="integration"}function W(e){return e.application.kind==="sales_channel"}function A(e){return e.application.kind==="webapp"}var d=class extends i{constructor(){super("Token expired"),this.name="TokenExpiredError"}};async function j(e,{ignoreExpiration:n=!1,domain:t,jwk:r}={}){let o=f(e),a=r??await R(o.header.kid,{domain:t});if(a==null||a.kid!==o.header.kid)throw new p('Invalid token "kid"');if(!n&&Date.now()>=o.payload.exp*1e3)throw new d;let s={name:"RSASSA-PKCS1-v1_5",hash:"SHA-512"},T=await crypto.subtle.importKey("jwk",a,s,!0,["verify"]),w=new Uint8Array(Array.from(l(o.signature),C=>C.charCodeAt(0))),k=new TextEncoder().encode(e.split(".").slice(0,2).join("."));if(!await crypto.subtle.verify(s,T,w,k))throw new p("Invalid signature");return o}var m={};async function R(e,n){if(m[e]!=null)return m[e];let t=await P(n);return m[e]=t.find(r=>r.kid===e),m[e]}async function P({domain:e="commercelayer.io"}){let n=`https://auth.${e}/.well-known/jwks.json`,t=await fetch(n).then(async r=>await r.json());if(t.keys==null)throw new i(`Invalid jwks response from "${n}": ${JSON.stringify(t)}`);return t.keys}async function O({payload:e}){return await I(e,"cl")}async function I(e,n){let r=u(JSON.stringify({alg:"HS512",typ:"JWT"})),o=u(JSON.stringify({...e,iat:Math.floor(new Date().getTime()/1e3)})),a=`${r}.${o}`,s=await K(a,n);return`${a}.${s}`}async function K(e,n){let t=new TextEncoder,r={name:"HMAC",hash:"SHA-512"},o=await crypto.subtle.importKey("raw",t.encode(n),r,!1,["sign","verify"]),a=await crypto.subtle.sign(r.name,o,t.encode(e));return u(String.fromCharCode(...new Uint8Array(a)))}export{p as InvalidTokenError,i as TokenError,d as TokenExpiredError,h as authenticate,O as createAssertion,f as jwtDecode,S as jwtIsDashboard,b as jwtIsIntegration,W as jwtIsSalesChannel,J as jwtIsUser,A as jwtIsWebApp,j as jwtVerify,x as revoke}; | ||
function m(e){return e.replace(/[A-Z]/g,function(t){return"_"+t.toLowerCase()})}function c(e,t){return Object.keys(e).reduce((n,r)=>{let o=t(r);return n[o]=e[r],n},{})}function g(e){return e.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}async function C(e,{domain:t="commercelayer.io",headers:n,...r}){let o=c({grant_type:e,...r},m),i=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 i.errors==null&&(i.expires=new Date(Date.now()+i.expires_in*1e3)),c(i,g)}async function x({domain:e="commercelayer.io",...t}){let n=c(t,m);return await(await fetch(`https://auth.${e}/oauth/revoke`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)})).json()}var p=class extends Error{constructor(t){super(t),this.name="TokenError"}};var a=class extends p{constructor(t){super(t),this.name="InvalidTokenError"}};function u(e){return typeof btoa<"u"?btoa(e).replaceAll("=","").replaceAll("+","-").replaceAll("/","_"):Buffer.from(e,"binary").toString("base64url")}function l(e){return typeof atob<"u"?atob(e.replaceAll("-","+").replaceAll("_","/")):Buffer.from(e,"base64url").toString("binary")}function d(e){let[t,n,r]=`${e}`.split(".");if(t==null||n==null||r==null)throw new a("Invalid token format");return{header:JSON.parse(l(t)),payload:JSON.parse(l(n)),signature:r}}function J(e){return e.application.kind==="user"}function S(e){return e.application.kind==="dashboard"}function b(e){return e.application.kind==="integration"}function W(e){return e.application.kind==="sales_channel"}function A(e){return e.application.kind==="webapp"}var y=class extends p{constructor(){super("Token expired"),this.name="TokenExpiredError"}};async function j(e,{ignoreExpiration:t=!1,domain:n,jwk:r}={}){let o=d(e),s=r??await R(o.header.kid,{domain:n});if(s==null||s.kid!==o.header.kid)throw new a('Invalid token "kid"');if(!t&&Date.now()>=o.payload.exp*1e3)throw new y;let i={name:"RSASSA-PKCS1-v1_5",hash:"SHA-512"},T=await crypto.subtle.importKey("jwk",s,i,!0,["verify"]),w=new Uint8Array(Array.from(l(o.signature),h=>h.charCodeAt(0))),k=new TextEncoder().encode(e.split(".").slice(0,2).join("."));if(!await crypto.subtle.verify(i,T,w,k))throw new a("Invalid signature");return o}var f={};async function R(e,t){if(f[e]!=null)return f[e];let n=await P(t);return f[e]=n.find(r=>r.kid===e),f[e]}async function P({domain:e="commercelayer.io"}){let t=`https://auth.${e}/.well-known/jwks.json`,n=await fetch(t).then(async r=>await r.json());if(n.keys==null)throw new p(`Invalid jwks response from "${t}": ${JSON.stringify(n)}`);return n.keys}async function O({payload:e}){return await I(e,"cl")}async function I(e,t){let r=u(JSON.stringify({alg:"HS512",typ:"JWT"})),o=u(JSON.stringify({...e,iat:Math.floor(new Date().getTime()/1e3)})),s=`${r}.${o}`,i=await K(s,t);return`${s}.${i}`}async function K(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"]),s=await crypto.subtle.sign(r.name,o,n.encode(e));return u(String.fromCharCode(...new Uint8Array(s)))}function v(e){let t=d(e);if(!("organization"in t.payload))throw new a("Invalid token format");return t.payload.iss.startsWith("https://auth.")?t.payload.iss.replace("auth",t.payload.organization.slug):`https://${t.payload.organization.slug}.commercelayer.io`}export{a as InvalidTokenError,p as TokenError,y as TokenExpiredError,C as authenticate,O as createAssertion,v as getCoreApiBaseEndpoint,d as jwtDecode,S as jwtIsDashboard,b as jwtIsIntegration,W as jwtIsSalesChannel,J as jwtIsUser,A as jwtIsWebApp,j as jwtVerify,x as revoke}; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@commercelayer/js-auth", | ||
"version": "6.4.0", | ||
"version": "6.5.0", | ||
"description": "A JavaScript library designed to simplify authentication when interacting with the Commerce Layer API.", | ||
@@ -44,3 +44,3 @@ "repository": { | ||
"tsup": "^8.2.4", | ||
"typescript": "^5.5.4", | ||
"typescript": "^5.6.2", | ||
"vitest": "^2.0.5", | ||
@@ -55,3 +55,3 @@ "vitest-fetch-mock": "^0.3.0" | ||
"lint:fix": "eslint src --ext .ts,.tsx --fix", | ||
"test": "pnpm run lint && vitest run", | ||
"test": "pnpm run lint:fix && vitest run", | ||
"test:watch": "vitest", | ||
@@ -58,0 +58,0 @@ "build": "tsup", |
@@ -27,2 +27,3 @@ # Commerce Layer JS Auth | ||
- [Verify an access token](#verify-an-access-token) | ||
- [Get Core API base endpoint](#get-core-api-base-endpoint) | ||
- [Contributors guide](#contributors-guide) | ||
@@ -81,2 +82,4 @@ - [Need help?](#need-help) | ||
- [Provisioning application](#provisioning) | ||
- [JWT bearer](#jwt-bearer) | ||
- [Revoking a token](#revoking-a-token) | ||
@@ -329,2 +332,14 @@ ### Sales channel (client credentials) | ||
### Get Core API base endpoint | ||
Derive the [Core API base endpoint](https://docs.commercelayer.io/core/api-specification#base-endpoint) given a valid access token. | ||
```ts | ||
import { getCoreApiBaseEndpoint } from '@commercelayer/js-auth' | ||
getCoreApiBaseEndpoint('a-valid-access-token') //= "https://yourdomain.commercelayer.io" | ||
``` | ||
The method requires a valid access token with an `organization` in the payload. When the organization is not set (e.g., provisioning token), it throws an `InvalidTokenError` exception. | ||
--- | ||
@@ -331,0 +346,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
113875
523
369