// Telnet commands may be split across TCP packets, including subnegotiations. export class TelnetText { constructor(reply){this.reply=reply;this.state='text';this.command=0;} read(chunk){const out=[];for(const b of chunk){switch(this.state){ case 'text':if(b===255)this.state='iac';else out.push(b);break; case 'iac':if(b===255){out.push(b);this.state='text';}else if(b===250)this.state='sub';else if([251,252,253,254].includes(b)){this.command=b;this.state='option';}else this.state='text';break; case 'option':if(this.command===251)this.reply(Buffer.from([255,254,b]));if(this.command===253)this.reply(Buffer.from([255,252,b]));this.state='text';break; case 'sub':if(b===255)this.state='sub-iac';break; case 'sub-iac':this.state=b===240?'text':'sub';break; }}return Buffer.from(out);} } // BPQ can send a custom CTEXT without a node prompt. Wait for the banner to // settle before declaring success; repeated credential prompts mean rejection. export class TelnetLogin { constructor(socket,credentials,options,ready){ this.socket=socket;this.credentials=credentials;this.options=options;this.ready=ready;this.stage=0;this.buffer='';this.closed=false; this.deadline=setTimeout(()=>this.fail('Accesso Telnet non confermato'),15000);this.deadline.unref(); } hasPrompt(text,kind){ const custom=this.options[kind+'Prompt']; return !!(custom&&text.toLowerCase().includes(custom.toLowerCase()))||(kind==='login'?/(?:^|[\r\n])\s*(?:Username|Login|User)\s*:/i:/\bPassword\s*:/i).test(text); } clean(text){ const password=this.credentials?.password; if(!password)return text;let clean=text.split(password).join(''); for(let n=password.length-1;n>0;n--)if(clean.endsWith(password.slice(0,n))){clean=clean.slice(0,-n);break;} return clean; } read(text){ if(this.closed||!text)return; this.buffer+=text;if(this.buffer.length>12000){this.fail('Accesso Telnet non confermato');return;} if(this.stage===0&&this.hasPrompt(this.buffer,'login')){this.buffer='';this.stage=1;this.socket.write(this.credentials.user+'\r');return;} if(this.stage===1&&this.hasPrompt(this.buffer,'password')){this.buffer='';this.stage=2;this.socket.write(this.credentials.password+'\r');return;} if(this.stage!==2)return; clearTimeout(this.quiet); const clean=this.clean(this.buffer); if(this.hasPrompt(clean,'login')||this.hasPrompt(clean,'password')||/\b(?:invalid|incorrect|denied|authentication failed|access rejected)\b/i.test(clean)){this.fail('Accesso rifiutato');return;} if(!clean.trim())return; this.quiet=setTimeout(()=>{ if(this.closed||this.socket.destroyed)return; const banner=this.clean(this.buffer).trimStart();this.close();this.ready(banner); },400);this.quiet.unref(); } fail(message){this.close();this.socket.destroy(new Error(message));} close(){this.closed=true;clearTimeout(this.quiet);clearTimeout(this.deadline);this.buffer='';this.credentials=null;} }