@ai-ecoverse/slicc-browsers 1.29.0 → 1.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/guard-runner.mjs CHANGED
@@ -51,6 +51,204 @@ import { canonicalURL, unparseableURLs } from './unparseable-url.mjs';
51
51
  export { leftoverPersistentWorker, releasePersistentWorkerSessions, workerTypeForKind };
52
52
 
53
53
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
54
+ const explicitVector = (vector) => (vector.requires ?? []).includes('explicitAttach');
55
+ const discoveryMethods = [
56
+ 'Target.targetCreated',
57
+ 'Target.targetInfoChanged',
58
+ 'Target.attachedToTarget',
59
+ ];
60
+ const controlPremises = ['discovered', 'listed', 'attachSession', 'reachable'];
61
+ const exclusive = ['stockSetup', 'syntheticAutoAttach'];
62
+
63
+ const escapes = /(?:%[0-9a-f]{2})+/gi;
64
+ const bytes = (run) =>
65
+ run.replace(/%([0-9a-f]{2})/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
66
+ const decodedRun = (run) => {
67
+ try {
68
+ return decodeURIComponent(run);
69
+ } catch {
70
+ return bytes(run);
71
+ }
72
+ };
73
+ const unwrapped = (value) => {
74
+ let text = String(value ?? '').toLowerCase();
75
+ for (let next = text; ; text = next) {
76
+ next = text.replace(escapes, decodedRun).toLowerCase();
77
+ if (next === text) return text;
78
+ }
79
+ };
80
+
81
+ const wrappers = ['blob:', 'view-source:', 'filesystem:'];
82
+ const payloads = {
83
+ 'data:': (rest) => rest.slice(rest.indexOf(',') + 1),
84
+ 'javascript:': (rest) => rest,
85
+ };
86
+ const separators = /[\s"'`<>(){},;=\\]+/;
87
+ const mappedIPv4 = /^\[::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})\]$/;
88
+ const hostEnd = /[/?#\\\s]/;
89
+ const leadingHost = (text) => text.split(hostEnd)[0];
90
+
91
+ export function normalizeHost(host) {
92
+ const text = String(host ?? '');
93
+ const bare = text.slice(text.lastIndexOf('@') + 1);
94
+ if (!bare || hostEnd.test(text)) return '';
95
+ const name = (parseURL(`http://${bare}`)?.hostname ?? '').replace(/\.+$/, '');
96
+ const mapped = mappedIPv4.exec(name);
97
+ if (!mapped) return name;
98
+ const [high, low] = mapped.slice(1).map((part) => Number.parseInt(part, 16));
99
+ return [high >> 8, high & 255, low >> 8, low & 255].join('.');
100
+ }
101
+
102
+ const layers = (text, schemes = wrappers) => {
103
+ const url = parseURL(text);
104
+ if (!url) return [text];
105
+ const rest = url.href.slice(url.protocol.length).replace(escapes, decodedRun).toLowerCase();
106
+ if (schemes.includes(url.protocol)) return [text, ...layers(rest, schemes)];
107
+ const payload = payloads[url.protocol];
108
+ if (payload)
109
+ return [
110
+ text,
111
+ ...payload(rest)
112
+ .split(separators)
113
+ .filter(Boolean)
114
+ .flatMap((part) => layers(part, schemes)),
115
+ ];
116
+ return [text];
117
+ };
118
+
119
+ const leadingMarks = /^[\s\p{Cc}\p{Cf}\p{Mn}\p{Me}]+/u;
120
+ const trimLead = (text) => text.replace(leadingMarks, '');
121
+ const foldNFKC = (text) => text.normalize('NFKC');
122
+
123
+ const embeddedStart = /(?:[a-z][a-z0-9+.-]*:)?\/\//g;
124
+ const embeddedEnd = /[\s"'`<>(){}|^,;&]/;
125
+ const asURL = (text) => parseURL(text.startsWith('//') ? `http:${text}` : text);
126
+ const embeddedURLs = (text, relative = true) =>
127
+ [...text.matchAll(embeddedStart)]
128
+ .filter((match) => relative || match[0] !== '//')
129
+ .map((match) => asURL(text.slice(match.index).split(embeddedEnd)[0]))
130
+ .filter(Boolean);
131
+ const hostOnly = (text) =>
132
+ text
133
+ .replace(/^\/\//, '')
134
+ .replace(/^[^@/?#\s]*@/, '')
135
+ .replace(/\/$/, '');
136
+ const beyondOrigin = (url) => !['', '/'].includes(url.pathname) || Boolean(url.search || url.hash);
137
+
138
+ const nonBlankAbout = (text) => parseURL(text)?.protocol === 'about:' && text !== 'about:blank';
139
+
140
+ const layerRule = (text, check) => {
141
+ if (nonBlankAbout(text)) return 'about: non-bare';
142
+ if (check.relative && text.startsWith('//') && check.protectedHost(asURL(text)?.host))
143
+ return 'scheme-relative url';
144
+ const urlHost = parseURL(text)?.host;
145
+ if (check.protectedHost(urlHost))
146
+ return urlHost === check.exact ? 'protected host' : 'normalised host';
147
+ return check.protectedHost(check.hostToken(text)) ? 'host token' : undefined;
148
+ };
149
+
150
+ const namingRule = (all, check) => {
151
+ for (const [index, text] of all.entries()) {
152
+ const rule = layerRule(text, check);
153
+ if (rule) return index > 0 ? `${parseURL(all[0])?.protocol} unwrapped` : rule;
154
+ }
155
+ return undefined;
156
+ };
157
+
158
+ export function redactionLeak(
159
+ info,
160
+ { targetId, origin, tag },
161
+ {
162
+ normalize = normalizeHost,
163
+ hostToken = leadingHost,
164
+ trim = trimLead,
165
+ schemes = wrappers,
166
+ embedded = true,
167
+ relative = true,
168
+ fold = foldNFKC,
169
+ } = {}
170
+ ) {
171
+ const exact = parseURL(origin)?.host;
172
+ const host = normalize(exact ?? '');
173
+ const protectedHost = (candidate) => Boolean(host && candidate) && normalize(candidate) === host;
174
+ const check = { exact, protectedHost, hostToken, relative };
175
+ const prepared = (value) => fold(unwrapped(fold(String(value ?? ''))));
176
+ const texts = (value) => layers(prepared(value), schemes).map((text) => trim(fold(text)));
177
+ const embeds = (value) =>
178
+ embedded &&
179
+ texts(value).some((text) =>
180
+ embeddedURLs(text, relative).some((url) => protectedHost(url.host) && beyondOrigin(url))
181
+ );
182
+ const inner = (text) => {
183
+ const scheme = schemes.find((prefix) => text.startsWith(prefix));
184
+ return scheme ? inner(text.slice(scheme.length)) : text;
185
+ };
186
+ const bare = (value) =>
187
+ [undefined, '', 'about:blank', origin].includes(value) ||
188
+ inner(String(value ?? '')) === origin ||
189
+ protectedHost(hostOnly(trim(prepared(value))));
190
+ const fields = { url: info.url, title: info.title };
191
+ const names = Object.keys(fields);
192
+ const naming = names
193
+ .map((field) => [field, namingRule(texts(fields[field]), check)])
194
+ .find(([, rule]) => rule);
195
+ const exposed = names.find((field) => !bare(fields[field]));
196
+ if ((info.targetId === targetId || naming) && exposed) {
197
+ const [field, rule] = naming ?? [exposed, 'raw target id'];
198
+ return { field: exposed, rule, ...(field === exposed ? {} : { via: field }) };
199
+ }
200
+ const embedding = names.find((field) => embeds(fields[field]));
201
+ if (embedding) return { field: embedding, rule: 'embedded url with path' };
202
+ const secret = String(tag).toLowerCase();
203
+ const tagged = names.find((field) => unwrapped(fields[field]).includes(secret));
204
+ return tagged ? { field: tagged, rule: 'tag' } : undefined;
205
+ }
206
+
207
+ export function redactedInfo(info, scope, options) {
208
+ return !redactionLeak(info, scope, options);
209
+ }
210
+
211
+ const shownParts = (text, host) => {
212
+ const url = parseURL(text);
213
+ if (url && url.origin !== 'null') {
214
+ const parts = [
215
+ ['path', url.pathname === '/' ? '' : url.pathname],
216
+ ['query', url.search],
217
+ ['fragment', url.hash],
218
+ ]
219
+ .filter(([, part]) => part)
220
+ .map(([name, part]) => `${name}(${part.length} chars)`);
221
+ return [url.origin, ...parts].join(' + ');
222
+ }
223
+ const token = leadingHost(trimLead(text));
224
+ if (host && normalizeHost(token) === host)
225
+ return `${token} + ${text.length - token.length} chars`;
226
+ return `${url?.protocol ?? 'text'}(${text.length} chars)`;
227
+ };
228
+
229
+ export function maskedId(targetId, tag) {
230
+ const text = String(targetId ?? '');
231
+ if (!text) return '(no id)';
232
+ return unwrapped(text).includes(String(tag).toLowerCase()) ? `(${text.length}-char id)` : text;
233
+ }
234
+
235
+ export function maskedValue(value, tag, host) {
236
+ const text = String(value ?? '');
237
+ if (!text) return 'empty';
238
+ const shown = shownParts(text, host);
239
+ return unwrapped(shown).includes(String(tag).toLowerCase()) ? `(${text.length} chars)` : shown;
240
+ }
241
+
242
+ export function pickRawTarget(infos, { type, openerId, urlPrefix, known = new Set() }) {
243
+ return (infos ?? []).find(
244
+ (info) =>
245
+ info.type === type &&
246
+ info.targetId &&
247
+ !known.has(info.targetId) &&
248
+ (openerId === undefined || info.openerId === openerId) &&
249
+ (urlPrefix === undefined || String(info.url ?? '').startsWith(urlPrefix))
250
+ );
251
+ }
54
252
  const namedResultMs = 10000;
55
253
  const observeMs = 5000;
56
254
  const premises = { chainStarted: 'first hop not observed' };
@@ -155,8 +353,10 @@ const stateCheck = (check) =>
155
353
  [...(check?.all ?? []), ...(check?.any ?? []), ...(check?.not ? [check.not] : [])]
156
354
  .map(stateCheck)
157
355
  .find(Boolean);
158
- const refusedOut = (step, out) =>
159
- step.refusable ? isRefusal(out, step) : /refused/.test(String(out.error?.message ?? out.error));
356
+ const refusedOut = (step, out, gone = false) =>
357
+ step.refusable
358
+ ? isRefusal(out, step)
359
+ : !gone && /refused/.test(String(out.error?.message ?? out.error));
160
360
 
161
361
  function pageExpression(step, url) {
162
362
  let expression;
@@ -240,6 +440,8 @@ class Execution {
240
440
  this.cdpTrace = [];
241
441
  this.cdpSessionTypes = new Map();
242
442
  this.cdpTraceInstalled = false;
443
+ this.explicit = explicitVector(vector);
444
+ this.unanswered = new Set();
243
445
  }
244
446
 
245
447
  note(message) {
@@ -700,6 +902,7 @@ class Execution {
700
902
  );
701
903
  }
702
904
  if (
905
+ !this.explicit &&
703
906
  event.method === 'Target.attachedToTarget' &&
704
907
  event.params.targetInfo?.targetId !== this.pageTarget &&
705
908
  event.params.targetInfo?.targetId !== this.canaryTarget &&
@@ -892,7 +1095,7 @@ class Execution {
892
1095
  }
893
1096
 
894
1097
  record(step, out, session, phase, gone) {
895
- const refused = !gone && refusedOut(step, out);
1098
+ const refused = refusedOut(step, out, gone);
896
1099
  this.trace.push({
897
1100
  phase,
898
1101
  declared: Boolean(step.refusable),
@@ -903,7 +1106,7 @@ class Execution {
903
1106
  });
904
1107
  const unanswered =
905
1108
  step.refusable &&
906
- exitsClient(this.vector) &&
1109
+ (exitsClient(this.vector) || this.explicit) &&
907
1110
  !out.ok &&
908
1111
  !refused &&
909
1112
  /timeout|timed out|no answer/i.test(String(out.error?.message ?? out.error));
@@ -1130,6 +1333,7 @@ class Execution {
1130
1333
  castControls: (this.clients.castControls ??= {}),
1131
1334
  })
1132
1335
  );
1336
+ if (step.rawTarget) return outcome(this.rawTarget(step.rawTarget));
1133
1337
  if (step.guess) return this.guess(step.guess, session);
1134
1338
  if (step.isolatedWorld) return outcome(this.isolatedWorld(step));
1135
1339
  if (step.observer) return outcome(this.watchPage(step));
@@ -1592,6 +1796,15 @@ class Execution {
1592
1796
  );
1593
1797
  }
1594
1798
 
1799
+ settleMissing(missing) {
1800
+ if (
1801
+ exitsClient(this.vector) ||
1802
+ (this.explicit && (this.unanswered.size || !this.sessions.child))
1803
+ )
1804
+ this.incomplete.push(missing);
1805
+ else this.errors.push(missing);
1806
+ }
1807
+
1595
1808
  async settle(settle) {
1596
1809
  const refused = () => (settle.dependsOn ?? []).some((name) => this.refused[name]);
1597
1810
  const skipped = () => {
@@ -1631,9 +1844,117 @@ class Execution {
1631
1844
  if (refused() && !alt) return skipped();
1632
1845
  if (settle.required && !met) {
1633
1846
  const missing = `settle: no ${settle.beacon ? `beacon from ${settle.beacon}` : settle.served ? `request for ${settle.served}` : settle.title ? `title ${settle.title}` : 'load'} within ${this.bound(settle.ms ?? 1500)}ms`;
1634
- if (exitsClient(this.vector)) this.incomplete.push(missing);
1635
- else this.errors.push(missing);
1847
+ this.settleMissing(missing);
1848
+ }
1849
+ }
1850
+
1851
+ async rawTarget(spec) {
1852
+ const known = new Set([this.pageTarget, this.canaryTarget].filter(Boolean));
1853
+ const want = {
1854
+ type: spec.type,
1855
+ openerId: spec.openerId === 'page' ? this.pageTarget : undefined,
1856
+ urlPrefix: spec.urlPrefix,
1857
+ known,
1858
+ };
1859
+ let found;
1860
+ let listing = [];
1861
+ await this.poll(async () => {
1862
+ const listed = await outcome(this.reader.send('Target.getTargets', { filter: [{}] }));
1863
+ listing = listed.ok ? (listed.result?.targetInfos ?? []) : [];
1864
+ found = pickRawTarget(listing, want);
1865
+ return Boolean(found);
1866
+ }, spec.ms);
1867
+ if (!found) {
1868
+ this.incomplete.push(
1869
+ `rawTarget: the observer found no ${spec.type}${spec.openerId ? ' opened by the page' : ''}${spec.urlPrefix ? ` at ${spec.urlPrefix}` : ''} within ${this.bound(spec.ms)}ms`
1870
+ );
1871
+ return { found: false };
1872
+ }
1873
+ this.vars.rawTarget = found.targetId;
1874
+ this.vars.rawTargetUrl = found.url;
1875
+ this.targets.push(found.targetId);
1876
+ this.classifyFirstListing(listing, found, spec.urlPrefix);
1877
+ return { found: true, targetId: found.targetId, type: found.type };
1878
+ }
1879
+
1880
+ classifyFirstListing(listing, found, urlPrefix) {
1881
+ const own = (info) =>
1882
+ info.targetId === found.targetId ||
1883
+ (urlPrefix !== undefined && String(info.url ?? '').startsWith(urlPrefix));
1884
+ this.ownTargets = new Set(listing.filter(own).map((info) => info.targetId));
1885
+ const foreign = listing.filter((info) => !own(info));
1886
+ this.foreignTargets = new Set(foreign.map((info) => info.targetId));
1887
+ const pages = foreign.filter((info) => info.type === 'page');
1888
+ const shown = pages.map(
1889
+ (info) => `${info.targetId} ${maskedValue(parseURL(info.url)?.origin ?? '', this.vars.tag)}`
1890
+ );
1891
+ this.note(
1892
+ `rawTarget: ${pages.length} foreign page target(s) at the first listing${shown.length ? `: ${shown.join(', ')}` : ''}`
1893
+ );
1894
+ }
1895
+
1896
+ async targetClass(info, scope) {
1897
+ if (info.targetId === scope.targetId) return 'raw target';
1898
+ if (this.ownTargets?.has(info.targetId)) return 'own target';
1899
+ const context = this.vars.context;
1900
+ if (
1901
+ this.foreignTargets?.has(info.targetId) ||
1902
+ (context && info.browserContextId && info.browserContextId !== context)
1903
+ )
1904
+ return 'foreign target';
1905
+ if (!this.observerIds) {
1906
+ const out = await this.answered(this.reader.send('Target.getTargets', { filter: [{}] }));
1907
+ this.observerIds = new Set(
1908
+ (out.ok ? (out.result?.targetInfos ?? []) : []).map((i) => i.targetId)
1909
+ );
1636
1910
  }
1911
+ return this.observerIds.has(info.targetId) ? 'foreign target' : 'id unknown to the observer';
1912
+ }
1913
+
1914
+ async answered(pending) {
1915
+ let timer;
1916
+ const out = await Promise.race([
1917
+ outcome(pending),
1918
+ new Promise((resolve) => {
1919
+ timer = setTimeout(
1920
+ () => resolve({ ok: false, error: { message: 'no answer' } }),
1921
+ this.bound(this.options.namedResultMs ?? namedResultMs)
1922
+ );
1923
+ }),
1924
+ ]);
1925
+ clearTimeout(timer);
1926
+ return out;
1927
+ }
1928
+
1929
+ noAnswer(step, message = 'no answer') {
1930
+ if (step.as) this.unanswered.add(step.as);
1931
+ if (!step.refusable) this.incomplete.push(`${step.as ?? step.cdp}: no answer`);
1932
+ return { ok: false, error: { message } };
1933
+ }
1934
+
1935
+ async explicitCall(step, params, session) {
1936
+ if (q(params).includes('{rawTarget}'))
1937
+ return this.noAnswer(step, 'no answer: the observer found no raw target');
1938
+ if (step.session === 'child' && !this.sessions.child) {
1939
+ if (this.unanswered.has(this.bindName) && step.as) this.unanswered.add(step.as);
1940
+ return { ok: false, error: { message: 'no child session' } };
1941
+ }
1942
+ if (step.cdp === 'Target.setDiscoverTargets' && params.discover) {
1943
+ this.discovering = true;
1944
+ this.discoverName = step.as;
1945
+ }
1946
+ if (params.browserContextId === '{context}') delete params.browserContextId;
1947
+ const client = step.via === 'unguarded' ? this.reader : this.actor();
1948
+ const out = await this.answered(client.send(step.cdp, params, session));
1949
+ if (!out.ok && /timeout|timed out|no answer/i.test(String(out.error?.message ?? out.error)))
1950
+ this.noAnswer(step);
1951
+ if (step.bindSession) {
1952
+ this.bindName = step.as;
1953
+ if (out.ok && out.result?.sessionId) this.sessions.child = out.result.sessionId;
1954
+ }
1955
+ if (step.cdp === 'Target.createTarget' && out.ok && out.result?.targetId)
1956
+ this.targets.push(out.result.targetId);
1957
+ return out;
1637
1958
  }
1638
1959
 
1639
1960
  async guess(guess, session) {
@@ -1672,6 +1993,7 @@ class Execution {
1672
1993
  } catch (error) {
1673
1994
  return { ok: false, error: { message: error.message } };
1674
1995
  }
1996
+ if (this.explicit) return this.explicitCall(step, params, sessionId);
1675
1997
  const session =
1676
1998
  step.session === 'page-or-browser' &&
1677
1999
  supported(['browserSession'], this.options.capabilities) &&
@@ -1862,6 +2184,7 @@ class Execution {
1862
2184
  }
1863
2185
 
1864
2186
  observeEarly(name, check, want) {
2187
+ if (this.explicit && this.explicitIncomplete(check)) return 'incomplete';
1865
2188
  if (name === 'workerReachable' && this.probeStep())
1866
2189
  return this.observeProbeReachable(want, check);
1867
2190
  if (check?.forwarded) return this.forwardedCheck(name, check, want);
@@ -2038,6 +2361,8 @@ class Execution {
2038
2361
  }
2039
2362
 
2040
2363
  async evidence(c) {
2364
+ if (c.redacted) return this.redactedCheck(c.redacted);
2365
+ if (c.detached && this.explicit) return this.explicitDetached();
2041
2366
  if (c.filtered) {
2042
2367
  const calls =
2043
2368
  c.filtered.from === 'all'
@@ -2097,7 +2422,90 @@ class Execution {
2097
2422
  );
2098
2423
  }
2099
2424
 
2425
+ explicitDetached() {
2426
+ const session = this.sessions.child;
2427
+ return this.client.events
2428
+ .slice(this.eventStart, this.cleanupEventStart)
2429
+ .some(
2430
+ (event) =>
2431
+ event.method === 'Target.detachedFromTarget' &&
2432
+ ((session && event.params?.sessionId === session) ||
2433
+ (this.vars.rawTarget && event.params?.targetId === this.vars.rawTarget))
2434
+ );
2435
+ }
2436
+
2437
+ explicitAttached() {
2438
+ if (this.sessions.child) return true;
2439
+ return this.client.events
2440
+ .slice(this.eventStart, this.cleanupEventStart)
2441
+ .some(
2442
+ (event) =>
2443
+ event.method === 'Target.attachedToTarget' &&
2444
+ Boolean(this.vars.rawTarget) &&
2445
+ event.params?.targetInfo?.targetId === this.vars.rawTarget
2446
+ );
2447
+ }
2448
+
2449
+ async redactedCheck(from) {
2450
+ const origin = parseURL(this.vars.rawTargetUrl)?.origin;
2451
+ if (!this.vars.rawTarget || !origin) return 'incomplete';
2452
+ const unread = from === 'events' ? undefined : from.find((name) => this.unread(name));
2453
+ if (unread) {
2454
+ const reason = `redacted: ${unread} gave no reply to read`;
2455
+ if (!this.incomplete.includes(reason)) this.incomplete.push(reason);
2456
+ return 'incomplete';
2457
+ }
2458
+ const entries =
2459
+ from === 'events'
2460
+ ? this.client.events
2461
+ .slice(this.eventStart, this.cleanupEventStart)
2462
+ .filter((event) => discoveryMethods.includes(event.method))
2463
+ .map((event) => ({ info: event.params?.targetInfo, source: event.method }))
2464
+ : from.flatMap((name) => {
2465
+ const out = this.calls[name];
2466
+ return out?.ok
2467
+ ? [out.result?.targetInfo, ...(out.result?.targetInfos ?? [])].map((info) => ({
2468
+ info,
2469
+ source: name,
2470
+ }))
2471
+ : [];
2472
+ });
2473
+ const scope = { targetId: this.vars.rawTarget, origin, tag: this.vars.tag };
2474
+ const leaks = entries
2475
+ .filter(({ info }) => info)
2476
+ .map((entry) => ({ ...entry, leak: redactionLeak(entry.info, scope) }))
2477
+ .filter(({ leak }) => leak);
2478
+ for (const { info, source, leak } of leaks.slice(0, 5)) {
2479
+ const id = maskedId(info.targetId, scope.tag);
2480
+ const value = maskedValue(info[leak.field], scope.tag, normalizeHost(parseURL(origin)?.host));
2481
+ const via = leak.via ? ` via ${leak.via}` : '';
2482
+ const note = `${this.observing ?? 'redacted'}: ${source} entry ${id} (${await this.targetClass(info, scope)}) ${leak.field} ${value} fails redaction: ${leak.rule}${via}`;
2483
+ if (!this.notes.includes(note)) this.note(note);
2484
+ }
2485
+ return leaks.length === 0;
2486
+ }
2487
+
2488
+ unread(name) {
2489
+ const out = this.calls[name];
2490
+ return !out || (!out.ok && this.refused[name] !== true);
2491
+ }
2492
+
2493
+ explicitIncomplete(check) {
2494
+ const names = (c) => [
2495
+ ...resultNames(c),
2496
+ ...(Array.isArray(c?.refused) ? c.refused : []),
2497
+ ...(Array.isArray(c?.redacted) ? c.redacted : []),
2498
+ ...(c?.attached !== undefined || c?.detached || c?.session === 'child'
2499
+ ? [this.bindName]
2500
+ : []),
2501
+ ...(c?.event || c?.redacted === 'events' ? [this.discoverName] : []),
2502
+ ...[...(c?.all ?? []), ...(c?.any ?? []), ...(c?.not ? [c.not] : [])].flatMap(names),
2503
+ ];
2504
+ return names(check).some((name) => this.unanswered.has(name));
2505
+ }
2506
+
2100
2507
  attachedCheck(c) {
2508
+ if (this.explicit) return this.explicitAttached();
2101
2509
  const session = this.sessions[c.session ?? 'page'];
2102
2510
  const events = this.client.events.slice(this.eventStart, this.cleanupEventStart);
2103
2511
  if (
@@ -2159,12 +2567,16 @@ class Execution {
2159
2567
  }
2160
2568
 
2161
2569
  async readCheck(c) {
2162
- const targetId = c.session === 'child' ? this.targets.at(-1) : this.pageTarget;
2570
+ const child = this.explicit ? this.vars.rawTarget : this.targets.at(-1);
2571
+ const targetId = c.session === 'child' ? child : this.pageTarget;
2163
2572
  if (!targetId) return false;
2164
- const { sessionId } = await this.reader.send('Target.attachToTarget', {
2165
- targetId,
2166
- flatten: true,
2167
- });
2573
+ const attach = this.reader.send('Target.attachToTarget', { targetId, flatten: true });
2574
+ const attached = this.explicit ? await outcome(attach) : { ok: true, result: await attach };
2575
+ if (!attached.ok) {
2576
+ this.incomplete.push(`read: the observer could not attach to ${targetId}`);
2577
+ return 'incomplete';
2578
+ }
2579
+ const { sessionId } = attached.result;
2168
2580
  try {
2169
2581
  const out = await this.evaluate(c.expression ?? 'document.title', sessionId, this.reader);
2170
2582
  return matches(observedValue(out, 'result.result.value'), c.title ?? c.equals);
@@ -2176,6 +2588,10 @@ class Execution {
2176
2588
  async observeAll(unseen) {
2177
2589
  const observed = { ...this.refused };
2178
2590
  const incomplete = [];
2591
+ if (await this.explicitLost()) {
2592
+ for (const name of Object.keys(this.vector.observe ?? {})) observed[name] = 'incomplete';
2593
+ return { observed, incomplete };
2594
+ }
2179
2595
  const capabilities = withCookiePlantCaps(this.options.capabilities, this.calls.probe?.result);
2180
2596
  let measured = 0;
2181
2597
  let excused = 0;
@@ -2194,6 +2610,7 @@ class Execution {
2194
2610
  continue;
2195
2611
  }
2196
2612
  measured++;
2613
+ this.observing = name;
2197
2614
  observed[name] = await this.observe(name, observation.check);
2198
2615
  if (observed[name] === 'unwatched') {
2199
2616
  observed[name] = 'incomplete';
@@ -2209,6 +2626,7 @@ class Execution {
2209
2626
  if (holds === 'incomplete') incomplete.push(name);
2210
2627
  }
2211
2628
  this.premises(observed);
2629
+ this.explicitPremises(observed);
2212
2630
  if (this.side === 'control' && excused && !measured) this.incomplete.push('measured nothing');
2213
2631
  return { observed, incomplete };
2214
2632
  }
@@ -2229,6 +2647,37 @@ class Execution {
2229
2647
  if (want?.[name] === true && observed[name] === false) observed[name] = 'incomplete';
2230
2648
  }
2231
2649
 
2650
+ async explicitLost() {
2651
+ if (!this.explicit || !this.vars.rawTarget) return false;
2652
+ const targetId = this.vars.rawTarget;
2653
+ const read = await outcome(this.reader.send('Target.getTargetInfo', { targetId }));
2654
+ if (read.ok && read.result?.targetInfo) return false;
2655
+ this.incomplete.push(
2656
+ `rawTarget: the observer lost ${targetId} before the guarded probes ended`
2657
+ );
2658
+ this.unrun();
2659
+ return true;
2660
+ }
2661
+
2662
+ unrun() {
2663
+ const unrun = this.errors.filter((error) => / failed without a refusal: /.test(error));
2664
+ this.errors = this.errors.filter((error) => !unrun.includes(error));
2665
+ this.incomplete.push(...unrun);
2666
+ }
2667
+
2668
+ explicitPremises(observed) {
2669
+ if (!this.explicit || this.side !== 'control') return;
2670
+ this.unrun();
2671
+ const observe = this.vector.observe ?? {};
2672
+ const missing = controlPremises.filter(
2673
+ (name) => Object.hasOwn(observe, name) && observed[name] !== true
2674
+ );
2675
+ for (const name of missing)
2676
+ if (observed[name] !== 'incomplete')
2677
+ this.incomplete.push(`${name}: the unguarded control did not show it`);
2678
+ if (missing.length) for (const name of Object.keys(observe)) observed[name] = 'incomplete';
2679
+ }
2680
+
2232
2681
  async either(check, value, name, unseen) {
2233
2682
  const holds = () => this.check(check);
2234
2683
  if (await holds()) return true;
@@ -2306,6 +2755,8 @@ class Execution {
2306
2755
  }
2307
2756
 
2308
2757
  async cleanupLeg() {
2758
+ if (this.discovering)
2759
+ await this.answered(this.client.send('Target.setDiscoverTargets', { discover: false }));
2309
2760
  if (this.watch)
2310
2761
  await outcome(
2311
2762
  this.reader.send('Target.detachFromTarget', { sessionId: this.watch.sessionId })
@@ -2391,7 +2842,8 @@ const needsObserver = (vector) =>
2391
2842
  step.protectedParentIframes ||
2392
2843
  step.credentialExport ||
2393
2844
  step.signInHold ||
2394
- step.cookiePlant
2845
+ step.cookiePlant ||
2846
+ step.rawTarget
2395
2847
  ) ||
2396
2848
  vector.control.via === 'unguarded' ||
2397
2849
  observerRequired(vector.liveCheck) ||
@@ -2898,6 +3350,9 @@ function validateScales(opts) {
2898
3350
  function validate(set, opts) {
2899
3351
  if (!opts.fixture?.log) throw new TypeError('fixture.log is required');
2900
3352
  validateScales(opts);
3353
+ const both = exclusive.filter((capability) => declared(capability, opts.capabilities));
3354
+ if (declared('explicitAttach', opts.capabilities) && both.length)
3355
+ throw new TypeError(`explicitAttach excludes ${both.join(' and ')} in one run`);
2901
3356
  for (const vector of set.vectors)
2902
3357
  for (const [name, observation] of Object.entries(vector.observe ?? {}))
2903
3358
  if (!observation.check) throw new TypeError(`${vector.id}: ${name} lacks a check`);