@memnexus-ai/mx-agent-cli 0.1.297 → 0.1.299

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 (75) hide show
  1. package/dist/agent-config/hooks/gh-pr-edit-guard.sh +21 -9
  2. package/dist/agent-config/settings.json +7 -1
  3. package/dist/commands/bootstrap.d.ts.map +1 -1
  4. package/dist/commands/bootstrap.js +5 -0
  5. package/dist/commands/bootstrap.js.map +1 -1
  6. package/dist/commands/check.d.ts +20 -0
  7. package/dist/commands/check.d.ts.map +1 -0
  8. package/dist/commands/check.js +30 -0
  9. package/dist/commands/check.js.map +1 -0
  10. package/dist/commands/create.d.ts.map +1 -1
  11. package/dist/commands/create.js +5 -0
  12. package/dist/commands/create.js.map +1 -1
  13. package/dist/commands/gh.d.ts +38 -0
  14. package/dist/commands/gh.d.ts.map +1 -0
  15. package/dist/commands/gh.js +162 -0
  16. package/dist/commands/gh.js.map +1 -0
  17. package/dist/commands/git-credential.d.ts +22 -0
  18. package/dist/commands/git-credential.d.ts.map +1 -0
  19. package/dist/commands/git-credential.js +53 -0
  20. package/dist/commands/git-credential.js.map +1 -0
  21. package/dist/commands/init.d.ts.map +1 -1
  22. package/dist/commands/init.js +7 -0
  23. package/dist/commands/init.js.map +1 -1
  24. package/dist/commands/new.d.ts +24 -0
  25. package/dist/commands/new.d.ts.map +1 -1
  26. package/dist/commands/new.js +68 -6
  27. package/dist/commands/new.js.map +1 -1
  28. package/dist/commands/pr-set-body.d.ts +120 -35
  29. package/dist/commands/pr-set-body.d.ts.map +1 -1
  30. package/dist/commands/pr-set-body.js +343 -108
  31. package/dist/commands/pr-set-body.js.map +1 -1
  32. package/dist/commands/pr-sync.d.ts +2 -1
  33. package/dist/commands/pr-sync.d.ts.map +1 -1
  34. package/dist/commands/pr-sync.js +129 -32
  35. package/dist/commands/pr-sync.js.map +1 -1
  36. package/dist/index.d.ts +3 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +82 -2
  39. package/dist/index.js.map +1 -1
  40. package/dist/lib/check-run.d.ts +131 -0
  41. package/dist/lib/check-run.d.ts.map +1 -0
  42. package/dist/lib/check-run.js +291 -0
  43. package/dist/lib/check-run.js.map +1 -0
  44. package/dist/lib/coordination-token.d.ts +39 -1
  45. package/dist/lib/coordination-token.d.ts.map +1 -1
  46. package/dist/lib/coordination-token.js +149 -9
  47. package/dist/lib/coordination-token.js.map +1 -1
  48. package/dist/lib/creation-login.d.ts +42 -0
  49. package/dist/lib/creation-login.d.ts.map +1 -0
  50. package/dist/lib/creation-login.js +62 -0
  51. package/dist/lib/creation-login.js.map +1 -0
  52. package/dist/lib/gh-remote.d.ts +46 -5
  53. package/dist/lib/gh-remote.d.ts.map +1 -1
  54. package/dist/lib/gh-remote.js +80 -16
  55. package/dist/lib/gh-remote.js.map +1 -1
  56. package/dist/lib/gh-token-run.d.ts +551 -0
  57. package/dist/lib/gh-token-run.d.ts.map +1 -0
  58. package/dist/lib/gh-token-run.js +1246 -0
  59. package/dist/lib/gh-token-run.js.map +1 -0
  60. package/dist/lib/git-credential.d.ts +120 -0
  61. package/dist/lib/git-credential.d.ts.map +1 -0
  62. package/dist/lib/git-credential.js +204 -0
  63. package/dist/lib/git-credential.js.map +1 -0
  64. package/dist/lib/github-app-token.d.ts +288 -0
  65. package/dist/lib/github-app-token.d.ts.map +1 -0
  66. package/dist/lib/github-app-token.js +519 -0
  67. package/dist/lib/github-app-token.js.map +1 -0
  68. package/dist/lib/memory.d.ts.map +1 -1
  69. package/dist/lib/memory.js +35 -2
  70. package/dist/lib/memory.js.map +1 -1
  71. package/dist/lib/repo-guard-state-dirs.d.ts +39 -0
  72. package/dist/lib/repo-guard-state-dirs.d.ts.map +1 -0
  73. package/dist/lib/repo-guard-state-dirs.js +170 -0
  74. package/dist/lib/repo-guard-state-dirs.js.map +1 -0
  75. package/package.json +1 -1
