@pontive/server 1.29.0 → 1.29.2

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/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("./client-BfPi8CfF.cjs"),T=require("./keyless.cjs"),y=require("./management-credential--CmS8XaV.cjs"),H=require("jose"),ke=10080*60;function se(t){const e=t.clientSecret?"server":"browser",r=["issuer","clientId"];e==="server"&&r.push("sessionSecret");for(const s of r)if(!t[s]){const o={issuer:"PONTIVE_ISSUER",clientId:"PONTIVE_CLIENT_ID",sessionSecret:"PONTIVE_SESSION_SECRET"}[s];throw new Error(`@pontive/server: ${s} is required${o?` (pass it, or set ${o})`:""}`)}if(e==="server"&&t.sessionSecret.length<32)throw new Error("@pontive/server: sessionSecret must be at least 32 characters");if(t.baseUrl)try{new URL(t.baseUrl)}catch{throw new Error(`@pontive/server: baseUrl "${t.baseUrl}" is not an absolute URL`)}return{mode:e,authPath:(t.authPath??"/__pontive").replace(/\/+$/,""),issuer:t.issuer.replace(/\/+$/,""),clientId:t.clientId,clientSecret:t.clientSecret||void 0,sessionSecret:t.sessionSecret??"",baseUrl:t.baseUrl?new URL(t.baseUrl).origin:void 0,scopes:t.scopes??"openid email profile offline_access",basePath:(t.basePath??"/api/auth").replace(/\/+$/,""),redirectUri:t.redirectUri,signInPath:t.signInPath??"/login",afterSignInPath:t.afterSignInPath??"/",prompt:t.prompt,cookieName:t.cookieName??"pontive_session",secureCookies:t.secureCookies,iframeSafe:t.iframeSafe??"auto",previewCallback:t.previewCallback??"auto",sessionMaxAgeSeconds:t.sessionMaxAgeSeconds??ke,refreshSkewSeconds:t.refreshSkewSeconds??60,fetch:t.fetch??((...s)=>fetch(...s)),logger:t.logger??console}}const q=3500,K=16;function C(t){const e=new Map;if(!t)return e;for(const r of t.split(";")){const s=r.indexOf("=");if(s<0)continue;const o=r.slice(0,s).trim();!o||e.has(o)||e.set(o,r.slice(s+1).trim())}return e}function F(t){return[...t].map(([e,r])=>`${e}=${r}`).join("; ")}function N(t,e,r){const s=r.sameSite??"Lax",o=[`${t}=${e}`,"Path=/","HttpOnly",`SameSite=${s}`,`Max-Age=${r.maxAge}`];return(r.secure||s==="None")&&o.push("Secure"),o.join("; ")}function U(t,e){return e===0?t:`${t}.${e}`}function Se(t,e){const r=t.get(e);if(r===void 0)return null;let s=r;for(let o=1;o<K;o++){const h=t.get(U(e,o));if(h===void 0)break;s+=h}return s}function ye(t,e,r,s){const o=[],h=Math.max(1,Math.ceil(r.length/q));for(let a=0;a<h;a++){const u=r.slice(a*q,(a+1)*q);t.set(U(e,a),u),o.push(N(U(e,a),u,s))}for(let a=h;a<K;a++){const u=U(e,a);if(!t.has(u))break;t.delete(u),o.push(N(u,"",{...s,maxAge:0}))}return o}function W(t,e,r){const s=[];for(let o=0;o<K;o++){const h=U(e,o);if(!t.has(h)){if(o>0)break;continue}t.delete(h),s.push(N(h,"",{...r,maxAge:0}))}return s}const G="switch-organization",ne="organization_error",B=t=>Array.isArray(t)?t.filter(e=>typeof e=="string"):[];function oe(t){const e=t.org_id;return typeof e!="string"||e===""?null:{id:e,roles:B(t.roles),permissions:B(t.permissions)}}function Te(t){try{return H.decodeJwt(t)}catch{return{}}}function ge(t,e,r="/"){const s=new URLSearchParams({organization_id:e,returnTo:r});return`${t}/${G}?${s.toString()}`}const ie="__Host-pontive_access",ae="__Secure-pontive_session_state";function be(t){const e=r=>typeof t[r]=="string"?t[r]:void 0;return{id:e("sub")??"",email:e("email"),name:e("name")??e("email"),username:e("preferred_username"),picture:e("picture"),emailVerified:t.email_verified===!0}}function Pe(t){const e={issuer:t.issuer,clientId:t.clientId},r=new Map;function s(a){for(const[u,m]of r)m.expiresAt<=a&&r.delete(u)}async function o(a,u){const m=Date.now();s(m);const p=await y.sha256Hex(a),l=r.get(p);if(l)return l.profile;const f=y.userInfo(e,t.fetch,a).catch(k=>(r.delete(p),t.logger.warn("[pontive] could not read the user's profile:",k instanceof Error?k.message:String(k)),null));return r.set(p,{expiresAt:u,profile:f}),f}async function h(a){const u=C(a).get(ie);if(!u)return null;let m;try{m=await y.verifyJwt(e,t.fetch,u)}catch(f){return f.code!=="ERR_JWT_EXPIRED"&&t.logger.warn("[pontive] access token cookie refused:",f instanceof Error?f.message:String(f)),null}const p=(m.exp??0)*1e3,l=await o(u,p);return{user:be({...l,...m,sub:m.sub}),accessToken:u,expiresAt:p,sessionId:typeof m.sid=="string"?m.sid:void 0,organization:oe(m),claims:m}}return{async handle(a){const u=new URL(a.url);if(u.pathname!==`${t.basePath}/${G}`)return null;const m=u.searchParams.get("organization_id"),p=$e(u.searchParams.get("returnTo"));if(!m)return J(p);const l=new URL(`${t.authPath}/oauth2/session`,u.origin);return l.searchParams.set("client_id",t.clientId),l.searchParams.set("return_to",p),l.searchParams.set("organization_id",m),J(l.pathname+l.search)},getSession:h,async refresh(a){const u=a.headers.get("cookie"),m=await h(u),p={session:m,setCookies:[],cookieHeader:u??""};if(m||!C(u).has(ae))return p;const l=new URL(a.url),f=new URL(`${t.authPath}/oauth2/session`,l.origin);return f.searchParams.set("client_id",t.clientId),f.searchParams.set("return_to",l.pathname+l.search),{...p,handshake:f.pathname+f.search}}}}function $e(t){return t&&t.startsWith("/")&&!t.startsWith("//")&&!t.startsWith("/\\")?t:"/"}function J(t){return new Response(null,{status:302,headers:{location:t,"cache-control":"no-store"}})}const _e=["lovable.app","lovableproject.com","lovable.dev","vusercontent.net","v0.dev","v0.app","webcontainer-api.io","webcontainer.io","replit.dev","replit.app","lp.dev","bolt.host","csb.app"];function Ie(t){const e=t.toLowerCase().replace(/\.$/,"");return _e.some(r=>e===r||e.endsWith(`.${r}`))}const Oe={lovable:["*.lovableproject.com","*.lovable.app","*.lovable.dev"],v0:["*.vusercontent.net","*.lite.vusercontent.net","*.v0.app","*.v0.dev"],vercel:["*.vercel.app"],replit:["*.replit.dev","*.*.replit.dev","*.replit.app"],bolt:["*.bolt.host","*.webcontainer-api.io","*.local-credentialless.webcontainer-api.io","*.local-corp.webcontainer-api.io"],codesandbox:["*.csb.app"]},Re="/oauth2/preview-callback",Ce="pontive:authorization-response",Ae=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function Ue(t){let e;try{e=new URL(t)}catch{return null}if(e.protocol!=="https:"||e.port!==""||e.origin!==t)return null;const r=e.hostname.split(".");for(const[s,o]of Object.entries(Oe))for(const h of o){const a=h.split(".");if(a.length===r.length&&a.every((u,m)=>u==="*"?Ae.test(r[m]):u===r[m]))return s}return null}function Ne(t,e){return`${t.replace(/\/$/,"")}${Re}?origin=${encodeURIComponent(e)}`}const Le=3e4;class xe{constructor(e=Le){this.recentMs=e}recentMs;inFlight=new Map;recent=new Map;async run(e,r){const s=await y.sha256Hex(e);this.sweep();const o=this.recent.get(s);if(o)return o.result;let h=this.inFlight.get(s);return h||(h=r().then(a=>(this.recent.set(s,{at:Date.now(),result:a}),a)).finally(()=>this.inFlight.delete(s)),this.inFlight.set(s,h)),h}sweep(){const e=Date.now()-this.recentMs;for(const[r,s]of this.recent)s.at<e&&this.recent.delete(r)}}const Y=new Map;function ce(t){let e=Y.get(t);return e||(e=crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)).then(r=>new Uint8Array(r)),Y.set(t,e)),e}async function Z(t,e,r){return new H.EncryptJWT(t).setProtectedHeader({alg:"dir",enc:"A256GCM"}).setIssuedAt().setExpirationTime(`${r}s`).encrypt(await ce(e))}async function X(t,e){try{const{payload:r}=await H.jwtDecrypt(t,await ce(e));return r}catch{return null}}const Me=900,Q=600;function ee(t,e){return t&&t.startsWith("/")&&!t.startsWith("//")&&!t.startsWith("/\\")?t:e}function O(t,e=[]){const r=new Headers({location:t,"cache-control":"no-store"});for(const s of e)r.append("set-cookie",s);return new Response(null,{status:302,headers:r})}const Ge="pontive:popup-complete";function je(t,e,r){const o=`<!doctype html><meta charset="utf-8"><title>Signing in</title><script type="application/json" id="pontive-popup">${JSON.stringify({message:{type:Ge,url:t},origin:e}).replace(/</g,"\\u003c")}<\/script><script>(function(){var d=JSON.parse(document.getElementById("pontive-popup").textContent);var go=function(){window.location.replace(d.message.url)};if(window.opener&&window.opener!==window){try{window.opener.postMessage(d.message,d.origin)}catch(e){}window.close();setTimeout(go,1000)}else{go()}})()<\/script>`,h=new Headers({"content-type":"text/html; charset=utf-8","cache-control":"no-store","content-security-policy":"default-src 'none'; script-src 'unsafe-inline'","x-content-type-options":"nosniff"});for(const a of r)h.append("set-cookie",a);return new Response(o,{status:200,headers:h})}function qe(t){const e=y.randomValue(),s=`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sign in</title><style>body{font-family:system-ui,sans-serif;margin:4rem auto;max-width:28rem;padding:0 1rem}</style><p>This preview signs in in a new window.</p><p><button id="go" type="button">Sign in</button></p><p id="status"></p><script type="application/json" id="pontive-preview-signin">${JSON.stringify({...t,type:Ce}).replace(/</g,"\\u003c")}<\/script><script nonce="${e}">(function(){var d=JSON.parse(document.getElementById("pontive-preview-signin").textContent);var s=document.getElementById("status");var w=null;window.addEventListener("message",function(e){if(!w||e.source!==w||e.origin!==d.authOrigin)return;var m=e.data;if(!m||m.type!==d.type||!m.response||typeof m.response!=="object")return;var u=new URL(d.callbackUrl);["code","state","iss","error","error_description","error_uri"].forEach(function(k){var v=m.response[k];if(typeof v==="string")u.searchParams.set(k,v)});try{w.close()}catch(x){}if(u.origin===location.origin)location.replace(u.toString())});document.getElementById("go").addEventListener("click",function(){w=window.open(d.popupUrl,"pontive_signin_popup","popup=yes,width=500,height=680");s.textContent=w?"Finish signing in in the new window.":"The sign-in window was blocked. Allow popups for this site and try again."})})()<\/script>`;return new Response(s,{status:200,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store","content-security-policy":`default-src 'none'; script-src 'nonce-${e}'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`,"x-content-type-options":"nosniff","referrer-policy":"no-referrer"}})}function $(t,e){if(t.baseUrl)return t.baseUrl;const r=e.headers.get("x-forwarded-host")?.split(",")[0]?.trim()||e.headers.get("host")?.trim();if(r){const s=e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()||new URL(e.url).protocol.replace(":","");try{return new URL(`${s}://${r}`).origin}catch{}}return new URL(e.url).origin}function Ve(t){const e=s=>typeof t[s]=="string"?t[s]:void 0,r=e("name")??([e("given_name"),e("family_name")].filter(Boolean).join(" ")||void 0)??e("email");return{id:t.sub??"",email:e("email"),name:r,username:e("preferred_username"),picture:e("picture"),emailVerified:t.email_verified===!0}}function te(t){return Date.now()+(t.expires_in??Me)*1e3}function he(t){return t.mode==="browser"?Pe(t):De(t)}function De(t){const e={issuer:t.issuer,clientId:t.clientId,clientSecret:t.clientSecret},r=`${t.cookieName}_tx`,s=new xe,o=i=>t.secureCookies??$(t,i).startsWith("https:"),h=i=>t.iframeSafe===!0||t.iframeSafe==="auto"&&Ie(new URL($(t,i)).hostname),a=(i,c)=>h(i)?{maxAge:c,secure:!0,sameSite:"None"}:{maxAge:c,secure:o(i)},u=i=>t.previewCallback==="always"||t.previewCallback==="auto"&&Ue($(t,i))!==null,m=i=>`${$(t,i)}${t.basePath}/callback`,p=i=>u(i)?Ne(t.issuer,$(t,i)):t.redirectUri??m(i),l=(i,c)=>{const d=new URL(t.signInPath,$(t,i));return c&&d.searchParams.set("error",c),d.toString()};async function f(i){const c=Se(i,t.cookieName);if(c===null)return null;const d=await X(c,t.sessionSecret);return d||t.logger.warn("[pontive] session cookie could not be read (sealed with another secret, or truncated)"),d}async function k(i,c,d){const w=await Z({...c},t.sessionSecret,t.sessionMaxAgeSeconds);return ye(i,t.cookieName,w,a(d,t.sessionMaxAgeSeconds))}function I(i){const{refreshToken:c,...d}=i,w=Te(i.accessToken);return{...d,organization:oe(w),claims:w}}async function A(i){const c=new URL(i.url),d=u(i),w=c.searchParams.get("popup")==="1";if(d&&!w){const E=new URL(`${t.basePath}/login`,$(t,i));return c.searchParams.forEach((g,R)=>E.searchParams.set(R,g)),E.searchParams.set("popup","1"),qe({popupUrl:E.toString(),authOrigin:new URL(t.issuer).origin,callbackUrl:m(i)})}const S={state:y.randomValue(),verifier:y.randomValue(),nonce:y.randomValue(),returnTo:ee(c.searchParams.get("returnTo")??c.searchParams.get("next"),t.afterSignInPath),popup:w,redirectUri:p(i),previewCallback:d},v=await y.authorizationUrl(e,t.fetch,{redirectUri:S.redirectUri,scopes:t.scopes,state:S.state,nonce:S.nonce,codeChallenge:await y.pkceChallenge(S.verifier),prompt:t.prompt,organizationId:c.searchParams.get("organization_id")??void 0,loginHint:c.searchParams.get("login_hint")??void 0}),P=await Z({...S},t.sessionSecret,Q);return O(v,[N(r,P,a(i,Q))])}async function L(i){const c=new URL(i.url),d=C(i.headers.get("cookie")),w=[N(r,"",a(i,0))],S=d.get(r),v=S?await X(S,t.sessionSecret):null,P=c.searchParams.get("code"),E=b=>v?.popup&&!v.previewCallback?je(b,$(t,i),w):O(b,w),g=c.searchParams.get("error");if(g)return E(l(i,g));if(!v||!P||c.searchParams.get("state")!==v.state)return E(l(i,"invalid_state"));const R=c.searchParams.get("iss");if(v.previewCallback&&R!==null&&R!==t.issuer)return E(l(i,"invalid_issuer"));try{const b=await y.exchangeCode(e,t.fetch,{code:P,codeVerifier:v.verifier,redirectUri:v.redirectUri??p(i)});if(!b.id_token)throw new Error("the token response carried no id_token; is the openid scope requested?");const j=await y.verifyIdToken(e,t.fetch,b.id_token,v.nonce),Ee={user:Ve(j),accessToken:b.access_token,refreshToken:b.refresh_token,expiresAt:te(b),sessionId:typeof j.sid=="string"?j.sid:void 0};w.push(...await k(d,Ee,i))}catch(b){return t.logger.warn("[pontive] sign-in failed:",b instanceof Error?b.message:String(b)),E(l(i,"exchange_failed"))}return E(new URL(v.returnTo,$(t,i)).toString())}async function x(i){const c=C(i.headers.get("cookie")),d=await f(c),w=W(c,t.cookieName,a(i,0));let S=l(i);try{S=await y.endSessionUrl(e,t.fetch,{postLogoutRedirectUri:l(i),sessionId:d?.sessionId})??S}catch(v){t.logger.warn("[pontive] could not reach the issuer to end its session:",v instanceof Error?v.message:String(v))}return O(S,w)}function z(i,c){return{...i,accessToken:c.access_token,refreshToken:c.refresh_token??i.refreshToken,expiresAt:te(c)}}async function ve(i){const c=new URL(i.url),d=C(i.headers.get("cookie")),w=ee(c.searchParams.get("returnTo"),t.afterSignInPath),S=c.searchParams.get("organization_id"),v=g=>{const R=new URL(w,$(t,i));return g&&R.searchParams.set(ne,g),R.toString()},P=await f(d);if(!P?.refreshToken)return O(l(i));if(!S)return O(v("invalid_request"));let E;try{E=await y.refreshTokens(e,t.fetch,P.refreshToken,S)}catch(g){return g instanceof y.TokenEndpointError&&g.code==="invalid_request"?O(v("not_a_member")):(t.logger.warn("[pontive] organization switch failed:",g instanceof Error?g.message:String(g)),O(v("switch_failed")))}return O(v(),await k(d,z(P,E),i))}async function fe(i){try{const c=await y.refreshTokens(e,t.fetch,i.refreshToken);return z(i,c)}catch(c){if(c instanceof y.TokenEndpointError&&c.status>=400&&c.status<500)return t.logger.warn("[pontive] refresh refused; signing out:",c.message),null;throw c}}return{async handle(i){const{pathname:c}=new URL(i.url);if(!c.startsWith(`${t.basePath}/`))return null;const d=c.slice(t.basePath.length+1);return d==="login"&&i.method==="GET"?A(i):d==="callback"&&i.method==="GET"?L(i):d==="logout"&&(i.method==="GET"||i.method==="POST")?x(i):d===G&&(i.method==="GET"||i.method==="POST")?ve(i):null},async getSession(i){const c=await f(C(i));return c?Date.now()>=c.expiresAt?(t.logger.warn("[pontive] the session's access token has expired and getSession cannot refresh it. Run the SDK's middleware on this path so it refreshes before the request is handled."),null):I(c):null},async refresh(i){const c=C(i.headers.get("cookie")),d=E=>({session:E,setCookies:[],cookieHeader:i.headers.get("cookie")??""}),w=await f(c);if(!w)return d(null);if(new URL(i.url).pathname.startsWith(`${t.basePath}/`))return d(Date.now()<w.expiresAt?I(w):null);if(Date.now()<w.expiresAt-t.refreshSkewSeconds*1e3)return d(I(w));const S=()=>({session:null,setCookies:W(c,t.cookieName,a(i,0)),cookieHeader:F(c)});if(!w.refreshToken)return S();let v;try{v=await s.run(w.refreshToken,()=>fe(w))}catch(E){return t.logger.warn("[pontive] refresh failed, will retry:",E instanceof Error?E.message:String(E)),d(Date.now()<w.expiresAt?I(w):null)}if(!v)return S();const P=await k(c,v,i);return{session:I(v),setCookies:P,cookieHeader:F(c)}}}}const ue="1.29.0",pe="claim";function He(t={},e={}){const r=_.processEnv(),s=_.withEnvFallback(t,r);if(_.keylessApplies(s,r))return Ke(s,e);const o=se(s),h=_.isDevelopment(r)?()=>de(le(e),o.issuer):async()=>null;return me(o,he(o),h)}function le(t){if(t.projectDir)return t.projectDir;const e=globalThis.process;if(typeof e?.cwd!="function")throw new T.KeylessUnavailableError("keyless mode needs a project directory (process.cwd)");return e.cwd()}async function de(t,e){try{const r=await T.readKeylessRecord(t);return r?.claim_token&&r.issuer.replace(/\/+$/,"")===e?r:null}catch{return null}}function M(t,e){return new Response(`${e}
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("./client-CYs-uotZ.cjs"),T=require("./keyless.cjs"),y=require("./management-credential--CmS8XaV.cjs"),H=require("jose"),ke=10080*60;function se(t){const e=t.clientSecret?"server":"browser",r=["issuer","clientId"];e==="server"&&r.push("sessionSecret");for(const s of r)if(!t[s]){const o={issuer:"PONTIVE_ISSUER",clientId:"PONTIVE_CLIENT_ID",sessionSecret:"PONTIVE_SESSION_SECRET"}[s];throw new Error(`@pontive/server: ${s} is required${o?` (pass it, or set ${o})`:""}`)}if(e==="server"&&t.sessionSecret.length<32)throw new Error("@pontive/server: sessionSecret must be at least 32 characters");if(t.baseUrl)try{new URL(t.baseUrl)}catch{throw new Error(`@pontive/server: baseUrl "${t.baseUrl}" is not an absolute URL`)}return{mode:e,authPath:(t.authPath??"/__pontive").replace(/\/+$/,""),issuer:t.issuer.replace(/\/+$/,""),clientId:t.clientId,clientSecret:t.clientSecret||void 0,sessionSecret:t.sessionSecret??"",baseUrl:t.baseUrl?new URL(t.baseUrl).origin:void 0,scopes:t.scopes??"openid email profile offline_access",basePath:(t.basePath??"/api/auth").replace(/\/+$/,""),redirectUri:t.redirectUri,signInPath:t.signInPath??"/login",afterSignInPath:t.afterSignInPath??"/",prompt:t.prompt,cookieName:t.cookieName??"pontive_session",secureCookies:t.secureCookies,iframeSafe:t.iframeSafe??"auto",previewCallback:t.previewCallback??"auto",sessionMaxAgeSeconds:t.sessionMaxAgeSeconds??ke,refreshSkewSeconds:t.refreshSkewSeconds??60,fetch:t.fetch??((...s)=>fetch(...s)),logger:t.logger??console}}const q=3500,K=16;function C(t){const e=new Map;if(!t)return e;for(const r of t.split(";")){const s=r.indexOf("=");if(s<0)continue;const o=r.slice(0,s).trim();!o||e.has(o)||e.set(o,r.slice(s+1).trim())}return e}function F(t){return[...t].map(([e,r])=>`${e}=${r}`).join("; ")}function N(t,e,r){const s=r.sameSite??"Lax",o=[`${t}=${e}`,"Path=/","HttpOnly",`SameSite=${s}`,`Max-Age=${r.maxAge}`];return(r.secure||s==="None")&&o.push("Secure"),o.join("; ")}function U(t,e){return e===0?t:`${t}.${e}`}function Se(t,e){const r=t.get(e);if(r===void 0)return null;let s=r;for(let o=1;o<K;o++){const h=t.get(U(e,o));if(h===void 0)break;s+=h}return s}function ye(t,e,r,s){const o=[],h=Math.max(1,Math.ceil(r.length/q));for(let a=0;a<h;a++){const u=r.slice(a*q,(a+1)*q);t.set(U(e,a),u),o.push(N(U(e,a),u,s))}for(let a=h;a<K;a++){const u=U(e,a);if(!t.has(u))break;t.delete(u),o.push(N(u,"",{...s,maxAge:0}))}return o}function W(t,e,r){const s=[];for(let o=0;o<K;o++){const h=U(e,o);if(!t.has(h)){if(o>0)break;continue}t.delete(h),s.push(N(h,"",{...r,maxAge:0}))}return s}const G="switch-organization",ne="organization_error",B=t=>Array.isArray(t)?t.filter(e=>typeof e=="string"):[];function oe(t){const e=t.org_id;return typeof e!="string"||e===""?null:{id:e,roles:B(t.roles),permissions:B(t.permissions)}}function Te(t){try{return H.decodeJwt(t)}catch{return{}}}function ge(t,e,r="/"){const s=new URLSearchParams({organization_id:e,returnTo:r});return`${t}/${G}?${s.toString()}`}const ie="__Host-pontive_access",ae="__Secure-pontive_session_state";function be(t){const e=r=>typeof t[r]=="string"?t[r]:void 0;return{id:e("sub")??"",email:e("email"),name:e("name")??e("email"),username:e("preferred_username"),picture:e("picture"),emailVerified:t.email_verified===!0}}function Pe(t){const e={issuer:t.issuer,clientId:t.clientId},r=new Map;function s(a){for(const[u,m]of r)m.expiresAt<=a&&r.delete(u)}async function o(a,u){const m=Date.now();s(m);const p=await y.sha256Hex(a),l=r.get(p);if(l)return l.profile;const f=y.userInfo(e,t.fetch,a).catch(k=>(r.delete(p),t.logger.warn("[pontive] could not read the user's profile:",k instanceof Error?k.message:String(k)),null));return r.set(p,{expiresAt:u,profile:f}),f}async function h(a){const u=C(a).get(ie);if(!u)return null;let m;try{m=await y.verifyJwt(e,t.fetch,u)}catch(f){return f.code!=="ERR_JWT_EXPIRED"&&t.logger.warn("[pontive] access token cookie refused:",f instanceof Error?f.message:String(f)),null}const p=(m.exp??0)*1e3,l=await o(u,p);return{user:be({...l,...m,sub:m.sub}),accessToken:u,expiresAt:p,sessionId:typeof m.sid=="string"?m.sid:void 0,organization:oe(m),claims:m}}return{async handle(a){const u=new URL(a.url);if(u.pathname!==`${t.basePath}/${G}`)return null;const m=u.searchParams.get("organization_id"),p=$e(u.searchParams.get("returnTo"));if(!m)return J(p);const l=new URL(`${t.authPath}/oauth2/session`,u.origin);return l.searchParams.set("client_id",t.clientId),l.searchParams.set("return_to",p),l.searchParams.set("organization_id",m),J(l.pathname+l.search)},getSession:h,async refresh(a){const u=a.headers.get("cookie"),m=await h(u),p={session:m,setCookies:[],cookieHeader:u??""};if(m||!C(u).has(ae))return p;const l=new URL(a.url),f=new URL(`${t.authPath}/oauth2/session`,l.origin);return f.searchParams.set("client_id",t.clientId),f.searchParams.set("return_to",l.pathname+l.search),{...p,handshake:f.pathname+f.search}}}}function $e(t){return t&&t.startsWith("/")&&!t.startsWith("//")&&!t.startsWith("/\\")?t:"/"}function J(t){return new Response(null,{status:302,headers:{location:t,"cache-control":"no-store"}})}const _e=["lovable.app","lovableproject.com","lovable.dev","vusercontent.net","v0.dev","v0.app","webcontainer-api.io","webcontainer.io","replit.dev","replit.app","lp.dev","bolt.host","csb.app"];function Ie(t){const e=t.toLowerCase().replace(/\.$/,"");return _e.some(r=>e===r||e.endsWith(`.${r}`))}const Oe={lovable:["*.lovableproject.com","*.lovable.app","*.lovable.dev"],v0:["*.vusercontent.net","*.lite.vusercontent.net","*.v0.app","*.v0.dev"],vercel:["*.vercel.app"],replit:["*.replit.dev","*.*.replit.dev","*.replit.app"],bolt:["*.bolt.host","*.webcontainer-api.io","*.local-credentialless.webcontainer-api.io","*.local-corp.webcontainer-api.io"],codesandbox:["*.csb.app"]},Re="/oauth2/preview-callback",Ce="pontive:authorization-response",Ae=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function Ue(t){let e;try{e=new URL(t)}catch{return null}if(e.protocol!=="https:"||e.port!==""||e.origin!==t)return null;const r=e.hostname.split(".");for(const[s,o]of Object.entries(Oe))for(const h of o){const a=h.split(".");if(a.length===r.length&&a.every((u,m)=>u==="*"?Ae.test(r[m]):u===r[m]))return s}return null}function Ne(t,e){return`${t.replace(/\/$/,"")}${Re}?origin=${encodeURIComponent(e)}`}const Le=3e4;class xe{constructor(e=Le){this.recentMs=e}recentMs;inFlight=new Map;recent=new Map;async run(e,r){const s=await y.sha256Hex(e);this.sweep();const o=this.recent.get(s);if(o)return o.result;let h=this.inFlight.get(s);return h||(h=r().then(a=>(this.recent.set(s,{at:Date.now(),result:a}),a)).finally(()=>this.inFlight.delete(s)),this.inFlight.set(s,h)),h}sweep(){const e=Date.now()-this.recentMs;for(const[r,s]of this.recent)s.at<e&&this.recent.delete(r)}}const Y=new Map;function ce(t){let e=Y.get(t);return e||(e=crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)).then(r=>new Uint8Array(r)),Y.set(t,e)),e}async function Z(t,e,r){return new H.EncryptJWT(t).setProtectedHeader({alg:"dir",enc:"A256GCM"}).setIssuedAt().setExpirationTime(`${r}s`).encrypt(await ce(e))}async function X(t,e){try{const{payload:r}=await H.jwtDecrypt(t,await ce(e));return r}catch{return null}}const Me=900,Q=600;function ee(t,e){return t&&t.startsWith("/")&&!t.startsWith("//")&&!t.startsWith("/\\")?t:e}function O(t,e=[]){const r=new Headers({location:t,"cache-control":"no-store"});for(const s of e)r.append("set-cookie",s);return new Response(null,{status:302,headers:r})}const Ge="pontive:popup-complete";function je(t,e,r){const o=`<!doctype html><meta charset="utf-8"><title>Signing in</title><script type="application/json" id="pontive-popup">${JSON.stringify({message:{type:Ge,url:t},origin:e}).replace(/</g,"\\u003c")}<\/script><script>(function(){var d=JSON.parse(document.getElementById("pontive-popup").textContent);var go=function(){window.location.replace(d.message.url)};if(window.opener&&window.opener!==window){try{window.opener.postMessage(d.message,d.origin)}catch(e){}window.close();setTimeout(go,1000)}else{go()}})()<\/script>`,h=new Headers({"content-type":"text/html; charset=utf-8","cache-control":"no-store","content-security-policy":"default-src 'none'; script-src 'unsafe-inline'","x-content-type-options":"nosniff"});for(const a of r)h.append("set-cookie",a);return new Response(o,{status:200,headers:h})}function qe(t){const e=y.randomValue(),s=`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sign in</title><style>body{font-family:system-ui,sans-serif;margin:4rem auto;max-width:28rem;padding:0 1rem}</style><p>This preview signs in in a new window.</p><p><button id="go" type="button">Sign in</button></p><p id="status"></p><script type="application/json" id="pontive-preview-signin">${JSON.stringify({...t,type:Ce}).replace(/</g,"\\u003c")}<\/script><script nonce="${e}">(function(){var d=JSON.parse(document.getElementById("pontive-preview-signin").textContent);var s=document.getElementById("status");var w=null;window.addEventListener("message",function(e){if(!w||e.source!==w||e.origin!==d.authOrigin)return;var m=e.data;if(!m||m.type!==d.type||!m.response||typeof m.response!=="object")return;var u=new URL(d.callbackUrl);["code","state","iss","error","error_description","error_uri"].forEach(function(k){var v=m.response[k];if(typeof v==="string")u.searchParams.set(k,v)});try{w.close()}catch(x){}if(u.origin===location.origin)location.replace(u.toString())});document.getElementById("go").addEventListener("click",function(){w=window.open(d.popupUrl,"pontive_signin_popup","popup=yes,width=500,height=680");s.textContent=w?"Finish signing in in the new window.":"The sign-in window was blocked. Allow popups for this site and try again."})})()<\/script>`;return new Response(s,{status:200,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store","content-security-policy":`default-src 'none'; script-src 'nonce-${e}'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`,"x-content-type-options":"nosniff","referrer-policy":"no-referrer"}})}function $(t,e){if(t.baseUrl)return t.baseUrl;const r=e.headers.get("x-forwarded-host")?.split(",")[0]?.trim()||e.headers.get("host")?.trim();if(r){const s=e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()||new URL(e.url).protocol.replace(":","");try{return new URL(`${s}://${r}`).origin}catch{}}return new URL(e.url).origin}function Ve(t){const e=s=>typeof t[s]=="string"?t[s]:void 0,r=e("name")??([e("given_name"),e("family_name")].filter(Boolean).join(" ")||void 0)??e("email");return{id:t.sub??"",email:e("email"),name:r,username:e("preferred_username"),picture:e("picture"),emailVerified:t.email_verified===!0}}function te(t){return Date.now()+(t.expires_in??Me)*1e3}function he(t){return t.mode==="browser"?Pe(t):De(t)}function De(t){const e={issuer:t.issuer,clientId:t.clientId,clientSecret:t.clientSecret},r=`${t.cookieName}_tx`,s=new xe,o=i=>t.secureCookies??$(t,i).startsWith("https:"),h=i=>t.iframeSafe===!0||t.iframeSafe==="auto"&&Ie(new URL($(t,i)).hostname),a=(i,c)=>h(i)?{maxAge:c,secure:!0,sameSite:"None"}:{maxAge:c,secure:o(i)},u=i=>t.previewCallback==="always"||t.previewCallback==="auto"&&Ue($(t,i))!==null,m=i=>`${$(t,i)}${t.basePath}/callback`,p=i=>u(i)?Ne(t.issuer,$(t,i)):t.redirectUri??m(i),l=(i,c)=>{const d=new URL(t.signInPath,$(t,i));return c&&d.searchParams.set("error",c),d.toString()};async function f(i){const c=Se(i,t.cookieName);if(c===null)return null;const d=await X(c,t.sessionSecret);return d||t.logger.warn("[pontive] session cookie could not be read (sealed with another secret, or truncated)"),d}async function k(i,c,d){const w=await Z({...c},t.sessionSecret,t.sessionMaxAgeSeconds);return ye(i,t.cookieName,w,a(d,t.sessionMaxAgeSeconds))}function I(i){const{refreshToken:c,...d}=i,w=Te(i.accessToken);return{...d,organization:oe(w),claims:w}}async function A(i){const c=new URL(i.url),d=u(i),w=c.searchParams.get("popup")==="1";if(d&&!w){const E=new URL(`${t.basePath}/login`,$(t,i));return c.searchParams.forEach((g,R)=>E.searchParams.set(R,g)),E.searchParams.set("popup","1"),qe({popupUrl:E.toString(),authOrigin:new URL(t.issuer).origin,callbackUrl:m(i)})}const S={state:y.randomValue(),verifier:y.randomValue(),nonce:y.randomValue(),returnTo:ee(c.searchParams.get("returnTo")??c.searchParams.get("next"),t.afterSignInPath),popup:w,redirectUri:p(i),previewCallback:d},v=await y.authorizationUrl(e,t.fetch,{redirectUri:S.redirectUri,scopes:t.scopes,state:S.state,nonce:S.nonce,codeChallenge:await y.pkceChallenge(S.verifier),prompt:t.prompt,organizationId:c.searchParams.get("organization_id")??void 0,loginHint:c.searchParams.get("login_hint")??void 0}),P=await Z({...S},t.sessionSecret,Q);return O(v,[N(r,P,a(i,Q))])}async function L(i){const c=new URL(i.url),d=C(i.headers.get("cookie")),w=[N(r,"",a(i,0))],S=d.get(r),v=S?await X(S,t.sessionSecret):null,P=c.searchParams.get("code"),E=b=>v?.popup&&!v.previewCallback?je(b,$(t,i),w):O(b,w),g=c.searchParams.get("error");if(g)return E(l(i,g));if(!v||!P||c.searchParams.get("state")!==v.state)return E(l(i,"invalid_state"));const R=c.searchParams.get("iss");if(v.previewCallback&&R!==null&&R!==t.issuer)return E(l(i,"invalid_issuer"));try{const b=await y.exchangeCode(e,t.fetch,{code:P,codeVerifier:v.verifier,redirectUri:v.redirectUri??p(i)});if(!b.id_token)throw new Error("the token response carried no id_token; is the openid scope requested?");const j=await y.verifyIdToken(e,t.fetch,b.id_token,v.nonce),Ee={user:Ve(j),accessToken:b.access_token,refreshToken:b.refresh_token,expiresAt:te(b),sessionId:typeof j.sid=="string"?j.sid:void 0};w.push(...await k(d,Ee,i))}catch(b){return t.logger.warn("[pontive] sign-in failed:",b instanceof Error?b.message:String(b)),E(l(i,"exchange_failed"))}return E(new URL(v.returnTo,$(t,i)).toString())}async function x(i){const c=C(i.headers.get("cookie")),d=await f(c),w=W(c,t.cookieName,a(i,0));let S=l(i);try{S=await y.endSessionUrl(e,t.fetch,{postLogoutRedirectUri:l(i),sessionId:d?.sessionId})??S}catch(v){t.logger.warn("[pontive] could not reach the issuer to end its session:",v instanceof Error?v.message:String(v))}return O(S,w)}function z(i,c){return{...i,accessToken:c.access_token,refreshToken:c.refresh_token??i.refreshToken,expiresAt:te(c)}}async function ve(i){const c=new URL(i.url),d=C(i.headers.get("cookie")),w=ee(c.searchParams.get("returnTo"),t.afterSignInPath),S=c.searchParams.get("organization_id"),v=g=>{const R=new URL(w,$(t,i));return g&&R.searchParams.set(ne,g),R.toString()},P=await f(d);if(!P?.refreshToken)return O(l(i));if(!S)return O(v("invalid_request"));let E;try{E=await y.refreshTokens(e,t.fetch,P.refreshToken,S)}catch(g){return g instanceof y.TokenEndpointError&&g.code==="invalid_request"?O(v("not_a_member")):(t.logger.warn("[pontive] organization switch failed:",g instanceof Error?g.message:String(g)),O(v("switch_failed")))}return O(v(),await k(d,z(P,E),i))}async function fe(i){try{const c=await y.refreshTokens(e,t.fetch,i.refreshToken);return z(i,c)}catch(c){if(c instanceof y.TokenEndpointError&&c.status>=400&&c.status<500)return t.logger.warn("[pontive] refresh refused; signing out:",c.message),null;throw c}}return{async handle(i){const{pathname:c}=new URL(i.url);if(!c.startsWith(`${t.basePath}/`))return null;const d=c.slice(t.basePath.length+1);return d==="login"&&i.method==="GET"?A(i):d==="callback"&&i.method==="GET"?L(i):d==="logout"&&(i.method==="GET"||i.method==="POST")?x(i):d===G&&(i.method==="GET"||i.method==="POST")?ve(i):null},async getSession(i){const c=await f(C(i));return c?Date.now()>=c.expiresAt?(t.logger.warn("[pontive] the session's access token has expired and getSession cannot refresh it. Run the SDK's middleware on this path so it refreshes before the request is handled."),null):I(c):null},async refresh(i){const c=C(i.headers.get("cookie")),d=E=>({session:E,setCookies:[],cookieHeader:i.headers.get("cookie")??""}),w=await f(c);if(!w)return d(null);if(new URL(i.url).pathname.startsWith(`${t.basePath}/`))return d(Date.now()<w.expiresAt?I(w):null);if(Date.now()<w.expiresAt-t.refreshSkewSeconds*1e3)return d(I(w));const S=()=>({session:null,setCookies:W(c,t.cookieName,a(i,0)),cookieHeader:F(c)});if(!w.refreshToken)return S();let v;try{v=await s.run(w.refreshToken,()=>fe(w))}catch(E){return t.logger.warn("[pontive] refresh failed, will retry:",E instanceof Error?E.message:String(E)),d(Date.now()<w.expiresAt?I(w):null)}if(!v)return S();const P=await k(c,v,i);return{session:I(v),setCookies:P,cookieHeader:F(c)}}}}const ue="1.29.2",pe="claim";function He(t={},e={}){const r=_.processEnv(),s=_.withEnvFallback(t,r);if(_.keylessApplies(s,r))return Ke(s,e);const o=se(s),h=_.isDevelopment(r)?()=>de(le(e),o.issuer):async()=>null;return me(o,he(o),h)}function le(t){if(t.projectDir)return t.projectDir;const e=globalThis.process;if(typeof e?.cwd!="function")throw new T.KeylessUnavailableError("keyless mode needs a project directory (process.cwd)");return e.cwd()}async function de(t,e){try{const r=await T.readKeylessRecord(t);return r?.claim_token&&r.issuer.replace(/\/+$/,"")===e?r:null}catch{return null}}function M(t,e){return new Response(`${e}
2
2
  `,{status:t,headers:{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}})}function me(t,e,r){const s=`${t.basePath}/${pe}`;async function o(h){try{const a=await T.claimLinkFor(h,{fetch:t.fetch});return new Response(null,{status:302,headers:{location:a.url,"cache-control":"no-store","referrer-policy":"no-referrer"}})}catch(a){return a instanceof T.PontiveApiError&&a.status===409?M(409,"This Pontive instance has already been claimed. Nothing in your app changes; manage it in the Pontive dashboard."):a instanceof T.PontiveApiError&&a.status===404?M(410,T.goneMessage(h,"expired")):(t.logger.warn("[pontive] could not create a claim link:",a instanceof Error?a.message:String(a)),M(502,"Pontive could not create a claim link just now. Try again, or run `npx pontive claim`."))}}return{async handle(h){if(h.method==="GET"&&new URL(h.url).pathname===s){const a=await r();if(a)return o(a)}return e.handle(h)},getSession:h=>e.getSession(h),refresh:h=>e.refresh(h),async providerProps(){const h=await r();return{appId:t.clientId,domain:t.mode==="browser"?t.authPath:t.issuer,...h?{claimUrl:s}:{}}}}}const V=new Map,re=new Set;function Ke(t,e){const r=t.logger??console;let s,o,h=!1;async function a(){const p=le(e),l=(t.basePath??"/api/auth").replace(/\/+$/,"");let f=V.get(p);f||(f=T.ensureKeylessInstance({dir:p,redirectUris:t.redirectUri?[t.redirectUri]:T.loopbackCallbacks(l),client:{name:e.clientName??"@pontive/server",version:ue},fetch:t.fetch}),V.set(p,f),f.catch(()=>V.delete(p)));const k=await f;re.has(p)||(re.add(p),r.warn(`
3
3
  ${T.keylessMessage(k.record,{created:k.created})}
4
4
  `));const I=globalThis.process;if(I?.env)for(const[L,x]of Object.entries(k.env))x!==void 0&&!I.env[L]&&(I.env[L]=x);if(!t.clientSecret&&!k.env.PONTIVE_CLIENT_SECRET)throw new Error(`@pontive/server: ${T.KEYLESS_FILE} names ${k.record.instance_id}, but PONTIVE_CLIENT_SECRET is neither in ${T.ENV_FILE} nor in the environment. Put it back, or run \`npx pontive init --reset\`.`);const A=se({...t,issuer:t.issuer||k.env.PONTIVE_ISSUER,clientId:t.clientId||k.env.PONTIVE_CLIENT_ID,clientSecret:t.clientSecret||k.env.PONTIVE_CLIENT_SECRET,sessionSecret:t.sessionSecret||k.env.PONTIVE_SESSION_SECRET,fetch:ze(t.fetch,k.record,r)});return me(A,he(A),()=>de(p,A.issuer))}function u(){return o?Promise.reject(o):(s??=a().catch(p=>{throw s=void 0,p instanceof T.KeylessInstanceGoneError&&(o=p),p}),s)}function m(p){return p instanceof T.KeylessUnavailableError?(h||(h=!0,r.warn(`[pontive] ${p.message}. Requests here proceed without a session until the dev server restarts with the PONTIVE_* variables keyless mode wrote to .env.local.`)),!0):!1}return{async handle(p){try{return await(await u()).handle(p)}catch(l){if(m(l))return M(503,"Pontive keyless mode can't run in this runtime; restart the dev server.");throw l}},async getSession(p){try{return await(await u()).getSession(p)}catch(l){if(m(l))return null;throw l}},async refresh(p){try{return await(await u()).refresh(p)}catch(l){if(m(l))return{session:null,setCookies:[],cookieHeader:p.headers.get("cookie")??""};throw l}},async providerProps(){return(await u()).providerProps()}}}function ze(t,e,r){const s=t??((...h)=>fetch(...h));let o=!1;return async(h,a)=>{const u=await s(h,a);return u.status===401&&!o&&(typeof h=="string"?h:h instanceof URL?h.toString():h.url).startsWith(e.issuer)&&(o=!0,r.warn(`[pontive] ${T.goneMessage(e,"refused")}`)),u}}const n=encodeURIComponent;class Fe{constructor(e){this.core=e,this.domains=new We(e),this.instances=new Be(e),this.plans=new Je(e),this.projects=new Ye(e),this.workspaces=new Ze(e)}core;domains;instances;plans;projects;workspaces}class We{constructor(e){this.core=e}core;create(e,r){return this.core.request({host:"api",method:"POST",path:"/v1/domains",body:e},r)}delete(e,r){return this.core.request({host:"api",method:"DELETE",path:`/v1/domains/${n(e)}`},r)}list(e,r){return this.core.page("page",{host:"api",method:"GET",path:"/v1/domains",query:e},r)}verify(e,r){return this.core.request({host:"api",method:"POST",path:`/v1/domains/${n(e)}/verify`},r)}}class Be{constructor(e){this.core=e}core;create(e,r){return this.core.request({host:"api",method:"POST",path:"/v1/instances",body:e},r)}createMember(e,r,s){return this.core.request({host:"api",method:"POST",path:`/v1/instances/${n(e)}/members`,body:r},s)}createSecretKey(e,r,s){return this.core.request({host:"api",method:"POST",path:`/v1/instances/${n(e)}/secret-keys`,body:r},s)}delete(e,r,s){return this.core.request({host:"api",method:"DELETE",path:`/v1/instances/${n(e)}`,body:r},s)}deleteMember(e,r,s){return this.core.request({host:"api",method:"DELETE",path:`/v1/instances/${n(e)}/members/${n(r)}`},s)}get(e,r){return this.core.request({host:"api",method:"GET",path:`/v1/instances/${n(e)}`},r)}getAccess(e,r){return this.core.request({host:"api",method:"GET",path:`/v1/instances/${n(e)}/access`},r)}getSecretKey(e,r,s){return this.core.request({host:"api",method:"GET",path:`/v1/instances/${n(e)}/secret-keys/${n(r)}`},s)}list(e,r){return this.core.page("page",{host:"api",method:"GET",path:"/v1/instances",query:e},r)}listMembers(e,r,s){return this.core.page("page",{host:"api",method:"GET",path:`/v1/instances/${n(e)}/members`,query:r},s)}listSecretKeys(e,r,s){return this.core.page("page",{host:"api",method:"GET",path:`/v1/instances/${n(e)}/secret-keys`,query:r},s)}pause(e,r){return this.core.request({host:"api",method:"POST",path:`/v1/instances/${n(e)}/pause`},r)}purge(e,r){return this.core.request({host:"api",method:"POST",path:`/v1/instances/${n(e)}/purge`},r)}restore(e,r){return this.core.request({host:"api",method:"POST",path:`/v1/instances/${n(e)}/restore`},r)}resume(e,r){return this.core.request({host:"api",method:"POST",path:`/v1/instances/${n(e)}/resume`},r)}revokeSecretKey(e,r,s){return this.core.request({host:"api",method:"POST",path:`/v1/instances/${n(e)}/secret-keys/${n(r)}/revoke`},s)}rotateSecretKey(e,r,s,o){return this.core.request({host:"api",method:"POST",path:`/v1/instances/${n(e)}/secret-keys/${n(r)}/rotate`,body:s},o)}update(e,r,s){return this.core.request({host:"api",method:"PATCH",path:`/v1/instances/${n(e)}`,body:r},s)}updateMember(e,r,s,o){return this.core.request({host:"api",method:"PATCH",path:`/v1/instances/${n(e)}/members/${n(r)}`,body:s},o)}updateSecretKey(e,r,s,o){return this.core.request({host:"api",method:"PATCH",path:`/v1/instances/${n(e)}/secret-keys/${n(r)}`,body:s},o)}}class Je{constructor(e){this.core=e}core;list(e,r){return this.core.page("page",{host:"api",method:"GET",path:"/v1/plans",query:e},r)}}class Ye{constructor(e){this.core=e}core;create(e,r){return this.core.request({host:"api",method:"POST",path:"/v1/projects",body:e},r)}createInvitations(e,r,s){return this.core.request({host:"api",method:"POST",path:`/v1/projects/${n(e)}/invitations`,body:r},s)}createMember(e,r,s){return this.core.request({host:"api",method:"POST",path:`/v1/projects/${n(e)}/members`,body:r},s)}delete(e,r,s){return this.core.request({host:"api",method:"DELETE",path:`/v1/projects/${n(e)}`,body:r},s)}deleteInvitation(e,r,s,o){return this.core.request({host:"api",method:"DELETE",path:`/v1/projects/${n(e)}/invitations/${n(r)}`,query:s},o)}deleteMember(e,r,s){return this.core.request({host:"api",method:"DELETE",path:`/v1/projects/${n(e)}/members/${n(r)}`},s)}get(e,r){return this.core.request({host:"api",method:"GET",path:`/v1/projects/${n(e)}`},r)}getAccess(e,r){return this.core.request({host:"api",method:"GET",path:`/v1/projects/${n(e)}/access`},r)}list(e,r){return this.core.page("page",{host:"api",method:"GET",path:"/v1/projects",query:e},r)}listInvitations(e,r,s){return this.core.page("page",{host:"api",method:"GET",path:`/v1/projects/${n(e)}/invitations`,query:r},s)}listMembers(e,r,s){return this.core.page("page",{host:"api",method:"GET",path:`/v1/projects/${n(e)}/members`,query:r},s)}pause(e,r){return this.core.request({host:"api",method:"POST",path:`/v1/projects/${n(e)}/pause`},r)}purge(e,r){return this.core.request({host:"api",method:"POST",path:`/v1/projects/${n(e)}/purge`},r)}resendInvitation(e,r,s,o){return this.core.request({host:"api",method:"POST",path:`/v1/projects/${n(e)}/invitations/${n(r)}/resend`,body:s},o)}restore(e,r){return this.core.request({host:"api",method:"POST",path:`/v1/projects/${n(e)}/restore`},r)}resume(e,r){return this.core.request({host:"api",method:"POST",path:`/v1/projects/${n(e)}/resume`},r)}update(e,r,s){return this.core.request({host:"api",method:"PATCH",path:`/v1/projects/${n(e)}`,body:r},s)}updateMember(e,r,s,o){return this.core.request({host:"api",method:"PATCH",path:`/v1/projects/${n(e)}/members/${n(r)}`,body:s},o)}}class Ze{constructor(e){this.core=e,this.webhooks=new Xe(e)}core;webhooks;createInvitations(e,r,s){return this.core.request({host:"api",method:"POST",path:`/v1/workspaces/${n(e)}/invitations`,body:r},s)}deleteInvitation(e,r,s,o){return this.core.request({host:"api",method:"DELETE",path:`/v1/workspaces/${n(e)}/invitations/${n(r)}`,query:s},o)}deleteMember(e,r,s){return this.core.request({host:"api",method:"DELETE",path:`/v1/workspaces/${n(e)}/members/${n(r)}`},s)}get(e,r){return this.core.request({host:"api",method:"GET",path:`/v1/workspaces/${n(e)}`},r)}getAccess(e,r){return this.core.request({host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/access`},r)}getBilling(e,r){return this.core.request({host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/billing`},r)}getUsage(e,r){return this.core.request({host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/usage`},r)}list(e,r){return this.core.page("page",{host:"api",method:"GET",path:"/v1/workspaces",query:e},r)}listInvitations(e,r,s){return this.core.page("page",{host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/invitations`,query:r},s)}listMemberGrants(e,r,s,o){return this.core.page("page",{host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/members/${n(r)}/grants`,query:s},o)}listMembers(e,r,s){return this.core.page("page",{host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/members`,query:r},s)}resendInvitation(e,r,s,o){return this.core.request({host:"api",method:"POST",path:`/v1/workspaces/${n(e)}/invitations/${n(r)}/resend`,body:s},o)}update(e,r,s){return this.core.request({host:"api",method:"PATCH",path:`/v1/workspaces/${n(e)}`,body:r},s)}updateMember(e,r,s,o){return this.core.request({host:"api",method:"PATCH",path:`/v1/workspaces/${n(e)}/members/${n(r)}`,body:s},o)}}class Xe{constructor(e){this.core=e}core;createSubscription(e,r,s){return this.core.request({host:"api",method:"POST",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions`,body:r},s)}deleteSubscription(e,r,s){return this.core.request({host:"api",method:"DELETE",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions/${n(r)}`},s)}getActivity(e,r,s,o){return this.core.request({host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions/${n(r)}/activity`,query:s},o)}getDelivery(e,r,s,o){return this.core.request({host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions/${n(r)}/deliveries/${n(s)}`},o)}getEvent(e,r,s){return this.core.request({host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/webhooks/events/${n(r)}`},s)}getSubscription(e,r,s){return this.core.request({host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions/${n(r)}`},s)}listDeliveries(e,r,s,o){return this.core.page("cursor",{host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions/${n(r)}/deliveries`,query:s},o)}listEventTypes(e,r,s){return this.core.page("page",{host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/webhooks/event-types`,query:r},s)}listEvents(e,r,s){return this.core.page("cursor",{host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/webhooks/events`,query:r},s)}listSubscriptions(e,r,s){return this.core.page("page",{host:"api",method:"GET",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions`,query:r},s)}pauseSubscription(e,r,s){return this.core.request({host:"api",method:"POST",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions/${n(r)}/pause`},s)}resumeSubscription(e,r,s){return this.core.request({host:"api",method:"POST",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions/${n(r)}/resume`},s)}retryDelivery(e,r,s,o){return this.core.request({host:"api",method:"POST",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions/${n(r)}/deliveries/${n(s)}/retry`},o)}rotateSecret(e,r,s,o){return this.core.request({host:"api",method:"POST",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions/${n(r)}/rotate-secret`,body:s},o)}updateSubscription(e,r,s,o){return this.core.request({host:"api",method:"PATCH",path:`/v1/workspaces/${n(e)}/webhooks/subscriptions/${n(r)}`,body:s},o)}}const we="https://api.pontive.com",D=t=>t&&t.trim()?t.trim():void 0;function Qe(){const t=globalThis;return typeof t.window<"u"&&typeof t.document<"u"}class et extends Fe{constructor(e={}){const r=e.env??_.processEnv(),s=e.workspaceKey??(e.token?void 0:D(r.PONTIVE_WORKSPACE_KEY)),o=e.token??(s?void 0:D(r.PONTIVE_ACCESS_TOKEN));if(!s&&!o)throw new Error("pontive: no credential: pass workspaceKey or token, or set PONTIVE_WORKSPACE_KEY or PONTIVE_ACCESS_TOKEN");if(Qe())throw new Error("pontive: a workspace secret key or personal access token must never reach a browser; call the platform API from your server");const a={api:y.managementBase(e.platformUrl??D(r.PONTIVE_PLATFORM_URL)??we),authz:"",ingest:"",auth:""},u=s??o;super(new _.Core({hosts:a,token:async()=>typeof u=="function"?u():u,invalidate:()=>!1,maxRetries:Math.max(e.maxRetries??2,0),timeout:e.timeout??6e4,fetch:e.fetch??globalThis.fetch.bind(globalThis)}))}}exports.PONTIVE_ENV=_.PONTIVE_ENV;exports.Pontive=_.Pontive;exports.PontiveAPIError=_.PontiveAPIError;exports.PontiveConnectionError=_.PontiveConnectionError;exports.ACCESS_COOKIE=ie;exports.CLAIM_ROUTE=pe;exports.ORGANIZATION_ERROR_PARAM=ne;exports.PLATFORM_URL=we;exports.PONTIVE_SERVER_VERSION=ue;exports.PontivePlatform=et;exports.SESSION_HINT_COOKIE=ae;exports.SWITCH_ORGANIZATION_ROUTE=G;exports.createServerAuth=He;exports.switchOrganizationPath=ge;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { p as se, w as fe, k as ke, i as Ee, h as ye } from "./client-B5zZyWMn.js";
2
- import { j as Lt, d as Nt, e as xt, f as Gt } from "./client-B5zZyWMn.js";
1
+ import { p as se, w as fe, k as ke, i as Ee, h as ye } from "./client-B0haKLYX.js";
2
+ import { j as Lt, d as Nt, e as xt, f as Gt } from "./client-B0haKLYX.js";
3
3
  import { readKeylessRecord as Se, KeylessUnavailableError as ne, claimLinkFor as ge, PontiveApiError as V, goneMessage as oe, ensureKeylessInstance as Te, loopbackCallbacks as be, keylessMessage as Pe, KEYLESS_FILE as $e, ENV_FILE as _e, KeylessInstanceGoneError as Ie } from "./keyless.js";
4
4
  import { v as Oe, s as ie, u as Ce, r as K, T as z, e as L, f as Re, p as Ue, g as Ae, h as Le, i as Ne, m as xe } from "./management-credential-CynS93TR.js";
5
5
  import { decodeJwt as Ge, jwtDecrypt as Me, EncryptJWT as je } from "jose";
@@ -516,7 +516,7 @@ function ut(t) {
516
516
  }
517
517
  };
