@gfargo/doorman 3.11.0 → 3.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/run.js CHANGED
@@ -1,53 +1,54 @@
1
- "use strict";var Fo=Object.create;var pt=Object.defineProperty;var No=Object.getOwnPropertyDescriptor;var Vo=Object.getOwnPropertyNames;var Bo=Object.getPrototypeOf,Wo=Object.prototype.hasOwnProperty;var qe=(i,e)=>()=>(i&&(e=i(i=0)),e);var M=(i,e)=>{for(var t in e)pt(i,t,{get:e[t],enumerable:!0})},hi=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Vo(e))!Wo.call(i,n)&&n!==t&&pt(i,n,{get:()=>e[n],enumerable:!(o=No(e,n))||o.enumerable});return i};var S=(i,e,t)=>(t=i!=null?Fo(Bo(i)):{},hi(e||!i||!i.__esModule?pt(t,"default",{value:i,enumerable:!0}):t,i)),ye=i=>hi(pt({},"__esModule",{value:!0}),i);var yi,r,T=qe(()=>{"use strict";yi=require("consola"),r=(0,yi.createConsola)({formatOptions:{colors:!0,compact:!0,date:!1}})});var Ii,w,pe=qe(()=>{"use strict";Ii=S(require("consola")),w=async(i,e)=>{let t=await Ii.default.prompt(i,e);return t!=null&&t.toString()==="Symbol(clack:cancel)"&&process.exit(0),(!e?.type||e.type==="text")&&t===void 0?"":t}});function mn(i,e){return e?.ctrl&&e.name==="c"?{type:"cancel"}:e?.name==="return"||e?.name==="enter"?{type:"submit"}:e?.name==="backspace"?{type:"backspace"}:i&&!e?.ctrl&&!e?.meta&&i.length===1&&i>=" "?{type:"append",char:i}:{type:"ignore"}}function hn(i,e){switch(e.type){case"append":return{value:i+e.char,done:!1,cancelled:!1,echo:"add"};case"backspace":return i.length===0?{value:i,done:!1,cancelled:!1,echo:"none"}:{value:i.slice(0,-1),done:!1,cancelled:!1,echo:"remove"};case"submit":return{value:i,done:!0,cancelled:!1,echo:"none"};case"cancel":return{value:i,done:!0,cancelled:!0,echo:"none"};case"ignore":return{value:i,done:!1,cancelled:!1,echo:"none"}}}async function rt(i){if(process.stdout.write(i),!process.stdin.isTTY){let{createInterface:e}=await import("readline"),t=e({input:process.stdin,output:process.stdout,terminal:!1});return new Promise(o=>{t.question("",n=>{t.close(),o(n)})})}return new Promise(e=>{let t=process.stdin,o=t.isRaw;(0,Bi.emitKeypressEvents)(t),t.setRawMode(!0),t.resume();let n="",s=()=>{t.removeListener("keypress",a),t.setRawMode(o??!1)},a=(l,c)=>{let d=mn(l,c),u=hn(n,d);n=u.value,u.echo==="add"?process.stdout.write("*"):u.echo==="remove"&&process.stdout.write("\b \b"),u.done&&(s(),process.stdout.write(`
2
- `),u.cancelled&&process.exit(0),e(n))};t.on("keypress",a)})}var Bi,jt=qe(()=>{"use strict";Bi=require("readline")});var De={};M(De,{TranslationWarningSystem:()=>O});var O,fe=qe(()=>{"use strict";O=class i{static DOCS_BASE_URL="https://docs.doorman.griffen.codes";static WARNING_CONFIGS={managed_rules:{category:"feature_unsupported",severity:"critical",explanation:"Managed rules are provider-specific security rules that cannot be directly translated between platforms.",suggestion:"Replace with custom rules using equivalent conditions and actions.",alternativeApproach:"Create custom rules that match the same traffic patterns using standard conditions like IP, country, user agent, or request headers.",impact:"Security coverage may be reduced until equivalent custom rules are implemented.",docsUrl:`${i.DOCS_BASE_URL}/migration/managed-rules`},bot_management:{category:"feature_unsupported",severity:"critical",explanation:"Bot management features use provider-specific detection algorithms that cannot be translated.",suggestion:"Configure bot management separately in the target provider.",alternativeApproach:"Use user agent filtering, rate limiting, and challenge actions to implement basic bot protection.",impact:"Bot protection effectiveness may vary between providers.",docsUrl:`${i.DOCS_BASE_URL}/migration/bot-management`},complex_expressions:{category:"lossy_conversion",severity:"warning",explanation:"Complex expressions may not translate perfectly due to differences in syntax and supported operators between providers.",suggestion:"Review translated expressions and test thoroughly before deploying.",alternativeApproach:"Break complex expressions into simpler, more portable conditions.",impact:"Rule behavior may differ slightly from the original configuration.",docsUrl:`${i.DOCS_BASE_URL}/migration/expressions`},geo_blocking:{category:"lossy_conversion",severity:"warning",explanation:"Geographic blocking may use different country codes or geographic databases between providers.",suggestion:"Verify country codes and geographic targeting after translation.",alternativeApproach:"Use ISO country codes when possible for better compatibility.",impact:"Some geographic regions may be blocked or allowed differently than intended.",docsUrl:`${i.DOCS_BASE_URL}/migration/geo-blocking`},rate_limiting_precision:{category:"lossy_conversion",severity:"info",explanation:"Rate limiting configurations may be adjusted to match the target provider's supported time windows and request thresholds.",suggestion:"Review rate limiting settings and adjust if necessary.",alternativeApproach:"Use the closest supported time window and request threshold values.",impact:"Rate limiting may be slightly more or less restrictive than the original configuration.",docsUrl:`${i.DOCS_BASE_URL}/migration/rate-limiting`},regex_patterns:{category:"syntax_limitation",severity:"warning",explanation:"Regular expression patterns may have different syntax requirements or feature support between providers.",suggestion:"Test regex patterns in the target provider and adjust syntax if needed.",alternativeApproach:"Use simpler string matching operations (contains, starts_with, ends_with) when possible.",impact:"Pattern matching may behave differently or fail to match intended traffic.",docsUrl:`${i.DOCS_BASE_URL}/migration/regex-patterns`},header_manipulation:{category:"syntax_limitation",severity:"warning",explanation:"Header manipulation capabilities vary between providers in terms of supported headers and modification types.",suggestion:"Verify header modification support in the target provider.",alternativeApproach:"Use redirect rules or custom error pages to achieve similar functionality.",impact:"Header modifications may not work as expected or may be ignored.",docsUrl:`${i.DOCS_BASE_URL}/migration/headers`},large_ip_lists:{category:"performance_impact",severity:"info",explanation:"Large IP lists may impact rule evaluation performance differently between providers.",suggestion:"Consider using provider-specific IP list features for better performance.",alternativeApproach:"Break large IP lists into smaller, more targeted rules or use CIDR notation to reduce list size.",impact:"Rule evaluation may be slower with large IP lists, potentially affecting site performance.",docsUrl:`${i.DOCS_BASE_URL}/migration/ip-lists`},many_conditions:{category:"performance_impact",severity:"info",explanation:"Rules with many conditions may have different performance characteristics between providers.",suggestion:"Monitor rule performance and consider optimizing complex rules.",alternativeApproach:"Split complex rules into multiple simpler rules or use more efficient condition types.",impact:"Complex rules may impact request processing speed.",docsUrl:`${i.DOCS_BASE_URL}/migration/rule-optimization`},action_differences:{category:"security_consideration",severity:"warning",explanation:"Security actions (block, challenge, etc.) may behave differently between providers in terms of user experience and effectiveness.",suggestion:"Test security actions thoroughly and adjust based on provider capabilities.",alternativeApproach:"Use the most appropriate equivalent action available in the target provider.",impact:"Security effectiveness and user experience may differ from the original configuration.",docsUrl:`${i.DOCS_BASE_URL}/migration/security-actions`},challenge_types:{category:"security_consideration",severity:"info",explanation:"Challenge types (CAPTCHA, JavaScript, etc.) vary between providers and may affect user experience.",suggestion:"Choose challenge types that balance security and user experience for your use case.",alternativeApproach:"Use the provider's recommended challenge type for your security requirements.",impact:"User experience during security challenges may vary.",docsUrl:`${i.DOCS_BASE_URL}/migration/challenges`},version_compatibility:{category:"compatibility_issue",severity:"warning",explanation:"Some features may only be available in specific provider plan tiers or API versions.",suggestion:"Verify feature availability in your target provider plan.",alternativeApproach:"Use alternative features available in your plan tier.",impact:"Some rules may not work as expected if required features are unavailable.",docsUrl:`${i.DOCS_BASE_URL}/migration/compatibility`},plan_limitations:{category:"compatibility_issue",severity:"critical",explanation:"Your current plan may not support all features being translated.",suggestion:"Upgrade your plan or modify rules to use available features.",alternativeApproach:"Implement equivalent functionality using features available in your current plan.",impact:"Rules may be rejected or ignored if they use unavailable features.",docsUrl:`${i.DOCS_BASE_URL}/migration/plan-limits`}};static createWarning(e,t,o,n,s){let a=this.WARNING_CONFIGS[e];return a?{rule:t,field:o,category:a.category,message:n||`${e.replace(/_/g," ")} translation issue`,explanation:a.explanation,severity:a.severity,suggestion:s||a.suggestion,alternativeApproach:a.alternativeApproach,impact:a.impact,docsUrl:a.docsUrl}:{rule:t,field:o,category:"compatibility_issue",message:n||`Unknown translation issue: ${e}`,explanation:"This translation scenario is not fully documented.",severity:"warning",suggestion:s||"Review the translated configuration manually and test thoroughly.",docsUrl:`${this.DOCS_BASE_URL}/migration/troubleshooting`}}static createUnsupportedFeatureWarning(e,t,o,n,s){return{rule:n,field:s,category:"feature_unsupported",message:`${e} is not supported in ${o}`,explanation:`The ${e} feature from ${t} cannot be directly translated to ${o} due to platform differences.`,severity:"critical",suggestion:`Remove or replace ${e} with equivalent functionality supported by ${o}.`,alternativeApproach:`Check ${o} documentation for similar features or use custom rules to achieve equivalent functionality.`,impact:"This rule may not work as expected or may be ignored entirely.",docsUrl:`${this.DOCS_BASE_URL}/migration/unsupported-features`}}static createLossyConversionWarning(e,t,o,n){return{rule:o,field:n,category:"lossy_conversion",message:`${e} translation may be lossy`,explanation:`The ${e} configuration cannot be perfectly translated: ${t}`,severity:"warning",suggestion:"Review the translated configuration and test thoroughly to ensure it behaves as expected.",alternativeApproach:"Consider simplifying the configuration or using more portable alternatives.",impact:"The translated rule may behave differently than the original.",docsUrl:`${this.DOCS_BASE_URL}/migration/lossy-conversions`}}static createSyntaxLimitationWarning(e,t,o,n){return{rule:o,field:n,category:"syntax_limitation",message:`${e} has syntax limitations`,explanation:`The ${e} syntax has been modified due to provider limitations: ${t}`,severity:"warning",suggestion:"Verify the translated syntax works correctly in the target provider.",alternativeApproach:"Use simpler syntax or alternative approaches that are more widely supported.",impact:"The rule may not match traffic as precisely as intended.",docsUrl:`${this.DOCS_BASE_URL}/migration/syntax-limitations`}}static createPerformanceWarning(e,t,o,n){return{rule:o,field:n,category:"performance_impact",message:`${e} may impact performance`,explanation:`The ${e} configuration may have performance implications: ${t}`,severity:"info",suggestion:"Monitor performance after deployment and optimize if necessary.",alternativeApproach:"Consider using more efficient alternatives or breaking complex rules into simpler ones.",impact:"Request processing may be slower than expected.",docsUrl:`${this.DOCS_BASE_URL}/migration/performance`}}static formatWarning(e){let o={critical:"\u{1F6A8}",warning:"\u26A0\uFE0F",info:"\u2139\uFE0F"}[e.severity],n=e.rule?` (Rule: ${e.rule}${e.field?`, Field: ${e.field}`:""})`:"",s=`${o} ${e.severity.toUpperCase()}: ${e.message}${n}
1
+ "use strict";var Wn=Object.create;var gt=Object.defineProperty;var jn=Object.getOwnPropertyDescriptor;var qn=Object.getOwnPropertyNames;var zn=Object.getPrototypeOf,Mn=Object.prototype.hasOwnProperty;var qe=(i,e)=>()=>(i&&(e=i(i=0)),e);var M=(i,e)=>{for(var t in e)gt(i,t,{get:e[t],enumerable:!0})},wi=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of qn(e))!Mn.call(i,o)&&o!==t&&gt(i,o,{get:()=>e[o],enumerable:!(n=jn(e,o))||n.enumerable});return i};var S=(i,e,t)=>(t=i!=null?Wn(zn(i)):{},wi(e||!i||!i.__esModule?gt(t,"default",{value:i,enumerable:!0}):t,i)),ye=i=>wi(gt({},"__esModule",{value:!0}),i);var Ii,r,T=qe(()=>{"use strict";Ii=require("consola"),r=(0,Ii.createConsola)({formatOptions:{colors:!0,compact:!0,date:!1}})});var Ci,w,pe=qe(()=>{"use strict";Ci=S(require("consola")),w=async(i,e)=>{if(!process.stdin.isTTY)throw new Error(`Cannot prompt for "${i}" \u2014 no interactive terminal available. Re-run with the appropriate non-interactive flag for this command (e.g. --interactive=false, --ci, --force).`);let t=await Ci.default.prompt(i,e);return t!=null&&t.toString()==="Symbol(clack:cancel)"&&process.exit(0),(!e?.type||e.type==="text")&&t===void 0?"":t}});function Io(i,e){return e?.ctrl&&e.name==="c"?{type:"cancel"}:e?.name==="return"||e?.name==="enter"?{type:"submit"}:e?.name==="backspace"?{type:"backspace"}:i&&!e?.ctrl&&!e?.meta&&i.length===1&&i>=" "?{type:"append",char:i}:{type:"ignore"}}function Ro(i,e){switch(e.type){case"append":return{value:i+e.char,done:!1,cancelled:!1,echo:"add"};case"backspace":return i.length===0?{value:i,done:!1,cancelled:!1,echo:"none"}:{value:i.slice(0,-1),done:!1,cancelled:!1,echo:"remove"};case"submit":return{value:i,done:!0,cancelled:!1,echo:"none"};case"cancel":return{value:i,done:!0,cancelled:!0,echo:"none"};case"ignore":return{value:i,done:!1,cancelled:!1,echo:"none"}}}async function at(i){if(process.stdout.write(i),!process.stdin.isTTY){let{createInterface:e}=await import("readline"),t=e({input:process.stdin,output:process.stdout,terminal:!1});return new Promise(n=>{t.question("",o=>{t.close(),n(o)})})}return new Promise(e=>{let t=process.stdin,n=t.isRaw;(0,zi.emitKeypressEvents)(t),t.setRawMode(!0),t.resume();let o="",s=()=>{t.removeListener("keypress",a),t.setRawMode(n??!1)},a=(l,c)=>{let d=Io(l,c),u=Ro(o,d);o=u.value,u.echo==="add"?process.stdout.write("*"):u.echo==="remove"&&process.stdout.write("\b \b"),u.done&&(s(),process.stdout.write(`
2
+ `),u.cancelled&&process.exit(0),e(o))};t.on("keypress",a)})}var zi,zt=qe(()=>{"use strict";zi=require("readline")});var De={};M(De,{TranslationWarningSystem:()=>O});var O,fe=qe(()=>{"use strict";O=class i{static DOCS_BASE_URL="https://docs.doorman.griffen.codes";static WARNING_CONFIGS={managed_rules:{category:"feature_unsupported",severity:"critical",explanation:"Managed rules are provider-specific security rules that cannot be directly translated between platforms.",suggestion:"Replace with custom rules using equivalent conditions and actions.",alternativeApproach:"Create custom rules that match the same traffic patterns using standard conditions like IP, country, user agent, or request headers.",impact:"Security coverage may be reduced until equivalent custom rules are implemented.",docsUrl:`${i.DOCS_BASE_URL}/migration/managed-rules`},bot_management:{category:"feature_unsupported",severity:"critical",explanation:"Bot management features use provider-specific detection algorithms that cannot be translated.",suggestion:"Configure bot management separately in the target provider.",alternativeApproach:"Use user agent filtering, rate limiting, and challenge actions to implement basic bot protection.",impact:"Bot protection effectiveness may vary between providers.",docsUrl:`${i.DOCS_BASE_URL}/migration/bot-management`},complex_expressions:{category:"lossy_conversion",severity:"warning",explanation:"Complex expressions may not translate perfectly due to differences in syntax and supported operators between providers.",suggestion:"Review translated expressions and test thoroughly before deploying.",alternativeApproach:"Break complex expressions into simpler, more portable conditions.",impact:"Rule behavior may differ slightly from the original configuration.",docsUrl:`${i.DOCS_BASE_URL}/migration/expressions`},geo_blocking:{category:"lossy_conversion",severity:"warning",explanation:"Geographic blocking may use different country codes or geographic databases between providers.",suggestion:"Verify country codes and geographic targeting after translation.",alternativeApproach:"Use ISO country codes when possible for better compatibility.",impact:"Some geographic regions may be blocked or allowed differently than intended.",docsUrl:`${i.DOCS_BASE_URL}/migration/geo-blocking`},rate_limiting_precision:{category:"lossy_conversion",severity:"info",explanation:"Rate limiting configurations may be adjusted to match the target provider's supported time windows and request thresholds.",suggestion:"Review rate limiting settings and adjust if necessary.",alternativeApproach:"Use the closest supported time window and request threshold values.",impact:"Rate limiting may be slightly more or less restrictive than the original configuration.",docsUrl:`${i.DOCS_BASE_URL}/migration/rate-limiting`},regex_patterns:{category:"syntax_limitation",severity:"warning",explanation:"Regular expression patterns may have different syntax requirements or feature support between providers.",suggestion:"Test regex patterns in the target provider and adjust syntax if needed.",alternativeApproach:"Use simpler string matching operations (contains, starts_with, ends_with) when possible.",impact:"Pattern matching may behave differently or fail to match intended traffic.",docsUrl:`${i.DOCS_BASE_URL}/migration/regex-patterns`},header_manipulation:{category:"syntax_limitation",severity:"warning",explanation:"Header manipulation capabilities vary between providers in terms of supported headers and modification types.",suggestion:"Verify header modification support in the target provider.",alternativeApproach:"Use redirect rules or custom error pages to achieve similar functionality.",impact:"Header modifications may not work as expected or may be ignored.",docsUrl:`${i.DOCS_BASE_URL}/migration/headers`},large_ip_lists:{category:"performance_impact",severity:"info",explanation:"Large IP lists may impact rule evaluation performance differently between providers.",suggestion:"Consider using provider-specific IP list features for better performance.",alternativeApproach:"Break large IP lists into smaller, more targeted rules or use CIDR notation to reduce list size.",impact:"Rule evaluation may be slower with large IP lists, potentially affecting site performance.",docsUrl:`${i.DOCS_BASE_URL}/migration/ip-lists`},many_conditions:{category:"performance_impact",severity:"info",explanation:"Rules with many conditions may have different performance characteristics between providers.",suggestion:"Monitor rule performance and consider optimizing complex rules.",alternativeApproach:"Split complex rules into multiple simpler rules or use more efficient condition types.",impact:"Complex rules may impact request processing speed.",docsUrl:`${i.DOCS_BASE_URL}/migration/rule-optimization`},action_differences:{category:"security_consideration",severity:"warning",explanation:"Security actions (block, challenge, etc.) may behave differently between providers in terms of user experience and effectiveness.",suggestion:"Test security actions thoroughly and adjust based on provider capabilities.",alternativeApproach:"Use the most appropriate equivalent action available in the target provider.",impact:"Security effectiveness and user experience may differ from the original configuration.",docsUrl:`${i.DOCS_BASE_URL}/migration/security-actions`},challenge_types:{category:"security_consideration",severity:"info",explanation:"Challenge types (CAPTCHA, JavaScript, etc.) vary between providers and may affect user experience.",suggestion:"Choose challenge types that balance security and user experience for your use case.",alternativeApproach:"Use the provider's recommended challenge type for your security requirements.",impact:"User experience during security challenges may vary.",docsUrl:`${i.DOCS_BASE_URL}/migration/challenges`},version_compatibility:{category:"compatibility_issue",severity:"warning",explanation:"Some features may only be available in specific provider plan tiers or API versions.",suggestion:"Verify feature availability in your target provider plan.",alternativeApproach:"Use alternative features available in your plan tier.",impact:"Some rules may not work as expected if required features are unavailable.",docsUrl:`${i.DOCS_BASE_URL}/migration/compatibility`},plan_limitations:{category:"compatibility_issue",severity:"critical",explanation:"Your current plan may not support all features being translated.",suggestion:"Upgrade your plan or modify rules to use available features.",alternativeApproach:"Implement equivalent functionality using features available in your current plan.",impact:"Rules may be rejected or ignored if they use unavailable features.",docsUrl:`${i.DOCS_BASE_URL}/migration/plan-limits`}};static createWarning(e,t,n,o,s){let a=this.WARNING_CONFIGS[e];return a?{rule:t,field:n,category:a.category,message:o||`${e.replace(/_/g," ")} translation issue`,explanation:a.explanation,severity:a.severity,suggestion:s||a.suggestion,alternativeApproach:a.alternativeApproach,impact:a.impact,docsUrl:a.docsUrl}:{rule:t,field:n,category:"compatibility_issue",message:o||`Unknown translation issue: ${e}`,explanation:"This translation scenario is not fully documented.",severity:"warning",suggestion:s||"Review the translated configuration manually and test thoroughly.",docsUrl:`${this.DOCS_BASE_URL}/migration/troubleshooting`}}static createUnsupportedFeatureWarning(e,t,n,o,s){return{rule:o,field:s,category:"feature_unsupported",message:`${e} is not supported in ${n}`,explanation:`The ${e} feature from ${t} cannot be directly translated to ${n} due to platform differences.`,severity:"critical",suggestion:`Remove or replace ${e} with equivalent functionality supported by ${n}.`,alternativeApproach:`Check ${n} documentation for similar features or use custom rules to achieve equivalent functionality.`,impact:"This rule may not work as expected or may be ignored entirely.",docsUrl:`${this.DOCS_BASE_URL}/migration/unsupported-features`}}static createLossyConversionWarning(e,t,n,o){return{rule:n,field:o,category:"lossy_conversion",message:`${e} translation may be lossy`,explanation:`The ${e} configuration cannot be perfectly translated: ${t}`,severity:"warning",suggestion:"Review the translated configuration and test thoroughly to ensure it behaves as expected.",alternativeApproach:"Consider simplifying the configuration or using more portable alternatives.",impact:"The translated rule may behave differently than the original.",docsUrl:`${this.DOCS_BASE_URL}/migration/lossy-conversions`}}static createSyntaxLimitationWarning(e,t,n,o){return{rule:n,field:o,category:"syntax_limitation",message:`${e} has syntax limitations`,explanation:`The ${e} syntax has been modified due to provider limitations: ${t}`,severity:"warning",suggestion:"Verify the translated syntax works correctly in the target provider.",alternativeApproach:"Use simpler syntax or alternative approaches that are more widely supported.",impact:"The rule may not match traffic as precisely as intended.",docsUrl:`${this.DOCS_BASE_URL}/migration/syntax-limitations`}}static createPerformanceWarning(e,t,n,o){return{rule:n,field:o,category:"performance_impact",message:`${e} may impact performance`,explanation:`The ${e} configuration may have performance implications: ${t}`,severity:"info",suggestion:"Monitor performance after deployment and optimize if necessary.",alternativeApproach:"Consider using more efficient alternatives or breaking complex rules into simpler ones.",impact:"Request processing may be slower than expected.",docsUrl:`${this.DOCS_BASE_URL}/migration/performance`}}static formatWarning(e){let n={critical:"\u{1F6A8}",warning:"\u26A0\uFE0F",info:"\u2139\uFE0F"}[e.severity],o=e.rule?` (Rule: ${e.rule}${e.field?`, Field: ${e.field}`:""})`:"",s=`${n} ${e.severity.toUpperCase()}: ${e.message}${o}
3
3
  `;return s+=` ${e.explanation}
4
4
  `,e.suggestion&&(s+=` \u{1F4A1} Suggestion: ${e.suggestion}
5
5
  `),e.alternativeApproach&&(s+=` \u{1F504} Alternative: ${e.alternativeApproach}
6
6
  `),e.impact&&(s+=` \u{1F4CA} Impact: ${e.impact}
7
7
  `),e.docsUrl&&(s+=` \u{1F4D6} Documentation: ${e.docsUrl}
8
- `),s}static groupWarningsBySeverity(e){return{critical:e.filter(t=>t.severity==="critical"),warning:e.filter(t=>t.severity==="warning"),info:e.filter(t=>t.severity==="info")}}static getWarningSummary(e){let t={critical:0,warning:0,info:0},o={feature_unsupported:0,lossy_conversion:0,syntax_limitation:0,performance_impact:0,security_consideration:0,compatibility_issue:0};return e.forEach(n=>{t[n.severity]++,o[n.category]++}),{total:e.length,bySeverity:t,byCategory:o,hasBlockingIssues:t.critical>0}}}});var vt={};M(vt,{OperationSafety:()=>Kt});var Ct,Kt,bt=qe(()=>{"use strict";Ct=S(require("chalk"));T();pe();Kt=class{static async confirmDestructiveOperation(e){let{operation:t,target:o,changes:n,riskLevel:s,skipConfirmation:a=!1,dryRun:l=!1,allowDeletions:c=!1}=e;if(l)return r.info(`\u{1F50D} Dry run mode: Would perform ${t} on ${o}`),!0;let d=(n?.rulesToDelete?.length||0)+(n?.ipsToDelete?.length||0);if(a)return d>0&&!c?(r.error(`
9
- \u{1F6A8} Refusing to run ${t} non-interactively: this would delete ${d} existing rule(s)/IP(s), and there is no confirmation prompt to catch a mistake.`),n&&this.displayChangeSummary(n),r.error(`
8
+ `),s}static groupWarningsBySeverity(e){return{critical:e.filter(t=>t.severity==="critical"),warning:e.filter(t=>t.severity==="warning"),info:e.filter(t=>t.severity==="info")}}static getWarningSummary(e){let t={critical:0,warning:0,info:0},n={feature_unsupported:0,lossy_conversion:0,syntax_limitation:0,performance_impact:0,security_consideration:0,compatibility_issue:0};return e.forEach(o=>{t[o.severity]++,n[o.category]++}),{total:e.length,bySeverity:t,byCategory:n,hasBlockingIssues:t.critical>0}}}});var Et={};M(Et,{OperationSafety:()=>Zt});var bt,Zt,Tt=qe(()=>{"use strict";bt=S(require("chalk"));T();pe();Zt=class{static async confirmDestructiveOperation(e){let{operation:t,target:n,changes:o,riskLevel:s,skipConfirmation:a=!1,dryRun:l=!1,allowDeletions:c=!1}=e;if(l)return r.info(`\u{1F50D} Dry run mode: Would perform ${t} on ${n}`),!0;let d=(o?.rulesToDelete?.length||0)+(o?.ipsToDelete?.length||0);if(a)return d>0&&!c?(r.error(`
9
+ \u{1F6A8} Refusing to run ${t} non-interactively: this would delete ${d} existing rule(s)/IP(s), and there is no confirmation prompt to catch a mistake.`),o&&this.displayChangeSummary(o),r.error(`
10
10
  If this is intended, re-run with --allow-deletions. Run "doorman diff" first if you're not sure what would be removed.`),!1):!0;r.info(`
11
- \u{1F6A8} Destructive Operation Confirmation`),r.info(`Operation: ${t}`),r.info(`Target: ${o}`),r.info(`Risk Level: ${this.formatRiskLevel(s)}`),n&&this.displayChangeSummary(n),this.displayRiskWarnings(s,t);let u=this.getBackupRecommendation(t,s);u.recommended&&(r.warn(`
11
+ \u{1F6A8} Destructive Operation Confirmation`),r.info(`Operation: ${t}`),r.info(`Target: ${n}`),r.info(`Risk Level: ${this.formatRiskLevel(s)}`),o&&this.displayChangeSummary(o),this.displayRiskWarnings(s,t);let u=this.getBackupRecommendation(t,s);u.recommended&&(r.warn(`
12
12
  \u{1F4BE} Backup Recommended: ${u.reason}`),u.instructions.forEach(I=>{r.info(` \u2022 ${I}`)}));let p=this.getRollbackGuidance(t);p.available&&(r.info(`
13
- \u{1F504} Rollback Available: ${p.method}`),p.timeWindow&&r.info(` Time Window: ${p.timeWindow}`));let g=this.getConfirmationMessage(s,t);return await w(g,{type:"confirm"})?(r.info("\u2705 Operation confirmed by user"),!0):(r.info("Operation cancelled by user"),!1)}static async performDryRunValidation(e,t,o){r.info(`\u{1F50D} Performing dry-run validation for ${t}...`);let n=[],s=[],a={rulesToAdd:[],rulesToUpdate:[],rulesToDelete:[],ipsToAdd:[],ipsToUpdate:[],ipsToDelete:[],hasChanges:!1};try{this.validateConfigurationStructure(e,n),a=await o(e),this.validateChanges(a,s),this.checkForPotentialIssues(e,a,s);let l=n.length===0;return l?r.info("\u2705 Dry-run validation passed"):(r.warn(`\u26A0\uFE0F Dry-run validation found ${n.length} issues:`),n.forEach(c=>r.warn(` \u2022 ${c}`))),s.length>0&&(r.warn(`\u26A0\uFE0F Dry-run validation found ${s.length} warning(s):`),s.forEach(c=>r.warn(` \u2022 ${c}`))),{valid:l,changes:a,issues:n,warnings:s}}catch(l){let c=`Dry-run validation failed: ${l instanceof Error?l.message:String(l)}`;return n.push(c),r.error(c),{valid:!1,changes:a,issues:n,warnings:s}}}static assessOperationRisk(e,t){let o=t.rules.length,n=t.ips?.length||0,s=(e.rulesToDelete?.length||0)+(e.ipsToDelete?.length||0),a=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+s;return s===o&&o>0||s>0&&s/Math.max(o+n,1)>.5||a>50||t.rules.some(c=>c.action.type==="deny"&&c.conditions.some(d=>d.field==="path"&&(d.value==="/"||d.value==="*")))?"high":s>0||a>10||e.rulesToUpdate&&e.rulesToUpdate.length>0?"medium":"low"}static getBackupRecommendation(e,t){return{"sync rules":{recommended:t!=="low",reason:"Rule synchronization can overwrite existing firewall configuration",instructions:['Run "doorman download" to backup current Cloudflare rules',"Save the downloaded configuration file with a timestamp","Consider using version control for configuration files"]},"delete ruleset":{recommended:!0,reason:"Ruleset deletion is irreversible and removes all associated rules",instructions:['Export current ruleset with "doorman export"',"Document the ruleset ID and configuration","Ensure you have the original configuration files"]},"update rules":{recommended:t==="high",reason:"Rule updates can affect traffic flow and security posture",instructions:["Download current configuration as backup","Test changes in a staging environment if possible","Have rollback plan ready"]},"clear all rules":{recommended:!0,reason:"Clearing all rules removes all firewall protection",instructions:['Export complete configuration with "doorman export"',"Save configuration to version control","Document business justification for clearing rules"]}}[e]||{recommended:t!=="low",reason:"Operation may modify existing configuration",instructions:["Download current configuration as backup","Document the changes being made"]}}static getRollbackGuidance(e){return{"sync rules":{available:!0,method:"Restore from backup configuration",instructions:['Use "doorman sync" with your backup configuration file',"Or manually restore rules in Cloudflare dashboard","Check that all rules are functioning as expected"],timeWindow:"No time limit - can rollback anytime"},"delete ruleset":{available:!1,method:"Recreation required",instructions:["Deleted rulesets cannot be restored","Must recreate ruleset and rules from backup",'Use "doorman sync" with backup configuration']},"update rules":{available:!0,method:"Restore previous rule version",instructions:["Sync with previous configuration version","Or use Cloudflare dashboard to revert changes","Verify rule functionality after rollback"],timeWindow:"Immediate - no time restrictions"},"clear all rules":{available:!0,method:"Restore from backup",instructions:["Sync with backup configuration file","Verify all rules are restored correctly","Test firewall functionality"],timeWindow:"No time limit"}}[e]||{available:!0,method:"Restore from backup",instructions:["Use backup configuration to restore previous state","Verify changes are reverted correctly"]}}static formatRiskLevel(e){switch(e){case"low":return Ct.default.green("LOW");case"medium":return Ct.default.yellow("MEDIUM");case"high":return Ct.default.red("HIGH");default:return String(e).toUpperCase()}}static displayChangeSummary(e){r.info(`
14
- \u{1F4CA} Change Summary:`),e.rulesToAdd?.length&&r.info(` \u2022 Rules to add: ${e.rulesToAdd.length}`),e.rulesToUpdate?.length&&r.info(` \u2022 Rules to update: ${e.rulesToUpdate.length}`),e.rulesToDelete?.length&&r.info(` \u2022 Rules to delete: ${e.rulesToDelete.length}`),e.ipsToAdd?.length&&r.info(` \u2022 IPs to add: ${e.ipsToAdd.length}`),e.ipsToUpdate?.length&&r.info(` \u2022 IPs to update: ${e.ipsToUpdate.length}`),e.ipsToDelete?.length&&r.info(` \u2022 IPs to delete: ${e.ipsToDelete.length}`),e.hasChanges||r.info(" \u2022 No changes detected")}static displayRiskWarnings(e,t){let o={low:["This operation has minimal risk of disrupting service"],medium:["This operation may temporarily affect traffic filtering","Monitor your application after the change"],high:["\u26A0\uFE0F This operation can significantly impact security and traffic flow","\u26A0\uFE0F Ensure you have tested the configuration in a safe environment","\u26A0\uFE0F Have a rollback plan ready before proceeding"]},n={"clear all rules":["\u{1F6A8} This will remove ALL firewall protection","\u{1F6A8} Your application will be unprotected until new rules are added"],"delete ruleset":["\u{1F6A8} This action is IRREVERSIBLE","\u{1F6A8} All rules in the ruleset will be permanently deleted"]};r.info(`
15
- \u26A0\uFE0F Warnings:`),o[e]?.forEach(s=>{r.warn(` ${s}`)}),n[t]?.forEach(s=>{r.warn(` ${s}`)})}static getConfirmationMessage(e,t){let o=`Do you want to proceed with ${t}?`;switch(e){case"high":return`${o} (Type 'yes' to confirm high-risk operation)`;case"medium":return`${o} (Proceed with caution)`;default:return o}}static validateConfigurationStructure(e,t){if(!e){t.push("Configuration is null or undefined");return}e.version||t.push("Configuration missing version field"),e.provider||t.push("Configuration missing provider field"),Array.isArray(e.rules)||t.push("Configuration rules field is not an array"),e.ips&&!Array.isArray(e.ips)&&t.push("Configuration ips field is not an array")}static validateChanges(e,t){let o=(e.rulesToDelete?.length||0)+(e.ipsToDelete?.length||0),n=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+o;if(o>0&&n>0){let s=o/n;s>.5&&t.push(`High deletion ratio detected: ${Math.round(s*100)}% of changes are deletions`)}n>100&&t.push(`Large number of changes detected: ${n} total changes`)}static checkForPotentialIssues(e,t,o){t.rulesToDelete?.length===e.rules.length&&e.rules.length>0&&o.push("All existing rules will be deleted - this removes all firewall protection");let n=e.rules.filter(l=>l.action.type==="deny"&&l.conditions.some(c=>c.field==="path"&&(c.value==="/"||c.value==="*")));n.length>0&&o.push(`Found ${n.length} rules that may block all traffic`),e.ips&&e.ips.length>1e3&&o.push(`Large IP list detected: ${e.ips.length} IPs may impact performance`);let s=e.rules.map(l=>l.name),a=s.filter((l,c)=>s.indexOf(l)!==c);a.length>0&&o.push(`Duplicate rule names found: ${[...new Set(a)].join(", ")}`)}}});var lo={};M(lo,{promptForCredentials:()=>or});async function or(i){let e=i.token||process.env.VERCEL_TOKEN||await rt("What is your Vercel API Auth Token? (https://vercel.com/guides/how-do-i-use-a-vercel-api-access-token#creating-an-access-token) "),o=i.teamId||process.env.VERCEL_TEAM_ID||await w("What is your Vercel Team ID? Leave blank to use your Vercel default team (every account, including Hobby, is a team). Only needed if you belong to more than one team and want to target a non-default one. (See https://vercel.com/docs/accounts#find-your-team-id)",{type:"text"})||void 0,n=i.projectId||process.env.VERCEL_PROJECT_ID||await w("What is your Vercel Project ID? (See https://vercel.com/docs/projects/project-configuration/general-settings#project-id)",{type:"text"});return{token:e,teamId:o,projectId:n}}var co=qe(()=>{"use strict";pe();jt()});var xo=require("dotenv"),Oo=S(require("yargs"));var Wt={};M(Wt,{builder:()=>ln,command:()=>sn,desc:()=>an,generateRuleId:()=>Bt,handler:()=>gn});var x=S(require("chalk")),Ni=require("consola");T();var C=require("zod"),ft=C.z.number().int().positive().optional(),jo=C.z.string().ip().or(C.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),wi=C.z.string().optional(),qo=C.z.enum(["eq","pre","suf","inc","sub","re","ex","nex"]),zo=C.z.enum(["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"]),Mo=C.z.object({op:qo,neg:C.z.boolean().optional(),type:zo,value:C.z.union([C.z.string(),C.z.array(C.z.string()),C.z.array(C.z.number())]).optional(),key:C.z.string().optional()}).refine(i=>{switch(i.type){case"ip_address":case"method":case"environment":case"protocol":return i.op==="eq"||i.op==="inc";default:return!0}},"Invalid operator for the given condition type").refine(i=>{let e=["header","cookie"];return!(e.includes(i.type)&&!i.key||e.includes(i.type)&&i.op!=="ex"&&i.op!=="nex"&&!i.value)},"Missing key from condition").refine(i=>!(["ex","nex"].includes(i.op)&&i.neg),"Negation is not supported for the given operator").refine(i=>!(i.op==="inc"&&!Array.isArray(i.value)),"When using `inc` operator, value must be an array"),$t=C.z.object({conditions:C.z.array(Mo).min(1,"Condition group must have at least one condition")}),Go=C.z.string().regex(/^\d+[smhd]$|^permanent$/),_t=C.z.object({requests:C.z.number().positive().int().refine(i=>i>0,"requests must be positive"),window:C.z.string().regex(/^\d+[smhd]$/).refine(i=>parseInt(i)>0,"window duration must be positive")}),Ko=C.z.object({location:C.z.string(),permanent:C.z.boolean().optional()}),Ho=C.z.enum(["log","deny","challenge","bypass","rate_limit","redirect"]),Zo=C.z.object({action:Ho,rateLimit:_t.nullable().optional(),redirect:Ko.nullable().optional(),actionDuration:Go.nullable().optional()}),Yo=C.z.object({mitigate:Zo}),St=C.z.object({id:wi,name:C.z.string(),description:C.z.string().optional(),conditionGroup:C.z.array($t),action:Yo,active:C.z.boolean()});var Lt=C.z.object({id:wi,ip:jo,hostname:C.z.string(),notes:C.z.string().optional(),action:C.z.literal("deny")}),Jo=C.z.object({projectId:C.z.string().optional(),teamId:C.z.string().optional()}),Te=Jo.extend({rules:C.z.array(St),ips:C.z.array(Lt).optional(),version:C.z.number().optional(),updatedAt:C.z.string().optional()});pe();var ne=require("fs"),Ui=require("crypto"),Di=require("path");T();var _i=require("net"),Si=S(require("ajv"));var Ri="https://doorman.griffen.codes/schema.json",Ci={$schema:"http://json-schema.org/draft-07/schema#",title:"Doorman Config",description:"Schema for doorman project configuration files",$ref:"#/definitions/FirewallConfig",definitions:{FirewallConfig:{type:"object",properties:{projectId:{type:"string"},teamId:{type:"string"},$schema:{type:"string"},version:{type:"number"},firewallEnabled:{type:"boolean"},rules:{type:"array",items:{$ref:"#/definitions/CustomRule"}},ips:{type:"array",items:{$ref:"#/definitions/IPBlockingRule"}},updatedAt:{type:"string"}},required:["rules"],additionalProperties:!1,description:"The main configuration type for Doorman"},CustomRule:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},conditionGroup:{type:"array",items:{$ref:"#/definitions/ConditionGroup"}},action:{$ref:"#/definitions/RuleAction"},active:{type:"boolean"}},required:["name","conditionGroup","action","active"],additionalProperties:!1,description:"Rule Types"},ConditionGroup:{type:"object",properties:{conditions:{type:"array",items:{$ref:"#/definitions/RuleCondition"}}},required:["conditions"],additionalProperties:!1},RuleCondition:{type:"object",properties:{op:{$ref:"#/definitions/RuleOperator"},neg:{type:"boolean"},type:{$ref:"#/definitions/RuleType"},key:{type:"string"},value:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{type:"string"}},{type:"array",items:{type:"number"}}]}},required:["op","type"],additionalProperties:!1,description:"Rule Condition Types"},RuleOperator:{type:"string",enum:["eq","pre","suf","inc","sub","re","ex","nex"]},RuleType:{type:"string",enum:["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"]},RuleAction:{type:"object",properties:{mitigate:{$ref:"#/definitions/MitigationAction"}},required:["mitigate"],additionalProperties:!1},MitigationAction:{type:"object",properties:{action:{$ref:"#/definitions/ActionType"},rateLimit:{anyOf:[{$ref:"#/definitions/RateLimit"},{type:"null"}]},redirect:{anyOf:[{$ref:"#/definitions/Redirect"},{type:"null"}]},actionDuration:{type:["string","null"]}},required:["action"],additionalProperties:!1},ActionType:{type:"string",enum:["log","deny","challenge","bypass","rate_limit","redirect"],description:"Core Types"},RateLimit:{type:"object",properties:{requests:{type:"number"},window:{type:"string"}},required:["requests","window"],additionalProperties:!1,description:"Action Types"},Redirect:{type:"object",properties:{location:{type:"string"},permanent:{type:"boolean"}},required:["location"],additionalProperties:!1},IPBlockingRule:{type:"object",properties:{id:{type:"string"},ip:{type:"string"},hostname:{type:"string"},notes:{type:"string"},action:{type:"string",const:"deny"}},required:["ip","hostname","action"],additionalProperties:!1}}};var A=require("zod");var E=require("zod");var re=["vercel","cloudflare","fastly"];var Ut=E.z.string().optional(),ze=E.z.string().ip().or(E.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),gt=E.z.string().datetime().or(E.z.string().optional()),vi=E.z.enum(["log","deny","challenge","bypass","rate_limit","redirect","allow","block"]),bi=E.z.enum(["eq","ne","contains","not_contains","starts_with","ends_with","matches","in","not_in","gt","ge","lt","le","exists","not_exists"]),Ei=E.z.enum(["ip","country","region","city","asn","path","host","method","header","query","cookie","user_agent","referer","scheme","port"]),$s=E.z.string().regex(/^\d+[smhd]$|^permanent$/),Ti=E.z.object({requests:E.z.number().positive().int(),window:E.z.string().regex(/^\d+[smhd]$/),characteristics:E.z.array(E.z.string()).optional()}),Ai=E.z.object({location:E.z.string().url(),statusCode:E.z.number().int().min(300).max(399).optional(),permanent:E.z.boolean().optional(),preserveQueryString:E.z.boolean().optional()}),Dt=E.z.object({version:E.z.number().int().positive().optional(),updatedAt:gt,createdAt:gt,lastSyncedAt:gt,migratedFrom:E.z.string().optional(),migratedAt:gt}),Qo=E.z.enum(re),Pi=E.z.object({vercel:E.z.object({projectId:E.z.string().optional(),teamId:E.z.string().optional()}).optional(),cloudflare:E.z.object({zoneId:E.z.string().optional(),accountId:E.z.string().optional()}).optional(),fastly:E.z.object({workspaceId:E.z.string().optional()}).optional()}),ki=E.z.object({$schema:E.z.string().url().optional(),version:E.z.string().optional(),provider:Qo.optional(),metadata:Dt.optional()});var Xo=A.z.object({field:Ei.or(A.z.string()),operator:bi,value:A.z.union([A.z.string(),A.z.number(),A.z.array(A.z.string()),A.z.array(A.z.number())]),negated:A.z.boolean().optional(),key:A.z.string().optional()}),en=A.z.object({type:vi,rateLimit:Ti.optional(),redirect:Ai.optional(),response:A.z.object({statusCode:A.z.number().int().min(100).max(599).optional(),content:A.z.string().optional(),contentType:A.z.string().optional()}).optional(),duration:A.z.string().optional()}),tn=A.z.object({id:Ut,name:A.z.string().min(1,"Rule name is required"),description:A.z.string().optional(),enabled:A.z.boolean(),conditions:A.z.array(Xo).min(1,"At least one condition is required"),conditionLogic:A.z.enum(["AND","OR"]).optional().default("AND"),action:en,priority:A.z.number().int().optional().describe("Rule evaluation order. Lower numbers are evaluated first. Rules without a priority keep their config order and run after all prioritised rules. Fully honoured on Cloudflare; best-effort on Vercel, which cannot reposition rules that already exist remotely."),categories:A.z.array(A.z.string()).optional()}),on=A.z.object({id:Ut,ip:ze,hostname:A.z.string().optional(),notes:A.z.string().optional(),action:A.z.enum(["deny","allow"])}),Le=ki.extend({providers:Pi.optional(),rules:A.z.array(tn),ips:A.z.array(on).optional(),metadata:Dt.optional()}),$i=i=>{let e=Le.safeParse(i);if(!e.success)throw new Error(`Invalid unified configuration: ${e.error.message}`);if(e.data.provider&&!e.data.providers?.[e.data.provider])throw new Error(`Provider '${e.data.provider}' specified but no configuration found in providers section`);return e.data};function we(i){if(!i||typeof i!="object")return!1;let e=i;return typeof e.provider=="string"||typeof e.providers=="object"&&e.providers!==null}var oe=S(require("chalk")),Ie=class{static formatValidationError(e){let t=e.instancePath||"/",o=oe.default.cyan(t);switch(e.keyword){case"type":return`${o}: Expected ${oe.default.green(e.schema)}, got ${oe.default.red(typeof e.data)}`;case"enum":{let n=e.params.allowedValues;return`${o}: Value must be one of: ${oe.default.green(n.join(", "))}`}case"required":{let n=e.params;return`${o}: Missing required property ${oe.default.yellow(n.missingProperty)}`}case"additionalProperties":{let n=e.params;return`${o}: Unknown property ${oe.default.red(n.additionalProperty)}`}default:return`${o}: ${e.message}`}}static formatCustomError(e,t){return`${oe.default.cyan(e)}: ${t}`}static wrapErrorBlock(e){let t=oe.default.red.bold("Validation Errors:"),o=e.map(n=>` ${n}`).join(`
13
+ \u{1F504} Rollback Available: ${p.method}`),p.timeWindow&&r.info(` Time Window: ${p.timeWindow}`));let g=this.getConfirmationMessage(s,t);return await w(g,{type:"confirm"})?(r.info("\u2705 Operation confirmed by user"),!0):(r.info("Operation cancelled by user"),!1)}static async performDryRunValidation(e,t,n){r.info(`\u{1F50D} Performing dry-run validation for ${t}...`);let o=[],s=[],a={rulesToAdd:[],rulesToUpdate:[],rulesToDelete:[],ipsToAdd:[],ipsToUpdate:[],ipsToDelete:[],hasChanges:!1};try{this.validateConfigurationStructure(e,o),a=await n(e),this.validateChanges(a,s),this.checkForPotentialIssues(e,a,s);let l=o.length===0;return l?r.info("\u2705 Dry-run validation passed"):(r.warn(`\u26A0\uFE0F Dry-run validation found ${o.length} issues:`),o.forEach(c=>r.warn(` \u2022 ${c}`))),s.length>0&&(r.warn(`\u26A0\uFE0F Dry-run validation found ${s.length} warning(s):`),s.forEach(c=>r.warn(` \u2022 ${c}`))),{valid:l,changes:a,issues:o,warnings:s}}catch(l){let c=`Dry-run validation failed: ${l instanceof Error?l.message:String(l)}`;return o.push(c),r.error(c),{valid:!1,changes:a,issues:o,warnings:s}}}static assessOperationRisk(e,t){let n=t.rules.length,o=t.ips?.length||0,s=(e.rulesToDelete?.length||0)+(e.ipsToDelete?.length||0),a=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+s;return s===n&&n>0||s>0&&s/Math.max(n+o,1)>.5||a>50||t.rules.some(c=>c.action.type==="deny"&&c.conditions.some(d=>d.field==="path"&&(d.value==="/"||d.value==="*")))?"high":s>0||a>10||e.rulesToUpdate&&e.rulesToUpdate.length>0?"medium":"low"}static getBackupRecommendation(e,t){return{"sync rules":{recommended:t!=="low",reason:"Rule synchronization can overwrite existing firewall configuration",instructions:['Run "doorman download" to backup current Cloudflare rules',"Save the downloaded configuration file with a timestamp","Consider using version control for configuration files"]},"delete ruleset":{recommended:!0,reason:"Ruleset deletion is irreversible and removes all associated rules",instructions:['Export current ruleset with "doorman export"',"Document the ruleset ID and configuration","Ensure you have the original configuration files"]},"update rules":{recommended:t==="high",reason:"Rule updates can affect traffic flow and security posture",instructions:["Download current configuration as backup","Test changes in a staging environment if possible","Have rollback plan ready"]},"clear all rules":{recommended:!0,reason:"Clearing all rules removes all firewall protection",instructions:['Export complete configuration with "doorman export"',"Save configuration to version control","Document business justification for clearing rules"]}}[e]||{recommended:t!=="low",reason:"Operation may modify existing configuration",instructions:["Download current configuration as backup","Document the changes being made"]}}static getRollbackGuidance(e){return{"sync rules":{available:!0,method:"Restore from backup configuration",instructions:['Use "doorman sync" with your backup configuration file',"Or manually restore rules in Cloudflare dashboard","Check that all rules are functioning as expected"],timeWindow:"No time limit - can rollback anytime"},"delete ruleset":{available:!1,method:"Recreation required",instructions:["Deleted rulesets cannot be restored","Must recreate ruleset and rules from backup",'Use "doorman sync" with backup configuration']},"update rules":{available:!0,method:"Restore previous rule version",instructions:["Sync with previous configuration version","Or use Cloudflare dashboard to revert changes","Verify rule functionality after rollback"],timeWindow:"Immediate - no time restrictions"},"clear all rules":{available:!0,method:"Restore from backup",instructions:["Sync with backup configuration file","Verify all rules are restored correctly","Test firewall functionality"],timeWindow:"No time limit"}}[e]||{available:!0,method:"Restore from backup",instructions:["Use backup configuration to restore previous state","Verify changes are reverted correctly"]}}static formatRiskLevel(e){switch(e){case"low":return bt.default.green("LOW");case"medium":return bt.default.yellow("MEDIUM");case"high":return bt.default.red("HIGH");default:return String(e).toUpperCase()}}static displayChangeSummary(e){r.info(`
14
+ \u{1F4CA} Change Summary:`),e.rulesToAdd?.length&&r.info(` \u2022 Rules to add: ${e.rulesToAdd.length}`),e.rulesToUpdate?.length&&r.info(` \u2022 Rules to update: ${e.rulesToUpdate.length}`),e.rulesToDelete?.length&&r.info(` \u2022 Rules to delete: ${e.rulesToDelete.length}`),e.ipsToAdd?.length&&r.info(` \u2022 IPs to add: ${e.ipsToAdd.length}`),e.ipsToUpdate?.length&&r.info(` \u2022 IPs to update: ${e.ipsToUpdate.length}`),e.ipsToDelete?.length&&r.info(` \u2022 IPs to delete: ${e.ipsToDelete.length}`),e.hasChanges||r.info(" \u2022 No changes detected")}static displayRiskWarnings(e,t){let n={low:["This operation has minimal risk of disrupting service"],medium:["This operation may temporarily affect traffic filtering","Monitor your application after the change"],high:["\u26A0\uFE0F This operation can significantly impact security and traffic flow","\u26A0\uFE0F Ensure you have tested the configuration in a safe environment","\u26A0\uFE0F Have a rollback plan ready before proceeding"]},o={"clear all rules":["\u{1F6A8} This will remove ALL firewall protection","\u{1F6A8} Your application will be unprotected until new rules are added"],"delete ruleset":["\u{1F6A8} This action is IRREVERSIBLE","\u{1F6A8} All rules in the ruleset will be permanently deleted"]};r.info(`
15
+ \u26A0\uFE0F Warnings:`),n[e]?.forEach(s=>{r.warn(` ${s}`)}),o[t]?.forEach(s=>{r.warn(` ${s}`)})}static getConfirmationMessage(e,t){let n=`Do you want to proceed with ${t}?`;switch(e){case"high":return`${n} (Type 'yes' to confirm high-risk operation)`;case"medium":return`${n} (Proceed with caution)`;default:return n}}static validateConfigurationStructure(e,t){if(!e){t.push("Configuration is null or undefined");return}e.version||t.push("Configuration missing version field"),e.provider||t.push("Configuration missing provider field"),Array.isArray(e.rules)||t.push("Configuration rules field is not an array"),e.ips&&!Array.isArray(e.ips)&&t.push("Configuration ips field is not an array")}static validateChanges(e,t){let n=(e.rulesToDelete?.length||0)+(e.ipsToDelete?.length||0),o=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+n;if(n>0&&o>0){let s=n/o;s>.5&&t.push(`High deletion ratio detected: ${Math.round(s*100)}% of changes are deletions`)}o>100&&t.push(`Large number of changes detected: ${o} total changes`)}static checkForPotentialIssues(e,t,n){t.rulesToDelete?.length===e.rules.length&&e.rules.length>0&&n.push("All existing rules will be deleted - this removes all firewall protection");let o=e.rules.filter(l=>l.action.type==="deny"&&l.conditions.some(c=>c.field==="path"&&(c.value==="/"||c.value==="*")));o.length>0&&n.push(`Found ${o.length} rules that may block all traffic`),e.ips&&e.ips.length>1e3&&n.push(`Large IP list detected: ${e.ips.length} IPs may impact performance`);let s=e.rules.map(l=>l.name),a=s.filter((l,c)=>s.indexOf(l)!==c);a.length>0&&n.push(`Duplicate rule names found: ${[...new Set(a)].join(", ")}`)}}});var fn={};M(fn,{promptForCredentials:()=>ar});async function ar(i){let e=i.token||process.env.VERCEL_TOKEN||await at("What is your Vercel API Auth Token? (https://vercel.com/guides/how-do-i-use-a-vercel-api-access-token#creating-an-access-token) "),n=i.teamId||process.env.VERCEL_TEAM_ID||await w("What is your Vercel Team ID? Leave blank to use your Vercel default team (every account, including Hobby, is a team). Only needed if you belong to more than one team and want to target a non-default one. (See https://vercel.com/docs/accounts#find-your-team-id)",{type:"text"})||void 0,o=i.projectId||process.env.VERCEL_PROJECT_ID||await w("What is your Vercel Project ID? (See https://vercel.com/docs/projects/project-configuration/general-settings#project-id)",{type:"text"});return{token:e,teamId:n,projectId:o}}var gn=qe(()=>{"use strict";pe();zt()});var Vn=require("dotenv"),Bn=S(require("yargs"));var jt={};M(jt,{builder:()=>po,command:()=>co,desc:()=>uo,generateRuleId:()=>Wt,handler:()=>wo});var U=S(require("chalk")),Bi=require("consola");T();var C=require("zod"),mt=C.z.number().int().positive().optional(),Gn=C.z.string().ip().or(C.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),Ri=C.z.string().optional(),Kn=C.z.enum(["eq","pre","suf","inc","sub","re","ex","nex"]),Hn=C.z.enum(["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"]),Zn=C.z.object({op:Kn,neg:C.z.boolean().optional(),type:Hn,value:C.z.union([C.z.string(),C.z.array(C.z.string()),C.z.array(C.z.number())]).optional(),key:C.z.string().optional()}).refine(i=>{switch(i.type){case"ip_address":case"method":case"environment":case"protocol":return i.op==="eq"||i.op==="inc";default:return!0}},"Invalid operator for the given condition type").refine(i=>{let e=["header","cookie"];return!(e.includes(i.type)&&!i.key||e.includes(i.type)&&i.op!=="ex"&&i.op!=="nex"&&!i.value)},"Missing key from condition").refine(i=>!(["ex","nex"].includes(i.op)&&i.neg),"Negation is not supported for the given operator").refine(i=>!(i.op==="inc"&&!Array.isArray(i.value)),"When using `inc` operator, value must be an array"),_t=C.z.object({conditions:C.z.array(Zn).min(1,"Condition group must have at least one condition")}),Yn=C.z.string().regex(/^\d+[smhd]$|^permanent$/),St=C.z.object({requests:C.z.number().positive().int().refine(i=>i>0,"requests must be positive"),window:C.z.string().regex(/^\d+[smhd]$/).refine(i=>parseInt(i)>0,"window duration must be positive")}),Jn=C.z.object({location:C.z.string(),permanent:C.z.boolean().optional()}),Qn=C.z.enum(["log","deny","challenge","bypass","rate_limit","redirect"]),Xn=C.z.object({action:Qn,rateLimit:St.nullable().optional(),redirect:Jn.nullable().optional(),actionDuration:Yn.nullable().optional()}),eo=C.z.object({mitigate:Xn}),Lt=C.z.object({id:Ri,name:C.z.string(),description:C.z.string().optional(),conditionGroup:C.z.array(_t),action:eo,active:C.z.boolean()});var Ut=C.z.object({id:Ri,ip:Gn,hostname:C.z.string(),notes:C.z.string().optional(),action:C.z.literal("deny")}),to=C.z.object({projectId:C.z.string().optional(),teamId:C.z.string().optional()}),Ae=to.extend({rules:C.z.array(Lt),ips:C.z.array(Ut).optional(),version:C.z.number().optional(),updatedAt:C.z.string().optional()});pe();var oe=require("fs"),xi=require("crypto"),Oi=require("path");T();var Li=require("net"),Ui=S(require("ajv"));var vi="https://doorman.griffen.codes/schema.json",bi={$schema:"http://json-schema.org/draft-07/schema#",title:"Doorman Config",description:"Schema for doorman project configuration files",$ref:"#/definitions/FirewallConfig",definitions:{FirewallConfig:{type:"object",properties:{projectId:{type:"string"},teamId:{type:"string"},$schema:{type:"string"},version:{type:"number"},firewallEnabled:{type:"boolean"},rules:{type:"array",items:{$ref:"#/definitions/CustomRule"}},ips:{type:"array",items:{$ref:"#/definitions/IPBlockingRule"}},updatedAt:{type:"string"}},required:["rules"],additionalProperties:!1,description:"The main configuration type for Doorman"},CustomRule:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},conditionGroup:{type:"array",items:{$ref:"#/definitions/ConditionGroup"}},action:{$ref:"#/definitions/RuleAction"},active:{type:"boolean"}},required:["name","conditionGroup","action","active"],additionalProperties:!1,description:"Rule Types"},ConditionGroup:{type:"object",properties:{conditions:{type:"array",items:{$ref:"#/definitions/RuleCondition"}}},required:["conditions"],additionalProperties:!1},RuleCondition:{type:"object",properties:{op:{$ref:"#/definitions/RuleOperator"},neg:{type:"boolean"},type:{$ref:"#/definitions/RuleType"},key:{type:"string"},value:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{type:"string"}},{type:"array",items:{type:"number"}}]}},required:["op","type"],additionalProperties:!1,description:"Rule Condition Types"},RuleOperator:{type:"string",enum:["eq","pre","suf","inc","sub","re","ex","nex"]},RuleType:{type:"string",enum:["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"]},RuleAction:{type:"object",properties:{mitigate:{$ref:"#/definitions/MitigationAction"}},required:["mitigate"],additionalProperties:!1},MitigationAction:{type:"object",properties:{action:{$ref:"#/definitions/ActionType"},rateLimit:{anyOf:[{$ref:"#/definitions/RateLimit"},{type:"null"}]},redirect:{anyOf:[{$ref:"#/definitions/Redirect"},{type:"null"}]},actionDuration:{type:["string","null"]}},required:["action"],additionalProperties:!1},ActionType:{type:"string",enum:["log","deny","challenge","bypass","rate_limit","redirect"],description:"Core Types"},RateLimit:{type:"object",properties:{requests:{type:"number"},window:{type:"string"}},required:["requests","window"],additionalProperties:!1,description:"Action Types"},Redirect:{type:"object",properties:{location:{type:"string"},permanent:{type:"boolean"}},required:["location"],additionalProperties:!1},IPBlockingRule:{type:"object",properties:{id:{type:"string"},ip:{type:"string"},hostname:{type:"string"},notes:{type:"string"},action:{type:"string",const:"deny"}},required:["ip","hostname","action"],additionalProperties:!1}}};var A=require("zod");var E=require("zod");var re=["vercel","cloudflare","fastly"];var Dt=E.z.string().optional(),ze=E.z.string().ip().or(E.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),ht=E.z.string().datetime().or(E.z.string().optional()),Ei=E.z.enum(["log","deny","challenge","bypass","rate_limit","redirect","allow","block"]),Ti=E.z.enum(["eq","ne","contains","not_contains","starts_with","ends_with","matches","in","not_in","gt","ge","lt","le","exists","not_exists"]),Ai=E.z.enum(["ip","country","region","city","asn","path","host","method","header","query","cookie","user_agent","referer","scheme","port"]),Ds=E.z.string().regex(/^\d+[smhd]$|^permanent$/),Pi=E.z.object({requests:E.z.number().positive().int(),window:E.z.string().regex(/^\d+[smhd]$/),characteristics:E.z.array(E.z.string()).optional()}),ki=E.z.object({location:E.z.string().url(),statusCode:E.z.number().int().min(300).max(399).optional(),permanent:E.z.boolean().optional(),preserveQueryString:E.z.boolean().optional()}),xt=E.z.object({version:E.z.number().int().positive().optional(),updatedAt:ht,createdAt:ht,lastSyncedAt:ht,migratedFrom:E.z.string().optional(),migratedAt:ht}),io=E.z.enum(re),$i=E.z.object({vercel:E.z.object({projectId:E.z.string().optional(),teamId:E.z.string().optional()}).optional(),cloudflare:E.z.object({zoneId:E.z.string().optional(),accountId:E.z.string().optional()}).optional(),fastly:E.z.object({workspaceId:E.z.string().optional()}).optional()}),_i=E.z.object({$schema:E.z.string().url().optional(),version:E.z.string().optional(),provider:io.optional(),metadata:xt.optional()});var no=A.z.object({field:Ai.or(A.z.string()),operator:Ti,value:A.z.union([A.z.string(),A.z.number(),A.z.array(A.z.string()),A.z.array(A.z.number())]),negated:A.z.boolean().optional(),key:A.z.string().optional()}),oo=A.z.object({type:Ei,rateLimit:Pi.optional(),redirect:ki.optional(),response:A.z.object({statusCode:A.z.number().int().min(100).max(599).optional(),content:A.z.string().optional(),contentType:A.z.string().optional()}).optional(),duration:A.z.string().optional()}),ro=A.z.object({id:Dt,name:A.z.string().min(1,"Rule name is required"),description:A.z.string().optional(),enabled:A.z.boolean(),conditions:A.z.array(no).min(1,"At least one condition is required"),conditionLogic:A.z.enum(["AND","OR"]).optional().default("AND"),action:oo,priority:A.z.number().int().optional().describe("Rule evaluation order. Lower numbers are evaluated first. Rules without a priority keep their config order and run after all prioritised rules. Fully honoured on Cloudflare; best-effort on Vercel, which cannot reposition rules that already exist remotely."),categories:A.z.array(A.z.string()).optional()}),so=A.z.object({id:Dt,ip:ze,hostname:A.z.string().optional(),notes:A.z.string().optional(),action:A.z.enum(["deny","allow"])}),Le=_i.extend({providers:$i.optional(),rules:A.z.array(ro),ips:A.z.array(so).optional(),metadata:xt.optional()}),Si=i=>{let e=Le.safeParse(i);if(!e.success)throw new Error(`Invalid unified configuration: ${e.error.message}`);if(e.data.provider&&!e.data.providers?.[e.data.provider])throw new Error(`Provider '${e.data.provider}' specified but no configuration found in providers section`);return e.data};function we(i){if(!i||typeof i!="object")return!1;let e=i;return typeof e.provider=="string"||typeof e.providers=="object"&&e.providers!==null}var ne=S(require("chalk")),Ie=class{static formatValidationError(e){let t=e.instancePath||"/",n=ne.default.cyan(t);switch(e.keyword){case"type":return`${n}: Expected ${ne.default.green(e.schema)}, got ${ne.default.red(typeof e.data)}`;case"enum":{let o=e.params.allowedValues;return`${n}: Value must be one of: ${ne.default.green(o.join(", "))}`}case"required":{let o=e.params;return`${n}: Missing required property ${ne.default.yellow(o.missingProperty)}`}case"additionalProperties":{let o=e.params;return`${n}: Unknown property ${ne.default.red(o.additionalProperty)}`}default:return`${n}: ${e.message}`}}static formatCustomError(e,t){return`${ne.default.cyan(e)}: ${t}`}static wrapErrorBlock(e){let t=ne.default.red.bold("Validation Errors:"),n=e.map(o=>` ${o}`).join(`
16
16
  `);return`${t}
17
- ${o}`}static formatDetailedRuleValidation(e,t){let o=oe.default.cyan(`Rule: ${e}`),n=t.map(s=>{let a=s.passed?oe.default.green("\u2713"):oe.default.red("\u2717"),l=s.passed?oe.default.green(s.name):oe.default.red(s.name);return` ${a} ${l}`}).join(`
18
- `);return`${o}
19
- ${n}`}};var D=class i extends Error{constructor(t,o,n,s=[]){super(t);this.ajvErrors=o;this.zodError=n;this.customErrors=s;this.name="ValidationError"}ajvErrors;zodError;customErrors;static formatErrors(t,o,n=[]){let s=[];return t?.length&&s.push(...t.map(Ie.formatValidationError)),o&&s.push(...o.errors.map(a=>`${a.path.join(".")}: ${a.message}`)),n.length&&s.push(...n),Ie.wrapErrorBlock(s)}getFormattedMessage(){return i.formatErrors(this.ajvErrors,this.zodError,this.customErrors)}},Re=class i{static instance;ajv;schema;constructor(){this.ajv=new Si.default({allErrors:!0,verbose:!0}),this.schema=Ci}static getInstance(){return i.instance||(i.instance=new i),i.instance}validateConfig(e){if(we(e))try{$i(e);return}catch(c){throw new D(`Invalid firewall configuration:
20
- `+(c instanceof Error?c.message:String(c)),null)}let t=this.ajv.compile(this.schema),o=t(e),n=t.errors,s=Te.safeParse(e),a;s.success||(a=s.error);let l=[];if(o&&s.success){try{this.validateRuleNames(e),this.validateRuleConditionGroup(e),this.validateRuleAction(e)}catch(c){if(c instanceof D)l.push(c.message,...c.customErrors||[]);else throw c}for(let c of e.rules){if(c.action.mitigate?.rateLimit){let d=_t.safeParse(c.action.mitigate.rateLimit);d.success||l.push(...d.error.errors.map(u=>u.message))}if(c.conditionGroup)for(let d of c.conditionGroup){let u=$t.safeParse(d);u.success||l.push(...u.error.errors.map(p=>p.message))}}}if(!o||!s.success||l.length>0)throw new D(`Invalid firewall configuration:
21
- `+D.formatErrors(n,a,l),n,a,l)}validateRuleNames(e){let t=new Set;for(let o of e.rules){if(t.has(o.name))throw new D(`Duplicate rule name found: "${o.name}"`,null);t.add(o.name)}}validateRuleConditionGroup(e){for(let t of e.rules)if(t.conditionGroup)for(let o of t.conditionGroup){if(!o.conditions||o.conditions.length===0)throw new D(`Rule "${t.name}" has an empty condition group`,null);for(let n of o.conditions){if(!n.type||!n.op)throw new D(`Rule "${t.name}" has an invalid condition`,null);let s=n.type==="header"||n.type==="cookie",a=n.op==="ex"||n.op==="nex";if(s){if(!n.key||typeof n.key!="string")throw new D(`Rule "${t.name}" has an invalid condition`,null);if(!a&&(n.value===void 0||n.value===null))throw new D(`Rule "${t.name}" has an invalid condition`,null)}else if(n.value===void 0||n.value===null)throw new D(`Rule "${t.name}" has an invalid condition`,null);let l=Array.isArray(n.value)?n.value:n.value!==void 0?[n.value]:[];if(Array.isArray(n.value)&&l.length===0)throw new D(`Rule "${t.name}" has an invalid value in condition`,null);if(n.type==="ip_address"){for(let c of l)if(typeof c!="string"||!this.isValidIP(c))throw new D(`Rule "${t.name}" has an invalid IP address in condition`,null)}if(n.type==="geo_as_number")for(let c of l){let d=typeof c=="number"?c:parseInt(String(c),10);if(!this.isValidASN(String(d)))throw new D(`Rule "${t.name}" has an invalid ASN in condition`,null)}if(n.type==="path"&&(n.op==="eq"||n.op==="pre")){for(let c of l)if(typeof c!="string"||!this.isValidPath(c))throw new D(`Rule "${t.name}" has an invalid path in condition`,null)}}}else throw new D("Either conditionGroup or type+values must be provided",null)}validateRuleAction(e){for(let t of e.rules)if(typeof t.action=="object"&&"mitigate"in t.action){let o=t.action.mitigate;if(o?.rateLimit){if(o.rateLimit.requests<=0)throw new D("Invalid rate limit configuration: requests must be positive",null);if(!o.rateLimit.window.match(/^\d+[smhd]$/))throw new D("Invalid rate limit configuration: invalid window format",null);if(parseInt(o.rateLimit.window)<=0)throw new D("Invalid rate limit configuration: window duration must be positive",null)}if(o?.actionDuration&&!o.actionDuration.match(/^\d+[smhd]$|^permanent$/))throw new D("Invalid action duration format: "+o.actionDuration,null);if(o?.redirect&&!o.redirect.location)throw new D("Invalid redirect configuration: location is required",null)}}isValidIP(e){let t=e.split("/"),o=t[0]??"",n=t[1],s=d=>{let u=d.split(".");return u.length!==4?!1:u.every(p=>{if(!/^\d{1,3}$/.test(p))return!1;let g=parseInt(p,10);return g>=0&&g<=255})},a=d=>(0,_i.isIPv6)(d),l=s(o),c=a(o);if(!l&&!c)return!1;if(n!==void 0){let d=parseInt(n,10);if(Number.isNaN(d)||l&&(d<0||d>32)||c&&(d<0||d>128))return!1}return!0}isValidASN(e){let t=parseInt(e,10);return!isNaN(t)&&t>=1&&t<=4294967295}isValidPath(e){return e.startsWith("/")&&!e.includes(" ")}};var Li=require("fs"),nt=require("path"),xt=[".doorman.json","vercel-firewall.config.json"],nn=xt[0],Ue=class{static async findConfig(e){let{findUp:t}=await import("find-up");for(let o of xt){let n=await t(o,{cwd:e||process.cwd()});if(n)return n}}static async findProjectRoot(e){let t=await this.findConfig(e);return t?(0,nt.dirname)(t):null}static configExists(e){return(0,Li.existsSync)((0,nt.resolve)(e))}static getDefaultConfigPath(){return(0,nt.resolve)(process.cwd(),nn)}static getSupportedFileNames(){return xt}};async function j(i,e="required"){let t=rn(e),o=i||await Ue.findConfig();if(!o||!(0,ne.existsSync)(o)){if(t==="optional")return r.debug("No config file found, returning empty config"),{};let s=Ue.getDefaultConfigPath();throw new Error(`No config file found. Run \`doorman init\` to create one at ${s}, or use --config to specify a custom path.`)}let n;try{let s=(0,ne.readFileSync)(o,"utf8");n=JSON.parse(s)}catch(s){throw s instanceof SyntaxError?new Error(`Invalid JSON in config file (${o}): ${s.message}`):s}if(t!=="raw")try{Re.getInstance().validateConfig(n)}catch(s){if(t==="lenient")r.warn("Config validation failed:",s);else throw s}return n}async function q(i,e,t={}){let{validate:o=!0,throwOnError:n=!0}=t,s=e||await Ue.findConfig()||Ue.getDefaultConfigPath();if(o)try{Re.getInstance().validateConfig(i)}catch(c){if(r.error("Config validation failed:",c),n)throw c}let a=(0,Di.dirname)(s);(0,ne.existsSync)(a)||(0,ne.mkdirSync)(a,{recursive:!0});let l=`${s}.${process.pid}.${(0,Ui.randomBytes)(4).toString("hex")}.tmp`;try{(0,ne.writeFileSync)(l,JSON.stringify(i,null,2)),(0,ne.renameSync)(l,s)}catch(c){try{(0,ne.existsSync)(l)&&(0,ne.unlinkSync)(l)}catch{}throw c}r.debug(`Config saved to ${s}`)}function rn(i){if(typeof i=="string")return i;let{validate:e=!0,throwOnError:t=!0}=i;return e?t?"required":"lenient":"raw"}var Ot=S(require("chalk")),xi=require("zod");T();function Z(i,e){i instanceof SyntaxError?r.log(Ie.wrapErrorBlock(["Invalid JSON format in config file:",` ${i.message}`])):i instanceof xi.ZodError?(r.error(Ot.default.red("Schema validation failed:")),i.errors.forEach(t=>{let o=t.path.join(".");r.error(Ot.default.red(` - ${o}: ${t.message}`))})):i instanceof Error&&i.name==="ValidationError"?r.error(i):i instanceof Error&&i.message.includes("Forbidden")?r.log(Ie.wrapErrorBlock([`Error ${e}:`," Access denied. Check that your token has the correct scope."," If using a team, ensure the token is scoped to that team."])):r.error(Ie.wrapErrorBlock([`Error ${e}:`,` ${i instanceof Error?i.message:String(i)}`])),process.exit(1)}var sn="add [type]",an="Add a new firewall rule to your configuration",ln={type:{type:"string",description:'Rule type: "rule" (default) or "ip"',default:"rule",choices:["rule","ip"]},interactive:{alias:"i",type:"boolean",description:"Guided prompts for rule creation",default:!1},name:{alias:"n",type:"string",description:"Rule name"},description:{type:"string",description:"Rule description"},field:{type:"string",description:"Condition field type (path, method, user_agent, etc.)"},op:{type:"string",description:"Operator (eq, pre, suf, sub, inc, re, ex, nex)"},value:{type:"string",description:"Match value (string or comma-separated for arrays)"},key:{type:"string",description:"Header/query/cookie key (required for header, cookie types)"},neg:{type:"boolean",description:"Negate the condition",default:!1},action:{alias:"a",type:"string",description:"Action type (deny, challenge, rate_limit, redirect, log, bypass)",default:"deny"},active:{type:"boolean",description:"Enable rule immediately",default:!0},requests:{type:"number",description:"Rate limit: max requests"},window:{type:"string",description:'Rate limit: time window (e.g., "60s", "5m")'},duration:{type:"string",description:'Action duration (e.g., "1h", "permanent")'},location:{type:"string",description:"Redirect URL"},permanent:{type:"boolean",description:"Redirect: use 301 instead of 302"},ip:{type:"string",description:"IP address or CIDR for IP blocking rules"},hostname:{type:"string",description:"Hostname for IP blocking rules",default:"*"},notes:{type:"string",description:"Notes for IP blocking rules"},config:{alias:"c",type:"string",description:"Config file path"},dryRun:{alias:"d",type:"boolean",description:"Show what would be added without writing",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1}},Ft=["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"],Nt=["eq","pre","suf","inc","sub","re","ex","nex"],Vt=["log","deny","challenge","bypass","rate_limit","redirect"];function Bt(i){let e=i.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");if(!e)throw new Error("Cannot generate rule ID: name must contain at least one alphanumeric character");return"rule_"+e}function Vi(i,e){return e==="inc"?i.split(",").map(t=>t.trim()):i}async function cn(){let i=await w("Rule name:",{type:"text"});if(!i.trim())throw new Error("Rule name cannot be empty");let e=await w("Description (optional):",{type:"text"}),t=[],o=!0;for(;o;){let u=[],p=!0;for(;p;){let g=await w("Condition type:",{type:"select",options:Ft,initial:"path"}),h=await w("Operator:",{type:"select",options:Nt,initial:"eq"}),I;(g==="header"||g==="cookie"||g==="query")&&(I=await w(`${g} key:`,{type:"text"}));let R;if(h!=="ex"&&h!=="nex"){let W=await w("Value:",{type:"text"});R=Vi(W,h)}let N=h!=="ex"&&h!=="nex"?await w("Negate this condition?",{type:"confirm",initial:!1}):!1,H={type:g,op:h,...R!==void 0&&{value:R},...I&&{key:I},...N&&{neg:N}};u.push(H),p=await w("Add another condition to this group? (AND logic)",{type:"confirm",initial:!1})}t.push({conditions:u}),o=await w("Add another condition group? (OR logic)",{type:"confirm",initial:!1})}let n=await w("Action:",{type:"select",options:Vt,initial:"deny"}),s;if(n==="rate_limit"){let u=parseInt(await w("Max requests:",{type:"text",initial:"100"}),10),p=await w('Time window (e.g., "60s", "1m", "1h"):',{type:"text",initial:"60s"});s={requests:u,window:p}}let a;if(n==="redirect"){let u=await w("Redirect URL:",{type:"text"}),p=await w("Permanent redirect (301)?",{type:"confirm",initial:!1});a={location:u,...p&&{permanent:p}}}let l;(n==="deny"||n==="challenge")&&await w("Set action duration? (default: permanent)",{type:"confirm",initial:!1})&&(l=await w('Duration (e.g., "1h", "1d", "permanent"):',{type:"text",initial:"permanent"}));let c=await w("Enable rule immediately?",{type:"confirm",initial:!0});return{id:Bt(i),name:i.trim(),...e.trim()&&{description:e.trim()},conditionGroup:t,action:{mitigate:{action:n,...s&&{rateLimit:s},...a&&{redirect:a},...l&&{actionDuration:l}}},active:c}}function dn(i){if(!i.name)throw new Error("--name is required in inline mode. Use --interactive for guided prompts.");if(!i.field)throw new Error("--field is required in inline mode (e.g., --field path)");if(!i.op)throw new Error("--op is required in inline mode (e.g., --op eq)");let e=i.op;if(!Nt.includes(e))throw new Error(`Invalid operator "${i.op}". Valid operators: ${Nt.join(", ")}`);let t=i.field;if(!Ft.includes(t))throw new Error(`Invalid field type "${i.field}". Valid types: ${Ft.join(", ")}`);let o=i.action||"deny";if(!Vt.includes(o))throw new Error(`Invalid action "${i.action}". Valid actions: ${Vt.join(", ")}`);if(e!=="ex"&&e!=="nex"&&!i.value)throw new Error("--value is required for the given operator");if((t==="header"||t==="cookie"||t==="query")&&!i.key)throw new Error(`--key is required for "${t}" condition type`);if(o==="rate_limit"&&(!i.requests||!i.window))throw new Error("--requests and --window are required when action is rate_limit");if(o==="redirect"&&!i.location)throw new Error("--location is required when action is redirect");let n=i.value?Vi(i.value,e):void 0,s={type:t,op:e,...n!==void 0&&{value:n},...i.key&&{key:i.key},...i.neg&&{neg:!0}};return{id:Bt(i.name),name:i.name.trim(),...i.description&&{description:i.description},conditionGroup:[{conditions:[s]}],action:{mitigate:{action:o,...o==="rate_limit"&&i.requests&&i.window&&{rateLimit:{requests:i.requests,window:i.window}},...o==="redirect"&&i.location&&{redirect:{location:i.location,...i.permanent&&{permanent:!0}}},...i.duration&&{actionDuration:i.duration}}},active:i.active!==!1}}async function un(){let i=await w("IP address or CIDR (e.g., 192.168.1.100/32):",{type:"text"});if(!i.trim())throw new Error("IP address cannot be empty");let e=await w("Hostname (use * for all):",{type:"text",initial:"*"}),t=await w("Notes (optional):",{type:"text"});return{ip:i.trim(),hostname:e.trim()||"*",...t.trim()&&{notes:t.trim()},action:"deny"}}function pn(i){if(!i.ip)throw new Error("--ip is required for IP blocking rules");return{ip:i.ip.trim(),hostname:i.hostname||"*",...i.notes&&{notes:i.notes},action:"deny"}}function fn(i,e){if(i.rules.map(n=>n.name.toLowerCase()).includes(e.name.toLowerCase()))return`A rule named "${e.name}" already exists`;let o=i.rules.map(n=>n.id).filter(Boolean);return e.id&&o.includes(e.id)?`A rule with ID "${e.id}" already exists`:null}function Oi(i){r.log(""),r.log(x.default.bold(` Rule: ${i.name}`)),i.description&&r.log(x.default.dim(` Description: ${i.description}`)),r.log(x.default.dim(` ID: ${i.id}`));let e=i.conditionGroup.map(n=>n.conditions.map(s=>{let a=s.neg?"NOT ":"",l=s.key?`[${s.key}] `:"",c=Array.isArray(s.value)?s.value.join(", "):s.value||"";return`${a}${s.type} ${l}${s.op} "${c}"`}).join(" AND "));r.log(x.default.dim(` Conditions: ${e.join(" OR ")}`));let t=i.action.mitigate.action,o=[];i.action.mitigate.rateLimit&&o.push(`${i.action.mitigate.rateLimit.requests} req/${i.action.mitigate.rateLimit.window}`),i.action.mitigate.redirect&&o.push(`\u2192 ${i.action.mitigate.redirect.location}`),i.action.mitigate.actionDuration&&o.push(`duration: ${i.action.mitigate.actionDuration}`),r.log(x.default.dim(` Action: ${t}${o.length?` (${o.join(", ")})`:""}`)),r.log(x.default.dim(` Active: ${i.active?"\u2705":"\u274C"}`))}function Fi(i){r.log(""),r.log(x.default.bold(` IP Rule: ${i.ip}`)),r.log(x.default.dim(` Hostname: ${i.hostname}`)),i.notes&&r.log(x.default.dim(` Notes: ${i.notes}`)),r.log(x.default.dim(` Action: ${i.action}`))}var gn=async i=>{try{if(i.debug&&(r.level=Ni.LogLevels.debug),r.debug("Add command arguments:",i),(i.type||"rule")==="ip"){let t=i.interactive?await un():pn(i),o=Lt.safeParse(t);if(o.success||(r.error(x.default.red("Rule validation failed:")),o.error.errors.forEach(a=>{let l=a.path.join(".");r.error(x.default.red(` - ${l||"ip"}: ${a.message}`))}),process.exit(1)),i.dryRun){r.info(x.default.cyan(`
22
- Dry run - The following IP rule would be added:`)),Fi(t),r.log(""),r.log(x.default.dim(JSON.stringify(t,null,2)));return}r.start("Loading configuration...");let n=await j(i.config,"raw"),s={...n,ips:[...n.ips||[],t]};await q(s,i.config),r.success(x.default.green(`\u2714 IP rule "${t.ip}" added to configuration`)),Fi(t)}else{let t=i.interactive?await cn():dn(i),o=St.safeParse(t);if(o.success||(r.error(x.default.red("Rule validation failed:")),o.error.errors.forEach(c=>{let d=c.path.join(".")||"rule";r.error(x.default.red(` - ${d}: ${c.message}`))}),process.exit(1)),i.dryRun){r.info(x.default.cyan(`
23
- Dry run - The following rule would be added:`)),Oi(t),r.log(""),r.log(x.default.dim(JSON.stringify(t,null,2)));return}r.start("Loading configuration...");let n=await j(i.config,"raw"),s=n.rules||[],a=fn({...n,rules:s},t);if(a&&(r.warn(x.default.yellow(`\u26A0\uFE0F ${a}`)),!await w("Proceed anyway?",{type:"confirm",initial:!1}))){r.info("Cancelled.");return}let l={...n,rules:[...s,t]};await q(l,i.config),r.success(x.default.green(`\u2714 Rule "${t.name}" added to configuration`)),Oi(t)}r.log(""),r.log(x.default.dim(`Run ${x.default.cyan("doorman sync")} to deploy this rule.`))}catch(e){Z(e,"adding rule")}};var Qt={};M(Qt,{builder:()=>dr,command:()=>lr,desc:()=>cr,handler:()=>ur});var Q=S(require("chalk")),ge=require("fs"),At=require("path"),mo=require("consola");T();pe();var Y={type:"string",choices:re,description:"Firewall provider (auto-detected)"};var go=require("consola");T();var po=S(require("chalk"));T();pe();jt();T();var mt=class{static detect(e){let t=[];if(e&&"provider"in e){let n=e.provider;if(typeof n=="string"&&this.isValidProvider(n))return t.push(`Explicit provider specified in config: ${e.provider}`),{provider:n,confidence:"high",reasons:t};r.warn(`Invalid provider specified in config: ${String(e.provider)}`)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let n=e.providers;if(typeof(n.cloudflare||{}).zoneId=="string")return t.push("Cloudflare zone ID found in config"),{provider:"cloudflare",confidence:"high",reasons:t};if(typeof(n.vercel||{}).projectId=="string")return t.push("Vercel project ID found in config"),{provider:"vercel",confidence:"high",reasons:t};if(typeof(n.fastly||{}).workspaceId=="string")return t.push("Fastly workspace ID found in config"),{provider:"fastly",confidence:"high",reasons:t}}if(e&&"projectId"in e&&typeof e.projectId=="string")return t.push("Legacy Vercel project ID found in config"),{provider:"vercel",confidence:"high",reasons:t};let o=this.detectFromEnvironment();return o.provider?o:(r.debug("Unable to auto-detect provider"),{provider:null,confidence:"low",reasons:["No provider information found in config or environment"]})}static detectFromEnvironment(){let e=[],t=process.env.DOORMAN_PROVIDER;return t&&this.isValidProvider(t)?(e.push(`Provider set via DOORMAN_PROVIDER environment variable: ${t}`),{provider:t,confidence:"high",reasons:e}):process.env.CLOUDFLARE_ZONE_ID&&process.env.CLOUDFLARE_API_TOKEN?(e.push("Cloudflare credentials found in environment variables"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.CLOUDFLARE_ZONE_ID?(e.push("Cloudflare zone ID found in environment"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID&&process.env.VERCEL_TOKEN?(e.push("Vercel credentials found in environment variables"),{provider:"vercel",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID?(e.push("Vercel project ID found in environment"),{provider:"vercel",confidence:"medium",reasons:e}):process.env.FASTLY_WORKSPACE_ID&&process.env.FASTLY_API_TOKEN?(e.push("Fastly credentials found in environment variables"),{provider:"fastly",confidence:"medium",reasons:e}):process.env.FASTLY_WORKSPACE_ID?(e.push("Fastly workspace ID found in environment"),{provider:"fastly",confidence:"medium",reasons:e}):{provider:null,confidence:"low",reasons:["No provider credentials found in environment"]}}static isValidProvider(e){return re.includes(e)}static getProvider(e,t="vercel"){let o=this.detect(e);return o.provider?(r.debug(`Provider detected: ${o.provider} (${o.confidence} confidence)`),o.reasons.length>0&&r.debug(`Detection reasons: ${o.reasons.join(", ")}`),o.provider):(r.debug(`No provider detected, using fallback: ${t}`),t)}static detectAll(e){let t=new Set;if(e&&"provider"in e){let o=e.provider;typeof o=="string"&&this.isValidProvider(o)&&t.add(o)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let o=e.providers;typeof(o.cloudflare||{}).zoneId=="string"&&t.add("cloudflare"),typeof(o.vercel||{}).projectId=="string"&&t.add("vercel"),typeof(o.fastly||{}).workspaceId=="string"&&t.add("fastly")}return e&&"projectId"in e&&typeof e.projectId=="string"&&t.add("vercel"),process.env.CLOUDFLARE_ZONE_ID&&t.add("cloudflare"),process.env.VERCEL_PROJECT_ID&&t.add("vercel"),process.env.FASTLY_WORKSPACE_ID&&t.add("fastly"),Array.from(t)}};var qt=S(require("chalk"));T();pe();var ht=i=>({$schema:Ri,firewallEnabled:!0,rules:[],ips:[],...i});T();var Ae=class{baseUrl;providerName;rateLimitInfo={};constructor(e,t){this.baseUrl=e,this.providerName=t}async makeRequest(e,t={}){let o=`${this.baseUrl}${e}`,{timeout:n=3e4,retries:s=3,retryDelay:a=1e3,...l}=t,c=null,d=null,u=null,p=()=>{u&&(clearTimeout(u),u=null),d&&(d.abort(),d=null)};try{for(let g=0;g<=s;g++)try{d=new AbortController,u=setTimeout(()=>{d&&d.abort()},n);let h=await fetch(o,{...l,headers:{"Content-Type":"application/json",...this.getAuthHeaders(),...l.headers},signal:d.signal});if(u&&(clearTimeout(u),u=null),this.updateRateLimitInfo(h),h.status===429){let R=this.calculateRateLimitWait(g,h);if(g===s)throw new Error(`${this.providerName} API rate limit exceeded after ${s+1} attempt(s) (429 Too Many Requests). Retry after ~${Math.round(R/1e3)}s.`);r.warn(`Rate limit exceeded for ${this.providerName}. Waiting ${R}ms before retry (attempt ${g+1}/${s+1})...`),await this.delay(R);continue}if(!h.ok)throw await this.handleErrorResponse(h);let I;try{let R=await h.text();R.trim()?I=JSON.parse(R):I={}}catch(R){throw r.error(`Failed to parse response from ${o}:`,R),new Error(`Invalid JSON response from ${this.providerName} API: ${R instanceof Error?R.message:String(R)}`)}return this.isLargeResponse(I)&&(r.debug(`Large response detected from ${o}, validating structure...`),this.validateLargeResponse(I)),I}catch(h){if(c=h,u&&(clearTimeout(u),u=null),this.isNonRetryableError(h)||g===s)throw h;let I=a*Math.pow(2,g),R=Math.random()*.1*I,N=Math.min(I+R,3e4);r.debug(`Request failed (attempt ${g+1}/${s+1}). Retrying in ${Math.round(N)}ms...`),r.debug(`Error details: ${h instanceof Error?h.message:String(h)}`),await this.delay(N)}throw c||new Error("Request failed after all retries")}finally{p()}}async get(e,t){return this.makeRequest(e,{...t,method:"GET"})}async post(e,t,o){return this.makeRequest(e,{...o,method:"POST",body:t?JSON.stringify(t):void 0})}async put(e,t,o){return this.makeRequest(e,{...o,method:"PUT",body:t?JSON.stringify(t):void 0})}async patch(e,t,o){return this.makeRequest(e,{...o,method:"PATCH",body:t?JSON.stringify(t):void 0})}async delete(e,t){return this.makeRequest(e,{...t,method:"DELETE"})}updateRateLimitInfo(e){let t=e.headers.get("X-RateLimit-Limit"),o=e.headers.get("X-RateLimit-Remaining"),n=e.headers.get("X-RateLimit-Reset");t&&(this.rateLimitInfo.limit=parseInt(t,10)),o&&(this.rateLimitInfo.remaining=parseInt(o,10)),n&&(this.rateLimitInfo.reset=parseInt(n,10)),this.rateLimitInfo.remaining&&this.rateLimitInfo.remaining<10&&r.warn(`Approaching rate limit for ${this.providerName}: ${this.rateLimitInfo.remaining} requests remaining`)}calculateRateLimitWait(e=0,t){let n=t?this.parseRetryAfter(t.headers.get("Retry-After")):null;if(n!==null)return Math.min(Math.max(n,1e3),6e4);if(this.rateLimitInfo.reset){let l=Math.floor(Date.now()/1e3),c=(this.rateLimitInfo.reset-l)*1e3;return Math.min(Math.max(c,1e3),6e4)}let a=5e3*Math.pow(2,e);return Math.min(a,6e4)}parseRetryAfter(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t))return t*1e3;let o=Date.parse(e);return Number.isNaN(o)?null:o-Date.now()}async handleErrorResponse(e){let t=`${this.providerName} API error: ${e.status} ${e.statusText}`,o=t;try{let n=await e.json();if(typeof n=="object"&&n!==null){let s=n;if(typeof s.error=="string")o=`${t} - ${s.error}`;else if(typeof s.message=="string")o=`${t} - ${s.message}`;else if(Array.isArray(s.errors)){let a=s.errors.map(l=>typeof l=="object"&&l!==null&&"message"in l?String(l.message):JSON.stringify(l)).join(", ");o=`${t} - ${a}`}}}catch{}return r.error(o),new Error(o)}isNonRetryableError(e){if(typeof e=="object"&&e!==null&&e.name==="AbortError")return!0;let t=e.message;return typeof t=="string"&&t.includes("API error: 4")?!t.includes("429"):!1}delay(e){return new Promise(t=>setTimeout(t,e))}getRateLimitInfo(){return{...this.rateLimitInfo}}isLargeResponse(e){if(!e||typeof e!="object")return!1;let t=(o,n=0)=>{if(n>10)return!1;for(let[,s]of Object.entries(o))if(Array.isArray(s)&&s.length>1e3||typeof s=="object"&&s!==null&&t(s,n+1))return!0;return!1};return t(e)}validateLargeResponse(e){if(!e||typeof e!="object")return;let t=(n,s)=>{n.length>5e3&&r.warn(`Large array detected at ${s} with ${n.length} items. This may impact performance.`);let a=Math.min(10,n.length),l=n[0];if(l&&typeof l=="object"){let c=Object.keys(l);for(let d=1;d<a;d++){let u=n[d];if(!u||typeof u!="object"){r.warn(`Inconsistent array structure at ${s}[${d}]: expected object, got ${typeof u}`);continue}let p=Object.keys(u),g=c.filter(h=>!p.includes(h));g.length>0&&r.warn(`Inconsistent array structure at ${s}[${d}]: missing keys ${g.join(", ")}`)}}},o=(n,s="root",a=0)=>{if(!(a>10))for(let[l,c]of Object.entries(n)){let d=`${s}.${l}`;Array.isArray(c)?t(c,d):typeof c=="object"&&c!==null&&o(c,d,a+1)}};o(e)}};var Wi=process.env.DOORMAN_VERCEL_API_BASE_URL||"https://api.vercel.com/v1/security/firewall/config",Me=class extends Ae{constructor(t,o,n){super("","vercel");this.projectId=t;this.teamId=o;this.token=n}projectId;teamId;token;getAuthHeaders(){return{Authorization:`Bearer ${this.token}`}}getUrl(t){let o=t!==void 0?`${Wi}/${t}`:Wi;r.debug("API URL:",o);let n=this.teamId?`&teamId=${this.teamId}`:"";return`${o}?projectId=${this.projectId}${n}`}async fetchFirewallConfig(t,o){let{allowCreate:n=!0}=o??{},s=await this.get(this.getUrl(t));if(r.debug("Config Version:",t??"latest"),r.debug("Fetched Config:",t?s:s.active),t)return s;if(!s||"active"in s&&s.active===null){if(r.warn(qt.default.bold("No firewall configuration found.")),!n)return r.debug("Skipping create-configuration prompt for read-only fetch."),this.emptyConfigPlaceholder();if(await w("Would you like to create one?",{type:"confirm"})){r.debug("Creating new empty firewall configuration...");let l=await this.putEmptyConfig();return r.debug("Empty firewall configuration created successfully"),r.debug(`New configuration version: ${qt.default.yellow(l.version)}`),l}else return s.active}return s.active}emptyConfigPlaceholder(){return{version:0,id:"",firewallEnabled:!0,crs:null,rules:[],ips:[],projectKey:"",ownerId:"",updatedAt:new Date(0).toISOString()}}async putEmptyConfig(){let{$schema:t,...o}=ht();return r.debug("Empty Config:",o),this.putConfig(o)}async putConfig(t){return(await this.put(this.getUrl(),t)).active}async fetchActiveFirewallRules(){return(await this.fetchFirewallConfig())?.rules}async updateFirewallRule(t){let o=!t.id||t.id==="-",n={action:o?"rules.insert":"rules.update",id:o?null:t.id,value:{name:t.name,description:t.description,action:t.action,conditionGroup:t.conditionGroup,active:t.active}};return this.patch(this.getUrl(),n)}async createFirewallRule(t){return this.updateFirewallRule({...t,id:"-"})}async deleteFirewallRule(t){let o={action:"rules.remove",id:t.id,value:null};await this.patch(this.getUrl(),o)}async updateIPBlockingRule(t){let o=!t.id||t.id==="-",n={action:o?"ip.insert":"ip.update",id:o?null:t.id,value:{action:t.action,hostname:t.hostname,ip:t.ip,notes:t.notes??null}};return this.patch(this.getUrl(),n)}async createIPBlockingRule(t){return this.updateIPBlockingRule({...t,id:"-"})}async deleteIPBlockingRule(t){let o={action:"ip.remove",id:t.id,value:null};await this.patch(this.getUrl(),o)}async verifyCredentials(){try{return await this.fetchFirewallConfig(),!0}catch(t){return r.debug("Credential verification failed:",t),!1}}};var te=S(require("chalk"));T();T();var Pe=class{validateConfig(e){let t=[],o=[];if(e||t.push({path:"root",message:"Configuration is required",code:"CONFIG_REQUIRED"}),e&&!e.rules&&t.push({path:"rules",message:"Rules array is required",code:"RULES_REQUIRED"}),e&&e.rules&&!Array.isArray(e.rules)&&t.push({path:"rules",message:"Rules must be an array",code:"RULES_INVALID_TYPE"}),e&&Array.isArray(e.rules)){let n=new Map;e.rules.forEach((s,a)=>{let l=s.id||s.name;if(!l)return;let c=n.get(l);if(c===void 0){n.set(l,a);return}let d=e.rules[c];o.push({path:`rules[${a}]`,message:s.id?`Rule "${s.name}" has the same id ("${s.id}") as rules[${c}] ("${d?.name}") \u2014 they will collide during sync diffing and one may be silently skipped.`:`Rule "${s.name}" has the same name as rules[${c}] and neither has an explicit id \u2014 they will collide during sync diffing and one may be silently skipped. Add unique ids to disambiguate.`,code:"DUPLICATE_RULE_IDENTIFIER"})})}return{valid:t.length===0,errors:t,warnings:o}}getHealthScore(e){let t=[],o=100;if(!e)return{score:0,grade:"poor",issues:[{severity:"error",category:"configuration",message:"No configuration found"}],recommendations:["Create a configuration file"]};if((!e.rules||e.rules.length===0)&&(o-=20,t.push({severity:"warning",category:"rules",message:"No rules defined",suggestion:"Add security rules to protect your application"})),e.rules&&e.rules.length>0){let a=e.rules.filter(l=>!l.description);a.length>0&&(o-=5,t.push({severity:"info",category:"maintainability",message:`${a.length} rule(s) missing descriptions`,suggestion:"Add descriptions to improve maintainability"}))}if(e.rules&&e.rules.length>0){let a=e.rules.filter(l=>l.active===!1||l.enabled===!1);a.length>0&&(o-=5,t.push({severity:"info",category:"maintenance",message:`${a.length} disabled rule(s) found`,suggestion:"Review and remove unused rules"}))}let n=this.calculateGrade(o),s=this.generateRecommendations(e,t);return{score:Math.max(0,o),grade:n,issues:t,recommendations:s}}diffItems(e,t,o,n="id"){let s=[],a=[],l=[],c=d=>d[n];for(let d of e){let u=t.find(p=>c(p)===c(d));u?o(d,u)||a.push(d):s.push(d)}for(let d of t)e.find(p=>c(p)===c(d))||l.push(d);return{toAdd:s,toUpdate:a,toDelete:l}}validateRuleCount(e,t){if(t&&e>t)throw new Error(`Rule count (${e}) exceeds provider limit (${t})`);t&&e>t*.9&&r.warn(`Approaching rule limit: ${e}/${t} rules`)}updateMetadata(e,t){return{...e,metadata:{...e.metadata,version:t,updatedAt:new Date().toISOString()}}}calculateGrade(e){return e>=80?"excellent":e>=60?"good":e>=40?"fair":"poor"}generateRecommendations(e,t){let o=[];return t.some(n=>n.category==="rules")&&o.push("Consider using predefined templates to get started"),t.some(n=>n.category==="maintainability")&&o.push("Add descriptions to all rules for better documentation"),t.some(n=>n.category==="maintenance")&&o.push("Remove or enable disabled rules to keep configuration clean"),o}logSyncStats(e){r.info(`Sync complete for ${this.name}:`),r.info(` Rules added: ${e.rulesAdded}`),r.info(` Rules updated: ${e.rulesUpdated}`),r.info(` Rules deleted: ${e.rulesDeleted}`),e.ipsAdded!==void 0&&(r.info(` IPs added: ${e.ipsAdded}`),r.info(` IPs updated: ${e.ipsUpdated}`),r.info(` IPs deleted: ${e.ipsDeleted}`)),e.version&&r.info(` New version: ${e.version}`)}};fe();function ji(i){let e=[],t=[];i.conditionGroup.forEach((s,a)=>{for(let l of s.conditions){let c=wn(l.op);l.op==="re"&&typeof l.value=="string"&&e.push(O.createWarning("regex_patterns",i.id,l.type,`Regular expression pattern may need adjustment for target provider: ${l.value}`,"Test the regex pattern in the target provider and adjust syntax if needed")),t.push({field:Rn(l.type),operator:c,value:l.value,negated:l.neg,key:l.key,group:a})}}),t.length>10&&e.push(O.createWarning("many_conditions",i.id,void 0,`Rule has ${t.length} conditions which may impact performance`,"Consider splitting complex rules into multiple simpler rules for better performance"));let o={type:i.action.mitigate.action,rateLimit:i.action.mitigate.rateLimit?{requests:i.action.mitigate.rateLimit.requests,window:i.action.mitigate.rateLimit.window,characteristics:i.action.mitigate.rateLimit.characteristics,mitigationTimeout:i.action.mitigate.rateLimit.mitigationTimeout,countingExpression:i.action.mitigate.rateLimit.countingExpression}:void 0,redirect:i.action.mitigate.redirect?{location:i.action.mitigate.redirect.location,permanent:i.action.mitigate.redirect.permanent}:void 0,duration:i.action.mitigate.actionDuration||void 0};return{result:{id:i.id,name:i.name,description:i.description,enabled:i.active,conditions:t,conditionLogic:i.conditionGroup.length>1?"OR":"AND",action:o},warnings:e}}function qi(i){let e=[],t=yn(i.conditions,i.id,e);if(i.action.response&&e.push(O.createUnsupportedFeatureWarning("custom response body","unified config","Vercel",i.id,"action.response")),t.length===0)throw new Error(`Rule "${i.name}" has no conditions Vercel can represent \u2014 every condition field is unsupported by Vercel (e.g. Cloudflare-only fields like referer/port). Cannot sync this rule to Vercel.`);return{result:{id:i.id,name:i.name,description:i.description,conditionGroup:t,action:{mitigate:{action:i.action.type,rateLimit:i.action.rateLimit?{requests:i.action.rateLimit.requests,window:i.action.rateLimit.window,characteristics:i.action.rateLimit.characteristics,mitigationTimeout:i.action.rateLimit.mitigationTimeout,countingExpression:i.action.rateLimit.countingExpression}:null,redirect:i.action.redirect?{location:i.action.redirect.location,permanent:i.action.redirect.permanent}:null,actionDuration:i.action.duration||null}},active:i.enabled},warnings:e}}function zi(i){return{id:i.id,ip:i.ip,hostname:i.hostname,notes:i.notes,action:i.action}}function yn(i,e,t){let o=new Map;for(let s of i){let a=s.group??0,l=o.get(a);l?l.push(s):o.set(a,[s])}let n=[];for(let s of o.values()){let a=[];for(let l of s){let c=vn(l.field);if(!c){t.push(O.createUnsupportedFeatureWarning(`condition field '${l.field}'`,"unified config","Vercel",e,l.field));continue}a.push({op:In(l.operator),neg:l.negated,type:c,key:l.key,value:l.value})}a.length>0&&n.push({conditions:a})}return n}function wn(i){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists",nex:"not_exists"}[i]||"eq"}function In(i){return{eq:"eq",starts_with:"pre",ends_with:"suf",in:"inc",contains:"sub",matches:"re",exists:"ex",not_exists:"nex"}[i]||"eq"}function Rn(i){return{host:"host",path:"path",method:"method",header:"header",query:"query",cookie:"cookie",ip_address:"ip",user_agent:"user_agent",geo_country:"country",geo_city:"city",geo_as_number:"asn",scheme:"scheme"}[i]||i}var Cn={host:"host",path:"path",method:"method",header:"header",query:"query",cookie:"cookie",ip:"ip_address",user_agent:"user_agent",country:"geo_country",city:"geo_city",asn:"geo_as_number",scheme:"scheme",target_path:"target_path",region:"region",protocol:"protocol",environment:"environment",geo_continent:"geo_continent",geo_country_region:"geo_country_region",ja4_digest:"ja4_digest",ja3_digest:"ja3_digest",rate_limit_api_id:"rate_limit_api_id"};function vn(i){return Cn[i]??null}fe();T();function Ge(i){return i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Mi(i){let e="";for(let t=0;t<i.length;t++)i[t]==="\\"&&(i[t+1]==="\\"||i[t+1]==='"')?(e+=i[t+1],t++):e+=i[t];return e}var st=class{static vercelToCloudflare={host:"http.host",path:"http.request.uri.path",method:"http.request.method",header:"http.request.headers",query:"http.request.uri.query",cookie:"http.cookie",target_path:"http.request.uri.path",ip_address:"ip.src",region:"ip.geoip.subdivision_1",protocol:"ssl",scheme:"ssl",environment:"",user_agent:"http.user_agent",geo_continent:"ip.geoip.continent",geo_country:"ip.geoip.country",geo_country_region:"ip.geoip.subdivision_1",geo_city:"ip.geoip.city",geo_as_number:"ip.geoip.asnum",ja4_digest:"",ja3_digest:"",rate_limit_api_id:""};static cloudflareToVercel={"http.host":"host","http.request.uri.path":"path","http.request.method":"method","http.request.headers":"header","http.request.uri.query":"query","http.cookie":"cookie","ip.src":"ip_address","ip.geoip.subdivision_1":"region",ssl:"protocol","http.user_agent":"user_agent","ip.geoip.continent":"geo_continent","ip.geoip.country":"geo_country","ip.geoip.city":"geo_city","ip.geoip.asnum":"geo_as_number"};static toCloudflare(e,t){let o=this.vercelToCloudflare[e];if(!o)throw r.warn(`No Cloudflare mapping for Vercel type: ${e}`),new Error(`Unsupported Vercel rule type for Cloudflare: ${e}`);return e==="header"&&t?`${o}["${Ge(t.toLowerCase())}"]`:e==="cookie"&&t?`${o}["${Ge(t)}"]`:o}static toVercel(e){let t=e.match(/http\.request\.headers\["([^"]+)"\]/);if(t)return{type:"header",key:t[1]};let o=e.match(/http\.cookie\["([^"]+)"\]/);if(o)return{type:"cookie",key:o[1]};if(e==="http.referer")return{type:"header",key:"referer"};let n=this.cloudflareToVercel[e];if(n)return{type:n};throw r.warn(`No Vercel mapping for Cloudflare field: ${e}`),new Error(`Unsupported Cloudflare field for Vercel: ${e}`)}static isCloudflareSupported(e){let t=this.vercelToCloudflare[e];return!!t&&t!==""}static isVercelSupported(e){return!!(this.cloudflareToVercel[e]||e==="http.referer"||e.startsWith("http.request.headers[")||e.startsWith("http.cookie["))}static getSupportedCloudflareFields(){return Object.values(this.vercelToCloudflare).filter(e=>e!=="")}static getSupportedVercelTypes(){return Object.keys(this.vercelToCloudflare).filter(e=>this.isCloudflareSupported(e))}};var bn=new Set(["ip.src"]),at=class{static fromVercelConditionGroups(e){if(!e||e.length===0)throw new Error("At least one condition group is required");let t=e.map(o=>{let n=o.conditions.map(s=>this.fromVercelCondition(s));if(n.length===0)throw new Error("Condition group must have at least one condition");return n.length>1?`(${n.join(" and ")})`:n[0]});return t.length>1?t.join(" or "):t[0]}static fromVercelCondition(e){let t=st.toCloudflare(e.type,e.key),o=this.buildExistsOrComparisonExpression(t,e.op,()=>`${this.mapVercelOperator(e.op)} ${this.formatValue(t,e.value)}`);return e.neg&&(o=`not (${o})`),o}static fromUnifiedConditions(e,t="AND"){if(!e||e.length===0)throw new Error("At least one condition is required");if(!e.some(a=>a.group!==void 0)){let a=e.map(c=>this.fromUnifiedCondition(c)),l=t==="AND"?" and ":" or ";return a.length>1?`(${a.join(l)})`:a[0]}let n=new Map;for(let a of e){let l=a.group??0,c=n.get(l);c?c.push(a):n.set(l,[a])}let s=Array.from(n.values()).map(a=>this.combineWithAnd(a.map(l=>this.fromUnifiedCondition(l))));return s.length>1?this.combineWithOr(s):s[0]}static fromUnifiedCondition(e){let t=this.mapUnifiedFieldToCloudflare(e.field),o=e.key&&(e.field==="header"||e.field==="cookie")?`${t}["${Ge(e.key)}"]`:t,n=this.buildUnifiedExpression(o,e.operator,e.value);return e.negated&&(n=`not (${n})`),n}static buildExistsOrComparisonExpression(e,t,o){return t==="ex"||t==="exists"?`${e} exists`:t==="nex"||t==="not_exists"?`not (${e} exists)`:`${e} ${o()}`}static buildUnifiedExpression(e,t,o){return t==="not_contains"?`not (${e} contains ${this.formatValue(e,o)})`:t==="not_in"?`not (${e} in ${this.formatValue(e,o)})`:this.buildExistsOrComparisonExpression(e,t,()=>`${this.mapUnifiedOperator(t)} ${this.formatValue(e,o)}`)}static mapVercelOperator(e){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists"}[e]||e}static mapUnifiedOperator(e){return{eq:"eq",ne:"ne",contains:"contains",starts_with:"starts_with",ends_with:"ends_with",matches:"matches",in:"in",gt:"gt",ge:"ge",lt:"lt",le:"le",exists:"exists"}[e]||e}static mapUnifiedFieldToCloudflare(e){return{ip:"ip.src",country:"ip.geoip.country",region:"ip.geoip.subdivision_1",city:"ip.geoip.city",asn:"ip.geoip.asnum",path:"http.request.uri.path",host:"http.host",method:"http.request.method",header:"http.request.headers",query:"http.request.uri.query",cookie:"http.cookie",user_agent:"http.user_agent",referer:"http.referer",scheme:"ssl",port:"cf.edge.server_port"}[e]||e}static formatValue(e,t){return Array.isArray(t)?`{${t.map(n=>this.formatSingleValue(e,n)).join(" ")}}`:this.formatSingleValue(e,t)}static formatSingleValue(e,t){if(typeof t=="string"){if(bn.has(e)){if(!ze.safeParse(t).success)throw new Error(`Invalid IP address or CIDR range: ${t}`);return t}return`"${Ge(t)}"`}return typeof t=="number"?String(t):typeof t=="boolean"?t?"true":"false":String(t)}static validate(e){if(!e||e.trim().length===0)return!1;let t=0;for(let o of e)if(o==="("&&t++,o===")"&&t--,t<0)return!1;return t===0}static combineWithAnd(e){if(e.length===0)throw new Error("At least one expression is required");return e.length===1?e[0]:`(${e.join(" and ")})`}static combineWithOr(e){if(e.length===0)throw new Error("At least one expression is required");return e.length===1?e[0]:`(${e.join(" or ")})`}};var En={"ip.src":"ip","ip.geoip.country":"country","ip.geoip.subdivision_1":"region","ip.geoip.city":"city","ip.geoip.asnum":"asn","http.request.uri.path":"path","http.host":"host","http.request.method":"method","http.request.headers":"header","http.request.uri.query":"query","http.cookie":"cookie","http.user_agent":"user_agent","http.referer":"referer",ssl:"scheme","cf.edge.server_port":"port"},Tn=new Set(["eq","ne","contains","starts_with","ends_with","matches","in","gt","ge","lt","le"]),An=new Set(["and","or","not"]),he=class extends Error{};function Pn(i){let e=[],t=0,o=i.length;for(;t<o;){let n=i[t];if(/\s/.test(n)){t++;continue}if(n==="("){e.push({type:"LPAREN",value:n}),t++;continue}if(n===")"){e.push({type:"RPAREN",value:n}),t++;continue}if(n==="{"){e.push({type:"LBRACE",value:n}),t++;continue}if(n==="}"){e.push({type:"RBRACE",value:n}),t++;continue}if(n==="["){e.push({type:"LBRACKET",value:n}),t++;continue}if(n==="]"){e.push({type:"RBRACKET",value:n}),t++;continue}if(n==='"'){let a=t+1,l="",c=!1;for(;a<o;){let d=i[a];if(d==="\\"&&a+1<o){l+=d+i[a+1],a+=2;continue}if(i[a]==='"'){c=!0,a++;break}l+=i[a],a++}if(!c)throw new he("Unterminated string literal");e.push({type:"STRING",value:Mi(l)}),t=a;continue}let s=t;for(;s<o&&!/[\s(){}[\]"]/.test(i[s]);)s++;if(s===t)throw new he(`Unexpected character '${n}' at position ${t}`);e.push({type:"WORD",value:i.slice(t,s)}),t=s}return e}var zt=class{constructor(e){this.tokens=e}tokens;pos=0;peek(){return this.tokens[this.pos]}next(){let e=this.tokens[this.pos];if(!e)throw new he("Unexpected end of expression");return this.pos++,e}expect(e,t){let o=this.next();if(o.type!==e||t!==void 0&&o.value!==t)throw new he(`Expected ${t??e} but got '${o.value}'`);return o}isWord(e){let t=this.peek();return!!t&&t.type==="WORD"&&t.value===e}atEnd(){return this.pos>=this.tokens.length}};function Mt(i){let e=[Gi(i)];for(;i.isWord("or");)i.next(),e.push(Gi(i));return e.length===1?e[0]:{type:"or",children:e}}function Gi(i){let e=[Ki(i)];for(;i.isWord("and");)i.next(),e.push(Ki(i));return e.length===1?e[0]:{type:"and",children:e}}function Ki(i){if(i.isWord("not")){i.next(),i.expect("LPAREN");let e=Mt(i);return i.expect("RPAREN"),{type:"not",child:e}}return kn(i)}function kn(i){let e=i.peek();if(e&&e.type==="LPAREN"){i.next();let t=Mt(i);return i.expect("RPAREN"),t}return Sn(i)}function $n(i){let e=i.expect("WORD");if(An.has(e.value))throw new he(`Expected a field reference but got keyword '${e.value}'`);if(i.peek()?.type==="LBRACKET"){i.next();let t=i.expect("STRING");return i.expect("RBRACKET"),{field:e.value,key:t.value}}return{field:e.value}}function Hi(i){let e=i.next();if(e.type==="STRING")return e.value;if(e.type==="WORD")return/^-?\d+(\.\d+)?$/.test(e.value)?Number(e.value):e.value;throw new he(`Unexpected token '${e.value}' where a value was expected`)}function _n(i){if(i.peek()?.type==="LBRACE"){i.next();let e=[];for(;i.peek()?.type!=="RBRACE";)e.push(Hi(i));return i.expect("RBRACE"),e}return Hi(i)}function Sn(i){let{field:e,key:t}=$n(i);if(i.isWord("exists"))return i.next(),{type:"exists",field:e,key:t};let o=i.next();if(o.type!=="WORD"||!Tn.has(o.value))throw new he(`Unsupported or unrecognized operator '${o.value}'`);let n=_n(i);return{type:"comparison",field:e,key:t,operator:o.value,value:n}}function Ln(i){let e=new zt(Pn(i)),t=Mt(e);if(!e.atEnd())throw new he("Unexpected trailing tokens");return t}function yt(i){return i.type==="comparison"||i.type==="exists"?!0:i.type==="not"?i.child.type==="comparison"||i.child.type==="exists":!1}function wt(i,e){let t=i.type==="not",o=i.type==="not"?i.child:i;if(o.type!=="comparison"&&o.type!=="exists")return null;let n=En[o.field];if(!n)return null;if(o.type==="exists")return{field:n,operator:t?"not_exists":"exists",value:"",key:o.key,group:e};let s=o.operator,a;return t&&(o.operator==="contains"?s="not_contains":o.operator==="in"?s="not_in":a=!0),{field:n,operator:s,value:o.value,key:o.key,negated:a,group:e}}function Un(i){if(yt(i)){let e=wt(i,0);return e?{conditions:[e],conditionLogic:"AND"}:null}if(i.type==="and"){let e=[];for(let t of i.children){if(!yt(t))return null;let o=wt(t,0);if(!o)return null;e.push(o)}return{conditions:e,conditionLogic:"AND"}}if(i.type==="or"){let e=[];i.children.forEach((n,s)=>{if(yt(n)){let a=wt(n,s);a&&e.push(a);return}if(n.type==="and")for(let a of n.children){if(!yt(a))return;let l=wt(a,s);l&&e.push(l)}});let t=i.children.length;return new Set(e.map(n=>n.group)).size!==t?null:{conditions:e,conditionLogic:"OR"}}return null}function Gt(i){if(!i||!i.trim())return null;try{let e=Ln(i);return Un(e)}catch{return null}}function Zi(i){let e=[],t=Gt(i.expression),o=[],n;t?(o=t.conditions,n=t.conditionLogic):e.push(O.createWarning("complex_expressions",i.id,"expression","Expression could not be parsed back into structured conditions \u2014 it may be hand-authored or use syntax outside what doorman itself generates.","Review the translated rule and add missing conditions manually if needed."));let s=i.action_parameters&&"response"in i.action_parameters?i.action_parameters.response:void 0,a={type:Dn(i.action),rateLimit:i.ratelimit?{requests:i.ratelimit.requests_per_period,window:`${i.ratelimit.period}s`,characteristics:i.ratelimit.characteristics,mitigationTimeout:i.ratelimit.mitigation_timeout,countingExpression:i.ratelimit.counting_expression}:void 0,response:s?{statusCode:s.status_code,content:s.content,contentType:s.content_type}:void 0};return{result:{id:i.id,name:i.description||`Rule ${i.id}`,description:i.description,enabled:i.enabled??!0,conditions:o,conditionLogic:n,action:a},warnings:e}}function Yi(i){let e=[],t=at.fromUnifiedConditions(i.conditions,i.conditionLogic),o={id:i.id||crypto.randomUUID(),action:xn(i.action.type),expression:t,description:i.description||i.name,enabled:i.enabled};return i.action.rateLimit&&(o.ratelimit={characteristics:i.action.rateLimit.characteristics||["ip.src"],period:On(i.action.rateLimit.window),requests_per_period:i.action.rateLimit.requests},i.action.rateLimit.mitigationTimeout?o.ratelimit.mitigation_timeout=i.action.rateLimit.mitigationTimeout:o.ratelimit.mitigation_timeout=3600,i.action.rateLimit.countingExpression&&(o.ratelimit.counting_expression=i.action.rateLimit.countingExpression)),i.action.response&&(o.action!=="block"?e.push(O.createUnsupportedFeatureWarning(`custom response on a '${o.action}' action`,"unified config","Cloudflare",i.id,"action.response")):i.action.response.content?o.action_parameters={response:{status_code:i.action.response.statusCode??403,content:i.action.response.content,content_type:i.action.response.contentType??"text/plain"}}:e.push(O.createWarning("lossy_conversion",i.id,"action.response","Custom response declared without `content`; Cloudflare requires a response body, so it was dropped.","Set action.response.content to the body you want returned."))),{result:o,warnings:e}}function Ji(i){if(!ze.safeParse(i.ip).success)throw new Error(`Invalid IP address or CIDR range: ${i.ip}`);let t=i.ip.includes("/")?`ip.src in {${i.ip}}`:`ip.src eq ${i.ip}`;return{id:i.id||crypto.randomUUID(),action:i.action==="allow"?"allow":"block",expression:t,description:i.notes||`IP ${i.action}: ${i.ip}${i.hostname?` (${i.hostname})`:""}`,enabled:!0}}function Dn(i){return{block:"deny",challenge:"challenge",managed_challenge:"challenge",js_challenge:"challenge",log:"log",skip:"bypass",allow:"allow",rewrite:"bypass",redirect:"redirect"}[i]||"deny"}function xn(i){return{log:"log",deny:"block",block:"block",challenge:"managed_challenge",bypass:"skip",rate_limit:"block",redirect:"redirect",allow:"allow"}[i]||"block"}function On(i){let e=i.match(/^(\d+)([smhd])$/);if(!e||!e[1]||!e[2])throw new Error(`Invalid window format: ${i}`);let t=parseInt(e[1],10),o=e[2],s={s:1,m:60,h:3600,d:86400}[o];if(s===void 0)throw new Error(`Invalid time unit: ${o}`);return t*s}fe();function se(i,e,t){return O.createWarning("complex_expressions",i,void 0,e,t)}var Fn={ip:"ip",path:"path",domain:"host",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},Nn={ip:"ip",path:"path",host:"domain",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},Vn={header:"request_header",query:"query_parameter",cookie:"request_cookie"},Bn={request_header:"header",query_parameter:"query",request_cookie:"cookie",response_header:"response_header",post_parameter:"post_parameter",signal:"signal"};function Wn(i){return Fn[i]??i}function jn(i){return Nn[i]??null}var qn={equals:{operator:"eq",negated:!1},does_not_equal:{operator:"eq",negated:!0},contains:{operator:"contains",negated:!1},does_not_contain:{operator:"contains",negated:!0},like:{operator:"matches",negated:!1},not_like:{operator:"matches",negated:!0},in_list:{operator:"in",negated:!1},not_in_list:{operator:"in",negated:!0},matches:{operator:"matches",negated:!1},does_not_match:{operator:"matches",negated:!0},greater_equal:{operator:"ge",negated:!1},lesser_equal:{operator:"le",negated:!1}};function Qi(i){return qn[i]??{operator:"eq",negated:!1}}function Xi(i,e,t,o){switch(i){case"eq":return e?"does_not_equal":"equals";case"ne":return"does_not_equal";case"contains":return e?"does_not_contain":"contains";case"not_contains":return"does_not_contain";case"starts_with":case"ends_with":return t.push(O.createWarning("regex_patterns",o,void 0,`Unified operator "${i}" has no direct Fastly equivalent \u2014 mapped to Fastly's wildcard "like" operator. Verify the translated value still matches as a wildcard pattern.`)),e?"not_like":"like";case"matches":return t.push(O.createWarning("regex_patterns",o,void 0,"Regular expression pattern may need adjustment for Fastly Next-Gen WAF regex syntax.")),e?"does_not_match":"matches";case"in":return e?"not_in_list":"in_list";case"not_in":return"not_in_list";case"gt":return t.push(se(o,'Unified operator "gt" (strictly greater than) has no Fastly equivalent \u2014 mapped to "greater_equal", which also matches the boundary value itself.')),"greater_equal";case"ge":return"greater_equal";case"lt":return t.push(se(o,'Unified operator "lt" (strictly less than) has no Fastly equivalent \u2014 mapped to "lesser_equal", which also matches the boundary value itself.')),"lesser_equal";case"le":return"lesser_equal";default:return"equals"}}function zn(i,e){let t=[],o=i.conditions.filter(s=>s.type==="group"),n=i.conditions.filter(s=>s.type!=="group");if(o.length>0&&n.length===0&&i.group_operator==="any")return o.forEach((s,a)=>{s.group_operator!=="all"&&e.push(se(i.id,`A condition group using "any" (OR) inside an outer "any" (OR) rule cannot be represented in doorman's flat AND-within/OR-across condition model \u2014 its members were kept in the same group (effectively AND'd) instead of OR'd. Review the translated rule against the original Fastly logic.`));for(let l of s.conditions)It(t,l,a,e,i.id)}),{conditions:t,conditionLogic:o.length>1?"OR":"AND"};if(o.length===0)return n.forEach((s,a)=>{let l=i.group_operator==="any"?a:0;It(t,s,l,e,i.id)}),{conditions:t,conditionLogic:i.group_operator==="any"&&n.length>1?"OR":"AND"};e.push(se(i.id,`Rule mixes top-level conditions with condition groups under group_operator "${i.group_operator}" \u2014 this doesn't fit doorman's flat AND-within/OR-across condition model. All conditions were combined with AND; review the translated rule against the original Fastly rule logic.`));for(let s of n)It(t,s,0,e,i.id);for(let s of o)for(let a of s.conditions)It(t,a,0,e,i.id);return{conditions:t,conditionLogic:"AND"}}function It(i,e,t,o,n){if(e.type==="single"){let{operator:u,negated:p}=Qi(e.operator);i.push({field:Wn(e.field),operator:u,value:e.value,...p?{negated:!0}:{},group:t});return}let s=Bn[e.field],a=e.conditions.find(u=>u.field==="name"),l=e.conditions.find(u=>u.field==="value"||u.field==="value_string");if(!l){o.push(se(n,`Multival condition on '${e.field}' has no value sub-condition doorman could extract (only a 'name' existence check) \u2014 skipped.`));return}let{operator:c,negated:d}=Qi(l.operator);i.push({field:s,operator:c,value:l.value,...d?{negated:!0}:{},...a?{key:a.value}:{},group:t})}function Mn(i,e){i.actions.length>1&&e.push(se(i.id,`Rule has ${i.actions.length} actions \u2014 doorman only models one action per rule; only the first ("${i.actions[0]?.type}") was translated.`));let t=i.actions[0];if(i.type==="rate_limit")return{type:"rate_limit",rateLimit:i.rate_limit?{requests:i.rate_limit.threshold,window:`${i.rate_limit.interval}s`,mitigationTimeout:i.rate_limit.duration}:void 0};switch(t?.type){case"block":return{type:"block"};case"allow":return{type:"allow"};case"browser_challenge":case"dynamic_challenge":case"verify_token":return{type:"challenge"};case"redirect":return{type:"redirect",redirect:{location:t.redirect_url??"",...t.response_code!==void 0?{statusCode:t.response_code}:{}}};case"add_signal":case"exclude_signal":case"deception":return e.push(O.createWarning("action_differences",i.id,"action.type",`Fastly action "${t.type}" tags or excludes a WAF signal rather than allowing/blocking the request \u2014 doorman has no matching action type. Mapped to "log" as the closest non-destructive fallback; review this rule.`)),{type:"log"};default:return e.push(se(i.id,`Unrecognised Fastly action type "${String(t?.type)}" \u2014 mapped to "log".`)),{type:"log"}}}function eo(i){let e=[],{conditions:t,conditionLogic:o}=zn(i,e),n=Mn(i,e);return t.length>10&&e.push(O.createWarning("many_conditions",i.id,void 0,`Rule has ${t.length} conditions which may impact performance`)),{result:{id:i.id,name:i.description||i.id,enabled:i.enabled,conditions:t,conditionLogic:o,action:n},warnings:e}}function Gn(i,e,t){let o=new Map;for(let a of i){let l=a.group??0,c=o.get(l);c?c.push(a):o.set(l,[a])}let n=a=>{let l=Vn[a.field];if(l){if(a.key===void 0)return t.push(se(e,`Condition on '${a.field}' has no 'key' set \u2014 Fastly needs a specific ${a.field} name to match on (e.g. a header name). Skipped.`)),null;let d=l==="request_header"||l==="response_header"?"value_string":"value";return{type:"multival",field:l,operator:"exists",group_operator:"all",conditions:[{type:"single",field:"name",operator:"equals",value:a.key},{type:"single",field:d,operator:Xi(a.operator,a.negated,t,e),value:String(a.value)}]}}let c=jn(a.field);return c?{type:"single",field:c,operator:Xi(a.operator,a.negated,t,e),value:String(a.value)}:(t.push(O.createUnsupportedFeatureWarning(`condition field '${a.field}'`,"unified config","Fastly",e,a.field)),null)};if(o.size<=1){let a=i.map(n).filter(l=>l!==null);return{conditions:a.filter(l=>l.type==="single"),groupConditions:[],multivalConditions:a.filter(l=>l.type==="multival"),groupOperator:"all"}}let s=[];for(let a of o.values()){let l=a.map(n).filter(c=>c!==null);l.length>0&&s.push({type:"group",group_operator:"all",conditions:l})}return{conditions:[],groupConditions:s,multivalConditions:[],groupOperator:"any"}}function Kn(i,e,t){switch(i.type){case"block":case"deny":return{type:"block"};case"allow":return{type:"allow"};case"challenge":return{type:"browser_challenge"};case"bypass":return e.push(se(t,'Unified action "bypass" has no direct Fastly equivalent \u2014 mapped to "allow".')),{type:"allow"};case"log":return e.push(se(t,'Unified action "log" has no dedicated Fastly action \u2014 mapped to "allow" (request_logging is enabled at the rule level regardless).')),{type:"allow"};case"redirect":return i.redirect?{type:"redirect",redirect_url:i.redirect.location,response_code:i.redirect.statusCode??(i.redirect.permanent?301:302)}:(e.push(se(t,'Unified action "redirect" has no redirect target \u2014 mapped to "allow".')),{type:"allow"});case"rate_limit":return{type:"block_signal"};default:return e.push(O.createUnsupportedFeatureWarning(`action type '${i.type}'`,"unified config","Fastly",t,"action.type")),{type:"block"}}}function Hn(i,e,t){let o=/^(\d+)\s*(s|m|h)?$/i.exec(i.trim()),n={s:1,m:60,h:3600},s=o?Number(o[1])*n[o[2]?.toLowerCase()||"s"]:NaN,a=[60,600,3600];if(!Number.isFinite(s)||s<=0)return e.push(O.createWarning("rate_limiting_precision",t,void 0,`Rate limit window "${i}" could not be parsed \u2014 defaulted to Fastly's 60-second interval.`)),60;let l=a.reduce((c,d)=>Math.abs(d-s)<Math.abs(c-s)?d:c);return l!==s&&e.push(O.createWarning("rate_limiting_precision",t,void 0,`Rate limit window "${i}" (${s}s) isn't one of Fastly's supported intervals (60s/600s/3600s) \u2014 rounded to ${l}s.`)),l}function Zn(i,e,t){if(!i)throw new Error(`Rule "${e??"(unnamed)"}" has action type "rate_limit" but no rateLimit configuration \u2014 Fastly requires a threshold and interval.`);let o=Hn(i.window,t,e);return t.push(O.createWarning("rate_limiting_precision",e,void 0,`Fastly rate-limit rules count requests against a named custom signal, which doorman does not create automatically \u2014 create a signal named "doorman-rate-limit-${e??"rule"}" in this workspace before syncing, or the rule will be rejected.`)),{client_identifiers:[{type:"ip"}],duration:i.mitigationTimeout??o,interval:o,signal:`doorman-rate-limit-${e??"rule"}`,threshold:i.requests}}function to(i){let e=[];i.description&&i.description!==i.name&&e.push(se(i.id,'Fastly rules have no separate "name" field \u2014 only "description" carries over, and it was set from this rule\'s `name`. The `description` text was dropped rather than merged in, to keep it round-trip-stable on the next sync.'));let{conditions:t,groupConditions:o,multivalConditions:n,groupOperator:s}=Gn(i.conditions,i.id,e);if(t.length===0&&o.length===0&&n.length===0)throw new Error(`Rule "${i.name}" has no conditions Fastly can represent \u2014 every condition field is unsupported by Fastly. Cannot sync this rule to Fastly.`);let a=i.action.type==="rate_limit";return{result:{type:a?"rate_limit":"request",description:i.name,enabled:i.enabled,group_operator:s,request_logging:"sampled",conditions:t,group_conditions:o,multival_conditions:n,actions:[Kn(i.action,e,i.id)],rate_limit:a?Zn(i.action.rateLimit,i.id,e):null},warnings:e}}function io(i,e){return i.map(t=>({ip:t,action:e}))}function oo(i){let e=[],t=[],o=[];for(let n of i)(n.hostname||n.notes)&&e.push(se(n.id,`IP rule "${n.ip}" sets ${n.hostname?"`hostname`":""}${n.hostname&&n.notes?" and ":""}${n.notes?"`notes`":""} \u2014 Fastly IP lists have no equivalent per-entry metadata; only the address was kept.`)),(n.action==="allow"?o:t).push(n.ip);return{result:{denyEntries:t,allowEntries:o},warnings:e}}var k=class{static vercelToUnified=ji;static unifiedToVercel=qi;static vercelIPToUnified=zi;static cloudflareToUnified=Zi;static unifiedToCloudflare=Yi;static unifiedIPToCloudflare=Ji;static fastlyToUnified=eo;static unifiedToFastly=to;static fastlyListEntriesToUnified=io;static unifiedIPsToFastlyEntries=oo};fe();function Ke(i,e){if(i===e)return!0;if(typeof i!="object"||i===null||typeof e!="object"||e===null||Array.isArray(i)!==Array.isArray(e))return!1;let t=Object.keys(i),o=Object.keys(e);if(t.length!==o.length)return!1;for(let n of t)if(!o.includes(n)||!Ke(i[n],e[n]))return!1;return!0}function ke(i){let{id:e,...t}=i;return t}function lt(i){return[...i].sort((e,t)=>{let o=e.priority!==void 0,n=t.priority!==void 0;return!o&&!n?0:o?n?e.priority-t.priority:-1:1})}function Rt(i){return i.some(e=>e.priority!==void 0)}var He=class extends Pe{constructor(t){super();this.client=t}client;name="vercel";async fetchConfig(t){try{r.debug("Fetching Vercel firewall configuration");let o=await this.client.fetchFirewallConfig(t),n=o.rules.map(a=>{let l=k.vercelToUnified(a);return l.warnings.length>0&&l.warnings.forEach(c=>{let{TranslationWarningSystem:d}=(fe(),ye(De)),u=d.formatWarning(c);r.warn(`Rule ${a.name}:
24
- ${u}`)}),l.result}),s=o.ips.map(a=>k.vercelIPToUnified(a));return{version:"2.0",provider:"vercel",providers:{vercel:{projectId:this.client.projectId,...this.client.teamId?{teamId:this.client.teamId}:{}}},rules:n,ips:s,metadata:{version:o.version,updatedAt:o.updatedAt}}}catch(o){throw r.error("Error fetching Vercel configuration:",o),new Error("Failed to fetch Vercel firewall configuration")}}async syncRules(t,o={}){let{dryRun:n=!1}=o;try{let{OperationSafety:s}=(bt(),ye(vt)),a=await s.performDryRunValidation(t,"sync rules",async f=>await this.getChanges(f,{allowCreate:!n}));if(!a.valid)throw new Error(`Dry-run validation failed: ${a.issues.join(", ")}`);let l=a.changes,{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u,version:p}=l,g=l.ipsToAdd||[],h=l.ipsToUpdate||[],I=l.ipsToDelete||[];if(n)return r.info("Dry run mode. The following changes would be made:"),r.info(`Custom Rules - Add: ${c.length}, Update: ${d.length}, Delete: ${u.length}`),r.info(`IP Rules - Add: ${g.length}, Update: ${h.length}, Delete: ${I.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,version:p,warnings:a.warnings};let R=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Vercel project ${this.client.projectId}`,changes:l,riskLevel:R,skipConfirmation:o.force||!1,dryRun:!1,allowDeletions:o.allowDeletions||!1}))throw new Error("Operation cancelled by user");let H=c.map(f=>k.unifiedToVercel(f).result),W=d.map(f=>k.unifiedToVercel(f).result),ue=u.map(f=>k.unifiedToVercel(f).result),me=g.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),_e=h.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),_=I.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),Ce=[],ve=[],be=[],We=[],Se=[],je=[],v=[],V=(f,b)=>`${f}: ${b instanceof Error?b.message:String(b)}`,ie=[];Rt(t.rules)&&t.rules.length>c.length&&ie.push("Rule `priority` is best-effort on Vercel: new rules are created in priority order, but rules that already exist remotely cannot be repositioned via the Vercel API. Recreate them (remove and re-add) if exact evaluation order matters.");let ae=[];for(let f of ue)try{r.debug(`Deleting custom rule: ${f.id}`),await this.client.deleteFirewallRule(f),be.push(f),r.debug(`Custom rule deleted: ${f.id}`)}catch(b){r.error(`Failed to delete custom rule ${f.id}:`,b),v.push(V(`Failed to delete custom rule ${f.id}`,b))}for(let f of _)try{r.debug(`Deleting IP blocking rule: ${f.id}`),await this.client.deleteIPBlockingRule(f),je.push(f),r.debug(`IP blocking rule deleted: ${f.id}`)}catch(b){r.error(`Failed to delete IP blocking rule ${f.id}:`,b),v.push(V(`Failed to delete IP blocking rule ${f.id}`,b))}for(let f of H)try{r.debug(`Adding new custom rule: ${f.name}`);let b=await this.client.createFirewallRule(f);Ce.push(b),b.id&&b.id!==f.id&&ae.push({oldId:f.id||void 0,newId:b.id,name:f.name}),r.debug(`New custom rule added: ${b.id}`)}catch(b){r.error(`Failed to add custom rule "${f.name}":`,b),v.push(V(`Failed to add custom rule "${f.name}"`,b))}for(let f of me)try{r.debug(`Adding new IP blocking rule: ${f.ip}`);let b=await this.client.createIPBlockingRule(f);We.push(b),r.debug(`New IP blocking rule added: (hostname): ${b.hostname} (ip): ${b.ip}`)}catch(b){r.error(`Failed to add IP blocking rule ${f.ip}:`,b),v.push(V(`Failed to add IP blocking rule ${f.ip}`,b))}for(let f of W)try{r.debug(`Updating custom rule: ${f.id}`);let b=await this.client.updateFirewallRule(f);ve.push(b),r.debug(`Custom rule updated: ${b.id}`)}catch(b){r.error(`Failed to update custom rule ${f.id}:`,b),v.push(V(`Failed to update custom rule ${f.id}`,b))}for(let f of _e)try{r.debug(`Updating IP blocking rule: ${f.id}`);let b=await this.client.updateIPBlockingRule(f);Se.push(b),r.debug(`IP blocking rule updated: ${b.id}`)}catch(b){r.error(`Failed to update IP blocking rule ${f.id}:`,b),v.push(V(`Failed to update IP blocking rule ${f.id}`,b))}r.debug(`${te.default.underline("Custom Rules:")} ${te.default.green("Added:")} ${te.default.green(Ce.length)}, ${te.default.cyan("Updated:")} ${te.default.cyan(ve.length)}, ${te.default.red("Deleted:")} ${te.default.red(be.length)}`),r.debug(`${te.default.underline("IP Rules:")} ${te.default.green("Added:")} ${te.default.green(We.length)}, ${te.default.cyan("Updated:")} ${te.default.cyan(Se.length)}, ${te.default.red("Deleted:")} ${te.default.red(je.length)}`);let it=p,ot,Ee=[...ie];try{let f=await this.client.fetchFirewallConfig();it=f.version,ot=f.updatedAt;let b=new Set(f.rules.map(F=>F.id)),mi=new Set(f.ips.map(F=>F.id));for(let F of[...Ce,...ve])F.id&&!b.has(F.id)&&Ee.push(`Rule "${F.name}" (${F.id}) was synced but is missing from the post-sync remote config \u2014 a subsequent sync may re-create or misdiff it.`);for(let F of be)F.id&&b.has(F.id)&&Ee.push(`Rule "${F.name}" (${F.id}) was deleted but still appears in the post-sync remote config.`);for(let F of[...We,...Se])F.id&&!mi.has(F.id)&&Ee.push(`IP rule "${F.ip}" (${F.id}) was synced but is missing from the post-sync remote config \u2014 a subsequent sync may re-create or misdiff it.`);for(let F of je)F.id&&mi.has(F.id)&&Ee.push(`IP rule "${F.ip}" (${F.id}) was deleted but still appears in the post-sync remote config.`)}catch(f){r.error("Failed to fetch updated firewall configuration version after sync:",f),v.push(V("Failed to fetch updated configuration version after sync",f))}return{success:v.length===0,rulesAdded:Ce.length,rulesUpdated:ve.length,rulesDeleted:be.length,ipsAdded:We.length,ipsUpdated:Se.length,ipsDeleted:je.length,version:it,updatedAt:ot,idRemappings:ae.length>0?ae:void 0,errors:v.length>0?v:void 0,warnings:Ee.length>0?Ee:void 0}}catch(s){throw r.error("Error during sync:",s),new Error(`Failed to synchronize firewall rules: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async getChanges(t,o){let n=Le.safeParse(t);if(!n.success)throw new Error(`Invalid firewall configuration: ${n.error.message}`);try{r.debug("Fetching existing firewall configuration");let s=await this.client.fetchFirewallConfig(void 0,{allowCreate:o?.allowCreate??!0});r.debug(`Fetched ${s.rules.length} custom rules and ${s.ips.length} IP blocking rules`);let a=s.rules.map(I=>{let R=k.vercelToUnified(I);return R.warnings.length>0&&R.warnings.forEach(N=>{let{TranslationWarningSystem:H}=(fe(),ye(De)),W=H.formatWarning(N);r.warn(`Rule ${I.name}:
25
- ${W}`)}),R.result}),{toAdd:l,toUpdate:c,toDelete:d}=this.diffRules(lt(t.rules),a),u=s.ips.map(I=>k.vercelIPToUnified(I)),{ipsToAdd:p,ipsToUpdate:g,ipsToDelete:h}=this.diffIPRules(t.ips||[],u);return{version:s.version,rulesToAdd:l,rulesToUpdate:c,rulesToDelete:d,ipsToAdd:p,ipsToUpdate:g,ipsToDelete:h,hasChanges:l.length>0||c.length>0||d.length>0||p.length>0||g.length>0||h.length>0}}catch(s){throw r.error("Error fetching existing firewall configuration:",s),new Error("Failed to fetch existing firewall configuration")}}getSupportedFeatures(){return{supportsCustomRules:!0,supportsIPBlocking:!0,supportsRateLimiting:!0,supportsGeoBlocking:!0,supportsManagedRules:!1,supportsRedirect:!0,supportsChallenge:!0}}async verifyCredentials(){return this.client.verifyCredentials()}validateConfig(t){let o=super.validateConfig(t),n=[...o.errors],s=[...o.warnings];t.provider&&t.provider!=="vercel"&&n.push({path:"provider",message:"Provider must be 'vercel' for VercelFirewallService",code:"INVALID_PROVIDER"});try{let a=Te.safeParse(t);a.success||n.push({path:"root",message:`Schema validation failed: ${a.error.message}`,code:"SCHEMA_VALIDATION_FAILED"})}catch(a){r.debug("Schema validation error:",a)}return{valid:n.length===0,errors:n,warnings:s}}getHealthScore(t){let o=super.getHealthScore(t),n=[...o.issues],s=o.score;return t.rules.filter(l=>l.action?.type==="rate_limit").length===0&&(s-=10,n.push({severity:"info",category:"security",message:"No rate limiting rules configured",suggestion:"Consider adding rate limiting to protect against abuse"})),(!t.ips||t.ips.length===0)&&n.push({severity:"info",category:"security",message:"No IP blocking rules configured",suggestion:"Consider blocking known malicious IPs"}),{score:Math.max(0,s),grade:o.grade,issues:n,recommendations:o.recommendations}}diffRules(t,o){let n=[],s=[],a=[...o];for(let l of t){let c=o.find(d=>d.id===l.id);if(!c)n.push(l);else{Ke(ke(l),ke(c))||s.push({...l,id:c.id});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{toAdd:n,toUpdate:s,toDelete:a}}diffIPRules(t,o){let n=[],s=[],a=[...o];for(let l of t){let c=o.find(d=>d.id===l.id);if(!c)r.debug("Rule not found in existing rules:",{configRule:l}),n.push(l);else{Ke(ke(l),ke(c))||s.push({...c,...l});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{ipsToAdd:n,ipsToUpdate:s,ipsToDelete:a}}};T();var Ze=class{static fromEnv(){let e=process.env.VERCEL_TOKEN,t=process.env.VERCEL_PROJECT_ID,o=process.env.VERCEL_TEAM_ID;if(!e)throw new Error("VERCEL_TOKEN environment variable is required");if(!t)throw new Error("VERCEL_PROJECT_ID environment variable is required");let n=new Me(t,o,e);return new He(n)}static fromConfig(e){let t=e.token||process.env.VERCEL_TOKEN,o=e.projectId||process.env.VERCEL_PROJECT_ID,n=e.teamId||process.env.VERCEL_TEAM_ID;if(!t)throw new Error("Vercel API token is required (provide token or set VERCEL_TOKEN env var)");if(!o)throw new Error("Vercel project ID is required (provide projectId or set VERCEL_PROJECT_ID env var)");r.debug("Creating Vercel provider with config:",{projectId:o,teamId:n});let s=new Me(o,n,t);return new He(s)}static create(e,t,o){return this.fromConfig({projectId:e,teamId:t,token:o})}};var so=require("crypto");T();var xe=S(require("chalk")),m=class i extends Error{code;suggestion;details;docsUrl;cause;constructor(e){super(e.message),this.name="DoormanError",this.code=e.code,this.suggestion=e.suggestion,this.details=e.details,this.docsUrl=e.docsUrl,this.cause=e.cause,Error.captureStackTrace&&Error.captureStackTrace(this,i)}format(){let e=[];return e.push(xe.default.red.bold(`[${this.code}] ${this.message}`)),e.push(""),this.suggestion&&(e.push(xe.default.yellow.bold("Suggestion:")),e.push(` ${this.suggestion}`),e.push("")),this.details&&Object.keys(this.details).length>0&&(e.push(xe.default.dim("Details:")),Object.entries(this.details).forEach(([t,o])=>{let n=typeof o=="object"?JSON.stringify(o,null,2).split(`
17
+ ${n}`}static formatDetailedRuleValidation(e,t){let n=ne.default.cyan(`Rule: ${e}`),o=t.map(s=>{let a=s.passed?ne.default.green("\u2713"):ne.default.red("\u2717"),l=s.passed?ne.default.green(s.name):ne.default.red(s.name);return` ${a} ${l}`}).join(`
18
+ `);return`${n}
19
+ ${o}`}};var x=class i extends Error{constructor(t,n,o,s=[]){super(t);this.ajvErrors=n;this.zodError=o;this.customErrors=s;this.name="ValidationError"}ajvErrors;zodError;customErrors;static formatErrors(t,n,o=[]){let s=[];return t?.length&&s.push(...t.map(Ie.formatValidationError)),n&&s.push(...n.errors.map(a=>`${a.path.join(".")}: ${a.message}`)),o.length&&s.push(...o),Ie.wrapErrorBlock(s)}getFormattedMessage(){return i.formatErrors(this.ajvErrors,this.zodError,this.customErrors)}},Re=class i{static instance;ajv;schema;constructor(){this.ajv=new Ui.default({allErrors:!0,verbose:!0}),this.schema=bi}static getInstance(){return i.instance||(i.instance=new i),i.instance}validateConfig(e){if(we(e))try{Si(e);return}catch(c){throw new x(`Invalid firewall configuration:
20
+ `+(c instanceof Error?c.message:String(c)),null)}let t=this.ajv.compile(this.schema),n=t(e),o=t.errors,s=Ae.safeParse(e),a;s.success||(a=s.error);let l=[];if(n&&s.success){try{this.validateRuleNames(e),this.validateRuleConditionGroup(e),this.validateRuleAction(e)}catch(c){if(c instanceof x)l.push(c.message,...c.customErrors||[]);else throw c}for(let c of e.rules){if(c.action.mitigate?.rateLimit){let d=St.safeParse(c.action.mitigate.rateLimit);d.success||l.push(...d.error.errors.map(u=>u.message))}if(c.conditionGroup)for(let d of c.conditionGroup){let u=_t.safeParse(d);u.success||l.push(...u.error.errors.map(p=>p.message))}}}if(!n||!s.success||l.length>0)throw new x(`Invalid firewall configuration:
21
+ `+x.formatErrors(o,a,l),o,a,l)}validateRuleNames(e){let t=new Set;for(let n of e.rules){if(t.has(n.name))throw new x(`Duplicate rule name found: "${n.name}"`,null);t.add(n.name)}}validateRuleConditionGroup(e){for(let t of e.rules)if(t.conditionGroup)for(let n of t.conditionGroup){if(!n.conditions||n.conditions.length===0)throw new x(`Rule "${t.name}" has an empty condition group`,null);for(let o of n.conditions){if(!o.type||!o.op)throw new x(`Rule "${t.name}" has an invalid condition`,null);let s=o.type==="header"||o.type==="cookie",a=o.op==="ex"||o.op==="nex";if(s){if(!o.key||typeof o.key!="string")throw new x(`Rule "${t.name}" has an invalid condition`,null);if(!a&&(o.value===void 0||o.value===null))throw new x(`Rule "${t.name}" has an invalid condition`,null)}else if(o.value===void 0||o.value===null)throw new x(`Rule "${t.name}" has an invalid condition`,null);let l=Array.isArray(o.value)?o.value:o.value!==void 0?[o.value]:[];if(Array.isArray(o.value)&&l.length===0)throw new x(`Rule "${t.name}" has an invalid value in condition`,null);if(o.type==="ip_address"){for(let c of l)if(typeof c!="string"||!this.isValidIP(c))throw new x(`Rule "${t.name}" has an invalid IP address in condition`,null)}if(o.type==="geo_as_number")for(let c of l){let d=typeof c=="number"?c:parseInt(String(c),10);if(!this.isValidASN(String(d)))throw new x(`Rule "${t.name}" has an invalid ASN in condition`,null)}if(o.type==="path"&&(o.op==="eq"||o.op==="pre")){for(let c of l)if(typeof c!="string"||!this.isValidPath(c))throw new x(`Rule "${t.name}" has an invalid path in condition`,null)}}}else throw new x("Either conditionGroup or type+values must be provided",null)}validateRuleAction(e){for(let t of e.rules)if(typeof t.action=="object"&&"mitigate"in t.action){let n=t.action.mitigate;if(n?.rateLimit){if(n.rateLimit.requests<=0)throw new x("Invalid rate limit configuration: requests must be positive",null);if(!n.rateLimit.window.match(/^\d+[smhd]$/))throw new x("Invalid rate limit configuration: invalid window format",null);if(parseInt(n.rateLimit.window)<=0)throw new x("Invalid rate limit configuration: window duration must be positive",null)}if(n?.actionDuration&&!n.actionDuration.match(/^\d+[smhd]$|^permanent$/))throw new x("Invalid action duration format: "+n.actionDuration,null);if(n?.redirect&&!n.redirect.location)throw new x("Invalid redirect configuration: location is required",null)}}isValidIP(e){let t=e.split("/"),n=t[0]??"",o=t[1],s=d=>{let u=d.split(".");return u.length!==4?!1:u.every(p=>{if(!/^\d{1,3}$/.test(p))return!1;let g=parseInt(p,10);return g>=0&&g<=255})},a=d=>(0,Li.isIPv6)(d),l=s(n),c=a(n);if(!l&&!c)return!1;if(o!==void 0){let d=parseInt(o,10);if(Number.isNaN(d)||l&&(d<0||d>32)||c&&(d<0||d>128))return!1}return!0}isValidASN(e){let t=parseInt(e,10);return!isNaN(t)&&t>=1&&t<=4294967295}isValidPath(e){return e.startsWith("/")&&!e.includes(" ")}};var Di=require("fs"),rt=require("path"),Ot=[".doorman.json","vercel-firewall.config.json"],ao=Ot[0],Ue=class{static async findConfig(e){let{findUp:t}=await import("find-up");for(let n of Ot){let o=await t(n,{cwd:e||process.cwd()});if(o)return o}}static async findProjectRoot(e){let t=await this.findConfig(e);return t?(0,rt.dirname)(t):null}static configExists(e){return(0,Di.existsSync)((0,rt.resolve)(e))}static getDefaultConfigPath(){return(0,rt.resolve)(process.cwd(),ao)}static getSupportedFileNames(){return Ot}};async function j(i,e="required"){let t=lo(e),n=i||await Ue.findConfig();if(!n||!(0,oe.existsSync)(n)){if(t==="optional")return r.debug("No config file found, returning empty config"),{};let s=Ue.getDefaultConfigPath();throw new Error(`No config file found. Run \`doorman init\` to create one at ${s}, or use --config to specify a custom path.`)}let o;try{let s=(0,oe.readFileSync)(n,"utf8");o=JSON.parse(s)}catch(s){throw s instanceof SyntaxError?new Error(`Invalid JSON in config file (${n}): ${s.message}`):s}if(t!=="raw")try{Re.getInstance().validateConfig(o)}catch(s){if(t==="lenient")r.warn("Config validation failed:",s);else throw s}return o}async function q(i,e,t={}){let{validate:n=!0,throwOnError:o=!0}=t,s=e||await Ue.findConfig()||Ue.getDefaultConfigPath();if(n)try{Re.getInstance().validateConfig(i)}catch(c){if(r.error("Config validation failed:",c),o)throw c}let a=(0,Oi.dirname)(s);(0,oe.existsSync)(a)||(0,oe.mkdirSync)(a,{recursive:!0});let l=`${s}.${process.pid}.${(0,xi.randomBytes)(4).toString("hex")}.tmp`;try{(0,oe.writeFileSync)(l,JSON.stringify(i,null,2)),(0,oe.renameSync)(l,s)}catch(c){try{(0,oe.existsSync)(l)&&(0,oe.unlinkSync)(l)}catch{}throw c}r.debug(`Config saved to ${s}`)}function lo(i){if(typeof i=="string")return i;let{validate:e=!0,throwOnError:t=!0}=i;return e?t?"required":"lenient":"raw"}var Ft=S(require("chalk")),Fi=require("zod");T();function Y(i,e){i instanceof SyntaxError?r.log(Ie.wrapErrorBlock(["Invalid JSON format in config file:",` ${i.message}`])):i instanceof Fi.ZodError?(r.error(Ft.default.red("Schema validation failed:")),i.errors.forEach(t=>{let n=t.path.join(".");r.error(Ft.default.red(` - ${n}: ${t.message}`))})):i instanceof Error&&i.name==="ValidationError"?r.error(i):i instanceof Error&&i.message.includes("Forbidden")?r.log(Ie.wrapErrorBlock([`Error ${e}:`," Access denied. Check that your token has the correct scope."," If using a team, ensure the token is scoped to that team."])):r.error(Ie.wrapErrorBlock([`Error ${e}:`,` ${i instanceof Error?i.message:String(i)}`])),process.exit(1)}var co="add [type]",uo="Add a new firewall rule to your configuration",po={type:{type:"string",description:'Rule type: "rule" (default) or "ip"',default:"rule",choices:["rule","ip"]},interactive:{alias:"i",type:"boolean",description:"Guided prompts for rule creation",default:!1},name:{alias:"n",type:"string",description:"Rule name"},description:{type:"string",description:"Rule description"},field:{type:"string",description:"Condition field type (path, method, user_agent, etc.)"},op:{type:"string",description:"Operator (eq, pre, suf, sub, inc, re, ex, nex)"},value:{type:"string",description:"Match value (string or comma-separated for arrays)"},key:{type:"string",description:"Header/query/cookie key (required for header, cookie types)"},neg:{type:"boolean",description:"Negate the condition",default:!1},action:{alias:"a",type:"string",description:"Action type (deny, challenge, rate_limit, redirect, log, bypass)",default:"deny"},active:{type:"boolean",description:"Enable rule immediately",default:!0},requests:{type:"number",description:"Rate limit: max requests"},window:{type:"string",description:'Rate limit: time window (e.g., "60s", "5m")'},duration:{type:"string",description:'Action duration (e.g., "1h", "permanent")'},location:{type:"string",description:"Redirect URL"},permanent:{type:"boolean",description:"Redirect: use 301 instead of 302"},ip:{type:"string",description:"IP address or CIDR for IP blocking rules"},hostname:{type:"string",description:"Hostname for IP blocking rules",default:"*"},notes:{type:"string",description:"Notes for IP blocking rules"},config:{alias:"c",type:"string",description:"Config file path"},dryRun:{alias:"d",type:"boolean",description:"Show what would be added without writing",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Nt=["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"],Vt=["eq","pre","suf","inc","sub","re","ex","nex"],Bt=["log","deny","challenge","bypass","rate_limit","redirect"];function Wt(i){let e=i.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");if(!e)throw new Error("Cannot generate rule ID: name must contain at least one alphanumeric character");return"rule_"+e}function Wi(i,e){return e==="inc"?i.split(",").map(t=>t.trim()):i}async function fo(){let i=await w("Rule name:",{type:"text"});if(!i.trim())throw new Error("Rule name cannot be empty");let e=await w("Description (optional):",{type:"text"}),t=[],n=!0;for(;n;){let u=[],p=!0;for(;p;){let g=await w("Condition type:",{type:"select",options:Nt,initial:"path"}),h=await w("Operator:",{type:"select",options:Vt,initial:"eq"}),I;(g==="header"||g==="cookie"||g==="query")&&(I=await w(`${g} key:`,{type:"text"}));let R;if(h!=="ex"&&h!=="nex"){let W=await w("Value:",{type:"text"});R=Wi(W,h)}let N=h!=="ex"&&h!=="nex"?await w("Negate this condition?",{type:"confirm",initial:!1}):!1,Z={type:g,op:h,...R!==void 0&&{value:R},...I&&{key:I},...N&&{neg:N}};u.push(Z),p=await w("Add another condition to this group? (AND logic)",{type:"confirm",initial:!1})}t.push({conditions:u}),n=await w("Add another condition group? (OR logic)",{type:"confirm",initial:!1})}let o=await w("Action:",{type:"select",options:Bt,initial:"deny"}),s;if(o==="rate_limit"){let u=parseInt(await w("Max requests:",{type:"text",initial:"100"}),10),p=await w('Time window (e.g., "60s", "1m", "1h"):',{type:"text",initial:"60s"});s={requests:u,window:p}}let a;if(o==="redirect"){let u=await w("Redirect URL:",{type:"text"}),p=await w("Permanent redirect (301)?",{type:"confirm",initial:!1});a={location:u,...p&&{permanent:p}}}let l;(o==="deny"||o==="challenge")&&await w("Set action duration? (default: permanent)",{type:"confirm",initial:!1})&&(l=await w('Duration (e.g., "1h", "1d", "permanent"):',{type:"text",initial:"permanent"}));let c=await w("Enable rule immediately?",{type:"confirm",initial:!0});return{id:Wt(i),name:i.trim(),...e.trim()&&{description:e.trim()},conditionGroup:t,action:{mitigate:{action:o,...s&&{rateLimit:s},...a&&{redirect:a},...l&&{actionDuration:l}}},active:c}}function go(i){if(!i.name)throw new Error("--name is required in inline mode. Use --interactive for guided prompts.");if(!i.field)throw new Error("--field is required in inline mode (e.g., --field path)");if(!i.op)throw new Error("--op is required in inline mode (e.g., --op eq)");let e=i.op;if(!Vt.includes(e))throw new Error(`Invalid operator "${i.op}". Valid operators: ${Vt.join(", ")}`);let t=i.field;if(!Nt.includes(t))throw new Error(`Invalid field type "${i.field}". Valid types: ${Nt.join(", ")}`);let n=i.action||"deny";if(!Bt.includes(n))throw new Error(`Invalid action "${i.action}". Valid actions: ${Bt.join(", ")}`);if(e!=="ex"&&e!=="nex"&&!i.value)throw new Error("--value is required for the given operator");if((t==="header"||t==="cookie"||t==="query")&&!i.key)throw new Error(`--key is required for "${t}" condition type`);if(n==="rate_limit"&&(!i.requests||!i.window))throw new Error("--requests and --window are required when action is rate_limit");if(n==="redirect"&&!i.location)throw new Error("--location is required when action is redirect");let o=i.value?Wi(i.value,e):void 0,s={type:t,op:e,...o!==void 0&&{value:o},...i.key&&{key:i.key},...i.neg&&{neg:!0}};return{id:Wt(i.name),name:i.name.trim(),...i.description&&{description:i.description},conditionGroup:[{conditions:[s]}],action:{mitigate:{action:n,...n==="rate_limit"&&i.requests&&i.window&&{rateLimit:{requests:i.requests,window:i.window}},...n==="redirect"&&i.location&&{redirect:{location:i.location,...i.permanent&&{permanent:!0}}},...i.duration&&{actionDuration:i.duration}}},active:i.active!==!1}}async function mo(){let i=await w("IP address or CIDR (e.g., 192.168.1.100/32):",{type:"text"});if(!i.trim())throw new Error("IP address cannot be empty");let e=await w("Hostname (use * for all):",{type:"text",initial:"*"}),t=await w("Notes (optional):",{type:"text"});return{ip:i.trim(),hostname:e.trim()||"*",...t.trim()&&{notes:t.trim()},action:"deny"}}function ho(i){if(!i.ip)throw new Error("--ip is required for IP blocking rules");return{ip:i.ip.trim(),hostname:i.hostname||"*",...i.notes&&{notes:i.notes},action:"deny"}}function yo(i,e){if(i.rules.map(o=>o.name.toLowerCase()).includes(e.name.toLowerCase()))return`A rule named "${e.name}" already exists`;let n=i.rules.map(o=>o.id).filter(Boolean);return e.id&&n.includes(e.id)?`A rule with ID "${e.id}" already exists`:null}function Ni(i){r.log(""),r.log(U.default.bold(` Rule: ${i.name}`)),i.description&&r.log(U.default.dim(` Description: ${i.description}`)),r.log(U.default.dim(` ID: ${i.id}`));let e=i.conditionGroup.map(o=>o.conditions.map(s=>{let a=s.neg?"NOT ":"",l=s.key?`[${s.key}] `:"",c=Array.isArray(s.value)?s.value.join(", "):s.value||"";return`${a}${s.type} ${l}${s.op} "${c}"`}).join(" AND "));r.log(U.default.dim(` Conditions: ${e.join(" OR ")}`));let t=i.action.mitigate.action,n=[];i.action.mitigate.rateLimit&&n.push(`${i.action.mitigate.rateLimit.requests} req/${i.action.mitigate.rateLimit.window}`),i.action.mitigate.redirect&&n.push(`\u2192 ${i.action.mitigate.redirect.location}`),i.action.mitigate.actionDuration&&n.push(`duration: ${i.action.mitigate.actionDuration}`),r.log(U.default.dim(` Action: ${t}${n.length?` (${n.join(", ")})`:""}`)),r.log(U.default.dim(` Active: ${i.active?"\u2705":"\u274C"}`))}function Vi(i){r.log(""),r.log(U.default.bold(` IP Rule: ${i.ip}`)),r.log(U.default.dim(` Hostname: ${i.hostname}`)),i.notes&&r.log(U.default.dim(` Notes: ${i.notes}`)),r.log(U.default.dim(` Action: ${i.action}`))}var wo=async i=>{try{if(i.debug&&(r.level=Bi.LogLevels.debug),r.debug("Add command arguments:",i),(i.type||"rule")==="ip"){let t=i.interactive?await mo():ho(i),n=Ut.safeParse(t);if(n.success||(r.error(U.default.red("Rule validation failed:")),n.error.errors.forEach(a=>{let l=a.path.join(".");r.error(U.default.red(` - ${l||"ip"}: ${a.message}`))}),process.exit(1)),i.dryRun){r.info(U.default.cyan(`
22
+ Dry run - The following IP rule would be added:`)),Vi(t),r.log(""),r.log(U.default.dim(JSON.stringify(t,null,2)));return}r.start("Loading configuration...");let o=await j(i.config,"raw"),s={...o,ips:[...o.ips||[],t]};await q(s,i.config),r.success(U.default.green(`\u2714 IP rule "${t.ip}" added to configuration`)),Vi(t)}else{let t=i.interactive?await fo():go(i),n=Lt.safeParse(t);if(n.success||(r.error(U.default.red("Rule validation failed:")),n.error.errors.forEach(c=>{let d=c.path.join(".")||"rule";r.error(U.default.red(` - ${d}: ${c.message}`))}),process.exit(1)),i.dryRun){r.info(U.default.cyan(`
23
+ Dry run - The following rule would be added:`)),Ni(t),r.log(""),r.log(U.default.dim(JSON.stringify(t,null,2)));return}r.start("Loading configuration...");let o=await j(i.config,"raw"),s=o.rules||[],a=yo({...o,rules:s},t);if(a){if(r.warn(U.default.yellow(`\u26A0\uFE0F ${a}`)),i.ci||!process.stdin.isTTY){r.info(U.default.dim("Skipping \u2014 non-interactive and a conflicting rule already exists. Rule not added."));return}if(!await w("Proceed anyway?",{type:"confirm",initial:!1})){r.info("Cancelled.");return}}let l={...o,rules:[...s,t]};await q(l,i.config),r.success(U.default.green(`\u2714 Rule "${t.name}" added to configuration`)),Ni(t)}r.log(""),r.log(U.default.dim(`Run ${U.default.cyan("doorman sync")} to deploy this rule.`))}catch(e){Y(e,"adding rule")}};var ei={};M(ei,{builder:()=>gr,command:()=>pr,desc:()=>fr,handler:()=>mr});var H=S(require("chalk")),ge=require("fs"),it=require("path"),In=require("consola");T();pe();var st=require("fs"),qt=require("path");function ji(i=process.cwd()){return(0,st.existsSync)((0,qt.join)(i,".git"))}function qi(i,e=process.cwd()){let t=(0,qt.join)(e,".gitignore");if(!(0,st.existsSync)(t))return!1;let n=i.replace(/^\.\//,"").replace(/^\//,"").replace(/\/$/,""),o;try{o=(0,st.readFileSync)(t,"utf8").split(`
24
+ `)}catch{return!1}return o.some(s=>{let a=s.trim();if(!a||a.startsWith("#"))return!1;let l=a.replace(/^\//,"").replace(/\/$/,"");return l===n||n.startsWith(`${l}/`)})}var J={type:"string",choices:re,description:"Firewall provider (auto-detected)"};var wn=require("consola");T();var hn=S(require("chalk"));T();pe();zt();T();var yt=class{static detect(e){let t=[];if(e&&"provider"in e){let o=e.provider;if(typeof o=="string"&&this.isValidProvider(o))return t.push(`Explicit provider specified in config: ${e.provider}`),{provider:o,confidence:"high",reasons:t};r.warn(`Invalid provider specified in config: ${String(e.provider)}`)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let o=e.providers;if(typeof(o.cloudflare||{}).zoneId=="string")return t.push("Cloudflare zone ID found in config"),{provider:"cloudflare",confidence:"high",reasons:t};if(typeof(o.vercel||{}).projectId=="string")return t.push("Vercel project ID found in config"),{provider:"vercel",confidence:"high",reasons:t};if(typeof(o.fastly||{}).workspaceId=="string")return t.push("Fastly workspace ID found in config"),{provider:"fastly",confidence:"high",reasons:t}}if(e&&"projectId"in e&&typeof e.projectId=="string")return t.push("Legacy Vercel project ID found in config"),{provider:"vercel",confidence:"high",reasons:t};let n=this.detectFromEnvironment();return n.provider?n:(r.debug("Unable to auto-detect provider"),{provider:null,confidence:"low",reasons:["No provider information found in config or environment"]})}static detectFromEnvironment(){let e=[],t=process.env.DOORMAN_PROVIDER;return t&&this.isValidProvider(t)?(e.push(`Provider set via DOORMAN_PROVIDER environment variable: ${t}`),{provider:t,confidence:"high",reasons:e}):process.env.CLOUDFLARE_ZONE_ID&&process.env.CLOUDFLARE_API_TOKEN?(e.push("Cloudflare credentials found in environment variables"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.CLOUDFLARE_ZONE_ID?(e.push("Cloudflare zone ID found in environment"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID&&process.env.VERCEL_TOKEN?(e.push("Vercel credentials found in environment variables"),{provider:"vercel",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID?(e.push("Vercel project ID found in environment"),{provider:"vercel",confidence:"medium",reasons:e}):process.env.FASTLY_WORKSPACE_ID&&process.env.FASTLY_API_TOKEN?(e.push("Fastly credentials found in environment variables"),{provider:"fastly",confidence:"medium",reasons:e}):process.env.FASTLY_WORKSPACE_ID?(e.push("Fastly workspace ID found in environment"),{provider:"fastly",confidence:"medium",reasons:e}):{provider:null,confidence:"low",reasons:["No provider credentials found in environment"]}}static isValidProvider(e){return re.includes(e)}static getProvider(e,t="vercel"){let n=this.detect(e);return n.provider?(r.debug(`Provider detected: ${n.provider} (${n.confidence} confidence)`),n.reasons.length>0&&r.debug(`Detection reasons: ${n.reasons.join(", ")}`),n.provider):(r.debug(`No provider detected, using fallback: ${t}`),t)}static detectAll(e){let t=new Set;if(e&&"provider"in e){let n=e.provider;typeof n=="string"&&this.isValidProvider(n)&&t.add(n)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let n=e.providers;typeof(n.cloudflare||{}).zoneId=="string"&&t.add("cloudflare"),typeof(n.vercel||{}).projectId=="string"&&t.add("vercel"),typeof(n.fastly||{}).workspaceId=="string"&&t.add("fastly")}return e&&"projectId"in e&&typeof e.projectId=="string"&&t.add("vercel"),process.env.CLOUDFLARE_ZONE_ID&&t.add("cloudflare"),process.env.VERCEL_PROJECT_ID&&t.add("vercel"),process.env.FASTLY_WORKSPACE_ID&&t.add("fastly"),Array.from(t)}};var Mt=S(require("chalk"));T();pe();var wt=i=>({$schema:vi,firewallEnabled:!0,rules:[],ips:[],...i});T();var Pe=class{baseUrl;providerName;rateLimitInfo={};constructor(e,t){this.baseUrl=e,this.providerName=t}async makeRequest(e,t={}){let n=`${this.baseUrl}${e}`,{timeout:o=3e4,retries:s=3,retryDelay:a=1e3,...l}=t,c=null,d=null,u=null,p=()=>{u&&(clearTimeout(u),u=null),d&&(d.abort(),d=null)};try{for(let g=0;g<=s;g++)try{d=new AbortController,u=setTimeout(()=>{d&&d.abort()},o);let h=await fetch(n,{...l,headers:{"Content-Type":"application/json",...this.getAuthHeaders(),...l.headers},signal:d.signal});if(u&&(clearTimeout(u),u=null),this.updateRateLimitInfo(h),h.status===429){let R=this.calculateRateLimitWait(g,h);if(g===s)throw new Error(`${this.providerName} API rate limit exceeded after ${s+1} attempt(s) (429 Too Many Requests). Retry after ~${Math.round(R/1e3)}s.`);r.warn(`Rate limit exceeded for ${this.providerName}. Waiting ${R}ms before retry (attempt ${g+1}/${s+1})...`),await this.delay(R);continue}if(!h.ok)throw await this.handleErrorResponse(h);let I;try{let R=await h.text();R.trim()?I=JSON.parse(R):I={}}catch(R){throw r.error(`Failed to parse response from ${n}:`,R),new Error(`Invalid JSON response from ${this.providerName} API: ${R instanceof Error?R.message:String(R)}`)}return this.isLargeResponse(I)&&(r.debug(`Large response detected from ${n}, validating structure...`),this.validateLargeResponse(I)),I}catch(h){if(c=h,u&&(clearTimeout(u),u=null),this.isNonRetryableError(h)||g===s)throw h;let I=a*Math.pow(2,g),R=Math.random()*.1*I,N=Math.min(I+R,3e4);r.debug(`Request failed (attempt ${g+1}/${s+1}). Retrying in ${Math.round(N)}ms...`),r.debug(`Error details: ${h instanceof Error?h.message:String(h)}`),await this.delay(N)}throw c||new Error("Request failed after all retries")}finally{p()}}async get(e,t){return this.makeRequest(e,{...t,method:"GET"})}async post(e,t,n){return this.makeRequest(e,{...n,method:"POST",body:t?JSON.stringify(t):void 0})}async put(e,t,n){return this.makeRequest(e,{...n,method:"PUT",body:t?JSON.stringify(t):void 0})}async patch(e,t,n){return this.makeRequest(e,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0})}async delete(e,t){return this.makeRequest(e,{...t,method:"DELETE"})}updateRateLimitInfo(e){let t=e.headers.get("X-RateLimit-Limit"),n=e.headers.get("X-RateLimit-Remaining"),o=e.headers.get("X-RateLimit-Reset");t&&(this.rateLimitInfo.limit=parseInt(t,10)),n&&(this.rateLimitInfo.remaining=parseInt(n,10)),o&&(this.rateLimitInfo.reset=parseInt(o,10)),this.rateLimitInfo.remaining&&this.rateLimitInfo.remaining<10&&r.warn(`Approaching rate limit for ${this.providerName}: ${this.rateLimitInfo.remaining} requests remaining`)}calculateRateLimitWait(e=0,t){let o=t?this.parseRetryAfter(t.headers.get("Retry-After")):null;if(o!==null)return Math.min(Math.max(o,1e3),6e4);if(this.rateLimitInfo.reset){let l=Math.floor(Date.now()/1e3),c=(this.rateLimitInfo.reset-l)*1e3;return Math.min(Math.max(c,1e3),6e4)}let a=5e3*Math.pow(2,e);return Math.min(a,6e4)}parseRetryAfter(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t))return t*1e3;let n=Date.parse(e);return Number.isNaN(n)?null:n-Date.now()}async handleErrorResponse(e){let t=`${this.providerName} API error: ${e.status} ${e.statusText}`,n=t;try{let o=await e.json();if(typeof o=="object"&&o!==null){let s=o;if(typeof s.error=="string")n=`${t} - ${s.error}`;else if(typeof s.message=="string")n=`${t} - ${s.message}`;else if(Array.isArray(s.errors)){let a=s.errors.map(l=>typeof l=="object"&&l!==null&&"message"in l?String(l.message):JSON.stringify(l)).join(", ");n=`${t} - ${a}`}}}catch{}return r.error(n),new Error(n)}isNonRetryableError(e){if(typeof e=="object"&&e!==null&&e.name==="AbortError")return!0;let t=e.message;return typeof t=="string"&&t.includes("API error: 4")?!t.includes("429"):!1}delay(e){return new Promise(t=>setTimeout(t,e))}getRateLimitInfo(){return{...this.rateLimitInfo}}isLargeResponse(e){if(!e||typeof e!="object")return!1;let t=(n,o=0)=>{if(o>10)return!1;for(let[,s]of Object.entries(n))if(Array.isArray(s)&&s.length>1e3||typeof s=="object"&&s!==null&&t(s,o+1))return!0;return!1};return t(e)}validateLargeResponse(e){if(!e||typeof e!="object")return;let t=(o,s)=>{o.length>5e3&&r.warn(`Large array detected at ${s} with ${o.length} items. This may impact performance.`);let a=Math.min(10,o.length),l=o[0];if(l&&typeof l=="object"){let c=Object.keys(l);for(let d=1;d<a;d++){let u=o[d];if(!u||typeof u!="object"){r.warn(`Inconsistent array structure at ${s}[${d}]: expected object, got ${typeof u}`);continue}let p=Object.keys(u),g=c.filter(h=>!p.includes(h));g.length>0&&r.warn(`Inconsistent array structure at ${s}[${d}]: missing keys ${g.join(", ")}`)}}},n=(o,s="root",a=0)=>{if(!(a>10))for(let[l,c]of Object.entries(o)){let d=`${s}.${l}`;Array.isArray(c)?t(c,d):typeof c=="object"&&c!==null&&n(c,d,a+1)}};n(e)}};var Mi=process.env.DOORMAN_VERCEL_API_BASE_URL||"https://api.vercel.com/v1/security/firewall/config",Me=class extends Pe{constructor(t,n,o){super("","vercel");this.projectId=t;this.teamId=n;this.token=o}projectId;teamId;token;getAuthHeaders(){return{Authorization:`Bearer ${this.token}`}}getUrl(t){let n=t!==void 0?`${Mi}/${t}`:Mi;r.debug("API URL:",n);let o=this.teamId?`&teamId=${this.teamId}`:"";return`${n}?projectId=${this.projectId}${o}`}async fetchFirewallConfig(t,n){let{allowCreate:o=!0}=n??{},s=await this.get(this.getUrl(t));if(r.debug("Config Version:",t??"latest"),r.debug("Fetched Config:",t?s:s.active),t)return s;if(!s||"active"in s&&s.active===null){if(r.warn(Mt.default.bold("No firewall configuration found.")),!o)return r.debug("Skipping create-configuration prompt for read-only fetch."),this.emptyConfigPlaceholder();if(await w("Would you like to create one?",{type:"confirm"})){r.debug("Creating new empty firewall configuration...");let l=await this.putEmptyConfig();return r.debug("Empty firewall configuration created successfully"),r.debug(`New configuration version: ${Mt.default.yellow(l.version)}`),l}else return s.active}return s.active}emptyConfigPlaceholder(){return{version:0,id:"",firewallEnabled:!0,crs:null,rules:[],ips:[],projectKey:"",ownerId:"",updatedAt:new Date(0).toISOString()}}async putEmptyConfig(){let{$schema:t,...n}=wt();return r.debug("Empty Config:",n),this.putConfig(n)}async putConfig(t){return(await this.put(this.getUrl(),t)).active}async fetchActiveFirewallRules(){return(await this.fetchFirewallConfig())?.rules}async updateFirewallRule(t){let n=!t.id||t.id==="-",o={action:n?"rules.insert":"rules.update",id:n?null:t.id,value:{name:t.name,description:t.description,action:t.action,conditionGroup:t.conditionGroup,active:t.active}};return this.patch(this.getUrl(),o)}async createFirewallRule(t){return this.updateFirewallRule({...t,id:"-"})}async deleteFirewallRule(t){let n={action:"rules.remove",id:t.id,value:null};await this.patch(this.getUrl(),n)}async updateIPBlockingRule(t){let n=!t.id||t.id==="-",o={action:n?"ip.insert":"ip.update",id:n?null:t.id,value:{action:t.action,hostname:t.hostname,ip:t.ip,notes:t.notes??null}};return this.patch(this.getUrl(),o)}async createIPBlockingRule(t){return this.updateIPBlockingRule({...t,id:"-"})}async deleteIPBlockingRule(t){let n={action:"ip.remove",id:t.id,value:null};await this.patch(this.getUrl(),n)}async verifyCredentials(){try{return await this.fetchFirewallConfig(),!0}catch(t){return r.debug("Credential verification failed:",t),!1}}};var te=S(require("chalk"));T();T();var ke=class{validateConfig(e){let t=[],n=[];if(e||t.push({path:"root",message:"Configuration is required",code:"CONFIG_REQUIRED"}),e&&!e.rules&&t.push({path:"rules",message:"Rules array is required",code:"RULES_REQUIRED"}),e&&e.rules&&!Array.isArray(e.rules)&&t.push({path:"rules",message:"Rules must be an array",code:"RULES_INVALID_TYPE"}),e&&Array.isArray(e.rules)){let o=new Map;e.rules.forEach((s,a)=>{let l=s.id||s.name;if(!l)return;let c=o.get(l);if(c===void 0){o.set(l,a);return}let d=e.rules[c];n.push({path:`rules[${a}]`,message:s.id?`Rule "${s.name}" has the same id ("${s.id}") as rules[${c}] ("${d?.name}") \u2014 they will collide during sync diffing and one may be silently skipped.`:`Rule "${s.name}" has the same name as rules[${c}] and neither has an explicit id \u2014 they will collide during sync diffing and one may be silently skipped. Add unique ids to disambiguate.`,code:"DUPLICATE_RULE_IDENTIFIER"})})}return{valid:t.length===0,errors:t,warnings:n}}getHealthScore(e){let t=[],n=100;if(!e)return{score:0,grade:"poor",issues:[{severity:"error",category:"configuration",message:"No configuration found"}],recommendations:["Create a configuration file"]};if((!e.rules||e.rules.length===0)&&(n-=20,t.push({severity:"warning",category:"rules",message:"No rules defined",suggestion:"Add security rules to protect your application"})),e.rules&&e.rules.length>0){let a=e.rules.filter(l=>!l.description);a.length>0&&(n-=5,t.push({severity:"info",category:"maintainability",message:`${a.length} rule(s) missing descriptions`,suggestion:"Add descriptions to improve maintainability"}))}if(e.rules&&e.rules.length>0){let a=e.rules.filter(l=>l.active===!1||l.enabled===!1);a.length>0&&(n-=5,t.push({severity:"info",category:"maintenance",message:`${a.length} disabled rule(s) found`,suggestion:"Review and remove unused rules"}))}let o=this.calculateGrade(n),s=this.generateRecommendations(e,t);return{score:Math.max(0,n),grade:o,issues:t,recommendations:s}}diffItems(e,t,n,o="id"){let s=[],a=[],l=[],c=d=>d[o];for(let d of e){let u=t.find(p=>c(p)===c(d));u?n(d,u)||a.push(d):s.push(d)}for(let d of t)e.find(p=>c(p)===c(d))||l.push(d);return{toAdd:s,toUpdate:a,toDelete:l}}validateRuleCount(e,t){if(t&&e>t)throw new Error(`Rule count (${e}) exceeds provider limit (${t})`);t&&e>t*.9&&r.warn(`Approaching rule limit: ${e}/${t} rules`)}updateMetadata(e,t){return{...e,metadata:{...e.metadata,version:t,updatedAt:new Date().toISOString()}}}calculateGrade(e){return e>=80?"excellent":e>=60?"good":e>=40?"fair":"poor"}generateRecommendations(e,t){let n=[];return t.some(o=>o.category==="rules")&&n.push("Consider using predefined templates to get started"),t.some(o=>o.category==="maintainability")&&n.push("Add descriptions to all rules for better documentation"),t.some(o=>o.category==="maintenance")&&n.push("Remove or enable disabled rules to keep configuration clean"),n}logSyncStats(e){r.info(`Sync complete for ${this.name}:`),r.info(` Rules added: ${e.rulesAdded}`),r.info(` Rules updated: ${e.rulesUpdated}`),r.info(` Rules deleted: ${e.rulesDeleted}`),e.ipsAdded!==void 0&&(r.info(` IPs added: ${e.ipsAdded}`),r.info(` IPs updated: ${e.ipsUpdated}`),r.info(` IPs deleted: ${e.ipsDeleted}`)),e.version&&r.info(` New version: ${e.version}`)}};fe();function Gi(i){let e=[],t=[];i.conditionGroup.forEach((s,a)=>{for(let l of s.conditions){let c=vo(l.op);l.op==="re"&&typeof l.value=="string"&&e.push(O.createWarning("regex_patterns",i.id,l.type,`Regular expression pattern may need adjustment for target provider: ${l.value}`,"Test the regex pattern in the target provider and adjust syntax if needed")),t.push({field:Eo(l.type),operator:c,value:l.value,negated:l.neg,key:l.key,group:a})}}),t.length>10&&e.push(O.createWarning("many_conditions",i.id,void 0,`Rule has ${t.length} conditions which may impact performance`,"Consider splitting complex rules into multiple simpler rules for better performance"));let n={type:i.action.mitigate.action,rateLimit:i.action.mitigate.rateLimit?{requests:i.action.mitigate.rateLimit.requests,window:i.action.mitigate.rateLimit.window,characteristics:i.action.mitigate.rateLimit.characteristics,mitigationTimeout:i.action.mitigate.rateLimit.mitigationTimeout,countingExpression:i.action.mitigate.rateLimit.countingExpression}:void 0,redirect:i.action.mitigate.redirect?{location:i.action.mitigate.redirect.location,permanent:i.action.mitigate.redirect.permanent}:void 0,duration:i.action.mitigate.actionDuration||void 0};return{result:{id:i.id,name:i.name,description:i.description,enabled:i.active,conditions:t,conditionLogic:i.conditionGroup.length>1?"OR":"AND",action:n},warnings:e}}function Ki(i){let e=[],t=Co(i.conditions,i.id,e);if(i.action.response&&e.push(O.createUnsupportedFeatureWarning("custom response body","unified config","Vercel",i.id,"action.response")),t.length===0)throw new Error(`Rule "${i.name}" has no conditions Vercel can represent \u2014 every condition field is unsupported by Vercel (e.g. Cloudflare-only fields like referer/port). Cannot sync this rule to Vercel.`);return{result:{id:i.id,name:i.name,description:i.description,conditionGroup:t,action:{mitigate:{action:i.action.type,rateLimit:i.action.rateLimit?{requests:i.action.rateLimit.requests,window:i.action.rateLimit.window,characteristics:i.action.rateLimit.characteristics,mitigationTimeout:i.action.rateLimit.mitigationTimeout,countingExpression:i.action.rateLimit.countingExpression}:null,redirect:i.action.redirect?{location:i.action.redirect.location,permanent:i.action.redirect.permanent}:null,actionDuration:i.action.duration||null}},active:i.enabled},warnings:e}}function Hi(i){return{id:i.id,ip:i.ip,hostname:i.hostname,notes:i.notes,action:i.action}}function Co(i,e,t){let n=new Map;for(let s of i){let a=s.group??0,l=n.get(a);l?l.push(s):n.set(a,[s])}let o=[];for(let s of n.values()){let a=[];for(let l of s){let c=Ao(l.field);if(!c){t.push(O.createUnsupportedFeatureWarning(`condition field '${l.field}'`,"unified config","Vercel",e,l.field));continue}a.push({op:bo(l.operator),neg:l.negated,type:c,key:l.key,value:l.value})}a.length>0&&o.push({conditions:a})}return o}function vo(i){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists",nex:"not_exists"}[i]||"eq"}function bo(i){return{eq:"eq",starts_with:"pre",ends_with:"suf",in:"inc",contains:"sub",matches:"re",exists:"ex",not_exists:"nex"}[i]||"eq"}function Eo(i){return{host:"host",path:"path",method:"method",header:"header",query:"query",cookie:"cookie",ip_address:"ip",user_agent:"user_agent",geo_country:"country",geo_city:"city",geo_as_number:"asn",scheme:"scheme"}[i]||i}var To={host:"host",path:"path",method:"method",header:"header",query:"query",cookie:"cookie",ip:"ip_address",user_agent:"user_agent",country:"geo_country",city:"geo_city",asn:"geo_as_number",scheme:"scheme",target_path:"target_path",region:"region",protocol:"protocol",environment:"environment",geo_continent:"geo_continent",geo_country_region:"geo_country_region",ja4_digest:"ja4_digest",ja3_digest:"ja3_digest",rate_limit_api_id:"rate_limit_api_id"};function Ao(i){return To[i]??null}fe();T();function Ge(i){return i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Zi(i){let e="";for(let t=0;t<i.length;t++)i[t]==="\\"&&(i[t+1]==="\\"||i[t+1]==='"')?(e+=i[t+1],t++):e+=i[t];return e}var lt=class{static vercelToCloudflare={host:"http.host",path:"http.request.uri.path",method:"http.request.method",header:"http.request.headers",query:"http.request.uri.query",cookie:"http.cookie",target_path:"http.request.uri.path",ip_address:"ip.src",region:"ip.geoip.subdivision_1",protocol:"ssl",scheme:"ssl",environment:"",user_agent:"http.user_agent",geo_continent:"ip.geoip.continent",geo_country:"ip.geoip.country",geo_country_region:"ip.geoip.subdivision_1",geo_city:"ip.geoip.city",geo_as_number:"ip.geoip.asnum",ja4_digest:"",ja3_digest:"",rate_limit_api_id:""};static cloudflareToVercel={"http.host":"host","http.request.uri.path":"path","http.request.method":"method","http.request.headers":"header","http.request.uri.query":"query","http.cookie":"cookie","ip.src":"ip_address","ip.geoip.subdivision_1":"region",ssl:"protocol","http.user_agent":"user_agent","ip.geoip.continent":"geo_continent","ip.geoip.country":"geo_country","ip.geoip.city":"geo_city","ip.geoip.asnum":"geo_as_number"};static toCloudflare(e,t){let n=this.vercelToCloudflare[e];if(!n)throw r.warn(`No Cloudflare mapping for Vercel type: ${e}`),new Error(`Unsupported Vercel rule type for Cloudflare: ${e}`);return e==="header"&&t?`${n}["${Ge(t.toLowerCase())}"]`:e==="cookie"&&t?`${n}["${Ge(t)}"]`:n}static toVercel(e){let t=e.match(/http\.request\.headers\["([^"]+)"\]/);if(t)return{type:"header",key:t[1]};let n=e.match(/http\.cookie\["([^"]+)"\]/);if(n)return{type:"cookie",key:n[1]};if(e==="http.referer")return{type:"header",key:"referer"};let o=this.cloudflareToVercel[e];if(o)return{type:o};throw r.warn(`No Vercel mapping for Cloudflare field: ${e}`),new Error(`Unsupported Cloudflare field for Vercel: ${e}`)}static isCloudflareSupported(e){let t=this.vercelToCloudflare[e];return!!t&&t!==""}static isVercelSupported(e){return!!(this.cloudflareToVercel[e]||e==="http.referer"||e.startsWith("http.request.headers[")||e.startsWith("http.cookie["))}static getSupportedCloudflareFields(){return Object.values(this.vercelToCloudflare).filter(e=>e!=="")}static getSupportedVercelTypes(){return Object.keys(this.vercelToCloudflare).filter(e=>this.isCloudflareSupported(e))}};var Po=new Set(["ip.src"]),ct=class{static fromVercelConditionGroups(e){if(!e||e.length===0)throw new Error("At least one condition group is required");let t=e.map(n=>{let o=n.conditions.map(s=>this.fromVercelCondition(s));if(o.length===0)throw new Error("Condition group must have at least one condition");return o.length>1?`(${o.join(" and ")})`:o[0]});return t.length>1?t.join(" or "):t[0]}static fromVercelCondition(e){let t=lt.toCloudflare(e.type,e.key),n=this.buildExistsOrComparisonExpression(t,e.op,()=>`${this.mapVercelOperator(e.op)} ${this.formatValue(t,e.value)}`);return e.neg&&(n=`not (${n})`),n}static fromUnifiedConditions(e,t="AND"){if(!e||e.length===0)throw new Error("At least one condition is required");if(!e.some(a=>a.group!==void 0)){let a=e.map(c=>this.fromUnifiedCondition(c)),l=t==="AND"?" and ":" or ";return a.length>1?`(${a.join(l)})`:a[0]}let o=new Map;for(let a of e){let l=a.group??0,c=o.get(l);c?c.push(a):o.set(l,[a])}let s=Array.from(o.values()).map(a=>this.combineWithAnd(a.map(l=>this.fromUnifiedCondition(l))));return s.length>1?this.combineWithOr(s):s[0]}static fromUnifiedCondition(e){let t=this.mapUnifiedFieldToCloudflare(e.field),n=e.key&&(e.field==="header"||e.field==="cookie")?`${t}["${Ge(e.key)}"]`:t,o=this.buildUnifiedExpression(n,e.operator,e.value);return e.negated&&(o=`not (${o})`),o}static buildExistsOrComparisonExpression(e,t,n){return t==="ex"||t==="exists"?`${e} exists`:t==="nex"||t==="not_exists"?`not (${e} exists)`:`${e} ${n()}`}static buildUnifiedExpression(e,t,n){return t==="not_contains"?`not (${e} contains ${this.formatValue(e,n)})`:t==="not_in"?`not (${e} in ${this.formatValue(e,n)})`:this.buildExistsOrComparisonExpression(e,t,()=>`${this.mapUnifiedOperator(t)} ${this.formatValue(e,n)}`)}static mapVercelOperator(e){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists"}[e]||e}static mapUnifiedOperator(e){return{eq:"eq",ne:"ne",contains:"contains",starts_with:"starts_with",ends_with:"ends_with",matches:"matches",in:"in",gt:"gt",ge:"ge",lt:"lt",le:"le",exists:"exists"}[e]||e}static mapUnifiedFieldToCloudflare(e){return{ip:"ip.src",country:"ip.geoip.country",region:"ip.geoip.subdivision_1",city:"ip.geoip.city",asn:"ip.geoip.asnum",path:"http.request.uri.path",host:"http.host",method:"http.request.method",header:"http.request.headers",query:"http.request.uri.query",cookie:"http.cookie",user_agent:"http.user_agent",referer:"http.referer",scheme:"ssl",port:"cf.edge.server_port"}[e]||e}static formatValue(e,t){return Array.isArray(t)?`{${t.map(o=>this.formatSingleValue(e,o)).join(" ")}}`:this.formatSingleValue(e,t)}static formatSingleValue(e,t){if(typeof t=="string"){if(Po.has(e)){if(!ze.safeParse(t).success)throw new Error(`Invalid IP address or CIDR range: ${t}`);return t}return`"${Ge(t)}"`}return typeof t=="number"?String(t):typeof t=="boolean"?t?"true":"false":String(t)}static validate(e){if(!e||e.trim().length===0)return!1;let t=0;for(let n of e)if(n==="("&&t++,n===")"&&t--,t<0)return!1;return t===0}static combineWithAnd(e){if(e.length===0)throw new Error("At least one expression is required");return e.length===1?e[0]:`(${e.join(" and ")})`}static combineWithOr(e){if(e.length===0)throw new Error("At least one expression is required");return e.length===1?e[0]:`(${e.join(" or ")})`}};var ko={"ip.src":"ip","ip.geoip.country":"country","ip.geoip.subdivision_1":"region","ip.geoip.city":"city","ip.geoip.asnum":"asn","http.request.uri.path":"path","http.host":"host","http.request.method":"method","http.request.headers":"header","http.request.uri.query":"query","http.cookie":"cookie","http.user_agent":"user_agent","http.referer":"referer",ssl:"scheme","cf.edge.server_port":"port"},$o=new Set(["eq","ne","contains","starts_with","ends_with","matches","in","gt","ge","lt","le"]),_o=new Set(["and","or","not"]),he=class extends Error{};function So(i){let e=[],t=0,n=i.length;for(;t<n;){let o=i[t];if(/\s/.test(o)){t++;continue}if(o==="("){e.push({type:"LPAREN",value:o}),t++;continue}if(o===")"){e.push({type:"RPAREN",value:o}),t++;continue}if(o==="{"){e.push({type:"LBRACE",value:o}),t++;continue}if(o==="}"){e.push({type:"RBRACE",value:o}),t++;continue}if(o==="["){e.push({type:"LBRACKET",value:o}),t++;continue}if(o==="]"){e.push({type:"RBRACKET",value:o}),t++;continue}if(o==='"'){let a=t+1,l="",c=!1;for(;a<n;){let d=i[a];if(d==="\\"&&a+1<n){l+=d+i[a+1],a+=2;continue}if(i[a]==='"'){c=!0,a++;break}l+=i[a],a++}if(!c)throw new he("Unterminated string literal");e.push({type:"STRING",value:Zi(l)}),t=a;continue}let s=t;for(;s<n&&!/[\s(){}[\]"]/.test(i[s]);)s++;if(s===t)throw new he(`Unexpected character '${o}' at position ${t}`);e.push({type:"WORD",value:i.slice(t,s)}),t=s}return e}var Gt=class{constructor(e){this.tokens=e}tokens;pos=0;peek(){return this.tokens[this.pos]}next(){let e=this.tokens[this.pos];if(!e)throw new he("Unexpected end of expression");return this.pos++,e}expect(e,t){let n=this.next();if(n.type!==e||t!==void 0&&n.value!==t)throw new he(`Expected ${t??e} but got '${n.value}'`);return n}isWord(e){let t=this.peek();return!!t&&t.type==="WORD"&&t.value===e}atEnd(){return this.pos>=this.tokens.length}};function Kt(i){let e=[Yi(i)];for(;i.isWord("or");)i.next(),e.push(Yi(i));return e.length===1?e[0]:{type:"or",children:e}}function Yi(i){let e=[Ji(i)];for(;i.isWord("and");)i.next(),e.push(Ji(i));return e.length===1?e[0]:{type:"and",children:e}}function Ji(i){if(i.isWord("not")){i.next(),i.expect("LPAREN");let e=Kt(i);return i.expect("RPAREN"),{type:"not",child:e}}return Lo(i)}function Lo(i){let e=i.peek();if(e&&e.type==="LPAREN"){i.next();let t=Kt(i);return i.expect("RPAREN"),t}return xo(i)}function Uo(i){let e=i.expect("WORD");if(_o.has(e.value))throw new he(`Expected a field reference but got keyword '${e.value}'`);if(i.peek()?.type==="LBRACKET"){i.next();let t=i.expect("STRING");return i.expect("RBRACKET"),{field:e.value,key:t.value}}return{field:e.value}}function Qi(i){let e=i.next();if(e.type==="STRING")return e.value;if(e.type==="WORD")return/^-?\d+(\.\d+)?$/.test(e.value)?Number(e.value):e.value;throw new he(`Unexpected token '${e.value}' where a value was expected`)}function Do(i){if(i.peek()?.type==="LBRACE"){i.next();let e=[];for(;i.peek()?.type!=="RBRACE";)e.push(Qi(i));return i.expect("RBRACE"),e}return Qi(i)}function xo(i){let{field:e,key:t}=Uo(i);if(i.isWord("exists"))return i.next(),{type:"exists",field:e,key:t};let n=i.next();if(n.type!=="WORD"||!$o.has(n.value))throw new he(`Unsupported or unrecognized operator '${n.value}'`);let o=Do(i);return{type:"comparison",field:e,key:t,operator:n.value,value:o}}function Oo(i){let e=new Gt(So(i)),t=Kt(e);if(!e.atEnd())throw new he("Unexpected trailing tokens");return t}function It(i){return i.type==="comparison"||i.type==="exists"?!0:i.type==="not"?i.child.type==="comparison"||i.child.type==="exists":!1}function Rt(i,e){let t=i.type==="not",n=i.type==="not"?i.child:i;if(n.type!=="comparison"&&n.type!=="exists")return null;let o=ko[n.field];if(!o)return null;if(n.type==="exists")return{field:o,operator:t?"not_exists":"exists",value:"",key:n.key,group:e};let s=n.operator,a;return t&&(n.operator==="contains"?s="not_contains":n.operator==="in"?s="not_in":a=!0),{field:o,operator:s,value:n.value,key:n.key,negated:a,group:e}}function Fo(i){if(It(i)){let e=Rt(i,0);return e?{conditions:[e],conditionLogic:"AND"}:null}if(i.type==="and"){let e=[];for(let t of i.children){if(!It(t))return null;let n=Rt(t,0);if(!n)return null;e.push(n)}return{conditions:e,conditionLogic:"AND"}}if(i.type==="or"){let e=[];i.children.forEach((o,s)=>{if(It(o)){let a=Rt(o,s);a&&e.push(a);return}if(o.type==="and")for(let a of o.children){if(!It(a))return;let l=Rt(a,s);l&&e.push(l)}});let t=i.children.length;return new Set(e.map(o=>o.group)).size!==t?null:{conditions:e,conditionLogic:"OR"}}return null}function Ht(i){if(!i||!i.trim())return null;try{let e=Oo(i);return Fo(e)}catch{return null}}function Xi(i){let e=[],t=Ht(i.expression),n=[],o;t?(n=t.conditions,o=t.conditionLogic):e.push(O.createWarning("complex_expressions",i.id,"expression","Expression could not be parsed back into structured conditions \u2014 it may be hand-authored or use syntax outside what doorman itself generates.","Review the translated rule and add missing conditions manually if needed."));let s=i.action_parameters&&"response"in i.action_parameters?i.action_parameters.response:void 0,a={type:No(i.action),rateLimit:i.ratelimit?{requests:i.ratelimit.requests_per_period,window:`${i.ratelimit.period}s`,characteristics:i.ratelimit.characteristics,mitigationTimeout:i.ratelimit.mitigation_timeout,countingExpression:i.ratelimit.counting_expression}:void 0,response:s?{statusCode:s.status_code,content:s.content,contentType:s.content_type}:void 0};return{result:{id:i.id,name:i.description||`Rule ${i.id}`,description:i.description,enabled:i.enabled??!0,conditions:n,conditionLogic:o,action:a},warnings:e}}function en(i){let e=[],t=ct.fromUnifiedConditions(i.conditions,i.conditionLogic),n={id:i.id||crypto.randomUUID(),action:Vo(i.action.type),expression:t,description:i.description||i.name,enabled:i.enabled};return i.action.rateLimit&&(n.ratelimit={characteristics:i.action.rateLimit.characteristics||["ip.src"],period:Bo(i.action.rateLimit.window),requests_per_period:i.action.rateLimit.requests},i.action.rateLimit.mitigationTimeout?n.ratelimit.mitigation_timeout=i.action.rateLimit.mitigationTimeout:n.ratelimit.mitigation_timeout=3600,i.action.rateLimit.countingExpression&&(n.ratelimit.counting_expression=i.action.rateLimit.countingExpression)),i.action.response&&(n.action!=="block"?e.push(O.createUnsupportedFeatureWarning(`custom response on a '${n.action}' action`,"unified config","Cloudflare",i.id,"action.response")):i.action.response.content?n.action_parameters={response:{status_code:i.action.response.statusCode??403,content:i.action.response.content,content_type:i.action.response.contentType??"text/plain"}}:e.push(O.createWarning("lossy_conversion",i.id,"action.response","Custom response declared without `content`; Cloudflare requires a response body, so it was dropped.","Set action.response.content to the body you want returned."))),{result:n,warnings:e}}function tn(i){if(!ze.safeParse(i.ip).success)throw new Error(`Invalid IP address or CIDR range: ${i.ip}`);let t=i.ip.includes("/")?`ip.src in {${i.ip}}`:`ip.src eq ${i.ip}`;return{id:i.id||crypto.randomUUID(),action:i.action==="allow"?"allow":"block",expression:t,description:i.notes||`IP ${i.action}: ${i.ip}${i.hostname?` (${i.hostname})`:""}`,enabled:!0}}function No(i){return{block:"deny",challenge:"challenge",managed_challenge:"challenge",js_challenge:"challenge",log:"log",skip:"bypass",allow:"allow",rewrite:"bypass",redirect:"redirect"}[i]||"deny"}function Vo(i){return{log:"log",deny:"block",block:"block",challenge:"managed_challenge",bypass:"skip",rate_limit:"block",redirect:"redirect",allow:"allow"}[i]||"block"}function Bo(i){let e=i.match(/^(\d+)([smhd])$/);if(!e||!e[1]||!e[2])throw new Error(`Invalid window format: ${i}`);let t=parseInt(e[1],10),n=e[2],s={s:1,m:60,h:3600,d:86400}[n];if(s===void 0)throw new Error(`Invalid time unit: ${n}`);return t*s}fe();function se(i,e,t){return O.createWarning("complex_expressions",i,void 0,e,t)}var Wo={ip:"ip",path:"path",domain:"host",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},jo={ip:"ip",path:"path",host:"domain",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},qo={header:"request_header",query:"query_parameter",cookie:"request_cookie"},zo={request_header:"header",query_parameter:"query",request_cookie:"cookie",response_header:"response_header",post_parameter:"post_parameter",signal:"signal"};function Mo(i){return Wo[i]??i}function Go(i){return jo[i]??null}var Ko={equals:{operator:"eq",negated:!1},does_not_equal:{operator:"eq",negated:!0},contains:{operator:"contains",negated:!1},does_not_contain:{operator:"contains",negated:!0},like:{operator:"matches",negated:!1},not_like:{operator:"matches",negated:!0},in_list:{operator:"in",negated:!1},not_in_list:{operator:"in",negated:!0},matches:{operator:"matches",negated:!1},does_not_match:{operator:"matches",negated:!0},greater_equal:{operator:"ge",negated:!1},lesser_equal:{operator:"le",negated:!1}};function nn(i){return Ko[i]??{operator:"eq",negated:!1}}function on(i,e,t,n){switch(i){case"eq":return e?"does_not_equal":"equals";case"ne":return"does_not_equal";case"contains":return e?"does_not_contain":"contains";case"not_contains":return"does_not_contain";case"starts_with":case"ends_with":return t.push(O.createWarning("regex_patterns",n,void 0,`Unified operator "${i}" has no direct Fastly equivalent \u2014 mapped to Fastly's wildcard "like" operator. Verify the translated value still matches as a wildcard pattern.`)),e?"not_like":"like";case"matches":return t.push(O.createWarning("regex_patterns",n,void 0,"Regular expression pattern may need adjustment for Fastly Next-Gen WAF regex syntax.")),e?"does_not_match":"matches";case"in":return e?"not_in_list":"in_list";case"not_in":return"not_in_list";case"gt":return t.push(se(n,'Unified operator "gt" (strictly greater than) has no Fastly equivalent \u2014 mapped to "greater_equal", which also matches the boundary value itself.')),"greater_equal";case"ge":return"greater_equal";case"lt":return t.push(se(n,'Unified operator "lt" (strictly less than) has no Fastly equivalent \u2014 mapped to "lesser_equal", which also matches the boundary value itself.')),"lesser_equal";case"le":return"lesser_equal";default:return"equals"}}function Ho(i,e){let t=[],n=i.conditions.filter(s=>s.type==="group"),o=i.conditions.filter(s=>s.type!=="group");if(n.length>0&&o.length===0&&i.group_operator==="any")return n.forEach((s,a)=>{s.group_operator!=="all"&&e.push(se(i.id,`A condition group using "any" (OR) inside an outer "any" (OR) rule cannot be represented in doorman's flat AND-within/OR-across condition model \u2014 its members were kept in the same group (effectively AND'd) instead of OR'd. Review the translated rule against the original Fastly logic.`));for(let l of s.conditions)Ct(t,l,a,e,i.id)}),{conditions:t,conditionLogic:n.length>1?"OR":"AND"};if(n.length===0)return o.forEach((s,a)=>{let l=i.group_operator==="any"?a:0;Ct(t,s,l,e,i.id)}),{conditions:t,conditionLogic:i.group_operator==="any"&&o.length>1?"OR":"AND"};e.push(se(i.id,`Rule mixes top-level conditions with condition groups under group_operator "${i.group_operator}" \u2014 this doesn't fit doorman's flat AND-within/OR-across condition model. All conditions were combined with AND; review the translated rule against the original Fastly rule logic.`));for(let s of o)Ct(t,s,0,e,i.id);for(let s of n)for(let a of s.conditions)Ct(t,a,0,e,i.id);return{conditions:t,conditionLogic:"AND"}}function Ct(i,e,t,n,o){if(e.type==="single"){let{operator:u,negated:p}=nn(e.operator);i.push({field:Mo(e.field),operator:u,value:e.value,...p?{negated:!0}:{},group:t});return}let s=zo[e.field],a=e.conditions.find(u=>u.field==="name"),l=e.conditions.find(u=>u.field==="value"||u.field==="value_string");if(!l){n.push(se(o,`Multival condition on '${e.field}' has no value sub-condition doorman could extract (only a 'name' existence check) \u2014 skipped.`));return}let{operator:c,negated:d}=nn(l.operator);i.push({field:s,operator:c,value:l.value,...d?{negated:!0}:{},...a?{key:a.value}:{},group:t})}function Zo(i,e){i.actions.length>1&&e.push(se(i.id,`Rule has ${i.actions.length} actions \u2014 doorman only models one action per rule; only the first ("${i.actions[0]?.type}") was translated.`));let t=i.actions[0];if(i.type==="rate_limit")return{type:"rate_limit",rateLimit:i.rate_limit?{requests:i.rate_limit.threshold,window:`${i.rate_limit.interval}s`,mitigationTimeout:i.rate_limit.duration}:void 0};switch(t?.type){case"block":return{type:"block"};case"allow":return{type:"allow"};case"browser_challenge":case"dynamic_challenge":case"verify_token":return{type:"challenge"};case"redirect":return{type:"redirect",redirect:{location:t.redirect_url??"",...t.response_code!==void 0?{statusCode:t.response_code}:{}}};case"add_signal":case"exclude_signal":case"deception":return e.push(O.createWarning("action_differences",i.id,"action.type",`Fastly action "${t.type}" tags or excludes a WAF signal rather than allowing/blocking the request \u2014 doorman has no matching action type. Mapped to "log" as the closest non-destructive fallback; review this rule.`)),{type:"log"};default:return e.push(se(i.id,`Unrecognised Fastly action type "${String(t?.type)}" \u2014 mapped to "log".`)),{type:"log"}}}function rn(i){let e=[],{conditions:t,conditionLogic:n}=Ho(i,e),o=Zo(i,e);return t.length>10&&e.push(O.createWarning("many_conditions",i.id,void 0,`Rule has ${t.length} conditions which may impact performance`)),{result:{id:i.id,name:i.description||i.id,enabled:i.enabled,conditions:t,conditionLogic:n,action:o},warnings:e}}function Yo(i,e,t){let n=new Map;for(let a of i){let l=a.group??0,c=n.get(l);c?c.push(a):n.set(l,[a])}let o=a=>{let l=qo[a.field];if(l){if(a.key===void 0)return t.push(se(e,`Condition on '${a.field}' has no 'key' set \u2014 Fastly needs a specific ${a.field} name to match on (e.g. a header name). Skipped.`)),null;let d=l==="request_header"||l==="response_header"?"value_string":"value";return{type:"multival",field:l,operator:"exists",group_operator:"all",conditions:[{type:"single",field:"name",operator:"equals",value:a.key},{type:"single",field:d,operator:on(a.operator,a.negated,t,e),value:String(a.value)}]}}let c=Go(a.field);return c?{type:"single",field:c,operator:on(a.operator,a.negated,t,e),value:String(a.value)}:(t.push(O.createUnsupportedFeatureWarning(`condition field '${a.field}'`,"unified config","Fastly",e,a.field)),null)};if(n.size<=1){let a=i.map(o).filter(l=>l!==null);return{conditions:a.filter(l=>l.type==="single"),groupConditions:[],multivalConditions:a.filter(l=>l.type==="multival"),groupOperator:"all"}}let s=[];for(let a of n.values()){let l=a.map(o).filter(c=>c!==null);l.length>0&&s.push({type:"group",group_operator:"all",conditions:l})}return{conditions:[],groupConditions:s,multivalConditions:[],groupOperator:"any"}}function Jo(i,e,t){switch(i.type){case"block":case"deny":return{type:"block"};case"allow":return{type:"allow"};case"challenge":return{type:"browser_challenge"};case"bypass":return e.push(se(t,'Unified action "bypass" has no direct Fastly equivalent \u2014 mapped to "allow".')),{type:"allow"};case"log":return e.push(se(t,'Unified action "log" has no dedicated Fastly action \u2014 mapped to "allow" (request_logging is enabled at the rule level regardless).')),{type:"allow"};case"redirect":return i.redirect?{type:"redirect",redirect_url:i.redirect.location,response_code:i.redirect.statusCode??(i.redirect.permanent?301:302)}:(e.push(se(t,'Unified action "redirect" has no redirect target \u2014 mapped to "allow".')),{type:"allow"});case"rate_limit":return{type:"block_signal"};default:return e.push(O.createUnsupportedFeatureWarning(`action type '${i.type}'`,"unified config","Fastly",t,"action.type")),{type:"block"}}}function Qo(i,e,t){let n=/^(\d+)\s*(s|m|h)?$/i.exec(i.trim()),o={s:1,m:60,h:3600},s=n?Number(n[1])*o[n[2]?.toLowerCase()||"s"]:NaN,a=[60,600,3600];if(!Number.isFinite(s)||s<=0)return e.push(O.createWarning("rate_limiting_precision",t,void 0,`Rate limit window "${i}" could not be parsed \u2014 defaulted to Fastly's 60-second interval.`)),60;let l=a.reduce((c,d)=>Math.abs(d-s)<Math.abs(c-s)?d:c);return l!==s&&e.push(O.createWarning("rate_limiting_precision",t,void 0,`Rate limit window "${i}" (${s}s) isn't one of Fastly's supported intervals (60s/600s/3600s) \u2014 rounded to ${l}s.`)),l}function Xo(i,e,t){if(!i)throw new Error(`Rule "${e??"(unnamed)"}" has action type "rate_limit" but no rateLimit configuration \u2014 Fastly requires a threshold and interval.`);let n=Qo(i.window,t,e);return t.push(O.createWarning("rate_limiting_precision",e,void 0,`Fastly rate-limit rules count requests against a named custom signal, which doorman does not create automatically \u2014 create a signal named "doorman-rate-limit-${e??"rule"}" in this workspace before syncing, or the rule will be rejected.`)),{client_identifiers:[{type:"ip"}],duration:i.mitigationTimeout??n,interval:n,signal:`doorman-rate-limit-${e??"rule"}`,threshold:i.requests}}function sn(i){let e=[];i.description&&i.description!==i.name&&e.push(se(i.id,'Fastly rules have no separate "name" field \u2014 only "description" carries over, and it was set from this rule\'s `name`. The `description` text was dropped rather than merged in, to keep it round-trip-stable on the next sync.'));let{conditions:t,groupConditions:n,multivalConditions:o,groupOperator:s}=Yo(i.conditions,i.id,e);if(t.length===0&&n.length===0&&o.length===0)throw new Error(`Rule "${i.name}" has no conditions Fastly can represent \u2014 every condition field is unsupported by Fastly. Cannot sync this rule to Fastly.`);let a=i.action.type==="rate_limit";return{result:{type:a?"rate_limit":"request",description:i.name,enabled:i.enabled,group_operator:s,request_logging:"sampled",conditions:t,group_conditions:n,multival_conditions:o,actions:[Jo(i.action,e,i.id)],rate_limit:a?Xo(i.action.rateLimit,i.id,e):null},warnings:e}}function an(i,e){return i.map(t=>({ip:t,action:e}))}function ln(i){let e=[],t=[],n=[];for(let o of i)(o.hostname||o.notes)&&e.push(se(o.id,`IP rule "${o.ip}" sets ${o.hostname?"`hostname`":""}${o.hostname&&o.notes?" and ":""}${o.notes?"`notes`":""} \u2014 Fastly IP lists have no equivalent per-entry metadata; only the address was kept.`)),(o.action==="allow"?n:t).push(o.ip);return{result:{denyEntries:t,allowEntries:n},warnings:e}}var k=class{static vercelToUnified=Gi;static unifiedToVercel=Ki;static vercelIPToUnified=Hi;static cloudflareToUnified=Xi;static unifiedToCloudflare=en;static unifiedIPToCloudflare=tn;static fastlyToUnified=rn;static unifiedToFastly=sn;static fastlyListEntriesToUnified=an;static unifiedIPsToFastlyEntries=ln};fe();function Ke(i,e){if(i===e)return!0;if(typeof i!="object"||i===null||typeof e!="object"||e===null||Array.isArray(i)!==Array.isArray(e))return!1;let t=Object.keys(i),n=Object.keys(e);if(t.length!==n.length)return!1;for(let o of t)if(!n.includes(o)||!Ke(i[o],e[o]))return!1;return!0}function $e(i){let{id:e,...t}=i;return t}function dt(i){return[...i].sort((e,t)=>{let n=e.priority!==void 0,o=t.priority!==void 0;return!n&&!o?0:n?o?e.priority-t.priority:-1:1})}function vt(i){return i.some(e=>e.priority!==void 0)}var He=class extends ke{constructor(t){super();this.client=t}client;name="vercel";async fetchConfig(t){try{r.debug("Fetching Vercel firewall configuration");let n=await this.client.fetchFirewallConfig(t),o=n.rules.map(a=>{let l=k.vercelToUnified(a);return l.warnings.length>0&&l.warnings.forEach(c=>{let{TranslationWarningSystem:d}=(fe(),ye(De)),u=d.formatWarning(c);r.warn(`Rule ${a.name}:
25
+ ${u}`)}),l.result}),s=n.ips.map(a=>k.vercelIPToUnified(a));return{version:"2.0",provider:"vercel",providers:{vercel:{projectId:this.client.projectId,...this.client.teamId?{teamId:this.client.teamId}:{}}},rules:o,ips:s,metadata:{version:n.version,updatedAt:n.updatedAt}}}catch(n){throw r.error("Error fetching Vercel configuration:",n),new Error("Failed to fetch Vercel firewall configuration")}}async syncRules(t,n={}){let{dryRun:o=!1}=n;try{let{OperationSafety:s}=(Tt(),ye(Et)),a=await s.performDryRunValidation(t,"sync rules",async f=>await this.getChanges(f,{allowCreate:!o}));if(!a.valid)throw new Error(`Dry-run validation failed: ${a.issues.join(", ")}`);let l=a.changes,{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u,version:p}=l,g=l.ipsToAdd||[],h=l.ipsToUpdate||[],I=l.ipsToDelete||[];if(o)return r.info("Dry run mode. The following changes would be made:"),r.info(`Custom Rules - Add: ${c.length}, Update: ${d.length}, Delete: ${u.length}`),r.info(`IP Rules - Add: ${g.length}, Update: ${h.length}, Delete: ${I.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,version:p,warnings:a.warnings};let R=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Vercel project ${this.client.projectId}`,changes:l,riskLevel:R,skipConfirmation:n.force||!1,dryRun:!1,allowDeletions:n.allowDeletions||!1}))throw new Error("Operation cancelled by user");let Z=c.map(f=>k.unifiedToVercel(f).result),W=d.map(f=>k.unifiedToVercel(f).result),ue=u.map(f=>k.unifiedToVercel(f).result),me=g.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),_e=h.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),_=I.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),ve=[],be=[],Ee=[],We=[],Se=[],je=[],v=[],V=(f,b)=>`${f}: ${b instanceof Error?b.message:String(b)}`,ie=[];vt(t.rules)&&t.rules.length>c.length&&ie.push("Rule `priority` is best-effort on Vercel: new rules are created in priority order, but rules that already exist remotely cannot be repositioned via the Vercel API. Recreate them (remove and re-add) if exact evaluation order matters.");let ae=[];for(let f of ue)try{r.debug(`Deleting custom rule: ${f.id}`),await this.client.deleteFirewallRule(f),Ee.push(f),r.debug(`Custom rule deleted: ${f.id}`)}catch(b){r.error(`Failed to delete custom rule ${f.id}:`,b),v.push(V(`Failed to delete custom rule ${f.id}`,b))}for(let f of _)try{r.debug(`Deleting IP blocking rule: ${f.id}`),await this.client.deleteIPBlockingRule(f),je.push(f),r.debug(`IP blocking rule deleted: ${f.id}`)}catch(b){r.error(`Failed to delete IP blocking rule ${f.id}:`,b),v.push(V(`Failed to delete IP blocking rule ${f.id}`,b))}for(let f of Z)try{r.debug(`Adding new custom rule: ${f.name}`);let b=await this.client.createFirewallRule(f);ve.push(b),b.id&&b.id!==f.id&&ae.push({oldId:f.id||void 0,newId:b.id,name:f.name}),r.debug(`New custom rule added: ${b.id}`)}catch(b){r.error(`Failed to add custom rule "${f.name}":`,b),v.push(V(`Failed to add custom rule "${f.name}"`,b))}for(let f of me)try{r.debug(`Adding new IP blocking rule: ${f.ip}`);let b=await this.client.createIPBlockingRule(f);We.push(b),r.debug(`New IP blocking rule added: (hostname): ${b.hostname} (ip): ${b.ip}`)}catch(b){r.error(`Failed to add IP blocking rule ${f.ip}:`,b),v.push(V(`Failed to add IP blocking rule ${f.ip}`,b))}for(let f of W)try{r.debug(`Updating custom rule: ${f.id}`);let b=await this.client.updateFirewallRule(f);be.push(b),r.debug(`Custom rule updated: ${b.id}`)}catch(b){r.error(`Failed to update custom rule ${f.id}:`,b),v.push(V(`Failed to update custom rule ${f.id}`,b))}for(let f of _e)try{r.debug(`Updating IP blocking rule: ${f.id}`);let b=await this.client.updateIPBlockingRule(f);Se.push(b),r.debug(`IP blocking rule updated: ${b.id}`)}catch(b){r.error(`Failed to update IP blocking rule ${f.id}:`,b),v.push(V(`Failed to update IP blocking rule ${f.id}`,b))}r.debug(`${te.default.underline("Custom Rules:")} ${te.default.green("Added:")} ${te.default.green(ve.length)}, ${te.default.cyan("Updated:")} ${te.default.cyan(be.length)}, ${te.default.red("Deleted:")} ${te.default.red(Ee.length)}`),r.debug(`${te.default.underline("IP Rules:")} ${te.default.green("Added:")} ${te.default.green(We.length)}, ${te.default.cyan("Updated:")} ${te.default.cyan(Se.length)}, ${te.default.red("Deleted:")} ${te.default.red(je.length)}`);let nt=p,ot,Te=[...ie];try{let f=await this.client.fetchFirewallConfig();nt=f.version,ot=f.updatedAt;let b=new Set(f.rules.map(F=>F.id)),yi=new Set(f.ips.map(F=>F.id));for(let F of[...ve,...be])F.id&&!b.has(F.id)&&Te.push(`Rule "${F.name}" (${F.id}) was synced but is missing from the post-sync remote config \u2014 a subsequent sync may re-create or misdiff it.`);for(let F of Ee)F.id&&b.has(F.id)&&Te.push(`Rule "${F.name}" (${F.id}) was deleted but still appears in the post-sync remote config.`);for(let F of[...We,...Se])F.id&&!yi.has(F.id)&&Te.push(`IP rule "${F.ip}" (${F.id}) was synced but is missing from the post-sync remote config \u2014 a subsequent sync may re-create or misdiff it.`);for(let F of je)F.id&&yi.has(F.id)&&Te.push(`IP rule "${F.ip}" (${F.id}) was deleted but still appears in the post-sync remote config.`)}catch(f){r.error("Failed to fetch updated firewall configuration version after sync:",f),v.push(V("Failed to fetch updated configuration version after sync",f))}return{success:v.length===0,rulesAdded:ve.length,rulesUpdated:be.length,rulesDeleted:Ee.length,ipsAdded:We.length,ipsUpdated:Se.length,ipsDeleted:je.length,version:nt,updatedAt:ot,idRemappings:ae.length>0?ae:void 0,errors:v.length>0?v:void 0,warnings:Te.length>0?Te:void 0}}catch(s){throw r.error("Error during sync:",s),new Error(`Failed to synchronize firewall rules: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async getChanges(t,n){let o=Le.safeParse(t);if(!o.success)throw new Error(`Invalid firewall configuration: ${o.error.message}`);try{r.debug("Fetching existing firewall configuration");let s=await this.client.fetchFirewallConfig(void 0,{allowCreate:n?.allowCreate??!0});r.debug(`Fetched ${s.rules.length} custom rules and ${s.ips.length} IP blocking rules`);let a=s.rules.map(I=>{let R=k.vercelToUnified(I);return R.warnings.length>0&&R.warnings.forEach(N=>{let{TranslationWarningSystem:Z}=(fe(),ye(De)),W=Z.formatWarning(N);r.warn(`Rule ${I.name}:
26
+ ${W}`)}),R.result}),{toAdd:l,toUpdate:c,toDelete:d}=this.diffRules(dt(t.rules),a),u=s.ips.map(I=>k.vercelIPToUnified(I)),{ipsToAdd:p,ipsToUpdate:g,ipsToDelete:h}=this.diffIPRules(t.ips||[],u);return{version:s.version,rulesToAdd:l,rulesToUpdate:c,rulesToDelete:d,ipsToAdd:p,ipsToUpdate:g,ipsToDelete:h,hasChanges:l.length>0||c.length>0||d.length>0||p.length>0||g.length>0||h.length>0}}catch(s){throw r.error("Error fetching existing firewall configuration:",s),new Error("Failed to fetch existing firewall configuration")}}getSupportedFeatures(){return{supportsCustomRules:!0,supportsIPBlocking:!0,supportsRateLimiting:!0,supportsGeoBlocking:!0,supportsManagedRules:!1,supportsRedirect:!0,supportsChallenge:!0}}async verifyCredentials(){return this.client.verifyCredentials()}validateConfig(t){let n=super.validateConfig(t),o=[...n.errors],s=[...n.warnings];t.provider&&t.provider!=="vercel"&&o.push({path:"provider",message:"Provider must be 'vercel' for VercelFirewallService",code:"INVALID_PROVIDER"});try{let a=Ae.safeParse(t);a.success||o.push({path:"root",message:`Schema validation failed: ${a.error.message}`,code:"SCHEMA_VALIDATION_FAILED"})}catch(a){r.debug("Schema validation error:",a)}return{valid:o.length===0,errors:o,warnings:s}}getHealthScore(t){let n=super.getHealthScore(t),o=[...n.issues],s=n.score;return t.rules.filter(l=>l.action?.type==="rate_limit").length===0&&(s-=10,o.push({severity:"info",category:"security",message:"No rate limiting rules configured",suggestion:"Consider adding rate limiting to protect against abuse"})),(!t.ips||t.ips.length===0)&&o.push({severity:"info",category:"security",message:"No IP blocking rules configured",suggestion:"Consider blocking known malicious IPs"}),{score:Math.max(0,s),grade:n.grade,issues:o,recommendations:n.recommendations}}diffRules(t,n){let o=[],s=[],a=[...n];for(let l of t){let c=n.find(d=>d.id===l.id);if(!c)o.push(l);else{Ke($e(l),$e(c))||s.push({...l,id:c.id});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{toAdd:o,toUpdate:s,toDelete:a}}diffIPRules(t,n){let o=[],s=[],a=[...n];for(let l of t){let c=n.find(d=>d.id===l.id);if(!c)r.debug("Rule not found in existing rules:",{configRule:l}),o.push(l);else{Ke($e(l),$e(c))||s.push({...c,...l});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{ipsToAdd:o,ipsToUpdate:s,ipsToDelete:a}}};T();var Ze=class{static fromEnv(){let e=process.env.VERCEL_TOKEN,t=process.env.VERCEL_PROJECT_ID,n=process.env.VERCEL_TEAM_ID;if(!e)throw new Error("VERCEL_TOKEN environment variable is required");if(!t)throw new Error("VERCEL_PROJECT_ID environment variable is required");let o=new Me(t,n,e);return new He(o)}static fromConfig(e){let t=e.token||process.env.VERCEL_TOKEN,n=e.projectId||process.env.VERCEL_PROJECT_ID,o=e.teamId||process.env.VERCEL_TEAM_ID;if(!t)throw new Error("Vercel API token is required (provide token or set VERCEL_TOKEN env var)");if(!n)throw new Error("Vercel project ID is required (provide projectId or set VERCEL_PROJECT_ID env var)");r.debug("Creating Vercel provider with config:",{projectId:n,teamId:o});let s=new Me(n,o,t);return new He(s)}static create(e,t,n){return this.fromConfig({projectId:e,teamId:t,token:n})}};var un=require("crypto");T();var xe=S(require("chalk")),m=class i extends Error{code;suggestion;details;docsUrl;cause;constructor(e){super(e.message),this.name="DoormanError",this.code=e.code,this.suggestion=e.suggestion,this.details=e.details,this.docsUrl=e.docsUrl,this.cause=e.cause,Error.captureStackTrace&&Error.captureStackTrace(this,i)}format(){let e=[];return e.push(xe.default.red.bold(`[${this.code}] ${this.message}`)),e.push(""),this.suggestion&&(e.push(xe.default.yellow.bold("Suggestion:")),e.push(` ${this.suggestion}`),e.push("")),this.details&&Object.keys(this.details).length>0&&(e.push(xe.default.dim("Details:")),Object.entries(this.details).forEach(([t,n])=>{let o=typeof n=="object"?JSON.stringify(n,null,2).split(`
26
27
  `).join(`
27
- `):o;e.push(` ${xe.default.cyan(t)}: ${n}`)}),e.push("")),this.cause&&(e.push(xe.default.dim("Caused by:")),e.push(` ${this.cause.message}`),e.push("")),this.docsUrl&&(e.push(xe.default.cyan.bold("Documentation:")),e.push(` ${this.docsUrl}`),e.push("")),e.join(`
28
- `)}toPlainText(){let e=[];return e.push(`[${this.code}] ${this.message}`),this.suggestion&&e.push(`Suggestion: ${this.suggestion}`),this.details&&Object.keys(this.details).length>0&&(e.push("Details:"),Object.entries(this.details).forEach(([t,o])=>{e.push(` ${t}: ${o}`)})),this.cause&&e.push(`Caused by: ${this.cause.message}`),this.docsUrl&&e.push(`Documentation: ${this.docsUrl}`),e.join(`
29
- `)}static isDoormanError(e){return e instanceof i}static from(e,t,o){return i.isDoormanError(e)?e:e instanceof Error?new i({code:t,message:o||e.message,cause:e}):new i({code:t,message:o||String(e)})}};var $="https://docs.doorman.griffen.codes/errors";var G={authFailed:(i,e)=>new m({code:"PROV_5000",message:`Authentication failed for ${i}`,suggestion:"Check that your API credentials are valid and have the correct permissions",details:{provider:i},cause:e,docsUrl:`${$}/PROV_5000`}),apiError:(i,e,t,o)=>new m({code:"PROV_5002",message:`${i} API error: ${t} ${o}`,suggestion:"Check the provider status page and your credentials",details:{provider:i,endpoint:e,statusCode:t,responseMessage:o},docsUrl:`${$}/PROV_5002`}),rateLimit:(i,e)=>new m({code:"PROV_5003",message:`Rate limit exceeded for ${i}`,suggestion:e?`Wait ${e} seconds and try again, or use --retry flag`:"Wait a few minutes and try again, or use --retry flag",details:{provider:i,retryAfter:e},docsUrl:`${$}/PROV_5003`}),timeout:(i,e)=>new m({code:"PROV_5006",message:`Request timeout for ${i} ${e}`,suggestion:"Check your internet connection and try again",details:{provider:i,operation:e},docsUrl:`${$}/PROV_5006`}),invalidCredentials:(i,e)=>new m({code:"PROV_5004",message:`Missing or invalid credentials for ${i}`,suggestion:`Please provide: ${e.join(", ")}`,details:{provider:i,missing:e},docsUrl:`${$}/PROV_5004`})},B={accountIdRequired:i=>new m({code:"CF_6004",message:`Account ID required for ${i}`,suggestion:"Provide CLOUDFLARE_ACCOUNT_ID in your environment or configuration to use Lists API",details:{operation:i},docsUrl:`${$}/CF_6004`}),zoneIdRequired:i=>new m({code:"CF_6005",message:`Zone ID required for ${i}`,suggestion:"Provide CLOUDFLARE_ZONE_ID in your environment or configuration",details:{operation:i},docsUrl:`${$}/CF_6005`}),invalidCredentials:(i,e)=>new m({code:"CF_6016",message:`Invalid Cloudflare ${i}`,suggestion:"Check your Cloudflare API credentials and ensure they have the correct permissions",details:{credentialType:i,...e},docsUrl:`${$}/CF_6016`}),insufficientPermissions:(i,e)=>new m({code:"CF_6017",message:`Insufficient permissions for ${i}`,suggestion:`Ensure your API token has the following permissions: ${e.join(", ")}`,details:{operation:i,requiredPermissions:e},docsUrl:`${$}/CF_6017`}),ruleLimitExceeded:(i,e)=>new m({code:"CF_6001",message:`Rule count (${i}) exceeds Cloudflare limit (${e})`,suggestion:"Consider consolidating rules, using Lists for IP blocking, or upgrading your Cloudflare plan",details:{count:i,limit:e},docsUrl:`${$}/CF_6001`}),invalidExpression:(i,e)=>new m({code:"CF_6002",message:`Invalid Cloudflare expression: ${e}`,suggestion:"Check Cloudflare Wirefilter expression syntax and field names",details:{expression:i,reason:e},docsUrl:`${$}/CF_6002`}),ruleNoConditions:i=>new m({code:"CF_6007",message:`Rule "${i}" has no conditions`,suggestion:"Add at least one condition to the rule or remove the empty rule",details:{ruleName:i},docsUrl:`${$}/CF_6007`}),invalidRateLimit:(i,e)=>new m({code:"CF_6008",message:`Invalid rate limit configuration for rule "${i}": ${e}`,suggestion:'Rate limit requests must be at least 1, and window format should be like "60s", "1h", "1d"',details:{ruleName:i,issue:e},docsUrl:`${$}/CF_6008`}),invalidWindowFormat:i=>new m({code:"CF_6009",message:`Invalid rate limit window format: ${i}`,suggestion:'Use format like "60s", "5m", "1h", or "1d"',details:{window:i},docsUrl:`${$}/CF_6009`}),shortMitigationTimeout:i=>new m({code:"CF_6010",message:`Mitigation timeout (${i}s) may be too short`,suggestion:"Consider using at least 60 seconds for effective rate limiting",details:{timeout:i},docsUrl:`${$}/CF_6010`}),redirectNoLocation:i=>new m({code:"CF_6011",message:`Redirect rule "${i}" is missing location URL`,suggestion:"Add a redirect.location property with a valid URL or path",details:{ruleName:i},docsUrl:`${$}/CF_6011`}),invalidRedirectUrl:i=>new m({code:"CF_6012",message:`Invalid redirect URL: ${i}`,suggestion:"Use a valid absolute URL (https://...) or relative path (/...)",details:{url:i},docsUrl:`${$}/CF_6012`}),invalidIP:i=>new m({code:"CF_6013",message:`Invalid IP address format: ${i}`,suggestion:"Use valid IPv4 or IPv6 address with optional CIDR notation (e.g., 192.168.1.1 or 192.168.1.0/24)",details:{ip:i},docsUrl:`${$}/CF_6013`}),largeIPList:i=>new m({code:"CF_6014",message:`Large IP list detected (${i} IPs)`,suggestion:"Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance with large IP lists",details:{count:i},docsUrl:`${$}/CF_6014`}),rulesetNotFound:i=>new m({code:"CF_6000",message:i?`Ruleset not found: ${i}`:"Ruleset not found",suggestion:"The ruleset may have been deleted. Try running the command again to create a new one.",details:{rulesetId:i},docsUrl:`${$}/CF_6000`}),listNotFound:i=>new m({code:"CF_6003",message:i?`List not found: ${i}`:"List not found",suggestion:"The IP list may have been deleted. Try running the command again to create a new one.",details:{listId:i},docsUrl:`${$}/CF_6003`}),emptyCharacteristics:i=>new m({code:"CF_6015",message:`Rate limit rule "${i}" has empty characteristics`,suggestion:'Add characteristics like ["ip.src"] or remove the characteristics array to use default',details:{ruleName:i},docsUrl:`${$}/CF_6015`}),translationWarning:(i,e)=>new m({code:"CF_6018",message:`Translation warning for feature "${i}": ${e}`,suggestion:"Review the translated configuration and adjust if necessary",details:{feature:i,limitation:e},docsUrl:`${$}/CF_6018`}),featureUnsupported:(i,e)=>new m({code:"CF_6019",message:`Feature "${i}" is not supported when migrating from ${e} to Cloudflare`,suggestion:"Remove this feature or implement it using Cloudflare-specific alternatives",details:{feature:i,provider:e},docsUrl:`${$}/CF_6019`}),planLimitExceeded:(i,e,t)=>new m({code:"CF_6020",message:`${i} limit exceeded: ${t}/${e}`,suggestion:"Consider upgrading your Cloudflare plan or reducing resource usage",details:{resource:i,limit:e,current:t},docsUrl:`${$}/CF_6020`}),zoneSuspended:(i,e)=>new m({code:"CF_6021",message:`Zone is suspended: ${i}${e?` (${e})`:""}`,suggestion:"Contact Cloudflare support to resolve zone suspension issues",details:{zoneId:i,reason:e},docsUrl:`${$}/CF_6021`}),maintenanceMode:i=>new m({code:"CF_6022",message:`Cloudflare ${i} is currently in maintenance mode`,suggestion:"Wait for maintenance to complete and try again. Check Cloudflare status page for updates.",details:{service:i,statusPage:"https://www.cloudflarestatus.com/"},docsUrl:`${$}/CF_6022`}),quotaExceeded:(i,e)=>new m({code:"CF_6023",message:`${i} quota exceeded`,suggestion:e?`Wait until ${e} for quota reset, or upgrade your plan for higher limits`:"Wait for quota reset or upgrade your plan for higher limits",details:{quotaType:i,resetTime:e},docsUrl:`${$}/CF_6023`}),listsAPIUnavailable:(i,e)=>new m({code:"CF_6004",message:`Lists API unavailable: ${i}`,suggestion:`Falling back to ${e}. To enable Lists API, provide CLOUDFLARE_ACCOUNT_ID and ensure your API token has Account:Read permissions.`,details:{reason:i,fallbackAction:e,severity:"warning"},docsUrl:`${$}/setup#account-id`}),performanceWarning:(i,e,t)=>new m({code:"CF_6014",message:`Performance warning: ${i} with ${e} items`,suggestion:`${t} Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance.`,details:{operation:i,count:e,impact:t,severity:"warning"},docsUrl:`${$}/performance#large-ip-lists`})};var K=class{static DOCS_BASE_URL="https://docs.doorman.griffen.codes/cloudflare";static ERROR_PATTERNS={authentication:{keywords:["authentication","token","unauthorized","invalid token"],suggestion:"Verify your CLOUDFLARE_API_TOKEN is correct and has not expired. Create a new token if needed.",docsSection:"setup#api-token"},permissions:{keywords:["forbidden","access denied","insufficient permissions"],suggestion:"Ensure your API token has the required permissions: Zone:Edit and Account:Read (for Lists API).",docsSection:"setup#permissions"},rateLimit:{keywords:["rate limit","too many requests","quota exceeded"],suggestion:"Wait before retrying or use --retry flag for automatic exponential backoff. Consider upgrading your plan.",docsSection:"troubleshooting#rate-limits"},network:{keywords:["timeout","connection","network","dns","enotfound","econnrefused"],suggestion:"Check your internet connection and ensure api.cloudflare.com is accessible through your firewall.",docsSection:"troubleshooting#connectivity"}};static detectErrorContext(e){let t=e.toLowerCase(),o={pattern:null,confidence:0};for(let[n,s]of Object.entries(this.ERROR_PATTERNS)){let l=s.keywords.filter(c=>t.includes(c)).length/s.keywords.length;l>o.confidence&&(o={pattern:n,confidence:l})}return o}static handleApiError(e){if(e.code&&e.code!==0){let t=this.mapCloudflareErrorCode(e);if(t.code!=="PROV_5002")return t}switch(e.status){case 400:return this.handleBadRequestError(e);case 401:return this.handleUnauthorizedError(e);case 403:return this.handleForbiddenError(e);case 404:return this.handleNotFoundError(e);case 429:return this.handleRateLimitError(e);case 500:case 502:case 503:case 504:return this.handleServerError(e);default:return this.handleGenericError(e)}}static handleApiResponse(e,t){if(e.success)throw new Error("Cannot handle successful response as error");let n={status:0,code:e.errors[0]?.code||0,message:e.errors.map(s=>s.message).join(", "),endpoint:t,details:{errors:e.errors,messages:e.messages}};return this.mapCloudflareErrorCode(n)}static handleCredentialError(e,t){switch(e){case"token":return new m({code:"PROV_5004",message:"Invalid or missing Cloudflare API token",suggestion:"Check your CLOUDFLARE_API_TOKEN environment variable or config file. Ensure the token has Zone:Edit and Account:Read permissions.",details:{credentialType:"api_token"},docsUrl:`${this.DOCS_BASE_URL}/setup#api-token`});case"zone":return new m({code:"CF_6005",message:t?`Invalid zone ID: ${t}`:"Missing zone ID",suggestion:"Provide a valid CLOUDFLARE_ZONE_ID. You can find this in your Cloudflare dashboard under the domain overview.",details:{zoneId:t,credentialType:"zone_id"},docsUrl:`${this.DOCS_BASE_URL}/setup#zone-id`});case"account":return new m({code:"CF_6004",message:t?`Invalid account ID: ${t}`:"Missing account ID for Lists API",suggestion:"Provide CLOUDFLARE_ACCOUNT_ID to use Lists for IP blocking. This is optional but recommended for large IP lists.",details:{accountId:t,credentialType:"account_id"},docsUrl:`${this.DOCS_BASE_URL}/setup#account-id`});default:return new m({code:"PROV_5004",message:"Invalid Cloudflare credentials",suggestion:"Check your Cloudflare API credentials",docsUrl:`${this.DOCS_BASE_URL}/setup`})}}static handleValidationError(e,t,o){let s={rules:{code:"CF_6006",suggestion:"Check your rule configuration syntax and ensure all required fields are present",docsUrl:`${this.DOCS_BASE_URL}/configuration#rules`},expression:{code:"CF_6002",suggestion:"Use valid Cloudflare Wirefilter expression syntax. Check field names and operators.",docsUrl:`${this.DOCS_BASE_URL}/expressions`},rateLimit:{code:"CF_6008",suggestion:'Rate limit requests must be at least 1, and window format should be like "60s", "1h", "1d"',docsUrl:`${this.DOCS_BASE_URL}/rate-limiting`},redirect:{code:"CF_6011",suggestion:"Redirect rules must include a valid location URL or path",docsUrl:`${this.DOCS_BASE_URL}/redirects`},ip:{code:"CF_6013",suggestion:"Use valid IPv4 or IPv6 address with optional CIDR notation (e.g., 192.168.1.1 or 192.168.1.0/24)",docsUrl:`${this.DOCS_BASE_URL}/ip-blocking`}}[e]||{code:"CF_6006",suggestion:"Check your configuration syntax",docsUrl:`${this.DOCS_BASE_URL}/configuration`};return new m({code:s.code,message:`Configuration validation failed for ${e}: ${t}`,suggestion:s.suggestion,details:{field:e,issue:t,value:o},docsUrl:s.docsUrl})}static createEnhancedSuggestion(e,t,o){let n=[e];if(o?.pattern&&o.confidence>.5){let l=this.ERROR_PATTERNS[o.pattern];n.push(l.suggestion)}let a={"syncing rules":"Try running with --dry-run first to validate your configuration.","fetching configuration":"Verify your zone ID is correct and accessible.","validating credentials":"Double-check your API token permissions in the Cloudflare dashboard.","creating ruleset":"Ensure you have Zone:Edit permissions for the specified zone.","updating rules":"Check if you have reached your plan's rule limit."}[t];return a&&n.push(a),n.join(" ")}static formatTranslationWarning(e,t,o){let{TranslationWarningSystem:n}=(fe(),ye(De)),s;try{s=n.createWarning(e,void 0,void 0,o)}catch{s=n.createLossyConversionWarning(e,`${o} (from ${t})`,void 0,void 0)}return n.formatWarning(s)}static handleNetworkError(e,t){let o=this.detectErrorContext(e.message);if(e.message.includes("timeout")){let s=this.createEnhancedSuggestion("Check your internet connection and try again. Use --retry flag for automatic retries.",t,o);return new m({code:"NET_8000",message:`Request timeout during ${t}`,suggestion:s,details:{operation:t,originalError:e.message,retryRecommended:!0,timeoutDuration:this.extractTimeoutDuration(e.message)},cause:e,docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#timeouts`})}if(e.message.includes("ENOTFOUND")||e.message.includes("ECONNREFUSED")){let s=this.createEnhancedSuggestion("Check your internet connection and firewall settings. Ensure api.cloudflare.com is accessible.",t,o);return new m({code:"NET_8001",message:`Network connection failed during ${t}`,suggestion:s,details:{operation:t,originalError:e.message,dnsResolutionFailed:e.message.includes("ENOTFOUND"),connectionRefused:e.message.includes("ECONNREFUSED")},cause:e,docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#connectivity`})}let n=this.createEnhancedSuggestion("Check your internet connection and try again",t,o);return new m({code:"NET_8004",message:`Network error during ${t}: ${e.message}`,suggestion:n,details:{operation:t,errorContext:o},cause:e,docsUrl:`${this.DOCS_BASE_URL}/troubleshooting`})}static extractTimeoutDuration(e){let t=e.match(/timeout.*?(\d+)(?:ms|s)/i);if(t&&t[1]){let o=parseInt(t[1],10),n=e.toLowerCase().includes("ms")?1:1e3;return o*n}}static handleGracefulDegradation(e,t,o,n){let a={lists_api:{code:"CF_6004",suggestion:"Provide CLOUDFLARE_ACCOUNT_ID to enable Lists API for better performance with large IP lists."},managed_rules:{code:"CF_6019",suggestion:"Use custom rules with equivalent conditions instead of managed rules."},advanced_expressions:{code:"CF_6018",suggestion:"Simplify expressions to use supported Cloudflare Wirefilter syntax."}}[e]||{code:"CF_6019",suggestion:"Consider alternative approaches or manual configuration."};return new m({code:a.code,message:`Feature degradation: ${e} - ${t}`,suggestion:`${a.suggestion} Fallback: ${o}${n?` Impact: ${n}`:""}`,details:{feature:e,reason:t,fallbackAction:o,impact:n,degradationType:"graceful"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#feature-degradation`})}static createUserFriendlyMessage(e,t,o){let n=`Failed to ${e}`,s=o?` (${Object.entries(o).map(([c,d])=>`${c}: ${d}`).join(", ")})`:"",l={401:"Please check your API token in the Cloudflare dashboard.",403:"Verify your API token has the required permissions.",404:"The requested resource may have been deleted or moved.",429:"You are being rate limited. Please wait before retrying.",500:"Cloudflare is experiencing issues. Check their status page."}[t.status]||"Please check your configuration and try again.";return`${n}${s}. ${l}`}static handleBadRequestError(e){return e.message.includes("expression")?new m({code:"CF_6002",message:`Invalid Cloudflare expression: ${e.message}`,suggestion:"Check your rule conditions and ensure they use valid Cloudflare Wirefilter syntax",details:e.details,docsUrl:`${this.DOCS_BASE_URL}/expressions`}):e.message.includes("rule")&&e.message.includes("condition")?new m({code:"CF_6007",message:"Rule validation failed: rules must have at least one condition",suggestion:"Add conditions to your rule or remove empty rules from your configuration",details:e.details,docsUrl:`${this.DOCS_BASE_URL}/rules#conditions`}):new m({code:"CF_6006",message:`Invalid request: ${e.message}`,suggestion:"Check your rule configuration for syntax errors and missing required fields",details:e.details,docsUrl:`${this.DOCS_BASE_URL}/configuration`})}static handleUnauthorizedError(e){return new m({code:"PROV_5000",message:"Authentication failed: Invalid API token",suggestion:"Check your CLOUDFLARE_API_TOKEN. Ensure it's valid and not expired. Create a new token if needed.",details:{endpoint:e.endpoint,hint:"API tokens can be created at https://dash.cloudflare.com/profile/api-tokens"},docsUrl:`${this.DOCS_BASE_URL}/setup#api-token`})}static handleForbiddenError(e){return e.endpoint?.includes("/accounts/")?new m({code:"CF_6004",message:"Access denied: Invalid account ID or insufficient permissions",suggestion:"Ensure your API token has Account:Read permissions and the account ID is correct",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/setup#permissions`}):e.endpoint?.includes("/zones/")?new m({code:"CF_6005",message:"Access denied: Invalid zone ID or insufficient permissions",suggestion:"Ensure your API token has Zone:Edit permissions and the zone ID is correct",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/setup#permissions`}):new m({code:"PROV_5000",message:"Access denied: Insufficient permissions",suggestion:"Ensure your API token has the required permissions: Zone:Edit and Account:Read (for Lists)",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/setup#permissions`})}static handleNotFoundError(e){return e.endpoint?.includes("/rulesets/")?new m({code:"CF_6000",message:"Ruleset not found",suggestion:"The ruleset may have been deleted. Try running the command again to create a new one.",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#ruleset-not-found`}):e.endpoint?.includes("/lists/")?new m({code:"CF_6003",message:"List not found",suggestion:"The IP list may have been deleted. Try running the command again to create a new one.",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#list-not-found`}):e.endpoint?.includes("/zones/")?new m({code:"CF_6005",message:"Zone not found: Invalid zone ID",suggestion:"Check your CLOUDFLARE_ZONE_ID. Find the correct zone ID in your Cloudflare dashboard.",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/setup#zone-id`}):new m({code:"PROV_5001",message:`Resource not found: ${e.message}`,suggestion:"Check that the resource exists and your credentials have access to it",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting`})}static handleRateLimitError(e){let t=e.details?.retryAfter||60;return new m({code:"PROV_5003",message:"Rate limit exceeded",suggestion:`Wait ${t} seconds and try again, or use --retry flag for automatic retries with exponential backoff`,details:{retryAfter:t,endpoint:e.endpoint,hint:"Consider upgrading your Cloudflare plan for higher rate limits"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#rate-limits`})}static handleServerError(e){return new m({code:"PROV_5002",message:`Cloudflare server error (${e.status}): ${e.message}`,suggestion:"This is a temporary Cloudflare issue. Wait a few minutes and try again, or check Cloudflare status page.",details:{status:e.status,endpoint:e.endpoint,statusPage:"https://www.cloudflarestatus.com/"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#server-errors`})}static handleGenericError(e){return new m({code:"PROV_5002",message:`Cloudflare API error (${e.status}): ${e.message}`,suggestion:"Check the Cloudflare API documentation and your request parameters",details:{status:e.status,code:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting`})}static mapCloudflareErrorCode(e){switch(e.code){case 1e4:return this.handleUnauthorizedError(e);case 10001:return this.handleForbiddenError(e);case 10013:return this.handleRateLimitError(e);case 81044:return new m({code:"CF_6000",message:"Ruleset not found",suggestion:"The ruleset may have been deleted. Try running the command again to create a new one.",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#ruleset-not-found`});case 81045:return new m({code:"CF_6001",message:"Rule limit exceeded for your Cloudflare plan",suggestion:"Consider consolidating rules, using Lists for IP blocking, or upgrading your Cloudflare plan",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#rule-limits`});case 81046:return new m({code:"CF_6002",message:`Invalid Cloudflare expression: ${e.message}`,suggestion:"Check your rule conditions and ensure they use valid Cloudflare Wirefilter syntax",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/expressions`});case 1001:return new m({code:"CF_6021",message:"Zone is suspended and cannot be modified",suggestion:"Contact Cloudflare support to resolve zone suspension issues",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#zone-suspended`});case 1014:case 1015:return new m({code:"CF_6020",message:`Plan limit exceeded: ${e.message}`,suggestion:"Consider upgrading your Cloudflare plan for higher limits",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#plan-limits`});case 1020:return new m({code:"CF_6022",message:"Cloudflare service is currently in maintenance mode",suggestion:"Wait for maintenance to complete and try again. Check Cloudflare status page.",details:{cloudflareCode:e.code,endpoint:e.endpoint,statusPage:"https://www.cloudflarestatus.com/"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#maintenance`});default:let t=e.message.toLowerCase();return t.includes("authentication")||t.includes("invalid token")?(e.status=401,this.handleUnauthorizedError(e)):t.includes("forbidden")||t.includes("access denied")?(e.status=403,this.handleForbiddenError(e)):t.includes("not found")?(e.status=404,this.handleNotFoundError(e)):t.includes("rate limit")?(e.status=429,this.handleRateLimitError(e)):new m({code:"PROV_5002",message:`Cloudflare API error: ${e.message}`,suggestion:"Check the Cloudflare API documentation and your request parameters",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting`})}}};T();var er={defaultTTL:300*1e3,maxEntries:100,enableLogging:!0},Et=class{cache=new Map;options;stats={hits:0,misses:0,evictions:0};constructor(e={}){this.options={...er,...e}}get(e){let t=this.cache.get(e);if(!t){this.stats.misses++,this.options.enableLogging&&r.debug(`Cache miss: ${e}`);return}if(Date.now()>t.expiresAt){this.cache.delete(e),this.stats.misses++,this.options.enableLogging&&r.debug(`Cache expired: ${e}`);return}return t.hits++,this.stats.hits++,this.options.enableLogging&&r.debug(`Cache hit: ${e} (${t.hits} total hits)`),t.value}set(e,t,o){this.cache.size>=this.options.maxEntries&&!this.cache.has(e)&&this.evictLeastRecentlyUsed();let n=o??this.options.defaultTTL;this.cache.set(e,{value:t,expiresAt:Date.now()+n,createdAt:Date.now(),hits:0}),this.options.enableLogging&&r.debug(`Cache set: ${e} (TTL: ${n}ms)`)}invalidate(e){let t=this.cache.delete(e);return t&&this.options.enableLogging&&r.debug(`Cache invalidated: ${e}`),t}invalidateByPrefix(e){let t=0;for(let o of this.cache.keys())o.startsWith(e)&&(this.cache.delete(o),t++);return t>0&&this.options.enableLogging&&r.debug(`Cache invalidated ${t} entries with prefix: ${e}`),t}clear(){let e=this.cache.size;this.cache.clear(),this.options.enableLogging&&r.debug(`Cache cleared (${e} entries removed)`)}getStats(){let e=this.stats.hits+this.stats.misses;return{hits:this.stats.hits,misses:this.stats.misses,size:this.cache.size,evictions:this.stats.evictions,hitRate:e>0?this.stats.hits/e:0}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}has(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),!1):!0:!1}evictLeastRecentlyUsed(){let e,t;for(let[o,n]of this.cache.entries()){if(Date.now()>n.expiresAt){this.cache.delete(o),this.stats.evictions++;return}(!t||n.hits<t.hits||n.hits===t.hits&&n.createdAt<t.createdAt)&&(e=o,t=n)}e&&(this.cache.delete(e),this.stats.evictions++,this.options.enableLogging&&r.debug(`Cache evicted LRU entry: ${e}`))}},Oe={zoneInfo:i=>`zone:${i}:info`,rulesets:i=>`zone:${i}:rulesets`,ruleset:(i,e)=>`zone:${i}:ruleset:${e}`,lists:i=>`account:${i}:lists`,listItems:(i,e)=>`account:${i}:list:${e}:items`,credentialValidation:i=>`cred:${i}`,configValidation:i=>`config:${i}`},Fe={ZONE_INFO:600*1e3,RULESETS:120*1e3,RULESET:60*1e3,LISTS:300*1e3,LIST_ITEMS:120*1e3,CREDENTIALS:900*1e3,CONFIG_VALIDATION:300*1e3};T();var tr={maxConnections:6,idleTimeout:3e4,keepAlive:!0},ir={ttl:5e3,maxEntries:100},Ne=class{stats={diffOperations:0,diffTotalDuration:0,earlyExits:0,deduplicatedRequests:0,pooledConnections:0,chunkedOperations:0};poolOptions;dedupOptions;inFlightRequests=new Map;hashCache=new Map;activeConnections=0;connectionQueue=[];constructor(e={},t={}){this.poolOptions={...tr,...e},this.dedupOptions={...ir,...t}}computeRuleHash(e){let t=this.canonicalizeRule(e),o=this.hashCache.get(t);if(o)return o;let n=this.simpleHash(t);return this.hashCache.set(t,n),n}diffRules(e,t){let o=performance.now();if(this.stats.diffOperations++,e.length===0&&t.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-o};if(e===t)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:e.length,duration:performance.now()-o};if(e.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[...t],unchanged:0,duration:performance.now()-o};if(t.length===0)return this.stats.earlyExits++,{toAdd:[...e],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-o};let n=new Map;for(let p of t){let g=p.id||p.name;n.set(g,{rule:p,hash:this.computeRuleHash(p)})}let s=new Map,a=[],l=[],c=0;for(let p of e){let g=p.id||p.name;s.set(g,!0);let h=n.get(g);h?this.computeRuleHash(p)!==h.hash?l.push(p):c++:a.push(p)}let d=[];for(let[p,g]of n)s.has(p)||d.push(g.rule);let u=performance.now()-o;return this.stats.diffTotalDuration+=u,r.debug(`Optimized diff: +${a.length} ~${l.length} -${d.length} =${c} (${u.toFixed(1)}ms)`),{toAdd:a,toUpdate:l,toDelete:d,unchanged:c,duration:u}}diffCloudflareRules(e,t){let o=new Map(t.map(p=>[p.id,p])),n=new Set,s=[],a=[];for(let{rule:p,translated:g}of e){let h=p.id||p.name;n.add(h);let I=o.get(h);I?this.cloudflareRulesEqual(g,I)||a.push(p):s.push(p)}let l=[];for(let[p,g]of o)n.has(p)||l.push(g);let c=new Set(a.map(p=>p.id||p.name)),d=e.map(({rule:p})=>p.id||p.name).filter(p=>o.has(p)),u=t.map(p=>p.id).filter(p=>n.has(p));return d.forEach((p,g)=>{if(u[g]===p||c.has(p))return;let h=e.find(({rule:I})=>(I.id||I.name)===p);h&&(a.push(h.rule),c.add(p))}),{toAdd:s,toUpdate:a,toDelete:l}}cloudflareRulesEqual(e,t){return e.action===t.action&&e.expression===t.expression&&(e.enabled??!0)===(t.enabled??!0)&&(e.description||"")===(t.description||"")&&JSON.stringify(e.ratelimit??null)===JSON.stringify(t.ratelimit??null)&&JSON.stringify(e.action_parameters??null)===JSON.stringify(t.action_parameters??null)}diffIPRules(e,t){let o=performance.now();if(e.length===0&&t.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-o};if(e.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[...t],unchanged:0,duration:performance.now()-o};if(t.length===0)return this.stats.earlyExits++,{toAdd:[...e],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-o};let n=new Map;for(let p of t)n.set(p.ip,p);let s=new Set,a=[],l=[],c=0;for(let p of e){s.add(p.ip);let g=n.get(p.ip);g?p.action!==g.action?l.push(p):c++:a.push(p)}let d=[];for(let[p,g]of n)s.has(p)||d.push(g);let u=performance.now()-o;return{toAdd:a,toUpdate:l,toDelete:d,unchanged:c,duration:u}}async acquireConnection(){if(this.activeConnections<this.poolOptions.maxConnections){this.activeConnections++,this.stats.pooledConnections++;return}return new Promise(e=>{this.connectionQueue.push(()=>{this.activeConnections++,this.stats.pooledConnections++,e()})})}releaseConnection(){this.activeConnections--,this.connectionQueue.length>0&&this.connectionQueue.shift()()}async withConnection(e){await this.acquireConnection();try{return await e()}finally{this.releaseConnection()}}async executePooled(e){if(e.length===0)return[];let t=new Array(e.length),o=[];for(let n=0;n<e.length;n++){let s=n,a=e[s],l=this.withConnection(async()=>{t[s]=await a()});o.push(l)}return await Promise.all(o),t}getConnectionHeaders(){return this.poolOptions.keepAlive?{Connection:"keep-alive","Keep-Alive":`timeout=${Math.floor(this.poolOptions.idleTimeout/1e3)}`}:{}}async deduplicateRequest(e,t){this.cleanupExpiredRequests();let o=this.inFlightRequests.get(e);if(o&&Date.now()-o.createdAt<this.dedupOptions.ttl)return this.stats.deduplicatedRequests++,r.debug(`Request deduplicated: ${e}`),o.promise;let n=t().finally(()=>{this.inFlightRequests.delete(e)});return this.inFlightRequests.set(e,{promise:n,createdAt:Date.now()}),n}static requestKey(e,t,o){let n=[e.toUpperCase(),t];return o&&n.push(o),n.join(":")}cleanupExpiredRequests(){let e=Date.now();for(let[t,o]of this.inFlightRequests)e-o.createdAt>this.dedupOptions.ttl&&this.inFlightRequests.delete(t);if(this.inFlightRequests.size>this.dedupOptions.maxEntries){let t=Array.from(this.inFlightRequests.entries());t.sort((n,s)=>n[1].createdAt-s[1].createdAt);let o=t.slice(0,t.length-this.dedupOptions.maxEntries);for(let[n]of o)this.inFlightRequests.delete(n)}}async processInChunks(e,t,o){if(e.length===0)return[];this.stats.chunkedOperations++;let n=[],s=Math.ceil(e.length/t);e.length>t&&r.debug(`Processing ${e.length} items in ${s} chunks of ${t}`);for(let a=0;a<e.length;a+=t){let l=e.slice(a,a+t),c=Math.floor(a/t),d=await o(l,c);n.push(...d)}return n}estimateMemoryUsage(e){if(e.length===0)return 0;let t=Math.min(10,e.length),o=0;for(let s=0;s<t;s++)o+=JSON.stringify(e[s]).length*2;let n=o/t;return Math.ceil(n*e.length)}getOptimalChunkSize(e,t=500){let n=Math.max(10,Math.floor(1048576/t)),s=Math.min(n,100);return e<=s?e:s}getStats(){return{...this.stats}}resetStats(){this.stats={diffOperations:0,diffTotalDuration:0,earlyExits:0,deduplicatedRequests:0,pooledConnections:0,chunkedOperations:0}}clearCaches(){this.hashCache.clear(),this.inFlightRequests.clear()}getActiveConnections(){return this.activeConnections}getPendingConnections(){return this.connectionQueue.length}getInFlightCount(){return this.inFlightRequests.size}canonicalizeRule(e){let t={action:e.action,conditions:e.conditions.map(o=>({field:o.field,key:o.key,negated:o.negated,operator:o.operator,value:o.value})).sort((o,n)=>`${o.field}:${o.operator}`.localeCompare(`${n.field}:${n.operator}`)),enabled:e.enabled,name:e.name};return e.conditionLogic&&(t.conditionLogic=e.conditionLogic),e.description&&(t.description=e.description),e.priority!==void 0&&(t.priority=e.priority),JSON.stringify(t)}simpleHash(e){let t=5381;for(let o=0;o<e.length;o++)t=(t<<5)+t+e.charCodeAt(o)|0;return t.toString(36)}};var Ye=class extends Ae{apiToken;zoneId;accountId;cache;optimizer;constructor(e,t,o){super("https://api.cloudflare.com/client/v4","cloudflare"),this.apiToken=e,this.zoneId=t,this.accountId=o,this.cache=new Et({enableLogging:!0}),this.optimizer=new Ne}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}invalidateRulesetCache(){this.cache.invalidateByPrefix(`zone:${this.zoneId}`)}invalidateListCache(){this.accountId&&this.cache.invalidateByPrefix(`account:${this.accountId}`)}getAuthHeaders(){return{Authorization:`Bearer ${this.apiToken}`,...this.optimizer.getConnectionHeaders()}}getOptimizer(){return this.optimizer}async listRulesets(){r.debug(`Fetching rulesets for zone ${this.zoneId}`);let e=Oe.rulesets(this.zoneId),t=this.cache.get(e);if(t)return t;let o=Ne.requestKey("GET",`/zones/${this.zoneId}/rulesets`);return this.optimizer.deduplicateRequest(o,async()=>{try{let n=await this.get(`/zones/${this.zoneId}/rulesets`);if(!n.success)throw K.handleApiResponse(n,`/zones/${this.zoneId}/rulesets`);if(!Array.isArray(n.result))return r.warn("Malformed API response: expected array of rulesets, got:",typeof n.result),[];let s=n.result.filter(a=>!a||typeof a!="object"?(r.warn("Skipping malformed ruleset object:",a),!1):!a.id||!a.name?(r.warn("Skipping ruleset with missing required fields:",{id:a.id,name:a.name}),!1):!0);return s.length!==n.result.length&&r.warn(`Filtered out ${n.result.length-s.length} malformed rulesets`),this.cache.set(e,s,Fe.RULESETS),s}catch(n){throw n instanceof Error&&!n.code?K.handleNetworkError(n,"listing rulesets"):n}})}async getRulesets(){return this.listRulesets()}async getRuleset(e){r.debug(`Fetching ruleset ${e}`);let t=Oe.ruleset(this.zoneId,e),o=this.cache.get(t);if(o)return o;let n=Ne.requestKey("GET",`/zones/${this.zoneId}/rulesets/${e}`);return this.optimizer.deduplicateRequest(n,async()=>{try{let s=await this.get(`/zones/${this.zoneId}/rulesets/${e}`);if(!s.success)throw K.handleApiResponse(s,`/zones/${this.zoneId}/rulesets/${e}`);if(!s.result||typeof s.result!="object")throw K.handleValidationError("ruleset","Invalid ruleset data received from API",s.result);let a=s.result;if(!a.id||!a.name)throw K.handleValidationError("ruleset","Ruleset missing required fields (id, name)",a);Array.isArray(a.rules)||(r.warn(`Ruleset ${e} has invalid rules array, initializing as empty`),a.rules=[]);let l=a.rules.filter(c=>!c||typeof c!="object"?(r.warn(`Skipping malformed rule in ruleset ${e}:`,c),!1):!c.id||!c.expression||!c.action?(r.warn(`Skipping rule with missing required fields in ruleset ${e}:`,{id:c.id,expression:c.expression,action:c.action}),!1):!0);return l.length!==a.rules.length&&(r.warn(`Filtered out ${a.rules.length-l.length} malformed rules from ruleset ${e}`),a.rules=l),this.cache.set(t,a,Fe.RULESET),a}catch(s){throw s instanceof Error&&!s.code?K.handleNetworkError(s,"fetching ruleset"):s}})}async createRuleset(e){r.debug(`Creating ruleset: ${e.name}`);let t=await this.post(`/zones/${this.zoneId}/rulesets`,e);if(!t.success){let o=t.errors.map(n=>n.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets`,t.errors[0]?.code||0,o)}return r.info(`Created ruleset: ${t.result.name} (${t.result.id})`),this.invalidateRulesetCache(),t.result}async updateRuleset(e,t){r.debug(`Updating ruleset ${e}`);let o=await this.put(`/zones/${this.zoneId}/rulesets/${e}`,t);if(!o.success){let n=o.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}`,o.errors[0]?.code||0,n)}return r.info(`Updated ruleset to version ${o.result.version}`),this.invalidateRulesetCache(),o.result}async deleteRuleset(e){r.debug(`Deleting ruleset ${e}`);let t=await this.delete(`/zones/${this.zoneId}/rulesets/${e}`);if(!t.success){let o=t.errors.map(n=>n.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}`,t.errors[0]?.code||0,o)}r.info(`Deleted ruleset ${e}`),this.invalidateRulesetCache()}async createRule(e,t){r.debug(`Adding rule to ruleset ${e}`);let o=await this.post(`/zones/${this.zoneId}/rulesets/${e}/rules`,t);if(!o.success){let n=o.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules`,o.errors[0]?.code||0,n)}return r.info(`Added rule to ruleset ${e}`),this.invalidateRulesetCache(),o.result}async updateRule(e,t,o){r.debug(`Updating rule ${t} in ruleset ${e}`);let n=await this.patch(`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,o);if(!n.success){let s=n.errors.map(a=>a.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,n.errors[0]?.code||0,s)}return r.info(`Updated rule ${t}`),this.invalidateRulesetCache(),n.result}async deleteRule(e,t){r.debug(`Deleting rule ${t} from ruleset ${e}`);let o=await this.delete(`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`);if(!o.success){let n=o.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,o.errors[0]?.code||0,n)}return r.info(`Deleted rule ${t}`),this.invalidateRulesetCache(),o.result}async getOrCreateFirewallRuleset(){r.debug("Looking for existing custom firewall ruleset");let t=(await this.listRulesets()).find(o=>o.kind==="custom"&&o.phase==="http_request_firewall_custom");return t?(r.debug(`Found existing ruleset: ${t.id}`),t):(r.info("No existing custom firewall ruleset found, creating new one"),this.createRuleset({name:"Doorman Custom Firewall Rules",kind:"custom",phase:"http_request_firewall_custom",description:"Custom firewall rules managed by Doorman",rules:[]}))}async verifyCredentials(){let e=(0,so.createHash)("sha256").update(this.apiToken).digest("hex").slice(0,8),t=Oe.credentialValidation(e),o=this.cache.get(t);if(o!==void 0)return r.debug("Using cached credential validation result"),o;try{return r.debug("Verifying Cloudflare credentials"),await this.listRulesets(),r.info("Cloudflare credentials verified successfully"),this.cache.set(t,!0,Fe.CREDENTIALS),!0}catch(n){if(r.error(`Cloudflare credential verification failed: ${n}`),n instanceof Error){let s=n.message.toLowerCase();if(s.includes("unauthorized")||s.includes("invalid token"))throw K.handleCredentialError("token");if(s.includes("forbidden")||s.includes("access denied"))throw K.handleCredentialError("zone",this.zoneId);if(s.includes("not found"))throw K.handleCredentialError("zone",this.zoneId)}return!1}}async getZoneInfo(){let e=Oe.zoneInfo(this.zoneId),t=this.cache.get(e);if(t)return t;let o=await this.get(`/zones/${this.zoneId}`);if(!o.success){let n=o.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}`,o.errors[0]?.code||0,n)}return this.cache.set(e,o.result,Fe.ZONE_INFO),o.result}async listLists(){if(r.debug("Fetching Cloudflare Lists"),!this.accountId)return r.warn("Account ID not provided, Lists API requires account-level access"),[];let e=Oe.lists(this.accountId),t=this.cache.get(e);if(t)return t;let o=await this.get(`/accounts/${this.accountId}/rules/lists`);if(!o.success){let n=o.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,o.errors[0]?.code||0,n)}return this.cache.set(e,o.result,Fe.LISTS),o.result}async getList(e){if(r.debug(`Fetching List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let t=await this.get(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let o=t.errors.map(n=>n.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,t.errors[0]?.code||0,o)}return t.result}async createList(e){if(r.debug(`Creating List: ${e.name}`),!this.accountId)throw B.accountIdRequired("Lists API");let t=await this.post(`/accounts/${this.accountId}/rules/lists`,e);if(!t.success){let o=t.errors.map(n=>n.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,t.errors[0]?.code||0,o)}return r.info(`Created List: ${t.result.name} (${t.result.id})`),this.invalidateListCache(),t.result}async updateList(e,t){if(r.debug(`Updating List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let o=await this.put(`/accounts/${this.accountId}/rules/lists/${e}`,t);if(!o.success){let n=o.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,o.errors[0]?.code||0,n)}return r.info(`Updated List ${e}`),this.invalidateListCache(),o.result}async deleteList(e){if(r.debug(`Deleting List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let t=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let o=t.errors.map(n=>n.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,t.errors[0]?.code||0,o)}r.info(`Deleted List ${e}`),this.invalidateListCache()}async getListItems(e){if(r.debug(`Fetching items from List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let t=Oe.listItems(this.accountId,e),o=this.cache.get(t);if(o)return o;let n=Ne.requestKey("GET",`/accounts/${this.accountId}/rules/lists/${e}/items`);return this.optimizer.deduplicateRequest(n,async()=>{let s=await this.fetchAllListItemPages(e);return this.cache.set(t,s,Fe.LIST_ITEMS),s})}async fetchAllListItemPages(e){let t=[],o=1;for(;;){let n=await this.get(`/accounts/${this.accountId}/rules/lists/${e}/items?page=${o}`);if(!n.success){let a=n.errors.map(l=>l.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,n.errors[0]?.code||0,a)}t.push(...n.result);let s=n.result_info?.total_pages??1;if(n.result.length===0||o>=s)break;o++}return t}async addListItems(e,t){if(r.debug(`Adding ${t.items.length} items to List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let o=await this.post(`/accounts/${this.accountId}/rules/lists/${e}/items`,t.items);if(!o.success){let n=o.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,o.errors[0]?.code||0,n)}return r.info(`Added ${t.items.length} items to List ${e}`),this.invalidateListCache(),o.result}async removeListItems(e,t){if(r.debug(`Removing ${t.items.length} items from List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let o=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}/items`,{body:JSON.stringify(t)});if(!o.success){let n=o.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,o.errors[0]?.code||0,n)}r.info(`Removed ${t.items.length} items from List ${e}`),this.invalidateListCache()}async getOrCreateIPBlocklist(){if(r.debug("Looking for existing Doorman IP blocklist"),!this.accountId)throw r.warn("Account ID not provided, cannot use Lists for IP blocking"),K.handleCredentialError("account");try{let t=(await this.listLists()).find(o=>o.name==="Doorman IP Blocklist"&&o.kind==="ip");return t?(r.debug(`Found existing IP blocklist: ${t.id}`),t):(r.info("No existing IP blocklist found, creating new one"),this.createList({name:"Doorman IP Blocklist",description:"IP addresses blocked by Doorman",kind:"ip"}))}catch(e){throw e instanceof Error&&!e.code?K.handleNetworkError(e,"managing IP blocklist"):e}}};var Je=require("net");T();var ct=class i extends Pe{name="cloudflare";client;optimizer;useListsForIPs;constructor(e,t,o){super(),this.client=new Ye(e,t,o),this.optimizer=this.client.getOptimizer(),this.useListsForIPs=!!o,this.useListsForIPs?r.debug("Lists API enabled for IP blocking (account ID provided)"):r.debug("Lists API disabled - will use individual IP rules (no account ID)")}async fetchConfig(e){r.info("Fetching configuration from Cloudflare");try{let t=await this.client.getOrCreateFirewallRuleset(),o=[],n=[],s=[],a=[],l=50,c=t.rules.length;c>100&&r.info(`Processing ${c} rules in batches of ${l} to optimize memory usage`);for(let d=0;d<c;d+=l){let u=t.rules.slice(d,d+l);r.debug(`Processing rules batch ${Math.floor(d/l)+1}/${Math.ceil(c/l)} (${u.length} rules)`);for(let p of u)try{if(!p||typeof p!="object"){a.push(`Skipped malformed rule at index ${d}: not an object`);continue}if(!p.id||!p.expression||!p.action){a.push(`Skipped rule with missing required fields: ${JSON.stringify({id:p.id,expression:!!p.expression,action:p.action})}`);continue}if(this.isListBasedIPRule(p))continue;if(this.isIPBlockingRule(p)){let g=this.cloudflareRuleToIPRule(p);n.push(g)}else{let g=k.cloudflareToUnified(p);o.push(g.result),g.warnings.length>0&&g.warnings.forEach(h=>{let{TranslationWarningSystem:I}=(fe(),ye(De)),R=I.formatWarning(h);s.push(R)})}}catch(g){let h=`Failed to process rule ${p?.id||"unknown"}: ${g instanceof Error?g.message:String(g)}`;r.warn(h),a.push(h)}c>200&&d+l<c&&await new Promise(p=>setTimeout(p,10))}if(a.length>0&&(r.warn(`Encountered ${a.length} rule processing errors:`),a.slice(0,5).forEach(d=>r.warn(` - ${d}`)),a.length>5&&r.warn(` ... and ${a.length-5} more errors`)),this.useListsForIPs)try{let d=await this.client.getOrCreateIPBlocklist(),u=await this.client.getListItems(d.id);for(let p of u)p.ip&&n.push({id:p.id,ip:p.ip,notes:p.comment,action:"deny"});r.debug(`Fetched ${u.length} IPs from List`)}catch(d){this.handleListsAPIFallback(d,"fetching IPs from List")}else n.length>10&&r.warn(`\u26A0\uFE0F Large IP list detected (${n.length} IPs) without Lists API. Consider providing CLOUDFLARE_ACCOUNT_ID for better performance.`);return s.length>0&&(r.warn("Translation warnings detected:"),s.forEach(d=>r.warn(d)),s.length>3&&r.warn(`
30
- \u{1F4CA} Summary: ${s.length} translation warnings detected. Review each warning above for specific guidance.`)),{version:"2.0",provider:"cloudflare",providers:{cloudflare:{zoneId:this.client.zoneId,accountId:this.client.accountId}},rules:o,ips:n,metadata:{version:parseInt(t.version,10),updatedAt:t.last_updated}}}catch(t){throw t instanceof Error&&!("code"in t)?K.handleNetworkError(t,"fetching configuration"):t}}async syncRules(e,t){r.info(`Syncing ${e.rules.length} rules to Cloudflare${t?.dryRun?" (dry run)":""}`);let{OperationSafety:o}=(bt(),ye(vt)),n=await o.performDryRunValidation(e,"sync rules",async I=>await this.getChanges(I));if(!n.valid)throw new Error(`Dry-run validation failed: ${n.issues.join(", ")}`);if(t?.dryRun)return{success:!0,rulesAdded:n.changes.rulesToAdd.length,rulesUpdated:n.changes.rulesToUpdate.length,rulesDeleted:n.changes.rulesToDelete.length,ipsAdded:n.changes.ipsToAdd?.length||0,ipsUpdated:n.changes.ipsToUpdate?.length||0,ipsDeleted:n.changes.ipsToDelete?.length||0,warnings:n.warnings};let s=o.assessOperationRisk(n.changes,e);if(!await o.confirmDestructiveOperation({operation:"sync rules",target:`Cloudflare zone ${this.client.zoneId}`,changes:n.changes,riskLevel:s,skipConfirmation:t?.force||!1,dryRun:t?.dryRun||!1,allowDeletions:t?.allowDeletions||!1}))throw new Error("Operation cancelled by user");let l=await this.client.getOrCreateFirewallRuleset(),c=[];for(let I of lt(e.rules)){let R=k.unifiedToCloudflare(I);c.push(R.result),R.warnings.length>0&&R.warnings.forEach(N=>{let{TranslationWarningSystem:H}=(fe(),ye(De)),W=H.formatWarning(N);r.warn(W)})}let d=0,u=0,p=0;if(this.useListsForIPs&&e.ips&&e.ips.length>0){let I=new Set;try{let R=await this.client.getOrCreateIPBlocklist(),N=await this.client.getListItems(R.id),H=new Set(N.map(_=>_.ip));H.forEach(_=>_&&I.add(_));let W=new Set(e.ips.map(_=>_.ip)),ue=e.ips.filter(_=>!H.has(_.ip));ue.length>0&&(await this.client.addListItems(R.id,{items:ue.map(_=>({ip:_.ip,comment:_.notes||_.hostname||"Blocked by Doorman"}))}),d=ue.length,ue.forEach(_=>I.add(_.ip)),r.info(`Added ${d} IPs to List`));let me=N.filter(_=>_.ip&&!W.has(_.ip));me.length>0&&(await this.client.removeListItems(R.id,{items:me.map(_=>({id:_.id}))}),p=me.length,me.forEach(_=>_.ip&&I.delete(_.ip)),r.info(`Removed ${p} IPs from List`));let _e=`ip.src in $${R.name.replace(/\s+/g,"_").toLowerCase()}`;c.push({id:"rule_doorman_ip_list",action:"block",expression:_e,description:"Block IPs in Doorman IP Blocklist",enabled:!0})}catch(R){this.handleListsAPIFallback(R,"syncing IPs via List");let N=e.ips.filter(H=>!I.has(H.ip));if(N.length>0){r.info(`\u{1F504} Falling back to individual IP rules for ${N.length} IPs`);for(let H of N){let W=k.unifiedIPToCloudflare(H);c.push(W)}d=N.length}else r.info("All IPs were already confirmed in the List before the failure; no fallback rules needed.");N.length>50&&r.warn(`\u26A0\uFE0F Performance warning: Using ${N.length} individual IP rules instead of Lists. This may impact rule processing speed and count against your rule limit.`)}}else if(e.ips&&e.ips.length>0){r.info(`\u{1F4DD} Using individual IP rules for ${e.ips.length} IPs (Lists API not available)`),e.ips.length>20&&r.warn(`\u26A0\uFE0F Large IP list detected (${e.ips.length} IPs) without Lists API. Consider providing CLOUDFLARE_ACCOUNT_ID for better performance and rule efficiency.`);for(let I of e.ips){let R=k.unifiedIPToCloudflare(I);c.push(R)}d=e.ips.length}let g=await this.client.updateRuleset(l.id,{rules:c}),h={success:!0,rulesAdded:n.changes.rulesToAdd.length,rulesUpdated:n.changes.rulesToUpdate.length,rulesDeleted:n.changes.rulesToDelete.length,ipsAdded:d,ipsUpdated:u,ipsDeleted:p,version:parseInt(g.version,10),warnings:n.warnings?.length?n.warnings:void 0};return this.logSyncStats(h),h}async getChanges(e){let t=await this.client.getOrCreateFirewallRuleset(),o=t.rules.filter(c=>c&&c.id&&c.expression&&c.action&&!this.isListBasedIPRule(c)&&!this.isIPBlockingRule(c)),n=lt(e.rules).map(c=>({rule:c,translated:k.unifiedToCloudflare(c).result})),s=this.optimizer.diffCloudflareRules(n,o),a=s.toDelete.map(c=>k.cloudflareToUnified(c).result),l={toAdd:[],toUpdate:[],toDelete:[]};if(e.ips){let c=await this.fetchRemoteIPRulesForDiff(t.rules);l=this.optimizer.diffIPRules(e.ips,c)}return{rulesToAdd:s.toAdd,rulesToUpdate:s.toUpdate,rulesToDelete:a,ipsToAdd:l.toAdd,ipsToUpdate:l.toUpdate,ipsToDelete:l.toDelete,version:parseInt(t.version,10),hasChanges:s.toAdd.length>0||s.toUpdate.length>0||a.length>0||l.toAdd.length>0||l.toUpdate.length>0||l.toDelete.length>0}}async fetchRemoteIPRulesForDiff(e){let t=[];for(let o of e)o&&o.id&&o.expression&&o.action&&this.isIPBlockingRule(o)&&t.push(this.cloudflareRuleToIPRule(o));if(this.useListsForIPs)try{let o=await this.client.getOrCreateIPBlocklist(),n=await this.client.getListItems(o.id);for(let s of n)s.ip&&t.push({id:s.id,ip:s.ip,notes:s.comment,action:"deny"})}catch(o){this.handleListsAPIFallback(o,"fetching IPs from List")}return t}getSupportedFeatures(){return{supportsCustomRules:!0,supportsIPBlocking:!0,supportsRateLimiting:!0,supportsManagedRules:!0,supportsGeoBlocking:!0,supportsRedirect:!0,supportsChallenge:!0,maxRules:125}}validateConfig(e){let t=super.validateConfig(e),o=[...t.errors],n=[...t.warnings];if(e&&e.rules){let s=this.getSupportedFeatures();if(s.maxRules&&e.rules.length>s.maxRules){let a=B.ruleLimitExceeded(e.rules.length,s.maxRules);o.push({path:"rules",message:a.message,code:a.code})}if(e.rules.forEach((a,l)=>{try{if(!a.conditions||a.conditions.length===0){let c=B.ruleNoConditions(a.name||`Rule ${l+1}`);o.push({path:`rules[${l}]`,message:c.message,code:c.code})}if(a.action.type==="rate_limit"&&a.action.rateLimit){let c=a.action.rateLimit;if(c.requests<1){let d=B.invalidRateLimit(a.name||`Rule ${l+1}`,"requests must be at least 1");o.push({path:`rules[${l}].action.rateLimit.requests`,message:d.message,code:d.code})}if(!c.window.match(/^\d+[smhd]$/)){let d=B.invalidWindowFormat(c.window);o.push({path:`rules[${l}].action.rateLimit.window`,message:d.message,code:d.code})}if(c.characteristics&&c.characteristics.length===0){let d=B.emptyCharacteristics(a.name||`Rule ${l+1}`);n.push({path:`rules[${l}].action.rateLimit.characteristics`,message:d.message,code:d.code})}if(c.mitigationTimeout!==void 0&&c.mitigationTimeout<60){let d=B.shortMitigationTimeout(c.mitigationTimeout);n.push({path:`rules[${l}].action.rateLimit.mitigationTimeout`,message:d.message,code:d.code})}}if(a.action.type==="redirect"&&a.action.redirect){let c=a.action.redirect;if(c.location)try{new URL(c.location)}catch{if(!c.location.startsWith("/")){let d=B.invalidRedirectUrl(c.location);o.push({path:`rules[${l}].action.redirect.location`,message:d.message,code:d.code})}}else{let d=B.redirectNoLocation(a.name||`Rule ${l+1}`);o.push({path:`rules[${l}].action.redirect.location`,message:d.message,code:d.code})}}}catch(c){o.push({path:`rules[${l}]`,message:`Validation error: ${c instanceof Error?c.message:String(c)}`,code:"CLOUDFLARE_VALIDATION_ERROR"})}}),e.ips&&(e.ips.forEach((a,l)=>{try{if(!i.isValidIPOrCIDR(a.ip)){let c=B.invalidIP(a.ip);o.push({path:`ips[${l}].ip`,message:c.message,code:c.code})}}catch(c){o.push({path:`ips[${l}]`,message:`IP validation error: ${c instanceof Error?c.message:String(c)}`,code:"CLOUDFLARE_IP_VALIDATION_ERROR"})}}),!this.useListsForIPs&&e.ips.length>50)){let a=B.largeIPList(e.ips.length);n.push({path:"ips",message:a.message,code:a.code})}}return{valid:o.length===0,errors:o,warnings:n}}getHealthScore(e){let t=super.getHealthScore(e),o=[...t.issues],n=this.getSupportedFeatures();return n.maxRules&&e.rules.length>n.maxRules*.8&&o.push({severity:"warning",category:"limits",message:`Approaching Cloudflare rule limit (${e.rules.length}/${n.maxRules})`,suggestion:"Consider consolidating rules or upgrading plan"}),{...t,issues:o}}async verifyCredentials(){return this.client.verifyCredentials()}getCacheStats(){return this.client.getCacheStats()}getOptimizerStats(){return this.optimizer.getStats()}clearCache(){this.client.clearCache(),this.optimizer.clearCaches()}static isValidIPOrCIDR(e){let[t,o,...n]=e.split("/");if(n.length>0||!t)return!1;if(o===void 0)return(0,Je.isIPv4)(t)||(0,Je.isIPv6)(t);if(!/^\d+$/.test(o))return!1;let s=Number(o);return(0,Je.isIPv4)(t)?s<=32:(0,Je.isIPv6)(t)?s<=128:!1}isListBasedIPRule(e){return/ip\.src in \$/.test(e.expression.trim())}isIPBlockingRule(e){if(e.action!=="block"&&e.action!=="allow")return!1;let t=e.expression.trim();return i.IP_EQ_PATTERN.test(t)||i.IP_IN_SET_PATTERN.test(t)}static IP_EQ_PATTERN=/^ip\.src eq ([0-9a-fA-F:.]+)$/;static IP_IN_SET_PATTERN=/^ip\.src in \{([0-9a-fA-F:./]+)\}$/;cloudflareRuleToIPRule(e){let t=e.expression.trim(),n=(t.match(i.IP_EQ_PATTERN)||t.match(i.IP_IN_SET_PATTERN))?.[1]||"",a=e.description?.match(/\(([^)]+)\)/)?.[1];return{id:e.id,ip:n,hostname:a,notes:e.description,action:e.action==="allow"?"allow":"deny"}}handleListsAPIFallback(e,t){if(e instanceof Error){let o=e.message.toLowerCase();o.includes("account")?(r.warn("\u{1F6AB} Lists API unavailable: Account ID not provided or invalid. Falling back to individual IP rules."),r.info(`\u{1F4A1} To enable Lists API for better performance with large IP lists:
28
+ `):n;e.push(` ${xe.default.cyan(t)}: ${o}`)}),e.push("")),this.cause&&(e.push(xe.default.dim("Caused by:")),e.push(` ${this.cause.message}`),e.push("")),this.docsUrl&&(e.push(xe.default.cyan.bold("Documentation:")),e.push(` ${this.docsUrl}`),e.push("")),e.join(`
29
+ `)}toPlainText(){let e=[];return e.push(`[${this.code}] ${this.message}`),this.suggestion&&e.push(`Suggestion: ${this.suggestion}`),this.details&&Object.keys(this.details).length>0&&(e.push("Details:"),Object.entries(this.details).forEach(([t,n])=>{e.push(` ${t}: ${n}`)})),this.cause&&e.push(`Caused by: ${this.cause.message}`),this.docsUrl&&e.push(`Documentation: ${this.docsUrl}`),e.join(`
30
+ `)}static isDoormanError(e){return e instanceof i}static from(e,t,n){return i.isDoormanError(e)?e:e instanceof Error?new i({code:t,message:n||e.message,cause:e}):new i({code:t,message:n||String(e)})}};var $="https://docs.doorman.griffen.codes/errors";var G={authFailed:(i,e)=>new m({code:"PROV_5000",message:`Authentication failed for ${i}`,suggestion:"Check that your API credentials are valid and have the correct permissions",details:{provider:i},cause:e,docsUrl:`${$}/PROV_5000`}),apiError:(i,e,t,n)=>new m({code:"PROV_5002",message:`${i} API error: ${t} ${n}`,suggestion:"Check the provider status page and your credentials",details:{provider:i,endpoint:e,statusCode:t,responseMessage:n},docsUrl:`${$}/PROV_5002`}),rateLimit:(i,e)=>new m({code:"PROV_5003",message:`Rate limit exceeded for ${i}`,suggestion:e?`Wait ${e} seconds and try again, or use --retry flag`:"Wait a few minutes and try again, or use --retry flag",details:{provider:i,retryAfter:e},docsUrl:`${$}/PROV_5003`}),timeout:(i,e)=>new m({code:"PROV_5006",message:`Request timeout for ${i} ${e}`,suggestion:"Check your internet connection and try again",details:{provider:i,operation:e},docsUrl:`${$}/PROV_5006`}),invalidCredentials:(i,e)=>new m({code:"PROV_5004",message:`Missing or invalid credentials for ${i}`,suggestion:`Please provide: ${e.join(", ")}`,details:{provider:i,missing:e},docsUrl:`${$}/PROV_5004`})},B={accountIdRequired:i=>new m({code:"CF_6004",message:`Account ID required for ${i}`,suggestion:"Provide CLOUDFLARE_ACCOUNT_ID in your environment or configuration to use Lists API",details:{operation:i},docsUrl:`${$}/CF_6004`}),zoneIdRequired:i=>new m({code:"CF_6005",message:`Zone ID required for ${i}`,suggestion:"Provide CLOUDFLARE_ZONE_ID in your environment or configuration",details:{operation:i},docsUrl:`${$}/CF_6005`}),invalidCredentials:(i,e)=>new m({code:"CF_6016",message:`Invalid Cloudflare ${i}`,suggestion:"Check your Cloudflare API credentials and ensure they have the correct permissions",details:{credentialType:i,...e},docsUrl:`${$}/CF_6016`}),insufficientPermissions:(i,e)=>new m({code:"CF_6017",message:`Insufficient permissions for ${i}`,suggestion:`Ensure your API token has the following permissions: ${e.join(", ")}`,details:{operation:i,requiredPermissions:e},docsUrl:`${$}/CF_6017`}),ruleLimitExceeded:(i,e)=>new m({code:"CF_6001",message:`Rule count (${i}) exceeds Cloudflare limit (${e})`,suggestion:"Consider consolidating rules, using Lists for IP blocking, or upgrading your Cloudflare plan",details:{count:i,limit:e},docsUrl:`${$}/CF_6001`}),invalidExpression:(i,e)=>new m({code:"CF_6002",message:`Invalid Cloudflare expression: ${e}`,suggestion:"Check Cloudflare Wirefilter expression syntax and field names",details:{expression:i,reason:e},docsUrl:`${$}/CF_6002`}),ruleNoConditions:i=>new m({code:"CF_6007",message:`Rule "${i}" has no conditions`,suggestion:"Add at least one condition to the rule or remove the empty rule",details:{ruleName:i},docsUrl:`${$}/CF_6007`}),invalidRateLimit:(i,e)=>new m({code:"CF_6008",message:`Invalid rate limit configuration for rule "${i}": ${e}`,suggestion:'Rate limit requests must be at least 1, and window format should be like "60s", "1h", "1d"',details:{ruleName:i,issue:e},docsUrl:`${$}/CF_6008`}),invalidWindowFormat:i=>new m({code:"CF_6009",message:`Invalid rate limit window format: ${i}`,suggestion:'Use format like "60s", "5m", "1h", or "1d"',details:{window:i},docsUrl:`${$}/CF_6009`}),shortMitigationTimeout:i=>new m({code:"CF_6010",message:`Mitigation timeout (${i}s) may be too short`,suggestion:"Consider using at least 60 seconds for effective rate limiting",details:{timeout:i},docsUrl:`${$}/CF_6010`}),redirectNoLocation:i=>new m({code:"CF_6011",message:`Redirect rule "${i}" is missing location URL`,suggestion:"Add a redirect.location property with a valid URL or path",details:{ruleName:i},docsUrl:`${$}/CF_6011`}),invalidRedirectUrl:i=>new m({code:"CF_6012",message:`Invalid redirect URL: ${i}`,suggestion:"Use a valid absolute URL (https://...) or relative path (/...)",details:{url:i},docsUrl:`${$}/CF_6012`}),invalidIP:i=>new m({code:"CF_6013",message:`Invalid IP address format: ${i}`,suggestion:"Use valid IPv4 or IPv6 address with optional CIDR notation (e.g., 192.168.1.1 or 192.168.1.0/24)",details:{ip:i},docsUrl:`${$}/CF_6013`}),largeIPList:i=>new m({code:"CF_6014",message:`Large IP list detected (${i} IPs)`,suggestion:"Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance with large IP lists",details:{count:i},docsUrl:`${$}/CF_6014`}),rulesetNotFound:i=>new m({code:"CF_6000",message:i?`Ruleset not found: ${i}`:"Ruleset not found",suggestion:"The ruleset may have been deleted. Try running the command again to create a new one.",details:{rulesetId:i},docsUrl:`${$}/CF_6000`}),listNotFound:i=>new m({code:"CF_6003",message:i?`List not found: ${i}`:"List not found",suggestion:"The IP list may have been deleted. Try running the command again to create a new one.",details:{listId:i},docsUrl:`${$}/CF_6003`}),emptyCharacteristics:i=>new m({code:"CF_6015",message:`Rate limit rule "${i}" has empty characteristics`,suggestion:'Add characteristics like ["ip.src"] or remove the characteristics array to use default',details:{ruleName:i},docsUrl:`${$}/CF_6015`}),translationWarning:(i,e)=>new m({code:"CF_6018",message:`Translation warning for feature "${i}": ${e}`,suggestion:"Review the translated configuration and adjust if necessary",details:{feature:i,limitation:e},docsUrl:`${$}/CF_6018`}),featureUnsupported:(i,e)=>new m({code:"CF_6019",message:`Feature "${i}" is not supported when migrating from ${e} to Cloudflare`,suggestion:"Remove this feature or implement it using Cloudflare-specific alternatives",details:{feature:i,provider:e},docsUrl:`${$}/CF_6019`}),planLimitExceeded:(i,e,t)=>new m({code:"CF_6020",message:`${i} limit exceeded: ${t}/${e}`,suggestion:"Consider upgrading your Cloudflare plan or reducing resource usage",details:{resource:i,limit:e,current:t},docsUrl:`${$}/CF_6020`}),zoneSuspended:(i,e)=>new m({code:"CF_6021",message:`Zone is suspended: ${i}${e?` (${e})`:""}`,suggestion:"Contact Cloudflare support to resolve zone suspension issues",details:{zoneId:i,reason:e},docsUrl:`${$}/CF_6021`}),maintenanceMode:i=>new m({code:"CF_6022",message:`Cloudflare ${i} is currently in maintenance mode`,suggestion:"Wait for maintenance to complete and try again. Check Cloudflare status page for updates.",details:{service:i,statusPage:"https://www.cloudflarestatus.com/"},docsUrl:`${$}/CF_6022`}),quotaExceeded:(i,e)=>new m({code:"CF_6023",message:`${i} quota exceeded`,suggestion:e?`Wait until ${e} for quota reset, or upgrade your plan for higher limits`:"Wait for quota reset or upgrade your plan for higher limits",details:{quotaType:i,resetTime:e},docsUrl:`${$}/CF_6023`}),listsAPIUnavailable:(i,e)=>new m({code:"CF_6004",message:`Lists API unavailable: ${i}`,suggestion:`Falling back to ${e}. To enable Lists API, provide CLOUDFLARE_ACCOUNT_ID and ensure your API token has Account:Read permissions.`,details:{reason:i,fallbackAction:e,severity:"warning"},docsUrl:`${$}/setup#account-id`}),performanceWarning:(i,e,t)=>new m({code:"CF_6014",message:`Performance warning: ${i} with ${e} items`,suggestion:`${t} Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance.`,details:{operation:i,count:e,impact:t,severity:"warning"},docsUrl:`${$}/performance#large-ip-lists`})};var K=class{static DOCS_BASE_URL="https://docs.doorman.griffen.codes/cloudflare";static ERROR_PATTERNS={authentication:{keywords:["authentication","token","unauthorized","invalid token"],suggestion:"Verify your CLOUDFLARE_API_TOKEN is correct and has not expired. Create a new token if needed.",docsSection:"setup#api-token"},permissions:{keywords:["forbidden","access denied","insufficient permissions"],suggestion:"Ensure your API token has the required permissions: Zone:Edit and Account:Read (for Lists API).",docsSection:"setup#permissions"},rateLimit:{keywords:["rate limit","too many requests","quota exceeded"],suggestion:"Wait before retrying or use --retry flag for automatic exponential backoff. Consider upgrading your plan.",docsSection:"troubleshooting#rate-limits"},network:{keywords:["timeout","connection","network","dns","enotfound","econnrefused"],suggestion:"Check your internet connection and ensure api.cloudflare.com is accessible through your firewall.",docsSection:"troubleshooting#connectivity"}};static detectErrorContext(e){let t=e.toLowerCase(),n={pattern:null,confidence:0};for(let[o,s]of Object.entries(this.ERROR_PATTERNS)){let l=s.keywords.filter(c=>t.includes(c)).length/s.keywords.length;l>n.confidence&&(n={pattern:o,confidence:l})}return n}static handleApiError(e){if(e.code&&e.code!==0){let t=this.mapCloudflareErrorCode(e);if(t.code!=="PROV_5002")return t}switch(e.status){case 400:return this.handleBadRequestError(e);case 401:return this.handleUnauthorizedError(e);case 403:return this.handleForbiddenError(e);case 404:return this.handleNotFoundError(e);case 429:return this.handleRateLimitError(e);case 500:case 502:case 503:case 504:return this.handleServerError(e);default:return this.handleGenericError(e)}}static handleApiResponse(e,t){if(e.success)throw new Error("Cannot handle successful response as error");let o={status:0,code:e.errors[0]?.code||0,message:e.errors.map(s=>s.message).join(", "),endpoint:t,details:{errors:e.errors,messages:e.messages}};return this.mapCloudflareErrorCode(o)}static handleCredentialError(e,t){switch(e){case"token":return new m({code:"PROV_5004",message:"Invalid or missing Cloudflare API token",suggestion:"Check your CLOUDFLARE_API_TOKEN environment variable or config file. Ensure the token has Zone:Edit and Account:Read permissions.",details:{credentialType:"api_token"},docsUrl:`${this.DOCS_BASE_URL}/setup#api-token`});case"zone":return new m({code:"CF_6005",message:t?`Invalid zone ID: ${t}`:"Missing zone ID",suggestion:"Provide a valid CLOUDFLARE_ZONE_ID. You can find this in your Cloudflare dashboard under the domain overview.",details:{zoneId:t,credentialType:"zone_id"},docsUrl:`${this.DOCS_BASE_URL}/setup#zone-id`});case"account":return new m({code:"CF_6004",message:t?`Invalid account ID: ${t}`:"Missing account ID for Lists API",suggestion:"Provide CLOUDFLARE_ACCOUNT_ID to use Lists for IP blocking. This is optional but recommended for large IP lists.",details:{accountId:t,credentialType:"account_id"},docsUrl:`${this.DOCS_BASE_URL}/setup#account-id`});default:return new m({code:"PROV_5004",message:"Invalid Cloudflare credentials",suggestion:"Check your Cloudflare API credentials",docsUrl:`${this.DOCS_BASE_URL}/setup`})}}static handleValidationError(e,t,n){let s={rules:{code:"CF_6006",suggestion:"Check your rule configuration syntax and ensure all required fields are present",docsUrl:`${this.DOCS_BASE_URL}/configuration#rules`},expression:{code:"CF_6002",suggestion:"Use valid Cloudflare Wirefilter expression syntax. Check field names and operators.",docsUrl:`${this.DOCS_BASE_URL}/expressions`},rateLimit:{code:"CF_6008",suggestion:'Rate limit requests must be at least 1, and window format should be like "60s", "1h", "1d"',docsUrl:`${this.DOCS_BASE_URL}/rate-limiting`},redirect:{code:"CF_6011",suggestion:"Redirect rules must include a valid location URL or path",docsUrl:`${this.DOCS_BASE_URL}/redirects`},ip:{code:"CF_6013",suggestion:"Use valid IPv4 or IPv6 address with optional CIDR notation (e.g., 192.168.1.1 or 192.168.1.0/24)",docsUrl:`${this.DOCS_BASE_URL}/ip-blocking`}}[e]||{code:"CF_6006",suggestion:"Check your configuration syntax",docsUrl:`${this.DOCS_BASE_URL}/configuration`};return new m({code:s.code,message:`Configuration validation failed for ${e}: ${t}`,suggestion:s.suggestion,details:{field:e,issue:t,value:n},docsUrl:s.docsUrl})}static createEnhancedSuggestion(e,t,n){let o=[e];if(n?.pattern&&n.confidence>.5){let l=this.ERROR_PATTERNS[n.pattern];o.push(l.suggestion)}let a={"syncing rules":"Try running with --dry-run first to validate your configuration.","fetching configuration":"Verify your zone ID is correct and accessible.","validating credentials":"Double-check your API token permissions in the Cloudflare dashboard.","creating ruleset":"Ensure you have Zone:Edit permissions for the specified zone.","updating rules":"Check if you have reached your plan's rule limit."}[t];return a&&o.push(a),o.join(" ")}static formatTranslationWarning(e,t,n){let{TranslationWarningSystem:o}=(fe(),ye(De)),s;try{s=o.createWarning(e,void 0,void 0,n)}catch{s=o.createLossyConversionWarning(e,`${n} (from ${t})`,void 0,void 0)}return o.formatWarning(s)}static handleNetworkError(e,t){let n=this.detectErrorContext(e.message);if(e.message.includes("timeout")){let s=this.createEnhancedSuggestion("Check your internet connection and try again. Use --retry flag for automatic retries.",t,n);return new m({code:"NET_8000",message:`Request timeout during ${t}`,suggestion:s,details:{operation:t,originalError:e.message,retryRecommended:!0,timeoutDuration:this.extractTimeoutDuration(e.message)},cause:e,docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#timeouts`})}if(e.message.includes("ENOTFOUND")||e.message.includes("ECONNREFUSED")){let s=this.createEnhancedSuggestion("Check your internet connection and firewall settings. Ensure api.cloudflare.com is accessible.",t,n);return new m({code:"NET_8001",message:`Network connection failed during ${t}`,suggestion:s,details:{operation:t,originalError:e.message,dnsResolutionFailed:e.message.includes("ENOTFOUND"),connectionRefused:e.message.includes("ECONNREFUSED")},cause:e,docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#connectivity`})}let o=this.createEnhancedSuggestion("Check your internet connection and try again",t,n);return new m({code:"NET_8004",message:`Network error during ${t}: ${e.message}`,suggestion:o,details:{operation:t,errorContext:n},cause:e,docsUrl:`${this.DOCS_BASE_URL}/troubleshooting`})}static extractTimeoutDuration(e){let t=e.match(/timeout.*?(\d+)(?:ms|s)/i);if(t&&t[1]){let n=parseInt(t[1],10),o=e.toLowerCase().includes("ms")?1:1e3;return n*o}}static handleGracefulDegradation(e,t,n,o){let a={lists_api:{code:"CF_6004",suggestion:"Provide CLOUDFLARE_ACCOUNT_ID to enable Lists API for better performance with large IP lists."},managed_rules:{code:"CF_6019",suggestion:"Use custom rules with equivalent conditions instead of managed rules."},advanced_expressions:{code:"CF_6018",suggestion:"Simplify expressions to use supported Cloudflare Wirefilter syntax."}}[e]||{code:"CF_6019",suggestion:"Consider alternative approaches or manual configuration."};return new m({code:a.code,message:`Feature degradation: ${e} - ${t}`,suggestion:`${a.suggestion} Fallback: ${n}${o?` Impact: ${o}`:""}`,details:{feature:e,reason:t,fallbackAction:n,impact:o,degradationType:"graceful"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#feature-degradation`})}static createUserFriendlyMessage(e,t,n){let o=`Failed to ${e}`,s=n?` (${Object.entries(n).map(([c,d])=>`${c}: ${d}`).join(", ")})`:"",l={401:"Please check your API token in the Cloudflare dashboard.",403:"Verify your API token has the required permissions.",404:"The requested resource may have been deleted or moved.",429:"You are being rate limited. Please wait before retrying.",500:"Cloudflare is experiencing issues. Check their status page."}[t.status]||"Please check your configuration and try again.";return`${o}${s}. ${l}`}static handleBadRequestError(e){return e.message.includes("expression")?new m({code:"CF_6002",message:`Invalid Cloudflare expression: ${e.message}`,suggestion:"Check your rule conditions and ensure they use valid Cloudflare Wirefilter syntax",details:e.details,docsUrl:`${this.DOCS_BASE_URL}/expressions`}):e.message.includes("rule")&&e.message.includes("condition")?new m({code:"CF_6007",message:"Rule validation failed: rules must have at least one condition",suggestion:"Add conditions to your rule or remove empty rules from your configuration",details:e.details,docsUrl:`${this.DOCS_BASE_URL}/rules#conditions`}):new m({code:"CF_6006",message:`Invalid request: ${e.message}`,suggestion:"Check your rule configuration for syntax errors and missing required fields",details:e.details,docsUrl:`${this.DOCS_BASE_URL}/configuration`})}static handleUnauthorizedError(e){return new m({code:"PROV_5000",message:"Authentication failed: Invalid API token",suggestion:"Check your CLOUDFLARE_API_TOKEN. Ensure it's valid and not expired. Create a new token if needed.",details:{endpoint:e.endpoint,hint:"API tokens can be created at https://dash.cloudflare.com/profile/api-tokens"},docsUrl:`${this.DOCS_BASE_URL}/setup#api-token`})}static handleForbiddenError(e){return e.endpoint?.includes("/accounts/")?new m({code:"CF_6004",message:"Access denied: Invalid account ID or insufficient permissions",suggestion:"Ensure your API token has Account:Read permissions and the account ID is correct",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/setup#permissions`}):e.endpoint?.includes("/zones/")?new m({code:"CF_6005",message:"Access denied: Invalid zone ID or insufficient permissions",suggestion:"Ensure your API token has Zone:Edit permissions and the zone ID is correct",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/setup#permissions`}):new m({code:"PROV_5000",message:"Access denied: Insufficient permissions",suggestion:"Ensure your API token has the required permissions: Zone:Edit and Account:Read (for Lists)",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/setup#permissions`})}static handleNotFoundError(e){return e.endpoint?.includes("/rulesets/")?new m({code:"CF_6000",message:"Ruleset not found",suggestion:"The ruleset may have been deleted. Try running the command again to create a new one.",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#ruleset-not-found`}):e.endpoint?.includes("/lists/")?new m({code:"CF_6003",message:"List not found",suggestion:"The IP list may have been deleted. Try running the command again to create a new one.",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#list-not-found`}):e.endpoint?.includes("/zones/")?new m({code:"CF_6005",message:"Zone not found: Invalid zone ID",suggestion:"Check your CLOUDFLARE_ZONE_ID. Find the correct zone ID in your Cloudflare dashboard.",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/setup#zone-id`}):new m({code:"PROV_5001",message:`Resource not found: ${e.message}`,suggestion:"Check that the resource exists and your credentials have access to it",details:{endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting`})}static handleRateLimitError(e){let t=e.details?.retryAfter||60;return new m({code:"PROV_5003",message:"Rate limit exceeded",suggestion:`Wait ${t} seconds and try again, or use --retry flag for automatic retries with exponential backoff`,details:{retryAfter:t,endpoint:e.endpoint,hint:"Consider upgrading your Cloudflare plan for higher rate limits"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#rate-limits`})}static handleServerError(e){return new m({code:"PROV_5002",message:`Cloudflare server error (${e.status}): ${e.message}`,suggestion:"This is a temporary Cloudflare issue. Wait a few minutes and try again, or check Cloudflare status page.",details:{status:e.status,endpoint:e.endpoint,statusPage:"https://www.cloudflarestatus.com/"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#server-errors`})}static handleGenericError(e){return new m({code:"PROV_5002",message:`Cloudflare API error (${e.status}): ${e.message}`,suggestion:"Check the Cloudflare API documentation and your request parameters",details:{status:e.status,code:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting`})}static mapCloudflareErrorCode(e){switch(e.code){case 1e4:return this.handleUnauthorizedError(e);case 10001:return this.handleForbiddenError(e);case 10013:return this.handleRateLimitError(e);case 81044:return new m({code:"CF_6000",message:"Ruleset not found",suggestion:"The ruleset may have been deleted. Try running the command again to create a new one.",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#ruleset-not-found`});case 81045:return new m({code:"CF_6001",message:"Rule limit exceeded for your Cloudflare plan",suggestion:"Consider consolidating rules, using Lists for IP blocking, or upgrading your Cloudflare plan",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#rule-limits`});case 81046:return new m({code:"CF_6002",message:`Invalid Cloudflare expression: ${e.message}`,suggestion:"Check your rule conditions and ensure they use valid Cloudflare Wirefilter syntax",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/expressions`});case 1001:return new m({code:"CF_6021",message:"Zone is suspended and cannot be modified",suggestion:"Contact Cloudflare support to resolve zone suspension issues",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#zone-suspended`});case 1014:case 1015:return new m({code:"CF_6020",message:`Plan limit exceeded: ${e.message}`,suggestion:"Consider upgrading your Cloudflare plan for higher limits",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#plan-limits`});case 1020:return new m({code:"CF_6022",message:"Cloudflare service is currently in maintenance mode",suggestion:"Wait for maintenance to complete and try again. Check Cloudflare status page.",details:{cloudflareCode:e.code,endpoint:e.endpoint,statusPage:"https://www.cloudflarestatus.com/"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#maintenance`});default:let t=e.message.toLowerCase();return t.includes("authentication")||t.includes("invalid token")?(e.status=401,this.handleUnauthorizedError(e)):t.includes("forbidden")||t.includes("access denied")?(e.status=403,this.handleForbiddenError(e)):t.includes("not found")?(e.status=404,this.handleNotFoundError(e)):t.includes("rate limit")?(e.status=429,this.handleRateLimitError(e)):new m({code:"PROV_5002",message:`Cloudflare API error: ${e.message}`,suggestion:"Check the Cloudflare API documentation and your request parameters",details:{cloudflareCode:e.code,endpoint:e.endpoint},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting`})}}};T();var or={defaultTTL:300*1e3,maxEntries:100,enableLogging:!0},At=class{cache=new Map;options;stats={hits:0,misses:0,evictions:0};constructor(e={}){this.options={...or,...e}}get(e){let t=this.cache.get(e);if(!t){this.stats.misses++,this.options.enableLogging&&r.debug(`Cache miss: ${e}`);return}if(Date.now()>t.expiresAt){this.cache.delete(e),this.stats.misses++,this.options.enableLogging&&r.debug(`Cache expired: ${e}`);return}return t.hits++,this.stats.hits++,this.options.enableLogging&&r.debug(`Cache hit: ${e} (${t.hits} total hits)`),t.value}set(e,t,n){this.cache.size>=this.options.maxEntries&&!this.cache.has(e)&&this.evictLeastRecentlyUsed();let o=n??this.options.defaultTTL;this.cache.set(e,{value:t,expiresAt:Date.now()+o,createdAt:Date.now(),hits:0}),this.options.enableLogging&&r.debug(`Cache set: ${e} (TTL: ${o}ms)`)}invalidate(e){let t=this.cache.delete(e);return t&&this.options.enableLogging&&r.debug(`Cache invalidated: ${e}`),t}invalidateByPrefix(e){let t=0;for(let n of this.cache.keys())n.startsWith(e)&&(this.cache.delete(n),t++);return t>0&&this.options.enableLogging&&r.debug(`Cache invalidated ${t} entries with prefix: ${e}`),t}clear(){let e=this.cache.size;this.cache.clear(),this.options.enableLogging&&r.debug(`Cache cleared (${e} entries removed)`)}getStats(){let e=this.stats.hits+this.stats.misses;return{hits:this.stats.hits,misses:this.stats.misses,size:this.cache.size,evictions:this.stats.evictions,hitRate:e>0?this.stats.hits/e:0}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}has(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),!1):!0:!1}evictLeastRecentlyUsed(){let e,t;for(let[n,o]of this.cache.entries()){if(Date.now()>o.expiresAt){this.cache.delete(n),this.stats.evictions++;return}(!t||o.hits<t.hits||o.hits===t.hits&&o.createdAt<t.createdAt)&&(e=n,t=o)}e&&(this.cache.delete(e),this.stats.evictions++,this.options.enableLogging&&r.debug(`Cache evicted LRU entry: ${e}`))}},Oe={zoneInfo:i=>`zone:${i}:info`,rulesets:i=>`zone:${i}:rulesets`,ruleset:(i,e)=>`zone:${i}:ruleset:${e}`,lists:i=>`account:${i}:lists`,listItems:(i,e)=>`account:${i}:list:${e}:items`,credentialValidation:i=>`cred:${i}`,configValidation:i=>`config:${i}`},Fe={ZONE_INFO:600*1e3,RULESETS:120*1e3,RULESET:60*1e3,LISTS:300*1e3,LIST_ITEMS:120*1e3,CREDENTIALS:900*1e3,CONFIG_VALIDATION:300*1e3};T();var rr={maxConnections:6,idleTimeout:3e4,keepAlive:!0},sr={ttl:5e3,maxEntries:100},Ne=class{stats={diffOperations:0,diffTotalDuration:0,earlyExits:0,deduplicatedRequests:0,pooledConnections:0,chunkedOperations:0};poolOptions;dedupOptions;inFlightRequests=new Map;hashCache=new Map;activeConnections=0;connectionQueue=[];constructor(e={},t={}){this.poolOptions={...rr,...e},this.dedupOptions={...sr,...t}}computeRuleHash(e){let t=this.canonicalizeRule(e),n=this.hashCache.get(t);if(n)return n;let o=this.simpleHash(t);return this.hashCache.set(t,o),o}diffRules(e,t){let n=performance.now();if(this.stats.diffOperations++,e.length===0&&t.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-n};if(e===t)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:e.length,duration:performance.now()-n};if(e.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[...t],unchanged:0,duration:performance.now()-n};if(t.length===0)return this.stats.earlyExits++,{toAdd:[...e],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-n};let o=new Map;for(let p of t){let g=p.id||p.name;o.set(g,{rule:p,hash:this.computeRuleHash(p)})}let s=new Map,a=[],l=[],c=0;for(let p of e){let g=p.id||p.name;s.set(g,!0);let h=o.get(g);h?this.computeRuleHash(p)!==h.hash?l.push(p):c++:a.push(p)}let d=[];for(let[p,g]of o)s.has(p)||d.push(g.rule);let u=performance.now()-n;return this.stats.diffTotalDuration+=u,r.debug(`Optimized diff: +${a.length} ~${l.length} -${d.length} =${c} (${u.toFixed(1)}ms)`),{toAdd:a,toUpdate:l,toDelete:d,unchanged:c,duration:u}}diffCloudflareRules(e,t){let n=new Map(t.map(p=>[p.id,p])),o=new Set,s=[],a=[];for(let{rule:p,translated:g}of e){let h=p.id||p.name;o.add(h);let I=n.get(h);I?this.cloudflareRulesEqual(g,I)||a.push(p):s.push(p)}let l=[];for(let[p,g]of n)o.has(p)||l.push(g);let c=new Set(a.map(p=>p.id||p.name)),d=e.map(({rule:p})=>p.id||p.name).filter(p=>n.has(p)),u=t.map(p=>p.id).filter(p=>o.has(p));return d.forEach((p,g)=>{if(u[g]===p||c.has(p))return;let h=e.find(({rule:I})=>(I.id||I.name)===p);h&&(a.push(h.rule),c.add(p))}),{toAdd:s,toUpdate:a,toDelete:l}}cloudflareRulesEqual(e,t){return e.action===t.action&&e.expression===t.expression&&(e.enabled??!0)===(t.enabled??!0)&&(e.description||"")===(t.description||"")&&JSON.stringify(e.ratelimit??null)===JSON.stringify(t.ratelimit??null)&&JSON.stringify(e.action_parameters??null)===JSON.stringify(t.action_parameters??null)}diffIPRules(e,t){let n=performance.now();if(e.length===0&&t.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-n};if(e.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[...t],unchanged:0,duration:performance.now()-n};if(t.length===0)return this.stats.earlyExits++,{toAdd:[...e],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-n};let o=new Map;for(let p of t)o.set(p.ip,p);let s=new Set,a=[],l=[],c=0;for(let p of e){s.add(p.ip);let g=o.get(p.ip);g?p.action!==g.action?l.push(p):c++:a.push(p)}let d=[];for(let[p,g]of o)s.has(p)||d.push(g);let u=performance.now()-n;return{toAdd:a,toUpdate:l,toDelete:d,unchanged:c,duration:u}}async acquireConnection(){if(this.activeConnections<this.poolOptions.maxConnections){this.activeConnections++,this.stats.pooledConnections++;return}return new Promise(e=>{this.connectionQueue.push(()=>{this.activeConnections++,this.stats.pooledConnections++,e()})})}releaseConnection(){this.activeConnections--,this.connectionQueue.length>0&&this.connectionQueue.shift()()}async withConnection(e){await this.acquireConnection();try{return await e()}finally{this.releaseConnection()}}async executePooled(e){if(e.length===0)return[];let t=new Array(e.length),n=[];for(let o=0;o<e.length;o++){let s=o,a=e[s],l=this.withConnection(async()=>{t[s]=await a()});n.push(l)}return await Promise.all(n),t}getConnectionHeaders(){return this.poolOptions.keepAlive?{Connection:"keep-alive","Keep-Alive":`timeout=${Math.floor(this.poolOptions.idleTimeout/1e3)}`}:{}}async deduplicateRequest(e,t){this.cleanupExpiredRequests();let n=this.inFlightRequests.get(e);if(n&&Date.now()-n.createdAt<this.dedupOptions.ttl)return this.stats.deduplicatedRequests++,r.debug(`Request deduplicated: ${e}`),n.promise;let o=t().finally(()=>{this.inFlightRequests.delete(e)});return this.inFlightRequests.set(e,{promise:o,createdAt:Date.now()}),o}static requestKey(e,t,n){let o=[e.toUpperCase(),t];return n&&o.push(n),o.join(":")}cleanupExpiredRequests(){let e=Date.now();for(let[t,n]of this.inFlightRequests)e-n.createdAt>this.dedupOptions.ttl&&this.inFlightRequests.delete(t);if(this.inFlightRequests.size>this.dedupOptions.maxEntries){let t=Array.from(this.inFlightRequests.entries());t.sort((o,s)=>o[1].createdAt-s[1].createdAt);let n=t.slice(0,t.length-this.dedupOptions.maxEntries);for(let[o]of n)this.inFlightRequests.delete(o)}}async processInChunks(e,t,n){if(e.length===0)return[];this.stats.chunkedOperations++;let o=[],s=Math.ceil(e.length/t);e.length>t&&r.debug(`Processing ${e.length} items in ${s} chunks of ${t}`);for(let a=0;a<e.length;a+=t){let l=e.slice(a,a+t),c=Math.floor(a/t),d=await n(l,c);o.push(...d)}return o}estimateMemoryUsage(e){if(e.length===0)return 0;let t=Math.min(10,e.length),n=0;for(let s=0;s<t;s++)n+=JSON.stringify(e[s]).length*2;let o=n/t;return Math.ceil(o*e.length)}getOptimalChunkSize(e,t=500){let o=Math.max(10,Math.floor(1048576/t)),s=Math.min(o,100);return e<=s?e:s}getStats(){return{...this.stats}}resetStats(){this.stats={diffOperations:0,diffTotalDuration:0,earlyExits:0,deduplicatedRequests:0,pooledConnections:0,chunkedOperations:0}}clearCaches(){this.hashCache.clear(),this.inFlightRequests.clear()}getActiveConnections(){return this.activeConnections}getPendingConnections(){return this.connectionQueue.length}getInFlightCount(){return this.inFlightRequests.size}canonicalizeRule(e){let t={action:e.action,conditions:e.conditions.map(n=>({field:n.field,key:n.key,negated:n.negated,operator:n.operator,value:n.value})).sort((n,o)=>`${n.field}:${n.operator}`.localeCompare(`${o.field}:${o.operator}`)),enabled:e.enabled,name:e.name};return e.conditionLogic&&(t.conditionLogic=e.conditionLogic),e.description&&(t.description=e.description),e.priority!==void 0&&(t.priority=e.priority),JSON.stringify(t)}simpleHash(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return t.toString(36)}};var Ye=class extends Pe{apiToken;zoneId;accountId;cache;optimizer;constructor(e,t,n){super("https://api.cloudflare.com/client/v4","cloudflare"),this.apiToken=e,this.zoneId=t,this.accountId=n,this.cache=new At({enableLogging:!0}),this.optimizer=new Ne}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}invalidateRulesetCache(){this.cache.invalidateByPrefix(`zone:${this.zoneId}`)}invalidateListCache(){this.accountId&&this.cache.invalidateByPrefix(`account:${this.accountId}`)}getAuthHeaders(){return{Authorization:`Bearer ${this.apiToken}`,...this.optimizer.getConnectionHeaders()}}getOptimizer(){return this.optimizer}async listRulesets(){r.debug(`Fetching rulesets for zone ${this.zoneId}`);let e=Oe.rulesets(this.zoneId),t=this.cache.get(e);if(t)return t;let n=Ne.requestKey("GET",`/zones/${this.zoneId}/rulesets`);return this.optimizer.deduplicateRequest(n,async()=>{try{let o=await this.get(`/zones/${this.zoneId}/rulesets`);if(!o.success)throw K.handleApiResponse(o,`/zones/${this.zoneId}/rulesets`);if(!Array.isArray(o.result))return r.warn("Malformed API response: expected array of rulesets, got:",typeof o.result),[];let s=o.result.filter(a=>!a||typeof a!="object"?(r.warn("Skipping malformed ruleset object:",a),!1):!a.id||!a.name?(r.warn("Skipping ruleset with missing required fields:",{id:a.id,name:a.name}),!1):!0);return s.length!==o.result.length&&r.warn(`Filtered out ${o.result.length-s.length} malformed rulesets`),this.cache.set(e,s,Fe.RULESETS),s}catch(o){throw o instanceof Error&&!o.code?K.handleNetworkError(o,"listing rulesets"):o}})}async getRulesets(){return this.listRulesets()}async getRuleset(e){r.debug(`Fetching ruleset ${e}`);let t=Oe.ruleset(this.zoneId,e),n=this.cache.get(t);if(n)return n;let o=Ne.requestKey("GET",`/zones/${this.zoneId}/rulesets/${e}`);return this.optimizer.deduplicateRequest(o,async()=>{try{let s=await this.get(`/zones/${this.zoneId}/rulesets/${e}`);if(!s.success)throw K.handleApiResponse(s,`/zones/${this.zoneId}/rulesets/${e}`);if(!s.result||typeof s.result!="object")throw K.handleValidationError("ruleset","Invalid ruleset data received from API",s.result);let a=s.result;if(!a.id||!a.name)throw K.handleValidationError("ruleset","Ruleset missing required fields (id, name)",a);Array.isArray(a.rules)||(r.warn(`Ruleset ${e} has invalid rules array, initializing as empty`),a.rules=[]);let l=a.rules.filter(c=>!c||typeof c!="object"?(r.warn(`Skipping malformed rule in ruleset ${e}:`,c),!1):!c.id||!c.expression||!c.action?(r.warn(`Skipping rule with missing required fields in ruleset ${e}:`,{id:c.id,expression:c.expression,action:c.action}),!1):!0);return l.length!==a.rules.length&&(r.warn(`Filtered out ${a.rules.length-l.length} malformed rules from ruleset ${e}`),a.rules=l),this.cache.set(t,a,Fe.RULESET),a}catch(s){throw s instanceof Error&&!s.code?K.handleNetworkError(s,"fetching ruleset"):s}})}async createRuleset(e){r.debug(`Creating ruleset: ${e.name}`);let t=await this.post(`/zones/${this.zoneId}/rulesets`,e);if(!t.success){let n=t.errors.map(o=>o.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets`,t.errors[0]?.code||0,n)}return r.info(`Created ruleset: ${t.result.name} (${t.result.id})`),this.invalidateRulesetCache(),t.result}async updateRuleset(e,t){r.debug(`Updating ruleset ${e}`);let n=await this.put(`/zones/${this.zoneId}/rulesets/${e}`,t);if(!n.success){let o=n.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}`,n.errors[0]?.code||0,o)}return r.info(`Updated ruleset to version ${n.result.version}`),this.invalidateRulesetCache(),n.result}async deleteRuleset(e){r.debug(`Deleting ruleset ${e}`);let t=await this.delete(`/zones/${this.zoneId}/rulesets/${e}`);if(!t.success){let n=t.errors.map(o=>o.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}`,t.errors[0]?.code||0,n)}r.info(`Deleted ruleset ${e}`),this.invalidateRulesetCache()}async createRule(e,t){r.debug(`Adding rule to ruleset ${e}`);let n=await this.post(`/zones/${this.zoneId}/rulesets/${e}/rules`,t);if(!n.success){let o=n.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules`,n.errors[0]?.code||0,o)}return r.info(`Added rule to ruleset ${e}`),this.invalidateRulesetCache(),n.result}async updateRule(e,t,n){r.debug(`Updating rule ${t} in ruleset ${e}`);let o=await this.patch(`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,n);if(!o.success){let s=o.errors.map(a=>a.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,o.errors[0]?.code||0,s)}return r.info(`Updated rule ${t}`),this.invalidateRulesetCache(),o.result}async deleteRule(e,t){r.debug(`Deleting rule ${t} from ruleset ${e}`);let n=await this.delete(`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`);if(!n.success){let o=n.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,n.errors[0]?.code||0,o)}return r.info(`Deleted rule ${t}`),this.invalidateRulesetCache(),n.result}async getOrCreateFirewallRuleset(){r.debug("Looking for existing custom firewall ruleset");let t=(await this.listRulesets()).find(n=>n.kind==="custom"&&n.phase==="http_request_firewall_custom");return t?(r.debug(`Found existing ruleset: ${t.id}`),t):(r.info("No existing custom firewall ruleset found, creating new one"),this.createRuleset({name:"Doorman Custom Firewall Rules",kind:"custom",phase:"http_request_firewall_custom",description:"Custom firewall rules managed by Doorman",rules:[]}))}async verifyCredentials(){let e=(0,un.createHash)("sha256").update(this.apiToken).digest("hex").slice(0,8),t=Oe.credentialValidation(e),n=this.cache.get(t);if(n!==void 0)return r.debug("Using cached credential validation result"),n;try{return r.debug("Verifying Cloudflare credentials"),await this.listRulesets(),r.info("Cloudflare credentials verified successfully"),this.cache.set(t,!0,Fe.CREDENTIALS),!0}catch(o){if(r.error(`Cloudflare credential verification failed: ${o}`),o instanceof Error){let s=o.message.toLowerCase();if(s.includes("unauthorized")||s.includes("invalid token"))throw K.handleCredentialError("token");if(s.includes("forbidden")||s.includes("access denied"))throw K.handleCredentialError("zone",this.zoneId);if(s.includes("not found"))throw K.handleCredentialError("zone",this.zoneId)}return!1}}async getZoneInfo(){let e=Oe.zoneInfo(this.zoneId),t=this.cache.get(e);if(t)return t;let n=await this.get(`/zones/${this.zoneId}`);if(!n.success){let o=n.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/zones/${this.zoneId}`,n.errors[0]?.code||0,o)}return this.cache.set(e,n.result,Fe.ZONE_INFO),n.result}async listLists(){if(r.debug("Fetching Cloudflare Lists"),!this.accountId)return r.warn("Account ID not provided, Lists API requires account-level access"),[];let e=Oe.lists(this.accountId),t=this.cache.get(e);if(t)return t;let n=await this.get(`/accounts/${this.accountId}/rules/lists`);if(!n.success){let o=n.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,n.errors[0]?.code||0,o)}return this.cache.set(e,n.result,Fe.LISTS),n.result}async getList(e){if(r.debug(`Fetching List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let t=await this.get(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let n=t.errors.map(o=>o.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,t.errors[0]?.code||0,n)}return t.result}async createList(e){if(r.debug(`Creating List: ${e.name}`),!this.accountId)throw B.accountIdRequired("Lists API");let t=await this.post(`/accounts/${this.accountId}/rules/lists`,e);if(!t.success){let n=t.errors.map(o=>o.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,t.errors[0]?.code||0,n)}return r.info(`Created List: ${t.result.name} (${t.result.id})`),this.invalidateListCache(),t.result}async updateList(e,t){if(r.debug(`Updating List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let n=await this.put(`/accounts/${this.accountId}/rules/lists/${e}`,t);if(!n.success){let o=n.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,n.errors[0]?.code||0,o)}return r.info(`Updated List ${e}`),this.invalidateListCache(),n.result}async deleteList(e){if(r.debug(`Deleting List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let t=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let n=t.errors.map(o=>o.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,t.errors[0]?.code||0,n)}r.info(`Deleted List ${e}`),this.invalidateListCache()}async getListItems(e){if(r.debug(`Fetching items from List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let t=Oe.listItems(this.accountId,e),n=this.cache.get(t);if(n)return n;let o=Ne.requestKey("GET",`/accounts/${this.accountId}/rules/lists/${e}/items`);return this.optimizer.deduplicateRequest(o,async()=>{let s=await this.fetchAllListItemPages(e);return this.cache.set(t,s,Fe.LIST_ITEMS),s})}async fetchAllListItemPages(e){let t=[],n=1;for(;;){let o=await this.get(`/accounts/${this.accountId}/rules/lists/${e}/items?page=${n}`);if(!o.success){let a=o.errors.map(l=>l.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,o.errors[0]?.code||0,a)}t.push(...o.result);let s=o.result_info?.total_pages??1;if(o.result.length===0||n>=s)break;n++}return t}async addListItems(e,t){if(r.debug(`Adding ${t.items.length} items to List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let n=await this.post(`/accounts/${this.accountId}/rules/lists/${e}/items`,t.items);if(!n.success){let o=n.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,n.errors[0]?.code||0,o)}return r.info(`Added ${t.items.length} items to List ${e}`),this.invalidateListCache(),n.result}async removeListItems(e,t){if(r.debug(`Removing ${t.items.length} items from List ${e}`),!this.accountId)throw B.accountIdRequired("Lists API");let n=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}/items`,{body:JSON.stringify(t)});if(!n.success){let o=n.errors.map(s=>s.message).join(", ");throw G.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,n.errors[0]?.code||0,o)}r.info(`Removed ${t.items.length} items from List ${e}`),this.invalidateListCache()}async getOrCreateIPBlocklist(){if(r.debug("Looking for existing Doorman IP blocklist"),!this.accountId)throw r.warn("Account ID not provided, cannot use Lists for IP blocking"),K.handleCredentialError("account");try{let t=(await this.listLists()).find(n=>n.name==="Doorman IP Blocklist"&&n.kind==="ip");return t?(r.debug(`Found existing IP blocklist: ${t.id}`),t):(r.info("No existing IP blocklist found, creating new one"),this.createList({name:"Doorman IP Blocklist",description:"IP addresses blocked by Doorman",kind:"ip"}))}catch(e){throw e instanceof Error&&!e.code?K.handleNetworkError(e,"managing IP blocklist"):e}}};var Je=require("net");T();var ut=class i extends ke{name="cloudflare";client;optimizer;useListsForIPs;constructor(e,t,n){super(),this.client=new Ye(e,t,n),this.optimizer=this.client.getOptimizer(),this.useListsForIPs=!!n,this.useListsForIPs?r.debug("Lists API enabled for IP blocking (account ID provided)"):r.debug("Lists API disabled - will use individual IP rules (no account ID)")}async fetchConfig(e){r.info("Fetching configuration from Cloudflare");try{let t=await this.client.getOrCreateFirewallRuleset(),n=[],o=[],s=[],a=[],l=50,c=t.rules.length;c>100&&r.info(`Processing ${c} rules in batches of ${l} to optimize memory usage`);for(let d=0;d<c;d+=l){let u=t.rules.slice(d,d+l);r.debug(`Processing rules batch ${Math.floor(d/l)+1}/${Math.ceil(c/l)} (${u.length} rules)`);for(let p of u)try{if(!p||typeof p!="object"){a.push(`Skipped malformed rule at index ${d}: not an object`);continue}if(!p.id||!p.expression||!p.action){a.push(`Skipped rule with missing required fields: ${JSON.stringify({id:p.id,expression:!!p.expression,action:p.action})}`);continue}if(this.isListBasedIPRule(p))continue;if(this.isIPBlockingRule(p)){let g=this.cloudflareRuleToIPRule(p);o.push(g)}else{let g=k.cloudflareToUnified(p);n.push(g.result),g.warnings.length>0&&g.warnings.forEach(h=>{let{TranslationWarningSystem:I}=(fe(),ye(De)),R=I.formatWarning(h);s.push(R)})}}catch(g){let h=`Failed to process rule ${p?.id||"unknown"}: ${g instanceof Error?g.message:String(g)}`;r.warn(h),a.push(h)}c>200&&d+l<c&&await new Promise(p=>setTimeout(p,10))}if(a.length>0&&(r.warn(`Encountered ${a.length} rule processing errors:`),a.slice(0,5).forEach(d=>r.warn(` - ${d}`)),a.length>5&&r.warn(` ... and ${a.length-5} more errors`)),this.useListsForIPs)try{let d=await this.client.getOrCreateIPBlocklist(),u=await this.client.getListItems(d.id);for(let p of u)p.ip&&o.push({id:p.id,ip:p.ip,notes:p.comment,action:"deny"});r.debug(`Fetched ${u.length} IPs from List`)}catch(d){this.handleListsAPIFallback(d,"fetching IPs from List")}else o.length>10&&r.warn(`\u26A0\uFE0F Large IP list detected (${o.length} IPs) without Lists API. Consider providing CLOUDFLARE_ACCOUNT_ID for better performance.`);return s.length>0&&(r.warn("Translation warnings detected:"),s.forEach(d=>r.warn(d)),s.length>3&&r.warn(`
31
+ \u{1F4CA} Summary: ${s.length} translation warnings detected. Review each warning above for specific guidance.`)),{version:"2.0",provider:"cloudflare",providers:{cloudflare:{zoneId:this.client.zoneId,accountId:this.client.accountId}},rules:n,ips:o,metadata:{version:parseInt(t.version,10),updatedAt:t.last_updated}}}catch(t){throw t instanceof Error&&!("code"in t)?K.handleNetworkError(t,"fetching configuration"):t}}async syncRules(e,t){r.info(`Syncing ${e.rules.length} rules to Cloudflare${t?.dryRun?" (dry run)":""}`);let{OperationSafety:n}=(Tt(),ye(Et)),o=await n.performDryRunValidation(e,"sync rules",async I=>await this.getChanges(I));if(!o.valid)throw new Error(`Dry-run validation failed: ${o.issues.join(", ")}`);if(t?.dryRun)return{success:!0,rulesAdded:o.changes.rulesToAdd.length,rulesUpdated:o.changes.rulesToUpdate.length,rulesDeleted:o.changes.rulesToDelete.length,ipsAdded:o.changes.ipsToAdd?.length||0,ipsUpdated:o.changes.ipsToUpdate?.length||0,ipsDeleted:o.changes.ipsToDelete?.length||0,warnings:o.warnings};let s=n.assessOperationRisk(o.changes,e);if(!await n.confirmDestructiveOperation({operation:"sync rules",target:`Cloudflare zone ${this.client.zoneId}`,changes:o.changes,riskLevel:s,skipConfirmation:t?.force||!1,dryRun:t?.dryRun||!1,allowDeletions:t?.allowDeletions||!1}))throw new Error("Operation cancelled by user");let l=await this.client.getOrCreateFirewallRuleset(),c=[];for(let I of dt(e.rules)){let R=k.unifiedToCloudflare(I);c.push(R.result),R.warnings.length>0&&R.warnings.forEach(N=>{let{TranslationWarningSystem:Z}=(fe(),ye(De)),W=Z.formatWarning(N);r.warn(W)})}let d=0,u=0,p=0;if(this.useListsForIPs&&e.ips&&e.ips.length>0){let I=new Set;try{let R=await this.client.getOrCreateIPBlocklist(),N=await this.client.getListItems(R.id),Z=new Set(N.map(_=>_.ip));Z.forEach(_=>_&&I.add(_));let W=new Set(e.ips.map(_=>_.ip)),ue=e.ips.filter(_=>!Z.has(_.ip));ue.length>0&&(await this.client.addListItems(R.id,{items:ue.map(_=>({ip:_.ip,comment:_.notes||_.hostname||"Blocked by Doorman"}))}),d=ue.length,ue.forEach(_=>I.add(_.ip)),r.info(`Added ${d} IPs to List`));let me=N.filter(_=>_.ip&&!W.has(_.ip));me.length>0&&(await this.client.removeListItems(R.id,{items:me.map(_=>({id:_.id}))}),p=me.length,me.forEach(_=>_.ip&&I.delete(_.ip)),r.info(`Removed ${p} IPs from List`));let _e=`ip.src in $${R.name.replace(/\s+/g,"_").toLowerCase()}`;c.push({id:"rule_doorman_ip_list",action:"block",expression:_e,description:"Block IPs in Doorman IP Blocklist",enabled:!0})}catch(R){this.handleListsAPIFallback(R,"syncing IPs via List");let N=e.ips.filter(Z=>!I.has(Z.ip));if(N.length>0){r.info(`\u{1F504} Falling back to individual IP rules for ${N.length} IPs`);for(let Z of N){let W=k.unifiedIPToCloudflare(Z);c.push(W)}d=N.length}else r.info("All IPs were already confirmed in the List before the failure; no fallback rules needed.");N.length>50&&r.warn(`\u26A0\uFE0F Performance warning: Using ${N.length} individual IP rules instead of Lists. This may impact rule processing speed and count against your rule limit.`)}}else if(e.ips&&e.ips.length>0){r.info(`\u{1F4DD} Using individual IP rules for ${e.ips.length} IPs (Lists API not available)`),e.ips.length>20&&r.warn(`\u26A0\uFE0F Large IP list detected (${e.ips.length} IPs) without Lists API. Consider providing CLOUDFLARE_ACCOUNT_ID for better performance and rule efficiency.`);for(let I of e.ips){let R=k.unifiedIPToCloudflare(I);c.push(R)}d=e.ips.length}let g=await this.client.updateRuleset(l.id,{rules:c}),h={success:!0,rulesAdded:o.changes.rulesToAdd.length,rulesUpdated:o.changes.rulesToUpdate.length,rulesDeleted:o.changes.rulesToDelete.length,ipsAdded:d,ipsUpdated:u,ipsDeleted:p,version:parseInt(g.version,10),warnings:o.warnings?.length?o.warnings:void 0};return this.logSyncStats(h),h}async getChanges(e){let t=await this.client.getOrCreateFirewallRuleset(),n=t.rules.filter(c=>c&&c.id&&c.expression&&c.action&&!this.isListBasedIPRule(c)&&!this.isIPBlockingRule(c)),o=dt(e.rules).map(c=>({rule:c,translated:k.unifiedToCloudflare(c).result})),s=this.optimizer.diffCloudflareRules(o,n),a=s.toDelete.map(c=>k.cloudflareToUnified(c).result),l={toAdd:[],toUpdate:[],toDelete:[]};if(e.ips){let c=await this.fetchRemoteIPRulesForDiff(t.rules);l=this.optimizer.diffIPRules(e.ips,c)}return{rulesToAdd:s.toAdd,rulesToUpdate:s.toUpdate,rulesToDelete:a,ipsToAdd:l.toAdd,ipsToUpdate:l.toUpdate,ipsToDelete:l.toDelete,version:parseInt(t.version,10),hasChanges:s.toAdd.length>0||s.toUpdate.length>0||a.length>0||l.toAdd.length>0||l.toUpdate.length>0||l.toDelete.length>0}}async fetchRemoteIPRulesForDiff(e){let t=[];for(let n of e)n&&n.id&&n.expression&&n.action&&this.isIPBlockingRule(n)&&t.push(this.cloudflareRuleToIPRule(n));if(this.useListsForIPs)try{let n=await this.client.getOrCreateIPBlocklist(),o=await this.client.getListItems(n.id);for(let s of o)s.ip&&t.push({id:s.id,ip:s.ip,notes:s.comment,action:"deny"})}catch(n){this.handleListsAPIFallback(n,"fetching IPs from List")}return t}getSupportedFeatures(){return{supportsCustomRules:!0,supportsIPBlocking:!0,supportsRateLimiting:!0,supportsManagedRules:!0,supportsGeoBlocking:!0,supportsRedirect:!0,supportsChallenge:!0,maxRules:125}}validateConfig(e){let t=super.validateConfig(e),n=[...t.errors],o=[...t.warnings];if(e&&e.rules){let s=this.getSupportedFeatures();if(s.maxRules&&e.rules.length>s.maxRules){let a=B.ruleLimitExceeded(e.rules.length,s.maxRules);n.push({path:"rules",message:a.message,code:a.code})}if(e.rules.forEach((a,l)=>{try{if(!a.conditions||a.conditions.length===0){let c=B.ruleNoConditions(a.name||`Rule ${l+1}`);n.push({path:`rules[${l}]`,message:c.message,code:c.code})}if(a.action.type==="rate_limit"&&a.action.rateLimit){let c=a.action.rateLimit;if(c.requests<1){let d=B.invalidRateLimit(a.name||`Rule ${l+1}`,"requests must be at least 1");n.push({path:`rules[${l}].action.rateLimit.requests`,message:d.message,code:d.code})}if(!c.window.match(/^\d+[smhd]$/)){let d=B.invalidWindowFormat(c.window);n.push({path:`rules[${l}].action.rateLimit.window`,message:d.message,code:d.code})}if(c.characteristics&&c.characteristics.length===0){let d=B.emptyCharacteristics(a.name||`Rule ${l+1}`);o.push({path:`rules[${l}].action.rateLimit.characteristics`,message:d.message,code:d.code})}if(c.mitigationTimeout!==void 0&&c.mitigationTimeout<60){let d=B.shortMitigationTimeout(c.mitigationTimeout);o.push({path:`rules[${l}].action.rateLimit.mitigationTimeout`,message:d.message,code:d.code})}}if(a.action.type==="redirect"&&a.action.redirect){let c=a.action.redirect;if(c.location)try{new URL(c.location)}catch{if(!c.location.startsWith("/")){let d=B.invalidRedirectUrl(c.location);n.push({path:`rules[${l}].action.redirect.location`,message:d.message,code:d.code})}}else{let d=B.redirectNoLocation(a.name||`Rule ${l+1}`);n.push({path:`rules[${l}].action.redirect.location`,message:d.message,code:d.code})}}}catch(c){n.push({path:`rules[${l}]`,message:`Validation error: ${c instanceof Error?c.message:String(c)}`,code:"CLOUDFLARE_VALIDATION_ERROR"})}}),e.ips&&(e.ips.forEach((a,l)=>{try{if(!i.isValidIPOrCIDR(a.ip)){let c=B.invalidIP(a.ip);n.push({path:`ips[${l}].ip`,message:c.message,code:c.code})}}catch(c){n.push({path:`ips[${l}]`,message:`IP validation error: ${c instanceof Error?c.message:String(c)}`,code:"CLOUDFLARE_IP_VALIDATION_ERROR"})}}),!this.useListsForIPs&&e.ips.length>50)){let a=B.largeIPList(e.ips.length);o.push({path:"ips",message:a.message,code:a.code})}}return{valid:n.length===0,errors:n,warnings:o}}getHealthScore(e){let t=super.getHealthScore(e),n=[...t.issues],o=this.getSupportedFeatures();return o.maxRules&&e.rules.length>o.maxRules*.8&&n.push({severity:"warning",category:"limits",message:`Approaching Cloudflare rule limit (${e.rules.length}/${o.maxRules})`,suggestion:"Consider consolidating rules or upgrading plan"}),{...t,issues:n}}async verifyCredentials(){return this.client.verifyCredentials()}getCacheStats(){return this.client.getCacheStats()}getOptimizerStats(){return this.optimizer.getStats()}clearCache(){this.client.clearCache(),this.optimizer.clearCaches()}static isValidIPOrCIDR(e){let[t,n,...o]=e.split("/");if(o.length>0||!t)return!1;if(n===void 0)return(0,Je.isIPv4)(t)||(0,Je.isIPv6)(t);if(!/^\d+$/.test(n))return!1;let s=Number(n);return(0,Je.isIPv4)(t)?s<=32:(0,Je.isIPv6)(t)?s<=128:!1}isListBasedIPRule(e){return/ip\.src in \$/.test(e.expression.trim())}isIPBlockingRule(e){if(e.action!=="block"&&e.action!=="allow")return!1;let t=e.expression.trim();return i.IP_EQ_PATTERN.test(t)||i.IP_IN_SET_PATTERN.test(t)}static IP_EQ_PATTERN=/^ip\.src eq ([0-9a-fA-F:.]+)$/;static IP_IN_SET_PATTERN=/^ip\.src in \{([0-9a-fA-F:./]+)\}$/;cloudflareRuleToIPRule(e){let t=e.expression.trim(),o=(t.match(i.IP_EQ_PATTERN)||t.match(i.IP_IN_SET_PATTERN))?.[1]||"",a=e.description?.match(/\(([^)]+)\)/)?.[1];return{id:e.id,ip:o,hostname:a,notes:e.description,action:e.action==="allow"?"allow":"deny"}}handleListsAPIFallback(e,t){if(e instanceof Error){let n=e.message.toLowerCase();n.includes("account")?(r.warn("\u{1F6AB} Lists API unavailable: Account ID not provided or invalid. Falling back to individual IP rules."),r.info(`\u{1F4A1} To enable Lists API for better performance with large IP lists:
31
32
  \u2022 Set CLOUDFLARE_ACCOUNT_ID in your environment
32
33
  \u2022 Ensure your API token has Account:Read permissions
33
- \u2022 Find your Account ID in the Cloudflare dashboard sidebar`)):o.includes("permission")||o.includes("forbidden")?(r.warn(`\u{1F6AB} Lists API permission denied: Insufficient permissions for ${t}. Falling back to individual IP rules.`),r.info(`\u{1F4A1} To fix Lists API permissions:
34
+ \u2022 Find your Account ID in the Cloudflare dashboard sidebar`)):n.includes("permission")||n.includes("forbidden")?(r.warn(`\u{1F6AB} Lists API permission denied: Insufficient permissions for ${t}. Falling back to individual IP rules.`),r.info(`\u{1F4A1} To fix Lists API permissions:
34
35
  \u2022 Ensure your API token has Account:Read permissions
35
36
  \u2022 Verify the account ID is correct
36
- \u2022 Check token permissions in Cloudflare dashboard`)):o.includes("not found")?(r.warn(`\u{1F6AB} Lists API resource not found during ${t}. Falling back to individual IP rules.`),r.info("\u{1F4A1} This may be temporary - the List will be recreated on next sync if Lists API is available.")):o.includes("rate limit")||o.includes("quota")?(r.warn(`\u{1F6AB} Lists API rate limited during ${t}. Falling back to individual IP rules.`),r.info("\u{1F4A1} Lists API rate limit reached. Individual rules will be used this time. Consider retrying later or upgrading your Cloudflare plan.")):(r.warn(`\u{1F6AB} Lists API error during ${t}: ${e.message}. Falling back to individual IP rules.`),r.info("\u{1F4A1} Lists API temporarily unavailable. Using individual IP rules as fallback. Check Cloudflare status if this persists."))}else r.warn(`\u{1F6AB} Unknown Lists API error during ${t}. Falling back to individual IP rules.`)}};var Qe=class{static create(e,t,o){let n=e||process.env.CLOUDFLARE_API_TOKEN,s=t||process.env.CLOUDFLARE_ZONE_ID,a=o||process.env.CLOUDFLARE_ACCOUNT_ID;if(!n)throw new Error("Cloudflare API token is required. Set CLOUDFLARE_API_TOKEN environment variable or pass as parameter.");if(!s)throw new Error("Cloudflare Zone ID is required. Set CLOUDFLARE_ZONE_ID environment variable or pass as parameter.");return new ct(n,s,a)}static fromEnv(){return this.create()}static fromConfig(e){return this.create(e.apiToken,e.zoneId,e.accountId)}};T();T();var ao=process.env.DOORMAN_FASTLY_API_BASE_URL||"https://api.fastly.com",dt="doorman-managed-deny",ut="doorman-managed-allow",Xe=class extends Ae{constructor(t,o){super(ao,"fastly");this.workspaceId=t;this.apiToken=o}workspaceId;apiToken;getAuthHeaders(){return{"Fastly-Key":this.apiToken}}workspacePath(...t){return["/ngwaf/v1/workspaces",this.workspaceId,...t].join("/")}async fetchRules(){return(await this.get(this.workspacePath("rules"))).data}async createRule(t){return this.post(this.workspacePath("rules"),t)}async updateRule(t,o){return this.patch(this.workspacePath("rules",t),o)}async deleteRule(t){await this.delete(this.workspacePath("rules",t))}async fetchLists(){return(await this.get(this.workspacePath("lists"))).data}async createList(t,o){return this.post(this.workspacePath("lists"),{name:t,type:"ip",description:"Managed by doorman \u2014 do not edit entries directly, they will be overwritten on the next sync.",entries:o})}async updateListEntries(t,o){return this.patch(this.workspacePath("lists",t),{entries:o})}async findList(t){return(await this.fetchLists()).find(n=>n.name===t&&n.type==="ip")??null}async getOrCreateList(t){let o=await this.findList(t);return o||(r.debug(`Creating Fastly list "${t}" in workspace ${this.workspaceId}`),this.createList(t,[]))}async fetchWorkspace(){return this.get(this.workspacePath())}async verifyCredentials(){try{return await this.fetchWorkspace(),!0}catch(t){return r.debug("Credential verification failed:",t),!1}}};T();var et=class extends Pe{constructor(t){super();this.client=t}client;name="fastly";async fetchConfig(){try{r.debug("Fetching Fastly Next-Gen WAF configuration");let[t,o,n]=await Promise.all([this.client.fetchRules(),this.client.findList(dt),this.client.findList(ut)]),s=this.translateFastlyRules(t),a=[...k.fastlyListEntriesToUnified(o?.entries??[],"deny"),...k.fastlyListEntriesToUnified(n?.entries??[],"allow")];return{version:"2.0",provider:"fastly",providers:{fastly:{workspaceId:this.client.workspaceId}},rules:s,ips:a}}catch(t){throw r.error("Error fetching Fastly configuration:",t),new Error("Failed to fetch Fastly Next-Gen WAF configuration")}}translateFastlyRules(t){let o=[];for(let n of t){if(n.type!=="request"&&n.type!=="rate_limit"){r.debug(`Skipping Fastly rule ${n.id} \u2014 type "${n.type}" is not a request/rate_limit rule doorman manages`);continue}let s=k.fastlyToUnified(n);s.warnings.length>0&&s.warnings.forEach(a=>{let{TranslationWarningSystem:l}=(fe(),ye(De));r.warn(`Rule ${n.description||n.id}:
37
- ${l.formatWarning(a)}`)}),o.push(s.result)}return o}async syncRules(t,o={}){let{dryRun:n=!1}=o;try{let{OperationSafety:s}=(bt(),ye(vt)),a=await s.performDryRunValidation(t,"sync rules",async v=>this.getChanges(v));if(!a.valid)throw new Error(`Dry-run validation failed: ${a.issues.join(", ")}`);let l=a.changes,{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u}=l,p=l.ipsToAdd||[],g=l.ipsToDelete||[];if(n)return r.info("Dry run mode. The following changes would be made:"),r.info(`Custom Rules - Add: ${c.length}, Update: ${d.length}, Delete: ${u.length}`),r.info(`IP Rules - Add: ${p.length}, Delete: ${g.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,warnings:a.warnings};let h=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Fastly workspace ${this.client.workspaceId}`,changes:l,riskLevel:h,skipConfirmation:o.force||!1,dryRun:!1,allowDeletions:o.allowDeletions||!1}))throw new Error("Operation cancelled by user");let R=[];Rt(t.rules)&&R.push("Rule `priority` has no effect on Fastly: Next-Gen WAF rules are evaluated independently and have no API-exposed ordering concept to honour.");let N=c.map(v=>({rule:v,translated:k.unifiedToFastly(v)})),H=d.map(v=>({rule:v,translated:k.unifiedToFastly(v)})),W=[],ue=(v,V)=>`${v}: ${V instanceof Error?V.message:String(V)}`,me=[],_e=[],_=[],Ce=[];for(let v of u)if(v.id)try{r.debug(`Deleting Fastly rule: ${v.id}`),await this.client.deleteRule(v.id),_.push(v.id)}catch(V){r.error(`Failed to delete Fastly rule ${v.id}:`,V),W.push(ue(`Failed to delete rule ${v.id}`,V))}for(let{rule:v,translated:V}of N){let ie=V.result;try{r.debug(`Adding new Fastly rule: ${ie.description}`);let ae=await this.client.createRule(ie);me.push(ae),Ce.push({oldId:v.id||void 0,newId:ae.id,name:ie.description})}catch(ae){r.error(`Failed to add Fastly rule "${ie.description}":`,ae),W.push(ue(`Failed to add rule "${ie.description}"`,ae))}}for(let{rule:v,translated:V}of H)if(v.id)try{r.debug(`Updating Fastly rule: ${v.id}`);let ie=await this.client.updateRule(v.id,V.result);_e.push(ie)}catch(ie){r.error(`Failed to update Fastly rule ${v.id}:`,ie),W.push(ue(`Failed to update rule ${v.id}`,ie))}let ve=0,be=0,We=t.ips||[],{result:Se,warnings:je}=k.unifiedIPsToFastlyEntries(We);je.forEach(v=>R.push(v.message));try{for(let[v,V]of[[dt,Se.denyEntries],[ut,Se.allowEntries]]){let ae=(await this.client.findList(v))?.entries??[],it=V.filter(f=>!ae.includes(f)),ot=ae.filter(f=>!V.includes(f));if(it.length===0&&ot.length===0)continue;let Ee=await this.client.getOrCreateList(v);await this.client.updateListEntries(Ee.id,V),ve+=it.length,be+=ot.length}}catch(v){r.error("Failed to sync Fastly IP lists:",v),W.push(ue("Failed to sync IP lists",v))}return r.debug(`Custom Rules: Added: ${me.length}, Updated: ${_e.length}, Deleted: ${_.length}`),r.debug(`IP Rules: Added: ${ve}, Deleted: ${be}`),{success:W.length===0,rulesAdded:me.length,rulesUpdated:_e.length,rulesDeleted:_.length,ipsAdded:ve,ipsUpdated:0,ipsDeleted:be,idRemappings:Ce.length>0?Ce:void 0,errors:W.length>0?W:void 0,warnings:R.length>0?R:void 0}}catch(s){throw r.error("Error during sync:",s),new Error(`Failed to synchronize firewall rules: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async getChanges(t){let o=Le.safeParse(t);if(!o.success)throw new Error(`Invalid firewall configuration: ${o.error.message}`);try{r.debug("Fetching existing Fastly configuration");let[n,s,a]=await Promise.all([this.client.fetchRules(),this.client.findList(dt),this.client.findList(ut)]),l=this.translateFastlyRules(n),{toAdd:c,toUpdate:d,toDelete:u}=this.diffRules(t.rules,l),p=s?.entries??[],g=a?.entries??[],h=[...k.fastlyListEntriesToUnified(p,"deny"),...k.fastlyListEntriesToUnified(g,"allow")],{ipsToAdd:I,ipsToDelete:R}=this.diffIPs(t.ips||[],h);return{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u,ipsToAdd:I,ipsToUpdate:[],ipsToDelete:R,hasChanges:c.length>0||d.length>0||u.length>0||I.length>0||R.length>0}}catch(n){throw r.error("Error fetching existing Fastly configuration:",n),new Error("Failed to fetch existing Fastly configuration")}}getSupportedFeatures(){return{supportsCustomRules:!0,supportsIPBlocking:!0,supportsRateLimiting:!0,supportsManagedRules:!1,supportsGeoBlocking:!0,supportsRedirect:!0,supportsChallenge:!0}}async verifyCredentials(){return this.client.verifyCredentials()}validateConfig(t){let o=super.validateConfig(t),n=[...o.errors],s=[...o.warnings];return t.provider&&t.provider!=="fastly"&&n.push({path:"provider",message:"Provider must be 'fastly' for FastlyFirewallService",code:"INVALID_PROVIDER"}),{valid:n.length===0,errors:n,warnings:s}}getHealthScore(t){let o=super.getHealthScore(t),n=[...o.issues],s=o.score;return t.rules.filter(l=>l.action?.type==="rate_limit").length===0&&(s-=10,n.push({severity:"info",category:"security",message:"No rate limiting rules configured",suggestion:"Consider adding rate limiting to protect against abuse"})),(!t.ips||t.ips.length===0)&&n.push({severity:"info",category:"security",message:"No IP blocking rules configured",suggestion:"Consider blocking known malicious IPs"}),{score:Math.max(0,s),grade:o.grade,issues:n,recommendations:o.recommendations}}diffRules(t,o){let n=[],s=[],a=[...o];for(let l of t){let c=o.find(d=>d.id===l.id);if(!c)n.push(l);else{Ke(ke(l),ke(c))||s.push({...l,id:c.id});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{toAdd:n,toUpdate:s,toDelete:a}}diffIPs(t,o){let n=l=>`${l.action}:${l.ip}`,s=new Set(o.map(n)),a=new Set(t.map(n));return{ipsToAdd:t.filter(l=>!s.has(n(l))),ipsToDelete:o.filter(l=>!a.has(n(l)))}}};T();var tt=class{static fromEnv(){let e=process.env.FASTLY_API_TOKEN,t=process.env.FASTLY_WORKSPACE_ID;if(!e)throw new Error("FASTLY_API_TOKEN environment variable is required");if(!t)throw new Error("FASTLY_WORKSPACE_ID environment variable is required");let o=new Xe(t,e);return new et(o)}static fromConfig(e){let t=e.apiToken||process.env.FASTLY_API_TOKEN,o=e.workspaceId||process.env.FASTLY_WORKSPACE_ID;if(!t)throw new Error("Fastly API token is required (provide apiToken or set FASTLY_API_TOKEN env var)");if(!o)throw new Error("Fastly workspace ID is required (provide workspaceId or set FASTLY_WORKSPACE_ID env var)");r.debug("Creating Fastly provider with config:",{workspaceId:o});let n=new Xe(o,t);return new et(n)}static create(e,t){return this.fromConfig({workspaceId:e,apiToken:t})}};var Zt={provider:"vercel",fields:[{key:"token",envVar:"VERCEL_TOKEN",label:"Vercel API Token",required:!0,secret:!0},{key:"projectId",envVar:"VERCEL_PROJECT_ID",label:"Vercel Project ID",required:!0,configKey:"projectId"},{key:"teamId",envVar:"VERCEL_TEAM_ID",label:"Vercel Team ID",required:!1,configKey:"teamId"}]};var Yt={provider:"cloudflare",fields:[{key:"apiToken",envVar:"CLOUDFLARE_API_TOKEN",label:"Cloudflare API Token",required:!0,secret:!0},{key:"zoneId",envVar:"CLOUDFLARE_ZONE_ID",label:"Cloudflare Zone ID",required:!0,configKey:"zoneId"},{key:"accountId",envVar:"CLOUDFLARE_ACCOUNT_ID",label:"Cloudflare Account ID",required:!1,configKey:"accountId"}]};var Jt={provider:"fastly",fields:[{key:"apiToken",envVar:"FASTLY_API_TOKEN",label:"Fastly API Token",required:!0,secret:!0},{key:"workspaceId",envVar:"FASTLY_WORKSPACE_ID",label:"Fastly Next-Gen WAF Workspace ID",required:!0,configKey:"workspaceId"}]};function Tt(i,e={}){let{explicit:t={},config:o={},env:n=process.env}=e,s={};for(let a of i.fields)s[a.key]=t[a.key]||o[a.key]||n[a.envVar];return s}async function fo(i){let e;if(i.provider)e=i.provider,r.debug(`Using explicitly specified provider: ${e}`);else{let t=mt.detect(i.config);t.provider?(e=t.provider,r.debug(`Auto-detected provider: ${e} (${t.confidence} confidence)`),t.reasons.length>0&&r.debug(`Reasons: ${t.reasons.join(", ")}`)):i.interactive!==!1?e=await ar():(e="vercel",r.warn("No provider detected, defaulting to Vercel"))}try{if(e==="vercel")return await nr(i);if(e==="cloudflare")return{provider:await rr(i)};if(e==="fastly")return{provider:await sr(i)};throw new Error(`Unknown provider: ${e}`)}catch(t){throw r.error(`Failed to initialize ${e} provider:`,t),t}}async function nr(i){let e=i.config,{token:t,projectId:o,teamId:n}=Tt(Zt,{explicit:{token:i.token,projectId:i.projectId,teamId:i.teamId},config:{projectId:e?.providers?.vercel?.projectId??e?.projectId,teamId:e?.providers?.vercel?.teamId??e?.teamId}});if(!t||!o){if(i.interactive===!1)throw new Error("Vercel credentials missing. Provide token and projectId.");r.warn("Missing Vercel credentials"),r.info("Please provide your Vercel credentials:");let{promptForCredentials:a}=await Promise.resolve().then(()=>(co(),lo)),l=await a({token:t,projectId:o,teamId:n});return{provider:Ze.fromConfig({token:l.token,projectId:l.projectId,teamId:l.teamId}),vercelCredentials:l}}return{provider:Ze.fromConfig({token:t,projectId:o,teamId:n}),vercelCredentials:{token:t,projectId:o,teamId:n}}}async function rr(i){let e=i.config,{apiToken:t,zoneId:o,accountId:n}=Tt(Yt,{explicit:{apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId},config:{zoneId:e?.providers?.cloudflare?.zoneId,accountId:e?.providers?.cloudflare?.accountId}});if(!t||!o){if(i.interactive===!1)throw new Error("Cloudflare credentials missing. Provide apiToken and zoneId.");r.warn("Missing Cloudflare credentials"),r.info("Please provide your Cloudflare credentials:");let s=t||await rt("Cloudflare API Token: "),a=o||await w("Cloudflare Zone ID:",{type:"text"}),l=n||await w("Cloudflare Account ID (optional):",{type:"text"});return Qe.fromConfig({apiToken:s,zoneId:a,accountId:l||void 0})}return Qe.fromConfig({apiToken:t,zoneId:o,accountId:n})}async function sr(i){let e=i.config,{apiToken:t,workspaceId:o}=Tt(Jt,{explicit:{apiToken:i.apiToken,workspaceId:i.workspaceId},config:{workspaceId:e?.providers?.fastly?.workspaceId}});if(!t||!o){if(i.interactive===!1)throw new Error("Fastly credentials missing. Provide apiToken and workspaceId.");r.warn("Missing Fastly credentials"),r.info("Please provide your Fastly credentials:");let n=t||await rt("Fastly API Token: "),s=o||await w("Fastly Next-Gen WAF Workspace ID:",{type:"text"});return tt.fromConfig({apiToken:n,workspaceId:s})}return tt.fromConfig({apiToken:t,workspaceId:o})}async function ar(){r.info(po.default.yellow("Unable to auto-detect firewall provider.")),r.info(`Please select a provider:
38
- `),re.forEach((s,a)=>{r.info(` ${a+1}. ${uo(s)}`)}),r.info("");let i=await w(`Select provider (1-${re.length}):`,{type:"text"}),e=String(i).trim().toLowerCase(),t=re.find(s=>s===e);if(t)return t;let o=Number(e);if(Number.isInteger(o)&&o>=1&&o<=re.length)return re[o-1];let n=re[0];return r.warn(`Invalid choice: ${i}, defaulting to ${uo(n)}`),n}function uo(i){switch(i){case"vercel":return"Vercel Firewall";case"cloudflare":return"Cloudflare WAF";case"fastly":return"Fastly Next-Gen WAF";default:return i}}async function J(i,e){try{i.debug&&(r.level=go.LogLevels.debug);let t;if(i.optionalConfig)try{t=await j(i.config,"optional")}catch{t={}}else i.skipValidation?t=await j(i.config,"raw"):t=await j(i.config,"required");let{provider:o,vercelCredentials:n}=await fo({provider:i.provider,config:t,interactive:!i.ci,token:i.token,projectId:i.projectId,teamId:i.teamId,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId}),s=n?.token??"",a=n?.projectId??"",l=n?.teamId??"";await e({config:t,provider:o,token:s,projectId:a,teamId:l})}catch(t){Z(t,i.errorContext)}}var lr="backup",cr="Backup or restore firewall configurations",dr={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:Y,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},output:{alias:"o",type:"string",description:"Output directory for backups",default:"./backups"},restore:{alias:"r",type:"string",description:"Restore from backup file"},list:{alias:"l",type:"boolean",description:"List available backups",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},ur=async i=>{try{i.debug&&(r.level=mo.LogLevels.debug);let e=i.output||"./backups";if(i.list){if(!(0,ge.existsSync)(e)){r.info(Q.default.yellow("No backup directory found."));return}let t=(0,ge.readdirSync)(e).filter(o=>o.endsWith(".json")).map(o=>{let n=(0,At.join)(e,o),s=(0,ge.statSync)(n);return{name:o,size:s.size,created:s.mtime}}).sort((o,n)=>n.created.getTime()-o.created.getTime());if(t.length===0){r.info(Q.default.yellow("No backups found."));return}r.log(Q.default.bold(`
37
+ \u2022 Check token permissions in Cloudflare dashboard`)):n.includes("not found")?(r.warn(`\u{1F6AB} Lists API resource not found during ${t}. Falling back to individual IP rules.`),r.info("\u{1F4A1} This may be temporary - the List will be recreated on next sync if Lists API is available.")):n.includes("rate limit")||n.includes("quota")?(r.warn(`\u{1F6AB} Lists API rate limited during ${t}. Falling back to individual IP rules.`),r.info("\u{1F4A1} Lists API rate limit reached. Individual rules will be used this time. Consider retrying later or upgrading your Cloudflare plan.")):(r.warn(`\u{1F6AB} Lists API error during ${t}: ${e.message}. Falling back to individual IP rules.`),r.info("\u{1F4A1} Lists API temporarily unavailable. Using individual IP rules as fallback. Check Cloudflare status if this persists."))}else r.warn(`\u{1F6AB} Unknown Lists API error during ${t}. Falling back to individual IP rules.`)}};var Qe=class{static create(e,t,n){let o=e||process.env.CLOUDFLARE_API_TOKEN,s=t||process.env.CLOUDFLARE_ZONE_ID,a=n||process.env.CLOUDFLARE_ACCOUNT_ID;if(!o)throw new Error("Cloudflare API token is required. Set CLOUDFLARE_API_TOKEN environment variable or pass as parameter.");if(!s)throw new Error("Cloudflare Zone ID is required. Set CLOUDFLARE_ZONE_ID environment variable or pass as parameter.");return new ut(o,s,a)}static fromEnv(){return this.create()}static fromConfig(e){return this.create(e.apiToken,e.zoneId,e.accountId)}};T();T();var pn=process.env.DOORMAN_FASTLY_API_BASE_URL||"https://api.fastly.com",pt="doorman-managed-deny",ft="doorman-managed-allow",Xe=class extends Pe{constructor(t,n){super(pn,"fastly");this.workspaceId=t;this.apiToken=n}workspaceId;apiToken;getAuthHeaders(){return{"Fastly-Key":this.apiToken}}workspacePath(...t){return["/ngwaf/v1/workspaces",this.workspaceId,...t].join("/")}async fetchRules(){return(await this.get(this.workspacePath("rules"))).data}async createRule(t){return this.post(this.workspacePath("rules"),t)}async updateRule(t,n){return this.patch(this.workspacePath("rules",t),n)}async deleteRule(t){await this.delete(this.workspacePath("rules",t))}async fetchLists(){return(await this.get(this.workspacePath("lists"))).data}async createList(t,n){return this.post(this.workspacePath("lists"),{name:t,type:"ip",description:"Managed by doorman \u2014 do not edit entries directly, they will be overwritten on the next sync.",entries:n})}async updateListEntries(t,n){return this.patch(this.workspacePath("lists",t),{entries:n})}async findList(t){return(await this.fetchLists()).find(o=>o.name===t&&o.type==="ip")??null}async getOrCreateList(t){let n=await this.findList(t);return n||(r.debug(`Creating Fastly list "${t}" in workspace ${this.workspaceId}`),this.createList(t,[]))}async fetchWorkspace(){return this.get(this.workspacePath())}async verifyCredentials(){try{return await this.fetchWorkspace(),!0}catch(t){return r.debug("Credential verification failed:",t),!1}}};T();var et=class extends ke{constructor(t){super();this.client=t}client;name="fastly";async fetchConfig(){try{r.debug("Fetching Fastly Next-Gen WAF configuration");let[t,n,o]=await Promise.all([this.client.fetchRules(),this.client.findList(pt),this.client.findList(ft)]),s=this.translateFastlyRules(t),a=[...k.fastlyListEntriesToUnified(n?.entries??[],"deny"),...k.fastlyListEntriesToUnified(o?.entries??[],"allow")];return{version:"2.0",provider:"fastly",providers:{fastly:{workspaceId:this.client.workspaceId}},rules:s,ips:a}}catch(t){throw r.error("Error fetching Fastly configuration:",t),new Error("Failed to fetch Fastly Next-Gen WAF configuration")}}translateFastlyRules(t){let n=[];for(let o of t){if(o.type!=="request"&&o.type!=="rate_limit"){r.debug(`Skipping Fastly rule ${o.id} \u2014 type "${o.type}" is not a request/rate_limit rule doorman manages`);continue}let s=k.fastlyToUnified(o);s.warnings.length>0&&s.warnings.forEach(a=>{let{TranslationWarningSystem:l}=(fe(),ye(De));r.warn(`Rule ${o.description||o.id}:
38
+ ${l.formatWarning(a)}`)}),n.push(s.result)}return n}async syncRules(t,n={}){let{dryRun:o=!1}=n;try{let{OperationSafety:s}=(Tt(),ye(Et)),a=await s.performDryRunValidation(t,"sync rules",async v=>this.getChanges(v));if(!a.valid)throw new Error(`Dry-run validation failed: ${a.issues.join(", ")}`);let l=a.changes,{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u}=l,p=l.ipsToAdd||[],g=l.ipsToDelete||[];if(o)return r.info("Dry run mode. The following changes would be made:"),r.info(`Custom Rules - Add: ${c.length}, Update: ${d.length}, Delete: ${u.length}`),r.info(`IP Rules - Add: ${p.length}, Delete: ${g.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,warnings:a.warnings};let h=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Fastly workspace ${this.client.workspaceId}`,changes:l,riskLevel:h,skipConfirmation:n.force||!1,dryRun:!1,allowDeletions:n.allowDeletions||!1}))throw new Error("Operation cancelled by user");let R=[];vt(t.rules)&&R.push("Rule `priority` has no effect on Fastly: Next-Gen WAF rules are evaluated independently and have no API-exposed ordering concept to honour.");let N=c.map(v=>({rule:v,translated:k.unifiedToFastly(v)})),Z=d.map(v=>({rule:v,translated:k.unifiedToFastly(v)})),W=[],ue=(v,V)=>`${v}: ${V instanceof Error?V.message:String(V)}`,me=[],_e=[],_=[],ve=[];for(let v of u)if(v.id)try{r.debug(`Deleting Fastly rule: ${v.id}`),await this.client.deleteRule(v.id),_.push(v.id)}catch(V){r.error(`Failed to delete Fastly rule ${v.id}:`,V),W.push(ue(`Failed to delete rule ${v.id}`,V))}for(let{rule:v,translated:V}of N){let ie=V.result;try{r.debug(`Adding new Fastly rule: ${ie.description}`);let ae=await this.client.createRule(ie);me.push(ae),ve.push({oldId:v.id||void 0,newId:ae.id,name:ie.description})}catch(ae){r.error(`Failed to add Fastly rule "${ie.description}":`,ae),W.push(ue(`Failed to add rule "${ie.description}"`,ae))}}for(let{rule:v,translated:V}of Z)if(v.id)try{r.debug(`Updating Fastly rule: ${v.id}`);let ie=await this.client.updateRule(v.id,V.result);_e.push(ie)}catch(ie){r.error(`Failed to update Fastly rule ${v.id}:`,ie),W.push(ue(`Failed to update rule ${v.id}`,ie))}let be=0,Ee=0,We=t.ips||[],{result:Se,warnings:je}=k.unifiedIPsToFastlyEntries(We);je.forEach(v=>R.push(v.message));try{for(let[v,V]of[[pt,Se.denyEntries],[ft,Se.allowEntries]]){let ae=(await this.client.findList(v))?.entries??[],nt=V.filter(f=>!ae.includes(f)),ot=ae.filter(f=>!V.includes(f));if(nt.length===0&&ot.length===0)continue;let Te=await this.client.getOrCreateList(v);await this.client.updateListEntries(Te.id,V),be+=nt.length,Ee+=ot.length}}catch(v){r.error("Failed to sync Fastly IP lists:",v),W.push(ue("Failed to sync IP lists",v))}return r.debug(`Custom Rules: Added: ${me.length}, Updated: ${_e.length}, Deleted: ${_.length}`),r.debug(`IP Rules: Added: ${be}, Deleted: ${Ee}`),{success:W.length===0,rulesAdded:me.length,rulesUpdated:_e.length,rulesDeleted:_.length,ipsAdded:be,ipsUpdated:0,ipsDeleted:Ee,idRemappings:ve.length>0?ve:void 0,errors:W.length>0?W:void 0,warnings:R.length>0?R:void 0}}catch(s){throw r.error("Error during sync:",s),new Error(`Failed to synchronize firewall rules: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async getChanges(t){let n=Le.safeParse(t);if(!n.success)throw new Error(`Invalid firewall configuration: ${n.error.message}`);try{r.debug("Fetching existing Fastly configuration");let[o,s,a]=await Promise.all([this.client.fetchRules(),this.client.findList(pt),this.client.findList(ft)]),l=this.translateFastlyRules(o),{toAdd:c,toUpdate:d,toDelete:u}=this.diffRules(t.rules,l),p=s?.entries??[],g=a?.entries??[],h=[...k.fastlyListEntriesToUnified(p,"deny"),...k.fastlyListEntriesToUnified(g,"allow")],{ipsToAdd:I,ipsToDelete:R}=this.diffIPs(t.ips||[],h);return{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u,ipsToAdd:I,ipsToUpdate:[],ipsToDelete:R,hasChanges:c.length>0||d.length>0||u.length>0||I.length>0||R.length>0}}catch(o){throw r.error("Error fetching existing Fastly configuration:",o),new Error("Failed to fetch existing Fastly configuration")}}getSupportedFeatures(){return{supportsCustomRules:!0,supportsIPBlocking:!0,supportsRateLimiting:!0,supportsManagedRules:!1,supportsGeoBlocking:!0,supportsRedirect:!0,supportsChallenge:!0}}async verifyCredentials(){return this.client.verifyCredentials()}validateConfig(t){let n=super.validateConfig(t),o=[...n.errors],s=[...n.warnings];return t.provider&&t.provider!=="fastly"&&o.push({path:"provider",message:"Provider must be 'fastly' for FastlyFirewallService",code:"INVALID_PROVIDER"}),{valid:o.length===0,errors:o,warnings:s}}getHealthScore(t){let n=super.getHealthScore(t),o=[...n.issues],s=n.score;return t.rules.filter(l=>l.action?.type==="rate_limit").length===0&&(s-=10,o.push({severity:"info",category:"security",message:"No rate limiting rules configured",suggestion:"Consider adding rate limiting to protect against abuse"})),(!t.ips||t.ips.length===0)&&o.push({severity:"info",category:"security",message:"No IP blocking rules configured",suggestion:"Consider blocking known malicious IPs"}),{score:Math.max(0,s),grade:n.grade,issues:o,recommendations:n.recommendations}}diffRules(t,n){let o=[],s=[],a=[...n];for(let l of t){let c=n.find(d=>d.id===l.id);if(!c)o.push(l);else{Ke($e(l),$e(c))||s.push({...l,id:c.id});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{toAdd:o,toUpdate:s,toDelete:a}}diffIPs(t,n){let o=l=>`${l.action}:${l.ip}`,s=new Set(n.map(o)),a=new Set(t.map(o));return{ipsToAdd:t.filter(l=>!s.has(o(l))),ipsToDelete:n.filter(l=>!a.has(o(l)))}}};T();var tt=class{static fromEnv(){let e=process.env.FASTLY_API_TOKEN,t=process.env.FASTLY_WORKSPACE_ID;if(!e)throw new Error("FASTLY_API_TOKEN environment variable is required");if(!t)throw new Error("FASTLY_WORKSPACE_ID environment variable is required");let n=new Xe(t,e);return new et(n)}static fromConfig(e){let t=e.apiToken||process.env.FASTLY_API_TOKEN,n=e.workspaceId||process.env.FASTLY_WORKSPACE_ID;if(!t)throw new Error("Fastly API token is required (provide apiToken or set FASTLY_API_TOKEN env var)");if(!n)throw new Error("Fastly workspace ID is required (provide workspaceId or set FASTLY_WORKSPACE_ID env var)");r.debug("Creating Fastly provider with config:",{workspaceId:n});let o=new Xe(n,t);return new et(o)}static create(e,t){return this.fromConfig({workspaceId:e,apiToken:t})}};var Jt={provider:"vercel",fields:[{key:"token",envVar:"VERCEL_TOKEN",label:"Vercel API Token",required:!0,secret:!0},{key:"projectId",envVar:"VERCEL_PROJECT_ID",label:"Vercel Project ID",required:!0,configKey:"projectId"},{key:"teamId",envVar:"VERCEL_TEAM_ID",label:"Vercel Team ID",required:!1,configKey:"teamId"}]};var Qt={provider:"cloudflare",fields:[{key:"apiToken",envVar:"CLOUDFLARE_API_TOKEN",label:"Cloudflare API Token",required:!0,secret:!0},{key:"zoneId",envVar:"CLOUDFLARE_ZONE_ID",label:"Cloudflare Zone ID",required:!0,configKey:"zoneId"},{key:"accountId",envVar:"CLOUDFLARE_ACCOUNT_ID",label:"Cloudflare Account ID",required:!1,configKey:"accountId"}]};var Xt={provider:"fastly",fields:[{key:"apiToken",envVar:"FASTLY_API_TOKEN",label:"Fastly API Token",required:!0,secret:!0},{key:"workspaceId",envVar:"FASTLY_WORKSPACE_ID",label:"Fastly Next-Gen WAF Workspace ID",required:!0,configKey:"workspaceId"}]};function Pt(i,e={}){let{explicit:t={},config:n={},env:o=process.env}=e,s={};for(let a of i.fields)s[a.key]=t[a.key]||n[a.key]||o[a.envVar];return s}async function yn(i){let e;if(i.provider)e=i.provider,r.debug(`Using explicitly specified provider: ${e}`);else{let t=yt.detect(i.config);t.provider?(e=t.provider,r.debug(`Auto-detected provider: ${e} (${t.confidence} confidence)`),t.reasons.length>0&&r.debug(`Reasons: ${t.reasons.join(", ")}`)):i.interactive!==!1?e=await ur():(e="vercel",r.warn("No provider detected, defaulting to Vercel"))}try{if(e==="vercel")return await lr(i);if(e==="cloudflare")return{provider:await cr(i)};if(e==="fastly")return{provider:await dr(i)};throw new Error(`Unknown provider: ${e}`)}catch(t){throw r.error(`Failed to initialize ${e} provider:`,t),t}}async function lr(i){let e=i.config,{token:t,projectId:n,teamId:o}=Pt(Jt,{explicit:{token:i.token,projectId:i.projectId,teamId:i.teamId},config:{projectId:e?.providers?.vercel?.projectId??e?.projectId,teamId:e?.providers?.vercel?.teamId??e?.teamId}});if(!t||!n){if(i.interactive===!1)throw new Error("Vercel credentials missing. Provide token and projectId.");r.warn("Missing Vercel credentials"),r.info("Please provide your Vercel credentials:");let{promptForCredentials:a}=await Promise.resolve().then(()=>(gn(),fn)),l=await a({token:t,projectId:n,teamId:o});return{provider:Ze.fromConfig({token:l.token,projectId:l.projectId,teamId:l.teamId}),vercelCredentials:l}}return{provider:Ze.fromConfig({token:t,projectId:n,teamId:o}),vercelCredentials:{token:t,projectId:n,teamId:o}}}async function cr(i){let e=i.config,{apiToken:t,zoneId:n,accountId:o}=Pt(Qt,{explicit:{apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId},config:{zoneId:e?.providers?.cloudflare?.zoneId,accountId:e?.providers?.cloudflare?.accountId}});if(!t||!n){if(i.interactive===!1)throw new Error("Cloudflare credentials missing. Provide apiToken and zoneId.");r.warn("Missing Cloudflare credentials"),r.info("Please provide your Cloudflare credentials:");let s=t||await at("Cloudflare API Token: "),a=n||await w("Cloudflare Zone ID:",{type:"text"}),l=o||await w("Cloudflare Account ID (optional):",{type:"text"});return Qe.fromConfig({apiToken:s,zoneId:a,accountId:l||void 0})}return Qe.fromConfig({apiToken:t,zoneId:n,accountId:o})}async function dr(i){let e=i.config,{apiToken:t,workspaceId:n}=Pt(Xt,{explicit:{apiToken:i.apiToken,workspaceId:i.workspaceId},config:{workspaceId:e?.providers?.fastly?.workspaceId}});if(!t||!n){if(i.interactive===!1)throw new Error("Fastly credentials missing. Provide apiToken and workspaceId.");r.warn("Missing Fastly credentials"),r.info("Please provide your Fastly credentials:");let o=t||await at("Fastly API Token: "),s=n||await w("Fastly Next-Gen WAF Workspace ID:",{type:"text"});return tt.fromConfig({apiToken:o,workspaceId:s})}return tt.fromConfig({apiToken:t,workspaceId:n})}async function ur(){r.info(hn.default.yellow("Unable to auto-detect firewall provider.")),r.info(`Please select a provider:
39
+ `),re.forEach((s,a)=>{r.info(` ${a+1}. ${mn(s)}`)}),r.info("");let i=await w(`Select provider (1-${re.length}):`,{type:"text"}),e=String(i).trim().toLowerCase(),t=re.find(s=>s===e);if(t)return t;let n=Number(e);if(Number.isInteger(n)&&n>=1&&n<=re.length)return re[n-1];let o=re[0];return r.warn(`Invalid choice: ${i}, defaulting to ${mn(o)}`),o}function mn(i){switch(i){case"vercel":return"Vercel Firewall";case"cloudflare":return"Cloudflare WAF";case"fastly":return"Fastly Next-Gen WAF";default:return i}}async function Q(i,e){try{i.debug&&(r.level=wn.LogLevels.debug);let t;if(i.optionalConfig)try{t=await j(i.config,"optional")}catch{t={}}else i.skipValidation?t=await j(i.config,"raw"):t=await j(i.config,"required");let{provider:n,vercelCredentials:o}=await yn({provider:i.provider,config:t,interactive:!i.ci,token:i.token,projectId:i.projectId,teamId:i.teamId,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId}),s=o?.token??"",a=o?.projectId??"",l=o?.teamId??"";await e({config:t,provider:n,token:s,projectId:a,teamId:l})}catch(t){Y(t,i.errorContext)}}var pr="backup",fr="Backup or restore firewall configurations",gr={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},output:{alias:"o",type:"string",description:"Output directory for backups",default:"./backups"},restore:{alias:"r",type:"string",description:"Restore from backup file"},list:{alias:"l",type:"boolean",description:"List available backups",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},mr=async i=>{try{i.debug&&(r.level=In.LogLevels.debug);let e=i.output||"./backups";if(i.list){if(!(0,ge.existsSync)(e)){r.info(H.default.yellow("No backup directory found."));return}let t=(0,ge.readdirSync)(e).filter(n=>n.endsWith(".json")).map(n=>{let o=(0,it.join)(e,n),s=(0,ge.statSync)(o);return{name:n,size:s.size,created:s.mtime}}).sort((n,o)=>o.created.getTime()-n.created.getTime());if(t.length===0){r.info(H.default.yellow("No backups found."));return}r.log(H.default.bold(`
39
40
  \u{1F4E6} Available Backups:
40
- `)),t.forEach(o=>{r.log(`${Q.default.cyan(o.name)}`),r.log(` ${Q.default.dim("Created:")} ${o.created.toLocaleString()}`),r.log(` ${Q.default.dim("Size:")} ${(o.size/1024).toFixed(1)} KB`),r.log("")});return}if(i.restore){let t=i.restore.startsWith("/")?i.restore:(0,At.join)(e,i.restore);(0,ge.existsSync)(t)||(r.error(`Backup file not found: ${t}`),process.exit(1));let o=await j(t,"raw"),n=i.config||".doorman.json";if((0,ge.existsSync)(n)&&!await w(`Config file ${n} already exists. Do you want to overwrite it?`,{type:"confirm"})){r.info(Q.default.yellow("Restore cancelled."));return}let{backup:s,...a}=o;await q(a,n),r.success(Q.default.green(`\u2705 Restored configuration from ${t} to ${n}`));return}await J({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"creating backup"},async({provider:t,projectId:o,teamId:n})=>{r.start("Fetching current remote configuration...");let s=await t.fetchConfig(),a=s.metadata?.version??s.version;Re.getInstance().validateConfig(s),(0,ge.existsSync)(e)||(0,ge.mkdirSync)(e,{recursive:!0});let c=new Date,d=c.toISOString().split("T")[0]??"unknown-date",u=(c.toISOString().split("T")[1]??"").split(".")[0]?.replace(/:/g,"-")??"unknown-time",g=`firewall-backup-${`${d}_${u}`}.json`,h=(0,At.join)(e,g),I={...s,backup:{createdAt:new Date().toISOString(),source:"remote",provider:t.name,...t.name==="vercel"?{projectId:o,teamId:n}:{},originalVersion:a}};await q(I,h,{validate:!1}),r.success(Q.default.green(`\u2705 Backup created: ${h}`)),r.log(""),r.log(Q.default.bold("Backup Details:")),r.log(`${Q.default.dim("Version:")} ${a??"unknown"}`),r.log(`${Q.default.dim("Rules:")} ${s.rules.length} custom, ${s.ips?.length??0} IP blocking`),r.log(`${Q.default.dim("Created:")} ${new Date().toLocaleString()}`),r.log(""),r.log(Q.default.dim("To restore this backup later, run:")),r.log(Q.default.cyan(`doorman backup --restore ${g}`))})}catch(e){Z(e,"managing backup")}};var Xt={};M(Xt,{builder:()=>gr,command:()=>pr,desc:()=>fr,handler:()=>mr});var X=S(require("chalk"));T();function le(i){if(we(i))return i;let e=i,t=e.rules.map(n=>k.vercelToUnified(n).result),o=(e.ips??[]).map(n=>k.vercelIPToUnified(n));return{version:"2.0",provider:"vercel",providers:{vercel:{projectId:e.projectId,teamId:e.teamId}},rules:t,ips:o,metadata:{version:e.version,updatedAt:e.updatedAt}}}function Pt(i,e){let t=!1,o=we(i),n=o?{...i,metadata:{...i.metadata}}:{...i};if(e.version!==void 0)if(o){let s=n;s.metadata?.version!==e.version&&(s.metadata={...s.metadata,version:e.version,updatedAt:e.updatedAt??new Date().toISOString()},t=!0)}else{let s=n;s.version!==e.version&&(s.version=e.version,s.updatedAt=e.updatedAt??new Date().toISOString(),t=!0)}if(e.idRemappings&&e.idRemappings.length>0){let s=new Map(e.idRemappings.filter(d=>d.oldId).map(d=>[d.oldId,d.newId])),a=new Map(e.idRemappings.filter(d=>!d.oldId).map(d=>[d.name,d.newId])),l=!1,c=n.rules.map(d=>{let u=d.id?s.get(d.id):a.get(d.name);return u&&u!==d.id?(l=!0,{...d,id:u}):d});l&&(n={...n,rules:c},t=!0)}return{config:n,changed:t}}function ho(i,e){if(we(e))return{...e,...i};let t=e,o=i.rules.map(s=>k.unifiedToVercel(s).result),n=(i.ips??[]).map(s=>({id:s.id||"",ip:s.ip,hostname:s.hostname||"",action:s.action,notes:s.notes}));return{...t,projectId:i.providers?.vercel?.projectId??t.projectId,teamId:i.providers?.vercel?.teamId??t.teamId,version:i.metadata?.version,updatedAt:i.metadata?.updatedAt,rules:o,ips:n}}var pr="diff",fr="Show detailed differences between local and remote firewall configuration",gr={config:{alias:"c",type:"string",description:"Path to firewall config file"},provider:Y,projectId:{alias:"p",type:"string",description:"Vercel Project ID"},teamId:{alias:"t",type:"string",description:"Vercel Team ID"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},format:{alias:"f",type:"string",choices:["table","json"],description:"Output format",default:"table"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},mr=async i=>{await J({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"calculating diff"},async({config:e,provider:t})=>{await hr(t,le(e),i)})};async function hr(i,e,t){let o=t.format==="json";o||r.start("Calculating differences...");let n=await i.getChanges(e),s=n.ipsToAdd??[],a=n.ipsToUpdate??[],l=n.ipsToDelete??[];if(o){r.log(JSON.stringify({rules:{toAdd:n.rulesToAdd,toUpdate:n.rulesToUpdate,toDelete:n.rulesToDelete},ips:{toAdd:s,toUpdate:a,toDelete:l},summary:{hasChanges:n.hasChanges,ruleChanges:n.rulesToAdd.length+n.rulesToUpdate.length+n.rulesToDelete.length,ipChanges:s.length+a.length+l.length}},null,2));return}if(!n.hasChanges){r.success(X.default.green("No differences found. Local and remote configurations are in sync."));return}r.log(X.default.bold(`
41
+ `)),t.forEach(n=>{r.log(`${H.default.cyan(n.name)}`),r.log(` ${H.default.dim("Created:")} ${n.created.toLocaleString()}`),r.log(` ${H.default.dim("Size:")} ${(n.size/1024).toFixed(1)} KB`),r.log("")});return}if(i.restore){let t=i.restore.startsWith("/")?i.restore:(0,it.join)(e,i.restore);(0,ge.existsSync)(t)||(r.error(`Backup file not found: ${t}`),process.exit(1));let n=await j(t,"raw"),o=i.config||".doorman.json";if((0,ge.existsSync)(o)&&!await w(`Config file ${o} already exists. Do you want to overwrite it?`,{type:"confirm"})){r.info(H.default.yellow("Restore cancelled."));return}let{backup:s,...a}=n;await q(a,o),r.success(H.default.green(`\u2705 Restored configuration from ${t} to ${o}`));return}await Q({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"creating backup"},async({provider:t,projectId:n,teamId:o})=>{r.start("Fetching current remote configuration...");let s=await t.fetchConfig(),a=s.metadata?.version??s.version;Re.getInstance().validateConfig(s),(0,ge.existsSync)(e)||(0,ge.mkdirSync)(e,{recursive:!0});let c=new Date,d=c.toISOString().split("T")[0]??"unknown-date",u=(c.toISOString().split("T")[1]??"").split(".")[0]?.replace(/:/g,"-")??"unknown-time",g=`firewall-backup-${`${d}_${u}`}.json`,h=(0,it.join)(e,g),I={...s,backup:{createdAt:new Date().toISOString(),source:"remote",provider:t.name,...t.name==="vercel"?{projectId:n,teamId:o}:{},originalVersion:a}};await q(I,h,{validate:!1}),r.success(H.default.green(`\u2705 Backup created: ${h}`)),r.log(""),r.log(H.default.bold("Backup Details:")),r.log(`${H.default.dim("Version:")} ${a??"unknown"}`),r.log(`${H.default.dim("Rules:")} ${s.rules.length} custom, ${s.ips?.length??0} IP blocking`),r.log(`${H.default.dim("Created:")} ${new Date().toLocaleString()}`),!(0,it.isAbsolute)(e)&&ji()&&!qi(e)&&r.warn(H.default.yellow(`\u{1F4A1} ${e} isn't in .gitignore \u2014 firewall backups may contain rule details you don't want in git history.`)),r.log(""),r.log(H.default.dim("To restore this backup later, run:")),r.log(H.default.cyan(`doorman backup --restore ${g}`))})}catch(e){Y(e,"managing backup")}};var ti={};M(ti,{builder:()=>wr,command:()=>hr,desc:()=>yr,handler:()=>Ir});var X=S(require("chalk"));T();function le(i){if(we(i))return i;let e=i,t=e.rules.map(o=>k.vercelToUnified(o).result),n=(e.ips??[]).map(o=>k.vercelIPToUnified(o));return{version:"2.0",provider:"vercel",providers:{vercel:{projectId:e.projectId,teamId:e.teamId}},rules:t,ips:n,metadata:{version:e.version,updatedAt:e.updatedAt}}}function kt(i,e){let t=!1,n=we(i),o=n?{...i,metadata:{...i.metadata}}:{...i};if(e.version!==void 0)if(n){let s=o;s.metadata?.version!==e.version&&(s.metadata={...s.metadata,version:e.version,updatedAt:e.updatedAt??new Date().toISOString()},t=!0)}else{let s=o;s.version!==e.version&&(s.version=e.version,s.updatedAt=e.updatedAt??new Date().toISOString(),t=!0)}if(e.idRemappings&&e.idRemappings.length>0){let s=new Map(e.idRemappings.filter(d=>d.oldId).map(d=>[d.oldId,d.newId])),a=new Map(e.idRemappings.filter(d=>!d.oldId).map(d=>[d.name,d.newId])),l=!1,c=o.rules.map(d=>{let u=d.id?s.get(d.id):a.get(d.name);return u&&u!==d.id?(l=!0,{...d,id:u}):d});l&&(o={...o,rules:c},t=!0)}return{config:o,changed:t}}function Rn(i,e){if(we(e))return{...e,...i};let t=e,n=i.rules.map(s=>k.unifiedToVercel(s).result),o=(i.ips??[]).map(s=>({id:s.id||"",ip:s.ip,hostname:s.hostname||"",action:s.action,notes:s.notes}));return{...t,projectId:i.providers?.vercel?.projectId??t.projectId,teamId:i.providers?.vercel?.teamId??t.teamId,version:i.metadata?.version,updatedAt:i.metadata?.updatedAt,rules:n,ips:o}}var hr="diff",yr="Show detailed differences between local and remote firewall configuration",wr={config:{alias:"c",type:"string",description:"Path to firewall config file"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID"},teamId:{alias:"t",type:"string",description:"Vercel Team ID"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},format:{alias:"f",type:"string",choices:["table","json"],description:"Output format",default:"table"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Ir=async i=>{await Q({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"calculating diff"},async({config:e,provider:t})=>{await Rr(t,le(e),i)})};async function Rr(i,e,t){let n=t.format==="json";n||r.start("Calculating differences...");let o=await i.getChanges(e),s=o.ipsToAdd??[],a=o.ipsToUpdate??[],l=o.ipsToDelete??[];if(n){r.log(JSON.stringify({rules:{toAdd:o.rulesToAdd,toUpdate:o.rulesToUpdate,toDelete:o.rulesToDelete},ips:{toAdd:s,toUpdate:a,toDelete:l},summary:{hasChanges:o.hasChanges,ruleChanges:o.rulesToAdd.length+o.rulesToUpdate.length+o.rulesToDelete.length,ipChanges:s.length+a.length+l.length}},null,2));return}if(!o.hasChanges){r.success(X.default.green("No differences found. Local and remote configurations are in sync."));return}r.log(X.default.bold(`
41
42
  \u{1F50D} ${i.name} Configuration Differences
42
- `)),r.log(X.default.bold("Rule Changes:")),r.log(` ${X.default.green("+")} ${n.rulesToAdd.length} to add`),n.rulesToAdd.forEach(d=>r.log(` ${X.default.green("+")} ${d.name}`)),r.log(` ${X.default.cyan("~")} ${n.rulesToUpdate.length} to update`),n.rulesToUpdate.forEach(d=>r.log(` ${X.default.cyan("~")} ${d.name}`)),r.log(` ${X.default.red("-")} ${n.rulesToDelete.length} to delete`),n.rulesToDelete.forEach(d=>r.log(` ${X.default.red("-")} ${d.name}`)),(s.length||a.length||l.length)&&(r.log(""),r.log(X.default.bold("IP Rule Changes:")),r.log(` ${X.default.green("+")} ${s.length} to add`),r.log(` ${X.default.cyan("~")} ${a.length} to update`),r.log(` ${X.default.red("-")} ${l.length} to delete`));let c=n.rulesToAdd.length+n.rulesToUpdate.length+n.rulesToDelete.length+s.length+a.length+l.length;r.log(""),r.log(X.default.bold(`Summary: ${c} total changes detected`)),r.log(X.default.dim("Run `sync` to apply these changes to the remote configuration."))}var ei={};M(ei,{builder:()=>Ir,command:()=>yr,desc:()=>wr,handler:()=>Rr});var Ve=S(require("chalk")),yo=require("zod");T();pe();var yr="download [configVersion]",wr="Download remote Vercel Firewall rules and update local config, optionally for a specific configuration version",Ir={configVersion:{type:"number",description:"Specific configuration version to download (defaults to latest)"},config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:Y,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},dryRun:{alias:"d",type:"boolean",description:"Show rules that would be downloaded without making changes",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Rr=async i=>{await J({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,optionalConfig:!0,skipValidation:!0,errorContext:"downloading firewall rules"},async({config:e,provider:t})=>{if(i.configVersion!==void 0)try{ft.parse(i.configVersion)}catch(o){throw o instanceof yo.z.ZodError&&(r.error("Invalid configuration version number. Version must be a positive integer."),process.exit(1)),o}await Cr(t,e,i)})};async function Cr(i,e,t){r.start(`Fetching remote firewall configuration${t.configVersion?` version ${t.configVersion}`:""} ...`);let o=await i.fetchConfig(t.configVersion),n=o.rules,s=o.ips??[];if(n.length>0?(r.log(Ve.default.bold(`
43
- Remote Custom Rules to Download (${n.length}):
44
- `)),n.forEach(c=>r.log(` - ${c.name}${c.enabled?"":Ve.default.dim(" (disabled)")}`))):r.info("No custom rules to download..."),s.length>0?(r.log(Ve.default.bold(`
43
+ `)),r.log(X.default.bold("Rule Changes:")),r.log(` ${X.default.green("+")} ${o.rulesToAdd.length} to add`),o.rulesToAdd.forEach(d=>r.log(` ${X.default.green("+")} ${d.name}`)),r.log(` ${X.default.cyan("~")} ${o.rulesToUpdate.length} to update`),o.rulesToUpdate.forEach(d=>r.log(` ${X.default.cyan("~")} ${d.name}`)),r.log(` ${X.default.red("-")} ${o.rulesToDelete.length} to delete`),o.rulesToDelete.forEach(d=>r.log(` ${X.default.red("-")} ${d.name}`)),(s.length||a.length||l.length)&&(r.log(""),r.log(X.default.bold("IP Rule Changes:")),r.log(` ${X.default.green("+")} ${s.length} to add`),r.log(` ${X.default.cyan("~")} ${a.length} to update`),r.log(` ${X.default.red("-")} ${l.length} to delete`));let c=o.rulesToAdd.length+o.rulesToUpdate.length+o.rulesToDelete.length+s.length+a.length+l.length;r.log(""),r.log(X.default.bold(`Summary: ${c} total changes detected`)),r.log(X.default.dim("Run `sync` to apply these changes to the remote configuration."))}var ii={};M(ii,{builder:()=>br,command:()=>Cr,desc:()=>vr,handler:()=>Er});var Ve=S(require("chalk")),Cn=require("zod");T();pe();var Cr="download [configVersion]",vr="Download remote Vercel Firewall rules and update local config, optionally for a specific configuration version",br={configVersion:{type:"number",description:"Specific configuration version to download (defaults to latest)"},config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},dryRun:{alias:"d",type:"boolean",description:"Show rules that would be downloaded without making changes",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Er=async i=>{await Q({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,optionalConfig:!0,skipValidation:!0,errorContext:"downloading firewall rules"},async({config:e,provider:t})=>{if(i.configVersion!==void 0)try{mt.parse(i.configVersion)}catch(n){throw n instanceof Cn.z.ZodError&&(r.error("Invalid configuration version number. Version must be a positive integer."),process.exit(1)),n}await Tr(t,e,i)})};async function Tr(i,e,t){r.start(`Fetching remote firewall configuration${t.configVersion?` version ${t.configVersion}`:""} ...`);let n=await i.fetchConfig(t.configVersion),o=n.rules,s=n.ips??[];if(o.length>0?(r.log(Ve.default.bold(`
44
+ Remote Custom Rules to Download (${o.length}):
45
+ `)),o.forEach(c=>r.log(` - ${c.name}${c.enabled?"":Ve.default.dim(" (disabled)")}`))):r.info("No custom rules to download..."),s.length>0?(r.log(Ve.default.bold(`
45
46
  Remote IP Blocking Rules to Download (${s.length}):
46
- `)),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info("No IP blocking rules to download..."),t.dryRun){r.info(Ve.default.cyan("Dry run completed. No changes made."));return}if(!await w(`Do you want to download${t.configVersion?` version ${t.configVersion}`:" the latest version"} of these rules? This will overwrite your local configuration.`,{type:"confirm"})){r.info(Ve.default.yellow("Download cancelled."));return}let l=ho(o,e);r.start("Saving configuration..."),await q(l,t.config),r.success(Ve.default.green("Successfully downloaded and updated configuration"))}var ti={};M(ti,{builder:()=>Er,command:()=>vr,desc:()=>br,handler:()=>kr});var Be=S(require("chalk")),wo=require("fs");T();var vr="export",br="Export firewall configuration in various formats",Er={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:Y,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},format:{alias:"f",type:"string",choices:["json","yaml","terraform","markdown"],description:"Export format",default:"json"},output:{alias:"o",type:"string",description:"Output file path"},source:{alias:"s",type:"string",choices:["local","remote"],description:"Export from local config or remote Vercel",default:"local"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}};function Tr(i){let e=new Map;for(let t of i){let o=t.group??0,n=e.get(o);n?n.push(t):e.set(o,[t])}return[...e.values()]}var Ar=i=>{let{rules:e,ips:t=[]}=i,o=i.metadata?.version,n=i.metadata?.updatedAt,s=`# Firewall Configuration Report
47
+ `)),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info("No IP blocking rules to download..."),t.dryRun){r.info(Ve.default.cyan("Dry run completed. No changes made."));return}if(!await w(`Do you want to download${t.configVersion?` version ${t.configVersion}`:" the latest version"} of these rules? This will overwrite your local configuration.`,{type:"confirm"})){r.info(Ve.default.yellow("Download cancelled."));return}let l=Rn(n,e);r.start("Saving configuration..."),await q(l,t.config),r.success(Ve.default.green("Successfully downloaded and updated configuration"))}var ni={};M(ni,{builder:()=>kr,command:()=>Ar,desc:()=>Pr,handler:()=>Lr});var Be=S(require("chalk")),vn=require("fs");T();var Ar="export",Pr="Export firewall configuration in various formats",kr={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},format:{alias:"f",type:"string",choices:["json","yaml","terraform","markdown"],description:"Export format",default:"json"},output:{alias:"o",type:"string",description:"Output file path"},source:{alias:"s",type:"string",choices:["local","remote"],description:"Export from local config or remote Vercel",default:"local"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}};function $r(i){let e=new Map;for(let t of i){let n=t.group??0,o=e.get(n);o?o.push(t):e.set(n,[t])}return[...e.values()]}var _r=i=>{let{rules:e,ips:t=[]}=i,n=i.metadata?.version,o=i.metadata?.updatedAt,s=`# Firewall Configuration Report
47
48
 
48
49
  `;return s+=`**Provider:** ${i.provider??"unknown"}
49
- `,s+=`**Version:** ${o??"unknown"}
50
- `,s+=`**Last Updated:** ${n?new Date(n).toLocaleString():"Unknown"}
50
+ `,s+=`**Version:** ${n??"unknown"}
51
+ `,s+=`**Last Updated:** ${o?new Date(o).toLocaleString():"Unknown"}
51
52
  `,s+=`**Generated:** ${new Date().toLocaleString()}
52
53
 
53
54
  `,s+=`## Custom Rules (${e.length})
@@ -60,7 +61,7 @@ Remote IP Blocking Rules to Download (${s.length}):
60
61
  `,s+=`- **Enabled:** ${a.enabled?"\u2705 Yes":"\u274C No"}
61
62
  `,a.action.rateLimit&&(s+=`- **Rate Limit:** ${a.action.rateLimit.requests} requests per ${a.action.rateLimit.window}
62
63
  `),s+=`- **Conditions:**
63
- `,Tr(a.conditions).forEach((c,d)=>{s+=` - Group ${d+1}:
64
+ `,$r(a.conditions).forEach((c,d)=>{s+=` - Group ${d+1}:
64
65
  `,c.forEach(u=>{s+=` - ${u.field} ${u.operator} \`${u.value}\`
65
66
  `})}),s+=`
66
67
  `}):s+=`No custom rules configured.
@@ -71,70 +72,70 @@ Remote IP Blocking Rules to Download (${s.length}):
71
72
  `,s+=`|------------|----------|--------|
72
73
  `,t.forEach(a=>{s+=`| \`${a.ip}\` | ${a.hostname||"N/A"} | ${a.action} |
73
74
  `})):s+=`No IP blocking rules configured.
74
- `,s},Pr=i=>{let{rules:e,ips:t=[]}=i,o=`# Firewall Configuration (${i.provider??"unknown"})
75
- `;return o+=`# Generated on ${new Date().toISOString()}
75
+ `,s},Sr=i=>{let{rules:e,ips:t=[]}=i,n=`# Firewall Configuration (${i.provider??"unknown"})
76
+ `;return n+=`# Generated on ${new Date().toISOString()}
76
77
 
77
- `,o+=`# Note: This is a conceptual Terraform configuration
78
- `,o+=`# A provider-specific Terraform provider would need to be implemented for actual use
78
+ `,n+=`# Note: This is a conceptual Terraform configuration
79
+ `,n+=`# A provider-specific Terraform provider would need to be implemented for actual use
79
80
 
80
- `,e.forEach((n,s)=>{o+=`resource "firewall_rule" "rule_${s}" {
81
- `,o+=` name = "${n.name}"
82
- `,o+=` description = "${n.description||""}"
83
- `,o+=` enabled = ${n.enabled}
84
- `,o+=` action = "${n.action.type}"
85
- `,n.action.rateLimit&&(o+=` rate_limit {
86
- `,o+=` requests = ${n.action.rateLimit.requests}
87
- `,o+=` window = "${n.action.rateLimit.window}"
88
- `,o+=` }
89
- `),o+=`}
81
+ `,e.forEach((o,s)=>{n+=`resource "firewall_rule" "rule_${s}" {
82
+ `,n+=` name = "${o.name}"
83
+ `,n+=` description = "${o.description||""}"
84
+ `,n+=` enabled = ${o.enabled}
85
+ `,n+=` action = "${o.action.type}"
86
+ `,o.action.rateLimit&&(n+=` rate_limit {
87
+ `,n+=` requests = ${o.action.rateLimit.requests}
88
+ `,n+=` window = "${o.action.rateLimit.window}"
89
+ `,n+=` }
90
+ `),n+=`}
90
91
 
91
- `}),t.forEach((n,s)=>{o+=`resource "firewall_ip_blocking_rule" "ip_${s}" {
92
- `,o+=` ip = "${n.ip}"
93
- `,o+=` hostname = "${n.hostname||""}"
94
- `,o+=` action = "${n.action}"
95
- `,o+=`}
92
+ `}),t.forEach((o,s)=>{n+=`resource "firewall_ip_blocking_rule" "ip_${s}" {
93
+ `,n+=` ip = "${o.ip}"
94
+ `,n+=` hostname = "${o.hostname||""}"
95
+ `,n+=` action = "${o.action}"
96
+ `,n+=`}
96
97
 
97
- `}),o},kr=async i=>{try{let e=i.output==="-"||!i.output,t;i.source==="remote"?await J({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"exporting configuration"},async({provider:a})=>{e||r.start("Fetching remote configuration..."),t=await a.fetchConfig()}):t=await j(i.config),e||r.start(`Exporting configuration in ${i.format} format...`);let o,n;switch(i.format){case"json":o=JSON.stringify(t,null,2),n="json";break;case"yaml":{let a=le(t);o=`# Firewall Configuration (${a.provider??"unknown"})
98
- `,o+=`version: ${a.metadata?.version??"unknown"}
99
- `,o+=`updatedAt: "${a.metadata?.updatedAt??""}"
100
- `,o+=`rules:
101
- `,a.rules.forEach(l=>{o+=` - name: "${l.name}"
102
- `,o+=` id: "${l.id??""}"
103
- `,o+=` enabled: ${l.enabled}
104
- `,o+=` action: "${l.action.type}"
105
- `}),n="yaml";break}case"terraform":o=Pr(le(t)),n="tf";break;case"markdown":o=Ar(le(t)),n="md";break;default:throw new Error(`Unsupported format: ${i.format}`)}let s=i.output||`firewall-export.${n}`;e?r.log(o):((0,wo.writeFileSync)(s,o,"utf8"),r.success(Be.default.green(`\u2705 Exported to ${s}`)),r.log(""),r.log(Be.default.bold("Export Summary:")),r.log(`${Be.default.dim("Format:")} ${i.format}`),r.log(`${Be.default.dim("Source:")} ${i.source}`),r.log(`${Be.default.dim("Rules:")} ${t.rules.length} custom, ${(t.ips||[]).length} IP blocking`),r.log(`${Be.default.dim("Size:")} ${(o.length/1024).toFixed(1)} KB`))}catch(e){Z(e,"exporting configuration")}};var ii={};M(ii,{BASIC_TEMPLATE_RULES:()=>Ro,SECURITY_FOCUSED_TEMPLATE_RULES:()=>Co,builder:()=>Sr,command:()=>$r,desc:()=>_r,handler:()=>xr});var y=S(require("chalk")),Io=require("fs");T();pe();var Ro=[{id:"rule_block_bad_bots",name:"Block Bad Bots",description:"Block known malicious bots and crawlers based on user agent patterns",conditionGroup:[{conditions:[{type:"user_agent",op:"sub",value:"bot"}]}],action:{mitigate:{action:"deny"}},active:!1},{id:"rule_block_scrapers",name:"Block Scrapers",description:"Block common scraping tools and automated requests",conditionGroup:[{conditions:[{type:"user_agent",op:"sub",value:"scraper"}]}],action:{mitigate:{action:"deny"}},active:!1}],Co=[{id:"rule_rate_limit_api",name:"Rate Limit API",description:"Rate limit API endpoints to prevent abuse and DoS attacks",conditionGroup:[{conditions:[{type:"path",op:"pre",value:"/api/"}]}],action:{mitigate:{action:"rate_limit",rateLimit:{requests:100,window:"1m"}}},active:!1},{id:"rule_block_suspicious_ips",name:"Block Suspicious IPs",description:"Block requests from a known suspicious IP range",conditionGroup:[{conditions:[{type:"ip_address",op:"eq",value:"10.0.0.0/24"}]}],action:{mitigate:{action:"deny"}},active:!1},{id:"rule_protect_admin",name:"Protect Admin Routes",description:"Add extra protection for admin and sensitive routes",conditionGroup:[{conditions:[{type:"path",op:"pre",value:"/admin"}]}],action:{mitigate:{action:"rate_limit",rateLimit:{requests:10,window:"1m"}}},active:!1}],$r="init [template]",_r="Initialize a new Doorman configuration",Sr={template:{type:"string",description:"Template to use for initialization (empty, basic, or security-focused)",choices:["empty","basic","security-focused"],default:"empty"},config:{alias:"c",type:"string",description:"Path for the new config file",default:".doorman.json"},force:{alias:"f",type:"boolean",description:"Overwrite existing config file",default:!1},interactive:{alias:"i",type:"boolean",description:"Interactive setup with guided prompts",default:!0},projectId:{alias:"p",type:"string",description:"Vercel Project ID"},teamId:{alias:"t",type:"string",description:"Vercel Team ID"}},Lr=()=>{r.log(""),r.log(y.default.bold.cyan("\u{1F6AA} Welcome to Doorman!")),r.log(y.default.dim(`Let's set up your firewall configuration.
106
- `))},Ur=()=>{r.log(y.default.bold(`
107
- \u{1F4DA} Helpful Resources:`)),r.log(""),r.log(y.default.cyan("\u{1F517} Find your Project ID:")),r.log(y.default.dim(" https://vercel.com/dashboard \u2192 Select your project \u2192 Settings \u2192 General")),r.log(""),r.log(y.default.cyan("\u{1F517} Find your Team ID:")),r.log(y.default.dim(" https://vercel.com/dashboard \u2192 Team Settings \u2192 General")),r.log(y.default.dim(" (Leave empty if using personal account)")),r.log(""),r.log(y.default.cyan("\u{1F517} Create API Token:")),r.log(y.default.dim(" https://vercel.com/account/tokens \u2192 Create Token")),r.log(y.default.dim(" Scopes needed: Read & Write for your project")),r.log(""),r.log(y.default.cyan("\u{1F517} Documentation:")),r.log(y.default.dim(" https://doorman.griffen.codes/getting-started")),r.log("")},Dr=async i=>{let e=i.projectId,t=i.teamId;return i.interactive&&(r.log(y.default.bold("\u{1F4CB} Project Configuration")),r.log(y.default.dim(`We need your Vercel project details to configure the firewall.
108
- `)),e||(e=await w("Enter your Vercel Project ID:",{type:"text"})),t||await w("Are you using a Vercel team account?",{type:"confirm"})&&(t=await w("Enter your Vercel Team ID:",{type:"text"})),process.env.VERCEL_TOKEN?r.log(y.default.green("\u2705 VERCEL_TOKEN environment variable found")):(r.log(""),r.log(y.default.yellow("\u26A0\uFE0F VERCEL_TOKEN environment variable not found")),r.log(y.default.dim("You'll need to set this before running sync commands.")),await w("Would you like to see how to create an API token?",{type:"confirm"})&&(r.log(""),r.log(y.default.bold("\u{1F511} Creating a Vercel API Token:")),r.log("1. Go to https://vercel.com/account/tokens"),r.log('2. Click "Create Token"'),r.log('3. Give it a descriptive name (e.g., "Doorman Firewall")'),r.log("4. Set expiration as needed"),r.log("5. Copy the token and set it as an environment variable:"),r.log(""),r.log(y.default.cyan(' export VERCEL_TOKEN="your-token-here"')),r.log(y.default.dim(" # Add this to your ~/.bashrc, ~/.zshrc, or .env file")),r.log("")))),{projectId:e,teamId:t}},xr=async i=>{try{let e=i.config||".doorman.json";if(i.interactive&&Lr(),(0,Io.existsSync)(e)&&!i.force&&!await w(`Config file ${e} already exists. Do you want to overwrite it?`,{type:"confirm"})){r.info(y.default.yellow("Initialization cancelled."));return}let{projectId:t,teamId:o}=await Dr(i);i.interactive&&(r.log(""),r.log(y.default.bold("\u{1F3A8} Template Selection")),r.log(y.default.dim(`Choose a starting template for your firewall configuration:
109
- `)),r.log(y.default.cyan("\u{1F4DD} empty")+y.default.dim(" - Minimal config, add your own rules")),r.log(y.default.cyan("\u{1F6E1}\uFE0F basic")+y.default.dim(" - Includes basic bot protection")),r.log(y.default.cyan("\u{1F512} security-focused")+y.default.dim(" - Comprehensive security rules")),r.log(""));let n=i.template;i.interactive&&!i.template&&(n=await w("Select a template:",{type:"select",options:["empty","basic","security-focused"],initial:"empty"})),r.start(`Creating ${n} configuration...`);let s=ht();switch(t&&(s.projectId=t),o&&(s.teamId=o),n){case"basic":s={...s,rules:Ro};break;case"security-focused":s={...s,rules:Co};break;default:break}await q(s,e),r.success(y.default.green(`\u2705 Created ${e}`)),r.log(""),r.log(y.default.bold("\u{1F4CB} Configuration Summary:")),r.log(`${y.default.dim("File:")} ${e}`),r.log(`${y.default.dim("Template:")} ${n}`),r.log(`${y.default.dim("Project ID:")} ${t||y.default.yellow("Not set - add manually")}`),r.log(`${y.default.dim("Team ID:")} ${o||y.default.dim("None (personal account)")}`),r.log(`${y.default.dim("Rules:")} ${s.rules.length} (all disabled for safety)`),r.log(""),r.log(y.default.bold("\u{1F680} Next Steps:")),t||r.log(`1. ${y.default.yellow("Add your projectId")} to ${e}`),process.env.VERCEL_TOKEN||r.log(`${t?"1":"2"}. ${y.default.yellow("Set VERCEL_TOKEN")} environment variable`);let a=t?process.env.VERCEL_TOKEN?1:2:3;r.log(`${a}. ${y.default.dim("Review and enable rules in")} ${e}`),r.log(`${a+1}. ${y.default.dim("Run")} ${y.default.cyan("doorman validate")} ${y.default.dim("to check your config")}`),r.log(`${a+2}. ${y.default.dim("Run")} ${y.default.cyan("doorman status")} ${y.default.dim("to see sync status")}`),r.log(`${a+3}. ${y.default.dim("Run")} ${y.default.cyan("doorman sync")} ${y.default.dim("to deploy your rules")}`),n!=="empty"&&(r.log(""),r.log(y.default.yellow("\u26A0\uFE0F All template rules are disabled by default for safety.")),r.log(y.default.dim(" Review each rule and set active: true when ready."))),i.interactive&&(!t||!process.env.VERCEL_TOKEN)&&Ur()}catch(e){Z(e,"initializing configuration")}};var oi={};M(oi,{builder:()=>Nr,command:()=>Or,desc:()=>Fr,handler:()=>Vr});var ce=S(require("chalk")),vo=require("zod");T();var Or="list [configVersion]",Fr="List Vercel Firewall rules, optionally for a specific configuration version",Nr={configVersion:{type:"number",description:"Specific configuration version to fetch (defaults to latest)"},provider:Y,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file or VERCEL_PROJECT_ID environment variable)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file or VERCEL_TEAM_ID environment variable)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},format:{alias:"f",type:"string",description:"Output format (json or table)",choices:["json","table"],default:"table"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Vr=async i=>{await J({provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,optionalConfig:!0,skipValidation:!0,errorContext:"listing firewall rules"},async({provider:e})=>{if(i.configVersion!==void 0)try{ft.parse(i.configVersion)}catch(t){throw t instanceof vo.z.ZodError&&(r.error("Invalid configuration version number. Version must be a positive integer."),process.exit(1)),t}await Br(e,i)})};async function Br(i,e){let t=e.format==="json";t||r.start(`Fetching firewall configuration${e.configVersion?` version ${e.configVersion}`:""} ...`);let o=await i.fetchConfig(e.configVersion),n=o.rules,s=o.ips??[],a=o.metadata?.version??o.version,l=o.metadata?.updatedAt;if(t){r.log(JSON.stringify({version:a,updatedAt:l,rules:n,ips:s},null,2));return}if(r.info(`Found ${ce.default.cyan(n.length)} custom rules and ${ce.default.cyan(s.length)} IP blocking rules
110
- `+ce.default.dim(`Version: ${ce.default.yellow(a??"unknown")}${l?` \u2022 Last Updated: ${ce.default.yellow(l)}`:""}`)),n.length===0&&s.length===0){r.info(ce.default.yellow("No rules found"));return}n.length>0?(r.log(ce.default.bold.underline(`
98
+ `}),n},Lr=async i=>{try{let e=i.output==="-"||!i.output,t;i.source==="remote"?await Q({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"exporting configuration"},async({provider:a})=>{e||r.start("Fetching remote configuration..."),t=await a.fetchConfig()}):t=await j(i.config),e||r.start(`Exporting configuration in ${i.format} format...`);let n,o;switch(i.format){case"json":n=JSON.stringify(t,null,2),o="json";break;case"yaml":{let a=le(t);n=`# Firewall Configuration (${a.provider??"unknown"})
99
+ `,n+=`version: ${a.metadata?.version??"unknown"}
100
+ `,n+=`updatedAt: "${a.metadata?.updatedAt??""}"
101
+ `,n+=`rules:
102
+ `,a.rules.forEach(l=>{n+=` - name: "${l.name}"
103
+ `,n+=` id: "${l.id??""}"
104
+ `,n+=` enabled: ${l.enabled}
105
+ `,n+=` action: "${l.action.type}"
106
+ `}),o="yaml";break}case"terraform":n=Sr(le(t)),o="tf";break;case"markdown":n=_r(le(t)),o="md";break;default:throw new Error(`Unsupported format: ${i.format}`)}let s=i.output||`firewall-export.${o}`;e?r.log(n):((0,vn.writeFileSync)(s,n,"utf8"),r.success(Be.default.green(`\u2705 Exported to ${s}`)),r.log(""),r.log(Be.default.bold("Export Summary:")),r.log(`${Be.default.dim("Format:")} ${i.format}`),r.log(`${Be.default.dim("Source:")} ${i.source}`),r.log(`${Be.default.dim("Rules:")} ${t.rules.length} custom, ${(t.ips||[]).length} IP blocking`),r.log(`${Be.default.dim("Size:")} ${(n.length/1024).toFixed(1)} KB`))}catch(e){Y(e,"exporting configuration")}};var oi={};M(oi,{BASIC_TEMPLATE_RULES:()=>En,SECURITY_FOCUSED_TEMPLATE_RULES:()=>Tn,builder:()=>xr,command:()=>Ur,desc:()=>Dr,handler:()=>Br});var y=S(require("chalk")),bn=require("fs");T();pe();var En=[{id:"rule_block_bad_bots",name:"Block Bad Bots",description:"Block known malicious bots and crawlers based on user agent patterns",conditionGroup:[{conditions:[{type:"user_agent",op:"sub",value:"bot"}]}],action:{mitigate:{action:"deny"}},active:!1},{id:"rule_block_scrapers",name:"Block Scrapers",description:"Block common scraping tools and automated requests",conditionGroup:[{conditions:[{type:"user_agent",op:"sub",value:"scraper"}]}],action:{mitigate:{action:"deny"}},active:!1}],Tn=[{id:"rule_rate_limit_api",name:"Rate Limit API",description:"Rate limit API endpoints to prevent abuse and DoS attacks",conditionGroup:[{conditions:[{type:"path",op:"pre",value:"/api/"}]}],action:{mitigate:{action:"rate_limit",rateLimit:{requests:100,window:"1m"}}},active:!1},{id:"rule_block_suspicious_ips",name:"Block Suspicious IPs",description:"Block requests from a known suspicious IP range",conditionGroup:[{conditions:[{type:"ip_address",op:"eq",value:"10.0.0.0/24"}]}],action:{mitigate:{action:"deny"}},active:!1},{id:"rule_protect_admin",name:"Protect Admin Routes",description:"Add extra protection for admin and sensitive routes",conditionGroup:[{conditions:[{type:"path",op:"pre",value:"/admin"}]}],action:{mitigate:{action:"rate_limit",rateLimit:{requests:10,window:"1m"}}},active:!1}],Ur="init [template]",Dr="Initialize a new Doorman configuration",xr={template:{type:"string",description:"Template to use for initialization (empty, basic, or security-focused)",choices:["empty","basic","security-focused"]},config:{alias:"c",type:"string",description:"Path for the new config file",default:".doorman.json"},force:{alias:"f",type:"boolean",description:"Overwrite existing config file",default:!1},interactive:{alias:"i",type:"boolean",description:"Interactive setup with guided prompts (default: on unless a template is given positionally)"},projectId:{alias:"p",type:"string",description:"Vercel Project ID"},teamId:{alias:"t",type:"string",description:"Vercel Team ID"}},Or=()=>{r.log(""),r.log(y.default.bold.cyan("\u{1F6AA} Welcome to Doorman!")),r.log(y.default.dim(`Let's set up your firewall configuration.
107
+ `))},Fr=()=>{r.log(y.default.bold(`
108
+ \u{1F4DA} Helpful Resources:`)),r.log(""),r.log(y.default.cyan("\u{1F517} Find your Project ID:")),r.log(y.default.dim(" https://vercel.com/dashboard \u2192 Select your project \u2192 Settings \u2192 General")),r.log(""),r.log(y.default.cyan("\u{1F517} Find your Team ID:")),r.log(y.default.dim(" https://vercel.com/dashboard \u2192 Team Settings \u2192 General")),r.log(y.default.dim(" (Leave empty if using personal account)")),r.log(""),r.log(y.default.cyan("\u{1F517} Create API Token:")),r.log(y.default.dim(" https://vercel.com/account/tokens \u2192 Create Token")),r.log(y.default.dim(" Scopes needed: Read & Write for your project")),r.log(""),r.log(y.default.cyan("\u{1F517} Documentation:")),r.log(y.default.dim(" https://doorman.griffen.codes/getting-started")),r.log("")};function Nr(i){return i.interactive??i.template===void 0}var Vr=async(i,e)=>{let t=i.projectId,n=i.teamId;return e&&(r.log(y.default.bold("\u{1F4CB} Project Configuration")),r.log(y.default.dim(`We need your Vercel project details to configure the firewall.
109
+ `)),t||(t=await w("Enter your Vercel Project ID:",{type:"text"})),n||await w("Are you using a Vercel team account?",{type:"confirm"})&&(n=await w("Enter your Vercel Team ID:",{type:"text"})),process.env.VERCEL_TOKEN?r.log(y.default.green("\u2705 VERCEL_TOKEN environment variable found")):(r.log(""),r.log(y.default.yellow("\u26A0\uFE0F VERCEL_TOKEN environment variable not found")),r.log(y.default.dim("You'll need to set this before running sync commands.")),await w("Would you like to see how to create an API token?",{type:"confirm"})&&(r.log(""),r.log(y.default.bold("\u{1F511} Creating a Vercel API Token:")),r.log("1. Go to https://vercel.com/account/tokens"),r.log('2. Click "Create Token"'),r.log('3. Give it a descriptive name (e.g., "Doorman Firewall")'),r.log("4. Set expiration as needed"),r.log("5. Copy the token and set it as an environment variable:"),r.log(""),r.log(y.default.cyan(' export VERCEL_TOKEN="your-token-here"')),r.log(y.default.dim(" # Add this to your ~/.bashrc, ~/.zshrc, or .env file")),r.log("")))),{projectId:t,teamId:n}},Br=async i=>{try{let e=i.config||".doorman.json",t=Nr(i);if(t&&Or(),(0,bn.existsSync)(e)&&!i.force&&!await w(`Config file ${e} already exists. Do you want to overwrite it?`,{type:"confirm"})){r.info(y.default.yellow("Initialization cancelled."));return}let{projectId:n,teamId:o}=await Vr(i,t);t&&(r.log(""),r.log(y.default.bold("\u{1F3A8} Template Selection")),r.log(y.default.dim(`Choose a starting template for your firewall configuration:
110
+ `)),r.log(y.default.cyan("\u{1F4DD} empty")+y.default.dim(" - Minimal config, add your own rules")),r.log(y.default.cyan("\u{1F6E1}\uFE0F basic")+y.default.dim(" - Includes basic bot protection")),r.log(y.default.cyan("\u{1F512} security-focused")+y.default.dim(" - Comprehensive security rules")),r.log(""));let s=i.template??"empty";t&&!i.template&&(s=await w("Select a template:",{type:"select",options:["empty","basic","security-focused"],initial:"empty"})),r.start(`Creating ${s} configuration...`);let a=wt();switch(n&&(a.projectId=n),o&&(a.teamId=o),s){case"basic":a={...a,rules:En};break;case"security-focused":a={...a,rules:Tn};break;default:break}await q(a,e),r.success(y.default.green(`\u2705 Created ${e}`)),r.log(""),r.log(y.default.bold("\u{1F4CB} Configuration Summary:")),r.log(`${y.default.dim("File:")} ${e}`),r.log(`${y.default.dim("Template:")} ${s}`),r.log(`${y.default.dim("Project ID:")} ${n||y.default.yellow("Not set - add manually")}`),r.log(`${y.default.dim("Team ID:")} ${o||y.default.dim("None (personal account)")}`),r.log(`${y.default.dim("Rules:")} ${a.rules.length} (all disabled for safety)`),r.log(""),r.log(y.default.bold("\u{1F680} Next Steps:")),n||r.log(`1. ${y.default.yellow("Add your projectId")} to ${e}`),process.env.VERCEL_TOKEN||r.log(`${n?"1":"2"}. ${y.default.yellow("Set VERCEL_TOKEN")} environment variable`);let l=n?process.env.VERCEL_TOKEN?1:2:3;r.log(`${l}. ${y.default.dim("Review and enable rules in")} ${e}`),r.log(`${l+1}. ${y.default.dim("Run")} ${y.default.cyan("doorman validate")} ${y.default.dim("to check your config")}`),r.log(`${l+2}. ${y.default.dim("Run")} ${y.default.cyan("doorman status")} ${y.default.dim("to see sync status")}`),r.log(`${l+3}. ${y.default.dim("Run")} ${y.default.cyan("doorman sync")} ${y.default.dim("to deploy your rules")}`),s!=="empty"&&(r.log(""),r.log(y.default.yellow("\u26A0\uFE0F All template rules are disabled by default for safety.")),r.log(y.default.dim(" Review each rule and set active: true when ready."))),t&&(!n||!process.env.VERCEL_TOKEN)&&Fr()}catch(e){Y(e,"initializing configuration")}};var ri={};M(ri,{builder:()=>qr,command:()=>Wr,desc:()=>jr,handler:()=>zr});var ce=S(require("chalk")),An=require("zod");T();var Wr="list [configVersion]",jr="List Vercel Firewall rules, optionally for a specific configuration version",qr={configVersion:{type:"number",description:"Specific configuration version to fetch (defaults to latest)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file or VERCEL_PROJECT_ID environment variable)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file or VERCEL_TEAM_ID environment variable)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},format:{alias:"f",type:"string",description:"Output format (json or table)",choices:["json","table"],default:"table"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},zr=async i=>{await Q({provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,optionalConfig:!0,skipValidation:!0,errorContext:"listing firewall rules"},async({provider:e})=>{if(i.configVersion!==void 0)try{mt.parse(i.configVersion)}catch(t){throw t instanceof An.z.ZodError&&(r.error("Invalid configuration version number. Version must be a positive integer."),process.exit(1)),t}await Mr(e,i)})};async function Mr(i,e){let t=e.format==="json";t||r.start(`Fetching firewall configuration${e.configVersion?` version ${e.configVersion}`:""} ...`);let n=await i.fetchConfig(e.configVersion),o=n.rules,s=n.ips??[],a=n.metadata?.version??n.version,l=n.metadata?.updatedAt;if(t){r.log(JSON.stringify({version:a,updatedAt:l,rules:o,ips:s},null,2));return}if(r.info(`Found ${ce.default.cyan(o.length)} custom rules and ${ce.default.cyan(s.length)} IP blocking rules
111
+ `+ce.default.dim(`Version: ${ce.default.yellow(a??"unknown")}${l?` \u2022 Last Updated: ${ce.default.yellow(l)}`:""}`)),o.length===0&&s.length===0){r.info(ce.default.yellow("No rules found"));return}o.length>0?(r.log(ce.default.bold.underline(`
111
112
  Custom Rules:`),`
112
- `),n.forEach(c=>r.log(` - ${c.name}${c.enabled?"":ce.default.dim(" (disabled)")}`))):r.info(ce.default.cyan("No custom rules found")),s.length>0?(r.log(ce.default.bold.underline(`
113
+ `),o.forEach(c=>r.log(` - ${c.name}${c.enabled?"":ce.default.dim(" (disabled)")}`))):r.info(ce.default.cyan("No custom rules found")),s.length>0?(r.log(ce.default.bold.underline(`
113
114
  IP Blocking Rules:`),`
114
- `),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info(ce.default.cyan("No IP blocking rules found"))}var ri={};M(ri,{aliases:()=>jr,builder:()=>zr,command:()=>Wr,desc:()=>qr,findFuzzyMatches:()=>Po,handler:()=>Mr,levenshtein:()=>Ao});var U=S(require("chalk")),To=require("consola");T();pe();var Wr="remove [type]",jr=["rm","delete"],qr="Remove a firewall rule or IP entry from your configuration",zr={type:{type:"string",description:'What to remove: "rule" (default) or "ip"',default:"rule",choices:["rule","ip"]},interactive:{alias:"i",type:"boolean",description:"Select rules to remove from a list",default:!1},name:{alias:"n",type:"string",description:"Remove rule by name (exact match)"},id:{type:"array",string:!0,description:"Remove rule by ID (supports multiple)"},ip:{type:"string",description:"Remove IP rule by IP address"},disabled:{type:"boolean",description:"Remove all disabled (active: false) rules",default:!1},all:{type:"boolean",description:"Remove all rules (requires confirmation)",default:!1},force:{alias:"f",type:"boolean",description:"Skip confirmation prompt",default:!1},config:{alias:"c",type:"string",description:"Config file path"},dryRun:{alias:"d",type:"boolean",description:"Show what would be removed without writing",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1}};function Ao(i,e){let t=i.length,o=e.length;if(t===0)return o;if(o===0)return t;let n=Array.from({length:t+1},(a,l)=>l),s=new Array(t+1).fill(0);for(let a=1;a<=o;a++){s[0]=a;for(let l=1;l<=t;l++)e.charAt(a-1)===i.charAt(l-1)?s[l]=n[l-1]:s[l]=Math.min(n[l-1]+1,s[l-1]+1,n[l]+1);for(let l=0;l<=t;l++)n[l]=s[l]}return n[t]}function Po(i,e,t=3){let o=i.toLowerCase(),n=e.filter(l=>l.name.toLowerCase().includes(o)||o.includes(l.name.toLowerCase()));if(n.length>0)return n.slice(0,t);let s=e.map(l=>({rule:l,distance:Ao(o,l.name.toLowerCase())})).sort((l,c)=>l.distance-c.distance),a=Math.max(i.length*.6,3);return s.filter(l=>l.distance<=a).slice(0,t).map(l=>l.rule)}function ni(i){for(let e of i){let t=e.id?` (${e.id})`:"",o=e.active?"":U.default.dim(" [disabled]"),n=e.action.mitigate.action;r.log(U.default.dim(` - ${e.name}${t} \u2014 ${n}${o}`))}}function bo(i){for(let e of i){let t=e.notes?` \u2014 ${e.notes}`:"";r.log(U.default.dim(` - ${e.ip}${t}`))}}async function Eo(i,e,t,o="rule"){if(e)return!0;if(t)return await w(U.default.red(`\u26A0\uFE0F Are you sure you want to remove ALL ${o}s? Type "YES" to confirm:`),{type:"text"})==="YES";let n=i===1?`Confirm removal of 1 ${o}?`:`Confirm removal of ${i} ${o}s?`;return await w(n,{type:"confirm",initial:!1})}var Mr=async i=>{try{i.debug&&(r.level=To.LogLevels.debug),r.debug("Remove command arguments:",i);let e=i.type||"rule";r.start("Loading configuration...");let t=await j(i.config);if(e==="ip"){let o=t.ips||[];if(o.length===0){r.info("No IP rules in configuration.");return}let n=[];if(i.interactive){let l=o.map(d=>{let u=d.notes?` \u2014 ${d.notes}`:"";return`${d.ip}${u}`}),c=await w("Select IP rules to remove:",{type:"multiselect",options:l});n=o.filter(d=>{let u=`${d.ip}${d.notes?` \u2014 ${d.notes}`:""}`;return c.includes(u)})}else i.ip?(n=o.filter(l=>l.ip===i.ip),n.length===0&&(r.error(U.default.red(`No IP rule found matching "${i.ip}"`)),o.length>0&&(r.log(U.default.dim(`
115
- Current IP rules:`)),bo(o)),process.exit(1))):i.all?n=[...o]:(r.error("Specify --ip, --interactive, or --all to select IP rules to remove."),process.exit(1));if(n.length===0){r.info("No IP rules selected for removal.");return}if(r.log(U.default.cyan(`
116
- ${i.dryRun?"Would remove":"Removing"} ${n.length} IP rule(s):`)),bo(n),i.dryRun){r.log(U.default.dim(`
117
- Dry run \u2014 no changes made.`));return}if(!await Eo(n.length,i.force||!1,i.all||!1,"IP rule")){r.info("Cancelled.");return}let s=new Set(n.map(l=>l.ip)),a={...t,ips:o.filter(l=>!s.has(l.ip))};await q(a,i.config),r.success(U.default.green(`\u2714 Removed ${n.length} IP rule(s) from configuration`))}else{let o=t.rules||[];if(o.length===0){r.info("No rules in configuration.");return}let n=[];if(i.interactive){let l=o.map((d,u)=>{let p=d.id?` (${d.id})`:"",g=d.active?"":" [disabled]",h=d.action.mitigate.action;return`[${u}] ${d.name}${p} \u2014 ${h}${g}`}),c=await w("Select rules to remove:",{type:"multiselect",options:l});n=o.filter((d,u)=>c.some(p=>p.startsWith(`[${u}]`)))}else if(i.name){if(n=o.filter(l=>l.name===i.name),n.length>1&&(r.warn(U.default.yellow(`
118
- \u26A0\uFE0F Found ${n.length} rules named "${i.name}". All will be removed.`)),ni(n)),n.length===0){r.error(U.default.red(`No rule found with exact name "${i.name}"`));let l=Po(i.name,o);l.length>0&&(r.log(U.default.yellow(`
119
- Did you mean one of these?`)),l.forEach((c,d)=>{let u=c.id?` (${c.id})`:"";r.log(U.default.dim(` ${d+1}. ${c.name}${u}`))}),r.log(U.default.dim(`
120
- Use --id for exact matching, or --interactive to select from a list.`))),process.exit(1)}}else if(i.id&&i.id.length>0){let l=new Set(i.id);n=o.filter(u=>u.id&&l.has(u.id));let c=new Set(n.map(u=>u.id)),d=i.id.filter(u=>!c.has(u));d.length>0&&r.warn(U.default.yellow(`No rules found for IDs: ${d.join(", ")}`)),n.length===0&&(r.error(U.default.red("No matching rules found for the given IDs.")),process.exit(1))}else if(i.disabled){if(n=o.filter(l=>!l.active),n.length===0){r.info("No disabled rules found.");return}}else i.all?n=[...o]:(r.error("Specify --name, --id, --disabled, --all, or --interactive to select rules to remove."),process.exit(1));if(n.length===0){r.info("No rules selected for removal.");return}if(n.length>=5&&!i.dryRun&&!i.force&&r.log(U.default.yellow(`
121
- \u{1F4A1} Tip: Run ${U.default.cyan("doorman backup")} before bulk removal operations.`)),r.log(U.default.cyan(`
122
- ${i.dryRun?"Would remove":"Removing"} ${n.length} rule(s):`)),ni(n),i.dryRun){r.log(U.default.dim(`
123
- Dry run \u2014 no changes made.`));return}if(!await Eo(n.length,i.force||!1,i.all||!1)){r.info("Cancelled.");return}let s=new Set(n),a={...t,rules:o.filter(l=>!s.has(l))};a.rules.length===0&&r.warn(U.default.yellow("\u26A0\uFE0F Configuration will have no rules after removal.")),await q(a,i.config),r.success(U.default.green(`\u2714 Removed ${n.length} rule(s) from configuration`)),ni(n)}r.log(""),r.log(U.default.dim(`Run ${U.default.cyan("doorman sync")} to deploy these changes.`))}catch(e){Z(e,"removing rule")}};var si={};M(si,{builder:()=>Hr,command:()=>Gr,desc:()=>Kr,handler:()=>Zr});var P=S(require("chalk"));T();var Gr="setup",Kr="Show setup instructions and helpful links for Doorman",Hr={},Zr=async i=>{r.log(""),r.log(P.default.bold.cyan("\u{1F6AA} Doorman Setup Guide")),r.log(P.default.dim(`Everything you need to get started with firewall management
115
+ `),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info(ce.default.cyan("No IP blocking rules found"))}var ai={};M(ai,{aliases:()=>Kr,builder:()=>Zr,command:()=>Gr,desc:()=>Hr,findFuzzyMatches:()=>Sn,handler:()=>Yr,levenshtein:()=>_n});var D=S(require("chalk")),$n=require("consola");T();pe();var Gr="remove [type]",Kr=["rm","delete"],Hr="Remove a firewall rule or IP entry from your configuration",Zr={type:{type:"string",description:'What to remove: "rule" (default) or "ip"',default:"rule",choices:["rule","ip"]},interactive:{alias:"i",type:"boolean",description:"Select rules to remove from a list",default:!1},name:{alias:"n",type:"string",description:"Remove rule by name (exact match)"},id:{type:"array",string:!0,description:"Remove rule by ID (supports multiple)"},ip:{type:"string",description:"Remove IP rule by IP address"},disabled:{type:"boolean",description:"Remove all disabled (active: false) rules",default:!1},all:{type:"boolean",description:"Remove all rules (requires confirmation)",default:!1},force:{alias:"f",type:"boolean",description:"Skip confirmation prompt",default:!1},config:{alias:"c",type:"string",description:"Config file path"},dryRun:{alias:"d",type:"boolean",description:"Show what would be removed without writing",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1}};function _n(i,e){let t=i.length,n=e.length;if(t===0)return n;if(n===0)return t;let o=Array.from({length:t+1},(a,l)=>l),s=new Array(t+1).fill(0);for(let a=1;a<=n;a++){s[0]=a;for(let l=1;l<=t;l++)e.charAt(a-1)===i.charAt(l-1)?s[l]=o[l-1]:s[l]=Math.min(o[l-1]+1,s[l-1]+1,o[l]+1);for(let l=0;l<=t;l++)o[l]=s[l]}return o[t]}function Sn(i,e,t=3){let n=i.toLowerCase(),o=e.filter(l=>l.name.toLowerCase().includes(n)||n.includes(l.name.toLowerCase()));if(o.length>0)return o.slice(0,t);let s=e.map(l=>({rule:l,distance:_n(n,l.name.toLowerCase())})).sort((l,c)=>l.distance-c.distance),a=Math.max(i.length*.6,3);return s.filter(l=>l.distance<=a).slice(0,t).map(l=>l.rule)}function si(i){for(let e of i){let t=e.id?` (${e.id})`:"",n=e.active?"":D.default.dim(" [disabled]"),o=e.action.mitigate.action;r.log(D.default.dim(` - ${e.name}${t} \u2014 ${o}${n}`))}}function Pn(i){for(let e of i){let t=e.notes?` \u2014 ${e.notes}`:"";r.log(D.default.dim(` - ${e.ip}${t}`))}}async function kn(i,e,t,n="rule"){if(e)return!0;if(t)return await w(D.default.red(`\u26A0\uFE0F Are you sure you want to remove ALL ${n}s? Type "YES" to confirm:`),{type:"text"})==="YES";let o=i===1?`Confirm removal of 1 ${n}?`:`Confirm removal of ${i} ${n}s?`;return await w(o,{type:"confirm",initial:!1})}var Yr=async i=>{try{i.debug&&(r.level=$n.LogLevels.debug),r.debug("Remove command arguments:",i);let e=i.type||"rule";r.start("Loading configuration...");let t=await j(i.config);if(e==="ip"){let n=t.ips||[];if(n.length===0){r.info("No IP rules in configuration.");return}let o=[];if(i.interactive){let l=n.map(d=>{let u=d.notes?` \u2014 ${d.notes}`:"";return`${d.ip}${u}`}),c=await w("Select IP rules to remove:",{type:"multiselect",options:l});o=n.filter(d=>{let u=`${d.ip}${d.notes?` \u2014 ${d.notes}`:""}`;return c.includes(u)})}else i.ip?(o=n.filter(l=>l.ip===i.ip),o.length===0&&(r.error(D.default.red(`No IP rule found matching "${i.ip}"`)),n.length>0&&(r.log(D.default.dim(`
116
+ Current IP rules:`)),Pn(n)),process.exit(1))):i.all?o=[...n]:(r.error("Specify --ip, --interactive, or --all to select IP rules to remove."),process.exit(1));if(o.length===0){r.info("No IP rules selected for removal.");return}if(r.log(D.default.cyan(`
117
+ ${i.dryRun?"Would remove":"Removing"} ${o.length} IP rule(s):`)),Pn(o),i.dryRun){r.log(D.default.dim(`
118
+ Dry run \u2014 no changes made.`));return}if(!await kn(o.length,i.force||!1,i.all||!1,"IP rule")){r.info("Cancelled.");return}let s=new Set(o.map(l=>l.ip)),a={...t,ips:n.filter(l=>!s.has(l.ip))};await q(a,i.config),r.success(D.default.green(`\u2714 Removed ${o.length} IP rule(s) from configuration`))}else{let n=t.rules||[];if(n.length===0){r.info("No rules in configuration.");return}let o=[];if(i.interactive){let l=n.map((d,u)=>{let p=d.id?` (${d.id})`:"",g=d.active?"":" [disabled]",h=d.action.mitigate.action;return`[${u}] ${d.name}${p} \u2014 ${h}${g}`}),c=await w("Select rules to remove:",{type:"multiselect",options:l});o=n.filter((d,u)=>c.some(p=>p.startsWith(`[${u}]`)))}else if(i.name){if(o=n.filter(l=>l.name===i.name),o.length>1&&(r.warn(D.default.yellow(`
119
+ \u26A0\uFE0F Found ${o.length} rules named "${i.name}". All will be removed.`)),si(o)),o.length===0){r.error(D.default.red(`No rule found with exact name "${i.name}"`));let l=Sn(i.name,n);l.length>0&&(r.log(D.default.yellow(`
120
+ Did you mean one of these?`)),l.forEach((c,d)=>{let u=c.id?` (${c.id})`:"";r.log(D.default.dim(` ${d+1}. ${c.name}${u}`))}),r.log(D.default.dim(`
121
+ Use --id for exact matching, or --interactive to select from a list.`))),process.exit(1)}}else if(i.id&&i.id.length>0){let l=new Set(i.id);o=n.filter(u=>u.id&&l.has(u.id));let c=new Set(o.map(u=>u.id)),d=i.id.filter(u=>!c.has(u));d.length>0&&r.warn(D.default.yellow(`No rules found for IDs: ${d.join(", ")}`)),o.length===0&&(r.error(D.default.red("No matching rules found for the given IDs.")),process.exit(1))}else if(i.disabled){if(o=n.filter(l=>!l.active),o.length===0){r.info("No disabled rules found.");return}}else i.all?o=[...n]:(r.error("Specify --name, --id, --disabled, --all, or --interactive to select rules to remove."),process.exit(1));if(o.length===0){r.info("No rules selected for removal.");return}if(o.length>=5&&!i.dryRun&&!i.force&&r.log(D.default.yellow(`
122
+ \u{1F4A1} Tip: Run ${D.default.cyan("doorman backup")} before bulk removal operations.`)),r.log(D.default.cyan(`
123
+ ${i.dryRun?"Would remove":"Removing"} ${o.length} rule(s):`)),si(o),i.dryRun){r.log(D.default.dim(`
124
+ Dry run \u2014 no changes made.`));return}if(!await kn(o.length,i.force||!1,i.all||!1)){r.info("Cancelled.");return}let s=new Set(o),a={...t,rules:n.filter(l=>!s.has(l))};a.rules.length===0&&r.warn(D.default.yellow("\u26A0\uFE0F Configuration will have no rules after removal.")),await q(a,i.config),r.success(D.default.green(`\u2714 Removed ${o.length} rule(s) from configuration`)),si(o)}r.log(""),r.log(D.default.dim(`Run ${D.default.cyan("doorman sync")} to deploy these changes.`))}catch(e){Y(e,"removing rule")}};var li={};M(li,{builder:()=>Xr,command:()=>Jr,desc:()=>Qr,handler:()=>es});var P=S(require("chalk"));T();var Jr="setup",Qr="Show setup instructions and helpful links for Doorman",Xr={},es=async i=>{r.log(""),r.log(P.default.bold.cyan("\u{1F6AA} Doorman Setup Guide")),r.log(P.default.dim(`Everything you need to get started with firewall management
124
125
  `)),r.log(P.default.bold("\u{1F4CB} Prerequisites")),r.log("\u2022 Vercel account with a deployed project"),r.log("\u2022 Project with Pro plan or higher (firewall feature requirement)"),r.log(`\u2022 Admin access to the project/team
125
- `),r.log(P.default.bold("\u{1F50D} Finding Your Project Information")),r.log(""),r.log(P.default.cyan("1. Project ID:")),r.log(" \u2022 Go to https://vercel.com/dashboard"),r.log(" \u2022 Select your project"),r.log(" \u2022 Navigate to Settings \u2192 General"),r.log(" \u2022 Copy the Project ID from the top of the page"),r.log(""),r.log(P.default.cyan("2. Team ID (if using team account):")),r.log(" \u2022 Go to https://vercel.com/dashboard"),r.log(" \u2022 Click on your team name in the top-left"),r.log(" \u2022 Go to Team Settings \u2192 General"),r.log(" \u2022 Copy the Team ID"),r.log(" \u2022 Leave empty to use your Vercel default team (every account has one)"),r.log(" \u2022 Belong to more than one team? Set this explicitly, or doorman will use whichever is your default"),r.log(""),r.log(P.default.bold("\u{1F511} Creating API Token")),r.log(""),r.log(P.default.cyan("Steps:")),r.log(" 1. Visit https://vercel.com/account/tokens"),r.log(' 2. Click "Create Token"'),r.log(' 3. Name: "Doorman Firewall Management"'),r.log(" 4. Expiration: Set as needed (90 days recommended)"),r.log(" 5. Scope: Select your project or team"),r.log(" 6. Copy the generated token"),r.log(""),r.log(P.default.cyan("Required Permissions:")),r.log(" \u2022 Read access to project settings"),r.log(" \u2022 Write access to firewall configuration"),r.log(""),r.log(P.default.bold("\u{1F30D} Environment Setup")),r.log(""),r.log(P.default.cyan("Set your API token as environment variable:")),r.log(""),r.log(P.default.green("# For current session:")),r.log('export VERCEL_TOKEN="your-token-here"'),r.log(""),r.log(P.default.green("# For permanent setup (add to ~/.bashrc or ~/.zshrc):")),r.log(`echo 'export VERCEL_TOKEN="your-token-here"' >> ~/.bashrc`),r.log(""),r.log(P.default.green("# Or create a .env file in your project:")),r.log('echo "VERCEL_TOKEN=your-token-here" > .env'),r.log(""),r.log(P.default.bold("\u{1F680} Quick Start Commands")),r.log(""),r.log(P.default.cyan("1. Initialize configuration:")),r.log(" doorman init --interactive"),r.log(""),r.log(P.default.cyan("2. Validate setup:")),r.log(" doorman validate"),r.log(""),r.log(P.default.cyan("3. Check current status:")),r.log(" doorman status"),r.log(""),r.log(P.default.cyan("4. View existing rules:")),r.log(" doorman list"),r.log(""),r.log(P.default.cyan("5. Sync your configuration:")),r.log(" doorman sync"),r.log(""),r.log(P.default.bold("\u{1F527} Common Issues")),r.log(""),r.log(P.default.yellow('\u274C "Project not found" error:')),r.log(" \u2022 Double-check your Project ID"),r.log(" \u2022 Ensure your token has access to the project"),r.log(" \u2022 Verify the project has Pro plan or higher"),r.log(""),r.log(P.default.yellow('\u274C "Unauthorized" error:')),r.log(" \u2022 Check your VERCEL_TOKEN is set correctly"),r.log(" \u2022 Ensure token hasn't expired"),r.log(" \u2022 Verify token has firewall permissions"),r.log(""),r.log(P.default.yellow('\u274C "Firewall not available" error:')),r.log(" \u2022 Upgrade to Pro plan or higher"),r.log(" \u2022 Contact Vercel support if issue persists"),r.log(""),r.log(P.default.bold("\u{1F4DA} Additional Resources")),r.log(""),r.log(P.default.cyan("Documentation:")),r.log(" \u2022 Doorman Docs: https://doorman.griffen.codes"),r.log(" \u2022 Vercel Firewall: https://vercel.com/docs/security/vercel-firewall"),r.log(" \u2022 API Reference: https://vercel.com/docs/rest-api/endpoints/firewall"),r.log(""),r.log(P.default.cyan("Support:")),r.log(" \u2022 GitHub Issues: https://github.com/gfargo/doorman/issues"),r.log(" \u2022 Vercel Support: https://vercel.com/help"),r.log(""),r.log(P.default.bold("\u{1F512} Security Best Practices")),r.log(""),r.log("\u2022 Store API tokens securely (use environment variables)"),r.log("\u2022 Set token expiration dates"),r.log("\u2022 Use principle of least privilege for token scopes"),r.log("\u2022 Regularly rotate API tokens"),r.log("\u2022 Test rules in staging before production"),r.log("\u2022 Keep backups of working configurations"),r.log(""),r.log(P.default.bold.green("\u2705 Ready to get started?")),r.log(P.default.dim("Run: ")+P.default.cyan("doorman init --interactive")),r.log("")};var ai={};M(ai,{builder:()=>Qr,command:()=>Yr,desc:()=>Jr,handler:()=>Xr});var L=S(require("chalk"));T();var Yr="status",Jr="Show sync status between local and remote firewall configuration",Qr={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:Y,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},format:{alias:"f",type:"string",choices:["table","json"],description:"Output format",default:"table"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Xr=async i=>{await J({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"checking status"},async({config:e,provider:t})=>{await es(t,le(e),i)})};async function es(i,e,t){let o=t.format==="json";o||r.start("Checking sync status...");let n=await i.getChanges(e),s=i.getHealthScore(e),a=e.metadata?.version,l=n.version!==void 0&&a!==void 0&&a!==n.version,c=!n.hasChanges&&!l;if(o){r.log(JSON.stringify({provider:i.name,inSync:c,version:{local:a??null,remote:n.version??null,matches:n.version!==void 0?!l:null},rules:{toAdd:n.rulesToAdd.length,toUpdate:n.rulesToUpdate.length,toDelete:n.rulesToDelete.length},ips:{toAdd:n.ipsToAdd?.length??0,toUpdate:n.ipsToUpdate?.length??0,toDelete:n.ipsToDelete?.length??0},health:s},null,2));return}r.log(L.default.bold(`
126
+ `),r.log(P.default.bold("\u{1F50D} Finding Your Project Information")),r.log(""),r.log(P.default.cyan("1. Project ID:")),r.log(" \u2022 Go to https://vercel.com/dashboard"),r.log(" \u2022 Select your project"),r.log(" \u2022 Navigate to Settings \u2192 General"),r.log(" \u2022 Copy the Project ID from the top of the page"),r.log(""),r.log(P.default.cyan("2. Team ID (if using team account):")),r.log(" \u2022 Go to https://vercel.com/dashboard"),r.log(" \u2022 Click on your team name in the top-left"),r.log(" \u2022 Go to Team Settings \u2192 General"),r.log(" \u2022 Copy the Team ID"),r.log(" \u2022 Leave empty to use your Vercel default team (every account has one)"),r.log(" \u2022 Belong to more than one team? Set this explicitly, or doorman will use whichever is your default"),r.log(""),r.log(P.default.bold("\u{1F511} Creating API Token")),r.log(""),r.log(P.default.cyan("Steps:")),r.log(" 1. Visit https://vercel.com/account/tokens"),r.log(' 2. Click "Create Token"'),r.log(' 3. Name: "Doorman Firewall Management"'),r.log(" 4. Expiration: Set as needed (90 days recommended)"),r.log(" 5. Scope: Select your project or team"),r.log(" 6. Copy the generated token"),r.log(""),r.log(P.default.cyan("Required Permissions:")),r.log(" \u2022 Read access to project settings"),r.log(" \u2022 Write access to firewall configuration"),r.log(""),r.log(P.default.bold("\u{1F30D} Environment Setup")),r.log(""),r.log(P.default.cyan("Set your API token as environment variable:")),r.log(""),r.log(P.default.green("# For current session:")),r.log('export VERCEL_TOKEN="your-token-here"'),r.log(""),r.log(P.default.green("# For permanent setup (add to ~/.bashrc or ~/.zshrc):")),r.log(`echo 'export VERCEL_TOKEN="your-token-here"' >> ~/.bashrc`),r.log(""),r.log(P.default.green("# Or create a .env file in your project:")),r.log('echo "VERCEL_TOKEN=your-token-here" > .env'),r.log(""),r.log(P.default.bold("\u{1F680} Quick Start Commands")),r.log(""),r.log(P.default.cyan("1. Initialize configuration:")),r.log(" doorman init --interactive"),r.log(""),r.log(P.default.cyan("2. Validate setup:")),r.log(" doorman validate"),r.log(""),r.log(P.default.cyan("3. Check current status:")),r.log(" doorman status"),r.log(""),r.log(P.default.cyan("4. View existing rules:")),r.log(" doorman list"),r.log(""),r.log(P.default.cyan("5. Sync your configuration:")),r.log(" doorman sync"),r.log(""),r.log(P.default.bold("\u{1F527} Common Issues")),r.log(""),r.log(P.default.yellow('\u274C "Project not found" error:')),r.log(" \u2022 Double-check your Project ID"),r.log(" \u2022 Ensure your token has access to the project"),r.log(" \u2022 Verify the project has Pro plan or higher"),r.log(""),r.log(P.default.yellow('\u274C "Unauthorized" error:')),r.log(" \u2022 Check your VERCEL_TOKEN is set correctly"),r.log(" \u2022 Ensure token hasn't expired"),r.log(" \u2022 Verify token has firewall permissions"),r.log(""),r.log(P.default.yellow('\u274C "Firewall not available" error:')),r.log(" \u2022 Upgrade to Pro plan or higher"),r.log(" \u2022 Contact Vercel support if issue persists"),r.log(""),r.log(P.default.bold("\u{1F4DA} Additional Resources")),r.log(""),r.log(P.default.cyan("Documentation:")),r.log(" \u2022 Doorman Docs: https://doorman.griffen.codes"),r.log(" \u2022 Vercel Firewall: https://vercel.com/docs/security/vercel-firewall"),r.log(" \u2022 API Reference: https://vercel.com/docs/rest-api/endpoints/firewall"),r.log(""),r.log(P.default.cyan("Support:")),r.log(" \u2022 GitHub Issues: https://github.com/gfargo/doorman/issues"),r.log(" \u2022 Vercel Support: https://vercel.com/help"),r.log(""),r.log(P.default.bold("\u{1F512} Security Best Practices")),r.log(""),r.log("\u2022 Store API tokens securely (use environment variables)"),r.log("\u2022 Set token expiration dates"),r.log("\u2022 Use principle of least privilege for token scopes"),r.log("\u2022 Regularly rotate API tokens"),r.log("\u2022 Test rules in staging before production"),r.log("\u2022 Keep backups of working configurations"),r.log(""),r.log(P.default.bold.green("\u2705 Ready to get started?")),r.log(P.default.dim("Run: ")+P.default.cyan("doorman init --interactive")),r.log("")};var ci={};M(ci,{builder:()=>ns,command:()=>ts,desc:()=>is,handler:()=>os});var L=S(require("chalk"));T();var ts="status",is="Show sync status between local and remote firewall configuration",ns={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},format:{alias:"f",type:"string",choices:["table","json"],description:"Output format",default:"table"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},os=async i=>{await Q({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"checking status"},async({config:e,provider:t})=>{await rs(t,le(e),i)})};async function rs(i,e,t){let n=t.format==="json";n||r.start("Checking sync status...");let o=await i.getChanges(e),s=i.getHealthScore(e),a=e.metadata?.version,l=o.version!==void 0&&a!==void 0&&a!==o.version,c=!o.hasChanges&&!l;if(n){r.log(JSON.stringify({provider:i.name,inSync:c,version:{local:a??null,remote:o.version??null,matches:o.version!==void 0?!l:null},rules:{toAdd:o.rulesToAdd.length,toUpdate:o.rulesToUpdate.length,toDelete:o.rulesToDelete.length},ips:{toAdd:o.ipsToAdd?.length??0,toUpdate:o.ipsToUpdate?.length??0,toDelete:o.ipsToDelete?.length??0},health:s},null,2));return}r.log(L.default.bold(`
126
127
  \u{1F4CA} ${i.name} Sync Status Summary
127
- `)),n.version!==void 0&&(r.log(`${L.default.dim("Local Version:")} ${L.default.yellow(a??"unknown")}`),r.log(`${L.default.dim("Remote Version:")} ${L.default.yellow(n.version)}`),r.log(`${L.default.dim("Version Status:")} ${l?L.default.red("Out of sync"):L.default.green("In sync")}`),r.log("")),r.log(`${L.default.dim("Rules:")}`),r.log(` ${L.default.green("+")} ${n.rulesToAdd.length} to add`),r.log(` ${L.default.cyan("~")} ${n.rulesToUpdate.length} to update`),r.log(` ${L.default.red("-")} ${n.rulesToDelete.length} to delete`),r.log(`${L.default.dim("IPs:")}`),r.log(` ${L.default.green("+")} ${n.ipsToAdd?.length??0} to add`),r.log(` ${L.default.cyan("~")} ${n.ipsToUpdate?.length??0} to update`),r.log(` ${L.default.red("-")} ${n.ipsToDelete?.length??0} to delete`),r.log(""),c?r.success(L.default.green("\u2705 Everything is in sync!")):r.warn(L.default.yellow("\u26A0\uFE0F Changes detected. Run `sync` to apply changes.")),r.log(`
128
+ `)),o.version!==void 0&&(r.log(`${L.default.dim("Local Version:")} ${L.default.yellow(a??"unknown")}`),r.log(`${L.default.dim("Remote Version:")} ${L.default.yellow(o.version)}`),r.log(`${L.default.dim("Version Status:")} ${l?L.default.red("Out of sync"):L.default.green("In sync")}`),r.log("")),r.log(`${L.default.dim("Rules:")}`),r.log(` ${L.default.green("+")} ${o.rulesToAdd.length} to add`),r.log(` ${L.default.cyan("~")} ${o.rulesToUpdate.length} to update`),r.log(` ${L.default.red("-")} ${o.rulesToDelete.length} to delete`),r.log(`${L.default.dim("IPs:")}`),r.log(` ${L.default.green("+")} ${o.ipsToAdd?.length??0} to add`),r.log(` ${L.default.cyan("~")} ${o.ipsToUpdate?.length??0} to update`),r.log(` ${L.default.red("-")} ${o.ipsToDelete?.length??0} to delete`),r.log(""),c?r.success(L.default.green("\u2705 Everything is in sync!")):r.warn(L.default.yellow("\u26A0\uFE0F Changes detected. Run `sync` to apply changes.")),r.log(`
128
129
  `+L.default.bold("\u{1F3E5} Configuration Health Check")),r.log(`${L.default.dim("Score:")} ${s.score}/100 (${s.grade})`),s.issues.forEach(d=>{let u=d.severity==="error"?L.default.red("\u2717"):d.severity==="warning"?L.default.yellow("\u26A0"):L.default.dim("\u2139");r.log(` ${u} [${d.category}] ${d.message}`),d.suggestion&&r.log(` ${L.default.dim(d.suggestion)}`)}),s.recommendations.length>0&&(r.log(L.default.dim(`
129
- Recommendations:`)),s.recommendations.forEach(d=>r.log(` - ${d}`)))}var di={};M(di,{builder:()=>os,command:()=>ts,desc:()=>is,handler:()=>ns});var z=S(require("chalk"));T();var ts="sync",is="Sync Vercel Firewall rules with config file",os={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:Y,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1},allowDeletions:{type:"boolean",description:"Required together with --ci to let a non-interactive sync delete existing rules/IPs. Without it, a --ci sync that would delete anything is refused rather than applied silently.",default:!1}},ns=async i=>{await J({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"syncing firewall rules"},async e=>{await rs(e.provider,e.config,i)})};async function rs(i,e,t){let o=le(e);r.start(z.default.magenta(`Calculating ${i.name} firewall configuration changes...`));let n=await i.getChanges(o),s=o.metadata?.version,a=n.version!==void 0&&s!==n.version;if(!n.hasChanges&&!a){r.success(z.default.green("No changes detected. Firewall rules are in sync."));return}r.log(z.default.bold(`
130
+ Recommendations:`)),s.recommendations.forEach(d=>r.log(` - ${d}`)))}var pi={};M(pi,{builder:()=>ls,command:()=>ss,desc:()=>as,handler:()=>cs});var z=S(require("chalk"));T();var ss="sync",as="Sync Vercel Firewall rules with config file",ls={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1},allowDeletions:{type:"boolean",description:"Required together with --ci to let a non-interactive sync delete existing rules/IPs. Without it, a --ci sync that would delete anything is refused rather than applied silently.",default:!1}},cs=async i=>{await Q({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"syncing firewall rules"},async e=>{await ds(e.provider,e.config,i)})};async function ds(i,e,t){let n=le(e);r.start(z.default.magenta(`Calculating ${i.name} firewall configuration changes...`));let o=await i.getChanges(n),s=n.metadata?.version,a=o.version!==void 0&&s!==o.version;if(!o.hasChanges&&!a){r.success(z.default.green("No changes detected. Firewall rules are in sync."));return}r.log(z.default.bold(`
130
131
  Proposed Changes:
131
- `)),li("Rules to add",n.rulesToAdd,z.default.green("+")),li("Rules to update",n.rulesToUpdate,z.default.cyan("~")),li("Rules to delete",n.rulesToDelete,z.default.red("-"));let l=n.ipsToAdd??[],c=n.ipsToUpdate??[],d=n.ipsToDelete??[];(l.length||c.length||d.length)&&(ci("IPs to add",l,z.default.green("+")),ci("IPs to update",c,z.default.cyan("~")),ci("IPs to delete",d,z.default.red("-"))),a&&r.log(` Remote config version: ${z.default.red(s??"unknown")} ${z.default.dim("->")} ${z.default.green(n.version)}`),r.start("Starting firewall rules sync...");let u=await i.syncRules(o,{force:t.ci,allowDeletions:t.allowDeletions});if(!u.success)throw new Error(`Sync failed: ${u.errors?.join(", ")||"unknown error"}`);r.success(z.default.green("Firewall rules sync completed successfully")),r.log(` Rules: ${u.rulesAdded} added, ${u.rulesUpdated} updated, ${u.rulesDeleted} deleted`),(u.ipsAdded||u.ipsUpdated||u.ipsDeleted)&&r.log(` IPs: ${u.ipsAdded??0} added, ${u.ipsUpdated??0} updated, ${u.ipsDeleted??0} deleted`),u.warnings?.forEach(g=>r.warn(g)),u.idRemappings?.length&&(r.info(z.default.yellow("Rule IDs were reassigned by the provider and written back to the local config:")),u.idRemappings.forEach(g=>{r.log(` - ${g.name}: ${z.default.red(g.oldId||"none")} ${z.default.dim("->")} ${z.default.green(g.newId)}`)}));let p=Pt(e,u);p.changed&&(await q(p.config,t.config),r.success(z.default.green("Updated local config with new version/metadata")))}function li(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(o=>r.log(` - ${o.name}`)))}function ci(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(o=>r.log(` - ${o.ip}${o.hostname?` (${o.hostname})`:""}`)))}var pi={};M(pi,{builder:()=>ls,command:()=>ss,desc:()=>as,handler:()=>us});var $e=S(require("chalk")),Uo=require("consola");T();var ko={metadata:{title:"Block AI Bots Firewall Rule",reference:"https://vercel.com/templates/other/block-ai-bots-firewall-rule"},config:{rules:[{id:"rule_detect_ai_bots",name:"Detect AI Bots",description:"",conditionGroup:[{conditions:[{type:"user_agent",op:"re",value:"AI2Bot|Ai2Bot-Dolma|Amazonbot|Applebot|Applebot-Extended|Bytespider|CCBot|ChatGPT-User|Claude-Web|ClaudeBot|Diffbot|FacebookBot|FriendlyCrawler|GPTBot|Google-Extended|GoogleOther|GoogleOther-Image|GoogleOther-Video|ICC-Crawler|ImagesiftBot|Meta-ExternalAgent|Meta-ExternalFetcher|OAI-SearchBot|PerplexityBot|PetalBot|Scrapy|Timpibot|VelenPublicWebCrawler|Webzio-Extended|YouBot|anthropic-ai|cohere-ai|facebookexternalhit|img2dataset|omgili|omgilibot"}]}],action:{mitigate:{action:"log"}},active:!0}]}};var $o={metadata:{title:"Block Bad Bots Firewall Rule",reference:"https://vercel.com/templates/other/block-bad-bots-firewall-rule"},config:{rules:[{id:"rule_detect_bad_bots",name:"Detect Bad Bots",description:"",conditionGroup:[{conditions:[{type:"user_agent",op:"re",value:"01h4x.com|360Spider|404checker|404enemy|80legs|ADmantX|AIBOT|ALittle Client|ASPSeek|Abonti|Aboundex|Aboundexbot|Acunetix|AdsTxtCrawlerTP|AfD-Verbotsverfahren|AhrefsBot|AiHitBot|Aipbot|Alexibot|AllSubmitter|Alligator|AlphaBot|Anarchie|Anarchy|Anarchy99|Ankit|Anthill|Apexoo|Aspiegel|Asterias|Atomseobot|Attach|AwarioBot|AwarioRssBot|AwarioSmartBot|BBBike|BDCbot|BDFetch|BLEXBot|BackDoorBot|BackStreet|BackWeb|Backlink-Ceck|BacklinkCrawler|BacklinksExtendedBot|Badass|Bandit|Barkrowler|BatchFTP|Battleztar Bazinga|BetaBot|Bigfoot|Bitacle|BlackWidow|Black Hole|Blackboard|Blow|BlowFish|Boardreader|Bolt|BotALot|Brandprotect|Brandwatch|Buck|Buddy|BuiltBotTough|BuiltWith|Bullseye|BunnySlippers|BuzzSumo|Bytespider|CATExplorador|CCBot|CODE87|CSHttp|Calculon|CazoodleBot|Cegbfeieh|CensysInspect|ChatGPT-User|CheTeam|CheeseBot|CherryPicker|ChinaClaw|Chlooe|Citoid|Claritybot|ClaudeBot|Cliqzbot|Cloud mapping|Cocolyzebot|Cogentbot|Collector|Copier|CopyRightCheck|Copyscape|Cosmos|Craftbot|Crawling at Home Project|CrazyWebCrawler|Crescent|CrunchBot|Curious|Custo|CyotekWebCopy|DBLBot|DIIbot|DSearch|DTS Agent|DataCha0s|DatabaseDriverMysqli|Demon|Deusu|Devil|Digincore|DigitalPebble|Dirbuster|Disco|Discobot|Discoverybot|Dispatch|DittoSpyder|DnBCrawler-Analytics|DnyzBot|DomCopBot|DomainAppender|DomainCrawler|DomainSigmaCrawler|DomainStatsBot|Domains Project|Dotbot|Download Wonder|Dragonfly|Drip|ECCP/1.0|EMail Siphon|EMail Wolf|EasyDL|Ebingbong|Ecxi|EirGrabber|EroCrawler|Evil|Exabot|Express WebPictures|ExtLinksBot|Extractor|ExtractorPro|Extreme Picture Finder|EyeNetIE|Ezooms|FDM|FHscan|FacebookBot|FemtosearchBot|Fimap|Firefox/7.0|FlashGet|Flunky|Foobot|Freeuploader|FrontPage|Fuzz|FyberSpider|Fyrebot|G-i-g-a-b-o-t|GPTBot|GT::WWW|GalaxyBot|Genieo|GermCrawler|GetRight|GetWeb|Getintent|Gigabot|Go!Zilla|Go-Ahead-Got-It|GoZilla|Gotit|GrabNet|Grabber|Grafula|GrapeFX|GrapeshotCrawler|GridBot|HEADMasterSEO|HMView|HTMLparser|HTTP::Lite|HTTrack|Haansoft|HaosouSpider|Harvest|Havij|Heritrix|Hloader|HonoluluBot|Humanlinks|HybridBot|IDBTE4M|IDBot|IRLbot|Iblog|Id-search|IlseBot|Image Fetch|Image Sucker|ImagesiftBot|IndeedBot|Indy Library|InfoNaviRobot|InfoTekies|Information Security Team InfraSec Scanner|InfraSec Scanner|Intelliseek|InterGET|InternetMeasurement|InternetSeer|Internet Ninja|Iria|Iskanie|IstellaBot|JOC Web Spider|JamesBOT|Jbrofuzz|JennyBot|JetCar|Jetty|JikeSpider|Joomla|Jorgee|JustView|Jyxobot|Kenjin Spider|Keybot Translation-Search-Machine|Keyword Density|Kinza|Kozmosbot|LNSpiderguy|LWP::Simple|Lanshanbot|Larbin|Leap|LeechFTP|LeechGet|LexiBot|Lftp|LibWeb|Libwhisker|LieBaoFast|Lightspeedsystems|Likse|LinkScan|LinkWalker|Linkbot|LinkextractorPro|LinkpadBot|LinksManager|LinqiaMetadataDownloaderBot|LinqiaRSSBot|LinqiaScrapeBot|Lipperhey|Lipperhey Spider|Litemage_walker|Lmspider|Ltx71|MFC_Tear_Sample|MIDown tool|MIIxpc|MJ12bot|MQQBrowser|MSFrontPage|MSIECrawler|MTRobot|Mag-Net|Magnet|Mail.RU_Bot|Majestic-SEO|Majestic12|Majestic SEO|MarkMonitor|MarkWatch|Mass Downloader|Masscan|Mata Hari|MauiBot|Mb2345Browser|MeanPath Bot|Meanpathbot|Mediatoolkitbot|MegaIndex.ru|Metauri|MicroMessenger|Microsoft Data Access|Microsoft URL Control|Minefield|Mister PiX|Moblie Safari|Mojeek|Mojolicious|MolokaiBot|Morfeus Fucking Scanner|Mozlila|Mr.4x3|Msrabot|Musobot|NICErsPRO|NPbot|Name Intelligence|Nameprotect|Navroad|NearSite|Needle|Nessus|NetAnts|NetLyzer|NetMechanic|NetSpider|NetZIP|Net Vampire|Netcraft|Nettrack|Netvibes|NextGenSearchBot|Nibbler|Niki-bot|Nikto|NimbleCrawler|Nimbostratus|Ninja|Nmap|Nuclei|Nutch|Octopus|Offline Explorer|Offline Navigator|OnCrawl|OpenLinkProfiler|OpenVAS|Openfind|Openvas|OrangeBot|OrangeSpider|OutclicksBot|OutfoxBot|PECL::HTTP|PHPCrawl|POE-Component-Client-HTTP|PageAnalyzer|PageGrabber|PageScorer|PageThing.com|Page Analyzer|Pandalytics|Panscient|Papa Foto|Pavuk|PeoplePal|Petalbot|Pi-Monster|Picscout|Picsearch|PictureFinder|Piepmatz|Pimonster|Pixray|PleaseCrawl|Pockey|ProPowerBot|ProWebWalker|Probethenet|Proximic|Psbot|Pu_iN|Pump|PxBroker|PyCurl|QueryN Metasearch|Quick-Crawler|RSSingBot|Rainbot|RankActive|RankActiveLinkBot|RankFlex|RankingBot|RankingBot2|Rankivabot|RankurBot|Re-re|ReGet|RealDownload|Reaper|RebelMouse|Recorder|RedesScrapy|RepoMonkey|Ripper|RocketCrawler|Rogerbot|SBIder|SEOkicks|SEOkicks-Robot|SEOlyt|SEOlyticsCrawler|SEOprofiler|SEOstats|SISTRIX|SMTBot|SalesIntelligent|ScanAlert|Scanbot|ScoutJet|Scrapy|Screaming|ScreenerBot|ScrepyBot|Searchestate|SearchmetricsBot|Seekport|SeekportBot|SemanticJuice|Semrush|SemrushBot|SentiBot|SenutoBot|SeoSiteCheckup|SeobilityBot|Seomoz|Shodan|Siphon|SiteCheckerBotCrawler|SiteExplorer|SiteLockSpider|SiteSnagger|SiteSucker|Site Sucker|Sitebeam|Siteimprove|Sitevigil|SlySearch|SmartDownload|Snake|Snapbot|Snoopy|SocialRankIOBot|Sociscraper|Sogou web spider|Sosospider|Sottopop|SpaceBison|Spammen|SpankBot|Spanner|Spbot|Spider_Bot|Spider_Bot/3.0|Spinn3r|SputnikBot|Sqlmap|Sqlworm|Sqworm|Steeler|Stripper|Sucker|Sucuri|SuperBot|SuperHTTP|Surfbot|SurveyBot|Suzuran|Swiftbot|Szukacz|T0PHackTeam|T8Abot|Teleport|TeleportPro|Telesoft|Telesphoreo|Telesphorep|TheNomad|The Intraformant|Thumbor|TightTwatBot|TinyTestBot|Titan|Toata|Toweyabot|Tracemyfile|Trendiction|Trendictionbot|True_Robot|Turingos|Turnitin|TurnitinBot|TwengaBot|Twice|Typhoeus|URLy.Warning|URLy Warning|UnisterBot|Upflow|V-BOT|VB Project|VCI|Vacuum|Vagabondo|VelenPublicWebCrawler|VeriCiteCrawler|VidibleScraper|Virusdie|VoidEYE|Voil|Voltron|WASALive-Bot|WBSearchBot|WEBDAV|WISENutbot|WPScan|WWW-Collector-E|WWW-Mechanize|WWW::Mechanize|WWWOFFLE|Wallpapers|Wallpapers/3.0|WallpapersHD|WeSEE|WebAuto|WebBandit|WebCollage|WebCopier|WebEnhancer|WebFetch|WebFuck|WebGo IS|WebImageCollector|WebLeacher|WebPix|WebReaper|WebSauger|WebStripper|WebSucker|WebWhacker|WebZIP|Web Auto|Web Collage|Web Enhancer|Web Fetch|Web Fuck|Web Pix|Web Sauger|Web Sucker|Webalta|WebmasterWorldForumBot|Webshag|WebsiteExtractor|WebsiteQuester|Website Quester|Webster|Whack|Whacker|Whatweb|Who.is Bot|Widow|WinHTTrack|WiseGuys Robot|Wonderbot|Woobot|Wotbox|Wprecon|Xaldon WebSpider|Xaldon_WebSpider|Xenu|YaK|YoudaoBot|Zade|Zauba|Zermelo|Zeus|Zitebot|ZmEu|ZoomBot|ZoominfoBot|ZumBot|ZyBorg|adscanner|anthropic-ai|archive.org_bot|arquivo-web-crawler|arquivo.pt|autoemailspider|awario.com|backlink-check|cah.io.community|check1.exe|clark-crawler|coccocbot|cognitiveseo|cohere-ai|com.plumanalytics|crawl.sogou.com|crawler.feedback|crawler4j|dataforseo.com|dataforseobot|demandbase-bot|domainsproject.org|eCatch|evc-batch|facebookscraper|gopher|heritrix|imagesift.com|instabid|internetVista monitor|ips-agent|isitwp.com|iubenda-radar|linkdexbot|linkfluence|lwp-request|lwp-trivial|magpie-crawler|meanpathbot|mediawords|muhstik-scan|netEstate NE Crawler|oBot|omgili|openai|openai.com|page scorer|pcBrowser|plumanalytics|polaris version|probe-image-size|ripz|s1z.ru|satoristudio.net|scalaj-http|scan.lol|seobility|seocompany.store|seoscanners|seostar|serpstatbot|sexsearcher|sitechecker.pro|siteripz|sogouspider|sp_auditbot|spyfu|sysscan|tAkeOut|trendiction.com|trendiction.de|ubermetrics-technologies.com|voyagerx.com|webgains-bot|webmeup-crawler|webpros.com|webprosbot|x09Mozilla|x22Mozilla|xpymep1.exe|zauba.io|zgrab"}]}],action:{mitigate:{action:"log"}},active:!0}]}};var _o={metadata:{title:"Block OFAC-Sanctioned Countries",reference:"https://vercel.com/templates/other/block-ofac-sanctioned-countries-firewall-rule"},config:{rules:[{id:"rule_block_traffic_from_ofac_sanctioned_countries",name:"Block traffic from OFAC-sanctioned countries",description:"Blocks traffic from OFAC-sanctioned countries and enforces a one-hour persistent block after the first violation.",conditionGroup:[{conditions:[{type:"geo_country",op:"inc",value:["SY","IR","RU","CU","KP"]}]}],action:{mitigate:{action:"deny",actionDuration:"1h"}},active:!0}]}};var So={metadata:{title:"Deny Common WordPress URLs Firewall Rule",reference:"https://vercel.com/templates/other/block-wordpress-urls-firewall-rule"},config:{rules:[{name:"Deny WordPress URLs",description:"",conditionGroup:[{conditions:[{type:"path",op:"re",value:"/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-content|wp-includes|wp-signup\\.php|wp-activate\\.php|register\\.php|wp-register\\.php)"}]}],action:{mitigate:{action:"deny"}},active:!0}]}};var ui={"ai-bots":ko,"bad-bots":$o,"block-ofac-sanctioned-countries":_o,wordpress:So};var Lo=i=>ui[i]?.config;pe();var ss="template [name]",as="Add a firewall rule template to your configuration",ls={name:{type:"string",description:"Name of the template to add"},config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},dryRun:{alias:"d",type:"boolean",description:"Preview changes without applying them",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1}};function cs(i,e){let t=new Set(i.map(n=>n.name.toLowerCase())),o=e.filter(n=>t.has(n.name.toLowerCase())).map(n=>n.name);return[...new Set(o)]}var ds=()=>Object.keys(ui),us=async i=>{try{i.debug&&(r.level=Uo.LogLevels.debug),r.debug("Template command arguments:",i);let e=i.name;if(!e){let c=ds();e=await w("Select a template to add:",{type:"select",options:c,initial:c[0]})}let t=Lo(e);t||(r.error(`Template not found: ${e}`),process.exit(1)),r.debug("Template content:",t),r.start("Loading current configuration...");let o=await j(i.config,"raw"),n=o.rules||[],s=cs(n,t.rules);if(i.dryRun){r.info($e.default.cyan(`
132
- Dry run - The following rules would be added:`)),r.log(JSON.stringify(t.rules,null,2)),s.length>0&&r.warn($e.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`));return}if(s.length>0&&(r.warn($e.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`)),!await w("Proceed anyway?",{type:"confirm",initial:!1}))){r.info("Cancelled.");return}let a={...o,rules:[...n,...t.rules]},l=Te.safeParse(a);l.success||(r.error($e.default.red("The resulting configuration would be invalid:")),l.error.errors.forEach(c=>{let d=c.path.join(".");r.error($e.default.red(` - ${d}: ${c.message}`))}),r.info($e.default.dim("Template was not applied. Fix the issues above and try again.")),process.exit(1)),r.start("Saving updated configuration..."),await q(a,i.config,{validate:!1}),r.success($e.default.green(`Successfully added template '${e}' to configuration`))}catch(e){Z(e,"adding template")}};var fi={};M(fi,{builder:()=>gs,command:()=>ps,desc:()=>fs,handler:()=>ms});var ee=S(require("chalk"));T();var ps="validate",fs="Validate firewall configuration file",gs={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},verbose:{alias:"v",type:"boolean",description:"Show detailed validation results",default:!1}},ms=async i=>{try{let e=await j(i.config,"raw"),t=Re.getInstance(),o=we(e);i.verbose&&r.start(`Validating configuration file...
133
- `);let n=o?Le.safeParse(e):Te.safeParse(e);i.verbose&&(r.log(ee.default.bold.underline("Zod Schema Validation:")),n.success?r.log(ee.default.green("\u2713 Schema validation passed")):(r.error(ee.default.red("\u2717 Schema validation failed:")),n.error.errors.forEach(l=>{let c=l.path.join(".");r.error(ee.default.red(` - ${c}: ${l.message}`))})));let s=!0,a=[];try{t.validateConfig(e),i.verbose&&(r.log(ee.default.bold.underline(`
134
- AJV Schema Validation:`)),r.log(ee.default.green("\u2713 JSON Schema validation passed")))}catch(l){if(s=!1,l instanceof D)a=l.ajvErrors||[],i.verbose&&(r.log(ee.default.bold.underline(`
135
- AJV Schema Validation:`)),r.error(ee.default.red("\u2717 JSON Schema validation failed:")),a.forEach(c=>{r.error(ee.default.red(` - ${c.instancePath}: ${c.message}`))}));else throw l}if(n.success&&s&&i.verbose){r.log(ee.default.bold.underline(`
136
- Custom Validations:`));let l=n.data,c=new Set,d=new Set;for(let u of l.rules)c.has(u.name)&&d.add(u.name),c.add(u.name);r.log(`${ee.default.cyan.dim(`
137
- Rule Names:`)}`),d.size>0?(r.error(ee.default.red("\u2717 Duplicate rule names found:")),d.forEach(u=>r.error(ee.default.red(` - "${u}"`)))):r.log(ee.default.green("\u2713 All rule names are unique")),r.log("")}if(n.success&&s)r.success(ee.default.green("Configuration is valid"));else throw new Error("Configuration validation failed")}catch(e){Z(e,"validating configuration")}};var gi={};M(gi,{builder:()=>ws,command:()=>hs,desc:()=>ys,handler:()=>Is});var de=S(require("chalk")),kt=require("fs");T();var hs="watch",ys="Watch config file for changes and auto-sync",ws={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:Y,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},interval:{alias:"i",type:"number",description:"Watch interval in milliseconds",default:1e3},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Is=async i=>{let e=i.config||".doorman.json";await J({config:e,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"setting up watch mode"},async({provider:t})=>{let o=!1,n=0;r.success(de.default.green(`\u{1F440} Watching ${e} for changes...`)),r.log(de.default.dim("Press Ctrl+C to stop watching")),r.log("");let s=async(c,d)=>{if(!(o||c.mtime.getTime()===n)){o=!0,n=c.mtime.getTime();try{r.log(de.default.yellow(`\u{1F4DD} Config file changed at ${new Date().toLocaleTimeString()}`)),r.start("Validating and syncing changes...");let u=await j(e);await Rs(t,u,e),r.log(de.default.dim("Watching for more changes..."))}catch(u){r.error(de.default.red(`\u274C Sync failed: ${u instanceof Error?u.message:String(u)}`)),r.log(de.default.dim("Continuing to watch for changes..."))}finally{o=!1}}};(0,kt.watchFile)(e,{interval:i.interval},s);let a=()=>{r.log(`
138
- `),r.info(de.default.yellow("Stopping watch mode...")),(0,kt.unwatchFile)(e),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a);let l=()=>{setTimeout(l,1e3)};l()})};async function Rs(i,e,t){let o=le(e),n=await i.getChanges(o),s=o.metadata?.version,a=n.version!==void 0&&s!==n.version;if(!n.hasChanges&&!a){r.info(de.default.blue("No changes detected, skipping sync"));return}let l=n.rulesToAdd.length+n.rulesToUpdate.length+n.rulesToDelete.length+(n.ipsToAdd?.length??0)+(n.ipsToUpdate?.length??0)+(n.ipsToDelete?.length??0);r.log(de.default.cyan(`Syncing ${l} changes...`));let c=await i.syncRules(o,{force:!0,allowDeletions:!0});if(!c.success)throw new Error(`Sync failed: ${c.errors?.join(", ")||"unknown error"}`);r.success(de.default.green(`\u2705 Sync completed at ${new Date().toLocaleTimeString()}`)),c.warnings?.forEach(u=>r.warn(u)),c.idRemappings?.length&&c.idRemappings.forEach(u=>{r.info(de.default.dim(` Rule "${u.name}" ID updated: ${u.oldId||"none"} -> ${u.newId}`))});let d=Pt(e,c);d.changed&&await q(d.config,t)}var Do=[si,ii,Wt,oi,ai,Xt,di,fi,ei,pi,ri,Qt,ti,gi];(0,xo.config)();async function Cs(){let i=(await import("chalk")).default,e=(0,Oo.default)(process.argv.slice(2));e.usage(`${i.bold("\u{1F6AA} Doorman")}
132
+ `)),di("Rules to add",o.rulesToAdd,z.default.green("+")),di("Rules to update",o.rulesToUpdate,z.default.cyan("~")),di("Rules to delete",o.rulesToDelete,z.default.red("-"));let l=o.ipsToAdd??[],c=o.ipsToUpdate??[],d=o.ipsToDelete??[];(l.length||c.length||d.length)&&(ui("IPs to add",l,z.default.green("+")),ui("IPs to update",c,z.default.cyan("~")),ui("IPs to delete",d,z.default.red("-"))),a&&r.log(` Remote config version: ${z.default.red(s??"unknown")} ${z.default.dim("->")} ${z.default.green(o.version)}`),r.start("Starting firewall rules sync...");let u=await i.syncRules(n,{force:t.ci,allowDeletions:t.allowDeletions});if(!u.success)throw new Error(`Sync failed: ${u.errors?.join(", ")||"unknown error"}`);r.success(z.default.green("Firewall rules sync completed successfully")),r.log(` Rules: ${u.rulesAdded} added, ${u.rulesUpdated} updated, ${u.rulesDeleted} deleted`),(u.ipsAdded||u.ipsUpdated||u.ipsDeleted)&&r.log(` IPs: ${u.ipsAdded??0} added, ${u.ipsUpdated??0} updated, ${u.ipsDeleted??0} deleted`),u.warnings?.forEach(g=>r.warn(g)),u.idRemappings?.length&&(r.info(z.default.yellow("Rule IDs were reassigned by the provider and written back to the local config:")),u.idRemappings.forEach(g=>{r.log(` - ${g.name}: ${z.default.red(g.oldId||"none")} ${z.default.dim("->")} ${z.default.green(g.newId)}`)}));let p=kt(e,u);p.changed&&(await q(p.config,t.config),r.success(z.default.green("Updated local config with new version/metadata")))}function di(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(n=>r.log(` - ${n.name}`)))}function ui(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(n=>r.log(` - ${n.ip}${n.hostname?` (${n.hostname})`:""}`)))}var gi={};M(gi,{builder:()=>fs,command:()=>us,desc:()=>ps,handler:()=>hs});var Ce=S(require("chalk")),Fn=require("consola");T();var Ln={metadata:{title:"Block AI Bots Firewall Rule",reference:"https://vercel.com/templates/other/block-ai-bots-firewall-rule"},config:{rules:[{id:"rule_detect_ai_bots",name:"Detect AI Bots",description:"",conditionGroup:[{conditions:[{type:"user_agent",op:"re",value:"AI2Bot|Ai2Bot-Dolma|Amazonbot|Applebot|Applebot-Extended|Bytespider|CCBot|ChatGPT-User|Claude-Web|ClaudeBot|Diffbot|FacebookBot|FriendlyCrawler|GPTBot|Google-Extended|GoogleOther|GoogleOther-Image|GoogleOther-Video|ICC-Crawler|ImagesiftBot|Meta-ExternalAgent|Meta-ExternalFetcher|OAI-SearchBot|PerplexityBot|PetalBot|Scrapy|Timpibot|VelenPublicWebCrawler|Webzio-Extended|YouBot|anthropic-ai|cohere-ai|facebookexternalhit|img2dataset|omgili|omgilibot"}]}],action:{mitigate:{action:"log"}},active:!0}]}};var Un={metadata:{title:"Block Bad Bots Firewall Rule",reference:"https://vercel.com/templates/other/block-bad-bots-firewall-rule"},config:{rules:[{id:"rule_detect_bad_bots",name:"Detect Bad Bots",description:"",conditionGroup:[{conditions:[{type:"user_agent",op:"re",value:"01h4x.com|360Spider|404checker|404enemy|80legs|ADmantX|AIBOT|ALittle Client|ASPSeek|Abonti|Aboundex|Aboundexbot|Acunetix|AdsTxtCrawlerTP|AfD-Verbotsverfahren|AhrefsBot|AiHitBot|Aipbot|Alexibot|AllSubmitter|Alligator|AlphaBot|Anarchie|Anarchy|Anarchy99|Ankit|Anthill|Apexoo|Aspiegel|Asterias|Atomseobot|Attach|AwarioBot|AwarioRssBot|AwarioSmartBot|BBBike|BDCbot|BDFetch|BLEXBot|BackDoorBot|BackStreet|BackWeb|Backlink-Ceck|BacklinkCrawler|BacklinksExtendedBot|Badass|Bandit|Barkrowler|BatchFTP|Battleztar Bazinga|BetaBot|Bigfoot|Bitacle|BlackWidow|Black Hole|Blackboard|Blow|BlowFish|Boardreader|Bolt|BotALot|Brandprotect|Brandwatch|Buck|Buddy|BuiltBotTough|BuiltWith|Bullseye|BunnySlippers|BuzzSumo|Bytespider|CATExplorador|CCBot|CODE87|CSHttp|Calculon|CazoodleBot|Cegbfeieh|CensysInspect|ChatGPT-User|CheTeam|CheeseBot|CherryPicker|ChinaClaw|Chlooe|Citoid|Claritybot|ClaudeBot|Cliqzbot|Cloud mapping|Cocolyzebot|Cogentbot|Collector|Copier|CopyRightCheck|Copyscape|Cosmos|Craftbot|Crawling at Home Project|CrazyWebCrawler|Crescent|CrunchBot|Curious|Custo|CyotekWebCopy|DBLBot|DIIbot|DSearch|DTS Agent|DataCha0s|DatabaseDriverMysqli|Demon|Deusu|Devil|Digincore|DigitalPebble|Dirbuster|Disco|Discobot|Discoverybot|Dispatch|DittoSpyder|DnBCrawler-Analytics|DnyzBot|DomCopBot|DomainAppender|DomainCrawler|DomainSigmaCrawler|DomainStatsBot|Domains Project|Dotbot|Download Wonder|Dragonfly|Drip|ECCP/1.0|EMail Siphon|EMail Wolf|EasyDL|Ebingbong|Ecxi|EirGrabber|EroCrawler|Evil|Exabot|Express WebPictures|ExtLinksBot|Extractor|ExtractorPro|Extreme Picture Finder|EyeNetIE|Ezooms|FDM|FHscan|FacebookBot|FemtosearchBot|Fimap|Firefox/7.0|FlashGet|Flunky|Foobot|Freeuploader|FrontPage|Fuzz|FyberSpider|Fyrebot|G-i-g-a-b-o-t|GPTBot|GT::WWW|GalaxyBot|Genieo|GermCrawler|GetRight|GetWeb|Getintent|Gigabot|Go!Zilla|Go-Ahead-Got-It|GoZilla|Gotit|GrabNet|Grabber|Grafula|GrapeFX|GrapeshotCrawler|GridBot|HEADMasterSEO|HMView|HTMLparser|HTTP::Lite|HTTrack|Haansoft|HaosouSpider|Harvest|Havij|Heritrix|Hloader|HonoluluBot|Humanlinks|HybridBot|IDBTE4M|IDBot|IRLbot|Iblog|Id-search|IlseBot|Image Fetch|Image Sucker|ImagesiftBot|IndeedBot|Indy Library|InfoNaviRobot|InfoTekies|Information Security Team InfraSec Scanner|InfraSec Scanner|Intelliseek|InterGET|InternetMeasurement|InternetSeer|Internet Ninja|Iria|Iskanie|IstellaBot|JOC Web Spider|JamesBOT|Jbrofuzz|JennyBot|JetCar|Jetty|JikeSpider|Joomla|Jorgee|JustView|Jyxobot|Kenjin Spider|Keybot Translation-Search-Machine|Keyword Density|Kinza|Kozmosbot|LNSpiderguy|LWP::Simple|Lanshanbot|Larbin|Leap|LeechFTP|LeechGet|LexiBot|Lftp|LibWeb|Libwhisker|LieBaoFast|Lightspeedsystems|Likse|LinkScan|LinkWalker|Linkbot|LinkextractorPro|LinkpadBot|LinksManager|LinqiaMetadataDownloaderBot|LinqiaRSSBot|LinqiaScrapeBot|Lipperhey|Lipperhey Spider|Litemage_walker|Lmspider|Ltx71|MFC_Tear_Sample|MIDown tool|MIIxpc|MJ12bot|MQQBrowser|MSFrontPage|MSIECrawler|MTRobot|Mag-Net|Magnet|Mail.RU_Bot|Majestic-SEO|Majestic12|Majestic SEO|MarkMonitor|MarkWatch|Mass Downloader|Masscan|Mata Hari|MauiBot|Mb2345Browser|MeanPath Bot|Meanpathbot|Mediatoolkitbot|MegaIndex.ru|Metauri|MicroMessenger|Microsoft Data Access|Microsoft URL Control|Minefield|Mister PiX|Moblie Safari|Mojeek|Mojolicious|MolokaiBot|Morfeus Fucking Scanner|Mozlila|Mr.4x3|Msrabot|Musobot|NICErsPRO|NPbot|Name Intelligence|Nameprotect|Navroad|NearSite|Needle|Nessus|NetAnts|NetLyzer|NetMechanic|NetSpider|NetZIP|Net Vampire|Netcraft|Nettrack|Netvibes|NextGenSearchBot|Nibbler|Niki-bot|Nikto|NimbleCrawler|Nimbostratus|Ninja|Nmap|Nuclei|Nutch|Octopus|Offline Explorer|Offline Navigator|OnCrawl|OpenLinkProfiler|OpenVAS|Openfind|Openvas|OrangeBot|OrangeSpider|OutclicksBot|OutfoxBot|PECL::HTTP|PHPCrawl|POE-Component-Client-HTTP|PageAnalyzer|PageGrabber|PageScorer|PageThing.com|Page Analyzer|Pandalytics|Panscient|Papa Foto|Pavuk|PeoplePal|Petalbot|Pi-Monster|Picscout|Picsearch|PictureFinder|Piepmatz|Pimonster|Pixray|PleaseCrawl|Pockey|ProPowerBot|ProWebWalker|Probethenet|Proximic|Psbot|Pu_iN|Pump|PxBroker|PyCurl|QueryN Metasearch|Quick-Crawler|RSSingBot|Rainbot|RankActive|RankActiveLinkBot|RankFlex|RankingBot|RankingBot2|Rankivabot|RankurBot|Re-re|ReGet|RealDownload|Reaper|RebelMouse|Recorder|RedesScrapy|RepoMonkey|Ripper|RocketCrawler|Rogerbot|SBIder|SEOkicks|SEOkicks-Robot|SEOlyt|SEOlyticsCrawler|SEOprofiler|SEOstats|SISTRIX|SMTBot|SalesIntelligent|ScanAlert|Scanbot|ScoutJet|Scrapy|Screaming|ScreenerBot|ScrepyBot|Searchestate|SearchmetricsBot|Seekport|SeekportBot|SemanticJuice|Semrush|SemrushBot|SentiBot|SenutoBot|SeoSiteCheckup|SeobilityBot|Seomoz|Shodan|Siphon|SiteCheckerBotCrawler|SiteExplorer|SiteLockSpider|SiteSnagger|SiteSucker|Site Sucker|Sitebeam|Siteimprove|Sitevigil|SlySearch|SmartDownload|Snake|Snapbot|Snoopy|SocialRankIOBot|Sociscraper|Sogou web spider|Sosospider|Sottopop|SpaceBison|Spammen|SpankBot|Spanner|Spbot|Spider_Bot|Spider_Bot/3.0|Spinn3r|SputnikBot|Sqlmap|Sqlworm|Sqworm|Steeler|Stripper|Sucker|Sucuri|SuperBot|SuperHTTP|Surfbot|SurveyBot|Suzuran|Swiftbot|Szukacz|T0PHackTeam|T8Abot|Teleport|TeleportPro|Telesoft|Telesphoreo|Telesphorep|TheNomad|The Intraformant|Thumbor|TightTwatBot|TinyTestBot|Titan|Toata|Toweyabot|Tracemyfile|Trendiction|Trendictionbot|True_Robot|Turingos|Turnitin|TurnitinBot|TwengaBot|Twice|Typhoeus|URLy.Warning|URLy Warning|UnisterBot|Upflow|V-BOT|VB Project|VCI|Vacuum|Vagabondo|VelenPublicWebCrawler|VeriCiteCrawler|VidibleScraper|Virusdie|VoidEYE|Voil|Voltron|WASALive-Bot|WBSearchBot|WEBDAV|WISENutbot|WPScan|WWW-Collector-E|WWW-Mechanize|WWW::Mechanize|WWWOFFLE|Wallpapers|Wallpapers/3.0|WallpapersHD|WeSEE|WebAuto|WebBandit|WebCollage|WebCopier|WebEnhancer|WebFetch|WebFuck|WebGo IS|WebImageCollector|WebLeacher|WebPix|WebReaper|WebSauger|WebStripper|WebSucker|WebWhacker|WebZIP|Web Auto|Web Collage|Web Enhancer|Web Fetch|Web Fuck|Web Pix|Web Sauger|Web Sucker|Webalta|WebmasterWorldForumBot|Webshag|WebsiteExtractor|WebsiteQuester|Website Quester|Webster|Whack|Whacker|Whatweb|Who.is Bot|Widow|WinHTTrack|WiseGuys Robot|Wonderbot|Woobot|Wotbox|Wprecon|Xaldon WebSpider|Xaldon_WebSpider|Xenu|YaK|YoudaoBot|Zade|Zauba|Zermelo|Zeus|Zitebot|ZmEu|ZoomBot|ZoominfoBot|ZumBot|ZyBorg|adscanner|anthropic-ai|archive.org_bot|arquivo-web-crawler|arquivo.pt|autoemailspider|awario.com|backlink-check|cah.io.community|check1.exe|clark-crawler|coccocbot|cognitiveseo|cohere-ai|com.plumanalytics|crawl.sogou.com|crawler.feedback|crawler4j|dataforseo.com|dataforseobot|demandbase-bot|domainsproject.org|eCatch|evc-batch|facebookscraper|gopher|heritrix|imagesift.com|instabid|internetVista monitor|ips-agent|isitwp.com|iubenda-radar|linkdexbot|linkfluence|lwp-request|lwp-trivial|magpie-crawler|meanpathbot|mediawords|muhstik-scan|netEstate NE Crawler|oBot|omgili|openai|openai.com|page scorer|pcBrowser|plumanalytics|polaris version|probe-image-size|ripz|s1z.ru|satoristudio.net|scalaj-http|scan.lol|seobility|seocompany.store|seoscanners|seostar|serpstatbot|sexsearcher|sitechecker.pro|siteripz|sogouspider|sp_auditbot|spyfu|sysscan|tAkeOut|trendiction.com|trendiction.de|ubermetrics-technologies.com|voyagerx.com|webgains-bot|webmeup-crawler|webpros.com|webprosbot|x09Mozilla|x22Mozilla|xpymep1.exe|zauba.io|zgrab"}]}],action:{mitigate:{action:"log"}},active:!0}]}};var Dn={metadata:{title:"Block OFAC-Sanctioned Countries",reference:"https://vercel.com/templates/other/block-ofac-sanctioned-countries-firewall-rule"},config:{rules:[{id:"rule_block_traffic_from_ofac_sanctioned_countries",name:"Block traffic from OFAC-sanctioned countries",description:"Blocks traffic from OFAC-sanctioned countries and enforces a one-hour persistent block after the first violation.",conditionGroup:[{conditions:[{type:"geo_country",op:"inc",value:["SY","IR","RU","CU","KP"]}]}],action:{mitigate:{action:"deny",actionDuration:"1h"}},active:!0}]}};var xn={metadata:{title:"Deny Common WordPress URLs Firewall Rule",reference:"https://vercel.com/templates/other/block-wordpress-urls-firewall-rule"},config:{rules:[{name:"Deny WordPress URLs",description:"",conditionGroup:[{conditions:[{type:"path",op:"re",value:"/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-content|wp-includes|wp-signup\\.php|wp-activate\\.php|register\\.php|wp-register\\.php)"}]}],action:{mitigate:{action:"deny"}},active:!0}]}};var fi={"ai-bots":Ln,"bad-bots":Un,"block-ofac-sanctioned-countries":Dn,wordpress:xn};var On=i=>fi[i]?.config;pe();var us="template [name]",ps="Add a firewall rule template to your configuration",fs={name:{type:"string",description:"Name of the template to add"},config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},dryRun:{alias:"d",type:"boolean",description:"Preview changes without applying them",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}};function gs(i,e){let t=new Set(i.map(o=>o.name.toLowerCase())),n=e.filter(o=>t.has(o.name.toLowerCase())).map(o=>o.name);return[...new Set(n)]}var ms=()=>Object.keys(fi),hs=async i=>{try{i.debug&&(r.level=Fn.LogLevels.debug),r.debug("Template command arguments:",i);let e=i.name;if(!e){let c=ms();e=await w("Select a template to add:",{type:"select",options:c,initial:c[0]})}let t=On(e);t||(r.error(`Template not found: ${e}`),process.exit(1)),r.debug("Template content:",t),r.start("Loading current configuration...");let n=await j(i.config,"raw"),o=n.rules||[],s=gs(o,t.rules);if(i.dryRun){r.info(Ce.default.cyan(`
133
+ Dry run - The following rules would be added:`)),r.log(JSON.stringify(t.rules,null,2)),s.length>0&&r.warn(Ce.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`));return}if(s.length>0){if(r.warn(Ce.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`)),i.ci||!process.stdin.isTTY){r.info(Ce.default.dim("Skipping \u2014 non-interactive and rule name(s) already exist. Template not applied."));return}if(!await w("Proceed anyway?",{type:"confirm",initial:!1})){r.info("Cancelled.");return}}let a={...n,rules:[...o,...t.rules]},l=Ae.safeParse(a);l.success||(r.error(Ce.default.red("The resulting configuration would be invalid:")),l.error.errors.forEach(c=>{let d=c.path.join(".");r.error(Ce.default.red(` - ${d}: ${c.message}`))}),r.info(Ce.default.dim("Template was not applied. Fix the issues above and try again.")),process.exit(1)),r.start("Saving updated configuration..."),await q(a,i.config,{validate:!1}),r.success(Ce.default.green(`Successfully added template '${e}' to configuration`))}catch(e){Y(e,"adding template")}};var mi={};M(mi,{builder:()=>Is,command:()=>ys,desc:()=>ws,handler:()=>Rs});var ee=S(require("chalk"));T();var ys="validate",ws="Validate firewall configuration file",Is={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},verbose:{alias:"v",type:"boolean",description:"Show detailed validation results",default:!1}},Rs=async i=>{try{let e=await j(i.config,"raw"),t=Re.getInstance(),n=we(e);i.verbose&&r.start(`Validating configuration file...
134
+ `);let o=n?Le.safeParse(e):Ae.safeParse(e);i.verbose&&(r.log(ee.default.bold.underline("Zod Schema Validation:")),o.success?r.log(ee.default.green("\u2713 Schema validation passed")):(r.error(ee.default.red("\u2717 Schema validation failed:")),o.error.errors.forEach(l=>{let c=l.path.join(".");r.error(ee.default.red(` - ${c}: ${l.message}`))})));let s=!0,a=[];try{t.validateConfig(e),i.verbose&&(r.log(ee.default.bold.underline(`
135
+ AJV Schema Validation:`)),r.log(ee.default.green("\u2713 JSON Schema validation passed")))}catch(l){if(s=!1,l instanceof x)a=l.ajvErrors||[],i.verbose&&(r.log(ee.default.bold.underline(`
136
+ AJV Schema Validation:`)),r.error(ee.default.red("\u2717 JSON Schema validation failed:")),a.forEach(c=>{r.error(ee.default.red(` - ${c.instancePath}: ${c.message}`))}));else throw l}if(o.success&&s&&i.verbose){r.log(ee.default.bold.underline(`
137
+ Custom Validations:`));let l=o.data,c=new Set,d=new Set;for(let u of l.rules)c.has(u.name)&&d.add(u.name),c.add(u.name);r.log(`${ee.default.cyan.dim(`
138
+ Rule Names:`)}`),d.size>0?(r.error(ee.default.red("\u2717 Duplicate rule names found:")),d.forEach(u=>r.error(ee.default.red(` - "${u}"`)))):r.log(ee.default.green("\u2713 All rule names are unique")),r.log("")}if(o.success&&s)r.success(ee.default.green("Configuration is valid"));else throw new Error("Configuration validation failed")}catch(e){Y(e,"validating configuration")}};var hi={};M(hi,{builder:()=>bs,command:()=>Cs,desc:()=>vs,handler:()=>Es});var de=S(require("chalk")),$t=require("fs");T();var Cs="watch",vs="Watch config file for changes and auto-sync",bs={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},interval:{alias:"i",type:"number",description:"Watch interval in milliseconds",default:1e3},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Es=async i=>{let e=i.config||".doorman.json";await Q({config:e,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"setting up watch mode"},async({provider:t})=>{let n=!1,o=0;r.success(de.default.green(`\u{1F440} Watching ${e} for changes...`)),r.log(de.default.dim("Press Ctrl+C to stop watching")),r.log("");let s=async(c,d)=>{if(!(n||c.mtime.getTime()===o)){n=!0,o=c.mtime.getTime();try{r.log(de.default.yellow(`\u{1F4DD} Config file changed at ${new Date().toLocaleTimeString()}`)),r.start("Validating and syncing changes...");let u=await j(e);await Ts(t,u,e),r.log(de.default.dim("Watching for more changes..."))}catch(u){r.error(de.default.red(`\u274C Sync failed: ${u instanceof Error?u.message:String(u)}`)),r.log(de.default.dim("Continuing to watch for changes..."))}finally{n=!1}}};(0,$t.watchFile)(e,{interval:i.interval},s);let a=()=>{r.log(`
139
+ `),r.info(de.default.yellow("Stopping watch mode...")),(0,$t.unwatchFile)(e),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a);let l=()=>{setTimeout(l,1e3)};l()})};async function Ts(i,e,t){let n=le(e),o=await i.getChanges(n),s=n.metadata?.version,a=o.version!==void 0&&s!==o.version;if(!o.hasChanges&&!a){r.info(de.default.blue("No changes detected, skipping sync"));return}let l=o.rulesToAdd.length+o.rulesToUpdate.length+o.rulesToDelete.length+(o.ipsToAdd?.length??0)+(o.ipsToUpdate?.length??0)+(o.ipsToDelete?.length??0);r.log(de.default.cyan(`Syncing ${l} changes...`));let c=await i.syncRules(n,{force:!0,allowDeletions:!0});if(!c.success)throw new Error(`Sync failed: ${c.errors?.join(", ")||"unknown error"}`);r.success(de.default.green(`\u2705 Sync completed at ${new Date().toLocaleTimeString()}`)),c.warnings?.forEach(u=>r.warn(u)),c.idRemappings?.length&&c.idRemappings.forEach(u=>{r.info(de.default.dim(` Rule "${u.name}" ID updated: ${u.oldId||"none"} -> ${u.newId}`))});let d=kt(e,c);d.changed&&await q(d.config,t)}var Nn=[li,oi,jt,ri,ci,ti,pi,mi,ii,gi,ai,ei,ni,hi];(0,Vn.config)();async function As(){let i=(await import("chalk")).default,e=(0,Bn.default)(process.argv.slice(2));e.usage(`${i.bold("\u{1F6AA} Doorman")}
139
140
 
140
- ${i.dim("Manage firewall rules as code across multiple providers")}`);for(let t of Do)e.command(t);e.demandCommand(1,"You need at least one command before moving on").help().epilogue(i.dim(`See ${i.bold("https://doorman.griffen.codes/getting-started")} for more info`)).argv}Cs().catch(console.error);
141
+ ${i.dim("Manage firewall rules as code across multiple providers")}`);for(let t of Nn)e.command(t);e.demandCommand(1,"You need at least one command before moving on").help().epilogue(i.dim(`See ${i.bold("https://doorman.griffen.codes/getting-started")} for more info`)).argv}As().catch(console.error);