@xkwdstore/agent 2.1.4 → 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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,130 @@
1
+ # Changelog — @xkwdstore/agent
2
+
3
+ ## 2.1.5 — browser connectivity, capability-based proxy health, Chrome Web Store support
4
+
5
+ ### Fixed
6
+ - **Indefinite `about:blank` on a stalled navigation.** A proxy that accepts TCP
7
+ but never answers `CONNECT` left Chromium pending forever: the tab stayed on
8
+ `about:blank` with a loading indicator, the caller's timeout was the only stop,
9
+ and several call sites discarded that error. Every context now gets a bounded
10
+ navigation timeout and a stall guard that watches the **main-frame document
11
+ request through CDP** (`Network.requestWillBeSent` / `responseReceived` /
12
+ `loadingFinished` / `loadingFailed`), so:
13
+ - a page that merely streams its body slowly is never interrupted (headers
14
+ received = progress; redirects reset the budget);
15
+ - downloads and cancelled navigations are ignored;
16
+ - a genuinely stalled document is replaced, after the stall budget, by a
17
+ script-free diagnostic page with the typed failure code, target host, session,
18
+ stage/reason, a **retry link** and explicit statements that the profile,
19
+ cookies and extensions were untouched and the proxy was not bypassed;
20
+ - a successful commit resets the guard, so a later stall is still caught.
21
+ - **Failed navigations now carry a typed, actionable code** on the direct and
22
+ machine-worker runtimes (`NAVIGATION_TIMEOUT`, `PROXY_TUNNEL_FAILED`,
23
+ `NAVIGATION_DNS_FAILED`, `TLS_CERTIFICATE_ERROR`, `ORIGIN_HTTP_ERROR`,
24
+ `ORIGIN_INVALID_RESPONSE`, `NETWORK_UNAVAILABLE`, `NAVIGATION_UNREACHABLE`,
25
+ `NAVIGATION_ABORTED`, `NAVIGATION_BLOCKED`, `NAVIGATION_STALLED`). Startup
26
+ verification paints the diagnostic page when the startup navigation failed.
27
+ - **Proxy validation is capability-based, not a single-endpoint ping.**
28
+ `api.ipify.org` answering no longer means "healthy". Every managed destination
29
+ is probed through the proxy (DNS/TCP/TLS/HTTP, HTTP CONNECT or SOCKS5):
30
+ Google Search, Chrome Web Store, Google accounts, gstatic, clients2,
31
+ `update.googleapis.com`, example.com, x.com, api.ipify.org. States:
32
+ `HEALTHY`, `DEGRADED`, `AUTHENTICATION_FAILED`, `CONNECT_TIMEOUT`, `DNS_FAILED`,
33
+ `TLS_FAILED`, `DESTINATION_UNREACHABLE`, `DESTINATION_RESTRICTED`,
34
+ `CONNECTION_REFUSED`, `UNREACHABLE`, `UNKNOWN`.
35
+ `DESTINATION_RESTRICTED` is reported with evidence: the proxy must carry a
36
+ baseline destination while a required destination is denied or refused.
37
+ Results are cached for 60 s and rate limited per proxy endpoint (2/min) and per
38
+ account at the API (6/min) to protect proxy bandwidth. No automatic failover
39
+ and no direct fallback.
40
+ - **Device authentication retry storm (2.1.5, phase 4).** A revoked or replaced
41
+ device was retried forever at the 60 s backoff cap: the production broker log
42
+ accumulated **43,576** `Device authentication failed` lines over ~7 weeks.
43
+ Authentication is now a permanent failure class: at most **3** consecutive
44
+ attempts with exponential backoff, then retries stop, a single actionable
45
+ message is written, and the state is exposed as **reauthorization required**
46
+ (`status`/`doctor` + `runtime/broker-health.json`). The device key and metadata
47
+ are **never** deleted on 4003; only explicit `logout`/`revoke-local` removes
48
+ them.
49
+ - **Device recovery without losing profiles (2.1.5, phase 4).** The backend now
50
+ advertises `device-recovery-v1`; `xkwd-agent recover` re-authorizes the
51
+ **same deviceId** with the existing key after owner approval. This preserves
52
+ device-bound browser profiles (cookies/sessions) instead of minting a new
53
+ device id, which would quarantine them. Recovery is allowed only for a device
54
+ revoked by the normal single-device replacement, never for an owner/security
55
+ revocation, and the dashboard warns that approving it revokes the currently
56
+ active device (the tenant permits one active protocol-v2 device per user).
57
+ The deployed backend does not advertise the capability yet, so the CLI refuses
58
+ rather than silently creating a new identity.
59
+ - **Silent tunnel drops** are detected and distinguished from timeouts.
60
+ - **IPv4/IPv6** capability of the proxy host is reported (resolution + TCP per
61
+ family), and the protocol is validated (`http`, `https`, `socks5`, `socks5h`,
62
+ `socks4`).
63
+ - **Atomic JSON writes failed on Windows** with `EPERM: fsync` because the live
64
+ file was opened read-only before `fsync`. Windows `FlushFileBuffers` requires a
65
+ writable handle; the live file is now opened `r+` (with a read-only fallback on
66
+ POSIX). This was a real cross-platform defect, not an environmental one, and it
67
+ caused 16 backend test failures on Windows.
68
+
69
+ ### Added
70
+ - `src/browserConnectivity.js` — classification, bounded navigation, CDP stall
71
+ guard, public-endpoint probes (HTTP CONNECT + SOCKS5), diagnostic page, NetLog
72
+ sanitization.
73
+ - `src/proxyCapability.js` — capability-based proxy health (per-destination
74
+ matrix, overall state, cache, rate limit, IP families, protocol check).
75
+ - `src/browserLaunch.js` — one shared Chromium launch-options builder used by the
76
+ machine worker, the broker/direct runtime and the legacy runtime. Drops
77
+ Playwright's `--disable-extensions` for branded Chrome/Edge and reports
78
+ `unpackedExtensionLoading: false` (branded Chrome ≥137 ignores
79
+ `--load-extension` — verified on Chrome 157.0.8103.80 and 158.0.8127.38: `extension_service.cc` logs
80
+ "not allowed in Google Chrome, ignoring").
81
+ - Typed read-only command `connectivity-test` (lease-optional, SSRF-limited to the
82
+ documented endpoint allowlist) and backend route
83
+ `POST /api/proxy/account/:accountId/connectivity`, plus per-destination results
84
+ in the proxy management UI (`ProxyConnectivityPanel`).
85
+ - `scripts/browser-connectivity-diag.js` — operator CLI: direct or through-proxy
86
+ capability matrix, optional explicit direct comparison, optional sanitized
87
+ NetLog capture.
88
+ - NetLog handling: capture remains **opt-in** (`XKWDSTORE_NETLOG_DIR`); files are
89
+ sanitized in place (header blocks dropped, credential keys redacted, URL
90
+ query/fragment/userinfo stripped). No raw copy remains.
91
+ - `getStatus` now reports `pageStalled`, the browser family/capabilities and the
92
+ navigation-guard state.
93
+
94
+ ### Verified
95
+ - Re-verified on Chrome 158.0.8127.38 (2026-11-24): Web Store home/search/live
96
+ detail render, the live item exposes a real "Add to Chrome" control, the
97
+ navigation guard contains stalls and recovers through retry, and branded
98
+ Chrome still refuses unpacked extension loading (0 service workers; its own
99
+ log: `--disable-extensions-except is not allowed in Google Chrome, ignoring.`).
100
+ - Real managed Chrome 157 + a preserved production profile load all Google
101
+ endpoints and X (200).
102
+ - A controlled proxy that permits X/example.com but denies every Google host is
103
+ reported `DESTINATION_RESTRICTED` (Google 0/6, X healthy) and the browser shows
104
+ `PROXY_TUNNEL_FAILED` instead of a blank tab.
105
+ - A black-holed proxy is reported `CONNECT_TIMEOUT`; missing credentials
106
+ `AUTHENTICATION_FAILED`; a dead port `CONNECTION_REFUSED`.
107
+ - Slow body transfer is not interrupted; a stalled navigation is contained and
108
+ the retry link resumes browsing.
109
+ - Chrome Web Store: live item pages render with "Add to Chrome"; installation is
110
+ gated by Chrome's native consent dialog (human confirmation, not automatable).
111
+
112
+ ### Known limitations
113
+ - Branded Google Chrome ignores `--load-extension`, so unpacked extension loading
114
+ requires Chromium/Chrome-for-Testing (or a Web Store install with human
115
+ confirmation). No feature assumes otherwise.
116
+ - A very slow **first byte** beyond the stall budget (default 30 s) is treated as
117
+ a stall by design; tune `XKWDSTORE_NAV_STALL_TIMEOUT_MS`.
118
+ - One active protocol-v2 device per user. Approving a new device (or recovering
119
+ this one) revokes the currently active device by design; the dashboard now
120
+ warns before approval. Recovery preserves the recovered device's profiles, but
121
+ the displaced device stops connecting until it is recovered in turn.
122
+ - `xkwd-agent recover` requires a backend that advertises `device-recovery-v1`;
123
+ against the currently deployed backend it refuses instead of creating a new
124
+ device id.
125
+
126
+ ## 2.1.4 — machine-wide hardening (published)
127
+
128
+ Profile ACL generation that keeps the interactive session user able to launch
129
+ Chromium, packaging completeness, broker/worker lifecycle and the X session
130
+ restoration pipeline. See `reports/` for the authoritative publication state.
package/README.md CHANGED
@@ -5,8 +5,9 @@ Terminal-only, cryptographically authenticated CLI for XKWDStore browser automat
5
5
  ## Installation