518
518
  }
519
- const lt = "1.29.0", dt = "claim";
519
+ const lt = "1.29.2", dt = "claim";
520
520
  function Ct(t = {}, e = {}) {
521
521
  const r = se(), s = fe(t, r);
522
522
  if (ke(s, r)) return mt(s, e);
@@ -3531,10 +3531,10 @@ export declare class MeBilling {
3531
3531
  * End-customer portal; billing-svc P124). Cancels the contract's pending change, a scheduled
3532
3532
  * downgrade, by deleting its edit: edit_id is the contract's pending_change.edit_id, and any other
3533
3533
  * edit is not_found. Only a change the end customer asked for, pending_change.initiated_by customer,
3534
- * may be cancelled here; one the client made is change_not_allowed. billing.contract.edit_canceled is
3535
- * written as for DELETE /v1/billing/contracts/{contract_id}/edits/{edit_id}. An instance user's token
3536
- * must be issued for the instance's me audience, https://{auth domain}/me/, with pontive:billing:pay
3537
- * (D31, D48).
3534
+ * may be cancelled here; one the client made is change_not_allowed. contract.edit_canceled is written
3535
+ * as for DELETE /v1/billing/contracts/{contract_id}/edits/{edit_id}. An instance user's token must be
3536
+ * issued for the instance's me audience, https://{auth domain}/me/, with pontive:billing:pay (D31,
3537
+ * D48).
3538
3538
  *
