@nordhavnhq/runner 0.97.0 → 0.99.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ import type { CliCtx } from './prompts.js';
2
+ export declare function gitCredential(ctx: CliCtx): Promise<void>;
@@ -0,0 +1,64 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { getConfigPath, hostedAgent } from '../config.js';
3
+ import { formatCredentialOutput, GIT_RUN_ENV, parseCredentialInput } from '../runtime/git-credentials.js';
4
+ /**
5
+ * `nordhavn git-credential [--config <path>] get`: the git credential helper
6
+ * of a run (runtime/git-credentials.ts). git starts it, it is not for people.
7
+ *
8
+ * For `get` on https://github.com it asks the studio for the token of the
9
+ * person the run (`NORDHAVN_GIT_RUN`) works for and prints it the way git
10
+ * reads it. Refused (nobody connected GitHub, the run ended), it says why on
11
+ * stderr, where git shows it, and answers `quit=1` so git asks nobody else.
12
+ * `store` and `erase` do nothing: the studio keeps the token, not this machine.
13
+ */
14
+ async function readStdin() {
15
+ const chunks = [];
16
+ for await (const chunk of process.stdin)
17
+ chunks.push(chunk);
18
+ return Buffer.concat(chunks).toString('utf8');
19
+ }
20
+ function refuse(reason) {
21
+ process.stderr.write(`nordhavn: ${reason}\n`);
22
+ process.stdout.write('quit=1\n');
23
+ }
24
+ export async function gitCredential(ctx) {
25
+ const args = ctx.cmdArgs;
26
+ const at = args.indexOf('--config');
27
+ const configPath = at >= 0 ? args[at + 1] : getConfigPath();
28
+ const operation = args.filter((arg, i) => !arg.startsWith('--') && (at < 0 || i !== at + 1))[0];
29
+ const input = parseCredentialInput(await readStdin());
30
+ if (operation !== 'get')
31
+ return;
32
+ if (input.protocol !== 'https' || input.host !== 'github.com')
33
+ return;
34
+ const queueUid = process.env[GIT_RUN_ENV];
35
+ if (!queueUid)
36
+ return refuse('this git runs outside an agent run, so there is no GitHub account to use.');
37
+ let config;
38
+ try {
39
+ config = JSON.parse(await readFile(configPath, 'utf8'));
40
+ }
41
+ catch {
42
+ return refuse(`cannot read the runner config at ${configPath}.`);
43
+ }
44
+ const agent = hostedAgent(config);
45
+ if (!agent || !config.studioUrl)
46
+ return refuse('this runner hosts no agent.');
47
+ let response;
48
+ try {
49
+ response = await fetch(`${config.studioUrl.replace(/\/+$/, '')}/api/agents/git/credential`, {
50
+ method: 'POST',
51
+ headers: { 'Authorization': `Bearer ${agent.token}`, 'Content-Type': 'application/json' },
52
+ body: JSON.stringify({ queueUid, host: input.host }),
53
+ signal: AbortSignal.timeout(20_000),
54
+ });
55
+ }
56
+ catch (err) {
57
+ return refuse(`the studio did not answer (${err.message}).`);
58
+ }
59
+ const body = await response.json().catch(() => ({}));
60
+ if (!response.ok || !body.username || !body.password) {
61
+ return refuse(body.message ?? `the studio refused the GitHub credential (${response.status}).`);
62
+ }
63
+ process.stdout.write(formatCredentialOutput({ username: body.username, password: body.password, expiresAt: body.expiresAt ?? null }));
64
+ }
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ import { ps } from './cli/ps.js';
11
11
  import { down, restart } from './cli/lifecycle.js';
12
12
  import { logs } from './cli/logs.js';
13
13
  import { relay } from './cli/relay.js';
14
+ import { gitCredential } from './cli/git-credential.js';
14
15
  import { update } from './cli/update.js';
15
16
  import { migrateLegacyDir } from './paths.js';
16
17
  // Before anything reads config: move a pre-rename ~/.justmade-studio (or
@@ -79,6 +80,8 @@ const commands = {
79
80
  restart,
80
81
  logs,
81
82
  relay,
83
+ // Started by git (runtime/git-credentials.ts), not listed in the help.
84
+ 'git-credential': gitCredential,
82
85
  update,
83
86
  version: async () => { console.log(VERSION); },
84
87
  };
