@zuplo/runtime 5.1814.0 → 5.1815.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.d.ts +8 -41
- package/index.minified.js +1 -1
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -2417,30 +2417,11 @@ export declare class MemoryZoneReadThroughCache<T = unknown> {
|
|
|
2417
2417
|
|
|
2418
2418
|
/* Excluded from this release type: MeteringPlugin */
|
|
2419
2419
|
|
|
2420
|
-
|
|
2420
|
+
/* Excluded from this release type: MeteringRegions */
|
|
2421
2421
|
|
|
2422
|
-
|
|
2423
|
-
status: MeteringSubscriptionStatus;
|
|
2424
|
-
type: "credits" | "periodic";
|
|
2425
|
-
region: MeteringRegions;
|
|
2426
|
-
renewalStrategy: "hourly" | "monthly" | "yearly";
|
|
2427
|
-
customerKey: string;
|
|
2428
|
-
/**
|
|
2429
|
-
* Array of Stripe product ids, they start with "prod_"
|
|
2430
|
-
*/
|
|
2431
|
-
planExternalIds: string[];
|
|
2432
|
-
/**
|
|
2433
|
-
* Stripe subscription id, starts with "sub_"
|
|
2434
|
-
*/
|
|
2435
|
-
subscriptionExternalId?: string;
|
|
2436
|
-
/**
|
|
2437
|
-
* Stripe customer id, starts with "cus_"
|
|
2438
|
-
*/
|
|
2439
|
-
customerExternalId?: string;
|
|
2440
|
-
metadata?: Record<string, string>;
|
|
2441
|
-
}
|
|
2422
|
+
/* Excluded from this release type: MeteringSubscription */
|
|
2442
2423
|
|
|
2443
|
-
|
|
2424
|
+
/* Excluded from this release type: MeteringSubscriptionStatus */
|
|
2444
2425
|
|
|
2445
2426
|
/* Excluded from this release type: MetricsData */
|
|
2446
2427
|
|
|
@@ -2584,6 +2565,8 @@ declare type MonetizationPolicyMeters = {
|
|
|
2584
2565
|
[Key in string]: number;
|
|
2585
2566
|
};
|
|
2586
2567
|
|
|
2568
|
+
/* Excluded from this release type: MonetizationSubscription */
|
|
2569
|
+
|
|
2587
2570
|
declare interface NotFoundOptions {
|
|
2588
2571
|
routesMatchedByPathOnly: RouteConfiguration[];
|
|
2589
2572
|
}
|
|
@@ -3676,22 +3659,6 @@ export declare interface SleepInboundPolicyOptions {
|
|
|
3676
3659
|
|
|
3677
3660
|
/* Excluded from this release type: StandardEnv */
|
|
3678
3661
|
|
|
3679
|
-
declare interface StoredMeteringSubscriptionWithQuotas extends MeteringSubscription {
|
|
3680
|
-
/**
|
|
3681
|
-
* Metering subscription id, starts with "sbsc_"
|
|
3682
|
-
*/
|
|
3683
|
-
id: string;
|
|
3684
|
-
createdOn: string;
|
|
3685
|
-
updatedOn: string;
|
|
3686
|
-
quotaResetAnchor?: Date;
|
|
3687
|
-
meters: {
|
|
3688
|
-
[Key in string]: {
|
|
3689
|
-
consumed: number;
|
|
3690
|
-
max: number;
|
|
3691
|
-
};
|
|
3692
|
-
};
|
|
3693
|
-
}
|
|
3694
|
-
|
|
3695
3662
|
/* Excluded from this release type: StripeMeteringPlugin */
|
|
3696
3663
|
|
|
3697
3664
|
/* Excluded from this release type: StripeMeteringPluginOptions */
|
|
@@ -4230,11 +4197,11 @@ export declare interface XmlToJsonPolicyOptions {
|
|
|
4230
4197
|
*/
|
|
4231
4198
|
removeNSPrefix?: boolean;
|
|
4232
4199
|
/**
|
|
4233
|
-
* Ignore processing instruction tags. i.e.
|
|
4200
|
+
* Ignore processing instruction tags. i.e. `<?elementnames <fred>, <bert>, <harry> ?>`.
|
|
4234
4201
|
*/
|
|
4235
4202
|
ignoreProcessingInstructions?: boolean;
|
|
4236
4203
|
/**
|
|
4237
|
-
* Ignore declarations. i.e.
|
|
4204
|
+
* Ignore declarations. i.e. `<?xml version="1.0"?>`.
|
|
4238
4205
|
*/
|
|
4239
4206
|
ignoreDeclarations?: boolean;
|
|
4240
4207
|
/**
|
|
@@ -4246,7 +4213,7 @@ export declare interface XmlToJsonPolicyOptions {
|
|
|
4246
4213
|
*/
|
|
4247
4214
|
stopNodes?: string[];
|
|
4248
4215
|
/**
|
|
4249
|
-
* The prefix of attribute names in the resulting JS object
|
|
4216
|
+
* The prefix of attribute names in the resulting JS object.
|
|
4250
4217
|
*/
|
|
4251
4218
|
attributeNamePrefix?: string;
|
|
4252
4219
|
/**
|
package/index.minified.js
CHANGED
|
@@ -74,5 +74,5 @@ Signature verification is impossible without access to the original signed mater
|
|
|
74
74
|
`+p}):new Pe(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
75
75
|
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.
|
|
76
76
|
`+l+`
|
|
77
|
-
`+p});let d=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&d>o)throw new Pe(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Pl,"validateComputedSignature");function El(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(El,"parseHeader");function Il(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(Il,"secureCompare");async function xl(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]=co[i[u]];return a.join("")}s(xl,"computeHMACSignatureAsync");var co=new Array(256);for(let t=0;t<co.length;t++)co[t]=t.toString(16).padStart(2,"0");function W(t,e){if(!De(t))throw new y(`Options on policy '${e}' is expected to be an object. Received the type '${typeof t}'.`);let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new y(`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 y(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new y(`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 y(`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 y(`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(W,"optionValidator");var nt=class extends pe{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Ps(o,r,this.options.signingSecret)}catch(o){return n.log.error("Error validating stripe webhook",o),S.badRequest(e,n,{title:"Webhook Error",detail:o.message})}return e}};function Es(t){return t!==null&&typeof t=="object"&&"id"in t&&se(t.id)&&"type"in t&&se(t.type)}s(Es,"isStripeWebhookEvent");var xn=class extends Ee{static{s(this,"MeteringPlugin")}};var vl={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new L(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new L(i)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(i,o),new L(i)}return o}},vn=vl;var lo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function Is({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=x.instance,c=new URL(`/v1/buckets/${t}/consumers`,lo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),p={name:l,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(p)}),g=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw a.log.error(m,g),new L(m)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}s(Is,"createConsumer");async function xs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=x.instance,u=new URL(`/v1/buckets/${t}/consumers`,lo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},p=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),d=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw i.log.error(g,d),new L(g)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}s(xs,"createConsumerInvite");async function vs({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=x.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,lo);o.searchParams.set("with-api-key","true");let i=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error deleting API Key Consumer";throw n.log.error(u,a),new L(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}s(vs,"deleteConsumer");async function Ts({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:p}=x.instance;if(!Ge(l))throw new q("No Zuplo JWT token set.");let d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!d.ok){let g="Error creating metering subscription.",m;try{m=await d.json()}catch{m={status:d.status,statusText:d.statusText}}throw t.log.error(g,m),new L(g)}t.log.info("Successfully created/updated metering subscription.",c)}s(Ts,"createSubscription");async function Tt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=x.instance;if(!Ge(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new L(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}s(Tt,"updateSubscription");async function St({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=x.instance;if(!Ge(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new L(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new L(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new L(c)}return u.data[0]}s(St,"getSubscription");function Tn(t){return t.replaceAll("_","-")}s(Tn,"stripeStatusToMeteringStatus");async function po(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),S.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=i.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await Is({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await vn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),S.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await xs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return S.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=Tn(n.data.object.status);await Ts({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await vs({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),S.internalServerError(t,e,{detail:l.message})}return S.ok(t,e)}s(po,"onCustomerSubscriptionCreated");async function go(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await Tt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),S.ok(t,e)}s(go,"onCustomerSubscriptionDeleted");async function mo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=Tn(n.data.object.status);return await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),S.ok(t,e)}if(a.plan&&a.plan.product!==n.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,l=await vn.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey});e.log.debug(`upcoming invoice: ${JSON.stringify(l)}`);let p=l.lines.data.filter(g=>(e.log.debug(`line item from invoice: ${JSON.stringify(g)}`),g.proration&&g.price.product===c)),d=0;return p.length===0?e.log.warn(`Not able to calculate proration details on plan change for subscription event '${n.id}'`):d=parseFloat(p[0].unit_amount_excluding_tax)/p[0].price.unit_amount,await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:d}}),S.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),S.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}s(mo,"onCustomerSubscriptionUpdated");var fo=class extends xn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:p,apiKeyBucketName:d}=this.options;if(!p)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)p=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!d)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!x.instance.build.ACCOUNT_NAME)throw new q("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.meteringBucketRegion??"us-central1";if(!Tl(g))throw new y(`StripeMeteringPlugin - The value '${g}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!Es(m))return S.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`),m.type){case"customer.subscription.created":return await po(c,l,m,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await mo(c,l,m,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await go(c,l,m,{meteringBucketId:p});default:return S.badRequest(c,l,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=Ci({inboundPolicies:[new nt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),a=new J({processors:[ne,i],handler:o,gateway:r}),u=new G({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Tl(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(Tl,"isMetricsRegion");var Os=new WeakMap,Ss={},Sn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Os.set(e,n)}};async function Cs(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=We(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Os.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new L(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ze(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 p=a?.meterValue??n.meterValue;if(!p){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let d={customerId:c,meterApiName:l,meterValue:p,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},g=Ss[n.apiKey];if(!g){let m=n.apiKey,R=t.headers.get("zm-test-id")??"";g=new B("amberflo-ingest-meter",10,async w=>{try{let I=n.url??"https://app.amberflo.io/ingest",T=await fetch(I,{method:"POST",body:JSON.stringify(w),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":R}});T.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${T.status}: ${await T.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),Ss[m]=g}g.enqueue(d),e.waitUntil(g.waitUntilFlushed())}}),t}s(Cs,"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 As=new Map;async function X(t,e){let n,r=As.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await On(JSON.stringify({policyName:t,options:e}))}`,As.set(t,n)),n}s(X,"getPolicyCacheName");var Ls="key-metadata-cache-type";function Sl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(Sl,"getKeyValue");async function Cn(t,e,n,r){if(!n.bucketName)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`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 y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(I=>o.allowUnauthenticatedRequests?t:S.unauthorized(t,e,{detail:I}),"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=Sl(a,o);if(!u||u==="")return i("No key present");let c=await Ol(u),l=await X(r,o),p=new Y(l,e),d=await p.get(c);if(d&&d.isValid===!0)return t.user=d.user,t;if(d&&!d.isValid)return d.typeId!==Ls&&F.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${d.typeId}'`,d),i("Authorization Failed");let g={key:u},m=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(e)},`${x.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":x.instance.deploymentName??"unknown","User-Agent":x.instance.systemUserAgent},body:JSON.stringify(g)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let I=await m.text(),T=JSON.parse(I);e.log.error("Unexpected response from key service",T)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let R=await m.json(),w={isValid:!0,typeId:Ls,user:{sub:R.name,data:R.metadata}};return t.user=w.user,p.put(c,w,o.cacheTtlSeconds),t}s(Cn,"ApiKeyInboundPolicy");async function Ol(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(Ol,"hashValue");var _s=Cn;var Ot=require("jose");var ho={},Cl=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");ho[e.jwkUrl]||(ho[e.jwkUrl]=(0,Ot.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,Ot.jwtVerify)(t,ho[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Al=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,Ot.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ee=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(g=>S.unauthorized(t,e,{detail:g}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Cl:Al,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 g=o.substring(i.length);if(!g||g.length===0)return a("No bearer token on authorization header");try{return await u(g,n)}catch(m){let R=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${R.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let p=n.subPropertyName??"sub",d=l[p];return d?(t.user={sub:d,data:l},t):a(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Ns=s(async(t,e,n,r)=>ee(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var ks=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>S.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 p=atob(l).normalize(),d=p.indexOf(":");if(d===-1||/[\0-\x1F\x7F]/.test(p))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let g=p.substring(0,d),m=p.substring(d+1),R=n.accounts.find(w=>w.username===g&&w.password===m);return R||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 Ll=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function _l(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(_l,"digestMessage");var Nl=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[p,d]of t.headers.entries())n.includes(p)&&r.push({key:p.toLowerCase(),value:d});r.sort((p,d)=>p.key.localeCompare(d.key));let o=await _l(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 Ms(t,e,n,r){let o=await X(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Nl(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let p=n.statusCodes??[200,206,301,302,303,404,410],d=l.response.clone();if(!p.includes(d.status)||!a.includes(t.method.toUpperCase()))return;let g=n?.expirationSecondsTtl??60,m=new Response(d.body,d);Ll.forEach(R=>m.headers.delete(R)),m.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(i.put(u,m))}catch(p){e.log.error(`Error in caching-inbound-policy '${r}': "${p.message}"`,p)}}),t)}s(Ms,"CachingInboundPolicy");var Us=s(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new j(t,{method:n.method})},"ChangeMethodInboundPolicy");var Hs=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 j(t,{headers:o})},"ClearHeadersInboundPolicy");var Ds=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 Zs=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",ee(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var qs=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return ee(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 $s=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Q.instance,i=yt(n.policies,o?.routeData.policies);return Cr(i)(t,e)},"CompositeInboundPolicy");var Fs=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return S.unauthorized(t,e,{detail:"No authorization header"});let i=kl(o);if(!i)return S.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await X(r,n),u=new Y(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"}),p=await l.text();if(l.status===200)c=p,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${p}'`),S.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):S.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function kl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(kl,"getToken");var Bs=s(async(t,e,n,r)=>(W(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ee(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 js=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[p,d]of a)u[p]=d.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var rt="__unknown__",Vs=s(async(t,e,n,r)=>{let o={allow:{countries:it(n.allow?.countries,"allow.countries",r),regionCodes:it(n.allow?.regionCodes,"allow.regionCode",r),asns:it(n.allow?.asns,"allow.asOrganization",r)},block:{countries:it(n.block?.countries,"block.countries",r),regionCodes:it(n.block?.regionCodes,"block.regionCode",r),asns:it(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??rt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??rt,u=e.incomingRequestProperties.asn?.toString()??rt,c=o.ignoreUnknown&&i===rt,l=o.ignoreUnknown&&a===rt,p=o.ignoreUnknown&&u===rt,d=o.allow.countries,g=o.allow.regionCodes,m=o.allow.asns;if(d.length>0&&!d.includes(i)&&!c||g.length>0&&!g.includes(a)&&!l||m.length>0&&!m.includes(u)&&!p)return ot(t,e,r,i,a,u);let R=o.block.countries,w=o.block.regionCodes,I=o.block.asns;return R.length>0&&R.includes(i)&&!c||w.length>0&&w.includes(a)&&!l||I.length>0&&I.includes(u)&&!p?ot(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function ot(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),S.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(ot,"blockedResponse");function it(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 y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(it,"toLowerStringArray");var zs=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 Ws=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return yo(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 yo(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 p=o[u].content[l].examples;p&&Object.keys(p).forEach(g=>{a.push({responseName:u,contentName:l,exampleName:g,exampleValue:p[g]})})})}),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 Gs(a[u])}else return a.length>0?Gs(a[0]):yo(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 Gs(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(Gs,"generateResponse");var yo=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return S.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Ml="Incoming",Ul={logRequestBody:!0,logResponseBody:!0};function Js(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Js,"headersToObject");function Ks(){return new Date().toISOString()}s(Ks,"timestamp");var bo=new WeakMap,Hl={};function Xs(t,e){let n=bo.get(t);n||(n=Hl);let r=Object.assign({...n},e);bo.set(t,r)}s(Xs,"setMoesifContext");async function Ys(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(Ys,"readBody");var Dl={},wo;function Qs(){if(!wo)throw new L("Invalid State - no _lastLogger");return wo}s(Qs,"getLastLogger");function Zl(t){let e=Dl[t];return e||(e=new B("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Qs().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||Qs().error({status:o.status,body:await o.text()})})),e}s(Zl,"getDispatcher");async function ea(t,e,n,r){wo=e.log;let o=Ks(),i=Object.assign(Ul,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Ys(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Zl(i.applicationId),p=t.headers.get("true-client-ip"),d=bo.get(e)??{},g={time:o,uri:t.url,verb:t.method,body:a,ip_address:p??void 0,api_version:d.apiVersion,headers:Js(t.headers)},m=i.logResponseBody?await Ys(u,e):void 0,R={time:Ks(),status:u.status,headers:Js(u.headers),body:m},w={request:g,response:R,user_id:d.userId??c.user?.sub,session_token:d.sessionToken,company_id:d.companyId,metadata:d.metadata,direction:Ml};l.enqueue(w),e.waitUntil(l.waitUntilFlushed())}),t}s(ea,"MoesifInboundPolicy");async function ta(t,e,n,r){let o=F.getLogger(t),{authApiJWT:i,meteringServiceUrl:a}=x.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let p=await l.json(),d=p.detail??p.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${d}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${d}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}s(ta,"loadSubscription");async function na(t,e,n,r,o){let{authApiJWT:i,meteringServiceUrl:a}=x.instance,u=F.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),p=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${p}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${p}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}s(na,"consumeSubcriptionQuotas");var ql=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function An(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}s(An,"validateMeters");function ra(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=qe(t),r=[];for(let o of n)ql.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}s(ra,"parseAllowedSubscriptionStatuses");var Ln=class extends pe{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,lt)}static setMeters(e,n){An(n,"setMeters"),le.set(e,_t,n)}async handler(e,n){if(W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),!this.options.meterOnStatusCodes)throw new y(`Invalid MonetizationInboundPolicy '${this.policyName}' - The property 'meterOnStatusCodes' must be an array of HTTP status code numbers`);let r=this.options.allowRequestsOverQuota??!1,o=We(this.options.meterOnStatusCodes),i=le.get(n,_t),a={...this.options.meters,...i};An(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ra(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(w,I,T)=>{let f=le.get(T,lt);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){T.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let A=le.get(T,_t),Z={...this.options.meters,...A};An(Z,this.policyName),o.includes(w.status)&&f&&Z&&(T.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(Z)} on response status '${w.status}'`),await na(T,f.id,this.policyName,this.options.bucketId,Z))});let l=e.user;if(!l)return u?e:S.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:p}=l,d=await ta(n,p,this.policyName,this.options.bucketId);if(!d)return n.log.warn("No valid subscription found"),u?e:S.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(d.status)&&!u)return n.log.warn(`Subscription '${d.id}' has status '${d.status}' which is not part of the allowed statuses.`),S.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(d.status)&&(n.log.debug(`Loading subscription '${d.id}' for user sub '${p}' to ContextData`),le.set(n,lt,d));let g=le.get(n,lt);if(!g)return u?e:(n.log.warn("Subscription is not available for user"),S.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(g&&Object.keys(g.meters).length===0)return n.log.error(`Quota is not set up for subscription '${g.id}'`),S.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let R=Object.keys(a).filter(w=>!Object.keys(g.meters).includes(w));if(R.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${R.join(", ")}`),S.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${R.join(", ")}`,title:"Quota Exceeded"});for(let w of Object.keys(a))if(g.meters[w].consumed<=0&&!r)return S.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${w}'`,title:"Quota Exceeded"});return e}};var oa=s(async(t,e,n,r)=>ee(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var ia=require("jose");var Ro,sa=s(async(t,e,n,r)=>{if(!Ro)try{Ro=await(0,ia.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ee(t,e,{issuer:n.authUrl,secret:Ro,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ua=ke(Ue());var _n=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Po=class extends _n{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Eo=class extends _n{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function $l(t,e){if(Ii(t))throw new Po(e)}s($l,"throwIfUndefinedOrNull");function Ct(t,e){if($l(t,e),!se(t))throw new Eo(e,"string")}s(Ct,"throwIfNotString");var Nn=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 Ct(e,"redisClientUrl"),Ct(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}){Ct(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 q("Redis client failed with 401: Unauthorized"):new q(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},kn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Ct(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 q("The in-memory redis client only supports /rate-limit calls")}};var Mn=(0,ua.debug)("zuplo:policies:RateLimitInboundPolicy"),Fl="strict",Bl=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"),jl=s(async t=>({key:`ip-${Bl(t)}`}),"getIP"),Vl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),zl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Un;function Gl(t,e){let n;if(Un)return Un;if(x.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new kn,Un=n,n;let{authApiJWT:r,redisURL:o}=x.instance;if(!se(o))throw new q(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!se(r))throw new q(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=Nn.initialize(o,r,x.instance.deploymentName??"unknown",x.instance.systemUserAgent)),!n||!n.isEnabled())throw new q(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Un=n,n}s(Gl,"getRedisClient");async function aa(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(aa,"getCountAndUpdateExpiry");function Wl(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`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 y(`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 L(c)}return u},"outerFunction")}s(Wl,"wrapUserFunction");var Jl="Retry-After",Io=s(async(t,e,n,r)=>{let o=Date.now(),i=F.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new q(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let p={};return(!c||c==="retry-after")&&(p[Jl]=l.toString()),S.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let l={function:Wl(n,r),user:Vl,ip:jl,all:zl}[n.rateLimitBy],p=await l(t,e,r),d=p.key,g=p.requestsAllowed??n.requestsAllowed,m=p.timeWindowMinutes??n.timeWindowMinutes,R=n.headerMode??"retry-after",w=Gl(r,i),T=`bucket/${x.instance.build.BUILD_ID}/${r}/${d}`;if((n.mode??Fl)==="async"){let A=await X(r,n),Z=new ve(A,{logger:F.getLogger(e)}),h=aa(T,m,w,i,e.requestId),b=await Z.get(T);if(b!==void 0&&b<=Date.now()){Mn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${T}' (async mode)`);let O=Math.round((b-Date.now())/1e3);return u(R,O)}return e.addEventListener("responseSending",O=>{try{let k=O,C=k.mutableResponse;k.mutableResponse=(async()=>{let _=await h;if(_.count>g){let $=Date.now()+_.ttlSeconds*1e3,M=Z.put(T,$,_.ttlSeconds).catch(N=>{throw i.error(new q("Error caching rate limit result.",{cause:N})),N});return e.waitUntil(M),Mn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${T}' (async mode)`),u(R,_.ttlSeconds)}return C})()}catch(k){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,k)}}),t}let E=await aa(T,m,w,i,e.requestId);return E.count>g?(Mn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${T}' (strict mode)`),u(R,E.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;Mn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var xo;function ca(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(ca,"headersToNameValuePairs");function Kl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Kl,"queryToNameValueParis");function Yl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Yl,"parseIntOrUndefined");var la={};async function da(t,e,n,r){let o=new Date,i=Date.now();return xo||(xo={name:"zuplo",version:x.instance.build.ZUPLO_VERSION,comment:`zuplo/${x.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ze(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ze(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:x.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:xo,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:ca(t.headers),queryString:Kl(t.query)},response:{status:a.status,statusText:a.statusText,headers:ca(a.headers),content:{size:Yl(t.headers.get("content-length"))}}}]}}},p=la[n.apiKey];if(!p){let d=n.apiKey;p=new B("readme-metering-inbound-policy",10,async g=>{try{let m=n.url??"https://metrics.readme.io/request",R=await fetch(m,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(d+":")}`}});R.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${R.status}: '${await R.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),la[d]=p}p.enqueue(l),e.waitUntil(p.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(da,"ReadmeMetricsInboundPolicy");var pa=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`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 j(t,{headers:i})},"RemoveHeadersInboundPolicy");var ga=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new y(`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 ma=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`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 j(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var fa=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 ha=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ya=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?ha():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ha():t},"RequestSizeLimitInboundPolicy");function ba(t,e,n){return`_${Ne(t+"_"+e+"_"+n)}`}s(ba,"getRawOperationDataIdentifierName");function Hn(t,e,n,r){return`_${Ne(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(Hn,"getIdForParameterSchema");function Dn(t,e,n){return`_${Ne(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ne(n.toLowerCase())}`}s(Dn,"getIdForRequestBodySchema");function wa(t,e){return`_${Ne(t)}__${Ne(e)}`}s(wa,"getIdForRefSchema");function Ne(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(Ne,"sanitizedIdentifierName");var st=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"),at=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let p=Hn(n,r,o,c.name),d=Q.instance.schemaValidator[p],g=d(e[c.name]),m=vo(d.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),me=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),fe=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),he=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),vo=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 Ra(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let R=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=S.badRequest(e,t,{detail:`${R}, see errors property for more details`,errors:`${m}`});if(fe(n.validateBody)&&me(t,n.logLevel??"info",R,[r],m),he(n.validateBody))return w}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,R=S.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?R:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Dn(t.route.path,e.method,o),u=Q.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")}`,R=S.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?R:void 0}if(u(r))return;let l=u.errors,p="Request body did not pass validation",d=vo(l),g=S.badRequest(e,t,{detail:`${p}, see errors property for more details`,errors:d});if(fe(n.validateBody)&&me(t,n.logLevel??"info",p,[r],d),he(n.validateBody))return g}s(Ra,"handleBodyValidation");function Pa(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=st(t),i=at(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=S.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(fe(n.validateHeaders)&&me(t,n.logLevel??"info",a,i.invalidValues,i.errors),he(n.validateHeaders))return u}}s(Pa,"handleHeadersValidation");function Ea(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=st(t),o=at(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=S.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(fe(n.validatePathParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),he(n.validatePathParameters))return a}}s(Ea,"handlePathParameterValidation");function Ia(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=st(t),o=at(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=S.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(fe(n.validateQueryParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),he(n.validateQueryParameters))return a}}s(Ia,"handleQueryParameterValidation");var To=s(async(t,e,n)=>{let r=Ia(e,t,n);if(r!==void 0||(r=Ea(e,t,n),r!==void 0)||(r=Pa(e,t,n),r!==void 0))return r;let o=await Ra(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),xa=To;var va=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`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 S.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Ta=s(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var Sa=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`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 y(`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 j(t,{headers:i})},"SetHeadersInboundPolicy");var Oa=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new y(`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 y(`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 Ca=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`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 y(`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 j(i.toString(),t)},"SetQueryParamsInboundPolicy");var Aa=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 Ql=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),La=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Ql(n.sleepInMs),t},"SleepInboundPolicy");var _a=s(async(t,e,n,r)=>{W(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await ee(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof j))throw new q("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 L(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(p=>{let d=a[p];Array.isArray(d)?d.includes(u[p])||l.push(p):d!==u[p]&&l.push(p)}),l.length>0?S.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Na=s(async(t,e,n,r)=>{W(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await X(r,n),i=new Y(o,e),a=await i.get(r);if(!a){let u=await Xl(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 Xl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({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 L("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 L("Response returned from Azure AD is not in the expected format.")}s(Xl,"getAccessToken");var ka="https://accounts.google.com/o/oauth2/token",So,Ma=s(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string"),So||(So=await ae.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 X(r,n),a=new Y(i,e),u=await a.get(r);if(!u){let c=await we({serviceAccount:So,audience:ka,payload:o}),l=await en(ka,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("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 ed="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",td=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Oo,Ua=s(async(t,e,n,r)=>{if(W(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let d in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,d)){if(td.indexOf(d)!==-1)throw new y(`Developer claim "${d}" is reserved and cannot be specified.`);o[d]=n.developerClaims[d]}}Oo||(Oo=await ae.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new L("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 L(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ze(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new L(`Unable to determine user from for the policy ${r}`);let a=await X(r,n),u=new Y(a,e),c={uid:i,claims:o},l=await On(JSON.stringify(c)),p=await u.get(l);if(!p){let d=await we({serviceAccount:Oo,audience:ed,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await qi(g,d,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new L("Invalid token response from Firebase");p=m.idToken,u.put(l,p,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${p}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Co,Ha=s(async(t,e,n,r)=>{W(n,r).required("audience","string").required("serviceAccountJson","string"),Co||(Co=await ae.init(n.serviceAccountJson));let o=await we({serviceAccount:Co,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Da="https://www.googleapis.com/oauth2/v4/token",Ao,Za=s(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ao||(Ao=await ae.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=qe(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let i=await X(r,n),a;n.useMemoryCacheOnly?a=new Be(i):a=new Y(i,e);let u=await a.get(r);if(!u){let c=await we({serviceAccount:Ao,audience:Da,payload:o}),l=await en(Da,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var qa=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return S.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 q("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 S.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ja=ke(Ba());var Zn=class extends Ie{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?We(e.parseOnStatusCodes):void 0,this.parser=new ja.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,n,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new L(c)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var qn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new q(`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 _o=["sha-1","sha-256","sha-384","sha-512"],$n=class{static{s(this,"BaseCryptoBeta")}};var Fn=class extends $n{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!_o.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${_o.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 Bn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var jn=class extends Bn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new At("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new y("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)}};
|
|
77
|
+
`+p});let d=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&d>o)throw new Pe(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Pl,"validateComputedSignature");function El(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(El,"parseHeader");function Il(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(Il,"secureCompare");async function xl(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]=co[i[u]];return a.join("")}s(xl,"computeHMACSignatureAsync");var co=new Array(256);for(let t=0;t<co.length;t++)co[t]=t.toString(16).padStart(2,"0");function W(t,e){if(!De(t))throw new y(`Options on policy '${e}' is expected to be an object. Received the type '${typeof t}'.`);let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new y(`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 y(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new y(`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 y(`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 y(`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(W,"optionValidator");var nt=class extends pe{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Ps(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a}return n.log.error("Error validating stripe webhook",i),S.badRequest(e,n,{title:"Webhook Error",detail:i})}return e}};function Es(t){return t!==null&&typeof t=="object"&&"id"in t&&se(t.id)&&"type"in t&&se(t.type)}s(Es,"isStripeWebhookEvent");var xn=class extends Ee{static{s(this,"MeteringPlugin")}};var vl={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new L(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new L(i)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(i,o),new L(i)}return o}},vn=vl;var lo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function Is({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=x.instance,c=new URL(`/v1/buckets/${t}/consumers`,lo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),p={name:l,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(p)}),g=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw a.log.error(m,g),new L(m)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}s(Is,"createConsumer");async function xs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=x.instance,u=new URL(`/v1/buckets/${t}/consumers`,lo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},p=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),d=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw i.log.error(g,d),new L(g)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}s(xs,"createConsumerInvite");async function vs({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=x.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,lo);o.searchParams.set("with-api-key","true");let i=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error deleting API Key Consumer";throw n.log.error(u,a),new L(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}s(vs,"deleteConsumer");async function Ts({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:p}=x.instance;if(!Ge(l))throw new q("No Zuplo JWT token set.");let d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!d.ok){let g="Error creating metering subscription.",m;try{m=await d.json()}catch{m={status:d.status,statusText:d.statusText}}throw t.log.error(g,m),new L(g)}t.log.info("Successfully created/updated metering subscription.",c)}s(Ts,"createSubscription");async function Tt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=x.instance;if(!Ge(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new L(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}s(Tt,"updateSubscription");async function St({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=x.instance;if(!Ge(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new L(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new L(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new L(c)}return u.data[0]}s(St,"getSubscription");function Tn(t){return t.replaceAll("_","-")}s(Tn,"stripeStatusToMeteringStatus");async function po(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),S.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=i.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await Is({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await vn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),S.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await xs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return S.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=Tn(n.data.object.status);await Ts({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await vs({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),S.internalServerError(t,e,{detail:l.message})}return S.ok(t,e)}s(po,"onCustomerSubscriptionCreated");async function go(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await Tt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),S.ok(t,e)}s(go,"onCustomerSubscriptionDeleted");async function mo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),S.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=Tn(n.data.object.status);return await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),S.ok(t,e)}if(a.plan&&a.plan.product!==n.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,p=(await vn.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(g=>g.proration&&g.price.product===c),d=0;return p.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):d=parseFloat(p[0].unit_amount_excluding_tax)/p[0].price.unit_amount,await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:d}}),S.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),S.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}s(mo,"onCustomerSubscriptionUpdated");var fo=class extends xn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:p,apiKeyBucketName:d}=this.options;if(!p)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)p=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!d)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!x.instance.build.ACCOUNT_NAME)throw new q("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.meteringBucketRegion??"us-central1";if(!Tl(g))throw new y(`StripeMeteringPlugin - The value '${g}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!Es(m))return S.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`),m.type){case"customer.subscription.created":return await po(c,l,m,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await mo(c,l,m,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await go(c,l,m,{meteringBucketId:p});default:return S.badRequest(c,l,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=Ci({inboundPolicies:[new nt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),a=new J({processors:[ne,i],handler:o,gateway:r}),u=new G({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Tl(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(Tl,"isMetricsRegion");var Os=new WeakMap,Ss={},Sn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Os.set(e,n)}};async function Cs(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=We(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Os.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new L(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ze(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 p=a?.meterValue??n.meterValue;if(!p){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let d={customerId:c,meterApiName:l,meterValue:p,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},g=Ss[n.apiKey];if(!g){let m=n.apiKey,R=t.headers.get("zm-test-id")??"";g=new B("amberflo-ingest-meter",10,async w=>{try{let I=n.url??"https://app.amberflo.io/ingest",T=await fetch(I,{method:"POST",body:JSON.stringify(w),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":R}});T.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${T.status}: ${await T.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),Ss[m]=g}g.enqueue(d),e.waitUntil(g.waitUntilFlushed())}}),t}s(Cs,"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 As=new Map;async function X(t,e){let n,r=As.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await On(JSON.stringify({policyName:t,options:e}))}`,As.set(t,n)),n}s(X,"getPolicyCacheName");var Ls="key-metadata-cache-type";function Sl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(Sl,"getKeyValue");async function Cn(t,e,n,r){if(!n.bucketName)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`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 y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(I=>o.allowUnauthenticatedRequests?t:S.unauthorized(t,e,{detail:I}),"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=Sl(a,o);if(!u||u==="")return i("No key present");let c=await Ol(u),l=await X(r,o),p=new Y(l,e),d=await p.get(c);if(d&&d.isValid===!0)return t.user=d.user,t;if(d&&!d.isValid)return d.typeId!==Ls&&F.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${d.typeId}'`,d),i("Authorization Failed");let g={key:u},m=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(e)},`${x.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":x.instance.deploymentName??"unknown","User-Agent":x.instance.systemUserAgent},body:JSON.stringify(g)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let I=await m.text(),T=JSON.parse(I);e.log.error("Unexpected response from key service",T)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let R=await m.json(),w={isValid:!0,typeId:Ls,user:{sub:R.name,data:R.metadata}};return t.user=w.user,p.put(c,w,o.cacheTtlSeconds),t}s(Cn,"ApiKeyInboundPolicy");async function Ol(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(Ol,"hashValue");var _s=Cn;var Ot=require("jose");var ho={},Cl=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");ho[e.jwkUrl]||(ho[e.jwkUrl]=(0,Ot.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,Ot.jwtVerify)(t,ho[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Al=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,Ot.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ee=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(g=>S.unauthorized(t,e,{detail:g}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Cl:Al,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 g=o.substring(i.length);if(!g||g.length===0)return a("No bearer token on authorization header");try{return await u(g,n)}catch(m){let R=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${R.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let p=n.subPropertyName??"sub",d=l[p];return d?(t.user={sub:d,data:l},t):a(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Ns=s(async(t,e,n,r)=>ee(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var ks=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>S.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 p=atob(l).normalize(),d=p.indexOf(":");if(d===-1||/[\0-\x1F\x7F]/.test(p))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let g=p.substring(0,d),m=p.substring(d+1),R=n.accounts.find(w=>w.username===g&&w.password===m);return R||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 Ll=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function _l(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(_l,"digestMessage");var Nl=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[p,d]of t.headers.entries())n.includes(p)&&r.push({key:p.toLowerCase(),value:d});r.sort((p,d)=>p.key.localeCompare(d.key));let o=await _l(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 Ms(t,e,n,r){let o=await X(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Nl(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let p=n.statusCodes??[200,206,301,302,303,404,410],d=l.response.clone();if(!p.includes(d.status)||!a.includes(t.method.toUpperCase()))return;let g=n?.expirationSecondsTtl??60,m=new Response(d.body,d);Ll.forEach(R=>m.headers.delete(R)),m.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(i.put(u,m))}catch(p){e.log.error(`Error in caching-inbound-policy '${r}': "${p.message}"`,p)}}),t)}s(Ms,"CachingInboundPolicy");var Us=s(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new j(t,{method:n.method})},"ChangeMethodInboundPolicy");var Hs=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 j(t,{headers:o})},"ClearHeadersInboundPolicy");var Ds=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 Zs=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",ee(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var qs=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return ee(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 $s=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Q.instance,i=yt(n.policies,o?.routeData.policies);return Cr(i)(t,e)},"CompositeInboundPolicy");var Fs=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return S.unauthorized(t,e,{detail:"No authorization header"});let i=kl(o);if(!i)return S.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await X(r,n),u=new Y(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"}),p=await l.text();if(l.status===200)c=p,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${p}'`),S.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):S.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function kl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(kl,"getToken");var Bs=s(async(t,e,n,r)=>(W(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ee(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 js=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[p,d]of a)u[p]=d.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var rt="__unknown__",Vs=s(async(t,e,n,r)=>{let o={allow:{countries:it(n.allow?.countries,"allow.countries",r),regionCodes:it(n.allow?.regionCodes,"allow.regionCode",r),asns:it(n.allow?.asns,"allow.asOrganization",r)},block:{countries:it(n.block?.countries,"block.countries",r),regionCodes:it(n.block?.regionCodes,"block.regionCode",r),asns:it(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??rt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??rt,u=e.incomingRequestProperties.asn?.toString()??rt,c=o.ignoreUnknown&&i===rt,l=o.ignoreUnknown&&a===rt,p=o.ignoreUnknown&&u===rt,d=o.allow.countries,g=o.allow.regionCodes,m=o.allow.asns;if(d.length>0&&!d.includes(i)&&!c||g.length>0&&!g.includes(a)&&!l||m.length>0&&!m.includes(u)&&!p)return ot(t,e,r,i,a,u);let R=o.block.countries,w=o.block.regionCodes,I=o.block.asns;return R.length>0&&R.includes(i)&&!c||w.length>0&&w.includes(a)&&!l||I.length>0&&I.includes(u)&&!p?ot(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function ot(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),S.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(ot,"blockedResponse");function it(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 y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(it,"toLowerStringArray");var zs=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 Ws=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return yo(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 yo(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 p=o[u].content[l].examples;p&&Object.keys(p).forEach(g=>{a.push({responseName:u,contentName:l,exampleName:g,exampleValue:p[g]})})})}),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 Gs(a[u])}else return a.length>0?Gs(a[0]):yo(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 Gs(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(Gs,"generateResponse");var yo=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return S.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Ml="Incoming",Ul={logRequestBody:!0,logResponseBody:!0};function Js(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Js,"headersToObject");function Ks(){return new Date().toISOString()}s(Ks,"timestamp");var bo=new WeakMap,Hl={};function Xs(t,e){let n=bo.get(t);n||(n=Hl);let r=Object.assign({...n},e);bo.set(t,r)}s(Xs,"setMoesifContext");async function Ys(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(Ys,"readBody");var Dl={},wo;function Qs(){if(!wo)throw new L("Invalid State - no _lastLogger");return wo}s(Qs,"getLastLogger");function Zl(t){let e=Dl[t];return e||(e=new B("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Qs().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||Qs().error({status:o.status,body:await o.text()})})),e}s(Zl,"getDispatcher");async function ea(t,e,n,r){wo=e.log;let o=Ks(),i=Object.assign(Ul,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Ys(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Zl(i.applicationId),p=t.headers.get("true-client-ip"),d=bo.get(e)??{},g={time:o,uri:t.url,verb:t.method,body:a,ip_address:p??void 0,api_version:d.apiVersion,headers:Js(t.headers)},m=i.logResponseBody?await Ys(u,e):void 0,R={time:Ks(),status:u.status,headers:Js(u.headers),body:m},w={request:g,response:R,user_id:d.userId??c.user?.sub,session_token:d.sessionToken,company_id:d.companyId,metadata:d.metadata,direction:Ml};l.enqueue(w),e.waitUntil(l.waitUntilFlushed())}),t}s(ea,"MoesifInboundPolicy");async function ta(t,e,n,r){let o=F.getLogger(t),{authApiJWT:i,meteringServiceUrl:a}=x.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let p=await l.json(),d=p.detail??p.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${d}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${d}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}s(ta,"loadSubscription");async function na(t,e,n,r,o){let{authApiJWT:i,meteringServiceUrl:a}=x.instance,u=F.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),p=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${p}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${p}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}s(na,"consumeSubcriptionQuotas");var ql=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function An(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}s(An,"validateMeters");function ra(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=qe(t),r=[];for(let o of n)ql.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}s(ra,"parseAllowedSubscriptionStatuses");var Ln=class extends pe{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,lt)}static setMeters(e,n){An(n,"setMeters"),le.set(e,_t,n)}async handler(e,n){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-299");let r=this.options.allowRequestsOverQuota??!1,o=We(this.options.meterOnStatusCodes),i=le.get(n,_t),a={...this.options.meters,...i};An(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ra(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(w,I,T)=>{let f=le.get(T,lt);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){T.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let A=le.get(T,_t),Z={...this.options.meters,...A};An(Z,this.policyName),o.includes(w.status)&&f&&Z&&(T.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(Z)} on response status '${w.status}'`),await na(T,f.id,this.policyName,this.options.bucketId,Z))});let l=e.user;if(!l)return u?e:S.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:p}=l,d=await ta(n,p,this.policyName,this.options.bucketId);if(!d)return n.log.warn("No valid subscription found"),u?e:S.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(d.status)&&!u)return n.log.warn(`Subscription '${d.id}' has status '${d.status}' which is not part of the allowed statuses.`),S.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(d.status)&&(n.log.debug(`Loading subscription '${d.id}' for user sub '${p}' to ContextData`),le.set(n,lt,d));let g=le.get(n,lt);if(!g)return u?e:(n.log.warn("Subscription is not available for user"),S.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(g&&Object.keys(g.meters).length===0)return n.log.error(`Quota is not set up for subscription '${g.id}'`),S.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let R=Object.keys(a).filter(w=>!Object.keys(g.meters).includes(w));if(R.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${R.join(", ")}`),S.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${R.join(", ")}`,title:"Quota Exceeded"});for(let w of Object.keys(a))if(g.meters[w].consumed<=0&&!r)return S.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${w}'`,title:"Quota Exceeded"});return e}};var oa=s(async(t,e,n,r)=>ee(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var ia=require("jose");var Ro,sa=s(async(t,e,n,r)=>{if(!Ro)try{Ro=await(0,ia.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ee(t,e,{issuer:n.authUrl,secret:Ro,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ua=ke(Ue());var _n=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Po=class extends _n{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Eo=class extends _n{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function $l(t,e){if(Ii(t))throw new Po(e)}s($l,"throwIfUndefinedOrNull");function Ct(t,e){if($l(t,e),!se(t))throw new Eo(e,"string")}s(Ct,"throwIfNotString");var Nn=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 Ct(e,"redisClientUrl"),Ct(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}){Ct(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 q("Redis client failed with 401: Unauthorized"):new q(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},kn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Ct(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 q("The in-memory redis client only supports /rate-limit calls")}};var Mn=(0,ua.debug)("zuplo:policies:RateLimitInboundPolicy"),Fl="strict",Bl=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"),jl=s(async t=>({key:`ip-${Bl(t)}`}),"getIP"),Vl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),zl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Un;function Gl(t,e){let n;if(Un)return Un;if(x.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new kn,Un=n,n;let{authApiJWT:r,redisURL:o}=x.instance;if(!se(o))throw new q(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!se(r))throw new q(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=Nn.initialize(o,r,x.instance.deploymentName??"unknown",x.instance.systemUserAgent)),!n||!n.isEnabled())throw new q(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Un=n,n}s(Gl,"getRedisClient");async function aa(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(aa,"getCountAndUpdateExpiry");function Wl(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`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 y(`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 L(c)}return u},"outerFunction")}s(Wl,"wrapUserFunction");var Jl="Retry-After",Io=s(async(t,e,n,r)=>{let o=Date.now(),i=F.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new q(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let p={};return(!c||c==="retry-after")&&(p[Jl]=l.toString()),S.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let l={function:Wl(n,r),user:Vl,ip:jl,all:zl}[n.rateLimitBy],p=await l(t,e,r),d=p.key,g=p.requestsAllowed??n.requestsAllowed,m=p.timeWindowMinutes??n.timeWindowMinutes,R=n.headerMode??"retry-after",w=Gl(r,i),T=`bucket/${x.instance.build.BUILD_ID}/${r}/${d}`;if((n.mode??Fl)==="async"){let A=await X(r,n),Z=new ve(A,{logger:F.getLogger(e)}),h=aa(T,m,w,i,e.requestId),b=await Z.get(T);if(b!==void 0&&b<=Date.now()){Mn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${T}' (async mode)`);let O=Math.round((b-Date.now())/1e3);return u(R,O)}return e.addEventListener("responseSending",O=>{try{let k=O,C=k.mutableResponse;k.mutableResponse=(async()=>{let _=await h;if(_.count>g){let $=Date.now()+_.ttlSeconds*1e3,M=Z.put(T,$,_.ttlSeconds).catch(N=>{throw i.error(new q("Error caching rate limit result.",{cause:N})),N});return e.waitUntil(M),Mn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${T}' (async mode)`),u(R,_.ttlSeconds)}return C})()}catch(k){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,k)}}),t}let E=await aa(T,m,w,i,e.requestId);return E.count>g?(Mn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${T}' (strict mode)`),u(R,E.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;Mn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var xo;function ca(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(ca,"headersToNameValuePairs");function Kl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Kl,"queryToNameValueParis");function Yl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Yl,"parseIntOrUndefined");var la={};async function da(t,e,n,r){let o=new Date,i=Date.now();return xo||(xo={name:"zuplo",version:x.instance.build.ZUPLO_VERSION,comment:`zuplo/${x.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ze(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ze(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:x.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:xo,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:ca(t.headers),queryString:Kl(t.query)},response:{status:a.status,statusText:a.statusText,headers:ca(a.headers),content:{size:Yl(t.headers.get("content-length"))}}}]}}},p=la[n.apiKey];if(!p){let d=n.apiKey;p=new B("readme-metering-inbound-policy",10,async g=>{try{let m=n.url??"https://metrics.readme.io/request",R=await fetch(m,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(d+":")}`}});R.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${R.status}: '${await R.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),la[d]=p}p.enqueue(l),e.waitUntil(p.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(da,"ReadmeMetricsInboundPolicy");var pa=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`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 j(t,{headers:i})},"RemoveHeadersInboundPolicy");var ga=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new y(`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 ma=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`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 j(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var fa=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 ha=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ya=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?ha():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ha():t},"RequestSizeLimitInboundPolicy");function ba(t,e,n){return`_${Ne(t+"_"+e+"_"+n)}`}s(ba,"getRawOperationDataIdentifierName");function Hn(t,e,n,r){return`_${Ne(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(Hn,"getIdForParameterSchema");function Dn(t,e,n){return`_${Ne(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ne(n.toLowerCase())}`}s(Dn,"getIdForRequestBodySchema");function wa(t,e){return`_${Ne(t)}__${Ne(e)}`}s(wa,"getIdForRefSchema");function Ne(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(Ne,"sanitizedIdentifierName");var st=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"),at=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let p=Hn(n,r,o,c.name),d=Q.instance.schemaValidator[p],g=d(e[c.name]),m=vo(d.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),me=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),fe=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),he=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),vo=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 Ra(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let R=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=S.badRequest(e,t,{detail:`${R}, see errors property for more details`,errors:`${m}`});if(fe(n.validateBody)&&me(t,n.logLevel??"info",R,[r],m),he(n.validateBody))return w}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,R=S.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?R:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Dn(t.route.path,e.method,o),u=Q.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")}`,R=S.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?R:void 0}if(u(r))return;let l=u.errors,p="Request body did not pass validation",d=vo(l),g=S.badRequest(e,t,{detail:`${p}, see errors property for more details`,errors:d});if(fe(n.validateBody)&&me(t,n.logLevel??"info",p,[r],d),he(n.validateBody))return g}s(Ra,"handleBodyValidation");function Pa(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=st(t),i=at(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=S.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(fe(n.validateHeaders)&&me(t,n.logLevel??"info",a,i.invalidValues,i.errors),he(n.validateHeaders))return u}}s(Pa,"handleHeadersValidation");function Ea(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=st(t),o=at(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=S.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(fe(n.validatePathParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),he(n.validatePathParameters))return a}}s(Ea,"handlePathParameterValidation");function Ia(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=st(t),o=at(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=S.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(fe(n.validateQueryParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),he(n.validateQueryParameters))return a}}s(Ia,"handleQueryParameterValidation");var To=s(async(t,e,n)=>{let r=Ia(e,t,n);if(r!==void 0||(r=Ea(e,t,n),r!==void 0)||(r=Pa(e,t,n),r!==void 0))return r;let o=await Ra(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),xa=To;var va=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`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 S.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Ta=s(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var Sa=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`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 y(`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 j(t,{headers:i})},"SetHeadersInboundPolicy");var Oa=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new y(`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 y(`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 Ca=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`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 y(`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 j(i.toString(),t)},"SetQueryParamsInboundPolicy");var Aa=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 Ql=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),La=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Ql(n.sleepInMs),t},"SleepInboundPolicy");var _a=s(async(t,e,n,r)=>{W(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await ee(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof j))throw new q("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 L(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(p=>{let d=a[p];Array.isArray(d)?d.includes(u[p])||l.push(p):d!==u[p]&&l.push(p)}),l.length>0?S.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Na=s(async(t,e,n,r)=>{W(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await X(r,n),i=new Y(o,e),a=await i.get(r);if(!a){let u=await Xl(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 Xl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({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 L("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 L("Response returned from Azure AD is not in the expected format.")}s(Xl,"getAccessToken");var ka="https://accounts.google.com/o/oauth2/token",So,Ma=s(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string"),So||(So=await ae.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 X(r,n),a=new Y(i,e),u=await a.get(r);if(!u){let c=await we({serviceAccount:So,audience:ka,payload:o}),l=await en(ka,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("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 ed="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",td=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Oo,Ua=s(async(t,e,n,r)=>{if(W(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let d in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,d)){if(td.indexOf(d)!==-1)throw new y(`Developer claim "${d}" is reserved and cannot be specified.`);o[d]=n.developerClaims[d]}}Oo||(Oo=await ae.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new L("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 L(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ze(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new L(`Unable to determine user from for the policy ${r}`);let a=await X(r,n),u=new Y(a,e),c={uid:i,claims:o},l=await On(JSON.stringify(c)),p=await u.get(l);if(!p){let d=await we({serviceAccount:Oo,audience:ed,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await qi(g,d,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new L("Invalid token response from Firebase");p=m.idToken,u.put(l,p,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${p}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Co,Ha=s(async(t,e,n,r)=>{W(n,r).required("audience","string").required("serviceAccountJson","string"),Co||(Co=await ae.init(n.serviceAccountJson));let o=await we({serviceAccount:Co,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Da="https://www.googleapis.com/oauth2/v4/token",Ao,Za=s(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ao||(Ao=await ae.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=qe(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let i=await X(r,n),a;n.useMemoryCacheOnly?a=new Be(i):a=new Y(i,e);let u=await a.get(r);if(!u){let c=await we({serviceAccount:Ao,audience:Da,payload:o}),l=await en(Da,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var qa=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return S.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 q("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 S.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ja=ke(Ba());var Zn=class extends Ie{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?We(e.parseOnStatusCodes):void 0,this.parser=new ja.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,n,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new L(c)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var qn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new q(`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 _o=["sha-1","sha-256","sha-384","sha-512"],$n=class{static{s(this,"BaseCryptoBeta")}};var Fn=class extends $n{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!_o.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${_o.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 Bn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var jn=class extends Bn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new At("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new y("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)}};
|
|
78
78
|
/*! For license information please see index.minified.js.LEGAL.txt */
|