6
6
 
7
7
  > **@xkwdstore/agent 2.1.4 is the last version published on npm.**
8
+ > **The source tree is prepared as 2.1.5 and is NOT published yet.**
8
9
  >
9
- > The current source version is **2.1.4** (machine-wide hardening). It is
10
+ > The current source version is **2.1.5** (machine-wide hardening). It is
10
11
  > NOT claimed to be published unless the release workflow has published it — see
11
12
  > `reports/` for the authoritative publication state.
12
13
 
@@ -29,7 +30,7 @@ curl -L -o "%TEMP%\xkwdstore-install.ps1" https://raw.githubusercontent.com/Essa
29
30
  The generated launcher runs the pinned command:
30
31
 
31
32
  ```powershell
32
- npx --yes @xkwdstore/agent@2.1.4 start
33
+ npx --yes @xkwdstore/agent@2.1.5 start
33
34
  ```
34
35
 
35
36
  Automated installer tests use `-NoLaunch` or a mocked `npx` command so the
@@ -86,6 +87,7 @@ No browser approval is needed unless:
86
87
  |---------|-------------|
87
88
  | `start` | Start the agent (connect, run browser sessions) |
88
89
  | `status` | Show device and connection status |
90
+ | `recover` | Re-authorize this device after replacement (owner approval; preserves profiles) |
89
91
  | `logout` | Delete local device identity (requires re-authorization) |