@@ -0,0 +1,1246 @@
1
+ /**
2
+ * gh-token-run -- run the real `gh` with an mx-bott `gh` token in the child's
3
+ * environment only (#440, v56).
4
+ *
5
+ * WHAT THIS DOES. runGhWithToken(args, deps) checks the gh arguments against a
6
+ * fixed allowlist, mints an installation token with the `gh` permission set
7
+ * in-process, and spawns /usr/bin/gh with that token in one place: the
8
+ * `GH_TOKEN` variable of the child's environment. The product owner accepted
9
+ * that one place on 2026-10-19 (#440 comment 6279203208). This module never
10
+ * puts the token in its own environment, an argument, a file or its output.
11
+ *
12
+ * NOT ENABLED BY THIS MODULE. Nothing here installs a PATH shim, edits a hook
13
+ * or changes any config. Plain `gh` still uses the product owner's saved login.
14
+ *
15
+ * ARGUMENTS ARE AN ALLOWLIST (v56 plan revision 1, SF1, #440 comment
16
+ * 6279235415). The first argument names a command, and for a group the second
17
+ * names a subcommand; both must be on ALLOWED_COMMANDS. Every later argument
18
+ * starting with `-` must exactly match a flag listed for that subcommand.
19
+ * A joined form such as `-XPOST` or `--method=POST` matches nothing and is
20
+ * refused. A flag that takes a value consumes the next argument, which must
21
+ * not start with `-`. `api` takes exactly one endpoint under API_ENDPOINT_PREFIX.
22
+ *
23
+ * `--body-file` IS READ BY THE WRAPPER, NOT BY GH (v70, #761; plan comment
24
+ * 6406642967, revision 1 comment 6406680912; product owner decision 2026-10-26,
25
+ * memory 8b6e82de). Only on BODY_FILE_COMMANDS: `pr create`, `pr edit`,
26
+ * `pr comment`, `issue create`, `issue edit` and `issue comment`. The order is
27
+ * parse (planBodyFile, which puts a fixed placeholder `--body` in the argv),
28
+ * checkGhArgs on that argv, read (readBodyFileForGh, once), rewrite
29
+ * (bodyFileGhArgs), mint. gh gets the joined form `--body=<text>`, so a body
30
+ * starting with `-` reaches gh as the value. gh never opens the path.
31
+ * `--body-file` stays in ALWAYS_REFUSED_FLAGS and in no allowlist table, so a
32
+ * `--body-file` that reaches checkGhArgs (any other subcommand, `api`
33
+ * included) is still `flag-not-allowed`. The read resolves the path against
34
+ * the caller's cwd, refuses BODY_FILE_DENYLIST_HOME under both `os.homedir()`
35
+ * and the passwd home, `$GH_CONFIG_DIR`, `$XDG_CONFIG_HOME/gh`,
36
+ * BODY_FILE_DENYLIST_ROOT, and a hard link to a listed file or a file
37
+ * directly inside a listed directory; see deniedIdentities for the gap. That denylist
38
+ * is NOT an access control: one `cp` to a new path defeats it, and any other
39
+ * file this user can read can be posted, as `--body "$(cat <file>)"` already
40
+ * allows. `-F`, `--input`, `-f`, `--field`, `--raw-field`, `-X` and
41
+ * `--method` stay refused on every subcommand.
42
+ *
43
+ * NO IN-PROCESS FILTERS (security review on PR #705, Must Fix). gh evaluates
44
+ * `--jq` with gojq inside the gh process, and gojq's `$ENV` and `env` read
45
+ * that process's environment, which holds GH_TOKEN. So `--jq`, `-q` and
46
+ * `--slurp` are refused everywhere. `--template` and `-t` are refused too
47
+ * (lead decision). Pipe `--json` output to the system `jq` instead.
48
+ *
49
+ * NO OTHER HOST (security review on PR #705, SF). gh reads a host from a
50
+ * `HOST/OWNER/REPO` argument or a URL, and sends GH_TOKEN to `*.ghe.com` and
51
+ * `github.localhost`. Every positional and every non-free-text flag value is
52
+ * checked by isAllowedValue(). Free text (titles, bodies, comments, searches)
53
+ * is not read as a host by gh and is not checked.
54
+ *
55
+ * THE CHILD ENVIRONMENT IS AN ALLOWLIST (SF2). buildChildEnv() copies only
56
+ * LANG and TERM from this process, then sets fixed values. PATH is fixed.
57
+ * No pager, editor, browser, proxy, CA override, GH_ENTERPRISE_* or debug
58
+ * variable reaches gh. HOME and GH_CONFIG_DIR are one empty 0700 temp dir, so
59
+ * gh never reads the product owner's hosts.yml. The dir is removed when gh
60
+ * exits, and on SIGINT, SIGTERM and SIGHUP.
61
+ *
62
+ * GH RUNS IN THE WRAPPER'S OWN TEMP DIR (v69, #763; plan comment 6405228134,
63
+ * revision 1 comment 6405259462). The spawn `cwd` is that same temp dir, never
64
+ * the caller's working directory. The dir is a plain directory, not a git
65
+ * repository. buildChildEnv() sets `GIT_CEILING_DIRECTORIES` to the absolute
66
+ * parent of the temp dir, so git that gh starts finds no repository there and
67
+ * does not search upward. Without the ceiling, a caller-set `TMPDIR` inside a
68
+ * repository would put that repository's fsmonitor, hooks and aliases back in
69
+ * reach (red-team on the v69 plan). GH_REPO already names the repository, so
70
+ * gh needs no remote from git. Whether every shipped command still works from
71
+ * the plain directory is shown only by the live rows, not by this module.
72
+ * The ceiling covers git that gh starts in its working directory. It does not
73
+ * cover git started with `-C <dir>`, git started in another directory, or
74
+ * `gh --version`, which runs outside the ceiling. (v71, #759 V69-3.)
75
+ *
76
+ * A TEMP PARENT HOLDING `:` IS REFUSED (v69, lead decision on PR #766). Git
77
+ * splits `GIT_CEILING_DIRECTORIES` on `:`, so a parent such as `<repo>/a:b`
78
+ * becomes two wrong entries and git walks up into `<repo>`. runGhWithToken
79
+ * checks the parent right after makeTempDir(), before any mint, removes the
80
+ * dir and refuses with `tempdir-unsafe`. buildChildEnv() throws on the same
81
+ * condition, so no caller can build a child env with a split ceiling.
82
+ *
83
+ * REVOKE WHEN GH EXITS (#440 v59, #707 item 3; plan comment 6282796699,
84
+ * revision 1 comment 6282817801). Once a token is minted, the injected
85
+ * `revoke` runs once: after gh exits with any status, after a spawn failure,
86
+ * and on SIGINT, SIGTERM or SIGHUP after the temp dir is removed. One shared
87
+ * single-flight promise serves every path. Each attempt is bounded by
88
+ * REVOKE_TIMEOUT_MS. A failure writes `mx-agent gh: revoke-failed` and never
89
+ * changes the exit status, which stays gh's. A second signal during the revoke
90
+ * exits at once. SIGKILL or a crash skips the revoke, and the token then lives
91
+ * for its 1 hour.
92
+ *
93
+ * FIXED, NO OVERRIDES. The gh path, the permission set and the repository are
94
+ * constants. No flag, environment variable or parameter changes them. The gh
95
+ * path is absolute and has no PATH fallback.
96
+ *
97
+ * FAIL CLOSED. Every refusal and failure writes one stderr line naming a code
98
+ * only, spawns nothing it has not yet spawned, and returns non-zero. gh's own
99
+ * exit status passes through. No refusal writes a second line: v68 removed the
100
+ * two hint lines (`pr checks` and plain `pr view`) with the refusals they
101
+ * followed.
102
+ *
103
+ * THE `gh` SET HOLDS `contents: read` (v68, #757). Product owner decision
104
+ * 2026-10-25 (#757 comment 6396745069, memory cd571fc0). The measurement under
105
+ * the new set (#757 comment 6397047004, engineer and witness agree) exited 0
106
+ * for `pr create --dry-run`, `pr checks <n> --json`, plain `pr view <n>`,
107
+ * `pr view <branch>`, `pr diff <branch>` and `pr diff <n>`. The decision table
108
+ * (#757 comments 6396788460 and 6396808436) directs what follows.
109
+ *
110
+ * `pr checks <selector> --json <fields>` IS ALLOWED AGAIN (v68). `--json` is
111
+ * required and is its only flag; `--watch` and `--required` stay refused until
112
+ * measured. The selector must be a number or a pull request URL in this
113
+ * repository (`pr-number-required`). With none, gh reads the current branch
114
+ * from git in the working directory. A branch is refused because
115
+ * `pr checks <branch>` was not measured; gh's finder runs no git for a
116
+ * non-empty branch (security review at 121b903, INFO).
117
+ *
118
+ * PLAIN `pr view` IS ALLOWED AGAIN (v68). The v67 `json-required` refusal for
119
+ * `pr view` is removed, so `-c`/`--comments` work too.
120
+ *
121
+ * `pr view` AND `pr diff` TAKE A NUMBER, A BRANCH OR A PULL REQUEST URL (v68).
122
+ * Exactly one selector. No selector is refused with `pr-number-required`,
123
+ * because gh then reads the current branch from git in the working directory.
124
+ * A value holding `://` must be a pull request URL in this repository.
125
+ *
126
+ * EVERY `pr create` NEEDS `--head` (v68, #757 r1 SF3, widened by the security
127
+ * review at 121b903, CWE-522). Without `--head`, gh runs
128
+ * `git status --porcelain` in the working directory, which runs that
129
+ * repository's `core.fsmonitor`, and can `git push`, which runs its pre-push
130
+ * hook, both with GH_TOKEN in the environment (gh v2.97.0 `create.go:503,621`;
131
+ * `--dry-run` help says "May still push git changes"). So `pr create` without
132
+ * `--head`, with or without `--dry-run`, is refused with `head-required`, and
133
+ * so is any `--head` value that is empty or all spaces (gh v2.97.0
134
+ * `create.go:778` reads an empty value as no head; security re-review at
135
+ * 93c2f23). Every
136
+ * `pr create --head` value must be a bare branch name or
137
+ * `memnexus-ai:<branch>`; any other owner prefix is refused with
138
+ * `head-not-allowed`. A dry run proves gh's read path only, not that the
139
+ * create mutation is permitted.
140
+ *
141
+ * STILL REFUSED (v64, #729; kept in v68). `pr status` runs git in the working
142
+ * directory with the token in its environment, so it stays refused whatever a
143
+ * measurement shows. `repo view` exited 1 in v64 for a cause the measurement
144
+ * did not classify, and it stays refused while that cause is unmeasured. The
145
+ * `statusCheckRollup` field of `pr view --json` and `pr list --json` stays
146
+ * refused (v68 final decision 1: the cell was record-only).
147
+ *
148
+ * `pr create` READS GIT IN THE WORKING DIRECTORY (#757 r1 SF-e; v69, #763).
149
+ * Since v69 that working directory is the wrapper's own temp dir, with
150
+ * `GIT_CEILING_DIRECTORIES` set to its parent, so the git gh starts finds no
151
+ * repository and reads no caller's `.git/config` or hooks. A non-empty
152
+ * `--head` is still required, and with it gh reads git config, remotes and
153
+ * commit history only, and pushes nothing (`skipPushRefs`). A push would also
154
+ * need `contents: write`, which the `gh` set does not hold. If that is ever
155
+ * added, the no-`--head` path matters again (red-team F2 at 121b903); #763
156
+ * records that trigger as closed only once its live runs pass. The child has
157
+ * `GIT_CONFIG_GLOBAL=/dev/null` and `GIT_CONFIG_NOSYSTEM=1`. `pr status` stays
158
+ * refused: it takes no selector, and without `--repo` (always refused) it
159
+ * reads the current branch from git on every call (gh v2.97.0
160
+ * `pkg/cmd/pr/status/status.go:98-100`).
161
+ *
162
+ * MEMORY EXPOSURE, NOT REMOVED. The token is a JavaScript string in this
163
+ * process and a C string in the child's environment. Node cannot zero it. A
164
+ * process with this user's rights can read /proc/<pid>/environ of the child
165
+ * while gh runs. The git processes gh starts inherit GH_TOKEN. Since v69 they
166
+ * run in the wrapper's temp dir under `GIT_CEILING_DIRECTORIES`, so no
167
+ * repository's own config or hooks apply to them.
168
+ */
169
+ import { closeSync, constants as fsConstants, existsSync, fstatSync, openSync, readSync, readdirSync, realpathSync, statSync, } from 'node:fs';
170
+ import { constants as osConstants, homedir, userInfo } from 'node:os';
171
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
172
+ import { GitHubAppTokenError, REPO_NAME, REPO_OWNER, boundedRevoke } from './github-app-token.js';
173
+ /** The one gh binary run. Absolute; never looked up on PATH. */
174
+ export const GH_PATH = '/usr/bin/gh';
175
+ /** The permission set minted. A closed set in github-app-token.ts. */
176
+ export const GH_PURPOSE = 'gh';
177
+ /** The host gh is pinned to. */
178
+ export const GH_HOST = 'github.com';
179
+ /** The repository gh is pinned to, as GH_REPO. */
180
+ export const GH_REPO = `${REPO_OWNER}/${REPO_NAME}`;
181
+ /** `pr edit` silently does nothing on gh 2.46.0 (gh-pr-edit-guard). Refused below this. */
182
+ export const MIN_GH_VERSION_FOR_PR_EDIT = [2, 97, 0];
183
+ /** The only endpoint prefix `api` accepts. */
184
+ export const API_ENDPOINT_PREFIX = `repos/${REPO_OWNER}/${REPO_NAME}/`;
185
+ /** The only URL prefix a positional argument or flag value outside `api` may hold. */
186
+ export const POSITIONAL_URL_PREFIX = `https://${GH_HOST}/${REPO_OWNER}/${REPO_NAME}/`;
187
+ /** Substrings an `api` endpoint must not hold (revision 1). */
188
+ export const API_ENDPOINT_FORBIDDEN = ['..', '%', '://', '?', '#'];
189
+ /** The search qualifier `search issues` requires. scanSearchScope() finds it anywhere in the query, any case. */
190
+ export const SEARCH_REPO_QUALIFIER = `repo:${GH_REPO}`;
191
+ /** The variables copied from this process into the child, when present. */
192
+ export const INHERITED_ENV_KEYS = ['LANG', 'TERM'];
193
+ /** The fixed variables set in the child, besides GH_TOKEN, HOME and GH_CONFIG_DIR. */
194
+ export const FIXED_CHILD_ENV = {
195
+ // Fixed, not inherited (credential-custody review on PR #705, SF2).
196
+ PATH: '/usr/bin:/bin',
197
+ GH_HOST,
198
+ // Lead decision after the PR #705 gates: gh uses this repository, not the
199
+ // one the current directory's remotes name.
200
+ GH_REPO,
201
+ GH_PROMPT_DISABLED: '1',
202
+ GH_PAGER: 'cat',
203
+ GIT_TERMINAL_PROMPT: '0',
204
+ GIT_ASKPASS: '',
205
+ NO_COLOR: '1',
206
+ // Not in revision 1. Lead decision for v56: both stop network calls the
207
+ // wrapper does not need (the 24-hour update check and gh telemetry).
208
+ GH_NO_UPDATE_NOTIFIER: '1',
209
+ DO_NOT_TRACK: '1',
210
+ // Lead decision after the PR #705 gates: git that gh runs reads neither
211
+ // /etc/gitconfig nor a global config. The repository's own config still applies.
212
+ GIT_CONFIG_NOSYSTEM: '1',
213
+ GIT_CONFIG_GLOBAL: '/dev/null',
214
+ };
215
+ /**
216
+ * Flags refused on every subcommand: revision 1's list, then the PR #705 gate
217
+ * additions. No allowlist entry below may hold one; test H1 checks that, and
218
+ * runGhWithToken checks this list first.
219
+ */
220
+ export const ALWAYS_REFUSED_FLAGS = [
221
+ '-R', '--repo', '--hostname', '-H', '--header', '--web', '--editor', '-e',
222
+ '--body-file', '-F', '--field', '-f', '--raw-field', '--input', '-X', '--method',
223
+ '--show-token',
224
+ '-q', '--jq', '--jq=', '--slurp', '-t', '--template',
225
+ ];
226
+ /**
227
+ * Commands and subcommands refused (revision 1). They are refused because they
228
+ * are absent from ALLOWED_COMMANDS; this list exists so tests can name them.
229
+ * Each is refused with `command-not-allowed` and WRAPPER_FAILURE_EXIT.
230
+ * v64 (#729, plan revision 1, SF4) adds `pr status`, and `repo view` (SF3,
231
+ * cause unmeasured). v68 (#757) removes `pr checks`, which v64 had added.
232
+ */
233
+ export const ALWAYS_REFUSED_COMMANDS = [
234
+ 'auth', 'config', 'alias', 'extension', 'ssh-key', 'gpg-key', 'secret', 'codespace',
235
+ 'pr merge', 'pr checkout', 'workflow',
236
+ 'pr status', 'repo view',
237
+ ];
238
+ /**
239
+ * Subcommands refused without `--json` (v67 #749 for `pr view`; v68 #757
240
+ * moves it to `pr checks`). `pr checks` was measured with `--json` only
241
+ * (#757 cell 2), and without it gh prints a table and exits 8 on a pending
242
+ * check, so `--json` is required.
243
+ */
244
+ export const JSON_REQUIRED_COMMANDS = ['pr checks'];
245
+ /**
246
+ * Subcommands whose one positional must be a pull request number (`123` or
247
+ * `#123`) or a pull request URL in this repository (v68, #757 decision table,
248
+ * cell 2). With no selector, gh's `pr checks` reads the current branch from
249
+ * git in the working directory. A branch is refused because it is unmeasured.
250
+ */
251
+ export const PR_NUMBER_REQUIRED_COMMANDS = ['pr checks'];
252
+ /**
253
+ * Subcommands that need exactly one selector: a number, a branch name or a
254
+ * pull request URL in this repository (v68, #757 cells 5 and 6 narrow the v67
255
+ * number-only rule). No selector is still refused with `pr-number-required`:
256
+ * gh would read the current branch from git in the working directory.
257
+ */
258
+ export const PR_SELECTOR_REQUIRED_COMMANDS = ['pr view', 'pr diff'];
259
+ /**
260
+ * `123` or `#123`, the selectors gh's finder reads as a number. At most 10
261
+ * digits (v72, #759 B4-I1, plan revision 1 comment 6408254892). gh v2.97.0
262
+ * parses the selector with `strconv.Atoi` (`pkg/cmd/pr/shared/finder.go:171`)
263
+ * and reads a value that overflows, from 19 digits, as a branch, which
264
+ * `pr checks` does not allow. Ten is a sanity cap, not the overflow point.
265
+ */
266
+ const PR_NUMBER_RE = /^#?[0-9]{1,10}$/;
267
+ /**
268
+ * True when the selector is a number or a pull request URL in this repository.
269
+ * The URL's number has the same 10-digit cap (v72): gh's URL path ignores the
270
+ * `Atoi` error (`finder.go:326`).
271
+ */
272
+ export function isPrNumberSelector(selector) {
273
+ if (PR_NUMBER_RE.test(selector))
274
+ return true;
275
+ if (!selector.startsWith(`${POSITIONAL_URL_PREFIX}pull/`))
276
+ return false;
277
+ return /^[0-9]{1,10}(?:\/.*)?$/.test(selector.slice(`${POSITIONAL_URL_PREFIX}pull/`.length));
278
+ }
279
+ /**
280
+ * True when the selector names one pull request for `pr view` or `pr diff`
281
+ * (v68): a number, or a branch name, or, when it holds `://`, a pull request
282
+ * URL in this repository (the v67 URL check, kept). An empty or all-space
283
+ * value is refused: gh would read it as no selector.
284
+ */
285
+ export function isPrSelector(selector) {
286
+ if (selector.trim() === '')
287
+ return false;
288
+ if (selector.includes('://'))
289
+ return isPrNumberSelector(selector);
290
+ return true;
291
+ }
292
+ /** The only owner prefix a `pr create --head` value may carry (v68, #757 r1 SF3). */
293
+ export const HEAD_OWNER_PREFIX = `${REPO_OWNER}:`;
294
+ /**
295
+ * The refusal for one `pr create --head` value, or null (v68). Allowed: a bare
296
+ * branch name (no `:`), or `memnexus-ai:<branch>` with a non-empty branch and
297
+ * no further `:`. Any other owner prefix, in any case, is `head-not-allowed`.
298
+ * The value is never echoed.
299
+ */
300
+ export function headRefusal(value) {
301
+ if (!value.includes(':'))
302
+ return null;
303
+ if (!value.startsWith(HEAD_OWNER_PREFIX))
304
+ return 'head-not-allowed';
305
+ const branch = value.slice(HEAD_OWNER_PREFIX.length);
306
+ return branch !== '' && !branch.includes(':') ? null : 'head-not-allowed';
307
+ }
308
+ /**
309
+ * `--json` fields refused per subcommand, compared case-insensitively (v64,
310
+ * #729 SF3). GitHub refuses `pr view --json statusCheckRollup` with the `gh`
311
+ * set (`graphql:repository.pullRequest.statusCheckRollup.nodes.0`, measured).
312
+ * `pr list` is listed by inference, not measurement (lead decision, v64): it
313
+ * selects the same field, and refusing is fail-closed. No other subcommand
314
+ * is listed.
315
+ */
316
+ export const REFUSED_JSON_FIELDS = {
317
+ 'pr view': ['statuscheckrollup'],
318
+ 'pr list': ['statuscheckrollup'],
319
+ };
320
+ const JSON_OUTPUT = { '--json': 'value' };
321
+ /**
322
+ * The allowlist. Keys are `command` or `command subcommand`. Each flag is a
323
+ * real gh 2.97.0 flag for that subcommand (`gh <cmd> --help`). Flags that read
324
+ * a file, open a browser or editor, delete a branch, filter output inside gh,
325
+ * or change the target repository or host are left out. `--body-file` is not
326
+ * here either: on BODY_FILE_COMMANDS the wrapper reads the file and gh gets
327
+ * `--body` (v70, applyBodyFile).
328
+ */
329
+ export const ALLOWED_COMMANDS = {
330
+ 'pr create': {
331
+ '--title': 'text', '-b': 'text', '--body': 'text',
332
+ '-B': 'value', '--base': 'value', '--head': 'value', '-d': 'bool', '--draft': 'bool',
333
+ '-l': 'value', '--label': 'value', '-a': 'value', '--assignee': 'value',
334
+ '-r': 'value', '--reviewer': 'value', '-m': 'value', '--milestone': 'value',
335
+ // v68 (#757): every `pr create` needs `--head`, checked in checkGhArgs.
336
+ '--dry-run': 'bool',
337
+ },
338
+ 'pr view': { ...JSON_OUTPUT, '-c': 'bool', '--comments': 'bool' },
339
+ // v68 (#757, cell 2): `--json` only, and required. No `--watch`, no `--required`.
340
+ 'pr checks': { ...JSON_OUTPUT },
341
+ 'pr list': {
342
+ ...JSON_OUTPUT, '--app': 'value', '-a': 'value', '--assignee': 'value', '-A': 'value', '--author': 'value',
343
+ '-B': 'value', '--base': 'value', '-d': 'bool', '--draft': 'bool', '--head': 'value',
344
+ '-l': 'value', '--label': 'value', '-L': 'value', '--limit': 'value',
345
+ '-S': 'text', '--search': 'text', '-s': 'value', '--state': 'value',
346
+ },
347
+ 'pr edit': {
348
+ '--title': 'text', '-b': 'text', '--body': 'text', '-B': 'value', '--base': 'value',
349
+ '--add-label': 'value', '--remove-label': 'value', '--add-assignee': 'value', '--remove-assignee': 'value',
350
+ '--add-reviewer': 'value', '--remove-reviewer': 'value', '-m': 'value', '--milestone': 'value',
351
+ '--remove-milestone': 'bool',
352
+ },
353
+ 'pr comment': { '-b': 'text', '--body': 'text', '--edit-last': 'bool', '--create-if-none': 'bool' },
354
+ 'pr diff': { '--name-only': 'bool', '--patch': 'bool', '--color': 'value' },
355
+ 'pr ready': { '--undo': 'bool' },
356
+ 'pr close': { '-c': 'text', '--comment': 'text' },
357
+ 'pr reopen': { '-c': 'text', '--comment': 'text' },
358
+ 'issue create': {
359
+ '--title': 'text', '-b': 'text', '--body': 'text',
360
+ '-l': 'value', '--label': 'value', '-a': 'value', '--assignee': 'value', '-m': 'value', '--milestone': 'value',
361
+ },
362
+ 'issue view': { ...JSON_OUTPUT, '-c': 'bool', '--comments': 'bool' },
363
+ 'issue list': {
364
+ ...JSON_OUTPUT, '--app': 'value', '-a': 'value', '--assignee': 'value', '-A': 'value', '--author': 'value',
365
+ '-l': 'value', '--label': 'value', '-L': 'value', '--limit': 'value', '--mention': 'value',
366
+ '-m': 'value', '--milestone': 'value', '-S': 'text', '--search': 'text', '-s': 'value', '--state': 'value',
367
+ },
368
+ 'issue edit': {
369
+ '--title': 'text', '-b': 'text', '--body': 'text',
370
+ '--add-label': 'value', '--remove-label': 'value', '--add-assignee': 'value', '--remove-assignee': 'value',
371
+ '-m': 'value', '--milestone': 'value', '--remove-milestone': 'bool',
372
+ },
373
+ 'issue comment': { '-b': 'text', '--body': 'text', '--edit-last': 'bool', '--create-if-none': 'bool' },
374
+ 'issue close': { '-c': 'text', '--comment': 'text', '-r': 'value', '--reason': 'value', '--duplicate-of': 'value' },
375
+ 'issue reopen': { '-c': 'text', '--comment': 'text' },
376
+ 'issue status': { ...JSON_OUTPUT },
377
+ 'run list': {
378
+ ...JSON_OUTPUT, '-a': 'bool', '--all': 'bool', '-b': 'value', '--branch': 'value', '-c': 'value', '--commit': 'value',
379
+ '--created': 'value', '--event': 'value', '-L': 'value', '--limit': 'value', '-s': 'value', '--status': 'value',
380
+ '-u': 'value', '--user': 'value', '--workflow': 'value',
381
+ },
382
+ 'run view': {
383
+ ...JSON_OUTPUT, '-a': 'value', '--attempt': 'value', '--exit-status': 'bool', '-j': 'value', '--job': 'value',
384
+ '--log': 'bool', '--log-failed': 'bool', '-v': 'bool', '--verbose': 'bool',
385
+ },
386
+ 'run watch': { '--compact': 'bool', '--exit-status': 'bool', '-i': 'value', '--interval': 'value' },
387
+ 'label list': {
388
+ ...JSON_OUTPUT, '-L': 'value', '--limit': 'value', '--order': 'value', '-S': 'text', '--search': 'text', '--sort': 'value',
389
+ },
390
+ 'search issues': {
391
+ ...JSON_OUTPUT, '--app': 'value', '--assignee': 'value', '--author': 'value', '--include-prs': 'bool',
392
+ '--label': 'value', '-L': 'value', '--limit': 'value', '--match': 'value', '--order': 'value',
393
+ '--sort': 'value', '--state': 'value',
394
+ },
395
+ api: { '--paginate': 'bool' },
396
+ };
397
+ /** Commands that take a subcommand. Every other allowed command is a single word. */
398
+ const GROUPS = new Set(['pr', 'issue', 'run', 'label', 'repo', 'search']);
399
+ /**
400
+ * A first path segment gh could read as a host in `HOST/OWNER/REPO`: one that
401
+ * holds a dot or a colon, or is `localhost`. A branch such as `v1.2/fix/x`
402
+ * matches too and is refused; that cost is accepted.
403
+ */
404
+ const HOST_FORM_RE = /^(?:[^/]*[.:][^/]*|localhost)\/[^/]*\/[^/]*/i;
405
+ /** Any C0 control character or DEL. */
406
+ const CONTROL_RE = /[\u0000-\u001f\u007f]/;
407
+ /**
408
+ * One positional or non-free-text flag value. Allowed: a value with no
409
+ * `://` and no host-shaped `HOST/OWNER/REPO` prefix (a number, a branch, a
410
+ * label, a login), this repository's `OWNER/REPO`, or a URL under
411
+ * POSITIONAL_URL_PREFIX. Returns the refusal code, or null when allowed.
412
+ */
413
+ export function valueRefusal(value) {
414
+ if (CONTROL_RE.test(value))
415
+ return 'url-not-allowed';
416
+ if (value.includes('://'))
417
+ return value.startsWith(POSITIONAL_URL_PREFIX) && !value.includes('..') ? null : 'url-not-allowed';
418
+ if (HOST_FORM_RE.test(value))
419
+ return 'url-not-allowed';
420
+ return null;
421
+ }
422
+ /** True when the value is allowed by valueRefusal(). */
423
+ export function isAllowedValue(value) {
424
+ return valueRefusal(value) === null;
425
+ }
426
+ /**
427
+ * Every search scope qualifier in a text, wherever it occurs (v57, #707 item 1,
428
+ * plan revision 1 S1, #707 comment 6280545721): `repo`, `org`, `user` or
429
+ * `owner`, any case, then optional spaces, `:` and optional spaces. Group 2 is
430
+ * the value: everything up to the first whitespace, `"`, `'`, `(` or `)`.
431
+ *
432
+ * The scan is unanchored. A qualifier after a quote, a parenthesis, `-` or
433
+ * `NOT` is found, and so is one inside a longer word: `superuser: x` is read
434
+ * as `user:` and refused. That over-refusal is intended.
435
+ */
436
+ const SCOPE_QUALIFIER_SCAN_RE = /(repo|org|user|owner)\s*:\s*([^\s"'()]*)/gi;
437
+ /**
438
+ * A negation just before a qualifier: `-` or `!`, then optional spaces or
439
+ * quotes (lead rulings on PR #709). `x -repo:memnexus-ai/mx-agent-framework`
440
+ * would search everything except this repository, so a negated qualifier is
441
+ * refused even when its value is this repository. The word `NOT` and
442
+ * parentheses are refused outright by SEARCH_OPERATOR_RE.
443
+ */
444
+ const NEGATION_BEFORE_RE = /[-!][\s"']*$/;
445
+ /**
446
+ * Search operators, refused anywhere in a search text (lead correction on PR
447
+ * #709): the words `OR`, `AND` and `NOT` in any case, and any `(` or `)`.
448
+ * GitHub's advanced issue search can read `repo:memnexus-ai/mx-agent-framework OR is:open`
449
+ * or `NOT (...)` as reaching other repositories. This over-refuses plain text
450
+ * that holds those words, such as `fix or revert`. That is intended.
451
+ */
452
+ const SEARCH_OPERATOR_RE = /\b(?:or|and|not)\b|[()]/i;
453
+ /** True when the search text holds a search operator (SEARCH_OPERATOR_RE). */
454
+ export function hasSearchOperator(text) {
455
+ return SEARCH_OPERATOR_RE.test(text);
456
+ }
457
+ /**
458
+ * A search text, or a `search issues` flag value, may hold printable ASCII
459
+ * only (red-team Must Fix list on PR #709, item 2). Look-alike characters
460
+ * such as U+FF1A (fullwidth colon), U+200B (zero-width space), U+00AD (soft
461
+ * hyphen), U+00A0 (no-break space) and U+FEFF could make GitHub read a
462
+ * qualifier the ASCII scan does not see. Control characters, tab and newline
463
+ * included, are refused too.
464
+ */
465
+ const SEARCH_TEXT_FORBIDDEN_RE = /[^\x20-\x7e]/;
466
+ /** True when the text holds a character outside printable ASCII. */
467
+ export function hasForbiddenSearchChar(text) {
468
+ return SEARCH_TEXT_FORBIDDEN_RE.test(text);
469
+ }
470
+ /**
471
+ * True when one scan match is a `repo:` qualifier GitHub reads as one, so it
472
+ * may count toward the qualifier `search issues` requires (red-team Must Fix on
473
+ * PR #709). All four must hold:
474
+ * - it starts the text or follows a space;
475
+ * - no space on either side of the colon;
476
+ * - no `"` or `'` anywhere before it, so it is not inside a quoted phrase;
477
+ * - it ends the text or a space follows it.
478
+ * The refusal side keeps the loose scan. A match that fails here and names
479
+ * this repository is neither counted nor refused on its own.
480
+ */
481
+ function isStrictQualifier(text, m) {
482
+ const start = m.index ?? 0;
483
+ const end = start + m[0].length;
484
+ const startsWord = start === 0 || text[start - 1] === ' ';
485
+ const noSpaceBeforeColon = !/\s:/.test(m[0]);
486
+ const noSpaceAfterColon = !/:\s/.test(m[0]);
487
+ const noQuoteBefore = !/["']/.test(text.slice(0, start));
488
+ const endsWord = end === text.length || text[end] === ' ';
489
+ return startsWord && noSpaceBeforeColon && noSpaceAfterColon && noQuoteBefore && endsWord;
490
+ }
491
+ /**
492
+ * Scan a search text for scope qualifiers. A `repo:` value is allowed only
493
+ * when it equals this repository, compared case-insensitively. `org:`,
494
+ * `user:` and `owner:` are never allowed, and neither is any qualifier after a
495
+ * `-` or `!` (NEGATION_BEFORE_RE). Callers refuse operators and non-ASCII
496
+ * text first. Every match is checked, not the first.
497
+ */
498
+ export function scanSearchScope(text) {
499
+ const allowed = GH_REPO.toLowerCase();
500
+ let hasAllowedRepo = false;
501
+ let other = false;
502
+ for (const m of text.matchAll(SCOPE_QUALIFIER_SCAN_RE)) {
503
+ const negated = NEGATION_BEFORE_RE.test(text.slice(0, m.index));
504
+ if (!negated && m[1].toLowerCase() === 'repo' && m[2].toLowerCase() === allowed) {
505
+ if (isStrictQualifier(text, m))
506
+ hasAllowedRepo = true;
507
+ }
508
+ else
509
+ other = true;
510
+ }
511
+ return { hasAllowedRepo, namesOtherScope: other };
512
+ }
513
+ /**
514
+ * True when the search text names a scope other than this repository. Used
515
+ * for `search issues` and every `-S`/`--search` value, `label list` included.
516
+ */
517
+ export function namesOtherScope(text) {
518
+ return scanSearchScope(text).namesOtherScope;
519
+ }
520
+ /**
521
+ * The refusal for one search text (an `-S`/`--search` value, the joined
522
+ * `search issues` positionals, or a value searchValueRefusal() checks), or null. Checked in this order: a character
523
+ * outside printable ASCII, a quote, a search operator, a scope other than this
524
+ * repository. The scan keeps its quote handling as a second layer.
525
+ */
526
+ export function searchTextRefusal(text) {
527
+ if (hasForbiddenSearchChar(text))
528
+ return 'search-text-not-allowed';
529
+ // No `"` or `'` at all (security review on PR #709): gh turns `-S 'foo "'`
530
+ // into a query with an unclosed quote ahead of its own qualifiers.
531
+ if (/["']/.test(text))
532
+ return 'search-text-not-allowed';
533
+ if (hasSearchOperator(text))
534
+ return 'search-operator-not-allowed';
535
+ if (namesOtherScope(text))
536
+ return 'search-repo-required';
537
+ return null;
538
+ }
539
+ /**
540
+ * The refusal for whitespace inside one argument gh writes into a search query
541
+ * as a single term, or null (v58, #707 item 1). `\s` covers space, tab,
542
+ * newline and the no-break space. gh 2.97.0 quotes such an argument after its
543
+ * first `:`, so `'is:open repo:memnexus-ai/mx-agent-framework'` becomes
544
+ * `is:"open repo:memnexus-ai/mx-agent-framework"` and the `repo:` qualifier is
545
+ * read as part of a value (security review on PR #709, comment 6281614905).
546
+ */
547
+ export function searchTermRefusal(term) {
548
+ return /\s/.test(term) ? 'search-text-not-allowed' : null;
549
+ }
550
+ /**
551
+ * The refusal for one value gh writes into a search query, or null: every
552
+ * `search issues` value flag, and the SEARCH_QUERY_VALUE_FLAGS of `pr list`
553
+ * and `issue list`. They get the search text checks, and whitespace is refused
554
+ * as well (red-team Must Fix list on PR #709, item 3).
555
+ */
556
+ export function searchValueRefusal(value) {
557
+ return searchTermRefusal(value) ?? searchTextRefusal(value);
558
+ }
559
+ /**
560
+ * The `pr list` and `issue list` value flags whose value gh 2.97.0 writes into
561
+ * the search query (v58, #707 item 1; security review on PR #709, S3). Measured
562
+ * offline with `--web` and GH_BROWSER=echo before this change; the table and
563
+ * method are in gh-token-run.test.ts (T3). `-L`/`--limit` and `--json` are not
564
+ * written into the query and keep the plain value check. `search issues` value
565
+ * flags are all checked, so it is not listed here.
566
+ */
567
+ export const SEARCH_QUERY_VALUE_FLAGS = {
568
+ 'pr list': ['--app', '-a', '--assignee', '-A', '--author', '-B', '--base', '--head', '-l', '--label', '-s', '--state'],
569
+ 'issue list': ['--app', '-a', '--assignee', '-A', '--author', '-l', '--label', '--mention', '-m', '--milestone', '-s', '--state'],
570
+ };
571
+ /**
572
+ * The `-s`/`--state` values each subcommand accepts, copied from gh 2.97.0's
573
+ * own help (lead request on PR #714): `gh pr list --help` lists
574
+ * `{open|closed|merged|all}`, `gh issue list --help` `{open|closed|all}`, and
575
+ * `gh search issues --help` `{open|closed}`. Any other value is refused with
576
+ * `state-not-allowed`, after the search value checks.
577
+ */
578
+ export const STATE_VALUES = {
579
+ 'pr list': ['open', 'closed', 'merged', 'all'],
580
+ 'issue list': ['open', 'closed', 'all'],
581
+ 'search issues': ['open', 'closed'],
582
+ };
583
+ /** True when gh writes this flag's value into the search query. */
584
+ function writesSearchQuery(key, flag) {
585
+ if (key === 'search issues')
586
+ return true;
587
+ return Object.prototype.hasOwnProperty.call(SEARCH_QUERY_VALUE_FLAGS, key) && SEARCH_QUERY_VALUE_FLAGS[key].includes(flag);
588
+ }
589
+ /**
590
+ * True when a `--json` value names a field in REFUSED_JSON_FIELDS for this
591
+ * key. gh reads the value as comma-separated field names; each is trimmed
592
+ * and compared case-insensitively, so a variant spelling is refused too.
593
+ */
594
+ function jsonFieldRefused(key, value) {
595
+ if (!Object.prototype.hasOwnProperty.call(REFUSED_JSON_FIELDS, key))
596
+ return false;
597
+ const refused = REFUSED_JSON_FIELDS[key];
598
+ return value.split(',').some((f) => refused.includes(f.trim().toLowerCase()));
599
+ }
600
+ /** `issue close --duplicate-of`: an issue number or a URL in this repository only. */
601
+ const DUPLICATE_OF_RE = /^\d+$/;
602
+ /**
603
+ * Check gh arguments against the allowlist. Pure. Returns the allowlist key
604
+ * on success so the caller can apply per-subcommand rules.
605
+ */
606
+ export function checkGhArgs(args) {
607
+ if (args.length === 0)
608
+ return { ok: false, code: 'no-command' };
609
+ const cmd = args[0];
610
+ let key;
611
+ let rest;
612
+ if (GROUPS.has(cmd)) {
613
+ if (args.length < 2)
614
+ return { ok: false, code: 'command-not-allowed' };
615
+ key = `${cmd} ${args[1]}`;
616
+ rest = args.slice(2);
617
+ }
618
+ else {
619
+ key = cmd;
620
+ rest = args.slice(1);
621
+ }
622
+ if (!Object.prototype.hasOwnProperty.call(ALLOWED_COMMANDS, key))
623
+ return { ok: false, code: 'command-not-allowed' };
624
+ const flags = ALLOWED_COMMANDS[key];
625
+ const positionals = [];
626
+ // True once `--json` is seen as a flag, in any position (v67, #749).
627
+ let sawJson = false;
628
+ // `pr create --head`, in any position (v68, #757).
629
+ let sawHead = false;
630
+ for (let i = 0; i < rest.length; i++) {
631
+ const tok = rest[i];
632
+ if (tok.startsWith('-')) {
633
+ if (ALWAYS_REFUSED_FLAGS.includes(tok))
634
+ return { ok: false, code: 'flag-not-allowed' };
635
+ if (!Object.prototype.hasOwnProperty.call(flags, tok))
636
+ return { ok: false, code: 'flag-not-allowed' };
637
+ if (tok === '--json')
638
+ sawJson = true;
639
+ const kind = flags[tok];
640
+ if (kind === 'value' || kind === 'text') {
641
+ const value = rest[i + 1];
642
+ // A value starting with `-` is refused, so every `-` token is checked.
643
+ if (value === undefined || value.startsWith('-'))
644
+ return { ok: false, code: 'flag-value-missing' };
645
+ if (kind === 'value') {
646
+ // gh writes these values into the search query: search checks first.
647
+ if (writesSearchQuery(key, tok)) {
648
+ const searchRefusal = searchValueRefusal(value);
649
+ if (searchRefusal !== null)
650
+ return { ok: false, code: searchRefusal };
651
+ }
652
+ // Every flag value, not only positionals (security review on PR #705, SF).
653
+ const refusal = valueRefusal(value);
654
+ if (refusal !== null)
655
+ return { ok: false, code: refusal };
656
+ if ((tok === '-s' || tok === '--state') && Object.prototype.hasOwnProperty.call(STATE_VALUES, key)
657
+ && !STATE_VALUES[key].includes(value)) {
658
+ return { ok: false, code: 'state-not-allowed' };
659
+ }
660
+ if (tok === '--duplicate-of' && !DUPLICATE_OF_RE.test(value) && !value.startsWith(POSITIONAL_URL_PREFIX)) {
661
+ return { ok: false, code: 'url-not-allowed' };
662
+ }
663
+ // v73 (#777, plan comment 6408736891, revision 1 comment 6408788487):
664
+ // every `--json` value, on every key with `--json` and every
665
+ // occurrence, is letter-only field names separated by single commas.
666
+ // gh v2.97.0 reads the value as CSV (pflag `readAsCSV`), which strips
667
+ // quotes, so `"statusCheckRollup"` reached gh as the refused field;
668
+ // every gh field name is letters only. No `m` flag: `$` matches only
669
+ // at the end of the value. This replaces the v72 empty-field check,
670
+ // which it covers. Before jsonFieldRefused, which stays for the
671
+ // policy hold on `pr view` and `pr list`.
672
+ if (tok === '--json' && !/^[A-Za-z]+(?:,[A-Za-z]+)*$/.test(value))
673
+ return { ok: false, code: 'json-field-not-allowed' };
674
+ if (tok === '--json' && jsonFieldRefused(key, value))
675
+ return { ok: false, code: 'json-field-not-allowed' };
676
+ if (key === 'pr create' && tok === '--head') {
677
+ // Security re-review at 93c2f23 (CWE-522): gh v2.97.0 reads an
678
+ // empty --head as no head (`create.go:778`), then runs git status
679
+ // and the push path. pflag keeps the last value, so every
680
+ // occurrence is checked, not only the first.
681
+ if (value.trim() === '')
682
+ return { ok: false, code: 'head-required' };
683
+ const head = headRefusal(value);
684
+ if (head !== null)
685
+ return { ok: false, code: head };
686
+ sawHead = true;
687
+ }
688
+ }
689
+ else if (tok === '-S' || tok === '--search') {
690
+ const searchRefusal = searchTextRefusal(value);
691
+ if (searchRefusal !== null)
692
+ return { ok: false, code: searchRefusal };
693
+ }
694
+ i += 1;
695
+ }
696
+ continue;
697
+ }
698
+ positionals.push(tok);
699
+ }
700
+ if (key === 'api') {
701
+ if (positionals.length !== 1 || !isAllowedApiEndpoint(positionals[0])) {
702
+ return { ok: false, code: 'api-endpoint-not-allowed' };
703
+ }
704
+ return { ok: true, key };
705
+ }
706
+ if (key === 'search issues') {
707
+ // Lead decision after the PR #705 gates: search stays, scoped to this
708
+ // repository. The query is free text, so it is not host-checked. It must
709
+ // hold this repository's `repo:` qualifier and no other scope qualifier,
710
+ // found by scanSearchScope() anywhere in the query (v57, #707 item 1).
711
+ const query = positionals.join(' ');
712
+ const searchRefusal = searchTextRefusal(query);
713
+ if (searchRefusal !== null)
714
+ return { ok: false, code: searchRefusal };
715
+ if (!scanSearchScope(query).hasAllowedRepo)
716
+ return { ok: false, code: 'search-repo-required' };
717
+ // One argument, one term (v58, #707 item 1): every positional, not the
718
+ // joined query, which always holds spaces. Checked last, so a query that
719
+ // also names another scope or holds an operator keeps that refusal code.
720
+ for (const p of positionals) {
721
+ const termRefusal = searchTermRefusal(p);
722
+ if (termRefusal !== null)
723
+ return { ok: false, code: termRefusal };
724
+ }
725
+ return { ok: true, key };
726
+ }
727
+ // A positional (a number, a branch, a pull request or issue URL) must not
728
+ // point gh at another host.
729
+ for (const p of positionals) {
730
+ const refusal = valueRefusal(p);
731
+ if (refusal !== null)
732
+ return { ok: false, code: refusal };
733
+ }
734
+ // v72 (#759 Pos, revision 1 comment 6408254892): `pr create` takes no
735
+ // positional. gh v2.97.0 rejects one in cobra's Args stage, before RunE
736
+ // (`create.go:254`, `Args: cmdutil.NoArgsQuoteReminder`), so refusing here
737
+ // saves a wasted mint. After the positional value checks, so a URL keeps
738
+ // url-not-allowed; before head-required, so `pr create extra` gets this code.
739
+ if (key === 'pr create' && positionals.length > 0)
740
+ return { ok: false, code: 'positional-not-allowed' };
741
+ // After every flag and value check, so a bad flag or host keeps its own code.
742
+ // v68 (#757 r1 SF3; security review at 121b903): without `--head`, gh runs
743
+ // git status and may push in the working directory with the token in env.
744
+ if (key === 'pr create' && !sawHead)
745
+ return { ok: false, code: 'head-required' };
746
+ if (PR_NUMBER_REQUIRED_COMMANDS.includes(key) && (positionals.length !== 1 || !isPrNumberSelector(positionals[0]))) {
747
+ return { ok: false, code: 'pr-number-required' };
748
+ }
749
+ if (PR_SELECTOR_REQUIRED_COMMANDS.includes(key) && (positionals.length !== 1 || !isPrSelector(positionals[0]))) {
750
+ return { ok: false, code: 'pr-number-required' };
751
+ }
752
+ if (JSON_REQUIRED_COMMANDS.includes(key) && !sawJson)
753
+ return { ok: false, code: 'json-required' };
754
+ return { ok: true, key };
755
+ }
756
+ /** Whitespace, a control character or a backslash. Not in the plan; refused as well. */
757
+ const ENDPOINT_EXTRA_RE = /[\s\u0000-\u001f\u007f\\]/;
758
+ /** One `api` endpoint: under API_ENDPOINT_PREFIX, with none of the forbidden substrings. */
759
+ export function isAllowedApiEndpoint(endpoint) {
760
+ if (!endpoint.startsWith(API_ENDPOINT_PREFIX))
761
+ return false;
762
+ for (const bad of API_ENDPOINT_FORBIDDEN)
763
+ if (endpoint.includes(bad))
764
+ return false;
765
+ return !ENDPOINT_EXTRA_RE.test(endpoint);
766
+ }
767
+ // ── `--body-file` (v70, #761) ───────────────────────────────────────────────
768
+ /**
769
+ * The six subcommands on which the wrapper reads `--body-file` itself (v70,
770
+ * #761 revision 1, design change 1). Everywhere else `--body-file` reaches
771
+ * checkGhArgs unchanged and is refused by ALWAYS_REFUSED_FLAGS.
772
+ */
773
+ export const BODY_FILE_COMMANDS = [
774
+ 'pr create', 'pr edit', 'pr comment', 'issue create', 'issue edit', 'issue comment',
775
+ ];
776
+ /**
777
+ * The largest argument the kernel passes to a child: MAX_ARG_STRLEN is 32
778
+ * pages, 131,072 bytes with 4 KiB pages, and that count includes the
779
+ * terminating NUL. This assumes 4 KiB pages (#761 comment 6406680912);
780
+ * a larger page size only raises the kernel limit. Measured on this machine:
781
+ * an argument of 131,071 bytes spawns, one of 131,072 bytes fails with E2BIG.
782
+ * gh receives `--body=<text>`, so the largest file accepted is 131,064 bytes.
783
+ */
784
+ export const BODY_ARG_MAX_BYTES = 131_071;
785
+ /**
786
+ * The largest `--body-file` file read: 131,071 bytes, one byte under the
787
+ * product owner's 128 KiB, for the kernel limit above (revision 1, design
788
+ * change 3). The read buffer is one byte larger, so a read that fills it
789
+ * proves the file is too large. BODY_ARG_MAX_BYTES then lowers the real
790
+ * ceiling to 131,064 bytes.
791
+ */
792
+ export const BODY_FILE_MAX_BYTES = 131_071;
793
+ const BODY_FILE_READ_CAP = BODY_FILE_MAX_BYTES + 1;
794
+ /**
795
+ * The `--body` value checkGhArgs sees in place of the file's text. checkGhArgs
796
+ * refuses a value starting with `-`, and a body such as `- item` is a valid
797
+ * body, so it checks this fixed value instead (revision 1, design change 2).
798
+ * gh never receives it.
799
+ */
800
+ export const BODY_PLACEHOLDER = 'mx-agent-body-file';
801
+ /**
802
+ * Refused paths under each home directory (revision 1, design change 4; the
803
+ * next five added after the security review of PR #771, INFO, and the last
804
+ * four after the red-team on PR #771, P2). A realpath
805
+ * equal to one of these, or under one, is refused. This narrows the product
806
+ * owner's "refuse the agent's config file" and widens nothing.
807
+ */
808
+ export const BODY_FILE_DENYLIST_HOME = [
809
+ '.mx-agent', '.config/gh', '.azure', '.kube', '.ssh', '.npmrc', '.git-credentials', '.claude/.credentials.json',
810
+ '.copilot', '.codex', '.memnexus', '.docker/config.json', '.gnupg',
811
+ // Red-team on PR #771, P2.
812
+ '.aws', '.config/gcloud', '.netrc', '.pgpass',
813
+ ];
814
+ /** Refused absolute roots (revision 1, design change 4). */
815
+ export const BODY_FILE_DENYLIST_ROOT = ['/proc', '/sys'];
816
+ /**
817
+ * The home directories the denylist applies under: `os.homedir()`, which
818
+ * reads HOME, and the passwd entry's home from `os.userInfo()`, absolute
819
+ * values only (security review of PR #771, SF, CWE-807: HOME alone is
820
+ * caller-controlled). A userInfo() failure throws into the caller's one
821
+ * catch, so the read refuses rather than drop the passwd home.
822
+ */
823
+ function denylistHomes() {
824
+ const homes = [homedir(), userInfo().homedir].filter((h) => typeof h === 'string' && isAbsolute(h));
825
+ return [...new Set(homes)];
826
+ }
827
+ /**
828
+ * Every denylisted path except the absolute roots: each home entry under each
829
+ * home, then `$GH_CONFIG_DIR` and `$XDG_CONFIG_HOME/gh` when set to an
830
+ * absolute path (credential-custody review of PR #771, SF1). gh reads its
831
+ * config, and a saved login, from those two.
832
+ */
833
+ function deniedEntries(homes, env) {
834
+ const entries = homes.flatMap((h) => BODY_FILE_DENYLIST_HOME.map((rel) => join(h, rel)));
835
+ const ghConfig = env.GH_CONFIG_DIR;
836
+ if (typeof ghConfig === 'string' && isAbsolute(ghConfig))
837
+ entries.push(resolve(ghConfig));
838
+ const xdg = env.XDG_CONFIG_HOME;
839
+ if (typeof xdg === 'string' && isAbsolute(xdg))
840
+ entries.push(join(xdg, 'gh'));
841
+ return entries;
842
+ }
843
+ /** Every denylisted root, with the realpath of each entry that exists. */
844
+ function deniedRoots(entries) {
845
+ const roots = [...BODY_FILE_DENYLIST_ROOT];
846
+ for (const p of entries) {
847
+ roots.push(p);
848
+ // An entry reached through a symlink: the file's realpath names the target.
849
+ if (existsSync(p))
850
+ roots.push(realpathSync(p));
851
+ }
852
+ return roots;
853
+ }
854
+ /**
855
+ * True when `real` equals a root or sits under one. A trailing `/` on a root
856
+ * is dropped first, so a root of `/` (for example `GH_CONFIG_DIR=/`) matches
857
+ * every absolute path and refuses every read (red-team F3 on PR #771).
858
+ */
859
+ function isUnderAny(real, roots) {
860
+ return roots.some((root) => {
861
+ const r = root.replace(/\/+$/, '');
862
+ return real === r || real.startsWith(`${r}/`);
863
+ });
864
+ }
865
+ /**
866
+ * `dev:ino` of each denylisted entry that is a file, and of each regular file
867
+ * directly inside a denylisted directory, so a hard link to one is caught
868
+ * (revision 1, design change 4). The one-level scope is intentional, and it
869
+ * leaves a gap: a hard link to a file two or more levels inside a listed
870
+ * directory is accepted. A hard link's realpath is its own path, so neither
871
+ * the denylist nor the /proc/self/fd re-check sees it. That re-check catches
872
+ * symlink and path swaps only (red-team F1, custody SF3, on PR #771).
873
+ */
874
+ function deniedIdentities(entries) {
875
+ const ids = new Set();
876
+ const add = (s) => void ids.add(`${s.dev}:${s.ino}`);
877
+ for (const p of entries) {
878
+ const st = statSync(p, { bigint: true, throwIfNoEntry: false });
879
+ if (st === undefined)
880
+ continue;
881
+ if (st.isFile())
882
+ add(st);
883
+ else if (st.isDirectory()) {
884
+ for (const name of readdirSync(p)) {
885
+ const s = statSync(join(p, name), { bigint: true, throwIfNoEntry: false });
886
+ if (s !== undefined && s.isFile())
887
+ add(s);
888
+ }
889
+ }
890
+ }
891
+ return ids;
892
+ }
893
+ /**
894
+ * Read one `--body-file` for gh (v70, #761 revision 1, design change 3). In
895
+ * order: the denylist homes (none absolute is refused), resolve against
896
+ * process.cwd() (no `~` expansion), realpath, the denylist, open with
897
+ * O_RDONLY|O_NONBLOCK|O_NOFOLLOW (a FIFO with no writer cannot block), fstat
898
+ * for a regular file, the denylist again on /proc/self/fd/<fd> (the file
899
+ * actually opened), the hard-link check, a read capped at BODY_FILE_READ_CAP,
900
+ * the size checks, a fatal UTF-8 decode that keeps a BOM, and a NUL check.
901
+ * One try/catch covers process.cwd() and every fs call. Every refusal is a
902
+ * code; no path or error text is returned.
903
+ */
904
+ export function readBodyFileForGh(path) {
905
+ const no = (code) => ({ ok: false, code });
906
+ let fd = null;
907
+ // The one catch below names a decode failure apart from an fs failure.
908
+ let decoding = false;
909
+ try {
910
+ const homes = denylistHomes();
911
+ if (homes.length === 0)
912
+ return no('body-file-unreadable');
913
+ const entries = deniedEntries(homes, process.env);
914
+ const real = realpathSync(resolve(process.cwd(), path));
915
+ const roots = deniedRoots(entries);
916
+ if (isUnderAny(real, roots))
917
+ return no('body-file-denied');
918
+ fd = openSync(real, fsConstants.O_RDONLY | fsConstants.O_NONBLOCK | fsConstants.O_NOFOLLOW);
919
+ const st = fstatSync(fd, { bigint: true });
920
+ if (!st.isFile())
921
+ return no('body-file-not-regular');
922
+ // The path could have been swapped between realpath and open.
923
+ if (isUnderAny(realpathSync(`/proc/self/fd/${fd}`), roots))
924
+ return no('body-file-denied-fd');
925
+ if (deniedIdentities(entries).has(`${st.dev}:${st.ino}`))
926
+ return no('body-file-hard-link');
927
+ const buf = Buffer.alloc(BODY_FILE_READ_CAP);
928
+ let total = 0;
929
+ while (total < BODY_FILE_READ_CAP) {
930
+ const n = readSync(fd, buf, total, BODY_FILE_READ_CAP - total, null);
931
+ if (n === 0)
932
+ break;
933
+ total += n;
934
+ }
935
+ if (total >= BODY_FILE_READ_CAP)
936
+ return no('body-file-too-large');
937
+ // procfs-style files report size 0 and still return bytes.
938
+ if (st.size === 0n && total > 0)
939
+ return no('body-file-size-zero');
940
+ if (BigInt(total) !== st.size)
941
+ return no('body-file-size-mismatch');
942
+ decoding = true;
943
+ const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(buf.subarray(0, total));
944
+ decoding = false;
945
+ if (text.includes('\u0000'))
946
+ return no('body-file-nul');
947
+ return { ok: true, text };
948
+ }
949
+ catch {
950
+ return no(decoding ? 'body-file-not-utf8' : 'body-file-unreadable');
951
+ }
952
+ finally {
953
+ if (fd !== null) {
954
+ // Credential-custody review of PR #771, SF2: a close failure must not
955
+ // replace the result with a throw.
956
+ try {
957
+ closeSync(fd);
958
+ }
959
+ catch {
960
+ // Nothing more can be done; the process exits soon after.
961
+ }
962
+ }
963
+ }
964
+ }
965
+ /**
966
+ * Parse `--body-file`, opening nothing (v70, #761 revision 1, design changes
967
+ * 1 and 2). Without `--body-file` on a BODY_FILE_COMMANDS subcommand,
968
+ * checkArgs is `args` and path is null. Otherwise: one `--body-file` only,
969
+ * not with `--body` or `-b`, and a value not starting with `-` (so `-`,
970
+ * stdin, is refused). checkArgs holds `--body BODY_PLACEHOLDER` in its place.
971
+ * runGhWithToken runs checkGhArgs on checkArgs before any file is opened
972
+ * (security review of PR #771, INFO), so a command refused for another reason
973
+ * never opens the file.
974
+ */
975
+ export function planBodyFile(args) {
976
+ const unchanged = { ok: true, checkArgs: [...args], path: null, at: -1 };
977
+ if (args.length === 0)
978
+ return unchanged;
979
+ const start = args.length >= 2 && GROUPS.has(args[0]) ? 2 : 1;
980
+ const key = start === 2 ? `${args[0]} ${args[1]}` : args[0];
981
+ if (!BODY_FILE_COMMANDS.includes(key))
982
+ return unchanged;
983
+ const at = [];
984
+ for (let i = start; i < args.length; i++)
985
+ if (args[i] === '--body-file')
986
+ at.push(i);
987
+ if (at.length === 0)
988
+ return unchanged;
989
+ if (at.length > 1)
990
+ return { ok: false, code: 'body-file-repeated' };
991
+ if (args.slice(start).some((a) => a === '--body' || a === '-b'))
992
+ return { ok: false, code: 'body-file-with-body' };
993
+ const i = at[0];
994
+ const value = args[i + 1];
995
+ if (value === undefined || value.startsWith('-'))
996
+ return { ok: false, code: 'flag-value-missing' };
997
+ return { ok: true, checkArgs: [...args.slice(0, i), '--body', BODY_PLACEHOLDER, ...args.slice(i + 2)], path: value, at: i };
998
+ }
999
+ /**
1000
+ * Read the planned file and build the argv gh receives: `--body-file <path>`
1001
+ * replaced by the joined `--body=<text>`, which only this function builds. A
1002
+ * caller's own `--body=` still reaches checkGhArgs and is refused there.
1003
+ */
1004
+ export function bodyFileGhArgs(args, plan) {
1005
+ if (plan.path === null)
1006
+ return { ok: true, checkArgs: plan.checkArgs, ghArgs: [...args] };
1007
+ const read = readBodyFileForGh(plan.path);
1008
+ if (!read.ok)
1009
+ return read;
1010
+ const joined = `--body=${read.text}`;
1011
+ if (Buffer.byteLength(joined, 'utf8') > BODY_ARG_MAX_BYTES)
1012
+ return { ok: false, code: 'body-arg-too-large' };
1013
+ return { ok: true, checkArgs: plan.checkArgs, ghArgs: [...args.slice(0, plan.at), joined, ...args.slice(plan.at + 2)] };
1014
+ }
1015
+ /**
1016
+ * planBodyFile then bodyFileGhArgs, with no checkGhArgs between them. For
1017
+ * tests and callers that check the argv themselves; runGhWithToken checks
1018
+ * between the two steps.
1019
+ */
1020
+ export function applyBodyFile(args) {
1021
+ const plan = planBodyFile(args);
1022
+ if (!plan.ok)
1023
+ return plan;
1024
+ return bodyFileGhArgs(args, plan);
1025
+ }
1026
+ /** Parse `gh version X.Y.Z` from `gh --version` output. Null when absent. */
1027
+ export function parseGhVersion(output) {
1028
+ if (typeof output !== 'string')
1029
+ return null;
1030
+ const m = /^gh version (\d+)\.(\d+)\.(\d+)\b/m.exec(output);
1031
+ if (!m)
1032
+ return null;
1033
+ return [Number(m[1]), Number(m[2]), Number(m[3])];
1034
+ }
1035
+ /** True when `v` is at least `min`. */
1036
+ export function versionAtLeast(v, min) {
1037
+ for (let i = 0; i < 3; i++) {
1038
+ if (v[i] > min[i])
1039
+ return true;
1040
+ if (v[i] < min[i])
1041
+ return false;
1042
+ }
1043
+ return true;
1044
+ }
1045
+ /** The git ceiling for `tempDir`: its absolute parent. */
1046
+ export function ceilingFor(tempDir) {
1047
+ return dirname(resolve(tempDir));
1048
+ }
1049
+ /**
1050
+ * True when git would split the ceiling: it holds `:`, git's list separator
1051
+ * for GIT_CEILING_DIRECTORIES (v69, lead decision on PR #766).
1052
+ */
1053
+ export function isUnsafeCeiling(ceiling) {
1054
+ return ceiling.includes(':');
1055
+ }
1056
+ /**
1057
+ * The child's whole environment. Only INHERITED_ENV_KEYS are read from
1058
+ * `parentEnv`; everything else is fixed or derived from `tempDir`. Test H2
1059
+ * asserts the key set exactly.
1060
+ *
1061
+ * `GIT_CEILING_DIRECTORIES` (v69, #763 revision 1) is the absolute parent of
1062
+ * `tempDir`, set on every call. gh runs with `tempDir` as its cwd, so git
1063
+ * checks `tempDir` itself and never moves up into the parent. Git ignores a
1064
+ * relative ceiling entry, so a relative `tempDir` is resolved first.
1065
+ *
1066
+ * Throws when that parent holds `:` (isUnsafeCeiling). runGhWithToken refuses
1067
+ * that case with `tempdir-unsafe` before any mint, so on its path this throw
1068
+ * is a second check that never fires. The message names no path.
1069
+ */
1070
+ export function buildChildEnv(parentEnv, token, tempDir) {
1071
+ const env = {};
1072
+ for (const k of INHERITED_ENV_KEYS) {
1073
+ const v = parentEnv[k];
1074
+ if (typeof v === 'string')
1075
+ env[k] = v;
1076
+ }
1077
+ env.HOME = tempDir;
1078
+ env.GH_CONFIG_DIR = tempDir;
1079
+ const ceiling = ceilingFor(tempDir);
1080
+ if (isUnsafeCeiling(ceiling))
1081
+ throw new Error('mx-agent gh: tempdir-unsafe');
1082
+ env.GIT_CEILING_DIRECTORIES = ceiling;
1083
+ for (const [k, v] of Object.entries(FIXED_CHILD_ENV))
1084
+ env[k] = v;
1085
+ env.GH_TOKEN = token;
1086
+ return env;
1087
+ }
1088
+ export const GH_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
1089
+ /** A token must fit in one environment value: printable ASCII with no space. */
1090
+ const TOKEN_RE = /^[!-~]+$/;
1091
+ /** Exit status for a wrapper refusal or failure. */
1092
+ export const WRAPPER_FAILURE_EXIT = 1;
1093
+ /** Shell convention for a process ended by a signal: 128 plus the signal number. */
1094
+ export function signalExit(sig) {
1095
+ return 128 + (osConstants.signals[sig] ?? 0);
1096
+ }
1097
+ /**
1098
+ * Attempt the revoke through boundedRevoke() (github-app-token.ts, moved there
1099
+ * in v60). Never rejects. A failure, a throw or the bound writes one line,
1100
+ * `mx-agent gh: revoke-failed`, with no error text, and changes no exit code.
1101
+ */
1102
+ async function revokeAndReport(deps, token) {
1103
+ if ((await boundedRevoke(deps.revoke, token, deps.setTimer)) === 'failed') {
1104
+ deps.writeStderr('mx-agent gh: revoke-failed\n');
1105
+ }
1106
+ }
1107
+ function refuse(deps, code) {
1108
+ deps.writeStderr(`mx-agent gh: ${code}\n`);
1109
+ return WRAPPER_FAILURE_EXIT;
1110
+ }
1111
+ /**
1112
+ * Run gh with an mx-bott token in the child only. Returns the exit status:
1113
+ * gh's own, or WRAPPER_FAILURE_EXIT on a refusal or failure.
1114
+ */
1115
+ export async function runGhWithToken(args, deps) {
1116
+ // v70 (#761 revision 1, design change 1; security review of PR #771,
1117
+ // INFO): parse, check the placeholder argv, then read and rewrite. A
1118
+ // command refused by checkGhArgs never opens its --body-file.
1119
+ const plan = planBodyFile(args);
1120
+ if (!plan.ok)
1121
+ return refuse(deps, plan.code);
1122
+ const check = checkGhArgs(plan.checkArgs);
1123
+ if (!check.ok)
1124
+ return refuse(deps, check.code);
1125
+ const body = bodyFileGhArgs(args, plan);
1126
+ if (!body.ok)
1127
+ return refuse(deps, body.code);
1128
+ const ghArgs = body.ghArgs;
1129
+ if (!deps.ghExists(GH_PATH))
1130
+ return refuse(deps, 'gh-missing');
1131
+ if (check.key === 'pr edit') {
1132
+ const v = parseGhVersion(deps.ghVersion(GH_PATH));
1133
+ if (v === null)
1134
+ return refuse(deps, 'gh-version-unknown');
1135
+ if (!versionAtLeast(v, MIN_GH_VERSION_FOR_PR_EDIT))
1136
+ return refuse(deps, 'gh-too-old-for-pr-edit');
1137
+ }
1138
+ let tempDir;
1139
+ try {
1140
+ tempDir = deps.makeTempDir();
1141
+ }
1142
+ catch {
1143
+ return refuse(deps, 'tempdir-failed');
1144
+ }
1145
+ // v69 (lead decision on PR #766): a parent holding `:` splits the git
1146
+ // ceiling. Refuse before any signal handler, mint or spawn; no path echoed.
1147
+ if (isUnsafeCeiling(ceilingFor(tempDir))) {
1148
+ deps.removeTempDir(tempDir);
1149
+ return refuse(deps, 'tempdir-unsafe');
1150
+ }
1151
+ let child = null;
1152
+ let token = null;
1153
+ let cleaned = false;
1154
+ let interrupted = null;
1155
+ const cleanup = () => {
1156
+ if (cleaned)
1157
+ return;
1158
+ cleaned = true;
1159
+ deps.removeTempDir(tempDir);
1160
+ };
1161
+ // Single flight (v59 revision 1, S1): the signal path and the normal path
1162
+ // share one revoke. Never rejects.
1163
+ let revoking = null;
1164
+ const revokeOnce = (t) => {
1165
+ if (revoking === null)
1166
+ revoking = revokeAndReport(deps, t);
1167
+ return revoking;
1168
+ };
1169
+ // Signals reach Node through the event loop, so no handler can run between
1170
+ // makeTempDir() above and the registrations below.
1171
+ //
1172
+ // v59 revision 1, S1. The first signal kills gh, removes the temp dir, then
1173
+ // attempts the revoke within REVOKE_TIMEOUT_MS, and exits from a `finally`.
1174
+ // With no token yet (a signal during the mint) it exits at once; the token,
1175
+ // if the mint still resolves, is revoked by the path below. A second signal
1176
+ // while the revoke is pending exits at once and leaves the token unrevoked.
1177
+ const onSig = (sig) => () => {
1178
+ if (interrupted !== null) {
1179
+ deps.exit(signalExit(sig));
1180
+ return;
1181
+ }
1182
+ interrupted = sig;
1183
+ if (child !== null)
1184
+ child.kill(sig);
1185
+ cleanup();
1186
+ if (token === null) {
1187
+ deps.exit(signalExit(sig));
1188
+ return;
1189
+ }
1190
+ const minted = token;
1191
+ void (async () => {
1192
+ try {
1193
+ await revokeOnce(minted);
1194
+ }
1195
+ finally {
1196
+ deps.exit(signalExit(sig));
1197
+ }
1198
+ })();
1199
+ };
1200
+ const offs = GH_SIGNALS.map((sig) => deps.onSignal(sig, onSig(sig)));
1201
+ try {
1202
+ let minted;
1203
+ try {
1204
+ minted = await deps.mint(GH_PURPOSE);
1205
+ }
1206
+ catch (err) {
1207
+ return refuse(deps, err instanceof GitHubAppTokenError ? err.code : 'mint-failed');
1208
+ }
1209
+ // Plan gap: the plan does not name the token-shape path. A value that fails
1210
+ // TOKEN_RE is not revoked: it never reached gh, and sending an unchecked
1211
+ // value in an Authorization header is not done.
1212
+ if (typeof minted !== 'string' || !TOKEN_RE.test(minted))
1213
+ return refuse(deps, 'token-shape');
1214
+ token = minted;
1215
+ // A signal during the mint has already removed the temp dir. Never spawn
1216
+ // after that, even if exit() returned (it does only in tests).
1217
+ if (interrupted !== null)
1218
+ return signalExit(interrupted);
1219
+ try {
1220
+ // v69 (#763): gh runs in the wrapper's own temp dir, never the caller's cwd.
1221
+ child = deps.spawn(GH_PATH, [...ghArgs], buildChildEnv(deps.parentEnv(), token, tempDir), tempDir);
1222
+ }
1223
+ catch {
1224
+ return refuse(deps, 'spawn-failed');
1225
+ }
1226
+ const result = await child.done;
1227
+ if (result.error)
1228
+ return refuse(deps, 'spawn-failed');
1229
+ if (typeof result.code === 'number')
1230
+ return result.code;
1231
+ if (result.signal !== null)
1232
+ return signalExit(result.signal);
1233
+ return WRAPPER_FAILURE_EXIT;
1234
+ }
1235
+ finally {
1236
+ cleanup();
1237
+ // After gh has exited, or spawn failed, or a signal arrived during the
1238
+ // mint. The signal handlers stay registered until the revoke settles, so
1239
+ // a signal now joins this revoke rather than starting another.
1240
+ if (token !== null)
1241
+ await revokeOnce(token);
1242
+ for (const off of offs)
1243
+ off();
1244
+ }
1245
+ }
1246
+ //# sourceMappingURL=gh-token-run.js.map