@juspay/neurolink 12.2.5 → 12.2.6
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/CHANGELOG.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
## [12.2.
|
|
1
|
+
## [12.2.6](https://github.com/juspay/neurolink/compare/v12.2.5...v12.2.6) (2026-08-27)
|
|
2
2
|
|
|
3
3
|
### Bug Fixes
|
|
4
4
|
|
|
5
|
-
- **(
|
|
5
|
+
- **(localUsage):** a window longer than history means everything, not nothing ([396553c](https://github.com/juspay/neurolink/commit/396553c073b31f07c30773221d45ed09a0965a10))
|
|
6
6
|
|
|
7
7
|
## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
|
|
8
8
|
|
|
@@ -2250,7 +2250,7 @@ Content:
|
|
|
2250
2250
|
${e.text}
|
|
2251
2251
|
|
|
2252
2252
|
Return the extracted data as JSON.`,s=await this.callLLM(o,t);try{const i=s.match(/\{[\s\S]*\}/);return JSON.parse(i?i[0]:s)}catch{return f.warn("[MetadataExtractor] Failed to parse custom extraction as JSON"),{raw:s}}}parseQAPairs(e,t){const r=[],n=e.split(`
|
|
2253
|
-
`).filter(i=>i.trim());let o=null,s=null;for(const i of n){const a=i.trim();/^\d+[.):]\s*/.test(a)||/^Q[.:]?\s*/i.test(a)?(o&&r.push({question:o,...t&&s?{answer:s}:{}}),o=a.replace(/^\d+[.):]\s*/,"").replace(/^Q[.:]?\s*/i,""),s=null):/^A[.:]?\s*/i.test(a)&&o?s=a.replace(/^A[.:]?\s*/i,""):o&&!s?o+=" "+a:s&&(s+=" "+a)}return o&&r.push({question:o,...t&&s?{answer:s}:{}}),r}async callLLM(e,t){return(await(await Ur.createProvider(t.provider||this.provider,t.modelName||this.modelName)).generate({prompt:e,maxTokens:t.maxTokens||500,temperature:t.temperature||.3}))?.content||""}}}}),UQt,Mie,zl,Mc=S({"src/lib/auth/providers/BaseAuthProvider.ts"(){"use strict";Ft(),vn(),q(),ta(),UQt=At,Mie=class{sessions=new Map;userSessions=new Map;async get(e){return this.sessions.get(e)??null}async save(e){this.sessions.set(e.id,e);const t=this.userSessions.get(e.user.id)??new Set;t.add(e.id),this.userSessions.set(e.user.id,t)}async delete(e){const t=this.sessions.get(e);if(t){this.sessions.delete(e);const r=this.userSessions.get(t.user.id);r&&(r.delete(e),r.size===0&&this.userSessions.delete(t.user.id))}}async deleteAllForUser(e){const t=this.userSessions.get(e);if(t){for(const r of t)this.sessions.delete(r);this.userSessions.delete(e)}}async getForUser(e){const t=this.userSessions.get(e);if(!t)return[];const r=Date.now(),n=[],o=[];for(const s of t){const i=this.sessions.get(s);if(i){if(i.expiresAt&&i.expiresAt.getTime()<r){o.push(s);continue}if(!i.isValid){o.push(s);continue}n.push(i)}}for(const s of o)this.sessions.delete(s),t.delete(s);return t.size===0&&this.userSessions.delete(e),n}async exists(e){return this.sessions.has(e)}async touch(e){const t=this.sessions.get(e);t&&(t.lastActivityAt=new Date,this.sessions.set(e,t))}async clear(){this.sessions.clear(),this.userSessions.clear()}get size(){return this.sessions.size}},zl=class{config;sessionStorage;sessionConfig;rbacConfig;emitter=new nn;constructor(e){const t={fromHeader:{name:"Authorization",scheme:"Bearer"}};this.config={required:!0,...e,tokenExtraction:{...t,...e.tokenExtraction}},this.sessionConfig={storage:"memory",duration:3600,autoRefresh:!0,refreshThreshold:300,allowMultipleSessions:!0,maxSessionsPerUser:10,prefix:"neurolink:session:",...e.session},this.rbacConfig={enabled:!0,defaultRoles:[],roleHierarchy:{},rolePermissions:{},superAdminRoles:["super_admin","root"],...e.rbac},this.sessionStorage=e.session?.customStorage??new Mie,f.debug("[BaseAuthProvider] Initialized")}async extractToken(e){const t=this.config.tokenExtraction;if(t?.fromHeader){const r=t.fromHeader.name.toLowerCase();let n;for(const[o,s]of Object.entries(e.headers))if(o.toLowerCase()===r&&typeof s=="string"){n=s;break}if(typeof n=="string")if(t.fromHeader.scheme){const o=`${t.fromHeader.scheme} `;if(n.startsWith(o))return n.slice(o.length)}else return n}if(t?.fromCookie&&e.cookies){const r=e.cookies[t.fromCookie.name];if(r)return r}if(t?.fromQuery&&e.path)try{const n=new URL(e.path,"http://localhost").searchParams.get(t.fromQuery.name);if(n)return n}catch{}return t?.custom?await Promise.resolve(t.custom(e)):null}async createSession(e,t){const r=new Date,n=this.sessionConfig.duration??3600;if(!this.sessionConfig.allowMultipleSessions)await this.revokeAllSessions(e.id);else if(this.sessionConfig.maxSessionsPerUser){const s=await this.sessionStorage.getForUser(e.id);if(s.length>=this.sessionConfig.maxSessionsPerUser){const i=s.sort((a,l)=>a.createdAt.getTime()-l.createdAt.getTime())[0];i&&await this.sessionStorage.delete(i.id)}}const o={id:st(),user:e,accessToken:st(),isValid:!0,expiresAt:new Date(r.getTime()+n*1e3),createdAt:r,lastActivityAt:r,ipAddress:t?.ip??t?.ipAddress,userAgent:t?.userAgent};return await this.sessionStorage.save(o),f.debug(`[BaseAuthProvider] Created session ${o.id} for user ${e.id}`),o}async validateSession(e){const t=await this.sessionStorage.get(e);if(!t)return{valid:!1,error:"Session not found",errorCode:"AUTH-010"};if(t.expiresAt&&t.expiresAt.getTime()<Date.now())return await this.sessionStorage.delete(e),{valid:!1,error:"Session expired",errorCode:"AUTH-011"};if(!t.isValid)return{valid:!1,error:"Session revoked",errorCode:"AUTH-012"};let r=!1;if(this.sessionConfig.autoRefresh&&this.sessionConfig.refreshThreshold&&t.expiresAt&&t.expiresAt.getTime()-Date.now()<this.sessionConfig.refreshThreshold*1e3){const n=await this.refreshSession(e);return r=!0,{valid:!0,session:n??void 0,refreshed:r}}return await this.sessionStorage.touch(e),{valid:!0,session:t,refreshed:r}}async refreshSession(e){const t=await this.sessionStorage.get(e);if(!t)throw At.create("SESSION_NOT_FOUND",`Session not found: ${e}`,{details:{sessionId:e}});if(!t.isValid)throw At.create("SESSION_REVOKED",`Cannot refresh revoked session: ${e}`,{details:{sessionId:e}});if(t.expiresAt&&t.expiresAt.getTime()<Date.now())throw await this.sessionStorage.delete(e),At.create("SESSION_EXPIRED",`Cannot refresh expired session: ${e}`,{details:{sessionId:e}});const r=this.sessionConfig.duration??3600;return t.expiresAt=new Date(Date.now()+r*1e3),t.lastActivityAt=new Date,await this.sessionStorage.save(t),f.debug(`[BaseAuthProvider] Refreshed session ${e}`),t}async revokeSession(e){const t=await this.sessionStorage.get(e);t&&(t.isValid=!1,await this.sessionStorage.save(t),f.debug(`[BaseAuthProvider] Revoked session ${e}`))}async revokeAllSessions(e){await this.sessionStorage.deleteAllForUser(e),f.debug(`[BaseAuthProvider] Revoked all sessions for user ${e}`)}async authorize(e,t){if(!this.rbacConfig.enabled)return{authorized:!0,user:e};if(this.isSuperAdmin(e))return{authorized:!0,user:e};const r={authorized:!0,user:e,requiredRoles:t.roles,requiredPermissions:t.permissions,missingRoles:[],missingPermissions:[]};if(t.roles&&t.roles.length>0){const n=this.getEffectiveRoles(e),o=t.roles.filter(s=>!n.has(s));t.requireAllRoles?o.length>0&&(r.authorized=!1,r.missingRoles=o,r.reason=`Missing required roles: ${o.join(", ")}`):t.roles.some(i=>n.has(i))||(r.authorized=!1,r.missingRoles=t.roles,r.reason=`Missing any of required roles: ${t.roles.join(", ")}`)}if(t.permissions&&t.permissions.length>0){const n=this.getEffectivePermissions(e),o=t.permissions.filter(s=>!this.hasPermission(n,s));o.length>0&&(r.authorized=!1,r.missingPermissions=o,r.reason=r.reason?`${r.reason}; Missing permissions: ${o.join(", ")}`:`Missing required permissions: ${o.join(", ")}`)}return r}isSuperAdmin(e){const t=this.rbacConfig.superAdminRoles??[];return e.roles.some(r=>t.includes(r))}getEffectiveRoles(e){const t=new Set(e.roles),r=this.rbacConfig.roleHierarchy??{};let n=!0;for(;n;){n=!1;for(const o of t){const s=r[o]??[];for(const i of s)t.has(i)||(t.add(i),n=!0)}}return t}getEffectivePermissions(e){const t=new Set(e.permissions),r=this.rbacConfig.rolePermissions??{},n=this.getEffectiveRoles(e);for(const o of n){const s=r[o]??[];for(const i of s)t.add(i)}return t}hasPermission(e,t){if(e.has(t)||e.has("*"))return!0;const r=t.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(e.has(o))return!0}return!1}parseJWT(e){try{const t=e.split(".");if(t.length!==3)return null;const r=t[1],n=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(n)}catch{return null}}isTokenExpired(e,t=0){if(!e.exp)return!1;const r=Math.floor(Date.now()/1e3);return e.exp+t<r}isTokenNotYetValid(e,t=0){if(!e.nbf)return!1;const r=Math.floor(Date.now()/1e3);return e.nbf-t>r}extractUserFromClaims(e,t){const r=t?.rolesClaimKey??"roles",n=t?.permissionsClaimKey??"permissions",o=t?.idClaimKey??"sub",s=Array.isArray(e[r])?e[r]:this.rbacConfig.defaultRoles??[],i=Array.isArray(e[n])?e[n]:[];return{id:e[o]??"",email:e.email,name:e.name,picture:e.picture,roles:s,permissions:i,emailVerified:e.email_verified,providerData:e}}async getUser(e){return f.debug(`[BaseAuthProvider] getUser not implemented for ${this.type}`),null}async updateUserRoles(e,t){throw At.create("PROVIDER_ERROR",`updateUserRoles not supported by ${this.type} provider`)}async updateUserPermissions(e,t){throw At.create("PROVIDER_ERROR",`updateUserPermissions not supported by ${this.type} provider`)}async dispose(){await this.sessionStorage.clear(),f.debug(`[BaseAuthProvider] Disposed ${this.type} provider`)}async authorizeUser(e,t){return this.authorize(e,{permissions:[t]})}async authorizeRoles(e,t){return this.authorize(e,{roles:t})}async authorizePermissions(e,t){return this.authorize(e,{permissions:t})}async getSession(e){return this.sessionStorage.get(e)}async destroySession(e){await this.revokeSession(e)}async getUserSessions(e){return this.sessionStorage.getForUser(e)}async destroyAllUserSessions(e){await this.revokeAllSessions(e)}async authenticateRequest(e){const t=await this.extractToken(e);if(!t)return this.config.required&&this.emitter.emit("auth:unauthorized",e,"No token provided"),null;const r=await this.authenticateToken(t,e);if(!r.valid||!r.user)return this.emitter.emit("auth:unauthorized",e,r.error??"Invalid token"),null;const s=(await this.getUserSessions(r.user.id)).find(i=>i.isValid&&(!i.expiresAt||i.expiresAt.getTime()>Date.now()))??await this.createSession(r.user,e);return{...e,user:r.user,session:s,request:e,authenticatedAt:new Date,provider:this.type}}async healthCheck(){return{healthy:!0,providerConnected:!0,sessionStorageHealthy:!0}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}emit(e,...t){this.emitter.emit(e,...t)}}}});function BQt(...e){const t=e.reduce((o,{length:s})=>o+s,0),r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function Ow(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}var Vx,Nw,OXr,Wx=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js"(){Vx=new TextEncoder,Nw=new TextDecoder,OXr=2**32}});function NXr(e){if(Uint8Array.prototype.toBase64)return e.toBase64();const t=32768,r=[];for(let n=0;n<e.length;n+=t)r.push(String.fromCharCode.apply(null,e.subarray(n,n+t)));return btoa(r.join(""))}function zQt(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}var jQt=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js"(){}});function i2(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:Nw.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=Nw.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return zQt(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Die(e){let t=e;return typeof t=="string"&&(t=Vx.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):NXr(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Kx=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js"(){Wx(),jQt()}});function LXr(e){return parseInt(e.name.slice(4),10)}function Oie(e,t){if(LXr(e.hash)!==t)throw Dp(`SHA-${t}`,"algorithm.hash")}function $Xr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function FXr(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function UXr(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!yy(e.algorithm,"HMAC"))throw Dp("HMAC");Oie(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!yy(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Dp("RSASSA-PKCS1-v1_5");Oie(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!yy(e.algorithm,"RSA-PSS"))throw Dp("RSA-PSS");Oie(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!yy(e.algorithm,"Ed25519"))throw Dp("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!yy(e.algorithm,t))throw Dp(t);break}case"ES256":case"ES384":case"ES512":{if(!yy(e.algorithm,"ECDSA"))throw Dp("ECDSA");const n=$Xr(t);if(e.algorithm.namedCurve!==n)throw Dp(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}FXr(e,r)}var Dp,yy,BXr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js"(){Dp=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),yy=(e,t)=>e.name===t}});function qQt(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}var GQt,Nie,HQt=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js"(){GQt=(e,...t)=>qQt("Key must be ",e,...t),Nie=(e,t,...r)=>qQt(`Key for the ${e} algorithm must be `,t,...r)}}),al,ku,Lie,VQt,jl,$o,a2,$ie,Fie,WQt,KQt,JQt,ql=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js"(){al=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},ku=class extends al{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}},Lie=class extends al{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}},VQt=class extends al{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},jl=class extends al{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},$o=class extends al{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},a2=class extends al{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},$ie=class extends al{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Fie=class extends al{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",t){super(e,t)}},WQt=class extends al{[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",t){super(e,t)}},KQt=class extends al{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}},JQt=class extends al{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}}}),Uie,Bie,zie,YQt=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js"(){Uie=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Bie=e=>e?.[Symbol.toStringTag]==="KeyObject",zie=e=>Uie(e)||Bie(e)}});function ZQt(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function XQt(e,t,r){try{return i2(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var QQt=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js"(){Kx()}});function Op(e){if(!ter(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 eer(...e){const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(const s of o){if(r.has(s))return!1;r.add(s)}}return!0}var ter,l2,rer,ner,oer,Np=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js"(){ter=e=>typeof e=="object"&&e!==null,l2=e=>Op(e)&&typeof e.kty=="string",rer=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),ner=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,oer=e=>e.kty==="oct"&&typeof e.k=="string"}});function ser(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 ier(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 jl(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function aer(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(GQt(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return UXr(t,e,r),t}async function zXr(e,t,r){const n=await aer(e,t,"sign");ser(e,n);const o=await crypto.subtle.sign(ier(e,n.algorithm),n,r);return new Uint8Array(o)}async function jXr(e,t,r,n){const o=await aer(e,t,"verify");ser(e,o);const s=ier(e,o.algorithm);try{return await crypto.subtle.verify(s,o,r,n)}catch{return!1}}var ler=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js"(){ql(),BXr(),HQt()}});function qXr(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 jl(Jx)}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 jl(Jx)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},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 jl(Jx)}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 jl(Jx)}break}default:throw new jl('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function c2(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=qXr(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)}var Jx,cer=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js"(){ql(),Jx='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'}});async function uer(e,t){if(e instanceof Uint8Array||Uie(e))return e;if(Bie(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return der(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return jie(e,r,t)}if(l2(e))return e.k?i2(e.k):jie(e,e,t,!0);throw new Error("unreachable")}var vy,Lw,jie,der,per=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js"(){Np(),Kx(),cer(),YQt(),vy="given KeyObject instance cannot be used for this algorithm",jie=async(e,t,r,n=!1)=>{Lw||=new WeakMap;let o=Lw.get(e);if(o?.[r])return o[r];const s=await c2({...t,alg:r});return n&&Object.freeze(e),o?o[r]=s:Lw.set(e,{[r]:s}),s},der=(e,t)=>{Lw||=new WeakMap;let r=Lw.get(e);if(r?.[t])return r[t];const n=e.type==="public",o=!!n;let s;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(vy)}s=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(vy);s=e.toCryptoKey(e.asymmetricKeyType,o,[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(vy);s=e.toCryptoKey(e.asymmetricKeyType,o,[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(vy)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:i},o,n?["encrypt"]:["decrypt"]);s=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){const a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(vy);const l={ES256:"P-256",ES384:"P-384",ES512:"P-521"};l[t]&&a===l[t]&&(s=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(s=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!s)throw new TypeError(vy);return r?r[t]=s:Lw.set(e,{[t]:s}),s}}});function GXr(e){Zx(e,48,"Invalid SPKI structure"),Yx(e),Zx(e,48,"Expected algorithm identifier");const t=Yx(e);return{algIdStart:e.pos,algIdLength:t}}var u2,mer,Yx,Zx,qie,her,fer,ger,yer,ver,HXr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/asn1.js"(){jQt(),ql(),u2=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},mer=e=>({data:e,pos:0}),Yx=e=>{const t=e.data[e.pos++];if(t&128){const r=t&127;let n=0;for(let o=0;o<r;o++)n=n<<8|e.data[e.pos++];return n}return t},Zx=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},qie=(e,t)=>{const r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},her=e=>{Zx(e,6,"Expected algorithm OID");const t=Yx(e);return qie(e,t)},fer=e=>{const t=her(e);if(u2(t,[43,101,110]))return"X25519";if(!u2(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");Zx(e,6,"Expected curve OID");const r=Yx(e),n=qie(e,r);for(const{name:o,oid:s}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(u2(n,s))return o;throw new Error("Unsupported named curve")},ger=async(e,t,r,n)=>{let o,s;const i=e==="spki",a=()=>i?["verify"]:["sign"],l=()=>i?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},s=l();break;case"ES256":case"ES384":case"ES512":{o={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},s=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{const c=n.getNamedCurve(t);o=c==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:c}}catch{throw new jl("Invalid or unsupported key format")}s=i?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":o={name:"Ed25519"},s=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":o={name:r},s=a();break;default:throw new jl('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,o,n?.extractable??!!i,s)},yer=(e,t)=>zQt(e.replace(t,"")),ver=(e,t,r)=>{const n=yer(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);let o=r;return t?.startsWith?.("ECDH-ES")&&(o||={},o.getNamedCurve=s=>{const i=mer(s);return GXr(i),fer(i)}),ger("spki",n,t,o)}}});async function VXr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return ver(e,t,r)}async function Gie(e,t,r){if(!Op(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return i2(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new jl('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return c2({...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 c2({...e,ext:n})}case"EC":case"OKP":return c2({...e,alg:t,ext:n});default:throw new jl('Unsupported "kty" (Key Type) Parameter value')}}var _er=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js"(){Kx(),HXr(),cer(),ql(),Np()}});function wer(e,t,r,n,o){if(o.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 s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(const i of n.crit){if(!s.has(i))throw new jl(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var ber=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js"(){ql()}});function WXr(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var KXr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js"(){}});function Ter(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Eer(e,t,r);break;default:Ser(e,t,r)}}var _y,d2,Eer,Ser,Cer=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js"(){HQt(),YQt(),Np(),_y=e=>e?.[Symbol.toStringTag],d2=(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==="sign"||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=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):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},Eer=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(l2(t)){if(oer(t)&&d2(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(!zie(t))throw new TypeError(Nie(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${_y(t)} instances for symmetric algorithms must be of type "secret"`)}},Ser=(e,t,r)=>{if(l2(t))switch(r){case"decrypt":case"sign":if(rer(t)&&d2(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(ner(t)&&d2(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!zie(t))throw new TypeError(Nie(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${_y(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${_y(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${_y(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${_y(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${_y(t)} instances for asymmetric algorithm encryption must be of type "public"`)}}}});async function JXr(e,t,r){if(!Op(e))throw new $o("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new $o('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new $o("JWS Protected Header incorrect type");if(e.payload===void 0)throw new $o("JWS Payload missing");if(typeof e.signature!="string")throw new $o("JWS Signature missing or incorrect type");if(e.header!==void 0&&!Op(e.header))throw new $o("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const v=i2(e.protected);n=JSON.parse(Nw.decode(v))}catch{throw new $o("JWS Protected Header is invalid")}if(!eer(n,e.header))throw new $o("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header},s=wer($o,new Map([["b64",!0]]),r?.crit,n,o);let i=!0;if(s.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new $o('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if(typeof a!="string"||!a)throw new $o('JWS "alg" (Algorithm) Header Parameter missing or invalid');const l=r&&WXr("algorithms",r.algorithms);if(l&&!l.has(a))throw new VQt('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof e.payload!="string")throw new $o("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new $o("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof t=="function"&&(t=await t(n,e),c=!0),Ter(a,t,"verify");const u=BQt(e.protected!==void 0?Ow(e.protected):new Uint8Array,Ow("."),typeof e.payload=="string"?i?Ow(e.payload):Vx.encode(e.payload):e.payload),d=XQt(e.signature,"signature",$o),m=await uer(t,a);if(!await jXr(a,m,d,u))throw new JQt;let g;i?g=XQt(e.payload,"payload",$o):typeof e.payload=="string"?g=Vx.encode(e.payload):g=e.payload;const y={payload:g};return e.protected!==void 0&&(y.protectedHeader=n),e.header!==void 0&&(y.unprotectedHeader=e.header),c?{...y,key:m}:y}var YXr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js"(){Kx(),ler(),ql(),Wx(),QQt(),Np(),Np(),Cer(),ber(),KXr(),per()}});async function ZXr(e,t,r){if(e instanceof Uint8Array&&(e=Nw.decode(e)),typeof e!="string")throw new $o("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:s,length:i}=e.split(".");if(i!==3)throw new $o("Invalid Compact JWS");const a=await JXr({payload:o,protected:n,signature:s},t,r),l={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...l,key:a.key}:l}var XXr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js"(){YXr(),ql(),Wx()}});function Xx(e){const t=Aer.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 o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*Hie);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*Vie);break;case"day":case"days":case"d":o=Math.round(r*p2);break;case"week":case"weeks":case"w":o=Math.round(r*ker);break;default:o=Math.round(r*xer);break}return t[1]==="-"||t[4]==="ago"?-o:o}function wy(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function QXr(e,t,r={}){let n;try{n=JSON.parse(Nw.decode(t))}catch{}if(!Op(n))throw new a2("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&(typeof e.typ!="string"||Wie(e.typ)!==Wie(o)))throw new ku('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:s=[],issuer:i,subject:a,audience:l,maxTokenAge:c}=r,u=[...s];c!==void 0&&u.push("iat"),l!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),i!==void 0&&u.push("iss");for(const g of new Set(u.reverse()))if(!(g in n))throw new ku(`missing required "${g}" claim`,n,g,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new ku('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new ku('unexpected "sub" claim value',n,"sub","check_failed");if(l&&!Ier(n.aud,typeof l=="string"?[l]:l))throw new ku('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=Xx(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,h=Lp(m||new Date);if((n.iat!==void 0||c)&&typeof n.iat!="number")throw new ku('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new ku('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>h+d)throw new ku('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new ku('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=h-d)throw new Lie('"exp" claim timestamp check failed',n,"exp","check_failed")}if(c){const g=h-n.iat,y=typeof c=="number"?c:Xx(c);if(g-d>y)throw new Lie('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(g<0-d)throw new ku('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var Lp,Hie,Vie,p2,ker,xer,Aer,Wie,Ier,Rer,Per=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js"(){ql(),Wx(),Np(),Lp=e=>Math.floor(e.getTime()/1e3),Hie=60,Vie=Hie*60,p2=Vie*24,ker=p2*7,xer=p2*365.25,Aer=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Wie=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,Ier=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,Rer=class{#e;constructor(e){if(!Op(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return Vx.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=wy("setNotBefore",e):e instanceof Date?this.#e.nbf=wy("setNotBefore",Lp(e)):this.#e.nbf=Lp(new Date)+Xx(e)}set exp(e){typeof e=="number"?this.#e.exp=wy("setExpirationTime",e):e instanceof Date?this.#e.exp=wy("setExpirationTime",Lp(e)):this.#e.exp=Lp(new Date)+Xx(e)}set iat(e){e===void 0?this.#e.iat=Lp(new Date):e instanceof Date?this.#e.iat=wy("setIssuedAt",Lp(e)):typeof e=="string"?this.#e.iat=wy("setIssuedAt",Lp(new Date)+Xx(e)):this.#e.iat=wy("setIssuedAt",e)}}}});async function xu(e,t,r){const n=await ZXr(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new a2("JWTs MUST NOT use unencoded payload");const s={payload:QXr(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...s,key:n.key}:s}var eQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js"(){XXr(),Per(),ql()}}),Mer,tQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js"(){Kx(),ler(),Np(),ql(),Wx(),Cer(),ber(),per(),QQt(),Mer=class{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return ZQt(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return ZQt(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,t){if(!this.#t&&!this.#r)throw new $o("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!eer(this.#t,this.#r))throw new $o("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this.#t,...this.#r},n=wer($o,new Map([["b64",!0]]),t?.crit,this.#t,r);let o=!0;if(n.has("b64")&&(o=this.#t.b64,typeof o!="boolean"))throw new $o('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if(typeof s!="string"||!s)throw new $o('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ter(s,e,"sign");let i,a;o?(i=Die(this.#e),a=Ow(i)):(a=this.#e,i="");let l,c;this.#t?(l=Die(JSON.stringify(this.#t)),c=Ow(l)):(l="",c=new Uint8Array);const u=BQt(c,Ow("."),a),d=await uer(e,s),m=await zXr(s,d,u),h={signature:Die(m),payload:i};return this.#r&&(h.header=this.#r),this.#t&&(h.protected=l),h}}}}),Der,rQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js"(){tQr(),Der=class{#e;constructor(e){this.#e=new Mer(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,t){const r=await this.#e.sign(e,t);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}}}),Oer,nQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js"(){rQr(),ql(),Per(),Oer=class{#e;#t;constructor(e={}){this.#t=new Rer(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,t){const r=new Der(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new a2("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}}});function oQr(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 jl('Unsupported "alg" value for a JSON Web Key Set')}}function sQr(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(iQr)}function iQr(e){return Op(e)}async function Ner(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){const o=await Gie({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new $ie("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function Ler(e){const t=new $er(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var $er,aQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js"(){_er(),ql(),Np(),$er=class{#e;#t=new WeakMap;constructor(e){if(!sQr(e))throw new $ie("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=oQr(r),s=this.#e.keys.filter(l=>{let c=o===l.kty;if(c&&typeof n=="string"&&(c=n===l.kid),c&&(typeof l.alg=="string"||o==="AKP")&&(c=r===l.alg),c&&typeof l.use=="string"&&(c=l.use==="sig"),c&&Array.isArray(l.key_ops)&&(c=l.key_ops.includes("verify")),c)switch(r){case"ES256":c=l.crv==="P-256";break;case"ES384":c=l.crv==="P-384";break;case"ES512":c=l.crv==="P-521";break;case"Ed25519":case"EdDSA":c=l.crv==="Ed25519";break}return c}),{0:i,length:a}=s;if(a===0)throw new Fie;if(a!==1){const l=new WQt,c=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(const u of s)try{yield await Ner(c,u,r)}catch{}},l}return Ner(this.#t,i,r)}}}});function lQr(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function cQr(e,t,r,n=fetch){const o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(s=>{throw s.name==="TimeoutError"?new KQt:s});if(o.status!==200)throw new al("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new al("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function uQr(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!Op(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,Op))}function Qx(e,t){const r=new Uer(e,t),n=async(o,s)=>r.getKey(o,s);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}var Kie,Fer,m2,Uer,dQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js"(){ql(),aQr(),Np(),(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Kie="jose/v6.2.2"),Fer=Symbol(),m2=Symbol(),Uer=class{#e;#t;#r;#n;#o;#s;#i;#c;#a;#l;constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration=="number"?t?.timeoutDuration:5e3,this.#r=typeof t?.cooldownDuration=="number"?t?.cooldownDuration:3e4,this.#n=typeof t?.cacheMaxAge=="number"?t?.cacheMaxAge:6e5,this.#i=new Headers(t?.headers),Kie&&!this.#i.has("User-Agent")&&this.#i.set("User-Agent",Kie),this.#i.has("accept")||(this.#i.set("accept","application/json"),this.#i.append("accept","application/jwk-set+json")),this.#c=t?.[Fer],t?.[m2]!==void 0&&(this.#l=t?.[m2],uQr(t?.[m2],this.#n)&&(this.#o=this.#l.uat,this.#a=Ler(this.#l.jwks)))}pendingFetch(){return!!this.#s}coolingDown(){return typeof this.#o=="number"?Date.now()<this.#o+this.#r:!1}fresh(){return typeof this.#o=="number"?Date.now()<this.#o+this.#n:!1}jwks(){return this.#a?.jwks()}async getKey(e,t){(!this.#a||!this.fresh())&&await this.reload();try{return await this.#a(e,t)}catch(r){if(r instanceof Fie&&this.coolingDown()===!1)return await this.reload(),this.#a(e,t);throw r}}async reload(){this.#s&&lQr()&&(this.#s=void 0),this.#s||=cQr(this.#e.href,this.#i,AbortSignal.timeout(this.#t),this.#c).then(e=>{this.#a=Ler(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#o=Date.now(),this.#s=void 0}).catch(e=>{throw this.#s=void 0,e}),await this.#s}}}}),vd=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js"(){eQr(),nQr(),dQr(),_er()}}),Ber={};he(Ber,{Auth0Provider:()=>zer});var zer,pQr=S({"src/lib/auth/providers/auth0.ts"(){"use strict";Mc(),ta(),q(),no(),vd(),zer=class extends zl{type="auth0";domain;clientId;audience;rolesNamespace;permissionsNamespace;jwks=null;constructor(e){if(super(e),!e.domain)throw At.create("CONFIGURATION_ERROR","Auth0 domain is required",{details:{missingFields:["domain"]}});if(!e.clientId)throw At.create("CONFIGURATION_ERROR","Auth0 clientId is required",{details:{missingFields:["clientId"]}});this.domain=e.domain,this.clientId=e.clientId,this.audience=e.audience,this.rolesNamespace=e.options?.rolesNamespace,this.permissionsNamespace=e.options?.permissionsNamespace}async initialize(){try{const e=new URL(`https://${this.domain}/.well-known/jwks.json`);this.jwks=Qx(e),f.debug(`Auth0 provider initialized for domain: ${this.domain}`)}catch(e){throw At.create("PROVIDER_INIT_FAILED","Failed to initialize Auth0 JWKS",{cause:e instanceof Error?e:new Error(String(e))})}}async authenticateToken(e,t){this.jwks||await this.initialize();try{if(!this.jwks)return{valid:!1,error:"Auth0 JWKS not initialized"};const{payload:r}=await xu(e,this.jwks,{issuer:`https://${this.domain}/`,audience:this.audience}),n=r;if(this.audience){const c=n.aud;if(!(Array.isArray(c)?c:[c]).includes(this.audience))return{valid:!1,error:`Token audience does not match expected audience: ${this.audience}`}}if(this.clientId){const c=n.aud,u=r.azp,d=Array.isArray(c)?c:[c];if(u){if(u!==this.clientId)return{valid:!1,error:`Token azp claim "${u}" does not match clientId "${this.clientId}"`}}else if(!d.includes(this.clientId))return{valid:!1,error:`Token audience does not include clientId "${this.clientId}"`}}const o=this.rolesNamespace??"roles",s=this.permissionsNamespace??"permissions",i=r[o]||n.roles||[],a=r[s]||n.permissions||[],l={id:n.sub,email:n.email,name:n.name,picture:n.picture,emailVerified:n.email_verified,roles:i,permissions:a,metadata:{iss:n.iss,aud:n.aud}};return{valid:!0,payload:r,user:l,expiresAt:new Date(n.exp*1e3),tokenType:"jwt"}}catch(r){const n=r instanceof Error?r.message:String(r);return f.warn("Auth0 token validation failed:",n),{valid:!1,error:n}}}async getUser(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return f.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user profile"),null;try{const n=await Bt()(`https://${this.domain}/api/v2/users/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok){if(n.status===404)return null;throw At.create("PROVIDER_ERROR",`Auth0 API returned ${n.status}`,{details:{statusCode:n.status}})}const o=await n.json();return{id:o.user_id,email:o.email,name:o.name,picture:o.picture,emailVerified:o.email_verified,roles:o.app_metadata?.roles||[],permissions:o.app_metadata?.permissions||[],createdAt:o.created_at?new Date(o.created_at):void 0,lastLoginAt:o.last_login?new Date(o.last_login):void 0,metadata:o.user_metadata}}catch(r){throw f.error("Failed to fetch Auth0 user:",r),r}}async getUserByEmail(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return f.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user by email"),null;try{const n=await Bt()(`https://${this.domain}/api/v2/users-by-email?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok)throw At.create("PROVIDER_ERROR",`Auth0 API returned ${n.status}`,{details:{statusCode:n.status}});const o=await n.json();if(o.length===0)return null;const s=o[0];return{id:s.user_id,email:s.email,name:s.name,picture:s.picture,emailVerified:s.email_verified,roles:s.app_metadata?.roles||[],permissions:s.app_metadata?.permissions||[],createdAt:s.created_at?new Date(s.created_at):void 0,lastLoginAt:s.last_login?new Date(s.last_login):void 0,metadata:s.user_metadata}}catch(r){throw f.error("Failed to fetch Auth0 user by email:",r),r}}async healthCheck(){try{const t=await Bt()(`https://${this.domain}/.well-known/openid-configuration`);return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0,error:t.ok?void 0:`HTTP ${t.status}`}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),jer={};he(jer,{ClerkProvider:()=>qer});var qer,mQr=S({"src/lib/auth/providers/clerk.ts"(){"use strict";Mc(),ta(),q(),no(),vd(),qer=class extends zl{type="clerk";secretKey;jwtKey;publishableKey;jwks=null;localKey=null;constructor(e){if(super(e),!e.secretKey)throw At.create("CONFIGURATION_ERROR","Clerk secretKey is required",{details:{missingFields:["secretKey"]}});this.secretKey=e.secretKey,this.jwtKey=e.jwtKey,this.publishableKey=e.publishableKey}async initialize(){const e=new URL("https://api.clerk.com/v1/jwks");this.jwks=Qx(e),f.debug("Clerk provider initialized")}async authenticateToken(e,t){return e.includes(".")&&e.split(".").length===3?this.validateJWT(e):this.validateSessionToken(e)}async validateJWT(e){try{let t;if(this.jwtKey)this.localKey||(this.localKey=new TextEncoder().encode(this.jwtKey)),{payload:t}=await xu(e,this.localKey);else{if(this.jwks||await this.initialize(),!this.jwks)return{valid:!1,error:"Clerk JWKS not initialized"};({payload:t}=await xu(e,this.jwks))}if(this.publishableKey&&t.azp&&t.azp!==this.publishableKey)return{valid:!1,error:`Invalid authorized party: ${t.azp}. Expected: ${this.publishableKey}`};const r={id:t.sub,email:t.email,name:t.name,picture:t.picture,emailVerified:t.email_verified,roles:t["https://clerk.dev/roles"]||[],permissions:t["https://clerk.dev/permissions"]||[],organizationId:t.org_id,metadata:{azp:t.azp,sid:t.sid}};return{valid:!0,payload:t,user:r,expiresAt:t.exp?new Date(t.exp*1e3):void 0,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async validateSessionToken(e){try{const r=await Bt()("https://api.clerk.com/v1/sessions/verify",{method:"POST",headers:{Authorization:`Bearer ${this.secretKey}`,"Content-Type":"application/json"},body:JSON.stringify({token:e})});if(!r.ok)return{valid:!1,error:(await r.json()).errors?.[0]?.message||"Session validation failed"};const n=await r.json(),o=n.user,s=o?.email_addresses,i={id:n.user_id,email:s?.[0]?.email_address,name:o?.first_name?`${o.first_name} ${o.last_name||""}`.trim():void 0,picture:o?.image_url,roles:o?.public_metadata?.roles||[],permissions:o?.public_metadata?.permissions||[],organizationId:n.active_organization_id};return{valid:!0,payload:n,user:i,expiresAt:n.expire_at?new Date(n.expire_at):void 0,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async getUser(e){try{const r=await Bt()(`https://api.clerk.com/v1/users/${e}`,{headers:{Authorization:`Bearer ${this.secretKey}`}});if(!r.ok){if(r.status===404)return null;throw At.create("PROVIDER_ERROR",`Clerk API returned ${r.status}`,{details:{statusCode:r.status}})}const n=await r.json(),o=n.email_addresses;return{id:n.id,email:o?.[0]?.email_address,name:n.first_name?`${n.first_name} ${n.last_name||""}`.trim():void 0,picture:n.image_url,emailVerified:o?.[0]?.verification?.status==="verified",roles:n.public_metadata?.roles||[],permissions:n.public_metadata?.permissions||[],createdAt:n.created_at?new Date(n.created_at):void 0,lastLoginAt:n.last_sign_in_at?new Date(n.last_sign_in_at):void 0,metadata:n.private_metadata}}catch(t){if(f.error("Failed to fetch Clerk user:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async getUserByEmail(e){try{const r=await Bt()(`https://api.clerk.com/v1/users?email_address=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.secretKey}`}});if(!r.ok)throw At.create("PROVIDER_ERROR",`Clerk API returned ${r.status}`,{details:{statusCode:r.status}});const n=await r.json();if(n.length===0)return null;const o=n[0],s=o.email_addresses;return{id:o.id,email:s?.[0]?.email_address,name:o.first_name?`${o.first_name} ${o.last_name||""}`.trim():void 0,picture:o.image_url,emailVerified:s?.[0]?.verification?.status==="verified",roles:o.public_metadata?.roles||[],permissions:o.public_metadata?.permissions||[],createdAt:o.created_at?new Date(o.created_at):void 0,lastLoginAt:o.last_sign_in_at?new Date(o.last_sign_in_at):void 0,metadata:o.private_metadata}}catch(t){if(f.error("Failed to fetch Clerk user by email:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async healthCheck(){try{const t=await Bt()("https://api.clerk.com/v1/organizations?limit=1",{headers:{Authorization:`Bearer ${this.secretKey}`}});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Ger={};he(Ger,{FirebaseAuthProvider:()=>Her});var Her,hQr=S({"src/lib/auth/providers/firebase.ts"(){"use strict";Mc(),ta(),q(),no(),vd(),Her=class extends zl{type="firebase";projectId;apiKey;serviceAccount;jwks=null;constructor(e){if(super(e),!e.projectId)throw At.create("CONFIGURATION_ERROR","Firebase projectId is required",{details:{missingFields:["projectId"]}});this.projectId=e.projectId,this.apiKey=e.apiKey,this.serviceAccount=e.serviceAccount}async initialize(){const e=new URL("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com");this.jwks=Qx(e),f.debug(`Firebase provider initialized for project: ${this.projectId}`)}async authenticateToken(e,t){this.jwks||await this.initialize();try{const r=this.jwks;if(!r)throw At.create("PROVIDER_INIT_FAILED","Firebase JWKS was not initialized",{details:{provider:"firebase"}});const{payload:n}=await xu(e,r,{issuer:`https://securetoken.google.com/${this.projectId}`,audience:this.projectId}),o=this.payloadToUser(n);return{valid:!0,payload:n,user:o,expiresAt:n.exp?new Date(n.exp*1e3):void 0,tokenType:"jwt"}}catch(r){return this.apiKey?this.validateViaApi(e):{valid:!1,error:r instanceof Error?r.message:String(r)}}}async validateViaApi(e){try{const r=await Bt()(`https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({idToken:e}),signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:(await r.json()).error?.message||`Firebase API returned ${r.status}`};const o=(await r.json()).users||[];if(o.length===0)return{valid:!1,error:"User not found"};const s=o[0],i=this.firebaseUserToAuthUser(s);return{valid:!0,payload:s,user:i,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}payloadToUser(e){const t=e;return{id:e.sub,email:e.email,name:e.name,picture:e.picture,emailVerified:e.email_verified,roles:t.roles||[],permissions:t.permissions||[],metadata:{firebase:{sign_in_provider:e.firebase?.sign_in_provider||"unknown",identities:e.firebase?.identities}}}}firebaseUserToAuthUser(e){let t={};if(e.customAttributes)try{t=JSON.parse(e.customAttributes)}catch{f.warn("Failed to parse Firebase customAttributes, treating as empty")}return{id:e.localId,email:e.email,name:e.displayName,picture:e.photoUrl,emailVerified:e.emailVerified,roles:t.roles||[],permissions:t.permissions||[],createdAt:e.createdAt?new Date(parseInt(e.createdAt)):void 0,lastLoginAt:e.lastLoginAt?new Date(parseInt(e.lastLoginAt)):void 0,metadata:{providerUserInfo:e.providerUserInfo}}}async getUser(e){return this.apiKey?(f.warn("Direct user lookup by ID requires Firebase Admin SDK which is not supported in browser/edge environments"),null):(f.warn("Firebase API key required for user lookup"),null)}async healthCheck(){try{const t=await Bt()("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",{signal:AbortSignal.timeout(5e3)});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Ver={};he(Ver,{SupabaseAuthProvider:()=>Wer});var Wer,fQr=S({"src/lib/auth/providers/supabase.ts"(){"use strict";Mc(),ta(),q(),no(),vd(),Wer=class extends zl{type="supabase";supabaseUrl;anonKey;serviceRoleKey;jwtSecret;constructor(e){if(super(e),!e.url)throw At.create("CONFIGURATION_ERROR","Supabase URL is required",{details:{missingFields:["url"]}});if(!e.anonKey)throw At.create("CONFIGURATION_ERROR","Supabase anon key is required",{details:{missingFields:["anonKey"]}});this.supabaseUrl=e.url.replace(/\/$/,""),this.anonKey=e.anonKey,this.serviceRoleKey=e.serviceRoleKey,this.jwtSecret=e.jwtSecret}async authenticateToken(e,t){try{if(this.jwtSecret){const i=new TextEncoder().encode(this.jwtSecret),{payload:a}=await xu(e,i);if(!a.sub)return{valid:!1,error:"Token missing sub claim: cannot authenticate without a user identity"};const l=a.role;if(l&&l!=="authenticated")return{valid:!1,error:`Invalid token role: ${l}. Only "authenticated" role is accepted`};const c=this.payloadToUser(a);return{valid:!0,payload:a,user:c,expiresAt:a.exp?new Date(a.exp*1e3):void 0,tokenType:"jwt"}}const n=await Bt()(`${this.supabaseUrl}/auth/v1/user`,{headers:{Authorization:`Bearer ${e}`,apikey:this.anonKey}});if(!n.ok)return{valid:!1,error:`Token validation failed: HTTP ${n.status}`};const o=await n.json(),s=this.supabaseUserToAuthUser(o);return{valid:!0,payload:o,user:s,tokenType:"jwt"}}catch(r){return{valid:!1,error:r instanceof Error?r.message:String(r)}}}payloadToUser(e){const t=e.app_metadata,r=e.user_metadata,n=e.role;return{id:e.sub,email:e.email,name:r?.full_name||r?.name,picture:r?.avatar_url,emailVerified:e.email_confirmed||!1,roles:n?[n]:t?.roles||[],permissions:t?.permissions||[],metadata:r}}supabaseUserToAuthUser(e){const t=e.app_metadata,r=e.user_metadata;return{id:e.id,email:e.email,name:r?.full_name||r?.name,picture:r?.avatar_url,emailVerified:!!e.email_confirmed_at,roles:t?.roles||[],permissions:t?.permissions||[],createdAt:e.created_at?new Date(e.created_at):void 0,lastLoginAt:e.last_sign_in_at?new Date(e.last_sign_in_at):void 0,metadata:r}}async getUser(e){if(!this.serviceRoleKey)return f.warn("Service role key required for user lookup"),null;try{const r=await Bt()(`${this.supabaseUrl}/auth/v1/admin/users/${e}`,{headers:{Authorization:`Bearer ${this.serviceRoleKey}`,apikey:this.anonKey}});if(!r.ok){if(r.status===404)return null;throw At.create("PROVIDER_ERROR",`Supabase API returned ${r.status}`,{details:{statusCode:r.status}})}const n=await r.json();return this.supabaseUserToAuthUser(n)}catch(t){if(f.error("Failed to fetch Supabase user:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async getUserByEmail(e){if(!this.serviceRoleKey)return f.warn("Service role key required for user lookup by email"),null;try{const r=await Bt()(`${this.supabaseUrl}/auth/v1/admin/users?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.serviceRoleKey}`,apikey:this.anonKey}});if(!r.ok)throw At.create("PROVIDER_ERROR",`Supabase API returned ${r.status}`,{details:{statusCode:r.status}});const o=(await r.json()).users||[];return o.length===0?null:this.supabaseUserToAuthUser(o[0])}catch(t){if(f.error("Failed to fetch Supabase user by email:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async healthCheck(){try{const t=await Bt()(`${this.supabaseUrl}/auth/v1/health`,{headers:{apikey:this.anonKey}});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Ker={};he(Ker,{CognitoProvider:()=>Jer});var Jie,Jer,gQr=S({"src/lib/auth/providers/CognitoProvider.ts"(){"use strict";vd(),q(),ta(),Mc(),Jie=new Map,Jer=class extends zl{type="cognito";cognitoConfig;jwksUri;jwksCacheDuration;expectedIssuer;constructor(e){if(super(e),e.type!=="cognito")throw At.create("CONFIGURATION_ERROR",`Invalid provider type: ${e.type}. Expected: cognito`);if(this.cognitoConfig=e,!this.cognitoConfig.userPoolId)throw At.create("CONFIGURATION_ERROR","Cognito userPoolId is required");if(!this.cognitoConfig.clientId)throw At.create("CONFIGURATION_ERROR","Cognito clientId is required");if(!this.cognitoConfig.region)throw At.create("CONFIGURATION_ERROR","Cognito region is required");this.expectedIssuer=`https://cognito-idp.${this.cognitoConfig.region}.amazonaws.com/${this.cognitoConfig.userPoolId}`,this.jwksUri=`${this.expectedIssuer}/.well-known/jwks.json`,this.jwksCacheDuration=e.tokenValidation?.jwksCacheDuration??6e5,f.debug(`[CognitoProvider] Initialized for user pool: ${this.cognitoConfig.userPoolId}`)}async authenticateToken(e){try{const t=this.parseJWT(e);if(!t)return{valid:!1,error:"Failed to decode token",errorCode:"AUTH-006"};if(t.iss!==this.expectedIssuer)return{valid:!1,error:`Invalid issuer: ${t.iss}. Expected: ${this.expectedIssuer}`,errorCode:"AUTH-001"};const r=t.token_use;if(r!=="id"&&r!=="access")return{valid:!1,error:`Invalid token_use: ${r}. Expected: id or access`,errorCode:"AUTH-001"};if(r==="id"){if(t.aud!==this.cognitoConfig.clientId)return{valid:!1,error:`Invalid audience: ${t.aud}. Expected: ${this.cognitoConfig.clientId}`,errorCode:"AUTH-001"}}else if(t.client_id!==this.cognitoConfig.clientId)return{valid:!1,error:`Invalid client_id: ${t.client_id}. Expected: ${this.cognitoConfig.clientId}`,errorCode:"AUTH-001"};const n=this.config.tokenValidation?.clockTolerance??30;if(this.isTokenExpired(t,n))return{valid:!1,error:"Token has expired",errorCode:"AUTH-002",expiresAt:t.exp?new Date(t.exp*1e3):void 0};if(this.config.tokenValidation?.validateSignature!==!1&&!await this.verifySignature(e))return{valid:!1,error:"Invalid token signature",errorCode:"AUTH-004"};const o=this.extractCognitoUser(t,r),s={};for(const[i,a]of Object.entries(t))a!==void 0&&(s[i]=a);return{valid:!0,user:o,claims:s,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return f.error("[CognitoProvider] Token validation error:",t),{valid:!1,error:t instanceof Error?t.message:"Token validation failed",errorCode:"AUTH-014"}}}async verifySignature(e){try{const t=e.split(".");if(t.length!==3)return!1;const r=JSON.parse(Buffer.from(t[0],"base64url").toString("utf-8")),n=r.kid;if(!n)return f.warn("[CognitoProvider] Token missing kid in header"),!1;const s=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!s)return f.warn(`[CognitoProvider] Key not found for kid: ${n}`),!1;const i=await Gie(s,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await xu(e,i,{clockTolerance:a}),!0}catch(t){return f.error("[CognitoProvider] Signature verification error:",t),!1}}async getJWKS(){const e=Jie.get(this.jwksUri);if(e&&e.expiresAt>Date.now())return e.jwks;try{const t=await fetch(this.jwksUri,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`JWKS fetch failed: ${t.status}`);const r=await t.json();return Jie.set(this.jwksUri,{jwks:r,expiresAt:Date.now()+this.jwksCacheDuration}),r}catch(t){throw At.create("JWKS_FETCH_FAILED",`Failed to fetch JWKS from ${this.jwksUri}: ${t instanceof Error?t.message:String(t)}`,{cause:t instanceof Error?t:void 0})}}extractCognitoUser(e,t){const r=e.sub??"",n=e.email??e["custom:email"],o=e.name??e["cognito:username"]??e.preferred_username,s=e.picture??e["custom:picture"];let i=[];const a=e["cognito:groups"];a&&Array.isArray(a)&&(i=a),i.length===0&&this.rbacConfig.defaultRoles&&(i=this.rbacConfig.defaultRoles);const l=[];if(this.cognitoConfig.customAttributes)for(const d of this.cognitoConfig.customAttributes){const m=e[`custom:${d}`];m&&(m.includes(",")?l.push(...m.split(",").map(h=>h.trim())):l.push(m))}const c={provider:"cognito"};e["cognito:username"]!==void 0&&(c.username=e["cognito:username"]),c.token_use=t,e.auth_time!==void 0&&(c.auth_time=e.auth_time);const u=e.client_id??e.aud;return u!==void 0&&(c.client_id=u),a!==void 0&&(c.cognito_groups=a),{id:r,email:n,name:o,picture:s,roles:i,permissions:l,emailVerified:e.email_verified,providerData:c}}async getUser(e){return f.debug("[CognitoProvider] getUser() is not implemented. Requires AWS SDK (@aws-sdk/client-cognito-identity-provider)."),null}}}}),Yer={};he(Yer,{KeycloakProvider:()=>Zer});var Yie,Zer,yQr=S({"src/lib/auth/providers/KeycloakProvider.ts"(){"use strict";vd(),q(),ta(),Mc(),Yie=new Map,Zer=class extends zl{type="keycloak";keycloakConfig;jwksUri;jwksCacheDuration;expectedIssuer;constructor(e){if(super(e),e.type!=="keycloak")throw At.create("CONFIGURATION_ERROR",`Invalid provider type: ${e.type}. Expected: keycloak`);if(this.keycloakConfig=e,!this.keycloakConfig.serverUrl)throw At.create("CONFIGURATION_ERROR","Keycloak serverUrl is required");if(!this.keycloakConfig.realm)throw At.create("CONFIGURATION_ERROR","Keycloak realm is required");if(!this.keycloakConfig.clientId)throw At.create("CONFIGURATION_ERROR","Keycloak clientId is required");const t=this.keycloakConfig.serverUrl.replace(/\/$/,"");this.expectedIssuer=`${t}/realms/${this.keycloakConfig.realm}`,this.jwksUri=`${this.expectedIssuer}/protocol/openid-connect/certs`,this.jwksCacheDuration=e.tokenValidation?.jwksCacheDuration??6e5,f.debug(`[KeycloakProvider] Initialized for realm: ${this.keycloakConfig.realm}`)}async authenticateToken(e){try{const t=this.parseJWT(e);if(!t)return{valid:!1,error:"Failed to decode token",errorCode:"AUTH-006"};if(t.iss!==this.expectedIssuer)return{valid:!1,error:`Invalid issuer: ${t.iss}. Expected: ${this.expectedIssuer}`,errorCode:"AUTH-001"};if(!(Array.isArray(t.aud)?t.aud:[t.aud]).includes(this.keycloakConfig.clientId))return{valid:!1,error:`Invalid audience: token aud does not contain clientId "${this.keycloakConfig.clientId}"`,errorCode:"AUTH-001"};const n=t.azp;if(n&&n!==this.keycloakConfig.clientId)return{valid:!1,error:`Invalid authorized party: ${n}. Expected: ${this.keycloakConfig.clientId}`,errorCode:"AUTH-001"};const o=this.config.tokenValidation?.clockTolerance??0;if(this.isTokenExpired(t,o))return{valid:!1,error:"Token has expired",errorCode:"AUTH-002",expiresAt:t.exp?new Date(t.exp*1e3):void 0};if(this.isTokenNotYetValid(t,o))return{valid:!1,error:"Token is not yet valid",errorCode:"AUTH-001"};if(this.keycloakConfig.verifyToken!==!1&&this.config.tokenValidation?.validateSignature!==!1&&!await this.verifySignature(e))return{valid:!1,error:"Invalid token signature",errorCode:"AUTH-004"};const s=this.extractKeycloakUser(t),i={};for(const[a,l]of Object.entries(t))l!==void 0&&(i[a]=l);return{valid:!0,user:s,claims:i,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return f.error("[KeycloakProvider] Token validation error:",t),{valid:!1,error:t instanceof Error?t.message:"Token validation failed",errorCode:"AUTH-014"}}}async verifySignature(e){try{const t=e.split(".");if(t.length!==3)return!1;const r=JSON.parse(Buffer.from(t[0],"base64url").toString("utf-8")),n=r.kid;if(!n)return f.warn("[KeycloakProvider] Token missing kid in header"),!1;const s=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!s)return f.warn(`[KeycloakProvider] Key not found for kid: ${n}`),!1;const i=await Gie(s,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await xu(e,i,{clockTolerance:a}),!0}catch(t){return f.error("[KeycloakProvider] Signature verification error:",t),!1}}async getJWKS(){const e=Yie.get(this.jwksUri);if(e&&e.expiresAt>Date.now())return e.jwks;try{const t=await fetch(this.jwksUri,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`JWKS fetch failed: ${t.status}`);const r=await t.json();return Yie.set(this.jwksUri,{jwks:r,expiresAt:Date.now()+this.jwksCacheDuration}),r}catch(t){throw At.create("JWKS_FETCH_FAILED",`Failed to fetch JWKS from ${this.jwksUri}: ${t instanceof Error?t.message:String(t)}`,{cause:t instanceof Error?t:void 0})}}extractKeycloakUser(e){const t=e.sub??"",r=e.email,n=e.name??e.preferred_username,o=e.picture;let s=[];const i=e.realm_access;i?.roles&&(s=[...i.roles]);const a=e.resource_access;if(a){const d=a[this.keycloakConfig.clientId]?.roles;d&&(s=[...s,...d.map(m=>`${this.keycloakConfig.clientId}:${m}`)]);for(const[m,h]of Object.entries(a))m!==this.keycloakConfig.clientId&&h.roles&&(s=[...s,...h.roles.map(g=>`${m}:${g}`)])}s.length===0&&this.rbacConfig.defaultRoles&&(s=this.rbacConfig.defaultRoles);let l=[];const c=e.scope;c&&(l=c.split(" ").filter(d=>d.length>0));const u={provider:"keycloak"};return e.preferred_username!==void 0&&(u.preferred_username=e.preferred_username),e.given_name!==void 0&&(u.given_name=e.given_name),e.family_name!==void 0&&(u.family_name=e.family_name),i!==void 0&&(u.realm_access=i),a!==void 0&&(u.resource_access=a),e.azp!==void 0&&(u.azp=e.azp),e.session_state!==void 0&&(u.session_state=e.session_state),e.acr!==void 0&&(u.acr=e.acr),e.typ!==void 0&&(u.typ=e.typ),{id:t,email:r,name:n,picture:o,roles:s,permissions:l,emailVerified:e.email_verified,providerData:u}}async getUser(e){if(!this.keycloakConfig.clientSecret)return f.debug("[KeycloakProvider] clientSecret required for admin API"),null;try{const t=await fetch(`${this.expectedIssuer}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:this.keycloakConfig.clientId,client_secret:this.keycloakConfig.clientSecret}),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Failed to get admin token: ${t.status}`);const r=await t.json(),n=this.keycloakConfig.serverUrl.replace(/\/$/,""),o=await fetch(`${n}/admin/realms/${this.keycloakConfig.realm}/users/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${r.access_token}`},signal:AbortSignal.timeout(5e3)});if(!o.ok){if(o.status===404)return null;throw new Error(`Failed to get user: ${o.status}`)}const s=await o.json(),i=await fetch(`${n}/admin/realms/${this.keycloakConfig.realm}/users/${encodeURIComponent(e)}/role-mappings/realm`,{headers:{Authorization:`Bearer ${r.access_token}`},signal:AbortSignal.timeout(5e3)});let a=this.rbacConfig.defaultRoles??[];i.ok&&(a=(await i.json()).map(u=>u.name));const l={};for(const[c,u]of Object.entries(s))u!==void 0&&(l[c]=u);return{id:s.id,email:s.email,name:`${s.firstName??""} ${s.lastName??""}`.trim()||s.username,picture:void 0,roles:a,permissions:[],emailVerified:s.emailVerified,providerData:l,createdAt:s.createdTimestamp?new Date(s.createdTimestamp):void 0}}catch(t){return f.error(`[KeycloakProvider] Failed to get user ${e}:`,t),null}}}}}),Xer={};he(Xer,{BetterAuthProvider:()=>Qer});var Qer,vQr=S({"src/lib/auth/providers/betterAuth.ts"(){"use strict";no(),ta(),vd(),Mc(),Qer=class extends zl{type="better-auth";secret;baseUrl;secretKey;constructor(e){if(super(e),!e.secret)throw At.create("CONFIGURATION_ERROR","Better Auth secret is required",{details:{provider:"better-auth",missingFields:["secret"]}});if(!e.baseUrl)throw At.create("CONFIGURATION_ERROR","Better Auth baseUrl is required",{details:{provider:"better-auth",missingFields:["baseUrl"]}});this.secret=e.secret,this.baseUrl=e.baseUrl.replace(/\/$/,""),this.secretKey=new TextEncoder().encode(this.secret)}async authenticateToken(e,t){if(e.includes(".")&&e.split(".").length===3){const r=await this.validateJWT(e);if(r.valid)return r}return this.validateSessionViaAPI(e)}async validateJWT(e){try{const{payload:t}=await xu(e,this.secretKey);if(!t.sub)return{valid:!1,error:"Token missing required 'sub' claim"};const r={id:t.sub,email:t.email,name:t.name,picture:t.picture,emailVerified:t.email_verified,roles:t.roles||[],permissions:t.permissions||[],metadata:t.metadata};return{valid:!0,payload:t,user:r,expiresAt:t.exp?new Date(t.exp*1e3):void 0,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async validateSessionViaAPI(e){try{const r=await Bt()(`${this.baseUrl}/api/auth/session`,{headers:{Cookie:`better-auth.session_token=${e}`},signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`Session validation failed: HTTP ${r.status}`};const n=await r.json();if(!n.user)return{valid:!1,error:"Invalid session"};const o={id:n.user.id,email:n.user.email,name:n.user.name,picture:n.user.image,emailVerified:n.user.emailVerified,roles:n.user.roles||[],permissions:n.user.permissions||[],createdAt:n.user.createdAt?new Date(n.user.createdAt):void 0,metadata:n.user};return{valid:!0,payload:n,user:o,expiresAt:n.session?.expiresAt?new Date(n.session.expiresAt):void 0,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async healthCheck(){try{const r=(await Bt()(`${this.baseUrl}/api/auth/session`,{signal:AbortSignal.timeout(5e3)})).status<500;return{healthy:r,providerConnected:r,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),etr={};he(etr,{WorkOSProvider:()=>ttr});var ttr,_Qr=S({"src/lib/auth/providers/workos.ts"(){"use strict";q(),no(),ta(),vd(),Mc(),ttr=class extends zl{type="workos";apiKey;clientId;organizationId;jwks=null;constructor(e){if(super(e),!e.apiKey)throw At.create("CONFIGURATION_ERROR","WorkOS API key is required",{details:{provider:"workos",missingFields:["apiKey"]}});if(!e.clientId)throw At.create("CONFIGURATION_ERROR","WorkOS client ID is required",{details:{provider:"workos",missingFields:["clientId"]}});this.apiKey=e.apiKey,this.clientId=e.clientId,this.organizationId=e.organizationId}async initialize(){const e=new URL("https://api.workos.com/sso/jwks");this.jwks=Qx(e),f.debug("WorkOS provider initialized")}async authenticateToken(e,t){this.jwks||await this.initialize();try{const r=this.jwks;if(!r)throw At.create("PROVIDER_INIT_FAILED","WorkOS JWKS was not initialized",{details:{provider:"workos"}});const{payload:n}=await xu(e,r,{audience:this.clientId});if(this.organizationId&&n.org_id!==this.organizationId)return{valid:!1,error:`Organization mismatch: expected ${this.organizationId}, got ${n.org_id}`};const o={id:n.sub,email:n.email,name:n.first_name&&n.last_name?`${n.first_name} ${n.last_name}`.trim():void 0,emailVerified:!0,roles:n.roles||[],permissions:n.permissions||[],organizationId:n.org_id,metadata:{connection_id:n.connection_id,connection_type:n.connection_type,idp_id:n.idp_id}};return{valid:!0,payload:n,user:o,expiresAt:n.exp?new Date(n.exp*1e3):void 0,tokenType:"jwt"}}catch{return this.validateSessionViaAPI(e)}}async validateSessionViaAPI(e){try{const r=await Bt()("https://api.workos.com/user_management/authenticate",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({session_token:e,client_id:this.clientId}),signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`Session validation failed: HTTP ${r.status}`};const n=await r.json();if(!n.user)return{valid:!1,error:"User not found in session"};if(this.organizationId&&n.organization_id!==this.organizationId)return{valid:!1,error:`Organization mismatch: expected ${this.organizationId}, got ${n.organization_id}`};const o={id:n.user.id,email:n.user.email,name:n.user.first_name&&n.user.last_name?`${n.user.first_name} ${n.user.last_name}`.trim():void 0,picture:n.user.profile_picture_url,emailVerified:n.user.email_verified,roles:[],permissions:[],organizationId:n.organization_id,createdAt:n.user.created_at?new Date(n.user.created_at):void 0,metadata:n.user};return{valid:!0,payload:n,user:o,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async getUser(e){try{const r=await Bt()(`https://api.workos.com/user_management/users/${e}`,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!r.ok){if(r.status===404)return null;throw At.create("PROVIDER_ERROR",`WorkOS API returned ${r.status}`,{details:{provider:"workos",statusCode:r.status}})}const n=await r.json();return{id:n.id,email:n.email,name:n.first_name&&n.last_name?`${n.first_name} ${n.last_name}`.trim():void 0,picture:n.profile_picture_url,emailVerified:n.email_verified,roles:[],permissions:[],createdAt:n.created_at?new Date(n.created_at):void 0,metadata:n}}catch(t){throw f.error("Failed to fetch WorkOS user:",t instanceof Error?t.message:String(t)),t}}async getUserByEmail(e){try{const r=await Bt()(`https://api.workos.com/user_management/users?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!r.ok)throw At.create("PROVIDER_ERROR",`WorkOS API returned ${r.status}`,{details:{provider:"workos",statusCode:r.status}});const o=(await r.json()).data||[];if(o.length===0)return null;const s=o[0];return{id:s.id,email:s.email,name:s.first_name&&s.last_name?`${s.first_name} ${s.last_name}`.trim():void 0,picture:s.profile_picture_url,emailVerified:s.email_verified,roles:[],permissions:[],createdAt:s.created_at?new Date(s.created_at):void 0,metadata:s}}catch(t){if(f.error("Failed to fetch WorkOS user by email:",t instanceof Error?t.message:String(t)),t instanceof Error&&t.name==="AuthError")throw t;return null}}async healthCheck(){try{const t=await Bt()("https://api.workos.com/sso/jwks");return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),rtr={};he(rtr,{OAuth2Provider:()=>ntr});var ntr,wQr=S({"src/lib/auth/providers/oauth2.ts"(){"use strict";vd(),no(),q(),ta(),Mc(),ntr=class extends zl{type="oauth2";authorizationUrl;tokenUrl;userInfoUrl;jwksUrl;clientId;clientSecret;scopes;redirectUrl;usePKCE;jwks=null;constructor(e){if(super(e),!e.authorizationUrl)throw At.create("CONFIGURATION_ERROR","OAuth2 authorizationUrl is required");if(!e.tokenUrl)throw At.create("CONFIGURATION_ERROR","OAuth2 tokenUrl is required");if(!e.clientId)throw At.create("CONFIGURATION_ERROR","OAuth2 clientId is required");this.authorizationUrl=e.authorizationUrl,this.tokenUrl=e.tokenUrl,this.userInfoUrl=e.userInfoUrl,this.jwksUrl=e.jwksUrl,this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.scopes=e.scopes??["openid","profile","email"],this.redirectUrl=e.redirectUrl,this.usePKCE=e.usePKCE??!1}async initialize(){if(this.jwksUrl)try{const e=new URL(this.jwksUrl);this.jwks=Qx(e),f.debug(`OAuth2 provider initialized with JWKS: ${this.jwksUrl}`)}catch(e){throw At.create("PROVIDER_INIT_FAILED","Failed to initialize OAuth2 JWKS",{cause:e instanceof Error?e:new Error(String(e))})}}async authenticateToken(e,t){if(this.jwksUrl){if(this.jwks||await this.initialize(),!this.jwks)return{valid:!1,error:"JWKS not available after initialization"};try{const{payload:r}=await xu(e,this.jwks);if(r.iss){const o=new URL(this.authorizationUrl).origin;if(!r.iss.startsWith(o))return{valid:!1,error:`Invalid issuer: ${r.iss}. Expected origin: ${o}`}}if(r.aud){const o=Array.isArray(r.aud)?r.aud:[r.aud];if(!o.includes(this.clientId))return{valid:!1,error:`Invalid audience: ${o.join(", ")}. Expected: ${this.clientId}`}}if(!r.sub)return{valid:!1,error:"JWT is missing required 'sub' claim: cannot identify user"};const n={id:r.sub,email:r.email,name:r.name,picture:r.picture,roles:r.roles??[],permissions:r.permissions??[],metadata:r};return{valid:!0,payload:r,user:n,expiresAt:r.exp?new Date(r.exp*1e3):void 0,tokenType:"jwt"}}catch{f.debug("JWKS validation failed, trying userinfo endpoint")}}return this.userInfoUrl?this.validateViaUserInfo(e):{valid:!1,error:"No validation method available (provide jwksUrl or userInfoUrl)"}}async validateViaUserInfo(e){try{const t=Bt();if(!this.userInfoUrl)return{valid:!1,error:"UserInfo URL not configured"};const r=await t(this.userInfoUrl,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`UserInfo endpoint returned ${r.status}`};const n=await r.json(),o=n.sub??n.id;if(!o)return{valid:!1,error:"UserInfo response is missing 'sub' and 'id': cannot identify user"};const s={id:o,email:n.email,name:n.name,picture:n.picture,emailVerified:n.email_verified,roles:n.roles??[],permissions:n.permissions??[],metadata:n};return{valid:!0,payload:n,user:s,tokenType:"oauth"}}catch(t){const r=t instanceof Error?t.message:String(t);return f.warn("OAuth2 userinfo validation failed:",r),{valid:!1,error:r}}}getAuthorizationUrl(e,t){const r=new URLSearchParams({response_type:"code",client_id:this.clientId,scope:this.scopes.join(" "),state:e});return this.redirectUrl&&r.set("redirect_uri",this.redirectUrl),this.usePKCE&&t&&(r.set("code_challenge",t),r.set("code_challenge_method","S256")),`${this.authorizationUrl}?${r.toString()}`}async exchangeCode(e,t){const r=Bt(),n=new URLSearchParams({grant_type:"authorization_code",client_id:this.clientId,code:e});this.clientSecret&&n.set("client_secret",this.clientSecret),this.redirectUrl&&n.set("redirect_uri",this.redirectUrl),this.usePKCE&&t&&n.set("code_verifier",t);const o=await r(this.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),signal:AbortSignal.timeout(5e3)});if(!o.ok)throw At.create("PROVIDER_ERROR",`Token exchange failed: ${o.status}`);const s=await o.json();return{accessToken:s.access_token,refreshToken:s.refresh_token,idToken:s.id_token}}async healthCheck(){try{const e=Bt(),t=this.jwksUrl??this.authorizationUrl,r=await e(t,{method:"HEAD"});return{healthy:r.ok||r.status===405,providerConnected:!0,sessionStorageHealthy:!0,error:r.ok||r.status===405?void 0:`HTTP ${r.status}`}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),otr={};he(otr,{JWTProvider:()=>str});var str,bQr=S({"src/lib/auth/providers/jwt.ts"(){"use strict";vd(),q(),ta(),Mc(),str=class extends zl{type="jwt";secret;publicKey;algorithms;issuer;audience;keyObject=null;constructor(e){if(super(e),!e.secret&&!e.publicKey)throw At.create("CONFIGURATION_ERROR","JWT requires either secret (for HMAC) or publicKey (for RSA/ECDSA)",{details:{provider:"jwt",missingFields:["secret","publicKey"]}});this.secret=e.secret,this.publicKey=e.publicKey,this.algorithms=e.algorithms??(e.secret?["HS256"]:["RS256"]),this.issuer=e.issuer,this.audience=e.audience}async initialize(){try{this.secret?(this.keyObject=new TextEncoder().encode(this.secret),f.debug("JWT provider initialized with symmetric secret")):this.publicKey&&(this.keyObject=await VXr(this.publicKey,this.algorithms[0]),f.debug("JWT provider initialized with asymmetric public key"))}catch(e){throw At.create("PROVIDER_INIT_FAILED",`Failed to initialize JWT key: ${e instanceof Error?e.message:String(e)}`,{details:{provider:"jwt"},cause:e instanceof Error?e:void 0})}}async authenticateToken(e,t){this.keyObject||await this.initialize();try{const r=this.keyObject;if(!r)throw At.create("PROVIDER_INIT_FAILED","JWT verification key was not initialized",{details:{provider:"jwt"}});const n={};this.algorithms.length>0&&(n.algorithms=this.algorithms),this.issuer&&(n.issuer=this.issuer),this.audience&&(n.audience=this.audience);const{payload:o}=await xu(e,r,n);if(!o.sub)return{valid:!1,error:"JWT is missing required 'sub' claim: cannot identify user"};const s={id:o.sub,email:o.email,name:o.name,picture:o.picture,emailVerified:o.email_verified,roles:o.roles??[],permissions:o.permissions??o.scope?.split(" ")??[],metadata:{iss:o.iss,aud:o.aud,jti:o.jti}};return{valid:!0,payload:o,user:s,expiresAt:o.exp?new Date(o.exp*1e3):void 0,tokenType:"jwt"}}catch(r){const n=r instanceof Error?r.message:String(r);f.warn("JWT validation failed:",n);let o=n;return n.includes("JWTExpired")?o="Token has expired":n.includes("signature")?o="Invalid token signature":n.includes("audience")?o="Invalid token audience":n.includes("issuer")&&(o="Invalid token issuer"),{valid:!1,error:o}}}async signToken(e,t){if(!this.secret)throw At.create("CONFIGURATION_ERROR","Token signing requires a secret (symmetric key)",{details:{provider:"jwt"}});this.keyObject||await this.initialize();const r=new Oer(e).setProtectedHeader({alg:this.algorithms[0]}).setIssuedAt();return this.issuer&&r.setIssuer(this.issuer),this.audience&&r.setAudience(this.audience),t?.expiresIn&&r.setExpirationTime(t.expiresIn),r.sign(this.keyObject)}async healthCheck(){try{return this.keyObject||await this.initialize(),{healthy:this.keyObject!==null,providerConnected:!0,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),itr={};he(itr,{CustomAuthProvider:()=>atr});var atr,TQr=S({"src/lib/auth/providers/custom.ts"(){"use strict";q(),ta(),Mc(),atr=class extends zl{type="custom";validateTokenFn;getUserFn;createSessionFn;constructor(e){if(super(e),!e.validateToken)throw At.create("CONFIGURATION_ERROR","Custom validateToken function is required",{details:{provider:"custom",missingFields:["validateToken"]}});this.validateTokenFn=e.validateToken,this.getUserFn=e.getUser,this.createSessionFn=e.createSession}async authenticateToken(e,t){try{return await this.validateTokenFn(e,t)}catch(r){return{valid:!1,error:r instanceof Error?r.message:String(r)}}}async createSession(e,t){if(this.createSessionFn){const r=await this.createSessionFn(e,t);return await this.sessionStorage.save(r),this.emit("auth:login",r.user),r}return super.createSession(e,t)}async getUser(e){if(this.getUserFn)try{return await this.getUserFn(e)}catch(t){return f.error("Custom getUser failed:",t),null}return f.warn("Custom getUser function not provided"),null}async healthCheck(){return{healthy:!0,providerConnected:!0,sessionStorageHealthy:!0}}}}}),EQr,SQr,CQr,kQr,h2,ltr,Zie,xQr,Xie,AQr,IQr,RQr,ctr=S({"node-stub:readline"(){EQr=globalThis.crypto,SQr=globalThis.ReadableStream||class{},CQr=globalThis.URL,kQr=globalThis.URLSearchParams,h2=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},h2.custom=Symbol.for("nodejs.util.inspect.custom"),h2.colors={},h2.styles={},ltr=globalThis.TextDecoder,Zie=globalThis.TextEncoder,xQr=globalThis.performance||{now:()=>Date.now()},Xie=()=>({}),AQr=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new Zie().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new Zie().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new ltr().decode(this)}},IQr=globalThis.clearTimeout,RQr=globalThis.clearInterval}});function Qie(e,t=utr){const r=e??t,n=Number.isNaN(r)?0:r;if(n===1/0)return;const o=Math.max(0,n)*dtr;return Date.now()-(Number.isFinite(o)?o:0)}var utr,dtr,eae=S({"src/lib/localUsage/scanWindow.ts"(){"use strict";utr=30,dtr=864e5}}),ptr={};he(ptr,{createClaudeCodeReader:()=>DQr});function mtr(){return Cr(Uu(),".claude","projects")}function PQr(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"modeled",unpricedRequests:0,unpricedModels:[]}}async function htr(e,t){let r;try{r=await AM(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Cr(e,n.name);n.isDirectory()?await htr(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function f2(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function MQr(e,t,r){const n=new Map,o=Xie({input:k1(e,{encoding:"utf8"}),crlfDelay:1/0});try{for await(const s of o){if(!s||s.charCodeAt(0)!==123)continue;let i;try{i=JSON.parse(s)}catch{continue}const a=i;if(a.type!=="assistant"||!a.message?.usage)continue;const l=a.message.usage,c=a.message.id;if(typeof c!="string"||c.length===0)continue;const u={model:a.message.model??"unknown",input:f2(l.input_tokens),output:f2(l.output_tokens),read:f2(l.cache_read_input_tokens),create:f2(l.cache_creation_input_tokens)},d=n.get(c);(!d||u.output>d.output)&&n.set(c,u)}}finally{o.close()}for(const s of n.values())t.requests+=1,t.inputTokens+=s.input,t.outputTokens+=s.output,t.cacheReadTokens+=s.read,t.cacheCreationTokens+=s.create,YE(tae,s.model)?t.costUsd+=Ga(tae,s.model,{input:s.input,output:s.output,total:s.input+s.output,cacheReadTokens:s.read,cacheCreationTokens:s.create}):(t.unpricedRequests+=1,r.add(s.model))}async function DQr(){return{descriptor:{id:g2,displayName:"Claude Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"modeled",requiresSqlite:!1},detect:async()=>{try{return(await Yu(mtr())).isDirectory()}catch{return!1}},scan:async e=>{const t=PQr(),r=[],n=new Set,o=[];await htr(mtr(),o);const s=Qie(e?.sinceDays);let i=0;for(const a of o)try{if(s!==void 0&&(await Yu(a)).mtimeMs<s)continue;await MQr(a,t,n),i+=1}catch(l){r.push({cliId:g2,filePath:a,message:l instanceof Error?l.message:String(l)})}return t.unpricedModels=[...n].sort(),t.costUsd=Math.round(t.costUsd*1e6)/1e6,{cliId:g2,totals:t,filesScanned:i,errors:r}}}}var g2,tae,OQr=S({"src/lib/localUsage/claudeCodeReader.ts"(){"use strict";gn(),ctr(),ya(),ic(),Lr(),uc(),eae(),g2="claude-code",tae="anthropic"}}),ftr={};he(ftr,{createCodexReader:()=>$Qr});function gtr(){return Cr(Uu(),".codex","sessions")}function NQr(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}async function ytr(e,t){let r;try{r=await AM(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Cr(e,n.name);n.isDirectory()?await ytr(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function y2(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function LQr(e){const t=Xie({input:k1(e,{encoding:"utf8"}),crlfDelay:1/0});let r,n=-1,o,s=-1,i=0;try{for await(const a of t){const l=a.includes('"token_count"'),c=a.includes('"turn_context"');if(!l&&!c)continue;let u;try{u=JSON.parse(a)}catch{continue}const d=u;if(d.type==="turn_context"&&d.payload?.model){r=d.payload.model;continue}if(d.payload?.type!=="token_count")continue;const m=d.payload.info?.total_token_usage;if(!m)continue;const h=y2(m.total_tokens);h>s&&(i+=1),s=h,h>n&&(n=h,o={input:y2(m.input_tokens),output:y2(m.output_tokens),cached:y2(m.cached_input_tokens)})}}finally{t.close()}return o?{model:r,billableEvents:i,...o}:null}async function $Qr(){return{descriptor:{id:v2,displayName:"Codex",verified:!0,dedupStrategy:"session-dag",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await Yu(gtr())).isDirectory()}catch{return!1}},scan:async e=>{const t=NQr(),r=[],n=new Set,o=[];await ytr(gtr(),o);const s=Qie(e?.sinceDays);let i=0;for(const a of o)try{if(s!==void 0&&(await Yu(a)).mtimeMs<s)continue;const l=await LQr(a);if(i+=1,!l)continue;t.requests+=l.billableEvents,t.inputTokens+=Math.max(0,l.input-l.cached),t.cacheReadTokens+=l.cached,t.outputTokens+=l.output,l.model&&n.add(l.model)}catch(l){r.push({cliId:v2,filePath:a,message:l instanceof Error?l.message:String(l)})}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:v2,totals:t,filesScanned:i,errors:r}}}}var v2,FQr=S({"src/lib/localUsage/codexReader.ts"(){"use strict";gn(),ctr(),ya(),ic(),Lr(),eae(),v2="codex"}}),vtr={};he(vtr,{AsyncLocalStorage:()=>Utr,Buffer:()=>Pnr,Channel:()=>wnr,DatabaseSync:()=>Rnr,Duplex:()=>ztr,EventEmitter:()=>Ftr,Http2ServerRequest:()=>Lnr,Http2ServerResponse:()=>$nr,Interface:()=>Inr,MIMEType:()=>qnr,PassThrough:()=>jtr,PerformanceObserver:()=>ynr,Readable:()=>nae,ReadableStream:()=>qtr,Resolver:()=>fnr,TextDecoder:()=>iae,TextEncoder:()=>tA,Transform:()=>Btr,URL:()=>rnr,URLSearchParams:()=>nnr,Worker:()=>Snr,Writable:()=>oae,access:()=>yrr,appendFile:()=>Ytr,appendFileSync:()=>Ctr,arch:()=>Nrr,arrayBuffer:()=>Fnr,basename:()=>Ptr,builtinModules:()=>Xrr,callbackify:()=>unr,channel:()=>_nr,chmodSync:()=>Jtr,clearInterval:()=>jnr,clearTimeout:()=>Bnr,closeSync:()=>err,connect:()=>Urr,constants:()=>Mnr,copyFileSync:()=>Xtr,cpSync:()=>ktr,cpus:()=>Prr,createConnection:()=>Brr,createGunzip:()=>Wrr,createGzip:()=>Krr,createHash:()=>rae,createHmac:()=>btr,createInterface:()=>Anr,createReadStream:()=>urr,createRequire:()=>Zrr,createServer:()=>xtr,createWriteStream:()=>crr,debug:()=>lnr,debuglog:()=>sae,default:()=>_tr,deflateSync:()=>jrr,deprecate:()=>cnr,deserialize:()=>Enr,dirname:()=>Rtr,exec:()=>Err,execFile:()=>Crr,execFileSync:()=>krr,execSync:()=>Srr,existsSync:()=>Vtr,extname:()=>Mtr,fileURLToPath:()=>onr,finished:()=>Htr,format:()=>tnr,freemem:()=>Mrr,fstatSync:()=>trr,get:()=>Frr,gunzip:()=>Vrr,gunzipSync:()=>qrr,gzip:()=>Hrr,gzipSync:()=>Grr,hasSubscribers:()=>bnr,homedir:()=>Arr,hostname:()=>Rrr,inflateSync:()=>zrr,inherits:()=>inr,inspect:()=>eA,isAbsolute:()=>Otr,isBuiltin:()=>Qrr,isDeepStrictEqual:()=>dnr,isIP:()=>Nnr,isIPv4:()=>Onr,isIPv6:()=>Dnr,isMainThread:()=>Cnr,join:()=>Atr,lookup:()=>hnr,mkdir:()=>mrr,mkdirSync:()=>rrr,monitorEventLoopDelay:()=>vnr,normalize:()=>$tr,ok:()=>Jrr,open:()=>wrr,openSync:()=>Qtr,parentPort:()=>knr,parse:()=>enr,pathToFileURL:()=>snr,performance:()=>gnr,pipeline:()=>Gtr,platform:()=>xrr,posix:()=>Ltr,promises:()=>wtr,promisify:()=>anr,randomBytes:()=>Ttr,randomUUID:()=>Etr,readFile:()=>drr,readFileSync:()=>Wtr,readdir:()=>frr,readdirSync:()=>orr,realpath:()=>brr,realpathSync:()=>Ztr,relative:()=>Dtr,release:()=>Lrr,rename:()=>vrr,renameSync:()=>irr,request:()=>$rr,resolve:()=>Itr,rm:()=>_rr,rmSync:()=>lrr,rmdirSync:()=>arr,sep:()=>Ntr,serialize:()=>Tnr,setInterval:()=>znr,setTimeout:()=>Unr,spawn:()=>Trr,stat:()=>hrr,statSync:()=>nrr,strict:()=>Yrr,tmpdir:()=>Irr,toUSVString:()=>pnr,totalmem:()=>Drr,type:()=>Orr,types:()=>mnr,unlink:()=>grr,unlinkSync:()=>srr,webcrypto:()=>Str,workerData:()=>xnr,writeFile:()=>prr,writeFileSync:()=>Ktr});var Fo,Zn,_tr,wtr,rae,btr,Ttr,Etr,Str,Ctr,ktr,xtr,Atr,Itr,Rtr,Ptr,Mtr,Dtr,Otr,Ntr,Ltr,$tr,Ftr,Utr,nae,oae,Btr,ztr,jtr,qtr,Gtr,Htr,Vtr,Wtr,Ktr,Jtr,Ytr,Ztr,Xtr,Qtr,err,trr,rrr,nrr,orr,srr,irr,arr,lrr,crr,urr,drr,prr,mrr,hrr,frr,grr,yrr,vrr,_rr,wrr,brr,Trr,Err,Srr,Crr,krr,xrr,Arr,Irr,Rrr,Prr,Mrr,Drr,Orr,Nrr,Lrr,$rr,Frr,Urr,Brr,zrr,jrr,qrr,Grr,Hrr,Vrr,Wrr,Krr,Jrr,Yrr,Zrr,Xrr,Qrr,enr,tnr,rnr,nnr,onr,snr,inr,anr,sae,lnr,eA,cnr,unr,dnr,pnr,mnr,iae,tA,hnr,fnr,gnr,ynr,vnr,_nr,wnr,bnr,Tnr,Enr,Snr,Cnr,knr,xnr,Anr,Inr,Rnr,Pnr,Mnr,Dnr,Onr,Nnr,Lnr,$nr,Fnr,aae,Unr,Bnr,znr,jnr,qnr,UQr=S({"node-stub:node:sqlite"(){Fo=()=>{},Zn=async()=>{},_tr={},wtr={readFile:Zn,writeFile:Zn,mkdir:Zn,stat:Zn,readdir:Zn,unlink:Zn,access:Zn,rm:Zn,rename:Zn},rae=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new tA().encode(r):r),this},digest(r){let n=0;for(const s of t)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},btr=(e,t)=>rae(e),Ttr=e=>new Uint8Array(e||32),Etr=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),Str=globalThis.crypto,Ctr=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},ktr=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},xtr=()=>({listen:Fo,close:Fo,on:Fo}),Atr=(...e)=>e.join("/"),Itr=(...e)=>e.join("/"),Rtr=e=>e||"",Ptr=e=>e?.split?.("/")?.pop?.()||"",Mtr=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},Dtr=(e,t)=>t||"",Otr=()=>!1,Ntr="/",Ltr={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},$tr=e=>e,Ftr=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},Utr=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},nae=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},oae=class{write(){return!0}end(){}on(){return this}destroy(){}},Btr=class{push(){}on(){return this}},ztr=class{on(){return this}},jtr=class{pipe(){return this}on(){return this}},qtr=globalThis.ReadableStream||class{},Gtr=Fo,Htr=Fo,Vtr=()=>!1,Wtr=()=>"",Ktr=Fo,Jtr=Fo,Ytr=Zn,Ztr=e=>e,Xtr=Fo,Qtr=()=>0,err=Fo,trr=()=>({}),rrr=Fo,nrr=()=>({}),orr=()=>[],srr=Fo,irr=Fo,arr=Fo,lrr=Fo,crr=()=>new oae,urr=()=>new nae,drr=Zn,prr=Zn,mrr=Zn,hrr=Zn,frr=Zn,grr=Zn,yrr=Zn,vrr=Zn,_rr=Zn,wrr=async()=>({stat:Zn,readFile:Zn,close:Zn,read:Zn,write:Zn}),brr=async e=>e,Trr=()=>({on:Fo,stdout:{on:Fo},stderr:{on:Fo},kill:Fo}),Err=(e,t)=>t?.(null,"",""),Srr=()=>"",Crr=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},krr=()=>"",xrr="browser",Arr=()=>"/",Irr=()=>"/tmp",Rrr=()=>"browser",Prr=()=>[{}],Mrr=()=>0,Drr=()=>0,Orr=()=>"Browser",Nrr=()=>"wasm",Lrr=()=>"0",$rr=()=>({}),Frr=()=>({}),Urr=()=>({}),Brr=()=>({}),zrr=()=>new Uint8Array,jrr=()=>new Uint8Array,qrr=()=>new Uint8Array,Grr=()=>new Uint8Array,Hrr=(e,t)=>t?.(null,e),Vrr=(e,t)=>t?.(null,e),Wrr=()=>({}),Krr=()=>({}),Jrr=Fo,Yrr={},Zrr=()=>()=>({}),Xrr=[],Qrr=()=>!1,enr=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),tnr=()=>"",rnr=globalThis.URL,nnr=globalThis.URLSearchParams,onr=e=>typeof e=="string"?e.replace("file://",""):e,snr=e=>new globalThis.URL("file://"+e),inr=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},anr=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),sae=e=>{const t=(...r)=>{};return t.enabled=!1,t},lnr=sae,eA=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},eA.custom=Symbol.for("nodejs.util.inspect.custom"),eA.colors={},eA.styles={},cnr=e=>e,unr=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},dnr=(e,t)=>JSON.stringify(e)===JSON.stringify(t),pnr=e=>String(e),mnr={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},iae=globalThis.TextDecoder,tA=globalThis.TextEncoder,hnr=(e,t)=>t?.(null,"127.0.0.1",4),fnr=class{},gnr=globalThis.performance||{now:()=>Date.now()},ynr=class{observe(){}disconnect(){}},vnr=()=>({enable:Fo,disable:Fo,percentile:()=>0}),_nr=()=>({}),wnr=class{},bnr=()=>!1,Tnr=()=>new Uint8Array,Enr=Fo,Snr=class{},Cnr=!0,knr=null,xnr=null,Anr=()=>({}),Inr=class{},Rnr=class{},Pnr=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new tA().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new tA().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new iae().decode(this)}},Mnr={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Dnr=()=>!1,Onr=()=>!1,Nnr=()=>0,Lnr=class{},$nr=class{},Fnr=async()=>new ArrayBuffer(0),aae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Unr=(...e)=>aae(globalThis.setTimeout(...e)),Bnr=globalThis.clearTimeout,znr=(...e)=>aae(globalThis.setInterval(...e)),jnr=globalThis.clearInterval,qnr=class{constructor(e){this.type=e}toString(){return this.type}}}}),Gnr={};he(Gnr,{createOpenCodeReader:()=>zQr});function Hnr(){return Cr(Uu(),".local","share","opencode","opencode.db")}function BQr(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function _2(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function zQr(){return{descriptor:{id:wh,displayName:"OpenCode",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},detect:async()=>{try{return(await Yu(Hnr())).isFile()}catch{return!1}},scan:async e=>{const t=BQr(),r=[],n=new Set,o=Hnr();let s;try{const l=await Promise.resolve().then(()=>(UQr(),vtr));typeof l=="object"&&l!==null&&"DatabaseSync"in l&&typeof l.DatabaseSync=="function"&&(s=l.DatabaseSync)}catch(l){return r.push({cliId:wh,filePath:o,message:`node:sqlite unavailable on this runtime: ${l instanceof Error?l.message:String(l)}`}),{cliId:wh,totals:t,filesScanned:0,errors:r}}if(!s)return r.push({cliId:wh,filePath:o,message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:wh,totals:t,filesScanned:0,errors:r};const i=Qie(e?.sinceDays)??0;let a;try{a=new s(o,{readOnly:!0});const l=a.prepare("SELECT data FROM message WHERE time_created >= ?").all(i);for(const c of l){if(typeof c.data!="string")continue;let u;try{u=JSON.parse(c.data)}catch{continue}const d=u,m=d.tokens;if(!m||d.role!=="assistant")continue;const h=_2(m.input),g=_2(m.output),y=_2(m.cache?.read),v=_2(m.cache?.write);h===0&&g===0&&y===0&&v===0||(t.requests+=1,t.inputTokens+=h,t.outputTokens+=g,t.cacheReadTokens+=y,t.cacheCreationTokens+=v,d.modelID&&n.add(d.modelID))}}catch(l){r.push({cliId:wh,filePath:o,message:l instanceof Error?l.message:String(l)})}finally{try{a?.close()}catch{}}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:wh,totals:t,filesScanned:t.requests>0||r.length===0?1:0,errors:r}}}}var wh,jQr=S({"src/lib/localUsage/openCodeReader.ts"(){"use strict";ya(),ic(),Lr(),eae(),wh="opencode"}});Ul(),aa(),By(),gn(),Lr(),Ft(),q(),yt();var{readFile:lae,writeFile:Vnr,readdir:qQr,mkdir:GQr,unlink:HQr,access:VQr}=Ci,WQr=class{configPath=".neurolink.config";backupDir=".neurolink.backups";config=null;configCache=new Map;async loadConfig(){return this.config||(this.config=await this.readConfigFile()),this.config}async updateConfig(e,t={}){const{createBackup:r=!0,validate:n=!0,merge:o=!0,reason:s="update",silent:i=!1}=t;r&&(await this.createBackup(s),i||f.info("\u{1F4BE} Backup created before config update"));const a=await this.loadConfig();if(this.config=o?{...a,...e,lastUpdated:Date.now()}:{...e,lastUpdated:Date.now()},n){const l=await this.validateConfig(this.config);if(!l.valid)throw new Error(`Config validation failed: ${l.errors.join(", ")}`)}try{await this.persistConfig(this.config),i||f.info("\u2705 Configuration updated successfully")}catch(l){throw r&&(await this.restoreLatestBackup(),i||f.info("\u{1F504} Auto-restored from backup due to error")),new Error(`Config update failed, restored from backup: ${l.message}`,{cause:l})}}async createBackup(e="manual"){await this.ensureBackupDirectory();const r=`neurolink-config-${new Date().toISOString().replace(/[:.]/g,"-")}.js`,n=Cr(this.backupDir,r),o=await this.loadConfig(),s=this.generateConfigHash(o),i={reason:e,timestamp:Date.now(),version:o.configVersion||"unknown",originalPath:this.configPath,hash:s,size:JSON.stringify(o).length,createdBy:"NeuroLinkConfigManager"},a=`// NeuroLink Config Backup - ${e}
|
|
2253
|
+
`).filter(i=>i.trim());let o=null,s=null;for(const i of n){const a=i.trim();/^\d+[.):]\s*/.test(a)||/^Q[.:]?\s*/i.test(a)?(o&&r.push({question:o,...t&&s?{answer:s}:{}}),o=a.replace(/^\d+[.):]\s*/,"").replace(/^Q[.:]?\s*/i,""),s=null):/^A[.:]?\s*/i.test(a)&&o?s=a.replace(/^A[.:]?\s*/i,""):o&&!s?o+=" "+a:s&&(s+=" "+a)}return o&&r.push({question:o,...t&&s?{answer:s}:{}}),r}async callLLM(e,t){return(await(await Ur.createProvider(t.provider||this.provider,t.modelName||this.modelName)).generate({prompt:e,maxTokens:t.maxTokens||500,temperature:t.temperature||.3}))?.content||""}}}}),UQt,Mie,zl,Mc=S({"src/lib/auth/providers/BaseAuthProvider.ts"(){"use strict";Ft(),vn(),q(),ta(),UQt=At,Mie=class{sessions=new Map;userSessions=new Map;async get(e){return this.sessions.get(e)??null}async save(e){this.sessions.set(e.id,e);const t=this.userSessions.get(e.user.id)??new Set;t.add(e.id),this.userSessions.set(e.user.id,t)}async delete(e){const t=this.sessions.get(e);if(t){this.sessions.delete(e);const r=this.userSessions.get(t.user.id);r&&(r.delete(e),r.size===0&&this.userSessions.delete(t.user.id))}}async deleteAllForUser(e){const t=this.userSessions.get(e);if(t){for(const r of t)this.sessions.delete(r);this.userSessions.delete(e)}}async getForUser(e){const t=this.userSessions.get(e);if(!t)return[];const r=Date.now(),n=[],o=[];for(const s of t){const i=this.sessions.get(s);if(i){if(i.expiresAt&&i.expiresAt.getTime()<r){o.push(s);continue}if(!i.isValid){o.push(s);continue}n.push(i)}}for(const s of o)this.sessions.delete(s),t.delete(s);return t.size===0&&this.userSessions.delete(e),n}async exists(e){return this.sessions.has(e)}async touch(e){const t=this.sessions.get(e);t&&(t.lastActivityAt=new Date,this.sessions.set(e,t))}async clear(){this.sessions.clear(),this.userSessions.clear()}get size(){return this.sessions.size}},zl=class{config;sessionStorage;sessionConfig;rbacConfig;emitter=new nn;constructor(e){const t={fromHeader:{name:"Authorization",scheme:"Bearer"}};this.config={required:!0,...e,tokenExtraction:{...t,...e.tokenExtraction}},this.sessionConfig={storage:"memory",duration:3600,autoRefresh:!0,refreshThreshold:300,allowMultipleSessions:!0,maxSessionsPerUser:10,prefix:"neurolink:session:",...e.session},this.rbacConfig={enabled:!0,defaultRoles:[],roleHierarchy:{},rolePermissions:{},superAdminRoles:["super_admin","root"],...e.rbac},this.sessionStorage=e.session?.customStorage??new Mie,f.debug("[BaseAuthProvider] Initialized")}async extractToken(e){const t=this.config.tokenExtraction;if(t?.fromHeader){const r=t.fromHeader.name.toLowerCase();let n;for(const[o,s]of Object.entries(e.headers))if(o.toLowerCase()===r&&typeof s=="string"){n=s;break}if(typeof n=="string")if(t.fromHeader.scheme){const o=`${t.fromHeader.scheme} `;if(n.startsWith(o))return n.slice(o.length)}else return n}if(t?.fromCookie&&e.cookies){const r=e.cookies[t.fromCookie.name];if(r)return r}if(t?.fromQuery&&e.path)try{const n=new URL(e.path,"http://localhost").searchParams.get(t.fromQuery.name);if(n)return n}catch{}return t?.custom?await Promise.resolve(t.custom(e)):null}async createSession(e,t){const r=new Date,n=this.sessionConfig.duration??3600;if(!this.sessionConfig.allowMultipleSessions)await this.revokeAllSessions(e.id);else if(this.sessionConfig.maxSessionsPerUser){const s=await this.sessionStorage.getForUser(e.id);if(s.length>=this.sessionConfig.maxSessionsPerUser){const i=s.sort((a,l)=>a.createdAt.getTime()-l.createdAt.getTime())[0];i&&await this.sessionStorage.delete(i.id)}}const o={id:st(),user:e,accessToken:st(),isValid:!0,expiresAt:new Date(r.getTime()+n*1e3),createdAt:r,lastActivityAt:r,ipAddress:t?.ip??t?.ipAddress,userAgent:t?.userAgent};return await this.sessionStorage.save(o),f.debug(`[BaseAuthProvider] Created session ${o.id} for user ${e.id}`),o}async validateSession(e){const t=await this.sessionStorage.get(e);if(!t)return{valid:!1,error:"Session not found",errorCode:"AUTH-010"};if(t.expiresAt&&t.expiresAt.getTime()<Date.now())return await this.sessionStorage.delete(e),{valid:!1,error:"Session expired",errorCode:"AUTH-011"};if(!t.isValid)return{valid:!1,error:"Session revoked",errorCode:"AUTH-012"};let r=!1;if(this.sessionConfig.autoRefresh&&this.sessionConfig.refreshThreshold&&t.expiresAt&&t.expiresAt.getTime()-Date.now()<this.sessionConfig.refreshThreshold*1e3){const n=await this.refreshSession(e);return r=!0,{valid:!0,session:n??void 0,refreshed:r}}return await this.sessionStorage.touch(e),{valid:!0,session:t,refreshed:r}}async refreshSession(e){const t=await this.sessionStorage.get(e);if(!t)throw At.create("SESSION_NOT_FOUND",`Session not found: ${e}`,{details:{sessionId:e}});if(!t.isValid)throw At.create("SESSION_REVOKED",`Cannot refresh revoked session: ${e}`,{details:{sessionId:e}});if(t.expiresAt&&t.expiresAt.getTime()<Date.now())throw await this.sessionStorage.delete(e),At.create("SESSION_EXPIRED",`Cannot refresh expired session: ${e}`,{details:{sessionId:e}});const r=this.sessionConfig.duration??3600;return t.expiresAt=new Date(Date.now()+r*1e3),t.lastActivityAt=new Date,await this.sessionStorage.save(t),f.debug(`[BaseAuthProvider] Refreshed session ${e}`),t}async revokeSession(e){const t=await this.sessionStorage.get(e);t&&(t.isValid=!1,await this.sessionStorage.save(t),f.debug(`[BaseAuthProvider] Revoked session ${e}`))}async revokeAllSessions(e){await this.sessionStorage.deleteAllForUser(e),f.debug(`[BaseAuthProvider] Revoked all sessions for user ${e}`)}async authorize(e,t){if(!this.rbacConfig.enabled)return{authorized:!0,user:e};if(this.isSuperAdmin(e))return{authorized:!0,user:e};const r={authorized:!0,user:e,requiredRoles:t.roles,requiredPermissions:t.permissions,missingRoles:[],missingPermissions:[]};if(t.roles&&t.roles.length>0){const n=this.getEffectiveRoles(e),o=t.roles.filter(s=>!n.has(s));t.requireAllRoles?o.length>0&&(r.authorized=!1,r.missingRoles=o,r.reason=`Missing required roles: ${o.join(", ")}`):t.roles.some(i=>n.has(i))||(r.authorized=!1,r.missingRoles=t.roles,r.reason=`Missing any of required roles: ${t.roles.join(", ")}`)}if(t.permissions&&t.permissions.length>0){const n=this.getEffectivePermissions(e),o=t.permissions.filter(s=>!this.hasPermission(n,s));o.length>0&&(r.authorized=!1,r.missingPermissions=o,r.reason=r.reason?`${r.reason}; Missing permissions: ${o.join(", ")}`:`Missing required permissions: ${o.join(", ")}`)}return r}isSuperAdmin(e){const t=this.rbacConfig.superAdminRoles??[];return e.roles.some(r=>t.includes(r))}getEffectiveRoles(e){const t=new Set(e.roles),r=this.rbacConfig.roleHierarchy??{};let n=!0;for(;n;){n=!1;for(const o of t){const s=r[o]??[];for(const i of s)t.has(i)||(t.add(i),n=!0)}}return t}getEffectivePermissions(e){const t=new Set(e.permissions),r=this.rbacConfig.rolePermissions??{},n=this.getEffectiveRoles(e);for(const o of n){const s=r[o]??[];for(const i of s)t.add(i)}return t}hasPermission(e,t){if(e.has(t)||e.has("*"))return!0;const r=t.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(e.has(o))return!0}return!1}parseJWT(e){try{const t=e.split(".");if(t.length!==3)return null;const r=t[1],n=Buffer.from(r,"base64url").toString("utf-8");return JSON.parse(n)}catch{return null}}isTokenExpired(e,t=0){if(!e.exp)return!1;const r=Math.floor(Date.now()/1e3);return e.exp+t<r}isTokenNotYetValid(e,t=0){if(!e.nbf)return!1;const r=Math.floor(Date.now()/1e3);return e.nbf-t>r}extractUserFromClaims(e,t){const r=t?.rolesClaimKey??"roles",n=t?.permissionsClaimKey??"permissions",o=t?.idClaimKey??"sub",s=Array.isArray(e[r])?e[r]:this.rbacConfig.defaultRoles??[],i=Array.isArray(e[n])?e[n]:[];return{id:e[o]??"",email:e.email,name:e.name,picture:e.picture,roles:s,permissions:i,emailVerified:e.email_verified,providerData:e}}async getUser(e){return f.debug(`[BaseAuthProvider] getUser not implemented for ${this.type}`),null}async updateUserRoles(e,t){throw At.create("PROVIDER_ERROR",`updateUserRoles not supported by ${this.type} provider`)}async updateUserPermissions(e,t){throw At.create("PROVIDER_ERROR",`updateUserPermissions not supported by ${this.type} provider`)}async dispose(){await this.sessionStorage.clear(),f.debug(`[BaseAuthProvider] Disposed ${this.type} provider`)}async authorizeUser(e,t){return this.authorize(e,{permissions:[t]})}async authorizeRoles(e,t){return this.authorize(e,{roles:t})}async authorizePermissions(e,t){return this.authorize(e,{permissions:t})}async getSession(e){return this.sessionStorage.get(e)}async destroySession(e){await this.revokeSession(e)}async getUserSessions(e){return this.sessionStorage.getForUser(e)}async destroyAllUserSessions(e){await this.revokeAllSessions(e)}async authenticateRequest(e){const t=await this.extractToken(e);if(!t)return this.config.required&&this.emitter.emit("auth:unauthorized",e,"No token provided"),null;const r=await this.authenticateToken(t,e);if(!r.valid||!r.user)return this.emitter.emit("auth:unauthorized",e,r.error??"Invalid token"),null;const s=(await this.getUserSessions(r.user.id)).find(i=>i.isValid&&(!i.expiresAt||i.expiresAt.getTime()>Date.now()))??await this.createSession(r.user,e);return{...e,user:r.user,session:s,request:e,authenticatedAt:new Date,provider:this.type}}async healthCheck(){return{healthy:!0,providerConnected:!0,sessionStorageHealthy:!0}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}emit(e,...t){this.emitter.emit(e,...t)}}}});function BQt(...e){const t=e.reduce((o,{length:s})=>o+s,0),r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function Ow(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}var Vx,Nw,OXr,Wx=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js"(){Vx=new TextEncoder,Nw=new TextDecoder,OXr=2**32}});function NXr(e){if(Uint8Array.prototype.toBase64)return e.toBase64();const t=32768,r=[];for(let n=0;n<e.length;n+=t)r.push(String.fromCharCode.apply(null,e.subarray(n,n+t)));return btoa(r.join(""))}function zQt(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}var jQt=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js"(){}});function i2(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:Nw.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=Nw.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return zQt(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Die(e){let t=e;return typeof t=="string"&&(t=Vx.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):NXr(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Kx=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js"(){Wx(),jQt()}});function LXr(e){return parseInt(e.name.slice(4),10)}function Oie(e,t){if(LXr(e.hash)!==t)throw Dp(`SHA-${t}`,"algorithm.hash")}function $Xr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function FXr(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function UXr(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!yy(e.algorithm,"HMAC"))throw Dp("HMAC");Oie(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!yy(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Dp("RSASSA-PKCS1-v1_5");Oie(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!yy(e.algorithm,"RSA-PSS"))throw Dp("RSA-PSS");Oie(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!yy(e.algorithm,"Ed25519"))throw Dp("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!yy(e.algorithm,t))throw Dp(t);break}case"ES256":case"ES384":case"ES512":{if(!yy(e.algorithm,"ECDSA"))throw Dp("ECDSA");const n=$Xr(t);if(e.algorithm.namedCurve!==n)throw Dp(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}FXr(e,r)}var Dp,yy,BXr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js"(){Dp=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),yy=(e,t)=>e.name===t}});function qQt(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}var GQt,Nie,HQt=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js"(){GQt=(e,...t)=>qQt("Key must be ",e,...t),Nie=(e,t,...r)=>qQt(`Key for the ${e} algorithm must be `,t,...r)}}),al,ku,Lie,VQt,jl,$o,a2,$ie,Fie,WQt,KQt,JQt,ql=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js"(){al=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},ku=class extends al{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}},Lie=class extends al{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}},VQt=class extends al{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},jl=class extends al{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},$o=class extends al{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},a2=class extends al{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},$ie=class extends al{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Fie=class extends al{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",t){super(e,t)}},WQt=class extends al{[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",t){super(e,t)}},KQt=class extends al{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}},JQt=class extends al{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}}}),Uie,Bie,zie,YQt=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js"(){Uie=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Bie=e=>e?.[Symbol.toStringTag]==="KeyObject",zie=e=>Uie(e)||Bie(e)}});function ZQt(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function XQt(e,t,r){try{return i2(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var QQt=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js"(){Kx()}});function Op(e){if(!ter(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 eer(...e){const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(const s of o){if(r.has(s))return!1;r.add(s)}}return!0}var ter,l2,rer,ner,oer,Np=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js"(){ter=e=>typeof e=="object"&&e!==null,l2=e=>Op(e)&&typeof e.kty=="string",rer=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),ner=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,oer=e=>e.kty==="oct"&&typeof e.k=="string"}});function ser(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 ier(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 jl(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function aer(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(GQt(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return UXr(t,e,r),t}async function zXr(e,t,r){const n=await aer(e,t,"sign");ser(e,n);const o=await crypto.subtle.sign(ier(e,n.algorithm),n,r);return new Uint8Array(o)}async function jXr(e,t,r,n){const o=await aer(e,t,"verify");ser(e,o);const s=ier(e,o.algorithm);try{return await crypto.subtle.verify(s,o,r,n)}catch{return!1}}var ler=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js"(){ql(),BXr(),HQt()}});function qXr(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 jl(Jx)}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 jl(Jx)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},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 jl(Jx)}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 jl(Jx)}break}default:throw new jl('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function c2(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=qXr(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)}var Jx,cer=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js"(){ql(),Jx='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'}});async function uer(e,t){if(e instanceof Uint8Array||Uie(e))return e;if(Bie(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return der(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return jie(e,r,t)}if(l2(e))return e.k?i2(e.k):jie(e,e,t,!0);throw new Error("unreachable")}var vy,Lw,jie,der,per=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js"(){Np(),Kx(),cer(),YQt(),vy="given KeyObject instance cannot be used for this algorithm",jie=async(e,t,r,n=!1)=>{Lw||=new WeakMap;let o=Lw.get(e);if(o?.[r])return o[r];const s=await c2({...t,alg:r});return n&&Object.freeze(e),o?o[r]=s:Lw.set(e,{[r]:s}),s},der=(e,t)=>{Lw||=new WeakMap;let r=Lw.get(e);if(r?.[t])return r[t];const n=e.type==="public",o=!!n;let s;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(vy)}s=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(vy);s=e.toCryptoKey(e.asymmetricKeyType,o,[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(vy);s=e.toCryptoKey(e.asymmetricKeyType,o,[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(vy)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:i},o,n?["encrypt"]:["decrypt"]);s=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){const a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(vy);const l={ES256:"P-256",ES384:"P-384",ES512:"P-521"};l[t]&&a===l[t]&&(s=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(s=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!s)throw new TypeError(vy);return r?r[t]=s:Lw.set(e,{[t]:s}),s}}});function GXr(e){Zx(e,48,"Invalid SPKI structure"),Yx(e),Zx(e,48,"Expected algorithm identifier");const t=Yx(e);return{algIdStart:e.pos,algIdLength:t}}var u2,mer,Yx,Zx,qie,her,fer,ger,yer,ver,HXr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/asn1.js"(){jQt(),ql(),u2=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},mer=e=>({data:e,pos:0}),Yx=e=>{const t=e.data[e.pos++];if(t&128){const r=t&127;let n=0;for(let o=0;o<r;o++)n=n<<8|e.data[e.pos++];return n}return t},Zx=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},qie=(e,t)=>{const r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},her=e=>{Zx(e,6,"Expected algorithm OID");const t=Yx(e);return qie(e,t)},fer=e=>{const t=her(e);if(u2(t,[43,101,110]))return"X25519";if(!u2(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");Zx(e,6,"Expected curve OID");const r=Yx(e),n=qie(e,r);for(const{name:o,oid:s}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(u2(n,s))return o;throw new Error("Unsupported named curve")},ger=async(e,t,r,n)=>{let o,s;const i=e==="spki",a=()=>i?["verify"]:["sign"],l=()=>i?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},s=l();break;case"ES256":case"ES384":case"ES512":{o={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},s=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{const c=n.getNamedCurve(t);o=c==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:c}}catch{throw new jl("Invalid or unsupported key format")}s=i?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":o={name:"Ed25519"},s=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":o={name:r},s=a();break;default:throw new jl('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,o,n?.extractable??!!i,s)},yer=(e,t)=>zQt(e.replace(t,"")),ver=(e,t,r)=>{const n=yer(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);let o=r;return t?.startsWith?.("ECDH-ES")&&(o||={},o.getNamedCurve=s=>{const i=mer(s);return GXr(i),fer(i)}),ger("spki",n,t,o)}}});async function VXr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return ver(e,t,r)}async function Gie(e,t,r){if(!Op(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return i2(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new jl('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return c2({...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 c2({...e,ext:n})}case"EC":case"OKP":return c2({...e,alg:t,ext:n});default:throw new jl('Unsupported "kty" (Key Type) Parameter value')}}var _er=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js"(){Kx(),HXr(),cer(),ql(),Np()}});function wer(e,t,r,n,o){if(o.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 s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(const i of n.crit){if(!s.has(i))throw new jl(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(s.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var ber=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js"(){ql()}});function WXr(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var KXr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js"(){}});function Ter(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Eer(e,t,r);break;default:Ser(e,t,r)}}var _y,d2,Eer,Ser,Cer=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js"(){HQt(),YQt(),Np(),_y=e=>e?.[Symbol.toStringTag],d2=(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==="sign"||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=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):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},Eer=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(l2(t)){if(oer(t)&&d2(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(!zie(t))throw new TypeError(Nie(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${_y(t)} instances for symmetric algorithms must be of type "secret"`)}},Ser=(e,t,r)=>{if(l2(t))switch(r){case"decrypt":case"sign":if(rer(t)&&d2(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(ner(t)&&d2(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!zie(t))throw new TypeError(Nie(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${_y(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${_y(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${_y(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${_y(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${_y(t)} instances for asymmetric algorithm encryption must be of type "public"`)}}}});async function JXr(e,t,r){if(!Op(e))throw new $o("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new $o('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new $o("JWS Protected Header incorrect type");if(e.payload===void 0)throw new $o("JWS Payload missing");if(typeof e.signature!="string")throw new $o("JWS Signature missing or incorrect type");if(e.header!==void 0&&!Op(e.header))throw new $o("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const v=i2(e.protected);n=JSON.parse(Nw.decode(v))}catch{throw new $o("JWS Protected Header is invalid")}if(!eer(n,e.header))throw new $o("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header},s=wer($o,new Map([["b64",!0]]),r?.crit,n,o);let i=!0;if(s.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new $o('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if(typeof a!="string"||!a)throw new $o('JWS "alg" (Algorithm) Header Parameter missing or invalid');const l=r&&WXr("algorithms",r.algorithms);if(l&&!l.has(a))throw new VQt('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof e.payload!="string")throw new $o("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new $o("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof t=="function"&&(t=await t(n,e),c=!0),Ter(a,t,"verify");const u=BQt(e.protected!==void 0?Ow(e.protected):new Uint8Array,Ow("."),typeof e.payload=="string"?i?Ow(e.payload):Vx.encode(e.payload):e.payload),d=XQt(e.signature,"signature",$o),m=await uer(t,a);if(!await jXr(a,m,d,u))throw new JQt;let g;i?g=XQt(e.payload,"payload",$o):typeof e.payload=="string"?g=Vx.encode(e.payload):g=e.payload;const y={payload:g};return e.protected!==void 0&&(y.protectedHeader=n),e.header!==void 0&&(y.unprotectedHeader=e.header),c?{...y,key:m}:y}var YXr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js"(){Kx(),ler(),ql(),Wx(),QQt(),Np(),Np(),Cer(),ber(),KXr(),per()}});async function ZXr(e,t,r){if(e instanceof Uint8Array&&(e=Nw.decode(e)),typeof e!="string")throw new $o("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:s,length:i}=e.split(".");if(i!==3)throw new $o("Invalid Compact JWS");const a=await JXr({payload:o,protected:n,signature:s},t,r),l={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...l,key:a.key}:l}var XXr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js"(){YXr(),ql(),Wx()}});function Xx(e){const t=Aer.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 o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*Hie);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*Vie);break;case"day":case"days":case"d":o=Math.round(r*p2);break;case"week":case"weeks":case"w":o=Math.round(r*ker);break;default:o=Math.round(r*xer);break}return t[1]==="-"||t[4]==="ago"?-o:o}function wy(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function QXr(e,t,r={}){let n;try{n=JSON.parse(Nw.decode(t))}catch{}if(!Op(n))throw new a2("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&(typeof e.typ!="string"||Wie(e.typ)!==Wie(o)))throw new ku('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:s=[],issuer:i,subject:a,audience:l,maxTokenAge:c}=r,u=[...s];c!==void 0&&u.push("iat"),l!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),i!==void 0&&u.push("iss");for(const g of new Set(u.reverse()))if(!(g in n))throw new ku(`missing required "${g}" claim`,n,g,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new ku('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new ku('unexpected "sub" claim value',n,"sub","check_failed");if(l&&!Ier(n.aud,typeof l=="string"?[l]:l))throw new ku('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=Xx(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,h=Lp(m||new Date);if((n.iat!==void 0||c)&&typeof n.iat!="number")throw new ku('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new ku('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>h+d)throw new ku('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new ku('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=h-d)throw new Lie('"exp" claim timestamp check failed',n,"exp","check_failed")}if(c){const g=h-n.iat,y=typeof c=="number"?c:Xx(c);if(g-d>y)throw new Lie('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(g<0-d)throw new ku('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var Lp,Hie,Vie,p2,ker,xer,Aer,Wie,Ier,Rer,Per=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js"(){ql(),Wx(),Np(),Lp=e=>Math.floor(e.getTime()/1e3),Hie=60,Vie=Hie*60,p2=Vie*24,ker=p2*7,xer=p2*365.25,Aer=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Wie=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,Ier=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,Rer=class{#e;constructor(e){if(!Op(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return Vx.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=wy("setNotBefore",e):e instanceof Date?this.#e.nbf=wy("setNotBefore",Lp(e)):this.#e.nbf=Lp(new Date)+Xx(e)}set exp(e){typeof e=="number"?this.#e.exp=wy("setExpirationTime",e):e instanceof Date?this.#e.exp=wy("setExpirationTime",Lp(e)):this.#e.exp=Lp(new Date)+Xx(e)}set iat(e){e===void 0?this.#e.iat=Lp(new Date):e instanceof Date?this.#e.iat=wy("setIssuedAt",Lp(e)):typeof e=="string"?this.#e.iat=wy("setIssuedAt",Lp(new Date)+Xx(e)):this.#e.iat=wy("setIssuedAt",e)}}}});async function xu(e,t,r){const n=await ZXr(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new a2("JWTs MUST NOT use unencoded payload");const s={payload:QXr(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...s,key:n.key}:s}var eQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js"(){XXr(),Per(),ql()}}),Mer,tQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js"(){Kx(),ler(),Np(),ql(),Wx(),Cer(),ber(),per(),QQt(),Mer=class{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return ZQt(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return ZQt(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,t){if(!this.#t&&!this.#r)throw new $o("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!eer(this.#t,this.#r))throw new $o("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this.#t,...this.#r},n=wer($o,new Map([["b64",!0]]),t?.crit,this.#t,r);let o=!0;if(n.has("b64")&&(o=this.#t.b64,typeof o!="boolean"))throw new $o('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if(typeof s!="string"||!s)throw new $o('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ter(s,e,"sign");let i,a;o?(i=Die(this.#e),a=Ow(i)):(a=this.#e,i="");let l,c;this.#t?(l=Die(JSON.stringify(this.#t)),c=Ow(l)):(l="",c=new Uint8Array);const u=BQt(c,Ow("."),a),d=await uer(e,s),m=await zXr(s,d,u),h={signature:Die(m),payload:i};return this.#r&&(h.header=this.#r),this.#t&&(h.protected=l),h}}}}),Der,rQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js"(){tQr(),Der=class{#e;constructor(e){this.#e=new Mer(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,t){const r=await this.#e.sign(e,t);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}}}),Oer,nQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js"(){rQr(),ql(),Per(),Oer=class{#e;#t;constructor(e={}){this.#t=new Rer(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,t){const r=new Der(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new a2("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}}});function oQr(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 jl('Unsupported "alg" value for a JSON Web Key Set')}}function sQr(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(iQr)}function iQr(e){return Op(e)}async function Ner(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){const o=await Gie({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new $ie("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function Ler(e){const t=new $er(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var $er,aQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js"(){_er(),ql(),Np(),$er=class{#e;#t=new WeakMap;constructor(e){if(!sQr(e))throw new $ie("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=oQr(r),s=this.#e.keys.filter(l=>{let c=o===l.kty;if(c&&typeof n=="string"&&(c=n===l.kid),c&&(typeof l.alg=="string"||o==="AKP")&&(c=r===l.alg),c&&typeof l.use=="string"&&(c=l.use==="sig"),c&&Array.isArray(l.key_ops)&&(c=l.key_ops.includes("verify")),c)switch(r){case"ES256":c=l.crv==="P-256";break;case"ES384":c=l.crv==="P-384";break;case"ES512":c=l.crv==="P-521";break;case"Ed25519":case"EdDSA":c=l.crv==="Ed25519";break}return c}),{0:i,length:a}=s;if(a===0)throw new Fie;if(a!==1){const l=new WQt,c=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(const u of s)try{yield await Ner(c,u,r)}catch{}},l}return Ner(this.#t,i,r)}}}});function lQr(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function cQr(e,t,r,n=fetch){const o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(s=>{throw s.name==="TimeoutError"?new KQt:s});if(o.status!==200)throw new al("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new al("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function uQr(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!Op(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,Op))}function Qx(e,t){const r=new Uer(e,t),n=async(o,s)=>r.getKey(o,s);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}var Kie,Fer,m2,Uer,dQr=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js"(){ql(),aQr(),Np(),(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Kie="jose/v6.2.2"),Fer=Symbol(),m2=Symbol(),Uer=class{#e;#t;#r;#n;#o;#s;#i;#c;#a;#l;constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration=="number"?t?.timeoutDuration:5e3,this.#r=typeof t?.cooldownDuration=="number"?t?.cooldownDuration:3e4,this.#n=typeof t?.cacheMaxAge=="number"?t?.cacheMaxAge:6e5,this.#i=new Headers(t?.headers),Kie&&!this.#i.has("User-Agent")&&this.#i.set("User-Agent",Kie),this.#i.has("accept")||(this.#i.set("accept","application/json"),this.#i.append("accept","application/jwk-set+json")),this.#c=t?.[Fer],t?.[m2]!==void 0&&(this.#l=t?.[m2],uQr(t?.[m2],this.#n)&&(this.#o=this.#l.uat,this.#a=Ler(this.#l.jwks)))}pendingFetch(){return!!this.#s}coolingDown(){return typeof this.#o=="number"?Date.now()<this.#o+this.#r:!1}fresh(){return typeof this.#o=="number"?Date.now()<this.#o+this.#n:!1}jwks(){return this.#a?.jwks()}async getKey(e,t){(!this.#a||!this.fresh())&&await this.reload();try{return await this.#a(e,t)}catch(r){if(r instanceof Fie&&this.coolingDown()===!1)return await this.reload(),this.#a(e,t);throw r}}async reload(){this.#s&&lQr()&&(this.#s=void 0),this.#s||=cQr(this.#e.href,this.#i,AbortSignal.timeout(this.#t),this.#c).then(e=>{this.#a=Ler(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#o=Date.now(),this.#s=void 0}).catch(e=>{throw this.#s=void 0,e}),await this.#s}}}}),vd=S({"node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js"(){eQr(),nQr(),dQr(),_er()}}),Ber={};he(Ber,{Auth0Provider:()=>zer});var zer,pQr=S({"src/lib/auth/providers/auth0.ts"(){"use strict";Mc(),ta(),q(),no(),vd(),zer=class extends zl{type="auth0";domain;clientId;audience;rolesNamespace;permissionsNamespace;jwks=null;constructor(e){if(super(e),!e.domain)throw At.create("CONFIGURATION_ERROR","Auth0 domain is required",{details:{missingFields:["domain"]}});if(!e.clientId)throw At.create("CONFIGURATION_ERROR","Auth0 clientId is required",{details:{missingFields:["clientId"]}});this.domain=e.domain,this.clientId=e.clientId,this.audience=e.audience,this.rolesNamespace=e.options?.rolesNamespace,this.permissionsNamespace=e.options?.permissionsNamespace}async initialize(){try{const e=new URL(`https://${this.domain}/.well-known/jwks.json`);this.jwks=Qx(e),f.debug(`Auth0 provider initialized for domain: ${this.domain}`)}catch(e){throw At.create("PROVIDER_INIT_FAILED","Failed to initialize Auth0 JWKS",{cause:e instanceof Error?e:new Error(String(e))})}}async authenticateToken(e,t){this.jwks||await this.initialize();try{if(!this.jwks)return{valid:!1,error:"Auth0 JWKS not initialized"};const{payload:r}=await xu(e,this.jwks,{issuer:`https://${this.domain}/`,audience:this.audience}),n=r;if(this.audience){const c=n.aud;if(!(Array.isArray(c)?c:[c]).includes(this.audience))return{valid:!1,error:`Token audience does not match expected audience: ${this.audience}`}}if(this.clientId){const c=n.aud,u=r.azp,d=Array.isArray(c)?c:[c];if(u){if(u!==this.clientId)return{valid:!1,error:`Token azp claim "${u}" does not match clientId "${this.clientId}"`}}else if(!d.includes(this.clientId))return{valid:!1,error:`Token audience does not include clientId "${this.clientId}"`}}const o=this.rolesNamespace??"roles",s=this.permissionsNamespace??"permissions",i=r[o]||n.roles||[],a=r[s]||n.permissions||[],l={id:n.sub,email:n.email,name:n.name,picture:n.picture,emailVerified:n.email_verified,roles:i,permissions:a,metadata:{iss:n.iss,aud:n.aud}};return{valid:!0,payload:r,user:l,expiresAt:new Date(n.exp*1e3),tokenType:"jwt"}}catch(r){const n=r instanceof Error?r.message:String(r);return f.warn("Auth0 token validation failed:",n),{valid:!1,error:n}}}async getUser(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return f.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user profile"),null;try{const n=await Bt()(`https://${this.domain}/api/v2/users/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok){if(n.status===404)return null;throw At.create("PROVIDER_ERROR",`Auth0 API returned ${n.status}`,{details:{statusCode:n.status}})}const o=await n.json();return{id:o.user_id,email:o.email,name:o.name,picture:o.picture,emailVerified:o.email_verified,roles:o.app_metadata?.roles||[],permissions:o.app_metadata?.permissions||[],createdAt:o.created_at?new Date(o.created_at):void 0,lastLoginAt:o.last_login?new Date(o.last_login):void 0,metadata:o.user_metadata}}catch(r){throw f.error("Failed to fetch Auth0 user:",r),r}}async getUserByEmail(e){const t=process.env.AUTH0_MANAGEMENT_TOKEN;if(!t)return f.warn("AUTH0_MANAGEMENT_TOKEN not set, cannot fetch user by email"),null;try{const n=await Bt()(`https://${this.domain}/api/v2/users-by-email?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok)throw At.create("PROVIDER_ERROR",`Auth0 API returned ${n.status}`,{details:{statusCode:n.status}});const o=await n.json();if(o.length===0)return null;const s=o[0];return{id:s.user_id,email:s.email,name:s.name,picture:s.picture,emailVerified:s.email_verified,roles:s.app_metadata?.roles||[],permissions:s.app_metadata?.permissions||[],createdAt:s.created_at?new Date(s.created_at):void 0,lastLoginAt:s.last_login?new Date(s.last_login):void 0,metadata:s.user_metadata}}catch(r){throw f.error("Failed to fetch Auth0 user by email:",r),r}}async healthCheck(){try{const t=await Bt()(`https://${this.domain}/.well-known/openid-configuration`);return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0,error:t.ok?void 0:`HTTP ${t.status}`}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),jer={};he(jer,{ClerkProvider:()=>qer});var qer,mQr=S({"src/lib/auth/providers/clerk.ts"(){"use strict";Mc(),ta(),q(),no(),vd(),qer=class extends zl{type="clerk";secretKey;jwtKey;publishableKey;jwks=null;localKey=null;constructor(e){if(super(e),!e.secretKey)throw At.create("CONFIGURATION_ERROR","Clerk secretKey is required",{details:{missingFields:["secretKey"]}});this.secretKey=e.secretKey,this.jwtKey=e.jwtKey,this.publishableKey=e.publishableKey}async initialize(){const e=new URL("https://api.clerk.com/v1/jwks");this.jwks=Qx(e),f.debug("Clerk provider initialized")}async authenticateToken(e,t){return e.includes(".")&&e.split(".").length===3?this.validateJWT(e):this.validateSessionToken(e)}async validateJWT(e){try{let t;if(this.jwtKey)this.localKey||(this.localKey=new TextEncoder().encode(this.jwtKey)),{payload:t}=await xu(e,this.localKey);else{if(this.jwks||await this.initialize(),!this.jwks)return{valid:!1,error:"Clerk JWKS not initialized"};({payload:t}=await xu(e,this.jwks))}if(this.publishableKey&&t.azp&&t.azp!==this.publishableKey)return{valid:!1,error:`Invalid authorized party: ${t.azp}. Expected: ${this.publishableKey}`};const r={id:t.sub,email:t.email,name:t.name,picture:t.picture,emailVerified:t.email_verified,roles:t["https://clerk.dev/roles"]||[],permissions:t["https://clerk.dev/permissions"]||[],organizationId:t.org_id,metadata:{azp:t.azp,sid:t.sid}};return{valid:!0,payload:t,user:r,expiresAt:t.exp?new Date(t.exp*1e3):void 0,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async validateSessionToken(e){try{const r=await Bt()("https://api.clerk.com/v1/sessions/verify",{method:"POST",headers:{Authorization:`Bearer ${this.secretKey}`,"Content-Type":"application/json"},body:JSON.stringify({token:e})});if(!r.ok)return{valid:!1,error:(await r.json()).errors?.[0]?.message||"Session validation failed"};const n=await r.json(),o=n.user,s=o?.email_addresses,i={id:n.user_id,email:s?.[0]?.email_address,name:o?.first_name?`${o.first_name} ${o.last_name||""}`.trim():void 0,picture:o?.image_url,roles:o?.public_metadata?.roles||[],permissions:o?.public_metadata?.permissions||[],organizationId:n.active_organization_id};return{valid:!0,payload:n,user:i,expiresAt:n.expire_at?new Date(n.expire_at):void 0,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async getUser(e){try{const r=await Bt()(`https://api.clerk.com/v1/users/${e}`,{headers:{Authorization:`Bearer ${this.secretKey}`}});if(!r.ok){if(r.status===404)return null;throw At.create("PROVIDER_ERROR",`Clerk API returned ${r.status}`,{details:{statusCode:r.status}})}const n=await r.json(),o=n.email_addresses;return{id:n.id,email:o?.[0]?.email_address,name:n.first_name?`${n.first_name} ${n.last_name||""}`.trim():void 0,picture:n.image_url,emailVerified:o?.[0]?.verification?.status==="verified",roles:n.public_metadata?.roles||[],permissions:n.public_metadata?.permissions||[],createdAt:n.created_at?new Date(n.created_at):void 0,lastLoginAt:n.last_sign_in_at?new Date(n.last_sign_in_at):void 0,metadata:n.private_metadata}}catch(t){if(f.error("Failed to fetch Clerk user:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async getUserByEmail(e){try{const r=await Bt()(`https://api.clerk.com/v1/users?email_address=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.secretKey}`}});if(!r.ok)throw At.create("PROVIDER_ERROR",`Clerk API returned ${r.status}`,{details:{statusCode:r.status}});const n=await r.json();if(n.length===0)return null;const o=n[0],s=o.email_addresses;return{id:o.id,email:s?.[0]?.email_address,name:o.first_name?`${o.first_name} ${o.last_name||""}`.trim():void 0,picture:o.image_url,emailVerified:s?.[0]?.verification?.status==="verified",roles:o.public_metadata?.roles||[],permissions:o.public_metadata?.permissions||[],createdAt:o.created_at?new Date(o.created_at):void 0,lastLoginAt:o.last_sign_in_at?new Date(o.last_sign_in_at):void 0,metadata:o.private_metadata}}catch(t){if(f.error("Failed to fetch Clerk user by email:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async healthCheck(){try{const t=await Bt()("https://api.clerk.com/v1/organizations?limit=1",{headers:{Authorization:`Bearer ${this.secretKey}`}});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Ger={};he(Ger,{FirebaseAuthProvider:()=>Her});var Her,hQr=S({"src/lib/auth/providers/firebase.ts"(){"use strict";Mc(),ta(),q(),no(),vd(),Her=class extends zl{type="firebase";projectId;apiKey;serviceAccount;jwks=null;constructor(e){if(super(e),!e.projectId)throw At.create("CONFIGURATION_ERROR","Firebase projectId is required",{details:{missingFields:["projectId"]}});this.projectId=e.projectId,this.apiKey=e.apiKey,this.serviceAccount=e.serviceAccount}async initialize(){const e=new URL("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com");this.jwks=Qx(e),f.debug(`Firebase provider initialized for project: ${this.projectId}`)}async authenticateToken(e,t){this.jwks||await this.initialize();try{const r=this.jwks;if(!r)throw At.create("PROVIDER_INIT_FAILED","Firebase JWKS was not initialized",{details:{provider:"firebase"}});const{payload:n}=await xu(e,r,{issuer:`https://securetoken.google.com/${this.projectId}`,audience:this.projectId}),o=this.payloadToUser(n);return{valid:!0,payload:n,user:o,expiresAt:n.exp?new Date(n.exp*1e3):void 0,tokenType:"jwt"}}catch(r){return this.apiKey?this.validateViaApi(e):{valid:!1,error:r instanceof Error?r.message:String(r)}}}async validateViaApi(e){try{const r=await Bt()(`https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({idToken:e}),signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:(await r.json()).error?.message||`Firebase API returned ${r.status}`};const o=(await r.json()).users||[];if(o.length===0)return{valid:!1,error:"User not found"};const s=o[0],i=this.firebaseUserToAuthUser(s);return{valid:!0,payload:s,user:i,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}payloadToUser(e){const t=e;return{id:e.sub,email:e.email,name:e.name,picture:e.picture,emailVerified:e.email_verified,roles:t.roles||[],permissions:t.permissions||[],metadata:{firebase:{sign_in_provider:e.firebase?.sign_in_provider||"unknown",identities:e.firebase?.identities}}}}firebaseUserToAuthUser(e){let t={};if(e.customAttributes)try{t=JSON.parse(e.customAttributes)}catch{f.warn("Failed to parse Firebase customAttributes, treating as empty")}return{id:e.localId,email:e.email,name:e.displayName,picture:e.photoUrl,emailVerified:e.emailVerified,roles:t.roles||[],permissions:t.permissions||[],createdAt:e.createdAt?new Date(parseInt(e.createdAt)):void 0,lastLoginAt:e.lastLoginAt?new Date(parseInt(e.lastLoginAt)):void 0,metadata:{providerUserInfo:e.providerUserInfo}}}async getUser(e){return this.apiKey?(f.warn("Direct user lookup by ID requires Firebase Admin SDK which is not supported in browser/edge environments"),null):(f.warn("Firebase API key required for user lookup"),null)}async healthCheck(){try{const t=await Bt()("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",{signal:AbortSignal.timeout(5e3)});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Ver={};he(Ver,{SupabaseAuthProvider:()=>Wer});var Wer,fQr=S({"src/lib/auth/providers/supabase.ts"(){"use strict";Mc(),ta(),q(),no(),vd(),Wer=class extends zl{type="supabase";supabaseUrl;anonKey;serviceRoleKey;jwtSecret;constructor(e){if(super(e),!e.url)throw At.create("CONFIGURATION_ERROR","Supabase URL is required",{details:{missingFields:["url"]}});if(!e.anonKey)throw At.create("CONFIGURATION_ERROR","Supabase anon key is required",{details:{missingFields:["anonKey"]}});this.supabaseUrl=e.url.replace(/\/$/,""),this.anonKey=e.anonKey,this.serviceRoleKey=e.serviceRoleKey,this.jwtSecret=e.jwtSecret}async authenticateToken(e,t){try{if(this.jwtSecret){const i=new TextEncoder().encode(this.jwtSecret),{payload:a}=await xu(e,i);if(!a.sub)return{valid:!1,error:"Token missing sub claim: cannot authenticate without a user identity"};const l=a.role;if(l&&l!=="authenticated")return{valid:!1,error:`Invalid token role: ${l}. Only "authenticated" role is accepted`};const c=this.payloadToUser(a);return{valid:!0,payload:a,user:c,expiresAt:a.exp?new Date(a.exp*1e3):void 0,tokenType:"jwt"}}const n=await Bt()(`${this.supabaseUrl}/auth/v1/user`,{headers:{Authorization:`Bearer ${e}`,apikey:this.anonKey}});if(!n.ok)return{valid:!1,error:`Token validation failed: HTTP ${n.status}`};const o=await n.json(),s=this.supabaseUserToAuthUser(o);return{valid:!0,payload:o,user:s,tokenType:"jwt"}}catch(r){return{valid:!1,error:r instanceof Error?r.message:String(r)}}}payloadToUser(e){const t=e.app_metadata,r=e.user_metadata,n=e.role;return{id:e.sub,email:e.email,name:r?.full_name||r?.name,picture:r?.avatar_url,emailVerified:e.email_confirmed||!1,roles:n?[n]:t?.roles||[],permissions:t?.permissions||[],metadata:r}}supabaseUserToAuthUser(e){const t=e.app_metadata,r=e.user_metadata;return{id:e.id,email:e.email,name:r?.full_name||r?.name,picture:r?.avatar_url,emailVerified:!!e.email_confirmed_at,roles:t?.roles||[],permissions:t?.permissions||[],createdAt:e.created_at?new Date(e.created_at):void 0,lastLoginAt:e.last_sign_in_at?new Date(e.last_sign_in_at):void 0,metadata:r}}async getUser(e){if(!this.serviceRoleKey)return f.warn("Service role key required for user lookup"),null;try{const r=await Bt()(`${this.supabaseUrl}/auth/v1/admin/users/${e}`,{headers:{Authorization:`Bearer ${this.serviceRoleKey}`,apikey:this.anonKey}});if(!r.ok){if(r.status===404)return null;throw At.create("PROVIDER_ERROR",`Supabase API returned ${r.status}`,{details:{statusCode:r.status}})}const n=await r.json();return this.supabaseUserToAuthUser(n)}catch(t){if(f.error("Failed to fetch Supabase user:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async getUserByEmail(e){if(!this.serviceRoleKey)return f.warn("Service role key required for user lookup by email"),null;try{const r=await Bt()(`${this.supabaseUrl}/auth/v1/admin/users?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.serviceRoleKey}`,apikey:this.anonKey}});if(!r.ok)throw At.create("PROVIDER_ERROR",`Supabase API returned ${r.status}`,{details:{statusCode:r.status}});const o=(await r.json()).users||[];return o.length===0?null:this.supabaseUserToAuthUser(o[0])}catch(t){if(f.error("Failed to fetch Supabase user by email:",t),t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")throw t;return null}}async healthCheck(){try{const t=await Bt()(`${this.supabaseUrl}/auth/v1/health`,{headers:{apikey:this.anonKey}});return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),Ker={};he(Ker,{CognitoProvider:()=>Jer});var Jie,Jer,gQr=S({"src/lib/auth/providers/CognitoProvider.ts"(){"use strict";vd(),q(),ta(),Mc(),Jie=new Map,Jer=class extends zl{type="cognito";cognitoConfig;jwksUri;jwksCacheDuration;expectedIssuer;constructor(e){if(super(e),e.type!=="cognito")throw At.create("CONFIGURATION_ERROR",`Invalid provider type: ${e.type}. Expected: cognito`);if(this.cognitoConfig=e,!this.cognitoConfig.userPoolId)throw At.create("CONFIGURATION_ERROR","Cognito userPoolId is required");if(!this.cognitoConfig.clientId)throw At.create("CONFIGURATION_ERROR","Cognito clientId is required");if(!this.cognitoConfig.region)throw At.create("CONFIGURATION_ERROR","Cognito region is required");this.expectedIssuer=`https://cognito-idp.${this.cognitoConfig.region}.amazonaws.com/${this.cognitoConfig.userPoolId}`,this.jwksUri=`${this.expectedIssuer}/.well-known/jwks.json`,this.jwksCacheDuration=e.tokenValidation?.jwksCacheDuration??6e5,f.debug(`[CognitoProvider] Initialized for user pool: ${this.cognitoConfig.userPoolId}`)}async authenticateToken(e){try{const t=this.parseJWT(e);if(!t)return{valid:!1,error:"Failed to decode token",errorCode:"AUTH-006"};if(t.iss!==this.expectedIssuer)return{valid:!1,error:`Invalid issuer: ${t.iss}. Expected: ${this.expectedIssuer}`,errorCode:"AUTH-001"};const r=t.token_use;if(r!=="id"&&r!=="access")return{valid:!1,error:`Invalid token_use: ${r}. Expected: id or access`,errorCode:"AUTH-001"};if(r==="id"){if(t.aud!==this.cognitoConfig.clientId)return{valid:!1,error:`Invalid audience: ${t.aud}. Expected: ${this.cognitoConfig.clientId}`,errorCode:"AUTH-001"}}else if(t.client_id!==this.cognitoConfig.clientId)return{valid:!1,error:`Invalid client_id: ${t.client_id}. Expected: ${this.cognitoConfig.clientId}`,errorCode:"AUTH-001"};const n=this.config.tokenValidation?.clockTolerance??30;if(this.isTokenExpired(t,n))return{valid:!1,error:"Token has expired",errorCode:"AUTH-002",expiresAt:t.exp?new Date(t.exp*1e3):void 0};if(this.config.tokenValidation?.validateSignature!==!1&&!await this.verifySignature(e))return{valid:!1,error:"Invalid token signature",errorCode:"AUTH-004"};const o=this.extractCognitoUser(t,r),s={};for(const[i,a]of Object.entries(t))a!==void 0&&(s[i]=a);return{valid:!0,user:o,claims:s,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return f.error("[CognitoProvider] Token validation error:",t),{valid:!1,error:t instanceof Error?t.message:"Token validation failed",errorCode:"AUTH-014"}}}async verifySignature(e){try{const t=e.split(".");if(t.length!==3)return!1;const r=JSON.parse(Buffer.from(t[0],"base64url").toString("utf-8")),n=r.kid;if(!n)return f.warn("[CognitoProvider] Token missing kid in header"),!1;const s=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!s)return f.warn(`[CognitoProvider] Key not found for kid: ${n}`),!1;const i=await Gie(s,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await xu(e,i,{clockTolerance:a}),!0}catch(t){return f.error("[CognitoProvider] Signature verification error:",t),!1}}async getJWKS(){const e=Jie.get(this.jwksUri);if(e&&e.expiresAt>Date.now())return e.jwks;try{const t=await fetch(this.jwksUri,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`JWKS fetch failed: ${t.status}`);const r=await t.json();return Jie.set(this.jwksUri,{jwks:r,expiresAt:Date.now()+this.jwksCacheDuration}),r}catch(t){throw At.create("JWKS_FETCH_FAILED",`Failed to fetch JWKS from ${this.jwksUri}: ${t instanceof Error?t.message:String(t)}`,{cause:t instanceof Error?t:void 0})}}extractCognitoUser(e,t){const r=e.sub??"",n=e.email??e["custom:email"],o=e.name??e["cognito:username"]??e.preferred_username,s=e.picture??e["custom:picture"];let i=[];const a=e["cognito:groups"];a&&Array.isArray(a)&&(i=a),i.length===0&&this.rbacConfig.defaultRoles&&(i=this.rbacConfig.defaultRoles);const l=[];if(this.cognitoConfig.customAttributes)for(const d of this.cognitoConfig.customAttributes){const m=e[`custom:${d}`];m&&(m.includes(",")?l.push(...m.split(",").map(h=>h.trim())):l.push(m))}const c={provider:"cognito"};e["cognito:username"]!==void 0&&(c.username=e["cognito:username"]),c.token_use=t,e.auth_time!==void 0&&(c.auth_time=e.auth_time);const u=e.client_id??e.aud;return u!==void 0&&(c.client_id=u),a!==void 0&&(c.cognito_groups=a),{id:r,email:n,name:o,picture:s,roles:i,permissions:l,emailVerified:e.email_verified,providerData:c}}async getUser(e){return f.debug("[CognitoProvider] getUser() is not implemented. Requires AWS SDK (@aws-sdk/client-cognito-identity-provider)."),null}}}}),Yer={};he(Yer,{KeycloakProvider:()=>Zer});var Yie,Zer,yQr=S({"src/lib/auth/providers/KeycloakProvider.ts"(){"use strict";vd(),q(),ta(),Mc(),Yie=new Map,Zer=class extends zl{type="keycloak";keycloakConfig;jwksUri;jwksCacheDuration;expectedIssuer;constructor(e){if(super(e),e.type!=="keycloak")throw At.create("CONFIGURATION_ERROR",`Invalid provider type: ${e.type}. Expected: keycloak`);if(this.keycloakConfig=e,!this.keycloakConfig.serverUrl)throw At.create("CONFIGURATION_ERROR","Keycloak serverUrl is required");if(!this.keycloakConfig.realm)throw At.create("CONFIGURATION_ERROR","Keycloak realm is required");if(!this.keycloakConfig.clientId)throw At.create("CONFIGURATION_ERROR","Keycloak clientId is required");const t=this.keycloakConfig.serverUrl.replace(/\/$/,"");this.expectedIssuer=`${t}/realms/${this.keycloakConfig.realm}`,this.jwksUri=`${this.expectedIssuer}/protocol/openid-connect/certs`,this.jwksCacheDuration=e.tokenValidation?.jwksCacheDuration??6e5,f.debug(`[KeycloakProvider] Initialized for realm: ${this.keycloakConfig.realm}`)}async authenticateToken(e){try{const t=this.parseJWT(e);if(!t)return{valid:!1,error:"Failed to decode token",errorCode:"AUTH-006"};if(t.iss!==this.expectedIssuer)return{valid:!1,error:`Invalid issuer: ${t.iss}. Expected: ${this.expectedIssuer}`,errorCode:"AUTH-001"};if(!(Array.isArray(t.aud)?t.aud:[t.aud]).includes(this.keycloakConfig.clientId))return{valid:!1,error:`Invalid audience: token aud does not contain clientId "${this.keycloakConfig.clientId}"`,errorCode:"AUTH-001"};const n=t.azp;if(n&&n!==this.keycloakConfig.clientId)return{valid:!1,error:`Invalid authorized party: ${n}. Expected: ${this.keycloakConfig.clientId}`,errorCode:"AUTH-001"};const o=this.config.tokenValidation?.clockTolerance??0;if(this.isTokenExpired(t,o))return{valid:!1,error:"Token has expired",errorCode:"AUTH-002",expiresAt:t.exp?new Date(t.exp*1e3):void 0};if(this.isTokenNotYetValid(t,o))return{valid:!1,error:"Token is not yet valid",errorCode:"AUTH-001"};if(this.keycloakConfig.verifyToken!==!1&&this.config.tokenValidation?.validateSignature!==!1&&!await this.verifySignature(e))return{valid:!1,error:"Invalid token signature",errorCode:"AUTH-004"};const s=this.extractKeycloakUser(t),i={};for(const[a,l]of Object.entries(t))l!==void 0&&(i[a]=l);return{valid:!0,user:s,claims:i,expiresAt:t.exp?new Date(t.exp*1e3):void 0,issuer:t.iss,audience:t.aud}}catch(t){return f.error("[KeycloakProvider] Token validation error:",t),{valid:!1,error:t instanceof Error?t.message:"Token validation failed",errorCode:"AUTH-014"}}}async verifySignature(e){try{const t=e.split(".");if(t.length!==3)return!1;const r=JSON.parse(Buffer.from(t[0],"base64url").toString("utf-8")),n=r.kid;if(!n)return f.warn("[KeycloakProvider] Token missing kid in header"),!1;const s=(await this.getJWKS()).keys.find(l=>l.kid===n);if(!s)return f.warn(`[KeycloakProvider] Key not found for kid: ${n}`),!1;const i=await Gie(s,r.alg),a=this.config.tokenValidation?.clockTolerance??30;return await xu(e,i,{clockTolerance:a}),!0}catch(t){return f.error("[KeycloakProvider] Signature verification error:",t),!1}}async getJWKS(){const e=Yie.get(this.jwksUri);if(e&&e.expiresAt>Date.now())return e.jwks;try{const t=await fetch(this.jwksUri,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`JWKS fetch failed: ${t.status}`);const r=await t.json();return Yie.set(this.jwksUri,{jwks:r,expiresAt:Date.now()+this.jwksCacheDuration}),r}catch(t){throw At.create("JWKS_FETCH_FAILED",`Failed to fetch JWKS from ${this.jwksUri}: ${t instanceof Error?t.message:String(t)}`,{cause:t instanceof Error?t:void 0})}}extractKeycloakUser(e){const t=e.sub??"",r=e.email,n=e.name??e.preferred_username,o=e.picture;let s=[];const i=e.realm_access;i?.roles&&(s=[...i.roles]);const a=e.resource_access;if(a){const d=a[this.keycloakConfig.clientId]?.roles;d&&(s=[...s,...d.map(m=>`${this.keycloakConfig.clientId}:${m}`)]);for(const[m,h]of Object.entries(a))m!==this.keycloakConfig.clientId&&h.roles&&(s=[...s,...h.roles.map(g=>`${m}:${g}`)])}s.length===0&&this.rbacConfig.defaultRoles&&(s=this.rbacConfig.defaultRoles);let l=[];const c=e.scope;c&&(l=c.split(" ").filter(d=>d.length>0));const u={provider:"keycloak"};return e.preferred_username!==void 0&&(u.preferred_username=e.preferred_username),e.given_name!==void 0&&(u.given_name=e.given_name),e.family_name!==void 0&&(u.family_name=e.family_name),i!==void 0&&(u.realm_access=i),a!==void 0&&(u.resource_access=a),e.azp!==void 0&&(u.azp=e.azp),e.session_state!==void 0&&(u.session_state=e.session_state),e.acr!==void 0&&(u.acr=e.acr),e.typ!==void 0&&(u.typ=e.typ),{id:t,email:r,name:n,picture:o,roles:s,permissions:l,emailVerified:e.email_verified,providerData:u}}async getUser(e){if(!this.keycloakConfig.clientSecret)return f.debug("[KeycloakProvider] clientSecret required for admin API"),null;try{const t=await fetch(`${this.expectedIssuer}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:this.keycloakConfig.clientId,client_secret:this.keycloakConfig.clientSecret}),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Failed to get admin token: ${t.status}`);const r=await t.json(),n=this.keycloakConfig.serverUrl.replace(/\/$/,""),o=await fetch(`${n}/admin/realms/${this.keycloakConfig.realm}/users/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${r.access_token}`},signal:AbortSignal.timeout(5e3)});if(!o.ok){if(o.status===404)return null;throw new Error(`Failed to get user: ${o.status}`)}const s=await o.json(),i=await fetch(`${n}/admin/realms/${this.keycloakConfig.realm}/users/${encodeURIComponent(e)}/role-mappings/realm`,{headers:{Authorization:`Bearer ${r.access_token}`},signal:AbortSignal.timeout(5e3)});let a=this.rbacConfig.defaultRoles??[];i.ok&&(a=(await i.json()).map(u=>u.name));const l={};for(const[c,u]of Object.entries(s))u!==void 0&&(l[c]=u);return{id:s.id,email:s.email,name:`${s.firstName??""} ${s.lastName??""}`.trim()||s.username,picture:void 0,roles:a,permissions:[],emailVerified:s.emailVerified,providerData:l,createdAt:s.createdTimestamp?new Date(s.createdTimestamp):void 0}}catch(t){return f.error(`[KeycloakProvider] Failed to get user ${e}:`,t),null}}}}}),Xer={};he(Xer,{BetterAuthProvider:()=>Qer});var Qer,vQr=S({"src/lib/auth/providers/betterAuth.ts"(){"use strict";no(),ta(),vd(),Mc(),Qer=class extends zl{type="better-auth";secret;baseUrl;secretKey;constructor(e){if(super(e),!e.secret)throw At.create("CONFIGURATION_ERROR","Better Auth secret is required",{details:{provider:"better-auth",missingFields:["secret"]}});if(!e.baseUrl)throw At.create("CONFIGURATION_ERROR","Better Auth baseUrl is required",{details:{provider:"better-auth",missingFields:["baseUrl"]}});this.secret=e.secret,this.baseUrl=e.baseUrl.replace(/\/$/,""),this.secretKey=new TextEncoder().encode(this.secret)}async authenticateToken(e,t){if(e.includes(".")&&e.split(".").length===3){const r=await this.validateJWT(e);if(r.valid)return r}return this.validateSessionViaAPI(e)}async validateJWT(e){try{const{payload:t}=await xu(e,this.secretKey);if(!t.sub)return{valid:!1,error:"Token missing required 'sub' claim"};const r={id:t.sub,email:t.email,name:t.name,picture:t.picture,emailVerified:t.email_verified,roles:t.roles||[],permissions:t.permissions||[],metadata:t.metadata};return{valid:!0,payload:t,user:r,expiresAt:t.exp?new Date(t.exp*1e3):void 0,tokenType:"jwt"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async validateSessionViaAPI(e){try{const r=await Bt()(`${this.baseUrl}/api/auth/session`,{headers:{Cookie:`better-auth.session_token=${e}`},signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`Session validation failed: HTTP ${r.status}`};const n=await r.json();if(!n.user)return{valid:!1,error:"Invalid session"};const o={id:n.user.id,email:n.user.email,name:n.user.name,picture:n.user.image,emailVerified:n.user.emailVerified,roles:n.user.roles||[],permissions:n.user.permissions||[],createdAt:n.user.createdAt?new Date(n.user.createdAt):void 0,metadata:n.user};return{valid:!0,payload:n,user:o,expiresAt:n.session?.expiresAt?new Date(n.session.expiresAt):void 0,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async healthCheck(){try{const r=(await Bt()(`${this.baseUrl}/api/auth/session`,{signal:AbortSignal.timeout(5e3)})).status<500;return{healthy:r,providerConnected:r,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),etr={};he(etr,{WorkOSProvider:()=>ttr});var ttr,_Qr=S({"src/lib/auth/providers/workos.ts"(){"use strict";q(),no(),ta(),vd(),Mc(),ttr=class extends zl{type="workos";apiKey;clientId;organizationId;jwks=null;constructor(e){if(super(e),!e.apiKey)throw At.create("CONFIGURATION_ERROR","WorkOS API key is required",{details:{provider:"workos",missingFields:["apiKey"]}});if(!e.clientId)throw At.create("CONFIGURATION_ERROR","WorkOS client ID is required",{details:{provider:"workos",missingFields:["clientId"]}});this.apiKey=e.apiKey,this.clientId=e.clientId,this.organizationId=e.organizationId}async initialize(){const e=new URL("https://api.workos.com/sso/jwks");this.jwks=Qx(e),f.debug("WorkOS provider initialized")}async authenticateToken(e,t){this.jwks||await this.initialize();try{const r=this.jwks;if(!r)throw At.create("PROVIDER_INIT_FAILED","WorkOS JWKS was not initialized",{details:{provider:"workos"}});const{payload:n}=await xu(e,r,{audience:this.clientId});if(this.organizationId&&n.org_id!==this.organizationId)return{valid:!1,error:`Organization mismatch: expected ${this.organizationId}, got ${n.org_id}`};const o={id:n.sub,email:n.email,name:n.first_name&&n.last_name?`${n.first_name} ${n.last_name}`.trim():void 0,emailVerified:!0,roles:n.roles||[],permissions:n.permissions||[],organizationId:n.org_id,metadata:{connection_id:n.connection_id,connection_type:n.connection_type,idp_id:n.idp_id}};return{valid:!0,payload:n,user:o,expiresAt:n.exp?new Date(n.exp*1e3):void 0,tokenType:"jwt"}}catch{return this.validateSessionViaAPI(e)}}async validateSessionViaAPI(e){try{const r=await Bt()("https://api.workos.com/user_management/authenticate",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({session_token:e,client_id:this.clientId}),signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`Session validation failed: HTTP ${r.status}`};const n=await r.json();if(!n.user)return{valid:!1,error:"User not found in session"};if(this.organizationId&&n.organization_id!==this.organizationId)return{valid:!1,error:`Organization mismatch: expected ${this.organizationId}, got ${n.organization_id}`};const o={id:n.user.id,email:n.user.email,name:n.user.first_name&&n.user.last_name?`${n.user.first_name} ${n.user.last_name}`.trim():void 0,picture:n.user.profile_picture_url,emailVerified:n.user.email_verified,roles:[],permissions:[],organizationId:n.organization_id,createdAt:n.user.created_at?new Date(n.user.created_at):void 0,metadata:n.user};return{valid:!0,payload:n,user:o,tokenType:"session"}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async getUser(e){try{const r=await Bt()(`https://api.workos.com/user_management/users/${e}`,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!r.ok){if(r.status===404)return null;throw At.create("PROVIDER_ERROR",`WorkOS API returned ${r.status}`,{details:{provider:"workos",statusCode:r.status}})}const n=await r.json();return{id:n.id,email:n.email,name:n.first_name&&n.last_name?`${n.first_name} ${n.last_name}`.trim():void 0,picture:n.profile_picture_url,emailVerified:n.email_verified,roles:[],permissions:[],createdAt:n.created_at?new Date(n.created_at):void 0,metadata:n}}catch(t){throw f.error("Failed to fetch WorkOS user:",t instanceof Error?t.message:String(t)),t}}async getUserByEmail(e){try{const r=await Bt()(`https://api.workos.com/user_management/users?email=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!r.ok)throw At.create("PROVIDER_ERROR",`WorkOS API returned ${r.status}`,{details:{provider:"workos",statusCode:r.status}});const o=(await r.json()).data||[];if(o.length===0)return null;const s=o[0];return{id:s.id,email:s.email,name:s.first_name&&s.last_name?`${s.first_name} ${s.last_name}`.trim():void 0,picture:s.profile_picture_url,emailVerified:s.email_verified,roles:[],permissions:[],createdAt:s.created_at?new Date(s.created_at):void 0,metadata:s}}catch(t){if(f.error("Failed to fetch WorkOS user by email:",t instanceof Error?t.message:String(t)),t instanceof Error&&t.name==="AuthError")throw t;return null}}async healthCheck(){try{const t=await Bt()("https://api.workos.com/sso/jwks");return{healthy:t.ok,providerConnected:t.ok,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),rtr={};he(rtr,{OAuth2Provider:()=>ntr});var ntr,wQr=S({"src/lib/auth/providers/oauth2.ts"(){"use strict";vd(),no(),q(),ta(),Mc(),ntr=class extends zl{type="oauth2";authorizationUrl;tokenUrl;userInfoUrl;jwksUrl;clientId;clientSecret;scopes;redirectUrl;usePKCE;jwks=null;constructor(e){if(super(e),!e.authorizationUrl)throw At.create("CONFIGURATION_ERROR","OAuth2 authorizationUrl is required");if(!e.tokenUrl)throw At.create("CONFIGURATION_ERROR","OAuth2 tokenUrl is required");if(!e.clientId)throw At.create("CONFIGURATION_ERROR","OAuth2 clientId is required");this.authorizationUrl=e.authorizationUrl,this.tokenUrl=e.tokenUrl,this.userInfoUrl=e.userInfoUrl,this.jwksUrl=e.jwksUrl,this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.scopes=e.scopes??["openid","profile","email"],this.redirectUrl=e.redirectUrl,this.usePKCE=e.usePKCE??!1}async initialize(){if(this.jwksUrl)try{const e=new URL(this.jwksUrl);this.jwks=Qx(e),f.debug(`OAuth2 provider initialized with JWKS: ${this.jwksUrl}`)}catch(e){throw At.create("PROVIDER_INIT_FAILED","Failed to initialize OAuth2 JWKS",{cause:e instanceof Error?e:new Error(String(e))})}}async authenticateToken(e,t){if(this.jwksUrl){if(this.jwks||await this.initialize(),!this.jwks)return{valid:!1,error:"JWKS not available after initialization"};try{const{payload:r}=await xu(e,this.jwks);if(r.iss){const o=new URL(this.authorizationUrl).origin;if(!r.iss.startsWith(o))return{valid:!1,error:`Invalid issuer: ${r.iss}. Expected origin: ${o}`}}if(r.aud){const o=Array.isArray(r.aud)?r.aud:[r.aud];if(!o.includes(this.clientId))return{valid:!1,error:`Invalid audience: ${o.join(", ")}. Expected: ${this.clientId}`}}if(!r.sub)return{valid:!1,error:"JWT is missing required 'sub' claim: cannot identify user"};const n={id:r.sub,email:r.email,name:r.name,picture:r.picture,roles:r.roles??[],permissions:r.permissions??[],metadata:r};return{valid:!0,payload:r,user:n,expiresAt:r.exp?new Date(r.exp*1e3):void 0,tokenType:"jwt"}}catch{f.debug("JWKS validation failed, trying userinfo endpoint")}}return this.userInfoUrl?this.validateViaUserInfo(e):{valid:!1,error:"No validation method available (provide jwksUrl or userInfoUrl)"}}async validateViaUserInfo(e){try{const t=Bt();if(!this.userInfoUrl)return{valid:!1,error:"UserInfo URL not configured"};const r=await t(this.userInfoUrl,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(!r.ok)return{valid:!1,error:`UserInfo endpoint returned ${r.status}`};const n=await r.json(),o=n.sub??n.id;if(!o)return{valid:!1,error:"UserInfo response is missing 'sub' and 'id': cannot identify user"};const s={id:o,email:n.email,name:n.name,picture:n.picture,emailVerified:n.email_verified,roles:n.roles??[],permissions:n.permissions??[],metadata:n};return{valid:!0,payload:n,user:s,tokenType:"oauth"}}catch(t){const r=t instanceof Error?t.message:String(t);return f.warn("OAuth2 userinfo validation failed:",r),{valid:!1,error:r}}}getAuthorizationUrl(e,t){const r=new URLSearchParams({response_type:"code",client_id:this.clientId,scope:this.scopes.join(" "),state:e});return this.redirectUrl&&r.set("redirect_uri",this.redirectUrl),this.usePKCE&&t&&(r.set("code_challenge",t),r.set("code_challenge_method","S256")),`${this.authorizationUrl}?${r.toString()}`}async exchangeCode(e,t){const r=Bt(),n=new URLSearchParams({grant_type:"authorization_code",client_id:this.clientId,code:e});this.clientSecret&&n.set("client_secret",this.clientSecret),this.redirectUrl&&n.set("redirect_uri",this.redirectUrl),this.usePKCE&&t&&n.set("code_verifier",t);const o=await r(this.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),signal:AbortSignal.timeout(5e3)});if(!o.ok)throw At.create("PROVIDER_ERROR",`Token exchange failed: ${o.status}`);const s=await o.json();return{accessToken:s.access_token,refreshToken:s.refresh_token,idToken:s.id_token}}async healthCheck(){try{const e=Bt(),t=this.jwksUrl??this.authorizationUrl,r=await e(t,{method:"HEAD"});return{healthy:r.ok||r.status===405,providerConnected:!0,sessionStorageHealthy:!0,error:r.ok||r.status===405?void 0:`HTTP ${r.status}`}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),otr={};he(otr,{JWTProvider:()=>str});var str,bQr=S({"src/lib/auth/providers/jwt.ts"(){"use strict";vd(),q(),ta(),Mc(),str=class extends zl{type="jwt";secret;publicKey;algorithms;issuer;audience;keyObject=null;constructor(e){if(super(e),!e.secret&&!e.publicKey)throw At.create("CONFIGURATION_ERROR","JWT requires either secret (for HMAC) or publicKey (for RSA/ECDSA)",{details:{provider:"jwt",missingFields:["secret","publicKey"]}});this.secret=e.secret,this.publicKey=e.publicKey,this.algorithms=e.algorithms??(e.secret?["HS256"]:["RS256"]),this.issuer=e.issuer,this.audience=e.audience}async initialize(){try{this.secret?(this.keyObject=new TextEncoder().encode(this.secret),f.debug("JWT provider initialized with symmetric secret")):this.publicKey&&(this.keyObject=await VXr(this.publicKey,this.algorithms[0]),f.debug("JWT provider initialized with asymmetric public key"))}catch(e){throw At.create("PROVIDER_INIT_FAILED",`Failed to initialize JWT key: ${e instanceof Error?e.message:String(e)}`,{details:{provider:"jwt"},cause:e instanceof Error?e:void 0})}}async authenticateToken(e,t){this.keyObject||await this.initialize();try{const r=this.keyObject;if(!r)throw At.create("PROVIDER_INIT_FAILED","JWT verification key was not initialized",{details:{provider:"jwt"}});const n={};this.algorithms.length>0&&(n.algorithms=this.algorithms),this.issuer&&(n.issuer=this.issuer),this.audience&&(n.audience=this.audience);const{payload:o}=await xu(e,r,n);if(!o.sub)return{valid:!1,error:"JWT is missing required 'sub' claim: cannot identify user"};const s={id:o.sub,email:o.email,name:o.name,picture:o.picture,emailVerified:o.email_verified,roles:o.roles??[],permissions:o.permissions??o.scope?.split(" ")??[],metadata:{iss:o.iss,aud:o.aud,jti:o.jti}};return{valid:!0,payload:o,user:s,expiresAt:o.exp?new Date(o.exp*1e3):void 0,tokenType:"jwt"}}catch(r){const n=r instanceof Error?r.message:String(r);f.warn("JWT validation failed:",n);let o=n;return n.includes("JWTExpired")?o="Token has expired":n.includes("signature")?o="Invalid token signature":n.includes("audience")?o="Invalid token audience":n.includes("issuer")&&(o="Invalid token issuer"),{valid:!1,error:o}}}async signToken(e,t){if(!this.secret)throw At.create("CONFIGURATION_ERROR","Token signing requires a secret (symmetric key)",{details:{provider:"jwt"}});this.keyObject||await this.initialize();const r=new Oer(e).setProtectedHeader({alg:this.algorithms[0]}).setIssuedAt();return this.issuer&&r.setIssuer(this.issuer),this.audience&&r.setAudience(this.audience),t?.expiresIn&&r.setExpirationTime(t.expiresIn),r.sign(this.keyObject)}async healthCheck(){try{return this.keyObject||await this.initialize(),{healthy:this.keyObject!==null,providerConnected:!0,sessionStorageHealthy:!0}}catch(e){return{healthy:!1,providerConnected:!1,sessionStorageHealthy:!0,error:e instanceof Error?e.message:String(e)}}}}}}),itr={};he(itr,{CustomAuthProvider:()=>atr});var atr,TQr=S({"src/lib/auth/providers/custom.ts"(){"use strict";q(),ta(),Mc(),atr=class extends zl{type="custom";validateTokenFn;getUserFn;createSessionFn;constructor(e){if(super(e),!e.validateToken)throw At.create("CONFIGURATION_ERROR","Custom validateToken function is required",{details:{provider:"custom",missingFields:["validateToken"]}});this.validateTokenFn=e.validateToken,this.getUserFn=e.getUser,this.createSessionFn=e.createSession}async authenticateToken(e,t){try{return await this.validateTokenFn(e,t)}catch(r){return{valid:!1,error:r instanceof Error?r.message:String(r)}}}async createSession(e,t){if(this.createSessionFn){const r=await this.createSessionFn(e,t);return await this.sessionStorage.save(r),this.emit("auth:login",r.user),r}return super.createSession(e,t)}async getUser(e){if(this.getUserFn)try{return await this.getUserFn(e)}catch(t){return f.error("Custom getUser failed:",t),null}return f.warn("Custom getUser function not provided"),null}async healthCheck(){return{healthy:!0,providerConnected:!0,sessionStorageHealthy:!0}}}}}),EQr,SQr,CQr,kQr,h2,ltr,Zie,xQr,Xie,AQr,IQr,RQr,ctr=S({"node-stub:readline"(){EQr=globalThis.crypto,SQr=globalThis.ReadableStream||class{},CQr=globalThis.URL,kQr=globalThis.URLSearchParams,h2=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},h2.custom=Symbol.for("nodejs.util.inspect.custom"),h2.colors={},h2.styles={},ltr=globalThis.TextDecoder,Zie=globalThis.TextEncoder,xQr=globalThis.performance||{now:()=>Date.now()},Xie=()=>({}),AQr=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new Zie().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new Zie().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new ltr().decode(this)}},IQr=globalThis.clearTimeout,RQr=globalThis.clearInterval}});function Qie(e,t=utr){const r=e??t,n=Number.isNaN(r)?0:r;if(n===1/0)return;const o=Math.max(0,n)*dtr;if(Number.isFinite(o))return Date.now()-o}var utr,dtr,eae=S({"src/lib/localUsage/scanWindow.ts"(){"use strict";utr=30,dtr=864e5}}),ptr={};he(ptr,{createClaudeCodeReader:()=>DQr});function mtr(){return Cr(Uu(),".claude","projects")}function PQr(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"modeled",unpricedRequests:0,unpricedModels:[]}}async function htr(e,t){let r;try{r=await AM(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Cr(e,n.name);n.isDirectory()?await htr(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function f2(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function MQr(e,t,r){const n=new Map,o=Xie({input:k1(e,{encoding:"utf8"}),crlfDelay:1/0});try{for await(const s of o){if(!s||s.charCodeAt(0)!==123)continue;let i;try{i=JSON.parse(s)}catch{continue}const a=i;if(a.type!=="assistant"||!a.message?.usage)continue;const l=a.message.usage,c=a.message.id;if(typeof c!="string"||c.length===0)continue;const u={model:a.message.model??"unknown",input:f2(l.input_tokens),output:f2(l.output_tokens),read:f2(l.cache_read_input_tokens),create:f2(l.cache_creation_input_tokens)},d=n.get(c);(!d||u.output>d.output)&&n.set(c,u)}}finally{o.close()}for(const s of n.values())t.requests+=1,t.inputTokens+=s.input,t.outputTokens+=s.output,t.cacheReadTokens+=s.read,t.cacheCreationTokens+=s.create,YE(tae,s.model)?t.costUsd+=Ga(tae,s.model,{input:s.input,output:s.output,total:s.input+s.output,cacheReadTokens:s.read,cacheCreationTokens:s.create}):(t.unpricedRequests+=1,r.add(s.model))}async function DQr(){return{descriptor:{id:g2,displayName:"Claude Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"modeled",requiresSqlite:!1},detect:async()=>{try{return(await Yu(mtr())).isDirectory()}catch{return!1}},scan:async e=>{const t=PQr(),r=[],n=new Set,o=[];await htr(mtr(),o);const s=Qie(e?.sinceDays);let i=0;for(const a of o)try{if(s!==void 0&&(await Yu(a)).mtimeMs<s)continue;await MQr(a,t,n),i+=1}catch(l){r.push({cliId:g2,filePath:a,message:l instanceof Error?l.message:String(l)})}return t.unpricedModels=[...n].sort(),t.costUsd=Math.round(t.costUsd*1e6)/1e6,{cliId:g2,totals:t,filesScanned:i,errors:r}}}}var g2,tae,OQr=S({"src/lib/localUsage/claudeCodeReader.ts"(){"use strict";gn(),ctr(),ya(),ic(),Lr(),uc(),eae(),g2="claude-code",tae="anthropic"}}),ftr={};he(ftr,{createCodexReader:()=>$Qr});function gtr(){return Cr(Uu(),".codex","sessions")}function NQr(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}async function ytr(e,t){let r;try{r=await AM(e,{withFileTypes:!0})}catch{return}for(const n of r){const o=Cr(e,n.name);n.isDirectory()?await ytr(o,t):n.isFile()&&n.name.endsWith(".jsonl")&&t.push(o)}}function y2(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function LQr(e){const t=Xie({input:k1(e,{encoding:"utf8"}),crlfDelay:1/0});let r,n=-1,o,s=-1,i=0;try{for await(const a of t){const l=a.includes('"token_count"'),c=a.includes('"turn_context"');if(!l&&!c)continue;let u;try{u=JSON.parse(a)}catch{continue}const d=u;if(d.type==="turn_context"&&d.payload?.model){r=d.payload.model;continue}if(d.payload?.type!=="token_count")continue;const m=d.payload.info?.total_token_usage;if(!m)continue;const h=y2(m.total_tokens);h>s&&(i+=1),s=h,h>n&&(n=h,o={input:y2(m.input_tokens),output:y2(m.output_tokens),cached:y2(m.cached_input_tokens)})}}finally{t.close()}return o?{model:r,billableEvents:i,...o}:null}async function $Qr(){return{descriptor:{id:v2,displayName:"Codex",verified:!0,dedupStrategy:"session-dag",costConfidence:"unavailable",requiresSqlite:!1},detect:async()=>{try{return(await Yu(gtr())).isDirectory()}catch{return!1}},scan:async e=>{const t=NQr(),r=[],n=new Set,o=[];await ytr(gtr(),o);const s=Qie(e?.sinceDays);let i=0;for(const a of o)try{if(s!==void 0&&(await Yu(a)).mtimeMs<s)continue;const l=await LQr(a);if(i+=1,!l)continue;t.requests+=l.billableEvents,t.inputTokens+=Math.max(0,l.input-l.cached),t.cacheReadTokens+=l.cached,t.outputTokens+=l.output,l.model&&n.add(l.model)}catch(l){r.push({cliId:v2,filePath:a,message:l instanceof Error?l.message:String(l)})}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:v2,totals:t,filesScanned:i,errors:r}}}}var v2,FQr=S({"src/lib/localUsage/codexReader.ts"(){"use strict";gn(),ctr(),ya(),ic(),Lr(),eae(),v2="codex"}}),vtr={};he(vtr,{AsyncLocalStorage:()=>Utr,Buffer:()=>Pnr,Channel:()=>wnr,DatabaseSync:()=>Rnr,Duplex:()=>ztr,EventEmitter:()=>Ftr,Http2ServerRequest:()=>Lnr,Http2ServerResponse:()=>$nr,Interface:()=>Inr,MIMEType:()=>qnr,PassThrough:()=>jtr,PerformanceObserver:()=>ynr,Readable:()=>nae,ReadableStream:()=>qtr,Resolver:()=>fnr,TextDecoder:()=>iae,TextEncoder:()=>tA,Transform:()=>Btr,URL:()=>rnr,URLSearchParams:()=>nnr,Worker:()=>Snr,Writable:()=>oae,access:()=>yrr,appendFile:()=>Ytr,appendFileSync:()=>Ctr,arch:()=>Nrr,arrayBuffer:()=>Fnr,basename:()=>Ptr,builtinModules:()=>Xrr,callbackify:()=>unr,channel:()=>_nr,chmodSync:()=>Jtr,clearInterval:()=>jnr,clearTimeout:()=>Bnr,closeSync:()=>err,connect:()=>Urr,constants:()=>Mnr,copyFileSync:()=>Xtr,cpSync:()=>ktr,cpus:()=>Prr,createConnection:()=>Brr,createGunzip:()=>Wrr,createGzip:()=>Krr,createHash:()=>rae,createHmac:()=>btr,createInterface:()=>Anr,createReadStream:()=>urr,createRequire:()=>Zrr,createServer:()=>xtr,createWriteStream:()=>crr,debug:()=>lnr,debuglog:()=>sae,default:()=>_tr,deflateSync:()=>jrr,deprecate:()=>cnr,deserialize:()=>Enr,dirname:()=>Rtr,exec:()=>Err,execFile:()=>Crr,execFileSync:()=>krr,execSync:()=>Srr,existsSync:()=>Vtr,extname:()=>Mtr,fileURLToPath:()=>onr,finished:()=>Htr,format:()=>tnr,freemem:()=>Mrr,fstatSync:()=>trr,get:()=>Frr,gunzip:()=>Vrr,gunzipSync:()=>qrr,gzip:()=>Hrr,gzipSync:()=>Grr,hasSubscribers:()=>bnr,homedir:()=>Arr,hostname:()=>Rrr,inflateSync:()=>zrr,inherits:()=>inr,inspect:()=>eA,isAbsolute:()=>Otr,isBuiltin:()=>Qrr,isDeepStrictEqual:()=>dnr,isIP:()=>Nnr,isIPv4:()=>Onr,isIPv6:()=>Dnr,isMainThread:()=>Cnr,join:()=>Atr,lookup:()=>hnr,mkdir:()=>mrr,mkdirSync:()=>rrr,monitorEventLoopDelay:()=>vnr,normalize:()=>$tr,ok:()=>Jrr,open:()=>wrr,openSync:()=>Qtr,parentPort:()=>knr,parse:()=>enr,pathToFileURL:()=>snr,performance:()=>gnr,pipeline:()=>Gtr,platform:()=>xrr,posix:()=>Ltr,promises:()=>wtr,promisify:()=>anr,randomBytes:()=>Ttr,randomUUID:()=>Etr,readFile:()=>drr,readFileSync:()=>Wtr,readdir:()=>frr,readdirSync:()=>orr,realpath:()=>brr,realpathSync:()=>Ztr,relative:()=>Dtr,release:()=>Lrr,rename:()=>vrr,renameSync:()=>irr,request:()=>$rr,resolve:()=>Itr,rm:()=>_rr,rmSync:()=>lrr,rmdirSync:()=>arr,sep:()=>Ntr,serialize:()=>Tnr,setInterval:()=>znr,setTimeout:()=>Unr,spawn:()=>Trr,stat:()=>hrr,statSync:()=>nrr,strict:()=>Yrr,tmpdir:()=>Irr,toUSVString:()=>pnr,totalmem:()=>Drr,type:()=>Orr,types:()=>mnr,unlink:()=>grr,unlinkSync:()=>srr,webcrypto:()=>Str,workerData:()=>xnr,writeFile:()=>prr,writeFileSync:()=>Ktr});var Fo,Zn,_tr,wtr,rae,btr,Ttr,Etr,Str,Ctr,ktr,xtr,Atr,Itr,Rtr,Ptr,Mtr,Dtr,Otr,Ntr,Ltr,$tr,Ftr,Utr,nae,oae,Btr,ztr,jtr,qtr,Gtr,Htr,Vtr,Wtr,Ktr,Jtr,Ytr,Ztr,Xtr,Qtr,err,trr,rrr,nrr,orr,srr,irr,arr,lrr,crr,urr,drr,prr,mrr,hrr,frr,grr,yrr,vrr,_rr,wrr,brr,Trr,Err,Srr,Crr,krr,xrr,Arr,Irr,Rrr,Prr,Mrr,Drr,Orr,Nrr,Lrr,$rr,Frr,Urr,Brr,zrr,jrr,qrr,Grr,Hrr,Vrr,Wrr,Krr,Jrr,Yrr,Zrr,Xrr,Qrr,enr,tnr,rnr,nnr,onr,snr,inr,anr,sae,lnr,eA,cnr,unr,dnr,pnr,mnr,iae,tA,hnr,fnr,gnr,ynr,vnr,_nr,wnr,bnr,Tnr,Enr,Snr,Cnr,knr,xnr,Anr,Inr,Rnr,Pnr,Mnr,Dnr,Onr,Nnr,Lnr,$nr,Fnr,aae,Unr,Bnr,znr,jnr,qnr,UQr=S({"node-stub:node:sqlite"(){Fo=()=>{},Zn=async()=>{},_tr={},wtr={readFile:Zn,writeFile:Zn,mkdir:Zn,stat:Zn,readdir:Zn,unlink:Zn,access:Zn,rm:Zn,rename:Zn},rae=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new tA().encode(r):r),this},digest(r){let n=0;for(const s of t)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},btr=(e,t)=>rae(e),Ttr=e=>new Uint8Array(e||32),Etr=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),Str=globalThis.crypto,Ctr=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},ktr=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},xtr=()=>({listen:Fo,close:Fo,on:Fo}),Atr=(...e)=>e.join("/"),Itr=(...e)=>e.join("/"),Rtr=e=>e||"",Ptr=e=>e?.split?.("/")?.pop?.()||"",Mtr=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},Dtr=(e,t)=>t||"",Otr=()=>!1,Ntr="/",Ltr={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},$tr=e=>e,Ftr=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},Utr=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},nae=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},oae=class{write(){return!0}end(){}on(){return this}destroy(){}},Btr=class{push(){}on(){return this}},ztr=class{on(){return this}},jtr=class{pipe(){return this}on(){return this}},qtr=globalThis.ReadableStream||class{},Gtr=Fo,Htr=Fo,Vtr=()=>!1,Wtr=()=>"",Ktr=Fo,Jtr=Fo,Ytr=Zn,Ztr=e=>e,Xtr=Fo,Qtr=()=>0,err=Fo,trr=()=>({}),rrr=Fo,nrr=()=>({}),orr=()=>[],srr=Fo,irr=Fo,arr=Fo,lrr=Fo,crr=()=>new oae,urr=()=>new nae,drr=Zn,prr=Zn,mrr=Zn,hrr=Zn,frr=Zn,grr=Zn,yrr=Zn,vrr=Zn,_rr=Zn,wrr=async()=>({stat:Zn,readFile:Zn,close:Zn,read:Zn,write:Zn}),brr=async e=>e,Trr=()=>({on:Fo,stdout:{on:Fo},stderr:{on:Fo},kill:Fo}),Err=(e,t)=>t?.(null,"",""),Srr=()=>"",Crr=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},krr=()=>"",xrr="browser",Arr=()=>"/",Irr=()=>"/tmp",Rrr=()=>"browser",Prr=()=>[{}],Mrr=()=>0,Drr=()=>0,Orr=()=>"Browser",Nrr=()=>"wasm",Lrr=()=>"0",$rr=()=>({}),Frr=()=>({}),Urr=()=>({}),Brr=()=>({}),zrr=()=>new Uint8Array,jrr=()=>new Uint8Array,qrr=()=>new Uint8Array,Grr=()=>new Uint8Array,Hrr=(e,t)=>t?.(null,e),Vrr=(e,t)=>t?.(null,e),Wrr=()=>({}),Krr=()=>({}),Jrr=Fo,Yrr={},Zrr=()=>()=>({}),Xrr=[],Qrr=()=>!1,enr=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),tnr=()=>"",rnr=globalThis.URL,nnr=globalThis.URLSearchParams,onr=e=>typeof e=="string"?e.replace("file://",""):e,snr=e=>new globalThis.URL("file://"+e),inr=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},anr=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),sae=e=>{const t=(...r)=>{};return t.enabled=!1,t},lnr=sae,eA=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},eA.custom=Symbol.for("nodejs.util.inspect.custom"),eA.colors={},eA.styles={},cnr=e=>e,unr=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},dnr=(e,t)=>JSON.stringify(e)===JSON.stringify(t),pnr=e=>String(e),mnr={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},iae=globalThis.TextDecoder,tA=globalThis.TextEncoder,hnr=(e,t)=>t?.(null,"127.0.0.1",4),fnr=class{},gnr=globalThis.performance||{now:()=>Date.now()},ynr=class{observe(){}disconnect(){}},vnr=()=>({enable:Fo,disable:Fo,percentile:()=>0}),_nr=()=>({}),wnr=class{},bnr=()=>!1,Tnr=()=>new Uint8Array,Enr=Fo,Snr=class{},Cnr=!0,knr=null,xnr=null,Anr=()=>({}),Inr=class{},Rnr=class{},Pnr=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new tA().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new tA().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new iae().decode(this)}},Mnr={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Dnr=()=>!1,Onr=()=>!1,Nnr=()=>0,Lnr=class{},$nr=class{},Fnr=async()=>new ArrayBuffer(0),aae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Unr=(...e)=>aae(globalThis.setTimeout(...e)),Bnr=globalThis.clearTimeout,znr=(...e)=>aae(globalThis.setInterval(...e)),jnr=globalThis.clearInterval,qnr=class{constructor(e){this.type=e}toString(){return this.type}}}}),Gnr={};he(Gnr,{createOpenCodeReader:()=>zQr});function Hnr(){return Cr(Uu(),".local","share","opencode","opencode.db")}function BQr(){return{requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,costConfidence:"unavailable",unpricedRequests:0,unpricedModels:[]}}function _2(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function zQr(){return{descriptor:{id:wh,displayName:"OpenCode",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},detect:async()=>{try{return(await Yu(Hnr())).isFile()}catch{return!1}},scan:async e=>{const t=BQr(),r=[],n=new Set,o=Hnr();let s;try{const l=await Promise.resolve().then(()=>(UQr(),vtr));typeof l=="object"&&l!==null&&"DatabaseSync"in l&&typeof l.DatabaseSync=="function"&&(s=l.DatabaseSync)}catch(l){return r.push({cliId:wh,filePath:o,message:`node:sqlite unavailable on this runtime: ${l instanceof Error?l.message:String(l)}`}),{cliId:wh,totals:t,filesScanned:0,errors:r}}if(!s)return r.push({cliId:wh,filePath:o,message:"node:sqlite did not expose a callable DatabaseSync \u2014 the experimental API has likely changed shape"}),{cliId:wh,totals:t,filesScanned:0,errors:r};const i=Qie(e?.sinceDays)??0;let a;try{a=new s(o,{readOnly:!0});const l=a.prepare("SELECT data FROM message WHERE time_created >= ?").all(i);for(const c of l){if(typeof c.data!="string")continue;let u;try{u=JSON.parse(c.data)}catch{continue}const d=u,m=d.tokens;if(!m||d.role!=="assistant")continue;const h=_2(m.input),g=_2(m.output),y=_2(m.cache?.read),v=_2(m.cache?.write);h===0&&g===0&&y===0&&v===0||(t.requests+=1,t.inputTokens+=h,t.outputTokens+=g,t.cacheReadTokens+=y,t.cacheCreationTokens+=v,d.modelID&&n.add(d.modelID))}}catch(l){r.push({cliId:wh,filePath:o,message:l instanceof Error?l.message:String(l)})}finally{try{a?.close()}catch{}}return t.unpricedRequests=t.requests,t.unpricedModels=[...n].sort(),{cliId:wh,totals:t,filesScanned:t.requests>0||r.length===0?1:0,errors:r}}}}var wh,jQr=S({"src/lib/localUsage/openCodeReader.ts"(){"use strict";ya(),ic(),Lr(),eae(),wh="opencode"}});Ul(),aa(),By(),gn(),Lr(),Ft(),q(),yt();var{readFile:lae,writeFile:Vnr,readdir:qQr,mkdir:GQr,unlink:HQr,access:VQr}=Ci,WQr=class{configPath=".neurolink.config";backupDir=".neurolink.backups";config=null;configCache=new Map;async loadConfig(){return this.config||(this.config=await this.readConfigFile()),this.config}async updateConfig(e,t={}){const{createBackup:r=!0,validate:n=!0,merge:o=!0,reason:s="update",silent:i=!1}=t;r&&(await this.createBackup(s),i||f.info("\u{1F4BE} Backup created before config update"));const a=await this.loadConfig();if(this.config=o?{...a,...e,lastUpdated:Date.now()}:{...e,lastUpdated:Date.now()},n){const l=await this.validateConfig(this.config);if(!l.valid)throw new Error(`Config validation failed: ${l.errors.join(", ")}`)}try{await this.persistConfig(this.config),i||f.info("\u2705 Configuration updated successfully")}catch(l){throw r&&(await this.restoreLatestBackup(),i||f.info("\u{1F504} Auto-restored from backup due to error")),new Error(`Config update failed, restored from backup: ${l.message}`,{cause:l})}}async createBackup(e="manual"){await this.ensureBackupDirectory();const r=`neurolink-config-${new Date().toISOString().replace(/[:.]/g,"-")}.js`,n=Cr(this.backupDir,r),o=await this.loadConfig(),s=this.generateConfigHash(o),i={reason:e,timestamp:Date.now(),version:o.configVersion||"unknown",originalPath:this.configPath,hash:s,size:JSON.stringify(o).length,createdBy:"NeuroLinkConfigManager"},a=`// NeuroLink Config Backup - ${e}
|
|
2254
2254
|
// Created: ${new Date().toISOString()}
|
|
2255
2255
|
// Reason: ${e}
|
|
2256
2256
|
// Hash: ${s}
|
|
@@ -38,5 +38,8 @@ export function resolveScanCutoffMs(sinceDays, defaultDays = DEFAULT_SINCE_DAYS)
|
|
|
38
38
|
// anything near it overflow on the multiply. Treat that as no window rather
|
|
39
39
|
// than letting `Date.now() - Infinity` become -Infinity, which every
|
|
40
40
|
// timestamp compares as newer than.
|
|
41
|
-
|
|
41
|
+
if (!Number.isFinite(span)) {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
return Date.now() - span;
|
|
42
45
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "12.2.
|
|
3
|
+
"version": "12.2.6",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
|
|
6
6
|
"author": {
|