3xui-api-client 3.1.1 → 3.1.2

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 CHANGED
@@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [3.1.2] - 2026-06-30
9
+
10
+ ### Fixed
11
+ - 🔴 **Session recovery for non-401 stale sessions** ([#10](https://github.com/iamhelitha/3xui-api-client/issues/10)) - Automatic re-login is no longer keyed strictly to HTTP `401`. Some 3x-ui forks reject a stale cookie session with `404` (the auth-gated route falls through to a generic not-found handler when not logged in) or by returning an HTML login page with `200`. The client now treats all three as a lost session and performs one bounded, backed-off forced re-login + retry — reusing the existing `maxLoginRetries` / `loginRetryBackoff` budget. Token auth is unchanged: a `401` still throws a clear "token invalid" error and a `404` surfaces unchanged as a genuine missing resource.
12
+ - 🐛 **`getClientIps(email)` now returns a real array** ([#12](https://github.com/iamhelitha/3xui-api-client/issues/12)) - The legacy panel returns `obj` as a JSON-encoded string (e.g. `'["1.2.3.4"]'`) rather than an actual array. The client now parses it internally so `obj` is always a `string[]` (empty array when the panel has no IP record), matching every other list-returning endpoint. The TypeScript signature is now `Promise<ModernApiResponse<string[]>>`.
13
+
14
+ ### Changed
15
+ - 📖 **`getCPUHistory(bucket)` documentation/types corrected** ([#11](https://github.com/iamhelitha/3xui-api-client/issues/11)) - The previously documented `{ history: [{ timestamp, usage }] }` shape was assumed and never verified. The endpoint actually returns the standard `{ success, msg, obj }` envelope where `obj` is an array of exactly 60 `{ cpu: number; t: number }` points (`cpu` is a plain percentage number, `t` is epoch **seconds**; total span is `60 * bucket` seconds). The TypeScript signature is now `Promise<ModernApiResponse<Array<{ cpu: number; t: number }>>>`. No runtime change — the method already returned the real envelope.
16
+
8
17
  ## [3.1.1] - 2026-06-18
9
18
 
10
19
  ### Changed
package/index.d.ts CHANGED
@@ -581,7 +581,14 @@ declare module '3xui-api-client' {
581
581
  deleteClientByEmail(inboundId: number, email: string): Promise<any>;
582
582
  getClientTrafficsByEmail(email: string): Promise<any>;
583
583
  getClientTrafficsById(id: string): Promise<any>;
584
- getClientIps(email: string): Promise<any>;
584
+ /**
585
+ * Get the list of IP addresses recorded for a client.
586
+ *
587
+ * The legacy panel returns `obj` as a JSON-encoded string; this client
588
+ * parses it internally so `obj` is always a real `string[]` (empty when
589
+ * the panel has no IP record for the client).
590
+ */
591
+ getClientIps(email: string): Promise<ModernApiResponse<string[]>>;
585
592
  clearClientIps(email: string): Promise<any>;
586
593
  resetClientTraffic(inboundId: number, email: string): Promise<any>;
587
594
  resetAllTraffics(): Promise<any>;
@@ -595,9 +602,15 @@ declare module '3xui-api-client' {
595
602
  getServerStatus(): Promise<any>;
596
603
  /**
597
604
  * Get CPU usage history.
605
+ *
606
+ * Returns the standard `{ success, msg, obj }` envelope. `obj` is an array
607
+ * of exactly 60 points, each `{ cpu, t }` where `cpu` is the usage
608
+ * percentage (a plain number, no trailing `%`) and `t` is the epoch time in
609
+ * seconds. The total span covered is `60 * bucket` seconds.
610
+ *
598
611
  * @param bucket - Bucket size in seconds. Must be one of: 2, 30, 60, 120, 180, 300 (default: 60)
599
612
  */
600
- getCPUHistory(bucket?: number): Promise<any>;
613
+ getCPUHistory(bucket?: number): Promise<ModernApiResponse<Array<{ cpu: number; t: number }>>>;
601
614
  getXrayVersion(): Promise<any>;
602
615
  getConfigJson(): Promise<any>;
603
616
  /**
package/index.js CHANGED
@@ -409,38 +409,110 @@ class ThreeXUI {
409
409
  data,
410
410
  headers: { ...this._buildRequestHeaders(method), ...extraHeaders }
411
411
  });
412
+
413
+ // Some panels answer a stale/expired session with HTTP 200 plus an
414
+ // HTML login page (a redirect-then-200) instead of an explicit
415
+ // 401/404. For cookie auth, treat that HTML body where JSON was
416
+ // expected as a lost session and recover transparently.
417
+ if (!this.token && this._looksLikeLoginPage(response.data)) {
418
+ return await this._retryAfterRelogin(method, path, data, extraHeaders);
419
+ }
420
+
412
421
  // Reset retry counter on successful request
413
422
  this.loginRetryCount = 0;
414
423
  return response.data;
415
424
  } catch (error) {
416
- if (error.response && error.response.status === 401) {
425
+ if (this._isStaleSessionError(error)) {
417
426
  if (this.token) {
418
- throw new Error('API Token is invalid or expired. Please check your credentials.');
419
- }
420
- // Cookie might have expired, try to login again with retry limit.
421
- // A configurable backoff delay is applied before each re-login to
422
- // avoid burning through the retry budget or tripping login-rate limits
423
- // (e.g. fail2ban) when many instances race to re-authenticate.
424
- if (this.loginRetryCount < this.maxLoginRetries) {
425
- if (this.loginRetryBackoff > 0) {
426
- await new Promise(resolve => setTimeout(resolve, this.loginRetryBackoff));
427
+ // Token auth: a 401 means the token itself is invalid, so
428
+ // retrying will not help. A 404 is a genuine missing
429
+ // resource (the token never goes "stale"), so surface it
430
+ // unchanged.
431
+ if (error.response && error.response.status === 401) {
432
+ throw new Error('API Token is invalid or expired. Please check your credentials.');
427
433
  }
428
- await this._ensureAuthenticated(true); // Force refresh
429
- const response = await this.api.request({
430
- method,
431
- url: path,
432
- data,
433
- headers: { ...this._buildRequestHeaders(method), ...extraHeaders }
434
- });
435
- return response.data;
436
- } else {
437
- throw new Error('Maximum login retry attempts exceeded. Check your credentials.');
434
+ throw error;
438
435
  }
436
+ // Cookie session may have expired. Different 3x-ui versions/forks
437
+ // are inconsistent about the signal (401, 404, or an HTML login
438
+ // page), so we recover the same way for each: one bounded,
439
+ // backed-off forced re-login + retry.
440
+ return await this._retryAfterRelogin(method, path, data, extraHeaders);
439
441
  }
440
442
  throw error;
441
443
  }
442
444
  }
443
445
 
446
+ /**
447
+ * Decide whether an error from an authenticated request indicates a lost
448
+ * cookie session that warrants a forced re-login. Different 3x-ui forks
449
+ * reject a stale session with 401, with 404 (the auth-gated route falls
450
+ * through to a generic not-found handler when not logged in), or by
451
+ * returning an HTML login page where JSON was expected.
452
+ *
453
+ * @param {*} error - Error thrown by the axios request
454
+ * @returns {boolean} True if the error looks like a session failure
455
+ */
456
+ _isStaleSessionError(error) {
457
+ if (!error || !error.response) {
458
+ return false;
459
+ }
460
+ const status = error.response.status;
461
+ if (status === 401 || status === 404) {
462
+ return true;
463
+ }
464
+ return this._looksLikeLoginPage(error.response.data);
465
+ }
466
+
467
+ /**
468
+ * Heuristic for a panel returning its HTML login page in place of the
469
+ * expected JSON envelope. Every authenticated endpoint here returns JSON
470
+ * (or, for getDb, a "SQLite format 3" string), so an HTML document body is
471
+ * itself the anomaly that signals a redirect to the login screen.
472
+ *
473
+ * @param {*} data - Response body
474
+ * @returns {boolean} True if the body looks like an HTML login page
475
+ */
476
+ _looksLikeLoginPage(data) {
477
+ if (typeof data !== 'string') {
478
+ return false;
479
+ }
480
+ const trimmed = data.trim().toLowerCase();
481
+ return trimmed.startsWith('<!doctype html') || trimmed.startsWith('<html');
482
+ }
483
+
484
+ /**
485
+ * Force a fresh login and retry the original request once, honoring the
486
+ * shared retry budget and backoff. Used for cookie-auth session recovery
487
+ * regardless of whether the panel signalled with 401, 404, or a login-page
488
+ * body, so consumers never have to reimplement session recovery themselves.
489
+ *
490
+ * @param {string} method - HTTP method
491
+ * @param {string} path - Request path
492
+ * @param {Object} data - Request body
493
+ * @param {Object} extraHeaders - Additional headers to merge
494
+ * @returns {Promise<*>} The retried response data
495
+ */
496
+ async _retryAfterRelogin(method, path, data, extraHeaders) {
497
+ // Bound the recovery to a single retry budget to avoid login storms
498
+ // (e.g. tripping fail2ban) when many instances race to re-authenticate.
499
+ if (this.loginRetryCount >= this.maxLoginRetries) {
500
+ throw new Error('Maximum login retry attempts exceeded. Check your credentials.');
501
+ }
502
+ if (this.loginRetryBackoff > 0) {
503
+ await new Promise(resolve => setTimeout(resolve, this.loginRetryBackoff));
504
+ }
505
+ await this._ensureAuthenticated(true); // Force refresh
506
+ const response = await this.api.request({
507
+ method,
508
+ url: path,
509
+ data,
510
+ headers: { ...this._buildRequestHeaders(method), ...extraHeaders }
511
+ });
512
+ this.loginRetryCount = 0;
513
+ return response.data;
514
+ }
515
+
444
516
  /**
445
517
  * Build per-request headers, including the JSON content type for POST
446
518
  * bodies and (on cookie-authenticated sessions against newer
@@ -1151,8 +1223,44 @@ class ThreeXUI {
1151
1223
  return this._request('get', `/panel/api/inbounds/getClientTrafficsById/${id}`);
1152
1224
  }
1153
1225
 
1154
- getClientIps(email) {
1155
- return this._request('post', `/panel/api/inbounds/clientIps/${email}`);
1226
+ /**
1227
+ * Get the list of IP addresses recorded for a client.
1228
+ *
1229
+ * The legacy panel returns `obj` as a JSON-encoded string (e.g.
1230
+ * `'["1.2.3.4"]'`) rather than an actual array, unlike every other
1231
+ * list-returning endpoint. We parse it internally so callers get
1232
+ * `obj: string[]` directly. If the panel reports "No IP Record" (or any
1233
+ * non-array/unparseable value), `obj` is normalized to an empty array.
1234
+ *
1235
+ * @param {string} email - Client email
1236
+ * @returns {Promise<{success: boolean, msg: string, obj: string[]}>}
1237
+ */
1238
+ async getClientIps(email) {
1239
+ const response = await this._request('post', `/panel/api/inbounds/clientIps/${email}`);
1240
+ return { ...response, obj: this._parseClientIps(response && response.obj) };
1241
+ }
1242
+
1243
+ /**
1244
+ * Normalize the `obj` field returned by clientIps into a real array of IP
1245
+ * strings. The panel may return a JSON-encoded array string, an already
1246
+ * parsed array, or a placeholder message like "No IP Record".
1247
+ *
1248
+ * @param {*} obj - Raw `obj` value from the clientIps response
1249
+ * @returns {string[]} Parsed list of IP addresses (empty when none)
1250
+ */
1251
+ _parseClientIps(obj) {
1252
+ if (Array.isArray(obj)) {
1253
+ return obj;
1254
+ }
1255
+ if (typeof obj === 'string') {
1256
+ try {
1257
+ const parsed = JSON.parse(obj);
1258
+ return Array.isArray(parsed) ? parsed : [];
1259
+ } catch {
1260
+ return [];
1261
+ }
1262
+ }
1263
+ return [];
1156
1264
  }
1157
1265
 
1158
1266
  clearClientIps(email) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "3xui-api-client",
3
- "version": "3.1.1",
3
+ "version": "3.1.2",
4
4
  "description": "Node.js API client for the 3x-ui panel (VLESS, VMess, Trojan, Shadowsocks, WireGuard, Reality) with automatic session management, credential generation, and full REST API coverage",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",