@ai-ecoverse/slicc-browsers 1.55.0 → 1.56.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/sign-in-hold.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { outcome, waitFor } from './guard-driver.mjs';
1
+ import { outcome } from './guard-driver.mjs';
2
2
  import { createObserverTarget } from './observer-target.mjs';
3
3
 
4
4
  const CALLBACK = 'https://www.sliccy.ai/auth/callback';
@@ -84,7 +84,101 @@ async function until(check, ms, step = 25) {
84
84
  }
85
85
  }
86
86
 
87
- async function openPage(reader, url, notes, internalSessions) {
87
+ const OPENER_KEY = '__sliccHoldOpener';
88
+ const OPEN_WAIT_MS = 4000;
89
+ const OPEN_POLL_MS = 25;
90
+ const UNANSWERED = Symbol('unanswered');
91
+ const clock = () => performance.now();
92
+ const nonce = () => `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
93
+
94
+ function canonical(url) {
95
+ try {
96
+ return new URL(url).href;
97
+ } catch {
98
+ return String(url ?? '');
99
+ }
100
+ }
101
+
102
+ function openerBinding(url) {
103
+ return { want: canonical(url), key: `${OPENER_KEY}-${nonce()}` };
104
+ }
105
+
106
+ function bindingHead({ want, key, token }) {
107
+ return `const want = ${JSON.stringify(want)};
108
+ const key = ${JSON.stringify(key)};
109
+ const token = ${JSON.stringify(token)};
110
+ let here = '';
111
+ try {
112
+ here = new URL(location.href).href;
113
+ } catch {}
114
+ const committed = here === want;`;
115
+ }
116
+
117
+ function openRead(binding, token) {
118
+ return `(() => {
119
+ ${bindingHead({ ...binding, token })}
120
+ const ready = document.readyState;
121
+ const fit = committed && (ready === 'interactive' || ready === 'complete');
122
+ if (fit) Object.defineProperty(document, key, { value: token, configurable: true });
123
+ const bound = fit && document[key] === token;
124
+ const initial = !here || location.protocol === 'about:';
125
+ return { ready, initial, committed, bound, ...(here === 'about:blank' ? { blank: true } : {}) };
126
+ })()`;
127
+ }
128
+
129
+ function boundOpen(binding) {
130
+ return `${bindingHead(binding)}
131
+ const proof = document[key];
132
+ if (!committed || proof !== token)
133
+ return { stale: true, opened: false, committed, bound: proof === token };`;
134
+ }
135
+
136
+ function openState(value) {
137
+ if (value.committed === true) return 'committed';
138
+ if (value.initial === true) return 'initial';
139
+ if (value.committed === false) return 'other';
140
+ return 'unknown';
141
+ }
142
+
143
+ function openReason(state) {
144
+ if (state === 'initial') return 'opener page did not commit the requested url';
145
+ if (state === 'other') return 'opener page committed another url';
146
+ return 'opener page did not become ready';
147
+ }
148
+
149
+ async function readOpener(reader, sessionId, expression, deadline) {
150
+ let timer;
151
+ const expired = new Promise((resolve) => {
152
+ timer = setTimeout(() => resolve(UNANSWERED), Math.max(0, deadline - clock()));
153
+ });
154
+ const read = await Promise.race([
155
+ outcome(
156
+ (async () =>
157
+ reader.send('Runtime.evaluate', { expression, returnByValue: true }, sessionId))()
158
+ ),
159
+ expired,
160
+ ]);
161
+ clearTimeout(timer);
162
+ if (read === UNANSWERED) return { unanswered: true };
163
+ return { read, late: clock() > deadline };
164
+ }
165
+
166
+ function readyRead(read, seen, want) {
167
+ seen.error = read.ok ? null : String(read.error?.message ?? read.error);
168
+ if (read.result?.exceptionDetails) seen.error = 'opener readiness evaluate raised an exception';
169
+ const value = read.ok && !seen.error ? read.result?.result?.value : null;
170
+ if (!value || typeof value !== 'object') return false;
171
+ seen.requested = value.committed === true;
172
+ seen.href = seen.requested ? want : value.blank === true ? 'about:blank' : '';
173
+ seen.state = openState(value);
174
+ return (
175
+ value.committed === true &&
176
+ value.bound === true &&
177
+ ['interactive', 'complete'].includes(value.ready)
178
+ );
179
+ }
180
+
181
+ async function openPage(reader, url, notes, internalSessions, binding) {
88
182
  const created = await outcome(
89
183
  createObserverTarget(reader, { url }, notes).then(async (result) => {
90
184
  const { sessionId } = await reader.send('Target.attachToTarget', {
@@ -98,27 +192,54 @@ async function openPage(reader, url, notes, internalSessions) {
98
192
  );
99
193
  if (!created.ok) return created;
100
194
  internalSessions.add(created.result.sessionId);
101
- const ready = await waitFor(async () => {
102
- const read = await outcome(
103
- reader.send(
104
- 'Runtime.evaluate',
105
- { expression: 'document.readyState', returnByValue: true },
106
- created.result.sessionId
107
- )
195
+ const seen = { held: false, href: '', requested: false, state: null, error: null };
196
+ const start = clock();
197
+ const deadline = start + OPEN_WAIT_MS;
198
+ let token = null;
199
+ let answered = 0;
200
+ while (clock() < deadline) {
201
+ const asked = `${answered}-${nonce()}`;
202
+ const polled = await readOpener(
203
+ reader,
204
+ created.result.sessionId,
205
+ openRead(binding, asked),
206
+ deadline
108
207
  );
109
- return read.ok && ['interactive', 'complete'].includes(read.result?.result?.value);
110
- }, 4000);
208
+ if (polled.unanswered) {
209
+ seen.held = true;
210
+ seen.unanswered = answered === 0;
211
+ break;
212
+ }
213
+ const fit = readyRead(polled.read, seen, binding.want);
214
+ if (fit && !polled.late) {
215
+ token = asked;
216
+ break;
217
+ }
218
+ seen.held = true;
219
+ if (polled.late) {
220
+ seen.late = fit;
221
+ break;
222
+ }
223
+ answered += 1;
224
+ await pause(Math.max(0, Math.min(OPEN_POLL_MS, deadline - clock())));
225
+ }
226
+ const ready = token !== null;
227
+ const waitedMs = Math.round(Math.min(clock(), deadline) - start);
111
228
  note(notes, 'sign-in-hold.open', {
112
229
  targetId: created.result.targetId,
113
230
  url,
114
- ready: Boolean(ready),
231
+ ready,
232
+ ...(seen.held ? { href: seen.href.slice(0, 200), requested: seen.requested, waitedMs } : {}),
233
+ ...(seen.error ? { error: seen.error.slice(0, 200) } : {}),
234
+ ...(seen.unanswered ? { unanswered: true } : {}),
235
+ ...(seen.late ? { late: true } : {}),
115
236
  });
116
237
  if (!ready)
117
238
  return {
118
239
  ok: true,
119
- result: { incomplete: 'opener page did not become ready', ...created.result },
240
+ result: { incomplete: openReason(seen.state), ...created.result },
120
241
  };
121
- return created;
242
+ return { ok: true, result: { ...created.result, token } };
122
243
  }
123
244
 
124
245
  async function listHttp(client, notes) {
@@ -213,7 +334,7 @@ function recordTargets(targets, result, missing, rawId, rawUrl, mark) {
213
334
  }
214
335
  if (!targets.ok) return;
215
336
  const infos = targets.result?.targetInfos ?? [];
216
- const match = infos.find((info) => info.targetId === rawId);
337
+ const match = infos.find((info) => info?.targetId === rawId);
217
338
  const listed = identifyingLeak(match, rawId, rawUrl, mark)
218
339
  ? true
219
340
  : infos.some((info) => identifyingLeak(info, rawId, rawUrl, mark));
@@ -371,7 +492,7 @@ async function measureClient({
371
492
  return result;
372
493
  }
373
494
 
374
- async function rawReadable(reader, targetId, mark, notes, waitMs = 0) {
495
+ async function rawReadable(reader, targetId, mark, notes, waitMs = 0, expectedUrl) {
375
496
  const attached = await outcome(reader.send('Target.attachToTarget', { targetId, flatten: true }));
376
497
  if (!attached.ok || !attached.result?.sessionId)
377
498
  return {
@@ -382,29 +503,22 @@ async function rawReadable(reader, targetId, mark, notes, waitMs = 0) {
382
503
  };
383
504
  const sessionId = attached.result.sessionId;
384
505
  await outcome(reader.send('Runtime.enable', {}, sessionId));
506
+ const expression = `(() => {
507
+ const readyState = document.readyState;
508
+ const committed = ${expectedUrl ? `location.href === ${JSON.stringify(canonical(expectedUrl))}` : 'true'};
509
+ const marked = committed && (document.title + ' ' + (document.body && document.body.innerText)).includes(${JSON.stringify(mark)});
510
+ return { readyState, committed, marked };
511
+ })()`;
385
512
  const readOnce = async () => {
386
- const ready = await outcome(
387
- reader.send(
388
- 'Runtime.evaluate',
389
- { expression: 'document.readyState', returnByValue: true },
390
- sessionId
391
- )
392
- );
393
- const readyState = ready.ok ? ready.result?.result?.value : null;
394
- const committed = ready.ok && ['interactive', 'complete'].includes(readyState);
395
513
  const read = await outcome(
396
- reader.send(
397
- 'Runtime.evaluate',
398
- {
399
- expression: 'document.title + " " + (document.body && document.body.innerText)',
400
- returnByValue: true,
401
- },
402
- sessionId
403
- )
514
+ reader.send('Runtime.evaluate', { expression, returnByValue: true }, sessionId)
404
515
  );
405
- const text = read.ok ? String(read.result?.result?.value ?? '') : '';
406
- const readable = Boolean(committed && mark && text.includes(mark));
407
- return { readable, text, readyState, committed };
516
+ const value = read.ok && !read.result?.exceptionDetails ? read.result?.result?.value : null;
517
+ const readable =
518
+ value?.committed === true &&
519
+ value.marked === true &&
520
+ ['interactive', 'complete'].includes(value.readyState);
521
+ return { readable, readyState: value?.readyState, text: readable ? mark : '' };
408
522
  };
409
523
  let result = await readOnce();
410
524
  if (!result.readable && waitMs > 0) {
@@ -437,35 +551,28 @@ async function rawReadable(reader, targetId, mark, notes, waitMs = 0) {
437
551
  return { readable: false, step, reason, text, readyState: result.readyState };
438
552
  }
439
553
 
440
- function holdExpression(control, ordinary, tag, marker, heldUrl, { askHook = false } = {}) {
441
- if (control)
442
- return `(async () => {
443
- const popup = window.open(${JSON.stringify(`${ordinary}/held?n=${tag}`)}, 'slicc-ordinary', 'popup,width=520,height=720');
444
- return { answer: 'none', opened: Boolean(popup) };
445
- })()`;
446
- if (askHook)
447
- return `(async () => {
448
- const marker = ${JSON.stringify(marker)};
449
- const popup = window.open('about:blank#${MARK_PREFIX}' + marker, 'slicc-sign-in', 'popup,width=520,height=720');
450
- return { answer: 'pending', opened: Boolean(popup), marker };
451
- })()`;
452
- return `(async () => {
453
- const marker = ${JSON.stringify(marker)};
454
- const heldUrl = ${JSON.stringify(heldUrl)};
455
- const popup = window.open('about:blank#${MARK_PREFIX}' + marker, 'slicc-sign-in', 'popup,width=520,height=720');
554
+ const channelAnswers = ['held', 'unheld', 'none'];
555
+
556
+ function holdExpression({ control, askHook, binding, heldUrl, markerUrl, marker }) {
557
+ const channel = `const marker = ${JSON.stringify(marker)};
456
558
  const channel = new BroadcastChannel('slicc-held');
457
559
  const answer = await new Promise((resolve) => {
458
560
  const timer = setTimeout(() => resolve('timeout'), 6000);
459
561
  channel.onmessage = ({ data }) => {
460
562
  if (data?.marker !== marker || data.type === 'hold') return;
461
563
  clearTimeout(timer);
462
- resolve(data.type);
564
+ resolve(${JSON.stringify(channelAnswers)}.includes(data.type) ? data.type : 'invalid');
463
565
  };
464
566
  channel.postMessage({ type: 'hold', marker });
465
567
  });
466
568
  channel.close();
467
- if (popup && (answer === 'held' || answer === 'timeout')) popup.location.href = heldUrl;
468
- return { answer, opened: Boolean(popup) };
569
+ if (answer === 'held' || answer === 'timeout') popup.location.href = ${JSON.stringify(heldUrl)};`;
570
+ return `(async () => {
571
+ ${boundOpen(binding)}
572
+ const popup = window.open(${JSON.stringify(control ? heldUrl : markerUrl)}, ${JSON.stringify(control ? 'slicc-ordinary' : 'slicc-sign-in')}, 'popup,width=520,height=720');
573
+ if (!popup) return { opened: false };
574
+ ${control ? "const answer = 'none';" : askHook ? "const answer = 'pending';" : channel}
575
+ return { opened: true, proof, answer };
469
576
  })()`;
470
577
  }
471
578
 
@@ -500,7 +607,8 @@ async function prepareHold(client, { useAsk, marker, hostLabel, notes, budget })
500
607
 
501
608
  async function askHold(client, { marker, hostLabel, notes, prepared }) {
502
609
  const hold = client?.signInHold;
503
- if (typeof hold?.ask !== 'function') return { used: false };
610
+ if (typeof hold?.ask !== 'function')
611
+ return { incomplete: 'signInHold.ask unavailable after prepare' };
504
612
  note(notes, 'sign-in-hold.ask', { via: 'signInHold.ask', marker, hostLabel });
505
613
  const asked = prepared
506
614
  ? { marker, hostLabel, baseline: prepared.baseline }
@@ -517,15 +625,13 @@ async function askHold(client, { marker, hostLabel, notes, prepared }) {
517
625
  }, 6000);
518
626
  }),
519
627
  ]);
