@gfargo/doorman 3.2.5 → 3.3.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 +56 -56
- package/dist/bin/run.mjs +56 -56
- package/package.json +1 -1
package/dist/bin/run.js
CHANGED
|
@@ -1,74 +1,74 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`),u.cancelled&&process.exit(0),e(n))};t.on("keypress",a)})}var
|
|
1
|
+
"use strict";var yo=Object.create;var it=Object.defineProperty;var wo=Object.getOwnPropertyDescriptor;var Ro=Object.getOwnPropertyNames;var Co=Object.getPrototypeOf,Io=Object.prototype.hasOwnProperty;var xe=(r,e)=>()=>(r&&(e=r(r=0)),e);var K=(r,e)=>{for(var t in e)it(r,t,{get:e[t],enumerable:!0})},li=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ro(e))!Io.call(r,n)&&n!==t&&it(r,n,{get:()=>e[n],enumerable:!(i=wo(e,n))||i.enumerable});return r};var S=(r,e,t)=>(t=r!=null?yo(Co(r)):{},li(e||!r||!r.__esModule?it(t,"default",{value:r,enumerable:!0}):t,r)),ce=r=>li(it({},"__esModule",{value:!0}),r);var ci,o,k=xe(()=>{"use strict";ci=require("consola"),o=(0,ci.createConsola)({formatOptions:{colors:!0,compact:!0,date:!1}})});var ui,C,de=xe(()=>{"use strict";ui=S(require("consola")),C=async(r,e)=>{let t=await ui.default.prompt(r,e);return t!=null&&t.toString()==="Symbol(clack:cancel)"&&process.exit(0),(!e?.type||e.type==="text")&&t===void 0?"":t}});function Zo(r,e){return e?.ctrl&&e.name==="c"?{type:"cancel"}:e?.name==="return"||e?.name==="enter"?{type:"submit"}:e?.name==="backspace"?{type:"backspace"}:r&&!e?.ctrl&&!e?.meta&&r.length===1&&r>=" "?{type:"append",char:r}:{type:"ignore"}}function Ko(r,e){switch(e.type){case"append":return{value:r+e.char,done:!1,cancelled:!1,echo:"add"};case"backspace":return r.length===0?{value:r,done:!1,cancelled:!1,echo:"none"}:{value:r.slice(0,-1),done:!1,cancelled:!1,echo:"remove"};case"submit":return{value:r,done:!0,cancelled:!1,echo:"none"};case"cancel":return{value:r,done:!0,cancelled:!0,echo:"none"};case"ignore":return{value:r,done:!1,cancelled:!1,echo:"none"}}}async function at(r){if(process.stdout.write(r),!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("",n=>{t.close(),i(n)})})}return new Promise(e=>{let t=process.stdin,i=t.isRaw;(0,Ui.emitKeypressEvents)(t),t.setRawMode(!0),t.resume();let n="",s=()=>{t.removeListener("keypress",a),t.setRawMode(i??!1)},a=(c,l)=>{let d=Zo(c,l),u=Ko(n,d);n=u.value,u.echo==="add"?process.stdout.write("*"):u.echo==="remove"&&process.stdout.write("\b \b"),u.done&&(s(),process.stdout.write(`
|
|
2
|
+
`),u.cancelled&&process.exit(0),e(n))};t.on("keypress",a)})}var Ui,Dt=xe(()=>{"use strict";Ui=require("readline")});var ge={};K(ge,{TranslationWarningSystem:()=>ct});var ct,ue=xe(()=>{"use strict";ct=class r{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:`${r.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:`${r.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:`${r.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:`${r.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:`${r.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:`${r.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:`${r.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:`${r.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:`${r.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:`${r.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:`${r.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:`${r.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:`${r.DOCS_BASE_URL}/migration/plan-limits`}};static createWarning(e,t,i,n,s){let a=this.WARNING_CONFIGS[e];return a?{rule:t,field:i,category:a.category,message:n||`${e.replace(/_/g," ")} translation issue`,explanation:a.explanation,severity:a.severity,suggestion:s||a.suggestion,alternativeApproach:a.alternativeApproach,impact:a.impact,docsUrl:a.docsUrl}:{rule:t,field:i,category:"compatibility_issue",message:n||`Unknown translation issue: ${e}`,explanation:"This translation scenario is not fully documented.",severity:"warning",suggestion:s||"Review the translated configuration manually and test thoroughly.",docsUrl:`${this.DOCS_BASE_URL}/migration/troubleshooting`}}static createUnsupportedFeatureWarning(e,t,i,n,s){return{rule:n,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,n){return{rule:i,field:n,category:"lossy_conversion",message:`${e} translation may be lossy`,explanation:`The ${e} configuration cannot be perfectly translated: ${t}`,severity:"warning",suggestion:"Review the translated configuration and test thoroughly to ensure it behaves as expected.",alternativeApproach:"Consider simplifying the configuration or using more portable alternatives.",impact:"The translated rule may behave differently than the original.",docsUrl:`${this.DOCS_BASE_URL}/migration/lossy-conversions`}}static createSyntaxLimitationWarning(e,t,i,n){return{rule:i,field:n,category:"syntax_limitation",message:`${e} has syntax limitations`,explanation:`The ${e} syntax has been modified due to provider limitations: ${t}`,severity:"warning",suggestion:"Verify the translated syntax works correctly in the target provider.",alternativeApproach:"Use simpler syntax or alternative approaches that are more widely supported.",impact:"The rule may not match traffic as precisely as intended.",docsUrl:`${this.DOCS_BASE_URL}/migration/syntax-limitations`}}static createPerformanceWarning(e,t,i,n){return{rule:i,field:n,category:"performance_impact",message:`${e} may impact performance`,explanation:`The ${e} configuration may have performance implications: ${t}`,severity:"info",suggestion:"Monitor performance after deployment and optimize if necessary.",alternativeApproach:"Consider using more efficient alternatives or breaking complex rules into simpler ones.",impact:"Request processing may be slower than expected.",docsUrl:`${this.DOCS_BASE_URL}/migration/performance`}}static formatWarning(e){let i={critical:"\u{1F6A8}",warning:"\u26A0\uFE0F",info:"\u2139\uFE0F"}[e.severity],n=e.rule?` (Rule: ${e.rule}${e.field?`, Field: ${e.field}`:""})`:"",s=`${i} ${e.severity.toUpperCase()}: ${e.message}${n}
|
|
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(n=>{t[n.severity]++,i[n.category]++}),{total:e.length,bySeverity:t,byCategory:i,hasBlockingIssues:t.critical>0}}}});var xt={};K(xt,{OperationSafety:()=>Ut});var Ut,Ot=xe(()=>{"use strict";
|
|
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(n=>{t[n.severity]++,i[n.category]++}),{total:e.length,bySeverity:t,byCategory:i,hasBlockingIssues:t.critical>0}}}});var xt={};K(xt,{OperationSafety:()=>Ut});var Ut,Ot=xe(()=>{"use strict";k();de();Ut=class{static async confirmDestructiveOperation(e){let{operation:t,target:i,changes:n,riskLevel:s,skipConfirmation:a=!1,dryRun:c=!1,allowDeletions:l=!1}=e;if(c)return o.info(`\u{1F50D} Dry run mode: Would perform ${t} on ${i}`),!0;let d=(n?.rulesToDelete?.length||0)+(n?.ipsToDelete?.length||0);if(a)return d>0&&!l?(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.`),n&&this.displayChangeSummary(n),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)}`),n&&this.displayChangeSummary(n),this.displayRiskWarnings(s,t);let u=this.getBackupRecommendation(t,s);u.recommended&&(o.warn(`
|
|
12
12
|
\u{1F4BE} Backup Recommended: ${u.reason}`),u.instructions.forEach(v=>{o.info(` \u2022 ${v}`)}));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
|
|
13
|
+
\u{1F504} Rollback Available: ${p.method}`),p.timeWindow&&o.info(` Time Window: ${p.timeWindow}`));let m=this.getConfirmationMessage(s,t);return await C(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 n=[],s=[],a={rulesToAdd:[],rulesToUpdate:[],rulesToDelete:[],ipsToAdd:[],ipsToUpdate:[],ipsToDelete:[],hasChanges:!1};try{this.validateConfigurationStructure(e,n),a=await i(e),this.validateChanges(a,s),this.checkForPotentialIssues(e,a,s);let c=n.length===0;return c?o.info("\u2705 Dry-run validation passed"):(o.warn(`\u26A0\uFE0F Dry-run validation found ${n.length} issues:`),n.forEach(l=>o.warn(` \u2022 ${l}`))),s.length>0&&(o.warn(`\u26A0\uFE0F Dry-run validation found ${s.length} warning(s):`),s.forEach(l=>o.warn(` \u2022 ${l}`))),{valid:c,changes:a,issues:n,warnings:s}}catch(c){let l=`Dry-run validation failed: ${c instanceof Error?c.message:String(c)}`;return n.push(l),o.error(l),{valid:!1,changes:a,issues:n,warnings:s}}}static assessOperationRisk(e,t){let i=t.rules.length,n=t.ips?.length||0,s=(e.rulesToDelete?.length||0)+(e.ipsToDelete?.length||0),a=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+s;return s===i&&i>0||s>0&&s/Math.max(i+n,1)>.5||a>50||t.rules.some(l=>l.action.type==="deny"&&l.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){let t=require("chalk");switch(e){case"low":return t.green("LOW");case"medium":return t.yellow("MEDIUM");case"high":return t.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"]},n={"clear all rules":["\u{1F6A8} This will remove ALL firewall protection","\u{1F6A8} Your application will be unprotected until new rules are added"],"delete ruleset":["\u{1F6A8} This action is IRREVERSIBLE","\u{1F6A8} All rules in the ruleset will be permanently deleted"]};o.info(`
|
|
15
|
-
\u26A0\uFE0F Warnings:`),i[e]?.forEach(s=>{o.warn(` ${s}`)}),n[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),n=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+i;if(i>0&&n>0){let s=i/n;s>.5&&t.push(`High deletion ratio detected: ${Math.round(s*100)}% of changes are deletions`)}n>100&&t.push(`Large number of changes detected: ${n} total changes`)}static checkForPotentialIssues(e,t,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 n=e.rules.filter(c=>c.action.type==="deny"&&c.conditions.some(l=>l.field==="path"&&(l.value==="/"||l.value==="*")));n.length>0&&i.push(`Found ${n.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(c=>c.name),a=s.filter((c,l)=>s.indexOf(c)!==l);a.length>0&&i.push(`Duplicate rule names found: ${[...new Set(a)].join(", ")}`)}}});var Ni={};K(Ni,{promptForCredentials:()=>nn});async function nn(r){let e=r.token||process.env.VERCEL_TOKEN||await at("What is your Vercel API Auth Token? (https://vercel.com/guides/how-do-i-use-a-vercel-api-access-token#creating-an-access-token) "),t=r.teamId||process.env.VERCEL_TEAM_ID||await R("What is your Vercel Team ID? (See https://vercel.com/docs/accounts/create-a-team#find-your-team-id)",{type:"text"}),i=r.projectId||process.env.VERCEL_PROJECT_ID||await R("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=xe(()=>{"use strict";de();Dt()});var fo=require("dotenv"),mo=k(require("yargs"));var St={};K(St,{builder:()=>Bo,command:()=>No,desc:()=>Vo,generateRuleId:()=>kt,handler:()=>Go});var j=k(require("chalk")),Pi=require("consola");P();var $=require("zod"),ot=$.z.number().int().positive().optional(),Io=$.z.string().ip().or($.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),ci=$.z.string().optional(),bo=$.z.enum(["eq","pre","suf","inc","sub","re","ex","nex"]),vo=$.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=$.z.object({op:bo,neg:$.z.boolean().optional(),type:vo,value:$.z.union([$.z.string(),$.z.array($.z.string()),$.z.array($.z.number())]).optional(),key:$.z.string().optional()}).refine(r=>{switch(r.type){case"ip_address":case"method":case"environment":case"protocol":return r.op==="eq"||r.op==="inc";default:return!0}},"Invalid operator for the given condition type").refine(r=>{let e=["header","cookie"];return!(e.includes(r.type)&&!r.key||e.includes(r.type)&&r.op!=="ex"&&r.op!=="nex"&&!r.value)},"Missing key from condition").refine(r=>!(["ex","nex"].includes(r.op)&&r.neg),"Negation is not supported for the given operator").refine(r=>!(r.op==="inc"&&!Array.isArray(r.value)),"When using `inc` operator, value must be an array"),ht=$.z.object({conditions:$.z.array(Eo).min(1,"Condition group must have at least one condition")}),$o=$.z.string().regex(/^\d+[smhd]$|^permanent$/),yt=$.z.object({requests:$.z.number().positive().int().refine(r=>r>0,"requests must be positive"),window:$.z.string().regex(/^\d+[smhd]$/).refine(r=>parseInt(r)>0,"window duration must be positive")}),Ao=$.z.object({location:$.z.string(),permanent:$.z.boolean().optional()}),To=$.z.enum(["log","deny","challenge","bypass","rate_limit","redirect"]),Po=$.z.object({action:To,rateLimit:yt.nullable().optional(),redirect:Ao.nullable().optional(),actionDuration:$o.nullable().optional()}),ko=$.z.object({mitigate:Po}),wt=$.z.object({id:ci,name:$.z.string(),description:$.z.string().optional(),conditionGroup:$.z.array(ht),action:ko,active:$.z.boolean()});var Ct=$.z.object({id:ci,ip:Io,hostname:$.z.string(),notes:$.z.string().optional(),action:$.z.literal("deny")}),So=$.z.object({projectId:$.z.string().optional(),teamId:$.z.string().optional()}),we=So.extend({rules:$.z.array(wt),ips:$.z.array(Ct).optional(),version:$.z.number().optional(),updatedAt:$.z.string().optional()});de();var Ie=require("fs"),Ei=require("path");P();var Ii=require("net"),bi=k(require("ajv"));var ui="https://doorman.griffen.codes/schema.json",pi={$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 D=require("zod");var _=require("zod"),Rt=_.z.string().optional(),Oe=_.z.string().ip().or(_.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),nt=_.z.string().datetime().or(_.z.string().optional()),gi=_.z.enum(["log","deny","challenge","bypass","rate_limit","redirect","allow","block"]),fi=_.z.enum(["eq","ne","contains","not_contains","starts_with","ends_with","matches","in","not_in","gt","ge","lt","le","exists","not_exists"]),mi=_.z.enum(["ip","country","region","city","asn","path","host","method","header","query","cookie","user_agent","referer","scheme","port"]),Tr=_.z.string().regex(/^\d+[smhd]$|^permanent$/),hi=_.z.object({requests:_.z.number().positive().int(),window:_.z.string().regex(/^\d+[smhd]$/),characteristics:_.z.array(_.z.string()).optional()}),yi=_.z.object({location:_.z.string().url(),statusCode:_.z.number().int().min(300).max(399).optional(),permanent:_.z.boolean().optional(),preserveQueryString:_.z.boolean().optional()}),It=_.z.object({version:_.z.number().int().positive().optional(),updatedAt:nt,createdAt:nt,lastSyncedAt:nt,migratedFrom:_.z.string().optional(),migratedAt:nt}),_o=_.z.enum(["vercel","cloudflare"]),wi=_.z.object({vercel:_.z.object({projectId:_.z.string().optional(),teamId:_.z.string().optional()}).optional(),cloudflare:_.z.object({zoneId:_.z.string().optional(),accountId:_.z.string().optional()}).optional()}),Ci=_.z.object({$schema:_.z.string().url().optional(),version:_.z.string().optional(),provider:_o.optional(),metadata:It.optional()});var Do=D.z.object({field:mi.or(D.z.string()),operator:fi,value:D.z.union([D.z.string(),D.z.number(),D.z.array(D.z.string()),D.z.array(D.z.number())]),negated:D.z.boolean().optional(),key:D.z.string().optional()}),Lo=D.z.object({type:gi,rateLimit:hi.optional(),redirect:yi.optional(),response:D.z.object({statusCode:D.z.number().int().min(100).max(599).optional(),content:D.z.string().optional(),contentType:D.z.string().optional()}).optional(),duration:D.z.string().optional()}),Uo=D.z.object({id:Rt,name:D.z.string().min(1,"Rule name is required"),description:D.z.string().optional(),enabled:D.z.boolean(),conditions:D.z.array(Do).min(1,"At least one condition is required"),conditionLogic:D.z.enum(["AND","OR"]).optional().default("AND"),action:Lo,priority:D.z.number().int().optional(),categories:D.z.array(D.z.string()).optional()}),xo=D.z.object({id:Rt,ip:Oe,hostname:D.z.string().optional(),notes:D.z.string().optional(),action:D.z.enum(["deny","allow"])}),bt=Ci.extend({providers:wi.optional(),rules:D.z.array(Uo),ips:D.z.array(xo).optional(),metadata:It.optional()}),Ri=r=>{let e=bt.safeParse(r);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 vt(r){return!!r&&typeof r=="object"&&"rules"in r&&Array.isArray(r.rules)}function Pe(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.provider=="string"||typeof e.providers=="object"&&e.providers!==null}var se=k(require("chalk")),Ce=class{static formatValidationError(e){let t=e.instancePath||"/",i=se.default.cyan(t);switch(e.keyword){case"type":return`${i}: Expected ${se.default.green(e.schema)}, got ${se.default.red(typeof e.data)}`;case"enum":{let n=e.params.allowedValues;return`${i}: Value must be one of: ${se.default.green(n.join(", "))}`}case"required":{let n=e.params;return`${i}: Missing required property ${se.default.yellow(n.missingProperty)}`}case"additionalProperties":{let n=e.params;return`${i}: Unknown property ${se.default.red(n.additionalProperty)}`}default:return`${i}: ${e.message}`}}static formatCustomError(e,t){return`${se.default.cyan(e)}: ${t}`}static wrapErrorBlock(e){let t=se.default.red.bold("Validation Errors:"),i=e.map(n=>` ${n}`).join(`
|
|
15
|
+
\u26A0\uFE0F Warnings:`),i[e]?.forEach(s=>{o.warn(` ${s}`)}),n[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),n=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+i;if(i>0&&n>0){let s=i/n;s>.5&&t.push(`High deletion ratio detected: ${Math.round(s*100)}% of changes are deletions`)}n>100&&t.push(`Large number of changes detected: ${n} total changes`)}static checkForPotentialIssues(e,t,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 n=e.rules.filter(c=>c.action.type==="deny"&&c.conditions.some(l=>l.field==="path"&&(l.value==="/"||l.value==="*")));n.length>0&&i.push(`Found ${n.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(c=>c.name),a=s.filter((c,l)=>s.indexOf(c)!==l);a.length>0&&i.push(`Duplicate rule names found: ${[...new Set(a)].join(", ")}`)}}});var Vi={};K(Vi,{promptForCredentials:()=>rn});async function rn(r){let e=r.token||process.env.VERCEL_TOKEN||await at("What is your Vercel API Auth Token? (https://vercel.com/guides/how-do-i-use-a-vercel-api-access-token#creating-an-access-token) "),t=r.teamId||process.env.VERCEL_TEAM_ID||await C("What is your Vercel Team ID? (See https://vercel.com/docs/accounts/create-a-team#find-your-team-id)",{type:"text"}),i=r.projectId||process.env.VERCEL_PROJECT_ID||await C("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 Bi=xe(()=>{"use strict";de();Dt()});var mo=require("dotenv"),ho=S(require("yargs"));var St={};K(St,{builder:()=>jo,command:()=>Vo,desc:()=>Bo,generateRuleId:()=>kt,handler:()=>Ho});var j=S(require("chalk")),ki=require("consola");k();var $=require("zod"),ot=$.z.number().int().positive().optional(),bo=$.z.string().ip().or($.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),di=$.z.string().optional(),vo=$.z.enum(["eq","pre","suf","inc","sub","re","ex","nex"]),Eo=$.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"]),$o=$.z.object({op:vo,neg:$.z.boolean().optional(),type:Eo,value:$.z.union([$.z.string(),$.z.array($.z.string()),$.z.array($.z.number())]).optional(),key:$.z.string().optional()}).refine(r=>{switch(r.type){case"ip_address":case"method":case"environment":case"protocol":return r.op==="eq"||r.op==="inc";default:return!0}},"Invalid operator for the given condition type").refine(r=>{let e=["header","cookie"];return!(e.includes(r.type)&&!r.key||e.includes(r.type)&&r.op!=="ex"&&r.op!=="nex"&&!r.value)},"Missing key from condition").refine(r=>!(["ex","nex"].includes(r.op)&&r.neg),"Negation is not supported for the given operator").refine(r=>!(r.op==="inc"&&!Array.isArray(r.value)),"When using `inc` operator, value must be an array"),yt=$.z.object({conditions:$.z.array($o).min(1,"Condition group must have at least one condition")}),Ao=$.z.string().regex(/^\d+[smhd]$|^permanent$/),wt=$.z.object({requests:$.z.number().positive().int().refine(r=>r>0,"requests must be positive"),window:$.z.string().regex(/^\d+[smhd]$/).refine(r=>parseInt(r)>0,"window duration must be positive")}),To=$.z.object({location:$.z.string(),permanent:$.z.boolean().optional()}),Po=$.z.enum(["log","deny","challenge","bypass","rate_limit","redirect"]),ko=$.z.object({action:Po,rateLimit:wt.nullable().optional(),redirect:To.nullable().optional(),actionDuration:Ao.nullable().optional()}),So=$.z.object({mitigate:ko}),Rt=$.z.object({id:di,name:$.z.string(),description:$.z.string().optional(),conditionGroup:$.z.array(yt),action:So,active:$.z.boolean()});var Ct=$.z.object({id:di,ip:bo,hostname:$.z.string(),notes:$.z.string().optional(),action:$.z.literal("deny")}),_o=$.z.object({projectId:$.z.string().optional(),teamId:$.z.string().optional()}),we=_o.extend({rules:$.z.array(Rt),ips:$.z.array(Ct).optional(),version:$.z.number().optional(),updatedAt:$.z.string().optional()});de();var Ie=require("fs"),$i=require("path");k();var bi=require("net"),vi=S(require("ajv"));var pi="https://doorman.griffen.codes/schema.json",gi={$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 D=require("zod");var _=require("zod"),It=_.z.string().optional(),Oe=_.z.string().ip().or(_.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),nt=_.z.string().datetime().or(_.z.string().optional()),fi=_.z.enum(["log","deny","challenge","bypass","rate_limit","redirect","allow","block"]),mi=_.z.enum(["eq","ne","contains","not_contains","starts_with","ends_with","matches","in","not_in","gt","ge","lt","le","exists","not_exists"]),hi=_.z.enum(["ip","country","region","city","asn","path","host","method","header","query","cookie","user_agent","referer","scheme","port"]),Pr=_.z.string().regex(/^\d+[smhd]$|^permanent$/),yi=_.z.object({requests:_.z.number().positive().int(),window:_.z.string().regex(/^\d+[smhd]$/),characteristics:_.z.array(_.z.string()).optional()}),wi=_.z.object({location:_.z.string().url(),statusCode:_.z.number().int().min(300).max(399).optional(),permanent:_.z.boolean().optional(),preserveQueryString:_.z.boolean().optional()}),bt=_.z.object({version:_.z.number().int().positive().optional(),updatedAt:nt,createdAt:nt,lastSyncedAt:nt,migratedFrom:_.z.string().optional(),migratedAt:nt}),Do=_.z.enum(["vercel","cloudflare"]),Ri=_.z.object({vercel:_.z.object({projectId:_.z.string().optional(),teamId:_.z.string().optional()}).optional(),cloudflare:_.z.object({zoneId:_.z.string().optional(),accountId:_.z.string().optional()}).optional()}),Ci=_.z.object({$schema:_.z.string().url().optional(),version:_.z.string().optional(),provider:Do.optional(),metadata:bt.optional()});var Lo=D.z.object({field:hi.or(D.z.string()),operator:mi,value:D.z.union([D.z.string(),D.z.number(),D.z.array(D.z.string()),D.z.array(D.z.number())]),negated:D.z.boolean().optional(),key:D.z.string().optional()}),Uo=D.z.object({type:fi,rateLimit:yi.optional(),redirect:wi.optional(),response:D.z.object({statusCode:D.z.number().int().min(100).max(599).optional(),content:D.z.string().optional(),contentType:D.z.string().optional()}).optional(),duration:D.z.string().optional()}),xo=D.z.object({id:It,name:D.z.string().min(1,"Rule name is required"),description:D.z.string().optional(),enabled:D.z.boolean(),conditions:D.z.array(Lo).min(1,"At least one condition is required"),conditionLogic:D.z.enum(["AND","OR"]).optional().default("AND"),action:Uo,priority:D.z.number().int().optional(),categories:D.z.array(D.z.string()).optional()}),Oo=D.z.object({id:It,ip:Oe,hostname:D.z.string().optional(),notes:D.z.string().optional(),action:D.z.enum(["deny","allow"])}),vt=Ci.extend({providers:Ri.optional(),rules:D.z.array(xo),ips:D.z.array(Oo).optional(),metadata:bt.optional()}),Ii=r=>{let e=vt.safeParse(r);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 Pe(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.provider=="string"||typeof e.providers=="object"&&e.providers!==null}var se=S(require("chalk")),Re=class{static formatValidationError(e){let t=e.instancePath||"/",i=se.default.cyan(t);switch(e.keyword){case"type":return`${i}: Expected ${se.default.green(e.schema)}, got ${se.default.red(typeof e.data)}`;case"enum":{let n=e.params.allowedValues;return`${i}: Value must be one of: ${se.default.green(n.join(", "))}`}case"required":{let n=e.params;return`${i}: Missing required property ${se.default.yellow(n.missingProperty)}`}case"additionalProperties":{let n=e.params;return`${i}: Unknown property ${se.default.red(n.additionalProperty)}`}default:return`${i}: ${e.message}`}}static formatCustomError(e,t){return`${se.default.cyan(e)}: ${t}`}static wrapErrorBlock(e){let t=se.default.red.bold("Validation Errors:"),i=e.map(n=>` ${n}`).join(`
|
|
16
16
|
`);return`${t}
|
|
17
17
|
${i}`}static formatDetailedRuleValidation(e,t){let i=se.default.cyan(`Rule: ${e}`),n=t.map(s=>{let a=s.passed?se.default.green("\u2713"):se.default.red("\u2717"),c=s.passed?se.default.green(s.name):se.default.red(s.name);return` ${a} ${c}`}).join(`
|
|
18
18
|
`);return`${i}
|
|
19
|
-
${n}`}};var B=class r extends Error{constructor(t,i,n,s=[]){super(t);this.ajvErrors=i;this.zodError=n;this.customErrors=s;this.name="ValidationError"}ajvErrors;zodError;customErrors;static formatErrors(t,i,n=[]){let s=[];return t?.length&&s.push(...t.map(
|
|
20
|
-
`+(l instanceof Error?l.message:String(l)),null)}let t=this.ajv.compile(this.schema),i=t(e),n=t.errors,s=we.safeParse(e),a;s.success||(a=s.error);let c=[];if(i&&s.success){try{this.validateRuleNames(e),this.validateRuleConditionGroup(e),this.validateRuleAction(e)}catch(l){if(l instanceof B)c.push(l.message,...l.customErrors||[]);else throw l}for(let l of e.rules){if(l.action.mitigate?.rateLimit){let d=
|
|
21
|
-
`+B.formatErrors(n,a,c),n,a,c)}validateRuleNames(e){let t=new Set;for(let i of e.rules){if(t.has(i.name))throw new B(`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 B(`Rule "${t.name}" has an empty condition group`,null);for(let n of i.conditions){if(!n.type||!n.op)throw new B(`Rule "${t.name}" has an invalid condition`,null);let s=n.type==="header"||n.type==="cookie",a=n.op==="ex"||n.op==="nex";if(s){if(!n.key||typeof n.key!="string")throw new B(`Rule "${t.name}" has an invalid condition`,null);if(!a&&(n.value===void 0||n.value===null))throw new B(`Rule "${t.name}" has an invalid condition`,null)}else if(n.value===void 0||n.value===null)throw new B(`Rule "${t.name}" has an invalid condition`,null);let c=Array.isArray(n.value)?n.value:n.value!==void 0?[n.value]:[];if(Array.isArray(n.value)&&c.length===0)throw new B(`Rule "${t.name}" has an invalid value in condition`,null);if(n.type==="ip_address"){for(let l of c)if(typeof l!="string"||!this.isValidIP(l))throw new B(`Rule "${t.name}" has an invalid IP address in condition`,null)}if(n.type==="geo_as_number")for(let l of c){let d=typeof l=="number"?l:parseInt(String(l),10);if(!this.isValidASN(String(d)))throw new B(`Rule "${t.name}" has an invalid ASN in condition`,null)}if(n.type==="path"&&(n.op==="eq"||n.op==="pre")){for(let l of c)if(typeof l!="string"||!this.isValidPath(l))throw new B(`Rule "${t.name}" has an invalid path in condition`,null)}}}else throw new B("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 B("Invalid rate limit configuration: requests must be positive",null);if(!i.rateLimit.window.match(/^\d+[smhd]$/))throw new B("Invalid rate limit configuration: invalid window format",null);if(parseInt(i.rateLimit.window)<=0)throw new B("Invalid rate limit configuration: window duration must be positive",null)}if(i?.actionDuration&&!i.actionDuration.match(/^\d+[smhd]$|^permanent$/))throw new B("Invalid action duration format: "+i.actionDuration,null);if(i?.redirect&&!i.redirect.location)throw new B("Invalid redirect configuration: location is required",null)}}isValidIP(e){let t=e.split("/"),i=t[0]??"",n=t[1],s=d=>{let u=d.split(".");return u.length!==4?!1:u.every(p=>{if(!/^\d{1,3}$/.test(p))return!1;let m=parseInt(p,10);return m>=0&&m<=255})},a=d=>(0,Ii.isIPv6)(d),c=s(i),l=a(i);if(!c&&!l)return!1;if(n!==void 0){let d=parseInt(n,10);if(Number.isNaN(d)||c&&(d<0||d>32)||l&&(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 vi=require("fs"),Ke=require("path"),Et=[".doorman.json","vercel-firewall.config.json"],Oo=Et[0],ke=class{static async findConfig(e){let{findUp:t}=await import("find-up");for(let i of Et){let n=await t(i,{cwd:e||process.cwd()});if(n)return n}}static async findProjectRoot(e){let t=await this.findConfig(e);return t?(0,Ke.dirname)(t):null}static configExists(e){return(0,vi.existsSync)((0,Ke.resolve)(e))}static getDefaultConfigPath(){return(0,Ke.resolve)(process.cwd(),Oo)}static getSupportedFileNames(){return Et}};async function H(r,e="required"){let t=Fo(e),i=r||await ke.findConfig();if(!i||!(0,Ie.existsSync)(i)){if(t==="optional")return o.debug("No config file found, returning empty config"),{};let s=ke.getDefaultConfigPath();throw new Error(`No config file found. Run \`doorman init\` to create one at ${s}, or use --config to specify a custom path.`)}let n;try{let s=(0,Ie.readFileSync)(i,"utf8");n=JSON.parse(s)}catch(s){throw s instanceof SyntaxError?new Error(`Invalid JSON in config file (${i}): ${s.message}`):s}if(t!=="raw")try{Re.getInstance().validateConfig(n)}catch(s){if(t==="lenient")o.warn("Config validation failed:",s);else throw s}return n}async function M(r,e,t={validate:!0,throwOnError:!0}){let i=e||await ke.findConfig()||ke.getDefaultConfigPath();if(t.validate)try{Re.getInstance().validateConfig(r)}catch(s){if(o.error("Config validation failed:",s),t.throwOnError)throw s}let n=(0,Ei.dirname)(i);(0,Ie.existsSync)(n)||(0,Ie.mkdirSync)(n,{recursive:!0}),(0,Ie.writeFileSync)(i,JSON.stringify(r,null,2)),o.debug(`Config saved to ${i}`)}function Fo(r){if(typeof r=="string")return r;let{validate:e=!0,throwOnError:t=!0}=r;return e?t?"required":"lenient":"raw"}var $t=k(require("chalk")),$i=require("zod");P();function ee(r,e){r instanceof SyntaxError?o.log(Ce.wrapErrorBlock(["Invalid JSON format in config file:",` ${r.message}`])):r instanceof $i.ZodError?(o.error($t.default.red("Schema validation failed:")),r.errors.forEach(t=>{let i=t.path.join(".");o.error($t.default.red(` - ${i}: ${t.message}`))})):r instanceof Error&&r.name==="ValidationError"?o.error(r):r instanceof Error&&r.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}:`,` ${r instanceof Error?r.message:String(r)}`])),process.exit(1)}var No="add [type]",Vo="Add a new firewall rule to your configuration",Bo={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}},At=["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"],Tt=["eq","pre","suf","inc","sub","re","ex","nex"],Pt=["log","deny","challenge","bypass","rate_limit","redirect"];function kt(r){let e=r.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 ki(r,e){return e==="inc"?r.split(",").map(t=>t.trim()):r}async function jo(){let r=await R("Rule name:",{type:"text"});if(!r.trim())throw new Error("Rule name cannot be empty");let e=await R("Description (optional):",{type:"text"}),t=[],i=!0;for(;i;){let u=[],p=!0;for(;p;){let m=await R("Condition type:",{type:"select",options:At,initial:"path"}),h=await R("Operator:",{type:"select",options:Tt,initial:"eq"}),v;(m==="header"||m==="cookie"||m==="query")&&(v=await R(`${m} key:`,{type:"text"}));let f;if(h!=="ex"&&h!=="nex"){let x=await R("Value:",{type:"text"});f=ki(x,h)}let E=h!=="ex"&&h!=="nex"?await R("Negate this condition?",{type:"confirm",initial:!1}):!1,U={type:m,op:h,...f!==void 0&&{value:f},...v&&{key:v},...E&&{neg:E}};u.push(U),p=await R("Add another condition to this group? (AND logic)",{type:"confirm",initial:!1})}t.push({conditions:u}),i=await R("Add another condition group? (OR logic)",{type:"confirm",initial:!1})}let n=await R("Action:",{type:"select",options:Pt,initial:"deny"}),s;if(n==="rate_limit"){let u=parseInt(await R("Max requests:",{type:"text",initial:"100"}),10),p=await R('Time window (e.g., "60s", "1m", "1h"):',{type:"text",initial:"60s"});s={requests:u,window:p}}let a;if(n==="redirect"){let u=await R("Redirect URL:",{type:"text"}),p=await R("Permanent redirect (301)?",{type:"confirm",initial:!1});a={location:u,...p&&{permanent:p}}}let c;(n==="deny"||n==="challenge")&&await R("Set action duration? (default: permanent)",{type:"confirm",initial:!1})&&(c=await R('Duration (e.g., "1h", "1d", "permanent"):',{type:"text",initial:"permanent"}));let l=await R("Enable rule immediately?",{type:"confirm",initial:!0});return{id:kt(r),name:r.trim(),...e.trim()&&{description:e.trim()},conditionGroup:t,action:{mitigate:{action:n,...s&&{rateLimit:s},...a&&{redirect:a},...c&&{actionDuration:c}}},active:l}}function zo(r){if(!r.name)throw new Error("--name is required in inline mode. Use --interactive for guided prompts.");if(!r.field)throw new Error("--field is required in inline mode (e.g., --field path)");if(!r.op)throw new Error("--op is required in inline mode (e.g., --op eq)");let e=r.op;if(!Tt.includes(e))throw new Error(`Invalid operator "${r.op}". Valid operators: ${Tt.join(", ")}`);let t=r.field;if(!At.includes(t))throw new Error(`Invalid field type "${r.field}". Valid types: ${At.join(", ")}`);let i=r.action||"deny";if(!Pt.includes(i))throw new Error(`Invalid action "${r.action}". Valid actions: ${Pt.join(", ")}`);if(e!=="ex"&&e!=="nex"&&!r.value)throw new Error("--value is required for the given operator");if((t==="header"||t==="cookie"||t==="query")&&!r.key)throw new Error(`--key is required for "${t}" condition type`);if(i==="rate_limit"&&(!r.requests||!r.window))throw new Error("--requests and --window are required when action is rate_limit");if(i==="redirect"&&!r.location)throw new Error("--location is required when action is redirect");let n=r.value?ki(r.value,e):void 0,s={type:t,op:e,...n!==void 0&&{value:n},...r.key&&{key:r.key},...r.neg&&{neg:!0}};return{id:kt(r.name),name:r.name.trim(),...r.description&&{description:r.description},conditionGroup:[{conditions:[s]}],action:{mitigate:{action:i,...i==="rate_limit"&&r.requests&&r.window&&{rateLimit:{requests:r.requests,window:r.window}},...i==="redirect"&&r.location&&{redirect:{location:r.location,...r.permanent&&{permanent:!0}}},...r.duration&&{actionDuration:r.duration}}},active:r.active!==!1}}async function Wo(){let r=await R("IP address or CIDR (e.g., 192.168.1.100/32):",{type:"text"});if(!r.trim())throw new Error("IP address cannot be empty");let e=await R("Hostname (use * for all):",{type:"text",initial:"*"}),t=await R("Notes (optional):",{type:"text"});return{ip:r.trim(),hostname:e.trim()||"*",...t.trim()&&{notes:t.trim()},action:"deny"}}function Mo(r){if(!r.ip)throw new Error("--ip is required for IP blocking rules");return{ip:r.ip.trim(),hostname:r.hostname||"*",...r.notes&&{notes:r.notes},action:"deny"}}function qo(r,e){if(r.rules.map(n=>n.name.toLowerCase()).includes(e.name.toLowerCase()))return`A rule named "${e.name}" already exists`;let i=r.rules.map(n=>n.id).filter(Boolean);return e.id&&i.includes(e.id)?`A rule with ID "${e.id}" already exists`:null}function Ai(r){o.log(""),o.log(j.default.bold(` Rule: ${r.name}`)),r.description&&o.log(j.default.dim(` Description: ${r.description}`)),o.log(j.default.dim(` ID: ${r.id}`));let e=r.conditionGroup.map(n=>n.conditions.map(s=>{let a=s.neg?"NOT ":"",c=s.key?`[${s.key}] `:"",l=Array.isArray(s.value)?s.value.join(", "):s.value||"";return`${a}${s.type} ${c}${s.op} "${l}"`}).join(" AND "));o.log(j.default.dim(` Conditions: ${e.join(" OR ")}`));let t=r.action.mitigate.action,i=[];r.action.mitigate.rateLimit&&i.push(`${r.action.mitigate.rateLimit.requests} req/${r.action.mitigate.rateLimit.window}`),r.action.mitigate.redirect&&i.push(`\u2192 ${r.action.mitigate.redirect.location}`),r.action.mitigate.actionDuration&&i.push(`duration: ${r.action.mitigate.actionDuration}`),o.log(j.default.dim(` Action: ${t}${i.length?` (${i.join(", ")})`:""}`)),o.log(j.default.dim(` Active: ${r.active?"\u2705":"\u274C"}`))}function Ti(r){o.log(""),o.log(j.default.bold(` IP Rule: ${r.ip}`)),o.log(j.default.dim(` Hostname: ${r.hostname}`)),r.notes&&o.log(j.default.dim(` Notes: ${r.notes}`)),o.log(j.default.dim(` Action: ${r.action}`))}var Go=async r=>{try{if(r.debug&&(o.level=Pi.LogLevels.debug),o.debug("Add command arguments:",r),(r.type||"rule")==="ip"){let t=r.interactive?await Wo():Mo(r),i=Ct.safeParse(t);if(i.success||(o.error(j.default.red("Rule validation failed:")),i.error.errors.forEach(a=>{let c=a.path.join(".");o.error(j.default.red(` - ${c||"ip"}: ${a.message}`))}),process.exit(1)),r.dryRun){o.info(j.default.cyan(`
|
|
22
|
-
Dry run - The following IP rule would be added:`)),
|
|
23
|
-
Dry run - The following rule would be added:`)),
|
|
19
|
+
${n}`}};var B=class r extends Error{constructor(t,i,n,s=[]){super(t);this.ajvErrors=i;this.zodError=n;this.customErrors=s;this.name="ValidationError"}ajvErrors;zodError;customErrors;static formatErrors(t,i,n=[]){let s=[];return t?.length&&s.push(...t.map(Re.formatValidationError)),i&&s.push(...i.errors.map(a=>`${a.path.join(".")}: ${a.message}`)),n.length&&s.push(...n),Re.wrapErrorBlock(s)}getFormattedMessage(){return r.formatErrors(this.ajvErrors,this.zodError,this.customErrors)}},Ce=class r{static instance;ajv;schema;constructor(){this.ajv=new vi.default({allErrors:!0,verbose:!0}),this.schema=gi}static getInstance(){return r.instance||(r.instance=new r),r.instance}validateConfig(e){if(Pe(e))try{Ii(e);return}catch(l){throw new B(`Invalid firewall configuration:
|
|
20
|
+
`+(l instanceof Error?l.message:String(l)),null)}let t=this.ajv.compile(this.schema),i=t(e),n=t.errors,s=we.safeParse(e),a;s.success||(a=s.error);let c=[];if(i&&s.success){try{this.validateRuleNames(e),this.validateRuleConditionGroup(e),this.validateRuleAction(e)}catch(l){if(l instanceof B)c.push(l.message,...l.customErrors||[]);else throw l}for(let l of e.rules){if(l.action.mitigate?.rateLimit){let d=wt.safeParse(l.action.mitigate.rateLimit);d.success||c.push(...d.error.errors.map(u=>u.message))}if(l.conditionGroup)for(let d of l.conditionGroup){let u=yt.safeParse(d);u.success||c.push(...u.error.errors.map(p=>p.message))}}}if(!i||!s.success||c.length>0)throw new B(`Invalid firewall configuration:
|
|
21
|
+
`+B.formatErrors(n,a,c),n,a,c)}validateRuleNames(e){let t=new Set;for(let i of e.rules){if(t.has(i.name))throw new B(`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 B(`Rule "${t.name}" has an empty condition group`,null);for(let n of i.conditions){if(!n.type||!n.op)throw new B(`Rule "${t.name}" has an invalid condition`,null);let s=n.type==="header"||n.type==="cookie",a=n.op==="ex"||n.op==="nex";if(s){if(!n.key||typeof n.key!="string")throw new B(`Rule "${t.name}" has an invalid condition`,null);if(!a&&(n.value===void 0||n.value===null))throw new B(`Rule "${t.name}" has an invalid condition`,null)}else if(n.value===void 0||n.value===null)throw new B(`Rule "${t.name}" has an invalid condition`,null);let c=Array.isArray(n.value)?n.value:n.value!==void 0?[n.value]:[];if(Array.isArray(n.value)&&c.length===0)throw new B(`Rule "${t.name}" has an invalid value in condition`,null);if(n.type==="ip_address"){for(let l of c)if(typeof l!="string"||!this.isValidIP(l))throw new B(`Rule "${t.name}" has an invalid IP address in condition`,null)}if(n.type==="geo_as_number")for(let l of c){let d=typeof l=="number"?l:parseInt(String(l),10);if(!this.isValidASN(String(d)))throw new B(`Rule "${t.name}" has an invalid ASN in condition`,null)}if(n.type==="path"&&(n.op==="eq"||n.op==="pre")){for(let l of c)if(typeof l!="string"||!this.isValidPath(l))throw new B(`Rule "${t.name}" has an invalid path in condition`,null)}}}else throw new B("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 B("Invalid rate limit configuration: requests must be positive",null);if(!i.rateLimit.window.match(/^\d+[smhd]$/))throw new B("Invalid rate limit configuration: invalid window format",null);if(parseInt(i.rateLimit.window)<=0)throw new B("Invalid rate limit configuration: window duration must be positive",null)}if(i?.actionDuration&&!i.actionDuration.match(/^\d+[smhd]$|^permanent$/))throw new B("Invalid action duration format: "+i.actionDuration,null);if(i?.redirect&&!i.redirect.location)throw new B("Invalid redirect configuration: location is required",null)}}isValidIP(e){let t=e.split("/"),i=t[0]??"",n=t[1],s=d=>{let u=d.split(".");return u.length!==4?!1:u.every(p=>{if(!/^\d{1,3}$/.test(p))return!1;let m=parseInt(p,10);return m>=0&&m<=255})},a=d=>(0,bi.isIPv6)(d),c=s(i),l=a(i);if(!c&&!l)return!1;if(n!==void 0){let d=parseInt(n,10);if(Number.isNaN(d)||c&&(d<0||d>32)||l&&(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 Ei=require("fs"),Ke=require("path"),Et=[".doorman.json","vercel-firewall.config.json"],No=Et[0],ke=class{static async findConfig(e){let{findUp:t}=await import("find-up");for(let i of Et){let n=await t(i,{cwd:e||process.cwd()});if(n)return n}}static async findProjectRoot(e){let t=await this.findConfig(e);return t?(0,Ke.dirname)(t):null}static configExists(e){return(0,Ei.existsSync)((0,Ke.resolve)(e))}static getDefaultConfigPath(){return(0,Ke.resolve)(process.cwd(),No)}static getSupportedFileNames(){return Et}};async function H(r,e="required"){let t=Fo(e),i=r||await ke.findConfig();if(!i||!(0,Ie.existsSync)(i)){if(t==="optional")return o.debug("No config file found, returning empty config"),{};let s=ke.getDefaultConfigPath();throw new Error(`No config file found. Run \`doorman init\` to create one at ${s}, or use --config to specify a custom path.`)}let n;try{let s=(0,Ie.readFileSync)(i,"utf8");n=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(n)}catch(s){if(t==="lenient")o.warn("Config validation failed:",s);else throw s}return n}async function M(r,e,t={validate:!0,throwOnError:!0}){let i=e||await ke.findConfig()||ke.getDefaultConfigPath();if(t.validate)try{Ce.getInstance().validateConfig(r)}catch(s){if(o.error("Config validation failed:",s),t.throwOnError)throw s}let n=(0,$i.dirname)(i);(0,Ie.existsSync)(n)||(0,Ie.mkdirSync)(n,{recursive:!0}),(0,Ie.writeFileSync)(i,JSON.stringify(r,null,2)),o.debug(`Config saved to ${i}`)}function Fo(r){if(typeof r=="string")return r;let{validate:e=!0,throwOnError:t=!0}=r;return e?t?"required":"lenient":"raw"}var $t=S(require("chalk")),Ai=require("zod");k();function ee(r,e){r instanceof SyntaxError?o.log(Re.wrapErrorBlock(["Invalid JSON format in config file:",` ${r.message}`])):r instanceof Ai.ZodError?(o.error($t.default.red("Schema validation failed:")),r.errors.forEach(t=>{let i=t.path.join(".");o.error($t.default.red(` - ${i}: ${t.message}`))})):r instanceof Error&&r.name==="ValidationError"?o.error(r):r instanceof Error&&r.message.includes("Forbidden")?o.log(Re.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(Re.wrapErrorBlock([`Error ${e}:`,` ${r instanceof Error?r.message:String(r)}`])),process.exit(1)}var Vo="add [type]",Bo="Add a new firewall rule to your configuration",jo={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}},At=["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"],Tt=["eq","pre","suf","inc","sub","re","ex","nex"],Pt=["log","deny","challenge","bypass","rate_limit","redirect"];function kt(r){let e=r.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 Si(r,e){return e==="inc"?r.split(",").map(t=>t.trim()):r}async function zo(){let r=await C("Rule name:",{type:"text"});if(!r.trim())throw new Error("Rule name cannot be empty");let e=await C("Description (optional):",{type:"text"}),t=[],i=!0;for(;i;){let u=[],p=!0;for(;p;){let m=await C("Condition type:",{type:"select",options:At,initial:"path"}),h=await C("Operator:",{type:"select",options:Tt,initial:"eq"}),v;(m==="header"||m==="cookie"||m==="query")&&(v=await C(`${m} key:`,{type:"text"}));let f;if(h!=="ex"&&h!=="nex"){let x=await C("Value:",{type:"text"});f=Si(x,h)}let E=h!=="ex"&&h!=="nex"?await C("Negate this condition?",{type:"confirm",initial:!1}):!1,U={type:m,op:h,...f!==void 0&&{value:f},...v&&{key:v},...E&&{neg:E}};u.push(U),p=await C("Add another condition to this group? (AND logic)",{type:"confirm",initial:!1})}t.push({conditions:u}),i=await C("Add another condition group? (OR logic)",{type:"confirm",initial:!1})}let n=await C("Action:",{type:"select",options:Pt,initial:"deny"}),s;if(n==="rate_limit"){let u=parseInt(await C("Max requests:",{type:"text",initial:"100"}),10),p=await C('Time window (e.g., "60s", "1m", "1h"):',{type:"text",initial:"60s"});s={requests:u,window:p}}let a;if(n==="redirect"){let u=await C("Redirect URL:",{type:"text"}),p=await C("Permanent redirect (301)?",{type:"confirm",initial:!1});a={location:u,...p&&{permanent:p}}}let c;(n==="deny"||n==="challenge")&&await C("Set action duration? (default: permanent)",{type:"confirm",initial:!1})&&(c=await C('Duration (e.g., "1h", "1d", "permanent"):',{type:"text",initial:"permanent"}));let l=await C("Enable rule immediately?",{type:"confirm",initial:!0});return{id:kt(r),name:r.trim(),...e.trim()&&{description:e.trim()},conditionGroup:t,action:{mitigate:{action:n,...s&&{rateLimit:s},...a&&{redirect:a},...c&&{actionDuration:c}}},active:l}}function Wo(r){if(!r.name)throw new Error("--name is required in inline mode. Use --interactive for guided prompts.");if(!r.field)throw new Error("--field is required in inline mode (e.g., --field path)");if(!r.op)throw new Error("--op is required in inline mode (e.g., --op eq)");let e=r.op;if(!Tt.includes(e))throw new Error(`Invalid operator "${r.op}". Valid operators: ${Tt.join(", ")}`);let t=r.field;if(!At.includes(t))throw new Error(`Invalid field type "${r.field}". Valid types: ${At.join(", ")}`);let i=r.action||"deny";if(!Pt.includes(i))throw new Error(`Invalid action "${r.action}". Valid actions: ${Pt.join(", ")}`);if(e!=="ex"&&e!=="nex"&&!r.value)throw new Error("--value is required for the given operator");if((t==="header"||t==="cookie"||t==="query")&&!r.key)throw new Error(`--key is required for "${t}" condition type`);if(i==="rate_limit"&&(!r.requests||!r.window))throw new Error("--requests and --window are required when action is rate_limit");if(i==="redirect"&&!r.location)throw new Error("--location is required when action is redirect");let n=r.value?Si(r.value,e):void 0,s={type:t,op:e,...n!==void 0&&{value:n},...r.key&&{key:r.key},...r.neg&&{neg:!0}};return{id:kt(r.name),name:r.name.trim(),...r.description&&{description:r.description},conditionGroup:[{conditions:[s]}],action:{mitigate:{action:i,...i==="rate_limit"&&r.requests&&r.window&&{rateLimit:{requests:r.requests,window:r.window}},...i==="redirect"&&r.location&&{redirect:{location:r.location,...r.permanent&&{permanent:!0}}},...r.duration&&{actionDuration:r.duration}}},active:r.active!==!1}}async function Mo(){let r=await C("IP address or CIDR (e.g., 192.168.1.100/32):",{type:"text"});if(!r.trim())throw new Error("IP address cannot be empty");let e=await C("Hostname (use * for all):",{type:"text",initial:"*"}),t=await C("Notes (optional):",{type:"text"});return{ip:r.trim(),hostname:e.trim()||"*",...t.trim()&&{notes:t.trim()},action:"deny"}}function qo(r){if(!r.ip)throw new Error("--ip is required for IP blocking rules");return{ip:r.ip.trim(),hostname:r.hostname||"*",...r.notes&&{notes:r.notes},action:"deny"}}function Go(r,e){if(r.rules.map(n=>n.name.toLowerCase()).includes(e.name.toLowerCase()))return`A rule named "${e.name}" already exists`;let i=r.rules.map(n=>n.id).filter(Boolean);return e.id&&i.includes(e.id)?`A rule with ID "${e.id}" already exists`:null}function Ti(r){o.log(""),o.log(j.default.bold(` Rule: ${r.name}`)),r.description&&o.log(j.default.dim(` Description: ${r.description}`)),o.log(j.default.dim(` ID: ${r.id}`));let e=r.conditionGroup.map(n=>n.conditions.map(s=>{let a=s.neg?"NOT ":"",c=s.key?`[${s.key}] `:"",l=Array.isArray(s.value)?s.value.join(", "):s.value||"";return`${a}${s.type} ${c}${s.op} "${l}"`}).join(" AND "));o.log(j.default.dim(` Conditions: ${e.join(" OR ")}`));let t=r.action.mitigate.action,i=[];r.action.mitigate.rateLimit&&i.push(`${r.action.mitigate.rateLimit.requests} req/${r.action.mitigate.rateLimit.window}`),r.action.mitigate.redirect&&i.push(`\u2192 ${r.action.mitigate.redirect.location}`),r.action.mitigate.actionDuration&&i.push(`duration: ${r.action.mitigate.actionDuration}`),o.log(j.default.dim(` Action: ${t}${i.length?` (${i.join(", ")})`:""}`)),o.log(j.default.dim(` Active: ${r.active?"\u2705":"\u274C"}`))}function Pi(r){o.log(""),o.log(j.default.bold(` IP Rule: ${r.ip}`)),o.log(j.default.dim(` Hostname: ${r.hostname}`)),r.notes&&o.log(j.default.dim(` Notes: ${r.notes}`)),o.log(j.default.dim(` Action: ${r.action}`))}var Ho=async r=>{try{if(r.debug&&(o.level=ki.LogLevels.debug),o.debug("Add command arguments:",r),(r.type||"rule")==="ip"){let t=r.interactive?await Mo():qo(r),i=Ct.safeParse(t);if(i.success||(o.error(j.default.red("Rule validation failed:")),i.error.errors.forEach(a=>{let c=a.path.join(".");o.error(j.default.red(` - ${c||"ip"}: ${a.message}`))}),process.exit(1)),r.dryRun){o.info(j.default.cyan(`
|
|
22
|
+
Dry run - The following IP rule would be added:`)),Pi(t),o.log(""),o.log(j.default.dim(JSON.stringify(t,null,2)));return}o.start("Loading configuration...");let n=await H(r.config,"raw"),s={...n,ips:[...n.ips||[],t]};await M(s,r.config),o.success(j.default.green(`\u2714 IP rule "${t.ip}" added to configuration`)),Pi(t)}else{let t=r.interactive?await zo():Wo(r),i=Rt.safeParse(t);if(i.success||(o.error(j.default.red("Rule validation failed:")),i.error.errors.forEach(l=>{let d=l.path.join(".")||"rule";o.error(j.default.red(` - ${d}: ${l.message}`))}),process.exit(1)),r.dryRun){o.info(j.default.cyan(`
|
|
23
|
+
Dry run - The following rule would be added:`)),Ti(t),o.log(""),o.log(j.default.dim(JSON.stringify(t,null,2)));return}o.start("Loading configuration...");let n=await H(r.config,"raw"),s=n.rules||[],a=Go({...n,rules:s},t);if(a&&(o.warn(j.default.yellow(`\u26A0\uFE0F ${a}`)),!await C("Proceed anyway?",{type:"confirm",initial:!1}))){o.info("Cancelled.");return}let c={...n,rules:[...s,t]};await M(c,r.config),o.success(j.default.green(`\u2714 Rule "${t.name}" added to configuration`)),Ti(t)}o.log(""),o.log(j.default.dim(`Run ${j.default.cyan("doorman sync")} to deploy this rule.`))}catch(e){ee(e,"adding rule")}};var Ft={};K(Ft,{builder:()=>un,command:()=>cn,desc:()=>dn,handler:()=>pn});var oe=S(require("chalk")),me=require("fs"),ut=require("path"),Mi=require("consola");k();de();var Wi=require("consola");k();var te=S(require("chalk")),Di=require("consola");k();function ae(r,e){if(r===e)return!0;if(typeof r!="object"||r===null||typeof e!="object"||e===null||Array.isArray(r)!==Array.isArray(e))return!1;let t=Object.keys(r),i=Object.keys(e);if(t.length!==i.length)return!1;for(let n of t)if(!i.includes(n)||!ae(r[n],e[n]))return!1;return!0}function z(r){let{id:e,...t}=r;return t}k();async function ve(r,e={}){let{maxAttempts:t=3,delayMs:i=1e3,backoff:n=!0}=e,s;for(let a=1;a<=t;a++)try{return await r()}catch(c){if(s=c instanceof Error?c:new Error(String(c)),a===t)break;let l=n?i*a:i;o.debug(`Retry attempt ${a}/${t} failed. Retrying in ${l}ms...`),await new Promise(d=>setTimeout(d,l))}throw o.debug(`Operation failed after ${t} attempts.`),s??new Error(`Operation failed after ${t} attempts`)}function _i(r){if(!r||r.trim().length===0)return"";let e=r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2"),t=["IP","HTTP","XML","API"];return t.forEach(i=>{let n=new RegExp(`\\b${i}\\b`,"g");e=e.replace(n,i.toLowerCase())}),e=e.replace(/[A-Z]{2,}/g,i=>t.includes(i)?i.toLowerCase():i.split("").join("_")).toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_"),t.forEach(i=>{let n=i.toLowerCase();e=e.replace(new RegExp(`([a-z])${n}`,"g"),`$1_${n}`)}),e}var rt=class{constructor(e){this.client=e}client;async getChanges(e){try{let t=we.safeParse(e);if(!t.success)throw new Error(`Invalid firewall configuration: ${t.error.message}`);o.debug("Fetching existing firewall configuration");let i=await this.client.fetchFirewallConfig();o.debug(`Fetched ${i.rules.length} custom rules and ${i.ips.length} IP blocking rules`);let n=e.rules,{toAdd:s,toUpdate:a,toDelete:c}=this.diffRules(n,i.rules);o.debug("Pre Filter IP Rules:",{ips:e.ips,activeConfig:i.ips});let{ipsToAdd:l,ipsToUpdate:d,ipsToDelete:u}=this.diffIPRules(e.ips||[],i.ips);return{version:i.version,toAdd:s,toUpdate:a,toDelete:c,ipsToAdd:l,ipsToUpdate:d,ipsToDelete:u}}catch(t){throw o.error("Error fetching existing firewall configuration:",t),t instanceof Error&&t.message.includes("Invalid firewall configuration")?t:new Error("Failed to fetch existing firewall configuration. Please check your network connection and try again.")}}async syncRules(e,t={}){let{dryRun:i=!1,retryAttempts:n=3,debug:s=!1}=t;s&&(o.level=Di.LogLevels.debug);try{let{toAdd:a,toUpdate:c,toDelete:l,ipsToAdd:d,ipsToUpdate:u,ipsToDelete:p}=await this.getChanges(e);if(i)return o.info("Dry run mode. The following changes would be made:"),o.info(`Custom Rules - Add: ${a.length}, Update: ${c.length}, Delete: ${l.length}`),o.info(`IP Rules - Add: ${d.length}, Update: ${u.length}, Delete: ${p.length}`),{addedRules:[],updatedRules:[],deletedRules:[],addedIPRules:[],updatedIPRules:[],deletedIPRules:[],rulesToUpdateLocally:[]};let m=[],h=[],v=[],f=[],E=[],U=[],x=[];for(let g of l)o.debug(`Deleting custom rule: ${g.id}`),await ve(()=>this.client.deleteFirewallRule(g),{maxAttempts:n}),v.push(g),o.debug(`Custom rule deleted: ${g.id}`);for(let g of p)o.debug(`Deleting IP blocking rule: ${g.id}`),await ve(()=>this.client.deleteIPBlockingRule(g),{maxAttempts:n}),U.push(g),o.debug(`IP blocking rule deleted: ${g.id}`);for(let g of a){let A=`rule_${_i(g.name)}`;o.debug(`Adding new custom rule: ${g.name}`);let R=await ve(()=>this.client.createFirewallRule(g),{maxAttempts:n});m.push(R),o.debug(`New custom rule added: ${R.id}`),g.id!==A&&(x.push({oldId:g.id??"",newId:A,name:g.name}),o.debug(`Rule ID needs update locally: ${g.id} -> ${A}`))}for(let g of d){o.debug(`Adding new IP blocking rule: ${g.ip}`);let A=await ve(()=>this.client.createIPBlockingRule(g),{maxAttempts:n});f.push(A),o.debug(`New IP blocking rule added: (hostname): ${A.hostname} (ip): ${A.ip}`)}for(let g of c){o.debug(`Updating custom rule: ${g.id}`);let A=await ve(()=>this.client.updateFirewallRule(g),{maxAttempts:n});h.push(A),o.debug(`Custom rule updated: ${A.id}`)}for(let g of u){o.debug(`Updating IP blocking rule: ${g.id}`);let A=await ve(()=>this.client.updateIPBlockingRule(g),{maxAttempts:n});E.push(A),o.debug(`IP blocking rule updated: ${A.id}`)}return o.debug(`${te.default.underline("Custom Rules:")} ${te.default.green("Added:")} ${te.default.green(m.length)}, ${te.default.cyan("Updated:")} ${te.default.cyan(h.length)}, ${te.default.red("Deleted:")} ${te.default.red(v.length)}`),o.debug(`${te.default.underline("IP Rules:")} ${te.default.green("Added:")} ${te.default.green(f.length)}, ${te.default.cyan("Updated:")} ${te.default.cyan(E.length)}, ${te.default.red("Deleted:")} ${te.default.red(U.length)}`),{addedRules:m,updatedRules:h,deletedRules:v,addedIPRules:f,updatedIPRules:E,deletedIPRules:U,rulesToUpdateLocally:x}}catch(a){throw o.error("Error during sync:",a),new Error("Failed to synchronize firewall rules. Please check the error logs and try again.")}}diffRules(e,t){let i=[],n=[],s=[...t];for(let a of e){let c=t.find(l=>l.id===a.id);if(!c)i.push(a);else{ae(z(a),z(c))||n.push({...a,id:c.id});let l=s.findIndex(d=>d.id===c.id);l!==-1&&s.splice(l,1)}}return{toAdd:i,toUpdate:n,toDelete:s}}diffIPRules(e,t){let i=[],n=[],s=[...t];for(let a of e){let c=t.find(l=>l.id===a.id);if(!c&&!a.id&&(c=t.find(l=>l.ip===a.ip&&l.hostname===a.hostname&&l.action===a.action)),!c)o.debug("Rule not found in existing rules:",{configRule:a}),i.push(a);else{ae(z(a),z(c))||n.push({...c,...a});let l=s.findIndex(d=>d.id===c.id);l!==-1&&s.splice(l,1)}}return{ipsToAdd:i,ipsToUpdate:n,ipsToDelete:s}}async validateAndUpdateConfig(e,t,i={}){if(i.dryRun)return o.info(te.default.cyan("Dry run: Config metadata would be updated after successful sync")),e;await new Promise(R=>setTimeout(R,2e3));let n=await ve(()=>this.client.fetchFirewallConfig(),{maxAttempts:5,delayMs:1500,backoff:!0}),s=n.rules,a=n.ips,c=new Set(t.addedRules.map(R=>R.id)),l=new Set(t.updatedRules.map(R=>R.id)),d=new Set(t.deletedRules.map(R=>R.id)),u=new Set(t.addedIPRules.map(R=>R.id).filter(Boolean)),p=new Set(t.updatedIPRules.map(R=>R.id).filter(Boolean)),m=new Set(t.deletedIPRules.map(R=>R.id).filter(Boolean)),h=new Map(t.addedRules.map(R=>[R.name,R])),v=t.addedIPRules.map(R=>z(R)),f=s.filter(R=>{if(c.has(R.id)||l.has(R.id))return!1;let I=h.get(R.name);if(I&&ae(z(R),z(I)))return!1;if(d.has(R.id))return!0;let Y=e.rules.find(he=>he.id===R.id);return Y?!ae(z(R),z(Y)):!e.rules.find(Ze=>ae(z(R),z(Ze)))}),E=a.filter(R=>u.has(R.id)||p.has(R.id)||v.some(he=>ae(z(R),he))?!1:!!(m.has(R.id)||!e.ips?.find(he=>ae(z(R),z(he))))),U=[];if(f.length>0){let R=f.map(I=>` - ${I.name} (${I.id})`).join(`
|
|
24
24
|
`);U.push(`The following custom rules have unexpected state:
|
|
25
|
-
`+
|
|
25
|
+
`+R)}if(E.length>0){let R=E.map(I=>` - ${I.ip} (${I.id})`).join(`
|
|
26
26
|
`);U.push(`The following IP blocking rules have unexpected state:
|
|
27
|
-
`+
|
|
27
|
+
`+R)}if(U.length>0)throw new Error(`Firewall configuration validation failed:
|
|
28
28
|
`+U.join(`
|
|
29
29
|
|
|
30
|
-
`));let x={...e,version:n.version,updatedAt:n.updatedAt},g=new Set;x.rules=x.rules.map(
|
|
30
|
+
`));let x={...e,version:n.version,updatedAt:n.updatedAt},g=new Set;x.rules=x.rules.map(R=>{let I=s.find(Y=>!g.has(Y.id)&&ae(z(Y),z(R))&&Y.id!==R.id);return I?(g.add(I.id),{...R,id:I.id}):R});let A=new Set;return x.ips&&(x.ips=x.ips.map(R=>{let I=a.find(Y=>!A.has(Y.id)&&ae(z(Y),z(R)));return I&&I.id!==R.id?(A.add(I.id),{...R,id:I.id}):R})),x}};var _t=S(require("chalk"));k();de();var Ne=r=>({$schema:pi,firewallEnabled:!0,rules:[],ips:[],...r});var Li=process.env.DOORMAN_VERCEL_API_BASE_URL||"https://api.vercel.com/v1/security/firewall/config",st=class{constructor(e,t,i){this.projectId=e;this.teamId=t;this.token=i}projectId;teamId;token;getHeaders(){return{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"}}getUrl(e){let t=e!==void 0?`${Li}/${e}`:Li;return o.debug("API URL:",t),`${t}?projectId=${this.projectId}&teamId=${this.teamId}`}async handleResponse(e,t){if(!e.ok){let i=await e.text();throw new Error(`Error ${t?"creating":"updating"} firewall rule: ${e.statusText}
|
|
31
31
|
${i}`)}return await e.json()}async fetchFirewallConfig(e){let t=await fetch(this.getUrl(e),{method:"GET",headers:this.getHeaders()});if(!t.ok){let n=await t.text();throw o.debug("Error fetching firewall rules:",t.statusText,n),new Error(`Error fetching firewall rules: ${t.statusText}
|
|
32
|
-
${n}`)}let i=await t.json();if(o.debug("Config Version:",e??"latest"),o.debug("Fetched Config:",e?i:i.active),e)return i;if(!i||"active"in i&&i.active===null)if(o.warn(_t.default.bold("No firewall configuration found.")),await
|
|
32
|
+
${n}`)}let i=await t.json();if(o.debug("Config Version:",e??"latest"),o.debug("Fetched Config:",e?i:i.active),e)return i;if(!i||"active"in i&&i.active===null)if(o.warn(_t.default.bold("No firewall configuration found.")),await C("Would you like to create one?",{type:"confirm"})){o.debug("Creating new empty firewall configuration...");let s=await this.putEmptyConfig();return o.debug("Empty firewall configuration created successfully"),o.debug(`New configuration version: ${_t.default.yellow(s.version)}`),s}else return i.active;return i.active}async putEmptyConfig(){let{$schema:e,...t}=Ne();return o.debug("Empty Config:",t),this.putConfig(t)}async putConfig(e){let t=await fetch(this.getUrl(),{method:"PUT",headers:this.getHeaders(),body:JSON.stringify(e)});if(!t.ok){let i=await t.text();throw new Error(`Error putting config: ${t.statusText}
|
|
33
33
|
${i}`)}return(await t.json()).active}async fetchActiveFirewallRules(){return(await this.fetchFirewallConfig())?.rules}async updateFirewallRule(e){let t=!e.id||e.id==="-",i={action:t?"rules.insert":"rules.update",id:t?null:e.id,value:{name:e.name,description:e.description,action:e.action,conditionGroup:e.conditionGroup,active:e.active}},n=await fetch(this.getUrl(),{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(i)});if(!n.ok){let s=await n.text();throw new Error(`Error ${t?"creating":"updating"} firewall rule: ${n.statusText}
|
|
34
34
|
${s}`)}return this.handleResponse(n,t)}async createFirewallRule(e){return this.updateFirewallRule({...e,id:"-"})}async deleteFirewallRule(e){let t=JSON.stringify({action:"rules.remove",id:e.id,value:null}),i=await fetch(this.getUrl(),{method:"PATCH",headers:this.getHeaders(),body:t});if(!i.ok){let n=await i.text();throw new Error(`Error deleting firewall rule: ${i.statusText}
|
|
35
35
|
${n}`)}}async updateIPBlockingRule(e){let t=!e.id||e.id==="-",i={action:t?"ip.insert":"ip.update",id:t?null:e.id,value:{action:e.action,hostname:e.hostname,ip:e.ip,...e.notes&&{notes:e.notes}}},n=await fetch(this.getUrl(),{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(i)});if(!n.ok){let s=await n.text();throw new Error(`Error ${t?"creating":"updating"} IP blocking rule: ${n.statusText}
|
|
36
36
|
${s}`)}return await n.json()}async createIPBlockingRule(e){return this.updateIPBlockingRule({...e,id:"-"})}async deleteIPBlockingRule(e){let t=JSON.stringify({action:"ip.remove",id:e.id,value:null}),i=await fetch(this.getUrl(),{method:"PATCH",headers:this.getHeaders(),body:t});if(!i.ok){let n=await i.text();throw new Error(`Error deleting IP blocking rule: ${i.statusText}
|
|
37
|
-
${n}`)}}};var Bi=k(require("chalk"));P();de();Dt();P();var lt=class{static detect(e){let t=[];if(e&&"provider"in e){let n=e.provider;if(typeof n=="string"&&this.isValidProvider(n))return t.push(`Explicit provider specified in config: ${e.provider}`),{provider:n,confidence:"high",reasons:t};o.warn(`Invalid provider specified in config: ${String(e.provider)}`)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let n=e.providers;if(typeof(n.cloudflare||{}).zoneId=="string")return t.push("Cloudflare zone ID found in config"),{provider:"cloudflare",confidence:"high",reasons:t};if(typeof(n.vercel||{}).projectId=="string")return t.push("Vercel project ID found in config"),{provider:"vercel",confidence:"high",reasons:t}}if(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 Lt=k(require("chalk"));P();de();P();var Ne=class{baseUrl;providerName;rateLimitInfo={};constructor(e,t){this.baseUrl=e,this.providerName=t}async makeRequest(e,t={}){let i=`${this.baseUrl}${e}`,{timeout:n=3e4,retries:s=3,retryDelay:a=1e3,...c}=t,l=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()},n);let h=await fetch(i,{...c,headers:{"Content-Type":"application/json",...this.getAuthHeaders(),...c.headers},signal:d.signal});if(u&&(clearTimeout(u),u=null),this.updateRateLimitInfo(h),h.status===429){let f=this.calculateRateLimitWait(m,h);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(f/1e3)}s.`);o.warn(`Rate limit exceeded for ${this.providerName}. Waiting ${f}ms before retry (attempt ${m+1}/${s+1})...`),await this.delay(f);continue}if(!h.ok)throw await this.handleErrorResponse(h);let v;try{let f=await h.text();f.trim()?v=JSON.parse(f):v={}}catch(f){throw o.error(`Failed to parse response from ${i}:`,f),new Error(`Invalid JSON response from ${this.providerName} API: ${f instanceof Error?f.message:String(f)}`)}return this.isLargeResponse(v)&&(o.debug(`Large response detected from ${i}, validating structure...`),this.validateLargeResponse(v)),v}catch(h){if(l=h,u&&(clearTimeout(u),u=null),this.isNonRetryableError(h)||m===s)throw h;let v=a*Math.pow(2,m),f=Math.random()*.1*v,E=Math.min(v+f,3e4);o.debug(`Request failed (attempt ${m+1}/${s+1}). Retrying in ${Math.round(E)}ms...`),o.debug(`Error details: ${h instanceof Error?h.message:String(h)}`),await this.delay(E)}throw l||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"),n=e.headers.get("X-RateLimit-Reset");t&&(this.rateLimitInfo.limit=parseInt(t,10)),i&&(this.rateLimitInfo.remaining=parseInt(i,10)),n&&(this.rateLimitInfo.reset=parseInt(n,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 n=t?this.parseRetryAfter(t.headers.get("Retry-After")):null;if(n!==null)return Math.min(Math.max(n,1e3),6e4);if(this.rateLimitInfo.reset){let c=Math.floor(Date.now()/1e3),l=(this.rateLimitInfo.reset-c)*1e3;return Math.min(Math.max(l,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 n=await e.json();if(typeof n=="object"&&n!==null){let s=n;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(c=>typeof c=="object"&&c!==null&&"message"in c?String(c.message):JSON.stringify(c)).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,n=0)=>{if(n>10)return!1;for(let[,s]of Object.entries(i))if(Array.isArray(s)&&s.length>1e3||typeof s=="object"&&s!==null&&t(s,n+1))return!0;return!1};return t(e)}validateLargeResponse(e){if(!e||typeof e!="object")return;let t=(n,s)=>{n.length>5e3&&o.warn(`Large array detected at ${s} with ${n.length} items. This may impact performance.`);let a=Math.min(10,n.length),c=n[0];if(c&&typeof c=="object"){let l=Object.keys(c);for(let d=1;d<a;d++){let u=n[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=l.filter(h=>!p.includes(h));m.length>0&&o.warn(`Inconsistent array structure at ${s}[${d}]: missing keys ${m.join(", ")}`)}}},i=(n,s="root",a=0)=>{if(!(a>10))for(let[c,l]of Object.entries(n)){let d=`${s}.${c}`;Array.isArray(l)?t(l,d):typeof l=="object"&&l!==null&&i(l,d,a+1)}};i(e)}};var Ui="https://api.vercel.com/v1/security/firewall/config",Ve=class extends Ne{constructor(t,i,n){super("","vercel");this.projectId=t;this.teamId=i;this.token=n}projectId;teamId;token;getAuthHeaders(){return{Authorization:`Bearer ${this.token}`}}getUrl(t){let i=t!==void 0?`${Ui}/${t}`:Ui;return o.debug("API URL:",i),`${i}?projectId=${this.projectId}&teamId=${this.teamId}`}async fetchFirewallConfig(t,i){let{allowCreate:n=!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(Lt.default.bold("No firewall configuration found.")),!n)return o.debug("Skipping create-configuration prompt for read-only fetch."),this.emptyConfigPlaceholder();if(await R("Would you like to create one?",{type:"confirm"})){o.debug("Creating new empty firewall configuration...");let c=await this.putEmptyConfig();return o.debug("Empty firewall configuration created successfully"),o.debug(`New configuration version: ${Lt.default.yellow(c.version)}`),c}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}=Fe();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==="-",n={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(),n)}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==="-",n={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(),n)}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 re=k(require("chalk"));P();P();var Be=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 n=new Map;e.rules.forEach((s,a)=>{let c=s.id||s.name;if(!c)return;let l=n.get(c);if(l===void 0){n.set(c,a);return}let d=e.rules[l];i.push({path:`rules[${a}]`,message:s.id?`Rule "${s.name}" has the same id ("${s.id}") as rules[${l}] ("${d?.name}") \u2014 they will collide during sync diffing and one may be silently skipped.`:`Rule "${s.name}" has the same name as rules[${l}] 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(c=>!c.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(c=>c.active===!1||c.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 n=this.calculateGrade(i),s=this.generateRecommendations(e,t);return{score:Math.max(0,i),grade:n,issues:t,recommendations:s}}diffItems(e,t,i,n="id"){let s=[],a=[],c=[],l=d=>d[n];for(let d of e){let u=t.find(p=>l(p)===l(d));u?i(d,u)||a.push(d):s.push(d)}for(let d of t)e.find(p=>l(p)===l(d))||c.push(d);return{toAdd:s,toUpdate:a,toDelete:c}}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(n=>n.category==="rules")&&i.push("Consider using predefined templates to get started"),t.some(n=>n.category==="maintainability")&&i.push("Add descriptions to all rules for better documentation"),t.some(n=>n.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}`)}};P();function je(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Je=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}["${je(t.toLowerCase())}"]`:e==="cookie"&&t?`${i}["${je(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 n=this.cloudflareToVercel[e];if(n)return{type:n};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"]),ze=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 n=i.conditions.map(s=>this.fromVercelCondition(s));if(n.length===0)throw new Error("Condition group must have at least one condition");return n.length>1?`(${n.join(" and ")})`:n[0]});return t.length>1?t.join(" or "):t[0]}static fromVercelCondition(e){let t=Je.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(l=>this.fromUnifiedCondition(l)),c=t==="AND"?" and ":" or ";return a.length>1?`(${a.join(c)})`:a[0]}let n=new Map;for(let a of e){let c=a.group??0,l=n.get(c);l?l.push(a):n.set(c,[a])}let s=Array.from(n.values()).map(a=>this.combineWithAnd(a.map(c=>this.fromUnifiedCondition(c))));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}["${je(e.key)}"]`:t,n=this.buildUnifiedExpression(i,e.operator,e.value);return e.negated&&(n=`not (${n})`),n}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(n=>this.formatSingleValue(e,n)).join(" ")}}`:this.formatSingleValue(e,t)}static formatSingleValue(e,t){if(typeof t=="string"){if(Ko.has(e)){if(!Oe.safeParse(t).success)throw new Error(`Invalid IP address or CIDR range: ${t}`);return t}return`"${je(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 ")})`}};P();var W=class{static vercelToCloudflare(e){let t=[];try{let i=ze.fromVercelConditionGroups(e.conditionGroup),n=this.translateVercelActionToCloudflare(e.action.mitigate.action),s={id:e.id||crypto.randomUUID(),action:n,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:c}=(ue(),ce(ge));t.push(c.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}=(ue(),ce(ge));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,c)=>{for(let l of a.conditions){let d=this.mapVercelOperatorToUnified(l.op);if(l.op==="re"&&typeof l.value=="string"){let{TranslationWarningSystem:u}=(ue(),ce(ge));t.push(u.createWarning("regex_patterns",e.id,l.type,`Regular expression pattern may need adjustment for target provider: ${l.value}`,"Test the regex pattern in the target provider and adjust syntax if needed"))}i.push({field:this.mapVercelTypeToUnified(l.type),operator:d,value:l.value,negated:l.neg,key:l.key,group:c})}}),i.length>10){let{TranslationWarningSystem:a}=(ue(),ce(ge));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 n={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:n},warnings:t}}static cloudflareToUnified(e){let t=[],{TranslationWarningSystem:i}=(ue(),ce(ge));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 n={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:n},warnings:t}}static unifiedToCloudflare(e){let t=[],i=ze.fromUnifiedConditions(e.conditions,e.conditionLogic),n={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&&(n.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?n.ratelimit.mitigation_timeout=e.action.rateLimit.mitigationTimeout:n.ratelimit.mitigation_timeout=3600,e.action.rateLimit.countingExpression&&(n.ratelimit.counting_expression=e.action.rateLimit.countingExpression)),{result:n,warnings:t}}static unifiedToVercel(e){let t=[],i=new Map;for(let a of e.conditions){let c=a.group??0,l=i.get(c);l?l.push(a):i.set(c,[a])}let n=[];for(let a of i.values()){let c=[];for(let l of a){let d=this.mapUnifiedTypeToVercel(l.field);if(!d){let{TranslationWarningSystem:u}=(ue(),ce(ge));t.push(u.createUnsupportedFeatureWarning(`condition field '${l.field}'`,"unified config","Vercel",e.id,l.field));continue}c.push({op:this.mapUnifiedOperatorToVercel(l.operator),neg:l.negated,type:d,key:l.key,value:l.value})}c.length>0&&n.push({conditions:c})}if(n.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:n,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(!Oe.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),n=t[2],a={s:1,m:60,h:3600,d:86400}[n];if(a===void 0)throw new Error(`Invalid time unit: ${n}`);return i*a}};ue();var We=class extends Be{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),n=i.rules.map(a=>{let c=W.vercelToUnified(a);return c.warnings.length>0&&c.warnings.forEach(l=>{let{TranslationWarningSystem:d}=(ue(),ce(ge)),u=d.formatWarning(l);o.warn(`Rule ${a.name}:
|
|
38
|
-
${u}`)}),c.result}),s=i.ips.map(a=>W.vercelIPToUnified(a));return{version:"2.0",provider:"vercel",rules:n,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:n=!1}=i;try{let{OperationSafety:s}=(Ot(),ce(xt)),a=await s.performDryRunValidation(t,"sync rules",async
|
|
39
|
-
${Y}`)}),A.result}),{toAdd:a,toUpdate:c,toDelete:l}=this.diffRules(s,n.rules),d=(t.ips||[]).map(g=>({id:g.id||"",ip:g.ip,hostname:g.hostname||"",action:g.action,notes:g.notes})),{ipsToAdd:u,ipsToUpdate:p,ipsToDelete:m}=this.diffIPRules(d,n.ips),h=a.map(g=>W.vercelToUnified(g).result),v=c.map(g=>W.vercelToUnified(g).result),f=l.map(g=>W.vercelToUnified(g).result),E=u.map(g=>W.vercelIPToUnified(g)),U=p.map(g=>W.vercelIPToUnified(g)),x=m.map(g=>W.vercelIPToUnified(g));return{version:n.version,rulesToAdd:h,rulesToUpdate:v,rulesToDelete:f,ipsToAdd:E,ipsToUpdate:U,ipsToDelete:x,hasChanges:a.length>0||c.length>0||l.length>0||u.length>0||p.length>0||m.length>0}}catch(n){throw o.error("Error fetching existing firewall configuration:",n),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),n=[...i.errors],s=[...i.warnings];t.provider&&t.provider!=="vercel"&&n.push({path:"provider",message:"Provider must be 'vercel' for VercelFirewallService",code:"INVALID_PROVIDER"});try{let a=we.safeParse(t);a.success||n.push({path:"root",message:`Schema validation failed: ${a.error.message}`,code:"SCHEMA_VALIDATION_FAILED"})}catch(a){o.debug("Schema validation error:",a)}return{valid:n.length===0,errors:n,warnings:s}}getHealthScore(t){let i=super.getHealthScore(t),n=[...i.issues],s=i.score;return t.rules.filter(c=>c.action?.type==="rate_limit").length===0&&(s-=10,n.push({severity:"info",category:"security",message:"No rate limiting rules configured",suggestion:"Consider adding rate limiting to protect against abuse"})),(!t.ips||t.ips.length===0)&&n.push({severity:"info",category:"security",message:"No IP blocking rules configured",suggestion:"Consider blocking known malicious IPs"}),{score:Math.max(0,s),grade:i.grade,issues:n,recommendations:i.recommendations}}diffRules(t,i){let n=[],s=[],a=[...i];for(let c of t){let l=i.find(d=>d.id===c.id);if(!l)n.push(c);else{ae(z(c),z(l))||s.push({...c,id:l.id});let d=a.findIndex(u=>u.id===l.id);d!==-1&&a.splice(d,1)}}return{toAdd:n,toUpdate:s,toDelete:a}}diffIPRules(t,i){let n=[],s=[],a=[...i];for(let c of t){let l=i.find(d=>d.id===c.id);if(!l)o.debug("Rule not found in existing rules:",{configRule:c}),n.push(c);else{ae(z(c),z(l))||s.push({...l,...c});let d=a.findIndex(u=>u.id===l.id);d!==-1&&a.splice(d,1)}}return{ipsToAdd:n,ipsToUpdate:s,ipsToDelete:a}}};
|
|
37
|
+
${n}`)}}};var ji=S(require("chalk"));k();de();Dt();k();var lt=class{static detect(e){let t=[];if(e&&"provider"in e){let n=e.provider;if(typeof n=="string"&&this.isValidProvider(n))return t.push(`Explicit provider specified in config: ${e.provider}`),{provider:n,confidence:"high",reasons:t};o.warn(`Invalid provider specified in config: ${String(e.provider)}`)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let n=e.providers;if(typeof(n.cloudflare||{}).zoneId=="string")return t.push("Cloudflare zone ID found in config"),{provider:"cloudflare",confidence:"high",reasons:t};if(typeof(n.vercel||{}).projectId=="string")return t.push("Vercel project ID found in config"),{provider:"vercel",confidence:"high",reasons:t}}if(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 Lt=S(require("chalk"));k();de();k();var Fe=class{baseUrl;providerName;rateLimitInfo={};constructor(e,t){this.baseUrl=e,this.providerName=t}async makeRequest(e,t={}){let i=`${this.baseUrl}${e}`,{timeout:n=3e4,retries:s=3,retryDelay:a=1e3,...c}=t,l=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()},n);let h=await fetch(i,{...c,headers:{"Content-Type":"application/json",...this.getAuthHeaders(),...c.headers},signal:d.signal});if(u&&(clearTimeout(u),u=null),this.updateRateLimitInfo(h),h.status===429){let f=this.calculateRateLimitWait(m,h);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(f/1e3)}s.`);o.warn(`Rate limit exceeded for ${this.providerName}. Waiting ${f}ms before retry (attempt ${m+1}/${s+1})...`),await this.delay(f);continue}if(!h.ok)throw await this.handleErrorResponse(h);let v;try{let f=await h.text();f.trim()?v=JSON.parse(f):v={}}catch(f){throw o.error(`Failed to parse response from ${i}:`,f),new Error(`Invalid JSON response from ${this.providerName} API: ${f instanceof Error?f.message:String(f)}`)}return this.isLargeResponse(v)&&(o.debug(`Large response detected from ${i}, validating structure...`),this.validateLargeResponse(v)),v}catch(h){if(l=h,u&&(clearTimeout(u),u=null),this.isNonRetryableError(h)||m===s)throw h;let v=a*Math.pow(2,m),f=Math.random()*.1*v,E=Math.min(v+f,3e4);o.debug(`Request failed (attempt ${m+1}/${s+1}). Retrying in ${Math.round(E)}ms...`),o.debug(`Error details: ${h instanceof Error?h.message:String(h)}`),await this.delay(E)}throw l||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"),n=e.headers.get("X-RateLimit-Reset");t&&(this.rateLimitInfo.limit=parseInt(t,10)),i&&(this.rateLimitInfo.remaining=parseInt(i,10)),n&&(this.rateLimitInfo.reset=parseInt(n,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 n=t?this.parseRetryAfter(t.headers.get("Retry-After")):null;if(n!==null)return Math.min(Math.max(n,1e3),6e4);if(this.rateLimitInfo.reset){let c=Math.floor(Date.now()/1e3),l=(this.rateLimitInfo.reset-c)*1e3;return Math.min(Math.max(l,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 n=await e.json();if(typeof n=="object"&&n!==null){let s=n;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(c=>typeof c=="object"&&c!==null&&"message"in c?String(c.message):JSON.stringify(c)).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,n=0)=>{if(n>10)return!1;for(let[,s]of Object.entries(i))if(Array.isArray(s)&&s.length>1e3||typeof s=="object"&&s!==null&&t(s,n+1))return!0;return!1};return t(e)}validateLargeResponse(e){if(!e||typeof e!="object")return;let t=(n,s)=>{n.length>5e3&&o.warn(`Large array detected at ${s} with ${n.length} items. This may impact performance.`);let a=Math.min(10,n.length),c=n[0];if(c&&typeof c=="object"){let l=Object.keys(c);for(let d=1;d<a;d++){let u=n[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=l.filter(h=>!p.includes(h));m.length>0&&o.warn(`Inconsistent array structure at ${s}[${d}]: missing keys ${m.join(", ")}`)}}},i=(n,s="root",a=0)=>{if(!(a>10))for(let[c,l]of Object.entries(n)){let d=`${s}.${c}`;Array.isArray(l)?t(l,d):typeof l=="object"&&l!==null&&i(l,d,a+1)}};i(e)}};var xi=process.env.DOORMAN_VERCEL_API_BASE_URL||"https://api.vercel.com/v1/security/firewall/config",Ve=class extends Fe{constructor(t,i,n){super("","vercel");this.projectId=t;this.teamId=i;this.token=n}projectId;teamId;token;getAuthHeaders(){return{Authorization:`Bearer ${this.token}`}}getUrl(t){let i=t!==void 0?`${xi}/${t}`:xi;return o.debug("API URL:",i),`${i}?projectId=${this.projectId}&teamId=${this.teamId}`}async fetchFirewallConfig(t,i){let{allowCreate:n=!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(Lt.default.bold("No firewall configuration found.")),!n)return o.debug("Skipping create-configuration prompt for read-only fetch."),this.emptyConfigPlaceholder();if(await C("Would you like to create one?",{type:"confirm"})){o.debug("Creating new empty firewall configuration...");let c=await this.putEmptyConfig();return o.debug("Empty firewall configuration created successfully"),o.debug(`New configuration version: ${Lt.default.yellow(c.version)}`),c}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}=Ne();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==="-",n={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(),n)}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==="-",n={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(),n)}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 re=S(require("chalk"));k();k();var Be=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 n=new Map;e.rules.forEach((s,a)=>{let c=s.id||s.name;if(!c)return;let l=n.get(c);if(l===void 0){n.set(c,a);return}let d=e.rules[l];i.push({path:`rules[${a}]`,message:s.id?`Rule "${s.name}" has the same id ("${s.id}") as rules[${l}] ("${d?.name}") \u2014 they will collide during sync diffing and one may be silently skipped.`:`Rule "${s.name}" has the same name as rules[${l}] 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(c=>!c.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(c=>c.active===!1||c.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 n=this.calculateGrade(i),s=this.generateRecommendations(e,t);return{score:Math.max(0,i),grade:n,issues:t,recommendations:s}}diffItems(e,t,i,n="id"){let s=[],a=[],c=[],l=d=>d[n];for(let d of e){let u=t.find(p=>l(p)===l(d));u?i(d,u)||a.push(d):s.push(d)}for(let d of t)e.find(p=>l(p)===l(d))||c.push(d);return{toAdd:s,toUpdate:a,toDelete:c}}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(n=>n.category==="rules")&&i.push("Consider using predefined templates to get started"),t.some(n=>n.category==="maintainability")&&i.push("Add descriptions to all rules for better documentation"),t.some(n=>n.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}`)}};k();function je(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Je=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}["${je(t.toLowerCase())}"]`:e==="cookie"&&t?`${i}["${je(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 n=this.cloudflareToVercel[e];if(n)return{type:n};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 Jo=new Set(["ip.src"]),ze=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 n=i.conditions.map(s=>this.fromVercelCondition(s));if(n.length===0)throw new Error("Condition group must have at least one condition");return n.length>1?`(${n.join(" and ")})`:n[0]});return t.length>1?t.join(" or "):t[0]}static fromVercelCondition(e){let t=Je.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(l=>this.fromUnifiedCondition(l)),c=t==="AND"?" and ":" or ";return a.length>1?`(${a.join(c)})`:a[0]}let n=new Map;for(let a of e){let c=a.group??0,l=n.get(c);l?l.push(a):n.set(c,[a])}let s=Array.from(n.values()).map(a=>this.combineWithAnd(a.map(c=>this.fromUnifiedCondition(c))));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}["${je(e.key)}"]`:t,n=this.buildUnifiedExpression(i,e.operator,e.value);return e.negated&&(n=`not (${n})`),n}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(n=>this.formatSingleValue(e,n)).join(" ")}}`:this.formatSingleValue(e,t)}static formatSingleValue(e,t){if(typeof t=="string"){if(Jo.has(e)){if(!Oe.safeParse(t).success)throw new Error(`Invalid IP address or CIDR range: ${t}`);return t}return`"${je(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 ")})`}};k();var W=class{static vercelToCloudflare(e){let t=[];try{let i=ze.fromVercelConditionGroups(e.conditionGroup),n=this.translateVercelActionToCloudflare(e.action.mitigate.action),s={id:e.id||crypto.randomUUID(),action:n,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:c}=(ue(),ce(ge));t.push(c.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}=(ue(),ce(ge));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,c)=>{for(let l of a.conditions){let d=this.mapVercelOperatorToUnified(l.op);if(l.op==="re"&&typeof l.value=="string"){let{TranslationWarningSystem:u}=(ue(),ce(ge));t.push(u.createWarning("regex_patterns",e.id,l.type,`Regular expression pattern may need adjustment for target provider: ${l.value}`,"Test the regex pattern in the target provider and adjust syntax if needed"))}i.push({field:this.mapVercelTypeToUnified(l.type),operator:d,value:l.value,negated:l.neg,key:l.key,group:c})}}),i.length>10){let{TranslationWarningSystem:a}=(ue(),ce(ge));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 n={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:n},warnings:t}}static cloudflareToUnified(e){let t=[],{TranslationWarningSystem:i}=(ue(),ce(ge));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 n={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:n},warnings:t}}static unifiedToCloudflare(e){let t=[],i=ze.fromUnifiedConditions(e.conditions,e.conditionLogic),n={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&&(n.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?n.ratelimit.mitigation_timeout=e.action.rateLimit.mitigationTimeout:n.ratelimit.mitigation_timeout=3600,e.action.rateLimit.countingExpression&&(n.ratelimit.counting_expression=e.action.rateLimit.countingExpression)),{result:n,warnings:t}}static unifiedToVercel(e){let t=[],i=new Map;for(let a of e.conditions){let c=a.group??0,l=i.get(c);l?l.push(a):i.set(c,[a])}let n=[];for(let a of i.values()){let c=[];for(let l of a){let d=this.mapUnifiedTypeToVercel(l.field);if(!d){let{TranslationWarningSystem:u}=(ue(),ce(ge));t.push(u.createUnsupportedFeatureWarning(`condition field '${l.field}'`,"unified config","Vercel",e.id,l.field));continue}c.push({op:this.mapUnifiedOperatorToVercel(l.operator),neg:l.negated,type:d,key:l.key,value:l.value})}c.length>0&&n.push({conditions:c})}if(n.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:n,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(!Oe.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),n=t[2],a={s:1,m:60,h:3600,d:86400}[n];if(a===void 0)throw new Error(`Invalid time unit: ${n}`);return i*a}};ue();var We=class extends Be{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),n=i.rules.map(a=>{let c=W.vercelToUnified(a);return c.warnings.length>0&&c.warnings.forEach(l=>{let{TranslationWarningSystem:d}=(ue(),ce(ge)),u=d.formatWarning(l);o.warn(`Rule ${a.name}:
|
|
38
|
+
${u}`)}),c.result}),s=i.ips.map(a=>W.vercelIPToUnified(a));return{version:"2.0",provider:"vercel",providers:{vercel:{projectId:this.client.projectId,teamId:this.client.teamId}},rules:n,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:n=!1}=i;try{let{OperationSafety:s}=(Ot(),ce(xt)),a=await s.performDryRunValidation(t,"sync rules",async y=>await this.getChanges(y,{allowCreate:!n}));if(!a.valid)throw new Error(`Dry-run validation failed: ${a.issues.join(", ")}`);let c=a.changes,{rulesToAdd:l,rulesToUpdate:d,rulesToDelete:u,version:p}=c,m=c.ipsToAdd||[],h=c.ipsToUpdate||[],v=c.ipsToDelete||[];if(n)return o.info("Dry run mode. The following changes would be made:"),o.info(`Custom Rules - Add: ${l.length}, Update: ${d.length}, Delete: ${u.length}`),o.info(`IP Rules - Add: ${m.length}, Update: ${h.length}, Delete: ${v.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,version:p,warnings:a.warnings};let f=s.assessOperationRisk(c,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Vercel project ${this.client.projectId}`,changes:c,riskLevel:f,skipConfirmation:i.force||!1,dryRun:!1,allowDeletions:i.allowDeletions||!1}))throw new Error("Operation cancelled by user");let U=l.map(y=>W.unifiedToVercel(y).result),x=d.map(y=>W.unifiedToVercel(y).result),g=u.map(y=>W.unifiedToVercel(y).result),A=m.map(y=>({id:y.id||"",ip:y.ip,hostname:y.hostname||"",action:y.action,notes:y.notes})),R=h.map(y=>({id:y.id||"",ip:y.ip,hostname:y.hostname||"",action:y.action,notes:y.notes})),I=v.map(y=>({id:y.id||"",ip:y.ip,hostname:y.hostname||"",action:y.action,notes:y.notes})),Y=[],he=[],Ze=[],gt=[],ft=[],mt=[],ye=[],Te=(y,P)=>`${y}: ${P instanceof Error?P.message:String(P)}`,ht=[];for(let y of g)try{o.debug(`Deleting custom rule: ${y.id}`),await this.client.deleteFirewallRule(y),Ze.push(y),o.debug(`Custom rule deleted: ${y.id}`)}catch(P){o.error(`Failed to delete custom rule ${y.id}:`,P),ye.push(Te(`Failed to delete custom rule ${y.id}`,P))}for(let y of I)try{o.debug(`Deleting IP blocking rule: ${y.id}`),await this.client.deleteIPBlockingRule(y),mt.push(y),o.debug(`IP blocking rule deleted: ${y.id}`)}catch(P){o.error(`Failed to delete IP blocking rule ${y.id}:`,P),ye.push(Te(`Failed to delete IP blocking rule ${y.id}`,P))}for(let y of U)try{o.debug(`Adding new custom rule: ${y.name}`);let P=await this.client.createFirewallRule(y);Y.push(P),P.id&&P.id!==y.id&&ht.push({oldId:y.id||void 0,newId:P.id,name:y.name}),o.debug(`New custom rule added: ${P.id}`)}catch(P){o.error(`Failed to add custom rule "${y.name}":`,P),ye.push(Te(`Failed to add custom rule "${y.name}"`,P))}for(let y of A)try{o.debug(`Adding new IP blocking rule: ${y.ip}`);let P=await this.client.createIPBlockingRule(y);gt.push(P),o.debug(`New IP blocking rule added: (hostname): ${P.hostname} (ip): ${P.ip}`)}catch(P){o.error(`Failed to add IP blocking rule ${y.ip}:`,P),ye.push(Te(`Failed to add IP blocking rule ${y.ip}`,P))}for(let y of x)try{o.debug(`Updating custom rule: ${y.id}`);let P=await this.client.updateFirewallRule(y);he.push(P),o.debug(`Custom rule updated: ${P.id}`)}catch(P){o.error(`Failed to update custom rule ${y.id}:`,P),ye.push(Te(`Failed to update custom rule ${y.id}`,P))}for(let y of R)try{o.debug(`Updating IP blocking rule: ${y.id}`);let P=await this.client.updateIPBlockingRule(y);ft.push(P),o.debug(`IP blocking rule updated: ${P.id}`)}catch(P){o.error(`Failed to update IP blocking rule ${y.id}:`,P),ye.push(Te(`Failed to update IP blocking rule ${y.id}`,P))}o.debug(`${re.default.underline("Custom Rules:")} ${re.default.green("Added:")} ${re.default.green(Y.length)}, ${re.default.cyan("Updated:")} ${re.default.cyan(he.length)}, ${re.default.red("Deleted:")} ${re.default.red(Ze.length)}`),o.debug(`${re.default.underline("IP Rules:")} ${re.default.green("Added:")} ${re.default.green(gt.length)}, ${re.default.cyan("Updated:")} ${re.default.cyan(ft.length)}, ${re.default.red("Deleted:")} ${re.default.red(mt.length)}`);let si=p,ai;try{let y=await this.client.fetchFirewallConfig();si=y.version,ai=y.updatedAt}catch(y){o.error("Failed to fetch updated firewall configuration version after sync:",y),ye.push(Te("Failed to fetch updated configuration version after sync",y))}return{success:ye.length===0,rulesAdded:Y.length,rulesUpdated:he.length,rulesDeleted:Ze.length,ipsAdded:gt.length,ipsUpdated:ft.length,ipsDeleted:mt.length,version:si,updatedAt:ai,idRemappings:ht.length>0?ht:void 0,errors:ye.length>0?ye: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){try{o.debug("Fetching existing firewall configuration");let n=await this.client.fetchFirewallConfig(void 0,{allowCreate:i?.allowCreate??!0});o.debug(`Fetched ${n.rules.length} custom rules and ${n.ips.length} IP blocking rules`);let s=t.rules.map(g=>{let A=W.unifiedToVercel(g);return A.warnings.length>0&&A.warnings.forEach(R=>{let{TranslationWarningSystem:I}=(ue(),ce(ge)),Y=I.formatWarning(R);o.warn(`Rule ${g.name}:
|
|
39
|
+
${Y}`)}),A.result}),{toAdd:a,toUpdate:c,toDelete:l}=this.diffRules(s,n.rules),d=(t.ips||[]).map(g=>({id:g.id||"",ip:g.ip,hostname:g.hostname||"",action:g.action,notes:g.notes})),{ipsToAdd:u,ipsToUpdate:p,ipsToDelete:m}=this.diffIPRules(d,n.ips),h=a.map(g=>W.vercelToUnified(g).result),v=c.map(g=>W.vercelToUnified(g).result),f=l.map(g=>W.vercelToUnified(g).result),E=u.map(g=>W.vercelIPToUnified(g)),U=p.map(g=>W.vercelIPToUnified(g)),x=m.map(g=>W.vercelIPToUnified(g));return{version:n.version,rulesToAdd:h,rulesToUpdate:v,rulesToDelete:f,ipsToAdd:E,ipsToUpdate:U,ipsToDelete:x,hasChanges:a.length>0||c.length>0||l.length>0||u.length>0||p.length>0||m.length>0}}catch(n){throw o.error("Error fetching existing firewall configuration:",n),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),n=[...i.errors],s=[...i.warnings];t.provider&&t.provider!=="vercel"&&n.push({path:"provider",message:"Provider must be 'vercel' for VercelFirewallService",code:"INVALID_PROVIDER"});try{let a=we.safeParse(t);a.success||n.push({path:"root",message:`Schema validation failed: ${a.error.message}`,code:"SCHEMA_VALIDATION_FAILED"})}catch(a){o.debug("Schema validation error:",a)}return{valid:n.length===0,errors:n,warnings:s}}getHealthScore(t){let i=super.getHealthScore(t),n=[...i.issues],s=i.score;return t.rules.filter(c=>c.action?.type==="rate_limit").length===0&&(s-=10,n.push({severity:"info",category:"security",message:"No rate limiting rules configured",suggestion:"Consider adding rate limiting to protect against abuse"})),(!t.ips||t.ips.length===0)&&n.push({severity:"info",category:"security",message:"No IP blocking rules configured",suggestion:"Consider blocking known malicious IPs"}),{score:Math.max(0,s),grade:i.grade,issues:n,recommendations:i.recommendations}}diffRules(t,i){let n=[],s=[],a=[...i];for(let c of t){let l=i.find(d=>d.id===c.id);if(!l)n.push(c);else{ae(z(c),z(l))||s.push({...c,id:l.id});let d=a.findIndex(u=>u.id===l.id);d!==-1&&a.splice(d,1)}}return{toAdd:n,toUpdate:s,toDelete:a}}diffIPRules(t,i){let n=[],s=[],a=[...i];for(let c of t){let l=i.find(d=>d.id===c.id);if(!l)o.debug("Rule not found in existing rules:",{configRule:c}),n.push(c);else{ae(z(c),z(l))||s.push({...l,...c});let d=a.findIndex(u=>u.id===l.id);d!==-1&&a.splice(d,1)}}return{ipsToAdd:n,ipsToUpdate:s,ipsToDelete:a}}};k();var Me=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 n=new Ve(t,i,e);return new We(n)}static fromConfig(e){let t=e.token||process.env.VERCEL_TOKEN,i=e.projectId||process.env.VERCEL_PROJECT_ID,n=e.teamId||process.env.VERCEL_TEAM_ID;if(!t)throw new Error("Vercel API token is required (provide token or set VERCEL_TOKEN env var)");if(!i)throw new Error("Vercel project ID is required (provide projectId or set VERCEL_PROJECT_ID env var)");if(!n)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:n});let s=new Ve(i,n,t);return new We(s)}static create(e,t,i){return this.fromConfig({projectId:e,teamId:t,token:i})}};var Fi=require("crypto");k();var Se=S(require("chalk")),w=class r 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,r)}format(){let e=[];return e.push(Se.default.red.bold(`[${this.code}] ${this.message}`)),e.push(""),this.suggestion&&(e.push(Se.default.yellow.bold("Suggestion:")),e.push(` ${this.suggestion}`),e.push("")),this.details&&Object.keys(this.details).length>0&&(e.push(Se.default.dim("Details:")),Object.entries(this.details).forEach(([t,i])=>{let n=typeof i=="object"?JSON.stringify(i,null,2).split(`
|
|
40
40
|
`).join(`
|
|
41
41
|
`):i;e.push(` ${Se.default.cyan(t)}: ${n}`)}),e.push("")),this.cause&&(e.push(Se.default.dim("Caused by:")),e.push(` ${this.cause.message}`),e.push("")),this.docsUrl&&(e.push(Se.default.cyan.bold("Documentation:")),e.push(` ${this.docsUrl}`),e.push("")),e.join(`
|
|
42
42
|
`)}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(`
|
|
43
|
-
`)}static isDoormanError(e){return e instanceof r}static from(e,t,i){return r.isDoormanError(e)?e:e instanceof Error?new r({code:t,message:i||e.message,cause:e}):new r({code:t,message:i||String(e)})}};var O="https://docs.doorman.griffen.codes/errors";var J={authFailed:(r,e)=>new y({code:"PROV_5000",message:`Authentication failed for ${r}`,suggestion:"Check that your API credentials are valid and have the correct permissions",details:{provider:r},cause:e,docsUrl:`${O}/PROV_5000`}),apiError:(r,e,t,i)=>new y({code:"PROV_5002",message:`${r} API error: ${t} ${i}`,suggestion:"Check the provider status page and your credentials",details:{provider:r,endpoint:e,statusCode:t,responseMessage:i},docsUrl:`${O}/PROV_5002`}),rateLimit:(r,e)=>new y({code:"PROV_5003",message:`Rate limit exceeded for ${r}`,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:r,retryAfter:e},docsUrl:`${O}/PROV_5003`}),timeout:(r,e)=>new y({code:"PROV_5006",message:`Request timeout for ${r} ${e}`,suggestion:"Check your internet connection and try again",details:{provider:r,operation:e},docsUrl:`${O}/PROV_5006`}),invalidCredentials:(r,e)=>new y({code:"PROV_5004",message:`Missing or invalid credentials for ${r}`,suggestion:`Please provide: ${e.join(", ")}`,details:{provider:r,missing:e},docsUrl:`${O}/PROV_5004`})},G={accountIdRequired:r=>new y({code:"CF_6004",message:`Account ID required for ${r}`,suggestion:"Provide CLOUDFLARE_ACCOUNT_ID in your environment or configuration to use Lists API",details:{operation:r},docsUrl:`${O}/CF_6004`}),zoneIdRequired:r=>new y({code:"CF_6005",message:`Zone ID required for ${r}`,suggestion:"Provide CLOUDFLARE_ZONE_ID in your environment or configuration",details:{operation:r},docsUrl:`${O}/CF_6005`}),invalidCredentials:(r,e)=>new y({code:"CF_6016",message:`Invalid Cloudflare ${r}`,suggestion:"Check your Cloudflare API credentials and ensure they have the correct permissions",details:{credentialType:r,...e},docsUrl:`${O}/CF_6016`}),insufficientPermissions:(r,e)=>new y({code:"CF_6017",message:`Insufficient permissions for ${r}`,suggestion:`Ensure your API token has the following permissions: ${e.join(", ")}`,details:{operation:r,requiredPermissions:e},docsUrl:`${O}/CF_6017`}),ruleLimitExceeded:(r,e)=>new y({code:"CF_6001",message:`Rule count (${r}) exceeds Cloudflare limit (${e})`,suggestion:"Consider consolidating rules, using Lists for IP blocking, or upgrading your Cloudflare plan",details:{count:r,limit:e},docsUrl:`${O}/CF_6001`}),invalidExpression:(r,e)=>new y({code:"CF_6002",message:`Invalid Cloudflare expression: ${e}`,suggestion:"Check Cloudflare Wirefilter expression syntax and field names",details:{expression:r,reason:e},docsUrl:`${O}/CF_6002`}),ruleNoConditions:r=>new y({code:"CF_6007",message:`Rule "${r}" has no conditions`,suggestion:"Add at least one condition to the rule or remove the empty rule",details:{ruleName:r},docsUrl:`${O}/CF_6007`}),invalidRateLimit:(r,e)=>new y({code:"CF_6008",message:`Invalid rate limit configuration for rule "${r}": ${e}`,suggestion:'Rate limit requests must be at least 1, and window format should be like "60s", "1h", "1d"',details:{ruleName:r,issue:e},docsUrl:`${O}/CF_6008`}),invalidWindowFormat:r=>new y({code:"CF_6009",message:`Invalid rate limit window format: ${r}`,suggestion:'Use format like "60s", "5m", "1h", or "1d"',details:{window:r},docsUrl:`${O}/CF_6009`}),shortMitigationTimeout:r=>new y({code:"CF_6010",message:`Mitigation timeout (${r}s) may be too short`,suggestion:"Consider using at least 60 seconds for effective rate limiting",details:{timeout:r},docsUrl:`${O}/CF_6010`}),redirectNoLocation:r=>new y({code:"CF_6011",message:`Redirect rule "${r}" is missing location URL`,suggestion:"Add a redirect.location property with a valid URL or path",details:{ruleName:r},docsUrl:`${O}/CF_6011`}),invalidRedirectUrl:r=>new y({code:"CF_6012",message:`Invalid redirect URL: ${r}`,suggestion:"Use a valid absolute URL (https://...) or relative path (/...)",details:{url:r},docsUrl:`${O}/CF_6012`}),invalidIP:r=>new y({code:"CF_6013",message:`Invalid IP address format: ${r}`,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:r},docsUrl:`${O}/CF_6013`}),largeIPList:r=>new y({code:"CF_6014",message:`Large IP list detected (${r} IPs)`,suggestion:"Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance with large IP lists",details:{count:r},docsUrl:`${O}/CF_6014`}),rulesetNotFound:r=>new y({code:"CF_6000",message:r?`Ruleset not found: ${r}`:"Ruleset not found",suggestion:"The ruleset may have been deleted. Try running the command again to create a new one.",details:{rulesetId:r},docsUrl:`${O}/CF_6000`}),listNotFound:r=>new y({code:"CF_6003",message:r?`List not found: ${r}`:"List not found",suggestion:"The IP list may have been deleted. Try running the command again to create a new one.",details:{listId:r},docsUrl:`${O}/CF_6003`}),emptyCharacteristics:r=>new y({code:"CF_6015",message:`Rate limit rule "${r}" has empty characteristics`,suggestion:'Add characteristics like ["ip.src"] or remove the characteristics array to use default',details:{ruleName:r},docsUrl:`${O}/CF_6015`}),translationWarning:(r,e)=>new y({code:"CF_6018",message:`Translation warning for feature "${r}": ${e}`,suggestion:"Review the translated configuration and adjust if necessary",details:{feature:r,limitation:e},docsUrl:`${O}/CF_6018`}),featureUnsupported:(r,e)=>new y({code:"CF_6019",message:`Feature "${r}" is not supported when migrating from ${e} to Cloudflare`,suggestion:"Remove this feature or implement it using Cloudflare-specific alternatives",details:{feature:r,provider:e},docsUrl:`${O}/CF_6019`}),planLimitExceeded:(r,e,t)=>new y({code:"CF_6020",message:`${r} limit exceeded: ${t}/${e}`,suggestion:"Consider upgrading your Cloudflare plan or reducing resource usage",details:{resource:r,limit:e,current:t},docsUrl:`${O}/CF_6020`}),zoneSuspended:(r,e)=>new y({code:"CF_6021",message:`Zone is suspended: ${r}${e?` (${e})`:""}`,suggestion:"Contact Cloudflare support to resolve zone suspension issues",details:{zoneId:r,reason:e},docsUrl:`${O}/CF_6021`}),maintenanceMode:r=>new y({code:"CF_6022",message:`Cloudflare ${r} is currently in maintenance mode`,suggestion:"Wait for maintenance to complete and try again. Check Cloudflare status page for updates.",details:{service:r,statusPage:"https://www.cloudflarestatus.com/"},docsUrl:`${O}/CF_6022`}),quotaExceeded:(r,e)=>new y({code:"CF_6023",message:`${r} 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:r,resetTime:e},docsUrl:`${O}/CF_6023`}),listsAPIUnavailable:(r,e)=>new y({code:"CF_6004",message:`Lists API unavailable: ${r}`,suggestion:`Falling back to ${e}. To enable Lists API, provide CLOUDFLARE_ACCOUNT_ID and ensure your API token has Account:Read permissions.`,details:{reason:r,fallbackAction:e,severity:"warning"},docsUrl:`${O}/setup#account-id`}),performanceWarning:(r,e,t)=>new y({code:"CF_6014",message:`Performance warning: ${r} with ${e} items`,suggestion:`${t} Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance.`,details:{operation:r,count:e,impact:t,severity:"warning"},docsUrl:`${O}/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[n,s]of Object.entries(this.ERROR_PATTERNS)){let c=s.keywords.filter(l=>t.includes(l)).length/s.keywords.length;c>i.confidence&&(i={pattern:n,confidence:c})}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 n={status:0,code:e.errors[0]?.code||0,message:e.errors.map(s=>s.message).join(", "),endpoint:t,details:{errors:e.errors,messages:e.messages}};return this.mapCloudflareErrorCode(n)}static handleCredentialError(e,t){switch(e){case"token":return new y({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 y({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 y({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 y({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 y({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 n=[e];if(i?.pattern&&i.confidence>.5){let c=this.ERROR_PATTERNS[i.pattern];n.push(c.suggestion)}let a={"syncing rules":"Try running with --dry-run first to validate your configuration.","fetching configuration":"Verify your zone ID is correct and accessible.","validating credentials":"Double-check your API token permissions in the Cloudflare dashboard.","creating ruleset":"Ensure you have Zone:Edit permissions for the specified zone.","updating rules":"Check if you have reached your plan's rule limit."}[t];return a&&n.push(a),n.join(" ")}static formatTranslationWarning(e,t,i){let{TranslationWarningSystem:n}=(ue(),ce(ge)),s;try{s=n.createWarning(e,void 0,void 0,i)}catch{s=n.createLossyConversionWarning(e,`${i} (from ${t})`,void 0,void 0)}return n.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 y({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 y({code:"NET_8001",message:`Network connection failed during ${t}`,suggestion:s,details:{operation:t,originalError:e.message,dnsResolutionFailed:e.message.includes("ENOTFOUND"),connectionRefused:e.message.includes("ECONNREFUSED")},cause:e,docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#connectivity`})}let n=this.createEnhancedSuggestion("Check your internet connection and try again",t,i);return new y({code:"NET_8004",message:`Network error during ${t}: ${e.message}`,suggestion:n,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),n=e.toLowerCase().includes("ms")?1:1e3;return i*n}}static handleGracefulDegradation(e,t,i,n){let a={lists_api:{code:"CF_6004",suggestion:"Provide CLOUDFLARE_ACCOUNT_ID to enable Lists API for better performance with large IP lists."},managed_rules:{code:"CF_6019",suggestion:"Use custom rules with equivalent conditions instead of managed rules."},advanced_expressions:{code:"CF_6018",suggestion:"Simplify expressions to use supported Cloudflare Wirefilter syntax."}}[e]||{code:"CF_6019",suggestion:"Consider alternative approaches or manual configuration."};return new y({code:a.code,message:`Feature degradation: ${e} - ${t}`,suggestion:`${a.suggestion} Fallback: ${i}${n?` Impact: ${n}`:""}`,details:{feature:e,reason:t,fallbackAction:i,impact:n,degradationType:"graceful"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#feature-degradation`})}static createUserFriendlyMessage(e,t,i){let n=`Failed to ${e}`,s=i?` (${Object.entries(i).map(([l,d])=>`${l}: ${d}`).join(", ")})`:"",c={401:"Please check your API token in the Cloudflare dashboard.",403:"Verify your API token has the required permissions.",404:"The requested resource may have been deleted or moved.",429:"You are being rate limited. Please wait before retrying.",500:"Cloudflare is experiencing issues. Check their status page."}[t.status]||"Please check your configuration and try again.";return`${n}${s}. ${c}`}static handleBadRequestError(e){return e.message.includes("expression")?new y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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 y({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`})}}};P();var en={defaultTTL:300*1e3,maxEntries:100,enableLogging:!0},dt=class{cache=new Map;options;stats={hits:0,misses:0,evictions:0};constructor(e={}){this.options={...en,...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 n=i??this.options.defaultTTL;this.cache.set(e,{value:t,expiresAt:Date.now()+n,createdAt:Date.now(),hits:0}),this.options.enableLogging&&o.debug(`Cache set: ${e} (TTL: ${n}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,n]of this.cache.entries()){if(Date.now()>n.expiresAt){this.cache.delete(i),this.stats.evictions++;return}(!t||n.hits<t.hits||n.hits===t.hits&&n.createdAt<t.createdAt)&&(e=i,t=n)}e&&(this.cache.delete(e),this.stats.evictions++,this.options.enableLogging&&o.debug(`Cache evicted LRU entry: ${e}`))}},_e={zoneInfo:r=>`zone:${r}:info`,rulesets:r=>`zone:${r}:rulesets`,ruleset:(r,e)=>`zone:${r}:ruleset:${e}`,lists:r=>`account:${r}:lists`,listItems:(r,e)=>`account:${r}:list:${e}:items`,credentialValidation:r=>`cred:${r}`,configValidation:r=>`config:${r}`},De={ZONE_INFO:600*1e3,RULESETS:120*1e3,RULESET:60*1e3,LISTS:300*1e3,LIST_ITEMS:120*1e3,CREDENTIALS:900*1e3,CONFIG_VALIDATION:300*1e3};P();var tn={maxConnections:6,idleTimeout:3e4,keepAlive:!0},on={ttl:5e3,maxEntries:100},Le=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={...tn,...e},this.dedupOptions={...on,...t}}computeRuleHash(e){let t=this.canonicalizeRule(e),i=this.hashCache.get(t);if(i)return i;let n=this.simpleHash(t);return this.hashCache.set(t,n),n}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 n=new Map;for(let p of t){let m=p.id||p.name;n.set(m,{rule:p,hash:this.computeRuleHash(p)})}let s=new Map,a=[],c=[],l=0;for(let p of e){let m=p.id||p.name;s.set(m,!0);let h=n.get(m);h?this.computeRuleHash(p)!==h.hash?c.push(p):l++:a.push(p)}let d=[];for(let[p,m]of n)s.has(p)||d.push(m.rule);let u=performance.now()-i;return this.stats.diffTotalDuration+=u,o.debug(`Optimized diff: +${a.length} ~${c.length} -${d.length} =${l} (${u.toFixed(1)}ms)`),{toAdd:a,toUpdate:c,toDelete:d,unchanged:l,duration:u}}diffCloudflareRules(e,t){let i=new Map(t.map(l=>[l.id,l])),n=new Set,s=[],a=[];for(let{rule:l,translated:d}of e){let u=l.id||l.name;n.add(u);let p=i.get(u);p?this.cloudflareRulesEqual(d,p)||a.push(l):s.push(l)}let c=[];for(let[l,d]of i)n.has(l)||c.push(d);return{toAdd:s,toUpdate:a,toDelete:c}}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 n=new Map;for(let p of t)n.set(p.ip,p);let s=new Set,a=[],c=[],l=0;for(let p of e){s.add(p.ip);let m=n.get(p.ip);m?p.action!==m.action?c.push(p):l++:a.push(p)}let d=[];for(let[p,m]of n)s.has(p)||d.push(m);let u=performance.now()-i;return{toAdd:a,toUpdate:c,toDelete:d,unchanged:l,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 n=0;n<e.length;n++){let s=n,a=e[s],c=this.withConnection(async()=>{t[s]=await a()});i.push(c)}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 n=t().finally(()=>{this.inFlightRequests.delete(e)});return this.inFlightRequests.set(e,{promise:n,createdAt:Date.now()}),n}static requestKey(e,t,i){let n=[e.toUpperCase(),t];return i&&n.push(i),n.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((n,s)=>n[1].createdAt-s[1].createdAt);let i=t.slice(0,t.length-this.dedupOptions.maxEntries);for(let[n]of i)this.inFlightRequests.delete(n)}}async processInChunks(e,t,i){if(e.length===0)return[];this.stats.chunkedOperations++;let n=[],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 c=e.slice(a,a+t),l=Math.floor(a/t),d=await i(c,l);n.push(...d)}return n}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 n=i/t;return Math.ceil(n*e.length)}getOptimalChunkSize(e,t=500){let n=Math.max(10,Math.floor(1048576/t)),s=Math.min(n,100);return e<=s?e:s}getStats(){return{...this.stats}}resetStats(){this.stats={diffOperations:0,diffTotalDuration:0,earlyExits:0,deduplicatedRequests:0,pooledConnections:0,chunkedOperations:0}}clearCaches(){this.hashCache.clear(),this.inFlightRequests.clear()}getActiveConnections(){return this.activeConnections}getPendingConnections(){return this.connectionQueue.length}getInFlightCount(){return this.inFlightRequests.size}canonicalizeRule(e){let t={action:e.action,conditions:e.conditions.map(i=>({field:i.field,key:i.key,negated:i.negated,operator:i.operator,value:i.value})).sort((i,n)=>`${i.field}:${i.operator}`.localeCompare(`${n.field}:${n.operator}`)),enabled:e.enabled,name:e.name};return e.conditionLogic&&(t.conditionLogic=e.conditionLogic),e.description&&(t.description=e.description),e.priority!==void 0&&(t.priority=e.priority),JSON.stringify(t)}simpleHash(e){let t=5381;for(let i=0;i<e.length;i++)t=(t<<5)+t+e.charCodeAt(i)|0;return t.toString(36)}};var qe=class extends Ne{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 dt({enableLogging:!0}),this.optimizer=new Le}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=_e.rulesets(this.zoneId),t=this.cache.get(e);if(t)return t;let i=Le.requestKey("GET",`/zones/${this.zoneId}/rulesets`);return this.optimizer.deduplicateRequest(i,async()=>{try{let n=await this.get(`/zones/${this.zoneId}/rulesets`);if(!n.success)throw Q.handleApiResponse(n,`/zones/${this.zoneId}/rulesets`);if(!Array.isArray(n.result))return o.warn("Malformed API response: expected array of rulesets, got:",typeof n.result),[];let s=n.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!==n.result.length&&o.warn(`Filtered out ${n.result.length-s.length} malformed rulesets`),this.cache.set(e,s,De.RULESETS),s}catch(n){throw n instanceof Error&&!n.code?Q.handleNetworkError(n,"listing rulesets"):n}})}async getRulesets(){return this.listRulesets()}async getRuleset(e){o.debug(`Fetching ruleset ${e}`);let t=_e.ruleset(this.zoneId,e),i=this.cache.get(t);if(i)return i;let n=Le.requestKey("GET",`/zones/${this.zoneId}/rulesets/${e}`);return this.optimizer.deduplicateRequest(n,async()=>{try{let s=await this.get(`/zones/${this.zoneId}/rulesets/${e}`);if(!s.success)throw 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 c=a.rules.filter(l=>!l||typeof l!="object"?(o.warn(`Skipping malformed rule in ruleset ${e}:`,l),!1):!l.id||!l.expression||!l.action?(o.warn(`Skipping rule with missing required fields in ruleset ${e}:`,{id:l.id,expression:l.expression,action:l.action}),!1):!0);return c.length!==a.rules.length&&(o.warn(`Filtered out ${a.rules.length-c.length} malformed rules from ruleset ${e}`),a.rules=c),this.cache.set(t,a,De.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(n=>n.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 n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}`,i.errors[0]?.code||0,n)}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(n=>n.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 n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules`,i.errors[0]?.code||0,n)}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 n=await this.patch(`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,i);if(!n.success){let s=n.errors.map(a=>a.message).join(", ");throw J.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,n.errors[0]?.code||0,s)}return o.info(`Updated rule ${t}`),this.invalidateRulesetCache(),n.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 n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,i.errors[0]?.code||0,n)}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,Fi.createHash)("sha256").update(this.apiToken).digest("hex").slice(0,8),t=_e.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,De.CREDENTIALS),!0}catch(n){if(o.error(`Cloudflare credential verification failed: ${n}`),n instanceof Error){let s=n.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=_e.zoneInfo(this.zoneId),t=this.cache.get(e);if(t)return t;let i=await this.get(`/zones/${this.zoneId}`);if(!i.success){let n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/zones/${this.zoneId}`,i.errors[0]?.code||0,n)}return this.cache.set(e,i.result,De.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=_e.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 n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,i.errors[0]?.code||0,n)}return this.cache.set(e,i.result,De.LISTS),i.result}async getList(e){if(o.debug(`Fetching List ${e}`),!this.accountId)throw G.accountIdRequired("Lists API");let t=await this.get(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let i=t.errors.map(n=>n.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 G.accountIdRequired("Lists API");let t=await this.post(`/accounts/${this.accountId}/rules/lists`,e);if(!t.success){let i=t.errors.map(n=>n.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 G.accountIdRequired("Lists API");let i=await this.put(`/accounts/${this.accountId}/rules/lists/${e}`,t);if(!i.success){let n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,i.errors[0]?.code||0,n)}return o.info(`Updated List ${e}`),this.invalidateListCache(),i.result}async deleteList(e){if(o.debug(`Deleting List ${e}`),!this.accountId)throw G.accountIdRequired("Lists API");let t=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let i=t.errors.map(n=>n.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 G.accountIdRequired("Lists API");let t=_e.listItems(this.accountId,e),i=this.cache.get(t);if(i)return i;let n=Le.requestKey("GET",`/accounts/${this.accountId}/rules/lists/${e}/items`);return this.optimizer.deduplicateRequest(n,async()=>{let s=await this.fetchAllListItemPages(e);return this.cache.set(t,s,De.LIST_ITEMS),s})}async fetchAllListItemPages(e){let t=[],i=1;for(;;){let n=await this.get(`/accounts/${this.accountId}/rules/lists/${e}/items?page=${i}`);if(!n.success){let a=n.errors.map(c=>c.message).join(", ");throw J.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,n.errors[0]?.code||0,a)}t.push(...n.result);let s=n.result_info?.total_pages??1;if(n.result.length===0||i>=s)break;i++}return t}async addListItems(e,t){if(o.debug(`Adding ${t.items.length} items to List ${e}`),!this.accountId)throw G.accountIdRequired("Lists API");let i=await this.post(`/accounts/${this.accountId}/rules/lists/${e}/items`,t.items);if(!i.success){let n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,i.errors[0]?.code||0,n)}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 G.accountIdRequired("Lists API");let i=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}/items`,{body:JSON.stringify(t)});if(!i.success){let n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,i.errors[0]?.code||0,n)}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 Ge=require("net");P();var Qe=class r extends Be{name="cloudflare";client;optimizer;useListsForIPs;constructor(e,t,i){super(),this.client=new qe(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=[],n=[],s=[],a=[],c=50,l=t.rules.length;l>100&&o.info(`Processing ${l} rules in batches of ${c} to optimize memory usage`);for(let d=0;d<l;d+=c){let u=t.rules.slice(d,d+c);o.debug(`Processing rules batch ${Math.floor(d/c)+1}/${Math.ceil(l/c)} (${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);n.push(m)}else{let m=W.cloudflareToUnified(p);i.push(m.result),m.warnings.length>0&&m.warnings.forEach(h=>{let{TranslationWarningSystem:v}=(ue(),ce(ge)),f=v.formatWarning(h);s.push(f)})}}catch(m){let h=`Failed to process rule ${p?.id||"unknown"}: ${m instanceof Error?m.message:String(m)}`;o.warn(h),a.push(h)}l>200&&d+c<l&&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&&n.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 n.length>10&&o.warn(`\u26A0\uFE0F Large IP list detected (${n.length} IPs) without Lists API. Consider providing CLOUDFLARE_ACCOUNT_ID for better performance.`);return s.length>0&&(o.warn("Translation warnings detected:"),s.forEach(d=>o.warn(d)),s.length>3&&o.warn(`
|
|
44
|
-
\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:n,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}=(Ot(),ce(xt)),n=await i.performDryRunValidation(e,"sync rules",async v=>await this.getChanges(v));if(!n.valid)throw new Error(`Dry-run validation failed: ${n.issues.join(", ")}`);if(t?.dryRun)return{success:!0,rulesAdded:n.changes.rulesToAdd.length,rulesUpdated:n.changes.rulesToUpdate.length,rulesDeleted:n.changes.rulesToDelete.length,ipsAdded:n.changes.ipsToAdd?.length||0,ipsUpdated:n.changes.ipsToUpdate?.length||0,ipsDeleted:n.changes.ipsToDelete?.length||0,warnings:n.warnings};let s=i.assessOperationRisk(n.changes,e);if(!await i.confirmDestructiveOperation({operation:"sync rules",target:`Cloudflare zone ${this.client.zoneId}`,changes:n.changes,riskLevel:s,skipConfirmation:t?.force||!1,dryRun:t?.dryRun||!1,allowDeletions:t?.allowDeletions||!1}))throw new Error("Operation cancelled by user");let c=await this.client.getOrCreateFirewallRuleset(),l=[];for(let v of e.rules){let f=W.unifiedToCloudflare(v);l.push(f.result),f.warnings.length>0&&f.warnings.forEach(E=>{let{TranslationWarningSystem:U}=(ue(),ce(ge)),x=U.formatWarning(E);o.warn(x)})}let d=0,u=0,p=0;if(this.useListsForIPs&&e.ips&&e.ips.length>0){let v=new Set;try{let f=await this.client.getOrCreateIPBlocklist(),E=await this.client.getListItems(f.id),U=new Set(E.map(I=>I.ip));U.forEach(I=>I&&v.add(I));let x=new Set(e.ips.map(I=>I.ip)),g=e.ips.filter(I=>!U.has(I.ip));g.length>0&&(await this.client.addListItems(f.id,{items:g.map(I=>({ip:I.ip,comment:I.notes||I.hostname||"Blocked by Doorman"}))}),d=g.length,g.forEach(I=>v.add(I.ip)),o.info(`Added ${d} IPs to List`));let A=E.filter(I=>I.ip&&!x.has(I.ip));A.length>0&&(await this.client.removeListItems(f.id,{items:A.map(I=>({id:I.id}))}),p=A.length,A.forEach(I=>I.ip&&v.delete(I.ip)),o.info(`Removed ${p} IPs from List`));let
|
|
43
|
+
`)}static isDoormanError(e){return e instanceof r}static from(e,t,i){return r.isDoormanError(e)?e:e instanceof Error?new r({code:t,message:i||e.message,cause:e}):new r({code:t,message:i||String(e)})}};var O="https://docs.doorman.griffen.codes/errors";var J={authFailed:(r,e)=>new w({code:"PROV_5000",message:`Authentication failed for ${r}`,suggestion:"Check that your API credentials are valid and have the correct permissions",details:{provider:r},cause:e,docsUrl:`${O}/PROV_5000`}),apiError:(r,e,t,i)=>new w({code:"PROV_5002",message:`${r} API error: ${t} ${i}`,suggestion:"Check the provider status page and your credentials",details:{provider:r,endpoint:e,statusCode:t,responseMessage:i},docsUrl:`${O}/PROV_5002`}),rateLimit:(r,e)=>new w({code:"PROV_5003",message:`Rate limit exceeded for ${r}`,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:r,retryAfter:e},docsUrl:`${O}/PROV_5003`}),timeout:(r,e)=>new w({code:"PROV_5006",message:`Request timeout for ${r} ${e}`,suggestion:"Check your internet connection and try again",details:{provider:r,operation:e},docsUrl:`${O}/PROV_5006`}),invalidCredentials:(r,e)=>new w({code:"PROV_5004",message:`Missing or invalid credentials for ${r}`,suggestion:`Please provide: ${e.join(", ")}`,details:{provider:r,missing:e},docsUrl:`${O}/PROV_5004`})},G={accountIdRequired:r=>new w({code:"CF_6004",message:`Account ID required for ${r}`,suggestion:"Provide CLOUDFLARE_ACCOUNT_ID in your environment or configuration to use Lists API",details:{operation:r},docsUrl:`${O}/CF_6004`}),zoneIdRequired:r=>new w({code:"CF_6005",message:`Zone ID required for ${r}`,suggestion:"Provide CLOUDFLARE_ZONE_ID in your environment or configuration",details:{operation:r},docsUrl:`${O}/CF_6005`}),invalidCredentials:(r,e)=>new w({code:"CF_6016",message:`Invalid Cloudflare ${r}`,suggestion:"Check your Cloudflare API credentials and ensure they have the correct permissions",details:{credentialType:r,...e},docsUrl:`${O}/CF_6016`}),insufficientPermissions:(r,e)=>new w({code:"CF_6017",message:`Insufficient permissions for ${r}`,suggestion:`Ensure your API token has the following permissions: ${e.join(", ")}`,details:{operation:r,requiredPermissions:e},docsUrl:`${O}/CF_6017`}),ruleLimitExceeded:(r,e)=>new w({code:"CF_6001",message:`Rule count (${r}) exceeds Cloudflare limit (${e})`,suggestion:"Consider consolidating rules, using Lists for IP blocking, or upgrading your Cloudflare plan",details:{count:r,limit:e},docsUrl:`${O}/CF_6001`}),invalidExpression:(r,e)=>new w({code:"CF_6002",message:`Invalid Cloudflare expression: ${e}`,suggestion:"Check Cloudflare Wirefilter expression syntax and field names",details:{expression:r,reason:e},docsUrl:`${O}/CF_6002`}),ruleNoConditions:r=>new w({code:"CF_6007",message:`Rule "${r}" has no conditions`,suggestion:"Add at least one condition to the rule or remove the empty rule",details:{ruleName:r},docsUrl:`${O}/CF_6007`}),invalidRateLimit:(r,e)=>new w({code:"CF_6008",message:`Invalid rate limit configuration for rule "${r}": ${e}`,suggestion:'Rate limit requests must be at least 1, and window format should be like "60s", "1h", "1d"',details:{ruleName:r,issue:e},docsUrl:`${O}/CF_6008`}),invalidWindowFormat:r=>new w({code:"CF_6009",message:`Invalid rate limit window format: ${r}`,suggestion:'Use format like "60s", "5m", "1h", or "1d"',details:{window:r},docsUrl:`${O}/CF_6009`}),shortMitigationTimeout:r=>new w({code:"CF_6010",message:`Mitigation timeout (${r}s) may be too short`,suggestion:"Consider using at least 60 seconds for effective rate limiting",details:{timeout:r},docsUrl:`${O}/CF_6010`}),redirectNoLocation:r=>new w({code:"CF_6011",message:`Redirect rule "${r}" is missing location URL`,suggestion:"Add a redirect.location property with a valid URL or path",details:{ruleName:r},docsUrl:`${O}/CF_6011`}),invalidRedirectUrl:r=>new w({code:"CF_6012",message:`Invalid redirect URL: ${r}`,suggestion:"Use a valid absolute URL (https://...) or relative path (/...)",details:{url:r},docsUrl:`${O}/CF_6012`}),invalidIP:r=>new w({code:"CF_6013",message:`Invalid IP address format: ${r}`,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:r},docsUrl:`${O}/CF_6013`}),largeIPList:r=>new w({code:"CF_6014",message:`Large IP list detected (${r} IPs)`,suggestion:"Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance with large IP lists",details:{count:r},docsUrl:`${O}/CF_6014`}),rulesetNotFound:r=>new w({code:"CF_6000",message:r?`Ruleset not found: ${r}`:"Ruleset not found",suggestion:"The ruleset may have been deleted. Try running the command again to create a new one.",details:{rulesetId:r},docsUrl:`${O}/CF_6000`}),listNotFound:r=>new w({code:"CF_6003",message:r?`List not found: ${r}`:"List not found",suggestion:"The IP list may have been deleted. Try running the command again to create a new one.",details:{listId:r},docsUrl:`${O}/CF_6003`}),emptyCharacteristics:r=>new w({code:"CF_6015",message:`Rate limit rule "${r}" has empty characteristics`,suggestion:'Add characteristics like ["ip.src"] or remove the characteristics array to use default',details:{ruleName:r},docsUrl:`${O}/CF_6015`}),translationWarning:(r,e)=>new w({code:"CF_6018",message:`Translation warning for feature "${r}": ${e}`,suggestion:"Review the translated configuration and adjust if necessary",details:{feature:r,limitation:e},docsUrl:`${O}/CF_6018`}),featureUnsupported:(r,e)=>new w({code:"CF_6019",message:`Feature "${r}" is not supported when migrating from ${e} to Cloudflare`,suggestion:"Remove this feature or implement it using Cloudflare-specific alternatives",details:{feature:r,provider:e},docsUrl:`${O}/CF_6019`}),planLimitExceeded:(r,e,t)=>new w({code:"CF_6020",message:`${r} limit exceeded: ${t}/${e}`,suggestion:"Consider upgrading your Cloudflare plan or reducing resource usage",details:{resource:r,limit:e,current:t},docsUrl:`${O}/CF_6020`}),zoneSuspended:(r,e)=>new w({code:"CF_6021",message:`Zone is suspended: ${r}${e?` (${e})`:""}`,suggestion:"Contact Cloudflare support to resolve zone suspension issues",details:{zoneId:r,reason:e},docsUrl:`${O}/CF_6021`}),maintenanceMode:r=>new w({code:"CF_6022",message:`Cloudflare ${r} is currently in maintenance mode`,suggestion:"Wait for maintenance to complete and try again. Check Cloudflare status page for updates.",details:{service:r,statusPage:"https://www.cloudflarestatus.com/"},docsUrl:`${O}/CF_6022`}),quotaExceeded:(r,e)=>new w({code:"CF_6023",message:`${r} 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:r,resetTime:e},docsUrl:`${O}/CF_6023`}),listsAPIUnavailable:(r,e)=>new w({code:"CF_6004",message:`Lists API unavailable: ${r}`,suggestion:`Falling back to ${e}. To enable Lists API, provide CLOUDFLARE_ACCOUNT_ID and ensure your API token has Account:Read permissions.`,details:{reason:r,fallbackAction:e,severity:"warning"},docsUrl:`${O}/setup#account-id`}),performanceWarning:(r,e,t)=>new w({code:"CF_6014",message:`Performance warning: ${r} with ${e} items`,suggestion:`${t} Consider providing CLOUDFLARE_ACCOUNT_ID to use Lists API for better performance.`,details:{operation:r,count:e,impact:t,severity:"warning"},docsUrl:`${O}/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[n,s]of Object.entries(this.ERROR_PATTERNS)){let c=s.keywords.filter(l=>t.includes(l)).length/s.keywords.length;c>i.confidence&&(i={pattern:n,confidence:c})}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 n={status:0,code:e.errors[0]?.code||0,message:e.errors.map(s=>s.message).join(", "),endpoint:t,details:{errors:e.errors,messages:e.messages}};return this.mapCloudflareErrorCode(n)}static handleCredentialError(e,t){switch(e){case"token":return new w({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 w({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 w({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 w({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 w({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 n=[e];if(i?.pattern&&i.confidence>.5){let c=this.ERROR_PATTERNS[i.pattern];n.push(c.suggestion)}let a={"syncing rules":"Try running with --dry-run first to validate your configuration.","fetching configuration":"Verify your zone ID is correct and accessible.","validating credentials":"Double-check your API token permissions in the Cloudflare dashboard.","creating ruleset":"Ensure you have Zone:Edit permissions for the specified zone.","updating rules":"Check if you have reached your plan's rule limit."}[t];return a&&n.push(a),n.join(" ")}static formatTranslationWarning(e,t,i){let{TranslationWarningSystem:n}=(ue(),ce(ge)),s;try{s=n.createWarning(e,void 0,void 0,i)}catch{s=n.createLossyConversionWarning(e,`${i} (from ${t})`,void 0,void 0)}return n.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 w({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 w({code:"NET_8001",message:`Network connection failed during ${t}`,suggestion:s,details:{operation:t,originalError:e.message,dnsResolutionFailed:e.message.includes("ENOTFOUND"),connectionRefused:e.message.includes("ECONNREFUSED")},cause:e,docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#connectivity`})}let n=this.createEnhancedSuggestion("Check your internet connection and try again",t,i);return new w({code:"NET_8004",message:`Network error during ${t}: ${e.message}`,suggestion:n,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),n=e.toLowerCase().includes("ms")?1:1e3;return i*n}}static handleGracefulDegradation(e,t,i,n){let a={lists_api:{code:"CF_6004",suggestion:"Provide CLOUDFLARE_ACCOUNT_ID to enable Lists API for better performance with large IP lists."},managed_rules:{code:"CF_6019",suggestion:"Use custom rules with equivalent conditions instead of managed rules."},advanced_expressions:{code:"CF_6018",suggestion:"Simplify expressions to use supported Cloudflare Wirefilter syntax."}}[e]||{code:"CF_6019",suggestion:"Consider alternative approaches or manual configuration."};return new w({code:a.code,message:`Feature degradation: ${e} - ${t}`,suggestion:`${a.suggestion} Fallback: ${i}${n?` Impact: ${n}`:""}`,details:{feature:e,reason:t,fallbackAction:i,impact:n,degradationType:"graceful"},docsUrl:`${this.DOCS_BASE_URL}/troubleshooting#feature-degradation`})}static createUserFriendlyMessage(e,t,i){let n=`Failed to ${e}`,s=i?` (${Object.entries(i).map(([l,d])=>`${l}: ${d}`).join(", ")})`:"",c={401:"Please check your API token in the Cloudflare dashboard.",403:"Verify your API token has the required permissions.",404:"The requested resource may have been deleted or moved.",429:"You are being rate limited. Please wait before retrying.",500:"Cloudflare is experiencing issues. Check their status page."}[t.status]||"Please check your configuration and try again.";return`${n}${s}. ${c}`}static handleBadRequestError(e){return e.message.includes("expression")?new w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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 w({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`})}}};k();var tn={defaultTTL:300*1e3,maxEntries:100,enableLogging:!0},dt=class{cache=new Map;options;stats={hits:0,misses:0,evictions:0};constructor(e={}){this.options={...tn,...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 n=i??this.options.defaultTTL;this.cache.set(e,{value:t,expiresAt:Date.now()+n,createdAt:Date.now(),hits:0}),this.options.enableLogging&&o.debug(`Cache set: ${e} (TTL: ${n}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,n]of this.cache.entries()){if(Date.now()>n.expiresAt){this.cache.delete(i),this.stats.evictions++;return}(!t||n.hits<t.hits||n.hits===t.hits&&n.createdAt<t.createdAt)&&(e=i,t=n)}e&&(this.cache.delete(e),this.stats.evictions++,this.options.enableLogging&&o.debug(`Cache evicted LRU entry: ${e}`))}},_e={zoneInfo:r=>`zone:${r}:info`,rulesets:r=>`zone:${r}:rulesets`,ruleset:(r,e)=>`zone:${r}:ruleset:${e}`,lists:r=>`account:${r}:lists`,listItems:(r,e)=>`account:${r}:list:${e}:items`,credentialValidation:r=>`cred:${r}`,configValidation:r=>`config:${r}`},De={ZONE_INFO:600*1e3,RULESETS:120*1e3,RULESET:60*1e3,LISTS:300*1e3,LIST_ITEMS:120*1e3,CREDENTIALS:900*1e3,CONFIG_VALIDATION:300*1e3};k();var on={maxConnections:6,idleTimeout:3e4,keepAlive:!0},nn={ttl:5e3,maxEntries:100},Le=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={...on,...e},this.dedupOptions={...nn,...t}}computeRuleHash(e){let t=this.canonicalizeRule(e),i=this.hashCache.get(t);if(i)return i;let n=this.simpleHash(t);return this.hashCache.set(t,n),n}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 n=new Map;for(let p of t){let m=p.id||p.name;n.set(m,{rule:p,hash:this.computeRuleHash(p)})}let s=new Map,a=[],c=[],l=0;for(let p of e){let m=p.id||p.name;s.set(m,!0);let h=n.get(m);h?this.computeRuleHash(p)!==h.hash?c.push(p):l++:a.push(p)}let d=[];for(let[p,m]of n)s.has(p)||d.push(m.rule);let u=performance.now()-i;return this.stats.diffTotalDuration+=u,o.debug(`Optimized diff: +${a.length} ~${c.length} -${d.length} =${l} (${u.toFixed(1)}ms)`),{toAdd:a,toUpdate:c,toDelete:d,unchanged:l,duration:u}}diffCloudflareRules(e,t){let i=new Map(t.map(l=>[l.id,l])),n=new Set,s=[],a=[];for(let{rule:l,translated:d}of e){let u=l.id||l.name;n.add(u);let p=i.get(u);p?this.cloudflareRulesEqual(d,p)||a.push(l):s.push(l)}let c=[];for(let[l,d]of i)n.has(l)||c.push(d);return{toAdd:s,toUpdate:a,toDelete:c}}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 n=new Map;for(let p of t)n.set(p.ip,p);let s=new Set,a=[],c=[],l=0;for(let p of e){s.add(p.ip);let m=n.get(p.ip);m?p.action!==m.action?c.push(p):l++:a.push(p)}let d=[];for(let[p,m]of n)s.has(p)||d.push(m);let u=performance.now()-i;return{toAdd:a,toUpdate:c,toDelete:d,unchanged:l,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 n=0;n<e.length;n++){let s=n,a=e[s],c=this.withConnection(async()=>{t[s]=await a()});i.push(c)}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 n=t().finally(()=>{this.inFlightRequests.delete(e)});return this.inFlightRequests.set(e,{promise:n,createdAt:Date.now()}),n}static requestKey(e,t,i){let n=[e.toUpperCase(),t];return i&&n.push(i),n.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((n,s)=>n[1].createdAt-s[1].createdAt);let i=t.slice(0,t.length-this.dedupOptions.maxEntries);for(let[n]of i)this.inFlightRequests.delete(n)}}async processInChunks(e,t,i){if(e.length===0)return[];this.stats.chunkedOperations++;let n=[],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 c=e.slice(a,a+t),l=Math.floor(a/t),d=await i(c,l);n.push(...d)}return n}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 n=i/t;return Math.ceil(n*e.length)}getOptimalChunkSize(e,t=500){let n=Math.max(10,Math.floor(1048576/t)),s=Math.min(n,100);return e<=s?e:s}getStats(){return{...this.stats}}resetStats(){this.stats={diffOperations:0,diffTotalDuration:0,earlyExits:0,deduplicatedRequests:0,pooledConnections:0,chunkedOperations:0}}clearCaches(){this.hashCache.clear(),this.inFlightRequests.clear()}getActiveConnections(){return this.activeConnections}getPendingConnections(){return this.connectionQueue.length}getInFlightCount(){return this.inFlightRequests.size}canonicalizeRule(e){let t={action:e.action,conditions:e.conditions.map(i=>({field:i.field,key:i.key,negated:i.negated,operator:i.operator,value:i.value})).sort((i,n)=>`${i.field}:${i.operator}`.localeCompare(`${n.field}:${n.operator}`)),enabled:e.enabled,name:e.name};return e.conditionLogic&&(t.conditionLogic=e.conditionLogic),e.description&&(t.description=e.description),e.priority!==void 0&&(t.priority=e.priority),JSON.stringify(t)}simpleHash(e){let t=5381;for(let i=0;i<e.length;i++)t=(t<<5)+t+e.charCodeAt(i)|0;return t.toString(36)}};var qe=class extends Fe{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 dt({enableLogging:!0}),this.optimizer=new Le}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=_e.rulesets(this.zoneId),t=this.cache.get(e);if(t)return t;let i=Le.requestKey("GET",`/zones/${this.zoneId}/rulesets`);return this.optimizer.deduplicateRequest(i,async()=>{try{let n=await this.get(`/zones/${this.zoneId}/rulesets`);if(!n.success)throw Q.handleApiResponse(n,`/zones/${this.zoneId}/rulesets`);if(!Array.isArray(n.result))return o.warn("Malformed API response: expected array of rulesets, got:",typeof n.result),[];let s=n.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!==n.result.length&&o.warn(`Filtered out ${n.result.length-s.length} malformed rulesets`),this.cache.set(e,s,De.RULESETS),s}catch(n){throw n instanceof Error&&!n.code?Q.handleNetworkError(n,"listing rulesets"):n}})}async getRulesets(){return this.listRulesets()}async getRuleset(e){o.debug(`Fetching ruleset ${e}`);let t=_e.ruleset(this.zoneId,e),i=this.cache.get(t);if(i)return i;let n=Le.requestKey("GET",`/zones/${this.zoneId}/rulesets/${e}`);return this.optimizer.deduplicateRequest(n,async()=>{try{let s=await this.get(`/zones/${this.zoneId}/rulesets/${e}`);if(!s.success)throw 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 c=a.rules.filter(l=>!l||typeof l!="object"?(o.warn(`Skipping malformed rule in ruleset ${e}:`,l),!1):!l.id||!l.expression||!l.action?(o.warn(`Skipping rule with missing required fields in ruleset ${e}:`,{id:l.id,expression:l.expression,action:l.action}),!1):!0);return c.length!==a.rules.length&&(o.warn(`Filtered out ${a.rules.length-c.length} malformed rules from ruleset ${e}`),a.rules=c),this.cache.set(t,a,De.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(n=>n.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 n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}`,i.errors[0]?.code||0,n)}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(n=>n.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 n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules`,i.errors[0]?.code||0,n)}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 n=await this.patch(`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,i);if(!n.success){let s=n.errors.map(a=>a.message).join(", ");throw J.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,n.errors[0]?.code||0,s)}return o.info(`Updated rule ${t}`),this.invalidateRulesetCache(),n.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 n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/zones/${this.zoneId}/rulesets/${e}/rules/${t}`,i.errors[0]?.code||0,n)}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,Fi.createHash)("sha256").update(this.apiToken).digest("hex").slice(0,8),t=_e.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,De.CREDENTIALS),!0}catch(n){if(o.error(`Cloudflare credential verification failed: ${n}`),n instanceof Error){let s=n.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=_e.zoneInfo(this.zoneId),t=this.cache.get(e);if(t)return t;let i=await this.get(`/zones/${this.zoneId}`);if(!i.success){let n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/zones/${this.zoneId}`,i.errors[0]?.code||0,n)}return this.cache.set(e,i.result,De.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=_e.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 n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists`,i.errors[0]?.code||0,n)}return this.cache.set(e,i.result,De.LISTS),i.result}async getList(e){if(o.debug(`Fetching List ${e}`),!this.accountId)throw G.accountIdRequired("Lists API");let t=await this.get(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let i=t.errors.map(n=>n.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 G.accountIdRequired("Lists API");let t=await this.post(`/accounts/${this.accountId}/rules/lists`,e);if(!t.success){let i=t.errors.map(n=>n.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 G.accountIdRequired("Lists API");let i=await this.put(`/accounts/${this.accountId}/rules/lists/${e}`,t);if(!i.success){let n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}`,i.errors[0]?.code||0,n)}return o.info(`Updated List ${e}`),this.invalidateListCache(),i.result}async deleteList(e){if(o.debug(`Deleting List ${e}`),!this.accountId)throw G.accountIdRequired("Lists API");let t=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}`);if(!t.success){let i=t.errors.map(n=>n.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 G.accountIdRequired("Lists API");let t=_e.listItems(this.accountId,e),i=this.cache.get(t);if(i)return i;let n=Le.requestKey("GET",`/accounts/${this.accountId}/rules/lists/${e}/items`);return this.optimizer.deduplicateRequest(n,async()=>{let s=await this.fetchAllListItemPages(e);return this.cache.set(t,s,De.LIST_ITEMS),s})}async fetchAllListItemPages(e){let t=[],i=1;for(;;){let n=await this.get(`/accounts/${this.accountId}/rules/lists/${e}/items?page=${i}`);if(!n.success){let a=n.errors.map(c=>c.message).join(", ");throw J.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,n.errors[0]?.code||0,a)}t.push(...n.result);let s=n.result_info?.total_pages??1;if(n.result.length===0||i>=s)break;i++}return t}async addListItems(e,t){if(o.debug(`Adding ${t.items.length} items to List ${e}`),!this.accountId)throw G.accountIdRequired("Lists API");let i=await this.post(`/accounts/${this.accountId}/rules/lists/${e}/items`,t.items);if(!i.success){let n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,i.errors[0]?.code||0,n)}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 G.accountIdRequired("Lists API");let i=await this.delete(`/accounts/${this.accountId}/rules/lists/${e}/items`,{body:JSON.stringify(t)});if(!i.success){let n=i.errors.map(s=>s.message).join(", ");throw J.apiError("cloudflare",`/accounts/${this.accountId}/rules/lists/${e}/items`,i.errors[0]?.code||0,n)}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 Ge=require("net");k();var Qe=class r extends Be{name="cloudflare";client;optimizer;useListsForIPs;constructor(e,t,i){super(),this.client=new qe(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=[],n=[],s=[],a=[],c=50,l=t.rules.length;l>100&&o.info(`Processing ${l} rules in batches of ${c} to optimize memory usage`);for(let d=0;d<l;d+=c){let u=t.rules.slice(d,d+c);o.debug(`Processing rules batch ${Math.floor(d/c)+1}/${Math.ceil(l/c)} (${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);n.push(m)}else{let m=W.cloudflareToUnified(p);i.push(m.result),m.warnings.length>0&&m.warnings.forEach(h=>{let{TranslationWarningSystem:v}=(ue(),ce(ge)),f=v.formatWarning(h);s.push(f)})}}catch(m){let h=`Failed to process rule ${p?.id||"unknown"}: ${m instanceof Error?m.message:String(m)}`;o.warn(h),a.push(h)}l>200&&d+c<l&&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&&n.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 n.length>10&&o.warn(`\u26A0\uFE0F Large IP list detected (${n.length} IPs) without Lists API. Consider providing CLOUDFLARE_ACCOUNT_ID for better performance.`);return s.length>0&&(o.warn("Translation warnings detected:"),s.forEach(d=>o.warn(d)),s.length>3&&o.warn(`
|
|
44
|
+
\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:n,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}=(Ot(),ce(xt)),n=await i.performDryRunValidation(e,"sync rules",async v=>await this.getChanges(v));if(!n.valid)throw new Error(`Dry-run validation failed: ${n.issues.join(", ")}`);if(t?.dryRun)return{success:!0,rulesAdded:n.changes.rulesToAdd.length,rulesUpdated:n.changes.rulesToUpdate.length,rulesDeleted:n.changes.rulesToDelete.length,ipsAdded:n.changes.ipsToAdd?.length||0,ipsUpdated:n.changes.ipsToUpdate?.length||0,ipsDeleted:n.changes.ipsToDelete?.length||0,warnings:n.warnings};let s=i.assessOperationRisk(n.changes,e);if(!await i.confirmDestructiveOperation({operation:"sync rules",target:`Cloudflare zone ${this.client.zoneId}`,changes:n.changes,riskLevel:s,skipConfirmation:t?.force||!1,dryRun:t?.dryRun||!1,allowDeletions:t?.allowDeletions||!1}))throw new Error("Operation cancelled by user");let c=await this.client.getOrCreateFirewallRuleset(),l=[];for(let v of e.rules){let f=W.unifiedToCloudflare(v);l.push(f.result),f.warnings.length>0&&f.warnings.forEach(E=>{let{TranslationWarningSystem:U}=(ue(),ce(ge)),x=U.formatWarning(E);o.warn(x)})}let d=0,u=0,p=0;if(this.useListsForIPs&&e.ips&&e.ips.length>0){let v=new Set;try{let f=await this.client.getOrCreateIPBlocklist(),E=await this.client.getListItems(f.id),U=new Set(E.map(I=>I.ip));U.forEach(I=>I&&v.add(I));let x=new Set(e.ips.map(I=>I.ip)),g=e.ips.filter(I=>!U.has(I.ip));g.length>0&&(await this.client.addListItems(f.id,{items:g.map(I=>({ip:I.ip,comment:I.notes||I.hostname||"Blocked by Doorman"}))}),d=g.length,g.forEach(I=>v.add(I.ip)),o.info(`Added ${d} IPs to List`));let A=E.filter(I=>I.ip&&!x.has(I.ip));A.length>0&&(await this.client.removeListItems(f.id,{items:A.map(I=>({id:I.id}))}),p=A.length,A.forEach(I=>I.ip&&v.delete(I.ip)),o.info(`Removed ${p} IPs from List`));let R=`ip.src in $${f.name.replace(/\s+/g,"_").toLowerCase()}`;l.push({id:"rule_doorman_ip_list",action:"block",expression:R,description:"Block IPs in Doorman IP Blocklist",enabled:!0})}catch(f){this.handleListsAPIFallback(f,"syncing IPs via List");let E=e.ips.filter(U=>!v.has(U.ip));if(E.length>0){o.info(`\u{1F504} Falling back to individual IP rules for ${E.length} IPs`);for(let U of E){let x=W.unifiedIPToCloudflare(U);l.push(x)}d=E.length}else o.info("All IPs were already confirmed in the List before the failure; no fallback rules needed.");E.length>50&&o.warn(`\u26A0\uFE0F Performance warning: Using ${E.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 v of e.ips){let f=W.unifiedIPToCloudflare(v);l.push(f)}d=e.ips.length}let m=await this.client.updateRuleset(c.id,{rules:l}),h={success:!0,rulesAdded:n.changes.rulesToAdd.length,rulesUpdated:n.changes.rulesToUpdate.length,rulesDeleted:n.changes.rulesToDelete.length,ipsAdded:d,ipsUpdated:u,ipsDeleted:p,version:parseInt(m.version,10),warnings:n.warnings?.length?n.warnings:void 0};return this.logSyncStats(h),h}async getChanges(e){let t=await this.client.getOrCreateFirewallRuleset(),i=t.rules.filter(l=>l&&l.id&&l.expression&&l.action&&!this.isListBasedIPRule(l)&&!this.isIPBlockingRule(l)),n=e.rules.map(l=>({rule:l,translated:W.unifiedToCloudflare(l).result})),s=this.optimizer.diffCloudflareRules(n,i),a=s.toDelete.map(l=>W.cloudflareToUnified(l).result),c={toAdd:[],toUpdate:[],toDelete:[]};if(e.ips){let l=await this.fetchRemoteIPRulesForDiff(t.rules);c=this.optimizer.diffIPRules(e.ips,l)}return{rulesToAdd:s.toAdd,rulesToUpdate:s.toUpdate,rulesToDelete:a,ipsToAdd:c.toAdd,ipsToUpdate:c.toUpdate,ipsToDelete:c.toDelete,version:parseInt(t.version,10),hasChanges:s.toAdd.length>0||s.toUpdate.length>0||a.length>0||c.toAdd.length>0||c.toUpdate.length>0||c.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(),n=await this.client.getListItems(i.id);for(let s of n)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],n=[...t.warnings];if(e&&e.rules){let s=this.getSupportedFeatures();if(s.maxRules&&e.rules.length>s.maxRules){let a=G.ruleLimitExceeded(e.rules.length,s.maxRules);i.push({path:"rules",message:a.message,code:a.code})}if(e.rules.forEach((a,c)=>{try{if(!a.conditions||a.conditions.length===0){let l=G.ruleNoConditions(a.name||`Rule ${c+1}`);i.push({path:`rules[${c}]`,message:l.message,code:l.code})}if(a.action.type==="rate_limit"&&a.action.rateLimit){let l=a.action.rateLimit;if(l.requests<1){let d=G.invalidRateLimit(a.name||`Rule ${c+1}`,"requests must be at least 1");i.push({path:`rules[${c}].action.rateLimit.requests`,message:d.message,code:d.code})}if(!l.window.match(/^\d+[smhd]$/)){let d=G.invalidWindowFormat(l.window);i.push({path:`rules[${c}].action.rateLimit.window`,message:d.message,code:d.code})}if(l.characteristics&&l.characteristics.length===0){let d=G.emptyCharacteristics(a.name||`Rule ${c+1}`);n.push({path:`rules[${c}].action.rateLimit.characteristics`,message:d.message,code:d.code})}if(l.mitigationTimeout!==void 0&&l.mitigationTimeout<60){let d=G.shortMitigationTimeout(l.mitigationTimeout);n.push({path:`rules[${c}].action.rateLimit.mitigationTimeout`,message:d.message,code:d.code})}}if(a.action.type==="redirect"&&a.action.redirect){let l=a.action.redirect;if(l.location)try{new URL(l.location)}catch{if(!l.location.startsWith("/")){let d=G.invalidRedirectUrl(l.location);i.push({path:`rules[${c}].action.redirect.location`,message:d.message,code:d.code})}}else{let d=G.redirectNoLocation(a.name||`Rule ${c+1}`);i.push({path:`rules[${c}].action.redirect.location`,message:d.message,code:d.code})}}}catch(l){i.push({path:`rules[${c}]`,message:`Validation error: ${l instanceof Error?l.message:String(l)}`,code:"CLOUDFLARE_VALIDATION_ERROR"})}}),e.ips&&(e.ips.forEach((a,c)=>{try{if(!r.isValidIPOrCIDR(a.ip)){let l=G.invalidIP(a.ip);i.push({path:`ips[${c}].ip`,message:l.message,code:l.code})}}catch(l){i.push({path:`ips[${c}]`,message:`IP validation error: ${l instanceof Error?l.message:String(l)}`,code:"CLOUDFLARE_IP_VALIDATION_ERROR"})}}),!this.useListsForIPs&&e.ips.length>50)){let a=G.largeIPList(e.ips.length);n.push({path:"ips",message:a.message,code:a.code})}}return{valid:i.length===0,errors:i,warnings:n}}getHealthScore(e){let t=super.getHealthScore(e),i=[...t.issues],n=this.getSupportedFeatures();return n.maxRules&&e.rules.length>n.maxRules*.8&&i.push({severity:"warning",category:"limits",message:`Approaching Cloudflare rule limit (${e.rules.length}/${n.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,...n]=e.split("/");if(n.length>0||!t)return!1;if(i===void 0)return(0,Ge.isIPv4)(t)||(0,Ge.isIPv6)(t);if(!/^\d+$/.test(i))return!1;let s=Number(i);return(0,Ge.isIPv4)(t)?s<=32:(0,Ge.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 r.IP_EQ_PATTERN.test(t)||r.IP_IN_SET_PATTERN.test(t)}static IP_EQ_PATTERN=/^ip\.src eq ([0-9a-fA-F:.]+)$/;static IP_IN_SET_PATTERN=/^ip\.src in \{([0-9a-fA-F:./]+)\}$/;cloudflareRuleToIPRule(e){let t=e.expression.trim(),n=(t.match(r.IP_EQ_PATTERN)||t.match(r.IP_IN_SET_PATTERN))?.[1]||"",a=e.description?.match(/\(([^)]+)\)/)?.[1];return{id:e.id,ip:n,hostname:a,notes:e.description,action:e.action==="allow"?"allow":"deny"}}handleListsAPIFallback(e,t){if(e instanceof Error){let 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:
|
|
45
45
|
\u2022 Set CLOUDFLARE_ACCOUNT_ID in your environment
|
|
46
46
|
\u2022 Ensure your API token has Account:Read permissions
|
|
47
47
|
\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:
|
|
48
48
|
\u2022 Ensure your API token has Account:Read permissions
|
|
49
49
|
\u2022 Verify the account ID is correct
|
|
50
|
-
\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 He=class{static create(e,t,i){let n=e||process.env.CLOUDFLARE_API_TOKEN,s=t||process.env.CLOUDFLARE_ZONE_ID,a=i||process.env.CLOUDFLARE_ACCOUNT_ID;if(!n)throw new Error("Cloudflare API token is required. Set CLOUDFLARE_API_TOKEN environment variable or pass as parameter.");if(!s)throw new Error("Cloudflare Zone ID is required. Set CLOUDFLARE_ZONE_ID environment variable or pass as parameter.");return new Qe(n,s,a)}static fromEnv(){return this.create()}static fromConfig(e){return this.create(e.apiToken,e.zoneId,e.accountId)}};
|
|
50
|
+
\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 He=class{static create(e,t,i){let n=e||process.env.CLOUDFLARE_API_TOKEN,s=t||process.env.CLOUDFLARE_ZONE_ID,a=i||process.env.CLOUDFLARE_ACCOUNT_ID;if(!n)throw new Error("Cloudflare API token is required. Set CLOUDFLARE_API_TOKEN environment variable or pass as parameter.");if(!s)throw new Error("Cloudflare Zone ID is required. Set CLOUDFLARE_ZONE_ID environment variable or pass as parameter.");return new Qe(n,s,a)}static fromEnv(){return this.create()}static fromConfig(e){return this.create(e.apiToken,e.zoneId,e.accountId)}};k();async function zi(r){let e;if(r.provider)e=r.provider,o.debug(`Using explicitly specified provider: ${e}`);else{let t=lt.detect(r.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(", ")}`)):r.interactive!==!1?e=await ln():(e="vercel",o.warn("No provider detected, defaulting to Vercel"))}try{if(e==="vercel")return await sn(r);if(e==="cloudflare")return{provider:await an(r)};throw new Error(`Unknown provider: ${e}`)}catch(t){throw o.error(`Failed to initialize ${e} provider:`,t),t}}async function sn(r){let e=r.token||process.env.VERCEL_TOKEN,t=r.config,i=t?.providers?.vercel?.projectId??t?.projectId,n=t?.providers?.vercel?.teamId??t?.teamId,s=r.projectId||i||process.env.VERCEL_PROJECT_ID,a=r.teamId||n||process.env.VERCEL_TEAM_ID;if(!e||!s||!a){if(r.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:l}=await Promise.resolve().then(()=>(Bi(),Vi)),d=await l({token:e,projectId:s,teamId:a});return{provider:Me.fromConfig({token:d.token,projectId:d.projectId,teamId:d.teamId}),vercelCredentials:d}}return{provider:Me.fromConfig({token:e,projectId:s,teamId:a}),vercelCredentials:{token:e,projectId:s,teamId:a}}}async function an(r){let e=r.apiToken||process.env.CLOUDFLARE_API_TOKEN,t=r.zoneId||process.env.CLOUDFLARE_ZONE_ID,i=r.accountId||process.env.CLOUDFLARE_ACCOUNT_ID;if(!e||!t){if(r.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 n=e||await at("Cloudflare API Token: "),s=t||await C("Cloudflare Zone ID:",{type:"text"}),a=i||await C("Cloudflare Account ID (optional):",{type:"text"});return He.fromConfig({apiToken:n,zoneId:s,accountId:a||void 0})}return He.fromConfig({apiToken:e,zoneId:t,accountId:i})}async function ln(){o.info(ji.default.yellow("Unable to auto-detect firewall provider.")),o.info(`Please select a provider:
|
|
51
51
|
`),o.info(" 1. Vercel Firewall"),o.info(` 2. Cloudflare WAF
|
|
52
|
-
`);let r=await
|
|
52
|
+
`);let r=await C("Select provider (1 or 2):",{type:"text"}),e=String(r).toLowerCase();return e==="1"||e==="vercel"?"vercel":e==="2"||e==="cloudflare"?"cloudflare":(o.warn(`Invalid choice: ${r}, defaulting to Vercel`),"vercel")}async function ie(r,e){try{r.debug&&(o.level=Wi.LogLevels.debug);let t;if(r.optionalConfig)try{t=await H(r.config,"optional")}catch{t={}}else r.skipValidation?t=await H(r.config,"raw"):t=await H(r.config,"required");let{provider:i,vercelCredentials:n}=await zi({provider:r.provider,config:t,interactive:!r.ci,token:r.token,projectId:r.projectId,teamId:r.teamId,apiToken:r.apiToken,zoneId:r.zoneId,accountId:r.accountId}),s,a,c="",l="",d="";i.name==="vercel"&&n?(c=n.token,l=n.projectId,d=n.teamId,s=new st(l,d,c),a=new rt(s)):(s={},a={}),await e({config:t,provider:i,client:s,service:a,token:c,projectId:l,teamId:d})}catch(t){ee(t,r.errorContext)}}var cn="backup",dn="Backup or restore firewall configurations",un={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}},pn=async r=>{try{r.debug&&(o.level=Mi.LogLevels.debug);let e=r.output||"./backups";if(r.list){if(!(0,me.existsSync)(e)){o.info(oe.default.yellow("No backup directory found."));return}let t=(0,me.readdirSync)(e).filter(i=>i.endsWith(".json")).map(i=>{let n=(0,ut.join)(e,i),s=(0,me.statSync)(n);return{name:i,size:s.size,created:s.mtime}}).sort((i,n)=>n.created.getTime()-i.created.getTime());if(t.length===0){o.info(oe.default.yellow("No backups found."));return}o.log(oe.default.bold(`
|
|
53
53
|
\u{1F4E6} Available Backups:
|
|
54
|
-
`)),t.forEach(i=>{o.log(`${oe.default.cyan(i.name)}`),o.log(` ${oe.default.dim("Created:")} ${i.created.toLocaleString()}`),o.log(` ${oe.default.dim("Size:")} ${(i.size/1024).toFixed(1)} KB`),o.log("")});return}if(r.restore){let t=r.restore.startsWith("/")?r.restore:(0,ut.join)(e,r.restore);(0,me.existsSync)(t)||(o.error(`Backup file not found: ${t}`),process.exit(1));let i=await H(t,"raw"),n=r.config||".doorman.json";if((0,me.existsSync)(n)&&!await
|
|
54
|
+
`)),t.forEach(i=>{o.log(`${oe.default.cyan(i.name)}`),o.log(` ${oe.default.dim("Created:")} ${i.created.toLocaleString()}`),o.log(` ${oe.default.dim("Size:")} ${(i.size/1024).toFixed(1)} KB`),o.log("")});return}if(r.restore){let t=r.restore.startsWith("/")?r.restore:(0,ut.join)(e,r.restore);(0,me.existsSync)(t)||(o.error(`Backup file not found: ${t}`),process.exit(1));let i=await H(t,"raw"),n=r.config||".doorman.json";if((0,me.existsSync)(n)&&!await C(`Config file ${n} already exists. Do you want to overwrite it?`,{type:"confirm"})){o.info(oe.default.yellow("Restore cancelled."));return}let{backup:s,...a}=i;await M(a,n),o.success(oe.default.green(`\u2705 Restored configuration from ${t} to ${n}`));return}await ie({config:r.config,provider:r.provider,projectId:r.projectId,teamId:r.teamId,token:r.token,apiToken:r.apiToken,zoneId:r.zoneId,accountId:r.accountId,debug:r.debug,ci:r.ci,errorContext:"creating backup"},async({client:t,provider:i,projectId:n,teamId:s})=>{o.start("Fetching current remote configuration...");let a=i.name==="vercel"?await t.fetchFirewallConfig():await i.fetchConfig(),c=i.name==="vercel"?{version:a.version,firewallEnabled:a.firewallEnabled,rules:a.rules.map(({valid:E,validationErrors:U,...x})=>x),ips:a.ips.map(({id:E,ip:U,hostname:x,notes:g,action:A})=>({...E!==void 0&&{id:E},ip:U,hostname:x,...g!==void 0&&{notes:g},action:A})),updatedAt:a.updatedAt}:a;Ce.getInstance().validateConfig(c),(0,me.existsSync)(e)||(0,me.mkdirSync)(e,{recursive:!0});let d=new Date,u=d.toISOString().split("T")[0]??"unknown-date",p=(d.toISOString().split("T")[1]??"").split(".")[0]?.replace(/:/g,"-")??"unknown-time",h=`firewall-backup-${`${u}_${p}`}.json`,v=(0,ut.join)(e,h),f={...c,backup:{createdAt:new Date().toISOString(),source:"remote",provider:i.name,...i.name==="vercel"?{projectId:n,teamId:s}:{},originalVersion:a.version}};await M(f,v,{validate:!1}),o.success(oe.default.green(`\u2705 Backup created: ${v}`)),o.log(""),o.log(oe.default.bold("Backup Details:")),o.log(`${oe.default.dim("Version:")} ${a.version}`),o.log(`${oe.default.dim("Rules:")} ${a.rules.length} custom, ${a.ips?.length??0} IP blocking`),o.log(`${oe.default.dim("Created:")} ${new Date().toLocaleString()}`),o.log(""),o.log(oe.default.dim("To restore this backup later, run:")),o.log(oe.default.cyan(`doorman backup --restore ${h}`))})}catch(e){ee(e,"managing backup")}};var Gt={};K(Gt,{builder:()=>hn,command:()=>fn,desc:()=>mn,handler:()=>yn});var F=S(require("chalk"));k();var Z=S(require("chalk")),qt=S(require("cli-table3"));k();var Vt=(r,e,t,i)=>{if(!e.length)throw new Error("minWidths array cannot be empty");if(i.some(l=>l>=e.length))throw new Error("flexColumns contains invalid column index");if(e.length!==t.length)throw new Error("minWidths and maxWidths arrays must have the same length");e.forEach((l,d)=>{let u=t[d];if(u!=null&&l>u)throw new Error(`Column ${d} has minimum width (${l}) greater than maximum width (${u})`)});let n=r||400,s=[...e],a=e.reduce((l,d)=>l+d,0),c=n-a-28;if(c>0&&i.length>0){let l=i.filter(d=>{let u=t[d],p=s[d];return u!==void 0&&p!==void 0&&(u===null||p<u)});for(;c>0&&l.length>0;){let d=Math.floor(c/l.length);if(d===0)break;let u=0;l=l.filter(p=>{let m=t[p],h=s[p];if(m===null)return s[p]!==void 0&&(s[p]+=d),u+=d,!0;{let v=(m??0)-(h??0);if(v<=0)return!1;let f=Math.min(d,v);return s[p]!==void 0&&(s[p]+=f),u+=f,f===d}}),c-=u}if(c>0){let d=i.findLast(u=>t[u]===null);d!==void 0&&d!==void 0&&s[d]!==void 0&&(s[d]+=c)}}return s};var pe=S(require("chalk")),qi=r=>{if(r==="permanent")return"permanent";let e=r.slice(0,-1),t=r.slice(-1);return`${e}${{s:"sec",m:"min",h:"hr",d:"day"}[t]||t}`},gn=(r,e)=>e==="60s"?`${r}/min`:e==="3600s"?`${r}/hr`:e==="86400s"?`${r}/day`:`${r}/${qi(e)}`;function Gi(r){if(!r.mitigate)return"unknown";let{mitigate:e}=r,t=[];switch(e.action){case"log":t.push(pe.default.blue("log"));break;case"deny":t.push(pe.default.red("deny"));break;case"challenge":t.push(pe.default.yellow("challenge"));break;case"bypass":t.push(pe.default.green("bypass"));break;case"rate_limit":t.push(pe.default.yellow("rate-limit"));break;case"redirect":t.push(pe.default.magenta("redirect"));break;default:t.push(e.action)}return e.rateLimit&&(t[0]=pe.default.yellow("rate-limit"),t.push(pe.default.yellow(gn(e.rateLimit.requests,e.rateLimit.window)))),e.redirect&&(t[0]=pe.default.magenta("redirect"),t.push(pe.default.magenta(`\u2192 ${e.redirect.location}`)),e.redirect.permanent!==void 0&&t.push(pe.default.gray(`(${e.redirect.permanent?"301":"302"})`))),e.actionDuration&&t.push(pe.default.gray(`for ${qi(e.actionDuration)}`)),t.join(" ")}var Xe=S(require("chalk"));function Bt(r){switch(r){case"unchanged":return Xe.default.bold.gray(" ");case"modified":return Xe.default.bold.yellow("\u25B4");case"new":return Xe.default.bold.green("+");case"deleted":return Xe.default.bold.red("-")}}var Ye=S(require("chalk"));function Hi(r=[]){return r.map((e,t)=>{let i=e.conditions.map(n=>Ye.default.cyan(`${n.type}:${n.neg?Ye.default.red(`!${n.op}:`):`${n.op}:`}${Ye.default.white(n.value)}`)).join(`
|
|
55
55
|
`);return t>0?`${Ye.default.yellow("OR")}
|
|
56
56
|
${i}`:i}).join(`
|
|
57
|
-
`)}var jt=
|
|
57
|
+
`)}var jt=S(require("chalk"));function Zi(r){return{id:r.id||"-",ip:r.ip,hostname:r.hostname,notes:r.notes||"-",status:r.changeStatus?jt.default.yellow(r.changeStatus):jt.default.red("deny")}}var et=S(require("chalk"));function zt(r){switch(r){default:case"unchanged":return et.default.white;case"modified":return et.default.yellow;case"new":return et.default.green;case"deleted":return et.default.red}}var le={unchanged:"unchanged",modified:"modified",new:"new",deleted:"deleted"},Wt={minWidths:[10,28,20,5,12,35],maxWidths:[15,32,36,8,24,null],flexColumns:[0,1,2,4,5]},Mt={minWidths:[10,28,24,5,12],maxWidths:[20,32,26,null,16],flexColumns:[0,1,3]},Ki=(r,e)=>r==="ip"?Vt(e,Mt.minWidths,Mt.maxWidths,Mt.flexColumns):Vt(e,Wt.minWidths,Wt.maxWidths,Wt.flexColumns);function Ee(r,{showStatus:e}){let t=[Z.default.bold.gray("ID"),Z.default.bold.gray("Name"),Z.default.bold.gray("Conditions"),Z.default.bold.gray(" "),Z.default.bold.gray("Action"),Z.default.bold.gray("Description")],i=["left","left","left","center","left","left"],n=process.stdout.columns||400,s=Ki("rules",n);e&&(t.unshift(Z.default.bold.gray("Status")),i.unshift("center"),s.unshift(10));let a=new qt.default({head:t,colAligns:i,wrapOnWordBoundary:!0,wordWrap:!0,colWidths:s});r.forEach(c=>{let l="changeStatus"in c&&e,d=l?zt(c.changeStatus):Z.default.white,u=[d(c.id?c.id:"-"),d(c.name),d(Hi(c.conditionGroup)),c.active?Z.default.bold.green("\u2713"):Z.default.bold.red("\u2717"),d(Gi(c.action)),d(c.description||"")];l&&u.unshift(d(Bt(c.changeStatus))),a.push(u)}),o.log(a.toString())}function $e(r,{showStatus:e}){let t=[Z.default.bold.gray("ID"),Z.default.bold.gray("IP"),Z.default.bold.gray("Hostname"),Z.default.bold.gray("Notes"),Z.default.bold.gray("Action")],i=["left","left","left","left","center"],n=process.stdout.columns||400,s=Ki("ip",n);e&&(t.unshift(Z.default.bold.gray("Status")),i.unshift("center"),s.unshift(10));let a=new qt.default({head:t,colAligns:i,wrapOnWordBoundary:!0,wordWrap:!0,colWidths:s});r.forEach(c=>{let l=c.changeStatus!==void 0&&e,d=l?zt(c.changeStatus):Z.default.white,u=Zi(c),p=[d(u.id),d(u.ip),d(u.hostname),d(u.notes),u.status];l&&p.unshift(d(Bt(c.changeStatus))),a.push(p)}),o.log(a.toString())}var fn="diff",mn="Show detailed differences between local and remote firewall configuration",hn={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}},yn=async r=>{await ie({config:r.config,provider:r.provider,projectId:r.projectId,teamId:r.teamId,token:r.token,apiToken:r.apiToken,zoneId:r.zoneId,accountId:r.accountId,debug:r.debug,ci:r.ci,errorContext:"calculating diff"},async({config:e,service:t,provider:i})=>{if(i.name!=="vercel"){await wn(i,e,r);return}o.start("Calculating differences...");let{toAdd:n,toUpdate:s,toDelete:a,ipsToAdd:c,ipsToUpdate:l,ipsToDelete:d,version:u}=await t.getChanges(e),p=n.length>0||s.length>0||a.length>0,m=c.length>0||l.length>0||d.length>0,h=e.version!==u;if(!p&&!m&&!h){o.success(F.default.green("No differences found. Local and remote configurations are in sync."));return}if(r.format==="json"){let f={version:{local:e.version,remote:u,changed:h},customRules:{toAdd:n.map(E=>({...E,status:"add"})),toUpdate:s.map(E=>({...E,status:"update"})),toDelete:a.map(E=>({...E,status:"delete"}))},ipRules:{toAdd:c.map(E=>({...E,status:"add"})),toUpdate:l.map(E=>({...E,status:"update"})),toDelete:d.map(E=>({...E,status:"delete"}))},summary:{hasChanges:p||m||h,customRuleChanges:n.length+s.length+a.length,ipRuleChanges:c.length+l.length+d.length}};o.log(JSON.stringify(f,null,2));return}o.log(F.default.bold(`
|
|
58
58
|
\u{1F50D} Configuration Differences
|
|
59
|
-
`)),h&&(o.log(
|
|
60
|
-
`)),Ee([...n.map(f=>({...f,changeStatus:le.new,id:f.id})),...s.map(f=>({...f,changeStatus:le.modified,id:f.id})),...a.map(f=>({...f,changeStatus:le.deleted,id:f.id}))],{showStatus:!0}),o.log("")),m&&(o.log(
|
|
61
|
-
`)),$e([...c.map(f=>({...f,changeStatus:le.new,id:f.id||void 0})),...l.map(f=>({...f,changeStatus:le.modified,id:f.id||void 0})),...d.map(f=>({...f,changeStatus:le.deleted,id:f.id||void 0}))],{showStatus:!0}),o.log(""));let v=n.length+s.length+a.length+c.length+l.length+d.length;o.log(
|
|
59
|
+
`)),h&&(o.log(F.default.bold("Version Changes:")),o.log(` Local: ${F.default.red(e.version||"unknown")}`),o.log(` Remote: ${F.default.green(u)}`),o.log("")),p&&(o.log(F.default.bold(`Custom Rule Changes:
|
|
60
|
+
`)),Ee([...n.map(f=>({...f,changeStatus:le.new,id:f.id})),...s.map(f=>({...f,changeStatus:le.modified,id:f.id})),...a.map(f=>({...f,changeStatus:le.deleted,id:f.id}))],{showStatus:!0}),o.log("")),m&&(o.log(F.default.bold(`IP Blocking Rule Changes:
|
|
61
|
+
`)),$e([...c.map(f=>({...f,changeStatus:le.new,id:f.id||void 0})),...l.map(f=>({...f,changeStatus:le.modified,id:f.id||void 0})),...d.map(f=>({...f,changeStatus:le.deleted,id:f.id||void 0}))],{showStatus:!0}),o.log(""));let v=n.length+s.length+a.length+c.length+l.length+d.length;o.log(F.default.bold(`Summary: ${v} total changes detected`)),o.log(F.default.dim("Run `sync` to apply these changes to the remote configuration."))})};async function wn(r,e,t){o.start("Calculating differences...");let i=await r.getChanges(e);if(!i.hasChanges){o.success(F.default.green("No differences found. Local and remote configurations are in sync."));return}let n=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:n,toUpdate:s,toDelete:a},summary:{hasChanges:i.hasChanges,ruleChanges:i.rulesToAdd.length+i.rulesToUpdate.length+i.rulesToDelete.length,ipChanges:n.length+s.length+a.length}},null,2));return}o.log(F.default.bold(`
|
|
62
62
|
\u{1F50D} ${r.name} Configuration Differences
|
|
63
|
-
`)),o.log(
|
|
63
|
+
`)),o.log(F.default.bold("Rule Changes:")),o.log(` ${F.default.green("+")} ${i.rulesToAdd.length} to add`),i.rulesToAdd.forEach(l=>o.log(` ${F.default.green("+")} ${l.name}`)),o.log(` ${F.default.cyan("~")} ${i.rulesToUpdate.length} to update`),i.rulesToUpdate.forEach(l=>o.log(` ${F.default.cyan("~")} ${l.name}`)),o.log(` ${F.default.red("-")} ${i.rulesToDelete.length} to delete`),i.rulesToDelete.forEach(l=>o.log(` ${F.default.red("-")} ${l.name}`)),(n.length||s.length||a.length)&&(o.log(""),o.log(F.default.bold("IP Rule Changes:")),o.log(` ${F.default.green("+")} ${n.length} to add`),o.log(` ${F.default.cyan("~")} ${s.length} to update`),o.log(` ${F.default.red("-")} ${a.length} to delete`));let c=i.rulesToAdd.length+i.rulesToUpdate.length+i.rulesToDelete.length+n.length+s.length+a.length;o.log(""),o.log(F.default.bold(`Summary: ${c} total changes detected`)),o.log(F.default.dim("Run `sync` to apply these changes to the remote configuration."))}var Ht={};K(Ht,{builder:()=>In,command:()=>Rn,desc:()=>Cn,handler:()=>bn});var fe=S(require("chalk")),Ji=require("zod");k();de();var Rn="download [configVersion]",Cn="Download remote Vercel Firewall rules and update local config, optionally for a specific configuration version",In={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}},bn=async r=>{await ie({config:r.config,provider:r.provider,projectId:r.projectId,teamId:r.teamId,token:r.token,apiToken:r.apiToken,zoneId:r.zoneId,accountId:r.accountId,debug:r.debug,ci:r.ci,optionalConfig:!0,skipValidation:!0,errorContext:"downloading firewall rules"},async({config:e,client:t,provider:i,projectId:n,teamId:s})=>{if(r.configVersion!==void 0)try{ot.parse(r.configVersion)}catch(p){throw p instanceof Ji.z.ZodError&&(o.error("Invalid configuration version number. Version must be a positive integer."),process.exit(1)),p}if(i.name!=="vercel"){await vn(i,e,r);return}o.start(`Fetching remote firewall configuration${r.configVersion?` version ${r.configVersion}`:""} ...`);let a=await t.fetchFirewallConfig(r.configVersion),c=a.rules,l=a.ips;if(c.length>0?(o.log(fe.default.bold(`
|
|
64
64
|
Remote Custom Rules to Download:
|
|
65
65
|
`)),Ee(c,{showStatus:!1})):o.info("No custom rules to download..."),l.length>0?(o.log(fe.default.bold(`
|
|
66
66
|
Remote IP Blocking Rules to Download:
|
|
67
|
-
`)),$e(l,{showStatus:!1})):o.info("No IP blocking rules to download..."),r.dryRun){o.info(fe.default.cyan("Dry run completed. No changes made."));return}if(!await
|
|
67
|
+
`)),$e(l,{showStatus:!1})):o.info("No IP blocking rules to download..."),r.dryRun){o.info(fe.default.cyan("Dry run completed. No changes made."));return}if(!await C(`Do you want to download${r.configVersion?` version ${r.configVersion}`:" the latest version"} of these rules? This will overwrite your local configuration.`,{type:"confirm"})){o.info(fe.default.yellow("Download cancelled."));return}let u={...e,projectId:n,teamId:s,version:a.version,updatedAt:a.updatedAt,rules:c.map(({valid:p,validationErrors:m,...h})=>h),ips:l};o.start(`Saving configuration with version: ${u.version}`),await M(u,r.config),o.success(fe.default.green("Successfully downloaded and updated configuration"))})};async function vn(r,e,t){o.start(`Fetching remote firewall configuration${t.configVersion?` version ${t.configVersion}`:""} ...`);let i=await r.fetchConfig(t.configVersion),n=i.rules,s=i.ips??[];if(n.length>0?(o.log(fe.default.bold(`
|
|
68
68
|
Remote Custom Rules to Download (${n.length}):
|
|
69
69
|
`)),n.forEach(l=>o.log(` - ${l.name}${l.enabled?"":fe.default.dim(" (disabled)")}`))):o.info("No custom rules to download..."),s.length>0?(o.log(fe.default.bold(`
|
|
70
70
|
Remote IP Blocking Rules to Download (${s.length}):
|
|
71
|
-
`)),s.forEach(l=>o.log(` - ${l.ip} (${l.action})`))):o.info("No IP blocking rules to download..."),t.dryRun){o.info(fe.default.cyan("Dry run completed. No changes made."));return}if(!await
|
|
71
|
+
`)),s.forEach(l=>o.log(` - ${l.ip} (${l.action})`))):o.info("No IP blocking rules to download..."),t.dryRun){o.info(fe.default.cyan("Dry run completed. No changes made."));return}if(!await C(`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(fe.default.yellow("Download cancelled."));return}let c={...e,...i};o.start("Saving configuration..."),await M(c,t.config),o.success(fe.default.green("Successfully downloaded and updated configuration"))}var Zt={};K(Zt,{builder:()=>An,command:()=>En,desc:()=>$n,handler:()=>kn});var Ue=S(require("chalk")),Qi=require("fs");k();var En="export",$n="Export firewall configuration in various formats",An={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}},Tn=r=>{let{rules:e,ips:t=[],version:i,updatedAt:n}=r,s=`# Vercel Firewall Configuration Report
|
|
72
72
|
|
|
73
73
|
`;return s+=`**Version:** ${i}
|
|
74
74
|
`,s+=`**Last Updated:** ${n?new Date(n).toLocaleString():"Unknown"}
|
|
@@ -95,7 +95,7 @@ Remote IP Blocking Rules to Download (${s.length}):
|
|
|
95
95
|
`,s+=`|------------|----------|--------|
|
|
96
96
|
`,t.forEach(a=>{s+=`| \`${a.ip}\` | ${a.hostname||"N/A"} | ${a.action} |
|
|
97
97
|
`})):s+=`No IP blocking rules configured.
|
|
98
|
-
`,s},
|
|
98
|
+
`,s},Pn=r=>{let{rules:e,ips:t=[]}=r,i=`# Vercel Firewall Configuration
|
|
99
99
|
`;return i+=`# Generated on ${new Date().toISOString()}
|
|
100
100
|
|
|
101
101
|
`,i+=`# Note: This is a conceptual Terraform configuration
|
|
@@ -118,7 +118,7 @@ Remote IP Blocking Rules to Download (${s.length}):
|
|
|
118
118
|
`,i+=` action = "${n.action}"
|
|
119
119
|
`,i+=`}
|
|
120
120
|
|
|
121
|
-
`}),i},
|
|
121
|
+
`}),i},kn=async r=>{try{let e;if(r.source==="remote"?await ie({config:r.config,provider:r.provider,projectId:r.projectId,teamId:r.teamId,token:r.token,apiToken:r.apiToken,zoneId:r.zoneId,accountId:r.accountId,debug:r.debug,ci:r.ci,errorContext:"exporting configuration"},async({client:s,provider:a})=>{o.start("Fetching remote configuration..."),e=a.name==="vercel"?await s.fetchFirewallConfig():await a.fetchConfig()}):e=await H(r.config),o.start(`Exporting configuration in ${r.format} format...`),r.format!=="json"&&Pe(e))throw new Error(`The '${r.format}' export format is currently only supported for Vercel configurations. Use --format json instead.`);let t,i;switch(r.format){case"json":t=JSON.stringify(e,null,2),i="json";break;case"yaml":t=`# Vercel Firewall Configuration
|
|
122
122
|
`,t+=`version: ${e.version}
|
|
123
123
|
`,t+=`updatedAt: "${e.updatedAt}"
|
|
124
124
|
`,t+=`rules:
|
|
@@ -126,32 +126,32 @@ Remote IP Blocking Rules to Download (${s.length}):
|
|
|
126
126
|
`,t+=` id: "${s.id}"
|
|
127
127
|
`,t+=` active: ${s.active}
|
|
128
128
|
`,t+=` action: "${s.action.mitigate.action}"
|
|
129
|
-
`}),i="yaml";break;case"terraform":t=
|
|
130
|
-
`))},
|
|
131
|
-
\u{1F4DA} Helpful Resources:`)),o.log(""),o.log(b.default.cyan("\u{1F517} Find your Project ID:")),o.log(b.default.dim(" https://vercel.com/dashboard \u2192 Select your project \u2192 Settings \u2192 General")),o.log(""),o.log(b.default.cyan("\u{1F517} Find your Team ID:")),o.log(b.default.dim(" https://vercel.com/dashboard \u2192 Team Settings \u2192 General")),o.log(b.default.dim(" (Leave empty if using personal account)")),o.log(""),o.log(b.default.cyan("\u{1F517} Create API Token:")),o.log(b.default.dim(" https://vercel.com/account/tokens \u2192 Create Token")),o.log(b.default.dim(" Scopes needed: Read & Write for your project")),o.log(""),o.log(b.default.cyan("\u{1F517} Documentation:")),o.log(b.default.dim(" https://doorman.griffen.codes/getting-started")),o.log("")},
|
|
132
|
-
`)),e||(e=await
|
|
133
|
-
`)),o.log(b.default.cyan("\u{1F4DD} empty")+b.default.dim(" - Minimal config, add your own rules")),o.log(b.default.cyan("\u{1F6E1}\uFE0F basic")+b.default.dim(" - Includes basic bot protection")),o.log(b.default.cyan("\u{1F512} security-focused")+b.default.dim(" - Comprehensive security rules")),o.log(""));let n=r.template;r.interactive&&!r.template&&(n=await
|
|
129
|
+
`}),i="yaml";break;case"terraform":t=Pn(e),i="tf";break;case"markdown":t=Tn(e),i="md";break;default:throw new Error(`Unsupported format: ${r.format}`)}let n=r.output||`firewall-export.${i}`;r.output==="-"||!r.output?o.log(t):((0,Qi.writeFileSync)(n,t,"utf8"),o.success(Ue.default.green(`\u2705 Exported to ${n}`)),o.log(""),o.log(Ue.default.bold("Export Summary:")),o.log(`${Ue.default.dim("Format:")} ${r.format}`),o.log(`${Ue.default.dim("Source:")} ${r.source}`),o.log(`${Ue.default.dim("Rules:")} ${e.rules.length} custom, ${(e.ips||[]).length} IP blocking`),o.log(`${Ue.default.dim("Size:")} ${(t.length/1024).toFixed(1)} KB`))}catch(e){ee(e,"exporting configuration")}};var Kt={};K(Kt,{BASIC_TEMPLATE_RULES:()=>Yi,SECURITY_FOCUSED_TEMPLATE_RULES:()=>eo,builder:()=>Dn,command:()=>Sn,desc:()=>_n,handler:()=>On});var b=S(require("chalk")),Xi=require("fs");k();de();var Yi=[{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}],eo=[{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}],Sn="init [template]",_n="Initialize a new Doorman configuration",Dn={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"}},Ln=()=>{o.log(""),o.log(b.default.bold.cyan("\u{1F6AA} Welcome to Doorman!")),o.log(b.default.dim(`Let's set up your firewall configuration.
|
|
130
|
+
`))},Un=()=>{o.log(b.default.bold(`
|
|
131
|
+
\u{1F4DA} Helpful Resources:`)),o.log(""),o.log(b.default.cyan("\u{1F517} Find your Project ID:")),o.log(b.default.dim(" https://vercel.com/dashboard \u2192 Select your project \u2192 Settings \u2192 General")),o.log(""),o.log(b.default.cyan("\u{1F517} Find your Team ID:")),o.log(b.default.dim(" https://vercel.com/dashboard \u2192 Team Settings \u2192 General")),o.log(b.default.dim(" (Leave empty if using personal account)")),o.log(""),o.log(b.default.cyan("\u{1F517} Create API Token:")),o.log(b.default.dim(" https://vercel.com/account/tokens \u2192 Create Token")),o.log(b.default.dim(" Scopes needed: Read & Write for your project")),o.log(""),o.log(b.default.cyan("\u{1F517} Documentation:")),o.log(b.default.dim(" https://doorman.griffen.codes/getting-started")),o.log("")},xn=async r=>{let e=r.projectId,t=r.teamId;return r.interactive&&(o.log(b.default.bold("\u{1F4CB} Project Configuration")),o.log(b.default.dim(`We need your Vercel project details to configure the firewall.
|
|
132
|
+
`)),e||(e=await C("Enter your Vercel Project ID:",{type:"text"})),t||await C("Are you using a Vercel team account?",{type:"confirm"})&&(t=await C("Enter your Vercel Team ID:",{type:"text"})),process.env.VERCEL_TOKEN?o.log(b.default.green("\u2705 VERCEL_TOKEN environment variable found")):(o.log(""),o.log(b.default.yellow("\u26A0\uFE0F VERCEL_TOKEN environment variable not found")),o.log(b.default.dim("You'll need to set this before running sync commands.")),await C("Would you like to see how to create an API token?",{type:"confirm"})&&(o.log(""),o.log(b.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(b.default.cyan(' export VERCEL_TOKEN="your-token-here"')),o.log(b.default.dim(" # Add this to your ~/.bashrc, ~/.zshrc, or .env file")),o.log("")))),{projectId:e,teamId:t}},On=async r=>{try{let e=r.config||".doorman.json";if(r.interactive&&Ln(),(0,Xi.existsSync)(e)&&!r.force&&!await C(`Config file ${e} already exists. Do you want to overwrite it?`,{type:"confirm"})){o.info(b.default.yellow("Initialization cancelled."));return}let{projectId:t,teamId:i}=await xn(r);r.interactive&&(o.log(""),o.log(b.default.bold("\u{1F3A8} Template Selection")),o.log(b.default.dim(`Choose a starting template for your firewall configuration:
|
|
133
|
+
`)),o.log(b.default.cyan("\u{1F4DD} empty")+b.default.dim(" - Minimal config, add your own rules")),o.log(b.default.cyan("\u{1F6E1}\uFE0F basic")+b.default.dim(" - Includes basic bot protection")),o.log(b.default.cyan("\u{1F512} security-focused")+b.default.dim(" - Comprehensive security rules")),o.log(""));let n=r.template;r.interactive&&!r.template&&(n=await C("Select a template:",{type:"select",options:["empty","basic","security-focused"],initial:"empty"})),o.start(`Creating ${n} configuration...`);let s=Ne();switch(t&&(s.projectId=t),i&&(s.teamId=i),n){case"basic":s={...s,rules:Yi};break;case"security-focused":s={...s,rules:eo};break;default:break}await M(s,e),o.success(b.default.green(`\u2705 Created ${e}`)),o.log(""),o.log(b.default.bold("\u{1F4CB} Configuration Summary:")),o.log(`${b.default.dim("File:")} ${e}`),o.log(`${b.default.dim("Template:")} ${n}`),o.log(`${b.default.dim("Project ID:")} ${t||b.default.yellow("Not set - add manually")}`),o.log(`${b.default.dim("Team ID:")} ${i||b.default.dim("None (personal account)")}`),o.log(`${b.default.dim("Rules:")} ${s.rules.length} (all disabled for safety)`),o.log(""),o.log(b.default.bold("\u{1F680} Next Steps:")),t||o.log(`1. ${b.default.yellow("Add your projectId")} to ${e}`),process.env.VERCEL_TOKEN||o.log(`${t?"1":"2"}. ${b.default.yellow("Set VERCEL_TOKEN")} environment variable`);let a=t?process.env.VERCEL_TOKEN?1:2:3;o.log(`${a}. ${b.default.dim("Review and enable rules in")} ${e}`),o.log(`${a+1}. ${b.default.dim("Run")} ${b.default.cyan("doorman validate")} ${b.default.dim("to check your config")}`),o.log(`${a+2}. ${b.default.dim("Run")} ${b.default.cyan("doorman status")} ${b.default.dim("to see sync status")}`),o.log(`${a+3}. ${b.default.dim("Run")} ${b.default.cyan("doorman sync")} ${b.default.dim("to deploy your rules")}`),n!=="empty"&&(o.log(""),o.log(b.default.yellow("\u26A0\uFE0F All template rules are disabled by default for safety.")),o.log(b.default.dim(" Review each rule and set active: true when ready."))),r.interactive&&(!t||!process.env.VERCEL_TOKEN)&&Un()}catch(e){ee(e,"initializing configuration")}};var Jt={};K(Jt,{builder:()=>Vn,command:()=>Nn,desc:()=>Fn,handler:()=>Bn});var q=S(require("chalk")),to=require("zod");k();var Nn="list [configVersion]",Fn="List Vercel Firewall rules, optionally for a specific configuration version",Vn={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}},Bn=async r=>{await ie({provider:r.provider,projectId:r.projectId,teamId:r.teamId,token:r.token,apiToken:r.apiToken,zoneId:r.zoneId,accountId:r.accountId,debug:r.debug,ci:r.ci,optionalConfig:!0,skipValidation:!0,errorContext:"listing firewall rules"},async({client:e,provider:t,projectId:i,teamId:n})=>{if(r.configVersion!==void 0)try{ot.parse(r.configVersion)}catch(u){throw u instanceof to.z.ZodError&&(o.error("Invalid configuration version number. Version must be a positive integer."),process.exit(1)),u}if(t.name!=="vercel"){await jn(t,r);return}o.start(`Fetching firewall configuration${r.configVersion?` version ${r.configVersion}`:""} ...`),o.verbose(`projectId: ${i} teamId: ${n}`);let s=await e.fetchFirewallConfig(r.configVersion),a=s.rules,c=s.ips,l=new Date(s.updatedAt),d=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"medium"}).format(l);if(o.info(`Found ${q.default.cyan(a.length)} custom rules and ${q.default.cyan(c.length)} IP blocking rules
|
|
134
134
|
`+q.default.dim(`Version: ${q.default.yellow(s.version)} \u2022 Last Updated: ${q.default.yellow(d)}`)),r.format==="json")o.info(JSON.stringify({version:s.version,updatedAt:s.updatedAt,lastUpdated:d,rules:a,ips:c},null,2));else{if(a.length===0&&c.length===0){o.info(q.default.yellow("No rules found"));return}a.length>0?(o.log(q.default.bold.underline(`
|
|
135
135
|
Custom Rules:`),`
|
|
136
136
|
`),Ee(a,{showStatus:!1})):o.info(q.default.cyan("No custom rules found")),c.length>0?(o.log(q.default.bold.underline(`
|
|
137
137
|
IP Blocking Rules:`),`
|
|
138
|
-
`),$e(c,{showStatus:!1})):o.info(q.default.cyan("No IP blocking rules found"))}})};async function
|
|
138
|
+
`),$e(c,{showStatus:!1})):o.info(q.default.cyan("No IP blocking rules found"))}})};async function jn(r,e){o.start(`Fetching firewall configuration${e.configVersion?` version ${e.configVersion}`:""} ...`);let t=await r.fetchConfig(e.configVersion),i=t.rules,n=t.ips??[],s=t.metadata?.version??t.version,a=t.metadata?.updatedAt;if(o.info(`Found ${q.default.cyan(i.length)} custom rules and ${q.default.cyan(n.length)} IP blocking rules
|
|
139
139
|
`+q.default.dim(`Version: ${q.default.yellow(s??"unknown")}${a?` \u2022 Last Updated: ${q.default.yellow(a)}`:""}`)),e.format==="json"){o.info(JSON.stringify({version:s,updatedAt:a,rules:i,ips:n},null,2));return}if(i.length===0&&n.length===0){o.info(q.default.yellow("No rules found"));return}i.length>0?(o.log(q.default.bold.underline(`
|
|
140
140
|
Custom Rules:`),`
|
|
141
141
|
`),i.forEach(c=>o.log(` - ${c.name}${c.enabled?"":q.default.dim(" (disabled)")}`))):o.info(q.default.cyan("No custom rules found")),n.length>0?(o.log(q.default.bold.underline(`
|
|
142
142
|
IP Blocking Rules:`),`
|
|
143
|
-
`),n.forEach(c=>o.log(` - ${c.ip} (${c.action})`))):o.info(q.default.cyan("No IP blocking rules found"))}var Xt={};K(Xt,{aliases:()=>
|
|
144
|
-
Current IP rules:`)),
|
|
145
|
-
${r.dryRun?"Would remove":"Removing"} ${n.length} IP rule(s):`)),
|
|
146
|
-
Dry run \u2014 no changes made.`));return}if(!await
|
|
147
|
-
\u26A0\uFE0F Found ${n.length} rules named "${r.name}". All will be removed.`)),Qt(n)),n.length===0){o.error(V.default.red(`No rule found with exact name "${r.name}"`));let c=
|
|
143
|
+
`),n.forEach(c=>o.log(` - ${c.ip} (${c.action})`))):o.info(q.default.cyan("No IP blocking rules found"))}var Xt={};K(Xt,{aliases:()=>Wn,builder:()=>qn,command:()=>zn,desc:()=>Mn,findFuzzyMatches:()=>so,handler:()=>Gn,levenshtein:()=>ro});var V=S(require("chalk")),no=require("consola");k();de();var zn="remove [type]",Wn=["rm","delete"],Mn="Remove a firewall rule or IP entry from your configuration",qn={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 ro(r,e){let t=r.length,i=e.length;if(t===0)return i;if(i===0)return t;let n=Array.from({length:t+1},(a,c)=>c),s=new Array(t+1).fill(0);for(let a=1;a<=i;a++){s[0]=a;for(let c=1;c<=t;c++)e.charAt(a-1)===r.charAt(c-1)?s[c]=n[c-1]:s[c]=Math.min(n[c-1]+1,s[c-1]+1,n[c]+1);for(let c=0;c<=t;c++)n[c]=s[c]}return n[t]}function so(r,e,t=3){let i=r.toLowerCase(),n=e.filter(c=>c.name.toLowerCase().includes(i)||i.includes(c.name.toLowerCase()));if(n.length>0)return n.slice(0,t);let s=e.map(c=>({rule:c,distance:ro(i,c.name.toLowerCase())})).sort((c,l)=>c.distance-l.distance),a=Math.max(r.length*.6,3);return s.filter(c=>c.distance<=a).slice(0,t).map(c=>c.rule)}function Qt(r){for(let e of r){let t=e.id?` (${e.id})`:"",i=e.active?"":V.default.dim(" [disabled]"),n=e.action.mitigate.action;o.log(V.default.dim(` - ${e.name}${t} \u2014 ${n}${i}`))}}function io(r){for(let e of r){let t=e.notes?` \u2014 ${e.notes}`:"";o.log(V.default.dim(` - ${e.ip}${t}`))}}async function oo(r,e,t,i="rule"){if(e)return!0;if(t)return await C(V.default.red(`\u26A0\uFE0F Are you sure you want to remove ALL ${i}s? Type "YES" to confirm:`),{type:"text"})==="YES";let n=r===1?`Confirm removal of 1 ${i}?`:`Confirm removal of ${r} ${i}s?`;return await C(n,{type:"confirm",initial:!1})}var Gn=async r=>{try{r.debug&&(o.level=no.LogLevels.debug),o.debug("Remove command arguments:",r);let e=r.type||"rule";o.start("Loading configuration...");let t=await H(r.config);if(e==="ip"){let i=t.ips||[];if(i.length===0){o.info("No IP rules in configuration.");return}let n=[];if(r.interactive){let c=i.map(d=>{let u=d.notes?` \u2014 ${d.notes}`:"";return`${d.ip}${u}`}),l=await C("Select IP rules to remove:",{type:"multiselect",options:c});n=i.filter(d=>{let u=`${d.ip}${d.notes?` \u2014 ${d.notes}`:""}`;return l.includes(u)})}else r.ip?(n=i.filter(c=>c.ip===r.ip),n.length===0&&(o.error(V.default.red(`No IP rule found matching "${r.ip}"`)),i.length>0&&(o.log(V.default.dim(`
|
|
144
|
+
Current IP rules:`)),io(i)),process.exit(1))):r.all?n=[...i]:(o.error("Specify --ip, --interactive, or --all to select IP rules to remove."),process.exit(1));if(n.length===0){o.info("No IP rules selected for removal.");return}if(o.log(V.default.cyan(`
|
|
145
|
+
${r.dryRun?"Would remove":"Removing"} ${n.length} IP rule(s):`)),io(n),r.dryRun){o.log(V.default.dim(`
|
|
146
|
+
Dry run \u2014 no changes made.`));return}if(!await oo(n.length,r.force||!1,r.all||!1,"IP rule")){o.info("Cancelled.");return}let s=new Set(n.map(c=>c.ip)),a={...t,ips:i.filter(c=>!s.has(c.ip))};await M(a,r.config),o.success(V.default.green(`\u2714 Removed ${n.length} IP rule(s) from configuration`))}else{let i=t.rules||[];if(i.length===0){o.info("No rules in configuration.");return}let n=[];if(r.interactive){let c=i.map((d,u)=>{let p=d.id?` (${d.id})`:"",m=d.active?"":" [disabled]",h=d.action.mitigate.action;return`[${u}] ${d.name}${p} \u2014 ${h}${m}`}),l=await C("Select rules to remove:",{type:"multiselect",options:c});n=i.filter((d,u)=>l.some(p=>p.startsWith(`[${u}]`)))}else if(r.name){if(n=i.filter(c=>c.name===r.name),n.length>1&&(o.warn(V.default.yellow(`
|
|
147
|
+
\u26A0\uFE0F Found ${n.length} rules named "${r.name}". All will be removed.`)),Qt(n)),n.length===0){o.error(V.default.red(`No rule found with exact name "${r.name}"`));let c=so(r.name,i);c.length>0&&(o.log(V.default.yellow(`
|
|
148
148
|
Did you mean one of these?`)),c.forEach((l,d)=>{let u=l.id?` (${l.id})`:"";o.log(V.default.dim(` ${d+1}. ${l.name}${u}`))}),o.log(V.default.dim(`
|
|
149
149
|
Use --id for exact matching, or --interactive to select from a list.`))),process.exit(1)}}else if(r.id&&r.id.length>0){let c=new Set(r.id);n=i.filter(u=>u.id&&c.has(u.id));let l=new Set(n.map(u=>u.id)),d=r.id.filter(u=>!l.has(u));d.length>0&&o.warn(V.default.yellow(`No rules found for IDs: ${d.join(", ")}`)),n.length===0&&(o.error(V.default.red("No matching rules found for the given IDs.")),process.exit(1))}else if(r.disabled){if(n=i.filter(c=>!c.active),n.length===0){o.info("No disabled rules found.");return}}else r.all?n=[...i]:(o.error("Specify --name, --id, --disabled, --all, or --interactive to select rules to remove."),process.exit(1));if(n.length===0){o.info("No rules selected for removal.");return}if(n.length>=5&&!r.dryRun&&!r.force&&o.log(V.default.yellow(`
|
|
150
150
|
\u{1F4A1} Tip: Run ${V.default.cyan("doorman backup")} before bulk removal operations.`)),o.log(V.default.cyan(`
|
|
151
151
|
${r.dryRun?"Would remove":"Removing"} ${n.length} rule(s):`)),Qt(n),r.dryRun){o.log(V.default.dim(`
|
|
152
|
-
Dry run \u2014 no changes made.`));return}if(!await
|
|
152
|
+
Dry run \u2014 no changes made.`));return}if(!await oo(n.length,r.force||!1,r.all||!1)){o.info("Cancelled.");return}let s=new Set(n),a={...t,rules:i.filter(c=>!s.has(c))};a.rules.length===0&&o.warn(V.default.yellow("\u26A0\uFE0F Configuration will have no rules after removal.")),await M(a,r.config),o.success(V.default.green(`\u2714 Removed ${n.length} rule(s) from configuration`)),Qt(n)}o.log(""),o.log(V.default.dim(`Run ${V.default.cyan("doorman sync")} to deploy these changes.`))}catch(e){ee(e,"removing rule")}};var Yt={};K(Yt,{builder:()=>Kn,command:()=>Hn,desc:()=>Zn,handler:()=>Jn});var L=S(require("chalk"));k();var Hn="setup",Zn="Show setup instructions and helpful links for Doorman",Kn={},Jn=async r=>{o.log(""),o.log(L.default.bold.cyan("\u{1F6AA} Doorman Setup Guide")),o.log(L.default.dim(`Everything you need to get started with firewall management
|
|
153
153
|
`)),o.log(L.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
|
|
154
|
-
`),o.log(L.default.bold("\u{1F50D} Finding Your Project Information")),o.log(""),o.log(L.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(L.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(L.default.bold("\u{1F511} Creating API Token")),o.log(""),o.log(L.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(L.default.cyan("Required Permissions:")),o.log(" \u2022 Read access to project settings"),o.log(" \u2022 Write access to firewall configuration"),o.log(""),o.log(L.default.bold("\u{1F30D} Environment Setup")),o.log(""),o.log(L.default.cyan("Set your API token as environment variable:")),o.log(""),o.log(L.default.green("# For current session:")),o.log('export VERCEL_TOKEN="your-token-here"'),o.log(""),o.log(L.default.green("# For permanent setup (add to ~/.bashrc or ~/.zshrc):")),o.log(`echo 'export VERCEL_TOKEN="your-token-here"' >> ~/.bashrc`),o.log(""),o.log(L.default.green("# Or create a .env file in your project:")),o.log('echo "VERCEL_TOKEN=your-token-here" > .env'),o.log(""),o.log(L.default.bold("\u{1F680} Quick Start Commands")),o.log(""),o.log(L.default.cyan("1. Initialize configuration:")),o.log(" doorman init --interactive"),o.log(""),o.log(L.default.cyan("2. Validate setup:")),o.log(" doorman validate"),o.log(""),o.log(L.default.cyan("3. Check current status:")),o.log(" doorman status"),o.log(""),o.log(L.default.cyan("4. View existing rules:")),o.log(" doorman list"),o.log(""),o.log(L.default.cyan("5. Sync your configuration:")),o.log(" doorman sync"),o.log(""),o.log(L.default.bold("\u{1F527} Common Issues")),o.log(""),o.log(L.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(L.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(L.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(L.default.bold("\u{1F4DA} Additional Resources")),o.log(""),o.log(L.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(L.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(L.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(L.default.bold.green("\u2705 Ready to get started?")),o.log(L.default.dim("Run: ")+L.default.cyan("doorman init --interactive")),o.log("")};var ei={};K(ei,{builder:()=>
|
|
154
|
+
`),o.log(L.default.bold("\u{1F50D} Finding Your Project Information")),o.log(""),o.log(L.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(L.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(L.default.bold("\u{1F511} Creating API Token")),o.log(""),o.log(L.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(L.default.cyan("Required Permissions:")),o.log(" \u2022 Read access to project settings"),o.log(" \u2022 Write access to firewall configuration"),o.log(""),o.log(L.default.bold("\u{1F30D} Environment Setup")),o.log(""),o.log(L.default.cyan("Set your API token as environment variable:")),o.log(""),o.log(L.default.green("# For current session:")),o.log('export VERCEL_TOKEN="your-token-here"'),o.log(""),o.log(L.default.green("# For permanent setup (add to ~/.bashrc or ~/.zshrc):")),o.log(`echo 'export VERCEL_TOKEN="your-token-here"' >> ~/.bashrc`),o.log(""),o.log(L.default.green("# Or create a .env file in your project:")),o.log('echo "VERCEL_TOKEN=your-token-here" > .env'),o.log(""),o.log(L.default.bold("\u{1F680} Quick Start Commands")),o.log(""),o.log(L.default.cyan("1. Initialize configuration:")),o.log(" doorman init --interactive"),o.log(""),o.log(L.default.cyan("2. Validate setup:")),o.log(" doorman validate"),o.log(""),o.log(L.default.cyan("3. Check current status:")),o.log(" doorman status"),o.log(""),o.log(L.default.cyan("4. View existing rules:")),o.log(" doorman list"),o.log(""),o.log(L.default.cyan("5. Sync your configuration:")),o.log(" doorman sync"),o.log(""),o.log(L.default.bold("\u{1F527} Common Issues")),o.log(""),o.log(L.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(L.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(L.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(L.default.bold("\u{1F4DA} Additional Resources")),o.log(""),o.log(L.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(L.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(L.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(L.default.bold.green("\u2705 Ready to get started?")),o.log(L.default.dim("Run: ")+L.default.cyan("doorman init --interactive")),o.log("")};var ei={};K(ei,{builder:()=>Yn,command:()=>Qn,desc:()=>Xn,handler:()=>er});var T=S(require("chalk"));k();var be=S(require("chalk")),tt=class{static check(e){let t=[],i=[],n=100;return this.checkRuleNaming(e.rules,t),this.checkRuleComplexity(e.rules,t),this.checkSecurityBestPractices(e,t,i),this.checkPerformanceImpact(e,t,i),this.checkMaintainability(e,t,i),t.forEach(s=>{switch(s.severity){case"error":n-=20;break;case"warning":n-=10;break;case"info":n-=5;break}}),{score:Math.max(0,n),issues:t,recommendations:i}}static checkRuleNaming(e,t){e.forEach(i=>{i.id&&!i.id.match(/^rule_[a-z0-9_]+$/)&&t.push({severity:"warning",message:"Rule ID should follow snake_case format: rule_*",rule:i.name,suggestion:`Consider renaming to: rule_${i.name.toLowerCase().replace(/\s+/g,"_")}`}),i.name.length<5&&t.push({severity:"info",message:"Rule name is very short, consider making it more descriptive",rule:i.name}),(!i.description||i.description.length<10)&&t.push({severity:"info",message:"Rule lacks a detailed description",rule:i.name,suggestion:"Add a clear description explaining what this rule does and why"})})}static checkRuleComplexity(e,t){e.forEach(i=>{i.conditionGroup.reduce((s,a)=>s+a.conditions.length,0)>10&&t.push({severity:"warning",message:"Rule has many conditions, consider splitting into multiple rules",rule:i.name,suggestion:"Complex rules can be harder to maintain and debug"}),i.conditionGroup.length>5&&t.push({severity:"warning",message:"Rule has many condition groups, consider simplifying",rule:i.name})})}static checkSecurityBestPractices(e,t,i){let{rules:n,ips:s}=e;n.some(l=>l.action.mitigate.action==="rate_limit")||i.push("Consider adding rate limiting rules for API endpoints"),n.some(l=>l.conditionGroup.some(d=>d.conditions.some(u=>u.type==="user_agent"&&typeof u.value=="string"&&(u.value.toLowerCase().includes("bot")||u.value.toLowerCase().includes("crawler")))))||i.push("Consider adding bot protection rules"),n.forEach(l=>{l.conditionGroup.some(u=>u.conditions.some(p=>p.type==="path"&&p.value==="/"))&&l.action.mitigate.action==="deny"&&t.push({severity:"error",message:"Rule blocks root path - this could block all traffic",rule:l.name,suggestion:"Be more specific with path conditions"})}),s&&s.length>100&&t.push({severity:"warning",message:"Large number of IP blocking rules may impact performance",suggestion:"Consider using CIDR ranges or external IP lists"})}static checkPerformanceImpact(e,t,i){let{rules:n}=e;n.forEach(a=>{a.conditionGroup.some(l=>l.conditions.some(d=>d.op==="re"))&&t.push({severity:"info",message:"Rule uses regex matching, which may impact performance",rule:a.name,suggestion:"Consider using simpler string operations when possible"})}),n.filter(a=>a.active).length>50&&t.push({severity:"warning",message:"Large number of active rules may impact performance",suggestion:"Consider consolidating similar rules or disabling unused ones"})}static checkMaintainability(e,t,i){let{rules:n}=e;n.filter(l=>!l.active).length>n.length*.3&&i.push("Consider removing disabled rules to reduce config complexity");let a=n.map(l=>l.name);a.filter((l,d)=>a.indexOf(l)!==d).forEach(l=>{t.push({severity:"error",message:"Duplicate rule name found",rule:l,suggestion:"Rule names must be unique"})}),e.version||t.push({severity:"warning",message:"Configuration lacks version information",suggestion:"Version tracking helps with change management"})}static formatHealthReport(e){let t="",i=e.score>=80?be.default.green:e.score>=60?be.default.yellow:be.default.red;return t+=be.default.bold(`
|
|
155
155
|
\u{1F3E5} Configuration Health Score: ${i(e.score)}/100
|
|
156
156
|
|
|
157
157
|
`),e.issues.length>0&&(t+=be.default.bold(`Issues Found:
|
|
@@ -160,29 +160,29 @@ Dry run \u2014 no changes made.`));return}if(!await io(n.length,r.force||!1,r.al
|
|
|
160
160
|
`))}),t+=`
|
|
161
161
|
`),e.recommendations.length>0&&(t+=be.default.bold(`Recommendations:
|
|
162
162
|
`),e.recommendations.forEach(n=>{t+=`\u{1F4A1} ${n}
|
|
163
|
-
`})),t}};var
|
|
163
|
+
`})),t}};var Qn="status",Xn="Show sync status between local and remote firewall configuration",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)"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},er=async r=>{await ie({config:r.config,provider:r.provider,projectId:r.projectId,teamId:r.teamId,token:r.token,apiToken:r.apiToken,zoneId:r.zoneId,accountId:r.accountId,debug:r.debug,ci:r.ci,errorContext:"checking status"},async({config:e,service:t,provider:i})=>{if(i.name!=="vercel"){await tr(i,e);return}o.start("Checking sync status...");let{toAdd:n,toUpdate:s,toDelete:a,ipsToAdd:c,ipsToUpdate:l,ipsToDelete:d,version:u}=await t.getChanges(e),p=n.length>0||s.length>0||a.length>0,m=c.length>0||l.length>0||d.length>0,h=e.version!==u;o.log(T.default.bold(`
|
|
164
164
|
\u{1F4CA} Sync Status Summary
|
|
165
165
|
`)),o.log(`${T.default.dim("Local Version:")} ${T.default.yellow(e.version||"unknown")}`),o.log(`${T.default.dim("Remote Version:")} ${T.default.yellow(u)}`),h?o.log(`${T.default.dim("Version Status:")} ${T.default.red("Out of sync")}`):o.log(`${T.default.dim("Version Status:")} ${T.default.green("In sync")}`),o.log(""),o.log(`${T.default.dim("Custom Rules:")}`),o.log(` ${T.default.green("+")} ${n.length} to add`),o.log(` ${T.default.cyan("~")} ${s.length} to update`),o.log(` ${T.default.red("-")} ${a.length} to delete`),o.log(`${T.default.dim("IP Blocking Rules:")}`),o.log(` ${T.default.green("+")} ${c.length} to add`),o.log(` ${T.default.cyan("~")} ${l.length} to update`),o.log(` ${T.default.red("-")} ${d.length} to delete`),o.log(""),!p&&!m&&!h?o.success(T.default.green("\u2705 Everything is in sync!")):(o.warn(T.default.yellow("\u26A0\uFE0F Changes detected. Run `sync` to apply changes.")),h&&o.info(T.default.dim("\u{1F4A1} Version mismatch detected - this will be updated during sync"))),e.updatedAt&&o.log(`
|
|
166
166
|
${T.default.dim("Last Updated:")} ${new Date(e.updatedAt).toLocaleString()}`),o.log(`
|
|
167
|
-
`+T.default.bold("\u{1F3E5} Configuration Health Check"));let v=tt.check(e),f=tt.formatHealthReport(v);o.log(f)})};async function
|
|
167
|
+
`+T.default.bold("\u{1F3E5} Configuration Health Check"));let v=tt.check(e),f=tt.formatHealthReport(v);o.log(f)})};async function tr(r,e){o.start("Checking sync status...");let t=await r.getChanges(e);o.log(T.default.bold(`
|
|
168
168
|
\u{1F4CA} ${r.name} Sync Status Summary
|
|
169
169
|
`)),o.log(`${T.default.dim("Rules:")}`),o.log(` ${T.default.green("+")} ${t.rulesToAdd.length} to add`),o.log(` ${T.default.cyan("~")} ${t.rulesToUpdate.length} to update`),o.log(` ${T.default.red("-")} ${t.rulesToDelete.length} to delete`),o.log(`${T.default.dim("IPs:")}`),o.log(` ${T.default.green("+")} ${t.ipsToAdd?.length??0} to add`),o.log(` ${T.default.cyan("~")} ${t.ipsToUpdate?.length??0} to update`),o.log(` ${T.default.red("-")} ${t.ipsToDelete?.length??0} to delete`),o.log(""),t.hasChanges?o.warn(T.default.yellow("\u26A0\uFE0F Changes detected. Run `sync` to apply changes.")):o.success(T.default.green("\u2705 Everything is in sync!")),o.log(`
|
|
170
170
|
`+T.default.bold("\u{1F3E5} Configuration Health Check"));let i=r.getHealthScore(e);o.log(`${T.default.dim("Score:")} ${i.score}/100 (${i.grade})`),i.issues.forEach(n=>{let s=n.severity==="error"?T.default.red("\u2717"):n.severity==="warning"?T.default.yellow("\u26A0"):T.default.dim("\u2139");o.log(` ${s} [${n.category}] ${n.message}`),n.suggestion&&o.log(` ${T.default.dim(n.suggestion)}`)}),i.recommendations.length>0&&(o.log(T.default.dim(`
|
|
171
|
-
Recommendations:`)),i.recommendations.forEach(n=>o.log(` - ${n}`)))}var ti={};K(ti,{builder:()=>
|
|
171
|
+
Recommendations:`)),i.recommendations.forEach(n=>o.log(` - ${n}`)))}var ti={};K(ti,{builder:()=>nr,command:()=>ir,desc:()=>or,handler:()=>rr});var N=S(require("chalk"));k();de();var ir="sync",or="Sync Vercel Firewall rules with config file",nr={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}},rr=async r=>{await ie({config:r.config,provider:r.provider,projectId:r.projectId,teamId:r.teamId,token:r.token,apiToken:r.apiToken,zoneId:r.zoneId,accountId:r.accountId,debug:r.debug,ci:r.ci,errorContext:"syncing firewall rules"},async e=>{if(e.provider.name!=="vercel"){await sr(e.provider,e.config,r);return}let t=e.config,i=e.service;o.start(N.default.magenta("Calculating firewall configuration changes..."));let{toAdd:n,toUpdate:s,toDelete:a,ipsToAdd:c,ipsToUpdate:l,ipsToDelete:d,version:u}=await i.getChanges(t),p=n.length>0||s.length>0||a.length>0,m=c.length>0||l.length>0||d.length>0,h=t.version!==u;if(!p&&!m&&!h){o.success(N.default.green("No changes detected. Firewall rules are in sync."));return}if(p&&(o.log(N.default.bold(`
|
|
172
172
|
Proposed Custom Rule Changes:
|
|
173
|
-
`)),Ee([...n.map(g=>({...g,changeStatus:le.new,id:g.id})),...s.map(g=>({...g,changeStatus:le.modified,id:g.id})),...a.map(g=>({...g,changeStatus:le.deleted,id:g.id}))],{showStatus:!0})),m&&(o.log(
|
|
173
|
+
`)),Ee([...n.map(g=>({...g,changeStatus:le.new,id:g.id})),...s.map(g=>({...g,changeStatus:le.modified,id:g.id})),...a.map(g=>({...g,changeStatus:le.deleted,id:g.id}))],{showStatus:!0})),m&&(o.log(N.default.bold(`
|
|
174
174
|
Proposed IP Blocking Rule Changes:
|
|
175
|
-
`)),$e([...c.map(g=>({...g,changeStatus:le.new,id:g.id||void 0})),...l.map(g=>({...g,changeStatus:le.modified,id:g.id||void 0})),...d.map(g=>({...g,changeStatus:le.deleted,id:g.id||void 0}))],{showStatus:!0})),h&&(o.log(
|
|
175
|
+
`)),$e([...c.map(g=>({...g,changeStatus:le.new,id:g.id||void 0})),...l.map(g=>({...g,changeStatus:le.modified,id:g.id||void 0})),...d.map(g=>({...g,changeStatus:le.deleted,id:g.id||void 0}))],{showStatus:!0})),h&&(o.log(N.default.bold(`
|
|
176
176
|
Proposed Metadata Changes:
|
|
177
|
-
`)),o.log(` - Version: ${
|
|
177
|
+
`)),o.log(` - Version: ${N.default.red(t.version)} ${N.default.dim("->")} ${N.default.green(u)}`)),!await C("Do you want to apply these changes?",{type:"confirm"})){o.info(N.default.yellow("Sync cancelled."));return}o.start("Starting firewall rules sync...");let f=JSON.parse(JSON.stringify(t)),E=await i.syncRules(t,{debug:r.debug}),{rulesToUpdateLocally:U}=E;o.success(N.default.green("Firewall rules sync completed successfully"));try{t=await i.validateAndUpdateConfig(t,E,{dryRun:!1})}catch(g){throw o.error("Failed to validate sync result or update config metadata"),o.error(g instanceof Error?g.message:String(g)),await M(f,r.config),o.info(N.default.yellow("Restored original config due to validation failure")),new Error("Sync validation failed - original config restored")}let x=U.filter(g=>t.rules.some(A=>g.oldId===A.id||g.oldId===""&&g.name===A.name));x.length>0&&(o.log(""),o.info(N.default.yellow("Some rules have IDs that do not match their expected snake_case name:")),x.forEach(A=>{o.log(` - Rule "${A.name}": ${N.default.red(A.oldId||"empty")} ${N.default.dim("->")} ${N.default.green(A.newId)}`)}),await C("Do you want to update the local config with the new IDs?",{type:"confirm"})?(t={...t,rules:t.rules.map(A=>{let R=x.find(I=>I.oldId===A.id||I.oldId===""&&I.name===A.name);return R?{...A,id:R.newId}:A}),ips:t.ips||[]},await M(t,r.config),o.success(N.default.green("Updated local config with new rule IDs"))):o.warn(N.default.yellow("Local config not updated. Remember to update rule IDs manually if needed."))),(f.version!==t.version||f.updatedAt!==t.updatedAt)&&(await M(t,r.config),o.success(N.default.green(`Updated version ${N.default.dim(`(v${t.version})`)} and metadata in local config file`)))})};async function sr(r,e,t){let i=e;o.start(N.default.magenta(`Calculating ${r.name} firewall configuration changes...`));let n=await r.getChanges(i);if(!n.hasChanges){o.success(N.default.green("No changes detected. Firewall rules are in sync."));return}o.log(N.default.bold(`
|
|
178
178
|
Proposed Changes:
|
|
179
|
-
`)),o.log(` ${F.default.green("+")} ${n.rulesToAdd.length} rules to add`),o.log(` ${F.default.cyan("~")} ${n.rulesToUpdate.length} rules to update`),o.log(` ${F.default.red("-")} ${n.rulesToDelete.length} rules to delete`);let s=n.ipsToAdd??[],a=n.ipsToUpdate??[],c=n.ipsToDelete??[];(s.length||a.length||c.length)&&(o.log(` ${F.default.green("+")} ${s.length} IPs to add`),o.log(` ${F.default.cyan("~")} ${a.length} IPs to update`),o.log(` ${F.default.red("-")} ${c.length} IPs to delete`)),o.start("Starting firewall rules sync...");let l=await r.syncRules(i,{force:t.ci,allowDeletions:t.allowDeletions});if(!l.success)throw new Error(`Sync failed: ${l.errors?.join(", ")||"unknown error"}`);o.success(F.default.green("Firewall rules sync completed successfully")),o.log(` Rules: ${l.rulesAdded} added, ${l.rulesUpdated} updated, ${l.rulesDeleted} deleted`),(l.ipsAdded||l.ipsUpdated||l.ipsDeleted)&&o.log(` IPs: ${l.ipsAdded??0} added, ${l.ipsUpdated??0} updated, ${l.ipsDeleted??0} deleted`),l.warnings?.forEach(d=>o.warn(d))}var oi={};K(oi,{builder:()=>lr,command:()=>sr,desc:()=>ar,handler:()=>ur});var Ae=k(require("chalk")),po=require("consola");P();var so={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 ao={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 lo={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 co={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 ii={"ai-bots":so,"bad-bots":ao,"block-ofac-sanctioned-countries":lo,wordpress:co};var uo=r=>ii[r]?.config;de();var sr="template [name]",ar="Add a firewall rule template to your configuration",lr={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 cr(r,e){let t=new Set(r.map(n=>n.name.toLowerCase())),i=e.filter(n=>t.has(n.name.toLowerCase())).map(n=>n.name);return[...new Set(i)]}var dr=()=>Object.keys(ii),ur=async r=>{try{r.debug&&(o.level=po.LogLevels.debug),o.debug("Template command arguments:",r);let e=r.name;if(!e){let l=dr();e=await R("Select a template to add:",{type:"select",options:l,initial:l[0]})}let t=uo(e);t||(o.error(`Template not found: ${e}`),process.exit(1)),o.debug("Template content:",t),o.start("Loading current configuration...");let i=await H(r.config,"raw"),n=i.rules||[],s=cr(n,t.rules);if(r.dryRun){o.info(Ae.default.cyan(`
|
|
180
|
-
Dry run - The following rules would be added:`)),o.log(JSON.stringify(t.rules,null,2)),s.length>0&&o.warn(Ae.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`));return}if(s.length>0&&(o.warn(Ae.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`)),!await
|
|
181
|
-
`);let n=i?
|
|
179
|
+
`)),o.log(` ${N.default.green("+")} ${n.rulesToAdd.length} rules to add`),o.log(` ${N.default.cyan("~")} ${n.rulesToUpdate.length} rules to update`),o.log(` ${N.default.red("-")} ${n.rulesToDelete.length} rules to delete`);let s=n.ipsToAdd??[],a=n.ipsToUpdate??[],c=n.ipsToDelete??[];(s.length||a.length||c.length)&&(o.log(` ${N.default.green("+")} ${s.length} IPs to add`),o.log(` ${N.default.cyan("~")} ${a.length} IPs to update`),o.log(` ${N.default.red("-")} ${c.length} IPs to delete`)),o.start("Starting firewall rules sync...");let l=await r.syncRules(i,{force:t.ci,allowDeletions:t.allowDeletions});if(!l.success)throw new Error(`Sync failed: ${l.errors?.join(", ")||"unknown error"}`);o.success(N.default.green("Firewall rules sync completed successfully")),o.log(` Rules: ${l.rulesAdded} added, ${l.rulesUpdated} updated, ${l.rulesDeleted} deleted`),(l.ipsAdded||l.ipsUpdated||l.ipsDeleted)&&o.log(` IPs: ${l.ipsAdded??0} added, ${l.ipsUpdated??0} updated, ${l.ipsDeleted??0} deleted`),l.warnings?.forEach(d=>o.warn(d))}var oi={};K(oi,{builder:()=>cr,command:()=>ar,desc:()=>lr,handler:()=>pr});var Ae=S(require("chalk")),go=require("consola");k();var ao={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 lo={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 co={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 uo={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 ii={"ai-bots":ao,"bad-bots":lo,"block-ofac-sanctioned-countries":co,wordpress:uo};var po=r=>ii[r]?.config;de();var ar="template [name]",lr="Add a firewall rule template to your configuration",cr={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 dr(r,e){let t=new Set(r.map(n=>n.name.toLowerCase())),i=e.filter(n=>t.has(n.name.toLowerCase())).map(n=>n.name);return[...new Set(i)]}var ur=()=>Object.keys(ii),pr=async r=>{try{r.debug&&(o.level=go.LogLevels.debug),o.debug("Template command arguments:",r);let e=r.name;if(!e){let l=ur();e=await C("Select a template to add:",{type:"select",options:l,initial:l[0]})}let t=po(e);t||(o.error(`Template not found: ${e}`),process.exit(1)),o.debug("Template content:",t),o.start("Loading current configuration...");let i=await H(r.config,"raw"),n=i.rules||[],s=dr(n,t.rules);if(r.dryRun){o.info(Ae.default.cyan(`
|
|
180
|
+
Dry run - The following rules would be added:`)),o.log(JSON.stringify(t.rules,null,2)),s.length>0&&o.warn(Ae.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`));return}if(s.length>0&&(o.warn(Ae.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`)),!await C("Proceed anyway?",{type:"confirm",initial:!1}))){o.info("Cancelled.");return}let a={...i,rules:[...n,...t.rules]},c=we.safeParse(a);c.success||(o.error(Ae.default.red("The resulting configuration would be invalid:")),c.error.errors.forEach(l=>{let d=l.path.join(".");o.error(Ae.default.red(` - ${d}: ${l.message}`))}),o.info(Ae.default.dim("Template was not applied. Fix the issues above and try again.")),process.exit(1)),o.start("Saving updated configuration..."),await M(a,r.config,{validate:!1}),o.success(Ae.default.green(`Successfully added template '${e}' to configuration`))}catch(e){ee(e,"adding template")}};var ni={};K(ni,{builder:()=>mr,command:()=>gr,desc:()=>fr,handler:()=>hr});var ne=S(require("chalk"));k();var gr="validate",fr="Validate firewall configuration file",mr={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}},hr=async r=>{try{let e=await H(r.config,"raw"),t=Ce.getInstance(),i=Pe(e);r.verbose&&o.start(`Validating configuration file...
|
|
181
|
+
`);let n=i?vt.safeParse(e):we.safeParse(e);r.verbose&&(o.log(ne.default.bold.underline("Zod Schema Validation:")),n.success?o.log(ne.default.green("\u2713 Schema validation passed")):(o.error(ne.default.red("\u2717 Schema validation failed:")),n.error.errors.forEach(c=>{let l=c.path.join(".");o.error(ne.default.red(` - ${l}: ${c.message}`))})));let s=!0,a=[];try{t.validateConfig(e),r.verbose&&(o.log(ne.default.bold.underline(`
|
|
182
182
|
AJV Schema Validation:`)),o.log(ne.default.green("\u2713 JSON Schema validation passed")))}catch(c){if(s=!1,c instanceof B)a=c.ajvErrors||[],r.verbose&&(o.log(ne.default.bold.underline(`
|
|
183
183
|
AJV Schema Validation:`)),o.error(ne.default.red("\u2717 JSON Schema validation failed:")),a.forEach(l=>{o.error(ne.default.red(` - ${l.instancePath}: ${l.message}`))}));else throw c}if(n.success&&s&&r.verbose){o.log(ne.default.bold.underline(`
|
|
184
184
|
Custom Validations:`));let c=n.data,l=new Set,d=new Set;for(let u of c.rules)l.has(u.name)&&d.add(u.name),l.add(u.name);o.log(`${ne.default.cyan.dim(`
|
|
185
|
-
Rule Names:`)}`),d.size>0?(o.error(ne.default.red("\u2717 Duplicate rule names found:")),d.forEach(u=>o.error(ne.default.red(` - "${u}"`)))):o.log(ne.default.green("\u2713 All rule names are unique")),o.log("")}if(n.success&&s)o.success(ne.default.green("Configuration is valid"));else throw new Error("Configuration validation failed")}catch(e){ee(e,"validating configuration")}};var ri={};K(ri,{builder:()=>
|
|
186
|
-
`),o.info(X.default.yellow("Stopping watch mode...")),(0,pt.unwatchFile)(e),process.exit(0)};process.on("SIGINT",c),process.on("SIGTERM",c);let l=()=>{setTimeout(l,1e3)};l()})};async function
|
|
185
|
+
Rule Names:`)}`),d.size>0?(o.error(ne.default.red("\u2717 Duplicate rule names found:")),d.forEach(u=>o.error(ne.default.red(` - "${u}"`)))):o.log(ne.default.green("\u2713 All rule names are unique")),o.log("")}if(n.success&&s)o.success(ne.default.green("Configuration is valid"));else throw new Error("Configuration validation failed")}catch(e){ee(e,"validating configuration")}};var ri={};K(ri,{builder:()=>Rr,command:()=>yr,desc:()=>wr,handler:()=>Cr});var X=S(require("chalk")),pt=require("fs");k();var yr="watch",wr="Watch config file for changes and auto-sync",Rr={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}},Cr=async r=>{let e=r.config||".doorman.json";await ie({config:e,provider:r.provider,projectId:r.projectId,teamId:r.teamId,token:r.token,apiToken:r.apiToken,zoneId:r.zoneId,accountId:r.accountId,debug:r.debug,ci:r.ci,errorContext:"setting up watch mode"},async({service:t,provider:i})=>{let n=!1,s=0;o.success(X.default.green(`\u{1F440} Watching ${e} for changes...`)),o.log(X.default.dim("Press Ctrl+C to stop watching")),o.log("");let a=async(d,u)=>{if(!(n||d.mtime.getTime()===s)){n=!0,s=d.mtime.getTime();try{o.log(X.default.yellow(`\u{1F4DD} Config file changed at ${new Date().toLocaleTimeString()}`)),o.start("Validating and syncing changes...");let p=await H(e);if(i.name!=="vercel"){await Ir(i,p),o.log(X.default.dim("Watching for more changes..."));return}let{toAdd:m,toUpdate:h,toDelete:v,ipsToAdd:f,ipsToUpdate:E,ipsToDelete:U,version:x}=await t.getChanges(p);if(!(m.length>0||h.length>0||v.length>0||f.length>0||E.length>0||U.length>0||p.version!==x)){o.info(X.default.blue("No changes detected, skipping sync"));return}let A=m.length+h.length+v.length+f.length+E.length+U.length;o.log(X.default.cyan(`Syncing ${A} changes...`));let R=await t.syncRules(p,{debug:r.debug});try{let I=await t.validateAndUpdateConfig(p,R,{dryRun:!1});await M(I,e),o.success(X.default.green(`\u2705 Sync completed at ${new Date().toLocaleTimeString()}`))}catch(I){o.warn(X.default.yellow(`\u26A0\uFE0F Sync applied but validation failed: ${I instanceof Error?I.message:String(I)}`)),o.info(X.default.dim("Run `download` to reconcile local config with remote state"))}o.log(X.default.dim("Watching for more changes..."))}catch(p){o.error(X.default.red(`\u274C Sync failed: ${p instanceof Error?p.message:String(p)}`)),o.log(X.default.dim("Continuing to watch for changes..."))}finally{n=!1}}};(0,pt.watchFile)(e,{interval:r.interval},a);let c=()=>{o.log(`
|
|
186
|
+
`),o.info(X.default.yellow("Stopping watch mode...")),(0,pt.unwatchFile)(e),process.exit(0)};process.on("SIGINT",c),process.on("SIGTERM",c);let l=()=>{setTimeout(l,1e3)};l()})};async function Ir(r,e){let t=await r.getChanges(e);if(!t.hasChanges){o.info(X.default.blue("No changes detected, skipping sync"));return}let i=t.rulesToAdd.length+t.rulesToUpdate.length+t.rulesToDelete.length+(t.ipsToAdd?.length??0)+(t.ipsToUpdate?.length??0)+(t.ipsToDelete?.length??0);o.log(X.default.cyan(`Syncing ${i} changes...`));let n=await r.syncRules(e,{force:!0,allowDeletions:!0});if(!n.success)throw new Error(`Sync failed: ${n.errors?.join(", ")||"unknown error"}`);o.success(X.default.green(`\u2705 Sync completed at ${new Date().toLocaleTimeString()}`)),n.warnings?.forEach(s=>o.warn(s))}var fo=[Yt,Kt,St,Jt,ei,Gt,ti,ni,Ht,oi,Xt,Ft,Zt,ri];(0,mo.config)();async function br(){let r=(await import("chalk")).default,e=(0,ho.default)(process.argv.slice(2));e.usage(`${r.bold("\u{1F6AA} Doorman")}
|
|
187
187
|
|
|
188
|
-
${r.dim("Manage firewall rules as code across multiple providers")}`);for(let t of
|
|
188
|
+
${r.dim("Manage firewall rules as code across multiple providers")}`);for(let t of fo)e.command(t);e.demandCommand(1,"You need at least one command before moving on").help().epilogue(r.dim(`See ${r.bold("https://doorman.griffen.codes/getting-started")} for more info`)).argv}br().catch(console.error);
|