3539
3539
  * `DELETE /v1/me/billing/contracts/{contract_id}/edits/{edit_id}` (DeleteMyContractEdit)
3540
3540
  */
@@ -3531,10 +3531,10 @@ export declare class MeBilling {
3531
3531
  * End-customer portal; billing-svc P124). Cancels the contract's pending change, a scheduled
3532
3532
  * downgrade, by deleting its edit: edit_id is the contract's pending_change.edit_id, and any other
3533
3533
  * edit is not_found. Only a change the end customer asked for, pending_change.initiated_by customer,
3534
- * may be cancelled here; one the client made is change_not_allowed. billing.contract.edit_canceled is
3535
- * written as for DELETE /v1/billing/contracts/{contract_id}/edits/{edit_id}. An instance user's token
3536
- * must be issued for the instance's me audience, https://{auth domain}/me/, with pontive:billing:pay
3537
- * (D31, D48).
3534
+ * may be cancelled here; one the client made is change_not_allowed. contract.edit_canceled is written
3535
+ * as for DELETE /v1/billing/contracts/{contract_id}/edits/{edit_id}. An instance user's token must be
3536
+ * issued for the instance's me audience, https://{auth domain}/me/, with pontive:billing:pay (D31,
3537
+ * D48).
3538
3538
  *
