@farmslot/adapter-web 0.19.7 → 0.19.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/web-dapp/index.d.mts +1 -1
- package/dist/web-dapp/lib/blind-browser.d.mts +9 -0
- package/dist/web-dapp/lib/native-proc-args.d.mts +8 -0
- package/dist/web-dapp/lib/process-info.d.mts +3 -0
- package/dist/web-dapp/lib/processes.d.mts +4 -3
- package/dist/web-dapp/lib/python.d.mts +6 -0
- package/dist/web-dapp/lib/readiness.d.mts +1 -5
- package/package.json +3 -3
- package/src/web-dapp/index.mjs +4 -1
- package/src/web-dapp/launch.mjs +14 -4
- package/src/web-dapp/lib/blind-browser.mjs +36 -0
- package/src/web-dapp/lib/native-proc-args.mjs +63 -0
- package/src/web-dapp/lib/process-info.mjs +77 -0
- package/src/web-dapp/lib/processes.mjs +46 -33
- package/src/web-dapp/lib/python.mjs +34 -0
- package/src/web-dapp/lib/readiness.mjs +3 -59
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,15 @@ All notable changes to `@farmslot/adapter-web` are tracked here.
|
|
|
6
6
|
|
|
7
7
|
- Active-development baseline; add user-facing changes here before release or package publication.
|
|
8
8
|
|
|
9
|
+
## 0.19.9 - 2026-11-13
|
|
10
|
+
|
|
11
|
+
- Republish against recipe-runner 0.46.14 so consumers load one copy of it, with blind Mobile CDP broker sockets routed into the trial directory.
|
|
12
|
+
|
|
13
|
+
## 0.19.8 - 2026-11-12
|
|
14
|
+
|
|
15
|
+
- Launch blind trial browsers on their allocated recipe CDP endpoint while configured slot endpoints remain protected.
|
|
16
|
+
- Inspect owned browser processes without setuid ps, recheck authorized process identities before teardown, reject unusable Python helpers without opening install dialogs, and launch blind-trial Chrome directly under the verified outer seatbelt.
|
|
17
|
+
|
|
9
18
|
## 0.19.7 - 2026-11-10
|
|
10
19
|
|
|
11
20
|
- Republish against recipe-runner 0.46.12 so consumers load one copy of it, with the fixed-element visibility fix.
|
|
@@ -123,7 +123,7 @@ export { hostOf, hostResolverRules, isBlockedUrl } from "./lib/blocked-hosts.mjs
|
|
|
123
123
|
export { browserWebSocketUrl, CdpClient } from "./lib/cdp-client.mjs";
|
|
124
124
|
export { recipeHarnessPath, recipeRuntimeDir, recipeRuntimePath, shellQuote, walletFixturePath } from "./lib/paths.mjs";
|
|
125
125
|
export { assertPolicyDigest, fencePolicy, POLICY_DIGEST_ENV, PolicyFenceError } from "./lib/policy-fence.mjs";
|
|
126
|
-
export { cdpListenerPids, ownedBrowserPids, OWNER_FLAG, OWNER_KINDS, ownerMarker, ownsProcess, pidAlive, portFree, stopConsoleCollector, stopWebDappBrowser, terminate } from "./lib/processes.mjs";
|
|
126
|
+
export { cdpListenerPids, ownedBrowserPids, ownedProcessIdentity, OWNER_FLAG, OWNER_KINDS, ownerMarker, ownsProcess, pidAlive, portFree, stopConsoleCollector, stopWebDappBrowser, terminate } from "./lib/processes.mjs";
|
|
127
127
|
export { assertLaunchNetwork, DEV_SERVER_PID_FILE, devServerTestnetDiagnostic, pythonFor, webDappReadiness } from "./lib/readiness.mjs";
|
|
128
128
|
export { accountName, appOrigin, appPort, canonicalPath, cdpPort, DEFAULT_ACCOUNT, DERIVED_ACCOUNTS_ENV, fixtureAccount, fixtureEntry, fixturePath, loadWalletFixture, readBrowserState, readJsonFile, resolveAccountAddress, resolveSigner, SIGNER_MODES, viemAccountFromEntry, walletAccount, walletAccounts, webDappRuntimeDir, webDappRuntimePath, writePrivateJson } from "./lib/runtime.mjs";
|
|
129
129
|
export { macosSessionLocked, parseSessionLocked, SESSION_LOCKED_MESSAGE, SESSION_LOCKED_USER_ACTION } from "./lib/session-lock.mjs";
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export function blindBrowserOptions(env: any, { platform, sandboxed }?: {
|
|
2
|
+
platform?: NodeJS.Platform | undefined;
|
|
3
|
+
sandboxed?: typeof activeSeatbelt | undefined;
|
|
4
|
+
}): {
|
|
5
|
+
args: string[];
|
|
6
|
+
direct: boolean;
|
|
7
|
+
};
|
|
8
|
+
declare function activeSeatbelt(): boolean;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function runNativeProcessProbe(source: any, pid: any, { python }?: {
|
|
2
|
+
python?: typeof usablePython | undefined;
|
|
3
|
+
}): any;
|
|
4
|
+
export function readNativeProcArgs(pid: any, { includeEnvironment }?: {
|
|
5
|
+
includeEnvironment?: boolean | undefined;
|
|
6
|
+
}): any;
|
|
7
|
+
export const NATIVE_PROC_ARGS: string;
|
|
8
|
+
import { usablePython } from './python.mjs';
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
export function pidAlive(pid: any): boolean;
|
|
2
|
-
export function processCommand(pid: any):
|
|
2
|
+
export function processCommand(pid: any): any;
|
|
3
3
|
export function ownerMarker(kind: any, runtimeDir: any): string;
|
|
4
|
-
export function ownsProcess(kind: any, pid: any, runtimeDir: any, command
|
|
4
|
+
export function ownsProcess(kind: any, pid: any, runtimeDir: any, command: any): any;
|
|
5
|
+
export function ownedProcessIdentity(kind: any, pid: any, runtimeDir: any): any;
|
|
5
6
|
export function portFree(port: any): Promise<any>;
|
|
6
|
-
export function terminate(pid: any, graceMs
|
|
7
|
+
export function terminate(pid: any, graceMs: number | undefined, identity: any): Promise<boolean>;
|
|
7
8
|
/**
|
|
8
9
|
* @param {string} target
|
|
9
10
|
* @param {{ log?: (message: string) => void, runtimeDir?: string }} [options]
|
|
@@ -13,11 +13,6 @@ export function check(id: string, ok: boolean, detail: string, { required, statu
|
|
|
13
13
|
required: boolean;
|
|
14
14
|
detail: string;
|
|
15
15
|
};
|
|
16
|
-
export function pythonFor({ found, platform, developerDir }: {
|
|
17
|
-
found: any;
|
|
18
|
-
platform?: NodeJS.Platform | undefined;
|
|
19
|
-
developerDir: any;
|
|
20
|
-
}): any;
|
|
21
16
|
export function environmentValue(env: any, name: any): any;
|
|
22
17
|
export function nextServerMode(argv: any): any;
|
|
23
18
|
/**
|
|
@@ -82,4 +77,5 @@ export const systemProbe: Readonly<{
|
|
|
82
77
|
cwd: (pid: any) => any;
|
|
83
78
|
procArgs: (pid: any) => any;
|
|
84
79
|
}>;
|
|
80
|
+
export { pythonFor } from "./python.mjs";
|
|
85
81
|
export const MAINNET_CONFIRMATION: "REAL_FUNDS";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@farmslot/adapter-web",
|
|
3
|
-
"version": "0.19.
|
|
3
|
+
"version": "0.19.9",
|
|
4
4
|
"description": "Web platform adapter for Farmslot recipes: resolve and launch an isolated Chromium, own its CDP port, load unpacked extensions, and keep macOS focus.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"exports": {
|
|
@@ -87,9 +87,9 @@
|
|
|
87
87
|
"prepublishOnly": "node ../../scripts/quality/check-farmslot-package-readiness.mjs --publish --packages @farmslot/adapter-web"
|
|
88
88
|
},
|
|
89
89
|
"dependencies": {
|
|
90
|
-
"@farmslot/adapter-sdk": "0.27.
|
|
90
|
+
"@farmslot/adapter-sdk": "0.27.4",
|
|
91
91
|
"@farmslot/protocol": "0.83.1",
|
|
92
|
-
"@farmslot/recipe-runner": "0.46.
|
|
92
|
+
"@farmslot/recipe-runner": "0.46.14",
|
|
93
93
|
"ws": "^8.18.0"
|
|
94
94
|
},
|
|
95
95
|
"devDependencies": {
|
package/src/web-dapp/index.mjs
CHANGED
|
@@ -66,6 +66,7 @@ export {
|
|
|
66
66
|
export {
|
|
67
67
|
cdpListenerPids,
|
|
68
68
|
ownedBrowserPids,
|
|
69
|
+
ownedProcessIdentity,
|
|
69
70
|
OWNER_FLAG,
|
|
70
71
|
OWNER_KINDS,
|
|
71
72
|
ownerMarker,
|
|
@@ -470,7 +471,9 @@ export function createWebDappAdapter(factoryOptions = {}) {
|
|
|
470
471
|
async launch({ options, target, jsonOutput, stream, usage }) {
|
|
471
472
|
const adapterId = webDappAdapterId();
|
|
472
473
|
const cdpPort =
|
|
473
|
-
|
|
474
|
+
process.env.FARMSLOT_BLIND_SEATBELT === '1'
|
|
475
|
+
? process.env.RECIPE_CDP_PORT
|
|
476
|
+
: (str(options, 'cdpPort') ?? process.env.RECIPE_CDP_PORT ?? process.env.CDP_PORT);
|
|
474
477
|
// Same precedence as the web-dapp surface and live actions.
|
|
475
478
|
const appPort =
|
|
476
479
|
str(options, 'watcherPort') ??
|
package/src/web-dapp/launch.mjs
CHANGED
|
@@ -48,6 +48,7 @@ import { fileURLToPath } from 'node:url';
|
|
|
48
48
|
|
|
49
49
|
import { disableMacCodeSignClone } from '../chrome-args.cjs';
|
|
50
50
|
|
|
51
|
+
import { blindBrowserOptions } from './lib/blind-browser.mjs';
|
|
51
52
|
import { hostResolverRules } from './lib/blocked-hosts.mjs';
|
|
52
53
|
import { browserWebSocketUrl, CdpClient } from './lib/cdp-client.mjs';
|
|
53
54
|
import {
|
|
@@ -61,6 +62,7 @@ import { clearHudState } from './lib/hud.mjs';
|
|
|
61
62
|
import {
|
|
62
63
|
cdpListenerPids,
|
|
63
64
|
ownedBrowserPids,
|
|
65
|
+
ownedProcessIdentity,
|
|
64
66
|
ownerMarker,
|
|
65
67
|
ownsProcess,
|
|
66
68
|
pidAlive,
|
|
@@ -239,7 +241,8 @@ async function launchInBackground(
|
|
|
239
241
|
}
|
|
240
242
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
241
243
|
}
|
|
242
|
-
for (const pid of ownedBrowserPids(runtime))
|
|
244
|
+
for (const pid of ownedBrowserPids(runtime))
|
|
245
|
+
await terminate(pid, 3000, ownedProcessIdentity('browser', pid, runtime));
|
|
243
246
|
throw new Error(
|
|
244
247
|
`${path.basename(application)} started but no browser on this slot's profile listened on CDP ${cdpPort} within ${timeoutMs}ms.`,
|
|
245
248
|
);
|
|
@@ -407,6 +410,7 @@ export async function launchWebDappBrowser(
|
|
|
407
410
|
env = process.env,
|
|
408
411
|
{ timeouts = LAUNCH_TIMEOUTS, sessionLocked = macosSessionLocked } = {},
|
|
409
412
|
) {
|
|
413
|
+
const blindBrowser = blindBrowserOptions(env);
|
|
410
414
|
const policy = webDappPolicy(env);
|
|
411
415
|
const signerModule = args['signer-module'] ?? env[SIGNER_MODULE_ENV];
|
|
412
416
|
const signerHooks = await loadSigners({
|
|
@@ -426,7 +430,9 @@ export async function launchWebDappBrowser(
|
|
|
426
430
|
);
|
|
427
431
|
}
|
|
428
432
|
const target = path.resolve(args.target);
|
|
429
|
-
const cdpPort = Number(args['cdp-port']);
|
|
433
|
+
const cdpPort = Number(blindBrowser.direct ? env.RECIPE_CDP_PORT : args['cdp-port']);
|
|
434
|
+
if (!Number.isInteger(cdpPort) || cdpPort < 1 || cdpPort > 65535)
|
|
435
|
+
throw new Error('A valid browser CDP port is required; blind trials use RECIPE_CDP_PORT.');
|
|
430
436
|
const appPort = Number(args['app-port']);
|
|
431
437
|
const signer = args.signer;
|
|
432
438
|
// Mainnet needs the real-funds confirmation. Testnet is enforced inside the
|
|
@@ -509,6 +515,7 @@ export async function launchWebDappBrowser(
|
|
|
509
515
|
previous.account?.name === account.name &&
|
|
510
516
|
previous.account?.address?.toLowerCase() === account.address.toLowerCase() &&
|
|
511
517
|
previous.browser?.headless === headless &&
|
|
518
|
+
Boolean(previous.browser?.outerSeatbelt) === blindBrowser.direct &&
|
|
512
519
|
(previous.network ?? 'testnet') === network &&
|
|
513
520
|
previous.networkEnforcement?.fingerprint === enforcementFingerprint &&
|
|
514
521
|
ownsProcess('browser', previous.browserPid, runtime) &&
|
|
@@ -540,6 +547,7 @@ export async function launchWebDappBrowser(
|
|
|
540
547
|
writeProfileZoom(profile, placement?.zoom ?? 1);
|
|
541
548
|
|
|
542
549
|
const browserArgs = [
|
|
550
|
+
...blindBrowser.args,
|
|
543
551
|
`--user-data-dir=${profile}`,
|
|
544
552
|
'--remote-debugging-address=127.0.0.1',
|
|
545
553
|
`--remote-debugging-port=${cdpPort}`,
|
|
@@ -564,7 +572,7 @@ export async function launchWebDappBrowser(
|
|
|
564
572
|
return file;
|
|
565
573
|
};
|
|
566
574
|
let started = false;
|
|
567
|
-
const launchMethod = launchMethodFor(browser.bin);
|
|
575
|
+
const launchMethod = blindBrowser.direct ? SPAWN : launchMethodFor(browser.bin);
|
|
568
576
|
// Focus is checked for a visible browser started in the background.
|
|
569
577
|
const guardFocus = launchMethod === LAUNCH_SERVICES && !headless;
|
|
570
578
|
// With no startup window, windows are created over CDP at these bounds; a
|
|
@@ -774,6 +782,7 @@ export async function launchWebDappBrowser(
|
|
|
774
782
|
version: browser.version,
|
|
775
783
|
source: browser.source,
|
|
776
784
|
headless,
|
|
785
|
+
outerSeatbelt: blindBrowser.direct,
|
|
777
786
|
launchMethod,
|
|
778
787
|
},
|
|
779
788
|
window: placement,
|
|
@@ -793,7 +802,8 @@ export async function launchWebDappBrowser(
|
|
|
793
802
|
await stopWebDappBrowser(target, { cdpPort, log }).catch((stopError) =>
|
|
794
803
|
log(`rollback incomplete: ${stopError.message}`),
|
|
795
804
|
);
|
|
796
|
-
for (const pid of ownedBrowserPids(runtime))
|
|
805
|
+
for (const pid of ownedBrowserPids(runtime))
|
|
806
|
+
await terminate(pid, 3000, ownedProcessIdentity('browser', pid, runtime));
|
|
797
807
|
}
|
|
798
808
|
throw error;
|
|
799
809
|
} finally {
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
import { usablePython } from './python.mjs';
|
|
4
|
+
|
|
5
|
+
// This opt-in is supplied by the blind worker boundary, never a general Chrome
|
|
6
|
+
// flag. LaunchServices would delegate to an unsandboxed service, so spawn directly.
|
|
7
|
+
function activeSeatbelt() {
|
|
8
|
+
const python = usablePython();
|
|
9
|
+
if (!python) throw new Error('blind browser requires a usable python3');
|
|
10
|
+
return (
|
|
11
|
+
execFileSync(
|
|
12
|
+
python,
|
|
13
|
+
[
|
|
14
|
+
'-c',
|
|
15
|
+
`
|
|
16
|
+
import ctypes, os
|
|
17
|
+
lib = ctypes.CDLL('/usr/lib/libsandbox.dylib')
|
|
18
|
+
print(lib.sandbox_check(os.getpid(), None, 0))
|
|
19
|
+
`,
|
|
20
|
+
],
|
|
21
|
+
{ encoding: 'utf8', timeout: 2000 },
|
|
22
|
+
).trim() === '1'
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function blindBrowserOptions(
|
|
27
|
+
env,
|
|
28
|
+
{ platform = process.platform, sandboxed = activeSeatbelt } = {},
|
|
29
|
+
) {
|
|
30
|
+
const mode = env.FARMSLOT_BLIND_SEATBELT;
|
|
31
|
+
if (mode === undefined) return { args: [], direct: false };
|
|
32
|
+
if (mode !== '1') throw new Error('invalid blind seatbelt browser mode');
|
|
33
|
+
const active = platform === 'darwin' && sandboxed();
|
|
34
|
+
if (!active) throw new Error('blind browser needs an active macOS seatbelt');
|
|
35
|
+
return { args: ['--no-sandbox'], direct: true };
|
|
36
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Shared KERN_PROCARGS2 reader. Environment decoding is opt-in; ownership
|
|
2
|
+
// inspection never returns or decodes a process's environment.
|
|
3
|
+
import { execFileSync } from 'node:child_process';
|
|
4
|
+
|
|
5
|
+
import { usablePython } from './python.mjs';
|
|
6
|
+
|
|
7
|
+
export const NATIVE_PROC_ARGS = String.raw`
|
|
8
|
+
import ctypes, json, struct, sys
|
|
9
|
+
def read_native_proc_args(pid, include_environment=False):
|
|
10
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
11
|
+
argmax = ctypes.c_int()
|
|
12
|
+
size = ctypes.c_size_t(ctypes.sizeof(argmax))
|
|
13
|
+
if libc.sysctl((ctypes.c_int * 2)(1, 8), 2, ctypes.byref(argmax), ctypes.byref(size), None, 0):
|
|
14
|
+
raise OSError('cannot read argument limit')
|
|
15
|
+
buf = ctypes.create_string_buffer(argmax.value)
|
|
16
|
+
size = ctypes.c_size_t(argmax.value)
|
|
17
|
+
if libc.sysctl((ctypes.c_int * 3)(1, 49, pid), 3, buf, ctypes.byref(size), None, 0):
|
|
18
|
+
raise ProcessLookupError('process arguments are absent or unreadable')
|
|
19
|
+
raw = buf.raw[:size.value]
|
|
20
|
+
argc = struct.unpack('i', raw[:4])[0]
|
|
21
|
+
rest = raw[4:]
|
|
22
|
+
rest = rest[rest.index(b'\0') + 1:].lstrip(b'\0')
|
|
23
|
+
parts = rest.split(b'\0')
|
|
24
|
+
result = {'argv': [p.decode('utf-8', 'replace') for p in parts[:argc]]}
|
|
25
|
+
if include_environment:
|
|
26
|
+
env = []
|
|
27
|
+
for part in parts[argc:]:
|
|
28
|
+
if not part:
|
|
29
|
+
break
|
|
30
|
+
env.append(part.decode('utf-8', 'replace'))
|
|
31
|
+
result['env'] = env
|
|
32
|
+
return result
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
export function runNativeProcessProbe(source, pid, { python = usablePython } = {}) {
|
|
36
|
+
const interpreter = python();
|
|
37
|
+
if (!interpreter)
|
|
38
|
+
throw new Error(
|
|
39
|
+
'macOS process inspection requires a usable python3; install Python or Command Line Tools',
|
|
40
|
+
);
|
|
41
|
+
// Absent/denied identities are JSON null. Interpreter failures must propagate.
|
|
42
|
+
return JSON.parse(
|
|
43
|
+
execFileSync(interpreter, ['-c', source, String(pid)], {
|
|
44
|
+
encoding: 'utf8',
|
|
45
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
46
|
+
timeout: 2000,
|
|
47
|
+
}),
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function readNativeProcArgs(pid, { includeEnvironment = false } = {}) {
|
|
52
|
+
if (process.platform !== 'darwin') return null;
|
|
53
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return null;
|
|
54
|
+
return runNativeProcessProbe(
|
|
55
|
+
`${NATIVE_PROC_ARGS}
|
|
56
|
+
try:
|
|
57
|
+
print(json.dumps(read_native_proc_args(int(sys.argv[1]), ${includeEnvironment ? 'True' : 'False'})))
|
|
58
|
+
except (OSError, ValueError):
|
|
59
|
+
print('null')
|
|
60
|
+
`,
|
|
61
|
+
pid,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// /bin/ps is setuid on macOS and cannot execute inside a seatbelt. Inspect
|
|
2
|
+
// only same-UID processes with libproc + KERN_PROCARGS2, as the gateway does.
|
|
3
|
+
import { execFileSync } from 'node:child_process';
|
|
4
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
5
|
+
|
|
6
|
+
import { NATIVE_PROC_ARGS, runNativeProcessProbe } from './native-proc-args.mjs';
|
|
7
|
+
|
|
8
|
+
const MAC_PROCESS_INFO = String.raw`${NATIVE_PROC_ARGS}
|
|
9
|
+
import os
|
|
10
|
+
class BsdInfo(ctypes.Structure):
|
|
11
|
+
_fields_ = [(name, ctypes.c_uint32) for name in (
|
|
12
|
+
'flags', 'status', 'xstatus', 'pid', 'ppid', 'uid', 'gid', 'ruid',
|
|
13
|
+
'rgid', 'svuid', 'svgid', 'rfu')] + [
|
|
14
|
+
('comm', ctypes.c_char * 16), ('name', ctypes.c_char * 32)] + [
|
|
15
|
+
(name, ctypes.c_uint32) for name in ('nfiles', 'pgid', 'pjobc', 'tdev', 'tpgid')] + [
|
|
16
|
+
('nice', ctypes.c_int32), ('sec', ctypes.c_uint64), ('usec', ctypes.c_uint64)]
|
|
17
|
+
pid = int(sys.argv[1])
|
|
18
|
+
libproc = ctypes.CDLL('/usr/lib/libproc.dylib', use_errno=True)
|
|
19
|
+
def info():
|
|
20
|
+
value = BsdInfo()
|
|
21
|
+
if libproc.proc_pidinfo(pid, 3, 0, ctypes.byref(value), ctypes.sizeof(value)) != ctypes.sizeof(value):
|
|
22
|
+
raise ProcessLookupError('process is absent or unreadable')
|
|
23
|
+
if value.uid != os.getuid() or value.ruid != os.getuid():
|
|
24
|
+
raise PermissionError('foreign UID')
|
|
25
|
+
return value
|
|
26
|
+
try:
|
|
27
|
+
before = info()
|
|
28
|
+
argv = read_native_proc_args(pid)['argv']
|
|
29
|
+
after = info()
|
|
30
|
+
if (before.sec, before.usec) != (after.sec, after.usec):
|
|
31
|
+
raise ProcessLookupError('process identity changed')
|
|
32
|
+
print(json.dumps({'argv': argv, 'pgid': after.pgid, 'state': after.status,
|
|
33
|
+
'startedAt': str(after.sec) + ':' + str(after.usec)}))
|
|
34
|
+
except (OSError, ValueError):
|
|
35
|
+
# Unreadable or vanished identities cannot authorize a signal. No env is emitted.
|
|
36
|
+
print('null')
|
|
37
|
+
`;
|
|
38
|
+
|
|
39
|
+
export function processInfo(pid, { platform = process.platform, python } = {}) {
|
|
40
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return null;
|
|
41
|
+
if (platform === 'darwin') return runNativeProcessProbe(MAC_PROCESS_INFO, pid, { python });
|
|
42
|
+
try {
|
|
43
|
+
if (platform === 'linux') {
|
|
44
|
+
const root = `/proc/${pid}`;
|
|
45
|
+
if (statSync(root).uid !== process.getuid()) return null;
|
|
46
|
+
const before = readFileSync(`${root}/stat`, 'utf8').split(/.*\) /u)[1].split(' ');
|
|
47
|
+
const argv = readFileSync(`${root}/cmdline`, 'utf8').split('\0').slice(0, -1);
|
|
48
|
+
const after = readFileSync(`${root}/stat`, 'utf8').split(/.*\) /u)[1].split(' ');
|
|
49
|
+
if (before[19] !== after[19]) return null;
|
|
50
|
+
return { argv, pgid: Number(after[2]), state: after[0], startedAt: after[19] };
|
|
51
|
+
}
|
|
52
|
+
const row = execFileSync('ps', ['-ww', '-o', 'pgid=,stat=,lstart=,args=', '-p', String(pid)], {
|
|
53
|
+
encoding: 'utf8',
|
|
54
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
55
|
+
timeout: 2000,
|
|
56
|
+
}).trim();
|
|
57
|
+
const match = row.match(/^(\d+)\s+(\S+)\s+((?:\S+\s+){4}\S+)\s+(.+)$/u);
|
|
58
|
+
return match
|
|
59
|
+
? {
|
|
60
|
+
pgid: Number(match[1]),
|
|
61
|
+
state: match[2],
|
|
62
|
+
startedAt: match[3],
|
|
63
|
+
argv: match[4].split(/\s+/u),
|
|
64
|
+
}
|
|
65
|
+
: null;
|
|
66
|
+
} catch (error) {
|
|
67
|
+
// Absent or unreadable processes cannot establish ownership. Native macOS
|
|
68
|
+
// interpreter failures were deliberately handled outside this recovery.
|
|
69
|
+
if (
|
|
70
|
+
error.status === 1 ||
|
|
71
|
+
['ESRCH', 'EACCES', 'EPERM'].includes(error.code) ||
|
|
72
|
+
(platform === 'linux' && error.code === 'ENOENT')
|
|
73
|
+
)
|
|
74
|
+
return null;
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -10,6 +10,7 @@ import { existsSync, readFileSync, rmSync } from 'node:fs';
|
|
|
10
10
|
import net from 'node:net';
|
|
11
11
|
import path from 'node:path';
|
|
12
12
|
|
|
13
|
+
import { processInfo } from './process-info.mjs';
|
|
13
14
|
import { webDappPolicy, webDappRuntimeDir } from './runtime.mjs';
|
|
14
15
|
|
|
15
16
|
export function pidAlive(pid) {
|
|
@@ -37,19 +38,8 @@ function readPid(file) {
|
|
|
37
38
|
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
function psField(pid, field) {
|
|
41
|
-
try {
|
|
42
|
-
return execFileSync('ps', ['-ww', '-o', `${field}=`, '-p', String(pid)], {
|
|
43
|
-
encoding: 'utf8',
|
|
44
|
-
stdio: ['ignore', 'pipe', 'ignore'],
|
|
45
|
-
}).trim();
|
|
46
|
-
} catch {
|
|
47
|
-
return '';
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
41
|
export function processCommand(pid) {
|
|
52
|
-
return
|
|
42
|
+
return processInfo(pid)?.argv.join(' ') ?? '';
|
|
53
43
|
}
|
|
54
44
|
|
|
55
45
|
// Each process the slot starts carries `--mm-harness-owner=<kind>-<id>`, where
|
|
@@ -66,11 +56,19 @@ export function ownerMarker(kind, runtimeDir) {
|
|
|
66
56
|
return `${OWNER_FLAG}=${kind}-${id}`;
|
|
67
57
|
}
|
|
68
58
|
|
|
69
|
-
export function ownsProcess(kind, pid, runtimeDir, command
|
|
70
|
-
if (
|
|
59
|
+
export function ownsProcess(kind, pid, runtimeDir, command) {
|
|
60
|
+
if (command === undefined) return ownedProcessIdentity(kind, pid, runtimeDir) !== null;
|
|
71
61
|
return command.split(/\s+/u).includes(ownerMarker(kind, runtimeDir));
|
|
72
62
|
}
|
|
73
63
|
|
|
64
|
+
// Carry this authorization into termination. A later snapshot cannot authorize
|
|
65
|
+
// a recycled PID, even if the replacement happens to carry the same marker.
|
|
66
|
+
export function ownedProcessIdentity(kind, pid, runtimeDir) {
|
|
67
|
+
const identity = processInfo(pid);
|
|
68
|
+
const marker = ownerMarker(kind, runtimeDir);
|
|
69
|
+
return identity?.argv.includes(marker) ? { ...identity, pid, marker } : null;
|
|
70
|
+
}
|
|
71
|
+
|
|
74
72
|
export function portFree(port) {
|
|
75
73
|
return new Promise((resolve) => {
|
|
76
74
|
const socket = net.connect({ host: '127.0.0.1', port }, () => {
|
|
@@ -84,23 +82,37 @@ export function portFree(port) {
|
|
|
84
82
|
// Browsers and hosts are spawned detached, each leading its own process group.
|
|
85
83
|
// When the pid leads its group the whole group is signalled and waited for,
|
|
86
84
|
// so children that outlive the leader (renderers, a child ignoring SIGTERM)
|
|
87
|
-
// are killed too; otherwise only the pid.
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
85
|
+
// are killed too; otherwise only the pid. The caller must pass the snapshot
|
|
86
|
+
// returned by ownedProcessIdentity, never reacquire identity inside terminate.
|
|
87
|
+
export async function terminate(pid, graceMs = 8000, identity) {
|
|
88
|
+
if (!identity || identity.pid !== pid || !identity.marker) return false;
|
|
89
|
+
if (identity.state === 5 || String(identity.state).startsWith('Z')) return false;
|
|
90
|
+
const group = identity.pgid === pid;
|
|
91
|
+
if (!pidAlive(pid) && (!group || !groupAlive(pid))) return true;
|
|
91
92
|
const alive = () => (group ? groupAlive(pid) : pidAlive(pid));
|
|
92
93
|
const signal = (name) => {
|
|
94
|
+
const current = processInfo(pid);
|
|
95
|
+
// A group can outlive its leader, but a reused leader PID is never ours.
|
|
96
|
+
if (current) {
|
|
97
|
+
if (
|
|
98
|
+
current.startedAt !== identity.startedAt ||
|
|
99
|
+
current.pgid !== identity.pgid ||
|
|
100
|
+
!current.argv.includes(identity.marker)
|
|
101
|
+
)
|
|
102
|
+
return false;
|
|
103
|
+
} else if (pidAlive(pid)) return false;
|
|
93
104
|
try {
|
|
94
105
|
process.kill(group ? -pid : pid, name);
|
|
95
|
-
} catch {
|
|
96
|
-
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (error.code !== 'ESRCH') throw error;
|
|
97
108
|
}
|
|
109
|
+
return true;
|
|
98
110
|
};
|
|
99
|
-
signal('SIGTERM');
|
|
111
|
+
if (!signal('SIGTERM')) return false;
|
|
100
112
|
const deadline = Date.now() + graceMs;
|
|
101
113
|
while (alive() && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 200));
|
|
102
114
|
if (alive()) {
|
|
103
|
-
signal('SIGKILL');
|
|
115
|
+
if (!signal('SIGKILL')) return false;
|
|
104
116
|
const killDeadline = Date.now() + 5000;
|
|
105
117
|
while (alive() && Date.now() < killDeadline)
|
|
106
118
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
@@ -119,13 +131,13 @@ export async function stopConsoleCollector(target, { log = () => {}, runtimeDir
|
|
|
119
131
|
const pidFile = path.join(runtime, 'console-tail.pid');
|
|
120
132
|
const pid = readPid(pidFile);
|
|
121
133
|
if (!pid) return { stopped: null };
|
|
122
|
-
|
|
123
|
-
|
|
134
|
+
const identity = ownedProcessIdentity('console-collector', pid, runtime);
|
|
135
|
+
if (identity && (await terminate(pid, 3000, identity))) {
|
|
124
136
|
rmSync(pidFile, { force: true });
|
|
125
137
|
log(`stopped console collector pid ${pid}`);
|
|
126
138
|
return { stopped: pid };
|
|
127
139
|
}
|
|
128
|
-
if (pidAlive(pid)) {
|
|
140
|
+
if (identity || pidAlive(pid)) {
|
|
129
141
|
log(`console collector pid ${pid} is alive but is not this slot's collector; left it alone`);
|
|
130
142
|
return { stopped: null, foreign: pid };
|
|
131
143
|
}
|
|
@@ -180,13 +192,12 @@ export async function stopWebDappBrowser(target, { cdpPort, log = () => {}, runt
|
|
|
180
192
|
for (const name of ['wallet-host', 'browser']) {
|
|
181
193
|
const pidFile = path.join(runtime, `${name}.pid`);
|
|
182
194
|
const pid = readPid(pidFile);
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
}
|
|
195
|
+
const identity = pid && ownedProcessIdentity(name, pid, runtime);
|
|
196
|
+
if (identity && (await terminate(pid, 8000, identity))) {
|
|
197
|
+
stopped.push({ name, pid });
|
|
198
|
+
log(`stopped ${name} pid ${pid}`);
|
|
188
199
|
rmSync(pidFile, { force: true });
|
|
189
|
-
} else if (pid && pidAlive(pid)) {
|
|
200
|
+
} else if (pid && (identity || pidAlive(pid))) {
|
|
190
201
|
foreign.push({ name, pid });
|
|
191
202
|
log(
|
|
192
203
|
`${name} pid ${pid} is alive but is not this slot's ${name}; left it and its pid file alone`,
|
|
@@ -196,8 +207,10 @@ export async function stopWebDappBrowser(target, { cdpPort, log = () => {}, runt
|
|
|
196
207
|
rmSync(pidFile, { force: true });
|
|
197
208
|
}
|
|
198
209
|
}
|
|
199
|
-
|
|
200
|
-
|
|
210
|
+
if (foreign.length === 0) {
|
|
211
|
+
rmSync(path.join(runtime, 'wallet-host.ready'), { force: true });
|
|
212
|
+
rmSync(path.join(runtime, 'browser.json'), { force: true });
|
|
213
|
+
}
|
|
201
214
|
let free = null;
|
|
202
215
|
if (cdpPort) {
|
|
203
216
|
const deadline = Date.now() + 10000;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
// /usr/bin/python3 opens an install dialog until Command Line Tools exist.
|
|
4
|
+
// Resolve a real interpreter before any native probe can steal keyboard focus.
|
|
5
|
+
export function pythonFor({ found, platform = process.platform, developerDir }) {
|
|
6
|
+
if (!found) return null;
|
|
7
|
+
if (platform === 'darwin' && found === '/usr/bin/python3' && !developerDir()) return null;
|
|
8
|
+
return found;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function output(command, args) {
|
|
12
|
+
try {
|
|
13
|
+
return execFileSync(command, args, {
|
|
14
|
+
encoding: 'utf8',
|
|
15
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
16
|
+
timeout: 2000,
|
|
17
|
+
}).trim();
|
|
18
|
+
} catch (error) {
|
|
19
|
+
// which exits 1 when absent; xcode-select exits 2 before CLT is installed.
|
|
20
|
+
if (error.status === 1 || error.status === 2 || error.code === 'ENOENT') return '';
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
let pythonChoice;
|
|
26
|
+
export function usablePython() {
|
|
27
|
+
if (pythonChoice === undefined) {
|
|
28
|
+
pythonChoice = pythonFor({
|
|
29
|
+
found: output('/usr/bin/which', ['python3']),
|
|
30
|
+
developerDir: () => output('/usr/bin/xcode-select', ['-p']),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
return pythonChoice;
|
|
34
|
+
}
|
|
@@ -8,6 +8,7 @@ import { execFileSync } from 'node:child_process';
|
|
|
8
8
|
import { existsSync, readFileSync } from 'node:fs';
|
|
9
9
|
import path from 'node:path';
|
|
10
10
|
|
|
11
|
+
import { readNativeProcArgs } from './native-proc-args.mjs';
|
|
11
12
|
import { ownsProcess, pidAlive, portFree } from './processes.mjs';
|
|
12
13
|
import {
|
|
13
14
|
canonicalPath,
|
|
@@ -62,30 +63,6 @@ function run(command, args) {
|
|
|
62
63
|
}
|
|
63
64
|
}
|
|
64
65
|
|
|
65
|
-
const PROCARGS_HELPER = `
|
|
66
|
-
import ctypes, ctypes.util, json, struct, sys
|
|
67
|
-
libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)
|
|
68
|
-
pid = int(sys.argv[1])
|
|
69
|
-
argmax = ctypes.c_int(0)
|
|
70
|
-
size = ctypes.c_size_t(ctypes.sizeof(argmax))
|
|
71
|
-
if libc.sysctl((ctypes.c_int * 2)(1, 8), 2, ctypes.byref(argmax), ctypes.byref(size), None, 0) != 0:
|
|
72
|
-
print("null"); sys.exit(0)
|
|
73
|
-
buf = ctypes.create_string_buffer(argmax.value)
|
|
74
|
-
size = ctypes.c_size_t(argmax.value)
|
|
75
|
-
if libc.sysctl((ctypes.c_int * 3)(1, 49, pid), 3, buf, ctypes.byref(size), None, 0) != 0:
|
|
76
|
-
print("null"); sys.exit(0)
|
|
77
|
-
raw = buf.raw[:size.value]
|
|
78
|
-
argc = struct.unpack("i", raw[:4])[0]
|
|
79
|
-
rest = raw[4:]
|
|
80
|
-
rest = rest[rest.index(b"\\0"):].lstrip(b"\\0")
|
|
81
|
-
parts = rest.split(b"\\0")
|
|
82
|
-
env = []
|
|
83
|
-
for part in parts[argc:]:
|
|
84
|
-
if not part: break
|
|
85
|
-
env.append(part.decode("utf-8", "replace"))
|
|
86
|
-
print(json.dumps({"argv": [p.decode("utf-8", "replace") for p in parts[:argc]], "env": env}))
|
|
87
|
-
`;
|
|
88
|
-
|
|
89
66
|
export const systemProbe = Object.freeze({
|
|
90
67
|
listeners: (port) =>
|
|
91
68
|
run('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-t'])
|
|
@@ -106,43 +83,10 @@ export const systemProbe = Object.freeze({
|
|
|
106
83
|
.find((line) => line.startsWith('n')) ?? ''
|
|
107
84
|
).slice(1) || null,
|
|
108
85
|
// { argv: string[], env: string[] } with exact element boundaries, or null.
|
|
109
|
-
procArgs: (pid) => {
|
|
110
|
-
const python = usablePython();
|
|
111
|
-
if (!python) return null;
|
|
112
|
-
try {
|
|
113
|
-
return JSON.parse(
|
|
114
|
-
execFileSync(python, ['-c', PROCARGS_HELPER, String(pid)], {
|
|
115
|
-
encoding: 'utf8',
|
|
116
|
-
stdio: ['ignore', 'pipe', 'ignore'],
|
|
117
|
-
timeout: 15000,
|
|
118
|
-
}).trim(),
|
|
119
|
-
);
|
|
120
|
-
} catch {
|
|
121
|
-
return null;
|
|
122
|
-
}
|
|
123
|
-
},
|
|
86
|
+
procArgs: (pid) => readNativeProcArgs(pid, { includeEnvironment: true }),
|
|
124
87
|
});
|
|
125
88
|
|
|
126
|
-
|
|
127
|
-
// installed, and running it opens an install dialog that takes keyboard
|
|
128
|
-
// focus. Use it only when xcode-select reports a developer directory; any
|
|
129
|
-
// other python3 on PATH is a real install.
|
|
130
|
-
export function pythonFor({ found, platform = process.platform, developerDir }) {
|
|
131
|
-
if (!found) return null;
|
|
132
|
-
if (platform === 'darwin' && found === '/usr/bin/python3' && !developerDir()) return null;
|
|
133
|
-
return found;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
let pythonChoice;
|
|
137
|
-
function usablePython() {
|
|
138
|
-
if (pythonChoice === undefined) {
|
|
139
|
-
pythonChoice = pythonFor({
|
|
140
|
-
found: run('/usr/bin/which', ['python3']).trim(),
|
|
141
|
-
developerDir: () => run('/usr/bin/xcode-select', ['-p']).trim(),
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
|
-
return pythonChoice;
|
|
145
|
-
}
|
|
89
|
+
export { pythonFor } from './python.mjs';
|
|
146
90
|
|
|
147
91
|
export function environmentValue(env, name) {
|
|
148
92
|
const entry = env.find((item) => item.startsWith(`${name}=`));
|