@commercelayer/js-auth
Advanced tools
Comparing version 6.7.0 to 6.7.1
@@ -32,3 +32,3 @@ interface TBaseOptions { | ||
*/ | ||
'x-backend-auth'?: string; | ||
"x-backend-auth"?: string; | ||
/** | ||
@@ -41,3 +41,3 @@ * Optional header to forward the client IP address in server-side requests. Its use requires the presence of | ||
*/ | ||
'x-true-client-ip'?: string; | ||
"x-true-client-ip"?: string; | ||
/** | ||
@@ -58,3 +58,3 @@ * Allows for additional headers as needed, where each key is the header name and the value is the header content. | ||
*/ | ||
tokenType: 'bearer'; | ||
tokenType: "bearer"; | ||
/** | ||
@@ -106,3 +106,3 @@ * The access token expiration time in seconds. | ||
ownerId: string; | ||
ownerType: 'customer'; | ||
ownerType: "customer"; | ||
refreshToken: string; | ||
@@ -129,4 +129,4 @@ } | ||
} | ||
interface TAuthorizationCodeReturn extends Omit<TPasswordReturn, 'ownerType'> { | ||
ownerType: 'user'; | ||
interface TAuthorizationCodeReturn extends Omit<TPasswordReturn, "ownerType"> { | ||
ownerType: "user"; | ||
} | ||
@@ -169,4 +169,4 @@ | ||
} | ||
interface TJwtBearerReturn extends Omit<TPasswordReturn, 'ownerType'> { | ||
ownerType: 'user' | 'customer'; | ||
interface TJwtBearerReturn extends Omit<TPasswordReturn, "ownerType"> { | ||
ownerType: "user" | "customer"; | ||
} | ||
@@ -193,9 +193,9 @@ | ||
*/ | ||
type GrantType = 'password' | 'refresh_token' | 'client_credentials' | 'authorization_code' | 'urn:ietf:params:oauth:grant-type:jwt-bearer'; | ||
type GrantType = "password" | "refresh_token" | "client_credentials" | "authorization_code" | "urn:ietf:params:oauth:grant-type:jwt-bearer"; | ||
/** The options type for the `authenticate` helper. */ | ||
type AuthenticateOptions<TGrantType extends GrantType> = TGrantType extends 'urn:ietf:params:oauth:grant-type:jwt-bearer' ? TJwtBearerOptions : TGrantType extends 'password' ? TPasswordOptions : TGrantType extends 'refresh_token' ? TRefreshTokenOptions : TGrantType extends 'client_credentials' ? TClientCredentialsOptions : TGrantType extends 'authorization_code' ? TAuthorizationCodeOptions : never; | ||
type AuthenticateOptions<TGrantType extends GrantType> = TGrantType extends "urn:ietf:params:oauth:grant-type:jwt-bearer" ? TJwtBearerOptions : TGrantType extends "password" ? TPasswordOptions : TGrantType extends "refresh_token" ? TRefreshTokenOptions : TGrantType extends "client_credentials" ? TClientCredentialsOptions : TGrantType extends "authorization_code" ? TAuthorizationCodeOptions : never; | ||
/** The return type of the `authenticate` helper. */ | ||
type AuthenticateReturn<TGrantType extends GrantType> = TGrantType extends 'urn:ietf:params:oauth:grant-type:jwt-bearer' ? TJwtBearerReturn : TGrantType extends 'password' ? TPasswordReturn : TGrantType extends 'refresh_token' ? TPasswordReturn : TGrantType extends 'client_credentials' ? TBaseReturn : TGrantType extends 'authorization_code' ? TAuthorizationCodeReturn : never; | ||
type AuthenticateReturn<TGrantType extends GrantType> = TGrantType extends "urn:ietf:params:oauth:grant-type:jwt-bearer" ? TJwtBearerReturn : TGrantType extends "password" ? TPasswordReturn : TGrantType extends "refresh_token" ? TPasswordReturn : TGrantType extends "client_credentials" ? TBaseReturn : TGrantType extends "authorization_code" ? TAuthorizationCodeReturn : never; | ||
/** The options type for the `revoke` helper. */ | ||
type RevokeOptions = Pick<TBaseOptions, 'clientId'> & { | ||
type RevokeOptions = Pick<TBaseOptions, "clientId"> & { | ||
/** Your application's client secret (required for confidential API credentials and non-confidential API credentials without a customer or a user in the JWT only). */ | ||
@@ -207,3 +207,3 @@ clientSecret?: string; | ||
/** The return type of the `revoke` helper. */ | ||
type RevokeReturn = Pick<TError, 'errors'>; | ||
type RevokeReturn = Pick<TError, "errors">; | ||
@@ -295,3 +295,3 @@ /** | ||
application: { | ||
kind: 'user'; | ||
kind: "user"; | ||
}; | ||
@@ -309,3 +309,3 @@ /** The authenticated user. */ | ||
application: { | ||
kind: 'dashboard'; | ||
kind: "dashboard"; | ||
}; | ||
@@ -328,3 +328,3 @@ /** The authenticated user. */ | ||
id: string; | ||
type: 'Customer' | 'User'; | ||
type: "Customer" | "User"; | ||
}; | ||
@@ -350,6 +350,6 @@ /** | ||
*/ | ||
type JWTWebApp = SetRequired<JWTOrganizationBase, 'owner'> & { | ||
type JWTWebApp = SetRequired<JWTOrganizationBase, "owner"> & { | ||
/** The type of credentials you're using to authenticate to the APIs. */ | ||
application: { | ||
kind: 'webapp'; | ||
kind: "webapp"; | ||
}; | ||
@@ -367,3 +367,3 @@ }; | ||
application: { | ||
kind: 'sales_channel'; | ||
kind: "sales_channel"; | ||
}; | ||
@@ -377,3 +377,3 @@ }; | ||
application: { | ||
kind: 'integration'; | ||
kind: "integration"; | ||
}; | ||
@@ -437,3 +437,3 @@ }; | ||
interface Owner { | ||
type: 'User' | 'Customer'; | ||
type: "User" | "Customer"; | ||
id: string; | ||
@@ -479,3 +479,3 @@ } | ||
/** At least one of `owner` or `custom_claim` is required. You cannot use an empty object. */ | ||
'https://commercelayer.io/claims': RequireAtLeastOne<{ | ||
"https://commercelayer.io/claims": RequireAtLeastOne<{ | ||
/** The customer or user you want to make the calls on behalf of. */ | ||
@@ -482,0 +482,0 @@ owner?: Owner; |
@@ -1,2 +0,2 @@ | ||
function y(e){return e.replace(/[A-Z]/g,function(t){return"_"+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}; | ||
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 |
{ | ||
"name": "@commercelayer/js-auth", | ||
"version": "6.7.0", | ||
"version": "6.7.1", | ||
"description": "A JavaScript library designed to simplify authentication when interacting with the Commerce Layer API.", | ||
@@ -40,9 +40,9 @@ "repository": { | ||
"devDependencies": { | ||
"@types/jsonwebtoken": "^9.0.7", | ||
"@types/jsonwebtoken": "^9.0.8", | ||
"@types/node": "^20", | ||
"jsonwebtoken": "^9.0.2", | ||
"tsup": "^8.3.0", | ||
"typescript": "^5.6.3", | ||
"vitest": "^2.1.3", | ||
"vitest-fetch-mock": "^0.3.0" | ||
"tsup": "^8.3.6", | ||
"typescript": "^5.7.3", | ||
"vitest": "^3.0.5", | ||
"vitest-fetch-mock": "^0.4.3" | ||
}, | ||
@@ -53,4 +53,4 @@ "engines": { | ||
"scripts": { | ||
"lint": "eslint src --ext .ts,.tsx", | ||
"lint:fix": "eslint src --ext .ts,.tsx --fix", | ||
"lint": "pnpm biome check src", | ||
"lint:fix": "pnpm biome check src --write", | ||
"test": "pnpm run lint:fix && vitest run", | ||
@@ -57,0 +57,0 @@ "test:watch": "vitest", |
@@ -41,4 +41,5 @@ # Commerce Layer JS Auth | ||
[](https://jsr.io/@commercelayer/js-auth) | ||
 | ||
 | ||
| ||
[](https://discord.gg/commercelayer) | ||
@@ -91,3 +92,3 @@ ### Installation | ||
metricsAPI(<b>Metrics API</b><br/><br/>https://<<b>slug</b>>.commercelayer.io/metrics) | ||
comingSoon(<b>Metrics API</b><br/><br/>https://<b>metrics</b>.commercelayer.io) | ||
comingSoon(<b>Metrics API</b> (coming soon)<br/><br/>https://<b>metrics</b>.commercelayer.io) | ||
@@ -100,2 +101,3 @@ %% Node styles | ||
style webapp fill:#E1D5E7,stroke:#9673A6,color:#000 | ||
style comingSoon opacity:.3 | ||
@@ -111,3 +113,3 @@ %% Connections | ||
user --> provisioningAPI | ||
user -- coming soon --> comingSoon | ||
user --> comingSoon | ||
sales_channel --> coreAPI | ||
@@ -123,3 +125,3 @@ integration --> coreAPI | ||
linkStyle 6 stroke:#B85450 | ||
linkStyle 7 stroke:#B85450,stroke-dasharray: 5 5; | ||
linkStyle 7 stroke:#B85450,stroke-dasharray: 5 5,opacity:.3 | ||
linkStyle 8 stroke:#82B366 | ||
@@ -432,10 +434,8 @@ linkStyle 9 stroke:#6C8EBF | ||
1. Request an invite to join [Commerce Layer's Slack community](https://slack.commercelayer.app/). | ||
- Join [Commerce Layer's Discord community](https://discord.gg/commercelayer). | ||
- Ping us on [Bluesky](https://bsky.app/profile/commercelayer.io), [X (formerly Twitter)](https://x.com/commercelayer), or [LinkedIn](https://www.linkedin.com/company/commerce-layer). | ||
- Is there a bug? Create an [issue](https://github.com/commercelayer/commercelayer-js-auth/issues) on this repository. | ||
2. Create an [issue](https://github.com/commercelayer/commercelayer-js-auth/issues) in this repository. | ||
3. Ping us [on Twitter](https://twitter.com/commercelayer). | ||
## License | ||
This repository is published under the [MIT](LICENSE) license. |
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
139016