hammerkit 2.0.0-next.8 → 2.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 (99) hide show
  1. package/build.schema.json +228 -63
  2. package/dist/cache/backends/registry/registry-client.js +8 -2
  3. package/dist/cache/explain.js +5 -0
  4. package/dist/cache/last-resolved.js +11 -0
  5. package/dist/cli.js +4 -1
  6. package/dist/dashboard/assets/{graph-canvas-HmkW_-XJ.js → graph-canvas-DtJSpova.js} +1 -1
  7. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  8. package/dist/dashboard/assets/{index-vE22S5E_.js → index-DRSwIRXd.js} +9 -9
  9. package/dist/dashboard/index.html +2 -2
  10. package/dist/docker/item-network.js +51 -18
  11. package/dist/docker/package.js +85 -76
  12. package/dist/docker/server-tools.js +96 -0
  13. package/dist/docker/stream.js +15 -7
  14. package/dist/environment/replace-env-variables.js +1 -1
  15. package/dist/environment/run-source-envs.js +18 -0
  16. package/dist/executer/check-container-binds.js +158 -0
  17. package/dist/executer/docker-service.js +42 -3
  18. package/dist/executer/docker-task.js +33 -6
  19. package/dist/executer/execute-command.js +9 -15
  20. package/dist/executer/execute-work-task.js +11 -1
  21. package/dist/executer/execute-work-tree.js +2 -1
  22. package/dist/executer/execution-steps.js +6 -2
  23. package/dist/executer/get-container-binds.js +2 -0
  24. package/dist/executer/print-container-options.js +10 -10
  25. package/dist/executer/process-manager.js +84 -5
  26. package/dist/executer/scheduler/state-key.js +19 -1
  27. package/dist/executer/task-priority.js +131 -0
  28. package/dist/file/stat-beneath.js +66 -0
  29. package/dist/file/within-root.js +13 -4
  30. package/dist/harness/connect.js +1 -6
  31. package/dist/harness/mcp-command.js +1 -1
  32. package/dist/harness/sandbox-client.js +39 -4
  33. package/dist/harness/service-tools.js +2 -2
  34. package/dist/kubernetes/await-running-state.js +42 -26
  35. package/dist/kubernetes/ensure-persistent-data.js +22 -7
  36. package/dist/kubernetes/follow-pod-logs.js +5 -3
  37. package/dist/kubernetes/network-gate.js +74 -11
  38. package/dist/kubernetes/network-policy.js +32 -10
  39. package/dist/kubernetes/remove-stale-items.js +15 -2
  40. package/dist/kubernetes/restore-kubernetes-data.js +3 -2
  41. package/dist/kubernetes/sandbox-runner.js +3 -4
  42. package/dist/kubernetes/store-kubernetes-data.js +3 -2
  43. package/dist/kubernetes/transfer-tools.js +66 -0
  44. package/dist/kubernetes/volumes.js +52 -10
  45. package/dist/optimizer/check-key.js +7 -0
  46. package/dist/optimizer/check-keys.js +19 -5
  47. package/dist/optimizer/get-work-cache-stats.js +19 -7
  48. package/dist/optimizer/work-task-cache-description.js +42 -8
  49. package/dist/parser/read-build-file.js +8 -3
  50. package/dist/planner/image-build.js +172 -0
  51. package/dist/planner/utils/append-work-dependencies.js +14 -1
  52. package/dist/planner/utils/append-work-service.js +1 -1
  53. package/dist/planner/utils/append-work-task.js +51 -1
  54. package/dist/planner/utils/assert-item-paths.js +6 -7
  55. package/dist/planner/utils/dependency-outputs.js +18 -0
  56. package/dist/planner/utils/template-value.js +20 -4
  57. package/dist/planner/work-runtime-docker.js +48 -50
  58. package/dist/planner/work-runtime-kubernetes.js +1 -0
  59. package/dist/planner/work-runtime-local.js +3 -7
  60. package/dist/planner/work-secret.js +135 -13
  61. package/dist/planner/work-tree.js +10 -0
  62. package/dist/remote/collect-bundle.js +9 -1
  63. package/dist/remote/host-config.js +49 -3
  64. package/dist/remote/location.js +5 -5
  65. package/dist/remote/remote-commands.js +12 -14
  66. package/dist/remote/remote-work-commands.js +20 -8
  67. package/dist/schema/build-file-image-build-schema.js +77 -0
  68. package/dist/schema/build-file-task-schema.js +9 -2
  69. package/dist/schema/reference-parser.js +10 -1
  70. package/dist/schema/schema-parser.js +46 -2
  71. package/dist/schema/work-scope-parser.js +16 -1
  72. package/dist/secrets/secret-catalog.js +8 -1
  73. package/dist/server/dashboard.js +8 -5
  74. package/dist/server/executor.js +58 -35
  75. package/dist/server/kubernetes-backend.js +29 -4
  76. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  77. package/dist/server/overview.js +20 -2
  78. package/dist/server/plan.js +31 -3
  79. package/dist/server/policy.js +14 -7
  80. package/dist/server/repo-access.js +4 -3
  81. package/dist/server/run-environment.js +5 -2
  82. package/dist/server/run-plan.js +18 -6
  83. package/dist/server/run-retry.js +57 -0
  84. package/dist/server/run-source-environment.js +39 -0
  85. package/dist/server/run-worker.js +38 -9
  86. package/dist/server/runs.js +59 -1
  87. package/dist/server/sandbox-files.js +339 -55
  88. package/dist/server/sandbox-patch.js +43 -17
  89. package/dist/server/sandboxes.js +57 -23
  90. package/dist/server/server-config.js +24 -4
  91. package/dist/server/server.js +107 -12
  92. package/dist/server/service-runs.js +42 -4
  93. package/dist/server/sources.js +68 -11
  94. package/dist/utils/buffer-context.js +30 -20
  95. package/dist/utils/line-splitter.js +52 -0
  96. package/dist/utils/read-lines.js +65 -0
  97. package/dist/utils/tar.js +51 -1
  98. package/package.json +1 -1
  99. package/dist/dashboard/assets/index-gIBDC_m8.css +0 -2
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.dockerServiceRuntime = exports.dockerTaskRuntime = void 0;
3
+ exports.dockerServiceRuntime = exports.getCacheHelperOptions = exports.dockerTaskRuntime = void 0;
4
4
  const run_labels_1 = require("../docker/run-labels");
