@ship.zone/runner 0.1.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,1605 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { dirname, join, resolve } from '@std/path';
3
+ import { ProtocolError, ResourceCleanupError, RunnerError } from './errors.ts';
4
+ import type {
5
+ ITransferDownload,
6
+ ITransferMetadata,
7
+ ITransferRecord,
8
+ IWorkspaceTreeMetadata,
9
+ TOpenTransferBody,
10
+ } from './interfaces.ts';
11
+
12
+ const tarBlockSize = 512;
13
+ const maximumPaxHeaderBytes = 16 * 1024;
14
+ const maximumPathBytes = 4096;
15
+ const maximumPathSegmentBytes = 255;
16
+ const streamBufferBytes = 64 * 1024;
17
+ const zeroBlock = new Uint8Array(tarBlockSize);
18
+ const textEncoder = new TextEncoder();
19
+ const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
20
+ const asciiDecoder = new TextDecoder('ascii', { fatal: true });
21
+ const sha256Pattern = /^[a-f0-9]{64}$/;
22
+
23
+ export interface IArchiveLimits {
24
+ maximumArchiveBytes: number;
25
+ maximumExtractedBytes: number;
26
+ maximumEntries: number;
27
+ }
28
+
29
+ export interface IStagedTransferArchive {
30
+ path: string;
31
+ metadata: ITransferMetadata;
32
+ cleanup(): Promise<void>;
33
+ }
34
+
35
+ export interface IExtractTarGzipOptions {
36
+ archivePath: string;
37
+ destinationPath: string;
38
+ expectedMetadata: ITransferMetadata;
39
+ maximumExtractedBytes: number;
40
+ maximumEntries: number;
41
+ signal?: AbortSignal;
42
+ allowSymlinks?: boolean;
43
+ allowedPaths?: string[];
44
+ requireAllowedPaths?: boolean;
45
+ }
46
+
47
+ export interface ICreateTarGzipOptions {
48
+ sourcePath: string;
49
+ selections: string[];
50
+ expectedMetadata: IWorkspaceTreeMetadata;
51
+ archiveDirectory: string;
52
+ archivePrefix: string;
53
+ maximumArchiveBytes: number;
54
+ maximumExtractedBytes: number;
55
+ maximumEntries: number;
56
+ allowSymlinks: boolean;
57
+ requireAllSelections?: boolean;
58
+ signal?: AbortSignal;
59
+ fileOperations?: ITransferArchiveFileOperations;
60
+ }
61
+
62
+ export interface ITransferArchiveFileOperations {
63
+ makeTempFile(options: Deno.MakeTempOptions): Promise<string>;
64
+ chmod(path: string, mode: number): Promise<void>;
65
+ remove(path: string, options?: Deno.RemoveOptions): Promise<void>;
66
+ }
67
+
68
+ export interface IPreparedTransferArchive {
69
+ path: string;
70
+ metadata: ITransferMetadata;
71
+ openBody: TOpenTransferBody;
72
+ cleanup(): Promise<void>;
73
+ }
74
+
75
+ type TArchiveEntryType = 'directory' | 'file' | 'symlink';
76
+
77
+ interface IArchiveEntry {
78
+ path: string;
79
+ absolutePath: string;
80
+ type: TArchiveEntryType;
81
+ sizeBytes: number;
82
+ executable: boolean;
83
+ linkTarget?: string;
84
+ symlinkScope: string[];
85
+ snapshot: IFileSnapshot;
86
+ }
87
+
88
+ interface IFileSnapshot {
89
+ type: TArchiveEntryType;
90
+ dev: number;
91
+ ino: number;
92
+ nlink: number;
93
+ size: number;
94
+ mode: number;
95
+ mtime: number | null;
96
+ }
97
+
98
+ interface ISymlinkDescription {
99
+ path: string;
100
+ target: string;
101
+ scope: string[];
102
+ }
103
+
104
+ const checkedInteger = (value: number, field: string, allowZero = true): number => {
105
+ if (!Number.isSafeInteger(value) || value < (allowZero ? 0 : 1)) {
106
+ throw new ProtocolError(
107
+ `${field} must be a ${allowZero ? 'non-negative' : 'positive'} integer`,
108
+ );
109
+ }
110
+ return value;
111
+ };
112
+
113
+ const checkedAdd = (left: number, right: number, message: string): number => {
114
+ const result = left + right;
115
+ if (!Number.isSafeInteger(result)) throw new ProtocolError(message);
116
+ return result;
117
+ };
118
+
119
+ const checkedMultiply = (left: number, right: number, message: string): number => {
120
+ const result = left * right;
121
+ if (!Number.isSafeInteger(result)) throw new ProtocolError(message);
122
+ return result;
123
+ };
124
+
125
+ const defaultFileOperations: ITransferArchiveFileOperations = {
126
+ makeTempFile: (options) => Deno.makeTempFile(options),
127
+ chmod: (path, mode) => Deno.chmod(path, mode),
128
+ remove: (path, options) => Deno.remove(path, options),
129
+ };
130
+
131
+ export const removePathIfPresent = async (
132
+ path: string,
133
+ recursive = false,
134
+ remove: ITransferArchiveFileOperations['remove'] = defaultFileOperations.remove,
135
+ ): Promise<void> => {
136
+ try {
137
+ await remove(path, { recursive });
138
+ } catch (error) {
139
+ if (!(error instanceof Deno.errors.NotFound)) {
140
+ throw new ResourceCleanupError(`Unable to remove owned path ${path}`, [error]);
141
+ }
142
+ }
143
+ };
144
+
145
+ const cleanupForPath = (
146
+ path: string,
147
+ recursive = false,
148
+ remove: ITransferArchiveFileOperations['remove'] = defaultFileOperations.remove,
149
+ ): () => Promise<void> => {
150
+ let cleaned = false;
151
+ let cleanupPromise: Promise<void> | undefined;
152
+ return () => {
153
+ if (cleaned) return Promise.resolve();
154
+ cleanupPromise ??= removePathIfPresent(path, recursive, remove).then(
155
+ () => {
156
+ cleaned = true;
157
+ },
158
+ (error) => {
159
+ cleanupPromise = undefined;
160
+ throw error;
161
+ },
162
+ );
163
+ return cleanupPromise;
164
+ };
165
+ };
166
+
167
+ export const ensureStagingCapacity = async (
168
+ path: string,
169
+ requiredBytes: number,
170
+ requiredInodes: number,
171
+ reserveBytes: number,
172
+ reserveInodes: number,
173
+ ): Promise<void> => {
174
+ checkedInteger(requiredBytes, 'Required staging bytes');
175
+ checkedInteger(requiredInodes, 'Required staging inodes');
176
+ checkedInteger(reserveBytes, 'Transfer staging byte reserve');
177
+ checkedInteger(reserveInodes, 'Transfer staging inode reserve');
178
+ let output: Deno.CommandOutput;
179
+ try {
180
+ output = await new Deno.Command('/usr/bin/stat', {
181
+ args: ['--file-system', '--format=%a %S %d', '--', path],
182
+ stdin: 'null',
183
+ stdout: 'piped',
184
+ stderr: 'piped',
185
+ }).output();
186
+ } catch (error) {
187
+ throw new RunnerError('Unable to inspect transfer staging capacity', { cause: error });
188
+ }
189
+ if (!output.success || output.stdout.byteLength > 256) {
190
+ throw new RunnerError('Unable to inspect transfer staging capacity');
191
+ }
192
+ const match = /^(\d+) (\d+) (\d+)\n?$/.exec(new TextDecoder().decode(output.stdout));
193
+ if (!match) throw new RunnerError('Transfer staging filesystem returned invalid capacity');
194
+ const blockSize = BigInt(match[2]);
195
+ const availableBytes = BigInt(match[1]) * blockSize;
196
+ const availableInodes = BigInt(match[3]);
197
+ if (availableBytes < 0n || availableInodes < 0n) {
198
+ throw new RunnerError('Transfer staging filesystem returned invalid capacity');
199
+ }
200
+ const allocatedBytes = BigInt(requiredBytes) + BigInt(requiredInodes) * blockSize;
201
+ if (availableBytes < allocatedBytes + BigInt(reserveBytes)) {
202
+ throw new RunnerError('Transfer staging filesystem has insufficient available bytes');
203
+ }
204
+ if (availableInodes < BigInt(requiredInodes) + BigInt(reserveInodes)) {
205
+ throw new RunnerError('Transfer staging filesystem has insufficient available inodes');
206
+ }
207
+ };
208
+
209
+ export const validateTransferMetadata = (
210
+ metadata: ITransferMetadata,
211
+ limits: IArchiveLimits,
212
+ label: string,
213
+ ): void => {
214
+ if (!sha256Pattern.test(metadata.sha256)) {
215
+ throw new ProtocolError(`${label} SHA-256 is invalid`);
216
+ }
217
+ checkedInteger(metadata.sizeBytes, `${label} archive bytes`);
218
+ checkedInteger(metadata.extractedSizeBytes, `${label} extracted bytes`);
219
+ checkedInteger(metadata.entryCount, `${label} entry count`);
220
+ checkedInteger(limits.maximumArchiveBytes, `${label} maximum archive bytes`);
221
+ checkedInteger(limits.maximumExtractedBytes, `${label} maximum extracted bytes`);
222
+ checkedInteger(limits.maximumEntries, `${label} maximum entries`);
223
+ if (
224
+ metadata.sizeBytes > limits.maximumArchiveBytes ||
225
+ metadata.extractedSizeBytes > limits.maximumExtractedBytes ||
226
+ metadata.entryCount > limits.maximumEntries
227
+ ) {
228
+ throw new ProtocolError(`${label} metadata exceeds the effective transfer limits`);
229
+ }
230
+ };
231
+
232
+ export const assertTransferMetadataEqual = (
233
+ actual: ITransferMetadata,
234
+ expected: ITransferMetadata,
235
+ label: string,
236
+ ): void => {
237
+ if (
238
+ actual.sha256 !== expected.sha256 ||
239
+ actual.sizeBytes !== expected.sizeBytes ||
240
+ actual.extractedSizeBytes !== expected.extractedSizeBytes ||
241
+ actual.entryCount !== expected.entryCount
242
+ ) {
243
+ throw new ProtocolError(`${label} metadata did not match its declaration`);
244
+ }
245
+ };
246
+
247
+ const cancelBody = async (
248
+ body: ReadableStream<Uint8Array>,
249
+ error: unknown,
250
+ cleanup?: () => Promise<void>,
251
+ ): Promise<never> => {
252
+ const errors = [error];
253
+ if (cleanup) {
254
+ try {
255
+ await cleanup();
256
+ } catch (cleanupError) {
257
+ errors.push(cleanupError);
258
+ }
259
+ }
260
+ try {
261
+ await body.cancel(error);
262
+ } catch (cancelError) {
263
+ errors.push(cancelError);
264
+ }
265
+ if (errors.length > 1) {
266
+ throw new ResourceCleanupError('Transfer rejection and cleanup failed', errors);
267
+ }
268
+ throw error;
269
+ };
270
+
271
+ const writeAll = async (file: Deno.FsFile, value: Uint8Array): Promise<void> => {
272
+ let offset = 0;
273
+ while (offset < value.byteLength) {
274
+ const written = await file.write(value.subarray(offset));
275
+ if (written <= 0) throw new RunnerError('Transfer staging write made no progress');
276
+ offset += written;
277
+ }
278
+ };
279
+
280
+ export const stageTransferDownload = async (
281
+ download: ITransferDownload,
282
+ options: {
283
+ directory: string;
284
+ prefix: string;
285
+ limits: IArchiveLimits;
286
+ reserveBytes: number;
287
+ reserveInodes: number;
288
+ expectedMetadata?: ITransferMetadata;
289
+ signal?: AbortSignal;
290
+ label: string;
291
+ fileOperations?: ITransferArchiveFileOperations;
292
+ },
293
+ ): Promise<IStagedTransferArchive> => {
294
+ try {
295
+ validateTransferMetadata(download, options.limits, options.label);
296
+ if (options.expectedMetadata) {
297
+ assertTransferMetadataEqual(download, options.expectedMetadata, options.label);
298
+ }
299
+ } catch (error) {
300
+ return await cancelBody(download.body, error);
301
+ }
302
+ const fileOperations = options.fileOperations ?? defaultFileOperations;
303
+ let path: string | undefined;
304
+ let cleanup: (() => Promise<void>) | undefined;
305
+ try {
306
+ await Deno.mkdir(options.directory, { recursive: true, mode: 0o700 });
307
+ await ensureStagingCapacity(
308
+ options.directory,
309
+ download.sizeBytes,
310
+ 1,
311
+ options.reserveBytes,
312
+ options.reserveInodes,
313
+ );
314
+ path = await fileOperations.makeTempFile({
315
+ dir: options.directory,
316
+ prefix: options.prefix,
317
+ suffix: '.tar.gz',
318
+ });
319
+ cleanup = cleanupForPath(path, false, fileOperations.remove);
320
+ await fileOperations.chmod(path, 0o600);
321
+ } catch (error) {
322
+ return await cancelBody(download.body, error, cleanup);
323
+ }
324
+ if (!path || !cleanup) {
325
+ throw new RunnerError('Transfer staging path ownership was not established');
326
+ }
327
+ const digest = createHash('sha256');
328
+ let reader: ReadableStreamDefaultReader<Uint8Array>;
329
+ try {
330
+ reader = download.body.getReader();
331
+ } catch (error) {
332
+ try {
333
+ await cleanup();
334
+ } catch (cleanupError) {
335
+ throw new ResourceCleanupError(
336
+ 'Transfer setup and cleanup failed',
337
+ [error, cleanupError],
338
+ );
339
+ }
340
+ throw error;
341
+ }
342
+ let file: Deno.FsFile | undefined;
343
+ let sizeBytes = 0;
344
+ let primaryError: unknown;
345
+ try {
346
+ file = await Deno.open(path, { write: true, truncate: true });
347
+ while (true) {
348
+ if (options.signal?.aborted) throw options.signal.reason;
349
+ const { done, value } = await reader.read();
350
+ if (done) break;
351
+ if (value.byteLength === 0) continue;
352
+ sizeBytes = checkedAdd(sizeBytes, value.byteLength, 'Transfer body length overflow');
353
+ if (sizeBytes > download.sizeBytes || sizeBytes > options.limits.maximumArchiveBytes) {
354
+ throw new ProtocolError(`${options.label} body exceeded its declared length`);
355
+ }
356
+ digest.update(value);
357
+ await writeAll(file, value);
358
+ }
359
+ if (sizeBytes !== download.sizeBytes) {
360
+ throw new ProtocolError(`${options.label} body length did not match its declaration`);
361
+ }
362
+ if (digest.digest('hex') !== download.sha256) {
363
+ throw new ProtocolError(`${options.label} SHA-256 did not match its declaration`);
364
+ }
365
+ } catch (error) {
366
+ primaryError = error;
367
+ try {
368
+ await reader.cancel(error);
369
+ } catch (cleanupError) {
370
+ primaryError = new ResourceCleanupError(
371
+ 'Transfer staging and body cleanup failed',
372
+ [error, cleanupError],
373
+ );
374
+ }
375
+ } finally {
376
+ const cleanupErrors: unknown[] = [];
377
+ try {
378
+ reader.releaseLock();
379
+ } catch (error) {
380
+ cleanupErrors.push(error);
381
+ }
382
+ try {
383
+ file?.close();
384
+ } catch (error) {
385
+ cleanupErrors.push(error);
386
+ }
387
+ if (cleanupErrors.length > 0) {
388
+ primaryError = new ResourceCleanupError(
389
+ 'Transfer staging stream cleanup failed',
390
+ primaryError === undefined ? cleanupErrors : [primaryError, ...cleanupErrors],
391
+ );
392
+ }
393
+ }
394
+ if (primaryError !== undefined) {
395
+ try {
396
+ await cleanup();
397
+ } catch (cleanupError) {
398
+ throw new ResourceCleanupError(
399
+ 'Transfer staging and file cleanup failed',
400
+ [primaryError, cleanupError],
401
+ );
402
+ }
403
+ throw primaryError;
404
+ }
405
+ return {
406
+ path,
407
+ metadata: {
408
+ sha256: download.sha256,
409
+ sizeBytes: download.sizeBytes,
410
+ extractedSizeBytes: download.extractedSizeBytes,
411
+ entryCount: download.entryCount,
412
+ },
413
+ cleanup,
414
+ };
415
+ };
416
+
417
+ const pathSegments = (value: string, maximumBytes: number, label: string): string[] => {
418
+ if (
419
+ !value ||
420
+ value.startsWith('/') ||
421
+ value.includes('\\') ||
422
+ value.includes('\0') ||
423
+ textEncoder.encode(value).byteLength > maximumBytes
424
+ ) {
425
+ throw new ProtocolError(`${label} contains an unsafe path`);
426
+ }
427
+ const segments = value.split('/');
428
+ if (
429
+ segments.some((segment) =>
430
+ !segment ||
431
+ segment === '.' ||
432
+ segment === '..' ||
433
+ textEncoder.encode(segment).byteLength > maximumPathSegmentBytes
434
+ )
435
+ ) {
436
+ throw new ProtocolError(`${label} contains an unsafe path`);
437
+ }
438
+ return segments;
439
+ };
440
+
441
+ export const validateRelativeSelections = (
442
+ paths: string[],
443
+ label: string,
444
+ maximumCount = 32,
445
+ ): string[] => {
446
+ if (paths.length === 0 || paths.length > maximumCount) {
447
+ throw new ProtocolError(`${label} must contain between 1 and ${maximumCount} paths`);
448
+ }
449
+ for (const path of paths) pathSegments(path, 1024, label);
450
+ const sorted = [...paths].sort(compareUtf8);
451
+ if (new Set(sorted).size !== sorted.length) {
452
+ throw new ProtocolError(`${label} paths must be unique`);
453
+ }
454
+ for (let left = 0; left < sorted.length; left++) {
455
+ for (let right = left + 1; right < sorted.length; right++) {
456
+ if (sorted[right].startsWith(`${sorted[left]}/`)) {
457
+ throw new ProtocolError(`${label} paths must not overlap`);
458
+ }
459
+ }
460
+ }
461
+ return [...paths];
462
+ };
463
+
464
+ const compareUtf8 = (left: string, right: string): number => {
465
+ const leftBytes = textEncoder.encode(left);
466
+ const rightBytes = textEncoder.encode(right);
467
+ const length = Math.min(leftBytes.byteLength, rightBytes.byteLength);
468
+ for (let index = 0; index < length; index++) {
469
+ if (leftBytes[index] !== rightBytes[index]) return leftBytes[index] - rightBytes[index];
470
+ }
471
+ return leftBytes.byteLength - rightBytes.byteLength;
472
+ };
473
+
474
+ const decodeTarText = (bytes: Uint8Array, field: string): string => {
475
+ const nul = bytes.indexOf(0);
476
+ const valueBytes = nul === -1 ? bytes : bytes.subarray(0, nul);
477
+ if (nul !== -1 && bytes.subarray(nul).some((byte) => byte !== 0)) {
478
+ throw new ProtocolError(`Tar ${field} contains data after a NUL terminator`);
479
+ }
480
+ try {
481
+ return utf8Decoder.decode(valueBytes);
482
+ } catch (error) {
483
+ throw new ProtocolError(`Tar ${field} is not valid UTF-8`, { cause: error });
484
+ }
485
+ };
486
+
487
+ const parseTarNumber = (bytes: Uint8Array, field: string): number => {
488
+ if ((bytes[0] & 0x80) !== 0) {
489
+ if ((bytes[0] & 0x40) !== 0) throw new ProtocolError(`Tar ${field} is negative`);
490
+ let value = BigInt(bytes[0] & 0x3f);
491
+ for (const byte of bytes.subarray(1)) value = value * 256n + BigInt(byte);
492
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) {
493
+ throw new ProtocolError(`Tar ${field} exceeds the safe integer range`);
494
+ }
495
+ return Number(value);
496
+ }
497
+ let text: string;
498
+ try {
499
+ const raw = asciiDecoder.decode(bytes);
500
+ const nul = raw.indexOf('\0');
501
+ if (nul === -1) {
502
+ text = raw.trim();
503
+ } else {
504
+ if (!/^[\0 ]*$/.test(raw.slice(nul))) {
505
+ throw new ProtocolError(`Tar ${field} is invalid`);
506
+ }
507
+ text = raw.slice(0, nul).trim();
508
+ }
509
+ } catch (error) {
510
+ if (error instanceof ProtocolError) throw error;
511
+ throw new ProtocolError(`Tar ${field} is invalid`, { cause: error });
512
+ }
513
+ if (text && !/^[0-7]+$/.test(text)) throw new ProtocolError(`Tar ${field} is invalid`);
514
+ const value = text ? Number.parseInt(text, 8) : 0;
515
+ if (!Number.isSafeInteger(value) || value < 0) {
516
+ throw new ProtocolError(`Tar ${field} is invalid`);
517
+ }
518
+ return value;
519
+ };
520
+
521
+ const verifyTarChecksum = (header: Uint8Array): void => {
522
+ const expected = parseTarNumber(header.subarray(148, 156), 'checksum');
523
+ let actual = 0;
524
+ for (let index = 0; index < header.byteLength; index++) {
525
+ actual += index >= 148 && index < 156 ? 32 : header[index];
526
+ }
527
+ if (actual !== expected) throw new ProtocolError('Tar header checksum did not match');
528
+ };
529
+
530
+ const parsePaxRecords = (content: Uint8Array): Map<string, string> => {
531
+ const records = new Map<string, string>();
532
+ let offset = 0;
533
+ while (offset < content.byteLength) {
534
+ const space = content.indexOf(32, offset);
535
+ if (space === -1) throw new ProtocolError('Tar PAX metadata is malformed');
536
+ let lengthText: string;
537
+ try {
538
+ lengthText = asciiDecoder.decode(content.subarray(offset, space));
539
+ } catch (error) {
540
+ throw new ProtocolError('Tar PAX metadata is malformed', { cause: error });
541
+ }
542
+ if (!/^[1-9][0-9]*$/.test(lengthText)) {
543
+ throw new ProtocolError('Tar PAX metadata is malformed');
544
+ }
545
+ const length = Number(lengthText);
546
+ if (
547
+ !Number.isSafeInteger(length) ||
548
+ length <= space - offset + 2 ||
549
+ offset + length > content.byteLength ||
550
+ content[offset + length - 1] !== 10
551
+ ) {
552
+ throw new ProtocolError('Tar PAX metadata is malformed');
553
+ }
554
+ let record: string;
555
+ try {
556
+ record = utf8Decoder.decode(content.subarray(space + 1, offset + length - 1));
557
+ } catch (error) {
558
+ throw new ProtocolError('Tar PAX metadata is not valid UTF-8', { cause: error });
559
+ }
560
+ const separator = record.indexOf('=');
561
+ if (separator <= 0) throw new ProtocolError('Tar PAX metadata is malformed');
562
+ const key = record.slice(0, separator);
563
+ if (!/^[A-Za-z][A-Za-z0-9._-]{0,63}$/.test(key) || records.has(key)) {
564
+ throw new ProtocolError('Tar PAX metadata contains an unsupported key');
565
+ }
566
+ records.set(key, record.slice(separator + 1));
567
+ offset += length;
568
+ }
569
+ return records;
570
+ };
571
+
572
+ class StreamBytes {
573
+ private readonly reader: ReadableStreamDefaultReader<Uint8Array>;
574
+ private chunk = new Uint8Array();
575
+ private offset = 0;
576
+ private total = 0;
577
+ private done = false;
578
+ private failed = false;
579
+
580
+ constructor(
581
+ stream: ReadableStream<Uint8Array>,
582
+ private readonly maximumBytes: number,
583
+ private readonly signal?: AbortSignal,
584
+ ) {
585
+ this.reader = stream.getReader();
586
+ }
587
+
588
+ async readExactly(length: number): Promise<Uint8Array> {
589
+ const result = new Uint8Array(length);
590
+ let written = 0;
591
+ await this.consume(length, (value) => {
592
+ result.set(value, written);
593
+ written += value.byteLength;
594
+ });
595
+ return result;
596
+ }
597
+
598
+ async consume(
599
+ length: number,
600
+ handler?: (value: Uint8Array) => void | Promise<void>,
601
+ ): Promise<void> {
602
+ let remaining = length;
603
+ while (remaining > 0) {
604
+ if (this.offset === this.chunk.byteLength) await this.pull();
605
+ if (this.done) throw new ProtocolError('Tar archive is truncated');
606
+ const count = Math.min(remaining, this.chunk.byteLength - this.offset);
607
+ const value = this.chunk.subarray(this.offset, this.offset + count);
608
+ this.offset += count;
609
+ remaining -= count;
610
+ await handler?.(value);
611
+ }
612
+ }
613
+
614
+ async consumeRemainder(handler: (value: Uint8Array) => void | Promise<void>): Promise<void> {
615
+ while (true) {
616
+ if (this.offset < this.chunk.byteLength) {
617
+ const value = this.chunk.subarray(this.offset);
618
+ this.offset = this.chunk.byteLength;
619
+ await handler(value);
620
+ }
621
+ await this.pull();
622
+ if (this.done) return;
623
+ }
624
+ }
625
+
626
+ async close(cancel: boolean): Promise<void> {
627
+ const cleanupErrors: unknown[] = [];
628
+ try {
629
+ if (cancel && !this.done && !this.failed) await this.reader.cancel();
630
+ } catch (error) {
631
+ cleanupErrors.push(error);
632
+ }
633
+ try {
634
+ this.reader.releaseLock();
635
+ } catch (error) {
636
+ cleanupErrors.push(error);
637
+ }
638
+ if (cleanupErrors.length > 0) {
639
+ throw new ResourceCleanupError('Archive stream cleanup failed', cleanupErrors);
640
+ }
641
+ }
642
+
643
+ private async pull(): Promise<void> {
644
+ if (this.done) return;
645
+ if (this.signal?.aborted) throw this.signal.reason;
646
+ let result: ReadableStreamReadResult<Uint8Array>;
647
+ try {
648
+ result = await this.reader.read();
649
+ } catch (error) {
650
+ this.failed = true;
651
+ if (this.signal?.aborted) throw this.signal.reason;
652
+ throw new ProtocolError('Gzip archive decompression failed', { cause: error });
653
+ }
654
+ if (result.done) {
655
+ this.done = true;
656
+ this.chunk = new Uint8Array();
657
+ this.offset = 0;
658
+ return;
659
+ }
660
+ this.total = checkedAdd(
661
+ this.total,
662
+ result.value.byteLength,
663
+ 'Decompressed tar length overflow',
664
+ );
665
+ if (this.total > this.maximumBytes) {
666
+ throw new ProtocolError('Gzip archive exceeded its decompressed structural limit');
667
+ }
668
+ this.chunk = Uint8Array.from(result.value);
669
+ this.offset = 0;
670
+ }
671
+ }
672
+
673
+ const allZero = (value: Uint8Array): boolean => value.every((byte) => byte === 0);
674
+
675
+ const normalizeArchivePath = (value: string, type: string): string => {
676
+ const directory = type === '5';
677
+ const normalized = directory && value.endsWith('/') ? value.slice(0, -1) : value;
678
+ if (!directory && value.endsWith('/')) {
679
+ throw new ProtocolError('Tar non-directory entry has a trailing slash');
680
+ }
681
+ return pathSegments(normalized, maximumPathBytes, 'Tar archive').join('/');
682
+ };
683
+
684
+ const parseLinkTarget = (target: string): string[] => {
685
+ if (
686
+ !target ||
687
+ target.startsWith('/') ||
688
+ target.includes('\\') ||
689
+ target.includes('\0') ||
690
+ textEncoder.encode(target).byteLength > maximumPathBytes
691
+ ) {
692
+ throw new ProtocolError('Tar symlink target is unsafe');
693
+ }
694
+ const segments = target.split('/');
695
+ if (
696
+ segments.some((segment) =>
697
+ !segment || textEncoder.encode(segment).byteLength > maximumPathSegmentBytes
698
+ )
699
+ ) {
700
+ throw new ProtocolError('Tar symlink target is unsafe');
701
+ }
702
+ return segments;
703
+ };
704
+
705
+ const isComponentPrefix = (prefix: string[], value: string[]): boolean =>
706
+ prefix.length <= value.length && prefix.every((component, index) => component === value[index]);
707
+
708
+ const validateSymlinkSet = (symlinks: ISymlinkDescription[]): void => {
709
+ const byPath = new Map(symlinks.map((entry) => [entry.path, entry]));
710
+ const resolveTarget = (
711
+ base: string[],
712
+ target: string,
713
+ scope: string[],
714
+ active: Set<string>,
715
+ ): string[] => {
716
+ let current = [...base];
717
+ for (const segment of parseLinkTarget(target)) {
718
+ if (segment === '.') continue;
719
+ if (segment === '..') {
720
+ if (current.length <= scope.length) {
721
+ throw new ProtocolError('Tar symlink target escapes its collection root');
722
+ }
723
+ current.pop();
724
+ } else {
725
+ current.push(segment);
726
+ const linkedPath = current.join('/');
727
+ const linked = byPath.get(linkedPath);
728
+ if (linked) {
729
+ if (active.has(linkedPath)) throw new ProtocolError('Tar symlink chain is cyclic');
730
+ const nextActive = new Set(active);
731
+ nextActive.add(linkedPath);
732
+ current = resolveTarget(
733
+ linkedPath.split('/').slice(0, -1),
734
+ linked.target,
735
+ scope,
736
+ nextActive,
737
+ );
738
+ }
739
+ }
740
+ if (!isComponentPrefix(scope, current)) {
741
+ throw new ProtocolError('Tar symlink target escapes its collection root');
742
+ }
743
+ }
744
+ return current;
745
+ };
746
+ for (const symlink of symlinks) {
747
+ const active = new Set([symlink.path]);
748
+ resolveTarget(symlink.path.split('/').slice(0, -1), symlink.target, symlink.scope, active);
749
+ }
750
+ };
751
+
752
+ const assertArchiveStructure = (
753
+ seen: Map<string, TArchiveEntryType>,
754
+ path: string,
755
+ type: TArchiveEntryType,
756
+ ): void => {
757
+ if (seen.has(path)) throw new ProtocolError('Tar archive contains a duplicate path');
758
+ const segments = path.split('/');
759
+ for (let length = 1; length < segments.length; length++) {
760
+ const ancestor = seen.get(segments.slice(0, length).join('/'));
761
+ if (ancestor && ancestor !== 'directory') {
762
+ throw new ProtocolError('Tar archive contains entries below a non-directory');
763
+ }
764
+ }
765
+ if ([...seen.keys()].some((candidate) => candidate.startsWith(`${path}/`))) {
766
+ throw new ProtocolError('Tar archive declares an ancestor after its descendants');
767
+ }
768
+ seen.set(path, type);
769
+ };
770
+
771
+ const maximumTarStreamBytes = (maximumExtractedBytes: number, maximumEntries: number): number => {
772
+ const perEntryOverhead = maximumPaxHeaderBytes + tarBlockSize * 4;
773
+ return checkedAdd(
774
+ checkedAdd(
775
+ maximumExtractedBytes,
776
+ checkedMultiply(maximumEntries, perEntryOverhead, 'Tar structural limit overflow'),
777
+ 'Tar structural limit overflow',
778
+ ),
779
+ maximumPaxHeaderBytes + tarBlockSize * 4,
780
+ 'Tar structural limit overflow',
781
+ );
782
+ };
783
+
784
+ const assertEmptyDirectory = async (path: string): Promise<string> => {
785
+ const absolute = resolve(path);
786
+ const stat = await Deno.lstat(absolute).catch((error) => {
787
+ throw new RunnerError('Unable to inspect archive extraction root', { cause: error });
788
+ });
789
+ if (!stat.isDirectory || stat.isSymlink) {
790
+ throw new RunnerError('Archive extraction root must be a real directory');
791
+ }
792
+ for await (const _entry of Deno.readDir(absolute)) {
793
+ throw new RunnerError('Archive extraction root must be empty');
794
+ }
795
+ return absolute;
796
+ };
797
+
798
+ const parseTarGzip = async (
799
+ options: IExtractTarGzipOptions,
800
+ destination: string,
801
+ extract: boolean,
802
+ ): Promise<IWorkspaceTreeMetadata> => {
803
+ const allowedPaths = options.allowedPaths
804
+ ? validateRelativeSelections(options.allowedPaths, 'Cache declaration')
805
+ : undefined;
806
+ const archive = await Deno.open(options.archivePath, { read: true }).catch((error) => {
807
+ throw new RunnerError('Unable to open staged transfer archive', { cause: error });
808
+ });
809
+ let decompressed: ReadableStream<Uint8Array>;
810
+ try {
811
+ decompressed = archive.readable.pipeThrough(new DecompressionStream('gzip'));
812
+ } catch (error) {
813
+ try {
814
+ archive.close();
815
+ } catch (cleanupError) {
816
+ throw new ResourceCleanupError('Transfer archive setup cleanup failed', [
817
+ error,
818
+ cleanupError,
819
+ ]);
820
+ }
821
+ throw new ProtocolError('Transfer archive is not valid gzip data', { cause: error });
822
+ }
823
+ const bytes = new StreamBytes(
824
+ decompressed,
825
+ maximumTarStreamBytes(options.maximumExtractedBytes, options.maximumEntries),
826
+ options.signal,
827
+ );
828
+ const seen = new Map<string, TArchiveEntryType>();
829
+ const symlinks: ISymlinkDescription[] = [];
830
+ let localPax: { path?: string; linkpath?: string } | undefined;
831
+ let globalPaxSeen = false;
832
+ let logicalBytes = 0;
833
+ let entryCount = 0;
834
+ let complete = false;
835
+ let primaryError: unknown;
836
+ let result: IWorkspaceTreeMetadata | undefined;
837
+ try {
838
+ while (true) {
839
+ const header = await bytes.readExactly(tarBlockSize);
840
+ if (allZero(header)) {
841
+ const second = await bytes.readExactly(tarBlockSize);
842
+ if (!allZero(second)) throw new ProtocolError('Tar archive has an invalid terminator');
843
+ await bytes.consumeRemainder((value) => {
844
+ if (!allZero(value)) throw new ProtocolError('Tar archive contains trailing data');
845
+ });
846
+ break;
847
+ }
848
+ verifyTarChecksum(header);
849
+ const magic = decodeTarText(header.subarray(257, 263), 'magic');
850
+ const version = decodeTarText(header.subarray(263, 265), 'version');
851
+ if (magic !== 'ustar' || version !== '00') {
852
+ throw new ProtocolError('Tar archive is not in the supported USTAR format');
853
+ }
854
+ const mode = parseTarNumber(header.subarray(100, 108), 'mode');
855
+ if ((mode & ~0o777) !== 0) throw new ProtocolError('Tar entry mode contains unsafe bits');
856
+ parseTarNumber(header.subarray(108, 116), 'uid');
857
+ parseTarNumber(header.subarray(116, 124), 'gid');
858
+ const sizeBytes = parseTarNumber(header.subarray(124, 136), 'size');
859
+ parseTarNumber(header.subarray(136, 148), 'mtime');
860
+ parseTarNumber(header.subarray(329, 337), 'device major');
861
+ parseTarNumber(header.subarray(337, 345), 'device minor');
862
+ const typeByte = header[156];
863
+ const type = typeByte === 0 ? '0' : String.fromCharCode(typeByte);
864
+ const name = decodeTarText(header.subarray(0, 100), 'name');
865
+ const prefix = decodeTarText(header.subarray(345, 500), 'prefix');
866
+ const headerPath = prefix ? `${prefix}/${name}` : name;
867
+ const padding = (tarBlockSize - (sizeBytes % tarBlockSize)) % tarBlockSize;
868
+
869
+ if (type === 'x' || type === 'g') {
870
+ normalizeArchivePath(headerPath, '0');
871
+ if (sizeBytes > maximumPaxHeaderBytes) {
872
+ throw new ProtocolError('Tar PAX metadata exceeds the supported limit');
873
+ }
874
+ const content = await bytes.readExactly(sizeBytes);
875
+ if (padding) {
876
+ await bytes.consume(padding, (value) => {
877
+ if (!allZero(value)) throw new ProtocolError('Tar PAX padding is not zeroed');
878
+ });
879
+ }
880
+ const records = parsePaxRecords(content);
881
+ if (type === 'g') {
882
+ if (
883
+ globalPaxSeen ||
884
+ localPax ||
885
+ seen.size > 0 ||
886
+ records.size !== 1 ||
887
+ !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(records.get('comment') ?? '')
888
+ ) {
889
+ throw new ProtocolError('Tar global PAX metadata is unsupported');
890
+ }
891
+ globalPaxSeen = true;
892
+ } else {
893
+ if (localPax) throw new ProtocolError('Tar archive stacks local PAX metadata');
894
+ for (const key of records.keys()) {
895
+ if (key !== 'path' && key !== 'linkpath') {
896
+ throw new ProtocolError('Tar local PAX metadata is unsupported');
897
+ }
898
+ }
899
+ localPax = {
900
+ ...(records.has('path') ? { path: records.get('path')! } : {}),
901
+ ...(records.has('linkpath') ? { linkpath: records.get('linkpath')! } : {}),
902
+ };
903
+ }
904
+ continue;
905
+ }
906
+
907
+ if (type !== '0' && type !== '5' && type !== '2') {
908
+ throw new ProtocolError('Tar archive contains a hardlink, special, or unsupported entry');
909
+ }
910
+ entryCount = checkedAdd(entryCount, 1, 'Tar entry count overflow');
911
+ if (entryCount > options.maximumEntries) {
912
+ throw new ProtocolError('Tar archive exceeds the effective entry limit');
913
+ }
914
+ const entryPax = localPax;
915
+ localPax = undefined;
916
+ const path = normalizeArchivePath(entryPax?.path ?? headerPath, type);
917
+ const entryType: TArchiveEntryType = type === '5'
918
+ ? 'directory'
919
+ : type === '2'
920
+ ? 'symlink'
921
+ : 'file';
922
+ assertArchiveStructure(seen, path, entryType);
923
+ if (allowedPaths) {
924
+ const selected = allowedPaths.some((allowed) =>
925
+ path === allowed || path.startsWith(`${allowed}/`)
926
+ );
927
+ const requiredAncestor = entryType === 'directory' &&
928
+ allowedPaths.some((allowed) => allowed.startsWith(`${path}/`));
929
+ if (!selected && !requiredAncestor) {
930
+ throw new ProtocolError('Cache archive contains an undeclared path');
931
+ }
932
+ }
933
+ const target = join(destination, ...path.split('/'));
934
+
935
+ if (entryType === 'directory') {
936
+ if (sizeBytes !== 0 || entryPax?.linkpath !== undefined) {
937
+ throw new ProtocolError('Tar directory metadata is invalid');
938
+ }
939
+ if (extract) {
940
+ await Deno.mkdir(target, { recursive: true, mode: 0o700 });
941
+ await Deno.chmod(target, 0o700);
942
+ }
943
+ } else if (entryType === 'symlink') {
944
+ if (options.allowSymlinks === false) {
945
+ throw new ProtocolError('Cache archive contains a symbolic link');
946
+ }
947
+ if (sizeBytes !== 0) throw new ProtocolError('Tar symlink has a non-zero size');
948
+ const linkTarget = entryPax?.linkpath ??
949
+ decodeTarText(header.subarray(157, 257), 'link name');
950
+ parseLinkTarget(linkTarget);
951
+ symlinks.push({ path, target: linkTarget, scope: [] });
952
+ } else {
953
+ if (entryPax?.linkpath !== undefined) {
954
+ throw new ProtocolError('Tar regular file has link metadata');
955
+ }
956
+ logicalBytes = checkedAdd(logicalBytes, sizeBytes, 'Tar logical byte count overflow');
957
+ if (logicalBytes > options.maximumExtractedBytes) {
958
+ throw new ProtocolError('Tar archive exceeds the effective extracted byte limit');
959
+ }
960
+ let output: Deno.FsFile | undefined;
961
+ let entryError: unknown;
962
+ try {
963
+ if (extract) {
964
+ await Deno.mkdir(dirname(target), { recursive: true, mode: 0o700 });
965
+ output = await Deno.open(target, {
966
+ write: true,
967
+ createNew: true,
968
+ mode: (mode & 0o111) !== 0 ? 0o700 : 0o600,
969
+ });
970
+ }
971
+ await bytes.consume(sizeBytes, output ? (value) => writeAll(output!, value) : undefined);
972
+ } catch (error) {
973
+ entryError = error;
974
+ }
975
+ try {
976
+ output?.close();
977
+ } catch (cleanupError) {
978
+ throw new ResourceCleanupError(
979
+ 'Archive extraction file cleanup failed',
980
+ entryError === undefined ? [cleanupError] : [entryError, cleanupError],
981
+ );
982
+ }
983
+ if (entryError !== undefined) throw entryError;
984
+ if (extract) {
985
+ await Deno.chmod(target, (mode & 0o111) !== 0 ? 0o700 : 0o600);
986
+ }
987
+ }
988
+ if (padding) {
989
+ await bytes.consume(padding, (value) => {
990
+ if (!allZero(value)) throw new ProtocolError('Tar entry padding is not zeroed');
991
+ });
992
+ }
993
+ }
994
+ if (localPax) throw new ProtocolError('Tar archive ends with unused PAX metadata');
995
+ validateSymlinkSet(symlinks);
996
+ if (allowedPaths && options.requireAllowedPaths) {
997
+ for (const allowed of allowedPaths) {
998
+ if (!seen.has(allowed)) {
999
+ throw new ProtocolError('Cache archive omits a declared path');
1000
+ }
1001
+ }
1002
+ }
1003
+ if (
1004
+ logicalBytes !== options.expectedMetadata.extractedSizeBytes ||
1005
+ entryCount !== options.expectedMetadata.entryCount
1006
+ ) {
1007
+ throw new ProtocolError('Tar logical metadata did not match the transfer declaration');
1008
+ }
1009
+ if (extract) {
1010
+ for (const symlink of symlinks) {
1011
+ const target = join(destination, ...symlink.path.split('/'));
1012
+ await Deno.mkdir(dirname(target), { recursive: true, mode: 0o700 });
1013
+ await Deno.symlink(symlink.target, target);
1014
+ }
1015
+ }
1016
+ complete = true;
1017
+ result = { logicalBytes, entryCount };
1018
+ } catch (error) {
1019
+ primaryError = error;
1020
+ }
1021
+ let cleanupError: unknown;
1022
+ try {
1023
+ await bytes.close(!complete);
1024
+ } catch (error) {
1025
+ cleanupError = error;
1026
+ }
1027
+ if (primaryError !== undefined && cleanupError !== undefined) {
1028
+ throw new ResourceCleanupError(
1029
+ 'Archive parsing and stream cleanup failed',
1030
+ [primaryError, cleanupError],
1031
+ );
1032
+ }
1033
+ if (primaryError !== undefined) throw primaryError;
1034
+ if (cleanupError !== undefined) throw cleanupError;
1035
+ if (!result) throw new RunnerError('Archive parser completed without metadata');
1036
+ return result;
1037
+ };
1038
+
1039
+ export const extractTarGzipArchive = async (
1040
+ options: IExtractTarGzipOptions,
1041
+ ): Promise<IWorkspaceTreeMetadata> => {
1042
+ checkedInteger(options.maximumExtractedBytes, 'Maximum extracted bytes');
1043
+ checkedInteger(options.maximumEntries, 'Maximum archive entries');
1044
+ if (
1045
+ options.expectedMetadata.extractedSizeBytes > options.maximumExtractedBytes ||
1046
+ options.expectedMetadata.entryCount > options.maximumEntries
1047
+ ) {
1048
+ throw new ProtocolError('Transfer metadata exceeds the effective extraction limits');
1049
+ }
1050
+ const destination = await assertEmptyDirectory(options.destinationPath);
1051
+ await parseTarGzip(options, destination, false);
1052
+ return await parseTarGzip(options, destination, true);
1053
+ };
1054
+
1055
+ const snapshotFor = (
1056
+ stat: Deno.FileInfo,
1057
+ type: TArchiveEntryType,
1058
+ label: string,
1059
+ ): IFileSnapshot => {
1060
+ if (
1061
+ stat.dev === null ||
1062
+ stat.ino === null ||
1063
+ stat.nlink === null ||
1064
+ stat.mode === null ||
1065
+ stat.size === null
1066
+ ) {
1067
+ throw new RunnerError(`${label} does not expose stable filesystem metadata`);
1068
+ }
1069
+ return {
1070
+ type,
1071
+ dev: stat.dev,
1072
+ ino: stat.ino,
1073
+ nlink: stat.nlink,
1074
+ size: stat.size,
1075
+ mode: stat.mode,
1076
+ mtime: stat.mtime?.getTime() ?? null,
1077
+ };
1078
+ };
1079
+
1080
+ const typeForStat = (stat: Deno.FileInfo): TArchiveEntryType => {
1081
+ if (stat.isDirectory) return 'directory';
1082
+ if (stat.isFile) return 'file';
1083
+ if (stat.isSymlink) return 'symlink';
1084
+ throw new RunnerError('Workspace export contains a special filesystem entry');
1085
+ };
1086
+
1087
+ const assertSnapshot = async (path: string, expected: IFileSnapshot): Promise<void> => {
1088
+ const stat = await Deno.lstat(path).catch((error) => {
1089
+ throw new RunnerError('Workspace export changed during archive creation', { cause: error });
1090
+ });
1091
+ const current = snapshotFor(stat, typeForStat(stat), 'Workspace export entry');
1092
+ if (
1093
+ current.type !== expected.type ||
1094
+ current.dev !== expected.dev ||
1095
+ current.ino !== expected.ino ||
1096
+ current.nlink !== expected.nlink ||
1097
+ current.size !== expected.size ||
1098
+ current.mode !== expected.mode ||
1099
+ current.mtime !== expected.mtime
1100
+ ) {
1101
+ throw new RunnerError('Workspace export changed during archive creation');
1102
+ }
1103
+ };
1104
+
1105
+ const selectedMembership = (
1106
+ path: string,
1107
+ type: TArchiveEntryType,
1108
+ selections: string[],
1109
+ ): { accepted: boolean; scope: string[] } => {
1110
+ const selected = selections.find((candidate) =>
1111
+ path === candidate || path.startsWith(`${candidate}/`)
1112
+ );
1113
+ if (selected) {
1114
+ return {
1115
+ accepted: true,
1116
+ scope: path === selected ? selected.split('/').slice(0, -1) : selected.split('/'),
1117
+ };
1118
+ }
1119
+ return {
1120
+ accepted: type === 'directory' &&
1121
+ selections.some((candidate) => candidate.startsWith(`${path}/`)),
1122
+ scope: [],
1123
+ };
1124
+ };
1125
+
1126
+ const collectArchiveEntries = async (
1127
+ options: ICreateTarGzipOptions,
1128
+ ): Promise<{ entries: IArchiveEntry[]; root: string; rootSnapshot: IFileSnapshot }> => {
1129
+ const selections = validateRelativeSelections(options.selections, 'Workspace export selection');
1130
+ const root = await Deno.realPath(options.sourcePath).catch((error) => {
1131
+ throw new RunnerError('Unable to resolve workspace export root', { cause: error });
1132
+ });
1133
+ const rootStat = await Deno.lstat(root);
1134
+ if (!rootStat.isDirectory || rootStat.isSymlink) {
1135
+ throw new RunnerError('Workspace export root must be a real directory');
1136
+ }
1137
+ const rootSnapshot = snapshotFor(rootStat, 'directory', 'Workspace export root');
1138
+ const entries: IArchiveEntry[] = [];
1139
+ const present = new Set<string>();
1140
+ let logicalBytes = 0;
1141
+ const visit = async (path: string): Promise<void> => {
1142
+ if (options.signal?.aborted) throw options.signal.reason;
1143
+ pathSegments(path, maximumPathBytes, 'Workspace export');
1144
+ const absolutePath = join(root, ...path.split('/'));
1145
+ const stat = await Deno.lstat(absolutePath);
1146
+ const type = typeForStat(stat);
1147
+ const membership = selectedMembership(path, type, selections);
1148
+ if (!membership.accepted) {
1149
+ throw new RunnerError('Workspace exporter returned an undeclared path');
1150
+ }
1151
+ const snapshot = snapshotFor(stat, type, 'Workspace export entry');
1152
+ if (snapshot.dev !== rootSnapshot.dev) {
1153
+ throw new RunnerError('Workspace export crosses a filesystem boundary');
1154
+ }
1155
+ if (type === 'file' && snapshot.nlink !== 1) {
1156
+ throw new RunnerError('Workspace export contains a hardlinked regular file');
1157
+ }
1158
+ if (type === 'symlink' && !options.allowSymlinks) {
1159
+ throw new RunnerError('Workspace export contains a symbolic link');
1160
+ }
1161
+ let linkTarget: string | undefined;
1162
+ if (type === 'symlink') {
1163
+ linkTarget = await Deno.readLink(absolutePath);
1164
+ parseLinkTarget(linkTarget);
1165
+ }
1166
+ const sizeBytes = type === 'file' ? snapshot.size : 0;
1167
+ logicalBytes = checkedAdd(logicalBytes, sizeBytes, 'Workspace export byte count overflow');
1168
+ if (logicalBytes > options.maximumExtractedBytes) {
1169
+ throw new ProtocolError('Workspace export exceeds the effective extracted byte limit');
1170
+ }
1171
+ entries.push({
1172
+ path,
1173
+ absolutePath,
1174
+ type,
1175
+ sizeBytes,
1176
+ executable: type === 'file' && (snapshot.mode & 0o111) !== 0,
1177
+ ...(linkTarget === undefined ? {} : { linkTarget }),
1178
+ symlinkScope: membership.scope,
1179
+ snapshot,
1180
+ });
1181
+ present.add(path);
1182
+ if (entries.length > options.maximumEntries) {
1183
+ throw new ProtocolError('Workspace export exceeds the effective entry limit');
1184
+ }
1185
+ if (type === 'directory') {
1186
+ const children: string[] = [];
1187
+ for await (const child of Deno.readDir(absolutePath)) children.push(child.name);
1188
+ children.sort(compareUtf8);
1189
+ for (const child of children) await visit(`${path}/${child}`);
1190
+ await assertSnapshot(absolutePath, snapshot);
1191
+ }
1192
+ };
1193
+ const roots: string[] = [];
1194
+ for await (const entry of Deno.readDir(root)) roots.push(entry.name);
1195
+ roots.sort(compareUtf8);
1196
+ for (const path of roots) await visit(path);
1197
+ entries.sort((left, right) => compareUtf8(left.path, right.path));
1198
+ if (options.requireAllSelections !== false) {
1199
+ for (const selection of selections) {
1200
+ if (!present.has(selection)) throw new RunnerError('Workspace export omits a selected path');
1201
+ }
1202
+ }
1203
+ if (
1204
+ logicalBytes !== options.expectedMetadata.logicalBytes ||
1205
+ entries.length !== options.expectedMetadata.entryCount
1206
+ ) {
1207
+ throw new ProtocolError('Workspace exporter returned mismatched tree metadata');
1208
+ }
1209
+ validateSymlinkSet(
1210
+ entries.filter((entry) => entry.type === 'symlink').map((entry) => ({
1211
+ path: entry.path,
1212
+ target: entry.linkTarget!,
1213
+ scope: entry.symlinkScope,
1214
+ })),
1215
+ );
1216
+ await assertSnapshot(root, rootSnapshot);
1217
+ return { entries, root, rootSnapshot };
1218
+ };
1219
+
1220
+ const writeAscii = (target: Uint8Array, offset: number, length: number, value: string): void => {
1221
+ const bytes = textEncoder.encode(value);
1222
+ if (bytes.byteLength > length || bytes.some((byte) => byte > 0x7f)) {
1223
+ throw new RunnerError('Tar header text exceeds its field');
1224
+ }
1225
+ target.set(bytes, offset);
1226
+ };
1227
+
1228
+ const writeTarNumber = (
1229
+ target: Uint8Array,
1230
+ offset: number,
1231
+ length: number,
1232
+ value: number,
1233
+ ): void => {
1234
+ checkedInteger(value, 'Tar numeric value');
1235
+ const octal = value.toString(8);
1236
+ if (octal.length <= length - 1) {
1237
+ writeAscii(target, offset, length, octal.padStart(length - 1, '0') + '\0');
1238
+ return;
1239
+ }
1240
+ let remaining = BigInt(value);
1241
+ for (let index = offset + length - 1; index > offset; index--) {
1242
+ target[index] = Number(remaining & 0xffn);
1243
+ remaining >>= 8n;
1244
+ }
1245
+ if (remaining > 0x3fn) throw new RunnerError('Tar numeric value exceeds its field');
1246
+ target[offset] = Number(remaining) | 0x80;
1247
+ };
1248
+
1249
+ const ustarPath = (path: string): { name: string; prefix: string } | undefined => {
1250
+ const bytes = textEncoder.encode(path);
1251
+ if (bytes.some((byte) => byte > 0x7f)) return undefined;
1252
+ if (bytes.byteLength <= 100) return { name: path, prefix: '' };
1253
+ const separators = [...path.matchAll(/\//g)].map((match) => match.index!);
1254
+ for (let index = separators.length - 1; index >= 0; index--) {
1255
+ const split = separators[index];
1256
+ const prefix = path.slice(0, split);
1257
+ const name = path.slice(split + 1);
1258
+ if (
1259
+ textEncoder.encode(prefix).byteLength <= 155 && textEncoder.encode(name).byteLength <= 100
1260
+ ) {
1261
+ return { name, prefix };
1262
+ }
1263
+ }
1264
+ return undefined;
1265
+ };
1266
+
1267
+ const tarHeader = (
1268
+ path: { name: string; prefix: string },
1269
+ type: '0' | '2' | '5' | 'x',
1270
+ sizeBytes: number,
1271
+ executable = false,
1272
+ linkTarget = '',
1273
+ ): Uint8Array => {
1274
+ const header = new Uint8Array(tarBlockSize);
1275
+ writeAscii(header, 0, 100, path.name);
1276
+ writeTarNumber(header, 100, 8, type === '5' || executable ? 0o755 : 0o644);
1277
+ writeTarNumber(header, 108, 8, 0);
1278
+ writeTarNumber(header, 116, 8, 0);
1279
+ writeTarNumber(header, 124, 12, sizeBytes);
1280
+ writeTarNumber(header, 136, 12, 0);
1281
+ header.fill(32, 148, 156);
1282
+ header[156] = type.charCodeAt(0);
1283
+ writeAscii(header, 157, 100, linkTarget);
1284
+ writeAscii(header, 257, 6, 'ustar\0');
1285
+ writeAscii(header, 263, 2, '00');
1286
+ writeTarNumber(header, 329, 8, 0);
1287
+ writeTarNumber(header, 337, 8, 0);
1288
+ writeAscii(header, 345, 155, path.prefix);
1289
+ let checksum = 0;
1290
+ for (const byte of header) checksum += byte;
1291
+ writeAscii(header, 148, 8, checksum.toString(8).padStart(6, '0') + '\0 ');
1292
+ return header;
1293
+ };
1294
+
1295
+ const paxRecord = (key: string, value: string): string => {
1296
+ let length = textEncoder.encode(`0 ${key}=${value}\n`).byteLength;
1297
+ while (true) {
1298
+ const record = `${length} ${key}=${value}\n`;
1299
+ const actual = textEncoder.encode(record).byteLength;
1300
+ if (actual === length) return record;
1301
+ length = actual;
1302
+ }
1303
+ };
1304
+
1305
+ const paddingFor = (sizeBytes: number): Uint8Array =>
1306
+ new Uint8Array((tarBlockSize - (sizeBytes % tarBlockSize)) % tarBlockSize);
1307
+
1308
+ const assertSafeAncestors = async (root: string, path: string, device: number): Promise<void> => {
1309
+ const segments = path.split('/').slice(0, -1);
1310
+ let current = root;
1311
+ for (const segment of segments) {
1312
+ current = join(current, segment);
1313
+ const stat = await Deno.lstat(current);
1314
+ if (!stat.isDirectory || stat.isSymlink || stat.dev !== device) {
1315
+ throw new RunnerError('Workspace export path changed or crossed a boundary');
1316
+ }
1317
+ }
1318
+ };
1319
+
1320
+ const assertOpenFileSnapshot = async (
1321
+ file: Deno.FsFile,
1322
+ expected: IFileSnapshot,
1323
+ ): Promise<void> => {
1324
+ const stat = await file.stat();
1325
+ const current = snapshotFor(stat, typeForStat(stat), 'Open workspace export file');
1326
+ if (
1327
+ current.type !== 'file' ||
1328
+ current.dev !== expected.dev ||
1329
+ current.ino !== expected.ino ||
1330
+ current.nlink !== 1 ||
1331
+ current.size !== expected.size ||
1332
+ current.mode !== expected.mode ||
1333
+ current.mtime !== expected.mtime
1334
+ ) {
1335
+ throw new RunnerError('Workspace export file changed during archive creation');
1336
+ }
1337
+ };
1338
+
1339
+ async function* tarChunks(
1340
+ entries: IArchiveEntry[],
1341
+ root: string,
1342
+ rootDevice: number,
1343
+ signal?: AbortSignal,
1344
+ ): AsyncGenerator<Uint8Array> {
1345
+ let index = 0;
1346
+ for (const entry of entries) {
1347
+ if (signal?.aborted) throw signal.reason;
1348
+ await assertSafeAncestors(root, entry.path, rootDevice);
1349
+ await assertSnapshot(entry.absolutePath, entry.snapshot);
1350
+ const paxValues: Array<[string, string]> = [];
1351
+ let pathField = ustarPath(entry.path);
1352
+ if (!pathField) {
1353
+ paxValues.push(['path', entry.path]);
1354
+ pathField = { name: `entry-${index}`, prefix: '' };
1355
+ }
1356
+ let linkField = entry.linkTarget ?? '';
1357
+ if (linkField && (!ustarPath(linkField) || textEncoder.encode(linkField).byteLength > 100)) {
1358
+ paxValues.push(['linkpath', linkField]);
1359
+ linkField = `link-${index}`;
1360
+ }
1361
+ if (paxValues.length) {
1362
+ const content = textEncoder.encode(
1363
+ paxValues.sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)
1364
+ .map(([key, value]) => paxRecord(key, value)).join(''),
1365
+ );
1366
+ if (content.byteLength > maximumPaxHeaderBytes) {
1367
+ throw new RunnerError('Workspace export path metadata is too large');
1368
+ }
1369
+ yield tarHeader({ name: `PaxHeaders/${index}`, prefix: '' }, 'x', content.byteLength);
1370
+ yield content;
1371
+ const paxPadding = paddingFor(content.byteLength);
1372
+ if (paxPadding.byteLength) yield paxPadding;
1373
+ }
1374
+ const type = entry.type === 'directory' ? '5' : entry.type === 'symlink' ? '2' : '0';
1375
+ yield tarHeader(pathField, type, entry.sizeBytes, entry.executable, linkField);
1376
+ if (entry.type === 'file') {
1377
+ const file = await Deno.open(entry.absolutePath, { read: true });
1378
+ let fileError: unknown;
1379
+ try {
1380
+ await assertOpenFileSnapshot(file, entry.snapshot);
1381
+ const buffer = new Uint8Array(streamBufferBytes);
1382
+ let emitted = 0;
1383
+ while (true) {
1384
+ if (signal?.aborted) throw signal.reason;
1385
+ const read = await file.read(buffer);
1386
+ if (read === null) break;
1387
+ emitted = checkedAdd(emitted, read, 'Workspace export file length overflow');
1388
+ if (emitted > entry.sizeBytes) {
1389
+ throw new RunnerError('Workspace export file grew during archive creation');
1390
+ }
1391
+ yield buffer.slice(0, read);
1392
+ }
1393
+ if (emitted !== entry.sizeBytes) {
1394
+ throw new RunnerError('Workspace export file shrank during archive creation');
1395
+ }
1396
+ await assertOpenFileSnapshot(file, entry.snapshot);
1397
+ } catch (error) {
1398
+ fileError = error;
1399
+ }
1400
+ try {
1401
+ file.close();
1402
+ } catch (cleanupError) {
1403
+ throw new ResourceCleanupError(
1404
+ 'Workspace export file cleanup failed',
1405
+ fileError === undefined ? [cleanupError] : [fileError, cleanupError],
1406
+ );
1407
+ }
1408
+ if (fileError !== undefined) throw fileError;
1409
+ await assertSnapshot(entry.absolutePath, entry.snapshot);
1410
+ const padding = paddingFor(entry.sizeBytes);
1411
+ if (padding.byteLength) yield padding;
1412
+ } else if (entry.type === 'symlink') {
1413
+ if (await Deno.readLink(entry.absolutePath) !== entry.linkTarget) {
1414
+ throw new RunnerError('Workspace export symlink changed during archive creation');
1415
+ }
1416
+ }
1417
+ index++;
1418
+ }
1419
+ yield zeroBlock;
1420
+ yield zeroBlock;
1421
+ }
1422
+
1423
+ const iteratorStream = (iterator: AsyncGenerator<Uint8Array>): ReadableStream<Uint8Array> =>
1424
+ new ReadableStream<Uint8Array>({
1425
+ async pull(controller) {
1426
+ const result = await iterator.next();
1427
+ if (result.done) controller.close();
1428
+ else controller.enqueue(result.value);
1429
+ },
1430
+ async cancel() {
1431
+ await iterator.return(undefined);
1432
+ },
1433
+ });
1434
+
1435
+ export const createTarGzipArchive = async (
1436
+ options: ICreateTarGzipOptions,
1437
+ ): Promise<IPreparedTransferArchive> => {
1438
+ checkedInteger(options.maximumArchiveBytes, 'Maximum archive bytes', false);
1439
+ checkedInteger(options.maximumExtractedBytes, 'Maximum extracted bytes');
1440
+ checkedInteger(options.maximumEntries, 'Maximum archive entries', false);
1441
+ checkedInteger(options.expectedMetadata.logicalBytes, 'Workspace export logical bytes');
1442
+ checkedInteger(options.expectedMetadata.entryCount, 'Workspace export entry count');
1443
+ const collected = await collectArchiveEntries(options);
1444
+ await Deno.mkdir(options.archiveDirectory, { recursive: true, mode: 0o700 });
1445
+ const fileOperations = options.fileOperations ?? defaultFileOperations;
1446
+ const path = await fileOperations.makeTempFile({
1447
+ dir: options.archiveDirectory,
1448
+ prefix: options.archivePrefix,
1449
+ suffix: '.tar.gz',
1450
+ });
1451
+ const cleanup = cleanupForPath(path, false, fileOperations.remove);
1452
+ try {
1453
+ await fileOperations.chmod(path, 0o600);
1454
+ } catch (error) {
1455
+ try {
1456
+ await cleanup();
1457
+ } catch (cleanupError) {
1458
+ throw new ResourceCleanupError(
1459
+ 'Archive setup and cleanup failed',
1460
+ [error, cleanupError],
1461
+ );
1462
+ }
1463
+ throw error;
1464
+ }
1465
+ const digest = createHash('sha256');
1466
+ let sizeBytes = 0;
1467
+ let output: Deno.FsFile | undefined;
1468
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
1469
+ let archiveSnapshot: IFileSnapshot | undefined;
1470
+ try {
1471
+ output = await Deno.open(path, { write: true, truncate: true });
1472
+ const compressor = new CompressionStream('gzip') as unknown as TransformStream<
1473
+ Uint8Array,
1474
+ Uint8Array
1475
+ >;
1476
+ const compressed = iteratorStream(
1477
+ tarChunks(collected.entries, collected.root, collected.rootSnapshot.dev, options.signal),
1478
+ ).pipeThrough(compressor);
1479
+ reader = compressed.getReader();
1480
+ while (true) {
1481
+ if (options.signal?.aborted) throw options.signal.reason;
1482
+ const { done, value } = await reader.read();
1483
+ if (done) break;
1484
+ sizeBytes = checkedAdd(sizeBytes, value.byteLength, 'Archive size overflow');
1485
+ if (sizeBytes > options.maximumArchiveBytes) {
1486
+ throw new RunnerError('Archive exceeds the effective compressed byte limit');
1487
+ }
1488
+ digest.update(value);
1489
+ await writeAll(output, value);
1490
+ }
1491
+ await assertSnapshot(collected.root, collected.rootSnapshot);
1492
+ for (const entry of collected.entries) await assertSnapshot(entry.absolutePath, entry.snapshot);
1493
+ archiveSnapshot = snapshotFor(
1494
+ await Deno.lstat(path),
1495
+ 'file',
1496
+ 'Prepared transfer archive',
1497
+ );
1498
+ } catch (error) {
1499
+ const errors = [error];
1500
+ try {
1501
+ await reader?.cancel(error);
1502
+ } catch (cleanupError) {
1503
+ errors.push(cleanupError);
1504
+ }
1505
+ try {
1506
+ reader?.releaseLock();
1507
+ } catch (cleanupError) {
1508
+ errors.push(cleanupError);
1509
+ }
1510
+ try {
1511
+ output?.close();
1512
+ } catch (cleanupError) {
1513
+ errors.push(cleanupError);
1514
+ }
1515
+ try {
1516
+ await cleanup();
1517
+ } catch (cleanupError) {
1518
+ errors.push(cleanupError);
1519
+ }
1520
+ if (errors.length > 1) {
1521
+ throw new ResourceCleanupError('Archive creation and cleanup failed', errors);
1522
+ }
1523
+ throw error;
1524
+ }
1525
+ const streamCleanupErrors: unknown[] = [];
1526
+ try {
1527
+ reader.releaseLock();
1528
+ } catch (error) {
1529
+ streamCleanupErrors.push(error);
1530
+ }
1531
+ try {
1532
+ output.close();
1533
+ } catch (error) {
1534
+ streamCleanupErrors.push(error);
1535
+ }
1536
+ if (streamCleanupErrors.length > 0) {
1537
+ try {
1538
+ await cleanup();
1539
+ } catch (cleanupError) {
1540
+ streamCleanupErrors.push(cleanupError);
1541
+ }
1542
+ throw new ResourceCleanupError('Archive stream cleanup failed', streamCleanupErrors);
1543
+ }
1544
+ if (!archiveSnapshot) {
1545
+ const error = new RunnerError('Prepared transfer archive snapshot was not created');
1546
+ try {
1547
+ await cleanup();
1548
+ } catch (cleanupError) {
1549
+ throw new ResourceCleanupError('Archive setup and cleanup failed', [error, cleanupError]);
1550
+ }
1551
+ throw error;
1552
+ }
1553
+ const metadata: ITransferMetadata = {
1554
+ sha256: digest.digest('hex'),
1555
+ sizeBytes,
1556
+ extractedSizeBytes: options.expectedMetadata.logicalBytes,
1557
+ entryCount: options.expectedMetadata.entryCount,
1558
+ };
1559
+ return {
1560
+ path,
1561
+ metadata,
1562
+ openBody: async () => {
1563
+ await assertSnapshot(path, archiveSnapshot);
1564
+ return (await Deno.open(path, { read: true })).readable;
1565
+ },
1566
+ cleanup,
1567
+ };
1568
+ };
1569
+
1570
+ const validTimestamp = (value: string): boolean => {
1571
+ const match =
1572
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/.exec(
1573
+ value,
1574
+ );
1575
+ if (!match || !Number.isFinite(Date.parse(value))) return false;
1576
+ const year = Number(match[1]);
1577
+ const month = Number(match[2]);
1578
+ const day = Number(match[3]);
1579
+ const hour = Number(match[4]);
1580
+ const minute = Number(match[5]);
1581
+ const second = Number(match[6]);
1582
+ const offsetHour = match[7] === undefined ? 0 : Number(match[7]);
1583
+ const offsetMinute = match[8] === undefined ? 0 : Number(match[8]);
1584
+ return month >= 1 && month <= 12 && day >= 1 &&
1585
+ day <= new Date(Date.UTC(year, month, 0)).getUTCDate() && hour <= 23 && minute <= 59 &&
1586
+ second <= 59 && offsetHour <= 23 && offsetMinute <= 59;
1587
+ };
1588
+
1589
+ export const validateTransferRecord = (
1590
+ record: ITransferRecord,
1591
+ name: string,
1592
+ metadata: ITransferMetadata,
1593
+ ): void => {
1594
+ if (
1595
+ record.name !== name ||
1596
+ record.format !== 'tar.gz' ||
1597
+ record.sha256 !== metadata.sha256 ||
1598
+ record.sizeBytes !== metadata.sizeBytes ||
1599
+ record.extractedSizeBytes !== metadata.extractedSizeBytes ||
1600
+ record.entryCount !== metadata.entryCount ||
1601
+ !validTimestamp(record.createdAt)
1602
+ ) {
1603
+ throw new ProtocolError('Coordinator returned a mismatched transfer record');
1604
+ }
1605
+ };