@genation/sdk 0.2.10 → 0.2.11
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 +11 -0
- package/dist/genation.cjs.js +1 -1
- package/dist/genation.cjs.js.map +1 -1
- package/dist/genation.es.js +511 -520
- package/dist/genation.es.js.map +1 -1
- package/dist/genation.umd.js +1 -1
- package/dist/genation.umd.js.map +1 -1
- package/dist/index.d.ts +12 -1
- package/package.json +1 -1
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
|
package/dist/genation.cjs.js
CHANGED
|
@@ -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 P extends Error{code;cause;constructor(t,r,n){super(t),this.name="GenationError",this.code=r,this.cause=n}}class S extends P{constructor(t,r,n){super(t,r,n),this.name="AuthError"}static invalidGrant(t="Invalid authorization code or refresh token"){return new S(t,"invalid_grant")}static accessDenied(t="User denied access"){return new S(t,"access_denied")}static expiredToken(t="Token has expired"){return new S(t,"expired_token")}static invalidState(t="State mismatch, possible CSRF attack"){return new S(t,"invalid_state")}static pkceVerificationFailed(t="PKCE verification failed"){return new S(t,"pkce_verification_failed")}}class w extends P{status;constructor(t,r,n){super(t,"network_error",n),this.name="NetworkError",this.status=r}static fromResponse(t){return new w(`HTTP ${t.status}: ${t.statusText}`,t.status)}}class K extends P{constructor(t){super(t,"config_error"),this.name="ConfigError"}static missingField(t){return new K(`Missing required config field: ${t}`)}}class M{baseUrl;timeout;constructor(t){this.baseUrl=t.baseUrl.replace(/\/$/,""),this.timeout=t.timeout??3e4}async request(t,r={}){const{method:n="GET",headers:s={},body:a,params:i}=r;let c=`${this.baseUrl}${t}`;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(t,r,n={}){const s=`${this.baseUrl}${t}`,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(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function me(){const e=new Uint8Array(32);return crypto.getRandomValues(e),L(e)}async function we(e){const r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return L(new Uint8Array(n))}async function Se(){const e=me(),t=await we(e);return{codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}function ge(){const e=new Uint8Array(16);return crypto.getRandomValues(e),L(e)}const W="tokens",I="pkce",J="state";class be{storage;constructor(t){this.storage=t}async setTokens(t){await this.storage.set(W,JSON.stringify(t))}async getTokens(){const t=await this.storage.get(W);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async clearTokens(){await this.storage.remove(W)}async isTokenExpired(){const t=await this.getTokens();if(!t)return!0;const r=t.issuedAt+t.expiresIn*1e3;return Date.now()>r-6e4}async setPKCE(t){await this.storage.set(I,t)}async consumePKCE(){const t=await this.storage.get(I);return t&&await this.storage.remove(I),t}async setState(t){await this.storage.set(J,t)}async consumeState(){const t=await this.storage.get(J);return t&&await this.storage.remove(J),t}async clearAll(){await this.storage.clear()}}const ee="https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";class Ee{config;http;tokenManager;constructor(t,r){this.config={clientId:t.clientId,clientSecret:t.clientSecret,redirectUri:t.redirectUri,scopes:t.scopes,authUrl:t.authUrl??ee},this.http=new M({baseUrl:this.config.authUrl}),this.tokenManager=r}async getAuthorizationUrl(){const t=await Se(),r=ge();await this.tokenManager.setPKCE(t.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:t.codeChallenge,code_challenge_method:t.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(t,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:t,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 t=await this.tokenManager.getTokens();if(!t?.refreshToken)throw S.invalidGrant("No refresh token available");const r=await this.http.postForm("/oauth/token",{grant_type:"refresh_token",refresh_token:t.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 t=await this.tokenManager.getTokens();if(t)try{await this.http.postForm("/oauth/revoke",{token:t.accessToken,client_id:this.config.clientId,client_secret:this.config.clientSecret})}finally{await this.tokenManager.clearTokens()}}mapTokenResponse(t){return{accessToken:t.access_token,refreshToken:t.refresh_token,tokenType:t.token_type,expiresIn:t.expires_in,issuedAt:Date.now(),scope:t.scope}}}const z=new TextEncoder,_=new TextDecoder;function Ae(...e){const t=e.reduce((s,{length:a})=>s+a,0),r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}function x(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function Te(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function C(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:_.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=_.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Te(t)}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(t,r){super(t,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(t,r,n="unspecified",s="unspecified"){super(t,{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(t,r,n="unspecified",s="unspecified"){super(t,{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 te extends d{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class re extends d{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class ne extends d{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}}class Ke extends d{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}}class ve extends d{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(t="request timed out",r){super(t,r)}}class Ce extends d{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}}const m=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),A=(e,t)=>e.name===t;function U(e){return parseInt(e.name.slice(4),10)}function _e(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Re(e,t){if(!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Pe(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!A(e.algorithm,"HMAC"))throw m("HMAC");const n=parseInt(t.slice(2),10);if(U(e.algorithm.hash)!==n)throw m(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!A(e.algorithm,"RSASSA-PKCS1-v1_5"))throw m("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(U(e.algorithm.hash)!==n)throw m(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!A(e.algorithm,"RSA-PSS"))throw m("RSA-PSS");const n=parseInt(t.slice(2),10);if(U(e.algorithm.hash)!==n)throw m(`SHA-${n}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":{if(!A(e.algorithm,"Ed25519"))throw m("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!A(e.algorithm,t))throw m(t);break}case"ES256":case"ES384":case"ES512":{if(!A(e.algorithm,"ECDSA"))throw m("ECDSA");const n=_e(t);if(e.algorithm.namedCurve!==n)throw m(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Re(e,r)}function se(e,t,...r){if(r=r.filter(Boolean),r.length>2){const n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const ke=(e,...t)=>se("Key must be ",e,...t),ae=(e,t,...r)=>se(`Key for the ${e} algorithm must be `,t,...r),ie=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},oe=e=>e?.[Symbol.toStringTag]==="KeyObject",ce=e=>ie(e)||oe(e);function We(...e){const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){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 Ie=e=>typeof e=="object"&&e!==null;function E(e){if(!Ie(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Je(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function xe(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new g('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.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:t,keyUsages:r}}async function R(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=xe(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}async function Ue(e,t,r){if(!E(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return C(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new g('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return R({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return R({...e,ext:n})}case"EC":case"OKP":return R({...e,alg:t,ext:n});default:throw new g('Unsupported "kty" (Key Type) Parameter value')}}function De(e,t,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new e('"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 e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;a=t;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 e(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}const F=e=>E(e)&&typeof e.kty=="string",Me=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),Oe=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,He=e=>e.kty==="oct"&&typeof e.k=="string";let v;const q=async(e,t,r,n=!1)=>{v||=new WeakMap;let s=v.get(e);if(s?.[r])return s[r];const a=await R({...t,alg:r});return n&&Object.freeze(e),s?s[r]=a:v.set(e,{[r]:a}),a},Ne=(e,t)=>{v||=new WeakMap;let r=v.get(e);if(r?.[t])return r[t];const n=e.type==="public",s=!!n;let a;if(e.asymmetricKeyType==="x25519"){switch(t){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=e.toCryptoKey(e.asymmetricKeyType,s,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");a=e.toCryptoKey(e.asymmetricKeyType,s,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");a=e.toCryptoKey(e.asymmetricKeyType,s,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let i;switch(t){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(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:i},s,n?["encrypt"]:["decrypt"]);a=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},s,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){const c=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!c)throw new TypeError("given KeyObject instance cannot be used for this algorithm");t==="ES256"&&c==="P-256"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),t==="ES384"&&c==="P-384"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),t==="ES512"&&c==="P-521"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:c},s,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(a=e.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[t]=a:v.set(e,{[t]:a}),a};async function $e(e,t){if(e instanceof Uint8Array||ie(e))return e;if(oe(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return Ne(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return q(e,r,t)}if(F(e))return e.k?C(e.k):q(e,e,t,!0);throw new Error("unreachable")}const T=e=>e?.[Symbol.toStringTag],O=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case r==="verify":case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n="unwrapKey":n=r;break;case r==="encrypt":n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Le=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(F(t)){if(He(t)&&O(e,t,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(!ce(t))throw new TypeError(ae(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${T(t)} instances for symmetric algorithms must be of type "secret"`)}},Fe=(e,t,r)=>{if(F(t))switch(r){case"decrypt":case"sign":if(Me(t)&&O(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Oe(t)&&O(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ce(t))throw new TypeError(ae(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${T(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${T(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${T(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${T(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${T(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Ve(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Le(e,t,r);break;default:Fe(e,t,r)}}function Ge(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){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(e.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:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new g(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function ze(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(ke(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return Pe(t,e,r),t}async function Be(e,t,r,n){const s=await ze(e,t,"verify");Je(e,s);const a=Ge(e,s.algorithm);try{return await crypto.subtle.verify(a,s,r,n)}catch{return!1}}async function qe(e,t,r){if(!E(e))throw new f("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new f('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new f("JWS Protected Header incorrect type");if(e.payload===void 0)throw new f("JWS Payload missing");if(typeof e.signature!="string")throw new f("JWS Signature missing or incorrect type");if(e.header!==void 0&&!E(e.header))throw new f("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const k=C(e.protected);n=JSON.parse(_.decode(k))}catch{throw new f("JWS Protected Header is invalid")}if(!We(n,e.header))throw new f("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...n,...e.header},a=De(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 e.payload!="string")throw new f("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new f("JWS Payload must be a string or an Uint8Array instance");let h=!1;typeof t=="function"&&(t=await t(n,e),h=!0),Ve(c,t,"verify");const u=Ae(e.protected!==void 0?x(e.protected):new Uint8Array,x("."),typeof e.payload=="string"?i?x(e.payload):z.encode(e.payload):e.payload);let o;try{o=C(e.signature)}catch{throw new f("Failed to base64url decode the signature")}const l=await $e(t,c);if(!await Be(c,l,o,u))throw new Ce;let b;if(i)try{b=C(e.payload)}catch{throw new f("Failed to base64url decode the payload")}else typeof e.payload=="string"?b=z.encode(e.payload):b=e.payload;const p={payload:b};return e.protected!==void 0&&(p.protectedHeader=n),e.header!==void 0&&(p.unprotectedHeader=e.header),h?{...p,key:l}:p}async function Ye(e,t,r){if(e instanceof Uint8Array&&(e=_.decode(e)),typeof e!="string")throw new f("Compact JWS must be a string or Uint8Array");const{0:n,1:s,2:a,length:i}=e.split(".");if(i!==3)throw new f("Invalid Compact JWS");const c=await qe({payload:s,protected:n,signature:a},t,r),h={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t=="function"?{...h,key:c.key}:h}const Xe=e=>Math.floor(e.getTime()/1e3),ue=60,he=ue*60,V=he*24,Qe=V*7,Ze=V*365.25,je=/^(\+|\-)? ?(\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(e){const t=je.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]),n=t[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*ue);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*he);break;case"day":case"days":case"d":s=Math.round(r*V);break;case"week":case"weeks":case"w":s=Math.round(r*Qe);break;default:s=Math.round(r*Ze);break}return t[1]==="-"||t[4]==="ago"?-s:s}const X=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,et=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function tt(e,t,r={}){let n;try{n=JSON.parse(_.decode(t))}catch{}if(!E(n))throw new te("JWT Claims Set must be a top-level JSON object");const{typ:s}=r;if(s&&(typeof e.typ!="string"||X(e.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&&!et(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=Xe(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 rt(e,t,r){const n=await Ye(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new te("JWTs MUST NOT use unencoded payload");const a={payload:tt(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...a,key:n.key}:a}function nt(e){switch(typeof e=="string"&&e.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 st(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(at)}function at(e){return E(e)}class it{#r;#i=new WeakMap;constructor(t){if(!st(t))throw new re("JSON Web Key Set malformed");this.#r=structuredClone(t)}jwks(){return this.#r}async getKey(t,r){const{alg:n,kid:s}={...t,...r?.header},a=nt(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 ne;if(h!==1){const u=new Ke,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(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){const s=await Ue({...t,ext:!0},r);if(s instanceof Uint8Array||s.type!=="public")throw new re("JSON Web Key Set members must be public keys");n[r]=s}return n[r]}function Z(e){const t=new it(e),r=async(n,s)=>t.getKey(n,s);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}function ot(){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 ct=Symbol();async function ut(e,t,r,n=fetch){const s=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(a=>{throw a.name==="TimeoutError"?new ve: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 ht(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!E(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,E))}class ft{#r;#i;#c;#o;#n;#e;#t;#u;#s;#a;constructor(t,r){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this.#r=new URL(t.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?.[ct],r?.[D]!==void 0&&(this.#a=r?.[D],ht(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(t,r){(!this.#s||!this.fresh())&&await this.reload();try{return await this.#s(t,r)}catch(n){if(n instanceof ne&&this.coolingDown()===!1)return await this.reload(),this.#s(t,r);throw n}}async reload(){this.#e&&ot()&&(this.#e=void 0),this.#e||=ut(this.#r.href,this.#t,AbortSignal.timeout(this.#i),this.#u).then(t=>{this.#s=Z(t),this.#a&&(this.#a.uat=Date.now(),this.#a.jwks=t),this.#n=Date.now(),this.#e=void 0}).catch(t=>{throw this.#e=void 0,t}),await this.#e}}function lt(e,t){const r=new ft(e,t),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 j=new Map;async function fe(e,t=`${ee}/.well-known/jwks.json`){let r=j.get(t);return r||(r=lt(new URL(t)),j.set(t,r)),rt(e,r)}class le{store=new Map;async get(t){return this.store.get(t)??null}async set(t,r){this.store.set(t,r)}async remove(t){this.store.delete(t)}async clear(){this.store.clear()}}class N{prefix;constructor(t="genation"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}async get(t){return typeof window>"u"?null:localStorage.getItem(this.getKey(t))}async set(t,r){typeof window>"u"||localStorage.setItem(this.getKey(t),r)}async remove(t){typeof window>"u"||localStorage.removeItem(this.getKey(t))}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(t="genation"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}async get(t){return typeof window>"u"?null:sessionStorage.getItem(this.getKey(t))}async set(t,r){typeof window>"u"||sessionStorage.setItem(this.getKey(t),r)}async remove(t){typeof window>"u"||sessionStorage.removeItem(this.getKey(t))}async clear(){if(typeof window>"u")return;Object.keys(sessionStorage).filter(r=>r.startsWith(`${this.prefix}:`)).forEach(r=>sessionStorage.removeItem(r))}}function pe(e="localStorage"){switch(e){case"memory":return new le;case"localStorage":return new N;case"sessionStorage":return new de;default:return new N}}function $(e){return Array.isArray(e)?e.map($):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([t,r])=>[t.replace(/_([a-z])/g,(n,s)=>s.toUpperCase()),$(r)])):e}class ye{oauth;tokenManager;jwksUrl;http;httpServer;listeners=new Set;initialized=!1;constructor(t){this.validateConfig(t);const r=typeof t.storage=="object"?t.storage:pe(t.storage),n=t.authUrl??"https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";this.tokenManager=new be(r),this.oauth=new Ee(t,this.tokenManager),this.jwksUrl=`${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(t){if(!t.clientId)throw K.missingField("clientId");if(!t.clientSecret)throw K.missingField("clientSecret");if(!t.redirectUri)throw K.missingField("redirectUri")}async emitAuthStateChange(t){const r=await this.getSession();this.listeners.forEach(n=>{try{n(t,r)}catch(s){console.error("Error in auth state change callback:",s)}})}onAuthStateChange(t){return this.listeners.add(t),this.initialized?setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0):(this.initialized=!0,setTimeout(()=>{this.emitAuthStateChange("INITIAL_SESSION")},0)),{subscription:{unsubscribe:()=>{this.listeners.delete(t)}}}}async signIn(){return this.oauth.getAuthorizationUrl()}async handleCallback(t){const r=new URL(t),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(t){const{payload:r}=await fe(t,this.jwksUrl);return r}async getLicenses(t={}){const r=await this.getSession();if(!r)return null;const n=r.accessToken,{expiresAfter:s=new Date}=t,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(t){try{const r=await this.http.request("/oauth/userinfo",{headers:{Authorization:`Bearer ${t}`}});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 dt(e){return new ye(e)}exports.AuthError=S;exports.ConfigError=K;exports.GenationClient=ye;exports.GenationError=P;exports.LocalStorage=N;exports.MemoryStorage=le;exports.NetworkError=w;exports.SessionStorage=de;exports.createClient=dt;exports.createStorage=pe;exports.verifyToken=fe;
|
|
2
2
|
//# sourceMappingURL=genation.cjs.js.map
|