noracu 0.2.6 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +489 -0
- package/README.md +75 -16
- package/README.zh-CN.md +75 -16
- package/SECURITY.md +31 -11
- package/docs/architecture.md +24 -5
- package/docs/ios-runner-protocol.md +156 -0
- package/docs/tools.md +36 -19
- package/docs/usage.md +98 -5
- package/imctl/pyproject.toml +1 -1
- package/imctl/src/imctl/__init__.py +1 -1
- package/imctl/src/imctl/cli.py +315 -23
- package/imctl/src/imctl/gestures.py +169 -13
- package/imctl/src/imctl/input.py +112 -23
- package/imctl/src/imctl/pointer.py +81 -0
- package/imctl/src/imctl/screenrect.py +167 -0
- package/imctl/src/imctl/verify.py +68 -4
- package/imctl/src/imctl/window.py +39 -6
- package/ios-runner/LICENSE +21 -0
- package/ios-runner/NoracuRunner.xcodeproj/project.pbxproj +228 -0
- package/ios-runner/NoracuRunner.xcodeproj/xcshareddata/xcschemes/NoracuRunner.xcscheme +69 -0
- package/ios-runner/NoracuRunnerUITests/NoracuRunner.swift +172 -0
- package/ios-runner/NoracuRunnerUITests/RunnerCommands.swift +567 -0
- package/ios-runner/NoracuRunnerUITests/RunnerServer.swift +187 -0
- package/ios-runner/README.md +59 -0
- package/package.json +12 -6
- package/src/approval.js +177 -0
- package/src/bg-inject.js +154 -0
- package/src/ios-session.js +650 -0
- package/src/ios-setup.js +155 -0
- package/src/ios-xcuitest.js +373 -0
- package/src/mac-ax.js +22 -5
- package/src/server.mjs +1375 -173
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// RunnerServer.swift — TCP line server for protocol v1: framing, token check, peer filter,
|
|
3
|
+
// and dispatch of one command at a time onto the main thread. MIT licensed, see LICENSE.
|
|
4
|
+
|
|
5
|
+
import Foundation
|
|
6
|
+
import Network
|
|
7
|
+
|
|
8
|
+
final class RunnerServer: @unchecked Sendable {
|
|
9
|
+
let box: RunnerBox
|
|
10
|
+
private let queue = DispatchQueue(label: "noracu.runner.conn")
|
|
11
|
+
|
|
12
|
+
init(box: RunnerBox) { self.box = box }
|
|
13
|
+
|
|
14
|
+
func accept(_ conn: NWConnection) {
|
|
15
|
+
var reading = false // touched on `queue` only
|
|
16
|
+
conn.stateUpdateHandler = { [weak self] st in
|
|
17
|
+
guard let self else { return }
|
|
18
|
+
if case .ready = st {
|
|
19
|
+
// fail-closed peer check, before the first byte is read: an endpoint that is missing,
|
|
20
|
+
// not a hostPort, or outside the allowed range closes the connection at once
|
|
21
|
+
if !self.peerAllowed(conn.endpoint) {
|
|
22
|
+
conn.cancel()
|
|
23
|
+
return
|
|
24
|
+
}
|
|
25
|
+
if !reading { reading = true; self.serve(conn, Data()) }
|
|
26
|
+
}
|
|
27
|
+
if case .failed = st { conn.cancel() }
|
|
28
|
+
}
|
|
29
|
+
conn.start(queue: queue)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
private func peerAllowed(_ ep: NWEndpoint) -> Bool {
|
|
33
|
+
guard case let .hostPort(host, _) = ep else { return false }
|
|
34
|
+
if case let .ipv4(v4) = host {
|
|
35
|
+
return box.isLoopbackBind && v4.rawValue[0] == 127
|
|
36
|
+
}
|
|
37
|
+
if case let .ipv6(v6) = host {
|
|
38
|
+
if box.isLoopbackBind { return v6.isLoopback }
|
|
39
|
+
if let bind6 = box.bindIPv6 {
|
|
40
|
+
return samePrefix64(v6, bind6)
|
|
41
|
+
}
|
|
42
|
+
return false
|
|
43
|
+
}
|
|
44
|
+
return false
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private func samePrefix64(_ a: IPv6Address, _ b: IPv6Address) -> Bool {
|
|
48
|
+
let x = a.rawValue, y = b.rawValue
|
|
49
|
+
guard x.count == 16, y.count == 16 else { return false }
|
|
50
|
+
for i in 0..<8 where x[i] != y[i] { return false }
|
|
51
|
+
return true
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
private func serve(_ conn: NWConnection, _ buf: Data) {
|
|
55
|
+
conn.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, _, isComplete, error in
|
|
56
|
+
guard let self else { return }
|
|
57
|
+
var b = buf
|
|
58
|
+
if let d = data { b.append(d) }
|
|
59
|
+
// a single line over 64 KiB closes the connection: only when the
|
|
60
|
+
// first 64 KiB of the buffer hold no newline. Multiple complete
|
|
61
|
+
// short lines accumulating past 64 KiB are fine.
|
|
62
|
+
if let nl = b.firstIndex(of: 0x0A) {
|
|
63
|
+
if b.distance(from: b.startIndex, to: nl) > 65536 {
|
|
64
|
+
conn.cancel()
|
|
65
|
+
return
|
|
66
|
+
}
|
|
67
|
+
} else if b.count > 65536 {
|
|
68
|
+
conn.cancel()
|
|
69
|
+
return
|
|
70
|
+
}
|
|
71
|
+
while let nl = b.firstIndex(of: 0x0A) {
|
|
72
|
+
let raw = b[b.startIndex..<nl]
|
|
73
|
+
b = Data(b[b.index(after: nl)...])
|
|
74
|
+
guard let line = String(data: Data(raw), encoding: .utf8) else {
|
|
75
|
+
conn.cancel()
|
|
76
|
+
return
|
|
77
|
+
}
|
|
78
|
+
// an auth failure or a quit ends this connection: what follows it in the buffer is not read
|
|
79
|
+
if !self.handleLine(line, conn) { return }
|
|
80
|
+
if self.box.done { conn.cancel(); return }
|
|
81
|
+
if conn.state == .cancelled { return }
|
|
82
|
+
}
|
|
83
|
+
if isComplete || error != nil { conn.cancel(); return }
|
|
84
|
+
self.serve(conn, b)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private func handleLine(_ line: String, _ conn: NWConnection) -> Bool {
|
|
89
|
+
// Before the token check passes, reply only "auth" — malformed JSON or
|
|
90
|
+
// a missing token field is treated as an auth failure.
|
|
91
|
+
guard let data = line.data(using: .utf8),
|
|
92
|
+
let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
|
93
|
+
let token = obj["token"] as? String else {
|
|
94
|
+
sendThenClose(conn, ["id": 0, "ok": false, "error": "auth"])
|
|
95
|
+
return false
|
|
96
|
+
}
|
|
97
|
+
let id = obj["id"].flatMap { RunnerCommands.isBool($0) ? nil : ($0 as? Int) } ?? 0
|
|
98
|
+
if !constantTimeEqual(token, box.token) {
|
|
99
|
+
sendThenClose(conn, ["id": id, "ok": false, "error": "auth"])
|
|
100
|
+
return false
|
|
101
|
+
}
|
|
102
|
+
guard let rawId = obj["id"], !RunnerCommands.isBool(rawId), rawId is Int else {
|
|
103
|
+
// a missing id, or one that is not a whole number, cannot be matched to its request: the command is not
|
|
104
|
+
// run (pre-review P3 and P4)
|
|
105
|
+
var no = RunnerCommands.fail(0, "invalid_args", "id must be a whole number", sent: RunnerCommands.inputOps.contains(obj["op"] as? String ?? "") ? false : nil)
|
|
106
|
+
no["id"] = 0
|
|
107
|
+
send(conn, no)
|
|
108
|
+
return true
|
|
109
|
+
}
|
|
110
|
+
DispatchQueue.main.async { self.box.served += 1 }
|
|
111
|
+
let op = obj["op"] as? String ?? ""
|
|
112
|
+
if op == "quit" {
|
|
113
|
+
sendQuitReply(conn, id: id)
|
|
114
|
+
return false
|
|
115
|
+
}
|
|
116
|
+
let input = RunnerCommands.inputOps.contains(op)
|
|
117
|
+
if let rawArgs = obj["args"], !(rawArgs is [String: Any]) {
|
|
118
|
+
var no = RunnerCommands.fail(0, "invalid_args", "args must be an object", sent: input ? false : nil)
|
|
119
|
+
no["id"] = id
|
|
120
|
+
send(conn, no)
|
|
121
|
+
return true
|
|
122
|
+
}
|
|
123
|
+
let args = obj["args"] as? [String: Any] ?? [:]
|
|
124
|
+
let reply = DispatchQueue.main.sync { () -> [String: Any] in
|
|
125
|
+
MainActor.assumeIsolated {
|
|
126
|
+
// A failure XCTest recorded between two commands belongs to one that has already answered:
|
|
127
|
+
// this command is not run, and says why. (ping stays a plain sign of life.)
|
|
128
|
+
if op != "ping", self.box.issueCount > self.box.issuesAnswered {
|
|
129
|
+
self.box.issuesAnswered = self.box.issueCount
|
|
130
|
+
return RunnerCommands.fail(0, "xctest_issue", "recorded after an earlier command had answered: " + self.box.lastIssue, sent: input ? false : nil)
|
|
131
|
+
}
|
|
132
|
+
let r = RunnerCommands.dispatch(op: op, args: args, box: self.box)
|
|
133
|
+
guard op != "ping", self.box.issueCount > self.box.issuesAnswered else { return r }
|
|
134
|
+
self.box.issuesAnswered = self.box.issueCount
|
|
135
|
+
// XCTest recorded a failure during the call and carried on (continueAfterFailure): whatever the
|
|
136
|
+
// command answered, it did not do what that says. Only a refusal that sent nothing stays "not sent".
|
|
137
|
+
let nothingSent = (r["ok"] as? Bool) == false && (r["sent"] as? Bool) == false
|
|
138
|
+
return RunnerCommands.fail(0, "xctest_issue", self.box.lastIssue, sent: input ? (nothingSent ? false : "unknown") : nil)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
var stamped = reply
|
|
142
|
+
stamped["id"] = id
|
|
143
|
+
send(conn, stamped)
|
|
144
|
+
return true
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private func send(_ conn: NWConnection, _ obj: [String: Any]) {
|
|
148
|
+
guard let data = try? JSONSerialization.data(withJSONObject: obj, options: [.sortedKeys]) else { return }
|
|
149
|
+
var payload = data
|
|
150
|
+
payload.append(0x0A)
|
|
151
|
+
conn.send(content: payload, completion: .contentProcessed { _ in })
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// auth failure: the reply must actually go out before the connection closes
|
|
155
|
+
private func sendThenClose(_ conn: NWConnection, _ obj: [String: Any]) {
|
|
156
|
+
guard let data = try? JSONSerialization.data(withJSONObject: obj, options: [.sortedKeys]) else {
|
|
157
|
+
conn.cancel()
|
|
158
|
+
return
|
|
159
|
+
}
|
|
160
|
+
var payload = data
|
|
161
|
+
payload.append(0x0A)
|
|
162
|
+
conn.send(content: payload, completion: .contentProcessed { _ in conn.cancel() })
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// quit: send the reply, then close the connection and end the test only
|
|
166
|
+
// after the reply has actually gone out.
|
|
167
|
+
private func sendQuitReply(_ conn: NWConnection, id: Int) {
|
|
168
|
+
guard let data = try? JSONSerialization.data(withJSONObject: ["id": id, "ok": true, "result": [:]], options: [.sortedKeys]) else {
|
|
169
|
+
conn.cancel()
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
var payload = data
|
|
173
|
+
payload.append(0x0A)
|
|
174
|
+
conn.send(content: payload, completion: .contentProcessed { [weak self] _ in
|
|
175
|
+
conn.cancel()
|
|
176
|
+
DispatchQueue.main.async { self?.box.done = true }
|
|
177
|
+
})
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
private func constantTimeEqual(_ a: String, _ b: String) -> Bool {
|
|
181
|
+
let ab = Array(a.utf8), bb = Array(b.utf8)
|
|
182
|
+
if ab.count != bb.count { return false }
|
|
183
|
+
var diff: UInt8 = 0
|
|
184
|
+
for i in 0..<ab.count { diff |= ab[i] ^ bb[i] }
|
|
185
|
+
return diff == 0
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
<!-- SPDX-License-Identifier: MIT -->
|
|
2
|
+
# NoracuRunner — iOS runner for the XCUITest backend (protocol v1)
|
|
3
|
+
|
|
4
|
+
A minimal Xcode project that builds a single **UI test bundle** (no host app).
|
|
5
|
+
One long test (`NoracuRunnerUITests/NoracuRunner.swift`, method `testServe`) starts a
|
|
6
|
+
TCP line server on the address it is given and executes JSON commands, one per line,
|
|
7
|
+
on the main thread. The Mac side launches apps (`devicectl` / `simctl`) and talks to
|
|
8
|
+
this runner over the CoreDevice tunnel (device) or loopback (simulator).
|
|
9
|
+
|
|
10
|
+
## Build
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
xcodebuild build-for-testing -project ios-runner/NoracuRunner.xcodeproj -scheme NoracuRunner \
|
|
14
|
+
-destination 'platform=iOS Simulator,id=<SIM_UDID>' -derivedDataPath /tmp/noracu-dd CODE_SIGNING_ALLOWED=NO
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
For a real device add `DEVELOPMENT_TEAM=<team> -allowProvisioningUpdates`
|
|
18
|
+
(the project itself leaves `DEVELOPMENT_TEAM` empty).
|
|
19
|
+
|
|
20
|
+
## Run
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
TEST_RUNNER_NORACU_TOKEN=<32 lowercase hex> TEST_RUNNER_NORACU_BIND=<ip> TEST_RUNNER_NORACU_PORT=<49152-65535> \
|
|
24
|
+
xcodebuild test-without-building -project ios-runner/NoracuRunner.xcodeproj -scheme NoracuRunner \
|
|
25
|
+
-destination '<destination>' -derivedDataPath /tmp/noracu-dd \
|
|
26
|
+
-only-testing:NoracuRunnerUITests/NoracuRunner/testServe
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The runner prints `NORACU_RUNNER ready v=1 port=<port> build=<hash of these sources>` on
|
|
30
|
+
its own line when the listener is up (after a change here run `node scripts/gen-runner-build.mjs`), and `NORACU_RUNNER error bad_token|bad_bind|bad_port|bind_failed`
|
|
31
|
+
on invalid start-up values. It ends on `quit` or after 12 hours.
|
|
32
|
+
|
|
33
|
+
## Protocol
|
|
34
|
+
|
|
35
|
+
UTF-8, one JSON object per line, request lines limited to 64 KiB.
|
|
36
|
+
Request `{"id":n,"token":"<hex>","op":"...","args":{...}}`; success
|
|
37
|
+
`{"id":n,"ok":true,"result":{...}}`; failure `{"id":n,"ok":false,"error":"<code>",
|
|
38
|
+
"message":"...","sent":false}`. Wrong token → `{"id":n,"ok":false,"error":"auth"}`
|
|
39
|
+
and the connection is closed (constant-time compare). Commands: `ping`, `app_state`,
|
|
40
|
+
`snapshot`, `tap`, `press`, `drag`, `type`, `keys`, `home`, `screenshot`, `quit`.
|
|
41
|
+
Coordinates are screen points, origin top-left. See `docs/ios-runner-protocol.md`
|
|
42
|
+
in the repository root for the full specification.
|
|
43
|
+
|
|
44
|
+
## Security notes
|
|
45
|
+
|
|
46
|
+
- The listener binds **only** the address given in `NORACU_BIND` (via
|
|
47
|
+
`NWParameters.requiredLocalEndpoint`). Connections are accepted only from the
|
|
48
|
+
same /64 (IPv6) or loopback; everything else is closed immediately.
|
|
49
|
+
- A per-start token (32 hex chars, passed as a test-runner environment variable)
|
|
50
|
+
is required on every request and compared in constant time.
|
|
51
|
+
- The runner uses only public APIs (XCTest / XCUIAutomation / Network / Foundation),
|
|
52
|
+
never touches the clipboard, never reads or writes files outside the test sandbox,
|
|
53
|
+
and makes no outbound connections.
|
|
54
|
+
- The runner never launches or activates apps itself (launching is the Mac side's
|
|
55
|
+
job via `devicectl`), never retries a gesture, and never taps on its own initiative.
|
|
56
|
+
|
|
57
|
+
## License
|
|
58
|
+
|
|
59
|
+
MIT — see `LICENSE` (same as the repository root).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "noracu",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"mcpName": "io.github.sgInnora/noracu",
|
|
5
5
|
"description": "Local MCP server: macOS apps and a browser by element index, plus iPhone Mirroring (experimental).",
|
|
6
6
|
"type": "module",
|
|
@@ -10,11 +10,11 @@
|
|
|
10
10
|
},
|
|
11
11
|
"scripts": {
|
|
12
12
|
"start": "node src/server.mjs",
|
|
13
|
-
"test": "node test/engine-unit.mjs && node test/e2e.mjs",
|
|
14
|
-
"test:ci": "node test/engine-unit.mjs && NORACU_CI=1 node test/e2e.mjs",
|
|
13
|
+
"test": "node test/engine-unit.mjs && node test/bg-inject-unit.mjs && node test/release-gate-unit.mjs && node test/ios-xcuitest-unit.mjs && node test/ios-session-unit.mjs && node test/ios-setup-unit.mjs && node test/ios-e2e.mjs && node test/e2e.mjs",
|
|
14
|
+
"test:ci": "node test/engine-unit.mjs && node test/bg-inject-unit.mjs && node test/release-gate-unit.mjs && node test/ios-xcuitest-unit.mjs && node test/ios-session-unit.mjs && node test/ios-setup-unit.mjs && node test/ios-e2e.mjs && NORACU_CI=1 node test/e2e.mjs",
|
|
15
15
|
"test:imctl": "cd imctl && ${NORACU_PYTHON:-python3} tests/test_smoke.py",
|
|
16
|
-
"check": "node --check src/server.mjs && node --check src/mac-ax.js && node --check scripts/gen-tools.mjs && python3 -c \"import ast,sys; [ast.parse(open(f).read(), f) for f in sys.argv[1:]]\" imctl/src/imctl/*.py",
|
|
17
|
-
"prepublishOnly": "npm run check && node scripts/check-pack.mjs && node scripts/gen-tools.mjs && git diff --exit-code docs/tools.md"
|
|
16
|
+
"check": "node --check src/server.mjs && node --check src/mac-ax.js && node --check src/approval.js && node --check src/bg-inject.js && node --check src/ios-xcuitest.js && node --check src/ios-session.js && node --check src/ios-setup.js && node --check scripts/gen-tools.mjs && node --check scripts/release-gate.mjs && python3 -c \"import ast,sys; [ast.parse(open(f).read(), f) for f in sys.argv[1:]]\" imctl/src/imctl/*.py",
|
|
17
|
+
"prepublishOnly": "npm run check && node scripts/release-gate.mjs && node scripts/check-pack.mjs && node scripts/gen-tools.mjs && git diff --exit-code docs/tools.md"
|
|
18
18
|
},
|
|
19
19
|
"engines": {
|
|
20
20
|
"node": ">=20"
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
],
|
|
38
38
|
"license": "MIT",
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"playwright": "
|
|
40
|
+
"playwright": "~1.65.1"
|
|
41
41
|
},
|
|
42
42
|
"repository": {
|
|
43
43
|
"type": "git",
|
|
@@ -58,6 +58,12 @@
|
|
|
58
58
|
"LICENSE",
|
|
59
59
|
"CHANGELOG.md",
|
|
60
60
|
"SECURITY.md",
|
|
61
|
+
"docs/ios-runner-protocol.md",
|
|
62
|
+
"ios-runner/README.md",
|
|
63
|
+
"ios-runner/LICENSE",
|
|
64
|
+
"ios-runner/NoracuRunner.xcodeproj/project.pbxproj",
|
|
65
|
+
"ios-runner/NoracuRunner.xcodeproj/xcshareddata/xcschemes/NoracuRunner.xcscheme",
|
|
66
|
+
"ios-runner/NoracuRunnerUITests/*.swift",
|
|
61
67
|
"imctl/README.md",
|
|
62
68
|
"imctl/LICENSE",
|
|
63
69
|
"imctl/pyproject.toml",
|
package/src/approval.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// approval — stateless per-call input gate (0.3.0).
|
|
2
|
+
//
|
|
3
|
+
// noracu is a stdio MCP server — one client, one process — so there are no leases: every input call is
|
|
4
|
+
// checked on its own, on the app that receives the input (server.mjs approveTarget).
|
|
5
|
+
//
|
|
6
|
+
// • NORACU_APPROVAL_FILE (opt-in): JSON { "allow": ["bundle.id.*"], "ask": [...], "deny": [...] }.
|
|
7
|
+
// Patterns match a bundle id or an app name (exact, or with * and ? wildcards). "ask" returns
|
|
8
|
+
// approval_required — the person at the Mac edits the file to allow; noracu itself never writes it
|
|
9
|
+
// (an agent must not be able to grant itself always-allow). Once the variable is set, a missing,
|
|
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).
|
|
13
|
+
// • NORACU_DENY_APPS: comma-separated bundle ids / app names that never get input, on top of the default
|
|
14
|
+
// list — the terminal apps and the IDEs with a built-in terminal below, plus the terminal hosting this
|
|
15
|
+
// server when the PPID chain shows one that is not on the list — so an agent cannot type into a shell.
|
|
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
|
|
18
|
+
// silently let input into Terminal again. The PPID
|
|
19
|
+
// chain stops at launchd (a tmux or screen session started elsewhere, npx under a GUI host): then only
|
|
20
|
+
// the listed terminals apply.
|
|
21
|
+
// • NORACU_STOP_FILE: while this file exists, every input tool returns user_stopped and sends
|
|
22
|
+
// nothing. stat errors other than ENOENT fail closed.
|
|
23
|
+
// • A variable that is set but blank (NORACU_APPROVAL_FILE= or NORACU_STOP_FILE=, e.g. an unfilled
|
|
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).
|
|
26
|
+
|
|
27
|
+
import { readFileSync, statSync, openSync, fstatSync, closeSync, constants as fsc } from "node:fs";
|
|
28
|
+
import { execFileSync } from "node:child_process";
|
|
29
|
+
|
|
30
|
+
// Terminal apps by bundle id, and how their executable path looks in ps (review CR1/CR2 T6: iTerm2,
|
|
31
|
+
// wezterm-gui, Ghostty and Warp were missed, and the walk stopped at tmux/screen)
|
|
32
|
+
const TERMINALS = [
|
|
33
|
+
{ bundle: "com.apple.Terminal", path: /\/Terminal\.app\//i },
|
|
34
|
+
{ bundle: "com.googlecode.iterm2", path: /\/iTerm2?\.app\//i },
|
|
35
|
+
{ bundle: "com.github.wez.wezterm", path: /\/WezTerm\.app\/|\/wezterm(-gui)?$/i },
|
|
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)
|
|
38
|
+
{ bundle: "org.alacritty", path: /\/Alacritty\.app\/|\/alacritty$/i },
|
|
39
|
+
{ bundle: "net.kovidgoyal.kitty", path: /\/kitty\.app\/|\/kitty$/i },
|
|
40
|
+
{ bundle: "co.zeit.hyper", path: /\/Hyper\.app\//i },
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
// --- host terminal (resolved once): the first ancestor that is a terminal app; tmux / screen are walked
|
|
44
|
+
// through. Returns { bundle } for a listed terminal, { name } for another app bundle named like a terminal,
|
|
45
|
+
// or null (chain broken, no terminal found).
|
|
46
|
+
function hostTerminal() {
|
|
47
|
+
try {
|
|
48
|
+
let pid = process.ppid;
|
|
49
|
+
for (let i = 0; i < 12 && pid > 1; i++) {
|
|
50
|
+
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] };
|
|
55
|
+
// anything else — a shell, node, npm, tmux, screen — is walked through to its parent
|
|
56
|
+
const ppidLine = execFileSync("/bin/ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf8", timeout: 2000 }).trim();
|
|
57
|
+
pid = Number(ppidLine);
|
|
58
|
+
if (!Number.isFinite(pid) || pid <= 1) break;
|
|
59
|
+
}
|
|
60
|
+
} catch { /* chain broken — only the listed terminals apply */ }
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
const HOST_TERMINAL = hostTerminal();
|
|
64
|
+
|
|
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
|
|
69
|
+
// they get no input by default either. Bundle ids (VS Code and Cursor read from installed apps), and names,
|
|
70
|
+
// 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).
|
|
72
|
+
// 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).
|
|
74
|
+
const IDE_BUNDLES = [
|
|
75
|
+
"com.microsoft.VSCode*", "com.vscodium*",
|
|
76
|
+
"com.todesktop.230313mzl4w4u92", // Cursor
|
|
77
|
+
"com.exafunction.windsurf*", "dev.zed.Zed*",
|
|
78
|
+
"com.jetbrains.*", "com.google.android.studio*",
|
|
79
|
+
];
|
|
80
|
+
const IDE_NAMES = ["Code", "Visual Studio Code*", "Code - Insiders", "Code - Exploration", "VSCodium*", "Cursor*", "Windsurf*", "Zed*",
|
|
81
|
+
"IntelliJ IDEA*", "PyCharm*", "WebStorm*", "GoLand*", "CLion*", "RubyMine*", "PhpStorm*", "Rider*", "DataGrip*", "RustRover*", "Fleet", "Android Studio*"];
|
|
82
|
+
export function defaultDenyList() {
|
|
83
|
+
const list = [...TERMINALS.map((t) => t.bundle), ...TERMINAL_NAMES, ...IDE_BUNDLES, ...IDE_NAMES];
|
|
84
|
+
if (HOST_TERMINAL?.name && !list.some((l) => l.toLowerCase() === HOST_TERMINAL.name.toLowerCase())) list.push(HOST_TERMINAL.name);
|
|
85
|
+
return list;
|
|
86
|
+
}
|
|
87
|
+
// the deny list in force, and where it came from
|
|
88
|
+
export function denyList() {
|
|
89
|
+
const raw = process.env.NORACU_DENY_APPS;
|
|
90
|
+
const list = (raw || "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
91
|
+
if (list.length && list[0].toLowerCase() === "none") {
|
|
92
|
+
const own = list.slice(1);
|
|
93
|
+
return own.length ? { list: own, source: "NORACU_DENY_APPS (none: default list dropped)" } : { list: [], source: "NORACU_DENY_APPS=none" };
|
|
94
|
+
}
|
|
95
|
+
if (list.length) return { list: [...list, ...defaultDenyList()], own: list.length, source: "NORACU_DENY_APPS and the default deny list" };
|
|
96
|
+
return { list: defaultDenyList(), source: "the default deny list (terminal apps and IDEs with a terminal; NORACU_DENY_APPS unset)" };
|
|
97
|
+
}
|
|
98
|
+
// whether any approval rule is in force — then an app known only by name cannot be ruled out
|
|
99
|
+
export function gateActive() {
|
|
100
|
+
return denyList().list.length > 0 || process.env.NORACU_APPROVAL_FILE !== undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// --- stop file ---
|
|
104
|
+
export function stopFileBlocked() {
|
|
105
|
+
const p = process.env.NORACU_STOP_FILE;
|
|
106
|
+
if (p === undefined) return null;
|
|
107
|
+
if (!p.trim()) return "stop_check_error: NORACU_STOP_FILE is set but blank — remove it or give a path; nothing was sent (fail closed; delivery=not_delivered, retry=safe)";
|
|
108
|
+
try {
|
|
109
|
+
statSync(p);
|
|
110
|
+
return `user_stopped: ${p} exists — the person at the Mac stopped noracu's input; nothing was sent (delivery=not_delivered, retry=safe); remove the file to resume`;
|
|
111
|
+
} catch (e) {
|
|
112
|
+
if (e && e.code === "ENOENT") return null;
|
|
113
|
+
return `stop_check_error: could not check ${p} (${e && e.code ? e.code : "unknown"}) — nothing was sent (fail closed; delivery=not_delivered, retry=safe)`;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// --- 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) ---
|
|
119
|
+
function matches(pattern, bundleId, appName) {
|
|
120
|
+
const p = String(pattern ?? "").trim();
|
|
121
|
+
if (!p) return false;
|
|
122
|
+
const rx = new RegExp("^" + p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".") + "$", "i");
|
|
123
|
+
return (bundleId ? rx.test(String(bundleId)) : false) || (appName ? rx.test(String(appName)) : false);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// --- 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
|
|
129
|
+
// bundle id is unknown cannot be ruled out by bundle-id patterns (server.mjs approveKnown already refuses
|
|
130
|
+
// both; this keeps the module safe on its own)
|
|
131
|
+
const bid = String(bundleId ?? "").trim(), name = String(appName ?? "").trim();
|
|
132
|
+
if (!bid && (!name || gateActive())) {
|
|
133
|
+
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
|
+
}
|
|
135
|
+
const deny = denyList();
|
|
136
|
+
// 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)
|
|
138
|
+
for (const [i, d] of deny.list.entries()) if (matches(d, bid, name)) {
|
|
139
|
+
// with a list of the user's own, say which of the two lists named the app
|
|
140
|
+
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}")` };
|
|
142
|
+
}
|
|
143
|
+
const file = process.env.NORACU_APPROVAL_FILE;
|
|
144
|
+
if (file === undefined) return { verdict: "allow" };
|
|
145
|
+
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
|
+
let conf;
|
|
147
|
+
let fd = null;
|
|
148
|
+
try {
|
|
149
|
+
// opened without following a symlink, and checked on the open descriptor (no swap between check and read)
|
|
150
|
+
// 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
|
|
152
|
+
fd = openSync(file, fsc.O_RDONLY | fsc.O_NOFOLLOW | fsc.O_NONBLOCK);
|
|
153
|
+
const st = fstatSync(fd);
|
|
154
|
+
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
|
+
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
|
+
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"));
|
|
158
|
+
} catch (e) {
|
|
159
|
+
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
|
+
return { error: `approval_file_error: ${file} ${why} — NORACU_APPROVAL_FILE is set, so nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
|
|
161
|
+
} finally {
|
|
162
|
+
if (fd !== null) try { closeSync(fd); } catch { /* already closed */ }
|
|
163
|
+
}
|
|
164
|
+
if (!conf || typeof conf !== "object" || Array.isArray(conf)) return { error: `approval_file_error: ${file} must hold a JSON object — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
|
|
165
|
+
const unknown = Object.keys(conf).filter((k) => !["allow", "ask", "deny"].includes(k));
|
|
166
|
+
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
|
+
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
|
|
169
|
+
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)` };
|
|
170
|
+
for (const d of conf.deny || []) if (matches(d, bid, name)) return { verdict: "deny", reason: `denied by approval file ("${d}")` };
|
|
171
|
+
for (const a of conf.ask || []) if (matches(a, bid, name)) {
|
|
172
|
+
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
|
+
}
|
|
174
|
+
for (const a of conf.allow || []) if (matches(a, bid, name)) return { verdict: "allow", reason: `allowed by approval file ("${a}")` };
|
|
175
|
+
// nothing matched: ask (an approval file that lists apps but not this one means "ask")
|
|
176
|
+
return { verdict: "ask", reason: `approval_required: ${file} lists apps but not "${bundleId || appName}" — add it to "allow" or "deny"; nothing was sent (delivery=not_delivered, retry=safe)` };
|
|
177
|
+
}
|
package/src/bg-inject.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// bg-inject — background targeted input via CGEventPostToPid (0.3.0).
|
|
2
|
+
//
|
|
3
|
+
// Events are posted straight to a pid: the real pointer never moves, the target app need not be
|
|
4
|
+
// frontmost, and the person at the Mac sees nothing. Everything runs in ONE osascript invocation per
|
|
5
|
+
// gesture: CF event objects must stay inside a single ObjC call chain, and each osascript spawn costs
|
|
6
|
+
// 50–200 ms.
|
|
7
|
+
//
|
|
8
|
+
// Scope guards:
|
|
9
|
+
// • NORACU_NO_BGPOST=1 turns the whole layer off (cliclick as in 0.2.7).
|
|
10
|
+
// • Web-engine apps (Chromium/Electron renderers) keep the cliclick path: their event loops check
|
|
11
|
+
// key-window state and the pointer location, so pid-posted events often do not land. Detection is a
|
|
12
|
+
// bundle-id / name heuristic — a denylist, not a promise: unknown apps are tried.
|
|
13
|
+
// • Only an answer that proves nothing was posted falls back to cliclick. A posted click is checked by
|
|
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).
|
|
16
|
+
// • Posted events reset HIDIdleTime like any other input; mac_* input jobs run under serializedInput,
|
|
17
|
+
// whose drain() advances lastOwnInputEnd, so user_active does not mistake our own events for the
|
|
18
|
+
// person's (server.mjs, 0.2.7 comment block).
|
|
19
|
+
|
|
20
|
+
import { execFile } from "node:child_process";
|
|
21
|
+
|
|
22
|
+
export const BGPOST_DISABLED = process.env.NORACU_NO_BGPOST === "1";
|
|
23
|
+
|
|
24
|
+
// Chromium / Electron / web-shell bundle ids (and app names, for hosts that report no bundle id).
|
|
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
|
|
27
|
+
// would still read as posted, and only a "nothing was posted" answer may fall back; Arc is company.thebrowser.*
|
|
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
|
+
export function bgCandidate(bundleId, appName) {
|
|
30
|
+
if (BGPOST_DISABLED) return false;
|
|
31
|
+
const b = String(bundleId || "");
|
|
32
|
+
const n = String(appName || "");
|
|
33
|
+
return !(WEB_ENGINE.test(b) || WEB_ENGINE.test(n));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// macOS virtual key codes for named keys (mirrors server.mjs ENGINE_KEYS) and modifier flag masks
|
|
37
|
+
// (CGEventSetFlags): cmd 1<<20, shift 1<<17, alt 1<<19, ctrl 1<<18, fn 1<<23, numpad 1<<21.
|
|
38
|
+
const NAMED_KEYS = {
|
|
39
|
+
return: 36, esc: 53, tab: 48, space: 49, delete: 51, "fwd-delete": 117, home: 115, end: 119,
|
|
40
|
+
"page-up": 116, "page-down": 121, "arrow-left": 123, "arrow-right": 124, "arrow-down": 125, "arrow-up": 126,
|
|
41
|
+
f1: 122, f2: 120, f3: 99, f4: 118, f5: 96, f6: 97, f7: 98, f8: 100, f9: 101, f10: 109, f11: 103, f12: 111,
|
|
42
|
+
f13: 105, f14: 107, f15: 113, f16: 106,
|
|
43
|
+
};
|
|
44
|
+
const MOD_FLAGS = { cmd: 1 << 20, shift: 1 << 17, alt: 1 << 19, ctrl: 1 << 18, fn: 1 << 23, numpad: 1 << 21 };
|
|
45
|
+
|
|
46
|
+
// One osascript per gesture. argv: [op, pid, ...numbers]. Numbers are clamped server-side; pid is
|
|
47
|
+
// Math.trunc()'d (pid_t is int32 — a float here is undefined behaviour through libffi).
|
|
48
|
+
// Every event of a gesture is created before the first one is posted, so the "nothing was posted"
|
|
49
|
+
// answers (bad-*, create-failed) are exact: only those may fall back to the cliclick pointer path.
|
|
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
|
|
52
|
+
// (middle); macOS reads it for the "other" event types only.
|
|
53
|
+
export const BG_SCRIPT = `
|
|
54
|
+
ObjC.import('CoreGraphics');
|
|
55
|
+
ObjC.bindFunction('CGEventCreateKeyboardEvent', ['void*', ['void*', 'int', 'bool']]);
|
|
56
|
+
ObjC.bindFunction('CGEventCreateMouseEvent', ['void*', ['void*', 'int', '{CGPoint=dd}', 'int']]);
|
|
57
|
+
ObjC.bindFunction('CGEventPostToPid', ['void', ['int', 'void*']]);
|
|
58
|
+
ObjC.bindFunction('CGEventSetFlags', ['void', ['void*', 'uint64']]);
|
|
59
|
+
ObjC.bindFunction('CGEventSetIntegerValueField', ['void', ['void*', 'int', 'int64']]);
|
|
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)
|
|
62
|
+
const pid = Number(argv[1]);
|
|
63
|
+
if (!Number.isInteger(pid) || pid <= 0 || pid > 2147483647) return 'bad-pid';
|
|
64
|
+
const src = $.CGEventSourceCreate($.kCGEventSourceStateHIDSystemState);
|
|
65
|
+
const events = [];
|
|
66
|
+
if (argv[0] === 'key') {
|
|
67
|
+
// argv: key, pid, keyCode, flags
|
|
68
|
+
const code = Number(argv[2]), flags = Number(argv[3]);
|
|
69
|
+
if (!Number.isInteger(code) || code < 0 || code > 127 || !Number.isInteger(flags) || flags < 0) return 'bad-key';
|
|
70
|
+
const down = $.CGEventCreateKeyboardEvent(src, code, true);
|
|
71
|
+
const up = $.CGEventCreateKeyboardEvent(src, code, false);
|
|
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)
|
|
74
|
+
$.CGEventSetFlags(down, flags); $.CGEventSetFlags(up, flags);
|
|
75
|
+
events.push(down, up);
|
|
76
|
+
} else if (argv[0] === 'click') {
|
|
77
|
+
// argv: click, pid, x, y, downType, upType, count, button
|
|
78
|
+
const x = Number(argv[2]), y = Number(argv[3]);
|
|
79
|
+
const dT = Math.trunc(Number(argv[4])), uT = Math.trunc(Number(argv[5]));
|
|
80
|
+
const n0 = Number(argv[6]);
|
|
81
|
+
if (!Number.isInteger(n0) || n0 < 1) return 'bad-count';
|
|
82
|
+
const n = Math.min(n0, 5);
|
|
83
|
+
const btn = Math.min(Math.max(Math.trunc(Number(argv[7]) || 0), 0), 2);
|
|
84
|
+
if (!isFinite(x) || !isFinite(y)) return 'bad-point';
|
|
85
|
+
const pt = $.CGPointMake(x, y);
|
|
86
|
+
for (let i = 0; i < n; i++) {
|
|
87
|
+
const down = $.CGEventCreateMouseEvent(src, dT, pt, btn);
|
|
88
|
+
const up = $.CGEventCreateMouseEvent(src, uT, pt, btn);
|
|
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)
|
|
91
|
+
$.CGEventSetFlags(down, 0); $.CGEventSetFlags(up, 0);
|
|
92
|
+
$.CGEventSetIntegerValueField(down, 1, i + 1);
|
|
93
|
+
$.CGEventSetIntegerValueField(up, 1, i + 1);
|
|
94
|
+
events.push(down, up);
|
|
95
|
+
}
|
|
96
|
+
} else return 'bad-op';
|
|
97
|
+
for (const ev of events) $.CGEventPostToPid(pid, ev);
|
|
98
|
+
return 'ok';
|
|
99
|
+
}`;
|
|
100
|
+
|
|
101
|
+
// kCGEvent{Left,Right,Other}Mouse{Down,Up} and the button number CGEventCreateMouseEvent takes
|
|
102
|
+
const MOUSE = { left: { types: [1, 2], button: 0 }, right: { types: [3, 4], button: 1 }, middle: { types: [25, 26], button: 2 } };
|
|
103
|
+
// answers that prove nothing was posted
|
|
104
|
+
export const NOT_POSTED = new Set(["bad-pid", "bad-key", "bad-point", "bad-count", "bad-op", "create-failed"]);
|
|
105
|
+
|
|
106
|
+
// S4A-s11-Gemini-1 / -2: null, "", false and fractions are not numbers here — Number(null) is 0, which is the A
|
|
107
|
+
// key, the pid of no process and the screen corner. A bad value goes out as "NaN" and the script answers bad-*.
|
|
108
|
+
const num = (v) => (typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN);
|
|
109
|
+
const intIn = (v, lo, hi) => { const n = num(v); return Number.isInteger(n) && n >= lo && n <= hi ? n : NaN; };
|
|
110
|
+
|
|
111
|
+
// The argv after `--` for one gesture (pure: the contract tests check it).
|
|
112
|
+
export function keyArgv(pid, keyCode, mods = []) {
|
|
113
|
+
let flags = 0;
|
|
114
|
+
// an unknown modifier is a bad chord, not a bare key (S4A-s11-2)
|
|
115
|
+
for (const m of mods) { if (!Object.hasOwn(MOD_FLAGS, m)) { flags = NaN; break; } flags |= MOD_FLAGS[m]; }
|
|
116
|
+
return ["key", intIn(pid, 1, 2147483647), intIn(keyCode, 0, 127), flags].map(String);
|
|
117
|
+
}
|
|
118
|
+
export function clickArgv(pid, x, y, { button = "left", count = 1 } = {}) {
|
|
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)
|
|
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
|
+
}
|
|
123
|
+
|
|
124
|
+
// Runs one gesture. run(argv) → { code, stdout, timedOut, error } — the server passes its own runner, so
|
|
125
|
+
// the osascript child is timed, counted among the running children (killed on shutdown) and waited for
|
|
126
|
+
// by the input queue like every other one (invariant 10). Answers:
|
|
127
|
+
// { ok: true } posted
|
|
128
|
+
// { ok: false, sent: false, error } nothing was posted (the caller may use another path)
|
|
129
|
+
// { ok: false, sent: "unknown", error } a timeout or an odd exit: events may have gone out — no fallback
|
|
130
|
+
function defaultRun(argv) {
|
|
131
|
+
return new Promise((resolve) => {
|
|
132
|
+
execFile("/usr/bin/osascript", ["-l", "JavaScript", "-e", BG_SCRIPT, "--", ...argv], { timeout: 8000 }, (err, stdout) => {
|
|
133
|
+
resolve({ code: err ? (err.code ?? 1) : 0, stdout: String(stdout || ""), timedOut: Boolean(err && err.killed), error: err && err.code === "ENOENT" ? err : null });
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
async function post(argv, run = defaultRun) {
|
|
138
|
+
if (BGPOST_DISABLED) return { ok: false, sent: false, error: "bgpost disabled" };
|
|
139
|
+
const r = await run(argv);
|
|
140
|
+
if (r.error) return { ok: false, sent: false, error: `bgpost could not start: ${String(r.error.message || r.error).slice(0, 120)}` };
|
|
141
|
+
if (r.timedOut) return { ok: false, sent: "unknown", error: "bgpost did not finish in time" };
|
|
142
|
+
const out = String(r.stdout || "").trim();
|
|
143
|
+
if (out === "ok" && r.code === 0) return { ok: true };
|
|
144
|
+
if (NOT_POSTED.has(out)) return { ok: false, sent: false, error: `bgpost ${out}` };
|
|
145
|
+
return { ok: false, sent: "unknown", error: `bgpost ${out || `exited with ${r.code}`}` };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Post a key chord to one pid. keyCode: a macOS virtual key code; mods: array of "cmd"|"shift"|"alt"|"ctrl"|"fn"|"numpad".
|
|
149
|
+
export function postKeyToPid(pid, keyCode, mods = [], { run } = {}) { return post(keyArgv(pid, keyCode, mods), run); }
|
|
150
|
+
|
|
151
|
+
// Post count clicks at a point to one pid. Coordinates are in points (logical screen coordinates).
|
|
152
|
+
export function postClickToPid(pid, x, y, { button = "left", count = 1, run } = {}) { return post(clickArgv(pid, x, y, { button, count }), run); }
|
|
153
|
+
|
|
154
|
+
export function namedKeyCode(name) { return NAMED_KEYS[name] ?? null; }
|