3539
3539
  * `DELETE /v1/me/billing/contracts/{contract_id}/edits/{edit_id}` (DeleteMyContractEdit)
3540
3540
  */
@@ -1081,7 +1081,7 @@ export interface BillingEvent {
1081
1081
  */
1082
1082
  sequence: number;
1083
1083
  /**
1084
- * An event name the billing specs list, such as "billing.invoice.finalized".
1084
+ * An event name the billing specs list, such as "invoice.finalized".
1085
1085
  */
1086
1086
  type: string;
1087
1087
  }
@@ -3466,9 +3466,9 @@ export interface CustomerAccess {
3466
3466
  }
3467
3467
  /**
3468
3468
  * CustomerAccessFeature is one feature's value in an access, by its type. The gateway writes it as
3469
- * billing.customer.access_changed carries it: { type, value } for a boolean (true or false) or a
3470
- * numeric feature (a decimal string), and { type, allowance, per, limit, overage, exhausted } for a
3471
- * metered one, the metered fields inline.
3469
+ * customer.access_changed carries it: { type, value } for a boolean (true or false) or a numeric
3470
+ * feature (a decimal string), and { type, allowance, per, limit, overage, exhausted } for a metered
3471
+ * one, the metered fields inline.
3472
3472
  */
3473
3473
  export interface CustomerAccessFeature {
3474
3474
  /**
@@ -12639,7 +12639,7 @@ export interface ListEventsParams {
12639
12639
  */
12640
12640
  before?: string;
12641
12641
  /**
12642
- * repeated or comma separated
12642
+ * Event names, such as invoice.finalized; repeated or comma separated
12643
12643
  */
12644
12644
  type?: string;
12645
12645
  /**
@@ -1081,7 +1081,7 @@ export interface BillingEvent {
1081
1081
  */
1082
1082
  sequence: number;
1083
1083
  /**
1084
- * An event name the billing specs list, such as "billing.invoice.finalized".
1084
+ * An event name the billing specs list, such as "invoice.finalized".
1085
1085
  */
1086
1086
  type: string;
1087
1087
  }