@@ -83,7 +83,8 @@ export function devCommandRefusal(command, cwd) {
83
83
  // One command, nothing chained, piped, redirected, quoted or substituted beside it.
84
84
  if (/[;&|`$<>()\\'"]/.test(line))
85
85
  return 'A dev command is a single command, without ; & | ` $ < > ( ) \\ or quotes';
86
- const blocked = isBlocked(line);
86
+ // A dev server never needs root, also not on a runner that allows sudo.
87
+ const blocked = isBlocked(line, { allowSudo: false });
87
88
  if (blocked)
88
89
  return blocked;
89
90
  if (!isLongRunningCommand(line))
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Git over https with the GitHub account of the person a run works for.
3
+ *
4
+ * With `NORDHAVN_GIT_CREDENTIALS=studio` in the runner's own environment (the
5
+ * container image sets it) every git the runner starts for a run - its git
6
+ * tools and the agent's shell - gets one credential helper for
7
+ * https://github.com: `nordhavn git-credential`. That helper asks the studio
8
+ * (`POST /api/agents/git/credential`, agent token + the run's queueUid) and
9
+ * hands git the person's token. Helpers from the machine's own git config are
10
+ * reset for github.com, so nothing else (a stored token, the macOS keychain)
11
+ * answers instead and the token is never written to disk.
12
+ *
13
+ * Off (the default on a laptop), git keeps using the machine's own setup: the
14
+ * person's keychain, ssh keys, the git relay.
15
+ *
16
+ * The helper lives in the env as `GIT_CONFIG_COUNT` / `GIT_CONFIG_KEY_n` /
17
+ * `GIT_CONFIG_VALUE_n` (git 2.31+), so no config file of the checkout or the
18
+ * home changes. `NORDHAVN_GIT_RUN` names the run; it is no secret on its own,
19
+ * the agent token stays in the runner's config.
20
+ */
21
+ export declare const GIT_RUN_ENV = "NORDHAVN_GIT_RUN";
22
+ export declare function studioGitCredentials(env?: NodeJS.ProcessEnv): boolean;
23
+ /**
24
+ * The env that points git at the studio credential of run `queueUid`, or
25
+ * `{}` when studio credentials are off or the run has no uid. `cli` is the
26
+ * nordhavn entry script (`process.argv[1]` of the runner).
27
+ */
28
+ export declare function gitCredentialEnv(queueUid: string | null | undefined, options?: {
29
+ env?: NodeJS.ProcessEnv;
30
+ node?: string;
31
+ cli?: string;
32
+ configPath?: string;
33
+ }): NodeJS.ProcessEnv;
34
+ /** `key=value` lines git hands a credential helper on stdin. */
35
+ export declare function parseCredentialInput(input: string): Record<string, string>;
36
+ /** What the helper prints for git: a credential, or `quit` with a reason on stderr. */
37
+ export declare function formatCredentialOutput(reply: {
38
+ username: string;
39
+ password: string;
40
+ expiresAt: string | null;
41
+ }): string;
@@ -0,0 +1,72 @@
1
+ import { getConfigPath } from '../config.js';
2
+ /**
3
+ * Git over https with the GitHub account of the person a run works for.
4
+ *
5
+ * With `NORDHAVN_GIT_CREDENTIALS=studio` in the runner's own environment (the
6
+ * container image sets it) every git the runner starts for a run - its git
7
+ * tools and the agent's shell - gets one credential helper for
8
+ * https://github.com: `nordhavn git-credential`. That helper asks the studio
9
+ * (`POST /api/agents/git/credential`, agent token + the run's queueUid) and
10
+ * hands git the person's token. Helpers from the machine's own git config are
11
+ * reset for github.com, so nothing else (a stored token, the macOS keychain)
12
+ * answers instead and the token is never written to disk.
13
+ *
14
+ * Off (the default on a laptop), git keeps using the machine's own setup: the
15
+ * person's keychain, ssh keys, the git relay.
16
+ *
17
+ * The helper lives in the env as `GIT_CONFIG_COUNT` / `GIT_CONFIG_KEY_n` /
18
+ * `GIT_CONFIG_VALUE_n` (git 2.31+), so no config file of the checkout or the
19
+ * home changes. `NORDHAVN_GIT_RUN` names the run; it is no secret on its own,
20
+ * the agent token stays in the runner's config.
21
+ */
22
+ export const GIT_RUN_ENV = 'NORDHAVN_GIT_RUN';
23
+ const HELPER_KEY = 'credential.https://github.com.helper';
24
+ export function studioGitCredentials(env = process.env) {
25
+ return env.NORDHAVN_GIT_CREDENTIALS?.trim().toLowerCase() === 'studio';
26
+ }
27
+ /** A word for `sh -c`, in double quotes. */
28
+ function shellWord(value) {
29
+ return `"${value.replace(/(["\\$`])/g, '\\$1')}"`;
30
+ }
31
+ /**
32
+ * The env that points git at the studio credential of run `queueUid`, or
33
+ * `{}` when studio credentials are off or the run has no uid. `cli` is the
34
+ * nordhavn entry script (`process.argv[1]` of the runner).
35
+ */
36
+ export function gitCredentialEnv(queueUid, options = {}) {
37
+ if (!queueUid || !studioGitCredentials(options.env))
38
+ return {};
39
+ const node = options.node ?? process.execPath;
40
+ const cli = options.cli ?? process.argv[1] ?? 'nordhavn';
41
+ // The config path goes on the command line: a command's HOME is the agent's
42
+ // home, where the runner's config is not.
43
+ const configPath = options.configPath ?? getConfigPath();
44
+ return {
45
+ GIT_CONFIG_COUNT: '2',
46
+ // An empty value clears every helper git collected so far for this URL.
47
+ GIT_CONFIG_KEY_0: HELPER_KEY,
48
+ GIT_CONFIG_VALUE_0: '',
49
+ GIT_CONFIG_KEY_1: HELPER_KEY,
50
+ GIT_CONFIG_VALUE_1: `!${shellWord(node)} ${shellWord(cli)} git-credential --config ${shellWord(configPath)}`,
51
+ GIT_TERMINAL_PROMPT: '0',
52
+ [GIT_RUN_ENV]: queueUid,
53
+ };
54
+ }
55
+ /** `key=value` lines git hands a credential helper on stdin. */
56
+ export function parseCredentialInput(input) {
57
+ const out = {};
58
+ for (const line of input.split('\n')) {
59
+ const at = line.indexOf('=');
60
+ if (at > 0)
61
+ out[line.slice(0, at)] = line.slice(at + 1).replace(/\r$/, '');
62
+ }
63
+ return out;
64
+ }
65
+ /** What the helper prints for git: a credential, or `quit` with a reason on stderr. */
66
+ export function formatCredentialOutput(reply) {
67
+ const lines = [`username=${reply.username}`, `password=${reply.password}`];
68
+ const expiry = reply.expiresAt ? Math.floor(new Date(reply.expiresAt).getTime() / 1000) : NaN;
69
+ if (Number.isFinite(expiry))
70
+ lines.push(`password_expiry_utc=${expiry}`);
71
+ return `${lines.join('\n')}\n`;
72
+ }
@@ -25,7 +25,15 @@ export declare function commandEnv(context: ToolContext | undefined, base: strin
25
25
  * result that is no JSON object gets the warning as a last line.
26
26
  */
27
27
  export declare function withProjectNode(result: string, node: ProjectNode | null): Promise<string>;
28
- export declare function isBlocked(command: string): string | null;
28
+ /**
29
+ * Whether this runner lets an agent use sudo: only when the operator says so
30
+ * with `NORDHAVN_ALLOW_SUDO=1`, as the container image does (the agent owns
31
+ * that machine, docs/runner.md). On a person's own machine it stays blocked.
32
+ */
33
+ export declare function sudoAllowed(): boolean;
34
+ export declare function isBlocked(command: string, options?: {
35
+ allowSudo?: boolean;
36
+ }): string | null;
29
37
  /** Block any attempt to publish commits to a remote from the shell. Exported for tests. */
30
38
  export declare function detectGitPush(command: string): string | null;
31
39
  export declare function detectPathEscape(command: string, roots: string[], base: string, readRoots?: string[], shellHome?: string): string | null;
@@ -8,6 +8,7 @@ import { stopAllProcesses, trackProcess, waitForPreview } from '../runtime/proce
8
8
  import { projectNodeLabel, projectNodeNote, resolveProjectNode, withNodeBin } from '../runtime/project-node.js';
9
9
  import { recordTouched, snapshotCheckout } from './_touched.js';
10
10
  import { isForcedRecursiveRm, unquote } from './_shell-words.js';
11
+ import { gitCredentialEnv } from '../runtime/git-credentials.js';
11
12
  // ─── Long-running / Dev Server Detection ────
12
13
  // These patterns indicate a command that starts a persistent server
13
14
  // and will never exit on its own (dev servers, watchers, etc.)
@@ -98,15 +99,15 @@ const runCommandDefinition = {
98
99
  required: ['command'],
99
100
  },
100
101
  };
