@gfargo/doorman 3.13.1 → 3.13.3
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 +30 -30
- package/dist/bin/run.mjs +30 -30
- package/package.json +1 -1
package/dist/bin/run.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var bo=Object.create;var Et=Object.defineProperty;var Io=Object.getOwnPropertyDescriptor;var Eo=Object.getOwnPropertyNames;var Ao=Object.getPrototypeOf,To=Object.prototype.hasOwnProperty;var At=(i,e)=>()=>(i&&(e=i(i=0)),e);var X=(i,e)=>{for(var t in e)Et(i,t,{get:e[t],enumerable:!0})},ki=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Eo(e))!To.call(i,o)&&o!==t&&Et(i,o,{get:()=>e[o],enumerable:!(n=Io(e,o))||n.enumerable});return i};var O=(i,e,t)=>(t=i!=null?bo(Ao(i)):{},ki(e||!i||!i.__esModule?Et(t,"default",{value:i,enumerable:!0}):t,i)),Ee=i=>ki(Et({},"__esModule",{value:!0}),i);var Si,r,T=At(()=>{"use strict";Si=require("consola"),r=(0,Si.createConsola)({formatOptions:{colors:!0,compact:!0,date:!1}})});var Li,v,$e=At(()=>{"use strict";Li=O(require("consola")),v=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 Li.default.prompt(i,e);return t!=null&&t.toString()==="Symbol(clack:cancel)"&&process.exit(0),(!e?.type||e.type==="text")&&t===void 0?"":t}});var Be={};X(Be,{TranslationWarningSystem:()=>U});var U,pe=At(()=>{"use strict";U=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}
|
|
1
|
+
"use strict";var vo=Object.create;var Et=Object.defineProperty;var Io=Object.getOwnPropertyDescriptor;var Eo=Object.getOwnPropertyNames;var Ao=Object.getPrototypeOf,To=Object.prototype.hasOwnProperty;var At=(i,e)=>()=>(i&&(e=i(i=0)),e);var X=(i,e)=>{for(var t in e)Et(i,t,{get:e[t],enumerable:!0})},ki=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Eo(e))!To.call(i,o)&&o!==t&&Et(i,o,{get:()=>e[o],enumerable:!(n=Io(e,o))||n.enumerable});return i};var O=(i,e,t)=>(t=i!=null?vo(Ao(i)):{},ki(e||!i||!i.__esModule?Et(t,"default",{value:i,enumerable:!0}):t,i)),Ie=i=>ki(Et({},"__esModule",{value:!0}),i);var Si,r,T=At(()=>{"use strict";Si=require("consola"),r=(0,Si.createConsola)({formatOptions:{colors:!0,compact:!0,date:!1}})});var Li,b,$e=At(()=>{"use strict";Li=O(require("consola")),b=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 Li.default.prompt(i,e);return t!=null&&t.toString()==="Symbol(clack:cancel)"&&process.exit(0),(!e?.type||e.type==="text")&&t===void 0?"":t}});var Be={};X(Be,{TranslationWarningSystem:()=>U});var U,pe=At(()=>{"use strict";U=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}
|
|
2
2
|
`;return s+=` ${e.explanation}
|
|
3
3
|
`,e.suggestion&&(s+=` \u{1F4A1} Suggestion: ${e.suggestion}
|
|
4
4
|
`),e.alternativeApproach&&(s+=` \u{1F504} Alternative: ${e.alternativeApproach}
|
|
@@ -9,43 +9,43 @@
|
|
|
9
9
|
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(`
|
|
10
10
|
\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(`
|
|
11
11
|
\u{1F4BE} Backup Recommended: ${u.reason}`),u.instructions.forEach(R=>{r.info(` \u2022 ${R}`)}));let p=this.getRollbackGuidance(t);p.available&&(r.info(`
|
|
12
|
-
\u{1F504} Rollback Available: ${p.method}`),p.timeWindow&&r.info(` Time Window: ${p.timeWindow}`));let f=this.getConfirmationMessage(s,t);return await
|
|
12
|
+
\u{1F504} Rollback Available: ${p.method}`),p.timeWindow&&r.info(` Time Window: ${p.timeWindow}`));let f=this.getConfirmationMessage(s,t);return await b(f,{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 Ft.default.green("LOW");case"medium":return Ft.default.yellow("MEDIUM");case"high":return Ft.default.red("HIGH");default:return String(e).toUpperCase()}}static displayChangeSummary(e){r.info(`
|
|
13
13
|
\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(`
|
|
14
|
-
\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 Co=require("dotenv"),vo=O(require("yargs"));var ei={};X(ei,{builder:()=>Go,command:()=>jo,desc:()=>zo,generateRuleId:()=>Xt,handler:()=>Qo});var B=O(require("chalk")),Qi=require("consola");T();var b=require("zod"),Tt=b.z.number().int().positive().optional(),$o=b.z.string().ip().or(b.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),Ui=b.z.string().optional(),Po=b.z.enum(["eq","pre","suf","inc","sub","re","ex","nex"]),_o=b.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"]),ko=b.z.object({op:Po,neg:b.z.boolean().optional(),type:_o,value:b.z.union([b.z.string(),b.z.array(b.z.string()),b.z.array(b.z.number())]).optional(),key:b.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"),Wt=b.z.object({conditions:b.z.array(ko).min(1,"Condition group must have at least one condition")}),So=b.z.string().regex(/^\d+[smhd]$|^permanent$/),Mt=b.z.object({requests:b.z.number().positive().int().refine(i=>i>0,"requests must be positive"),window:b.z.string().regex(/^\d+[smhd]$/).refine(i=>parseInt(i)>0,"window duration must be positive")}),Uo=b.z.object({location:b.z.string(),permanent:b.z.boolean().optional()}),Lo=b.z.enum(["log","deny","challenge","bypass","rate_limit","redirect"]),xo=b.z.object({action:Lo,rateLimit:Mt.nullable().optional(),redirect:Uo.nullable().optional(),actionDuration:So.nullable().optional()}),Do=b.z.object({mitigate:xo}),jt=b.z.object({id:Ui,name:b.z.string(),description:b.z.string().optional(),conditionGroup:b.z.array(Wt),action:Do,active:b.z.boolean()});var zt=b.z.object({id:Ui,ip:$o,hostname:b.z.string().optional(),notes:b.z.string().optional(),action:b.z.literal("deny")}),Oo=b.z.object({projectId:b.z.string().optional(),teamId:b.z.string().optional()}),Ve=Oo.extend({rules:b.z.array(jt),ips:b.z.array(zt).optional(),version:b.z.number().optional(),updatedAt:b.z.string().optional()});$e();var le=require("fs"),Ki=require("crypto"),Hi=require("path");T();var ji=require("net"),zi=O(require("ajv"));var xi="https://doorman.griffen.codes/schema.json",Di={$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","action"],additionalProperties:!1}}};var _=require("zod");var E=require("zod");var z=["vercel","cloudflare","fastly","gcp"];var Gt=E.z.string().optional(),Pe=E.z.string().ip().or(E.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),$t=E.z.string().datetime().or(E.z.string().optional()),Oi=E.z.enum(["log","deny","challenge","bypass","rate_limit","redirect","allow","block"]),Fi=E.z.enum(["eq","ne","contains","not_contains","starts_with","ends_with","matches","in","not_in","gt","ge","lt","le","exists","not_exists"]),Ni=E.z.enum(["ip","country","region","city","asn","path","host","method","header","query","cookie","user_agent","referer","scheme","port"]),xa=E.z.string().regex(/^\d+[smhd]$|^permanent$/),Vi=E.z.object({requests:E.z.number().positive().int(),window:E.z.string().regex(/^\d+[smhd]$/),characteristics:E.z.array(E.z.string()).optional()}),Bi=E.z.object({location:E.z.string().refine(i=>i.startsWith("/")||E.z.string().url().safeParse(i).success,'location must be an absolute URL or a path starting with "/"'),statusCode:E.z.number().int().min(300).max(399).optional(),permanent:E.z.boolean().optional(),preserveQueryString:E.z.boolean().optional()}),Kt=E.z.object({version:E.z.number().int().positive().optional(),updatedAt:$t,createdAt:$t,lastSyncedAt:$t,migratedFrom:E.z.string().optional(),migratedAt:$t}),Fo=E.z.enum(z),qi=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(),gcp:E.z.object({projectId:E.z.string().optional(),policyName:E.z.string().optional()}).optional()}),Wi=E.z.object({$schema:E.z.string().url().optional(),version:E.z.string().optional(),provider:Fo.optional(),metadata:Kt.optional()});var No=_.z.object({field:Ni.or(_.z.string()),operator:Fi,value:_.z.union([_.z.string(),_.z.number(),_.z.array(_.z.string()),_.z.array(_.z.number())]).optional(),negated:_.z.boolean().optional(),key:_.z.string().optional(),group:_.z.number().optional()}).refine(i=>i.operator==="exists"||i.operator==="not_exists"||i.value!==void 0,{message:'value is required unless operator is "exists" or "not_exists"',path:["value"]}),Vo=_.z.object({type:Oi,rateLimit:Vi.optional(),redirect:Bi.optional(),response:_.z.object({statusCode:_.z.number().int().min(100).max(599).optional(),content:_.z.string().optional(),contentType:_.z.string().optional()}).optional(),duration:_.z.string().optional()}),Bo=_.z.object({id:Gt,name:_.z.string().min(1,"Rule name is required"),description:_.z.string().optional(),enabled:_.z.boolean(),conditions:_.z.array(No).min(1,"At least one condition is required"),conditionLogic:_.z.enum(["AND","OR"]).optional().default("AND"),action:Vo,priority:_.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:_.z.array(_.z.string()).optional()}),qo=_.z.object({id:Gt,ip:Pe,hostname:_.z.string().optional(),notes:_.z.string().optional(),action:_.z.enum(["deny","allow"])}),Ue=Wi.extend({providers:qi.optional(),rules:_.z.array(Bo),ips:_.z.array(qo).optional(),metadata:Kt.optional()}),Mi=i=>{let e=Ue.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 Le(i){if(!i||typeof i!="object")return!1;let e=i;return typeof e.provider=="string"||typeof e.providers=="object"&&e.providers!==null}var ae=O(require("chalk")),xe=class{static formatValidationError(e){let t=e.instancePath||"/",n=ae.default.cyan(t);switch(e.keyword){case"type":return`${n}: Expected ${ae.default.green(e.schema)}, got ${ae.default.red(typeof e.data)}`;case"enum":{let o=e.params.allowedValues;return`${n}: Value must be one of: ${ae.default.green(o.join(", "))}`}case"required":{let o=e.params;return`${n}: Missing required property ${ae.default.yellow(o.missingProperty)}`}case"additionalProperties":{let o=e.params;return`${n}: Unknown property ${ae.default.red(o.additionalProperty)}`}default:return`${n}: ${e.message}`}}static formatCustomError(e,t){return`${ae.default.cyan(e)}: ${t}`}static wrapErrorBlock(e){let t=ae.default.red.bold("Validation Errors:"),n=e.map(o=>` ${o}`).join(`
|
|
14
|
+
\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 Co=require("dotenv"),bo=O(require("yargs"));var ei={};X(ei,{builder:()=>Go,command:()=>jo,desc:()=>zo,generateRuleId:()=>Xt,handler:()=>Qo});var B=O(require("chalk")),Qi=require("consola");T();var v=require("zod"),Tt=v.z.number().int().positive().optional(),$o=v.z.string().ip().or(v.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),Ui=v.z.string().optional(),Po=v.z.enum(["eq","pre","suf","inc","sub","re","ex","nex"]),_o=v.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"]),ko=v.z.object({op:Po,neg:v.z.boolean().optional(),type:_o,value:v.z.union([v.z.string(),v.z.array(v.z.string()),v.z.array(v.z.number())]).optional(),key:v.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"),Wt=v.z.object({conditions:v.z.array(ko).min(1,"Condition group must have at least one condition")}),So=v.z.string().regex(/^\d+[smhd]$|^permanent$/),Mt=v.z.object({requests:v.z.number().positive().int().refine(i=>i>0,"requests must be positive"),window:v.z.string().regex(/^\d+[smhd]$/).refine(i=>parseInt(i)>0,"window duration must be positive")}),Uo=v.z.object({location:v.z.string(),permanent:v.z.boolean().optional()}),Lo=v.z.enum(["log","deny","challenge","bypass","rate_limit","redirect"]),xo=v.z.object({action:Lo,rateLimit:Mt.nullable().optional(),redirect:Uo.nullable().optional(),actionDuration:So.nullable().optional()}),Do=v.z.object({mitigate:xo}),jt=v.z.object({id:Ui,name:v.z.string(),description:v.z.string().optional(),conditionGroup:v.z.array(Wt),action:Do,active:v.z.boolean()});var zt=v.z.object({id:Ui,ip:$o,hostname:v.z.string().optional(),notes:v.z.string().optional(),action:v.z.literal("deny")}),Oo=v.z.object({projectId:v.z.string().optional(),teamId:v.z.string().optional()}),Ve=Oo.extend({rules:v.z.array(jt),ips:v.z.array(zt).optional(),version:v.z.number().optional(),updatedAt:v.z.string().optional()});$e();var le=require("fs"),Ki=require("crypto"),Hi=require("path");T();var ji=require("net"),zi=O(require("ajv"));var xi="https://doorman.griffen.codes/schema.json",Di={$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","action"],additionalProperties:!1}}};var _=require("zod");var E=require("zod");var z=["vercel","cloudflare","fastly","gcp"];var Gt=E.z.string().optional(),Pe=E.z.string().ip().or(E.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),$t=E.z.string().datetime().or(E.z.string().optional()),Oi=E.z.enum(["log","deny","challenge","bypass","rate_limit","redirect","allow","block"]),Fi=E.z.enum(["eq","ne","contains","not_contains","starts_with","ends_with","matches","in","not_in","gt","ge","lt","le","exists","not_exists"]),Ni=E.z.enum(["ip","country","region","city","asn","path","host","method","header","query","cookie","user_agent","referer","scheme","port"]),xa=E.z.string().regex(/^\d+[smhd]$|^permanent$/),Vi=E.z.object({requests:E.z.number().positive().int(),window:E.z.string().regex(/^\d+[smhd]$/),characteristics:E.z.array(E.z.string()).optional()}),Bi=E.z.object({location:E.z.string().refine(i=>i.startsWith("/")||E.z.string().url().safeParse(i).success,'location must be an absolute URL or a path starting with "/"'),statusCode:E.z.number().int().min(300).max(399).optional(),permanent:E.z.boolean().optional(),preserveQueryString:E.z.boolean().optional()}),Kt=E.z.object({version:E.z.number().int().positive().optional(),updatedAt:$t,createdAt:$t,lastSyncedAt:$t,migratedFrom:E.z.string().optional(),migratedAt:$t}),Fo=E.z.enum(z),qi=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(),gcp:E.z.object({projectId:E.z.string().optional(),policyName:E.z.string().optional()}).optional()}),Wi=E.z.object({$schema:E.z.string().url().optional(),version:E.z.string().optional(),provider:Fo.optional(),metadata:Kt.optional()});var No=_.z.object({field:Ni.or(_.z.string()),operator:Fi,value:_.z.union([_.z.string(),_.z.number(),_.z.array(_.z.string()),_.z.array(_.z.number())]).optional(),negated:_.z.boolean().optional(),key:_.z.string().optional(),group:_.z.number().optional()}).refine(i=>i.operator==="exists"||i.operator==="not_exists"||i.value!==void 0,{message:'value is required unless operator is "exists" or "not_exists"',path:["value"]}),Vo=_.z.object({type:Oi,rateLimit:Vi.optional(),redirect:Bi.optional(),response:_.z.object({statusCode:_.z.number().int().min(100).max(599).optional(),content:_.z.string().optional(),contentType:_.z.string().optional()}).optional(),duration:_.z.string().optional()}),Bo=_.z.object({id:Gt,name:_.z.string().min(1,"Rule name is required"),description:_.z.string().optional(),enabled:_.z.boolean(),conditions:_.z.array(No).min(1,"At least one condition is required"),conditionLogic:_.z.enum(["AND","OR"]).optional().default("AND"),action:Vo,priority:_.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:_.z.array(_.z.string()).optional()}),qo=_.z.object({id:Gt,ip:Pe,hostname:_.z.string().optional(),notes:_.z.string().optional(),action:_.z.enum(["deny","allow"])}),Ue=Wi.extend({providers:qi.optional(),rules:_.z.array(Bo),ips:_.z.array(qo).optional(),metadata:Kt.optional()}),Mi=i=>{let e=Ue.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 Le(i){if(!i||typeof i!="object")return!1;let e=i;return typeof e.provider=="string"||typeof e.providers=="object"&&e.providers!==null}var ae=O(require("chalk")),xe=class{static formatValidationError(e){let t=e.instancePath||"/",n=ae.default.cyan(t);switch(e.keyword){case"type":return`${n}: Expected ${ae.default.green(e.schema)}, got ${ae.default.red(typeof e.data)}`;case"enum":{let o=e.params.allowedValues;return`${n}: Value must be one of: ${ae.default.green(o.join(", "))}`}case"required":{let o=e.params;return`${n}: Missing required property ${ae.default.yellow(o.missingProperty)}`}case"additionalProperties":{let o=e.params;return`${n}: Unknown property ${ae.default.red(o.additionalProperty)}`}default:return`${n}: ${e.message}`}}static formatCustomError(e,t){return`${ae.default.cyan(e)}: ${t}`}static wrapErrorBlock(e){let t=ae.default.red.bold("Validation Errors:"),n=e.map(o=>` ${o}`).join(`
|
|
15
15
|
`);return`${t}
|
|
16
16
|
${n}`}static formatDetailedRuleValidation(e,t){let n=ae.default.cyan(`Rule: ${e}`),o=t.map(s=>{let a=s.passed?ae.default.green("\u2713"):ae.default.red("\u2717"),l=s.passed?ae.default.green(s.name):ae.default.red(s.name);return` ${a} ${l}`}).join(`
|
|
17
17
|
`);return`${n}
|
|
18
18
|
${o}`}};var W=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(xe.formatValidationError)),n&&s.push(...n.errors.map(a=>`${a.path.join(".")}: ${a.message}`)),o.length&&s.push(...o),xe.wrapErrorBlock(s)}getFormattedMessage(){return i.formatErrors(this.ajvErrors,this.zodError,this.customErrors)}},De=class i{static instance;ajv;schema;constructor(){this.ajv=new zi.default({allErrors:!0,verbose:!0}),this.schema=Di}static getInstance(){return i.instance||(i.instance=new i),i.instance}validateConfig(e){if(Le(e))try{Mi(e);return}catch(c){throw new W(`Invalid firewall configuration:
|
|
19
19
|
`+(c instanceof Error?c.message:String(c)),null)}let t=this.ajv.compile(this.schema),n=t(e),o=t.errors,s=Ve.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 W)l.push(c.message,...c.customErrors||[]);else throw c}for(let c of e.rules){if(c.action.mitigate?.rateLimit){let d=Mt.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=Wt.safeParse(d);u.success||l.push(...u.error.errors.map(p=>p.message))}}}if(!n||!s.success||l.length>0)throw new W(`Invalid firewall configuration:
|
|
20
|
-
`+W.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 W(`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 W(`Rule "${t.name}" has an empty condition group`,null);for(let o of n.conditions){if(!o.type||!o.op)throw new W(`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 W(`Rule "${t.name}" has an invalid condition`,null);if(!a&&(o.value===void 0||o.value===null))throw new W(`Rule "${t.name}" has an invalid condition`,null)}else if(o.value===void 0||o.value===null)throw new W(`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 W(`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 W(`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 W(`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 W(`Rule "${t.name}" has an invalid path in condition`,null)}}}else throw new W("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 W("Invalid rate limit configuration: requests must be positive",null);if(!n.rateLimit.window.match(/^\d+[smhd]$/))throw new W("Invalid rate limit configuration: invalid window format",null);if(parseInt(n.rateLimit.window)<=0)throw new W("Invalid rate limit configuration: window duration must be positive",null)}if(n?.actionDuration&&!n.actionDuration.match(/^\d+[smhd]$|^permanent$/))throw new W("Invalid action duration format: "+n.actionDuration,null);if(n?.redirect&&!n.redirect.location)throw new W("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 f=parseInt(p,10);return f>=0&&f<=255})},a=d=>(0,ji.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 Gi=require("fs"),lt=require("path"),Ht=[".doorman.json","vercel-firewall.config.json"],Wo=Ht[0],qe=class{static async findConfig(e){let{findUp:t}=await import("find-up");for(let n of Ht){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,lt.dirname)(t):null}static configExists(e){return(0,Gi.existsSync)((0,lt.resolve)(e))}static getDefaultConfigPath(){return(0,lt.resolve)(process.cwd(),Wo)}static getSupportedFileNames(){return Ht}};async function G(i,e="required"){let t=Mo(e),n=i||await qe.findConfig();if(!n||!(0,le.existsSync)(n)){if(t==="optional")return r.debug("No config file found, returning empty config"),{};let s=qe.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,le.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{De.getInstance().validateConfig(o)}catch(s){if(t==="lenient")r.warn("Config validation failed:",s);else throw s}return o}async function K(i,e,t={}){let{validate:n=!0,throwOnError:o=!0}=t,s=e||await qe.findConfig()||qe.getDefaultConfigPath();if(n)try{De.getInstance().validateConfig(i)}catch(c){if(r.error("Config validation failed:",c),o)throw c}let a=(0,Hi.dirname)(s);(0,le.existsSync)(a)||(0,le.mkdirSync)(a,{recursive:!0});let l=`${s}.${process.pid}.${(0,Ki.randomBytes)(4).toString("hex")}.tmp`;try{(0,le.writeFileSync)(l,JSON.stringify(i,null,2)),(0,le.renameSync)(l,s)}catch(c){try{(0,le.existsSync)(l)&&(0,le.unlinkSync)(l)}catch{}throw c}r.debug(`Config saved to ${s}`)}function Mo(i){if(typeof i=="string")return i;let{validate:e=!0,throwOnError:t=!0}=i;return e?t?"required":"lenient":"raw"}var Zt=O(require("chalk")),Zi=require("zod");T();function ee(i,e){i instanceof SyntaxError?r.log(xe.wrapErrorBlock(["Invalid JSON format in config file:",` ${i.message}`])):i instanceof Zi.ZodError?(r.error(Zt.default.red("Schema validation failed:")),i.errors.forEach(t=>{let n=t.path.join(".");r.error(Zt.default.red(` - ${n}: ${t.message}`))})):i instanceof Error&&i.name==="ValidationError"?r.error(i):i instanceof Error&&i.message.includes("Forbidden")?r.log(xe.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(xe.wrapErrorBlock([`Error ${e}:`,` ${i instanceof Error?i.message:String(i)}`])),process.exit(1)}var jo="add [type]",zo="Add a new firewall rule to your configuration",Go={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}},Yt=["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"],Jt=["eq","pre","suf","inc","sub","re","ex","nex"],Qt=["log","deny","challenge","bypass","rate_limit","redirect"];function Xt(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 Xi(i,e){return e==="inc"?i.split(",").map(t=>t.trim()):i}async function Ko(){let i=await v("Rule name:",{type:"text"});if(!i.trim())throw new Error("Rule name cannot be empty");let e=await v("Description (optional):",{type:"text"}),t=[],n=!0;for(;n;){let u=[],p=!0;for(;p;){let f=await v("Condition type:",{type:"select",options:Yt,initial:"path"}),y=await v("Operator:",{type:"select",options:Jt,initial:"eq"}),R;(f==="header"||f==="cookie"||f==="query")&&(R=await v(`${f} key:`,{type:"text"}));let C;if(y!=="ex"&&y!=="nex"){let V=await v("Value:",{type:"text"});C=Xi(V,y)}let x=y!=="ex"&&y!=="nex"?await v("Negate this condition?",{type:"confirm",initial:!1}):!1,N={type:f,op:y,...C!==void 0&&{value:C},...R&&{key:R},...x&&{neg:x}};u.push(N),p=await v("Add another condition to this group? (AND logic)",{type:"confirm",initial:!1})}t.push({conditions:u}),n=await v("Add another condition group? (OR logic)",{type:"confirm",initial:!1})}let o=await v("Action:",{type:"select",options:Qt,initial:"deny"}),s;if(o==="rate_limit"){let u=parseInt(await v("Max requests:",{type:"text",initial:"100"}),10),p=await v('Time window (e.g., "60s", "1m", "1h"):',{type:"text",initial:"60s"});s={requests:u,window:p}}let a;if(o==="redirect"){let u=await v("Redirect URL:",{type:"text"}),p=await v("Permanent redirect (301)?",{type:"confirm",initial:!1});a={location:u,...p&&{permanent:p}}}let l;(o==="deny"||o==="challenge")&&await v("Set action duration? (default: permanent)",{type:"confirm",initial:!1})&&(l=await v('Duration (e.g., "1h", "1d", "permanent"):',{type:"text",initial:"permanent"}));let c=await v("Enable rule immediately?",{type:"confirm",initial:!0});return{id:Xt(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 Ho(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(!Jt.includes(e))throw new Error(`Invalid operator "${i.op}". Valid operators: ${Jt.join(", ")}`);let t=i.field;if(!Yt.includes(t))throw new Error(`Invalid field type "${i.field}". Valid types: ${Yt.join(", ")}`);let n=i.action||"deny";if(!Qt.includes(n))throw new Error(`Invalid action "${i.action}". Valid actions: ${Qt.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?Xi(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:Xt(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 Zo(){let i=await v("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 v("Hostname (use * for all):",{type:"text",initial:"*"}),t=await v("Notes (optional):",{type:"text"});return{ip:i.trim(),hostname:e.trim()||"*",...t.trim()&&{notes:t.trim()},action:"deny"}}function Yo(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 Jo(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 Yi(i){r.log(""),r.log(B.default.bold(` Rule: ${i.name}`)),i.description&&r.log(B.default.dim(` Description: ${i.description}`)),r.log(B.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(B.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(B.default.dim(` Action: ${t}${n.length?` (${n.join(", ")})`:""}`)),r.log(B.default.dim(` Active: ${i.active?"\u2705":"\u274C"}`))}function Ji(i){r.log(""),r.log(B.default.bold(` IP Rule: ${i.ip}`)),r.log(B.default.dim(` Hostname: ${i.hostname}`)),i.notes&&r.log(B.default.dim(` Notes: ${i.notes}`)),r.log(B.default.dim(` Action: ${i.action}`))}var Qo=async i=>{try{if(i.debug&&(r.level=Qi.LogLevels.debug),r.debug("Add command arguments:",i),(i.type||"rule")==="ip"){let t=i.interactive?await Zo():Yo(i),n=zt.safeParse(t);if(n.success||(r.error(B.default.red("Rule validation failed:")),n.error.errors.forEach(a=>{let l=a.path.join(".");r.error(B.default.red(` - ${l||"ip"}: ${a.message}`))}),process.exit(1)),i.dryRun){r.info(B.default.cyan(`
|
|
20
|
+
`+W.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 W(`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 W(`Rule "${t.name}" has an empty condition group`,null);for(let o of n.conditions){if(!o.type||!o.op)throw new W(`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 W(`Rule "${t.name}" has an invalid condition`,null);if(!a&&(o.value===void 0||o.value===null))throw new W(`Rule "${t.name}" has an invalid condition`,null)}else if(o.value===void 0||o.value===null)throw new W(`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 W(`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 W(`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 W(`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 W(`Rule "${t.name}" has an invalid path in condition`,null)}}}else throw new W("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 W("Invalid rate limit configuration: requests must be positive",null);if(!n.rateLimit.window.match(/^\d+[smhd]$/))throw new W("Invalid rate limit configuration: invalid window format",null);if(parseInt(n.rateLimit.window)<=0)throw new W("Invalid rate limit configuration: window duration must be positive",null)}if(n?.actionDuration&&!n.actionDuration.match(/^\d+[smhd]$|^permanent$/))throw new W("Invalid action duration format: "+n.actionDuration,null);if(n?.redirect&&!n.redirect.location)throw new W("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 f=parseInt(p,10);return f>=0&&f<=255})},a=d=>(0,ji.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 Gi=require("fs"),lt=require("path"),Ht=[".doorman.json","vercel-firewall.config.json"],Wo=Ht[0],qe=class{static async findConfig(e){let{findUp:t}=await import("find-up");for(let n of Ht){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,lt.dirname)(t):null}static configExists(e){return(0,Gi.existsSync)((0,lt.resolve)(e))}static getDefaultConfigPath(){return(0,lt.resolve)(process.cwd(),Wo)}static getSupportedFileNames(){return Ht}};async function G(i,e="required"){let t=Mo(e),n=i||await qe.findConfig();if(!n||!(0,le.existsSync)(n)){if(t==="optional")return r.debug("No config file found, returning empty config"),{};let s=qe.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,le.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{De.getInstance().validateConfig(o)}catch(s){if(t==="lenient")r.warn("Config validation failed:",s);else throw s}return o}async function K(i,e,t={}){let{validate:n=!0,throwOnError:o=!0}=t,s=e||await qe.findConfig()||qe.getDefaultConfigPath();if(n)try{De.getInstance().validateConfig(i)}catch(c){if(r.error("Config validation failed:",c),o)throw c}let a=(0,Hi.dirname)(s);(0,le.existsSync)(a)||(0,le.mkdirSync)(a,{recursive:!0});let l=`${s}.${process.pid}.${(0,Ki.randomBytes)(4).toString("hex")}.tmp`;try{(0,le.writeFileSync)(l,JSON.stringify(i,null,2)),(0,le.renameSync)(l,s)}catch(c){try{(0,le.existsSync)(l)&&(0,le.unlinkSync)(l)}catch{}throw c}r.debug(`Config saved to ${s}`)}function Mo(i){if(typeof i=="string")return i;let{validate:e=!0,throwOnError:t=!0}=i;return e?t?"required":"lenient":"raw"}var Zt=O(require("chalk")),Zi=require("zod");T();function ee(i,e){i instanceof SyntaxError?r.log(xe.wrapErrorBlock(["Invalid JSON format in config file:",` ${i.message}`])):i instanceof Zi.ZodError?(r.error(Zt.default.red("Schema validation failed:")),i.errors.forEach(t=>{let n=t.path.join(".");r.error(Zt.default.red(` - ${n}: ${t.message}`))})):i instanceof Error&&i.name==="ValidationError"?r.error(i):i instanceof Error&&i.message.includes("Forbidden")?r.log(xe.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(xe.wrapErrorBlock([`Error ${e}:`,` ${i instanceof Error?i.message:String(i)}`])),process.exit(1)}var jo="add [type]",zo="Add a new firewall rule to your configuration",Go={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}},Yt=["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"],Jt=["eq","pre","suf","inc","sub","re","ex","nex"],Qt=["log","deny","challenge","bypass","rate_limit","redirect"];function Xt(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 Xi(i,e){return e==="inc"?i.split(",").map(t=>t.trim()):i}async function Ko(){let i=await b("Rule name:",{type:"text"});if(!i.trim())throw new Error("Rule name cannot be empty");let e=await b("Description (optional):",{type:"text"}),t=[],n=!0;for(;n;){let u=[],p=!0;for(;p;){let f=await b("Condition type:",{type:"select",options:Yt,initial:"path"}),y=await b("Operator:",{type:"select",options:Jt,initial:"eq"}),R;(f==="header"||f==="cookie"||f==="query")&&(R=await b(`${f} key:`,{type:"text"}));let C;if(y!=="ex"&&y!=="nex"){let V=await b("Value:",{type:"text"});C=Xi(V,y)}let x=y!=="ex"&&y!=="nex"?await b("Negate this condition?",{type:"confirm",initial:!1}):!1,N={type:f,op:y,...C!==void 0&&{value:C},...R&&{key:R},...x&&{neg:x}};u.push(N),p=await b("Add another condition to this group? (AND logic)",{type:"confirm",initial:!1})}t.push({conditions:u}),n=await b("Add another condition group? (OR logic)",{type:"confirm",initial:!1})}let o=await b("Action:",{type:"select",options:Qt,initial:"deny"}),s;if(o==="rate_limit"){let u=parseInt(await b("Max requests:",{type:"text",initial:"100"}),10),p=await b('Time window (e.g., "60s", "1m", "1h"):',{type:"text",initial:"60s"});s={requests:u,window:p}}let a;if(o==="redirect"){let u=await b("Redirect URL:",{type:"text"}),p=await b("Permanent redirect (301)?",{type:"confirm",initial:!1});a={location:u,...p&&{permanent:p}}}let l;(o==="deny"||o==="challenge")&&await b("Set action duration? (default: permanent)",{type:"confirm",initial:!1})&&(l=await b('Duration (e.g., "1h", "1d", "permanent"):',{type:"text",initial:"permanent"}));let c=await b("Enable rule immediately?",{type:"confirm",initial:!0});return{id:Xt(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 Ho(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(!Jt.includes(e))throw new Error(`Invalid operator "${i.op}". Valid operators: ${Jt.join(", ")}`);let t=i.field;if(!Yt.includes(t))throw new Error(`Invalid field type "${i.field}". Valid types: ${Yt.join(", ")}`);let n=i.action||"deny";if(!Qt.includes(n))throw new Error(`Invalid action "${i.action}". Valid actions: ${Qt.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?Xi(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:Xt(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 Zo(){let i=await b("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 b("Hostname (use * for all):",{type:"text",initial:"*"}),t=await b("Notes (optional):",{type:"text"});return{ip:i.trim(),hostname:e.trim()||"*",...t.trim()&&{notes:t.trim()},action:"deny"}}function Yo(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 Jo(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 Yi(i){r.log(""),r.log(B.default.bold(` Rule: ${i.name}`)),i.description&&r.log(B.default.dim(` Description: ${i.description}`)),r.log(B.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(B.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(B.default.dim(` Action: ${t}${n.length?` (${n.join(", ")})`:""}`)),r.log(B.default.dim(` Active: ${i.active?"\u2705":"\u274C"}`))}function Ji(i){r.log(""),r.log(B.default.bold(` IP Rule: ${i.ip}`)),r.log(B.default.dim(` Hostname: ${i.hostname}`)),i.notes&&r.log(B.default.dim(` Notes: ${i.notes}`)),r.log(B.default.dim(` Action: ${i.action}`))}var Qo=async i=>{try{if(i.debug&&(r.level=Qi.LogLevels.debug),r.debug("Add command arguments:",i),(i.type||"rule")==="ip"){let t=i.interactive?await Zo():Yo(i),n=zt.safeParse(t);if(n.success||(r.error(B.default.red("Rule validation failed:")),n.error.errors.forEach(a=>{let l=a.path.join(".");r.error(B.default.red(` - ${l||"ip"}: ${a.message}`))}),process.exit(1)),i.dryRun){r.info(B.default.cyan(`
|
|
21
21
|
Dry run - The following IP rule would be added:`)),Ji(t),r.log(""),r.log(B.default.dim(JSON.stringify(t,null,2)));return}r.start("Loading configuration...");let o=await G(i.config,"raw"),s={...o,ips:[...o.ips||[],t]};await K(s,i.config),r.success(B.default.green(`\u2714 IP rule "${t.ip}" added to configuration`)),Ji(t)}else{let t=i.interactive?await Ko():Ho(i),n=jt.safeParse(t);if(n.success||(r.error(B.default.red("Rule validation failed:")),n.error.errors.forEach(c=>{let d=c.path.join(".")||"rule";r.error(B.default.red(` - ${d}: ${c.message}`))}),process.exit(1)),i.dryRun){r.info(B.default.cyan(`
|
|
22
|
-
Dry run - The following rule would be added:`)),Yi(t),r.log(""),r.log(B.default.dim(JSON.stringify(t,null,2)));return}r.start("Loading configuration...");let o=await G(i.config,"raw"),s=o.rules||[],a=Jo({...o,rules:s},t);if(a){if(r.warn(B.default.yellow(`\u26A0\uFE0F ${a}`)),i.ci||!process.stdin.isTTY){r.info(B.default.dim("Skipping \u2014 non-interactive and a conflicting rule already exists. Rule not added."));return}if(!await
|
|
22
|
+
Dry run - The following rule would be added:`)),Yi(t),r.log(""),r.log(B.default.dim(JSON.stringify(t,null,2)));return}r.start("Loading configuration...");let o=await G(i.config,"raw"),s=o.rules||[],a=Jo({...o,rules:s},t);if(a){if(r.warn(B.default.yellow(`\u26A0\uFE0F ${a}`)),i.ci||!process.stdin.isTTY){r.info(B.default.dim("Skipping \u2014 non-interactive and a conflicting rule already exists. Rule not added."));return}if(!await b("Proceed anyway?",{type:"confirm",initial:!1})){r.info("Cancelled.");return}}let l={...o,rules:[...s,t]};await K(l,i.config),r.success(B.default.green(`\u2714 Rule "${t.name}" added to configuration`)),Yi(t)}r.log(""),r.log(B.default.dim(`Run ${B.default.cyan("doorman sync")} to deploy this rule.`))}catch(e){ee(e,"adding rule")}};var pi={};X(pi,{builder:()=>gs,command:()=>ps,desc:()=>fs,handler:()=>ms});var Q=O(require("chalk")),Ae=require("fs"),rt=require("path"),Xn=require("consola");T();$e();var ct=require("fs"),ti=require("path");function en(i=process.cwd()){return(0,ct.existsSync)((0,ti.join)(i,".git"))}function tn(i,e=process.cwd()){let t=(0,ti.join)(e,".gitignore");if(!(0,ct.existsSync)(t))return!1;let n=i.replace(/^\.\//,"").replace(/^\//,"").replace(/\/$/,""),o;try{o=(0,ct.readFileSync)(t,"utf8").split(`
|
|
23
23
|
`)}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 te={type:"string",choices:z,description:"Firewall provider (auto-detected)"};var Qn=require("consola");T();var Yn=O(require("chalk"));T();$e();var nn=require("readline");function Xo(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 er(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 on(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,nn.emitKeypressEvents)(t),t.setRawMode(!0),t.resume();let o="",s=()=>{t.removeListener("keypress",a),t.setRawMode(n??!1)},a=(l,c)=>{let d=Xo(l,c),u=er(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(`
|
|
24
|
-
`),u.cancelled&&process.exit(0),e(o))};t.on("keypress",a)})}T();var rn={provider:"vercel",fields:[{key:"token",envVar:"VERCEL_TOKEN",label:"Vercel API Token",required:!0,secret:!0,promptMessage:"What is your Vercel API Auth Token? (https://vercel.com/guides/how-do-i-use-a-vercel-api-access-token#creating-an-access-token) "},{key:"projectId",envVar:"VERCEL_PROJECT_ID",label:"Vercel Project ID",required:!0,configKey:"projectId",cliAlias:"p",legacyConfigKey:"projectId",promptMessage:"What is your Vercel Project ID? (See https://vercel.com/docs/projects/project-configuration/general-settings#project-id)"},{key:"teamId",envVar:"VERCEL_TEAM_ID",label:"Vercel Team ID",required:!1,configKey:"teamId",cliAlias:"t",legacyConfigKey:"teamId",promptMessage:"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)"}]};var sn={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 an={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"}]};var ln={provider:"gcp",fields:[{key:"serviceAccountKeyPath",envVar:"GOOGLE_APPLICATION_CREDENTIALS",label:"GCP Service Account Key Path",required:!1,promptMessage:"Path to a GCP service account JSON key file (leave blank to use Application Default Credentials \u2014 gcloud auth application-default login, or the GCE/Cloud Run metadata server): "},{key:"projectId",envVar:"GOOGLE_CLOUD_PROJECT",label:"GCP Project ID",required:!0,configKey:"projectId"},{key:"policyName",envVar:"GCP_POLICY_NAME",label:"Cloud Armor Security Policy Name",required:!0,configKey:"policyName"}]};function cn(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}function dn(i,e){return i.fields.filter(t=>t.required&&!e[t.key])}var He={vercel:rn,cloudflare:sn,fastly:an,gcp:ln};var Pt=class{static detectionField(e){return He[e].fields.find(t=>t.required&&t.configKey)}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;for(let s of z){let a=this.detectionField(s);if(!a?.configKey)continue;if(typeof(o[s]||{})[a.configKey]=="string")return t.push(`${a.label} found in config`),{provider:s,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;if(t&&this.isValidProvider(t))return e.push(`Provider set via DOORMAN_PROVIDER environment variable: ${t}`),{provider:t,confidence:"high",reasons:e};for(let n of z){let o=this.detectionField(n);if(!(!o||!process.env[o.envVar]))return e.push(`${o.label} found in environment (${o.envVar})`),{provider:n,confidence:"medium",reasons:e}}return{provider:null,confidence:"low",reasons:["No provider credentials found in environment"]}}static isValidProvider(e){return z.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;for(let o of z){let s=this.detectionField(o);if(!s?.configKey)continue;typeof(n[o]||{})[s.configKey]=="string"&&t.add(o)}}e&&"projectId"in e&&typeof e.projectId=="string"&&t.add("vercel");for(let n of z){let o=this.detectionField(n);o&&process.env[o.envVar]&&t.add(n)}return Array.from(t)}};var ii=O(require("chalk"));T();$e();var _t=i=>({$schema:xi,firewallEnabled:!0,rules:[],ips:[],...i});T();var _e=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 f=0;f<=s;f++)try{d=new AbortController,u=setTimeout(()=>{d&&d.abort()},o);let y=await fetch(n,{...l,headers:{"Content-Type":"application/json",...await this.getAuthHeaders(),...l.headers},signal:d.signal});if(u&&(clearTimeout(u),u=null),this.updateRateLimitInfo(y),y.status===429){let C=this.calculateRateLimitWait(f,y);if(f===s)throw new Error(`${this.providerName} API rate limit exceeded after ${s+1} attempt(s) (429 Too Many Requests). Retry after ~${Math.round(C/1e3)}s.`);r.warn(`Rate limit exceeded for ${this.providerName}. Waiting ${C}ms before retry (attempt ${f+1}/${s+1})...`),await this.delay(C);continue}if(!y.ok)throw await this.handleErrorResponse(y);let R;try{let C=await y.text();C.trim()?R=JSON.parse(C):R={}}catch(C){throw r.error(`Failed to parse response from ${n}:`,C),new Error(`Invalid JSON response from ${this.providerName} API: ${C instanceof Error?C.message:String(C)}`)}return this.isLargeResponse(R)&&(r.debug(`Large response detected from ${n}, validating structure...`),this.validateLargeResponse(R)),R}catch(y){if(c=y,u&&(clearTimeout(u),u=null),this.isNonRetryableError(y)||f===s)throw y;let R=a*Math.pow(2,f),C=Math.random()*.1*R,x=Math.min(R+C,3e4);r.debug(`Request failed (attempt ${f+1}/${s+1}). Retrying in ${Math.round(x)}ms...`),r.debug(`Error details: ${y instanceof Error?y.message:String(y)}`),await this.delay(x)}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),f=c.filter(y=>!p.includes(y));f.length>0&&r.warn(`Inconsistent array structure at ${s}[${d}]: missing keys ${f.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 un=process.env.DOORMAN_VERCEL_API_BASE_URL||"https://api.vercel.com/v1/security/firewall/config",Ze=class extends _e{constructor(t,n,o){super("","vercel");this.projectId=t;this.teamId=n;this.token=o}projectId;teamId;token;async getAuthHeaders(){return{Authorization:`Bearer ${this.token}`}}getUrl(t){let n=t!==void 0?`${un}/${t}`:un;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(ii.default.bold("No firewall configuration found.")),!o)return r.debug("Skipping create-configuration prompt for read-only fetch."),this.emptyConfigPlaceholder();if(await v("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: ${ii.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}=_t();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,n?{retries:0}:void 0)}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,n?{retries:0}:void 0)}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 se=O(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}`)}};pe();function pn(i){let e=[],t=[];i.conditionGroup.forEach((s,a)=>{for(let l of s.conditions){let c=ir(l.op);t.push({field:or(l.type),operator:c,...l.value!==void 0?{value:l.value}:{},...l.neg?{negated:!0}:{},...l.key?{key:l.key}:{},group:a})}}),t.length>10&&e.push(U.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,...i.action.mitigate.rateLimit?{rateLimit:{requests:i.action.mitigate.rateLimit.requests,window:i.action.mitigate.rateLimit.window,...i.action.mitigate.rateLimit.characteristics?{characteristics:i.action.mitigate.rateLimit.characteristics}:{},...i.action.mitigate.rateLimit.mitigationTimeout?{mitigationTimeout:i.action.mitigate.rateLimit.mitigationTimeout}:{},...i.action.mitigate.rateLimit.countingExpression?{countingExpression:i.action.mitigate.rateLimit.countingExpression}:{}}}:{},...i.action.mitigate.redirect?{redirect:{location:i.action.mitigate.redirect.location,...i.action.mitigate.redirect.permanent?{permanent:i.action.mitigate.redirect.permanent}:{}}}:{},...i.action.mitigate.actionDuration?{duration:i.action.mitigate.actionDuration}:{}};return{result:{id:i.id,name:i.name,...i.description?{description:i.description}:{},enabled:i.active,conditions:t,conditionLogic:i.conditionGroup.length>1?"OR":"AND",action:n},warnings:e}}function fn(i){let e=[],t=tr(i.conditions,i.id,e);if(i.action.response&&e.push(U.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 gn(i){return{id:i.id,ip:i.ip,...i.hostname?{hostname:i.hostname}:{},...i.notes?{notes:i.notes}:{},action:i.action}}function tr(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=sr(l.field);if(!c){t.push(U.createUnsupportedFeatureWarning(`condition field '${l.field}'`,"unified config","Vercel",e,l.field));continue}a.push({op:nr(l.operator),neg:l.negated,type:c,key:l.key,value:l.value})}a.length>0&&o.push({conditions:a})}return o}function ir(i){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists",nex:"not_exists"}[i]||"eq"}function nr(i){return{eq:"eq",starts_with:"pre",ends_with:"suf",in:"inc",contains:"sub",matches:"re",exists:"ex",not_exists:"nex"}[i]||"eq"}function or(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 rr={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 sr(i){return rr[i]??null}pe();T();function Ye(i){return i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function mn(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 dt=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}["${Ye(t.toLowerCase())}"]`:e==="cookie"&&t?`${n}["${Ye(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 ar=new Set(["ip.src"]),ut=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=dt.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}["${Ye(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(ar.has(e)){if(!Pe.safeParse(t).success)throw new Error(`Invalid IP address or CIDR range: ${t}`);return t}return`"${Ye(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 lr={"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"},cr=new Set(["eq","ne","contains","starts_with","ends_with","matches","in","gt","ge","lt","le"]),dr=new Set(["and","or","not"]),Se=class extends Error{};function ur(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 Se("Unterminated string literal");e.push({type:"STRING",value:mn(l)}),t=a;continue}let s=t;for(;s<n&&!/[\s(){}[\]"]/.test(i[s]);)s++;if(s===t)throw new Se(`Unexpected character '${o}' at position ${t}`);e.push({type:"WORD",value:i.slice(t,s)}),t=s}return e}var ni=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 Se("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 Se(`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 oi(i){let e=[hn(i)];for(;i.isWord("or");)i.next(),e.push(hn(i));return e.length===1?e[0]:{type:"or",children:e}}function hn(i){let e=[yn(i)];for(;i.isWord("and");)i.next(),e.push(yn(i));return e.length===1?e[0]:{type:"and",children:e}}function yn(i){if(i.isWord("not")){i.next(),i.expect("LPAREN");let e=oi(i);return i.expect("RPAREN"),{type:"not",child:e}}return pr(i)}function pr(i){let e=i.peek();if(e&&e.type==="LPAREN"){i.next();let t=oi(i);return i.expect("RPAREN"),t}return mr(i)}function fr(i){let e=i.expect("WORD");if(dr.has(e.value))throw new Se(`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 wn(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 Se(`Unexpected token '${e.value}' where a value was expected`)}function gr(i){if(i.peek()?.type==="LBRACE"){i.next();let e=[];for(;i.peek()?.type!=="RBRACE";)e.push(wn(i));return i.expect("RBRACE"),e}return wn(i)}function mr(i){let{field:e,key:t}=fr(i);if(i.isWord("exists"))return i.next(),{type:"exists",field:e,key:t};let n=i.next();if(n.type!=="WORD"||!cr.has(n.value))throw new Se(`Unsupported or unrecognized operator '${n.value}'`);let o=gr(i);return{type:"comparison",field:e,key:t,operator:n.value,value:o}}function hr(i){let e=new ni(ur(i)),t=oi(e);if(!e.atEnd())throw new Se("Unexpected trailing tokens");return t}function kt(i){return i.type==="comparison"||i.type==="exists"?!0:i.type==="not"?i.child.type==="comparison"||i.child.type==="exists":!1}function St(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=lr[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 yr(i){if(kt(i)){let e=St(i,0);return e?{conditions:[e],conditionLogic:"AND"}:null}if(i.type==="and"){let e=[];for(let t of i.children){if(!kt(t))return null;let n=St(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(kt(o)){let a=St(o,s);a&&e.push(a);return}if(o.type==="and")for(let a of o.children){if(!kt(a))return;let l=St(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 ri(i){if(!i||!i.trim())return null;try{let e=hr(i);return yr(e)}catch{return null}}function Rn(i){let e=[],t=ri(i.expression),n=[],o;t?(n=t.conditions,o=t.conditionLogic):e.push(U.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:wr(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 Cn(i){let e=[],t=ut.fromUnifiedConditions(i.conditions,i.conditionLogic),n={id:i.id||crypto.randomUUID(),action:Rr(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:Cr(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,e.push(U.createWarning("rate_limiting_precision",i.id,"action.rateLimit.mitigationTimeout",`No mitigationTimeout set for rate limit rule "${i.name}" \u2014 defaulted to Cloudflare's 3600s (1 hour) block duration.`))),i.action.rateLimit.countingExpression&&(n.ratelimit.counting_expression=i.action.rateLimit.countingExpression)),i.action.type==="redirect"&&i.action.redirect&&(n.action_parameters={from_value:{status_code:i.action.redirect.statusCode??(i.action.redirect.permanent?301:302),target_url:{value:i.action.redirect.location},...i.action.redirect.preserveQueryString!==void 0?{preserve_query_string:i.action.redirect.preserveQueryString}:{}}}),i.action.response&&(n.action!=="block"?e.push(U.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(U.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 vn(i){if(!Pe.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 wr(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 Rr(i){return{log:"log",deny:"block",block:"block",challenge:"managed_challenge",bypass:"skip",rate_limit:"block",redirect:"redirect",allow:"allow"}[i]||"block"}function Cr(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}pe();function fe(i,e,t){return U.createWarning("complex_expressions",i,void 0,e,t)}var vr={ip:"ip",path:"path",domain:"host",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},br={ip:"ip",path:"path",host:"domain",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},Ir={header:"request_header",query:"query_parameter",cookie:"request_cookie"},Er={request_header:"header",query_parameter:"query",request_cookie:"cookie",response_header:"response_header",post_parameter:"post_parameter",signal:"signal"};function Ar(i){return vr[i]??i}function Tr(i){return br[i]??null}var $r={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 bn(i){return $r[i]??{operator:"eq",negated:!1}}function In(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(U.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(U.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(fe(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(fe(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 Pr(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(fe(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)Ut(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;Ut(t,s,l,e,i.id)}),{conditions:t,conditionLogic:i.group_operator==="any"&&o.length>1?"OR":"AND"};e.push(fe(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)Ut(t,s,0,e,i.id);for(let s of n)for(let a of s.conditions)Ut(t,a,0,e,i.id);return{conditions:t,conditionLogic:"AND"}}function Ut(i,e,t,n,o){if(e.type==="single"){let{operator:u,negated:p}=bn(e.operator);i.push({field:Ar(e.field),operator:u,value:e.value,...p?{negated:!0}:{},group:t});return}let s=Er[e.field],a=e.conditions.find(u=>u.field==="name"),l=e.conditions.find(u=>u.field==="value"||u.field==="value_string");if(!l){if(a){i.push({field:s,operator:e.operator==="does_not_exist"?"not_exists":"exists",key:a.value,group:t});return}n.push(fe(o,`Multival condition on '${e.field}' has no value or name sub-condition doorman could extract \u2014 skipped.`));return}let{operator:c,negated:d}=bn(l.operator);i.push({field:s,operator:c,value:l.value,...d?{negated:!0}:{},...a?{key:a.value}:{},group:t})}function _r(i,e){i.actions.length>1&&e.push(fe(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(U.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(fe(i.id,`Unrecognised Fastly action type "${String(t?.type)}" \u2014 mapped to "log".`)),{type:"log"}}}function En(i){let e=[],{conditions:t,conditionLogic:n}=Pr(i,e),o=_r(i,e);return t.length>10&&e.push(U.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 kr(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=Ir[a.field];if(l){if(a.key===void 0)return t.push(fe(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;if(a.operator==="exists"||a.operator==="not_exists")return{type:"multival",field:l,operator:a.operator==="exists"?"exists":"does_not_exist",group_operator:"all",conditions:[{type:"single",field:"name",operator:"equals",value:a.key}]};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:In(a.operator,a.negated,t,e),value:String(a.value)}]}}if(a.operator==="exists"||a.operator==="not_exists")return t.push(U.createUnsupportedFeatureWarning(`"${a.operator}" on field '${a.field}'`,"unified config","Fastly",e,a.field)),null;let c=Tr(a.field);return c?{type:"single",field:c,operator:In(a.operator,a.negated,t,e),value:String(a.value)}:(t.push(U.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 Sr(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(fe(t,'Unified action "bypass" has no direct Fastly equivalent \u2014 mapped to "allow".')),{type:"allow"};case"log":return e.push(fe(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(fe(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(U.createUnsupportedFeatureWarning(`action type '${i.type}'`,"unified config","Fastly",t,"action.type")),{type:"block"}}}function Ur(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(U.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(U.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 Lr(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=Ur(i.window,t,e);return t.push(U.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 An(i){let e=[];i.description&&i.description!==i.name&&e.push(fe(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}=kr(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:[Sr(i.action,e,i.id)],rate_limit:a?Lr(i.action.rateLimit,i.id,e):null},warnings:e}}function Tn(i,e){return i.map(t=>({ip:t,action:e}))}function $n(i){let e=[],t=[],n=[];for(let o of i)(o.hostname||o.notes)&&e.push(fe(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}}pe();function Je(i){return i.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Pn(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 xr=new Set(["region","city","port","scheme"]),Dr={host:"host",user_agent:"user-agent",referer:"referer"},pt=class{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"?" && ":" || ";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){if(xr.has(e.field))throw new Error(`Cloud Armor has no CEL equivalent for the "${e.field}" condition field \u2014 this rule cannot be represented and would otherwise be silently dropped.`);if(e.field==="ip")return this.buildIpCondition(e);if(e.field==="cookie")return this.buildCookieCondition(e);let t=Dr[e.field];if(t)return this.buildHeaderCondition(t,e);if(e.field==="header"||e.field==="query"){if(e.field==="header"){if(!e.key)throw new Error('A "header" condition requires a key naming the header');return this.buildHeaderCondition(e.key,e)}return this.buildComparison("request.query",e,!1)}let n=Or[e.field];if(n)return this.buildComparison(n.path,e,n.numeric);throw new Error(`Cloud Armor CEL builder has no mapping for condition field "${e.field}"`)}static buildIpCondition(e){let t=(Array.isArray(e.value)?e.value:[e.value]).map(String);if(t.length===0||t.some(a=>!a))throw new Error('An "ip" condition requires at least one value');let n=t.map(a=>{if(!Pe.safeParse(a).success)throw new Error(`Invalid IP address or CIDR range: ${a}`);return a.includes("/")?`inIpRange(origin.ip, '${Je(a)}')`:`origin.ip == '${Je(a)}'`}),o=e.operator==="not_in"||e.operator==="ne";if(n.length>1){let a=`(${n.join(" || ")})`;return o?`!${a}`:a}let s=n[0];return o?s.startsWith("inIpRange(")?`!${s}`:`!(${s})`:s}static buildHeaderCondition(e,t){let n=`request.headers['${Je(e)}']`,o=`has(${n})`;return t.operator==="exists"?o:t.operator==="not_exists"?`!${o}`:`(${o} && ${this.buildComparison(n,t,!1)})`}static buildCookieCondition(e){let t="request.headers['cookie']",n=`has(${t})`;if(e.operator==="exists")return n;if(e.operator==="not_exists")return`!${n}`;if(!e.key)return`(${n} && ${this.buildComparison(t,e,!1)})`;if(!["eq","ne","contains","not_contains"].includes(e.operator))throw new Error(`Cloud Armor can only check a specific cookie's value via substring search (has no parsed cookie map) \u2014 "${e.operator}" on a keyed cookie condition has no unambiguous CEL representation.`);let o=`${e.key}=${String(e.value)}`,s=`${t}.contains('${Je(o)}')`,a=e.operator==="ne"||e.operator==="not_contains";return`(${n} && ${a?`!${s}`:s})`}static buildComparison(e,t,n){let{operator:o,value:s}=t;if(o==="exists"||o==="not_exists")throw new Error(`"${o}" is not meaningful for Cloud Armor's "${e}" \u2014 it is always present`);if(o==="in"||o==="not_in"){let c=(Array.isArray(s)?s:[s]).map(u=>this.formatLiteral(u,n)).join(", "),d=`${e} in [${c}]`;return o==="not_in"?`!(${d})`:d}let a=this.formatLiteral(s,n);switch(o){case"eq":return`${e} == ${a}`;case"ne":return`${e} != ${a}`;case"contains":return`${e}.contains(${a})`;case"not_contains":return`!${e}.contains(${a})`;case"starts_with":return`${e}.startsWith(${a})`;case"ends_with":return`${e}.endsWith(${a})`;case"matches":return`${e}.matches(${a})`;case"gt":return`${e} > ${a}`;case"ge":return`${e} >= ${a}`;case"lt":return`${e} < ${a}`;case"le":return`${e} <= ${a}`;default:throw new Error(`Cloud Armor CEL builder has no mapping for operator "${o}"`)}}static formatLiteral(e,t){if(t){let n=Number(e);if(!Number.isFinite(n))throw new Error(`Expected a numeric value, got "${String(e)}"`);return String(n)}return`'${Je(String(e))}'`}static combineWithAnd(e){if(e.length===0)throw new Error("At least one expression is required");return e.length===1?e[0]:`(${e.join(" && ")})`}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={country:{path:"origin.region_code",numeric:!1},asn:{path:"origin.asn",numeric:!0},path:{path:"request.path",numeric:!1},method:{path:"request.method",numeric:!1}};var Fr={"origin.region_code":"country","origin.asn":"asn","request.path":"path","request.method":"method","request.query":"query"},Nr={host:"host","user-agent":"user_agent",referer:"referer",cookie:"cookie"},xn={contains:"contains",startsWith:"starts_with",endsWith:"ends_with",matches:"matches"},Re=class extends Error{};function Vr(i){let e=[],t=0,n=i.length,o=(s,a)=>i[t]===s&&i[t+1]===a;for(;t<n;){let s=i[t];if(/\s/.test(s)){t++;continue}if(s==="("){e.push({type:"LPAREN",value:s}),t++;continue}if(s===")"){e.push({type:"RPAREN",value:s}),t++;continue}if(s==="["){e.push({type:"LBRACKET",value:s}),t++;continue}if(s==="]"){e.push({type:"RBRACKET",value:s}),t++;continue}if(s===","){e.push({type:"COMMA",value:s}),t++;continue}if(o("&","&")){e.push({type:"AND",value:"&&"}),t+=2;continue}if(o("|","|")){e.push({type:"OR",value:"||"}),t+=2;continue}if(o("=","=")){e.push({type:"EQ",value:"=="}),t+=2;continue}if(o("!","=")){e.push({type:"NE",value:"!="}),t+=2;continue}if(o(">","=")){e.push({type:"GE",value:">="}),t+=2;continue}if(o("<","=")){e.push({type:"LE",value:"<="}),t+=2;continue}if(s==="!"){e.push({type:"NOT",value:"!"}),t++;continue}if(s===">"){e.push({type:"GT",value:">"}),t++;continue}if(s==="<"){e.push({type:"LT",value:"<"}),t++;continue}if(s==="."){e.push({type:"DOT",value:s}),t++;continue}if(s==="'"){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 Re("Unterminated string literal");e.push({type:"STRING",value:Pn(l)}),t=a;continue}if(/[0-9]/.test(s)||s==="-"&&/[0-9]/.test(i[t+1]??"")){let a=t+1;for(;a<n&&/[0-9.]/.test(i[a]);)a++;e.push({type:"NUMBER",value:i.slice(t,a)}),t=a;continue}if(/[A-Za-z_]/.test(s)){let a=t;for(;a<n&&/[A-Za-z0-9_]/.test(i[a]);)a++;e.push({type:"IDENT",value:i.slice(t,a)}),t=a;continue}throw new Re(`Unexpected character '${s}' at position ${t}`)}return e}var ai=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 Re("Unexpected end of expression");return this.pos++,e}expect(e){let t=this.next();if(t.type!==e)throw new Re(`Expected ${e} but got '${t.value}'`);return t}isIdent(e){let t=this.peek();return!!t&&t.type==="IDENT"&&t.value===e}atEnd(){return this.pos>=this.tokens.length}};function Br(i){let e=i.expect("IDENT").value;for(;i.peek()?.type==="DOT";){let t=i.pos;i.next();let n=i.expect("IDENT");if(i.peek()?.type==="LPAREN"){i.pos=t;break}e+=`.${n.value}`}return e}function si(i){let e=Br(i);if(i.peek()?.type==="LBRACKET"){i.next();let t=i.expect("STRING");return i.expect("RBRACKET"),{field:e,key:t.value}}return{field:e}}function _n(i){let e=i.next();if(e.type==="STRING")return e.value;if(e.type==="NUMBER")return Number(e.value);throw new Re(`Unexpected token '${e.value}' where a literal was expected`)}function qr(i){if(i.isIdent("has")){i.next(),i.expect("LPAREN");let a=si(i);return i.expect("RPAREN"),{type:"has",...a}}if(i.isIdent("inIpRange")){i.next(),i.expect("LPAREN");let a=si(i);if(a.field!=="origin.ip")throw new Re(`inIpRange must reference origin.ip, got '${a.field}'`);i.expect("COMMA");let l=i.expect("STRING");return i.expect("RPAREN"),{type:"inIpRange",value:l.value}}let e=si(i);if(i.peek()?.type==="DOT"){i.next();let a=i.expect("IDENT").value;if(!xn[a])throw new Re(`Unrecognized method '${a}'`);i.expect("LPAREN");let l=i.expect("STRING");return i.expect("RPAREN"),{type:"methodCall",...e,method:a,value:l.value}}if(i.isIdent("in")){i.next(),i.expect("LBRACKET");let a=[];for(;i.peek()?.type!=="RBRACKET";)a.push(_n(i)),i.peek()?.type==="COMMA"&&i.next();return i.expect("RBRACKET"),{type:"membership",...e,values:a}}let t=i.next(),o={EQ:"eq",NE:"ne",GT:"gt",GE:"ge",LT:"lt",LE:"le"}[t.type];if(!o)throw new Re(`Unexpected token '${t.value}' after field reference`);let s=_n(i);return{type:"comparison",...e,operator:o,value:s}}function kn(i){if(i.peek()?.type==="LPAREN"){i.next();let e=Dn(i);return i.expect("RPAREN"),e}return qr(i)}function Sn(i){return i.peek()?.type==="NOT"?(i.next(),{type:"not",child:kn(i)}):kn(i)}function Un(i){let e=[Sn(i)];for(;i.peek()?.type==="AND";)i.next(),e.push(Sn(i));return e.length===1?e[0]:{type:"and",children:e}}function Dn(i){let e=[Un(i)];for(;i.peek()?.type==="OR";)i.next(),e.push(Un(i));return e.length===1?e[0]:{type:"or",children:e}}function Wr(i){let e=new ai(Vr(i)),t=Dn(e);if(!e.atEnd())throw new Re("Unexpected trailing tokens");return t}function Mr(i){return i.type==="inIpRange"||i.type==="comparison"&&i.field==="origin.ip"&&i.operator==="eq"}function li(i){return i.type==="or"&&i.children.length>0&&i.children.every(Mr)}function jr(i){return i.type==="inIpRange"?i.value:String(i.value)}function On(i){if(i.type!=="and"||i.children.length!==2)return!1;let e=i.children[0],t=i.children[1];if(e.type!=="has")return!1;let n=t.type==="not"?t.child:t;return!("field"in n)||n.field!==e.field||n.key!==e.key?!1:n.type==="comparison"||n.type==="methodCall"||n.type==="membership"}function zr(i){let e=i.children[0],t=i.children[1],n=t.type==="not",o=n?t.child:t;return{guard:e,comparisonNegated:n,comparison:o}}function Lt(i){if(i.type==="has"||i.type==="comparison"||i.type==="methodCall"||i.type==="membership"||i.type==="inIpRange"||li(i)||On(i))return!0;if(i.type==="not"){let e=i.child;return e.type==="has"||e.type==="comparison"||e.type==="methodCall"||e.type==="membership"||e.type==="inIpRange"||li(e)}return!1}function Fn(i,e){if(i==="origin.ip")return{unifiedField:"ip"};let t=Fr[i];if(t)return{unifiedField:t};if(i==="request.headers"&&e!==void 0){let n=Nr[e];return n?{unifiedField:n}:{unifiedField:"header",unifiedKey:e}}return null}function xt(i,e){let t=i.type==="not",n=i.type==="not"?i.child:i;if(li(n)){let o=n.children.map(s=>jr(s));return{field:"ip",operator:t?"not_in":"in",value:o,...e!==void 0?{group:e}:{}}}if(n.type==="inIpRange"||n.type==="comparison"&&n.field==="origin.ip"){let o=n.type==="inIpRange"?n.value:String(n.value);return{field:"ip",operator:t?"ne":"eq",value:o,...e!==void 0?{group:e}:{}}}if(n.type==="and"&&On(n)){if(t)return null;let{guard:o,comparisonNegated:s,comparison:a}=zr(n);return a.type!=="comparison"&&a.type!=="methodCall"&&a.type!=="membership"?null:Ln(a,s,o.field,o.key,e)}if(n.type==="comparison"||n.type==="methodCall"||n.type==="membership")return Ln(n,t,n.field,n.key,e);if(n.type==="has"){let o=Fn(n.field,n.key);return o?{field:o.unifiedField,operator:t?"not_exists":"exists",value:"",...o.unifiedKey!==void 0?{key:o.unifiedKey}:{},...e!==void 0?{group:e}:{}}:null}return null}function Ln(i,e,t,n,o){let s=Fn(t,n);if(!s)return null;let a,l;if(i.type==="comparison")a=e?Gr(i.operator):i.operator,l=i.value;else if(i.type==="methodCall"){let c=xn[i.method];if(!c||(a=e?`not_${c}`:c,e&&a!=="not_contains"))return null;l=i.value}else a=e?"not_in":"in",l=i.values;return{field:s.unifiedField,operator:a,value:l,...s.unifiedKey!==void 0?{key:s.unifiedKey}:{},...o!==void 0?{group:o}:{}}}function Gr(i){if(i==="eq")return"ne";if(i==="ne")return"eq";throw new Re(`No negated form for comparison operator '${i}'`)}function Kr(i){if(Lt(i)){let e=xt(i,void 0);return e?{conditions:[e],conditionLogic:"AND"}:null}if(i.type==="and"){let e=[];for(let t of i.children){if(!Lt(t))return null;let n=xt(t,void 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(Lt(o)){let a=xt(o,s);a&&e.push(a);return}if(o.type==="and")for(let a of o.children){if(!Lt(a))return;let l=xt(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 Dt(i){if(!i||!i.trim())return null;try{let e=Wr(i);return Kr(e)}catch{return null}}function Nn(i){if(i.priority===void 0)throw new Error(`Rule "${i.name}" has no priority assigned \u2014 CloudArmorFirewallService must assign one before calling unifiedToGcp`);let e=[],t=pt.fromUnifiedConditions(i.conditions,i.conditionLogic),{action:n,actionWarning:o}=Zr(i.action.type,i.name,i.id);o&&e.push(o);let s={priority:i.priority,description:(i.description||i.name).slice(0,64),match:{expr:{expression:t}},action:n,preview:i.action.type==="log"?!0:void 0};if((n==="throttle"||n==="rate_based_ban")&&i.action.rateLimit){let a=Yr(i.action.rateLimit.window);s.rateLimitOptions={rateLimitThreshold:{count:i.action.rateLimit.requests,intervalSec:a},conformAction:"allow",exceedAction:"deny(429)",enforceOnKey:"IP"}}else n==="throttle"&&!i.action.rateLimit&&e.push(U.createWarning("lossy_conversion",i.id,"action.rateLimit",`Rule "${i.name}" maps to Cloud Armor's "throttle" action but declares no rateLimit block \u2014 Cloud Armor requires rateLimitOptions for this action; the rule will likely be rejected by the API.`));return n==="redirect"&&(i.action.redirect?s.redirectOptions={type:"EXTERNAL_302",target:i.action.redirect.location}:e.push(U.createWarning("lossy_conversion",i.id,"action.redirect",`Rule "${i.name}" maps to Cloud Armor's "redirect" action but declares no redirect target \u2014 Cloud Armor requires redirectOptions for this action; the rule will likely be rejected by the API.`))),{result:s,warnings:e}}function Vn(i){let e=[],t=Dt(i.match.expr.expression),n=[],o;t?(n=t.conditions,o=t.conditionLogic):e.push(U.createWarning("complex_expressions",String(i.priority),"match.expr.expression","CEL 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={type:Hr(i.action),...i.rateLimitOptions?{rateLimit:{requests:i.rateLimitOptions.rateLimitThreshold.count,window:`${i.rateLimitOptions.rateLimitThreshold.intervalSec}s`}}:{},...i.redirectOptions?{redirect:{location:i.redirectOptions.target}}:{}};return{result:{id:String(i.priority),name:i.description||`Rule ${i.priority}`,...i.description?{description:i.description}:{},enabled:!i.preview,conditions:n,...o==="OR"?{conditionLogic:o}:{},action:s,priority:i.priority},warnings:e}}function Bn(i){if(i.action!=="allow"&&i.action!=="deny(403)"||i.preview)return!1;let e=Dt(i.match.expr.expression);if(!e||e.conditions.length!==1)return!1;let t=e.conditions[0];return t.field==="ip"&&(t.operator==="eq"||t.operator==="in")&&!t.key}function qn(i){let t=Dt(i.match.expr.expression).conditions[0].value;return{id:String(i.priority),ip:Array.isArray(t)?String(t[0]):String(t),...i.description?{notes:i.description}:{},action:i.action==="allow"?"allow":"deny"}}function Wn(i,e){if(!Pe.safeParse(i.ip).success)throw new Error(`Invalid IP address or CIDR range: ${i.ip}`);let t=pt.fromUnifiedCondition({field:"ip",operator:"eq",value:i.ip});return{priority:e,description:(i.notes||`IP ${i.action}: ${i.ip}${i.hostname?` (${i.hostname})`:""}`).slice(0,64),match:{expr:{expression:t}},action:i.action==="allow"?"allow":"deny(403)"}}function Hr(i){return{allow:"allow","deny(403)":"deny","deny(404)":"deny","deny(502)":"deny",rate_based_ban:"rate_limit",throttle:"rate_limit",redirect:"redirect"}[i]||"deny"}function Zr(i,e,t){switch(i){case"log":return{action:"allow"};case"deny":case"block":return{action:"deny(403)"};case"challenge":return{action:"deny(403)",actionWarning:U.createUnsupportedFeatureWarning("challenge action","unified config","Cloud Armor",t,"action")};case"bypass":return{action:"allow"};case"rate_limit":return{action:"throttle"};case"redirect":return{action:"redirect"};case"allow":return{action:"allow"};default:return{action:"deny(403)",actionWarning:U.createWarning("lossy_conversion",t,"action",`Rule "${e}" has unrecognized action "${i}" \u2014 defaulted to Cloud Armor's "deny(403)".`)}}}function Yr(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={s:1,m:60,h:3600,d:86400}[e[2]];if(o===void 0)throw new Error(`Invalid time unit: ${e[2]}`);return t*o}var A=class{static vercelToUnified=pn;static unifiedToVercel=fn;static vercelIPToUnified=gn;static cloudflareToUnified=Rn;static unifiedToCloudflare=Cn;static unifiedIPToCloudflare=vn;static fastlyToUnified=En;static unifiedToFastly=An;static fastlyListEntriesToUnified=Tn;static unifiedIPsToFastlyEntries=$n;static gcpToUnified=Vn;static unifiedToGcp=Nn;static gcpToUnifiedIP=qn;static unifiedIPToGcp=Wn;static gcpLooksLikeIpRule=Bn};pe();function Oe(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)||!Oe(i[o],e[o]))return!1;return!0}function ge(i){let{id:e,...t}=i;return t}function ft(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 Ot(i){return i.some(e=>e.priority!==void 0)}var Qe=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=A.vercelToUnified(a);return l.warnings.length>0&&l.warnings.forEach(c=>{let{TranslationWarningSystem:d}=(pe(),Ee(Be)),u=d.formatWarning(c);r.warn(`Rule ${a.name}:
|
|
25
|
-
${u}`)}),l.result}),s=n.ips.map(a=>A.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}=(mt(),
|
|
24
|
+
`),u.cancelled&&process.exit(0),e(o))};t.on("keypress",a)})}T();var rn={provider:"vercel",fields:[{key:"token",envVar:"VERCEL_TOKEN",label:"Vercel API Token",required:!0,secret:!0,promptMessage:"What is your Vercel API Auth Token? (https://vercel.com/guides/how-do-i-use-a-vercel-api-access-token#creating-an-access-token) "},{key:"projectId",envVar:"VERCEL_PROJECT_ID",label:"Vercel Project ID",required:!0,configKey:"projectId",cliAlias:"p",legacyConfigKey:"projectId",promptMessage:"What is your Vercel Project ID? (See https://vercel.com/docs/projects/project-configuration/general-settings#project-id)"},{key:"teamId",envVar:"VERCEL_TEAM_ID",label:"Vercel Team ID",required:!1,configKey:"teamId",cliAlias:"t",legacyConfigKey:"teamId",promptMessage:"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)"}]};var sn={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 an={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"}]};var ln={provider:"gcp",fields:[{key:"serviceAccountKeyPath",envVar:"GOOGLE_APPLICATION_CREDENTIALS",label:"GCP Service Account Key Path",required:!1,promptMessage:"Path to a GCP service account JSON key file (leave blank to use Application Default Credentials \u2014 gcloud auth application-default login, or the GCE/Cloud Run metadata server): "},{key:"projectId",envVar:"GOOGLE_CLOUD_PROJECT",label:"GCP Project ID",required:!0,configKey:"projectId"},{key:"policyName",envVar:"GCP_POLICY_NAME",label:"Cloud Armor Security Policy Name",required:!0,configKey:"policyName"}]};function cn(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}function dn(i,e){return i.fields.filter(t=>t.required&&!e[t.key])}var He={vercel:rn,cloudflare:sn,fastly:an,gcp:ln};var Pt=class{static detectionField(e){return He[e].fields.find(t=>t.required&&t.configKey)}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;for(let s of z){let a=this.detectionField(s);if(!a?.configKey)continue;if(typeof(o[s]||{})[a.configKey]=="string")return t.push(`${a.label} found in config`),{provider:s,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;if(t&&this.isValidProvider(t))return e.push(`Provider set via DOORMAN_PROVIDER environment variable: ${t}`),{provider:t,confidence:"high",reasons:e};for(let n of z){let o=this.detectionField(n);if(!(!o||!process.env[o.envVar]))return e.push(`${o.label} found in environment (${o.envVar})`),{provider:n,confidence:"medium",reasons:e}}return{provider:null,confidence:"low",reasons:["No provider credentials found in environment"]}}static isValidProvider(e){return z.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;for(let o of z){let s=this.detectionField(o);if(!s?.configKey)continue;typeof(n[o]||{})[s.configKey]=="string"&&t.add(o)}}e&&"projectId"in e&&typeof e.projectId=="string"&&t.add("vercel");for(let n of z){let o=this.detectionField(n);o&&process.env[o.envVar]&&t.add(n)}return Array.from(t)}};var ii=O(require("chalk"));T();$e();var _t=i=>({$schema:xi,firewallEnabled:!0,rules:[],ips:[],...i});T();var _e=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 f=0;f<=s;f++)try{d=new AbortController,u=setTimeout(()=>{d&&d.abort()},o);let y=await fetch(n,{...l,headers:{"Content-Type":"application/json",...await this.getAuthHeaders(),...l.headers},signal:d.signal});if(u&&(clearTimeout(u),u=null),this.updateRateLimitInfo(y),y.status===429){let C=this.calculateRateLimitWait(f,y);if(f===s)throw new Error(`${this.providerName} API rate limit exceeded after ${s+1} attempt(s) (429 Too Many Requests). Retry after ~${Math.round(C/1e3)}s.`);r.warn(`Rate limit exceeded for ${this.providerName}. Waiting ${C}ms before retry (attempt ${f+1}/${s+1})...`),await this.delay(C);continue}if(!y.ok)throw await this.handleErrorResponse(y);let R;try{let C=await y.text();C.trim()?R=JSON.parse(C):R={}}catch(C){throw r.error(`Failed to parse response from ${n}:`,C),new Error(`Invalid JSON response from ${this.providerName} API: ${C instanceof Error?C.message:String(C)}`)}return this.isLargeResponse(R)&&(r.debug(`Large response detected from ${n}, validating structure...`),this.validateLargeResponse(R)),R}catch(y){if(c=y,u&&(clearTimeout(u),u=null),this.isNonRetryableError(y)||f===s)throw y;let R=a*Math.pow(2,f),C=Math.random()*.1*R,x=Math.min(R+C,3e4);r.debug(`Request failed (attempt ${f+1}/${s+1}). Retrying in ${Math.round(x)}ms...`),r.debug(`Error details: ${y instanceof Error?y.message:String(y)}`),await this.delay(x)}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),f=c.filter(y=>!p.includes(y));f.length>0&&r.warn(`Inconsistent array structure at ${s}[${d}]: missing keys ${f.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 un=process.env.DOORMAN_VERCEL_API_BASE_URL||"https://api.vercel.com/v1/security/firewall/config",Ze=class extends _e{constructor(t,n,o){super("","vercel");this.projectId=t;this.teamId=n;this.token=o}projectId;teamId;token;async getAuthHeaders(){return{Authorization:`Bearer ${this.token}`}}getUrl(t){let n=t!==void 0?`${un}/${t}`:un;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(ii.default.bold("No firewall configuration found.")),!o)return r.debug("Skipping create-configuration prompt for read-only fetch."),this.emptyConfigPlaceholder();if(await b("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: ${ii.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}=_t();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,n?{retries:0}:void 0)}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,n?{retries:0}:void 0)}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 se=O(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}`)}};pe();function pn(i){let e=[],t=[];i.conditionGroup.forEach((s,a)=>{for(let l of s.conditions){let c=ir(l.op);t.push({field:or(l.type),operator:c,...l.value!==void 0?{value:l.value}:{},...l.neg?{negated:!0}:{},...l.key?{key:l.key}:{},group:a})}}),t.length>10&&e.push(U.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,...i.action.mitigate.rateLimit?{rateLimit:{requests:i.action.mitigate.rateLimit.requests,window:i.action.mitigate.rateLimit.window,...i.action.mitigate.rateLimit.characteristics?{characteristics:i.action.mitigate.rateLimit.characteristics}:{},...i.action.mitigate.rateLimit.mitigationTimeout?{mitigationTimeout:i.action.mitigate.rateLimit.mitigationTimeout}:{},...i.action.mitigate.rateLimit.countingExpression?{countingExpression:i.action.mitigate.rateLimit.countingExpression}:{}}}:{},...i.action.mitigate.redirect?{redirect:{location:i.action.mitigate.redirect.location,...i.action.mitigate.redirect.permanent?{permanent:i.action.mitigate.redirect.permanent}:{}}}:{},...i.action.mitigate.actionDuration?{duration:i.action.mitigate.actionDuration}:{}};return{result:{id:i.id,name:i.name,...i.description?{description:i.description}:{},enabled:i.active,conditions:t,conditionLogic:i.conditionGroup.length>1?"OR":"AND",action:n},warnings:e}}function fn(i){let e=[],t=tr(i.conditions,i.id,e);if(i.action.response&&e.push(U.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 gn(i){return{id:i.id,ip:i.ip,...i.hostname?{hostname:i.hostname}:{},...i.notes?{notes:i.notes}:{},action:i.action}}function tr(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=sr(l.field);if(!c){t.push(U.createUnsupportedFeatureWarning(`condition field '${l.field}'`,"unified config","Vercel",e,l.field));continue}a.push({op:nr(l.operator),neg:l.negated,type:c,key:l.key,value:l.value})}a.length>0&&o.push({conditions:a})}return o}function ir(i){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists",nex:"not_exists"}[i]||"eq"}function nr(i){return{eq:"eq",starts_with:"pre",ends_with:"suf",in:"inc",contains:"sub",matches:"re",exists:"ex",not_exists:"nex"}[i]||"eq"}function or(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 rr={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 sr(i){return rr[i]??null}pe();T();function Ye(i){return i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function mn(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 dt=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}["${Ye(t.toLowerCase())}"]`:e==="cookie"&&t?`${n}["${Ye(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 ar=new Set(["ip.src"]),ut=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=dt.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}["${Ye(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(ar.has(e)){if(!Pe.safeParse(t).success)throw new Error(`Invalid IP address or CIDR range: ${t}`);return t}return`"${Ye(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 lr={"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"},cr=new Set(["eq","ne","contains","starts_with","ends_with","matches","in","gt","ge","lt","le"]),dr=new Set(["and","or","not"]),Se=class extends Error{};function ur(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 Se("Unterminated string literal");e.push({type:"STRING",value:mn(l)}),t=a;continue}let s=t;for(;s<n&&!/[\s(){}[\]"]/.test(i[s]);)s++;if(s===t)throw new Se(`Unexpected character '${o}' at position ${t}`);e.push({type:"WORD",value:i.slice(t,s)}),t=s}return e}var ni=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 Se("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 Se(`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 oi(i){let e=[hn(i)];for(;i.isWord("or");)i.next(),e.push(hn(i));return e.length===1?e[0]:{type:"or",children:e}}function hn(i){let e=[yn(i)];for(;i.isWord("and");)i.next(),e.push(yn(i));return e.length===1?e[0]:{type:"and",children:e}}function yn(i){if(i.isWord("not")){i.next(),i.expect("LPAREN");let e=oi(i);return i.expect("RPAREN"),{type:"not",child:e}}return pr(i)}function pr(i){let e=i.peek();if(e&&e.type==="LPAREN"){i.next();let t=oi(i);return i.expect("RPAREN"),t}return mr(i)}function fr(i){let e=i.expect("WORD");if(dr.has(e.value))throw new Se(`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 wn(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 Se(`Unexpected token '${e.value}' where a value was expected`)}function gr(i){if(i.peek()?.type==="LBRACE"){i.next();let e=[];for(;i.peek()?.type!=="RBRACE";)e.push(wn(i));return i.expect("RBRACE"),e}return wn(i)}function mr(i){let{field:e,key:t}=fr(i);if(i.isWord("exists"))return i.next(),{type:"exists",field:e,key:t};let n=i.next();if(n.type!=="WORD"||!cr.has(n.value))throw new Se(`Unsupported or unrecognized operator '${n.value}'`);let o=gr(i);return{type:"comparison",field:e,key:t,operator:n.value,value:o}}function hr(i){let e=new ni(ur(i)),t=oi(e);if(!e.atEnd())throw new Se("Unexpected trailing tokens");return t}function kt(i){return i.type==="comparison"||i.type==="exists"?!0:i.type==="not"?i.child.type==="comparison"||i.child.type==="exists":!1}function St(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=lr[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 yr(i){if(kt(i)){let e=St(i,0);return e?{conditions:[e],conditionLogic:"AND"}:null}if(i.type==="and"){let e=[];for(let t of i.children){if(!kt(t))return null;let n=St(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(kt(o)){let a=St(o,s);a&&e.push(a);return}if(o.type==="and")for(let a of o.children){if(!kt(a))return;let l=St(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 ri(i){if(!i||!i.trim())return null;try{let e=hr(i);return yr(e)}catch{return null}}function Rn(i){let e=[],t=ri(i.expression),n=[],o;t?(n=t.conditions,o=t.conditionLogic):e.push(U.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:wr(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 Cn(i){let e=[],t=ut.fromUnifiedConditions(i.conditions,i.conditionLogic),n={id:i.id||crypto.randomUUID(),action:Rr(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:Cr(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,e.push(U.createWarning("rate_limiting_precision",i.id,"action.rateLimit.mitigationTimeout",`No mitigationTimeout set for rate limit rule "${i.name}" \u2014 defaulted to Cloudflare's 3600s (1 hour) block duration.`))),i.action.rateLimit.countingExpression&&(n.ratelimit.counting_expression=i.action.rateLimit.countingExpression)),i.action.type==="redirect"&&i.action.redirect&&(n.action_parameters={from_value:{status_code:i.action.redirect.statusCode??(i.action.redirect.permanent?301:302),target_url:{value:i.action.redirect.location},...i.action.redirect.preserveQueryString!==void 0?{preserve_query_string:i.action.redirect.preserveQueryString}:{}}}),i.action.response&&(n.action!=="block"?e.push(U.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(U.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 bn(i){if(!Pe.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 wr(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 Rr(i){return{log:"log",deny:"block",block:"block",challenge:"managed_challenge",bypass:"skip",rate_limit:"block",redirect:"redirect",allow:"allow"}[i]||"block"}function Cr(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}pe();function fe(i,e,t){return U.createWarning("complex_expressions",i,void 0,e,t)}var br={ip:"ip",path:"path",domain:"host",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},vr={ip:"ip",path:"path",host:"domain",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},Ir={header:"request_header",query:"query_parameter",cookie:"request_cookie"},Er={request_header:"header",query_parameter:"query",request_cookie:"cookie",response_header:"response_header",post_parameter:"post_parameter",signal:"signal"};function Ar(i){return br[i]??i}function Tr(i){return vr[i]??null}var $r={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 vn(i){return $r[i]??{operator:"eq",negated:!1}}function In(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(U.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(U.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(fe(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(fe(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 Pr(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(fe(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)Ut(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;Ut(t,s,l,e,i.id)}),{conditions:t,conditionLogic:i.group_operator==="any"&&o.length>1?"OR":"AND"};e.push(fe(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)Ut(t,s,0,e,i.id);for(let s of n)for(let a of s.conditions)Ut(t,a,0,e,i.id);return{conditions:t,conditionLogic:"AND"}}function Ut(i,e,t,n,o){if(e.type==="single"){let{operator:u,negated:p}=vn(e.operator);i.push({field:Ar(e.field),operator:u,value:e.value,...p?{negated:!0}:{},group:t});return}let s=Er[e.field],a=e.conditions.find(u=>u.field==="name"),l=e.conditions.find(u=>u.field==="value"||u.field==="value_string");if(!l){if(a){i.push({field:s,operator:e.operator==="does_not_exist"?"not_exists":"exists",key:a.value,group:t});return}n.push(fe(o,`Multival condition on '${e.field}' has no value or name sub-condition doorman could extract \u2014 skipped.`));return}let{operator:c,negated:d}=vn(l.operator);i.push({field:s,operator:c,value:l.value,...d?{negated:!0}:{},...a?{key:a.value}:{},group:t})}function _r(i,e){i.actions.length>1&&e.push(fe(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(U.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(fe(i.id,`Unrecognised Fastly action type "${String(t?.type)}" \u2014 mapped to "log".`)),{type:"log"}}}function En(i){let e=[],{conditions:t,conditionLogic:n}=Pr(i,e),o=_r(i,e);return t.length>10&&e.push(U.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 kr(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=Ir[a.field];if(l){if(a.key===void 0)return t.push(fe(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;if(a.operator==="exists"||a.operator==="not_exists")return{type:"multival",field:l,operator:a.operator==="exists"?"exists":"does_not_exist",group_operator:"all",conditions:[{type:"single",field:"name",operator:"equals",value:a.key}]};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:In(a.operator,a.negated,t,e),value:String(a.value)}]}}if(a.operator==="exists"||a.operator==="not_exists")return t.push(U.createUnsupportedFeatureWarning(`"${a.operator}" on field '${a.field}'`,"unified config","Fastly",e,a.field)),null;let c=Tr(a.field);return c?{type:"single",field:c,operator:In(a.operator,a.negated,t,e),value:String(a.value)}:(t.push(U.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 Sr(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(fe(t,'Unified action "bypass" has no direct Fastly equivalent \u2014 mapped to "allow".')),{type:"allow"};case"log":return e.push(fe(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(fe(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(U.createUnsupportedFeatureWarning(`action type '${i.type}'`,"unified config","Fastly",t,"action.type")),{type:"block"}}}function Ur(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(U.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(U.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 Lr(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=Ur(i.window,t,e);return t.push(U.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 An(i){let e=[];i.description&&i.description!==i.name&&e.push(fe(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}=kr(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:[Sr(i.action,e,i.id)],rate_limit:a?Lr(i.action.rateLimit,i.id,e):null},warnings:e}}function Tn(i,e){return i.map(t=>({ip:t,action:e}))}function $n(i){let e=[],t=[],n=[];for(let o of i)(o.hostname||o.notes)&&e.push(fe(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}}pe();function Je(i){return i.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Pn(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 xr=new Set(["region","city","port","scheme"]),Dr={host:"host",user_agent:"user-agent",referer:"referer"},pt=class{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"?" && ":" || ";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){if(xr.has(e.field))throw new Error(`Cloud Armor has no CEL equivalent for the "${e.field}" condition field \u2014 this rule cannot be represented and would otherwise be silently dropped.`);if(e.field==="ip")return this.buildIpCondition(e);if(e.field==="cookie")return this.buildCookieCondition(e);let t=Dr[e.field];if(t)return this.buildHeaderCondition(t,e);if(e.field==="header"||e.field==="query"){if(e.field==="header"){if(!e.key)throw new Error('A "header" condition requires a key naming the header');return this.buildHeaderCondition(e.key,e)}return this.buildComparison("request.query",e,!1)}let n=Fr[e.field];if(n)return this.buildComparison(n.path,e,n.numeric);throw new Error(`Cloud Armor CEL builder has no mapping for condition field "${e.field}"`)}static buildIpCondition(e){let t=(Array.isArray(e.value)?e.value:[e.value]).map(String);if(t.length===0||t.some(a=>!a))throw new Error('An "ip" condition requires at least one value');let n=t.map(a=>{if(!Pe.safeParse(a).success)throw new Error(`Invalid IP address or CIDR range: ${a}`);return a.includes("/")?`inIpRange(origin.ip, '${Je(a)}')`:`origin.ip == '${Je(a)}'`}),o=this.isNegated(e,e.operator==="not_in"||e.operator==="ne");if(n.length>1){let a=`(${n.join(" || ")})`;return o?`!${a}`:a}let s=n[0];return o?s.startsWith("inIpRange(")?`!${s}`:`!(${s})`:s}static buildHeaderCondition(e,t){let n=`request.headers['${Je(e)}']`,o=`has(${n})`;return t.operator==="exists"||t.operator==="not_exists"?this.isNegated(t,t.operator==="not_exists")?`!${o}`:o:`(${o} && ${this.buildComparison(n,t,!1)})`}static buildCookieCondition(e){let t="request.headers['cookie']",n=`has(${t})`;if(e.operator==="exists"||e.operator==="not_exists")return this.isNegated(e,e.operator==="not_exists")?`!${n}`:n;if(!e.key)return`(${n} && ${this.buildComparison(t,e,!1)})`;if(!["eq","ne","contains","not_contains"].includes(e.operator))throw new Error(`Cloud Armor can only check a specific cookie's value via substring search (has no parsed cookie map) \u2014 "${e.operator}" on a keyed cookie condition has no unambiguous CEL representation.`);let o=`${e.key}=${String(e.value)}`,s=`${t}.contains('${Je(o)}')`,a=this.isNegated(e,e.operator==="ne"||e.operator==="not_contains");return`(${n} && ${a?`!${s}`:s})`}static buildComparison(e,t,n){let{value:o}=t;if(t.operator==="exists"||t.operator==="not_exists")throw new Error(`"${t.operator}" is not meaningful for Cloud Armor's "${e}" \u2014 it is always present`);let s=t.operator,a=!1;if(t.negated){let d=Or[s];d?s=d:a=!0}if(s==="in"||s==="not_in"){let u=(Array.isArray(o)?o:[o]).map(f=>this.formatLiteral(f,n)).join(", "),p=`${e} in [${u}]`;return s==="not_in"?`!(${p})`:p}let l=this.formatLiteral(o,n),c;switch(s){case"eq":c=`${e} == ${l}`;break;case"ne":c=`${e} != ${l}`;break;case"contains":c=`${e}.contains(${l})`;break;case"not_contains":c=`!${e}.contains(${l})`;break;case"starts_with":c=`${e}.startsWith(${l})`;break;case"ends_with":c=`${e}.endsWith(${l})`;break;case"matches":c=`${e}.matches(${l})`;break;case"gt":c=`${e} > ${l}`;break;case"ge":c=`${e} >= ${l}`;break;case"lt":c=`${e} < ${l}`;break;case"le":c=`${e} <= ${l}`;break;default:throw new Error(`Cloud Armor CEL builder has no mapping for operator "${s}"`)}return a?`!(${c})`:c}static isNegated(e,t){return t!==!!e.negated}static formatLiteral(e,t){if(t){let n=Number(e);if(!Number.isFinite(n))throw new Error(`Expected a numeric value, got "${String(e)}"`);return String(n)}return`'${Je(String(e))}'`}static combineWithAnd(e){if(e.length===0)throw new Error("At least one expression is required");return e.length===1?e[0]:`(${e.join(" && ")})`}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={eq:"ne",ne:"eq",contains:"not_contains",not_contains:"contains",in:"not_in",not_in:"in"},Fr={country:{path:"origin.region_code",numeric:!1},asn:{path:"origin.asn",numeric:!0},path:{path:"request.path",numeric:!1},method:{path:"request.method",numeric:!1}};var Nr={"origin.region_code":"country","origin.asn":"asn","request.path":"path","request.method":"method","request.query":"query"},Vr={host:"host","user-agent":"user_agent",referer:"referer",cookie:"cookie"},xn={contains:"contains",startsWith:"starts_with",endsWith:"ends_with",matches:"matches"},Ee=class extends Error{};function Br(i){let e=[],t=0,n=i.length,o=(s,a)=>i[t]===s&&i[t+1]===a;for(;t<n;){let s=i[t];if(/\s/.test(s)){t++;continue}if(s==="("){e.push({type:"LPAREN",value:s}),t++;continue}if(s===")"){e.push({type:"RPAREN",value:s}),t++;continue}if(s==="["){e.push({type:"LBRACKET",value:s}),t++;continue}if(s==="]"){e.push({type:"RBRACKET",value:s}),t++;continue}if(s===","){e.push({type:"COMMA",value:s}),t++;continue}if(o("&","&")){e.push({type:"AND",value:"&&"}),t+=2;continue}if(o("|","|")){e.push({type:"OR",value:"||"}),t+=2;continue}if(o("=","=")){e.push({type:"EQ",value:"=="}),t+=2;continue}if(o("!","=")){e.push({type:"NE",value:"!="}),t+=2;continue}if(o(">","=")){e.push({type:"GE",value:">="}),t+=2;continue}if(o("<","=")){e.push({type:"LE",value:"<="}),t+=2;continue}if(s==="!"){e.push({type:"NOT",value:"!"}),t++;continue}if(s===">"){e.push({type:"GT",value:">"}),t++;continue}if(s==="<"){e.push({type:"LT",value:"<"}),t++;continue}if(s==="."){e.push({type:"DOT",value:s}),t++;continue}if(s==="'"){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 Ee("Unterminated string literal");e.push({type:"STRING",value:Pn(l)}),t=a;continue}if(/[0-9]/.test(s)||s==="-"&&/[0-9]/.test(i[t+1]??"")){let a=t+1;for(;a<n&&/[0-9.]/.test(i[a]);)a++;e.push({type:"NUMBER",value:i.slice(t,a)}),t=a;continue}if(/[A-Za-z_]/.test(s)){let a=t;for(;a<n&&/[A-Za-z0-9_]/.test(i[a]);)a++;e.push({type:"IDENT",value:i.slice(t,a)}),t=a;continue}throw new Ee(`Unexpected character '${s}' at position ${t}`)}return e}var ai=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 Ee("Unexpected end of expression");return this.pos++,e}expect(e){let t=this.next();if(t.type!==e)throw new Ee(`Expected ${e} but got '${t.value}'`);return t}isIdent(e){let t=this.peek();return!!t&&t.type==="IDENT"&&t.value===e}atEnd(){return this.pos>=this.tokens.length}};function qr(i){let e=i.expect("IDENT").value;for(;i.peek()?.type==="DOT";){let t=i.pos;i.next();let n=i.expect("IDENT");if(i.peek()?.type==="LPAREN"){i.pos=t;break}e+=`.${n.value}`}return e}function si(i){let e=qr(i);if(i.peek()?.type==="LBRACKET"){i.next();let t=i.expect("STRING");return i.expect("RBRACKET"),{field:e,key:t.value}}return{field:e}}function _n(i){let e=i.next();if(e.type==="STRING")return e.value;if(e.type==="NUMBER")return Number(e.value);throw new Ee(`Unexpected token '${e.value}' where a literal was expected`)}function Wr(i){if(i.isIdent("has")){i.next(),i.expect("LPAREN");let a=si(i);return i.expect("RPAREN"),{type:"has",...a}}if(i.isIdent("inIpRange")){i.next(),i.expect("LPAREN");let a=si(i);if(a.field!=="origin.ip")throw new Ee(`inIpRange must reference origin.ip, got '${a.field}'`);i.expect("COMMA");let l=i.expect("STRING");return i.expect("RPAREN"),{type:"inIpRange",value:l.value}}let e=si(i);if(i.peek()?.type==="DOT"){i.next();let a=i.expect("IDENT").value;if(!xn[a])throw new Ee(`Unrecognized method '${a}'`);i.expect("LPAREN");let l=i.expect("STRING");return i.expect("RPAREN"),{type:"methodCall",...e,method:a,value:l.value}}if(i.isIdent("in")){i.next(),i.expect("LBRACKET");let a=[];for(;i.peek()?.type!=="RBRACKET";)a.push(_n(i)),i.peek()?.type==="COMMA"&&i.next();return i.expect("RBRACKET"),{type:"membership",...e,values:a}}let t=i.next(),o={EQ:"eq",NE:"ne",GT:"gt",GE:"ge",LT:"lt",LE:"le"}[t.type];if(!o)throw new Ee(`Unexpected token '${t.value}' after field reference`);let s=_n(i);return{type:"comparison",...e,operator:o,value:s}}function kn(i){if(i.peek()?.type==="LPAREN"){i.next();let e=Dn(i);return i.expect("RPAREN"),e}return Wr(i)}function Sn(i){return i.peek()?.type==="NOT"?(i.next(),{type:"not",child:kn(i)}):kn(i)}function Un(i){let e=[Sn(i)];for(;i.peek()?.type==="AND";)i.next(),e.push(Sn(i));return e.length===1?e[0]:{type:"and",children:e}}function Dn(i){let e=[Un(i)];for(;i.peek()?.type==="OR";)i.next(),e.push(Un(i));return e.length===1?e[0]:{type:"or",children:e}}function Mr(i){let e=new ai(Br(i)),t=Dn(e);if(!e.atEnd())throw new Ee("Unexpected trailing tokens");return t}function jr(i){return i.type==="inIpRange"||i.type==="comparison"&&i.field==="origin.ip"&&i.operator==="eq"}function li(i){return i.type==="or"&&i.children.length>0&&i.children.every(jr)}function zr(i){return i.type==="inIpRange"?i.value:String(i.value)}function On(i){if(i.type!=="and"||i.children.length!==2)return!1;let e=i.children[0],t=i.children[1];if(e.type!=="has")return!1;let n=t.type==="not"?t.child:t;return!("field"in n)||n.field!==e.field||n.key!==e.key?!1:n.type==="comparison"||n.type==="methodCall"||n.type==="membership"}function Gr(i){let e=i.children[0],t=i.children[1],n=t.type==="not",o=n?t.child:t;return{guard:e,comparisonNegated:n,comparison:o}}function Lt(i){if(i.type==="has"||i.type==="comparison"||i.type==="methodCall"||i.type==="membership"||i.type==="inIpRange"||li(i)||On(i))return!0;if(i.type==="not"){let e=i.child;return e.type==="has"||e.type==="comparison"||e.type==="methodCall"||e.type==="membership"||e.type==="inIpRange"||li(e)}return!1}function Fn(i,e){if(i==="origin.ip")return{unifiedField:"ip"};let t=Nr[i];if(t)return{unifiedField:t};if(i==="request.headers"&&e!==void 0){let n=Vr[e];return n?{unifiedField:n}:{unifiedField:"header",unifiedKey:e}}return null}function xt(i,e){let t=i.type==="not",n=i.type==="not"?i.child:i;if(li(n)){let o=n.children.map(s=>zr(s));return{field:"ip",operator:t?"not_in":"in",value:o,...e!==void 0?{group:e}:{}}}if(n.type==="inIpRange"||n.type==="comparison"&&n.field==="origin.ip"){let o=n.type==="inIpRange"?n.value:String(n.value);return{field:"ip",operator:t?"ne":"eq",value:o,...e!==void 0?{group:e}:{}}}if(n.type==="and"&&On(n)){if(t)return null;let{guard:o,comparisonNegated:s,comparison:a}=Gr(n);return a.type!=="comparison"&&a.type!=="methodCall"&&a.type!=="membership"?null:Ln(a,s,o.field,o.key,e)}if(n.type==="comparison"||n.type==="methodCall"||n.type==="membership")return Ln(n,t,n.field,n.key,e);if(n.type==="has"){let o=Fn(n.field,n.key);return o?{field:o.unifiedField,operator:t?"not_exists":"exists",value:"",...o.unifiedKey!==void 0?{key:o.unifiedKey}:{},...e!==void 0?{group:e}:{}}:null}return null}function Ln(i,e,t,n,o){let s=Fn(t,n);if(!s)return null;let a,l,c=!1;if(i.type==="comparison")e?i.operator==="eq"?a="ne":i.operator==="ne"?a="eq":(a=i.operator,c=!0):a=i.operator,l=i.value;else if(i.type==="methodCall"){let d=xn[i.method];if(!d)return null;e?d==="contains"?a="not_contains":(a=d,c=!0):a=d,l=i.value}else a=e?"not_in":"in",l=i.values;return{field:s.unifiedField,operator:a,value:l,...c?{negated:!0}:{},...s.unifiedKey!==void 0?{key:s.unifiedKey}:{},...o!==void 0?{group:o}:{}}}function Kr(i){if(Lt(i)){let e=xt(i,void 0);return e?{conditions:[e],conditionLogic:"AND"}:null}if(i.type==="and"){let e=[];for(let t of i.children){if(!Lt(t))return null;let n=xt(t,void 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(Lt(o)){let a=xt(o,s);a&&e.push(a);return}if(o.type==="and")for(let a of o.children){if(!Lt(a))return;let l=xt(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 Dt(i){if(!i||!i.trim())return null;try{let e=Mr(i);return Kr(e)}catch{return null}}function Nn(i){if(i.priority===void 0)throw new Error(`Rule "${i.name}" has no priority assigned \u2014 CloudArmorFirewallService must assign one before calling unifiedToGcp`);let e=[],t=pt.fromUnifiedConditions(i.conditions,i.conditionLogic),{action:n,actionWarning:o}=Zr(i.action.type,i.name,i.id);o&&e.push(o);let s={priority:i.priority,description:(i.description||i.name).slice(0,64),match:{expr:{expression:t}},action:n,preview:i.action.type==="log"?!0:void 0};if((n==="throttle"||n==="rate_based_ban")&&i.action.rateLimit){let a=Yr(i.action.rateLimit.window);s.rateLimitOptions={rateLimitThreshold:{count:i.action.rateLimit.requests,intervalSec:a},conformAction:"allow",exceedAction:"deny(429)",enforceOnKey:"IP"}}else n==="throttle"&&!i.action.rateLimit&&e.push(U.createWarning("lossy_conversion",i.id,"action.rateLimit",`Rule "${i.name}" maps to Cloud Armor's "throttle" action but declares no rateLimit block \u2014 Cloud Armor requires rateLimitOptions for this action; the rule will likely be rejected by the API.`));return n==="redirect"&&(i.action.redirect?s.redirectOptions={type:"EXTERNAL_302",target:i.action.redirect.location}:e.push(U.createWarning("lossy_conversion",i.id,"action.redirect",`Rule "${i.name}" maps to Cloud Armor's "redirect" action but declares no redirect target \u2014 Cloud Armor requires redirectOptions for this action; the rule will likely be rejected by the API.`))),{result:s,warnings:e}}function Vn(i){let e=[],t=Dt(i.match.expr.expression),n=[],o;t?(n=t.conditions,o=t.conditionLogic):e.push(U.createWarning("complex_expressions",String(i.priority),"match.expr.expression","CEL 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={type:Hr(i.action),...i.rateLimitOptions?{rateLimit:{requests:i.rateLimitOptions.rateLimitThreshold.count,window:`${i.rateLimitOptions.rateLimitThreshold.intervalSec}s`}}:{},...i.redirectOptions?{redirect:{location:i.redirectOptions.target}}:{}};return{result:{id:String(i.priority),name:i.description||`Rule ${i.priority}`,...i.description?{description:i.description}:{},enabled:!i.preview,conditions:n,...o==="OR"?{conditionLogic:o}:{},action:s,priority:i.priority},warnings:e}}function Bn(i){if(i.action!=="allow"&&i.action!=="deny(403)"||i.preview)return!1;let e=Dt(i.match.expr.expression);if(!e||e.conditions.length!==1)return!1;let t=e.conditions[0];return t.field==="ip"&&(t.operator==="eq"||t.operator==="in")&&!t.key}function qn(i){let t=Dt(i.match.expr.expression).conditions[0].value;return{id:String(i.priority),ip:Array.isArray(t)?String(t[0]):String(t),...i.description?{notes:i.description}:{},action:i.action==="allow"?"allow":"deny"}}function Wn(i,e){if(!Pe.safeParse(i.ip).success)throw new Error(`Invalid IP address or CIDR range: ${i.ip}`);let t=pt.fromUnifiedCondition({field:"ip",operator:"eq",value:i.ip});return{priority:e,description:(i.notes||`IP ${i.action}: ${i.ip}${i.hostname?` (${i.hostname})`:""}`).slice(0,64),match:{expr:{expression:t}},action:i.action==="allow"?"allow":"deny(403)"}}function Hr(i){return{allow:"allow","deny(403)":"deny","deny(404)":"deny","deny(502)":"deny",rate_based_ban:"rate_limit",throttle:"rate_limit",redirect:"redirect"}[i]||"deny"}function Zr(i,e,t){switch(i){case"log":return{action:"allow"};case"deny":case"block":return{action:"deny(403)"};case"challenge":return{action:"deny(403)",actionWarning:U.createUnsupportedFeatureWarning("challenge action","unified config","Cloud Armor",t,"action")};case"bypass":return{action:"allow"};case"rate_limit":return{action:"throttle"};case"redirect":return{action:"redirect"};case"allow":return{action:"allow"};default:return{action:"deny(403)",actionWarning:U.createWarning("lossy_conversion",t,"action",`Rule "${e}" has unrecognized action "${i}" \u2014 defaulted to Cloud Armor's "deny(403)".`)}}}function Yr(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={s:1,m:60,h:3600,d:86400}[e[2]];if(o===void 0)throw new Error(`Invalid time unit: ${e[2]}`);return t*o}var A=class{static vercelToUnified=pn;static unifiedToVercel=fn;static vercelIPToUnified=gn;static cloudflareToUnified=Rn;static unifiedToCloudflare=Cn;static unifiedIPToCloudflare=bn;static fastlyToUnified=En;static unifiedToFastly=An;static fastlyListEntriesToUnified=Tn;static unifiedIPsToFastlyEntries=$n;static gcpToUnified=Vn;static unifiedToGcp=Nn;static gcpToUnifiedIP=qn;static unifiedIPToGcp=Wn;static gcpLooksLikeIpRule=Bn};pe();function Oe(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)||!Oe(i[o],e[o]))return!1;return!0}function ge(i){let{id:e,...t}=i;return t}function ft(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 Ot(i){return i.some(e=>e.priority!==void 0)}var Qe=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=A.vercelToUnified(a);return l.warnings.length>0&&l.warnings.forEach(c=>{let{TranslationWarningSystem:d}=(pe(),Ie(Be)),u=d.formatWarning(c);r.warn(`Rule ${a.name}:
|
|
25
|
+
${u}`)}),l.result}),s=n.ips.map(a=>A.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}=(mt(),Ie(gt)),a=await s.performDryRunValidation(t,"sync rules",async g=>await this.getChanges(g,{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,f=l.ipsToAdd||[],y=l.ipsToUpdate||[],R=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: ${f.length}, Update: ${y.length}, Delete: ${R.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,version:p,warnings:a.warnings};let C=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Vercel project ${this.client.projectId}`,changes:l,riskLevel:C,skipConfirmation:n.force||!1,dryRun:!1,allowDeletions:n.allowDeletions||!1}))throw new Error("Operation cancelled by user");let N=c.map(g=>A.unifiedToVercel(g).result),V=d.map(g=>A.unifiedToVercel(g).result),ce=u.map(g=>A.unifiedToVercel(g).result),de=f.map(g=>({id:g.id||"",ip:g.ip,hostname:g.hostname||"",action:g.action,notes:g.notes})),me=y.map(g=>({id:g.id||"",ip:g.ip,hostname:g.hostname||"",action:g.action,notes:g.notes})),S=R.map(g=>({id:g.id||"",ip:g.ip,hostname:g.hostname||"",action:g.action,notes:g.notes})),ue=[],he=[],ye=[],Te=[],ve=[],P=[],m=[],$=(g,I)=>`${g}: ${I instanceof Error?I.message:String(I)}`,D=[];Ot(t.rules)&&t.rules.length>c.length&&D.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 we=[];for(let g of ce)try{r.debug(`Deleting custom rule: ${g.id}`),await this.client.deleteFirewallRule(g),ye.push(g),r.debug(`Custom rule deleted: ${g.id}`)}catch(I){r.error(`Failed to delete custom rule ${g.id}:`,I),m.push($(`Failed to delete custom rule ${g.id}`,I))}for(let g of S)try{r.debug(`Deleting IP blocking rule: ${g.id}`),await this.client.deleteIPBlockingRule(g),P.push(g),r.debug(`IP blocking rule deleted: ${g.id}`)}catch(I){r.error(`Failed to delete IP blocking rule ${g.id}:`,I),m.push($(`Failed to delete IP blocking rule ${g.id}`,I))}for(let g of N)try{r.debug(`Adding new custom rule: ${g.name}`);let I=await this.client.createFirewallRule(g);ue.push(I),I.id&&I.id!==g.id&&we.push({oldId:g.id||void 0,newId:I.id,name:g.name}),r.debug(`New custom rule added: ${I.id}`)}catch(I){r.error(`Failed to add custom rule "${g.name}":`,I),m.push($(`Failed to add custom rule "${g.name}"`,I))}for(let g of de)try{r.debug(`Adding new IP blocking rule: ${g.ip}`);let I=await this.client.createIPBlockingRule(g);Te.push(I),r.debug(`New IP blocking rule added: (hostname): ${I.hostname} (ip): ${I.ip}`)}catch(I){r.error(`Failed to add IP blocking rule ${g.ip}:`,I),m.push($(`Failed to add IP blocking rule ${g.ip}`,I))}for(let g of V)try{r.debug(`Updating custom rule: ${g.id}`);let I=await this.client.updateFirewallRule(g);he.push(I),r.debug(`Custom rule updated: ${I.id}`)}catch(I){r.error(`Failed to update custom rule ${g.id}:`,I),m.push($(`Failed to update custom rule ${g.id}`,I))}for(let g of me)try{r.debug(`Updating IP blocking rule: ${g.id}`);let I=await this.client.updateIPBlockingRule(g);ve.push(I),r.debug(`IP blocking rule updated: ${I.id}`)}catch(I){r.error(`Failed to update IP blocking rule ${g.id}:`,I),m.push($(`Failed to update IP blocking rule ${g.id}`,I))}r.debug(`${se.default.underline("Custom Rules:")} ${se.default.green("Added:")} ${se.default.green(ue.length)}, ${se.default.cyan("Updated:")} ${se.default.cyan(he.length)}, ${se.default.red("Deleted:")} ${se.default.red(ye.length)}`),r.debug(`${se.default.underline("IP Rules:")} ${se.default.green("Added:")} ${se.default.green(Te.length)}, ${se.default.cyan("Updated:")} ${se.default.cyan(ve.length)}, ${se.default.red("Deleted:")} ${se.default.red(P.length)}`);let st=p,at,Ne=[...D];try{let g=await this.client.fetchFirewallConfig();st=g.version,at=g.updatedAt;let I=new Set(g.rules.map(M=>M.id)),_i=new Set(g.ips.map(M=>M.id));for(let M of[...ue,...he])M.id&&!I.has(M.id)&&Ne.push(`Rule "${M.name}" (${M.id}) was synced but is missing from the post-sync remote config \u2014 a subsequent sync may re-create or misdiff it.`);for(let M of ye)M.id&&I.has(M.id)&&Ne.push(`Rule "${M.name}" (${M.id}) was deleted but still appears in the post-sync remote config.`);for(let M of[...Te,...ve])M.id&&!_i.has(M.id)&&Ne.push(`IP rule "${M.ip}" (${M.id}) was synced but is missing from the post-sync remote config \u2014 a subsequent sync may re-create or misdiff it.`);for(let M of P)M.id&&_i.has(M.id)&&Ne.push(`IP rule "${M.ip}" (${M.id}) was deleted but still appears in the post-sync remote config.`)}catch(g){r.error("Failed to fetch updated firewall configuration version after sync:",g),m.push($("Failed to fetch updated configuration version after sync",g))}return{success:m.length===0,rulesAdded:ue.length,rulesUpdated:he.length,rulesDeleted:ye.length,ipsAdded:Te.length,ipsUpdated:ve.length,ipsDeleted:P.length,version:st,updatedAt:at,idRemappings:we.length>0?we:void 0,errors:m.length>0?m:void 0,warnings:Ne.length>0?Ne: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=Ue.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(R=>{let C=A.vercelToUnified(R);return C.warnings.length>0&&C.warnings.forEach(x=>{let{TranslationWarningSystem:N}=(pe(),Ie(Be)),V=N.formatWarning(x);r.warn(`Rule ${R.name}:
|
|
26
26
|
${V}`)}),C.result}),{toAdd:l,toUpdate:c,toDelete:d}=this.diffRules(ft(o.data.rules),a),u=s.ips.map(R=>A.vercelIPToUnified(R)),{ipsToAdd:p,ipsToUpdate:f,ipsToDelete:y}=this.diffIPRules(o.data.ips||[],u);return{version:s.version,rulesToAdd:l,rulesToUpdate:c,rulesToDelete:d,ipsToAdd:p,ipsToUpdate:f,ipsToDelete:y,hasChanges:l.length>0||c.length>0||d.length>0||p.length>0||f.length>0||y.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=Ve.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{Oe(ge(l),ge(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{Oe(ge(l),ge(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 ht=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 Ze(t,n,e);return new Qe(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 Ze(n,o,t);return new Qe(s)}static create(e,t,n){return this.fromConfig({projectId:e,teamId:t,token:n})}};var zn=require("crypto");T();var We=O(require("chalk")),h=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(We.default.red.bold(`[${this.code}] ${this.message}`)),e.push(""),this.suggestion&&(e.push(We.default.yellow.bold("Suggestion:")),e.push(` ${this.suggestion}`),e.push("")),this.details&&Object.keys(this.details).length>0&&(e.push(We.default.dim("Details:")),Object.entries(this.details).forEach(([t,n])=>{let o=typeof n=="object"?JSON.stringify(n,null,2).split(`
|
|
27
27
|
`).join(`
|
|
28
28
|
`):n;e.push(` ${We.default.cyan(t)}: ${o}`)}),e.push("")),this.cause&&(e.push(We.default.dim("Caused by:")),e.push(` ${this.cause.message}`),e.push("")),this.docsUrl&&(e.push(We.default.cyan.bold("Documentation:")),e.push(` ${this.docsUrl}`),e.push("")),e.join(`
|
|
29
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 L="https://docs.doorman.griffen.codes/errors";var Y={authFailed:(i,e)=>new h({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:`${L}/PROV_5000`}),apiError:(i,e,t,n)=>new h({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:`${L}/PROV_5002`}),rateLimit:(i,e)=>new h({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:`${L}/PROV_5003`}),timeout:(i,e)=>new h({code:"PROV_5006",message:`Request timeout for ${i} ${e}`,suggestion:"Check your internet connection and try again",details:{provider:i,operation:e},docsUrl:`${L}/PROV_5006`}),invalidCredentials:(i,e)=>new h({code:"PROV_5004",message:`Missing or invalid credentials for ${i}`,suggestion:`Please provide: ${e.join(", ")}`,details:{provider:i,missing:e},docsUrl:`${L}/PROV_5004`})},j={accountIdRequired:i=>new h({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:`${L}/CF_6004`}),zoneIdRequired:i=>new h({code:"CF_6005",message:`Zone ID required for ${i}`,suggestion:"Provide CLOUDFLARE_ZONE_ID in your environment or configuration",details:{operation:i},docsUrl:`${L}/CF_6005`}),invalidCredentials:(i,e)=>new h({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:`${L}/CF_6016`}),insufficientPermissions:(i,e)=>new h({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:`${L}/CF_6017`}),ruleLimitExceeded:(i,e)=>new h({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:`${L}/CF_6001`}),invalidExpression:(i,e)=>new h({code:"CF_6002",message:`Invalid Cloudflare expression: ${e}`,suggestion:"Check Cloudflare Wirefilter expression syntax and field names",details:{expression:i,reason:e},docsUrl:`${L}/CF_6002`}),ruleNoConditions:i=>new h({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:`${L}/CF_6007`}),invalidRateLimit:(i,e)=>new h({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:`${L}/CF_6008`}),invalidWindowFormat:i=>new h({code:"CF_6009",message:`Invalid rate limit window format: ${i}`,suggestion:'Use format like "60s", "5m", "1h", or "1d"',details:{window:i},docsUrl:`${L}/CF_6009`}),shortMitigationTimeout:i=>new h({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:`${L}/CF_6010`}),redirectNoLocation:i=>new h({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:`${L}/CF_6011`}),invalidRedirectUrl:i=>new h({code:"CF_6012",message:`Invalid redirect URL: ${i}`,suggestion:"Use a valid absolute URL (https://...) or relative path (/...)",details:{url:i},docsUrl:`${L}/CF_6012`}),invalidIP:i=>new h({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:`${L}/CF_6013`}),largeIPList:i=>new h({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:`${L}/CF_6014`}),rulesetNotFound:i=>new h({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:`${L}/CF_6000`}),listNotFound:i=>new h({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:`${L}/CF_6003`}),emptyCharacteristics:i=>new h({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:`${L}/CF_6015`}),translationWarning:(i,e)=>new h({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:`${L}/CF_6018`}),featureUnsupported:(i,e)=>new h({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:`${L}/CF_6019`}),planLimitExceeded:(i,e,t)=>new h({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:`${L}/CF_6020`}),zoneSuspended:(i,e)=>new h({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:`${L}/CF_6021`}),maintenanceMode:i=>new h({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:`${L}/CF_6022`}),quotaExceeded:(i,e)=>new h({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:`${L}/CF_6023`}),listsAPIUnavailable:(i,e)=>new h({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:`${L}/setup#account-id`}),performanceWarning:(i,e,t)=>new h({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:`${L}/performance#large-ip-lists`})};var J=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 h({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 h({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 h({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 h({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 h({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}=(pe(),Ee(Be)),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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 ts={defaultTTL:300*1e3,maxEntries:100,enableLogging:!0},Nt=class{cache=new Map;options;stats={hits:0,misses:0,evictions:0};constructor(e={}){this.options={...ts,...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}`))}},Me={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}`},je={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 is={maxConnections:6,idleTimeout:3e4,keepAlive:!0},ns={ttl:5e3,maxEntries:100},ze=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={...is,...e},this.dedupOptions={...ns,...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 f=p.id||p.name;o.set(f,{rule:p,hash:this.computeRuleHash(p)})}let s=new Map,a=[],l=[],c=0;for(let p of e){let f=p.id||p.name;s.set(f,!0);let y=o.get(f);y?this.computeRuleHash(p)!==y.hash?l.push(p):c++:a.push(p)}let d=[];for(let[p,f]of o)s.has(p)||d.push(f.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:f}of e){let y=p.id||p.name;o.add(y);let R=n.get(y);R?this.cloudflareRulesEqual(f,R)||a.push(p):s.push(p)}let l=[];for(let[p,f]of n)o.has(p)||l.push(f);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,f)=>{if(u[f]===p||c.has(p))return;let y=e.find(({rule:R})=>(R.id||R.name)===p);y&&(a.push(y.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 f=o.get(p.ip);f?p.action!==f.action?l.push(p):c++:a.push(p)}let d=[];for(let[p,f]of o)s.has(p)||d.push(f);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 Xe=class extends _e{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 Nt({enableLogging:!0}),this.optimizer=new ze}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}`)}async 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=Me.rulesets(this.zoneId),t=this.cache.get(e);if(t)return t;let n=ze.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 J.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,je.RULESETS),s}catch(o){throw o instanceof Error&&!o.code?J.handleNetworkError(o,"listing rulesets"):o}})}async getRulesets(){return this.listRulesets()}async getRuleset(e){r.debug(`Fetching ruleset ${e}`);let t=Me.ruleset(this.zoneId,e),n=this.cache.get(t);if(n)return n;let o=ze.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 J.handleApiResponse(s,`/zones/${this.zoneId}/rulesets/${e}`);if(!s.result||typeof s.result!="object")throw J.handleValidationError("ruleset","Invalid ruleset data received from API",s.result);let a=s.result;if(!a.id||!a.name)throw J.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,je.RULESET),a}catch(s){throw s instanceof Error&&!s.code?J.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 Y.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 Y.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 Y.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 Y.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 Y.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 Y.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,zn.createHash)("sha256").update(this.apiToken).digest("hex").slice(0,8),t=Me.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,je.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 J.handleCredentialError("token");if(s.includes("forbidden")||s.includes("access denied"))throw J.handleCredentialError("zone",this.zoneId);if(s.includes("not found"))throw J.handleCredentialError("zone",this.zoneId)}return!1}}async getZoneInfo(){let e=Me.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 Y.apiError("cloudflare",`/zones/${this.zoneId}`,n.errors[0]?.code||0,o)}return this.cache.set(e,n.result,je.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=Me.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 Y.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,n.errors[0]?.code||0,o)}return this.cache.set(e,n.result,je.LISTS),n.result}async getList(e){if(r.debug(`Fetching List ${e}`),!this.accountId)throw j.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 Y.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 j.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 Y.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 j.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 Y.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 j.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 Y.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 j.accountIdRequired("Lists API");let t=Me.listItems(this.accountId,e),n=this.cache.get(t);if(n)return n;let o=ze.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,je.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 Y.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 j.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 Y.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 j.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 Y.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"),J.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?J.handleNetworkError(e,"managing IP blocklist"):e}}};var et=require("net");T();var yt=class i extends ke{name="cloudflare";client;optimizer;useListsForIPs;constructor(e,t,n){super(),this.client=new Xe(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 f=this.cloudflareRuleToIPRule(p);o.push(f)}else{let f=A.cloudflareToUnified(p);n.push(f.result),f.warnings.length>0&&f.warnings.forEach(y=>{let{TranslationWarningSystem:R}=(pe(),Ee(Be)),C=R.formatWarning(y);s.push(C)})}}catch(f){let y=`Failed to process rule ${p?.id||"unknown"}: ${f instanceof Error?f.message:String(f)}`;r.warn(y),a.push(y)}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)?J.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}=(mt(),
|
|
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 L="https://docs.doorman.griffen.codes/errors";var Y={authFailed:(i,e)=>new h({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:`${L}/PROV_5000`}),apiError:(i,e,t,n)=>new h({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:`${L}/PROV_5002`}),rateLimit:(i,e)=>new h({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:`${L}/PROV_5003`}),timeout:(i,e)=>new h({code:"PROV_5006",message:`Request timeout for ${i} ${e}`,suggestion:"Check your internet connection and try again",details:{provider:i,operation:e},docsUrl:`${L}/PROV_5006`}),invalidCredentials:(i,e)=>new h({code:"PROV_5004",message:`Missing or invalid credentials for ${i}`,suggestion:`Please provide: ${e.join(", ")}`,details:{provider:i,missing:e},docsUrl:`${L}/PROV_5004`})},j={accountIdRequired:i=>new h({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:`${L}/CF_6004`}),zoneIdRequired:i=>new h({code:"CF_6005",message:`Zone ID required for ${i}`,suggestion:"Provide CLOUDFLARE_ZONE_ID in your environment or configuration",details:{operation:i},docsUrl:`${L}/CF_6005`}),invalidCredentials:(i,e)=>new h({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:`${L}/CF_6016`}),insufficientPermissions:(i,e)=>new h({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:`${L}/CF_6017`}),ruleLimitExceeded:(i,e)=>new h({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:`${L}/CF_6001`}),invalidExpression:(i,e)=>new h({code:"CF_6002",message:`Invalid Cloudflare expression: ${e}`,suggestion:"Check Cloudflare Wirefilter expression syntax and field names",details:{expression:i,reason:e},docsUrl:`${L}/CF_6002`}),ruleNoConditions:i=>new h({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:`${L}/CF_6007`}),invalidRateLimit:(i,e)=>new h({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:`${L}/CF_6008`}),invalidWindowFormat:i=>new h({code:"CF_6009",message:`Invalid rate limit window format: ${i}`,suggestion:'Use format like "60s", "5m", "1h", or "1d"',details:{window:i},docsUrl:`${L}/CF_6009`}),shortMitigationTimeout:i=>new h({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:`${L}/CF_6010`}),redirectNoLocation:i=>new h({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:`${L}/CF_6011`}),invalidRedirectUrl:i=>new h({code:"CF_6012",message:`Invalid redirect URL: ${i}`,suggestion:"Use a valid absolute URL (https://...) or relative path (/...)",details:{url:i},docsUrl:`${L}/CF_6012`}),invalidIP:i=>new h({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:`${L}/CF_6013`}),largeIPList:i=>new h({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:`${L}/CF_6014`}),rulesetNotFound:i=>new h({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:`${L}/CF_6000`}),listNotFound:i=>new h({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:`${L}/CF_6003`}),emptyCharacteristics:i=>new h({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:`${L}/CF_6015`}),translationWarning:(i,e)=>new h({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:`${L}/CF_6018`}),featureUnsupported:(i,e)=>new h({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:`${L}/CF_6019`}),planLimitExceeded:(i,e,t)=>new h({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:`${L}/CF_6020`}),zoneSuspended:(i,e)=>new h({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:`${L}/CF_6021`}),maintenanceMode:i=>new h({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:`${L}/CF_6022`}),quotaExceeded:(i,e)=>new h({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:`${L}/CF_6023`}),listsAPIUnavailable:(i,e)=>new h({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:`${L}/setup#account-id`}),performanceWarning:(i,e,t)=>new h({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:`${L}/performance#large-ip-lists`})};var J=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 h({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 h({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 h({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 h({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 h({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}=(pe(),Ie(Be)),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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 h({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 ts={defaultTTL:300*1e3,maxEntries:100,enableLogging:!0},Nt=class{cache=new Map;options;stats={hits:0,misses:0,evictions:0};constructor(e={}){this.options={...ts,...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}`))}},Me={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}`},je={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 is={maxConnections:6,idleTimeout:3e4,keepAlive:!0},ns={ttl:5e3,maxEntries:100},ze=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={...is,...e},this.dedupOptions={...ns,...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 f=p.id||p.name;o.set(f,{rule:p,hash:this.computeRuleHash(p)})}let s=new Map,a=[],l=[],c=0;for(let p of e){let f=p.id||p.name;s.set(f,!0);let y=o.get(f);y?this.computeRuleHash(p)!==y.hash?l.push(p):c++:a.push(p)}let d=[];for(let[p,f]of o)s.has(p)||d.push(f.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:f}of e){let y=p.id||p.name;o.add(y);let R=n.get(y);R?this.cloudflareRulesEqual(f,R)||a.push(p):s.push(p)}let l=[];for(let[p,f]of n)o.has(p)||l.push(f);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,f)=>{if(u[f]===p||c.has(p))return;let y=e.find(({rule:R})=>(R.id||R.name)===p);y&&(a.push(y.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 f=o.get(p.ip);f?p.action!==f.action?l.push(p):c++:a.push(p)}let d=[];for(let[p,f]of o)s.has(p)||d.push(f);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 Xe=class extends _e{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 Nt({enableLogging:!0}),this.optimizer=new ze}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}`)}async 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=Me.rulesets(this.zoneId),t=this.cache.get(e);if(t)return t;let n=ze.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 J.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,je.RULESETS),s}catch(o){throw o instanceof Error&&!o.code?J.handleNetworkError(o,"listing rulesets"):o}})}async getRulesets(){return this.listRulesets()}async getRuleset(e){r.debug(`Fetching ruleset ${e}`);let t=Me.ruleset(this.zoneId,e),n=this.cache.get(t);if(n)return n;let o=ze.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 J.handleApiResponse(s,`/zones/${this.zoneId}/rulesets/${e}`);if(!s.result||typeof s.result!="object")throw J.handleValidationError("ruleset","Invalid ruleset data received from API",s.result);let a=s.result;if(!a.id||!a.name)throw J.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,je.RULESET),a}catch(s){throw s instanceof Error&&!s.code?J.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 Y.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 Y.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 Y.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 Y.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 Y.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 Y.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,zn.createHash)("sha256").update(this.apiToken).digest("hex").slice(0,8),t=Me.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,je.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 J.handleCredentialError("token");if(s.includes("forbidden")||s.includes("access denied"))throw J.handleCredentialError("zone",this.zoneId);if(s.includes("not found"))throw J.handleCredentialError("zone",this.zoneId)}return!1}}async getZoneInfo(){let e=Me.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 Y.apiError("cloudflare",`/zones/${this.zoneId}`,n.errors[0]?.code||0,o)}return this.cache.set(e,n.result,je.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=Me.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 Y.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,n.errors[0]?.code||0,o)}return this.cache.set(e,n.result,je.LISTS),n.result}async getList(e){if(r.debug(`Fetching List ${e}`),!this.accountId)throw j.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 Y.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 j.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 Y.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 j.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 Y.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 j.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 Y.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 j.accountIdRequired("Lists API");let t=Me.listItems(this.accountId,e),n=this.cache.get(t);if(n)return n;let o=ze.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,je.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 Y.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 j.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 Y.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 j.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 Y.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"),J.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?J.handleNetworkError(e,"managing IP blocklist"):e}}};var et=require("net");T();var yt=class i extends ke{name="cloudflare";client;optimizer;useListsForIPs;constructor(e,t,n){super(),this.client=new Xe(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 f=this.cloudflareRuleToIPRule(p);o.push(f)}else{let f=A.cloudflareToUnified(p);n.push(f.result),f.warnings.length>0&&f.warnings.forEach(y=>{let{TranslationWarningSystem:R}=(pe(),Ie(Be)),C=R.formatWarning(y);s.push(C)})}}catch(f){let y=`Failed to process rule ${p?.id||"unknown"}: ${f instanceof Error?f.message:String(f)}`;r.warn(y),a.push(y)}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)?J.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}=(mt(),Ie(gt)),o=await n.performDryRunValidation(e,"sync rules",async R=>await this.getChanges(R));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 R of ft(e.rules)){let C=A.unifiedToCloudflare(R);c.push(C.result),C.warnings.length>0&&C.warnings.forEach(x=>{let{TranslationWarningSystem:N}=(pe(),Ie(Be)),V=N.formatWarning(x);r.warn(V)})}let d=0,u=0,p=0;if(this.useListsForIPs&&e.ips&&e.ips.length>0){let R=new Set;try{let C=await this.client.getOrCreateIPBlocklist(),x=await this.client.getListItems(C.id),N=new Set(x.map(S=>S.ip));N.forEach(S=>S&&R.add(S));let V=new Set(e.ips.map(S=>S.ip)),ce=e.ips.filter(S=>!N.has(S.ip));ce.length>0&&(await this.client.addListItems(C.id,{items:ce.map(S=>({ip:S.ip,comment:S.notes||S.hostname||"Blocked by Doorman"}))}),d=ce.length,ce.forEach(S=>R.add(S.ip)),r.info(`Added ${d} IPs to List`));let de=x.filter(S=>S.ip&&!V.has(S.ip));de.length>0&&(await this.client.removeListItems(C.id,{items:de.map(S=>({id:S.id}))}),p=de.length,de.forEach(S=>S.ip&&R.delete(S.ip)),r.info(`Removed ${p} IPs from List`));let me=`ip.src in $${C.name.replace(/\s+/g,"_").toLowerCase()}`;c.push({id:"rule_doorman_ip_list",action:"block",expression:me,description:"Block IPs in Doorman IP Blocklist",enabled:!0})}catch(C){this.handleListsAPIFallback(C,"syncing IPs via List");let x=e.ips.filter(N=>!R.has(N.ip));if(x.length>0){r.info(`\u{1F504} Falling back to individual IP rules for ${x.length} IPs`);for(let N of x){let V=A.unifiedIPToCloudflare(N);c.push(V)}d=x.length}else r.info("All IPs were already confirmed in the List before the failure; no fallback rules needed.");x.length>50&&r.warn(`\u26A0\uFE0F Performance warning: Using ${x.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 R of e.ips){let C=A.unifiedIPToCloudflare(R);c.push(C)}d=e.ips.length}let f=await this.client.updateRuleset(l.id,{rules:c}),y={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(f.version,10),warnings:o.warnings?.length?o.warnings:void 0};return this.logSyncStats(y),y}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=ft(e.rules).map(c=>({rule:c,translated:A.unifiedToCloudflare(c).result})),s=this.optimizer.diffCloudflareRules(o,n),a=s.toDelete.map(c=>A.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=j.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=j.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=j.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=j.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=j.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=j.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=j.invalidRedirectUrl(c.location);n.push({path:`rules[${l}].action.redirect.location`,message:d.message,code:d.code})}}else{let d=j.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=j.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=j.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,et.isIPv4)(t)||(0,et.isIPv6)(t);if(!/^\d+$/.test(n))return!1;let s=Number(n);return(0,et.isIPv4)(t)?s<=32:(0,et.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:
|
|
32
32
|
\u2022 Set CLOUDFLARE_ACCOUNT_ID in your environment
|
|
33
33
|
\u2022 Ensure your API token has Account:Read permissions
|
|
34
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:
|
|
35
35
|
\u2022 Ensure your API token has Account:Read permissions
|
|
36
36
|
\u2022 Verify the account ID is correct
|
|
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 wt=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 yt(o,s,a)}static fromEnv(){return this.create()}static fromConfig(e){return this.create(e.apiToken,e.zoneId,e.accountId)}};T();T();var Gn=process.env.DOORMAN_FASTLY_API_BASE_URL||"https://api.fastly.com",Rt="doorman-managed-deny",Ct="doorman-managed-allow",tt=class extends _e{constructor(t,n){super(Gn,"fastly");this.workspaceId=t;this.apiToken=n}workspaceId;apiToken;async 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 it=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(Rt),this.client.findList(Ct)]),s=this.translateFastlyRules(t),a=[...A.fastlyListEntriesToUnified(n?.entries??[],"deny"),...A.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=A.fastlyToUnified(o);s.warnings.length>0&&s.warnings.forEach(a=>{let{TranslationWarningSystem:l}=(pe(),
|
|
38
|
-
${l.formatWarning(a)}`)}),n.push(s.result)}return n}async syncRules(t,n={}){let{dryRun:o=!1}=n;try{let{OperationSafety:s}=(mt(),
|
|
39
|
-
${c.formatWarning(l)}`)}),n.push(a.result)}return{rules:n,ips:o}}async syncRules(t,n={}){let{dryRun:o=!1}=n;try{let{OperationSafety:s}=(mt(),
|
|
40
|
-
`),z.forEach((s,a)=>{r.info(` ${a+1}. ${It(s)}`)}),r.info("");let i=await
|
|
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 wt=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 yt(o,s,a)}static fromEnv(){return this.create()}static fromConfig(e){return this.create(e.apiToken,e.zoneId,e.accountId)}};T();T();var Gn=process.env.DOORMAN_FASTLY_API_BASE_URL||"https://api.fastly.com",Rt="doorman-managed-deny",Ct="doorman-managed-allow",tt=class extends _e{constructor(t,n){super(Gn,"fastly");this.workspaceId=t;this.apiToken=n}workspaceId;apiToken;async 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 it=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(Rt),this.client.findList(Ct)]),s=this.translateFastlyRules(t),a=[...A.fastlyListEntriesToUnified(n?.entries??[],"deny"),...A.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=A.fastlyToUnified(o);s.warnings.length>0&&s.warnings.forEach(a=>{let{TranslationWarningSystem:l}=(pe(),Ie(Be));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}=(mt(),Ie(gt)),a=await s.performDryRunValidation(t,"sync rules",async m=>this.getChanges(m));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||[],f=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: ${f.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,warnings:a.warnings};let y=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Fastly workspace ${this.client.workspaceId}`,changes:l,riskLevel:y,skipConfirmation:n.force||!1,dryRun:!1,allowDeletions:n.allowDeletions||!1}))throw new Error("Operation cancelled by user");let C=[];Ot(t.rules)&&C.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 x=c.map(m=>({rule:m,translated:A.unifiedToFastly(m)})),N=d.map(m=>({rule:m,translated:A.unifiedToFastly(m)})),V=[],ce=(m,$)=>`${m}: ${$ instanceof Error?$.message:String($)}`,de=[],me=[],S=[],ue=[];for(let m of u)if(m.id)try{r.debug(`Deleting Fastly rule: ${m.id}`),await this.client.deleteRule(m.id),S.push(m.id)}catch($){r.error(`Failed to delete Fastly rule ${m.id}:`,$),V.push(ce(`Failed to delete rule ${m.id}`,$))}for(let{rule:m,translated:$}of x){let D=$.result;try{r.debug(`Adding new Fastly rule: ${D.description}`);let we=await this.client.createRule(D);de.push(we),ue.push({oldId:m.id||void 0,newId:we.id,name:D.description})}catch(we){r.error(`Failed to add Fastly rule "${D.description}":`,we),V.push(ce(`Failed to add rule "${D.description}"`,we))}}for(let{rule:m,translated:$}of N)if(m.id)try{r.debug(`Updating Fastly rule: ${m.id}`);let D=await this.client.updateRule(m.id,$.result);me.push(D)}catch(D){r.error(`Failed to update Fastly rule ${m.id}:`,D),V.push(ce(`Failed to update rule ${m.id}`,D))}let he=0,ye=0,Te=t.ips||[],{result:ve,warnings:P}=A.unifiedIPsToFastlyEntries(Te);P.forEach(m=>C.push(m.message));try{for(let[m,$]of[[Rt,ve.denyEntries],[Ct,ve.allowEntries]]){let we=(await this.client.findList(m))?.entries??[],st=$.filter(g=>!we.includes(g)),at=we.filter(g=>!$.includes(g));if(st.length===0&&at.length===0)continue;let Ne=await this.client.getOrCreateList(m);await this.client.updateListEntries(Ne.id,$),he+=st.length,ye+=at.length}}catch(m){r.error("Failed to sync Fastly IP lists:",m),V.push(ce("Failed to sync IP lists",m))}return r.debug(`Custom Rules: Added: ${de.length}, Updated: ${me.length}, Deleted: ${S.length}`),r.debug(`IP Rules: Added: ${he}, Deleted: ${ye}`),{success:V.length===0,rulesAdded:de.length,rulesUpdated:me.length,rulesDeleted:S.length,ipsAdded:he,ipsUpdated:0,ipsDeleted:ye,idRemappings:ue.length>0?ue:void 0,errors:V.length>0?V:void 0,warnings:C.length>0?C: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=Ue.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(Rt),this.client.findList(Ct)]),l=this.translateFastlyRules(o),{toAdd:c,toUpdate:d,toDelete:u}=this.diffRules(t.rules,l),p=s?.entries??[],f=a?.entries??[],y=[...A.fastlyListEntriesToUnified(p,"deny"),...A.fastlyListEntriesToUnified(f,"allow")],{ipsToAdd:R,ipsToDelete:C}=this.diffIPs(t.ips||[],y);return{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u,ipsToAdd:R,ipsToUpdate:[],ipsToDelete:C,hasChanges:c.length>0||d.length>0||u.length>0||R.length>0||C.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{Oe(ge(l),ge(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 bt=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 tt(t,e);return new it(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 tt(n,t);return new it(o)}static create(e,t){return this.fromConfig({workspaceId:e,apiToken:t})}};var Hn=require("google-auth-library");T();var Zn=process.env.DOORMAN_GCP_API_BASE_URL||"https://compute.googleapis.com/compute/v1",os="https://www.googleapis.com/auth/compute",rs=1e3,Kn=6e4,nt=class extends _e{auth;projectId;policyName;constructor(e,t,n){super(`${Zn}/projects/${e}/global`,"gcp"),this.projectId=e,this.policyName=t,this.auth=new Hn.GoogleAuth({scopes:[os],...n?{keyFile:n}:{}})}async getAuthHeaders(){return await(await this.auth.getClient()).getRequestHeaders()}policyPath(...e){return["/securityPolicies",this.policyName,...e].join("/")}async getPolicy(){return this.get(this.policyPath())}async addRule(e){let t=await this.post(this.policyPath("addRule"),e);await this.waitForOperation(t)}async patchRule(e,t){let n=await this.post(`${this.policyPath("patchRule")}?priority=${e}`,t);await this.waitForOperation(n)}async removeRule(e){let t=await this.post(`${this.policyPath("removeRule")}?priority=${e}`);await this.waitForOperation(t)}async waitForOperation(e){let t=Date.now()+Kn,n=e;for(;n.status!=="DONE";){if(Date.now()>=t)throw new Error(`gcp operation "${n.name}" did not complete within ${Kn}ms (last status: ${n.status})`);await this.delay(rs),n=await this.get(`/operations/${n.name}`)}if(n.httpErrorStatusCode||n.error){let o=n.error?.errors?.map(s=>s.message).join(", ")||n.httpErrorMessage;throw new Error(`gcp operation "${n.name}" failed: ${o||"unknown error"}`)}n.warnings?.length&&n.warnings.forEach(o=>r.warn(`gcp operation "${n.name}" warning: ${o.message}`))}async verifyCredentials(){try{return await this.getPolicy(),!0}catch(e){return r.debug("Credential verification failed:",e),!1}}};T();function Vt(i){return i!==void 0&&/^\d+$/.test(i)?Number(i):void 0}var ot=class extends ke{constructor(t){super();this.client=t}client;name="gcp";async fetchConfig(){try{r.debug("Fetching Cloud Armor security policy");let t=await this.client.getPolicy(),{rules:n,ips:o}=this.translatePolicy(t);return{version:"2.0",provider:"gcp",providers:{gcp:{projectId:this.client.projectId,policyName:this.client.policyName}},rules:n,ips:o}}catch(t){throw r.error("Error fetching Cloud Armor configuration:",t),new Error("Failed to fetch Cloud Armor security policy")}}translatePolicy(t){let n=[],o=[];for(let s of t.rules){if(A.gcpLooksLikeIpRule(s)){o.push(A.gcpToUnifiedIP(s));continue}let a=A.gcpToUnified(s);a.warnings.length>0&&a.warnings.forEach(l=>{let{TranslationWarningSystem:c}=(pe(),Ie(Be));r.warn(`Rule ${s.description||s.priority}:
|
|
39
|
+
${c.formatWarning(l)}`)}),n.push(a.result)}return{rules:n,ips:o}}async syncRules(t,n={}){let{dryRun:o=!1}=n;try{let{OperationSafety:s}=(mt(),Ie(gt)),a=await s.performDryRunValidation(t,"sync rules",async P=>this.getChanges(P));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||[],f=l.ipsToUpdate||[],y=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}, Update: ${f.length}, Delete: ${y.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,warnings:a.warnings};let R=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Cloud Armor policy ${this.client.policyName}`,changes:l,riskLevel:R,skipConfirmation:n.force||!1,dryRun:!1,allowDeletions:n.allowDeletions||!1}))throw new Error("Operation cancelled by user");let x=[],N=[],V=(P,m)=>`${P}: ${m instanceof Error?m.message:String(m)}`,ce=await this.client.getPolicy(),de=new Set(ce.rules.map(P=>P.priority)),me=1e3,S=()=>{for(;de.has(me);)me+=1e3;return de.add(me),me},ue=[];for(let P of[...u,...y]){let m=Vt(P.id);if(m!==void 0)try{r.debug(`Removing Cloud Armor rule at priority ${m}`),await this.client.removeRule(m)}catch($){r.error(`Failed to remove Cloud Armor rule at priority ${m}:`,$),N.push(V(`Failed to delete rule at priority ${m}`,$))}}let he=0;for(let P of c){let m=P.priority??S(),$=A.unifiedToGcp({...P,priority:m});$.warnings.forEach(D=>x.push(D.message));try{r.debug(`Adding Cloud Armor rule at priority ${m}: ${$.result.description}`),await this.client.addRule($.result),he++,ue.push({oldId:P.id,newId:String(m),name:P.name})}catch(D){r.error(`Failed to add Cloud Armor rule "${P.name}":`,D),N.push(V(`Failed to add rule "${P.name}"`,D))}}let ye=0;for(let P of d){let m=Vt(P.id);if(m===void 0)continue;let $=A.unifiedToGcp(P);$.warnings.forEach(D=>x.push(D.message));try{r.debug(`Updating Cloud Armor rule at priority ${m}`),await this.client.patchRule(m,$.result),ye++}catch(D){r.error(`Failed to update Cloud Armor rule at priority ${m}:`,D),N.push(V(`Failed to update rule at priority ${m}`,D))}}let Te=0;for(let P of p){let m=Vt(P.id)??S(),$=A.unifiedIPToGcp(P,m);try{r.debug(`Adding Cloud Armor IP rule at priority ${m}: ${P.ip}`),await this.client.addRule($),Te++,ue.push({oldId:P.id,newId:String(m),name:P.ip})}catch(D){r.error(`Failed to add Cloud Armor IP rule for ${P.ip}:`,D),N.push(V(`Failed to add IP rule for ${P.ip}`,D))}}let ve=0;for(let P of f){let m=Vt(P.id);if(m!==void 0)try{r.debug(`Updating Cloud Armor IP rule at priority ${m}: ${P.ip}`),await this.client.patchRule(m,A.unifiedIPToGcp(P,m)),ve++}catch($){r.error(`Failed to update Cloud Armor IP rule at priority ${m}:`,$),N.push(V(`Failed to update IP rule at priority ${m}`,$))}}return r.debug(`Custom Rules: Added: ${he}, Updated: ${ye}, Deleted: ${u.length}`),r.debug(`IP Rules: Added: ${Te}, Updated: ${ve}, Deleted: ${y.length}`),{success:N.length===0,rulesAdded:he,rulesUpdated:ye,rulesDeleted:u.length,ipsAdded:Te,ipsUpdated:ve,ipsDeleted:y.length,idRemappings:ue.length>0?ue:void 0,errors:N.length>0?N:void 0,warnings:x.length>0?x: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=Ue.safeParse(t);if(!n.success)throw new Error(`Invalid firewall configuration: ${n.error.message}`);try{r.debug("Fetching existing Cloud Armor configuration");let o=await this.client.getPolicy(),{rules:s,ips:a}=this.translatePolicy(o),{toAdd:l,toUpdate:c,toDelete:d}=this.diffItems(t.rules,s,(y,R)=>Oe(ge(y),ge(R))),{toAdd:u,toUpdate:p,toDelete:f}=this.diffItems(t.ips||[],a,(y,R)=>Oe(ge(y),ge(R)));return{rulesToAdd:l,rulesToUpdate:c,rulesToDelete:d,ipsToAdd:u,ipsToUpdate:p,ipsToDelete:f,hasChanges:l.length>0||c.length>0||d.length>0||u.length>0||p.length>0||f.length>0}}catch(o){throw r.error("Error fetching existing Cloud Armor configuration:",o),new Error("Failed to fetch existing Cloud Armor configuration")}}getSupportedFeatures(){return{supportsCustomRules:!0,supportsIPBlocking:!0,supportsRateLimiting:!0,supportsManagedRules:!1,supportsGeoBlocking:!0,supportsRedirect:!0,supportsChallenge:!1}}async verifyCredentials(){return this.client.verifyCredentials()}validateConfig(t){let n=super.validateConfig(t),o=[...n.errors],s=[...n.warnings];return t.provider&&t.provider!=="gcp"&&o.push({path:"provider",message:"Provider must be 'gcp' for CloudArmorFirewallService",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}}};T();var vt=class{static fromEnv(){let e=process.env.GOOGLE_CLOUD_PROJECT,t=process.env.GCP_POLICY_NAME,n=process.env.GOOGLE_APPLICATION_CREDENTIALS;if(!e)throw new Error("GOOGLE_CLOUD_PROJECT environment variable is required");if(!t)throw new Error("GCP_POLICY_NAME environment variable is required");let o=new nt(e,t,n);return new ot(o)}static fromConfig(e){let t=e.projectId||process.env.GOOGLE_CLOUD_PROJECT,n=e.policyName||process.env.GCP_POLICY_NAME,o=e.serviceAccountKeyPath||process.env.GOOGLE_APPLICATION_CREDENTIALS;if(!t)throw new Error("GCP project ID is required (provide projectId or set GOOGLE_CLOUD_PROJECT env var)");if(!n)throw new Error("Cloud Armor policy name is required (provide policyName or set GCP_POLICY_NAME env var)");r.debug("Creating Cloud Armor provider with config:",{projectId:t,policyName:n});let s=new nt(t,n,o);return new ot(s)}static create(e,t,n){return this.fromConfig({projectId:e,policyName:t,serviceAccountKeyPath:n})}};async function Jn(i){let e;if(i.provider)e=i.provider,r.debug(`Using explicitly specified provider: ${e}`);else{let t=Pt.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 ds():(e="vercel",r.warn("No provider detected, defaulting to Vercel"))}try{let t=await as(e,i);return cs(e,t)}catch(t){throw r.error(`Failed to initialize ${e} provider:`,t),t}}function ss(i,e,t){if(!t.configKey)return;let o=i?.providers?.[e]?.[t.configKey];if(typeof o=="string")return o;if(t.legacyConfigKey){let s=i?.[t.legacyConfigKey];if(typeof s=="string")return s}}async function as(i,e){let t=He[i],n=e.config,o={};for(let l of t.fields)o[l.key]=ss(n,i,l);let s=cn(t,{explicit:e.credentials,config:o}),a=dn(t,s);if(a.length===0)return s;if(e.interactive===!1){let l=a.map(c=>`--${c.key}`).join(", ");throw new Error(`${It(i)} credentials missing. Provide ${l}.`)}r.warn(`Missing ${It(i)} credentials`),r.info(`Please provide your ${It(i)} credentials:`);for(let l of t.fields){if(s[l.key])continue;let c=l.promptMessage??ls(l),d=l.secret?await on(c):await b(c,{type:"text"});s[l.key]=d||void 0}return s}function ls(i){let e=i.required?"":" (optional)",t=i.secret?" ":"";return`${i.label}${e}:${t}`}function cs(i,e){switch(i){case"vercel":{let t={token:e.token,projectId:e.projectId,teamId:e.teamId};return{provider:ht.fromConfig(t),vercelCredentials:t}}case"cloudflare":return{provider:wt.fromConfig({apiToken:e.apiToken,zoneId:e.zoneId,accountId:e.accountId})};case"fastly":return{provider:bt.fromConfig({apiToken:e.apiToken,workspaceId:e.workspaceId})};case"gcp":return{provider:vt.fromConfig({projectId:e.projectId,policyName:e.policyName,serviceAccountKeyPath:e.serviceAccountKeyPath})};default:throw new Error(`Unknown provider: ${i}`)}}async function ds(){r.info(Yn.default.yellow("Unable to auto-detect firewall provider.")),r.info(`Please select a provider:
|
|
40
|
+
`),z.forEach((s,a)=>{r.info(` ${a+1}. ${It(s)}`)}),r.info("");let i=await b(`Select provider (1-${z.length}):`,{type:"text"}),e=String(i).trim().toLowerCase(),t=z.find(s=>s===e);if(t)return t;let n=Number(e);if(Number.isInteger(n)&&n>=1&&n<=z.length)return z[n-1];let o=z[0];return r.warn(`Invalid choice: ${i}, defaulting to ${It(o)}`),o}function It(i){switch(i){case"vercel":return"Vercel Firewall";case"cloudflare":return"Cloudflare WAF";case"fastly":return"Fastly Next-Gen WAF";case"gcp":return"Google Cloud Armor";default:return i}}function us(i){if(i.length===1){let{field:t}=i[0],n=t.required?"":" (optional)",o=t.configKey?" or config file":"";return`${t.label}${n} (defaults to ${t.envVar} env var${o})`}return`Resolved against whichever provider is active: ${i.map(t=>`${t.field.label} (${t.field.envVar})`).join(" / ")}`}var ui=new Map;for(let i of z)for(let e of He[i].fields){let t=ui.get(e.key)??[];t.push({provider:i,field:e}),ui.set(e.key,t)}var ie=Object.fromEntries(Array.from(ui.entries()).map(([i,e])=>{let t=e.map(n=>n.field.cliAlias).find(n=>!!n);return[i,{type:"string",...t?{alias:t}:{},description:us(e)}]}));function Z(i){return{token:i.token,projectId:i.projectId,teamId:i.teamId,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,policyName:i.policyName,serviceAccountKeyPath:i.serviceAccountKeyPath}}async function ne(i,e){try{i.debug&&(r.level=Qn.LogLevels.debug);let t;if(i.optionalConfig)try{t=await G(i.config,"optional")}catch{t={}}else i.skipValidation?t=await G(i.config,"raw"):t=await G(i.config,"required");let{provider:n,vercelCredentials:o}=await Jn({provider:i.provider,config:t,interactive:!i.ci,credentials:Z(i)}),s=o?.token??"",a=o?.projectId??"",l=o?.teamId??"";await e({config:t,provider:n,token:s,projectId:a,teamId:l})}catch(t){ee(t,i.errorContext)}}var ps="backup",fs="Backup or restore firewall configurations",gs={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:te,...ie,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}},ms=async i=>{try{i.debug&&(r.level=Xn.LogLevels.debug);let e=i.output||"./backups";if(i.list){if(!(0,Ae.existsSync)(e)){r.info(Q.default.yellow("No backup directory found."));return}let t=(0,Ae.readdirSync)(e).filter(n=>n.endsWith(".json")).map(n=>{let o=(0,rt.join)(e,n),s=(0,Ae.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(Q.default.yellow("No backups found."));return}r.log(Q.default.bold(`
|
|
41
41
|
\u{1F4E6} Available Backups:
|
|
42
|
-
`)),t.forEach(n=>{r.log(`${Q.default.cyan(n.name)}`),r.log(` ${Q.default.dim("Created:")} ${n.created.toLocaleString()}`),r.log(` ${Q.default.dim("Size:")} ${(n.size/1024).toFixed(1)} KB`),r.log("")});return}if(i.restore){let t=i.restore.startsWith("/")?i.restore:(0,rt.join)(e,i.restore);(0,Ae.existsSync)(t)||(r.error(`Backup file not found: ${t}`),process.exit(1));let n=await G(t,"raw"),o=i.config||".doorman.json";if((0,Ae.existsSync)(o)&&!await
|
|
42
|
+
`)),t.forEach(n=>{r.log(`${Q.default.cyan(n.name)}`),r.log(` ${Q.default.dim("Created:")} ${n.created.toLocaleString()}`),r.log(` ${Q.default.dim("Size:")} ${(n.size/1024).toFixed(1)} KB`),r.log("")});return}if(i.restore){let t=i.restore.startsWith("/")?i.restore:(0,rt.join)(e,i.restore);(0,Ae.existsSync)(t)||(r.error(`Backup file not found: ${t}`),process.exit(1));let n=await G(t,"raw"),o=i.config||".doorman.json";if((0,Ae.existsSync)(o)&&!await b(`Config file ${o} already exists. Do you want to overwrite it?`,{type:"confirm"})){r.info(Q.default.yellow("Restore cancelled."));return}let{backup:s,...a}=n;await K(a,o),r.success(Q.default.green(`\u2705 Restored configuration from ${t} to ${o}`));return}await ne({config:i.config,provider:i.provider,...Z(i),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;De.getInstance().validateConfig(s),(0,Ae.existsSync)(e)||(0,Ae.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",f=`firewall-backup-${`${d}_${u}`}.json`,y=(0,rt.join)(e,f),R={...s,backup:{createdAt:new Date().toISOString(),source:"remote",provider:t.name,...t.name==="vercel"?{projectId:n,teamId:o}:{},originalVersion:a}};await K(R,y,{validate:!1}),r.success(Q.default.green(`\u2705 Backup created: ${y}`)),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()}`),!(0,rt.isAbsolute)(e)&&en()&&!tn(e)&&r.warn(Q.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(Q.default.dim("To restore this backup later, run:")),r.log(Q.default.cyan(`doorman backup --restore ${f}`))})}catch(e){ee(e,"managing backup")}};var fi={};X(fi,{builder:()=>ws,command:()=>hs,desc:()=>ys,handler:()=>Rs});var oe=O(require("chalk"));T();function Re(i){if(Le(i))return i;let e=i,t=e.rules.map(o=>A.vercelToUnified(o).result),n=(e.ips??[]).map(o=>A.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 Bt(i,e){let t=!1,n=Le(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 eo(i,e){if(Le(e))return{...e,...i};let t=e,n=i.rules.map(s=>A.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 hs="diff",ys="Show detailed differences between local and remote firewall configuration",ws={config:{alias:"c",type:"string",description:"Path to firewall config file"},provider:te,...ie,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}},Rs=async i=>{await ne({config:i.config,provider:i.provider,...Z(i),debug:i.debug,ci:i.ci,errorContext:"calculating diff"},async({config:e,provider:t})=>{await Cs(t,Re(e),i)})};async function Cs(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(oe.default.green("No differences found. Local and remote configurations are in sync."));return}r.log(oe.default.bold(`
|
|
43
43
|
\u{1F50D} ${i.name} Configuration Differences
|
|
44
|
-
`)),r.log(oe.default.bold("Rule Changes:")),r.log(` ${oe.default.green("+")} ${o.rulesToAdd.length} to add`),o.rulesToAdd.forEach(d=>r.log(` ${oe.default.green("+")} ${d.name}`)),r.log(` ${oe.default.cyan("~")} ${o.rulesToUpdate.length} to update`),o.rulesToUpdate.forEach(d=>r.log(` ${oe.default.cyan("~")} ${d.name}`)),r.log(` ${oe.default.red("-")} ${o.rulesToDelete.length} to delete`),o.rulesToDelete.forEach(d=>r.log(` ${oe.default.red("-")} ${d.name}`)),(s.length||a.length||l.length)&&(r.log(""),r.log(oe.default.bold("IP Rule Changes:")),r.log(` ${oe.default.green("+")} ${s.length} to add`),r.log(` ${oe.default.cyan("~")} ${a.length} to update`),r.log(` ${oe.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(oe.default.bold(`Summary: ${c} total changes detected`)),r.log(oe.default.dim("Run `sync` to apply these changes to the remote configuration."))}var gi={};X(gi,{builder:()=>Is,command:()=>
|
|
44
|
+
`)),r.log(oe.default.bold("Rule Changes:")),r.log(` ${oe.default.green("+")} ${o.rulesToAdd.length} to add`),o.rulesToAdd.forEach(d=>r.log(` ${oe.default.green("+")} ${d.name}`)),r.log(` ${oe.default.cyan("~")} ${o.rulesToUpdate.length} to update`),o.rulesToUpdate.forEach(d=>r.log(` ${oe.default.cyan("~")} ${d.name}`)),r.log(` ${oe.default.red("-")} ${o.rulesToDelete.length} to delete`),o.rulesToDelete.forEach(d=>r.log(` ${oe.default.red("-")} ${d.name}`)),(s.length||a.length||l.length)&&(r.log(""),r.log(oe.default.bold("IP Rule Changes:")),r.log(` ${oe.default.green("+")} ${s.length} to add`),r.log(` ${oe.default.cyan("~")} ${a.length} to update`),r.log(` ${oe.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(oe.default.bold(`Summary: ${c} total changes detected`)),r.log(oe.default.dim("Run `sync` to apply these changes to the remote configuration."))}var gi={};X(gi,{builder:()=>Is,command:()=>bs,desc:()=>vs,handler:()=>Es});var Ge=O(require("chalk")),to=require("zod");T();$e();var bs="download [configVersion]",vs="Download remote Vercel Firewall rules and update local config, optionally for a specific configuration version",Is={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:te,...ie,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}},Es=async i=>{await ne({config:i.config,provider:i.provider,...Z(i),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{Tt.parse(i.configVersion)}catch(n){throw n instanceof to.z.ZodError&&(r.error("Invalid configuration version number. Version must be a positive integer."),process.exit(1)),n}await As(t,e,i)})};async function As(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(Ge.default.bold(`
|
|
45
45
|
Remote Custom Rules to Download (${o.length}):
|
|
46
46
|
`)),o.forEach(c=>r.log(` - ${c.name}${c.enabled?"":Ge.default.dim(" (disabled)")}`))):r.info("No custom rules to download..."),s.length>0?(r.log(Ge.default.bold(`
|
|
47
47
|
Remote IP Blocking Rules to Download (${s.length}):
|
|
48
|
-
`)),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info("No IP blocking rules to download..."),t.dryRun){r.info(Ge.default.cyan("Dry run completed. No changes made."));return}if(!await
|
|
48
|
+
`)),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info("No IP blocking rules to download..."),t.dryRun){r.info(Ge.default.cyan("Dry run completed. No changes made."));return}if(!await b(`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(Ge.default.yellow("Download cancelled."));return}let l=eo(n,e);r.start("Saving configuration..."),await K(l,t.config),r.success(Ge.default.green("Successfully downloaded and updated configuration"))}var mi={};X(mi,{builder:()=>Ps,command:()=>Ts,desc:()=>$s,handler:()=>Us});var Ke=O(require("chalk")),io=require("fs");T();var Ts="export",$s="Export firewall configuration in various formats",Ps={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:te,...ie,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 _s(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 ks=i=>{let{rules:e,ips:t=[]}=i,n=i.metadata?.version,o=i.metadata?.updatedAt,s=`# Firewall Configuration Report
|
|
49
49
|
|
|
50
50
|
`;return s+=`**Provider:** ${i.provider??"unknown"}
|
|
51
51
|
`,s+=`**Version:** ${n??"unknown"}
|
|
@@ -96,7 +96,7 @@ Remote IP Blocking Rules to Download (${s.length}):
|
|
|
96
96
|
`,n+=` action = "${o.action}"
|
|
97
97
|
`,n+=`}
|
|
98
98
|
|
|
99
|
-
`}),n},Us=async i=>{try{let e=i.output==="-"||!i.output,t;i.source==="remote"?await ne({config:i.config,provider:i.provider,...Z(i),debug:i.debug,ci:i.ci,errorContext:"exporting configuration"},async({provider:a})=>{e||r.start("Fetching remote configuration..."),t=await a.fetchConfig()}):t=await G(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=
|
|
99
|
+
`}),n},Us=async i=>{try{let e=i.output==="-"||!i.output,t;i.source==="remote"?await ne({config:i.config,provider:i.provider,...Z(i),debug:i.debug,ci:i.ci,errorContext:"exporting configuration"},async({provider:a})=>{e||r.start("Fetching remote configuration..."),t=await a.fetchConfig()}):t=await G(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=Re(t);n=`# Firewall Configuration (${a.provider??"unknown"})
|
|
100
100
|
`,n+=`version: ${a.metadata?.version??"unknown"}
|
|
101
101
|
`,n+=`updatedAt: "${a.metadata?.updatedAt??""}"
|
|
102
102
|
`,n+=`rules:
|
|
@@ -104,19 +104,19 @@ Remote IP Blocking Rules to Download (${s.length}):
|
|
|
104
104
|
`,n+=` id: "${l.id??""}"
|
|
105
105
|
`,n+=` enabled: ${l.enabled}
|
|
106
106
|
`,n+=` action: "${l.action.type}"
|
|
107
|
-
`}),o="yaml";break}case"terraform":n=Ss(
|
|
107
|
+
`}),o="yaml";break}case"terraform":n=Ss(Re(t)),o="tf";break;case"markdown":n=ks(Re(t)),o="md";break;default:throw new Error(`Unsupported format: ${i.format}`)}let s=i.output||`firewall-export.${o}`;e?r.log(n):((0,io.writeFileSync)(s,n,"utf8"),r.success(Ke.default.green(`\u2705 Exported to ${s}`)),r.log(""),r.log(Ke.default.bold("Export Summary:")),r.log(`${Ke.default.dim("Format:")} ${i.format}`),r.log(`${Ke.default.dim("Source:")} ${i.source}`),r.log(`${Ke.default.dim("Rules:")} ${t.rules.length} custom, ${(t.ips||[]).length} IP blocking`),r.log(`${Ke.default.dim("Size:")} ${(n.length/1024).toFixed(1)} KB`))}catch(e){ee(e,"exporting configuration")}};var hi={};X(hi,{BASIC_TEMPLATE_RULES:()=>oo,SECURITY_FOCUSED_TEMPLATE_RULES:()=>ro,builder:()=>Ds,command:()=>Ls,desc:()=>xs,handler:()=>Bs});var w=O(require("chalk")),no=require("fs");T();$e();var oo=[{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}],ro=[{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}],Ls="init [template]",xs="Initialize a new Doorman configuration",Ds={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"}},Os=()=>{r.log(""),r.log(w.default.bold.cyan("\u{1F6AA} Welcome to Doorman!")),r.log(w.default.dim(`Let's set up your firewall configuration.
|
|
108
108
|
`))},Fs=()=>{r.log(w.default.bold(`
|
|
109
109
|
\u{1F4DA} Helpful Resources:`)),r.log(""),r.log(w.default.cyan("\u{1F517} Find your Project ID:")),r.log(w.default.dim(" https://vercel.com/dashboard \u2192 Select your project \u2192 Settings \u2192 General")),r.log(""),r.log(w.default.cyan("\u{1F517} Find your Team ID:")),r.log(w.default.dim(" https://vercel.com/dashboard \u2192 Team Settings \u2192 General")),r.log(w.default.dim(" (Leave empty if using personal account)")),r.log(""),r.log(w.default.cyan("\u{1F517} Create API Token:")),r.log(w.default.dim(" https://vercel.com/account/tokens \u2192 Create Token")),r.log(w.default.dim(" Scopes needed: Read & Write for your project")),r.log(""),r.log(w.default.cyan("\u{1F517} Documentation:")),r.log(w.default.dim(" https://doorman.griffen.codes/getting-started")),r.log("")};function Ns(i){return i.interactive??i.template===void 0}var Vs=async(i,e)=>{let t=i.projectId,n=i.teamId;return e&&(r.log(w.default.bold("\u{1F4CB} Project Configuration")),r.log(w.default.dim(`We need your Vercel project details to configure the firewall.
|
|
110
|
-
`)),t||(t=await
|
|
111
|
-
`)),r.log(w.default.cyan("\u{1F4DD} empty")+w.default.dim(" - Minimal config, add your own rules")),r.log(w.default.cyan("\u{1F6E1}\uFE0F basic")+w.default.dim(" - Includes basic bot protection")),r.log(w.default.cyan("\u{1F512} security-focused")+w.default.dim(" - Comprehensive security rules")),r.log(""));let s=i.template??"empty";t&&!i.template&&(s=await
|
|
112
|
-
`+
|
|
110
|
+
`)),t||(t=await b("Enter your Vercel Project ID:",{type:"text"})),n||await b("Are you using a Vercel team account?",{type:"confirm"})&&(n=await b("Enter your Vercel Team ID:",{type:"text"})),process.env.VERCEL_TOKEN?r.log(w.default.green("\u2705 VERCEL_TOKEN environment variable found")):(r.log(""),r.log(w.default.yellow("\u26A0\uFE0F VERCEL_TOKEN environment variable not found")),r.log(w.default.dim("You'll need to set this before running sync commands.")),await b("Would you like to see how to create an API token?",{type:"confirm"})&&(r.log(""),r.log(w.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(w.default.cyan(' export VERCEL_TOKEN="your-token-here"')),r.log(w.default.dim(" # Add this to your ~/.bashrc, ~/.zshrc, or .env file")),r.log("")))),{projectId:t,teamId:n}},Bs=async i=>{try{let e=i.config||".doorman.json",t=Ns(i);if(t&&Os(),(0,no.existsSync)(e)&&!i.force&&!await b(`Config file ${e} already exists. Do you want to overwrite it?`,{type:"confirm"})){r.info(w.default.yellow("Initialization cancelled."));return}let{projectId:n,teamId:o}=await Vs(i,t);t&&(r.log(""),r.log(w.default.bold("\u{1F3A8} Template Selection")),r.log(w.default.dim(`Choose a starting template for your firewall configuration:
|
|
111
|
+
`)),r.log(w.default.cyan("\u{1F4DD} empty")+w.default.dim(" - Minimal config, add your own rules")),r.log(w.default.cyan("\u{1F6E1}\uFE0F basic")+w.default.dim(" - Includes basic bot protection")),r.log(w.default.cyan("\u{1F512} security-focused")+w.default.dim(" - Comprehensive security rules")),r.log(""));let s=i.template??"empty";t&&!i.template&&(s=await b("Select a template:",{type:"select",options:["empty","basic","security-focused"],initial:"empty"})),r.start(`Creating ${s} configuration...`);let a=_t();switch(n&&(a.projectId=n),o&&(a.teamId=o),s){case"basic":a={...a,rules:oo};break;case"security-focused":a={...a,rules:ro};break;default:break}await K(a,e),r.success(w.default.green(`\u2705 Created ${e}`)),r.log(""),r.log(w.default.bold("\u{1F4CB} Configuration Summary:")),r.log(`${w.default.dim("File:")} ${e}`),r.log(`${w.default.dim("Template:")} ${s}`),r.log(`${w.default.dim("Project ID:")} ${n||w.default.yellow("Not set - add manually")}`),r.log(`${w.default.dim("Team ID:")} ${o||w.default.dim("None (personal account)")}`),r.log(`${w.default.dim("Rules:")} ${a.rules.length} (all disabled for safety)`),r.log(""),r.log(w.default.bold("\u{1F680} Next Steps:")),n||r.log(`1. ${w.default.yellow("Add your projectId")} to ${e}`),process.env.VERCEL_TOKEN||r.log(`${n?"1":"2"}. ${w.default.yellow("Set VERCEL_TOKEN")} environment variable`);let l=n?process.env.VERCEL_TOKEN?1:2:3;r.log(`${l}. ${w.default.dim("Review and enable rules in")} ${e}`),r.log(`${l+1}. ${w.default.dim("Run")} ${w.default.cyan("doorman validate")} ${w.default.dim("to check your config")}`),r.log(`${l+2}. ${w.default.dim("Run")} ${w.default.cyan("doorman status")} ${w.default.dim("to see sync status")}`),r.log(`${l+3}. ${w.default.dim("Run")} ${w.default.cyan("doorman sync")} ${w.default.dim("to deploy your rules")}`),s!=="empty"&&(r.log(""),r.log(w.default.yellow("\u26A0\uFE0F All template rules are disabled by default for safety.")),r.log(w.default.dim(" Review each rule and set active: true when ready."))),t&&(!n||!process.env.VERCEL_TOKEN)&&Fs()}catch(e){ee(e,"initializing configuration")}};var yi={};X(yi,{builder:()=>Ms,command:()=>qs,desc:()=>Ws,handler:()=>js});var Ce=O(require("chalk")),so=require("zod");T();var qs="list [configVersion]",Ws="List Vercel Firewall rules, optionally for a specific configuration version",Ms={configVersion:{type:"number",description:"Specific configuration version to fetch (defaults to latest)"},provider:te,...ie,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}},js=async i=>{await ne({provider:i.provider,...Z(i),debug:i.debug,ci:i.ci,optionalConfig:!0,skipValidation:!0,errorContext:"listing firewall rules"},async({provider:e})=>{if(i.configVersion!==void 0)try{Tt.parse(i.configVersion)}catch(t){throw t instanceof so.z.ZodError&&(r.error("Invalid configuration version number. Version must be a positive integer."),process.exit(1)),t}await zs(e,i)})};async function zs(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
|
|
112
|
+
`+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(`
|
|
113
113
|
Custom Rules:`),`
|
|
114
|
-
`),o.forEach(c=>r.log(` - ${c.name}${c.enabled?"":
|
|
114
|
+
`),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(`
|
|
115
115
|
IP Blocking Rules:`),`
|
|
116
|
-
`),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info(
|
|
116
|
+
`),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info(Ce.default.cyan("No IP blocking rules found"))}var Ri={};X(Ri,{aliases:()=>Ks,builder:()=>Zs,command:()=>Gs,desc:()=>Hs,findFuzzyMatches:()=>po,handler:()=>Ys,levenshtein:()=>uo});var q=O(require("chalk")),co=require("consola");T();$e();var Gs="remove [type]",Ks=["rm","delete"],Hs="Remove a firewall rule or IP entry from your configuration",Zs={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 uo(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 po(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:uo(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 wi(i){for(let e of i){let t=e.id?` (${e.id})`:"",n=e.active?"":q.default.dim(" [disabled]"),o=e.action.mitigate.action;r.log(q.default.dim(` - ${e.name}${t} \u2014 ${o}${n}`))}}function ao(i){for(let e of i){let t=e.notes?` \u2014 ${e.notes}`:"";r.log(q.default.dim(` - ${e.ip}${t}`))}}async function lo(i,e,t,n="rule"){if(e)return!0;if(t)return await b(q.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 b(o,{type:"confirm",initial:!1})}var Ys=async i=>{try{i.debug&&(r.level=co.LogLevels.debug),r.debug("Remove command arguments:",i);let e=i.type||"rule";r.start("Loading configuration...");let t=await G(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 b("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(q.default.red(`No IP rule found matching "${i.ip}"`)),n.length>0&&(r.log(q.default.dim(`
|
|
117
117
|
Current IP rules:`)),ao(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(q.default.cyan(`
|
|
118
118
|
${i.dryRun?"Would remove":"Removing"} ${o.length} IP rule(s):`)),ao(o),i.dryRun){r.log(q.default.dim(`
|
|
119
|
-
Dry run \u2014 no changes made.`));return}if(!await lo(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 K(a,i.config),r.success(q.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})`:"",f=d.active?"":" [disabled]",y=d.action.mitigate.action;return`[${u}] ${d.name}${p} \u2014 ${y}${f}`}),c=await
|
|
119
|
+
Dry run \u2014 no changes made.`));return}if(!await lo(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 K(a,i.config),r.success(q.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})`:"",f=d.active?"":" [disabled]",y=d.action.mitigate.action;return`[${u}] ${d.name}${p} \u2014 ${y}${f}`}),c=await b("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(q.default.yellow(`
|
|
120
120
|
\u26A0\uFE0F Found ${o.length} rules named "${i.name}". All will be removed.`)),wi(o)),o.length===0){r.error(q.default.red(`No rule found with exact name "${i.name}"`));let l=po(i.name,n);l.length>0&&(r.log(q.default.yellow(`
|
|
121
121
|
Did you mean one of these?`)),l.forEach((c,d)=>{let u=c.id?` (${c.id})`:"";r.log(q.default.dim(` ${d+1}. ${c.name}${u}`))}),r.log(q.default.dim(`
|
|
122
122
|
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(q.default.yellow(`No rules found for IDs: ${d.join(", ")}`)),o.length===0&&(r.error(q.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(q.default.yellow(`
|
|
@@ -124,21 +124,21 @@ Use --id for exact matching, or --interactive to select from a list.`))),process
|
|
|
124
124
|
${i.dryRun?"Would remove":"Removing"} ${o.length} rule(s):`)),wi(o),i.dryRun){r.log(q.default.dim(`
|
|
125
125
|
Dry run \u2014 no changes made.`));return}if(!await lo(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(q.default.yellow("\u26A0\uFE0F Configuration will have no rules after removal.")),await K(a,i.config),r.success(q.default.green(`\u2714 Removed ${o.length} rule(s) from configuration`)),wi(o)}r.log(""),r.log(q.default.dim(`Run ${q.default.cyan("doorman sync")} to deploy these changes.`))}catch(e){ee(e,"removing rule")}};var Ci={};X(Ci,{builder:()=>Xs,command:()=>Js,desc:()=>Qs,handler:()=>ea});var k=O(require("chalk"));T();var Js="setup",Qs="Show setup instructions and helpful links for Doorman",Xs={},ea=async i=>{r.log(""),r.log(k.default.bold.cyan("\u{1F6AA} Doorman Setup Guide")),r.log(k.default.dim(`Everything you need to get started with firewall management
|
|
126
126
|
`)),r.log(k.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
|
|
127
|
-
`),r.log(k.default.bold("\u{1F50D} Finding Your Project Information")),r.log(""),r.log(k.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(k.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(k.default.bold("\u{1F511} Creating API Token")),r.log(""),r.log(k.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(k.default.cyan("Required Permissions:")),r.log(" \u2022 Read access to project settings"),r.log(" \u2022 Write access to firewall configuration"),r.log(""),r.log(k.default.bold("\u{1F30D} Environment Setup")),r.log(""),r.log(k.default.cyan("Set your API token as environment variable:")),r.log(""),r.log(k.default.green("# For current session:")),r.log('export VERCEL_TOKEN="your-token-here"'),r.log(""),r.log(k.default.green("# For permanent setup (add to ~/.bashrc or ~/.zshrc):")),r.log(`echo 'export VERCEL_TOKEN="your-token-here"' >> ~/.bashrc`),r.log(""),r.log(k.default.green("# Or create a .env file in your project:")),r.log('echo "VERCEL_TOKEN=your-token-here" > .env'),r.log(""),r.log(k.default.bold("\u{1F680} Quick Start Commands")),r.log(""),r.log(k.default.cyan("1. Initialize configuration:")),r.log(" doorman init --interactive"),r.log(""),r.log(k.default.cyan("2. Validate setup:")),r.log(" doorman validate"),r.log(""),r.log(k.default.cyan("3. Check current status:")),r.log(" doorman status"),r.log(""),r.log(k.default.cyan("4. View existing rules:")),r.log(" doorman list"),r.log(""),r.log(k.default.cyan("5. Sync your configuration:")),r.log(" doorman sync"),r.log(""),r.log(k.default.bold("\u{1F527} Common Issues")),r.log(""),r.log(k.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(k.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(k.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(k.default.bold("\u{1F4DA} Additional Resources")),r.log(""),r.log(k.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(k.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(k.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(k.default.bold.green("\u2705 Ready to get started?")),r.log(k.default.dim("Run: ")+k.default.cyan("doorman init --interactive")),r.log("")};var
|
|
127
|
+
`),r.log(k.default.bold("\u{1F50D} Finding Your Project Information")),r.log(""),r.log(k.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(k.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(k.default.bold("\u{1F511} Creating API Token")),r.log(""),r.log(k.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(k.default.cyan("Required Permissions:")),r.log(" \u2022 Read access to project settings"),r.log(" \u2022 Write access to firewall configuration"),r.log(""),r.log(k.default.bold("\u{1F30D} Environment Setup")),r.log(""),r.log(k.default.cyan("Set your API token as environment variable:")),r.log(""),r.log(k.default.green("# For current session:")),r.log('export VERCEL_TOKEN="your-token-here"'),r.log(""),r.log(k.default.green("# For permanent setup (add to ~/.bashrc or ~/.zshrc):")),r.log(`echo 'export VERCEL_TOKEN="your-token-here"' >> ~/.bashrc`),r.log(""),r.log(k.default.green("# Or create a .env file in your project:")),r.log('echo "VERCEL_TOKEN=your-token-here" > .env'),r.log(""),r.log(k.default.bold("\u{1F680} Quick Start Commands")),r.log(""),r.log(k.default.cyan("1. Initialize configuration:")),r.log(" doorman init --interactive"),r.log(""),r.log(k.default.cyan("2. Validate setup:")),r.log(" doorman validate"),r.log(""),r.log(k.default.cyan("3. Check current status:")),r.log(" doorman status"),r.log(""),r.log(k.default.cyan("4. View existing rules:")),r.log(" doorman list"),r.log(""),r.log(k.default.cyan("5. Sync your configuration:")),r.log(" doorman sync"),r.log(""),r.log(k.default.bold("\u{1F527} Common Issues")),r.log(""),r.log(k.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(k.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(k.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(k.default.bold("\u{1F4DA} Additional Resources")),r.log(""),r.log(k.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(k.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(k.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(k.default.bold.green("\u2705 Ready to get started?")),r.log(k.default.dim("Run: ")+k.default.cyan("doorman init --interactive")),r.log("")};var bi={};X(bi,{builder:()=>na,command:()=>ta,desc:()=>ia,handler:()=>oa});var F=O(require("chalk"));T();var ta="status",ia="Show sync status between local and remote firewall configuration",na={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:te,...ie,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}},oa=async i=>{await ne({config:i.config,provider:i.provider,...Z(i),debug:i.debug,ci:i.ci,errorContext:"checking status"},async({config:e,provider:t})=>{await ra(t,Re(e),i)})};async function ra(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(F.default.bold(`
|
|
128
128
|
\u{1F4CA} ${i.name} Sync Status Summary
|
|
129
129
|
`)),o.version!==void 0&&(r.log(`${F.default.dim("Local Version:")} ${F.default.yellow(a??"unknown")}`),r.log(`${F.default.dim("Remote Version:")} ${F.default.yellow(o.version)}`),r.log(`${F.default.dim("Version Status:")} ${l?F.default.red("Out of sync"):F.default.green("In sync")}`),r.log("")),r.log(`${F.default.dim("Rules:")}`),r.log(` ${F.default.green("+")} ${o.rulesToAdd.length} to add`),r.log(` ${F.default.cyan("~")} ${o.rulesToUpdate.length} to update`),r.log(` ${F.default.red("-")} ${o.rulesToDelete.length} to delete`),r.log(`${F.default.dim("IPs:")}`),r.log(` ${F.default.green("+")} ${o.ipsToAdd?.length??0} to add`),r.log(` ${F.default.cyan("~")} ${o.ipsToUpdate?.length??0} to update`),r.log(` ${F.default.red("-")} ${o.ipsToDelete?.length??0} to delete`),r.log(""),c?r.success(F.default.green("\u2705 Everything is in sync!")):r.warn(F.default.yellow("\u26A0\uFE0F Changes detected. Run `sync` to apply changes.")),r.log(`
|
|
130
130
|
`+F.default.bold("\u{1F3E5} Configuration Health Check")),r.log(`${F.default.dim("Score:")} ${s.score}/100 (${s.grade})`),s.issues.forEach(d=>{let u=d.severity==="error"?F.default.red("\u2717"):d.severity==="warning"?F.default.yellow("\u26A0"):F.default.dim("\u2139");r.log(` ${u} [${d.category}] ${d.message}`),d.suggestion&&r.log(` ${F.default.dim(d.suggestion)}`)}),s.recommendations.length>0&&(r.log(F.default.dim(`
|
|
131
|
-
Recommendations:`)),s.recommendations.forEach(d=>r.log(` - ${d}`)))}var Ei={};X(Ei,{builder:()=>la,command:()=>sa,desc:()=>aa,handler:()=>ca});var H=O(require("chalk"));T();var sa="sync",aa="Sync Vercel Firewall rules with config file",la={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:te,...ie,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}},ca=async i=>{await ne({config:i.config,provider:i.provider,...Z(i),debug:i.debug,ci:i.ci,errorContext:"syncing firewall rules"},async e=>{await da(e.provider,e.config,i)})};async function da(i,e,t){let n=
|
|
131
|
+
Recommendations:`)),s.recommendations.forEach(d=>r.log(` - ${d}`)))}var Ei={};X(Ei,{builder:()=>la,command:()=>sa,desc:()=>aa,handler:()=>ca});var H=O(require("chalk"));T();var sa="sync",aa="Sync Vercel Firewall rules with config file",la={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:te,...ie,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}},ca=async i=>{await ne({config:i.config,provider:i.provider,...Z(i),debug:i.debug,ci:i.ci,errorContext:"syncing firewall rules"},async e=>{await da(e.provider,e.config,i)})};async function da(i,e,t){let n=Re(e);r.start(H.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(H.default.green("No changes detected. Firewall rules are in sync."));return}r.log(H.default.bold(`
|
|
132
132
|
Proposed Changes:
|
|
133
|
-
`)),bi("Rules to add",o.rulesToAdd,H.default.green("+")),bi("Rules to update",o.rulesToUpdate,H.default.cyan("~")),bi("Rules to delete",o.rulesToDelete,H.default.red("-"));let l=o.ipsToAdd??[],c=o.ipsToUpdate??[],d=o.ipsToDelete??[];(l.length||c.length||d.length)&&(Ii("IPs to add",l,H.default.green("+")),Ii("IPs to update",c,H.default.cyan("~")),Ii("IPs to delete",d,H.default.red("-"))),a&&r.log(` Remote config version: ${H.default.red(s??"unknown")} ${H.default.dim("->")} ${H.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(H.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(f=>r.warn(f)),u.idRemappings?.length&&(r.info(H.default.yellow("Rule IDs were reassigned by the provider and written back to the local config:")),u.idRemappings.forEach(f=>{r.log(` - ${f.name}: ${H.default.red(f.oldId||"none")} ${H.default.dim("->")} ${H.default.green(f.newId)}`)}));let p=Bt(e,u);p.changed&&(await K(p.config,t.config),r.success(H.default.green("Updated local config with new version/metadata")))}function bi(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(n=>r.log(` - ${n.name}`)))}function Ii(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(n=>r.log(` - ${n.ip}${n.hostname?` (${n.hostname})`:""}`)))}var Ti={};X(Ti,{builder:()=>fa,command:()=>ua,desc:()=>pa,handler:()=>ha});var Fe=O(require("chalk")),wo=require("consola");T();var fo={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 go={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 mo={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 ho={metadata:{title:"Deny Common WordPress URLs Firewall Rule",reference:"https://vercel.com/templates/other/block-wordpress-urls-firewall-rule"},config:{rules:[{id:"rule_deny_word_press_ur_ls",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 Ai={"ai-bots":fo,"bad-bots":go,"block-ofac-sanctioned-countries":mo,wordpress:ho};var yo=i=>Ai[i]?.config;$e();var ua="template [name]",pa="Add a firewall rule template to your configuration",fa={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 ga(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 ma=()=>Object.keys(Ai),ha=async i=>{try{i.debug&&(r.level=wo.LogLevels.debug),r.debug("Template command arguments:",i);let e=i.name;if(!e){let c=ma();e=await v("Select a template to add:",{type:"select",options:c,initial:c[0]})}let t=yo(e);t||(r.error(`Template not found: ${e}`),process.exit(1)),r.debug("Template content:",t),r.start("Loading current configuration...");let n=await G(i.config,"raw"),o=n.rules||[],s=ga(o,t.rules);if(i.dryRun){r.info(Fe.default.cyan(`
|
|
134
|
-
Dry run - The following rules would be added:`)),r.log(JSON.stringify(t.rules,null,2)),s.length>0&&r.warn(Fe.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`));return}if(s.length>0){if(r.warn(Fe.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`)),i.ci||!process.stdin.isTTY){r.info(Fe.default.dim("Skipping \u2014 non-interactive and rule name(s) already exist. Template not applied."));return}if(!await
|
|
133
|
+
`)),vi("Rules to add",o.rulesToAdd,H.default.green("+")),vi("Rules to update",o.rulesToUpdate,H.default.cyan("~")),vi("Rules to delete",o.rulesToDelete,H.default.red("-"));let l=o.ipsToAdd??[],c=o.ipsToUpdate??[],d=o.ipsToDelete??[];(l.length||c.length||d.length)&&(Ii("IPs to add",l,H.default.green("+")),Ii("IPs to update",c,H.default.cyan("~")),Ii("IPs to delete",d,H.default.red("-"))),a&&r.log(` Remote config version: ${H.default.red(s??"unknown")} ${H.default.dim("->")} ${H.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(H.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(f=>r.warn(f)),u.idRemappings?.length&&(r.info(H.default.yellow("Rule IDs were reassigned by the provider and written back to the local config:")),u.idRemappings.forEach(f=>{r.log(` - ${f.name}: ${H.default.red(f.oldId||"none")} ${H.default.dim("->")} ${H.default.green(f.newId)}`)}));let p=Bt(e,u);p.changed&&(await K(p.config,t.config),r.success(H.default.green("Updated local config with new version/metadata")))}function vi(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(n=>r.log(` - ${n.name}`)))}function Ii(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(n=>r.log(` - ${n.ip}${n.hostname?` (${n.hostname})`:""}`)))}var Ti={};X(Ti,{builder:()=>fa,command:()=>ua,desc:()=>pa,handler:()=>ha});var Fe=O(require("chalk")),wo=require("consola");T();var fo={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 go={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 mo={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 ho={metadata:{title:"Deny Common WordPress URLs Firewall Rule",reference:"https://vercel.com/templates/other/block-wordpress-urls-firewall-rule"},config:{rules:[{id:"rule_deny_word_press_ur_ls",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 Ai={"ai-bots":fo,"bad-bots":go,"block-ofac-sanctioned-countries":mo,wordpress:ho};var yo=i=>Ai[i]?.config;$e();var ua="template [name]",pa="Add a firewall rule template to your configuration",fa={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 ga(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 ma=()=>Object.keys(Ai),ha=async i=>{try{i.debug&&(r.level=wo.LogLevels.debug),r.debug("Template command arguments:",i);let e=i.name;if(!e){let c=ma();e=await b("Select a template to add:",{type:"select",options:c,initial:c[0]})}let t=yo(e);t||(r.error(`Template not found: ${e}`),process.exit(1)),r.debug("Template content:",t),r.start("Loading current configuration...");let n=await G(i.config,"raw"),o=n.rules||[],s=ga(o,t.rules);if(i.dryRun){r.info(Fe.default.cyan(`
|
|
134
|
+
Dry run - The following rules would be added:`)),r.log(JSON.stringify(t.rules,null,2)),s.length>0&&r.warn(Fe.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`));return}if(s.length>0){if(r.warn(Fe.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`)),i.ci||!process.stdin.isTTY){r.info(Fe.default.dim("Skipping \u2014 non-interactive and rule name(s) already exist. Template not applied."));return}if(!await b("Proceed anyway?",{type:"confirm",initial:!1})){r.info("Cancelled.");return}}let a={...n,rules:[...o,...t.rules]},l=Ve.safeParse(a);l.success||(r.error(Fe.default.red("The resulting configuration would be invalid:")),l.error.errors.forEach(c=>{let d=c.path.join(".");r.error(Fe.default.red(` - ${d}: ${c.message}`))}),r.info(Fe.default.dim("Template was not applied. Fix the issues above and try again.")),process.exit(1)),r.start("Saving updated configuration..."),await K(a,i.config,{validate:!1}),r.success(Fe.default.green(`Successfully added template '${e}' to configuration`))}catch(e){ee(e,"adding template")}};var $i={};X($i,{builder:()=>Ra,command:()=>ya,desc:()=>wa,handler:()=>Ca});var re=O(require("chalk"));T();var ya="validate",wa="Validate firewall configuration file",Ra={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}},Ca=async i=>{try{let e=await G(i.config,"raw"),t=De.getInstance(),n=Le(e);i.verbose&&r.start(`Validating configuration file...
|
|
135
135
|
`);let o=n?Ue.safeParse(e):Ve.safeParse(e);i.verbose&&(r.log(re.default.bold.underline("Zod Schema Validation:")),o.success?r.log(re.default.green("\u2713 Schema validation passed")):(r.error(re.default.red("\u2717 Schema validation failed:")),o.error.errors.forEach(l=>{let c=l.path.join(".");r.error(re.default.red(` - ${c}: ${l.message}`))})));let s=!0,a=[];try{t.validateConfig(e),i.verbose&&(r.log(re.default.bold.underline(`
|
|
136
136
|
AJV Schema Validation:`)),r.log(re.default.green("\u2713 JSON Schema validation passed")))}catch(l){if(s=!1,l instanceof W)a=l.ajvErrors||[],i.verbose&&(r.log(re.default.bold.underline(`
|
|
137
137
|
AJV Schema Validation:`)),r.error(re.default.red("\u2717 JSON Schema validation failed:")),a.forEach(c=>{r.error(re.default.red(` - ${c.instancePath}: ${c.message}`))}));else throw l}if(o.success&&s&&i.verbose){r.log(re.default.bold.underline(`
|
|
138
138
|
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(`${re.default.cyan.dim(`
|
|
139
139
|
Rule Names:`)}`),d.size>0?(r.error(re.default.red("\u2717 Duplicate rule names found:")),d.forEach(u=>r.error(re.default.red(` - "${u}"`)))):r.log(re.default.green("\u2713 All rule names are unique")),r.log("")}if(o.success&&s)r.success(re.default.green("Configuration is valid"));else{if(i.verbose)throw new Error("Configuration validation failed");{let l=[...o.success?[]:o.error.errors.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`),...s?[]:a.map(c=>`${c.instancePath||"(root)"}: ${c.message}`)];throw new Error(`Configuration validation failed:
|
|
140
140
|
${l.join(`
|
|
141
|
-
`)}`)}}}catch(e){ee(e,"validating configuration")}};var Pi={};X(Pi,{builder:()=>Ia,command:()=>
|
|
142
|
-
`),r.info(be.default.yellow("Stopping watch mode...")),(0,qt.unwatchFile)(e),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a);let l=()=>{setTimeout(l,1e3)};l()})};async function Aa(i,e,t){let n=
|
|
141
|
+
`)}`)}}}catch(e){ee(e,"validating configuration")}};var Pi={};X(Pi,{builder:()=>Ia,command:()=>ba,desc:()=>va,handler:()=>Ea});var be=O(require("chalk")),qt=require("fs");T();var ba="watch",va="Watch config file for changes and auto-sync",Ia={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:te,...ie,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}},Ea=async i=>{let e=i.config||".doorman.json";await ne({config:e,provider:i.provider,...Z(i),debug:i.debug,ci:i.ci,errorContext:"setting up watch mode"},async({provider:t})=>{let n=!1,o=0;r.success(be.default.green(`\u{1F440} Watching ${e} for changes...`)),r.log(be.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(be.default.yellow(`\u{1F4DD} Config file changed at ${new Date().toLocaleTimeString()}`)),r.start("Validating and syncing changes...");let u=await G(e);await Aa(t,u,e),r.log(be.default.dim("Watching for more changes..."))}catch(u){r.error(be.default.red(`\u274C Sync failed: ${u instanceof Error?u.message:String(u)}`)),r.log(be.default.dim("Continuing to watch for changes..."))}finally{n=!1}}};(0,qt.watchFile)(e,{interval:i.interval},s);let a=()=>{r.log(`
|
|
142
|
+
`),r.info(be.default.yellow("Stopping watch mode...")),(0,qt.unwatchFile)(e),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a);let l=()=>{setTimeout(l,1e3)};l()})};async function Aa(i,e,t){let n=Re(e),o=await i.getChanges(n),s=n.metadata?.version,a=o.version!==void 0&&s!==o.version;if(!o.hasChanges&&!a){r.info(be.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(be.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(be.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(be.default.dim(` Rule "${u.name}" ID updated: ${u.oldId||"none"} -> ${u.newId}`))});let d=Bt(e,c);d.changed&&await K(d.config,t)}var Ro=[Ci,hi,ei,yi,bi,fi,Ei,$i,gi,Ti,Ri,pi,mi,Pi];(0,Co.config)();async function Ta(){let i=(await import("chalk")).default,e=(0,bo.default)(process.argv.slice(2));e.usage(`${i.bold("\u{1F6AA} Doorman")}
|
|
143
143
|
|
|
144
144
|
${i.dim("Manage firewall rules as code across multiple providers")}`);for(let t of Ro)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}Ta().catch(console.error);
|