@@ -370,6 +370,11 @@ export async function cpFromInstance(cfg: CpConfig, opts: CpFromInstanceOptions)
370370 } ) ;
371371
372372 ws . on ( 'message' , ( data : Buffer | string ) => {
373+ // Don't process messages after the operation has settled
374+ if ( settled ) {
375+ return ;
376+ }
377+
373378 // Try to parse as JSON first
374379 let msg : CpMessage | null = null ;
375380 if ( typeof data === 'string' || ( Buffer . isBuffer ( data ) && ! isBinaryData ( data ) ) ) {
@@ -397,7 +402,13 @@ export async function cpFromInstance(cfg: CpConfig, opts: CpFromInstanceOptions)
397402
398403 if ( currentHeader . is_dir ) {
399404 fs . mkdirSync ( targetPath , { recursive : true , mode : currentHeader . mode } ) ;
400- } else if ( currentHeader . is_symlink && currentHeader . link_target ) {
405+ } else if ( currentHeader . is_symlink ) {
406+ // Handle symlink - ensure link_target is present
407+ if ( ! currentHeader . link_target ) {
408+ doReject ( new Error ( `Symlink ${ currentHeader . path } missing link target` ) ) ;
409+ ws . close ( ) ;
410+ return ;
411+ }
401412 // Validate symlink target
402413 const linkTarget = currentHeader . link_target ;
403414 if ( path . isAbsolute ( linkTarget ) || path . normalize ( linkTarget ) . startsWith ( '..' ) ) {
@@ -417,7 +428,10 @@ export async function cpFromInstance(cfg: CpConfig, opts: CpFromInstanceOptions)
417428 fs . mkdirSync ( path . dirname ( targetPath ) , { recursive : true } ) ;
418429 currentFile = fs . createWriteStream ( targetPath , { mode : currentHeader . mode } ) ;
419430 // Add error handler to prevent unhandled 'error' events from crashing
431+ const fileBeingWritten = currentFile ;
420432 currentFile . on ( 'error' , ( err ) => {
433+ fileBeingWritten . destroy ( ) ;
434+ currentFile = null ;
421435 doReject ( new Error ( `Failed to write file ${ targetPath } : ${ err . message } ` ) ) ;
422436 ws . close ( ) ;
423437 } ) ;
0 commit comments