@leitwerk-dev/session-transfer 0.0.0-bootstrap.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/archive.ts","../src/format.ts","../src/project-evidence.ts","../src/symlink-confinement.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport {\n\tchmod,\n\tlstat,\n\tmkdir,\n\topen,\n\treaddir,\n\treadlink,\n\tsymlink,\n\tutimes,\n\twriteFile,\n} from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { type Readable, Transform } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { createZstdCompress, createZstdDecompress, constants as zlibConstants } from \"node:zlib\";\nimport tar from \"tar-stream\";\nimport {\n\tassertSafeRelativePath,\n\tDEFAULT_SESSION_TRANSFER_LIMITS,\n\tisPathInside,\n\ttype LeitwerkTransferManifestV1,\n\tparseTransferManifest,\n\ttype SessionTransferLimits,\n\ttype SessionTransferPreflight,\n\ttype TransferArchiveProgress,\n} from \"./format.js\";\nimport { readProjectEvidence } from \"./project-evidence.js\";\nimport { assertConfinedSymlinks } from \"./symlink-confinement.js\";\n\nconst MANIFEST_MAX_BYTES = 1024 * 1024;\ntype TarHeader = Partial<tar.Header> & Pick<tar.Header, \"name\">;\n\nexport interface PortableEntry {\n\trelativePath: string;\n\tkind: \"file\" | \"directory\" | \"symlink\";\n\tmode: number;\n\tmtimeMs: number;\n\tsize: number;\n\tlinkTarget?: string;\n}\n\nexport interface TransferPreflight extends SessionTransferPreflight {\n\tentries: PortableEntry[];\n}\n\nexport interface ExtractTransferResult {\n\tmanifest: LeitwerkTransferManifestV1;\n\tcompressedBytes: number;\n\tstreamSha256: string;\n}\n\nexport interface PreparedTransferArchive {\n\tmanifest: LeitwerkTransferManifestV1;\n\tpreflight: TransferPreflight;\n\tstream(input: { signal?: AbortSignal }): Readable;\n}\n\nfunction abortIfNeeded(signal?: AbortSignal): void {\n\tif (signal?.aborted) throw signal.reason ?? new Error(\"Transfer cancelled\");\n}\n\nfunction toSafeNumber(value: bigint, label: string): number {\n\tif (value > BigInt(Number.MAX_SAFE_INTEGER))\n\t\tthrow new Error(`${label} exceeds safe integer range`);\n\treturn Number(value);\n}\n\nexport async function scanPortableWorkspace(input: {\n\tworkspaceRoot: string;\n\tsessionFile: string;\n\tlimits?: SessionTransferLimits;\n\tsignal?: AbortSignal;\n}): Promise<TransferPreflight> {\n\tconst limits = input.limits ?? DEFAULT_SESSION_TRANSFER_LIMITS;\n\tconst root = path.resolve(input.workspaceRoot);\n\tif (!(await lstat(root, { bigint: true })).isDirectory()) {\n\t\tthrow new Error(\"Process workspace is not a directory\");\n\t}\n\tconst entries: PortableEntry[] = [];\n\tlet logicalBytesTotal = 0;\n\tconst add = (entry: PortableEntry): void => {\n\t\tentries.push(entry);\n\t\tif (entries.length + 3 > limits.maxEntries) throw new Error(\"Transfer entry limit exceeded\");\n\t\tif (entry.kind === \"file\") {\n\t\t\tlogicalBytesTotal += entry.size;\n\t\t\tif (!Number.isSafeInteger(logicalBytesTotal) || logicalBytesTotal > limits.maxLogicalBytes) {\n\t\t\t\tthrow new Error(\"Transfer logical byte limit exceeded\");\n\t\t\t}\n\t\t}\n\t};\n\tconst walk = async (directory: string, relativeDirectory: string): Promise<void> => {\n\t\tabortIfNeeded(input.signal);\n\t\tconst names = await readdir(directory);\n\t\tnames.sort((left, right) => Buffer.from(left).compare(Buffer.from(right)));\n\t\tfor (const name of names) {\n\t\t\tabortIfNeeded(input.signal);\n\t\t\t// Archive paths are normalized with POSIX separators during extraction.\n\t\t\t// A backslash is a valid POSIX filename character, so reject it here\n\t\t\t// rather than silently changing the exported filename on import.\n\t\t\tif (name.includes(\"\\\\\")) {\n\t\t\t\tthrow new Error(`Workspace entry contains an unsupported path separator: ${name}`);\n\t\t\t}\n\t\t\tconst absolute = path.join(directory, name);\n\t\t\tif (!isPathInside(root, absolute))\n\t\t\t\tthrow new Error(\"Workspace scan escaped its configured root\");\n\t\t\tconst relativePath = path.posix.join(relativeDirectory, name);\n\t\t\tconst stats = await lstat(absolute, { bigint: true });\n\t\t\tconst common = {\n\t\t\t\trelativePath,\n\t\t\t\tmode: Number(stats.mode & 0o7777n),\n\t\t\t\tmtimeMs: Number(stats.mtimeMs),\n\t\t\t};\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\tadd({ ...common, kind: \"directory\", size: 0 });\n\t\t\t\tawait walk(absolute, relativePath);\n\t\t\t} else if (stats.isFile()) {\n\t\t\t\tadd({ ...common, kind: \"file\", size: toSafeNumber(stats.size, relativePath) });\n\t\t\t} else if (stats.isSymbolicLink()) {\n\t\t\t\tconst linkTarget = await readlink(absolute);\n\t\t\t\tif (path.isAbsolute(linkTarget) || path.win32.isAbsolute(linkTarget)) {\n\t\t\t\t\tthrow new Error(`Absolute symlink is not portable: ${relativePath}`);\n\t\t\t\t}\n\t\t\t\tadd({ ...common, kind: \"symlink\", size: 0, linkTarget });\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Unsupported workspace entry type: ${relativePath}`);\n\t\t\t}\n\t\t}\n\t};\n\tawait walk(root, \"\");\n\tassertConfinedSymlinks(\n\t\tnew Map(\n\t\t\tentries.flatMap((entry) =>\n\t\t\t\tentry.kind === \"symlink\" ? [[entry.relativePath, entry.linkTarget ?? \"\"] as const] : [],\n\t\t\t),\n\t\t),\n\t);\n\tconst sessionStats = await lstat(path.resolve(input.sessionFile), { bigint: true });\n\tif (!sessionStats.isFile()) throw new Error(\"Primary Pi session is not a regular file\");\n\tlogicalBytesTotal += toSafeNumber(sessionStats.size, \"Pi session\");\n\tif (!Number.isSafeInteger(logicalBytesTotal) || logicalBytesTotal > limits.maxLogicalBytes) {\n\t\tthrow new Error(\"Transfer logical byte limit exceeded\");\n\t}\n\treturn { entries, entriesTotal: entries.length + 3, logicalBytesTotal };\n}\n\nfunction addBufferEntry(\n\tpack: tar.Pack,\n\theader: TarHeader,\n\tcontent: Buffer | string = Buffer.alloc(0),\n): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tpack.entry(header, content, (error) => (error ? reject(error) : resolve()));\n\t});\n}\n\nasync function addFileEntry(\n\tpack: tar.Pack,\n\theader: TarHeader,\n\tfilePath: string,\n\tsignal: AbortSignal | undefined,\n): Promise<void> {\n\tabortIfNeeded(signal);\n\tconst entry = pack.entry(header);\n\tawait pipeline(createReadStream(filePath), entry, { signal });\n}\n\nexport async function prepareTransferArchive(input: {\n\tworkspaceRoot: string;\n\tsessionFile: string;\n\tmanifest: LeitwerkTransferManifestV1;\n\tlimits: SessionTransferLimits;\n\tsignal?: AbortSignal;\n}): Promise<PreparedTransferArchive> {\n\tconst preflight = await scanPortableWorkspace(input);\n\tconst manifest: LeitwerkTransferManifestV1 = {\n\t\t...input.manifest,\n\t\tprojects: await readProjectEvidence(input.workspaceRoot, input.manifest.projects, input.signal),\n\t};\n\treturn {\n\t\tmanifest,\n\t\tpreflight,\n\t\tstream: ({ signal }) => createTransferArchive({ ...input, manifest, preflight, signal }),\n\t};\n}\n\nexport function createTransferArchive(input: {\n\tworkspaceRoot: string;\n\tsessionFile: string;\n\tmanifest: LeitwerkTransferManifestV1;\n\tpreflight: TransferPreflight;\n\tsignal?: AbortSignal;\n}): Readable {\n\tconst pack = tar.pack();\n\tconst zstd = createZstdCompress({\n\t\tparams: {\n\t\t\t[zlibConstants.ZSTD_c_compressionLevel]: 1,\n\t\t\t[zlibConstants.ZSTD_c_checksumFlag]: 1,\n\t\t},\n\t});\n\tconst createdAt = new Date(input.manifest.createdAt);\n\tconst finish = async (): Promise<void> => {\n\t\tabortIfNeeded(input.signal);\n\t\tconst manifest = `${JSON.stringify(input.manifest)}\\n`;\n\t\tawait addBufferEntry(pack, { name: \"manifest.json\", mode: 0o600, mtime: createdAt }, manifest);\n\t\tawait addBufferEntry(pack, {\n\t\t\tname: \"workspace/\",\n\t\t\ttype: \"directory\",\n\t\t\tmode: 0o755,\n\t\t\tmtime: createdAt,\n\t\t});\n\t\tfor (const entry of input.preflight.entries) {\n\t\t\tabortIfNeeded(input.signal);\n\t\t\tconst name = `workspace/${entry.relativePath}${entry.kind === \"directory\" ? \"/\" : \"\"}`;\n\t\t\tconst header: TarHeader = {\n\t\t\t\tname,\n\t\t\t\ttype: entry.kind === \"file\" ? \"file\" : entry.kind,\n\t\t\t\tmode: entry.mode,\n\t\t\t\tmtime: new Date(entry.mtimeMs),\n\t\t\t\t...(entry.kind === \"file\" ? { size: entry.size } : {}),\n\t\t\t\t...(entry.linkTarget ? { linkname: entry.linkTarget } : {}),\n\t\t\t};\n\t\t\tif (entry.kind === \"file\") {\n\t\t\t\tawait addFileEntry(\n\t\t\t\t\tpack,\n\t\t\t\t\theader,\n\t\t\t\t\tpath.join(input.workspaceRoot, ...entry.relativePath.split(\"/\")),\n\t\t\t\t\tinput.signal,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tawait addBufferEntry(pack, header);\n\t\t\t}\n\t\t}\n\t\tconst workspaceBytes = input.preflight.entries.reduce(\n\t\t\t(sum, entry) => sum + (entry.kind === \"file\" ? entry.size : 0),\n\t\t\t0,\n\t\t);\n\t\tawait addFileEntry(\n\t\t\tpack,\n\t\t\t{\n\t\t\t\tname: \"session.jsonl\",\n\t\t\t\tmode: 0o600,\n\t\t\t\tmtime: createdAt,\n\t\t\t\tsize: input.preflight.logicalBytesTotal - workspaceBytes,\n\t\t\t},\n\t\t\tinput.sessionFile,\n\t\t\tinput.signal,\n\t\t);\n\t\tpack.finalize();\n\t};\n\t// Pipeline propagates failures and consumer cancellation in both directions.\n\t// Its rejection is also exposed as an error on the returned compressed stream.\n\tvoid pipeline(pack, zstd, { signal: input.signal }).catch(() => undefined);\n\tvoid finish().catch((error) => pack.destroy(error as Error));\n\treturn zstd;\n}\n\nasync function assertNoSymlinkParents(root: string, target: string): Promise<void> {\n\tlet current = root;\n\tfor (const segment of path.relative(root, path.dirname(target)).split(path.sep).filter(Boolean)) {\n\t\tcurrent = path.join(current, segment);\n\t\ttry {\n\t\t\tif ((await lstat(current)).isSymbolicLink()) {\n\t\t\t\tthrow new Error(`Archive path traverses symlink '${segment}'`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t}\n\t}\n}\n\nasync function drainEntry(stream: AsyncIterable<unknown>): Promise<void> {\n\tfor await (const _chunk of stream) {\n\t\t// tar-stream requires each entry to be drained before advancing.\n\t}\n}\n\nasync function streamBuffer(\n\tstream: AsyncIterable<Uint8Array>,\n\tlimit: number,\n\tlabel: string,\n): Promise<Buffer> {\n\tconst chunks: Buffer[] = [];\n\tlet size = 0;\n\tfor await (const chunk of stream) {\n\t\tconst buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n\t\tsize += buffer.length;\n\t\tif (size > limit) throw new Error(`${label} is too large`);\n\t\tchunks.push(buffer);\n\t}\n\treturn Buffer.concat(chunks);\n}\n\nexport async function extractTransferArchive(input: {\n\tcompressed: Readable;\n\toutputRoot: string;\n\tlimits?: SessionTransferLimits;\n\tsignal?: AbortSignal;\n\tonProgress?: (progress: TransferArchiveProgress & { compressedBytes: number }) => void;\n\townershipMarker?: { name: string; value: string };\n}): Promise<ExtractTransferResult> {\n\tconst limits = input.limits ?? DEFAULT_SESSION_TRANSFER_LIMITS;\n\tconst outputRoot = path.resolve(input.outputRoot);\n\tawait mkdir(outputRoot, { recursive: false, mode: 0o700 });\n\tif (input.ownershipMarker) {\n\t\tconst markerName = assertSafeRelativePath(input.ownershipMarker.name, \"ownership marker\");\n\t\tif (markerName.includes(\"/\")) throw new Error(\"Ownership marker must be a root file\");\n\t\tawait writeFile(path.join(outputRoot, markerName), `${input.ownershipMarker.value}\\n`, {\n\t\t\tflag: \"wx\",\n\t\t\tmode: 0o600,\n\t\t});\n\t}\n\n\tconst hash = createHash(\"sha256\");\n\tlet compressedBytes = 0;\n\tlet entriesProcessed = 0;\n\tlet logicalBytesProcessed = 0;\n\tlet manifest: LeitwerkTransferManifestV1 | null = null;\n\tconst seen = new Set<string>();\n\tconst symlinks = new Map<string, string>();\n\tconst directoryMetadata: Array<{ target: string; mode: number; mtime: Date }> = [];\n\tconst report = (): void =>\n\t\tinput.onProgress?.({ entriesProcessed, logicalBytesProcessed, compressedBytes });\n\tconst metered = new Transform({\n\t\ttransform(chunk: Buffer, _encoding, callback) {\n\t\t\tcompressedBytes += chunk.length;\n\t\t\tif (compressedBytes > limits.maxCompressedBytes) {\n\t\t\t\tcallback(new Error(\"Transfer compressed byte limit exceeded\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thash.update(chunk);\n\t\t\treport();\n\t\t\tcallback(null, chunk);\n\t\t},\n\t});\n\tconst extract = tar.extract();\n\textract.on(\"entry\", (header, entryStream, next) => {\n\t\tvoid (async () => {\n\t\t\tabortIfNeeded(input.signal);\n\t\t\tconst name = assertSafeRelativePath(header.name.replace(/\\/$/, \"\"), \"archive path\");\n\t\t\tif (seen.has(name)) throw new Error(`Duplicate archive path '${name}'`);\n\t\t\tseen.add(name);\n\t\t\tentriesProcessed += 1;\n\t\t\tif (entriesProcessed > limits.maxEntries) throw new Error(\"Transfer entry limit exceeded\");\n\t\t\tif (entriesProcessed === 1 && name !== \"manifest.json\") {\n\t\t\t\tthrow new Error(\"manifest.json must be the first archive entry\");\n\t\t\t}\n\t\t\tif (\n\t\t\t\tname !== \"manifest.json\" &&\n\t\t\t\tname !== \"session.jsonl\" &&\n\t\t\t\tname !== \"workspace\" &&\n\t\t\t\t!name.startsWith(\"workspace/\")\n\t\t\t) {\n\t\t\t\tthrow new Error(`Unexpected archive path '${name}'`);\n\t\t\t}\n\t\t\tconst target = path.resolve(outputRoot, ...name.split(\"/\"));\n\t\t\tif (!isPathInside(outputRoot, target))\n\t\t\t\tthrow new Error(`Archive path escapes output: ${name}`);\n\t\t\tawait assertNoSymlinkParents(outputRoot, target);\n\t\t\tconst mode = (header.mode ?? (header.type === \"directory\" ? 0o755 : 0o600)) & 0o7777;\n\t\t\tconst mtime = header.mtime ?? new Date(0);\n\t\t\tif (header.type === \"directory\") {\n\t\t\t\tif (header.size !== 0) throw new Error(`Directory '${name}' has content`);\n\t\t\t\tawait drainEntry(entryStream);\n\t\t\t\tawait mkdir(target, { recursive: false, mode: mode | 0o700 });\n\t\t\t\tdirectoryMetadata.push({ target, mode, mtime });\n\t\t\t} else if (header.type === \"symlink\") {\n\t\t\t\tif (header.size !== 0) throw new Error(`Symlink '${name}' has content`);\n\t\t\t\tawait drainEntry(entryStream);\n\t\t\t\tif (!name.startsWith(\"workspace/\")) {\n\t\t\t\t\tthrow new Error(`Archive symlink is outside the workspace: ${name}`);\n\t\t\t\t}\n\t\t\t\tconst link = header.linkname ?? \"\";\n\t\t\t\tif (path.isAbsolute(link) || path.win32.isAbsolute(link)) {\n\t\t\t\t\tthrow new Error(`Absolute archive symlink '${name}'`);\n\t\t\t\t}\n\t\t\t\tawait mkdir(path.dirname(target), { recursive: true, mode: 0o700 });\n\t\t\t\tawait symlink(link, target);\n\t\t\t\tsymlinks.set(name.slice(\"workspace/\".length), link);\n\t\t\t} else if (header.type === \"file\" || !header.type) {\n\t\t\t\tconst size = header.size ?? 0;\n\t\t\t\tif (!Number.isSafeInteger(size) || size < 0) {\n\t\t\t\t\tthrow new Error(`Invalid size for archive entry '${name}'`);\n\t\t\t\t}\n\t\t\t\tawait mkdir(path.dirname(target), { recursive: true, mode: 0o700 });\n\t\t\t\tif (name === \"manifest.json\") {\n\t\t\t\t\tconst content = await streamBuffer(\n\t\t\t\t\t\tentryStream as AsyncIterable<Uint8Array>,\n\t\t\t\t\t\tMANIFEST_MAX_BYTES,\n\t\t\t\t\t\t\"Transfer manifest\",\n\t\t\t\t\t);\n\t\t\t\t\tawait writeFile(target, content, { flag: \"wx\", mode: 0o600 });\n\t\t\t\t\tmanifest = parseTransferManifest(JSON.parse(content.toString(\"utf8\")));\n\t\t\t\t} else {\n\t\t\t\t\tconst handle = await open(target, \"wx\", mode);\n\t\t\t\t\tlet actualSize = 0;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor await (const chunk of entryStream as AsyncIterable<Uint8Array>) {\n\t\t\t\t\t\t\tconst buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n\t\t\t\t\t\t\tactualSize += buffer.length;\n\t\t\t\t\t\t\tlogicalBytesProcessed += buffer.length;\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!Number.isSafeInteger(actualSize) ||\n\t\t\t\t\t\t\t\tlogicalBytesProcessed > limits.maxLogicalBytes\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthrow new Error(\"Transfer logical byte limit exceeded\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait handle.write(buffer);\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait handle.close();\n\t\t\t\t\t}\n\t\t\t\t\tif (actualSize !== size) {\n\t\t\t\t\t\tthrow new Error(`Archive entry '${name}' size does not match its content`);\n\t\t\t\t\t}\n\t\t\t\t\tawait chmod(target, mode);\n\t\t\t\t\tawait utimes(target, mtime, mtime);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tawait drainEntry(entryStream);\n\t\t\t\tthrow new Error(`Unsupported tar entry type '${header.type}' for '${name}'`);\n\t\t\t}\n\t\t\treport();\n\t\t\tnext();\n\t\t})().catch((error) => next(error as Error));\n\t});\n\tconst abort = (): void => extract.destroy(input.signal?.reason);\n\tinput.signal?.addEventListener(\"abort\", abort, { once: true });\n\ttry {\n\t\tawait pipeline(input.compressed, metered, createZstdDecompress(), extract);\n\t} finally {\n\t\tinput.signal?.removeEventListener(\"abort\", abort);\n\t}\n\tassertConfinedSymlinks(symlinks);\n\tfor (const directory of directoryMetadata.reverse()) {\n\t\tawait chmod(directory.target, directory.mode);\n\t\tawait utimes(directory.target, directory.mtime, directory.mtime);\n\t}\n\tif (!manifest) throw new Error(\"Transfer manifest is missing\");\n\tif (!seen.has(\"workspace\") || !seen.has(\"session.jsonl\")) {\n\t\tthrow new Error(\"Transfer archive is incomplete\");\n\t}\n\treturn {\n\t\tmanifest,\n\t\tcompressedBytes,\n\t\tstreamSha256: hash.digest(\"hex\"),\n\t};\n}\n","import path from \"node:path\";\nimport * as v from \"valibot\";\n\nexport const SESSION_TRANSFER_CONTENT_TYPE = \"application/vnd.leitwerk.session-transfer+tar+zstd\";\n\nexport const SESSION_TRANSFER_ATTEMPT_STATES = [\n\t\"queued\",\n\t\"exporting\",\n\t\"awaiting_ack\",\n\t\"cancelled\",\n\t\"failed\",\n\t\"consumed\",\n] as const;\nexport type SessionTransferAttemptState = (typeof SESSION_TRANSFER_ATTEMPT_STATES)[number];\n\nexport const SESSION_TRANSFER_PHASES = [\n\t\"queued\",\n\t\"waiting_for_execution_chain\",\n\t\"stopping_worker\",\n\t\"starting_exporter\",\n\t\"scanning\",\n\t\"ready_to_stream\",\n\t\"streaming\",\n\t\"awaiting_ack\",\n\t\"consumed\",\n\t\"cancelled\",\n\t\"failed\",\n] as const;\nexport type SessionTransferPhase = (typeof SESSION_TRANSFER_PHASES)[number];\n\n/** Derives the public coarse status from the persisted lifecycle phase. */\nexport function sessionTransferAttemptStateForPhase(\n\tphase: SessionTransferPhase,\n): SessionTransferAttemptState {\n\tswitch (phase) {\n\t\tcase \"queued\":\n\t\tcase \"waiting_for_execution_chain\":\n\t\t\treturn \"queued\";\n\t\tcase \"stopping_worker\":\n\t\tcase \"starting_exporter\":\n\t\tcase \"scanning\":\n\t\tcase \"ready_to_stream\":\n\t\tcase \"streaming\":\n\t\t\treturn \"exporting\";\n\t\tcase \"awaiting_ack\":\n\t\tcase \"consumed\":\n\t\tcase \"cancelled\":\n\t\tcase \"failed\":\n\t\t\treturn phase;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown session transfer phase: ${phase}`);\n\t}\n}\n\nexport interface SessionTransferAttemptWire {\n\tid: string;\n\tgrantId: string;\n\tinstanceId: string;\n\t/** Derived from phase; it is not persisted in the server database. */\n\tstate: SessionTransferAttemptState;\n\tphase: SessionTransferPhase;\n\tleaseUntil: string;\n\thardDeadline: string;\n\tentriesTotal: number | null;\n\tlogicalBytesTotal: number | null;\n\tcompressedBytes: number | null;\n\tstreamSha256: string | null;\n\tfailureCode: string | null;\n}\n\nconst nonBlankStringSchema = v.pipe(\n\tv.string(),\n\tv.check((value) => value.trim().length > 0, \"Expected a non-empty string\"),\n);\nconst safeIntegerSchema = v.pipe(v.number(), v.safeInteger());\nconst positiveSafeIntegerSchema = v.pipe(safeIntegerSchema, v.minValue(1));\nconst nonNegativeSafeIntegerSchema = v.pipe(safeIntegerSchema, v.minValue(0));\nconst normalizedRelativePathSchema = v.pipe(\n\tnonBlankStringSchema,\n\tv.check((value) => {\n\t\ttry {\n\t\t\treturn assertSafeRelativePath(value) === value;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}, \"Expected a normalized relative path\"),\n);\n\nexport const sessionTransferLimitsSchema = v.object({\n\tmaxEntries: positiveSafeIntegerSchema,\n\tmaxLogicalBytes: positiveSafeIntegerSchema,\n\tmaxCompressedBytes: positiveSafeIntegerSchema,\n});\nexport type SessionTransferLimits = v.InferOutput<typeof sessionTransferLimitsSchema>;\n\nexport const DEFAULT_SESSION_TRANSFER_LIMITS: SessionTransferLimits = {\n\tmaxEntries: 250_000,\n\tmaxLogicalBytes: 20 * 1024 * 1024 * 1024,\n\tmaxCompressedBytes: 10 * 1024 * 1024 * 1024,\n};\n\nexport const leitwerkTransferManifestV1Schema = v.object({\n\tversion: v.literal(1, \"Unsupported transfer manifest version\"),\n\tinstanceId: nonBlankStringSchema,\n\tcreatedAt: v.pipe(\n\t\tnonBlankStringSchema,\n\t\tv.check((value) => Number.isFinite(Date.parse(value)), \"Expected an ISO datetime\"),\n\t),\n\tsession: v.object({\n\t\tsourceCwd: nonBlankStringSchema,\n\t\tcwdRelativeToWorkspace: v.nullable(v.union([v.literal(\".\"), normalizedRelativePathSchema])),\n\t}),\n\tprojects: v.array(\n\t\tv.object({\n\t\t\tkey: nonBlankStringSchema,\n\t\t\trelativePath: normalizedRelativePathSchema,\n\t\t\tbranch: v.nullable(v.string()),\n\t\t\thead: v.nullable(v.string()),\n\t\t}),\n\t),\n});\nexport type LeitwerkTransferManifestV1 = v.InferOutput<typeof leitwerkTransferManifestV1Schema>;\n\nexport const sessionTransferPreflightSchema = v.object({\n\tentriesTotal: v.pipe(nonNegativeSafeIntegerSchema, v.minValue(3)),\n\tlogicalBytesTotal: nonNegativeSafeIntegerSchema,\n});\nexport type SessionTransferPreflight = v.InferOutput<typeof sessionTransferPreflightSchema>;\n\nexport const sessionTransferPreflightReportSchema = v.object({\n\tmanifest: leitwerkTransferManifestV1Schema,\n\tpreflight: sessionTransferPreflightSchema,\n});\nexport type SessionTransferPreflightReport = v.InferOutput<\n\ttypeof sessionTransferPreflightReportSchema\n>;\n\nexport interface TransferArchiveProgress {\n\tentriesProcessed: number;\n\tlogicalBytesProcessed: number;\n}\n\nexport const sessionTransferHelperSpecSchema = v.object({\n\tmanifest: leitwerkTransferManifestV1Schema,\n\tlimits: sessionTransferLimitsSchema,\n});\nexport type SessionTransferHelperSpec = v.InferOutput<typeof sessionTransferHelperSpecSchema>;\n\nexport interface ParsedTransferLink {\n\torigin: string;\n\tinstanceId: string;\n\tgrantId: string;\n\ttoken: string;\n\tgrantUrl: string;\n}\n\nfunction object(value: unknown, label: string): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\tthrow new Error(`${label} must be an object`);\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nfunction string(value: unknown, label: string): string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new Error(`${label} must be a non-empty string`);\n\t}\n\treturn value;\n}\n\nexport function parsePiSessionHeader(content: string): Record<string, unknown> {\n\tconst firstLine = content.split(/\\r?\\n/, 1)[0];\n\tif (!firstLine) throw new Error(\"Pi session is empty\");\n\tconst value = JSON.parse(firstLine) as unknown;\n\tif (\n\t\t!value ||\n\t\ttypeof value !== \"object\" ||\n\t\tArray.isArray(value) ||\n\t\t(value as Record<string, unknown>).type !== \"session\"\n\t) {\n\t\tthrow new Error(\"Pi session header is invalid\");\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nexport function isPathInside(root: string, candidate: string): boolean {\n\tconst relative = path.relative(path.resolve(root), path.resolve(candidate));\n\treturn (\n\t\trelative === \"\" ||\n\t\t(!relative.startsWith(`..${path.sep}`) && relative !== \"..\" && !path.isAbsolute(relative))\n\t);\n}\n\nexport function assertSafeRelativePath(value: string, label = \"path\"): string {\n\tif (value.includes(\"\\0\") || path.posix.isAbsolute(value) || path.win32.isAbsolute(value)) {\n\t\tthrow new Error(`${label} must be relative`);\n\t}\n\tconst normalized = path.posix.normalize(value.replaceAll(\"\\\\\", \"/\"));\n\tif (normalized === \"..\" || normalized.startsWith(\"../\") || normalized === \".\") {\n\t\tthrow new Error(`${label} escapes its root`);\n\t}\n\treturn normalized;\n}\n\nexport function parseTransferManifest(value: unknown): LeitwerkTransferManifestV1 {\n\treturn v.parse(leitwerkTransferManifestV1Schema, value);\n}\n\nexport function parseSessionTransferHelperSpec(value: unknown): SessionTransferHelperSpec {\n\treturn v.parse(sessionTransferHelperSpecSchema, value);\n}\n\nconst TRANSFER_ID_PATTERN = /^[A-Za-z0-9_.-]+$/;\n\nfunction decodeTransferId(value: string, label: string): string {\n\tlet decoded: string;\n\ttry {\n\t\tdecoded = decodeURIComponent(value);\n\t} catch (error) {\n\t\tthrow new Error(`Transfer link has an invalid ${label}`, { cause: error });\n\t}\n\t// IDs are used to construct subsequent request paths. Reject encoded path\n\t// separators rather than allowing a single route parameter to become a\n\t// different path when it is re-encoded by the client.\n\tif (!TRANSFER_ID_PATTERN.test(decoded)) {\n\t\tthrow new Error(`Transfer link has an invalid ${label}`);\n\t}\n\treturn decoded;\n}\n\nexport function parseTransferLink(raw: string): ParsedTransferLink {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(raw.trim());\n\t} catch {\n\t\tthrow new Error(\"Transfer link is not a valid URL\");\n\t}\n\tconst loopback =\n\t\turl.hostname === \"127.0.0.1\" ||\n\t\turl.hostname === \"localhost\" ||\n\t\turl.hostname === \"::1\" ||\n\t\turl.hostname === \"[::1]\";\n\tif (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && loopback)) {\n\t\tthrow new Error(\"Transfer links require HTTPS (HTTP is allowed only for loopback development)\");\n\t}\n\tif (url.username || url.password || url.search)\n\t\tthrow new Error(\"Transfer link contains unexpected URL credentials or query parameters\");\n\tconst match = /^\\/api\\/session-transfers\\/([^/]+)\\/([^/]+)$/.exec(url.pathname);\n\tif (!match) throw new Error(\"Transfer link has an unexpected path\");\n\tconst instanceId = decodeTransferId(match[1] as string, \"instance id\");\n\tconst grantId = decodeTransferId(match[2] as string, \"grant id\");\n\tconst token = new URLSearchParams(url.hash.slice(1)).get(\"token\");\n\tif (!token || token.length < 32)\n\t\tthrow new Error(\"Transfer link is missing its bearer token fragment\");\n\treturn {\n\t\torigin: url.origin,\n\t\tinstanceId,\n\t\tgrantId,\n\t\ttoken,\n\t\tgrantUrl: `${url.origin}/api/session-transfers/${encodeURIComponent(instanceId)}/${encodeURIComponent(grantId)}`,\n\t};\n}\n\nexport interface RewrittenPiSession {\n\tcontent: string;\n\theader: Record<string, unknown>;\n\tentryCount: number;\n}\n\nexport function rewritePiSession(\n\tcontent: string,\n\tlocalCwd: string,\n\texpectedSourceCwd?: string,\n): RewrittenPiSession {\n\tconst lines = content.split(/\\r?\\n/).filter((line) => line.trim() !== \"\");\n\tif (lines.length === 0) throw new Error(\"Transferred Pi session is empty\");\n\tconst parsed = lines.map((line, index) => {\n\t\ttry {\n\t\t\treturn object(JSON.parse(line), `session line ${index + 1}`);\n\t\t} catch (error) {\n\t\t\tif (error instanceof SyntaxError)\n\t\t\t\tthrow new Error(`Session line ${index + 1} is not valid JSON`, { cause: error });\n\t\t\tthrow error;\n\t\t}\n\t});\n\tconst sourceHeader = parsePiSessionHeader(content);\n\tif (sourceHeader.version !== 3) {\n\t\tthrow new Error(\"unsupported_pi_session_version\");\n\t}\n\tstring(sourceHeader.id, \"session header.id\");\n\tconst sourceCwd = string(sourceHeader.cwd, \"session header.cwd\");\n\tif (!path.isAbsolute(sourceCwd)) throw new Error(\"Transferred session cwd must be absolute\");\n\tif (expectedSourceCwd !== undefined && sourceCwd !== expectedSourceCwd) {\n\t\tthrow new Error(\"Transferred session cwd does not match the transfer manifest\");\n\t}\n\tconst timestamp = string(sourceHeader.timestamp, \"session header.timestamp\");\n\tif (\n\t\t!/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(timestamp) ||\n\t\t!Number.isFinite(Date.parse(timestamp))\n\t) {\n\t\tthrow new Error(\"Transferred session timestamp must be an ISO datetime\");\n\t}\n\n\tconst ids = new Set<string>();\n\tfor (let index = 1; index < parsed.length; index += 1) {\n\t\tconst entry = parsed[index] as Record<string, unknown>;\n\t\tif (entry.type === \"session\") throw new Error(\"Transferred session contains a second header\");\n\t\tstring(entry.type, `session line ${index + 1}.type`);\n\t\tconst id = string(entry.id, `session line ${index + 1}.id`);\n\t\tif (ids.has(id)) throw new Error(`Transferred session contains duplicate entry id '${id}'`);\n\t\tconst parentId = entry.parentId;\n\t\tif (parentId !== null && (typeof parentId !== \"string\" || !ids.has(parentId))) {\n\t\t\tthrow new Error(`Transferred session entry '${id}' has an invalid parent`);\n\t\t}\n\t\tids.add(id);\n\t}\n\tconst { parentSession: _parentSession, ...rest } = sourceHeader;\n\tconst header = { ...rest, cwd: path.resolve(localCwd) };\n\treturn {\n\t\tcontent: `${[header, ...parsed.slice(1)].map((entry) => JSON.stringify(entry)).join(\"\\n\")}\\n`,\n\t\theader,\n\t\tentryCount: parsed.length - 1,\n\t};\n}\n","import { execFile } from \"node:child_process\";\nimport { lstat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport type { LeitwerkTransferManifestV1 } from \"./format.js\";\nimport { isPathInside } from \"./format.js\";\n\nconst execFileAsync = promisify(execFile);\n\ntype TransferProject = LeitwerkTransferManifestV1[\"projects\"][number];\n\nexport async function readProjectEvidence(\n\tworkspaceRoot: string,\n\tprojects: readonly TransferProject[],\n\tsignal?: AbortSignal,\n): Promise<TransferProject[]> {\n\treturn Promise.all(\n\t\tprojects.map(async (project) => {\n\t\t\tconst projectRoot = path.resolve(workspaceRoot, ...project.relativePath.split(\"/\"));\n\t\t\tif (!isPathInside(workspaceRoot, projectRoot)) {\n\t\t\t\tthrow new Error(`Project '${project.key}' escapes the workspace`);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait lstat(path.join(projectRoot, \".git\"));\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Project '${project.key}' is not a Git worktree`);\n\t\t\t}\n\t\t\tconst [head = \"\", branch = \"\"] = (\n\t\t\t\tawait execFileAsync(\n\t\t\t\t\t\"git\",\n\t\t\t\t\t[\"-C\", projectRoot, \"rev-parse\", \"HEAD\", \"--abbrev-ref\", \"HEAD\"],\n\t\t\t\t\t{\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t).stdout\n\t\t\t\t.trim()\n\t\t\t\t.split(\"\\n\");\n\t\t\treturn {\n\t\t\t\t...project,\n\t\t\t\thead: head || null,\n\t\t\t\tbranch: branch && branch !== \"HEAD\" ? branch : null,\n\t\t\t};\n\t\t}),\n\t);\n}\n","import path from \"node:path\";\n\n/** Resolve each component before interpreting '..', including targets that do not exist yet. */\nexport function assertConfinedSymlinks(links: ReadonlyMap<string, string>): void {\n\tconst resolvedLinks = new Map<string, string[]>();\n\tconst resolving = new Set<string>();\n\tconst resolve = (segments: readonly string[], initial: readonly string[] = []): string[] => {\n\t\tlet resolved = [...initial];\n\t\tfor (const segment of segments) {\n\t\t\tif (segment === \"\" || segment === \".\") continue;\n\t\t\tif (segment === \"..\") {\n\t\t\t\tif (resolved.length === 0) throw new Error(\"Symlink escapes the workspace\");\n\t\t\t\tresolved.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst candidate = [...resolved, segment].join(\"/\");\n\t\t\tconst target = links.get(candidate);\n\t\t\tif (target === undefined) {\n\t\t\t\tresolved.push(segment);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (path.posix.isAbsolute(target) || path.win32.isAbsolute(target)) {\n\t\t\t\tthrow new Error(`Absolute symlink is not portable: ${candidate}`);\n\t\t\t}\n\t\t\tif (resolving.has(candidate)) throw new Error(`Symlink cycle in workspace: ${candidate}`);\n\t\t\tlet destination = resolvedLinks.get(candidate);\n\t\t\tif (!destination) {\n\t\t\t\tresolving.add(candidate);\n\t\t\t\tdestination = resolve(target.split(\"/\"), resolved);\n\t\t\t\tresolving.delete(candidate);\n\t\t\t\tresolvedLinks.set(candidate, destination);\n\t\t\t}\n\t\t\tresolved = [...destination];\n\t\t}\n\t\treturn resolved;\n\t};\n\tfor (const name of links.keys()) resolve(name.split(\"/\"));\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B,SAAS,wBAAwB;AACjC;AAAA,EACC;AAAA,EACA,SAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,OAAOC,WAAU;AACjB,SAAwB,iBAAiB;AACzC,SAAS,gBAAgB;AACzB,SAAS,oBAAoB,sBAAsB,aAAa,qBAAqB;AACrF,OAAO,SAAS;;;ACjBhB,OAAO,UAAU;AACjB,YAAY,OAAO;AAEZ,IAAM,gCAAgC;AAEtC,IAAM,kCAAkC;AAAA,EAC9C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AAGO,IAAM,0BAA0B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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MAAM,QAAQ,MAAM;AAC9D,QAAM,QAAQ,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;AAC7D,MAAI;AACH,UAAM,SAAS,MAAM,YAAY,SAAS,qBAAqB,GAAG,OAAO;AAAA,EAC1E,UAAE;AACD,UAAM,QAAQ,oBAAoB,SAAS,KAAK;AAAA,EACjD;AACA,yBAAuB,QAAQ;AAC/B,aAAW,aAAa,kBAAkB,QAAQ,GAAG;AACpD,UAAM,MAAM,UAAU,QAAQ,UAAU,IAAI;AAC5C,UAAM,OAAO,UAAU,QAAQ,UAAU,OAAO,UAAU,KAAK;AAAA,EAChE;AACA,MAAI,CAAC,SAAU,OAAM,IAAI,MAAM,8BAA8B;AAC7D,MAAI,CAAC,KAAK,IAAI,WAAW,KAAK,CAAC,KAAK,IAAI,eAAe,GAAG;AACzD,UAAM,IAAI,MAAM,gCAAgC;AAAA,EACjD;AACA,SAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA,cAAc,KAAK,OAAO,KAAK;AAAA,EAChC;AACD;","names":["lstat","path","object","string","path","path","path","path","lstat"]}
@@ -0,0 +1,5 @@
1
+ import type { LeitwerkTransferManifestV1 } from "./format.js";
2
+ type TransferProject = LeitwerkTransferManifestV1["projects"][number];
3
+ export declare function readProjectEvidence(workspaceRoot: string, projects: readonly TransferProject[], signal?: AbortSignal): Promise<TransferProject[]>;
4
+ export {};
5
+ //# sourceMappingURL=project-evidence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-evidence.d.ts","sourceRoot":"","sources":["../src/project-evidence.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC;AAK9D,KAAK,eAAe,GAAG,0BAA0B,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC;AAEtE,wBAAsB,mBAAmB,CACxC,aAAa,EAAE,MAAM,EACrB,QAAQ,EAAE,SAAS,eAAe,EAAE,EACpC,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,eAAe,EAAE,CAAC,CA8B5B"}
@@ -0,0 +1,3 @@
1
+ /** Resolve each component before interpreting '..', including targets that do not exist yet. */
2
+ export declare function assertConfinedSymlinks(links: ReadonlyMap<string, string>): void;
3
+ //# sourceMappingURL=symlink-confinement.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"symlink-confinement.d.ts","sourceRoot":"","sources":["../src/symlink-confinement.ts"],"names":[],"mappings":"AAEA,gGAAgG;AAChG,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAkC/E"}
package/package.json CHANGED
@@ -1,16 +1,42 @@
1
1
  {
2
- "name": "@leitwerk-dev/session-transfer",
3
- "version": "0.0.0-bootstrap.0",
4
- "description": "Registration placeholder only. Not a usable Leitwerk release.",
5
- "license": "Apache-2.0",
6
- "repository": {
7
- "type": "git",
8
- "url": "git+https://github.com/leitwerk-dev/leitwerk.git"
9
- },
10
- "publishConfig": {
11
- "access": "public",
12
- "registry": "https://registry.npmjs.org/",
13
- "tag": "bootstrap",
14
- "provenance": false
15
- }
2
+ "name": "@leitwerk-dev/session-transfer",
3
+ "version": "0.2.0",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/leitwerk-dev/leitwerk.git",
7
+ "directory": "packages/session-transfer"
8
+ },
9
+ "type": "module",
10
+ "exports": {
11
+ ".": {
12
+ "source": "./src/index.ts",
13
+ "import": "./dist/index.js",
14
+ "types": "./dist/index.d.ts"
15
+ }
16
+ },
17
+ "scripts": {
18
+ "build": "tsup --silent"
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^22.15.30",
22
+ "@types/tar-stream": "^3.1.4",
23
+ "tsup": "^8.5.1"
24
+ },
25
+ "license": "Apache-2.0",
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "engines": {
30
+ "node": ">=26 <27"
31
+ },
32
+ "files": [
33
+ "dist/**",
34
+ "src/**",
35
+ "!dist/**/*.test.*",
36
+ "!src/**/*.test.ts"
37
+ ],
38
+ "dependencies": {
39
+ "tar-stream": "^3.2.1",
40
+ "valibot": "^1.3.1"
41
+ }
16
42
  }
