noracu 0.3.0 → 0.3.2

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.
package/src/approval.js CHANGED
@@ -8,13 +8,13 @@
8
8
  // approval_required — the person at the Mac edits the file to allow; noracu itself never writes it
9
9
  // (an agent must not be able to grant itself always-allow). Once the variable is set, a missing,
10
10
  // malformed or unreadable file, a symlink, an unknown key, or an empty or non-string pattern fails
11
- // CLOSED: no input goes out until it is fixed (cross-verification A0 2026-11-09: a missing file
12
- // allowed everything). Unset: no approval check (0.2.7 behaviour).
11
+ // CLOSED: no input goes out until it is fixed (before 0.3.0 a missing file allowed everything).
12
+ // Unset: no approval check (0.2.7 behaviour).
13
13
  // • NORACU_DENY_APPS: comma-separated bundle ids / app names that never get input, on top of the default
14
14
  // list — the terminal apps and the IDEs with a built-in terminal below, plus the terminal hosting this
15
15
  // server when the PPID chain shows one that is not on the list — so an agent cannot type into a shell.
16
16
  // A list that starts with "none" drops the default ("none" alone: no deny list; "none,com.x.y": only
17
- // com.x.y). Review S4A-s11-Gemini-2: a custom list used to replace the default, so naming one app
17
+ // com.x.y). a custom list used to replace the default, so naming one app
18
18
  // silently let input into Terminal again. The PPID
19
19
  // chain stops at launchd (a tmux or screen session started elsewhere, npx under a GUI host): then only
20
20
  // the listed terminals apply.
@@ -22,36 +22,51 @@
22
22
  // nothing. stat errors other than ENOENT fail closed.
23
23
  // • A variable that is set but blank (NORACU_APPROVAL_FILE= or NORACU_STOP_FILE=, e.g. an unfilled
24
24
  // placeholder in a client's config) is a broken setting, not "unset": input is refused until it is
25
- // removed or given a path (review S4A-s11-me-1: blank read as unset and turned both checks off).
25
+ // removed or given a path (blank read as unset and turned both checks off).
26
26
 
27
27
  import { readFileSync, statSync, openSync, fstatSync, closeSync, constants as fsc } from "node:fs";
28
28
  import { execFileSync } from "node:child_process";
29
29
 
30
- // Terminal apps by bundle id, and how their executable path looks in ps (review CR1/CR2 T6: iTerm2,
30
+ // Terminal apps by bundle id, and how their executable path looks in ps (iTerm2,
31
31
  // wezterm-gui, Ghostty and Warp were missed, and the walk stopped at tmux/screen)