90
92
  | `revoke-local` | Delete local device identity and credentials |
91
93
  | `doctor` | Run diagnostic checks |
@@ -203,7 +205,7 @@ The agent does NOT update itself. To use a newer version, change the version
203
205
  number in the command. The pinned command for this release is:
204
206
 
205
207
  ```powershell
206
- npx --yes @xkwdstore/agent@2.1.4 start
208
+ npx --yes @xkwdstore/agent@2.1.5 start
207
209
  ```
208
210
 
209
211
  > 2.1.0 is the current local agent version (machine-wide hardening).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xkwdstore/agent",
3
- "version": "2.1.4",
3
+ "version": "2.1.5",
4
4
  "description": "XKWDStore Agent — machine-wide, cryptographically authenticated CLI for isolated browser automation",
5
5
  "main": "src/cli.js",
6
6
  "bin": {
@@ -22,7 +22,8 @@
22
22
  "scripts/broker-service-host.cs",
23
23
  "scripts/session-launcher.cs",
24
24
  "README.md",
25
- "LICENSE"
25
+ "LICENSE",
26
+ "CHANGELOG.md"
26
27
  ],
27
28
  "dependencies": {
28
29
  "otpauth": "^9.3.0",
@@ -39,4 +40,4 @@
39
40
  "publishConfig": {
40
41
  "access": "public"
41
42
  }
42
- }
43
+ }
@@ -26,7 +26,7 @@
26
26
  # to a worker in the active session. This script installs both halves.
27
27
  #
28
28
  # Options:
29
- # -AgentVersion <ver> pinned agent version (default 2.1.0)
29
+ # -AgentVersion <ver> pinned agent version (default 2.1.5)
30
30
  # -Server <url> server origin (default https://x.kwdstore.com)
31
31
  # -ServiceAccount <s> service identity (default LocalSystem)
32
32
  # -Uninstall remove service + startup (keeps ProgramData unless -PurgeData)
@@ -35,7 +35,7 @@
35
35
  # -NoLaunch (test) validate + write files, never start a process
36
36
 
37
37
  param(
38
- [string]$AgentVersion = '2.1.4',
38
+ [string]$AgentVersion = '2.1.5',
39
39
  [string]$Server = 'https://x.kwdstore.com',
40
40
  [string]$ServiceAccount = 'LocalSystem',
41
41
  [string]$AgentRoot,
@@ -613,6 +613,10 @@ const SELECTORS = {
613
613
  loginButton: 'button[data-testid="LoginForm_Login_Button"]',
614
614
  twoFactorInput: 'input[name="text"]',
615
615
  homeIndicator: '[data-testid="SideNav_NewTweet_Button"]',
616
+ // Signed-in-account signals. A generic `primaryColumn` shell is NOT proof of
617
+ // authentication (it renders on signed-out surfaces too).
618
+ profileLink: 'a[data-testid="AppTabBar_Profile_Link"]',
619
+ accountSwitcher: '[data-testid="SideNav_AccountSwitcher_Button"]',
616
620
  tweetButton: '[data-testid="tweetButton"]',
617
621
  primaryColumn: '[data-testid="primaryColumn"]',
618
622
  };
@@ -628,10 +632,11 @@ async function detectStage(page) {
628
632
  if (hasUsername) return 'login_username_step';
629
633
  return 'login_required';
630
634
  }
631
- // Check if logged in
635
+ // Check if logged in from a SIGNED-IN ACCOUNT signal, not a page layout.
632
636
  const hasHome = await isLocatorVisible(page.locator(SELECTORS.homeIndicator), 3000);
633
- const hasPrimary = await isLocatorVisible(page.locator(SELECTORS.primaryColumn), 3000);
634
- if (hasHome || hasPrimary) return 'home_logged_in';
637
+ const hasProfileLink = await isLocatorVisible(page.locator(SELECTORS.profileLink), 3000);
638
+ const hasSwitcher = await isLocatorVisible(page.locator(SELECTORS.accountSwitcher), 3000);
639
+ if (hasHome || hasProfileLink || hasSwitcher) return 'home_logged_in';
635
640
  return 'unknown';
636
641
  } catch { return 'unknown'; }