102
+ const SUDO_PATTERN = /\bsudo\b/;
101
103
  // Commands that are never allowed
102
104
  const BLOCKED_PATTERNS = [
103
- /\bsudo\b/,
104
105
  /\bmkfs\b/,
105
106
  /\bdd\s+/,
106
107
  /\b:(){ :|:& };:/, // fork bomb
107
108
  /\bchmod\s+-R\s+777/,
108
- /\bcurl\b.*\|\s*(sh|bash)/, // curl pipe to shell
109
- /\bwget\b.*\|\s*(sh|bash)/,
109
+ /\bcurl\b.*\|\s*(sudo\s+)?(sh|bash)/, // curl pipe to shell
110
+ /\bwget\b.*\|\s*(sudo\s+)?(sh|bash)/,
110
111
  ];
111
112
  /**
112
113
  * The variables of the runner's own environment a command an agent starts
@@ -165,6 +166,8 @@ export function commandEnv(context, base, source = process.env, nodeBin) {
165
166
  HOME: shellHome(context, base),
166
167
  // JUSTMADE_SCRATCH: the pre-rename name, for prompts and scripts that still use it.
167
168
  ...(context?.scratchRoot ? { NORDHAVN_SCRATCH: context.scratchRoot, JUSTMADE_SCRATCH: context.scratchRoot } : {}),
169
+ // git signs in to GitHub as the person behind this run (runtime/git-credentials.ts).
170
+ ...gitCredentialEnv(context?.queueUid),
168
171
  };
169
172
  return nodeBin ? withNodeBin(out, nodeBin) : out;
170
173
  }
@@ -187,9 +190,20 @@ export async function withProjectNode(result, node) {
187
190
  catch { /* plain text */ }