package/src/archive.ts ADDED
@@ -0,0 +1,449 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import {
4
+ chmod,
5
+ lstat,
6
+ mkdir,
7
+ open,
8
+ readdir,
9
+ readlink,
10
+ symlink,
11
+ utimes,
12
+ writeFile,
13
+ } from "node:fs/promises";
14
+ import path from "node:path";
15
+ import { type Readable, Transform } from "node:stream";
16
+ import { pipeline } from "node:stream/promises";
17
+ import { createZstdCompress, createZstdDecompress, constants as zlibConstants } from "node:zlib";
18
+ import tar from "tar-stream";
19
+ import {
20
+ assertSafeRelativePath,
21
+ DEFAULT_SESSION_TRANSFER_LIMITS,
22
+ isPathInside,
23
+ type LeitwerkTransferManifestV1,
24
+ parseTransferManifest,
25
+ type SessionTransferLimits,
26
+ type SessionTransferPreflight,
27
+ type TransferArchiveProgress,
28
+ } from "./format.js";
29
+ import { readProjectEvidence } from "./project-evidence.js";
30
+ import { assertConfinedSymlinks } from "./symlink-confinement.js";
31
+
32
+ const MANIFEST_MAX_BYTES = 1024 * 1024;
33
+ type TarHeader = Partial<tar.Header> & Pick<tar.Header, "name">;
34
+
35
+ export interface PortableEntry {
36
+ relativePath: string;
37
+ kind: "file" | "directory" | "symlink";
38
+ mode: number;
39
+ mtimeMs: number;
40
+ size: number;
41
+ linkTarget?: string;
42
+ }
43
+
44
+ export interface TransferPreflight extends SessionTransferPreflight {
45
+ entries: PortableEntry[];
46
+ }
47
+
48
+ export interface ExtractTransferResult {
49
+ manifest: LeitwerkTransferManifestV1;
50
+ compressedBytes: number;
51
+ streamSha256: string;
52
+ }
53
+
54
+ export interface PreparedTransferArchive {
55
+ manifest: LeitwerkTransferManifestV1;
56
+ preflight: TransferPreflight;
57
+ stream(input: { signal?: AbortSignal }): Readable;
58
+ }
59
+
60
+ function abortIfNeeded(signal?: AbortSignal): void {
61
+ if (signal?.aborted) throw signal.reason ?? new Error("Transfer cancelled");
62
+ }
63
+
64
+ function toSafeNumber(value: bigint, label: string): number {
65
+ if (value > BigInt(Number.MAX_SAFE_INTEGER))
66
+ throw new Error(`${label} exceeds safe integer range`);
67
+ return Number(value);
68
+ }
69
+
70
+ export async function scanPortableWorkspace(input: {
71
+ workspaceRoot: string;
72
+ sessionFile: string;
73
+ limits?: SessionTransferLimits;
74
+ signal?: AbortSignal;
75
+ }): Promise<TransferPreflight> {
76
+ const limits = input.limits ?? DEFAULT_SESSION_TRANSFER_LIMITS;
77
+ const root = path.resolve(input.workspaceRoot);
78
+ if (!(await lstat(root, { bigint: true })).isDirectory()) {
79
+ throw new Error("Process workspace is not a directory");
80
+ }
81
+ const entries: PortableEntry[] = [];
82
+ let logicalBytesTotal = 0;
83
+ const add = (entry: PortableEntry): void => {
84
+ entries.push(entry);
85
+ if (entries.length + 3 > limits.maxEntries) throw new Error("Transfer entry limit exceeded");
86
+ if (entry.kind === "file") {
87
+ logicalBytesTotal += entry.size;
88
+ if (!Number.isSafeInteger(logicalBytesTotal) || logicalBytesTotal > limits.maxLogicalBytes) {
89
+ throw new Error("Transfer logical byte limit exceeded");
90
+ }
91
+ }
92
+ };
93
+ const walk = async (directory: string, relativeDirectory: string): Promise<void> => {
94
+ abortIfNeeded(input.signal);
95
+ const names = await readdir(directory);
96
+ names.sort((left, right) => Buffer.from(left).compare(Buffer.from(right)));
97
+ for (const name of names) {
98
+ abortIfNeeded(input.signal);
99
+ // Archive paths are normalized with POSIX separators during extraction.
100
+ // A backslash is a valid POSIX filename character, so reject it here
101
+ // rather than silently changing the exported filename on import.
102
+ if (name.includes("\\")) {
103
+ throw new Error(`Workspace entry contains an unsupported path separator: ${name}`);
104
+ }
105
+ const absolute = path.join(directory, name);
106
+ if (!isPathInside(root, absolute))
107
+ throw new Error("Workspace scan escaped its configured root");
108
+ const relativePath = path.posix.join(relativeDirectory, name);
109
+ const stats = await lstat(absolute, { bigint: true });
110
+ const common = {
111
+ relativePath,
112
+ mode: Number(stats.mode & 0o7777n),
113
+ mtimeMs: Number(stats.mtimeMs),
114
+ };
115
+ if (stats.isDirectory()) {
116
+ add({ ...common, kind: "directory", size: 0 });
117
+ await walk(absolute, relativePath);
118
+ } else if (stats.isFile()) {
119
+ add({ ...common, kind: "file", size: toSafeNumber(stats.size, relativePath) });
120
+ } else if (stats.isSymbolicLink()) {
121
+ const linkTarget = await readlink(absolute);
122
+ if (path.isAbsolute(linkTarget) || path.win32.isAbsolute(linkTarget)) {
123
+ throw new Error(`Absolute symlink is not portable: ${relativePath}`);
124
+ }
125
+ add({ ...common, kind: "symlink", size: 0, linkTarget });
126
+ } else {
127
+ throw new Error(`Unsupported workspace entry type: ${relativePath}`);
128
+ }
129
+ }
130
+ };
131
+ await walk(root, "");
132
+ assertConfinedSymlinks(
133
+ new Map(
134
+ entries.flatMap((entry) =>
135
+ entry.kind === "symlink" ? [[entry.relativePath, entry.linkTarget ?? ""] as const] : [],
136
+ ),
137
+ ),
138
+ );
139
+ const sessionStats = await lstat(path.resolve(input.sessionFile), { bigint: true });
140
+ if (!sessionStats.isFile()) throw new Error("Primary Pi session is not a regular file");
141
+ logicalBytesTotal += toSafeNumber(sessionStats.size, "Pi session");
142
+ if (!Number.isSafeInteger(logicalBytesTotal) || logicalBytesTotal > limits.maxLogicalBytes) {
143
+ throw new Error("Transfer logical byte limit exceeded");
144
+ }
145
+ return { entries, entriesTotal: entries.length + 3, logicalBytesTotal };
146
+ }
147
+
148
+ function addBufferEntry(
149
+ pack: tar.Pack,
150
+ header: TarHeader,
151
+ content: Buffer | string = Buffer.alloc(0),
152
+ ): Promise<void> {
153
+ return new Promise((resolve, reject) => {
154
+ pack.entry(header, content, (error) => (error ? reject(error) : resolve()));
155
+ });
156
+ }
157
+
158
+ async function addFileEntry(
159
+ pack: tar.Pack,
160
+ header: TarHeader,
161
+ filePath: string,
162
+ signal: AbortSignal | undefined,
163
+ ): Promise<void> {
164
+ abortIfNeeded(signal);
165
+ const entry = pack.entry(header);
166
+ await pipeline(createReadStream(filePath), entry, { signal });
167
+ }
168
+
169
+ export async function prepareTransferArchive(input: {
170
+ workspaceRoot: string;
171
+ sessionFile: string;
172
+ manifest: LeitwerkTransferManifestV1;
173
+ limits: SessionTransferLimits;
174
+ signal?: AbortSignal;
175
+ }): Promise<PreparedTransferArchive> {
176
+ const preflight = await scanPortableWorkspace(input);
177
+ const manifest: LeitwerkTransferManifestV1 = {
178
+ ...input.manifest,
179
+ projects: await readProjectEvidence(input.workspaceRoot, input.manifest.projects, input.signal),
180
+ };
181
+ return {
182
+ manifest,
183
+ preflight,
184
+ stream: ({ signal }) => createTransferArchive({ ...input, manifest, preflight, signal }),
185
+ };
186
+ }
187
+
188
+ export function createTransferArchive(input: {
189
+ workspaceRoot: string;
190
+ sessionFile: string;
191
+ manifest: LeitwerkTransferManifestV1;
192
+ preflight: TransferPreflight;
193
+ signal?: AbortSignal;
194
+ }): Readable {
195
+ const pack = tar.pack();
196
+ const zstd = createZstdCompress({
197
+ params: {
198
+ [zlibConstants.ZSTD_c_compressionLevel]: 1,
199
+ [zlibConstants.ZSTD_c_checksumFlag]: 1,
200
+ },
201
+ });
202
+ const createdAt = new Date(input.manifest.createdAt);
203
+ const finish = async (): Promise<void> => {
204
+ abortIfNeeded(input.signal);
205
+ const manifest = `${JSON.stringify(input.manifest)}\n`;
206
+ await addBufferEntry(pack, { name: "manifest.json", mode: 0o600, mtime: createdAt }, manifest);
207
+ await addBufferEntry(pack, {
208
+ name: "workspace/",
209
+ type: "directory",
210
+ mode: 0o755,
211
+ mtime: createdAt,
212
+ });
213
+ for (const entry of input.preflight.entries) {
214
+ abortIfNeeded(input.signal);
215
+ const name = `workspace/${entry.relativePath}${entry.kind === "directory" ? "/" : ""}`;
216
+ const header: TarHeader = {
217
+ name,
218
+ type: entry.kind === "file" ? "file" : entry.kind,
219
+ mode: entry.mode,
220
+ mtime: new Date(entry.mtimeMs),
221
+ ...(entry.kind === "file" ? { size: entry.size } : {}),
222
+ ...(entry.linkTarget ? { linkname: entry.linkTarget } : {}),
223
+ };
224
+ if (entry.kind === "file") {
225
+ await addFileEntry(
226
+ pack,
227
+ header,
228
+ path.join(input.workspaceRoot, ...entry.relativePath.split("/")),
229
+ input.signal,
230
+ );
231
+ } else {
232
+ await addBufferEntry(pack, header);
233
+ }
234
+ }
235
+ const workspaceBytes = input.preflight.entries.reduce(
236
+ (sum, entry) => sum + (entry.kind === "file" ? entry.size : 0),
237
+ 0,
238
+ );
239
+ await addFileEntry(
240
+ pack,
241
+ {
242
+ name: "session.jsonl",
243
+ mode: 0o600,
244
+ mtime: createdAt,
245
+ size: input.preflight.logicalBytesTotal - workspaceBytes,
246
+ },
247
+ input.sessionFile,
248
+ input.signal,
249
+ );
250
+ pack.finalize();
251
+ };
252
+ // Pipeline propagates failures and consumer cancellation in both directions.
253
+ // Its rejection is also exposed as an error on the returned compressed stream.
254
+ void pipeline(pack, zstd, { signal: input.signal }).catch(() => undefined);
255
+ void finish().catch((error) => pack.destroy(error as Error));
256
+ return zstd;
257
+ }
258
+
259
+ async function assertNoSymlinkParents(root: string, target: string): Promise<void> {
260
+ let current = root;
261
+ for (const segment of path.relative(root, path.dirname(target)).split(path.sep).filter(Boolean)) {
262
+ current = path.join(current, segment);
263
+ try {
264
+ if ((await lstat(current)).isSymbolicLink()) {
265
+ throw new Error(`Archive path traverses symlink '${segment}'`);
266
+ }
267
+ } catch (error) {
268
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
269
+ }
270
+ }
271
+ }
272
+
273
+ async function drainEntry(stream: AsyncIterable<unknown>): Promise<void> {
274
+ for await (const _chunk of stream) {
275
+ // tar-stream requires each entry to be drained before advancing.
276
+ }
277
+ }
278
+
279
+ async function streamBuffer(
280
+ stream: AsyncIterable<Uint8Array>,
281
+ limit: number,
282
+ label: string,
283
+ ): Promise<Buffer> {
284
+ const chunks: Buffer[] = [];
285
+ let size = 0;
286
+ for await (const chunk of stream) {
287
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
288
+ size += buffer.length;
289
+ if (size > limit) throw new Error(`${label} is too large`);
290
+ chunks.push(buffer);
291
+ }
292
+ return Buffer.concat(chunks);
293
+ }
294
+
295
+ export async function extractTransferArchive(input: {
296
+ compressed: Readable;
297
+ outputRoot: string;
298
+ limits?: SessionTransferLimits;
299
+ signal?: AbortSignal;
300
+ onProgress?: (progress: TransferArchiveProgress & { compressedBytes: number }) => void;
301
+ ownershipMarker?: { name: string; value: string };
302
+ }): Promise<ExtractTransferResult> {
303
+ const limits = input.limits ?? DEFAULT_SESSION_TRANSFER_LIMITS;
304
+ const outputRoot = path.resolve(input.outputRoot);
305
+ await mkdir(outputRoot, { recursive: false, mode: 0o700 });
306
+ if (input.ownershipMarker) {
307
+ const markerName = assertSafeRelativePath(input.ownershipMarker.name, "ownership marker");
308
+ if (markerName.includes("/")) throw new Error("Ownership marker must be a root file");
309
+ await writeFile(path.join(outputRoot, markerName), `${input.ownershipMarker.value}\n`, {
310
+ flag: "wx",
311
+ mode: 0o600,
312
+ });
313
+ }
314
+
315
+ const hash = createHash("sha256");
316
+ let compressedBytes = 0;
317
+ let entriesProcessed = 0;
318
+ let logicalBytesProcessed = 0;
319
+ let manifest: LeitwerkTransferManifestV1 | null = null;
320
+ const seen = new Set<string>();
321
+ const symlinks = new Map<string, string>();
322
+ const directoryMetadata: Array<{ target: string; mode: number; mtime: Date }> = [];
323
+ const report = (): void =>
324
+ input.onProgress?.({ entriesProcessed, logicalBytesProcessed, compressedBytes });
325
+ const metered = new Transform({
326
+ transform(chunk: Buffer, _encoding, callback) {
327
+ compressedBytes += chunk.length;
328
+ if (compressedBytes > limits.maxCompressedBytes) {
329
+ callback(new Error("Transfer compressed byte limit exceeded"));
330
+ return;
331
+ }
332
+ hash.update(chunk);
333
+ report();
334
+ callback(null, chunk);
335
+ },
336
+ });
337
+ const extract = tar.extract();
338
+ extract.on("entry", (header, entryStream, next) => {
339
+ void (async () => {
340
+ abortIfNeeded(input.signal);
341
+ const name = assertSafeRelativePath(header.name.replace(/\/$/, ""), "archive path");
342
+ if (seen.has(name)) throw new Error(`Duplicate archive path '${name}'`);
343
+ seen.add(name);
344
+ entriesProcessed += 1;
345
+ if (entriesProcessed > limits.maxEntries) throw new Error("Transfer entry limit exceeded");
346
+ if (entriesProcessed === 1 && name !== "manifest.json") {
347
+ throw new Error("manifest.json must be the first archive entry");
348
+ }
349
+ if (
350
+ name !== "manifest.json" &&
351
+ name !== "session.jsonl" &&
352
+ name !== "workspace" &&
353
+ !name.startsWith("workspace/")
354
+ ) {
355
+ throw new Error(`Unexpected archive path '${name}'`);
356
+ }
357
+ const target = path.resolve(outputRoot, ...name.split("/"));
358
+ if (!isPathInside(outputRoot, target))
359
+ throw new Error(`Archive path escapes output: ${name}`);
360
+ await assertNoSymlinkParents(outputRoot, target);
361
+ const mode = (header.mode ?? (header.type === "directory" ? 0o755 : 0o600)) & 0o7777;
362
+ const mtime = header.mtime ?? new Date(0);
363
+ if (header.type === "directory") {
364
+ if (header.size !== 0) throw new Error(`Directory '${name}' has content`);
365
+ await drainEntry(entryStream);
366
+ await mkdir(target, { recursive: false, mode: mode | 0o700 });
367
+ directoryMetadata.push({ target, mode, mtime });
368
+ } else if (header.type === "symlink") {
369
+ if (header.size !== 0) throw new Error(`Symlink '${name}' has content`);
370
+ await drainEntry(entryStream);
371
+ if (!name.startsWith("workspace/")) {
372
+ throw new Error(`Archive symlink is outside the workspace: ${name}`);
373
+ }
374
+ const link = header.linkname ?? "";
375
+ if (path.isAbsolute(link) || path.win32.isAbsolute(link)) {
376
+ throw new Error(`Absolute archive symlink '${name}'`);
377
+ }
378
+ await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
379
+ await symlink(link, target);
380
+ symlinks.set(name.slice("workspace/".length), link);
381
+ } else if (header.type === "file" || !header.type) {
382
+ const size = header.size ?? 0;
383
+ if (!Number.isSafeInteger(size) || size < 0) {
384
+ throw new Error(`Invalid size for archive entry '${name}'`);
385
+ }
386
+ await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
387
+ if (name === "manifest.json") {
388
+ const content = await streamBuffer(
389
+ entryStream as AsyncIterable<Uint8Array>,
390
+ MANIFEST_MAX_BYTES,
391
+ "Transfer manifest",
392
+ );
393
+ await writeFile(target, content, { flag: "wx", mode: 0o600 });
394
+ manifest = parseTransferManifest(JSON.parse(content.toString("utf8")));
395
+ } else {
396
+ const handle = await open(target, "wx", mode);
397
+ let actualSize = 0;
398
+ try {
399
+ for await (const chunk of entryStream as AsyncIterable<Uint8Array>) {
400
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
401
+ actualSize += buffer.length;
402
+ logicalBytesProcessed += buffer.length;
403
+ if (
404
+ !Number.isSafeInteger(actualSize) ||
405
+ logicalBytesProcessed > limits.maxLogicalBytes
406
+ ) {
407
+ throw new Error("Transfer logical byte limit exceeded");
408
+ }
409
+ await handle.write(buffer);
410
+ }
411
+ } finally {
412
+ await handle.close();
413
+ }
414
+ if (actualSize !== size) {
415
+ throw new Error(`Archive entry '${name}' size does not match its content`);
416
+ }
417
+ await chmod(target, mode);
418
+ await utimes(target, mtime, mtime);
419
+ }
420
+ } else {
421
+ await drainEntry(entryStream);
422
+ throw new Error(`Unsupported tar entry type '${header.type}' for '${name}'`);
423
+ }
424
+ report();
425
+ next();
426
+ })().catch((error) => next(error as Error));
427
+ });
428
+ const abort = (): void => extract.destroy(input.signal?.reason);
429
+ input.signal?.addEventListener("abort", abort, { once: true });
430
+ try {
431
+ await pipeline(input.compressed, metered, createZstdDecompress(), extract);
432
+ } finally {
433
+ input.signal?.removeEventListener("abort", abort);
434
+ }
435
+ assertConfinedSymlinks(symlinks);
436
+ for (const directory of directoryMetadata.reverse()) {
437
+ await chmod(directory.target, directory.mode);
438
+ await utimes(directory.target, directory.mtime, directory.mtime);
439
+ }
440
+ if (!manifest) throw new Error("Transfer manifest is missing");
441
+ if (!seen.has("workspace") || !seen.has("session.jsonl")) {
442
+ throw new Error("Transfer archive is incomplete");
443
+ }
444
+ return {
445
+ manifest,
446
+ compressedBytes,
447
+ streamSha256: hash.digest("hex"),
448
+ };
449
+ }