@authhero/cloudflare-adapter 2.38.14 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require("./sync-defaults-errors-BliFySmE.js");let l=require("@authhero/adapter-interfaces"),u=require("@hono/zod-openapi"),d=require("hono/http-exception"),f=require("wretch");f=s(f);let p=require("wretch/middlewares");var m=u.z.object({code:u.z.number(),message:u.z.string()}),h=u.z.object({message:u.z.string()}),g=u.z.object({emails:u.z.array(u.z.string()).optional(),http_body:u.z.string().optional(),http_url:u.z.string().optional(),txt_name:u.z.string().optional(),txt_value:u.z.string().optional()}),_=u.z.object({ciphers:u.z.array(u.z.string()).optional(),early_hints:u.z.string().optional(),http2:u.z.string().optional(),min_tls_version:u.z.string().optional(),tls_1_3:u.z.string().optional()}),ee=u.z.object({id:u.z.string(),bundle_method:u.z.string().optional(),certificate_authority:u.z.string(),custom_certificate:u.z.string().optional(),custom_csr_id:u.z.string().optional(),custom_key:u.z.string().optional(),expires_on:u.z.string().optional(),hosts:u.z.array(u.z.string()).optional(),issuer:u.z.string().optional(),method:u.z.string(),serial_number:u.z.string().optional(),settings:_.optional(),signature:u.z.string().optional(),type:u.z.string(),uploaded_on:u.z.string().optional(),validation_errors:u.z.array(h).optional(),validation_records:u.z.array(g).optional(),wildcard:u.z.boolean()}),te=u.z.object({name:u.z.string(),type:u.z.string(),value:u.z.string()}),ne=u.z.object({http_body:u.z.string().optional(),http_url:u.z.string().optional()}),v=u.z.object({id:u.z.string(),ssl:ee,hostname:u.z.string(),custom_metadata:u.z.record(u.z.string(),u.z.string()).optional(),custom_origin_server:u.z.string().optional(),custom_origin_sni:u.z.string().optional(),ownership_verification:te.optional(),ownership_verification_http:ne.optional(),status:u.z.string(),verification_errors:u.z.array(u.z.string()).optional(),created_at:u.z.string()}),y=u.z.object({errors:u.z.array(m),messages:u.z.array(m),success:u.z.boolean(),result:v});u.z.object({errors:u.z.array(m),messages:u.z.array(m),success:u.z.boolean(),result:u.z.array(v)});function b(e){return(0,f.default)(`https://api.cloudflare.com/client/v4/zones/${e.zoneId}`).headers({"X-Auth-Email":e.authEmail,"X-Auth-Key":e.authKey,"Content-Type":`application/json`}).middlewares([(0,p.retry)(),(0,p.dedupe)()])}function x(e){let t={},n={};if(!e)return{sslOverrides:t,rest:n};for(let[r,i]of Object.entries(e))r.startsWith(`ssl.`)?t[r.slice(4)]=i:n[r]=i;return{sslOverrides:t,rest:n}}function S(e){let t=[];if(e.ssl.validation_records)for(let n of e.ssl.validation_records)n.txt_name&&n.txt_value&&t.push({name:`txt`,record:n.txt_value,domain:n.txt_name});if(e.ownership_verification&&t.push({name:`txt`,record:e.ownership_verification.value,domain:e.ownership_verification.name}),e.ownership_verification_http?.http_body&&e.ownership_verification_http?.http_url&&t.push({name:`http`,http_body:e.ownership_verification_http.http_body,http_url:e.ownership_verification_http.http_url}),e.ssl.validation_records)for(let n of e.ssl.validation_records)n.http_body&&n.http_url&&t.push({name:`http`,http_body:n.http_body,http_url:n.http_url});let n={...e.domain_metadata||{},"ssl.method":e.ssl.method,"ssl.type":e.ssl.type,"ssl.certificate_authority":e.ssl.certificate_authority};return{custom_domain_id:e.id,domain:e.hostname,primary:e.primary,status:e.status===`active`?`ready`:`pending`,type:e.type??`auth0_managed_certs`,verification:{methods:u.z.array(l.verificationMethodsSchema).parse(t)},domain_metadata:n}}function re(e){return{create:async(t,n)=>{let{sslOverrides:r,rest:i}=x(n.domain_metadata),{result:a,errors:o,success:s}=y.parse(await b(e).post({hostname:n.domain,ssl:{method:`txt`,type:`dv`,...r},custom_metadata:e.enterprise?{tenant_id:t}:void 0},`/custom_hostnames`).json());if(!s)throw Error(JSON.stringify(o));let c=S({...a,primary:!1,type:n.type,domain_metadata:i});return await e.customDomainAdapter.create(t,{custom_domain_id:c.custom_domain_id,domain:c.domain,type:c.type,domain_metadata:n.domain_metadata}),await e.customDomainAdapter.update(t,c.custom_domain_id,{status:c.status,primary:c.primary,verification:c.verification}),c},get:async(t,n)=>{let r=await e.customDomainAdapter.get(t,n);if(!r)throw new d.HTTPException(404);let i;try{i=await b(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json()}catch(e){return console.warn(`[custom-domains] CF fetch failed for ${n} (tenant=${t}); returning stale DB row:`,e instanceof Error?e.message:e),r}let a=y.safeParse(i);if(!a.success||!a.data.success)return console.warn(`[custom-domains] CF response unparseable for ${n} (tenant=${t}); returning stale DB row.`,a.success?{cfErrors:a.data.errors}:{zodIssues:a.error.issues,body:i}),r;let{result:o}=a.data;if(e.enterprise&&o.custom_metadata?.tenant_id!==t)throw new d.HTTPException(404);let s;try{s=S({...r,...o})}catch(e){return console.warn(`[custom-domains] mapCustomDomainResponse failed for ${n} (tenant=${t}); returning stale DB row.`,e instanceof Error?e.message:e),r}if(s.status!==r.status||JSON.stringify(s.verification)!==JSON.stringify(r.verification))try{await e.customDomainAdapter.update(t,n,{status:s.status,verification:s.verification})}catch(e){console.warn(`[custom-domains] DB writeback failed for ${n} (tenant=${t}); returning merged response without DB sync.`,e instanceof Error?e.message:e)}return s},getByDomain:async t=>e.customDomainAdapter.getByDomain(t),list:async t=>e.customDomainAdapter.list(t),remove:async(t,n)=>{if(e.enterprise){let{result:r,success:i}=y.parse(await b(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json());if(!i||r.custom_metadata?.tenant_id!==t)throw new d.HTTPException(404)}let r=await b(e).delete(`/custom_hostnames/${encodeURIComponent(n)}`).res();return r.ok&&await e.customDomainAdapter.remove(t,n),r.ok},update:async(t,n,r)=>{let{sslOverrides:i}=x(r.domain_metadata),a={};if(Object.keys(i).length>0){let t;try{t=await b(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json()}catch(e){throw new d.HTTPException(503,{message:`Failed to fetch current custom hostname state: ${e instanceof Error?e.message:String(e)}`})}let r=y.safeParse(t);if(!r.success||!r.data.success)throw new d.HTTPException(503,{message:`Failed to parse current custom hostname state: ${JSON.stringify(r.success?r.data.errors:r.error.issues)}`});a.ssl={method:r.data.result.ssl.method,type:r.data.result.ssl.type,certificate_authority:r.data.result.ssl.certificate_authority,...i}}if(Object.keys(a).length>0){let t=await b(e).patch(a,`/custom_hostnames/${encodeURIComponent(n)}`).res().catch(e=>{throw new d.HTTPException(503,{message:`Failed to update custom hostname: ${e instanceof Error?e.message:String(e)}`})});if(!t.ok)throw new d.HTTPException(503,{message:await t.text()})}return e.customDomainAdapter.update(t,n,r)},uploadCertificate:async(t,n,r)=>{let i=await e.customDomainAdapter.get(t,n);if(!i)throw new d.HTTPException(404);let a=await b(e).patch({ssl:{custom_certificate:r.certificate,custom_key:r.private_key}},`/custom_hostnames/${encodeURIComponent(n)}`).json(),{result:o,errors:s,success:c}=y.parse(a);if(!c)throw new d.HTTPException(503,{message:JSON.stringify(s)});let l=S({...i,...o});return await e.customDomainAdapter.update(t,n,{status:l.status,verification:l.verification}),l}}}var C=class{config;cache=null;constructor(e){this.config=e}async getCache(){if(this.cache)return this.cache;if(typeof caches>`u`)throw Error(`caches API is not available - CloudflareCache should only be used in Cloudflare Workers`);return this.config.cacheName?this.cache=await caches.open(this.config.cacheName):this.cache=caches.default,this.cache}getKey(e){return this.config.keyPrefix?`${this.config.keyPrefix}:${e}`:e}createRequest(e){return new Request(`https://cache.internal/${this.getKey(e)}`)}async matchWithTimeout(e,t){let n=this.config.getTimeoutMs??200;return n<=0?e.match(t):new Promise(r=>{let i=setTimeout(()=>r(void 0),n);e.match(t).then(e=>{clearTimeout(i),r(e)},()=>{clearTimeout(i),r(void 0)})})}async get(e){try{let t=await this.getCache(),n=this.createRequest(e),r=await this.matchWithTimeout(t,n);if(!r)return null;let i=await r.text();if(!i)return await this.delete(e),null;let a;try{a=JSON.parse(i)}catch{return await this.delete(e),null}return a.expiresAt&&new Date(a.expiresAt)<new Date?(await this.delete(e),null):a.value}catch(t){return console.error(`CloudflareCache: get error for key ${e}:`,t),null}}async set(e,t,n){try{let r=await this.getCache(),i=n??this.config.defaultTtlSeconds,a=i!==void 0,o=a?Math.max(0,i):0,s={value:t,expiresAt:a?new Date(Date.now()+(o>0?o*1e3:-1)).toISOString():void 0,cachedAt:new Date().toISOString()},c=this.createRequest(e),l={"Content-Type":`application/json`};a&&o>0&&(l[`Cache-Control`]=`max-age=${o}`);let u=new Response(JSON.stringify(s),{headers:l});await r.put(c,u)}catch(t){console.error(`CloudflareCache: set error for key ${e}:`,t)}}async delete(e){try{let t=await this.getCache(),n=this.createRequest(e);return await t.delete(n)}catch(t){return console.error(`CloudflareCache: delete error for key ${e}:`,t),!1}}async deleteByPrefix(e){return console.warn(`CloudflareCache.deleteByPrefix() is not implemented - Cloudflare Cache API does not support prefix-based deletion`),0}async clear(){console.warn(`CloudflareCache.clear() is not implemented - Cloudflare Cache API does not support clearing all entries`)}};function ie(e={}){return new C({defaultTtlSeconds:300,keyPrefix:`authhero`,getTimeoutMs:200,...e})}var ae=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,w=(e=21)=>{let t=``,n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=ae[n[e]&63];return t};async function T(e,t){let n=e.timeout||3e4,r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=`https://api.sql.cloudflarestorage.com/api/v1/accounts/${e.accountId}/r2-sql/query/${e.warehouseName}`,i=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.authToken}`},body:JSON.stringify({query:t}),signal:r.signal});if(!i.ok)throw Error(`R2 SQL query failed: ${i.status} ${i.statusText}`);let a=await i.json();if(!a.success&&a.errors)throw Error(`R2 SQL error: ${a.errors.join(`, `)}`);return a.data||a.result?.data||[]}finally{clearTimeout(i)}}function E(e){return`'${e.replace(/'/g,`''`)}'`}function D(e){return`"${e.replace(/"/g,`""`)}"`}function O(e){let t=e=>{if(!e)return``;try{return JSON.parse(e)}catch{return e}};return{type:e.type,date:e.date,description:e.description,ip:e.ip,user_agent:e.user_agent,details:t(e.details),isMobile:!!e.isMobile,user_id:e.user_id,user_name:e.user_name,connection:e.connection,connection_id:e.connection_id,client_id:e.client_id,client_name:e.client_name,audience:e.audience,scope:e.scope,strategy:e.strategy,strategy_type:e.strategy_type,hostname:e.hostname,auth0_client:t(e.auth0_client),log_id:e.id,location_info:e.country_code||e.city_name||e.latitude||e.longitude||e.time_zone||e.continent_code?{country_code:e.country_code||``,city_name:e.city_name||``,latitude:e.latitude||``,longitude:e.longitude||``,time_zone:e.time_zone||``,continent_code:e.continent_code||``}:void 0}}function oe(e){return async(t,n)=>{let r=n.log_id||w(),i={...n,log_id:r};return await k(e,t,i),i}}async function k(e,t,n){let r=e=>e?JSON.stringify(e):void 0,i={id:n.log_id,tenant_id:t,type:n.type,date:n.date,description:n.description?.substring(0,256),ip:n.ip,user_agent:n.user_agent,details:r(n.details)?.substring(0,8192),isMobile:+!!n.isMobile,user_id:n.user_id,user_name:n.user_name,connection:n.connection,connection_id:n.connection_id,client_id:n.client_id,client_name:n.client_name,audience:n.audience,scope:n.scope,strategy:n.strategy,strategy_type:n.strategy_type,hostname:n.hostname,auth0_client:r(n.auth0_client),log_id:n.log_id,country_code:n.location_info?.country_code,city_name:n.location_info?.city_name,latitude:n.location_info?.latitude,longitude:n.location_info?.longitude,time_zone:n.location_info?.time_zone,continent_code:n.location_info?.continent_code};try{if(e.pipelineBinding)await e.pipelineBinding.send([i]);else if(e.pipelineEndpoint){let t=e.timeout||3e4,n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let t=await fetch(e.pipelineEndpoint,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify([i]),signal:n.signal});if(!t.ok)throw Error(`Pipeline ingestion failed: ${t.status} ${t.statusText}`)}finally{clearTimeout(r)}}else throw Error(`Either pipelineEndpoint or pipelineBinding must be configured`)}catch(e){throw console.error(`Failed to send log to Pipeline:`,e),e}}function se(e){return async(t,n)=>{let r=e.namespace||`default`,i=e.tableName||`logs`,a=await T(e,`
1
+ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require("./sync-defaults-errors-Htp1NWTq.js");let l=require("@authhero/adapter-interfaces"),u=require("@hono/zod-openapi"),d=require("hono/http-exception"),f=require("wretch");f=s(f);let p=require("wretch/middlewares");var m=u.z.object({code:u.z.number(),message:u.z.string()}),h=u.z.object({message:u.z.string()}),g=u.z.object({emails:u.z.array(u.z.string()).optional(),http_body:u.z.string().optional(),http_url:u.z.string().optional(),txt_name:u.z.string().optional(),txt_value:u.z.string().optional()}),_=u.z.object({ciphers:u.z.array(u.z.string()).optional(),early_hints:u.z.string().optional(),http2:u.z.string().optional(),min_tls_version:u.z.string().optional(),tls_1_3:u.z.string().optional()}),ee=u.z.object({id:u.z.string(),bundle_method:u.z.string().optional(),certificate_authority:u.z.string(),custom_certificate:u.z.string().optional(),custom_csr_id:u.z.string().optional(),custom_key:u.z.string().optional(),expires_on:u.z.string().optional(),hosts:u.z.array(u.z.string()).optional(),issuer:u.z.string().optional(),method:u.z.string(),serial_number:u.z.string().optional(),settings:_.optional(),signature:u.z.string().optional(),type:u.z.string(),uploaded_on:u.z.string().optional(),validation_errors:u.z.array(h).optional(),validation_records:u.z.array(g).optional(),wildcard:u.z.boolean()}),te=u.z.object({name:u.z.string(),type:u.z.string(),value:u.z.string()}),ne=u.z.object({http_body:u.z.string().optional(),http_url:u.z.string().optional()}),v=u.z.object({id:u.z.string(),ssl:ee,hostname:u.z.string(),custom_metadata:u.z.record(u.z.string(),u.z.string()).optional(),custom_origin_server:u.z.string().optional(),custom_origin_sni:u.z.string().optional(),ownership_verification:te.optional(),ownership_verification_http:ne.optional(),status:u.z.string(),verification_errors:u.z.array(u.z.string()).optional(),created_at:u.z.string()}),y=u.z.object({errors:u.z.array(m),messages:u.z.array(m),success:u.z.boolean(),result:v});u.z.object({errors:u.z.array(m),messages:u.z.array(m),success:u.z.boolean(),result:u.z.array(v)});function b(e){return(0,f.default)(`https://api.cloudflare.com/client/v4/zones/${e.zoneId}`).headers({"X-Auth-Email":e.authEmail,"X-Auth-Key":e.authKey,"Content-Type":`application/json`}).middlewares([(0,p.retry)(),(0,p.dedupe)()])}function x(e){let t={},n={};if(!e)return{sslOverrides:t,rest:n};for(let[r,i]of Object.entries(e))r.startsWith(`ssl.`)?t[r.slice(4)]=i:n[r]=i;return{sslOverrides:t,rest:n}}function S(e){let t=[];if(e.ssl.validation_records)for(let n of e.ssl.validation_records)n.txt_name&&n.txt_value&&t.push({name:`txt`,record:n.txt_value,domain:n.txt_name});if(e.ownership_verification&&t.push({name:`txt`,record:e.ownership_verification.value,domain:e.ownership_verification.name}),e.ownership_verification_http?.http_body&&e.ownership_verification_http?.http_url&&t.push({name:`http`,http_body:e.ownership_verification_http.http_body,http_url:e.ownership_verification_http.http_url}),e.ssl.validation_records)for(let n of e.ssl.validation_records)n.http_body&&n.http_url&&t.push({name:`http`,http_body:n.http_body,http_url:n.http_url});let n={...e.domain_metadata||{},"ssl.method":e.ssl.method,"ssl.type":e.ssl.type,"ssl.certificate_authority":e.ssl.certificate_authority};return{custom_domain_id:e.id,domain:e.hostname,primary:e.primary,status:e.status===`active`?`ready`:`pending`,type:e.type??`auth0_managed_certs`,verification:{methods:u.z.array(l.verificationMethodsSchema).parse(t)},domain_metadata:n}}function re(e){return{create:async(t,n)=>{let{sslOverrides:r,rest:i}=x(n.domain_metadata),{result:a,errors:o,success:s}=y.parse(await b(e).post({hostname:n.domain,ssl:{method:`txt`,type:`dv`,...r},custom_metadata:e.enterprise?{tenant_id:t}:void 0},`/custom_hostnames`).json());if(!s)throw Error(JSON.stringify(o));let c=S({...a,primary:!1,type:n.type,domain_metadata:i});return await e.customDomainAdapter.create(t,{custom_domain_id:c.custom_domain_id,domain:c.domain,type:c.type,domain_metadata:n.domain_metadata}),await e.customDomainAdapter.update(t,c.custom_domain_id,{status:c.status,primary:c.primary,verification:c.verification}),c},get:async(t,n)=>{let r=await e.customDomainAdapter.get(t,n);if(!r)throw new d.HTTPException(404);let i;try{i=await b(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json()}catch(e){return console.warn(`[custom-domains] CF fetch failed for ${n} (tenant=${t}); returning stale DB row:`,e instanceof Error?e.message:e),r}let a=y.safeParse(i);if(!a.success||!a.data.success)return console.warn(`[custom-domains] CF response unparseable for ${n} (tenant=${t}); returning stale DB row.`,a.success?{cfErrors:a.data.errors}:{zodIssues:a.error.issues,body:i}),r;let{result:o}=a.data;if(e.enterprise&&o.custom_metadata?.tenant_id!==t)throw new d.HTTPException(404);let s;try{s=S({...r,...o})}catch(e){return console.warn(`[custom-domains] mapCustomDomainResponse failed for ${n} (tenant=${t}); returning stale DB row.`,e instanceof Error?e.message:e),r}if(s.status!==r.status||JSON.stringify(s.verification)!==JSON.stringify(r.verification))try{await e.customDomainAdapter.update(t,n,{status:s.status,verification:s.verification})}catch(e){console.warn(`[custom-domains] DB writeback failed for ${n} (tenant=${t}); returning merged response without DB sync.`,e instanceof Error?e.message:e)}return s},getByDomain:async t=>e.customDomainAdapter.getByDomain(t),list:async t=>e.customDomainAdapter.list(t),remove:async(t,n)=>{if(e.enterprise){let{result:r,success:i}=y.parse(await b(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json());if(!i||r.custom_metadata?.tenant_id!==t)throw new d.HTTPException(404)}let r=await b(e).delete(`/custom_hostnames/${encodeURIComponent(n)}`).res();return r.ok&&await e.customDomainAdapter.remove(t,n),r.ok},update:async(t,n,r)=>{let{sslOverrides:i}=x(r.domain_metadata),a={};if(Object.keys(i).length>0){let t;try{t=await b(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json()}catch(e){throw new d.HTTPException(503,{message:`Failed to fetch current custom hostname state: ${e instanceof Error?e.message:String(e)}`})}let r=y.safeParse(t);if(!r.success||!r.data.success)throw new d.HTTPException(503,{message:`Failed to parse current custom hostname state: ${JSON.stringify(r.success?r.data.errors:r.error.issues)}`});a.ssl={method:r.data.result.ssl.method,type:r.data.result.ssl.type,certificate_authority:r.data.result.ssl.certificate_authority,...i}}if(Object.keys(a).length>0){let t=await b(e).patch(a,`/custom_hostnames/${encodeURIComponent(n)}`).res().catch(e=>{throw new d.HTTPException(503,{message:`Failed to update custom hostname: ${e instanceof Error?e.message:String(e)}`})});if(!t.ok)throw new d.HTTPException(503,{message:await t.text()})}return e.customDomainAdapter.update(t,n,r)},uploadCertificate:async(t,n,r)=>{let i=await e.customDomainAdapter.get(t,n);if(!i)throw new d.HTTPException(404);let a=await b(e).patch({ssl:{custom_certificate:r.certificate,custom_key:r.private_key}},`/custom_hostnames/${encodeURIComponent(n)}`).json(),{result:o,errors:s,success:c}=y.parse(a);if(!c)throw new d.HTTPException(503,{message:JSON.stringify(s)});let l=S({...i,...o});return await e.customDomainAdapter.update(t,n,{status:l.status,verification:l.verification}),l}}}var C=class{config;cache=null;constructor(e){this.config=e}async getCache(){if(this.cache)return this.cache;if(typeof caches>`u`)throw Error(`caches API is not available - CloudflareCache should only be used in Cloudflare Workers`);return this.config.cacheName?this.cache=await caches.open(this.config.cacheName):this.cache=caches.default,this.cache}getKey(e){return this.config.keyPrefix?`${this.config.keyPrefix}:${e}`:e}createRequest(e){return new Request(`https://cache.internal/${this.getKey(e)}`)}async matchWithTimeout(e,t){let n=this.config.getTimeoutMs??200;return n<=0?e.match(t):new Promise(r=>{let i=setTimeout(()=>r(void 0),n);e.match(t).then(e=>{clearTimeout(i),r(e)},()=>{clearTimeout(i),r(void 0)})})}async get(e){try{let t=await this.getCache(),n=this.createRequest(e),r=await this.matchWithTimeout(t,n);if(!r)return null;let i=await r.text();if(!i)return await this.delete(e),null;let a;try{a=JSON.parse(i)}catch{return await this.delete(e),null}return a.expiresAt&&new Date(a.expiresAt)<new Date?(await this.delete(e),null):a.value}catch(t){return console.error(`CloudflareCache: get error for key ${e}:`,t),null}}async set(e,t,n){try{let r=await this.getCache(),i=n??this.config.defaultTtlSeconds,a=i!==void 0,o=a?Math.max(0,i):0,s={value:t,expiresAt:a?new Date(Date.now()+(o>0?o*1e3:-1)).toISOString():void 0,cachedAt:new Date().toISOString()},c=this.createRequest(e),l={"Content-Type":`application/json`};a&&o>0&&(l[`Cache-Control`]=`max-age=${o}`);let u=new Response(JSON.stringify(s),{headers:l});await r.put(c,u)}catch(t){console.error(`CloudflareCache: set error for key ${e}:`,t)}}async delete(e){try{let t=await this.getCache(),n=this.createRequest(e);return await t.delete(n)}catch(t){return console.error(`CloudflareCache: delete error for key ${e}:`,t),!1}}async deleteByPrefix(e){return console.warn(`CloudflareCache.deleteByPrefix() is not implemented - Cloudflare Cache API does not support prefix-based deletion`),0}async clear(){console.warn(`CloudflareCache.clear() is not implemented - Cloudflare Cache API does not support clearing all entries`)}};function ie(e={}){return new C({defaultTtlSeconds:300,keyPrefix:`authhero`,getTimeoutMs:200,...e})}var ae=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,w=(e=21)=>{let t=``,n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=ae[n[e]&63];return t};async function T(e,t){let n=e.timeout||3e4,r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=`https://api.sql.cloudflarestorage.com/api/v1/accounts/${e.accountId}/r2-sql/query/${e.warehouseName}`,i=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.authToken}`},body:JSON.stringify({query:t}),signal:r.signal});if(!i.ok)throw Error(`R2 SQL query failed: ${i.status} ${i.statusText}`);let a=await i.json();if(!a.success&&a.errors)throw Error(`R2 SQL error: ${a.errors.join(`, `)}`);return a.data||a.result?.data||[]}finally{clearTimeout(i)}}function E(e){return`'${e.replace(/'/g,`''`)}'`}function D(e){return`"${e.replace(/"/g,`""`)}"`}function O(e){let t=e=>{if(!e)return``;try{return JSON.parse(e)}catch{return e}};return{type:e.type,date:e.date,description:e.description,ip:e.ip,user_agent:e.user_agent,details:t(e.details),isMobile:!!e.isMobile,user_id:e.user_id,user_name:e.user_name,connection:e.connection,connection_id:e.connection_id,client_id:e.client_id,client_name:e.client_name,audience:e.audience,scope:e.scope,strategy:e.strategy,strategy_type:e.strategy_type,hostname:e.hostname,auth0_client:t(e.auth0_client),log_id:e.id,location_info:e.country_code||e.city_name||e.latitude||e.longitude||e.time_zone||e.continent_code?{country_code:e.country_code||``,city_name:e.city_name||``,latitude:e.latitude||``,longitude:e.longitude||``,time_zone:e.time_zone||``,continent_code:e.continent_code||``}:void 0}}function oe(e){return async(t,n)=>{let r=n.log_id||w(),i={...n,log_id:r};return await k(e,t,i),i}}async function k(e,t,n){let r=e=>e?JSON.stringify(e):void 0,i={id:n.log_id,tenant_id:t,type:n.type,date:n.date,description:n.description?.substring(0,256),ip:n.ip,user_agent:n.user_agent,details:r(n.details)?.substring(0,8192),isMobile:+!!n.isMobile,user_id:n.user_id,user_name:n.user_name,connection:n.connection,connection_id:n.connection_id,client_id:n.client_id,client_name:n.client_name,audience:n.audience,scope:n.scope,strategy:n.strategy,strategy_type:n.strategy_type,hostname:n.hostname,auth0_client:r(n.auth0_client),log_id:n.log_id,country_code:n.location_info?.country_code,city_name:n.location_info?.city_name,latitude:n.location_info?.latitude,longitude:n.location_info?.longitude,time_zone:n.location_info?.time_zone,continent_code:n.location_info?.continent_code};try{if(e.pipelineBinding)await e.pipelineBinding.send([i]);else if(e.pipelineEndpoint){let t=e.timeout||3e4,n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let t=await fetch(e.pipelineEndpoint,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify([i]),signal:n.signal});if(!t.ok)throw Error(`Pipeline ingestion failed: ${t.status} ${t.statusText}`)}finally{clearTimeout(r)}}else throw Error(`Either pipelineEndpoint or pipelineBinding must be configured`)}catch(e){throw console.error(`Failed to send log to Pipeline:`,e),e}}function se(e){return async(t,n)=>{let r=e.namespace||`default`,i=e.tableName||`logs`,a=await T(e,`
2
2
  SELECT * FROM ${D(r)}.${D(i)}
3
3
  WHERE tenant_id = ${E(t)}
4
4
  AND id = ${E(n)}
@@ -72,25 +72,9 @@ const fnNames = {
72
72
  "post-user-registration": "onExecutePostUserRegistration",
73
73
  };
74
74
 
75
- const apiShapes = {
76
- "post-user-login": {
77
- accessToken: ["setCustomClaim"],
78
- idToken: ["setCustomClaim"],
79
- access: ["deny"],
80
- prompt: ["render"],
81
- redirect: ["sendUserTo"],
82
- },
83
- "credentials-exchange": {
84
- accessToken: ["setCustomClaim"],
85
- idToken: ["setCustomClaim"],
86
- access: ["deny"],
87
- },
88
- "pre-user-registration": {
89
- user: ["setUserMetadata", "setLinkedTo"],
90
- access: ["deny"],
91
- },
92
- "post-user-registration": {},
93
- };
75
+ // Shared source of truth for the per-trigger API allowlist — see
76
+ // TRIGGER_API_SHAPES in @authhero/adapter-interfaces.
77
+ const apiShapes = ${JSON.stringify(l.TRIGGER_API_SHAPES)};
94
78
 
95
79
  function createRecordingApiProxy(triggerId) {
96
80
  const calls = [];
@@ -166,7 +150,7 @@ export default {
166
150
  }
167
151
  },
168
152
  };
169
- `}var Z=class{config;constructor(e){this.config=e}async execute(e){let t=Date.now();if(!e.hookCodeId)return{success:!1,error:`DispatchNamespaceCodeExecutor requires hookCodeId`,durationMs:Date.now()-t,apiCalls:[]};let n=`hook-${e.hookCodeId}`,r=JSON.stringify({triggerId:e.triggerId,event:e.event});try{let i;if(this.config.dispatcher)i=await this.config.dispatcher.get(n,{},{limits:{cpuMs:e.cpuLimitMs??5e3}}).fetch(new Request(`https://hook.internal/execute`,{method:`POST`,headers:{"Content-Type":`application/json`},body:r}));else if(this.config.dispatchUrl)i=await fetch(`${this.config.dispatchUrl}/${n}`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.config.apiToken}`},body:r});else return{success:!1,error:`No dispatcher binding or dispatchUrl configured`,durationMs:Date.now()-t,apiCalls:[]};if(!i.ok){let e=await i.text();return{success:!1,error:`Worker invocation failed (${i.status}): ${e}`,durationMs:Date.now()-t,apiCalls:[]}}return{...await i.json(),durationMs:Date.now()-t}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t,apiCalls:[]}}}async deploy(e,t){let n=`hook-${e}`,r=X(t),i=`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/workers/dispatch/namespaces/${this.config.dispatchNamespace}/scripts/${n}`,a=JSON.stringify({main_module:`index.js`,compatibility_date:this.config.compatibilityDate??`2024-11-20`}),o=new FormData;o.append(`metadata`,new Blob([a],{type:`application/json`})),o.append(`index.js`,new Blob([r],{type:`application/javascript+module`}),`index.js`);let s=await fetch(i,{method:`PUT`,headers:{Authorization:`Bearer ${this.config.apiToken}`},body:o});if(!s.ok){let e=await s.text();throw Error(`Failed to deploy hook worker ${n}: ${s.status} ${e}`)}}async remove(e){let t=`hook-${e}`,n=`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/workers/dispatch/namespaces/${this.config.dispatchNamespace}/scripts/${t}`,r=await fetch(n,{method:`DELETE`,headers:{Authorization:`Bearer ${this.config.apiToken}`}});if(!r.ok&&r.status!==404){let e=await r.text();throw Error(`Failed to remove hook worker ${t}: ${r.status} ${e}`)}}},ze=Z,Be={"post-user-login":`onExecutePostLogin`,"credentials-exchange":`onExecuteCredentialsExchange`,"pre-user-registration":`onExecutePreUserRegistration`,"post-user-registration":`onExecutePostUserRegistration`},Ve={"post-user-login":{accessToken:[`setCustomClaim`],idToken:[`setCustomClaim`],access:[`deny`],prompt:[`render`],redirect:[`sendUserTo`]},"credentials-exchange":{accessToken:[`setCustomClaim`],idToken:[`setCustomClaim`],access:[`deny`]},"pre-user-registration":{user:[`setUserMetadata`,`setLinkedTo`],access:[`deny`]},"post-user-registration":{}};async function He(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t),r=new Uint8Array(n),i=``;for(let e of r)i+=e.toString(16).padStart(2,`0`);return i}function Ue(e){return`
153
+ `}var Z=class{config;constructor(e){this.config=e}async execute(e){let t=Date.now();if(!e.hookCodeId)return{success:!1,error:`DispatchNamespaceCodeExecutor requires hookCodeId`,durationMs:Date.now()-t,apiCalls:[]};let n=`hook-${e.hookCodeId}`,r=JSON.stringify({triggerId:e.triggerId,event:e.event});try{let i;if(this.config.dispatcher)i=await this.config.dispatcher.get(n,{},{limits:{cpuMs:e.cpuLimitMs??5e3}}).fetch(new Request(`https://hook.internal/execute`,{method:`POST`,headers:{"Content-Type":`application/json`},body:r}));else if(this.config.dispatchUrl)i=await fetch(`${this.config.dispatchUrl}/${n}`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.config.apiToken}`},body:r});else return{success:!1,error:`No dispatcher binding or dispatchUrl configured`,durationMs:Date.now()-t,apiCalls:[]};if(!i.ok){let e=await i.text();return{success:!1,error:`Worker invocation failed (${i.status}): ${e}`,durationMs:Date.now()-t,apiCalls:[]}}return{...await i.json(),durationMs:Date.now()-t}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t,apiCalls:[]}}}async deploy(e,t){let n=`hook-${e}`,r=X(t),i=`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/workers/dispatch/namespaces/${this.config.dispatchNamespace}/scripts/${n}`,a=JSON.stringify({main_module:`index.js`,compatibility_date:this.config.compatibilityDate??`2024-11-20`}),o=new FormData;o.append(`metadata`,new Blob([a],{type:`application/json`})),o.append(`index.js`,new Blob([r],{type:`application/javascript+module`}),`index.js`);let s=await fetch(i,{method:`PUT`,headers:{Authorization:`Bearer ${this.config.apiToken}`},body:o});if(!s.ok){let e=await s.text();throw Error(`Failed to deploy hook worker ${n}: ${s.status} ${e}`)}}async remove(e){let t=`hook-${e}`,n=`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/workers/dispatch/namespaces/${this.config.dispatchNamespace}/scripts/${t}`,r=await fetch(n,{method:`DELETE`,headers:{Authorization:`Bearer ${this.config.apiToken}`}});if(!r.ok&&r.status!==404){let e=await r.text();throw Error(`Failed to remove hook worker ${t}: ${r.status} ${e}`)}}},ze=Z,Be={"post-user-login":`onExecutePostLogin`,"credentials-exchange":`onExecuteCredentialsExchange`,"pre-user-registration":`onExecutePreUserRegistration`,"post-user-registration":`onExecutePostUserRegistration`},Ve=l.TRIGGER_API_SHAPES;async function He(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t),r=new Uint8Array(n),i=``;for(let e of r)i+=e.toString(16).padStart(2,`0`);return i}function Ue(e){return`
170
154
  const TRIGGER_FN_NAMES = ${JSON.stringify(Be)};
171
155
  const API_SHAPES = ${JSON.stringify(Ve)};
172
156
  const MAX_LOG_ENTRIES = 50;
@@ -266,4 +250,4 @@ export default {
266
250
  }
267
251
  },