@@ -3466,9 +3466,9 @@ export interface CustomerAccess {
3466
3466
  }
3467
3467
  /**
3468
3468
  * CustomerAccessFeature is one feature's value in an access, by its type. The gateway writes it as
3469
- * billing.customer.access_changed carries it: { type, value } for a boolean (true or false) or a
3470
- * numeric feature (a decimal string), and { type, allowance, per, limit, overage, exhausted } for a
3471
- * metered one, the metered fields inline.
3469
+ * customer.access_changed carries it: { type, value } for a boolean (true or false) or a numeric
3470
+ * feature (a decimal string), and { type, allowance, per, limit, overage, exhausted } for a metered
3471
+ * one, the metered fields inline.
3472
3472
  */
3473
3473
  export interface CustomerAccessFeature {
3474
3474
  /**
@@ -12639,7 +12639,7 @@ export interface ListEventsParams {
12639
12639
  */
12640
12640
  before?: string;
12641
12641
  /**
12642
- * repeated or comma separated
12642
+ * Event names, such as invoice.finalized; repeated or comma separated
12643
12643
  */
12644
12644
  type?: string;
12645
12645
  /**
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./client-BfPi8CfF.cjs");exports.APIPromise=r.APIPromise;exports.AuthenticationError=r.AuthenticationError;exports.BadRequestError=r.BadRequestError;exports.ConflictError=r.ConflictError;exports.InternalServerError=r.InternalServerError;exports.NotFoundError=r.NotFoundError;exports.Page=r.Page;exports.PagePromise=r.PagePromise;exports.PermissionDeniedError=r.PermissionDeniedError;exports.Pontive=r.Pontive;exports.PontiveAPIError=r.PontiveAPIError;exports.PontiveConnectionError=r.PontiveConnectionError;exports.PreconditionFailedError=r.PreconditionFailedError;exports.RateLimitError=r.RateLimitError;exports.UnprocessableEntityError=r.UnprocessableEntityError;exports.secretKeyRegion=r.secretKeyRegion;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./client-CYs-uotZ.cjs");exports.APIPromise=r.APIPromise;exports.AuthenticationError=r.AuthenticationError;exports.BadRequestError=r.BadRequestError;exports.ConflictError=r.ConflictError;exports.InternalServerError=r.InternalServerError;exports.NotFoundError=r.NotFoundError;exports.Page=r.Page;exports.PagePromise=r.PagePromise;exports.PermissionDeniedError=r.PermissionDeniedError;exports.Pontive=r.Pontive;exports.PontiveAPIError=r.PontiveAPIError;exports.PontiveConnectionError=r.PontiveConnectionError;exports.PreconditionFailedError=r.PreconditionFailedError;exports.RateLimitError=r.RateLimitError;exports.UnprocessableEntityError=r.UnprocessableEntityError;exports.secretKeyRegion=r.secretKeyRegion;
2
2
  //# sourceMappingURL=management.cjs.map
@@ -1,4 +1,4 @@
1
- import { A as e, a, B as s, C as i, I as n, N as t, P as E, b as P, c, d, e as m, f as g, g as l, R as v, U as A, s as I } from "./client-B5zZyWMn.js";
1
+ import { A as e, a, B as s, C as i, I as n, N as t, P as E, b as P, c, d, e as m, f as g, g as l, R as v, U as A, s as I } from "./client-B0haKLYX.js";
2
2
  export {
3
3
  e as APIPromise,
4
4
  a as AuthenticationError,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pontive/server",
3
- "version": "1.29.0",
3
+ "version": "1.29.2",
4
4
  "license": "MIT",
5
5
  "description": "The Pontive SDK for TypeScript servers: the management API client, sessions for apps (sign-in, a sealed session cookie, safe token refresh) and resource-server middleware for APIs and MCP servers, on Web Request/Response.",
6
6
  "type": "module",