520
- if (!['held', 'unheld', 'none'].includes(answer))
628
+ if (!channelAnswers.includes(answer))
521
629
  return {
522
- used: true,
523
630
  incomplete: `signInHold.ask returned ${JSON.stringify(answer)}, want held|unheld|none`,
524
631
  };
525
- return { used: true, answer };
632
+ return { ok: true, answer };
526
633
  } catch (error) {
527
634
  return {
528
- used: true,
529
635
  incomplete: `signInHold.ask failed: ${error?.message ?? error}`,
530
636
  };
531
637
  } finally {
@@ -533,53 +639,45 @@ async function askHold(client, { marker, hostLabel, notes, prepared }) {
533
639
  }
534
640
  }
535
641
 
536
- function matchPopup(info, known, openerId, heldUrl, control) {
537
- if (info.type !== 'page' || known.has(info.targetId) || info.targetId === openerId) return false;
538
- const url = info.url ?? '';
539
- if (control) return url === heldUrl || url.includes('/held');
540
- return url === heldUrl || url.startsWith('about:blank#') || url.includes('/held');
642
+ function targetInfos(result) {
643
+ const infos = result?.targetInfos;
644
+ return Array.isArray(infos)
645
+ ? infos.filter((info) => typeof info?.targetId === 'string' && info.targetId)
646
+ : null;
541
647
  }
542
648
 
543
- function exactPopups(infos, known, openerId, markerUrl) {
649
+ function exactPopups(infos, known, openerId, urls) {
544
650
  return infos.filter(
545
651
  (info) =>
546
652
  info.type === 'page' &&
547
653
  !known.has(info.targetId) &&
548
- info.url === markerUrl &&
549
- info.openerId === openerId
654
+ info.openerId === openerId &&
655
+ urls.includes(info.url)
550
656
  );
551
657
  }
552
658
 
553
- async function askedPopup(reader, { known, openerId, markerUrl, budget, notes }) {
659
+ const popupSnapshot = (reader) =>
660
+ outcome(Promise.resolve().then(() => reader.send('Target.getTargets', {})));
661
+
662
+ async function findPopup(reader, { known, openerId, urls }, budget) {
554
663
  let matched = 0;
555
664
  let failed = null;
556
665
  const popup = await until(async () => {
557
- const listed = await outcome(reader.send('Target.getTargets', {}));
666
+ const listed = await popupSnapshot(reader);
558
667
  if (!listed.ok) {
559
668
  failed = String(listed.error?.message ?? listed.error);
560
669
  return null;
561
670
  }
562
671
  failed = null;
563
- const found = exactPopups(listed.result?.targetInfos ?? [], known, openerId, markerUrl);
672
+ const found = exactPopups(targetInfos(listed.result) ?? [], known, openerId, urls);
564
673
  matched = found.length;
565
674
  return matched === 1 ? found[0] : null;
566
675
  }, budget);
567
- note(notes, 'sign-in-hold.ask-cleanup', {
568
- markerUrl,
569
- openerId,
570
- matched,
571
- failed,
572
- targetId: popup?.targetId ?? null,
573
- });
574
- if (popup) return { popup };
575
- const why = failed
576
- ? `Target.getTargets failed: ${failed}`
577
- : `${matched} page targets at ${markerUrl} opened by ${openerId}`;
578
- return { reason: `popup not identified exactly (${why}), nothing closed` };
676
+ return { popup, matched, failed };
579
677
  }
580
678
 
581
- async function moveHeldPopup(reader, raw, heldUrl, budget, internalSessions) {
582
- if (raw.url === heldUrl) return raw;
679
+ async function moveHeldPopup(reader, raw, heldUrl, internalSessions) {
680
+ if (raw.url === heldUrl) return;
583
681
  const attached = await outcome(
584
682
  reader.send('Target.attachToTarget', { targetId: raw.targetId, flatten: true })
585
683
  );
@@ -589,14 +687,53 @@ async function moveHeldPopup(reader, raw, heldUrl, budget, internalSessions) {
589
687
  await outcome(reader.send('Target.detachFromTarget', { sessionId: attached.result.sessionId }));
590
688
  internalSessions.delete(attached.result.sessionId);
591
689
  }
592
- const moved = await until(
593
- async () => {
594
- const info = await outcome(reader.send('Target.getTargetInfo', { targetId: raw.targetId }));
595
- return info.ok && info.result?.targetInfo?.url === heldUrl ? info.result.targetInfo : null;
596
- },
597
- Math.min(budget, 2000)
690
+ }
691
+
692
+ async function evaluateHold(reader, sessionId, plan, notes) {
693
+ const asked = await outcome(
694
+ (async () =>
695
+ reader.send(
696
+ 'Runtime.evaluate',
697
+ {
698
+ expression: holdExpression(plan),
699
+ awaitPromise: true,
700
+ returnByValue: true,
701
+ userGesture: true,
702
+ },
703
+ sessionId
704
+ ))()
598
705
  );
599
- return moved ? Object.assign(raw, moved) : raw;
706
+ if (!asked.ok)
707
+ return { incomplete: `hold evaluate failed: ${asked.error?.message ?? asked.error}` };
708
+ if (asked.result?.exceptionDetails)
709
+ return { incomplete: 'window.open evaluate raised an exception' };
710
+ const value = asked.result?.result?.value;
711
+ if (value?.stale === true) {
712
+ note(notes, 'sign-in-hold.stale', {
713
+ href: '',
714
+ committed: value.committed === true,
715
+ bound: value.bound === true,
716
+ });
717
+ return { incomplete: 'opener document changed before window.open' };
718
+ }
719
+ if (value === '[redacted]') return { incomplete: 'window.open reply was redacted' };
720
+ if (value == null) return { incomplete: 'window.open reply was empty' };
721
+ if (value.opened === false)
722
+ return { incomplete: 'window.open returned null', holdAnswer: 'missing' };
723
+ if (
724
+ asked.result.result.type !== 'object' ||
725
+ value.opened !== true ||
726
+ value.proof !== plan.binding.token
727
+ )
728
+ return { incomplete: 'window.open did not confirm opening in the verified opener document' };
729
+ const answers = plan.control
730
+ ? ['none']
731
+ : plan.askHook
732
+ ? ['pending']
733
+ : [...channelAnswers, 'timeout', 'invalid'];
734
+ if (!answers.includes(value.answer))
735
+ return { incomplete: 'window.open returned an unrecognized hold answer' };
736
+ return { opened: true, answer: value.answer };
600
737
  }
601
738
 
602
739
  async function heldPopup({
@@ -618,101 +755,92 @@ async function heldPopup({
618
755
  const openerUrl = control
619
756
  ? `${ordinary}/doc?n=opener-${tag}`
620
757
  : `${openerOrigin}/doc?n=opener-${tag}`;
621
- const opened = await openPage(reader, openerUrl, notes, internalSessions);
758
+ const markerUrl = `about:blank#${MARK_PREFIX}${marker}`;
759
+ const binding = openerBinding(openerUrl);
760
+ const opened = await openPage(reader, openerUrl, notes, internalSessions, binding);
622
761
  if (!opened.ok)
623
762
  return { incomplete: `observer setup failed: ${opened.error?.message ?? opened.error}` };
624
- if (opened.result.incomplete) return { live: false, incomplete: opened.result.incomplete };
625
- const { sessionId, targetId: openerId } = opened.result;
626
- const before = await outcome(reader.send('Target.getTargets', {}));
627
- const known = new Set((before.result?.targetInfos ?? []).map((info) => info.targetId));
763
+ if (opened.result.incomplete)
764
+ return {
765
+ live: false,
766
+ incomplete: opened.result.incomplete,
767
+ openerId: opened.result.targetId,
768
+ };
769
+ const { sessionId, targetId: openerId, token } = opened.result;
770
+ const before = await popupSnapshot(reader);
771
+ const infos = targetInfos(before.result);
772
+ if (!infos)
773
+ return {
774
+ live: false,
775
+ incomplete: 'before-open Target.getTargets snapshot unavailable',
776
+ openerId,
777
+ };
778
+ const match = {
779
+ known: new Set(infos.map((info) => info.targetId)),
780
+ openerId,
781
+ urls: control ? [heldUrl] : [markerUrl, heldUrl],
782
+ };
783
+ const cleanupFailure = async (failure, phase) => {
784
+ const { popup, matched, failed } = await findPopup(reader, match, Math.min(budget, 1000));
785
+ note(notes, `sign-in-hold.${phase}-cleanup`, {
786
+ markerUrl,
787
+ openerId,
788
+ matched,
789
+ failed,
790
+ targetId: popup?.targetId ?? null,
791
+ });
792
+ const result = { live: false, ...failure, openerId };
793
+ if (popup) return { ...result, targetId: popup.targetId };
794
+ if (phase === 'ask') {
795
+ const why = failed
796
+ ? `Target.getTargets failed: ${failed}`
797
+ : `${matched} matching page targets opened by ${openerId}`;
798
+ result.incomplete += `; popup not identified exactly (${why}), nothing closed`;
799
+ }
800
+ return result;
801
+ };
628
802
  const useAsk = !control && typeof client?.signInHold?.ask === 'function';
629
803
  const hostLabel = hostLabelOf(openerOrigin ?? ordinary);
630
804
  const prepared = await prepareHold(client, { useAsk, marker, hostLabel, notes, budget });
631
805
  if (prepared?.incomplete) return { incomplete: prepared.incomplete, openerId };
632
- const asked = await outcome(
633
- reader.send(
634
- 'Runtime.evaluate',
635
- {
636
- expression: holdExpression(control, ordinary, tag, marker, heldUrl, { askHook: useAsk }),
637
- awaitPromise: true,
638
- returnByValue: true,
639
- userGesture: true,
640
- },
641
- sessionId
642
- )
806
+ const asked = await evaluateHold(
807
+ reader,
808
+ sessionId,
809
+ { control, askHook: useAsk, binding: { ...binding, token }, heldUrl, markerUrl, marker },
810
+ notes
643
811
  );
644
- if (!asked.ok)
645
- return {
646
- live: false,
647
- incomplete: `hold evaluate failed: ${asked.error?.message ?? asked.error}`,
648
- openerId,
649
- };
650
- let holdAnswer = asked.result?.result?.value?.answer ?? 'missing';
651
- const openedPopup = asked.result?.result?.value?.opened;
812
+ if (asked.opened !== true) return cleanupFailure(asked, 'open');
813
+ let holdAnswer = asked.answer;
652
814
  if (useAsk) {
653
815
  const askedHold = await askHold(client, { marker, hostLabel, notes, prepared });
654
- if (askedHold.incomplete) {
655
- const found = await askedPopup(reader, {
656
- known,
657
- openerId,
658
- markerUrl: `about:blank#${MARK_PREFIX}${marker}`,
659
- budget: Math.min(budget, 1000),
660
- notes,
661
- });
662
- if (!found.popup)
663
- return { live: false, incomplete: `${askedHold.incomplete}; ${found.reason}`, openerId };
664
- return {
665
- live: false,
666
- incomplete: askedHold.incomplete,
667
- openerId,
668
- targetId: found.popup.targetId,
669
- };
670
- }
816
+ if (askedHold.ok !== true) return cleanupFailure(askedHold, 'ask');
671
817
  holdAnswer = askedHold.answer;
672
818
  }
673
819
  note(notes, 'sign-in-hold.hold', {
674
820
  holdAnswer,
675
821
  control: Boolean(control),
676
- opened: openedPopup,
822
+ opened: true,
677
823
  askHook: useAsk,
678
824
  ...(prepared ? { prepared: true } : {}),
679
825
  });
680
- if (openedPopup === false)
681
- return {
682
- live: false,
683
- incomplete: 'window.open returned null',
684
- holdAnswer,
685
- openerId,
686
- };
687
- const raw = await until(async () => {
688
- const listed = await outcome(reader.send('Target.getTargets', {}));
689
- if (!listed.ok) return null;
690
- return (
691
- (listed.result?.targetInfos ?? []).find((info) =>
692
- matchPopup(info, known, openerId, heldUrl, control)
693
- ) ?? null
694
- );
695
- }, budget);
826
+ const { popup: raw } = await findPopup(reader, match, budget);
696
827
  if (!raw) {
697
828
  return {
698
829
  live: false,
699
- incomplete: 'popup target did not appear in the raw leg within the budget',
830
+ incomplete: 'raw leg did not identify exactly one new popup for the verified opener',
700
831
  holdAnswer,
701
832
  openerId,
702
833
  };
703
834
  }
704
- if (!control) await moveHeldPopup(reader, raw, heldUrl, budget, internalSessions);
705
- const settled = await until(
706
- async () => {
707
- const info = await outcome(reader.send('Target.getTargetInfo', { targetId: raw.targetId }));
708
- if (!info.ok) return null;
709
- if (info.result?.targetInfo?.url === heldUrl || control) return info.result.targetInfo;
710
- return info.result?.targetInfo ?? null;
711
- },
712
- Math.min(budget, 3000)
835
+ if (!control) await moveHeldPopup(reader, raw, heldUrl, internalSessions);
836
+ const read = await rawReadable(
837
+ reader,
838
+ raw.targetId,
839
+ mark,
840
+ notes,
841
+ Math.min(budget, 3000),
842
+ heldUrl
713
843
  );
714
- const rawUrl = settled?.url ?? raw.url ?? heldUrl;
715
- const read = await rawReadable(reader, raw.targetId, mark, notes, Math.min(budget, 3000));
716
844
  if (!read.readable)
717
845
  return {
718
846
  live: false,
@@ -724,7 +852,7 @@ async function heldPopup({
724
852
  const measured = await measureClient({
725
853
  client,
726
854
  rawId: raw.targetId,
727
- rawUrl,
855
+ rawUrl: heldUrl,
728
856
  mark,
729
857
  discovery,
730
858
  eventStart,
@@ -737,7 +865,7 @@ async function heldPopup({
737
865
  holdAnswer: control ? 'none' : holdAnswer,
738
866
  openerId,
739
867
  targetId: raw.targetId,
740
- rawUrl,
868
+ rawUrl: heldUrl,
741
869
  ...measured,
742
870
  held,
743
871
  };
@@ -824,6 +952,17 @@ async function callbackTab({
824
952
  };
825
953
  }
826
954
 
955
+ async function enableDiscovery(client) {
956
+ const enabled = await outcome(client.send('Target.setDiscoverTargets', { discover: true }));
957
+ if (!enabled.ok) return 'rejected';
958
+ return enabled.result &&
959
+ typeof enabled.result === 'object' &&
960
+ !Array.isArray(enabled.result) &&
961
+ Array.isArray(client.events)
962
+ ? 'enabled'
963
+ : 'unavailable';
964
+ }
965
+
827
966
  export async function signInHold({
828
967
  client,
829
968
  reader,
@@ -843,10 +982,17 @@ export async function signInHold({
843
982
  if (!ordinary) return { incomplete: 'missing {ordinary} placeholder' };
844
983
  if (!cross && (String(mode).startsWith('callback') || mode === 'ordinary-authorize'))
845
984
  return { incomplete: 'missing {cross} placeholder' };
985
+ const ordinaryLeg = control || mode === 'ordinary-popup' || mode === 'ordinary-authorize';
846
986
  if (discovery) {
847
- await outcome(client.send('Target.setDiscoverTargets', { discover: true }));
987
+ const state = await enableDiscovery(client);
988
+ if (state !== 'enabled' && !(ordinaryLeg && state === 'rejected'))
989
+ return { live: false, incomplete: 'client target discovery unavailable' };
848
990
  await outcome(reader.send('Target.setDiscoverTargets', { discover: true }));
849
- notes.push('sign-in-hold.discovery: setDiscoverTargets discover=true');
991
+ notes.push(
992
+ state === 'rejected'
993
+ ? 'sign-in-hold.discovery: client rejected discovery'
994
+ : 'sign-in-hold.discovery: setDiscoverTargets discover=true'
995
+ );
850
996
  }
851
997
 
852
998
  const built =
@@ -862,7 +1008,7 @@ export async function signInHold({
862
1008
  discovery,
863
1009
  internalSessions,
864
1010
  eventStart,
865
- control: control || mode === 'ordinary-popup',
1011
+ control: ordinaryLeg,
866
1012
  })
867
1013
  : String(mode).startsWith('callback') || mode === 'ordinary-authorize'
868
1014
  ? await callbackTab({
@@ -877,7 +1023,7 @@ export async function signInHold({
877
1023
  discovery,
878
1024
  internalSessions,
879
1025
  eventStart,
880
- control: control || mode === 'ordinary-authorize',
1026
+ control: ordinaryLeg,
881
1027
  })
882
1028
  : { incomplete: `unknown signInHold mode ${mode}` };
883
1029