overvues 0.0.1 → 0.4.10

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 (78) hide show
  1. package/README.md +58 -2
  2. package/dist/ansi.js +24 -0
  3. package/dist/attach-client.js +586 -0
  4. package/dist/auth-connect-browser.js +112 -0
  5. package/dist/auth-connect.js +306 -0
  6. package/dist/browser-bootstrap.js +190 -0
  7. package/dist/browser-loopback.js +289 -0
  8. package/dist/build-identity.js +6 -0
  9. package/dist/codex-reviewer-apparmor.json +4 -0
  10. package/dist/codex-reviewer-seccomp.json +1238 -0
  11. package/dist/codex-runtime-protocol.js +1 -0
  12. package/dist/codex-subscription.js +53 -0
  13. package/dist/config.js +297 -0
  14. package/dist/connect-comparison-code.js +26 -0
  15. package/dist/development-runner.js +109 -0
  16. package/dist/dns-doctor.js +390 -0
  17. package/dist/docker-names.js +47 -0
  18. package/dist/doctor.js +114 -0
  19. package/dist/gadget-job.js +804 -0
  20. package/dist/health-check.js +112 -0
  21. package/dist/help.js +71 -0
  22. package/dist/host-auth.js +22 -0
  23. package/dist/host-diagnostics.js +20 -0
  24. package/dist/host-runtime-identity.js +39 -0
  25. package/dist/host-runtime-metadata.js +56 -0
  26. package/dist/host-service.js +377 -0
  27. package/dist/host-stack.js +484 -0
  28. package/dist/host-supervisor.js +237 -0
  29. package/dist/host-update.js +387 -0
  30. package/dist/hub-address.js +100 -0
  31. package/dist/hub-client.js +459 -0
  32. package/dist/hub-kind.js +88 -0
  33. package/dist/identity.js +73 -0
  34. package/dist/index.js +185 -0
  35. package/dist/init.js +295 -0
  36. package/dist/isolated-run-cache.js +116 -0
  37. package/dist/local-stack.js +685 -0
  38. package/dist/machine-capacity.js +128 -0
  39. package/dist/managed-runner-image.js +13 -0
  40. package/dist/os-acted-record.js +49 -0
  41. package/dist/os-adapter.js +8190 -0
  42. package/dist/os-command.js +292 -0
  43. package/dist/os-handoff.js +274 -0
  44. package/dist/os-keychain.js +247 -0
  45. package/dist/os-machine.js +818 -0
  46. package/dist/os-owner.js +61 -0
  47. package/dist/os-private-file.js +98 -0
  48. package/dist/os-protocol.js +468 -0
  49. package/dist/os-session-store.js +133 -0
  50. package/dist/os-status.js +102 -0
  51. package/dist/picker.js +863 -0
  52. package/dist/portable-workspace-capability.js +60 -0
  53. package/dist/project-environment-capability.js +62 -0
  54. package/dist/project-environment.js +28 -0
  55. package/dist/project-preparation.js +134 -0
  56. package/dist/readiness.js +28 -0
  57. package/dist/redaction.js +27 -0
  58. package/dist/reviewer-isolation-capability.js +61 -0
  59. package/dist/runner-api-auth.js +80 -0
  60. package/dist/runner-command-fence.js +536 -0
  61. package/dist/runner-inspection.js +57 -0
  62. package/dist/runner-inventory.js +587 -0
  63. package/dist/runner-server.js +2520 -0
  64. package/dist/runner-session.js +470 -0
  65. package/dist/runner-slug-folder.js +39 -0
  66. package/dist/runner-slug.js +40 -0
  67. package/dist/setup.js +139 -0
  68. package/dist/shutdown.js +102 -0
  69. package/dist/splash.js +65 -0
  70. package/dist/staged-workspaces.js +441 -0
  71. package/dist/staging-disk.js +97 -0
  72. package/dist/terminal-lane.js +339 -0
  73. package/dist/terminal-recovery.js +502 -0
  74. package/licenses/capnweb.txt +23 -0
  75. package/licenses/moby-profiles.txt +212 -0
  76. package/licenses/ws.txt +22 -0
  77. package/package.json +28 -7
  78. package/cli.js +0 -2
