mobile-automator 0.35.0 → 0.35.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mobile-automator",
3
- "version": "0.35.0",
3
+ "version": "0.35.2",
4
4
  "description": "Host-agnostic mauto CLI for AI-driven mobile QA automation — analyzes a mobile project and drives devices through mobile-mcp.",
5
5
  "homepage": "https://github.com/sh3lan93/mobile-automator#readme",
6
6
  "repository": {
@@ -8,6 +8,7 @@ const { resolveSingleDevice } = require('./device-resolver');
8
8
  const { normalizeDevices } = require('./device-model');
9
9
  const { resolveEngineTelemetry } = require('../observe/telemetry');
10
10
  const { ErrorCode } = require('@modelcontextprotocol/sdk/types.js');
11
+ const { argvPath } = require('./session-paths');
11
12
 
12
13
  // Bound on mobile-mcp's MCP initialize handshake (#156). Measured at ~200ms on
13
14
  // mobile-mcp 1.0.5 — initialize touches no device — so 10s is ~50x headroom.
@@ -80,7 +81,42 @@ function resolveServerEntry() {
80
81
  // the user set. The decision lives in resolveEngineTelemetry so that
81
82
  // `mauto telemetry status` reports exactly what this hands the engine, and the
82
83
  // same `mauto session end` rule applies to a change.
83
- function buildEngineEnv({ device = null, baseEnv = process.env, engine = null } = {}) {
84
+ //
85
+ // MOBILECLI_PATH is set root-relative when `projectRoot` is given (#236).
86
+ // mobile-mcp runs mobilecli by the absolute path its own resolver finds, and
87
+ // for an in-project install that path contains the project root, which `ps`
88
+ // shows every user on the host. mobile-mcp 1.0.5 takes MOBILECLI_PATH verbatim
89
+ // and spawns mobilecli without a cwd option, so the binary inherits the
90
+ // engine's cwd, which createCall pins to projectRoot: a root-relative path
91
+ // reaches the same file. The lookup itself stays mobile-mcp's
92
+ // (resolveMobilecli; tests/integration/mobile-mcp-contract.test.js fails if an
93
+ // engine bump moves it). A resolver that throws leaves the key unset, so the
94
+ // engine surfaces its own "mobilecli not found". A user-set value always wins.
95
+ // A bare relative name would be a PATH lookup for execFile, so a binary
96
+ // sitting directly in the root keeps a `./`.
97
+ function defaultResolveMobilecli() {
98
+ return require('@mobilenext/mobile-mcp/lib/mobilecli.js').Mobilecli.getMobilecliPath();
99
+ }
100
+
101
+ function relativeMobilecliPath(projectRoot, resolveMobilecli) {
102
+ let resolved;
103
+ try {
104
+ resolved = resolveMobilecli();
105
+ } catch (_e) {
106
+ return undefined;
107
+ }
108
+ if (!resolved) return undefined;
109
+ const p = argvPath(projectRoot, resolved);
110
+ return path.isAbsolute(p) || p.includes(path.sep) ? p : `.${path.sep}${p}`;
111
+ }
112
+
113
+ function buildEngineEnv({
114
+ device = null,
115
+ baseEnv = process.env,
116
+ engine = null,
117
+ projectRoot = null,
118
+ resolveMobilecli = defaultResolveMobilecli,
119
+ } = {}) {
84
120
  const env = {
85
121
  ...baseEnv,
86
122
  MOBILEMCP_ALLOW_UNSAFE_URLS: baseEnv.MOBILEMCP_ALLOW_UNSAFE_URLS ?? '1',
@@ -92,6 +128,10 @@ function buildEngineEnv({ device = null, baseEnv = process.env, engine = null }
92
128
  // mobile-mcp reads the target device from the environment / its own
93
129
  // selection; we pass it through when provided so callers can pin a device.
94
130
  if (device) env.MOBILE_MCP_DEVICE = device;
131
+ if (projectRoot && baseEnv.MOBILECLI_PATH === undefined) {
132
+ const mobilecli = relativeMobilecliPath(projectRoot, resolveMobilecli);
133
+ if (mobilecli !== undefined) env.MOBILECLI_PATH = mobilecli;
134
+ }
95
135
  return env;
96
136
  }
97
137
 
@@ -115,6 +155,12 @@ function pidTracking(Transport) {
115
155
  // Integration glue: spawns mobile-mcp over stdio and returns a `call`
116
156
  // function shaped exactly like the one DeviceBridge expects.
117
157
  //
158
+ // `projectRoot` (#236): the daemon passes its workspace root. The engine then
159
+ // runs with cwd = root, its in-project entry is passed relative to that root
160
+ // (argvPath), and so is MOBILECLI_PATH (buildEngineEnv): the engine is the
161
+ // daemon's long-lived child and `ps` shows its argv to every user on the host.
162
+ // Null keeps the absolute entry and the inherited cwd.
163
+ //
118
164
  // `sdk`, `server` and `reaper` are test seams: production passes none of them.
119
165
  // tests/unit/device/mobile-mcp-client-lifecycle.test.js drives this against a
120
166
  // fake SDK; tests/integration/engine-lifecycle.test.js against the real SDK and
@@ -122,6 +168,7 @@ function pidTracking(Transport) {
122
168
  async function createCall({
123
169
  device,
124
170
  engine = null,
171
+ projectRoot = null,
125
172
  connectTimeoutMs = CONNECT_TIMEOUT_MS,
126
173
  onEngineExit = null,
127
174
  sdk = { Client, StdioClientTransport },
@@ -129,12 +176,16 @@ async function createCall({
129
176
  reaper = require('./process-reaper'),
130
177
  } = {}) {
131
178
  // Resolved lazily, here, so the module still loads without mobile-mcp installed.
132
- const { command, args } = server || { command: process.execPath, args: [resolveServerEntry()] };
179
+ // The relative entry and MOBILECLI_PATH only resolve because cwd is the same
180
+ // projectRoot, so both come from it here.
181
+ const entry = () => (projectRoot ? argvPath(projectRoot, resolveServerEntry()) : resolveServerEntry());
182
+ const { command, args } = server || { command: process.execPath, args: [entry()] };
133
183
  const Transport = pidTracking(sdk.StdioClientTransport);
134
184
  const transport = new Transport({
135
185
  command,
136
186
  args,
137
- env: buildEngineEnv({ device, engine }),
187
+ env: buildEngineEnv({ device, engine, projectRoot }),
188
+ ...(projectRoot ? { cwd: projectRoot } : {}),
138
189
  });
139
190
 
140
191
  const client = new sdk.Client({ name: 'mauto', version: '0.1.0' }, { capabilities: {} });
@@ -13,6 +13,7 @@ const childProcess = require('child_process');
13
13
  const fs = require('fs');
14
14
 
15
15
  const paths = require('./session-paths');
16
+ const sessionSalt = require('./session-salt');
16
17
 
17
18
  // True when a pid is a live process we own. ESRCH => dead; EPERM => alive.
18
19
  // cleanStale routes through pidIdentity, which also checks the process's
@@ -73,12 +74,18 @@ function isZombie(
73
74
  // 'unknown' - alive but `ps` itself failed (e.g. no `ps` on the host) —
74
75
  // treated as 'ours' by cleanStale: never clean when unsure.
75
76
  // `execFile` is injectable for tests; a failure there must never crash the
76
- // daemon, hence the 'unknown' fallback.
77
+ // daemon, hence the 'unknown' fallback. So is `readSalt` (#236): the marker is
78
+ // HMAC(salt, root), and the salt is read from THIS workspace's .session/, only
79
+ // when a projectRoot is given. A copied workspace has the salt but not the
80
+ // root, so the original's daemon stays 'foreign' to it.
77
81
  //
78
82
  // cleanStale passes no projectRoot and keeps the binary-level answer: there a
79
83
  // wrong 'ours' only means stale files are left alone. `session end` passes one,
80
84
  // because there a wrong 'ours' sends a process-group kill (src/device/connection.js).
81
- function pidIdentity(pid, { execFile = childProcess.execFileSync, projectRoot = null } = {}) {
85
+ function pidIdentity(
86
+ pid,
87
+ { execFile = childProcess.execFileSync, projectRoot = null, readSalt = sessionSalt.readSalt } = {}
88
+ ) {
82
89
  if (!pid || !Number.isInteger(pid)) return 'dead';
83
90
  // Our own pid is the in-process daemon (unit tests run startDaemon in the
84
91
  // test process, so the lock/pidfile carry the test runner's pid). Never clean
@@ -105,7 +112,7 @@ function pidIdentity(pid, { execFile = childProcess.execFileSync, projectRoot =
105
112
  );
106
113
  if (!/mauto-session-daemon/.test(out)) return 'other';
107
114
  if (projectRoot == null) return 'ours';
108
- return paths.commandNamesWorkspace(out, projectRoot) ? 'ours' : 'foreign';
115
+ return paths.commandNamesWorkspace(out, projectRoot, readSalt(projectRoot)) ? 'ours' : 'foreign';
109
116
  } catch (_) {
110
117
  return 'unknown';
111
118
  }
@@ -23,7 +23,7 @@ const net = require('net');
23
23
 
24
24
  const paths = require('./session-paths');
25
25
  const { FrameParser } = require('./session-protocol');
26
- const { newSessionId } = require('./session-handle');
26
+ const { newSessionId } = require('./session-id');
27
27
  const { makeDeviceCall } = require('./device-call');
28
28
  const { safeObserve: guardObserve } = require('../observe/recorder');
29
29
  const { FLUSH_INTERVAL_MS } = require('../observe/flush');
@@ -272,7 +272,9 @@ async function startDaemon({
272
272
  let call;
273
273
  let close;
274
274
  try {
275
- ({ call, close } = await createCall({ device, engine, onEngineExit }));
275
+ // projectRoot lets the engine run from the root with root-relative paths in
276
+ // its argv and MOBILECLI_PATH, so `ps` never shows the project path (#236).
277
+ ({ call, close } = await createCall({ device, engine, projectRoot, onEngineExit }));
276
278
  } catch (err) {
277
279
  // #156's core symptom: mobile-mcp never came up, and until now the only
278
280
  // trace was a 15s readiness timeout in the spawning verb.
@@ -1,9 +1,10 @@
1
1
  'use strict';
2
2
 
3
- // Read side of mobile-automator/.session/session.json — the ONLY one — plus the
4
- // generator for the session id it carries. resolve-connection.js's
5
- // readHandleDevice() is a projection onto the `device` field and delegates here;
6
- // it used to parse the file itself, which meant two readers of one artifact.
3
+ // Read side of mobile-automator/.session/session.json — the ONLY one. The
4
+ // session id it carries is minted, and its shape defined, in session-id.js.
5
+ // resolve-connection.js's readHandleDevice() is a projection onto the `device`
6
+ // field and delegates here; it used to parse the file itself, which meant two
7
+ // readers of one artifact.
7
8
  //
8
9
  // The handle is where session_id lives because it is a file that is ALREADY
9
10
  // there, already written at exactly the right moment (once the daemon is
@@ -16,24 +17,9 @@
16
17
  // session", which is a normal state, not an error.
17
18
 
18
19
  const realFs = require('fs');
19
- const crypto = require('crypto');
20
20
 
21
21
  const { handlePath } = require('./session-paths');
22
- const { SESSION_ID_PATTERN } = require('../observe/event');
23
-
24
- // 16 hex chars from the CSPRNG, derived from NOTHING — not the project root,
25
- // not the device, not the pid. That is what makes the event catalog's
26
- // `sends: true` on session_id true rather than merely asserted, and
27
- // tests/unit/device/session-handle.test.js is where the claim is enforced.
28
- // readSessionId() holds the read side to the same shape (SESSION_ID_PATTERN).
29
- //
30
- // Deliberately NOT persisted across daemon restarts. A stable id would be a
31
- // machine fingerprint; this one changes exactly when the daemon does, which is
32
- // the fact it exists to report — run_id cannot express "the daemon died and
33
- // respawned mid-run".
34
- function newSessionId() {
35
- return crypto.randomBytes(8).toString('hex');
36
- }
22
+ const { SESSION_ID_PATTERN } = require('./session-id');
37
23
 
38
24
  function readHandle(projectRoot, { fs = realFs } = {}) {
39
25
  try {
@@ -50,4 +36,4 @@ function readSessionId(projectRoot, { fs = realFs } = {}) {
50
36
  return typeof id === 'string' && SESSION_ID_PATTERN.test(id) ? id : null;
51
37
  }
52
38
 
53
- module.exports = { newSessionId, readHandle, readSessionId };
39
+ module.exports = { readHandle, readSessionId };
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ // The session id: the function that mints it and the shape it is minted in.
4
+ //
5
+ // This is its own module, rather than living beside the handle reader in
6
+ // session-handle.js, because the event catalog (src/observe/event.js) imports
7
+ // the shape — and so this module must import nothing local. The device layer
8
+ // already imports observe/ (session-daemon.js, failure-probe.js,
9
+ // mobile-mcp-client.js); if anything on this module's require path ever
10
+ // reached back into observe/, the cycle could hand event.js a half-built
11
+ // exports object with SESSION_ID_PATTERN still undefined. The session_id check
12
+ // would then throw when telemetryPayload() runs it, and safeObserve
13
+ // (src/observe/recorder.js) swallows that — session_id telemetry would vanish
14
+ // with nothing failing. Requiring only `crypto` makes that impossible, and
15
+ // tests/lint/session-id-pure.test.js keeps it that way (#196).
16
+
17
+ const crypto = require('crypto');
18
+
19
+ // 16 hex chars from the CSPRNG, derived from NOTHING — not the project root,
20
+ // not the device, not the pid. That is what makes the event catalog's
21
+ // `sends: true` on session_id true rather than merely asserted, and
22
+ // tests/unit/device/session-id.test.js is where the claim is enforced.
23
+ // session-handle.readSessionId() holds the read side to the same shape
24
+ // (SESSION_ID_PATTERN).
25
+ //
26
+ // Deliberately NOT persisted across daemon restarts. A stable id would be a
27
+ // machine fingerprint; this one changes exactly when the daemon does, which is
28
+ // the fact it exists to report — run_id cannot express "the daemon died and
29
+ // respawned mid-run".
30
+ function newSessionId() {
31
+ return crypto.randomBytes(8).toString('hex');
32
+ }
33
+
34
+ // The shape of what newSessionId() mints (8 CSPRNG bytes as hex) and the only
35
+ // shape readSessionId() will return. The handle file is just a file, so the
36
+ // shape is what keeps `sends: true` true for a stale or hand-edited one. It
37
+ // lives here, with its minter; the event catalog imports it (#196).
38
+ const SESSION_ID_PATTERN = /^[0-9a-f]{16}$/;
39
+
40
+ module.exports = { SESSION_ID_PATTERN, newSessionId };
@@ -7,10 +7,15 @@
7
7
  // daemon.pid — pidfile written once the daemon is listening
8
8
  // session.json — handle describing the live session (device pin, socket, pid)
9
9
  // daemon.log — bounded stdout/stderr capture from the detached daemon
10
+ // marker.salt — per-workspace secret salting the daemon's argv marker
11
+ // (#236); created once (session-salt.js), never rotated or
12
+ // deleted by any teardown
10
13
  //
11
14
  // These are intentionally side-effect-free so they can be unit-tested without
12
- // touching the filesystem.
15
+ // touching the filesystem. argvPath is the one exception: it reads realpaths,
16
+ // but never writes.
13
17
 
18
+ const fs = require('fs');
14
19
  const path = require('path');
15
20
  const os = require('os');
16
21
  const crypto = require('crypto');
@@ -21,6 +26,7 @@ const PID_NAME = 'daemon.pid';
21
26
  const HANDLE_NAME = 'session.json';
22
27
  const LOCK_NAME = 'daemon.lock';
23
28
  const LOG_NAME = 'daemon.log';
29
+ const SALT_NAME = 'marker.salt';
24
30
 
25
31
  // Unix domain socket paths have a hard length limit (~104 bytes on macOS,
26
32
  // ~108 on Linux). Deep project roots blow past it, so when the in-workspace
@@ -44,12 +50,16 @@ function workspaceSocketPath(projectRoot) {
44
50
  function socketPath(projectRoot) {
45
51
  const inWorkspace = workspaceSocketPath(projectRoot);
46
52
  if (Buffer.byteLength(inWorkspace) <= SOCKET_PATH_LIMIT) return inWorkspace;
47
- const hash = crypto
48
- .createHash('sha1')
49
- .update(path.resolve(projectRoot))
50
- .digest('hex')
51
- .slice(0, 16);
52
- return path.join(os.tmpdir(), `mauto-${hash}.sock`);
53
+ return path.join(os.tmpdir(), `mauto-${workspaceKey(projectRoot)}.sock`);
54
+ }
55
+
56
+ // A short, deterministic name for a workspace: the first 16 hex chars of
57
+ // sha1(resolved project root). It names ONLY the tmpdir socket fallback above.
58
+ // It is unsalted, so anyone who guesses the root can compute it; the daemon's
59
+ // argv marker uses daemonMarkerKey below instead (#236). Changing it moves the
60
+ // socket a running daemon is bound to, so its output is pinned by tests.
61
+ function workspaceKey(projectRoot) {
62
+ return crypto.createHash('sha1').update(path.resolve(projectRoot)).digest('hex').slice(0, 16);
53
63
  }
54
64
 
55
65
  // Deliberately has no os.tmpdir() fallback, unlike socketPath(). That fallback
@@ -68,6 +78,12 @@ function handlePath(projectRoot) {
68
78
  return path.join(sessionDir(projectRoot), HANDLE_NAME);
69
79
  }
70
80
 
81
+ // The per-workspace salt for the daemon's argv marker (#236). Read and created
82
+ // by session-salt.js; this module stays free of IO.
83
+ function saltPath(projectRoot) {
84
+ return path.join(sessionDir(projectRoot), SALT_NAME);
85
+ }
86
+
71
87
  // Exclusive workspace lock acquired BEFORE building the mobile-mcp connection so
72
88
  // a double-spawn loser fails fast and exits before it ever spawns a child.
73
89
  function lockPath(projectRoot) {
@@ -80,18 +96,76 @@ function lockPath(projectRoot) {
80
96
  // marker is what lets `session end` tell THIS workspace's daemon from another
81
97
  // workspace's before it signals a process group: a copied workspace (`cp -R`
82
98
  // carries daemon.pid) or a recycled pid can name a different live daemon.
83
- // The root is the LAST argument so a match can be anchored at the end.
84
- const DAEMON_ROOT_FLAG = '--project-root';
99
+ //
100
+ // The marker is a SALTED key, not the path (#236). `ps` shows every process's
101
+ // argv to every user on the host, and a project path can name a client or an
102
+ // unreleased project. An unsalted digest would not hide it: another user can
103
+ // guess `/Users/alice/clients/acme-app`, hash it, and compare. So the key is
104
+ // HMAC-SHA256(salt, resolved root), where the salt is a per-workspace secret in
105
+ // .session/marker.salt (mode 0600, session-salt.js). Both inputs are needed:
106
+ // - the salt makes the key unconfirmable by anyone who cannot read the
107
+ // workspace;
108
+ // - the root keeps `cp -R` safe: a copied workspace carries the salt AND
109
+ // daemon.pid, but its root differs, so the original daemon's key never
110
+ // names the copy.
111
+ // Losing the salt strands nothing new: it lives beside daemon.pid, so whatever
112
+ // removes one removes the other. The daemon never reads its argv. The key is
113
+ // the LAST argument so a match can be anchored at the end.
114
+ const DAEMON_WORKSPACE_FLAG = '--workspace-key';
115
+
116
+ // Match-only, never emitted. Daemons started by 0.28.0-0.35.0 carry the
117
+ // absolute root behind this flag; still recognising them keeps a stuck one
118
+ // force-stoppable by `session end` after an upgrade.
119
+ const LEGACY_DAEMON_ROOT_FLAG = '--project-root';
85
120
 
86
- function daemonArgv(projectRoot) {
87
- return [DAEMON_ROOT_FLAG, path.resolve(projectRoot)];
121
+ function daemonMarkerKey(projectRoot, salt) {
122
+ return crypto.createHmac('sha256', String(salt)).update(path.resolve(projectRoot)).digest('hex').slice(0, 16);
88
123
  }
89
124
 
90
- // Does a `ps -o command=` line name exactly this workspace? Anchored at the end
91
- // of the line so `/a/proj` never matches a daemon serving `/a/proj2`.
92
- function commandNamesWorkspace(command, projectRoot) {
125
+ function daemonArgv(projectRoot, salt) {
126
+ return [DAEMON_WORKSPACE_FLAG, daemonMarkerKey(projectRoot, salt)];
127
+ }
128
+
129
+ // Does a `ps -o command=` line name exactly this workspace, by salted key or by
130
+ // the legacy root? The key form needs the workspace's salt: with none (missing
131
+ // or unreadable) no keyed daemon can be proven ours. The legacy form needs no
132
+ // salt. Anchored at the end of the line so `/a/proj` never matches a daemon
133
+ // serving `/a/proj2`, and a key never matches a longer or shorter one.
134
+ function commandNamesWorkspace(command, projectRoot, salt = null) {
93
135
  const line = String(command || '').replace(/\s+$/, '');
94
- return line.endsWith(` ${DAEMON_ROOT_FLAG} ${path.resolve(projectRoot)}`);
136
+ if (salt != null && line.endsWith(` ${DAEMON_WORKSPACE_FLAG} ${daemonMarkerKey(projectRoot, salt)}`)) return true;
137
+ return line.endsWith(` ${LEGACY_DAEMON_ROOT_FLAG} ${path.resolve(projectRoot)}`);
138
+ }
139
+
140
+ // A path as it should appear in a child's argv (or an env var the child execs
141
+ // by) (#236). `ps` shows every process's argv to every user on the host, and
142
+ // when mobile-automator is installed inside the project (a devDependency, a
143
+ // source checkout) the absolute paths of the daemon bin, the engine entry and
144
+ // mobilecli all contain the project root, which often names a client. A file
145
+ // under the root is returned relative to it; the caller MUST run the child with
146
+ // cwd = projectRoot, or the relative path resolves somewhere else. A file
147
+ // outside the root (a global install) is returned unchanged: it reveals no
148
+ // project path.
149
+ //
150
+ // Both sides are compared by realpath, so a root reached through a symlink
151
+ // (macOS /tmp vs /private/tmp, a symlinked checkout) still gets the relative
152
+ // form, and the result is relative to the REAL root, which is what the child's
153
+ // cwd resolves to. A path that cannot be realpath'd (it does not exist yet, or
154
+ // in unit tests) falls back to path.resolve. "Under" is strict: the root itself
155
+ // is not under it, and a sibling sharing its prefix (/a/proj2 vs /a/proj) is
156
+ // outside it.
157
+ function realOrResolved(p) {
158
+ try {
159
+ return fs.realpathSync(p);
160
+ } catch (_e) {
161
+ return path.resolve(p);
162
+ }
163
+ }
164
+
165
+ function argvPath(projectRoot, absPath) {
166
+ const rel = path.relative(realOrResolved(projectRoot), realOrResolved(absPath));
167
+ if (!rel || path.isAbsolute(rel) || rel === '..' || rel.startsWith('..' + path.sep)) return absPath;
168
+ return rel;
95
169
  }
96
170
 
97
171
  module.exports = {
@@ -101,6 +175,7 @@ module.exports = {
101
175
  HANDLE_NAME,
102
176
  LOCK_NAME,
103
177
  LOG_NAME,
178
+ SALT_NAME,
104
179
  SOCKET_PATH_LIMIT,
105
180
  sessionDir,
106
181
  workspaceSocketPath,
@@ -109,7 +184,12 @@ module.exports = {
109
184
  pidFilePath,
110
185
  handlePath,
111
186
  lockPath,
112
- DAEMON_ROOT_FLAG,
187
+ saltPath,
188
+ workspaceKey,
189
+ daemonMarkerKey,
190
+ DAEMON_WORKSPACE_FLAG,
191
+ LEGACY_DAEMON_ROOT_FLAG,
113
192
  daemonArgv,
114
193
  commandNamesWorkspace,
194
+ argvPath,
115
195
  };
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+
3
+ // The per-workspace salt behind the daemon's argv marker (#236).
4
+ //
5
+ // `ps` shows every process's argv to every user on the host, so the daemon's
6
+ // command line carries HMAC(salt, root) (session-paths.daemonMarkerKey) rather
7
+ // than a digest anyone could recompute from a guessed project path. The salt is
8
+ // 32 random bytes as hex in <root>/mobile-automator/.session/marker.salt, mode
9
+ // 0600 so only the workspace's owner can read it. It is created once and never
10
+ // rotated: rotating it would orphan a running daemon's marker, and no teardown
11
+ // deletes it (cleanStale, daemon stop and the bin's exit cleanup all unlink
12
+ // named files only).
13
+ //
14
+ // Kept out of session-paths.js so that module stays free of IO.
15
+
16
+ const realFs = require('fs');
17
+ const path = require('path');
18
+ const crypto = require('crypto');
19
+
20
+ const paths = require('./session-paths');
21
+
22
+ // The salt, or null when it is missing, unreadable or empty. Any other content
23
+ // IS the salt: an HMAC key needs no particular shape, so there is no
24
+ // "malformed" salt to detect or repair. A null salt means no keyed daemon can
25
+ // be proven this workspace's (commandNamesWorkspace).
26
+ function readSalt(projectRoot, { fs = realFs } = {}) {
27
+ try {
28
+ return String(fs.readFileSync(paths.saltPath(projectRoot), 'utf8')).trim() || null;
29
+ } catch (_) {
30
+ return null;
31
+ }
32
+ }
33
+
34
+ // The salt, created if this workspace has none yet. Throws when it can neither
35
+ // read nor create one: an unwritable workspace, or an empty salt file, which
36
+ // only a hand edit makes and which is never replaced behind a running
37
+ // daemon's back.
38
+ //
39
+ // Race-free without a lock: the salt is written and fsynced in full to a
40
+ // private temp file, then link(2)ed to its final name. link never replaces an
41
+ // existing file, so exactly one of several concurrent spawners wins; every
42
+ // loser gets EEXIST and reads the winner's salt, which was complete before it
43
+ // became visible. A reader therefore never sees a half-written salt. (The
44
+ // rename in util/atomic.js would not do: it replaces, so two racers could each
45
+ // hand back a different salt.)
46
+ function ensureSalt(projectRoot, { fs = realFs } = {}) {
47
+ const existing = readSalt(projectRoot, { fs });
48
+ if (existing) return existing;
49
+
50
+ const file = paths.saltPath(projectRoot);
51
+ fs.mkdirSync(path.dirname(file), { recursive: true });
52
+ const tmp = path.join(
53
+ path.dirname(file),
54
+ `.${path.basename(file)}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`
55
+ );
56
+ const salt = crypto.randomBytes(32).toString('hex');
57
+ try {
58
+ const fd = fs.openSync(tmp, 'wx', 0o600);
59
+ try {
60
+ fs.writeFileSync(fd, `${salt}\n`);
61
+ fs.fsyncSync(fd);
62
+ } finally {
63
+ fs.closeSync(fd);
64
+ }
65
+ try {
66
+ fs.linkSync(tmp, file);
67
+ return salt;
68
+ } catch (err) {
69
+ if (err.code !== 'EEXIST') throw err;
70
+ }
71
+ // Another process won the race; its salt was complete before it was linked.
72
+ const theirs = readSalt(projectRoot, { fs });
73
+ if (theirs) return theirs;
74
+ throw new Error(`the session marker salt at ${file} is empty; delete it and retry`);
75
+ } finally {
76
+ try {
77
+ fs.unlinkSync(tmp);
78
+ } catch (_) {
79
+ /* never created */
80
+ }
81
+ }
82
+ }
83
+
84
+ module.exports = { ensureSalt, readSalt };
@@ -13,6 +13,7 @@ const childProcess = require('child_process');
13
13
  const sessionClient = require('./session-client');
14
14
  const sessionLog = require('./session-log');
15
15
  const paths = require('./session-paths');
16
+ const sessionSalt = require('./session-salt');
16
17
  const reaper = require('./process-reaper');
17
18
 
18
19
  const DAEMON_BIN = path.join(__dirname, '..', '..', 'bin', 'mauto-session-daemon.js');
@@ -38,6 +39,9 @@ async function spawnDaemon({
38
39
  pollMs = DEFAULT_POLL_MS,
39
40
  isAlive = sessionClient.isAlive,
40
41
  openLog = sessionLog.openDaemonLog,
42
+ // Reads or creates the workspace's marker salt (#236). Injectable so the
43
+ // spawn args are testable without a writable workspace.
44
+ ensureSalt = sessionSalt.ensureSalt,
41
45
  // Kills a daemon that never became ready (#156). group:true reaches the
42
46
  // daemon AND its mobile-mcp engine: `detached: true` below makes the daemon
43
47
  // a process-group leader, and the engine is spawned into its group.
@@ -63,14 +67,31 @@ async function spawnDaemon({
63
67
  const log = openLog(projectRoot);
64
68
 
65
69
  try {
66
- // The root in argv is an identity marker only (see paths.daemonArgv): env
67
- // stays the daemon's source of truth, but `ps` can only see argv.
70
+ // The workspace key in argv is an identity marker only (see paths.daemonArgv):
71
+ // env stays the daemon's source of truth, but `ps` can only see argv. It is
72
+ // salted with the workspace's own secret, so `ps` readers cannot confirm a
73
+ // guessed path by hashing it (#236). A salt we can neither read nor create
74
+ // fails the spawn, like a bin that cannot exec: a daemon with no marker is
75
+ // one `session end` can never force-stop, and a workspace that cannot hold
76
+ // the salt cannot hold the daemon's own lock and pidfile either. No
77
+ // argument names the project path, since `ps` shows argv to every user on
78
+ // the host (#236): an in-project bin is passed relative to the root
79
+ // (paths.argvPath), which only resolves because the child's cwd IS that
80
+ // root. One `cwd` feeds both, so the two cannot drift apart.
68
81
  // cwd: the engine inherits the daemon's cwd, and mobile-mcp's
69
82
  // validateOutputPath only allows screenshots under its own process.cwd()
70
83
  // (or the temp dir). Pin it to the project root so the allow-list never
71
84
  // depends on which subdirectory happened to spawn the daemon (#214).
72
- const child = spawn(process.execPath, [DAEMON_BIN, ...paths.daemonArgv(projectRoot)], {
73
- cwd: projectRoot,
85
+ let marker;
86
+ try {
87
+ marker = paths.daemonArgv(projectRoot, ensureSalt(projectRoot));
88
+ } catch (err) {
89
+ log.write(`mauto: daemon not spawned: could not create the session marker salt: ${err && err.message ? err.message : err}\n`);
90
+ return false;
91
+ }
92
+ const cwd = projectRoot;
93
+ const child = spawn(process.execPath, [paths.argvPath(cwd, DAEMON_BIN), ...marker], {
94
+ cwd,
74
95
  detached: true,
75
96
  stdio: log.stdio,
76
97
  env,
@@ -40,16 +40,13 @@ const { ERROR_KINDS } = require('../output/envelope');
40
40
  // Pure module with no requires, so this adds no cycle. It is THE closed set of
41
41
  // mobile-mcp primitive names and must not be restated here.
42
42
  const { MOBILE_MCP_TOOL_NAMES } = require('../device/mobile-mcp-tools');
43
+ // Pure: requires only crypto, so this adds no cycle — and
44
+ // tests/lint/session-id-pure.test.js keeps it that way. The shape is owned by
45
+ // its minter (#196).
46
+ const { SESSION_ID_PATTERN } = require('../device/session-id');
43
47
 
44
48
  const EVENT_VERSION = 1;
45
49
 
46
- // The shape of a session_id: what session-handle.newSessionId() mints (8 CSPRNG
47
- // bytes as hex) and the only shape readSessionId() will return. session_id is
48
- // sends:true on the grounds that it is random and carries no user content; the
49
- // handle file it is read back from is just a file, so the shape is what keeps
50
- // that true for a stale or hand-edited one.
51
- const SESSION_ID_PATTERN = /^[0-9a-f]{16}$/;
52
-
53
50
  // Ascending severity. Index order is the comparison order.
54
51
  const LEVELS = ['debug', 'info', 'warn', 'error'];
55
52
 
@@ -88,14 +85,15 @@ const EVENT_FIELDS = {
88
85
  dur_ms: sendable(integer({ min: 0 }), 'duration; carries no user content'),
89
86
 
90
87
  // --- daemon ------------------------------------------------------------
91
- // Random per-daemon-lifetime id, generated by session-handle.newSessionId()
88
+ // Random per-daemon-lifetime id, generated by session-id.newSessionId()
92
89
  // from crypto.randomBytes and derived from NOTHING — not the project root,
93
90
  // not the device, not the pid. Deliberately NOT persisted across restarts: a
94
91
  // stable id would be a machine fingerprint, whereas this one changes exactly
95
92
  // when the daemon does, which is the fact it exists to report. Enforced on
96
- // the mint side by tests/unit/device/session-handle.test.js and on the read
97
- // side by readSessionId() checking SESSION_ID_PATTERN — and at the wire by
98
- // the same pattern, so a stale or hand-edited handle file cannot ship text.
93
+ // the mint side by tests/unit/device/session-id.test.js, on the read side by
94
+ // session-handle.readSessionId() checking session-id's SESSION_ID_PATTERN,
95
+ // and at the wire by the same imported pattern, so a stale or hand-edited
96
+ // handle file cannot ship text.
99
97
  session_id: sendable(matches(SESSION_ID_PATTERN, 'csprng'), 'random id scoped to one daemon lifetime; no user-derived content'),
100
98
  // As with `verb`, the justification holds only because the value is enforced
101
99
  // to be one: src/device/device-call.js records this field ONLY when
@@ -230,7 +228,6 @@ function telemetryPayload(event = {}) {
230
228
 
231
229
  module.exports = {
232
230
  EVENT_VERSION,
233
- SESSION_ID_PATTERN,
234
231
  LEVELS,
235
232
  EVENT_FIELDS,
236
233
  NEVER_SENDS,