5
5
  const execute_docker_1 = require("../executer/execute-docker");
6
6
  const remove_container_1 = require("../docker/remove-container");
@@ -11,12 +11,12 @@ const using_container_1 = require("../docker/using-container");
11
11
  const event_cache_1 = require("../executer/event-cache");
12
12
  const get_docker_executor_1 = require("../executer/get-docker-executor");
13
13
  const path_1 = require("path");
14
- const tar_1 = require("tar");
15
- const tar_2 = require("../utils/tar");
14
+ const tar_1 = require("../utils/tar");
16
15
  const plan_work_volume_1 = require("./utils/plan-work-volume");
17
16
  const work_instance_id_1 = require("./work-instance-id");
18
17
  const stream_1 = require("stream");
19
18
  const service_definition_1 = require("./service-definition");
19
+ const image_build_1 = require("./image-build");
20
20
  const container_task_state_1 = require("../executer/container-task-state");
21
21
  const item_network_1 = require("../docker/item-network");
22
22
  const execution_steps_1 = require("../executer/execution-steps");
@@ -78,6 +78,13 @@ function dockerTaskRuntime(task, workEnvironment) {
78
78
  async remove(environment) {
79
79
  await this.stop();
80
80
  await (0, container_task_state_1.removeContainerTaskState)(environment, task);
81
+ // the layers BuildKit kept for the task's builds (see getBuildKitBinds)
82
+ if (task.data.build && !environment.hosted) {
83
+ const buildKitVolume = (0, image_build_1.getBuildKitVolumeName)(task.data);
84
+ if (await (0, get_docker_executor_1.existsVolume)(docker, buildKitVolume)) {
85
+ await (0, get_docker_executor_1.removeVolume)(docker, task.status, buildKitVolume);
86
+ }
87
+ }
81
88
  for (const generate of task.data.generates) {
82
89
  if (generate.inherited) {
83
90
  continue;
@@ -117,20 +124,11 @@ exports.dockerTaskRuntime = dockerTaskRuntime;
117
124
  function isOnHost(generate) {
118
125
  return generate.isFile || generate.export;
119
126
  }
120
- async function restoreContainer(docker, environment, item, path) {
121
- await (0, execution_steps_1.refuseHostLinks)(item, environment);
122
- // on a server the volumes the outputs are restored into carry the run's files, so they
123
- // are removed with a sandbox
124
- const root = (0, execution_steps_1.hostedRoot)(environment);
125
- if (root) {
126
- const names = item.data.type === 'container-service'
127
- ? item.data.volumes.filter((v) => !v.inherited).map((v) => v.name)
128
- : item.data.generates.filter((v) => !v.inherited && !v.isFile).map((v) => v.volumeName);
129
- for (const name of names) {
130
- await (0, get_docker_executor_1.ensureVolumeExists)(docker, item.status, name, (0, get_docker_executor_1.volumeLabels)(root));
131
- }
132
- }
133
- await (0, using_container_1.usingContainer)(docker, item, {
127
+ // The container that copies an item's outputs into and out of its volumes for the cache:
128
+ // the item's image with those volumes mounted, kept running while archives go in or out.
129
+ // The image is the item's, so whatever its network, this step has none.
130
+ function getCacheHelperOptions(item, environment) {
131
+ return {
134
132
  abortSignal: environment.abortCtrl.signal,
135
133
  Image: item.data.image,
136
134
  Tty: true,
@@ -145,19 +143,41 @@ async function restoreContainer(docker, environment, item, path) {
145
143
  },
146
144
  HostConfig: {
147
145
  AutoRemove: true,
148
- // mount the same volumes archiveContainer reads from, so the restored
149
- // archives land in the task's output volumes rather than in this
150
- // throwaway container's filesystem
146
+ NetworkMode: 'none',
147
+ // the item's own output volumes, so restored archives land there rather than in
148
+ // this throwaway container's filesystem
151
149
  Binds: item.data.type === 'container-service'
152
- ? item.data.volumes
153
- .filter((v) => !v.inherited)
154
- .map((v) => `${v.name}:${(0, execute_docker_1.convertToPosixPath)(v.containerPath)}`)
150
+ ? item.data.volumes.filter((v) => !v.inherited).map((v) => `${v.name}:${(0, execute_docker_1.convertToPosixPath)(v.containerPath)}`)
155
151
  : item.data.generates
156
152
  .filter((v) => !v.inherited && !v.isFile)
157
153
  .map((v) => `${v.volumeName}:${(0, execute_docker_1.convertToPosixPath)(v.path)}`),
158
154
  },
159
- }, async (container) => {
155
+ };
156
+ }
157
+ exports.getCacheHelperOptions = getCacheHelperOptions;
158
+ async function restoreContainer(docker, environment, item, path) {
159
+ await (0, execution_steps_1.refuseHostLinks)(item, environment);
160
+ // on a server the volumes the outputs are restored into carry the run's files, so they
161
+ // are removed with a sandbox
162
+ const root = (0, execution_steps_1.hostedRoot)(environment);
163
+ if (root) {
164
+ const names = item.data.type === 'container-service'
165
+ ? item.data.volumes.filter((v) => !v.inherited).map((v) => v.name)
166
+ : item.data.generates.filter((v) => !v.inherited && !v.isFile).map((v) => v.volumeName);
167
+ for (const name of names) {
168
+ await (0, get_docker_executor_1.ensureVolumeExists)(docker, item.status, name, (0, get_docker_executor_1.volumeLabels)(root));
169
+ }
170
+ }
171
+ await (0, using_container_1.usingContainer)(docker, item, getCacheHelperOptions(item, environment), async (container) => {
172
+ // a file output is a bind of a host file, restored on the host below; its folder (as
173
+ // `.images` of `.images/app`) is not in this container
174
+ const files = new Set(item.data.type === 'container-task'
175
+ ? item.data.generates.filter((g) => !g.inherited && g.isFile).map((g) => g.path)
176
+ : []);
160
177
  for (const generate of (0, event_cache_1.getArchivePaths)(item.data, path)) {
178
+ if (files.has(generate.path)) {
179
+ continue;
180
+ }
161
181
  if (await environment.file.exists(generate.filename)) {
162
182
  // a cache hit means exactly the stored outputs: whatever a failed or
163
183
  // older run left in the volume goes first
@@ -174,7 +194,8 @@ async function restoreContainer(docker, environment, item, path) {
174
194
  for (const generate of (0, event_cache_1.getArchivePaths)(item.data, path)) {
175
195
  if (onHost.has(generate.path) && (await environment.file.exists(generate.filename))) {
176
196
  await environment.file.remove(generate.path);
177
- await (0, tar_1.extract)({ file: generate.filename, cwd: (0, path_1.dirname)(generate.path) });
197
+ await environment.file.createDirectory((0, path_1.dirname)(generate.path));
198
+ await (0, tar_1.extractOutput)(generate.filename, (0, path_1.dirname)(generate.path), (0, path_1.basename)(generate.path), !!environment.hosted);
178
199
  }
179
200
  }
180
201
  }
@@ -273,37 +294,14 @@ function dockerServiceRuntime(service, workEnvironment) {
273
294
  exports.dockerServiceRuntime = dockerServiceRuntime;
274
295
  async function archiveContainer(docker, environment, item, path) {
275
296
  await (0, execution_steps_1.refuseHostLinks)(item, environment);
276
- await (0, using_container_1.usingContainer)(docker, item, {
277
- abortSignal: environment.abortCtrl.signal,
278
- Image: item.data.image,
279
- Tty: true,
280
- Entrypoint: ['sh'],
281
- Cmd: ['-c', 'sleep 3600'],
282
- WorkingDir: (0, execute_docker_1.convertToPosixPath)(item.data.cwd),
283
- Labels: {
284
- app: 'hammerkit',
285
- 'hammerkit-id': (0, work_instance_id_1.getWorkInstanceId)(item),
286
- ...(0, run_labels_1.getRunLabels)(),
287
- 'hammerkit-type': 'task',
288
- },
289
- HostConfig: {
290
- AutoRemove: true,
291
- Binds: item.data.type === 'container-service'
292
- ? item.data.volumes
293
- .filter((v) => !v.inherited)
294
- .map((v) => `${v.name}:${(0, execute_docker_1.convertToPosixPath)(v.containerPath)}`)
295
- : item.data.generates
296
- .filter((v) => !v.inherited && !v.isFile)
297
- .map((v) => `${v.volumeName}:${(0, execute_docker_1.convertToPosixPath)(v.path)}`),
298
- },
299
- }, async (container) => {
297
+ await (0, using_container_1.usingContainer)(docker, item, getCacheHelperOptions(item, environment), async (container) => {
300
298
  const hostFiles = new Set(item.data.type === 'container-task'
301
299
  ? item.data.generates.filter((g) => !g.inherited && g.isFile).map((g) => g.path)
302
300
  : []);
303
301
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(item.data, path)) {
304
302
  // a file output is a bind mount of a host file, so archive it from the host
305
303
  const readable = hostFiles.has(generatedArchive.path)
306
- ? stream_1.Readable.from((0, tar_2.packArchive)({ cwd: (0, path_1.dirname)(generatedArchive.path) }, [(0, path_1.basename)(generatedArchive.path)]))
304
+ ? stream_1.Readable.from((0, tar_1.packArchive)({ cwd: (0, path_1.dirname)(generatedArchive.path) }, [(0, path_1.basename)(generatedArchive.path)]))
307
305
  : await container.getArchive({
308
306
  path: generatedArchive.path,
309
307
  });
@@ -388,6 +388,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
388
388
  await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, spec.metadata.name, options.abort, 1000, {
389
389
  onWaiting: (text) => task.status.write('warn', `${task.name} ${text}`),
390
390
  timeout: ensure_persistent_data_1.QUOTA_TIMEOUT,
391
+ onRefused: options.onQuotaRefused,
391
392
  });
392
393
  }
393
394
  catch (e) {
@@ -4,8 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getLocalWorkRuntime = exports.getStateFilename = void 0;
7
- const tar_1 = require("tar");
8
- const tar_2 = require("../utils/tar");
7
+ const tar_1 = require("../utils/tar");
9
8
  const path_1 = require("path");
10
9
  const local_task_1 = require("../executer/local-task");
11
10
  const event_cache_1 = require("../executer/event-cache");
@@ -122,7 +121,7 @@ async function archiveLocal(environment, task, path) {
122
121
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(task.data, path)) {
123
122
  await environment.file.writeStream(generatedArchive.filename,
124
123
  // tar's stream is a Minipass stream; Readable.from adapts it to a Node one
125
- stream_1.Readable.from((0, tar_2.packArchive)({ cwd: task.data.cwd, gzip: true }, [(0, path_1.relative)(task.data.cwd, generatedArchive.path)])));
124
+ stream_1.Readable.from((0, tar_1.packArchive)({ cwd: task.data.cwd, gzip: true }, [(0, path_1.relative)(task.data.cwd, generatedArchive.path)])));
126
125
  }
127
126
  }
128
127
  async function restoreLocal(environment, task, path) {
@@ -131,10 +130,7 @@ async function restoreLocal(environment, task, path) {
131
130
  // a cache hit means exactly the stored outputs: whatever a failed or
132
131
  // older run left in the folder goes first
133
132
  await environment.file.remove(generate.path);
134
- await (0, tar_1.extract)({
135
- file: generate.filename,
136
- cwd: task.cwd,
137
- });
133
+ await (0, tar_1.extractOutput)(generate.filename, task.cwd, (0, path_1.relative)(task.cwd, generate.path), !!environment.hosted);
138
134
  }
139
135
  }
140
136
  }
@@ -8,6 +8,7 @@ const normalize_path_1 = require("./utils/normalize-path");
8
8
  const template_value_1 = require("./utils/template-value");
9
9
  const portable_path_1 = require("./utils/portable-path");
10
10
  const abort_1 = require("../executer/abort");
11
+ const secret_catalog_1 = require("../secrets/secret-catalog");
11
12
  const provider_values_1 = require("../secrets/provider-values");
12
13
  // Where the value comes from, for messages and for what makes a service
13
14
  // different: never the value.
@@ -30,6 +31,8 @@ function getPortableSecretName(projectRoot, secret) {
30
31
  }
31
32
  exports.getPortableSecretName = getPortableSecretName;
32
33
  function parseWorkSecrets(cwd, projectRoot, secrets, envs, environment, catalog,
34
+ // what the secrets belong to, for messages: `task build` or `service db`
35
+ owner,
33
36
  // the service account of the task or service the secrets belong to
34
37
  account) {
35
38
  return (secrets ?? []).map((secret) => {
@@ -38,7 +41,7 @@ account) {
38
41
  ? { type: 'env', name: secret.env }
39
42
  : { type: 'file', path: (0, normalize_path_1.normalizePath)(cwd, cwd, (0, template_value_1.templateValue)(secret.path ?? '', envs)) };
40
43
  const name = target.type === 'env' ? target.name : secret.path;
41
- const source = parseSecretSource(secret, ref, cwd, envs, catalog, account, `secret ${name}`);
44
+ const source = parseSecretSource(secret, ref, cwd, envs, catalog, account, owner, `secret ${name}`);
42
45
  const workSecret = {
43
46
  source,
44
47
  target,
@@ -49,7 +52,7 @@ account) {
49
52
  });
50
53
  }
51
54
  exports.parseWorkSecrets = parseWorkSecrets;
52
- function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label) {
55
+ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, owner, label) {
53
56
  const kind = secret.from.substring(0, secret.from.indexOf(':'));
54
57
  if (kind === 'env') {
55
58
  return { type: 'env', name: ref };
@@ -57,30 +60,29 @@ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label)
57
60
  if (kind === 'file') {
58
61
  return { type: 'file', path: (0, normalize_path_1.normalizePath)(cwd, (0, os_1.homedir)(), (0, template_value_1.templateValue)(ref, envs)) };
59
62
  }
60
- const provider = catalog.providers[kind];
63
+ const reads = `${owner} reads ${label} from ${secret.from}`;
64
+ const provider = (0, secret_catalog_1.declared)(catalog.providers, kind);
61
65
  if (!provider) {
62
- const declared = Object.keys(catalog.providers);
63
- throw new Error(`${label}: unknown secret provider ${kind}, ${declared.length > 0 ? `declared: ${declared.join(', ')}` : 'none is declared'}`);
66
+ throw new Error(unknownProviderMessage(catalog, reads, kind));
64
67
  }
65
68
  const providerRef = (0, template_value_1.templateValue)(ref, envs);
66
69
  if (providerRef.length === 0 || providerRef.startsWith('-')) {
67
- throw new Error(`${label}: a reference for ${kind} must not be empty or start with -`);
70
+ throw new Error(`${reads}: a reference for ${kind} must not be empty or start with -`);
68
71
  }
69
72
  const accountName = catalog.explicitAccounts
70
73
  ? secret.account
71
74
  : secret.account ?? taskAccount ?? Object.values(catalog.accounts).find((a) => a.default)?.name;
72
75
  if (!accountName) {
73
- throw new Error(catalog.explicitAccounts
74
- ? `${label}: ${kind}:${providerRef} needs account: on the secret, a server uses neither a task's account nor a default`
75
- : `${label}: ${kind}:${providerRef} needs an account, and none is named or marked default: true`);
76
+ throw new Error(missingAccountMessage(catalog, reads, owner));
76
77
  }
77
- const account = catalog.accounts[accountName];
78
+ const account = (0, secret_catalog_1.declared)(catalog.accounts, accountName);
78
79
  if (!account) {
79
- throw new Error(`${label}: unknown secret account ${accountName}, declared: ${Object.keys(catalog.accounts).join(', ') || 'none'}`);
80
+ const namedBy = secret.account ? 'the account: of the secret' : `the account: of ${owner}`;
81
+ throw new Error(unknownAccountMessage(catalog, reads, owner, accountName, namedBy, kind));
80
82
  }
81
- const credentials = account.providers[kind];
83
+ const credentials = (0, secret_catalog_1.declared)(account.providers, kind);
82
84
  if (!credentials) {
83
- throw new Error(`${label}: account ${accountName} has no credentials for provider ${kind}`);
85
+ throw new Error(missingCredentialsMessage(catalog, reads, account, kind));
84
86
  }
85
87
  return {
86
88
  type: 'provider',
@@ -90,6 +92,126 @@ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label)
90
92
  binding: { definition: provider, account: { name: accountName, env: credentials.env } },
91
93
  };
92
94
  }
95
+ // The messages below say what is wrong, where the names come from and what to write: a
96
+ // person who only ran a task should not need to know how secrets are declared. On a
97
+ // server the build file can only change what it names, the operator declares the rest.
98
+ const SECRET_PROVIDERS_DOCS = 'https://hammerkit.dev/docs/task/secret-providers';
99
+ // `tests, dev in ~/.hammerkit/config.yaml and ci in .hammerkit.yaml`, or `none`
100
+ function listDeclared(definitions, server) {
101
+ if (definitions.length === 0) {
102
+ return 'none';
103
+ }
104
+ if (server) {
105
+ return definitions.map((d) => d.name).join(', ');
106
+ }
107
+ const byFile = new Map();
108
+ for (const definition of definitions) {
109
+ byFile.set(definition.declaredIn, [...(byFile.get(definition.declaredIn) ?? []), definition.name]);
110
+ }
111
+ return [...byFile.entries()].map(([file, names]) => `${names.join(', ')} in ${file}`).join(' and ');
112
+ }
113
+ // A build file is checked as a whole when it is read, so one wrong secret stops
114
+ // the tasks that don't read it, too.
115
+ function seeDocs(anchor) {
116
+ return `Every task of the build file is checked when it is read, so this stops other tasks too. See ${SECRET_PROVIDERS_DOCS}#${anchor}`;
117
+ }
118
+ function hostConfigOf(catalog) {
119
+ return catalog.hostConfig ?? 'the host config';
120
+ }
121
+ function indent(lines) {
122
+ return lines.map((line) => ` ${line}`).join('\n');
123
+ }
124
+ // A variable of this machine to hold the credential, for snippets: `${OPERATOR_CREDENTIALS}`
125
+ function credentialVariable(account, key, keys) {
126
+ const prefix = account.toUpperCase().replace(/[^A-Z0-9]+/g, '_');
127
+ return `\${${prefix}_${keys === 1 ? 'CREDENTIALS' : key}}`;
128
+ }
129
+ // The credential variables a provider's command reads, as another account passes them;
130
+ // a placeholder when no account has credentials for the provider yet
131
+ function credentialLines(catalog, account, provider) {
132
+ const sibling = Object.values(catalog.accounts).find((a) => (0, secret_catalog_1.declared)(a.providers, provider));
133
+ const keys = sibling ? Object.keys(sibling.providers[provider].env) : [];
134
+ if (keys.length === 0) {
135
+ return [`<VARIABLE>: \${<VARIABLE OF THIS MACHINE>} # what ${provider} reads its credential from`];
136
+ }
137
+ return keys.map((key) => `${key}: ${credentialVariable(account, key, keys.length)}`);
138
+ }
139
+ function unknownProviderMessage(catalog, reads, kind) {
140
+ const declaredProviders = listDeclared(Object.values(catalog.providers), !!catalog.explicitAccounts);
141
+ if (catalog.explicitAccounts) {
142
+ return (`${reads}, but this server has no secret provider ${kind} (it has: ${declaredProviders}). ` +
143
+ `Use one of its providers, or ask the operator of the server to add ${kind} to its config.`);
144
+ }
145
+ return [
146
+ `${reads}, but no secret provider ${kind} is declared (declared: ${declaredProviders}).`,
147
+ `A provider is the command that prints a secret's value. Declare it in the host config, ${hostConfigOf(catalog)}:`,
148
+ '',
149
+ indent(['secretProviders:', ` ${kind}:`, ` command: [<command>, <its arguments>, '{{ref}}']`]),
150
+ '',
151
+ seeDocs('providers'),
152
+ ].join('\n');
153
+ }
154
+ function missingAccountMessage(catalog, reads, owner) {
155
+ const declaredAccounts = listDeclared(Object.values(catalog.accounts), !!catalog.explicitAccounts);
156
+ if (catalog.explicitAccounts) {
157
+ return (`${reads}, but names no account. A server reads every secret as the account the secret names, ` +
158
+ `never as the account of a task or a default: add account: to the secret (this server has: ${declaredAccounts}).`);
159
+ }
160
+ return [
161
+ `${reads}, but neither the secret nor ${owner} names an account, and no account is marked default: true (declared: ${declaredAccounts}).`,
162
+ `An account says which credential a secret is read with. Name one with account: on the secret or on ${owner}, ` +
163
+ `or mark one as the default in ${hostConfigOf(catalog)}:`,
164
+ '',
165
+ indent(['secretAccounts:', ' <account>:', ' default: true']),
166
+ '',
167
+ seeDocs('accounts'),
168
+ ].join('\n');
169
+ }
170
+ function unknownAccountMessage(catalog, reads, owner, account, namedBy, provider) {
171
+ const declaredAccounts = listDeclared(Object.values(catalog.accounts), !!catalog.explicitAccounts);
172
+ if (catalog.explicitAccounts) {
173
+ return (`${reads} as account ${account}, but this server has no account ${account} (it has: ${declaredAccounts}). ` +
174
+ `Name one of its accounts with account: on the secret, or ask the operator of the server to add ${account} to its config.`);
175
+ }
176
+ return [
177
+ `${reads} as account ${account} (${namedBy}), but no account ${account} is declared (declared: ${declaredAccounts}).`,
178
+ `An account says which credential a secret is read with, and each machine declares its own in its host config, ` +
179
+ `${hostConfigOf(catalog)}. Add ${account} there:`,
180
+ '',
181
+ indent([
182
+ 'secretAccounts:',
183
+ ` ${account}:`,
184
+ ' providers:',
185
+ ` ${provider}:`,
186
+ ' env:',
187
+ ...credentialLines(catalog, account, provider).map((line) => ` ${line}`),
188
+ ]),
189
+ '',
190
+ `Or read the secret as one of the declared accounts with account: on the secret${namedBy === 'the account: of the secret' ? '' : ` or on ${owner}`}.`,
191
+ seeDocs('accounts'),
192
+ ].join('\n');
193
+ }
194
+ function missingCredentialsMessage(catalog, reads, account, provider) {
195
+ if (catalog.explicitAccounts) {
196
+ return (`${reads} as account ${account.name}, but that account of this server has no credentials for ${provider}. ` +
197
+ `Ask the operator of the server to add them to its config.`);
198
+ }
199
+ return [
200
+ `${reads} as account ${account.name}, but account ${account.name} (in ${account.declaredIn}) has no credentials for provider ${provider}.`,
201
+ `Add the variables that make ${provider} act as ${account.name}:`,
202
+ '',
203
+ indent([
204
+ 'secretAccounts:',
205
+ ` ${account.name}:`,
206
+ ' providers:',
207
+ ` ${provider}:`,
208
+ ' env:',
209
+ ...credentialLines(catalog, account.name, provider).map((line) => ` ${line}`),
210
+ ]),
211
+ '',
212
+ seeDocs('accounts'),
213
+ ].join('\n');
214
+ }
93
215
  function readSecretValueSync(secret, environment) {
94
216
  if (secret.source.type === 'env') {
95
217
  const value = environment.processEnvs[secret.source.name];
@@ -1,3 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isAskedByName = void 0;
4
+ // Whether a task was asked for by name: one of the tasks named, or the one task the run
5
+ // was asked for. An init task asked for by name starts its service and runs.
6
+ function isAskedByName(workTree, name) {
7
+ if (workTree.named) {
8
+ return workTree.named.includes(name);
9
+ }
10
+ return workTree.requested?.length === 1 && workTree.requested[0] === name;
11
+ }
12
+ exports.isAskedByName = isAskedByName;
3
13
  //# sourceMappingURL=work-tree.js.map
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.collectBundle = void 0;
4
+ const promises_1 = require("node:fs/promises");
4
5
  const path_1 = require("path");
5
6
  const resolve_git_source_1 = require("../includes/resolve-git-source");
6
7
  const schema_parser_1 = require("../schema/schema-parser");
@@ -10,7 +11,10 @@ const bundle_1 = require("./bundle");
10
11
  // The build file is read with the parser of a run, so what it pulls in is what a
11
12
  // run would read. Git includes are not part of it (the server fetches them, at
12
13
  // the commit they are pinned to), and neither is anything outside of the
13
- // directory of the build file, which a server could not reproduce.
14
+ // directory of the build file, which a server could not reproduce. That holds for
15
+ // where a file really is too: a link to a file outside of the directory is refused
16
+ // rather than followed, so publishing a checkout never sends a file of this machine
17
+ // that the checkout only points to.
14
18
  async function collectBundle(fileName, environment) {
15
19
  if (!(await environment.file.exists(fileName))) {
16
20
  throw new Error(`there is no build file at ${fileName}`);
@@ -24,11 +28,15 @@ async function collectBundle(fileName, environment) {
24
28
  paths.add((0, path_1.resolve)(scope.fileName));
25
29
  }
26
30
  }
31
+ const realRoot = await (0, promises_1.realpath)(root);
27
32
  const files = {};
28
33
  for (const path of [...paths].sort()) {
29
34
  if (!(0, resolve_git_source_1.isWithin)(root, path)) {
30
35
  throw new Error(`${path} is outside of ${root}: a published build file can only include files below its own directory`);
31
36
  }
37
+ if (!(0, resolve_git_source_1.isWithin)(realRoot, await (0, promises_1.realpath)(path))) {
38
+ throw new Error(`${path} links to a file outside of ${root}: a published build file can only include files below its own directory`);
39
+ }
32
40
  files[(0, path_1.relative)(root, path).split(path_1.sep).join('/')] = await environment.file.read(path);
33
41
  }
34
42
  const result = bundle_1.bundleSchema.safeParse({ entry: (0, path_1.relative)(root, entryPath).split(path_1.sep).join('/'), files });
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.pinLogin = exports.setDefaultLocation = exports.removeServer = exports.addServer = exports.normalizeServerUrl = exports.validateServerName = exports.writeHostConfig = exports.readHostConfig = exports.getHostConfigPath = exports.getRegisteredServer = exports.getTokenCommand = exports.hasServer = exports.hostConfigSchema = exports.hostServerSchema = exports.RESERVED_SERVER_NAMES = void 0;
3
+ exports.pinLogin = exports.setDefaultLocation = exports.removeServer = exports.addServer = exports.normalizeServerUrl = exports.validateServerName = exports.writeHostConfig = exports.readHostConfig = exports.getHostConfigPath = exports.chooseServer = exports.notRegisteredMessage = exports.getRegisteredServer = exports.getTokenCommand = exports.hasServer = exports.hostConfigSchema = exports.hostServerSchema = exports.RESERVED_SERVER_NAMES = void 0;
4
4
  const path_1 = require("path");
5
5
  const zod_1 = require("zod");
6
6
  const yaml_1 = require("yaml");
@@ -69,6 +69,52 @@ function getRegisteredServer(config, name) {
69
69
  return { ...config.servers[name], ...(tokenCommand ? { tokenCommand } : {}) };
70
70
  }
71
71
  exports.getRegisteredServer = getRegisteredServer;
72
+ // `a, b and c`
73
+ function listNames(names) {
74
+ return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` : names.join('');
75
+ }
76
+ // `(registered: a and b)`, for a name that is not one of them
77
+ function registeredNote(config) {
78
+ const names = Object.keys(config.servers).sort();
79
+ return names.length === 0 ? '(no server is registered yet)' : `(registered: ${listNames(names)})`;
80
+ }
81
+ // `server nope is not registered (registered: a and b)`, with how to add it unless it is being removed
82
+ function notRegisteredMessage(config, name, howToAdd = true) {
83
+ const add = howToAdd ? `, add it with: hammerkit remote add ${name} <url> --issuer <url>` : '';
84
+ return `server ${name} is not registered ${registeredNote(config)}${add}`;
85
+ }
86
+ exports.notRegisteredMessage = notRegisteredMessage;
87
+ // The server a remote command talks to: the one it names, else the default of `remote use`,
88
+ // else the only one registered. With several and no default, the person names one.
89
+ // A default that names a server no longer registered is an error, as it is for `hammerkit run`:
90
+ // a call never goes to another server than the one chosen. `how` says how a name is given,
91
+ // for the message: `with --server <name>`.
92
+ function chooseServer(config, name, how = 'as the last argument') {
93
+ if (name !== undefined) {
94
+ if (!hasServer(config.servers, name)) {
95
+ throw new Error(notRegisteredMessage(config, name));
96
+ }
97
+ return name;
98
+ }
99
+ const on = config.run.on;
100
+ if (on && !exports.RESERVED_SERVER_NAMES.includes(on)) {
101
+ if (!hasServer(config.servers, on)) {
102
+ throw new Error(`the default of remote use, server ${on}, is not registered ${registeredNote(config)}; ` +
103
+ `pick another with: hammerkit remote use <name>, or add it with: hammerkit remote add ${on} <url> --issuer <url>`);
104
+ }
105
+ return on;
106
+ }
107
+ const names = Object.keys(config.servers).sort();
108
+ if (names.length === 1) {
109
+ return names[0];
110
+ }
111
+ if (names.length === 0) {
112
+ throw new Error('no server is registered, add one with: hammerkit remote add <name> <url> --issuer <url>');
113
+ }
114
+ throw new Error(`${names.length} servers are registered (${listNames(names)}), name one ${how}, ` +
115
+ `or make one the default with: hammerkit remote use <name>`);
116
+ }
117
+ exports.chooseServer = chooseServer;
72
118
  function setTokenCommand(config, name, entry) {
73
119
  const commands = { ...(config.tokenCommands ?? {}) };
74
120
  if (entry) {
@@ -201,7 +247,7 @@ exports.addServer = addServer;
201
247
  async function removeServer(environment, name) {
202
248
  const config = await readHostConfig(environment);
203
249
  if (!hasServer(config.servers, name)) {
204
- throw new Error(`server "${name}" is not registered`);
250
+ throw new Error(notRegisteredMessage(config, name, false));
205
251
  }
206
252
  delete config.servers[name];
207
253
  setTokenCommand(config, name, undefined);
@@ -216,7 +262,7 @@ exports.removeServer = removeServer;
216
262
  async function setDefaultLocation(environment, on) {
217
263
  const config = await readHostConfig(environment);
218
264
  if (!exports.RESERVED_SERVER_NAMES.includes(on) && !hasServer(config.servers, on)) {
219
- throw new Error(`server "${on}" is not registered; add it with: hammerkit remote add ${on} <url> --issuer <url>`);
265
+ throw new Error(notRegisteredMessage(config, on));
220
266
  }
221
267
  config.run.on = on;
222
268
  await writeHostConfig(environment, config);
@@ -14,7 +14,7 @@ async function resolveRunLocation(workTree, environment, options = {}) {
14
14
  const config = await (0, host_config_1.readHostConfig)(environment);
15
15
  const explicit = options.local ? 'local' : options.on ?? (environment.processEnvs.HAMMERKIT_ON || undefined);
16
16
  if (explicit && explicit !== 'auto') {
17
- return explicit === 'local' ? { type: 'local' } : lookup(config.servers, explicit);
17
+ return explicit === 'local' ? { type: 'local' } : lookup(config, explicit);
18
18
  }
19
19
  const runners = getTaskRunners(workTree);
20
20
  if (runners.length > 1) {
@@ -24,13 +24,13 @@ async function resolveRunLocation(workTree, environment, options = {}) {
24
24
  if (!requested || requested === 'local' || requested === 'auto') {
25
25
  return { type: 'local' };
26
26
  }
27
- return lookup(config.servers, requested);
27
+ return lookup(config, requested);
28
28
  }
29
29
  exports.resolveRunLocation = resolveRunLocation;
30
- function lookup(servers, name) {
31
- const server = (0, host_config_1.hasServer)(servers, name) ? servers[name] : undefined;
30
+ function lookup(config, name) {
31
+ const server = (0, host_config_1.hasServer)(config.servers, name) ? config.servers[name] : undefined;
32
32
  if (!server) {
33
- throw new Error(`server ${name} is not registered, add it with: hammerkit remote add ${name} <url> --issuer <url>`);
33
+ throw new Error((0, host_config_1.notRegisteredMessage)(config, name));
34
34
  }
35
35
  return { type: 'server', name, server };
36
36
  }
@@ -94,21 +94,17 @@ passthrough = []) {
94
94
  await (0, host_config_1.setDefaultLocation)(environment, location);
95
95
  environment.stdout.write(`default location: ${location}\n`);
96
96
  }));
97
- const getServer = async (name) => {
97
+ // a command that takes a server: the named one, the default or the only one, see chooseServer
98
+ const getServer = async (name, how) => {
98
99
  const config = await (0, host_config_1.readHostConfig)(environment);
99
- const chosen = name ?? config.run.on;
100
- if (!chosen || !(0, host_config_1.hasServer)(config.servers, chosen)) {
101
- throw new Error(name
102
- ? `server ${name} is not registered, add it with: hammerkit remote add ${name} <url> --issuer <url>`
103
- : 'name a server, or set one as the default with: hammerkit remote use <name>');
104
- }
100
+ const chosen = (0, host_config_1.chooseServer)(config, name, how);
105
101
  return { name: chosen, server: (0, host_config_1.getRegisteredServer)(config, chosen) };
106
102
  };
107
103
  remote
108
- .command('login <name>')
109
- .description('sign in to a registered server with your identity provider (device code, works headless)')
110
- .action(guarded('Remote login was not successful', async (name) => {
111
- const { server } = await getServer(name);
104
+ .command('login [name]')
105
+ .description('sign in to a registered server with your identity provider (device code, works headless); the name can be left out when only one server is registered or one is set with remote use')
106
+ .action(guarded('Remote login was not successful', async (given) => {
107
+ const { name, server } = await getServer(given);
112
108
  if (server.tokenCommand) {
113
109
  // a sign-in would never be used: the command's token goes first
114
110
  throw new Error(`${name} takes its tokens from its token command (${server.tokenCommand}), it needs no sign-in; ` +
@@ -145,9 +141,11 @@ passthrough = []) {
145
141
  }
146
142
  }));
147
143
  remote
148
- .command('logout <name>')
149
- .description('forget the sign-in to a server')
150
- .action(guarded('Remote logout was not successful', async (name) => {
144
+ .command('logout [name]')
145
+ .description('forget the sign-in to a server; the name can be left out as for login')
146
+ .action(guarded('Remote logout was not successful', async (given) => {
147
+ // a sign-in outlives its server's registration, so a name given is taken as it is
148
+ const name = given ?? (0, host_config_1.chooseServer)(await (0, host_config_1.readHostConfig)(environment), undefined);
151
149
  const removed = await (0, credentials_1.removeToken)(environment, name);
152
150
  environment.stdout.write(removed ? `signed out of ${name}\n` : `not signed in to ${name}\n`);
153
151
  }));