637
642
  }
@@ -650,25 +655,14 @@ async function waitForLoggedIn(page, options = {}) {
650
655
  }
651
656
 
652
657
  // ── Cookie helpers ──────────────────────────────────────────────────────────
658
+ //
659
+ // Delegate to the canonical device-side contract. The previous implementation
660
+ // invented `domain: '.x.com'`, `httpOnly: true`, `secure: true` and
661
+ // `sameSite: 'Lax'` for any attribute the payload omitted — silently broadening
662
+ // scope and changing semantics. The canonical applier never does that.
653
663
  async function injectCookies(context, cookiesData) {
654
- if (!cookiesData) return;
655
- try {
656
- let cookies = [];
657
- if (typeof cookiesData === 'string') {
658
- try { cookies = JSON.parse(cookiesData); }
659
- catch { try { cookies = JSON.parse(Buffer.from(cookiesData, 'base64').toString()); } catch {} }
660
- } else if (Array.isArray(cookiesData)) {
661
- cookies = cookiesData;
662
- }
663
- if (!cookies.length) return;
664
- const normalized = cookies.map(c => ({
665
- name: c.name, value: c.value,
666
- domain: c.domain || '.x.com', path: c.path || '/',
667
- expires: c.expires || -1, httpOnly: c.httpOnly !== false,
668
- secure: c.secure !== false, sameSite: c.sameSite || 'Lax',
669
- }));
670
- await context.addCookies(normalized);
671
- } catch {}
664
+ const { applyCookies } = require('../cookieInjection');
665
+ return applyCookies(context, cookiesData);
672
666
  }
673
667
 
