@veda-hq/niyam 0.6.23 → 0.6.25

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 DEFAULTS = {
12
12
  skip: ['mergify/', 'gh-readonly-queue/'],
13
13
  optOut: [],
14
14
  describe: '`gh pr edit --body-file`',
15
+ autofixList: false,
15
16
  };
16
17
  const where = `${SETTINGS_PATH} "prAutocreate"`;
17
18
  const BRANCH = /^(?!\/)(?!.*\/\/)(?!.*\.\.)[\w.\/+-]+$/;
@@ -35,17 +36,20 @@ export function autocreateSettings(raw) {
35
36
  return { ...DEFAULTS };
36
37
  if (typeof value !== 'object' || value === null || Array.isArray(value))
37
38
  throw new Error(`${where} must be an object`);
38
- const { base = DEFAULTS.base, draft = DEFAULTS.draft, protected: guarded = DEFAULTS.protected, skip = DEFAULTS.skip, optOut = DEFAULTS.optOut, describe, retired, retire, footer, ...rest } = value;
39
+ const { base = DEFAULTS.base, draft = DEFAULTS.draft, protected: guarded = DEFAULTS.protected, skip = DEFAULTS.skip, optOut = DEFAULTS.optOut, describe, retired, retire, footer, autofixList = DEFAULTS.autofixList, ...rest } = value;
39
40
  const extra = Object.keys(rest)[0];
40
41
  if (extra !== undefined)
41
- throw new Error(`${where} has an unknown key "${extra}"; it takes "base", "draft", "protected", "skip", "optOut", "describe", "retired", "retire" and "footer"`);
42
+ throw new Error(`${where} has an unknown key "${extra}"; it takes "base", "draft", "protected", "skip", "optOut", "describe", "retired", "retire", "footer" and "autofixList"`);
42
43
  if (typeof base !== 'string' || !BRANCH.test(base))
43
44
  throw new Error(`${where}.base must be a branch name`);
44
45
  if (typeof draft !== 'boolean')
45
46
  throw new Error(`${where}.draft must be true or false`);
47
+ if (typeof autofixList !== 'boolean')
48
+ throw new Error(`${where}.autofixList must be true or false`);
46
49
  const settings = {
47
50
  base,
48
51
  draft,
52
+ autofixList,
49
53
  protected: strings(guarded, 'protected', (item) => BRANCH.test(item)),
50
54
  skip: strings(skip, 'skip', (item) => item.length > 0 && BRANCH.test(item)),
51
55
  optOut: strings(optOut, 'optOut', (item) => ENV_NAME.test(item)),
@@ -499,29 +503,97 @@ export function pushTarget(command, cwd, home) {
499
503
  }
500
504
  return undefined;
501
505
  }
502
- /** The instruction a session in the desktop app gets: switch Autofix on for the pull request. */
503
- export function reminder(pr, opened, created, cloud) {
506
+ /**
507
+ * The instruction a session in the desktop app gets: switch Autofix on for the pull request. `listed`: the pull
508
+ * request is on the session's sarathi Auto-fix list and the repository says sarathi warns from it, so the
509
+ * `set_monitor` step is sarathi's and left out here. The tag and `bind_pr` stay: without them the app refuses
510
+ * `set_monitor` for a pull request a hook opened, and sarathi goes quiet once it records the refusal.
511
+ */
512
+ export function reminder(pr, opened, created, cloud, listed = false) {
504
513
  if (cloud) {
505
514
  return `PR #${pr.number} (${pr.url}) ${opened}\nThis cloud session has no Autofix: CI, conflicts and review comments reach no one until a session reads them (gh api; GraphQL is refused here).`;
506
515
  }
507
516
  // The tag claims the session opened the pull request, so one merely found
508
517
  // on the branch gets it only when the session knows it ran that create.
509
518
  const claim = created ? 'Write' : 'Only if this session itself ran the `gh pr create` that opened this PR (in a background command, say), write';
510
- return (`PR #${pr.number} (${pr.url}) ${opened}\n` +
511
- 'Standing instruction from the user: Autofix must be ON for every PR a session pushes. Do this now, before anything else:\n' +
512
- '1. If mcp__ccd_pr__get_status is not yet a callable tool, it may only be deferred: run ToolSearch with query "select:mcp__ccd_pr__get_status,mcp__ccd_pr__bind_pr,mcp__ccd_pr__set_monitor" to load its schema before concluding it is unavailable.\n' +
519
+ const steps = '1. If mcp__ccd_pr__get_status is not yet a callable tool, it may only be deferred: run ToolSearch with query "select:mcp__ccd_pr__get_status,mcp__ccd_pr__bind_pr,mcp__ccd_pr__set_monitor" to load its schema before concluding it is unavailable.\n' +
513
520
  `2. ${claim} this line in your reply text, exactly: <pr-created>${pr.url}</pr-created>\n` +
514
521
  'The app lets a session turn Autofix on only for a PR it is sure the session opened, and it learns that only from a FOREGROUND `gh pr create` result or this tag; a PR opened by this hook or inside a background command has neither. Never write the tag for a PR this session did not open.\n' +
515
- `3. Call mcp__ccd_pr__get_status. If it reports no bound PR, call mcp__ccd_pr__bind_pr with url ${pr.url}.\n` +
522
+ `3. Call mcp__ccd_pr__get_status. If it reports no bound PR, call mcp__ccd_pr__bind_pr with url ${pr.url}.\n`;
523
+ const why = "tell the user in one line that Autofix could not be enabled and why, quoting the app's reason (the tag counts only within 15 minutes of the PR's creation, from the PR's own branch, and when the app's gh login authored it) — never fail silently and leave it off unreported.";
524
+ if (listed) {
525
+ return (`PR #${pr.number} (${pr.url}) ${opened}\n` +
526
+ "Standing instruction from the user: Autofix must be ON for every PR a session pushes. This PR is on this session's sarathi Auto-fix list, and sarathi's warning gives the mcp__ccd_pr__set_monitor call that switches it on. Do this now, before anything else, so that call is not refused:\n" +
527
+ steps +
528
+ `If ToolSearch cannot find mcp__ccd_pr__* at all (truly not the desktop app), or get_status/bind_pr still fails, ${why}`);
529
+ }
530
+ return (`PR #${pr.number} (${pr.url}) ${opened}\n` +
531
+ 'Standing instruction from the user: Autofix must be ON for every PR a session pushes. Do this now, before anything else:\n' +
532
+ steps +
516
533
  `4. If auto_fix is not true, call mcp__ccd_pr__set_monitor with {"auto_fix": true, "address_comments": true, "url": "${pr.url}"}. If it says the app is not sure this session opened the PR, or has not read it yet, call get_status once more and retry set_monitor once.\n` +
517
- "If ToolSearch cannot find mcp__ccd_pr__* at all (truly not the desktop app), or get_status/bind_pr/set_monitor still fails, tell the user in one line that Autofix could not be enabled and why, quoting the app's reason (the tag counts only within 15 minutes of the PR's creation, from the PR's own branch, and when the app's gh login authored it) — never fail silently and leave it off unreported.");
534
+ `If ToolSearch cannot find mcp__ccd_pr__* at all (truly not the desktop app), or get_status/bind_pr/set_monitor still fails, ${why}`);
535
+ }
536
+ /** A Claude session id sarathi lets name a list file (its `SESSION`). */
537
+ const SARATHI_SESSION = /^[\w.-]{1,128}$/;
538
+ const NAME = /^[\w.-]+$/;
539
+ export const AUTOFIX_SOURCE = 'niyam pr-autocreate';
540
+ /** owner/repo#N and the bare URL of https://<host>/<owner>/<repo>/pull/<N>, as sarathi's `fromUrl` reads one. */
541
+ function pullOf(url) {
542
+ let parsed;
543
+ try {
544
+ parsed = new URL(url);
545
+ }
546
+ catch {
547
+ // fail-open: what is not a URL names no pull request, and the whole instruction goes out
548
+ return undefined;
549
+ }
550
+ const [, owner = '', repo = '', kind, number = ''] = parsed.pathname.split('/');
551
+ if (parsed.protocol !== 'https:' || kind !== 'pull' || !NAME.test(owner) || !NAME.test(repo) || !/^\d+$/.test(number))
552
+ return undefined;
553
+ return { pr: `${owner}/${repo}#${number}`, url: `https://${parsed.host}/${owner}/${repo}/pull/${number}` };
554
+ }
555
+ /** sarathi's Auto-fix list folder: SARATHI_AUTOFIX_DIR, else $XDG_STATE_HOME/sarathi/autofix, else ~/.local/state/sarathi/autofix. */
556
+ export function autofixDir(sys) {
557
+ const override = sys.env.SARATHI_AUTOFIX_DIR;
558
+ if (override)
559
+ return override;
560
+ const state = sys.env.XDG_STATE_HOME;
561
+ return resolve(state || resolve(sys.home, '.local', 'state'), 'sarathi', 'autofix');
562
+ }
563
+ /**
564
+ * Puts the pull request on the session's sarathi Auto-fix list (sarathi
565
+ * 0.6.15's `<dir>/<session id>.jsonl`, one JSON row per fact), as `sarathi
566
+ * autofix add` does: an `opened` row, unless the list names it already, so a
567
+ * Stop after every turn adds no more. True once it is on the list; false when
568
+ * the session id cannot name a list or the row could not be written.
569
+ */
570
+ export function listForAutofix(sys, session, url) {
571
+ const pull = pullOf(url);
572
+ if (!session || !SARATHI_SESSION.test(session) || !pull)
573
+ return false;
574
+ const file = resolve(autofixDir(sys), `${session}.jsonl`);
575
+ // sarathi writes its rows with JSON.stringify, so a row for the pull request holds this text; sarathi folds two
576
+ // spellings of one together by lower case. A row this misses only adds an `opened` row sarathi ignores.
577
+ const named = JSON.stringify({ pr: pull.pr }).slice(1, -1).toLowerCase();
578
+ try {
579
+ if (sys.exists(file) && sys.read(file).toLowerCase().includes(named))
580
+ return true;
581
+ sys.mkdir(dirname(file));
582
+ // The leading newline ends a partial row a short append left, as sarathi's appendRows does.
583
+ sys.append(file, `\n${JSON.stringify({ at: sys.now().toISOString(), ...pull, event: 'opened', source: AUTOFIX_SOURCE })}\n`);
584
+ return true;
585
+ }
586
+ catch {
587
+ // fail-open: a list that cannot be read or written leaves the pull request off it, and the whole instruction goes out
588
+ return false;
589
+ }
518
590
  }
519
591
  /** How the session replaces the placeholder body. */
520
592
  function editHint(settings, pulls, number) {
521
593
  return pulls.cloud ? `gh api -X PATCH repos/${pulls.slug}/pulls/${number} -F body=@FILE` : settings.describe;
522
594
  }
523
595
  /** The instruction for the record's open pull request, once per session and pull request; empty when there is nothing to say. */
524
- async function autofixMessage(sys, root, settings, state, session, pulls) {
596
+ async function autofixMessage(sys, root, settings, state, session, pulls, listed) {
525
597
  const pr = state.pr;
526
598
  if (!pr || pr.state !== 'OPEN' || !pr.url)
527
599
  return '';
@@ -547,7 +619,7 @@ async function autofixMessage(sys, root, settings, state, session, pulls) {
547
619
  else if (body.includes(MARKER))
548
620
  opened += ` Its body is still the automatic placeholder: ${replace}`;
549
621
  }
550
- return reminder(pr, opened, state.created, pulls.cloud);
622
+ return reminder(pr, opened, state.created, pulls.cloud, listed && settings.autofixList);
551
623
  }
552
624
  /**
553
625
  * The transport with the token GitHub is asked with: a session's hook acts
@@ -672,7 +744,10 @@ export async function claudeHook(sys, io, stdin, pullsOf = pullsFor) {
672
744
  }
673
745
  if ('problem' in state)
674
746
  return bail(state.problem);
675
- let message = await autofixMessage(sys, root, settings, state, session, pulls);
747
+ // On the session's sarathi Auto-fix list, every time and before the once-only instruction, so a pull request
748
+ // told about before this release joins it too. A cloud session has no set_monitor, and sarathi is quiet there.
749
+ const listed = !pulls.cloud && state.pr?.state === 'OPEN' && Boolean(state.pr.url) && listForAutofix(sys, session, state.pr.url);
750
+ let message = await autofixMessage(sys, root, settings, state, session, pulls, listed);
676
751
  if (typeof message !== 'string')
677
752
  return bail(message.problem);
678
753
  if (!message && state.notes.length > 0 && event === 'PostToolUse') {
package/dist/run.js CHANGED
@@ -25,6 +25,7 @@ import { reviewThread, threadArgs } from './review-thread.js';
25
25
  import { onboard, onboardArgs } from './onboard.js';
26
26
  import { ownerStep, ownerStepArgs } from './owner-step.js';
27
27
  import { sessionStart } from './session-start.js';
28
+ import { SSH_SIGN, sshSign } from './ssh-sign.js';
28
29
  import { upgrade } from './upgrade.js';
29
30
  import { prMerged, prStarted, prePush, prWorkRules, propose } from './work.js';
30
31
  import { CLI } from './names.js';
@@ -52,6 +53,8 @@ Commands:
52
53
  For agents run from any tool: the GitHub lock, then the agent identity where this Mac
53
54
  has it, as shell lines for eval "$(niyam env)", or with -- the command run under them
54
55
  session-start Run by a client's SessionStart hook: the agent identity, or GitHub locked out
56
+ ssh-sign -Y sign -n <namespace> -f <key> <file>...
57
+ Run by git in a Claude cloud session, as gpg.ssh.program: signs as ssh-keygen does
55
58
  guard Run by a client's PreToolUse hook: gh and git's remote commands only as the agent
56
59
  as-agent --session <session_id> -- <command> [args...]
57
60
  For a client's hook: run one command as the session's agent, or nothing (exit ${LOCKED})
@@ -151,7 +154,7 @@ export function proposeArgs(args) {
151
154
  /** Runs one command and returns its exit code: 0 done, 1 failed, 2 bad usage. */
152
155
  export async function run(args, io, sys) {
153
156
  const [command, ...rest] = args;
154
- const allowed = command === 'onboard' || command === 'machine' || command === 'cloud-key' || command === 'review-thread' || command === 'as-agent' || command === 'env' || command === 'propose' || command === 'owner-step' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss' || command === 'pr-autocreate' || command === 'keep-going' || command === 'doc-number' || command === 'renumber-doc' || command === 'work-item-number' || command === 'board-audit' ? Infinity : command === 'pre-push' || command === 'pr-signals' ? 2 : command === 'doctor' ? 1 : 0;
157
+ const allowed = command === 'onboard' || command === 'machine' || command === 'cloud-key' || command === 'review-thread' || command === 'as-agent' || command === 'env' || command === 'propose' || command === 'owner-step' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss' || command === 'pr-autocreate' || command === 'keep-going' || command === 'doc-number' || command === 'renumber-doc' || command === 'work-item-number' || command === 'board-audit' || command === SSH_SIGN ? Infinity : command === 'pre-push' || command === 'pr-signals' ? 2 : command === 'doctor' ? 1 : 0;
155
158
  const extra = rest[allowed];
156
159
  if (extra !== undefined) {
157
160
  io.err(`niyam: unexpected argument "${extra}"`);
@@ -183,6 +186,8 @@ export async function run(args, io, sys) {
183
186
  return 0;
184
187
  case 'cloud-setup':
185
188
  return cloudSetup(io);
189
+ case SSH_SIGN:
190
+ return sshSign(io, rest);
186
191
  case 'session-start':
187
192
  return sessionStart(await sys(), io);
188
193
  case 'guard':
package/dist/secrets.js CHANGED
@@ -8,48 +8,96 @@ import { API } from './agent.js';
8
8
  export async function secretNames(sys, slug, token) {
9
9
  const names = [];
10
10
  for (const kind of ['secrets', 'organization-secrets']) {
11
- for (let page = 1;; page++) {
12
- const listed = await sys.http(`${API}/repos/${slug}/actions/${kind}?per_page=100&page=${page}`, { token });
13
- const secrets = listed.json?.secrets;
14
- if (listed.status !== 200 || !Array.isArray(secrets))
15
- return undefined;
16
- names.push(...secrets.flatMap((secret) => (typeof secret?.name === 'string' ? [secret.name] : [])));
17
- if (secrets.length < 100)
18
- break;
19
- }
11
+ const listed = await listNames(sys, `${API}/repos/${slug}/actions/${kind}`, token);
12
+ if (listed === undefined)
13
+ return undefined;
14
+ names.push(...listed);
20
15
  }
21
16
  return names;
22
17
  }
18
+ /** The names of `slug`'s own Actions secrets, not its organization's, as `token` sees them; undefined when GitHub will not list them. */
19
+ export function repoSecretNames(sys, slug, token) {
20
+ return listNames(sys, `${API}/repos/${slug}/actions/secrets`, token);
21
+ }
22
+ /** The names of the organization `org`'s own Actions secrets, as `token` sees them; undefined when GitHub will not list them. */
23
+ export function orgSecretNames(sys, org, token) {
24
+ return listNames(sys, `${API}/orgs/${org}/actions/secrets`, token);
25
+ }
26
+ /** The names of the secrets GitHub lists at `url`, page by page; undefined when it will not list them. */
27
+ async function listNames(sys, url, token) {
28
+ const names = [];
29
+ for (let page = 1;; page++) {
30
+ const listed = await sys.http(`${url}?per_page=100&page=${page}`, { token });
31
+ const secrets = listed.json?.secrets;
32
+ if (listed.status !== 200 || !Array.isArray(secrets))
33
+ return undefined;
34
+ names.push(...secrets.flatMap((secret) => (typeof secret?.name === 'string' ? [secret.name] : [])));
35
+ if (secrets.length < 100)
36
+ return names;
37
+ }
38
+ }
23
39
  /**
24
- * Sets the Actions secret `name` of `slug` to `value`, as the account `token`
25
- * is: GitHub takes a secret only sealed with the repository's Actions public
26
- * key, as a libsodium sealed box, so the value never reaches GitHub, or any
27
- * output, in the clear. Returns why it failed, never naming the value.
40
+ * `value` sealed with the Actions public key GitHub gives at `keyUrl`, as a
41
+ * libsodium sealed box, so the value never reaches GitHub, or any output, in
42
+ * the clear; or why not, naming `where` and never the value.
28
43
  */
29
- export async function setSecret(sys, slug, token, name, value) {
30
- const asked = await sys.http(`${API}/repos/${slug}/actions/secrets/public-key`, { token });
44
+ async function seal(sys, keyUrl, token, where, name, value) {
45
+ const asked = await sys.http(keyUrl, { token });
31
46
  const { key_id: id, key } = (asked.json ?? {});
32
47
  if (asked.status !== 200 || typeof id !== 'string' || typeof key !== 'string') {
33
- return `GitHub did not give ${slug}'s Actions public key (HTTP ${asked.status}), so the ${name} secret is not set`;
48
+ return { problem: `GitHub did not give ${where}'s Actions public key (HTTP ${asked.status}), so the ${name} secret is not set` };
34
49
  }
35
50
  // Loaded here alone: the shared checks run the CLI from its source with no packages installed.
36
51
  const { default: sodium } = await import('libsodium-wrappers');
37
52
  await sodium.ready;
38
- let sealed;
39
53
  try {
40
- sealed = sodium.crypto_box_seal(new TextEncoder().encode(value), Buffer.from(key, 'base64'));
54
+ return { encrypted_value: Buffer.from(sodium.crypto_box_seal(new TextEncoder().encode(value), Buffer.from(key, 'base64'))).toString('base64'), key_id: id };
41
55
  }
42
56
  catch {
43
- return `${slug}'s Actions public key is not one a secret can be sealed with, so the ${name} secret is not set`;
57
+ return { problem: `${where}'s Actions public key is not one a secret can be sealed with, so the ${name} secret is not set` };
44
58
  }
45
- const put = await sys.http(`${API}/repos/${slug}/actions/secrets/${name}`, {
46
- method: 'PUT',
47
- token,
48
- body: { encrypted_value: Buffer.from(sealed).toString('base64'), key_id: id },
49
- });
50
- // 201: made; 204: replaced.
59
+ }
60
+ /** Why a PUT of the secret `name` failed; nothing when GitHub made (201) or replaced (204) it. */
61
+ function putProblem(name, put) {
51
62
  if (put.status === 201 || put.status === 204)
52
63
  return undefined;
53
64
  const why = put.json?.message;
54
65
  return `GitHub did not set the ${name} secret (HTTP ${put.status}${typeof why === 'string' ? `: ${why}` : ''})`;
55
66
  }
67
+ /**
68
+ * Sets the Actions secret `name` of `slug` to `value`, as the account `token`
69
+ * is, sealed with the repository's Actions public key. Returns why it failed,
70
+ * never naming the value.
71
+ */
72
+ export async function setSecret(sys, slug, token, name, value) {
73
+ const sealed = await seal(sys, `${API}/repos/${slug}/actions/secrets/public-key`, token, slug, name, value);
74
+ if ('problem' in sealed)
75
+ return sealed.problem;
76
+ return putProblem(name, await sys.http(`${API}/repos/${slug}/actions/secrets/${name}`, { method: 'PUT', token, body: sealed }));
77
+ }
78
+ /**
79
+ * Sets the organization `org`'s Actions secret `name` to `value`, shared
80
+ * with the repositories `repositoryIds` alone, as the account `token` is,
81
+ * sealed with the organization's Actions public key. Returns why it failed,
82
+ * never naming the value.
83
+ */
84
+ export async function setOrgSecret(sys, org, token, name, value, repositoryIds) {
85
+ const sealed = await seal(sys, `${API}/orgs/${org}/actions/secrets/public-key`, token, org, name, value);
86
+ if ('problem' in sealed)
87
+ return sealed.problem;
88
+ const body = { ...sealed, visibility: 'selected', selected_repository_ids: repositoryIds };
89
+ return putProblem(name, await sys.http(`${API}/orgs/${org}/actions/secrets/${name}`, { method: 'PUT', token, body }));
90
+ }
91
+ /**
92
+ * Shares the organization `org`'s Actions secret `name`, one with selected
93
+ * repositories, with the repository `repositoryId` too. Returns why not.
94
+ */
95
+ export async function shareOrgSecret(sys, org, token, name, repositoryId) {
96
+ const put = await sys.http(`${API}/orgs/${org}/actions/secrets/${name}/repositories/${repositoryId}`, { method: 'PUT', token });
97
+ if (put.status === 204)
98
+ return undefined;
99
+ // 409: the secret's visibility is all or private repositories, so GitHub decides by that which repositories see it.
100
+ return put.status === 409
101
+ ? `${org}'s ${name} secret is visible by type of repository, not to selected ones, so GitHub will not add one to it`
102
+ : `GitHub did not share ${org}'s ${name} secret with the repository (HTTP ${put.status})`;
103
+ }
@@ -0,0 +1,84 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs';
2
+ import { quote } from './agent.js';
3
+ import { errorDetail } from './error-detail.js';
4
+ import { readPrivateKey, signMessage } from './sshsig.js';
5
+ /** The command git runs as `gpg.ssh.program` in a cloud session niyam signs for (#425). */
6
+ export const SSH_SIGN = 'ssh-sign';
7
+ /**
8
+ * The script git runs as `gpg.ssh.program`: niyam's own signer, with the
9
+ * Node and CLI that wrote it, since git runs the program as a path alone.
10
+ */
11
+ export function signerScript(node, cli) {
12
+ return ['#!/bin/sh', `# Written by niyam session-start: git's SSH signer for this cloud session, which has no ssh-keygen.`, `exec ${quote(node)} ${quote(cli)} ${SSH_SIGN} "$@"`, ''].join('\n');
13
+ }
14
+ /**
15
+ * Signs as `ssh-keygen -Y sign -n <namespace> -f <key> <file>…` does, for
16
+ * git's SSH signing where there is no ssh-keygen: each file's signature goes
17
+ * to `<file>.sig`. The key is `-f`'s file, or, when that is a `.pub`, the
18
+ * private key beside it, as git names `user.signingkey`. Only an unencrypted
19
+ * ed25519 key, and only `-Y sign`: anything else fails, naming it.
20
+ */
21
+ export function sshSign(io, args) {
22
+ const fail = (why) => {
23
+ io.err(`niyam ${SSH_SIGN}: ${why}`);
24
+ return 1;
25
+ };
26
+ if (args[0] !== '-Y' || args[1] !== 'sign')
27
+ return fail(`signs only, as ssh-keygen -Y sign does; asked for ${args.slice(0, 2).join(' ') || 'nothing'}`);
28
+ let namespace;
29
+ let keyFile;
30
+ const files = [];
31
+ for (let i = 2; i < args.length; i += 1) {
32
+ const arg = args[i];
33
+ if (arg === '-n' || arg === '-f') {
34
+ const value = args[i + 1];
35
+ if (value === undefined)
36
+ return fail(`${arg} needs a value`);
37
+ if (arg === '-n')
38
+ namespace = value;
39
+ else
40
+ keyFile = value;
41
+ i += 1;
42
+ }
43
+ else if (arg === '-U') {
44
+ return fail('cannot sign with a key in an agent (-U); user.signingkey must name the key file');
45
+ }
46
+ else if (arg === '-q') {
47
+ // Quiet already: it prints nothing on success.
48
+ }
49
+ else if (arg.startsWith('-')) {
50
+ return fail(`unknown option ${arg}`);
51
+ }
52
+ else {
53
+ files.push(arg);
54
+ }
55
+ }
56
+ if (!namespace)
57
+ return fail('no namespace (-n)');
58
+ if (!keyFile)
59
+ return fail('no key (-f)');
60
+ if (files.length === 0)
61
+ return fail('no file to sign');
62
+ const privateFile = keyFile.endsWith('.pub') ? keyFile.slice(0, -'.pub'.length) : keyFile;
63
+ let text;
64
+ try {
65
+ text = readFileSync(privateFile, 'utf8');
66
+ }
67
+ catch (error) {
68
+ // fail-open: git reports the signing failure, with this line.
69
+ return fail(`cannot read the key ${privateFile} (${errorDetail(error)})`);
70
+ }
71
+ const key = readPrivateKey(text);
72
+ if ('problem' in key)
73
+ return fail(`the key ${privateFile}: ${key.problem}`);
74
+ for (const file of files) {
75
+ try {
76
+ writeFileSync(`${file}.sig`, signMessage(key, readFileSync(file), namespace), { mode: 0o644 });
77
+ }
78
+ catch (error) {
79
+ // fail-open: git reports the signing failure, with this line.
80
+ return fail(`cannot sign ${file} (${errorDetail(error)})`);
81
+ }
82
+ }
83
+ return 0;
84
+ }
package/dist/sshsig.js ADDED
@@ -0,0 +1,218 @@
1
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign, verify } from 'node:crypto';
2
+ import { errorDetail } from './error-detail.js';
3
+ /**
4
+ * SSH signing in Node, for the hosted Claude cloud image, which has no
5
+ * ssh-keygen (#425): the unencrypted ed25519 key an OpenSSH private key file
6
+ * holds, and SSHSIG signatures over it, as `ssh-keygen -Y sign` makes them
7
+ * and `ssh-keygen -Y verify` and GitHub check them (OpenSSH's PROTOCOL.sshsig
8
+ * and PROTOCOL.key).
9
+ */
10
+ const PEM_BEGIN = '-----BEGIN OPENSSH PRIVATE KEY-----';
11
+ const PEM_END = '-----END OPENSSH PRIVATE KEY-----';
12
+ const SIG_BEGIN = '-----BEGIN SSH SIGNATURE-----';
13
+ const SIG_END = '-----END SSH SIGNATURE-----';
14
+ const KEY_MAGIC = 'openssh-key-v1\0';
15
+ const SIG_MAGIC = 'SSHSIG';
16
+ const ED25519 = 'ssh-ed25519';
17
+ const HASH = 'sha512';
18
+ /** Reads SSH wire-format fields from a buffer, throwing on a field that runs past its end. */
19
+ class Reader {
20
+ at = 0;
21
+ data;
22
+ constructor(data) {
23
+ this.data = data;
24
+ }
25
+ uint32() {
26
+ if (this.at + 4 > this.data.length)
27
+ throw new Error('it ends early');
28
+ const value = this.data.readUInt32BE(this.at);
29
+ this.at += 4;
30
+ return value;
31
+ }
32
+ bytes(length) {
33
+ if (this.at + length > this.data.length)
34
+ throw new Error('it ends early');
35
+ const value = this.data.subarray(this.at, this.at + length);
36
+ this.at += length;
37
+ return value;
38
+ }
39
+ string() {
40
+ return this.bytes(this.uint32());
41
+ }
42
+ text() {
43
+ return this.string().toString('latin1');
44
+ }
45
+ get done() {
46
+ return this.at === this.data.length;
47
+ }
48
+ }
49
+ function field(value) {
50
+ const bytes = typeof value === 'string' ? Buffer.from(value, 'latin1') : value;
51
+ const length = Buffer.alloc(4);
52
+ length.writeUInt32BE(bytes.length);
53
+ return Buffer.concat([length, bytes]);
54
+ }
55
+ /** The key's public blob, as SSH writes it: its type, then the 32 bytes. */
56
+ function publicBlob(publicKey) {
57
+ return Buffer.concat([field(ED25519), field(publicKey)]);
58
+ }
59
+ /**
60
+ * The ed25519 key in an OpenSSH private key file's text, or why it cannot be
61
+ * used: niyam signs with an unencrypted ed25519 key alone, which is what
62
+ * `niyam cloud-key` makes.
63
+ */
64
+ export function readPrivateKey(text) {
65
+ const trimmed = text.trim();
66
+ if (!trimmed.startsWith(PEM_BEGIN) || !trimmed.endsWith(PEM_END))
67
+ return { problem: 'it is not an OpenSSH private key' };
68
+ const data = Buffer.from(trimmed.slice(PEM_BEGIN.length, -PEM_END.length).replace(/\s+/g, ''), 'base64');
69
+ try {
70
+ if (data.subarray(0, KEY_MAGIC.length).toString('latin1') !== KEY_MAGIC)
71
+ return { problem: 'it is not an OpenSSH private key' };
72
+ const reader = new Reader(data.subarray(KEY_MAGIC.length));
73
+ const cipher = reader.text();
74
+ const kdf = reader.text();
75
+ reader.string();
76
+ if (cipher !== 'none' || kdf !== 'none')
77
+ return { problem: 'it has a passphrase, and niyam signs with a key that has none' };
78
+ if (reader.uint32() !== 1)
79
+ return { problem: 'it holds more than one key' };
80
+ reader.string();
81
+ const secret = new Reader(reader.string());
82
+ if (secret.uint32() !== secret.uint32())
83
+ return { problem: 'its check numbers differ' };
84
+ const type = secret.text();
85
+ if (type !== ED25519)
86
+ return { problem: `it is a ${type} key, and niyam signs with ed25519 alone` };
87
+ const publicKey = secret.string();
88
+ const both = secret.string();
89
+ if (publicKey.length !== 32 || both.length !== 64 || !both.subarray(32).equals(publicKey))
90
+ return { problem: 'its ed25519 halves do not match' };
91
+ return { seed: Buffer.from(both.subarray(0, 32)), publicKey: Buffer.from(publicKey) };
92
+ }
93
+ catch (error) {
94
+ // fail-open: a key niyam cannot read is a problem the caller reports, never a crash.
95
+ return { problem: `it cannot be read (${errorDetail(error)})` };
96
+ }
97
+ }
98
+ /** The key's public half as a line of an authorized_keys file, with no comment. */
99
+ export function publicLine(key) {
100
+ return `${ED25519} ${publicBlob(key.publicKey).toString('base64')}`;
101
+ }
102
+ /** A new ed25519 key pair from Node's crypto, held in memory alone (#437). */
103
+ export function newKey() {
104
+ const { privateKey } = generateKeyPairSync('ed25519');
105
+ const { d, x } = privateKey.export({ format: 'jwk' });
106
+ return { seed: Buffer.from(d, 'base64url'), publicKey: Buffer.from(x, 'base64url') };
107
+ }
108
+ function uint32(value) {
109
+ const bytes = Buffer.alloc(4);
110
+ bytes.writeUInt32BE(value);
111
+ return bytes;
112
+ }
113
+ /**
114
+ * `key` as an unencrypted OpenSSH private key file's text, as `ssh-keygen -N ''`
115
+ * writes one (PROTOCOL.key), with `comment`: what `readPrivateKey` and
116
+ * ssh-keygen read back.
117
+ */
118
+ export function privateKeyText(key, comment) {
119
+ const check = randomBytes(4);
120
+ const secret = Buffer.concat([check, check, field(ED25519), field(key.publicKey), field(Buffer.concat([key.seed, key.publicKey])), field(Buffer.from(comment, 'utf8'))]);
121
+ // Padded to the cipher's block size, 8 with none, by the bytes 1, 2, 3, … as OpenSSH pads it.
122
+ const padding = Buffer.from(Array.from({ length: (8 - (secret.length % 8)) % 8 }, (_, i) => i + 1));
123
+ const body = Buffer.concat([Buffer.from(KEY_MAGIC, 'latin1'), field('none'), field('none'), field(''), uint32(1), field(publicBlob(key.publicKey)), field(Buffer.concat([secret, padding]))]).toString('base64');
124
+ return `${PEM_BEGIN}\n${body.match(/.{1,70}/g)?.join('\n') ?? ''}\n${PEM_END}\n`;
125
+ }
126
+ function base64url(bytes) {
127
+ return bytes.toString('base64url');
128
+ }
129
+ /** What SSHSIG signs: its preamble, the namespace, and the message's sha512. */
130
+ function signedData(message, namespace) {
131
+ return Buffer.concat([Buffer.from(SIG_MAGIC, 'latin1'), field(namespace), field(''), field(HASH), field(createHash(HASH).update(message).digest())]);
132
+ }
133
+ /** An armored SSHSIG signature of `message` by `key`, in `namespace`, as `ssh-keygen -Y sign` writes it. */
134
+ export function signMessage(key, message, namespace) {
135
+ const privateKey = createPrivateKey({ key: { kty: 'OKP', crv: 'Ed25519', d: base64url(key.seed), x: base64url(key.publicKey) }, format: 'jwk' });
136
+ const signature = sign(null, signedData(message, namespace), privateKey);
137
+ const version = Buffer.alloc(4);
138
+ version.writeUInt32BE(1);
139
+ const blob = Buffer.concat([
140
+ Buffer.from(SIG_MAGIC, 'latin1'),
141
+ version,
142
+ field(publicBlob(key.publicKey)),
143
+ field(namespace),
144
+ field(''),
145
+ field(HASH),
146
+ field(Buffer.concat([field(ED25519), field(signature)])),
147
+ ]).toString('base64');
148
+ return `${SIG_BEGIN}\n${blob.match(/.{1,70}/g)?.join('\n') ?? ''}\n${SIG_END}\n`;
149
+ }
150
+ /**
151
+ * Whether `armored` is an SSHSIG signature of `message` in `namespace` by the
152
+ * key whose public line is `publicKeyLine`; undefined when it is, else why not.
153
+ */
154
+ export function signatureProblem(armored, message, namespace, publicKeyLine) {
155
+ const trimmed = armored.trim();
156
+ if (!trimmed.startsWith(SIG_BEGIN) || !trimmed.endsWith(SIG_END))
157
+ return 'it is not an SSH signature';
158
+ try {
159
+ const data = Buffer.from(trimmed.slice(SIG_BEGIN.length, -SIG_END.length).replace(/\s+/g, ''), 'base64');
160
+ if (data.subarray(0, SIG_MAGIC.length).toString('latin1') !== SIG_MAGIC)
161
+ return 'it is not an SSH signature';
162
+ const reader = new Reader(data.subarray(SIG_MAGIC.length));
163
+ if (reader.uint32() !== 1)
164
+ return 'its version is not 1';
165
+ const signer = reader.string();
166
+ const signedNamespace = reader.text();
167
+ reader.string();
168
+ const hash = reader.text();
169
+ const signature = new Reader(reader.string());
170
+ if (!reader.done)
171
+ return 'it has bytes after the signature';
172
+ if (signedNamespace !== namespace)
173
+ return `it is for the namespace "${signedNamespace}", not "${namespace}"`;
174
+ if (hash !== HASH)
175
+ return `it hashes with ${hash}, not ${HASH}`;
176
+ if (`${ED25519} ${signer.toString('base64')}` !== publicKeyLine.trim().split(/\s+/).slice(0, 2).join(' '))
177
+ return 'another key made it';
178
+ if (signature.text() !== ED25519)
179
+ return 'it is not an ed25519 signature';
180
+ const bytes = signature.string();
181
+ const keyBytes = new Reader(signer);
182
+ keyBytes.string();
183
+ const publicKey = createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: base64url(keyBytes.string()) }, format: 'jwk' });
184
+ return verify(null, signedData(message, namespace), publicKey, bytes) ? undefined : 'the signature does not match';
185
+ }
186
+ catch (error) {
187
+ // fail-open: a signature niyam cannot read is one that does not verify.
188
+ return `it cannot be read (${errorDetail(error)})`;
189
+ }
190
+ }
191
+ /**
192
+ * A raw commit object split into what its SSH signature signs, the object
193
+ * without its gpgsig header, and that signature; none when it has no gpgsig.
194
+ */
195
+ export function commitSignature(raw) {
196
+ const end = raw.indexOf('\n\n');
197
+ const headers = (end === -1 ? raw : raw.slice(0, end)).split('\n');
198
+ const rest = end === -1 ? '' : raw.slice(end);
199
+ const kept = [];
200
+ const signature = [];
201
+ let inSignature = false;
202
+ for (const line of headers) {
203
+ if (line.startsWith('gpgsig ')) {
204
+ inSignature = true;
205
+ signature.push(line.slice('gpgsig '.length));
206
+ }
207
+ else if (inSignature && line.startsWith(' ')) {
208
+ signature.push(line.slice(1));
209
+ }
210
+ else {
211
+ inSignature = false;
212
+ kept.push(line);
213
+ }
214
+ }
215
+ if (signature.length === 0)
216
+ return undefined;
217
+ return { payload: Buffer.from(`${kept.join('\n')}${rest}`, 'utf8'), signature: `${signature.join('\n')}\n` };
218
+ }
package/dist/sys.js CHANGED
@@ -189,6 +189,31 @@ export function realSys() {
189
189
  open(url) {
190
190
  spawnSync('open', [url]);
191
191
  },
192
+ serve(handle) {
193
+ const server = http.createServer((request, response) => {
194
+ const answer = (status, headers = {}, body = '') => {
195
+ response.writeHead(status, { 'cache-control': 'no-store', ...headers });
196
+ response.end(body);
197
+ };
198
+ if (request.method !== 'GET')
199
+ return answer(405, { allow: 'GET' });
200
+ const url = new URL(request.url ?? '/', 'http://127.0.0.1');
201
+ handle({ path: url.pathname, query: Object.fromEntries(url.searchParams) }).then(({ status, headers, body }) => answer(status, headers, body), () => answer(500));
202
+ });
203
+ return new Promise((done, fail) => {
204
+ server.once('error', fail);
205
+ server.listen(0, '127.0.0.1', () => {
206
+ const { port } = server.address();
207
+ done({
208
+ port,
209
+ close() {
210
+ server.closeAllConnections();
211
+ server.close();
212
+ },
213
+ });
214
+ });
215
+ });
216
+ },
192
217
  onInterrupt(handler) {
193
218
  process.on('SIGINT', handler);
194
219
  return () => {