UNPKG

@interopio/gateway

Version:

[![npm version](https://img.shields.io/npm/v/@interopio/gateway.svg)](https://www.npmjs.com/package/@interopio/gateway)

3 lines (2 loc) 7.14 kB
"use strict";var R=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var B=(t,e)=>{for(var r in e)R(t,r,{get:e[r],enumerable:!0})},Q=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of q(e))!z.call(t,n)&&n!==r&&R(t,n,{get:()=>e[n],enumerable:!(s=Y(e,n))||s.enumerable});return t};var X=t=>Q(R({},"__esModule",{value:!0}),t);var oe={};B(oe,{JwtVerifyError:()=>l,jwtVerifier:()=>U});module.exports=X(oe);async function b(t,e,r){let s=await(r?.fetchFn??globalThis.fetch)(t.href,{signal:AbortSignal.timeout(e),headers:r?.headers});if(s.status!==200)throw new Error(`Failed to fetch ${t.href}: ${s.statusText}`);try{return await s.json()}catch{throw new Error("Failed to parse response")}}var W="/.well-known/openid-configuration",V="/.well-known/oauth-authorization-server";function I(t){if(!t.issuer)throw new Error("'issuer' not found is authorization server metadata")}async function Z({issuerBaseUri:t,timeout:e,fetchFn:r}){let s=new URL(t);if(s.pathname.includes("/.well-known/")){let a=await b(s,e,{fetchFn:r});return I(a),a}let n=[];s.pathname.endsWith("/")?n.push(`${s.pathname}${W.substring(1)}`):n.push(`${s.pathname}${W}`),s.pathname.endsWith("/")?n.push(`${V}`):n.push(`${V}${s.pathname}`);for(let a of n)try{let i=new URL(a,s),o=await b(i,e,{fetchFn:r});return I(o),o}catch{}throw new Error("Failed to fetch authorization server metadata")}var L=t=>{let e,r=0;return()=>{let s=Date.now();return(!e||s>r+t.cacheMaxAge)&&(r=s,e=Z(t).catch(n=>{throw e=void 0,n})),e}};var g=require("jsrsasign");var c=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}},w=class extends c{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},y=class extends c{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},h=class extends c{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},m=class extends c{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="No matching key found in the JSON Web Key Set",r){super(e,r)}},J=class extends c{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",r){super(e,r)}};function ee(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new w('Unsupported "alg" value for a JSON Web Key Set')}}function te(t){return!!t&&typeof t=="object"&&Array.isArray(t.keys)}var K=class{#e;#t=new WeakMap;constructor(e){if(!te(e))throw new h("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,r){let{alg:s,kid:n}={...e,...r?.header},a=ee(s),i=this.#e.keys.filter(u=>{let f=u.kty===a;return f&&typeof n=="string"&&(f=u.kid===n),f&&typeof u.alg=="string"&&(f=u.alg===s),f&&typeof u.use=="string"&&(f=u.use==="sig"),f}),{0:o,length:d}=i;if(d===0)throw new m;if(d!==1)throw new Error("Multiple matching keys found");return re(this.#t,o,s)}};async function re(t,e,r){let s=t.get(e)||t.set(e,{}).get(e);if(s[r]===void 0){let n=g.KEYUTIL.getKey(e);if(n instanceof g.RSAKey)s[r]=n;else throw new Error("RSA key expected!")}return s[r]}function T(t){let e=new K(t),r=async(s,n)=>await e.getKey(s,n);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(e.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}async function se(t,e,r,s=globalThis.fetch){let n=await s(t,{method:"GET",signal:r,redirect:"manual",headers:e}).catch(a=>{throw a.name==="TimeoutError"?new J:a});if(n.status!==200)throw new c(`Expected 200 OK from JSON Web Key Set response, got ${n.status} ${n.statusText}`);try{return await n.json()}catch(a){throw new c(`Failed to parse the JSON Web Key Set response as JSON: ${a instanceof Error?a.message:String(a)}`)}}var k=class{#e;#t;#o;#a;#n;#r;#i;#s;constructor(e,r){this.#t=new URL(e.href),this.#o=typeof r.timeout=="number"?r.timeout:5e3,this.#a=typeof r.cacheMaxAge=="number"?r.cacheMaxAge:6e5,this.#e=r.fetchFn,this.#i=new Headers(r.headers)}fresh(){return typeof this.#n=="number"?Date.now()<this.#n+this.#a:!1}jwks(){return this.#s?.jwks()}async getKey(e,r){return(!this.#s||!this.fresh())&&await this.reload(),await this.#s(e,r)}async reload(){this.#r||=se(this.#t.href,this.#i,AbortSignal.timeout(this.#o),this.#e).then(e=>{this.#s=T(e),this.#n=Date.now(),this.#r=void 0}).catch(e=>{throw this.#r=void 0,e}),await this.#r}};function A(t,e){let r=new k(t,e),s=async(n,a)=>r.getKey(n,a);return Object.defineProperties(s,{jwks:{value:()=>structuredClone(r.jwks()),enumerable:!1,configurable:!1,writable:!1}}),s}var F=({timeout:t,cacheMaxAge:e,fetchFn:r,crypto:s})=>{let n,a;return i=>((n===void 0||a!==i)&&(a=i,n=A(new URL(i),{fetchFn:r,timeout:t,cacheMaxAge:e})),n)};var S=require("jsrsasign");function E(t){if(typeof t=="string")return[t];if(Array.isArray(t))return t}function M(t,e,r){let{headerObj:s,payloadObj:n}=S.KJUR.jws.JWS.parse(t),a={alg:r?.algorithms??[s.alg],aud:E(r?.audience),iss:E(r?.issuer),sub:E(r?.subject),gracePeriod:r?.clockTolerance};if(typeof e=="function")return e(s).then(i=>S.KJUR.jws.JWS.verifyJWT(t,i,a)).then(i=>{if(!i)throw new y;return{payload:n,protectedHeader:s}});if(S.KJUR.jws.JWS.verifyJWT(t,e,a))return{payload:n,protectedHeader:s};throw new y}var H=(t,e,r)=>{for(let[s,n]of Object.entries(r))if(n!==!1){let a=s==="alg"||s==="typ"?e[s]:t[s];if(!(typeof n=="string"&&a===n||typeof n=="function"&&n(a,t,e)))throw new Error(`Unexpected '${s}' value: ${JSON.stringify(a)}`)}},N=(t,e,r,s,n,a,i)=>({alg:o=>typeof o=="string"&&o.toLowerCase()!=="none"&&(a===void 0||a.includes(o))&&(i===void 0||o===i),typ:o=>!n||typeof o=="string"&&o.toLowerCase().replace(/^application\//,"")==="at+jwt",iss:o=>typeof o=="string"&&o===t,aud:o=>(e=typeof e=="string"?[e]:e,typeof o=="string"?e.includes(o):Array.isArray(o)?e.some(Set.prototype.has.bind(new Set(o))):!1),exp:o=>{let d=Math.floor(Date.now()/1e3);return typeof o=="number"&&o>=d-r},iat:o=>{if(s===void 0)return o===void 0&&!n||typeof o=="number";let d=Math.floor(Date.now()/1e3);return typeof o=="number"&&o<d+r&&o>d-r-s},sub:o=>o===void 0&&!n||typeof o=="string",jti:o=>o===void 0&&!n||typeof o=="string"});var l=class extends Error{},ne=({issuerBaseUri:t="",jwksUri:e="",issuer:r="",audience:s="",tokenSigningAlg:n,timeout:a=5e3,cacheMaxAge:i=6e5,clockTolerance:o=5,maxTokenAge:d,strict:u=!1,validators:f,fetchFn:O})=>{let P,_;if(!(t||r&&e))throw new Error("Either 'issuerBaseUri' or both 'issuer' and 'jwksUri' must be provided");if(!s)throw new Error("An 'audience' is required to validate the 'aud' claim");let C=L({issuerBaseUri:t,timeout:a,cacheMaxAge:i,fetchFn:O}),j=F({timeout:a,cacheMaxAge:i,fetchFn:O});return async x=>{try{if(t){let{jwks_uri:D,issuer:$,id_token_signing_alg_values_supported:G}=await C();e=e||D,r=r||$,P=G}_??={...N(r,s,o,d,u,P,n),...f};let{payload:p,protectedHeader:v}=await M(x,j(e),{clockTolerance:o});return H(p,v,_),{payload:p,header:v,token:x}}catch(p){throw new l(`${p instanceof Error?p.message:String(p)}`)}}},U=ne; //# sourceMappingURL=jwt.cjs.map