188
191
  return warning ? `${result}\n${warning}` : result;
189
192
  }
190
- export function isBlocked(command) {
193
+ /**
194
+ * Whether this runner lets an agent use sudo: only when the operator says so
195
+ * with `NORDHAVN_ALLOW_SUDO=1`, as the container image does (the agent owns
196
+ * that machine, docs/runner.md). On a person's own machine it stays blocked.
197
+ */
198
+ export function sudoAllowed() {
199
+ return process.env.NORDHAVN_ALLOW_SUDO === '1';
200
+ }
201
+ export function isBlocked(command, options = {}) {
191
202
  if (isForcedRecursiveRm(command))
192
203
  return 'Blocked: a recursive forced rm (rm -rf and its spellings) is not allowed';
204
+ if (!(options.allowSudo ?? sudoAllowed()) && SUDO_PATTERN.test(command)) {
205
+ return `Blocked: command matches restricted pattern ${SUDO_PATTERN}`;
206
+ }
193
207
  for (const pattern of BLOCKED_PATTERNS) {
194
208
  if (pattern.test(command)) {
195
209
  return `Blocked: command matches restricted pattern ${pattern}`;
@@ -1,6 +1,7 @@
1
1
  import { type ToolDefinition } from '@nordhavnhq/runner-runtime';
2
2
  import type { ToolContext } from './index.js';
3
- export declare function runGit(cwd: string, args: string[]): Promise<{
3
+ /** `env` goes on top of the runner's own, e.g. the run's git credential (`remoteEnv`). */
4
+ export declare function runGit(cwd: string, args: string[], env?: NodeJS.ProcessEnv): Promise<{
4
5
  stdout: string;
5
6
  stderr: string;
6
7
  }>;
package/dist/tools/git.js CHANGED
@@ -6,6 +6,7 @@ import { dirname, isAbsolute, join, relative, sep } from 'node:path';
6
6
  import { splitOwnFiles } from '@nordhavnhq/runner-runtime';
7
7
  import { githubRepo, relayBranch, RELAY_BUNDLE_MAX_BYTES } from '../runtime/git-relay.js';
8
8
  import { unpushedAnnotatedTags } from '../runtime/git-unpushed.js';
9
+ import { gitCredentialEnv } from '../runtime/git-credentials.js';
9
10
  import { hasWriteScope, missingScopeError, missingWriteScope, resolveInCheckout, resolveInJail } from './_jail.js';
10
11
  import { commitOutsideScope, outOfScopeError, outOfScopePaths, scopePathspec } from './_commit-scope.js';
11
12
  import { runWorktreeSetup } from './_worktree-setup.js';
@@ -49,14 +50,20 @@ const PROTECTED_BRANCHES = ['main', 'master'];
49
50
  const BRANCH_NAMING = /^(feat|fix|chore|test|task)\//;
50
51
  const DIFF_MAX_LINES = 200;
51
52
  // ─── Helpers ────────────────────────────────
52
- export async function runGit(cwd, args) {
53
+ /** `env` goes on top of the runner's own, e.g. the run's git credential (`remoteEnv`). */
54
+ export async function runGit(cwd, args, env) {
53
55
  const { stdout, stderr } = await execFileAsync('git', args, {
54
56
  cwd,
55
57
  maxBuffer: 10 * 1024 * 1024,
56
58
  timeout: 60_000,
59
+ ...(env && Object.keys(env).length > 0 ? { env: { ...process.env, ...env } } : {}),
57
60
  });
58
61
  return { stdout, stderr };
59
62
  }
63
+ /** What a git that talks to a remote gets: the GitHub credential of the person behind this run, when the runner uses studio credentials. */
64
+ function remoteEnv(context) {
65
+ return gitCredentialEnv(context?.queueUid);
66
+ }
60
67
  /** Extract a readable message from a failed execFile call. */
61
68
  export function gitErrorMessage(err) {
62
69
  const e = err;
@@ -1016,7 +1023,7 @@ export async function executePush(params, context) {
1016
1023
  args.push('-u');
1017
1024
  args.push(remote, branch);
1018
1025
  // git push reports progress and result on stderr; keep both for the model.
1019
- const { stdout, stderr } = await runGit(repo, args);
1026
+ const { stdout, stderr } = await runGit(repo, args, remoteEnv(context));
1020
1027
  const output = [stdout.trim(), stderr.trim()].filter(Boolean).join('\n');
1021
1028
  return JSON.stringify({
1022
1029
  success: true,
@@ -1058,7 +1065,7 @@ export async function executeFetch(params, context) {
1058
1065
  if (params.prune === true)
1059
1066
  args.push('--prune');
1060
1067
  try {
1061
- const { stdout, stderr } = await runGit(repo, args);
1068
+ const { stdout, stderr } = await runGit(repo, args, remoteEnv(context));
1062
1069
  const output = [stdout.trim(), stderr.trim()].filter(Boolean).join('\n');
1063
1070
  return JSON.stringify({
1064
1071
  success: true,
@@ -1112,7 +1119,7 @@ export async function executePull(params, context) {
1112
1119
  const flag = strategy === 'rebase' ? '--rebase' : strategy === 'merge' ? '--no-rebase' : '--ff-only';
1113
1120
  try {
1114
1121
  const identity = await identityArgs(repo, context);
1115
- const { stdout, stderr } = await runGit(repo, [...identity, 'pull', flag, remote, branch]);
1122
+ const { stdout, stderr } = await runGit(repo, [...identity, 'pull', flag, remote, branch], remoteEnv(context));
1116
1123
  const output = [stdout.trim(), stderr.trim()].filter(Boolean).join('\n');
1117
1124
  return JSON.stringify({
1118
1125
  success: true,
package/dist/version.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.97.0",
3
- "tag": "v0.97.0",
4
- "packageVersion": "0.97.0"
2
+ "version": "0.99.0",
3
+ "tag": "v0.99.0",
4
+ "packageVersion": "0.99.0"
5
5
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nordhavnhq/runner-browser",
3
- "version": "0.97.0",
3
+ "version": "0.99.0",
4
4
  "description": "Nordhavn OS agent browser: Playwright sessions, the browser tools, the confirm-first guard and the live view, for the runner and the browser host",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nordhavnhq/runner-runtime",
3
- "version": "0.97.0",
3
+ "version": "0.99.0",
4
4
  "description": "Nordhavn OS agent-runtime core: studio connection, dispatch wire, MCP client, inference, agent loop",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nordhavnhq/runner",
3
- "version": "0.97.0",
3
+ "version": "0.99.0",
4
4
  "description": "Nordhavn OS runner CLI: runs agents headless on a host and supplies the host tools",
5
5
  "license": "UNLICENSED",
6
6
  "publishConfig": {
@@ -25,8 +25,8 @@
25
25
  "@ffmpeg-installer/ffmpeg": "^1.1.0",
26
26
  "@vscode/ripgrep": "^1.18.0",
27
27
  "mysql2": "^3.24.6",
28
- "@nordhavnhq/runner-runtime": "0.97.0",
29
- "@nordhavnhq/runner-browser": "0.97.0"
28
+ "@nordhavnhq/runner-runtime": "0.99.0",
29
+ "@nordhavnhq/runner-browser": "0.99.0"
30
30
  },
31
31
  "bundleDependencies": [
32
32
  "@nordhavnhq/runner-runtime",