@metamask/device-mcp 0.2.0 → 0.3.1
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 +28 -1
- package/README.md +55 -2
- package/dist/backends/adb-backend.cjs +12 -5
- package/dist/backends/adb-backend.cjs.map +1 -1
- package/dist/backends/adb-backend.d.cts +8 -2
- package/dist/backends/adb-backend.d.cts.map +1 -1
- package/dist/backends/adb-backend.d.mts +8 -2
- package/dist/backends/adb-backend.d.mts.map +1 -1
- package/dist/backends/adb-backend.mjs +12 -5
- package/dist/backends/adb-backend.mjs.map +1 -1
- package/dist/backends/appium-backend.cjs +16 -7
- package/dist/backends/appium-backend.cjs.map +1 -1
- package/dist/backends/appium-backend.d.cts +8 -2
- package/dist/backends/appium-backend.d.cts.map +1 -1
- package/dist/backends/appium-backend.d.mts +8 -2
- package/dist/backends/appium-backend.d.mts.map +1 -1
- package/dist/backends/appium-backend.mjs +16 -7
- package/dist/backends/appium-backend.mjs.map +1 -1
- package/dist/backends/idb-backend.cjs +12 -5
- package/dist/backends/idb-backend.cjs.map +1 -1
- package/dist/backends/idb-backend.d.cts +8 -2
- package/dist/backends/idb-backend.d.cts.map +1 -1
- package/dist/backends/idb-backend.d.mts +8 -2
- package/dist/backends/idb-backend.d.mts.map +1 -1
- package/dist/backends/idb-backend.mjs +12 -5
- package/dist/backends/idb-backend.mjs.map +1 -1
- package/dist/backends/index.cjs +4 -3
- package/dist/backends/index.cjs.map +1 -1
- package/dist/backends/index.d.cts.map +1 -1
- package/dist/backends/index.d.mts.map +1 -1
- package/dist/backends/index.mjs +4 -3
- package/dist/backends/index.mjs.map +1 -1
- package/dist/backends/types.cjs.map +1 -1
- package/dist/backends/types.d.cts +19 -1
- package/dist/backends/types.d.cts.map +1 -1
- package/dist/backends/types.d.mts +19 -1
- package/dist/backends/types.d.mts.map +1 -1
- package/dist/backends/types.mjs.map +1 -1
- package/dist/hermes/hermes-cdp.cjs +674 -0
- package/dist/hermes/hermes-cdp.cjs.map +1 -0
- package/dist/hermes/hermes-cdp.d.cts +248 -0
- package/dist/hermes/hermes-cdp.d.cts.map +1 -0
- package/dist/hermes/hermes-cdp.d.mts +248 -0
- package/dist/hermes/hermes-cdp.d.mts.map +1 -0
- package/dist/hermes/hermes-cdp.mjs +665 -0
- package/dist/hermes/hermes-cdp.mjs.map +1 -0
- package/dist/hermes/session.cjs +196 -0
- package/dist/hermes/session.cjs.map +1 -0
- package/dist/hermes/session.d.cts +163 -0
- package/dist/hermes/session.d.cts.map +1 -0
- package/dist/hermes/session.d.mts +163 -0
- package/dist/hermes/session.d.mts.map +1 -0
- package/dist/hermes/session.mjs +189 -0
- package/dist/hermes/session.mjs.map +1 -0
- package/dist/index.cjs +21 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +7 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -0
- package/dist/index.mjs.map +1 -1
- package/dist/server.cjs +3 -0
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts.map +1 -1
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +4 -1
- package/dist/server.mjs.map +1 -1
- package/dist/tools/hermes-cdp.cjs +102 -0
- package/dist/tools/hermes-cdp.cjs.map +1 -0
- package/dist/tools/hermes-cdp.d.cts +18 -0
- package/dist/tools/hermes-cdp.d.cts.map +1 -0
- package/dist/tools/hermes-cdp.d.mts +18 -0
- package/dist/tools/hermes-cdp.d.mts.map +1 -0
- package/dist/tools/hermes-cdp.mjs +99 -0
- package/dist/tools/hermes-cdp.mjs.map +1 -0
- package/dist/tools/hermes-targets.cjs +127 -0
- package/dist/tools/hermes-targets.cjs.map +1 -0
- package/dist/tools/hermes-targets.d.cts +20 -0
- package/dist/tools/hermes-targets.d.cts.map +1 -0
- package/dist/tools/hermes-targets.d.mts +20 -0
- package/dist/tools/hermes-targets.d.mts.map +1 -0
- package/dist/tools/hermes-targets.mjs +124 -0
- package/dist/tools/hermes-targets.mjs.map +1 -0
- package/dist/tools/index.cjs +5 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.cts +2 -0
- package/dist/tools/index.d.cts.map +1 -1
- package/dist/tools/index.d.mts +2 -0
- package/dist/tools/index.d.mts.map +1 -1
- package/dist/tools/index.mjs +2 -0
- package/dist/tools/index.mjs.map +1 -1
- package/dist/tools/screenshot.cjs +8 -3
- package/dist/tools/screenshot.cjs.map +1 -1
- package/dist/tools/screenshot.d.cts.map +1 -1
- package/dist/tools/screenshot.d.mts.map +1 -1
- package/dist/tools/screenshot.mjs +8 -3
- package/dist/tools/screenshot.mjs.map +1 -1
- package/dist/utils/output-path.cjs +128 -0
- package/dist/utils/output-path.cjs.map +1 -0
- package/dist/utils/output-path.d.cts +41 -0
- package/dist/utils/output-path.d.cts.map +1 -0
- package/dist/utils/output-path.d.mts +41 -0
- package/dist/utils/output-path.d.mts.map +1 -0
- package/dist/utils/output-path.mjs +123 -0
- package/dist/utils/output-path.mjs.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,665 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure Hermes Chrome DevTools Protocol (CDP) core for `@metamask/device-mcp`.
|
|
3
|
+
*
|
|
4
|
+
* Ported from `@metamask/client-mcp-core`'s `src/tools/hermes-cdp.ts`, decoupled
|
|
5
|
+
* from that repo's `ToolContext`/`ErrorCodes`/`createToolError|Success`. Every
|
|
6
|
+
* function here takes EXPLICIT parameters (port, appId, pin) and returns a
|
|
7
|
+
* discriminated {@link HermesCdpResult} so this module is MCP-free and
|
|
8
|
+
* unit-testable. The tools layer is responsible for resolving session state and
|
|
9
|
+
* for PERSISTING the device pin — this file never imports `HermesSession`.
|
|
10
|
+
*
|
|
11
|
+
* Mechanism: the React Native Hermes runtime connects out to Metro's inspector
|
|
12
|
+
* proxy; Metro exposes debuggable targets over `http://localhost:<metroPort>/json`
|
|
13
|
+
* and a per-target `webSocketDebuggerUrl`. We speak real CDP over that WebSocket
|
|
14
|
+
* using the GLOBAL `WebSocket` (no library) and the global `fetch` for discovery.
|
|
15
|
+
*
|
|
16
|
+
* Five fail-closed safety checks are preserved VERBATIM from the reference:
|
|
17
|
+
* 1. Strict `appId` match (`===`, no substring, no `targets[0]` fallback).
|
|
18
|
+
* 2. `HermesInternal.getRuntimeProperties()` identity probe before the user method.
|
|
19
|
+
* 3. Device pin on `reactNative.logicalDeviceId` (set on first success).
|
|
20
|
+
* 4. Multi-device fail-closed (missing or >1 distinct `logicalDeviceId`).
|
|
21
|
+
* 5. WebSocket URL validation (protocol/hostname/port).
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* No Hermes debug target matched the expected appId (after synthetic-title and
|
|
25
|
+
* pin filtering). Often means Metro is up but the app is not registered.
|
|
26
|
+
*/
|
|
27
|
+
export const HERMES_TARGET_NOT_FOUND = 'HERMES_TARGET_NOT_FOUND';
|
|
28
|
+
/**
|
|
29
|
+
* A target was found but could not be verified as the expected Hermes runtime
|
|
30
|
+
* (identity probe failed, missing `logicalDeviceId`, or non-JSON probe payload).
|
|
31
|
+
*/
|
|
32
|
+
export const HERMES_NOT_VERIFIED = 'HERMES_NOT_VERIFIED';
|
|
33
|
+
/**
|
|
34
|
+
* Multiple distinct logical devices are registered without a session pin (or a
|
|
35
|
+
* candidate is missing its `logicalDeviceId`); routing would be a guess, so we
|
|
36
|
+
* fail closed.
|
|
37
|
+
*/
|
|
38
|
+
export const HERMES_MULTIPLE_DEVICES = 'HERMES_MULTIPLE_DEVICES';
|
|
39
|
+
/**
|
|
40
|
+
* The resolved target's `logicalDeviceId` does not match the session pin.
|
|
41
|
+
*/
|
|
42
|
+
export const HERMES_DEVICE_PIN_MISMATCH = 'HERMES_DEVICE_PIN_MISMATCH';
|
|
43
|
+
/**
|
|
44
|
+
* The requested CDP method is in the destructive blocked set.
|
|
45
|
+
*/
|
|
46
|
+
export const HERMES_BLOCKED_METHOD = 'HERMES_BLOCKED_METHOD';
|
|
47
|
+
/**
|
|
48
|
+
* The target's `webSocketDebuggerUrl` failed protocol/hostname/port validation.
|
|
49
|
+
*/
|
|
50
|
+
export const HERMES_INVALID_WS_URL = 'HERMES_INVALID_WS_URL';
|
|
51
|
+
/**
|
|
52
|
+
* The underlying connection (discovery fetch or WebSocket) failed.
|
|
53
|
+
*/
|
|
54
|
+
export const HERMES_CONNECTION_FAILED = 'HERMES_CONNECTION_FAILED';
|
|
55
|
+
/**
|
|
56
|
+
* A discovery, socket-open, or CDP round-trip exceeded the configured timeout.
|
|
57
|
+
*/
|
|
58
|
+
export const HERMES_TIMEOUT = 'HERMES_TIMEOUT';
|
|
59
|
+
/**
|
|
60
|
+
* The user's CDP method returned a CDP-level error.
|
|
61
|
+
*/
|
|
62
|
+
export const HERMES_CDP_FAILED = 'HERMES_CDP_FAILED';
|
|
63
|
+
/**
|
|
64
|
+
* The global `WebSocket` constructor is unavailable in this Node runtime.
|
|
65
|
+
*/
|
|
66
|
+
export const HERMES_WEBSOCKET_UNAVAILABLE = 'HERMES_WEBSOCKET_UNAVAILABLE';
|
|
67
|
+
/**
|
|
68
|
+
* CDP methods blocked for safety. Ported VERBATIM from the reference — do not
|
|
69
|
+
* weaken.
|
|
70
|
+
*/
|
|
71
|
+
const HERMES_BLOCKED_METHODS = new Set([
|
|
72
|
+
'Runtime.terminateExecution',
|
|
73
|
+
'Inspector.detached',
|
|
74
|
+
]);
|
|
75
|
+
const DISCOVERY_PATHS = ['/json', '/json/list'];
|
|
76
|
+
const ALLOWED_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
|
|
77
|
+
/**
|
|
78
|
+
* Title of the synthetic legacy "Improved Chrome Reloads" page that Metro
|
|
79
|
+
* registers alongside the real Hermes target. Filtered out during selection.
|
|
80
|
+
* Ported VERBATIM from the reference.
|
|
81
|
+
*/
|
|
82
|
+
export const LEGACY_SYNTHETIC_TITLE = 'React Native Experimental (Improved Chrome Reloads)';
|
|
83
|
+
/**
|
|
84
|
+
* JavaScript expression evaluated against a candidate target BEFORE the user's
|
|
85
|
+
* method, to verify it is a genuine Hermes runtime. Copied VERBATIM from the
|
|
86
|
+
* reference — do not alter the verification semantics.
|
|
87
|
+
*/
|
|
88
|
+
export const IDENTITY_PROBE_EXPR = `(function () {
|
|
89
|
+
try {
|
|
90
|
+
var hi = typeof HermesInternal !== 'undefined' ? HermesInternal : null;
|
|
91
|
+
var p =
|
|
92
|
+
hi && typeof hi.getRuntimeProperties === 'function'
|
|
93
|
+
? hi.getRuntimeProperties()
|
|
94
|
+
: null;
|
|
95
|
+
return JSON.stringify({
|
|
96
|
+
isHermes: !!hi,
|
|
97
|
+
ossVersion: p ? p['OSS Release Version'] : null,
|
|
98
|
+
debuggerEnabled: p ? p['Debugger Enabled'] : null,
|
|
99
|
+
});
|
|
100
|
+
} catch (e) {
|
|
101
|
+
return JSON.stringify({ error: String(e) });
|
|
102
|
+
}
|
|
103
|
+
})();`;
|
|
104
|
+
/**
|
|
105
|
+
* Orchestrates a single verified Hermes CDP command end to end.
|
|
106
|
+
*
|
|
107
|
+
* Resolves a target from Metro discovery, enforces all five fail-closed safety
|
|
108
|
+
* checks, runs the identity probe, persists the device pin via `onPin` on first
|
|
109
|
+
* success, sends the user's method, and returns the raw CDP `result`. The caller
|
|
110
|
+
* supplies the resolved port/appId/pin and persists the pin — this function is
|
|
111
|
+
* pure with respect to session state.
|
|
112
|
+
*
|
|
113
|
+
* @param input - Method, params, timeout, resolved port/appId/pin, and the pin
|
|
114
|
+
* persistence callback. See {@link RunHermesCdpInput}.
|
|
115
|
+
* @returns A discriminated {@link HermesCdpResult}.
|
|
116
|
+
*/
|
|
117
|
+
export async function runHermesCdp(input) {
|
|
118
|
+
if (HERMES_BLOCKED_METHODS.has(input.method)) {
|
|
119
|
+
return {
|
|
120
|
+
ok: false,
|
|
121
|
+
code: HERMES_BLOCKED_METHOD,
|
|
122
|
+
message: `CDP method "${input.method}" is blocked for safety. ` +
|
|
123
|
+
`Blocked methods: ${[...HERMES_BLOCKED_METHODS].join(', ')}`,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
if (typeof WebSocket !== 'function') {
|
|
127
|
+
return {
|
|
128
|
+
ok: false,
|
|
129
|
+
code: HERMES_WEBSOCKET_UNAVAILABLE,
|
|
130
|
+
message: 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' +
|
|
131
|
+
'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).',
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
const targets = await fetchDiscoveryTargets(input.metroPort, input.timeoutMs);
|
|
136
|
+
const selection = selectHermesTarget(targets, input.appId, input.pinnedDeviceId);
|
|
137
|
+
if (!selection.ok) {
|
|
138
|
+
return { ok: false, code: selection.code, message: selection.message };
|
|
139
|
+
}
|
|
140
|
+
const validation = validateWebSocketUrl(selection.target.webSocketDebuggerUrl, input.metroPort);
|
|
141
|
+
if (!validation.ok) {
|
|
142
|
+
return {
|
|
143
|
+
ok: false,
|
|
144
|
+
code: HERMES_INVALID_WS_URL,
|
|
145
|
+
message: validation.message,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
return await executeVerifiedCdpCommand(selection.target, input, input.pinnedDeviceId, input.onPin);
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
152
|
+
return {
|
|
153
|
+
ok: false,
|
|
154
|
+
code: HERMES_CONNECTION_FAILED,
|
|
155
|
+
message: `Hermes CDP connection failed: ${message}`,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Fetches debuggable Hermes targets from Metro, trying `/json` then falling
|
|
161
|
+
* back to `/json/list`. Each attempt is bounded by an `AbortController`
|
|
162
|
+
* timeout. The payload must be an array; non-object entries are filtered out.
|
|
163
|
+
*
|
|
164
|
+
* @param metroPort - The Metro inspector proxy port.
|
|
165
|
+
* @param timeoutMs - Per-attempt timeout in milliseconds.
|
|
166
|
+
* @returns The discovered targets (objects only).
|
|
167
|
+
* @throws The last error encountered if all discovery paths fail.
|
|
168
|
+
*/
|
|
169
|
+
export async function fetchDiscoveryTargets(metroPort, timeoutMs) {
|
|
170
|
+
let lastError;
|
|
171
|
+
for (const path of DISCOVERY_PATHS) {
|
|
172
|
+
const controller = new AbortController();
|
|
173
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
174
|
+
try {
|
|
175
|
+
const response = await fetch(`http://localhost:${metroPort}${path}`, {
|
|
176
|
+
signal: controller.signal,
|
|
177
|
+
});
|
|
178
|
+
if (!response.ok) {
|
|
179
|
+
throw new Error(`Metro ${path} returned HTTP ${response.status}`);
|
|
180
|
+
}
|
|
181
|
+
const payload = await response.json();
|
|
182
|
+
if (!Array.isArray(payload)) {
|
|
183
|
+
throw new Error(`Metro ${path} returned a non-array response`);
|
|
184
|
+
}
|
|
185
|
+
return payload.filter(isHermesTarget);
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
lastError = error;
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
clearTimeout(timer);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Narrows an unknown discovery entry to a {@link HermesTarget} (object guard).
|
|
198
|
+
*
|
|
199
|
+
* @param value - A raw entry from the Metro discovery payload.
|
|
200
|
+
* @returns True when `value` is a non-null object.
|
|
201
|
+
*/
|
|
202
|
+
function isHermesTarget(value) {
|
|
203
|
+
return typeof value === 'object' && value !== null;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Selects the single safe Hermes target for the expected app, applying the
|
|
207
|
+
* fail-closed selection algorithm VERBATIM from the reference:
|
|
208
|
+
*
|
|
209
|
+
* `webSocketDebuggerUrl` present → drop the synthetic legacy title → strict
|
|
210
|
+
* `appId` match (`===`) → pin filter → ambiguity check ({@link hasAmbiguousTarget})
|
|
211
|
+
* → `nativePageReloads` tiebreak → last-in-array.
|
|
212
|
+
*
|
|
213
|
+
* @param targets - All discovered targets.
|
|
214
|
+
* @param expectedAppId - The strict app bundle identifier to match.
|
|
215
|
+
* @param pinnedDeviceId - The session pin, if set, used to filter candidates.
|
|
216
|
+
* @returns The selected target or a classified failure.
|
|
217
|
+
*/
|
|
218
|
+
export function selectHermesTarget(targets, expectedAppId, pinnedDeviceId) {
|
|
219
|
+
const seenAppIds = [...new Set(targets.map((target) => target.appId))].filter((appId) => typeof appId === 'string');
|
|
220
|
+
let candidates = targets
|
|
221
|
+
.filter((target) => Boolean(target.webSocketDebuggerUrl))
|
|
222
|
+
.filter((target) => target.title !== LEGACY_SYNTHETIC_TITLE)
|
|
223
|
+
.filter((target) => target.appId === expectedAppId);
|
|
224
|
+
if (pinnedDeviceId) {
|
|
225
|
+
candidates = candidates.filter((target) => target.reactNative?.logicalDeviceId === pinnedDeviceId);
|
|
226
|
+
}
|
|
227
|
+
if (candidates.length === 0) {
|
|
228
|
+
return {
|
|
229
|
+
ok: false,
|
|
230
|
+
code: HERMES_TARGET_NOT_FOUND,
|
|
231
|
+
message: `No Hermes debug target found for appId ${expectedAppId}. Saw appIds: ${JSON.stringify(seenAppIds)}`,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
if (hasAmbiguousTarget(candidates)) {
|
|
235
|
+
return {
|
|
236
|
+
ok: false,
|
|
237
|
+
code: HERMES_MULTIPLE_DEVICES,
|
|
238
|
+
message: `Ambiguous Hermes target after pin filtering. Candidates: ${candidates
|
|
239
|
+
.map((target) => `${target.id ?? '<unknown>'} (device=${target.reactNative?.logicalDeviceId ?? '<missing>'})`)
|
|
240
|
+
.join(', ')}`,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
// Same-device tiebreak: prefer pages with nativePageReloads (newer RN page
|
|
244
|
+
// registrations) over stale entries left behind after in-app reloads.
|
|
245
|
+
const nativeReloadTargets = candidates.filter((target) => target.reactNative?.capabilities?.nativePageReloads === true);
|
|
246
|
+
if (nativeReloadTargets.length > 0) {
|
|
247
|
+
candidates = nativeReloadTargets;
|
|
248
|
+
}
|
|
249
|
+
return { ok: true, target: candidates[candidates.length - 1] };
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Determines whether a multi-candidate target list is too ambiguous to choose
|
|
253
|
+
* from safely. Returns true when:
|
|
254
|
+
* - any candidate is missing a `reactNative.logicalDeviceId` (we can't route safely), or
|
|
255
|
+
* - candidates resolve to more than one distinct `logicalDeviceId` (multi-device
|
|
256
|
+
* without a session pin — picking any one would silently bind the wrong device).
|
|
257
|
+
*
|
|
258
|
+
* Returns false when all candidates share the same logical device ID. In that
|
|
259
|
+
* case the caller falls through to the "last-in-array" tiebreak, matching the
|
|
260
|
+
* React Native convention that the most recent page registration wins (e.g.,
|
|
261
|
+
* stale + fresh page after an in-app reload).
|
|
262
|
+
*
|
|
263
|
+
* @param candidates - Targets remaining after appId/pin/capability filtering.
|
|
264
|
+
* @returns True when the caller must fail closed; false when tiebreak is safe.
|
|
265
|
+
*/
|
|
266
|
+
export function hasAmbiguousTarget(candidates) {
|
|
267
|
+
if (candidates.length <= 1) {
|
|
268
|
+
return false;
|
|
269
|
+
}
|
|
270
|
+
const deviceIds = candidates.map((target) => target.reactNative?.logicalDeviceId);
|
|
271
|
+
// Any candidate missing a logicalDeviceId → can't safely route.
|
|
272
|
+
if (deviceIds.some((id) => !id)) {
|
|
273
|
+
return true;
|
|
274
|
+
}
|
|
275
|
+
// Multiple distinct device IDs → multi-device without pin.
|
|
276
|
+
return new Set(deviceIds).size > 1;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Validates a target's `webSocketDebuggerUrl` before connecting. The protocol
|
|
280
|
+
* must be `ws:`, the hostname must be loopback (`localhost`, `127.0.0.1`, `::1`,
|
|
281
|
+
* or `[::1]`), and the port must equal the resolved Metro port. Ported VERBATIM
|
|
282
|
+
* from the reference.
|
|
283
|
+
*
|
|
284
|
+
* @param rawUrl - The candidate `webSocketDebuggerUrl`.
|
|
285
|
+
* @param expectedPort - The resolved Metro port the URL must point at.
|
|
286
|
+
* @returns `{ ok: true }` when valid, otherwise a failure with a message.
|
|
287
|
+
*/
|
|
288
|
+
export function validateWebSocketUrl(rawUrl, expectedPort) {
|
|
289
|
+
if (!rawUrl) {
|
|
290
|
+
return { ok: false, message: 'webSocketDebuggerUrl is missing' };
|
|
291
|
+
}
|
|
292
|
+
let parsed;
|
|
293
|
+
try {
|
|
294
|
+
parsed = new URL(rawUrl);
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
return {
|
|
298
|
+
ok: false,
|
|
299
|
+
message: `webSocketDebuggerUrl is not a valid URL: ${rawUrl}`,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
if (parsed.protocol !== 'ws:') {
|
|
303
|
+
return { ok: false, message: `Unexpected protocol '${parsed.protocol}'` };
|
|
304
|
+
}
|
|
305
|
+
if (!ALLOWED_HOSTNAMES.has(parsed.hostname)) {
|
|
306
|
+
return { ok: false, message: `Unexpected hostname '${parsed.hostname}'` };
|
|
307
|
+
}
|
|
308
|
+
if (Number(parsed.port) !== expectedPort) {
|
|
309
|
+
return {
|
|
310
|
+
ok: false,
|
|
311
|
+
message: `Port mismatch: target=${parsed.port} expected=${expectedPort}`,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
return { ok: true };
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Opens the target WebSocket, runs the identity probe, enforces the device pin
|
|
318
|
+
* (persisting it via `onPin` on first success, failing closed on mismatch),
|
|
319
|
+
* sends the user's method, matches the response by `id`, and always closes the
|
|
320
|
+
* socket in a `finally`. Ported faithfully from the reference.
|
|
321
|
+
*
|
|
322
|
+
* @param target - The validated, selected target.
|
|
323
|
+
* @param input - The original {@link RunHermesCdpInput} (method/params/timeout).
|
|
324
|
+
* @param pinnedDeviceId - The session pin, if set.
|
|
325
|
+
* @param onPin - Callback to persist the resolved pin on first success.
|
|
326
|
+
* @returns A discriminated {@link HermesCdpResult}.
|
|
327
|
+
*/
|
|
328
|
+
export async function executeVerifiedCdpCommand(target, input, pinnedDeviceId, onPin) {
|
|
329
|
+
if (!target.webSocketDebuggerUrl) {
|
|
330
|
+
return {
|
|
331
|
+
ok: false,
|
|
332
|
+
code: HERMES_INVALID_WS_URL,
|
|
333
|
+
message: 'Target is missing webSocketDebuggerUrl',
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
if (typeof WebSocket !== 'function') {
|
|
337
|
+
return {
|
|
338
|
+
ok: false,
|
|
339
|
+
code: HERMES_WEBSOCKET_UNAVAILABLE,
|
|
340
|
+
message: 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' +
|
|
341
|
+
'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).',
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
const socket = new WebSocket(target.webSocketDebuggerUrl);
|
|
345
|
+
let nextId = 1;
|
|
346
|
+
try {
|
|
347
|
+
await waitForSocketOpen(socket, input.timeoutMs);
|
|
348
|
+
const probe = await runIdentityProbe(socket, input.timeoutMs, nextId);
|
|
349
|
+
nextId += 1;
|
|
350
|
+
if (!probe.ok) {
|
|
351
|
+
return { ok: false, code: probe.code, message: probe.message };
|
|
352
|
+
}
|
|
353
|
+
const targetDeviceId = target.reactNative?.logicalDeviceId;
|
|
354
|
+
if (!targetDeviceId) {
|
|
355
|
+
return {
|
|
356
|
+
ok: false,
|
|
357
|
+
code: HERMES_NOT_VERIFIED,
|
|
358
|
+
message: 'Target is missing reactNative.logicalDeviceId',
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
if (!pinnedDeviceId) {
|
|
362
|
+
onPin?.(targetDeviceId);
|
|
363
|
+
}
|
|
364
|
+
else if (pinnedDeviceId !== targetDeviceId) {
|
|
365
|
+
return {
|
|
366
|
+
ok: false,
|
|
367
|
+
code: HERMES_DEVICE_PIN_MISMATCH,
|
|
368
|
+
message: `Hermes target device ${targetDeviceId} does not match session pin ${pinnedDeviceId}`,
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
const response = await sendUserMethod(socket, input, nextId);
|
|
372
|
+
nextId += 1;
|
|
373
|
+
if (isCdpErrorResponse(response)) {
|
|
374
|
+
return {
|
|
375
|
+
ok: false,
|
|
376
|
+
code: HERMES_CDP_FAILED,
|
|
377
|
+
message: `Hermes CDP "${input.method}" failed: ${formatCdpError(response)}`,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
return { ok: true, result: response.result };
|
|
381
|
+
}
|
|
382
|
+
finally {
|
|
383
|
+
closeSocket(socket);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Runs the {@link IDENTITY_PROBE_EXPR} against an open socket and verifies the
|
|
388
|
+
* response confirms a Hermes runtime. Distinguishes timeout from connection
|
|
389
|
+
* failure and unverified payloads.
|
|
390
|
+
*
|
|
391
|
+
* @param socket - The open target WebSocket.
|
|
392
|
+
* @param timeoutMs - Round-trip timeout in milliseconds.
|
|
393
|
+
* @param id - The CDP message id to use for this probe.
|
|
394
|
+
* @returns A {@link ProbeResult}.
|
|
395
|
+
*/
|
|
396
|
+
async function runIdentityProbe(socket, timeoutMs, id) {
|
|
397
|
+
socket.send(JSON.stringify({
|
|
398
|
+
id,
|
|
399
|
+
method: 'Runtime.evaluate',
|
|
400
|
+
params: { expression: IDENTITY_PROBE_EXPR, returnByValue: true },
|
|
401
|
+
}));
|
|
402
|
+
let response;
|
|
403
|
+
try {
|
|
404
|
+
response = await waitForCdpResponse(socket, id, timeoutMs);
|
|
405
|
+
}
|
|
406
|
+
catch (error) {
|
|
407
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
408
|
+
if (message.includes('timed out')) {
|
|
409
|
+
return {
|
|
410
|
+
ok: false,
|
|
411
|
+
code: HERMES_TIMEOUT,
|
|
412
|
+
message: `Identity probe timed out after ${timeoutMs}ms`,
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
return {
|
|
416
|
+
ok: false,
|
|
417
|
+
code: HERMES_CONNECTION_FAILED,
|
|
418
|
+
message: `Hermes CDP connection failed: ${message}`,
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
if (isCdpErrorResponse(response)) {
|
|
422
|
+
return {
|
|
423
|
+
ok: false,
|
|
424
|
+
code: HERMES_NOT_VERIFIED,
|
|
425
|
+
message: `Identity probe failed: ${formatCdpError(response)}`,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
const remoteResult = getProbeRemoteResult(response);
|
|
429
|
+
if (remoteResult.subtype === 'error') {
|
|
430
|
+
return {
|
|
431
|
+
ok: false,
|
|
432
|
+
code: HERMES_NOT_VERIFIED,
|
|
433
|
+
message: 'Identity probe evaluation returned an error subtype',
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
if (remoteResult.value === undefined || remoteResult.value === null) {
|
|
437
|
+
return {
|
|
438
|
+
ok: false,
|
|
439
|
+
code: HERMES_NOT_VERIFIED,
|
|
440
|
+
message: 'Identity probe response missing result.value',
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
const raw = typeof remoteResult.value === 'string'
|
|
444
|
+
? remoteResult.value
|
|
445
|
+
: JSON.stringify(remoteResult.value);
|
|
446
|
+
let parsed;
|
|
447
|
+
try {
|
|
448
|
+
parsed = JSON.parse(raw);
|
|
449
|
+
}
|
|
450
|
+
catch {
|
|
451
|
+
return {
|
|
452
|
+
ok: false,
|
|
453
|
+
code: HERMES_NOT_VERIFIED,
|
|
454
|
+
message: `Identity probe returned non-JSON: ${raw}`,
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
if (!isHermesProbePayload(parsed)) {
|
|
458
|
+
return {
|
|
459
|
+
ok: false,
|
|
460
|
+
code: HERMES_NOT_VERIFIED,
|
|
461
|
+
message: `Identity probe did not verify Hermes runtime: ${raw}`,
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
return { ok: true };
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Safely extracts the nested CDP `result.result` (the remote object) from a
|
|
468
|
+
* `Runtime.evaluate` success response.
|
|
469
|
+
*
|
|
470
|
+
* @param response - A CDP success response.
|
|
471
|
+
* @returns The remote object's `subtype`/`value`, or an empty object.
|
|
472
|
+
*/
|
|
473
|
+
function getProbeRemoteResult(response) {
|
|
474
|
+
if (typeof response.result !== 'object' || response.result === null) {
|
|
475
|
+
return {};
|
|
476
|
+
}
|
|
477
|
+
const outer = response.result;
|
|
478
|
+
if (typeof outer.result !== 'object' || outer.result === null) {
|
|
479
|
+
return {};
|
|
480
|
+
}
|
|
481
|
+
return outer.result;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Narrows a parsed probe payload to one confirming a Hermes runtime.
|
|
485
|
+
*
|
|
486
|
+
* @param value - The parsed probe JSON payload.
|
|
487
|
+
* @returns True when `isHermes === true`.
|
|
488
|
+
*/
|
|
489
|
+
function isHermesProbePayload(value) {
|
|
490
|
+
return (typeof value === 'object' &&
|
|
491
|
+
value !== null &&
|
|
492
|
+
value.isHermes === true);
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Sends the user's CDP method over an open, verified socket and awaits the
|
|
496
|
+
* matching response by id.
|
|
497
|
+
*
|
|
498
|
+
* @param socket - The open, verified target WebSocket.
|
|
499
|
+
* @param input - The original input carrying method/params/timeout.
|
|
500
|
+
* @param id - The CDP message id to use.
|
|
501
|
+
* @returns The matching CDP success or error response.
|
|
502
|
+
*/
|
|
503
|
+
async function sendUserMethod(socket, input, id) {
|
|
504
|
+
socket.send(JSON.stringify({
|
|
505
|
+
id,
|
|
506
|
+
method: input.method,
|
|
507
|
+
params: input.params ?? {},
|
|
508
|
+
}));
|
|
509
|
+
return await waitForCdpResponse(socket, id, input.timeoutMs);
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Resolves once the socket reaches the OPEN state, rejecting on error or
|
|
513
|
+
* timeout. Listeners are always cleaned up.
|
|
514
|
+
*
|
|
515
|
+
* @param socket - The connecting target WebSocket.
|
|
516
|
+
* @param timeoutMs - Connection timeout in milliseconds.
|
|
517
|
+
* @returns A promise that resolves when the socket is open.
|
|
518
|
+
*/
|
|
519
|
+
async function waitForSocketOpen(socket, timeoutMs) {
|
|
520
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
521
|
+
return Promise.resolve();
|
|
522
|
+
}
|
|
523
|
+
return new Promise((resolve, reject) => {
|
|
524
|
+
let cleanup = () => undefined;
|
|
525
|
+
const handleOpen = () => {
|
|
526
|
+
cleanup();
|
|
527
|
+
resolve();
|
|
528
|
+
};
|
|
529
|
+
const handleError = () => {
|
|
530
|
+
cleanup();
|
|
531
|
+
reject(new Error('WebSocket connection error'));
|
|
532
|
+
};
|
|
533
|
+
const timer = setTimeout(() => {
|
|
534
|
+
cleanup();
|
|
535
|
+
reject(new Error(`WebSocket connection timed out after ${timeoutMs}ms`));
|
|
536
|
+
}, timeoutMs);
|
|
537
|
+
cleanup = () => {
|
|
538
|
+
clearTimeout(timer);
|
|
539
|
+
socket.removeEventListener('open', handleOpen);
|
|
540
|
+
socket.removeEventListener('error', handleError);
|
|
541
|
+
};
|
|
542
|
+
socket.addEventListener('open', handleOpen);
|
|
543
|
+
socket.addEventListener('error', handleError);
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Resolves with the CDP response whose `id` matches, rejecting on socket error,
|
|
548
|
+
* premature close, or timeout. Listeners are always cleaned up.
|
|
549
|
+
*
|
|
550
|
+
* @param socket - The open target WebSocket.
|
|
551
|
+
* @param id - The CDP message id to match.
|
|
552
|
+
* @param timeoutMs - Round-trip timeout in milliseconds.
|
|
553
|
+
* @returns The matching CDP success or error response.
|
|
554
|
+
*/
|
|
555
|
+
async function waitForCdpResponse(socket, id, timeoutMs) {
|
|
556
|
+
return new Promise((resolve, reject) => {
|
|
557
|
+
let cleanup = () => undefined;
|
|
558
|
+
const handleMessage = (event) => {
|
|
559
|
+
try {
|
|
560
|
+
const parsed = parseCdpResponse(event.data);
|
|
561
|
+
if (parsed?.id !== id) {
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
cleanup();
|
|
565
|
+
resolve(parsed);
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
cleanup();
|
|
569
|
+
reject(error);
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
const handleError = () => {
|
|
573
|
+
cleanup();
|
|
574
|
+
reject(new Error('WebSocket message error'));
|
|
575
|
+
};
|
|
576
|
+
const handleClose = () => {
|
|
577
|
+
cleanup();
|
|
578
|
+
reject(new Error('WebSocket closed before CDP response'));
|
|
579
|
+
};
|
|
580
|
+
const timer = setTimeout(() => {
|
|
581
|
+
cleanup();
|
|
582
|
+
reject(new Error(`Hermes CDP call timed out after ${timeoutMs}ms`));
|
|
583
|
+
}, timeoutMs);
|
|
584
|
+
cleanup = () => {
|
|
585
|
+
clearTimeout(timer);
|
|
586
|
+
socket.removeEventListener('message', handleMessage);
|
|
587
|
+
socket.removeEventListener('error', handleError);
|
|
588
|
+
socket.removeEventListener('close', handleClose);
|
|
589
|
+
};
|
|
590
|
+
socket.addEventListener('message', handleMessage);
|
|
591
|
+
socket.addEventListener('error', handleError);
|
|
592
|
+
socket.addEventListener('close', handleClose);
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Parses a raw WebSocket frame into a CDP response, returning undefined when it
|
|
597
|
+
* is not an addressable (`id`-bearing) message.
|
|
598
|
+
*
|
|
599
|
+
* @param data - The raw `MessageEvent.data`.
|
|
600
|
+
* @returns A CDP success/error response, or undefined when not addressable.
|
|
601
|
+
* @throws When the frame is not a text frame.
|
|
602
|
+
*/
|
|
603
|
+
function parseCdpResponse(data) {
|
|
604
|
+
if (typeof data !== 'string') {
|
|
605
|
+
throw new Error('Hermes CDP returned a non-text WebSocket frame');
|
|
606
|
+
}
|
|
607
|
+
const parsed = JSON.parse(data);
|
|
608
|
+
if (typeof parsed !== 'object' || parsed === null) {
|
|
609
|
+
return undefined;
|
|
610
|
+
}
|
|
611
|
+
const candidate = parsed;
|
|
612
|
+
if (typeof candidate.id !== 'number') {
|
|
613
|
+
return undefined;
|
|
614
|
+
}
|
|
615
|
+
if (isCdpError(candidate.error)) {
|
|
616
|
+
return { id: candidate.id, error: candidate.error };
|
|
617
|
+
}
|
|
618
|
+
return { id: candidate.id, result: candidate.result };
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Narrows an unknown value to a CDP error object.
|
|
622
|
+
*
|
|
623
|
+
* @param value - The candidate `error` field.
|
|
624
|
+
* @returns True when `value` is a non-null object.
|
|
625
|
+
*/
|
|
626
|
+
function isCdpError(value) {
|
|
627
|
+
return typeof value === 'object' && value !== null;
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Discriminates a CDP response as an error response.
|
|
631
|
+
*
|
|
632
|
+
* @param response - A CDP success or error response.
|
|
633
|
+
* @returns True when the response carries an `error` field.
|
|
634
|
+
*/
|
|
635
|
+
function isCdpErrorResponse(response) {
|
|
636
|
+
return 'error' in response;
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Formats a CDP error response into a single human-readable line.
|
|
640
|
+
*
|
|
641
|
+
* @param response - The CDP error response.
|
|
642
|
+
* @returns A combined message including code and data when present.
|
|
643
|
+
*/
|
|
644
|
+
function formatCdpError(response) {
|
|
645
|
+
const parts = [response.error.message ?? 'Unknown CDP error'];
|
|
646
|
+
if (typeof response.error.code === 'number') {
|
|
647
|
+
parts.push(`code ${response.error.code}`);
|
|
648
|
+
}
|
|
649
|
+
if (response.error.data !== undefined) {
|
|
650
|
+
parts.push(JSON.stringify(response.error.data));
|
|
651
|
+
}
|
|
652
|
+
return parts.join(' - ');
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Closes the socket if it is still connecting or open.
|
|
656
|
+
*
|
|
657
|
+
* @param socket - The target WebSocket.
|
|
658
|
+
*/
|
|
659
|
+
function closeSocket(socket) {
|
|
660
|
+
if (socket.readyState === WebSocket.CONNECTING ||
|
|
661
|
+
socket.readyState === WebSocket.OPEN) {
|
|
662
|
+
socket.close();
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
//# sourceMappingURL=hermes-cdp.mjs.map
|