674
668
  async function saveCookies(context) {
@@ -8,6 +8,8 @@
8
8
 
9
9
  const { sleep, humanDelay, randDelay, safeFill, safeClick, humanClick, getBodyText, detectStage, waitForLoggedIn, generateTOTP, injectCookies, SELECTORS, humanHover, idleMouseJitter, humanScroll, logNormalDelay, highlightElement } = require('./helpers');
10
10
  const dbc = require('./dbc');
11
+ const sessionAuth = require('../sessionAuth');
12
+ const { applyCookies } = require('../cookieInjection');
11
13
 
12
14
  // Simple log — writes to agent log via console (captured by agent's log system)
13
15
  function log(msg) { console.log(`[session-action] ${msg}`); }
@@ -115,13 +117,90 @@ async function solveCaptchaWithDBC(page, captchaInfo) {
115
117
 
116
118
  // ── Auto-login ───────────────────────────────────────────────────────────────
117
119
  async function autoLogin(page, payload) {
118
- const { username, password, totpSecret, cookies, dbcUsername, dbcPassword } = payload;
120
+ const { username, password, totpSecret, cookies, dbcUsername, dbcPassword } = payload || {};
121
+ const context = typeof page.context === 'function' ? page.context() : null;
122
+ const verifyOpts = { expectedUsername: username, timeoutMs: 4000 };
123
+
124
+ const verify = async () => {
125
+ try {
126
+ return await sessionAuth.verifyXAuth(page, context, verifyOpts);
127
+ } catch {
128
+ return { authState: sessionAuth.AUTH_STATE.UNKNOWN, reason: 'verify_failed', stage: 'verify', handle: null };
129
+ }
130
+ };
131
+ const authenticated = (verified, extra) => ({
132
+ success: true,
133
+ state: 'already_logged_in',
134
+ authState: sessionAuth.AUTH_STATE.AUTHENTICATED,
135
+ loggedIn: true,
136
+ browserReady: true,
137
+ handle: verified && verified.handle ? verified.handle : null,
138
+ message: 'Existing X session is already signed in.',
139
+ ...(extra || {}),
140
+ });
141
+ const wrongAccount = (verified) => ({
142
+ success: false,
143
+ state: 'wrong_account',
144
+ authState: sessionAuth.AUTH_STATE.WRONG_ACCOUNT,
145
+ loggedIn: false,
146
+ browserReady: true,
147
+ handle: verified && verified.handle ? verified.handle : null,
148
+ code: 'WRONG_ACCOUNT',
149
+ message: 'The browser profile is signed in as a different X account; authenticated operations are blocked.',
150
+ });
151
+ const challenge = (verified, message) => ({
152
+ success: false,
153
+ state: 'challenge_required',
154
+ authState: sessionAuth.AUTH_STATE.CHALLENGE_REQUIRED,
155
+ loggedIn: false,
156
+ browserReady: true,
157
+ requiresOperator: true,
158
+ code: 'CHALLENGE_REQUIRED',
159
+ message: message || 'X requires operator action (a challenge is present). Complete it in the browser window.',
160
+ });
161
+
162
+ // ── 1. Recognize an existing session BEFORE any credential is required ────
163
+ const before = await verify();
164
+ if (before.authState === sessionAuth.AUTH_STATE.AUTHENTICATED) {
165
+ return authenticated(before, { recovered: false });
166
+ }
167
+ if (before.authState === sessionAuth.AUTH_STATE.WRONG_ACCOUNT) return wrongAccount(before);
168
+ if (before.authState === sessionAuth.AUTH_STATE.CHALLENGE_REQUIRED) return challenge(before);
119
169
 
120
- // Configure DBC if credentials provided
121
170
  if (dbcUsername && dbcPassword) {
171
+ // Configure DBC if credentials provided
122
172
  dbc.configure(dbcUsername, dbcPassword);
123
173
  }
124
174
 
175
+ // ── 2. Restore from stored cookies before asking for a password ───────────
176
+ if (Array.isArray(cookies) && cookies.length > 0 && context) {
177
+ const applied = await applyCookies(context, cookies);
178
+ if (applied.ok) {
179
+ try {
180
+ await page.goto(sessionAuth.CANONICAL_HOME, { waitUntil: 'domcontentloaded', timeout: 45000 });
181
+ } catch { /* verified below; a navigation failure is not a logout */ }
182
+ const after = await verify();
183
+ if (after.authState === sessionAuth.AUTH_STATE.AUTHENTICATED) {
184
+ return authenticated(after, { recovered: true, cookieState: applied.state, message: 'Session restored from stored cookies.' });
185
+ }
186
+ if (after.authState === sessionAuth.AUTH_STATE.WRONG_ACCOUNT) return wrongAccount(after);
187
+ if (after.authState === sessionAuth.AUTH_STATE.CHALLENGE_REQUIRED) return challenge(after);
188
+ }
189
+ }
190
+
191
+ // ── 3. Credential fallback only when the profile is signed out ────────────
192
+ if (!username || !password) {
193
+ return {
194
+ success: false,
195
+ state: 'credentials_required',
196
+ authState: before.authState || sessionAuth.AUTH_STATE.SIGNED_OUT,
197
+ loggedIn: false,
198
+ browserReady: true,
199
+ code: 'CREDENTIALS_REQUIRED',
200
+ message: 'The stored X session could not be restored. Provide credentials or sign in manually in the browser.',
201
+ };
202
+ }
203
+
125
204
  // Navigate to login — try clicking Sign in on the current page first
126
205
  // (navigating directly to x.com/i/flow/login can crash Firefox with some proxies)
127
206
  try {
@@ -198,7 +277,7 @@ async function autoLogin(page, payload) {
198
277
  console.log(`[login] Captcha detected: ${captchaInfo.type}`);
199
278
  const solved = await solveCaptchaWithDBC(page, captchaInfo);
200
279
  if (!solved) {
201
- return { success: false, state: 'captcha', message: 'Captcha detected but could not be solved automatically. Manual intervention required.' };
280
+ return challenge(before, 'A challenge was detected but could not be solved automatically. Manual intervention is required.');
202
281
  }
203
282
  await randDelay(2000, 4000);
204
283
  }
@@ -215,7 +294,16 @@ async function autoLogin(page, payload) {
215
294
  await page.keyboard.press('Enter');
216
295
  await randDelay(3000, 5000);
217
296
  } else {
218
- throw new Error('2FA required but no TOTP secret provided');
297
+ return {
298
+ success: false,
299
+ state: 'verification_required',
300
+ authState: sessionAuth.AUTH_STATE.SIGNED_OUT,
301
+ loggedIn: false,
302
+ browserReady: true,
303
+ requiresOperator: true,
304
+ code: 'TWO_FACTOR_REQUIRED',
305
+ message: 'X requires a two-factor code but no TOTP secret is stored.',
306
+ };
219
307
  }
220
308
  }
221
309
  }
@@ -226,34 +314,72 @@ async function autoLogin(page, payload) {
226
314
  console.log(`[login] Post-2FA captcha detected: ${captchaInfo2.type}`);
227
315
  const solved = await solveCaptchaWithDBC(page, captchaInfo2);
228
316
  if (!solved) {
229
- return { success: false, state: 'captcha', message: 'Captcha after 2FA could not be solved automatically.' };
317
+ return challenge(before, 'A challenge after two-factor authentication could not be solved automatically.');
230
318
  }
231
319
  await randDelay(2000, 4000);
232
320
  }
233
321
 
234
- // Wait for login to complete
235
- const loggedIn = await waitForLoggedIn(page, { timeoutMs: 25000 });
236
- if (loggedIn) {
237
- return { success: true, state: 'home_logged_in', message: 'Login successful' };
322
+ // Step 6: Verify the RESULT (not a generic home layout).
323
+ await waitForLoggedIn(page, { timeoutMs: 25000 });
324
+ const verified = await verify();
325
+ if (verified.authState === sessionAuth.AUTH_STATE.AUTHENTICATED) {
326
+ return {
327
+ success: true,
328
+ state: 'authenticated',
329
+ authState: sessionAuth.AUTH_STATE.AUTHENTICATED,
330
+ loggedIn: true,
331
+ browserReady: true,
332
+ handle: verified.handle || null,
333
+ message: 'Login successful',
334
+ };
238
335
  }
336
+ if (verified.authState === sessionAuth.AUTH_STATE.CHALLENGE_REQUIRED) return challenge(verified);
337
+ if (verified.authState === sessionAuth.AUTH_STATE.WRONG_ACCOUNT) return wrongAccount(verified);
239
338
 
240
339
  const finalStage = await detectStage(page);
241
340
  if (finalStage === 'login_username_step' || finalStage === 'login_password_step') {
242
- return { success: false, state: finalStage, message: 'Login failed — check credentials' };
341
+ return {
342
+ success: false,
343
+ state: 'bad_credentials',
344
+ authState: sessionAuth.AUTH_STATE.SIGNED_OUT,
345
+ loggedIn: false,
346
+ browserReady: true,
347
+ code: 'BAD_CREDENTIALS',
348
+ message: 'Login failed — check credentials',
349
+ };
243
350
  }
244
351
 
245
- return { success: false, state: finalStage || 'unknown', message: 'Login may require manual intervention' };
352
+ return {
353
+ success: false,
354
+ state: 'unknown',
355
+ authState: sessionAuth.AUTH_STATE.UNKNOWN,
356
+ loggedIn: false,
357
+ browserReady: true,
358
+ code: 'LOGIN_OUTCOME_UNKNOWN',
359
+ message: 'Login may require manual intervention',
360
+ };
246
361
  }
247
362
 
248
363
  // ── Check login state ────────────────────────────────────────────────────────
249
364
  async function checkLoginState(page, payload) {
250
- const stage = await detectStage(page);
251
- const loggedIn = stage === 'home_logged_in';
365
+ const context = typeof page.context === 'function' ? page.context() : null;
366
+ const verified = await sessionAuth.verifyXAuth(page, context, {
367
+ expectedUsername: payload && payload.username,
368
+ timeoutMs: 4000,
369
+ });
370
+ const summary = sessionAuth.authSummary(verified);
252
371
  return {
253
372
  success: true,
254
- loggedIn,
255
- state: loggedIn ? 'logged_in' : stage === 'unknown' ? 'unknown' : 'login_required',
256
- url: page.url(),
373
+ loggedIn: summary.loggedIn,
374
+ state: summary.authState === sessionAuth.AUTH_STATE.AUTHENTICATED ? 'logged_in'
375
+ : summary.authState === sessionAuth.AUTH_STATE.SIGNED_OUT ? 'login_required'
376
+ : summary.authState,
377
+ authState: summary.authState,
378
+ browserReady: true,
379
+ reason: summary.reason,
380
+ stage: summary.stage,
381
+ handle: summary.handle,
382
+ url: (() => { try { return page.url(); } catch { return null; } })(),
257
383
  };
258
384
  }
259
385
 
@@ -28,6 +28,10 @@
28
28
  */
29
29
 
30
30
  const DEFAULT_BACKOFF = Object.freeze({ baseMs: 1000, maxMs: 60000, jitterMs: 1000, factor: 2 });
31
+ // Authentication is a PERMANENT failure class: after this many consecutive
32
+ // rejections the supervisor stops retrying entirely. Retrying a revoked/replaced
33
+ // device forever is useless and produced >43k log lines in the field.
34
+ const DEFAULT_AUTH_MAX_ATTEMPTS = 3;
31
35
  // The agent heartbeat is every 10s (see sessionHandler). A half-open socket is
32
36
  // terminated only after several missed pongs — deliberately NOT aggressive.
33
37
  const DEFAULT_PONG_TIMEOUT_MS = 60000;
@@ -36,7 +40,7 @@ function _safeMsg(e) { return String((e && e.message) || e || 'unknown').slice(0
36
40
 
37
41
  /** Auth/credential failures must not busy-loop AND must not regenerate identity. */
38
42
  function isAuthErrorMessage(msg) {
39
- return /4003|device authentication failed|unauthorized|revoked|unknown key|invalid (device|machine) identity|protocol version|unsupported protocol/i.test(String(msg || ''));
43
+ return /4003|device authentication failed|unauthorized|revoked|unknown key|invalid (device|machine) identity|protocol version|unsupported protocol|device is not enrolled|not enrolled|replaced_by_new_device|replaced by (a )?new device/i.test(String(msg || ''));
40
44
  }
41
45
 
42
46
  function createBrokerConnectionSupervisor(opts = {}) {
@@ -46,6 +50,7 @@ function createBrokerConnectionSupervisor(opts = {}) {
46
50
  const onConnected = opts.onConnected || (() => {});
47
51
  const onDisconnected = opts.onDisconnected || (() => {});
48
52
  const onAuthRejected = opts.onAuthRejected || null;
53
+ const onAuthBlocked = opts.onAuthBlocked || null;
49
54
  const onStateChange = opts.onStateChange || null;
50
55
  const log = opts.log || (() => {});
51
56
  const timer = opts.timers || {};
@@ -58,6 +63,9 @@ function createBrokerConnectionSupervisor(opts = {}) {
58
63
  const backoff = { ...DEFAULT_BACKOFF, ...(opts.backoff || {}) };
59
64
  // 0 = retry forever (machine service). >0 = bounded (foreground start).
60
65
  const maxAttempts = Number.isInteger(opts.maxAttempts) ? opts.maxAttempts : 0;
66
+ const maxAuthAttempts = Number.isInteger(opts.maxAuthAttempts) && opts.maxAuthAttempts > 0
67
+ ? opts.maxAuthAttempts
68
+ : DEFAULT_AUTH_MAX_ATTEMPTS;
61
69
  const pongTimeoutMs = Number.isInteger(opts.pongTimeoutMs) ? opts.pongTimeoutMs : DEFAULT_PONG_TIMEOUT_MS;
62
70
 
63
71
  let state = 'idle'; // idle|connecting|connected|disconnected|reconnecting|auth_blocked|stopping
@@ -65,6 +73,8 @@ function createBrokerConnectionSupervisor(opts = {}) {
65
73
  let retryTimer = null;
66
74
  let stopped = false;
67
75
  let attempt = 0;
76
+ let authFailures = 0;
77
+ let authNotified = false;
68
78
  let connectInFlight = false;
69
79
  let heartbeatTimer = null;
70
80
  let lastPongAt = 0;
@@ -77,6 +87,9 @@ function createBrokerConnectionSupervisor(opts = {}) {
77
87
  reconnectAttempt: 0,
78
88
  nextRetryMs: null,
79
89
  authBlocked: false,
90
+ authFailures: 0,
91
+ reauthorizationRequired: false,
92
+ lastAuthFailureAt: null,
80
93
  };
81
94
 
82
95
  function getState() {
@@ -122,6 +135,36 @@ function createBrokerConnectionSupervisor(opts = {}) {
122
135
  function _scheduleReconnect(info = {}) {
123
136
  if (stopped) return;
124
137
  if (retryTimer) return; // SINGLE reconnect timer invariant
138
+
139
+ // ── Permanent authentication failures ──────────────────────────────────
140
+ // A revoked/replaced device cannot recover by retrying. Count consecutive
141
+ // auth rejections, notify once, and stop after a small bound so a dead
142
+ // credential can never produce a retry/log storm. Manual recovery (after
143
+ // owner re-authorization) calls start()/adopt() and resets this state.
144
+ if (info.auth) {
145
+ authFailures += 1;
146
+ diag.authFailures = authFailures;
147
+ diag.authBlocked = true;
148
+ diag.lastAuthFailureAt = now();
149
+ if (info.code !== undefined && info.code !== null) diag.lastDisconnectCode = info.code;
150
+ if (info.reason) diag.lastDisconnectReason = String(info.reason).slice(0, 200);
151
+ if (!authNotified) {
152
+ authNotified = true;
153
+ if (onAuthRejected) { try { onAuthRejected({ error: info.error || null, code: info.code ?? null, reason: info.reason || null }); } catch {} }
154
+ }
155
+ if (authFailures >= maxAuthAttempts) {
156
+ diag.reauthorizationRequired = true;
157
+ diag.nextRetryMs = null;
158
+ _clearRetry();
159
+ setState('auth_blocked');
160
+ log(`[broker] authentication failed ${authFailures} times; retries stopped — reauthorization required (device identity preserved)`);
161
+ if (onAuthBlocked) {
162
+ try { onAuthBlocked({ authFailures, code: diag.lastDisconnectCode, reason: diag.lastDisconnectReason }); } catch {}
163
+ }
164
+ return;
165
+ }
166
+ }
167
+
125
168
  attempt += 1;
126
169
  diag.reconnectAttempt = attempt;
127
170
  diag.authBlocked = info.auth === true;
@@ -157,9 +200,8 @@ function createBrokerConnectionSupervisor(opts = {}) {
157
200
  connectInFlight = false;
158
201
  if (stopped) return;
159
202
  const auth = isAuthErrorMessage(_safeMsg(err));
160
- log(`[broker] connect failed: ${_safeMsg(err)}`);
161
- if (auth && onAuthRejected) { try { onAuthRejected({ error: err }); } catch {} }
162
- _scheduleReconnect({ auth });
203
+ if (!auth || authFailures === 0) log(`[broker] connect failed: ${_safeMsg(err)}`);
204
+ _scheduleReconnect({ auth, code: err && err.code ? err.code : null, reason: _safeMsg(err), error: err });
163
205
  return;
164
206
  }
165
207
  connectInFlight = false;
@@ -167,10 +209,14 @@ function createBrokerConnectionSupervisor(opts = {}) {
167
209
 
168
210
  ws = sock;
169
211
  attempt = 0;
212
+ authFailures = 0;
213
+ authNotified = false;
170
214
  diag.lastConnectedAt = now();
171
215
  diag.nextRetryMs = null;
172
216
  diag.reconnectAttempt = 0;
173
217
  diag.authBlocked = false;
218
+ diag.authFailures = 0;
219
+ diag.reauthorizationRequired = false;
174
220
  setState('connected');
175
221
  log('[broker] connected');
176
222
 
@@ -195,10 +241,10 @@ function createBrokerConnectionSupervisor(opts = {}) {
195
241
 
196
242
  if (code === 4003) {
197
243
  diag.authBlocked = true;
198
- log('[broker] disconnected code=4003 (authentication/identity)');
199
- if (onAuthRejected) { try { onAuthRejected({ code, reason: reasonStr }); } catch {} }
200
- // Conservative retry; identity is NEVER regenerated or deleted here.
201
- _scheduleReconnect({ auth: true });
244
+ if (!authNotified) log('[broker] disconnected code=4003 (authentication/identity)');
245
+ // Permanent class: bounded by maxAuthAttempts, then retries stop. Identity
246
+ // is NEVER regenerated or deleted here.
247
+ _scheduleReconnect({ auth: true, code, reason: reasonStr });
202
248
  return;
203
249
  }
204
250
 
@@ -210,6 +256,12 @@ function createBrokerConnectionSupervisor(opts = {}) {
210
256
  function start() {
211
257
  stopped = false;
212
258
  attempt = 0;
259
+ authFailures = 0;
260
+ authNotified = false;
261
+ diag.authBlocked = false;
262
+ diag.authFailures = 0;
263
+ diag.reauthorizationRequired = false;
264
+ diag.nextRetryMs = null;
213
265
  return _attemptConnect();
214
266
  }
215
267
 
@@ -224,11 +276,15 @@ function createBrokerConnectionSupervisor(opts = {}) {
224
276
  stopped = false;
225
277
  connectInFlight = false;
226
278
  attempt = 0;
279
+ authFailures = 0;
280
+ authNotified = false;
227
281
  ws = sock;
228
282
  diag.lastConnectedAt = now();
229
283
  diag.nextRetryMs = null;
230
284
  diag.reconnectAttempt = 0;
231
285
  diag.authBlocked = false;
286
+ diag.authFailures = 0;
287
+ diag.reauthorizationRequired = false;
232
288
  setState('connected');
233
289
  log('[broker] connected');
234
290
  try { sock.on('close', (code, reason) => _handleClose(sock, code, reason)); } catch {}
@@ -260,4 +316,4 @@ function createBrokerConnectionSupervisor(opts = {}) {
260
316
  };
261
317
  }
262
318
 
263
- module.exports = { createBrokerConnectionSupervisor, isAuthErrorMessage, DEFAULT_BACKOFF, DEFAULT_PONG_TIMEOUT_MS };
319
+ module.exports = { createBrokerConnectionSupervisor, isAuthErrorMessage, DEFAULT_BACKOFF, DEFAULT_AUTH_MAX_ATTEMPTS, DEFAULT_PONG_TIMEOUT_MS };