@ai-ecoverse/slicc-browsers 1.28.5 → 1.29.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.
@@ -0,0 +1,4353 @@
1
+ import { outcome, waitFor } from './guard-driver.mjs';
2
+ import { createObserverTarget } from './observer-target.mjs';
3
+
4
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5
+
6
+ const bytesOf = (text) => new TextEncoder().encode(text);
7
+ const b64 = (bytes) => {
8
+ let s = '';
9
+ for (const byte of bytes) s += String.fromCharCode(byte);
10
+ return btoa(s);
11
+ };
12
+ const b64text = (text) => b64(bytesOf(text));
13
+ const fromB64 = (text) =>
14
+ new TextDecoder().decode(Uint8Array.from(atob(text), (char) => char.charCodeAt(0)));
15
+
16
+ function cookieNames(tag) {
17
+ const id = String(tag ?? '')
18
+ .replace(/[^a-zA-Z0-9]/g, '')
19
+ .slice(-20);
20
+ const suffix = id || 'x';
21
+ return {
22
+ plant: `cplant${suffix}`,
23
+ ordinary: `oord${suffix}`,
24
+ adobe: `oadobe${suffix}`,
25
+ delete: `sid${suffix}`,
26
+ };
27
+ }
28
+
29
+ function answered(out) {
30
+ if (!out) return false;
31
+ if (out.ok) return true;
32
+ const err = out.error;
33
+ if (err && typeof err.code === 'number') return true;
34
+ const message = String(err?.message ?? err ?? '');
35
+ if (/^slicc: refused:/.test(message)) return true;
36
+ if (/Invalid (parameters|Params)|Invalid request id|continueResponse at Request/i.test(message))
37
+ return true;
38
+ return false;
39
+ }
40
+
41
+ function refused(out) {
42
+ if (!out || out.ok) return false;
43
+ return /^slicc: refused:/.test(String(out.error?.message ?? out.error ?? ''));
44
+ }
45
+
46
+ function sessionCut(out) {
47
+ return refused(out);
48
+ }
49
+
50
+ function note(notes, label, evidence) {
51
+ notes.push(`${label}: ${JSON.stringify(evidence)}`);
52
+ }
53
+
54
+ async function pageSnapshot(client, pageSession) {
55
+ if (!pageSession) return { ready: false };
56
+ const ready = await capped(
57
+ outcome(
58
+ client.send(
59
+ 'Runtime.evaluate',
60
+ { expression: 'document.readyState', returnByValue: true },
61
+ pageSession
62
+ )
63
+ ),
64
+ 800,
65
+ 'pageSnapshot'
66
+ );
67
+ const href = await capped(
68
+ outcome(
69
+ client.send(
70
+ 'Runtime.evaluate',
71
+ { expression: 'location.href', returnByValue: true },
72
+ pageSession
73
+ )
74
+ ),
75
+ 800,
76
+ 'pageSnapshot'
77
+ );
78
+ return {
79
+ ready: ready.ok,
80
+ readyState: ready.result?.result?.value ?? null,
81
+ href: href.ok ? (href.result?.result?.value ?? null) : null,
82
+ readyError: ready.ok ? undefined : String(ready.error?.message ?? ready.error),
83
+ hrefError: href.ok ? undefined : String(href.error?.message ?? href.error),
84
+ };
85
+ }
86
+
87
+ async function serverHitsFor(fixtureLog, url, since) {
88
+ if (typeof fixtureLog !== 'function') return null;
89
+ let entries;
90
+ try {
91
+ entries = await fixtureLog();
92
+ } catch (error) {
93
+ return { error: String(error?.message ?? error) };
94
+ }
95
+ if (!Array.isArray(entries)) return { error: 'fixture log not an array' };
96
+ const matched = entries.filter(
97
+ (entry) =>
98
+ Number(entry?.time ?? 0) >= since &&
99
+ (entry?.url === url || String(entry?.url ?? '').startsWith(url))
100
+ );
101
+ const byPath = {};
102
+ for (const entry of entries) {
103
+ if (Number(entry?.time ?? 0) < since) continue;
104
+ let path = entry?.url ?? '';
105
+ try {
106
+ path = new URL(entry.url).pathname;
107
+ } catch {}
108
+ byPath[path] = (byPath[path] ?? 0) + 1;
109
+ }
110
+ return { hits: matched.length, urls: matched.map((e) => e.url), byPath };
111
+ }
112
+
113
+ async function diagnoseIncomplete({
114
+ notes,
115
+ label,
116
+ incomplete,
117
+ url,
118
+ client,
119
+ pageSession,
120
+ from,
121
+ methods,
122
+ pauseMs,
123
+ startedAt,
124
+ legStartedAt,
125
+ fixtureLog,
126
+ ensure,
127
+ trigger,
128
+ firstIncomplete,
129
+ handle,
130
+ }) {
131
+ const elapsedMs = Date.now() - startedAt;
132
+ const legElapsedMs = Date.now() - legStartedAt;
133
+ const page = await pageSnapshot(client, pageSession);
134
+ const since = client.events.slice(from);
135
+ const pauses = pauseEvents(since, 0, url, methods);
136
+ const anyPaused = since.filter((event) => methods.includes(event.method)).length;
137
+ const server = await serverHitsFor(fixtureLog, url, startedAt);
138
+ const timing = timingOf(handle);
139
+ const evidence = {
140
+ incomplete,
141
+ path: label,
142
+ url,
143
+ elapsedMs,
144
+ legElapsedMs,
145
+ pauseMs,
146
+ ensure: ensure ?? null,
147
+ triggerOk: trigger?.ok ?? null,
148
+ triggerError: trigger?.ok ? undefined : String(trigger?.error?.message ?? trigger?.error ?? ''),
149
+ page,
150
+ pauseHits: pauses.length,
151
+ anyPaused,
152
+ server,
153
+ ...timing,
154
+ };
155
+ note(notes, `cookie-plant.${label}`, evidence);
156
+ if (firstIncomplete && !firstIncomplete.noted) {
157
+ firstIncomplete.noted = true;
158
+ note(notes, 'cookie-plant.firstIncomplete', evidence);
159
+ }
160
+ return evidence;
161
+ }
162
+
163
+ function hostOf(origin) {
164
+ try {
165
+ return new URL(origin).hostname.toLowerCase();
166
+ } catch {
167
+ return '';
168
+ }
169
+ }
170
+
171
+ function cookieHeader(name, value, domain, extra = '', domainAttr = null) {
172
+ const parts = [`${name}=${value}`];
173
+ if (domainAttr) parts.push(domainAttr);
174
+ else if (domain) parts.push(`Domain=${domain}`);
175
+ parts.push('Path=/');
176
+ if (extra) parts.push(extra);
177
+ return parts.join('; ');
178
+ }
179
+
180
+ const hstsPreloaded = (host) => {
181
+ const name = String(host ?? '')
182
+ .toLowerCase()
183
+ .replace(/\.$/, '');
184
+ return (
185
+ name === 'adobe.com' ||
186
+ name.endsWith('.adobe.com') ||
187
+ name === 'adobelogin.com' ||
188
+ name.endsWith('.adobelogin.com')
189
+ );
190
+ };
191
+
192
+ function fixtureOriginFor(templateUrl, host, { insecurePreloaded = false } = {}) {
193
+ try {
194
+ const parsed = new URL(templateUrl);
195
+ const name = host ?? parsed.hostname;
196
+ const port = parsed.port ? `:${parsed.port}` : '';
197
+ const scheme =
198
+ !insecurePreloaded && hstsPreloaded(name) ? 'https:' : (parsed?.protocol ?? 'http:');
199
+ return `${scheme}//${name}${port}`;
200
+ } catch {
201
+ return null;
202
+ }
203
+ }
204
+
205
+ function siteHost(host) {
206
+ const parts = String(host ?? '')
207
+ .toLowerCase()
208
+ .split('.')
209
+ .filter(Boolean);
210
+ return parts.length >= 2 ? parts.slice(-2).join('.') : String(host ?? '').toLowerCase();
211
+ }
212
+
213
+ function binaryHeaders(pairs) {
214
+ const chunks = [];
215
+ for (const { name, value } of pairs) {
216
+ chunks.push(`${name}: ${value}`);
217
+ }
218
+ return b64text(`${chunks.join('\0')}\0`);
219
+ }
220
+
221
+ function rawHttpResponse({ code, phrase, headers, body = '' }) {
222
+ const lines = [`HTTP/1.1 ${code} ${phrase}`];
223
+ for (const { name, value } of headers) lines.push(`${name}: ${value}`);
224
+ lines.push('', body);
225
+ return b64text(lines.join('\r\n'));
226
+ }
227
+
228
+ async function until(check, ms, step = 25) {
229
+ const deadline = Date.now() + ms;
230
+ for (;;) {
231
+ const value = await check();
232
+ if (value) return value;
233
+ if (Date.now() > deadline) return null;
234
+ await pause(step);
235
+ }
236
+ }
237
+
238
+ async function openPage(reader, url, notes, internalSessions, browserContextId = null) {
239
+ const created = await outcome(
240
+ createObserverTarget(
241
+ reader,
242
+ { url, ...(browserContextId ? { browserContextId } : {}) },
243
+ notes
244
+ ).then(async (result) => {
245
+ const { sessionId } = await reader.send('Target.attachToTarget', {
246
+ targetId: result.targetId,
247
+ flatten: true,
248
+ });
249
+ await reader.send('Page.enable', {}, sessionId);
250
+ await reader.send('Runtime.enable', {}, sessionId);
251
+ await reader.send('Network.enable', {}, sessionId);
252
+ return { targetId: result.targetId, sessionId };
253
+ })
254
+ );
255
+ if (!created.ok) return created;
256
+ internalSessions.add(created.result.sessionId);
257
+ const ready = await waitFor(async () => {
258
+ const read = await outcome(
259
+ reader.send(
260
+ 'Runtime.evaluate',
261
+ { expression: 'document.readyState', returnByValue: true },
262
+ created.result.sessionId
263
+ )
264
+ );
265
+ return read.ok && ['interactive', 'complete'].includes(read.result?.result?.value);
266
+ }, 4000);
267
+ note(notes, 'cookie-plant.open', {
268
+ targetId: created.result.targetId,
269
+ url,
270
+ ready: Boolean(ready),
271
+ });
272
+ if (!ready)
273
+ return {
274
+ ok: true,
275
+ result: { incomplete: 'opener page did not become ready', ...created.result },
276
+ };
277
+ return created;
278
+ }
279
+
280
+ async function detectTransport(client, sessionId, notes) {
281
+ const fetchEnable = await capped(
282
+ outcome(
283
+ client.send(
284
+ 'Fetch.enable',
285
+ {
286
+ patterns: [
287
+ { urlPattern: '*', requestStage: 'Request' },
288
+ { urlPattern: '*', requestStage: 'Response' },
289
+ ],
290
+ },
291
+ sessionId
292
+ )
293
+ ),
294
+ 800,
295
+ 'detectTransport'
296
+ );
297
+ if (fetchEnable.ok) {
298
+ note(notes, 'cookie-plant.transport', { kind: 'fetch' });
299
+ return { kind: 'fetch', fetch: true, legacy: false, fetchEnable };
300
+ }
301
+ if (refused(fetchEnable) || /timeout/i.test(String(fetchEnable.error?.message ?? ''))) {
302
+ note(notes, 'cookie-plant.transport', {
303
+ kind: 'fetch',
304
+ enable: refused(fetchEnable) ? 'refused' : 'unanswered',
305
+ });
306
+ return { kind: 'fetch', fetch: true, legacy: false, fetchEnable };
307
+ }
308
+ const legacyEnable = await capped(
309
+ outcome(
310
+ client.send('Network.setRequestInterception', { patterns: [{ urlPattern: '*' }] }, sessionId)
311
+ ),
312
+ 800,
313
+ 'detectTransport'
314
+ );
315
+ if (legacyEnable.ok) {
316
+ note(notes, 'cookie-plant.transport', { kind: 'legacy' });
317
+ return { kind: 'legacy', fetch: false, legacy: true, fetchEnable: null };
318
+ }
319
+ note(notes, 'cookie-plant.transport', {
320
+ kind: null,
321
+ fetchError: String(fetchEnable.error?.message ?? fetchEnable.error),
322
+ legacyError: String(legacyEnable.error?.message ?? legacyEnable.error),
323
+ });
324
+ return { kind: null, fetch: false, legacy: false, fetchEnable: null };
325
+ }
326
+
327
+ async function enableLegacy(client, sessionId) {
328
+ return outcome(
329
+ client.send('Network.setRequestInterception', { patterns: [{ urlPattern: '*' }] }, sessionId)
330
+ );
331
+ }
332
+
333
+ async function disableInterception(client, sessionId, transport) {
334
+ if (transport.fetch) await outcome(client.send('Fetch.disable', {}, sessionId));
335
+ if (transport.legacy)
336
+ await outcome(client.send('Network.setRequestInterception', { patterns: [] }, sessionId));
337
+ }
338
+
339
+ function pauseEvents(events, from, url, methods) {
340
+ return events.slice(from).filter((event) => {
341
+ if (!methods.includes(event.method)) return false;
342
+ const requestUrl = event.params?.request?.url ?? event.params?.request?.urlFragment;
343
+ return requestUrl === url || String(requestUrl ?? '').startsWith(url);
344
+ });
345
+ }
346
+
347
+ async function waitPause(client, from, url, methods, budget) {
348
+ return until(() => {
349
+ const hits = pauseEvents(client.events, from, url, methods);
350
+ return hits.at(-1) ?? null;
351
+ }, budget);
352
+ }
353
+
354
+ async function tabHrefFromReader(reader, pageTarget) {
355
+ if (!reader || !pageTarget) return null;
356
+ const info = await capped(
357
+ outcome(reader.send('Target.getTargetInfo', { targetId: pageTarget })),
358
+ 800,
359
+ 'tabHref'
360
+ );
361
+ if (!info.ok) return null;
362
+ const value = info.result?.targetInfo?.url;
363
+ return typeof value === 'string' ? value : null;
364
+ }
365
+
366
+ async function readTabHref({ reader, pageTarget }) {
367
+ return tabHrefFromReader(reader, pageTarget);
368
+ }
369
+
370
+ function pathRequestMatch(reqUrl, url) {
371
+ if (!reqUrl || !url) return false;
372
+ if (reqUrl === url || reqUrl.startsWith(`${url}&`) || reqUrl.startsWith(`${url}#`)) return true;
373
+ try {
374
+ const want = new URL(url);
375
+ const got = new URL(reqUrl);
376
+ if (want.origin !== got.origin || want.pathname !== got.pathname) return false;
377
+ for (const [key, value] of want.searchParams) {
378
+ if (got.searchParams.get(key) !== value) return false;
379
+ }
380
+ return want.searchParams.toString().length > 0 || got.searchParams.toString().length === 0;
381
+ } catch {
382
+ return false;
383
+ }
384
+ }
385
+
386
+ function readerNetworkBlocked(reader, sessionId, url, from = 0) {
387
+ if (!reader?.events || !url || !sessionId) return false;
388
+ const events = reader.events.slice(Math.max(0, from));
389
+ const requests = new Map();
390
+ for (const event of events) {
391
+ if (event.sessionId !== sessionId) continue;
392
+ if (event.method === 'Network.requestWillBeSent') {
393
+ const id = event.params?.requestId;
394
+ if (!id) continue;
395
+ const reqUrl = String(event.params?.request?.url ?? '');
396
+ if (pathRequestMatch(reqUrl, url)) requests.set(id, reqUrl);
397
+ }
398
+ if (event.method === 'Network.loadingFailed') {
399
+ const id = event.params?.requestId;
400
+ if (!id || !requests.has(id)) continue;
401
+ const err = String(event.params?.errorText ?? event.params?.blockedReason ?? '');
402
+ if (/ERR_BLOCKED_BY_CLIENT|BlockedByClient/i.test(err)) return true;
403
+ }
404
+ }
405
+ return false;
406
+ }
407
+
408
+ async function quietFixture(fixtureLog, ms) {
409
+ const quiet = Math.max(25, Number(ms) || 100);
410
+ if (typeof fixtureLog !== 'function') {
411
+ await pause(quiet);
412
+ return;
413
+ }
414
+ const deadline = Date.now() + quiet * 8;
415
+ let last = -1;
416
+ while (Date.now() < deadline) {
417
+ let length = 0;
418
+ try {
419
+ const entries = await fixtureLog();
420
+ length = Array.isArray(entries) ? entries.length : 0;
421
+ } catch {
422
+ length = Math.max(last, 0);
423
+ }
424
+ if (last >= 0 && length === last) return;
425
+ last = length;
426
+ await pause(quiet);
427
+ }
428
+ }
429
+
430
+ function leftHome(href, homeUrl) {
431
+ if (!href || !homeUrl) return false;
432
+ if (href === homeUrl) return false;
433
+ try {
434
+ const home = new URL(homeUrl);
435
+ const now = new URL(href);
436
+ if (now.href === home.href) return false;
437
+ if (now.origin === home.origin && now.pathname === home.pathname) return false;
438
+ } catch {
439
+ return href !== homeUrl;
440
+ }
441
+ return true;
442
+ }
443
+
444
+ async function continueItselfEvidence({ fixtureLog, url, since, tag, proofTag, cookie, handle }) {
445
+ requireAttemptHandle(handle, 'continueItselfEvidence');
446
+ if (!fixtureLog || !url || !cookie || !handle.readerSession) return null;
447
+ const hits = await fixtureHitsFor(fixtureLog, url, since, tag, proofTag);
448
+ if (typeof hits !== 'number' || hits < 1) return null;
449
+ const jar = await capped(readJarWithCanary(handle, cookie), 1500, 'readJar');
450
+ const planted = plantedOf(
451
+ jar?.error?.message?.includes('timeout') ? { incomplete: 'cookie jar unreadable' } : jar
452
+ );
453
+ return { fixtureHits: hits, planted, jar };
454
+ }
455
+
456
+ async function pollHandleEvidence({
457
+ handle,
458
+ fixtureLog,
459
+ url,
460
+ since,
461
+ tag,
462
+ proofTag,
463
+ cookie,
464
+ settled,
465
+ probedRefusal,
466
+ }) {
467
+ if (!handle) return { probedRefusal, postTriggerRefusal: null, bios: null };
468
+ const bios = await continueItselfEvidence({
469
+ fixtureLog,
470
+ url,
471
+ since,
472
+ tag,
473
+ proofTag,
474
+ cookie,
475
+ handle,
476
+ });
477
+ if (bios) return { probedRefusal, postTriggerRefusal: null, bios };
478
+ if (settled == null || probedRefusal)
479
+ return { probedRefusal, postTriggerRefusal: null, bios: null };
480
+ const postTriggerRefusal = await probePostTriggerRefusal(handle);
481
+ return { probedRefusal: true, postTriggerRefusal, bios: null };
482
+ }
483
+
484
+ async function waitPauseOrBlocked({
485
+ client,
486
+ reader,
487
+ pageTarget,
488
+ pageSession,
489
+ homeUrl,
490
+ from,
491
+ url,
492
+ methods,
493
+ pauseMs,
494
+ triggerPromise,
495
+ blockedMarkers,
496
+ fixtureLog,
497
+ handle,
498
+ tag = null,
499
+ proofTag = null,
500
+ triggerSentAt = null,
501
+ cookie = null,
502
+ }) {
503
+ let settled = null;
504
+ let href = null;
505
+ let postTriggerRefusal = null;
506
+ let probedRefusal = false;
507
+ let fixtureHits = null;
508
+ let planted = null;
509
+ let jar = null;
510
+ const quietMs = Math.min(150, Math.max(50, Math.floor(pauseMs / 16)));
511
+ const since = triggerSentAt ?? Date.now();
512
+ const triggerDone = Promise.resolve(triggerPromise).then(
513
+ (value) => {
514
+ settled = value;
515
+ return value;
516
+ },
517
+ (error) => {
518
+ settled = { ok: false, error: { message: String(error?.message ?? error) } };
519
+ return settled;
520
+ }
521
+ );
522
+ const deadline = Date.now() + pauseMs;
523
+ const pack = (paused, early) => ({
524
+ paused,
525
+ settled,
526
+ href,
527
+ postTriggerRefusal,
528
+ early,
529
+ fixtureHits,
530
+ planted,
531
+ jar,
532
+ });
533
+ const finish = async (paused, early, opts = {}) => {
534
+ href = (await readTabHref({ reader, pageTarget })) ?? href;
535
+ if (!probedRefusal && handle && !paused && !opts.skipRefusalProbe) {
536
+ postTriggerRefusal = await probePostTriggerRefusal(handle);
537
+ probedRefusal = true;
538
+ }
539
+ if ((early || paused) && !opts.skipQuiet) await quietFixture(fixtureLog, quietMs);
540
+ return pack(paused, early);
541
+ };
542
+ while (Date.now() < deadline) {
543
+ const paused = pauseEvents(client.events, from, url, methods).at(-1) ?? null;
544
+ if (paused) return finish(paused, false);
545
+ if (settled != null && triggerRefusal(settled) === true) {
546
+ await Promise.race([triggerDone, pause(50)]);
547
+ return finish(null, true);
548
+ }
549
+ href = await readTabHref({ reader, pageTarget });
550
+ if (blockedMarkerHit(href, blockedMarkers)) {
551
+ await Promise.race([triggerDone, pause(50)]);
552
+ return finish(null, true);
553
+ }
554
+ if (readerNetworkBlocked(reader, handle?.readerSession, url, handle?.readerEventFrom ?? 0)) {
555
+ await Promise.race([triggerDone, pause(50)]);
556
+ return finish(null, true);
557
+ }
558
+ const polled = await pollHandleEvidence({
559
+ handle,
560
+ fixtureLog,
561
+ url,
562
+ since,
563
+ tag,
564
+ proofTag,
565
+ cookie,
566
+ settled,
567
+ probedRefusal,
568
+ });
569
+ probedRefusal = polled.probedRefusal;
570
+ if (polled.bios) {
571
+ fixtureHits = polled.bios.fixtureHits;
572
+ planted = polled.bios.planted;
573
+ jar = polled.bios.jar ?? null;
574
+ return finish(null, true, { skipRefusalProbe: true, skipQuiet: true });
575
+ }
576
+ if (polled.postTriggerRefusal) {
577
+ postTriggerRefusal = polled.postTriggerRefusal;
578
+ if (refused(postTriggerRefusal)) return finish(null, true);
579
+ }
580
+ if (settled != null && leftHome(href, homeUrl)) return finish(null, true);
581
+ await Promise.race([triggerDone.then(() => null), pause(25)]);
582
+ }
583
+ settled = settled ?? (await settleTrigger(triggerDone, Math.min(pauseMs, 500)));
584
+ return finish(null, false);
585
+ }
586
+
587
+ async function evidenceAfterTrigger({
588
+ handle,
589
+ cookie,
590
+ fixtureLog,
591
+ url,
592
+ tag,
593
+ proofTag,
594
+ startedAt,
595
+ hrefHint,
596
+ }) {
597
+ requireAttemptHandle(handle, 'evidenceAfterTrigger');
598
+ const readerHref =
599
+ hrefHint != null ? hrefHint : await tabHrefFromReader(handle.reader, handle.pageTarget);
600
+ const page = { href: readerHref, ready: readerHref != null };
601
+ const afterTriggerAt = Date.now();
602
+ if (afterTriggerAt < startedAt) {
603
+ return {
604
+ page,
605
+ fixtureHits: await fixtureHitsFor(fixtureLog, url, startedAt, tag, proofTag),
606
+ planted: 'incomplete',
607
+ afterTriggerAt,
608
+ };
609
+ }
610
+ const cached = handle.blockedEvidence;
611
+ const reusable =
612
+ cached &&
613
+ cached.afterTriggerAt >= startedAt &&
614
+ cached.cookieName === cookie?.name &&
615
+ cached.cookieDomain === cookie?.domain &&
616
+ cached.href === (page.href ?? hrefHint);
617
+ if (reusable) {
618
+ return {
619
+ page: { href: cached.href, ready: true },
620
+ fixtureHits: cached.fixtureHits,
621
+ planted: cached.planted,
622
+ jar: cached.jar ?? null,
623
+ afterTriggerAt: cached.afterTriggerAt,
624
+ };
625
+ }
626
+ const fixtureHits = await fixtureHitsFor(fixtureLog, url, startedAt, tag, proofTag);
627
+ const jar = await capped(readJarWithCanary(handle, cookie), 1500, 'readJar');
628
+ const planted = plantedOf(
629
+ jar?.error?.message?.includes('timeout') ? { incomplete: 'cookie jar unreadable' } : jar
630
+ );
631
+ handle.blockedEvidence = {
632
+ afterTriggerAt,
633
+ cookieName: cookie?.name,
634
+ cookieDomain: cookie?.domain,
635
+ href: page.href ?? hrefHint ?? null,
636
+ fixtureHits,
637
+ planted,
638
+ jar,
639
+ };
640
+ return { page, fixtureHits, planted, jar, afterTriggerAt };
641
+ }
642
+
643
+ function storageContextParams(browserContextId) {
644
+ return browserContextId ? { browserContextId } : {};
645
+ }
646
+
647
+ function contextKey(browserContextId) {
648
+ return browserContextId || null;
649
+ }
650
+
651
+ function jarContextIncomplete(handle) {
652
+ if (!handle?.browserContexts) return null;
653
+ if (handle.browserContextId == null || handle.browserContextId === '')
654
+ return { incomplete: 'unknown context' };
655
+ return null;
656
+ }
657
+
658
+ async function resolveTabContextId(reader, targetId, fallback = null) {
659
+ if (!targetId) return fallback ?? null;
660
+ const info = await outcome(reader.send('Target.getTargetInfo', { targetId }));
661
+ return info.result?.targetInfo?.browserContextId || fallback || null;
662
+ }
663
+
664
+ function canarySpec({ tag, homeUrl }) {
665
+ const host = hostOf(homeUrl);
666
+ const id = String(tag ?? '')
667
+ .replace(/[^a-zA-Z0-9]/g, '')
668
+ .slice(-16);
669
+ let origin = `http://${host}/`;
670
+ try {
671
+ origin = `${new URL(homeUrl).origin}/`;
672
+ } catch {
673
+ origin = `http://${host}/`;
674
+ }
675
+ return {
676
+ name: `cplantcanary${id || 'x'}`,
677
+ value: `canary-${tag}`,
678
+ domain: host,
679
+ path: '/',
680
+ url: origin,
681
+ };
682
+ }
683
+
684
+ function requireAttemptHandle(handle, where) {
685
+ if (handle == null || typeof handle !== 'object')
686
+ throw new Error(`cookie-plant.${where}: attempt handle required`);
687
+ if (!Object.prototype.hasOwnProperty.call(handle, 'browserContextId'))
688
+ throw new Error(`cookie-plant.${where}: handle.browserContextId required`);
689
+ if (!handle.reader) throw new Error(`cookie-plant.${where}: handle.reader required`);
690
+ return handle;
691
+ }
692
+
693
+ async function plantCanary(handle) {
694
+ requireAttemptHandle(handle, 'plantCanary');
695
+ const unknown = jarContextIncomplete(handle);
696
+ if (unknown) return unknown;
697
+ const canary = handle.canary;
698
+ if (!canary) throw new Error('cookie-plant.plantCanary: handle.canary required');
699
+ const path = canary.path ?? '/';
700
+ await outcome(
701
+ handle.reader.send('Storage.setCookies', {
702
+ ...storageContextParams(handle.browserContextId),
703
+ cookies: [
704
+ canary.url
705
+ ? { name: canary.name, value: canary.value, url: canary.url, path }
706
+ : { name: canary.name, value: canary.value, domain: canary.domain, path },
707
+ ],
708
+ })
709
+ );
710
+ }
711
+
712
+ async function clearCookie(handle, { name, url, domain }) {
713
+ requireAttemptHandle(handle, 'clearCookie');
714
+ const unknown = jarContextIncomplete(handle);
715
+ if (unknown) return unknown;
716
+ const { reader, readerSession: sessionId, browserContextId } = handle;
717
+ await outcome(
718
+ reader.send(
719
+ 'Network.deleteCookies',
720
+ {
721
+ name,
722
+ ...(url ? { url } : {}),
723
+ ...(domain ? { domain } : {}),
724
+ },
725
+ sessionId
726
+ )
727
+ );
728
+ await outcome(
729
+ reader.send('Storage.getCookies', storageContextParams(browserContextId)).then(async (all) => {
730
+ const cookies = (all?.cookies ?? []).filter(
731
+ (cookie) =>
732
+ cookie.name === name &&
733
+ (!domain ||
734
+ cookie.domain.replace(/^\./, '') === domain.replace(/^\./, '') ||
735
+ cookie.domain === domain)
736
+ );
737
+ if (!cookies.length) return;
738
+ await reader.send('Storage.setCookies', {
739
+ ...storageContextParams(browserContextId),
740
+ cookies: (all.cookies ?? []).filter((cookie) => !cookies.includes(cookie)),
741
+ });
742
+ })
743
+ );
744
+ }
745
+
746
+ function jarCookieMatch(cookie, { name, domain, value, path }) {
747
+ if (cookie.name !== name) return false;
748
+ const wantDomain = String(domain ?? '')
749
+ .replace(/^\./, '')
750
+ .toLowerCase();
751
+ const got = String(cookie.domain ?? '')
752
+ .replace(/^\./, '')
753
+ .toLowerCase();
754
+ if (got !== wantDomain && !wantDomain.endsWith(`.${got}`) && !got.endsWith(`.${wantDomain}`))
755
+ return false;
756
+ if ((cookie.path ?? '/') !== (path ?? '/')) return false;
757
+ if (value !== undefined && cookie.value !== value) return false;
758
+ return true;
759
+ }
760
+
761
+ function jarUrlHints(cookie, canary = null) {
762
+ const urls = [];
763
+ const pushHost = (host) => {
764
+ const name = String(host ?? '')
765
+ .replace(/^\./, '')
766
+ .toLowerCase();
767
+ if (!name) return;
768
+ urls.push(`https://${name}/`, `http://${name}/`);
769
+ };
770
+ if (cookie?.url) {
771
+ try {
772
+ urls.push(new URL(cookie.url).origin + '/');
773
+ } catch {
774
+ pushHost(cookie.domain);
775
+ }
776
+ } else pushHost(cookie?.domain);
777
+ if (canary?.url) {
778
+ try {
779
+ urls.push(new URL(canary.url).origin + '/');
780
+ } catch {
781
+ pushHost(canary.domain);
782
+ }
783
+ } else pushHost(canary?.domain);
784
+ return [...new Set(urls.filter(Boolean))];
785
+ }
786
+
787
+ async function readJarView(handle, urlHints = []) {
788
+ requireAttemptHandle(handle, 'readJarView');
789
+ const unknown = jarContextIncomplete(handle);
790
+ if (unknown) return unknown;
791
+ const { reader, readerSession: sessionId, browserContextId } = handle;
792
+ const storage = await outcome(
793
+ reader.send('Storage.getCookies', storageContextParams(browserContextId))
794
+ );
795
+ if (storage.ok && Array.isArray(storage.result?.cookies))
796
+ return { via: 'Storage.getCookies', cookies: storage.result.cookies };
797
+ const all = await outcome(reader.send('Network.getAllCookies', {}, sessionId));
798
+ if (all.ok && Array.isArray(all.result?.cookies))
799
+ return { via: 'Network.getAllCookies', cookies: all.result.cookies };
800
+ const urls = urlHints.length ? urlHints : ['https://example.invalid/', 'http://example.invalid/'];
801
+ const byUrl = await outcome(reader.send('Network.getCookies', { urls }, sessionId));
802
+ if (byUrl.ok && Array.isArray(byUrl.result?.cookies))
803
+ return { via: 'Network.getCookies', cookies: byUrl.result.cookies };
804
+ return { incomplete: 'cookie jar unreadable' };
805
+ }
806
+
807
+ async function readJar(handle, { name, domain, value, path }, { urlHints = [] } = {}) {
808
+ requireAttemptHandle(handle, 'readJar');
809
+ const view = await readJarView(handle, urlHints);
810
+ if (view.incomplete) return view;
811
+ const hit = view.cookies.find((cookie) => jarCookieMatch(cookie, { name, domain, value, path }));
812
+ if (hit) return { via: view.via, cookie: hit, cookies: view.cookies };
813
+ return { via: view.via, missing: true, cookies: view.cookies };
814
+ }
815
+
816
+ function jarAuditFields(handle, jar) {
817
+ if (!jar) return { jarRead: false };
818
+ const canaryName = handle?.canary?.name ?? jar.canaryName ?? null;
819
+ const browserContextId =
820
+ handle && Object.prototype.hasOwnProperty.call(handle, 'browserContextId')
821
+ ? (handle.browserContextId ?? null)
822
+ : (jar.browserContextId ?? null);
823
+ const canaryVisible =
824
+ jar.canaryOk === true
825
+ ? true
826
+ : jar.canaryMissing === true || jar.canaryVisible === false
827
+ ? false
828
+ : Boolean(jar.canaryVisible);
829
+ return {
830
+ jarRead: true,
831
+ canaryName,
832
+ canaryVisible,
833
+ via: jar.via ?? null,
834
+ browserContextId,
835
+ };
836
+ }
837
+
838
+ function evidenceFormOf({ answered, refused, planted }) {
839
+ if (answered !== true) return null;
840
+ if (refused === true && planted === false) return 'commandRefused';
841
+ if (refused === false && planted === true) return 'allowedPlant';
842
+ if (refused === false && planted === false) return 'answeredNotPlanted';
843
+ return null;
844
+ }
845
+
846
+ async function readJarWithCanary(handle, cookie) {
847
+ requireAttemptHandle(handle, 'readJarWithCanary');
848
+ const canary = handle.canary;
849
+ if (!canary) throw new Error('cookie-plant.readJarWithCanary: handle.canary required');
850
+ const urlHints = jarUrlHints(cookie, canary);
851
+ const jar = await readJar(handle, cookie, { urlHints });
852
+ const audit = {
853
+ canaryName: canary.name,
854
+ browserContextId: handle.browserContextId ?? null,
855
+ };
856
+ if (jar?.incomplete) return { ...jar, ...audit, canaryVisible: false };
857
+ const canaryHit = (jar.cookies ?? []).some((entry) =>
858
+ jarCookieMatch(entry, {
859
+ name: canary.name,
860
+ domain: canary.domain,
861
+ value: canary.value,
862
+ path: canary.path ?? '/',
863
+ })
864
+ );
865
+ if (!canaryHit)
866
+ return {
867
+ incomplete: 'jar view canary absent',
868
+ via: jar?.via,
869
+ canaryMissing: true,
870
+ canaryVisible: false,
871
+ ...audit,
872
+ };
873
+ return { ...jar, canaryOk: true, canaryVisible: true, ...audit };
874
+ }
875
+
876
+ function plantedOf(jar) {
877
+ if (!jar || jar.incomplete) return 'incomplete';
878
+ if (jar.missing) return false;
879
+ return true;
880
+ }
881
+
882
+ async function triggerFetch(client, sessionId, url) {
883
+ return outcome(
884
+ client.send(
885
+ 'Runtime.evaluate',
886
+ {
887
+ expression: `fetch(${JSON.stringify(url)},{credentials:'include'}).then(r=>r.status+' '+r.url,e=>'error:'+e)`,
888
+ awaitPromise: true,
889
+ returnByValue: true,
890
+ },
891
+ sessionId
892
+ )
893
+ );
894
+ }
895
+
896
+ async function triggerNavigate(client, sessionId, url) {
897
+ return outcome(
898
+ client.send(
899
+ 'Runtime.evaluate',
900
+ {
901
+ expression: `location.assign(${JSON.stringify(url)})`,
902
+ returnByValue: true,
903
+ },
904
+ sessionId
905
+ )
906
+ );
907
+ }
908
+
909
+ async function capped(promise, ms, label = 'cdp') {
910
+ let timer;
911
+ try {
912
+ return await Promise.race([
913
+ promise,
914
+ new Promise((resolve) => {
915
+ timer = setTimeout(
916
+ () => resolve({ ok: false, error: { message: `${label} timeout` } }),
917
+ ms
918
+ );
919
+ }),
920
+ ]);
921
+ } finally {
922
+ clearTimeout(timer);
923
+ }
924
+ }
925
+
926
+ async function settleTrigger(promise, budget) {
927
+ return capped(
928
+ promise.then(
929
+ (value) => value,
930
+ (error) => ({ ok: false, error: { message: String(error?.message ?? error) } })
931
+ ),
932
+ budget,
933
+ 'trigger settle'
934
+ );
935
+ }
936
+
937
+ async function releasePause(client, paused) {
938
+ if (!paused) return { ok: true };
939
+ if (paused.method === 'Fetch.requestPaused' && paused.params?.requestId) {
940
+ return capped(
941
+ outcome(
942
+ client.send(
943
+ 'Fetch.failRequest',
944
+ { requestId: paused.params.requestId, errorReason: 'Aborted' },
945
+ paused.sessionId
946
+ )
947
+ ),
948
+ 800,
949
+ 'releasePause'
950
+ );
951
+ }
952
+ if (paused.method === 'Network.requestIntercepted' && paused.params?.interceptionId) {
953
+ return capped(
954
+ outcome(
955
+ client.send(
956
+ 'Network.continueInterceptedRequest',
957
+ { interceptionId: paused.params.interceptionId, errorReason: 'Aborted' },
958
+ paused.sessionId
959
+ )
960
+ ),
961
+ 800,
962
+ 'releasePause'
963
+ );
964
+ }
965
+ return { ok: true };
966
+ }
967
+
968
+ async function drainPauses(client, from = 0) {
969
+ const seen = new Set();
970
+ for (const event of client.events.slice(from)) {
971
+ if (event.method === 'Fetch.requestPaused' && event.params?.requestId) {
972
+ const key = `fetch:${event.params.requestId}`;
973
+ if (seen.has(key)) continue;
974
+ seen.add(key);
975
+ await releasePause(client, event);
976
+ }
977
+ if (event.method === 'Network.requestIntercepted' && event.params?.interceptionId) {
978
+ const key = `legacy:${event.params.interceptionId}`;
979
+ if (seen.has(key)) continue;
980
+ seen.add(key);
981
+ await releasePause(client, event);
982
+ }
983
+ }
984
+ }
985
+
986
+ async function withPathBudget(promise, ms, label) {
987
+ let timer;
988
+ try {
989
+ return await Promise.race([
990
+ promise,
991
+ new Promise((_, reject) => {
992
+ timer = setTimeout(() => reject(new Error(`path timeout: ${label}`)), ms);
993
+ }),
994
+ ]);
995
+ } finally {
996
+ clearTimeout(timer);
997
+ }
998
+ }
999
+
1000
+ function pathCeiling(budget) {
1001
+ const ms = Number(budget);
1002
+ if (!Number.isFinite(ms) || ms <= 0) return 400;
1003
+ return Math.min(Math.max(ms * 2, 200), 6000);
1004
+ }
1005
+
1006
+ function cleanupCeiling(budget = 5000) {
1007
+ const ms = Number(budget);
1008
+ if (!Number.isFinite(ms) || ms <= 0) return 200;
1009
+ return Math.min(Math.max(ms, 200), 2000);
1010
+ }
1011
+
1012
+ async function enableFetch(client, pageSession) {
1013
+ return capped(
1014
+ outcome(
1015
+ client.send(
1016
+ 'Fetch.enable',
1017
+ {
1018
+ patterns: [
1019
+ { urlPattern: '*', requestStage: 'Request' },
1020
+ { urlPattern: '*', requestStage: 'Response' },
1021
+ ],
1022
+ },
1023
+ pageSession
1024
+ )
1025
+ ),
1026
+ 800,
1027
+ 'enableFetch'
1028
+ );
1029
+ }
1030
+
1031
+ async function ensureInterception(client, pageSession, transport, fetchEnable = null) {
1032
+ if (!pageSession || !transport?.kind) return { ok: true };
1033
+ if (transport.fetch) {
1034
+ if (fetchEnable && (fetchEnable.ok === true || refused(fetchEnable))) return fetchEnable;
1035
+ if (fetchEnable && /timeout/i.test(String(fetchEnable.error?.message ?? '')))
1036
+ return fetchEnable;
1037
+ return enableFetch(client, pageSession);
1038
+ }
1039
+ if (transport.legacy) return capped(enableLegacy(client, pageSession), 800, 'enableLegacy');
1040
+ return { ok: true };
1041
+ }
1042
+
1043
+ async function reattachClient(handle) {
1044
+ const { client, reader, pageTarget, homeUrl, transport, internalSessions, notes } = handle;
1045
+ if (!pageTarget) return { ok: false, error: { message: 'missing page target for reattach' } };
1046
+ if (reader && handle.readerSession && homeUrl) {
1047
+ await capped(
1048
+ outcome(reader.send('Page.navigate', { url: homeUrl }, handle.readerSession)),
1049
+ 800,
1050
+ 'recover-navigate'
1051
+ );
1052
+ await pageReady(reader, handle.readerSession, 1000);
1053
+ }
1054
+ if (handle.pageSession)
1055
+ await capped(
1056
+ outcome(client.send('Target.detachFromTarget', { sessionId: handle.pageSession })),
1057
+ 800,
1058
+ 'recover-detach'
1059
+ );
1060
+ const attached = await attachClientPage(client, pageTarget, internalSessions);
1061
+ if (!attached.pageSession)
1062
+ return { ok: false, error: { message: attached.incomplete ?? 'reattach failed' } };
1063
+ handle.pageSession = attached.pageSession;
1064
+ let enabled = { ok: true };
1065
+ if (transport?.fetch) enabled = await enableFetch(client, handle.pageSession);
1066
+ else if (transport?.legacy)
1067
+ enabled = await capped(enableLegacy(client, handle.pageSession), 800, 'recover-legacy');
1068
+ note(notes, 'cookie-plant.recover', {
1069
+ pageSession: handle.pageSession,
1070
+ enabled: enabled.ok,
1071
+ cut: sessionCut(enabled),
1072
+ });
1073
+ if (sessionCut(enabled)) return enabled;
1074
+ return enabled.ok ? { ok: true, pageSession: handle.pageSession } : enabled;
1075
+ }
1076
+
1077
+ async function ensureLiveSession(handle) {
1078
+ if (!handle?.pageSession) return { ok: false, error: { message: 'missing page session' } };
1079
+ const probe = await capped(
1080
+ outcome(
1081
+ handle.client.send(
1082
+ 'Runtime.evaluate',
1083
+ { expression: '1', returnByValue: true },
1084
+ handle.pageSession
1085
+ )
1086
+ ),
1087
+ 800,
1088
+ 'session-probe'
1089
+ );
1090
+ if (probe.ok) return { ok: true, pageSession: handle.pageSession };
1091
+ return reattachClient(handle);
1092
+ }
1093
+
1094
+ async function ensureInterceptionLive(handle) {
1095
+ const live = await ensureLiveSession(handle);
1096
+ if (!live.ok) return live;
1097
+ const ensure = await ensureInterception(
1098
+ handle.client,
1099
+ handle.pageSession,
1100
+ handle.transport,
1101
+ handle.fetchEnable
1102
+ );
1103
+ if (ensure.ok) return ensure;
1104
+ if (
1105
+ !sessionCut(ensure) &&
1106
+ !/session with given id not found/i.test(String(ensure.error?.message))
1107
+ )
1108
+ return ensure;
1109
+ const recovered = await reattachClient(handle);
1110
+ if (!recovered.ok) return ensure;
1111
+ return ensureInterception(
1112
+ handle.client,
1113
+ handle.pageSession,
1114
+ handle.transport,
1115
+ handle.fetchEnable
1116
+ );
1117
+ }
1118
+
1119
+ async function cleanupPath({ handle, paused, from, triggerPromise, budget }) {
1120
+ const { client } = handle;
1121
+ await releasePause(client, paused);
1122
+ await drainPauses(client, from);
1123
+ await settleTrigger(triggerPromise, Math.min(budget, 500));
1124
+ }
1125
+
1126
+ function attemptRecord(out, planted) {
1127
+ if (!answered(out))
1128
+ return {
1129
+ answered: 'incomplete',
1130
+ refused: 'incomplete',
1131
+ planted: 'incomplete',
1132
+ };
1133
+ const plantedOut = planted === true ? true : planted === false ? false : 'incomplete';
1134
+ return {
1135
+ answered: true,
1136
+ refused: refused(out),
1137
+ planted: plantedOut,
1138
+ };
1139
+ }
1140
+
1141
+ function incompletePlantedAttempt(notes, label, evidence) {
1142
+ note(notes, `cookie-plant.${label}`, {
1143
+ ...evidence,
1144
+ incomplete: evidence?.incomplete ?? 'protected plant evidence incomplete',
1145
+ });
1146
+ return {
1147
+ answered: 'incomplete',
1148
+ refused: 'incomplete',
1149
+ planted: 'incomplete',
1150
+ };
1151
+ }
1152
+
1153
+ async function fulfillPaused(client, paused, params) {
1154
+ const requestId = paused.params.requestId;
1155
+ const interceptionId = paused.params.interceptionId;
1156
+ if (paused.method === 'Fetch.requestPaused') {
1157
+ return outcome(
1158
+ client.send(
1159
+ 'Fetch.fulfillRequest',
1160
+ { requestId, responseCode: 200, ...params },
1161
+ paused.sessionId
1162
+ )
1163
+ );
1164
+ }
1165
+ if (paused.method === 'Network.requestIntercepted') {
1166
+ const raw =
1167
+ params.rawResponse ??
1168
+ rawHttpResponse({
1169
+ code: params.responseCode ?? 200,
1170
+ phrase: 'OK',
1171
+ headers: Array.isArray(params.responseHeaders)
1172
+ ? params.responseHeaders
1173
+ : Object.entries(params.responseHeaders ?? {}).map(([name, value]) => ({ name, value })),
1174
+ body: params.body ? fromB64(params.body) : 'planted',
1175
+ });
1176
+ return outcome(
1177
+ client.send(
1178
+ 'Network.continueInterceptedRequest',
1179
+ { interceptionId, rawResponse: raw },
1180
+ paused.sessionId
1181
+ )
1182
+ );
1183
+ }
1184
+ return { ok: false, error: { message: `unsupported pause ${paused.method}` } };
1185
+ }
1186
+
1187
+ async function pageReady(client, pageSession, ms = 4000) {
1188
+ return waitFor(
1189
+ async () => {
1190
+ const read = await outcome(
1191
+ client.send(
1192
+ 'Runtime.evaluate',
1193
+ { expression: 'document.readyState', returnByValue: true },
1194
+ pageSession
1195
+ )
1196
+ );
1197
+ return read.ok && ['interactive', 'complete'].includes(read.result?.result?.value);
1198
+ },
1199
+ ms,
1200
+ 25,
1201
+ true
1202
+ );
1203
+ }
1204
+
1205
+ async function restorePage(client, pageSession, homeUrl, transport, reader, readerSession) {
1206
+ if (!homeUrl) return { ok: true };
1207
+ const wasFetch = Boolean(transport?.fetch);
1208
+ const wasLegacy = Boolean(transport?.legacy);
1209
+ try {
1210
+ if (pageSession)
1211
+ await capped(
1212
+ disableInterception(client, pageSession, { fetch: true, legacy: true }),
1213
+ 800,
1214
+ 'disable'
1215
+ );
1216
+ if (reader && readerSession)
1217
+ await capped(
1218
+ disableInterception(reader, readerSession, { fetch: true, legacy: true }),
1219
+ 800,
1220
+ 'disable'
1221
+ );
1222
+ const navClient = reader ?? client;
1223
+ const navSession = readerSession ?? pageSession;
1224
+ if (!navSession) return { ok: true };
1225
+ await capped(
1226
+ outcome(navClient.send('Page.navigate', { url: homeUrl }, navSession)),
1227
+ 800,
1228
+ 'navigate'
1229
+ );
1230
+ await pageReady(navClient, navSession, 1000);
1231
+ } finally {
1232
+ if (pageSession && wasFetch) await enableFetch(client, pageSession);
1233
+ else if (pageSession && wasLegacy)
1234
+ await capped(enableLegacy(client, pageSession), 800, 'reenable');
1235
+ }
1236
+ return { ok: true };
1237
+ }
1238
+
1239
+ async function finishPlant({ out, cookie, notes, label, handle }) {
1240
+ requireAttemptHandle(handle, 'finishPlant');
1241
+ const unknown = jarContextIncomplete(handle);
1242
+ if (unknown) {
1243
+ note(notes, `cookie-plant.${label}`, {
1244
+ ...unknown,
1245
+ jarRead: false,
1246
+ ...timingOf(handle),
1247
+ });
1248
+ return attemptRecord(out, 'incomplete');
1249
+ }
1250
+ const jar = await capped(readJarWithCanary(handle, cookie), 1500, 'readJar');
1251
+ const planted = plantedOf(
1252
+ jar?.error?.message?.includes('timeout') ? { incomplete: 'cookie jar unreadable' } : jar
1253
+ );
1254
+ const evidence = {
1255
+ answered: answered(out),
1256
+ refused: refused(out),
1257
+ planted,
1258
+ jarIncomplete: jar?.incomplete,
1259
+ ...jarAuditFields(handle, jar),
1260
+ ...timingOf(handle),
1261
+ };
1262
+ if (handle.credential) {
1263
+ const form = evidenceFormOf({
1264
+ answered: evidence.answered,
1265
+ refused: evidence.refused,
1266
+ planted,
1267
+ });
1268
+ if (form) evidence.evidenceForm = form;
1269
+ }
1270
+ note(notes, `cookie-plant.${label}`, evidence);
1271
+ return attemptRecord(out, planted);
1272
+ }
1273
+
1274
+ function blockedMarkerHit(href, markers) {
1275
+ if (typeof href !== 'string' || !href) return false;
1276
+ const list = Array.isArray(markers) ? markers : [];
1277
+ return list.some((marker) => {
1278
+ const m = String(marker ?? '');
1279
+ return m && (href === m || href.startsWith(m));
1280
+ });
1281
+ }
1282
+
1283
+ function triggerText(outcome) {
1284
+ if (!outcome || typeof outcome !== 'object') return null;
1285
+ if (outcome.unresolved === true) return null;
1286
+ const value = outcome.result?.result?.value ?? outcome.result?.value;
1287
+ if (typeof value === 'string' && value) return value;
1288
+ if (outcome.ok === false && outcome.error)
1289
+ return String(outcome.error?.message ?? outcome.error ?? '');
1290
+ return null;
1291
+ }
1292
+
1293
+ function triggerRefusal(outcome) {
1294
+ if (outcome == null) return 'incomplete';
1295
+ if (outcome === 'incomplete') return 'incomplete';
1296
+ if (typeof outcome === 'object' && outcome.unresolved === true) return 'incomplete';
1297
+ const text = triggerText(outcome);
1298
+ if (text == null) return false;
1299
+ return /slicc:\s*refused:|net::ERR_BLOCKED_BY_CLIENT|ERR_BLOCKED_BY_CLIENT|BlockedByClient|error:BlockedByClient/i.test(
1300
+ text
1301
+ );
1302
+ }
1303
+
1304
+ function scoreRawOrDoorBranch({
1305
+ evidence,
1306
+ notes,
1307
+ label,
1308
+ planted,
1309
+ rawDoor,
1310
+ doorAbsent,
1311
+ plantSurfaceRefused,
1312
+ handle = null,
1313
+ }) {
1314
+ if (
1315
+ rawDoor &&
1316
+ handle &&
1317
+ Object.hasOwn(rawDoor, 'browserContextId') &&
1318
+ contextKey(rawDoor.browserContextId) !== contextKey(handle.browserContextId)
1319
+ ) {
1320
+ note(notes, `cookie-plant.${label}`, {
1321
+ ...evidence,
1322
+ incomplete: 'raw/guarded browserContext mismatch',
1323
+ rawBrowserContextId: rawDoor.browserContextId ?? null,
1324
+ browserContextId: handle.browserContextId ?? null,
1325
+ });
1326
+ return {
1327
+ answered: 'incomplete',
1328
+ refused: 'incomplete',
1329
+ planted: planted === true ? true : 'incomplete',
1330
+ };
1331
+ }
1332
+ if (rawDoor && !doorAbsentOf(rawDoor) && (rawDoor.incomplete || rawDoor.observed !== true)) {
1333
+ note(notes, `cookie-plant.${label}`, {
1334
+ ...evidence,
1335
+ incomplete: 'raw leg incomplete',
1336
+ });
1337
+ return {
1338
+ answered: 'incomplete',
1339
+ refused: 'incomplete',
1340
+ planted: planted === true ? true : 'incomplete',
1341
+ };
1342
+ }
1343
+ if (plantSurfaceRefused) {
1344
+ if (planted === true) {
1345
+ note(notes, `cookie-plant.${label}`, {
1346
+ ...evidence,
1347
+ answered: true,
1348
+ refused: true,
1349
+ note: 'Fetch.enable refused: interception plant surface refused',
1350
+ });
1351
+ return { answered: true, refused: true, planted: true };
1352
+ }
1353
+ if (planted === false) {
1354
+ note(notes, `cookie-plant.${label}`, {
1355
+ ...evidence,
1356
+ answered: true,
1357
+ refused: true,
1358
+ note: 'Fetch.enable refused: interception plant surface refused',
1359
+ });
1360
+ return { answered: true, refused: true, planted: false };
1361
+ }
1362
+ return incompletePlantedAttempt(notes, label, {
1363
+ ...evidence,
1364
+ note: 'Fetch.enable refused: interception plant surface refused',
1365
+ });
1366
+ }
1367
+ if (!doorAbsent) return null;
1368
+ note(notes, `cookie-plant.${label}`, {
1369
+ ...evidence,
1370
+ note: 'door not present on this browser',
1371
+ });
1372
+ if (planted === true) return { answered: true, refused: false, planted: true };
1373
+ if (planted === false) return { answered: true, refused: false, planted: false };
1374
+ return incompletePlantedAttempt(notes, label, evidence);
1375
+ }
1376
+
1377
+ function protectedPlantSignals({
1378
+ pauseCount,
1379
+ fixtureHits,
1380
+ planted,
1381
+ pageHref,
1382
+ triggerOutcome,
1383
+ blockedMarkers,
1384
+ postTriggerRefusal,
1385
+ triggerIssued,
1386
+ fetchEnableOk,
1387
+ doorAbsent,
1388
+ rawDoor,
1389
+ readerBlocked,
1390
+ }) {
1391
+ const href = pageHref == null ? null : String(pageHref);
1392
+ const onMarker = blockedMarkerHit(href, blockedMarkers);
1393
+ const refusal = triggerRefusal(triggerOutcome);
1394
+ const sessionBlocked = Boolean(triggerIssued && postTriggerRefusal === true);
1395
+ const blockSeen = Boolean(onMarker === true || readerBlocked === true);
1396
+ const issuedAndBlocked =
1397
+ refusal === 'incomplete'
1398
+ ? 'incomplete'
1399
+ : Boolean(blockSeen || refusal === true || sessionBlocked);
1400
+ const loadBlocked =
1401
+ fixtureHits === 'incomplete' || issuedAndBlocked === 'incomplete'
1402
+ ? 'incomplete'
1403
+ : issuedAndBlocked === true && fixtureHits === 0;
1404
+ const rawPremise =
1405
+ Boolean(rawDoor) &&
1406
+ !doorAbsent &&
1407
+ rawDoor.observed === true &&
1408
+ rawDoor.answered === true &&
1409
+ rawDoor.planted === true;
1410
+ const shapeD =
1411
+ Boolean(triggerIssued) &&
1412
+ pauseCount === 0 &&
1413
+ fixtureHits === 0 &&
1414
+ planted === false &&
1415
+ rawPremise &&
1416
+ blockSeen &&
1417
+ fetchEnableOk === true;
1418
+ return {
1419
+ href,
1420
+ onMarker,
1421
+ refusal,
1422
+ sessionBlocked,
1423
+ blockSeen,
1424
+ issuedAndBlocked,
1425
+ loadBlocked,
1426
+ shapeD,
1427
+ };
1428
+ }
1429
+
1430
+ function scoreProtectedPlant({
1431
+ pauseCount,
1432
+ fixtureHits,
1433
+ planted,
1434
+ pageHref,
1435
+ notes,
1436
+ label,
1437
+ triggerOutcome,
1438
+ blockedMarkers,
1439
+ postTriggerRefusal = false,
1440
+ triggerIssued = false,
1441
+ handle,
1442
+ fetchEnableOk = null,
1443
+ doorAbsent = false,
1444
+ rawDoor = null,
1445
+ plantSurfaceRefused = false,
1446
+ readerBlocked = false,
1447
+ jar = null,
1448
+ }) {
1449
+ const signals = protectedPlantSignals({
1450
+ pauseCount,
1451
+ fixtureHits,
1452
+ planted,
1453
+ pageHref,
1454
+ triggerOutcome,
1455
+ blockedMarkers,
1456
+ postTriggerRefusal,
1457
+ triggerIssued,
1458
+ fetchEnableOk,
1459
+ doorAbsent,
1460
+ rawDoor,
1461
+ readerBlocked,
1462
+ });
1463
+ const {
1464
+ href,
1465
+ onMarker,
1466
+ refusal,
1467
+ sessionBlocked,
1468
+ blockSeen,
1469
+ issuedAndBlocked,
1470
+ loadBlocked,
1471
+ shapeD,
1472
+ } = signals;
1473
+ const evidence = {
1474
+ pauseCount,
1475
+ fixtureHits,
1476
+ planted,
1477
+ pageHref: href,
1478
+ onMarker,
1479
+ readerBlocked: Boolean(readerBlocked),
1480
+ triggerRefused: refusal,
1481
+ postTriggerRefusal: sessionBlocked,
1482
+ triggerIssued: Boolean(triggerIssued),
1483
+ issuedAndBlocked,
1484
+ loadBlocked,
1485
+ shapeD,
1486
+ fetchEnableOk,
1487
+ doorAbsent: Boolean(doorAbsent),
1488
+ plantSurfaceRefused: Boolean(plantSurfaceRefused),
1489
+ ...(rawDoor
1490
+ ? {
1491
+ rawAnswered: rawDoor.answered,
1492
+ rawPlanted: rawDoor.planted,
1493
+ rawTimedOut: rawDoor.timedOut,
1494
+ rawObserved: rawDoor.observed === true,
1495
+ rawIncomplete: Boolean(rawDoor.incomplete),
1496
+ }
1497
+ : {}),
1498
+ ...jarAuditFields(handle, jar),
1499
+ ...timingOf(handle),
1500
+ };
1501
+ const early = scoreRawOrDoorBranch({
1502
+ evidence,
1503
+ notes,
1504
+ label,
1505
+ planted,
1506
+ rawDoor,
1507
+ doorAbsent,
1508
+ plantSurfaceRefused,
1509
+ handle,
1510
+ });
1511
+ if (early) return early;
1512
+ if (planted === true) {
1513
+ const refused = pauseCount > 0 || sessionBlocked || blockSeen;
1514
+ note(notes, `cookie-plant.${label}`, { ...evidence, answered: true, refused });
1515
+ return { answered: true, refused, planted: true };
1516
+ }
1517
+ if (
1518
+ (planted !== true && planted !== false) ||
1519
+ pauseCount === 'incomplete' ||
1520
+ fixtureHits === 'incomplete' ||
1521
+ loadBlocked === 'incomplete' ||
1522
+ issuedAndBlocked === 'incomplete'
1523
+ ) {
1524
+ return incompletePlantedAttempt(notes, label, evidence);
1525
+ }
1526
+ if (shapeD) {
1527
+ note(notes, `cookie-plant.${label}`, {
1528
+ ...evidence,
1529
+ answered: true,
1530
+ refused: true,
1531
+ note: 'guard blocks the request itself',
1532
+ });
1533
+ return { answered: true, refused: true, planted: false };
1534
+ }
1535
+ if (pauseCount === 0 && loadBlocked === true && planted === false) {
1536
+ if (fetchEnableOk === false) {
1537
+ return incompletePlantedAttempt(notes, label, {
1538
+ ...evidence,
1539
+ incomplete: 'Fetch.enable unanswered for bios-shape',
1540
+ });
1541
+ }
1542
+ note(notes, `cookie-plant.${label}`, { ...evidence, answered: true, refused: true });
1543
+ return { answered: true, refused: true, planted: false };
1544
+ }
1545
+ if (
1546
+ pauseCount === 0 &&
1547
+ typeof fixtureHits === 'number' &&
1548
+ fixtureHits >= 1 &&
1549
+ planted === false
1550
+ ) {
1551
+ if (fetchEnableOk !== true) {
1552
+ return incompletePlantedAttempt(notes, label, {
1553
+ ...evidence,
1554
+ incomplete: 'Fetch.enable unanswered for continue-itself',
1555
+ });
1556
+ }
1557
+ note(notes, `cookie-plant.${label}`, {
1558
+ ...evidence,
1559
+ answered: true,
1560
+ refused: true,
1561
+ note: 'continue-itself: guard continued the protected request',
1562
+ });
1563
+ return { answered: true, refused: true, planted: false };
1564
+ }
1565
+ return incompletePlantedAttempt(notes, label, evidence);
1566
+ }
1567
+
1568
+ async function fixtureHitsFor(fixtureLog, url, since, tag, proofTag) {
1569
+ if (typeof fixtureLog !== 'function') return 'incomplete';
1570
+ let entries;
1571
+ try {
1572
+ entries = await fixtureLog();
1573
+ } catch {
1574
+ return 'incomplete';
1575
+ }
1576
+ if (!Array.isArray(entries)) return 'incomplete';
1577
+ if (entries.length === 0) return 'incomplete';
1578
+ const proof = proofTag ? String(proofTag) : '';
1579
+ if (proof) {
1580
+ const seen = entries.some((entry) => String(entry?.url ?? '').includes(proof));
1581
+ if (!seen) return 'incomplete';
1582
+ }
1583
+ const afterSince = entries.filter((entry) => Number(entry?.time ?? 0) >= since);
1584
+ const needle = tag ? String(tag) : '';
1585
+ const matched = afterSince.filter((entry) => {
1586
+ const hit = String(entry?.url ?? '');
1587
+ if (!(hit === url || hit.startsWith(url) || (url && hit.startsWith(String(url).split('?')[0]))))
1588
+ return false;
1589
+ if (!needle) return true;
1590
+ return hit.includes(needle);
1591
+ });
1592
+ return matched.length;
1593
+ }
1594
+
1595
+ async function recordSessionCut({ handle, cookie, notes, label, out }) {
1596
+ requireAttemptHandle(handle, 'recordSessionCut');
1597
+ return finishPlant({
1598
+ handle,
1599
+ out: out ?? {
1600
+ ok: false,
1601
+ error: { message: 'slicc: refused: session cut on protected execution context' },
1602
+ },
1603
+ cookie,
1604
+ notes,
1605
+ label,
1606
+ });
1607
+ }
1608
+
1609
+ async function probePostTriggerRefusal(handle) {
1610
+ const { client, pageTarget, pageSession, internalSessions } = handle;
1611
+ if (pageSession) {
1612
+ const enabled = await capped(
1613
+ outcome(client.send('Page.enable', {}, pageSession)),
1614
+ 800,
1615
+ 'post-Page.enable'
1616
+ );
1617
+ if (refused(enabled)) return enabled;
1618
+ const fetchEnabled = await capped(
1619
+ outcome(
1620
+ client.send(
1621
+ 'Fetch.enable',
1622
+ {
1623
+ patterns: [
1624
+ { urlPattern: '*', requestStage: 'Request' },
1625
+ { urlPattern: '*', requestStage: 'Response' },
1626
+ ],
1627
+ },
1628
+ pageSession
1629
+ )
1630
+ ),
1631
+ 800,
1632
+ 'post-Fetch.enable'
1633
+ );
1634
+ if (refused(fetchEnabled)) return fetchEnabled;
1635
+ }
1636
+ if (!pageTarget) return null;
1637
+ const attached = await capped(
1638
+ outcome(client.send('Target.attachToTarget', { targetId: pageTarget, flatten: true })),
1639
+ 800,
1640
+ 'post-attach'
1641
+ );
1642
+ if (refused(attached)) return attached;
1643
+ const sessionId = attached.result?.sessionId;
1644
+ if (!sessionId) return null;
1645
+ internalSessions?.add(sessionId);
1646
+ const enabled = await capped(
1647
+ outcome(client.send('Page.enable', {}, sessionId)),
1648
+ 800,
1649
+ 'post-attach-Page.enable'
1650
+ );
1651
+ return refused(enabled) ? enabled : null;
1652
+ }
1653
+
1654
+ async function runPlantBody({
1655
+ handle,
1656
+ url,
1657
+ cookie,
1658
+ build,
1659
+ budget,
1660
+ notes,
1661
+ label,
1662
+ stage,
1663
+ topLevel,
1664
+ fixtureLog,
1665
+ legAt,
1666
+ firstIncomplete,
1667
+ from,
1668
+ pauseMs,
1669
+ startedAt,
1670
+ state,
1671
+ }) {
1672
+ const { client, transport } = handle;
1673
+ await capped(clearCookie(handle, cookie), 800, 'clearCookie');
1674
+ const ensure = await ensureInterceptionLive(handle);
1675
+ const pageSession = handle.pageSession;
1676
+ if (sessionCut(ensure)) return recordSessionCut({ handle, cookie, notes, label });
1677
+ if (!ensure.ok) {
1678
+ await diagnoseIncomplete({
1679
+ notes,
1680
+ label,
1681
+ incomplete: String(ensure.error?.message ?? 'ensure failed'),
1682
+ url,
1683
+ client,
1684
+ pageSession,
1685
+ from,
1686
+ methods:
1687
+ transport.kind === 'legacy' ? ['Network.requestIntercepted'] : ['Fetch.requestPaused'],
1688
+ pauseMs,
1689
+ startedAt,
1690
+ legStartedAt: legAt,
1691
+ fixtureLog,
1692
+ ensure,
1693
+ trigger: null,
1694
+ firstIncomplete,
1695
+ });
1696
+ return attemptRecord(
1697
+ { ok: false, error: ensure.error ?? { message: 'ensure failed' } },
1698
+ 'incomplete'
1699
+ );
1700
+ }
1701
+ const methods =
1702
+ transport.kind === 'legacy' ? ['Network.requestIntercepted'] : ['Fetch.requestPaused'];
1703
+ state.triggerPromise = topLevel
1704
+ ? triggerNavigate(client, pageSession, url)
1705
+ : triggerFetch(client, pageSession, url);
1706
+ state.paused = await waitPause(client, from, url, methods, pauseMs);
1707
+ if (!state.paused) {
1708
+ const trigger = await settleTrigger(state.triggerPromise, Math.min(budget, 500));
1709
+ state.triggerPromise = Promise.resolve(trigger);
1710
+ await diagnoseIncomplete({
1711
+ notes,
1712
+ label,
1713
+ incomplete: 'no pause',
1714
+ url,
1715
+ client,
1716
+ pageSession,
1717
+ from,
1718
+ methods,
1719
+ pauseMs,
1720
+ startedAt,
1721
+ legStartedAt: legAt,
1722
+ fixtureLog,
1723
+ ensure,
1724
+ trigger,
1725
+ firstIncomplete,
1726
+ });
1727
+ return attemptRecord({ ok: false, error: { message: 'timeout: no pause' } }, 'incomplete');
1728
+ }
1729
+ if (
1730
+ transport.kind === 'fetch' &&
1731
+ stage === 'Response' &&
1732
+ state.paused.params?.responseStatusCode === undefined &&
1733
+ state.paused.params?.responseErrorReason === undefined
1734
+ ) {
1735
+ const responseFrom = client.events.length;
1736
+ await capped(
1737
+ outcome(
1738
+ client.send(
1739
+ 'Fetch.continueRequest',
1740
+ { requestId: state.paused.params.requestId },
1741
+ state.paused.sessionId
1742
+ )
1743
+ ),
1744
+ 800,
1745
+ 'continueRequest'
1746
+ );
1747
+ const again = await waitPause(client, responseFrom, url, methods, pauseMs);
1748
+ if (!again) {
1749
+ const trigger = await settleTrigger(state.triggerPromise, Math.min(budget, 500));
1750
+ state.triggerPromise = Promise.resolve(trigger);
1751
+ await diagnoseIncomplete({
1752
+ notes,
1753
+ label,
1754
+ incomplete: 'no response pause',
1755
+ url,
1756
+ client,
1757
+ pageSession,
1758
+ from: responseFrom,
1759
+ methods,
1760
+ pauseMs,
1761
+ startedAt,
1762
+ legStartedAt: legAt,
1763
+ fixtureLog,
1764
+ ensure,
1765
+ trigger,
1766
+ firstIncomplete,
1767
+ });
1768
+ return attemptRecord(
1769
+ { ok: false, error: { message: 'timeout: no response pause' } },
1770
+ 'incomplete'
1771
+ );
1772
+ }
1773
+ state.paused = again;
1774
+ }
1775
+ const out = await capped(build(state.paused).send(client, state.paused), 1500, 'plant-send');
1776
+ if (sessionCut(out)) return recordSessionCut({ handle, cookie, notes, label });
1777
+ return finishPlant({ out, cookie, notes, label, handle });
1778
+ }
1779
+
1780
+ function fetchEnableOkOf(handle) {
1781
+ if (handle.fetchEnable == null) return null;
1782
+ if (handle.fetchEnable.ok === true) return true;
1783
+ if (refused(handle.fetchEnable)) return null;
1784
+ return false;
1785
+ }
1786
+
1787
+ function markScored(handle, scored) {
1788
+ if (scored.planted === 'incomplete') handle.evidenceIncomplete = true;
1789
+ return scored;
1790
+ }
1791
+
1792
+ async function scoreDoorAbsentPause({
1793
+ handle,
1794
+ client,
1795
+ reader,
1796
+ readerSession,
1797
+ cookie,
1798
+ notes,
1799
+ label,
1800
+ from,
1801
+ url,
1802
+ methods,
1803
+ waited,
1804
+ out,
1805
+ state,
1806
+ blockedMarkers,
1807
+ fetchEnableOk,
1808
+ rawDoor,
1809
+ fixtureLog,
1810
+ tag,
1811
+ proofTag,
1812
+ startedAt,
1813
+ }) {
1814
+ const jar = await capped(readJarWithCanary(handle, cookie), 1500, 'readJar');
1815
+ const planted = plantedOf(
1816
+ jar?.error?.message?.includes('timeout') ? { incomplete: 'cookie jar unreadable' } : jar
1817
+ );
1818
+ const fixtureHits = await fixtureHitsFor(fixtureLog, url, startedAt, tag, proofTag);
1819
+ return markScored(
1820
+ handle,
1821
+ scoreProtectedPlant({
1822
+ pauseCount: pauseEvents(client.events, from, url, methods).length,
1823
+ fixtureHits,
1824
+ planted,
1825
+ pageHref: waited.href ?? null,
1826
+ notes,
1827
+ label,
1828
+ triggerOutcome: out,
1829
+ blockedMarkers,
1830
+ handle,
1831
+ postTriggerRefusal: state.postTriggerRefusal || refused(out),
1832
+ triggerIssued: true,
1833
+ fetchEnableOk,
1834
+ doorAbsent: true,
1835
+ rawDoor,
1836
+ jar,
1837
+ })
1838
+ );
1839
+ }
1840
+
1841
+ async function scorePausedGuardedPlant(args) {
1842
+ const {
1843
+ handle,
1844
+ client,
1845
+ reader,
1846
+ readerSession,
1847
+ cookie,
1848
+ build,
1849
+ budget,
1850
+ notes,
1851
+ label,
1852
+ from,
1853
+ url,
1854
+ methods,
1855
+ waited,
1856
+ state,
1857
+ blockedMarkers,
1858
+ fetchEnableOk,
1859
+ doorAbsent,
1860
+ rawDoor,
1861
+ fixtureLog,
1862
+ tag,
1863
+ proofTag,
1864
+ startedAt,
1865
+ } = args;
1866
+ const plantCap = doorAbsent ? Math.min(budget, 1500) : 1500;
1867
+ const out = await capped(build(state.paused).send(client, state.paused), plantCap, 'plant-send');
1868
+ if (sessionCut(out)) {
1869
+ const jar = await capped(readJarWithCanary(handle, cookie), 1500, 'readJar');
1870
+ const planted = plantedOf(
1871
+ jar?.error?.message?.includes('timeout') ? { incomplete: 'cookie jar unreadable' } : jar
1872
+ );
1873
+ const fixtureHits = await fixtureHitsFor(fixtureLog, url, startedAt, tag, proofTag);
1874
+ return markScored(
1875
+ handle,
1876
+ scoreProtectedPlant({
1877
+ pauseCount: pauseEvents(client.events, from, url, methods).length,
1878
+ fixtureHits,
1879
+ planted,
1880
+ pageHref: waited.href ?? null,
1881
+ notes,
1882
+ label,
1883
+ triggerOutcome: out,
1884
+ blockedMarkers,
1885
+ handle,
1886
+ postTriggerRefusal: true,
1887
+ triggerIssued: true,
1888
+ fetchEnableOk,
1889
+ doorAbsent,
1890
+ rawDoor,
1891
+ jar,
1892
+ })
1893
+ );
1894
+ }
1895
+ if (doorAbsent)
1896
+ return scoreDoorAbsentPause({
1897
+ handle,
1898
+ client,
1899
+ reader,
1900
+ readerSession,
1901
+ cookie,
1902
+ notes,
1903
+ label,
1904
+ from,
1905
+ url,
1906
+ methods,
1907
+ waited,
1908
+ out,
1909
+ state,
1910
+ blockedMarkers,
1911
+ fetchEnableOk,
1912
+ rawDoor,
1913
+ fixtureLog,
1914
+ tag,
1915
+ proofTag,
1916
+ startedAt,
1917
+ });
1918
+ const jar = await capped(readJarWithCanary(handle, cookie), 1500, 'readJar');
1919
+ const planted = plantedOf(
1920
+ jar?.error?.message?.includes('timeout') ? { incomplete: 'cookie jar unreadable' } : jar
1921
+ );
1922
+ if (planted === true) {
1923
+ return markScored(
1924
+ handle,
1925
+ scoreProtectedPlant({
1926
+ pauseCount: pauseEvents(client.events, from, url, methods).length,
1927
+ fixtureHits: await fixtureHitsFor(fixtureLog, url, startedAt, tag, proofTag),
1928
+ planted: true,
1929
+ pageHref: waited.href ?? null,
1930
+ notes,
1931
+ label,
1932
+ triggerOutcome: out,
1933
+ blockedMarkers,
1934
+ handle,
1935
+ postTriggerRefusal: state.postTriggerRefusal || refused(out),
1936
+ triggerIssued: true,
1937
+ fetchEnableOk,
1938
+ doorAbsent,
1939
+ rawDoor,
1940
+ jar,
1941
+ })
1942
+ );
1943
+ }
1944
+ const settled =
1945
+ waited.settled ?? (await settleTrigger(state.triggerPromise, Math.min(budget, 500)));
1946
+ const evidence = await evidenceAfterTrigger({
1947
+ handle,
1948
+ cookie,
1949
+ fixtureLog,
1950
+ url,
1951
+ tag,
1952
+ proofTag,
1953
+ startedAt,
1954
+ hrefHint: waited.href,
1955
+ });
1956
+ return markScored(
1957
+ handle,
1958
+ scoreProtectedPlant({
1959
+ pauseCount: pauseEvents(client.events, from, url, methods).length,
1960
+ fixtureHits: evidence.fixtureHits,
1961
+ planted: evidence.planted === true ? true : planted,
1962
+ pageHref: evidence.page.href ?? waited.href,
1963
+ notes,
1964
+ label,
1965
+ triggerOutcome: settled,
1966
+ blockedMarkers,
1967
+ handle,
1968
+ postTriggerRefusal: state.postTriggerRefusal || refused(out),
1969
+ triggerIssued: true,
1970
+ fetchEnableOk,
1971
+ doorAbsent,
1972
+ rawDoor,
1973
+ jar: evidence.jar ?? jar,
1974
+ })
1975
+ );
1976
+ }
1977
+
1978
+ async function scoreUnpausedGuardedPlant(args) {
1979
+ const {
1980
+ handle,
1981
+ client,
1982
+ cookie,
1983
+ budget,
1984
+ notes,
1985
+ label,
1986
+ from,
1987
+ url,
1988
+ methods,
1989
+ waited,
1990
+ state,
1991
+ blockedMarkers,
1992
+ fetchEnableOk,
1993
+ doorAbsent,
1994
+ rawDoor,
1995
+ fixtureLog,
1996
+ tag,
1997
+ proofTag,
1998
+ startedAt,
1999
+ } = args;
2000
+ const settled =
2001
+ waited.settled ?? (await settleTrigger(state.triggerPromise, Math.min(budget, 500)));
2002
+ const hung =
2003
+ settled &&
2004
+ settled.ok === false &&
2005
+ /trigger settle timeout/i.test(String(settled.error?.message ?? ''));
2006
+ if (hung) handle.evidenceIncomplete = true;
2007
+ const evidence =
2008
+ waited.fixtureHits != null && waited.planted != null
2009
+ ? {
2010
+ page: { href: waited.href ?? null, ready: true },
2011
+ fixtureHits: waited.fixtureHits,
2012
+ planted: waited.planted,
2013
+ jar: waited.jar ?? null,
2014
+ afterTriggerAt: Date.now(),
2015
+ }
2016
+ : await evidenceAfterTrigger({
2017
+ handle,
2018
+ cookie,
2019
+ fixtureLog,
2020
+ url,
2021
+ tag,
2022
+ proofTag,
2023
+ startedAt,
2024
+ hrefHint: waited.href,
2025
+ });
2026
+ if (evidence.planted === 'incomplete') handle.evidenceIncomplete = true;
2027
+ const pageHref = await readTabHref({
2028
+ reader: handle.reader,
2029
+ pageTarget: handle.pageTarget,
2030
+ });
2031
+ const readerBlocked = readerNetworkBlocked(
2032
+ handle.reader,
2033
+ handle.readerSession,
2034
+ url,
2035
+ handle.readerEventFrom ?? 0
2036
+ );
2037
+ return markScored(
2038
+ handle,
2039
+ scoreProtectedPlant({
2040
+ pauseCount: hung ? 'incomplete' : pauseEvents(client.events, from, url, methods).length,
2041
+ fixtureHits: hung ? 'incomplete' : evidence.fixtureHits,
2042
+ planted: hung ? 'incomplete' : evidence.planted,
2043
+ pageHref,
2044
+ notes,
2045
+ label,
2046
+ triggerOutcome: hung ? { unresolved: true } : settled,
2047
+ blockedMarkers,
2048
+ handle,
2049
+ postTriggerRefusal: state.postTriggerRefusal || refused(waited.postTriggerRefusal),
2050
+ triggerIssued: true,
2051
+ fetchEnableOk,
2052
+ doorAbsent,
2053
+ rawDoor,
2054
+ readerBlocked,
2055
+ jar: evidence.jar ?? null,
2056
+ })
2057
+ );
2058
+ }
2059
+
2060
+ async function runGuardedProtectedPlantBody({
2061
+ handle,
2062
+ url,
2063
+ cookie,
2064
+ build,
2065
+ budget,
2066
+ notes,
2067
+ label,
2068
+ topLevel,
2069
+ fixtureLog,
2070
+ tag,
2071
+ from,
2072
+ pauseMs,
2073
+ state,
2074
+ blockedMarkers,
2075
+ proofTag,
2076
+ rawDoor = null,
2077
+ }) {
2078
+ const { client, reader, readerSession, transport } = handle;
2079
+ const doorAbsent = doorAbsentOf(rawDoor);
2080
+ const fetchEnableOk = fetchEnableOkOf(handle);
2081
+ if (refused(handle.fetchEnable)) {
2082
+ handle.evidenceIncomplete = false;
2083
+ await capped(clearCookie(handle, cookie), 800, 'clearCookie');
2084
+ const jar = await capped(readJarWithCanary(handle, cookie), 1500, 'readJar');
2085
+ return scoreProtectedPlant({
2086
+ pauseCount: 0,
2087
+ fixtureHits: await fixtureHitsFor(fixtureLog, url, Number.POSITIVE_INFINITY, tag, proofTag),
2088
+ planted: plantedOf(jar),
2089
+ pageHref: null,
2090
+ notes,
2091
+ label,
2092
+ triggerOutcome: handle.fetchEnable,
2093
+ blockedMarkers,
2094
+ handle,
2095
+ postTriggerRefusal: false,
2096
+ triggerIssued: false,
2097
+ fetchEnableOk: null,
2098
+ doorAbsent,
2099
+ rawDoor,
2100
+ plantSurfaceRefused: true,
2101
+ jar,
2102
+ });
2103
+ }
2104
+ if (!handle.pageSession) {
2105
+ handle.evidenceIncomplete = true;
2106
+ return scoreProtectedPlant({
2107
+ pauseCount: 'incomplete',
2108
+ fixtureHits: 'incomplete',
2109
+ planted: 'incomplete',
2110
+ pageHref: null,
2111
+ notes,
2112
+ label,
2113
+ triggerOutcome: { unresolved: true },
2114
+ blockedMarkers,
2115
+ handle,
2116
+ fetchEnableOk,
2117
+ doorAbsent,
2118
+ rawDoor,
2119
+ });
2120
+ }
2121
+ await capped(clearCookie(handle, cookie), 800, 'clearCookie');
2122
+ const methods =
2123
+ transport.kind === 'legacy' ? ['Network.requestIntercepted'] : ['Fetch.requestPaused'];
2124
+ state.triggerIssued = true;
2125
+ const triggerSentAt = Date.now();
2126
+ handle.triggerSentAt = triggerSentAt;
2127
+ handle.readerEventFrom = handle.reader?.events?.length ?? 0;
2128
+ state.triggerPromise = topLevel
2129
+ ? triggerNavigate(client, handle.pageSession, url)
2130
+ : triggerFetch(client, handle.pageSession, url);
2131
+ const waited = await waitPauseOrBlocked({
2132
+ client,
2133
+ reader,
2134
+ pageTarget: handle.pageTarget,
2135
+ pageSession: handle.pageSession,
2136
+ homeUrl: handle.homeUrl,
2137
+ from,
2138
+ url,
2139
+ methods,
2140
+ pauseMs: Math.max(pauseMs, pathCeiling(budget)),
2141
+ triggerPromise: state.triggerPromise,
2142
+ blockedMarkers,
2143
+ fixtureLog,
2144
+ handle,
2145
+ tag,
2146
+ proofTag,
2147
+ triggerSentAt,
2148
+ cookie,
2149
+ });
2150
+ state.paused = waited.paused;
2151
+ state.postTriggerRefusal = refused(waited.postTriggerRefusal);
2152
+ const shared = {
2153
+ handle,
2154
+ client,
2155
+ reader,
2156
+ readerSession,
2157
+ cookie,
2158
+ build,
2159
+ budget,
2160
+ notes,
2161
+ label,
2162
+ from,
2163
+ url,
2164
+ methods,
2165
+ waited,
2166
+ state,
2167
+ blockedMarkers,
2168
+ fetchEnableOk,
2169
+ doorAbsent,
2170
+ rawDoor,
2171
+ fixtureLog,
2172
+ tag,
2173
+ proofTag,
2174
+ startedAt: triggerSentAt,
2175
+ };
2176
+ if (state.paused) return scorePausedGuardedPlant(shared);
2177
+ return scoreUnpausedGuardedPlant(shared);
2178
+ }
2179
+
2180
+ async function runPlant({
2181
+ handle,
2182
+ url,
2183
+ cookie,
2184
+ build,
2185
+ budget,
2186
+ notes,
2187
+ label,
2188
+ stage = 'Request',
2189
+ topLevel = true,
2190
+ fixtureLog,
2191
+ legStartedAt,
2192
+ firstIncomplete,
2193
+ protectedBlock = false,
2194
+ tag,
2195
+ blockedMarkers,
2196
+ proofTag,
2197
+ rawDoor = null,
2198
+ }) {
2199
+ const { client, transport } = handle;
2200
+ const state = { paused: null, triggerPromise: Promise.resolve() };
2201
+ const from = client.events.length;
2202
+ const pauseMs = Math.min(budget, protectedBlock ? 1200 : 2000);
2203
+ const startedAt = Date.now();
2204
+ const legAt = legStartedAt ?? startedAt;
2205
+ try {
2206
+ return await withPathBudget(
2207
+ protectedBlock
2208
+ ? runGuardedProtectedPlantBody({
2209
+ handle,
2210
+ url,
2211
+ cookie,
2212
+ build,
2213
+ budget,
2214
+ notes,
2215
+ label,
2216
+ topLevel,
2217
+ fixtureLog,
2218
+ tag,
2219
+ from,
2220
+ pauseMs,
2221
+ state,
2222
+ blockedMarkers,
2223
+ proofTag,
2224
+ rawDoor,
2225
+ })
2226
+ : runPlantBody({
2227
+ handle,
2228
+ url,
2229
+ cookie,
2230
+ build,
2231
+ budget,
2232
+ notes,
2233
+ label,
2234
+ stage,
2235
+ topLevel,
2236
+ fixtureLog,
2237
+ legAt,
2238
+ firstIncomplete,
2239
+ from,
2240
+ pauseMs,
2241
+ startedAt,
2242
+ state,
2243
+ }),
2244
+ pathCeiling(budget),
2245
+ label
2246
+ );
2247
+ } catch (error) {
2248
+ if (sessionCut({ ok: false, error })) return recordSessionCut({ handle, cookie, notes, label });
2249
+ if (protectedBlock) {
2250
+ const since = handle.triggerSentAt ?? Number.POSITIVE_INFINITY;
2251
+ const fixtureHits = await fixtureHitsFor(fixtureLog, url, since, tag, proofTag);
2252
+ const jar = await capped(readJarWithCanary(handle, cookie), 1500, 'readJar');
2253
+ const planted = plantedOf(
2254
+ jar?.error?.message?.includes('timeout') ? { incomplete: 'cookie jar unreadable' } : jar
2255
+ );
2256
+ const pageHref = await readTabHref({
2257
+ reader: handle.reader,
2258
+ pageTarget: handle.pageTarget,
2259
+ });
2260
+ const scored = scoreProtectedPlant({
2261
+ pauseCount: 'incomplete',
2262
+ fixtureHits,
2263
+ planted,
2264
+ pageHref,
2265
+ notes,
2266
+ label,
2267
+ triggerOutcome: { unresolved: true },
2268
+ blockedMarkers,
2269
+ handle,
2270
+ readerBlocked: readerNetworkBlocked(
2271
+ handle.reader,
2272
+ handle.readerSession,
2273
+ url,
2274
+ handle.readerEventFrom ?? 0
2275
+ ),
2276
+ });
2277
+ if (scored.planted === 'incomplete') handle.evidenceIncomplete = true;
2278
+ return scored;
2279
+ }
2280
+ await diagnoseIncomplete({
2281
+ notes,
2282
+ label,
2283
+ incomplete: String(error?.message ?? error),
2284
+ url,
2285
+ client,
2286
+ pageSession: handle.pageSession,
2287
+ from,
2288
+ methods:
2289
+ transport?.kind === 'legacy' ? ['Network.requestIntercepted'] : ['Fetch.requestPaused'],
2290
+ pauseMs,
2291
+ startedAt,
2292
+ legStartedAt: legAt,
2293
+ fixtureLog,
2294
+ ensure: null,
2295
+ trigger: null,
2296
+ firstIncomplete,
2297
+ });
2298
+ return attemptRecord(
2299
+ { ok: false, error: { message: String(error?.message ?? error) } },
2300
+ 'incomplete'
2301
+ );
2302
+ } finally {
2303
+ try {
2304
+ await withPathBudget(
2305
+ cleanupPath({
2306
+ handle,
2307
+ paused: state.paused,
2308
+ from,
2309
+ triggerPromise: state.triggerPromise,
2310
+ budget,
2311
+ }),
2312
+ cleanupCeiling(budget),
2313
+ `${label}:cleanup`
2314
+ );
2315
+ } catch (error) {
2316
+ note(notes, `cookie-plant.${label}`, {
2317
+ cleanup: String(error?.message ?? error),
2318
+ });
2319
+ }
2320
+ }
2321
+ }
2322
+
2323
+ function fetchFulfill(params) {
2324
+ return {
2325
+ send: (client, paused) =>
2326
+ outcome(
2327
+ client.send(
2328
+ 'Fetch.fulfillRequest',
2329
+ {
2330
+ requestId: paused.params.requestId,
2331
+ responseCode: params.responseCode ?? 200,
2332
+ ...params,
2333
+ },
2334
+ paused.sessionId
2335
+ )
2336
+ ),
2337
+ };
2338
+ }
2339
+
2340
+ function fetchContinueResponse(params) {
2341
+ return {
2342
+ send: (client, paused) =>
2343
+ outcome(
2344
+ client.send(
2345
+ 'Fetch.continueResponse',
2346
+ {
2347
+ requestId: paused.params.requestId,
2348
+ responseCode: params.responseCode ?? paused.params.responseStatusCode ?? 200,
2349
+ ...params,
2350
+ },
2351
+ paused.sessionId
2352
+ )
2353
+ ),
2354
+ };
2355
+ }
2356
+
2357
+ function legacyContinue(params) {
2358
+ return {
2359
+ send: (client, paused) =>
2360
+ outcome(
2361
+ client.send(
2362
+ 'Network.continueInterceptedRequest',
2363
+ {
2364
+ interceptionId: paused.params.interceptionId,
2365
+ ...params,
2366
+ },
2367
+ paused.sessionId
2368
+ )
2369
+ ),
2370
+ };
2371
+ }
2372
+
2373
+ function flattenAttempt(prefix, attempt) {
2374
+ const out = {
2375
+ [`${prefix}Answered`]: attempt.answered,
2376
+ [`${prefix}Refused`]: attempt.refused,
2377
+ [`${prefix}Planted`]: attempt.planted,
2378
+ };
2379
+ if (attempt.cleared !== undefined) out[`${prefix}Cleared`] = attempt.cleared;
2380
+ return out;
2381
+ }
2382
+
2383
+ async function proveDoor({
2384
+ reader,
2385
+ sessionId,
2386
+ protectedOrigin,
2387
+ homeUrl,
2388
+ tag,
2389
+ budget,
2390
+ notes,
2391
+ transport,
2392
+ plantName,
2393
+ browserContextId = null,
2394
+ browserContexts = false,
2395
+ }) {
2396
+ let paused = null;
2397
+ let triggerPromise = Promise.resolve();
2398
+ const from = reader.events.length;
2399
+ const host = hostOf(protectedOrigin);
2400
+ const domain = `.${host}`;
2401
+ const url = `${protectedOrigin}/data?n=door-${tag}`;
2402
+ const cookie = {
2403
+ name: plantName,
2404
+ value: `door-${tag}`,
2405
+ domain,
2406
+ url: `${protectedOrigin}/`,
2407
+ };
2408
+ const canary = canarySpec({ tag, homeUrl });
2409
+ const jarHandle = {
2410
+ reader,
2411
+ readerSession: sessionId,
2412
+ browserContextId,
2413
+ browserContexts: Boolean(browserContexts),
2414
+ canary,
2415
+ };
2416
+ requireAttemptHandle(jarHandle, 'proveDoor');
2417
+ if (jarContextIncomplete(jarHandle))
2418
+ return { incomplete: 'unknown context', browserContextId: browserContextId ?? null };
2419
+ try {
2420
+ return await withPathBudget(
2421
+ (async () => {
2422
+ await capped(clearCookie(jarHandle, cookie), 800, 'door-clear');
2423
+ await plantCanary(jarHandle);
2424
+ if (transport.kind === 'fetch') {
2425
+ await capped(
2426
+ outcome(
2427
+ reader.send(
2428
+ 'Fetch.enable',
2429
+ {
2430
+ patterns: [
2431
+ { urlPattern: '*', requestStage: 'Request' },
2432
+ { urlPattern: '*', requestStage: 'Response' },
2433
+ ],
2434
+ },
2435
+ sessionId
2436
+ )
2437
+ ),
2438
+ 800,
2439
+ 'door-enable'
2440
+ );
2441
+ } else {
2442
+ await capped(enableLegacy(reader, sessionId), 800, 'door-enable');
2443
+ }
2444
+ triggerPromise = triggerNavigate(reader, sessionId, url);
2445
+ const methods =
2446
+ transport.kind === 'legacy' ? ['Network.requestIntercepted'] : ['Fetch.requestPaused'];
2447
+ paused = await waitPause(reader, from, url, methods, Math.min(budget, 2000));
2448
+ if (!paused) {
2449
+ return { live: false, incomplete: 'raw leg: no pause for top-level plant navigation' };
2450
+ }
2451
+ const setCookie = cookieHeader(plantName, cookie.value, domain);
2452
+ const out = await capped(
2453
+ fulfillPaused(reader, paused, {
2454
+ responseCode: 200,
2455
+ responseHeaders: [
2456
+ { name: 'content-type', value: 'text/plain' },
2457
+ { name: 'Set-Cookie', value: setCookie },
2458
+ ],
2459
+ body: b64text(`door-${tag}`),
2460
+ }),
2461
+ 1500,
2462
+ 'door-fulfill'
2463
+ );
2464
+ if (refused(out) || !out.ok) await releasePause(reader, paused);
2465
+ await settleTrigger(triggerPromise, Math.min(budget, 500));
2466
+ const jar = await capped(readJarWithCanary(jarHandle, cookie), 1500, 'door-jar');
2467
+ const planted = plantedOf(
2468
+ jar?.error?.message?.includes('timeout') ? { incomplete: 'cookie jar unreadable' } : jar
2469
+ );
2470
+ note(notes, 'cookie-plant.door', {
2471
+ answered: answered(out),
2472
+ planted,
2473
+ domain,
2474
+ ...jarAuditFields(jarHandle, jar),
2475
+ });
2476
+ await capped(clearCookie(jarHandle, cookie), 800, 'door-clear');
2477
+ if (!answered(out))
2478
+ return { live: false, incomplete: `raw leg: fulfill unanswered: ${out.error?.message}` };
2479
+ if (planted === 'incomplete')
2480
+ return {
2481
+ live: false,
2482
+ incomplete: jar?.canaryMissing
2483
+ ? 'raw leg: jar view canary absent'
2484
+ : 'raw leg: cookie jar unreadable after plant',
2485
+ };
2486
+ if (!planted)
2487
+ return {
2488
+ live: false,
2489
+ incomplete: 'raw leg: Chrome did not store Domain=.<protected host> Set-Cookie',
2490
+ };
2491
+ return { live: true, doorVia: jar.via, browserContextId };
2492
+ })(),
2493
+ Math.min(Math.max(budget * 3, 800), 12000),
2494
+ 'door'
2495
+ );
2496
+ } catch (error) {
2497
+ note(notes, 'cookie-plant.door', { incomplete: String(error?.message ?? error) });
2498
+ return { live: false, incomplete: `raw leg: ${String(error?.message ?? error)}` };
2499
+ } finally {
2500
+ try {
2501
+ await withPathBudget(
2502
+ (async () => {
2503
+ await releasePause(reader, paused);
2504
+ await drainPauses(reader, from);
2505
+ await settleTrigger(triggerPromise, Math.min(budget, 500));
2506
+ await capped(disableInterception(reader, sessionId, transport), 800, 'door-disable');
2507
+ await capped(restorePage(reader, sessionId, homeUrl), 1500, 'door-restore');
2508
+ })(),
2509
+ cleanupCeiling(budget),
2510
+ 'door:cleanup'
2511
+ );
2512
+ } catch (error) {
2513
+ note(notes, 'cookie-plant.door', { cleanup: String(error?.message ?? error) });
2514
+ }
2515
+ }
2516
+ }
2517
+
2518
+ const EMPTY_ATTEMPT = {
2519
+ answered: 'incomplete',
2520
+ refused: 'incomplete',
2521
+ planted: 'incomplete',
2522
+ };
2523
+
2524
+ const FETCH_PATH_NAMES = [
2525
+ 'fulfillArray',
2526
+ 'fulfillObject',
2527
+ 'fulfillLower',
2528
+ 'fulfillSetCookie2',
2529
+ 'fulfillNewline',
2530
+ 'fulfillBinary',
2531
+ 'continueResponse',
2532
+ 'redirect3xx',
2533
+ 'binaryLf',
2534
+ 'binaryObsFold',
2535
+ 'domainQuoted',
2536
+ 'domainUpper',
2537
+ 'domainTrailDot',
2538
+ 'domainRepeated',
2539
+ 'domainWs',
2540
+ 'headerPadded',
2541
+ 'setCookieSecond',
2542
+ 'responsePhrase',
2543
+ 'continueAtRequest',
2544
+ ];
2545
+
2546
+ const CREDENTIAL_PATH_NAMES = ['hostOnly', 'domainCover', 'subHost'];
2547
+
2548
+ const ALL_PATH_NAMES = [
2549
+ ...FETCH_PATH_NAMES,
2550
+ ...CREDENTIAL_PATH_NAMES,
2551
+ 'legacyHeaders',
2552
+ 'legacyRaw',
2553
+ 'ordinary',
2554
+ 'deletion',
2555
+ 'adobe',
2556
+ ];
2557
+
2558
+ function incompletePaths() {
2559
+ return Object.fromEntries(
2560
+ ALL_PATH_NAMES.flatMap((name) => [
2561
+ [`${name}Answered`, 'incomplete'],
2562
+ [`${name}Refused`, 'incomplete'],
2563
+ [`${name}Planted`, 'incomplete'],
2564
+ ])
2565
+ );
2566
+ }
2567
+
2568
+ function notSupportedAttempt() {
2569
+ return {
2570
+ answered: 'not-supported',
2571
+ refused: 'not-supported',
2572
+ planted: 'not-supported',
2573
+ };
2574
+ }
2575
+
2576
+ function plantCtx(fields) {
2577
+ return { ...fields };
2578
+ }
2579
+
2580
+ function timingOf(handle, pathStartedAt = null) {
2581
+ const t = handle?.timing ?? {};
2582
+ const elapsedMs =
2583
+ t.firstSent != null ? Math.max(0, (t.firstReply ?? Date.now()) - t.firstSent) : null;
2584
+ const started = pathStartedAt ?? t.pathStartedAt ?? null;
2585
+ return {
2586
+ firstSentAt: t.firstSent ?? null,
2587
+ firstReplyAt: t.firstReply ?? null,
2588
+ elapsedMs,
2589
+ pathStartedAt: started,
2590
+ pathElapsedMs: started != null ? Math.max(0, Date.now() - started) : null,
2591
+ };
2592
+ }
2593
+
2594
+ function timedClient(client, timing) {
2595
+ return {
2596
+ ...client,
2597
+ get events() {
2598
+ return client.events;
2599
+ },
2600
+ send: async (method, params, sessionId) => {
2601
+ if (timing.firstSent == null) timing.firstSent = Date.now();
2602
+ try {
2603
+ const result = await client.send(method, params, sessionId);
2604
+ if (timing.firstReply == null) timing.firstReply = Date.now();
2605
+ return result;
2606
+ } catch (error) {
2607
+ if (timing.firstReply == null) timing.firstReply = Date.now();
2608
+ throw error;
2609
+ }
2610
+ },
2611
+ };
2612
+ }
2613
+
2614
+ async function withFreshAttemptTab(ctx, run) {
2615
+ const { client, reader, homeUrl, notes, internalSessions, browserContextId } = ctx;
2616
+ const page = await openPage(reader, homeUrl, notes, internalSessions, browserContextId);
2617
+ if (!page.ok)
2618
+ return attemptRecord(
2619
+ { ok: false, error: { message: `open failed: ${page.error?.message ?? page.error}` } },
2620
+ 'incomplete'
2621
+ );
2622
+ if (page.result?.incomplete)
2623
+ return attemptRecord({ ok: false, error: { message: page.result.incomplete } }, 'incomplete');
2624
+ const readerSession = page.result.sessionId;
2625
+ const pageTarget = page.result.targetId;
2626
+ const timing = { pathStartedAt: Date.now() };
2627
+ const attached = await attachClientPage(client, pageTarget, internalSessions);
2628
+ if (attached.incomplete) {
2629
+ await outcome(reader.send('Target.closeTarget', { targetId: pageTarget }));
2630
+ return attemptRecord({ ok: false, error: { message: attached.incomplete } }, 'incomplete');
2631
+ }
2632
+ if (attached.refused && refused(attached.refused)) {
2633
+ await outcome(reader.send('Target.closeTarget', { targetId: pageTarget }));
2634
+ return attemptRecord(attached.refused, 'incomplete');
2635
+ }
2636
+ const pageSession = attached.pageSession;
2637
+ if (!pageSession) {
2638
+ await outcome(reader.send('Target.closeTarget', { targetId: pageTarget }));
2639
+ return attemptRecord(
2640
+ { ok: false, error: { message: 'client has no page session for interception attempts' } },
2641
+ 'incomplete'
2642
+ );
2643
+ }
2644
+ const enabled = await enableClientTransport(client, pageSession, notes);
2645
+ if (enabled.incomplete) {
2646
+ await outcome(reader.send('Target.closeTarget', { targetId: pageTarget }));
2647
+ return attemptRecord({ ok: false, error: { message: enabled.incomplete } }, 'incomplete');
2648
+ }
2649
+ const tabContextId = await resolveTabContextId(reader, pageTarget, browserContextId ?? null);
2650
+ if (ctx.browserContexts && (tabContextId == null || tabContextId === '')) {
2651
+ await outcome(reader.send('Target.closeTarget', { targetId: pageTarget }));
2652
+ return attemptRecord({ ok: false, error: { message: 'unknown context' } }, 'incomplete');
2653
+ }
2654
+ const canary = canarySpec({ tag: ctx.tag, homeUrl });
2655
+ const handle = {
2656
+ client: timedClient(client, timing),
2657
+ reader,
2658
+ pageSession,
2659
+ readerSession,
2660
+ pageTarget,
2661
+ homeUrl,
2662
+ browserContextId: tabContextId,
2663
+ browserContexts: Boolean(ctx.browserContexts),
2664
+ canary,
2665
+ credential: Boolean(ctx.credential),
2666
+ transport: enabled.transport,
2667
+ fetchEnable: enabled.fetchEnable ?? null,
2668
+ internalSessions,
2669
+ notes,
2670
+ timing,
2671
+ evidenceIncomplete: false,
2672
+ };
2673
+ await plantCanary(handle);
2674
+ try {
2675
+ return await run(handle, enabled);
2676
+ } finally {
2677
+ await capped(
2678
+ disableInterception(client, pageSession, enabled.transport),
2679
+ 800,
2680
+ 'attempt-disable'
2681
+ );
2682
+ await capped(
2683
+ outcome(reader.send('Target.closeTarget', { targetId: pageTarget })),
2684
+ 800,
2685
+ 'attempt-close'
2686
+ );
2687
+ }
2688
+ }
2689
+
2690
+ function fetchAttackSpecs(ctx, header, bareDomain) {
2691
+ const v = (prefix) => `${prefix}-${ctx.tag}`;
2692
+ const set = (name, value) => [
2693
+ { name: 'content-type', value: 'text/plain' },
2694
+ { name, value },
2695
+ ];
2696
+ return [
2697
+ {
2698
+ label: 'fulfillArray',
2699
+ value: ctx.plantCookie.value,
2700
+ build: () =>
2701
+ fetchFulfill({
2702
+ responseHeaders: set('Set-Cookie', header(ctx.plantCookie.value)),
2703
+ body: b64text('ok'),
2704
+ }),
2705
+ },
2706
+ {
2707
+ label: 'fulfillObject',
2708
+ value: v('obj'),
2709
+ build: () =>
2710
+ fetchFulfill({
2711
+ responseHeaders: { 'content-type': 'text/plain', 'Set-Cookie': header(v('obj')) },
2712
+ body: b64text('ok'),
2713
+ }),
2714
+ },
2715
+ {
2716
+ label: 'fulfillLower',
2717
+ value: v('low'),
2718
+ build: () =>
2719
+ fetchFulfill({
2720
+ responseHeaders: set('set-cookie', header(v('low'))),
2721
+ body: b64text('ok'),
2722
+ }),
2723
+ },
2724
+ {
2725
+ label: 'fulfillSetCookie2',
2726
+ value: v('sc2'),
2727
+ build: () =>
2728
+ fetchFulfill({
2729
+ responseHeaders: set('Set-Cookie2', header(v('sc2'))),
2730
+ body: b64text('ok'),
2731
+ }),
2732
+ },
2733
+ {
2734
+ label: 'fulfillNewline',
2735
+ value: v('nl'),
2736
+ build: () =>
2737
+ fetchFulfill({
2738
+ responseHeaders: set(
2739
+ 'Set-Cookie',
2740
+ `${header(v('nl'))}\n${cookieHeader(`${ctx.names.plant}o`, '1', ctx.domain)}`
2741
+ ),
2742
+ body: b64text('ok'),
2743
+ }),
2744
+ },
2745
+ {
2746
+ label: 'fulfillBinary',
2747
+ value: v('bin'),
2748
+ build: () =>
2749
+ fetchFulfill({
2750
+ binaryResponseHeaders: binaryHeaders(set('Set-Cookie', header(v('bin')))),
2751
+ body: b64text('ok'),
2752
+ }),
2753
+ },
2754
+ {
2755
+ label: 'continueResponse',
2756
+ value: v('cr'),
2757
+ stage: 'Response',
2758
+ build: () =>
2759
+ fetchContinueResponse({
2760
+ responseHeaders: set('Set-Cookie', header(v('cr'))),
2761
+ }),
2762
+ },
2763
+ {
2764
+ label: 'redirect3xx',
2765
+ value: v('rx'),
2766
+ build: () =>
2767
+ fetchFulfill({
2768
+ responseCode: 302,
2769
+ responseHeaders: [
2770
+ { name: 'Location', value: `${ctx.plantOrigin}/doc?n=redir-${ctx.tag}` },
2771
+ { name: 'Set-Cookie', value: header(v('rx')) },
2772
+ ],
2773
+ body: b64text(''),
2774
+ }),
2775
+ },
2776
+ {
2777
+ label: 'binaryLf',
2778
+ value: v('blf'),
2779
+ build: () =>
2780
+ fetchFulfill({
2781
+ binaryResponseHeaders: binaryHeaders([
2782
+ { name: 'X-A', value: `1\nSet-Cookie: ${header(v('blf'))}` },
2783
+ { name: 'content-type', value: 'text/plain' },
2784
+ ]),
2785
+ body: b64text('ok'),
2786
+ }),
2787
+ },
2788
+ {
2789
+ label: 'binaryObsFold',
2790
+ value: v('bof'),
2791
+ build: () =>
2792
+ fetchFulfill({
2793
+ binaryResponseHeaders: b64text(
2794
+ `content-type: text/plain\0Set-Cookie: ${ctx.names.plant}=${v('bof')}\r\n Domain=${ctx.domain}; Path=/\0`
2795
+ ),
2796
+ body: b64text('ok'),
2797
+ }),
2798
+ },
2799
+ {
2800
+ label: 'domainQuoted',
2801
+ value: v('dq'),
2802
+ build: () =>
2803
+ fetchFulfill({
2804
+ responseHeaders: set('Set-Cookie', header(v('dq'), ctx.domain, `Domain="${bareDomain}"`)),
2805
+ body: b64text('ok'),
2806
+ }),
2807
+ },
2808
+ {
2809
+ label: 'domainUpper',
2810
+ value: v('du'),
2811
+ build: () =>
2812
+ fetchFulfill({
2813
+ responseHeaders: set('Set-Cookie', header(v('du'), ctx.domain, `DOMAIN=${ctx.domain}`)),
2814
+ body: b64text('ok'),
2815
+ }),
2816
+ },
2817
+ {
2818
+ label: 'domainTrailDot',
2819
+ value: v('dtd'),
2820
+ build: () =>
2821
+ fetchFulfill({
2822
+ responseHeaders: set('Set-Cookie', header(v('dtd'), ctx.domain, `Domain=${bareDomain}.`)),
2823
+ body: b64text('ok'),
2824
+ }),
2825
+ },
2826
+ {
2827
+ label: 'domainRepeated',
2828
+ value: v('dr'),
2829
+ build: () =>
2830
+ fetchFulfill({
2831
+ responseHeaders: set(
2832
+ 'Set-Cookie',
2833
+ `${ctx.names.plant}=${v('dr')}; Domain=example.invalid; Domain=${ctx.domain}; Path=/`
2834
+ ),
2835
+ body: b64text('ok'),
2836
+ }),
2837
+ },
2838
+ {
2839
+ label: 'domainWs',
2840
+ value: v('dws'),
2841
+ build: () =>
2842
+ fetchFulfill({
2843
+ responseHeaders: set(
2844
+ 'Set-Cookie',
2845
+ header(v('dws'), ctx.domain, `Domain = ${ctx.domain}`)
2846
+ ),
2847
+ body: b64text('ok'),
2848
+ }),
2849
+ },
2850
+ {
2851
+ label: 'headerPadded',
2852
+ value: v('hp'),
2853
+ build: () =>
2854
+ fetchFulfill({
2855
+ responseHeaders: set('Set-Cookie\t', header(v('hp'))),
2856
+ body: b64text('ok'),
2857
+ }),
2858
+ },
2859
+ {
2860
+ label: 'setCookieSecond',
2861
+ value: v('sc2nd'),
2862
+ build: () =>
2863
+ fetchFulfill({
2864
+ responseHeaders: [
2865
+ { name: 'content-type', value: 'text/plain' },
2866
+ { name: 'X-Other', value: '1' },
2867
+ { name: 'Set-Cookie', value: header(v('sc2nd')) },
2868
+ ],
2869
+ body: b64text('ok'),
2870
+ }),
2871
+ },
2872
+ {
2873
+ label: 'responsePhrase',
2874
+ value: v('rp'),
2875
+ build: () =>
2876
+ fetchFulfill({
2877
+ responseCode: 200,
2878
+ responsePhrase: `OK\r\nSet-Cookie: ${header(v('rp'))}`,
2879
+ responseHeaders: [{ name: 'content-type', value: 'text/plain' }],
2880
+ body: b64text('ok'),
2881
+ }),
2882
+ },
2883
+ {
2884
+ label: 'continueAtRequest',
2885
+ value: v('car'),
2886
+ stage: 'Request',
2887
+ build: () =>
2888
+ fetchContinueResponse({
2889
+ responseCode: 200,
2890
+ responseHeaders: set('Set-Cookie', header(v('car'))),
2891
+ }),
2892
+ },
2893
+ ];
2894
+ }
2895
+
2896
+ function doorAbsentOf(raw) {
2897
+ if (raw?.observed !== true || raw?.incomplete) return false;
2898
+ return raw.doorPresent === false;
2899
+ }
2900
+
2901
+ function noteRawDoor(notes, label, raw, text, handle = null, pathStartedAt = null) {
2902
+ note(notes, `cookie-plant.raw.${label}`, {
2903
+ ...raw,
2904
+ ...timingOf(handle, pathStartedAt),
2905
+ note: text,
2906
+ });
2907
+ return raw;
2908
+ }
2909
+
2910
+ function forcedRawDoor(forced, notes, label) {
2911
+ const pathStartedAt = Date.now();
2912
+ if (forced === 'timeout') {
2913
+ return noteRawDoor(
2914
+ notes,
2915
+ label,
2916
+ {
2917
+ observed: true,
2918
+ answered: false,
2919
+ planted: false,
2920
+ timedOut: true,
2921
+ doorPresent: false,
2922
+ },
2923
+ 'door not present on this browser',
2924
+ null,
2925
+ pathStartedAt
2926
+ );
2927
+ }
2928
+ if (forced === 'plant') {
2929
+ return noteRawDoor(
2930
+ notes,
2931
+ label,
2932
+ {
2933
+ observed: true,
2934
+ answered: true,
2935
+ planted: true,
2936
+ timedOut: false,
2937
+ doorPresent: true,
2938
+ },
2939
+ 'raw leg planted: plant path',
2940
+ null,
2941
+ pathStartedAt
2942
+ );
2943
+ }
2944
+ const incompleteBy = {
2945
+ unreadable: 'cookie jar unreadable',
2946
+ 'open-fail': 'raw open failed',
2947
+ 'enable-fail': 'raw Fetch.enable failed',
2948
+ 'no-pause': 'raw leg: no pause',
2949
+ missing: 'raw leg missing',
2950
+ };
2951
+ if (!Object.hasOwn(incompleteBy, forced)) return null;
2952
+ return noteRawDoor(
2953
+ notes,
2954
+ label,
2955
+ {
2956
+ observed: false,
2957
+ answered: false,
2958
+ planted: false,
2959
+ timedOut: false,
2960
+ doorPresent: false,
2961
+ incomplete: incompleteBy[forced],
2962
+ },
2963
+ 'raw leg incomplete',
2964
+ null,
2965
+ pathStartedAt
2966
+ );
2967
+ }
2968
+
2969
+ function incompleteRaw(incomplete) {
2970
+ return {
2971
+ observed: false,
2972
+ answered: false,
2973
+ planted: false,
2974
+ timedOut: false,
2975
+ doorPresent: false,
2976
+ incomplete,
2977
+ };
2978
+ }
2979
+
2980
+ async function observeRawPlantSend({
2981
+ reader,
2982
+ sessionId,
2983
+ cookie,
2984
+ plantUrl,
2985
+ budget,
2986
+ from,
2987
+ spec,
2988
+ notes,
2989
+ label,
2990
+ triggerHolder,
2991
+ handle,
2992
+ pathStartedAt,
2993
+ browserContextId,
2994
+ canary,
2995
+ }) {
2996
+ const jarHandle = {
2997
+ reader,
2998
+ readerSession: sessionId,
2999
+ browserContextId,
3000
+ browserContexts: Boolean(handle?.browserContexts),
3001
+ canary,
3002
+ };
3003
+ requireAttemptHandle(jarHandle, 'observeRawPlantSend');
3004
+ if (!canary) throw new Error('cookie-plant.observeRawPlantSend: canary required');
3005
+ if (jarContextIncomplete(jarHandle))
3006
+ return noteRawDoor(
3007
+ notes,
3008
+ label,
3009
+ { ...incompleteRaw('unknown context'), browserContextId },
3010
+ 'unknown context',
3011
+ handle,
3012
+ pathStartedAt
3013
+ );
3014
+ await capped(clearCookie(jarHandle, cookie), 800, 'raw-clear');
3015
+ await plantCanary(jarHandle);
3016
+ const enabled = await capped(
3017
+ outcome(
3018
+ reader.send(
3019
+ 'Fetch.enable',
3020
+ {
3021
+ patterns: [
3022
+ { urlPattern: '*', requestStage: 'Request' },
3023
+ { urlPattern: '*', requestStage: 'Response' },
3024
+ ],
3025
+ },
3026
+ sessionId
3027
+ )
3028
+ ),
3029
+ 800,
3030
+ 'raw-enable'
3031
+ );
3032
+ if (!enabled.ok) {
3033
+ return noteRawDoor(
3034
+ notes,
3035
+ label,
3036
+ {
3037
+ ...incompleteRaw(String(enabled.error?.message ?? 'raw Fetch.enable failed')),
3038
+ browserContextId,
3039
+ },
3040
+ 'raw leg incomplete',
3041
+ handle,
3042
+ pathStartedAt
3043
+ );
3044
+ }
3045
+ triggerHolder.promise = triggerNavigate(reader, sessionId, plantUrl);
3046
+ triggerHolder.paused = await waitPause(
3047
+ reader,
3048
+ from,
3049
+ plantUrl,
3050
+ ['Fetch.requestPaused'],
3051
+ Math.min(budget, 2000)
3052
+ );
3053
+ if (!triggerHolder.paused) {
3054
+ return noteRawDoor(
3055
+ notes,
3056
+ label,
3057
+ { ...incompleteRaw('raw leg: no pause'), browserContextId },
3058
+ 'raw leg incomplete',
3059
+ handle,
3060
+ pathStartedAt
3061
+ );
3062
+ }
3063
+ const out = await capped(
3064
+ spec.build(triggerHolder.paused).send(reader, triggerHolder.paused),
3065
+ Math.min(budget, 1500),
3066
+ 'raw-plant-send'
3067
+ );
3068
+ const timedOut = Boolean(out?.error?.message && /timeout/i.test(String(out.error.message)));
3069
+ if (refused(out) || !out.ok) await releasePause(reader, triggerHolder.paused);
3070
+ await settleTrigger(triggerHolder.promise, Math.min(budget, 500));
3071
+ const jar = await capped(readJarWithCanary(jarHandle, cookie), 1500, 'raw-jar');
3072
+ if (
3073
+ jar?.error?.message?.includes('timeout') ||
3074
+ jar?.incomplete ||
3075
+ plantedOf(jar) === 'incomplete'
3076
+ ) {
3077
+ return noteRawDoor(
3078
+ notes,
3079
+ label,
3080
+ {
3081
+ observed: true,
3082
+ answered: answered(out),
3083
+ planted: false,
3084
+ timedOut,
3085
+ doorPresent: false,
3086
+ incomplete: jar?.canaryMissing ? 'jar view canary absent' : 'cookie jar unreadable',
3087
+ ...jarAuditFields(jarHandle, jar),
3088
+ },
3089
+ 'raw leg incomplete',
3090
+ handle,
3091
+ pathStartedAt
3092
+ );
3093
+ }
3094
+ const planted = plantedOf(jar) === true;
3095
+ const answeredOk = answered(out);
3096
+ const doorPresent = answeredOk === true && planted;
3097
+ const raw = {
3098
+ observed: true,
3099
+ answered: answeredOk,
3100
+ planted,
3101
+ timedOut,
3102
+ doorPresent,
3103
+ browserContextId,
3104
+ };
3105
+ const audited = { ...raw, ...jarAuditFields(jarHandle, jar) };
3106
+ noteRawDoor(
3107
+ notes,
3108
+ label,
3109
+ audited,
3110
+ doorPresent ? 'raw leg planted: plant path' : 'door not present on this browser',
3111
+ handle,
3112
+ pathStartedAt
3113
+ );
3114
+ await capped(clearCookie(jarHandle, cookie), 800, 'raw-clear');
3115
+ return audited;
3116
+ }
3117
+
3118
+ async function measureRawDoor(ctx, spec) {
3119
+ const {
3120
+ reader,
3121
+ homeUrl,
3122
+ notes,
3123
+ internalSessions,
3124
+ budget,
3125
+ plantUrl,
3126
+ plantCookie,
3127
+ forcedRaw,
3128
+ browserContextId = null,
3129
+ } = ctx;
3130
+ const forced = forcedRawDoor(forcedRaw?.[spec.label], notes, spec.label);
3131
+ if (forced) return forced;
3132
+ const pathStartedAt = Date.now();
3133
+ const timing = { pathStartedAt };
3134
+ const timedReader = timedClient(reader, timing);
3135
+ const handle = { timing };
3136
+ const page = await openPage(timedReader, homeUrl, notes, internalSessions, browserContextId);
3137
+ if (!page.ok || page.result?.incomplete) {
3138
+ return noteRawDoor(
3139
+ notes,
3140
+ spec.label,
3141
+ incompleteRaw(page.result?.incomplete ?? page.error?.message ?? 'raw open failed'),
3142
+ 'raw leg incomplete',
3143
+ handle,
3144
+ pathStartedAt
3145
+ );
3146
+ }
3147
+ const sessionId = page.result.sessionId;
3148
+ const targetId = page.result.targetId;
3149
+ const tabContextId = await resolveTabContextId(timedReader, targetId, browserContextId ?? null);
3150
+ if (ctx.browserContexts && (tabContextId == null || tabContextId === '')) {
3151
+ await outcome(timedReader.send('Target.closeTarget', { targetId }));
3152
+ return noteRawDoor(
3153
+ notes,
3154
+ spec.label,
3155
+ incompleteRaw('unknown context'),
3156
+ 'unknown context',
3157
+ handle,
3158
+ pathStartedAt
3159
+ );
3160
+ }
3161
+ const canary = canarySpec({ tag: ctx.tag, homeUrl });
3162
+ const cookie = { ...plantCookie, value: spec.value };
3163
+ const triggerHolder = { paused: null, promise: Promise.resolve() };
3164
+ const from = timedReader.events.length;
3165
+ handle.browserContexts = Boolean(ctx.browserContexts);
3166
+ handle.browserContextId = tabContextId;
3167
+ try {
3168
+ return await withPathBudget(
3169
+ observeRawPlantSend({
3170
+ reader: timedReader,
3171
+ sessionId,
3172
+ cookie,
3173
+ plantUrl,
3174
+ budget,
3175
+ from,
3176
+ spec,
3177
+ notes,
3178
+ label: spec.label,
3179
+ triggerHolder,
3180
+ handle,
3181
+ pathStartedAt,
3182
+ browserContextId: tabContextId,
3183
+ canary,
3184
+ }),
3185
+ pathCeiling(budget),
3186
+ `raw:${spec.label}`
3187
+ );
3188
+ } catch (error) {
3189
+ return noteRawDoor(
3190
+ notes,
3191
+ spec.label,
3192
+ {
3193
+ ...incompleteRaw(String(error?.message ?? error)),
3194
+ timedOut: /timeout/i.test(String(error?.message ?? error)),
3195
+ },
3196
+ 'raw leg incomplete',
3197
+ handle,
3198
+ pathStartedAt
3199
+ );
3200
+ } finally {
3201
+ try {
3202
+ await releasePause(timedReader, triggerHolder.paused);
3203
+ await drainPauses(timedReader, from);
3204
+ await settleTrigger(triggerHolder.promise, Math.min(budget, 500));
3205
+ await capped(
3206
+ disableInterception(timedReader, sessionId, { fetch: true, legacy: false }),
3207
+ 800,
3208
+ 'raw-disable'
3209
+ );
3210
+ await capped(outcome(timedReader.send('Target.closeTarget', { targetId })), 800, 'raw-close');
3211
+ } catch {
3212
+ await outcome(timedReader.send('Target.closeTarget', { targetId })).catch(() => {});
3213
+ }
3214
+ }
3215
+ }
3216
+
3217
+ function fetchAttacks(ctx) {
3218
+ if (!ctx.transport?.fetch) return null;
3219
+ const header = (value, domain = ctx.domain, domainAttr = null) =>
3220
+ cookieHeader(ctx.names.plant, value, domain, '', domainAttr);
3221
+ const bareDomain = ctx.domain.replace(/^\./, '');
3222
+ const out = {};
3223
+ for (const spec of fetchAttackSpecs(ctx, header, bareDomain)) {
3224
+ out[spec.label] = () =>
3225
+ (async () => {
3226
+ let rawDoor = ctx.rawDoors?.[spec.label] ?? null;
3227
+ if (ctx.guardedProtected && !rawDoor) {
3228
+ rawDoor = await measureRawDoor(ctx, spec);
3229
+ ctx.rawDoors = { ...(ctx.rawDoors ?? {}), [spec.label]: rawDoor };
3230
+ }
3231
+ return withFreshAttemptTab(ctx, (handle) =>
3232
+ runPlant({
3233
+ handle,
3234
+ url: ctx.plantUrl,
3235
+ budget: ctx.budget,
3236
+ notes: ctx.notes,
3237
+ topLevel: true,
3238
+ fixtureLog: ctx.fixtureLog,
3239
+ legStartedAt: ctx.legStartedAt,
3240
+ firstIncomplete: ctx.firstIncomplete,
3241
+ protectedBlock: Boolean(ctx.guardedProtected),
3242
+ tag: ctx.tag,
3243
+ blockedMarkers: ctx.blockedMarkers,
3244
+ proofTag: ctx.proofTag,
3245
+ cookie: { ...ctx.plantCookie, value: spec.value },
3246
+ label: spec.label,
3247
+ stage: spec.stage ?? 'Request',
3248
+ build: spec.build,
3249
+ rawDoor,
3250
+ })
3251
+ );
3252
+ })();
3253
+ }
3254
+ return out;
3255
+ }
3256
+
3257
+ async function withLegacyOnly(handle, transport, run) {
3258
+ const session = () => handle.pageSession;
3259
+ if (transport.fetch) await outcome(handle.client.send('Fetch.disable', {}, session()));
3260
+ await enableLegacy(handle.client, session());
3261
+ try {
3262
+ return await run();
3263
+ } finally {
3264
+ if (transport.fetch) {
3265
+ await outcome(
3266
+ handle.client.send(
3267
+ 'Fetch.enable',
3268
+ {
3269
+ patterns: [
3270
+ { urlPattern: '*', requestStage: 'Request' },
3271
+ { urlPattern: '*', requestStage: 'Response' },
3272
+ ],
3273
+ },
3274
+ session()
3275
+ )
3276
+ );
3277
+ }
3278
+ }
3279
+ }
3280
+
3281
+ function legacyAttacks(ctx, legacyReady) {
3282
+ if (!legacyReady) return null;
3283
+ const legacyTransport = { kind: 'legacy', fetch: false, legacy: true };
3284
+ const runLegacy = (label, value) => () =>
3285
+ withFreshAttemptTab(ctx, (handle) =>
3286
+ withLegacyOnly(handle, handle.transport, () => {
3287
+ const prior = handle.transport;
3288
+ handle.transport = legacyTransport;
3289
+ return runPlant({
3290
+ handle,
3291
+ url: ctx.plantUrl,
3292
+ budget: ctx.budget,
3293
+ notes: ctx.notes,
3294
+ topLevel: true,
3295
+ fixtureLog: ctx.fixtureLog,
3296
+ legStartedAt: ctx.legStartedAt,
3297
+ firstIncomplete: ctx.firstIncomplete,
3298
+ protectedBlock: Boolean(ctx.guardedProtected),
3299
+ tag: ctx.tag,
3300
+ blockedMarkers: ctx.blockedMarkers,
3301
+ proofTag: ctx.proofTag,
3302
+ cookie: { ...ctx.plantCookie, value },
3303
+ label,
3304
+ build: () =>
3305
+ legacyContinue({
3306
+ rawResponse: rawHttpResponse({
3307
+ code: 200,
3308
+ phrase: 'OK',
3309
+ headers: [
3310
+ { name: 'content-type', value: 'text/plain' },
3311
+ {
3312
+ name: 'Set-Cookie',
3313
+ value: cookieHeader(ctx.names.plant, value, ctx.domain),
3314
+ },
3315
+ ],
3316
+ body: 'ok',
3317
+ }),
3318
+ }),
3319
+ }).finally(() => {
3320
+ handle.transport = prior;
3321
+ });
3322
+ })
3323
+ );
3324
+ return {
3325
+ legacyHeaders: runLegacy('legacyHeaders', `lh-${ctx.tag}`),
3326
+ legacyRaw: runLegacy('legacyRaw', `lr-${ctx.tag}`),
3327
+ };
3328
+ }
3329
+
3330
+ async function allowedHeaderAttempt({
3331
+ handle,
3332
+ url,
3333
+ budget,
3334
+ notes,
3335
+ label,
3336
+ header,
3337
+ cookie,
3338
+ fetchReady,
3339
+ topLevel = false,
3340
+ fixtureLog,
3341
+ legStartedAt,
3342
+ firstIncomplete,
3343
+ }) {
3344
+ const { client, transport } = handle;
3345
+ let pageSession = handle.pageSession;
3346
+ let paused = null;
3347
+ let triggerPromise = Promise.resolve();
3348
+ const from = client.events.length;
3349
+ const pauseMs = Math.min(budget, 2000);
3350
+ const startedAt = Date.now();
3351
+ const legAt = legStartedAt ?? startedAt;
3352
+ const finish = (out) =>
3353
+ cookie
3354
+ ? finishPlant({ out, cookie, notes, label, handle })
3355
+ : (() => {
3356
+ note(notes, `cookie-plant.${label}`, {
3357
+ answered: answered(out),
3358
+ refused: refused(out),
3359
+ });
3360
+ return {
3361
+ answered: answered(out) ? true : 'incomplete',
3362
+ refused: answered(out) ? refused(out) : 'incomplete',
3363
+ planted: false,
3364
+ };
3365
+ })();
3366
+ try {
3367
+ return await withPathBudget(
3368
+ (async () => {
3369
+ const ensure = await ensureInterceptionLive(handle);
3370
+ pageSession = handle.pageSession;
3371
+ if (sessionCut(ensure))
3372
+ return cookie
3373
+ ? recordSessionCut({ handle, cookie, notes, label })
3374
+ : finish({
3375
+ ok: false,
3376
+ error: { message: 'slicc: refused: session cut on protected execution context' },
3377
+ });
3378
+ if (!ensure.ok) {
3379
+ await diagnoseIncomplete({
3380
+ notes,
3381
+ label,
3382
+ incomplete: String(ensure.error?.message ?? 'ensure failed'),
3383
+ url,
3384
+ client,
3385
+ pageSession,
3386
+ from,
3387
+ methods:
3388
+ transport.kind === 'legacy'
3389
+ ? ['Network.requestIntercepted']
3390
+ : ['Fetch.requestPaused'],
3391
+ pauseMs,
3392
+ startedAt,
3393
+ legStartedAt: legAt,
3394
+ fixtureLog,
3395
+ ensure,
3396
+ trigger: null,
3397
+ firstIncomplete,
3398
+ });
3399
+ return attemptRecord(
3400
+ { ok: false, error: ensure.error ?? { message: 'ensure failed' } },
3401
+ 'incomplete'
3402
+ );
3403
+ }
3404
+ const methods =
3405
+ transport.kind === 'legacy' ? ['Network.requestIntercepted'] : ['Fetch.requestPaused'];
3406
+ triggerPromise = topLevel
3407
+ ? triggerNavigate(client, pageSession, url)
3408
+ : triggerFetch(client, pageSession, url);
3409
+ paused = await waitPause(client, from, url, methods, pauseMs);
3410
+ if (!paused) {
3411
+ const trigger = await settleTrigger(triggerPromise, Math.min(budget, 500));
3412
+ triggerPromise = Promise.resolve(trigger);
3413
+ await diagnoseIncomplete({
3414
+ notes,
3415
+ label,
3416
+ incomplete: 'no pause',
3417
+ url,
3418
+ client,
3419
+ pageSession,
3420
+ from,
3421
+ methods,
3422
+ pauseMs,
3423
+ startedAt,
3424
+ legStartedAt: legAt,
3425
+ fixtureLog,
3426
+ ensure,
3427
+ trigger,
3428
+ firstIncomplete,
3429
+ });
3430
+ return attemptRecord(
3431
+ { ok: false, error: { message: 'timeout: no pause' } },
3432
+ 'incomplete'
3433
+ );
3434
+ }
3435
+ const out = await capped(
3436
+ fetchReady
3437
+ ? fetchFulfill({
3438
+ responseHeaders: [
3439
+ { name: 'content-type', value: 'text/plain' },
3440
+ { name: 'Set-Cookie', value: header },
3441
+ ],
3442
+ body: b64text('ok'),
3443
+ }).send(client, paused)
3444
+ : legacyContinue({
3445
+ rawResponse: rawHttpResponse({
3446
+ code: 200,
3447
+ phrase: 'OK',
3448
+ headers: [{ name: 'Set-Cookie', value: header }],
3449
+ body: 'ok',
3450
+ }),
3451
+ }).send(client, paused),
3452
+ 1500,
3453
+ 'allowed-send'
3454
+ );
3455
+ if (sessionCut(out))
3456
+ return cookie ? recordSessionCut({ handle, cookie, notes, label }) : finish(out);
3457
+ return finish(out);
3458
+ })(),
3459
+ pathCeiling(budget),
3460
+ label
3461
+ );
3462
+ } catch (error) {
3463
+ if (sessionCut({ ok: false, error }))
3464
+ return cookie
3465
+ ? recordSessionCut({ handle, cookie, notes, label })
3466
+ : finish({
3467
+ ok: false,
3468
+ error: { message: 'slicc: refused: session cut on protected execution context' },
3469
+ });
3470
+ note(notes, `cookie-plant.${label}`, { incomplete: String(error?.message ?? error) });
3471
+ return attemptRecord(
3472
+ { ok: false, error: { message: String(error?.message ?? error) } },
3473
+ 'incomplete'
3474
+ );
3475
+ } finally {
3476
+ try {
3477
+ await withPathBudget(
3478
+ cleanupPath({
3479
+ handle,
3480
+ paused,
3481
+ from,
3482
+ triggerPromise,
3483
+ budget,
3484
+ }),
3485
+ cleanupCeiling(budget),
3486
+ `${label}:cleanup`
3487
+ );
3488
+ } catch (error) {
3489
+ note(notes, `cookie-plant.${label}`, {
3490
+ cleanup: String(error?.message ?? error),
3491
+ });
3492
+ }
3493
+ }
3494
+ }
3495
+
3496
+ function seedProof(jar, cookie) {
3497
+ if (plantedOf(jar) !== true || !jar?.cookie) return false;
3498
+ const got = jar.cookie;
3499
+ if (got.name !== cookie.name) return false;
3500
+ if (got.domain.replace(/^\./, '') !== String(cookie.domain ?? '').replace(/^\./, ''))
3501
+ return false;
3502
+ if ((got.path ?? '/') !== (cookie.path ?? '/')) return false;
3503
+ if (cookie.value !== undefined && got.value !== cookie.value) return false;
3504
+ return true;
3505
+ }
3506
+
3507
+ async function seedCookie(handle, cookie) {
3508
+ requireAttemptHandle(handle, 'seedCookie');
3509
+ const unknown = jarContextIncomplete(handle);
3510
+ if (unknown) return unknown;
3511
+ const path = cookie.path ?? '/';
3512
+ await clearCookie(handle, { ...cookie, path });
3513
+ const all = await outcome(
3514
+ handle.reader.send('Storage.getCookies', storageContextParams(handle.browserContextId))
3515
+ );
3516
+ const rest = (all.result?.cookies ?? []).filter(
3517
+ (entry) =>
3518
+ !(
3519
+ entry.name === cookie.name &&
3520
+ entry.domain.replace(/^\./, '') === cookie.domain.replace(/^\./, '') &&
3521
+ (entry.path ?? '/') === path
3522
+ )
3523
+ );
3524
+ const seeded = cookie.url
3525
+ ? { name: cookie.name, value: cookie.value, url: cookie.url, path }
3526
+ : { name: cookie.name, value: cookie.value, domain: cookie.domain, path };
3527
+ await outcome(
3528
+ handle.reader.send('Storage.setCookies', {
3529
+ ...storageContextParams(handle.browserContextId),
3530
+ cookies: [...rest, seeded],
3531
+ })
3532
+ );
3533
+ return readJar(handle, {
3534
+ name: cookie.name,
3535
+ domain: cookie.domain,
3536
+ value: cookie.value,
3537
+ path,
3538
+ });
3539
+ }
3540
+
3541
+ function controlAttacks(ctx) {
3542
+ const ordinaryCookie = {
3543
+ name: ctx.names.ordinary,
3544
+ value: `o-${ctx.tag}`,
3545
+ domain: hostOf(ctx.ordinary),
3546
+ url: `${ctx.ordinary}/`,
3547
+ };
3548
+ const ordinaryUrl = `${ctx.ordinary}/data?n=ctrl-${ctx.tag}`;
3549
+ const diag = (handle) => ({
3550
+ handle,
3551
+ budget: ctx.budget,
3552
+ notes: ctx.notes,
3553
+ fixtureLog: ctx.fixtureLog,
3554
+ legStartedAt: ctx.legStartedAt,
3555
+ firstIncomplete: ctx.firstIncomplete,
3556
+ });
3557
+ return {
3558
+ ordinary: () =>
3559
+ withFreshAttemptTab(ctx, (handle) => {
3560
+ const fetchReady = Boolean(handle.transport?.fetch);
3561
+ return runPlant({
3562
+ ...diag(handle),
3563
+ url: ordinaryUrl,
3564
+ cookie: ordinaryCookie,
3565
+ label: 'ordinary',
3566
+ topLevel: false,
3567
+ build: () =>
3568
+ fetchReady
3569
+ ? fetchFulfill({
3570
+ responseHeaders: [
3571
+ { name: 'content-type', value: 'text/plain' },
3572
+ {
3573
+ name: 'Set-Cookie',
3574
+ value: cookieHeader(ctx.names.ordinary, ordinaryCookie.value, null),
3575
+ },
3576
+ ],
3577
+ body: b64text('ok'),
3578
+ })
3579
+ : legacyContinue({
3580
+ rawResponse: rawHttpResponse({
3581
+ code: 200,
3582
+ phrase: 'OK',
3583
+ headers: [
3584
+ { name: 'content-type', value: 'text/plain' },
3585
+ {
3586
+ name: 'Set-Cookie',
3587
+ value: cookieHeader(ctx.names.ordinary, ordinaryCookie.value, null),
3588
+ },
3589
+ ],
3590
+ body: 'ok',
3591
+ }),
3592
+ }),
3593
+ });
3594
+ }),
3595
+ adobe: () =>
3596
+ withFreshAttemptTab(ctx, (handle) => {
3597
+ const fetchReady = Boolean(handle.transport?.fetch);
3598
+ const adobeOrigin =
3599
+ fixtureOriginFor(ctx.ordinary, 'www.adobe.com') ?? 'https://www.adobe.com';
3600
+ const adobeCookie = {
3601
+ name: ctx.names.adobe,
3602
+ value: `a-${ctx.tag}`,
3603
+ domain: '.adobe.com',
3604
+ url: `${adobeOrigin}/`,
3605
+ };
3606
+ return allowedHeaderAttempt({
3607
+ ...diag(handle),
3608
+ url: `${adobeOrigin}/data?n=adobe-${ctx.tag}`,
3609
+ label: 'adobe',
3610
+ header: cookieHeader(ctx.names.adobe, adobeCookie.value, '.adobe.com'),
3611
+ cookie: adobeCookie,
3612
+ fetchReady,
3613
+ topLevel: true,
3614
+ });
3615
+ }),
3616
+ deletion: () =>
3617
+ withFreshAttemptTab(ctx, async (handle) => {
3618
+ const fetchReady = Boolean(handle.transport?.fetch);
3619
+ const browserContextId = handle.browserContextId ?? null;
3620
+ const deleteOnOrdinary = {
3621
+ name: ctx.names.delete,
3622
+ value: `seed-${ctx.tag}`,
3623
+ domain: hostOf(ctx.ordinary),
3624
+ path: '/',
3625
+ url: `${ctx.ordinary}/`,
3626
+ };
3627
+ const incompleteDeletion = (reason) => {
3628
+ note(ctx.notes, 'cookie-plant.deletion', {
3629
+ incomplete: reason,
3630
+ browserContextId,
3631
+ ...timingOf(handle),
3632
+ });
3633
+ return {
3634
+ answered: 'incomplete',
3635
+ refused: 'incomplete',
3636
+ planted: 'incomplete',
3637
+ cleared: 'incomplete',
3638
+ };
3639
+ };
3640
+ const seeded = await seedCookie(handle, deleteOnOrdinary);
3641
+ if (!seedProof(seeded, deleteOnOrdinary))
3642
+ return incompleteDeletion(
3643
+ seeded?.incomplete ? 'seed jar unreadable' : 'seed missing exact name+domain+path'
3644
+ );
3645
+ const seedJar = await capped(readJarWithCanary(handle, deleteOnOrdinary), 1500, 'readJar');
3646
+ note(ctx.notes, 'cookie-plant.deletion.seed', {
3647
+ seeded: true,
3648
+ ...jarAuditFields(handle, seedJar),
3649
+ ...timingOf(handle),
3650
+ });
3651
+ const attempt = await allowedHeaderAttempt({
3652
+ ...diag(handle),
3653
+ url: ordinaryUrl,
3654
+ label: 'deletion',
3655
+ header: cookieHeader(ctx.names.delete, '', null, 'Max-Age=0'),
3656
+ cookie: deleteOnOrdinary,
3657
+ fetchReady,
3658
+ topLevel: false,
3659
+ });
3660
+ if (attempt.answered === 'incomplete' || attempt.planted === 'incomplete') {
3661
+ note(ctx.notes, 'cookie-plant.deletion.cleared', {
3662
+ cleared: 'incomplete',
3663
+ incomplete: 'delete attempt incomplete',
3664
+ jarRead: false,
3665
+ browserContextId,
3666
+ ...timingOf(handle),
3667
+ });
3668
+ return { ...attempt, cleared: 'incomplete' };
3669
+ }
3670
+ const after = await readJarWithCanary(handle, {
3671
+ name: ctx.names.delete,
3672
+ domain: deleteOnOrdinary.domain,
3673
+ path: deleteOnOrdinary.path,
3674
+ });
3675
+ const afterPlanted = plantedOf(after);
3676
+ if (afterPlanted === 'incomplete') {
3677
+ note(ctx.notes, 'cookie-plant.deletion.cleared', {
3678
+ cleared: 'incomplete',
3679
+ incomplete: 'after jar unreadable',
3680
+ ...jarAuditFields(handle, after),
3681
+ ...timingOf(handle),
3682
+ });
3683
+ return { ...attempt, cleared: 'incomplete' };
3684
+ }
3685
+ const cleared = afterPlanted === false;
3686
+ note(ctx.notes, 'cookie-plant.deletion.cleared', {
3687
+ cleared,
3688
+ seedVia: seeded?.via,
3689
+ ...jarAuditFields(handle, after),
3690
+ ...timingOf(handle),
3691
+ });
3692
+ return { ...attempt, cleared };
3693
+ }),
3694
+ };
3695
+ }
3696
+
3697
+ function fillMissingAttempts(results, legacyReady) {
3698
+ for (const name of ALL_PATH_NAMES) {
3699
+ if (results[name]) continue;
3700
+ if (!legacyReady && (name === 'legacyHeaders' || name === 'legacyRaw'))
3701
+ results[name] = notSupportedAttempt();
3702
+ else if (CREDENTIAL_PATH_NAMES.includes(name)) results[name] = notSupportedAttempt();
3703
+ else results[name] = EMPTY_ATTEMPT;
3704
+ }
3705
+ }
3706
+
3707
+ async function runOneAttempt(name, run, ceiling, legacyReady, results, ran) {
3708
+ if (!legacyReady && (name === 'legacyHeaders' || name === 'legacyRaw')) {
3709
+ results[name] = notSupportedAttempt();
3710
+ ran.add(name);
3711
+ return;
3712
+ }
3713
+ try {
3714
+ results[name] = await withPathBudget(run(), ceiling, name);
3715
+ } catch (error) {
3716
+ results[name] = attemptRecord(
3717
+ { ok: false, error: { message: String(error?.message ?? error) } },
3718
+ 'incomplete'
3719
+ );
3720
+ }
3721
+ ran.add(name);
3722
+ }
3723
+
3724
+ async function runAttempts(groups, budget = 5000, onlyPaths = null, legacyReady = true) {
3725
+ const results = {};
3726
+ const ran = new Set();
3727
+ const ceiling = pathCeiling(budget) + cleanupCeiling(budget) + Math.min(budget, 500);
3728
+ const allow =
3729
+ Array.isArray(onlyPaths) && onlyPaths.length ? new Set(onlyPaths.map(String)) : null;
3730
+ for (const group of groups) {
3731
+ for (const [name, run] of Object.entries(group ?? {})) {
3732
+ if (allow && !allow.has(name)) continue;
3733
+ await runOneAttempt(name, run, ceiling, legacyReady, results, ran);
3734
+ }
3735
+ }
3736
+ fillMissingAttempts(results, legacyReady);
3737
+ return { results, ran };
3738
+ }
3739
+
3740
+ async function attachClientPage(client, pageTarget, internalSessions) {
3741
+ const attached = await capped(
3742
+ outcome(client.send('Target.attachToTarget', { targetId: pageTarget, flatten: true })),
3743
+ 800,
3744
+ 'attachToTarget'
3745
+ );
3746
+ if (!attached.ok) {
3747
+ if (sessionCut(attached) || refused(attached)) return { refused: attached, pageSession: null };
3748
+ return {
3749
+ incomplete: `client attach failed: ${attached.error?.message ?? attached.error}`,
3750
+ };
3751
+ }
3752
+ const pageSession = attached.result?.sessionId;
3753
+ if (pageSession) {
3754
+ internalSessions.add(pageSession);
3755
+ for (const [method, label] of [
3756
+ ['Page.enable', 'Page.enable'],
3757
+ ['Runtime.enable', 'Runtime.enable'],
3758
+ ['Network.enable', 'Network.enable'],
3759
+ ]) {
3760
+ const enabled = await capped(outcome(client.send(method, {}, pageSession)), 800, label);
3761
+ if (!enabled.ok) {
3762
+ if (sessionCut(enabled) || refused(enabled)) return { refused: enabled, pageSession };
3763
+ return {
3764
+ incomplete: `client ${label} failed: ${enabled.error?.message ?? enabled.error}`,
3765
+ };
3766
+ }
3767
+ }
3768
+ }
3769
+ return { pageSession };
3770
+ }
3771
+
3772
+ async function enableClientTransport(client, pageSession, notes) {
3773
+ const transport = await detectTransport(client, pageSession, notes);
3774
+ if (!transport.kind)
3775
+ return {
3776
+ incomplete:
3777
+ 'neither Fetch.enable nor Network.setRequestInterception is available on the guarded client',
3778
+ };
3779
+ let fetchEnable = transport.fetchEnable ?? null;
3780
+ if (transport.fetch && refused(fetchEnable))
3781
+ return { transport, legacyReady: false, fetchEnable };
3782
+ if (transport.fetch && fetchEnable && !fetchEnable.ok)
3783
+ return { transport, legacyReady: false, fetchEnable };
3784
+ let legacyReady = transport.legacy;
3785
+ if (!legacyReady && transport.fetch && fetchEnable?.ok) {
3786
+ await outcome(client.send('Fetch.disable', {}, pageSession));
3787
+ const legacy = await enableLegacy(client, pageSession);
3788
+ legacyReady = legacy.ok;
3789
+ if (legacyReady) {
3790
+ transport.legacy = true;
3791
+ await outcome(client.send('Network.setRequestInterception', { patterns: [] }, pageSession));
3792
+ }
3793
+ fetchEnable = await capped(
3794
+ outcome(
3795
+ client.send(
3796
+ 'Fetch.enable',
3797
+ {
3798
+ patterns: [
3799
+ { urlPattern: '*', requestStage: 'Request' },
3800
+ { urlPattern: '*', requestStage: 'Response' },
3801
+ ],
3802
+ },
3803
+ pageSession
3804
+ )
3805
+ ),
3806
+ 800,
3807
+ 'Fetch.enable'
3808
+ );
3809
+ if (refused(fetchEnable)) return { transport, legacyReady, fetchEnable };
3810
+ if (!fetchEnable.ok) return { transport, legacyReady, fetchEnable };
3811
+ if (legacyReady) note(notes, 'cookie-plant.legacyProbe', { ready: true });
3812
+ else
3813
+ note(notes, 'cookie-plant.legacyProbe', {
3814
+ ready: false,
3815
+ note: 'legacy unsupported in this Chrome',
3816
+ });
3817
+ }
3818
+ return { transport, legacyReady, fetchEnable };
3819
+ }
3820
+
3821
+ function credentialAttacks(ctx) {
3822
+ if (!ctx.credential) return null;
3823
+ const hostOnlyUrl = ctx.plantUrl;
3824
+ const hostOnlyCookie = {
3825
+ name: ctx.names.plant,
3826
+ value: `ho-${ctx.tag}`,
3827
+ domain: hostOf(hostOnlyUrl) || ctx.credentialHost,
3828
+ url: `${ctx.plantOrigin}/`,
3829
+ };
3830
+ const coverCookie = {
3831
+ name: ctx.names.plant,
3832
+ value: `dc-${ctx.tag}`,
3833
+ domain: ctx.credentialSiteDomain,
3834
+ url: `${ctx.plantOrigin}/`,
3835
+ };
3836
+ const subHost = `x.${ctx.credentialHost}`;
3837
+ const idpFixture =
3838
+ fixtureOriginFor(ctx.plantOrigin ?? ctx.ordinary, ctx.credentialHost) ??
3839
+ fixtureOriginFor(ctx.ordinary, ctx.credentialHost);
3840
+ const subUrl = `${fixtureOriginFor(idpFixture ?? ctx.ordinary, subHost) ?? `https://${subHost}`}/data?n=sub-${ctx.tag}`;
3841
+ const diag = (handle) => ({
3842
+ handle,
3843
+ budget: ctx.budget,
3844
+ notes: ctx.notes,
3845
+ fixtureLog: ctx.fixtureLog,
3846
+ legStartedAt: ctx.legStartedAt,
3847
+ firstIncomplete: ctx.firstIncomplete,
3848
+ });
3849
+ return {
3850
+ hostOnly: () =>
3851
+ withFreshAttemptTab(ctx, (handle) => {
3852
+ const fetchReady = Boolean(handle.transport?.fetch);
3853
+ return runPlant({
3854
+ ...diag(handle),
3855
+ url: hostOnlyUrl,
3856
+ cookie: hostOnlyCookie,
3857
+ label: 'hostOnly',
3858
+ topLevel: true,
3859
+ build: () =>
3860
+ fetchReady
3861
+ ? fetchFulfill({
3862
+ responseHeaders: [
3863
+ { name: 'content-type', value: 'text/plain' },
3864
+ {
3865
+ name: 'Set-Cookie',
3866
+ value: cookieHeader(ctx.names.plant, hostOnlyCookie.value, null),
3867
+ },
3868
+ ],
3869
+ body: b64text('ok'),
3870
+ })
3871
+ : legacyContinue({
3872
+ rawResponse: rawHttpResponse({
3873
+ code: 200,
3874
+ phrase: 'OK',
3875
+ headers: [
3876
+ {
3877
+ name: 'Set-Cookie',
3878
+ value: cookieHeader(ctx.names.plant, hostOnlyCookie.value, null),
3879
+ },
3880
+ ],
3881
+ body: 'ok',
3882
+ }),
3883
+ }),
3884
+ });
3885
+ }),
3886
+ domainCover: () =>
3887
+ withFreshAttemptTab(ctx, (handle) => {
3888
+ const fetchReady = Boolean(handle.transport?.fetch);
3889
+ return runPlant({
3890
+ ...diag(handle),
3891
+ url: subUrl,
3892
+ cookie: coverCookie,
3893
+ label: 'domainCover',
3894
+ topLevel: true,
3895
+ build: () =>
3896
+ fetchReady
3897
+ ? fetchFulfill({
3898
+ responseHeaders: [
3899
+ { name: 'content-type', value: 'text/plain' },
3900
+ {
3901
+ name: 'Set-Cookie',
3902
+ value: cookieHeader(
3903
+ ctx.names.plant,
3904
+ coverCookie.value,
3905
+ ctx.credentialSiteDomain
3906
+ ),
3907
+ },
3908
+ ],
3909
+ body: b64text('ok'),
3910
+ })
3911
+ : legacyContinue({
3912
+ rawResponse: rawHttpResponse({
3913
+ code: 200,
3914
+ phrase: 'OK',
3915
+ headers: [
3916
+ {
3917
+ name: 'Set-Cookie',
3918
+ value: cookieHeader(
3919
+ ctx.names.plant,
3920
+ coverCookie.value,
3921
+ ctx.credentialSiteDomain
3922
+ ),
3923
+ },
3924
+ ],
3925
+ body: 'ok',
3926
+ }),
3927
+ }),
3928
+ });
3929
+ }),
3930
+ subHost: () =>
3931
+ withFreshAttemptTab(ctx, (handle) => {
3932
+ const fetchReady = Boolean(handle.transport?.fetch);
3933
+ const subCookie = {
3934
+ name: ctx.names.ordinary,
3935
+ value: `sub-${ctx.tag}`,
3936
+ domain: `.${subHost}`,
3937
+ url: `${fixtureOriginFor(idpFixture ?? ctx.ordinary, subHost) ?? `https://${subHost}`}/`,
3938
+ };
3939
+ return allowedHeaderAttempt({
3940
+ ...diag(handle),
3941
+ url: subUrl,
3942
+ label: 'subHost',
3943
+ header: cookieHeader(ctx.names.ordinary, subCookie.value, `.${subHost}`),
3944
+ cookie: subCookie,
3945
+ fetchReady,
3946
+ topLevel: true,
3947
+ });
3948
+ }),
3949
+ };
3950
+ }
3951
+
3952
+ function sessionBlockedPlantResults(credential, notes = []) {
3953
+ const blocked = Object.fromEntries(
3954
+ ALL_PATH_NAMES.filter((name) => !['ordinary', 'adobe', 'deletion'].includes(name)).map(
3955
+ (name) => [
3956
+ name,
3957
+ scoreProtectedPlant({
3958
+ pauseCount: 0,
3959
+ fixtureHits: 0,
3960
+ planted: 'incomplete',
3961
+ pageHref: null,
3962
+ notes,
3963
+ label: name,
3964
+ triggerOutcome: {
3965
+ ok: false,
3966
+ error: { message: 'slicc: refused: session cut on protected execution context' },
3967
+ },
3968
+ blockedMarkers: [],
3969
+ triggerIssued: false,
3970
+ fetchEnableOk: null,
3971
+ plantSurfaceRefused: true,
3972
+ }),
3973
+ ]
3974
+ )
3975
+ );
3976
+ return finishCookiePlant({
3977
+ control: false,
3978
+ credential,
3979
+ fetch: false,
3980
+ legacy: false,
3981
+ evidenceIncomplete: true,
3982
+ results: {
3983
+ ...Object.fromEntries(ALL_PATH_NAMES.map((name) => [name, EMPTY_ATTEMPT])),
3984
+ ...blocked,
3985
+ ordinary: EMPTY_ATTEMPT,
3986
+ adobe: EMPTY_ATTEMPT,
3987
+ deletion: EMPTY_ATTEMPT,
3988
+ },
3989
+ });
3990
+ }
3991
+
3992
+ async function proveDoorOnOwnTab({
3993
+ reader,
3994
+ homeUrl,
3995
+ doorOrigin,
3996
+ tag,
3997
+ budget,
3998
+ notes,
3999
+ internalSessions,
4000
+ plantName,
4001
+ browserContextId = null,
4002
+ browserContexts = false,
4003
+ }) {
4004
+ const host = hostOf(doorOrigin);
4005
+ const domain = `.${host}`;
4006
+ const value = `door-${tag}`;
4007
+ const setCookie = cookieHeader(plantName, value, domain);
4008
+ const probePage = await openPage(reader, homeUrl, notes, internalSessions, browserContextId);
4009
+ if (!probePage.ok)
4010
+ return { incomplete: `open failed: ${probePage.error?.message ?? probePage.error}` };
4011
+ if (probePage.result?.incomplete) return { incomplete: probePage.result.incomplete };
4012
+ const probeSession = probePage.result.sessionId;
4013
+ const probeTarget = probePage.result.targetId;
4014
+ const readerTransport = await detectTransport(reader, probeSession, notes);
4015
+ await capped(
4016
+ outcome(reader.send('Target.closeTarget', { targetId: probeTarget })),
4017
+ 800,
4018
+ 'door-probe-close'
4019
+ );
4020
+ if (!readerTransport.kind) {
4021
+ return {
4022
+ incomplete:
4023
+ 'neither Fetch.enable nor Network.setRequestInterception is available on the unguarded session',
4024
+ live: false,
4025
+ };
4026
+ }
4027
+ if (readerTransport.kind === 'fetch') {
4028
+ const raw = await measureRawDoor(
4029
+ {
4030
+ reader,
4031
+ homeUrl,
4032
+ notes,
4033
+ internalSessions,
4034
+ budget,
4035
+ browserContextId,
4036
+ browserContexts,
4037
+ plantUrl: `${doorOrigin}/data?n=door-${tag}`,
4038
+ plantCookie: {
4039
+ name: plantName,
4040
+ value,
4041
+ domain,
4042
+ url: `${doorOrigin}/`,
4043
+ },
4044
+ forcedRaw: null,
4045
+ },
4046
+ {
4047
+ label: 'door',
4048
+ value,
4049
+ build: (paused) => ({
4050
+ send: (client, pause) =>
4051
+ fulfillPaused(client, pause, {
4052
+ responseCode: 200,
4053
+ responseHeaders: [
4054
+ { name: 'content-type', value: 'text/plain' },
4055
+ { name: 'Set-Cookie', value: setCookie },
4056
+ ],
4057
+ body: b64text(value),
4058
+ }),
4059
+ }),
4060
+ }
4061
+ );
4062
+ if (raw.incomplete || raw.observed !== true) {
4063
+ return { live: false, incomplete: raw.incomplete ?? 'raw leg incomplete' };
4064
+ }
4065
+ if (!raw.doorPresent) {
4066
+ return {
4067
+ live: false,
4068
+ incomplete: 'raw leg: Chrome did not store Domain=.<protected host> Set-Cookie',
4069
+ };
4070
+ }
4071
+ note(notes, 'cookie-plant.door', {
4072
+ answered: raw.answered,
4073
+ planted: raw.planted,
4074
+ domain,
4075
+ jarRead: raw.jarRead ?? false,
4076
+ canaryName: raw.canaryName ?? null,
4077
+ canaryVisible: raw.canaryVisible,
4078
+ via: raw.via ?? null,
4079
+ browserContextId: raw.browserContextId ?? null,
4080
+ });
4081
+ return { live: true };
4082
+ }
4083
+ const doorPage = await openPage(reader, homeUrl, notes, internalSessions, browserContextId);
4084
+ if (!doorPage.ok)
4085
+ return { incomplete: `open failed: ${doorPage.error?.message ?? doorPage.error}` };
4086
+ if (doorPage.result?.incomplete) return { incomplete: doorPage.result.incomplete };
4087
+ const doorContextId = await resolveTabContextId(
4088
+ reader,
4089
+ doorPage.result.targetId,
4090
+ browserContextId ?? null
4091
+ );
4092
+ if (browserContexts && (doorContextId == null || doorContextId === ''))
4093
+ return { incomplete: 'unknown context', browserContextId: null };
4094
+ const door = await proveDoor({
4095
+ reader,
4096
+ sessionId: doorPage.result.sessionId,
4097
+ protectedOrigin: doorOrigin,
4098
+ homeUrl,
4099
+ tag,
4100
+ budget,
4101
+ notes,
4102
+ transport: readerTransport,
4103
+ plantName,
4104
+ browserContextId: doorContextId,
4105
+ browserContexts,
4106
+ });
4107
+ await capped(
4108
+ outcome(reader.send('Target.closeTarget', { targetId: doorPage.result.targetId })),
4109
+ 800,
4110
+ 'door-close'
4111
+ );
4112
+ return door.live ? { live: true, doorVia: door.doorVia } : { ...door, live: false };
4113
+ }
4114
+
4115
+ async function openPlantClient({
4116
+ client,
4117
+ reader,
4118
+ homeUrl,
4119
+ notes,
4120
+ internalSessions,
4121
+ control,
4122
+ credential,
4123
+ browserContextId = null,
4124
+ }) {
4125
+ const page = await openPage(reader, homeUrl, notes, internalSessions, browserContextId);
4126
+ if (!page.ok)
4127
+ return { done: { incomplete: `open failed: ${page.error?.message ?? page.error}` } };
4128
+ if (page.result?.incomplete) return { done: { incomplete: page.result.incomplete } };
4129
+ const readerSession = page.result.sessionId;
4130
+ const pageTarget = page.result.targetId;
4131
+ const attached = await attachClientPage(client, pageTarget, internalSessions);
4132
+ if (attached.incomplete) {
4133
+ await outcome(reader.send('Target.closeTarget', { targetId: pageTarget }));
4134
+ return { done: { incomplete: attached.incomplete, live: true } };
4135
+ }
4136
+ if (attached.refused && sessionCut(attached.refused)) {
4137
+ await outcome(reader.send('Target.closeTarget', { targetId: pageTarget }));
4138
+ return {
4139
+ done: {
4140
+ live: true,
4141
+ incomplete: String(attached.refused.error?.message ?? 'session refused before trigger'),
4142
+ ...incompletePaths(),
4143
+ },
4144
+ };
4145
+ }
4146
+ const pageSession = attached.pageSession;
4147
+ if (!pageSession) {
4148
+ await outcome(reader.send('Target.closeTarget', { targetId: pageTarget }));
4149
+ return {
4150
+ done: {
4151
+ live: true,
4152
+ incomplete: 'client has no page session for interception attempts',
4153
+ ...incompletePaths(),
4154
+ },
4155
+ };
4156
+ }
4157
+ const enabled = await enableClientTransport(client, pageSession, notes);
4158
+ if (enabled.incomplete) {
4159
+ await outcome(reader.send('Target.closeTarget', { targetId: pageTarget }));
4160
+ if (sessionCut({ ok: false, error: { message: enabled.incomplete } }) && !control)
4161
+ return { done: sessionBlockedPlantResults(credential, notes) };
4162
+ return { done: { live: true, incomplete: enabled.incomplete } };
4163
+ }
4164
+ if (
4165
+ !control &&
4166
+ enabled.fetchEnable &&
4167
+ /session cut on protected execution context/i.test(
4168
+ String(enabled.fetchEnable.error?.message ?? '')
4169
+ )
4170
+ ) {
4171
+ await outcome(reader.send('Target.closeTarget', { targetId: pageTarget }));
4172
+ return { done: sessionBlockedPlantResults(credential, notes) };
4173
+ }
4174
+ return { readerSession, pageTarget, pageSession, enabled };
4175
+ }
4176
+
4177
+ export async function cookiePlant({
4178
+ client,
4179
+ reader,
4180
+ protectedOrigin,
4181
+ ordinary,
4182
+ tag,
4183
+ internalSessions = new Set(),
4184
+ notes = [],
4185
+ budget = 5000,
4186
+ control = false,
4187
+ mode = 'set-cookie',
4188
+ credentialOrigin,
4189
+ fixtureLog,
4190
+ blockedMarkers,
4191
+ onlyPaths = null,
4192
+ forcedRaw = null,
4193
+ browserContextId = null,
4194
+ browserContexts = false,
4195
+ }) {
4196
+ if (!reader) return { incomplete: 'missing unguarded reader' };
4197
+ const credential = mode === 'credential' || mode === 'credential-set-cookie';
4198
+ const sourceOrigin = credential ? (credentialOrigin ?? protectedOrigin) : protectedOrigin;
4199
+ if (!sourceOrigin) return { incomplete: 'missing protected origin' };
4200
+ if (!ordinary) return { incomplete: 'missing ordinary origin' };
4201
+
4202
+ const names = cookieNames(tag);
4203
+ const credentialHost = hostOf(sourceOrigin);
4204
+ const mappedOrigin = fixtureOriginFor(ordinary, credentialHost) ?? sourceOrigin;
4205
+ const plantOrigin = control ? ordinary : credential ? mappedOrigin : sourceOrigin;
4206
+ const credentialSiteDomain = `.${siteHost(credentialHost)}`;
4207
+ const domain = credential
4208
+ ? control
4209
+ ? `.${hostOf(ordinary)}`
4210
+ : credentialSiteDomain
4211
+ : `.${hostOf(plantOrigin)}`;
4212
+ const homeUrl = `${ordinary}/doc?n=cookie-plant-${tag}`;
4213
+
4214
+ const door = await proveDoorOnOwnTab({
4215
+ reader,
4216
+ homeUrl,
4217
+ doorOrigin: credential ? mappedOrigin : sourceOrigin,
4218
+ tag,
4219
+ budget,
4220
+ notes,
4221
+ internalSessions,
4222
+ plantName: names.plant,
4223
+ browserContextId,
4224
+ browserContexts,
4225
+ });
4226
+ if (!door.live) return door;
4227
+
4228
+ const probe = await openPlantClient({
4229
+ client,
4230
+ reader,
4231
+ homeUrl,
4232
+ notes,
4233
+ internalSessions,
4234
+ control,
4235
+ credential,
4236
+ browserContextId,
4237
+ });
4238
+ if (probe.done) return probe.done;
4239
+ const transport = probe.enabled.transport;
4240
+ const legacyReady = probe.enabled.legacyReady;
4241
+ await capped(disableInterception(client, probe.pageSession, transport), 800, 'probe-disable');
4242
+ await capped(
4243
+ outcome(reader.send('Target.closeTarget', { targetId: probe.pageTarget })),
4244
+ 800,
4245
+ 'probe-close'
4246
+ );
4247
+
4248
+ const ctx = plantCtx({
4249
+ client,
4250
+ reader,
4251
+ plantUrl: `${plantOrigin}/data?n=plant-${tag}`,
4252
+ plantCookie: {
4253
+ name: names.plant,
4254
+ value: `p-${tag}`,
4255
+ domain,
4256
+ url: `${plantOrigin}/`,
4257
+ },
4258
+ domain,
4259
+ tag,
4260
+ names,
4261
+ plantOrigin,
4262
+ protectedOrigin: sourceOrigin,
4263
+ ordinary,
4264
+ homeUrl,
4265
+ transport,
4266
+ budget,
4267
+ notes,
4268
+ internalSessions,
4269
+ credential,
4270
+ credentialHost,
4271
+ credentialSiteDomain,
4272
+ fixtureLog,
4273
+ legStartedAt: Date.now(),
4274
+ firstIncomplete: { noted: false },
4275
+ guardedProtected: !control && !credential,
4276
+ blockedMarkers: Array.isArray(blockedMarkers) ? blockedMarkers : [],
4277
+ proofTag: tag,
4278
+ rawDoors: {},
4279
+ forcedRaw: forcedRaw && typeof forcedRaw === 'object' ? forcedRaw : null,
4280
+ browserContextId,
4281
+ browserContexts: Boolean(browserContexts),
4282
+ });
4283
+
4284
+ const { results, ran } = await runAttempts(
4285
+ control
4286
+ ? [controlAttacks(ctx)]
4287
+ : [
4288
+ controlAttacks(ctx),
4289
+ fetchAttacks(ctx),
4290
+ legacyAttacks(ctx, legacyReady),
4291
+ credential ? credentialAttacks(ctx) : null,
4292
+ ],
4293
+ budget,
4294
+ onlyPaths,
4295
+ legacyReady
4296
+ );
4297
+
4298
+ const evidenceIncomplete =
4299
+ !control &&
4300
+ [...ran].some((name) => {
4301
+ const attempt = results[name];
4302
+ if (!attempt || attempt.answered === 'not-supported') return false;
4303
+ return (
4304
+ attempt.planted === 'incomplete' ||
4305
+ attempt.answered === 'incomplete' ||
4306
+ attempt.refused === 'incomplete'
4307
+ );
4308
+ });
4309
+
4310
+ return finishCookiePlant({
4311
+ control,
4312
+ credential,
4313
+ fetch: Boolean(transport.fetch),
4314
+ legacy: Boolean(legacyReady),
4315
+ evidenceIncomplete,
4316
+ results,
4317
+ });
4318
+ }
4319
+
4320
+ function finishCookiePlant({ control, credential, fetch, legacy, evidenceIncomplete, results }) {
4321
+ return Object.assign(
4322
+ {
4323
+ live: true,
4324
+ control: Boolean(control),
4325
+ fetch,
4326
+ legacy,
4327
+ credential,
4328
+ ...(evidenceIncomplete && !control
4329
+ ? { incomplete: 'protected plant evidence incomplete' }
4330
+ : {}),
4331
+ },
4332
+ ...Object.entries(results).map(([name, attempt]) => flattenAttempt(name, attempt))
4333
+ );
4334
+ }
4335
+
4336
+ export { cookieNames };
4337
+
4338
+ export const cookiePlantHandleApi = {
4339
+ requireAttemptHandle,
4340
+ jarContextIncomplete,
4341
+ jarAuditFields,
4342
+ evidenceFormOf,
4343
+ plantCanary,
4344
+ clearCookie,
4345
+ readJar,
4346
+ readJarView,
4347
+ readJarWithCanary,
4348
+ seedCookie,
4349
+ finishPlant,
4350
+ recordSessionCut,
4351
+ continueItselfEvidence,
4352
+ evidenceAfterTrigger,
4353
+ };