@ship.zone/runner 3.0.0 → 5.0.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.
Files changed (80) hide show
  1. package/.smartconfig.json +19 -1
  2. package/changelog.md +61 -0
  3. package/dist_rust/runnerworkspace_linux_amd64_musl +0 -0
  4. package/dist_rust/runnerworkspace_linux_amd64_musl.tsrust-build.json +4 -4
  5. package/dist_rust/runnerworkspace_linux_arm64_musl +0 -0
  6. package/dist_rust/runnerworkspace_linux_arm64_musl.tsrust-build.json +4 -4
  7. package/dist_ts/00_commitinfo_data.js +3 -3
  8. package/dist_ts/api-client.d.ts +2 -1
  9. package/dist_ts/api-client.js +10 -2
  10. package/dist_ts/artifact-manager.js +1 -1
  11. package/dist_ts/attempt-state.js +1 -1
  12. package/dist_ts/cache-manager.js +1 -1
  13. package/dist_ts/cli-entry.js +17 -3
  14. package/dist_ts/cli.d.ts +7 -0
  15. package/dist_ts/cli.js +155 -35
  16. package/dist_ts/config.js +75 -22
  17. package/dist_ts/egress-proxy.d.ts +99 -0
  18. package/dist_ts/egress-proxy.js +607 -0
  19. package/dist_ts/errors.js +1 -1
  20. package/dist_ts/filesystem.js +1 -1
  21. package/dist_ts/index.d.ts +5 -1
  22. package/dist_ts/index.js +6 -2
  23. package/dist_ts/interfaces.d.ts +85 -31
  24. package/dist_ts/interfaces.js +1 -1
  25. package/dist_ts/log-sender.js +1 -1
  26. package/dist_ts/microvm-executor.d.ts +90 -0
  27. package/dist_ts/microvm-executor.js +1078 -0
  28. package/dist_ts/node-version.d.ts +11 -0
  29. package/dist_ts/node-version.js +43 -0
  30. package/dist_ts/npm-grants.d.ts +9 -0
  31. package/dist_ts/npm-grants.js +44 -0
  32. package/dist_ts/oci-registry.d.ts +73 -0
  33. package/dist_ts/oci-registry.js +508 -0
  34. package/dist_ts/plugins.d.ts +6 -2
  35. package/dist_ts/plugins.js +7 -3
  36. package/dist_ts/protocol-validator.d.ts +3 -5
  37. package/dist_ts/protocol-validator.js +27 -51
  38. package/dist_ts/redactor.js +1 -1
  39. package/dist_ts/registration-state.js +1 -1
  40. package/dist_ts/runner.d.ts +5 -5
  41. package/dist_ts/runner.js +47 -22
  42. package/dist_ts/source-workspace.js +1 -1
  43. package/dist_ts/spec-version.js +1 -1
  44. package/dist_ts/staging-scavenger.js +1 -1
  45. package/dist_ts/state-owner.js +4 -2
  46. package/dist_ts/transfer-archive.js +1 -1
  47. package/dist_ts/validation.js +1 -1
  48. package/dist_ts/vsock-protocol.d.ts +130 -0
  49. package/dist_ts/vsock-protocol.js +336 -0
  50. package/dist_ts/wire-schema.js +1 -1
  51. package/package.json +19 -15
  52. package/readme.md +106 -108
  53. package/rust/Cargo.lock +1 -0
  54. package/rust/Cargo.toml +2 -1
  55. package/rust/src/cpio.rs +147 -0
  56. package/rust/src/extfs.rs +747 -0
  57. package/rust/src/guest.rs +2411 -0
  58. package/rust/src/lib.rs +41 -0
  59. package/rust/src/main.rs +6 -1
  60. package/rust/src/oci_tar.rs +842 -0
  61. package/ts/00_commitinfo_data.ts +2 -2
  62. package/ts/api-client.ts +19 -1
  63. package/ts/cli-entry.ts +15 -2
  64. package/ts/cli.ts +172 -40
  65. package/ts/config.ts +100 -25
  66. package/ts/egress-proxy.ts +649 -0
  67. package/ts/index.ts +5 -1
  68. package/ts/interfaces.ts +97 -30
  69. package/ts/microvm-executor.ts +1310 -0
  70. package/ts/node-version.ts +49 -0
  71. package/ts/npm-grants.ts +49 -0
  72. package/ts/oci-registry.ts +649 -0
  73. package/ts/plugins.ts +6 -2
  74. package/ts/protocol-validator.ts +29 -58
  75. package/ts/runner.ts +48 -21
  76. package/ts/state-owner.ts +8 -1
  77. package/ts/vsock-protocol.ts +437 -0
  78. package/dist_ts/oci-executor.d.ts +0 -155
  79. package/dist_ts/oci-executor.js +0 -2238
  80. package/ts/oci-executor.ts +0 -2989
