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