@zuplo/runtime 6.40.38 → 6.40.40
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/out/esm/index.js +1 -1
- package/out/types/index.d.ts +10 -2
- package/package.json +1 -1
package/out/esm/index.js
CHANGED
|
@@ -78,7 +78,7 @@ Signature verification is impossible without access to the original signed mater
|
|
|
78
78
|
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.
|
|
79
79
|
`+l+`
|
|
80
80
|
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Me(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i($l,"validateComputedSignature");function Hl(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}i(Hl,"parseHeader");function Zl(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Zl,"secureCompare");async function Fl(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Qo[s[u]];return a.join("")}i(Fl,"computeHMACSignatureAsync");var Qo=new Array(256);for(let n=0;n<Qo.length;n++)Qo[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",r){let o=`${t} '${e}'`;if(!ot(n))throw new g(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],m=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new g(`Value of '${m}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new g(`Value of '${m}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new g(`Value of '${m}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new g(`Value of '${m}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new g(`Value of '${m}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var rn=class extends ae{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){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 Ta(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function Aa(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(Aa,"isStripeWebhookEvent");var jl={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await z.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new k(s)}return o},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await z.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new k(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await z.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new k(s)}return o},"getUpcomingInvoice")},Wn=jl;var Yo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Sa="My API Key";async function Ca({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=y.instance,c=new URL(`/v1/buckets/${n}/consumers`,Yo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Sa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,m),new k(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Ca,"createConsumer");async function va({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=y.instance,u=new URL(`/v1/buckets/${n}/consumers`,Yo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Sa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new k(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(va,"createConsumerInvite");async function Oa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=y.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,Yo);o.searchParams.set("with-api-key","true");let s=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Oa,"deleteConsumer");async function ka({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:m}=y.instance;if(!ft(p))throw new K("No Zuplo JWT token set.");let h=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${m}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!h.ok){let I=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,S="";try{b=await h.json(),S=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(I,b),new k(`${I} ${S}`)}n.log.info("Successfully created monetization subscription.",d)}i(ka,"createSubscription");async function Pt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=y.instance;if(!ft(o))throw new K("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(Pt,"updateSubscription");async function It({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=y.instance;if(!ft(o))throw new K("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}i(It,"getSubscription");var ue="Skipping since we're unable to process the webhook event.",Xe="Successfully processed the webhook event",Ie="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Jn(n){return n.replaceAll("_","-")}i(Jn,"stripeStatusToMeteringStatus");function at(n){return new Date(n*1e3).toISOString()}i(at,"unixTimestampToISOString");async function Xo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:ue,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ue,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await Ca({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Wn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),x.ok(n,e,{title:ue,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await va({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:ue,detail:p.message})}if(!c)return x.ok(n,e,{title:ue,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Jn(t.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}});let h;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(h={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:at(t.data.object.trial_end),trialStartDate:at(t.data.object.trial_start)}),await ka({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:h})}catch(p){return await Oa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:ue,detail:p.message})}return x.ok(n,e,{title:Xe})}i(Xo,"onCustomerSubscriptionCreated");async function ei(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ue,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});try{let a=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await Pt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:ue,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ie})}return x.ok(n,e,{title:Xe})}i(ei,"onCustomerSubscriptionDeleted");async function ti(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),x.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ue,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Jn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=at(t.data.object.trial_end)),await Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:ue,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return x.ok(n,e,{title:Xe})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Wn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:ue,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return x.ok(n,e,{title:Xe})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?at(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?at(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:ue,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return x.ok(n,e,{title:Xe})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:ue,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ie})}i(ti,"onCustomerSubscriptionUpdated");var La=class extends En{constructor(t){super();this.options=t;f("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(fe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=fe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(fe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=fe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!zl(m))throw new g(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!Aa(h))return x.ok(c,l,{title:ue,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ie});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await Xo(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await ti(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await ei(c,l,h,{meteringBucketId:d});default:return x.ok(c,l,{title:ue,detail:`Event '${h.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie})}},"stripeWebhookHandler"),s=zs({inboundPolicies:[new rn({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new ge({processors:[Re,s],handler:o,gateway:r}),u=new de({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function zl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(zl,"isMetricsRegion");var Na=new WeakMap,_a={},ni=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Na.set(e,t)}};async function Bl(n,e,t,r){if(f("policy.inbound.amberflo-metering"),!t.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Ve(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Na.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=$e(n.user,t.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??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},m=_a[t.apiKey];if(!m){let h=t.apiKey,I=n.headers.get("zm-test-id")??"";m=new Y("amberflo-ingest-meter",10,async b=>{try{let S=t.url??"https://app.amberflo.io/ingest",L=await z.fetch(S,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":I}});L.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${L.status}: ${await L.text()}`)}catch(S){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${S.message}`),S}}),_a[h]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}i(Bl,"AmberfloMeteringInboundPolicy");async function ut(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(ut,"sha256");var Da=new Map;async function se(n,e,t){let r,o=`${n}-${e}`,s=Da.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ut(JSON.stringify({policyName:n,options:t}))}`,Da.set(n,r)),r}i(se,"getPolicyCacheName");var Ma="key-metadata-cache-type";function Gl(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Gl,"getKeyValue");async function ri(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(fe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=fe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(L=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:L}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Gl(a,o);if(!u||u==="")return s("No key present");let c=await Vl(u),l=await se(r,void 0,o),d=new oe(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Ma&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},h=new Headers({"content-type":"application/json"});_e(h,e.requestId);let I=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:h,body:JSON.stringify(m)});if(I.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(I.status!==200){try{let L=await I.text(),C=JSON.parse(L);e.log.error("Unexpected response from key service",C)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${I.status}`)}let b=await I.json(),S={isValid:!0,typeId:Ma,user:{apiKeyId:b.id,sub:b.name,data:b.metadata}};return n.user=S.user,d.put(c,S,o.cacheTtlSeconds),n}i(ri,"ApiKeyInboundPolicy");async function Vl(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Vl,"hashValue");var Wl=ri;var qa=Symbol("aserto-authz-resource-context"),oi=class extends ae{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){te.set(e,qa,t)}constructor(e,t){if(super(e,t),W(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new g(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let c=await se(this.policyName,void 0,this.options);this.cache=new oe(c,t)}let r=i(c=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:c}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),x.unauthorized(e,t);let o=te.get(t,qa),s;o?.policyInstance?s=o.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?$e(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:o?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:o?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:o?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await z.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?r(d):x.internalServerError(e,t)}let l=await c.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),r("The request was not authorized."))}catch(c){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),x.internalServerError(e,t)}}};var Ua=new Map;function Jl(n){let e=[],t=0;for(;t<n.length;){if(n[t]==="."){t++;continue}if(n[t]==="["){for(t++;t<n.length&&/\s/.test(n[t]);)t++;let r=n[t];if(r!=='"'&&r!=="'"){for(;t<n.length&&n[t]!=="]";)t++;t++;continue}t++;let o=t;for(;t<n.length&&n[t]!==r;)t++;let s=n.substring(o,t);for(e.push(s),t++;t<n.length&&/\s/.test(n[t]);)t++;n[t]==="]"&&t++}else{let r=t;for(;t<n.length&&n[t]!=="."&&n[t]!=="[";)t++;let o=n.substring(r,t).trim();o.length>0&&e.push(o)}}return e}i(Jl,"parsePropertyPath");function Kn(n,e){let t="$authzen-prop(";if(!n.startsWith(t)||!n.endsWith(")"))return n;let r=n.slice(t.length,-1),o=Ua.get(r);o||(o=Jl(r),Ua.set(r,o));let s=e;for(let a of o){if(s==null)return;typeof s.get=="function"?s=s.get(a):s=s[a]}return s}i(Kn,"evaluateAuthzenProp");var $a=Symbol("AUTHZEN_CONTEXT_DATA_52a5cf22-d922-4673-9815-6dc3d49071d9"),ii=class n extends ae{static{i(this,"AuthZenInboundPolicy")}#e;#t;constructor(e,t){if(super(e,t),W(e,t).required("authorizerHostname","string").optional("authorizerAuthorizationHeader","string").optional("subject","object").optional("resource","object").optional("action","string").optional("throwOnError","boolean"),e.subject&&!e.subject.type)throw new g(`${this.policyType} '${this.policyName}' - subject.type is required.`);if(e.subject&&!e.subject.id)throw new g(`${this.policyType} '${this.policyName}' - subject.id is required.`);if(e.resource&&!e.resource.type)throw new g(`${this.policyType} '${this.policyName}' - resource.type is required.`);if(e.resource&&!e.resource.id)throw new g(`${this.policyType} '${this.policyName}' - resource.id is required.`);this.#e=(e.authorizerHostname.startsWith("https://")?e.authorizerHostname:`https://${e.authorizerHostname}`)+"/access/v1/evaluation";try{new URL(this.#e)}catch(r){throw new g(`${this.policyType} '${this.policyName}' - authorizerUrl '${this.#e}' is not valid
|
|
81
|
-
${r}`)}}async handler(e,t){try{await this.#o(t);let r=this.options.debug===!0,o={subject:Object.assign({},this.options.subject),resource:Object.assign({},this.options.resource),action:this.options.action},s={request:e,context:t};o.action!==void 0&&(o.action=Kn(o.action,s)),o.subject?.id!==void 0&&(o.subject.id=Kn(o.subject.id,s)),o.resource?.id!==void 0&&(o.resource.id=Kn(o.resource.id,s)),r&&t.log.debug(`${this.policyType} '${this.policyName}' - Evaluated payload from options`,o);let a=n.getAuthorizationPayload(t);a&&Object.assign(o,a),r&&t.log.debug(`${this.policyType} '${this.policyName}' - Using context payload to override working payload`,{contextPayload:a,final:o}),this.#n(t,!o.subject?.type||!o.subject?.id,"Missing required subject type or id"),this.#n(t,!o.resource?.type||!o.resource?.id,"Missing required resource type or id"),this.#n(t,!o.action,"Missing required action");let u={"content-type":"application/json"};this.options.authorizerAuthorizationHeader&&(u.authorization=this.options.authorizerAuthorizationHeader);let c=await fetch(this.#e,{method:"POST",body:JSON.stringify(o),headers:u});if(!c.ok){let d=`${this.policyType} '${this.policyName}' - Unexpected response from PDP: ${c.status} - ${c.statusText}:
|
|
81
|
+
${r}`)}}async handler(e,t){try{await this.#o(t);let r=this.options.debug===!0,o={subject:Object.assign({},this.options.subject),resource:Object.assign({},this.options.resource),action:Object.assign({},this.options.action)},s={request:e,context:t};o.action?.name!==void 0&&(o.action.name=Kn(o.action.name,s)),o.subject?.id!==void 0&&(o.subject.id=Kn(o.subject.id,s)),o.resource?.id!==void 0&&(o.resource.id=Kn(o.resource.id,s)),r&&t.log.debug(`${this.policyType} '${this.policyName}' - Evaluated payload from options`,o);let a=n.getAuthorizationPayload(t);a&&Object.assign(o,a),r&&t.log.debug(`${this.policyType} '${this.policyName}' - Using context payload to override working payload`,{contextPayload:a,final:o}),this.#n(t,!o.subject?.type||!o.subject?.id,"Missing required subject type or id"),this.#n(t,!o.resource?.type||!o.resource?.id,"Missing required resource type or id"),this.#n(t,!o.action,"Missing required action");let u={"content-type":"application/json"};this.options.authorizerAuthorizationHeader&&(u.authorization=this.options.authorizerAuthorizationHeader);let c=await fetch(this.#e,{method:"POST",body:JSON.stringify(o),headers:u});if(!c.ok){let d=`${this.policyType} '${this.policyName}' - Unexpected response from PDP: ${c.status} - ${c.statusText}:
|
|
82
82
|
${await c.text()}`;if(this.options.throwOnError)throw new Error(d);t.log.error(d)}let l=await c.json();if(r&&t.log.debug(`${this.policyType} '${this.policyName}' - PDP response`,l),l.decision!==!0)return this.#r(e,t,l.reason)}catch(r){if(this.options.throwOnError)throw r;t.log.error(`${this.policyType} '${this.policyName}' - Error in policy: ${r}`)}return e}#n(e,t,r){if(t){let o=`${this.policyType} '${this.policyName}' - ${r}`;if(this.options.throwOnError)throw new g(o);e.log.warn(o)}}async#r(e,t,r){return x.forbidden(e,t,{detail:r})}async#o(e){if(!this.#t){let t=await se(this.policyName,void 0,this.options);this.#t=new oe(t,e)}}static setAuthorizationPayload(e,t){te.set(e,$a,t)}static getAuthorizationPayload(e){return te.get(e,$a)}};import{createRemoteJWKSet as Ql,jwtVerify as Za}from"jose";import{createLocalJWKSet as Kl}from"jose";var si=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof ai&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",y.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Kl(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await z.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new ui("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Et("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new Et("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ha(n,e,t){let r=new si(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Ha,"createRemoteJWKSet");var Et=class extends k{static{i(this,"JWKSError")}},ai=class extends Et{static{i(this,"JWKSNoMatchingKey")}},ui=class extends Et{static{i(this,"JWKSTimeout")}};var Qn={},Yl=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");if(!Qn[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await se(n,void 0,r),u=new oe(a,e);Qn[r.jwkUrl]=Ha(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else Qn[r.jwkUrl]=Ql(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await Za(t,Qn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Xl=i(async(n,e)=>{let t;if(e.secret===void 0)throw new g("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await Za(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Pe=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=t.authHeader??"Authorization",s=n.headers.get(o),a="bearer ",u=i(h=>x.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?Yl(r,e):Xl,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let h=s.substring(a.length);if(!h||h.length===0)return u("No bearer token on authorization header");try{return await c(h,t)}catch(I){let b=new URL(n.url);return"code"in I&&I.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,I):e.log.warn(`Invalid token on: ${n.method} ${b.pathname}`,I),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",m=d[p];return m?(n.user={sub:m,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var ed=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),Pe(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var Yn=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await z.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var ci=class n extends ae{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Yn(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var td=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),h=d.substring(p+1),I=t.accounts.find(b=>b.username===m&&b.password===h);return I||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Xn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(Xn,"extractDateElements");function Fa(n,e){return new Date(n,e+1,0).getDate()}i(Fa,"getDaysInMonth");function li(n,e){return n<=e?e-n:6-n+e+1}i(li,"getDaysBetweenWeekdays");var er=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let s=Fa(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?li(d,p):li(p,d);l=e==="next"?o+m:o-m,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Xn(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("next",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=Xn(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("prev",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:s,month:a,weekday:u}=Xn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var nd={min:0,max:59},rd={min:0,max:59},od={min:0,max:23},id={min:1,max:31},sd={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},ad={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},ud={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function ct(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{ct(d,e).forEach(m=>t.add(m))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(ct,"parseElement");function di(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=ud[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new er({seconds:ct(t,nd),minutes:ct(r,rd),hours:ct(o,od),days:ct(s,id),months:new Set(Array.from(ct(a,sd)).map(c=>c-1)),weekdays:new Set(Array.from(ct(u,ad)).map(c=>c%7))})}i(di,"parseCronExpression");var pi=class extends ae{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new g(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[di(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>di(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=x.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return x.format(s,e,t)}return e}};var cd=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function ld(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ld,"digestMessage");var dd=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await ld(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function pd(n,e,t,r){f("policy.inbound.caching");let o=await se(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await dd(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let m=t?.expirationSecondsTtl??60,h=new Response(p.body,p);cd.forEach(I=>h.headers.delete(I)),h.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(pd,"CachingInboundPolicy");var md=i(async(n,e,t,r)=>{if(f("policy.inbound.change-method"),!t.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new re(n,{method:t.method})},"ChangeMethodInboundPolicy");var gd=i(async(n,e,t)=>{f("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new re(n,{headers:o})},"ClearHeadersInboundPolicy");var fd=i(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var hd=i(async(n,e,t,r)=>{f("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",Pe(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var yd=i(async(n,e,t,r)=>{if(f("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return Pe(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var tr=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},mi=class extends tr{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},gi=class extends tr{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function bd(n,e){if(Ms(n))throw new mi(e)}i(bd,"throwIfUndefinedOrNull");function ja(n,e){if(bd(n,e),!xe(n))throw new gi(e,"string")}i(ja,"throwIfNotString");var fi=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),s=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},wd=500,hi=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:r,requestId:o}){ja(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},wd);let a,u=new Headers({"content-type":"application/json"});_e(u,o);try{a=await z.fetch(`${this.clientUrl}${e}`,{method:r,body:t,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new K("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await ut(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await ut(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},xt;function et(n,e){let{redisURL:t,authApiJWT:r}=y.instance;if(xt)return xt;if(!r)return e.info("Using in-memory rate limit client for local development."),xt=new fi,xt;if(!xe(t))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!xe(r))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return xt=new hi(t),xt}i(et,"getRateLimitClient");var Rd=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function Tt(n,e){return{function:xd(e,"RateLimitInboundPolicy",n),user:Id,ip:Pd,all:Ed}[e.rateLimitBy??"ip"]}i(Tt,"getRateLimitByFunctions");var Pd=i(async n=>({key:`ip-${Rd(n)}`}),"getIP"),Id=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Ed=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function xd(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new g(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(xd,"wrapUserFunction");var At="Retry-After";var za=be("zuplo:policies:ComplexRateLimitInboundPolicy"),yi=Symbol("complex-rate-limit-counters"),bi=class n extends ae{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=te.get(e,yi)??{};Object.assign(r,t),te.set(e,yi,t)}static getIncrements(e){return te.get(e,yi)??{}}constructor(e,t){super(e,t),f("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new g(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=Q.getLogger(t),s=et(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[At]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await Tt(this.policyName,this.options)(e,t,this.policyName),d=y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),m=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let S=n.getIncrements(t);za(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(S)}`);let L=Object.entries(p).map(([H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${H}`,ttlSeconds:m,increment:S[H]??0})),C=s.multiIncrement(L,t.requestId);t.waitUntil(C),await C}catch(S){o.error(S),t.log.error(S)}});let h=Object.entries(p).map(([S,L])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${S}`,ttlSeconds:m,limit:L})),I=await s.multiCount(h,t.requestId);return Td(I,h).length>0?u(this.options.headerMode??"retry-after",m):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;za(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Td(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(Td,"findOverLimits");var Ad=i(async(n,e,t,r)=>{if(f("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=he.instance,s=Vt(t.policies,o?.routeData.policies);return oo(s)(n,e)},"CompositeInboundPolicy");var Sd=i(async(n,e,t,r,o)=>{if(f("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new g(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let s=he.instance,a=Wt(r.policies,s?.routeData.policies);return io(a)(n,e,t)},"CompositeOutboundPolicy");var Cd=i(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=vd(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await se(r,void 0,t),u=new oe(a,e),c=await u.get(s);if(!c){let l=await z.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function vd(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(vd,"getToken");var Od=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),W(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Pe(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var kd=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new re(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var St="__unknown__",Ld=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:vt(t.allow?.countries,"allow.countries",r),regionCodes:vt(t.allow?.regionCodes,"allow.regionCode",r),asns:vt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:vt(t.block?.countries,"block.countries",r),regionCodes:vt(t.block?.regionCodes,"block.regionCode",r),asns:vt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??St,a=e.incomingRequestProperties.regionCode?.toLowerCase()??St,u=e.incomingRequestProperties.asn?.toString()??St,c=o.ignoreUnknown&&s===St,l=o.ignoreUnknown&&a===St,d=o.ignoreUnknown&&u===St,p=o.allow.countries,m=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return Ct(n,e,r,s,a,u);let I=o.block.countries,b=o.block.regionCodes,S=o.block.asns;return I.length>0&&I.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||S.length>0&&S.includes(u)&&!d?Ct(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Ct(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Ct,"blockedResponse");function vt(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new g(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(vt,"toLowerStringArray");var _d=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Nd=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return wi(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return wi(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ba(a[u])}else return a.length>0?Ba(a[0]):wi(r,n,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 Ba(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(Ba,"generateResponse");var wi=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var Dd="Incoming",Md={logRequestBody:!0,logResponseBody:!0};function Ga(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(Ga,"headersToObject");function Va(){return new Date().toISOString()}i(Va,"timestamp");var Ri=new WeakMap,qd={};function Ud(n,e){let t=Ri.get(n);t||(t=qd);let r=Object.assign({...t},e);Ri.set(n,r)}i(Ud,"setMoesifContext");async function Wa(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}i(Wa,"readBody");var $d={},Pi;function Ja(){if(!Pi)throw new k("Invalid State - no _lastLogger");return Pi}i(Ja,"getLastLogger");function Hd(n){let e=$d[n];return e||(e=new Y("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Ja().debug("posting",r);let o=await z.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Ja().error({status:o.status,body:await o.text()})})),e}i(Hd,"getDispatcher");async function Zd(n,e,t,r){f("policy.inbound.moesif-analytics"),Pi=e.log;let o=Va(),s=Object.assign(Md,t);if(!s.applicationId)throw new g(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Wa(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Hd(s.applicationId),d=n.headers.get("true-client-ip"),p=Ri.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ga(n.headers)},h=s.logResponseBody?await Wa(u,e):void 0,I={time:Va(),status:u.status,headers:Ga(u.headers),body:h},b={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Dd};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}i(Zd,"MoesifInboundPolicy");async function Ka(n,e,t,r){let o=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=y.instance,u;try{let l=await z.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Ka,"loadSubscription");async function Qa(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=y.instance,u=Q.getLogger(n);try{let c=await z.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(Qa,"consumeSubcriptionQuotas");var Fd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function nr(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new g(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof g?new g(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(nr,"validateMeters");function Ya(n,e){if(n)try{if(n.length===0)throw new g("Must set valid subscription statuses");let t=it(n),r=[];for(let o of t)Fd.has(o)||r.push(o);if(r.length>0)throw new g(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof g?new g(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Ya,"parseAllowedSubscriptionStatuses");function Xa(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}i(Xa,"compareMeters");var Ii=class extends ae{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return te.get(e,Ht)}static setMeters(e,t){nr(t,"setMeters");let r=te.get(e,Zt)??{};Object.assign(r,t),te.set(e,Zt,r)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=Ve(this.options.meterOnStatusCodes),s=te.get(t,Zt),a={...this.options.meters,...s};nr(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Ya(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,S,L)=>{let C=te.get(L,Ht);if((this.options.allowRequestsWithoutSubscription??!1)&&!C){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(fe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=fe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let Z=te.get(L,Zt),q={...this.options.meters,...Z};if(nr(q,this.policyName),o.includes(b.status)&&C&&q){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${C.id}' with meters '${JSON.stringify(q)} on response status '${b.status}'`);let{metersInSubscription:v,metersNotInSubscription:$}=Xa(C.meters,q);if($&&Object.keys($).length>0){let V=Object.keys($);L.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await Qa(L,C.id,this.policyName,this.options.bucketId,v)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(fe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=fe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Ka(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),te.set(t,Ht,p));let m=te.get(t,Ht);if(!m)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(I.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};async function rr(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await we({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,s)}catch{}throw new k("Error getting token from identity provider.")}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 k("Response returned from identity provider is not in the expected format.")}i(rr,"getClientCredentialsAccessToken");var Ot=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},or=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new g("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",y.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await z.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Ot("unknown",`Unknown error. Status: ${c.status}`):new Ot(l.code,l.message)}return c.json()}};function on(n,e,t){!n[e]&&t&&(n[e]=t)}i(on,"setHeaderIfNotSet");var eu="X-OpenFGA-Client-Method",tu="X-OpenFGA-Client-Bulk-Request-Id",sn=class extends or{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return on(r,eu,"BatchCheck"),on(r,tu,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof Ot)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(on(c,eu,"ListRelations"),on(c,tu,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var nu=Symbol("openfga-authz-context-data"),kt=class extends ae{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];te.set(e,nu,r)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new g(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new g(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new sn({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await se(this.policyName,void 0,this.options);this.cache=new oe(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=te.get(t,nu);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new K(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let s=await rr({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var ru=["us1","eu1","au1"],Ei=class extends kt{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!ru.includes(e.region))throw new g(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${ru.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),f("policy.inbound.oktafga-authz")}};var jd=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),Pe(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var xi=class extends kt{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.openfga-authz")}};import{importSPKI as zd}from"jose";var Ti,Bd=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!Ti)try{Ti=await zd(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Pe(n,e,{issuer:t.authUrl,secret:Ti,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ai="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",ou="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var Si=class n extends ae{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=Q.getLogger(t);try{let s=Gd(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=Vd(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=et(this.policyName,o),m=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,m),r&&t.log.debug("QuotaInboundPolicy: quotaResult",m),c&&new Date(m.anchorDate).getTime()!==c.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${m.anchorDate}')`);let h=Object.assign({},s.defaultAllowances);Object.assign(h,l.allowances);let I=[],b="";if(Object.entries(h).forEach(([S,L])=>{r&&(b+=`${S} - allowed: ${L} value: ${m.meters[S]??0}
|
|
83
83
|
`),(m.meters[S]??0)>=L&&I.push(S)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",b),I.length>0)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${I.join(", ")}'`});t.addResponseSendingFinalHook(async(S,L,C)=>{if(r&&C.log.debug(`QuotaInboundPolicy: backend response - ${S.status}: ${S.statusText}`),!s.quotaOnStatusCodes.includes(S.status))return;let H=te.get(C,Ai),Z={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:H};r&&C.log.debug("QuotaInboundPolicy: setQuotaDetails",Z);let q=p.setQuota(d,Z,C.requestId);C.waitUntil(q)})}catch(s){o.error(s),t.log.error(s)}return e}static setMeters(e,t){let r=te.get(e,Ai)??{};Object.assign(r,t),te.set(e,Ai,r)}static getUsage(e,t){let r=te.get(e,`${ou}-${t}`);if(r===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return r}static#e(e,t,r){te.set(e,`${ou}-${t}`,r)}};function Gd(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),r=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);r=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:Ve(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}i(Gd,"validateAndParseOptions");function Vd(n,e){return encodeURIComponent(`${e}-${n}`)}i(Vd,"processKey");var iu=be("zuplo:policies:RateLimitInboundPolicy"),su=i(async(n,e,t,r)=>{let o=Q.getLogger(e),s=i((q,v)=>{let $={};return(!q||q==="retry-after")&&($[At]=v.toString()),x.tooManyRequests(n,e,void 0,$)},"rateLimited"),u=await Tt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",m=et(r,o),I=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${c}`,b=await se(r,void 0,t),S=new oe(b,e),L=m.getCountAndUpdateExpiry(I,d,e.requestId),C;i(async()=>{let q=await L;if(q.count>l){let v=Date.now()+q.ttlSeconds*1e3;S.put(I,v,q.ttlSeconds),iu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${I}' (async mode)`),C=s(p,q.ttlSeconds)}},"asyncCheck")();let Z=await S.get(I);if(Z!==void 0&&Z>Date.now()){iu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${I}' (async mode)`);let q=Math.round((Z-Date.now())/1e3);return s(p,q)}return e.addResponseSendingHook(async q=>C??q),n},"AsyncRateLimitInboundPolicyImpl");function Ci(n,e){if(n===null)throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: null`);if(n==="")throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: empty string`);if(typeof n=="number")return n;if(typeof n!="number"){let t=Number(n);if(isNaN(t)||!Number.isInteger(t))throw new Error(`RateLimitInboundPolicy - Invalid ${e} value not of type integer: ${n}`);return t}throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: ${n}`)}i(Ci,"convertToNumber");var au=be("zuplo:policies:RateLimitInboundPolicy"),Wd="strict",uu=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Wd)==="async")return su(n,e,t,r);let s=Date.now(),a=Q.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new K(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[At]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await Tt(r,t)(n,e,r),p=d.key,m=Ci(d.requestsAllowed??t.requestsAllowed,"requestsAllowed"),h=Ci(d.timeWindowMinutes??t.timeWindowMinutes,"timeWindowMinutes"),I=t.headerMode??"retry-after",b=et(r,a),L=`rate-limit${y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:""}/${r}/${p}`,C=await b.getCountAndUpdateExpiry(L,h,e.requestId);return C.count>m?(au(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${L}' (strict mode)`),c(I,C.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;au(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var vi;function cu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(cu,"headersToNameValuePairs");function Jd(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Jd,"queryToNameValueParis");function Kd(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Kd,"parseIntOrUndefined");var lu={};async function Qd(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return vi||(vi={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?$e(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?$e(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:y.instance.isWorkingCopy||y.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:vi,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:cu(n.headers),queryString:Jd(n.query)},response:{status:a.status,statusText:a.statusText,headers:cu(a.headers),content:{size:Kd(n.headers.get("content-length"))}}}]}}},d=lu[t.apiKey];if(!d){let p=t.apiKey;d=new Y("readme-metering-inbound-policy",10,async m=>{try{let h=t.url??"https://metrics.readme.io/request",I=await z.fetch(h,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),lu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Qd,"ReadmeMetricsInboundPolicy");var Yd=i(async(n,e,t,r)=>{f("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new re(n,{headers:s})},"RemoveHeadersInboundPolicy");var Xd=i(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var ep=i(async(n,e,t,r)=>{f("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new re(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var tp=i(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var du=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),np=i(async(n,e,t)=>{f("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?du():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?du():n},"RequestSizeLimitInboundPolicy");var Lt=i(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),_t=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=lr(t,r,o,c.name),p=he.instance.schemaValidator[d],m=p(e[c.name]),h=Oi(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Oe=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Oi=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function pu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let I=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=x.badRequest(e,n,{detail:`${I}, see errors property for more details`,errors:`${h}`});if(ke(t.validateBody)&&Oe(n,t.logLevel??"info",I,[r],h),Le(t.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,I=x.badRequest(e,n,{detail:h});return ke(t.validateBody)&&Oe(n,t.logLevel??"info",h,[r],[h]),Le(t.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=dr(n.route.path,e.method,o),u=he.instance.schemaValidator[a];if(!u){let h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=x.badRequest(e,n,{detail:h});return ke(t.validateBody)&&Oe(n,t.logLevel??"info",h,[r],[h]),Le(t.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Oi(l),m=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Oe(n,t.logLevel??"info",d,[r],p),Le(t.validateBody))return m}i(pu,"handleBodyValidation");function mu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Lt(n),s=_t(o.filter(a=>a.in==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Oe(n,t.logLevel??"info",a,s.invalidValues,s.errors),Le(t.validateHeaders))return u}}i(mu,"handleHeadersValidation");function gu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Lt(n),o=_t(r.filter(s=>s.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Oe(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validatePathParameters))return a}}i(gu,"handlePathParameterValidation");function fu(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Lt(n),o=_t(r.filter(s=>s.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Oe(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validateQueryParameters))return a}}i(fu,"handleQueryParameterValidation");var hu=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=fu(e,n,t);if(r!==void 0||(r=gu(e,n,t),r!==void 0)||(r=mu(e,n,t),r!==void 0))return r;let o=await pu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),rp=hu;var op=i(async(n,e,t,r)=>{if(f("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new g(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var ip=i(async(n,e,t)=>(f("policy.inbound.set-body"),new re(n,{body:t.body})),"SetBodyInboundPolicy");var sp=i(async(n,e,t,r)=>{f("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new re(n,{headers:s})},"SetHeadersInboundPolicy");var ap=i(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`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(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var up=i(async(n,e,t,r)=>{f("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new re(s.toString(),n)},"SetQueryParamsInboundPolicy");var cp=i(async(n,e,t,r,o)=>{if(f("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new g(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var lp=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),dp=i(async(n,e,t,r)=>{if(f("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await lp(t.sleepInMs),n},"SleepInboundPolicy");var pp=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),W(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await Pe(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof re))throw new K("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new k(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var mp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),W(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await se(r,void 0,t),s=new oe(o,e),a=await s.get(r);if(!a){let u=await gp(t,e);s.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function gp(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await we({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new k("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 k("Response returned from Azure AD is not in the expected format.")}i(gp,"getAccessToken");var yu="https://accounts.google.com/o/oauth2/token",ki,fp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),W(t,r).required("serviceAccountJson","string"),ki||(ki=await Te.init(t.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(" ")},s=await se(r,void 0,t),a=new oe(s,e),u=await a.get(r);if(!u){let c=await De({serviceAccount:ki,audience:yu,payload:o}),l=await qn(yu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var hp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",yp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Li,bp=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),W(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new g(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(yp.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Li||(Li=await Te.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=$e(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new k(`Unable to determine user from for the policy ${r}`);let a=await se(r,void 0,t),u=new oe(a,e),c={uid:s,claims:o},l=await ut(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:Li,audience:hp,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await ia(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new k("Invalid token response from Firebase");d=h.idToken,u.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var an=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let r=new oe("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await se("zuplo-token",void 0,t),s=await r.get(o);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=y.instance;if(!a||!u)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await rr({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return r.put(o,d.access_token,d.expires_in-300),d.access_token}};var bu="service-account-id-token",_i=class extends ae{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),f("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await se(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new ze(this.cacheName):r=new oe(this.cacheName,t);let o=await r.get(bu);if(!o){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await an.getIDToken(t,{audience:s}),u=await ra(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!u.access_token||!u.expires_in)throw new k("Invalid token response from GCP");let c=u.access_token,l=await oa({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");o=l.token,r.put(bu,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var Ni,wp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),W(t,r).required("audience","string").required("serviceAccountJson","string"),Ni||(Ni=await Te.init(t.serviceAccountJson));let o=await De({serviceAccount:Ni,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var wu="https://www.googleapis.com/oauth2/v4/token",Di,Rp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),W(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Di||(Di=await Te.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=it(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await se(r,void 0,t),a;t.useMemoryCacheOnly?a=new ze(s):a=new oe(s,e);let u=await a.get(r);if(!u){let c=await De({serviceAccount:Di,audience:wu,payload:o}),l=await qn(wu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var Pp=i(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(o))return n;let{errors:a}=t.validator.default;if(!a)throw new K("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 x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Ru=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((b,S)=>e(b,"name",{value:S,configurable:!0}),"__name"),o=i((b,S)=>i(function(){return S||(0,b[t(b)[0]])((S={exports:{}}).exports,S),S.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(b){var S={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(C,H){return H},"tagValueProcessor"),attributeValueProcessor:i(function(C,H){return H},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(C,H,Z){return C},"updateTag")},L=r(function(C){return Object.assign({},S,C)},"buildOptions");b.buildOptions=L,b.defaultOptions=S}}),a=o({"node_modules/fast-xml-parser/src/util.js"(b){"use strict";var S=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",L=S+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",C="["+S+"]["+L+"]*",H=new RegExp("^"+C+"$"),Z=r(function(v,$){let V=[],F=$.exec(v);for(;F;){let T=[];T.startIndex=$.lastIndex-F[0].length;let E=F.length;for(let M=0;M<E;M++)T.push(F[M]);V.push(T),F=$.exec(v)}return V},"getAllMatches"),q=r(function(v){let $=H.exec(v);return!($===null||typeof $>"u")},"isName");b.isExist=function(v){return typeof v<"u"},b.isEmptyObject=function(v){return Object.keys(v).length===0},b.merge=function(v,$,V){if($){let F=Object.keys($),T=F.length;for(let E=0;E<T;E++)V==="strict"?v[F[E]]=[$[F[E]]]:v[F[E]]=$[F[E]]}},b.getValue=function(v){return b.isExist(v)?v:""},b.isName=q,b.getAllMatches=Z,b.nameRegexp=C}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(b,S){"use strict";var L=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(C){this.tagname=C,this.child=[],this[":@"]={}}add(C,H){C==="__proto__"&&(C="#__proto__"),this.child.push({[C]:H})}addChild(C){C.tagname==="__proto__"&&(C.tagname="#__proto__"),C[":@"]&&Object.keys(C[":@"]).length>0?this.child.push({[C.tagname]:C.child,":@":C[":@"]}):this.child.push({[C.tagname]:C.child})}};S.exports=L}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(b,S){var L=a();function C(T,E){let M={};if(T[E+3]==="O"&&T[E+4]==="C"&&T[E+5]==="T"&&T[E+6]==="Y"&&T[E+7]==="P"&&T[E+8]==="E"){E=E+9;let ce=1,J=!1,X=!1,Se="";for(;E<T.length;E++)if(T[E]==="<"&&!X){if(J&&q(T,E))E+=7,[entityName,val,E]=H(T,E+1),val.indexOf("&")===-1&&(M[F(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(J&&v(T,E))E+=8;else if(J&&$(T,E))E+=8;else if(J&&V(T,E))E+=9;else if(Z)X=!0;else throw new Error("Invalid DOCTYPE");ce++,Se=""}else if(T[E]===">"){if(X?T[E-1]==="-"&&T[E-2]==="-"&&(X=!1,ce--):ce--,ce===0)break}else T[E]==="["?J=!0:Se+=T[E];if(ce!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:M,i:E}}i(C,"readDocType"),r(C,"readDocType");function H(T,E){let M="";for(;E<T.length&&T[E]!=="'"&&T[E]!=='"';E++)M+=T[E];if(M=M.trim(),M.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=T[E++],J="";for(;E<T.length&&T[E]!==ce;E++)J+=T[E];return[M,J,E]}i(H,"readEntityExp"),r(H,"readEntityExp");function Z(T,E){return T[E+1]==="!"&&T[E+2]==="-"&&T[E+3]==="-"}i(Z,"isComment"),r(Z,"isComment");function q(T,E){return T[E+1]==="!"&&T[E+2]==="E"&&T[E+3]==="N"&&T[E+4]==="T"&&T[E+5]==="I"&&T[E+6]==="T"&&T[E+7]==="Y"}i(q,"isEntity"),r(q,"isEntity");function v(T,E){return T[E+1]==="!"&&T[E+2]==="E"&&T[E+3]==="L"&&T[E+4]==="E"&&T[E+5]==="M"&&T[E+6]==="E"&&T[E+7]==="N"&&T[E+8]==="T"}i(v,"isElement"),r(v,"isElement");function $(T,E){return T[E+1]==="!"&&T[E+2]==="A"&&T[E+3]==="T"&&T[E+4]==="T"&&T[E+5]==="L"&&T[E+6]==="I"&&T[E+7]==="S"&&T[E+8]==="T"}i($,"isAttlist"),r($,"isAttlist");function V(T,E){return T[E+1]==="!"&&T[E+2]==="N"&&T[E+3]==="O"&&T[E+4]==="T"&&T[E+5]==="A"&&T[E+6]==="T"&&T[E+7]==="I"&&T[E+8]==="O"&&T[E+9]==="N"}i(V,"isNotation"),r(V,"isNotation");function F(T){if(L.isName(T))return T;throw new Error(`Invalid entity name ${T}`)}i(F,"validateEntityName"),r(F,"validateEntityName"),S.exports=C}}),l=o({"../../node_modules/strnum/strnum.js"(b,S){var L=/^[-+]?0x[a-fA-F0-9]+$/,C=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var H={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Z(v,$={}){if($=Object.assign({},H,$),!v||typeof v!="string")return v;let V=v.trim();if($.skipLike!==void 0&&$.skipLike.test(V))return v;if($.hex&&L.test(V))return Number.parseInt(V,16);{let F=C.exec(V);if(F){let T=F[1],E=F[2],M=q(F[3]),ce=F[4]||F[6];if(!$.leadingZeros&&E.length>0&&T&&V[2]!==".")return v;if(!$.leadingZeros&&E.length>0&&!T&&V[1]!==".")return v;{let J=Number(V),X=""+J;return X.search(/[eE]/)!==-1||ce?$.eNotation?J:v:V.indexOf(".")!==-1?X==="0"&&M===""||X===M||T&&X==="-"+M?J:v:E?M===X||T+M===X?J:v:V===X||V===T+X?J:v}}else return v}}i(Z,"toNumber"),r(Z,"toNumber");function q(v){return v&&v.indexOf(".")!==-1&&(v=v.replace(/0+$/,""),v==="."?v="0":v[0]==="."?v="0"+v:v[v.length-1]==="."&&(v=v.substr(0,v.length-1))),v}i(q,"trimZeros"),r(q,"trimZeros"),S.exports=Z}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(b,S){"use strict";var L=a(),C=u(),H=c(),Z=l(),q=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((A,_)=>String.fromCharCode(Number.parseInt(_,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((A,_)=>String.fromCharCode(Number.parseInt(_,16)),"val")}},this.addExternalEntities=v,this.parseXml=E,this.parseTextData=$,this.resolveNameSpace=V,this.buildAttributesMap=T,this.isItStopNode=X,this.replaceEntitiesValue=ce,this.readStopNodeData=G,this.saveTextToParentTag=J,this.addChild=M}};function v(P){let A=Object.keys(P);for(let _=0;_<A.length;_++){let B=A[_];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:P[B]}}}i(v,"addExternalEntities"),r(v,"addExternalEntities");function $(P,A,_,B,N,D,ee){if(P!==void 0&&(this.options.trimValues&&!B&&(P=P.trim()),P.length>0)){ee||(P=this.replaceEntitiesValue(P));let j=this.options.tagValueProcessor(A,P,_,N,D);return j==null?P:typeof j!=typeof P||j!==P?j:this.options.trimValues?pe(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?pe(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i($,"parseTextData"),r($,"parseTextData");function V(P){if(this.options.removeNSPrefix){let A=P.split(":"),_=P.charAt(0)==="/"?"/":"";if(A[0]==="xmlns")return"";A.length===2&&(P=_+A[1])}return P}i(V,"resolveNameSpace"),r(V,"resolveNameSpace");var F=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function T(P,A,_){if(!this.options.ignoreAttributes&&typeof P=="string"){let B=L.getAllMatches(P,F),N=B.length,D={};for(let ee=0;ee<N;ee++){let j=this.resolveNameSpace(B[ee][1]),U=B[ee][4],le=this.options.attributeNamePrefix+j;if(j.length)if(this.options.transformAttributeName&&(le=this.options.transformAttributeName(le)),le==="__proto__"&&(le="#__proto__"),U!==void 0){this.options.trimValues&&(U=U.trim()),U=this.replaceEntitiesValue(U);let ie=this.options.attributeValueProcessor(j,U,A);ie==null?D[le]=U:typeof ie!=typeof U||ie!==U?D[le]=ie:D[le]=pe(U,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[le]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}i(T,"buildAttributesMap"),r(T,"buildAttributesMap");var E=r(function(P){P=P.replace(/\r\n?/g,`
|
|
84
84
|
`);let A=new C("!xml"),_=A,B="",N="";for(let D=0;D<P.length;D++)if(P[D]==="<")if(P[D+1]==="/"){let j=w(P,">",D,"Closing Tag is not closed."),U=P.substring(D+2,j).trim();if(this.options.removeNSPrefix){let ve=U.indexOf(":");ve!==-1&&(U=U.substr(ve+1))}this.options.transformTagName&&(U=this.options.transformTagName(U)),_&&(B=this.saveTextToParentTag(B,_,N));let le=N.substring(N.lastIndexOf(".")+1);if(U&&this.options.unpairedTags.indexOf(U)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${U}>`);let ie=0;le&&this.options.unpairedTags.indexOf(le)!==-1?(ie=N.lastIndexOf(".",N.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=N.lastIndexOf("."),N=N.substring(0,ie),_=this.tagsNodeStack.pop(),B="",D=j}else if(P[D+1]==="?"){let j=O(P,D,!1,"?>");if(!j)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,_,N),!(this.options.ignoreDeclaration&&j.tagName==="?xml"||this.options.ignorePiTags)){let U=new C(j.tagName);U.add(this.options.textNodeName,""),j.tagName!==j.tagExp&&j.attrExpPresent&&(U[":@"]=this.buildAttributesMap(j.tagExp,N,j.tagName)),this.addChild(_,U,N)}D=j.closeIndex+1}else if(P.substr(D+1,3)==="!--"){let j=w(P,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let U=P.substring(D+4,j-2);B=this.saveTextToParentTag(B,_,N),_.add(this.options.commentPropName,[{[this.options.textNodeName]:U}])}D=j}else if(P.substr(D+1,2)==="!D"){let j=H(P,D);this.docTypeEntities=j.entities,D=j.i}else if(P.substr(D+1,2)==="!["){let j=w(P,"]]>",D,"CDATA is not closed.")-2,U=P.substring(D+9,j);B=this.saveTextToParentTag(B,_,N);let le=this.parseTextData(U,_.tagname,N,!0,!1,!0,!0);le==null&&(le=""),this.options.cdataPropName?_.add(this.options.cdataPropName,[{[this.options.textNodeName]:U}]):_.add(this.options.textNodeName,le),D=j+2}else{let j=O(P,D,this.options.removeNSPrefix),U=j.tagName,le=j.rawTagName,ie=j.tagExp,ve=j.attrExpPresent,Wi=j.closeIndex;this.options.transformTagName&&(U=this.options.transformTagName(U)),_&&B&&_.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,_,N,!1));let Ji=_;if(Ji&&this.options.unpairedTags.indexOf(Ji.tagname)!==-1&&(_=this.tagsNodeStack.pop(),N=N.substring(0,N.lastIndexOf("."))),U!==A.tagname&&(N+=N?"."+U:U),this.isItStopNode(this.options.stopNodes,N,U)){let Ce="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)D=j.closeIndex;else if(this.options.unpairedTags.indexOf(U)!==-1)D=j.closeIndex;else{let cr=this.readStopNodeData(P,le,Wi+1);if(!cr)throw new Error(`Unexpected end of ${le}`);D=cr.i,Ce=cr.tagContent}let ur=new C(U);U!==ie&&ve&&(ur[":@"]=this.buildAttributesMap(ie,N,U)),Ce&&(Ce=this.parseTextData(Ce,U,N,!0,ve,!0,!0)),N=N.substr(0,N.lastIndexOf(".")),ur.add(this.options.textNodeName,Ce),this.addChild(_,ur,N)}else{if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1){U[U.length-1]==="/"?(U=U.substr(0,U.length-1),N=N.substr(0,N.length-1),ie=U):ie=ie.substr(0,ie.length-1),this.options.transformTagName&&(U=this.options.transformTagName(U));let Ce=new C(U);U!==ie&&ve&&(Ce[":@"]=this.buildAttributesMap(ie,N,U)),this.addChild(_,Ce,N),N=N.substr(0,N.lastIndexOf("."))}else{let Ce=new C(U);this.tagsNodeStack.push(_),U!==ie&&ve&&(Ce[":@"]=this.buildAttributesMap(ie,N,U)),this.addChild(_,Ce,N),_=Ce}B="",D=Wi}}else B+=P[D];return A.child},"parseXml");function M(P,A,_){let B=this.options.updateTag(A.tagname,_,A[":@"]);B===!1||(typeof B=="string"&&(A.tagname=B),P.addChild(A))}i(M,"addChild"),r(M,"addChild");var ce=r(function(P){if(this.options.processEntities){for(let A in this.docTypeEntities){let _=this.docTypeEntities[A];P=P.replace(_.regx,_.val)}for(let A in this.lastEntities){let _=this.lastEntities[A];P=P.replace(_.regex,_.val)}if(this.options.htmlEntities)for(let A in this.htmlEntities){let _=this.htmlEntities[A];P=P.replace(_.regex,_.val)}P=P.replace(this.ampEntity.regex,this.ampEntity.val)}return P},"replaceEntitiesValue");function J(P,A,_,B){return P&&(B===void 0&&(B=Object.keys(A.child).length===0),P=this.parseTextData(P,A.tagname,_,!1,A[":@"]?Object.keys(A[":@"]).length!==0:!1,B),P!==void 0&&P!==""&&A.add(this.options.textNodeName,P),P=""),P}i(J,"saveTextToParentTag"),r(J,"saveTextToParentTag");function X(P,A,_){let B="*."+_;for(let N in P){let D=P[N];if(B===D||A===D)return!0}return!1}i(X,"isItStopNode"),r(X,"isItStopNode");function Se(P,A,_=">"){let B,N="";for(let D=A;D<P.length;D++){let ee=P[D];if(B)ee===B&&(B="");else if(ee==='"'||ee==="'")B=ee;else if(ee===_[0])if(_[1]){if(P[D+1]===_[1])return{data:N,index:D}}else return{data:N,index:D};else ee===" "&&(ee=" ");N+=ee}}i(Se,"tagExpWithClosingIndex"),r(Se,"tagExpWithClosingIndex");function w(P,A,_,B){let N=P.indexOf(A,_);if(N===-1)throw new Error(B);return N+A.length-1}i(w,"findClosingIndex"),r(w,"findClosingIndex");function O(P,A,_,B=">"){let N=Se(P,A+1,B);if(!N)return;let D=N.data,ee=N.index,j=D.search(/\s/),U=D,le=!0;j!==-1&&(U=D.substring(0,j),D=D.substring(j+1).trimStart());let ie=U;if(_){let ve=U.indexOf(":");ve!==-1&&(U=U.substr(ve+1),le=U!==N.data.substr(ve+1))}return{tagName:U,tagExp:D,closeIndex:ee,attrExpPresent:le,rawTagName:ie}}i(O,"readTagExp"),r(O,"readTagExp");function G(P,A,_){let B=_,N=1;for(;_<P.length;_++)if(P[_]==="<")if(P[_+1]==="/"){let D=w(P,">",_,`${A} is not closed`);if(P.substring(_+2,D).trim()===A&&(N--,N===0))return{tagContent:P.substring(B,_),i:D};_=D}else if(P[_+1]==="?")_=w(P,"?>",_+1,"StopNode is not closed.");else if(P.substr(_+1,3)==="!--")_=w(P,"-->",_+3,"StopNode is not closed.");else if(P.substr(_+1,2)==="![")_=w(P,"]]>",_,"StopNode is not closed.")-2;else{let D=O(P,_,">");D&&((D&&D.tagName)===A&&D.tagExp[D.tagExp.length-1]!=="/"&&N++,_=D.closeIndex)}}i(G,"readStopNodeData"),r(G,"readStopNodeData");function pe(P,A,_){if(A&&typeof P=="string"){let B=P.trim();return B==="true"?!0:B==="false"?!1:Z(P,_)}else return L.isExist(P)?P:""}i(pe,"parseValue"),r(pe,"parseValue"),S.exports=q}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(b){"use strict";function S(q,v){return L(q,v)}i(S,"prettify"),r(S,"prettify");function L(q,v,$){let V,F={};for(let T=0;T<q.length;T++){let E=q[T],M=C(E),ce="";if($===void 0?ce=M:ce=$+"."+M,M===v.textNodeName)V===void 0?V=E[M]:V+=""+E[M];else{if(M===void 0)continue;if(E[M]){let J=L(E[M],v,ce),X=Z(J,v);E[":@"]?H(J,E[":@"],ce,v):Object.keys(J).length===1&&J[v.textNodeName]!==void 0&&!v.alwaysCreateTextNode?J=J[v.textNodeName]:Object.keys(J).length===0&&(v.alwaysCreateTextNode?J[v.textNodeName]="":J=""),F[M]!==void 0&&F.hasOwnProperty(M)?(Array.isArray(F[M])||(F[M]=[F[M]]),F[M].push(J)):v.isArray(M,ce,X)?F[M]=[J]:F[M]=J}}}return typeof V=="string"?V.length>0&&(F[v.textNodeName]=V):V!==void 0&&(F[v.textNodeName]=V),F}i(L,"compress"),r(L,"compress");function C(q){let v=Object.keys(q);for(let $=0;$<v.length;$++){let V=v[$];if(V!==":@")return V}}i(C,"propName"),r(C,"propName");function H(q,v,$,V){if(v){let F=Object.keys(v),T=F.length;for(let E=0;E<T;E++){let M=F[E];V.isArray(M,$+"."+M,!0,!0)?q[M]=[v[M]]:q[M]=v[M]}}}i(H,"assignAttributes"),r(H,"assignAttributes");function Z(q,v){let{textNodeName:$}=v,V=Object.keys(q).length;return!!(V===0||V===1&&(q[$]||typeof q[$]=="boolean"||q[$]===0))}i(Z,"isLeafTag"),r(Z,"isLeafTag"),b.prettify=S}}),m=o({"node_modules/fast-xml-parser/src/validator.js"(b){"use strict";var S=a(),L={allowBooleanAttributes:!1,unpairedTags:[]};b.validate=function(w,O){O=Object.assign({},L,O);let G=[],pe=!1,P=!1;w[0]==="\uFEFF"&&(w=w.substr(1));for(let A=0;A<w.length;A++)if(w[A]==="<"&&w[A+1]==="?"){if(A+=2,A=H(w,A),A.err)return A}else if(w[A]==="<"){let _=A;if(A++,w[A]==="!"){A=Z(w,A);continue}else{let B=!1;w[A]==="/"&&(B=!0,A++);let N="";for(;A<w.length&&w[A]!==">"&&w[A]!==" "&&w[A]!==" "&&w[A]!==`
|
package/out/types/index.d.ts
CHANGED
|
@@ -532,7 +532,13 @@ export declare interface AuthZenInboundPolicyOptions {
|
|
|
532
532
|
/**
|
|
533
533
|
* The action of the request. Note you can use the `$authzen-prop()` syntax to reference the action.
|
|
534
534
|
*/
|
|
535
|
-
action:
|
|
535
|
+
action: {
|
|
536
|
+
/**
|
|
537
|
+
* The name of the action. Note you can use the `$authzen-prop()` syntax to reference the action name.
|
|
538
|
+
*/
|
|
539
|
+
name: string;
|
|
540
|
+
[k: string]: unknown;
|
|
541
|
+
};
|
|
536
542
|
/**
|
|
537
543
|
* If explicitly set to false, the policy will not throw an error if there is any problem communicating with the AuthZen PDP service and allow calls through. By default throwOnError is assumed to be on/true.
|
|
538
544
|
*/
|
|
@@ -544,7 +550,9 @@ export declare interface AuthZenInboundPolicyOptions {
|
|
|
544
550
|
export declare interface AuthZenPayloadSettings {
|
|
545
551
|
subject?: AuthZenTypeIdPair;
|
|
546
552
|
resource?: AuthZenTypeIdPair;
|
|
547
|
-
action?:
|
|
553
|
+
action?: {
|
|
554
|
+
name: string;
|
|
555
|
+
};
|
|
548
556
|
}
|
|
549
557
|
|
|
550
558
|
export declare interface AuthZenTypeIdPair {
|