@namzu/computer-use 4.4.0 → 4.5.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 +16 -0
- package/dist/SubprocessComputerUseHost.d.ts +8 -1
- package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
- package/dist/SubprocessComputerUseHost.js +15 -4
- package/dist/SubprocessComputerUseHost.js.map +1 -1
- package/dist/a11y/a11y.d.ts +15 -7
- package/dist/a11y/a11y.d.ts.map +1 -1
- package/dist/a11y/a11y.js +12 -5
- package/dist/a11y/a11y.js.map +1 -1
- package/dist/a11y/index.d.ts +7 -1
- package/dist/a11y/index.d.ts.map +1 -1
- package/dist/a11y/index.js +4 -1
- package/dist/a11y/index.js.map +1 -1
- package/dist/a11y/macos-helper.d.ts +80 -0
- package/dist/a11y/macos-helper.d.ts.map +1 -0
- package/dist/a11y/macos-helper.js +436 -0
- package/dist/a11y/macos-helper.js.map +1 -0
- package/dist/a11y/macos-signing.d.ts +56 -0
- package/dist/a11y/macos-signing.d.ts.map +1 -0
- package/dist/a11y/macos-signing.js +228 -0
- package/dist/a11y/macos-signing.js.map +1 -0
- package/dist/a11y/macos.d.ts +173 -0
- package/dist/a11y/macos.d.ts.map +1 -0
- package/dist/a11y/macos.js +271 -0
- package/dist/a11y/macos.js.map +1 -0
- package/dist/a11y/windows.d.ts +13 -2
- package/dist/a11y/windows.d.ts.map +1 -1
- package/dist/a11y/windows.js +29 -6
- package/dist/a11y/windows.js.map +1 -1
- package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
- package/dist/adapters/cua-driver/adapter.js +48 -10
- package/dist/adapters/cua-driver/adapter.js.map +1 -1
- package/dist/adapters/cua-driver/ui-tree.d.ts +1 -0
- package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
- package/dist/adapters/cua-driver/ui-tree.js +2 -0
- package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
- package/dist/adapters/darwin-ax.d.ts +94 -0
- package/dist/adapters/darwin-ax.d.ts.map +1 -0
- package/dist/adapters/darwin-ax.js +754 -0
- package/dist/adapters/darwin-ax.js.map +1 -0
- package/dist/adapters/darwin.d.ts +43 -2
- package/dist/adapters/darwin.d.ts.map +1 -1
- package/dist/adapters/darwin.js +145 -7
- package/dist/adapters/darwin.js.map +1 -1
- package/dist/adapters/png.d.ts +6 -0
- package/dist/adapters/png.d.ts.map +1 -0
- package/dist/adapters/png.js +7 -0
- package/dist/adapters/png.js.map +1 -0
- package/dist/adapters/win32-native.d.ts +53 -0
- package/dist/adapters/win32-native.d.ts.map +1 -0
- package/dist/adapters/win32-native.js +279 -0
- package/dist/adapters/win32-native.js.map +1 -0
- package/dist/adapters/win32.d.ts +19 -1
- package/dist/adapters/win32.d.ts.map +1 -1
- package/dist/adapters/win32.js +34 -8
- package/dist/adapters/win32.js.map +1 -1
- package/dist/foreground/ladder.d.ts.map +1 -1
- package/dist/foreground/ladder.js +5 -1
- package/dist/foreground/ladder.js.map +1 -1
- package/dist/foreground/types.d.ts +6 -0
- package/dist/foreground/types.d.ts.map +1 -1
- package/dist/foreground/types.js.map +1 -1
- package/dist/foreground/windows.d.ts +2 -0
- package/dist/foreground/windows.d.ts.map +1 -1
- package/dist/foreground/windows.js +23 -11
- package/dist/foreground/windows.js.map +1 -1
- package/dist/native/a11y.d.ts +61 -0
- package/dist/native/a11y.d.ts.map +1 -0
- package/dist/native/a11y.js +197 -0
- package/dist/native/a11y.js.map +1 -0
- package/dist/native/foreground-monitor.d.ts +51 -0
- package/dist/native/foreground-monitor.d.ts.map +1 -0
- package/dist/native/foreground-monitor.js +120 -0
- package/dist/native/foreground-monitor.js.map +1 -0
- package/dist/native/presence.d.ts +24 -0
- package/dist/native/presence.d.ts.map +1 -0
- package/dist/native/presence.js +47 -0
- package/dist/native/presence.js.map +1 -0
- package/dist/native/process.d.ts +73 -0
- package/dist/native/process.d.ts.map +1 -0
- package/dist/native/process.js +292 -0
- package/dist/native/process.js.map +1 -0
- package/dist/native/protocol.d.ts +408 -0
- package/dist/native/protocol.d.ts.map +1 -0
- package/dist/native/protocol.js +527 -0
- package/dist/native/protocol.js.map +1 -0
- package/dist/native/shared.d.ts +16 -0
- package/dist/native/shared.d.ts.map +1 -0
- package/dist/native/shared.js +62 -0
- package/dist/native/shared.js.map +1 -0
- package/dist/presence/presence.d.ts +3 -2
- package/dist/presence/presence.d.ts.map +1 -1
- package/dist/presence/presence.js.map +1 -1
- package/dist/presence/windows.d.ts +2 -0
- package/dist/presence/windows.d.ts.map +1 -1
- package/dist/presence/windows.js +14 -0
- package/dist/presence/windows.js.map +1 -1
- package/helper-macos/main.swift +1756 -0
- package/package.json +3 -2
- package/src/SubprocessComputerUseHost.ts +26 -2
- package/src/a11y/a11y.ts +25 -11
- package/src/a11y/index.ts +28 -1
- package/src/a11y/macos-helper.ts +538 -0
- package/src/a11y/macos-signing.ts +280 -0
- package/src/a11y/macos.ts +496 -0
- package/src/a11y/windows.ts +29 -4
- package/src/adapters/cua-driver/adapter.ts +55 -15
- package/src/adapters/cua-driver/ui-tree.ts +2 -0
- package/src/adapters/darwin-ax.ts +920 -0
- package/src/adapters/darwin.ts +184 -4
- package/src/adapters/png.ts +5 -0
- package/src/adapters/win32-native.ts +328 -0
- package/src/adapters/win32.ts +52 -5
- package/src/foreground/ladder.ts +5 -1
- package/src/foreground/types.ts +6 -0
- package/src/foreground/windows.ts +24 -11
- package/src/native/a11y.ts +267 -0
- package/src/native/foreground-monitor.ts +165 -0
- package/src/native/presence.ts +58 -0
- package/src/native/process.ts +335 -0
- package/src/native/protocol.ts +963 -0
- package/src/native/shared.ts +75 -0
- package/src/presence/presence.ts +3 -2
- package/src/presence/windows.ts +14 -0
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
2
|
+
import {
|
|
3
|
+
existsSync,
|
|
4
|
+
mkdirSync,
|
|
5
|
+
readFileSync,
|
|
6
|
+
readdirSync,
|
|
7
|
+
renameSync,
|
|
8
|
+
rmSync,
|
|
9
|
+
statSync,
|
|
10
|
+
writeFileSync,
|
|
11
|
+
} from 'node:fs'
|
|
12
|
+
import { type Socket, connect } from 'node:net'
|
|
13
|
+
import { homedir, tmpdir } from 'node:os'
|
|
14
|
+
import { join } from 'node:path'
|
|
15
|
+
import { createInterface } from 'node:readline'
|
|
16
|
+
import { fileURLToPath } from 'node:url'
|
|
17
|
+
import { hasExecutable, runCommand } from '../util/spawn.js'
|
|
18
|
+
import type { A11yProcess } from './a11y.js'
|
|
19
|
+
import { A11yError } from './interface.js'
|
|
20
|
+
import {
|
|
21
|
+
type MacSigningIdentity,
|
|
22
|
+
ensureSigningIdentity,
|
|
23
|
+
lockSigningKeychain,
|
|
24
|
+
macSigningDir,
|
|
25
|
+
unlockSigningKeychain,
|
|
26
|
+
} from './macos-signing.js'
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The macOS accessibility helper: a small Swift app, "Namzu Helper", that
|
|
30
|
+
* LaunchServices starts in the person's own GUI session.
|
|
31
|
+
*
|
|
32
|
+
* Why an app and not a command: macOS gives the Accessibility and Screen
|
|
33
|
+
* Recording permissions to a signed program, and a program started from a
|
|
34
|
+
* terminal or from sshd borrows the terminal's or sshd's (usually none).
|
|
35
|
+
* Started with `open -a`, the helper is its own program, so the person turns
|
|
36
|
+
* two switches on once, for "Namzu Helper", and every later session works.
|
|
37
|
+
*
|
|
38
|
+
* How it is shipped: the Swift source travels in this package
|
|
39
|
+
* (`helper-macos/main.swift`) and is compiled on first use with `swiftc`
|
|
40
|
+
* (Xcode Command Line Tools, which a Mac used for development has) and kept at
|
|
41
|
+
* a stable path, `<NAMZU_HOME>/computer-use/macos/Namzu Helper.app`, which a
|
|
42
|
+
* new build replaces in place (the old app is moved to `replaced/`). It is
|
|
43
|
+
* signed with a per-user local identity (see `macos-signing.ts`) so that the
|
|
44
|
+
* permission the person gave survives every rebuild; on macOS 27 an ad-hoc
|
|
45
|
+
* signature is not trusted at all, and it is used only when the identity
|
|
46
|
+
* cannot be made. A prebuilt binary per architecture would have to be signed
|
|
47
|
+
* with a paid identity to carry a permission across versions and notarised to
|
|
48
|
+
* open without a warning; building on the person's Mac needs neither and
|
|
49
|
+
* makes the binary one that was compiled from the source they can read. The
|
|
50
|
+
* cost is the Command Line Tools and a few seconds the first time (3 to 4
|
|
51
|
+
* seconds on an M-series Mac mini). The socket is keyed by the source's digest,
|
|
52
|
+
* so an old helper still running is left to end by itself (it exits after 15
|
|
53
|
+
* quiet minutes) and never answers a newer client. Nothing needs sudo.
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
export const MAC_HELPER_NAME = 'Namzu Helper'
|
|
57
|
+
export const MAC_HELPER_BUNDLE_ID = 'com.namzu.helper'
|
|
58
|
+
const EXECUTABLE = 'NamzuHelper'
|
|
59
|
+
/** A unix socket path must be shorter than this on macOS. */
|
|
60
|
+
const SOCKET_PATH_LIMIT = 100
|
|
61
|
+
|
|
62
|
+
/** Variable names never handed to a helper or to the compiler. */
|
|
63
|
+
const SECRET_NAME = /(API_?KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)/i
|
|
64
|
+
|
|
65
|
+
export interface MacHelperPaths {
|
|
66
|
+
/** `<NAMZU_HOME>/computer-use/macos` */
|
|
67
|
+
readonly root: string
|
|
68
|
+
readonly hash: string
|
|
69
|
+
/** `…/Namzu Helper.app`: one path for every build, so the person's grant keeps pointing at it. */
|
|
70
|
+
readonly bundle: string
|
|
71
|
+
readonly executable: string
|
|
72
|
+
readonly socket: string
|
|
73
|
+
/** Where window captures are written for the client to read; owner only. */
|
|
74
|
+
readonly captures: string
|
|
75
|
+
/** What was built and how it was signed. */
|
|
76
|
+
readonly state: string
|
|
77
|
+
/** Where the local signing identity lives. */
|
|
78
|
+
readonly signing: string
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function macHelperSourcePath(): string {
|
|
82
|
+
return fileURLToPath(new URL('../../helper-macos/main.swift', import.meta.url))
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function macHelperSourceHash(source: string): string {
|
|
86
|
+
return createHash('sha256').update(source).digest('hex').slice(0, 16)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function namzuHome(env: NodeJS.ProcessEnv): string {
|
|
90
|
+
return env.NAMZU_HOME && env.NAMZU_HOME.length > 0 ? env.NAMZU_HOME : join(homedir(), '.namzu')
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function macHelperPaths(env: NodeJS.ProcessEnv, hash: string): MacHelperPaths {
|
|
94
|
+
const root = join(namzuHome(env), 'computer-use', 'macos')
|
|
95
|
+
const bundle = join(root, `${MAC_HELPER_NAME}.app`)
|
|
96
|
+
let socket = join(root, `h-${hash.slice(0, 8)}.sock`)
|
|
97
|
+
if (Buffer.byteLength(socket) >= SOCKET_PATH_LIMIT) {
|
|
98
|
+
socket = join(tmpdir(), `namzu-${process.getuid?.() ?? 0}-${hash.slice(0, 8)}`, 'h.sock')
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
root,
|
|
102
|
+
hash,
|
|
103
|
+
bundle,
|
|
104
|
+
executable: join(bundle, 'Contents', 'MacOS', EXECUTABLE),
|
|
105
|
+
socket,
|
|
106
|
+
captures: join(root, 'captures'),
|
|
107
|
+
state: join(root, 'helper-build.json'),
|
|
108
|
+
signing: macSigningDir(root),
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function macHelperInfoPlist(hash: string): string {
|
|
113
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
114
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
115
|
+
<plist version="1.0">
|
|
116
|
+
<dict>
|
|
117
|
+
<key>CFBundleIdentifier</key><string>${MAC_HELPER_BUNDLE_ID}</string>
|
|
118
|
+
<key>CFBundleName</key><string>${MAC_HELPER_NAME}</string>
|
|
119
|
+
<key>CFBundleDisplayName</key><string>${MAC_HELPER_NAME}</string>
|
|
120
|
+
<key>CFBundleExecutable</key><string>${EXECUTABLE}</string>
|
|
121
|
+
<key>CFBundlePackageType</key><string>APPL</string>
|
|
122
|
+
<key>CFBundleShortVersionString</key><string>1.0</string>
|
|
123
|
+
<key>CFBundleVersion</key><string>${hash}</string>
|
|
124
|
+
<key>LSMinimumSystemVersion</key><string>14.0</string>
|
|
125
|
+
<key>LSUIElement</key><true/>
|
|
126
|
+
<key>NSHighResolutionCapable</key><true/>
|
|
127
|
+
<key>NSScreenCaptureUsageDescription</key><string>Namzu reads the windows it is asked to work in, to show them to the model.</string>
|
|
128
|
+
</dict>
|
|
129
|
+
</plist>
|
|
130
|
+
`
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function cleanEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
|
134
|
+
const out: NodeJS.ProcessEnv = {}
|
|
135
|
+
for (const [name, value] of Object.entries(env)) if (!SECRET_NAME.test(name)) out[name] = value
|
|
136
|
+
return out
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface EnsureMacHelperOptions {
|
|
140
|
+
readonly env: NodeJS.ProcessEnv
|
|
141
|
+
/** Told once, in plain words, before the helper is compiled. */
|
|
142
|
+
readonly onNotice?: (notice: string) => void
|
|
143
|
+
/** For tests. */
|
|
144
|
+
readonly sourcePath?: string
|
|
145
|
+
readonly run?: typeof runCommand
|
|
146
|
+
readonly hasTool?: (name: string) => Promise<boolean>
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const NO_COMPILER_TEXT =
|
|
150
|
+
'the macOS accessibility helper is built on this Mac the first time, and the Swift compiler is missing. Run `xcode-select --install` once (Xcode Command Line Tools), then try again.'
|
|
151
|
+
|
|
152
|
+
/** What the last build left, kept beside the app. */
|
|
153
|
+
interface BuildState {
|
|
154
|
+
readonly hash: string
|
|
155
|
+
readonly signing: 'identity' | 'adhoc'
|
|
156
|
+
readonly identity?: string
|
|
157
|
+
/** For an ad-hoc build: when to try to make the identity again, ms since the epoch. */
|
|
158
|
+
readonly retryAfter?: number
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const RETRY_IDENTITY_MS = 24 * 60 * 60 * 1000
|
|
162
|
+
|
|
163
|
+
function readState(path: string): BuildState | undefined {
|
|
164
|
+
try {
|
|
165
|
+
const value = JSON.parse(readFileSync(path, 'utf8')) as Partial<BuildState>
|
|
166
|
+
if (typeof value.hash !== 'string') return undefined
|
|
167
|
+
return {
|
|
168
|
+
hash: value.hash,
|
|
169
|
+
signing: value.signing === 'identity' ? 'identity' : 'adhoc',
|
|
170
|
+
...(typeof value.identity === 'string' ? { identity: value.identity } : {}),
|
|
171
|
+
...(typeof value.retryAfter === 'number' ? { retryAfter: value.retryAfter } : {}),
|
|
172
|
+
}
|
|
173
|
+
} catch {
|
|
174
|
+
return undefined
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function writeState(path: string, state: BuildState): void {
|
|
179
|
+
writeFileSync(path, `${JSON.stringify(state)}\n`, { mode: 0o600 })
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const NO_IDENTITY_NOTICE = (reason: string): string =>
|
|
183
|
+
`Namzu could not make its local signing identity (${reason.slice(0, 200)}), so the macOS helper is signed ad hoc. macOS 27 does not trust an ad-hoc app even with its switch on, and an older macOS asks for the switches again after every rebuild.`
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* The helper's paths, compiling and signing it first when this source has
|
|
187
|
+
* not been built on this machine. Throws {@link A11yError} (`no_compiler`,
|
|
188
|
+
* `build_failed`) with what the person can do.
|
|
189
|
+
*/
|
|
190
|
+
export async function ensureMacHelper(options: EnsureMacHelperOptions): Promise<MacHelperPaths> {
|
|
191
|
+
const source = readFileSync(options.sourcePath ?? macHelperSourcePath(), 'utf8')
|
|
192
|
+
const paths = macHelperPaths(options.env, macHelperSourceHash(source))
|
|
193
|
+
const run = options.run ?? runCommand
|
|
194
|
+
const env = cleanEnv(options.env)
|
|
195
|
+
const current = (): BuildState | undefined => {
|
|
196
|
+
const state = readState(paths.state)
|
|
197
|
+
return existsSync(paths.executable) && state?.hash === paths.hash ? state : undefined
|
|
198
|
+
}
|
|
199
|
+
const done = current()
|
|
200
|
+
if (done?.signing === 'identity') return paths
|
|
201
|
+
if (done && Date.now() < (done.retryAfter ?? 0)) return paths
|
|
202
|
+
mkdirSync(paths.root, { recursive: true, mode: 0o700 })
|
|
203
|
+
const release = await takeBuildLock(paths.root, () => current() !== undefined)
|
|
204
|
+
if (!release) return paths
|
|
205
|
+
try {
|
|
206
|
+
return await buildMacHelper(options, paths, run, env)
|
|
207
|
+
} finally {
|
|
208
|
+
release()
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const LOCK_STALE_MS = 10 * 60 * 1000
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* One build at a time per Namzu home. Resolves a release function, or
|
|
216
|
+
* `undefined` when another process finished a usable app while this one waited.
|
|
217
|
+
*/
|
|
218
|
+
async function takeBuildLock(
|
|
219
|
+
root: string,
|
|
220
|
+
ready: () => boolean,
|
|
221
|
+
): Promise<(() => void) | undefined> {
|
|
222
|
+
const lock = join(root, 'build.lock')
|
|
223
|
+
for (let attempt = 0; attempt < 240; attempt++) {
|
|
224
|
+
try {
|
|
225
|
+
writeFileSync(lock, `${process.pid}\n`, { flag: 'wx', mode: 0o600 })
|
|
226
|
+
return () => rmSync(lock, { force: true })
|
|
227
|
+
} catch {
|
|
228
|
+
if (ready()) return undefined
|
|
229
|
+
let holder = 0
|
|
230
|
+
let age = 0
|
|
231
|
+
try {
|
|
232
|
+
holder = Number.parseInt(readFileSync(lock, 'utf8'), 10)
|
|
233
|
+
age = Date.now() - statSync(lock).mtimeMs
|
|
234
|
+
} catch {
|
|
235
|
+
continue
|
|
236
|
+
}
|
|
237
|
+
let alive = true
|
|
238
|
+
try {
|
|
239
|
+
process.kill(holder, 0)
|
|
240
|
+
} catch {
|
|
241
|
+
alive = false
|
|
242
|
+
}
|
|
243
|
+
if (!alive || age > LOCK_STALE_MS) rmSync(lock, { force: true })
|
|
244
|
+
else await new Promise<void>((resolve) => setTimeout(resolve, 500))
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return undefined
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function buildMacHelper(
|
|
251
|
+
options: EnsureMacHelperOptions,
|
|
252
|
+
paths: MacHelperPaths,
|
|
253
|
+
run: typeof runCommand,
|
|
254
|
+
env: NodeJS.ProcessEnv,
|
|
255
|
+
): Promise<MacHelperPaths> {
|
|
256
|
+
const state = readState(paths.state)
|
|
257
|
+
const haveApp = existsSync(paths.executable) && state?.hash === paths.hash
|
|
258
|
+
// Built ad hoc earlier: the identity is tried again once a day, and the app is replaced only if it signs with it.
|
|
259
|
+
const retrying = haveApp
|
|
260
|
+
const giveUp = (error: A11yError): MacHelperPaths => {
|
|
261
|
+
if (!retrying || !state) throw error
|
|
262
|
+
writeState(paths.state, { ...state, retryAfter: Date.now() + RETRY_IDENTITY_MS })
|
|
263
|
+
return paths
|
|
264
|
+
}
|
|
265
|
+
let regrant = false
|
|
266
|
+
const onBroken = (): void => {
|
|
267
|
+
regrant = true
|
|
268
|
+
}
|
|
269
|
+
let identity: MacSigningIdentity | undefined
|
|
270
|
+
if (retrying) {
|
|
271
|
+
identity = await ensureSigningIdentity({ root: paths.root, env, run, onBroken })
|
|
272
|
+
if (!identity) return giveUp(new A11yError('build_failed', 'no signing identity'))
|
|
273
|
+
}
|
|
274
|
+
const has = options.hasTool ?? hasExecutable
|
|
275
|
+
const noCompiler = new A11yError('no_compiler', NO_COMPILER_TEXT)
|
|
276
|
+
if (!(await has('swiftc'))) return giveUp(noCompiler)
|
|
277
|
+
// Without the Command Line Tools /usr/bin/swiftc is still there, as a shim
|
|
278
|
+
// that opens an install dialog, so presence on PATH proves nothing.
|
|
279
|
+
const developerDir = await run('xcode-select', ['-p'], {
|
|
280
|
+
timeoutMs: 5_000,
|
|
281
|
+
env,
|
|
282
|
+
}).catch(() => undefined)
|
|
283
|
+
if (!developerDir || developerDir.exitCode !== 0) return giveUp(noCompiler)
|
|
284
|
+
options.onNotice?.(
|
|
285
|
+
`Namzu is building its macOS helper (${MAC_HELPER_NAME}) from source, once. It takes a few seconds.`,
|
|
286
|
+
)
|
|
287
|
+
const stage = join(
|
|
288
|
+
paths.root,
|
|
289
|
+
`build-${paths.hash}-${process.pid}-${randomBytes(4).toString('hex')}`,
|
|
290
|
+
)
|
|
291
|
+
const app = join(stage, `${MAC_HELPER_NAME}.app`)
|
|
292
|
+
try {
|
|
293
|
+
mkdirSync(join(app, 'Contents', 'MacOS'), { recursive: true, mode: 0o700 })
|
|
294
|
+
writeFileSync(join(app, 'Contents', 'Info.plist'), macHelperInfoPlist(paths.hash))
|
|
295
|
+
const compile = await run(
|
|
296
|
+
'swiftc',
|
|
297
|
+
[
|
|
298
|
+
'-O',
|
|
299
|
+
'-swift-version',
|
|
300
|
+
'5',
|
|
301
|
+
options.sourcePath ?? macHelperSourcePath(),
|
|
302
|
+
'-o',
|
|
303
|
+
join(app, 'Contents', 'MacOS', EXECUTABLE),
|
|
304
|
+
'-framework',
|
|
305
|
+
'AppKit',
|
|
306
|
+
'-framework',
|
|
307
|
+
'ApplicationServices',
|
|
308
|
+
'-framework',
|
|
309
|
+
'ScreenCaptureKit',
|
|
310
|
+
],
|
|
311
|
+
{ timeoutMs: 300_000, env },
|
|
312
|
+
)
|
|
313
|
+
if (compile.exitCode !== 0) {
|
|
314
|
+
if (/xcode-select|developer tools/i.test(compile.stderr)) return giveUp(noCompiler)
|
|
315
|
+
return giveUp(
|
|
316
|
+
new A11yError(
|
|
317
|
+
'build_failed',
|
|
318
|
+
`the macOS helper did not compile: ${compile.stderr.trim().slice(0, 600)}`,
|
|
319
|
+
),
|
|
320
|
+
)
|
|
321
|
+
}
|
|
322
|
+
let why = ''
|
|
323
|
+
const make = (): Promise<MacSigningIdentity | undefined> =>
|
|
324
|
+
ensureSigningIdentity({
|
|
325
|
+
root: paths.root,
|
|
326
|
+
env,
|
|
327
|
+
run,
|
|
328
|
+
onBroken,
|
|
329
|
+
onFailure: (reason) => {
|
|
330
|
+
why = reason
|
|
331
|
+
},
|
|
332
|
+
})
|
|
333
|
+
const signWith = async (id: MacSigningIdentity): Promise<boolean> => {
|
|
334
|
+
try {
|
|
335
|
+
if (!(await unlockSigningKeychain(id, env, run))) {
|
|
336
|
+
why = 'the signing keychain would not open'
|
|
337
|
+
return false
|
|
338
|
+
}
|
|
339
|
+
const sign = await run(
|
|
340
|
+
'codesign',
|
|
341
|
+
[
|
|
342
|
+
'--force',
|
|
343
|
+
'--keychain',
|
|
344
|
+
id.keychain,
|
|
345
|
+
'--sign',
|
|
346
|
+
id.identity,
|
|
347
|
+
'--identifier',
|
|
348
|
+
MAC_HELPER_BUNDLE_ID,
|
|
349
|
+
app,
|
|
350
|
+
],
|
|
351
|
+
{ timeoutMs: 60_000, env },
|
|
352
|
+
)
|
|
353
|
+
if (sign.exitCode !== 0) why = sign.stderr.trim()
|
|
354
|
+
return sign.exitCode === 0
|
|
355
|
+
} finally {
|
|
356
|
+
await lockSigningKeychain(id.keychain, env, run)
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
identity ??= await make()
|
|
360
|
+
let signedBy: MacSigningIdentity | undefined
|
|
361
|
+
if (identity && (await signWith(identity))) signedBy = identity
|
|
362
|
+
else if (identity) {
|
|
363
|
+
// The identity listed fine but would not open or sign: set it aside once and make a new one.
|
|
364
|
+
const dir = macSigningDir(paths.root)
|
|
365
|
+
try {
|
|
366
|
+
renameSync(dir, `${dir}.broken-${Date.now()}`)
|
|
367
|
+
regrant = true
|
|
368
|
+
const fresh = await make()
|
|
369
|
+
if (fresh && (await signWith(fresh))) signedBy = fresh
|
|
370
|
+
} catch {
|
|
371
|
+
// Stays ad hoc below, with the reason.
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (retrying && !signedBy) return giveUp(new A11yError('build_failed', why))
|
|
375
|
+
if (!signedBy) {
|
|
376
|
+
options.onNotice?.(NO_IDENTITY_NOTICE(why || 'the tools it needs are missing'))
|
|
377
|
+
const sign = await run(
|
|
378
|
+
'codesign',
|
|
379
|
+
['--force', '--sign', '-', '--identifier', MAC_HELPER_BUNDLE_ID, app],
|
|
380
|
+
{ timeoutMs: 60_000, env },
|
|
381
|
+
)
|
|
382
|
+
if (sign.exitCode !== 0)
|
|
383
|
+
throw new A11yError(
|
|
384
|
+
'build_failed',
|
|
385
|
+
`the macOS helper did not sign: ${sign.stderr.trim().slice(0, 600)}`,
|
|
386
|
+
)
|
|
387
|
+
}
|
|
388
|
+
if (regrant)
|
|
389
|
+
options.onNotice?.(
|
|
390
|
+
`Namzu made a new signing identity for ${MAC_HELPER_NAME}, so macOS needs the permissions again: remove the old "${MAC_HELPER_NAME}" row in Privacy & Security first, then turn them on for the new one.`,
|
|
391
|
+
)
|
|
392
|
+
// The old app is moved aside, not deleted (a helper still running from it keeps its files), and
|
|
393
|
+
// moved back if the new one cannot take its place.
|
|
394
|
+
let aside: string | undefined
|
|
395
|
+
if (existsSync(paths.bundle)) {
|
|
396
|
+
const dir = join(paths.root, 'replaced', `${state?.hash ?? 'old'}-${Date.now()}`)
|
|
397
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
398
|
+
aside = join(dir, `${MAC_HELPER_NAME}.app`)
|
|
399
|
+
renameSync(paths.bundle, aside)
|
|
400
|
+
}
|
|
401
|
+
try {
|
|
402
|
+
renameSync(app, paths.bundle)
|
|
403
|
+
} catch (error) {
|
|
404
|
+
if (aside && !existsSync(paths.bundle)) renameSync(aside, paths.bundle)
|
|
405
|
+
throw error
|
|
406
|
+
}
|
|
407
|
+
writeState(
|
|
408
|
+
paths.state,
|
|
409
|
+
signedBy
|
|
410
|
+
? { hash: paths.hash, signing: 'identity', identity: signedBy.identity }
|
|
411
|
+
: { hash: paths.hash, signing: 'adhoc', retryAfter: Date.now() + RETRY_IDENTITY_MS },
|
|
412
|
+
)
|
|
413
|
+
pruneReplaced(join(paths.root, 'replaced'))
|
|
414
|
+
return paths
|
|
415
|
+
} finally {
|
|
416
|
+
// This build's own staging folder, nothing else.
|
|
417
|
+
rmSync(stage, { recursive: true, force: true })
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** Keeps the last few moved-aside apps (names start with the time-ordered suffix) and drops older ones. */
|
|
422
|
+
function pruneReplaced(dir: string, keep = 3): void {
|
|
423
|
+
try {
|
|
424
|
+
const entries = readdirSync(dir)
|
|
425
|
+
.map((name) => ({ name, time: Number(name.slice(name.lastIndexOf('-') + 1)) || 0 }))
|
|
426
|
+
.sort((a, b) => b.time - a.time)
|
|
427
|
+
for (const old of entries.slice(keep))
|
|
428
|
+
rmSync(join(dir, old.name), { recursive: true, force: true })
|
|
429
|
+
} catch {
|
|
430
|
+
// Nothing to prune.
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** Starts the helper through LaunchServices, in the GUI session, without bringing it forward. */
|
|
435
|
+
export async function launchMacHelper(
|
|
436
|
+
paths: MacHelperPaths,
|
|
437
|
+
env: NodeJS.ProcessEnv,
|
|
438
|
+
run: typeof runCommand = runCommand,
|
|
439
|
+
): Promise<void> {
|
|
440
|
+
const result = await run(
|
|
441
|
+
'open',
|
|
442
|
+
['-g', '-a', paths.bundle, '--args', '--socket', paths.socket, '--build', paths.hash],
|
|
443
|
+
{ timeoutMs: 20_000, env: cleanEnv(env) },
|
|
444
|
+
)
|
|
445
|
+
if (result.exitCode !== 0) {
|
|
446
|
+
throw new A11yError(
|
|
447
|
+
'launch_failed',
|
|
448
|
+
`macOS would not start ${MAC_HELPER_NAME}: ${result.stderr.trim().slice(0, 300) || `exit ${result.exitCode}`}. It must be started from a logged-in desktop session.`,
|
|
449
|
+
)
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function tryConnect(socketPath: string): Promise<Socket | undefined> {
|
|
454
|
+
return new Promise((resolve) => {
|
|
455
|
+
const socket = connect(socketPath)
|
|
456
|
+
socket.once('connect', () => {
|
|
457
|
+
socket.removeAllListeners('error')
|
|
458
|
+
resolve(socket)
|
|
459
|
+
})
|
|
460
|
+
socket.once('error', () => {
|
|
461
|
+
socket.destroy()
|
|
462
|
+
resolve(undefined)
|
|
463
|
+
})
|
|
464
|
+
})
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
export interface ConnectMacHelperOptions {
|
|
468
|
+
readonly paths: MacHelperPaths
|
|
469
|
+
readonly env: NodeJS.ProcessEnv
|
|
470
|
+
/** How long to wait for a started helper to open its socket, ms. Default 15 000. */
|
|
471
|
+
readonly waitMs?: number
|
|
472
|
+
readonly run?: typeof runCommand
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** A connection to the running helper, starting it when nothing listens. */
|
|
476
|
+
export async function connectMacHelper(options: ConnectMacHelperOptions): Promise<Socket> {
|
|
477
|
+
const first = await tryConnect(options.paths.socket)
|
|
478
|
+
if (first) return first
|
|
479
|
+
await launchMacHelper(options.paths, options.env, options.run)
|
|
480
|
+
const deadline = Date.now() + (options.waitMs ?? 15_000)
|
|
481
|
+
for (;;) {
|
|
482
|
+
const socket = await tryConnect(options.paths.socket)
|
|
483
|
+
if (socket) return socket
|
|
484
|
+
if (Date.now() > deadline)
|
|
485
|
+
throw new A11yError(
|
|
486
|
+
'helper_not_listening',
|
|
487
|
+
`${MAC_HELPER_NAME} was started but did not open its socket`,
|
|
488
|
+
)
|
|
489
|
+
await new Promise((resolve) => setTimeout(resolve, 150))
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** The helper's end of a socket as the client's process interface. Lines written before it is connected wait for it. */
|
|
494
|
+
export function socketProcess(open: () => Promise<Socket>): A11yProcess {
|
|
495
|
+
let socket: Socket | undefined
|
|
496
|
+
const queued: string[] = []
|
|
497
|
+
const lineHandlers: ((line: string) => void)[] = []
|
|
498
|
+
const exitHandlers: (() => void)[] = []
|
|
499
|
+
let ended = false
|
|
500
|
+
const end = (): void => {
|
|
501
|
+
if (ended) return
|
|
502
|
+
ended = true
|
|
503
|
+
for (const handler of exitHandlers) handler()
|
|
504
|
+
}
|
|
505
|
+
open().then(
|
|
506
|
+
(connected) => {
|
|
507
|
+
if (ended) {
|
|
508
|
+
connected.destroy()
|
|
509
|
+
return
|
|
510
|
+
}
|
|
511
|
+
socket = connected
|
|
512
|
+
socket.on('error', () => undefined)
|
|
513
|
+
socket.on('close', end)
|
|
514
|
+
createInterface({ input: socket }).on('line', (line) => {
|
|
515
|
+
for (const handler of lineHandlers) handler(line)
|
|
516
|
+
})
|
|
517
|
+
for (const line of queued.splice(0)) socket.write(`${line}\n`)
|
|
518
|
+
},
|
|
519
|
+
() => end(),
|
|
520
|
+
)
|
|
521
|
+
return {
|
|
522
|
+
write: (line) => {
|
|
523
|
+
if (socket) socket.write(`${line}\n`)
|
|
524
|
+
else queued.push(line)
|
|
525
|
+
},
|
|
526
|
+
onLine: (handler) => {
|
|
527
|
+
lineHandlers.push(handler)
|
|
528
|
+
},
|
|
529
|
+
onExit: (handler) => {
|
|
530
|
+
exitHandlers.push(handler)
|
|
531
|
+
},
|
|
532
|
+
kill: () => {
|
|
533
|
+
// Ends this connection; the helper itself stays up for the next session.
|
|
534
|
+
ended = true
|
|
535
|
+
socket?.destroy()
|
|
536
|
+
},
|
|
537
|
+
}
|
|
538
|
+
}
|