@genation/sdk 0.2.10 → 0.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -127,6 +127,17 @@ try {
127
127
  }
128
128
  ```
129
129
 
130
+ ### Standalone Token Verification
131
+
132
+ You can also verify tokens without a client instance:
133
+
134
+ ```typescript
135
+ import { verifyToken } from "@genation/sdk";
136
+
137
+ // Uses default Genation Auth URL
138
+ const payload = await verifyToken(token);
139
+ ```
140
+
130
141
  ## Session Object
131
142
 
132
143
  ```typescript
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class P extends Error{code;cause;constructor(e,r,n){super(e),this.name="GenationError",this.code=r,this.cause=n}}class S extends P{constructor(e,r,n){super(e,r,n),this.name="AuthError"}static invalidGrant(e="Invalid authorization code or refresh token"){return new S(e,"invalid_grant")}static accessDenied(e="User denied access"){return new S(e,"access_denied")}static expiredToken(e="Token has expired"){return new S(e,"expired_token")}static invalidState(e="State mismatch, possible CSRF attack"){return new S(e,"invalid_state")}static pkceVerificationFailed(e="PKCE verification failed"){return new S(e,"pkce_verification_failed")}}class w extends P{status;constructor(e,r,n){super(e,"network_error",n),this.name="NetworkError",this.status=r}static fromResponse(e){return new w(`HTTP ${e.status}: ${e.statusText}`,e.status)}}class T extends P{constructor(e){super(e,"config_error"),this.name="ConfigError"}static missingField(e){return new T(`Missing required config field: ${e}`)}}class M{baseUrl;timeout;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout??3e4}async request(e,r={}){const{method:n="GET",headers:s={},body:a,params:i}=r;let c=`${this.baseUrl}${e}`;if(i){const o=new URLSearchParams(i);c+=`?${o.toString()}`}const h=new AbortController,u=setTimeout(()=>h.abort(),this.timeout);try{const o=await fetch(c,{method:n,headers:{"Content-Type":"application/json",...s},body:a?JSON.stringify(a):void 0,signal:h.signal});if(clearTimeout(u),!o.ok)throw w.fromResponse(o);return await o.json()}catch(o){throw clearTimeout(u),o instanceof w?o:o instanceof Error&&o.name==="AbortError"?new w("Request timeout",void 0,o):new w("Network request failed",void 0,o)}}async postForm(e,r,n={}){const s=`${this.baseUrl}${e}`,a=new AbortController,i=setTimeout(()=>a.abort(),this.timeout);try{const c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...n},body:new URLSearchParams(r).toString(),signal:a.signal});if(clearTimeout(i),!c.ok)throw w.fromResponse(c);return await c.json()}catch(c){throw clearTimeout(i),c instanceof w?c:new w("Network request failed",void 0,c)}}}function L(t){return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function de(){const t=new Uint8Array(32);return crypto.getRandomValues(t),L(t)}async function pe(t){const r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return L(new Uint8Array(n))}async function ye(){const t=de(),e=await pe(t);return{codeVerifier:t,codeChallenge:e,codeChallengeMethod:"S256"}}function me(){const t=new Uint8Array(16);return crypto.getRandomValues(t),L(t)}const W="tokens",I="pkce",J="state";class we{storage;constructor(e){this.storage=e}async setTokens(e){await this.storage.set(W,JSON.stringify(e))}async getTokens(){const e=await this.storage.get(W);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async clearTokens(){await this.storage.remove(W)}async isTokenExpired(){const e=await this.getTokens();if(!e)return!0;const r=e.issuedAt+e.expiresIn*1e3;return Date.now()>r-6e4}async setPKCE(e){await this.storage.set(I,e)}async consumePKCE(){const e=await this.storage.get(I);return e&&await this.storage.remove(I),e}async setState(e){await this.storage.set(J,e)}async consumeState(){const e=await this.storage.get(J);return e&&await this.storage.remove(J),e}async clearAll(){await this.storage.clear()}}const Se="https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";class ge{config;http;tokenManager;constructor(e,r){this.config={clientId:e.clientId,clientSecret:e.clientSecret,redirectUri:e.redirectUri,scopes:e.scopes,authUrl:e.authUrl??Se},this.http=new M({baseUrl:this.config.authUrl}),this.tokenManager=r}async getAuthorizationUrl(){const e=await ye(),r=me();await this.tokenManager.setPKCE(e.codeVerifier),await this.tokenManager.setState(r);const n=new URLSearchParams({response_type:"code",client_id:this.config.clientId,redirect_uri:this.config.redirectUri,state:r,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod});return this.config.scopes&&this.config.scopes.length>0&&n.append("scope",this.config.scopes.join(" ")),`${this.config.authUrl}/oauth/authorize?${n.toString()}`}async exchangeCode(e,r){const n=await this.tokenManager.consumeState();if(!n||n!==r)throw S.invalidState();const s=await this.tokenManager.consumePKCE();if(!s)throw S.pkceVerificationFailed("Missing code verifier");const a=await this.http.postForm("/oauth/token",{grant_type:"authorization_code",code:e,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret,code_verifier:s}),i=this.mapTokenResponse(a);return await this.tokenManager.setTokens(i),i}async refreshToken(){const e=await this.tokenManager.getTokens();if(!e?.refreshToken)throw S.invalidGrant("No refresh token available");const r=await this.http.postForm("/oauth/token",{grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:this.config.clientId,client_secret:this.config.clientSecret}),n=this.mapTokenResponse(r);return await this.tokenManager.setTokens(n),n}async revokeToken(){const e=await this.tokenManager.getTokens();if(e)try{await this.http.postForm("/oauth/revoke",{token:e.accessToken,client_id:this.config.clientId,client_secret:this.config.clientSecret})}finally{await this.tokenManager.clearTokens()}}mapTokenResponse(e){return{accessToken:e.access_token,refreshToken:e.refresh_token,tokenType:e.token_type,expiresIn:e.expires_in,issuedAt:Date.now(),scope:e.scope}}}const z=new TextEncoder,_=new TextDecoder;function be(...t){const e=t.reduce((s,{length:a})=>s+a,0),r=new Uint8Array(e);let n=0;for(const s of t)r.set(s,n),n+=s.length;return r}function U(t){const e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){const n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}function Ee(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function C(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:_.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=_.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return Ee(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}class d 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)}}class y extends d{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.claim=n,this.reason=s,this.payload=r}}class B extends d{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.claim=n,this.reason=s,this.payload=r}}class g extends d{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class f extends d{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class j extends d{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class ee extends d{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class te extends d{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r)}}class Ae extends d{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r)}}class Ke extends d{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",r){super(e,r)}}class Te extends d{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}const m=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),A=(t,e)=>t.name===e;function x(t){return parseInt(t.name.slice(4),10)}function ve(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Ce(t,e){if(!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function _e(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!A(t.algorithm,"HMAC"))throw m("HMAC");const n=parseInt(e.slice(2),10);if(x(t.algorithm.hash)!==n)throw m(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!A(t.algorithm,"RSASSA-PKCS1-v1_5"))throw m("RSASSA-PKCS1-v1_5");const n=parseInt(e.slice(2),10);if(x(t.algorithm.hash)!==n)throw m(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!A(t.algorithm,"RSA-PSS"))throw m("RSA-PSS");const n=parseInt(e.slice(2),10);if(x(t.algorithm.hash)!==n)throw m(`SHA-${n}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":{if(!A(t.algorithm,"Ed25519"))throw m("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!A(t.algorithm,e))throw m(e);break}case"ES256":case"ES384":case"ES512":{if(!A(t.algorithm,"ECDSA"))throw m("ECDSA");const n=ve(e);if(t.algorithm.namedCurve!==n)throw m(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Ce(t,r)}function re(t,e,...r){if(r=r.filter(Boolean),r.length>2){const n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}const Re=(t,...e)=>re("Key must be ",t,...e),ne=(t,e,...r)=>re(`Key for the ${t} algorithm must be `,e,...r),se=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},ae=t=>t?.[Symbol.toStringTag]==="KeyObject",ie=t=>se(t)||ae(t);function Pe(...t){const e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const n of e){const s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(const a of s){if(r.has(a))return!1;r.add(a)}}return!0}const ke=t=>typeof t=="object"&&t!==null;function E(t){if(!ke(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function We(t,e){if(t.startsWith("RS")||t.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function Ie(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new g('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function R(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=Ie(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}async function Je(t,e,r){if(!E(t))throw new TypeError("JWK must be an object");let n;switch(e??=t.alg,n??=t.ext,t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return C(t.k);case"RSA":if("oth"in t&&t.oth!==void 0)throw new g('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return R({...t,alg:e,ext:n});case"AKP":{if(typeof t.alg!="string"||!t.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==void 0&&e!==t.alg)throw new TypeError("JWK alg and alg option value mismatch");return R({...t,ext:n})}case"EC":case"OKP":return R({...t,alg:e,ext:n});default:throw new g('Unsupported "kty" (Key Type) Parameter value')}}function Ue(t,e,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;a=e;for(const i of n.crit){if(!a.has(i))throw new g(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new t(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new t(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}const F=t=>E(t)&&typeof t.kty=="string",xe=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),De=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,Me=t=>t.kty==="oct"&&typeof t.k=="string";let v;const q=async(t,e,r,n=!1)=>{v||=new WeakMap;let s=v.get(t);if(s?.[r])return s[r];const a=await R({...e,alg:r});return n&&Object.freeze(t),s?s[r]=a:v.set(t,{[r]:a}),a},Oe=(t,e)=>{v||=new WeakMap;let r=v.get(t);if(r?.[e])return r[e];const n=t.type==="public",s=!!n;let a;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}a=t.toCryptoKey(t.asymmetricKeyType,s,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");a=t.toCryptoKey(t.asymmetricKeyType,s,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");a=t.toCryptoKey(t.asymmetricKeyType,s,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let i;switch(e){case"RSA-OAEP":i="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":i="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":i="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":i="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:i},s,n?["encrypt"]:["decrypt"]);a=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},s,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){const c=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!c)throw new TypeError("given KeyObject instance cannot be used for this algorithm");e==="ES256"&&c==="P-256"&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),e==="ES384"&&c==="P-384"&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),e==="ES512"&&c==="P-521"&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(a=t.toCryptoKey({name:"ECDH",namedCurve:c},s,n?[]:["deriveBits"]))}if(!a)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return r?r[e]=a:v.set(t,{[e]:a}),a};async function He(t,e){if(t instanceof Uint8Array||se(t))return t;if(ae(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return Oe(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return q(t,r,e)}if(F(t))return t.k?C(t.k):q(t,t,e,!0);throw new Error("unreachable")}const K=t=>t?.[Symbol.toStringTag],O=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case r==="verify":case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n="unwrapKey":n=r;break;case r==="encrypt":n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Ne=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(F(e)){if(Me(e)&&O(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ie(e))throw new TypeError(ne(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${K(e)} instances for symmetric algorithms must be of type "secret"`)}},$e=(t,e,r)=>{if(F(e))switch(r){case"decrypt":case"sign":if(xe(e)&&O(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(De(e)&&O(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ie(e))throw new TypeError(ne(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${K(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${K(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${K(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${K(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${K(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Le(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Ne(t,e,r);break;default:$e(t,e,r)}}function Fe(t,e){const r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new g(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Ve(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Re(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return _e(e,t,r),e}async function Ge(t,e,r,n){const s=await Ve(t,e,"verify");We(t,s);const a=Fe(t,s.algorithm);try{return await crypto.subtle.verify(a,s,r,n)}catch{return!1}}async function ze(t,e,r){if(!E(t))throw new f("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new f('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new f("JWS Protected Header incorrect type");if(t.payload===void 0)throw new f("JWS Payload missing");if(typeof t.signature!="string")throw new f("JWS Signature missing or incorrect type");if(t.header!==void 0&&!E(t.header))throw new f("JWS Unprotected Header incorrect type");let n={};if(t.protected)try{const k=C(t.protected);n=JSON.parse(_.decode(k))}catch{throw new f("JWS Protected Header is invalid")}if(!Pe(n,t.header))throw new f("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...n,...t.header},a=Ue(f,new Map([["b64",!0]]),r?.crit,n,s);let i=!0;if(a.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new f('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:c}=s;if(typeof c!="string"||!c)throw new f('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(i){if(typeof t.payload!="string")throw new f("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new f("JWS Payload must be a string or an Uint8Array instance");let h=!1;typeof e=="function"&&(e=await e(n,t),h=!0),Le(c,e,"verify");const u=be(t.protected!==void 0?U(t.protected):new Uint8Array,U("."),typeof t.payload=="string"?i?U(t.payload):z.encode(t.payload):t.payload);let o;try{o=C(t.signature)}catch{throw new f("Failed to base64url decode the signature")}const l=await He(e,c);if(!await Ge(c,l,o,u))throw new Te;let b;if(i)try{b=C(t.payload)}catch{throw new f("Failed to base64url decode the payload")}else typeof t.payload=="string"?b=z.encode(t.payload):b=t.payload;const p={payload:b};return t.protected!==void 0&&(p.protectedHeader=n),t.header!==void 0&&(p.unprotectedHeader=t.header),h?{...p,key:l}:p}async function Be(t,e,r){if(t instanceof Uint8Array&&(t=_.decode(t)),typeof t!="string")throw new f("Compact JWS must be a string or Uint8Array");const{0:n,1:s,2:a,length:i}=t.split(".");if(i!==3)throw new f("Invalid Compact JWS");const c=await ze({payload:s,protected:n,signature:a},e,r),h={payload:c.payload,protectedHeader:c.protectedHeader};return typeof e=="function"?{...h,key:c.key}:h}const qe=t=>Math.floor(t.getTime()/1e3),oe=60,ce=oe*60,V=ce*24,Ye=V*7,Xe=V*365.25,Qe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Y(t){const e=Qe.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),n=e[3].toLowerCase();let s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*oe);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*ce);break;case"day":case"days":case"d":s=Math.round(r*V);break;case"week":case"weeks":case"w":s=Math.round(r*Ye);break;default:s=Math.round(r*Xe);break}return e[1]==="-"||e[4]==="ago"?-s:s}const X=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,Ze=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1;function je(t,e,r={}){let n;try{n=JSON.parse(_.decode(e))}catch{}if(!E(n))throw new j("JWT Claims Set must be a top-level JSON object");const{typ:s}=r;if(s&&(typeof t.typ!="string"||X(t.typ)!==X(s)))throw new y('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:a=[],issuer:i,subject:c,audience:h,maxTokenAge:u}=r,o=[...a];u!==void 0&&o.push("iat"),h!==void 0&&o.push("aud"),c!==void 0&&o.push("sub"),i!==void 0&&o.push("iss");for(const p of new Set(o.reverse()))if(!(p in n))throw new y(`missing required "${p}" claim`,n,p,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new y('unexpected "iss" claim value',n,"iss","check_failed");if(c&&n.sub!==c)throw new y('unexpected "sub" claim value',n,"sub","check_failed");if(h&&!Ze(n.aud,typeof h=="string"?[h]:h))throw new y('unexpected "aud" claim value',n,"aud","check_failed");let l;switch(typeof r.clockTolerance){case"string":l=Y(r.clockTolerance);break;case"number":l=r.clockTolerance;break;case"undefined":l=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:G}=r,b=qe(G||new Date);if((n.iat!==void 0||u)&&typeof n.iat!="number")throw new y('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new y('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>b+l)throw new y('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new y('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=b-l)throw new B('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){const p=b-n.iat,k=typeof u=="number"?u:Y(u);if(p-l>k)throw new B('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(p<0-l)throw new y('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function et(t,e,r){const n=await Be(t,e,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new j("JWTs MUST NOT use unencoded payload");const a={payload:je(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof e=="function"?{...a,key:n.key}:a}function tt(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new g('Unsupported "alg" value for a JSON Web Key Set')}}function rt(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(nt)}function nt(t){return E(t)}class st{#r;#i=new WeakMap;constructor(e){if(!rt(e))throw new ee("JSON Web Key Set malformed");this.#r=structuredClone(e)}jwks(){return this.#r}async getKey(e,r){const{alg:n,kid:s}={...e,...r?.header},a=tt(n),i=this.#r.keys.filter(u=>{let o=a===u.kty;if(o&&typeof s=="string"&&(o=s===u.kid),o&&(typeof u.alg=="string"||a==="AKP")&&(o=n===u.alg),o&&typeof u.use=="string"&&(o=u.use==="sig"),o&&Array.isArray(u.key_ops)&&(o=u.key_ops.includes("verify")),o)switch(n){case"ES256":o=u.crv==="P-256";break;case"ES384":o=u.crv==="P-384";break;case"ES512":o=u.crv==="P-521";break;case"Ed25519":case"EdDSA":o=u.crv==="Ed25519";break}return o}),{0:c,length:h}=i;if(h===0)throw new te;if(h!==1){const u=new Ae,o=this.#i;throw u[Symbol.asyncIterator]=async function*(){for(const l of i)try{yield await Q(o,l,n)}catch{}},u}return Q(this.#i,c,n)}}async function Q(t,e,r){const n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){const s=await Je({...e,ext:!0},r);if(s instanceof Uint8Array||s.type!=="public")throw new ee("JSON Web Key Set members must be public keys");n[r]=s}return n[r]}function Z(t){const e=new st(t),r=async(n,s)=>e.getKey(n,s);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(e.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}function at(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let H;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(H="jose/v6.1.3");const it=Symbol();async function ot(t,e,r,n=fetch){const s=await n(t,{method:"GET",signal:r,redirect:"manual",headers:e}).catch(a=>{throw a.name==="TimeoutError"?new Ke:a});if(s.status!==200)throw new d("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await s.json()}catch{throw new d("Failed to parse the JSON Web Key Set HTTP response as JSON")}}const D=Symbol();function ct(t,e){return!(typeof t!="object"||t===null||!("uat"in t)||typeof t.uat!="number"||Date.now()-t.uat>=e||!("jwks"in t)||!E(t.jwks)||!Array.isArray(t.jwks.keys)||!Array.prototype.every.call(t.jwks.keys,E))}class ut{#r;#i;#c;#o;#n;#e;#t;#u;#s;#a;constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#r=new URL(e.href),this.#i=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#c=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#o=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#t=new Headers(r?.headers),H&&!this.#t.has("User-Agent")&&this.#t.set("User-Agent",H),this.#t.has("accept")||(this.#t.set("accept","application/json"),this.#t.append("accept","application/jwk-set+json")),this.#u=r?.[it],r?.[D]!==void 0&&(this.#a=r?.[D],ct(r?.[D],this.#o)&&(this.#n=this.#a.uat,this.#s=Z(this.#a.jwks)))}pendingFetch(){return!!this.#e}coolingDown(){return typeof this.#n=="number"?Date.now()<this.#n+this.#c:!1}fresh(){return typeof this.#n=="number"?Date.now()<this.#n+this.#o:!1}jwks(){return this.#s?.jwks()}async getKey(e,r){(!this.#s||!this.fresh())&&await this.reload();try{return await this.#s(e,r)}catch(n){if(n instanceof te&&this.coolingDown()===!1)return await this.reload(),this.#s(e,r);throw n}}async reload(){this.#e&&at()&&(this.#e=void 0),this.#e||=ot(this.#r.href,this.#t,AbortSignal.timeout(this.#i),this.#u).then(e=>{this.#s=Z(e),this.#a&&(this.#a.uat=Date.now(),this.#a.jwks=e),this.#n=Date.now(),this.#e=void 0}).catch(e=>{throw this.#e=void 0,e}),await this.#e}}function ht(t,e){const r=new ut(t,e),n=async(s,a)=>r.getKey(s,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>r.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>r.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}class ft{jwksUrl;JWKS;constructor(e){this.jwksUrl=e,this.JWKS=ht(new URL(this.jwksUrl))}async verify(e){return et(e,this.JWKS)}}class ue{store=new Map;async get(e){return this.store.get(e)??null}async set(e,r){this.store.set(e,r)}async remove(e){this.store.delete(e)}async clear(){this.store.clear()}}class N{prefix;constructor(e="genation"){this.prefix=e}getKey(e){return`${this.prefix}:${e}`}async get(e){return typeof window>"u"?null:localStorage.getItem(this.getKey(e))}async set(e,r){typeof window>"u"||localStorage.setItem(this.getKey(e),r)}async remove(e){typeof window>"u"||localStorage.removeItem(this.getKey(e))}async clear(){if(typeof window>"u")return;Object.keys(localStorage).filter(r=>r.startsWith(`${this.prefix}:`)).forEach(r=>localStorage.removeItem(r))}}class he{prefix;constructor(e="genation"){this.prefix=e}getKey(e){return`${this.prefix}:${e}`}async get(e){return typeof window>"u"?null:sessionStorage.getItem(this.getKey(e))}async set(e,r){typeof window>"u"||sessionStorage.setItem(this.getKey(e),r)}async remove(e){typeof window>"u"||sessionStorage.removeItem(this.getKey(e))}async clear(){if(typeof window>"u")return;Object.keys(sessionStorage).filter(r=>r.startsWith(`${this.prefix}:`)).forEach(r=>sessionStorage.removeItem(r))}}function fe(t="localStorage"){switch(t){case"memory":return new ue;case"localStorage":return new N;case"sessionStorage":return new he;default:return new N}}function $(t){return Array.isArray(t)?t.map($):typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t).map(([e,r])=>[e.replace(/_([a-z])/g,(n,s)=>s.toUpperCase()),$(r)])):t}class le{oauth;tokenManager;tokenVerifier;http;httpServer;listeners=new Set;initialized=!1;constructor(e){this.validateConfig(e);const r=typeof e.storage=="object"?e.storage:fe(e.storage),n=e.authUrl??"https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";this.tokenManager=new we(r),this.oauth=new ge(e,this.tokenManager),this.tokenVerifier=new ft(`${n}/.well-known/jwks.json`),this.http=new M({baseUrl:n}),this.httpServer=new M({baseUrl:"https://ff-api.genation.ai/api/v2/client"})}validateConfig(e){if(!e.clientId)throw T.missingField("clientId");if(!e.clientSecret)throw T.missingField("clientSecret");if(!e.redirectUri)throw T.missingField("redirectUri")}async emitAuthStateChange(e){const r=await this.getSession();this.listeners.forEach(n=>{try{n(e,r)}catch(s){console.error("Error in auth state change callback:",s)}})}onAuthStateChange(e){return this.listeners.add(e),this.initialized?setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0):(this.initialized=!0,setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0)),{subscription:{unsubscribe:()=>{this.listeners.delete(e)}}}}async signIn(){return this.oauth.getAuthorizationUrl()}async handleCallback(e){const r=new URL(e),n=r.searchParams.get("code"),s=r.searchParams.get("state");if(!n||!s)throw new Error("Missing code or state");const a=await this.oauth.exchangeCode(n,s);return await this.emitAuthStateChange("SIGNED_IN"),a}async signOut(){await this.tokenManager.clearTokens(),await this.emitAuthStateChange("SIGNED_OUT")}async getSession(){if(await this.tokenManager.isTokenExpired())try{await this.oauth.refreshToken()}catch{return null}const r=await this.tokenManager.getTokens();if(!r)return null;const n=await this.fetchUser(r.accessToken);return{accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:r.expiresIn,expiresAt:r.issuedAt+r.expiresIn*1e3,user:n}}async verifyToken(e){const{payload:r}=await this.tokenVerifier.verify(e);return r}async getLicenses(e={}){const r=await this.getSession();if(!r)return null;const n=r.accessToken,{expiresAfter:s=new Date}=e,a=await this.httpServer.request("/licenses",{headers:{Authorization:`Bearer ${n}`},params:{expiresAfter:s.toISOString()}});return a.ok?$(a.data):(console.error("GenationClient: Error fetching licenses:",a.error),null)}async fetchUser(e){try{const r=await this.http.request("/oauth/userinfo",{headers:{Authorization:`Bearer ${e}`}});return{sub:r.sub,name:r.name,picture:r.picture,email:r.email,email_verified:r.email_verified,phone_number:r.phone_number,phone_number_verified:r.phone_number_verified}}catch(r){return console.error("GenationClient: Error fetching user:",r),null}}}function lt(t){return new le(t)}exports.AuthError=S;exports.ConfigError=T;exports.GenationClient=le;exports.GenationError=P;exports.LocalStorage=N;exports.MemoryStorage=ue;exports.NetworkError=w;exports.SessionStorage=he;exports.createClient=lt;exports.createStorage=fe;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class k extends Error{code;cause;constructor(e,r,n){super(e),this.name="GenationError",this.code=r,this.cause=n}}class S extends k{constructor(e,r,n){super(e,r,n),this.name="AuthError"}static invalidGrant(e="Invalid authorization code or refresh token"){return new S(e,"invalid_grant")}static accessDenied(e="User denied access"){return new S(e,"access_denied")}static expiredToken(e="Token has expired"){return new S(e,"expired_token")}static invalidState(e="State mismatch, possible CSRF attack"){return new S(e,"invalid_state")}static pkceVerificationFailed(e="PKCE verification failed"){return new S(e,"pkce_verification_failed")}}class w extends k{status;constructor(e,r,n){super(e,"network_error",n),this.name="NetworkError",this.status=r}static fromResponse(e){return new w(`HTTP ${e.status}: ${e.statusText}`,e.status)}}class K extends k{constructor(e){super(e,"config_error"),this.name="ConfigError"}static missingField(e){return new K(`Missing required config field: ${e}`)}}class M{baseUrl;timeout;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout??3e4}async request(e,r={}){const{method:n="GET",headers:s={},body:a,params:i}=r;let c=`${this.baseUrl}${e}`;if(i){const o=new URLSearchParams(i);c+=`?${o.toString()}`}const h=new AbortController,u=setTimeout(()=>h.abort(),this.timeout);try{const o=await fetch(c,{method:n,headers:{"Content-Type":"application/json",...s},body:a?JSON.stringify(a):void 0,signal:h.signal});if(clearTimeout(u),!o.ok)throw w.fromResponse(o);return await o.json()}catch(o){throw clearTimeout(u),o instanceof w?o:o instanceof Error&&o.name==="AbortError"?new w("Request timeout",void 0,o):new w("Network request failed",void 0,o)}}async postForm(e,r,n={}){const s=`${this.baseUrl}${e}`,a=new AbortController,i=setTimeout(()=>a.abort(),this.timeout);try{const c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...n},body:new URLSearchParams(r).toString(),signal:a.signal});if(clearTimeout(i),!c.ok)throw w.fromResponse(c);return await c.json()}catch(c){throw clearTimeout(i),c instanceof w?c:new w("Network request failed",void 0,c)}}}function F(t){return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function me(){const t=new Uint8Array(32);return crypto.getRandomValues(t),F(t)}async function we(t){const r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return F(new Uint8Array(n))}async function Se(){const t=me(),e=await we(t);return{codeVerifier:t,codeChallenge:e,codeChallengeMethod:"S256"}}function ge(){const t=new Uint8Array(16);return crypto.getRandomValues(t),F(t)}const I="tokens",J="pkce",O="state";class be{storage;constructor(e){this.storage=e}async setTokens(e){await this.storage.set(I,JSON.stringify(e))}async getTokens(){const e=await this.storage.get(I);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async clearTokens(){await this.storage.remove(I)}async isTokenExpired(){const e=await this.getTokens();if(!e)return!0;const r=e.issuedAt+e.expiresIn*1e3;return Date.now()>r-6e4}async setPKCE(e){await this.storage.set(J,e)}async consumePKCE(){const e=await this.storage.get(J);return e&&await this.storage.remove(J),e}async setState(e){await this.storage.set(O,e)}async consumeState(){const e=await this.storage.get(O);return e&&await this.storage.remove(O),e}async clearAll(){await this.storage.clear()}}const G="https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";class Ee{config;http;tokenManager;constructor(e,r){this.config={clientId:e.clientId,clientSecret:e.clientSecret,redirectUri:e.redirectUri,scopes:e.scopes,authUrl:e.authUrl??G},this.http=new M({baseUrl:this.config.authUrl}),this.tokenManager=r}async getAuthorizationUrl(){const e=await Se(),r=ge();await this.tokenManager.setPKCE(e.codeVerifier),await this.tokenManager.setState(r);const n=new URLSearchParams({response_type:"code",client_id:this.config.clientId,redirect_uri:this.config.redirectUri,state:r,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod});return this.config.scopes&&this.config.scopes.length>0&&n.append("scope",this.config.scopes.join(" ")),`${this.config.authUrl}/oauth/authorize?${n.toString()}`}async exchangeCode(e,r){const n=await this.tokenManager.consumeState();if(!n||n!==r)throw S.invalidState();const s=await this.tokenManager.consumePKCE();if(!s)throw S.pkceVerificationFailed("Missing code verifier");const a=await this.http.postForm("/oauth/token",{grant_type:"authorization_code",code:e,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret,code_verifier:s}),i=this.mapTokenResponse(a);return await this.tokenManager.setTokens(i),i}async refreshToken(){const e=await this.tokenManager.getTokens();if(!e?.refreshToken)throw S.invalidGrant("No refresh token available");const r=await this.http.postForm("/oauth/token",{grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:this.config.clientId,client_secret:this.config.clientSecret}),n=this.mapTokenResponse(r);return await this.tokenManager.setTokens(n),n}async revokeToken(){const e=await this.tokenManager.getTokens();if(e)try{await this.http.postForm("/oauth/revoke",{token:e.accessToken,client_id:this.config.clientId,client_secret:this.config.clientSecret})}finally{await this.tokenManager.clearTokens()}}mapTokenResponse(e){return{accessToken:e.access_token,refreshToken:e.refresh_token,tokenType:e.token_type,expiresIn:e.expires_in,issuedAt:Date.now(),scope:e.scope}}}const z=new TextEncoder,_=new TextDecoder;function Ae(...t){const e=t.reduce((s,{length:a})=>s+a,0),r=new Uint8Array(e);let n=0;for(const s of t)r.set(s,n),n+=s.length;return r}function x(t){const e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){const n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}function Te(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function C(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:_.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=_.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return Te(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}class d 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)}}class y extends d{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.claim=n,this.reason=s,this.payload=r}}class q extends d{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.claim=n,this.reason=s,this.payload=r}}class Ke extends d{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class g extends d{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class f extends d{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class ee extends d{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class te extends d{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class re extends d{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r)}}class ve extends d{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r)}}class Ce extends d{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",r){super(e,r)}}class _e extends d{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}const m=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),A=(t,e)=>t.name===e;function D(t){return parseInt(t.name.slice(4),10)}function Re(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Pe(t,e){if(!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function We(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!A(t.algorithm,"HMAC"))throw m("HMAC");const n=parseInt(e.slice(2),10);if(D(t.algorithm.hash)!==n)throw m(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!A(t.algorithm,"RSASSA-PKCS1-v1_5"))throw m("RSASSA-PKCS1-v1_5");const n=parseInt(e.slice(2),10);if(D(t.algorithm.hash)!==n)throw m(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!A(t.algorithm,"RSA-PSS"))throw m("RSA-PSS");const n=parseInt(e.slice(2),10);if(D(t.algorithm.hash)!==n)throw m(`SHA-${n}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":{if(!A(t.algorithm,"Ed25519"))throw m("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!A(t.algorithm,e))throw m(e);break}case"ES256":case"ES384":case"ES512":{if(!A(t.algorithm,"ECDSA"))throw m("ECDSA");const n=Re(e);if(t.algorithm.namedCurve!==n)throw m(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Pe(t,r)}function ne(t,e,...r){if(r=r.filter(Boolean),r.length>2){const n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}const ke=(t,...e)=>ne("Key must be ",t,...e),se=(t,e,...r)=>ne(`Key for the ${t} algorithm must be `,e,...r),ae=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},ie=t=>t?.[Symbol.toStringTag]==="KeyObject",oe=t=>ae(t)||ie(t);function Ie(...t){const e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const n of e){const s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(const a of s){if(r.has(a))return!1;r.add(a)}}return!0}const Je=t=>typeof t=="object"&&t!==null;function b(t){if(!Je(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Oe(t,e){if(t.startsWith("RS")||t.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function xe(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new g('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function W(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=xe(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}async function De(t,e,r){if(!b(t))throw new TypeError("JWK must be an object");let n;switch(e??=t.alg,n??=t.ext,t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return C(t.k);case"RSA":if("oth"in t&&t.oth!==void 0)throw new g('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return W({...t,alg:e,ext:n});case"AKP":{if(typeof t.alg!="string"||!t.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==void 0&&e!==t.alg)throw new TypeError("JWK alg and alg option value mismatch");return W({...t,ext:n})}case"EC":case"OKP":return W({...t,alg:e,ext:n});default:throw new g('Unsupported "kty" (Key Type) Parameter value')}}function Ue(t,e,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...e.entries()]):a=e;for(const i of n.crit){if(!a.has(i))throw new g(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new t(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new t(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}function Me(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);if(e)return new Set(e)}const V=t=>b(t)&&typeof t.kty=="string",Ne=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),He=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,Le=t=>t.kty==="oct"&&typeof t.k=="string";let v;const Y=async(t,e,r,n=!1)=>{v||=new WeakMap;let s=v.get(t);if(s?.[r])return s[r];const a=await W({...e,alg:r});return n&&Object.freeze(t),s?s[r]=a:v.set(t,{[r]:a}),a},$e=(t,e)=>{v||=new WeakMap;let r=v.get(t);if(r?.[e])return r[e];const n=t.type==="public",s=!!n;let a;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}a=t.toCryptoKey(t.asymmetricKeyType,s,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");a=t.toCryptoKey(t.asymmetricKeyType,s,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");a=t.toCryptoKey(t.asymmetricKeyType,s,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let i;switch(e){case"RSA-OAEP":i="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":i="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":i="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":i="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:i},s,n?["encrypt"]:["decrypt"]);a=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},s,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){const c=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!c)throw new TypeError("given KeyObject instance cannot be used for this algorithm");e==="ES256"&&c==="P-256"&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),e==="ES384"&&c==="P-384"&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),e==="ES512"&&c==="P-521"&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(a=t.toCryptoKey({name:"ECDH",namedCurve:c},s,n?[]:["deriveBits"]))}if(!a)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return r?r[e]=a:v.set(t,{[e]:a}),a};async function Fe(t,e){if(t instanceof Uint8Array||ae(t))return t;if(ie(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return $e(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return Y(t,r,e)}if(V(t))return t.k?C(t.k):Y(t,t,e,!0);throw new Error("unreachable")}const T=t=>t?.[Symbol.toStringTag],N=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case r==="verify":case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n="unwrapKey":n=r;break;case r==="encrypt":n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Ge=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(V(e)){if(Le(e)&&N(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!oe(e))throw new TypeError(se(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${T(e)} instances for symmetric algorithms must be of type "secret"`)}},Ve=(t,e,r)=>{if(V(e))switch(r){case"decrypt":case"sign":if(Ne(e)&&N(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(He(e)&&N(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!oe(e))throw new TypeError(se(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${T(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${T(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${T(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${T(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${T(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Be(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Ge(t,e,r);break;default:Ve(t,e,r)}}function ze(t,e){const r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new g(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function qe(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(ke(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return We(e,t,r),e}async function Ye(t,e,r,n){const s=await qe(t,e,"verify");Oe(t,s);const a=ze(t,s.algorithm);try{return await crypto.subtle.verify(a,s,r,n)}catch{return!1}}async function Xe(t,e,r){if(!b(t))throw new f("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new f('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new f("JWS Protected Header incorrect type");if(t.payload===void 0)throw new f("JWS Payload missing");if(typeof t.signature!="string")throw new f("JWS Signature missing or incorrect type");if(t.header!==void 0&&!b(t.header))throw new f("JWS Unprotected Header incorrect type");let n={};if(t.protected)try{const ye=C(t.protected);n=JSON.parse(_.decode(ye))}catch{throw new f("JWS Protected Header is invalid")}if(!Ie(n,t.header))throw new f("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...n,...t.header},a=Ue(f,new Map([["b64",!0]]),r?.crit,n,s);let i=!0;if(a.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new f('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:c}=s;if(typeof c!="string"||!c)throw new f('JWS "alg" (Algorithm) Header Parameter missing or invalid');const h=r&&Me("algorithms",r.algorithms);if(h&&!h.has(c))throw new Ke('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof t.payload!="string")throw new f("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new f("JWS Payload must be a string or an Uint8Array instance");let u=!1;typeof e=="function"&&(e=await e(n,t),u=!0),Be(c,e,"verify");const o=Ae(t.protected!==void 0?x(t.protected):new Uint8Array,x("."),typeof t.payload=="string"?i?x(t.payload):z.encode(t.payload):t.payload);let l;try{l=C(t.signature)}catch{throw new f("Failed to base64url decode the signature")}const R=await Fe(e,c);if(!await Ye(c,R,l,o))throw new _e;let p;if(i)try{p=C(t.payload)}catch{throw new f("Failed to base64url decode the payload")}else typeof t.payload=="string"?p=z.encode(t.payload):p=t.payload;const E={payload:p};return t.protected!==void 0&&(E.protectedHeader=n),t.header!==void 0&&(E.unprotectedHeader=t.header),u?{...E,key:R}:E}async function Qe(t,e,r){if(t instanceof Uint8Array&&(t=_.decode(t)),typeof t!="string")throw new f("Compact JWS must be a string or Uint8Array");const{0:n,1:s,2:a,length:i}=t.split(".");if(i!==3)throw new f("Invalid Compact JWS");const c=await Xe({payload:s,protected:n,signature:a},e,r),h={payload:c.payload,protectedHeader:c.protectedHeader};return typeof e=="function"?{...h,key:c.key}:h}const Ze=t=>Math.floor(t.getTime()/1e3),ce=60,ue=ce*60,B=ue*24,je=B*7,et=B*365.25,tt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function X(t){const e=tt.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),n=e[3].toLowerCase();let s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*ce);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*ue);break;case"day":case"days":case"d":s=Math.round(r*B);break;case"week":case"weeks":case"w":s=Math.round(r*je);break;default:s=Math.round(r*et);break}return e[1]==="-"||e[4]==="ago"?-s:s}const Q=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,rt=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1;function nt(t,e,r={}){let n;try{n=JSON.parse(_.decode(e))}catch{}if(!b(n))throw new ee("JWT Claims Set must be a top-level JSON object");const{typ:s}=r;if(s&&(typeof t.typ!="string"||Q(t.typ)!==Q(s)))throw new y('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:a=[],issuer:i,subject:c,audience:h,maxTokenAge:u}=r,o=[...a];u!==void 0&&o.push("iat"),h!==void 0&&o.push("aud"),c!==void 0&&o.push("sub"),i!==void 0&&o.push("iss");for(const p of new Set(o.reverse()))if(!(p in n))throw new y(`missing required "${p}" claim`,n,p,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new y('unexpected "iss" claim value',n,"iss","check_failed");if(c&&n.sub!==c)throw new y('unexpected "sub" claim value',n,"sub","check_failed");if(h&&!rt(n.aud,typeof h=="string"?[h]:h))throw new y('unexpected "aud" claim value',n,"aud","check_failed");let l;switch(typeof r.clockTolerance){case"string":l=X(r.clockTolerance);break;case"number":l=r.clockTolerance;break;case"undefined":l=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:R}=r,P=Ze(R||new Date);if((n.iat!==void 0||u)&&typeof n.iat!="number")throw new y('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new y('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>P+l)throw new y('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new y('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=P-l)throw new q('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){const p=P-n.iat,E=typeof u=="number"?u:X(u);if(p-l>E)throw new q('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(p<0-l)throw new y('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function st(t,e,r){const n=await Qe(t,e,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new ee("JWTs MUST NOT use unencoded payload");const a={payload:nt(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof e=="function"?{...a,key:n.key}:a}function at(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new g('Unsupported "alg" value for a JSON Web Key Set')}}function it(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(ot)}function ot(t){return b(t)}class ct{#r;#i=new WeakMap;constructor(e){if(!it(e))throw new te("JSON Web Key Set malformed");this.#r=structuredClone(e)}jwks(){return this.#r}async getKey(e,r){const{alg:n,kid:s}={...e,...r?.header},a=at(n),i=this.#r.keys.filter(u=>{let o=a===u.kty;if(o&&typeof s=="string"&&(o=s===u.kid),o&&(typeof u.alg=="string"||a==="AKP")&&(o=n===u.alg),o&&typeof u.use=="string"&&(o=u.use==="sig"),o&&Array.isArray(u.key_ops)&&(o=u.key_ops.includes("verify")),o)switch(n){case"ES256":o=u.crv==="P-256";break;case"ES384":o=u.crv==="P-384";break;case"ES512":o=u.crv==="P-521";break;case"Ed25519":case"EdDSA":o=u.crv==="Ed25519";break}return o}),{0:c,length:h}=i;if(h===0)throw new re;if(h!==1){const u=new ve,o=this.#i;throw u[Symbol.asyncIterator]=async function*(){for(const l of i)try{yield await Z(o,l,n)}catch{}},u}return Z(this.#i,c,n)}}async function Z(t,e,r){const n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){const s=await De({...e,ext:!0},r);if(s instanceof Uint8Array||s.type!=="public")throw new te("JSON Web Key Set members must be public keys");n[r]=s}return n[r]}function j(t){const e=new ct(t),r=async(n,s)=>e.getKey(n,s);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(e.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}function ut(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let H;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(H="jose/v6.1.3");const ht=Symbol();async function ft(t,e,r,n=fetch){const s=await n(t,{method:"GET",signal:r,redirect:"manual",headers:e}).catch(a=>{throw a.name==="TimeoutError"?new Ce:a});if(s.status!==200)throw new d("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await s.json()}catch{throw new d("Failed to parse the JSON Web Key Set HTTP response as JSON")}}const U=Symbol();function dt(t,e){return!(typeof t!="object"||t===null||!("uat"in t)||typeof t.uat!="number"||Date.now()-t.uat>=e||!("jwks"in t)||!b(t.jwks)||!Array.isArray(t.jwks.keys)||!Array.prototype.every.call(t.jwks.keys,b))}class lt{#r;#i;#c;#o;#n;#e;#t;#u;#s;#a;constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#r=new URL(e.href),this.#i=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#c=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#o=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#t=new Headers(r?.headers),H&&!this.#t.has("User-Agent")&&this.#t.set("User-Agent",H),this.#t.has("accept")||(this.#t.set("accept","application/json"),this.#t.append("accept","application/jwk-set+json")),this.#u=r?.[ht],r?.[U]!==void 0&&(this.#a=r?.[U],dt(r?.[U],this.#o)&&(this.#n=this.#a.uat,this.#s=j(this.#a.jwks)))}pendingFetch(){return!!this.#e}coolingDown(){return typeof this.#n=="number"?Date.now()<this.#n+this.#c:!1}fresh(){return typeof this.#n=="number"?Date.now()<this.#n+this.#o:!1}jwks(){return this.#s?.jwks()}async getKey(e,r){(!this.#s||!this.fresh())&&await this.reload();try{return await this.#s(e,r)}catch(n){if(n instanceof re&&this.coolingDown()===!1)return await this.reload(),this.#s(e,r);throw n}}async reload(){this.#e&&ut()&&(this.#e=void 0),this.#e||=ft(this.#r.href,this.#t,AbortSignal.timeout(this.#i),this.#u).then(e=>{this.#s=j(e),this.#a&&(this.#a.uat=Date.now(),this.#a.jwks=e),this.#n=Date.now(),this.#e=void 0}).catch(e=>{throw this.#e=void 0,e}),await this.#e}}function pt(t,e){const r=new lt(t,e),n=async(s,a)=>r.getKey(s,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>r.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>r.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}const yt=pt(new URL(`${G}/.well-known/jwks.json`));async function he(t){try{const{payload:e}=await st(t,yt,{issuer:G,audience:"authenticated"});return e}catch(e){return console.error("Token verification failed:",e),null}}class fe{store=new Map;async get(e){return this.store.get(e)??null}async set(e,r){this.store.set(e,r)}async remove(e){this.store.delete(e)}async clear(){this.store.clear()}}class L{prefix;constructor(e="genation"){this.prefix=e}getKey(e){return`${this.prefix}:${e}`}async get(e){return typeof window>"u"?null:localStorage.getItem(this.getKey(e))}async set(e,r){typeof window>"u"||localStorage.setItem(this.getKey(e),r)}async remove(e){typeof window>"u"||localStorage.removeItem(this.getKey(e))}async clear(){if(typeof window>"u")return;Object.keys(localStorage).filter(r=>r.startsWith(`${this.prefix}:`)).forEach(r=>localStorage.removeItem(r))}}class de{prefix;constructor(e="genation"){this.prefix=e}getKey(e){return`${this.prefix}:${e}`}async get(e){return typeof window>"u"?null:sessionStorage.getItem(this.getKey(e))}async set(e,r){typeof window>"u"||sessionStorage.setItem(this.getKey(e),r)}async remove(e){typeof window>"u"||sessionStorage.removeItem(this.getKey(e))}async clear(){if(typeof window>"u")return;Object.keys(sessionStorage).filter(r=>r.startsWith(`${this.prefix}:`)).forEach(r=>sessionStorage.removeItem(r))}}function le(t="localStorage"){switch(t){case"memory":return new fe;case"localStorage":return new L;case"sessionStorage":return new de;default:return new L}}function $(t){return Array.isArray(t)?t.map($):typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t).map(([e,r])=>[e.replace(/_([a-z])/g,(n,s)=>s.toUpperCase()),$(r)])):t}class pe{oauth;tokenManager;http;httpServer;listeners=new Set;initialized=!1;constructor(e){this.validateConfig(e);const r=typeof e.storage=="object"?e.storage:le(e.storage),n=e.authUrl??"https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";this.tokenManager=new be(r),this.oauth=new Ee(e,this.tokenManager),this.http=new M({baseUrl:n}),this.httpServer=new M({baseUrl:"https://ff-api.genation.ai/api/v2/client"})}validateConfig(e){if(!e.clientId)throw K.missingField("clientId");if(!e.clientSecret)throw K.missingField("clientSecret");if(!e.redirectUri)throw K.missingField("redirectUri")}async emitAuthStateChange(e){const r=await this.getSession();this.listeners.forEach(n=>{try{n(e,r)}catch(s){console.error("Error in auth state change callback:",s)}})}onAuthStateChange(e){return this.listeners.add(e),this.initialized?setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0):(this.initialized=!0,setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0)),{subscription:{unsubscribe:()=>{this.listeners.delete(e)}}}}async signIn(){return this.oauth.getAuthorizationUrl()}async handleCallback(e){const r=new URL(e),n=r.searchParams.get("code"),s=r.searchParams.get("state");if(!n||!s)throw new Error("Missing code or state");const a=await this.oauth.exchangeCode(n,s);return await this.emitAuthStateChange("SIGNED_IN"),a}async signOut(){await this.tokenManager.clearTokens(),await this.emitAuthStateChange("SIGNED_OUT")}async getSession(){if(await this.tokenManager.isTokenExpired())try{await this.oauth.refreshToken()}catch{return null}const r=await this.tokenManager.getTokens();if(!r)return null;const n=await this.fetchUser(r.accessToken);return{accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:r.expiresIn,expiresAt:r.issuedAt+r.expiresIn*1e3,user:n}}async verifyToken(e){return await he(e)}async getLicenses(e={}){const r=await this.getSession();if(!r)return null;const n=r.accessToken,{expiresAfter:s=new Date}=e,a=await this.httpServer.request("/licenses",{headers:{Authorization:`Bearer ${n}`},params:{expiresAfter:s.toISOString()}});return a.ok?$(a.data):(console.error("GenationClient: Error fetching licenses:",a.error),null)}async fetchUser(e){try{const r=await this.http.request("/oauth/userinfo",{headers:{Authorization:`Bearer ${e}`}});return{sub:r.sub,name:r.name,picture:r.picture,email:r.email,email_verified:r.email_verified,phone_number:r.phone_number,phone_number_verified:r.phone_number_verified}}catch(r){return console.error("GenationClient: Error fetching user:",r),null}}}function mt(t){return new pe(t)}exports.AuthError=S;exports.ConfigError=K;exports.GenationClient=pe;exports.GenationError=k;exports.LocalStorage=L;exports.MemoryStorage=fe;exports.NetworkError=w;exports.SessionStorage=de;exports.createClient=mt;exports.createStorage=le;exports.verifyToken=he;
2
2
  //# sourceMappingURL=genation.cjs.js.map