@gfargo/doorman 3.7.0 → 3.7.1
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 +52 -52
- package/dist/bin/run.mjs +52 -52
- package/package.json +1 -1
package/dist/bin/run.js
CHANGED
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`),u.cancelled&&process.exit(0),e(r))};t.on("keypress",a)})}var
|
|
1
|
+
"use strict";var Ki=Object.create;var He=Object.defineProperty;var Ji=Object.getOwnPropertyDescriptor;var Qi=Object.getOwnPropertyNames;var Yi=Object.getPrototypeOf,Xi=Object.prototype.hasOwnProperty;var Ae=(n,e)=>()=>(n&&(e=n(n=0)),e);var j=(n,e)=>{for(var t in e)He(n,t,{get:e[t],enumerable:!0})},Ht=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Qi(e))!Xi.call(n,r)&&r!==t&&He(n,r,{get:()=>e[r],enumerable:!(i=Ji(e,r))||i.enumerable});return n};var P=(n,e,t)=>(t=n!=null?Ki(Yi(n)):{},Ht(e||!n||!n.__esModule?He(t,"default",{value:n,enumerable:!0}):t,n)),Y=n=>Ht(He({},"__esModule",{value:!0}),n);var Kt,o,E=Ae(()=>{"use strict";Kt=require("consola"),o=(0,Kt.createConsola)({formatOptions:{colors:!0,compact:!0,date:!1}})});var Qt,y,re=Ae(()=>{"use strict";Qt=P(require("consola")),y=async(n,e)=>{let t=await Qt.default.prompt(n,e);return t!=null&&t.toString()==="Symbol(clack:cancel)"&&process.exit(0),(!e?.type||e.type==="text")&&t===void 0?"":t}});function To(n,e){return e?.ctrl&&e.name==="c"?{type:"cancel"}:e?.name==="return"||e?.name==="enter"?{type:"submit"}:e?.name==="backspace"?{type:"backspace"}:n&&!e?.ctrl&&!e?.meta&&n.length===1&&n>=" "?{type:"append",char:n}:{type:"ignore"}}function Po(n,e){switch(e.type){case"append":return{value:n+e.char,done:!1,cancelled:!1,echo:"add"};case"backspace":return n.length===0?{value:n,done:!1,cancelled:!1,echo:"none"}:{value:n.slice(0,-1),done:!1,cancelled:!1,echo:"remove"};case"submit":return{value:n,done:!0,cancelled:!1,echo:"none"};case"cancel":return{value:n,done:!0,cancelled:!0,echo:"none"};case"ignore":return{value:n,done:!1,cancelled:!1,echo:"none"}}}async function Qe(n){if(process.stdout.write(n),!process.stdin.isTTY){let{createInterface:e}=await import("readline"),t=e({input:process.stdin,output:process.stdout,terminal:!1});return new Promise(i=>{t.question("",r=>{t.close(),i(r)})})}return new Promise(e=>{let t=process.stdin,i=t.isRaw;(0,yi.emitKeypressEvents)(t),t.setRawMode(!0),t.resume();let r="",s=()=>{t.removeListener("keypress",a),t.setRawMode(i??!1)},a=(l,c)=>{let d=To(l,c),u=Po(r,d);r=u.value,u.echo==="add"?process.stdout.write("*"):u.echo==="remove"&&process.stdout.write("\b \b"),u.done&&(s(),process.stdout.write(`
|
|
2
|
+
`),u.cancelled&&process.exit(0),e(r))};t.on("keypress",a)})}var yi,bt=Ae(()=>{"use strict";yi=require("readline")});var ee={};j(ee,{TranslationWarningSystem:()=>et});var et,X=Ae(()=>{"use strict";et=class n{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:`${n.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:`${n.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:`${n.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:`${n.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:`${n.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:`${n.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:`${n.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:`${n.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:`${n.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:`${n.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:`${n.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:`${n.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:`${n.DOCS_BASE_URL}/migration/plan-limits`}};static createWarning(e,t,i,r,s){let a=this.WARNING_CONFIGS[e];return a?{rule:t,field:i,category:a.category,message:r||`${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:i,category:"compatibility_issue",message:r||`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,i,r,s){return{rule:r,field:s,category:"feature_unsupported",message:`${e} is not supported in ${i}`,explanation:`The ${e} feature from ${t} cannot be directly translated to ${i} due to platform differences.`,severity:"critical",suggestion:`Remove or replace ${e} with equivalent functionality supported by ${i}.`,alternativeApproach:`Check ${i} 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,i,r){return{rule:i,field:r,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,i,r){return{rule:i,field:r,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,i,r){return{rule:i,field:r,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 i={critical:"\u{1F6A8}",warning:"\u26A0\uFE0F",info:"\u2139\uFE0F"}[e.severity],r=e.rule?` (Rule: ${e.rule}${e.field?`, Field: ${e.field}`:""})`:"",s=`${i} ${e.severity.toUpperCase()}: ${e.message}${r}
|
|
3
3
|
`;return s+=` ${e.explanation}
|
|
4
4
|
`,e.suggestion&&(s+=` \u{1F4A1} Suggestion: ${e.suggestion}
|
|
5
5
|
`),e.alternativeApproach&&(s+=` \u{1F504} Alternative: ${e.alternativeApproach}
|
|
6
6
|
`),e.impact&&(s+=` \u{1F4CA} Impact: ${e.impact}
|
|
7
7
|
`),e.docsUrl&&(s+=` \u{1F4D6} Documentation: ${e.docsUrl}
|
|
8
|
-
`),s}static groupWarningsBySeverity(e){return{critical:e.filter(t=>t.severity==="critical"),warning:e.filter(t=>t.severity==="warning"),info:e.filter(t=>t.severity==="info")}}static getWarningSummary(e){let t={critical:0,warning:0,info:0},i={feature_unsupported:0,lossy_conversion:0,syntax_limitation:0,performance_impact:0,security_consideration:0,compatibility_issue:0};return e.forEach(r=>{t[r.severity]++,i[r.category]++}),{total:e.length,bySeverity:t,byCategory:i,hasBlockingIssues:t.critical>0}}}});var
|
|
8
|
+
`),s}static groupWarningsBySeverity(e){return{critical:e.filter(t=>t.severity==="critical"),warning:e.filter(t=>t.severity==="warning"),info:e.filter(t=>t.severity==="info")}}static getWarningSummary(e){let t={critical:0,warning:0,info:0},i={feature_unsupported:0,lossy_conversion:0,syntax_limitation:0,performance_impact:0,security_consideration:0,compatibility_issue:0};return e.forEach(r=>{t[r.severity]++,i[r.category]++}),{total:e.length,bySeverity:t,byCategory:i,hasBlockingIssues:t.critical>0}}}});var At={};j(At,{OperationSafety:()=>Et});var it,Et,$t=Ae(()=>{"use strict";it=P(require("chalk"));E();re();Et=class{static async confirmDestructiveOperation(e){let{operation:t,target:i,changes:r,riskLevel:s,skipConfirmation:a=!1,dryRun:l=!1,allowDeletions:c=!1}=e;if(l)return o.info(`\u{1F50D} Dry run mode: Would perform ${t} on ${i}`),!0;let d=(r?.rulesToDelete?.length||0)+(r?.ipsToDelete?.length||0);if(a)return d>0&&!c?(o.error(`
|
|
9
9
|
\u{1F6A8} Refusing to run ${t} non-interactively: this would delete ${d} existing rule(s)/IP(s), and there is no confirmation prompt to catch a mistake.`),r&&this.displayChangeSummary(r),o.error(`
|
|
10
10
|
If this is intended, re-run with --allow-deletions. Run "doorman diff" first if you're not sure what would be removed.`),!1):!0;o.info(`
|
|
11
11
|
\u{1F6A8} Destructive Operation Confirmation`),o.info(`Operation: ${t}`),o.info(`Target: ${i}`),o.info(`Risk Level: ${this.formatRiskLevel(s)}`),r&&this.displayChangeSummary(r),this.displayRiskWarnings(s,t);let u=this.getBackupRecommendation(t,s);u.recommended&&(o.warn(`
|
|
12
|
-
\u{1F4BE} Backup Recommended: ${u.reason}`),u.instructions.forEach(
|
|
13
|
-
\u{1F504} Rollback Available: ${p.method}`),p.timeWindow&&o.info(` Time Window: ${p.timeWindow}`));let m=this.getConfirmationMessage(s,t);return await y(m,{type:"confirm"})?(o.info("\u2705 Operation confirmed by user"),!0):(o.info("Operation cancelled by user"),!1)}static async performDryRunValidation(e,t,i){o.info(`\u{1F50D} Performing dry-run validation for ${t}...`);let r=[],s=[],a={rulesToAdd:[],rulesToUpdate:[],rulesToDelete:[],ipsToAdd:[],ipsToUpdate:[],ipsToDelete:[],hasChanges:!1};try{this.validateConfigurationStructure(e,r),a=await i(e),this.validateChanges(a,s),this.checkForPotentialIssues(e,a,s);let l=r.length===0;return l?o.info("\u2705 Dry-run validation passed"):(o.warn(`\u26A0\uFE0F Dry-run validation found ${r.length} issues:`),r.forEach(c=>o.warn(` \u2022 ${c}`))),s.length>0&&(o.warn(`\u26A0\uFE0F Dry-run validation found ${s.length} warning(s):`),s.forEach(c=>o.warn(` \u2022 ${c}`))),{valid:l,changes:a,issues:r,warnings:s}}catch(l){let c=`Dry-run validation failed: ${l instanceof Error?l.message:String(l)}`;return r.push(c),o.error(c),{valid:!1,changes:a,issues:r,warnings:s}}}static assessOperationRisk(e,t){let i=t.rules.length,r=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===i&&i>0||s>0&&s/Math.max(i+r,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
|
|
12
|
+
\u{1F4BE} Backup Recommended: ${u.reason}`),u.instructions.forEach(b=>{o.info(` \u2022 ${b}`)}));let p=this.getRollbackGuidance(t);p.available&&(o.info(`
|
|
13
|
+
\u{1F504} Rollback Available: ${p.method}`),p.timeWindow&&o.info(` Time Window: ${p.timeWindow}`));let m=this.getConfirmationMessage(s,t);return await y(m,{type:"confirm"})?(o.info("\u2705 Operation confirmed by user"),!0):(o.info("Operation cancelled by user"),!1)}static async performDryRunValidation(e,t,i){o.info(`\u{1F50D} Performing dry-run validation for ${t}...`);let r=[],s=[],a={rulesToAdd:[],rulesToUpdate:[],rulesToDelete:[],ipsToAdd:[],ipsToUpdate:[],ipsToDelete:[],hasChanges:!1};try{this.validateConfigurationStructure(e,r),a=await i(e),this.validateChanges(a,s),this.checkForPotentialIssues(e,a,s);let l=r.length===0;return l?o.info("\u2705 Dry-run validation passed"):(o.warn(`\u26A0\uFE0F Dry-run validation found ${r.length} issues:`),r.forEach(c=>o.warn(` \u2022 ${c}`))),s.length>0&&(o.warn(`\u26A0\uFE0F Dry-run validation found ${s.length} warning(s):`),s.forEach(c=>o.warn(` \u2022 ${c}`))),{valid:l,changes:a,issues:r,warnings:s}}catch(l){let c=`Dry-run validation failed: ${l instanceof Error?l.message:String(l)}`;return r.push(c),o.error(c),{valid:!1,changes:a,issues:r,warnings:s}}}static assessOperationRisk(e,t){let i=t.rules.length,r=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===i&&i>0||s>0&&s/Math.max(i+r,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 it.default.green("LOW");case"medium":return it.default.yellow("MEDIUM");case"high":return it.default.red("HIGH");default:return String(e).toUpperCase()}}static displayChangeSummary(e){o.info(`
|
|
14
14
|
\u{1F4CA} Change Summary:`),e.rulesToAdd?.length&&o.info(` \u2022 Rules to add: ${e.rulesToAdd.length}`),e.rulesToUpdate?.length&&o.info(` \u2022 Rules to update: ${e.rulesToUpdate.length}`),e.rulesToDelete?.length&&o.info(` \u2022 Rules to delete: ${e.rulesToDelete.length}`),e.ipsToAdd?.length&&o.info(` \u2022 IPs to add: ${e.ipsToAdd.length}`),e.ipsToUpdate?.length&&o.info(` \u2022 IPs to update: ${e.ipsToUpdate.length}`),e.ipsToDelete?.length&&o.info(` \u2022 IPs to delete: ${e.ipsToDelete.length}`),e.hasChanges||o.info(" \u2022 No changes detected")}static displayRiskWarnings(e,t){let i={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"]},r={"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"]};o.info(`
|
|
15
|
-
\u26A0\uFE0F Warnings:`),i[e]?.forEach(s=>{o.warn(` ${s}`)}),r[t]?.forEach(s=>{o.warn(` ${s}`)})}static getConfirmationMessage(e,t){let i=`Do you want to proceed with ${t}?`;switch(e){case"high":return`${i} (Type 'yes' to confirm high-risk operation)`;case"medium":return`${i} (Proceed with caution)`;default:return i}}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 i=(e.rulesToDelete?.length||0)+(e.ipsToDelete?.length||0),r=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+i;if(i>0&&r>0){let s=i/r;s>.5&&t.push(`High deletion ratio detected: ${Math.round(s*100)}% of changes are deletions`)}r>100&&t.push(`Large number of changes detected: ${r} total changes`)}static checkForPotentialIssues(e,t,i){t.rulesToDelete?.length===e.rules.length&&e.rules.length>0&&i.push("All existing rules will be deleted - this removes all firewall protection");let r=e.rules.filter(l=>l.action.type==="deny"&&l.conditions.some(c=>c.field==="path"&&(c.value==="/"||c.value==="*")));r.length>0&&i.push(`Found ${r.length} rules that may block all traffic`),e.ips&&e.ips.length>1e3&&i.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&&i.push(`Duplicate rule names found: ${[...new Set(a)].join(", ")}`)}}});var Ii={};B(Ii,{promptForCredentials:()=>Do});async function Do(n){let e=n.token||process.env.VERCEL_TOKEN||await ze("What is your Vercel API Auth Token? (https://vercel.com/guides/how-do-i-use-a-vercel-api-access-token#creating-an-access-token) "),t=n.teamId||process.env.VERCEL_TEAM_ID||await y("What is your Vercel Team ID? (See https://vercel.com/docs/accounts/create-a-team#find-your-team-id)",{type:"text"}),i=n.projectId||process.env.VERCEL_PROJECT_ID||await y("What is your Vercel Project ID? (See https://vercel.com/docs/projects/project-configuration/general-settings#project-id)",{type:"text"});return{token:e,teamId:t,projectId:i}}var Ci=ve(()=>{"use strict";oe();Ct()});var Mi=require("dotenv"),Wi=P(require("yargs"));var It={};B(It,{builder:()=>yo,command:()=>mo,desc:()=>ho,generateRuleId:()=>wt,handler:()=>vo});var U=P(require("chalk")),pi=require("consola");E();var I=require("zod"),Be=I.z.number().int().positive().optional(),Qi=I.z.string().ip().or(I.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),Zt=I.z.string().optional(),Yi=I.z.enum(["eq","pre","suf","inc","sub","re","ex","nex"]),Xi=I.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"]),eo=I.z.object({op:Yi,neg:I.z.boolean().optional(),type:Xi,value:I.z.union([I.z.string(),I.z.array(I.z.string()),I.z.array(I.z.number())]).optional(),key:I.z.string().optional()}).refine(n=>{switch(n.type){case"ip_address":case"method":case"environment":case"protocol":return n.op==="eq"||n.op==="inc";default:return!0}},"Invalid operator for the given condition type").refine(n=>{let e=["header","cookie"];return!(e.includes(n.type)&&!n.key||e.includes(n.type)&&n.op!=="ex"&&n.op!=="nex"&&!n.value)},"Missing key from condition").refine(n=>!(["ex","nex"].includes(n.op)&&n.neg),"Negation is not supported for the given operator").refine(n=>!(n.op==="inc"&&!Array.isArray(n.value)),"When using `inc` operator, value must be an array"),st=I.z.object({conditions:I.z.array(eo).min(1,"Condition group must have at least one condition")}),to=I.z.string().regex(/^\d+[smhd]$|^permanent$/),at=I.z.object({requests:I.z.number().positive().int().refine(n=>n>0,"requests must be positive"),window:I.z.string().regex(/^\d+[smhd]$/).refine(n=>parseInt(n)>0,"window duration must be positive")}),io=I.z.object({location:I.z.string(),permanent:I.z.boolean().optional()}),oo=I.z.enum(["log","deny","challenge","bypass","rate_limit","redirect"]),no=I.z.object({action:oo,rateLimit:at.nullable().optional(),redirect:io.nullable().optional(),actionDuration:to.nullable().optional()}),ro=I.z.object({mitigate:no}),lt=I.z.object({id:Zt,name:I.z.string(),description:I.z.string().optional(),conditionGroup:I.z.array(st),action:ro,active:I.z.boolean()});var ct=I.z.object({id:Zt,ip:Qi,hostname:I.z.string(),notes:I.z.string().optional(),action:I.z.literal("deny")}),so=I.z.object({projectId:I.z.string().optional(),teamId:I.z.string().optional()}),ue=so.extend({rules:I.z.array(lt),ips:I.z.array(ct).optional(),version:I.z.number().optional(),updatedAt:I.z.string().optional()});oe();var de=require("fs"),li=require("path");E();var ri=require("net"),si=P(require("ajv"));var Kt="https://doorman.griffen.codes/schema.json",Jt={$schema:"http://json-schema.org/draft-07/schema#",title:"Doorman Config",description:"Schema for doorman project configuration files",$ref:"#/definitions/FirewallConfig",definitions:{FirewallConfig:{type:"object",properties:{projectId:{type:"string"},teamId:{type:"string"},$schema:{type:"string"},version:{type:"number"},firewallEnabled:{type:"boolean"},rules:{type:"array",items:{$ref:"#/definitions/CustomRule"}},ips:{type:"array",items:{$ref:"#/definitions/IPBlockingRule"}},updatedAt:{type:"string"}},required:["rules"],additionalProperties:!1,description:"The main configuration type for Doorman"},CustomRule:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},conditionGroup:{type:"array",items:{$ref:"#/definitions/ConditionGroup"}},action:{$ref:"#/definitions/RuleAction"},active:{type:"boolean"}},required:["name","conditionGroup","action","active"],additionalProperties:!1,description:"Rule Types"},ConditionGroup:{type:"object",properties:{conditions:{type:"array",items:{$ref:"#/definitions/RuleCondition"}}},required:["conditions"],additionalProperties:!1},RuleCondition:{type:"object",properties:{op:{$ref:"#/definitions/RuleOperator"},neg:{type:"boolean"},type:{$ref:"#/definitions/RuleType"},key:{type:"string"},value:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{type:"string"}},{type:"array",items:{type:"number"}}]}},required:["op","type"],additionalProperties:!1,description:"Rule Condition Types"},RuleOperator:{type:"string",enum:["eq","pre","suf","inc","sub","re","ex","nex"]},RuleType:{type:"string",enum:["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"]},RuleAction:{type:"object",properties:{mitigate:{$ref:"#/definitions/MitigationAction"}},required:["mitigate"],additionalProperties:!1},MitigationAction:{type:"object",properties:{action:{$ref:"#/definitions/ActionType"},rateLimit:{anyOf:[{$ref:"#/definitions/RateLimit"},{type:"null"}]},redirect:{anyOf:[{$ref:"#/definitions/Redirect"},{type:"null"}]},actionDuration:{type:["string","null"]}},required:["action"],additionalProperties:!1},ActionType:{type:"string",enum:["log","deny","challenge","bypass","rate_limit","redirect"],description:"Core Types"},RateLimit:{type:"object",properties:{requests:{type:"number"},window:{type:"string"}},required:["requests","window"],additionalProperties:!1,description:"Action Types"},Redirect:{type:"object",properties:{location:{type:"string"},permanent:{type:"boolean"}},required:["location"],additionalProperties:!1},IPBlockingRule:{type:"object",properties:{id:{type:"string"},ip:{type:"string"},hostname:{type:"string"},notes:{type:"string"},action:{type:"string",const:"deny"}},required:["ip","hostname","action"],additionalProperties:!1}}};var A=require("zod");var v=require("zod"),dt=v.z.string().optional(),Ee=v.z.string().ip().or(v.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),je=v.z.string().datetime().or(v.z.string().optional()),Qt=v.z.enum(["log","deny","challenge","bypass","rate_limit","redirect","allow","block"]),Yt=v.z.enum(["eq","ne","contains","not_contains","starts_with","ends_with","matches","in","not_in","gt","ge","lt","le","exists","not_exists"]),Xt=v.z.enum(["ip","country","region","city","asn","path","host","method","header","query","cookie","user_agent","referer","scheme","port"]),nr=v.z.string().regex(/^\d+[smhd]$|^permanent$/),ei=v.z.object({requests:v.z.number().positive().int(),window:v.z.string().regex(/^\d+[smhd]$/),characteristics:v.z.array(v.z.string()).optional()}),ti=v.z.object({location:v.z.string().url(),statusCode:v.z.number().int().min(300).max(399).optional(),permanent:v.z.boolean().optional(),preserveQueryString:v.z.boolean().optional()}),ut=v.z.object({version:v.z.number().int().positive().optional(),updatedAt:je,createdAt:je,lastSyncedAt:je,migratedFrom:v.z.string().optional(),migratedAt:je}),ao=v.z.enum(["vercel","cloudflare"]),ii=v.z.object({vercel:v.z.object({projectId:v.z.string().optional(),teamId:v.z.string().optional()}).optional(),cloudflare:v.z.object({zoneId:v.z.string().optional(),accountId:v.z.string().optional()}).optional()}),oi=v.z.object({$schema:v.z.string().url().optional(),version:v.z.string().optional(),provider:ao.optional(),metadata:ut.optional()});var lo=A.z.object({field:Xt.or(A.z.string()),operator:Yt,value:A.z.union([A.z.string(),A.z.number(),A.z.array(A.z.string()),A.z.array(A.z.number())]),negated:A.z.boolean().optional(),key:A.z.string().optional()}),co=A.z.object({type:Qt,rateLimit:ei.optional(),redirect:ti.optional(),response:A.z.object({statusCode:A.z.number().int().min(100).max(599).optional(),content:A.z.string().optional(),contentType:A.z.string().optional()}).optional(),duration:A.z.string().optional()}),uo=A.z.object({id:dt,name:A.z.string().min(1,"Rule name is required"),description:A.z.string().optional(),enabled:A.z.boolean(),conditions:A.z.array(lo).min(1,"At least one condition is required"),conditionLogic:A.z.enum(["AND","OR"]).optional().default("AND"),action:co,priority:A.z.number().int().optional(),categories:A.z.array(A.z.string()).optional()}),po=A.z.object({id:dt,ip:Ee,hostname:A.z.string().optional(),notes:A.z.string().optional(),action:A.z.enum(["deny","allow"])}),pt=oi.extend({providers:ii.optional(),rules:A.z.array(uo),ips:A.z.array(po).optional(),metadata:ut.optional()}),ni=n=>{let e=pt.safeParse(n);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 ae(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.provider=="string"||typeof e.providers=="object"&&e.providers!==null}var J=P(require("chalk")),le=class{static formatValidationError(e){let t=e.instancePath||"/",i=J.default.cyan(t);switch(e.keyword){case"type":return`${i}: Expected ${J.default.green(e.schema)}, got ${J.default.red(typeof e.data)}`;case"enum":{let r=e.params.allowedValues;return`${i}: Value must be one of: ${J.default.green(r.join(", "))}`}case"required":{let r=e.params;return`${i}: Missing required property ${J.default.yellow(r.missingProperty)}`}case"additionalProperties":{let r=e.params;return`${i}: Unknown property ${J.default.red(r.additionalProperty)}`}default:return`${i}: ${e.message}`}}static formatCustomError(e,t){return`${J.default.cyan(e)}: ${t}`}static wrapErrorBlock(e){let t=J.default.red.bold("Validation Errors:"),i=e.map(r=>` ${r}`).join(`
|
|
15
|
+
\u26A0\uFE0F Warnings:`),i[e]?.forEach(s=>{o.warn(` ${s}`)}),r[t]?.forEach(s=>{o.warn(` ${s}`)})}static getConfirmationMessage(e,t){let i=`Do you want to proceed with ${t}?`;switch(e){case"high":return`${i} (Type 'yes' to confirm high-risk operation)`;case"medium":return`${i} (Proceed with caution)`;default:return i}}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 i=(e.rulesToDelete?.length||0)+(e.ipsToDelete?.length||0),r=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+i;if(i>0&&r>0){let s=i/r;s>.5&&t.push(`High deletion ratio detected: ${Math.round(s*100)}% of changes are deletions`)}r>100&&t.push(`Large number of changes detected: ${r} total changes`)}static checkForPotentialIssues(e,t,i){t.rulesToDelete?.length===e.rules.length&&e.rules.length>0&&i.push("All existing rules will be deleted - this removes all firewall protection");let r=e.rules.filter(l=>l.action.type==="deny"&&l.conditions.some(c=>c.field==="path"&&(c.value==="/"||c.value==="*")));r.length>0&&i.push(`Found ${r.length} rules that may block all traffic`),e.ips&&e.ips.length>1e3&&i.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&&i.push(`Duplicate rule names found: ${[...new Set(a)].join(", ")}`)}}});var bi={};j(bi,{promptForCredentials:()=>No});async function No(n){let e=n.token||process.env.VERCEL_TOKEN||await Qe("What is your Vercel API Auth Token? (https://vercel.com/guides/how-do-i-use-a-vercel-api-access-token#creating-an-access-token) "),t=n.teamId||process.env.VERCEL_TEAM_ID||await y("What is your Vercel Team ID? (See https://vercel.com/docs/accounts/create-a-team#find-your-team-id)",{type:"text"}),i=n.projectId||process.env.VERCEL_PROJECT_ID||await y("What is your Vercel Project ID? (See https://vercel.com/docs/projects/project-configuration/general-settings#project-id)",{type:"text"});return{token:e,teamId:t,projectId:i}}var vi=Ae(()=>{"use strict";re();bt()});var Zi=require("dotenv"),Hi=P(require("yargs"));var Rt={};j(Rt,{builder:()=>Co,command:()=>wo,desc:()=>Io,generateRuleId:()=>Ct,handler:()=>$o});var U=P(require("chalk")),mi=require("consola");E();var I=require("zod"),Ke=I.z.number().int().positive().optional(),eo=I.z.string().ip().or(I.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),Jt=I.z.string().optional(),to=I.z.enum(["eq","pre","suf","inc","sub","re","ex","nex"]),io=I.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"]),oo=I.z.object({op:to,neg:I.z.boolean().optional(),type:io,value:I.z.union([I.z.string(),I.z.array(I.z.string()),I.z.array(I.z.number())]).optional(),key:I.z.string().optional()}).refine(n=>{switch(n.type){case"ip_address":case"method":case"environment":case"protocol":return n.op==="eq"||n.op==="inc";default:return!0}},"Invalid operator for the given condition type").refine(n=>{let e=["header","cookie"];return!(e.includes(n.type)&&!n.key||e.includes(n.type)&&n.op!=="ex"&&n.op!=="nex"&&!n.value)},"Missing key from condition").refine(n=>!(["ex","nex"].includes(n.op)&&n.neg),"Negation is not supported for the given operator").refine(n=>!(n.op==="inc"&&!Array.isArray(n.value)),"When using `inc` operator, value must be an array"),ct=I.z.object({conditions:I.z.array(oo).min(1,"Condition group must have at least one condition")}),no=I.z.string().regex(/^\d+[smhd]$|^permanent$/),dt=I.z.object({requests:I.z.number().positive().int().refine(n=>n>0,"requests must be positive"),window:I.z.string().regex(/^\d+[smhd]$/).refine(n=>parseInt(n)>0,"window duration must be positive")}),ro=I.z.object({location:I.z.string(),permanent:I.z.boolean().optional()}),so=I.z.enum(["log","deny","challenge","bypass","rate_limit","redirect"]),ao=I.z.object({action:so,rateLimit:dt.nullable().optional(),redirect:ro.nullable().optional(),actionDuration:no.nullable().optional()}),lo=I.z.object({mitigate:ao}),ut=I.z.object({id:Jt,name:I.z.string(),description:I.z.string().optional(),conditionGroup:I.z.array(ct),action:lo,active:I.z.boolean()});var pt=I.z.object({id:Jt,ip:eo,hostname:I.z.string(),notes:I.z.string().optional(),action:I.z.literal("deny")}),co=I.z.object({projectId:I.z.string().optional(),teamId:I.z.string().optional()}),pe=co.extend({rules:I.z.array(ut),ips:I.z.array(pt).optional(),version:I.z.number().optional(),updatedAt:I.z.string().optional()});re();var ue=require("fs"),ui=require("path");E();var li=require("net"),ci=P(require("ajv"));var Yt="https://doorman.griffen.codes/schema.json",Xt={$schema:"http://json-schema.org/draft-07/schema#",title:"Doorman Config",description:"Schema for doorman project configuration files",$ref:"#/definitions/FirewallConfig",definitions:{FirewallConfig:{type:"object",properties:{projectId:{type:"string"},teamId:{type:"string"},$schema:{type:"string"},version:{type:"number"},firewallEnabled:{type:"boolean"},rules:{type:"array",items:{$ref:"#/definitions/CustomRule"}},ips:{type:"array",items:{$ref:"#/definitions/IPBlockingRule"}},updatedAt:{type:"string"}},required:["rules"],additionalProperties:!1,description:"The main configuration type for Doorman"},CustomRule:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},conditionGroup:{type:"array",items:{$ref:"#/definitions/ConditionGroup"}},action:{$ref:"#/definitions/RuleAction"},active:{type:"boolean"}},required:["name","conditionGroup","action","active"],additionalProperties:!1,description:"Rule Types"},ConditionGroup:{type:"object",properties:{conditions:{type:"array",items:{$ref:"#/definitions/RuleCondition"}}},required:["conditions"],additionalProperties:!1},RuleCondition:{type:"object",properties:{op:{$ref:"#/definitions/RuleOperator"},neg:{type:"boolean"},type:{$ref:"#/definitions/RuleType"},key:{type:"string"},value:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{type:"string"}},{type:"array",items:{type:"number"}}]}},required:["op","type"],additionalProperties:!1,description:"Rule Condition Types"},RuleOperator:{type:"string",enum:["eq","pre","suf","inc","sub","re","ex","nex"]},RuleType:{type:"string",enum:["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"]},RuleAction:{type:"object",properties:{mitigate:{$ref:"#/definitions/MitigationAction"}},required:["mitigate"],additionalProperties:!1},MitigationAction:{type:"object",properties:{action:{$ref:"#/definitions/ActionType"},rateLimit:{anyOf:[{$ref:"#/definitions/RateLimit"},{type:"null"}]},redirect:{anyOf:[{$ref:"#/definitions/Redirect"},{type:"null"}]},actionDuration:{type:["string","null"]}},required:["action"],additionalProperties:!1},ActionType:{type:"string",enum:["log","deny","challenge","bypass","rate_limit","redirect"],description:"Core Types"},RateLimit:{type:"object",properties:{requests:{type:"number"},window:{type:"string"}},required:["requests","window"],additionalProperties:!1,description:"Action Types"},Redirect:{type:"object",properties:{location:{type:"string"},permanent:{type:"boolean"}},required:["location"],additionalProperties:!1},IPBlockingRule:{type:"object",properties:{id:{type:"string"},ip:{type:"string"},hostname:{type:"string"},notes:{type:"string"},action:{type:"string",const:"deny"}},required:["ip","hostname","action"],additionalProperties:!1}}};var A=require("zod");var v=require("zod"),gt=v.z.string().optional(),$e=v.z.string().ip().or(v.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),Je=v.z.string().datetime().or(v.z.string().optional()),ei=v.z.enum(["log","deny","challenge","bypass","rate_limit","redirect","allow","block"]),ti=v.z.enum(["eq","ne","contains","not_contains","starts_with","ends_with","matches","in","not_in","gt","ge","lt","le","exists","not_exists"]),ii=v.z.enum(["ip","country","region","city","asn","path","host","method","header","query","cookie","user_agent","referer","scheme","port"]),ar=v.z.string().regex(/^\d+[smhd]$|^permanent$/),oi=v.z.object({requests:v.z.number().positive().int(),window:v.z.string().regex(/^\d+[smhd]$/),characteristics:v.z.array(v.z.string()).optional()}),ni=v.z.object({location:v.z.string().url(),statusCode:v.z.number().int().min(300).max(399).optional(),permanent:v.z.boolean().optional(),preserveQueryString:v.z.boolean().optional()}),ft=v.z.object({version:v.z.number().int().positive().optional(),updatedAt:Je,createdAt:Je,lastSyncedAt:Je,migratedFrom:v.z.string().optional(),migratedAt:Je}),uo=v.z.enum(["vercel","cloudflare"]),ri=v.z.object({vercel:v.z.object({projectId:v.z.string().optional(),teamId:v.z.string().optional()}).optional(),cloudflare:v.z.object({zoneId:v.z.string().optional(),accountId:v.z.string().optional()}).optional()}),si=v.z.object({$schema:v.z.string().url().optional(),version:v.z.string().optional(),provider:uo.optional(),metadata:ft.optional()});var po=A.z.object({field:ii.or(A.z.string()),operator:ti,value:A.z.union([A.z.string(),A.z.number(),A.z.array(A.z.string()),A.z.array(A.z.number())]),negated:A.z.boolean().optional(),key:A.z.string().optional()}),go=A.z.object({type:ei,rateLimit:oi.optional(),redirect:ni.optional(),response:A.z.object({statusCode:A.z.number().int().min(100).max(599).optional(),content:A.z.string().optional(),contentType:A.z.string().optional()}).optional(),duration:A.z.string().optional()}),fo=A.z.object({id:gt,name:A.z.string().min(1,"Rule name is required"),description:A.z.string().optional(),enabled:A.z.boolean(),conditions:A.z.array(po).min(1,"At least one condition is required"),conditionLogic:A.z.enum(["AND","OR"]).optional().default("AND"),action:go,priority:A.z.number().int().optional(),categories:A.z.array(A.z.string()).optional()}),mo=A.z.object({id:gt,ip:$e,hostname:A.z.string().optional(),notes:A.z.string().optional(),action:A.z.enum(["deny","allow"])}),Ne=si.extend({providers:ri.optional(),rules:A.z.array(fo),ips:A.z.array(mo).optional(),metadata:ft.optional()}),ai=n=>{let e=Ne.safeParse(n);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(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.provider=="string"||typeof e.providers=="object"&&e.providers!==null}var Q=P(require("chalk")),ce=class{static formatValidationError(e){let t=e.instancePath||"/",i=Q.default.cyan(t);switch(e.keyword){case"type":return`${i}: Expected ${Q.default.green(e.schema)}, got ${Q.default.red(typeof e.data)}`;case"enum":{let r=e.params.allowedValues;return`${i}: Value must be one of: ${Q.default.green(r.join(", "))}`}case"required":{let r=e.params;return`${i}: Missing required property ${Q.default.yellow(r.missingProperty)}`}case"additionalProperties":{let r=e.params;return`${i}: Unknown property ${Q.default.red(r.additionalProperty)}`}default:return`${i}: ${e.message}`}}static formatCustomError(e,t){return`${Q.default.cyan(e)}: ${t}`}static wrapErrorBlock(e){let t=Q.default.red.bold("Validation Errors:"),i=e.map(r=>` ${r}`).join(`
|
|
16
16
|
`);return`${t}
|
|
17
|
-
${i}`}static formatDetailedRuleValidation(e,t){let i=
|
|
17
|
+
${i}`}static formatDetailedRuleValidation(e,t){let i=Q.default.cyan(`Rule: ${e}`),r=t.map(s=>{let a=s.passed?Q.default.green("\u2713"):Q.default.red("\u2717"),l=s.passed?Q.default.green(s.name):Q.default.red(s.name);return` ${a} ${l}`}).join(`
|
|
18
18
|
`);return`${i}
|
|
19
|
-
${r}`}};var L=class n extends Error{constructor(t,i,r,s=[]){super(t);this.ajvErrors=i;this.zodError=r;this.customErrors=s;this.name="ValidationError"}ajvErrors;zodError;customErrors;static formatErrors(t,i,r=[]){let s=[];return t?.length&&s.push(...t.map(
|
|
20
|
-
`+(c instanceof Error?c.message:String(c)),null)}let t=this.ajv.compile(this.schema),i=t(e),r=t.errors,s=
|
|
21
|
-
`+L.formatErrors(r,a,l),r,a,l)}validateRuleNames(e){let t=new Set;for(let i of e.rules){if(t.has(i.name))throw new L(`Duplicate rule name found: "${i.name}"`,null);t.add(i.name)}}validateRuleConditionGroup(e){for(let t of e.rules)if(t.conditionGroup)for(let i of t.conditionGroup){if(!i.conditions||i.conditions.length===0)throw new L(`Rule "${t.name}" has an empty condition group`,null);for(let r of i.conditions){if(!r.type||!r.op)throw new L(`Rule "${t.name}" has an invalid condition`,null);let s=r.type==="header"||r.type==="cookie",a=r.op==="ex"||r.op==="nex";if(s){if(!r.key||typeof r.key!="string")throw new L(`Rule "${t.name}" has an invalid condition`,null);if(!a&&(r.value===void 0||r.value===null))throw new L(`Rule "${t.name}" has an invalid condition`,null)}else if(r.value===void 0||r.value===null)throw new L(`Rule "${t.name}" has an invalid condition`,null);let l=Array.isArray(r.value)?r.value:r.value!==void 0?[r.value]:[];if(Array.isArray(r.value)&&l.length===0)throw new L(`Rule "${t.name}" has an invalid value in condition`,null);if(r.type==="ip_address"){for(let c of l)if(typeof c!="string"||!this.isValidIP(c))throw new L(`Rule "${t.name}" has an invalid IP address in condition`,null)}if(r.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 L(`Rule "${t.name}" has an invalid ASN in condition`,null)}if(r.type==="path"&&(r.op==="eq"||r.op==="pre")){for(let c of l)if(typeof c!="string"||!this.isValidPath(c))throw new L(`Rule "${t.name}" has an invalid path in condition`,null)}}}else throw new L("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 i=t.action.mitigate;if(i?.rateLimit){if(i.rateLimit.requests<=0)throw new L("Invalid rate limit configuration: requests must be positive",null);if(!i.rateLimit.window.match(/^\d+[smhd]$/))throw new L("Invalid rate limit configuration: invalid window format",null);if(parseInt(i.rateLimit.window)<=0)throw new L("Invalid rate limit configuration: window duration must be positive",null)}if(i?.actionDuration&&!i.actionDuration.match(/^\d+[smhd]$|^permanent$/))throw new L("Invalid action duration format: "+i.actionDuration,null);if(i?.redirect&&!i.redirect.location)throw new L("Invalid redirect configuration: location is required",null)}}isValidIP(e){let t=e.split("/"),i=t[0]??"",r=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 m=parseInt(p,10);return m>=0&&m<=255})},a=d=>(0,ri.isIPv6)(d),l=s(i),c=a(i);if(!l&&!c)return!1;if(r!==void 0){let d=parseInt(r,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 ai=require("fs"),Oe=require("path"),gt=[".doorman.json","vercel-firewall.config.json"],go=gt[0],fe=class{static async findConfig(e){let{findUp:t}=await import("find-up");for(let i of gt){let r=await t(i,{cwd:e||process.cwd()});if(r)return r}}static async findProjectRoot(e){let t=await this.findConfig(e);return t?(0,Oe.dirname)(t):null}static configExists(e){return(0,ai.existsSync)((0,Oe.resolve)(e))}static getDefaultConfigPath(){return(0,Oe.resolve)(process.cwd(),go)}static getSupportedFileNames(){return gt}};async function N(n,e="required"){let t=fo(e),i=n||await fe.findConfig();if(!i||!(0,de.existsSync)(i)){if(t==="optional")return o.debug("No config file found, returning empty config"),{};let s=fe.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 r;try{let s=(0,de.readFileSync)(i,"utf8");r=JSON.parse(s)}catch(s){throw s instanceof SyntaxError?new Error(`Invalid JSON in config file (${i}): ${s.message}`):s}if(t!=="raw")try{ce.getInstance().validateConfig(r)}catch(s){if(t==="lenient")o.warn("Config validation failed:",s);else throw s}return r}async function F(n,e,t={validate:!0,throwOnError:!0}){let i=e||await fe.findConfig()||fe.getDefaultConfigPath();if(t.validate)try{ce.getInstance().validateConfig(n)}catch(s){if(o.error("Config validation failed:",s),t.throwOnError)throw s}let r=(0,li.dirname)(i);(0,de.existsSync)(r)||(0,de.mkdirSync)(r,{recursive:!0}),(0,de.writeFileSync)(i,JSON.stringify(n,null,2)),o.debug(`Config saved to ${i}`)}function fo(n){if(typeof n=="string")return n;let{validate:e=!0,throwOnError:t=!0}=n;return e?t?"required":"lenient":"raw"}var ft=P(require("chalk")),ci=require("zod");E();function q(n,e){n instanceof SyntaxError?o.log(le.wrapErrorBlock(["Invalid JSON format in config file:",` ${n.message}`])):n instanceof ci.ZodError?(o.error(ft.default.red("Schema validation failed:")),n.errors.forEach(t=>{let i=t.path.join(".");o.error(ft.default.red(` - ${i}: ${t.message}`))})):n instanceof Error&&n.name==="ValidationError"?o.error(n):n instanceof Error&&n.message.includes("Forbidden")?o.log(le.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."])):o.error(le.wrapErrorBlock([`Error ${e}:`,` ${n instanceof Error?n.message:String(n)}`])),process.exit(1)}var mo="add [type]",ho="Add a new firewall rule to your configuration",yo={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}},mt=["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"],ht=["eq","pre","suf","inc","sub","re","ex","nex"],yt=["log","deny","challenge","bypass","rate_limit","redirect"];function wt(n){let e=n.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 gi(n,e){return e==="inc"?n.split(",").map(t=>t.trim()):n}async function wo(){let n=await y("Rule name:",{type:"text"});if(!n.trim())throw new Error("Rule name cannot be empty");let e=await y("Description (optional):",{type:"text"}),t=[],i=!0;for(;i;){let u=[],p=!0;for(;p;){let m=await y("Condition type:",{type:"select",options:mt,initial:"path"}),w=await y("Operator:",{type:"select",options:ht,initial:"eq"}),C;(m==="header"||m==="cookie"||m==="query")&&(C=await y(`${m} key:`,{type:"text"}));let R;if(w!=="ex"&&w!=="nex"){let se=await y("Value:",{type:"text"});R=gi(se,w)}let O=w!=="ex"&&w!=="nex"?await y("Negate this condition?",{type:"confirm",initial:!1}):!1,K={type:m,op:w,...R!==void 0&&{value:R},...C&&{key:C},...O&&{neg:O}};u.push(K),p=await y("Add another condition to this group? (AND logic)",{type:"confirm",initial:!1})}t.push({conditions:u}),i=await y("Add another condition group? (OR logic)",{type:"confirm",initial:!1})}let r=await y("Action:",{type:"select",options:yt,initial:"deny"}),s;if(r==="rate_limit"){let u=parseInt(await y("Max requests:",{type:"text",initial:"100"}),10),p=await y('Time window (e.g., "60s", "1m", "1h"):',{type:"text",initial:"60s"});s={requests:u,window:p}}let a;if(r==="redirect"){let u=await y("Redirect URL:",{type:"text"}),p=await y("Permanent redirect (301)?",{type:"confirm",initial:!1});a={location:u,...p&&{permanent:p}}}let l;(r==="deny"||r==="challenge")&&await y("Set action duration? (default: permanent)",{type:"confirm",initial:!1})&&(l=await y('Duration (e.g., "1h", "1d", "permanent"):',{type:"text",initial:"permanent"}));let c=await y("Enable rule immediately?",{type:"confirm",initial:!0});return{id:wt(n),name:n.trim(),...e.trim()&&{description:e.trim()},conditionGroup:t,action:{mitigate:{action:r,...s&&{rateLimit:s},...a&&{redirect:a},...l&&{actionDuration:l}}},active:c}}function Io(n){if(!n.name)throw new Error("--name is required in inline mode. Use --interactive for guided prompts.");if(!n.field)throw new Error("--field is required in inline mode (e.g., --field path)");if(!n.op)throw new Error("--op is required in inline mode (e.g., --op eq)");let e=n.op;if(!ht.includes(e))throw new Error(`Invalid operator "${n.op}". Valid operators: ${ht.join(", ")}`);let t=n.field;if(!mt.includes(t))throw new Error(`Invalid field type "${n.field}". Valid types: ${mt.join(", ")}`);let i=n.action||"deny";if(!yt.includes(i))throw new Error(`Invalid action "${n.action}". Valid actions: ${yt.join(", ")}`);if(e!=="ex"&&e!=="nex"&&!n.value)throw new Error("--value is required for the given operator");if((t==="header"||t==="cookie"||t==="query")&&!n.key)throw new Error(`--key is required for "${t}" condition type`);if(i==="rate_limit"&&(!n.requests||!n.window))throw new Error("--requests and --window are required when action is rate_limit");if(i==="redirect"&&!n.location)throw new Error("--location is required when action is redirect");let r=n.value?gi(n.value,e):void 0,s={type:t,op:e,...r!==void 0&&{value:r},...n.key&&{key:n.key},...n.neg&&{neg:!0}};return{id:wt(n.name),name:n.name.trim(),...n.description&&{description:n.description},conditionGroup:[{conditions:[s]}],action:{mitigate:{action:i,...i==="rate_limit"&&n.requests&&n.window&&{rateLimit:{requests:n.requests,window:n.window}},...i==="redirect"&&n.location&&{redirect:{location:n.location,...n.permanent&&{permanent:!0}}},...n.duration&&{actionDuration:n.duration}}},active:n.active!==!1}}async function Co(){let n=await y("IP address or CIDR (e.g., 192.168.1.100/32):",{type:"text"});if(!n.trim())throw new Error("IP address cannot be empty");let e=await y("Hostname (use * for all):",{type:"text",initial:"*"}),t=await y("Notes (optional):",{type:"text"});return{ip:n.trim(),hostname:e.trim()||"*",...t.trim()&&{notes:t.trim()},action:"deny"}}function Ro(n){if(!n.ip)throw new Error("--ip is required for IP blocking rules");return{ip:n.ip.trim(),hostname:n.hostname||"*",...n.notes&&{notes:n.notes},action:"deny"}}function bo(n,e){if(n.rules.map(r=>r.name.toLowerCase()).includes(e.name.toLowerCase()))return`A rule named "${e.name}" already exists`;let i=n.rules.map(r=>r.id).filter(Boolean);return e.id&&i.includes(e.id)?`A rule with ID "${e.id}" already exists`:null}function di(n){o.log(""),o.log(U.default.bold(` Rule: ${n.name}`)),n.description&&o.log(U.default.dim(` Description: ${n.description}`)),o.log(U.default.dim(` ID: ${n.id}`));let e=n.conditionGroup.map(r=>r.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 "));o.log(U.default.dim(` Conditions: ${e.join(" OR ")}`));let t=n.action.mitigate.action,i=[];n.action.mitigate.rateLimit&&i.push(`${n.action.mitigate.rateLimit.requests} req/${n.action.mitigate.rateLimit.window}`),n.action.mitigate.redirect&&i.push(`\u2192 ${n.action.mitigate.redirect.location}`),n.action.mitigate.actionDuration&&i.push(`duration: ${n.action.mitigate.actionDuration}`),o.log(U.default.dim(` Action: ${t}${i.length?` (${i.join(", ")})`:""}`)),o.log(U.default.dim(` Active: ${n.active?"\u2705":"\u274C"}`))}function ui(n){o.log(""),o.log(U.default.bold(` IP Rule: ${n.ip}`)),o.log(U.default.dim(` Hostname: ${n.hostname}`)),n.notes&&o.log(U.default.dim(` Notes: ${n.notes}`)),o.log(U.default.dim(` Action: ${n.action}`))}var vo=async n=>{try{if(n.debug&&(o.level=pi.LogLevels.debug),o.debug("Add command arguments:",n),(n.type||"rule")==="ip"){let t=n.interactive?await Co():Ro(n),i=ct.safeParse(t);if(i.success||(o.error(U.default.red("Rule validation failed:")),i.error.errors.forEach(a=>{let l=a.path.join(".");o.error(U.default.red(` - ${l||"ip"}: ${a.message}`))}),process.exit(1)),n.dryRun){o.info(U.default.cyan(`
|
|
22
|
-
Dry run - The following IP rule would be added:`)),
|
|
23
|
-
Dry run - The following rule would be added:`)),di(t),o.log(""),o.log(U.default.dim(JSON.stringify(t,null,2)));return}o.start("Loading configuration...");let r=await N(n.config,"raw"),s=r.rules||[],a=bo({...r,rules:s},t);if(a&&(o.warn(U.default.yellow(`\u26A0\uFE0F ${a}`)),!await y("Proceed anyway?",{type:"confirm",initial:!1}))){o.info("Cancelled.");return}let l={...r,rules:[...s,t]};await F(l,n.config),o.success(U.default.green(`\u2714 Rule "${t.name}" added to configuration`)),di(t)}o.log(""),o.log(U.default.dim(`Run ${U.default.cyan("doorman sync")} to deploy this rule.`))}catch(e){q(e,"adding rule")}};var Tt={};B(Tt,{builder:()=>Bo,command:()=>Fo,desc:()=>Vo,handler:()=>jo});var W=P(require("chalk")),ne=require("fs"),Ke=require("path"),Ei=require("consola");E();oe();var vi=require("consola");E();var Ri=P(require("chalk"));E();oe();Ct();E();var qe=class{static detect(e){let t=[];if(e&&"provider"in e){let r=e.provider;if(typeof r=="string"&&this.isValidProvider(r))return t.push(`Explicit provider specified in config: ${e.provider}`),{provider:r,confidence:"high",reasons:t};o.warn(`Invalid provider specified in config: ${String(e.provider)}`)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let r=e.providers;if(typeof(r.cloudflare||{}).zoneId=="string")return t.push("Cloudflare zone ID found in config"),{provider:"cloudflare",confidence:"high",reasons:t};if(typeof(r.vercel||{}).projectId=="string")return t.push("Vercel project ID found in config"),{provider:"vercel",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 i=this.detectFromEnvironment();return i.provider?i:(o.debug("Unable to auto-detect provider"),{provider:null,confidence:"low",reasons:["No provider information found in config or environment"]})}static detectFromEnvironment(){let e=[],t=process.env.DOORMAN_PROVIDER;return t&&this.isValidProvider(t)?(e.push(`Provider set via DOORMAN_PROVIDER environment variable: ${t}`),{provider:t,confidence:"high",reasons:e}):process.env.CLOUDFLARE_ZONE_ID&&process.env.CLOUDFLARE_API_TOKEN?(e.push("Cloudflare credentials found in environment variables"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.CLOUDFLARE_ZONE_ID?(e.push("Cloudflare zone ID found in environment"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID&&process.env.VERCEL_TOKEN?(e.push("Vercel credentials found in environment variables"),{provider:"vercel",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID?(e.push("Vercel project ID found in environment"),{provider:"vercel",confidence:"medium",reasons:e}):{provider:null,confidence:"low",reasons:["No provider credentials found in environment"]}}static isValidProvider(e){return e==="vercel"||e==="cloudflare"}static getProvider(e,t="vercel"){let i=this.detect(e);return i.provider?(o.debug(`Provider detected: ${i.provider} (${i.confidence} confidence)`),i.reasons.length>0&&o.debug(`Detection reasons: ${i.reasons.join(", ")}`),i.provider):(o.debug(`No provider detected, using fallback: ${t}`),t)}static detectAll(e){let t=new Set;if(e&&"provider"in e){let i=e.provider;typeof i=="string"&&this.isValidProvider(i)&&t.add(i)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let i=e.providers;typeof(i.cloudflare||{}).zoneId=="string"&&t.add("cloudflare"),typeof(i.vercel||{}).projectId=="string"&&t.add("vercel")}return e&&"projectId"in e&&typeof e.projectId=="string"&&t.add("vercel"),process.env.CLOUDFLARE_ZONE_ID&&t.add("cloudflare"),process.env.VERCEL_PROJECT_ID&&t.add("vercel"),Array.from(t)}};var Rt=P(require("chalk"));E();oe();var Me=n=>({$schema:Kt,firewallEnabled:!0,rules:[],ips:[],...n});E();var Ae=class{baseUrl;providerName;rateLimitInfo={};constructor(e,t){this.baseUrl=e,this.providerName=t}async makeRequest(e,t={}){let i=`${this.baseUrl}${e}`,{timeout:r=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 m=0;m<=s;m++)try{d=new AbortController,u=setTimeout(()=>{d&&d.abort()},r);let w=await fetch(i,{...l,headers:{"Content-Type":"application/json",...this.getAuthHeaders(),...l.headers},signal:d.signal});if(u&&(clearTimeout(u),u=null),this.updateRateLimitInfo(w),w.status===429){let R=this.calculateRateLimitWait(m,w);if(m===s)throw new Error(`${this.providerName} API rate limit exceeded after ${s+1} attempt(s) (429 Too Many Requests). Retry after ~${Math.round(R/1e3)}s.`);o.warn(`Rate limit exceeded for ${this.providerName}. Waiting ${R}ms before retry (attempt ${m+1}/${s+1})...`),await this.delay(R);continue}if(!w.ok)throw await this.handleErrorResponse(w);let C;try{let R=await w.text();R.trim()?C=JSON.parse(R):C={}}catch(R){throw o.error(`Failed to parse response from ${i}:`,R),new Error(`Invalid JSON response from ${this.providerName} API: ${R instanceof Error?R.message:String(R)}`)}return this.isLargeResponse(C)&&(o.debug(`Large response detected from ${i}, validating structure...`),this.validateLargeResponse(C)),C}catch(w){if(c=w,u&&(clearTimeout(u),u=null),this.isNonRetryableError(w)||m===s)throw w;let C=a*Math.pow(2,m),R=Math.random()*.1*C,O=Math.min(C+R,3e4);o.debug(`Request failed (attempt ${m+1}/${s+1}). Retrying in ${Math.round(O)}ms...`),o.debug(`Error details: ${w instanceof Error?w.message:String(w)}`),await this.delay(O)}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,i){return this.makeRequest(e,{...i,method:"POST",body:t?JSON.stringify(t):void 0})}async put(e,t,i){return this.makeRequest(e,{...i,method:"PUT",body:t?JSON.stringify(t):void 0})}async patch(e,t,i){return this.makeRequest(e,{...i,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"),i=e.headers.get("X-RateLimit-Remaining"),r=e.headers.get("X-RateLimit-Reset");t&&(this.rateLimitInfo.limit=parseInt(t,10)),i&&(this.rateLimitInfo.remaining=parseInt(i,10)),r&&(this.rateLimitInfo.reset=parseInt(r,10)),this.rateLimitInfo.remaining&&this.rateLimitInfo.remaining<10&&o.warn(`Approaching rate limit for ${this.providerName}: ${this.rateLimitInfo.remaining} requests remaining`)}calculateRateLimitWait(e=0,t){let r=t?this.parseRetryAfter(t.headers.get("Retry-After")):null;if(r!==null)return Math.min(Math.max(r,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 i=Date.parse(e);return Number.isNaN(i)?null:i-Date.now()}async handleErrorResponse(e){let t=`${this.providerName} API error: ${e.status} ${e.statusText}`,i=t;try{let r=await e.json();if(typeof r=="object"&&r!==null){let s=r;if(typeof s.error=="string")i=`${t} - ${s.error}`;else if(typeof s.message=="string")i=`${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(", ");i=`${t} - ${a}`}}}catch{}return o.error(i),new Error(i)}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=(i,r=0)=>{if(r>10)return!1;for(let[,s]of Object.entries(i))if(Array.isArray(s)&&s.length>1e3||typeof s=="object"&&s!==null&&t(s,r+1))return!0;return!1};return t(e)}validateLargeResponse(e){if(!e||typeof e!="object")return;let t=(r,s)=>{r.length>5e3&&o.warn(`Large array detected at ${s} with ${r.length} items. This may impact performance.`);let a=Math.min(10,r.length),l=r[0];if(l&&typeof l=="object"){let c=Object.keys(l);for(let d=1;d<a;d++){let u=r[d];if(!u||typeof u!="object"){o.warn(`Inconsistent array structure at ${s}[${d}]: expected object, got ${typeof u}`);continue}let p=Object.keys(u),m=c.filter(w=>!p.includes(w));m.length>0&&o.warn(`Inconsistent array structure at ${s}[${d}]: missing keys ${m.join(", ")}`)}}},i=(r,s="root",a=0)=>{if(!(a>10))for(let[l,c]of Object.entries(r)){let d=`${s}.${l}`;Array.isArray(c)?t(c,d):typeof c=="object"&&c!==null&&i(c,d,a+1)}};i(e)}};var mi=process.env.DOORMAN_VERCEL_API_BASE_URL||"https://api.vercel.com/v1/security/firewall/config",Te=class extends Ae{constructor(t,i,r){super("","vercel");this.projectId=t;this.teamId=i;this.token=r}projectId;teamId;token;getAuthHeaders(){return{Authorization:`Bearer ${this.token}`}}getUrl(t){let i=t!==void 0?`${mi}/${t}`:mi;return o.debug("API URL:",i),`${i}?projectId=${this.projectId}&teamId=${this.teamId}`}async fetchFirewallConfig(t,i){let{allowCreate:r=!0}=i??{},s=await this.get(this.getUrl(t));if(o.debug("Config Version:",t??"latest"),o.debug("Fetched Config:",t?s:s.active),t)return s;if(!s||"active"in s&&s.active===null){if(o.warn(Rt.default.bold("No firewall configuration found.")),!r)return o.debug("Skipping create-configuration prompt for read-only fetch."),this.emptyConfigPlaceholder();if(await y("Would you like to create one?",{type:"confirm"})){o.debug("Creating new empty firewall configuration...");let l=await this.putEmptyConfig();return o.debug("Empty firewall configuration created successfully"),o.debug(`New configuration version: ${Rt.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,...i}=Me();return o.debug("Empty Config:",i),this.putConfig(i)}async putConfig(t){return(await this.put(this.getUrl(),t)).active}async fetchActiveFirewallRules(){return(await this.fetchFirewallConfig())?.rules}async updateFirewallRule(t){let i=!t.id||t.id==="-",r={action:i?"rules.insert":"rules.update",id:i?null:t.id,value:{name:t.name,description:t.description,action:t.action,conditionGroup:t.conditionGroup,active:t.active}};return this.patch(this.getUrl(),r)}async createFirewallRule(t){return this.updateFirewallRule({...t,id:"-"})}async deleteFirewallRule(t){let i={action:"rules.remove",id:t.id,value:null};await this.patch(this.getUrl(),i)}async updateIPBlockingRule(t){let i=!t.id||t.id==="-",r={action:i?"ip.insert":"ip.update",id:i?null:t.id,value:{action:t.action,hostname:t.hostname,ip:t.ip,notes:t.notes??null}};return this.patch(this.getUrl(),r)}async createIPBlockingRule(t){return this.updateIPBlockingRule({...t,id:"-"})}async deleteIPBlockingRule(t){let i={action:"ip.remove",id:t.id,value:null};await this.patch(this.getUrl(),i)}async verifyCredentials(){try{return await this.fetchFirewallConfig(),!0}catch(t){return o.debug("Credential verification failed:",t),!1}}};var H=P(require("chalk"));E();E();var $e=class{validateConfig(e){let t=[],i=[];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 r=new Map;e.rules.forEach((s,a)=>{let l=s.id||s.name;if(!l)return;let c=r.get(l);if(c===void 0){r.set(l,a);return}let d=e.rules[c];i.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:i}}getHealthScore(e){let t=[],i=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)&&(i-=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&&(i-=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&&(i-=5,t.push({severity:"info",category:"maintenance",message:`${a.length} disabled rule(s) found`,suggestion:"Review and remove unused rules"}))}let r=this.calculateGrade(i),s=this.generateRecommendations(e,t);return{score:Math.max(0,i),grade:r,issues:t,recommendations:s}}diffItems(e,t,i,r="id"){let s=[],a=[],l=[],c=d=>d[r];for(let d of e){let u=t.find(p=>c(p)===c(d));u?i(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&&o.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 i=[];return t.some(r=>r.category==="rules")&&i.push("Consider using predefined templates to get started"),t.some(r=>r.category==="maintainability")&&i.push("Add descriptions to all rules for better documentation"),t.some(r=>r.category==="maintenance")&&i.push("Remove or enable disabled rules to keep configuration clean"),i}logSyncStats(e){o.info(`Sync complete for ${this.name}:`),o.info(` Rules added: ${e.rulesAdded}`),o.info(` Rules updated: ${e.rulesUpdated}`),o.info(` Rules deleted: ${e.rulesDeleted}`),e.ipsAdded!==void 0&&(o.info(` IPs added: ${e.ipsAdded}`),o.info(` IPs updated: ${e.ipsUpdated}`),o.info(` IPs deleted: ${e.ipsDeleted}`)),e.version&&o.info(` New version: ${e.version}`)}};E();function Pe(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var xe=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 i=this.vercelToCloudflare[e];if(!i)throw o.warn(`No Cloudflare mapping for Vercel type: ${e}`),new Error(`Unsupported Vercel rule type for Cloudflare: ${e}`);return e==="header"&&t?`${i}["${Pe(t.toLowerCase())}"]`:e==="cookie"&&t?`${i}["${Pe(t)}"]`:i}static toVercel(e){let t=e.match(/http\.request\.headers\["([^"]+)"\]/);if(t)return{type:"header",key:t[1]};let i=e.match(/http\.cookie\["([^"]+)"\]/);if(i)return{type:"cookie",key:i[1]};if(e==="http.referer")return{type:"header",key:"referer"};let r=this.cloudflareToVercel[e];if(r)return{type:r};throw o.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 To=new Set(["ip.src"]),ke=class{static fromVercelConditionGroups(e){if(!e||e.length===0)throw new Error("At least one condition group is required");let t=e.map(i=>{let r=i.conditions.map(s=>this.fromVercelCondition(s));if(r.length===0)throw new Error("Condition group must have at least one condition");return r.length>1?`(${r.join(" and ")})`:r[0]});return t.length>1?t.join(" or "):t[0]}static fromVercelCondition(e){let t=xe.toCloudflare(e.type,e.key),i=this.buildExistsOrComparisonExpression(t,e.op,()=>`${this.mapVercelOperator(e.op)} ${this.formatValue(t,e.value)}`);return e.neg&&(i=`not (${i})`),i}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 r=new Map;for(let a of e){let l=a.group??0,c=r.get(l);c?c.push(a):r.set(l,[a])}let s=Array.from(r.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),i=e.key&&(e.field==="header"||e.field==="cookie")?`${t}["${Pe(e.key)}"]`:t,r=this.buildUnifiedExpression(i,e.operator,e.value);return e.negated&&(r=`not (${r})`),r}static buildExistsOrComparisonExpression(e,t,i){return t==="ex"||t==="exists"?`${e} exists`:t==="nex"||t==="not_exists"?`not (${e} exists)`:`${e} ${i()}`}static buildUnifiedExpression(e,t,i){return t==="not_contains"?`not (${e} contains ${this.formatValue(e,i)})`:t==="not_in"?`not (${e} in ${this.formatValue(e,i)})`:this.buildExistsOrComparisonExpression(e,t,()=>`${this.mapUnifiedOperator(t)} ${this.formatValue(e,i)}`)}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(r=>this.formatSingleValue(e,r)).join(" ")}}`:this.formatSingleValue(e,t)}static formatSingleValue(e,t){if(typeof t=="string"){if(To.has(e)){if(!Ee.safeParse(t).success)throw new Error(`Invalid IP address or CIDR range: ${t}`);return t}return`"${Pe(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 i of e)if(i==="("&&t++,i===")"&&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 ")})`}};E();var D=class{static vercelToCloudflare(e){let t=[];try{let i=ke.fromVercelConditionGroups(e.conditionGroup),r=this.translateVercelActionToCloudflare(e.action.mitigate.action),s={id:e.id||crypto.randomUUID(),action:r,expression:i,description:e.description||e.name,enabled:e.active};if(e.action.mitigate.action==="rate_limit"&&e.action.mitigate.rateLimit){let a=e.action.mitigate.rateLimit;if(s.ratelimit={characteristics:a.characteristics||["ip.src"],period:this.parseWindowToSeconds(a.window),requests_per_period:a.requests},a.mitigationTimeout)s.ratelimit.mitigation_timeout=a.mitigationTimeout;else{s.ratelimit.mitigation_timeout=3600;let{TranslationWarningSystem:l}=(Y(),Q(X));t.push(l.createWarning("rate_limiting_precision",e.id,"rateLimit.mitigationTimeout","No mitigation timeout specified, using default 1 hour (3600 seconds)","Specify mitigationTimeout in your rate limit configuration for precise control"))}a.countingExpression&&(s.ratelimit.counting_expression=a.countingExpression)}return e.action.mitigate.action==="redirect"&&e.action.mitigate.redirect&&(s.action_parameters={from_value:{status_code:e.action.mitigate.redirect.permanent?301:302,target_url:{value:e.action.mitigate.redirect.location}}}),{result:s,warnings:t}}catch(i){throw o.error(`Failed to translate Vercel rule to Cloudflare: ${i}`),i}}static cloudflareToVercel(e){let t=[],{TranslationWarningSystem:i}=(Y(),Q(X));return t.push(i.createLossyConversionWarning("Cloudflare expression","Cloudflare expressions cannot be perfectly converted to Vercel structured conditions",e.id,"expression")),{result:{id:e.id,name:e.description||`Rule ${e.id}`,description:e.description,conditionGroup:[{conditions:[]}],action:{mitigate:{action:this.translateCloudflareActionToVercel(e.action)}},active:e.enabled??!0},warnings:t}}static vercelToUnified(e){let t=[],i=[];if(e.conditionGroup.forEach((a,l)=>{for(let c of a.conditions){let d=this.mapVercelOperatorToUnified(c.op);if(c.op==="re"&&typeof c.value=="string"){let{TranslationWarningSystem:u}=(Y(),Q(X));t.push(u.createWarning("regex_patterns",e.id,c.type,`Regular expression pattern may need adjustment for target provider: ${c.value}`,"Test the regex pattern in the target provider and adjust syntax if needed"))}i.push({field:this.mapVercelTypeToUnified(c.type),operator:d,value:c.value,negated:c.neg,key:c.key,group:l})}}),i.length>10){let{TranslationWarningSystem:a}=(Y(),Q(X));t.push(a.createWarning("many_conditions",e.id,void 0,`Rule has ${i.length} conditions which may impact performance`,"Consider splitting complex rules into multiple simpler rules for better performance"))}let r={type:e.action.mitigate.action,rateLimit:e.action.mitigate.rateLimit?{requests:e.action.mitigate.rateLimit.requests,window:e.action.mitigate.rateLimit.window,characteristics:e.action.mitigate.rateLimit.characteristics,mitigationTimeout:e.action.mitigate.rateLimit.mitigationTimeout,countingExpression:e.action.mitigate.rateLimit.countingExpression}:void 0,redirect:e.action.mitigate.redirect?{location:e.action.mitigate.redirect.location,permanent:e.action.mitigate.redirect.permanent}:void 0,duration:e.action.mitigate.actionDuration||void 0};return{result:{id:e.id,name:e.name,description:e.description,enabled:e.active,conditions:i,conditionLogic:e.conditionGroup.length>1?"OR":"AND",action:r},warnings:t}}static cloudflareToUnified(e){let t=[],{TranslationWarningSystem:i}=(Y(),Q(X));t.push(i.createWarning("complex_expressions",e.id,"expression","Expression parsing not fully implemented. Using simplified translation.","Review the translated rule and add missing conditions manually if needed."));let r={type:this.mapCloudflareActionToUnified(e.action),rateLimit:e.ratelimit?{requests:e.ratelimit.requests_per_period,window:`${e.ratelimit.period}s`,characteristics:e.ratelimit.characteristics,mitigationTimeout:e.ratelimit.mitigation_timeout,countingExpression:e.ratelimit.counting_expression}:void 0};return{result:{id:e.id,name:e.description||`Rule ${e.id}`,description:e.description,enabled:e.enabled??!0,conditions:[],action:r},warnings:t}}static unifiedToCloudflare(e){let t=[],i=ke.fromUnifiedConditions(e.conditions,e.conditionLogic),r={id:e.id||crypto.randomUUID(),action:this.mapUnifiedActionToCloudflare(e.action.type),expression:i,description:e.description||e.name,enabled:e.enabled};return e.action.rateLimit&&(r.ratelimit={characteristics:e.action.rateLimit.characteristics||["ip.src"],period:this.parseWindowToSeconds(e.action.rateLimit.window),requests_per_period:e.action.rateLimit.requests},e.action.rateLimit.mitigationTimeout?r.ratelimit.mitigation_timeout=e.action.rateLimit.mitigationTimeout:r.ratelimit.mitigation_timeout=3600,e.action.rateLimit.countingExpression&&(r.ratelimit.counting_expression=e.action.rateLimit.countingExpression)),{result:r,warnings:t}}static unifiedToVercel(e){let t=[],i=new Map;for(let a of e.conditions){let l=a.group??0,c=i.get(l);c?c.push(a):i.set(l,[a])}let r=[];for(let a of i.values()){let l=[];for(let c of a){let d=this.mapUnifiedTypeToVercel(c.field);if(!d){let{TranslationWarningSystem:u}=(Y(),Q(X));t.push(u.createUnsupportedFeatureWarning(`condition field '${c.field}'`,"unified config","Vercel",e.id,c.field));continue}l.push({op:this.mapUnifiedOperatorToVercel(c.operator),neg:c.negated,type:d,key:c.key,value:c.value})}l.length>0&&r.push({conditions:l})}if(r.length===0)throw new Error(`Rule "${e.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:e.id,name:e.name,description:e.description,conditionGroup:r,action:{mitigate:{action:e.action.type,rateLimit:e.action.rateLimit?{requests:e.action.rateLimit.requests,window:e.action.rateLimit.window,characteristics:e.action.rateLimit.characteristics,mitigationTimeout:e.action.rateLimit.mitigationTimeout,countingExpression:e.action.rateLimit.countingExpression}:null,redirect:e.action.redirect?{location:e.action.redirect.location,permanent:e.action.redirect.permanent}:null,actionDuration:e.action.duration||null}},active:e.enabled},warnings:t}}static vercelIPToUnified(e){return{id:e.id,ip:e.ip,hostname:e.hostname,notes:e.notes,action:e.action}}static unifiedIPToCloudflare(e){if(!Ee.safeParse(e.ip).success)throw new Error(`Invalid IP address or CIDR range: ${e.ip}`);let i=e.ip.includes("/")?`ip.src in {${e.ip}}`:`ip.src eq ${e.ip}`;return{id:e.id||crypto.randomUUID(),action:e.action==="allow"?"allow":"block",expression:i,description:e.notes||`IP ${e.action}: ${e.ip}${e.hostname?` (${e.hostname})`:""}`,enabled:!0}}static translateVercelActionToCloudflare(e){return{log:"log",deny:"block",challenge:"managed_challenge",bypass:"skip",rate_limit:"block",redirect:"redirect"}[e]||"block"}static translateCloudflareActionToVercel(e){return{block:"deny",challenge:"challenge",managed_challenge:"challenge",js_challenge:"challenge",log:"log",skip:"bypass",allow:"bypass",rewrite:"bypass",redirect:"redirect"}[e]||"deny"}static mapVercelOperatorToUnified(e){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists",nex:"not_exists"}[e]||"eq"}static mapUnifiedOperatorToVercel(e){return{eq:"eq",starts_with:"pre",ends_with:"suf",in:"inc",contains:"sub",matches:"re",exists:"ex",not_exists:"nex"}[e]||"eq"}static mapVercelTypeToUnified(e){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"}[e]||e}static UNIFIED_TO_VERCEL_TYPE_MAP={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"};static mapUnifiedTypeToVercel(e){return this.UNIFIED_TO_VERCEL_TYPE_MAP[e]??null}static mapCloudflareActionToUnified(e){return{block:"deny",challenge:"challenge",managed_challenge:"challenge",js_challenge:"challenge",log:"log",skip:"bypass",allow:"allow",rewrite:"bypass",redirect:"redirect"}[e]||"deny"}static mapUnifiedActionToCloudflare(e){return{log:"log",deny:"block",block:"block",challenge:"managed_challenge",bypass:"skip",rate_limit:"block",redirect:"redirect",allow:"allow"}[e]||"block"}static parseWindowToSeconds(e){let t=e.match(/^(\d+)([smhd])$/);if(!t||!t[1]||!t[2])throw new Error(`Invalid window format: ${e}`);let i=parseInt(t[1],10),r=t[2],a={s:1,m:60,h:3600,d:86400}[r];if(a===void 0)throw new Error(`Invalid time unit: ${r}`);return i*a}};Y();function Ge(n,e){if(n===e)return!0;if(typeof n!="object"||n===null||typeof e!="object"||e===null||Array.isArray(n)!==Array.isArray(e))return!1;let t=Object.keys(n),i=Object.keys(e);if(t.length!==i.length)return!1;for(let r of t)if(!i.includes(r)||!Ge(n[r],e[r]))return!1;return!0}function Ne(n){let{id:e,...t}=n;return t}var _e=class extends $e{constructor(t){super();this.client=t}client;name="vercel";async fetchConfig(t){try{o.debug("Fetching Vercel firewall configuration");let i=await this.client.fetchFirewallConfig(t),r=i.rules.map(a=>{let l=D.vercelToUnified(a);return l.warnings.length>0&&l.warnings.forEach(c=>{let{TranslationWarningSystem:d}=(Y(),Q(X)),u=d.formatWarning(c);o.warn(`Rule ${a.name}:
|
|
24
|
-
${u}`)}),l.result}),s=i.ips.map(a=>
|
|
25
|
-
${
|
|
19
|
+
${r}`}};var L=class n extends Error{constructor(t,i,r,s=[]){super(t);this.ajvErrors=i;this.zodError=r;this.customErrors=s;this.name="ValidationError"}ajvErrors;zodError;customErrors;static formatErrors(t,i,r=[]){let s=[];return t?.length&&s.push(...t.map(ce.formatValidationError)),i&&s.push(...i.errors.map(a=>`${a.path.join(".")}: ${a.message}`)),r.length&&s.push(...r),ce.wrapErrorBlock(s)}getFormattedMessage(){return n.formatErrors(this.ajvErrors,this.zodError,this.customErrors)}},de=class n{static instance;ajv;schema;constructor(){this.ajv=new ci.default({allErrors:!0,verbose:!0}),this.schema=Xt}static getInstance(){return n.instance||(n.instance=new n),n.instance}validateConfig(e){if(le(e))try{ai(e);return}catch(c){throw new L(`Invalid firewall configuration:
|
|
20
|
+
`+(c instanceof Error?c.message:String(c)),null)}let t=this.ajv.compile(this.schema),i=t(e),r=t.errors,s=pe.safeParse(e),a;s.success||(a=s.error);let l=[];if(i&&s.success){try{this.validateRuleNames(e),this.validateRuleConditionGroup(e),this.validateRuleAction(e)}catch(c){if(c instanceof L)l.push(c.message,...c.customErrors||[]);else throw c}for(let c of e.rules){if(c.action.mitigate?.rateLimit){let d=dt.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=ct.safeParse(d);u.success||l.push(...u.error.errors.map(p=>p.message))}}}if(!i||!s.success||l.length>0)throw new L(`Invalid firewall configuration:
|
|
21
|
+
`+L.formatErrors(r,a,l),r,a,l)}validateRuleNames(e){let t=new Set;for(let i of e.rules){if(t.has(i.name))throw new L(`Duplicate rule name found: "${i.name}"`,null);t.add(i.name)}}validateRuleConditionGroup(e){for(let t of e.rules)if(t.conditionGroup)for(let i of t.conditionGroup){if(!i.conditions||i.conditions.length===0)throw new L(`Rule "${t.name}" has an empty condition group`,null);for(let r of i.conditions){if(!r.type||!r.op)throw new L(`Rule "${t.name}" has an invalid condition`,null);let s=r.type==="header"||r.type==="cookie",a=r.op==="ex"||r.op==="nex";if(s){if(!r.key||typeof r.key!="string")throw new L(`Rule "${t.name}" has an invalid condition`,null);if(!a&&(r.value===void 0||r.value===null))throw new L(`Rule "${t.name}" has an invalid condition`,null)}else if(r.value===void 0||r.value===null)throw new L(`Rule "${t.name}" has an invalid condition`,null);let l=Array.isArray(r.value)?r.value:r.value!==void 0?[r.value]:[];if(Array.isArray(r.value)&&l.length===0)throw new L(`Rule "${t.name}" has an invalid value in condition`,null);if(r.type==="ip_address"){for(let c of l)if(typeof c!="string"||!this.isValidIP(c))throw new L(`Rule "${t.name}" has an invalid IP address in condition`,null)}if(r.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 L(`Rule "${t.name}" has an invalid ASN in condition`,null)}if(r.type==="path"&&(r.op==="eq"||r.op==="pre")){for(let c of l)if(typeof c!="string"||!this.isValidPath(c))throw new L(`Rule "${t.name}" has an invalid path in condition`,null)}}}else throw new L("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 i=t.action.mitigate;if(i?.rateLimit){if(i.rateLimit.requests<=0)throw new L("Invalid rate limit configuration: requests must be positive",null);if(!i.rateLimit.window.match(/^\d+[smhd]$/))throw new L("Invalid rate limit configuration: invalid window format",null);if(parseInt(i.rateLimit.window)<=0)throw new L("Invalid rate limit configuration: window duration must be positive",null)}if(i?.actionDuration&&!i.actionDuration.match(/^\d+[smhd]$|^permanent$/))throw new L("Invalid action duration format: "+i.actionDuration,null);if(i?.redirect&&!i.redirect.location)throw new L("Invalid redirect configuration: location is required",null)}}isValidIP(e){let t=e.split("/"),i=t[0]??"",r=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 m=parseInt(p,10);return m>=0&&m<=255})},a=d=>(0,li.isIPv6)(d),l=s(i),c=a(i);if(!l&&!c)return!1;if(r!==void 0){let d=parseInt(r,10);if(Number.isNaN(d)||l&&(d<0||d>32)||c&&(d<0||d>128))return!1}return!0}isValidASN(e){let t=parseInt(e,10);return!isNaN(t)&&t>=1&&t<=4294967295}isValidPath(e){return e.startsWith("/")&&!e.includes(" ")}};var di=require("fs"),Fe=require("path"),mt=[".doorman.json","vercel-firewall.config.json"],ho=mt[0],me=class{static async findConfig(e){let{findUp:t}=await import("find-up");for(let i of mt){let r=await t(i,{cwd:e||process.cwd()});if(r)return r}}static async findProjectRoot(e){let t=await this.findConfig(e);return t?(0,Fe.dirname)(t):null}static configExists(e){return(0,di.existsSync)((0,Fe.resolve)(e))}static getDefaultConfigPath(){return(0,Fe.resolve)(process.cwd(),ho)}static getSupportedFileNames(){return mt}};async function F(n,e="required"){let t=yo(e),i=n||await me.findConfig();if(!i||!(0,ue.existsSync)(i)){if(t==="optional")return o.debug("No config file found, returning empty config"),{};let s=me.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 r;try{let s=(0,ue.readFileSync)(i,"utf8");r=JSON.parse(s)}catch(s){throw s instanceof SyntaxError?new Error(`Invalid JSON in config file (${i}): ${s.message}`):s}if(t!=="raw")try{de.getInstance().validateConfig(r)}catch(s){if(t==="lenient")o.warn("Config validation failed:",s);else throw s}return r}async function V(n,e,t={validate:!0,throwOnError:!0}){let i=e||await me.findConfig()||me.getDefaultConfigPath();if(t.validate)try{de.getInstance().validateConfig(n)}catch(s){if(o.error("Config validation failed:",s),t.throwOnError)throw s}let r=(0,ui.dirname)(i);(0,ue.existsSync)(r)||(0,ue.mkdirSync)(r,{recursive:!0}),(0,ue.writeFileSync)(i,JSON.stringify(n,null,2)),o.debug(`Config saved to ${i}`)}function yo(n){if(typeof n=="string")return n;let{validate:e=!0,throwOnError:t=!0}=n;return e?t?"required":"lenient":"raw"}var ht=P(require("chalk")),pi=require("zod");E();function M(n,e){n instanceof SyntaxError?o.log(ce.wrapErrorBlock(["Invalid JSON format in config file:",` ${n.message}`])):n instanceof pi.ZodError?(o.error(ht.default.red("Schema validation failed:")),n.errors.forEach(t=>{let i=t.path.join(".");o.error(ht.default.red(` - ${i}: ${t.message}`))})):n instanceof Error&&n.name==="ValidationError"?o.error(n):n instanceof Error&&n.message.includes("Forbidden")?o.log(ce.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."])):o.error(ce.wrapErrorBlock([`Error ${e}:`,` ${n instanceof Error?n.message:String(n)}`])),process.exit(1)}var wo="add [type]",Io="Add a new firewall rule to your configuration",Co={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}},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"],wt=["eq","pre","suf","inc","sub","re","ex","nex"],It=["log","deny","challenge","bypass","rate_limit","redirect"];function Ct(n){let e=n.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 hi(n,e){return e==="inc"?n.split(",").map(t=>t.trim()):n}async function Ro(){let n=await y("Rule name:",{type:"text"});if(!n.trim())throw new Error("Rule name cannot be empty");let e=await y("Description (optional):",{type:"text"}),t=[],i=!0;for(;i;){let u=[],p=!0;for(;p;){let m=await y("Condition type:",{type:"select",options:yt,initial:"path"}),w=await y("Operator:",{type:"select",options:wt,initial:"eq"}),b;(m==="header"||m==="cookie"||m==="query")&&(b=await y(`${m} key:`,{type:"text"}));let R;if(w!=="ex"&&w!=="nex"){let ne=await y("Value:",{type:"text"});R=hi(ne,w)}let x=w!=="ex"&&w!=="nex"?await y("Negate this condition?",{type:"confirm",initial:!1}):!1,J={type:m,op:w,...R!==void 0&&{value:R},...b&&{key:b},...x&&{neg:x}};u.push(J),p=await y("Add another condition to this group? (AND logic)",{type:"confirm",initial:!1})}t.push({conditions:u}),i=await y("Add another condition group? (OR logic)",{type:"confirm",initial:!1})}let r=await y("Action:",{type:"select",options:It,initial:"deny"}),s;if(r==="rate_limit"){let u=parseInt(await y("Max requests:",{type:"text",initial:"100"}),10),p=await y('Time window (e.g., "60s", "1m", "1h"):',{type:"text",initial:"60s"});s={requests:u,window:p}}let a;if(r==="redirect"){let u=await y("Redirect URL:",{type:"text"}),p=await y("Permanent redirect (301)?",{type:"confirm",initial:!1});a={location:u,...p&&{permanent:p}}}let l;(r==="deny"||r==="challenge")&&await y("Set action duration? (default: permanent)",{type:"confirm",initial:!1})&&(l=await y('Duration (e.g., "1h", "1d", "permanent"):',{type:"text",initial:"permanent"}));let c=await y("Enable rule immediately?",{type:"confirm",initial:!0});return{id:Ct(n),name:n.trim(),...e.trim()&&{description:e.trim()},conditionGroup:t,action:{mitigate:{action:r,...s&&{rateLimit:s},...a&&{redirect:a},...l&&{actionDuration:l}}},active:c}}function bo(n){if(!n.name)throw new Error("--name is required in inline mode. Use --interactive for guided prompts.");if(!n.field)throw new Error("--field is required in inline mode (e.g., --field path)");if(!n.op)throw new Error("--op is required in inline mode (e.g., --op eq)");let e=n.op;if(!wt.includes(e))throw new Error(`Invalid operator "${n.op}". Valid operators: ${wt.join(", ")}`);let t=n.field;if(!yt.includes(t))throw new Error(`Invalid field type "${n.field}". Valid types: ${yt.join(", ")}`);let i=n.action||"deny";if(!It.includes(i))throw new Error(`Invalid action "${n.action}". Valid actions: ${It.join(", ")}`);if(e!=="ex"&&e!=="nex"&&!n.value)throw new Error("--value is required for the given operator");if((t==="header"||t==="cookie"||t==="query")&&!n.key)throw new Error(`--key is required for "${t}" condition type`);if(i==="rate_limit"&&(!n.requests||!n.window))throw new Error("--requests and --window are required when action is rate_limit");if(i==="redirect"&&!n.location)throw new Error("--location is required when action is redirect");let r=n.value?hi(n.value,e):void 0,s={type:t,op:e,...r!==void 0&&{value:r},...n.key&&{key:n.key},...n.neg&&{neg:!0}};return{id:Ct(n.name),name:n.name.trim(),...n.description&&{description:n.description},conditionGroup:[{conditions:[s]}],action:{mitigate:{action:i,...i==="rate_limit"&&n.requests&&n.window&&{rateLimit:{requests:n.requests,window:n.window}},...i==="redirect"&&n.location&&{redirect:{location:n.location,...n.permanent&&{permanent:!0}}},...n.duration&&{actionDuration:n.duration}}},active:n.active!==!1}}async function vo(){let n=await y("IP address or CIDR (e.g., 192.168.1.100/32):",{type:"text"});if(!n.trim())throw new Error("IP address cannot be empty");let e=await y("Hostname (use * for all):",{type:"text",initial:"*"}),t=await y("Notes (optional):",{type:"text"});return{ip:n.trim(),hostname:e.trim()||"*",...t.trim()&&{notes:t.trim()},action:"deny"}}function Eo(n){if(!n.ip)throw new Error("--ip is required for IP blocking rules");return{ip:n.ip.trim(),hostname:n.hostname||"*",...n.notes&&{notes:n.notes},action:"deny"}}function Ao(n,e){if(n.rules.map(r=>r.name.toLowerCase()).includes(e.name.toLowerCase()))return`A rule named "${e.name}" already exists`;let i=n.rules.map(r=>r.id).filter(Boolean);return e.id&&i.includes(e.id)?`A rule with ID "${e.id}" already exists`:null}function gi(n){o.log(""),o.log(U.default.bold(` Rule: ${n.name}`)),n.description&&o.log(U.default.dim(` Description: ${n.description}`)),o.log(U.default.dim(` ID: ${n.id}`));let e=n.conditionGroup.map(r=>r.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 "));o.log(U.default.dim(` Conditions: ${e.join(" OR ")}`));let t=n.action.mitigate.action,i=[];n.action.mitigate.rateLimit&&i.push(`${n.action.mitigate.rateLimit.requests} req/${n.action.mitigate.rateLimit.window}`),n.action.mitigate.redirect&&i.push(`\u2192 ${n.action.mitigate.redirect.location}`),n.action.mitigate.actionDuration&&i.push(`duration: ${n.action.mitigate.actionDuration}`),o.log(U.default.dim(` Action: ${t}${i.length?` (${i.join(", ")})`:""}`)),o.log(U.default.dim(` Active: ${n.active?"\u2705":"\u274C"}`))}function fi(n){o.log(""),o.log(U.default.bold(` IP Rule: ${n.ip}`)),o.log(U.default.dim(` Hostname: ${n.hostname}`)),n.notes&&o.log(U.default.dim(` Notes: ${n.notes}`)),o.log(U.default.dim(` Action: ${n.action}`))}var $o=async n=>{try{if(n.debug&&(o.level=mi.LogLevels.debug),o.debug("Add command arguments:",n),(n.type||"rule")==="ip"){let t=n.interactive?await vo():Eo(n),i=pt.safeParse(t);if(i.success||(o.error(U.default.red("Rule validation failed:")),i.error.errors.forEach(a=>{let l=a.path.join(".");o.error(U.default.red(` - ${l||"ip"}: ${a.message}`))}),process.exit(1)),n.dryRun){o.info(U.default.cyan(`
|
|
22
|
+
Dry run - The following IP rule would be added:`)),fi(t),o.log(""),o.log(U.default.dim(JSON.stringify(t,null,2)));return}o.start("Loading configuration...");let r=await F(n.config,"raw"),s={...r,ips:[...r.ips||[],t]};await V(s,n.config),o.success(U.default.green(`\u2714 IP rule "${t.ip}" added to configuration`)),fi(t)}else{let t=n.interactive?await Ro():bo(n),i=ut.safeParse(t);if(i.success||(o.error(U.default.red("Rule validation failed:")),i.error.errors.forEach(c=>{let d=c.path.join(".")||"rule";o.error(U.default.red(` - ${d}: ${c.message}`))}),process.exit(1)),n.dryRun){o.info(U.default.cyan(`
|
|
23
|
+
Dry run - The following rule would be added:`)),gi(t),o.log(""),o.log(U.default.dim(JSON.stringify(t,null,2)));return}o.start("Loading configuration...");let r=await F(n.config,"raw"),s=r.rules||[],a=Ao({...r,rules:s},t);if(a&&(o.warn(U.default.yellow(`\u26A0\uFE0F ${a}`)),!await y("Proceed anyway?",{type:"confirm",initial:!1}))){o.info("Cancelled.");return}let l={...r,rules:[...s,t]};await V(l,n.config),o.success(U.default.green(`\u2714 Rule "${t.name}" added to configuration`)),gi(t)}o.log(""),o.log(U.default.dim(`Run ${U.default.cyan("doorman sync")} to deploy this rule.`))}catch(e){M(e,"adding rule")}};var Pt={};j(Pt,{builder:()=>qo,command:()=>jo,desc:()=>zo,handler:()=>Mo});var G=P(require("chalk")),se=require("fs"),nt=require("path"),Ti=require("consola");E();re();var $i=require("consola");E();var Ei=P(require("chalk"));E();re();bt();E();var Ye=class{static detect(e){let t=[];if(e&&"provider"in e){let r=e.provider;if(typeof r=="string"&&this.isValidProvider(r))return t.push(`Explicit provider specified in config: ${e.provider}`),{provider:r,confidence:"high",reasons:t};o.warn(`Invalid provider specified in config: ${String(e.provider)}`)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let r=e.providers;if(typeof(r.cloudflare||{}).zoneId=="string")return t.push("Cloudflare zone ID found in config"),{provider:"cloudflare",confidence:"high",reasons:t};if(typeof(r.vercel||{}).projectId=="string")return t.push("Vercel project ID found in config"),{provider:"vercel",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 i=this.detectFromEnvironment();return i.provider?i:(o.debug("Unable to auto-detect provider"),{provider:null,confidence:"low",reasons:["No provider information found in config or environment"]})}static detectFromEnvironment(){let e=[],t=process.env.DOORMAN_PROVIDER;return t&&this.isValidProvider(t)?(e.push(`Provider set via DOORMAN_PROVIDER environment variable: ${t}`),{provider:t,confidence:"high",reasons:e}):process.env.CLOUDFLARE_ZONE_ID&&process.env.CLOUDFLARE_API_TOKEN?(e.push("Cloudflare credentials found in environment variables"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.CLOUDFLARE_ZONE_ID?(e.push("Cloudflare zone ID found in environment"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID&&process.env.VERCEL_TOKEN?(e.push("Vercel credentials found in environment variables"),{provider:"vercel",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID?(e.push("Vercel project ID found in environment"),{provider:"vercel",confidence:"medium",reasons:e}):{provider:null,confidence:"low",reasons:["No provider credentials found in environment"]}}static isValidProvider(e){return e==="vercel"||e==="cloudflare"}static getProvider(e,t="vercel"){let i=this.detect(e);return i.provider?(o.debug(`Provider detected: ${i.provider} (${i.confidence} confidence)`),i.reasons.length>0&&o.debug(`Detection reasons: ${i.reasons.join(", ")}`),i.provider):(o.debug(`No provider detected, using fallback: ${t}`),t)}static detectAll(e){let t=new Set;if(e&&"provider"in e){let i=e.provider;typeof i=="string"&&this.isValidProvider(i)&&t.add(i)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let i=e.providers;typeof(i.cloudflare||{}).zoneId=="string"&&t.add("cloudflare"),typeof(i.vercel||{}).projectId=="string"&&t.add("vercel")}return e&&"projectId"in e&&typeof e.projectId=="string"&&t.add("vercel"),process.env.CLOUDFLARE_ZONE_ID&&t.add("cloudflare"),process.env.VERCEL_PROJECT_ID&&t.add("vercel"),Array.from(t)}};var vt=P(require("chalk"));E();re();var Xe=n=>({$schema:Yt,firewallEnabled:!0,rules:[],ips:[],...n});E();var Te=class{baseUrl;providerName;rateLimitInfo={};constructor(e,t){this.baseUrl=e,this.providerName=t}async makeRequest(e,t={}){let i=`${this.baseUrl}${e}`,{timeout:r=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 m=0;m<=s;m++)try{d=new AbortController,u=setTimeout(()=>{d&&d.abort()},r);let w=await fetch(i,{...l,headers:{"Content-Type":"application/json",...this.getAuthHeaders(),...l.headers},signal:d.signal});if(u&&(clearTimeout(u),u=null),this.updateRateLimitInfo(w),w.status===429){let R=this.calculateRateLimitWait(m,w);if(m===s)throw new Error(`${this.providerName} API rate limit exceeded after ${s+1} attempt(s) (429 Too Many Requests). Retry after ~${Math.round(R/1e3)}s.`);o.warn(`Rate limit exceeded for ${this.providerName}. Waiting ${R}ms before retry (attempt ${m+1}/${s+1})...`),await this.delay(R);continue}if(!w.ok)throw await this.handleErrorResponse(w);let b;try{let R=await w.text();R.trim()?b=JSON.parse(R):b={}}catch(R){throw o.error(`Failed to parse response from ${i}:`,R),new Error(`Invalid JSON response from ${this.providerName} API: ${R instanceof Error?R.message:String(R)}`)}return this.isLargeResponse(b)&&(o.debug(`Large response detected from ${i}, validating structure...`),this.validateLargeResponse(b)),b}catch(w){if(c=w,u&&(clearTimeout(u),u=null),this.isNonRetryableError(w)||m===s)throw w;let b=a*Math.pow(2,m),R=Math.random()*.1*b,x=Math.min(b+R,3e4);o.debug(`Request failed (attempt ${m+1}/${s+1}). Retrying in ${Math.round(x)}ms...`),o.debug(`Error details: ${w instanceof Error?w.message:String(w)}`),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,i){return this.makeRequest(e,{...i,method:"POST",body:t?JSON.stringify(t):void 0})}async put(e,t,i){return this.makeRequest(e,{...i,method:"PUT",body:t?JSON.stringify(t):void 0})}async patch(e,t,i){return this.makeRequest(e,{...i,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"),i=e.headers.get("X-RateLimit-Remaining"),r=e.headers.get("X-RateLimit-Reset");t&&(this.rateLimitInfo.limit=parseInt(t,10)),i&&(this.rateLimitInfo.remaining=parseInt(i,10)),r&&(this.rateLimitInfo.reset=parseInt(r,10)),this.rateLimitInfo.remaining&&this.rateLimitInfo.remaining<10&&o.warn(`Approaching rate limit for ${this.providerName}: ${this.rateLimitInfo.remaining} requests remaining`)}calculateRateLimitWait(e=0,t){let r=t?this.parseRetryAfter(t.headers.get("Retry-After")):null;if(r!==null)return Math.min(Math.max(r,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 i=Date.parse(e);return Number.isNaN(i)?null:i-Date.now()}async handleErrorResponse(e){let t=`${this.providerName} API error: ${e.status} ${e.statusText}`,i=t;try{let r=await e.json();if(typeof r=="object"&&r!==null){let s=r;if(typeof s.error=="string")i=`${t} - ${s.error}`;else if(typeof s.message=="string")i=`${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(", ");i=`${t} - ${a}`}}}catch{}return o.error(i),new Error(i)}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=(i,r=0)=>{if(r>10)return!1;for(let[,s]of Object.entries(i))if(Array.isArray(s)&&s.length>1e3||typeof s=="object"&&s!==null&&t(s,r+1))return!0;return!1};return t(e)}validateLargeResponse(e){if(!e||typeof e!="object")return;let t=(r,s)=>{r.length>5e3&&o.warn(`Large array detected at ${s} with ${r.length} items. This may impact performance.`);let a=Math.min(10,r.length),l=r[0];if(l&&typeof l=="object"){let c=Object.keys(l);for(let d=1;d<a;d++){let u=r[d];if(!u||typeof u!="object"){o.warn(`Inconsistent array structure at ${s}[${d}]: expected object, got ${typeof u}`);continue}let p=Object.keys(u),m=c.filter(w=>!p.includes(w));m.length>0&&o.warn(`Inconsistent array structure at ${s}[${d}]: missing keys ${m.join(", ")}`)}}},i=(r,s="root",a=0)=>{if(!(a>10))for(let[l,c]of Object.entries(r)){let d=`${s}.${l}`;Array.isArray(c)?t(c,d):typeof c=="object"&&c!==null&&i(c,d,a+1)}};i(e)}};var wi=process.env.DOORMAN_VERCEL_API_BASE_URL||"https://api.vercel.com/v1/security/firewall/config",Pe=class extends Te{constructor(t,i,r){super("","vercel");this.projectId=t;this.teamId=i;this.token=r}projectId;teamId;token;getAuthHeaders(){return{Authorization:`Bearer ${this.token}`}}getUrl(t){let i=t!==void 0?`${wi}/${t}`:wi;return o.debug("API URL:",i),`${i}?projectId=${this.projectId}&teamId=${this.teamId}`}async fetchFirewallConfig(t,i){let{allowCreate:r=!0}=i??{},s=await this.get(this.getUrl(t));if(o.debug("Config Version:",t??"latest"),o.debug("Fetched Config:",t?s:s.active),t)return s;if(!s||"active"in s&&s.active===null){if(o.warn(vt.default.bold("No firewall configuration found.")),!r)return o.debug("Skipping create-configuration prompt for read-only fetch."),this.emptyConfigPlaceholder();if(await y("Would you like to create one?",{type:"confirm"})){o.debug("Creating new empty firewall configuration...");let l=await this.putEmptyConfig();return o.debug("Empty firewall configuration created successfully"),o.debug(`New configuration version: ${vt.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,...i}=Xe();return o.debug("Empty Config:",i),this.putConfig(i)}async putConfig(t){return(await this.put(this.getUrl(),t)).active}async fetchActiveFirewallRules(){return(await this.fetchFirewallConfig())?.rules}async updateFirewallRule(t){let i=!t.id||t.id==="-",r={action:i?"rules.insert":"rules.update",id:i?null:t.id,value:{name:t.name,description:t.description,action:t.action,conditionGroup:t.conditionGroup,active:t.active}};return this.patch(this.getUrl(),r)}async createFirewallRule(t){return this.updateFirewallRule({...t,id:"-"})}async deleteFirewallRule(t){let i={action:"rules.remove",id:t.id,value:null};await this.patch(this.getUrl(),i)}async updateIPBlockingRule(t){let i=!t.id||t.id==="-",r={action:i?"ip.insert":"ip.update",id:i?null:t.id,value:{action:t.action,hostname:t.hostname,ip:t.ip,notes:t.notes??null}};return this.patch(this.getUrl(),r)}async createIPBlockingRule(t){return this.updateIPBlockingRule({...t,id:"-"})}async deleteIPBlockingRule(t){let i={action:"ip.remove",id:t.id,value:null};await this.patch(this.getUrl(),i)}async verifyCredentials(){try{return await this.fetchFirewallConfig(),!0}catch(t){return o.debug("Credential verification failed:",t),!1}}};var K=P(require("chalk"));E();E();var ke=class{validateConfig(e){let t=[],i=[];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 r=new Map;e.rules.forEach((s,a)=>{let l=s.id||s.name;if(!l)return;let c=r.get(l);if(c===void 0){r.set(l,a);return}let d=e.rules[c];i.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:i}}getHealthScore(e){let t=[],i=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)&&(i-=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&&(i-=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&&(i-=5,t.push({severity:"info",category:"maintenance",message:`${a.length} disabled rule(s) found`,suggestion:"Review and remove unused rules"}))}let r=this.calculateGrade(i),s=this.generateRecommendations(e,t);return{score:Math.max(0,i),grade:r,issues:t,recommendations:s}}diffItems(e,t,i,r="id"){let s=[],a=[],l=[],c=d=>d[r];for(let d of e){let u=t.find(p=>c(p)===c(d));u?i(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&&o.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 i=[];return t.some(r=>r.category==="rules")&&i.push("Consider using predefined templates to get started"),t.some(r=>r.category==="maintainability")&&i.push("Add descriptions to all rules for better documentation"),t.some(r=>r.category==="maintenance")&&i.push("Remove or enable disabled rules to keep configuration clean"),i}logSyncStats(e){o.info(`Sync complete for ${this.name}:`),o.info(` Rules added: ${e.rulesAdded}`),o.info(` Rules updated: ${e.rulesUpdated}`),o.info(` Rules deleted: ${e.rulesDeleted}`),e.ipsAdded!==void 0&&(o.info(` IPs added: ${e.ipsAdded}`),o.info(` IPs updated: ${e.ipsUpdated}`),o.info(` IPs deleted: ${e.ipsDeleted}`)),e.version&&o.info(` New version: ${e.version}`)}};E();function _e(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Ve=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 i=this.vercelToCloudflare[e];if(!i)throw o.warn(`No Cloudflare mapping for Vercel type: ${e}`),new Error(`Unsupported Vercel rule type for Cloudflare: ${e}`);return e==="header"&&t?`${i}["${_e(t.toLowerCase())}"]`:e==="cookie"&&t?`${i}["${_e(t)}"]`:i}static toVercel(e){let t=e.match(/http\.request\.headers\["([^"]+)"\]/);if(t)return{type:"header",key:t[1]};let i=e.match(/http\.cookie\["([^"]+)"\]/);if(i)return{type:"cookie",key:i[1]};if(e==="http.referer")return{type:"header",key:"referer"};let r=this.cloudflareToVercel[e];if(r)return{type:r};throw o.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 ko=new Set(["ip.src"]),Se=class{static fromVercelConditionGroups(e){if(!e||e.length===0)throw new Error("At least one condition group is required");let t=e.map(i=>{let r=i.conditions.map(s=>this.fromVercelCondition(s));if(r.length===0)throw new Error("Condition group must have at least one condition");return r.length>1?`(${r.join(" and ")})`:r[0]});return t.length>1?t.join(" or "):t[0]}static fromVercelCondition(e){let t=Ve.toCloudflare(e.type,e.key),i=this.buildExistsOrComparisonExpression(t,e.op,()=>`${this.mapVercelOperator(e.op)} ${this.formatValue(t,e.value)}`);return e.neg&&(i=`not (${i})`),i}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 r=new Map;for(let a of e){let l=a.group??0,c=r.get(l);c?c.push(a):r.set(l,[a])}let s=Array.from(r.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),i=e.key&&(e.field==="header"||e.field==="cookie")?`${t}["${_e(e.key)}"]`:t,r=this.buildUnifiedExpression(i,e.operator,e.value);return e.negated&&(r=`not (${r})`),r}static buildExistsOrComparisonExpression(e,t,i){return t==="ex"||t==="exists"?`${e} exists`:t==="nex"||t==="not_exists"?`not (${e} exists)`:`${e} ${i()}`}static buildUnifiedExpression(e,t,i){return t==="not_contains"?`not (${e} contains ${this.formatValue(e,i)})`:t==="not_in"?`not (${e} in ${this.formatValue(e,i)})`:this.buildExistsOrComparisonExpression(e,t,()=>`${this.mapUnifiedOperator(t)} ${this.formatValue(e,i)}`)}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(r=>this.formatSingleValue(e,r)).join(" ")}}`:this.formatSingleValue(e,t)}static formatSingleValue(e,t){if(typeof t=="string"){if(ko.has(e)){if(!$e.safeParse(t).success)throw new Error(`Invalid IP address or CIDR range: ${t}`);return t}return`"${_e(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 i of e)if(i==="("&&t++,i===")"&&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 ")})`}};E();var O=class{static vercelToCloudflare(e){let t=[];try{let i=Se.fromVercelConditionGroups(e.conditionGroup),r=this.translateVercelActionToCloudflare(e.action.mitigate.action),s={id:e.id||crypto.randomUUID(),action:r,expression:i,description:e.description||e.name,enabled:e.active};if(e.action.mitigate.action==="rate_limit"&&e.action.mitigate.rateLimit){let a=e.action.mitigate.rateLimit;if(s.ratelimit={characteristics:a.characteristics||["ip.src"],period:this.parseWindowToSeconds(a.window),requests_per_period:a.requests},a.mitigationTimeout)s.ratelimit.mitigation_timeout=a.mitigationTimeout;else{s.ratelimit.mitigation_timeout=3600;let{TranslationWarningSystem:l}=(X(),Y(ee));t.push(l.createWarning("rate_limiting_precision",e.id,"rateLimit.mitigationTimeout","No mitigation timeout specified, using default 1 hour (3600 seconds)","Specify mitigationTimeout in your rate limit configuration for precise control"))}a.countingExpression&&(s.ratelimit.counting_expression=a.countingExpression)}return e.action.mitigate.action==="redirect"&&e.action.mitigate.redirect&&(s.action_parameters={from_value:{status_code:e.action.mitigate.redirect.permanent?301:302,target_url:{value:e.action.mitigate.redirect.location}}}),{result:s,warnings:t}}catch(i){throw o.error(`Failed to translate Vercel rule to Cloudflare: ${i}`),i}}static cloudflareToVercel(e){let t=[],{TranslationWarningSystem:i}=(X(),Y(ee));return t.push(i.createLossyConversionWarning("Cloudflare expression","Cloudflare expressions cannot be perfectly converted to Vercel structured conditions",e.id,"expression")),{result:{id:e.id,name:e.description||`Rule ${e.id}`,description:e.description,conditionGroup:[{conditions:[]}],action:{mitigate:{action:this.translateCloudflareActionToVercel(e.action)}},active:e.enabled??!0},warnings:t}}static vercelToUnified(e){let t=[],i=[];if(e.conditionGroup.forEach((a,l)=>{for(let c of a.conditions){let d=this.mapVercelOperatorToUnified(c.op);if(c.op==="re"&&typeof c.value=="string"){let{TranslationWarningSystem:u}=(X(),Y(ee));t.push(u.createWarning("regex_patterns",e.id,c.type,`Regular expression pattern may need adjustment for target provider: ${c.value}`,"Test the regex pattern in the target provider and adjust syntax if needed"))}i.push({field:this.mapVercelTypeToUnified(c.type),operator:d,value:c.value,negated:c.neg,key:c.key,group:l})}}),i.length>10){let{TranslationWarningSystem:a}=(X(),Y(ee));t.push(a.createWarning("many_conditions",e.id,void 0,`Rule has ${i.length} conditions which may impact performance`,"Consider splitting complex rules into multiple simpler rules for better performance"))}let r={type:e.action.mitigate.action,rateLimit:e.action.mitigate.rateLimit?{requests:e.action.mitigate.rateLimit.requests,window:e.action.mitigate.rateLimit.window,characteristics:e.action.mitigate.rateLimit.characteristics,mitigationTimeout:e.action.mitigate.rateLimit.mitigationTimeout,countingExpression:e.action.mitigate.rateLimit.countingExpression}:void 0,redirect:e.action.mitigate.redirect?{location:e.action.mitigate.redirect.location,permanent:e.action.mitigate.redirect.permanent}:void 0,duration:e.action.mitigate.actionDuration||void 0};return{result:{id:e.id,name:e.name,description:e.description,enabled:e.active,conditions:i,conditionLogic:e.conditionGroup.length>1?"OR":"AND",action:r},warnings:t}}static cloudflareToUnified(e){let t=[],{TranslationWarningSystem:i}=(X(),Y(ee));t.push(i.createWarning("complex_expressions",e.id,"expression","Expression parsing not fully implemented. Using simplified translation.","Review the translated rule and add missing conditions manually if needed."));let r={type:this.mapCloudflareActionToUnified(e.action),rateLimit:e.ratelimit?{requests:e.ratelimit.requests_per_period,window:`${e.ratelimit.period}s`,characteristics:e.ratelimit.characteristics,mitigationTimeout:e.ratelimit.mitigation_timeout,countingExpression:e.ratelimit.counting_expression}:void 0};return{result:{id:e.id,name:e.description||`Rule ${e.id}`,description:e.description,enabled:e.enabled??!0,conditions:[],action:r},warnings:t}}static unifiedToCloudflare(e){let t=[],i=Se.fromUnifiedConditions(e.conditions,e.conditionLogic),r={id:e.id||crypto.randomUUID(),action:this.mapUnifiedActionToCloudflare(e.action.type),expression:i,description:e.description||e.name,enabled:e.enabled};return e.action.rateLimit&&(r.ratelimit={characteristics:e.action.rateLimit.characteristics||["ip.src"],period:this.parseWindowToSeconds(e.action.rateLimit.window),requests_per_period:e.action.rateLimit.requests},e.action.rateLimit.mitigationTimeout?r.ratelimit.mitigation_timeout=e.action.rateLimit.mitigationTimeout:r.ratelimit.mitigation_timeout=3600,e.action.rateLimit.countingExpression&&(r.ratelimit.counting_expression=e.action.rateLimit.countingExpression)),{result:r,warnings:t}}static unifiedToVercel(e){let t=[],i=new Map;for(let a of e.conditions){let l=a.group??0,c=i.get(l);c?c.push(a):i.set(l,[a])}let r=[];for(let a of i.values()){let l=[];for(let c of a){let d=this.mapUnifiedTypeToVercel(c.field);if(!d){let{TranslationWarningSystem:u}=(X(),Y(ee));t.push(u.createUnsupportedFeatureWarning(`condition field '${c.field}'`,"unified config","Vercel",e.id,c.field));continue}l.push({op:this.mapUnifiedOperatorToVercel(c.operator),neg:c.negated,type:d,key:c.key,value:c.value})}l.length>0&&r.push({conditions:l})}if(r.length===0)throw new Error(`Rule "${e.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:e.id,name:e.name,description:e.description,conditionGroup:r,action:{mitigate:{action:e.action.type,rateLimit:e.action.rateLimit?{requests:e.action.rateLimit.requests,window:e.action.rateLimit.window,characteristics:e.action.rateLimit.characteristics,mitigationTimeout:e.action.rateLimit.mitigationTimeout,countingExpression:e.action.rateLimit.countingExpression}:null,redirect:e.action.redirect?{location:e.action.redirect.location,permanent:e.action.redirect.permanent}:null,actionDuration:e.action.duration||null}},active:e.enabled},warnings:t}}static vercelIPToUnified(e){return{id:e.id,ip:e.ip,hostname:e.hostname,notes:e.notes,action:e.action}}static unifiedIPToCloudflare(e){if(!$e.safeParse(e.ip).success)throw new Error(`Invalid IP address or CIDR range: ${e.ip}`);let i=e.ip.includes("/")?`ip.src in {${e.ip}}`:`ip.src eq ${e.ip}`;return{id:e.id||crypto.randomUUID(),action:e.action==="allow"?"allow":"block",expression:i,description:e.notes||`IP ${e.action}: ${e.ip}${e.hostname?` (${e.hostname})`:""}`,enabled:!0}}static translateVercelActionToCloudflare(e){return{log:"log",deny:"block",challenge:"managed_challenge",bypass:"skip",rate_limit:"block",redirect:"redirect"}[e]||"block"}static translateCloudflareActionToVercel(e){return{block:"deny",challenge:"challenge",managed_challenge:"challenge",js_challenge:"challenge",log:"log",skip:"bypass",allow:"bypass",rewrite:"bypass",redirect:"redirect"}[e]||"deny"}static mapVercelOperatorToUnified(e){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists",nex:"not_exists"}[e]||"eq"}static mapUnifiedOperatorToVercel(e){return{eq:"eq",starts_with:"pre",ends_with:"suf",in:"inc",contains:"sub",matches:"re",exists:"ex",not_exists:"nex"}[e]||"eq"}static mapVercelTypeToUnified(e){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"}[e]||e}static UNIFIED_TO_VERCEL_TYPE_MAP={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"};static mapUnifiedTypeToVercel(e){return this.UNIFIED_TO_VERCEL_TYPE_MAP[e]??null}static mapCloudflareActionToUnified(e){return{block:"deny",challenge:"challenge",managed_challenge:"challenge",js_challenge:"challenge",log:"log",skip:"bypass",allow:"allow",rewrite:"bypass",redirect:"redirect"}[e]||"deny"}static mapUnifiedActionToCloudflare(e){return{log:"log",deny:"block",block:"block",challenge:"managed_challenge",bypass:"skip",rate_limit:"block",redirect:"redirect",allow:"allow"}[e]||"block"}static parseWindowToSeconds(e){let t=e.match(/^(\d+)([smhd])$/);if(!t||!t[1]||!t[2])throw new Error(`Invalid window format: ${e}`);let i=parseInt(t[1],10),r=t[2],a={s:1,m:60,h:3600,d:86400}[r];if(a===void 0)throw new Error(`Invalid time unit: ${r}`);return i*a}};X();function tt(n,e){if(n===e)return!0;if(typeof n!="object"||n===null||typeof e!="object"||e===null||Array.isArray(n)!==Array.isArray(e))return!1;let t=Object.keys(n),i=Object.keys(e);if(t.length!==i.length)return!1;for(let r of t)if(!i.includes(r)||!tt(n[r],e[r]))return!1;return!0}function Be(n){let{id:e,...t}=n;return t}var Le=class extends ke{constructor(t){super();this.client=t}client;name="vercel";async fetchConfig(t){try{o.debug("Fetching Vercel firewall configuration");let i=await this.client.fetchFirewallConfig(t),r=i.rules.map(a=>{let l=O.vercelToUnified(a);return l.warnings.length>0&&l.warnings.forEach(c=>{let{TranslationWarningSystem:d}=(X(),Y(ee)),u=d.formatWarning(c);o.warn(`Rule ${a.name}:
|
|
24
|
+
${u}`)}),l.result}),s=i.ips.map(a=>O.vercelIPToUnified(a));return{version:"2.0",provider:"vercel",providers:{vercel:{projectId:this.client.projectId,teamId:this.client.teamId}},rules:r,ips:s,metadata:{version:i.version,updatedAt:i.updatedAt}}}catch(i){throw o.error("Error fetching Vercel configuration:",i),new Error("Failed to fetch Vercel firewall configuration")}}async syncRules(t,i={}){let{dryRun:r=!1}=i;try{let{OperationSafety:s}=($t(),Y(At)),a=await s.performDryRunValidation(t,"sync rules",async g=>await this.getChanges(g,{allowCreate:!r}));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,m=l.ipsToAdd||[],w=l.ipsToUpdate||[],b=l.ipsToDelete||[];if(r)return o.info("Dry run mode. The following changes would be made:"),o.info(`Custom Rules - Add: ${c.length}, Update: ${d.length}, Delete: ${u.length}`),o.info(`IP Rules - Add: ${m.length}, Update: ${w.length}, Delete: ${b.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,version:p,warnings:a.warnings};let R=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Vercel project ${this.client.projectId}`,changes:l,riskLevel:R,skipConfirmation:i.force||!1,dryRun:!1,allowDeletions:i.allowDeletions||!1}))throw new Error("Operation cancelled by user");let J=c.map(g=>O.unifiedToVercel(g).result),ne=d.map(g=>O.unifiedToVercel(g).result),be=u.map(g=>O.unifiedToVercel(g).result),ve=m.map(g=>({id:g.id||"",ip:g.ip,hostname:g.hostname||"",action:g.action,notes:g.notes})),at=w.map(g=>({id:g.id||"",ip:g.ip,hostname:g.hostname||"",action:g.action,notes:g.notes})),S=b.map(g=>({id:g.id||"",ip:g.ip,hostname:g.hostname||"",action:g.action,notes:g.notes})),ze=[],qe=[],Me=[],We=[],Ge=[],Ze=[],ae=[],fe=(g,C)=>`${g}: ${C instanceof Error?C.message:String(C)}`,lt=[];for(let g of be)try{o.debug(`Deleting custom rule: ${g.id}`),await this.client.deleteFirewallRule(g),Me.push(g),o.debug(`Custom rule deleted: ${g.id}`)}catch(C){o.error(`Failed to delete custom rule ${g.id}:`,C),ae.push(fe(`Failed to delete custom rule ${g.id}`,C))}for(let g of S)try{o.debug(`Deleting IP blocking rule: ${g.id}`),await this.client.deleteIPBlockingRule(g),Ze.push(g),o.debug(`IP blocking rule deleted: ${g.id}`)}catch(C){o.error(`Failed to delete IP blocking rule ${g.id}:`,C),ae.push(fe(`Failed to delete IP blocking rule ${g.id}`,C))}for(let g of J)try{o.debug(`Adding new custom rule: ${g.name}`);let C=await this.client.createFirewallRule(g);ze.push(C),C.id&&C.id!==g.id&<.push({oldId:g.id||void 0,newId:C.id,name:g.name}),o.debug(`New custom rule added: ${C.id}`)}catch(C){o.error(`Failed to add custom rule "${g.name}":`,C),ae.push(fe(`Failed to add custom rule "${g.name}"`,C))}for(let g of ve)try{o.debug(`Adding new IP blocking rule: ${g.ip}`);let C=await this.client.createIPBlockingRule(g);We.push(C),o.debug(`New IP blocking rule added: (hostname): ${C.hostname} (ip): ${C.ip}`)}catch(C){o.error(`Failed to add IP blocking rule ${g.ip}:`,C),ae.push(fe(`Failed to add IP blocking rule ${g.ip}`,C))}for(let g of ne)try{o.debug(`Updating custom rule: ${g.id}`);let C=await this.client.updateFirewallRule(g);qe.push(C),o.debug(`Custom rule updated: ${C.id}`)}catch(C){o.error(`Failed to update custom rule ${g.id}:`,C),ae.push(fe(`Failed to update custom rule ${g.id}`,C))}for(let g of at)try{o.debug(`Updating IP blocking rule: ${g.id}`);let C=await this.client.updateIPBlockingRule(g);Ge.push(C),o.debug(`IP blocking rule updated: ${C.id}`)}catch(C){o.error(`Failed to update IP blocking rule ${g.id}:`,C),ae.push(fe(`Failed to update IP blocking rule ${g.id}`,C))}o.debug(`${K.default.underline("Custom Rules:")} ${K.default.green("Added:")} ${K.default.green(ze.length)}, ${K.default.cyan("Updated:")} ${K.default.cyan(qe.length)}, ${K.default.red("Deleted:")} ${K.default.red(Me.length)}`),o.debug(`${K.default.underline("IP Rules:")} ${K.default.green("Added:")} ${K.default.green(We.length)}, ${K.default.cyan("Updated:")} ${K.default.cyan(Ge.length)}, ${K.default.red("Deleted:")} ${K.default.red(Ze.length)}`);let Wt=p,Gt,Ee=[];try{let g=await this.client.fetchFirewallConfig();Wt=g.version,Gt=g.updatedAt;let C=new Set(g.rules.map(D=>D.id)),Zt=new Set(g.ips.map(D=>D.id));for(let D of[...ze,...qe])D.id&&!C.has(D.id)&&Ee.push(`Rule "${D.name}" (${D.id}) was synced but is missing from the post-sync remote config \u2014 a subsequent sync may re-create or misdiff it.`);for(let D of Me)D.id&&C.has(D.id)&&Ee.push(`Rule "${D.name}" (${D.id}) was deleted but still appears in the post-sync remote config.`);for(let D of[...We,...Ge])D.id&&!Zt.has(D.id)&&Ee.push(`IP rule "${D.ip}" (${D.id}) was synced but is missing from the post-sync remote config \u2014 a subsequent sync may re-create or misdiff it.`);for(let D of Ze)D.id&&Zt.has(D.id)&&Ee.push(`IP rule "${D.ip}" (${D.id}) was deleted but still appears in the post-sync remote config.`)}catch(g){o.error("Failed to fetch updated firewall configuration version after sync:",g),ae.push(fe("Failed to fetch updated configuration version after sync",g))}return{success:ae.length===0,rulesAdded:ze.length,rulesUpdated:qe.length,rulesDeleted:Me.length,ipsAdded:We.length,ipsUpdated:Ge.length,ipsDeleted:Ze.length,version:Wt,updatedAt:Gt,idRemappings:lt.length>0?lt:void 0,errors:ae.length>0?ae:void 0,warnings:Ee.length>0?Ee:void 0}}catch(s){throw o.error("Error during sync:",s),new Error(`Failed to synchronize firewall rules: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async getChanges(t,i){let r=Ne.safeParse(t);if(!r.success)throw new Error(`Invalid firewall configuration: ${r.error.message}`);try{o.debug("Fetching existing firewall configuration");let s=await this.client.fetchFirewallConfig(void 0,{allowCreate:i?.allowCreate??!0});o.debug(`Fetched ${s.rules.length} custom rules and ${s.ips.length} IP blocking rules`);let a=s.rules.map(b=>{let R=O.vercelToUnified(b);return R.warnings.length>0&&R.warnings.forEach(x=>{let{TranslationWarningSystem:J}=(X(),Y(ee)),ne=J.formatWarning(x);o.warn(`Rule ${b.name}:
|
|
25
|
+
${ne}`)}),R.result}),{toAdd:l,toUpdate:c,toDelete:d}=this.diffRules(t.rules,a),u=s.ips.map(b=>O.vercelIPToUnified(b)),{ipsToAdd:p,ipsToUpdate:m,ipsToDelete:w}=this.diffIPRules(t.ips||[],u);return{version:s.version,rulesToAdd:l,rulesToUpdate:c,rulesToDelete:d,ipsToAdd:p,ipsToUpdate:m,ipsToDelete:w,hasChanges:l.length>0||c.length>0||d.length>0||p.length>0||m.length>0||w.length>0}}catch(s){throw o.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 i=super.validateConfig(t),r=[...i.errors],s=[...i.warnings];t.provider&&t.provider!=="vercel"&&r.push({path:"provider",message:"Provider must be 'vercel' for VercelFirewallService",code:"INVALID_PROVIDER"});try{let a=pe.safeParse(t);a.success||r.push({path:"root",message:`Schema validation failed: ${a.error.message}`,code:"SCHEMA_VALIDATION_FAILED"})}catch(a){o.debug("Schema validation error:",a)}return{valid:r.length===0,errors:r,warnings:s}}getHealthScore(t){let i=super.getHealthScore(t),r=[...i.issues],s=i.score;return t.rules.filter(l=>l.action?.type==="rate_limit").length===0&&(s-=10,r.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)&&r.push({severity:"info",category:"security",message:"No IP blocking rules configured",suggestion:"Consider blocking known malicious IPs"}),{score:Math.max(0,s),grade:i.grade,issues:r,recommendations:i.recommendations}}diffRules(t,i){let r=[],s=[],a=[...i];for(let l of t){let c=i.find(d=>d.id===l.id);if(!c)r.push(l);else{tt(Be(l),Be(c))||s.push({...l,id:c.id});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{toAdd:r,toUpdate:s,toDelete:a}}diffIPRules(t,i){let r=[],s=[],a=[...i];for(let l of t){let c=i.find(d=>d.id===l.id);if(!c)o.debug("Rule not found in existing rules:",{configRule:l}),r.push(l);else{tt(Be(l),Be(c))||s.push({...c,...l});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{ipsToAdd:r,ipsToUpdate:s,ipsToDelete:a}}};E();var Ue=class{static fromEnv(){let e=process.env.VERCEL_TOKEN,t=process.env.VERCEL_PROJECT_ID,i=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");if(!i)throw new Error("VERCEL_TEAM_ID environment variable is required");let r=new Pe(t,i,e);return new Le(r)}static fromConfig(e){let t=e.token||process.env.VERCEL_TOKEN,i=e.projectId||process.env.VERCEL_PROJECT_ID,r=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(!i)throw new Error("Vercel project ID is required (provide projectId or set VERCEL_PROJECT_ID env var)");if(!r)throw new Error("Vercel team ID is required (provide teamId or set VERCEL_TEAM_ID env var)");o.debug("Creating Vercel provider with config:",{projectId:i,teamId:r});let s=new Pe(i,r,t);return new Le(s)}static create(e,t,i){return this.fromConfig({projectId:e,teamId:t,token:i})}};var Ri=require("crypto");E();var he=P(require("chalk")),f=class n 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,n)}format(){let e=[];return e.push(he.default.red.bold(`[${this.code}] ${this.message}`)),e.push(""),this.suggestion&&(e.push(he.default.yellow.bold("Suggestion:")),e.push(` ${this.suggestion}`),e.push("")),this.details&&Object.keys(this.details).length>0&&(e.push(he.default.dim("Details:")),Object.entries(this.details).forEach(([t,i])=>{let r=typeof i=="object"?JSON.stringify(i,null,2).split(`
|
|
26
26
|
`).join(`
|
|
27
|
-
`):i;e.push(` ${
|
|
27
|
+
`):i;e.push(` ${he.default.cyan(t)}: ${r}`)}),e.push("")),this.cause&&(e.push(he.default.dim("Caused by:")),e.push(` ${this.cause.message}`),e.push("")),this.docsUrl&&(e.push(he.default.cyan.bold("Documentation:")),e.push(` ${this.docsUrl}`),e.push("")),e.join(`
|
|
28
28
|
`)}toPlainText(){let e=[];return e.push(`[${this.code}] ${this.message}`),this.suggestion&&e.push(`Suggestion: ${this.suggestion}`),this.details&&Object.keys(this.details).length>0&&(e.push("Details:"),Object.entries(this.details).forEach(([t,i])=>{e.push(` ${t}: ${i}`)})),this.cause&&e.push(`Caused by: ${this.cause.message}`),this.docsUrl&&e.push(`Documentation: ${this.docsUrl}`),e.join(`
|
|
29
|
-
`)}static isDoormanError(e){return e instanceof n}static from(e,t,i){return n.isDoormanError(e)?e:e instanceof Error?new n({code:t,message:i||e.message,cause:e}):new n({code:t,message:i||String(e)})}};var $="https://docs.doorman.griffen.codes/errors";var j={authFailed:(n,e)=>new f({code:"PROV_5000",message:`Authentication failed for ${n}`,suggestion:"Check that your API credentials are valid and have the correct permissions",details:{provider:n},cause:e,docsUrl:`${$}/PROV_5000`}),apiError:(n,e,t,i)=>new f({code:"PROV_5002",message:`${n} API error: ${t} ${i}`,suggestion:"Check the provider status page and your credentials",details:{provider:n,endpoint:e,statusCode:t,responseMessage:i},docsUrl:`${$}/PROV_5002`}),rateLimit:(n,e)=>new f({code:"PROV_5003",message:`Rate limit exceeded for ${n}`,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:n,retryAfter:e},docsUrl:`${$}/PROV_5003`}),timeout:(n,e)=>new f({code:"PROV_5006",message:`Request timeout for ${n} ${e}`,suggestion:"Check your internet connection and try again",details:{provider:n,operation:e},docsUrl:`${$}/PROV_5006`}),invalidCredentials:(n,e)=>new f({code:"PROV_5004",message:`Missing or invalid credentials for ${n}`,suggestion:`Please provide: ${e.join(", ")}`,details:{provider:n,missing:e},docsUrl:`${$}/PROV_5004`})},x={accountIdRequired:n=>new f({code:"CF_6004",message:`Account ID required for ${n}`,suggestion:"Provide CLOUDFLARE_ACCOUNT_ID in your environment or configuration to use Lists API",details:{operation:n},docsUrl:`${$}/CF_6004`}),zoneIdRequired:n=>new f({code:"CF_6005",message:`Zone ID required for ${n}`,suggestion:"Provide CLOUDFLARE_ZONE_ID in your environment or configuration",details:{operation:n},docsUrl:`${$}/CF_6005`}),invalidCredentials:(n,e)=>new f({code:"CF_6016",message:`Invalid Cloudflare ${n}`,suggestion:"Check your Cloudflare API credentials and ensure they have the correct permissions",details:{credentialType:n,...e},docsUrl:`${$}/CF_6016`}),insufficientPermissions:(n,e)=>new f({code:"CF_6017",message:`Insufficient permissions for ${n}`,suggestion:`Ensure your API token has the following permissions: ${e.join(", ")}`,details:{operation:n,requiredPermissions:e},docsUrl:`${$}/CF_6017`}),ruleLimitExceeded:(n,e)=>new f({code:"CF_6001",message:`Rule count (${n}) exceeds Cloudflare limit (${e})`,suggestion:"Consider consolidating rules, using Lists for IP blocking, or upgrading your Cloudflare plan",details:{count:n,limit:e},docsUrl:`${$}/CF_6001`}),invalidExpression:(n,e)=>new f({code:"CF_6002",message:`Invalid Cloudflare expression: ${e}`,suggestion:"Check Cloudflare Wirefilter expression syntax and field names",details:{expression:n,reason:e},docsUrl:`${$}/CF_6002`}),ruleNoConditions:n=>new f({code:"CF_6007",message:`Rule "${n}" has no conditions`,suggestion:"Add at least one condition to the rule or remove the empty rule",details:{ruleName:n},docsUrl:`${$}/CF_6007`}),invalidRateLimit:(n,e)=>new f({code:"CF_6008",message:`Invalid rate limit configuration for rule "${n}": ${e}`,suggestion:'Rate limit requests must be at least 1, and window format should be like "60s", "1h", "1d"',details:{ruleName:n,issue:e},docsUrl:`${$}/CF_6008`}),invalidWindowFormat:n=>new f({code:"CF_6009",message:`Invalid rate limit window format: ${n}`,suggestion:'Use format like "60s", "5m", "1h", or "1d"',details:{window:n},docsUrl:`${$}/CF_6009`}),shortMitigationTimeout:n=>new f({code:"CF_6010",message:`Mitigation timeout (${n}s) may be too short`,suggestion:"Consider using at least 60 seconds for effective rate limiting",details:{timeout:n},docsUrl:`${$}/CF_6010`}),redirectNoLocation:n=>new f({code:"CF_6011",message:`Redirect rule "${n}" is missing location URL`,suggestion:"Add a redirect.location property with a valid URL or path",details:{ruleName:n},docsUrl:`${$}/CF_6011`}),invalidRedirectUrl:n=>new f({code:"CF_6012",message:`Invalid redirect URL: ${n}`,suggestion:"Use a valid absolute URL (https://...) or relative path (/...)",details:{url:n},docsUrl:`${$}/CF_6012`}),invalidIP:n=>new f({code:"CF_6013",message:`Invalid IP address format: ${n}`,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:n},docsUrl:`${$}/CF_6013`}),largeIPList:n=>new f({code:"CF_6014",message:`Large IP list detected (${n} IPs)`,suggestion:"Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance with large IP lists",details:{count:n},docsUrl:`${$}/CF_6014`}),rulesetNotFound:n=>new f({code:"CF_6000",message:n?`Ruleset not found: ${n}`:"Ruleset not found",suggestion:"The ruleset may have been deleted. Try running the command again to create a new one.",details:{rulesetId:n},docsUrl:`${$}/CF_6000`}),listNotFound:n=>new f({code:"CF_6003",message:n?`List not found: ${n}`:"List not found",suggestion:"The IP list may have been deleted. Try running the command again to create a new one.",details:{listId:n},docsUrl:`${$}/CF_6003`}),emptyCharacteristics:n=>new f({code:"CF_6015",message:`Rate limit rule "${n}" has empty characteristics`,suggestion:'Add characteristics like ["ip.src"] or remove the characteristics array to use default',details:{ruleName:n},docsUrl:`${$}/CF_6015`}),translationWarning:(n,e)=>new f({code:"CF_6018",message:`Translation warning for feature "${n}": ${e}`,suggestion:"Review the translated configuration and adjust if necessary",details:{feature:n,limitation:e},docsUrl:`${$}/CF_6018`}),featureUnsupported:(n,e)=>new f({code:"CF_6019",message:`Feature "${n}" is not supported when migrating from ${e} to Cloudflare`,suggestion:"Remove this feature or implement it using Cloudflare-specific alternatives",details:{feature:n,provider:e},docsUrl:`${$}/CF_6019`}),planLimitExceeded:(n,e,t)=>new f({code:"CF_6020",message:`${n} limit exceeded: ${t}/${e}`,suggestion:"Consider upgrading your Cloudflare plan or reducing resource usage",details:{resource:n,limit:e,current:t},docsUrl:`${$}/CF_6020`}),zoneSuspended:(n,e)=>new f({code:"CF_6021",message:`Zone is suspended: ${n}${e?` (${e})`:""}`,suggestion:"Contact Cloudflare support to resolve zone suspension issues",details:{zoneId:n,reason:e},docsUrl:`${$}/CF_6021`}),maintenanceMode:n=>new f({code:"CF_6022",message:`Cloudflare ${n} is currently in maintenance mode`,suggestion:"Wait for maintenance to complete and try again. Check Cloudflare status page for updates.",details:{service:n,statusPage:"https://www.cloudflarestatus.com/"},docsUrl:`${$}/CF_6022`}),quotaExceeded:(n,e)=>new f({code:"CF_6023",message:`${n} 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:n,resetTime:e},docsUrl:`${$}/CF_6023`}),listsAPIUnavailable:(n,e)=>new f({code:"CF_6004",message:`Lists API unavailable: ${n}`,suggestion:`Falling back to ${e}. To enable Lists API, provide CLOUDFLARE_ACCOUNT_ID and ensure your API token has Account:Read permissions.`,details:{reason:n,fallbackAction:e,severity:"warning"},docsUrl:`${$}/setup#account-id`}),performanceWarning:(n,e,t)=>new f({code:"CF_6014",message:`Performance warning: ${n} with ${e} items`,suggestion:`${t} Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance.`,details:{operation:n,count:e,impact:t,severity:"warning"},docsUrl:`${$}/performance#large-ip-lists`})};var z=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(),i={pattern:null,confidence:0};for(let[r,s]of Object.entries(this.ERROR_PATTERNS)){let l=s.keywords.filter(c=>t.includes(c)).length/s.keywords.length;l>i.confidence&&(i={pattern:r,confidence:l})}return i}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 r={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(r)}static handleCredentialError(e,t){switch(e){case"token":return new f({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 f({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 f({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 f({code:"PROV_5004",message:"Invalid Cloudflare credentials",suggestion:"Check your Cloudflare API credentials",docsUrl:`${this.DOCS_BASE_URL}/setup`})}}static handleValidationError(e,t,i){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 f({code:s.code,message:`Configuration validation failed for ${e}: ${t}`,suggestion:s.suggestion,details:{field:e,issue:t,value:i},docsUrl:s.docsUrl})}static createEnhancedSuggestion(e,t,i){let r=[e];if(i?.pattern&&i.confidence>.5){let l=this.ERROR_PATTERNS[i.pattern];r.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&&r.push(a),r.join(" ")}static formatTranslationWarning(e,t,i){let{TranslationWarningSystem:r}=(Y(),Q(X)),s;try{s=r.createWarning(e,void 0,void 0,i)}catch{s=r.createLossyConversionWarning(e,`${i} (from ${t})`,void 0,void 0)}return r.formatWarning(s)}static handleNetworkError(e,t){let i=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,i);return new f({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,i);return new f({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 r=this.createEnhancedSuggestion("Check your internet connection and try again",t,i);return new f({code:"NET_8004",message:`Network error during ${t}: ${e.message}`,suggestion:r,details:{operation:t,errorContext:i},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 i=parseInt(t[1],10),r=e.toLowerCase().includes("ms")?1:1e3;return i*r}}static handleGracefulDegradation(e,t,i,r){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 f({code:a.code,message:`Feature degradation: ${e} - ${t}`,suggestion:`${a.suggestion} Fallback: ${i}${r?` Impact: ${r}`:""}`,details:{feature:e,reason:t,fallbackAction:i,impact:r,degradationType:"graceful"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#feature-degradation`})}static createUserFriendlyMessage(e,t,i){let r=`Failed to ${e}`,s=i?` (${Object.entries(i).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`${r}${s}. ${l}`}static handleBadRequestError(e){return e.message.includes("expression")?new f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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`})}}};E();var So={defaultTTL:300*1e3,maxEntries:100,enableLogging:!0},He=class{cache=new Map;options;stats={hits:0,misses:0,evictions:0};constructor(e={}){this.options={...So,...e}}get(e){let t=this.cache.get(e);if(!t){this.stats.misses++,this.options.enableLogging&&o.debug(`Cache miss: ${e}`);return}if(Date.now()>t.expiresAt){this.cache.delete(e),this.stats.misses++,this.options.enableLogging&&o.debug(`Cache expired: ${e}`);return}return t.hits++,this.stats.hits++,this.options.enableLogging&&o.debug(`Cache hit: ${e} (${t.hits} total hits)`),t.value}set(e,t,i){this.cache.size>=this.options.maxEntries&&!this.cache.has(e)&&this.evictLeastRecentlyUsed();let r=i??this.options.defaultTTL;this.cache.set(e,{value:t,expiresAt:Date.now()+r,createdAt:Date.now(),hits:0}),this.options.enableLogging&&o.debug(`Cache set: ${e} (TTL: ${r}ms)`)}invalidate(e){let t=this.cache.delete(e);return t&&this.options.enableLogging&&o.debug(`Cache invalidated: ${e}`),t}invalidateByPrefix(e){let t=0;for(let i of this.cache.keys())i.startsWith(e)&&(this.cache.delete(i),t++);return t>0&&this.options.enableLogging&&o.debug(`Cache invalidated ${t} entries with prefix: ${e}`),t}clear(){let e=this.cache.size;this.cache.clear(),this.options.enableLogging&&o.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[i,r]of this.cache.entries()){if(Date.now()>r.expiresAt){this.cache.delete(i),this.stats.evictions++;return}(!t||r.hits<t.hits||r.hits===t.hits&&r.createdAt<t.createdAt)&&(e=i,t=r)}e&&(this.cache.delete(e),this.stats.evictions++,this.options.enableLogging&&o.debug(`Cache evicted LRU entry: ${e}`))}},he={zoneInfo:n=>`zone:${n}:info`,rulesets:n=>`zone:${n}:rulesets`,ruleset:(n,e)=>`zone:${n}:ruleset:${e}`,lists:n=>`account:${n}:lists`,listItems:(n,e)=>`account:${n}:list:${e}:items`,credentialValidation:n=>`cred:${n}`,configValidation:n=>`config:${n}`},ye={ZONE_INFO:600*1e3,RULESETS:120*1e3,RULESET:60*1e3,LISTS:300*1e3,LIST_ITEMS:120*1e3,CREDENTIALS:900*1e3,CONFIG_VALIDATION:300*1e3};E();var Lo={maxConnections:6,idleTimeout:3e4,keepAlive:!0},Uo={ttl:5e3,maxEntries:100},we=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={...Lo,...e},this.dedupOptions={...Uo,...t}}computeRuleHash(e){let t=this.canonicalizeRule(e),i=this.hashCache.get(t);if(i)return i;let r=this.simpleHash(t);return this.hashCache.set(t,r),r}diffRules(e,t){let i=performance.now();if(this.stats.diffOperations++,e.length===0&&t.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-i};if(e===t)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:e.length,duration:performance.now()-i};if(e.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[...t],unchanged:0,duration:performance.now()-i};if(t.length===0)return this.stats.earlyExits++,{toAdd:[...e],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-i};let r=new Map;for(let p of t){let m=p.id||p.name;r.set(m,{rule:p,hash:this.computeRuleHash(p)})}let s=new Map,a=[],l=[],c=0;for(let p of e){let m=p.id||p.name;s.set(m,!0);let w=r.get(m);w?this.computeRuleHash(p)!==w.hash?l.push(p):c++:a.push(p)}let d=[];for(let[p,m]of r)s.has(p)||d.push(m.rule);let u=performance.now()-i;return this.stats.diffTotalDuration+=u,o.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 i=new Map(t.map(c=>[c.id,c])),r=new Set,s=[],a=[];for(let{rule:c,translated:d}of e){let u=c.id||c.name;r.add(u);let p=i.get(u);p?this.cloudflareRulesEqual(d,p)||a.push(c):s.push(c)}let l=[];for(let[c,d]of i)r.has(c)||l.push(d);return{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 i=performance.now();if(e.length===0&&t.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-i};if(e.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[...t],unchanged:0,duration:performance.now()-i};if(t.length===0)return this.stats.earlyExits++,{toAdd:[...e],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-i};let r=new Map;for(let p of t)r.set(p.ip,p);let s=new Set,a=[],l=[],c=0;for(let p of e){s.add(p.ip);let m=r.get(p.ip);m?p.action!==m.action?l.push(p):c++:a.push(p)}let d=[];for(let[p,m]of r)s.has(p)||d.push(m);let u=performance.now()-i;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),i=[];for(let r=0;r<e.length;r++){let s=r,a=e[s],l=this.withConnection(async()=>{t[s]=await a()});i.push(l)}return await Promise.all(i),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 i=this.inFlightRequests.get(e);if(i&&Date.now()-i.createdAt<this.dedupOptions.ttl)return this.stats.deduplicatedRequests++,o.debug(`Request deduplicated: ${e}`),i.promise;let r=t().finally(()=>{this.inFlightRequests.delete(e)});return this.inFlightRequests.set(e,{promise:r,createdAt:Date.now()}),r}static requestKey(e,t,i){let r=[e.toUpperCase(),t];return i&&r.push(i),r.join(":")}cleanupExpiredRequests(){let e=Date.now();for(let[t,i]of this.inFlightRequests)e-i.createdAt>this.dedupOptions.ttl&&this.inFlightRequests.delete(t);if(this.inFlightRequests.size>this.dedupOptions.maxEntries){let t=Array.from(this.inFlightRequests.entries());t.sort((r,s)=>r[1].createdAt-s[1].createdAt);let i=t.slice(0,t.length-this.dedupOptions.maxEntries);for(let[r]of i)this.inFlightRequests.delete(r)}}async processInChunks(e,t,i){if(e.length===0)return[];this.stats.chunkedOperations++;let r=[],s=Math.ceil(e.length/t);e.length>t&&o.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 i(l,c);r.push(...d)}return r}estimateMemoryUsage(e){if(e.length===0)return 0;let t=Math.min(10,e.length),i=0;for(let s=0;s<t;s++)i+=JSON.stringify(e[s]).length*2;let r=i/t;return Math.ceil(r*e.length)}getOptimalChunkSize(e,t=500){let r=Math.max(10,Math.floor(1048576/t)),s=Math.min(r,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(i=>({field:i.field,key:i.key,negated:i.negated,operator:i.operator,value:i.value})).sort((i,r)=>`${i.field}:${i.operator}`.localeCompare(`${r.field}:${r.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 i=0;i<e.length;i++)t=(t<<5)+t+e.charCodeAt(i)|0;return t.toString(36)}};var Le=class extends Ae{apiToken;zoneId;accountId;cache;optimizer;constructor(e,t,i){super("https://api.cloudflare.com/client/v4","cloudflare"),this.apiToken=e,this.zoneId=t,this.accountId=i,this.cache=new He({enableLogging:!0}),this.optimizer=new we}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}invalidateRulesetCache(){this.cache.invalidateByPrefix(`zone:${this.zoneId}`)}invalidateListCache(){this.accountId&&this.cache.invalidateByPrefix(`account:${this.accountId}`)}getAuthHeaders(){return{Authorization:`Bearer ${this.apiToken}`,...this.optimizer.getConnectionHeaders()}}getOptimizer(){return this.optimizer}async listRulesets(){o.debug(`Fetching rulesets for zone ${this.zoneId}`);let e=he.rulesets(this.zoneId),t=this.cache.get(e);if(t)return t;let i=we.requestKey("GET",`/zones/${this.zoneId}/rulesets`);return this.optimizer.deduplicateRequest(i,async()=>{try{let r=await this.get(`/zones/${this.zoneId}/rulesets`);if(!r.success)throw z.handleApiResponse(r,`/zones/${this.zoneId}/rulesets`);if(!Array.isArray(r.result))return o.warn("Malformed API response: expected array of rulesets, got:",typeof r.result),[];let s=r.result.filter(a=>!a||typeof a!="object"?(o.warn("Skipping malformed ruleset object:",a),!1):!a.id||!a.name?(o.warn("Skipping ruleset with missing required fields:",{id:a.id,name:a.name}),!1):!0);return s.length!==r.result.length&&o.warn(`Filtered out ${r.result.length-s.length} malformed rulesets`),this.cache.set(e,s,ye.RULESETS),s}catch(r){throw r instanceof Error&&!r.code?z.handleNetworkError(r,"listing rulesets"):r}})}async getRulesets(){return this.listRulesets()}async getRuleset(e){o.debug(`Fetching ruleset ${e}`);let t=he.ruleset(this.zoneId,e),i=this.cache.get(t);if(i)return i;let r=we.requestKey("GET",`/zones/${this.zoneId}/rulesets/${e}`);return this.optimizer.deduplicateRequest(r,async()=>{try{let s=await this.get(`/zones/${this.zoneId}/rulesets/${e}`);if(!s.success)throw z.handleApiResponse(s,`/zones/${this.zoneId}/rulesets/${e}`);if(!s.result||typeof s.result!="object")throw z.handleValidationError("ruleset","Invalid ruleset data received from API",s.result);let a=s.result;if(!a.id||!a.name)throw z.handleValidationError("ruleset","Ruleset missing required fields (id, name)",a);Array.isArray(a.rules)||(o.warn(`Ruleset ${e} has invalid rules array, initializing as empty`),a.rules=[]);let l=a.rules.filter(c=>!c||typeof c!="object"?(o.warn(`Skipping malformed rule in ruleset ${e}:`,c),!1):!c.id||!c.expression||!c.action?(o.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&&(o.warn(`Filtered out ${a.rules.length-l.length} malformed rules from ruleset ${e}`),a.rules=l),this.cache.set(t,a,ye.RULESET),a}catch(s){throw s instanceof Error&&!s.code?z.handleNetworkError(s,"fetching ruleset"):s}})}async createRuleset(e){o.debug(`Creating ruleset: ${e.name}`);let t=await this.post(`/zones/${this.zoneId}/rulesets`,e);if(!t.success){let i=t.errors.map(r=>r.message).join(", ");throw j.apiError("cloudflare",`/zones/${this.zoneId}/rulesets`,t.errors[0]?.code||0,i)}return o.info(`Created ruleset: ${t.result.name} (${t.result.id})`),this.invalidateRulesetCache(),t.result}async updateRuleset(e,t){o.debug(`Updating ruleset ${e}`);let i=await this.put(`/zones/${this.zoneId}/rulesets/${e}`,t);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw j.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}`,i.errors[0]?.code||0,r)}return o.info(`Updated ruleset to version ${i.result.version}`),this.invalidateRulesetCache(),i.result}async deleteRuleset(e){o.debug(`Deleting ruleset ${e}`);let t=await this.delete(`/zones/${this.zoneId}/rulesets/${e}`);if(!t.success){let i=t.errors.map(r=>r.message).join(", ");throw j.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}`,t.errors[0]?.code||0,i)}o.info(`Deleted ruleset ${e}`),this.invalidateRulesetCache()}async createRule(e,t){o.debug(`Adding rule to ruleset ${e}`);let i=await this.post(`/zones/${this.zoneId}/rulesets/${e}/rules`,t);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw j.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules`,i.errors[0]?.code||0,r)}return o.info(`Added rule to ruleset ${e}`),this.invalidateRulesetCache(),i.result}async updateRule(e,t,i){o.debug(`Updating rule ${t} in ruleset ${e}`);let r=await this.patch(`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,i);if(!r.success){let s=r.errors.map(a=>a.message).join(", ");throw j.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,r.errors[0]?.code||0,s)}return o.info(`Updated rule ${t}`),this.invalidateRulesetCache(),r.result}async deleteRule(e,t){o.debug(`Deleting rule ${t} from ruleset ${e}`);let i=await this.delete(`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw j.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,i.errors[0]?.code||0,r)}return o.info(`Deleted rule ${t}`),this.invalidateRulesetCache(),i.result}async getOrCreateFirewallRuleset(){o.debug("Looking for existing custom firewall ruleset");let t=(await this.listRulesets()).find(i=>i.kind==="custom"&&i.phase==="http_request_firewall_custom");return t?(o.debug(`Found existing ruleset: ${t.id}`),t):(o.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,wi.createHash)("sha256").update(this.apiToken).digest("hex").slice(0,8),t=he.credentialValidation(e),i=this.cache.get(t);if(i!==void 0)return o.debug("Using cached credential validation result"),i;try{return o.debug("Verifying Cloudflare credentials"),await this.listRulesets(),o.info("Cloudflare credentials verified successfully"),this.cache.set(t,!0,ye.CREDENTIALS),!0}catch(r){if(o.error(`Cloudflare credential verification failed: ${r}`),r instanceof Error){let s=r.message.toLowerCase();if(s.includes("unauthorized")||s.includes("invalid token"))throw z.handleCredentialError("token");if(s.includes("forbidden")||s.includes("access denied"))throw z.handleCredentialError("zone",this.zoneId);if(s.includes("not found"))throw z.handleCredentialError("zone",this.zoneId)}return!1}}async getZoneInfo(){let e=he.zoneInfo(this.zoneId),t=this.cache.get(e);if(t)return t;let i=await this.get(`/zones/${this.zoneId}`);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw j.apiError("cloudflare",`/zones/${this.zoneId}`,i.errors[0]?.code||0,r)}return this.cache.set(e,i.result,ye.ZONE_INFO),i.result}async listLists(){if(o.debug("Fetching Cloudflare Lists"),!this.accountId)return o.warn("Account ID not provided, Lists API requires account-level access"),[];let e=he.lists(this.accountId),t=this.cache.get(e);if(t)return t;let i=await this.get(`/accounts/${this.accountId}/rules/lists`);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw j.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,i.errors[0]?.code||0,r)}return this.cache.set(e,i.result,ye.LISTS),i.result}async getList(e){if(o.debug(`Fetching List ${e}`),!this.accountId)throw x.accountIdRequired("Lists API");let t=await this.get(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let i=t.errors.map(r=>r.message).join(", ");throw j.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,t.errors[0]?.code||0,i)}return t.result}async createList(e){if(o.debug(`Creating List: ${e.name}`),!this.accountId)throw x.accountIdRequired("Lists API");let t=await this.post(`/accounts/${this.accountId}/rules/lists`,e);if(!t.success){let i=t.errors.map(r=>r.message).join(", ");throw j.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,t.errors[0]?.code||0,i)}return o.info(`Created List: ${t.result.name} (${t.result.id})`),this.invalidateListCache(),t.result}async updateList(e,t){if(o.debug(`Updating List ${e}`),!this.accountId)throw x.accountIdRequired("Lists API");let i=await this.put(`/accounts/${this.accountId}/rules/lists/${e}`,t);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw j.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,i.errors[0]?.code||0,r)}return o.info(`Updated List ${e}`),this.invalidateListCache(),i.result}async deleteList(e){if(o.debug(`Deleting List ${e}`),!this.accountId)throw x.accountIdRequired("Lists API");let t=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let i=t.errors.map(r=>r.message).join(", ");throw j.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,t.errors[0]?.code||0,i)}o.info(`Deleted List ${e}`),this.invalidateListCache()}async getListItems(e){if(o.debug(`Fetching items from List ${e}`),!this.accountId)throw x.accountIdRequired("Lists API");let t=he.listItems(this.accountId,e),i=this.cache.get(t);if(i)return i;let r=we.requestKey("GET",`/accounts/${this.accountId}/rules/lists/${e}/items`);return this.optimizer.deduplicateRequest(r,async()=>{let s=await this.fetchAllListItemPages(e);return this.cache.set(t,s,ye.LIST_ITEMS),s})}async fetchAllListItemPages(e){let t=[],i=1;for(;;){let r=await this.get(`/accounts/${this.accountId}/rules/lists/${e}/items?page=${i}`);if(!r.success){let a=r.errors.map(l=>l.message).join(", ");throw j.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,r.errors[0]?.code||0,a)}t.push(...r.result);let s=r.result_info?.total_pages??1;if(r.result.length===0||i>=s)break;i++}return t}async addListItems(e,t){if(o.debug(`Adding ${t.items.length} items to List ${e}`),!this.accountId)throw x.accountIdRequired("Lists API");let i=await this.post(`/accounts/${this.accountId}/rules/lists/${e}/items`,t.items);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw j.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,i.errors[0]?.code||0,r)}return o.info(`Added ${t.items.length} items to List ${e}`),this.invalidateListCache(),i.result}async removeListItems(e,t){if(o.debug(`Removing ${t.items.length} items from List ${e}`),!this.accountId)throw x.accountIdRequired("Lists API");let i=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}/items`,{body:JSON.stringify(t)});if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw j.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,i.errors[0]?.code||0,r)}o.info(`Removed ${t.items.length} items from List ${e}`),this.invalidateListCache()}async getOrCreateIPBlocklist(){if(o.debug("Looking for existing Doorman IP blocklist"),!this.accountId)throw o.warn("Account ID not provided, cannot use Lists for IP blocking"),z.handleCredentialError("account");try{let t=(await this.listLists()).find(i=>i.name==="Doorman IP Blocklist"&&i.kind==="ip");return t?(o.debug(`Found existing IP blocklist: ${t.id}`),t):(o.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?z.handleNetworkError(e,"managing IP blocklist"):e}}};var Ue=require("net");E();var Fe=class n extends $e{name="cloudflare";client;optimizer;useListsForIPs;constructor(e,t,i){super(),this.client=new Le(e,t,i),this.optimizer=this.client.getOptimizer(),this.useListsForIPs=!!i,this.useListsForIPs?o.debug("Lists API enabled for IP blocking (account ID provided)"):o.debug("Lists API disabled - will use individual IP rules (no account ID)")}async fetchConfig(e){o.info("Fetching configuration from Cloudflare");try{let t=await this.client.getOrCreateFirewallRuleset(),i=[],r=[],s=[],a=[],l=50,c=t.rules.length;c>100&&o.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);o.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 m=this.cloudflareRuleToIPRule(p);r.push(m)}else{let m=D.cloudflareToUnified(p);i.push(m.result),m.warnings.length>0&&m.warnings.forEach(w=>{let{TranslationWarningSystem:C}=(Y(),Q(X)),R=C.formatWarning(w);s.push(R)})}}catch(m){let w=`Failed to process rule ${p?.id||"unknown"}: ${m instanceof Error?m.message:String(m)}`;o.warn(w),a.push(w)}c>200&&d+l<c&&await new Promise(p=>setTimeout(p,10))}if(a.length>0&&(o.warn(`Encountered ${a.length} rule processing errors:`),a.slice(0,5).forEach(d=>o.warn(` - ${d}`)),a.length>5&&o.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&&r.push({id:p.id,ip:p.ip,notes:p.comment,action:"deny"});o.debug(`Fetched ${u.length} IPs from List`)}catch(d){this.handleListsAPIFallback(d,"fetching IPs from List")}else r.length>10&&o.warn(`\u26A0\uFE0F Large IP list detected (${r.length} IPs) without Lists API. Consider providing CLOUDFLARE_ACCOUNT_ID for better performance.`);return s.length>0&&(o.warn("Translation warnings detected:"),s.forEach(d=>o.warn(d)),s.length>3&&o.warn(`
|
|
30
|
-
\u{1F4CA} Summary: ${s.length} translation warnings detected. Review each warning above for specific guidance.`)),{version:"2.0",provider:"cloudflare",providers:{cloudflare:{zoneId:this.client.zoneId,accountId:this.client.accountId}},rules:i,ips:r,metadata:{version:parseInt(t.version,10),updatedAt:t.last_updated}}}catch(t){throw t instanceof Error&&!("code"in t)?
|
|
29
|
+
`)}static isDoormanError(e){return e instanceof n}static from(e,t,i){return n.isDoormanError(e)?e:e instanceof Error?new n({code:t,message:i||e.message,cause:e}):new n({code:t,message:i||String(e)})}};var T="https://docs.doorman.griffen.codes/errors";var z={authFailed:(n,e)=>new f({code:"PROV_5000",message:`Authentication failed for ${n}`,suggestion:"Check that your API credentials are valid and have the correct permissions",details:{provider:n},cause:e,docsUrl:`${T}/PROV_5000`}),apiError:(n,e,t,i)=>new f({code:"PROV_5002",message:`${n} API error: ${t} ${i}`,suggestion:"Check the provider status page and your credentials",details:{provider:n,endpoint:e,statusCode:t,responseMessage:i},docsUrl:`${T}/PROV_5002`}),rateLimit:(n,e)=>new f({code:"PROV_5003",message:`Rate limit exceeded for ${n}`,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:n,retryAfter:e},docsUrl:`${T}/PROV_5003`}),timeout:(n,e)=>new f({code:"PROV_5006",message:`Request timeout for ${n} ${e}`,suggestion:"Check your internet connection and try again",details:{provider:n,operation:e},docsUrl:`${T}/PROV_5006`}),invalidCredentials:(n,e)=>new f({code:"PROV_5004",message:`Missing or invalid credentials for ${n}`,suggestion:`Please provide: ${e.join(", ")}`,details:{provider:n,missing:e},docsUrl:`${T}/PROV_5004`})},N={accountIdRequired:n=>new f({code:"CF_6004",message:`Account ID required for ${n}`,suggestion:"Provide CLOUDFLARE_ACCOUNT_ID in your environment or configuration to use Lists API",details:{operation:n},docsUrl:`${T}/CF_6004`}),zoneIdRequired:n=>new f({code:"CF_6005",message:`Zone ID required for ${n}`,suggestion:"Provide CLOUDFLARE_ZONE_ID in your environment or configuration",details:{operation:n},docsUrl:`${T}/CF_6005`}),invalidCredentials:(n,e)=>new f({code:"CF_6016",message:`Invalid Cloudflare ${n}`,suggestion:"Check your Cloudflare API credentials and ensure they have the correct permissions",details:{credentialType:n,...e},docsUrl:`${T}/CF_6016`}),insufficientPermissions:(n,e)=>new f({code:"CF_6017",message:`Insufficient permissions for ${n}`,suggestion:`Ensure your API token has the following permissions: ${e.join(", ")}`,details:{operation:n,requiredPermissions:e},docsUrl:`${T}/CF_6017`}),ruleLimitExceeded:(n,e)=>new f({code:"CF_6001",message:`Rule count (${n}) exceeds Cloudflare limit (${e})`,suggestion:"Consider consolidating rules, using Lists for IP blocking, or upgrading your Cloudflare plan",details:{count:n,limit:e},docsUrl:`${T}/CF_6001`}),invalidExpression:(n,e)=>new f({code:"CF_6002",message:`Invalid Cloudflare expression: ${e}`,suggestion:"Check Cloudflare Wirefilter expression syntax and field names",details:{expression:n,reason:e},docsUrl:`${T}/CF_6002`}),ruleNoConditions:n=>new f({code:"CF_6007",message:`Rule "${n}" has no conditions`,suggestion:"Add at least one condition to the rule or remove the empty rule",details:{ruleName:n},docsUrl:`${T}/CF_6007`}),invalidRateLimit:(n,e)=>new f({code:"CF_6008",message:`Invalid rate limit configuration for rule "${n}": ${e}`,suggestion:'Rate limit requests must be at least 1, and window format should be like "60s", "1h", "1d"',details:{ruleName:n,issue:e},docsUrl:`${T}/CF_6008`}),invalidWindowFormat:n=>new f({code:"CF_6009",message:`Invalid rate limit window format: ${n}`,suggestion:'Use format like "60s", "5m", "1h", or "1d"',details:{window:n},docsUrl:`${T}/CF_6009`}),shortMitigationTimeout:n=>new f({code:"CF_6010",message:`Mitigation timeout (${n}s) may be too short`,suggestion:"Consider using at least 60 seconds for effective rate limiting",details:{timeout:n},docsUrl:`${T}/CF_6010`}),redirectNoLocation:n=>new f({code:"CF_6011",message:`Redirect rule "${n}" is missing location URL`,suggestion:"Add a redirect.location property with a valid URL or path",details:{ruleName:n},docsUrl:`${T}/CF_6011`}),invalidRedirectUrl:n=>new f({code:"CF_6012",message:`Invalid redirect URL: ${n}`,suggestion:"Use a valid absolute URL (https://...) or relative path (/...)",details:{url:n},docsUrl:`${T}/CF_6012`}),invalidIP:n=>new f({code:"CF_6013",message:`Invalid IP address format: ${n}`,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:n},docsUrl:`${T}/CF_6013`}),largeIPList:n=>new f({code:"CF_6014",message:`Large IP list detected (${n} IPs)`,suggestion:"Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance with large IP lists",details:{count:n},docsUrl:`${T}/CF_6014`}),rulesetNotFound:n=>new f({code:"CF_6000",message:n?`Ruleset not found: ${n}`:"Ruleset not found",suggestion:"The ruleset may have been deleted. Try running the command again to create a new one.",details:{rulesetId:n},docsUrl:`${T}/CF_6000`}),listNotFound:n=>new f({code:"CF_6003",message:n?`List not found: ${n}`:"List not found",suggestion:"The IP list may have been deleted. Try running the command again to create a new one.",details:{listId:n},docsUrl:`${T}/CF_6003`}),emptyCharacteristics:n=>new f({code:"CF_6015",message:`Rate limit rule "${n}" has empty characteristics`,suggestion:'Add characteristics like ["ip.src"] or remove the characteristics array to use default',details:{ruleName:n},docsUrl:`${T}/CF_6015`}),translationWarning:(n,e)=>new f({code:"CF_6018",message:`Translation warning for feature "${n}": ${e}`,suggestion:"Review the translated configuration and adjust if necessary",details:{feature:n,limitation:e},docsUrl:`${T}/CF_6018`}),featureUnsupported:(n,e)=>new f({code:"CF_6019",message:`Feature "${n}" is not supported when migrating from ${e} to Cloudflare`,suggestion:"Remove this feature or implement it using Cloudflare-specific alternatives",details:{feature:n,provider:e},docsUrl:`${T}/CF_6019`}),planLimitExceeded:(n,e,t)=>new f({code:"CF_6020",message:`${n} limit exceeded: ${t}/${e}`,suggestion:"Consider upgrading your Cloudflare plan or reducing resource usage",details:{resource:n,limit:e,current:t},docsUrl:`${T}/CF_6020`}),zoneSuspended:(n,e)=>new f({code:"CF_6021",message:`Zone is suspended: ${n}${e?` (${e})`:""}`,suggestion:"Contact Cloudflare support to resolve zone suspension issues",details:{zoneId:n,reason:e},docsUrl:`${T}/CF_6021`}),maintenanceMode:n=>new f({code:"CF_6022",message:`Cloudflare ${n} is currently in maintenance mode`,suggestion:"Wait for maintenance to complete and try again. Check Cloudflare status page for updates.",details:{service:n,statusPage:"https://www.cloudflarestatus.com/"},docsUrl:`${T}/CF_6022`}),quotaExceeded:(n,e)=>new f({code:"CF_6023",message:`${n} 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:n,resetTime:e},docsUrl:`${T}/CF_6023`}),listsAPIUnavailable:(n,e)=>new f({code:"CF_6004",message:`Lists API unavailable: ${n}`,suggestion:`Falling back to ${e}. To enable Lists API, provide CLOUDFLARE_ACCOUNT_ID and ensure your API token has Account:Read permissions.`,details:{reason:n,fallbackAction:e,severity:"warning"},docsUrl:`${T}/setup#account-id`}),performanceWarning:(n,e,t)=>new f({code:"CF_6014",message:`Performance warning: ${n} with ${e} items`,suggestion:`${t} Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance.`,details:{operation:n,count:e,impact:t,severity:"warning"},docsUrl:`${T}/performance#large-ip-lists`})};var q=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(),i={pattern:null,confidence:0};for(let[r,s]of Object.entries(this.ERROR_PATTERNS)){let l=s.keywords.filter(c=>t.includes(c)).length/s.keywords.length;l>i.confidence&&(i={pattern:r,confidence:l})}return i}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 r={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(r)}static handleCredentialError(e,t){switch(e){case"token":return new f({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 f({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 f({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 f({code:"PROV_5004",message:"Invalid Cloudflare credentials",suggestion:"Check your Cloudflare API credentials",docsUrl:`${this.DOCS_BASE_URL}/setup`})}}static handleValidationError(e,t,i){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 f({code:s.code,message:`Configuration validation failed for ${e}: ${t}`,suggestion:s.suggestion,details:{field:e,issue:t,value:i},docsUrl:s.docsUrl})}static createEnhancedSuggestion(e,t,i){let r=[e];if(i?.pattern&&i.confidence>.5){let l=this.ERROR_PATTERNS[i.pattern];r.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&&r.push(a),r.join(" ")}static formatTranslationWarning(e,t,i){let{TranslationWarningSystem:r}=(X(),Y(ee)),s;try{s=r.createWarning(e,void 0,void 0,i)}catch{s=r.createLossyConversionWarning(e,`${i} (from ${t})`,void 0,void 0)}return r.formatWarning(s)}static handleNetworkError(e,t){let i=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,i);return new f({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,i);return new f({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 r=this.createEnhancedSuggestion("Check your internet connection and try again",t,i);return new f({code:"NET_8004",message:`Network error during ${t}: ${e.message}`,suggestion:r,details:{operation:t,errorContext:i},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 i=parseInt(t[1],10),r=e.toLowerCase().includes("ms")?1:1e3;return i*r}}static handleGracefulDegradation(e,t,i,r){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 f({code:a.code,message:`Feature degradation: ${e} - ${t}`,suggestion:`${a.suggestion} Fallback: ${i}${r?` Impact: ${r}`:""}`,details:{feature:e,reason:t,fallbackAction:i,impact:r,degradationType:"graceful"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#feature-degradation`})}static createUserFriendlyMessage(e,t,i){let r=`Failed to ${e}`,s=i?` (${Object.entries(i).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`${r}${s}. ${l}`}static handleBadRequestError(e){return e.message.includes("expression")?new f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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 f({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`})}}};E();var Do={defaultTTL:300*1e3,maxEntries:100,enableLogging:!0},ot=class{cache=new Map;options;stats={hits:0,misses:0,evictions:0};constructor(e={}){this.options={...Do,...e}}get(e){let t=this.cache.get(e);if(!t){this.stats.misses++,this.options.enableLogging&&o.debug(`Cache miss: ${e}`);return}if(Date.now()>t.expiresAt){this.cache.delete(e),this.stats.misses++,this.options.enableLogging&&o.debug(`Cache expired: ${e}`);return}return t.hits++,this.stats.hits++,this.options.enableLogging&&o.debug(`Cache hit: ${e} (${t.hits} total hits)`),t.value}set(e,t,i){this.cache.size>=this.options.maxEntries&&!this.cache.has(e)&&this.evictLeastRecentlyUsed();let r=i??this.options.defaultTTL;this.cache.set(e,{value:t,expiresAt:Date.now()+r,createdAt:Date.now(),hits:0}),this.options.enableLogging&&o.debug(`Cache set: ${e} (TTL: ${r}ms)`)}invalidate(e){let t=this.cache.delete(e);return t&&this.options.enableLogging&&o.debug(`Cache invalidated: ${e}`),t}invalidateByPrefix(e){let t=0;for(let i of this.cache.keys())i.startsWith(e)&&(this.cache.delete(i),t++);return t>0&&this.options.enableLogging&&o.debug(`Cache invalidated ${t} entries with prefix: ${e}`),t}clear(){let e=this.cache.size;this.cache.clear(),this.options.enableLogging&&o.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[i,r]of this.cache.entries()){if(Date.now()>r.expiresAt){this.cache.delete(i),this.stats.evictions++;return}(!t||r.hits<t.hits||r.hits===t.hits&&r.createdAt<t.createdAt)&&(e=i,t=r)}e&&(this.cache.delete(e),this.stats.evictions++,this.options.enableLogging&&o.debug(`Cache evicted LRU entry: ${e}`))}},ye={zoneInfo:n=>`zone:${n}:info`,rulesets:n=>`zone:${n}:rulesets`,ruleset:(n,e)=>`zone:${n}:ruleset:${e}`,lists:n=>`account:${n}:lists`,listItems:(n,e)=>`account:${n}:list:${e}:items`,credentialValidation:n=>`cred:${n}`,configValidation:n=>`config:${n}`},we={ZONE_INFO:600*1e3,RULESETS:120*1e3,RULESET:60*1e3,LISTS:300*1e3,LIST_ITEMS:120*1e3,CREDENTIALS:900*1e3,CONFIG_VALIDATION:300*1e3};E();var Oo={maxConnections:6,idleTimeout:3e4,keepAlive:!0},xo={ttl:5e3,maxEntries:100},Ie=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={...Oo,...e},this.dedupOptions={...xo,...t}}computeRuleHash(e){let t=this.canonicalizeRule(e),i=this.hashCache.get(t);if(i)return i;let r=this.simpleHash(t);return this.hashCache.set(t,r),r}diffRules(e,t){let i=performance.now();if(this.stats.diffOperations++,e.length===0&&t.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-i};if(e===t)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:e.length,duration:performance.now()-i};if(e.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[...t],unchanged:0,duration:performance.now()-i};if(t.length===0)return this.stats.earlyExits++,{toAdd:[...e],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-i};let r=new Map;for(let p of t){let m=p.id||p.name;r.set(m,{rule:p,hash:this.computeRuleHash(p)})}let s=new Map,a=[],l=[],c=0;for(let p of e){let m=p.id||p.name;s.set(m,!0);let w=r.get(m);w?this.computeRuleHash(p)!==w.hash?l.push(p):c++:a.push(p)}let d=[];for(let[p,m]of r)s.has(p)||d.push(m.rule);let u=performance.now()-i;return this.stats.diffTotalDuration+=u,o.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 i=new Map(t.map(c=>[c.id,c])),r=new Set,s=[],a=[];for(let{rule:c,translated:d}of e){let u=c.id||c.name;r.add(u);let p=i.get(u);p?this.cloudflareRulesEqual(d,p)||a.push(c):s.push(c)}let l=[];for(let[c,d]of i)r.has(c)||l.push(d);return{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 i=performance.now();if(e.length===0&&t.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-i};if(e.length===0)return this.stats.earlyExits++,{toAdd:[],toUpdate:[],toDelete:[...t],unchanged:0,duration:performance.now()-i};if(t.length===0)return this.stats.earlyExits++,{toAdd:[...e],toUpdate:[],toDelete:[],unchanged:0,duration:performance.now()-i};let r=new Map;for(let p of t)r.set(p.ip,p);let s=new Set,a=[],l=[],c=0;for(let p of e){s.add(p.ip);let m=r.get(p.ip);m?p.action!==m.action?l.push(p):c++:a.push(p)}let d=[];for(let[p,m]of r)s.has(p)||d.push(m);let u=performance.now()-i;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),i=[];for(let r=0;r<e.length;r++){let s=r,a=e[s],l=this.withConnection(async()=>{t[s]=await a()});i.push(l)}return await Promise.all(i),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 i=this.inFlightRequests.get(e);if(i&&Date.now()-i.createdAt<this.dedupOptions.ttl)return this.stats.deduplicatedRequests++,o.debug(`Request deduplicated: ${e}`),i.promise;let r=t().finally(()=>{this.inFlightRequests.delete(e)});return this.inFlightRequests.set(e,{promise:r,createdAt:Date.now()}),r}static requestKey(e,t,i){let r=[e.toUpperCase(),t];return i&&r.push(i),r.join(":")}cleanupExpiredRequests(){let e=Date.now();for(let[t,i]of this.inFlightRequests)e-i.createdAt>this.dedupOptions.ttl&&this.inFlightRequests.delete(t);if(this.inFlightRequests.size>this.dedupOptions.maxEntries){let t=Array.from(this.inFlightRequests.entries());t.sort((r,s)=>r[1].createdAt-s[1].createdAt);let i=t.slice(0,t.length-this.dedupOptions.maxEntries);for(let[r]of i)this.inFlightRequests.delete(r)}}async processInChunks(e,t,i){if(e.length===0)return[];this.stats.chunkedOperations++;let r=[],s=Math.ceil(e.length/t);e.length>t&&o.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 i(l,c);r.push(...d)}return r}estimateMemoryUsage(e){if(e.length===0)return 0;let t=Math.min(10,e.length),i=0;for(let s=0;s<t;s++)i+=JSON.stringify(e[s]).length*2;let r=i/t;return Math.ceil(r*e.length)}getOptimalChunkSize(e,t=500){let r=Math.max(10,Math.floor(1048576/t)),s=Math.min(r,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(i=>({field:i.field,key:i.key,negated:i.negated,operator:i.operator,value:i.value})).sort((i,r)=>`${i.field}:${i.operator}`.localeCompare(`${r.field}:${r.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 i=0;i<e.length;i++)t=(t<<5)+t+e.charCodeAt(i)|0;return t.toString(36)}};var De=class extends Te{apiToken;zoneId;accountId;cache;optimizer;constructor(e,t,i){super("https://api.cloudflare.com/client/v4","cloudflare"),this.apiToken=e,this.zoneId=t,this.accountId=i,this.cache=new ot({enableLogging:!0}),this.optimizer=new Ie}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}invalidateRulesetCache(){this.cache.invalidateByPrefix(`zone:${this.zoneId}`)}invalidateListCache(){this.accountId&&this.cache.invalidateByPrefix(`account:${this.accountId}`)}getAuthHeaders(){return{Authorization:`Bearer ${this.apiToken}`,...this.optimizer.getConnectionHeaders()}}getOptimizer(){return this.optimizer}async listRulesets(){o.debug(`Fetching rulesets for zone ${this.zoneId}`);let e=ye.rulesets(this.zoneId),t=this.cache.get(e);if(t)return t;let i=Ie.requestKey("GET",`/zones/${this.zoneId}/rulesets`);return this.optimizer.deduplicateRequest(i,async()=>{try{let r=await this.get(`/zones/${this.zoneId}/rulesets`);if(!r.success)throw q.handleApiResponse(r,`/zones/${this.zoneId}/rulesets`);if(!Array.isArray(r.result))return o.warn("Malformed API response: expected array of rulesets, got:",typeof r.result),[];let s=r.result.filter(a=>!a||typeof a!="object"?(o.warn("Skipping malformed ruleset object:",a),!1):!a.id||!a.name?(o.warn("Skipping ruleset with missing required fields:",{id:a.id,name:a.name}),!1):!0);return s.length!==r.result.length&&o.warn(`Filtered out ${r.result.length-s.length} malformed rulesets`),this.cache.set(e,s,we.RULESETS),s}catch(r){throw r instanceof Error&&!r.code?q.handleNetworkError(r,"listing rulesets"):r}})}async getRulesets(){return this.listRulesets()}async getRuleset(e){o.debug(`Fetching ruleset ${e}`);let t=ye.ruleset(this.zoneId,e),i=this.cache.get(t);if(i)return i;let r=Ie.requestKey("GET",`/zones/${this.zoneId}/rulesets/${e}`);return this.optimizer.deduplicateRequest(r,async()=>{try{let s=await this.get(`/zones/${this.zoneId}/rulesets/${e}`);if(!s.success)throw q.handleApiResponse(s,`/zones/${this.zoneId}/rulesets/${e}`);if(!s.result||typeof s.result!="object")throw q.handleValidationError("ruleset","Invalid ruleset data received from API",s.result);let a=s.result;if(!a.id||!a.name)throw q.handleValidationError("ruleset","Ruleset missing required fields (id, name)",a);Array.isArray(a.rules)||(o.warn(`Ruleset ${e} has invalid rules array, initializing as empty`),a.rules=[]);let l=a.rules.filter(c=>!c||typeof c!="object"?(o.warn(`Skipping malformed rule in ruleset ${e}:`,c),!1):!c.id||!c.expression||!c.action?(o.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&&(o.warn(`Filtered out ${a.rules.length-l.length} malformed rules from ruleset ${e}`),a.rules=l),this.cache.set(t,a,we.RULESET),a}catch(s){throw s instanceof Error&&!s.code?q.handleNetworkError(s,"fetching ruleset"):s}})}async createRuleset(e){o.debug(`Creating ruleset: ${e.name}`);let t=await this.post(`/zones/${this.zoneId}/rulesets`,e);if(!t.success){let i=t.errors.map(r=>r.message).join(", ");throw z.apiError("cloudflare",`/zones/${this.zoneId}/rulesets`,t.errors[0]?.code||0,i)}return o.info(`Created ruleset: ${t.result.name} (${t.result.id})`),this.invalidateRulesetCache(),t.result}async updateRuleset(e,t){o.debug(`Updating ruleset ${e}`);let i=await this.put(`/zones/${this.zoneId}/rulesets/${e}`,t);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw z.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}`,i.errors[0]?.code||0,r)}return o.info(`Updated ruleset to version ${i.result.version}`),this.invalidateRulesetCache(),i.result}async deleteRuleset(e){o.debug(`Deleting ruleset ${e}`);let t=await this.delete(`/zones/${this.zoneId}/rulesets/${e}`);if(!t.success){let i=t.errors.map(r=>r.message).join(", ");throw z.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}`,t.errors[0]?.code||0,i)}o.info(`Deleted ruleset ${e}`),this.invalidateRulesetCache()}async createRule(e,t){o.debug(`Adding rule to ruleset ${e}`);let i=await this.post(`/zones/${this.zoneId}/rulesets/${e}/rules`,t);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw z.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules`,i.errors[0]?.code||0,r)}return o.info(`Added rule to ruleset ${e}`),this.invalidateRulesetCache(),i.result}async updateRule(e,t,i){o.debug(`Updating rule ${t} in ruleset ${e}`);let r=await this.patch(`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,i);if(!r.success){let s=r.errors.map(a=>a.message).join(", ");throw z.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,r.errors[0]?.code||0,s)}return o.info(`Updated rule ${t}`),this.invalidateRulesetCache(),r.result}async deleteRule(e,t){o.debug(`Deleting rule ${t} from ruleset ${e}`);let i=await this.delete(`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw z.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,i.errors[0]?.code||0,r)}return o.info(`Deleted rule ${t}`),this.invalidateRulesetCache(),i.result}async getOrCreateFirewallRuleset(){o.debug("Looking for existing custom firewall ruleset");let t=(await this.listRulesets()).find(i=>i.kind==="custom"&&i.phase==="http_request_firewall_custom");return t?(o.debug(`Found existing ruleset: ${t.id}`),t):(o.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,Ri.createHash)("sha256").update(this.apiToken).digest("hex").slice(0,8),t=ye.credentialValidation(e),i=this.cache.get(t);if(i!==void 0)return o.debug("Using cached credential validation result"),i;try{return o.debug("Verifying Cloudflare credentials"),await this.listRulesets(),o.info("Cloudflare credentials verified successfully"),this.cache.set(t,!0,we.CREDENTIALS),!0}catch(r){if(o.error(`Cloudflare credential verification failed: ${r}`),r instanceof Error){let s=r.message.toLowerCase();if(s.includes("unauthorized")||s.includes("invalid token"))throw q.handleCredentialError("token");if(s.includes("forbidden")||s.includes("access denied"))throw q.handleCredentialError("zone",this.zoneId);if(s.includes("not found"))throw q.handleCredentialError("zone",this.zoneId)}return!1}}async getZoneInfo(){let e=ye.zoneInfo(this.zoneId),t=this.cache.get(e);if(t)return t;let i=await this.get(`/zones/${this.zoneId}`);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw z.apiError("cloudflare",`/zones/${this.zoneId}`,i.errors[0]?.code||0,r)}return this.cache.set(e,i.result,we.ZONE_INFO),i.result}async listLists(){if(o.debug("Fetching Cloudflare Lists"),!this.accountId)return o.warn("Account ID not provided, Lists API requires account-level access"),[];let e=ye.lists(this.accountId),t=this.cache.get(e);if(t)return t;let i=await this.get(`/accounts/${this.accountId}/rules/lists`);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw z.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,i.errors[0]?.code||0,r)}return this.cache.set(e,i.result,we.LISTS),i.result}async getList(e){if(o.debug(`Fetching List ${e}`),!this.accountId)throw N.accountIdRequired("Lists API");let t=await this.get(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let i=t.errors.map(r=>r.message).join(", ");throw z.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,t.errors[0]?.code||0,i)}return t.result}async createList(e){if(o.debug(`Creating List: ${e.name}`),!this.accountId)throw N.accountIdRequired("Lists API");let t=await this.post(`/accounts/${this.accountId}/rules/lists`,e);if(!t.success){let i=t.errors.map(r=>r.message).join(", ");throw z.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,t.errors[0]?.code||0,i)}return o.info(`Created List: ${t.result.name} (${t.result.id})`),this.invalidateListCache(),t.result}async updateList(e,t){if(o.debug(`Updating List ${e}`),!this.accountId)throw N.accountIdRequired("Lists API");let i=await this.put(`/accounts/${this.accountId}/rules/lists/${e}`,t);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw z.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,i.errors[0]?.code||0,r)}return o.info(`Updated List ${e}`),this.invalidateListCache(),i.result}async deleteList(e){if(o.debug(`Deleting List ${e}`),!this.accountId)throw N.accountIdRequired("Lists API");let t=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let i=t.errors.map(r=>r.message).join(", ");throw z.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,t.errors[0]?.code||0,i)}o.info(`Deleted List ${e}`),this.invalidateListCache()}async getListItems(e){if(o.debug(`Fetching items from List ${e}`),!this.accountId)throw N.accountIdRequired("Lists API");let t=ye.listItems(this.accountId,e),i=this.cache.get(t);if(i)return i;let r=Ie.requestKey("GET",`/accounts/${this.accountId}/rules/lists/${e}/items`);return this.optimizer.deduplicateRequest(r,async()=>{let s=await this.fetchAllListItemPages(e);return this.cache.set(t,s,we.LIST_ITEMS),s})}async fetchAllListItemPages(e){let t=[],i=1;for(;;){let r=await this.get(`/accounts/${this.accountId}/rules/lists/${e}/items?page=${i}`);if(!r.success){let a=r.errors.map(l=>l.message).join(", ");throw z.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,r.errors[0]?.code||0,a)}t.push(...r.result);let s=r.result_info?.total_pages??1;if(r.result.length===0||i>=s)break;i++}return t}async addListItems(e,t){if(o.debug(`Adding ${t.items.length} items to List ${e}`),!this.accountId)throw N.accountIdRequired("Lists API");let i=await this.post(`/accounts/${this.accountId}/rules/lists/${e}/items`,t.items);if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw z.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,i.errors[0]?.code||0,r)}return o.info(`Added ${t.items.length} items to List ${e}`),this.invalidateListCache(),i.result}async removeListItems(e,t){if(o.debug(`Removing ${t.items.length} items from List ${e}`),!this.accountId)throw N.accountIdRequired("Lists API");let i=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}/items`,{body:JSON.stringify(t)});if(!i.success){let r=i.errors.map(s=>s.message).join(", ");throw z.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,i.errors[0]?.code||0,r)}o.info(`Removed ${t.items.length} items from List ${e}`),this.invalidateListCache()}async getOrCreateIPBlocklist(){if(o.debug("Looking for existing Doorman IP blocklist"),!this.accountId)throw o.warn("Account ID not provided, cannot use Lists for IP blocking"),q.handleCredentialError("account");try{let t=(await this.listLists()).find(i=>i.name==="Doorman IP Blocklist"&&i.kind==="ip");return t?(o.debug(`Found existing IP blocklist: ${t.id}`),t):(o.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?q.handleNetworkError(e,"managing IP blocklist"):e}}};var Oe=require("net");E();var je=class n extends ke{name="cloudflare";client;optimizer;useListsForIPs;constructor(e,t,i){super(),this.client=new De(e,t,i),this.optimizer=this.client.getOptimizer(),this.useListsForIPs=!!i,this.useListsForIPs?o.debug("Lists API enabled for IP blocking (account ID provided)"):o.debug("Lists API disabled - will use individual IP rules (no account ID)")}async fetchConfig(e){o.info("Fetching configuration from Cloudflare");try{let t=await this.client.getOrCreateFirewallRuleset(),i=[],r=[],s=[],a=[],l=50,c=t.rules.length;c>100&&o.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);o.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 m=this.cloudflareRuleToIPRule(p);r.push(m)}else{let m=O.cloudflareToUnified(p);i.push(m.result),m.warnings.length>0&&m.warnings.forEach(w=>{let{TranslationWarningSystem:b}=(X(),Y(ee)),R=b.formatWarning(w);s.push(R)})}}catch(m){let w=`Failed to process rule ${p?.id||"unknown"}: ${m instanceof Error?m.message:String(m)}`;o.warn(w),a.push(w)}c>200&&d+l<c&&await new Promise(p=>setTimeout(p,10))}if(a.length>0&&(o.warn(`Encountered ${a.length} rule processing errors:`),a.slice(0,5).forEach(d=>o.warn(` - ${d}`)),a.length>5&&o.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&&r.push({id:p.id,ip:p.ip,notes:p.comment,action:"deny"});o.debug(`Fetched ${u.length} IPs from List`)}catch(d){this.handleListsAPIFallback(d,"fetching IPs from List")}else r.length>10&&o.warn(`\u26A0\uFE0F Large IP list detected (${r.length} IPs) without Lists API. Consider providing CLOUDFLARE_ACCOUNT_ID for better performance.`);return s.length>0&&(o.warn("Translation warnings detected:"),s.forEach(d=>o.warn(d)),s.length>3&&o.warn(`
|
|
30
|
+
\u{1F4CA} Summary: ${s.length} translation warnings detected. Review each warning above for specific guidance.`)),{version:"2.0",provider:"cloudflare",providers:{cloudflare:{zoneId:this.client.zoneId,accountId:this.client.accountId}},rules:i,ips:r,metadata:{version:parseInt(t.version,10),updatedAt:t.last_updated}}}catch(t){throw t instanceof Error&&!("code"in t)?q.handleNetworkError(t,"fetching configuration"):t}}async syncRules(e,t){o.info(`Syncing ${e.rules.length} rules to Cloudflare${t?.dryRun?" (dry run)":""}`);let{OperationSafety:i}=($t(),Y(At)),r=await i.performDryRunValidation(e,"sync rules",async b=>await this.getChanges(b));if(!r.valid)throw new Error(`Dry-run validation failed: ${r.issues.join(", ")}`);if(t?.dryRun)return{success:!0,rulesAdded:r.changes.rulesToAdd.length,rulesUpdated:r.changes.rulesToUpdate.length,rulesDeleted:r.changes.rulesToDelete.length,ipsAdded:r.changes.ipsToAdd?.length||0,ipsUpdated:r.changes.ipsToUpdate?.length||0,ipsDeleted:r.changes.ipsToDelete?.length||0,warnings:r.warnings};let s=i.assessOperationRisk(r.changes,e);if(!await i.confirmDestructiveOperation({operation:"sync rules",target:`Cloudflare zone ${this.client.zoneId}`,changes:r.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 b of e.rules){let R=O.unifiedToCloudflare(b);c.push(R.result),R.warnings.length>0&&R.warnings.forEach(x=>{let{TranslationWarningSystem:J}=(X(),Y(ee)),ne=J.formatWarning(x);o.warn(ne)})}let d=0,u=0,p=0;if(this.useListsForIPs&&e.ips&&e.ips.length>0){let b=new Set;try{let R=await this.client.getOrCreateIPBlocklist(),x=await this.client.getListItems(R.id),J=new Set(x.map(S=>S.ip));J.forEach(S=>S&&b.add(S));let ne=new Set(e.ips.map(S=>S.ip)),be=e.ips.filter(S=>!J.has(S.ip));be.length>0&&(await this.client.addListItems(R.id,{items:be.map(S=>({ip:S.ip,comment:S.notes||S.hostname||"Blocked by Doorman"}))}),d=be.length,be.forEach(S=>b.add(S.ip)),o.info(`Added ${d} IPs to List`));let ve=x.filter(S=>S.ip&&!ne.has(S.ip));ve.length>0&&(await this.client.removeListItems(R.id,{items:ve.map(S=>({id:S.id}))}),p=ve.length,ve.forEach(S=>S.ip&&b.delete(S.ip)),o.info(`Removed ${p} IPs from List`));let at=`ip.src in $${R.name.replace(/\s+/g,"_").toLowerCase()}`;c.push({id:"rule_doorman_ip_list",action:"block",expression:at,description:"Block IPs in Doorman IP Blocklist",enabled:!0})}catch(R){this.handleListsAPIFallback(R,"syncing IPs via List");let x=e.ips.filter(J=>!b.has(J.ip));if(x.length>0){o.info(`\u{1F504} Falling back to individual IP rules for ${x.length} IPs`);for(let J of x){let ne=O.unifiedIPToCloudflare(J);c.push(ne)}d=x.length}else o.info("All IPs were already confirmed in the List before the failure; no fallback rules needed.");x.length>50&&o.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){o.info(`\u{1F4DD} Using individual IP rules for ${e.ips.length} IPs (Lists API not available)`),e.ips.length>20&&o.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 b of e.ips){let R=O.unifiedIPToCloudflare(b);c.push(R)}d=e.ips.length}let m=await this.client.updateRuleset(l.id,{rules:c}),w={success:!0,rulesAdded:r.changes.rulesToAdd.length,rulesUpdated:r.changes.rulesToUpdate.length,rulesDeleted:r.changes.rulesToDelete.length,ipsAdded:d,ipsUpdated:u,ipsDeleted:p,version:parseInt(m.version,10),warnings:r.warnings?.length?r.warnings:void 0};return this.logSyncStats(w),w}async getChanges(e){let t=await this.client.getOrCreateFirewallRuleset(),i=t.rules.filter(c=>c&&c.id&&c.expression&&c.action&&!this.isListBasedIPRule(c)&&!this.isIPBlockingRule(c)),r=e.rules.map(c=>({rule:c,translated:O.unifiedToCloudflare(c).result})),s=this.optimizer.diffCloudflareRules(r,i),a=s.toDelete.map(c=>O.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 i of e)i&&i.id&&i.expression&&i.action&&this.isIPBlockingRule(i)&&t.push(this.cloudflareRuleToIPRule(i));if(this.useListsForIPs)try{let i=await this.client.getOrCreateIPBlocklist(),r=await this.client.getListItems(i.id);for(let s of r)s.ip&&t.push({id:s.id,ip:s.ip,notes:s.comment,action:"deny"})}catch(i){this.handleListsAPIFallback(i,"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),i=[...t.errors],r=[...t.warnings];if(e&&e.rules){let s=this.getSupportedFeatures();if(s.maxRules&&e.rules.length>s.maxRules){let a=N.ruleLimitExceeded(e.rules.length,s.maxRules);i.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=N.ruleNoConditions(a.name||`Rule ${l+1}`);i.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=N.invalidRateLimit(a.name||`Rule ${l+1}`,"requests must be at least 1");i.push({path:`rules[${l}].action.rateLimit.requests`,message:d.message,code:d.code})}if(!c.window.match(/^\d+[smhd]$/)){let d=N.invalidWindowFormat(c.window);i.push({path:`rules[${l}].action.rateLimit.window`,message:d.message,code:d.code})}if(c.characteristics&&c.characteristics.length===0){let d=N.emptyCharacteristics(a.name||`Rule ${l+1}`);r.push({path:`rules[${l}].action.rateLimit.characteristics`,message:d.message,code:d.code})}if(c.mitigationTimeout!==void 0&&c.mitigationTimeout<60){let d=N.shortMitigationTimeout(c.mitigationTimeout);r.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=N.invalidRedirectUrl(c.location);i.push({path:`rules[${l}].action.redirect.location`,message:d.message,code:d.code})}}else{let d=N.redirectNoLocation(a.name||`Rule ${l+1}`);i.push({path:`rules[${l}].action.redirect.location`,message:d.message,code:d.code})}}}catch(c){i.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(!n.isValidIPOrCIDR(a.ip)){let c=N.invalidIP(a.ip);i.push({path:`ips[${l}].ip`,message:c.message,code:c.code})}}catch(c){i.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=N.largeIPList(e.ips.length);r.push({path:"ips",message:a.message,code:a.code})}}return{valid:i.length===0,errors:i,warnings:r}}getHealthScore(e){let t=super.getHealthScore(e),i=[...t.issues],r=this.getSupportedFeatures();return r.maxRules&&e.rules.length>r.maxRules*.8&&i.push({severity:"warning",category:"limits",message:`Approaching Cloudflare rule limit (${e.rules.length}/${r.maxRules})`,suggestion:"Consider consolidating rules or upgrading plan"}),{...t,issues:i}}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,i,...r]=e.split("/");if(r.length>0||!t)return!1;if(i===void 0)return(0,Oe.isIPv4)(t)||(0,Oe.isIPv6)(t);if(!/^\d+$/.test(i))return!1;let s=Number(i);return(0,Oe.isIPv4)(t)?s<=32:(0,Oe.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 n.IP_EQ_PATTERN.test(t)||n.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(),r=(t.match(n.IP_EQ_PATTERN)||t.match(n.IP_IN_SET_PATTERN))?.[1]||"",a=e.description?.match(/\(([^)]+)\)/)?.[1];return{id:e.id,ip:r,hostname:a,notes:e.description,action:e.action==="allow"?"allow":"deny"}}handleListsAPIFallback(e,t){if(e instanceof Error){let i=e.message.toLowerCase();i.includes("account")?(o.warn("\u{1F6AB} Lists API unavailable: Account ID not provided or invalid. Falling back to individual IP rules."),o.info(`\u{1F4A1} To enable Lists API for better performance with large IP lists:
|
|
31
31
|
\u2022 Set CLOUDFLARE_ACCOUNT_ID in your environment
|
|
32
32
|
\u2022 Ensure your API token has Account:Read permissions
|
|
33
33
|
\u2022 Find your Account ID in the Cloudflare dashboard sidebar`)):i.includes("permission")||i.includes("forbidden")?(o.warn(`\u{1F6AB} Lists API permission denied: Insufficient permissions for ${t}. Falling back to individual IP rules.`),o.info(`\u{1F4A1} To fix Lists API permissions:
|
|
34
34
|
\u2022 Ensure your API token has Account:Read permissions
|
|
35
35
|
\u2022 Verify the account ID is correct
|
|
36
|
-
\u2022 Check token permissions in Cloudflare dashboard`)):i.includes("not found")?(o.warn(`\u{1F6AB} Lists API resource not found during ${t}. Falling back to individual IP rules.`),o.info("\u{1F4A1} This may be temporary - the List will be recreated on next sync if Lists API is available.")):i.includes("rate limit")||i.includes("quota")?(o.warn(`\u{1F6AB} Lists API rate limited during ${t}. Falling back to individual IP rules.`),o.info("\u{1F4A1} Lists API rate limit reached. Individual rules will be used this time. Consider retrying later or upgrading your Cloudflare plan.")):(o.warn(`\u{1F6AB} Lists API error during ${t}: ${e.message}. Falling back to individual IP rules.`),o.info("\u{1F4A1} Lists API temporarily unavailable. Using individual IP rules as fallback. Check Cloudflare status if this persists."))}else o.warn(`\u{1F6AB} Unknown Lists API error during ${t}. Falling back to individual IP rules.`)}};var
|
|
36
|
+
\u2022 Check token permissions in Cloudflare dashboard`)):i.includes("not found")?(o.warn(`\u{1F6AB} Lists API resource not found during ${t}. Falling back to individual IP rules.`),o.info("\u{1F4A1} This may be temporary - the List will be recreated on next sync if Lists API is available.")):i.includes("rate limit")||i.includes("quota")?(o.warn(`\u{1F6AB} Lists API rate limited during ${t}. Falling back to individual IP rules.`),o.info("\u{1F4A1} Lists API rate limit reached. Individual rules will be used this time. Consider retrying later or upgrading your Cloudflare plan.")):(o.warn(`\u{1F6AB} Lists API error during ${t}: ${e.message}. Falling back to individual IP rules.`),o.info("\u{1F4A1} Lists API temporarily unavailable. Using individual IP rules as fallback. Check Cloudflare status if this persists."))}else o.warn(`\u{1F6AB} Unknown Lists API error during ${t}. Falling back to individual IP rules.`)}};var xe=class{static create(e,t,i){let r=e||process.env.CLOUDFLARE_API_TOKEN,s=t||process.env.CLOUDFLARE_ZONE_ID,a=i||process.env.CLOUDFLARE_ACCOUNT_ID;if(!r)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 je(r,s,a)}static fromEnv(){return this.create()}static fromConfig(e){return this.create(e.apiToken,e.zoneId,e.accountId)}};E();async function Ai(n){let e;if(n.provider)e=n.provider,o.debug(`Using explicitly specified provider: ${e}`);else{let t=Ye.detect(n.config);t.provider?(e=t.provider,o.debug(`Auto-detected provider: ${e} (${t.confidence} confidence)`),t.reasons.length>0&&o.debug(`Reasons: ${t.reasons.join(", ")}`)):n.interactive!==!1?e=await Bo():(e="vercel",o.warn("No provider detected, defaulting to Vercel"))}try{if(e==="vercel")return await Fo(n);if(e==="cloudflare")return{provider:await Vo(n)};throw new Error(`Unknown provider: ${e}`)}catch(t){throw o.error(`Failed to initialize ${e} provider:`,t),t}}async function Fo(n){let e=n.token||process.env.VERCEL_TOKEN,t=n.config,i=t?.providers?.vercel?.projectId??t?.projectId,r=t?.providers?.vercel?.teamId??t?.teamId,s=n.projectId||i||process.env.VERCEL_PROJECT_ID,a=n.teamId||r||process.env.VERCEL_TEAM_ID;if(!e||!s||!a){if(n.interactive===!1)throw new Error("Vercel credentials missing. Provide token, projectId, and teamId.");o.warn("Missing Vercel credentials"),o.info("Please provide your Vercel credentials:");let{promptForCredentials:c}=await Promise.resolve().then(()=>(vi(),bi)),d=await c({token:e,projectId:s,teamId:a});return{provider:Ue.fromConfig({token:d.token,projectId:d.projectId,teamId:d.teamId}),vercelCredentials:d}}return{provider:Ue.fromConfig({token:e,projectId:s,teamId:a}),vercelCredentials:{token:e,projectId:s,teamId:a}}}async function Vo(n){let e=n.apiToken||process.env.CLOUDFLARE_API_TOKEN,t=n.zoneId||process.env.CLOUDFLARE_ZONE_ID,i=n.accountId||process.env.CLOUDFLARE_ACCOUNT_ID;if(!e||!t){if(n.interactive===!1)throw new Error("Cloudflare credentials missing. Provide apiToken and zoneId.");o.warn("Missing Cloudflare credentials"),o.info("Please provide your Cloudflare credentials:");let r=e||await Qe("Cloudflare API Token: "),s=t||await y("Cloudflare Zone ID:",{type:"text"}),a=i||await y("Cloudflare Account ID (optional):",{type:"text"});return xe.fromConfig({apiToken:r,zoneId:s,accountId:a||void 0})}return xe.fromConfig({apiToken:e,zoneId:t,accountId:i})}async function Bo(){o.info(Ei.default.yellow("Unable to auto-detect firewall provider.")),o.info(`Please select a provider:
|
|
37
37
|
`),o.info(" 1. Vercel Firewall"),o.info(` 2. Cloudflare WAF
|
|
38
|
-
`);let n=await y("Select provider (1 or 2):",{type:"text"}),e=String(n).toLowerCase();return e==="1"||e==="vercel"?"vercel":e==="2"||e==="cloudflare"?"cloudflare":(o.warn(`Invalid choice: ${n}, defaulting to Vercel`),"vercel")}async function
|
|
38
|
+
`);let n=await y("Select provider (1 or 2):",{type:"text"}),e=String(n).toLowerCase();return e==="1"||e==="vercel"?"vercel":e==="2"||e==="cloudflare"?"cloudflare":(o.warn(`Invalid choice: ${n}, defaulting to Vercel`),"vercel")}async function W(n,e){try{n.debug&&(o.level=$i.LogLevels.debug);let t;if(n.optionalConfig)try{t=await F(n.config,"optional")}catch{t={}}else n.skipValidation?t=await F(n.config,"raw"):t=await F(n.config,"required");let{provider:i,vercelCredentials:r}=await Ai({provider:n.provider,config:t,interactive:!n.ci,token:n.token,projectId:n.projectId,teamId:n.teamId,apiToken:n.apiToken,zoneId:n.zoneId,accountId:n.accountId}),s=r?.token??"",a=r?.projectId??"",l=r?.teamId??"";await e({config:t,provider:i,token:s,projectId:a,teamId:l})}catch(t){M(t,n.errorContext)}}var jo="backup",zo="Backup or restore firewall configurations",qo={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:{type:"string",choices:["vercel","cloudflare"],description:"Firewall provider (auto-detected)"},projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},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}},Mo=async n=>{try{n.debug&&(o.level=Ti.LogLevels.debug);let e=n.output||"./backups";if(n.list){if(!(0,se.existsSync)(e)){o.info(G.default.yellow("No backup directory found."));return}let t=(0,se.readdirSync)(e).filter(i=>i.endsWith(".json")).map(i=>{let r=(0,nt.join)(e,i),s=(0,se.statSync)(r);return{name:i,size:s.size,created:s.mtime}}).sort((i,r)=>r.created.getTime()-i.created.getTime());if(t.length===0){o.info(G.default.yellow("No backups found."));return}o.log(G.default.bold(`
|
|
39
39
|
\u{1F4E6} Available Backups:
|
|
40
|
-
`)),t.forEach(i=>{o.log(`${
|
|
40
|
+
`)),t.forEach(i=>{o.log(`${G.default.cyan(i.name)}`),o.log(` ${G.default.dim("Created:")} ${i.created.toLocaleString()}`),o.log(` ${G.default.dim("Size:")} ${(i.size/1024).toFixed(1)} KB`),o.log("")});return}if(n.restore){let t=n.restore.startsWith("/")?n.restore:(0,nt.join)(e,n.restore);(0,se.existsSync)(t)||(o.error(`Backup file not found: ${t}`),process.exit(1));let i=await F(t,"raw"),r=n.config||".doorman.json";if((0,se.existsSync)(r)&&!await y(`Config file ${r} already exists. Do you want to overwrite it?`,{type:"confirm"})){o.info(G.default.yellow("Restore cancelled."));return}let{backup:s,...a}=i;await V(a,r),o.success(G.default.green(`\u2705 Restored configuration from ${t} to ${r}`));return}await W({config:n.config,provider:n.provider,projectId:n.projectId,teamId:n.teamId,token:n.token,apiToken:n.apiToken,zoneId:n.zoneId,accountId:n.accountId,debug:n.debug,ci:n.ci,errorContext:"creating backup"},async({provider:t,projectId:i,teamId:r})=>{o.start("Fetching current remote configuration...");let s=await t.fetchConfig(),a=s.metadata?.version??s.version;de.getInstance().validateConfig(s),(0,se.existsSync)(e)||(0,se.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",m=`firewall-backup-${`${d}_${u}`}.json`,w=(0,nt.join)(e,m),b={...s,backup:{createdAt:new Date().toISOString(),source:"remote",provider:t.name,...t.name==="vercel"?{projectId:i,teamId:r}:{},originalVersion:a}};await V(b,w,{validate:!1}),o.success(G.default.green(`\u2705 Backup created: ${w}`)),o.log(""),o.log(G.default.bold("Backup Details:")),o.log(`${G.default.dim("Version:")} ${a??"unknown"}`),o.log(`${G.default.dim("Rules:")} ${s.rules.length} custom, ${s.ips?.length??0} IP blocking`),o.log(`${G.default.dim("Created:")} ${new Date().toLocaleString()}`),o.log(""),o.log(G.default.dim("To restore this backup later, run:")),o.log(G.default.cyan(`doorman backup --restore ${m}`))})}catch(e){M(e,"managing backup")}};var kt={};j(kt,{builder:()=>Zo,command:()=>Wo,desc:()=>Go,handler:()=>Ho});var Z=P(require("chalk"));E();function te(n){if(le(n))return n;let e=n,t=e.rules.map(r=>O.vercelToUnified(r).result),i=(e.ips??[]).map(r=>O.vercelIPToUnified(r));return{version:"2.0",provider:"vercel",providers:{vercel:{projectId:e.projectId,teamId:e.teamId}},rules:t,ips:i,metadata:{version:e.version,updatedAt:e.updatedAt}}}function rt(n,e){let t=!1,i=le(n),r=i?{...n,metadata:{...n.metadata}}:{...n};if(e.version!==void 0)if(i){let s=r;s.metadata?.version!==e.version&&(s.metadata={...s.metadata,version:e.version,updatedAt:e.updatedAt??new Date().toISOString()},t=!0)}else{let s=r;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=r.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&&(r={...r,rules:c},t=!0)}return{config:r,changed:t}}function Pi(n,e){if(le(e))return{...e,...n};let t=e,i=n.rules.map(s=>O.unifiedToVercel(s).result),r=(n.ips??[]).map(s=>({id:s.id||"",ip:s.ip,hostname:s.hostname||"",action:s.action,notes:s.notes}));return{...t,projectId:n.providers?.vercel?.projectId??t.projectId,teamId:n.providers?.vercel?.teamId??t.teamId,version:n.metadata?.version,updatedAt:n.metadata?.updatedAt,rules:i,ips:r}}var Wo="diff",Go="Show detailed differences between local and remote firewall configuration",Zo={config:{alias:"c",type:"string",description:"Path to firewall config file"},provider:{type:"string",choices:["vercel","cloudflare"],description:"Firewall provider (auto-detected)"},projectId:{alias:"p",type:"string",description:"Vercel Project ID"},teamId:{alias:"t",type:"string",description:"Vercel Team ID"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},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}},Ho=async n=>{await W({config:n.config,provider:n.provider,projectId:n.projectId,teamId:n.teamId,token:n.token,apiToken:n.apiToken,zoneId:n.zoneId,accountId:n.accountId,debug:n.debug,ci:n.ci,errorContext:"calculating diff"},async({config:e,provider:t})=>{await Ko(t,te(e),n)})};async function Ko(n,e,t){o.start("Calculating differences...");let i=await n.getChanges(e);if(!i.hasChanges){o.success(Z.default.green("No differences found. Local and remote configurations are in sync."));return}let r=i.ipsToAdd??[],s=i.ipsToUpdate??[],a=i.ipsToDelete??[];if(t.format==="json"){o.log(JSON.stringify({rules:{toAdd:i.rulesToAdd,toUpdate:i.rulesToUpdate,toDelete:i.rulesToDelete},ips:{toAdd:r,toUpdate:s,toDelete:a},summary:{hasChanges:i.hasChanges,ruleChanges:i.rulesToAdd.length+i.rulesToUpdate.length+i.rulesToDelete.length,ipChanges:r.length+s.length+a.length}},null,2));return}o.log(Z.default.bold(`
|
|
41
41
|
\u{1F50D} ${n.name} Configuration Differences
|
|
42
|
-
`)),o.log(
|
|
42
|
+
`)),o.log(Z.default.bold("Rule Changes:")),o.log(` ${Z.default.green("+")} ${i.rulesToAdd.length} to add`),i.rulesToAdd.forEach(c=>o.log(` ${Z.default.green("+")} ${c.name}`)),o.log(` ${Z.default.cyan("~")} ${i.rulesToUpdate.length} to update`),i.rulesToUpdate.forEach(c=>o.log(` ${Z.default.cyan("~")} ${c.name}`)),o.log(` ${Z.default.red("-")} ${i.rulesToDelete.length} to delete`),i.rulesToDelete.forEach(c=>o.log(` ${Z.default.red("-")} ${c.name}`)),(r.length||s.length||a.length)&&(o.log(""),o.log(Z.default.bold("IP Rule Changes:")),o.log(` ${Z.default.green("+")} ${r.length} to add`),o.log(` ${Z.default.cyan("~")} ${s.length} to update`),o.log(` ${Z.default.red("-")} ${a.length} to delete`));let l=i.rulesToAdd.length+i.rulesToUpdate.length+i.rulesToDelete.length+r.length+s.length+a.length;o.log(""),o.log(Z.default.bold(`Summary: ${l} total changes detected`)),o.log(Z.default.dim("Run `sync` to apply these changes to the remote configuration."))}var _t={};j(_t,{builder:()=>Yo,command:()=>Jo,desc:()=>Qo,handler:()=>Xo});var Ce=P(require("chalk")),ki=require("zod");E();re();var Jo="download [configVersion]",Qo="Download remote Vercel Firewall rules and update local config, optionally for a specific configuration version",Yo={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:{type:"string",choices:["vercel","cloudflare"],description:"Firewall provider (auto-detected)"},projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},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}},Xo=async n=>{await W({config:n.config,provider:n.provider,projectId:n.projectId,teamId:n.teamId,token:n.token,apiToken:n.apiToken,zoneId:n.zoneId,accountId:n.accountId,debug:n.debug,ci:n.ci,optionalConfig:!0,skipValidation:!0,errorContext:"downloading firewall rules"},async({config:e,provider:t})=>{if(n.configVersion!==void 0)try{Ke.parse(n.configVersion)}catch(i){throw i instanceof ki.z.ZodError&&(o.error("Invalid configuration version number. Version must be a positive integer."),process.exit(1)),i}await en(t,e,n)})};async function en(n,e,t){o.start(`Fetching remote firewall configuration${t.configVersion?` version ${t.configVersion}`:""} ...`);let i=await n.fetchConfig(t.configVersion),r=i.rules,s=i.ips??[];if(r.length>0?(o.log(Ce.default.bold(`
|
|
43
43
|
Remote Custom Rules to Download (${r.length}):
|
|
44
|
-
`)),r.forEach(c=>o.log(` - ${c.name}${c.enabled?"":
|
|
44
|
+
`)),r.forEach(c=>o.log(` - ${c.name}${c.enabled?"":Ce.default.dim(" (disabled)")}`))):o.info("No custom rules to download..."),s.length>0?(o.log(Ce.default.bold(`
|
|
45
45
|
Remote IP Blocking Rules to Download (${s.length}):
|
|
46
|
-
`)),s.forEach(c=>o.log(` - ${c.ip} (${c.action})`))):o.info("No IP blocking rules to download..."),t.dryRun){o.info(
|
|
46
|
+
`)),s.forEach(c=>o.log(` - ${c.ip} (${c.action})`))):o.info("No IP blocking rules to download..."),t.dryRun){o.info(Ce.default.cyan("Dry run completed. No changes made."));return}if(!await y(`Do you want to download${t.configVersion?` version ${t.configVersion}`:" the latest version"} of these rules? This will overwrite your local configuration.`,{type:"confirm"})){o.info(Ce.default.yellow("Download cancelled."));return}let l=Pi(i,e);o.start("Saving configuration..."),await V(l,t.config),o.success(Ce.default.green("Successfully downloaded and updated configuration"))}var St={};j(St,{builder:()=>nn,command:()=>tn,desc:()=>on,handler:()=>ln});var Re=P(require("chalk")),_i=require("fs");E();var tn="export",on="Export firewall configuration in various formats",nn={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:{type:"string",choices:["vercel","cloudflare"],description:"Firewall provider (auto-detected)"},projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},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 rn(n){let e=new Map;for(let t of n){let i=t.group??0,r=e.get(i);r?r.push(t):e.set(i,[t])}return[...e.values()]}var sn=n=>{let{rules:e,ips:t=[]}=n,i=n.metadata?.version,r=n.metadata?.updatedAt,s=`# Firewall Configuration Report
|
|
47
47
|
|
|
48
48
|
`;return s+=`**Provider:** ${n.provider??"unknown"}
|
|
49
49
|
`,s+=`**Version:** ${i??"unknown"}
|
|
@@ -60,7 +60,7 @@ Remote IP Blocking Rules to Download (${s.length}):
|
|
|
60
60
|
`,s+=`- **Enabled:** ${a.enabled?"\u2705 Yes":"\u274C No"}
|
|
61
61
|
`,a.action.rateLimit&&(s+=`- **Rate Limit:** ${a.action.rateLimit.requests} requests per ${a.action.rateLimit.window}
|
|
62
62
|
`),s+=`- **Conditions:**
|
|
63
|
-
`,
|
|
63
|
+
`,rn(a.conditions).forEach((c,d)=>{s+=` - Group ${d+1}:
|
|
64
64
|
`,c.forEach(u=>{s+=` - ${u.field} ${u.operator} \`${u.value}\`
|
|
65
65
|
`})}),s+=`
|
|
66
66
|
`}):s+=`No custom rules configured.
|
|
@@ -71,7 +71,7 @@ Remote IP Blocking Rules to Download (${s.length}):
|
|
|
71
71
|
`,s+=`|------------|----------|--------|
|
|
72
72
|
`,t.forEach(a=>{s+=`| \`${a.ip}\` | ${a.hostname||"N/A"} | ${a.action} |
|
|
73
73
|
`})):s+=`No IP blocking rules configured.
|
|
74
|
-
`,s},
|
|
74
|
+
`,s},an=n=>{let{rules:e,ips:t=[]}=n,i=`# Firewall Configuration (${n.provider??"unknown"})
|
|
75
75
|
`;return i+=`# Generated on ${new Date().toISOString()}
|
|
76
76
|
|
|
77
77
|
`,i+=`# Note: This is a conceptual Terraform configuration
|
|
@@ -94,7 +94,7 @@ Remote IP Blocking Rules to Download (${s.length}):
|
|
|
94
94
|
`,i+=` action = "${r.action}"
|
|
95
95
|
`,i+=`}
|
|
96
96
|
|
|
97
|
-
`}),i},
|
|
97
|
+
`}),i},ln=async n=>{try{let e;n.source==="remote"?await W({config:n.config,provider:n.provider,projectId:n.projectId,teamId:n.teamId,token:n.token,apiToken:n.apiToken,zoneId:n.zoneId,accountId:n.accountId,debug:n.debug,ci:n.ci,errorContext:"exporting configuration"},async({provider:s})=>{o.start("Fetching remote configuration..."),e=await s.fetchConfig()}):e=await F(n.config),o.start(`Exporting configuration in ${n.format} format...`);let t,i;switch(n.format){case"json":t=JSON.stringify(e,null,2),i="json";break;case"yaml":{let s=te(e);t=`# Firewall Configuration (${s.provider??"unknown"})
|
|
98
98
|
`,t+=`version: ${s.metadata?.version??"unknown"}
|
|
99
99
|
`,t+=`updatedAt: "${s.metadata?.updatedAt??""}"
|
|
100
100
|
`,t+=`rules:
|
|
@@ -102,39 +102,39 @@ Remote IP Blocking Rules to Download (${s.length}):
|
|
|
102
102
|
`,t+=` id: "${a.id??""}"
|
|
103
103
|
`,t+=` enabled: ${a.enabled}
|
|
104
104
|
`,t+=` action: "${a.action.type}"
|
|
105
|
-
`}),i="yaml";break}case"terraform":t=
|
|
106
|
-
`))},
|
|
107
|
-
\u{1F4DA} Helpful Resources:`)),o.log(""),o.log(h.default.cyan("\u{1F517} Find your Project ID:")),o.log(h.default.dim(" https://vercel.com/dashboard \u2192 Select your project \u2192 Settings \u2192 General")),o.log(""),o.log(h.default.cyan("\u{1F517} Find your Team ID:")),o.log(h.default.dim(" https://vercel.com/dashboard \u2192 Team Settings \u2192 General")),o.log(h.default.dim(" (Leave empty if using personal account)")),o.log(""),o.log(h.default.cyan("\u{1F517} Create API Token:")),o.log(h.default.dim(" https://vercel.com/account/tokens \u2192 Create Token")),o.log(h.default.dim(" Scopes needed: Read & Write for your project")),o.log(""),o.log(h.default.cyan("\u{1F517} Documentation:")),o.log(h.default.dim(" https://doorman.griffen.codes/getting-started")),o.log("")},
|
|
108
|
-
`)),e||(e=await y("Enter your Vercel Project ID:",{type:"text"})),t||await y("Are you using a Vercel team account?",{type:"confirm"})&&(t=await y("Enter your Vercel Team ID:",{type:"text"})),process.env.VERCEL_TOKEN?o.log(h.default.green("\u2705 VERCEL_TOKEN environment variable found")):(o.log(""),o.log(h.default.yellow("\u26A0\uFE0F VERCEL_TOKEN environment variable not found")),o.log(h.default.dim("You'll need to set this before running sync commands.")),await y("Would you like to see how to create an API token?",{type:"confirm"})&&(o.log(""),o.log(h.default.bold("\u{1F511} Creating a Vercel API Token:")),o.log("1. Go to https://vercel.com/account/tokens"),o.log('2. Click "Create Token"'),o.log('3. Give it a descriptive name (e.g., "Doorman Firewall")'),o.log("4. Set expiration as needed"),o.log("5. Copy the token and set it as an environment variable:"),o.log(""),o.log(h.default.cyan(' export VERCEL_TOKEN="your-token-here"')),o.log(h.default.dim(" # Add this to your ~/.bashrc, ~/.zshrc, or .env file")),o.log("")))),{projectId:e,teamId:t}},
|
|
109
|
-
`)),o.log(h.default.cyan("\u{1F4DD} empty")+h.default.dim(" - Minimal config, add your own rules")),o.log(h.default.cyan("\u{1F6E1}\uFE0F basic")+h.default.dim(" - Includes basic bot protection")),o.log(h.default.cyan("\u{1F512} security-focused")+h.default.dim(" - Comprehensive security rules")),o.log(""));let r=n.template;n.interactive&&!n.template&&(r=await y("Select a template:",{type:"select",options:["empty","basic","security-focused"],initial:"empty"})),o.start(`Creating ${r} configuration...`);let s=
|
|
110
|
-
`+
|
|
105
|
+
`}),i="yaml";break}case"terraform":t=an(te(e)),i="tf";break;case"markdown":t=sn(te(e)),i="md";break;default:throw new Error(`Unsupported format: ${n.format}`)}let r=n.output||`firewall-export.${i}`;n.output==="-"||!n.output?o.log(t):((0,_i.writeFileSync)(r,t,"utf8"),o.success(Re.default.green(`\u2705 Exported to ${r}`)),o.log(""),o.log(Re.default.bold("Export Summary:")),o.log(`${Re.default.dim("Format:")} ${n.format}`),o.log(`${Re.default.dim("Source:")} ${n.source}`),o.log(`${Re.default.dim("Rules:")} ${e.rules.length} custom, ${(e.ips||[]).length} IP blocking`),o.log(`${Re.default.dim("Size:")} ${(t.length/1024).toFixed(1)} KB`))}catch(e){M(e,"exporting configuration")}};var Lt={};j(Lt,{BASIC_TEMPLATE_RULES:()=>Li,SECURITY_FOCUSED_TEMPLATE_RULES:()=>Ui,builder:()=>un,command:()=>cn,desc:()=>dn,handler:()=>mn});var h=P(require("chalk")),Si=require("fs");E();re();var Li=[{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}],Ui=[{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}],cn="init [template]",dn="Initialize a new Doorman configuration",un={template:{type:"string",description:"Template to use for initialization (empty, basic, or security-focused)",choices:["empty","basic","security-focused"],default:"empty"},config:{alias:"c",type:"string",description:"Path for the new config file",default:".doorman.json"},force:{alias:"f",type:"boolean",description:"Overwrite existing config file",default:!1},interactive:{alias:"i",type:"boolean",description:"Interactive setup with guided prompts",default:!0},projectId:{alias:"p",type:"string",description:"Vercel Project ID"},teamId:{alias:"t",type:"string",description:"Vercel Team ID"}},pn=()=>{o.log(""),o.log(h.default.bold.cyan("\u{1F6AA} Welcome to Doorman!")),o.log(h.default.dim(`Let's set up your firewall configuration.
|
|
106
|
+
`))},gn=()=>{o.log(h.default.bold(`
|
|
107
|
+
\u{1F4DA} Helpful Resources:`)),o.log(""),o.log(h.default.cyan("\u{1F517} Find your Project ID:")),o.log(h.default.dim(" https://vercel.com/dashboard \u2192 Select your project \u2192 Settings \u2192 General")),o.log(""),o.log(h.default.cyan("\u{1F517} Find your Team ID:")),o.log(h.default.dim(" https://vercel.com/dashboard \u2192 Team Settings \u2192 General")),o.log(h.default.dim(" (Leave empty if using personal account)")),o.log(""),o.log(h.default.cyan("\u{1F517} Create API Token:")),o.log(h.default.dim(" https://vercel.com/account/tokens \u2192 Create Token")),o.log(h.default.dim(" Scopes needed: Read & Write for your project")),o.log(""),o.log(h.default.cyan("\u{1F517} Documentation:")),o.log(h.default.dim(" https://doorman.griffen.codes/getting-started")),o.log("")},fn=async n=>{let e=n.projectId,t=n.teamId;return n.interactive&&(o.log(h.default.bold("\u{1F4CB} Project Configuration")),o.log(h.default.dim(`We need your Vercel project details to configure the firewall.
|
|
108
|
+
`)),e||(e=await y("Enter your Vercel Project ID:",{type:"text"})),t||await y("Are you using a Vercel team account?",{type:"confirm"})&&(t=await y("Enter your Vercel Team ID:",{type:"text"})),process.env.VERCEL_TOKEN?o.log(h.default.green("\u2705 VERCEL_TOKEN environment variable found")):(o.log(""),o.log(h.default.yellow("\u26A0\uFE0F VERCEL_TOKEN environment variable not found")),o.log(h.default.dim("You'll need to set this before running sync commands.")),await y("Would you like to see how to create an API token?",{type:"confirm"})&&(o.log(""),o.log(h.default.bold("\u{1F511} Creating a Vercel API Token:")),o.log("1. Go to https://vercel.com/account/tokens"),o.log('2. Click "Create Token"'),o.log('3. Give it a descriptive name (e.g., "Doorman Firewall")'),o.log("4. Set expiration as needed"),o.log("5. Copy the token and set it as an environment variable:"),o.log(""),o.log(h.default.cyan(' export VERCEL_TOKEN="your-token-here"')),o.log(h.default.dim(" # Add this to your ~/.bashrc, ~/.zshrc, or .env file")),o.log("")))),{projectId:e,teamId:t}},mn=async n=>{try{let e=n.config||".doorman.json";if(n.interactive&&pn(),(0,Si.existsSync)(e)&&!n.force&&!await y(`Config file ${e} already exists. Do you want to overwrite it?`,{type:"confirm"})){o.info(h.default.yellow("Initialization cancelled."));return}let{projectId:t,teamId:i}=await fn(n);n.interactive&&(o.log(""),o.log(h.default.bold("\u{1F3A8} Template Selection")),o.log(h.default.dim(`Choose a starting template for your firewall configuration:
|
|
109
|
+
`)),o.log(h.default.cyan("\u{1F4DD} empty")+h.default.dim(" - Minimal config, add your own rules")),o.log(h.default.cyan("\u{1F6E1}\uFE0F basic")+h.default.dim(" - Includes basic bot protection")),o.log(h.default.cyan("\u{1F512} security-focused")+h.default.dim(" - Comprehensive security rules")),o.log(""));let r=n.template;n.interactive&&!n.template&&(r=await y("Select a template:",{type:"select",options:["empty","basic","security-focused"],initial:"empty"})),o.start(`Creating ${r} configuration...`);let s=Xe();switch(t&&(s.projectId=t),i&&(s.teamId=i),r){case"basic":s={...s,rules:Li};break;case"security-focused":s={...s,rules:Ui};break;default:break}await V(s,e),o.success(h.default.green(`\u2705 Created ${e}`)),o.log(""),o.log(h.default.bold("\u{1F4CB} Configuration Summary:")),o.log(`${h.default.dim("File:")} ${e}`),o.log(`${h.default.dim("Template:")} ${r}`),o.log(`${h.default.dim("Project ID:")} ${t||h.default.yellow("Not set - add manually")}`),o.log(`${h.default.dim("Team ID:")} ${i||h.default.dim("None (personal account)")}`),o.log(`${h.default.dim("Rules:")} ${s.rules.length} (all disabled for safety)`),o.log(""),o.log(h.default.bold("\u{1F680} Next Steps:")),t||o.log(`1. ${h.default.yellow("Add your projectId")} to ${e}`),process.env.VERCEL_TOKEN||o.log(`${t?"1":"2"}. ${h.default.yellow("Set VERCEL_TOKEN")} environment variable`);let a=t?process.env.VERCEL_TOKEN?1:2:3;o.log(`${a}. ${h.default.dim("Review and enable rules in")} ${e}`),o.log(`${a+1}. ${h.default.dim("Run")} ${h.default.cyan("doorman validate")} ${h.default.dim("to check your config")}`),o.log(`${a+2}. ${h.default.dim("Run")} ${h.default.cyan("doorman status")} ${h.default.dim("to see sync status")}`),o.log(`${a+3}. ${h.default.dim("Run")} ${h.default.cyan("doorman sync")} ${h.default.dim("to deploy your rules")}`),r!=="empty"&&(o.log(""),o.log(h.default.yellow("\u26A0\uFE0F All template rules are disabled by default for safety.")),o.log(h.default.dim(" Review each rule and set active: true when ready."))),n.interactive&&(!t||!process.env.VERCEL_TOKEN)&&gn()}catch(e){M(e,"initializing configuration")}};var Ut={};j(Ut,{builder:()=>wn,command:()=>hn,desc:()=>yn,handler:()=>In});var ie=P(require("chalk")),Di=require("zod");E();var hn="list [configVersion]",yn="List Vercel Firewall rules, optionally for a specific configuration version",wn={configVersion:{type:"number",description:"Specific configuration version to fetch (defaults to latest)"},provider:{type:"string",choices:["vercel","cloudflare"],description:"Firewall provider (auto-detected)"},projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file or VERCEL_PROJECT_ID environment variable)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file or VERCEL_TEAM_ID environment variable)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},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}},In=async n=>{await W({provider:n.provider,projectId:n.projectId,teamId:n.teamId,token:n.token,apiToken:n.apiToken,zoneId:n.zoneId,accountId:n.accountId,debug:n.debug,ci:n.ci,optionalConfig:!0,skipValidation:!0,errorContext:"listing firewall rules"},async({provider:e})=>{if(n.configVersion!==void 0)try{Ke.parse(n.configVersion)}catch(t){throw t instanceof Di.z.ZodError&&(o.error("Invalid configuration version number. Version must be a positive integer."),process.exit(1)),t}await Cn(e,n)})};async function Cn(n,e){o.start(`Fetching firewall configuration${e.configVersion?` version ${e.configVersion}`:""} ...`);let t=await n.fetchConfig(e.configVersion),i=t.rules,r=t.ips??[],s=t.metadata?.version??t.version,a=t.metadata?.updatedAt;if(o.info(`Found ${ie.default.cyan(i.length)} custom rules and ${ie.default.cyan(r.length)} IP blocking rules
|
|
110
|
+
`+ie.default.dim(`Version: ${ie.default.yellow(s??"unknown")}${a?` \u2022 Last Updated: ${ie.default.yellow(a)}`:""}`)),e.format==="json"){o.info(JSON.stringify({version:s,updatedAt:a,rules:i,ips:r},null,2));return}if(i.length===0&&r.length===0){o.info(ie.default.yellow("No rules found"));return}i.length>0?(o.log(ie.default.bold.underline(`
|
|
111
111
|
Custom Rules:`),`
|
|
112
|
-
`),i.forEach(l=>o.log(` - ${l.name}${l.enabled?"":
|
|
112
|
+
`),i.forEach(l=>o.log(` - ${l.name}${l.enabled?"":ie.default.dim(" (disabled)")}`))):o.info(ie.default.cyan("No custom rules found")),r.length>0?(o.log(ie.default.bold.underline(`
|
|
113
113
|
IP Blocking Rules:`),`
|
|
114
|
-
`),r.forEach(l=>o.log(` - ${l.ip} (${l.action})`))):o.info(
|
|
115
|
-
Current IP rules:`)),
|
|
116
|
-
${n.dryRun?"Would remove":"Removing"} ${r.length} IP rule(s):`)),
|
|
117
|
-
Dry run \u2014 no changes made.`));return}if(!await
|
|
118
|
-
\u26A0\uFE0F Found ${r.length} rules named "${n.name}". All will be removed.`)),
|
|
114
|
+
`),r.forEach(l=>o.log(` - ${l.ip} (${l.action})`))):o.info(ie.default.cyan("No IP blocking rules found"))}var Ot={};j(Ot,{aliases:()=>bn,builder:()=>En,command:()=>Rn,desc:()=>vn,findFuzzyMatches:()=>Vi,handler:()=>An,levenshtein:()=>Fi});var _=P(require("chalk")),Ni=require("consola");E();re();var Rn="remove [type]",bn=["rm","delete"],vn="Remove a firewall rule or IP entry from your configuration",En={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 Fi(n,e){let t=n.length,i=e.length;if(t===0)return i;if(i===0)return t;let r=Array.from({length:t+1},(a,l)=>l),s=new Array(t+1).fill(0);for(let a=1;a<=i;a++){s[0]=a;for(let l=1;l<=t;l++)e.charAt(a-1)===n.charAt(l-1)?s[l]=r[l-1]:s[l]=Math.min(r[l-1]+1,s[l-1]+1,r[l]+1);for(let l=0;l<=t;l++)r[l]=s[l]}return r[t]}function Vi(n,e,t=3){let i=n.toLowerCase(),r=e.filter(l=>l.name.toLowerCase().includes(i)||i.includes(l.name.toLowerCase()));if(r.length>0)return r.slice(0,t);let s=e.map(l=>({rule:l,distance:Fi(i,l.name.toLowerCase())})).sort((l,c)=>l.distance-c.distance),a=Math.max(n.length*.6,3);return s.filter(l=>l.distance<=a).slice(0,t).map(l=>l.rule)}function Dt(n){for(let e of n){let t=e.id?` (${e.id})`:"",i=e.active?"":_.default.dim(" [disabled]"),r=e.action.mitigate.action;o.log(_.default.dim(` - ${e.name}${t} \u2014 ${r}${i}`))}}function Oi(n){for(let e of n){let t=e.notes?` \u2014 ${e.notes}`:"";o.log(_.default.dim(` - ${e.ip}${t}`))}}async function xi(n,e,t,i="rule"){if(e)return!0;if(t)return await y(_.default.red(`\u26A0\uFE0F Are you sure you want to remove ALL ${i}s? Type "YES" to confirm:`),{type:"text"})==="YES";let r=n===1?`Confirm removal of 1 ${i}?`:`Confirm removal of ${n} ${i}s?`;return await y(r,{type:"confirm",initial:!1})}var An=async n=>{try{n.debug&&(o.level=Ni.LogLevels.debug),o.debug("Remove command arguments:",n);let e=n.type||"rule";o.start("Loading configuration...");let t=await F(n.config);if(e==="ip"){let i=t.ips||[];if(i.length===0){o.info("No IP rules in configuration.");return}let r=[];if(n.interactive){let l=i.map(d=>{let u=d.notes?` \u2014 ${d.notes}`:"";return`${d.ip}${u}`}),c=await y("Select IP rules to remove:",{type:"multiselect",options:l});r=i.filter(d=>{let u=`${d.ip}${d.notes?` \u2014 ${d.notes}`:""}`;return c.includes(u)})}else n.ip?(r=i.filter(l=>l.ip===n.ip),r.length===0&&(o.error(_.default.red(`No IP rule found matching "${n.ip}"`)),i.length>0&&(o.log(_.default.dim(`
|
|
115
|
+
Current IP rules:`)),Oi(i)),process.exit(1))):n.all?r=[...i]:(o.error("Specify --ip, --interactive, or --all to select IP rules to remove."),process.exit(1));if(r.length===0){o.info("No IP rules selected for removal.");return}if(o.log(_.default.cyan(`
|
|
116
|
+
${n.dryRun?"Would remove":"Removing"} ${r.length} IP rule(s):`)),Oi(r),n.dryRun){o.log(_.default.dim(`
|
|
117
|
+
Dry run \u2014 no changes made.`));return}if(!await xi(r.length,n.force||!1,n.all||!1,"IP rule")){o.info("Cancelled.");return}let s=new Set(r.map(l=>l.ip)),a={...t,ips:i.filter(l=>!s.has(l.ip))};await V(a,n.config),o.success(_.default.green(`\u2714 Removed ${r.length} IP rule(s) from configuration`))}else{let i=t.rules||[];if(i.length===0){o.info("No rules in configuration.");return}let r=[];if(n.interactive){let l=i.map((d,u)=>{let p=d.id?` (${d.id})`:"",m=d.active?"":" [disabled]",w=d.action.mitigate.action;return`[${u}] ${d.name}${p} \u2014 ${w}${m}`}),c=await y("Select rules to remove:",{type:"multiselect",options:l});r=i.filter((d,u)=>c.some(p=>p.startsWith(`[${u}]`)))}else if(n.name){if(r=i.filter(l=>l.name===n.name),r.length>1&&(o.warn(_.default.yellow(`
|
|
118
|
+
\u26A0\uFE0F Found ${r.length} rules named "${n.name}". All will be removed.`)),Dt(r)),r.length===0){o.error(_.default.red(`No rule found with exact name "${n.name}"`));let l=Vi(n.name,i);l.length>0&&(o.log(_.default.yellow(`
|
|
119
119
|
Did you mean one of these?`)),l.forEach((c,d)=>{let u=c.id?` (${c.id})`:"";o.log(_.default.dim(` ${d+1}. ${c.name}${u}`))}),o.log(_.default.dim(`
|
|
120
120
|
Use --id for exact matching, or --interactive to select from a list.`))),process.exit(1)}}else if(n.id&&n.id.length>0){let l=new Set(n.id);r=i.filter(u=>u.id&&l.has(u.id));let c=new Set(r.map(u=>u.id)),d=n.id.filter(u=>!c.has(u));d.length>0&&o.warn(_.default.yellow(`No rules found for IDs: ${d.join(", ")}`)),r.length===0&&(o.error(_.default.red("No matching rules found for the given IDs.")),process.exit(1))}else if(n.disabled){if(r=i.filter(l=>!l.active),r.length===0){o.info("No disabled rules found.");return}}else n.all?r=[...i]:(o.error("Specify --name, --id, --disabled, --all, or --interactive to select rules to remove."),process.exit(1));if(r.length===0){o.info("No rules selected for removal.");return}if(r.length>=5&&!n.dryRun&&!n.force&&o.log(_.default.yellow(`
|
|
121
121
|
\u{1F4A1} Tip: Run ${_.default.cyan("doorman backup")} before bulk removal operations.`)),o.log(_.default.cyan(`
|
|
122
|
-
${n.dryRun?"Would remove":"Removing"} ${r.length} rule(s):`)),
|
|
123
|
-
Dry run \u2014 no changes made.`));return}if(!await
|
|
124
|
-
`)),o.log(
|
|
125
|
-
`),o.log(
|
|
122
|
+
${n.dryRun?"Would remove":"Removing"} ${r.length} rule(s):`)),Dt(r),n.dryRun){o.log(_.default.dim(`
|
|
123
|
+
Dry run \u2014 no changes made.`));return}if(!await xi(r.length,n.force||!1,n.all||!1)){o.info("Cancelled.");return}let s=new Set(r),a={...t,rules:i.filter(l=>!s.has(l))};a.rules.length===0&&o.warn(_.default.yellow("\u26A0\uFE0F Configuration will have no rules after removal.")),await V(a,n.config),o.success(_.default.green(`\u2714 Removed ${r.length} rule(s) from configuration`)),Dt(r)}o.log(""),o.log(_.default.dim(`Run ${_.default.cyan("doorman sync")} to deploy these changes.`))}catch(e){M(e,"removing rule")}};var xt={};j(xt,{builder:()=>Pn,command:()=>$n,desc:()=>Tn,handler:()=>kn});var $=P(require("chalk"));E();var $n="setup",Tn="Show setup instructions and helpful links for Doorman",Pn={},kn=async n=>{o.log(""),o.log($.default.bold.cyan("\u{1F6AA} Doorman Setup Guide")),o.log($.default.dim(`Everything you need to get started with firewall management
|
|
124
|
+
`)),o.log($.default.bold("\u{1F4CB} Prerequisites")),o.log("\u2022 Vercel account with a deployed project"),o.log("\u2022 Project with Pro plan or higher (firewall feature requirement)"),o.log(`\u2022 Admin access to the project/team
|
|
125
|
+
`),o.log($.default.bold("\u{1F50D} Finding Your Project Information")),o.log(""),o.log($.default.cyan("1. Project ID:")),o.log(" \u2022 Go to https://vercel.com/dashboard"),o.log(" \u2022 Select your project"),o.log(" \u2022 Navigate to Settings \u2192 General"),o.log(" \u2022 Copy the Project ID from the top of the page"),o.log(""),o.log($.default.cyan("2. Team ID (if using team account):")),o.log(" \u2022 Go to https://vercel.com/dashboard"),o.log(" \u2022 Click on your team name in the top-left"),o.log(" \u2022 Go to Team Settings \u2192 General"),o.log(" \u2022 Copy the Team ID"),o.log(" \u2022 Leave empty if using personal account"),o.log(""),o.log($.default.bold("\u{1F511} Creating API Token")),o.log(""),o.log($.default.cyan("Steps:")),o.log(" 1. Visit https://vercel.com/account/tokens"),o.log(' 2. Click "Create Token"'),o.log(' 3. Name: "Doorman Firewall Management"'),o.log(" 4. Expiration: Set as needed (90 days recommended)"),o.log(" 5. Scope: Select your project or team"),o.log(" 6. Copy the generated token"),o.log(""),o.log($.default.cyan("Required Permissions:")),o.log(" \u2022 Read access to project settings"),o.log(" \u2022 Write access to firewall configuration"),o.log(""),o.log($.default.bold("\u{1F30D} Environment Setup")),o.log(""),o.log($.default.cyan("Set your API token as environment variable:")),o.log(""),o.log($.default.green("# For current session:")),o.log('export VERCEL_TOKEN="your-token-here"'),o.log(""),o.log($.default.green("# For permanent setup (add to ~/.bashrc or ~/.zshrc):")),o.log(`echo 'export VERCEL_TOKEN="your-token-here"' >> ~/.bashrc`),o.log(""),o.log($.default.green("# Or create a .env file in your project:")),o.log('echo "VERCEL_TOKEN=your-token-here" > .env'),o.log(""),o.log($.default.bold("\u{1F680} Quick Start Commands")),o.log(""),o.log($.default.cyan("1. Initialize configuration:")),o.log(" doorman init --interactive"),o.log(""),o.log($.default.cyan("2. Validate setup:")),o.log(" doorman validate"),o.log(""),o.log($.default.cyan("3. Check current status:")),o.log(" doorman status"),o.log(""),o.log($.default.cyan("4. View existing rules:")),o.log(" doorman list"),o.log(""),o.log($.default.cyan("5. Sync your configuration:")),o.log(" doorman sync"),o.log(""),o.log($.default.bold("\u{1F527} Common Issues")),o.log(""),o.log($.default.yellow('\u274C "Project not found" error:')),o.log(" \u2022 Double-check your Project ID"),o.log(" \u2022 Ensure your token has access to the project"),o.log(" \u2022 Verify the project has Pro plan or higher"),o.log(""),o.log($.default.yellow('\u274C "Unauthorized" error:')),o.log(" \u2022 Check your VERCEL_TOKEN is set correctly"),o.log(" \u2022 Ensure token hasn't expired"),o.log(" \u2022 Verify token has firewall permissions"),o.log(""),o.log($.default.yellow('\u274C "Firewall not available" error:')),o.log(" \u2022 Upgrade to Pro plan or higher"),o.log(" \u2022 Contact Vercel support if issue persists"),o.log(""),o.log($.default.bold("\u{1F4DA} Additional Resources")),o.log(""),o.log($.default.cyan("Documentation:")),o.log(" \u2022 Doorman Docs: https://doorman.griffen.codes"),o.log(" \u2022 Vercel Firewall: https://vercel.com/docs/security/vercel-firewall"),o.log(" \u2022 API Reference: https://vercel.com/docs/rest-api/endpoints/firewall"),o.log(""),o.log($.default.cyan("Support:")),o.log(" \u2022 GitHub Issues: https://github.com/gfargo/doorman/issues"),o.log(" \u2022 Vercel Support: https://vercel.com/help"),o.log(""),o.log($.default.bold("\u{1F512} Security Best Practices")),o.log(""),o.log("\u2022 Store API tokens securely (use environment variables)"),o.log("\u2022 Set token expiration dates"),o.log("\u2022 Use principle of least privilege for token scopes"),o.log("\u2022 Regularly rotate API tokens"),o.log("\u2022 Test rules in staging before production"),o.log("\u2022 Keep backups of working configurations"),o.log(""),o.log($.default.bold.green("\u2705 Ready to get started?")),o.log($.default.dim("Run: ")+$.default.cyan("doorman init --interactive")),o.log("")};var Nt={};j(Nt,{builder:()=>Ln,command:()=>_n,desc:()=>Sn,handler:()=>Un});var k=P(require("chalk"));E();var _n="status",Sn="Show sync status between local and remote firewall configuration",Ln={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:{type:"string",choices:["vercel","cloudflare"],description:"Firewall provider (auto-detected)"},projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Un=async n=>{await W({config:n.config,provider:n.provider,projectId:n.projectId,teamId:n.teamId,token:n.token,apiToken:n.apiToken,zoneId:n.zoneId,accountId:n.accountId,debug:n.debug,ci:n.ci,errorContext:"checking status"},async({config:e,provider:t})=>{await Dn(t,te(e))})};async function Dn(n,e){o.start("Checking sync status...");let t=await n.getChanges(e),i=e.metadata?.version,r=t.version!==void 0&&i!==void 0&&i!==t.version;o.log(k.default.bold(`
|
|
126
126
|
\u{1F4CA} ${n.name} Sync Status Summary
|
|
127
127
|
`)),t.version!==void 0&&(o.log(`${k.default.dim("Local Version:")} ${k.default.yellow(i??"unknown")}`),o.log(`${k.default.dim("Remote Version:")} ${k.default.yellow(t.version)}`),o.log(`${k.default.dim("Version Status:")} ${r?k.default.red("Out of sync"):k.default.green("In sync")}`),o.log("")),o.log(`${k.default.dim("Rules:")}`),o.log(` ${k.default.green("+")} ${t.rulesToAdd.length} to add`),o.log(` ${k.default.cyan("~")} ${t.rulesToUpdate.length} to update`),o.log(` ${k.default.red("-")} ${t.rulesToDelete.length} to delete`),o.log(`${k.default.dim("IPs:")}`),o.log(` ${k.default.green("+")} ${t.ipsToAdd?.length??0} to add`),o.log(` ${k.default.cyan("~")} ${t.ipsToUpdate?.length??0} to update`),o.log(` ${k.default.red("-")} ${t.ipsToDelete?.length??0} to delete`),o.log(""),!t.hasChanges&&!r?o.success(k.default.green("\u2705 Everything is in sync!")):o.warn(k.default.yellow("\u26A0\uFE0F Changes detected. Run `sync` to apply changes.")),o.log(`
|
|
128
128
|
`+k.default.bold("\u{1F3E5} Configuration Health Check"));let s=n.getHealthScore(e);o.log(`${k.default.dim("Score:")} ${s.score}/100 (${s.grade})`),s.issues.forEach(a=>{let l=a.severity==="error"?k.default.red("\u2717"):a.severity==="warning"?k.default.yellow("\u26A0"):k.default.dim("\u2139");o.log(` ${l} [${a.category}] ${a.message}`),a.suggestion&&o.log(` ${k.default.dim(a.suggestion)}`)}),s.recommendations.length>0&&(o.log(k.default.dim(`
|
|
129
|
-
Recommendations:`)),s.recommendations.forEach(a=>o.log(` - ${a}`)))}var
|
|
129
|
+
Recommendations:`)),s.recommendations.forEach(a=>o.log(` - ${a}`)))}var Bt={};j(Bt,{builder:()=>Nn,command:()=>On,desc:()=>xn,handler:()=>Fn});var B=P(require("chalk"));E();var On="sync",xn="Sync Vercel Firewall rules with config file",Nn={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:{type:"string",choices:["vercel","cloudflare"],description:"Firewall provider (auto-detected)"},projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},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}},Fn=async n=>{await W({config:n.config,provider:n.provider,projectId:n.projectId,teamId:n.teamId,token:n.token,apiToken:n.apiToken,zoneId:n.zoneId,accountId:n.accountId,debug:n.debug,ci:n.ci,errorContext:"syncing firewall rules"},async e=>{await Vn(e.provider,e.config,n)})};async function Vn(n,e,t){let i=te(e);o.start(B.default.magenta(`Calculating ${n.name} firewall configuration changes...`));let r=await n.getChanges(i),s=i.metadata?.version,a=r.version!==void 0&&s!==r.version;if(!r.hasChanges&&!a){o.success(B.default.green("No changes detected. Firewall rules are in sync."));return}o.log(B.default.bold(`
|
|
130
130
|
Proposed Changes:
|
|
131
|
-
`)),xt("Rules to add",r.rulesToAdd,V.default.green("+")),xt("Rules to update",r.rulesToUpdate,V.default.cyan("~")),xt("Rules to delete",r.rulesToDelete,V.default.red("-"));let l=r.ipsToAdd??[],c=r.ipsToUpdate??[],d=r.ipsToDelete??[];(l.length||c.length||d.length)&&(Nt("IPs to add",l,V.default.green("+")),Nt("IPs to update",c,V.default.cyan("~")),Nt("IPs to delete",d,V.default.red("-"))),a&&o.log(` Remote config version: ${V.default.red(s??"unknown")} ${V.default.dim("->")} ${V.default.green(r.version)}`),o.start("Starting firewall rules sync...");let u=await n.syncRules(i,{force:t.ci,allowDeletions:t.allowDeletions});if(!u.success)throw new Error(`Sync failed: ${u.errors?.join(", ")||"unknown error"}`);o.success(V.default.green("Firewall rules sync completed successfully")),o.log(` Rules: ${u.rulesAdded} added, ${u.rulesUpdated} updated, ${u.rulesDeleted} deleted`),(u.ipsAdded||u.ipsUpdated||u.ipsDeleted)&&o.log(` IPs: ${u.ipsAdded??0} added, ${u.ipsUpdated??0} updated, ${u.ipsDeleted??0} deleted`),u.warnings?.forEach(m=>o.warn(m)),u.idRemappings?.length&&(o.info(V.default.yellow("Rule IDs were reassigned by the provider and written back to the local config:")),u.idRemappings.forEach(m=>{o.log(` - ${m.name}: ${V.default.red(m.oldId||"none")} ${V.default.dim("->")} ${V.default.green(m.newId)}`)}));let p=Je(e,u);p.changed&&(await F(p.config,t.config),o.success(V.default.green("Updated local config with new version/metadata")))}function xt(n,e,t){e.length!==0&&(o.log(` ${t} ${n} (${e.length}):`),e.forEach(i=>o.log(` - ${i.name}`)))}function Nt(n,e,t){e.length!==0&&(o.log(` ${t} ${n} (${e.length}):`),e.forEach(i=>o.log(` - ${i.ip}${i.hostname?` (${i.hostname})`:""}`)))}var Bt={};B(Bt,{builder:()=>Vn,command:()=>Nn,desc:()=>Fn,handler:()=>zn});var pe=P(require("chalk")),zi=require("consola");E();var Ni={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 Fi={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 Vi={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 Bi={metadata:{title:"Deny Common WordPress URLs Firewall Rule",reference:"https://vercel.com/templates/other/block-wordpress-urls-firewall-rule"},config:{rules:[{name:"Deny WordPress URLs",description:"",conditionGroup:[{conditions:[{type:"path",op:"re",value:"/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-content|wp-includes|wp-signup\\.php|wp-activate\\.php|register\\.php|wp-register\\.php)"}]}],action:{mitigate:{action:"deny"}},active:!0}]}};var Vt={"ai-bots":Ni,"bad-bots":Fi,"block-ofac-sanctioned-countries":Vi,wordpress:Bi};var ji=n=>Vt[n]?.config;oe();var Nn="template [name]",Fn="Add a firewall rule template to your configuration",Vn={name:{type:"string",description:"Name of the template to add"},config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},dryRun:{alias:"d",type:"boolean",description:"Preview changes without applying them",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1}};function Bn(n,e){let t=new Set(n.map(r=>r.name.toLowerCase())),i=e.filter(r=>t.has(r.name.toLowerCase())).map(r=>r.name);return[...new Set(i)]}var jn=()=>Object.keys(Vt),zn=async n=>{try{n.debug&&(o.level=zi.LogLevels.debug),o.debug("Template command arguments:",n);let e=n.name;if(!e){let c=jn();e=await y("Select a template to add:",{type:"select",options:c,initial:c[0]})}let t=ji(e);t||(o.error(`Template not found: ${e}`),process.exit(1)),o.debug("Template content:",t),o.start("Loading current configuration...");let i=await N(n.config,"raw"),r=i.rules||[],s=Bn(r,t.rules);if(n.dryRun){o.info(pe.default.cyan(`
|
|
132
|
-
Dry run - The following rules would be added:`)),o.log(JSON.stringify(t.rules,null,2)),s.length>0&&o.warn(
|
|
133
|
-
`);let r=i?
|
|
134
|
-
AJV Schema Validation:`)),o.log(
|
|
135
|
-
AJV Schema Validation:`)),o.error(
|
|
136
|
-
Custom Validations:`));let l=r.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);o.log(`${
|
|
137
|
-
Rule Names:`)}`),d.size>0?(o.error(
|
|
138
|
-
`),o.info(
|
|
131
|
+
`)),Ft("Rules to add",r.rulesToAdd,B.default.green("+")),Ft("Rules to update",r.rulesToUpdate,B.default.cyan("~")),Ft("Rules to delete",r.rulesToDelete,B.default.red("-"));let l=r.ipsToAdd??[],c=r.ipsToUpdate??[],d=r.ipsToDelete??[];(l.length||c.length||d.length)&&(Vt("IPs to add",l,B.default.green("+")),Vt("IPs to update",c,B.default.cyan("~")),Vt("IPs to delete",d,B.default.red("-"))),a&&o.log(` Remote config version: ${B.default.red(s??"unknown")} ${B.default.dim("->")} ${B.default.green(r.version)}`),o.start("Starting firewall rules sync...");let u=await n.syncRules(i,{force:t.ci,allowDeletions:t.allowDeletions});if(!u.success)throw new Error(`Sync failed: ${u.errors?.join(", ")||"unknown error"}`);o.success(B.default.green("Firewall rules sync completed successfully")),o.log(` Rules: ${u.rulesAdded} added, ${u.rulesUpdated} updated, ${u.rulesDeleted} deleted`),(u.ipsAdded||u.ipsUpdated||u.ipsDeleted)&&o.log(` IPs: ${u.ipsAdded??0} added, ${u.ipsUpdated??0} updated, ${u.ipsDeleted??0} deleted`),u.warnings?.forEach(m=>o.warn(m)),u.idRemappings?.length&&(o.info(B.default.yellow("Rule IDs were reassigned by the provider and written back to the local config:")),u.idRemappings.forEach(m=>{o.log(` - ${m.name}: ${B.default.red(m.oldId||"none")} ${B.default.dim("->")} ${B.default.green(m.newId)}`)}));let p=rt(e,u);p.changed&&(await V(p.config,t.config),o.success(B.default.green("Updated local config with new version/metadata")))}function Ft(n,e,t){e.length!==0&&(o.log(` ${t} ${n} (${e.length}):`),e.forEach(i=>o.log(` - ${i.name}`)))}function Vt(n,e,t){e.length!==0&&(o.log(` ${t} ${n} (${e.length}):`),e.forEach(i=>o.log(` - ${i.ip}${i.hostname?` (${i.hostname})`:""}`)))}var zt={};j(zt,{builder:()=>zn,command:()=>Bn,desc:()=>jn,handler:()=>Wn});var ge=P(require("chalk")),Wi=require("consola");E();var Bi={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 ji={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 zi={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 qi={metadata:{title:"Deny Common WordPress URLs Firewall Rule",reference:"https://vercel.com/templates/other/block-wordpress-urls-firewall-rule"},config:{rules:[{name:"Deny WordPress URLs",description:"",conditionGroup:[{conditions:[{type:"path",op:"re",value:"/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-content|wp-includes|wp-signup\\.php|wp-activate\\.php|register\\.php|wp-register\\.php)"}]}],action:{mitigate:{action:"deny"}},active:!0}]}};var jt={"ai-bots":Bi,"bad-bots":ji,"block-ofac-sanctioned-countries":zi,wordpress:qi};var Mi=n=>jt[n]?.config;re();var Bn="template [name]",jn="Add a firewall rule template to your configuration",zn={name:{type:"string",description:"Name of the template to add"},config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},dryRun:{alias:"d",type:"boolean",description:"Preview changes without applying them",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1}};function qn(n,e){let t=new Set(n.map(r=>r.name.toLowerCase())),i=e.filter(r=>t.has(r.name.toLowerCase())).map(r=>r.name);return[...new Set(i)]}var Mn=()=>Object.keys(jt),Wn=async n=>{try{n.debug&&(o.level=Wi.LogLevels.debug),o.debug("Template command arguments:",n);let e=n.name;if(!e){let c=Mn();e=await y("Select a template to add:",{type:"select",options:c,initial:c[0]})}let t=Mi(e);t||(o.error(`Template not found: ${e}`),process.exit(1)),o.debug("Template content:",t),o.start("Loading current configuration...");let i=await F(n.config,"raw"),r=i.rules||[],s=qn(r,t.rules);if(n.dryRun){o.info(ge.default.cyan(`
|
|
132
|
+
Dry run - The following rules would be added:`)),o.log(JSON.stringify(t.rules,null,2)),s.length>0&&o.warn(ge.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`));return}if(s.length>0&&(o.warn(ge.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`)),!await y("Proceed anyway?",{type:"confirm",initial:!1}))){o.info("Cancelled.");return}let a={...i,rules:[...r,...t.rules]},l=pe.safeParse(a);l.success||(o.error(ge.default.red("The resulting configuration would be invalid:")),l.error.errors.forEach(c=>{let d=c.path.join(".");o.error(ge.default.red(` - ${d}: ${c.message}`))}),o.info(ge.default.dim("Template was not applied. Fix the issues above and try again.")),process.exit(1)),o.start("Saving updated configuration..."),await V(a,n.config,{validate:!1}),o.success(ge.default.green(`Successfully added template '${e}' to configuration`))}catch(e){M(e,"adding template")}};var qt={};j(qt,{builder:()=>Hn,command:()=>Gn,desc:()=>Zn,handler:()=>Kn});var H=P(require("chalk"));E();var Gn="validate",Zn="Validate firewall configuration file",Hn={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}},Kn=async n=>{try{let e=await F(n.config,"raw"),t=de.getInstance(),i=le(e);n.verbose&&o.start(`Validating configuration file...
|
|
133
|
+
`);let r=i?Ne.safeParse(e):pe.safeParse(e);n.verbose&&(o.log(H.default.bold.underline("Zod Schema Validation:")),r.success?o.log(H.default.green("\u2713 Schema validation passed")):(o.error(H.default.red("\u2717 Schema validation failed:")),r.error.errors.forEach(l=>{let c=l.path.join(".");o.error(H.default.red(` - ${c}: ${l.message}`))})));let s=!0,a=[];try{t.validateConfig(e),n.verbose&&(o.log(H.default.bold.underline(`
|
|
134
|
+
AJV Schema Validation:`)),o.log(H.default.green("\u2713 JSON Schema validation passed")))}catch(l){if(s=!1,l instanceof L)a=l.ajvErrors||[],n.verbose&&(o.log(H.default.bold.underline(`
|
|
135
|
+
AJV Schema Validation:`)),o.error(H.default.red("\u2717 JSON Schema validation failed:")),a.forEach(c=>{o.error(H.default.red(` - ${c.instancePath}: ${c.message}`))}));else throw l}if(r.success&&s&&n.verbose){o.log(H.default.bold.underline(`
|
|
136
|
+
Custom Validations:`));let l=r.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);o.log(`${H.default.cyan.dim(`
|
|
137
|
+
Rule Names:`)}`),d.size>0?(o.error(H.default.red("\u2717 Duplicate rule names found:")),d.forEach(u=>o.error(H.default.red(` - "${u}"`)))):o.log(H.default.green("\u2713 All rule names are unique")),o.log("")}if(r.success&&s)o.success(H.default.green("Configuration is valid"));else throw new Error("Configuration validation failed")}catch(e){M(e,"validating configuration")}};var Mt={};j(Mt,{builder:()=>Yn,command:()=>Jn,desc:()=>Qn,handler:()=>Xn});var oe=P(require("chalk")),st=require("fs");E();var Jn="watch",Qn="Watch config file for changes and auto-sync",Yn={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:{type:"string",choices:["vercel","cloudflare"],description:"Firewall provider (auto-detected)"},projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},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}},Xn=async n=>{let e=n.config||".doorman.json";await W({config:e,provider:n.provider,projectId:n.projectId,teamId:n.teamId,token:n.token,apiToken:n.apiToken,zoneId:n.zoneId,accountId:n.accountId,debug:n.debug,ci:n.ci,errorContext:"setting up watch mode"},async({provider:t})=>{let i=!1,r=0;o.success(oe.default.green(`\u{1F440} Watching ${e} for changes...`)),o.log(oe.default.dim("Press Ctrl+C to stop watching")),o.log("");let s=async(c,d)=>{if(!(i||c.mtime.getTime()===r)){i=!0,r=c.mtime.getTime();try{o.log(oe.default.yellow(`\u{1F4DD} Config file changed at ${new Date().toLocaleTimeString()}`)),o.start("Validating and syncing changes...");let u=await F(e);await er(t,u,e),o.log(oe.default.dim("Watching for more changes..."))}catch(u){o.error(oe.default.red(`\u274C Sync failed: ${u instanceof Error?u.message:String(u)}`)),o.log(oe.default.dim("Continuing to watch for changes..."))}finally{i=!1}}};(0,st.watchFile)(e,{interval:n.interval},s);let a=()=>{o.log(`
|
|
138
|
+
`),o.info(oe.default.yellow("Stopping watch mode...")),(0,st.unwatchFile)(e),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a);let l=()=>{setTimeout(l,1e3)};l()})};async function er(n,e,t){let i=te(e),r=await n.getChanges(i),s=i.metadata?.version,a=r.version!==void 0&&s!==r.version;if(!r.hasChanges&&!a){o.info(oe.default.blue("No changes detected, skipping sync"));return}let l=r.rulesToAdd.length+r.rulesToUpdate.length+r.rulesToDelete.length+(r.ipsToAdd?.length??0)+(r.ipsToUpdate?.length??0)+(r.ipsToDelete?.length??0);o.log(oe.default.cyan(`Syncing ${l} changes...`));let c=await n.syncRules(i,{force:!0,allowDeletions:!0});if(!c.success)throw new Error(`Sync failed: ${c.errors?.join(", ")||"unknown error"}`);o.success(oe.default.green(`\u2705 Sync completed at ${new Date().toLocaleTimeString()}`)),c.warnings?.forEach(u=>o.warn(u)),c.idRemappings?.length&&c.idRemappings.forEach(u=>{o.info(oe.default.dim(` Rule "${u.name}" ID updated: ${u.oldId||"none"} -> ${u.newId}`))});let d=rt(e,c);d.changed&&await V(d.config,t)}var Gi=[xt,Lt,Rt,Ut,Nt,kt,Bt,qt,_t,zt,Ot,Pt,St,Mt];(0,Zi.config)();async function tr(){let n=(await import("chalk")).default,e=(0,Hi.default)(process.argv.slice(2));e.usage(`${n.bold("\u{1F6AA} Doorman")}
|
|
139
139
|
|
|
140
|
-
${n.dim("Manage firewall rules as code across multiple providers")}`);for(let t of
|
|
140
|
+
${n.dim("Manage firewall rules as code across multiple providers")}`);for(let t of Gi)e.command(t);e.demandCommand(1,"You need at least one command before moving on").help().epilogue(n.dim(`See ${n.bold("https://doorman.griffen.codes/getting-started")} for more info`)).argv}tr().catch(console.error);
|