@rttnd/gau 1.4.0 → 1.4.1
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/dist/{chunk-NX4HKWJR.js → chunk-H7HMOWU7.js} +1 -1
- package/dist/{chunk-NX4HKWJR.js.map → chunk-H7HMOWU7.js.map} +1 -1
- package/dist/src/client/svelte/index.svelte.js.map +1 -1
- package/dist/src/core/handlers/index.js +1 -1
- package/dist/src/core/index.d.ts +1 -1
- package/dist/src/core/index.d.ts.map +1 -1
- package/dist/src/core/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/jwt/index.js +1 -1
- package/dist/src/solidstart/index.js +1 -1
- package/dist/src/sveltekit/index.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{htmlResponse as e,renderCancelledPage as t,renderSuccessPage as r}from"./chunk-5KEP3AIT.js";import{createJWTSignatureMessage as n,encodeJWT as o,JWSRegisteredHeaders as s,JWTRegisteredClaims as i,parseJWT as a}from"@oslojs/jwt";import{parse as c,serialize as l}from"cookie";var d={path:"/",sameSite:"lax",secure:!0,httpOnly:!0};function u(e){const t=new Map;if(e){const r=c(e);for(const e in r)t.set(e,r[e])}return t}var h=class{constructor(e,t){this.requestCookies=e,this.defaultOptions=t}#e=[];get(e){return this.requestCookies.get(e)}set(e,t,r){const n={...this.defaultOptions,...r};this.#e.push([e,t,n])}delete(e,t){this.set(e,"",{...t,expires:new Date(0),maxAge:0})}toHeaders(){const e=new Headers;for(const[t,r,n]of this.#e)e.append("Set-Cookie",l(t,r,n));return e}},f="__gau-csrf-token",w="__gau-session-token",p="__gau-session-stash",g="__gau-session-strategy",A="__gau-linking-token",m="__gau-pkce-code-verifier",E="__gau-callback-uri",I="__gau-provider-options",T="__gau-client-challenge",O=600;import{parse as y,serialize as U}from"cookie";function k(e){const t=u(e.headers.get("Cookie")).get(w);if(t)return{token:t,source:"cookie"};const r=e.headers.get("Authorization");return r?.startsWith("Bearer ")?{token:r.substring(7),source:"bearer"}:{}}function N({adapter:e,providers:t,basePath:r="/api/auth",jwt:n={},session:o={},cookies:s={},onOAuthExchange:i,mapExternalProfile:a,onBeforeLinkAccount:c,onAfterLinkAccount:l,trustHosts:u=[],autoLink:h="verifiedEmail",allowDifferentEmails:f=!0,updateUserInfoOnLink:g=!1,roles:A={},cors:m=!0,profiles:E,onError:I,errorRedirect:T,impersonation:O}){const{algorithm:N="ES256",secret:_,iss:L,aud:S,ttl:D=604800}=n,C={...d,...s},x=o.strategy??"auto";if("ES256"===N&&void 0!==_&&"string"!=typeof _)throw new Q("For ES256, the secret option must be a string.");const b=new Map(t.map(e=>[e.id,e])),P=!1!==m&&{allowedOrigins:(!0===m?"all":m.allowedOrigins)??"all",allowCredentials:(!0===m||m.allowCredentials)??!0,allowedHeaders:(!0===m?void 0:m.allowedHeaders)??["Content-Type","Authorization","Cookie"],allowedMethods:(!0===m?void 0:m.allowedMethods)??["GET","POST","OPTIONS"],exposeHeaders:!0===m?void 0:m.exposeHeaders,maxAge:!0===m?void 0:m.maxAge},H=E??{},M={defaultRole:A.defaultRole??"user",resolveOnCreate:A.resolveOnCreate,adminRoles:A.adminRoles??["admin"],adminUserIds:A.adminUserIds??[]},F=O?.enabled?{enabled:!0,allowedRoles:O.allowedRoles??M.adminRoles,cannotImpersonate:O.cannotImpersonate??M.adminRoles,maxTTL:O.maxTTL??3600,onImpersonate:O.onImpersonate}:null;async function V(e,t={}){return se(e,function(e={}){const t={ttl:e.ttl,iss:e.iss??L,aud:e.aud??S,sub:e.sub};if("HS256"===N)return{algorithm:N,secret:e.secret??_,...t};{if(void 0!==e.secret&&"string"!=typeof e.secret)throw new Q("For ES256, the secret option must be a string.");const r=e.secret??_;return{algorithm:N,privateKey:e.privateKey,secret:r,...t}}}(t))}async function K(e,t={}){const r=function(e={}){const t={iss:e.iss??L,aud:e.aud??S};if("HS256"===N)return{algorithm:N,secret:e.secret??_,...t};{if(void 0!==e.secret&&"string"!=typeof e.secret)throw new Q("For ES256, the secret option must be a string.");const r=e.secret??_;return{algorithm:N,publicKey:e.publicKey,secret:r,...t}}}(t);try{return await ie(e,r)}catch{return null}}async function W(e,t={},r=D){return V({sub:e,...t},{ttl:r})}async function j(e,t={}){const{data:r={},ttl:n=D}=t,o=await W(e,r,n),s={...C,maxAge:n};return{token:o,cookie:U(w,o,s),cookieName:w,maxAge:n}}return{...e,providerMap:b,basePath:r,cookieOptions:C,jwt:{ttl:D},onOAuthExchange:i,mapExternalProfile:a,onBeforeLinkAccount:c,onAfterLinkAccount:l,signJWT:V,verifyJWT:K,createSession:W,validateSession:async function(t){const r=await K(t);if(!r)return null;const n=await e.getUserAndAccounts(r.sub);if(!n)return null;const{user:o,accounts:s}=n,i=Boolean(o&&(o.role&&M.adminRoles.includes(o.role)||M.adminUserIds.length>0&&M.adminUserIds.includes(o.id)));return{user:o?{...o,isAdmin:i}:null,session:{id:t,...r},accounts:s}},issueSession:j,refreshSession:async function(t,r={}){let n,o;if("string"==typeof t)n=t,o="token";else{const e=k(t);if(!e.token||!e.source)return null;n=e.token,o=e.source}const s=await K(n);if(!s||!s.sub)return null;if(null!=r.threshold&&r.threshold>0&&r.threshold<1){const{iat:e}=s;if(e){if(Math.floor(Date.now()/1e3)-e<(r.ttl??D)*r.threshold)return null}}if(!await e.getUser(s.sub))return null;const{sub:i,iat:a,exp:c,iss:l,aud:d,nbf:u,jti:h,...f}=s;return{...await j(s.sub,{data:f,ttl:r.ttl}),source:o}},getAccessToken:async function(t,r){const n=b.get(r);if(!n)return null;const o=(await e.getAccounts(t)).find(e=>e.provider===r);if(!o||!o.accessToken)return null;const s=Math.floor(Date.now()/1e3);if(!("number"==typeof o.expiresAt&&o.expiresAt<=s))return{accessToken:o.accessToken,expiresAt:o.expiresAt??null};if(!o.refreshToken||!n.refreshAccessToken)return null;try{const r=await n.refreshAccessToken(o.refreshToken,{}),s={userId:t,provider:o.provider,providerAccountId:o.providerAccountId,accessToken:r.accessToken??o.accessToken,refreshToken:r.refreshToken??o.refreshToken,expiresAt:r.expiresAt??null,idToken:r.idToken??o.idToken??null,tokenType:r.tokenType??o.tokenType??null,scope:r.scope??o.scope??null};return await(e.updateAccount?.(s)),{accessToken:s.accessToken,expiresAt:s.expiresAt}}catch{return null}},trustHosts:u,autoLink:h,allowDifferentEmails:f,profiles:H,updateUserInfoOnLink:g,sessionStrategy:x,development:!1,roles:M,cors:P,onError:I,errorRedirect:T,startImpersonation:async function(t,r,n={}){if(!F)throw new R(v.IMPERSONATION_DISABLED);const o=await e.getUser(t);if(!o)throw new R(v.USER_NOT_FOUND,`Admin user "${t}" not found`);const s=!!o.role&&F.allowedRoles.includes(o.role),i=M.adminUserIds.includes(t);if(!s&&!i)throw new R(v.IMPERSONATION_NOT_ALLOWED);const a=await e.getUser(r);if(!a)throw new R(v.USER_NOT_FOUND,`Target user "${r}" not found`);if(a.role&&F.cannotImpersonate.includes(a.role))throw new R(v.IMPERSONATION_TARGET_PROTECTED);F.onImpersonate&&await F.onImpersonate({adminUserId:t,targetUserId:r,reason:n.reason,timestamp:Date.now()});const c=Math.min(n.ttl??F.maxTTL,F.maxTTL),l=Math.floor(Date.now()/1e3)+c,d=await W(r,{impersonatedBy:t,impersonationExpiresAt:l},c),u={...C,maxAge:c},h=U(w,d,u),f=await V({adminUserId:t},{ttl:2*F.maxTTL});return{token:d,cookie:h,originalCookie:U(p,f,u),maxAge:c}},endImpersonation:async function(t){const r=t.headers.get("cookie");if(!r)return null;const n=y(r)[p];if(!n)return null;const o=await K(n);if(!o?.adminUserId)return null;if(!await e.getUser(o.adminUserId))return null;const s=await j(o.adminUserId),i=U(p,"",{...C,expires:new Date(0),maxAge:0});return{token:s.token,cookie:s.cookie,clearCookies:[i]}},impersonation:F}}var _={CSRF_INVALID:"Invalid CSRF token",PKCE_MISSING:"Missing PKCE code verifier",PKCE_CHALLENGE_MISSING:"Missing PKCE challenge",OAUTH_CANCELLED:"Authentication was cancelled",PROVIDER_NOT_FOUND:"Provider not found",AUTHORIZATION_URL_FAILED:"Could not create authorization URL",USER_NOT_FOUND:"User not found",USER_CREATE_FAILED:"Failed to create user",ACCOUNT_ALREADY_LINKED:"Account already linked to another user",ACCOUNT_LINK_FAILED:"Failed to link account",ACCOUNT_NOT_LINKED:"Account not linked",CANNOT_UNLINK_LAST_ACCOUNT:"Cannot unlink the last account",EMAIL_ALREADY_EXISTS:"An account with this email already exists",EMAIL_MISMATCH:"Email mismatch between existing account and provider",LINKING_NOT_ALLOWED:"Linking not allowed",LINK_ONLY_PROVIDER:"Sign-in with this provider is disabled. Please link it to an existing account.",UNAUTHORIZED:"Unauthorized",FORBIDDEN:"Forbidden",SESSION_INVALID:"Invalid session",SESSION_VALIDATION_FAILED:"Failed to validate session",TOKEN_INVALID:"Invalid token",TOKEN_EXPIRED:"Token expired",CODE_VERIFIER_INVALID:"Invalid code verifier",NOT_FOUND:"Not found",METHOD_NOT_ALLOWED:"Method not allowed",INVALID_REQUEST:"Invalid request",INVALID_REDIRECT_URL:"Invalid redirect URL",UNTRUSTED_HOST:"Untrusted redirect host",UNKNOWN_PROFILE:"Unknown profile",INTERNAL_ERROR:"An unexpected error occurred",IMPERSONATION_DISABLED:"Impersonation is not enabled",IMPERSONATION_NOT_ALLOWED:"You are not allowed to impersonate users",IMPERSONATION_TARGET_PROTECTED:"Cannot impersonate users with protected roles"},v=Object.fromEntries(Object.keys(_).map(e=>[e,e])),L={CSRF_INVALID:403,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,INTERNAL_ERROR:500,USER_CREATE_FAILED:500,ACCOUNT_LINK_FAILED:500,AUTHORIZATION_URL_FAILED:500,SESSION_VALIDATION_FAILED:500,ACCOUNT_ALREADY_LINKED:409,EMAIL_ALREADY_EXISTS:409,LINKING_NOT_ALLOWED:403,IMPERSONATION_DISABLED:403,IMPERSONATION_NOT_ALLOWED:403,IMPERSONATION_TARGET_PROTECTED:403},R=class extends Error{code;status;redirectUrl;cause;constructor(e,t,r){const n="object"==typeof t?t:r??{};super("string"==typeof t?t:_[e]),this.name="GauError",this.code=e,this.status=n.status??L[e]??400,this.redirectUrl=n.redirectUrl,this.cause=n.cause}toJSON(){return{error:this.message,code:this.code,...this.redirectUrl&&{redirectUrl:this.redirectUrl}}}};function S(e,t){const r=new URL(e,"http://placeholder");return r.searchParams.set("code",t.code),r.searchParams.set("message",t.message),r.searchParams.set("status",String(t.status)),t.redirectUrl&&r.searchParams.set("redirect",t.redirectUrl),r.pathname+r.search}function D(e,t){if("GET"!==e.method)return!1;const r=new URL(e.url).pathname.substring(t.length).split("/").filter(Boolean);return(1!==r.length||"session"!==r[0])&&(1===r.length||2===r.length&&("callback"===r[0]||"link"===r[0]))}async function C(e,t){const{error:r,request:n}=e;if(t.onError)try{const r=await t.onError(e);if(r)return r}catch(e){console.error("onError handler threw:",e)}const o=D(n,t.basePath);if(t.errorRedirect&&o){const e=S(t.errorRedirect,r);return new Response(null,{status:302,headers:{Location:e}})}if(o){const{renderErrorPage:e,htmlResponse:t}=await import("./templates-WVHIDNMP.js");return t(e({title:"Authentication Error",message:r.message,code:r.code,redirectUrl:r.redirectUrl}),r.status)}return new Response(JSON.stringify(r.toJSON()),{status:r.status,headers:{"Content-Type":"application/json; charset=utf-8"}})}async function x(e,t){if(e&&"function"==typeof e.onAfterLinkAccount)try{await e.onAfterLinkAccount(t)}catch(e){console.error("onAfterLinkAccount hook error:",e)}}async function b(n,o,s){const i=o.providerMap.get(s);if(!i)throw new R(v.PROVIDER_NOT_FOUND);const a=new URL(n.url),c=a.searchParams.get("code"),l=a.searchParams.get("state"),d=a.searchParams.get("error");if(!c||!l||d){let r="/";if(l&&l.includes("."))try{const e=l.split(".")[1];r=atob(e??"")||"/"}catch{r="/"}const n=t({redirectUrl:r});return e(n)}const p=u(n.headers.get("Cookie")),g=new h(p,o.cookieOptions);let O,y="/";if(l.includes(".")){const[e,t]=l.split(".");O=e;try{y=atob(t??"")||"/"}catch{y="/"}}else O=l;const U=g.get(f);if(!U||U!==O)throw new R(v.CSRF_INVALID,{redirectUrl:y});const k=g.get(m);if(!k)throw new R(v.PKCE_MISSING,{redirectUrl:y});const N=g.get(E),_=g.get(I);let L;if(_)try{const e=atob(_),t=JSON.parse(e);L=t?.overrides}catch{}const S=g.get(A);S&&g.delete(A);const D=!!S;if(D){if(!await o.validateSession(S)){g.delete(f),g.delete(m),N&&g.delete(E),g.delete(I);const e=te(y);return g.toHeaders().forEach((t,r)=>e.headers.append(r,t)),e}}const{user:C,tokens:b}=await i.validateCallback(c,k,N??void 0,L);{const e=D?await o.validateSession(S):null,t=await async function(e,t){if(!e||"function"!=typeof e.onOAuthExchange)return{handled:!1};try{const r=await e.onOAuthExchange(t);return r&&"object"==typeof r?r:{handled:!1}}catch(e){return console.error("onOAuthExchange hook error:",e),{handled:!1}}}(o,{request:n,providerId:s,state:l,code:c,codeVerifier:k,callbackUri:N,redirectTo:y,cookies:g,providerUser:C,tokens:b,isLinking:D,sessionUserId:e?.user?.id});if(t.handled){g.delete(f),g.delete(m),N&&g.delete(E),g.delete(I);const e=t.response;return g.toHeaders().forEach((t,r)=>e.headers.append(r,t)),e}}const P=await async function(e,t){if(!e||"function"!=typeof e.mapExternalProfile)return t.providerUser;try{const r=await e.mapExternalProfile(t);return r?{...t.providerUser,...r}:t.providerUser}catch(e){return console.error("mapExternalProfile hook error:",e),t.providerUser}}(o,{request:n,providerId:s,providerUser:C,tokens:b,isLinking:D});if(!D&&!0===o.providerMap.get(s)?.linkOnly)throw g.delete(f),g.delete(m),N&&g.delete(E),g.delete(I),new R(v.LINK_ONLY_PROVIDER,{redirectUrl:y});let H=null;const M=await o.getUserByAccount(s,P.id);if(D){if(H=(await o.validateSession(S)).user,!H)throw new R(v.USER_NOT_FOUND,{redirectUrl:y});if(M&&M.id!==H.id)throw new R(v.ACCOUNT_ALREADY_LINKED,{redirectUrl:y});if(!1===o.allowDifferentEmails){const e=H.email,t=P.email;if(e&&t&&e!==t)throw new R(v.EMAIL_MISMATCH,{redirectUrl:y})}if(H){const e={id:H.id};let t=!1;if(o.updateUserInfoOnLink?(P.name&&P.name!==H.name&&(e.name=P.name,t=!0),P.avatar&&P.avatar!==H.image&&(e.image=P.avatar,t=!0)):(!H.name&&P.name&&(e.name=P.name,t=!0),!H.image&&P.avatar&&(e.image=P.avatar,t=!0)),H.email&&P.email&&H.email===P.email&&!0===P.emailVerified&&(!H.emailVerified||o.updateUserInfoOnLink)&&(e.emailVerified=!0,t=!0),t)try{H=await o.updateUser(e)}catch(e){console.error("Failed to update user info on link:",e)}}}else H=M;if(!H){const e=o.autoLink??"verifiedEmail";if(P.email&&("always"===e||"verifiedEmail"===e&&!0===P.emailVerified)){const e=await o.getUserByEmail(P.email);e&&(H=P.emailVerified&&!e.emailVerified?await o.updateUser({id:e.id,emailVerified:!0}):e)}if(!H)try{if(P.email&&!0===P.emailVerified&&!1===o.autoLink){if(await o.getUserByEmail(P.email))throw new R(v.EMAIL_ALREADY_EXISTS,{redirectUrl:y})}let e;try{e=o.roles.resolveOnCreate?.({providerId:s,profile:P,request:n})}catch(e){console.error("roles.resolveOnCreate threw:",e)}const t=!0===P.emailVerified?P.email:null;H=await o.createUser({name:P.name,email:t,image:P.avatar,emailVerified:P.emailVerified,role:e??o.roles.defaultRole})}catch(e){if(e instanceof R)throw e;throw console.error("Failed to create user:",e),new R(v.USER_CREATE_FAILED,{cause:e,redirectUrl:y})}}if(H&&P.email){const{email:e,emailVerified:t}=H,{email:r,emailVerified:n}=P,s={id:H.id};let i=!1;if(e||!0!==n?e!==r||!0!==n||t||(s.emailVerified=!0,i=!0):(s.email=r,s.emailVerified=!0,i=!0),i)try{H=await o.updateUser(s)}catch(e){console.error("Failed to update user after sign-in:",e)}}if(M)try{const e=(await o.getAccounts(H.id)).find(e=>e.provider===s&&e.providerAccountId===P.id);if(e&&o.updateAccount){let t,r,i,a;try{t=b.refreshToken()}catch{t=e.refreshToken??null}try{const e=b.accessTokenExpiresAt();e&&(r=Math.floor(e.getTime()/1e3))}catch{r=e.expiresAt??void 0}try{i=b.idToken()}catch{i=e.idToken??null}try{a=b.scopes()?.join(" ")??e.scope??null}catch{a=e.scope??null}await o.updateAccount({userId:H.id,provider:s,providerAccountId:P.id,accessToken:b.accessToken()??e.accessToken??void 0,refreshToken:t,expiresAt:r??e.expiresAt??void 0,tokenType:b.tokenType?.()??e.tokenType??null,scope:a,idToken:i}),await x(o,{request:n,providerId:s,userId:H.id,providerUser:P,tokens:b,action:"update"})}}catch(e){console.error("Failed to update account tokens on sign-in:",e)}else{let e,t,r;try{e=b.refreshToken()}catch{e=null}try{const e=b.accessTokenExpiresAt();e&&(t=Math.floor(e.getTime()/1e3))}catch{}try{r=b.idToken()}catch{r=null}{const e=await async function(e,t){if(!e||"function"!=typeof e.onBeforeLinkAccount)return{allow:!0};try{return await e.onBeforeLinkAccount(t)||{allow:!0}}catch(e){return console.error("onBeforeLinkAccount hook error:",e),{allow:!0}}}(o,{request:n,providerId:s,userId:H.id,providerUser:P,tokens:b});if(!1===e.allow){const t=e.response??(()=>{throw new R(v.LINKING_NOT_ALLOWED,{redirectUrl:y})})();return g.toHeaders().forEach((e,r)=>t.headers.append(r,e)),t}}try{let i;try{i=b.scopes()?.join(" ")??null}catch{i=null}await o.linkAccount({userId:H.id,provider:s,providerAccountId:P.id,accessToken:b.accessToken(),refreshToken:e,expiresAt:t,tokenType:b.tokenType?.()??null,scope:i,idToken:r}),await x(o,{request:n,providerId:s,userId:H.id,providerUser:P,tokens:b,action:"link"})}catch(e){throw console.error("Error linking account:",e),new R(v.ACCOUNT_LINK_FAILED,{cause:e,redirectUrl:y})}}const F=await o.createSession(H.id),V=new URL(n.url),K=new URL(y,n.url),W="token"===o.sessionStrategy,j="cookie"===o.sessionStrategy,B="http:"!==K.protocol&&"https:"!==K.protocol,J=V.host!==K.host;if(W||!j&&(B||J)){const t=new URL(K),n=g.get(T);if(!n)throw new R(v.PKCE_CHALLENGE_MISSING,{redirectUrl:y});{const e=await o.signJWT({sub:H.id,challenge:n},{ttl:60});t.searchParams.set("code",e)}const s=r({redirectUrl:t.toString()});g.delete(f),g.delete(m),N&&g.delete(E),g.delete(I),g.delete(T);const i=e(s);return g.toHeaders().forEach((e,t)=>{i.headers.append(t,e)}),i}g.set(w,F,{maxAge:o.jwt.ttl,sameSite:o.development?"lax":"none",secure:!o.development}),g.delete(f),g.delete(m),N&&g.delete(E),g.delete(I);let G;if("false"===a.searchParams.get("redirect")){const e=await o.getAccounts(H.id),t=Boolean(H.role&&o.roles.adminRoles.includes(H.role)||o.roles.adminUserIds.includes(H.id));G=ee({user:{...H,isAdmin:t,accounts:e}})}else G=te(y);return g.toHeaders().forEach((e,t)=>{G.headers.append(t,e)}),G}function P(e,t){if(!1===t.cors)return!1;const r=t.cors;if("all"===r.allowedOrigins)return!0;if("trust"===r.allowedOrigins){if("all"===t.trustHosts)return!0;try{const r=new URL(e);return t.trustHosts.includes(r.host)||t.trustHosts.includes(r.hostname)}catch{return!1}}if(r.allowedOrigins.includes("*"))return!0;try{const t=new URL(e);return r.allowedOrigins.includes(e)||r.allowedOrigins.includes(t.origin)||r.allowedOrigins.includes(t.host)||r.allowedOrigins.includes(t.hostname)}catch{return r.allowedOrigins.includes(e)}}function H(e,t,r){if(!1===r.cors)return t;const n=e.headers.get("Origin")||e.headers.get("origin");if(!n)return t;if(!P(n,r))return t;const o=r.cors;t.headers.set("Vary","Origin");const s=o.allowCredentials,i="all"!==o.allowedOrigins||s?n:"*";return t.headers.set("Access-Control-Allow-Origin",i),s&&t.headers.set("Access-Control-Allow-Credentials","true"),t.headers.set("Access-Control-Allow-Headers",o.allowedHeaders.join(", ")),t.headers.set("Access-Control-Allow-Methods",o.allowedMethods.join(", ")),o.exposeHeaders?.length&&t.headers.set("Access-Control-Expose-Headers",o.exposeHeaders.join(", ")),t}function M(e,t){if(!1===t.cors)return new Response(null,{status:204});const r=e.headers.get("Origin")||e.headers.get("origin"),n=t.cors,o={};if(r&&P(r,t)){const e=n.allowCredentials,t="all"!==n.allowedOrigins||e?r:"*";o["Access-Control-Allow-Origin"]=t,e&&(o["Access-Control-Allow-Credentials"]="true")}return o["Access-Control-Allow-Headers"]=n.allowedHeaders.join(", "),o["Access-Control-Allow-Methods"]=n.allowedMethods.join(", "),null!=n.maxAge&&(o["Access-Control-Max-Age"]=String(n.maxAge)),n.exposeHeaders?.length&&(o["Access-Control-Expose-Headers"]=n.exposeHeaders.join(", ")),new Response(null,{status:204,headers:o})}import{generateCodeVerifier as F,generateState as V}from"arctic";function K(e,t,r){if("all"===t)return!0;const n=e.headers.get("origin");if(!n)return!1;let o;try{o=new URL(n).host}catch{return!1}if(r){if(o.startsWith("localhost")||o.startsWith("127.0.0.1"))return!0}const s=new URL(e.url),i=s.host;return n===`${s.protocol}//${i}`||t.includes(o)}async function W(e,t,r,n){const o=t.providerMap.get(r);if(!o)throw new R(v.PROVIDER_NOT_FOUND);const{state:s,codeVerifier:i}={state:V(),codeVerifier:F()},a=new URL(e.url),c=a.searchParams.get("redirectTo"),l=a.searchParams.get("profile"),d=a.searchParams.get("prompt");if(c){let r;try{if(c.startsWith("//"))throw new Error("Protocol-relative URL not allowed");r=new URL(c,a.origin)}catch{throw new R(v.INVALID_REDIRECT_URL,'Invalid "redirectTo" URL',{status:400})}const n=r.host,o=n===new URL(e.url).host,s="all"===t.trustHosts||t.trustHosts.includes(n);if(("http:"===r.protocol||"https:"===r.protocol)&&!o&&!s)throw new R(v.UNTRUSTED_HOST)}const w=c?`${s}.${btoa(c)}`:s;let p,g,O,y,U=a.searchParams.get("callbackUri");if(!U&&o.requiresRedirectUri&&(U=`${a.origin}${t.basePath}/callback/${r}`),l){const e=(t.profiles?.[r]??{})[l];if(!e)throw new R(v.UNKNOWN_PROFILE,`Unknown profile "${l}" for provider "${r}"`,{status:400});e.redirectUri&&(U=e.redirectUri),e.scopes&&(p=e.scopes),e.params&&(g={...e.params??{}});const{tenant:o,prompt:s}=e;if(null==o&&null==s||(O={...O??{},tenant:o,prompt:s}),!n&&!0===e.linkOnly)throw new R(v.LINK_ONLY_PROVIDER,"This profile is link-only. Please link it to an existing account.",{status:400})}if(d&&(g={...g??{},prompt:d}),!n&&!0===o.linkOnly)throw new R(v.LINK_ONLY_PROVIDER);try{y=await o.getAuthorizationUrl(w,i,{redirectUri:U??void 0,scopes:p,params:g,overrides:O})}catch(e){console.error("Error getting authorization URL:",e),y=null}if(!y)throw new R(v.AUTHORIZATION_URL_FAILED,"Could not create authorization URL",{status:500});const k=u(e.headers.get("Cookie")),N=new h(k,t.cookieOptions),_={maxAge:600,sameSite:t.development?"lax":"none",secure:!t.development};N.set(f,s,_),N.set(m,i,_),n?N.set(A,n,_):N.delete(A,{sameSite:t.development?"lax":"none",secure:!t.development}),U&&N.set(E,U,_);const L=JSON.stringify({params:g??{},overrides:O??{}});N.set(I,btoa(L),_);const S=a.searchParams.get("code_challenge");S&&N.set(T,S,_);if("false"===a.searchParams.get("redirect")){const e=ee({url:y.toString()});return N.toHeaders().forEach((t,r)=>{e.headers.append(r,t)}),e}const D=te(y.toString());return N.toHeaders().forEach((e,t)=>{D.headers.append(t,e)}),D}async function j(e,t,r){const n=new URL(e.url);let o=k(e).token;if(o||(o=n.searchParams.get("token")??void 0),!o)throw new R(v.UNAUTHORIZED);if(!await t.validateSession(o))throw new R(v.UNAUTHORIZED);n.searchParams.delete("token");return W(new Request(n.toString(),e),t,r,o)}async function B(e,t,r){const n=k(e).token;if(!n)throw new R(v.UNAUTHORIZED);const o=await t.validateSession(n);if(!o||!o.user)throw new R(v.UNAUTHORIZED);const s=o.accounts??[];if(s.length<=1)throw new R(v.CANNOT_UNLINK_LAST_ACCOUNT);const i=s.find(e=>e.provider===r);if(!i)throw new R(v.ACCOUNT_NOT_LINKED,`Provider "${r}" not linked`);await t.unlinkAccount(r,i.providerAccountId);if((await t.getAccounts(o.user.id)).length>0&&o.user.email)try{await t.updateUser({id:o.user.id,email:null,emailVerified:!1})}catch(e){console.error("Failed to clear stale email after unlinking:",e)}return ee({message:"Account unlinked successfully"})}async function J(e,t,r){return W(e,t,r,null)}async function G(e,t){const r=u(e.headers.get("Cookie")),n=new h(r,t.cookieOptions);n.delete(w,{sameSite:t.development?"lax":"none",secure:!t.development}),n.delete(A,{sameSite:t.development?"lax":"none",secure:!t.development});const o=ee({message:"Signed out"});return n.toHeaders().forEach((e,t)=>{o.headers.append(t,e)}),o}async function q(e,t){const{token:r}=k(e),n=Array.from(t.providerMap.keys());if(!r)return ee({...z,providers:n});try{const e=await t.validateSession(r);return e?ee({...X(e),providers:n}):ee({...z,providers:n},{status:401})}catch(e){throw console.error("Error validating session:",e),new R(v.SESSION_VALIDATION_FAILED,{cause:e})}}async function Y(e,t){if("POST"!==e.method)throw new R(v.METHOD_NOT_ALLOWED);let r;try{r=await e.json()}catch{throw new R(v.INVALID_REQUEST,"Invalid JSON body",{status:400})}const{code:n,codeVerifier:o}=r;if(!n||!o)throw new R(v.INVALID_REQUEST,"Missing code or codeVerifier",{status:400});const s=await t.verifyJWT(n);if(!s)throw new R(v.TOKEN_EXPIRED,"Invalid or expired code");const{sub:i,challenge:a}=s,c=(new TextEncoder).encode(o),l=await crypto.subtle.digest("SHA-256",c),d=Array.from(new Uint8Array(l));if(a!==btoa(String.fromCharCode(...d)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""))throw new R(v.CODE_VERIFIER_INVALID);return ee({token:await t.createSession(i)})}function Z(e){const{basePath:t}=e;return async function(r){if("OPTIONS"===r.method)return M(r,e);const n=new URL(r.url);if(!n.pathname.startsWith(t)){const n=new R(v.NOT_FOUND);return H(r,await C({error:n,request:r},{basePath:t,onError:e.onError,errorRedirect:e.errorRedirect}),e)}try{if("POST"===r.method&&!K(r,e.trustHosts,e.development)){const t=r.headers.get("origin")??"unknown",n=e.development?`Untrusted origin: '${t}'. Add this origin to 'trustHosts' in createAuth() or ensure you are using 'localhost' or '127.0.0.1' for development.`:"Forbidden";throw new R(v.FORBIDDEN,n,{status:403})}const o=n.pathname.substring(t.length).split("/").filter(Boolean),s=o[0];if(!s)throw new R(v.NOT_FOUND);let i;if("GET"===r.method)if("session"===s)i=await q(r,e);else if(2===o.length&&"link"===o[0])i=await j(r,e,o[1]);else if(2===o.length&&"callback"===o[0])i=await b(r,e,o[1]);else{if(1!==o.length)throw new R(v.NOT_FOUND);i=await J(r,e,s)}else{if("POST"!==r.method)throw new R(v.METHOD_NOT_ALLOWED);if(1===o.length&&"signout"===s)i=await G(r,e);else if(1===o.length&&"token"===s)i=await Y(r,e);else{if(2!==o.length||"unlink"!==o[0])throw new R(v.NOT_FOUND);i=await B(r,e,o[1])}}try{i.headers.set("Cache-Control","no-store, private"),i.headers.set("Pragma","no-cache"),i.headers.set("Expires","0")}catch{}return H(r,i,e)}catch(n){if(n instanceof R){return H(r,await C({error:n,request:r},{basePath:t,onError:e.onError,errorRedirect:e.errorRedirect}),e)}console.error("Unexpected error in gau handler:",n);const o=new R(v.INTERNAL_ERROR,{cause:n});return H(r,await C({error:o,request:r},{basePath:t,onError:e.onError,errorRedirect:e.errorRedirect}),e)}}}var z={user:null,session:null,accounts:null};function X(e){return{user:e.user,session:e.session,accounts:e.accounts?.map(e=>({provider:e.provider,providerAccountId:e.providerAccountId}))??null,providers:e.providers}}var Q=class extends Error{cause;constructor(e,t){super(e),this.name="AuthError",this.cause=t}};function ee(e,t={}){const r=new Headers(t.headers);return r.has("Content-Type")||r.set("Content-Type","application/json; charset=utf-8"),new Response(JSON.stringify(e),{...t,headers:r})}function te(e,t=302){return new Response(null,{status:t,headers:{Location:e}})}var re="X-Refreshed-Token";function ne(e){return null!=e?.impersonatedBy}async function oe(e){try{const t=function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=(4-t.length%4)%4,n=t.padEnd(t.length+r,"=");try{const e=atob(n),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return r}catch{throw new Q("Invalid base64url string")}}(e),r=await crypto.subtle.importKey("pkcs8",t.slice(),{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),n=await crypto.subtle.exportKey("jwk",r);delete n.d,n.key_ops=["verify"];return{privateKey:r,publicKey:await crypto.subtle.importKey("jwk",n,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"])}}catch(e){if(e instanceof Q)throw e;throw new Q("Invalid secret. Must be a base64url-encoded PKCS#8 private key for ES256. Use `bunx gau secret` to generate one.",e)}}async function se(e,t={}){let{algorithm:r="ES256",ttl:s,iss:i,aud:a,sub:c,privateKey:l,secret:d}=t;if("ES256"===r){if(!l){if("string"!=typeof d)throw new Q("Missing secret for ES256 signing. It must be a base64url-encoded string.");({privateKey:l}=await oe(d))}}else if("HS256"===r&&!d)throw new Q("Missing secret for HS256 signing");const u=Math.floor(Date.now()/1e3),h={iat:u,iss:i,aud:a,sub:c,...e};null!=s&&s>0&&(h.exp=u+s);const f="HS256"===r,w=f?"HS256":"ES256",p=JSON.stringify({alg:w,typ:"JWT"}),g=JSON.stringify(h),A=n(p,g);let m;if(f){const e="string"==typeof d?(new TextEncoder).encode(d):d,t=await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);m=new Uint8Array(await crypto.subtle.sign("HMAC",t,A))}else m=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},l,A));return o(p,g,m)}async function ie(e,t){let{algorithm:r="ES256",publicKey:n,secret:o,iss:c,aud:l}=t;if("ES256"===r&&!n){if("string"!=typeof o)throw new Q("Missing secret for ES256 verification. Must be a base64url-encoded string.");({publicKey:n}=await oe(o))}if("HS256"===r&&!o)throw new Q("Missing secret for HS256 verification");const[d,u,h,f]=a(e),w=new s(d).algorithm();let p=!1;if("HS256"===r){if("HS256"!==w)throw new Error(`JWT algorithm is "${w}", but verifier was configured for "HS256"`);const e="string"==typeof o?(new TextEncoder).encode(o):o,t=await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);p=function(e,t){let r=e.length^t.length;const n=Math.max(e.length,t.length);for(let o=0;o<n;o++)r|=(e[o]??0)^(t[o]??0);return 0===r}(new Uint8Array(await crypto.subtle.sign("HMAC",t,f)),new Uint8Array(h))}else{if("ES256"!==w)throw new Q(`JWT algorithm is "${w}", but verifier was configured for "ES256"`);const e=new Uint8Array(h);if(p=await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},n,e,f),!p&&64===e.length)try{const t=function(e){if(64!==e.length)throw new Error("Invalid raw signature length");let t=e.slice(0,32),r=e.slice(32),n=0;for(;n<t.length-1&&0===t[n];)n++;t=t.slice(n);let o=0;for(;o<r.length-1&&0===r[o];)o++;if(r=r.slice(o),t.length>0&&128&t[0]){const e=new Uint8Array(t.length+1);e[0]=0,e.set(t,1),t=e}if(r.length>0&&128&r[0]){const e=new Uint8Array(r.length+1);e[0]=0,e.set(r,1),r=e}const s=t.length,i=r.length,a=2+s+2+i,c=new Uint8Array(2+a);return c[0]=48,c[1]=a,c[2]=2,c[3]=s,c.set(t,4),c[4+s]=2,c[5+s]=i,c.set(r,6+s),c}(e);p=await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},n,t,f)}catch{p=!1}}if(!p)throw new Q("Invalid JWT signature");const g=new i(u);if(g.hasExpiration()&&!g.verifyExpiration())throw new Q("JWT expired");if(g.hasNotBefore()&&!g.verifyNotBefore())throw new Q("JWT not yet valid");if(c&&u.iss!==c)throw new Q("Invalid JWT issuer");if(l){const e=Array.isArray(l)?l:[l],t=u.aud?Array.isArray(u.aud)?u.aud:[u.aud]:[];if(!e.some(e=>t.includes(e)))throw new Q("Invalid JWT audience")}return u}export{d as DEFAULT_COOKIE_SERIALIZE_OPTIONS,u as parseCookies,h as Cookies,f as CSRF_COOKIE_NAME,w as SESSION_COOKIE_NAME,p as SESSION_STASH_COOKIE_NAME,g as SESSION_STRATEGY_COOKIE_NAME,A as LINKING_TOKEN_COOKIE_NAME,m as PKCE_COOKIE_NAME,E as CALLBACK_URI_COOKIE_NAME,I as PROVIDER_OPTIONS_COOKIE_NAME,T as CLIENT_CHALLENGE_COOKIE_NAME,O as CSRF_MAX_AGE,se as sign,ie as verify,k as getSessionTokenFromRequest,N as createAuth,_ as ErrorMessages,v as ErrorCodes,L as ErrorStatuses,R as GauError,S as createErrorRedirectUrl,D as isUserFacingRequest,C as handleError,b as handleCallback,H as applyCors,M as handlePreflight,K as verifyRequestOrigin,j as handleLink,B as handleUnlink,J as handleSignIn,G as handleSignOut,q as handleSession,Y as handleToken,Z as createHandler,z as NULL_SESSION,X as toClientSession,Q as AuthError,ee as json,te as redirect,re as REFRESHED_TOKEN_HEADER,ne as isImpersonating};//# sourceMappingURL=chunk-NX4HKWJR.js.map
|
|
1
|
+
import{htmlResponse as e,renderCancelledPage as t,renderSuccessPage as r}from"./chunk-5KEP3AIT.js";import{createJWTSignatureMessage as n,encodeJWT as o,JWSRegisteredHeaders as s,JWTRegisteredClaims as i,parseJWT as a}from"@oslojs/jwt";import{parse as c,serialize as l}from"cookie";var d={path:"/",sameSite:"lax",secure:!0,httpOnly:!0};function u(e){const t=new Map;if(e){const r=c(e);for(const e in r)t.set(e,r[e])}return t}var h=class{constructor(e,t){this.requestCookies=e,this.defaultOptions=t}#e=[];get(e){return this.requestCookies.get(e)}set(e,t,r){const n={...this.defaultOptions,...r};this.#e.push([e,t,n])}delete(e,t){this.set(e,"",{...t,expires:new Date(0),maxAge:0})}toHeaders(){const e=new Headers;for(const[t,r,n]of this.#e)e.append("Set-Cookie",l(t,r,n));return e}},f="__gau-csrf-token",w="__gau-session-token",p="__gau-session-stash",g="__gau-session-strategy",A="__gau-linking-token",m="__gau-pkce-code-verifier",E="__gau-callback-uri",I="__gau-provider-options",T="__gau-client-challenge",O=600;import{parse as y,serialize as U}from"cookie";function k(e){const t=u(e.headers.get("Cookie")).get(w);if(t)return{token:t,source:"cookie"};const r=e.headers.get("Authorization");return r?.startsWith("Bearer ")?{token:r.substring(7),source:"bearer"}:{}}function N({adapter:e,providers:t,basePath:r="/api/auth",jwt:n={},session:o={},cookies:s={},onOAuthExchange:i,mapExternalProfile:a,onBeforeLinkAccount:c,onAfterLinkAccount:l,trustHosts:u=[],autoLink:h="verifiedEmail",allowDifferentEmails:f=!0,updateUserInfoOnLink:g=!1,roles:A={},cors:m=!0,profiles:E,onError:I,errorRedirect:T,impersonation:O}){const{algorithm:N="ES256",secret:_,iss:L,aud:S,ttl:D=604800}=n,C={...d,...s},x=o.strategy??"auto";if("ES256"===N&&void 0!==_&&"string"!=typeof _)throw new Q("For ES256, the secret option must be a string.");const b=new Map(t.map(e=>[e.id,e])),P=!1!==m&&{allowedOrigins:(!0===m?"all":m.allowedOrigins)??"all",allowCredentials:(!0===m||m.allowCredentials)??!0,allowedHeaders:(!0===m?void 0:m.allowedHeaders)??["Content-Type","Authorization","Cookie"],allowedMethods:(!0===m?void 0:m.allowedMethods)??["GET","POST","OPTIONS"],exposeHeaders:!0===m?void 0:m.exposeHeaders,maxAge:!0===m?void 0:m.maxAge},H=E??{},M={defaultRole:A.defaultRole??"user",resolveOnCreate:A.resolveOnCreate,adminRoles:A.adminRoles??["admin"],adminUserIds:A.adminUserIds??[]},F=O?.enabled?{enabled:!0,allowedRoles:O.allowedRoles??M.adminRoles,cannotImpersonate:O.cannotImpersonate??M.adminRoles,maxTTL:O.maxTTL??3600,onImpersonate:O.onImpersonate}:null;async function V(e,t={}){return se(e,function(e={}){const t={ttl:e.ttl,iss:e.iss??L,aud:e.aud??S,sub:e.sub};if("HS256"===N)return{algorithm:N,secret:e.secret??_,...t};{if(void 0!==e.secret&&"string"!=typeof e.secret)throw new Q("For ES256, the secret option must be a string.");const r=e.secret??_;return{algorithm:N,privateKey:e.privateKey,secret:r,...t}}}(t))}async function K(e,t={}){const r=function(e={}){const t={iss:e.iss??L,aud:e.aud??S};if("HS256"===N)return{algorithm:N,secret:e.secret??_,...t};{if(void 0!==e.secret&&"string"!=typeof e.secret)throw new Q("For ES256, the secret option must be a string.");const r=e.secret??_;return{algorithm:N,publicKey:e.publicKey,secret:r,...t}}}(t);try{return await ie(e,r)}catch{return null}}async function W(e,t={},r=D){return V({sub:e,...t},{ttl:r})}async function j(e,t={}){const{data:r={},ttl:n=D}=t,o=await W(e,r,n),s={...C,maxAge:n};return{token:o,cookie:U(w,o,s),cookieName:w,maxAge:n}}return{...e,providerMap:b,basePath:r,cookieOptions:C,jwt:{ttl:D},onOAuthExchange:i,mapExternalProfile:a,onBeforeLinkAccount:c,onAfterLinkAccount:l,signJWT:V,verifyJWT:K,createSession:W,validateSession:async function(t){const r=await K(t);if(!r)return null;const n=await e.getUserAndAccounts(r.sub);if(!n)return null;const{user:o,accounts:s}=n,i=Boolean(o&&(o.role&&M.adminRoles.includes(o.role)||M.adminUserIds.length>0&&M.adminUserIds.includes(o.id)));return{user:o?{...o,isAdmin:i}:null,session:{id:t,...r},accounts:s}},issueSession:j,refreshSession:async function(t,r={}){let n,o;if("string"==typeof t)n=t,o="token";else{const e=k(t);if(!e.token||!e.source)return null;n=e.token,o=e.source}const s=await K(n);if(!s||!s.sub)return null;if(null!=r.threshold&&r.threshold>0&&r.threshold<1){const{iat:e}=s;if(e){if(Math.floor(Date.now()/1e3)-e<(r.ttl??D)*r.threshold)return null}}if(!await e.getUser(s.sub))return null;const{sub:i,iat:a,exp:c,iss:l,aud:d,nbf:u,jti:h,...f}=s;return{...await j(s.sub,{data:f,ttl:r.ttl}),source:o}},getAccessToken:async function(t,r){const n=b.get(r);if(!n)return null;const o=(await e.getAccounts(t)).find(e=>e.provider===r);if(!o||!o.accessToken)return null;const s=Math.floor(Date.now()/1e3);if(!("number"==typeof o.expiresAt&&o.expiresAt<=s))return{accessToken:o.accessToken,expiresAt:o.expiresAt??null};if(!o.refreshToken||!n.refreshAccessToken)return null;try{const r=await n.refreshAccessToken(o.refreshToken,{}),s={userId:t,provider:o.provider,providerAccountId:o.providerAccountId,accessToken:r.accessToken??o.accessToken,refreshToken:r.refreshToken??o.refreshToken,expiresAt:r.expiresAt??null,idToken:r.idToken??o.idToken??null,tokenType:r.tokenType??o.tokenType??null,scope:r.scope??o.scope??null};return await(e.updateAccount?.(s)),{accessToken:s.accessToken,expiresAt:s.expiresAt}}catch{return null}},trustHosts:u,autoLink:h,allowDifferentEmails:f,profiles:H,updateUserInfoOnLink:g,sessionStrategy:x,development:!1,roles:M,cors:P,onError:I,errorRedirect:T,startImpersonation:async function(t,r,n={}){if(!F)throw new R(v.IMPERSONATION_DISABLED);const o=await e.getUser(t);if(!o)throw new R(v.USER_NOT_FOUND,`Admin user "${t}" not found`);const s=!!o.role&&F.allowedRoles.includes(o.role),i=M.adminUserIds.includes(t);if(!s&&!i)throw new R(v.IMPERSONATION_NOT_ALLOWED);const a=await e.getUser(r);if(!a)throw new R(v.USER_NOT_FOUND,`Target user "${r}" not found`);if(a.role&&F.cannotImpersonate.includes(a.role))throw new R(v.IMPERSONATION_TARGET_PROTECTED);F.onImpersonate&&await F.onImpersonate({adminUserId:t,targetUserId:r,reason:n.reason,timestamp:Date.now()});const c=Math.min(n.ttl??F.maxTTL,F.maxTTL),l=Math.floor(Date.now()/1e3)+c,d=await W(r,{impersonatedBy:t,impersonationExpiresAt:l},c),u={...C,maxAge:c},h=U(w,d,u),f=await V({adminUserId:t},{ttl:2*F.maxTTL});return{token:d,cookie:h,originalCookie:U(p,f,u),maxAge:c}},endImpersonation:async function(t){const r=t.headers.get("cookie");if(!r)return null;const n=y(r)[p];if(!n)return null;const o=await K(n);if(!o?.adminUserId)return null;if(!await e.getUser(o.adminUserId))return null;const s=await j(o.adminUserId),i=U(p,"",{...C,expires:new Date(0),maxAge:0});return{token:s.token,cookie:s.cookie,clearCookies:[i]}},impersonation:F}}var _={CSRF_INVALID:"Invalid CSRF token",PKCE_MISSING:"Missing PKCE code verifier",PKCE_CHALLENGE_MISSING:"Missing PKCE challenge",OAUTH_CANCELLED:"Authentication was cancelled",PROVIDER_NOT_FOUND:"Provider not found",AUTHORIZATION_URL_FAILED:"Could not create authorization URL",USER_NOT_FOUND:"User not found",USER_CREATE_FAILED:"Failed to create user",ACCOUNT_ALREADY_LINKED:"Account already linked to another user",ACCOUNT_LINK_FAILED:"Failed to link account",ACCOUNT_NOT_LINKED:"Account not linked",CANNOT_UNLINK_LAST_ACCOUNT:"Cannot unlink the last account",EMAIL_ALREADY_EXISTS:"An account with this email already exists",EMAIL_MISMATCH:"Email mismatch between existing account and provider",LINKING_NOT_ALLOWED:"Linking not allowed",LINK_ONLY_PROVIDER:"Sign-in with this provider is disabled. Please link it to an existing account.",UNAUTHORIZED:"Unauthorized",FORBIDDEN:"Forbidden",SESSION_INVALID:"Invalid session",SESSION_VALIDATION_FAILED:"Failed to validate session",TOKEN_INVALID:"Invalid token",TOKEN_EXPIRED:"Token expired",CODE_VERIFIER_INVALID:"Invalid code verifier",NOT_FOUND:"Not found",METHOD_NOT_ALLOWED:"Method not allowed",INVALID_REQUEST:"Invalid request",INVALID_REDIRECT_URL:"Invalid redirect URL",UNTRUSTED_HOST:"Untrusted redirect host",UNKNOWN_PROFILE:"Unknown profile",INTERNAL_ERROR:"An unexpected error occurred",IMPERSONATION_DISABLED:"Impersonation is not enabled",IMPERSONATION_NOT_ALLOWED:"You are not allowed to impersonate users",IMPERSONATION_TARGET_PROTECTED:"Cannot impersonate users with protected roles"},v=Object.fromEntries(Object.keys(_).map(e=>[e,e])),L={CSRF_INVALID:403,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,INTERNAL_ERROR:500,USER_CREATE_FAILED:500,ACCOUNT_LINK_FAILED:500,AUTHORIZATION_URL_FAILED:500,SESSION_VALIDATION_FAILED:500,ACCOUNT_ALREADY_LINKED:409,EMAIL_ALREADY_EXISTS:409,LINKING_NOT_ALLOWED:403,IMPERSONATION_DISABLED:403,IMPERSONATION_NOT_ALLOWED:403,IMPERSONATION_TARGET_PROTECTED:403},R=class extends Error{code;status;redirectUrl;cause;constructor(e,t,r){const n="object"==typeof t?t:r??{};super("string"==typeof t?t:_[e]),this.name="GauError",this.code=e,this.status=n.status??L[e]??400,this.redirectUrl=n.redirectUrl,this.cause=n.cause}toJSON(){return{error:this.message,code:this.code,...this.redirectUrl&&{redirectUrl:this.redirectUrl}}}};function S(e,t){const r=new URL(e,"http://placeholder");return r.searchParams.set("code",t.code),r.searchParams.set("message",t.message),r.searchParams.set("status",String(t.status)),t.redirectUrl&&r.searchParams.set("redirect",t.redirectUrl),r.pathname+r.search}function D(e,t){if("GET"!==e.method)return!1;const r=new URL(e.url).pathname.substring(t.length).split("/").filter(Boolean);return(1!==r.length||"session"!==r[0])&&(1===r.length||2===r.length&&("callback"===r[0]||"link"===r[0]))}async function C(e,t){const{error:r,request:n}=e;if(t.onError)try{const r=await t.onError(e);if(r)return r}catch(e){console.error("onError handler threw:",e)}const o=D(n,t.basePath);if(t.errorRedirect&&o){const e=S(t.errorRedirect,r);return new Response(null,{status:302,headers:{Location:e}})}if(o){const{renderErrorPage:e,htmlResponse:t}=await import("./templates-WVHIDNMP.js");return t(e({title:"Authentication Error",message:r.message,code:r.code,redirectUrl:r.redirectUrl}),r.status)}return new Response(JSON.stringify(r.toJSON()),{status:r.status,headers:{"Content-Type":"application/json; charset=utf-8"}})}async function x(e,t){if(e&&"function"==typeof e.onAfterLinkAccount)try{await e.onAfterLinkAccount(t)}catch(e){console.error("onAfterLinkAccount hook error:",e)}}async function b(n,o,s){const i=o.providerMap.get(s);if(!i)throw new R(v.PROVIDER_NOT_FOUND);const a=new URL(n.url),c=a.searchParams.get("code"),l=a.searchParams.get("state"),d=a.searchParams.get("error");if(!c||!l||d){let r="/";if(l&&l.includes("."))try{const e=l.split(".")[1];r=atob(e??"")||"/"}catch{r="/"}const n=t({redirectUrl:r});return e(n)}const p=u(n.headers.get("Cookie")),g=new h(p,o.cookieOptions);let O,y="/";if(l.includes(".")){const[e,t]=l.split(".");O=e;try{y=atob(t??"")||"/"}catch{y="/"}}else O=l;const U=g.get(f);if(!U||U!==O)throw new R(v.CSRF_INVALID,{redirectUrl:y});const k=g.get(m);if(!k)throw new R(v.PKCE_MISSING,{redirectUrl:y});const N=g.get(E),_=g.get(I);let L;if(_)try{const e=atob(_),t=JSON.parse(e);L=t?.overrides}catch{}const S=g.get(A);S&&g.delete(A);const D=!!S;if(D){if(!await o.validateSession(S)){g.delete(f),g.delete(m),N&&g.delete(E),g.delete(I);const e=te(y);return g.toHeaders().forEach((t,r)=>e.headers.append(r,t)),e}}const{user:C,tokens:b}=await i.validateCallback(c,k,N??void 0,L);{const e=D?await o.validateSession(S):null,t=await async function(e,t){if(!e||"function"!=typeof e.onOAuthExchange)return{handled:!1};try{const r=await e.onOAuthExchange(t);return r&&"object"==typeof r?r:{handled:!1}}catch(e){return console.error("onOAuthExchange hook error:",e),{handled:!1}}}(o,{request:n,providerId:s,state:l,code:c,codeVerifier:k,callbackUri:N,redirectTo:y,cookies:g,providerUser:C,tokens:b,isLinking:D,sessionUserId:e?.user?.id});if(t.handled){g.delete(f),g.delete(m),N&&g.delete(E),g.delete(I);const e=t.response;return g.toHeaders().forEach((t,r)=>e.headers.append(r,t)),e}}const P=await async function(e,t){if(!e||"function"!=typeof e.mapExternalProfile)return t.providerUser;try{const r=await e.mapExternalProfile(t);return r?{...t.providerUser,...r}:t.providerUser}catch(e){return console.error("mapExternalProfile hook error:",e),t.providerUser}}(o,{request:n,providerId:s,providerUser:C,tokens:b,isLinking:D});if(!D&&!0===o.providerMap.get(s)?.linkOnly)throw g.delete(f),g.delete(m),N&&g.delete(E),g.delete(I),new R(v.LINK_ONLY_PROVIDER,{redirectUrl:y});let H=null;const M=await o.getUserByAccount(s,P.id);if(D){if(H=(await o.validateSession(S)).user,!H)throw new R(v.USER_NOT_FOUND,{redirectUrl:y});if(M&&M.id!==H.id)throw new R(v.ACCOUNT_ALREADY_LINKED,{redirectUrl:y});if(!1===o.allowDifferentEmails){const e=H.email,t=P.email;if(e&&t&&e!==t)throw new R(v.EMAIL_MISMATCH,{redirectUrl:y})}if(H){const e={id:H.id};let t=!1;if(o.updateUserInfoOnLink?(P.name&&P.name!==H.name&&(e.name=P.name,t=!0),P.avatar&&P.avatar!==H.image&&(e.image=P.avatar,t=!0)):(!H.name&&P.name&&(e.name=P.name,t=!0),!H.image&&P.avatar&&(e.image=P.avatar,t=!0)),H.email&&P.email&&H.email===P.email&&!0===P.emailVerified&&(!H.emailVerified||o.updateUserInfoOnLink)&&(e.emailVerified=!0,t=!0),t)try{H=await o.updateUser(e)}catch(e){console.error("Failed to update user info on link:",e)}}}else H=M;if(!H){const e=o.autoLink??"verifiedEmail";if(P.email&&("always"===e||"verifiedEmail"===e&&!0===P.emailVerified)){const e=await o.getUserByEmail(P.email);e&&(H=P.emailVerified&&!e.emailVerified?await o.updateUser({id:e.id,emailVerified:!0}):e)}if(!H)try{if(P.email&&!0===P.emailVerified&&!1===o.autoLink){if(await o.getUserByEmail(P.email))throw new R(v.EMAIL_ALREADY_EXISTS,{redirectUrl:y})}let e;try{e=o.roles.resolveOnCreate?.({providerId:s,profile:P,request:n})}catch(e){console.error("roles.resolveOnCreate threw:",e)}const t=!0===P.emailVerified?P.email:null;H=await o.createUser({name:P.name,email:t,image:P.avatar,emailVerified:P.emailVerified,role:e??o.roles.defaultRole})}catch(e){if(e instanceof R)throw e;throw console.error("Failed to create user:",e),new R(v.USER_CREATE_FAILED,{cause:e,redirectUrl:y})}}if(H&&P.email){const{email:e,emailVerified:t}=H,{email:r,emailVerified:n}=P,s={id:H.id};let i=!1;if(e||!0!==n?e!==r||!0!==n||t||(s.emailVerified=!0,i=!0):(s.email=r,s.emailVerified=!0,i=!0),i)try{H=await o.updateUser(s)}catch(e){console.error("Failed to update user after sign-in:",e)}}if(M)try{const e=(await o.getAccounts(H.id)).find(e=>e.provider===s&&e.providerAccountId===P.id);if(e&&o.updateAccount){let t,r,i,a;try{t=b.refreshToken()}catch{t=e.refreshToken??null}try{const e=b.accessTokenExpiresAt();e&&(r=Math.floor(e.getTime()/1e3))}catch{r=e.expiresAt??void 0}try{i=b.idToken()}catch{i=e.idToken??null}try{a=b.scopes()?.join(" ")??e.scope??null}catch{a=e.scope??null}await o.updateAccount({userId:H.id,provider:s,providerAccountId:P.id,accessToken:b.accessToken()??e.accessToken??void 0,refreshToken:t,expiresAt:r??e.expiresAt??void 0,tokenType:b.tokenType?.()??e.tokenType??null,scope:a,idToken:i}),await x(o,{request:n,providerId:s,userId:H.id,providerUser:P,tokens:b,action:"update"})}}catch(e){console.error("Failed to update account tokens on sign-in:",e)}else{let e,t,r;try{e=b.refreshToken()}catch{e=null}try{const e=b.accessTokenExpiresAt();e&&(t=Math.floor(e.getTime()/1e3))}catch{}try{r=b.idToken()}catch{r=null}{const e=await async function(e,t){if(!e||"function"!=typeof e.onBeforeLinkAccount)return{allow:!0};try{return await e.onBeforeLinkAccount(t)||{allow:!0}}catch(e){return console.error("onBeforeLinkAccount hook error:",e),{allow:!0}}}(o,{request:n,providerId:s,userId:H.id,providerUser:P,tokens:b});if(!1===e.allow){const t=e.response??(()=>{throw new R(v.LINKING_NOT_ALLOWED,{redirectUrl:y})})();return g.toHeaders().forEach((e,r)=>t.headers.append(r,e)),t}}try{let i;try{i=b.scopes()?.join(" ")??null}catch{i=null}await o.linkAccount({userId:H.id,provider:s,providerAccountId:P.id,accessToken:b.accessToken(),refreshToken:e,expiresAt:t,tokenType:b.tokenType?.()??null,scope:i,idToken:r}),await x(o,{request:n,providerId:s,userId:H.id,providerUser:P,tokens:b,action:"link"})}catch(e){throw console.error("Error linking account:",e),new R(v.ACCOUNT_LINK_FAILED,{cause:e,redirectUrl:y})}}const F=await o.createSession(H.id),V=new URL(n.url),K=new URL(y,n.url),W="token"===o.sessionStrategy,j="cookie"===o.sessionStrategy,B="http:"!==K.protocol&&"https:"!==K.protocol,J=V.host!==K.host;if(W||!j&&(B||J)){const t=new URL(K),n=g.get(T);if(!n)throw new R(v.PKCE_CHALLENGE_MISSING,{redirectUrl:y});{const e=await o.signJWT({sub:H.id,challenge:n},{ttl:60});t.searchParams.set("code",e)}const s=r({redirectUrl:t.toString()});g.delete(f),g.delete(m),N&&g.delete(E),g.delete(I),g.delete(T);const i=e(s);return g.toHeaders().forEach((e,t)=>{i.headers.append(t,e)}),i}g.set(w,F,{maxAge:o.jwt.ttl,sameSite:o.development?"lax":"none",secure:!o.development}),g.delete(f),g.delete(m),N&&g.delete(E),g.delete(I);let G;if("false"===a.searchParams.get("redirect")){const e=await o.getAccounts(H.id),t=Boolean(H.role&&o.roles.adminRoles.includes(H.role)||o.roles.adminUserIds.includes(H.id));G=ee({user:{...H,isAdmin:t,accounts:e}})}else G=te(y);return g.toHeaders().forEach((e,t)=>{G.headers.append(t,e)}),G}function P(e,t){if(!1===t.cors)return!1;const r=t.cors;if("all"===r.allowedOrigins)return!0;if("trust"===r.allowedOrigins){if("all"===t.trustHosts)return!0;try{const r=new URL(e);return t.trustHosts.includes(r.host)||t.trustHosts.includes(r.hostname)}catch{return!1}}if(r.allowedOrigins.includes("*"))return!0;try{const t=new URL(e);return r.allowedOrigins.includes(e)||r.allowedOrigins.includes(t.origin)||r.allowedOrigins.includes(t.host)||r.allowedOrigins.includes(t.hostname)}catch{return r.allowedOrigins.includes(e)}}function H(e,t,r){if(!1===r.cors)return t;const n=e.headers.get("Origin")||e.headers.get("origin");if(!n)return t;if(!P(n,r))return t;const o=r.cors;t.headers.set("Vary","Origin");const s=o.allowCredentials,i="all"!==o.allowedOrigins||s?n:"*";return t.headers.set("Access-Control-Allow-Origin",i),s&&t.headers.set("Access-Control-Allow-Credentials","true"),t.headers.set("Access-Control-Allow-Headers",o.allowedHeaders.join(", ")),t.headers.set("Access-Control-Allow-Methods",o.allowedMethods.join(", ")),o.exposeHeaders?.length&&t.headers.set("Access-Control-Expose-Headers",o.exposeHeaders.join(", ")),t}function M(e,t){if(!1===t.cors)return new Response(null,{status:204});const r=e.headers.get("Origin")||e.headers.get("origin"),n=t.cors,o={};if(r&&P(r,t)){const e=n.allowCredentials,t="all"!==n.allowedOrigins||e?r:"*";o["Access-Control-Allow-Origin"]=t,e&&(o["Access-Control-Allow-Credentials"]="true")}return o["Access-Control-Allow-Headers"]=n.allowedHeaders.join(", "),o["Access-Control-Allow-Methods"]=n.allowedMethods.join(", "),null!=n.maxAge&&(o["Access-Control-Max-Age"]=String(n.maxAge)),n.exposeHeaders?.length&&(o["Access-Control-Expose-Headers"]=n.exposeHeaders.join(", ")),new Response(null,{status:204,headers:o})}import{generateCodeVerifier as F,generateState as V}from"arctic";function K(e,t,r){if("all"===t)return!0;const n=e.headers.get("origin");if(!n)return!1;let o;try{o=new URL(n).host}catch{return!1}if(r){if(o.startsWith("localhost")||o.startsWith("127.0.0.1"))return!0}const s=new URL(e.url),i=s.host;return n===`${s.protocol}//${i}`||t.includes(o)}async function W(e,t,r,n){const o=t.providerMap.get(r);if(!o)throw new R(v.PROVIDER_NOT_FOUND);const{state:s,codeVerifier:i}={state:V(),codeVerifier:F()},a=new URL(e.url),c=a.searchParams.get("redirectTo"),l=a.searchParams.get("profile"),d=a.searchParams.get("prompt");if(c){let r;try{if(c.startsWith("//"))throw new Error("Protocol-relative URL not allowed");r=new URL(c,a.origin)}catch{throw new R(v.INVALID_REDIRECT_URL,'Invalid "redirectTo" URL',{status:400})}const n=r.host,o=n===new URL(e.url).host,s="all"===t.trustHosts||t.trustHosts.includes(n);if(("http:"===r.protocol||"https:"===r.protocol)&&!o&&!s)throw new R(v.UNTRUSTED_HOST)}const w=c?`${s}.${btoa(c)}`:s;let p,g,O,y,U=a.searchParams.get("callbackUri");if(!U&&o.requiresRedirectUri&&(U=`${a.origin}${t.basePath}/callback/${r}`),l){const e=(t.profiles?.[r]??{})[l];if(!e)throw new R(v.UNKNOWN_PROFILE,`Unknown profile "${l}" for provider "${r}"`,{status:400});e.redirectUri&&(U=e.redirectUri),e.scopes&&(p=e.scopes),e.params&&(g={...e.params??{}});const{tenant:o,prompt:s}=e;if(null==o&&null==s||(O={...O??{},tenant:o,prompt:s}),!n&&!0===e.linkOnly)throw new R(v.LINK_ONLY_PROVIDER,"This profile is link-only. Please link it to an existing account.",{status:400})}if(d&&(g={...g??{},prompt:d}),!n&&!0===o.linkOnly)throw new R(v.LINK_ONLY_PROVIDER);try{y=await o.getAuthorizationUrl(w,i,{redirectUri:U??void 0,scopes:p,params:g,overrides:O})}catch(e){console.error("Error getting authorization URL:",e),y=null}if(!y)throw new R(v.AUTHORIZATION_URL_FAILED,"Could not create authorization URL",{status:500});const k=u(e.headers.get("Cookie")),N=new h(k,t.cookieOptions),_={maxAge:600,sameSite:t.development?"lax":"none",secure:!t.development};N.set(f,s,_),N.set(m,i,_),n?N.set(A,n,_):N.delete(A,{sameSite:t.development?"lax":"none",secure:!t.development}),U&&N.set(E,U,_);const L=JSON.stringify({params:g??{},overrides:O??{}});N.set(I,btoa(L),_);const S=a.searchParams.get("code_challenge");S&&N.set(T,S,_);if("false"===a.searchParams.get("redirect")){const e=ee({url:y.toString()});return N.toHeaders().forEach((t,r)=>{e.headers.append(r,t)}),e}const D=te(y.toString());return N.toHeaders().forEach((e,t)=>{D.headers.append(t,e)}),D}async function j(e,t,r){const n=new URL(e.url);let o=k(e).token;if(o||(o=n.searchParams.get("token")??void 0),!o)throw new R(v.UNAUTHORIZED);if(!await t.validateSession(o))throw new R(v.UNAUTHORIZED);n.searchParams.delete("token");return W(new Request(n.toString(),e),t,r,o)}async function B(e,t,r){const n=k(e).token;if(!n)throw new R(v.UNAUTHORIZED);const o=await t.validateSession(n);if(!o||!o.user)throw new R(v.UNAUTHORIZED);const s=o.accounts??[];if(s.length<=1)throw new R(v.CANNOT_UNLINK_LAST_ACCOUNT);const i=s.find(e=>e.provider===r);if(!i)throw new R(v.ACCOUNT_NOT_LINKED,`Provider "${r}" not linked`);await t.unlinkAccount(r,i.providerAccountId);if((await t.getAccounts(o.user.id)).length>0&&o.user.email)try{await t.updateUser({id:o.user.id,email:null,emailVerified:!1})}catch(e){console.error("Failed to clear stale email after unlinking:",e)}return ee({message:"Account unlinked successfully"})}async function J(e,t,r){return W(e,t,r,null)}async function G(e,t){const r=u(e.headers.get("Cookie")),n=new h(r,t.cookieOptions);n.delete(w,{sameSite:t.development?"lax":"none",secure:!t.development}),n.delete(A,{sameSite:t.development?"lax":"none",secure:!t.development});const o=ee({message:"Signed out"});return n.toHeaders().forEach((e,t)=>{o.headers.append(t,e)}),o}async function q(e,t){const{token:r}=k(e),n=Array.from(t.providerMap.keys());if(!r)return ee({...z,providers:n});try{const e=await t.validateSession(r);return e?ee({...X(e),providers:n}):ee({...z,providers:n},{status:401})}catch(e){throw console.error("Error validating session:",e),new R(v.SESSION_VALIDATION_FAILED,{cause:e})}}async function Y(e,t){if("POST"!==e.method)throw new R(v.METHOD_NOT_ALLOWED);let r;try{r=await e.json()}catch{throw new R(v.INVALID_REQUEST,"Invalid JSON body",{status:400})}const{code:n,codeVerifier:o}=r;if(!n||!o)throw new R(v.INVALID_REQUEST,"Missing code or codeVerifier",{status:400});const s=await t.verifyJWT(n);if(!s)throw new R(v.TOKEN_EXPIRED,"Invalid or expired code");const{sub:i,challenge:a}=s,c=(new TextEncoder).encode(o),l=await crypto.subtle.digest("SHA-256",c),d=Array.from(new Uint8Array(l));if(a!==btoa(String.fromCharCode(...d)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""))throw new R(v.CODE_VERIFIER_INVALID);return ee({token:await t.createSession(i)})}function Z(e){const{basePath:t}=e;return async function(r){if("OPTIONS"===r.method)return M(r,e);const n=new URL(r.url);if(!n.pathname.startsWith(t)){const n=new R(v.NOT_FOUND);return H(r,await C({error:n,request:r},{basePath:t,onError:e.onError,errorRedirect:e.errorRedirect}),e)}try{if("POST"===r.method&&!K(r,e.trustHosts,e.development)){const t=r.headers.get("origin")??"unknown",n=e.development?`Untrusted origin: '${t}'. Add this origin to 'trustHosts' in createAuth() or ensure you are using 'localhost' or '127.0.0.1' for development.`:"Forbidden";throw new R(v.FORBIDDEN,n,{status:403})}const o=n.pathname.substring(t.length).split("/").filter(Boolean),s=o[0];if(!s)throw new R(v.NOT_FOUND);let i;if("GET"===r.method)if("session"===s)i=await q(r,e);else if(2===o.length&&"link"===o[0])i=await j(r,e,o[1]);else if(2===o.length&&"callback"===o[0])i=await b(r,e,o[1]);else{if(1!==o.length)throw new R(v.NOT_FOUND);i=await J(r,e,s)}else{if("POST"!==r.method)throw new R(v.METHOD_NOT_ALLOWED);if(1===o.length&&"signout"===s)i=await G(r,e);else if(1===o.length&&"token"===s)i=await Y(r,e);else{if(2!==o.length||"unlink"!==o[0])throw new R(v.NOT_FOUND);i=await B(r,e,o[1])}}try{i.headers.set("Cache-Control","no-store, private"),i.headers.set("Pragma","no-cache"),i.headers.set("Expires","0")}catch{}return H(r,i,e)}catch(n){if(n instanceof R){return H(r,await C({error:n,request:r},{basePath:t,onError:e.onError,errorRedirect:e.errorRedirect}),e)}console.error("Unexpected error in gau handler:",n);const o=new R(v.INTERNAL_ERROR,{cause:n});return H(r,await C({error:o,request:r},{basePath:t,onError:e.onError,errorRedirect:e.errorRedirect}),e)}}}var z={user:null,session:null,accounts:null};function X(e){const t=e.session&&(({id:e,...t})=>t)(e.session);return{user:e.user,session:t,accounts:e.accounts?.map(e=>({provider:e.provider,providerAccountId:e.providerAccountId}))??null,providers:e.providers}}var Q=class extends Error{cause;constructor(e,t){super(e),this.name="AuthError",this.cause=t}};function ee(e,t={}){const r=new Headers(t.headers);return r.has("Content-Type")||r.set("Content-Type","application/json; charset=utf-8"),new Response(JSON.stringify(e),{...t,headers:r})}function te(e,t=302){return new Response(null,{status:t,headers:{Location:e}})}var re="X-Refreshed-Token";function ne(e){return null!=e?.impersonatedBy}async function oe(e){try{const t=function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=(4-t.length%4)%4,n=t.padEnd(t.length+r,"=");try{const e=atob(n),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return r}catch{throw new Q("Invalid base64url string")}}(e),r=await crypto.subtle.importKey("pkcs8",t.slice(),{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),n=await crypto.subtle.exportKey("jwk",r);delete n.d,n.key_ops=["verify"];return{privateKey:r,publicKey:await crypto.subtle.importKey("jwk",n,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"])}}catch(e){if(e instanceof Q)throw e;throw new Q("Invalid secret. Must be a base64url-encoded PKCS#8 private key for ES256. Use `bunx gau secret` to generate one.",e)}}async function se(e,t={}){let{algorithm:r="ES256",ttl:s,iss:i,aud:a,sub:c,privateKey:l,secret:d}=t;if("ES256"===r){if(!l){if("string"!=typeof d)throw new Q("Missing secret for ES256 signing. It must be a base64url-encoded string.");({privateKey:l}=await oe(d))}}else if("HS256"===r&&!d)throw new Q("Missing secret for HS256 signing");const u=Math.floor(Date.now()/1e3),h={iat:u,iss:i,aud:a,sub:c,...e};null!=s&&s>0&&(h.exp=u+s);const f="HS256"===r,w=f?"HS256":"ES256",p=JSON.stringify({alg:w,typ:"JWT"}),g=JSON.stringify(h),A=n(p,g);let m;if(f){const e="string"==typeof d?(new TextEncoder).encode(d):d,t=await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);m=new Uint8Array(await crypto.subtle.sign("HMAC",t,A))}else m=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},l,A));return o(p,g,m)}async function ie(e,t){let{algorithm:r="ES256",publicKey:n,secret:o,iss:c,aud:l}=t;if("ES256"===r&&!n){if("string"!=typeof o)throw new Q("Missing secret for ES256 verification. Must be a base64url-encoded string.");({publicKey:n}=await oe(o))}if("HS256"===r&&!o)throw new Q("Missing secret for HS256 verification");const[d,u,h,f]=a(e),w=new s(d).algorithm();let p=!1;if("HS256"===r){if("HS256"!==w)throw new Error(`JWT algorithm is "${w}", but verifier was configured for "HS256"`);const e="string"==typeof o?(new TextEncoder).encode(o):o,t=await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);p=function(e,t){let r=e.length^t.length;const n=Math.max(e.length,t.length);for(let o=0;o<n;o++)r|=(e[o]??0)^(t[o]??0);return 0===r}(new Uint8Array(await crypto.subtle.sign("HMAC",t,f)),new Uint8Array(h))}else{if("ES256"!==w)throw new Q(`JWT algorithm is "${w}", but verifier was configured for "ES256"`);const e=new Uint8Array(h);if(p=await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},n,e,f),!p&&64===e.length)try{const t=function(e){if(64!==e.length)throw new Error("Invalid raw signature length");let t=e.slice(0,32),r=e.slice(32),n=0;for(;n<t.length-1&&0===t[n];)n++;t=t.slice(n);let o=0;for(;o<r.length-1&&0===r[o];)o++;if(r=r.slice(o),t.length>0&&128&t[0]){const e=new Uint8Array(t.length+1);e[0]=0,e.set(t,1),t=e}if(r.length>0&&128&r[0]){const e=new Uint8Array(r.length+1);e[0]=0,e.set(r,1),r=e}const s=t.length,i=r.length,a=2+s+2+i,c=new Uint8Array(2+a);return c[0]=48,c[1]=a,c[2]=2,c[3]=s,c.set(t,4),c[4+s]=2,c[5+s]=i,c.set(r,6+s),c}(e);p=await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},n,t,f)}catch{p=!1}}if(!p)throw new Q("Invalid JWT signature");const g=new i(u);if(g.hasExpiration()&&!g.verifyExpiration())throw new Q("JWT expired");if(g.hasNotBefore()&&!g.verifyNotBefore())throw new Q("JWT not yet valid");if(c&&u.iss!==c)throw new Q("Invalid JWT issuer");if(l){const e=Array.isArray(l)?l:[l],t=u.aud?Array.isArray(u.aud)?u.aud:[u.aud]:[];if(!e.some(e=>t.includes(e)))throw new Q("Invalid JWT audience")}return u}export{d as DEFAULT_COOKIE_SERIALIZE_OPTIONS,u as parseCookies,h as Cookies,f as CSRF_COOKIE_NAME,w as SESSION_COOKIE_NAME,p as SESSION_STASH_COOKIE_NAME,g as SESSION_STRATEGY_COOKIE_NAME,A as LINKING_TOKEN_COOKIE_NAME,m as PKCE_COOKIE_NAME,E as CALLBACK_URI_COOKIE_NAME,I as PROVIDER_OPTIONS_COOKIE_NAME,T as CLIENT_CHALLENGE_COOKIE_NAME,O as CSRF_MAX_AGE,se as sign,ie as verify,k as getSessionTokenFromRequest,N as createAuth,_ as ErrorMessages,v as ErrorCodes,L as ErrorStatuses,R as GauError,S as createErrorRedirectUrl,D as isUserFacingRequest,C as handleError,b as handleCallback,H as applyCors,M as handlePreflight,K as verifyRequestOrigin,j as handleLink,B as handleUnlink,J as handleSignIn,G as handleSignOut,q as handleSession,Y as handleToken,Z as createHandler,z as NULL_SESSION,X as toClientSession,Q as AuthError,ee as json,te as redirect,re as REFRESHED_TOKEN_HEADER,ne as isImpersonating};//# sourceMappingURL=chunk-H7HMOWU7.js.map
|