@leitwerk-dev/session-transfer 0.0.0-bootstrap.0 → 0.2.1
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.
- package/dist/LICENSE +13 -0
- package/dist/archive.d.ts +104 -0
- package/dist/archive.d.ts.map +1 -0
- package/dist/format.d.ts +215 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +674 -0
- package/dist/index.js.map +1 -0
- package/dist/project-evidence.d.ts +7 -0
- package/dist/project-evidence.d.ts.map +1 -0
- package/dist/symlink-confinement.d.ts +3 -0
- package/dist/symlink-confinement.d.ts.map +1 -0
- package/package.json +40 -14
- package/src/archive.ts +503 -0
- package/src/format.ts +392 -0
- package/src/index.ts +28 -0
- package/src/project-evidence.ts +48 -0
- package/src/symlink-confinement.ts +38 -0
- package/README.md +0 -1
package/src/archive.ts
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
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
|
+
/** @internal */
|
|
36
|
+
export interface PortableEntry {
|
|
37
|
+
/** @internal */
|
|
38
|
+
relativePath: string;
|
|
39
|
+
/** @internal */
|
|
40
|
+
kind: "file" | "directory" | "symlink";
|
|
41
|
+
/** @internal */
|
|
42
|
+
mode: number;
|
|
43
|
+
/** @internal */
|
|
44
|
+
mtimeMs: number;
|
|
45
|
+
/** @internal */
|
|
46
|
+
size: number;
|
|
47
|
+
/** @internal */
|
|
48
|
+
linkTarget?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** @internal */
|
|
52
|
+
export interface TransferPreflight extends SessionTransferPreflight {
|
|
53
|
+
/** @internal */
|
|
54
|
+
entries: PortableEntry[];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** @internal */
|
|
58
|
+
export interface ExtractTransferResult {
|
|
59
|
+
/** @internal */
|
|
60
|
+
manifest: LeitwerkTransferManifestV1;
|
|
61
|
+
/** @internal */
|
|
62
|
+
compressedBytes: number;
|
|
63
|
+
/** @internal */
|
|
64
|
+
streamSha256: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** @internal */
|
|
68
|
+
export interface PreparedTransferArchive {
|
|
69
|
+
/** @internal */
|
|
70
|
+
manifest: LeitwerkTransferManifestV1;
|
|
71
|
+
/** @internal */
|
|
72
|
+
preflight: TransferPreflight;
|
|
73
|
+
/** @internal */
|
|
74
|
+
stream(input: {
|
|
75
|
+
/** @internal */
|
|
76
|
+
signal?: AbortSignal;
|
|
77
|
+
}): Readable;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function abortIfNeeded(signal?: AbortSignal): void {
|
|
81
|
+
if (signal?.aborted) throw signal.reason ?? new Error("Transfer cancelled");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function toSafeNumber(value: bigint, label: string): number {
|
|
85
|
+
if (value > BigInt(Number.MAX_SAFE_INTEGER))
|
|
86
|
+
throw new Error(`${label} exceeds safe integer range`);
|
|
87
|
+
return Number(value);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** @internal */
|
|
91
|
+
export async function scanPortableWorkspace(input: {
|
|
92
|
+
/** @internal */
|
|
93
|
+
workspaceRoot: string;
|
|
94
|
+
/** @internal */
|
|
95
|
+
sessionFile: string;
|
|
96
|
+
/** @internal */
|
|
97
|
+
limits?: SessionTransferLimits;
|
|
98
|
+
/** @internal */
|
|
99
|
+
signal?: AbortSignal;
|
|
100
|
+
}): Promise<TransferPreflight> {
|
|
101
|
+
const limits = input.limits ?? DEFAULT_SESSION_TRANSFER_LIMITS;
|
|
102
|
+
const root = path.resolve(input.workspaceRoot);
|
|
103
|
+
if (!(await lstat(root, { bigint: true })).isDirectory()) {
|
|
104
|
+
throw new Error("Process workspace is not a directory");
|
|
105
|
+
}
|
|
106
|
+
const entries: PortableEntry[] = [];
|
|
107
|
+
let logicalBytesTotal = 0;
|
|
108
|
+
const add = (entry: PortableEntry): void => {
|
|
109
|
+
entries.push(entry);
|
|
110
|
+
if (entries.length + 3 > limits.maxEntries) throw new Error("Transfer entry limit exceeded");
|
|
111
|
+
if (entry.kind === "file") {
|
|
112
|
+
logicalBytesTotal += entry.size;
|
|
113
|
+
if (!Number.isSafeInteger(logicalBytesTotal) || logicalBytesTotal > limits.maxLogicalBytes) {
|
|
114
|
+
throw new Error("Transfer logical byte limit exceeded");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
const walk = async (directory: string, relativeDirectory: string): Promise<void> => {
|
|
119
|
+
abortIfNeeded(input.signal);
|
|
120
|
+
const names = await readdir(directory);
|
|
121
|
+
names.sort((left, right) => Buffer.from(left).compare(Buffer.from(right)));
|
|
122
|
+
for (const name of names) {
|
|
123
|
+
abortIfNeeded(input.signal);
|
|
124
|
+
// Archive paths are normalized with POSIX separators during extraction.
|
|
125
|
+
// A backslash is a valid POSIX filename character, so reject it here
|
|
126
|
+
// rather than silently changing the exported filename on import.
|
|
127
|
+
if (name.includes("\\")) {
|
|
128
|
+
throw new Error(`Workspace entry contains an unsupported path separator: ${name}`);
|
|
129
|
+
}
|
|
130
|
+
const absolute = path.join(directory, name);
|
|
131
|
+
if (!isPathInside(root, absolute))
|
|
132
|
+
throw new Error("Workspace scan escaped its configured root");
|
|
133
|
+
const relativePath = path.posix.join(relativeDirectory, name);
|
|
134
|
+
const stats = await lstat(absolute, { bigint: true });
|
|
135
|
+
const common = {
|
|
136
|
+
relativePath,
|
|
137
|
+
mode: Number(stats.mode & 0o7777n),
|
|
138
|
+
mtimeMs: Number(stats.mtimeMs),
|
|
139
|
+
};
|
|
140
|
+
if (stats.isDirectory()) {
|
|
141
|
+
add({ ...common, kind: "directory", size: 0 });
|
|
142
|
+
await walk(absolute, relativePath);
|
|
143
|
+
} else if (stats.isFile()) {
|
|
144
|
+
add({ ...common, kind: "file", size: toSafeNumber(stats.size, relativePath) });
|
|
145
|
+
} else if (stats.isSymbolicLink()) {
|
|
146
|
+
const linkTarget = await readlink(absolute);
|
|
147
|
+
if (path.isAbsolute(linkTarget) || path.win32.isAbsolute(linkTarget)) {
|
|
148
|
+
throw new Error(`Absolute symlink is not portable: ${relativePath}`);
|
|
149
|
+
}
|
|
150
|
+
add({ ...common, kind: "symlink", size: 0, linkTarget });
|
|
151
|
+
} else {
|
|
152
|
+
throw new Error(`Unsupported workspace entry type: ${relativePath}`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
await walk(root, "");
|
|
157
|
+
assertConfinedSymlinks(
|
|
158
|
+
new Map(
|
|
159
|
+
entries.flatMap((entry) =>
|
|
160
|
+
entry.kind === "symlink" ? [[entry.relativePath, entry.linkTarget ?? ""] as const] : [],
|
|
161
|
+
),
|
|
162
|
+
),
|
|
163
|
+
);
|
|
164
|
+
const sessionStats = await lstat(path.resolve(input.sessionFile), { bigint: true });
|
|
165
|
+
if (!sessionStats.isFile()) throw new Error("Primary Pi session is not a regular file");
|
|
166
|
+
logicalBytesTotal += toSafeNumber(sessionStats.size, "Pi session");
|
|
167
|
+
if (!Number.isSafeInteger(logicalBytesTotal) || logicalBytesTotal > limits.maxLogicalBytes) {
|
|
168
|
+
throw new Error("Transfer logical byte limit exceeded");
|
|
169
|
+
}
|
|
170
|
+
return { entries, entriesTotal: entries.length + 3, logicalBytesTotal };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function addBufferEntry(
|
|
174
|
+
pack: tar.Pack,
|
|
175
|
+
header: TarHeader,
|
|
176
|
+
content: Buffer | string = Buffer.alloc(0),
|
|
177
|
+
): Promise<void> {
|
|
178
|
+
return new Promise((resolve, reject) => {
|
|
179
|
+
pack.entry(header, content, (error) => (error ? reject(error) : resolve()));
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function addFileEntry(
|
|
184
|
+
pack: tar.Pack,
|
|
185
|
+
header: TarHeader,
|
|
186
|
+
filePath: string,
|
|
187
|
+
signal: AbortSignal | undefined,
|
|
188
|
+
): Promise<void> {
|
|
189
|
+
abortIfNeeded(signal);
|
|
190
|
+
const entry = pack.entry(header);
|
|
191
|
+
await pipeline(createReadStream(filePath), entry, { signal });
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** @internal */
|
|
195
|
+
export async function prepareTransferArchive(input: {
|
|
196
|
+
/** @internal */
|
|
197
|
+
workspaceRoot: string;
|
|
198
|
+
/** @internal */
|
|
199
|
+
sessionFile: string;
|
|
200
|
+
/** @internal */
|
|
201
|
+
manifest: LeitwerkTransferManifestV1;
|
|
202
|
+
/** @internal */
|
|
203
|
+
limits: SessionTransferLimits;
|
|
204
|
+
/** @internal */
|
|
205
|
+
signal?: AbortSignal;
|
|
206
|
+
}): Promise<PreparedTransferArchive> {
|
|
207
|
+
const preflight = await scanPortableWorkspace(input);
|
|
208
|
+
const manifest: LeitwerkTransferManifestV1 = {
|
|
209
|
+
...input.manifest,
|
|
210
|
+
projects: await readProjectEvidence(input.workspaceRoot, input.manifest.projects, input.signal),
|
|
211
|
+
};
|
|
212
|
+
return {
|
|
213
|
+
manifest,
|
|
214
|
+
preflight,
|
|
215
|
+
stream: ({ signal }) => createTransferArchive({ ...input, manifest, preflight, signal }),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** @internal */
|
|
220
|
+
export function createTransferArchive(input: {
|
|
221
|
+
/** @internal */
|
|
222
|
+
workspaceRoot: string;
|
|
223
|
+
/** @internal */
|
|
224
|
+
sessionFile: string;
|
|
225
|
+
/** @internal */
|
|
226
|
+
manifest: LeitwerkTransferManifestV1;
|
|
227
|
+
/** @internal */
|
|
228
|
+
preflight: TransferPreflight;
|
|
229
|
+
/** @internal */
|
|
230
|
+
signal?: AbortSignal;
|
|
231
|
+
}): Readable {
|
|
232
|
+
const pack = tar.pack();
|
|
233
|
+
const zstd = createZstdCompress({
|
|
234
|
+
params: {
|
|
235
|
+
[zlibConstants.ZSTD_c_compressionLevel]: 1,
|
|
236
|
+
[zlibConstants.ZSTD_c_checksumFlag]: 1,
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
const createdAt = new Date(input.manifest.createdAt);
|
|
240
|
+
const finish = async (): Promise<void> => {
|
|
241
|
+
abortIfNeeded(input.signal);
|
|
242
|
+
const manifest = `${JSON.stringify(input.manifest)}\n`;
|
|
243
|
+
await addBufferEntry(pack, { name: "manifest.json", mode: 0o600, mtime: createdAt }, manifest);
|
|
244
|
+
await addBufferEntry(pack, {
|
|
245
|
+
name: "workspace/",
|
|
246
|
+
type: "directory",
|
|
247
|
+
mode: 0o755,
|
|
248
|
+
mtime: createdAt,
|
|
249
|
+
});
|
|
250
|
+
for (const entry of input.preflight.entries) {
|
|
251
|
+
abortIfNeeded(input.signal);
|
|
252
|
+
const name = `workspace/${entry.relativePath}${entry.kind === "directory" ? "/" : ""}`;
|
|
253
|
+
const header: TarHeader = {
|
|
254
|
+
name,
|
|
255
|
+
type: entry.kind === "file" ? "file" : entry.kind,
|
|
256
|
+
mode: entry.mode,
|
|
257
|
+
mtime: new Date(entry.mtimeMs),
|
|
258
|
+
...(entry.kind === "file" ? { size: entry.size } : {}),
|
|
259
|
+
...(entry.linkTarget ? { linkname: entry.linkTarget } : {}),
|
|
260
|
+
};
|
|
261
|
+
if (entry.kind === "file") {
|
|
262
|
+
await addFileEntry(
|
|
263
|
+
pack,
|
|
264
|
+
header,
|
|
265
|
+
path.join(input.workspaceRoot, ...entry.relativePath.split("/")),
|
|
266
|
+
input.signal,
|
|
267
|
+
);
|
|
268
|
+
} else {
|
|
269
|
+
await addBufferEntry(pack, header);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const workspaceBytes = input.preflight.entries.reduce(
|
|
273
|
+
(sum, entry) => sum + (entry.kind === "file" ? entry.size : 0),
|
|
274
|
+
0,
|
|
275
|
+
);
|
|
276
|
+
await addFileEntry(
|
|
277
|
+
pack,
|
|
278
|
+
{
|
|
279
|
+
name: "session.jsonl",
|
|
280
|
+
mode: 0o600,
|
|
281
|
+
mtime: createdAt,
|
|
282
|
+
size: input.preflight.logicalBytesTotal - workspaceBytes,
|
|
283
|
+
},
|
|
284
|
+
input.sessionFile,
|
|
285
|
+
input.signal,
|
|
286
|
+
);
|
|
287
|
+
pack.finalize();
|
|
288
|
+
};
|
|
289
|
+
// Pipeline propagates failures and consumer cancellation in both directions.
|
|
290
|
+
// Its rejection is also exposed as an error on the returned compressed stream.
|
|
291
|
+
void pipeline(pack, zstd, { signal: input.signal }).catch(() => undefined);
|
|
292
|
+
void finish().catch((error) => pack.destroy(error as Error));
|
|
293
|
+
return zstd;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async function assertNoSymlinkParents(root: string, target: string): Promise<void> {
|
|
297
|
+
let current = root;
|
|
298
|
+
for (const segment of path.relative(root, path.dirname(target)).split(path.sep).filter(Boolean)) {
|
|
299
|
+
current = path.join(current, segment);
|
|
300
|
+
try {
|
|
301
|
+
if ((await lstat(current)).isSymbolicLink()) {
|
|
302
|
+
throw new Error(`Archive path traverses symlink '${segment}'`);
|
|
303
|
+
}
|
|
304
|
+
} catch (error) {
|
|
305
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function drainEntry(stream: AsyncIterable<unknown>): Promise<void> {
|
|
311
|
+
for await (const _chunk of stream) {
|
|
312
|
+
// tar-stream requires each entry to be drained before advancing.
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async function streamBuffer(
|
|
317
|
+
stream: AsyncIterable<Uint8Array>,
|
|
318
|
+
limit: number,
|
|
319
|
+
label: string,
|
|
320
|
+
): Promise<Buffer> {
|
|
321
|
+
const chunks: Buffer[] = [];
|
|
322
|
+
let size = 0;
|
|
323
|
+
for await (const chunk of stream) {
|
|
324
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
325
|
+
size += buffer.length;
|
|
326
|
+
if (size > limit) throw new Error(`${label} is too large`);
|
|
327
|
+
chunks.push(buffer);
|
|
328
|
+
}
|
|
329
|
+
return Buffer.concat(chunks);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** @internal */
|
|
333
|
+
export async function extractTransferArchive(input: {
|
|
334
|
+
/** @internal */
|
|
335
|
+
compressed: Readable;
|
|
336
|
+
/** @internal */
|
|
337
|
+
outputRoot: string;
|
|
338
|
+
/** @internal */
|
|
339
|
+
limits?: SessionTransferLimits;
|
|
340
|
+
/** @internal */
|
|
341
|
+
signal?: AbortSignal;
|
|
342
|
+
/** @internal */
|
|
343
|
+
onProgress?: (
|
|
344
|
+
progress: TransferArchiveProgress & {
|
|
345
|
+
/** @internal */
|
|
346
|
+
compressedBytes: number;
|
|
347
|
+
},
|
|
348
|
+
) => void;
|
|
349
|
+
/** @internal */
|
|
350
|
+
ownershipMarker?: {
|
|
351
|
+
/** @internal */
|
|
352
|
+
name: string;
|
|
353
|
+
/** @internal */
|
|
354
|
+
value: string;
|
|
355
|
+
};
|
|
356
|
+
}): Promise<ExtractTransferResult> {
|
|
357
|
+
const limits = input.limits ?? DEFAULT_SESSION_TRANSFER_LIMITS;
|
|
358
|
+
const outputRoot = path.resolve(input.outputRoot);
|
|
359
|
+
await mkdir(outputRoot, { recursive: false, mode: 0o700 });
|
|
360
|
+
if (input.ownershipMarker) {
|
|
361
|
+
const markerName = assertSafeRelativePath(input.ownershipMarker.name, "ownership marker");
|
|
362
|
+
if (markerName.includes("/")) throw new Error("Ownership marker must be a root file");
|
|
363
|
+
await writeFile(path.join(outputRoot, markerName), `${input.ownershipMarker.value}\n`, {
|
|
364
|
+
flag: "wx",
|
|
365
|
+
mode: 0o600,
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const hash = createHash("sha256");
|
|
370
|
+
let compressedBytes = 0;
|
|
371
|
+
let entriesProcessed = 0;
|
|
372
|
+
let logicalBytesProcessed = 0;
|
|
373
|
+
let manifest: LeitwerkTransferManifestV1 | null = null;
|
|
374
|
+
const seen = new Set<string>();
|
|
375
|
+
const symlinks = new Map<string, string>();
|
|
376
|
+
const directoryMetadata: Array<{ target: string; mode: number; mtime: Date }> = [];
|
|
377
|
+
const report = (): void =>
|
|
378
|
+
input.onProgress?.({ entriesProcessed, logicalBytesProcessed, compressedBytes });
|
|
379
|
+
const metered = new Transform({
|
|
380
|
+
transform(chunk: Buffer, _encoding, callback) {
|
|
381
|
+
compressedBytes += chunk.length;
|
|
382
|
+
if (compressedBytes > limits.maxCompressedBytes) {
|
|
383
|
+
callback(new Error("Transfer compressed byte limit exceeded"));
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
hash.update(chunk);
|
|
387
|
+
report();
|
|
388
|
+
callback(null, chunk);
|
|
389
|
+
},
|
|
390
|
+
});
|
|
391
|
+
const extract = tar.extract();
|
|
392
|
+
extract.on("entry", (header, entryStream, next) => {
|
|
393
|
+
void (async () => {
|
|
394
|
+
abortIfNeeded(input.signal);
|
|
395
|
+
const name = assertSafeRelativePath(header.name.replace(/\/$/, ""), "archive path");
|
|
396
|
+
if (seen.has(name)) throw new Error(`Duplicate archive path '${name}'`);
|
|
397
|
+
seen.add(name);
|
|
398
|
+
entriesProcessed += 1;
|
|
399
|
+
if (entriesProcessed > limits.maxEntries) throw new Error("Transfer entry limit exceeded");
|
|
400
|
+
if (entriesProcessed === 1 && name !== "manifest.json") {
|
|
401
|
+
throw new Error("manifest.json must be the first archive entry");
|
|
402
|
+
}
|
|
403
|
+
if (
|
|
404
|
+
name !== "manifest.json" &&
|
|
405
|
+
name !== "session.jsonl" &&
|
|
406
|
+
name !== "workspace" &&
|
|
407
|
+
!name.startsWith("workspace/")
|
|
408
|
+
) {
|
|
409
|
+
throw new Error(`Unexpected archive path '${name}'`);
|
|
410
|
+
}
|
|
411
|
+
const target = path.resolve(outputRoot, ...name.split("/"));
|
|
412
|
+
if (!isPathInside(outputRoot, target))
|
|
413
|
+
throw new Error(`Archive path escapes output: ${name}`);
|
|
414
|
+
await assertNoSymlinkParents(outputRoot, target);
|
|
415
|
+
const mode = (header.mode ?? (header.type === "directory" ? 0o755 : 0o600)) & 0o7777;
|
|
416
|
+
const mtime = header.mtime ?? new Date(0);
|
|
417
|
+
if (header.type === "directory") {
|
|
418
|
+
if (header.size !== 0) throw new Error(`Directory '${name}' has content`);
|
|
419
|
+
await drainEntry(entryStream);
|
|
420
|
+
await mkdir(target, { recursive: false, mode: mode | 0o700 });
|
|
421
|
+
directoryMetadata.push({ target, mode, mtime });
|
|
422
|
+
} else if (header.type === "symlink") {
|
|
423
|
+
if (header.size !== 0) throw new Error(`Symlink '${name}' has content`);
|
|
424
|
+
await drainEntry(entryStream);
|
|
425
|
+
if (!name.startsWith("workspace/")) {
|
|
426
|
+
throw new Error(`Archive symlink is outside the workspace: ${name}`);
|
|
427
|
+
}
|
|
428
|
+
const link = header.linkname ?? "";
|
|
429
|
+
if (path.isAbsolute(link) || path.win32.isAbsolute(link)) {
|
|
430
|
+
throw new Error(`Absolute archive symlink '${name}'`);
|
|
431
|
+
}
|
|
432
|
+
await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
433
|
+
await symlink(link, target);
|
|
434
|
+
symlinks.set(name.slice("workspace/".length), link);
|
|
435
|
+
} else if (header.type === "file" || !header.type) {
|
|
436
|
+
const size = header.size ?? 0;
|
|
437
|
+
if (!Number.isSafeInteger(size) || size < 0) {
|
|
438
|
+
throw new Error(`Invalid size for archive entry '${name}'`);
|
|
439
|
+
}
|
|
440
|
+
await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
441
|
+
if (name === "manifest.json") {
|
|
442
|
+
const content = await streamBuffer(
|
|
443
|
+
entryStream as AsyncIterable<Uint8Array>,
|
|
444
|
+
MANIFEST_MAX_BYTES,
|
|
445
|
+
"Transfer manifest",
|
|
446
|
+
);
|
|
447
|
+
await writeFile(target, content, { flag: "wx", mode: 0o600 });
|
|
448
|
+
manifest = parseTransferManifest(JSON.parse(content.toString("utf8")));
|
|
449
|
+
} else {
|
|
450
|
+
const handle = await open(target, "wx", mode);
|
|
451
|
+
let actualSize = 0;
|
|
452
|
+
try {
|
|
453
|
+
for await (const chunk of entryStream as AsyncIterable<Uint8Array>) {
|
|
454
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
455
|
+
actualSize += buffer.length;
|
|
456
|
+
logicalBytesProcessed += buffer.length;
|
|
457
|
+
if (
|
|
458
|
+
!Number.isSafeInteger(actualSize) ||
|
|
459
|
+
logicalBytesProcessed > limits.maxLogicalBytes
|
|
460
|
+
) {
|
|
461
|
+
throw new Error("Transfer logical byte limit exceeded");
|
|
462
|
+
}
|
|
463
|
+
await handle.write(buffer);
|
|
464
|
+
}
|
|
465
|
+
} finally {
|
|
466
|
+
await handle.close();
|
|
467
|
+
}
|
|
468
|
+
if (actualSize !== size) {
|
|
469
|
+
throw new Error(`Archive entry '${name}' size does not match its content`);
|
|
470
|
+
}
|
|
471
|
+
await chmod(target, mode);
|
|
472
|
+
await utimes(target, mtime, mtime);
|
|
473
|
+
}
|
|
474
|
+
} else {
|
|
475
|
+
await drainEntry(entryStream);
|
|
476
|
+
throw new Error(`Unsupported tar entry type '${header.type}' for '${name}'`);
|
|
477
|
+
}
|
|
478
|
+
report();
|
|
479
|
+
next();
|
|
480
|
+
})().catch((error) => next(error as Error));
|
|
481
|
+
});
|
|
482
|
+
const abort = (): void => extract.destroy(input.signal?.reason);
|
|
483
|
+
input.signal?.addEventListener("abort", abort, { once: true });
|
|
484
|
+
try {
|
|
485
|
+
await pipeline(input.compressed, metered, createZstdDecompress(), extract);
|
|
486
|
+
} finally {
|
|
487
|
+
input.signal?.removeEventListener("abort", abort);
|
|
488
|
+
}
|
|
489
|
+
assertConfinedSymlinks(symlinks);
|
|
490
|
+
for (const directory of directoryMetadata.reverse()) {
|
|
491
|
+
await chmod(directory.target, directory.mode);
|
|
492
|
+
await utimes(directory.target, directory.mtime, directory.mtime);
|
|
493
|
+
}
|
|
494
|
+
if (!manifest) throw new Error("Transfer manifest is missing");
|
|
495
|
+
if (!seen.has("workspace") || !seen.has("session.jsonl")) {
|
|
496
|
+
throw new Error("Transfer archive is incomplete");
|
|
497
|
+
}
|
|
498
|
+
return {
|
|
499
|
+
manifest,
|
|
500
|
+
compressedBytes,
|
|
501
|
+
streamSha256: hash.digest("hex"),
|
|
502
|
+
};
|
|
503
|
+
}
|