@pontive/server 1.26.0 → 1.27.0

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 R=require("./client-fmMA2Var.cjs"),k=require("./keyless.cjs"),y=require("./management-credential--CmS8XaV.cjs"),D=require("jose"),me=10080*60;function te(e){const t=e.clientSecret?"server":"browser",n=["issuer","clientId"];t==="server"&&n.push("sessionSecret");for(const o of n)if(!e[o]){const c={issuer:"PONTIVE_ISSUER",clientId:"PONTIVE_CLIENT_ID",sessionSecret:"PONTIVE_SESSION_SECRET"}[o];throw new Error(`@pontive/server: ${o} is required${c?` (pass it, or set ${c})`:""}`)}if(t==="server"&&e.sessionSecret.length<32)throw new Error("@pontive/server: sessionSecret must be at least 32 characters");if(e.baseUrl)try{new URL(e.baseUrl)}catch{throw new Error(`@pontive/server: baseUrl "${e.baseUrl}" is not an absolute URL`)}return{mode:t,authPath:(e.authPath??"/__pontive").replace(/\/+$/,""),issuer:e.issuer.replace(/\/+$/,""),clientId:e.clientId,clientSecret:e.clientSecret||void 0,sessionSecret:e.sessionSecret??"",baseUrl:e.baseUrl?new URL(e.baseUrl).origin:void 0,scopes:e.scopes??"openid email profile offline_access",basePath:(e.basePath??"/api/auth").replace(/\/+$/,""),redirectUri:e.redirectUri,signInPath:e.signInPath??"/login",afterSignInPath:e.afterSignInPath??"/",prompt:e.prompt,cookieName:e.cookieName??"pontive_session",secureCookies:e.secureCookies,iframeSafe:e.iframeSafe??"auto",previewCallback:e.previewCallback??"auto",sessionMaxAgeSeconds:e.sessionMaxAgeSeconds??me,refreshSkewSeconds:e.refreshSkewSeconds??60,fetch:e.fetch??((...o)=>fetch(...o)),logger:e.logger??console}}const H=3500,j=16;function C(e){const t=new Map;if(!e)return t;for(const n of e.split(";")){const o=n.indexOf("=");if(o<0)continue;const c=n.slice(0,o).trim();!c||t.has(c)||t.set(c,n.slice(o+1).trim())}return t}function W(e){return[...e].map(([t,n])=>`${t}=${n}`).join("; ")}function N(e,t,n){const o=n.sameSite??"Lax",c=[`${e}=${t}`,"Path=/","HttpOnly",`SameSite=${o}`,`Max-Age=${n.maxAge}`];return(n.secure||o==="None")&&c.push("Secure"),c.join("; ")}function A(e,t){return t===0?e:`${e}.${t}`}function ve(e,t){const n=e.get(t);if(n===void 0)return null;let o=n;for(let c=1;c<j;c++){const a=e.get(A(t,c));if(a===void 0)break;o+=a}return o}function Se(e,t,n,o){const c=[],a=Math.max(1,Math.ceil(n.length/H));for(let i=0;i<a;i++){const l=n.slice(i*H,(i+1)*H);e.set(A(t,i),l),c.push(N(A(t,i),l,o))}for(let i=a;i<j;i++){const l=A(t,i);if(!e.has(l))break;e.delete(l),c.push(N(l,"",{...o,maxAge:0}))}return c}function K(e,t,n){const o=[];for(let c=0;c<j;c++){const a=A(t,c);if(!e.has(a)){if(c>0)break;continue}e.delete(a),o.push(N(a,"",{...n,maxAge:0}))}return o}const V="switch-organization",ne="organization_error",G=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[];function re(e){const t=e.org_id;return typeof t!="string"||t===""?null:{id:t,roles:G(e.roles),permissions:G(e.permissions)}}function Ee(e){try{return D.decodeJwt(e)}catch{return{}}}function ye(e,t,n="/"){const o=new URLSearchParams({organization_id:t,returnTo:n});return`${e}/${V}?${o.toString()}`}const oe="__Host-pontive_access",se="__Secure-pontive_session_state";function ke(e){const t=n=>typeof e[n]=="string"?e[n]:void 0;return{id:t("sub")??"",email:t("email"),name:t("name")??t("email"),username:t("preferred_username"),picture:t("picture"),emailVerified:e.email_verified===!0}}function ge(e){const t={issuer:e.issuer,clientId:e.clientId},n=new Map;function o(i){for(const[l,d]of n)d.expiresAt<=i&&n.delete(l)}async function c(i,l){const d=Date.now();o(d);const u=await y.sha256Hex(i),h=n.get(u);if(h)return h.profile;const m=y.userInfo(t,e.fetch,i).catch(S=>(n.delete(u),e.logger.warn("[pontive] could not read the user's profile:",S instanceof Error?S.message:String(S)),null));return n.set(u,{expiresAt:l,profile:m}),m}async function a(i){const l=C(i).get(oe);if(!l)return null;let d;try{d=await y.verifyJwt(t,e.fetch,l)}catch(m){return m.code!=="ERR_JWT_EXPIRED"&&e.logger.warn("[pontive] access token cookie refused:",m instanceof Error?m.message:String(m)),null}const u=(d.exp??0)*1e3,h=await c(l,u);return{user:ke({...h,...d,sub:d.sub}),accessToken:l,expiresAt:u,sessionId:typeof d.sid=="string"?d.sid:void 0,organization:re(d),claims:d}}return{async handle(i){const l=new URL(i.url);if(l.pathname!==`${e.basePath}/${V}`)return null;const d=l.searchParams.get("organization_id"),u=_e(l.searchParams.get("returnTo"));if(!d)return B(u);const h=new URL(`${e.authPath}/oauth2/session`,l.origin);return h.searchParams.set("client_id",e.clientId),h.searchParams.set("return_to",u),h.searchParams.set("organization_id",d),B(h.pathname+h.search)},getSession:a,async refresh(i){const l=i.headers.get("cookie"),d=await a(l),u={session:d,setCookies:[],cookieHeader:l??""};if(d||!C(l).has(se))return u;const h=new URL(i.url),m=new URL(`${e.authPath}/oauth2/session`,h.origin);return m.searchParams.set("client_id",e.clientId),m.searchParams.set("return_to",h.pathname+h.search),{...u,handshake:m.pathname+m.search}}}}function _e(e){return e&&e.startsWith("/")&&!e.startsWith("//")&&!e.startsWith("/\\")?e:"/"}function B(e){return new Response(null,{status:302,headers:{location:e,"cache-control":"no-store"}})}const Pe=["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(e){const t=e.toLowerCase().replace(/\.$/,"");return Pe.some(n=>t===n||t.endsWith(`.${n}`))}const be={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"]},Te="/oauth2/preview-callback",Re="pontive:authorization-response",Ue=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function Ce(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!=="https:"||t.port!==""||t.origin!==e)return null;const n=t.hostname.split(".");for(const[o,c]of Object.entries(be))for(const a of c){const i=a.split(".");if(i.length===n.length&&i.every((l,d)=>l==="*"?Ue.test(n[d]):l===n[d]))return o}return null}function Oe(e,t){return`${e.replace(/\/$/,"")}${Te}?origin=${encodeURIComponent(t)}`}const Ae=3e4;class Ne{constructor(t=Ae){this.recentMs=t}recentMs;inFlight=new Map;recent=new Map;async run(t,n){const o=await y.sha256Hex(t);this.sweep();const c=this.recent.get(o);if(c)return c.result;let a=this.inFlight.get(o);return a||(a=n().then(i=>(this.recent.set(o,{at:Date.now(),result:i}),i)).finally(()=>this.inFlight.delete(o)),this.inFlight.set(o,a)),a}sweep(){const t=Date.now()-this.recentMs;for(const[n,o]of this.recent)o.at<t&&this.recent.delete(n)}}const J=new Map;function ie(e){let t=J.get(e);return t||(t=crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)).then(n=>new Uint8Array(n)),J.set(e,t)),t}async function Z(e,t,n){return new D.EncryptJWT(e).setProtectedHeader({alg:"dir",enc:"A256GCM"}).setIssuedAt().setExpirationTime(`${n}s`).encrypt(await ie(t))}async function X(e,t){try{const{payload:n}=await D.jwtDecrypt(e,await ie(t));return n}catch{return null}}const $e=900,Y=600;function Q(e,t){return e&&e.startsWith("/")&&!e.startsWith("//")&&!e.startsWith("/\\")?e:t}function T(e,t=[]){const n=new Headers({location:e,"cache-control":"no-store"});for(const o of t)n.append("set-cookie",o);return new Response(null,{status:302,headers:n})}const Le="pontive:popup-complete";function xe(e,t,n){const c=`<!doctype html><meta charset="utf-8"><title>Signing in</title><script type="application/json" id="pontive-popup">${JSON.stringify({message:{type:Le,url:e},origin:t}).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>`,a=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 i of n)a.append("set-cookie",i);return new Response(c,{status:200,headers:a})}function Ve(e){const t=y.randomValue(),o=`<!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({...e,type:Re}).replace(/</g,"\\u003c")}<\/script><script nonce="${t}">(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(o,{status:200,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store","content-security-policy":`default-src 'none'; script-src 'nonce-${t}'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`,"x-content-type-options":"nosniff","referrer-policy":"no-referrer"}})}function I(e,t){if(e.baseUrl)return e.baseUrl;const n=t.headers.get("x-forwarded-host")?.split(",")[0]?.trim()||t.headers.get("host")?.trim();if(n){const o=t.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()||new URL(t.url).protocol.replace(":","");try{return new URL(`${o}://${n}`).origin}catch{}}return new URL(t.url).origin}function Me(e){const t=o=>typeof e[o]=="string"?e[o]:void 0,n=t("name")??([t("given_name"),t("family_name")].filter(Boolean).join(" ")||void 0)??t("email");return{id:e.sub??"",email:t("email"),name:n,username:t("preferred_username"),picture:t("picture"),emailVerified:e.email_verified===!0}}function q(e){return Date.now()+(e.expires_in??$e)*1e3}function ae(e){return e.mode==="browser"?ge(e):He(e)}function He(e){const t={issuer:e.issuer,clientId:e.clientId,clientSecret:e.clientSecret},n=`${e.cookieName}_tx`,o=new Ne,c=r=>e.secureCookies??I(e,r).startsWith("https:"),a=r=>e.iframeSafe===!0||e.iframeSafe==="auto"&&Ie(new URL(I(e,r)).hostname),i=(r,s)=>a(r)?{maxAge:s,secure:!0,sameSite:"None"}:{maxAge:s,secure:c(r)},l=r=>e.previewCallback==="always"||e.previewCallback==="auto"&&Ce(I(e,r))!==null,d=r=>`${I(e,r)}${e.basePath}/callback`,u=r=>l(r)?Oe(e.issuer,I(e,r)):e.redirectUri??d(r),h=(r,s)=>{const p=new URL(e.signInPath,I(e,r));return s&&p.searchParams.set("error",s),p.toString()};async function m(r){const s=ve(r,e.cookieName);if(s===null)return null;const p=await X(s,e.sessionSecret);return p||e.logger.warn("[pontive] session cookie could not be read (sealed with another secret, or truncated)"),p}async function S(r,s,p){const f=await Z({...s},e.sessionSecret,e.sessionMaxAgeSeconds);return Se(r,e.cookieName,f,i(p,e.sessionMaxAgeSeconds))}function b(r){const{refreshToken:s,...p}=r,f=Ee(r.accessToken);return{...p,organization:re(f),claims:f}}async function O(r){const s=new URL(r.url),p=l(r),f=s.searchParams.get("popup")==="1";if(p&&!f){const v=new URL(`${e.basePath}/login`,I(e,r));return s.searchParams.forEach((g,U)=>v.searchParams.set(U,g)),v.searchParams.set("popup","1"),Ve({popupUrl:v.toString(),authOrigin:new URL(e.issuer).origin,callbackUrl:d(r)})}const E={state:y.randomValue(),verifier:y.randomValue(),nonce:y.randomValue(),returnTo:Q(s.searchParams.get("returnTo")??s.searchParams.get("next"),e.afterSignInPath),popup:f,redirectUri:u(r),previewCallback:p},w=await y.authorizationUrl(t,e.fetch,{redirectUri:E.redirectUri,scopes:e.scopes,state:E.state,nonce:E.nonce,codeChallenge:await y.pkceChallenge(E.verifier),prompt:e.prompt,organizationId:s.searchParams.get("organization_id")??void 0,loginHint:s.searchParams.get("login_hint")??void 0}),P=await Z({...E},e.sessionSecret,Y);return T(w,[N(n,P,i(r,Y))])}async function $(r){const s=new URL(r.url),p=C(r.headers.get("cookie")),f=[N(n,"",i(r,0))],E=p.get(n),w=E?await X(E,e.sessionSecret):null,P=s.searchParams.get("code"),v=_=>w?.popup&&!w.previewCallback?xe(_,I(e,r),f):T(_,f),g=s.searchParams.get("error");if(g)return v(h(r,g));if(!w||!P||s.searchParams.get("state")!==w.state)return v(h(r,"invalid_state"));const U=s.searchParams.get("iss");if(w.previewCallback&&U!==null&&U!==e.issuer)return v(h(r,"invalid_issuer"));try{const _=await y.exchangeCode(t,e.fetch,{code:P,codeVerifier:w.verifier,redirectUri:w.redirectUri??u(r)});if(!_.id_token)throw new Error("the token response carried no id_token; is the openid scope requested?");const M=await y.verifyIdToken(t,e.fetch,_.id_token,w.nonce),we={user:Me(M),accessToken:_.access_token,refreshToken:_.refresh_token,expiresAt:q(_),sessionId:typeof M.sid=="string"?M.sid:void 0};f.push(...await S(p,we,r))}catch(_){return e.logger.warn("[pontive] sign-in failed:",_ instanceof Error?_.message:String(_)),v(h(r,"exchange_failed"))}return v(new URL(w.returnTo,I(e,r)).toString())}async function L(r){const s=C(r.headers.get("cookie")),p=await m(s),f=K(s,e.cookieName,i(r,0));let E=h(r);try{E=await y.endSessionUrl(t,e.fetch,{postLogoutRedirectUri:h(r),sessionId:p?.sessionId})??E}catch(w){e.logger.warn("[pontive] could not reach the issuer to end its session:",w instanceof Error?w.message:String(w))}return T(E,f)}function F(r,s){return{...r,accessToken:s.access_token,refreshToken:s.refresh_token??r.refreshToken,expiresAt:q(s)}}async function de(r){const s=new URL(r.url),p=C(r.headers.get("cookie")),f=Q(s.searchParams.get("returnTo"),e.afterSignInPath),E=s.searchParams.get("organization_id"),w=g=>{const U=new URL(f,I(e,r));return g&&U.searchParams.set(ne,g),U.toString()},P=await m(p);if(!P?.refreshToken)return T(h(r));if(!E)return T(w("invalid_request"));let v;try{v=await y.refreshTokens(t,e.fetch,P.refreshToken,E)}catch(g){return g instanceof y.TokenEndpointError&&g.code==="invalid_request"?T(w("not_a_member")):(e.logger.warn("[pontive] organization switch failed:",g instanceof Error?g.message:String(g)),T(w("switch_failed")))}return T(w(),await S(p,F(P,v),r))}async function fe(r){try{const s=await y.refreshTokens(t,e.fetch,r.refreshToken);return F(r,s)}catch(s){if(s instanceof y.TokenEndpointError&&s.status>=400&&s.status<500)return e.logger.warn("[pontive] refresh refused; signing out:",s.message),null;throw s}}return{async handle(r){const{pathname:s}=new URL(r.url);if(!s.startsWith(`${e.basePath}/`))return null;const p=s.slice(e.basePath.length+1);return p==="login"&&r.method==="GET"?O(r):p==="callback"&&r.method==="GET"?$(r):p==="logout"&&(r.method==="GET"||r.method==="POST")?L(r):p===V&&(r.method==="GET"||r.method==="POST")?de(r):null},async getSession(r){const s=await m(C(r));return s?Date.now()>=s.expiresAt?(e.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):b(s):null},async refresh(r){const s=C(r.headers.get("cookie")),p=v=>({session:v,setCookies:[],cookieHeader:r.headers.get("cookie")??""}),f=await m(s);if(!f)return p(null);if(new URL(r.url).pathname.startsWith(`${e.basePath}/`))return p(Date.now()<f.expiresAt?b(f):null);if(Date.now()<f.expiresAt-e.refreshSkewSeconds*1e3)return p(b(f));const E=()=>({session:null,setCookies:K(s,e.cookieName,i(r,0)),cookieHeader:W(s)});if(!f.refreshToken)return E();let w;try{w=await o.run(f.refreshToken,()=>fe(f))}catch(v){return e.logger.warn("[pontive] refresh failed, will retry:",v instanceof Error?v.message:String(v)),p(Date.now()<f.expiresAt?b(f):null)}if(!w)return E();const P=await S(s,w,r);return{session:b(w),setCookies:P,cookieHeader:W(s)}}}}const ce="1.26.0",le="claim";function ze(e={},t={}){const n=R.processEnv(),o=R.withEnvFallback(e,n);if(R.keylessApplies(o,n))return De(o,t);const c=te(o),a=R.isDevelopment(n)?()=>he(ue(t),c.issuer):async()=>null;return pe(c,ae(c),a)}function ue(e){if(e.projectDir)return e.projectDir;const t=globalThis.process;if(typeof t?.cwd!="function")throw new k.KeylessUnavailableError("keyless mode needs a project directory (process.cwd)");return t.cwd()}async function he(e,t){try{const n=await k.readKeylessRecord(e);return n?.claim_token&&n.issuer.replace(/\/+$/,"")===t?n:null}catch{return null}}function x(e,t){return new Response(`${t}
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("./client-DdtDcUK9.cjs"),k=require("./keyless.cjs"),y=require("./management-credential--CmS8XaV.cjs"),D=require("jose"),me=10080*60;function te(e){const t=e.clientSecret?"server":"browser",n=["issuer","clientId"];t==="server"&&n.push("sessionSecret");for(const o of n)if(!e[o]){const c={issuer:"PONTIVE_ISSUER",clientId:"PONTIVE_CLIENT_ID",sessionSecret:"PONTIVE_SESSION_SECRET"}[o];throw new Error(`@pontive/server: ${o} is required${c?` (pass it, or set ${c})`:""}`)}if(t==="server"&&e.sessionSecret.length<32)throw new Error("@pontive/server: sessionSecret must be at least 32 characters");if(e.baseUrl)try{new URL(e.baseUrl)}catch{throw new Error(`@pontive/server: baseUrl "${e.baseUrl}" is not an absolute URL`)}return{mode:t,authPath:(e.authPath??"/__pontive").replace(/\/+$/,""),issuer:e.issuer.replace(/\/+$/,""),clientId:e.clientId,clientSecret:e.clientSecret||void 0,sessionSecret:e.sessionSecret??"",baseUrl:e.baseUrl?new URL(e.baseUrl).origin:void 0,scopes:e.scopes??"openid email profile offline_access",basePath:(e.basePath??"/api/auth").replace(/\/+$/,""),redirectUri:e.redirectUri,signInPath:e.signInPath??"/login",afterSignInPath:e.afterSignInPath??"/",prompt:e.prompt,cookieName:e.cookieName??"pontive_session",secureCookies:e.secureCookies,iframeSafe:e.iframeSafe??"auto",previewCallback:e.previewCallback??"auto",sessionMaxAgeSeconds:e.sessionMaxAgeSeconds??me,refreshSkewSeconds:e.refreshSkewSeconds??60,fetch:e.fetch??((...o)=>fetch(...o)),logger:e.logger??console}}const H=3500,j=16;function C(e){const t=new Map;if(!e)return t;for(const n of e.split(";")){const o=n.indexOf("=");if(o<0)continue;const c=n.slice(0,o).trim();!c||t.has(c)||t.set(c,n.slice(o+1).trim())}return t}function W(e){return[...e].map(([t,n])=>`${t}=${n}`).join("; ")}function N(e,t,n){const o=n.sameSite??"Lax",c=[`${e}=${t}`,"Path=/","HttpOnly",`SameSite=${o}`,`Max-Age=${n.maxAge}`];return(n.secure||o==="None")&&c.push("Secure"),c.join("; ")}function A(e,t){return t===0?e:`${e}.${t}`}function ve(e,t){const n=e.get(t);if(n===void 0)return null;let o=n;for(let c=1;c<j;c++){const a=e.get(A(t,c));if(a===void 0)break;o+=a}return o}function Se(e,t,n,o){const c=[],a=Math.max(1,Math.ceil(n.length/H));for(let i=0;i<a;i++){const l=n.slice(i*H,(i+1)*H);e.set(A(t,i),l),c.push(N(A(t,i),l,o))}for(let i=a;i<j;i++){const l=A(t,i);if(!e.has(l))break;e.delete(l),c.push(N(l,"",{...o,maxAge:0}))}return c}function K(e,t,n){const o=[];for(let c=0;c<j;c++){const a=A(t,c);if(!e.has(a)){if(c>0)break;continue}e.delete(a),o.push(N(a,"",{...n,maxAge:0}))}return o}const V="switch-organization",ne="organization_error",G=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[];function re(e){const t=e.org_id;return typeof t!="string"||t===""?null:{id:t,roles:G(e.roles),permissions:G(e.permissions)}}function Ee(e){try{return D.decodeJwt(e)}catch{return{}}}function ye(e,t,n="/"){const o=new URLSearchParams({organization_id:t,returnTo:n});return`${e}/${V}?${o.toString()}`}const oe="__Host-pontive_access",se="__Secure-pontive_session_state";function ke(e){const t=n=>typeof e[n]=="string"?e[n]:void 0;return{id:t("sub")??"",email:t("email"),name:t("name")??t("email"),username:t("preferred_username"),picture:t("picture"),emailVerified:e.email_verified===!0}}function ge(e){const t={issuer:e.issuer,clientId:e.clientId},n=new Map;function o(i){for(const[l,d]of n)d.expiresAt<=i&&n.delete(l)}async function c(i,l){const d=Date.now();o(d);const u=await y.sha256Hex(i),h=n.get(u);if(h)return h.profile;const m=y.userInfo(t,e.fetch,i).catch(S=>(n.delete(u),e.logger.warn("[pontive] could not read the user's profile:",S instanceof Error?S.message:String(S)),null));return n.set(u,{expiresAt:l,profile:m}),m}async function a(i){const l=C(i).get(oe);if(!l)return null;let d;try{d=await y.verifyJwt(t,e.fetch,l)}catch(m){return m.code!=="ERR_JWT_EXPIRED"&&e.logger.warn("[pontive] access token cookie refused:",m instanceof Error?m.message:String(m)),null}const u=(d.exp??0)*1e3,h=await c(l,u);return{user:ke({...h,...d,sub:d.sub}),accessToken:l,expiresAt:u,sessionId:typeof d.sid=="string"?d.sid:void 0,organization:re(d),claims:d}}return{async handle(i){const l=new URL(i.url);if(l.pathname!==`${e.basePath}/${V}`)return null;const d=l.searchParams.get("organization_id"),u=_e(l.searchParams.get("returnTo"));if(!d)return B(u);const h=new URL(`${e.authPath}/oauth2/session`,l.origin);return h.searchParams.set("client_id",e.clientId),h.searchParams.set("return_to",u),h.searchParams.set("organization_id",d),B(h.pathname+h.search)},getSession:a,async refresh(i){const l=i.headers.get("cookie"),d=await a(l),u={session:d,setCookies:[],cookieHeader:l??""};if(d||!C(l).has(se))return u;const h=new URL(i.url),m=new URL(`${e.authPath}/oauth2/session`,h.origin);return m.searchParams.set("client_id",e.clientId),m.searchParams.set("return_to",h.pathname+h.search),{...u,handshake:m.pathname+m.search}}}}function _e(e){return e&&e.startsWith("/")&&!e.startsWith("//")&&!e.startsWith("/\\")?e:"/"}function B(e){return new Response(null,{status:302,headers:{location:e,"cache-control":"no-store"}})}const Pe=["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(e){const t=e.toLowerCase().replace(/\.$/,"");return Pe.some(n=>t===n||t.endsWith(`.${n}`))}const be={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"]},Te="/oauth2/preview-callback",Re="pontive:authorization-response",Ue=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function Ce(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!=="https:"||t.port!==""||t.origin!==e)return null;const n=t.hostname.split(".");for(const[o,c]of Object.entries(be))for(const a of c){const i=a.split(".");if(i.length===n.length&&i.every((l,d)=>l==="*"?Ue.test(n[d]):l===n[d]))return o}return null}function Oe(e,t){return`${e.replace(/\/$/,"")}${Te}?origin=${encodeURIComponent(t)}`}const Ae=3e4;class Ne{constructor(t=Ae){this.recentMs=t}recentMs;inFlight=new Map;recent=new Map;async run(t,n){const o=await y.sha256Hex(t);this.sweep();const c=this.recent.get(o);if(c)return c.result;let a=this.inFlight.get(o);return a||(a=n().then(i=>(this.recent.set(o,{at:Date.now(),result:i}),i)).finally(()=>this.inFlight.delete(o)),this.inFlight.set(o,a)),a}sweep(){const t=Date.now()-this.recentMs;for(const[n,o]of this.recent)o.at<t&&this.recent.delete(n)}}const J=new Map;function ie(e){let t=J.get(e);return t||(t=crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)).then(n=>new Uint8Array(n)),J.set(e,t)),t}async function Z(e,t,n){return new D.EncryptJWT(e).setProtectedHeader({alg:"dir",enc:"A256GCM"}).setIssuedAt().setExpirationTime(`${n}s`).encrypt(await ie(t))}async function X(e,t){try{const{payload:n}=await D.jwtDecrypt(e,await ie(t));return n}catch{return null}}const $e=900,Y=600;function Q(e,t){return e&&e.startsWith("/")&&!e.startsWith("//")&&!e.startsWith("/\\")?e:t}function T(e,t=[]){const n=new Headers({location:e,"cache-control":"no-store"});for(const o of t)n.append("set-cookie",o);return new Response(null,{status:302,headers:n})}const Le="pontive:popup-complete";function xe(e,t,n){const c=`<!doctype html><meta charset="utf-8"><title>Signing in</title><script type="application/json" id="pontive-popup">${JSON.stringify({message:{type:Le,url:e},origin:t}).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>`,a=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 i of n)a.append("set-cookie",i);return new Response(c,{status:200,headers:a})}function Ve(e){const t=y.randomValue(),o=`<!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({...e,type:Re}).replace(/</g,"\\u003c")}<\/script><script nonce="${t}">(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(o,{status:200,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store","content-security-policy":`default-src 'none'; script-src 'nonce-${t}'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`,"x-content-type-options":"nosniff","referrer-policy":"no-referrer"}})}function I(e,t){if(e.baseUrl)return e.baseUrl;const n=t.headers.get("x-forwarded-host")?.split(",")[0]?.trim()||t.headers.get("host")?.trim();if(n){const o=t.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()||new URL(t.url).protocol.replace(":","");try{return new URL(`${o}://${n}`).origin}catch{}}return new URL(t.url).origin}function Me(e){const t=o=>typeof e[o]=="string"?e[o]:void 0,n=t("name")??([t("given_name"),t("family_name")].filter(Boolean).join(" ")||void 0)??t("email");return{id:e.sub??"",email:t("email"),name:n,username:t("preferred_username"),picture:t("picture"),emailVerified:e.email_verified===!0}}function q(e){return Date.now()+(e.expires_in??$e)*1e3}function ae(e){return e.mode==="browser"?ge(e):He(e)}function He(e){const t={issuer:e.issuer,clientId:e.clientId,clientSecret:e.clientSecret},n=`${e.cookieName}_tx`,o=new Ne,c=r=>e.secureCookies??I(e,r).startsWith("https:"),a=r=>e.iframeSafe===!0||e.iframeSafe==="auto"&&Ie(new URL(I(e,r)).hostname),i=(r,s)=>a(r)?{maxAge:s,secure:!0,sameSite:"None"}:{maxAge:s,secure:c(r)},l=r=>e.previewCallback==="always"||e.previewCallback==="auto"&&Ce(I(e,r))!==null,d=r=>`${I(e,r)}${e.basePath}/callback`,u=r=>l(r)?Oe(e.issuer,I(e,r)):e.redirectUri??d(r),h=(r,s)=>{const p=new URL(e.signInPath,I(e,r));return s&&p.searchParams.set("error",s),p.toString()};async function m(r){const s=ve(r,e.cookieName);if(s===null)return null;const p=await X(s,e.sessionSecret);return p||e.logger.warn("[pontive] session cookie could not be read (sealed with another secret, or truncated)"),p}async function S(r,s,p){const f=await Z({...s},e.sessionSecret,e.sessionMaxAgeSeconds);return Se(r,e.cookieName,f,i(p,e.sessionMaxAgeSeconds))}function b(r){const{refreshToken:s,...p}=r,f=Ee(r.accessToken);return{...p,organization:re(f),claims:f}}async function O(r){const s=new URL(r.url),p=l(r),f=s.searchParams.get("popup")==="1";if(p&&!f){const v=new URL(`${e.basePath}/login`,I(e,r));return s.searchParams.forEach((g,U)=>v.searchParams.set(U,g)),v.searchParams.set("popup","1"),Ve({popupUrl:v.toString(),authOrigin:new URL(e.issuer).origin,callbackUrl:d(r)})}const E={state:y.randomValue(),verifier:y.randomValue(),nonce:y.randomValue(),returnTo:Q(s.searchParams.get("returnTo")??s.searchParams.get("next"),e.afterSignInPath),popup:f,redirectUri:u(r),previewCallback:p},w=await y.authorizationUrl(t,e.fetch,{redirectUri:E.redirectUri,scopes:e.scopes,state:E.state,nonce:E.nonce,codeChallenge:await y.pkceChallenge(E.verifier),prompt:e.prompt,organizationId:s.searchParams.get("organization_id")??void 0,loginHint:s.searchParams.get("login_hint")??void 0}),P=await Z({...E},e.sessionSecret,Y);return T(w,[N(n,P,i(r,Y))])}async function $(r){const s=new URL(r.url),p=C(r.headers.get("cookie")),f=[N(n,"",i(r,0))],E=p.get(n),w=E?await X(E,e.sessionSecret):null,P=s.searchParams.get("code"),v=_=>w?.popup&&!w.previewCallback?xe(_,I(e,r),f):T(_,f),g=s.searchParams.get("error");if(g)return v(h(r,g));if(!w||!P||s.searchParams.get("state")!==w.state)return v(h(r,"invalid_state"));const U=s.searchParams.get("iss");if(w.previewCallback&&U!==null&&U!==e.issuer)return v(h(r,"invalid_issuer"));try{const _=await y.exchangeCode(t,e.fetch,{code:P,codeVerifier:w.verifier,redirectUri:w.redirectUri??u(r)});if(!_.id_token)throw new Error("the token response carried no id_token; is the openid scope requested?");const M=await y.verifyIdToken(t,e.fetch,_.id_token,w.nonce),we={user:Me(M),accessToken:_.access_token,refreshToken:_.refresh_token,expiresAt:q(_),sessionId:typeof M.sid=="string"?M.sid:void 0};f.push(...await S(p,we,r))}catch(_){return e.logger.warn("[pontive] sign-in failed:",_ instanceof Error?_.message:String(_)),v(h(r,"exchange_failed"))}return v(new URL(w.returnTo,I(e,r)).toString())}async function L(r){const s=C(r.headers.get("cookie")),p=await m(s),f=K(s,e.cookieName,i(r,0));let E=h(r);try{E=await y.endSessionUrl(t,e.fetch,{postLogoutRedirectUri:h(r),sessionId:p?.sessionId})??E}catch(w){e.logger.warn("[pontive] could not reach the issuer to end its session:",w instanceof Error?w.message:String(w))}return T(E,f)}function F(r,s){return{...r,accessToken:s.access_token,refreshToken:s.refresh_token??r.refreshToken,expiresAt:q(s)}}async function de(r){const s=new URL(r.url),p=C(r.headers.get("cookie")),f=Q(s.searchParams.get("returnTo"),e.afterSignInPath),E=s.searchParams.get("organization_id"),w=g=>{const U=new URL(f,I(e,r));return g&&U.searchParams.set(ne,g),U.toString()},P=await m(p);if(!P?.refreshToken)return T(h(r));if(!E)return T(w("invalid_request"));let v;try{v=await y.refreshTokens(t,e.fetch,P.refreshToken,E)}catch(g){return g instanceof y.TokenEndpointError&&g.code==="invalid_request"?T(w("not_a_member")):(e.logger.warn("[pontive] organization switch failed:",g instanceof Error?g.message:String(g)),T(w("switch_failed")))}return T(w(),await S(p,F(P,v),r))}async function fe(r){try{const s=await y.refreshTokens(t,e.fetch,r.refreshToken);return F(r,s)}catch(s){if(s instanceof y.TokenEndpointError&&s.status>=400&&s.status<500)return e.logger.warn("[pontive] refresh refused; signing out:",s.message),null;throw s}}return{async handle(r){const{pathname:s}=new URL(r.url);if(!s.startsWith(`${e.basePath}/`))return null;const p=s.slice(e.basePath.length+1);return p==="login"&&r.method==="GET"?O(r):p==="callback"&&r.method==="GET"?$(r):p==="logout"&&(r.method==="GET"||r.method==="POST")?L(r):p===V&&(r.method==="GET"||r.method==="POST")?de(r):null},async getSession(r){const s=await m(C(r));return s?Date.now()>=s.expiresAt?(e.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):b(s):null},async refresh(r){const s=C(r.headers.get("cookie")),p=v=>({session:v,setCookies:[],cookieHeader:r.headers.get("cookie")??""}),f=await m(s);if(!f)return p(null);if(new URL(r.url).pathname.startsWith(`${e.basePath}/`))return p(Date.now()<f.expiresAt?b(f):null);if(Date.now()<f.expiresAt-e.refreshSkewSeconds*1e3)return p(b(f));const E=()=>({session:null,setCookies:K(s,e.cookieName,i(r,0)),cookieHeader:W(s)});if(!f.refreshToken)return E();let w;try{w=await o.run(f.refreshToken,()=>fe(f))}catch(v){return e.logger.warn("[pontive] refresh failed, will retry:",v instanceof Error?v.message:String(v)),p(Date.now()<f.expiresAt?b(f):null)}if(!w)return E();const P=await S(s,w,r);return{session:b(w),setCookies:P,cookieHeader:W(s)}}}}const ce="1.27.0",le="claim";function ze(e={},t={}){const n=R.processEnv(),o=R.withEnvFallback(e,n);if(R.keylessApplies(o,n))return De(o,t);const c=te(o),a=R.isDevelopment(n)?()=>he(ue(t),c.issuer):async()=>null;return pe(c,ae(c),a)}function ue(e){if(e.projectDir)return e.projectDir;const t=globalThis.process;if(typeof t?.cwd!="function")throw new k.KeylessUnavailableError("keyless mode needs a project directory (process.cwd)");return t.cwd()}async function he(e,t){try{const n=await k.readKeylessRecord(e);return n?.claim_token&&n.issuer.replace(/\/+$/,"")===t?n:null}catch{return null}}function x(e,t){return new Response(`${t}
2
2
  `,{status:e,headers:{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}})}function pe(e,t,n){const o=`${e.basePath}/${le}`;async function c(a){try{const i=await k.claimLinkFor(a,{fetch:e.fetch});return new Response(null,{status:302,headers:{location:i.url,"cache-control":"no-store","referrer-policy":"no-referrer"}})}catch(i){return i instanceof k.PontiveApiError&&i.status===409?x(409,"This Pontive instance has already been claimed. Nothing in your app changes; manage it in the Pontive dashboard."):i instanceof k.PontiveApiError&&i.status===404?x(410,k.goneMessage(a,"expired")):(e.logger.warn("[pontive] could not create a claim link:",i instanceof Error?i.message:String(i)),x(502,"Pontive could not create a claim link just now. Try again, or run `npx pontive claim`."))}}return{async handle(a){if(a.method==="GET"&&new URL(a.url).pathname===o){const i=await n();if(i)return c(i)}return t.handle(a)},getSession:a=>t.getSession(a),refresh:a=>t.refresh(a),async providerProps(){const a=await n();return{appId:e.clientId,domain:e.mode==="browser"?e.authPath:e.issuer,...a?{claimUrl:o}:{}}}}}const z=new Map,ee=new Set;function De(e,t){const n=e.logger??console;let o,c,a=!1;async function i(){const u=ue(t),h=(e.basePath??"/api/auth").replace(/\/+$/,"");let m=z.get(u);m||(m=k.ensureKeylessInstance({dir:u,redirectUris:e.redirectUri?[e.redirectUri]:k.loopbackCallbacks(h),client:{name:t.clientName??"@pontive/server",version:ce},fetch:e.fetch}),z.set(u,m),m.catch(()=>z.delete(u)));const S=await m;ee.has(u)||(ee.add(u),n.warn(`
3
3
  ${k.keylessMessage(S.record,{created:S.created})}
4
4
  `));const b=globalThis.process;if(b?.env)for(const[$,L]of Object.entries(S.env))L!==void 0&&!b.env[$]&&(b.env[$]=L);if(!e.clientSecret&&!S.env.PONTIVE_CLIENT_SECRET)throw new Error(`@pontive/server: ${k.KEYLESS_FILE} names ${S.record.instance_id}, but PONTIVE_CLIENT_SECRET is neither in ${k.ENV_FILE} nor in the environment. Put it back, or run \`npx pontive init --reset\`.`);const O=te({...e,issuer:e.issuer||S.env.PONTIVE_ISSUER,clientId:e.clientId||S.env.PONTIVE_CLIENT_ID,clientSecret:e.clientSecret||S.env.PONTIVE_CLIENT_SECRET,sessionSecret:e.sessionSecret||S.env.PONTIVE_SESSION_SECRET,fetch:je(e.fetch,S.record,n)});return pe(O,ae(O),()=>he(u,O.issuer))}function l(){return c?Promise.reject(c):(o??=i().catch(u=>{throw o=void 0,u instanceof k.KeylessInstanceGoneError&&(c=u),u}),o)}function d(u){return u instanceof k.KeylessUnavailableError?(a||(a=!0,n.warn(`[pontive] ${u.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(u){try{return await(await l()).handle(u)}catch(h){if(d(h))return x(503,"Pontive keyless mode can't run in this runtime; restart the dev server.");throw h}},async getSession(u){try{return await(await l()).getSession(u)}catch(h){if(d(h))return null;throw h}},async refresh(u){try{return await(await l()).refresh(u)}catch(h){if(d(h))return{session:null,setCookies:[],cookieHeader:u.headers.get("cookie")??""};throw h}},async providerProps(){return(await l()).providerProps()}}}function je(e,t,n){const o=e??((...a)=>fetch(...a));let c=!1;return async(a,i)=>{const l=await o(a,i);return l.status===401&&!c&&(typeof a=="string"?a:a instanceof URL?a.toString():a.url).startsWith(t.issuer)&&(c=!0,n.warn(`[pontive] ${k.goneMessage(t,"refused")}`)),l}}exports.PONTIVE_ENV=R.PONTIVE_ENV;exports.Pontive=R.Pontive;exports.PontiveAPIError=R.PontiveAPIError;exports.PontiveConnectionError=R.PontiveConnectionError;exports.ACCESS_COOKIE=oe;exports.CLAIM_ROUTE=le;exports.ORGANIZATION_ERROR_PARAM=ne;exports.PONTIVE_SERVER_VERSION=ce;exports.SESSION_HINT_COOKIE=se;exports.SWITCH_ORGANIZATION_ROUTE=V;exports.createServerAuth=ze;exports.switchOrganizationPath=ye;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { p as fe, w as we, k as me, i as ve } from "./client-BI4W1IJJ.js";
2
- import { h as yt, d as gt, e as Et, f as _t } from "./client-BI4W1IJJ.js";
1
+ import { p as fe, w as we, k as me, i as ve } from "./client-B3NStbMW.js";
2
+ import { h as yt, d as gt, e as Et, f as _t } from "./client-B3NStbMW.js";
3
3
  import { readKeylessRecord as Se, KeylessUnavailableError as te, claimLinkFor as ke, PontiveApiError as D, goneMessage as ne, ensureKeylessInstance as ye, loopbackCallbacks as ge, keylessMessage as Ee, KEYLESS_FILE as _e, ENV_FILE as Pe, KeylessInstanceGoneError as be } from "./keyless.js";
4
4
  import { v as Ie, s as re, u as Te, r as F, T as j, e as $, f as Re, p as Ue, g as Ce, h as Ae, i as Ne } from "./management-credential-CynS93TR.js";
5
5
  import { decodeJwt as $e, jwtDecrypt as Oe, EncryptJWT as Le } from "jose";
@@ -516,7 +516,7 @@ function at(e) {
516
516
  }
517
517
  };
518
518
  }
519
- const ct = "1.26.0", lt = "claim";
519
+ const ct = "1.27.0", lt = "claim";
520
520
  function vt(e = {}, t = {}) {
521
521
  const n = fe(), s = we(e, n);
522
522
  if (me(s, n)) return ut(s, t);
@@ -1567,7 +1567,6 @@ export declare class Billing {
1567
1567
  readonly rateCards: BillingRateCards;
1568
1568
  readonly refunds: BillingRefunds;
1569
1569
  readonly settings: BillingSettings;
1570
- readonly subjectStates: BillingSubjectStates;
1571
1570
  readonly tax: BillingTax;
1572
1571
  readonly timeMachines: BillingTimeMachines;
1573
1572
  readonly usage: BillingUsage;
@@ -1866,6 +1865,22 @@ export declare class BillingCustomers {
1866
1865
  * `GET /v1/billing/customers/{customer_id}` (GetCustomer)
1867
1866
  */
1868
1867
  get(customerId: string, options?: RequestOptions): APIPromise<T.Customer>;
1868
+ /**
1869
+ * billing.entitlement.v1.CustomerAccessService/GetCustomerAccess (32-billing-overview.md, API Surface,
1870
+ * Customer access; Data Model, Customer access; billing-svc docs/questions.md, P125). The Customer's
1871
+ * current access: its subject, the package it is on, every feature it resolves a value for by key ({
1872
+ * type, value } for a boolean or numeric feature, { type, allowance, per, limit, overage, exhausted }
1873
+ * for a metered one; billing-svc docs/questions.md, P107), seat_limit, suspended and suspension_cause,
1874
+ * with a version that increases on every change. A Customer with no access stored yet answers the
1875
+ * access computed now with version 0. A client that knows only a subject finds its Customer with GET
1876
+ * /v1/billing/customers?subject_type=&subject_id=; a subject with no Customer has no access, only the
1877
+ * defaults. Needs sys:billing:read on the root, and answers while billing is off (billing-svc
1878
+ * docs/questions.md, P41). An unknown Customer is customer_not_found. The RPC writes nothing, so
1879
+ * X-Idempotency-Key is not read.
1880
+ *
1881
+ * `GET /v1/billing/customers/{customer_id}/access` (GetCustomerAccess)
1882
+ */
1883
+ getAccess(customerId: string, options?: RequestOptions): APIPromise<T.CustomerAccess>;
1869
1884
  /**
1870
1885
  * billing.customer.v1.CustomerService/ListCustomers (32-billing-overview.md, API Surface).
1871
1886
  *
@@ -2855,29 +2870,6 @@ export declare class BillingSettings {
2855
2870
  */
2856
2871
  updateLimits(body?: T.UpdateBillingLimitsRequest, options?: RequestOptions): APIPromise<T.BillingSettings>;
2857
2872
  }
2858
- /**
2859
- * The `billing.subjectStates` operations.
2860
- */
2861
- export declare class BillingSubjectStates {
2862
- protected readonly core: Core;
2863
- /** @internal */
2864
- constructor(core: Core);
2865
- /**
2866
- * billing.entitlement.v1.SubjectStateService/GetSubjectState (32-billing-overview.md, API Surface,
2867
- * Subject states; Data Model, Subject state). The subject's current state: its package, every feature
2868
- * it resolves a value for by key ({ type, value } for a boolean or numeric feature, { type, allowance,
2869
- * per, limit, overage, exhausted } for a metered one; billing-svc docs/questions.md, P107),
2870
- * seat_limit, suspended and suspension_cause, with a version that increases on every change. A subject
2871
- * with no state yet answers the defaults with version 0: customer_id, package and seat_limit null, the
2872
- * values of default_features as features (a metered default not exhausted), suspended false. Needs
2873
- * sys:billing:read on the root, and answers while billing is off (billing-svc docs/questions.md, P41).
2874
- * An unknown subject_type is invalid_subject_type; a user or organization not in the instance is
2875
- * subject_not_found. The RPC writes nothing, so X-Idempotency-Key is not read.
2876
- *
2877
- * `GET /v1/billing/subject-state` (GetSubjectState)
2878
- */
2879
- get(params: T.GetSubjectStateParams, options?: RequestOptions): APIPromise<T.SubjectState>;
2880
- }
2881
2873
  /**
2882
2874
  * The `billing.tax` operations.
2883
2875
  */
@@ -3539,7 +3531,7 @@ export declare class MeBilling {
3539
3531
  * End-customer portal; billing-svc P124). Cancels the contract's pending change, a scheduled
3540
3532
  * downgrade, by deleting its edit: edit_id is the contract's pending_change.edit_id, and any other
3541
3533
  * edit is not_found. Only a change the end customer asked for, pending_change.initiated_by customer,
3542
- * may be cancelled here; one the client made is change_not_allowed. billing.contract.edit_cancelled is
3534
+ * may be cancelled here; one the client made is change_not_allowed. billing.contract.edit_canceled is
3543
3535
  * written as for DELETE /v1/billing/contracts/{contract_id}/edits/{edit_id}. An instance user's token
3544
3536
  * must be issued for the instance's me audience, https://{auth domain}/me/, with pontive:billing:pay
3545
3537
  * (D31, D48).
@@ -5249,9 +5241,10 @@ export declare class Webhooks {
5249
5241
  * Create webhook subscription.
5250
5242
  *
5251
5243
  * Register an endpoint for event delivery. The Standard Webhooks signing secret ("whsec_…") is
5252
- * returned ONLY in this response — store it now. Omit scope (or pass "project") for a client
5244
+ * returned ONLY in this response — store it now. Omit scope, or pass "instance", for a client
5253
5245
  * subscription; scope "organization" with organization_id creates an organization self-service
5254
- * subscription.
5246
+ * subscription, and scope "workspace" with workspace_id one of a workspace's webhooks in the Platform
5247
+ * Plane instance, which platform-management-api creates.
5255
5248
  *
5256
5249
  * `POST /v1/webhooks/subscriptions` (CreateWebhookSubscription)
5257
5250
  */
@@ -1567,7 +1567,6 @@ export declare class Billing {
1567
1567
  readonly rateCards: BillingRateCards;
1568
1568
  readonly refunds: BillingRefunds;
1569
1569
  readonly settings: BillingSettings;
1570
- readonly subjectStates: BillingSubjectStates;
1571
1570
  readonly tax: BillingTax;
1572
1571
  readonly timeMachines: BillingTimeMachines;
1573
1572
  readonly usage: BillingUsage;
@@ -1866,6 +1865,22 @@ export declare class BillingCustomers {
1866
1865
  * `GET /v1/billing/customers/{customer_id}` (GetCustomer)
1867
1866
  */
1868
1867
  get(customerId: string, options?: RequestOptions): APIPromise<T.Customer>;
1868
+ /**
1869
+ * billing.entitlement.v1.CustomerAccessService/GetCustomerAccess (32-billing-overview.md, API Surface,
1870
+ * Customer access; Data Model, Customer access; billing-svc docs/questions.md, P125). The Customer's
1871
+ * current access: its subject, the package it is on, every feature it resolves a value for by key ({
1872
+ * type, value } for a boolean or numeric feature, { type, allowance, per, limit, overage, exhausted }
1873
+ * for a metered one; billing-svc docs/questions.md, P107), seat_limit, suspended and suspension_cause,
1874
+ * with a version that increases on every change. A Customer with no access stored yet answers the
1875
+ * access computed now with version 0. A client that knows only a subject finds its Customer with GET
1876
+ * /v1/billing/customers?subject_type=&subject_id=; a subject with no Customer has no access, only the
1877
+ * defaults. Needs sys:billing:read on the root, and answers while billing is off (billing-svc
1878
+ * docs/questions.md, P41). An unknown Customer is customer_not_found. The RPC writes nothing, so
1879
+ * X-Idempotency-Key is not read.
1880
+ *
1881
+ * `GET /v1/billing/customers/{customer_id}/access` (GetCustomerAccess)
1882
+ */
1883
+ getAccess(customerId: string, options?: RequestOptions): APIPromise<T.CustomerAccess>;
1869
1884
  /**
1870
1885
  * billing.customer.v1.CustomerService/ListCustomers (32-billing-overview.md, API Surface).
1871
1886
  *
@@ -2855,29 +2870,6 @@ export declare class BillingSettings {
2855
2870
  */
2856
2871
  updateLimits(body?: T.UpdateBillingLimitsRequest, options?: RequestOptions): APIPromise<T.BillingSettings>;
2857
2872
  }
2858
- /**
2859
- * The `billing.subjectStates` operations.
2860
- */
2861
- export declare class BillingSubjectStates {
2862
- protected readonly core: Core;
2863
- /** @internal */
2864
- constructor(core: Core);
2865
- /**
2866
- * billing.entitlement.v1.SubjectStateService/GetSubjectState (32-billing-overview.md, API Surface,
2867
- * Subject states; Data Model, Subject state). The subject's current state: its package, every feature
2868
- * it resolves a value for by key ({ type, value } for a boolean or numeric feature, { type, allowance,
2869
- * per, limit, overage, exhausted } for a metered one; billing-svc docs/questions.md, P107),
2870
- * seat_limit, suspended and suspension_cause, with a version that increases on every change. A subject
2871
- * with no state yet answers the defaults with version 0: customer_id, package and seat_limit null, the
2872
- * values of default_features as features (a metered default not exhausted), suspended false. Needs
2873
- * sys:billing:read on the root, and answers while billing is off (billing-svc docs/questions.md, P41).
2874
- * An unknown subject_type is invalid_subject_type; a user or organization not in the instance is
2875
- * subject_not_found. The RPC writes nothing, so X-Idempotency-Key is not read.
2876
- *
2877
- * `GET /v1/billing/subject-state` (GetSubjectState)
2878
- */
2879
- get(params: T.GetSubjectStateParams, options?: RequestOptions): APIPromise<T.SubjectState>;
2880
- }
2881
2873
  /**
2882
2874
  * The `billing.tax` operations.
2883
2875
  */
@@ -3539,7 +3531,7 @@ export declare class MeBilling {
3539
3531
  * End-customer portal; billing-svc P124). Cancels the contract's pending change, a scheduled
3540
3532
  * downgrade, by deleting its edit: edit_id is the contract's pending_change.edit_id, and any other
3541
3533
  * edit is not_found. Only a change the end customer asked for, pending_change.initiated_by customer,
3542
- * may be cancelled here; one the client made is change_not_allowed. billing.contract.edit_cancelled is
3534
+ * may be cancelled here; one the client made is change_not_allowed. billing.contract.edit_canceled is
3543
3535
  * written as for DELETE /v1/billing/contracts/{contract_id}/edits/{edit_id}. An instance user's token
3544
3536
  * must be issued for the instance's me audience, https://{auth domain}/me/, with pontive:billing:pay
3545
3537
  * (D31, D48).
@@ -5249,9 +5241,10 @@ export declare class Webhooks {
5249
5241
  * Create webhook subscription.
5250
5242
  *
5251
5243
  * Register an endpoint for event delivery. The Standard Webhooks signing secret ("whsec_…") is
5252
- * returned ONLY in this response — store it now. Omit scope (or pass "project") for a client
5244
+ * returned ONLY in this response — store it now. Omit scope, or pass "instance", for a client
5253
5245
  * subscription; scope "organization" with organization_id creates an organization self-service
5254
- * subscription.
5246
+ * subscription, and scope "workspace" with workspace_id one of a workspace's webhooks in the Platform
5247
+ * Plane instance, which platform-management-api creates.
5255
5248
  *
5256
5249
  * `POST /v1/webhooks/subscriptions` (CreateWebhookSubscription)
5257
5250
  */
@@ -38,8 +38,8 @@ export interface AccessKeyWithSecret {
38
38
  updated_at?: string;
39
39
  }
40
40
  /**
41
- * AccessOutcomes decide what losing a contract or access leads to in the subject state. On a read both
42
- * are set; on an update only the fields given change.
41
+ * AccessOutcomes decide what losing a contract or access leads to in the Customer's access. On a read
42
+ * both are set; on an update only the fields given change.
43
43
  */
44
44
  export interface AccessOutcomes {
45
45
  /**
@@ -52,8 +52,8 @@ export interface AccessOutcomes {
52
52
  on_contract_ended: string;
53
53
  }
54
54
  /**
55
- * AccessOutcomes decide what losing a contract or access leads to in the subject state. On a read both
56
- * are set; on an update only the fields given change.
55
+ * AccessOutcomes decide what losing a contract or access leads to in the Customer's access. On a read
56
+ * both are set; on an update only the fields given change.
57
57
  */
58
58
  export interface AccessOutcomesInput {
59
59
  /**
@@ -1131,7 +1131,7 @@ export interface BillingScheduleInput {
1131
1131
  */
1132
1132
  export interface BillingSettings {
1133
1133
  /**
1134
- * What losing a contract or access leads to in the subject state.
1134
+ * What losing a contract or access leads to in the Customer's access.
1135
1135
  */
1136
1136
  access_outcomes: AccessOutcomes;
1137
1137
  default_collection: Collection;
@@ -3009,8 +3009,9 @@ export interface CreateSubscriptionRequest {
3009
3009
  headers?: Record<string, string>;
3010
3010
  metadata?: Record<string, string>;
3011
3011
  organization_id?: string;
3012
- scope?: "project" | "organization";
3012
+ scope?: "instance" | "organization" | "workspace";
3013
3013
  url: string;
3014
+ workspace_id?: string;
3014
3015
  }
3015
3016
  export interface CreateTimeMachineRequest {
3016
3017
  /**
@@ -3426,6 +3427,81 @@ export interface Customer {
3426
3427
  time_machine_id: string;
3427
3428
  updated_at: string;
3428
3429
  }
3430
+ /**
3431
+ * CustomerAccess is a Customer's access, part of the Customer: it has no id of its own.
3432
+ */
3433
+ export interface CustomerAccess {
3434
+ computed_at: string;
3435
+ /**
3436
+ * "cust_" plus 26 characters.
3437
+ */
3438
+ customer_id: string;
3439
+ /**
3440
+ * Every feature the subject resolves a value for, by key. A feature no source sets is absent: the
3441
+ * subject is not entitled to it.
3442
+ */
3443
+ features: Record<string, CustomerAccessFeature>;
3444
+ object: "customer_access";
3445
+ /**
3446
+ * The key of the package of the contract in force; unset with none.
3447
+ */
3448
+ package: string;
3449
+ /**
3450
+ * The seat cap; unset with none.
3451
+ */
3452
+ seat_limit: number;
3453
+ /**
3454
+ * The Customer's subject, since an enforcer works by subject.
3455
+ */
3456
+ subject: EntitlementSubject;
3457
+ suspended: boolean;
3458
+ /**
3459
+ * dunning, contract_ended, client_block or subject_deleted; unset when not suspended.
3460
+ */
3461
+ suspension_cause: string;
3462
+ /**
3463
+ * Increases on every change; 0 for a Customer with no access stored yet.
3464
+ */
3465
+ version: number;
3466
+ }
3467
+ /**
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.
3472
+ */
3473
+ export interface CustomerAccessFeature {
3474
+ /**
3475
+ * A decimal.
3476
+ */
3477
+ allowance?: string;
3478
+ /**
3479
+ * True when the usage period's usage has reached the allowance: under a hard limit the next use is
3480
+ * denied. Recomputed, with a new version, when usage crosses the allowance either way.
3481
+ */
3482
+ exhausted?: boolean;
3483
+ /**
3484
+ * hard or soft.
3485
+ */
3486
+ limit?: string;
3487
+ /**
3488
+ * bill or block.
3489
+ */
3490
+ overage?: string;
3491
+ /**
3492
+ * period: the allowance is per usage period.
3493
+ */
3494
+ per?: string;
3495
+ /**
3496
+ * boolean, numeric or metered.
3497
+ */
3498
+ type: string;
3499
+ /**
3500
+ * A boolean or numeric feature's value; null for no limit. A metered feature carries its fields
3501
+ * instead.
3502
+ */
3503
+ value?: boolean | string;
3504
+ }
3429
3505
  export interface CustomerList {
3430
3506
  data: Customer[];
3431
3507
  object: "list";
@@ -3852,7 +3928,7 @@ export interface Edge {
3852
3928
  */
3853
3929
  export interface Edit {
3854
3930
  applied_at: string;
3855
- cancelled_at: string;
3931
+ canceled_at: string;
3856
3932
  contract_id: string;
3857
3933
  created_at: string;
3858
3934
  deleted_at: string;
@@ -3870,7 +3946,7 @@ export interface Edit {
3870
3946
  operations: Array<OperationSetQuantity | OperationAddSubscription | OperationEndSubscription | OperationAddOverride | OperationEndOverride | OperationChangePackage | OperationEndTrial | OperationAddBlock | OperationLiftBlock | OperationSetFeature | OperationUnsetFeature | OperationChangeBillingFrequency>;
3871
3947
  reason: string;
3872
3948
  /**
3873
- * scheduled, applied, deleted, dropped or cancelled.
3949
+ * scheduled, applied, deleted, dropped or canceled.
3874
3950
  */
3875
3951
  status: string;
3876
3952
  }
@@ -4079,6 +4155,10 @@ export interface Event {
4079
4155
  organization_id?: string;
4080
4156
  source?: "system" | "custom" | "meta" | "test";
4081
4157
  type?: string;
4158
+ /**
4159
+ * WorkspaceID is set on a workspace-level event, in the Platform Plane instance.
4160
+ */
4161
+ workspace_id?: string;
4082
4162
  }
4083
4163
  export interface EventCursorList {
4084
4164
  data: BillingEvent[];
@@ -4124,7 +4204,7 @@ export interface EventType {
4124
4204
  object?: string;
4125
4205
  payload_schema?: string;
4126
4206
  schema_mode?: "strict" | "lenient";
4127
- scope?: "project" | "organization";
4207
+ scope?: "instance" | "organization" | "workspace";
4128
4208
  type?: "system" | "custom";
4129
4209
  updated_at?: string;
4130
4210
  }
@@ -10111,82 +10191,6 @@ export interface StaffAccess {
10111
10191
  reason?: string;
10112
10192
  session_id?: string;
10113
10193
  }
10114
- /**
10115
- * SubjectState is one subject's state.
10116
- */
10117
- export interface SubjectState {
10118
- computed_at: string;
10119
- /**
10120
- * "cust_" plus 26 characters; unset when the subject has no Customer.
10121
- */
10122
- customer_id: string;
10123
- /**
10124
- * Every feature the subject resolves a value for, by key. A feature no source sets is absent: the
10125
- * subject is not entitled to it.
10126
- */
10127
- features: Record<string, SubjectStateFeature>;
10128
- /**
10129
- * "inst_" plus 26 characters.
10130
- */
10131
- instance_id: string;
10132
- object: "subject_state";
10133
- /**
10134
- * The key of the package of the contract in force; unset with none.
10135
- */
10136
- package: string;
10137
- /**
10138
- * The seat cap; unset with none.
10139
- */
10140
- seat_limit: number;
10141
- subject: EntitlementSubject;
10142
- suspended: boolean;
10143
- /**
10144
- * dunning, contract_ended, client_block or subject_deleted; unset when not suspended.
10145
- */
10146
- suspension_cause: string;
10147
- /**
10148
- * Increases on every change; 0 for a subject with no state stored.
10149
- */
10150
- version: number;
10151
- }
10152
- /**
10153
- * SubjectStateFeature is one feature's value in a state, by its type. The gateway writes it as
10154
- * billing.subject_state.changed carries it: { type, value } for a boolean (true or false) or a numeric
10155
- * feature (a decimal string), and { type, allowance, per, limit, overage, exhausted } for a metered
10156
- * one, the metered fields inline.
10157
- */
10158
- export interface SubjectStateFeature {
10159
- /**
10160
- * A decimal.
10161
- */
10162
- allowance?: string;
10163
- /**
10164
- * True when the usage period's usage has reached the allowance: under a hard limit the next use is
10165
- * denied. Recomputed, with a new version, when usage crosses the allowance either way.
10166
- */
10167
- exhausted?: boolean;
10168
- /**
10169
- * hard or soft.
10170
- */
10171
- limit?: string;
10172
- /**
10173
- * bill or block.
10174
- */
10175
- overage?: string;
10176
- /**
10177
- * period: the allowance is per usage period.
10178
- */
10179
- per?: string;
10180
- /**
10181
- * boolean, numeric or metered.
10182
- */
10183
- type: string;
10184
- /**
10185
- * A boolean or numeric feature's value; null for no limit. A metered feature carries its fields
10186
- * instead.
10187
- */
10188
- value?: boolean | string;
10189
- }
10190
10194
  export interface Subscription {
10191
10195
  allow_private_ips?: boolean;
10192
10196
  created_at?: string;
@@ -10199,7 +10203,7 @@ export interface Subscription {
10199
10203
  metadata?: Record<string, string>;
10200
10204
  object?: string;
10201
10205
  organization_id?: string;
10202
- scope?: "project" | "organization";
10206
+ scope?: "instance" | "organization" | "workspace";
10203
10207
  /**
10204
10208
  * Secret is the plaintext Standard Webhooks signing secret ("whsec_…"). Present only in
10205
10209
  * create/rotate-secret responses; never readable again.
@@ -10210,6 +10214,11 @@ export interface Subscription {
10210
10214
  status?: "active" | "paused" | "failing" | "disabled";
10211
10215
  updated_at?: string;
10212
10216
  url?: string;
10217
+ /**
10218
+ * WorkspaceID is the workspace a workspace-scope subscription is bound to, in the Platform Plane
10219
+ * instance (pontive-spec 11, Webhook levels).
10220
+ */
10221
+ workspace_id?: string;
10213
10222
  }
10214
10223
  /**
10215
10224
  * SubscriptionInput is a subscription as a client sends it, at creation or in add_subscription.
@@ -13043,19 +13052,6 @@ export interface UpdateBillingSettingsParams {
13043
13052
  */
13044
13053
  if_match?: string;
13045
13054
  }
13046
- /**
13047
- * The parameters of `GetSubjectState`.
13048
- */
13049
- export interface GetSubjectStateParams {
13050
- /**
13051
- * user, organization or external
13052
- */
13053
- subject_type: string;
13054
- /**
13055
- * A user's or organization's id, or the client's own external id
13056
- */
13057
- subject_id: string;
13058
- }
13059
13055
  /**
13060
13056
  * The parameters of `ListTimeMachines`.
13061
13057
  */
@@ -14754,7 +14750,7 @@ export interface ListWebhookEventTypesParams {
14754
14750
  */
14755
14751
  type?: string;
14756
14752
  /**
14757
- * Filter by scope (project|organization)
14753
+ * Filter by scope (instance|organization|workspace)
14758
14754
  */
14759
14755
  scope?: string;
14760
14756
  /**
@@ -14782,6 +14778,10 @@ export interface ListWebhookEventsParams {
14782
14778
  * Filter by organization (org_…)
14783
14779
  */
14784
14780
  organization_id?: string;
14781
+ /**
14782
+ * Filter by workspace (ws_…): a workspace-level event, in the Platform Plane instance
14783
+ */
14784
+ workspace_id?: string;
14785
14785
  /**
14786
14786
  * RFC 3339: created at or after
14787
14787
  */
@@ -14808,7 +14808,7 @@ export interface ListWebhookEventsParams {
14808
14808
  */
14809
14809
  export interface ListWebhookSubscriptionsParams {
14810
14810
  /**
14811
- * Filter by scope (project|organization)
14811
+ * Filter by scope (instance|organization|workspace)
14812
14812
  */
14813
14813
  scope?: string;
14814
14814
  /**
@@ -14819,6 +14819,10 @@ export interface ListWebhookSubscriptionsParams {
14819
14819
  * Filter organization-scope subscriptions by organization (org_…)
14820
14820
  */
14821
14821
  organization_id?: string;
14822
+ /**
14823
+ * Filter workspace-scope subscriptions by workspace (ws_…)
14824
+ */
14825
+ workspace_id?: string;
14822
14826
  /**
14823
14827
  * Sort field; prefix with - for descending. Allowed: created_at, updated_at, status, url. Default:
14824
14828
  * -created_at