hammerkit 2.0.0-next.15 → 2.0.0-next.17

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.
@@ -12,6 +12,7 @@ const capacity_1 = require("./capacity");
12
12
  const kubernetes_instance_1 = require("../kubernetes/kubernetes-instance");
13
13
  const log_1 = require("../log");
14
14
  const network_policy_1 = require("../kubernetes/network-policy");
15
+ const network_gate_1 = require("../kubernetes/network-gate");
15
16
  const sleep_1 = require("../utils/sleep");
16
17
  const version_1 = require("../version");
17
18
  const executor_1 = require("./executor");
@@ -98,6 +99,8 @@ function readInClusterNamespace() {
98
99
  * Policies add up, so neither selects the pods of a limited item: its own policy (see
99
100
  * buildNetworkPolicy) is all it may reach, DNS left out, and all that may reach it. An
100
101
  * egress proxy takes connections from its item only (buildProxyPolicy).
102
+ * - the pods that copy files into and out of claims: no network at all (they are limited,
103
+ * and the policies of the items whose labels they carry leave them out)
101
104
  */
102
105
  function getNamespacePolicies(namespace, deniedEgress, allowedEgress = []) {
103
106
  const metadata = (name) => ({
@@ -157,6 +160,17 @@ function getNamespacePolicies(namespace, deniedEgress, allowedEgress = []) {
157
160
  ingress: [],
158
161
  },
159
162
  },
163
+ {
164
+ apiVersion: 'networking.k8s.io/v1',
165
+ kind: 'NetworkPolicy',
166
+ metadata: metadata('hammerkit-transfer'),
167
+ spec: {
168
+ // the pods that copy files into and out of a claim, which are reached through the
169
+ // API (exec): nothing in or out
170
+ podSelector: { matchLabels: { [network_policy_1.TRANSFER_LABEL]: 'true' } },
171
+ policyTypes: ['Ingress', 'Egress'],
172
+ },
173
+ },
160
174
  ];
161
175
  }
162
176
  exports.getNamespacePolicies = getNamespacePolicies;
@@ -565,6 +579,7 @@ class KubernetesExecutor {
565
579
  // The cluster as the process of a run sees it: the namespace its tasks and services go in.
566
580
  environmentOf(run, namespace, work, capabilitiesProblem) {
567
581
  const backend = this.config.backend;
582
+ const openGate = (0, network_gate_1.getOpenNetworkGate)(backend);
568
583
  return {
569
584
  type: 'kubernetes',
570
585
  namespace,
@@ -585,6 +600,7 @@ class KubernetesExecutor {
585
600
  // the claims of a service run go with its namespace
586
601
  ...(this.keep > 0 && !run.up ? { volumeScope: getVolumeScope(run) } : {}),
587
602
  ...(run.up ? { serviceRun: true } : {}),
603
+ ...(openGate ? { openGate } : {}),
588
604
  ...(backend.capabilities
589
605
  ? {
590
606
  capabilities: {
@@ -284,14 +284,19 @@ up) {
284
284
  if (input.kubernetes.server?.serviceRun) {
285
285
  // a run that moved here from another commit: what it made for items it has no more
286
286
  const ids = [...Object.values(workTree.tasks), ...Object.values(workTree.services)].map((item) => item.id());
287
- await (0, remove_stale_items_1.removeStaleItems)((0, kubernetes_instance_1.createKubernetesInstances)(input.kubernetes), input.kubernetes, ids).catch((e) => emit({
287
+ await (0, remove_stale_items_1.removeStaleItems)((0, kubernetes_instance_1.createKubernetesInstances)(input.kubernetes), input.kubernetes, ids, {
288
+ signal: abortCtrl.signal,
289
+ }).catch((e) => emit({
288
290
  type: 'log',
289
291
  task: 'hammerkit',
290
292
  stream: 'stderr',
291
293
  text: `what the run made at its previous commit could not be removed: ${(0, log_1.getErrorMessage)(e)}`,
292
294
  }));
293
295
  }
294
- await new Promise((resolve) => abortCtrl.signal.addEventListener('abort', () => resolve(), { once: true }));
296
+ // stopped while the old pods ended, or up until it is stopped
297
+ if (!abortCtrl.signal.aborted) {
298
+ await new Promise((resolve) => abortCtrl.signal.addEventListener('abort', () => resolve(), { once: true }));
299
+ }
295
300
  return;
296
301
  }
297
302
  if (input.up && ready) {
@@ -456,7 +456,10 @@ class RunRegistry {
456
456
  }
457
457
  // The run that holds a sandbox: the oldest on it that is not over. It holds it from
458
458
  // when it is submitted, so the files are not moved under what an approver saw. A service
459
- // run that is up works on a copy of the files, and holds it no longer.
459
+ // run that is up holds it no longer, so the agent can go on working while its services
460
+ // run: an approved one works on a copy of the files, any other (on a host) in the sandbox
461
+ // itself, which edits then write in through the directories they checked (see `write` of
462
+ // HostSandboxFiles).
460
463
  holder(sandbox) {
461
464
  return [...this.entries.values()].find((entry) => onSandbox(entry.run, sandbox) &&
462
465
  !isFinal(entry.run.state) &&
@@ -5,6 +5,7 @@ const child_process_1 = require("child_process");
5
5
  const crypto_1 = require("crypto");
6
6
  const fs_1 = require("fs");
7
7
  const promises_1 = require("fs/promises");
8
+ const os_1 = require("os");
8
9
  const path_1 = require("path");
9
10
  const minimatch_1 = require("minimatch");
10
11
  const source_manifest_1 = require("../remote/source-manifest");
@@ -193,6 +194,8 @@ function fileType(stats) {
193
194
  * without following a link, and on Linux the opened file is checked to be the one in the
194
195
  * sandbox, in case a task swapped a directory for a link in between.
195
196
  */
197
+ // the ignore files ripgrep reads in the folders above the path it searches
198
+ const IGNORE_FILES = ['.gitignore', '.ignore', '.rgignore'];
196
199
  class HostSandboxFiles {
197
200
  constructor(root, git,
198
201
  // the environment of ripgrep: the variables runs see
@@ -301,12 +304,17 @@ class HostSandboxFiles {
301
304
  }
302
305
  }
303
306
  // The opened file is the one in the sandbox: a task may have swapped a directory above it
304
- // for a link after the names were checked. Linux names the file a descriptor is open on;
305
- // elsewhere the path has to lead to the same file and to no link.
307
+ // for a link after the names were checked. Linux names the file a descriptor is open on,
308
+ // and a server that can't read that (no /proc) reads nothing: a check of the path would
309
+ // leave a moment for a swap. Elsewhere (a machine of a developer) the path has to lead to
310
+ // the same file and to no link.
306
311
  async mustBeInside(handle, absolute, path) {
307
312
  let actual;
308
313
  if (process.platform === 'linux') {
309
314
  actual = await (0, promises_1.readlink)(`/proc/self/fd/${handle.fd}`).catch(() => undefined);
315
+ if (actual === undefined) {
316
+ throw new SandboxFileError(503, `${path} can not be read: the server can not tell which file it opened, /proc/self/fd is not readable`);
317
+ }
310
318
  }
311
319
  if (actual === undefined) {
312
320
  const [opened, named] = await Promise.all([handle.stat(), (0, promises_1.lstat)(absolute)]);
@@ -534,7 +542,13 @@ class HostSandboxFiles {
534
542
  else {
535
543
  args.push('--count-matches', '--null');
536
544
  }
537
- args.push('--regexp', query.pattern, '--', path ?? '.');
545
+ // ripgrep follows a link in the path it is given, which a running task can swap in after
546
+ // the check above: it reads what was checked (see pin)
547
+ const target = await this.pin(path);
548
+ if (target.stdin) {
549
+ args.push('--with-filename');
550
+ }
551
+ args.push('--regexp', query.pattern, '--', target.arg);
538
552
  const result = { output_mode: mode, total: 0, exact: true, truncated: false, cursor: null };
539
553
  const files = [];
540
554
  const matches = [];
@@ -549,8 +563,11 @@ class HostSandboxFiles {
549
563
  };
550
564
  // the JSON of ripgrep names paths with the separator of the system, whatever --path-separator says
551
565
  const clean = (file) => {
552
- const path = process.platform === 'win32' ? file.replace(/\\/g, '/') : file;
553
- return path.startsWith('./') ? path.slice(2) : path;
566
+ if (target.stdin && file === '<stdin>') {
567
+ return path;
568
+ }
569
+ const name = process.platform === 'win32' ? file.replace(/\\/g, '/') : file;
570
+ return name.startsWith('./') ? name.slice(2) : name;
554
571
  };
555
572
  const onRecord = (record) => {
556
573
  if (mode === 'files_with_matches') {
@@ -577,7 +594,16 @@ class HostSandboxFiles {
577
594
  ...(message.type === 'context' ? { context: true } : {}),
578
595
  })));
579
596
  };
580
- const { code, stderr, stopped } = await this.ripgrep(args, mode === 'files_with_matches' ? '\0' : '\n', onRecord);
597
+ let ran;
598
+ try {
599
+ ran = target.skip
600
+ ? { code: 1, stderr: '', stopped: false }
601
+ : await this.ripgrep(args, mode === 'files_with_matches' ? '\0' : '\n', onRecord, target);
602
+ }
603
+ finally {
604
+ await target.release();
605
+ }
606
+ const { code, stderr, stopped } = ran;
581
607
  if (code === 2 && total === 0 && !stopped) {
582
608
  throw new SandboxFileError(400, stderr.trim() || 'ripgrep failed');
583
609
  }
@@ -596,9 +622,93 @@ class HostSandboxFiles {
596
622
  }
597
623
  return result;
598
624
  }
625
+ // What ripgrep searches for a `path` of a search, so that it reads what was checked when a
626
+ // task swaps a link into the path meanwhile (ripgrep follows the links of the path it is
627
+ // given, not those it finds below it). A file is read here, through the check of what was
628
+ // opened, and handed to ripgrep on stdin. A directory is opened here and checked the same
629
+ // way; ripgrep is given the same relative path in a folder of its own where it is a link
630
+ // to that open directory (on Linux, /proc/<pid>/fd/<n>), next to copies of the ignore
631
+ // files above it, so that globs, `.gitignore` and the paths it prints are what they were.
632
+ // Elsewhere (a machine of a developer) a directory is searched by its name.
633
+ async pin(path) {
634
+ const none = async () => undefined;
635
+ if (!path) {
636
+ return { arg: '.', cwd: this.root, release: none };
637
+ }
638
+ const found = await this.stat(path);
639
+ if (found?.type === 'file') {
640
+ const { handle, stat } = await this.open(path);
641
+ if (stat.size > exports.MAX_FILE_BYTES) {
642
+ // as ripgrep's --max-filesize leaves it out
643
+ await handle.close();
644
+ return { arg: '-', cwd: this.root, skip: true, release: none };
645
+ }
646
+ const stdin = handle.createReadStream();
647
+ return { arg: '-', cwd: this.root, stdin, release: async () => void stdin.destroy() };
648
+ }
649
+ if (process.platform !== 'linux') {
650
+ return { arg: path, cwd: this.root, release: none };
651
+ }
652
+ const absolute = this.absolute(path);
653
+ const handle = await (0, promises_1.open)(absolute, fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY | fs_1.constants.O_NOFOLLOW).catch((e) => {
654
+ if (e.code === 'ELOOP' || e.code === 'ENOTDIR') {
655
+ throw new SandboxFileError(409, `${path} changed while it was searched, search again`);
656
+ }
657
+ throw e;
658
+ });
659
+ let folder;
660
+ try {
661
+ await this.mustBeInside(handle, absolute, path);
662
+ folder = await (0, promises_1.mkdtemp)((0, path_1.join)((0, os_1.tmpdir)(), 'hammerkit-search-'));
663
+ const parts = path.split('/');
664
+ for (let depth = 0; depth < parts.length; depth++) {
665
+ const above = parts.slice(0, depth).join('/');
666
+ await (0, promises_1.mkdir)((0, path_1.join)(folder, ...parts.slice(0, depth)), { recursive: true });
667
+ for (const name of IGNORE_FILES) {
668
+ const file = above ? `${above}/${name}` : name;
669
+ const content = await this.ignoreFile(file);
670
+ if (content !== undefined) {
671
+ await (0, promises_1.writeFile)((0, path_1.join)(folder, ...parts.slice(0, depth), name), content);
672
+ }
673
+ }
674
+ }
675
+ await (0, promises_1.symlink)(`/proc/${process.pid}/fd/${handle.fd}`, (0, path_1.join)(folder, ...parts));
676
+ }
677
+ catch (e) {
678
+ await handle.close();
679
+ if (folder) {
680
+ await (0, promises_1.rm)(folder, { recursive: true, force: true });
681
+ }
682
+ throw e;
683
+ }
684
+ const pinned = folder;
685
+ return {
686
+ arg: path,
687
+ cwd: pinned,
688
+ release: async () => {
689
+ await (0, promises_1.rm)(pinned, { recursive: true, force: true });
690
+ await handle.close();
691
+ },
692
+ };
693
+ }
694
+ // An ignore file above the path of a search, read as any file is; none when there is none
695
+ // or it can not be read as a file
696
+ async ignoreFile(path) {
697
+ const found = await this.stat(path);
698
+ if (found?.type !== 'file' || found.size > exports.MAX_FILE_BYTES) {
699
+ return undefined;
700
+ }
701
+ const { handle, stat } = await this.open(path);
702
+ try {
703
+ return await readOpened(handle, stat.size);
704
+ }
705
+ finally {
706
+ await handle.close();
707
+ }
708
+ }
599
709
  // Runs ripgrep in the files and hands each record of its output to `onRecord`, which
600
710
  // answers whether to read on.
601
- ripgrep(args, separator, onRecord) {
711
+ ripgrep(args, separator, onRecord, target = { cwd: this.root }) {
602
712
  const env = {};
603
713
  for (const [key, value] of Object.entries(this.env)) {
604
714
  if (value !== undefined && !key.toUpperCase().startsWith('RIPGREP_')) {
@@ -607,11 +717,20 @@ class HostSandboxFiles {
607
717
  }
608
718
  return new Promise((resolve, reject) => {
609
719
  const child = (0, child_process_1.spawn)('rg', args, {
610
- cwd: this.root,
720
+ cwd: target.cwd,
611
721
  env,
612
- stdio: ['ignore', 'pipe', 'pipe'],
722
+ stdio: ['pipe', 'pipe', 'pipe'],
613
723
  signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
614
724
  });
725
+ // ripgrep stops reading when it is stopped or has seen enough
726
+ child.stdin.on('error', () => undefined);
727
+ if (target.stdin) {
728
+ target.stdin.on('error', () => child.stdin.destroy());
729
+ target.stdin.pipe(child.stdin);
730
+ }
731
+ else {
732
+ child.stdin.end();
733
+ }
615
734
  let stopped = false;
616
735
  let buffered = '';
617
736
  let stderr = '';
@@ -797,50 +916,124 @@ class HostSandboxFiles {
797
916
  return state.content;
798
917
  }
799
918
  // Writes the changes: what a path held is moved aside first, and put back when a later
800
- // write fails.
919
+ // write fails. Each name is written in the directory above it, opened from the root name
920
+ // by name (see `folder`), so what a task swaps in meanwhile leads no write out of the files.
801
921
  async write(changes) {
802
922
  const backups = [];
803
923
  const written = [];
804
- // the directories above every path are still the ones the edits were planned in
805
- for (const [path] of changes) {
806
- await this.sameParents(path);
807
- }
924
+ const folders = new Map();
925
+ const folderOf = async (path, create) => {
926
+ const key = (0, path_1.dirname)(path);
927
+ let folder = folders.get(key);
928
+ if (!folder) {
929
+ folder = await this.folder(path, create);
930
+ folders.set(key, folder);
931
+ }
932
+ return folder;
933
+ };
808
934
  try {
809
- for (const [path, before] of changes) {
810
- if (before.kind === 'file' || before.kind === 'link') {
811
- const absolute = this.absolute(path);
812
- const backup = (0, path_1.join)((0, path_1.dirname)(absolute), `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.bak`);
813
- await (0, promises_1.rename)(absolute, backup);
814
- backups.push([absolute, backup]);
935
+ // the directories above every path are still the ones the edits were planned in
936
+ for (const [path] of changes) {
937
+ await this.sameParents(path);
938
+ }
939
+ try {
940
+ for (const [path, before] of changes) {
941
+ if (before.kind === 'file' || before.kind === 'link') {
942
+ const folder = await folderOf(path, false);
943
+ const name = (0, path_1.basename)(path);
944
+ const backup = `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.bak`;
945
+ await (0, promises_1.rename)(folder.at(name), folder.at(backup));
946
+ backups.push([folder, name, backup]);
947
+ }
948
+ }
949
+ for (const [path, before, after] of [...changes].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
950
+ if (after.kind !== 'file') {
951
+ continue;
952
+ }
953
+ const folder = await folderOf(path, true);
954
+ const name = (0, path_1.basename)(path);
955
+ const temporary = `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.tmp`;
956
+ const base = before.kind === 'file' ? before.mode ?? 0o644 : 0o644;
957
+ const mode = after.exec ? base | ((base & 0o444) >> 2) | 0o100 : base & ~0o111;
958
+ const flags = fs_1.constants.O_WRONLY | fs_1.constants.O_CREAT | fs_1.constants.O_EXCL | (fs_1.constants.O_NOFOLLOW ?? 0);
959
+ const handle = await (0, promises_1.open)(folder.at(temporary), flags, mode);
960
+ try {
961
+ await handle.writeFile(after.content ?? Buffer.alloc(0));
962
+ await handle.chmod(mode);
963
+ }
964
+ finally {
965
+ await handle.close();
966
+ }
967
+ await (0, promises_1.rename)(folder.at(temporary), folder.at(name));
968
+ written.push([folder, name]);
815
969
  }
816
970
  }
817
- for (const [path, before, after] of [...changes].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
818
- if (after.kind !== 'file') {
819
- continue;
971
+ catch (e) {
972
+ for (const [folder, name] of written.reverse()) {
973
+ await (0, promises_1.rm)(folder.at(name), { force: true });
820
974
  }
975
+ for (const [folder, name, backup] of backups.reverse()) {
976
+ await (0, promises_1.rename)(folder.at(backup), folder.at(name)).catch(() => undefined);
977
+ }
978
+ throw e;
979
+ }
980
+ for (const [folder, , backup] of backups) {
981
+ await (0, promises_1.rm)(folder.at(backup), { force: true });
982
+ }
983
+ }
984
+ finally {
985
+ for (const folder of folders.values()) {
986
+ await folder.release();
987
+ }
988
+ }
989
+ }
990
+ // The directory above `path`, made where it is missing and `create` is set. On Linux it is
991
+ // opened from the root name by name, never through a link, and its names are reached
992
+ // through the open descriptor (/proc/self/fd/<n>/<name>): a directory a task swaps for a link
993
+ // after the checks leads no write out of the files. A server on Linux that can not read
994
+ // /proc writes nothing. Elsewhere (a machine of a developer) the names are checked on the way.
995
+ async folder(path, create) {
996
+ const parts = path.split('/').slice(0, -1);
997
+ if (process.platform !== 'linux') {
998
+ if (create) {
821
999
  await this.makeParents(path);
822
- const absolute = this.absolute(path);
823
- const temporary = (0, path_1.join)((0, path_1.dirname)(absolute), `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.tmp`);
824
- const base = before.kind === 'file' ? before.mode ?? 0o644 : 0o644;
825
- const mode = after.exec ? base | ((base & 0o444) >> 2) | 0o100 : base & ~0o111;
826
- await (0, promises_1.writeFile)(temporary, after.content ?? Buffer.alloc(0), { flag: 'wx', mode });
827
- await (0, promises_1.chmod)(temporary, mode);
828
- await (0, promises_1.rename)(temporary, absolute);
829
- written.push(absolute);
830
1000
  }
1001
+ const absolute = (0, path_1.dirname)(this.absolute(path));
1002
+ return { at: (name) => (0, path_1.join)(absolute, name), release: async () => undefined };
831
1003
  }
832
- catch (e) {
833
- for (const absolute of written.reverse()) {
834
- await (0, promises_1.rm)(absolute, { force: true });
1004
+ let handle = await (0, promises_1.open)(this.root, fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY);
1005
+ try {
1006
+ if ((await (0, promises_1.readlink)(`/proc/self/fd/${handle.fd}`).catch(() => undefined)) === undefined) {
1007
+ throw new SandboxFileError(503, `${path} can not be written: the server can not reach a directory it opened, /proc/self/fd is not readable`);
835
1008
  }
836
- for (const [absolute, backup] of backups.reverse()) {
837
- await (0, promises_1.rename)(backup, absolute).catch(() => undefined);
1009
+ const flags = fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY | (fs_1.constants.O_NOFOLLOW ?? 0);
1010
+ for (const part of parts) {
1011
+ const at = `/proc/self/fd/${handle.fd}/${part}`;
1012
+ const next = await (0, promises_1.open)(at, flags).catch(async (e) => {
1013
+ if (create && isNotFound(e)) {
1014
+ await (0, promises_1.mkdir)(at).catch((made) => {
1015
+ if (made.code !== 'EEXIST') {
1016
+ throw made;
1017
+ }
1018
+ });
1019
+ return (0, promises_1.open)(at, flags);
1020
+ }
1021
+ throw e;
1022
+ });
1023
+ await handle.close();
1024
+ handle = next;
838
1025
  }
839
- throw e;
840
1026
  }
841
- for (const [, backup] of backups) {
842
- await (0, promises_1.rm)(backup, { force: true });
1027
+ catch (e) {
1028
+ await handle.close().catch(() => undefined);
1029
+ const code = e.code;
1030
+ if (code === 'ELOOP' || code === 'ENOTDIR' || code === 'ENOENT') {
1031
+ throw new SandboxFileError(409, `${parts.join('/')} is not a directory any more`);
1032
+ }
1033
+ throw e;
843
1034
  }
1035
+ const opened = handle;
1036
+ return { at: (name) => `/proc/self/fd/${opened.fd}/${name}`, release: () => opened.close() };
844
1037
  }
845
1038
  async sameParents(path) {
846
1039
  const parts = path.split('/');
@@ -299,6 +299,15 @@ const kubernetesBackendSchema = zod_1.z
299
299
  // build file's environment does: hammerkit can't tell from the API, and without it a
300
300
  // task with a limited network fails rather than runs open
301
301
  networkPolicy: zod_1.z.literal('enforced').optional(),
302
+ // what the pods with an open network wait to no longer reach before they start, under
303
+ // `networkPolicy: enforced`: an address and port `deniedEgress` covers that answers without
304
+ // the policy (the metadata endpoint by default), or `false` for no wait
305
+ openNetworkGate: zod_1.z
306
+ .union([
307
+ zod_1.z.literal(false),
308
+ zod_1.z.object({ host: zod_1.z.string().ip({ version: 'v4' }), port: zod_1.z.number().int().min(1).max(65535) }).strict(),
309
+ ])
310
+ .optional(),
302
311
  // `runtimeClass` is a RuntimeClass of a sandbox, such as gvisor; the pods of tasks that
303
312
  // add capabilities run in it
304
313
  capabilities: zod_1.z.object({ allow: capabilitiesAllowSchema, runtimeClass: kubernetesNameSchema }).strict().optional(),
package/dist/utils/tar.js CHANGED
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.packArchive = void 0;
3
+ exports.onlyBelow = exports.extractOutput = exports.packArchive = void 0;
4
4
  const tar_1 = require("tar");
5
+ const path_1 = require("path");
5
6
  function packArchive(options, files) {
6
7
  return (0, tar_1.create)({ ...options, jobs: 1, linkCache: new ExactLinkCache() }, files);
7
8
  }
@@ -33,4 +34,53 @@ const NOT_PACKED = '\0';
33
34
  function isExact(key) {
34
35
  return key.split(':').every((part) => Number.isSafeInteger(Number(part)));
35
36
  }
37
+ // Extracts the archive of one output (a path relative to `cwd`) into `cwd`. An archive
38
+ // comes from a cache another run, or whoever writes to the cache backend, filled, so only
39
+ // entries of that output are taken: one beside it (another output, a source of the task, a
40
+ // build file) would otherwise be written over the project. A hard link is taken only to a
41
+ // file of the output (packArchive stores one to a file outside as its content). A symbolic
42
+ // link may point out of the output on a machine (a node_modules links its workspace
43
+ // packages); on a server, which did not write the archive, it is left out.
44
+ async function extractOutput(file, cwd, output, hosted) {
45
+ const below = onlyBelow(output);
46
+ await (0, tar_1.extract)({
47
+ file,
48
+ cwd,
49
+ filter: (path, entry) => {
50
+ if (!below(path)) {
51
+ return false;
52
+ }
53
+ const read = entry;
54
+ if (read.type === 'Link') {
55
+ return below(read.linkpath ?? '');
56
+ }
57
+ if (read.type === 'SymbolicLink' && hosted) {
58
+ const target = read.linkpath ?? '';
59
+ return !path_1.posix.isAbsolute(target) && below(path_1.posix.join(path_1.posix.dirname(normalizeEntry(path)), target));
60
+ }
61
+ return true;
62
+ },
63
+ });
64
+ }
65
+ exports.extractOutput = extractOutput;
66
+ // Whether an entry of an archive is the output (a path relative to where the archive is
67
+ // extracted) or below it.
68
+ function onlyBelow(output) {
69
+ const own = normalizeEntry(output);
70
+ return (path) => {
71
+ const entry = normalizeEntry(path);
72
+ if (own === '.') {
73
+ // the output is the folder the archive is extracted in
74
+ return entry !== '..' && !entry.startsWith('../') && !path_1.posix.isAbsolute(entry);
75
+ }
76
+ return entry === own || entry.startsWith(`${own}/`);
77
+ };
78
+ }
79
+ exports.onlyBelow = onlyBelow;
80
+ function normalizeEntry(path) {
81
+ return path_1.posix
82
+ .normalize(path.replace(/\\/g, '/'))
83
+ .replace(/^(\.\/)+/, '')
84
+ .replace(/\/+$/, '');
85
+ }
36
86
  //# sourceMappingURL=tar.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hammerkit",
3
3
  "description": "Containerized build tool with incremental caching that runs the same build file locally, in Docker and on Kubernetes.",
4
- "version": "2.0.0-next.15",
4
+ "version": "2.0.0-next.17",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",