@@ -0,0 +1,60 @@
1
+ import { spawnSync } from "node:child_process";
2
+ const IMAGE_ID = /^sha256:[a-f0-9]{64}$/;
3
+ const RESTORE_VARIABLE = "TILLER_PORTABLE_WORKSPACE_RESTORE";
4
+ export const PORTABLE_WORKSPACE_LABEL = "dev.tiller.portable-workspace-restore-protocol";
5
+ export const PORTABLE_NATIVE_LABEL = "dev.tiller.portable-native-restore-protocol";
6
+ export const PORTABLE_WORKSPACE_UPGRADE_REQUIRED = "Saved workspace recovery requires a compatible host and runtime image. Update both, then recreate the execution without discarding saved work.";
7
+ export function resolvePortableWorkspaceImage(image, label = PORTABLE_WORKSPACE_LABEL) {
8
+ try {
9
+ const result = spawnSync("docker", [
10
+ "image", "inspect", "--format",
11
+ `[{{json .Id}},{{json (index .Config.Labels "${label}")}}]`,
12
+ "--", image,
13
+ ], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000, maxBuffer: 4096 });
14
+ if (result.status !== 0)
15
+ return null;
16
+ const descriptor = JSON.parse(result.stdout);
17
+ if (!Array.isArray(descriptor) || descriptor.length !== 2 ||
18
+ typeof descriptor[0] !== "string" || descriptor[0].length !== 71 ||
19
+ !IMAGE_ID.test(descriptor[0]) || descriptor[1] !== "1")
20
+ return null;
21
+ if (IMAGE_ID.test(image) && descriptor[0] !== image)
22
+ return null;
23
+ return descriptor[0];
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ export function requirePortableWorkspaceImage(image, env) {
30
+ if (env.TILLER_PORTABLE_NATIVE_RESTORE !== undefined) {
31
+ const resolved = resolvePortableWorkspaceImage(image, PORTABLE_NATIVE_LABEL);
32
+ if (!resolved || env[RESTORE_VARIABLE] === undefined)
33
+ throw new Error(PORTABLE_WORKSPACE_UPGRADE_REQUIRED);
34
+ image = resolved;
35
+ }
36
+ if (env[RESTORE_VARIABLE] === undefined)
37
+ return image;
38
+ const resolved = resolvePortableWorkspaceImage(image);
39
+ if (!resolved)
40
+ throw new Error(PORTABLE_WORKSPACE_UPGRADE_REQUIRED);
41
+ return resolved;
42
+ }
43
+ export function requirePortableWorkspaceContainer(container, expected) {
44
+ const nativeSelection = expected?.TILLER_PORTABLE_NATIVE_RESTORE;
45
+ const nativeCarried = container.Config?.Env?.filter(entry => entry === "TILLER_PORTABLE_NATIVE_RESTORE" || entry.startsWith("TILLER_PORTABLE_NATIVE_RESTORE="));
46
+ if (nativeSelection !== undefined || nativeCarried?.length) {
47
+ if (nativeSelection === undefined || !container.Image || expected?.[RESTORE_VARIABLE] === undefined ||
48
+ resolvePortableWorkspaceImage(container.Image, PORTABLE_NATIVE_LABEL) !== container.Image ||
49
+ nativeCarried?.length !== 1 || nativeCarried[0] !== `TILLER_PORTABLE_NATIVE_RESTORE=${nativeSelection}`)
50
+ throw new Error(PORTABLE_WORKSPACE_UPGRADE_REQUIRED);
51
+ }
52
+ const selection = expected?.[RESTORE_VARIABLE];
53
+ const carried = container.Config?.Env?.filter(entry => entry === RESTORE_VARIABLE || entry.startsWith(`${RESTORE_VARIABLE}=`));
54
+ if (selection === undefined && !carried?.length)
55
+ return;
56
+ if (selection === undefined || !container.Image || container.Image.length !== 71 ||
57
+ !IMAGE_ID.test(container.Image) || resolvePortableWorkspaceImage(container.Image) !== container.Image ||
58
+ carried?.length !== 1 || carried[0] !== `${RESTORE_VARIABLE}=${selection}`)
59
+ throw new Error(PORTABLE_WORKSPACE_UPGRADE_REQUIRED);
60
+ }
@@ -0,0 +1,62 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { validateProjectEnvironmentDelivery } from "./project-environment.js";
3
+ const IMAGE_ID = /^sha256:[a-f0-9]{64}$/;
4
+ export const PROJECT_ENVIRONMENT_LABEL = "dev.tiller.project-environment-protocol";
5
+ export const PROJECT_ENVIRONMENT_UPGRADE_REQUIRED = "This execution requires isolated project settings. Update the host and its runtime image, then recreate the execution without discarding saved work.";
6
+ export function resolveProjectEnvironmentImage(image) {
7
+ try {
8
+ const result = spawnSync("docker", [
9
+ "image", "inspect", "--format",
10
+ `[{{json .Id}},{{json (index .Config.Labels "${PROJECT_ENVIRONMENT_LABEL}")}}]`,
11
+ "--", image,
12
+ ], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000, maxBuffer: 4096 });
13
+ if (result.status !== 0)
14
+ return null;
15
+ const descriptor = JSON.parse(result.stdout);
16
+ if (!Array.isArray(descriptor) || descriptor.length !== 2 ||
17
+ typeof descriptor[0] !== "string" || descriptor[0].length !== 71 || !IMAGE_ID.test(descriptor[0]) || descriptor[1] !== "1")
18
+ return null;
19
+ if (IMAGE_ID.test(image) && image !== descriptor[0])
20
+ return null;
21
+ return descriptor[0];
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ export function projectEnvironmentRequired(env) {
28
+ return Boolean(env?.TILLER_SESSION_ENV_NAMES || env?.TILLER_PROJECT_ENV_PROTOCOL ||
29
+ Object.keys(env ?? {}).some(name => name.startsWith("TILLER_PROJECT_ENV_VALUE_")));
30
+ }
31
+ export function requireProjectEnvironmentImage(image, env) {
32
+ validateProjectEnvironmentDelivery(env);
33
+ if (!projectEnvironmentRequired(env))
34
+ return image;
35
+ const resolved = resolveProjectEnvironmentImage(image);
36
+ if (!resolved)
37
+ throw new Error(PROJECT_ENVIRONMENT_UPGRADE_REQUIRED);
38
+ return resolved;
39
+ }
40
+ export function requireProjectEnvironmentContainer(container, expected) {
41
+ if (!projectEnvironmentRequired(expected))
42
+ return;
43
+ validateProjectEnvironmentDelivery(expected);
44
+ if (!container.Image || container.Image.length !== 71 || !IMAGE_ID.test(container.Image) ||
45
+ resolveProjectEnvironmentImage(container.Image) !== container.Image || !Array.isArray(container.Config?.Env))
46
+ throw new Error(PROJECT_ENVIRONMENT_UPGRADE_REQUIRED);
47
+ const actual = Object.create(null);
48
+ for (const entry of container.Config.Env) {
49
+ if (typeof entry !== "string")
50
+ throw new Error(PROJECT_ENVIRONMENT_UPGRADE_REQUIRED);
51
+ const separator = entry.indexOf("=");
52
+ const name = entry.slice(0, separator);
53
+ if (!name.startsWith("TILLER_PROJECT_ENV_") && name !== "TILLER_SESSION_ENV_NAMES")
54
+ continue;
55
+ if (separator < 1 || Object.prototype.hasOwnProperty.call(actual, name))
56
+ throw new Error(PROJECT_ENVIRONMENT_UPGRADE_REQUIRED);
57
+ actual[name] = entry.slice(separator + 1);
58
+ }
59
+ const keys = Object.keys(expected).filter(name => name.startsWith("TILLER_PROJECT_ENV_") || name === "TILLER_SESSION_ENV_NAMES");
60
+ if (Object.keys(actual).length !== keys.length || keys.some(name => actual[name] !== expected[name]))
61
+ throw new Error(PROJECT_ENVIRONMENT_UPGRADE_REQUIRED);
62
+ }
@@ -0,0 +1,28 @@
1
+ const PREFIX = "TILLER_PROJECT_ENV_VALUE_";
2
+ const RESERVED_PREFIXES = ["TILLER_", "RUNNER_", "ANTHROPIC_", "CLAUDE_", "CODEX_", "OPENAI_", "OPENCODE_"];
3
+ const RESERVED_NAMES = new Set([
4
+ "HUB_URL", "NAMESPACE", "REPO_SLUG", "REPO_URL", "NODE_OPTIONS", "CLAUDECODE",
5
+ "HOME", "USERPROFILE", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME",
6
+ ]);
7
+ export function validateProjectEnvironmentDelivery(source) {
8
+ const protocol = source.TILLER_PROJECT_ENV_PROTOCOL;
9
+ const names = source.TILLER_SESSION_ENV_NAMES ? source.TILLER_SESSION_ENV_NAMES.split(",") : [];
10
+ const carried = Object.keys(source).filter(name => name.startsWith(PREFIX));
11
+ if ((protocol !== undefined && protocol !== "1") ||
12
+ ((names.length || carried.length) && protocol !== "1") ||
13
+ names.length > 64 || new Set(names).size !== names.length ||
14
+ carried.some(name => !names.includes(name.slice(PREFIX.length))) ||
15
+ names.some(name => !/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(name) || name !== name.trim() ||
16
+ (name !== "TILLER_WORKER_NAME" && RESERVED_PREFIXES.some(prefix => name.startsWith(prefix))) ||
17
+ RESERVED_NAMES.has(name) || Object.prototype.hasOwnProperty.call(source, name) ||
18
+ typeof source[`${PREFIX}${name}`] !== "string"))
19
+ throw new Error("Project variables must use isolated environment delivery; update the Hub and recreate this execution");
20
+ let totalBytes = 0;
21
+ for (const name of names) {
22
+ const value = source[`${PREFIX}${name}`];
23
+ const bytes = Buffer.byteLength(value);
24
+ totalBytes += bytes;
25
+ if (!bytes || bytes > 16 * 1024 || totalBytes > 64 * 1024 || /[\0\r\n]/.test(value))
26
+ throw new Error("Invalid isolated project environment value");
27
+ }
28
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Prepare on project open (fast session startup, Gate C2, runner side).
3
+ *
4
+ * The Hub asks the runner to refresh a repository's mirror while the project
5
+ * is open, so the next create finds the base commit locally. The refresh runs
6
+ * in a short-lived container of the sandbox image, started as root only to
7
+ * run the credential broker and hand the mirror to its writer: every Git
8
+ * command runs as `tiller-mirror` (uid 1002). It holds a GitHub bridge
9
+ * credential that the Hub scoped to one repository, read-only, for two
10
+ * minutes. It has no launch credential, no session identity and no workspace.
11
+ */
12
+ /**
13
+ * The only request variables a mirror refresh receives: the bridge credential
14
+ * and how to reach the Hub. Anything else is dropped, including the Hub's
15
+ * NODE_OPTIONS: the refresh starts as root and the entrypoint sets Node's flags.
16
+ */
17
+ /** The request variables that are secret, for redacting error messages. */
18
+ export const PREPARE_PROJECT_SECRET_NAMES = [
19
+ "TILLER_GITHUB_BRIDGE_ID",
20
+ "TILLER_GITHUB_BRIDGE_SECRET",
21
+ "TILLER_CLIENT_ID",
22
+ "TILLER_CLIENT_SECRET",
23
+ ];
24
+ export const PREPARE_PROJECT_ENV_NAMES = [
25
+ "HUB_URL",
26
+ "TILLER_GITHUB_BRIDGE_ID",
27
+ "TILLER_GITHUB_BRIDGE_SECRET",
28
+ "TILLER_GITHUB_ALLOWED_REPO",
29
+ "TILLER_CLIENT_ID",
30
+ "TILLER_CLIENT_SECRET",
31
+ ];
32
+ /** The refresh CLI's own cap; the runner removes the container shortly after. */
33
+ export const MIRROR_REFRESH_TIMEOUT_MS = 2 * 60 * 1000;
34
+ export const MIRROR_REFRESH_CONTAINER_TIMEOUT_MS = MIRROR_REFRESH_TIMEOUT_MS + 30 * 1000;
35
+ const MIRROR_CONTAINER_PATH = "/var/cache/tiller/git-mirror";
36
+ const COMMIT = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
37
+ export class ProjectPreparationRequestError extends Error {
38
+ status = 400;
39
+ }
40
+ /** Validates the request body; throws a 400 for anything malformed. */
41
+ export function parseProjectPreparationRequest(body) {
42
+ const { repoUrl, headSha, envVars, stage } = body;
43
+ if (stage !== undefined && stage !== false) {
44
+ throw new ProjectPreparationRequestError("stage may only be false");
45
+ }
46
+ if (typeof repoUrl !== "string" || !repoUrl.trim()) {
47
+ throw new ProjectPreparationRequestError("repoUrl is required");
48
+ }
49
+ if (typeof headSha !== "string" || !COMMIT.test(headSha)) {
50
+ throw new ProjectPreparationRequestError("headSha must be a full commit SHA");
51
+ }
52
+ if (envVars !== undefined && (!envVars || typeof envVars !== "object" || Array.isArray(envVars)
53
+ || Object.values(envVars).some((value) => typeof value !== "string"))) {
54
+ throw new ProjectPreparationRequestError("envVars must map names to strings");
55
+ }
56
+ return {
57
+ repoUrl: repoUrl.trim(),
58
+ headSha,
59
+ envVars: (envVars ?? {}),
60
+ ...(stage === false ? { stage: false } : {}),
61
+ };
62
+ }
63
+ /**
64
+ * The refresh container's environment: the allowed request variables, then
65
+ * the mode and inputs, which the request cannot override. The repository the
66
+ * credential is scoped to must be the one being refreshed.
67
+ */
68
+ export function buildMirrorRefreshEnv(request, canonicalRepoUrl) {
69
+ const env = {};
70
+ for (const name of PREPARE_PROJECT_ENV_NAMES) {
71
+ const value = request.envVars[name];
72
+ if (value === undefined)
73
+ continue;
74
+ if (/[\0\r\n]/.test(value))
75
+ throw new ProjectPreparationRequestError(`${name} cannot be passed to the mirror refresh`);
76
+ env[name] = value;
77
+ }
78
+ for (const name of ["HUB_URL", "TILLER_GITHUB_BRIDGE_ID", "TILLER_GITHUB_BRIDGE_SECRET", "TILLER_GITHUB_ALLOWED_REPO"]) {
79
+ if (!env[name]?.trim())
80
+ throw new ProjectPreparationRequestError(`envVars.${name} is required to refresh the mirror`);
81
+ }
82
+ const allowed = `https://github.com/${env.TILLER_GITHUB_ALLOWED_REPO.trim().toLowerCase().replace(/\.git$/, "")}.git`;
83
+ if (allowed !== canonicalRepoUrl) {
84
+ throw new ProjectPreparationRequestError("The bridge credential is for another repository");
85
+ }
86
+ return {
87
+ ...env,
88
+ TILLER_BOOTSTRAP_MODE: "mirror-refresh",
89
+ TILLER_GIT_MIRROR_PATH: MIRROR_CONTAINER_PATH,
90
+ TILLER_STAGE_REPO_URL: canonicalRepoUrl,
91
+ TILLER_STAGE_COMMIT: request.headSha,
92
+ TILLER_MIRROR_REFRESH_TIMEOUT_MS: String(MIRROR_REFRESH_TIMEOUT_MS),
93
+ };
94
+ }
95
+ /**
96
+ * Root, the mirror read-write, the credential only in the env file, and no
97
+ * capabilities but these: CHOWN, for the credential broker to hand its hook
98
+ * socket to the writer's group and for the one-time adoption of a root-owned
99
+ * mirror; SETUID and SETGID, to drop to `tiller-mirror`; SETPCAP, which
100
+ * `setpriv --bounding-set=-all` needs to empty the writer's bounding set.
101
+ */
102
+ export function buildMirrorRefreshRunArgs(options) {
103
+ return [
104
+ "run",
105
+ "--rm",
106
+ ...(options.image.startsWith("sha256:") ? ["--pull=never"] : []),
107
+ "--name",
108
+ options.containerName,
109
+ "--add-host",
110
+ "host.docker.internal:host-gateway",
111
+ "--cap-drop",
112
+ "ALL",
113
+ "--cap-add",
114
+ "CHOWN",
115
+ "--cap-add",
116
+ "SETUID",
117
+ "--cap-add",
118
+ "SETGID",
119
+ "--cap-add",
120
+ "SETPCAP",
121
+ "--security-opt",
122
+ "no-new-privileges",
123
+ "-v",
124
+ `${options.mirrorVolume}:${MIRROR_CONTAINER_PATH}`,
125
+ "--env-file",
126
+ options.envFilePath,
127
+ options.image,
128
+ ];
129
+ }
130
+ /** The refresh outcome the CLI printed, or null when it printed none. */
131
+ export function parseMirrorRefreshOutcome(output) {
132
+ const matches = [...output.matchAll(/git-mirror=(fetched|present)\b/g)];
133
+ return matches.at(-1)?.[1] ?? null;
134
+ }
@@ -0,0 +1,28 @@
1
+ import { ansi } from "./ansi.js";
2
+ import { CLI } from "./identity.js";
3
+ function levelIcon(level) {
4
+ switch (level) {
5
+ case "ok":
6
+ return `${ansi.green}✓${ansi.reset}`;
7
+ case "warn":
8
+ return `${ansi.yellow}!${ansi.reset}`;
9
+ case "fail":
10
+ return `${ansi.red}✕${ansi.reset}`;
11
+ }
12
+ }
13
+ export function hasFailures(checks) {
14
+ return checks.some((check) => check.level === "fail");
15
+ }
16
+ export function hasWarnings(checks) {
17
+ return checks.some((check) => check.level === "warn");
18
+ }
19
+ export function printCheckReport(title, checks) {
20
+ process.stderr.write(`${ansi.bold}${CLI.logTag}${ansi.reset} ${title}\n`);
21
+ for (const check of checks) {
22
+ const detail = check.detail ? ` ${ansi.dim}${check.detail}${ansi.reset}` : "";
23
+ process.stderr.write(`${ansi.bold}${CLI.logTag}${ansi.reset} ${levelIcon(check.level)} ${check.label}${detail}\n`);
24
+ if (check.fixHint) {
25
+ process.stderr.write(`${ansi.bold}${CLI.logTag}${ansi.reset} ${check.fixHint}\n`);
26
+ }
27
+ }
28
+ }
@@ -0,0 +1,27 @@
1
+ const MIN_REDACTION_VALUE_LENGTH = 4;
2
+ export const SESSION_ENV_NAMES_VAR = "TILLER_SESSION_ENV_NAMES";
3
+ export function redactValues(text, values, replacement = "[redacted]", minLength = MIN_REDACTION_VALUE_LENGTH) {
4
+ let redacted = text;
5
+ const uniqueValues = [...new Set([...values]
6
+ .filter((value) => typeof value === "string" && value.length >= minLength && value.length > 0))]
7
+ .sort((a, b) => b.length - a.length);
8
+ for (const value of uniqueValues) {
9
+ redacted = redacted.split(value).join(replacement);
10
+ }
11
+ return redacted;
12
+ }
13
+ function parseEnvNameList(value) {
14
+ return new Set((value ?? "")
15
+ .split(",")
16
+ .map((name) => name.trim())
17
+ .filter(Boolean));
18
+ }
19
+ export function redactEnvValues(text, envVars) {
20
+ const sessionEnvNames = parseEnvNameList(envVars[SESSION_ENV_NAMES_VAR]);
21
+ const sessionEnvValues = [...sessionEnvNames].flatMap((name) => [envVars[name], envVars[`TILLER_PROJECT_ENV_VALUE_${name}`]]);
22
+ const redactedSessionValues = redactValues(text, sessionEnvValues, "[redacted]", 1);
23
+ const otherValues = Object.entries(envVars)
24
+ .filter(([name]) => !sessionEnvNames.has(name))
25
+ .map(([, value]) => value);
26
+ return redactValues(redactedSessionValues, otherValues);
27
+ }
@@ -0,0 +1,61 @@
1
+ import { execFile, spawnSync } from "node:child_process";
2
+ const REVIEWER_ISOLATION_LABEL = "dev.tiller.reviewer-isolation-protocol";
3
+ function inspectArgs(image) {
4
+ return [
5
+ "image",
6
+ "inspect",
7
+ "--format",
8
+ `{{ index .Config.Labels "${REVIEWER_ISOLATION_LABEL}" }}`,
9
+ image,
10
+ ];
11
+ }
12
+ export function resolveHostReviewerIsolationProtocol(image, imageSourceId, options = {}) {
13
+ if (!imageSourceId)
14
+ return null;
15
+ const inspectLabel = options.inspectLabel ?? ((candidate) => {
16
+ const result = spawnSync("docker", inspectArgs(candidate), {
17
+ encoding: "utf8",
18
+ stdio: ["ignore", "pipe", "ignore"],
19
+ timeout: 2_000,
20
+ });
21
+ return result.status === 0 ? result.stdout.trim() : null;
22
+ });
23
+ return inspectLabel(image) === "1" ? 1 : null;
24
+ }
25
+ /** The image's label, or null when Docker did not answer. Never blocks the event loop. */
26
+ function inspectLabelAsync(image) {
27
+ return new Promise((resolvePromise) => {
28
+ execFile("docker", inspectArgs(image), { encoding: "utf8", timeout: 10_000 }, (error, stdout) => {
29
+ resolvePromise(error ? null : stdout.trim());
30
+ });
31
+ });
32
+ }
33
+ /**
34
+ * The reviewer isolation protocol the Hub advertisement carries. The image is
35
+ * fixed for the life of the runner process, so its label is read once, off
36
+ * the event loop, from the heartbeat; the advertisement reads the cached value.
37
+ */
38
+ export class HostReviewerIsolationAdvertisement {
39
+ image;
40
+ imageSourceId;
41
+ inspectLabel;
42
+ value = null;
43
+ known = false;
44
+ constructor(image, imageSourceId, inspectLabel = inspectLabelAsync) {
45
+ this.image = image;
46
+ this.imageSourceId = imageSourceId;
47
+ this.inspectLabel = inspectLabel;
48
+ }
49
+ current() {
50
+ return this.value;
51
+ }
52
+ async refresh() {
53
+ if (this.known || !this.imageSourceId)
54
+ return;
55
+ const label = await this.inspectLabel(this.image);
56
+ if (label === null)
57
+ return;
58
+ this.value = label === "1" ? 1 : null;
59
+ this.known = true;
60
+ }
61
+ }
@@ -0,0 +1,80 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ /**
5
+ * The runner API's shared secret.
6
+ *
7
+ * The runner listens on host loopback, but loopback is not private to this
8
+ * Mac's own processes: on Docker Desktop, every container, Tiller's session
9
+ * containers included, reaches it as `host.docker.internal`. Without a secret,
10
+ * an agent in a session could create, start, stop or destroy any environment
11
+ * on this machine, choosing its environment variables. So the runner makes a
12
+ * fresh secret each time it starts and refuses every request but `/healthz`
13
+ * that does not carry it.
14
+ *
15
+ * The secret lives in the runner process, which hands it to its own Hub
16
+ * session client, and in a file only this user can read
17
+ * (`runner-api-token` in the runner's state directory), for development tools
18
+ * on this Mac such as the startup bench. No container mounts that directory.
19
+ */
20
+ export const RUNNER_API_TOKEN_FILE = "runner-api-token";
21
+ export function createRunnerApiToken() {
22
+ return randomBytes(32).toString("base64url");
23
+ }
24
+ export function runnerApiTokenPath(localStateDir) {
25
+ return join(localStateDir, RUNNER_API_TOKEN_FILE);
26
+ }
27
+ export function runnerAuthorizationHeaders(token) {
28
+ return token ? { Authorization: `Bearer ${token}` } : {};
29
+ }
30
+ function digest(value) {
31
+ return createHash("sha256").update(value, "utf8").digest();
32
+ }
33
+ /**
34
+ * True when the request carries `Authorization: Bearer <token>`. Both sides
35
+ * are hashed first so the comparison takes the same time whatever the length
36
+ * or content of what was sent.
37
+ */
38
+ export function isAuthorizedRunnerRequest(req, token) {
39
+ const header = req.headers.authorization;
40
+ if (typeof header !== "string")
41
+ return false;
42
+ const match = /^Bearer\s+(\S+)\s*$/i.exec(header);
43
+ const presented = match?.[1] ?? "";
44
+ const equal = timingSafeEqual(digest(presented), digest(token));
45
+ return equal && presented.length > 0 && token.length > 0;
46
+ }
47
+ /**
48
+ * Writes the secret where only this user can read it, replacing any earlier
49
+ * runner's. Written atomically so a reader never sees half a secret.
50
+ */
51
+ export function writeRunnerApiTokenFile(localStateDir, token) {
52
+ mkdirSync(localStateDir, { recursive: true, mode: 0o700 });
53
+ const path = runnerApiTokenPath(localStateDir);
54
+ const temporary = `${path}.${process.pid}.tmp`;
55
+ try {
56
+ writeFileSync(temporary, `${token}\n`, { encoding: "utf8", mode: 0o600 });
57
+ chmodSync(temporary, 0o600);
58
+ renameSync(temporary, path);
59
+ }
60
+ catch (error) {
61
+ rmSync(temporary, { force: true });
62
+ throw error;
63
+ }
64
+ return path;
65
+ }
66
+ export function readRunnerApiTokenFile(localStateDir) {
67
+ try {
68
+ const token = readFileSync(runnerApiTokenPath(localStateDir), "utf8").trim();
69
+ return token || null;
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
75
+ /** Removes the file if it still holds this runner's secret, not a newer one's. */
76
+ export function removeRunnerApiTokenFile(localStateDir, token) {
77
+ if (readRunnerApiTokenFile(localStateDir) === token) {
78
+ rmSync(runnerApiTokenPath(localStateDir), { force: true });
79
+ }
80
+ }