@gfargo/doorman 3.11.4 → 3.11.5
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 +26 -26
- package/dist/bin/run.mjs +20 -20
- package/package.json +1 -1
package/dist/bin/run.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var Wo=Object.create;var gt=Object.defineProperty;var jo=Object.getOwnPropertyDescriptor;var qo=Object.getOwnPropertyNames;var zo=Object.getPrototypeOf,Mo=Object.prototype.hasOwnProperty;var qe=(i,e)=>()=>(i&&(e=i(i=0)),e);var M=(i,e)=>{for(var t in e)gt(i,t,{get:e[t],enumerable:!0})},wi=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qo(e))!Mo.call(i,n)&&n!==t&>(i,n,{get:()=>e[n],enumerable:!(o=jo(e,n))||o.enumerable});return i};var S=(i,e,t)=>(t=i!=null?Wo(zo(i)):{},wi(e||!i||!i.__esModule?gt(t,"default",{value:i,enumerable:!0}):t,i)),ye=i=>wi(gt({},"__esModule",{value:!0}),i);var Ii,r,T=qe(()=>{"use strict";Ii=require("consola"),r=(0,Ii.createConsola)({formatOptions:{colors:!0,compact:!0,date:!1}})});var
|
|
2
|
-
`),u.cancelled&&process.exit(0),e(n))};t.on("keypress",a)})}var zi,zt=qe(()=>{"use strict";zi=require("readline")});var De={};M(De,{TranslationWarningSystem:()=>
|
|
1
|
+
"use strict";var Wo=Object.create;var gt=Object.defineProperty;var jo=Object.getOwnPropertyDescriptor;var qo=Object.getOwnPropertyNames;var zo=Object.getPrototypeOf,Mo=Object.prototype.hasOwnProperty;var qe=(i,e)=>()=>(i&&(e=i(i=0)),e);var M=(i,e)=>{for(var t in e)gt(i,t,{get:e[t],enumerable:!0})},wi=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qo(e))!Mo.call(i,n)&&n!==t&>(i,n,{get:()=>e[n],enumerable:!(o=jo(e,n))||o.enumerable});return i};var S=(i,e,t)=>(t=i!=null?Wo(zo(i)):{},wi(e||!i||!i.__esModule?gt(t,"default",{value:i,enumerable:!0}):t,i)),ye=i=>wi(gt({},"__esModule",{value:!0}),i);var Ii,r,T=qe(()=>{"use strict";Ii=require("consola"),r=(0,Ii.createConsola)({formatOptions:{colors:!0,compact:!0,date:!1}})});var vi,w,pe=qe(()=>{"use strict";vi=S(require("consola")),w=async(i,e)=>{if(!process.stdin.isTTY)throw new Error(`Cannot prompt for "${i}" \u2014 no interactive terminal available. Re-run with the appropriate non-interactive flag for this command (e.g. --interactive=false, --ci, --force).`);let t=await vi.default.prompt(i,e);return t!=null&&t.toString()==="Symbol(clack:cancel)"&&process.exit(0),(!e?.type||e.type==="text")&&t===void 0?"":t}});function In(i,e){return e?.ctrl&&e.name==="c"?{type:"cancel"}:e?.name==="return"||e?.name==="enter"?{type:"submit"}:e?.name==="backspace"?{type:"backspace"}:i&&!e?.ctrl&&!e?.meta&&i.length===1&&i>=" "?{type:"append",char:i}:{type:"ignore"}}function Rn(i,e){switch(e.type){case"append":return{value:i+e.char,done:!1,cancelled:!1,echo:"add"};case"backspace":return i.length===0?{value:i,done:!1,cancelled:!1,echo:"none"}:{value:i.slice(0,-1),done:!1,cancelled:!1,echo:"remove"};case"submit":return{value:i,done:!0,cancelled:!1,echo:"none"};case"cancel":return{value:i,done:!0,cancelled:!0,echo:"none"};case"ignore":return{value:i,done:!1,cancelled:!1,echo:"none"}}}async function at(i){if(process.stdout.write(i),!process.stdin.isTTY){let{createInterface:e}=await import("readline"),t=e({input:process.stdin,output:process.stdout,terminal:!1});return new Promise(o=>{t.question("",n=>{t.close(),o(n)})})}return new Promise(e=>{let t=process.stdin,o=t.isRaw;(0,zi.emitKeypressEvents)(t),t.setRawMode(!0),t.resume();let n="",s=()=>{t.removeListener("keypress",a),t.setRawMode(o??!1)},a=(l,c)=>{let d=In(l,c),u=Rn(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 zi,zt=qe(()=>{"use strict";zi=require("readline")});var De={};M(De,{TranslationWarningSystem:()=>D});var D,fe=qe(()=>{"use strict";D=class i{static DOCS_BASE_URL="https://docs.doorman.griffen.codes";static WARNING_CONFIGS={managed_rules:{category:"feature_unsupported",severity:"critical",explanation:"Managed rules are provider-specific security rules that cannot be directly translated between platforms.",suggestion:"Replace with custom rules using equivalent conditions and actions.",alternativeApproach:"Create custom rules that match the same traffic patterns using standard conditions like IP, country, user agent, or request headers.",impact:"Security coverage may be reduced until equivalent custom rules are implemented.",docsUrl:`${i.DOCS_BASE_URL}/migration/managed-rules`},bot_management:{category:"feature_unsupported",severity:"critical",explanation:"Bot management features use provider-specific detection algorithms that cannot be translated.",suggestion:"Configure bot management separately in the target provider.",alternativeApproach:"Use user agent filtering, rate limiting, and challenge actions to implement basic bot protection.",impact:"Bot protection effectiveness may vary between providers.",docsUrl:`${i.DOCS_BASE_URL}/migration/bot-management`},complex_expressions:{category:"lossy_conversion",severity:"warning",explanation:"Complex expressions may not translate perfectly due to differences in syntax and supported operators between providers.",suggestion:"Review translated expressions and test thoroughly before deploying.",alternativeApproach:"Break complex expressions into simpler, more portable conditions.",impact:"Rule behavior may differ slightly from the original configuration.",docsUrl:`${i.DOCS_BASE_URL}/migration/expressions`},geo_blocking:{category:"lossy_conversion",severity:"warning",explanation:"Geographic blocking may use different country codes or geographic databases between providers.",suggestion:"Verify country codes and geographic targeting after translation.",alternativeApproach:"Use ISO country codes when possible for better compatibility.",impact:"Some geographic regions may be blocked or allowed differently than intended.",docsUrl:`${i.DOCS_BASE_URL}/migration/geo-blocking`},rate_limiting_precision:{category:"lossy_conversion",severity:"info",explanation:"Rate limiting configurations may be adjusted to match the target provider's supported time windows and request thresholds.",suggestion:"Review rate limiting settings and adjust if necessary.",alternativeApproach:"Use the closest supported time window and request threshold values.",impact:"Rate limiting may be slightly more or less restrictive than the original configuration.",docsUrl:`${i.DOCS_BASE_URL}/migration/rate-limiting`},regex_patterns:{category:"syntax_limitation",severity:"warning",explanation:"Regular expression patterns may have different syntax requirements or feature support between providers.",suggestion:"Test regex patterns in the target provider and adjust syntax if needed.",alternativeApproach:"Use simpler string matching operations (contains, starts_with, ends_with) when possible.",impact:"Pattern matching may behave differently or fail to match intended traffic.",docsUrl:`${i.DOCS_BASE_URL}/migration/regex-patterns`},header_manipulation:{category:"syntax_limitation",severity:"warning",explanation:"Header manipulation capabilities vary between providers in terms of supported headers and modification types.",suggestion:"Verify header modification support in the target provider.",alternativeApproach:"Use redirect rules or custom error pages to achieve similar functionality.",impact:"Header modifications may not work as expected or may be ignored.",docsUrl:`${i.DOCS_BASE_URL}/migration/headers`},large_ip_lists:{category:"performance_impact",severity:"info",explanation:"Large IP lists may impact rule evaluation performance differently between providers.",suggestion:"Consider using provider-specific IP list features for better performance.",alternativeApproach:"Break large IP lists into smaller, more targeted rules or use CIDR notation to reduce list size.",impact:"Rule evaluation may be slower with large IP lists, potentially affecting site performance.",docsUrl:`${i.DOCS_BASE_URL}/migration/ip-lists`},many_conditions:{category:"performance_impact",severity:"info",explanation:"Rules with many conditions may have different performance characteristics between providers.",suggestion:"Monitor rule performance and consider optimizing complex rules.",alternativeApproach:"Split complex rules into multiple simpler rules or use more efficient condition types.",impact:"Complex rules may impact request processing speed.",docsUrl:`${i.DOCS_BASE_URL}/migration/rule-optimization`},action_differences:{category:"security_consideration",severity:"warning",explanation:"Security actions (block, challenge, etc.) may behave differently between providers in terms of user experience and effectiveness.",suggestion:"Test security actions thoroughly and adjust based on provider capabilities.",alternativeApproach:"Use the most appropriate equivalent action available in the target provider.",impact:"Security effectiveness and user experience may differ from the original configuration.",docsUrl:`${i.DOCS_BASE_URL}/migration/security-actions`},challenge_types:{category:"security_consideration",severity:"info",explanation:"Challenge types (CAPTCHA, JavaScript, etc.) vary between providers and may affect user experience.",suggestion:"Choose challenge types that balance security and user experience for your use case.",alternativeApproach:"Use the provider's recommended challenge type for your security requirements.",impact:"User experience during security challenges may vary.",docsUrl:`${i.DOCS_BASE_URL}/migration/challenges`},version_compatibility:{category:"compatibility_issue",severity:"warning",explanation:"Some features may only be available in specific provider plan tiers or API versions.",suggestion:"Verify feature availability in your target provider plan.",alternativeApproach:"Use alternative features available in your plan tier.",impact:"Some rules may not work as expected if required features are unavailable.",docsUrl:`${i.DOCS_BASE_URL}/migration/compatibility`},plan_limitations:{category:"compatibility_issue",severity:"critical",explanation:"Your current plan may not support all features being translated.",suggestion:"Upgrade your plan or modify rules to use available features.",alternativeApproach:"Implement equivalent functionality using features available in your current plan.",impact:"Rules may be rejected or ignored if they use unavailable features.",docsUrl:`${i.DOCS_BASE_URL}/migration/plan-limits`}};static createWarning(e,t,o,n,s){let a=this.WARNING_CONFIGS[e];return a?{rule:t,field:o,category:a.category,message:n||`${e.replace(/_/g," ")} translation issue`,explanation:a.explanation,severity:a.severity,suggestion:s||a.suggestion,alternativeApproach:a.alternativeApproach,impact:a.impact,docsUrl:a.docsUrl}:{rule:t,field:o,category:"compatibility_issue",message:n||`Unknown translation issue: ${e}`,explanation:"This translation scenario is not fully documented.",severity:"warning",suggestion:s||"Review the translated configuration manually and test thoroughly.",docsUrl:`${this.DOCS_BASE_URL}/migration/troubleshooting`}}static createUnsupportedFeatureWarning(e,t,o,n,s){return{rule:n,field:s,category:"feature_unsupported",message:`${e} is not supported in ${o}`,explanation:`The ${e} feature from ${t} cannot be directly translated to ${o} due to platform differences.`,severity:"critical",suggestion:`Remove or replace ${e} with equivalent functionality supported by ${o}.`,alternativeApproach:`Check ${o} documentation for similar features or use custom rules to achieve equivalent functionality.`,impact:"This rule may not work as expected or may be ignored entirely.",docsUrl:`${this.DOCS_BASE_URL}/migration/unsupported-features`}}static createLossyConversionWarning(e,t,o,n){return{rule:o,field:n,category:"lossy_conversion",message:`${e} translation may be lossy`,explanation:`The ${e} configuration cannot be perfectly translated: ${t}`,severity:"warning",suggestion:"Review the translated configuration and test thoroughly to ensure it behaves as expected.",alternativeApproach:"Consider simplifying the configuration or using more portable alternatives.",impact:"The translated rule may behave differently than the original.",docsUrl:`${this.DOCS_BASE_URL}/migration/lossy-conversions`}}static createSyntaxLimitationWarning(e,t,o,n){return{rule:o,field:n,category:"syntax_limitation",message:`${e} has syntax limitations`,explanation:`The ${e} syntax has been modified due to provider limitations: ${t}`,severity:"warning",suggestion:"Verify the translated syntax works correctly in the target provider.",alternativeApproach:"Use simpler syntax or alternative approaches that are more widely supported.",impact:"The rule may not match traffic as precisely as intended.",docsUrl:`${this.DOCS_BASE_URL}/migration/syntax-limitations`}}static createPerformanceWarning(e,t,o,n){return{rule:o,field:n,category:"performance_impact",message:`${e} may impact performance`,explanation:`The ${e} configuration may have performance implications: ${t}`,severity:"info",suggestion:"Monitor performance after deployment and optimize if necessary.",alternativeApproach:"Consider using more efficient alternatives or breaking complex rules into simpler ones.",impact:"Request processing may be slower than expected.",docsUrl:`${this.DOCS_BASE_URL}/migration/performance`}}static formatWarning(e){let o={critical:"\u{1F6A8}",warning:"\u26A0\uFE0F",info:"\u2139\uFE0F"}[e.severity],n=e.rule?` (Rule: ${e.rule}${e.field?`, Field: ${e.field}`:""})`:"",s=`${o} ${e.severity.toUpperCase()}: ${e.message}${n}
|
|
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}
|
|
@@ -12,17 +12,17 @@ If this is intended, re-run with --allow-deletions. Run "doorman diff" first if
|
|
|
12
12
|
\u{1F4BE} Backup Recommended: ${u.reason}`),u.instructions.forEach(I=>{r.info(` \u2022 ${I}`)}));let p=this.getRollbackGuidance(t);p.available&&(r.info(`
|
|
13
13
|
\u{1F504} Rollback Available: ${p.method}`),p.timeWindow&&r.info(` Time Window: ${p.timeWindow}`));let g=this.getConfirmationMessage(s,t);return await w(g,{type:"confirm"})?(r.info("\u2705 Operation confirmed by user"),!0):(r.info("Operation cancelled by user"),!1)}static async performDryRunValidation(e,t,o){r.info(`\u{1F50D} Performing dry-run validation for ${t}...`);let n=[],s=[],a={rulesToAdd:[],rulesToUpdate:[],rulesToDelete:[],ipsToAdd:[],ipsToUpdate:[],ipsToDelete:[],hasChanges:!1};try{this.validateConfigurationStructure(e,n),a=await o(e),this.validateChanges(a,s),this.checkForPotentialIssues(e,a,s);let l=n.length===0;return l?r.info("\u2705 Dry-run validation passed"):(r.warn(`\u26A0\uFE0F Dry-run validation found ${n.length} issues:`),n.forEach(c=>r.warn(` \u2022 ${c}`))),s.length>0&&(r.warn(`\u26A0\uFE0F Dry-run validation found ${s.length} warning(s):`),s.forEach(c=>r.warn(` \u2022 ${c}`))),{valid:l,changes:a,issues:n,warnings:s}}catch(l){let c=`Dry-run validation failed: ${l instanceof Error?l.message:String(l)}`;return n.push(c),r.error(c),{valid:!1,changes:a,issues:n,warnings:s}}}static assessOperationRisk(e,t){let o=t.rules.length,n=t.ips?.length||0,s=(e.rulesToDelete?.length||0)+(e.ipsToDelete?.length||0),a=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+s;return s===o&&o>0||s>0&&s/Math.max(o+n,1)>.5||a>50||t.rules.some(c=>c.action.type==="deny"&&c.conditions.some(d=>d.field==="path"&&(d.value==="/"||d.value==="*")))?"high":s>0||a>10||e.rulesToUpdate&&e.rulesToUpdate.length>0?"medium":"low"}static getBackupRecommendation(e,t){return{"sync rules":{recommended:t!=="low",reason:"Rule synchronization can overwrite existing firewall configuration",instructions:['Run "doorman download" to backup current Cloudflare rules',"Save the downloaded configuration file with a timestamp","Consider using version control for configuration files"]},"delete ruleset":{recommended:!0,reason:"Ruleset deletion is irreversible and removes all associated rules",instructions:['Export current ruleset with "doorman export"',"Document the ruleset ID and configuration","Ensure you have the original configuration files"]},"update rules":{recommended:t==="high",reason:"Rule updates can affect traffic flow and security posture",instructions:["Download current configuration as backup","Test changes in a staging environment if possible","Have rollback plan ready"]},"clear all rules":{recommended:!0,reason:"Clearing all rules removes all firewall protection",instructions:['Export complete configuration with "doorman export"',"Save configuration to version control","Document business justification for clearing rules"]}}[e]||{recommended:t!=="low",reason:"Operation may modify existing configuration",instructions:["Download current configuration as backup","Document the changes being made"]}}static getRollbackGuidance(e){return{"sync rules":{available:!0,method:"Restore from backup configuration",instructions:['Use "doorman sync" with your backup configuration file',"Or manually restore rules in Cloudflare dashboard","Check that all rules are functioning as expected"],timeWindow:"No time limit - can rollback anytime"},"delete ruleset":{available:!1,method:"Recreation required",instructions:["Deleted rulesets cannot be restored","Must recreate ruleset and rules from backup",'Use "doorman sync" with backup configuration']},"update rules":{available:!0,method:"Restore previous rule version",instructions:["Sync with previous configuration version","Or use Cloudflare dashboard to revert changes","Verify rule functionality after rollback"],timeWindow:"Immediate - no time restrictions"},"clear all rules":{available:!0,method:"Restore from backup",instructions:["Sync with backup configuration file","Verify all rules are restored correctly","Test firewall functionality"],timeWindow:"No time limit"}}[e]||{available:!0,method:"Restore from backup",instructions:["Use backup configuration to restore previous state","Verify changes are reverted correctly"]}}static formatRiskLevel(e){switch(e){case"low":return bt.default.green("LOW");case"medium":return bt.default.yellow("MEDIUM");case"high":return bt.default.red("HIGH");default:return String(e).toUpperCase()}}static displayChangeSummary(e){r.info(`
|
|
14
14
|
\u{1F4CA} Change Summary:`),e.rulesToAdd?.length&&r.info(` \u2022 Rules to add: ${e.rulesToAdd.length}`),e.rulesToUpdate?.length&&r.info(` \u2022 Rules to update: ${e.rulesToUpdate.length}`),e.rulesToDelete?.length&&r.info(` \u2022 Rules to delete: ${e.rulesToDelete.length}`),e.ipsToAdd?.length&&r.info(` \u2022 IPs to add: ${e.ipsToAdd.length}`),e.ipsToUpdate?.length&&r.info(` \u2022 IPs to update: ${e.ipsToUpdate.length}`),e.ipsToDelete?.length&&r.info(` \u2022 IPs to delete: ${e.ipsToDelete.length}`),e.hasChanges||r.info(" \u2022 No changes detected")}static displayRiskWarnings(e,t){let o={low:["This operation has minimal risk of disrupting service"],medium:["This operation may temporarily affect traffic filtering","Monitor your application after the change"],high:["\u26A0\uFE0F This operation can significantly impact security and traffic flow","\u26A0\uFE0F Ensure you have tested the configuration in a safe environment","\u26A0\uFE0F Have a rollback plan ready before proceeding"]},n={"clear all rules":["\u{1F6A8} This will remove ALL firewall protection","\u{1F6A8} Your application will be unprotected until new rules are added"],"delete ruleset":["\u{1F6A8} This action is IRREVERSIBLE","\u{1F6A8} All rules in the ruleset will be permanently deleted"]};r.info(`
|
|
15
|
-
\u26A0\uFE0F Warnings:`),o[e]?.forEach(s=>{r.warn(` ${s}`)}),n[t]?.forEach(s=>{r.warn(` ${s}`)})}static getConfirmationMessage(e,t){let o=`Do you want to proceed with ${t}?`;switch(e){case"high":return`${o} (Type 'yes' to confirm high-risk operation)`;case"medium":return`${o} (Proceed with caution)`;default:return o}}static validateConfigurationStructure(e,t){if(!e){t.push("Configuration is null or undefined");return}e.version||t.push("Configuration missing version field"),e.provider||t.push("Configuration missing provider field"),Array.isArray(e.rules)||t.push("Configuration rules field is not an array"),e.ips&&!Array.isArray(e.ips)&&t.push("Configuration ips field is not an array")}static validateChanges(e,t){let o=(e.rulesToDelete?.length||0)+(e.ipsToDelete?.length||0),n=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+o;if(o>0&&n>0){let s=o/n;s>.5&&t.push(`High deletion ratio detected: ${Math.round(s*100)}% of changes are deletions`)}n>100&&t.push(`Large number of changes detected: ${n} total changes`)}static checkForPotentialIssues(e,t,o){t.rulesToDelete?.length===e.rules.length&&e.rules.length>0&&o.push("All existing rules will be deleted - this removes all firewall protection");let n=e.rules.filter(l=>l.action.type==="deny"&&l.conditions.some(c=>c.field==="path"&&(c.value==="/"||c.value==="*")));n.length>0&&o.push(`Found ${n.length} rules that may block all traffic`),e.ips&&e.ips.length>1e3&&o.push(`Large IP list detected: ${e.ips.length} IPs may impact performance`);let s=e.rules.map(l=>l.name),a=s.filter((l,c)=>s.indexOf(l)!==c);a.length>0&&o.push(`Duplicate rule names found: ${[...new Set(a)].join(", ")}`)}}});var fo={};M(fo,{promptForCredentials:()=>ar});async function ar(i){let e=i.token||process.env.VERCEL_TOKEN||await at("What is your Vercel API Auth Token? (https://vercel.com/guides/how-do-i-use-a-vercel-api-access-token#creating-an-access-token) "),o=i.teamId||process.env.VERCEL_TEAM_ID||await w("What is your Vercel Team ID? Leave blank to use your Vercel default team (every account, including Hobby, is a team). Only needed if you belong to more than one team and want to target a non-default one. (See https://vercel.com/docs/accounts#find-your-team-id)",{type:"text"})||void 0,n=i.projectId||process.env.VERCEL_PROJECT_ID||await w("What is your Vercel Project ID? (See https://vercel.com/docs/projects/project-configuration/general-settings#project-id)",{type:"text"});return{token:e,teamId:o,projectId:n}}var go=qe(()=>{"use strict";pe();zt()});var Vo=require("dotenv"),Bo=S(require("yargs"));var jt={};M(jt,{builder:()=>pn,command:()=>dn,desc:()=>un,generateRuleId:()=>Wt,handler:()=>wn});var U=S(require("chalk")),Bi=require("consola");T();var C=require("zod"),mt=C.z.number().int().positive().optional(),Go=C.z.string().ip().or(C.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),Ri=C.z.string().optional(),Ko=C.z.enum(["eq","pre","suf","inc","sub","re","ex","nex"]),Ho=C.z.enum(["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"]),Zo=C.z.object({op:Ko,neg:C.z.boolean().optional(),type:Ho,value:C.z.union([C.z.string(),C.z.array(C.z.string()),C.z.array(C.z.number())]).optional(),key:C.z.string().optional()}).refine(i=>{switch(i.type){case"ip_address":case"method":case"environment":case"protocol":return i.op==="eq"||i.op==="inc";default:return!0}},"Invalid operator for the given condition type").refine(i=>{let e=["header","cookie"];return!(e.includes(i.type)&&!i.key||e.includes(i.type)&&i.op!=="ex"&&i.op!=="nex"&&!i.value)},"Missing key from condition").refine(i=>!(["ex","nex"].includes(i.op)&&i.neg),"Negation is not supported for the given operator").refine(i=>!(i.op==="inc"&&!Array.isArray(i.value)),"When using `inc` operator, value must be an array"),_t=C.z.object({conditions:C.z.array(Zo).min(1,"Condition group must have at least one condition")}),Yo=C.z.string().regex(/^\d+[smhd]$|^permanent$/),St=C.z.object({requests:C.z.number().positive().int().refine(i=>i>0,"requests must be positive"),window:C.z.string().regex(/^\d+[smhd]$/).refine(i=>parseInt(i)>0,"window duration must be positive")}),Jo=C.z.object({location:C.z.string(),permanent:C.z.boolean().optional()}),Qo=C.z.enum(["log","deny","challenge","bypass","rate_limit","redirect"]),Xo=C.z.object({action:Qo,rateLimit:St.nullable().optional(),redirect:Jo.nullable().optional(),actionDuration:Yo.nullable().optional()}),en=C.z.object({mitigate:Xo}),Lt=C.z.object({id:Ri,name:C.z.string(),description:C.z.string().optional(),conditionGroup:C.z.array(_t),action:en,active:C.z.boolean()});var Ut=C.z.object({id:Ri,ip:Go,hostname:C.z.string().optional(),notes:C.z.string().optional(),action:C.z.literal("deny")}),tn=C.z.object({projectId:C.z.string().optional(),teamId:C.z.string().optional()}),Ae=tn.extend({rules:C.z.array(Lt),ips:C.z.array(Ut).optional(),version:C.z.number().optional(),updatedAt:C.z.string().optional()});pe();var ne=require("fs"),xi=require("crypto"),Oi=require("path");T();var Li=require("net"),Ui=S(require("ajv"));var vi="https://doorman.griffen.codes/schema.json",bi={$schema:"http://json-schema.org/draft-07/schema#",title:"Doorman Config",description:"Schema for doorman project configuration files",$ref:"#/definitions/FirewallConfig",definitions:{FirewallConfig:{type:"object",properties:{projectId:{type:"string"},teamId:{type:"string"},$schema:{type:"string"},version:{type:"number"},firewallEnabled:{type:"boolean"},rules:{type:"array",items:{$ref:"#/definitions/CustomRule"}},ips:{type:"array",items:{$ref:"#/definitions/IPBlockingRule"}},updatedAt:{type:"string"}},required:["rules"],additionalProperties:!1,description:"The main configuration type for Doorman"},CustomRule:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},conditionGroup:{type:"array",items:{$ref:"#/definitions/ConditionGroup"}},action:{$ref:"#/definitions/RuleAction"},active:{type:"boolean"}},required:["name","conditionGroup","action","active"],additionalProperties:!1,description:"Rule Types"},ConditionGroup:{type:"object",properties:{conditions:{type:"array",items:{$ref:"#/definitions/RuleCondition"}}},required:["conditions"],additionalProperties:!1},RuleCondition:{type:"object",properties:{op:{$ref:"#/definitions/RuleOperator"},neg:{type:"boolean"},type:{$ref:"#/definitions/RuleType"},key:{type:"string"},value:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{type:"string"}},{type:"array",items:{type:"number"}}]}},required:["op","type"],additionalProperties:!1,description:"Rule Condition Types"},RuleOperator:{type:"string",enum:["eq","pre","suf","inc","sub","re","ex","nex"]},RuleType:{type:"string",enum:["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"]},RuleAction:{type:"object",properties:{mitigate:{$ref:"#/definitions/MitigationAction"}},required:["mitigate"],additionalProperties:!1},MitigationAction:{type:"object",properties:{action:{$ref:"#/definitions/ActionType"},rateLimit:{anyOf:[{$ref:"#/definitions/RateLimit"},{type:"null"}]},redirect:{anyOf:[{$ref:"#/definitions/Redirect"},{type:"null"}]},actionDuration:{type:["string","null"]}},required:["action"],additionalProperties:!1},ActionType:{type:"string",enum:["log","deny","challenge","bypass","rate_limit","redirect"],description:"Core Types"},RateLimit:{type:"object",properties:{requests:{type:"number"},window:{type:"string"}},required:["requests","window"],additionalProperties:!1,description:"Action Types"},Redirect:{type:"object",properties:{location:{type:"string"},permanent:{type:"boolean"}},required:["location"],additionalProperties:!1},IPBlockingRule:{type:"object",properties:{id:{type:"string"},ip:{type:"string"},hostname:{type:"string"},notes:{type:"string"},action:{type:"string",const:"deny"}},required:["ip","action"],additionalProperties:!1}}};var A=require("zod");var E=require("zod");var re=["vercel","cloudflare","fastly"];var Dt=E.z.string().optional(),ze=E.z.string().ip().or(E.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),ht=E.z.string().datetime().or(E.z.string().optional()),Ei=E.z.enum(["log","deny","challenge","bypass","rate_limit","redirect","allow","block"]),Ti=E.z.enum(["eq","ne","contains","not_contains","starts_with","ends_with","matches","in","not_in","gt","ge","lt","le","exists","not_exists"]),Ai=E.z.enum(["ip","country","region","city","asn","path","host","method","header","query","cookie","user_agent","referer","scheme","port"]),Ds=E.z.string().regex(/^\d+[smhd]$|^permanent$/),Pi=E.z.object({requests:E.z.number().positive().int(),window:E.z.string().regex(/^\d+[smhd]$/),characteristics:E.z.array(E.z.string()).optional()}),$i=E.z.object({location:E.z.string().refine(i=>i.startsWith("/")||E.z.string().url().safeParse(i).success,'location must be an absolute URL or a path starting with "/"'),statusCode:E.z.number().int().min(300).max(399).optional(),permanent:E.z.boolean().optional(),preserveQueryString:E.z.boolean().optional()}),xt=E.z.object({version:E.z.number().int().positive().optional(),updatedAt:ht,createdAt:ht,lastSyncedAt:ht,migratedFrom:E.z.string().optional(),migratedAt:ht}),on=E.z.enum(re),ki=E.z.object({vercel:E.z.object({projectId:E.z.string().optional(),teamId:E.z.string().optional()}).optional(),cloudflare:E.z.object({zoneId:E.z.string().optional(),accountId:E.z.string().optional()}).optional(),fastly:E.z.object({workspaceId:E.z.string().optional()}).optional()}),_i=E.z.object({$schema:E.z.string().url().optional(),version:E.z.string().optional(),provider:on.optional(),metadata:xt.optional()});var nn=A.z.object({field:Ai.or(A.z.string()),operator:Ti,value:A.z.union([A.z.string(),A.z.number(),A.z.array(A.z.string()),A.z.array(A.z.number())]).optional(),negated:A.z.boolean().optional(),key:A.z.string().optional()}).refine(i=>i.operator==="exists"||i.operator==="not_exists"||i.value!==void 0,{message:'value is required unless operator is "exists" or "not_exists"',path:["value"]}),rn=A.z.object({type:Ei,rateLimit:Pi.optional(),redirect:$i.optional(),response:A.z.object({statusCode:A.z.number().int().min(100).max(599).optional(),content:A.z.string().optional(),contentType:A.z.string().optional()}).optional(),duration:A.z.string().optional()}),sn=A.z.object({id:Dt,name:A.z.string().min(1,"Rule name is required"),description:A.z.string().optional(),enabled:A.z.boolean(),conditions:A.z.array(nn).min(1,"At least one condition is required"),conditionLogic:A.z.enum(["AND","OR"]).optional().default("AND"),action:rn,priority:A.z.number().int().optional().describe("Rule evaluation order. Lower numbers are evaluated first. Rules without a priority keep their config order and run after all prioritised rules. Fully honoured on Cloudflare; best-effort on Vercel, which cannot reposition rules that already exist remotely."),categories:A.z.array(A.z.string()).optional()}),an=A.z.object({id:Dt,ip:ze,hostname:A.z.string().optional(),notes:A.z.string().optional(),action:A.z.enum(["deny","allow"])}),Le=_i.extend({providers:ki.optional(),rules:A.z.array(sn),ips:A.z.array(an).optional(),metadata:xt.optional()}),Si=i=>{let e=Le.safeParse(i);if(!e.success)throw new Error(`Invalid unified configuration: ${e.error.message}`);if(e.data.provider&&!e.data.providers?.[e.data.provider])throw new Error(`Provider '${e.data.provider}' specified but no configuration found in providers section`);return e.data};function we(i){if(!i||typeof i!="object")return!1;let e=i;return typeof e.provider=="string"||typeof e.providers=="object"&&e.providers!==null}var oe=S(require("chalk")),Ie=class{static formatValidationError(e){let t=e.instancePath||"/",o=oe.default.cyan(t);switch(e.keyword){case"type":return`${o}: Expected ${oe.default.green(e.schema)}, got ${oe.default.red(typeof e.data)}`;case"enum":{let n=e.params.allowedValues;return`${o}: Value must be one of: ${oe.default.green(n.join(", "))}`}case"required":{let n=e.params;return`${o}: Missing required property ${oe.default.yellow(n.missingProperty)}`}case"additionalProperties":{let n=e.params;return`${o}: Unknown property ${oe.default.red(n.additionalProperty)}`}default:return`${o}: ${e.message}`}}static formatCustomError(e,t){return`${oe.default.cyan(e)}: ${t}`}static wrapErrorBlock(e){let t=oe.default.red.bold("Validation Errors:"),o=e.map(n=>` ${n}`).join(`
|
|
15
|
+
\u26A0\uFE0F Warnings:`),o[e]?.forEach(s=>{r.warn(` ${s}`)}),n[t]?.forEach(s=>{r.warn(` ${s}`)})}static getConfirmationMessage(e,t){let o=`Do you want to proceed with ${t}?`;switch(e){case"high":return`${o} (Type 'yes' to confirm high-risk operation)`;case"medium":return`${o} (Proceed with caution)`;default:return o}}static validateConfigurationStructure(e,t){if(!e){t.push("Configuration is null or undefined");return}e.version||t.push("Configuration missing version field"),e.provider||t.push("Configuration missing provider field"),Array.isArray(e.rules)||t.push("Configuration rules field is not an array"),e.ips&&!Array.isArray(e.ips)&&t.push("Configuration ips field is not an array")}static validateChanges(e,t){let o=(e.rulesToDelete?.length||0)+(e.ipsToDelete?.length||0),n=(e.rulesToAdd?.length||0)+(e.rulesToUpdate?.length||0)+(e.ipsToAdd?.length||0)+(e.ipsToUpdate?.length||0)+o;if(o>0&&n>0){let s=o/n;s>.5&&t.push(`High deletion ratio detected: ${Math.round(s*100)}% of changes are deletions`)}n>100&&t.push(`Large number of changes detected: ${n} total changes`)}static checkForPotentialIssues(e,t,o){t.rulesToDelete?.length===e.rules.length&&e.rules.length>0&&o.push("All existing rules will be deleted - this removes all firewall protection");let n=e.rules.filter(l=>l.action.type==="deny"&&l.conditions.some(c=>c.field==="path"&&(c.value==="/"||c.value==="*")));n.length>0&&o.push(`Found ${n.length} rules that may block all traffic`),e.ips&&e.ips.length>1e3&&o.push(`Large IP list detected: ${e.ips.length} IPs may impact performance`);let s=e.rules.map(l=>l.name),a=s.filter((l,c)=>s.indexOf(l)!==c);a.length>0&&o.push(`Duplicate rule names found: ${[...new Set(a)].join(", ")}`)}}});var fo={};M(fo,{promptForCredentials:()=>ar});async function ar(i){let e=i.token||process.env.VERCEL_TOKEN||await at("What is your Vercel API Auth Token? (https://vercel.com/guides/how-do-i-use-a-vercel-api-access-token#creating-an-access-token) "),o=i.teamId||process.env.VERCEL_TEAM_ID||await w("What is your Vercel Team ID? Leave blank to use your Vercel default team (every account, including Hobby, is a team). Only needed if you belong to more than one team and want to target a non-default one. (See https://vercel.com/docs/accounts#find-your-team-id)",{type:"text"})||void 0,n=i.projectId||process.env.VERCEL_PROJECT_ID||await w("What is your Vercel Project ID? (See https://vercel.com/docs/projects/project-configuration/general-settings#project-id)",{type:"text"});return{token:e,teamId:o,projectId:n}}var go=qe(()=>{"use strict";pe();zt()});var Vo=require("dotenv"),Bo=S(require("yargs"));var jt={};M(jt,{builder:()=>pn,command:()=>dn,desc:()=>un,generateRuleId:()=>Wt,handler:()=>wn});var U=S(require("chalk")),Bi=require("consola");T();var v=require("zod"),mt=v.z.number().int().positive().optional(),Go=v.z.string().ip().or(v.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),Ri=v.z.string().optional(),Ko=v.z.enum(["eq","pre","suf","inc","sub","re","ex","nex"]),Ho=v.z.enum(["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"]),Zo=v.z.object({op:Ko,neg:v.z.boolean().optional(),type:Ho,value:v.z.union([v.z.string(),v.z.array(v.z.string()),v.z.array(v.z.number())]).optional(),key:v.z.string().optional()}).refine(i=>{switch(i.type){case"ip_address":case"method":case"environment":case"protocol":return i.op==="eq"||i.op==="inc";default:return!0}},"Invalid operator for the given condition type").refine(i=>{let e=["header","cookie"];return!(e.includes(i.type)&&!i.key||e.includes(i.type)&&i.op!=="ex"&&i.op!=="nex"&&!i.value)},"Missing key from condition").refine(i=>!(["ex","nex"].includes(i.op)&&i.neg),"Negation is not supported for the given operator").refine(i=>!(i.op==="inc"&&!Array.isArray(i.value)),"When using `inc` operator, value must be an array"),_t=v.z.object({conditions:v.z.array(Zo).min(1,"Condition group must have at least one condition")}),Yo=v.z.string().regex(/^\d+[smhd]$|^permanent$/),St=v.z.object({requests:v.z.number().positive().int().refine(i=>i>0,"requests must be positive"),window:v.z.string().regex(/^\d+[smhd]$/).refine(i=>parseInt(i)>0,"window duration must be positive")}),Jo=v.z.object({location:v.z.string(),permanent:v.z.boolean().optional()}),Qo=v.z.enum(["log","deny","challenge","bypass","rate_limit","redirect"]),Xo=v.z.object({action:Qo,rateLimit:St.nullable().optional(),redirect:Jo.nullable().optional(),actionDuration:Yo.nullable().optional()}),en=v.z.object({mitigate:Xo}),Lt=v.z.object({id:Ri,name:v.z.string(),description:v.z.string().optional(),conditionGroup:v.z.array(_t),action:en,active:v.z.boolean()});var Ut=v.z.object({id:Ri,ip:Go,hostname:v.z.string().optional(),notes:v.z.string().optional(),action:v.z.literal("deny")}),tn=v.z.object({projectId:v.z.string().optional(),teamId:v.z.string().optional()}),Ae=tn.extend({rules:v.z.array(Lt),ips:v.z.array(Ut).optional(),version:v.z.number().optional(),updatedAt:v.z.string().optional()});pe();var ne=require("fs"),xi=require("crypto"),Oi=require("path");T();var Li=require("net"),Ui=S(require("ajv"));var Ci="https://doorman.griffen.codes/schema.json",bi={$schema:"http://json-schema.org/draft-07/schema#",title:"Doorman Config",description:"Schema for doorman project configuration files",$ref:"#/definitions/FirewallConfig",definitions:{FirewallConfig:{type:"object",properties:{projectId:{type:"string"},teamId:{type:"string"},$schema:{type:"string"},version:{type:"number"},firewallEnabled:{type:"boolean"},rules:{type:"array",items:{$ref:"#/definitions/CustomRule"}},ips:{type:"array",items:{$ref:"#/definitions/IPBlockingRule"}},updatedAt:{type:"string"}},required:["rules"],additionalProperties:!1,description:"The main configuration type for Doorman"},CustomRule:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},conditionGroup:{type:"array",items:{$ref:"#/definitions/ConditionGroup"}},action:{$ref:"#/definitions/RuleAction"},active:{type:"boolean"}},required:["name","conditionGroup","action","active"],additionalProperties:!1,description:"Rule Types"},ConditionGroup:{type:"object",properties:{conditions:{type:"array",items:{$ref:"#/definitions/RuleCondition"}}},required:["conditions"],additionalProperties:!1},RuleCondition:{type:"object",properties:{op:{$ref:"#/definitions/RuleOperator"},neg:{type:"boolean"},type:{$ref:"#/definitions/RuleType"},key:{type:"string"},value:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{type:"string"}},{type:"array",items:{type:"number"}}]}},required:["op","type"],additionalProperties:!1,description:"Rule Condition Types"},RuleOperator:{type:"string",enum:["eq","pre","suf","inc","sub","re","ex","nex"]},RuleType:{type:"string",enum:["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"]},RuleAction:{type:"object",properties:{mitigate:{$ref:"#/definitions/MitigationAction"}},required:["mitigate"],additionalProperties:!1},MitigationAction:{type:"object",properties:{action:{$ref:"#/definitions/ActionType"},rateLimit:{anyOf:[{$ref:"#/definitions/RateLimit"},{type:"null"}]},redirect:{anyOf:[{$ref:"#/definitions/Redirect"},{type:"null"}]},actionDuration:{type:["string","null"]}},required:["action"],additionalProperties:!1},ActionType:{type:"string",enum:["log","deny","challenge","bypass","rate_limit","redirect"],description:"Core Types"},RateLimit:{type:"object",properties:{requests:{type:"number"},window:{type:"string"}},required:["requests","window"],additionalProperties:!1,description:"Action Types"},Redirect:{type:"object",properties:{location:{type:"string"},permanent:{type:"boolean"}},required:["location"],additionalProperties:!1},IPBlockingRule:{type:"object",properties:{id:{type:"string"},ip:{type:"string"},hostname:{type:"string"},notes:{type:"string"},action:{type:"string",const:"deny"}},required:["ip","action"],additionalProperties:!1}}};var A=require("zod");var E=require("zod");var re=["vercel","cloudflare","fastly"];var Dt=E.z.string().optional(),ze=E.z.string().ip().or(E.z.string().regex(/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/)),ht=E.z.string().datetime().or(E.z.string().optional()),Ei=E.z.enum(["log","deny","challenge","bypass","rate_limit","redirect","allow","block"]),Ti=E.z.enum(["eq","ne","contains","not_contains","starts_with","ends_with","matches","in","not_in","gt","ge","lt","le","exists","not_exists"]),Ai=E.z.enum(["ip","country","region","city","asn","path","host","method","header","query","cookie","user_agent","referer","scheme","port"]),Ds=E.z.string().regex(/^\d+[smhd]$|^permanent$/),Pi=E.z.object({requests:E.z.number().positive().int(),window:E.z.string().regex(/^\d+[smhd]$/),characteristics:E.z.array(E.z.string()).optional()}),$i=E.z.object({location:E.z.string().refine(i=>i.startsWith("/")||E.z.string().url().safeParse(i).success,'location must be an absolute URL or a path starting with "/"'),statusCode:E.z.number().int().min(300).max(399).optional(),permanent:E.z.boolean().optional(),preserveQueryString:E.z.boolean().optional()}),xt=E.z.object({version:E.z.number().int().positive().optional(),updatedAt:ht,createdAt:ht,lastSyncedAt:ht,migratedFrom:E.z.string().optional(),migratedAt:ht}),on=E.z.enum(re),ki=E.z.object({vercel:E.z.object({projectId:E.z.string().optional(),teamId:E.z.string().optional()}).optional(),cloudflare:E.z.object({zoneId:E.z.string().optional(),accountId:E.z.string().optional()}).optional(),fastly:E.z.object({workspaceId:E.z.string().optional()}).optional()}),_i=E.z.object({$schema:E.z.string().url().optional(),version:E.z.string().optional(),provider:on.optional(),metadata:xt.optional()});var nn=A.z.object({field:Ai.or(A.z.string()),operator:Ti,value:A.z.union([A.z.string(),A.z.number(),A.z.array(A.z.string()),A.z.array(A.z.number())]).optional(),negated:A.z.boolean().optional(),key:A.z.string().optional()}).refine(i=>i.operator==="exists"||i.operator==="not_exists"||i.value!==void 0,{message:'value is required unless operator is "exists" or "not_exists"',path:["value"]}),rn=A.z.object({type:Ei,rateLimit:Pi.optional(),redirect:$i.optional(),response:A.z.object({statusCode:A.z.number().int().min(100).max(599).optional(),content:A.z.string().optional(),contentType:A.z.string().optional()}).optional(),duration:A.z.string().optional()}),sn=A.z.object({id:Dt,name:A.z.string().min(1,"Rule name is required"),description:A.z.string().optional(),enabled:A.z.boolean(),conditions:A.z.array(nn).min(1,"At least one condition is required"),conditionLogic:A.z.enum(["AND","OR"]).optional().default("AND"),action:rn,priority:A.z.number().int().optional().describe("Rule evaluation order. Lower numbers are evaluated first. Rules without a priority keep their config order and run after all prioritised rules. Fully honoured on Cloudflare; best-effort on Vercel, which cannot reposition rules that already exist remotely."),categories:A.z.array(A.z.string()).optional()}),an=A.z.object({id:Dt,ip:ze,hostname:A.z.string().optional(),notes:A.z.string().optional(),action:A.z.enum(["deny","allow"])}),Le=_i.extend({providers:ki.optional(),rules:A.z.array(sn),ips:A.z.array(an).optional(),metadata:xt.optional()}),Si=i=>{let e=Le.safeParse(i);if(!e.success)throw new Error(`Invalid unified configuration: ${e.error.message}`);if(e.data.provider&&!e.data.providers?.[e.data.provider])throw new Error(`Provider '${e.data.provider}' specified but no configuration found in providers section`);return e.data};function we(i){if(!i||typeof i!="object")return!1;let e=i;return typeof e.provider=="string"||typeof e.providers=="object"&&e.providers!==null}var oe=S(require("chalk")),Ie=class{static formatValidationError(e){let t=e.instancePath||"/",o=oe.default.cyan(t);switch(e.keyword){case"type":return`${o}: Expected ${oe.default.green(e.schema)}, got ${oe.default.red(typeof e.data)}`;case"enum":{let n=e.params.allowedValues;return`${o}: Value must be one of: ${oe.default.green(n.join(", "))}`}case"required":{let n=e.params;return`${o}: Missing required property ${oe.default.yellow(n.missingProperty)}`}case"additionalProperties":{let n=e.params;return`${o}: Unknown property ${oe.default.red(n.additionalProperty)}`}default:return`${o}: ${e.message}`}}static formatCustomError(e,t){return`${oe.default.cyan(e)}: ${t}`}static wrapErrorBlock(e){let t=oe.default.red.bold("Validation Errors:"),o=e.map(n=>` ${n}`).join(`
|
|
16
16
|
`);return`${t}
|
|
17
17
|
${o}`}static formatDetailedRuleValidation(e,t){let o=oe.default.cyan(`Rule: ${e}`),n=t.map(s=>{let a=s.passed?oe.default.green("\u2713"):oe.default.red("\u2717"),l=s.passed?oe.default.green(s.name):oe.default.red(s.name);return` ${a} ${l}`}).join(`
|
|
18
18
|
`);return`${o}
|
|
19
|
-
${n}`}};var
|
|
20
|
-
`+(c instanceof Error?c.message:String(c)),null)}let t=this.ajv.compile(this.schema),o=t(e),n=t.errors,s=Ae.safeParse(e),a;s.success||(a=s.error);let l=[];if(o&&s.success){try{this.validateRuleNames(e),this.validateRuleConditionGroup(e),this.validateRuleAction(e)}catch(c){if(c instanceof
|
|
21
|
-
`+x.formatErrors(n,a,l),n,a,l)}validateRuleNames(e){let t=new Set;for(let o of e.rules){if(t.has(o.name))throw new x(`Duplicate rule name found: "${o.name}"`,null);t.add(o.name)}}validateRuleConditionGroup(e){for(let t of e.rules)if(t.conditionGroup)for(let o of t.conditionGroup){if(!o.conditions||o.conditions.length===0)throw new x(`Rule "${t.name}" has an empty condition group`,null);for(let n of o.conditions){if(!n.type||!n.op)throw new x(`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 x(`Rule "${t.name}" has an invalid condition`,null);if(!a&&(n.value===void 0||n.value===null))throw new x(`Rule "${t.name}" has an invalid condition`,null)}else if(n.value===void 0||n.value===null)throw new x(`Rule "${t.name}" has an invalid condition`,null);let l=Array.isArray(n.value)?n.value:n.value!==void 0?[n.value]:[];if(Array.isArray(n.value)&&l.length===0)throw new x(`Rule "${t.name}" has an invalid value in condition`,null);if(n.type==="ip_address"){for(let c of l)if(typeof c!="string"||!this.isValidIP(c))throw new x(`Rule "${t.name}" has an invalid IP address in condition`,null)}if(n.type==="geo_as_number")for(let c of l){let d=typeof c=="number"?c:parseInt(String(c),10);if(!this.isValidASN(String(d)))throw new x(`Rule "${t.name}" has an invalid ASN in condition`,null)}if(n.type==="path"&&(n.op==="eq"||n.op==="pre")){for(let c of l)if(typeof c!="string"||!this.isValidPath(c))throw new x(`Rule "${t.name}" has an invalid path in condition`,null)}}}else throw new x("Either conditionGroup or type+values must be provided",null)}validateRuleAction(e){for(let t of e.rules)if(typeof t.action=="object"&&"mitigate"in t.action){let o=t.action.mitigate;if(o?.rateLimit){if(o.rateLimit.requests<=0)throw new x("Invalid rate limit configuration: requests must be positive",null);if(!o.rateLimit.window.match(/^\d+[smhd]$/))throw new x("Invalid rate limit configuration: invalid window format",null);if(parseInt(o.rateLimit.window)<=0)throw new x("Invalid rate limit configuration: window duration must be positive",null)}if(o?.actionDuration&&!o.actionDuration.match(/^\d+[smhd]$|^permanent$/))throw new x("Invalid action duration format: "+o.actionDuration,null);if(o?.redirect&&!o.redirect.location)throw new x("Invalid redirect configuration: location is required",null)}}isValidIP(e){let t=e.split("/"),o=t[0]??"",n=t[1],s=d=>{let u=d.split(".");return u.length!==4?!1:u.every(p=>{if(!/^\d{1,3}$/.test(p))return!1;let g=parseInt(p,10);return g>=0&&g<=255})},a=d=>(0,Li.isIPv6)(d),l=s(o),c=a(o);if(!l&&!c)return!1;if(n!==void 0){let d=parseInt(n,10);if(Number.isNaN(d)||l&&(d<0||d>32)||c&&(d<0||d>128))return!1}return!0}isValidASN(e){let t=parseInt(e,10);return!isNaN(t)&&t>=1&&t<=4294967295}isValidPath(e){return e.startsWith("/")&&!e.includes(" ")}};var Di=require("fs"),rt=require("path"),Ot=[".doorman.json","vercel-firewall.config.json"],ln=Ot[0],Ue=class{static async findConfig(e){let{findUp:t}=await import("find-up");for(let o of Ot){let n=await t(o,{cwd:e||process.cwd()});if(n)return n}}static async findProjectRoot(e){let t=await this.findConfig(e);return t?(0,rt.dirname)(t):null}static configExists(e){return(0,Di.existsSync)((0,rt.resolve)(e))}static getDefaultConfigPath(){return(0,rt.resolve)(process.cwd(),ln)}static getSupportedFileNames(){return Ot}};async function j(i,e="required"){let t=cn(e),o=i||await Ue.findConfig();if(!o||!(0,ne.existsSync)(o)){if(t==="optional")return r.debug("No config file found, returning empty config"),{};let s=Ue.getDefaultConfigPath();throw new Error(`No config file found. Run \`doorman init\` to create one at ${s}, or use --config to specify a custom path.`)}let n;try{let s=(0,ne.readFileSync)(o,"utf8");n=JSON.parse(s)}catch(s){throw s instanceof SyntaxError?new Error(`Invalid JSON in config file (${o}): ${s.message}`):s}if(t!=="raw")try{Re.getInstance().validateConfig(n)}catch(s){if(t==="lenient")r.warn("Config validation failed:",s);else throw s}return n}async function q(i,e,t={}){let{validate:o=!0,throwOnError:n=!0}=t,s=e||await Ue.findConfig()||Ue.getDefaultConfigPath();if(o)try{Re.getInstance().validateConfig(i)}catch(c){if(r.error("Config validation failed:",c),n)throw c}let a=(0,Oi.dirname)(s);(0,ne.existsSync)(a)||(0,ne.mkdirSync)(a,{recursive:!0});let l=`${s}.${process.pid}.${(0,xi.randomBytes)(4).toString("hex")}.tmp`;try{(0,ne.writeFileSync)(l,JSON.stringify(i,null,2)),(0,ne.renameSync)(l,s)}catch(c){try{(0,ne.existsSync)(l)&&(0,ne.unlinkSync)(l)}catch{}throw c}r.debug(`Config saved to ${s}`)}function cn(i){if(typeof i=="string")return i;let{validate:e=!0,throwOnError:t=!0}=i;return e?t?"required":"lenient":"raw"}var Ft=S(require("chalk")),Fi=require("zod");T();function Y(i,e){i instanceof SyntaxError?r.log(Ie.wrapErrorBlock(["Invalid JSON format in config file:",` ${i.message}`])):i instanceof Fi.ZodError?(r.error(Ft.default.red("Schema validation failed:")),i.errors.forEach(t=>{let o=t.path.join(".");r.error(Ft.default.red(` - ${o}: ${t.message}`))})):i instanceof Error&&i.name==="ValidationError"?r.error(i):i instanceof Error&&i.message.includes("Forbidden")?r.log(Ie.wrapErrorBlock([`Error ${e}:`," Access denied. Check that your token has the correct scope."," If using a team, ensure the token is scoped to that team."])):r.error(Ie.wrapErrorBlock([`Error ${e}:`,` ${i instanceof Error?i.message:String(i)}`])),process.exit(1)}var dn="add [type]",un="Add a new firewall rule to your configuration",pn={type:{type:"string",description:'Rule type: "rule" (default) or "ip"',default:"rule",choices:["rule","ip"]},interactive:{alias:"i",type:"boolean",description:"Guided prompts for rule creation",default:!1},name:{alias:"n",type:"string",description:"Rule name"},description:{type:"string",description:"Rule description"},field:{type:"string",description:"Condition field type (path, method, user_agent, etc.)"},op:{type:"string",description:"Operator (eq, pre, suf, sub, inc, re, ex, nex)"},value:{type:"string",description:"Match value (string or comma-separated for arrays)"},key:{type:"string",description:"Header/query/cookie key (required for header, cookie types)"},neg:{type:"boolean",description:"Negate the condition",default:!1},action:{alias:"a",type:"string",description:"Action type (deny, challenge, rate_limit, redirect, log, bypass)",default:"deny"},active:{type:"boolean",description:"Enable rule immediately",default:!0},requests:{type:"number",description:"Rate limit: max requests"},window:{type:"string",description:'Rate limit: time window (e.g., "60s", "5m")'},duration:{type:"string",description:'Action duration (e.g., "1h", "permanent")'},location:{type:"string",description:"Redirect URL"},permanent:{type:"boolean",description:"Redirect: use 301 instead of 302"},ip:{type:"string",description:"IP address or CIDR for IP blocking rules"},hostname:{type:"string",description:"Hostname for IP blocking rules",default:"*"},notes:{type:"string",description:"Notes for IP blocking rules"},config:{alias:"c",type:"string",description:"Config file path"},dryRun:{alias:"d",type:"boolean",description:"Show what would be added without writing",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Nt=["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"],Vt=["eq","pre","suf","inc","sub","re","ex","nex"],Bt=["log","deny","challenge","bypass","rate_limit","redirect"];function Wt(i){let e=i.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");if(!e)throw new Error("Cannot generate rule ID: name must contain at least one alphanumeric character");return"rule_"+e}function Wi(i,e){return e==="inc"?i.split(",").map(t=>t.trim()):i}async function fn(){let i=await w("Rule name:",{type:"text"});if(!i.trim())throw new Error("Rule name cannot be empty");let e=await w("Description (optional):",{type:"text"}),t=[],o=!0;for(;o;){let u=[],p=!0;for(;p;){let g=await w("Condition type:",{type:"select",options:Nt,initial:"path"}),h=await w("Operator:",{type:"select",options:Vt,initial:"eq"}),I;(g==="header"||g==="cookie"||g==="query")&&(I=await w(`${g} key:`,{type:"text"}));let R;if(h!=="ex"&&h!=="nex"){let W=await w("Value:",{type:"text"});R=Wi(W,h)}let N=h!=="ex"&&h!=="nex"?await w("Negate this condition?",{type:"confirm",initial:!1}):!1,Z={type:g,op:h,...R!==void 0&&{value:R},...I&&{key:I},...N&&{neg:N}};u.push(Z),p=await w("Add another condition to this group? (AND logic)",{type:"confirm",initial:!1})}t.push({conditions:u}),o=await w("Add another condition group? (OR logic)",{type:"confirm",initial:!1})}let n=await w("Action:",{type:"select",options:Bt,initial:"deny"}),s;if(n==="rate_limit"){let u=parseInt(await w("Max requests:",{type:"text",initial:"100"}),10),p=await w('Time window (e.g., "60s", "1m", "1h"):',{type:"text",initial:"60s"});s={requests:u,window:p}}let a;if(n==="redirect"){let u=await w("Redirect URL:",{type:"text"}),p=await w("Permanent redirect (301)?",{type:"confirm",initial:!1});a={location:u,...p&&{permanent:p}}}let l;(n==="deny"||n==="challenge")&&await w("Set action duration? (default: permanent)",{type:"confirm",initial:!1})&&(l=await w('Duration (e.g., "1h", "1d", "permanent"):',{type:"text",initial:"permanent"}));let c=await w("Enable rule immediately?",{type:"confirm",initial:!0});return{id:Wt(i),name:i.trim(),...e.trim()&&{description:e.trim()},conditionGroup:t,action:{mitigate:{action:n,...s&&{rateLimit:s},...a&&{redirect:a},...l&&{actionDuration:l}}},active:c}}function gn(i){if(!i.name)throw new Error("--name is required in inline mode. Use --interactive for guided prompts.");if(!i.field)throw new Error("--field is required in inline mode (e.g., --field path)");if(!i.op)throw new Error("--op is required in inline mode (e.g., --op eq)");let e=i.op;if(!Vt.includes(e))throw new Error(`Invalid operator "${i.op}". Valid operators: ${Vt.join(", ")}`);let t=i.field;if(!Nt.includes(t))throw new Error(`Invalid field type "${i.field}". Valid types: ${Nt.join(", ")}`);let o=i.action||"deny";if(!Bt.includes(o))throw new Error(`Invalid action "${i.action}". Valid actions: ${Bt.join(", ")}`);if(e!=="ex"&&e!=="nex"&&!i.value)throw new Error("--value is required for the given operator");if((t==="header"||t==="cookie"||t==="query")&&!i.key)throw new Error(`--key is required for "${t}" condition type`);if(o==="rate_limit"&&(!i.requests||!i.window))throw new Error("--requests and --window are required when action is rate_limit");if(o==="redirect"&&!i.location)throw new Error("--location is required when action is redirect");let n=i.value?Wi(i.value,e):void 0,s={type:t,op:e,...n!==void 0&&{value:n},...i.key&&{key:i.key},...i.neg&&{neg:!0}};return{id:Wt(i.name),name:i.name.trim(),...i.description&&{description:i.description},conditionGroup:[{conditions:[s]}],action:{mitigate:{action:o,...o==="rate_limit"&&i.requests&&i.window&&{rateLimit:{requests:i.requests,window:i.window}},...o==="redirect"&&i.location&&{redirect:{location:i.location,...i.permanent&&{permanent:!0}}},...i.duration&&{actionDuration:i.duration}}},active:i.active!==!1}}async function mn(){let i=await w("IP address or CIDR (e.g., 192.168.1.100/32):",{type:"text"});if(!i.trim())throw new Error("IP address cannot be empty");let e=await w("Hostname (use * for all):",{type:"text",initial:"*"}),t=await w("Notes (optional):",{type:"text"});return{ip:i.trim(),hostname:e.trim()||"*",...t.trim()&&{notes:t.trim()},action:"deny"}}function hn(i){if(!i.ip)throw new Error("--ip is required for IP blocking rules");return{ip:i.ip.trim(),hostname:i.hostname||"*",...i.notes&&{notes:i.notes},action:"deny"}}function yn(i,e){if(i.rules.map(n=>n.name.toLowerCase()).includes(e.name.toLowerCase()))return`A rule named "${e.name}" already exists`;let o=i.rules.map(n=>n.id).filter(Boolean);return e.id&&o.includes(e.id)?`A rule with ID "${e.id}" already exists`:null}function Ni(i){r.log(""),r.log(U.default.bold(` Rule: ${i.name}`)),i.description&&r.log(U.default.dim(` Description: ${i.description}`)),r.log(U.default.dim(` ID: ${i.id}`));let e=i.conditionGroup.map(n=>n.conditions.map(s=>{let a=s.neg?"NOT ":"",l=s.key?`[${s.key}] `:"",c=Array.isArray(s.value)?s.value.join(", "):s.value||"";return`${a}${s.type} ${l}${s.op} "${c}"`}).join(" AND "));r.log(U.default.dim(` Conditions: ${e.join(" OR ")}`));let t=i.action.mitigate.action,o=[];i.action.mitigate.rateLimit&&o.push(`${i.action.mitigate.rateLimit.requests} req/${i.action.mitigate.rateLimit.window}`),i.action.mitigate.redirect&&o.push(`\u2192 ${i.action.mitigate.redirect.location}`),i.action.mitigate.actionDuration&&o.push(`duration: ${i.action.mitigate.actionDuration}`),r.log(U.default.dim(` Action: ${t}${o.length?` (${o.join(", ")})`:""}`)),r.log(U.default.dim(` Active: ${i.active?"\u2705":"\u274C"}`))}function Vi(i){r.log(""),r.log(U.default.bold(` IP Rule: ${i.ip}`)),r.log(U.default.dim(` Hostname: ${i.hostname}`)),i.notes&&r.log(U.default.dim(` Notes: ${i.notes}`)),r.log(U.default.dim(` Action: ${i.action}`))}var wn=async i=>{try{if(i.debug&&(r.level=Bi.LogLevels.debug),r.debug("Add command arguments:",i),(i.type||"rule")==="ip"){let t=i.interactive?await mn():hn(i),o=Ut.safeParse(t);if(o.success||(r.error(U.default.red("Rule validation failed:")),o.error.errors.forEach(a=>{let l=a.path.join(".");r.error(U.default.red(` - ${l||"ip"}: ${a.message}`))}),process.exit(1)),i.dryRun){r.info(U.default.cyan(`
|
|
19
|
+
${n}`}};var O=class i extends Error{constructor(t,o,n,s=[]){super(t);this.ajvErrors=o;this.zodError=n;this.customErrors=s;this.name="ValidationError"}ajvErrors;zodError;customErrors;static formatErrors(t,o,n=[]){let s=[];return t?.length&&s.push(...t.map(Ie.formatValidationError)),o&&s.push(...o.errors.map(a=>`${a.path.join(".")}: ${a.message}`)),n.length&&s.push(...n),Ie.wrapErrorBlock(s)}getFormattedMessage(){return i.formatErrors(this.ajvErrors,this.zodError,this.customErrors)}},Re=class i{static instance;ajv;schema;constructor(){this.ajv=new Ui.default({allErrors:!0,verbose:!0}),this.schema=bi}static getInstance(){return i.instance||(i.instance=new i),i.instance}validateConfig(e){if(we(e))try{Si(e);return}catch(c){throw new O(`Invalid firewall configuration:
|
|
20
|
+
`+(c instanceof Error?c.message:String(c)),null)}let t=this.ajv.compile(this.schema),o=t(e),n=t.errors,s=Ae.safeParse(e),a;s.success||(a=s.error);let l=[];if(o&&s.success){try{this.validateRuleNames(e),this.validateRuleConditionGroup(e),this.validateRuleAction(e)}catch(c){if(c instanceof O)l.push(c.message,...c.customErrors||[]);else throw c}for(let c of e.rules){if(c.action.mitigate?.rateLimit){let d=St.safeParse(c.action.mitigate.rateLimit);d.success||l.push(...d.error.errors.map(u=>u.message))}if(c.conditionGroup)for(let d of c.conditionGroup){let u=_t.safeParse(d);u.success||l.push(...u.error.errors.map(p=>p.message))}}}if(!o||!s.success||l.length>0)throw new O(`Invalid firewall configuration:
|
|
21
|
+
`+O.formatErrors(n,a,l),n,a,l)}validateRuleNames(e){let t=new Set;for(let o of e.rules){if(t.has(o.name))throw new O(`Duplicate rule name found: "${o.name}"`,null);t.add(o.name)}}validateRuleConditionGroup(e){for(let t of e.rules)if(t.conditionGroup)for(let o of t.conditionGroup){if(!o.conditions||o.conditions.length===0)throw new O(`Rule "${t.name}" has an empty condition group`,null);for(let n of o.conditions){if(!n.type||!n.op)throw new O(`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 O(`Rule "${t.name}" has an invalid condition`,null);if(!a&&(n.value===void 0||n.value===null))throw new O(`Rule "${t.name}" has an invalid condition`,null)}else if(n.value===void 0||n.value===null)throw new O(`Rule "${t.name}" has an invalid condition`,null);let l=Array.isArray(n.value)?n.value:n.value!==void 0?[n.value]:[];if(Array.isArray(n.value)&&l.length===0)throw new O(`Rule "${t.name}" has an invalid value in condition`,null);if(n.type==="ip_address"){for(let c of l)if(typeof c!="string"||!this.isValidIP(c))throw new O(`Rule "${t.name}" has an invalid IP address in condition`,null)}if(n.type==="geo_as_number")for(let c of l){let d=typeof c=="number"?c:parseInt(String(c),10);if(!this.isValidASN(String(d)))throw new O(`Rule "${t.name}" has an invalid ASN in condition`,null)}if(n.type==="path"&&(n.op==="eq"||n.op==="pre")){for(let c of l)if(typeof c!="string"||!this.isValidPath(c))throw new O(`Rule "${t.name}" has an invalid path in condition`,null)}}}else throw new O("Either conditionGroup or type+values must be provided",null)}validateRuleAction(e){for(let t of e.rules)if(typeof t.action=="object"&&"mitigate"in t.action){let o=t.action.mitigate;if(o?.rateLimit){if(o.rateLimit.requests<=0)throw new O("Invalid rate limit configuration: requests must be positive",null);if(!o.rateLimit.window.match(/^\d+[smhd]$/))throw new O("Invalid rate limit configuration: invalid window format",null);if(parseInt(o.rateLimit.window)<=0)throw new O("Invalid rate limit configuration: window duration must be positive",null)}if(o?.actionDuration&&!o.actionDuration.match(/^\d+[smhd]$|^permanent$/))throw new O("Invalid action duration format: "+o.actionDuration,null);if(o?.redirect&&!o.redirect.location)throw new O("Invalid redirect configuration: location is required",null)}}isValidIP(e){let t=e.split("/"),o=t[0]??"",n=t[1],s=d=>{let u=d.split(".");return u.length!==4?!1:u.every(p=>{if(!/^\d{1,3}$/.test(p))return!1;let g=parseInt(p,10);return g>=0&&g<=255})},a=d=>(0,Li.isIPv6)(d),l=s(o),c=a(o);if(!l&&!c)return!1;if(n!==void 0){let d=parseInt(n,10);if(Number.isNaN(d)||l&&(d<0||d>32)||c&&(d<0||d>128))return!1}return!0}isValidASN(e){let t=parseInt(e,10);return!isNaN(t)&&t>=1&&t<=4294967295}isValidPath(e){return e.startsWith("/")&&!e.includes(" ")}};var Di=require("fs"),rt=require("path"),Ot=[".doorman.json","vercel-firewall.config.json"],ln=Ot[0],Ue=class{static async findConfig(e){let{findUp:t}=await import("find-up");for(let o of Ot){let n=await t(o,{cwd:e||process.cwd()});if(n)return n}}static async findProjectRoot(e){let t=await this.findConfig(e);return t?(0,rt.dirname)(t):null}static configExists(e){return(0,Di.existsSync)((0,rt.resolve)(e))}static getDefaultConfigPath(){return(0,rt.resolve)(process.cwd(),ln)}static getSupportedFileNames(){return Ot}};async function j(i,e="required"){let t=cn(e),o=i||await Ue.findConfig();if(!o||!(0,ne.existsSync)(o)){if(t==="optional")return r.debug("No config file found, returning empty config"),{};let s=Ue.getDefaultConfigPath();throw new Error(`No config file found. Run \`doorman init\` to create one at ${s}, or use --config to specify a custom path.`)}let n;try{let s=(0,ne.readFileSync)(o,"utf8");n=JSON.parse(s)}catch(s){throw s instanceof SyntaxError?new Error(`Invalid JSON in config file (${o}): ${s.message}`):s}if(t!=="raw")try{Re.getInstance().validateConfig(n)}catch(s){if(t==="lenient")r.warn("Config validation failed:",s);else throw s}return n}async function q(i,e,t={}){let{validate:o=!0,throwOnError:n=!0}=t,s=e||await Ue.findConfig()||Ue.getDefaultConfigPath();if(o)try{Re.getInstance().validateConfig(i)}catch(c){if(r.error("Config validation failed:",c),n)throw c}let a=(0,Oi.dirname)(s);(0,ne.existsSync)(a)||(0,ne.mkdirSync)(a,{recursive:!0});let l=`${s}.${process.pid}.${(0,xi.randomBytes)(4).toString("hex")}.tmp`;try{(0,ne.writeFileSync)(l,JSON.stringify(i,null,2)),(0,ne.renameSync)(l,s)}catch(c){try{(0,ne.existsSync)(l)&&(0,ne.unlinkSync)(l)}catch{}throw c}r.debug(`Config saved to ${s}`)}function cn(i){if(typeof i=="string")return i;let{validate:e=!0,throwOnError:t=!0}=i;return e?t?"required":"lenient":"raw"}var Ft=S(require("chalk")),Fi=require("zod");T();function Y(i,e){i instanceof SyntaxError?r.log(Ie.wrapErrorBlock(["Invalid JSON format in config file:",` ${i.message}`])):i instanceof Fi.ZodError?(r.error(Ft.default.red("Schema validation failed:")),i.errors.forEach(t=>{let o=t.path.join(".");r.error(Ft.default.red(` - ${o}: ${t.message}`))})):i instanceof Error&&i.name==="ValidationError"?r.error(i):i instanceof Error&&i.message.includes("Forbidden")?r.log(Ie.wrapErrorBlock([`Error ${e}:`," Access denied. Check that your token has the correct scope."," If using a team, ensure the token is scoped to that team."])):r.error(Ie.wrapErrorBlock([`Error ${e}:`,` ${i instanceof Error?i.message:String(i)}`])),process.exit(1)}var dn="add [type]",un="Add a new firewall rule to your configuration",pn={type:{type:"string",description:'Rule type: "rule" (default) or "ip"',default:"rule",choices:["rule","ip"]},interactive:{alias:"i",type:"boolean",description:"Guided prompts for rule creation",default:!1},name:{alias:"n",type:"string",description:"Rule name"},description:{type:"string",description:"Rule description"},field:{type:"string",description:"Condition field type (path, method, user_agent, etc.)"},op:{type:"string",description:"Operator (eq, pre, suf, sub, inc, re, ex, nex)"},value:{type:"string",description:"Match value (string or comma-separated for arrays)"},key:{type:"string",description:"Header/query/cookie key (required for header, cookie types)"},neg:{type:"boolean",description:"Negate the condition",default:!1},action:{alias:"a",type:"string",description:"Action type (deny, challenge, rate_limit, redirect, log, bypass)",default:"deny"},active:{type:"boolean",description:"Enable rule immediately",default:!0},requests:{type:"number",description:"Rate limit: max requests"},window:{type:"string",description:'Rate limit: time window (e.g., "60s", "5m")'},duration:{type:"string",description:'Action duration (e.g., "1h", "permanent")'},location:{type:"string",description:"Redirect URL"},permanent:{type:"boolean",description:"Redirect: use 301 instead of 302"},ip:{type:"string",description:"IP address or CIDR for IP blocking rules"},hostname:{type:"string",description:"Hostname for IP blocking rules",default:"*"},notes:{type:"string",description:"Notes for IP blocking rules"},config:{alias:"c",type:"string",description:"Config file path"},dryRun:{alias:"d",type:"boolean",description:"Show what would be added without writing",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Nt=["host","path","method","header","query","cookie","target_path","ip_address","region","protocol","scheme","environment","user_agent","geo_continent","geo_country","geo_country_region","geo_city","geo_as_number","ja4_digest","ja3_digest","rate_limit_api_id"],Vt=["eq","pre","suf","inc","sub","re","ex","nex"],Bt=["log","deny","challenge","bypass","rate_limit","redirect"];function Wt(i){let e=i.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");if(!e)throw new Error("Cannot generate rule ID: name must contain at least one alphanumeric character");return"rule_"+e}function Wi(i,e){return e==="inc"?i.split(",").map(t=>t.trim()):i}async function fn(){let i=await w("Rule name:",{type:"text"});if(!i.trim())throw new Error("Rule name cannot be empty");let e=await w("Description (optional):",{type:"text"}),t=[],o=!0;for(;o;){let u=[],p=!0;for(;p;){let g=await w("Condition type:",{type:"select",options:Nt,initial:"path"}),h=await w("Operator:",{type:"select",options:Vt,initial:"eq"}),I;(g==="header"||g==="cookie"||g==="query")&&(I=await w(`${g} key:`,{type:"text"}));let R;if(h!=="ex"&&h!=="nex"){let W=await w("Value:",{type:"text"});R=Wi(W,h)}let N=h!=="ex"&&h!=="nex"?await w("Negate this condition?",{type:"confirm",initial:!1}):!1,Z={type:g,op:h,...R!==void 0&&{value:R},...I&&{key:I},...N&&{neg:N}};u.push(Z),p=await w("Add another condition to this group? (AND logic)",{type:"confirm",initial:!1})}t.push({conditions:u}),o=await w("Add another condition group? (OR logic)",{type:"confirm",initial:!1})}let n=await w("Action:",{type:"select",options:Bt,initial:"deny"}),s;if(n==="rate_limit"){let u=parseInt(await w("Max requests:",{type:"text",initial:"100"}),10),p=await w('Time window (e.g., "60s", "1m", "1h"):',{type:"text",initial:"60s"});s={requests:u,window:p}}let a;if(n==="redirect"){let u=await w("Redirect URL:",{type:"text"}),p=await w("Permanent redirect (301)?",{type:"confirm",initial:!1});a={location:u,...p&&{permanent:p}}}let l;(n==="deny"||n==="challenge")&&await w("Set action duration? (default: permanent)",{type:"confirm",initial:!1})&&(l=await w('Duration (e.g., "1h", "1d", "permanent"):',{type:"text",initial:"permanent"}));let c=await w("Enable rule immediately?",{type:"confirm",initial:!0});return{id:Wt(i),name:i.trim(),...e.trim()&&{description:e.trim()},conditionGroup:t,action:{mitigate:{action:n,...s&&{rateLimit:s},...a&&{redirect:a},...l&&{actionDuration:l}}},active:c}}function gn(i){if(!i.name)throw new Error("--name is required in inline mode. Use --interactive for guided prompts.");if(!i.field)throw new Error("--field is required in inline mode (e.g., --field path)");if(!i.op)throw new Error("--op is required in inline mode (e.g., --op eq)");let e=i.op;if(!Vt.includes(e))throw new Error(`Invalid operator "${i.op}". Valid operators: ${Vt.join(", ")}`);let t=i.field;if(!Nt.includes(t))throw new Error(`Invalid field type "${i.field}". Valid types: ${Nt.join(", ")}`);let o=i.action||"deny";if(!Bt.includes(o))throw new Error(`Invalid action "${i.action}". Valid actions: ${Bt.join(", ")}`);if(e!=="ex"&&e!=="nex"&&!i.value)throw new Error("--value is required for the given operator");if((t==="header"||t==="cookie"||t==="query")&&!i.key)throw new Error(`--key is required for "${t}" condition type`);if(o==="rate_limit"&&(!i.requests||!i.window))throw new Error("--requests and --window are required when action is rate_limit");if(o==="redirect"&&!i.location)throw new Error("--location is required when action is redirect");let n=i.value?Wi(i.value,e):void 0,s={type:t,op:e,...n!==void 0&&{value:n},...i.key&&{key:i.key},...i.neg&&{neg:!0}};return{id:Wt(i.name),name:i.name.trim(),...i.description&&{description:i.description},conditionGroup:[{conditions:[s]}],action:{mitigate:{action:o,...o==="rate_limit"&&i.requests&&i.window&&{rateLimit:{requests:i.requests,window:i.window}},...o==="redirect"&&i.location&&{redirect:{location:i.location,...i.permanent&&{permanent:!0}}},...i.duration&&{actionDuration:i.duration}}},active:i.active!==!1}}async function mn(){let i=await w("IP address or CIDR (e.g., 192.168.1.100/32):",{type:"text"});if(!i.trim())throw new Error("IP address cannot be empty");let e=await w("Hostname (use * for all):",{type:"text",initial:"*"}),t=await w("Notes (optional):",{type:"text"});return{ip:i.trim(),hostname:e.trim()||"*",...t.trim()&&{notes:t.trim()},action:"deny"}}function hn(i){if(!i.ip)throw new Error("--ip is required for IP blocking rules");return{ip:i.ip.trim(),hostname:i.hostname||"*",...i.notes&&{notes:i.notes},action:"deny"}}function yn(i,e){if(i.rules.map(n=>n.name.toLowerCase()).includes(e.name.toLowerCase()))return`A rule named "${e.name}" already exists`;let o=i.rules.map(n=>n.id).filter(Boolean);return e.id&&o.includes(e.id)?`A rule with ID "${e.id}" already exists`:null}function Ni(i){r.log(""),r.log(U.default.bold(` Rule: ${i.name}`)),i.description&&r.log(U.default.dim(` Description: ${i.description}`)),r.log(U.default.dim(` ID: ${i.id}`));let e=i.conditionGroup.map(n=>n.conditions.map(s=>{let a=s.neg?"NOT ":"",l=s.key?`[${s.key}] `:"",c=Array.isArray(s.value)?s.value.join(", "):s.value||"";return`${a}${s.type} ${l}${s.op} "${c}"`}).join(" AND "));r.log(U.default.dim(` Conditions: ${e.join(" OR ")}`));let t=i.action.mitigate.action,o=[];i.action.mitigate.rateLimit&&o.push(`${i.action.mitigate.rateLimit.requests} req/${i.action.mitigate.rateLimit.window}`),i.action.mitigate.redirect&&o.push(`\u2192 ${i.action.mitigate.redirect.location}`),i.action.mitigate.actionDuration&&o.push(`duration: ${i.action.mitigate.actionDuration}`),r.log(U.default.dim(` Action: ${t}${o.length?` (${o.join(", ")})`:""}`)),r.log(U.default.dim(` Active: ${i.active?"\u2705":"\u274C"}`))}function Vi(i){r.log(""),r.log(U.default.bold(` IP Rule: ${i.ip}`)),r.log(U.default.dim(` Hostname: ${i.hostname}`)),i.notes&&r.log(U.default.dim(` Notes: ${i.notes}`)),r.log(U.default.dim(` Action: ${i.action}`))}var wn=async i=>{try{if(i.debug&&(r.level=Bi.LogLevels.debug),r.debug("Add command arguments:",i),(i.type||"rule")==="ip"){let t=i.interactive?await mn():hn(i),o=Ut.safeParse(t);if(o.success||(r.error(U.default.red("Rule validation failed:")),o.error.errors.forEach(a=>{let l=a.path.join(".");r.error(U.default.red(` - ${l||"ip"}: ${a.message}`))}),process.exit(1)),i.dryRun){r.info(U.default.cyan(`
|
|
22
22
|
Dry run - The following IP rule would be added:`)),Vi(t),r.log(""),r.log(U.default.dim(JSON.stringify(t,null,2)));return}r.start("Loading configuration...");let n=await j(i.config,"raw"),s={...n,ips:[...n.ips||[],t]};await q(s,i.config),r.success(U.default.green(`\u2714 IP rule "${t.ip}" added to configuration`)),Vi(t)}else{let t=i.interactive?await fn():gn(i),o=Lt.safeParse(t);if(o.success||(r.error(U.default.red("Rule validation failed:")),o.error.errors.forEach(c=>{let d=c.path.join(".")||"rule";r.error(U.default.red(` - ${d}: ${c.message}`))}),process.exit(1)),i.dryRun){r.info(U.default.cyan(`
|
|
23
23
|
Dry run - The following rule would be added:`)),Ni(t),r.log(""),r.log(U.default.dim(JSON.stringify(t,null,2)));return}r.start("Loading configuration...");let n=await j(i.config,"raw"),s=n.rules||[],a=yn({...n,rules:s},t);if(a){if(r.warn(U.default.yellow(`\u26A0\uFE0F ${a}`)),i.ci||!process.stdin.isTTY){r.info(U.default.dim("Skipping \u2014 non-interactive and a conflicting rule already exists. Rule not added."));return}if(!await w("Proceed anyway?",{type:"confirm",initial:!1})){r.info("Cancelled.");return}}let l={...n,rules:[...s,t]};await q(l,i.config),r.success(U.default.green(`\u2714 Rule "${t.name}" added to configuration`)),Ni(t)}r.log(""),r.log(U.default.dim(`Run ${U.default.cyan("doorman sync")} to deploy this rule.`))}catch(e){Y(e,"adding rule")}};var ei={};M(ei,{builder:()=>gr,command:()=>pr,desc:()=>fr,handler:()=>mr});var H=S(require("chalk")),ge=require("fs"),it=require("path"),Io=require("consola");T();pe();var st=require("fs"),qt=require("path");function ji(i=process.cwd()){return(0,st.existsSync)((0,qt.join)(i,".git"))}function qi(i,e=process.cwd()){let t=(0,qt.join)(e,".gitignore");if(!(0,st.existsSync)(t))return!1;let o=i.replace(/^\.\//,"").replace(/^\//,"").replace(/\/$/,""),n;try{n=(0,st.readFileSync)(t,"utf8").split(`
|
|
24
|
-
`)}catch{return!1}return n.some(s=>{let a=s.trim();if(!a||a.startsWith("#"))return!1;let l=a.replace(/^\//,"").replace(/\/$/,"");return l===o||o.startsWith(`${l}/`)})}var J={type:"string",choices:re,description:"Firewall provider (auto-detected)"};var wo=require("consola");T();var ho=S(require("chalk"));T();pe();zt();T();var yt=class{static detect(e){let t=[];if(e&&"provider"in e){let n=e.provider;if(typeof n=="string"&&this.isValidProvider(n))return t.push(`Explicit provider specified in config: ${e.provider}`),{provider:n,confidence:"high",reasons:t};r.warn(`Invalid provider specified in config: ${String(e.provider)}`)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let n=e.providers;if(typeof(n.cloudflare||{}).zoneId=="string")return t.push("Cloudflare zone ID found in config"),{provider:"cloudflare",confidence:"high",reasons:t};if(typeof(n.vercel||{}).projectId=="string")return t.push("Vercel project ID found in config"),{provider:"vercel",confidence:"high",reasons:t};if(typeof(n.fastly||{}).workspaceId=="string")return t.push("Fastly workspace ID found in config"),{provider:"fastly",confidence:"high",reasons:t}}if(e&&"projectId"in e&&typeof e.projectId=="string")return t.push("Legacy Vercel project ID found in config"),{provider:"vercel",confidence:"high",reasons:t};let o=this.detectFromEnvironment();return o.provider?o:(r.debug("Unable to auto-detect provider"),{provider:null,confidence:"low",reasons:["No provider information found in config or environment"]})}static detectFromEnvironment(){let e=[],t=process.env.DOORMAN_PROVIDER;return t&&this.isValidProvider(t)?(e.push(`Provider set via DOORMAN_PROVIDER environment variable: ${t}`),{provider:t,confidence:"high",reasons:e}):process.env.CLOUDFLARE_ZONE_ID&&process.env.CLOUDFLARE_API_TOKEN?(e.push("Cloudflare credentials found in environment variables"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.CLOUDFLARE_ZONE_ID?(e.push("Cloudflare zone ID found in environment"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID&&process.env.VERCEL_TOKEN?(e.push("Vercel credentials found in environment variables"),{provider:"vercel",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID?(e.push("Vercel project ID found in environment"),{provider:"vercel",confidence:"medium",reasons:e}):process.env.FASTLY_WORKSPACE_ID&&process.env.FASTLY_API_TOKEN?(e.push("Fastly credentials found in environment variables"),{provider:"fastly",confidence:"medium",reasons:e}):process.env.FASTLY_WORKSPACE_ID?(e.push("Fastly workspace ID found in environment"),{provider:"fastly",confidence:"medium",reasons:e}):{provider:null,confidence:"low",reasons:["No provider credentials found in environment"]}}static isValidProvider(e){return re.includes(e)}static getProvider(e,t="vercel"){let o=this.detect(e);return o.provider?(r.debug(`Provider detected: ${o.provider} (${o.confidence} confidence)`),o.reasons.length>0&&r.debug(`Detection reasons: ${o.reasons.join(", ")}`),o.provider):(r.debug(`No provider detected, using fallback: ${t}`),t)}static detectAll(e){let t=new Set;if(e&&"provider"in e){let o=e.provider;typeof o=="string"&&this.isValidProvider(o)&&t.add(o)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let o=e.providers;typeof(o.cloudflare||{}).zoneId=="string"&&t.add("cloudflare"),typeof(o.vercel||{}).projectId=="string"&&t.add("vercel"),typeof(o.fastly||{}).workspaceId=="string"&&t.add("fastly")}return e&&"projectId"in e&&typeof e.projectId=="string"&&t.add("vercel"),process.env.CLOUDFLARE_ZONE_ID&&t.add("cloudflare"),process.env.VERCEL_PROJECT_ID&&t.add("vercel"),process.env.FASTLY_WORKSPACE_ID&&t.add("fastly"),Array.from(t)}};var Mt=S(require("chalk"));T();pe();var wt=i=>({$schema:vi,firewallEnabled:!0,rules:[],ips:[],...i});T();var Pe=class{baseUrl;providerName;rateLimitInfo={};constructor(e,t){this.baseUrl=e,this.providerName=t}async makeRequest(e,t={}){let o=`${this.baseUrl}${e}`,{timeout:n=3e4,retries:s=3,retryDelay:a=1e3,...l}=t,c=null,d=null,u=null,p=()=>{u&&(clearTimeout(u),u=null),d&&(d.abort(),d=null)};try{for(let g=0;g<=s;g++)try{d=new AbortController,u=setTimeout(()=>{d&&d.abort()},n);let h=await fetch(o,{...l,headers:{"Content-Type":"application/json",...this.getAuthHeaders(),...l.headers},signal:d.signal});if(u&&(clearTimeout(u),u=null),this.updateRateLimitInfo(h),h.status===429){let R=this.calculateRateLimitWait(g,h);if(g===s)throw new Error(`${this.providerName} API rate limit exceeded after ${s+1} attempt(s) (429 Too Many Requests). Retry after ~${Math.round(R/1e3)}s.`);r.warn(`Rate limit exceeded for ${this.providerName}. Waiting ${R}ms before retry (attempt ${g+1}/${s+1})...`),await this.delay(R);continue}if(!h.ok)throw await this.handleErrorResponse(h);let I;try{let R=await h.text();R.trim()?I=JSON.parse(R):I={}}catch(R){throw r.error(`Failed to parse response from ${o}:`,R),new Error(`Invalid JSON response from ${this.providerName} API: ${R instanceof Error?R.message:String(R)}`)}return this.isLargeResponse(I)&&(r.debug(`Large response detected from ${o}, validating structure...`),this.validateLargeResponse(I)),I}catch(h){if(c=h,u&&(clearTimeout(u),u=null),this.isNonRetryableError(h)||g===s)throw h;let I=a*Math.pow(2,g),R=Math.random()*.1*I,N=Math.min(I+R,3e4);r.debug(`Request failed (attempt ${g+1}/${s+1}). Retrying in ${Math.round(N)}ms...`),r.debug(`Error details: ${h instanceof Error?h.message:String(h)}`),await this.delay(N)}throw c||new Error("Request failed after all retries")}finally{p()}}async get(e,t){return this.makeRequest(e,{...t,method:"GET"})}async post(e,t,o){return this.makeRequest(e,{...o,method:"POST",body:t?JSON.stringify(t):void 0})}async put(e,t,o){return this.makeRequest(e,{...o,method:"PUT",body:t?JSON.stringify(t):void 0})}async patch(e,t,o){return this.makeRequest(e,{...o,method:"PATCH",body:t?JSON.stringify(t):void 0})}async delete(e,t){return this.makeRequest(e,{...t,method:"DELETE"})}updateRateLimitInfo(e){let t=e.headers.get("X-RateLimit-Limit"),o=e.headers.get("X-RateLimit-Remaining"),n=e.headers.get("X-RateLimit-Reset");t&&(this.rateLimitInfo.limit=parseInt(t,10)),o&&(this.rateLimitInfo.remaining=parseInt(o,10)),n&&(this.rateLimitInfo.reset=parseInt(n,10)),this.rateLimitInfo.remaining&&this.rateLimitInfo.remaining<10&&r.warn(`Approaching rate limit for ${this.providerName}: ${this.rateLimitInfo.remaining} requests remaining`)}calculateRateLimitWait(e=0,t){let n=t?this.parseRetryAfter(t.headers.get("Retry-After")):null;if(n!==null)return Math.min(Math.max(n,1e3),6e4);if(this.rateLimitInfo.reset){let l=Math.floor(Date.now()/1e3),c=(this.rateLimitInfo.reset-l)*1e3;return Math.min(Math.max(c,1e3),6e4)}let a=5e3*Math.pow(2,e);return Math.min(a,6e4)}parseRetryAfter(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t))return t*1e3;let o=Date.parse(e);return Number.isNaN(o)?null:o-Date.now()}async handleErrorResponse(e){let t=`${this.providerName} API error: ${e.status} ${e.statusText}`,o=t;try{let n=await e.json();if(typeof n=="object"&&n!==null){let s=n;if(typeof s.error=="string")o=`${t} - ${s.error}`;else if(typeof s.message=="string")o=`${t} - ${s.message}`;else if(Array.isArray(s.errors)){let a=s.errors.map(l=>typeof l=="object"&&l!==null&&"message"in l?String(l.message):JSON.stringify(l)).join(", ");o=`${t} - ${a}`}}}catch{}return r.error(o),new Error(o)}isNonRetryableError(e){if(typeof e=="object"&&e!==null&&e.name==="AbortError")return!0;let t=e.message;return typeof t=="string"&&t.includes("API error: 4")?!t.includes("429"):!1}delay(e){return new Promise(t=>setTimeout(t,e))}getRateLimitInfo(){return{...this.rateLimitInfo}}isLargeResponse(e){if(!e||typeof e!="object")return!1;let t=(o,n=0)=>{if(n>10)return!1;for(let[,s]of Object.entries(o))if(Array.isArray(s)&&s.length>1e3||typeof s=="object"&&s!==null&&t(s,n+1))return!0;return!1};return t(e)}validateLargeResponse(e){if(!e||typeof e!="object")return;let t=(n,s)=>{n.length>5e3&&r.warn(`Large array detected at ${s} with ${n.length} items. This may impact performance.`);let a=Math.min(10,n.length),l=n[0];if(l&&typeof l=="object"){let c=Object.keys(l);for(let d=1;d<a;d++){let u=n[d];if(!u||typeof u!="object"){r.warn(`Inconsistent array structure at ${s}[${d}]: expected object, got ${typeof u}`);continue}let p=Object.keys(u),g=c.filter(h=>!p.includes(h));g.length>0&&r.warn(`Inconsistent array structure at ${s}[${d}]: missing keys ${g.join(", ")}`)}}},o=(n,s="root",a=0)=>{if(!(a>10))for(let[l,c]of Object.entries(n)){let d=`${s}.${l}`;Array.isArray(c)?t(c,d):typeof c=="object"&&c!==null&&o(c,d,a+1)}};o(e)}};var Mi=process.env.DOORMAN_VERCEL_API_BASE_URL||"https://api.vercel.com/v1/security/firewall/config",Me=class extends Pe{constructor(t,o,n){super("","vercel");this.projectId=t;this.teamId=o;this.token=n}projectId;teamId;token;getAuthHeaders(){return{Authorization:`Bearer ${this.token}`}}getUrl(t){let o=t!==void 0?`${Mi}/${t}`:Mi;r.debug("API URL:",o);let n=this.teamId?`&teamId=${this.teamId}`:"";return`${o}?projectId=${this.projectId}${n}`}async fetchFirewallConfig(t,o){let{allowCreate:n=!0}=o??{},s=await this.get(this.getUrl(t));if(r.debug("Config Version:",t??"latest"),r.debug("Fetched Config:",t?s:s.active),t)return s;if(!s||"active"in s&&s.active===null){if(r.warn(Mt.default.bold("No firewall configuration found.")),!n)return r.debug("Skipping create-configuration prompt for read-only fetch."),this.emptyConfigPlaceholder();if(await w("Would you like to create one?",{type:"confirm"})){r.debug("Creating new empty firewall configuration...");let l=await this.putEmptyConfig();return r.debug("Empty firewall configuration created successfully"),r.debug(`New configuration version: ${Mt.default.yellow(l.version)}`),l}else return s.active}return s.active}emptyConfigPlaceholder(){return{version:0,id:"",firewallEnabled:!0,crs:null,rules:[],ips:[],projectKey:"",ownerId:"",updatedAt:new Date(0).toISOString()}}async putEmptyConfig(){let{$schema:t,...o}=wt();return r.debug("Empty Config:",o),this.putConfig(o)}async putConfig(t){return(await this.put(this.getUrl(),t)).active}async fetchActiveFirewallRules(){return(await this.fetchFirewallConfig())?.rules}async updateFirewallRule(t){let o=!t.id||t.id==="-",n={action:o?"rules.insert":"rules.update",id:o?null:t.id,value:{name:t.name,description:t.description,action:t.action,conditionGroup:t.conditionGroup,active:t.active}};return this.patch(this.getUrl(),n)}async createFirewallRule(t){return this.updateFirewallRule({...t,id:"-"})}async deleteFirewallRule(t){let o={action:"rules.remove",id:t.id,value:null};await this.patch(this.getUrl(),o)}async updateIPBlockingRule(t){let o=!t.id||t.id==="-",n={action:o?"ip.insert":"ip.update",id:o?null:t.id,value:{action:t.action,hostname:t.hostname,ip:t.ip,notes:t.notes??null}};return this.patch(this.getUrl(),n)}async createIPBlockingRule(t){return this.updateIPBlockingRule({...t,id:"-"})}async deleteIPBlockingRule(t){let o={action:"ip.remove",id:t.id,value:null};await this.patch(this.getUrl(),o)}async verifyCredentials(){try{return await this.fetchFirewallConfig(),!0}catch(t){return r.debug("Credential verification failed:",t),!1}}};var te=S(require("chalk"));T();T();var $e=class{validateConfig(e){let t=[],o=[];if(e||t.push({path:"root",message:"Configuration is required",code:"CONFIG_REQUIRED"}),e&&!e.rules&&t.push({path:"rules",message:"Rules array is required",code:"RULES_REQUIRED"}),e&&e.rules&&!Array.isArray(e.rules)&&t.push({path:"rules",message:"Rules must be an array",code:"RULES_INVALID_TYPE"}),e&&Array.isArray(e.rules)){let n=new Map;e.rules.forEach((s,a)=>{let l=s.id||s.name;if(!l)return;let c=n.get(l);if(c===void 0){n.set(l,a);return}let d=e.rules[c];o.push({path:`rules[${a}]`,message:s.id?`Rule "${s.name}" has the same id ("${s.id}") as rules[${c}] ("${d?.name}") \u2014 they will collide during sync diffing and one may be silently skipped.`:`Rule "${s.name}" has the same name as rules[${c}] and neither has an explicit id \u2014 they will collide during sync diffing and one may be silently skipped. Add unique ids to disambiguate.`,code:"DUPLICATE_RULE_IDENTIFIER"})})}return{valid:t.length===0,errors:t,warnings:o}}getHealthScore(e){let t=[],o=100;if(!e)return{score:0,grade:"poor",issues:[{severity:"error",category:"configuration",message:"No configuration found"}],recommendations:["Create a configuration file"]};if((!e.rules||e.rules.length===0)&&(o-=20,t.push({severity:"warning",category:"rules",message:"No rules defined",suggestion:"Add security rules to protect your application"})),e.rules&&e.rules.length>0){let a=e.rules.filter(l=>!l.description);a.length>0&&(o-=5,t.push({severity:"info",category:"maintainability",message:`${a.length} rule(s) missing descriptions`,suggestion:"Add descriptions to improve maintainability"}))}if(e.rules&&e.rules.length>0){let a=e.rules.filter(l=>l.active===!1||l.enabled===!1);a.length>0&&(o-=5,t.push({severity:"info",category:"maintenance",message:`${a.length} disabled rule(s) found`,suggestion:"Review and remove unused rules"}))}let n=this.calculateGrade(o),s=this.generateRecommendations(e,t);return{score:Math.max(0,o),grade:n,issues:t,recommendations:s}}diffItems(e,t,o,n="id"){let s=[],a=[],l=[],c=d=>d[n];for(let d of e){let u=t.find(p=>c(p)===c(d));u?o(d,u)||a.push(d):s.push(d)}for(let d of t)e.find(p=>c(p)===c(d))||l.push(d);return{toAdd:s,toUpdate:a,toDelete:l}}validateRuleCount(e,t){if(t&&e>t)throw new Error(`Rule count (${e}) exceeds provider limit (${t})`);t&&e>t*.9&&r.warn(`Approaching rule limit: ${e}/${t} rules`)}updateMetadata(e,t){return{...e,metadata:{...e.metadata,version:t,updatedAt:new Date().toISOString()}}}calculateGrade(e){return e>=80?"excellent":e>=60?"good":e>=40?"fair":"poor"}generateRecommendations(e,t){let o=[];return t.some(n=>n.category==="rules")&&o.push("Consider using predefined templates to get started"),t.some(n=>n.category==="maintainability")&&o.push("Add descriptions to all rules for better documentation"),t.some(n=>n.category==="maintenance")&&o.push("Remove or enable disabled rules to keep configuration clean"),o}logSyncStats(e){r.info(`Sync complete for ${this.name}:`),r.info(` Rules added: ${e.rulesAdded}`),r.info(` Rules updated: ${e.rulesUpdated}`),r.info(` Rules deleted: ${e.rulesDeleted}`),e.ipsAdded!==void 0&&(r.info(` IPs added: ${e.ipsAdded}`),r.info(` IPs updated: ${e.ipsUpdated}`),r.info(` IPs deleted: ${e.ipsDeleted}`)),e.version&&r.info(` New version: ${e.version}`)}};fe();function Gi(i){let e=[],t=[];i.conditionGroup.forEach((s,a)=>{for(let l of s.conditions){let c=vn(l.op);l.op==="re"&&typeof l.value=="string"&&e.push(O.createWarning("regex_patterns",i.id,l.type,`Regular expression pattern may need adjustment for target provider: ${l.value}`,"Test the regex pattern in the target provider and adjust syntax if needed")),t.push({field:En(l.type),operator:c,value:l.value,...l.neg?{negated:!0}:{},...l.key?{key:l.key}:{},group:a})}}),t.length>10&&e.push(O.createWarning("many_conditions",i.id,void 0,`Rule has ${t.length} conditions which may impact performance`,"Consider splitting complex rules into multiple simpler rules for better performance"));let o={type:i.action.mitigate.action,...i.action.mitigate.rateLimit?{rateLimit:{requests:i.action.mitigate.rateLimit.requests,window:i.action.mitigate.rateLimit.window,...i.action.mitigate.rateLimit.characteristics?{characteristics:i.action.mitigate.rateLimit.characteristics}:{},...i.action.mitigate.rateLimit.mitigationTimeout?{mitigationTimeout:i.action.mitigate.rateLimit.mitigationTimeout}:{},...i.action.mitigate.rateLimit.countingExpression?{countingExpression:i.action.mitigate.rateLimit.countingExpression}:{}}}:{},...i.action.mitigate.redirect?{redirect:{location:i.action.mitigate.redirect.location,...i.action.mitigate.redirect.permanent?{permanent:i.action.mitigate.redirect.permanent}:{}}}:{},...i.action.mitigate.actionDuration?{duration:i.action.mitigate.actionDuration}:{}};return{result:{id:i.id,name:i.name,...i.description?{description:i.description}:{},enabled:i.active,conditions:t,conditionLogic:i.conditionGroup.length>1?"OR":"AND",action:o},warnings:e}}function Ki(i){let e=[],t=Cn(i.conditions,i.id,e);if(i.action.response&&e.push(O.createUnsupportedFeatureWarning("custom response body","unified config","Vercel",i.id,"action.response")),t.length===0)throw new Error(`Rule "${i.name}" has no conditions Vercel can represent \u2014 every condition field is unsupported by Vercel (e.g. Cloudflare-only fields like referer/port). Cannot sync this rule to Vercel.`);return{result:{id:i.id,name:i.name,description:i.description,conditionGroup:t,action:{mitigate:{action:i.action.type,rateLimit:i.action.rateLimit?{requests:i.action.rateLimit.requests,window:i.action.rateLimit.window,characteristics:i.action.rateLimit.characteristics,mitigationTimeout:i.action.rateLimit.mitigationTimeout,countingExpression:i.action.rateLimit.countingExpression}:null,redirect:i.action.redirect?{location:i.action.redirect.location,permanent:i.action.redirect.permanent}:null,actionDuration:i.action.duration||null}},active:i.enabled},warnings:e}}function Hi(i){return{id:i.id,ip:i.ip,...i.hostname?{hostname:i.hostname}:{},...i.notes?{notes:i.notes}:{},action:i.action}}function Cn(i,e,t){let o=new Map;for(let s of i){let a=s.group??0,l=o.get(a);l?l.push(s):o.set(a,[s])}let n=[];for(let s of o.values()){let a=[];for(let l of s){let c=An(l.field);if(!c){t.push(O.createUnsupportedFeatureWarning(`condition field '${l.field}'`,"unified config","Vercel",e,l.field));continue}a.push({op:bn(l.operator),neg:l.negated,type:c,key:l.key,value:l.value})}a.length>0&&n.push({conditions:a})}return n}function vn(i){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists",nex:"not_exists"}[i]||"eq"}function bn(i){return{eq:"eq",starts_with:"pre",ends_with:"suf",in:"inc",contains:"sub",matches:"re",exists:"ex",not_exists:"nex"}[i]||"eq"}function En(i){return{host:"host",path:"path",method:"method",header:"header",query:"query",cookie:"cookie",ip_address:"ip",user_agent:"user_agent",geo_country:"country",geo_city:"city",geo_as_number:"asn",scheme:"scheme"}[i]||i}var Tn={host:"host",path:"path",method:"method",header:"header",query:"query",cookie:"cookie",ip:"ip_address",user_agent:"user_agent",country:"geo_country",city:"geo_city",asn:"geo_as_number",scheme:"scheme",target_path:"target_path",region:"region",protocol:"protocol",environment:"environment",geo_continent:"geo_continent",geo_country_region:"geo_country_region",ja4_digest:"ja4_digest",ja3_digest:"ja3_digest",rate_limit_api_id:"rate_limit_api_id"};function An(i){return Tn[i]??null}fe();T();function Ge(i){return i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Zi(i){let e="";for(let t=0;t<i.length;t++)i[t]==="\\"&&(i[t+1]==="\\"||i[t+1]==='"')?(e+=i[t+1],t++):e+=i[t];return e}var lt=class{static vercelToCloudflare={host:"http.host",path:"http.request.uri.path",method:"http.request.method",header:"http.request.headers",query:"http.request.uri.query",cookie:"http.cookie",target_path:"http.request.uri.path",ip_address:"ip.src",region:"ip.geoip.subdivision_1",protocol:"ssl",scheme:"ssl",environment:"",user_agent:"http.user_agent",geo_continent:"ip.geoip.continent",geo_country:"ip.geoip.country",geo_country_region:"ip.geoip.subdivision_1",geo_city:"ip.geoip.city",geo_as_number:"ip.geoip.asnum",ja4_digest:"",ja3_digest:"",rate_limit_api_id:""};static cloudflareToVercel={"http.host":"host","http.request.uri.path":"path","http.request.method":"method","http.request.headers":"header","http.request.uri.query":"query","http.cookie":"cookie","ip.src":"ip_address","ip.geoip.subdivision_1":"region",ssl:"protocol","http.user_agent":"user_agent","ip.geoip.continent":"geo_continent","ip.geoip.country":"geo_country","ip.geoip.city":"geo_city","ip.geoip.asnum":"geo_as_number"};static toCloudflare(e,t){let o=this.vercelToCloudflare[e];if(!o)throw r.warn(`No Cloudflare mapping for Vercel type: ${e}`),new Error(`Unsupported Vercel rule type for Cloudflare: ${e}`);return e==="header"&&t?`${o}["${Ge(t.toLowerCase())}"]`:e==="cookie"&&t?`${o}["${Ge(t)}"]`:o}static toVercel(e){let t=e.match(/http\.request\.headers\["([^"]+)"\]/);if(t)return{type:"header",key:t[1]};let o=e.match(/http\.cookie\["([^"]+)"\]/);if(o)return{type:"cookie",key:o[1]};if(e==="http.referer")return{type:"header",key:"referer"};let n=this.cloudflareToVercel[e];if(n)return{type:n};throw r.warn(`No Vercel mapping for Cloudflare field: ${e}`),new Error(`Unsupported Cloudflare field for Vercel: ${e}`)}static isCloudflareSupported(e){let t=this.vercelToCloudflare[e];return!!t&&t!==""}static isVercelSupported(e){return!!(this.cloudflareToVercel[e]||e==="http.referer"||e.startsWith("http.request.headers[")||e.startsWith("http.cookie["))}static getSupportedCloudflareFields(){return Object.values(this.vercelToCloudflare).filter(e=>e!=="")}static getSupportedVercelTypes(){return Object.keys(this.vercelToCloudflare).filter(e=>this.isCloudflareSupported(e))}};var Pn=new Set(["ip.src"]),ct=class{static fromVercelConditionGroups(e){if(!e||e.length===0)throw new Error("At least one condition group is required");let t=e.map(o=>{let n=o.conditions.map(s=>this.fromVercelCondition(s));if(n.length===0)throw new Error("Condition group must have at least one condition");return n.length>1?`(${n.join(" and ")})`:n[0]});return t.length>1?t.join(" or "):t[0]}static fromVercelCondition(e){let t=lt.toCloudflare(e.type,e.key),o=this.buildExistsOrComparisonExpression(t,e.op,()=>`${this.mapVercelOperator(e.op)} ${this.formatValue(t,e.value)}`);return e.neg&&(o=`not (${o})`),o}static fromUnifiedConditions(e,t="AND"){if(!e||e.length===0)throw new Error("At least one condition is required");if(!e.some(a=>a.group!==void 0)){let a=e.map(c=>this.fromUnifiedCondition(c)),l=t==="AND"?" and ":" or ";return a.length>1?`(${a.join(l)})`:a[0]}let n=new Map;for(let a of e){let l=a.group??0,c=n.get(l);c?c.push(a):n.set(l,[a])}let s=Array.from(n.values()).map(a=>this.combineWithAnd(a.map(l=>this.fromUnifiedCondition(l))));return s.length>1?this.combineWithOr(s):s[0]}static fromUnifiedCondition(e){let t=this.mapUnifiedFieldToCloudflare(e.field),o=e.key&&(e.field==="header"||e.field==="cookie")?`${t}["${Ge(e.key)}"]`:t,n=this.buildUnifiedExpression(o,e.operator,e.value);return e.negated&&(n=`not (${n})`),n}static buildExistsOrComparisonExpression(e,t,o){return t==="ex"||t==="exists"?`${e} exists`:t==="nex"||t==="not_exists"?`not (${e} exists)`:`${e} ${o()}`}static buildUnifiedExpression(e,t,o){return t==="not_contains"?`not (${e} contains ${this.formatValue(e,o)})`:t==="not_in"?`not (${e} in ${this.formatValue(e,o)})`:this.buildExistsOrComparisonExpression(e,t,()=>`${this.mapUnifiedOperator(t)} ${this.formatValue(e,o)}`)}static mapVercelOperator(e){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists"}[e]||e}static mapUnifiedOperator(e){return{eq:"eq",ne:"ne",contains:"contains",starts_with:"starts_with",ends_with:"ends_with",matches:"matches",in:"in",gt:"gt",ge:"ge",lt:"lt",le:"le",exists:"exists"}[e]||e}static mapUnifiedFieldToCloudflare(e){return{ip:"ip.src",country:"ip.geoip.country",region:"ip.geoip.subdivision_1",city:"ip.geoip.city",asn:"ip.geoip.asnum",path:"http.request.uri.path",host:"http.host",method:"http.request.method",header:"http.request.headers",query:"http.request.uri.query",cookie:"http.cookie",user_agent:"http.user_agent",referer:"http.referer",scheme:"ssl",port:"cf.edge.server_port"}[e]||e}static formatValue(e,t){return Array.isArray(t)?`{${t.map(n=>this.formatSingleValue(e,n)).join(" ")}}`:this.formatSingleValue(e,t)}static formatSingleValue(e,t){if(typeof t=="string"){if(Pn.has(e)){if(!ze.safeParse(t).success)throw new Error(`Invalid IP address or CIDR range: ${t}`);return t}return`"${Ge(t)}"`}return typeof t=="number"?String(t):typeof t=="boolean"?t?"true":"false":String(t)}static validate(e){if(!e||e.trim().length===0)return!1;let t=0;for(let o of e)if(o==="("&&t++,o===")"&&t--,t<0)return!1;return t===0}static combineWithAnd(e){if(e.length===0)throw new Error("At least one expression is required");return e.length===1?e[0]:`(${e.join(" and ")})`}static combineWithOr(e){if(e.length===0)throw new Error("At least one expression is required");return e.length===1?e[0]:`(${e.join(" or ")})`}};var $n={"ip.src":"ip","ip.geoip.country":"country","ip.geoip.subdivision_1":"region","ip.geoip.city":"city","ip.geoip.asnum":"asn","http.request.uri.path":"path","http.host":"host","http.request.method":"method","http.request.headers":"header","http.request.uri.query":"query","http.cookie":"cookie","http.user_agent":"user_agent","http.referer":"referer",ssl:"scheme","cf.edge.server_port":"port"},kn=new Set(["eq","ne","contains","starts_with","ends_with","matches","in","gt","ge","lt","le"]),_n=new Set(["and","or","not"]),he=class extends Error{};function Sn(i){let e=[],t=0,o=i.length;for(;t<o;){let n=i[t];if(/\s/.test(n)){t++;continue}if(n==="("){e.push({type:"LPAREN",value:n}),t++;continue}if(n===")"){e.push({type:"RPAREN",value:n}),t++;continue}if(n==="{"){e.push({type:"LBRACE",value:n}),t++;continue}if(n==="}"){e.push({type:"RBRACE",value:n}),t++;continue}if(n==="["){e.push({type:"LBRACKET",value:n}),t++;continue}if(n==="]"){e.push({type:"RBRACKET",value:n}),t++;continue}if(n==='"'){let a=t+1,l="",c=!1;for(;a<o;){let d=i[a];if(d==="\\"&&a+1<o){l+=d+i[a+1],a+=2;continue}if(i[a]==='"'){c=!0,a++;break}l+=i[a],a++}if(!c)throw new he("Unterminated string literal");e.push({type:"STRING",value:Zi(l)}),t=a;continue}let s=t;for(;s<o&&!/[\s(){}[\]"]/.test(i[s]);)s++;if(s===t)throw new he(`Unexpected character '${n}' at position ${t}`);e.push({type:"WORD",value:i.slice(t,s)}),t=s}return e}var Gt=class{constructor(e){this.tokens=e}tokens;pos=0;peek(){return this.tokens[this.pos]}next(){let e=this.tokens[this.pos];if(!e)throw new he("Unexpected end of expression");return this.pos++,e}expect(e,t){let o=this.next();if(o.type!==e||t!==void 0&&o.value!==t)throw new he(`Expected ${t??e} but got '${o.value}'`);return o}isWord(e){let t=this.peek();return!!t&&t.type==="WORD"&&t.value===e}atEnd(){return this.pos>=this.tokens.length}};function Kt(i){let e=[Yi(i)];for(;i.isWord("or");)i.next(),e.push(Yi(i));return e.length===1?e[0]:{type:"or",children:e}}function Yi(i){let e=[Ji(i)];for(;i.isWord("and");)i.next(),e.push(Ji(i));return e.length===1?e[0]:{type:"and",children:e}}function Ji(i){if(i.isWord("not")){i.next(),i.expect("LPAREN");let e=Kt(i);return i.expect("RPAREN"),{type:"not",child:e}}return Ln(i)}function Ln(i){let e=i.peek();if(e&&e.type==="LPAREN"){i.next();let t=Kt(i);return i.expect("RPAREN"),t}return xn(i)}function Un(i){let e=i.expect("WORD");if(_n.has(e.value))throw new he(`Expected a field reference but got keyword '${e.value}'`);if(i.peek()?.type==="LBRACKET"){i.next();let t=i.expect("STRING");return i.expect("RBRACKET"),{field:e.value,key:t.value}}return{field:e.value}}function Qi(i){let e=i.next();if(e.type==="STRING")return e.value;if(e.type==="WORD")return/^-?\d+(\.\d+)?$/.test(e.value)?Number(e.value):e.value;throw new he(`Unexpected token '${e.value}' where a value was expected`)}function Dn(i){if(i.peek()?.type==="LBRACE"){i.next();let e=[];for(;i.peek()?.type!=="RBRACE";)e.push(Qi(i));return i.expect("RBRACE"),e}return Qi(i)}function xn(i){let{field:e,key:t}=Un(i);if(i.isWord("exists"))return i.next(),{type:"exists",field:e,key:t};let o=i.next();if(o.type!=="WORD"||!kn.has(o.value))throw new he(`Unsupported or unrecognized operator '${o.value}'`);let n=Dn(i);return{type:"comparison",field:e,key:t,operator:o.value,value:n}}function On(i){let e=new Gt(Sn(i)),t=Kt(e);if(!e.atEnd())throw new he("Unexpected trailing tokens");return t}function It(i){return i.type==="comparison"||i.type==="exists"?!0:i.type==="not"?i.child.type==="comparison"||i.child.type==="exists":!1}function Rt(i,e){let t=i.type==="not",o=i.type==="not"?i.child:i;if(o.type!=="comparison"&&o.type!=="exists")return null;let n=$n[o.field];if(!n)return null;if(o.type==="exists")return{field:n,operator:t?"not_exists":"exists",value:"",key:o.key,group:e};let s=o.operator,a;return t&&(o.operator==="contains"?s="not_contains":o.operator==="in"?s="not_in":a=!0),{field:n,operator:s,value:o.value,key:o.key,negated:a,group:e}}function Fn(i){if(It(i)){let e=Rt(i,0);return e?{conditions:[e],conditionLogic:"AND"}:null}if(i.type==="and"){let e=[];for(let t of i.children){if(!It(t))return null;let o=Rt(t,0);if(!o)return null;e.push(o)}return{conditions:e,conditionLogic:"AND"}}if(i.type==="or"){let e=[];i.children.forEach((n,s)=>{if(It(n)){let a=Rt(n,s);a&&e.push(a);return}if(n.type==="and")for(let a of n.children){if(!It(a))return;let l=Rt(a,s);l&&e.push(l)}});let t=i.children.length;return new Set(e.map(n=>n.group)).size!==t?null:{conditions:e,conditionLogic:"OR"}}return null}function Ht(i){if(!i||!i.trim())return null;try{let e=On(i);return Fn(e)}catch{return null}}function Xi(i){let e=[],t=Ht(i.expression),o=[],n;t?(o=t.conditions,n=t.conditionLogic):e.push(O.createWarning("complex_expressions",i.id,"expression","Expression could not be parsed back into structured conditions \u2014 it may be hand-authored or use syntax outside what doorman itself generates.","Review the translated rule and add missing conditions manually if needed."));let s=i.action_parameters&&"response"in i.action_parameters?i.action_parameters.response:void 0,a={type:Nn(i.action),rateLimit:i.ratelimit?{requests:i.ratelimit.requests_per_period,window:`${i.ratelimit.period}s`,characteristics:i.ratelimit.characteristics,mitigationTimeout:i.ratelimit.mitigation_timeout,countingExpression:i.ratelimit.counting_expression}:void 0,response:s?{statusCode:s.status_code,content:s.content,contentType:s.content_type}:void 0};return{result:{id:i.id,name:i.description||`Rule ${i.id}`,description:i.description,enabled:i.enabled??!0,conditions:o,conditionLogic:n,action:a},warnings:e}}function eo(i){let e=[],t=ct.fromUnifiedConditions(i.conditions,i.conditionLogic),o={id:i.id||crypto.randomUUID(),action:Vn(i.action.type),expression:t,description:i.description||i.name,enabled:i.enabled};return i.action.rateLimit&&(o.ratelimit={characteristics:i.action.rateLimit.characteristics||["ip.src"],period:Bn(i.action.rateLimit.window),requests_per_period:i.action.rateLimit.requests},i.action.rateLimit.mitigationTimeout?o.ratelimit.mitigation_timeout=i.action.rateLimit.mitigationTimeout:o.ratelimit.mitigation_timeout=3600,i.action.rateLimit.countingExpression&&(o.ratelimit.counting_expression=i.action.rateLimit.countingExpression)),i.action.response&&(o.action!=="block"?e.push(O.createUnsupportedFeatureWarning(`custom response on a '${o.action}' action`,"unified config","Cloudflare",i.id,"action.response")):i.action.response.content?o.action_parameters={response:{status_code:i.action.response.statusCode??403,content:i.action.response.content,content_type:i.action.response.contentType??"text/plain"}}:e.push(O.createWarning("lossy_conversion",i.id,"action.response","Custom response declared without `content`; Cloudflare requires a response body, so it was dropped.","Set action.response.content to the body you want returned."))),{result:o,warnings:e}}function to(i){if(!ze.safeParse(i.ip).success)throw new Error(`Invalid IP address or CIDR range: ${i.ip}`);let t=i.ip.includes("/")?`ip.src in {${i.ip}}`:`ip.src eq ${i.ip}`;return{id:i.id||crypto.randomUUID(),action:i.action==="allow"?"allow":"block",expression:t,description:i.notes||`IP ${i.action}: ${i.ip}${i.hostname?` (${i.hostname})`:""}`,enabled:!0}}function Nn(i){return{block:"deny",challenge:"challenge",managed_challenge:"challenge",js_challenge:"challenge",log:"log",skip:"bypass",allow:"allow",rewrite:"bypass",redirect:"redirect"}[i]||"deny"}function Vn(i){return{log:"log",deny:"block",block:"block",challenge:"managed_challenge",bypass:"skip",rate_limit:"block",redirect:"redirect",allow:"allow"}[i]||"block"}function Bn(i){let e=i.match(/^(\d+)([smhd])$/);if(!e||!e[1]||!e[2])throw new Error(`Invalid window format: ${i}`);let t=parseInt(e[1],10),o=e[2],s={s:1,m:60,h:3600,d:86400}[o];if(s===void 0)throw new Error(`Invalid time unit: ${o}`);return t*s}fe();function se(i,e,t){return O.createWarning("complex_expressions",i,void 0,e,t)}var Wn={ip:"ip",path:"path",domain:"host",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},jn={ip:"ip",path:"path",host:"domain",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},qn={header:"request_header",query:"query_parameter",cookie:"request_cookie"},zn={request_header:"header",query_parameter:"query",request_cookie:"cookie",response_header:"response_header",post_parameter:"post_parameter",signal:"signal"};function Mn(i){return Wn[i]??i}function Gn(i){return jn[i]??null}var Kn={equals:{operator:"eq",negated:!1},does_not_equal:{operator:"eq",negated:!0},contains:{operator:"contains",negated:!1},does_not_contain:{operator:"contains",negated:!0},like:{operator:"matches",negated:!1},not_like:{operator:"matches",negated:!0},in_list:{operator:"in",negated:!1},not_in_list:{operator:"in",negated:!0},matches:{operator:"matches",negated:!1},does_not_match:{operator:"matches",negated:!0},greater_equal:{operator:"ge",negated:!1},lesser_equal:{operator:"le",negated:!1}};function io(i){return Kn[i]??{operator:"eq",negated:!1}}function oo(i,e,t,o){switch(i){case"eq":return e?"does_not_equal":"equals";case"ne":return"does_not_equal";case"contains":return e?"does_not_contain":"contains";case"not_contains":return"does_not_contain";case"starts_with":case"ends_with":return t.push(O.createWarning("regex_patterns",o,void 0,`Unified operator "${i}" has no direct Fastly equivalent \u2014 mapped to Fastly's wildcard "like" operator. Verify the translated value still matches as a wildcard pattern.`)),e?"not_like":"like";case"matches":return t.push(O.createWarning("regex_patterns",o,void 0,"Regular expression pattern may need adjustment for Fastly Next-Gen WAF regex syntax.")),e?"does_not_match":"matches";case"in":return e?"not_in_list":"in_list";case"not_in":return"not_in_list";case"gt":return t.push(se(o,'Unified operator "gt" (strictly greater than) has no Fastly equivalent \u2014 mapped to "greater_equal", which also matches the boundary value itself.')),"greater_equal";case"ge":return"greater_equal";case"lt":return t.push(se(o,'Unified operator "lt" (strictly less than) has no Fastly equivalent \u2014 mapped to "lesser_equal", which also matches the boundary value itself.')),"lesser_equal";case"le":return"lesser_equal";default:return"equals"}}function Hn(i,e){let t=[],o=i.conditions.filter(s=>s.type==="group"),n=i.conditions.filter(s=>s.type!=="group");if(o.length>0&&n.length===0&&i.group_operator==="any")return o.forEach((s,a)=>{s.group_operator!=="all"&&e.push(se(i.id,`A condition group using "any" (OR) inside an outer "any" (OR) rule cannot be represented in doorman's flat AND-within/OR-across condition model \u2014 its members were kept in the same group (effectively AND'd) instead of OR'd. Review the translated rule against the original Fastly logic.`));for(let l of s.conditions)Ct(t,l,a,e,i.id)}),{conditions:t,conditionLogic:o.length>1?"OR":"AND"};if(o.length===0)return n.forEach((s,a)=>{let l=i.group_operator==="any"?a:0;Ct(t,s,l,e,i.id)}),{conditions:t,conditionLogic:i.group_operator==="any"&&n.length>1?"OR":"AND"};e.push(se(i.id,`Rule mixes top-level conditions with condition groups under group_operator "${i.group_operator}" \u2014 this doesn't fit doorman's flat AND-within/OR-across condition model. All conditions were combined with AND; review the translated rule against the original Fastly rule logic.`));for(let s of n)Ct(t,s,0,e,i.id);for(let s of o)for(let a of s.conditions)Ct(t,a,0,e,i.id);return{conditions:t,conditionLogic:"AND"}}function Ct(i,e,t,o,n){if(e.type==="single"){let{operator:u,negated:p}=io(e.operator);i.push({field:Mn(e.field),operator:u,value:e.value,...p?{negated:!0}:{},group:t});return}let s=zn[e.field],a=e.conditions.find(u=>u.field==="name"),l=e.conditions.find(u=>u.field==="value"||u.field==="value_string");if(!l){o.push(se(n,`Multival condition on '${e.field}' has no value sub-condition doorman could extract (only a 'name' existence check) \u2014 skipped.`));return}let{operator:c,negated:d}=io(l.operator);i.push({field:s,operator:c,value:l.value,...d?{negated:!0}:{},...a?{key:a.value}:{},group:t})}function Zn(i,e){i.actions.length>1&&e.push(se(i.id,`Rule has ${i.actions.length} actions \u2014 doorman only models one action per rule; only the first ("${i.actions[0]?.type}") was translated.`));let t=i.actions[0];if(i.type==="rate_limit")return{type:"rate_limit",rateLimit:i.rate_limit?{requests:i.rate_limit.threshold,window:`${i.rate_limit.interval}s`,mitigationTimeout:i.rate_limit.duration}:void 0};switch(t?.type){case"block":return{type:"block"};case"allow":return{type:"allow"};case"browser_challenge":case"dynamic_challenge":case"verify_token":return{type:"challenge"};case"redirect":return{type:"redirect",redirect:{location:t.redirect_url??"",...t.response_code!==void 0?{statusCode:t.response_code}:{}}};case"add_signal":case"exclude_signal":case"deception":return e.push(O.createWarning("action_differences",i.id,"action.type",`Fastly action "${t.type}" tags or excludes a WAF signal rather than allowing/blocking the request \u2014 doorman has no matching action type. Mapped to "log" as the closest non-destructive fallback; review this rule.`)),{type:"log"};default:return e.push(se(i.id,`Unrecognised Fastly action type "${String(t?.type)}" \u2014 mapped to "log".`)),{type:"log"}}}function no(i){let e=[],{conditions:t,conditionLogic:o}=Hn(i,e),n=Zn(i,e);return t.length>10&&e.push(O.createWarning("many_conditions",i.id,void 0,`Rule has ${t.length} conditions which may impact performance`)),{result:{id:i.id,name:i.description||i.id,enabled:i.enabled,conditions:t,conditionLogic:o,action:n},warnings:e}}function Yn(i,e,t){let o=new Map;for(let a of i){let l=a.group??0,c=o.get(l);c?c.push(a):o.set(l,[a])}let n=a=>{let l=qn[a.field];if(l){if(a.key===void 0)return t.push(se(e,`Condition on '${a.field}' has no 'key' set \u2014 Fastly needs a specific ${a.field} name to match on (e.g. a header name). Skipped.`)),null;let d=l==="request_header"||l==="response_header"?"value_string":"value";return{type:"multival",field:l,operator:"exists",group_operator:"all",conditions:[{type:"single",field:"name",operator:"equals",value:a.key},{type:"single",field:d,operator:oo(a.operator,a.negated,t,e),value:String(a.value)}]}}let c=Gn(a.field);return c?{type:"single",field:c,operator:oo(a.operator,a.negated,t,e),value:String(a.value)}:(t.push(O.createUnsupportedFeatureWarning(`condition field '${a.field}'`,"unified config","Fastly",e,a.field)),null)};if(o.size<=1){let a=i.map(n).filter(l=>l!==null);return{conditions:a.filter(l=>l.type==="single"),groupConditions:[],multivalConditions:a.filter(l=>l.type==="multival"),groupOperator:"all"}}let s=[];for(let a of o.values()){let l=a.map(n).filter(c=>c!==null);l.length>0&&s.push({type:"group",group_operator:"all",conditions:l})}return{conditions:[],groupConditions:s,multivalConditions:[],groupOperator:"any"}}function Jn(i,e,t){switch(i.type){case"block":case"deny":return{type:"block"};case"allow":return{type:"allow"};case"challenge":return{type:"browser_challenge"};case"bypass":return e.push(se(t,'Unified action "bypass" has no direct Fastly equivalent \u2014 mapped to "allow".')),{type:"allow"};case"log":return e.push(se(t,'Unified action "log" has no dedicated Fastly action \u2014 mapped to "allow" (request_logging is enabled at the rule level regardless).')),{type:"allow"};case"redirect":return i.redirect?{type:"redirect",redirect_url:i.redirect.location,response_code:i.redirect.statusCode??(i.redirect.permanent?301:302)}:(e.push(se(t,'Unified action "redirect" has no redirect target \u2014 mapped to "allow".')),{type:"allow"});case"rate_limit":return{type:"block_signal"};default:return e.push(O.createUnsupportedFeatureWarning(`action type '${i.type}'`,"unified config","Fastly",t,"action.type")),{type:"block"}}}function Qn(i,e,t){let o=/^(\d+)\s*(s|m|h)?$/i.exec(i.trim()),n={s:1,m:60,h:3600},s=o?Number(o[1])*n[o[2]?.toLowerCase()||"s"]:NaN,a=[60,600,3600];if(!Number.isFinite(s)||s<=0)return e.push(O.createWarning("rate_limiting_precision",t,void 0,`Rate limit window "${i}" could not be parsed \u2014 defaulted to Fastly's 60-second interval.`)),60;let l=a.reduce((c,d)=>Math.abs(d-s)<Math.abs(c-s)?d:c);return l!==s&&e.push(O.createWarning("rate_limiting_precision",t,void 0,`Rate limit window "${i}" (${s}s) isn't one of Fastly's supported intervals (60s/600s/3600s) \u2014 rounded to ${l}s.`)),l}function Xn(i,e,t){if(!i)throw new Error(`Rule "${e??"(unnamed)"}" has action type "rate_limit" but no rateLimit configuration \u2014 Fastly requires a threshold and interval.`);let o=Qn(i.window,t,e);return t.push(O.createWarning("rate_limiting_precision",e,void 0,`Fastly rate-limit rules count requests against a named custom signal, which doorman does not create automatically \u2014 create a signal named "doorman-rate-limit-${e??"rule"}" in this workspace before syncing, or the rule will be rejected.`)),{client_identifiers:[{type:"ip"}],duration:i.mitigationTimeout??o,interval:o,signal:`doorman-rate-limit-${e??"rule"}`,threshold:i.requests}}function ro(i){let e=[];i.description&&i.description!==i.name&&e.push(se(i.id,'Fastly rules have no separate "name" field \u2014 only "description" carries over, and it was set from this rule\'s `name`. The `description` text was dropped rather than merged in, to keep it round-trip-stable on the next sync.'));let{conditions:t,groupConditions:o,multivalConditions:n,groupOperator:s}=Yn(i.conditions,i.id,e);if(t.length===0&&o.length===0&&n.length===0)throw new Error(`Rule "${i.name}" has no conditions Fastly can represent \u2014 every condition field is unsupported by Fastly. Cannot sync this rule to Fastly.`);let a=i.action.type==="rate_limit";return{result:{type:a?"rate_limit":"request",description:i.name,enabled:i.enabled,group_operator:s,request_logging:"sampled",conditions:t,group_conditions:o,multival_conditions:n,actions:[Jn(i.action,e,i.id)],rate_limit:a?Xn(i.action.rateLimit,i.id,e):null},warnings:e}}function so(i,e){return i.map(t=>({ip:t,action:e}))}function ao(i){let e=[],t=[],o=[];for(let n of i)(n.hostname||n.notes)&&e.push(se(n.id,`IP rule "${n.ip}" sets ${n.hostname?"`hostname`":""}${n.hostname&&n.notes?" and ":""}${n.notes?"`notes`":""} \u2014 Fastly IP lists have no equivalent per-entry metadata; only the address was kept.`)),(n.action==="allow"?o:t).push(n.ip);return{result:{denyEntries:t,allowEntries:o},warnings:e}}var $=class{static vercelToUnified=Gi;static unifiedToVercel=Ki;static vercelIPToUnified=Hi;static cloudflareToUnified=Xi;static unifiedToCloudflare=eo;static unifiedIPToCloudflare=to;static fastlyToUnified=no;static unifiedToFastly=ro;static fastlyListEntriesToUnified=so;static unifiedIPsToFastlyEntries=ao};fe();function Ke(i,e){if(i===e)return!0;if(typeof i!="object"||i===null||typeof e!="object"||e===null||Array.isArray(i)!==Array.isArray(e))return!1;let t=Object.keys(i),o=Object.keys(e);if(t.length!==o.length)return!1;for(let n of t)if(!o.includes(n)||!Ke(i[n],e[n]))return!1;return!0}function ke(i){let{id:e,...t}=i;return t}function dt(i){return[...i].sort((e,t)=>{let o=e.priority!==void 0,n=t.priority!==void 0;return!o&&!n?0:o?n?e.priority-t.priority:-1:1})}function vt(i){return i.some(e=>e.priority!==void 0)}var He=class extends $e{constructor(t){super();this.client=t}client;name="vercel";async fetchConfig(t){try{r.debug("Fetching Vercel firewall configuration");let o=await this.client.fetchFirewallConfig(t),n=o.rules.map(a=>{let l=$.vercelToUnified(a);return l.warnings.length>0&&l.warnings.forEach(c=>{let{TranslationWarningSystem:d}=(fe(),ye(De)),u=d.formatWarning(c);r.warn(`Rule ${a.name}:
|
|
25
|
-
${u}`)}),l.result}),s=o.ips.map(a=>$.vercelIPToUnified(a));return{version:"2.0",provider:"vercel",providers:{vercel:{projectId:this.client.projectId,...this.client.teamId?{teamId:this.client.teamId}:{}}},rules:n,ips:s,metadata:{version:o.version,updatedAt:o.updatedAt}}}catch(o){throw r.error("Error fetching Vercel configuration:",o),new Error("Failed to fetch Vercel firewall configuration")}}async syncRules(t,o={}){let{dryRun:n=!1}=o;try{let{OperationSafety:s}=(Tt(),ye(Et)),a=await s.performDryRunValidation(t,"sync rules",async f=>await this.getChanges(f,{allowCreate:!n}));if(!a.valid)throw new Error(`Dry-run validation failed: ${a.issues.join(", ")}`);let l=a.changes,{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u,version:p}=l,g=l.ipsToAdd||[],h=l.ipsToUpdate||[],I=l.ipsToDelete||[];if(n)return r.info("Dry run mode. The following changes would be made:"),r.info(`Custom Rules - Add: ${c.length}, Update: ${d.length}, Delete: ${u.length}`),r.info(`IP Rules - Add: ${g.length}, Update: ${h.length}, Delete: ${I.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,version:p,warnings:a.warnings};let R=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Vercel project ${this.client.projectId}`,changes:l,riskLevel:R,skipConfirmation:o.force||!1,dryRun:!1,allowDeletions:o.allowDeletions||!1}))throw new Error("Operation cancelled by user");let Z=c.map(f=>$.unifiedToVercel(f).result),W=d.map(f=>$.unifiedToVercel(f).result),ue=u.map(f=>$.unifiedToVercel(f).result),me=g.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),_e=h.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),_=I.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),
|
|
24
|
+
`)}catch{return!1}return n.some(s=>{let a=s.trim();if(!a||a.startsWith("#"))return!1;let l=a.replace(/^\//,"").replace(/\/$/,"");return l===o||o.startsWith(`${l}/`)})}var J={type:"string",choices:re,description:"Firewall provider (auto-detected)"};var wo=require("consola");T();var ho=S(require("chalk"));T();pe();zt();T();var yt=class{static detect(e){let t=[];if(e&&"provider"in e){let n=e.provider;if(typeof n=="string"&&this.isValidProvider(n))return t.push(`Explicit provider specified in config: ${e.provider}`),{provider:n,confidence:"high",reasons:t};r.warn(`Invalid provider specified in config: ${String(e.provider)}`)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let n=e.providers;if(typeof(n.cloudflare||{}).zoneId=="string")return t.push("Cloudflare zone ID found in config"),{provider:"cloudflare",confidence:"high",reasons:t};if(typeof(n.vercel||{}).projectId=="string")return t.push("Vercel project ID found in config"),{provider:"vercel",confidence:"high",reasons:t};if(typeof(n.fastly||{}).workspaceId=="string")return t.push("Fastly workspace ID found in config"),{provider:"fastly",confidence:"high",reasons:t}}if(e&&"projectId"in e&&typeof e.projectId=="string")return t.push("Legacy Vercel project ID found in config"),{provider:"vercel",confidence:"high",reasons:t};let o=this.detectFromEnvironment();return o.provider?o:(r.debug("Unable to auto-detect provider"),{provider:null,confidence:"low",reasons:["No provider information found in config or environment"]})}static detectFromEnvironment(){let e=[],t=process.env.DOORMAN_PROVIDER;return t&&this.isValidProvider(t)?(e.push(`Provider set via DOORMAN_PROVIDER environment variable: ${t}`),{provider:t,confidence:"high",reasons:e}):process.env.CLOUDFLARE_ZONE_ID&&process.env.CLOUDFLARE_API_TOKEN?(e.push("Cloudflare credentials found in environment variables"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.CLOUDFLARE_ZONE_ID?(e.push("Cloudflare zone ID found in environment"),{provider:"cloudflare",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID&&process.env.VERCEL_TOKEN?(e.push("Vercel credentials found in environment variables"),{provider:"vercel",confidence:"medium",reasons:e}):process.env.VERCEL_PROJECT_ID?(e.push("Vercel project ID found in environment"),{provider:"vercel",confidence:"medium",reasons:e}):process.env.FASTLY_WORKSPACE_ID&&process.env.FASTLY_API_TOKEN?(e.push("Fastly credentials found in environment variables"),{provider:"fastly",confidence:"medium",reasons:e}):process.env.FASTLY_WORKSPACE_ID?(e.push("Fastly workspace ID found in environment"),{provider:"fastly",confidence:"medium",reasons:e}):{provider:null,confidence:"low",reasons:["No provider credentials found in environment"]}}static isValidProvider(e){return re.includes(e)}static getProvider(e,t="vercel"){let o=this.detect(e);return o.provider?(r.debug(`Provider detected: ${o.provider} (${o.confidence} confidence)`),o.reasons.length>0&&r.debug(`Detection reasons: ${o.reasons.join(", ")}`),o.provider):(r.debug(`No provider detected, using fallback: ${t}`),t)}static detectAll(e){let t=new Set;if(e&&"provider"in e){let o=e.provider;typeof o=="string"&&this.isValidProvider(o)&&t.add(o)}if(e&&"providers"in e&&typeof e.providers=="object"&&e.providers!==null){let o=e.providers;typeof(o.cloudflare||{}).zoneId=="string"&&t.add("cloudflare"),typeof(o.vercel||{}).projectId=="string"&&t.add("vercel"),typeof(o.fastly||{}).workspaceId=="string"&&t.add("fastly")}return e&&"projectId"in e&&typeof e.projectId=="string"&&t.add("vercel"),process.env.CLOUDFLARE_ZONE_ID&&t.add("cloudflare"),process.env.VERCEL_PROJECT_ID&&t.add("vercel"),process.env.FASTLY_WORKSPACE_ID&&t.add("fastly"),Array.from(t)}};var Mt=S(require("chalk"));T();pe();var wt=i=>({$schema:Ci,firewallEnabled:!0,rules:[],ips:[],...i});T();var Pe=class{baseUrl;providerName;rateLimitInfo={};constructor(e,t){this.baseUrl=e,this.providerName=t}async makeRequest(e,t={}){let o=`${this.baseUrl}${e}`,{timeout:n=3e4,retries:s=3,retryDelay:a=1e3,...l}=t,c=null,d=null,u=null,p=()=>{u&&(clearTimeout(u),u=null),d&&(d.abort(),d=null)};try{for(let g=0;g<=s;g++)try{d=new AbortController,u=setTimeout(()=>{d&&d.abort()},n);let h=await fetch(o,{...l,headers:{"Content-Type":"application/json",...this.getAuthHeaders(),...l.headers},signal:d.signal});if(u&&(clearTimeout(u),u=null),this.updateRateLimitInfo(h),h.status===429){let R=this.calculateRateLimitWait(g,h);if(g===s)throw new Error(`${this.providerName} API rate limit exceeded after ${s+1} attempt(s) (429 Too Many Requests). Retry after ~${Math.round(R/1e3)}s.`);r.warn(`Rate limit exceeded for ${this.providerName}. Waiting ${R}ms before retry (attempt ${g+1}/${s+1})...`),await this.delay(R);continue}if(!h.ok)throw await this.handleErrorResponse(h);let I;try{let R=await h.text();R.trim()?I=JSON.parse(R):I={}}catch(R){throw r.error(`Failed to parse response from ${o}:`,R),new Error(`Invalid JSON response from ${this.providerName} API: ${R instanceof Error?R.message:String(R)}`)}return this.isLargeResponse(I)&&(r.debug(`Large response detected from ${o}, validating structure...`),this.validateLargeResponse(I)),I}catch(h){if(c=h,u&&(clearTimeout(u),u=null),this.isNonRetryableError(h)||g===s)throw h;let I=a*Math.pow(2,g),R=Math.random()*.1*I,N=Math.min(I+R,3e4);r.debug(`Request failed (attempt ${g+1}/${s+1}). Retrying in ${Math.round(N)}ms...`),r.debug(`Error details: ${h instanceof Error?h.message:String(h)}`),await this.delay(N)}throw c||new Error("Request failed after all retries")}finally{p()}}async get(e,t){return this.makeRequest(e,{...t,method:"GET"})}async post(e,t,o){return this.makeRequest(e,{...o,method:"POST",body:t?JSON.stringify(t):void 0})}async put(e,t,o){return this.makeRequest(e,{...o,method:"PUT",body:t?JSON.stringify(t):void 0})}async patch(e,t,o){return this.makeRequest(e,{...o,method:"PATCH",body:t?JSON.stringify(t):void 0})}async delete(e,t){return this.makeRequest(e,{...t,method:"DELETE"})}updateRateLimitInfo(e){let t=e.headers.get("X-RateLimit-Limit"),o=e.headers.get("X-RateLimit-Remaining"),n=e.headers.get("X-RateLimit-Reset");t&&(this.rateLimitInfo.limit=parseInt(t,10)),o&&(this.rateLimitInfo.remaining=parseInt(o,10)),n&&(this.rateLimitInfo.reset=parseInt(n,10)),this.rateLimitInfo.remaining&&this.rateLimitInfo.remaining<10&&r.warn(`Approaching rate limit for ${this.providerName}: ${this.rateLimitInfo.remaining} requests remaining`)}calculateRateLimitWait(e=0,t){let n=t?this.parseRetryAfter(t.headers.get("Retry-After")):null;if(n!==null)return Math.min(Math.max(n,1e3),6e4);if(this.rateLimitInfo.reset){let l=Math.floor(Date.now()/1e3),c=(this.rateLimitInfo.reset-l)*1e3;return Math.min(Math.max(c,1e3),6e4)}let a=5e3*Math.pow(2,e);return Math.min(a,6e4)}parseRetryAfter(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t))return t*1e3;let o=Date.parse(e);return Number.isNaN(o)?null:o-Date.now()}async handleErrorResponse(e){let t=`${this.providerName} API error: ${e.status} ${e.statusText}`,o=t;try{let n=await e.json();if(typeof n=="object"&&n!==null){let s=n;if(typeof s.error=="string")o=`${t} - ${s.error}`;else if(typeof s.message=="string")o=`${t} - ${s.message}`;else if(Array.isArray(s.errors)){let a=s.errors.map(l=>typeof l=="object"&&l!==null&&"message"in l?String(l.message):JSON.stringify(l)).join(", ");o=`${t} - ${a}`}}}catch{}return r.error(o),new Error(o)}isNonRetryableError(e){if(typeof e=="object"&&e!==null&&e.name==="AbortError")return!0;let t=e.message;return typeof t=="string"&&t.includes("API error: 4")?!t.includes("429"):!1}delay(e){return new Promise(t=>setTimeout(t,e))}getRateLimitInfo(){return{...this.rateLimitInfo}}isLargeResponse(e){if(!e||typeof e!="object")return!1;let t=(o,n=0)=>{if(n>10)return!1;for(let[,s]of Object.entries(o))if(Array.isArray(s)&&s.length>1e3||typeof s=="object"&&s!==null&&t(s,n+1))return!0;return!1};return t(e)}validateLargeResponse(e){if(!e||typeof e!="object")return;let t=(n,s)=>{n.length>5e3&&r.warn(`Large array detected at ${s} with ${n.length} items. This may impact performance.`);let a=Math.min(10,n.length),l=n[0];if(l&&typeof l=="object"){let c=Object.keys(l);for(let d=1;d<a;d++){let u=n[d];if(!u||typeof u!="object"){r.warn(`Inconsistent array structure at ${s}[${d}]: expected object, got ${typeof u}`);continue}let p=Object.keys(u),g=c.filter(h=>!p.includes(h));g.length>0&&r.warn(`Inconsistent array structure at ${s}[${d}]: missing keys ${g.join(", ")}`)}}},o=(n,s="root",a=0)=>{if(!(a>10))for(let[l,c]of Object.entries(n)){let d=`${s}.${l}`;Array.isArray(c)?t(c,d):typeof c=="object"&&c!==null&&o(c,d,a+1)}};o(e)}};var Mi=process.env.DOORMAN_VERCEL_API_BASE_URL||"https://api.vercel.com/v1/security/firewall/config",Me=class extends Pe{constructor(t,o,n){super("","vercel");this.projectId=t;this.teamId=o;this.token=n}projectId;teamId;token;getAuthHeaders(){return{Authorization:`Bearer ${this.token}`}}getUrl(t){let o=t!==void 0?`${Mi}/${t}`:Mi;r.debug("API URL:",o);let n=this.teamId?`&teamId=${this.teamId}`:"";return`${o}?projectId=${this.projectId}${n}`}async fetchFirewallConfig(t,o){let{allowCreate:n=!0}=o??{},s=await this.get(this.getUrl(t));if(r.debug("Config Version:",t??"latest"),r.debug("Fetched Config:",t?s:s.active),t)return s;if(!s||"active"in s&&s.active===null){if(r.warn(Mt.default.bold("No firewall configuration found.")),!n)return r.debug("Skipping create-configuration prompt for read-only fetch."),this.emptyConfigPlaceholder();if(await w("Would you like to create one?",{type:"confirm"})){r.debug("Creating new empty firewall configuration...");let l=await this.putEmptyConfig();return r.debug("Empty firewall configuration created successfully"),r.debug(`New configuration version: ${Mt.default.yellow(l.version)}`),l}else return s.active}return s.active}emptyConfigPlaceholder(){return{version:0,id:"",firewallEnabled:!0,crs:null,rules:[],ips:[],projectKey:"",ownerId:"",updatedAt:new Date(0).toISOString()}}async putEmptyConfig(){let{$schema:t,...o}=wt();return r.debug("Empty Config:",o),this.putConfig(o)}async putConfig(t){return(await this.put(this.getUrl(),t)).active}async fetchActiveFirewallRules(){return(await this.fetchFirewallConfig())?.rules}async updateFirewallRule(t){let o=!t.id||t.id==="-",n={action:o?"rules.insert":"rules.update",id:o?null:t.id,value:{name:t.name,description:t.description,action:t.action,conditionGroup:t.conditionGroup,active:t.active}};return this.patch(this.getUrl(),n)}async createFirewallRule(t){return this.updateFirewallRule({...t,id:"-"})}async deleteFirewallRule(t){let o={action:"rules.remove",id:t.id,value:null};await this.patch(this.getUrl(),o)}async updateIPBlockingRule(t){let o=!t.id||t.id==="-",n={action:o?"ip.insert":"ip.update",id:o?null:t.id,value:{action:t.action,hostname:t.hostname,ip:t.ip,notes:t.notes??null}};return this.patch(this.getUrl(),n)}async createIPBlockingRule(t){return this.updateIPBlockingRule({...t,id:"-"})}async deleteIPBlockingRule(t){let o={action:"ip.remove",id:t.id,value:null};await this.patch(this.getUrl(),o)}async verifyCredentials(){try{return await this.fetchFirewallConfig(),!0}catch(t){return r.debug("Credential verification failed:",t),!1}}};var te=S(require("chalk"));T();T();var $e=class{validateConfig(e){let t=[],o=[];if(e||t.push({path:"root",message:"Configuration is required",code:"CONFIG_REQUIRED"}),e&&!e.rules&&t.push({path:"rules",message:"Rules array is required",code:"RULES_REQUIRED"}),e&&e.rules&&!Array.isArray(e.rules)&&t.push({path:"rules",message:"Rules must be an array",code:"RULES_INVALID_TYPE"}),e&&Array.isArray(e.rules)){let n=new Map;e.rules.forEach((s,a)=>{let l=s.id||s.name;if(!l)return;let c=n.get(l);if(c===void 0){n.set(l,a);return}let d=e.rules[c];o.push({path:`rules[${a}]`,message:s.id?`Rule "${s.name}" has the same id ("${s.id}") as rules[${c}] ("${d?.name}") \u2014 they will collide during sync diffing and one may be silently skipped.`:`Rule "${s.name}" has the same name as rules[${c}] and neither has an explicit id \u2014 they will collide during sync diffing and one may be silently skipped. Add unique ids to disambiguate.`,code:"DUPLICATE_RULE_IDENTIFIER"})})}return{valid:t.length===0,errors:t,warnings:o}}getHealthScore(e){let t=[],o=100;if(!e)return{score:0,grade:"poor",issues:[{severity:"error",category:"configuration",message:"No configuration found"}],recommendations:["Create a configuration file"]};if((!e.rules||e.rules.length===0)&&(o-=20,t.push({severity:"warning",category:"rules",message:"No rules defined",suggestion:"Add security rules to protect your application"})),e.rules&&e.rules.length>0){let a=e.rules.filter(l=>!l.description);a.length>0&&(o-=5,t.push({severity:"info",category:"maintainability",message:`${a.length} rule(s) missing descriptions`,suggestion:"Add descriptions to improve maintainability"}))}if(e.rules&&e.rules.length>0){let a=e.rules.filter(l=>l.active===!1||l.enabled===!1);a.length>0&&(o-=5,t.push({severity:"info",category:"maintenance",message:`${a.length} disabled rule(s) found`,suggestion:"Review and remove unused rules"}))}let n=this.calculateGrade(o),s=this.generateRecommendations(e,t);return{score:Math.max(0,o),grade:n,issues:t,recommendations:s}}diffItems(e,t,o,n="id"){let s=[],a=[],l=[],c=d=>d[n];for(let d of e){let u=t.find(p=>c(p)===c(d));u?o(d,u)||a.push(d):s.push(d)}for(let d of t)e.find(p=>c(p)===c(d))||l.push(d);return{toAdd:s,toUpdate:a,toDelete:l}}validateRuleCount(e,t){if(t&&e>t)throw new Error(`Rule count (${e}) exceeds provider limit (${t})`);t&&e>t*.9&&r.warn(`Approaching rule limit: ${e}/${t} rules`)}updateMetadata(e,t){return{...e,metadata:{...e.metadata,version:t,updatedAt:new Date().toISOString()}}}calculateGrade(e){return e>=80?"excellent":e>=60?"good":e>=40?"fair":"poor"}generateRecommendations(e,t){let o=[];return t.some(n=>n.category==="rules")&&o.push("Consider using predefined templates to get started"),t.some(n=>n.category==="maintainability")&&o.push("Add descriptions to all rules for better documentation"),t.some(n=>n.category==="maintenance")&&o.push("Remove or enable disabled rules to keep configuration clean"),o}logSyncStats(e){r.info(`Sync complete for ${this.name}:`),r.info(` Rules added: ${e.rulesAdded}`),r.info(` Rules updated: ${e.rulesUpdated}`),r.info(` Rules deleted: ${e.rulesDeleted}`),e.ipsAdded!==void 0&&(r.info(` IPs added: ${e.ipsAdded}`),r.info(` IPs updated: ${e.ipsUpdated}`),r.info(` IPs deleted: ${e.ipsDeleted}`)),e.version&&r.info(` New version: ${e.version}`)}};fe();function Gi(i){let e=[],t=[];i.conditionGroup.forEach((s,a)=>{for(let l of s.conditions){let c=Cn(l.op);l.op==="re"&&typeof l.value=="string"&&e.push(D.createWarning("regex_patterns",i.id,l.type,`Regular expression pattern may need adjustment for target provider: ${l.value}`,"Test the regex pattern in the target provider and adjust syntax if needed")),t.push({field:En(l.type),operator:c,value:l.value,...l.neg?{negated:!0}:{},...l.key?{key:l.key}:{},group:a})}}),t.length>10&&e.push(D.createWarning("many_conditions",i.id,void 0,`Rule has ${t.length} conditions which may impact performance`,"Consider splitting complex rules into multiple simpler rules for better performance"));let o={type:i.action.mitigate.action,...i.action.mitigate.rateLimit?{rateLimit:{requests:i.action.mitigate.rateLimit.requests,window:i.action.mitigate.rateLimit.window,...i.action.mitigate.rateLimit.characteristics?{characteristics:i.action.mitigate.rateLimit.characteristics}:{},...i.action.mitigate.rateLimit.mitigationTimeout?{mitigationTimeout:i.action.mitigate.rateLimit.mitigationTimeout}:{},...i.action.mitigate.rateLimit.countingExpression?{countingExpression:i.action.mitigate.rateLimit.countingExpression}:{}}}:{},...i.action.mitigate.redirect?{redirect:{location:i.action.mitigate.redirect.location,...i.action.mitigate.redirect.permanent?{permanent:i.action.mitigate.redirect.permanent}:{}}}:{},...i.action.mitigate.actionDuration?{duration:i.action.mitigate.actionDuration}:{}};return{result:{id:i.id,name:i.name,...i.description?{description:i.description}:{},enabled:i.active,conditions:t,conditionLogic:i.conditionGroup.length>1?"OR":"AND",action:o},warnings:e}}function Ki(i){let e=[],t=vn(i.conditions,i.id,e);if(i.action.response&&e.push(D.createUnsupportedFeatureWarning("custom response body","unified config","Vercel",i.id,"action.response")),t.length===0)throw new Error(`Rule "${i.name}" has no conditions Vercel can represent \u2014 every condition field is unsupported by Vercel (e.g. Cloudflare-only fields like referer/port). Cannot sync this rule to Vercel.`);return{result:{id:i.id,name:i.name,description:i.description,conditionGroup:t,action:{mitigate:{action:i.action.type,rateLimit:i.action.rateLimit?{requests:i.action.rateLimit.requests,window:i.action.rateLimit.window,characteristics:i.action.rateLimit.characteristics,mitigationTimeout:i.action.rateLimit.mitigationTimeout,countingExpression:i.action.rateLimit.countingExpression}:null,redirect:i.action.redirect?{location:i.action.redirect.location,permanent:i.action.redirect.permanent}:null,actionDuration:i.action.duration||null}},active:i.enabled},warnings:e}}function Hi(i){return{id:i.id,ip:i.ip,...i.hostname?{hostname:i.hostname}:{},...i.notes?{notes:i.notes}:{},action:i.action}}function vn(i,e,t){let o=new Map;for(let s of i){let a=s.group??0,l=o.get(a);l?l.push(s):o.set(a,[s])}let n=[];for(let s of o.values()){let a=[];for(let l of s){let c=An(l.field);if(!c){t.push(D.createUnsupportedFeatureWarning(`condition field '${l.field}'`,"unified config","Vercel",e,l.field));continue}a.push({op:bn(l.operator),neg:l.negated,type:c,key:l.key,value:l.value})}a.length>0&&n.push({conditions:a})}return n}function Cn(i){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists",nex:"not_exists"}[i]||"eq"}function bn(i){return{eq:"eq",starts_with:"pre",ends_with:"suf",in:"inc",contains:"sub",matches:"re",exists:"ex",not_exists:"nex"}[i]||"eq"}function En(i){return{host:"host",path:"path",method:"method",header:"header",query:"query",cookie:"cookie",ip_address:"ip",user_agent:"user_agent",geo_country:"country",geo_city:"city",geo_as_number:"asn",scheme:"scheme"}[i]||i}var Tn={host:"host",path:"path",method:"method",header:"header",query:"query",cookie:"cookie",ip:"ip_address",user_agent:"user_agent",country:"geo_country",city:"geo_city",asn:"geo_as_number",scheme:"scheme",target_path:"target_path",region:"region",protocol:"protocol",environment:"environment",geo_continent:"geo_continent",geo_country_region:"geo_country_region",ja4_digest:"ja4_digest",ja3_digest:"ja3_digest",rate_limit_api_id:"rate_limit_api_id"};function An(i){return Tn[i]??null}fe();T();function Ge(i){return i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Zi(i){let e="";for(let t=0;t<i.length;t++)i[t]==="\\"&&(i[t+1]==="\\"||i[t+1]==='"')?(e+=i[t+1],t++):e+=i[t];return e}var lt=class{static vercelToCloudflare={host:"http.host",path:"http.request.uri.path",method:"http.request.method",header:"http.request.headers",query:"http.request.uri.query",cookie:"http.cookie",target_path:"http.request.uri.path",ip_address:"ip.src",region:"ip.geoip.subdivision_1",protocol:"ssl",scheme:"ssl",environment:"",user_agent:"http.user_agent",geo_continent:"ip.geoip.continent",geo_country:"ip.geoip.country",geo_country_region:"ip.geoip.subdivision_1",geo_city:"ip.geoip.city",geo_as_number:"ip.geoip.asnum",ja4_digest:"",ja3_digest:"",rate_limit_api_id:""};static cloudflareToVercel={"http.host":"host","http.request.uri.path":"path","http.request.method":"method","http.request.headers":"header","http.request.uri.query":"query","http.cookie":"cookie","ip.src":"ip_address","ip.geoip.subdivision_1":"region",ssl:"protocol","http.user_agent":"user_agent","ip.geoip.continent":"geo_continent","ip.geoip.country":"geo_country","ip.geoip.city":"geo_city","ip.geoip.asnum":"geo_as_number"};static toCloudflare(e,t){let o=this.vercelToCloudflare[e];if(!o)throw r.warn(`No Cloudflare mapping for Vercel type: ${e}`),new Error(`Unsupported Vercel rule type for Cloudflare: ${e}`);return e==="header"&&t?`${o}["${Ge(t.toLowerCase())}"]`:e==="cookie"&&t?`${o}["${Ge(t)}"]`:o}static toVercel(e){let t=e.match(/http\.request\.headers\["([^"]+)"\]/);if(t)return{type:"header",key:t[1]};let o=e.match(/http\.cookie\["([^"]+)"\]/);if(o)return{type:"cookie",key:o[1]};if(e==="http.referer")return{type:"header",key:"referer"};let n=this.cloudflareToVercel[e];if(n)return{type:n};throw r.warn(`No Vercel mapping for Cloudflare field: ${e}`),new Error(`Unsupported Cloudflare field for Vercel: ${e}`)}static isCloudflareSupported(e){let t=this.vercelToCloudflare[e];return!!t&&t!==""}static isVercelSupported(e){return!!(this.cloudflareToVercel[e]||e==="http.referer"||e.startsWith("http.request.headers[")||e.startsWith("http.cookie["))}static getSupportedCloudflareFields(){return Object.values(this.vercelToCloudflare).filter(e=>e!=="")}static getSupportedVercelTypes(){return Object.keys(this.vercelToCloudflare).filter(e=>this.isCloudflareSupported(e))}};var Pn=new Set(["ip.src"]),ct=class{static fromVercelConditionGroups(e){if(!e||e.length===0)throw new Error("At least one condition group is required");let t=e.map(o=>{let n=o.conditions.map(s=>this.fromVercelCondition(s));if(n.length===0)throw new Error("Condition group must have at least one condition");return n.length>1?`(${n.join(" and ")})`:n[0]});return t.length>1?t.join(" or "):t[0]}static fromVercelCondition(e){let t=lt.toCloudflare(e.type,e.key),o=this.buildExistsOrComparisonExpression(t,e.op,()=>`${this.mapVercelOperator(e.op)} ${this.formatValue(t,e.value)}`);return e.neg&&(o=`not (${o})`),o}static fromUnifiedConditions(e,t="AND"){if(!e||e.length===0)throw new Error("At least one condition is required");if(!e.some(a=>a.group!==void 0)){let a=e.map(c=>this.fromUnifiedCondition(c)),l=t==="AND"?" and ":" or ";return a.length>1?`(${a.join(l)})`:a[0]}let n=new Map;for(let a of e){let l=a.group??0,c=n.get(l);c?c.push(a):n.set(l,[a])}let s=Array.from(n.values()).map(a=>this.combineWithAnd(a.map(l=>this.fromUnifiedCondition(l))));return s.length>1?this.combineWithOr(s):s[0]}static fromUnifiedCondition(e){let t=this.mapUnifiedFieldToCloudflare(e.field),o=e.key&&(e.field==="header"||e.field==="cookie")?`${t}["${Ge(e.key)}"]`:t,n=this.buildUnifiedExpression(o,e.operator,e.value);return e.negated&&(n=`not (${n})`),n}static buildExistsOrComparisonExpression(e,t,o){return t==="ex"||t==="exists"?`${e} exists`:t==="nex"||t==="not_exists"?`not (${e} exists)`:`${e} ${o()}`}static buildUnifiedExpression(e,t,o){return t==="not_contains"?`not (${e} contains ${this.formatValue(e,o)})`:t==="not_in"?`not (${e} in ${this.formatValue(e,o)})`:this.buildExistsOrComparisonExpression(e,t,()=>`${this.mapUnifiedOperator(t)} ${this.formatValue(e,o)}`)}static mapVercelOperator(e){return{eq:"eq",pre:"starts_with",suf:"ends_with",inc:"in",sub:"contains",re:"matches",ex:"exists"}[e]||e}static mapUnifiedOperator(e){return{eq:"eq",ne:"ne",contains:"contains",starts_with:"starts_with",ends_with:"ends_with",matches:"matches",in:"in",gt:"gt",ge:"ge",lt:"lt",le:"le",exists:"exists"}[e]||e}static mapUnifiedFieldToCloudflare(e){return{ip:"ip.src",country:"ip.geoip.country",region:"ip.geoip.subdivision_1",city:"ip.geoip.city",asn:"ip.geoip.asnum",path:"http.request.uri.path",host:"http.host",method:"http.request.method",header:"http.request.headers",query:"http.request.uri.query",cookie:"http.cookie",user_agent:"http.user_agent",referer:"http.referer",scheme:"ssl",port:"cf.edge.server_port"}[e]||e}static formatValue(e,t){return Array.isArray(t)?`{${t.map(n=>this.formatSingleValue(e,n)).join(" ")}}`:this.formatSingleValue(e,t)}static formatSingleValue(e,t){if(typeof t=="string"){if(Pn.has(e)){if(!ze.safeParse(t).success)throw new Error(`Invalid IP address or CIDR range: ${t}`);return t}return`"${Ge(t)}"`}return typeof t=="number"?String(t):typeof t=="boolean"?t?"true":"false":String(t)}static validate(e){if(!e||e.trim().length===0)return!1;let t=0;for(let o of e)if(o==="("&&t++,o===")"&&t--,t<0)return!1;return t===0}static combineWithAnd(e){if(e.length===0)throw new Error("At least one expression is required");return e.length===1?e[0]:`(${e.join(" and ")})`}static combineWithOr(e){if(e.length===0)throw new Error("At least one expression is required");return e.length===1?e[0]:`(${e.join(" or ")})`}};var $n={"ip.src":"ip","ip.geoip.country":"country","ip.geoip.subdivision_1":"region","ip.geoip.city":"city","ip.geoip.asnum":"asn","http.request.uri.path":"path","http.host":"host","http.request.method":"method","http.request.headers":"header","http.request.uri.query":"query","http.cookie":"cookie","http.user_agent":"user_agent","http.referer":"referer",ssl:"scheme","cf.edge.server_port":"port"},kn=new Set(["eq","ne","contains","starts_with","ends_with","matches","in","gt","ge","lt","le"]),_n=new Set(["and","or","not"]),he=class extends Error{};function Sn(i){let e=[],t=0,o=i.length;for(;t<o;){let n=i[t];if(/\s/.test(n)){t++;continue}if(n==="("){e.push({type:"LPAREN",value:n}),t++;continue}if(n===")"){e.push({type:"RPAREN",value:n}),t++;continue}if(n==="{"){e.push({type:"LBRACE",value:n}),t++;continue}if(n==="}"){e.push({type:"RBRACE",value:n}),t++;continue}if(n==="["){e.push({type:"LBRACKET",value:n}),t++;continue}if(n==="]"){e.push({type:"RBRACKET",value:n}),t++;continue}if(n==='"'){let a=t+1,l="",c=!1;for(;a<o;){let d=i[a];if(d==="\\"&&a+1<o){l+=d+i[a+1],a+=2;continue}if(i[a]==='"'){c=!0,a++;break}l+=i[a],a++}if(!c)throw new he("Unterminated string literal");e.push({type:"STRING",value:Zi(l)}),t=a;continue}let s=t;for(;s<o&&!/[\s(){}[\]"]/.test(i[s]);)s++;if(s===t)throw new he(`Unexpected character '${n}' at position ${t}`);e.push({type:"WORD",value:i.slice(t,s)}),t=s}return e}var Gt=class{constructor(e){this.tokens=e}tokens;pos=0;peek(){return this.tokens[this.pos]}next(){let e=this.tokens[this.pos];if(!e)throw new he("Unexpected end of expression");return this.pos++,e}expect(e,t){let o=this.next();if(o.type!==e||t!==void 0&&o.value!==t)throw new he(`Expected ${t??e} but got '${o.value}'`);return o}isWord(e){let t=this.peek();return!!t&&t.type==="WORD"&&t.value===e}atEnd(){return this.pos>=this.tokens.length}};function Kt(i){let e=[Yi(i)];for(;i.isWord("or");)i.next(),e.push(Yi(i));return e.length===1?e[0]:{type:"or",children:e}}function Yi(i){let e=[Ji(i)];for(;i.isWord("and");)i.next(),e.push(Ji(i));return e.length===1?e[0]:{type:"and",children:e}}function Ji(i){if(i.isWord("not")){i.next(),i.expect("LPAREN");let e=Kt(i);return i.expect("RPAREN"),{type:"not",child:e}}return Ln(i)}function Ln(i){let e=i.peek();if(e&&e.type==="LPAREN"){i.next();let t=Kt(i);return i.expect("RPAREN"),t}return xn(i)}function Un(i){let e=i.expect("WORD");if(_n.has(e.value))throw new he(`Expected a field reference but got keyword '${e.value}'`);if(i.peek()?.type==="LBRACKET"){i.next();let t=i.expect("STRING");return i.expect("RBRACKET"),{field:e.value,key:t.value}}return{field:e.value}}function Qi(i){let e=i.next();if(e.type==="STRING")return e.value;if(e.type==="WORD")return/^-?\d+(\.\d+)?$/.test(e.value)?Number(e.value):e.value;throw new he(`Unexpected token '${e.value}' where a value was expected`)}function Dn(i){if(i.peek()?.type==="LBRACE"){i.next();let e=[];for(;i.peek()?.type!=="RBRACE";)e.push(Qi(i));return i.expect("RBRACE"),e}return Qi(i)}function xn(i){let{field:e,key:t}=Un(i);if(i.isWord("exists"))return i.next(),{type:"exists",field:e,key:t};let o=i.next();if(o.type!=="WORD"||!kn.has(o.value))throw new he(`Unsupported or unrecognized operator '${o.value}'`);let n=Dn(i);return{type:"comparison",field:e,key:t,operator:o.value,value:n}}function On(i){let e=new Gt(Sn(i)),t=Kt(e);if(!e.atEnd())throw new he("Unexpected trailing tokens");return t}function It(i){return i.type==="comparison"||i.type==="exists"?!0:i.type==="not"?i.child.type==="comparison"||i.child.type==="exists":!1}function Rt(i,e){let t=i.type==="not",o=i.type==="not"?i.child:i;if(o.type!=="comparison"&&o.type!=="exists")return null;let n=$n[o.field];if(!n)return null;if(o.type==="exists")return{field:n,operator:t?"not_exists":"exists",value:"",key:o.key,group:e};let s=o.operator,a;return t&&(o.operator==="contains"?s="not_contains":o.operator==="in"?s="not_in":a=!0),{field:n,operator:s,value:o.value,key:o.key,negated:a,group:e}}function Fn(i){if(It(i)){let e=Rt(i,0);return e?{conditions:[e],conditionLogic:"AND"}:null}if(i.type==="and"){let e=[];for(let t of i.children){if(!It(t))return null;let o=Rt(t,0);if(!o)return null;e.push(o)}return{conditions:e,conditionLogic:"AND"}}if(i.type==="or"){let e=[];i.children.forEach((n,s)=>{if(It(n)){let a=Rt(n,s);a&&e.push(a);return}if(n.type==="and")for(let a of n.children){if(!It(a))return;let l=Rt(a,s);l&&e.push(l)}});let t=i.children.length;return new Set(e.map(n=>n.group)).size!==t?null:{conditions:e,conditionLogic:"OR"}}return null}function Ht(i){if(!i||!i.trim())return null;try{let e=On(i);return Fn(e)}catch{return null}}function Xi(i){let e=[],t=Ht(i.expression),o=[],n;t?(o=t.conditions,n=t.conditionLogic):e.push(D.createWarning("complex_expressions",i.id,"expression","Expression could not be parsed back into structured conditions \u2014 it may be hand-authored or use syntax outside what doorman itself generates.","Review the translated rule and add missing conditions manually if needed."));let s=i.action_parameters&&"response"in i.action_parameters?i.action_parameters.response:void 0,a={type:Nn(i.action),rateLimit:i.ratelimit?{requests:i.ratelimit.requests_per_period,window:`${i.ratelimit.period}s`,characteristics:i.ratelimit.characteristics,mitigationTimeout:i.ratelimit.mitigation_timeout,countingExpression:i.ratelimit.counting_expression}:void 0,response:s?{statusCode:s.status_code,content:s.content,contentType:s.content_type}:void 0};return{result:{id:i.id,name:i.description||`Rule ${i.id}`,description:i.description,enabled:i.enabled??!0,conditions:o,conditionLogic:n,action:a},warnings:e}}function eo(i){let e=[],t=ct.fromUnifiedConditions(i.conditions,i.conditionLogic),o={id:i.id||crypto.randomUUID(),action:Vn(i.action.type),expression:t,description:i.description||i.name,enabled:i.enabled};return i.action.rateLimit&&(o.ratelimit={characteristics:i.action.rateLimit.characteristics||["ip.src"],period:Bn(i.action.rateLimit.window),requests_per_period:i.action.rateLimit.requests},i.action.rateLimit.mitigationTimeout?o.ratelimit.mitigation_timeout=i.action.rateLimit.mitigationTimeout:(o.ratelimit.mitigation_timeout=3600,e.push(D.createWarning("rate_limiting_precision",i.id,"action.rateLimit.mitigationTimeout",`No mitigationTimeout set for rate limit rule "${i.name}" \u2014 defaulted to Cloudflare's 3600s (1 hour) block duration.`))),i.action.rateLimit.countingExpression&&(o.ratelimit.counting_expression=i.action.rateLimit.countingExpression)),i.action.type==="redirect"&&i.action.redirect&&(o.action_parameters={from_value:{status_code:i.action.redirect.statusCode??(i.action.redirect.permanent?301:302),target_url:{value:i.action.redirect.location},...i.action.redirect.preserveQueryString!==void 0?{preserve_query_string:i.action.redirect.preserveQueryString}:{}}}),i.action.response&&(o.action!=="block"?e.push(D.createUnsupportedFeatureWarning(`custom response on a '${o.action}' action`,"unified config","Cloudflare",i.id,"action.response")):i.action.response.content?o.action_parameters={response:{status_code:i.action.response.statusCode??403,content:i.action.response.content,content_type:i.action.response.contentType??"text/plain"}}:e.push(D.createWarning("lossy_conversion",i.id,"action.response","Custom response declared without `content`; Cloudflare requires a response body, so it was dropped.","Set action.response.content to the body you want returned."))),{result:o,warnings:e}}function to(i){if(!ze.safeParse(i.ip).success)throw new Error(`Invalid IP address or CIDR range: ${i.ip}`);let t=i.ip.includes("/")?`ip.src in {${i.ip}}`:`ip.src eq ${i.ip}`;return{id:i.id||crypto.randomUUID(),action:i.action==="allow"?"allow":"block",expression:t,description:i.notes||`IP ${i.action}: ${i.ip}${i.hostname?` (${i.hostname})`:""}`,enabled:!0}}function Nn(i){return{block:"deny",challenge:"challenge",managed_challenge:"challenge",js_challenge:"challenge",log:"log",skip:"bypass",allow:"allow",rewrite:"bypass",redirect:"redirect"}[i]||"deny"}function Vn(i){return{log:"log",deny:"block",block:"block",challenge:"managed_challenge",bypass:"skip",rate_limit:"block",redirect:"redirect",allow:"allow"}[i]||"block"}function Bn(i){let e=i.match(/^(\d+)([smhd])$/);if(!e||!e[1]||!e[2])throw new Error(`Invalid window format: ${i}`);let t=parseInt(e[1],10),o=e[2],s={s:1,m:60,h:3600,d:86400}[o];if(s===void 0)throw new Error(`Invalid time unit: ${o}`);return t*s}fe();function se(i,e,t){return D.createWarning("complex_expressions",i,void 0,e,t)}var Wn={ip:"ip",path:"path",domain:"host",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},jn={ip:"ip",path:"path",host:"domain",method:"method",country:"country",scheme:"scheme",user_agent:"user_agent"},qn={header:"request_header",query:"query_parameter",cookie:"request_cookie"},zn={request_header:"header",query_parameter:"query",request_cookie:"cookie",response_header:"response_header",post_parameter:"post_parameter",signal:"signal"};function Mn(i){return Wn[i]??i}function Gn(i){return jn[i]??null}var Kn={equals:{operator:"eq",negated:!1},does_not_equal:{operator:"eq",negated:!0},contains:{operator:"contains",negated:!1},does_not_contain:{operator:"contains",negated:!0},like:{operator:"matches",negated:!1},not_like:{operator:"matches",negated:!0},in_list:{operator:"in",negated:!1},not_in_list:{operator:"in",negated:!0},matches:{operator:"matches",negated:!1},does_not_match:{operator:"matches",negated:!0},greater_equal:{operator:"ge",negated:!1},lesser_equal:{operator:"le",negated:!1}};function io(i){return Kn[i]??{operator:"eq",negated:!1}}function oo(i,e,t,o){switch(i){case"eq":return e?"does_not_equal":"equals";case"ne":return"does_not_equal";case"contains":return e?"does_not_contain":"contains";case"not_contains":return"does_not_contain";case"starts_with":case"ends_with":return t.push(D.createWarning("regex_patterns",o,void 0,`Unified operator "${i}" has no direct Fastly equivalent \u2014 mapped to Fastly's wildcard "like" operator. Verify the translated value still matches as a wildcard pattern.`)),e?"not_like":"like";case"matches":return t.push(D.createWarning("regex_patterns",o,void 0,"Regular expression pattern may need adjustment for Fastly Next-Gen WAF regex syntax.")),e?"does_not_match":"matches";case"in":return e?"not_in_list":"in_list";case"not_in":return"not_in_list";case"gt":return t.push(se(o,'Unified operator "gt" (strictly greater than) has no Fastly equivalent \u2014 mapped to "greater_equal", which also matches the boundary value itself.')),"greater_equal";case"ge":return"greater_equal";case"lt":return t.push(se(o,'Unified operator "lt" (strictly less than) has no Fastly equivalent \u2014 mapped to "lesser_equal", which also matches the boundary value itself.')),"lesser_equal";case"le":return"lesser_equal";default:return"equals"}}function Hn(i,e){let t=[],o=i.conditions.filter(s=>s.type==="group"),n=i.conditions.filter(s=>s.type!=="group");if(o.length>0&&n.length===0&&i.group_operator==="any")return o.forEach((s,a)=>{s.group_operator!=="all"&&e.push(se(i.id,`A condition group using "any" (OR) inside an outer "any" (OR) rule cannot be represented in doorman's flat AND-within/OR-across condition model \u2014 its members were kept in the same group (effectively AND'd) instead of OR'd. Review the translated rule against the original Fastly logic.`));for(let l of s.conditions)vt(t,l,a,e,i.id)}),{conditions:t,conditionLogic:o.length>1?"OR":"AND"};if(o.length===0)return n.forEach((s,a)=>{let l=i.group_operator==="any"?a:0;vt(t,s,l,e,i.id)}),{conditions:t,conditionLogic:i.group_operator==="any"&&n.length>1?"OR":"AND"};e.push(se(i.id,`Rule mixes top-level conditions with condition groups under group_operator "${i.group_operator}" \u2014 this doesn't fit doorman's flat AND-within/OR-across condition model. All conditions were combined with AND; review the translated rule against the original Fastly rule logic.`));for(let s of n)vt(t,s,0,e,i.id);for(let s of o)for(let a of s.conditions)vt(t,a,0,e,i.id);return{conditions:t,conditionLogic:"AND"}}function vt(i,e,t,o,n){if(e.type==="single"){let{operator:u,negated:p}=io(e.operator);i.push({field:Mn(e.field),operator:u,value:e.value,...p?{negated:!0}:{},group:t});return}let s=zn[e.field],a=e.conditions.find(u=>u.field==="name"),l=e.conditions.find(u=>u.field==="value"||u.field==="value_string");if(!l){o.push(se(n,`Multival condition on '${e.field}' has no value sub-condition doorman could extract (only a 'name' existence check) \u2014 skipped.`));return}let{operator:c,negated:d}=io(l.operator);i.push({field:s,operator:c,value:l.value,...d?{negated:!0}:{},...a?{key:a.value}:{},group:t})}function Zn(i,e){i.actions.length>1&&e.push(se(i.id,`Rule has ${i.actions.length} actions \u2014 doorman only models one action per rule; only the first ("${i.actions[0]?.type}") was translated.`));let t=i.actions[0];if(i.type==="rate_limit")return{type:"rate_limit",rateLimit:i.rate_limit?{requests:i.rate_limit.threshold,window:`${i.rate_limit.interval}s`,mitigationTimeout:i.rate_limit.duration}:void 0};switch(t?.type){case"block":return{type:"block"};case"allow":return{type:"allow"};case"browser_challenge":case"dynamic_challenge":case"verify_token":return{type:"challenge"};case"redirect":return{type:"redirect",redirect:{location:t.redirect_url??"",...t.response_code!==void 0?{statusCode:t.response_code}:{}}};case"add_signal":case"exclude_signal":case"deception":return e.push(D.createWarning("action_differences",i.id,"action.type",`Fastly action "${t.type}" tags or excludes a WAF signal rather than allowing/blocking the request \u2014 doorman has no matching action type. Mapped to "log" as the closest non-destructive fallback; review this rule.`)),{type:"log"};default:return e.push(se(i.id,`Unrecognised Fastly action type "${String(t?.type)}" \u2014 mapped to "log".`)),{type:"log"}}}function no(i){let e=[],{conditions:t,conditionLogic:o}=Hn(i,e),n=Zn(i,e);return t.length>10&&e.push(D.createWarning("many_conditions",i.id,void 0,`Rule has ${t.length} conditions which may impact performance`)),{result:{id:i.id,name:i.description||i.id,enabled:i.enabled,conditions:t,conditionLogic:o,action:n},warnings:e}}function Yn(i,e,t){let o=new Map;for(let a of i){let l=a.group??0,c=o.get(l);c?c.push(a):o.set(l,[a])}let n=a=>{let l=qn[a.field];if(l){if(a.key===void 0)return t.push(se(e,`Condition on '${a.field}' has no 'key' set \u2014 Fastly needs a specific ${a.field} name to match on (e.g. a header name). Skipped.`)),null;let d=l==="request_header"||l==="response_header"?"value_string":"value";return{type:"multival",field:l,operator:"exists",group_operator:"all",conditions:[{type:"single",field:"name",operator:"equals",value:a.key},{type:"single",field:d,operator:oo(a.operator,a.negated,t,e),value:String(a.value)}]}}let c=Gn(a.field);return c?{type:"single",field:c,operator:oo(a.operator,a.negated,t,e),value:String(a.value)}:(t.push(D.createUnsupportedFeatureWarning(`condition field '${a.field}'`,"unified config","Fastly",e,a.field)),null)};if(o.size<=1){let a=i.map(n).filter(l=>l!==null);return{conditions:a.filter(l=>l.type==="single"),groupConditions:[],multivalConditions:a.filter(l=>l.type==="multival"),groupOperator:"all"}}let s=[];for(let a of o.values()){let l=a.map(n).filter(c=>c!==null);l.length>0&&s.push({type:"group",group_operator:"all",conditions:l})}return{conditions:[],groupConditions:s,multivalConditions:[],groupOperator:"any"}}function Jn(i,e,t){switch(i.type){case"block":case"deny":return{type:"block"};case"allow":return{type:"allow"};case"challenge":return{type:"browser_challenge"};case"bypass":return e.push(se(t,'Unified action "bypass" has no direct Fastly equivalent \u2014 mapped to "allow".')),{type:"allow"};case"log":return e.push(se(t,'Unified action "log" has no dedicated Fastly action \u2014 mapped to "allow" (request_logging is enabled at the rule level regardless).')),{type:"allow"};case"redirect":return i.redirect?{type:"redirect",redirect_url:i.redirect.location,response_code:i.redirect.statusCode??(i.redirect.permanent?301:302)}:(e.push(se(t,'Unified action "redirect" has no redirect target \u2014 mapped to "allow".')),{type:"allow"});case"rate_limit":return{type:"block_signal"};default:return e.push(D.createUnsupportedFeatureWarning(`action type '${i.type}'`,"unified config","Fastly",t,"action.type")),{type:"block"}}}function Qn(i,e,t){let o=/^(\d+)\s*(s|m|h)?$/i.exec(i.trim()),n={s:1,m:60,h:3600},s=o?Number(o[1])*n[o[2]?.toLowerCase()||"s"]:NaN,a=[60,600,3600];if(!Number.isFinite(s)||s<=0)return e.push(D.createWarning("rate_limiting_precision",t,void 0,`Rate limit window "${i}" could not be parsed \u2014 defaulted to Fastly's 60-second interval.`)),60;let l=a.reduce((c,d)=>Math.abs(d-s)<Math.abs(c-s)?d:c);return l!==s&&e.push(D.createWarning("rate_limiting_precision",t,void 0,`Rate limit window "${i}" (${s}s) isn't one of Fastly's supported intervals (60s/600s/3600s) \u2014 rounded to ${l}s.`)),l}function Xn(i,e,t){if(!i)throw new Error(`Rule "${e??"(unnamed)"}" has action type "rate_limit" but no rateLimit configuration \u2014 Fastly requires a threshold and interval.`);let o=Qn(i.window,t,e);return t.push(D.createWarning("rate_limiting_precision",e,void 0,`Fastly rate-limit rules count requests against a named custom signal, which doorman does not create automatically \u2014 create a signal named "doorman-rate-limit-${e??"rule"}" in this workspace before syncing, or the rule will be rejected.`)),{client_identifiers:[{type:"ip"}],duration:i.mitigationTimeout??o,interval:o,signal:`doorman-rate-limit-${e??"rule"}`,threshold:i.requests}}function ro(i){let e=[];i.description&&i.description!==i.name&&e.push(se(i.id,'Fastly rules have no separate "name" field \u2014 only "description" carries over, and it was set from this rule\'s `name`. The `description` text was dropped rather than merged in, to keep it round-trip-stable on the next sync.'));let{conditions:t,groupConditions:o,multivalConditions:n,groupOperator:s}=Yn(i.conditions,i.id,e);if(t.length===0&&o.length===0&&n.length===0)throw new Error(`Rule "${i.name}" has no conditions Fastly can represent \u2014 every condition field is unsupported by Fastly. Cannot sync this rule to Fastly.`);let a=i.action.type==="rate_limit";return{result:{type:a?"rate_limit":"request",description:i.name,enabled:i.enabled,group_operator:s,request_logging:"sampled",conditions:t,group_conditions:o,multival_conditions:n,actions:[Jn(i.action,e,i.id)],rate_limit:a?Xn(i.action.rateLimit,i.id,e):null},warnings:e}}function so(i,e){return i.map(t=>({ip:t,action:e}))}function ao(i){let e=[],t=[],o=[];for(let n of i)(n.hostname||n.notes)&&e.push(se(n.id,`IP rule "${n.ip}" sets ${n.hostname?"`hostname`":""}${n.hostname&&n.notes?" and ":""}${n.notes?"`notes`":""} \u2014 Fastly IP lists have no equivalent per-entry metadata; only the address was kept.`)),(n.action==="allow"?o:t).push(n.ip);return{result:{denyEntries:t,allowEntries:o},warnings:e}}var $=class{static vercelToUnified=Gi;static unifiedToVercel=Ki;static vercelIPToUnified=Hi;static cloudflareToUnified=Xi;static unifiedToCloudflare=eo;static unifiedIPToCloudflare=to;static fastlyToUnified=no;static unifiedToFastly=ro;static fastlyListEntriesToUnified=so;static unifiedIPsToFastlyEntries=ao};fe();function Ke(i,e){if(i===e)return!0;if(typeof i!="object"||i===null||typeof e!="object"||e===null||Array.isArray(i)!==Array.isArray(e))return!1;let t=Object.keys(i),o=Object.keys(e);if(t.length!==o.length)return!1;for(let n of t)if(!o.includes(n)||!Ke(i[n],e[n]))return!1;return!0}function ke(i){let{id:e,...t}=i;return t}function dt(i){return[...i].sort((e,t)=>{let o=e.priority!==void 0,n=t.priority!==void 0;return!o&&!n?0:o?n?e.priority-t.priority:-1:1})}function Ct(i){return i.some(e=>e.priority!==void 0)}var He=class extends $e{constructor(t){super();this.client=t}client;name="vercel";async fetchConfig(t){try{r.debug("Fetching Vercel firewall configuration");let o=await this.client.fetchFirewallConfig(t),n=o.rules.map(a=>{let l=$.vercelToUnified(a);return l.warnings.length>0&&l.warnings.forEach(c=>{let{TranslationWarningSystem:d}=(fe(),ye(De)),u=d.formatWarning(c);r.warn(`Rule ${a.name}:
|
|
25
|
+
${u}`)}),l.result}),s=o.ips.map(a=>$.vercelIPToUnified(a));return{version:"2.0",provider:"vercel",providers:{vercel:{projectId:this.client.projectId,...this.client.teamId?{teamId:this.client.teamId}:{}}},rules:n,ips:s,metadata:{version:o.version,updatedAt:o.updatedAt}}}catch(o){throw r.error("Error fetching Vercel configuration:",o),new Error("Failed to fetch Vercel firewall configuration")}}async syncRules(t,o={}){let{dryRun:n=!1}=o;try{let{OperationSafety:s}=(Tt(),ye(Et)),a=await s.performDryRunValidation(t,"sync rules",async f=>await this.getChanges(f,{allowCreate:!n}));if(!a.valid)throw new Error(`Dry-run validation failed: ${a.issues.join(", ")}`);let l=a.changes,{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u,version:p}=l,g=l.ipsToAdd||[],h=l.ipsToUpdate||[],I=l.ipsToDelete||[];if(n)return r.info("Dry run mode. The following changes would be made:"),r.info(`Custom Rules - Add: ${c.length}, Update: ${d.length}, Delete: ${u.length}`),r.info(`IP Rules - Add: ${g.length}, Update: ${h.length}, Delete: ${I.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,version:p,warnings:a.warnings};let R=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Vercel project ${this.client.projectId}`,changes:l,riskLevel:R,skipConfirmation:o.force||!1,dryRun:!1,allowDeletions:o.allowDeletions||!1}))throw new Error("Operation cancelled by user");let Z=c.map(f=>$.unifiedToVercel(f).result),W=d.map(f=>$.unifiedToVercel(f).result),ue=u.map(f=>$.unifiedToVercel(f).result),me=g.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),_e=h.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),_=I.map(f=>({id:f.id||"",ip:f.ip,hostname:f.hostname||"",action:f.action,notes:f.notes})),Ce=[],be=[],Ee=[],We=[],Se=[],je=[],C=[],V=(f,b)=>`${f}: ${b instanceof Error?b.message:String(b)}`,ie=[];Ct(t.rules)&&t.rules.length>c.length&&ie.push("Rule `priority` is best-effort on Vercel: new rules are created in priority order, but rules that already exist remotely cannot be repositioned via the Vercel API. Recreate them (remove and re-add) if exact evaluation order matters.");let ae=[];for(let f of ue)try{r.debug(`Deleting custom rule: ${f.id}`),await this.client.deleteFirewallRule(f),Ee.push(f),r.debug(`Custom rule deleted: ${f.id}`)}catch(b){r.error(`Failed to delete custom rule ${f.id}:`,b),C.push(V(`Failed to delete custom rule ${f.id}`,b))}for(let f of _)try{r.debug(`Deleting IP blocking rule: ${f.id}`),await this.client.deleteIPBlockingRule(f),je.push(f),r.debug(`IP blocking rule deleted: ${f.id}`)}catch(b){r.error(`Failed to delete IP blocking rule ${f.id}:`,b),C.push(V(`Failed to delete IP blocking rule ${f.id}`,b))}for(let f of Z)try{r.debug(`Adding new custom rule: ${f.name}`);let b=await this.client.createFirewallRule(f);Ce.push(b),b.id&&b.id!==f.id&&ae.push({oldId:f.id||void 0,newId:b.id,name:f.name}),r.debug(`New custom rule added: ${b.id}`)}catch(b){r.error(`Failed to add custom rule "${f.name}":`,b),C.push(V(`Failed to add custom rule "${f.name}"`,b))}for(let f of me)try{r.debug(`Adding new IP blocking rule: ${f.ip}`);let b=await this.client.createIPBlockingRule(f);We.push(b),r.debug(`New IP blocking rule added: (hostname): ${b.hostname} (ip): ${b.ip}`)}catch(b){r.error(`Failed to add IP blocking rule ${f.ip}:`,b),C.push(V(`Failed to add IP blocking rule ${f.ip}`,b))}for(let f of W)try{r.debug(`Updating custom rule: ${f.id}`);let b=await this.client.updateFirewallRule(f);be.push(b),r.debug(`Custom rule updated: ${b.id}`)}catch(b){r.error(`Failed to update custom rule ${f.id}:`,b),C.push(V(`Failed to update custom rule ${f.id}`,b))}for(let f of _e)try{r.debug(`Updating IP blocking rule: ${f.id}`);let b=await this.client.updateIPBlockingRule(f);Se.push(b),r.debug(`IP blocking rule updated: ${b.id}`)}catch(b){r.error(`Failed to update IP blocking rule ${f.id}:`,b),C.push(V(`Failed to update IP blocking rule ${f.id}`,b))}r.debug(`${te.default.underline("Custom Rules:")} ${te.default.green("Added:")} ${te.default.green(Ce.length)}, ${te.default.cyan("Updated:")} ${te.default.cyan(be.length)}, ${te.default.red("Deleted:")} ${te.default.red(Ee.length)}`),r.debug(`${te.default.underline("IP Rules:")} ${te.default.green("Added:")} ${te.default.green(We.length)}, ${te.default.cyan("Updated:")} ${te.default.cyan(Se.length)}, ${te.default.red("Deleted:")} ${te.default.red(je.length)}`);let ot=p,nt,Te=[...ie];try{let f=await this.client.fetchFirewallConfig();ot=f.version,nt=f.updatedAt;let b=new Set(f.rules.map(F=>F.id)),yi=new Set(f.ips.map(F=>F.id));for(let F of[...Ce,...be])F.id&&!b.has(F.id)&&Te.push(`Rule "${F.name}" (${F.id}) was synced but is missing from the post-sync remote config \u2014 a subsequent sync may re-create or misdiff it.`);for(let F of Ee)F.id&&b.has(F.id)&&Te.push(`Rule "${F.name}" (${F.id}) was deleted but still appears in the post-sync remote config.`);for(let F of[...We,...Se])F.id&&!yi.has(F.id)&&Te.push(`IP rule "${F.ip}" (${F.id}) was synced but is missing from the post-sync remote config \u2014 a subsequent sync may re-create or misdiff it.`);for(let F of je)F.id&&yi.has(F.id)&&Te.push(`IP rule "${F.ip}" (${F.id}) was deleted but still appears in the post-sync remote config.`)}catch(f){r.error("Failed to fetch updated firewall configuration version after sync:",f),C.push(V("Failed to fetch updated configuration version after sync",f))}return{success:C.length===0,rulesAdded:Ce.length,rulesUpdated:be.length,rulesDeleted:Ee.length,ipsAdded:We.length,ipsUpdated:Se.length,ipsDeleted:je.length,version:ot,updatedAt:nt,idRemappings:ae.length>0?ae:void 0,errors:C.length>0?C:void 0,warnings:Te.length>0?Te:void 0}}catch(s){throw r.error("Error during sync:",s),new Error(`Failed to synchronize firewall rules: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async getChanges(t,o){let n=Le.safeParse(t);if(!n.success)throw new Error(`Invalid firewall configuration: ${n.error.message}`);try{r.debug("Fetching existing firewall configuration");let s=await this.client.fetchFirewallConfig(void 0,{allowCreate:o?.allowCreate??!0});r.debug(`Fetched ${s.rules.length} custom rules and ${s.ips.length} IP blocking rules`);let a=s.rules.map(I=>{let R=$.vercelToUnified(I);return R.warnings.length>0&&R.warnings.forEach(N=>{let{TranslationWarningSystem:Z}=(fe(),ye(De)),W=Z.formatWarning(N);r.warn(`Rule ${I.name}:
|
|
26
26
|
${W}`)}),R.result}),{toAdd:l,toUpdate:c,toDelete:d}=this.diffRules(dt(t.rules),a),u=s.ips.map(I=>$.vercelIPToUnified(I)),{ipsToAdd:p,ipsToUpdate:g,ipsToDelete:h}=this.diffIPRules(t.ips||[],u);return{version:s.version,rulesToAdd:l,rulesToUpdate:c,rulesToDelete:d,ipsToAdd:p,ipsToUpdate:g,ipsToDelete:h,hasChanges:l.length>0||c.length>0||d.length>0||p.length>0||g.length>0||h.length>0}}catch(s){throw r.error("Error fetching existing firewall configuration:",s),new Error("Failed to fetch existing firewall configuration")}}getSupportedFeatures(){return{supportsCustomRules:!0,supportsIPBlocking:!0,supportsRateLimiting:!0,supportsGeoBlocking:!0,supportsManagedRules:!1,supportsRedirect:!0,supportsChallenge:!0}}async verifyCredentials(){return this.client.verifyCredentials()}validateConfig(t){let o=super.validateConfig(t),n=[...o.errors],s=[...o.warnings];t.provider&&t.provider!=="vercel"&&n.push({path:"provider",message:"Provider must be 'vercel' for VercelFirewallService",code:"INVALID_PROVIDER"});try{let a=Ae.safeParse(t);a.success||n.push({path:"root",message:`Schema validation failed: ${a.error.message}`,code:"SCHEMA_VALIDATION_FAILED"})}catch(a){r.debug("Schema validation error:",a)}return{valid:n.length===0,errors:n,warnings:s}}getHealthScore(t){let o=super.getHealthScore(t),n=[...o.issues],s=o.score;return t.rules.filter(l=>l.action?.type==="rate_limit").length===0&&(s-=10,n.push({severity:"info",category:"security",message:"No rate limiting rules configured",suggestion:"Consider adding rate limiting to protect against abuse"})),(!t.ips||t.ips.length===0)&&n.push({severity:"info",category:"security",message:"No IP blocking rules configured",suggestion:"Consider blocking known malicious IPs"}),{score:Math.max(0,s),grade:o.grade,issues:n,recommendations:o.recommendations}}diffRules(t,o){let n=[],s=[],a=[...o];for(let l of t){let c=o.find(d=>d.id===l.id);if(!c)n.push(l);else{Ke(ke(l),ke(c))||s.push({...l,id:c.id});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{toAdd:n,toUpdate:s,toDelete:a}}diffIPRules(t,o){let n=[],s=[],a=[...o];for(let l of t){let c=o.find(d=>d.id===l.id);if(!c)r.debug("Rule not found in existing rules:",{configRule:l}),n.push(l);else{Ke(ke(l),ke(c))||s.push({...c,...l});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{ipsToAdd:n,ipsToUpdate:s,ipsToDelete:a}}};T();var Ze=class{static fromEnv(){let e=process.env.VERCEL_TOKEN,t=process.env.VERCEL_PROJECT_ID,o=process.env.VERCEL_TEAM_ID;if(!e)throw new Error("VERCEL_TOKEN environment variable is required");if(!t)throw new Error("VERCEL_PROJECT_ID environment variable is required");let n=new Me(t,o,e);return new He(n)}static fromConfig(e){let t=e.token||process.env.VERCEL_TOKEN,o=e.projectId||process.env.VERCEL_PROJECT_ID,n=e.teamId||process.env.VERCEL_TEAM_ID;if(!t)throw new Error("Vercel API token is required (provide token or set VERCEL_TOKEN env var)");if(!o)throw new Error("Vercel project ID is required (provide projectId or set VERCEL_PROJECT_ID env var)");r.debug("Creating Vercel provider with config:",{projectId:o,teamId:n});let s=new Me(o,n,t);return new He(s)}static create(e,t,o){return this.fromConfig({projectId:e,teamId:t,token:o})}};var uo=require("crypto");T();var xe=S(require("chalk")),m=class i extends Error{code;suggestion;details;docsUrl;cause;constructor(e){super(e.message),this.name="DoormanError",this.code=e.code,this.suggestion=e.suggestion,this.details=e.details,this.docsUrl=e.docsUrl,this.cause=e.cause,Error.captureStackTrace&&Error.captureStackTrace(this,i)}format(){let e=[];return e.push(xe.default.red.bold(`[${this.code}] ${this.message}`)),e.push(""),this.suggestion&&(e.push(xe.default.yellow.bold("Suggestion:")),e.push(` ${this.suggestion}`),e.push("")),this.details&&Object.keys(this.details).length>0&&(e.push(xe.default.dim("Details:")),Object.entries(this.details).forEach(([t,o])=>{let n=typeof o=="object"?JSON.stringify(o,null,2).split(`
|
|
27
27
|
`).join(`
|
|
28
28
|
`):o;e.push(` ${xe.default.cyan(t)}: ${n}`)}),e.push("")),this.cause&&(e.push(xe.default.dim("Caused by:")),e.push(` ${this.cause.message}`),e.push("")),this.docsUrl&&(e.push(xe.default.cyan.bold("Documentation:")),e.push(` ${this.docsUrl}`),e.push("")),e.join(`
|
|
@@ -35,16 +35,16 @@ ${W}`)}),R.result}),{toAdd:l,toUpdate:c,toDelete:d}=this.diffRules(dt(t.rules),a
|
|
|
35
35
|
\u2022 Ensure your API token has Account:Read permissions
|
|
36
36
|
\u2022 Verify the account ID is correct
|
|
37
37
|
\u2022 Check token permissions in Cloudflare dashboard`)):o.includes("not found")?(r.warn(`\u{1F6AB} Lists API resource not found during ${t}. Falling back to individual IP rules.`),r.info("\u{1F4A1} This may be temporary - the List will be recreated on next sync if Lists API is available.")):o.includes("rate limit")||o.includes("quota")?(r.warn(`\u{1F6AB} Lists API rate limited during ${t}. Falling back to individual IP rules.`),r.info("\u{1F4A1} Lists API rate limit reached. Individual rules will be used this time. Consider retrying later or upgrading your Cloudflare plan.")):(r.warn(`\u{1F6AB} Lists API error during ${t}: ${e.message}. Falling back to individual IP rules.`),r.info("\u{1F4A1} Lists API temporarily unavailable. Using individual IP rules as fallback. Check Cloudflare status if this persists."))}else r.warn(`\u{1F6AB} Unknown Lists API error during ${t}. Falling back to individual IP rules.`)}};var Qe=class{static create(e,t,o){let n=e||process.env.CLOUDFLARE_API_TOKEN,s=t||process.env.CLOUDFLARE_ZONE_ID,a=o||process.env.CLOUDFLARE_ACCOUNT_ID;if(!n)throw new Error("Cloudflare API token is required. Set CLOUDFLARE_API_TOKEN environment variable or pass as parameter.");if(!s)throw new Error("Cloudflare Zone ID is required. Set CLOUDFLARE_ZONE_ID environment variable or pass as parameter.");return new ut(n,s,a)}static fromEnv(){return this.create()}static fromConfig(e){return this.create(e.apiToken,e.zoneId,e.accountId)}};T();T();var po=process.env.DOORMAN_FASTLY_API_BASE_URL||"https://api.fastly.com",pt="doorman-managed-deny",ft="doorman-managed-allow",Xe=class extends Pe{constructor(t,o){super(po,"fastly");this.workspaceId=t;this.apiToken=o}workspaceId;apiToken;getAuthHeaders(){return{"Fastly-Key":this.apiToken}}workspacePath(...t){return["/ngwaf/v1/workspaces",this.workspaceId,...t].join("/")}async fetchRules(){return(await this.get(this.workspacePath("rules"))).data}async createRule(t){return this.post(this.workspacePath("rules"),t)}async updateRule(t,o){return this.patch(this.workspacePath("rules",t),o)}async deleteRule(t){await this.delete(this.workspacePath("rules",t))}async fetchLists(){return(await this.get(this.workspacePath("lists"))).data}async createList(t,o){return this.post(this.workspacePath("lists"),{name:t,type:"ip",description:"Managed by doorman \u2014 do not edit entries directly, they will be overwritten on the next sync.",entries:o})}async updateListEntries(t,o){return this.patch(this.workspacePath("lists",t),{entries:o})}async findList(t){return(await this.fetchLists()).find(n=>n.name===t&&n.type==="ip")??null}async getOrCreateList(t){let o=await this.findList(t);return o||(r.debug(`Creating Fastly list "${t}" in workspace ${this.workspaceId}`),this.createList(t,[]))}async fetchWorkspace(){return this.get(this.workspacePath())}async verifyCredentials(){try{return await this.fetchWorkspace(),!0}catch(t){return r.debug("Credential verification failed:",t),!1}}};T();var et=class extends $e{constructor(t){super();this.client=t}client;name="fastly";async fetchConfig(){try{r.debug("Fetching Fastly Next-Gen WAF configuration");let[t,o,n]=await Promise.all([this.client.fetchRules(),this.client.findList(pt),this.client.findList(ft)]),s=this.translateFastlyRules(t),a=[...$.fastlyListEntriesToUnified(o?.entries??[],"deny"),...$.fastlyListEntriesToUnified(n?.entries??[],"allow")];return{version:"2.0",provider:"fastly",providers:{fastly:{workspaceId:this.client.workspaceId}},rules:s,ips:a}}catch(t){throw r.error("Error fetching Fastly configuration:",t),new Error("Failed to fetch Fastly Next-Gen WAF configuration")}}translateFastlyRules(t){let o=[];for(let n of t){if(n.type!=="request"&&n.type!=="rate_limit"){r.debug(`Skipping Fastly rule ${n.id} \u2014 type "${n.type}" is not a request/rate_limit rule doorman manages`);continue}let s=$.fastlyToUnified(n);s.warnings.length>0&&s.warnings.forEach(a=>{let{TranslationWarningSystem:l}=(fe(),ye(De));r.warn(`Rule ${n.description||n.id}:
|
|
38
|
-
${l.formatWarning(a)}`)}),o.push(s.result)}return o}async syncRules(t,o={}){let{dryRun:n=!1}=o;try{let{OperationSafety:s}=(Tt(),ye(Et)),a=await s.performDryRunValidation(t,"sync rules",async v=>this.getChanges(v));if(!a.valid)throw new Error(`Dry-run validation failed: ${a.issues.join(", ")}`);let l=a.changes,{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u}=l,p=l.ipsToAdd||[],g=l.ipsToDelete||[];if(n)return r.info("Dry run mode. The following changes would be made:"),r.info(`Custom Rules - Add: ${c.length}, Update: ${d.length}, Delete: ${u.length}`),r.info(`IP Rules - Add: ${p.length}, Delete: ${g.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,warnings:a.warnings};let h=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Fastly workspace ${this.client.workspaceId}`,changes:l,riskLevel:h,skipConfirmation:o.force||!1,dryRun:!1,allowDeletions:o.allowDeletions||!1}))throw new Error("Operation cancelled by user");let R=[];vt(t.rules)&&R.push("Rule `priority` has no effect on Fastly: Next-Gen WAF rules are evaluated independently and have no API-exposed ordering concept to honour.");let N=c.map(v=>({rule:v,translated:$.unifiedToFastly(v)})),Z=d.map(v=>({rule:v,translated:$.unifiedToFastly(v)})),W=[],ue=(v,V)=>`${v}: ${V instanceof Error?V.message:String(V)}`,me=[],_e=[],_=[],ve=[];for(let v of u)if(v.id)try{r.debug(`Deleting Fastly rule: ${v.id}`),await this.client.deleteRule(v.id),_.push(v.id)}catch(V){r.error(`Failed to delete Fastly rule ${v.id}:`,V),W.push(ue(`Failed to delete rule ${v.id}`,V))}for(let{rule:v,translated:V}of N){let ie=V.result;try{r.debug(`Adding new Fastly rule: ${ie.description}`);let ae=await this.client.createRule(ie);me.push(ae),ve.push({oldId:v.id||void 0,newId:ae.id,name:ie.description})}catch(ae){r.error(`Failed to add Fastly rule "${ie.description}":`,ae),W.push(ue(`Failed to add rule "${ie.description}"`,ae))}}for(let{rule:v,translated:V}of Z)if(v.id)try{r.debug(`Updating Fastly rule: ${v.id}`);let ie=await this.client.updateRule(v.id,V.result);_e.push(ie)}catch(ie){r.error(`Failed to update Fastly rule ${v.id}:`,ie),W.push(ue(`Failed to update rule ${v.id}`,ie))}let be=0,Ee=0,We=t.ips||[],{result:Se,warnings:je}=$.unifiedIPsToFastlyEntries(We);je.forEach(v=>R.push(v.message));try{for(let[v,V]of[[pt,Se.denyEntries],[ft,Se.allowEntries]]){let ae=(await this.client.findList(v))?.entries??[],ot=V.filter(f=>!ae.includes(f)),nt=ae.filter(f=>!V.includes(f));if(ot.length===0&&nt.length===0)continue;let Te=await this.client.getOrCreateList(v);await this.client.updateListEntries(Te.id,V),be+=ot.length,Ee+=nt.length}}catch(v){r.error("Failed to sync Fastly IP lists:",v),W.push(ue("Failed to sync IP lists",v))}return r.debug(`Custom Rules: Added: ${me.length}, Updated: ${_e.length}, Deleted: ${_.length}`),r.debug(`IP Rules: Added: ${be}, Deleted: ${Ee}`),{success:W.length===0,rulesAdded:me.length,rulesUpdated:_e.length,rulesDeleted:_.length,ipsAdded:be,ipsUpdated:0,ipsDeleted:Ee,idRemappings:ve.length>0?ve:void 0,errors:W.length>0?W:void 0,warnings:R.length>0?R:void 0}}catch(s){throw r.error("Error during sync:",s),new Error(`Failed to synchronize firewall rules: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async getChanges(t){let o=Le.safeParse(t);if(!o.success)throw new Error(`Invalid firewall configuration: ${o.error.message}`);try{r.debug("Fetching existing Fastly configuration");let[n,s,a]=await Promise.all([this.client.fetchRules(),this.client.findList(pt),this.client.findList(ft)]),l=this.translateFastlyRules(n),{toAdd:c,toUpdate:d,toDelete:u}=this.diffRules(t.rules,l),p=s?.entries??[],g=a?.entries??[],h=[...$.fastlyListEntriesToUnified(p,"deny"),...$.fastlyListEntriesToUnified(g,"allow")],{ipsToAdd:I,ipsToDelete:R}=this.diffIPs(t.ips||[],h);return{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u,ipsToAdd:I,ipsToUpdate:[],ipsToDelete:R,hasChanges:c.length>0||d.length>0||u.length>0||I.length>0||R.length>0}}catch(n){throw r.error("Error fetching existing Fastly configuration:",n),new Error("Failed to fetch existing Fastly configuration")}}getSupportedFeatures(){return{supportsCustomRules:!0,supportsIPBlocking:!0,supportsRateLimiting:!0,supportsManagedRules:!1,supportsGeoBlocking:!0,supportsRedirect:!0,supportsChallenge:!0}}async verifyCredentials(){return this.client.verifyCredentials()}validateConfig(t){let o=super.validateConfig(t),n=[...o.errors],s=[...o.warnings];return t.provider&&t.provider!=="fastly"&&n.push({path:"provider",message:"Provider must be 'fastly' for FastlyFirewallService",code:"INVALID_PROVIDER"}),{valid:n.length===0,errors:n,warnings:s}}getHealthScore(t){let o=super.getHealthScore(t),n=[...o.issues],s=o.score;return t.rules.filter(l=>l.action?.type==="rate_limit").length===0&&(s-=10,n.push({severity:"info",category:"security",message:"No rate limiting rules configured",suggestion:"Consider adding rate limiting to protect against abuse"})),(!t.ips||t.ips.length===0)&&n.push({severity:"info",category:"security",message:"No IP blocking rules configured",suggestion:"Consider blocking known malicious IPs"}),{score:Math.max(0,s),grade:o.grade,issues:n,recommendations:o.recommendations}}diffRules(t,o){let n=[],s=[],a=[...o];for(let l of t){let c=o.find(d=>d.id===l.id);if(!c)n.push(l);else{Ke(ke(l),ke(c))||s.push({...l,id:c.id});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{toAdd:n,toUpdate:s,toDelete:a}}diffIPs(t,o){let n=l=>`${l.action}:${l.ip}`,s=new Set(o.map(n)),a=new Set(t.map(n));return{ipsToAdd:t.filter(l=>!s.has(n(l))),ipsToDelete:o.filter(l=>!a.has(n(l)))}}};T();var tt=class{static fromEnv(){let e=process.env.FASTLY_API_TOKEN,t=process.env.FASTLY_WORKSPACE_ID;if(!e)throw new Error("FASTLY_API_TOKEN environment variable is required");if(!t)throw new Error("FASTLY_WORKSPACE_ID environment variable is required");let o=new Xe(t,e);return new et(o)}static fromConfig(e){let t=e.apiToken||process.env.FASTLY_API_TOKEN,o=e.workspaceId||process.env.FASTLY_WORKSPACE_ID;if(!t)throw new Error("Fastly API token is required (provide apiToken or set FASTLY_API_TOKEN env var)");if(!o)throw new Error("Fastly workspace ID is required (provide workspaceId or set FASTLY_WORKSPACE_ID env var)");r.debug("Creating Fastly provider with config:",{workspaceId:o});let n=new Xe(o,t);return new et(n)}static create(e,t){return this.fromConfig({workspaceId:e,apiToken:t})}};var Jt={provider:"vercel",fields:[{key:"token",envVar:"VERCEL_TOKEN",label:"Vercel API Token",required:!0,secret:!0},{key:"projectId",envVar:"VERCEL_PROJECT_ID",label:"Vercel Project ID",required:!0,configKey:"projectId"},{key:"teamId",envVar:"VERCEL_TEAM_ID",label:"Vercel Team ID",required:!1,configKey:"teamId"}]};var Qt={provider:"cloudflare",fields:[{key:"apiToken",envVar:"CLOUDFLARE_API_TOKEN",label:"Cloudflare API Token",required:!0,secret:!0},{key:"zoneId",envVar:"CLOUDFLARE_ZONE_ID",label:"Cloudflare Zone ID",required:!0,configKey:"zoneId"},{key:"accountId",envVar:"CLOUDFLARE_ACCOUNT_ID",label:"Cloudflare Account ID",required:!1,configKey:"accountId"}]};var Xt={provider:"fastly",fields:[{key:"apiToken",envVar:"FASTLY_API_TOKEN",label:"Fastly API Token",required:!0,secret:!0},{key:"workspaceId",envVar:"FASTLY_WORKSPACE_ID",label:"Fastly Next-Gen WAF Workspace ID",required:!0,configKey:"workspaceId"}]};function Pt(i,e={}){let{explicit:t={},config:o={},env:n=process.env}=e,s={};for(let a of i.fields)s[a.key]=t[a.key]||o[a.key]||n[a.envVar];return s}async function yo(i){let e;if(i.provider)e=i.provider,r.debug(`Using explicitly specified provider: ${e}`);else{let t=yt.detect(i.config);t.provider?(e=t.provider,r.debug(`Auto-detected provider: ${e} (${t.confidence} confidence)`),t.reasons.length>0&&r.debug(`Reasons: ${t.reasons.join(", ")}`)):i.interactive!==!1?e=await ur():(e="vercel",r.warn("No provider detected, defaulting to Vercel"))}try{if(e==="vercel")return await lr(i);if(e==="cloudflare")return{provider:await cr(i)};if(e==="fastly")return{provider:await dr(i)};throw new Error(`Unknown provider: ${e}`)}catch(t){throw r.error(`Failed to initialize ${e} provider:`,t),t}}async function lr(i){let e=i.config,{token:t,projectId:o,teamId:n}=Pt(Jt,{explicit:{token:i.token,projectId:i.projectId,teamId:i.teamId},config:{projectId:e?.providers?.vercel?.projectId??e?.projectId,teamId:e?.providers?.vercel?.teamId??e?.teamId}});if(!t||!o){if(i.interactive===!1)throw new Error("Vercel credentials missing. Provide token and projectId.");r.warn("Missing Vercel credentials"),r.info("Please provide your Vercel credentials:");let{promptForCredentials:a}=await Promise.resolve().then(()=>(go(),fo)),l=await a({token:t,projectId:o,teamId:n});return{provider:Ze.fromConfig({token:l.token,projectId:l.projectId,teamId:l.teamId}),vercelCredentials:l}}return{provider:Ze.fromConfig({token:t,projectId:o,teamId:n}),vercelCredentials:{token:t,projectId:o,teamId:n}}}async function cr(i){let e=i.config,{apiToken:t,zoneId:o,accountId:n}=Pt(Qt,{explicit:{apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId},config:{zoneId:e?.providers?.cloudflare?.zoneId,accountId:e?.providers?.cloudflare?.accountId}});if(!t||!o){if(i.interactive===!1)throw new Error("Cloudflare credentials missing. Provide apiToken and zoneId.");r.warn("Missing Cloudflare credentials"),r.info("Please provide your Cloudflare credentials:");let s=t||await at("Cloudflare API Token: "),a=o||await w("Cloudflare Zone ID:",{type:"text"}),l=n||await w("Cloudflare Account ID (optional):",{type:"text"});return Qe.fromConfig({apiToken:s,zoneId:a,accountId:l||void 0})}return Qe.fromConfig({apiToken:t,zoneId:o,accountId:n})}async function dr(i){let e=i.config,{apiToken:t,workspaceId:o}=Pt(Xt,{explicit:{apiToken:i.apiToken,workspaceId:i.workspaceId},config:{workspaceId:e?.providers?.fastly?.workspaceId}});if(!t||!o){if(i.interactive===!1)throw new Error("Fastly credentials missing. Provide apiToken and workspaceId.");r.warn("Missing Fastly credentials"),r.info("Please provide your Fastly credentials:");let n=t||await at("Fastly API Token: "),s=o||await w("Fastly Next-Gen WAF Workspace ID:",{type:"text"});return tt.fromConfig({apiToken:n,workspaceId:s})}return tt.fromConfig({apiToken:t,workspaceId:o})}async function ur(){r.info(ho.default.yellow("Unable to auto-detect firewall provider.")),r.info(`Please select a provider:
|
|
38
|
+
${l.formatWarning(a)}`)}),o.push(s.result)}return o}async syncRules(t,o={}){let{dryRun:n=!1}=o;try{let{OperationSafety:s}=(Tt(),ye(Et)),a=await s.performDryRunValidation(t,"sync rules",async C=>this.getChanges(C));if(!a.valid)throw new Error(`Dry-run validation failed: ${a.issues.join(", ")}`);let l=a.changes,{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u}=l,p=l.ipsToAdd||[],g=l.ipsToDelete||[];if(n)return r.info("Dry run mode. The following changes would be made:"),r.info(`Custom Rules - Add: ${c.length}, Update: ${d.length}, Delete: ${u.length}`),r.info(`IP Rules - Add: ${p.length}, Delete: ${g.length}`),{success:!0,rulesAdded:0,rulesUpdated:0,rulesDeleted:0,ipsAdded:0,ipsUpdated:0,ipsDeleted:0,warnings:a.warnings};let h=s.assessOperationRisk(l,t);if(!await s.confirmDestructiveOperation({operation:"sync rules",target:`Fastly workspace ${this.client.workspaceId}`,changes:l,riskLevel:h,skipConfirmation:o.force||!1,dryRun:!1,allowDeletions:o.allowDeletions||!1}))throw new Error("Operation cancelled by user");let R=[];Ct(t.rules)&&R.push("Rule `priority` has no effect on Fastly: Next-Gen WAF rules are evaluated independently and have no API-exposed ordering concept to honour.");let N=c.map(C=>({rule:C,translated:$.unifiedToFastly(C)})),Z=d.map(C=>({rule:C,translated:$.unifiedToFastly(C)})),W=[],ue=(C,V)=>`${C}: ${V instanceof Error?V.message:String(V)}`,me=[],_e=[],_=[],Ce=[];for(let C of u)if(C.id)try{r.debug(`Deleting Fastly rule: ${C.id}`),await this.client.deleteRule(C.id),_.push(C.id)}catch(V){r.error(`Failed to delete Fastly rule ${C.id}:`,V),W.push(ue(`Failed to delete rule ${C.id}`,V))}for(let{rule:C,translated:V}of N){let ie=V.result;try{r.debug(`Adding new Fastly rule: ${ie.description}`);let ae=await this.client.createRule(ie);me.push(ae),Ce.push({oldId:C.id||void 0,newId:ae.id,name:ie.description})}catch(ae){r.error(`Failed to add Fastly rule "${ie.description}":`,ae),W.push(ue(`Failed to add rule "${ie.description}"`,ae))}}for(let{rule:C,translated:V}of Z)if(C.id)try{r.debug(`Updating Fastly rule: ${C.id}`);let ie=await this.client.updateRule(C.id,V.result);_e.push(ie)}catch(ie){r.error(`Failed to update Fastly rule ${C.id}:`,ie),W.push(ue(`Failed to update rule ${C.id}`,ie))}let be=0,Ee=0,We=t.ips||[],{result:Se,warnings:je}=$.unifiedIPsToFastlyEntries(We);je.forEach(C=>R.push(C.message));try{for(let[C,V]of[[pt,Se.denyEntries],[ft,Se.allowEntries]]){let ae=(await this.client.findList(C))?.entries??[],ot=V.filter(f=>!ae.includes(f)),nt=ae.filter(f=>!V.includes(f));if(ot.length===0&&nt.length===0)continue;let Te=await this.client.getOrCreateList(C);await this.client.updateListEntries(Te.id,V),be+=ot.length,Ee+=nt.length}}catch(C){r.error("Failed to sync Fastly IP lists:",C),W.push(ue("Failed to sync IP lists",C))}return r.debug(`Custom Rules: Added: ${me.length}, Updated: ${_e.length}, Deleted: ${_.length}`),r.debug(`IP Rules: Added: ${be}, Deleted: ${Ee}`),{success:W.length===0,rulesAdded:me.length,rulesUpdated:_e.length,rulesDeleted:_.length,ipsAdded:be,ipsUpdated:0,ipsDeleted:Ee,idRemappings:Ce.length>0?Ce:void 0,errors:W.length>0?W:void 0,warnings:R.length>0?R:void 0}}catch(s){throw r.error("Error during sync:",s),new Error(`Failed to synchronize firewall rules: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async getChanges(t){let o=Le.safeParse(t);if(!o.success)throw new Error(`Invalid firewall configuration: ${o.error.message}`);try{r.debug("Fetching existing Fastly configuration");let[n,s,a]=await Promise.all([this.client.fetchRules(),this.client.findList(pt),this.client.findList(ft)]),l=this.translateFastlyRules(n),{toAdd:c,toUpdate:d,toDelete:u}=this.diffRules(t.rules,l),p=s?.entries??[],g=a?.entries??[],h=[...$.fastlyListEntriesToUnified(p,"deny"),...$.fastlyListEntriesToUnified(g,"allow")],{ipsToAdd:I,ipsToDelete:R}=this.diffIPs(t.ips||[],h);return{rulesToAdd:c,rulesToUpdate:d,rulesToDelete:u,ipsToAdd:I,ipsToUpdate:[],ipsToDelete:R,hasChanges:c.length>0||d.length>0||u.length>0||I.length>0||R.length>0}}catch(n){throw r.error("Error fetching existing Fastly configuration:",n),new Error("Failed to fetch existing Fastly configuration")}}getSupportedFeatures(){return{supportsCustomRules:!0,supportsIPBlocking:!0,supportsRateLimiting:!0,supportsManagedRules:!1,supportsGeoBlocking:!0,supportsRedirect:!0,supportsChallenge:!0}}async verifyCredentials(){return this.client.verifyCredentials()}validateConfig(t){let o=super.validateConfig(t),n=[...o.errors],s=[...o.warnings];return t.provider&&t.provider!=="fastly"&&n.push({path:"provider",message:"Provider must be 'fastly' for FastlyFirewallService",code:"INVALID_PROVIDER"}),{valid:n.length===0,errors:n,warnings:s}}getHealthScore(t){let o=super.getHealthScore(t),n=[...o.issues],s=o.score;return t.rules.filter(l=>l.action?.type==="rate_limit").length===0&&(s-=10,n.push({severity:"info",category:"security",message:"No rate limiting rules configured",suggestion:"Consider adding rate limiting to protect against abuse"})),(!t.ips||t.ips.length===0)&&n.push({severity:"info",category:"security",message:"No IP blocking rules configured",suggestion:"Consider blocking known malicious IPs"}),{score:Math.max(0,s),grade:o.grade,issues:n,recommendations:o.recommendations}}diffRules(t,o){let n=[],s=[],a=[...o];for(let l of t){let c=o.find(d=>d.id===l.id);if(!c)n.push(l);else{Ke(ke(l),ke(c))||s.push({...l,id:c.id});let d=a.findIndex(u=>u.id===c.id);d!==-1&&a.splice(d,1)}}return{toAdd:n,toUpdate:s,toDelete:a}}diffIPs(t,o){let n=l=>`${l.action}:${l.ip}`,s=new Set(o.map(n)),a=new Set(t.map(n));return{ipsToAdd:t.filter(l=>!s.has(n(l))),ipsToDelete:o.filter(l=>!a.has(n(l)))}}};T();var tt=class{static fromEnv(){let e=process.env.FASTLY_API_TOKEN,t=process.env.FASTLY_WORKSPACE_ID;if(!e)throw new Error("FASTLY_API_TOKEN environment variable is required");if(!t)throw new Error("FASTLY_WORKSPACE_ID environment variable is required");let o=new Xe(t,e);return new et(o)}static fromConfig(e){let t=e.apiToken||process.env.FASTLY_API_TOKEN,o=e.workspaceId||process.env.FASTLY_WORKSPACE_ID;if(!t)throw new Error("Fastly API token is required (provide apiToken or set FASTLY_API_TOKEN env var)");if(!o)throw new Error("Fastly workspace ID is required (provide workspaceId or set FASTLY_WORKSPACE_ID env var)");r.debug("Creating Fastly provider with config:",{workspaceId:o});let n=new Xe(o,t);return new et(n)}static create(e,t){return this.fromConfig({workspaceId:e,apiToken:t})}};var Jt={provider:"vercel",fields:[{key:"token",envVar:"VERCEL_TOKEN",label:"Vercel API Token",required:!0,secret:!0},{key:"projectId",envVar:"VERCEL_PROJECT_ID",label:"Vercel Project ID",required:!0,configKey:"projectId"},{key:"teamId",envVar:"VERCEL_TEAM_ID",label:"Vercel Team ID",required:!1,configKey:"teamId"}]};var Qt={provider:"cloudflare",fields:[{key:"apiToken",envVar:"CLOUDFLARE_API_TOKEN",label:"Cloudflare API Token",required:!0,secret:!0},{key:"zoneId",envVar:"CLOUDFLARE_ZONE_ID",label:"Cloudflare Zone ID",required:!0,configKey:"zoneId"},{key:"accountId",envVar:"CLOUDFLARE_ACCOUNT_ID",label:"Cloudflare Account ID",required:!1,configKey:"accountId"}]};var Xt={provider:"fastly",fields:[{key:"apiToken",envVar:"FASTLY_API_TOKEN",label:"Fastly API Token",required:!0,secret:!0},{key:"workspaceId",envVar:"FASTLY_WORKSPACE_ID",label:"Fastly Next-Gen WAF Workspace ID",required:!0,configKey:"workspaceId"}]};function Pt(i,e={}){let{explicit:t={},config:o={},env:n=process.env}=e,s={};for(let a of i.fields)s[a.key]=t[a.key]||o[a.key]||n[a.envVar];return s}async function yo(i){let e;if(i.provider)e=i.provider,r.debug(`Using explicitly specified provider: ${e}`);else{let t=yt.detect(i.config);t.provider?(e=t.provider,r.debug(`Auto-detected provider: ${e} (${t.confidence} confidence)`),t.reasons.length>0&&r.debug(`Reasons: ${t.reasons.join(", ")}`)):i.interactive!==!1?e=await ur():(e="vercel",r.warn("No provider detected, defaulting to Vercel"))}try{if(e==="vercel")return await lr(i);if(e==="cloudflare")return{provider:await cr(i)};if(e==="fastly")return{provider:await dr(i)};throw new Error(`Unknown provider: ${e}`)}catch(t){throw r.error(`Failed to initialize ${e} provider:`,t),t}}async function lr(i){let e=i.config,{token:t,projectId:o,teamId:n}=Pt(Jt,{explicit:{token:i.token,projectId:i.projectId,teamId:i.teamId},config:{projectId:e?.providers?.vercel?.projectId??e?.projectId,teamId:e?.providers?.vercel?.teamId??e?.teamId}});if(!t||!o){if(i.interactive===!1)throw new Error("Vercel credentials missing. Provide token and projectId.");r.warn("Missing Vercel credentials"),r.info("Please provide your Vercel credentials:");let{promptForCredentials:a}=await Promise.resolve().then(()=>(go(),fo)),l=await a({token:t,projectId:o,teamId:n});return{provider:Ze.fromConfig({token:l.token,projectId:l.projectId,teamId:l.teamId}),vercelCredentials:l}}return{provider:Ze.fromConfig({token:t,projectId:o,teamId:n}),vercelCredentials:{token:t,projectId:o,teamId:n}}}async function cr(i){let e=i.config,{apiToken:t,zoneId:o,accountId:n}=Pt(Qt,{explicit:{apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId},config:{zoneId:e?.providers?.cloudflare?.zoneId,accountId:e?.providers?.cloudflare?.accountId}});if(!t||!o){if(i.interactive===!1)throw new Error("Cloudflare credentials missing. Provide apiToken and zoneId.");r.warn("Missing Cloudflare credentials"),r.info("Please provide your Cloudflare credentials:");let s=t||await at("Cloudflare API Token: "),a=o||await w("Cloudflare Zone ID:",{type:"text"}),l=n||await w("Cloudflare Account ID (optional):",{type:"text"});return Qe.fromConfig({apiToken:s,zoneId:a,accountId:l||void 0})}return Qe.fromConfig({apiToken:t,zoneId:o,accountId:n})}async function dr(i){let e=i.config,{apiToken:t,workspaceId:o}=Pt(Xt,{explicit:{apiToken:i.apiToken,workspaceId:i.workspaceId},config:{workspaceId:e?.providers?.fastly?.workspaceId}});if(!t||!o){if(i.interactive===!1)throw new Error("Fastly credentials missing. Provide apiToken and workspaceId.");r.warn("Missing Fastly credentials"),r.info("Please provide your Fastly credentials:");let n=t||await at("Fastly API Token: "),s=o||await w("Fastly Next-Gen WAF Workspace ID:",{type:"text"});return tt.fromConfig({apiToken:n,workspaceId:s})}return tt.fromConfig({apiToken:t,workspaceId:o})}async function ur(){r.info(ho.default.yellow("Unable to auto-detect firewall provider.")),r.info(`Please select a provider:
|
|
39
39
|
`),re.forEach((s,a)=>{r.info(` ${a+1}. ${mo(s)}`)}),r.info("");let i=await w(`Select provider (1-${re.length}):`,{type:"text"}),e=String(i).trim().toLowerCase(),t=re.find(s=>s===e);if(t)return t;let o=Number(e);if(Number.isInteger(o)&&o>=1&&o<=re.length)return re[o-1];let n=re[0];return r.warn(`Invalid choice: ${i}, defaulting to ${mo(n)}`),n}function mo(i){switch(i){case"vercel":return"Vercel Firewall";case"cloudflare":return"Cloudflare WAF";case"fastly":return"Fastly Next-Gen WAF";default:return i}}async function Q(i,e){try{i.debug&&(r.level=wo.LogLevels.debug);let t;if(i.optionalConfig)try{t=await j(i.config,"optional")}catch{t={}}else i.skipValidation?t=await j(i.config,"raw"):t=await j(i.config,"required");let{provider:o,vercelCredentials:n}=await yo({provider:i.provider,config:t,interactive:!i.ci,token:i.token,projectId:i.projectId,teamId:i.teamId,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId}),s=n?.token??"",a=n?.projectId??"",l=n?.teamId??"";await e({config:t,provider:o,token:s,projectId:a,teamId:l})}catch(t){Y(t,i.errorContext)}}var pr="backup",fr="Backup or restore firewall configurations",gr={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},output:{alias:"o",type:"string",description:"Output directory for backups",default:"./backups"},restore:{alias:"r",type:"string",description:"Restore from backup file"},list:{alias:"l",type:"boolean",description:"List available backups",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},mr=async i=>{try{i.debug&&(r.level=Io.LogLevels.debug);let e=i.output||"./backups";if(i.list){if(!(0,ge.existsSync)(e)){r.info(H.default.yellow("No backup directory found."));return}let t=(0,ge.readdirSync)(e).filter(o=>o.endsWith(".json")).map(o=>{let n=(0,it.join)(e,o),s=(0,ge.statSync)(n);return{name:o,size:s.size,created:s.mtime}}).sort((o,n)=>n.created.getTime()-o.created.getTime());if(t.length===0){r.info(H.default.yellow("No backups found."));return}r.log(H.default.bold(`
|
|
40
40
|
\u{1F4E6} Available Backups:
|
|
41
41
|
`)),t.forEach(o=>{r.log(`${H.default.cyan(o.name)}`),r.log(` ${H.default.dim("Created:")} ${o.created.toLocaleString()}`),r.log(` ${H.default.dim("Size:")} ${(o.size/1024).toFixed(1)} KB`),r.log("")});return}if(i.restore){let t=i.restore.startsWith("/")?i.restore:(0,it.join)(e,i.restore);(0,ge.existsSync)(t)||(r.error(`Backup file not found: ${t}`),process.exit(1));let o=await j(t,"raw"),n=i.config||".doorman.json";if((0,ge.existsSync)(n)&&!await w(`Config file ${n} already exists. Do you want to overwrite it?`,{type:"confirm"})){r.info(H.default.yellow("Restore cancelled."));return}let{backup:s,...a}=o;await q(a,n),r.success(H.default.green(`\u2705 Restored configuration from ${t} to ${n}`));return}await Q({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"creating backup"},async({provider:t,projectId:o,teamId:n})=>{r.start("Fetching current remote configuration...");let s=await t.fetchConfig(),a=s.metadata?.version??s.version;Re.getInstance().validateConfig(s),(0,ge.existsSync)(e)||(0,ge.mkdirSync)(e,{recursive:!0});let c=new Date,d=c.toISOString().split("T")[0]??"unknown-date",u=(c.toISOString().split("T")[1]??"").split(".")[0]?.replace(/:/g,"-")??"unknown-time",g=`firewall-backup-${`${d}_${u}`}.json`,h=(0,it.join)(e,g),I={...s,backup:{createdAt:new Date().toISOString(),source:"remote",provider:t.name,...t.name==="vercel"?{projectId:o,teamId:n}:{},originalVersion:a}};await q(I,h,{validate:!1}),r.success(H.default.green(`\u2705 Backup created: ${h}`)),r.log(""),r.log(H.default.bold("Backup Details:")),r.log(`${H.default.dim("Version:")} ${a??"unknown"}`),r.log(`${H.default.dim("Rules:")} ${s.rules.length} custom, ${s.ips?.length??0} IP blocking`),r.log(`${H.default.dim("Created:")} ${new Date().toLocaleString()}`),!(0,it.isAbsolute)(e)&&ji()&&!qi(e)&&r.warn(H.default.yellow(`\u{1F4A1} ${e} isn't in .gitignore \u2014 firewall backups may contain rule details you don't want in git history.`)),r.log(""),r.log(H.default.dim("To restore this backup later, run:")),r.log(H.default.cyan(`doorman backup --restore ${g}`))})}catch(e){Y(e,"managing backup")}};var ti={};M(ti,{builder:()=>wr,command:()=>hr,desc:()=>yr,handler:()=>Ir});var X=S(require("chalk"));T();function le(i){if(we(i))return i;let e=i,t=e.rules.map(n=>$.vercelToUnified(n).result),o=(e.ips??[]).map(n=>$.vercelIPToUnified(n));return{version:"2.0",provider:"vercel",providers:{vercel:{projectId:e.projectId,teamId:e.teamId}},rules:t,ips:o,metadata:{version:e.version,updatedAt:e.updatedAt}}}function $t(i,e){let t=!1,o=we(i),n=o?{...i,metadata:{...i.metadata}}:{...i};if(e.version!==void 0)if(o){let s=n;s.metadata?.version!==e.version&&(s.metadata={...s.metadata,version:e.version,updatedAt:e.updatedAt??new Date().toISOString()},t=!0)}else{let s=n;s.version!==e.version&&(s.version=e.version,s.updatedAt=e.updatedAt??new Date().toISOString(),t=!0)}if(e.idRemappings&&e.idRemappings.length>0){let s=new Map(e.idRemappings.filter(d=>d.oldId).map(d=>[d.oldId,d.newId])),a=new Map(e.idRemappings.filter(d=>!d.oldId).map(d=>[d.name,d.newId])),l=!1,c=n.rules.map(d=>{let u=d.id?s.get(d.id):a.get(d.name);return u&&u!==d.id?(l=!0,{...d,id:u}):d});l&&(n={...n,rules:c},t=!0)}return{config:n,changed:t}}function Ro(i,e){if(we(e))return{...e,...i};let t=e,o=i.rules.map(s=>$.unifiedToVercel(s).result),n=(i.ips??[]).map(s=>({id:s.id||"",ip:s.ip,hostname:s.hostname||"",action:s.action,notes:s.notes}));return{...t,projectId:i.providers?.vercel?.projectId??t.projectId,teamId:i.providers?.vercel?.teamId??t.teamId,version:i.metadata?.version,updatedAt:i.metadata?.updatedAt,rules:o,ips:n}}var hr="diff",yr="Show detailed differences between local and remote firewall configuration",wr={config:{alias:"c",type:"string",description:"Path to firewall config file"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID"},teamId:{alias:"t",type:"string",description:"Vercel Team ID"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},format:{alias:"f",type:"string",choices:["table","json"],description:"Output format",default:"table"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Ir=async i=>{await Q({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"calculating diff"},async({config:e,provider:t})=>{await Rr(t,le(e),i)})};async function Rr(i,e,t){let o=t.format==="json";o||r.start("Calculating differences...");let n=await i.getChanges(e),s=n.ipsToAdd??[],a=n.ipsToUpdate??[],l=n.ipsToDelete??[];if(o){r.log(JSON.stringify({rules:{toAdd:n.rulesToAdd,toUpdate:n.rulesToUpdate,toDelete:n.rulesToDelete},ips:{toAdd:s,toUpdate:a,toDelete:l},summary:{hasChanges:n.hasChanges,ruleChanges:n.rulesToAdd.length+n.rulesToUpdate.length+n.rulesToDelete.length,ipChanges:s.length+a.length+l.length}},null,2));return}if(!n.hasChanges){r.success(X.default.green("No differences found. Local and remote configurations are in sync."));return}r.log(X.default.bold(`
|
|
42
42
|
\u{1F50D} ${i.name} Configuration Differences
|
|
43
|
-
`)),r.log(X.default.bold("Rule Changes:")),r.log(` ${X.default.green("+")} ${n.rulesToAdd.length} to add`),n.rulesToAdd.forEach(d=>r.log(` ${X.default.green("+")} ${d.name}`)),r.log(` ${X.default.cyan("~")} ${n.rulesToUpdate.length} to update`),n.rulesToUpdate.forEach(d=>r.log(` ${X.default.cyan("~")} ${d.name}`)),r.log(` ${X.default.red("-")} ${n.rulesToDelete.length} to delete`),n.rulesToDelete.forEach(d=>r.log(` ${X.default.red("-")} ${d.name}`)),(s.length||a.length||l.length)&&(r.log(""),r.log(X.default.bold("IP Rule Changes:")),r.log(` ${X.default.green("+")} ${s.length} to add`),r.log(` ${X.default.cyan("~")} ${a.length} to update`),r.log(` ${X.default.red("-")} ${l.length} to delete`));let c=n.rulesToAdd.length+n.rulesToUpdate.length+n.rulesToDelete.length+s.length+a.length+l.length;r.log(""),r.log(X.default.bold(`Summary: ${c} total changes detected`)),r.log(X.default.dim("Run `sync` to apply these changes to the remote configuration."))}var ii={};M(ii,{builder:()=>br,command:()=>
|
|
43
|
+
`)),r.log(X.default.bold("Rule Changes:")),r.log(` ${X.default.green("+")} ${n.rulesToAdd.length} to add`),n.rulesToAdd.forEach(d=>r.log(` ${X.default.green("+")} ${d.name}`)),r.log(` ${X.default.cyan("~")} ${n.rulesToUpdate.length} to update`),n.rulesToUpdate.forEach(d=>r.log(` ${X.default.cyan("~")} ${d.name}`)),r.log(` ${X.default.red("-")} ${n.rulesToDelete.length} to delete`),n.rulesToDelete.forEach(d=>r.log(` ${X.default.red("-")} ${d.name}`)),(s.length||a.length||l.length)&&(r.log(""),r.log(X.default.bold("IP Rule Changes:")),r.log(` ${X.default.green("+")} ${s.length} to add`),r.log(` ${X.default.cyan("~")} ${a.length} to update`),r.log(` ${X.default.red("-")} ${l.length} to delete`));let c=n.rulesToAdd.length+n.rulesToUpdate.length+n.rulesToDelete.length+s.length+a.length+l.length;r.log(""),r.log(X.default.bold(`Summary: ${c} total changes detected`)),r.log(X.default.dim("Run `sync` to apply these changes to the remote configuration."))}var ii={};M(ii,{builder:()=>br,command:()=>vr,desc:()=>Cr,handler:()=>Er});var Ve=S(require("chalk")),vo=require("zod");T();pe();var vr="download [configVersion]",Cr="Download remote Vercel Firewall rules and update local config, optionally for a specific configuration version",br={configVersion:{type:"number",description:"Specific configuration version to download (defaults to latest)"},config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},dryRun:{alias:"d",type:"boolean",description:"Show rules that would be downloaded without making changes",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Er=async i=>{await Q({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,optionalConfig:!0,skipValidation:!0,errorContext:"downloading firewall rules"},async({config:e,provider:t})=>{if(i.configVersion!==void 0)try{mt.parse(i.configVersion)}catch(o){throw o instanceof vo.z.ZodError&&(r.error("Invalid configuration version number. Version must be a positive integer."),process.exit(1)),o}await Tr(t,e,i)})};async function Tr(i,e,t){r.start(`Fetching remote firewall configuration${t.configVersion?` version ${t.configVersion}`:""} ...`);let o=await i.fetchConfig(t.configVersion),n=o.rules,s=o.ips??[];if(n.length>0?(r.log(Ve.default.bold(`
|
|
44
44
|
Remote Custom Rules to Download (${n.length}):
|
|
45
45
|
`)),n.forEach(c=>r.log(` - ${c.name}${c.enabled?"":Ve.default.dim(" (disabled)")}`))):r.info("No custom rules to download..."),s.length>0?(r.log(Ve.default.bold(`
|
|
46
46
|
Remote IP Blocking Rules to Download (${s.length}):
|
|
47
|
-
`)),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info("No IP blocking rules to download..."),t.dryRun){r.info(Ve.default.cyan("Dry run completed. No changes made."));return}if(!await w(`Do you want to download${t.configVersion?` version ${t.configVersion}`:" the latest version"} of these rules? This will overwrite your local configuration.`,{type:"confirm"})){r.info(Ve.default.yellow("Download cancelled."));return}let l=Ro(o,e);r.start("Saving configuration..."),await q(l,t.config),r.success(Ve.default.green("Successfully downloaded and updated configuration"))}var oi={};M(oi,{builder:()=>$r,command:()=>Ar,desc:()=>Pr,handler:()=>Lr});var Be=S(require("chalk")),
|
|
47
|
+
`)),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info("No IP blocking rules to download..."),t.dryRun){r.info(Ve.default.cyan("Dry run completed. No changes made."));return}if(!await w(`Do you want to download${t.configVersion?` version ${t.configVersion}`:" the latest version"} of these rules? This will overwrite your local configuration.`,{type:"confirm"})){r.info(Ve.default.yellow("Download cancelled."));return}let l=Ro(o,e);r.start("Saving configuration..."),await q(l,t.config),r.success(Ve.default.green("Successfully downloaded and updated configuration"))}var oi={};M(oi,{builder:()=>$r,command:()=>Ar,desc:()=>Pr,handler:()=>Lr});var Be=S(require("chalk")),Co=require("fs");T();var Ar="export",Pr="Export firewall configuration in various formats",$r={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},format:{alias:"f",type:"string",choices:["json","yaml","terraform","markdown"],description:"Export format",default:"json"},output:{alias:"o",type:"string",description:"Output file path"},source:{alias:"s",type:"string",choices:["local","remote"],description:"Export from local config or remote Vercel",default:"local"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}};function kr(i){let e=new Map;for(let t of i){let o=t.group??0,n=e.get(o);n?n.push(t):e.set(o,[t])}return[...e.values()]}var _r=i=>{let{rules:e,ips:t=[]}=i,o=i.metadata?.version,n=i.metadata?.updatedAt,s=`# Firewall Configuration Report
|
|
48
48
|
|
|
49
49
|
`;return s+=`**Provider:** ${i.provider??"unknown"}
|
|
50
50
|
`,s+=`**Version:** ${o??"unknown"}
|
|
@@ -103,7 +103,7 @@ Remote IP Blocking Rules to Download (${s.length}):
|
|
|
103
103
|
`,o+=` id: "${l.id??""}"
|
|
104
104
|
`,o+=` enabled: ${l.enabled}
|
|
105
105
|
`,o+=` action: "${l.action.type}"
|
|
106
|
-
`}),n="yaml";break}case"terraform":o=Sr(le(t)),n="tf";break;case"markdown":o=_r(le(t)),n="md";break;default:throw new Error(`Unsupported format: ${i.format}`)}let s=i.output||`firewall-export.${n}`;e?r.log(o):((0,
|
|
106
|
+
`}),n="yaml";break}case"terraform":o=Sr(le(t)),n="tf";break;case"markdown":o=_r(le(t)),n="md";break;default:throw new Error(`Unsupported format: ${i.format}`)}let s=i.output||`firewall-export.${n}`;e?r.log(o):((0,Co.writeFileSync)(s,o,"utf8"),r.success(Be.default.green(`\u2705 Exported to ${s}`)),r.log(""),r.log(Be.default.bold("Export Summary:")),r.log(`${Be.default.dim("Format:")} ${i.format}`),r.log(`${Be.default.dim("Source:")} ${i.source}`),r.log(`${Be.default.dim("Rules:")} ${t.rules.length} custom, ${(t.ips||[]).length} IP blocking`),r.log(`${Be.default.dim("Size:")} ${(o.length/1024).toFixed(1)} KB`))}catch(e){Y(e,"exporting configuration")}};var ni={};M(ni,{BASIC_TEMPLATE_RULES:()=>Eo,SECURITY_FOCUSED_TEMPLATE_RULES:()=>To,builder:()=>xr,command:()=>Ur,desc:()=>Dr,handler:()=>Br});var y=S(require("chalk")),bo=require("fs");T();pe();var Eo=[{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}],To=[{id:"rule_rate_limit_api",name:"Rate Limit API",description:"Rate limit API endpoints to prevent abuse and DoS attacks",conditionGroup:[{conditions:[{type:"path",op:"pre",value:"/api/"}]}],action:{mitigate:{action:"rate_limit",rateLimit:{requests:100,window:"1m"}}},active:!1},{id:"rule_block_suspicious_ips",name:"Block Suspicious IPs",description:"Block requests from a known suspicious IP range",conditionGroup:[{conditions:[{type:"ip_address",op:"eq",value:"10.0.0.0/24"}]}],action:{mitigate:{action:"deny"}},active:!1},{id:"rule_protect_admin",name:"Protect Admin Routes",description:"Add extra protection for admin and sensitive routes",conditionGroup:[{conditions:[{type:"path",op:"pre",value:"/admin"}]}],action:{mitigate:{action:"rate_limit",rateLimit:{requests:10,window:"1m"}}},active:!1}],Ur="init [template]",Dr="Initialize a new Doorman configuration",xr={template:{type:"string",description:"Template to use for initialization (empty, basic, or security-focused)",choices:["empty","basic","security-focused"]},config:{alias:"c",type:"string",description:"Path for the new config file",default:".doorman.json"},force:{alias:"f",type:"boolean",description:"Overwrite existing config file",default:!1},interactive:{alias:"i",type:"boolean",description:"Interactive setup with guided prompts (default: on unless a template is given positionally)"},projectId:{alias:"p",type:"string",description:"Vercel Project ID"},teamId:{alias:"t",type:"string",description:"Vercel Team ID"}},Or=()=>{r.log(""),r.log(y.default.bold.cyan("\u{1F6AA} Welcome to Doorman!")),r.log(y.default.dim(`Let's set up your firewall configuration.
|
|
107
107
|
`))},Fr=()=>{r.log(y.default.bold(`
|
|
108
108
|
\u{1F4DA} Helpful Resources:`)),r.log(""),r.log(y.default.cyan("\u{1F517} Find your Project ID:")),r.log(y.default.dim(" https://vercel.com/dashboard \u2192 Select your project \u2192 Settings \u2192 General")),r.log(""),r.log(y.default.cyan("\u{1F517} Find your Team ID:")),r.log(y.default.dim(" https://vercel.com/dashboard \u2192 Team Settings \u2192 General")),r.log(y.default.dim(" (Leave empty if using personal account)")),r.log(""),r.log(y.default.cyan("\u{1F517} Create API Token:")),r.log(y.default.dim(" https://vercel.com/account/tokens \u2192 Create Token")),r.log(y.default.dim(" Scopes needed: Read & Write for your project")),r.log(""),r.log(y.default.cyan("\u{1F517} Documentation:")),r.log(y.default.dim(" https://doorman.griffen.codes/getting-started")),r.log("")};function Nr(i){return i.interactive??i.template===void 0}var Vr=async(i,e)=>{let t=i.projectId,o=i.teamId;return e&&(r.log(y.default.bold("\u{1F4CB} Project Configuration")),r.log(y.default.dim(`We need your Vercel project details to configure the firewall.
|
|
109
109
|
`)),t||(t=await w("Enter your Vercel Project ID:",{type:"text"})),o||await w("Are you using a Vercel team account?",{type:"confirm"})&&(o=await w("Enter your Vercel Team ID:",{type:"text"})),process.env.VERCEL_TOKEN?r.log(y.default.green("\u2705 VERCEL_TOKEN environment variable found")):(r.log(""),r.log(y.default.yellow("\u26A0\uFE0F VERCEL_TOKEN environment variable not found")),r.log(y.default.dim("You'll need to set this before running sync commands.")),await w("Would you like to see how to create an API token?",{type:"confirm"})&&(r.log(""),r.log(y.default.bold("\u{1F511} Creating a Vercel API Token:")),r.log("1. Go to https://vercel.com/account/tokens"),r.log('2. Click "Create Token"'),r.log('3. Give it a descriptive name (e.g., "Doorman Firewall")'),r.log("4. Set expiration as needed"),r.log("5. Copy the token and set it as an environment variable:"),r.log(""),r.log(y.default.cyan(' export VERCEL_TOKEN="your-token-here"')),r.log(y.default.dim(" # Add this to your ~/.bashrc, ~/.zshrc, or .env file")),r.log("")))),{projectId:t,teamId:o}},Br=async i=>{try{let e=i.config||".doorman.json",t=Nr(i);if(t&&Or(),(0,bo.existsSync)(e)&&!i.force&&!await w(`Config file ${e} already exists. Do you want to overwrite it?`,{type:"confirm"})){r.info(y.default.yellow("Initialization cancelled."));return}let{projectId:o,teamId:n}=await Vr(i,t);t&&(r.log(""),r.log(y.default.bold("\u{1F3A8} Template Selection")),r.log(y.default.dim(`Choose a starting template for your firewall configuration:
|
|
@@ -112,16 +112,16 @@ Remote IP Blocking Rules to Download (${s.length}):
|
|
|
112
112
|
Custom Rules:`),`
|
|
113
113
|
`),n.forEach(c=>r.log(` - ${c.name}${c.enabled?"":ce.default.dim(" (disabled)")}`))):r.info(ce.default.cyan("No custom rules found")),s.length>0?(r.log(ce.default.bold.underline(`
|
|
114
114
|
IP Blocking Rules:`),`
|
|
115
|
-
`),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info(ce.default.cyan("No IP blocking rules found"))}var ai={};M(ai,{aliases:()=>Kr,builder:()=>Zr,command:()=>Gr,desc:()=>Hr,findFuzzyMatches:()=>So,handler:()=>Yr,levenshtein:()=>_o});var
|
|
116
|
-
Current IP rules:`)),Po(o)),process.exit(1))):i.all?n=[...o]:(r.error("Specify --ip, --interactive, or --all to select IP rules to remove."),process.exit(1));if(n.length===0){r.info("No IP rules selected for removal.");return}if(r.log(
|
|
117
|
-
${i.dryRun?"Would remove":"Removing"} ${n.length} IP rule(s):`)),Po(n),i.dryRun){r.log(
|
|
118
|
-
Dry run \u2014 no changes made.`));return}if(!await $o(n.length,i.force||!1,i.all||!1,"IP rule")){r.info("Cancelled.");return}let s=new Set(n.map(l=>l.ip)),a={...t,ips:o.filter(l=>!s.has(l.ip))};await q(a,i.config),r.success(
|
|
119
|
-
\u26A0\uFE0F Found ${n.length} rules named "${i.name}". All will be removed.`)),si(n)),n.length===0){r.error(
|
|
120
|
-
Did you mean one of these?`)),l.forEach((c,d)=>{let u=c.id?` (${c.id})`:"";r.log(
|
|
121
|
-
Use --id for exact matching, or --interactive to select from a list.`))),process.exit(1)}}else if(i.id&&i.id.length>0){let l=new Set(i.id);n=o.filter(u=>u.id&&l.has(u.id));let c=new Set(n.map(u=>u.id)),d=i.id.filter(u=>!c.has(u));d.length>0&&r.warn(
|
|
122
|
-
\u{1F4A1} Tip: Run ${
|
|
123
|
-
${i.dryRun?"Would remove":"Removing"} ${n.length} rule(s):`)),si(n),i.dryRun){r.log(
|
|
124
|
-
Dry run \u2014 no changes made.`));return}if(!await $o(n.length,i.force||!1,i.all||!1)){r.info("Cancelled.");return}let s=new Set(n),a={...t,rules:o.filter(l=>!s.has(l))};a.rules.length===0&&r.warn(
|
|
115
|
+
`),s.forEach(c=>r.log(` - ${c.ip} (${c.action})`))):r.info(ce.default.cyan("No IP blocking rules found"))}var ai={};M(ai,{aliases:()=>Kr,builder:()=>Zr,command:()=>Gr,desc:()=>Hr,findFuzzyMatches:()=>So,handler:()=>Yr,levenshtein:()=>_o});var x=S(require("chalk")),ko=require("consola");T();pe();var Gr="remove [type]",Kr=["rm","delete"],Hr="Remove a firewall rule or IP entry from your configuration",Zr={type:{type:"string",description:'What to remove: "rule" (default) or "ip"',default:"rule",choices:["rule","ip"]},interactive:{alias:"i",type:"boolean",description:"Select rules to remove from a list",default:!1},name:{alias:"n",type:"string",description:"Remove rule by name (exact match)"},id:{type:"array",string:!0,description:"Remove rule by ID (supports multiple)"},ip:{type:"string",description:"Remove IP rule by IP address"},disabled:{type:"boolean",description:"Remove all disabled (active: false) rules",default:!1},all:{type:"boolean",description:"Remove all rules (requires confirmation)",default:!1},force:{alias:"f",type:"boolean",description:"Skip confirmation prompt",default:!1},config:{alias:"c",type:"string",description:"Config file path"},dryRun:{alias:"d",type:"boolean",description:"Show what would be removed without writing",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1}};function _o(i,e){let t=i.length,o=e.length;if(t===0)return o;if(o===0)return t;let n=Array.from({length:t+1},(a,l)=>l),s=new Array(t+1).fill(0);for(let a=1;a<=o;a++){s[0]=a;for(let l=1;l<=t;l++)e.charAt(a-1)===i.charAt(l-1)?s[l]=n[l-1]:s[l]=Math.min(n[l-1]+1,s[l-1]+1,n[l]+1);for(let l=0;l<=t;l++)n[l]=s[l]}return n[t]}function So(i,e,t=3){let o=i.toLowerCase(),n=e.filter(l=>l.name.toLowerCase().includes(o)||o.includes(l.name.toLowerCase()));if(n.length>0)return n.slice(0,t);let s=e.map(l=>({rule:l,distance:_o(o,l.name.toLowerCase())})).sort((l,c)=>l.distance-c.distance),a=Math.max(i.length*.6,3);return s.filter(l=>l.distance<=a).slice(0,t).map(l=>l.rule)}function si(i){for(let e of i){let t=e.id?` (${e.id})`:"",o=e.active?"":x.default.dim(" [disabled]"),n=e.action.mitigate.action;r.log(x.default.dim(` - ${e.name}${t} \u2014 ${n}${o}`))}}function Po(i){for(let e of i){let t=e.notes?` \u2014 ${e.notes}`:"";r.log(x.default.dim(` - ${e.ip}${t}`))}}async function $o(i,e,t,o="rule"){if(e)return!0;if(t)return await w(x.default.red(`\u26A0\uFE0F Are you sure you want to remove ALL ${o}s? Type "YES" to confirm:`),{type:"text"})==="YES";let n=i===1?`Confirm removal of 1 ${o}?`:`Confirm removal of ${i} ${o}s?`;return await w(n,{type:"confirm",initial:!1})}var Yr=async i=>{try{i.debug&&(r.level=ko.LogLevels.debug),r.debug("Remove command arguments:",i);let e=i.type||"rule";r.start("Loading configuration...");let t=await j(i.config);if(e==="ip"){let o=t.ips||[];if(o.length===0){r.info("No IP rules in configuration.");return}let n=[];if(i.interactive){let l=o.map(d=>{let u=d.notes?` \u2014 ${d.notes}`:"";return`${d.ip}${u}`}),c=await w("Select IP rules to remove:",{type:"multiselect",options:l});n=o.filter(d=>{let u=`${d.ip}${d.notes?` \u2014 ${d.notes}`:""}`;return c.includes(u)})}else i.ip?(n=o.filter(l=>l.ip===i.ip),n.length===0&&(r.error(x.default.red(`No IP rule found matching "${i.ip}"`)),o.length>0&&(r.log(x.default.dim(`
|
|
116
|
+
Current IP rules:`)),Po(o)),process.exit(1))):i.all?n=[...o]:(r.error("Specify --ip, --interactive, or --all to select IP rules to remove."),process.exit(1));if(n.length===0){r.info("No IP rules selected for removal.");return}if(r.log(x.default.cyan(`
|
|
117
|
+
${i.dryRun?"Would remove":"Removing"} ${n.length} IP rule(s):`)),Po(n),i.dryRun){r.log(x.default.dim(`
|
|
118
|
+
Dry run \u2014 no changes made.`));return}if(!await $o(n.length,i.force||!1,i.all||!1,"IP rule")){r.info("Cancelled.");return}let s=new Set(n.map(l=>l.ip)),a={...t,ips:o.filter(l=>!s.has(l.ip))};await q(a,i.config),r.success(x.default.green(`\u2714 Removed ${n.length} IP rule(s) from configuration`))}else{let o=t.rules||[];if(o.length===0){r.info("No rules in configuration.");return}let n=[];if(i.interactive){let l=o.map((d,u)=>{let p=d.id?` (${d.id})`:"",g=d.active?"":" [disabled]",h=d.action.mitigate.action;return`[${u}] ${d.name}${p} \u2014 ${h}${g}`}),c=await w("Select rules to remove:",{type:"multiselect",options:l});n=o.filter((d,u)=>c.some(p=>p.startsWith(`[${u}]`)))}else if(i.name){if(n=o.filter(l=>l.name===i.name),n.length>1&&(r.warn(x.default.yellow(`
|
|
119
|
+
\u26A0\uFE0F Found ${n.length} rules named "${i.name}". All will be removed.`)),si(n)),n.length===0){r.error(x.default.red(`No rule found with exact name "${i.name}"`));let l=So(i.name,o);l.length>0&&(r.log(x.default.yellow(`
|
|
120
|
+
Did you mean one of these?`)),l.forEach((c,d)=>{let u=c.id?` (${c.id})`:"";r.log(x.default.dim(` ${d+1}. ${c.name}${u}`))}),r.log(x.default.dim(`
|
|
121
|
+
Use --id for exact matching, or --interactive to select from a list.`))),process.exit(1)}}else if(i.id&&i.id.length>0){let l=new Set(i.id);n=o.filter(u=>u.id&&l.has(u.id));let c=new Set(n.map(u=>u.id)),d=i.id.filter(u=>!c.has(u));d.length>0&&r.warn(x.default.yellow(`No rules found for IDs: ${d.join(", ")}`)),n.length===0&&(r.error(x.default.red("No matching rules found for the given IDs.")),process.exit(1))}else if(i.disabled){if(n=o.filter(l=>!l.active),n.length===0){r.info("No disabled rules found.");return}}else i.all?n=[...o]:(r.error("Specify --name, --id, --disabled, --all, or --interactive to select rules to remove."),process.exit(1));if(n.length===0){r.info("No rules selected for removal.");return}if(n.length>=5&&!i.dryRun&&!i.force&&r.log(x.default.yellow(`
|
|
122
|
+
\u{1F4A1} Tip: Run ${x.default.cyan("doorman backup")} before bulk removal operations.`)),r.log(x.default.cyan(`
|
|
123
|
+
${i.dryRun?"Would remove":"Removing"} ${n.length} rule(s):`)),si(n),i.dryRun){r.log(x.default.dim(`
|
|
124
|
+
Dry run \u2014 no changes made.`));return}if(!await $o(n.length,i.force||!1,i.all||!1)){r.info("Cancelled.");return}let s=new Set(n),a={...t,rules:o.filter(l=>!s.has(l))};a.rules.length===0&&r.warn(x.default.yellow("\u26A0\uFE0F Configuration will have no rules after removal.")),await q(a,i.config),r.success(x.default.green(`\u2714 Removed ${n.length} rule(s) from configuration`)),si(n)}r.log(""),r.log(x.default.dim(`Run ${x.default.cyan("doorman sync")} to deploy these changes.`))}catch(e){Y(e,"removing rule")}};var li={};M(li,{builder:()=>Xr,command:()=>Jr,desc:()=>Qr,handler:()=>es});var P=S(require("chalk"));T();var Jr="setup",Qr="Show setup instructions and helpful links for Doorman",Xr={},es=async i=>{r.log(""),r.log(P.default.bold.cyan("\u{1F6AA} Doorman Setup Guide")),r.log(P.default.dim(`Everything you need to get started with firewall management
|
|
125
125
|
`)),r.log(P.default.bold("\u{1F4CB} Prerequisites")),r.log("\u2022 Vercel account with a deployed project"),r.log("\u2022 Project with Pro plan or higher (firewall feature requirement)"),r.log(`\u2022 Admin access to the project/team
|
|
126
126
|
`),r.log(P.default.bold("\u{1F50D} Finding Your Project Information")),r.log(""),r.log(P.default.cyan("1. Project ID:")),r.log(" \u2022 Go to https://vercel.com/dashboard"),r.log(" \u2022 Select your project"),r.log(" \u2022 Navigate to Settings \u2192 General"),r.log(" \u2022 Copy the Project ID from the top of the page"),r.log(""),r.log(P.default.cyan("2. Team ID (if using team account):")),r.log(" \u2022 Go to https://vercel.com/dashboard"),r.log(" \u2022 Click on your team name in the top-left"),r.log(" \u2022 Go to Team Settings \u2192 General"),r.log(" \u2022 Copy the Team ID"),r.log(" \u2022 Leave empty to use your Vercel default team (every account has one)"),r.log(" \u2022 Belong to more than one team? Set this explicitly, or doorman will use whichever is your default"),r.log(""),r.log(P.default.bold("\u{1F511} Creating API Token")),r.log(""),r.log(P.default.cyan("Steps:")),r.log(" 1. Visit https://vercel.com/account/tokens"),r.log(' 2. Click "Create Token"'),r.log(' 3. Name: "Doorman Firewall Management"'),r.log(" 4. Expiration: Set as needed (90 days recommended)"),r.log(" 5. Scope: Select your project or team"),r.log(" 6. Copy the generated token"),r.log(""),r.log(P.default.cyan("Required Permissions:")),r.log(" \u2022 Read access to project settings"),r.log(" \u2022 Write access to firewall configuration"),r.log(""),r.log(P.default.bold("\u{1F30D} Environment Setup")),r.log(""),r.log(P.default.cyan("Set your API token as environment variable:")),r.log(""),r.log(P.default.green("# For current session:")),r.log('export VERCEL_TOKEN="your-token-here"'),r.log(""),r.log(P.default.green("# For permanent setup (add to ~/.bashrc or ~/.zshrc):")),r.log(`echo 'export VERCEL_TOKEN="your-token-here"' >> ~/.bashrc`),r.log(""),r.log(P.default.green("# Or create a .env file in your project:")),r.log('echo "VERCEL_TOKEN=your-token-here" > .env'),r.log(""),r.log(P.default.bold("\u{1F680} Quick Start Commands")),r.log(""),r.log(P.default.cyan("1. Initialize configuration:")),r.log(" doorman init --interactive"),r.log(""),r.log(P.default.cyan("2. Validate setup:")),r.log(" doorman validate"),r.log(""),r.log(P.default.cyan("3. Check current status:")),r.log(" doorman status"),r.log(""),r.log(P.default.cyan("4. View existing rules:")),r.log(" doorman list"),r.log(""),r.log(P.default.cyan("5. Sync your configuration:")),r.log(" doorman sync"),r.log(""),r.log(P.default.bold("\u{1F527} Common Issues")),r.log(""),r.log(P.default.yellow('\u274C "Project not found" error:')),r.log(" \u2022 Double-check your Project ID"),r.log(" \u2022 Ensure your token has access to the project"),r.log(" \u2022 Verify the project has Pro plan or higher"),r.log(""),r.log(P.default.yellow('\u274C "Unauthorized" error:')),r.log(" \u2022 Check your VERCEL_TOKEN is set correctly"),r.log(" \u2022 Ensure token hasn't expired"),r.log(" \u2022 Verify token has firewall permissions"),r.log(""),r.log(P.default.yellow('\u274C "Firewall not available" error:')),r.log(" \u2022 Upgrade to Pro plan or higher"),r.log(" \u2022 Contact Vercel support if issue persists"),r.log(""),r.log(P.default.bold("\u{1F4DA} Additional Resources")),r.log(""),r.log(P.default.cyan("Documentation:")),r.log(" \u2022 Doorman Docs: https://doorman.griffen.codes"),r.log(" \u2022 Vercel Firewall: https://vercel.com/docs/security/vercel-firewall"),r.log(" \u2022 API Reference: https://vercel.com/docs/rest-api/endpoints/firewall"),r.log(""),r.log(P.default.cyan("Support:")),r.log(" \u2022 GitHub Issues: https://github.com/gfargo/doorman/issues"),r.log(" \u2022 Vercel Support: https://vercel.com/help"),r.log(""),r.log(P.default.bold("\u{1F512} Security Best Practices")),r.log(""),r.log("\u2022 Store API tokens securely (use environment variables)"),r.log("\u2022 Set token expiration dates"),r.log("\u2022 Use principle of least privilege for token scopes"),r.log("\u2022 Regularly rotate API tokens"),r.log("\u2022 Test rules in staging before production"),r.log("\u2022 Keep backups of working configurations"),r.log(""),r.log(P.default.bold.green("\u2705 Ready to get started?")),r.log(P.default.dim("Run: ")+P.default.cyan("doorman init --interactive")),r.log("")};var ci={};M(ci,{builder:()=>os,command:()=>ts,desc:()=>is,handler:()=>ns});var L=S(require("chalk"));T();var ts="status",is="Show sync status between local and remote firewall configuration",os={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},format:{alias:"f",type:"string",choices:["table","json"],description:"Output format",default:"table"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},ns=async i=>{await Q({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"checking status"},async({config:e,provider:t})=>{await rs(t,le(e),i)})};async function rs(i,e,t){let o=t.format==="json";o||r.start("Checking sync status...");let n=await i.getChanges(e),s=i.getHealthScore(e),a=e.metadata?.version,l=n.version!==void 0&&a!==void 0&&a!==n.version,c=!n.hasChanges&&!l;if(o){r.log(JSON.stringify({provider:i.name,inSync:c,version:{local:a??null,remote:n.version??null,matches:n.version!==void 0?!l:null},rules:{toAdd:n.rulesToAdd.length,toUpdate:n.rulesToUpdate.length,toDelete:n.rulesToDelete.length},ips:{toAdd:n.ipsToAdd?.length??0,toUpdate:n.ipsToUpdate?.length??0,toDelete:n.ipsToDelete?.length??0},health:s},null,2));return}r.log(L.default.bold(`
|
|
127
127
|
\u{1F4CA} ${i.name} Sync Status Summary
|
|
@@ -129,15 +129,15 @@ Dry run \u2014 no changes made.`));return}if(!await $o(n.length,i.force||!1,i.al
|
|
|
129
129
|
`+L.default.bold("\u{1F3E5} Configuration Health Check")),r.log(`${L.default.dim("Score:")} ${s.score}/100 (${s.grade})`),s.issues.forEach(d=>{let u=d.severity==="error"?L.default.red("\u2717"):d.severity==="warning"?L.default.yellow("\u26A0"):L.default.dim("\u2139");r.log(` ${u} [${d.category}] ${d.message}`),d.suggestion&&r.log(` ${L.default.dim(d.suggestion)}`)}),s.recommendations.length>0&&(r.log(L.default.dim(`
|
|
130
130
|
Recommendations:`)),s.recommendations.forEach(d=>r.log(` - ${d}`)))}var pi={};M(pi,{builder:()=>ls,command:()=>ss,desc:()=>as,handler:()=>cs});var z=S(require("chalk"));T();var ss="sync",as="Sync Vercel Firewall rules with config file",ls={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1},allowDeletions:{type:"boolean",description:"Required together with --ci to let a non-interactive sync delete existing rules/IPs. Without it, a --ci sync that would delete anything is refused rather than applied silently.",default:!1}},cs=async i=>{await Q({config:i.config,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"syncing firewall rules"},async e=>{await ds(e.provider,e.config,i)})};async function ds(i,e,t){let o=le(e);r.start(z.default.magenta(`Calculating ${i.name} firewall configuration changes...`));let n=await i.getChanges(o),s=o.metadata?.version,a=n.version!==void 0&&s!==n.version;if(!n.hasChanges&&!a){r.success(z.default.green("No changes detected. Firewall rules are in sync."));return}r.log(z.default.bold(`
|
|
131
131
|
Proposed Changes:
|
|
132
|
-
`)),di("Rules to add",n.rulesToAdd,z.default.green("+")),di("Rules to update",n.rulesToUpdate,z.default.cyan("~")),di("Rules to delete",n.rulesToDelete,z.default.red("-"));let l=n.ipsToAdd??[],c=n.ipsToUpdate??[],d=n.ipsToDelete??[];(l.length||c.length||d.length)&&(ui("IPs to add",l,z.default.green("+")),ui("IPs to update",c,z.default.cyan("~")),ui("IPs to delete",d,z.default.red("-"))),a&&r.log(` Remote config version: ${z.default.red(s??"unknown")} ${z.default.dim("->")} ${z.default.green(n.version)}`),r.start("Starting firewall rules sync...");let u=await i.syncRules(o,{force:t.ci,allowDeletions:t.allowDeletions});if(!u.success)throw new Error(`Sync failed: ${u.errors?.join(", ")||"unknown error"}`);r.success(z.default.green("Firewall rules sync completed successfully")),r.log(` Rules: ${u.rulesAdded} added, ${u.rulesUpdated} updated, ${u.rulesDeleted} deleted`),(u.ipsAdded||u.ipsUpdated||u.ipsDeleted)&&r.log(` IPs: ${u.ipsAdded??0} added, ${u.ipsUpdated??0} updated, ${u.ipsDeleted??0} deleted`),u.warnings?.forEach(g=>r.warn(g)),u.idRemappings?.length&&(r.info(z.default.yellow("Rule IDs were reassigned by the provider and written back to the local config:")),u.idRemappings.forEach(g=>{r.log(` - ${g.name}: ${z.default.red(g.oldId||"none")} ${z.default.dim("->")} ${z.default.green(g.newId)}`)}));let p=$t(e,u);p.changed&&(await q(p.config,t.config),r.success(z.default.green("Updated local config with new version/metadata")))}function di(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(o=>r.log(` - ${o.name}`)))}function ui(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(o=>r.log(` - ${o.ip}${o.hostname?` (${o.hostname})`:""}`)))}var gi={};M(gi,{builder:()=>fs,command:()=>us,desc:()=>ps,handler:()=>hs});var Ce=S(require("chalk")),Fo=require("consola");T();var Lo={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 Uo={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 Do={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 xo={metadata:{title:"Deny Common WordPress URLs Firewall Rule",reference:"https://vercel.com/templates/other/block-wordpress-urls-firewall-rule"},config:{rules:[{name:"Deny WordPress URLs",description:"",conditionGroup:[{conditions:[{type:"path",op:"re",value:"/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-content|wp-includes|wp-signup\\.php|wp-activate\\.php|register\\.php|wp-register\\.php)"}]}],action:{mitigate:{action:"deny"}},active:!0}]}};var fi={"ai-bots":Lo,"bad-bots":Uo,"block-ofac-sanctioned-countries":Do,wordpress:xo};var Oo=i=>fi[i]?.config;pe();var us="template [name]",ps="Add a firewall rule template to your configuration",fs={name:{type:"string",description:"Name of the template to add"},config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},dryRun:{alias:"d",type:"boolean",description:"Preview changes without applying them",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}};function gs(i,e){let t=new Set(i.map(n=>n.name.toLowerCase())),o=e.filter(n=>t.has(n.name.toLowerCase())).map(n=>n.name);return[...new Set(o)]}var ms=()=>Object.keys(fi),hs=async i=>{try{i.debug&&(r.level=Fo.LogLevels.debug),r.debug("Template command arguments:",i);let e=i.name;if(!e){let c=ms();e=await w("Select a template to add:",{type:"select",options:c,initial:c[0]})}let t=Oo(e);t||(r.error(`Template not found: ${e}`),process.exit(1)),r.debug("Template content:",t),r.start("Loading current configuration...");let o=await j(i.config,"raw"),n=o.rules||[],s=gs(n,t.rules);if(i.dryRun){r.info(Ce.default.cyan(`
|
|
133
|
-
Dry run - The following rules would be added:`)),r.log(JSON.stringify(t.rules,null,2)),s.length>0&&r.warn(
|
|
132
|
+
`)),di("Rules to add",n.rulesToAdd,z.default.green("+")),di("Rules to update",n.rulesToUpdate,z.default.cyan("~")),di("Rules to delete",n.rulesToDelete,z.default.red("-"));let l=n.ipsToAdd??[],c=n.ipsToUpdate??[],d=n.ipsToDelete??[];(l.length||c.length||d.length)&&(ui("IPs to add",l,z.default.green("+")),ui("IPs to update",c,z.default.cyan("~")),ui("IPs to delete",d,z.default.red("-"))),a&&r.log(` Remote config version: ${z.default.red(s??"unknown")} ${z.default.dim("->")} ${z.default.green(n.version)}`),r.start("Starting firewall rules sync...");let u=await i.syncRules(o,{force:t.ci,allowDeletions:t.allowDeletions});if(!u.success)throw new Error(`Sync failed: ${u.errors?.join(", ")||"unknown error"}`);r.success(z.default.green("Firewall rules sync completed successfully")),r.log(` Rules: ${u.rulesAdded} added, ${u.rulesUpdated} updated, ${u.rulesDeleted} deleted`),(u.ipsAdded||u.ipsUpdated||u.ipsDeleted)&&r.log(` IPs: ${u.ipsAdded??0} added, ${u.ipsUpdated??0} updated, ${u.ipsDeleted??0} deleted`),u.warnings?.forEach(g=>r.warn(g)),u.idRemappings?.length&&(r.info(z.default.yellow("Rule IDs were reassigned by the provider and written back to the local config:")),u.idRemappings.forEach(g=>{r.log(` - ${g.name}: ${z.default.red(g.oldId||"none")} ${z.default.dim("->")} ${z.default.green(g.newId)}`)}));let p=$t(e,u);p.changed&&(await q(p.config,t.config),r.success(z.default.green("Updated local config with new version/metadata")))}function di(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(o=>r.log(` - ${o.name}`)))}function ui(i,e,t){e.length!==0&&(r.log(` ${t} ${i} (${e.length}):`),e.forEach(o=>r.log(` - ${o.ip}${o.hostname?` (${o.hostname})`:""}`)))}var gi={};M(gi,{builder:()=>fs,command:()=>us,desc:()=>ps,handler:()=>hs});var ve=S(require("chalk")),Fo=require("consola");T();var Lo={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 Uo={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 Do={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 xo={metadata:{title:"Deny Common WordPress URLs Firewall Rule",reference:"https://vercel.com/templates/other/block-wordpress-urls-firewall-rule"},config:{rules:[{name:"Deny WordPress URLs",description:"",conditionGroup:[{conditions:[{type:"path",op:"re",value:"/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-content|wp-includes|wp-signup\\.php|wp-activate\\.php|register\\.php|wp-register\\.php)"}]}],action:{mitigate:{action:"deny"}},active:!0}]}};var fi={"ai-bots":Lo,"bad-bots":Uo,"block-ofac-sanctioned-countries":Do,wordpress:xo};var Oo=i=>fi[i]?.config;pe();var us="template [name]",ps="Add a firewall rule template to your configuration",fs={name:{type:"string",description:"Name of the template to add"},config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},dryRun:{alias:"d",type:"boolean",description:"Preview changes without applying them",default:!1},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}};function gs(i,e){let t=new Set(i.map(n=>n.name.toLowerCase())),o=e.filter(n=>t.has(n.name.toLowerCase())).map(n=>n.name);return[...new Set(o)]}var ms=()=>Object.keys(fi),hs=async i=>{try{i.debug&&(r.level=Fo.LogLevels.debug),r.debug("Template command arguments:",i);let e=i.name;if(!e){let c=ms();e=await w("Select a template to add:",{type:"select",options:c,initial:c[0]})}let t=Oo(e);t||(r.error(`Template not found: ${e}`),process.exit(1)),r.debug("Template content:",t),r.start("Loading current configuration...");let o=await j(i.config,"raw"),n=o.rules||[],s=gs(n,t.rules);if(i.dryRun){r.info(ve.default.cyan(`
|
|
133
|
+
Dry run - The following rules would be added:`)),r.log(JSON.stringify(t.rules,null,2)),s.length>0&&r.warn(ve.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`));return}if(s.length>0){if(r.warn(ve.default.yellow(`\u26A0\uFE0F Rule name(s) already exist in the configuration: ${s.join(", ")}`)),i.ci||!process.stdin.isTTY){r.info(ve.default.dim("Skipping \u2014 non-interactive and rule name(s) already exist. Template not applied."));return}if(!await w("Proceed anyway?",{type:"confirm",initial:!1})){r.info("Cancelled.");return}}let a={...o,rules:[...n,...t.rules]},l=Ae.safeParse(a);l.success||(r.error(ve.default.red("The resulting configuration would be invalid:")),l.error.errors.forEach(c=>{let d=c.path.join(".");r.error(ve.default.red(` - ${d}: ${c.message}`))}),r.info(ve.default.dim("Template was not applied. Fix the issues above and try again.")),process.exit(1)),r.start("Saving updated configuration..."),await q(a,i.config,{validate:!1}),r.success(ve.default.green(`Successfully added template '${e}' to configuration`))}catch(e){Y(e,"adding template")}};var mi={};M(mi,{builder:()=>Is,command:()=>ys,desc:()=>ws,handler:()=>Rs});var ee=S(require("chalk"));T();var ys="validate",ws="Validate firewall configuration file",Is={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},verbose:{alias:"v",type:"boolean",description:"Show detailed validation results",default:!1}},Rs=async i=>{try{let e=await j(i.config,"raw"),t=Re.getInstance(),o=we(e);i.verbose&&r.start(`Validating configuration file...
|
|
134
134
|
`);let n=o?Le.safeParse(e):Ae.safeParse(e);i.verbose&&(r.log(ee.default.bold.underline("Zod Schema Validation:")),n.success?r.log(ee.default.green("\u2713 Schema validation passed")):(r.error(ee.default.red("\u2717 Schema validation failed:")),n.error.errors.forEach(l=>{let c=l.path.join(".");r.error(ee.default.red(` - ${c}: ${l.message}`))})));let s=!0,a=[];try{t.validateConfig(e),i.verbose&&(r.log(ee.default.bold.underline(`
|
|
135
|
-
AJV Schema Validation:`)),r.log(ee.default.green("\u2713 JSON Schema validation passed")))}catch(l){if(s=!1,l instanceof
|
|
135
|
+
AJV Schema Validation:`)),r.log(ee.default.green("\u2713 JSON Schema validation passed")))}catch(l){if(s=!1,l instanceof O)a=l.ajvErrors||[],i.verbose&&(r.log(ee.default.bold.underline(`
|
|
136
136
|
AJV Schema Validation:`)),r.error(ee.default.red("\u2717 JSON Schema validation failed:")),a.forEach(c=>{r.error(ee.default.red(` - ${c.instancePath}: ${c.message}`))}));else throw l}if(n.success&&s&&i.verbose){r.log(ee.default.bold.underline(`
|
|
137
137
|
Custom Validations:`));let l=n.data,c=new Set,d=new Set;for(let u of l.rules)c.has(u.name)&&d.add(u.name),c.add(u.name);r.log(`${ee.default.cyan.dim(`
|
|
138
138
|
Rule Names:`)}`),d.size>0?(r.error(ee.default.red("\u2717 Duplicate rule names found:")),d.forEach(u=>r.error(ee.default.red(` - "${u}"`)))):r.log(ee.default.green("\u2713 All rule names are unique")),r.log("")}if(n.success&&s)r.success(ee.default.green("Configuration is valid"));else{if(i.verbose)throw new Error("Configuration validation failed");{let l=[...n.success?[]:n.error.errors.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`),...s?[]:a.map(c=>`${c.instancePath||"(root)"}: ${c.message}`)];throw new Error(`Configuration validation failed:
|
|
139
139
|
${l.join(`
|
|
140
|
-
`)}`)}}}catch(e){Y(e,"validating configuration")}};var hi={};M(hi,{builder:()=>bs,command:()=>
|
|
140
|
+
`)}`)}}}catch(e){Y(e,"validating configuration")}};var hi={};M(hi,{builder:()=>bs,command:()=>vs,desc:()=>Cs,handler:()=>Es});var de=S(require("chalk")),kt=require("fs");T();var vs="watch",Cs="Watch config file for changes and auto-sync",bs={config:{alias:"c",type:"string",description:"Path to firewall config file (defaults to .doorman.json)"},provider:J,projectId:{alias:"p",type:"string",description:"Vercel Project ID (can be set in config file)"},teamId:{alias:"t",type:"string",description:"Vercel Team ID (can be set in config file)"},token:{type:"string",description:"Vercel API token (defaults to VERCEL_TOKEN env var)"},apiToken:{type:"string",description:"Cloudflare API token (defaults to CLOUDFLARE_API_TOKEN env var)"},zoneId:{type:"string",description:"Cloudflare Zone ID (defaults to CLOUDFLARE_ZONE_ID env var)"},accountId:{type:"string",description:"Cloudflare Account ID (optional)"},workspaceId:{type:"string",description:"Fastly Next-Gen WAF Workspace ID (defaults to FASTLY_WORKSPACE_ID env var)"},interval:{alias:"i",type:"number",description:"Watch interval in milliseconds",default:1e3},debug:{type:"boolean",description:"Enable debug logging",default:!1},ci:{type:"boolean",description:"Run in CI mode (non-interactive)",default:!1}},Es=async i=>{let e=i.config||".doorman.json";await Q({config:e,provider:i.provider,projectId:i.projectId,teamId:i.teamId,token:i.token,apiToken:i.apiToken,zoneId:i.zoneId,accountId:i.accountId,workspaceId:i.workspaceId,debug:i.debug,ci:i.ci,errorContext:"setting up watch mode"},async({provider:t})=>{let o=!1,n=0;r.success(de.default.green(`\u{1F440} Watching ${e} for changes...`)),r.log(de.default.dim("Press Ctrl+C to stop watching")),r.log("");let s=async(c,d)=>{if(!(o||c.mtime.getTime()===n)){o=!0,n=c.mtime.getTime();try{r.log(de.default.yellow(`\u{1F4DD} Config file changed at ${new Date().toLocaleTimeString()}`)),r.start("Validating and syncing changes...");let u=await j(e);await Ts(t,u,e),r.log(de.default.dim("Watching for more changes..."))}catch(u){r.error(de.default.red(`\u274C Sync failed: ${u instanceof Error?u.message:String(u)}`)),r.log(de.default.dim("Continuing to watch for changes..."))}finally{o=!1}}};(0,kt.watchFile)(e,{interval:i.interval},s);let a=()=>{r.log(`
|
|
141
141
|
`),r.info(de.default.yellow("Stopping watch mode...")),(0,kt.unwatchFile)(e),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a);let l=()=>{setTimeout(l,1e3)};l()})};async function Ts(i,e,t){let o=le(e),n=await i.getChanges(o),s=o.metadata?.version,a=n.version!==void 0&&s!==n.version;if(!n.hasChanges&&!a){r.info(de.default.blue("No changes detected, skipping sync"));return}let l=n.rulesToAdd.length+n.rulesToUpdate.length+n.rulesToDelete.length+(n.ipsToAdd?.length??0)+(n.ipsToUpdate?.length??0)+(n.ipsToDelete?.length??0);r.log(de.default.cyan(`Syncing ${l} changes...`));let c=await i.syncRules(o,{force:!0,allowDeletions:!0});if(!c.success)throw new Error(`Sync failed: ${c.errors?.join(", ")||"unknown error"}`);r.success(de.default.green(`\u2705 Sync completed at ${new Date().toLocaleTimeString()}`)),c.warnings?.forEach(u=>r.warn(u)),c.idRemappings?.length&&c.idRemappings.forEach(u=>{r.info(de.default.dim(` Rule "${u.name}" ID updated: ${u.oldId||"none"} -> ${u.newId}`))});let d=$t(e,c);d.changed&&await q(d.config,t)}var No=[li,ni,jt,ri,ci,ti,pi,mi,ii,gi,ai,ei,oi,hi];(0,Vo.config)();async function As(){let i=(await import("chalk")).default,e=(0,Bo.default)(process.argv.slice(2));e.usage(`${i.bold("\u{1F6AA} Doorman")}
|
|
142
142
|
|
|
143
143
|
${i.dim("Manage firewall rules as code across multiple providers")}`);for(let t of No)e.command(t);e.demandCommand(1,"You need at least one command before moving on").help().epilogue(i.dim(`See ${i.bold("https://doorman.griffen.codes/getting-started")} for more info`)).argv}As().catch(console.error);
|