viewable-one 0.12.7 → 0.12.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ // Codex's PreToolUse hook for another login (#7466, otherLogins.mjs).
2
+ //
3
+ // Codex runs this before every tool call with the call on stdin, as JSON:
4
+ // `{ hook_event_name: "PreToolUse", tool_name: "Bash", tool_input: { command } }`.
5
+ // Exit 0 lets the call run. Exit 2 with a reason on stderr stops it before it
6
+ // runs and hands the reason to the agent. Any other ending lets the call run
7
+ // in Codex, so everything this cannot read is refused, never let through.
8
+ //
9
+ // argv[2], when given, is the board's ask in Codex's words
10
+ // (`mcp__glytch__ask_user`), for the words handed back.
11
+ import { hookCommandOf, otherLoginDenied, usesAnotherLogin } from "./otherLogins.mjs";
12
+
13
+ const ask = process.argv[2] || undefined;
14
+ const refuse = () => {
15
+ process.stderr.write(`${otherLoginDenied(ask)}\n`);
16
+ process.exit(2);
17
+ };
18
+
19
+ let input = "";
20
+ process.stdin.setEncoding("utf8");
21
+ process.stdin.on("data", (chunk) => { input += chunk; });
22
+ process.stdin.on("error", refuse);
23
+ process.stdin.on("end", () => {
24
+ try {
25
+ const command = hookCommandOf(JSON.parse(input)?.tool_input);
26
+ if (command !== null && usesAnotherLogin(command)) refuse();
27
+ process.exit(0);
28
+ } catch {
29
+ refuse();
30
+ }
31
+ });
@@ -0,0 +1,386 @@
1
+ // A REFUSAL STOPS THE RUN; IT NEVER SENDS IT TO ANOTHER LOGIN (#6995).
2
+ //
3
+ // A computer run asked for a Supabase user count. Its read-only key was
4
+ // refused, so it ran the count through the Supabase CLI's own login, which
5
+ // has full rights to the database. A narrow key is the person's choice of how
6
+ // much the run may do; a stronger login that happens to sit on the same
7
+ // computer is not a second door to the same data.
8
+ //
9
+ // This file is the one list of those other logins, and every door that can
10
+ // hold a run back reads it:
11
+ // - the words every run is told (conversationRules.mjs `refusalRule`, in the
12
+ // idea preamble and the chat turn's prefix, for every engine);
13
+ // - Claude Code's deny rules (`CLAUDE_OTHER_LOGIN_TOOLS`, in agents.mjs's
14
+ // --disallowedTools and the ACP adapter's `disallowedTools`), checked
15
+ // before any permission prompt, so neither the allowlist's `Bash(npx:*)`
16
+ // nor "Allow for this run" can let one through;
17
+ // - the shared permission asker (permissionAsk.mjs), which refuses
18
+ // `usesAnotherLogin` commands before any question, remembered rule or
19
+ // "Allow for this run": Claude's prompts, ACP's and Codex's sandbox
20
+ // escalations all land there;
21
+ // - opencode's own config (`OPENCODE_OTHER_LOGIN_RULES`, agents.mjs
22
+ // prepareWorkspace), since `--auto` approves everything it does not deny;
23
+ // - Codex's own PreToolUse hook (`codexOtherLoginArgs`, codex.mjs), which
24
+ // runs `usesAnotherLogin` on every command before it runs (#7466). The
25
+ // asker alone was not enough there: a plain command inside Codex's
26
+ // sandbox never asks, so it never reached the asker.
27
+ //
28
+ // EVERY ENGINE THE COMPUTER STARTS, and how the list holds on it (#7466):
29
+ // - Claude Code: `--disallowedTools` deny rules, then the asker.
30
+ // - Claude Code via ACP (the only ACP agent): the adapter's
31
+ // `disallowedTools`, then the asker.
32
+ // - Codex: the PreToolUse hook below, then the asker for a sandbox
33
+ // escalation. A Codex that does not list the hook as trusted is not
34
+ // given the run (codex.mjs `requireLoginHook`).
35
+ // - opencode: `permission.bash` deny patterns.
36
+ //
37
+ // WHAT IT DOES NOT STOP, said plainly so nobody repeats it as a fence: a
38
+ // command the allowlist already lets through without asking can still reach
39
+ // one through a script (`node -e`, `npm run <script>`, a `cat` of a token file
40
+ // spelled some new way). On Codex, text typed into a shell the run already
41
+ // opened (`write_stdin`) runs no hook. The words cover those. The child's environment is
42
+ // already an allowlist (child.mjs `childEnv`), so a token exported in the
43
+ // person's shell (SUPABASE_ACCESS_TOKEN, GH_TOKEN) is not handed to the run.
44
+ //
45
+ // WHAT COUNTS. A command-line tool that signs in with a stored login of its
46
+ // own and reaches the data a connected app's key was meant to bound (the
47
+ // Supabase CLI), and the stores that hand out a saved secret (the macOS
48
+ // keychain, the Linux keyring, password managers, git's credential helpers,
49
+ // `gh auth token`). A tool is judged where it RUNS, at a command's start, so
50
+ // a commit message or a folder named `supabase` is not refused.
51
+
52
+ import { createHash } from "node:crypto";
53
+ import { fileURLToPath } from "node:url";
54
+
55
+ /** Command-line tools that use a stored login of their own. */
56
+ const LOGIN_TOOLS = ["supabase"];
57
+
58
+ /** Password managers: every call hands out or unlocks saved secrets. */
59
+ const PASSWORD_MANAGERS = new Set(["op", "bw", "lpass"]);
60
+
61
+ /** The macOS keychain subcommands that print a saved secret. */
62
+ const KEYCHAIN_READS = new Set(["find-generic-password", "find-internet-password", "find-key", "dump-keychain", "export"]);
63
+
64
+ /** Token files a login tool keeps on disk, matched anywhere in a command:
65
+ * `cat`, `head`, `node -e` or a redirection that names one is refused. Each
66
+ * is written with `/`; a `\\` (Windows) is matched too. */
67
+ const TOKEN_FILE_PATHS = [".supabase/access-token", ".config/gh/hosts.yml"];
68
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
69
+ const TOKEN_FILES = new RegExp(TOKEN_FILE_PATHS.map((path) => path.split("/").map(escapeRegExp).join("[\\\\/]")).join("|"), "i");
70
+
71
+ /** Words that run the command after them. Each may take flags first; the
72
+ * flags listed take a value, which is skipped too. */
73
+ const WRAPPERS = new Map([
74
+ ["env", new Set(["-u", "-C", "--unset", "--chdir"])],
75
+ ["sudo", new Set(["-u", "-g", "-h", "-p", "-C", "-U", "-r", "-t", "-D"])],
76
+ ["doas", new Set(["-u", "-C"])],
77
+ ["command", new Set()], ["exec", new Set(["-a"])], ["builtin", new Set()], ["noglob", new Set()],
78
+ ["nohup", new Set()], ["time", new Set(["-f", "-o"])], ["nice", new Set(["-n"])],
79
+ ["xargs", new Set(["-I", "-n", "-P", "-L", "-d", "-E", "-s", "-a"])],
80
+ ["arch", new Set()], ["caffeinate", new Set(["-t", "-w"])], ["stdbuf", new Set()],
81
+ ["timeout", new Set(["-s", "-k", "--signal", "--kill-after"])],
82
+ // Shell keywords that start a command after them.
83
+ ["if", new Set()], ["then", new Set()], ["else", new Set()], ["elif", new Set()], ["do", new Set()],
84
+ ["while", new Set()], ["until", new Set()], ["!", new Set()],
85
+ ]);
86
+ /** Wrappers whose first plain word is a value, not the command. */
87
+ const FIRST_WORD_IS_VALUE = new Set(["timeout"]);
88
+
89
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
90
+
91
+ /** Package runners: `npx supabase`, `npm exec supabase`, `pnpm dlx supabase`. */
92
+ const PACKAGE_RUNNERS = new Map([
93
+ ["npx", null], ["bunx", null], ["pnpx", null],
94
+ ["npm", new Set(["exec", "x"])], ["pnpm", new Set(["dlx", "exec"])], ["yarn", new Set(["dlx", "exec"])], ["bun", new Set(["x"])],
95
+ ]);
96
+
97
+ /** A program's name as the shell finds it: no folder, no Windows suffix, any
98
+ * case (a Mac's disk does not tell `Supabase` from `supabase`). */
99
+ const programOf = (word) => String(word ?? "").split(/[\\/]/).pop().toLowerCase().replace(/\.(?:exe|cmd|bat|ps1)$/, "");
100
+
101
+ /** A package word without its version: `supabase@latest` is `supabase`. */
102
+ const packageOf = (word) => {
103
+ const name = String(word ?? "").replace(/^--package=/, "");
104
+ const at = name.indexOf("@", 1);
105
+ return (at > 0 ? name.slice(0, at) : name).toLowerCase();
106
+ };
107
+
108
+ /** A shell line as commands, each a list of words with quotes removed, and
109
+ * the command substitutions inside double quotes (`"$(...)"`, `` "`...`" ``),
110
+ * which still run. Separators (`;`, `&`, `|`, newline, parentheses, braces,
111
+ * backticks, `$(`) end a command only outside quotes; a quoted word stays one
112
+ * word, and single quotes hide a `$(` (it is literal text there). A
113
+ * redirection is not a word: `2>/dev/null supabase` runs `supabase`, so the
114
+ * fd number, the operator and its target are dropped. */
115
+ function commandsOf(line) {
116
+ const commands = [];
117
+ const substitutions = [];
118
+ let words = [];
119
+ let word = "";
120
+ let inWord = false;
121
+ let quote = null;
122
+ let target = false; // the next word is a redirection's target
123
+ const endWord = () => {
124
+ if (inWord && !target) words.push(word);
125
+ if (inWord) target = false;
126
+ word = "";
127
+ inWord = false;
128
+ };
129
+ const endCommand = () => { endWord(); target = false; if (words.length > 0) commands.push(words); words = []; };
130
+ for (let i = 0; i < line.length; i += 1) {
131
+ const c = line[i];
132
+ if (quote === "'") { if (c === "'") quote = null; else word += c; continue; }
133
+ if (quote === "\"") {
134
+ if (c === "\"") quote = null;
135
+ else if (c === "\\" && i + 1 < line.length) word += line[++i];
136
+ else {
137
+ if (c === "`" || (c === "$" && line[i + 1] === "(")) substitutions.push(line.slice(i + (c === "`" ? 1 : 2)));
138
+ word += c;
139
+ }
140
+ continue;
141
+ }
142
+ if (c === "\\") { if (i + 1 < line.length) { word += line[++i]; inWord = true; } continue; }
143
+ if (c === "'" || c === "\"") { quote = c; inWord = true; continue; }
144
+ if (c === "\n" || c === "\r") { endCommand(); continue; }
145
+ if (/\s/.test(c)) { endWord(); continue; }
146
+ if (c === "$" && line[i + 1] === "(") { endCommand(); i += 1; continue; }
147
+ if ((c === "<" || c === ">") && line[i + 1] !== "(") {
148
+ // `2>`, `&>`, `>>`, `<<<`, `>&1`, `>|`: a digit-only word before it is
149
+ // its fd, never a word of the command.
150
+ if (/^\d*$/.test(word) && !target) { word = ""; inWord = false; } else endWord();
151
+ while (i + 1 < line.length && "<>&|".includes(line[i + 1])) i += 1;
152
+ target = true;
153
+ continue;
154
+ }
155
+ if (";&|(){}`<>".includes(c)) { endCommand(); continue; }
156
+ word += c;
157
+ inWord = true;
158
+ }
159
+ endCommand();
160
+ return { commands, substitutions };
161
+ }
162
+
163
+ /** Whether one call of a program, with its words, reaches another login. */
164
+ function callUsesLogin(program, rest) {
165
+ if (LOGIN_TOOLS.includes(program) || PASSWORD_MANAGERS.has(program)) return true;
166
+ if (program.startsWith("git-credential")) return true;
167
+ if (program === "security") return KEYCHAIN_READS.has(rest[0]);
168
+ if (program === "secret-tool") return rest[0] === "lookup" || rest[0] === "search";
169
+ if (program === "git") {
170
+ // git's own options come before the subcommand; -c and -C take a value.
171
+ let i = 0;
172
+ while (i < rest.length && rest[i].startsWith("-")) i += rest[i] === "-c" || rest[i] === "-C" ? 2 : 1;
173
+ const sub = rest[i] ?? "";
174
+ return sub === "credential" || sub.startsWith("credential-");
175
+ }
176
+ if (program === "gh") {
177
+ const plain = rest.filter((w) => !w.startsWith("-"));
178
+ if (plain[0] !== "auth") return false;
179
+ return plain[1] === "token" || (plain[1] === "status" && rest.some((w) => w === "-t" || w === "--show-token"));
180
+ }
181
+ return false;
182
+ }
183
+
184
+ /** Whether a package runner's words start a login tool. */
185
+ function packageRunUsesLogin(words, depth) {
186
+ for (let i = 0; i < words.length; i += 1) {
187
+ const w = words[i];
188
+ if (w === "--") continue;
189
+ if (w === "-p" || w === "--package") { if (LOGIN_TOOLS.includes(packageOf(words[i + 1]))) return true; i += 1; continue; }
190
+ if (w.startsWith("--package=")) { if (LOGIN_TOOLS.includes(packageOf(w))) return true; continue; }
191
+ if (w === "-c" || w === "--call") return usesAnotherLogin(words[i + 1] ?? "", depth + 1);
192
+ if (w.startsWith("-")) continue;
193
+ return LOGIN_TOOLS.includes(packageOf(w)) || LOGIN_TOOLS.includes(programOf(w));
194
+ }
195
+ return false;
196
+ }
197
+
198
+ /** Whether one command (its words) reaches another login. */
199
+ function commandUsesLogin(words, depth) {
200
+ let i = 0;
201
+ for (;;) {
202
+ const w = words[i];
203
+ if (w === undefined) return false;
204
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) { i += 1; continue; }
205
+ const wrapper = WRAPPERS.get(programOf(w));
206
+ if (!wrapper) break;
207
+ i += 1;
208
+ while (words[i]?.startsWith("-") && words[i] !== "-") i += wrapper.has(words[i]) ? 2 : 1;
209
+ if (FIRST_WORD_IS_VALUE.has(programOf(w)) && words[i] !== undefined) i += 1;
210
+ }
211
+ const program = programOf(words[i]);
212
+ const rest = words.slice(i + 1);
213
+ if (SHELLS.has(program)) {
214
+ const flag = rest.findIndex((w) => /^-[A-Za-z]*c[A-Za-z]*$/.test(w));
215
+ return flag >= 0 && usesAnotherLogin(rest[flag + 1] ?? "", depth + 1);
216
+ }
217
+ if (program === "eval") return usesAnotherLogin(rest.join(" "), depth + 1);
218
+ if (PACKAGE_RUNNERS.has(program)) {
219
+ const subs = PACKAGE_RUNNERS.get(program);
220
+ if (subs === null) return packageRunUsesLogin(rest, depth);
221
+ return subs.has(rest[0]) && packageRunUsesLogin(rest.slice(1), depth);
222
+ }
223
+ return callUsesLogin(program, rest);
224
+ }
225
+
226
+ /** Whether a shell command reaches another login or a saved secret, at any
227
+ * command in the line, inside `sh -c`, `eval`, a package runner or a `$( )`.
228
+ * Anything it cannot read for sure (too deeply nested) counts as a yes. */
229
+ export function usesAnotherLogin(command, depth = 0) {
230
+ const line = String(command ?? "");
231
+ if (depth > 4) return true;
232
+ if (TOKEN_FILES.test(line)) return true;
233
+ const { commands, substitutions } = commandsOf(line);
234
+ if (commands.some((words) => commandUsesLogin(words, depth))) return true;
235
+ // A substitution inside double quotes still runs: "$(supabase ...)".
236
+ return substitutions.some((rest) => usesAnotherLogin(rest, depth + 1));
237
+ }
238
+
239
+ /** What the agent reads when the asker refuses one, naming the board's ask
240
+ * in that engine's own words (`ask_user` for Claude Code and ACP,
241
+ * `mcp__glytch__ask_user` for Codex), the way refusalRule does. It shuts the
242
+ * other doors and sends the run to ask with the reason. */
243
+ export const otherLoginDenied = (ask = "ask_user") =>
244
+ "Refused: this uses another login, token or saved key on this computer. A run never gets round a refusal that way. " +
245
+ `Stop this part of the task and ask the person on the board with ${ask}: say what was refused and why ` +
246
+ "(the error you got), and what they could change. Do not try another login, CLI, token or key.";
247
+
248
+ /** Claude Code deny rules for the same tools. A deny rule is checked before
249
+ * any allow rule or prompt, so it holds where `Bash(npx:*)`, `Bash(npm:*)`
250
+ * and `Bash(git:*)` on the allowlist would otherwise let the call run with no
251
+ * question, and so never reach usesAnotherLogin. The `:*` rules are prefix
252
+ * rules every Claude Code reads. The `*` rules are wildcards (Claude Code
253
+ * 2.1.316 reads them, "Use * for wildcards"; an older one matches nothing
254
+ * with them): they catch the package named by a flag (`npx --package
255
+ * supabase supabase`, `npx -y -p supabase@2 supabase`), a version, a script
256
+ * (`npx -c 'supabase ...'`) and flags before the name. They need the name as
257
+ * its own word, so `npx vitest run supabase/functions/x.test.mjs` and
258
+ * `npx eslint supabase` still run. `npm exec` and `npm x` are barred whenever
259
+ * they name the tool at all: a run uses npx for its own tools. */
260
+ /** git's credential subcommand and the helpers that print a saved login. */
261
+ const GIT_CREDENTIAL_WORDS = ["credential fill", "credential approve", "credential reject", "credential capability",
262
+ ...["osxkeychain", "manager", "manager-core", "store", "cache", "libsecret", "wincred"].map((helper) => `credential-${helper}`)];
263
+
264
+ export const CLAUDE_OTHER_LOGIN_TOOLS = [
265
+ ...LOGIN_TOOLS.flatMap((tool) => [
266
+ `Bash(${tool}:*)`,
267
+ `Bash(npx ${tool}:*)`, `Bash(npx -y ${tool}:*)`, `Bash(npx --yes ${tool}:*)`, `Bash(npx ${tool}@latest:*)`,
268
+ `Bash(npm exec ${tool}:*)`, `Bash(npm exec -- ${tool}:*)`, `Bash(npm x ${tool}:*)`,
269
+ `Bash(npx ${tool}*)`, `Bash(npx -* ${tool})`, `Bash(npx -* ${tool} *)`, `Bash(npx -* ${tool}@*)`,
270
+ `Bash(npx *-p ${tool}*)`, `Bash(npx *--package ${tool}*)`, `Bash(npx *--package=${tool}*)`,
271
+ `Bash(npx *-c *${tool}*)`, `Bash(npx *--call *${tool}*)`,
272
+ `Bash(npm exec *${tool}*)`, `Bash(npm x *${tool}*)`,
273
+ ]),
274
+ // git's own options first (`git -c core.pager=cat credential fill`, `git -C
275
+ // <dir> credential fill`) still match Bash(git:*), so the subcommands and
276
+ // helpers are named after any options. A commit message would have to say
277
+ // "credential fill" to be caught.
278
+ "Bash(git credential:*)",
279
+ ...GIT_CREDENTIAL_WORDS.flatMap((word) => [`Bash(git ${word}:*)`, `Bash(git * ${word}*)`]),
280
+ // The saved-secret stores, so Claude Code bars the same list the others do
281
+ // (#7466); none is on the allowlist, so the asker refuses them as well.
282
+ ...[...PASSWORD_MANAGERS].map((tool) => `Bash(${tool}:*)`),
283
+ ...[...KEYCHAIN_READS].map((sub) => `Bash(security ${sub}:*)`),
284
+ "Bash(secret-tool lookup:*)", "Bash(secret-tool search:*)",
285
+ "Bash(gh auth token:*)", "Bash(gh auth status *--show-token*)", "Bash(gh auth status *-t*)",
286
+ // A shell read of a token file (`cat`, `head`, `node -e`) is on the
287
+ // allowlist too: deny any command that names one.
288
+ ...TOKEN_FILE_PATHS.flatMap((path) => [`Bash(*${path}*)`, `Bash(*${path.replaceAll("/", "\\")}*)`]),
289
+ "Read(~/.supabase/**)",
290
+ ...TOKEN_FILE_PATHS.filter((path) => !path.startsWith(".supabase/")).map((path) => `Read(~/${path})`),
291
+ ];
292
+
293
+ /** opencode's own deny rules (its `permission.bash` patterns), for the same
294
+ * tools: `--auto` approves everything that is not denied. */
295
+ export const OPENCODE_OTHER_LOGIN_RULES = Object.fromEntries([
296
+ ...LOGIN_TOOLS.flatMap((tool) => [tool, `${tool} *`, `npx ${tool}*`, `npx -y ${tool}*`, `npm exec ${tool}*`]),
297
+ ...[...PASSWORD_MANAGERS].flatMap((tool) => [tool, `${tool} *`]),
298
+ ...LOGIN_TOOLS.flatMap((tool) => [`npx -* ${tool}`, `npx -* ${tool} *`, `npx -* ${tool}@*`, `npx *-p ${tool}*`, `npx *--package ${tool}*`,
299
+ `npx *--package=${tool}*`, `npx *-c *${tool}*`, `npm exec *${tool}*`, `npm x *${tool}*`]),
300
+ "security find-*", "security dump-keychain*", "security export*",
301
+ "secret-tool lookup*", "secret-tool search*",
302
+ "gh auth token*", "gh auth status *--show-token*", "gh auth status *-t*",
303
+ "git credential*", "git-credential*",
304
+ ...GIT_CREDENTIAL_WORDS.map((word) => `git * ${word}*`),
305
+ ...TOKEN_FILE_PATHS.flatMap((path) => [`*${path}*`, `*${path.replaceAll("/", "\\")}*`]),
306
+ ].map((pattern) => [pattern, "deny"]));
307
+
308
+ // CODEX'S OWN HOOK (#7466). Codex runs a plain command inside its sandbox
309
+ // without asking, and its sandbox reads files outside the workspace, so
310
+ // neither the asker nor the sandbox sees `ls ~/.supabase/access-token`. Its
311
+ // PreToolUse hook does: Codex runs it before every tool call (exec_command
312
+ // sends `{ tool_name: "Bash", tool_input: { command } }`) and does not run
313
+ // the call when the hook exits 2 with a reason on stderr. The hook is
314
+ // otherLoginHook.mjs, which runs the same `usesAnotherLogin` as the asker.
315
+ //
316
+ // TRUST. Codex runs a hook only when its config holds the hook's hash
317
+ // (`hooks.state."<key>".trusted_hash`); `--dangerously-bypass-hook-trust`
318
+ // would also run every untrusted hook in a project, so it is not used. The
319
+ // hash is Codex's own: sha256 of the hook's normalized identity as JSON with
320
+ // sorted keys (codex-rs hooks/src/engine/discovery.rs `hook_hash`, config
321
+ // fingerprint.rs `version_for_toml`), checked against codex-cli 0.165.0's
322
+ // `hooks/list`. Both go in as `-c` flags, which Codex merges into the
323
+ // person's own hook trust rather than replacing it. If a later Codex hashes
324
+ // differently, `hooks/list` shows the hook untrusted and codex.mjs refuses to
325
+ // start the run: it fails closed, never open.
326
+ //
327
+ // A hook that crashes or times out does not block in Codex, so the hook
328
+ // refuses whatever it cannot read, and runs on the node running this bridge.
329
+
330
+ /** The key Codex gives the first PreToolUse hook passed with `-c`. */
331
+ export const CODEX_LOGIN_HOOK_KEY = "/<session-flags>/config.toml:pre_tool_use:0:0";
332
+ const CODEX_HOOK_SCRIPT = fileURLToPath(new URL("./otherLoginHook.mjs", import.meta.url));
333
+ const CODEX_HOOK_TIMEOUT_SEC = 30;
334
+
335
+ /** A word as one literal shell word for the shell Codex runs a hook with
336
+ * (`$SHELL -lc` on a Mac or Linux, `cmd /C` on Windows). A hook that fails to
337
+ * start lets the call run in Codex, so a path must never expand: in sh a
338
+ * single-quoted word is literal (`$`, backticks and `\` included; a `'` is
339
+ * written `'\''`). cmd.exe has no such quote: inside `"..."` a `%` still
340
+ * expands and a `"` ends the word, so a path holding either is refused, and
341
+ * the run with it (codex.mjs), rather than quoted wrongly. */
342
+ const shellWord = (word, platform = process.platform) => {
343
+ const text = String(word);
344
+ if (platform !== "win32") return `'${text.replaceAll("'", "'\\''")}'`;
345
+ if (/["%\r\n]/.test(text)) throw new Error(`The block on other logins cannot be started from this path on Windows: ${text}`);
346
+ return `"${text}"`;
347
+ };
348
+
349
+ /** Sorted-key JSON, the way serde_json's `sort_all_objects` writes it. */
350
+ const sortedJson = (value) => {
351
+ if (Array.isArray(value)) return `[${value.map(sortedJson).join(",")}]`;
352
+ if (value && typeof value === "object") {
353
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${sortedJson(value[key])}`).join(",")}}`;
354
+ }
355
+ return JSON.stringify(value);
356
+ };
357
+
358
+ /** Codex's trust hash for one command hook (see TRUST above). */
359
+ export const codexHookHash = ({ eventName, matcher, handler }) =>
360
+ `sha256:${createHash("sha256").update(sortedJson({ event_name: eventName, matcher, hooks: [handler] })).digest("hex")}`;
361
+
362
+ /** The hook's command line: this node, the hook script, and the name of the
363
+ * board's ask in Codex's words, for the refusal it hands back. */
364
+ export const codexLoginHookCommand = ({ ask, node = process.execPath, script = CODEX_HOOK_SCRIPT, platform = process.platform } = {}) =>
365
+ [node, script, ...(ask ? [ask] : [])].map((word) => shellWord(word, platform)).join(" ");
366
+
367
+ /** The `-c` flags that give a Codex run the hook, already trusted. */
368
+ export function codexOtherLoginArgs(options = {}) {
369
+ const command = codexLoginHookCommand(options);
370
+ const handler = { type: "command", command, timeout: CODEX_HOOK_TIMEOUT_SEC, async: false };
371
+ const hash = codexHookHash({ eventName: "pre_tool_use", matcher: "*", handler });
372
+ return [
373
+ "-c", `hooks.PreToolUse=[{matcher="*", hooks=[{type="command", command=${JSON.stringify(command)}, timeout=${CODEX_HOOK_TIMEOUT_SEC}}]}]`,
374
+ "-c", `hooks.state={${JSON.stringify(CODEX_LOGIN_HOOK_KEY)}={trusted_hash=${JSON.stringify(hash)}}}`,
375
+ ];
376
+ }
377
+
378
+ /** The command a hook's tool input runs, or null when it runs none (an MCP
379
+ * tool's arguments). An argv list is quoted word by word, so `bash -lc '...'`
380
+ * is read inside. */
381
+ export function hookCommandOf(input) {
382
+ const command = input?.command ?? input?.cmd;
383
+ if (typeof command === "string") return command;
384
+ if (Array.isArray(command)) return command.map((word) => `'${String(word).replaceAll("'", "'\\''")}'`).join(" ");
385
+ return command == null ? null : String(command);
386
+ }
@@ -1,5 +1,6 @@
1
- import { writeRisk, riskReason } from "./writePolicy.mjs";
1
+ import { writeRisk, riskReason, automationReads } from "./writePolicy.mjs";
2
2
  import { appInputsText } from "./codexToolInputs.mjs";
3
+ import { otherLoginDenied, usesAnotherLogin } from "./otherLogins.mjs";
3
4
  // ASK IN THE IDEA (issue #478, rulings #470 #468 #417 #418).
4
5
  //
5
6
  // A coding agent on the person's computer works from a list of things it may
@@ -49,6 +50,11 @@ export const ALLOW = "Allow";
49
50
  * allow" (one exact command, #3726) never covers. */
50
51
  export const ALLOW_RUN = "Allow for this run";
51
52
  export const NOT_THIS = "Not this";
53
+ /** The lead the app puts before words typed on a permission (#8224), so they
54
+ * can never equal a label, even on a runner that only matches labels. */
55
+ export const TYPED_NO = "Not this: ";
56
+ /** What check_answer says after a typed answer's question id (board-mcp questionStatus.mjs). */
57
+ const TYPED_MARK = "typed in their own words, not a pick";
52
58
  /** "Always allow git status in my-app" names the safe family it saves (#3726);
53
59
  * without one (a tool, not a shell command) it stays "Always allow in my-app". */
54
60
  export const alwaysLabel = (folderName, word = "") => word === "" ? `Always allow in ${folderName}` : `Always allow ${word} in ${folderName}`;
@@ -601,11 +607,17 @@ export function ruleCovers(rules, toolName, input, folder, base) {
601
607
  // ---------------------------------------------------------------------------
602
608
 
603
609
  /** What check_answer said, as one of: {state:"open"}, {state:"answered",
604
- * decision}, {state:"gone"} (dismissed, or no such question). */
610
+ * decision, typed}, {state:"gone"} (dismissed, or no such question). `typed`:
611
+ * the person wrote the answer rather than picked it (#8224). The decision is
612
+ * every line up to the question's id, so words on several lines stay whole. */
605
613
  export function readAnswer(text) {
606
614
  const t = String(text ?? "");
607
- const answered = /^Answered\. The user's decision: (.*)$/m.exec(t);
608
- if (answered) return { state: "answered", decision: answered[1].trim() };
615
+ const whole = /^Answered\. The user's decision: ([\s\S]*)\n\(question [^\n]*\)\s*$/.exec(t);
616
+ const answered = whole ?? /^Answered\. The user's decision: (.*)$/m.exec(t);
617
+ if (answered) {
618
+ const typed = new RegExp(`\\n\\(question [^\\n]*; ${TYPED_MARK}\\)\\s*$`).test(t);
619
+ return { state: "answered", decision: answered[1].trim(), typed };
620
+ }
609
621
  if (/^Answered\./m.test(t)) return { state: "answered", decision: "" };
610
622
  if (/dismissed|^No such question/m.test(t)) return { state: "gone" };
611
623
  return { state: "open" };
@@ -622,15 +634,29 @@ export function verdictFor(answer, folderName, always = alwaysLabel(folderName),
622
634
  if (answer.state === "gone") {
623
635
  return { behavior: "deny", remember: false, message: "The person dismissed the question without answering. Carry on without it, and do not ask for it again." };
624
636
  }
637
+ // WORDS NEVER GRANT (#8224): only a picked Allow, Always or run label does.
638
+ // Typed words are a no plus the words, even words that spell a label.
639
+ if (answer.typed === true || isTypedNo(answer.decision)) return wordsVerdict(typedWords(answer.decision));
625
640
  if (answer.decision === ALLOW) return { behavior: "allow", remember: false };
626
641
  if (runOffered && answer.decision === ALLOW_RUN) return { behavior: "allow", remember: false, forRun: true };
627
642
  if (always && answer.decision === always) return { behavior: "allow", remember: true };
628
643
  if (answer.decision === NOT_THIS || answer.decision === "") return { behavior: "deny", remember: false, message: NO_MESSAGE };
629
644
  // Their own words: not a button. That is a no, with the words passed along,
630
645
  // because "use yarn instead" is guidance the agent should read.
631
- return { behavior: "deny", remember: false, message: `The person said no to this, and wrote: ${oneLine(answer.decision, 400)}. Carry on without it.` };
646
+ return wordsVerdict(answer.decision);
632
647
  }
633
648
 
649
+ /** The words behind the app's typed lead, or the answer as it came. */
650
+ export const typedWords = (decision) => isTypedNo(decision) ? decision.slice(TYPED_NO.trim().length).trim() : decision.trim();
651
+
652
+ /** The answer starts with the app's typed lead (its space may be trimmed off). */
653
+ export const isTypedNo = (decision) => decision === TYPED_NO.trim() || decision.startsWith(TYPED_NO);
654
+
655
+ /** A no that passes the person's words on, or a plain no when there are none. */
656
+ const wordsVerdict = (words) => words === ""
657
+ ? { behavior: "deny", remember: false, message: NO_MESSAGE }
658
+ : { behavior: "deny", remember: false, message: `The person said no to this, and wrote: ${oneLine(words, 400)}. Carry on without it.` };
659
+
634
660
  /** The deny an agent reads when the question could not be filed. The board's
635
661
  * own refusal ("The run's idea is missing or deleted...") is the reason, so it
636
662
  * reaches the run's transcript instead of a vague "could not be asked" (#592). */
@@ -662,6 +688,20 @@ export const CLICK_AND_SCREEN_DENIED = "I can't press buttons inside other apps.
662
688
  const CLICK_AND_SCREEN_WORD = new RegExp(`(?:^|[\\s;&|()\`'"=])(?:[^\\s;&|()\`'"]*/)?(?:${CLICK_AND_SCREEN_COMMANDS.join("|")})(?=$|[\\s;&|()\`'"])`);
663
689
  export const drivesAnotherApp = (command) => CLICK_AND_SCREEN_WORD.test(String(command ?? ""));
664
690
 
691
+ /** The run card's line for an app read an automation's run made with no
692
+ * question (#6955): it says the automation was the yes and, as the server's
693
+ * receipt does for the same read (integrations `read: true`, #6628), never
694
+ * calls it a change. The tool reads as the question names it. The app is the
695
+ * engine's server key ("argos", "google_calendar"), so it reads as a name,
696
+ * each word capitalised ("Argos", "Google Calendar"); a key that already has
697
+ * a capital ("GitHub") stays as it is. */
698
+ const appWords = (app) => {
699
+ const key = String(app);
700
+ return /[A-Z]/.test(key) ? key : key.split(/[-_\s]+/).filter(Boolean).map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
701
+ };
702
+ export const automationReadWords = (app, tool) =>
703
+ `Read ${String(tool).replaceAll("_", " ")} in ${appWords(app)} without asking: setting the automation was your yes. Nothing was changed.`;
704
+
665
705
  /** Build the asker for one run.
666
706
  *
667
707
  * `ask({ toolName, input, signal })` resolves to `{behavior: "allow"}` or
@@ -680,9 +720,12 @@ export const drivesAnotherApp = (command) => CLICK_AND_SCREEN_WORD.test(String(c
680
720
  * fromId the idea the run belongs to
681
721
  * poll the run's answer poll, so the permission question's answer is
682
722
  * not also typed into the conversation (`claim`)
723
+ * askTool the engine's own name for the board's ask_user, for the words
724
+ * a refused other login hands back (#6995)
683
725
  */
684
726
  export function createPermissionAsker({
685
- folder, cwd, session, boardId, fromId, env, callTool = hostedCallTool, poll, log = () => {}, pollMs = 2000,
727
+ folder, cwd, session, boardId, fromId, env, callTool = hostedCallTool, poll, log = () => {}, pollMs = 2000, automation = false,
728
+ askTool = "ask_user",
686
729
  }) {
687
730
  const folderName = basename(folder) || folder;
688
731
  const scopedCallTool = (name, args, options) => callTool(name, args, { ...options, sessionBoardId: boardId });
@@ -693,12 +736,28 @@ export function createPermissionAsker({
693
736
  // second command's ask that was waiting beside the one answered.
694
737
  const runAllowed = new AbortController();
695
738
  const coveredByRun = (toolName, question) => !question && toolName === "Bash" && runAllowed.signal.aborted;
739
+ /** Whether a call of `tool` is a read made inside an automation's run, so it
740
+ * needs no question (ruling #5495): the same rule the server runs
741
+ * (writePolicy.automationReads), and only when `hints`, the app's own labels
742
+ * for the tool as the engine reports them (Codex's inventory), say
743
+ * read-only (#6955). With no labels the computer cannot tell a read from a
744
+ * write, so Claude's and ACP's requests, which carry none, always ask. The
745
+ * server's own rule keeps its label-less reads: it holds the tool's labels
746
+ * and the person's Allow list, which the computer has neither of. */
747
+ const readInAutomation = (tool, input, hints) => automation && hints?.readOnlyHint === true
748
+ && automationReads(tool, input && typeof input === "object" ? input : {}, hints);
696
749
  const ask = async ({ toolName, input: asked = {}, signal, question }) => {
697
750
  if (signal?.aborted) return null;
698
751
  if (!question && toolName === "Bash" && drivesAnotherApp(asked.command)) {
699
752
  log("permission: a command that drives another app is refused (#4204)");
700
753
  return { behavior: "deny", message: CLICK_AND_SCREEN_DENIED };
701
754
  }
755
+ // Another login, token or saved key (#6995): refused before any question,
756
+ // remembered rule or "Allow for this run", so a refusal is never got round.
757
+ if (!question && toolName === "Bash" && usesAnotherLogin(asked.command)) {
758
+ log("permission: a command that uses another login is refused (#6995)");
759
+ return { behavior: "deny", message: otherLoginDenied(askTool) };
760
+ }
702
761
  // A Claude command carries no working folder: it runs in the shell the run
703
762
  // started in (a worktree, not the linked folder itself) and wherever its
704
763
  // allowed `cd`s moved it, so its paths and links are judged there (#3759,
@@ -768,7 +827,7 @@ export function createPermissionAsker({
768
827
  if (answer.state !== "open") {
769
828
  if (question) return answer.state === "gone"
770
829
  ? { behavior: "cancel" }
771
- : { behavior: "answer", answer: answer.decision };
830
+ : { behavior: "answer", answer: answer.decision, ...(answer.typed ? { typed: true } : {}) };
772
831
  const verdict = verdictFor(answer, folderName, q.options.find((o) => o.startsWith("Always allow")) ?? null, { runOffered: q.options.includes(ALLOW_RUN) });
773
832
  if (verdict.forRun) runAllowed.abort();
774
833
  if (verdict.remember && !rememberable(toolName, input)) log("permission: this grant names no scope, so it is allowed once and not remembered");
@@ -787,5 +846,8 @@ export function createPermissionAsker({
787
846
  if (delay > 0) await sleepFor(delay, waitSignal);
788
847
  }
789
848
  };
849
+ // Codex hands over the app, the tool and the tool's labels apart, so the
850
+ // boundary between app and tool is never guessed. The only door that skips.
851
+ ask.appRead = (app, name, input, hints) => readInAutomation(name, input, hints);
790
852
  return ask;
791
853
  }
@@ -21,7 +21,7 @@ import { mkdir, readFile, stat } from "node:fs/promises";
21
21
  import { dirname, join } from "node:path";
22
22
  import { parse as parseToml, stringify } from "smol-toml";
23
23
  import { parse as parseJsonc, modify, applyEdits } from "jsonc-parser";
24
- import { BOARD_MCP_URL, CODEX_TOOL_TIMEOUT_SEC, RETIRED_BOARD_MCP_URLS, entryIsAtRetiredUrl, isLegacyBoardCommand, moveRetiredUrl } from "./mcpjson.mjs";
24
+ import { BOARD_MCP_URL, CODEX_TOOL_TIMEOUT_SEC, RETIRED_BOARD_MCP_URLS, boardEntryIsOurs, entryIsAtRetiredUrl, isLegacyBoardCommand, moveRetiredUrl } from "./mcpjson.mjs";
25
25
  import { writeFileAtomic } from "./atomic.mjs";
26
26
 
27
27
  const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
@@ -110,31 +110,11 @@ function withMovedTomlUrl(text, header, to) {
110
110
  return null;
111
111
  }
112
112
 
113
- /** Is this Codex `board` table ours - the retired spawned-command shape, or
114
- * a `board` entry already sitting at our hosted URL from before this
115
- * rename? Mirrors `boardEntryIsOurs` in lib/mcpjson.mjs; kept as its own
116
- * function here because the TOML shape (`{url}`, no `type`) is Codex's own.
117
- *
118
- * EXPORTED (brief 31 review, 2026-09-12) for the same reuse reason as
119
- * `withoutTomlTable` above. */
120
- export function boardEntryIsOurs(entry, env) {
121
- if (!object(entry)) return false;
122
- if (isLegacyBoardCommand(entry.command, entry.args)) return true;
123
- return typeof entry.url === "string" && (entry.url === BOARD_MCP_URL(env) || RETIRED_BOARD_MCP_URLS.includes(entry.url));
124
- }
125
-
126
- /** opencode's own shape: a `command` ARRAY rather than separate
127
- * `command`/`args` strings, plus `{type, url}` for the hosted shape. Kept as
128
- * its own function (rather than reusing `boardEntryIsOurs` above) because
129
- * opencode's `command` field is an array where Codex's and `.mcp.json`'s are
130
- * separate `command`/`args` strings - EXPORTED for the same reuse reason as
131
- * `withoutTomlTable` and `boardEntryIsOurs` above: lib/uninstall-project.mjs
132
- * used to keep a byte-identical copy of exactly this check. */
133
- export function opencodeBoardEntryIsOurs(entry, env) {
134
- if (!object(entry)) return false;
135
- if (Array.isArray(entry.command) && isLegacyBoardCommand(entry.command[0], entry.command.slice(1))) return true;
136
- return typeof entry.url === "string" && (entry.url === BOARD_MCP_URL(env) || RETIRED_BOARD_MCP_URLS.includes(entry.url));
137
- }
113
+ /** Is this Codex `board` table or opencode `board` entry ours? One check for
114
+ * every format since #7550: `boardEntryIsOurs` in lib/mcpjson.mjs reads a
115
+ * `command`/`args` pair and opencode's command array alike. Both names stay
116
+ * exported because lib/uninstall-project.mjs imports them. */
117
+ export { boardEntryIsOurs, boardEntryIsOurs as opencodeBoardEntryIsOurs };
138
118
 
139
119
  export function mergeCodexBoard(existing, env = process.env) {
140
120
  try {
@@ -208,7 +188,7 @@ export function mergeOpencodeBoard(existing, env = process.env) {
208
188
  const glytchPresent = Object.hasOwn(parsed.mcp ?? {}, "glytch");
209
189
  const boardPresent = Object.hasOwn(parsed.mcp ?? {}, "board");
210
190
  const existingBoard = parsed.mcp?.board;
211
- const boardIsOurs = boardPresent && opencodeBoardEntryIsOurs(existingBoard, env);
191
+ const boardIsOurs = boardPresent && boardEntryIsOurs(existingBoard, env);
212
192
  const legacyCommand = boardIsOurs && object(existingBoard) && Array.isArray(existingBoard.command) &&
213
193
  isLegacyBoardCommand(existingBoard.command[0], existingBoard.command.slice(1));
214
194
  const server = { type: "remote", url: BOARD_MCP_URL(env), enabled: true };