ZZZ Digital Lab

Back to n8n workflow hardening

lint.cjs

'use strict';
// Static policy linter for these exports, not a full n8n schema or security validator.
const fs=require('node:fs');
function lintWorkflow(workflow,related=[]){
 const findings=[];
 const add=(code,node,detail)=>findings.push({code,node:node||'(workflow)',detail});
 if(!workflow||!Array.isArray(workflow.nodes)||!workflow.connections){add('STRUCTURE',null,'Expected nodes array and connections object');return findings;}
 const nodes=workflow.nodes, byName=new Map(nodes.map(n=>[n.name,n]));
 if(byName.size!==nodes.length) add('DUPLICATE_NODE_NAME',null,'Node names must be unique');
 if(workflow.active!==false) add('ACTIVE_EXPORT',null,'Portfolio export must remain inactive');
 if(!(Number.isInteger(workflow.settings?.executionTimeout)&&workflow.settings.executionTimeout>0&&workflow.settings.executionTimeout<=300)) add('WORKFLOW_TIMEOUT',null,'Set a positive workflow execution timeout <= 300 seconds');
 const isError=nodes.some(n=>n.type==='n8n-nodes-base.errorTrigger');
 if(!isError){
  const errorId=workflow.settings?.errorWorkflow;
  if(!errorId) add('MISSING_ERROR_WORKFLOW',null,'Main workflow must reference an error workflow');
  else if(!related.some(w=>w.id===errorId&&w.nodes?.some(n=>n.type==='n8n-nodes-base.errorTrigger'))) add('UNKNOWN_ERROR_WORKFLOW',null,'Referenced error workflow must be supplied with an Error Trigger');
 } else if(workflow.settings?.errorWorkflow===workflow.id) add('RECURSIVE_ERROR_WORKFLOW',null,'Do not explicitly route an error workflow to itself');
 function inspect(value,node,key=''){
  if(!value||typeof value!=='object') return;
  if(typeof value.name==='string'&&/^(authorization|x-api-key)$/i.test(value.name)&&typeof value.value==='string'&&!value.value.startsWith('={{')) add('INLINE_SECRET',node,'Sensitive header value is inline; value redacted');
  for(const [k,v] of Object.entries(value)){
   if(k==='credentials') continue; // credential IDs/names are references, not values
   if(/^(password|api[_-]?key|access[_-]?token|client[_-]?secret)$/i.test(k)&&v&&typeof v==='string'&&!v.startsWith('={{')) add('INLINE_SECRET',node,'Sensitive parameter value is inline; value redacted');
   if(v&&typeof v==='object') inspect(v,node,k);
  }
 }
 const adjacency=new Map(nodes.map(n=>[n.name,[]]));
 for(const [from,channels] of Object.entries(workflow.connections)){
  if(!byName.has(from)) add('BROKEN_CONNECTION',from,'Source node does not exist');
  for(const outputs of Object.values(channels||{})){
   if(!Array.isArray(outputs)){add('BROKEN_CONNECTION',from,'Connection outputs must be arrays');continue;}
   for(const branch of outputs) for(const edge of branch||[]){
    if(!byName.has(edge.node)) add('BROKEN_CONNECTION',from,'Target node does not exist');
    else adjacency.get(from)?.push(edge.node);
   }
  }
 }
 const visiting=new Set(),done=new Set();let cycle=false;
 function visit(name){if(visiting.has(name)){cycle=true;return;}if(done.has(name))return;visiting.add(name);for(const next of adjacency.get(name)||[])visit(next);visiting.delete(name);done.add(name);}
 for(const name of adjacency.keys()) visit(name);
 if(cycle) add('UNBOUNDED_CYCLE',null,'This policy requires an acyclic graph; review any back-edge');
 function reaches(from,target){const seen=new Set(),queue=[from];while(queue.length){const n=queue.shift();if(n===target)return true;if(seen.has(n))continue;seen.add(n);queue.push(...(adjacency.get(n)||[]));}return false;}
 for(const n of nodes){
  inspect(n.parameters,n.name);
  if(n.type==='n8n-nodes-base.code'&&/while\s*\(\s*true\s*\)|for\s*\(\s*;\s*;\s*\)/.test(n.parameters?.jsCode||'')) add('CODE_LOOP_REVIEW',n.name,'Obvious unbounded Code loop requires review');
  if(n.type==='n8n-nodes-base.webhook'){
   if(n.parameters?.authentication!=='headerAuth'||!n.credentials?.httpHeaderAuth?.id) add('WEBHOOK_AUTH',n.name,'Require a locally configured header-auth reference');
   if(n.parameters?.responseMode!=='lastNode') add('EARLY_ACK',n.name,'Acknowledge after processing, with client timeout/replay policy');
  }
  if(n.type==='n8n-nodes-base.httpRequest'){
   if(n.retryOnFail!==true||!Number.isInteger(n.maxTries)||n.maxTries<2||n.maxTries>5) add('RETRY_BOUND',n.name,'Require 2-5 bounded attempts');
   if(!Number.isInteger(n.waitBetweenTries)||n.waitBetweenTries<500||n.waitBetweenTries>10000) add('RETRY_BACKOFF',n.name,'Require a fixed retry delay of 500-10000 ms');
   if(!(n.parameters?.options?.timeout>0&&n.parameters.options.timeout<=10000)) add('HTTP_TIMEOUT',n.name,'Require a request header timeout <= 10000 ms');
   if(n.parameters?.authentication!=='genericCredentialType'||!n.credentials?.httpHeaderAuth?.id) add('CREDENTIAL_REFERENCE',n.name,'Use a locally configured credential reference');
   const header=n.parameters?.headerParameters?.parameters?.find(h=>h.name?.toLowerCase()==='idempotency-key');
   if(!header?.value?.startsWith('={{ $json.')) add('IDEMPOTENCY_HEADER',n.name,'Stable event-based Idempotency-Key header is required');
   if(n.parameters?.method!=='PUT') add('IDEMPOTENT_METHOD',n.name,'This receiver contract uses idempotent PUT resource writes');
   if(n.parameters?.options?.pagination) add('PAGINATION_REVIEW',n.name,'Pagination requires a separately verified bound');
  }
  if(n.type==='n8n-nodes-base.code'&&n.name==='Prepare Events'){
   const code=n.parameters?.jsCode||'';
   if(!/const MAX_BATCH = (?:[1-9]|[1-9][0-9]);/.test(code)||!code.includes('if (events.length > MAX_BATCH) throw')) add('BATCH_BOUND',n.name,'Expected explicit bounded event guard');
   if(!code.includes("'lead-event:v1:'")||!code.includes('IDEMPOTENCY_CONFLICT')) add('EVENT_IDENTITY',n.name,'Expected stable event identity and payload conflict rejection');
  }
 }
 if(!isError){
  if(!byName.has('Prepare Events')) add('BATCH_BOUND',null,'Missing bounded envelope preparation');
  const deliver=byName.get('Deliver Event'),dlq=byName.get('Persist Dead Letter');
  const errorTargets=workflow.connections['Deliver Event']?.main?.[1]||[];
  if(deliver?.onError!=='continueErrorOutput'||!errorTargets.some(e=>reaches(e.node,'Persist Dead Letter'))||!dlq||!reaches('Persist Dead Letter','Delivery Failed')) add('DEAD_LETTER_PATH',null,'Exhausted delivery must reach durable dead-letter sink then fail visibly');
  if(!byName.get('Build Dead Letter')?.parameters?.jsCode?.includes('itemMatching(index)')) add('DLQ_ITEM_LINKING',null,'Dead-letter payload must recover the original linked event');
 }
 return findings;
}
if(require.main===module){
 const files=process.argv.slice(2);
 if(!files.length){console.error('Usage: node lint.cjs <main.json> <related-error-workflow.json>');process.exitCode=2;}
 else{
  try{
   if(files.some(f=>!f.endsWith('.json'))) throw new Error('JSON_INPUT_REQUIRED');
   const workflows=files.map(f=>JSON.parse(fs.readFileSync(f,'utf8')));let count=0;
   workflows.forEach((w,i)=>{const findings=lintWorkflow(w,workflows);count+=findings.length;console.log(JSON.stringify({file:files[i].replaceAll('\\','/'),findings},null,2));});process.exitCode=count?1:0;
  }catch(error){console.error('LINT_INPUT_ERROR: invalid or unreadable JSON input');process.exitCode=2;}
 }
}
module.exports={lintWorkflow};