Skip to content

Commit b82d478

Browse files
committed
fix: improve error handling in cpFromInstance
- Handle symlinks with missing link_target - Check settled flag to stop processing after rejection - Nullify and destroy currentFile on write error
1 parent a4b3fb6 commit b82d478

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/lib/cp.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)