2026-07-12 21:12:18 +00:00
import { createHash } from "node:crypto" ;
import { constants } from "node:fs" ;
2026-09-08 10:59:13 +08:00
import {
lstat ,
mkdir ,
open ,
realpath ,
rm ,
type FileHandle ,
} from "node:fs/promises" ;
2026-07-12 21:12:18 +00:00
import { basename , dirname , isAbsolute , join , resolve } from "node:path" ;
import type { Readable } from "node:stream" ;
import { streamChunkToBuffer } from "./StreamBytes.js" ;
import {
ArtifactPathRegistry ,
normalizeArtifactPath ,
} from "./ArtifactPaths.js" ;
2026-09-29 12:15:49 +08:00
import { ArtifactReaderFailure } from "./ArtifactReader.js" ;
2026-07-12 21:12:18 +00:00
2026-07-12 21:45:26 +00:00
/** One file durably written to an operation-owned output tree. */
2026-07-12 21:12:18 +00:00
export interface SafeOutputFile {
readonly relativePath : string ;
readonly sha256 : string ;
readonly bytesWritten : number ;
}
2026-08-10 02:28:11 +08:00
/** Cleanup state established while rolling back an uncommitted tree. */
export type SafeOutputCleanup =
| { readonly status : "not-required" }
| { readonly status : "complete" ; readonly residualPaths : readonly [] }
| {
readonly status : "incomplete" ;
readonly residualPaths : readonly [ string , ... string []];
};
2026-07-12 21:12:18 +00:00
2026-07-12 21:45:26 +00:00
/** Symlink-resistant materialization in an exclusively owned, initially absent tree. */
2026-07-12 21:12:18 +00:00
export class SafeOutputTree {
readonly # registry = new ArtifactPathRegistry ();
readonly # outputRoot : string ;
# published = false ;
# cleanup : SafeOutputCleanup = {
2026-08-10 02:28:11 +08:00
status : "not-required" ,
2026-07-12 21:12:18 +00:00
};
2026-10-07 00:46:52 +07:00
private constructor (
outputRoot : string ,
private readonly platform : NodeJS.Platform ,
) {
2026-07-12 21:12:18 +00:00
this . # outputRoot = outputRoot ;
}
2026-10-07 00:46:52 +07:00
/**
* Exclusively create the absent destination as this operation's owned tree.
*
* POSIX mode bits and directory `fchmod`/`fsync` have no Windows equivalent:
* `mkdir` already applies the requested mode, so the redundant handle
* `chmod` is skipped there to avoid an `EPERM` on the directory descriptor.
*/
static async create (
outputRoot : string ,
platform : NodeJS.Platform = process . platform ,
) : Promise < SafeOutputTree > {
2026-07-12 21:12:18 +00:00
if ( ! isAbsolute ( outputRoot ))
throw new ArtifactReaderFailure (
"path" ,
"Extraction output root must be absolute" ,
);
const requested = resolve ( outputRoot );
const name = basename ( requested );
if ( name === "." || name === ".." )
throw new ArtifactReaderFailure ( "path" , "Invalid extraction output root" );
const parent = await realpath ( dirname ( requested )). catch (
( cause : unknown ) => {
throw new ArtifactReaderFailure (
"unavailable" ,
"Extraction output parent is unavailable" ,
{ cause },
);
},
);
const canonicalOutput = join ( parent , name );
await mkdir ( canonicalOutput , { mode : 0o700 }). catch (( cause : unknown ) => {
if ( isAlreadyExists ( cause ))
throw new ArtifactReaderFailure (
"path" ,
"Extraction output root already exists" ,
{ cause },
);
throw cause ;
});
try {
2026-10-07 00:46:52 +07:00
if ( platform !== "win32" ) {
const stagingHandle = await open (
canonicalOutput ,
constants . O_RDONLY | constants . O_DIRECTORY ,
);
try {
await stagingHandle . chmod ( 0 o700 );
} finally {
await stagingHandle . close ();
}
2026-07-12 21:12:18 +00:00
}
2026-10-07 00:46:52 +07:00
return new SafeOutputTree ( canonicalOutput , platform );
2026-07-12 21:12:18 +00:00
} catch ( cause : unknown ) {
await rm ( canonicalOutput , { recursive : true , force : true });
throw cause ;
}
}
get outputRoot () : string {
return this . # outputRoot ;
}
get cleanup () : SafeOutputCleanup {
2026-07-14 14:39:02 +08:00
return structuredClone ( this . # cleanup );
2026-07-12 21:12:18 +00:00
}
2026-09-29 12:15:49 +08:00
/** Stream one regular file with exact byte and digest verification. */
2026-07-12 21:12:18 +00:00
async write (
relativePath : string ,
source : Readable ,
expectedSha256 : string ,
signal? : AbortSignal ,
) : Promise < SafeOutputFile > {
this . # assertWritable ();
2026-09-29 12:15:49 +08:00
const path = normalizeArtifactPath ( relativePath );
2026-07-12 21:12:18 +00:00
this . # registry . add ( path , "file" );
const destination = await this . # prepareParent ( path );
const handle = await open (
destination ,
constants . O_CREAT |
constants . O_EXCL |
constants . O_WRONLY |
constants . O_NOFOLLOW ,
0 o600 ,
). catch (( cause : unknown ) => {
throw new ArtifactReaderFailure (
"path" ,
`Could not exclusively create extraction path: ${ path } ` ,
{ cause },
);
});
const hash = createHash ( "sha256" );
let bytes = 0 ;
try {
for await ( const raw of source ) {
abortIfNeeded ( signal );
const chunk = streamChunkToBuffer ( raw );
bytes += chunk . length ;
hash . update ( chunk );
await writeAll ( handle , chunk );
}
const sha256 = hash . digest ( "hex" );
if ( sha256 !== expectedSha256 )
throw new ArtifactReaderFailure (
"integrity" ,
`Extracted content disagrees with inventory: ${ path } ` ,
);
await handle . sync ();
await handle . close ();
const readback = await hashFile ( destination , bytes , signal );
if ( readback . sha256 !== sha256 || readback . bytes !== bytes )
throw new ArtifactReaderFailure (
"integrity" ,
`Durable readback verification failed: ${ path } ` ,
);
return { relativePath : path , sha256 , bytesWritten : bytes };
} catch ( cause : unknown ) {
2026-10-06 05:00:54 +08:00
// best-effort cleanup: file-handle close must not mask the write failure.
2026-07-12 21:12:18 +00:00
await handle . close (). catch (() => undefined );
throw cause ;
}
}
2026-07-12 21:45:26 +00:00
/** Sync the owned output tree and prevent further writes through this instance. */
2026-07-12 21:12:18 +00:00
async commit () : Promise < void > {
this . # assertWritable ();
2026-10-07 00:46:52 +07:00
// Windows has no directory fsync; file contents are already synced in write().
if ( this . platform === "win32" ) {
this . # published = true ;
return ;
}
2026-07-12 21:12:18 +00:00
const parent = await open (
dirname ( this . # outputRoot ),
constants . O_RDONLY | constants . O_DIRECTORY ,
);
2026-09-08 10:59:13 +08:00
let output : FileHandle | undefined ;
2026-07-12 21:12:18 +00:00
try {
2026-09-08 10:59:13 +08:00
output = await open (
this . # outputRoot ,
constants . O_RDONLY | constants . O_DIRECTORY ,
);
await output . sync ();
2026-07-12 21:12:18 +00:00
await parent . sync ();
this . # published = true ;
} catch ( cause : unknown ) {
throw new ArtifactReaderFailure (
"path" ,
2026-07-12 21:45:26 +00:00
"Could not durably sync extraction output" ,
2026-07-12 21:12:18 +00:00
{ cause },
);
} finally {
2026-09-08 10:59:13 +08:00
await Promise . allSettled ([ parent . close (), output ? . close ()]);
2026-07-12 21:12:18 +00:00
}
}
2026-07-12 21:45:26 +00:00
/** Remove only this operation's unsealed tree and verify absence. */
2026-07-12 21:12:18 +00:00
async rollback () : Promise < SafeOutputCleanup > {
2026-07-14 14:39:02 +08:00
if ( this . # published ) return structuredClone ( this . # cleanup );
2026-10-09 21:01:52 +08:00
let removalFailure : unknown ;
try {
await rm ( this . # outputRoot , { recursive : true , force : true });
} catch ( cause : unknown ) {
removalFailure = cause ;
}
2026-09-08 10:59:13 +08:00
const absent = await isAbsent ( this . # outputRoot );
2026-08-10 02:28:11 +08:00
this . # cleanup = absent
? { status : "complete" , residualPaths : [] }
: {
status : "incomplete" ,
2026-09-08 10:59:13 +08:00
residualPaths : [ basename ( this . # outputRoot )],
2026-08-10 02:28:11 +08:00
};
2026-07-12 21:12:18 +00:00
if ( ! absent )
throw new ArtifactReaderFailure (
"integrity" ,
2026-10-09 21:01:52 +08:00
`Extraction output cleanup could not be verified ${ removalFailure === undefined ? "" : `: ${ removalFailure instanceof Error ? removalFailure.message : String ( removalFailure ) } ` } ` ,
{
cause : removalFailure ,
cleanup : {
reason :
removalFailure instanceof Error
? removalFailure . message
: "Extraction output root remains after rollback" ,
resources : [ this . # outputRoot ],
},
},
2026-07-12 21:12:18 +00:00
);
2026-07-14 14:39:02 +08:00
return structuredClone ( this . # cleanup );
2026-07-12 21:12:18 +00:00
}
async # prepareParent ( relativePath : string ) : Promise < string > {
const parts = relativePath . split ( "/" );
const fileName = parts . pop ();
if ( fileName === undefined )
throw new ArtifactReaderFailure ( "path" , "Invalid extraction path" );
2026-09-08 10:59:13 +08:00
let current = this . # outputRoot ;
2026-07-12 21:12:18 +00:00
for ( const part of parts ) {
current = join ( current , part );
await mkdir ( current , { mode : 0o700 }). catch (( cause : unknown ) => {
if ( ! isAlreadyExists ( cause )) throw cause ;
});
const metadata = await lstat ( current );
if ( ! metadata . isDirectory () || metadata . isSymbolicLink ())
throw new ArtifactReaderFailure (
"path" ,
`Unsafe extraction parent: ${ relativePath } ` ,
);
}
return join ( current , fileName );
}
# assertWritable () : void {
if ( this . # published )
throw new ArtifactReaderFailure (
"integrity" ,
"Extraction tree is already committed" ,
);
}
}
const hashFile = async (
path : string ,
maximum : number ,
signal? : AbortSignal ,
) : Promise < { readonly sha256 : string ; readonly bytes : number } > => {
const handle = await open ( path , constants . O_RDONLY | constants . O_NOFOLLOW );
const hash = createHash ( "sha256" );
let bytes = 0 ;
try {
for await ( const raw of handle . createReadStream ({ autoClose : false })) {
abortIfNeeded ( signal );
const chunk = streamChunkToBuffer ( raw );
bytes += chunk . length ;
if ( bytes > maximum )
throw new ArtifactReaderFailure (
"integrity" ,
"Readback exceeded the bytes written" ,
);
hash . update ( chunk );
}
} finally {
await handle . close ();
}
return { sha256 : hash.digest ( "hex" ), bytes };
};
const writeAll = async (
handle : Awaited < ReturnType < typeof open >>,
chunk : Buffer ,
) : Promise < void > => {
let offset = 0 ;
while ( offset < chunk . length ) {
const { bytesWritten } = await handle . write (
chunk ,
offset ,
chunk . length - offset ,
);
if ( bytesWritten === 0 )
throw new ArtifactReaderFailure (
"unavailable" ,
"Extraction output stopped accepting bytes" ,
);
offset += bytesWritten ;
}
};
const isAbsent = async ( path : string ) : Promise < boolean > =>
lstat ( path ). then (
() => false ,
( cause : unknown ) => {
if ( isNotFound ( cause )) return true ;
throw cause ;
},
);
const isNotFound = ( cause : unknown ) : boolean =>
cause instanceof Error && "code" in cause && cause . code === "ENOENT" ;
const isAlreadyExists = ( cause : unknown ) : boolean =>
cause instanceof Error && "code" in cause && cause . code === "EEXIST" ;
const abortIfNeeded = ( signal? : AbortSignal ) : void => {
if ( signal ? . aborted === true )
throw new ArtifactReaderFailure (
"cancelled" ,
"Artifact extraction cancelled" ,
);
};