@xkwdstore/agent 2.1.3 → 2.1.5

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,255 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Device-side cookie restoration (defense in depth).
5
+ *
6
+ * The backend normalizes stored cookies once at the command chokepoint
7
+ * (backend/security/cookiePayload.js). This module is the SECOND gate on the
8
+ * device that owns the profile. It exists because a cookie payload can also
9
+ * arrive from a legacy agent path, a test fixture, or a future caller — and a
10
+ * bad payload must never silently widen a cookie's scope or extend its life.
11
+ *
12
+ * RULES (identical to the backend contract):
13
+ * - only authorized X/Twitter origins (x.com, twitter.com and subdomains),
14
+ * - never invent a name/value; entries without a usable scope are dropped,
15
+ * - `expires` supports seconds and millisecond timestamps; milliseconds are
16
+ * converted to the SAME instant in seconds (never extended),
17
+ * - already-expired persistent cookies are dropped and counted,
18
+ * - a host-only cookie stays host-only (rendered as a `url` cookie) rather
19
+ * than being silently promoted to a `.x.com` domain cookie,
20
+ * - optional attributes (secure/httpOnly/sameSite) are carried only when the
21
+ * payload supplied them; unknown sameSite is omitted,
22
+ * - no cookie value, header, or raw exception is ever logged or returned.
23
+ */
24
+
25
+ const { isAuthorizedXUrl } = require('./sessionAuth');
26
+
27
+ const MAX_COOKIES = 500;
28
+ // Stay well below the 256 KiB worker-bridge frame bound.
29
+ const MAX_TOTAL_COOKIE_BYTES = 180_000;
30
+ const MAX_COOKIE_VALUE_BYTES = 4096;
31
+ const MAX_COOKIE_EXPIRES_SECONDS = 253402300799;
32
+
33
+ const REASONS = Object.freeze({
34
+ ABSENT: 'absent',
35
+ EMPTY: 'empty',
36
+ MALFORMED: 'malformed',
37
+ EXPIRED: 'expired',
38
+ BAD_SCOPE: 'bad_scope',
39
+ UNAUTHORIZED_ORIGIN: 'unauthorized_origin',
40
+ BAD_EXPIRES: 'bad_expires',
41
+ BAD_NAME: 'bad_name',
42
+ BAD_VALUE: 'bad_value',
43
+ BAD_SIZE: 'bad_size',
44
+ PAYLOAD_TOO_LARGE: 'payload_too_large',
45
+ ACCEPTED: 'accepted',
46
+ REJECTED: 'rejected',
47
+ });
48
+
49
+ function _parseToArray(raw) {
50
+ if (Array.isArray(raw)) return { arr: raw, source: 'array' };
51
+ if (typeof raw === 'string') {
52
+ const text = raw.trim();
53
+ if (!text) return { arr: [], source: 'empty_string' };
54
+ try {
55
+ return { arr: JSON.parse(text), source: 'json_string' };
56
+ } catch {
57
+ try {
58
+ return { arr: JSON.parse(Buffer.from(text, 'base64').toString('utf8')), source: 'base64_json' };
59
+ } catch {
60
+ return { arr: null, source: 'unparsable_string' };
61
+ }
62
+ }
63
+ }
64
+ if (raw && typeof raw === 'object') {
65
+ if (Array.isArray(raw.cookies)) return { arr: raw.cookies, source: 'object.cookies' };
66
+ return { arr: null, source: 'object' };
67
+ }
68
+ return { arr: null, source: 'absent' };
69
+ }
70
+
71
+ function _authorizedDomain(domain) {
72
+ if (typeof domain !== 'string' || !domain.trim()) return null;
73
+ const host = domain.trim().toLowerCase().replace(/^\./, '');
74
+ if (host === 'x.com' || host.endsWith('.x.com') || host === 'twitter.com' || host.endsWith('.twitter.com')) {
75
+ return host;
76
+ }
77
+ return null;
78
+ }
79
+
80
+ function _canonSameSite(value) {
81
+ if (value == null) return null;
82
+ switch (String(value).trim().toLowerCase()) {
83
+ case 'strict': return 'Strict';
84
+ case 'lax': return 'Lax';
85
+ case 'none': return 'None';
86
+ default: return null;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Resolve an expiry to Playwright's seconds contract. A millisecond timestamp is
92
+ * converted to the SAME wall-clock instant. Never extends an expiry.
93
+ * @returns {{present:boolean, usable?:boolean, expired?:boolean, seconds?:number}}
94
+ */
95
+ function _resolveExpires(value, nowMs) {
96
+ if (value == null || value === '') return { present: false };
97
+ const n = Number(value);
98
+ if (!Number.isFinite(n)) return { present: true, usable: false };
99
+ if (n === -1) return { present: true, usable: true, seconds: -1 };
100
+ if (n <= 0 || n > MAX_COOKIE_EXPIRES_SECONDS * 1000) return { present: true, usable: false };
101
+ const seconds = n >= 1e12 ? Math.floor(n / 1000) : n;
102
+ if (seconds > MAX_COOKIE_EXPIRES_SECONDS) return { present: true, usable: false };
103
+ // A persistent cookie whose instant is already in the past cannot restore a
104
+ // session. Dropping it (rather than writing an expired cookie) is the honest
105
+ // outcome and avoids a misleading "restored" count.
106
+ if (seconds * 1000 <= nowMs) return { present: true, usable: true, expired: true, seconds };
107
+ return { present: true, usable: true, seconds };
108
+ }
109
+
110
+ function _buildHostOnlyUrl(host, pathValue) {
111
+ const p = typeof pathValue === 'string' && pathValue.startsWith('/') ? pathValue : '/';
112
+ return `https://${host}${p}`;
113
+ }
114
+
115
+ /**
116
+ * Normalize a cookie payload on the device.
117
+ * @returns {{cookies:object[], state:string, source:string, accepted:number, rejected:number, reasons:object}}
118
+ */
119
+ function prepareCookies(raw, opts = {}) {
120
+ const nowMs = Number.isFinite(opts.now) ? opts.now : Date.now();
121
+ const empty = (state, source) => ({
122
+ cookies: [], state, source: source || 'absent', accepted: 0, rejected: 0, reasons: {},
123
+ });
124
+
125
+ if (raw == null || raw === '') return empty(REASONS.ABSENT, 'absent');
126
+
127
+ const { arr, source } = _parseToArray(raw);
128
+ if (!Array.isArray(arr)) return empty(REASONS.MALFORMED, source);
129
+ if (arr.length === 0) return empty(REASONS.EMPTY, source);
130
+
131
+ const cookies = [];
132
+ const reasons = {};
133
+ const bump = (r) => { reasons[r] = (reasons[r] || 0) + 1; };
134
+ let rejected = 0;
135
+ let totalBytes = 0;
136
+
137
+ for (const c of arr) {
138
+ if (cookies.length >= MAX_COOKIES) { bump(REASONS.BAD_SCOPE); rejected += 1; continue; }
139
+ if (!c || typeof c !== 'object' || Array.isArray(c)) { bump(REASONS.MALFORMED); rejected += 1; continue; }
140
+ if (typeof c.name !== 'string' || !c.name) { bump(REASONS.BAD_NAME); rejected += 1; continue; }
141
+ if (c.value == null) { bump(REASONS.BAD_VALUE); rejected += 1; continue; }
142
+ if (String(c.value).length > MAX_COOKIE_VALUE_BYTES) { bump(REASONS.BAD_SIZE); rejected += 1; continue; }
143
+
144
+ const exp = _resolveExpires(c.expires, nowMs);
145
+ // Match the backend contract: an unusable expiry is omitted (session-cookie
146
+ // fallback), a provably expired persistent cookie is dropped.
147
+ if (exp.present && !exp.usable) bump(REASONS.BAD_EXPIRES);
148
+ if (exp.present && exp.expired) { bump(REASONS.EXPIRED); rejected += 1; continue; }
149
+
150
+ const out = { name: c.name, value: String(c.value) };
151
+
152
+ const domainHost = _authorizedDomain(c.domain);
153
+ const urlAuthorized = c.url ? isAuthorizedXUrl(c.url) : false;
154
+
155
+ if (domainHost) {
156
+ if (c.hostOnly === true) {
157
+ // Preserve host-only semantics: a url-scoped cookie is host-only and
158
+ // carries the path, instead of promoting it to a domain cookie.
159
+ out.url = _buildHostOnlyUrl(domainHost, c.path);
160
+ } else {
161
+ out.domain = c.domain;
162
+ out.path = (typeof c.path === 'string' && c.path) ? c.path : '/';
163
+ }
164
+ } else if (urlAuthorized) {
165
+ out.url = c.url;
166
+ } else {
167
+ bump(c.domain || c.url ? REASONS.UNAUTHORIZED_ORIGIN : REASONS.BAD_SCOPE);
168
+ rejected += 1;
169
+ continue;
170
+ }
171
+
172
+ if (exp.present && exp.usable && exp.seconds != null) out.expires = exp.seconds;
173
+ if (typeof c.httpOnly === 'boolean') out.httpOnly = c.httpOnly;
174
+ if (typeof c.secure === 'boolean') out.secure = c.secure;
175
+ if (c.sameSite != null) {
176
+ const sameSite = _canonSameSite(c.sameSite);
177
+ if (sameSite) out.sameSite = sameSite;
178
+ else if (String(c.sameSite).trim()) bump('unrecognized_samesite');
179
+ }
180
+ // Playwright does not accept a partitionKey field. Counting it keeps the
181
+ // rejection observable without inventing unsupported semantics.
182
+ if (c.partitionKey != null || c.partitioned === true) bump('partitioning_unsupported');
183
+
184
+ const approxBytes = JSON.stringify(out).length + 2;
185
+ if (totalBytes + approxBytes > MAX_TOTAL_COOKIE_BYTES) {
186
+ bump(REASONS.PAYLOAD_TOO_LARGE);
187
+ rejected += 1;
188
+ continue;
189
+ }
190
+ totalBytes += approxBytes;
191
+
192
+ cookies.push(out);
193
+ }
194
+
195
+ let state;
196
+ if (cookies.length === 0) {
197
+ state = Object.keys(reasons).length ? REASONS.REJECTED : REASONS.MALFORMED;
198
+ } else {
199
+ state = REASONS.ACCEPTED;
200
+ }
201
+ return { cookies, state, source, accepted: cookies.length, rejected, reasons };
202
+ }
203
+
204
+ /**
205
+ * Apply cookies to a live Playwright context. Never throws; returns safe counts.
206
+ * @returns {Promise<{ok:boolean, state:string, applied:number, rejected:number, reason:string|null, reasons:object}>}
207
+ */
208
+ async function applyCookies(context, raw) {
209
+ const prepared = prepareCookies(raw);
210
+ if (prepared.cookies.length === 0) {
211
+ return {
212
+ ok: false,
213
+ state: prepared.state,
214
+ applied: 0,
215
+ rejected: prepared.rejected,
216
+ reason: prepared.state === REASONS.ABSENT ? 'cookies_absent'
217
+ : prepared.state === REASONS.EMPTY ? 'cookies_empty'
218
+ : prepared.state === REASONS.MALFORMED ? 'cookies_malformed'
219
+ : 'cookies_rejected',
220
+ reasons: prepared.reasons,
221
+ };
222
+ }
223
+ try {
224
+ if (!context || typeof context.addCookies !== 'function') {
225
+ return { ok: false, state: 'rejected', applied: 0, rejected: prepared.rejected + prepared.cookies.length, reason: 'cookie_context_unavailable', reasons: prepared.reasons };
226
+ }
227
+ await context.addCookies(prepared.cookies);
228
+ return {
229
+ ok: true,
230
+ state: REASONS.ACCEPTED,
231
+ applied: prepared.cookies.length,
232
+ rejected: prepared.rejected,
233
+ reason: prepared.rejected ? 'some_cookies_rejected' : null,
234
+ reasons: prepared.reasons,
235
+ };
236
+ } catch (err) {
237
+ // Deployments differ in exactly which attribute Playwright rejects. We keep
238
+ // the reason coarse and NEVER echo the value/exception.
239
+ return { ok: false, state: 'rejected', applied: 0, rejected: prepared.cookies.length + prepared.rejected, reason: 'cookie_injection_failed', reasons: prepared.reasons };
240
+ }
241
+ }
242
+
243
+ /** Presence test used to decide whether a bootstrap restore is even eligible. */
244
+ function hasUsableCookies(raw) {
245
+ return prepareCookies(raw).cookies.length > 0;
246
+ }
247
+
248
+ module.exports = {
249
+ MAX_COOKIES,
250
+ MAX_COOKIE_EXPIRES_SECONDS,
251
+ REASONS,
252
+ prepareCookies,
253
+ applyCookies,
254
+ hasUsableCookies,
255
+ };
@@ -470,37 +470,58 @@ function collectDeviceMetadata() {
470
470
  async function enroll(serverOrigin, opts) {
471
471
  opts = opts || {};
472
472
  const chromePath = opts.chromePath || null;
473
+ const recoveringDeviceId = opts.recoverDeviceId || null;
474
+ const request = typeof opts.request === 'function' ? opts.request : _request;
475
+ const openBrowserFn = typeof opts.openBrowser === 'function' ? opts.openBrowser : openBrowser;
476
+ if (recoveringDeviceId && !/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(recoveringDeviceId)) {
477
+ throw new Error('Invalid recoverDeviceId');
478
+ }
479
+ if (recoveringDeviceId && !opts.keyPair) {
480
+ throw new Error('Recovery requires the existing device key; refusing to mint a new identity');
481
+ }
473
482
 
474
- // 1. Generate Ed25519 key pair
475
- const keyPair = generateKeyPair();
483
+ // 1. Generate Ed25519 key pair (or reuse the existing key for recovery).
484
+ // Recovery MUST reuse the existing public key: the server only reactivates the
485
+ // SAME device record when the enrolling key matches it, preserving profiles.
486
+ const keyPair = opts.keyPair
487
+ ? { publicKeyB64Url: opts.keyPair.publicKeyB64Url, publicKeyFingerprint: opts.keyPair.publicKeyFingerprint }
488
+ : generateKeyPair();
489
+ if (!keyPair.publicKeyB64Url || !keyPair.publicKeyFingerprint) {
490
+ throw new Error('Invalid existing key material for recovery');
491
+ }
476
492
 
477
- // 2. Store the private key securely (fail closed)
478
- // Server-scoped: the key is stored in a per-server directory so that
479
- // localhost and production identities never interfere.
480
- try {
481
- await storePrivateKey(keyPair.privateKeyB64Url, { serverOrigin });
482
- } catch (e) {
483
- const platform = os.platform();
484
- const guidance = platform === 'win32'
485
- ? 'On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available for the current user.'
486
- : 'On Linux, install gnome-keyring or seahorse (libsecret).';
487
- throw new Error(
488
- 'Secure key storage is unavailable on this system.\n' +
489
- 'The private key cannot be stored safely.\n' +
490
- guidance + '\n' +
491
- 'Error: ' + e.message
492
- );
493
+ // 2. Store the private key securely (fail closed) — only for a NEW key.
494
+ // Recovery reuses the already-stored key and never overwrites it before the
495
+ // owner approves, so a denied/expired request cannot destroy the identity.
496
+ if (!opts.keyPair) {
497
+ try {
498
+ await storePrivateKey(keyPair.privateKeyB64Url, { serverOrigin });
499
+ } catch (e) {
500
+ const platform = os.platform();
501
+ const guidance = platform === 'win32'
502
+ ? 'On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available for the current user.'
503
+ : 'On Linux, install gnome-keyring or seahorse (libsecret).';
504
+ throw new Error(
505
+ 'Secure key storage is unavailable on this system.\n' +
506
+ 'The private key cannot be stored safely.\n' +
507
+ guidance + '\n' +
508
+ 'Error: ' + e.message
509
+ );
510
+ }
493
511
  }
494
512
 
495
513
  // 3. Collect device metadata
496
514
  const deviceMeta = collectDeviceMetadata();
497
515
 
498
516
  // 4. Start enrollment
499
- console.log('\nThis computer is not authorized yet.\n');
500
- console.log('Generating device key pair...');
517
+ console.log(recoveringDeviceId
518
+ ? '\nRequesting recovery of the existing device identity...\n'
519
+ : '\nThis computer is not authorized yet.\n');
520
+ if (!recoveringDeviceId) console.log('Generating device key pair...');
501
521
  console.log(` Public-key fingerprint: ${keyPair.publicKeyFingerprint.slice(0, 4)}…${keyPair.publicKeyFingerprint.slice(-4)}`);
522
+ if (recoveringDeviceId) console.log(` Existing device ID: ${recoveringDeviceId}`);
502
523
 
503
- const startResponse = await _request('POST', `${serverOrigin}/api/agent/enrollment/start`, {
524
+ const startResponse = await request('POST', `${serverOrigin}/api/agent/enrollment/start`, {
504
525
  publicKey: keyPair.publicKeyB64Url,
505
526
  publicKeyFingerprint: keyPair.publicKeyFingerprint,
506
527
  deviceName: deviceMeta.deviceName,
@@ -508,6 +529,7 @@ async function enroll(serverOrigin, opts) {
508
529
  architecture: deviceMeta.architecture,
509
530
  chromeVersion: deviceMeta.chromeVersion,
510
531
  machineFingerprintHash: deviceMeta.machineFingerprintHash,
532
+ ...(recoveringDeviceId ? { recoverDeviceId: recoveringDeviceId } : {}),
511
533
  });
512
534
 
513
535
  if (startResponse.status !== 200) {
@@ -529,19 +551,19 @@ async function enroll(serverOrigin, opts) {
529
551
  // second fallback here — that was the source of the duplicate message.
530
552
  // await ensures we don't race the polling loop against an in-flight launch,
531
553
  // but the polling loop continues regardless of whether the browser opened.
532
- await openBrowser(authorizationUrl, { chromePath });
554
+ await openBrowserFn(authorizationUrl, { chromePath });
533
555
 
534
556
  // 6. Poll for approval
535
557
  console.log('\nWaiting for approval...');
536
558
 
537
- const pollInterval = 3000; // 3 seconds
559
+ const pollInterval = Number.isFinite(opts.pollIntervalMs) ? Math.max(1, opts.pollIntervalMs) : 3000; // 3 seconds
538
560
  const maxPollTime = (startResponse.body.expiresIn || 600) * 1000;
539
561
  const startTime = Date.now();
540
562
 
541
563
  while (Date.now() - startTime < maxPollTime) {
542
564
  await new Promise(resolve => setTimeout(resolve, pollInterval));
543
565
 
544
- const statusResponse = await _request(
566
+ const statusResponse = await request(
545
567
  'GET',
546
568
  `${serverOrigin}/api/agent/enrollment/${requestId}/status`,
547
569
  null,
@@ -556,21 +578,24 @@ async function enroll(serverOrigin, opts) {
556
578
  const status = statusResponse.body;
557
579
 
558
580
  if (status.state === 'approved') {
559
- // 7. Save device metadata (non-secret, server-scoped)
581
+ // 7. Save device metadata (non-secret, server-scoped). Recovery keeps the
582
+ // original createdAt (deviceId is unchanged).
560
583
  saveMetadata({
561
584
  deviceId: status.deviceId,
562
585
  publicKeyB64Url: keyPair.publicKeyB64Url,
563
586
  publicKeyFingerprint: keyPair.publicKeyFingerprint,
564
587
  deviceName: deviceMeta.deviceName,
565
588
  serverOrigin,
589
+ createdAt: (opts.existingMeta && opts.existingMeta.createdAt) || undefined,
566
590
  }, { serverOrigin });
567
591
 
568
- console.log('✓ Computer authorized');
592
+ console.log(status.recovered ? '✓ Existing device recovered (same device ID)' : '✓ Computer authorized');
569
593
  console.log(`✓ Device ID: ${status.deviceId}`);
570
594
 
571
595
  return {
572
596
  deviceId: status.deviceId,
573
597
  deviceCertificate: status.deviceCertificate,
598
+ recovered: status.recovered === true,
574
599
  };
575
600
  }
576
601
 
package/src/index.js CHANGED
@@ -333,40 +333,11 @@ function checkProxyHealth(proxyStr) {
333
333
  });
334
334
  }
335
335
  async function injectCookies(context, cookiesData) {
336
- if (!cookiesData) return;
337
- try {
338
- let cookies = [];
339
- if (typeof cookiesData === 'string') {
340
- // Try JSON parse, then base64, then raw
341
- try { cookies = JSON.parse(cookiesData); }
342
- catch { try { cookies = JSON.parse(Buffer.from(cookiesData, 'base64').toString()); } catch {} }
343
- } else if (Array.isArray(cookiesData)) {
344
- cookies = cookiesData;
345
- }
346
- if (cookies.length === 0) {
347
- log(`[session] No cookies to inject (empty)`);
348
- return;
349
- }
350
-
351
- // Inject cookies EXACTLY as stored — do NOT modify domains, sameSite,
352
- // or any other field. The stored data is the source of truth.
353
- // Only add required Playwright fields if missing (path, secure, httpOnly).
354
- const normalized = cookies.map(c => ({
355
- name: c.name,
356
- value: c.value,
357
- domain: c.domain,
358
- path: c.path || '/',
359
- expires: c.expires || -1,
360
- httpOnly: c.httpOnly !== undefined ? c.httpOnly : false,
361
- secure: c.secure !== undefined ? c.secure : true,
362
- sameSite: c.sameSite || 'None',
363
- }));
364
-
365
- await context.addCookies(normalized);
366
- log(`[session] Injected ${normalized.length} cookies (as stored, unmodified)`);
367
- } catch (err) {
368
- log(`[session] Cookie injection error: ${err.message}`);
369
- }
336
+ const { applyCookies } = require('./cookieInjection');
337
+ const result = await applyCookies(context, cookiesData);
338
+ if (result.ok) log(`[session] Restored ${result.applied} cookies (as stored, unmodified)`);
339
+ else log(`[session] Cookie restore not applied: ${result.reason || result.state}`);
340
+ return result;
370
341
  }
371
342
 
372
343
  /**
@@ -588,6 +559,20 @@ async function startSession(accountId, options = {}, lease) {
588
559
  ],
589
560
  };
590
561
 
562
+ // ── 2.1.5 shared Chromium launch hardening ──────────────────────────────────
563
+ // Keep the extension subsystem available on a branded Chrome (Playwright would
564
+ // otherwise pass --disable-extensions, breaking the Chrome Web Store), and
565
+ // capture a sanitized NetLog only when the operator enabled it.
566
+ try {
567
+ const browserLaunch = require('./browserLaunch');
568
+ const connectivity = require('./browserConnectivity');
569
+ if (browserLaunch.supportsChromeWebStore(launchOptions.executablePath)) {
570
+ launchOptions.ignoreDefaultArgs = browserLaunch.PLAYWRIGHT_DEFAULT_ARGS_TO_DROP.slice();
571
+ }
572
+ const netlogPath = connectivity.resolveNetlogPath();
573
+ if (netlogPath) launchOptions.args.push(...connectivity.netlogLaunchArgs(netlogPath));
574
+ } catch { /* launch safety is unaffected */ }
575
+
591
576
  // ── Extension loading (Chromium mode) ──
592
577
  // Chromium extensions are loaded via --load-extension= flag, not by copying
593
578
  // .xpi files into the profile. The EXTENSIONS_DIR is still created for future
@@ -615,6 +600,18 @@ async function startSession(accountId, options = {}, lease) {
615
600
  const context = await chromium.launchPersistentContext(profileDir, launchOptions);
616
601
  const page = context.pages()[0] || await context.newPage();
617
602
 
603
+ // ── 2.1.5 navigation containment ─────────────────────────────────────────
604
+ // Bound navigation for every page and replace a tab stuck on about:blank
605
+ // (proxy that never answers CONNECT) with an actionable diagnostic page.
606
+ try {
607
+ require('./browserConnectivity').installNavigationGuard(context, {
608
+ accountLabel: String(accountId),
609
+ onEvent: (event, detail) => {
610
+ try { log(`[session] navigation guard: ${event} ${JSON.stringify(detail || {})}`); } catch { /* safe */ }
611
+ },
612
+ });
613
+ } catch { /* containment is best effort */ }
614
+
618
615
  // ── Bandwidth saver: block heavy media from x.com / twitter.com CDNs ──
619
616
  // Residential proxy bandwidth is expensive. Tweets, timeline scrolling,
620
617
  // and profile pages pull in megabytes of images/videos/fonts that the
@@ -718,12 +715,28 @@ async function startSession(accountId, options = {}, lease) {
718
715
  log(`[session] HTTP header injection failed (non-fatal): ${e.message}`);
719
716
  }
720
717
 
721
- // Inject cookies BEFORE navigation so the session is authenticated
722
- if (options.cookies) {
723
- await injectCookies(context, options.cookies);
724
- } else {
725
- log(`[session] No cookies provided for account ${accountId} — will need manual login`);
718
+ // ── Canonical startup: verify the existing session BEFORE writing cookies ──
719
+ // A warm, newer native session must not be overwritten by a stale import. If
720
+ // the profile is proven signed out (or has no auth cookies), eligible stored
721
+ // cookies are applied with their original scope and the result is verified
722
+ // again. Same sequence as the machine worker and the direct runtime.
723
+ const { restoreAndVerify } = require('./sessionAuth');
724
+ const { applyCookies } = require('./cookieInjection');
725
+ const startupAuth = await restoreAndVerify({
726
+ page,
727
+ context,
728
+ cookies: Array.isArray(options.cookies) ? options.cookies : null,
729
+ url: options.url || null,
730
+ expectedUsername: options.username || null,
731
+ applyCookies,
732
+ navigationTimeoutMs: 60000,
733
+ verifyTimeoutMs: 8000,
734
+ });
735
+ if (startupAuth.authState) {
736
+ log(`[session] Startup auth state for account ${accountId}: ${startupAuth.authState}${startupAuth.reason ? ' (' + startupAuth.reason + ')' : ''}`);
726
737
  }
738
+ // Wait for network to settle (best-effort; never changes the auth verdict)
739
+ await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {});
727
740
 
728
741
  // Configure DBC (Death By Captcha) if credentials provided
729
742
  if (options.dbcUsername && options.dbcPassword) {
@@ -732,21 +745,10 @@ async function startSession(accountId, options = {}, lease) {
732
745
  dbc.configure(options.dbcUsername, options.dbcPassword);
733
746
  log(`[session] DBC configured for captcha solving`);
734
747
  } catch (e) {
735
- log(`[session] DBC setup failed: ${e.message}`);
748
+ log(`[session] DBC setup failed (non-fatal)`);
736
749
  }
737
750
  }
738
751
 
739
- // Navigate to x.com
740
- await page.goto('https://x.com/home', {
741
- waitUntil: 'domcontentloaded',
742
- timeout: 60000,
743
- }).catch((e) => {
744
- log(`[session] Navigation to x.com/home failed: ${e.message}`);
745
- });
746
-
747
- // Wait for network to settle
748
- await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {});
749
-
750
752
  // ── Session warm-up: simulate human browsing before first action ──────
751
753
  // Real users don't immediately perform actions — they scroll, read, hover
752
754
  try {
@@ -801,7 +803,7 @@ async function startSession(accountId, options = {}, lease) {
801
803
  log(`[session] Page closed for account ${accountId}`);
802
804
  });
803
805
 
804
- const sessionObj = { context, page, profileDir, setMediaAllowed };
806
+ const sessionObj = { context, page, profileDir, setMediaAllowed, lastAuth: startupAuth, expectedUsername: options.username || null };
805
807
  // Phase 3: bind the lease credential to the active session (in-memory only).
806
808
  // It is echoed back in every session-status/stop-ack/error message so the
807
809
  // server can verify the holder; never logged, never persisted to disk.
@@ -812,7 +814,20 @@ async function startSession(accountId, options = {}, lease) {
812
814
  // Report status to VPS (lease-bound so the server can activate the lease).
813
815
  sendToServer(leaseClient.boundStatusMessage(sessionObj, accountId, 'running'));
814
816
 
815
- return { success: true, sessionId: accountId, status: 'running', message: 'Browser opened locally on customer PC', migrationRequired: !!migrationRequired };
817
+ return {
818
+ success: true,
819
+ sessionId: accountId,
820
+ status: 'running',
821
+ message: 'Browser opened locally on customer PC',
822
+ migrationRequired: !!migrationRequired,
823
+ browserReady: true,
824
+ authState: startupAuth.authState,
825
+ loggedIn: startupAuth.authState === 'authenticated',
826
+ reason: startupAuth.reason || null,
827
+ stage: startupAuth.stage || null,
828
+ handle: startupAuth.handle || null,
829
+ cookieState: startupAuth.cookieState || null,
830
+ };
816
831
  } catch (err) {
817
832
  lastError = err.message;
818
833
  log(`[session] Failed to start for account ${accountId}: ${err.message}`);