32
32
  const TERMINALS = [
33
33
  { bundle: "com.apple.Terminal", path: /\/Terminal\.app\//i },
34
34
  { bundle: "com.googlecode.iterm2", path: /\/iTerm2?\.app\//i },
35
35
  { bundle: "com.github.wez.wezterm", path: /\/WezTerm\.app\/|\/wezterm(-gui)?$/i },
36
36
  { bundle: "com.mitchellh.ghostty", path: /\/Ghostty\.app\/|\/ghostty$/i },
37
- { bundle: "dev.warp.Warp*", path: /\/Warp[^/]*\.app\//i }, // Warp, Warp Preview (S4A-s11-Gemini-4)
37
+ { bundle: "dev.warp.Warp*", path: /\/Warp[^/]*\.app\//i }, // Warp, Warp Preview
38
38
  { bundle: "org.alacritty", path: /\/Alacritty\.app\/|\/alacritty$/i },
39
39
  { bundle: "net.kovidgoyal.kitty", path: /\/kitty\.app\/|\/kitty$/i },
40
40
  { bundle: "co.zeit.hyper", path: /\/Hyper\.app\//i },
41
+ // bundle ids from their signed bundles' code requirements and Homebrew's cask (2026-11-18)
42
+ { bundle: "org.tabby", path: /\/Tabby\.app\//i },
43
+ { bundle: "com.raphaelamorim.rio", path: /\/Rio\.app\/|\/rio$/i },
44
+ { bundle: "dev.commandline.waveterm", path: /\/Wave\.app\//i },
45
+ // Orca, an agent IDE whose terminals run a shell (appId and productName from its electron-builder config, and its
46
+ // Homebrew cask, 2026-11-19). On this list rather than with the IDEs so that a client running in one of its
47
+ // terminals is recognised as hosted by it too: its helper processes live inside Orca.app
48
+ { bundle: "com.stablyai.orca", path: /\/Orca\.app\//i },
41
49
  ];
42
50
 
43
51
  // --- host terminal (resolved once): the first ancestor that is a terminal app; tmux / screen are walked
44
52
  // through. Returns { bundle } for a listed terminal, { name } for another app bundle named like a terminal,
45
53
  // or null (chain broken, no terminal found).
54
+ // What one ancestor's executable path says: { bundle } for a listed terminal (a helper inside its .app counts),
55
+ // { name } for another app bundle named like a terminal, null for anything else. Exported for the tests.
56
+ export function terminalFromPath(comm) {
57
+ const t = TERMINALS.find((x) => x.path.test(comm));
58
+ if (t) return { bundle: t.bundle };
59
+ const app = /\/([^/]+)\.app\/Contents\/MacOS\/[^/]+$/.exec(comm);
60
+ if (app && /term|shell|console/i.test(app[1])) return { name: app[1] };
61
+ return null;
62
+ }
46
63
  function hostTerminal() {
47
64
  try {
48
65
  let pid = process.ppid;
49
66
  for (let i = 0; i < 12 && pid > 1; i++) {
50
67
  const comm = execFileSync("/bin/ps", ["-o", "comm=", "-p", String(pid)], { encoding: "utf8", timeout: 2000 }).trim();
51
- const t = TERMINALS.find((x) => x.path.test(comm));
52
- if (t) return { bundle: t.bundle };
53
- const app = /\/([^/]+)\.app\/Contents\/MacOS\/[^/]+$/.exec(comm);
54
- if (app && /term|shell|console/i.test(app[1])) return { name: app[1] };
68
+ const t = terminalFromPath(comm);
69
+ if (t) return t;
55
70
  // anything else — a shell, node, npm, tmux, screen — is walked through to its parent
56
71
  const ppidLine = execFileSync("/bin/ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf8", timeout: 2000 }).trim();
57
72
  pid = Number(ppidLine);
@@ -62,15 +77,14 @@ function hostTerminal() {
62
77
  }
63
78
  const HOST_TERMINAL = hostTerminal();
64
79
 
65
- // the same apps by name too, for an app whose bundle id cannot be read (cross-verification A0)
66
- // (S4A-s11-Gemini-4: Warp Preview was missed; Tabby, Rio and Wave are terminals known by name only here)
67
- const TERMINAL_NAMES = ["Terminal", "iTerm2", "iTerm", "WezTerm", "Ghostty", "Warp*", "Alacritty", "kitty", "Hyper", "Tabby", "Rio", "Wave"];
68
- // IDEs with a built-in terminal (next-steps R3, 2026-11-12): keys typed into one can reach its shell, so
80
+ // the same apps by name too, for an app whose bundle id cannot be read (Warp Preview was missed)
81
+ const TERMINAL_NAMES = ["Terminal", "iTerm2", "iTerm", "WezTerm", "Ghostty", "Warp*", "Alacritty", "kitty", "Hyper", "Tabby", "Rio", "Wave", "Orca"];
82
+ // IDEs with a built-in terminal (2026-11-12): keys typed into one can reach its shell, so
69
83
  // they get no input by default either. Bundle ids (VS Code and Cursor read from installed apps), and names,
70
84
  // which also match when the bundle id is read but differs (a fork, an edition)
71
- // Editions and channels are covered by a trailing * (Insiders, Exploration, Preview, Nightly, Canary — P18-Gemini-5).
85
+ // Editions and channels are covered by a trailing * (Insiders, Exploration, Preview, Nightly, Canary).
72
86
  // Two entries are broad on purpose and fail closed: the name "Code" (VS Code's own app name) also denies any other
73
- // app named exactly "Code", and com.jetbrains.* also denies JetBrains Toolbox, which has no shell (P18-Grok-3).
87
+ // app named exactly "Code", and com.jetbrains.* also denies JetBrains Toolbox, which has no shell.
74
88
  const IDE_BUNDLES = [
75
89
  "com.microsoft.VSCode*", "com.vscodium*",
76
90
  "com.todesktop.230313mzl4w4u92", // Cursor
@@ -115,7 +129,7 @@ export function stopFileBlocked() {
115
129
  }
116
130
 
117
131
  // --- pattern match: "com.apple.*" glob against a bundle id or app name. A missing bundle id or name is
118
- // never matched (review CR1/CR2 T6: an empty pattern matched every app without a bundle id) ---
132
+ // never matched (an empty pattern matched every app without a bundle id) ---
119
133
  function matches(pattern, bundleId, appName) {
120
134
  const p = String(pattern ?? "").trim();
121
135
  if (!p) return false;
@@ -123,9 +137,15 @@ function matches(pattern, bundleId, appName) {
123
137
  return (bundleId ? rx.test(String(bundleId)) : false) || (appName ? rx.test(String(appName)) : false);
124
138
  }
125
139
 
140
+ // a rule written as a bundle id ("com.apple.Terminal", "com.example.*"); anything else names apps by their name
141
+ const byBundle = (p) => /^[\w*?-]+(\.[\w*?-]+)+$/.test(String(p).trim());
142
+ const unnamed = (what) => ({ error: `input_denied: the name of the app that would receive the input could not be read, so ${what} cannot rule it out — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` });
143
+
126
144
  // --- approval file (opt-in). Returns { verdict: "allow"|"ask"|"deny", reason } or { error } (fail closed). ---
127
- export function evaluateApproval({ bundleId, appName } = {}) {
128
- // S4A-s11-4 / -Gemini-2: an app known by no name cannot be ruled out, and with a rule in force an app whose
145
+ // needName: the app has a name to read (a Mac app). Without one, a rule that names apps cannot rule it out, so the
146
+ // input is refused while such a rule is in force. An iOS app is matched on its bundle id alone (it has no name here).
147
+ export function evaluateApproval({ bundleId, appName, needName = false } = {}) {
148
+ // an app known by no name cannot be ruled out, and with a rule in force an app whose
129
149
  // bundle id is unknown cannot be ruled out by bundle-id patterns (server.mjs approveKnown already refuses
130
150
  // both; this keeps the module safe on its own)
131
151
  const bid = String(bundleId ?? "").trim(), name = String(appName ?? "").trim();
@@ -133,28 +153,42 @@ export function evaluateApproval({ bundleId, appName } = {}) {
133
153
  return { error: `input_denied: the app that would receive the input ${name ? `("${name}") has no readable bundle id, so the deny list / approval file cannot rule it out` : "could not be identified"} — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
134
154
  }
135
155
  const deny = denyList();
156
+ // how many entries at the head of the list the user wrote (NORACU_DENY_APPS): those always win. The rest is the
157
+ // default list, which an approval file can open for an app it names exactly
158
+ const userCount = deny.own !== undefined ? deny.own : /^NORACU_DENY_APPS/.test(deny.source) ? deny.list.length : 0;
159
+ let byDefault = null;
136
160
  // the trimmed bundle id and name are what every rule is matched against, as they are what was checked above
137
- // (audit S5A-s17-G-2: " com.apple.Terminal" was checked as known and then missed the deny list)
161
+ // (" com.apple.Terminal" was checked as known and then missed the deny list)
138
162
  for (const [i, d] of deny.list.entries()) if (matches(d, bid, name)) {
139
163
  // with a list of the user's own, say which of the two lists named the app
140
164
  const src = deny.own === undefined ? deny.source : i < deny.own ? "NORACU_DENY_APPS" : "the default deny list (terminal apps and IDEs with a terminal)";
141
- return { verdict: "deny", reason: `denied by ${src} ("${d}")` };
165
+ if (i < userCount) return { verdict: "deny", reason: `denied by ${src} ("${d}")` };
166
+ byDefault = { verdict: "deny", reason: `denied by ${src} ("${d}") — the person at the Mac can let this one app through by naming it exactly (no * or ?) under "allow" in an approval file (NORACU_APPROVAL_FILE)` };
167
+ break;
142
168
  }
169
+ // the default list names some apps by name (editions and forks whose bundle id differs)
170
+ if (needName && !name && !byDefault && deny.list.some((d) => !byBundle(d))) return unnamed("the deny list's entries that name apps");
143
171
  const file = process.env.NORACU_APPROVAL_FILE;
144
- if (file === undefined) return { verdict: "allow" };
172
+ if (file === undefined) return byDefault || { verdict: "allow" };
145
173
  if (!file.trim()) return { error: "approval_file_error: NORACU_APPROVAL_FILE is set but blank — remove it or give a path; nothing was sent (fail closed; delivery=not_delivered, retry=safe)" };
146
174
  let conf;
147
175
  let fd = null;
148
176
  try {
149
177
  // opened without following a symlink, and checked on the open descriptor (no swap between check and read)
150
178
  // O_NONBLOCK: a FIFO there would otherwise block the open, and the whole server with it, until something writes
151
- // to it (audit S5A-s17-G-4); the open descriptor is then refused as not a regular file
179
+ // to it; the open descriptor is then refused as not a regular file
152
180
  fd = openSync(file, fsc.O_RDONLY | fsc.O_NOFOLLOW | fsc.O_NONBLOCK);
153
181
  const st = fstatSync(fd);
154
182
  if (!st.isFile()) return { error: `approval_file_error: ${file} is not a regular file — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
155
183
  if (st.mode & 0o077) return { error: `approval_file_insecure: ${file} must be mode 0600 (is 0${(st.mode & 0o777).toString(8)}) — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
156
184
  if (st.uid !== process.getuid?.()) return { error: `approval_file_owner: ${file} is not owned by this user — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
157
- conf = JSON.parse(readFileSync(fd, "utf8"));
185
+ // a list of apps is small: a file over 64 KB is not read at all (it is read again before every input)
186
+ if (st.size > 65536) return { error: `approval_file_error: ${file} is larger than 64 KB — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
187
+ const text = readFileSync(fd, "utf8");
188
+ // JSON.parse's message quotes a piece of the file, and this answer goes to the agent: it is not passed on
189
+ try { conf = JSON.parse(text); } catch {
190
+ return { error: `approval_file_error: ${file} is not valid JSON — NORACU_APPROVAL_FILE is set, so nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
191
+ }
158
192
  } catch (e) {
159
193
  const why = e && e.code === "ENOENT" ? "does not exist" : e && e.code === "ELOOP" ? "is a symlink" : `is unreadable or not JSON (${e && e.code ? e.code : String(e).slice(0, 80)})`;
160
194
  return { error: `approval_file_error: ${file} ${why} — NORACU_APPROVAL_FILE is set, so nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
@@ -165,9 +199,16 @@ export function evaluateApproval({ bundleId, appName } = {}) {
165
199
  const unknown = Object.keys(conf).filter((k) => !["allow", "ask", "deny"].includes(k));
166
200
  if (unknown.length) return { error: `approval_file_error: ${file} has unknown key(s) ${unknown.slice(0, 3).map((k) => JSON.stringify(k)).join(", ")} — only "allow", "ask" and "deny"; nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
167
201
  for (const key of ["allow", "ask", "deny"]) if (conf[key] !== undefined && !Array.isArray(conf[key])) return { error: `approval_file_error: "${key}" must be an array — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
168
- // review CR1/CR2 T6: an empty or non-string pattern is a broken file, not a pattern
202
+ // an empty or non-string pattern is a broken file, not a pattern
169
203
  for (const key of ["allow", "ask", "deny"]) for (const p of conf[key] || []) if (typeof p !== "string" || !p.trim() || p.length > 200) return { error: `approval_file_error: "${key}" holds an empty or non-string pattern (${JSON.stringify(p)?.slice(0, 40)}) — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
204
+ if (needName && !name && [...(conf.deny || []), ...(conf.ask || [])].some((p) => !byBundle(p))) return unnamed(`the entries of ${file} that name apps`);
170
205
  for (const d of conf.deny || []) if (matches(d, bid, name)) return { verdict: "deny", reason: `denied by approval file ("${d}")` };
206
+ // on the default deny list: only an "allow" entry that names this app — its bundle id or its name, without a
207
+ // wildcard — lets it through; "*" or "com.example.*" in "allow" does not open a terminal
208
+ if (byDefault) {
209
+ for (const a of conf.allow || []) if (!/[*?]/.test(a) && matches(a, bid, name)) return { verdict: "allow", reason: `allowed by approval file ("${a}"), which names this app of the default deny list` };
210
+ return byDefault;
211
+ }
171
212
  for (const a of conf.ask || []) if (matches(a, bid, name)) {
172
213
  return { verdict: "ask", reason: `approval_required: "${bundleId || appName}" is listed under "ask" in ${file} — the person at the Mac must move it to "allow" (noracu never edits this file); nothing was sent (delivery=not_delivered, retry=safe)` };
173
214
  }
package/src/bg-inject.js CHANGED
@@ -12,7 +12,7 @@
12
12
  // bundle-id / name heuristic — a denylist, not a promise: unknown apps are tried.
13
13
  // • Only an answer that proves nothing was posted falls back to cliclick. A posted click is checked by
14
14
  // the caller (AX observe_after) and reported as it reads — never re-sent another way, since a click
15
- // that did land but changed nothing visible would then go out twice (review CR1/CR2 2026-11-09).
15
+ // that did land but changed nothing visible would then go out twice.
16
16
  // • Posted events reset HIDIdleTime like any other input; mac_* input jobs run under serializedInput,
17
17
  // whose drain() advances lastOwnInputEnd, so user_active does not mistake our own events for the
18
18
  // person's (server.mjs, 0.2.7 comment block).
@@ -23,7 +23,7 @@ export const BGPOST_DISABLED = process.env.NORACU_NO_BGPOST === "1";
23
23
 
24
24
  // Chromium / Electron / web-shell bundle ids (and app names, for hosts that report no bundle id).
25
25
  // Anything matching keeps the physical cliclick path even when bgpost is on.
26
- // S4A-s11-3 / -Gemini-5: Safari (WebKit) and Firefox take the cliclick path too — a pid-posted event they swallow
26
+ // Safari (WebKit) and Firefox take the cliclick path too — a pid-posted event they swallow
27
27
  // would still read as posted, and only a "nothing was posted" answer may fall back; Arc is company.thebrowser.*
28
28
  const WEB_ENGINE = /electron|chrome|chromium|brave|edge|arc\.|thebrowser|vivaldi|opera|safari|webkit|firefox|mozilla|discord|slack|vscode|code\.oss|notion|linear|spotify|figma|teams|zoom|feishu|lark|dingtalk|wecom|wechat|qq\.browser/i;
29
29
  export function bgCandidate(bundleId, appName) {
@@ -48,7 +48,7 @@ const MOD_FLAGS = { cmd: 1 << 20, shift: 1 << 17, alt: 1 << 19, ctrl: 1 << 18, f
48
48
  // Every event of a gesture is created before the first one is posted, so the "nothing was posted"
49
49
  // answers (bad-*, create-failed) are exact: only those may fall back to the cliclick pointer path.
50
50
  // A click carries its click state (1, 2, 3… — kCGMouseEventClickState, field 1): without it a double
51
- // click is two single clicks (review CR1/CR2 2026-11-09). The button number is 0 left, 1 right, 2 other
51
+ // click is two single clicks. The button number is 0 left, 1 right, 2 other
52
52
  // (middle); macOS reads it for the "other" event types only.
53
53
  export const BG_SCRIPT = `
54
54
  ObjC.import('CoreGraphics');
@@ -58,7 +58,7 @@ export const BG_SCRIPT = `
58
58
  ObjC.bindFunction('CGEventSetFlags', ['void', ['void*', 'uint64']]);
59
59
  ObjC.bindFunction('CGEventSetIntegerValueField', ['void', ['void*', 'int', 'int64']]);
60
60
  function run(argv) {
61
- // whole numbers in range only: pid_t is int32, and a fraction or a wrap would post to another process (S4A-s11-1)
61
+ // whole numbers in range only: pid_t is int32, and a fraction or a wrap would post to another process
62
62
  const pid = Number(argv[1]);
63
63
  if (!Number.isInteger(pid) || pid <= 0 || pid > 2147483647) return 'bad-pid';
64
64
  const src = $.CGEventSourceCreate($.kCGEventSourceStateHIDSystemState);
@@ -70,7 +70,7 @@ export const BG_SCRIPT = `
70
70
  const down = $.CGEventCreateKeyboardEvent(src, code, true);
71
71
  const up = $.CGEventCreateKeyboardEvent(src, code, false);
72
72
  if (!down || !up) return 'create-failed';
73
- // always set: 0 too, so a modifier someone holds on the keyboard does not ride along (cross-verification A0)
73
+ // always set: 0 too, so a modifier someone holds on the keyboard does not ride along
74
74
  $.CGEventSetFlags(down, flags); $.CGEventSetFlags(up, flags);
75
75
  events.push(down, up);
76
76
  } else if (argv[0] === 'click') {
@@ -87,7 +87,7 @@ export const BG_SCRIPT = `
87
87
  const down = $.CGEventCreateMouseEvent(src, dT, pt, btn);
88
88
  const up = $.CGEventCreateMouseEvent(src, uT, pt, btn);
89
89
  if (!down || !up) return 'create-failed';
90
- // no modifier rides along from the HID state the source was created from (S4A-s11-Gemini-3)
90
+ // no modifier rides along from the HID state the source was created from
91
91
  $.CGEventSetFlags(down, 0); $.CGEventSetFlags(up, 0);
92
92
  $.CGEventSetIntegerValueField(down, 1, i + 1);
93
93
  $.CGEventSetIntegerValueField(up, 1, i + 1);
@@ -103,7 +103,7 @@ const MOUSE = { left: { types: [1, 2], button: 0 }, right: { types: [3, 4], butt
103
103
  // answers that prove nothing was posted
104
104
  export const NOT_POSTED = new Set(["bad-pid", "bad-key", "bad-point", "bad-count", "bad-op", "create-failed"]);
105
105
 
106
- // S4A-s11-Gemini-1 / -2: null, "", false and fractions are not numbers here — Number(null) is 0, which is the A
106
+ // null, "", false and fractions are not numbers here — Number(null) is 0, which is the A
107
107
  // key, the pid of no process and the screen corner. A bad value goes out as "NaN" and the script answers bad-*.
108
108
  const num = (v) => (typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN);
109
109
  const intIn = (v, lo, hi) => { const n = num(v); return Number.isInteger(n) && n >= lo && n <= hi ? n : NaN; };
@@ -111,13 +111,13 @@ const intIn = (v, lo, hi) => { const n = num(v); return Number.isInteger(n) && n
111
111
  // The argv after `--` for one gesture (pure: the contract tests check it).
112
112
  export function keyArgv(pid, keyCode, mods = []) {
113
113
  let flags = 0;
114
- // an unknown modifier is a bad chord, not a bare key (S4A-s11-2)
114
+ // an unknown modifier is a bad chord, not a bare key
115
115
  for (const m of mods) { if (!Object.hasOwn(MOD_FLAGS, m)) { flags = NaN; break; } flags |= MOD_FLAGS[m]; }
116
116
  return ["key", intIn(pid, 1, 2147483647), intIn(keyCode, 0, 127), flags].map(String);
117
117
  }
118
118
  export function clickArgv(pid, x, y, { button = "left", count = 1 } = {}) {
119
119
  const m = MOUSE[button] || MOUSE.left;
120
- const c = intIn(count, 1, Number.MAX_SAFE_INTEGER); // 0 or a fraction is not one click (S4A-s11-2)
120
+ const c = intIn(count, 1, Number.MAX_SAFE_INTEGER); // 0 or a fraction is not one click
121
121
  return ["click", intIn(pid, 1, 2147483647), num(x), num(y), m.types[0], m.types[1], Number.isNaN(c) ? NaN : Math.min(c, 5), m.button].map(String);
122
122
  }
123
123
 
package/src/doctor.js ADDED
@@ -0,0 +1,156 @@
1
+ // `noracu doctor`, `noracu --help`, `noracu --version` — what a person at a terminal sees. None of this
2
+ // talks to an MCP client, and nothing is sent anywhere: it only reads this machine.
3
+ //
4
+ // doctor prints the client configuration with the absolute paths filled in (a GUI client does not inherit
5
+ // the shell's PATH, so `node` and the server both have to be named in full) and checks what the server
6
+ // needs around it. It cannot see the macOS permissions: those belong to the app that runs the server, and
7
+ // from a terminal only the terminal's own would show. The mac_status tool reports them from inside the client.
8
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
9
+ import { execFileSync } from "node:child_process";
10
+ import { fileURLToPath } from "node:url";
11
+ import { dirname, join, isAbsolute, resolve } from "node:path";
12
+
13
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
14
+ const SERVER = join(ROOT, "src", "server.mjs");
15
+ const VERSION = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")).version;
16
+ // Where Homebrew puts cliclick: /opt/homebrew on Apple silicon, /usr/local on an Intel Mac. Without NORACU_CLICLICK
17
+ // the server runs the first of these that exists (server.mjs CLICLICK); when neither does, the first is the one its
18
+ // "not found" answer names.
19
+ export const CLICLICK_PLACES = ["/opt/homebrew/bin/cliclick", "/usr/local/bin/cliclick"];
20
+ export function defaultCliclick(exists = existsSync) { return CLICLICK_PLACES.find((p) => exists(p)) || CLICLICK_PLACES[0]; }
21
+ const ISSUES = "https://github.com/sgInnora/noracu/issues/new/choose";
22
+ // the settings the server accepts (server.mjs LAYERS, PHONE_BACKEND); a value it would refuse or replace is not copied
23
+ // into a configuration
24
+ const LAYER_NAMES = ["mac", "browser", "iphone"];
25
+ const layersValid = (raw) => { const n = raw.trim().toLowerCase().split(",").map((x) => x.trim()).filter(Boolean); return n.length > 0 && n.every((x) => LAYER_NAMES.includes(x)); };
26
+ const backendValid = (raw) => ["mirror", "xcuitest"].includes(raw.trim().toLowerCase());
27
+
28
+ const run = (cmd, args) => { try { return execFileSync(cmd, args, { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { return null; } };
29
+ const shq = (s) => (/^[\w@%+:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
30
+
31
+ // The node to name in a client's configuration: this one, by a path that survives an upgrade where there is
32
+ // one. process.execPath is the versioned path under a package manager's cellar (it changes with every
33
+ // upgrade); the usual symlinks are preferred when they lead to this same binary, then `node` on PATH — unless
34
+ // that is a per-shell link of a version manager (under a temporary folder), which dies with the shell.
35
+ const EPHEMERAL = /^(?:\/private)?\/(?:tmp|var\/folders)\/|fnm_multishells/;
36
+ function stableNodePath() {
37
+ let real;
38
+ try { real = realpathSync(process.execPath); } catch { return process.execPath; }
39
+ for (const p of ["/opt/homebrew/bin/node", "/usr/local/bin/node", run("/usr/bin/which", ["node"])]) {
40
+ try { if (p && isAbsolute(p) && !EPHEMERAL.test(p) && realpathSync(p) === real) return p; } catch { /* not there */ }
41
+ }
42
+ return real;
43
+ }
44
+
45
+ export const HELP = `noracu ${VERSION} — a local MCP server: macOS apps and a browser by element index, plus iPhone (experimental).
46
+
47
+ It is started by an MCP client (Claude Desktop, Claude Code, Cursor), not by hand: it speaks JSON-RPC on stdin / stdout.
48
+
49
+ noracu the MCP server on stdio (what a client runs)
50
+ noracu doctor check this machine and print the client configuration with absolute paths
51
+ (also: noracu --doctor); exits 1 when something the server needs is missing
52
+ noracu doctor --json the same as JSON
53
+ noracu ios-setup … build the on-device runner of the XCUITest iPhone backend
54
+ noracu --version print the version
55
+
56
+ Documentation: https://github.com/sgInnora/noracu#readme
57
+ `;
58
+
59
+ // `sys` stands in for this machine in tests: its platform, whether a file exists, and where `which` finds cliclick.
60
+ export async function collect(env = process.env, sys = {}) {
61
+ const { platform = process.platform, exists = existsSync, whichCliclick = () => run("/usr/bin/which", ["cliclick"]) } = sys;
62
+ const nodeMajor = Number(process.versions.node.split(".")[0]);
63
+ const cliclickDefault = defaultCliclick(exists);
64
+ const cliclickPath = env.NORACU_CLICLICK ? resolve(env.NORACU_CLICLICK) : cliclickDefault;
65
+ const cliclickFound = exists(cliclickPath);
66
+ const onPath = cliclickFound ? null : whichCliclick();
67
+ const elsewhere = cliclickFound ? null : (CLICLICK_PLACES.find((p) => p !== cliclickPath && exists(p)) || (onPath && isAbsolute(onPath) && !EPHEMERAL.test(onPath) ? onPath : null));
68
+ let browser;
69
+ try {
70
+ const { chromium } = await import("playwright");
71
+ const path = chromium.executablePath();
72
+ browser = { installed: Boolean(path) && exists(path), path: path || null };
73
+ } catch (e) {
74
+ browser = { installed: false, path: null, error: String(e?.message || e).split("\n")[0].slice(0, 200) };
75
+ }
76
+ // What this shell has set is not what a GUI client starts the server with: a cliclick that is not at the
77
+ // server's default place, and layers asked for here, go into the configuration that is printed.
78
+ const cliclickUse = cliclickFound ? cliclickPath : elsewhere;
79
+ const layersSet = Boolean((env.NORACU_LAYERS || "").trim()), layersOk = !layersSet || layersValid(env.NORACU_LAYERS);
80
+ const backendSet = Boolean((env.NORACU_PHONE_BACKEND || "").trim()), backendOk = !backendSet || backendValid(env.NORACU_PHONE_BACKEND);
81
+ // the layers the server would run with: the ones set here when it accepts them (they go into the configuration
82
+ // below), else its default. macOS is needed by the Mac and iPhone layers, cliclick by the Mac layer only.
83
+ const layers = layersSet && layersOk ? env.NORACU_LAYERS.trim().toLowerCase().split(",").map((x) => x.trim()).filter(Boolean) : ["mac", "browser"];
84
+ const needsMacos = layers.includes("mac") || layers.includes("iphone"), needsCliclick = layers.includes("mac");
85
+ const serverEnvMap = {
86
+ ...(cliclickUse && cliclickUse !== cliclickDefault ? { NORACU_CLICLICK: cliclickUse } : {}),
87
+ ...(layersSet && layersOk ? { NORACU_LAYERS: env.NORACU_LAYERS.trim() } : {}),
88
+ ...(backendSet && backendOk ? { NORACU_PHONE_BACKEND: env.NORACU_PHONE_BACKEND.trim().toLowerCase() } : {}),
89
+ };
90
+ const serverEnv = Object.keys(serverEnvMap).length ? serverEnvMap : undefined;
91
+ const nodePath = stableNodePath();
92
+ const macos = platform === "darwin" ? run("/usr/bin/sw_vers", ["-productVersion"]) : null;
93
+ // what keeps the server from working as configured; any of these makes doctor exit 1. Playwright's Chromium is
94
+ // not one: the first browser_launch downloads it.
95
+ const problems = [
96
+ ...(nodeMajor >= 20 ? [] : ["node: Node 20 or later is needed"]),
97
+ ...(platform === "darwin" || !needsMacos ? [] : ["system: the Mac and iPhone layers need macOS"]),
98
+ ...(cliclickUse || !needsCliclick ? [] : ["cliclick: not found — brew install cliclick"]),
99
+ ...(layersOk ? [] : [`NORACU_LAYERS=${JSON.stringify(env.NORACU_LAYERS.slice(0, 40))}: not a comma-separated list of mac, browser, iphone — the server would not start; left out of the configuration`]),
100
+ ...(backendOk ? [] : [`NORACU_PHONE_BACKEND=${JSON.stringify(env.NORACU_PHONE_BACKEND.slice(0, 20))}: not mirror or xcuitest — left out of the configuration`]),
101
+ ];
102
+ // a line for a bug report: versions and what was found, no path and no user name
103
+ const report = `noracu ${VERSION} · node ${process.version} · ${platform === "darwin" ? `macOS ${macos || "?"}` : platform} ${process.arch} · cliclick ${cliclickUse ? "found" : "missing"} · Chromium ${browser.installed ? "installed" : "not installed"} · layers ${layersSet && layersOk ? env.NORACU_LAYERS.trim() : "mac,browser (default)"}${backendSet && backendOk ? ` · iPhone backend ${env.NORACU_PHONE_BACKEND.trim().toLowerCase()}` : ""}`;
104
+ return {
105
+ noracu: VERSION,
106
+ ok: problems.length === 0,
107
+ problems,
108
+ report,
109
+ node: { version: process.version, path: nodePath, exec_path: process.execPath, ok: nodeMajor >= 20 },
110
+ platform: { os: platform, arch: process.arch, macos, ok: platform === "darwin", needed: needsMacos },
111
+ server: { path: SERVER, in_npx_cache: /[\\/]_npx[\\/]/.test(SERVER) },
112
+ cliclick: { path: cliclickPath, found: cliclickFound, elsewhere, default: cliclickDefault, needed: needsCliclick },
113
+ browser,
114
+ layers: layersSet ? env.NORACU_LAYERS.trim() : "mac,browser (default)",
115
+ config: { mcpServers: { noracu: { command: nodePath, args: [SERVER], ...(serverEnv ? { env: serverEnv } : {}) } } },
116
+ claude_code: `claude mcp add -s user noracu ${Object.entries(serverEnv || {}).map(([k, v]) => `-e ${k}=${shq(v)} `).join("")}-- ${shq(nodePath)} ${shq(SERVER)}`,
117
+ };
118
+ }
119
+
120
+ export function render(d) {
121
+ const row = (name, value, note) => ` ${name.padEnd(10)}${value}${note ? `\n ${" ".repeat(10)}${note}` : ""}`;
122
+ const out = [`noracu ${d.noracu} — setup check. Nothing is sent anywhere; this only reads this machine.`, ""];
123
+ out.push(row("node", `${d.node.version} at ${d.node.path}`, d.node.ok ? "" : "needs Node 20 or later"));
124
+ out.push(row("system", d.platform.ok ? `macOS ${d.platform.macos || "(version unknown)"} (${d.platform.arch})` : `${d.platform.os} (${d.platform.arch})`,
125
+ d.platform.ok ? "" : d.platform.needed === false ? "NORACU_LAYERS=browser: the browser layer does not need macOS" : "the Mac and iPhone layers need macOS; start the server with NORACU_LAYERS=browser to use the browser layer alone"));
126
+ out.push(row("cliclick", d.cliclick.found ? d.cliclick.path : `not at ${d.cliclick.path}`,
127
+ d.cliclick.found ? (d.cliclick.path !== d.cliclick.default ? "not where the server looks by default — the configuration below passes it as NORACU_CLICLICK" : "") : d.cliclick.elsewhere ? (d.cliclick.elsewhere === d.cliclick.default ? `found at ${d.cliclick.elsewhere}, where the server looks by default — the configuration below leaves NORACU_CLICLICK out` : `found at ${d.cliclick.elsewhere} — the configuration below passes it as NORACU_CLICLICK`) : d.cliclick.needed === false ? "not needed: NORACU_LAYERS leaves the Mac layer out" : "physical Mac input needs it (mac_key, mac_drag, physical clicks and typing): brew install cliclick. Reading and semantic actions work without it."));
128
+ out.push(row("browser", d.browser.installed ? "Playwright's Chromium is installed" : "Playwright's Chromium is not installed yet",
129
+ d.browser.installed ? "" : d.browser.error ? `playwright could not be loaded: ${d.browser.error}` : "the first browser_launch downloads it (the one download noracu makes); or run: npx playwright install chromium"));
130
+ out.push(row("layers", d.layers, d.config.mcpServers.noracu.env?.NORACU_LAYERS ? "set in this shell — the configuration below passes it as NORACU_LAYERS" : d.problems.some((p) => p.startsWith("NORACU_LAYERS")) ? "not valid — the server would not start with it; the configuration below leaves it out" : "NORACU_LAYERS=mac,browser,iphone turns the experimental iPhone layer on"));
131
+ out.push(row("server", d.server.path, d.server.in_npx_cache ? "this copy is in npx's cache, which npm may clear: for a client configuration that keeps working, install it in a folder you keep (npm install noracu) and run doctor from there" : ""));
132
+ out.push("", "macOS permissions (Accessibility, Screen Recording) are granted to the app that runs noracu — Claude Desktop,",
133
+ "Cursor, or your terminal for Claude Code — not to node, and they apply after that app is quit and reopened.",
134
+ "This check cannot see them from here: once the client is set up, ask it to call mac_status.", "",
135
+ "Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json) and Cursor (~/.cursor/mcp.json):", "",
136
+ JSON.stringify(d.config, null, 2), "", "Claude Code (for every project of yours; drop `-s user` to add it to the current project only):", "", ` ${d.claude_code}`, "");
137
+ out.push(d.ok ? "Nothing is missing." : `Missing or not valid (exit code 1):\n${d.problems.map((p) => ` - ${p}`).join("\n")}`, "",
138
+ `Something does not work? Open an issue at ${ISSUES} with the tool, the steps, and this line (it holds no path or user name):`, "", ` ${d.report}`, "");
139
+ return out.join("\n");
140
+ }
141
+
142
+ // argv: what follows `noracu` on the command line. Returns the exit code.
143
+ export async function cli(argv) {
144
+ const [cmd, ...rest] = argv;
145
+ if (cmd === "--version") { process.stdout.write(`${VERSION}\n`); return 0; }
146
+ if (cmd === "--help") { process.stdout.write(HELP); return 0; }
147
+ if (cmd === "doctor" || cmd === "--doctor") {
148
+ const unknown = rest.filter((a) => a !== "--json");
149
+ if (unknown.length) { process.stderr.write(`noracu doctor: unknown option ${unknown[0]} (the only option is --json)\n`); return 2; }
150
+ const d = await collect();
151
+ process.stdout.write(rest.includes("--json") ? `${JSON.stringify(d, null, 2)}\n` : render(d));
152
+ return d.ok ? 0 : 1;
153
+ }
154
+ process.stderr.write(`noracu: unknown command ${cmd}\n\n${HELP}`);
155
+ return 2;
156
+ }