@@ -0,0 +1,649 @@
1
+ import * as plugins from './plugins.js';
2
+ import { ProtocolError, RunnerError } from './errors.js';
3
+ import { isNotFound, makeTempDir, removePath, sha256Hex } from './filesystem.js';
4
+ import type { IImageBinding, IImageGrant, TImageReference, TOciArchitecture } from './interfaces.js';
5
+
6
+ const { join } = plugins.path;
7
+
8
+ const digestPattern = /^sha256:([a-f0-9]{64})$/;
9
+ const manifestAcceptHeader = [
10
+ 'application/vnd.oci.image.index.v1+json',
11
+ 'application/vnd.docker.distribution.manifest.list.v2+json',
12
+ 'application/vnd.oci.image.manifest.v1+json',
13
+ 'application/vnd.docker.distribution.manifest.v2+json',
14
+ ].join(', ');
15
+
16
+ const maximumManifestBytes = 4 * 1024 * 1024;
17
+ const maximumConfigBytes = 4 * 1024 * 1024;
18
+ const maximumLayerBlobBytes = 2 * 1024 * 1024 * 1024;
19
+
20
+ export interface IParsedImageReference {
21
+ readonly raw: string;
22
+ readonly registry: string;
23
+ readonly repository: string;
24
+ /** Exact literal registry segment before the first `/` (undefined if hostless). */
25
+ readonly exactRegistry?: string;
26
+ /** Exact literal repository segment between the first `/` and `@` (undefined if hostless). */
27
+ readonly exactRepository?: string;
28
+ readonly digest: string;
29
+ readonly digestHex: string;
30
+ }
31
+
32
+ export interface IMaterializedOciImage {
33
+ readonly image: string;
34
+ readonly manifestDigest: string;
35
+ readonly os: 'linux';
36
+ readonly architecture: TOciArchitecture;
37
+ readonly rootfsPath: string;
38
+ readonly rootfsSha256: string;
39
+ readonly rootfsSizeBytes: number;
40
+ readonly defaultEnv: Record<string, string>;
41
+ readonly defaultWorkingDir?: string;
42
+ /** True when pulled with a lease pull grant into an attempt-private store. */
43
+ readonly attemptPrivate: boolean;
44
+ /** Removes the attempt-private store when `attemptPrivate` is true; no-op for shared cache. */
45
+ cleanup(): Promise<void>;
46
+ }
47
+
48
+ export interface IOciRegistryClientOptions {
49
+ readonly cacheDirectory: string;
50
+ readonly helperPath: string;
51
+ readonly allowInsecureLoopback: boolean;
52
+ readonly requestTimeoutMs: number;
53
+ readonly maximumRootfsBytes: number;
54
+ readonly fetchImplementation?: typeof fetch;
55
+ readonly buildRootfs?: (options: {
56
+ helperPath: string;
57
+ layerPaths: string[];
58
+ outputPath: string;
59
+ maximumBytes: number;
60
+ signal?: AbortSignal;
61
+ }) => Promise<void>;
62
+ }
63
+
64
+ const isLoopbackHost = (registry: string): boolean => {
65
+ const lowered = registry.toLowerCase();
66
+ const host = lowered.startsWith('[')
67
+ ? lowered.slice(1, lowered.indexOf(']'))
68
+ : lowered.split(':')[0];
69
+ return host === 'localhost' || host === '127.0.0.1' || host === '::1';
70
+ };
71
+
72
+ /**
73
+ * Resolves a job's `TImageReference` (either a digest-pinned string or `{ candidate }`) using the
74
+ * lease's `bindings`.
75
+ */
76
+ export const resolveImageReference = (
77
+ imageRef: TImageReference,
78
+ bindings: readonly IImageBinding[],
79
+ ): string => {
80
+ if (typeof imageRef === 'string') return imageRef;
81
+ const binding = bindings.find((entry) => entry.candidate === imageRef.candidate);
82
+ if (!binding) {
83
+ throw new ProtocolError(`No lease binding found for candidate image ${imageRef.candidate}`);
84
+ }
85
+ return binding.image;
86
+ };
87
+
88
+ /**
89
+ * Parses a digest-pinned OCI/Docker image reference (`<name>@sha256:<64 hex>`).
90
+ * Rejects mutable tags without a digest.
91
+ */
92
+ export const parseDigestPinnedImageReference = (image: string): IParsedImageReference => {
93
+ const atIndex = image.indexOf('@');
94
+ if (atIndex <= 0 || image.indexOf('@', atIndex + 1) >= 0) {
95
+ throw new ProtocolError('Job image must be pinned by an exact sha256 digest');
96
+ }
97
+ const namePart = image.slice(0, atIndex);
98
+ const digestPart = image.slice(atIndex + 1);
99
+ const match = digestPattern.exec(digestPart);
100
+ if (!match) {
101
+ throw new ProtocolError('Job image must use a lowercase sha256 digest');
102
+ }
103
+
104
+ // Exact registry/repository extraction per ci-spec Image Grants (text before first `/` and
105
+ // text between first `/` and `@`, with NO default registry or case folding).
106
+ const firstSlashRaw = namePart.indexOf('/');
107
+ const exactRegistry = firstSlashRaw > 0 ? namePart.slice(0, firstSlashRaw) : undefined;
108
+ const exactRepository = firstSlashRaw > 0 ? namePart.slice(firstSlashRaw + 1) : undefined;
109
+
110
+ // Strip optional `:tag` before `@sha256:...` (e.g. `node:26@sha256:...`).
111
+ const firstSlash = namePart.indexOf('/');
112
+ const lastColon = namePart.lastIndexOf(':');
113
+ const withoutTag = lastColon > firstSlash ? namePart.slice(0, lastColon) : namePart;
114
+ if (withoutTag.length === 0) {
115
+ throw new ProtocolError('Job image name must not be empty');
116
+ }
117
+
118
+ let registry: string;
119
+ let repository: string;
120
+ const slashIndex = withoutTag.indexOf('/');
121
+ if (slashIndex < 0) {
122
+ registry = 'registry-1.docker.io';
123
+ repository = `library/${withoutTag}`;
124
+ } else {
125
+ const firstSegment = withoutTag.slice(0, slashIndex);
126
+ const hasRegistryHost = firstSegment.includes('.') ||
127
+ firstSegment.includes(':') ||
128
+ firstSegment === 'localhost';
129
+ if (hasRegistryHost) {
130
+ registry = firstSegment === 'docker.io' ? 'registry-1.docker.io' : firstSegment;
131
+ repository = withoutTag.slice(slashIndex + 1);
132
+ } else {
133
+ registry = 'registry-1.docker.io';
134
+ repository = withoutTag;
135
+ }
136
+ }
137
+ if (repository.length === 0 || repository.startsWith('/') || repository.includes('..')) {
138
+ throw new ProtocolError('Job image repository is invalid');
139
+ }
140
+ return {
141
+ raw: image,
142
+ registry,
143
+ repository,
144
+ exactRegistry,
145
+ exactRepository,
146
+ digest: digestPart,
147
+ digestHex: match[1],
148
+ };
149
+ };
150
+
151
+ /**
152
+ * Matches an image reference against lease pull grants using exact literal registry & repository
153
+ * equality per `@ship.zone/ci-spec` (no default registry, no rewriting, no case folding).
154
+ */
155
+ export const findMatchingPullGrant = (
156
+ image: string,
157
+ grants: readonly IImageGrant[],
158
+ ): IImageGrant | undefined => {
159
+ const ref = parseDigestPinnedImageReference(image);
160
+ if (!ref.exactRegistry || !ref.exactRepository) return undefined;
161
+ return grants.find(
162
+ (grant) =>
163
+ grant.access === 'pull' &&
164
+ grant.registry === ref.exactRegistry &&
165
+ grant.repository === ref.exactRepository,
166
+ );
167
+ };
168
+
169
+ interface IBearerChallenge {
170
+ realm: string;
171
+ service?: string;
172
+ scope?: string;
173
+ }
174
+
175
+ const parseBearerChallenge = (header: string): IBearerChallenge | undefined => {
176
+ const trimmed = header.trim();
177
+ if (!trimmed.toLowerCase().startsWith('bearer ')) return undefined;
178
+ const rest = trimmed.slice(7);
179
+ const params: Record<string, string> = {};
180
+ const pattern = /([a-zA-Z0-9_-]+)="([^"]*)"/g;
181
+ let match: RegExpExecArray | null;
182
+ while ((match = pattern.exec(rest)) !== null) {
183
+ params[match[1].toLowerCase()] = match[2];
184
+ }
185
+ if (!params.realm) return undefined;
186
+ return { realm: params.realm, service: params.service, scope: params.scope };
187
+ };
188
+
189
+ const isRedirectStatus = (status: number): boolean =>
190
+ status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
191
+
192
+ const readBoundedResponseBytes = async (
193
+ response: Response,
194
+ maximumBytes: number,
195
+ label: string,
196
+ ): Promise<Uint8Array> => {
197
+ const contentLengthHeader = response.headers.get('content-length');
198
+ if (contentLengthHeader) {
199
+ const declared = Number(contentLengthHeader);
200
+ if (Number.isFinite(declared) && declared > maximumBytes) {
201
+ throw new RunnerError(`${label} exceeds maximum allowed size`);
202
+ }
203
+ }
204
+ if (!response.body) return new Uint8Array(0);
205
+ const reader = response.body.getReader();
206
+ const chunks: Uint8Array[] = [];
207
+ let total = 0;
208
+ try {
209
+ for (;;) {
210
+ const { done, value } = await reader.read();
211
+ if (done) break;
212
+ total += value.byteLength;
213
+ if (total > maximumBytes) {
214
+ throw new RunnerError(`${label} exceeds maximum allowed size`);
215
+ }
216
+ chunks.push(value);
217
+ }
218
+ } finally {
219
+ reader.releaseLock();
220
+ }
221
+ return Buffer.concat(chunks, total);
222
+ };
223
+
224
+ const hashFile = async (filePath: string): Promise<{ sha256: string; size: number }> => {
225
+ const hash = plugins.crypto.createHash('sha256');
226
+ let size = 0;
227
+ for await (const chunk of plugins.fsSync.createReadStream(filePath)) {
228
+ const buf = chunk as Buffer;
229
+ hash.update(buf);
230
+ size += buf.length;
231
+ }
232
+ return { sha256: hash.digest('hex'), size };
233
+ };
234
+
235
+ const defaultBuildRootfs = async (options: {
236
+ helperPath: string;
237
+ layerPaths: string[];
238
+ outputPath: string;
239
+ maximumBytes: number;
240
+ signal?: AbortSignal;
241
+ }): Promise<void> => {
242
+ const args = [
243
+ 'build-rootfs',
244
+ '--output',
245
+ options.outputPath,
246
+ '--maximum-bytes',
247
+ String(options.maximumBytes),
248
+ ];
249
+ for (const layerPath of options.layerPaths) {
250
+ args.push('--layer', layerPath);
251
+ }
252
+ await new Promise<void>((resolve, reject) => {
253
+ const child = plugins.childProcess.spawn(options.helperPath, args, {
254
+ env: {},
255
+ stdio: ['ignore', 'pipe', 'pipe'],
256
+ });
257
+ const stderrChunks: Buffer[] = [];
258
+ child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk));
259
+ const onAbort = (): void => {
260
+ child.kill('SIGKILL');
261
+ };
262
+ options.signal?.addEventListener('abort', onAbort, { once: true });
263
+ child.once('error', (error) => {
264
+ options.signal?.removeEventListener('abort', onAbort);
265
+ reject(new RunnerError(`Unable to execute rootfs builder: ${error.message}`, { cause: error }));
266
+ });
267
+ child.once('close', (code) => {
268
+ options.signal?.removeEventListener('abort', onAbort);
269
+ if (code === 0) resolve();
270
+ else {
271
+ const msg = Buffer.concat(stderrChunks).toString('utf8').trim();
272
+ reject(new RunnerError(`Rootfs builder failed (exit ${code}): ${msg || 'unknown error'}`));
273
+ }
274
+ });
275
+ });
276
+ };
277
+
278
+ const parseDefaultEnv = (entries: unknown): Record<string, string> => {
279
+ const out: Record<string, string> = {};
280
+ if (!Array.isArray(entries)) return out;
281
+ for (const entry of entries) {
282
+ if (typeof entry !== 'string') continue;
283
+ const eq = entry.indexOf('=');
284
+ if (eq > 0) out[entry.slice(0, eq)] = entry.slice(eq + 1);
285
+ }
286
+ return out;
287
+ };
288
+
289
+ const isGzipLayerMediaType = (mediaType: string, firstBytes: Uint8Array): boolean => {
290
+ const lowered = mediaType.toLowerCase();
291
+ if (lowered.endsWith('+gzip') || lowered.endsWith('.gzip')) return true;
292
+ return firstBytes.byteLength >= 2 && firstBytes[0] === 0x1f && firstBytes[1] === 0x8b;
293
+ };
294
+
295
+ /**
296
+ * Pulls digest-pinned Linux OCI/Docker images directly via OCI Distribution v2 over HTTP(S),
297
+ * verifies every manifest, config, and layer SHA-256 digest, honors attempt-scoped pull grants
298
+ * without following redirects or leaking private layers into shared cache, and materializes a
299
+ * deterministic read-only ext2 rootfs image.
300
+ */
301
+ export class OciRegistryClient {
302
+ private readonly fetchImpl: typeof fetch;
303
+ private readonly buildRootfsImpl: NonNullable<IOciRegistryClientOptions['buildRootfs']>;
304
+
305
+ constructor(private readonly options: IOciRegistryClientOptions) {
306
+ this.fetchImpl = options.fetchImplementation ?? globalThis.fetch;
307
+ this.buildRootfsImpl = options.buildRootfs ?? defaultBuildRootfs;
308
+ }
309
+
310
+ private originFor(registry: string): string {
311
+ if (isLoopbackHost(registry)) {
312
+ if (!this.options.allowInsecureLoopback) {
313
+ throw new RunnerError(
314
+ `Loopback registry ${registry} requires allowInsecureLoopback to be enabled`,
315
+ );
316
+ }
317
+ return `http://${registry}`;
318
+ }
319
+ return `https://${registry}`;
320
+ }
321
+
322
+ private async fetchRegistry(
323
+ url: string,
324
+ headers: Record<string, string>,
325
+ grant: IImageGrant | undefined,
326
+ signal?: AbortSignal,
327
+ allowUnauthenticatedRedirects = false,
328
+ ): Promise<Response> {
329
+ const basicHeader = grant
330
+ ? `Basic ${Buffer.from(`${grant.username}:${grant.secret}`, 'utf8').toString('base64')}`
331
+ : undefined;
332
+
333
+ // ci-spec: Registry redirects are NEVER followed with or without credentials when a grant
334
+ // applies; even without a grant, manifest requests never follow redirects.
335
+ const redirectMode: 'manual' | 'follow' =
336
+ grant !== undefined || !allowUnauthenticatedRedirects ? 'manual' : 'follow';
337
+
338
+ const attempt = async (authorization?: string): Promise<Response> => {
339
+ const combined = AbortSignal.any([
340
+ ...(signal ? [signal] : []),
341
+ AbortSignal.timeout(this.options.requestTimeoutMs),
342
+ ]);
343
+ const reqHeaders: Record<string, string> = { ...headers };
344
+ if (authorization) reqHeaders.authorization = authorization;
345
+ return await this.fetchImpl(url, {
346
+ method: 'GET',
347
+ headers: reqHeaders,
348
+ redirect: redirectMode,
349
+ signal: combined,
350
+ });
351
+ };
352
+
353
+ let response = await attempt(basicHeader);
354
+ if (isRedirectStatus(response.status)) {
355
+ throw new RunnerError(`Registry redirect (HTTP ${response.status}) refused`);
356
+ }
357
+ if (response.status === 401) {
358
+ const challengeHeader = response.headers.get('www-authenticate');
359
+ const challenge = challengeHeader ? parseBearerChallenge(challengeHeader) : undefined;
360
+ if (challenge) {
361
+ const tokenUrl = new URL(challenge.realm);
362
+ if (
363
+ tokenUrl.protocol !== 'https:' &&
364
+ !(this.options.allowInsecureLoopback && isLoopbackHost(tokenUrl.host))
365
+ ) {
366
+ throw new RunnerError('Registry auth realm must use HTTPS');
367
+ }
368
+ // When a grant applies, credentials must never be sent to an unrelated host!
369
+ if (grant && tokenUrl.host !== grant.registry) {
370
+ throw new RunnerError(
371
+ `Registry auth realm ${tokenUrl.host} does not match grant origin ${grant.registry}`,
372
+ );
373
+ }
374
+ if (challenge.service) tokenUrl.searchParams.set('service', challenge.service);
375
+ if (challenge.scope) tokenUrl.searchParams.set('scope', challenge.scope);
376
+ const tokenHeaders: Record<string, string> = {};
377
+ if (basicHeader) tokenHeaders.authorization = basicHeader;
378
+ const tokenResp = await this.fetchImpl(tokenUrl.toString(), {
379
+ method: 'GET',
380
+ headers: tokenHeaders,
381
+ redirect: 'manual',
382
+ signal: AbortSignal.any([
383
+ ...(signal ? [signal] : []),
384
+ AbortSignal.timeout(this.options.requestTimeoutMs),
385
+ ]),
386
+ });
387
+ if (isRedirectStatus(tokenResp.status)) {
388
+ throw new RunnerError(`Registry auth redirect (HTTP ${tokenResp.status}) refused`);
389
+ }
390
+ if (!tokenResp.ok) {
391
+ throw new RunnerError(`Registry token exchange failed with HTTP ${tokenResp.status}`);
392
+ }
393
+ const tokenJson = (await tokenResp.json()) as { token?: string; access_token?: string };
394
+ const token = tokenJson.token ?? tokenJson.access_token;
395
+ if (typeof token !== 'string' || token.length === 0) {
396
+ throw new RunnerError('Registry token response did not include a token');
397
+ }
398
+ response = await attempt(`Bearer ${token}`);
399
+ if (isRedirectStatus(response.status)) {
400
+ throw new RunnerError(`Registry redirect (HTTP ${response.status}) refused`);
401
+ }
402
+ }
403
+ }
404
+ return response;
405
+ }
406
+
407
+ private async fetchDigestBlob(
408
+ origin: string,
409
+ repository: string,
410
+ digest: string,
411
+ maximumBytes: number,
412
+ grant: IImageGrant | undefined,
413
+ signal?: AbortSignal,
414
+ ): Promise<Uint8Array> {
415
+ const match = digestPattern.exec(digest);
416
+ if (!match) throw new ProtocolError(`Invalid OCI blob digest: ${digest}`);
417
+ const url = `${origin}/v2/${repository}/blobs/${digest}`;
418
+ const response = await this.fetchRegistry(url, {}, grant, signal, grant === undefined);
419
+ if (!response.ok) {
420
+ throw new RunnerError(`Unable to pull OCI blob ${digest} (HTTP ${response.status})`);
421
+ }
422
+ const bytes = await readBoundedResponseBytes(response, maximumBytes, `OCI blob ${digest}`);
423
+ const actual = sha256Hex(bytes);
424
+ if (actual !== match[1]) {
425
+ throw new ProtocolError(`OCI blob ${digest} failed SHA-256 verification`);
426
+ }
427
+ return bytes;
428
+ }
429
+
430
+ async materializeImage(
431
+ image: string,
432
+ targetArchitecture: TOciArchitecture,
433
+ signal?: AbortSignal,
434
+ grants: readonly IImageGrant[] = [],
435
+ ): Promise<IMaterializedOciImage> {
436
+ const ref = parseDigestPinnedImageReference(image);
437
+ const matchingGrant = findMatchingPullGrant(image, grants);
438
+ // When a grant applies, connect to grant.registry + grant.repository literally (no rewriting).
439
+ const registry = matchingGrant ? matchingGrant.registry : ref.registry;
440
+ const repository = matchingGrant ? matchingGrant.repository : ref.repository;
441
+ const origin = this.originFor(registry);
442
+
443
+ // Content pulled with a pull grant is stored ONLY in an attempt-private store that is removed
444
+ // when the attempt ends (ci-spec Image Grants & Bindings).
445
+ let attemptPrivateDir: string | undefined;
446
+ let storeBase = this.options.cacheDirectory;
447
+ if (matchingGrant) {
448
+ const privateRoot = join(this.options.cacheDirectory, 'attempt-private');
449
+ await plugins.fs.mkdir(privateRoot, { recursive: true, mode: 0o700 });
450
+ attemptPrivateDir = await makeTempDir({ dir: privateRoot, prefix: 'private-' });
451
+ await plugins.fs.chmod(attemptPrivateDir, 0o700);
452
+ storeBase = attemptPrivateDir;
453
+ }
454
+
455
+ const cleanupPrivate = async (): Promise<void> => {
456
+ if (!attemptPrivateDir) return;
457
+ await removePath(attemptPrivateDir, { recursive: true }).catch((error) => {
458
+ if (!isNotFound(error)) throw error;
459
+ });
460
+ };
461
+
462
+ try {
463
+ const layersDir = join(storeBase, 'layers');
464
+ const rootfsDir = join(storeBase, 'rootfs');
465
+ await plugins.fs.mkdir(layersDir, { recursive: true, mode: 0o700 });
466
+ await plugins.fs.mkdir(rootfsDir, { recursive: true, mode: 0o700 });
467
+
468
+ const fetchVerifiedManifest = async (
469
+ digest: string,
470
+ ): Promise<{ digest: string; json: Record<string, unknown> }> => {
471
+ const expected = digestPattern.exec(digest);
472
+ if (!expected) throw new ProtocolError(`Invalid manifest digest: ${digest}`);
473
+ const url = `${origin}/v2/${repository}/manifests/${digest}`;
474
+ const response = await this.fetchRegistry(
475
+ url,
476
+ { accept: manifestAcceptHeader },
477
+ matchingGrant,
478
+ signal,
479
+ false,
480
+ );
481
+ if (!response.ok) {
482
+ throw new RunnerError(`Unable to pull OCI manifest ${digest} (HTTP ${response.status})`);
483
+ }
484
+ const raw = await readBoundedResponseBytes(response, maximumManifestBytes, 'OCI manifest');
485
+ if (sha256Hex(raw) !== expected[1]) {
486
+ throw new ProtocolError(`OCI manifest ${digest} failed SHA-256 verification`);
487
+ }
488
+ let json: unknown;
489
+ try {
490
+ json = JSON.parse(new TextDecoder().decode(raw));
491
+ } catch (error) {
492
+ throw new ProtocolError('OCI manifest is not valid JSON', { cause: error });
493
+ }
494
+ if (typeof json !== 'object' || json === null || Array.isArray(json)) {
495
+ throw new ProtocolError('OCI manifest must be a JSON object');
496
+ }
497
+ return { digest, json: json as Record<string, unknown> };
498
+ };
499
+
500
+ let resolved = await fetchVerifiedManifest(ref.digest);
501
+
502
+ // Handle multi-platform OCI Index / Docker Manifest List.
503
+ if (Array.isArray(resolved.json.manifests)) {
504
+ const manifests = resolved.json.manifests as Array<{
505
+ digest?: string;
506
+ platform?: { os?: string; architecture?: string };
507
+ }>;
508
+ const selected = manifests.find(
509
+ (entry) =>
510
+ entry?.platform?.os === 'linux' &&
511
+ entry?.platform?.architecture === targetArchitecture &&
512
+ typeof entry.digest === 'string',
513
+ );
514
+ if (!selected?.digest) {
515
+ throw new ProtocolError(
516
+ `Image ${image} does not contain a linux/${targetArchitecture} manifest`,
517
+ );
518
+ }
519
+ resolved = await fetchVerifiedManifest(selected.digest);
520
+ }
521
+
522
+ const configDesc = resolved.json.config as { digest?: string } | undefined;
523
+ const layerDescs = resolved.json.layers as
524
+ | Array<{ digest?: string; mediaType?: string }>
525
+ | undefined;
526
+ if (
527
+ typeof configDesc?.digest !== 'string' ||
528
+ !Array.isArray(layerDescs) ||
529
+ layerDescs.length === 0
530
+ ) {
531
+ throw new ProtocolError(`OCI manifest ${resolved.digest} is missing config or layers`);
532
+ }
533
+
534
+ const configBytes = await this.fetchDigestBlob(
535
+ origin,
536
+ repository,
537
+ configDesc.digest,
538
+ maximumConfigBytes,
539
+ matchingGrant,
540
+ signal,
541
+ );
542
+ const configJson = JSON.parse(new TextDecoder().decode(configBytes)) as {
543
+ os?: string;
544
+ architecture?: string;
545
+ config?: { Env?: unknown; WorkingDir?: unknown };
546
+ };
547
+ if (configJson.os !== 'linux') {
548
+ throw new ProtocolError(`Job image OS ${String(configJson.os)} is not linux`);
549
+ }
550
+ if (configJson.architecture !== targetArchitecture) {
551
+ throw new ProtocolError(
552
+ `Job image architecture ${String(configJson.architecture)} does not match ${targetArchitecture}`,
553
+ );
554
+ }
555
+
556
+ const manifestHex = digestPattern.exec(resolved.digest)![1];
557
+ const cachedRootfsPath = join(rootfsDir, `${manifestHex}.ext2`);
558
+ let rootfsExists = false;
559
+ if (!matchingGrant) {
560
+ try {
561
+ const stat = await plugins.fs.lstat(cachedRootfsPath);
562
+ rootfsExists = stat.isFile() && stat.size > 0;
563
+ } catch (error) {
564
+ if (!isNotFound(error)) throw error;
565
+ }
566
+ }
567
+
568
+ if (!rootfsExists) {
569
+ const layerTarPaths: string[] = [];
570
+ for (const layer of layerDescs) {
571
+ if (typeof layer?.digest !== 'string') {
572
+ throw new ProtocolError('OCI layer descriptor is missing digest');
573
+ }
574
+ const layerMatch = digestPattern.exec(layer.digest);
575
+ if (!layerMatch) throw new ProtocolError(`Invalid OCI layer digest: ${layer.digest}`);
576
+ const cachedLayerPath = join(layersDir, `${layerMatch[1]}.tar`);
577
+ let haveLayer = false;
578
+ if (!matchingGrant) {
579
+ try {
580
+ const stat = await plugins.fs.lstat(cachedLayerPath);
581
+ haveLayer = stat.isFile() && stat.size > 0;
582
+ } catch (error) {
583
+ if (!isNotFound(error)) throw error;
584
+ }
585
+ }
586
+ if (!haveLayer) {
587
+ const blobBytes = await this.fetchDigestBlob(
588
+ origin,
589
+ repository,
590
+ layer.digest,
591
+ maximumLayerBlobBytes,
592
+ matchingGrant,
593
+ signal,
594
+ );
595
+ const tarBytes = isGzipLayerMediaType(layer.mediaType ?? '', blobBytes)
596
+ ? plugins.zlib.gunzipSync(blobBytes)
597
+ : blobBytes;
598
+ const tempLayer = join(layersDir, `.${plugins.crypto.randomUUID()}.tar.tmp`);
599
+ try {
600
+ await plugins.fs.writeFile(tempLayer, tarBytes, { mode: 0o600 });
601
+ await plugins.fs.rename(tempLayer, cachedLayerPath);
602
+ } catch (error) {
603
+ await removePath(tempLayer).catch(() => {});
604
+ throw error;
605
+ }
606
+ }
607
+ layerTarPaths.push(cachedLayerPath);
608
+ }
609
+
610
+ const tempRootfs = join(rootfsDir, `.${plugins.crypto.randomUUID()}.ext2.tmp`);
611
+ try {
612
+ await this.buildRootfsImpl({
613
+ helperPath: this.options.helperPath,
614
+ layerPaths: layerTarPaths,
615
+ outputPath: tempRootfs,
616
+ maximumBytes: this.options.maximumRootfsBytes,
617
+ signal,
618
+ });
619
+ await plugins.fs.rename(tempRootfs, cachedRootfsPath);
620
+ } catch (error) {
621
+ await removePath(tempRootfs).catch(() => {});
622
+ throw error;
623
+ }
624
+ }
625
+
626
+ const { sha256: rootfsSha256, size: rootfsSizeBytes } = await hashFile(cachedRootfsPath);
627
+ return {
628
+ image,
629
+ manifestDigest: resolved.digest,
630
+ os: 'linux',
631
+ architecture: targetArchitecture,
632
+ rootfsPath: cachedRootfsPath,
633
+ rootfsSha256,
634
+ rootfsSizeBytes,
635
+ defaultEnv: parseDefaultEnv(configJson.config?.Env),
636
+ defaultWorkingDir:
637
+ typeof configJson.config?.WorkingDir === 'string' &&
638
+ configJson.config.WorkingDir.length > 0
639
+ ? configJson.config.WorkingDir
640
+ : undefined,
641
+ attemptPrivate: matchingGrant !== undefined,
642
+ cleanup: cleanupPrivate,
643
+ };
644
+ } catch (error) {
645
+ await cleanupPrivate().catch(() => {});
646
+ throw error;
647
+ }
648
+ }
649
+ }
package/ts/plugins.ts CHANGED
@@ -2,17 +2,21 @@
2
2
  import * as childProcess from 'node:child_process';
3
3
  import * as crypto from 'node:crypto';
4
4
  import * as fs from 'node:fs/promises';
5
+ import * as fsSync from 'node:fs';
6
+ import * as net from 'node:net';
5
7
  import * as os from 'node:os';
6
8
  import * as path from 'node:path';
7
9
  import * as stream from 'node:stream';
8
10
  import * as url from 'node:url';
11
+ import * as zlib from 'node:zlib';
9
12
 
10
- export { childProcess, crypto, fs, os, path, stream, url };
13
+ export { childProcess, crypto, fs, fsSync, net, os, path, stream, url, zlib };
11
14
  export type { BigIntStatsFs, Stats } from 'node:fs';
12
15
 
13
16
  // @push.rocks scope
14
17
  import * as smartsea from '@push.rocks/smartsea';
15
- export { smartsea };
18
+ import * as smartvm from '@push.rocks/smartvm';
19
+ export { smartsea, smartvm };
16
20
 
17
21
  // @ship.zone scope
18
22
  export {