@zuplo/runtime 5.1683.0 → 5.1685.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/index.minified.js +1 -1
- package/package.json +1 -1
package/index.minified.js
CHANGED
|
@@ -68,5 +68,5 @@ Signature verification is impossible without access to the original signed mater
|
|
|
68
68
|
`+d}):new oe(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
69
69
|
If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
|
|
70
70
|
`+l+`
|
|
71
|
-
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new oe(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Dc,"validateComputedSignature");function Hc(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(Hc,"parseHeader");function Uc(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s(Uc,"secureCompare");async function Nc(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=kr[i[u]];return a.join("")}s(Nc,"computeHMACSignatureAsync");var kr=new Array(256);for(let t=0;t<kr.length;t++)kr[t]=t.toString(16).padStart(2,"0");function M(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new f(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(M,"optionValidator");var tn=s(async(t,e,n,r)=>{M(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await Fi(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),w.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookInboundPolicy");var nn=class extends ie{static{s(this,"MeteringPlugin")}};var Mc=["customer.subscription.created","customer.subscription.deleted","customer.subscription.paused","customer.subscription.resumed","customer.subscription.updated"],Dr=class extends nn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.testMode)return"success";let{bucketId:d}=this.options;if(!d)throw new f("StripeMeteringPlugin - No bucketName property provided");let{authApiJWT:p,meteringServiceUrl:R}=h.instance,m=await c.json();try{Zc(m)}catch{return w.badRequest(c,l,{detail:"The received body was not in the expected format."})}if(!Mc.includes(m.type))return w.ok(c,l,{detail:"Event was ignored by Stripe metering plugin webhook."});let y=m.data?.object?.id;if(!y)return w.badRequest(c,l,{detail:"Invalid Stripe Webhook event. Expected '.data.object.id' to be the subscription ID."});let E=m.data?.object?.items?.data.find(k=>k.object==="subscription_item");if(!E||!E.id)return w.badRequest(c,l,{detail:"Invalid Stripe Webhook event. Expected '.data.object.items.data[]' to contain a subscription_item."});let P=E.plan;if(!P||!P.product)return w.badRequest(c,l,{detail:"Invalid Stripe Webhook event. Expected '.data.object.items.data[].plan'."});let x={status:"active",type:"periodic",renewalStrategy:"monthly",customerKey:"luis-tester",productKey:"routes.oas.json",planProviderKey:P.product,subscriptionProviderKey:y,region:this.options.bucketRegion??"us-central1"},T=await fetch(`${R}/internal/v1/metering/${d}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify(x)});if(T.status!==200){let k="Unknown error creating subscription",A;try{A=await T.json(),k=A.detail??A.title??k}catch{}return l.log.error(k,A),w.internalServerError(c,l,{detail:k})}return w.ok(c,l)},"stripeWebhookHandler"),i=Jo({inboundPolicies:[{handler:tn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new H({processors:[$,i],handler:o,gateway:r}),u=new D({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__zuplo/stripe-webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Zc(t){if(!(t!==null&&typeof t=="object"&&"id"in t&&K(t.id)&&"type"in t&&K(t.type)))throw new Error("Object is not a stripe webhook event")}s(Zc,"assertsStripeWebhookEvent");var ji=new WeakMap,$i={},rn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){ji.set(e,n)}};async function zi(t,e,n,r){if(!n.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:zo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=ji.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new I(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=we(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},R=$i[n.apiKey];if(!R){let m=n.apiKey,y=t.headers.get("zm-test-id")??"";R=new C("amberflo-ingest-meter",10,async E=>{try{let P=n.url??"https://app.amberflo.io/ingest",x=await fetch(P,{method:"POST",body:JSON.stringify(E),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":y}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(P){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${P.message}`),P}}),$i[m]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(zi,"AmberfloMeteringInboundPolicy");async function on(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(on,"sha256");var Bi=new Map;async function Z(t,e){let n,r=Bi.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await on(JSON.stringify({policyName:t,options:e}))}`,Bi.set(t,n)),n}s(Z,"getPolicyCacheName");var Gi="key-metadata-cache-type";function qc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(qc,"getKeyValue");async function sn(t,e,n,r){if(!n.bucketName)if(it.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=it.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(P=>o.allowUnauthenticatedRequests?t:w.unauthorized(t,e,{detail:P}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=qc(a,o);if(!u||u==="")return i("No key present");let c=await Fc(u),l=await Z(r,o),d=new N(l,{logger:S.getLogger(e)}),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Gi&&S.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let R={key:u},m=await Ae({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":h.instance.deploymentName??"unknown","User-Agent":h.instance.systemUserAgent},body:JSON.stringify(R)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let P=await m.text(),x=JSON.parse(P);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new I(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let y=await m.json(),E={isValid:!0,typeId:Gi,user:{sub:y.name,data:y.metadata}};return t.user=E.user,d.put(c,E,o.cacheTtlSeconds),t}s(sn,"ApiKeyInboundPolicy");async function Fc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Fc,"hashValue");var Vi=sn;var at=require("jose");var Hr={},$c=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");Hr[e.jwkUrl]||(Hr[e.jwkUrl]=(0,at.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,at.jwtVerify)(t,Hr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),jc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,at.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),q=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>w.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?$c:jc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(m){let y=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Wi=s(async(t,e,n,r)=>q(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Ji=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>w.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let R=d.substring(0,p),m=d.substring(p+1),y=n.accounts.find(E=>E.username===R&&E.password===m);return y||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var zc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Bc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Bc,"digestMessage");var Gc=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Bc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Ki(t,e,n,r){let o=await Z(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Gc(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let R=n?.expirationSecondsTtl??60,m=new Response(p.body,p);zc.forEach(y=>m.headers.delete(y)),m.headers.set("cache-control",`s-maxage=${R}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Ki,"CachingInboundPolicy");var Yi=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new L(t,{method:n.method})},"ChangeMethodInboundPolicy");var Qi=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new L(t,{headers:o})},"ClearHeadersInboundPolicy");var Xi=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var es=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",q(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ts=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return q(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var ns=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=G.instance,i=Ye(n.policies,o?.routeData.policies);return Xn(i)(t,e)},"CompositeInboundPolicy");var rs=s(async(t,e,n)=>{let r=t.user;if(!r)return w.unauthorized(t,e,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:o}=r;if(!n.bucketId)return w.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await Vc(i,o,e);if(!a)return w.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return w.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return w.forbidden(t,e,{title:"Insufficient credits"});return e.custom.subscription=a,e.addResponseSendingFinalHook(async()=>{let u=e.custom.meters,c={};for(let l of Object.keys(u))c[l]=u[l];await Wc(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function Vc(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=h.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerRef:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let u=await a.json();if(u.data.length!==0)return u.data.length>1&&n.log.warn(`Found more than one active subscription for customer ${e} -- using the first one.`),u.data[0]}s(Vc,"getSubscription");async function Wc(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=h.instance,a=new URL(`${i}/internal/v1/metering/${t}/subscriptions/${e}/quotas/consume`),u=await fetch(a,{method:"POST",body:JSON.stringify({meters:n}),headers:{Authorization:`Bearer ${o}`}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(Wc,"consumeSubscription");var os=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return w.unauthorized(t,e,{detail:"No authorization header"});let i=Jc(o);if(!i)return w.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await Z(r,n),u=new N(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),w.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):w.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function Jc(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(Jc,"getToken");var is=s(async(t,e,n,r)=>(M(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),q(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var ss=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new L(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ne="__unknown__",as=s(async(t,e,n,r)=>{let o={allow:{countries:Ze(n.allow?.countries,"allow.countries",r),regionCodes:Ze(n.allow?.regionCodes,"allow.regionCode",r),asns:Ze(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ze(n.block?.countries,"block.countries",r),regionCodes:Ze(n.block?.regionCodes,"block.regionCode",r),asns:Ze(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Ne,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ne,u=e.incomingRequestProperties.asn?.toString()??Ne,c=o.ignoreUnknown&&i===Ne,l=o.ignoreUnknown&&a===Ne,d=o.ignoreUnknown&&u===Ne,p=o.allow.countries,R=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return Me(t,e,r,i,a,u);let y=o.block.countries,E=o.block.regionCodes,P=o.block.asns;return y.length>0&&y.includes(i)&&!c||E.length>0&&E.includes(a)&&!l||P.length>0&&P.includes(u)&&!d?Me(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function Me(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),w.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(Me,"blockedResponse");function Ze(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ze,"toLowerStringArray");var us=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var ls=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Ur(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Ur(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return cs(a[u])}else return a.length>0?cs(a[0]):Ur(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function cs(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(cs,"generateResponse");var Ur=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return w.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Kc="Incoming",Yc={logRequestBody:!0,logResponseBody:!0};function ds(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ds,"headersToObject");function ps(){return new Date().toISOString()}s(ps,"timestamp");var Nr=new WeakMap,Qc={};function fs(t,e){let n=Nr.get(t);n||(n=Qc);let r=Object.assign({...n},e);Nr.set(t,r)}s(fs,"setMoesifContext");async function ms(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(ms,"readBody");var Xc={},Mr;function gs(){if(!Mr)throw new I("Invalid State - no _lastLogger");return Mr}s(gs,"getLastLogger");function el(t){let e=Xc[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);gs().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||gs().error({status:o.status,body:await o.text()})})),e}s(el,"getDispatcher");async function hs(t,e,n,r){Mr=e.log;let o=ps(),i=Object.assign(Yc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await ms(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=el(i.applicationId),d=t.headers.get("true-client-ip"),p=Nr.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ds(t.headers)},m=i.logResponseBody?await ms(u,e):void 0,y={time:ps(),status:u.status,headers:ds(u.headers),body:m},E={request:R,response:y,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Kc};l.enqueue(E),e.waitUntil(l.waitUntilFlushed())}),t}s(hs,"MoesifInboundPolicy");var ys=s(async(t,e,n,r)=>q(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var bs=require("jose");var Zr,Rs=s(async(t,e,n,r)=>{if(!Zr)try{Zr=await(0,bs.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return q(t,e,{issuer:n.authUrl,secret:Zr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ps=xe(be());var an=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},qr=class extends an{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fr=class extends an{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function tl(t,e){if($o(t))throw new qr(e)}s(tl,"throwIfUndefinedOrNull");function ut(t,e){if(tl(t,e),!K(t))throw new Fr(e,"string")}s(ut,"throwIfNotString");var un=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return ut(e,"redisClientUrl"),ut(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){ut(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new _("Redis client failed with 401: Unauthorized"):new _(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},cn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(ut(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new _("The in-memory redis client only supports /rate-limit calls")}};var ln=(0,Ps.debug)("zuplo:policies:RateLimitInboundPolicy"),nl="strict",rl=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),ol=s(async t=>({key:`ip-${rl(t)}`}),"getIP"),il=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),sl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),dn;function al(t,e){let n;if(dn)return dn;if(h.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new cn,dn=n,n;let{authApiJWT:r,redisURL:o}=h.instance;if(!K(o))throw new _(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!K(r))throw new _(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=un.initialize(o,r,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!n||!n.isEnabled())throw new _(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return dn=n,n}s(al,"getRedisClient");async function ws(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(ws,"getCountAndUpdateExpiry");function ul(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new I(c)}return u},"outerFunction")}s(ul,"wrapUserFunction");var cl="Retry-After",$r=s(async(t,e,n,r)=>{let o=Date.now(),i=S.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new _(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[cl]=l.toString()),w.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:ul(n,r),user:il,ip:ol,all:sl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,y=n.headerMode??"retry-after",E=al(r,i),x=`bucket/${h.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??nl)==="async"){let A=await Z(r,n),j=new ue(A,{logger:S.getLogger(e)}),W=ws(x,m,E,i,e.requestId),J=await j.get(x);if(J!==void 0&&J<=Date.now()){ln(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let Ee=Math.round((J-Date.now())/1e3);return u(y,Ee)}return e.addEventListener("responseSending",Ee=>{try{let Ie=Ee,Rn=Ie.mutableResponse;Ie.mutableResponse=(async()=>{let ct=await W;if(ct.count>R){let na=Date.now()+ct.ttlSeconds*1e3;return j.put(x,na,ct.ttlSeconds).catch(Yr=>{throw i.error(Yr),Yr}),ln(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(y,ct.ttlSeconds)}return Rn})()}catch(Ie){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Ie)}}),t}let k=await ws(x,m,E,i,e.requestId);return k.count>R?(ln(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(y,k.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;ln(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var jr;function Es(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(Es,"headersToNameValuePairs");function ll(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(ll,"queryToNameValueParis");function dl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(dl,"parseIntOrUndefined");var Is={};async function xs(t,e,n,r){let o=new Date,i=Date.now();return jr||(jr={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?we(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?we(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:h.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:jr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Es(t.headers),queryString:ll(t.query)},response:{status:a.status,statusText:a.statusText,headers:Es(a.headers),content:{size:dl(t.headers.get("content-length"))}}}]}}},d=Is[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async R=>{try{let m=n.url??"https://metrics.readme.io/request",y=await fetch(m,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${y.status}: '${await y.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),Is[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(xs,"ReadmeMetricsInboundPolicy");var vs=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new L(t,{headers:i})},"RemoveHeadersInboundPolicy");var Os=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var Ts=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new L(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var Ss=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Cs=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),As=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Cs():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Cs():t},"RequestSizeLimitInboundPolicy");function Ls(t,e,n){return`_${he(t+"_"+e+"_"+n)}`}s(Ls,"getRawOperationDataIdentifierName");function pn(t,e,n,r){return`_${he(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(pn,"getIdForParameterSchema");function mn(t,e,n){return`_${he(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${he(n.toLowerCase())}`}s(mn,"getIdForRequestBodySchema");function _s(t,e){return`_${he(t)}__${he(e)}`}s(_s,"getIdForRefSchema");function he(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(he,"sanitizedIdentifierName");var qe=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Fe=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=pn(n,r,o,c.name),d=G.instance.schemaValidator[l],p=d(e[c.name]),R=zr(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Q=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),X=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ee=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),zr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function ks(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,E=w.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${m}`});if(X(n.validateBody)&&Q(t,n.logLevel??"info",y,[r],m),ee(n.validateBody))return E}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=w.badRequest(e,t,{detail:m});return X(n.validateBody)&&Q(t,n.logLevel??"info",m,[r],[m]),ee(n.validateBody)?y:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=mn(t.route.path,e.method,o),u=G.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=w.badRequest(e,t,{detail:m});return X(n.validateBody)&&Q(t,n.logLevel??"info",m,[r],[m]),ee(n.validateBody)?y:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=zr(l),R=w.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(X(n.validateBody)&&Q(t,n.logLevel??"info",d,[r],p),ee(n.validateBody))return R}s(ks,"handleBodyValidation");function Ds(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=qe(t),i=Fe(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=w.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(X(n.validateHeaders)&&Q(t,n.logLevel??"info",a,i.invalidValues,i.errors),ee(n.validateHeaders))return u}}s(Ds,"handleHeadersValidation");function Hs(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=qe(t),o=Fe(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=w.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(X(n.validatePathParameters)&&Q(t,n.logLevel??"info",i,o.invalidValues,o.errors),ee(n.validatePathParameters))return a}}s(Hs,"handlePathParameterValidation");function Us(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=qe(t),o=Fe(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=w.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(X(n.validateQueryParameters)&&Q(t,n.logLevel??"info",i,o.invalidValues,o.errors),ee(n.validateQueryParameters))return a}}s(Us,"handleQueryParameterValidation");var Br=s(async(t,e,n)=>{let r=Us(e,t,n);if(r!==void 0||(r=Hs(e,t,n),r!==void 0)||(r=Ds(e,t,n),r!==void 0))return r;let o=await ks(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ns=Br;var Ms=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return w.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Zs=s(async(t,e,n)=>new L(t,{body:n.body}),"SetBodyInboundPolicy");var qs=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new L(t,{headers:i})},"SetHeadersInboundPolicy");var Fs=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var $s=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new L(i.toString(),t)},"SetQueryParamsInboundPolicy");var js=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var pl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),zs=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await pl(n.sleepInMs),t},"SleepInboundPolicy");var Bs=s(async(t,e,n,r)=>{M(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await q(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof L))throw new _("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new I(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?w.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Gs=s(async(t,e,n,r)=>{M(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await Z(r,n),i=new N(o,{logger:S.getLogger(e)}),a=await i.get(r);if(!a){let u=await ml(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function ml(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Ae({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new I("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new I("Response returned from Azure AD is not in the expected format.")}s(ml,"getAccessToken");var Vs="https://accounts.google.com/o/oauth2/token",Gr,Ws=s(async(t,e,n,r)=>{M(n,r).required("serviceAccountJson","string"),Gr||(Gr=await B.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await Z(r,n),a=new N(i,{logger:S.getLogger(e)}),u=await a.get(r);if(!u){let c=await ne({serviceAccount:Gr,audience:Vs,payload:o}),l=await _t(Vs,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new I("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var gl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",fl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Vr,Js=s(async(t,e,n,r)=>{if(M(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(fl.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Vr||(Vr=await B.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new I("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new I(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=we(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new I(`Unable to determine user from for the policy ${r}`);let a=await Z(r,n),u=new N(a,{logger:S.getLogger(e)}),c={uid:i,claims:o},l=await on(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ne({serviceAccount:Vr,audience:gl,payload:c}),R=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await si(R,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new I("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Wr,Ks=s(async(t,e,n,r)=>{M(n,r).required("audience","string").required("serviceAccountJson","string"),Wr||(Wr=await B.init(n.serviceAccountJson));let o=await ne({serviceAccount:Wr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Ys="https://www.googleapis.com/oauth2/v4/token",Jr,Qs=s(async(t,e,n,r)=>{M(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Jr||(Jr=await B.init(n.serviceAccountJson));let o=await Z(r,n),i;n.useMemoryCacheOnly?i=new ve(o):i=new N(o,e);let a=await i.get(r);if(!a){let u=await ne({serviceAccount:Jr,audience:Ys,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await _t(Ys,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new I("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Xs=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return w.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new _("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return w.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ea=s(async(t,e,n,r)=>{let o=S.getLogger(e);e.addResponseSendingFinalHook(async(d,p,R)=>{let m=ae.get(R,"subscription");if((n.allowRequestsWithoutSubscription??!1)&&!m)return;let E=n.bucketId;if(!E){R.log.error(`MeteringInboundPolicy '${r}' - no bucketName property provided`);return}let{authApiJWT:P,meteringServiceUrl:x}=h.instance;d.ok&&m&&n.meters&&fetch(`${x}/internal/v1/metering/${E}/subscriptions/${m.id}/quotas/consume`,{headers:{Authorization:`Bearer ${P}`},method:"POST",body:JSON.stringify({meters:n.meters})}).catch(T=>{R.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`,T)})});let i=ae.get(e,"subscription"),a=n.allowRequestsWithoutSubscription??!1,u=n.allowRequestsOverQuota??!1;if(!i){if(a)return t;throw new f("Subscription is not available for user")}if(i&&Object.keys(i.quotas).length===0)return w.forbidden(t,e,{detail:`Quota is not set up for subscription '${e.custom.subscription.id}'`});let l=Object.keys(n.meters).filter(d=>!Object.keys(i.quotas).includes(d));if(l.length>0)throw new f(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(i.quotas))if(i.quotas[d]<=0&&!u)return w.forbidden(t,e,{detail:`Quota exceeded for meter '${d}'`});return t},"MeteringInboundPolicy");var ta=s(async(t,e,n,r)=>{let o=S.getLogger(e),i=n.allowRequestsWithoutSubscription??!1,a=t.user;if(!a)return i?t:w.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});let u=n.bucketId;if(!u)throw new f(`LoadSubscriptionInboundPolicy '${r}' - no bucketName property provided`);let{authApiJWT:c,meteringServiceUrl:l}=h.instance,{sub:d}=a,p,R;try{if(p=await fetch(`${l}/internal/v1/metering/${u}/subscriptions?customerRef=${d}&status=active`,{headers:{Authorization:`Bearer ${c}`},method:"GET"}),!p.ok)return e.log.error(await p.text()),w.forbidden(t,e);R=await p.json()}catch(y){o.error(`LoadSubscriptionInboundPolicy '${r}' -error in serviceResponse`,y)}if((!R||!R.data||R.data.length===0)&&!i)return w.unauthorized(t,e,{detail:"No valid, active subscription found"});if((!R||!R.data||R.data.length===0)&&i)return t;let m=R&&R.data?R.data[0]:void 0;return ae.set(e,"subscription",m),t},"LoadSubscriptionInboundPolicy");var gn=class t{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,n){if(this.services.get(e))throw new _(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Kr=["sha-1","sha-256","sha-384","sha-512"],fn=class{static{s(this,"BaseCryptoBeta")}};var hn=class extends fn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Kr.includes(e.toLowerCase()))throw new I(`Algorithm ${e} is not supported. Try using ${Kr.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var yn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var bn=class extends yn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new lt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new f("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
|
|
71
|
+
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new oe(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Dc,"validateComputedSignature");function Hc(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(Hc,"parseHeader");function Uc(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s(Uc,"secureCompare");async function Nc(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=kr[i[u]];return a.join("")}s(Nc,"computeHMACSignatureAsync");var kr=new Array(256);for(let t=0;t<kr.length;t++)kr[t]=t.toString(16).padStart(2,"0");function M(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new f(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(M,"optionValidator");var tn=s(async(t,e,n,r)=>{M(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await Fi(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),w.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookInboundPolicy");var nn=class extends ie{static{s(this,"MeteringPlugin")}};var Mc=["customer.subscription.created","customer.subscription.deleted","customer.subscription.paused","customer.subscription.resumed","customer.subscription.updated"],Dr=class extends nn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.testMode)return"success";let{bucketId:d}=this.options;if(!d)throw new f("StripeMeteringPlugin - No bucketName property provided");let{authApiJWT:p,meteringServiceUrl:R}=h.instance,m=await c.json();try{Zc(m)}catch{return w.badRequest(c,l,{detail:"The received body was not in the expected format."})}if(!Mc.includes(m.type))return w.ok(c,l,{detail:"Event was ignored by Stripe metering plugin webhook."});let y=m.data?.object?.id;if(!y)return w.badRequest(c,l,{detail:"Invalid Stripe Webhook event. Expected '.data.object.id' to be the subscription ID."});let E=m.data?.object?.items?.data.find(k=>k.object==="subscription_item");if(!E||!E.id)return w.badRequest(c,l,{detail:"Invalid Stripe Webhook event. Expected '.data.object.items.data[]' to contain a subscription_item."});let P=E.plan;if(!P||!P.product)return w.badRequest(c,l,{detail:"Invalid Stripe Webhook event. Expected '.data.object.items.data[].plan'."});let x={status:"active",type:"periodic",renewalStrategy:"monthly",customerKey:"luis-tester",productKey:"routes.oas.json",planProviderKey:P.product,subscriptionProviderKey:y,region:this.options.bucketRegion??"us-central1"},T=await fetch(`${R}/internal/v1/metering/${d}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify(x)});if(T.status!==200){let k="Unknown error creating subscription",A;try{A=await T.json(),k=A.detail??A.title??k}catch{}return l.log.error(k,A),w.internalServerError(c,l,{detail:k})}return w.ok(c,l)},"stripeWebhookHandler"),i=Jo({inboundPolicies:[{handler:tn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new H({processors:[$,i],handler:o,gateway:r}),u=new D({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__zuplo/stripe-webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Zc(t){if(!(t!==null&&typeof t=="object"&&"id"in t&&K(t.id)&&"type"in t&&K(t.type)))throw new Error("Object is not a stripe webhook event")}s(Zc,"assertsStripeWebhookEvent");var ji=new WeakMap,$i={},rn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){ji.set(e,n)}};async function zi(t,e,n,r){if(!n.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:zo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=ji.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new I(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=we(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},R=$i[n.apiKey];if(!R){let m=n.apiKey,y=t.headers.get("zm-test-id")??"";R=new C("amberflo-ingest-meter",10,async E=>{try{let P=n.url??"https://app.amberflo.io/ingest",x=await fetch(P,{method:"POST",body:JSON.stringify(E),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":y}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(P){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${P.message}`),P}}),$i[m]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(zi,"AmberfloMeteringInboundPolicy");async function on(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(on,"sha256");var Bi=new Map;async function Z(t,e){let n,r=Bi.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await on(JSON.stringify({policyName:t,options:e}))}`,Bi.set(t,n)),n}s(Z,"getPolicyCacheName");var Gi="key-metadata-cache-type";function qc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(qc,"getKeyValue");async function sn(t,e,n,r){if(!n.bucketName)if(it.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=it.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(P=>o.allowUnauthenticatedRequests?t:w.unauthorized(t,e,{detail:P}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=qc(a,o);if(!u||u==="")return i("No key present");let c=await Fc(u),l=await Z(r,o),d=new N(l,{logger:S.getLogger(e)}),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Gi&&S.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let R={key:u},m=await Ae({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":h.instance.deploymentName??"unknown","User-Agent":h.instance.systemUserAgent},body:JSON.stringify(R)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let P=await m.text(),x=JSON.parse(P);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new I(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let y=await m.json(),E={isValid:!0,typeId:Gi,user:{sub:y.name,data:y.metadata}};return t.user=E.user,d.put(c,E,o.cacheTtlSeconds),t}s(sn,"ApiKeyInboundPolicy");async function Fc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Fc,"hashValue");var Vi=sn;var at=require("jose");var Hr={},$c=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");Hr[e.jwkUrl]||(Hr[e.jwkUrl]=(0,at.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,at.jwtVerify)(t,Hr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),jc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,at.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),q=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>w.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?$c:jc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(m){let y=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Wi=s(async(t,e,n,r)=>q(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Ji=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>w.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let R=d.substring(0,p),m=d.substring(p+1),y=n.accounts.find(E=>E.username===R&&E.password===m);return y||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var zc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Bc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Bc,"digestMessage");var Gc=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Bc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Ki(t,e,n,r){let o=await Z(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Gc(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let R=n?.expirationSecondsTtl??60,m=new Response(p.body,p);zc.forEach(y=>m.headers.delete(y)),m.headers.set("cache-control",`s-maxage=${R}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Ki,"CachingInboundPolicy");var Yi=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new L(t,{method:n.method})},"ChangeMethodInboundPolicy");var Qi=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new L(t,{headers:o})},"ClearHeadersInboundPolicy");var Xi=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var es=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",q(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ts=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return q(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var ns=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=G.instance,i=Ye(n.policies,o?.routeData.policies);return Xn(i)(t,e)},"CompositeInboundPolicy");var rs=s(async(t,e,n)=>{let r=t.user;if(!r)return w.unauthorized(t,e,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:o}=r;if(!n.bucketId)return w.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await Vc(i,o,e);if(!a)return w.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return w.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return w.forbidden(t,e,{title:"Insufficient credits"});return e.custom.subscription=a,e.addResponseSendingFinalHook(async()=>{let u=e.custom.meters,c={};for(let l of Object.keys(u))c[l]=u[l];await Wc(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function Vc(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=h.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerRef:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let u=await a.json();if(u.data.length!==0)return u.data.length>1&&n.log.warn(`Found more than one active subscription for customer ${e} -- using the first one.`),u.data[0]}s(Vc,"getSubscription");async function Wc(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=h.instance,a=new URL(`${i}/internal/v1/metering/${t}/subscriptions/${e}/quotas/consume`),u=await fetch(a,{method:"POST",body:JSON.stringify({meters:n}),headers:{Authorization:`Bearer ${o}`}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(Wc,"consumeSubscription");var os=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return w.unauthorized(t,e,{detail:"No authorization header"});let i=Jc(o);if(!i)return w.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await Z(r,n),u=new N(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),w.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):w.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function Jc(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(Jc,"getToken");var is=s(async(t,e,n,r)=>(M(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),q(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var ss=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new L(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ne="__unknown__",as=s(async(t,e,n,r)=>{let o={allow:{countries:Ze(n.allow?.countries,"allow.countries",r),regionCodes:Ze(n.allow?.regionCodes,"allow.regionCode",r),asns:Ze(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ze(n.block?.countries,"block.countries",r),regionCodes:Ze(n.block?.regionCodes,"block.regionCode",r),asns:Ze(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Ne,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ne,u=e.incomingRequestProperties.asn?.toString()??Ne,c=o.ignoreUnknown&&i===Ne,l=o.ignoreUnknown&&a===Ne,d=o.ignoreUnknown&&u===Ne,p=o.allow.countries,R=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return Me(t,e,r,i,a,u);let y=o.block.countries,E=o.block.regionCodes,P=o.block.asns;return y.length>0&&y.includes(i)&&!c||E.length>0&&E.includes(a)&&!l||P.length>0&&P.includes(u)&&!d?Me(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function Me(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),w.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(Me,"blockedResponse");function Ze(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ze,"toLowerStringArray");var us=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var ls=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Ur(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Ur(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return cs(a[u])}else return a.length>0?cs(a[0]):Ur(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function cs(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(cs,"generateResponse");var Ur=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return w.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Kc="Incoming",Yc={logRequestBody:!0,logResponseBody:!0};function ds(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ds,"headersToObject");function ps(){return new Date().toISOString()}s(ps,"timestamp");var Nr=new WeakMap,Qc={};function fs(t,e){let n=Nr.get(t);n||(n=Qc);let r=Object.assign({...n},e);Nr.set(t,r)}s(fs,"setMoesifContext");async function ms(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(ms,"readBody");var Xc={},Mr;function gs(){if(!Mr)throw new I("Invalid State - no _lastLogger");return Mr}s(gs,"getLastLogger");function el(t){let e=Xc[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);gs().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||gs().error({status:o.status,body:await o.text()})})),e}s(el,"getDispatcher");async function hs(t,e,n,r){Mr=e.log;let o=ps(),i=Object.assign(Yc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await ms(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=el(i.applicationId),d=t.headers.get("true-client-ip"),p=Nr.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ds(t.headers)},m=i.logResponseBody?await ms(u,e):void 0,y={time:ps(),status:u.status,headers:ds(u.headers),body:m},E={request:R,response:y,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Kc};l.enqueue(E),e.waitUntil(l.waitUntilFlushed())}),t}s(hs,"MoesifInboundPolicy");var ys=s(async(t,e,n,r)=>q(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var bs=require("jose");var Zr,Rs=s(async(t,e,n,r)=>{if(!Zr)try{Zr=await(0,bs.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return q(t,e,{issuer:n.authUrl,secret:Zr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ps=xe(be());var an=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},qr=class extends an{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fr=class extends an{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function tl(t,e){if($o(t))throw new qr(e)}s(tl,"throwIfUndefinedOrNull");function ut(t,e){if(tl(t,e),!K(t))throw new Fr(e,"string")}s(ut,"throwIfNotString");var un=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return ut(e,"redisClientUrl"),ut(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){ut(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new _("Redis client failed with 401: Unauthorized"):new _(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},cn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(ut(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new _("The in-memory redis client only supports /rate-limit calls")}};var ln=(0,Ps.debug)("zuplo:policies:RateLimitInboundPolicy"),nl="strict",rl=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),ol=s(async t=>({key:`ip-${rl(t)}`}),"getIP"),il=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),sl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),dn;function al(t,e){let n;if(dn)return dn;if(h.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new cn,dn=n,n;let{authApiJWT:r,redisURL:o}=h.instance;if(!K(o))throw new _(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!K(r))throw new _(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=un.initialize(o,r,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!n||!n.isEnabled())throw new _(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return dn=n,n}s(al,"getRedisClient");async function ws(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(ws,"getCountAndUpdateExpiry");function ul(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new I(c)}return u},"outerFunction")}s(ul,"wrapUserFunction");var cl="Retry-After",$r=s(async(t,e,n,r)=>{let o=Date.now(),i=S.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new _(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[cl]=l.toString()),w.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:ul(n,r),user:il,ip:ol,all:sl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,y=n.headerMode??"retry-after",E=al(r,i),x=`bucket/${h.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??nl)==="async"){let A=await Z(r,n),j=new ue(A,{logger:S.getLogger(e)}),W=ws(x,m,E,i,e.requestId),J=await j.get(x);if(J!==void 0&&J<=Date.now()){ln(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let Ee=Math.round((J-Date.now())/1e3);return u(y,Ee)}return e.addEventListener("responseSending",Ee=>{try{let Ie=Ee,Rn=Ie.mutableResponse;Ie.mutableResponse=(async()=>{let ct=await W;if(ct.count>R){let na=Date.now()+ct.ttlSeconds*1e3;return j.put(x,na,ct.ttlSeconds).catch(Yr=>{throw i.error(Yr),Yr}),ln(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(y,ct.ttlSeconds)}return Rn})()}catch(Ie){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Ie)}}),t}let k=await ws(x,m,E,i,e.requestId);return k.count>R?(ln(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(y,k.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;ln(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var jr;function Es(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(Es,"headersToNameValuePairs");function ll(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(ll,"queryToNameValueParis");function dl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(dl,"parseIntOrUndefined");var Is={};async function xs(t,e,n,r){let o=new Date,i=Date.now();return jr||(jr={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?we(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?we(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:h.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:jr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Es(t.headers),queryString:ll(t.query)},response:{status:a.status,statusText:a.statusText,headers:Es(a.headers),content:{size:dl(t.headers.get("content-length"))}}}]}}},d=Is[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async R=>{try{let m=n.url??"https://metrics.readme.io/request",y=await fetch(m,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${y.status}: '${await y.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),Is[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(xs,"ReadmeMetricsInboundPolicy");var vs=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new L(t,{headers:i})},"RemoveHeadersInboundPolicy");var Os=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var Ts=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new L(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var Ss=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Cs=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),As=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Cs():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Cs():t},"RequestSizeLimitInboundPolicy");function Ls(t,e,n){return`_${he(t+"_"+e+"_"+n)}`}s(Ls,"getRawOperationDataIdentifierName");function pn(t,e,n,r){return`_${he(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(pn,"getIdForParameterSchema");function mn(t,e,n){return`_${he(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${he(n.toLowerCase())}`}s(mn,"getIdForRequestBodySchema");function _s(t,e){return`_${he(t)}__${he(e)}`}s(_s,"getIdForRefSchema");function he(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(he,"sanitizedIdentifierName");var qe=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Fe=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=pn(n,r,o,c.name),d=G.instance.schemaValidator[l],p=d(e[c.name]),R=zr(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Q=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),X=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ee=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),zr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function ks(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,E=w.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${m}`});if(X(n.validateBody)&&Q(t,n.logLevel??"info",y,[r],m),ee(n.validateBody))return E}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=w.badRequest(e,t,{detail:m});return X(n.validateBody)&&Q(t,n.logLevel??"info",m,[r],[m]),ee(n.validateBody)?y:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=mn(t.route.path,e.method,o),u=G.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=w.badRequest(e,t,{detail:m});return X(n.validateBody)&&Q(t,n.logLevel??"info",m,[r],[m]),ee(n.validateBody)?y:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=zr(l),R=w.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(X(n.validateBody)&&Q(t,n.logLevel??"info",d,[r],p),ee(n.validateBody))return R}s(ks,"handleBodyValidation");function Ds(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=qe(t),i=Fe(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=w.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(X(n.validateHeaders)&&Q(t,n.logLevel??"info",a,i.invalidValues,i.errors),ee(n.validateHeaders))return u}}s(Ds,"handleHeadersValidation");function Hs(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=qe(t),o=Fe(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=w.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(X(n.validatePathParameters)&&Q(t,n.logLevel??"info",i,o.invalidValues,o.errors),ee(n.validatePathParameters))return a}}s(Hs,"handlePathParameterValidation");function Us(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=qe(t),o=Fe(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=w.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(X(n.validateQueryParameters)&&Q(t,n.logLevel??"info",i,o.invalidValues,o.errors),ee(n.validateQueryParameters))return a}}s(Us,"handleQueryParameterValidation");var Br=s(async(t,e,n)=>{let r=Us(e,t,n);if(r!==void 0||(r=Hs(e,t,n),r!==void 0)||(r=Ds(e,t,n),r!==void 0))return r;let o=await ks(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ns=Br;var Ms=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return w.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Zs=s(async(t,e,n)=>new L(t,{body:n.body}),"SetBodyInboundPolicy");var qs=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new L(t,{headers:i})},"SetHeadersInboundPolicy");var Fs=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var $s=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new L(i.toString(),t)},"SetQueryParamsInboundPolicy");var js=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var pl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),zs=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await pl(n.sleepInMs),t},"SleepInboundPolicy");var Bs=s(async(t,e,n,r)=>{M(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await q(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof L))throw new _("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new I(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?w.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Gs=s(async(t,e,n,r)=>{M(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await Z(r,n),i=new N(o,{logger:S.getLogger(e)}),a=await i.get(r);if(!a){let u=await ml(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function ml(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Ae({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new I("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new I("Response returned from Azure AD is not in the expected format.")}s(ml,"getAccessToken");var Vs="https://accounts.google.com/o/oauth2/token",Gr,Ws=s(async(t,e,n,r)=>{M(n,r).required("serviceAccountJson","string"),Gr||(Gr=await B.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await Z(r,n),a=new N(i,{logger:S.getLogger(e)}),u=await a.get(r);if(!u){let c=await ne({serviceAccount:Gr,audience:Vs,payload:o}),l=await _t(Vs,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new I("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var gl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",fl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Vr,Js=s(async(t,e,n,r)=>{if(M(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(fl.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Vr||(Vr=await B.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new I("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new I(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=we(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new I(`Unable to determine user from for the policy ${r}`);let a=await Z(r,n),u=new N(a,{logger:S.getLogger(e)}),c={uid:i,claims:o},l=await on(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ne({serviceAccount:Vr,audience:gl,payload:c}),R=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await si(R,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new I("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Wr,Ks=s(async(t,e,n,r)=>{M(n,r).required("audience","string").required("serviceAccountJson","string"),Wr||(Wr=await B.init(n.serviceAccountJson));let o=await ne({serviceAccount:Wr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Ys="https://www.googleapis.com/oauth2/v4/token",Jr,Qs=s(async(t,e,n,r)=>{M(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Jr||(Jr=await B.init(n.serviceAccountJson));let o=await Z(r,n),i;n.useMemoryCacheOnly?i=new ve(o):i=new N(o,e);let a=await i.get(r);if(!a){let u=await ne({serviceAccount:Jr,audience:Ys,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await _t(Ys,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new I("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Xs=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return w.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new _("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return w.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ea=s(async(t,e,n,r)=>{let o=S.getLogger(e);e.addResponseSendingFinalHook(async(d,p,R)=>{let m=ae.get(R,"subscription");if((n.allowRequestsWithoutSubscription??!1)&&!m)return;let E=n.bucketId;if(!E){R.log.error(`MeteringInboundPolicy '${r}' - no bucketName property provided`);return}let{authApiJWT:P,meteringServiceUrl:x}=h.instance;d.ok&&m&&n.meters&&fetch(`${x}/internal/v1/metering/${E}/subscriptions/${m.id}/quotas/consume`,{headers:{Authorization:`Bearer ${P}`},method:"POST",body:JSON.stringify({meters:n.meters})}).catch(T=>{R.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`,T)})});let i=ae.get(e,"subscription"),a=n.allowRequestsWithoutSubscription??!1,u=n.allowRequestsOverQuota??!1;if(!i){if(a)return t;throw new f("Subscription is not available for user")}if(i&&Object.keys(i.quotas).length===0)throw new f("Quota is not set up for the user's subscription");let l=Object.keys(n.meters).filter(d=>!Object.keys(i.quotas).includes(d));if(l.length>0)throw new f(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(i.quotas))if(i.quotas[d]<=0&&!u)return w.tooManyRequests(t,e,{detail:`Quota exceeded for meter '${d}'`});return t},"MeteringInboundPolicy");var ta=s(async(t,e,n,r)=>{let o=S.getLogger(e),i=n.allowRequestsWithoutSubscription??!1,a=t.user;if(!a)return i?t:w.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});let u=n.bucketId;if(!u)throw new f(`LoadSubscriptionInboundPolicy '${r}' - no bucketName property provided`);let{authApiJWT:c,meteringServiceUrl:l}=h.instance,{sub:d}=a,p,R;try{if(p=await fetch(`${l}/internal/v1/metering/${u}/subscriptions?customerRef=${d}&status=active`,{headers:{Authorization:`Bearer ${c}`},method:"GET"}),!p.ok)return e.log.error(await p.text()),w.forbidden(t,e);R=await p.json()}catch(y){o.error(`LoadSubscriptionInboundPolicy '${r}' -error in serviceResponse`,y)}if((!R||!R.data||R.data.length===0)&&!i)return w.unauthorized(t,e,{detail:"No valid, active subscription found"});if((!R||!R.data||R.data.length===0)&&i)return t;let m=R&&R.data?R.data[0]:void 0;return ae.set(e,"subscription",m),t},"LoadSubscriptionInboundPolicy");var gn=class t{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,n){if(this.services.get(e))throw new _(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Kr=["sha-1","sha-256","sha-384","sha-512"],fn=class{static{s(this,"BaseCryptoBeta")}};var hn=class extends fn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Kr.includes(e.toLowerCase()))throw new I(`Algorithm ${e} is not supported. Try using ${Kr.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var yn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var bn=class extends yn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new lt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new f("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
|
|
72
72
|
/*! For license information please see index.minified.js.LEGAL.txt */
|