268
252
  };
269
- `}var We=class{loader;compatibilityDate;constructor(e){this.loader=e.loader,this.compatibilityDate=e.compatibilityDate||`2025-01-01`}async execute(e){let t=Date.now();try{let t=Ue(e.code),n={compatibilityDate:this.compatibilityDate,mainModule:`hook.js`,modules:{"hook.js":t}},r=e.hookCodeId?`${e.hookCodeId}-${await He(e.code)}`:null;return await(await(r?this.loader.get(r,async()=>n):this.loader.load(n)).getEntrypoint().fetch(new Request(`https://hook/execute`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({event:e.event,triggerId:e.triggerId})}))).json()}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t,apiCalls:[]}}}};function Q(e){let t=c.n(e);return{async onProvision(e){let{scriptName:n,databaseName:r}=t.names(e),{databaseVersion:i,bundleConfiguration:a,workerVersion:o}=t.validate(),{id:s,created:c}=await t.findOrCreateDatabase(r);return await t.applyMigrations(s,c),await t.uploadScript(n,s),await t.uploadSecrets(n,e),{d1DatabaseId:s,scriptName:n,d1Name:r,bundleConfiguration:a,workerVersion:o,databaseVersion:i}},async onDeprovision(e){await t.deprovision(e)}}}function Ge(e){return e.deployment_type===`wfp`}var Ke=2048;function $(e){let t;if(e instanceof Error)t=e.message;else try{t=String(e)}catch{t=Object.prototype.toString.call(e)}return t.slice(0,Ke)}function qe(e){let{provisioner:t,tenants:n,syncDefaults:r}=e,i=e.shouldProvision??Ge,a=e.logger;async function o(e,t){try{await n.update(e,{provisioning_state:`failed`,provisioning_error:$(t),provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="failed" for tenant ${e}:`,t)}}async function s(e,i){let s=async(t,n,r)=>{if(i)try{await i(t,n,r)}catch(n){a?.warn(`Failed to report provisioning step "${t}" for tenant ${e}:`,n)}};await s(`provision-resources`,`started`);let l;try{l=await t.onProvision(e)}catch(t){throw await s(`provision-resources`,`failed`,{message:$(t)}),await o(e,t),t}let u={d1_database_id:l.d1DatabaseId,worker_script_name:l.scriptName,bundle_configuration:l.bundleConfiguration,worker_version:l.workerVersion,database_version:l.databaseVersion};await s(`provision-resources`,`succeeded`,{...u});try{if(r){await s(`seed-defaults`,`started`);try{let t=c.t(await r(e));if(t.length>0)throw Error(`sync-defaults seed reported ${t.length} error(s): ${t.join(`; `)}`);await s(`seed-defaults`,`succeeded`)}catch(e){throw await s(`seed-defaults`,`failed`,{message:$(e)}),e}}await n.update(e,{...u,provisioning_state:`ready`,provisioning_error:void 0,provisioning_state_changed_at:new Date().toISOString()})}catch(t){try{await n.update(e,{...u,provisioning_state:`failed`,provisioning_error:$(t),provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="failed" for tenant ${e}:`,t)}throw t}}return{async onProvision(e,t){let r=await n.get(e);r&&i(r)&&await s(e,t)},async onUpgrade(e,t){let r=await n.get(e);if(!r)throw Error(`Cannot upgrade tenant "${e}": not found.`);if(!i(r))throw Error(`Cannot upgrade tenant "${e}": not a WFP-provisioned tenant.`);try{await n.update(e,{provisioning_state:`pending`,provisioning_error:void 0,provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="pending" for tenant ${e}:`,t)}await s(e,t)},async onDeprovision(e){let r=await n.get(e);r&&!i(r)||await t.onDeprovision(e)}}}var Je=`DISPATCHER`,Ye=`tenant-{tenant_id}-auth`;function Xe(e){return typeof e==`object`&&!!e&&`get`in e&&typeof Reflect.get(e,`get`)==`function`}function Ze(e,t){return e.replace(/\{tenant_id\}/g,t)}function Qe(e){let{tenants:t,controlPlaneTenantId:n,dispatcherBinding:r=Je,scriptNameTemplate:i=Ye,resolveTenantId:a=e=>e.req.header(`tenant-id`)}=e;return async(e,o)=>{let s=await a(e);if(!s||s===n)return o();let c=await t.get(s);if(!c||c.deployment_type!==`wfp`||c.provisioning_state&&c.provisioning_state!==`ready`)return o();let l=Reflect.get(e.env??{},r);if(!Xe(l))return o();let u=Ze(i,s),d;try{d=await l.get(u).fetch(e.req.raw)}catch(t){let n=t instanceof Error?t.message:String(t),r=/not\s*found|no\s*such|does not exist/i.test(n),i=r?`wfp_worker_not_found`:`wfp_dispatch_failed`;return console.error(`[wfp-forward] ${i} tenant=${s} script=${u}: ${n}`),e.header(`X-Authhero-Error`,i),e.header(`X-Wfp-Tenant`,s),e.json({error:i,detail:r?`Tenant '${s}' is marked ready but its worker '${u}' is not deployed in the dispatch namespace.`:`The worker for tenant '${s}' could not be reached.`,tenant_id:s},r?503:502)}if(d.status>=500){let e=d.headers.get(`X-Authhero-Error`);console.error(`[wfp-forward] tenant worker ${d.status}${e?` (${e})`:``} tenant=${s} script=${u}`)}let f=Reflect.get(d,`webSocket`);if(d.status===101||f!=null)return d;let p=new Response(d.body,d);return p.headers.set(`X-Wfp-Tenant`,s),p}}function $e(e){let t={customDomains:re(e),cache:ie({...e.cacheName&&{cacheName:e.cacheName},...e.defaultTtlSeconds!==void 0&&{defaultTtlSeconds:e.defaultTtlSeconds},...e.keyPrefix&&{keyPrefix:e.keyPrefix}}),geo:Le()};e.r2SqlLogs?t.logs=A(e.r2SqlLogs):e.analyticsEngineLogs&&(t.logs=W(e.analyticsEngineLogs)),e.analyticsEngineLogs&&(t.analytics=U(e.analyticsEngineLogs)),e.analyticsEngineActionExecutions&&(t.actionExecutions=J(e.analyticsEngineActionExecutions));let n=Y(e.rateLimitBindings);return n&&(t.rateLimit=n),t}exports.CloudflareApiClient=c.i,exports.CloudflareApiError=c.a,exports.CloudflareCodeExecutor=ze,exports.DispatchNamespaceCodeExecutor=Z,exports.WorkerLoaderCodeExecutor=We,exports.createAnalyticsEngineActionExecutionsAdapter=J,exports.createAnalyticsEngineAnalyticsAdapter=U,exports.createAnalyticsEngineLogsAdapter=W,exports.createAnalyticsEngineStatsAdapter=be,exports.createCloudflareRateLimitAdapter=Y,exports.createCloudflareWfpD1Provisioner=Q,exports.createR2SQLLogsAdapter=A,exports.createR2SQLStatsAdapter=de,exports.createWfpForwardMiddleware=Qe,exports.createWfpProvisionerSteps=c.n,exports.createWfpTenantProvisioningHook=qe,exports.default=$e,exports.generateWorkerScript=X;
253
+ `}var We=class{loader;compatibilityDate;constructor(e){this.loader=e.loader,this.compatibilityDate=e.compatibilityDate||`2025-01-01`}async execute(e){let t=Date.now();try{let t=Ue(e.code),n={compatibilityDate:this.compatibilityDate,mainModule:`hook.js`,modules:{"hook.js":t}},r=e.hookCodeId?`${e.hookCodeId}-${await He(e.code)}`:null;return await(await(r?this.loader.get(r,async()=>n):this.loader.load(n)).getEntrypoint().fetch(new Request(`https://hook/execute`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({event:e.event,triggerId:e.triggerId})}))).json()}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t,apiCalls:[]}}}};function Q(e){let t=c.n(e);return{async onProvision(e){let{scriptName:n,databaseName:r}=t.names(e),{databaseVersion:i,bundleConfiguration:a,workerVersion:o}=t.validate(),{id:s,created:c}=await t.findOrCreateDatabase(r);return await t.applyMigrations(s,c),await t.uploadScript(n,s),await t.uploadSecrets(n,e),{d1DatabaseId:s,scriptName:n,d1Name:r,bundleConfiguration:a,workerVersion:o,databaseVersion:i}},async onDeprovision(e){await t.deprovision(e)}}}function Ge(e){return e.deployment_type===`wfp`}var Ke=2048;function $(e){let t;if(e instanceof Error)t=e.message;else try{t=String(e)}catch{t=Object.prototype.toString.call(e)}return t.slice(0,Ke)}function qe(e){let{provisioner:t,tenants:n,syncDefaults:r}=e,i=e.shouldProvision??Ge,a=e.logger;async function o(e,t){try{await n.update(e,{provisioning_state:`failed`,provisioning_error:$(t),provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="failed" for tenant ${e}:`,t)}}async function s(e,i){let s=async(t,n,r)=>{if(i)try{await i(t,n,r)}catch(n){a?.warn(`Failed to report provisioning step "${t}" for tenant ${e}:`,n)}};await s(`provision-resources`,`started`);let l;try{l=await t.onProvision(e)}catch(t){throw await s(`provision-resources`,`failed`,{message:$(t)}),await o(e,t),t}let u={d1_database_id:l.d1DatabaseId,worker_script_name:l.scriptName,bundle_configuration:l.bundleConfiguration,worker_version:l.workerVersion,database_version:l.databaseVersion};await s(`provision-resources`,`succeeded`,{...u});try{if(r){await s(`seed-defaults`,`started`);try{let t=c.t(await r(e));if(t.length>0)throw Error(`sync-defaults seed reported ${t.length} error(s): ${t.join(`; `)}`);await s(`seed-defaults`,`succeeded`)}catch(e){throw await s(`seed-defaults`,`failed`,{message:$(e)}),e}}await n.update(e,{...u,provisioning_state:`ready`,provisioning_error:void 0,provisioning_state_changed_at:new Date().toISOString()})}catch(t){try{await n.update(e,{...u,provisioning_state:`failed`,provisioning_error:$(t),provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="failed" for tenant ${e}:`,t)}throw t}}return{async onProvision(e,t){let r=await n.get(e);r&&i(r)&&await s(e,t)},async onUpgrade(e,t){let r=await n.get(e);if(!r)throw Error(`Cannot upgrade tenant "${e}": not found.`);if(!i(r))throw Error(`Cannot upgrade tenant "${e}": not a WFP-provisioned tenant.`);try{await n.update(e,{provisioning_state:`pending`,provisioning_error:void 0,provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="pending" for tenant ${e}:`,t)}await s(e,t)},async onDeprovision(e){let r=await n.get(e);r&&!i(r)||await t.onDeprovision(e)}}}var Je=`DISPATCHER`,Ye=`tenant-{tenant_id}-auth`,Xe=[`/u/widget/`];function Ze(e){return typeof e==`object`&&!!e&&`get`in e&&typeof Reflect.get(e,`get`)==`function`}function Qe(e,t){return e.replace(/\{tenant_id\}/g,t)}function $e(e){let{tenants:t,controlPlaneTenantId:n,dispatcherBinding:r=Je,scriptNameTemplate:i=Ye,resolveTenantId:a=e=>e.req.header(`tenant-id`),localPaths:o=Xe}=e;return async(e,s)=>{if(o.length>0){let t=e.req.path;if(o.some(e=>t.startsWith(e)))return s()}let c=await a(e);if(!c||c===n)return s();let l=await t.get(c);if(!l||l.deployment_type!==`wfp`||l.provisioning_state&&l.provisioning_state!==`ready`)return s();let u=Reflect.get(e.env??{},r);if(!Ze(u))return s();let d=Qe(i,c),f;try{f=await u.get(d).fetch(e.req.raw)}catch(t){let n=t instanceof Error?t.message:String(t),r=/not\s*found|no\s*such|does not exist/i.test(n),i=r?`wfp_worker_not_found`:`wfp_dispatch_failed`;return console.error(`[wfp-forward] ${i} tenant=${c} script=${d}: ${n}`),e.header(`X-Authhero-Error`,i),e.header(`X-Wfp-Tenant`,c),e.json({error:i,detail:r?`Tenant '${c}' is marked ready but its worker '${d}' is not deployed in the dispatch namespace.`:`The worker for tenant '${c}' could not be reached.`,tenant_id:c},r?503:502)}if(f.status>=500){let e=f.headers.get(`X-Authhero-Error`);console.error(`[wfp-forward] tenant worker ${f.status}${e?` (${e})`:``} tenant=${c} script=${d}`)}let p=Reflect.get(f,`webSocket`);if(f.status===101||p!=null)return f;let m=new Response(f.body,f);return m.headers.set(`X-Wfp-Tenant`,c),m}}function et(e){let t={customDomains:re(e),cache:ie({...e.cacheName&&{cacheName:e.cacheName},...e.defaultTtlSeconds!==void 0&&{defaultTtlSeconds:e.defaultTtlSeconds},...e.keyPrefix&&{keyPrefix:e.keyPrefix}}),geo:Le()};e.r2SqlLogs?t.logs=A(e.r2SqlLogs):e.analyticsEngineLogs&&(t.logs=W(e.analyticsEngineLogs)),e.analyticsEngineLogs&&(t.analytics=U(e.analyticsEngineLogs)),e.analyticsEngineActionExecutions&&(t.actionExecutions=J(e.analyticsEngineActionExecutions));let n=Y(e.rateLimitBindings);return n&&(t.rateLimit=n),t}exports.CloudflareApiClient=c.i,exports.CloudflareApiError=c.a,exports.CloudflareCodeExecutor=ze,exports.DispatchNamespaceCodeExecutor=Z,exports.WorkerLoaderCodeExecutor=We,exports.createAnalyticsEngineActionExecutionsAdapter=J,exports.createAnalyticsEngineAnalyticsAdapter=U,exports.createAnalyticsEngineLogsAdapter=W,exports.createAnalyticsEngineStatsAdapter=be,exports.createCloudflareRateLimitAdapter=Y,exports.createCloudflareWfpD1Provisioner=Q,exports.createR2SQLLogsAdapter=A,exports.createR2SQLStatsAdapter=de,exports.createWfpForwardMiddleware=$e,exports.createWfpProvisionerSteps=c.n,exports.createWfpTenantProvisioningHook=qe,exports.default=et,exports.generateWorkerScript=X;
@@ -1029,6 +1029,18 @@ interface WfpForwardOptions {
1029
1029
  * subdomain or custom domain. Return `undefined` to fall through locally.
1030
1030
  */
1031
1031
  resolveTenantId?: (c: Context) => string | undefined | Promise<string | undefined>;
1032
+ /**
1033
+ * Request path prefixes that are **never** dispatched to a tenant worker,
1034
+ * even for a fully-provisioned `wfp` tenant. Matching requests fall through
1035
+ * to the local (control-plane) app so it serves them from its own assets /
1036
+ * handlers.
1037
+ *
1038
+ * Use this for shared static assets that only the control plane can serve —
1039
+ * a per-tenant dispatch worker has no static-assets binding. Defaults to
1040
+ * `["/u/widget/"]` (the universal-login widget bundle); pass `[]` to disable
1041
+ * the carve-out entirely, or extend the list for other shared assets.
1042
+ */
1043
+ localPaths?: string[];
1032
1044
  }
1033
1045
  /**
1034
1046
  * Hono middleware that forwards a request to its tenant's WFP worker over a
@@ -1043,6 +1055,10 @@ interface WfpForwardOptions {
1043
1055
  * dispatching to a not-yet-deployed worker would only hard-fail the request.
1044
1056
  * The tenant worker receives the original request verbatim and owns the full
1045
1057
  * response.
1058
+ *
1059
+ * Requests whose path matches `localPaths` (default `["/u/widget/"]`) are also
1060
+ * never dispatched — they are shared static assets that only the control plane
1061
+ * can serve, so a per-tenant worker would 404 them. See `DEFAULT_LOCAL_PATHS`.
1046
1062
  */
1047
1063
  declare function createWfpForwardMiddleware(options: WfpForwardOptions): MiddlewareHandler;
1048
1064