adspower-browser 2.1.7-beta.0 → 2.1.7-beta.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/README.MD CHANGED
@@ -230,39 +230,35 @@ docker-compose exec adspower-cli /bin/bash
230
230
  ```
231
231
 
232
232
 
233
- ## WorkBuddy browser login
233
+ ## WorkBuddy client authorization
234
+
235
+ Set `IS_WORKBUDDY=1` for every CLI invocation in this mode (the Connector injects it):
234
236
 
235
237
  ```bash
238
+ export IS_WORKBUDDY=1
236
239
  ads login
237
240
  ads logstatus
238
- ads stop
241
+ ads get-browser-list '{"page":1,"limit":10}'
242
+ ads logout
239
243
  ```
240
244
 
241
- `login` starts a detached, five-minute loopback callback receiver and prints an
242
- HTTPS authorization URL for `https://app-wx.loginkits.com/login?source=workbuddy`.
243
- A dedicated loopback listener on port 59753 prevents concurrent login workers;
244
- the callback itself uses a random port. WorkBuddy can terminate the foreground command after reading this URL. The
245
- website must include the matching CLI login integration. It reads the existing
246
- API Key after sign-in and POSTs it to the one-time loopback receiver. No key is
247
- put in the authorization URL or process arguments. The receiver invokes the
248
- existing `start` command with `ADS_API_KEY` and the matching test API base
249
- `https://api-wx.loginkits.com/`; normal `ads start` defaults are unchanged.
250
-
251
- `logstatus` preserves the runtime status messages and appends a JSON result. Exit 0 means `getChildStatus()` returned true
252
- (runtime starting or running); exit 1 means it returned false. No authentication
253
- API is called. It does not expose the key.
254
- `stop` also cancels a pending login; no separate logout command is needed.
255
- A browser may request local-network permission: allow it for this authorization.
256
- An existing API Key is required; this flow never resets or generates a key.
257
-
258
- WorkBuddy `cli.json` command mapping (adapt installation/runtime fields separately):
259
-
260
- ```json
261
- {
262
- "auth": { "darwin": "ads login", "linux": "ads login", "win32": "ads.cmd login" },
263
- "status": { "darwin": "ads logstatus", "linux": "ads logstatus", "win32": "ads.cmd logstatus" },
264
- "unAuth": { "darwin": "ads stop", "linux": "ads stop", "win32": "ads.cmd stop" },
265
- "authUrlDomain": "app-wx.loginkits.com",
266
- "statusMatch": "authenticated.*true"
267
- }
268
- ```
245
+ With the variable present, login/logout/logstatus replace start/stop/restart/status.
246
+ Unset it for normal runtime commands. Presence is the switch, including an empty value or `0`.
247
+ `login --loginhost https://app-wx.loginkits.com` selects an alternate authorization site;
248
+ the default is https://app.adspower.com. Login no longer accepts --base-url or starts a runtime.
249
+ The website opens `adsPowerGlobal://auth` with source=workbuddy and the one-time callback challenge.
250
+ The logged-in desktop client returns apiKey, apiPort (Local API), rpaPort (RPA Plus), and userId.
251
+ Both actual services must be ready. The callback worker survives foreground process termination,
252
+ waits five minutes, uses a random callback port and serializes login workers on port 59753.
253
+
254
+ Credentials persist in `~/.adspowerCli/<md5(userId)>` with mode 0600 on POSIX;
255
+ `client-user.json` selects the current user without containing the key.
256
+ Business commands use this saved connection, independently of normal runtime PID files.
257
+ `logstatus` prints JSON and exits 0 only when all four saved fields are valid; it does not probe
258
+ client liveness or validate the key remotely. Reauthorize after client ports or credentials change.
259
+ `logout` cancels pending login and removes the current user's connection and index;
260
+ it does not stop the desktop client or revoke the server key. Other user files remain until explicitly logged out.
261
+
262
+ Deploy the matching frontend to both the authorization site and the desktop renderer site.
263
+ The native client must forward the complete protocol URL through renderer-scheme.
264
+ The connector's unAuth maps to ads logout. Build/package locally before testing; local changes do not update npm.
package/cli/authWorker.js CHANGED
@@ -24,9 +24,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
24
 
25
25
  // src/authWorker.ts
26
26
  var import_node_fs2 = require("fs");
27
- var import_node_path2 = __toESM(require("path"));
28
- var import_node_crypto2 = require("crypto");
29
- var import_node_child_process2 = require("child_process");
27
+ var import_node_path3 = __toESM(require("path"));
28
+ var import_node_crypto3 = require("crypto");
30
29
  var import_node_net2 = require("net");
31
30
 
32
31
  // src/auth.ts
@@ -35,23 +34,69 @@ var import_node_fs = require("fs");
35
34
  var import_node_os = __toESM(require("os"));
36
35
  var import_node_path = __toESM(require("path"));
37
36
  var import_node_net = require("net");
38
- var LOGIN_ORIGIN = "https://app-wx.loginkits.com";
39
- var LOGIN_API_BASE = "https://api-wx.loginkits.com/";
40
37
  var pendingPath = import_node_path.default.join(import_node_os.default.homedir(), ".adspowerCli", "workbuddy-login.json");
41
38
 
39
+ // src/clientSession.ts
40
+ var fs3 = __toESM(require("fs"));
41
+ var import_node_path2 = __toESM(require("path"));
42
+ var import_node_crypto = require("crypto");
43
+
44
+ // src/tools/paths.ts
45
+ var os2 = __toESM(require("os"));
46
+ var path2 = __toESM(require("path"));
47
+ var fs2 = __toESM(require("fs"));
48
+ var import_fs_extra2 = require("fs-extra2");
49
+ var getHomedir = () => {
50
+ return (typeof os2.homedir == "function" ? os2.homedir() : process.env[process.platform == "win32" ? "USERPROFILE" : "HOME"]) || "~";
51
+ };
52
+ var getPidFileDir = (create = true) => {
53
+ const dir = path2.join(getHomedir(), ".adspowerCli");
54
+ if (create && !fs2.existsSync(dir)) {
55
+ (0, import_fs_extra2.ensureDirSync)(dir);
56
+ }
57
+ return dir;
58
+ };
59
+
60
+ // src/clientSession.ts
61
+ var userFile = (userId) => import_node_path2.default.join(getPidFileDir(false), (0, import_node_crypto.createHash)("md5").update(userId).digest("hex"));
62
+ var indexFile = () => import_node_path2.default.join(getPidFileDir(false), "client-user.json");
63
+ var validPort = (value) => Number.isInteger(value) && Number(value) > 0 && Number(value) <= 65535;
64
+ function isClientSession(value) {
65
+ if (!value || typeof value !== "object") return false;
66
+ const session = value;
67
+ return typeof session.apiKey === "string" && !!session.apiKey.trim() && session.apiKey.length <= 4096 && !/[\r\n]/.test(session.apiKey) && typeof session.userId === "string" && !!session.userId.trim() && session.userId.length <= 256 && session.userId !== "1.0.0" && validPort(session.apiPort) && validPort(session.rpaPort);
68
+ }
69
+ function writePrivateJson(file, value) {
70
+ const temporary = `${file}.${(0, import_node_crypto.randomUUID)()}.tmp`;
71
+ try {
72
+ fs3.writeFileSync(temporary, JSON.stringify(value), { mode: 384, flag: "wx" });
73
+ fs3.renameSync(temporary, file);
74
+ } finally {
75
+ fs3.rmSync(temporary, { force: true });
76
+ }
77
+ }
78
+ function saveClientSession(session) {
79
+ if (!isClientSession(session)) throw new Error("Incomplete client connection");
80
+ getPidFileDir();
81
+ const { apiKey, userId, apiPort, rpaPort } = session;
82
+ writePrivateJson(userFile(userId), { apiKey, userId, apiPort, rpaPort });
83
+ writePrivateJson(indexFile(), { userId });
84
+ }
85
+
42
86
  // src/loginReceiver.ts
43
87
  var import_node_http = require("http");
44
- var import_node_crypto = require("crypto");
45
- async function createLoginReceiver(origin, onKey) {
46
- const state = (0, import_node_crypto.randomBytes)(32).toString("base64url");
88
+ var import_node_crypto2 = require("crypto");
89
+ async function createLoginReceiver(origin, onKey, onAccepted) {
90
+ const allowedOrigins = /* @__PURE__ */ new Set([origin, "https://app.adspower.com", "https://app.adspower.net"]);
91
+ const state = (0, import_node_crypto2.randomBytes)(32).toString("base64url");
47
92
  let consumed = false;
48
93
  const server = (0, import_node_http.createServer)(async (req, res) => {
49
94
  const address2 = server.address();
50
- if (!address2 || typeof address2 === "string" || req.headers.host !== `127.0.0.1:${address2.port}` || req.headers.origin !== origin || req.url !== "/callback") {
95
+ if (!address2 || typeof address2 === "string" || req.headers.host !== `127.0.0.1:${address2.port}` || !allowedOrigins.has(req.headers.origin || "") || req.url !== "/callback") {
51
96
  res.writeHead(403).end();
52
97
  return;
53
98
  }
54
- res.setHeader("Access-Control-Allow-Origin", origin);
99
+ res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
55
100
  res.setHeader("Vary", "Origin");
56
101
  res.setHeader("Cache-Control", "no-store");
57
102
  if (req.method === "OPTIONS") {
@@ -67,16 +112,17 @@ async function createLoginReceiver(origin, onKey) {
67
112
  }
68
113
  try {
69
114
  const body = await readBody(req);
70
- if (typeof body.state !== "string" || Buffer.byteLength(body.state) !== Buffer.byteLength(state) || !(0, import_node_crypto.timingSafeEqual)(Buffer.from(body.state), Buffer.from(state)) || consumed) {
115
+ if (typeof body.state !== "string" || Buffer.byteLength(body.state) !== Buffer.byteLength(state) || !(0, import_node_crypto2.timingSafeEqual)(Buffer.from(body.state), Buffer.from(state)) || consumed) {
71
116
  res.writeHead(403).end();
72
117
  return;
73
118
  }
74
- if (typeof body.apiKey !== "string" || !body.apiKey.trim() || body.apiKey.length > 4096 || /[\r\n]/.test(body.apiKey)) {
119
+ if (!isClientSession(body)) {
75
120
  res.writeHead(400).end();
76
121
  return;
77
122
  }
78
123
  consumed = true;
79
- await onKey(body.apiKey);
124
+ await onKey(body);
125
+ if (onAccepted) res.once("finish", onAccepted);
80
126
  res.setHeader("Content-Type", "application/json");
81
127
  res.end(JSON.stringify({ accepted: true }));
82
128
  } catch {
@@ -110,12 +156,13 @@ async function readBody(req) {
110
156
 
111
157
  // src/authWorker.ts
112
158
  async function main() {
159
+ const origin = new URL(process.argv[2] || "https://app.adspower.com").origin;
113
160
  const lock = (0, import_node_net2.createServer)((socket) => socket.destroy());
114
161
  await new Promise((resolve, reject) => {
115
162
  lock.once("error", reject);
116
163
  lock.listen({ host: "127.0.0.1", port: 59753, exclusive: true }, resolve);
117
164
  });
118
- const id = (0, import_node_crypto2.randomUUID)();
165
+ const id = (0, import_node_crypto3.randomUUID)();
119
166
  const ownsSession = async () => {
120
167
  try {
121
168
  return JSON.parse(await import_node_fs2.promises.readFile(pendingPath, "utf8")).id === id;
@@ -124,8 +171,6 @@ async function main() {
124
171
  }
125
172
  };
126
173
  let finishing = false;
127
- let cancelling = false;
128
- let starter;
129
174
  let receiver;
130
175
  let expiry;
131
176
  let cancellation;
@@ -141,44 +186,21 @@ async function main() {
141
186
  lock.close();
142
187
  }
143
188
  };
144
- const cancel = () => {
145
- if (cancelling || finishing) return;
146
- cancelling = true;
147
- if (starter?.pid && starter.exitCode === null && starter.signalCode === null) {
148
- starter.kill();
149
- const force = setTimeout(() => starter?.kill("SIGKILL"), 2e3);
150
- starter.once("exit", () => clearTimeout(force));
151
- } else {
152
- void finish();
153
- }
154
- };
155
189
  try {
156
- await import_node_fs2.promises.mkdir(import_node_path2.default.dirname(pendingPath), { recursive: true, mode: 448 });
190
+ await import_node_fs2.promises.mkdir(import_node_path3.default.dirname(pendingPath), { recursive: true, mode: 448 });
157
191
  await import_node_fs2.promises.writeFile(pendingPath, JSON.stringify({ id, expiresAt: Date.now() + 3e5 }), { mode: 384 });
158
- receiver = await createLoginReceiver(LOGIN_ORIGIN, async (apiKey) => {
159
- if (finishing || cancelling || !await ownsSession()) throw new Error("Login cancelled");
160
- starter = (0, import_node_child_process2.spawn)(process.execPath, [import_node_path2.default.join(__dirname, "index.js"), "start", "--base-url", LOGIN_API_BASE], {
161
- env: { ...process.env, ADS_API_KEY: apiKey },
162
- stdio: "ignore",
163
- windowsHide: true
164
- });
165
- starter.once("error", () => {
166
- void finish();
167
- });
168
- starter.once("exit", () => {
169
- void finish();
170
- });
171
- starter.once("spawn", () => {
172
- clearTimeout(expiry);
173
- expiry = setTimeout(cancel, 6e4);
174
- });
192
+ receiver = await createLoginReceiver(origin, async (session) => {
193
+ if (finishing || !await ownsSession()) throw new Error("Login cancelled");
194
+ saveClientSession(session);
195
+ }, () => {
196
+ void finish();
175
197
  });
176
198
  expiry = setTimeout(() => {
177
199
  void finish();
178
200
  }, 3e5);
179
201
  cancellation = setInterval(() => {
180
202
  void ownsSession().then((owns) => {
181
- if (!owns) cancel();
203
+ if (!owns) void finish();
182
204
  });
183
205
  }, 500);
184
206
  process.send?.({ url: receiver.url });
@@ -188,6 +210,6 @@ async function main() {
188
210
  }
189
211
  }
190
212
  main().catch(() => {
191
- process.send?.({ error: "Unable to start login. Check that port 59753 is available, or run ads stop to cancel a pending login." });
213
+ process.send?.({ error: "Unable to start login. Check port 59753, or run ads logout to cancel a pending login." });
192
214
  process.exitCode = 1;
193
215
  });
package/cli/index.js CHANGED
@@ -23,23 +23,70 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  mod
24
24
  ));
25
25
 
26
+ // src/clientSession.ts
27
+ var fs2 = __toESM(require("fs"));
28
+ var import_node_path = __toESM(require("path"));
29
+ var import_node_crypto = require("crypto");
30
+
31
+ // src/tools/paths.ts
32
+ var os = __toESM(require("os"));
33
+ var path = __toESM(require("path"));
34
+ var fs = __toESM(require("fs"));
35
+ var import_fs_extra2 = require("fs-extra2");
36
+ var getHomedir = () => {
37
+ return (typeof os.homedir == "function" ? os.homedir() : process.env[process.platform == "win32" ? "USERPROFILE" : "HOME"]) || "~";
38
+ };
39
+ var getPidFileDir = (create = true) => {
40
+ const dir = path.join(getHomedir(), ".adspowerCli");
41
+ if (create && !fs.existsSync(dir)) {
42
+ (0, import_fs_extra2.ensureDirSync)(dir);
43
+ }
44
+ return dir;
45
+ };
46
+
47
+ // src/clientSession.ts
48
+ var isClientMode = () => process.env.IS_WORKBUDDY !== void 0;
49
+ var userFile = (userId) => import_node_path.default.join(getPidFileDir(false), (0, import_node_crypto.createHash)("md5").update(userId).digest("hex"));
50
+ var indexFile = () => import_node_path.default.join(getPidFileDir(false), "client-user.json");
51
+ var validPort = (value) => Number.isInteger(value) && Number(value) > 0 && Number(value) <= 65535;
52
+ function isClientSession(value) {
53
+ if (!value || typeof value !== "object") return false;
54
+ const session = value;
55
+ return typeof session.apiKey === "string" && !!session.apiKey.trim() && session.apiKey.length <= 4096 && !/[\r\n]/.test(session.apiKey) && typeof session.userId === "string" && !!session.userId.trim() && session.userId.length <= 256 && session.userId !== "1.0.0" && validPort(session.apiPort) && validPort(session.rpaPort);
56
+ }
57
+ function readClientSession() {
58
+ try {
59
+ const { userId } = JSON.parse(fs2.readFileSync(indexFile(), "utf8"));
60
+ if (typeof userId !== "string") return;
61
+ const session = JSON.parse(fs2.readFileSync(userFile(userId), "utf8"));
62
+ if (isClientSession(session) && session.userId === userId) return session;
63
+ } catch {
64
+ }
65
+ }
66
+ function removeClientSession() {
67
+ let userId;
68
+ try {
69
+ userId = JSON.parse(fs2.readFileSync(indexFile(), "utf8")).userId;
70
+ } catch (error) {
71
+ if (error.code !== "ENOENT") throw new Error("Cannot read WorkBuddy user index");
72
+ }
73
+ if (typeof userId === "string" && userId && userId !== "1.0.0") fs2.rmSync(userFile(userId), { force: true });
74
+ fs2.rmSync(indexFile(), { force: true });
75
+ }
76
+
26
77
  // src/auth.ts
27
78
  var import_node_child_process = require("child_process");
28
79
  var import_node_fs = require("fs");
29
80
  var import_node_os = __toESM(require("os"));
30
- var import_node_path = __toESM(require("path"));
81
+ var import_node_path2 = __toESM(require("path"));
31
82
  var import_node_net = require("net");
32
- var pendingPath = import_node_path.default.join(import_node_os.default.homedir(), ".adspowerCli", "workbuddy-login.json");
83
+ var pendingPath = import_node_path2.default.join(import_node_os.default.homedir(), ".adspowerCli", "workbuddy-login.json");
33
84
  async function cancelLogin() {
34
- try {
35
- await import_node_fs.promises.access(pendingPath);
36
- } catch {
37
- return;
38
- }
39
85
  await import_node_fs.promises.rm(pendingPath, { force: true });
40
86
  const deadline = Date.now() + 8e3;
41
87
  while (await loginWorkerIsRunning()) {
42
- if (Date.now() >= deadline) throw new Error("Login cancellation timed out; retry ads stop");
88
+ if (Date.now() >= deadline) throw new Error("Login cancellation timed out; retry ads logout");
89
+ await import_node_fs.promises.rm(pendingPath, { force: true });
43
90
  await new Promise((resolve) => setTimeout(resolve, 100));
44
91
  }
45
92
  }
@@ -55,13 +102,13 @@ async function loginWorkerIsRunning() {
55
102
  socket.setTimeout(500, () => done(true));
56
103
  });
57
104
  }
58
- async function login() {
105
+ async function login(input = {}) {
59
106
  const options = {
60
107
  detached: true,
61
108
  windowsHide: true,
62
109
  stdio: ["ignore", "ignore", "ignore", "ipc"]
63
110
  };
64
- const child = (0, import_node_child_process.fork)(import_node_path.default.join(__dirname, "authWorker.js"), [], options);
111
+ const child = (0, import_node_child_process.fork)(import_node_path2.default.join(__dirname, "authWorker.js"), [input.loginhost || "https://app.adspower.com"], options);
65
112
  await new Promise((resolve, reject) => {
66
113
  const timer = setTimeout(() => {
67
114
  child.kill();
@@ -160,21 +207,20 @@ var Store = class {
160
207
  var store = new Store();
161
208
 
162
209
  // src/core/start.ts
163
- var fs4 = __toESM(require("fs"));
164
- var path5 = __toESM(require("path"));
210
+ var fs6 = __toESM(require("fs"));
211
+ var path7 = __toESM(require("path"));
165
212
  var import_node_child_process4 = require("child_process");
166
213
 
167
214
  // src/tools/index.ts
168
215
  var readline = __toESM(require("readline/promises"));
169
- var os2 = __toESM(require("os"));
170
- var path2 = __toESM(require("path"));
171
- var fs2 = __toESM(require("fs"));
216
+ var path4 = __toESM(require("path"));
217
+ var fs4 = __toESM(require("fs"));
172
218
  var crypto = __toESM(require("crypto"));
173
219
  var util = __toESM(require("util"));
174
220
  var import_node_child_process2 = require("child_process");
175
221
  var import_colors = require("colors");
176
- var import_fs_extra2 = require("fs-extra2");
177
- var VERSION = (0, import_fs_extra2.readJsonSync)(path2.join(__dirname, "../package.json")).version;
222
+ var import_fs_extra22 = require("fs-extra2");
223
+ var VERSION = (0, import_fs_extra22.readJsonSync)(path4.join(__dirname, "../package.json")).version;
178
224
  var VERSION_FILE = "1.0.0";
179
225
  var toTerminalLink = (url, label) => {
180
226
  const text = label || url;
@@ -217,36 +263,26 @@ var taskKillFlowser = () => new Promise((resolve) => {
217
263
  resolve();
218
264
  });
219
265
  });
220
- var getHomedir = () => {
221
- return (typeof os2.homedir == "function" ? os2.homedir() : process.env[process.platform == "win32" ? "USERPROFILE" : "HOME"]) || "~";
222
- };
223
- var getPidFileDir = (create = true) => {
224
- const dir = path2.join(getHomedir(), ".adspowerCli");
225
- if (create && !fs2.existsSync(dir)) {
226
- (0, import_fs_extra2.ensureDirSync)(dir);
227
- }
228
- return dir;
229
- };
230
266
  var pidFileName = () => {
231
267
  const md5 = crypto.createHash("md5").update(VERSION_FILE).digest("hex");
232
268
  return md5;
233
269
  };
234
270
  var writePidFile = (config2) => {
235
- const filePath = path2.join(getPidFileDir(), pidFileName());
236
- (0, import_fs_extra2.outputJsonSync)(filePath, config2 || {}, { mode: 384 });
237
- if (process.platform !== "win32") fs2.chmodSync(filePath, 384);
271
+ const filePath = path4.join(getPidFileDir(), pidFileName());
272
+ (0, import_fs_extra22.outputJsonSync)(filePath, config2 || {}, { mode: 384 });
273
+ if (process.platform !== "win32") fs4.chmodSync(filePath, 384);
238
274
  };
239
275
  var readPidFile = () => {
240
- const filePath = path2.join(getPidFileDir(false), pidFileName());
241
- if (fs2.existsSync(filePath)) {
242
- return (0, import_fs_extra2.readJsonSync)(filePath);
276
+ const filePath = path4.join(getPidFileDir(false), pidFileName());
277
+ if (fs4.existsSync(filePath)) {
278
+ return (0, import_fs_extra22.readJsonSync)(filePath);
243
279
  }
244
280
  return {};
245
281
  };
246
282
  var removePidFile = () => {
247
- const filePath = path2.join(getPidFileDir(), pidFileName());
248
- if (fs2.existsSync(filePath)) {
249
- (0, import_fs_extra2.removeSync)(filePath);
283
+ const filePath = path4.join(getPidFileDir(), pidFileName());
284
+ if (fs4.existsSync(filePath)) {
285
+ (0, import_fs_extra22.removeSync)(filePath);
250
286
  }
251
287
  };
252
288
  var isRunning = (pid) => {
@@ -265,23 +301,30 @@ var isRunning = (pid) => {
265
301
  });
266
302
  };
267
303
  var ensureBrowserPath = () => {
268
- const dir = path2.join(__dirname, "../cwd/source", ".browser");
269
- if (!fs2.existsSync(dir)) {
270
- (0, import_fs_extra2.ensureDirSync)(dir);
304
+ const dir = path4.join(__dirname, "../cwd/source", ".browser");
305
+ if (!fs4.existsSync(dir)) {
306
+ (0, import_fs_extra22.ensureDirSync)(dir);
271
307
  }
272
308
  };
273
309
  var getApiKeyAndPort = (options) => {
310
+ if (isClientMode()) {
311
+ const session = readClientSession();
312
+ if (!session) throw new Error("No saved client connection. Run ads login first.");
313
+ return { apiKey: session.apiKey, port: String(session.apiPort), rpaPort: String(session.rpaPort) };
314
+ }
274
315
  const apiKey = options.apiKey;
275
316
  const port = options.port;
276
317
  if (port) {
277
318
  return {
278
319
  apiKey: apiKey || "",
279
- port
320
+ port,
321
+ rpaPort: options.rpaPort
280
322
  };
281
323
  }
282
324
  const result = {
283
325
  apiKey,
284
- port
326
+ port,
327
+ rpaPort: options.rpaPort
285
328
  };
286
329
  const processInstance = readPidFile();
287
330
  if (!apiKey) {
@@ -297,6 +340,7 @@ var getApiKeyAndPort = (options) => {
297
340
  return result;
298
341
  };
299
342
  var hasRunning = async (options) => {
343
+ if (isClientMode()) return !!readClientSession();
300
344
  const { port } = options;
301
345
  if (port) {
302
346
  return true;
@@ -334,8 +378,8 @@ var createLoading = (text) => {
334
378
  };
335
379
  };
336
380
  var initSqlite3 = () => {
337
- const sqliteFile = path2.join(__dirname, "../cwd/lib", "node_sqlite3.node");
338
- if (fs2.existsSync(sqliteFile)) {
381
+ const sqliteFile = path4.join(__dirname, "../cwd/lib", "node_sqlite3.node");
382
+ if (fs4.existsSync(sqliteFile)) {
339
383
  return;
340
384
  }
341
385
  const isMac = process.platform === "darwin";
@@ -347,13 +391,13 @@ var initSqlite3 = () => {
347
391
  const winFolder = is32 ? "ia32" : "x64";
348
392
  const linuxFolder = isLinux && isX64 && "linux";
349
393
  const sqliteFolder = isMac ? macFolder : isLinux ? linuxFolder : winFolder;
350
- const dir = path2.join(__dirname, `../sqlite/${sqliteFolder}`);
351
- if (!fs2.existsSync(dir)) {
394
+ const dir = path4.join(__dirname, `../sqlite/${sqliteFolder}`);
395
+ if (!fs4.existsSync(dir)) {
352
396
  throw new Error(`SQLite folder not found: ${dir}`);
353
397
  } else {
354
- const sqliteFile2 = path2.join(dir, "node_sqlite3.node");
355
- const cwdPath = path2.join(__dirname, "../cwd/lib");
356
- (0, import_fs_extra2.copySync)(sqliteFile2, path2.join(cwdPath, "node_sqlite3.node"));
398
+ const sqliteFile2 = path4.join(dir, "node_sqlite3.node");
399
+ const cwdPath = path4.join(__dirname, "../cwd/lib");
400
+ (0, import_fs_extra22.copySync)(sqliteFile2, path4.join(cwdPath, "node_sqlite3.node"));
357
401
  logSuccess(`[i] SQLite file initialized successfully!`);
358
402
  }
359
403
  };
@@ -2912,11 +2956,11 @@ var import_axios3 = __toESM(require("axios"));
2912
2956
 
2913
2957
  // ../core/src/rpa/local/fileTransport.ts
2914
2958
  var import_promises = require("fs/promises");
2915
- var import_node_path2 = require("path");
2959
+ var import_node_path3 = require("path");
2916
2960
  var import_node_zlib = require("zlib");
2917
2961
  var MAX_FLOW_BYTES = 32 * 1024 * 1024;
2918
2962
  async function readDebugProcess(filePath) {
2919
- if (!(0, import_node_path2.isAbsolute)(filePath)) throw new Error("process_file must be an absolute local path");
2963
+ if (!(0, import_node_path3.isAbsolute)(filePath)) throw new Error("process_file must be an absolute local path");
2920
2964
  const file = await (0, import_promises.open)(filePath, "r");
2921
2965
  let bytes;
2922
2966
  try {
@@ -2939,7 +2983,7 @@ async function readDebugProcess(filePath) {
2939
2983
  }
2940
2984
  async function writeRpaLogResult(data, outputFile) {
2941
2985
  if (!outputFile) return JSON.stringify(data, null, 2);
2942
- if (!(0, import_node_path2.isAbsolute)(outputFile)) throw new Error("output_file must be an absolute local path");
2986
+ if (!(0, import_node_path3.isAbsolute)(outputFile)) throw new Error("output_file must be an absolute local path");
2943
2987
  await (0, import_promises.writeFile)(outputFile, JSON.stringify(data), { flag: "wx", mode: 384 });
2944
2988
  const result = Array.isArray(data) ? { total_items: data.length, items: data.slice(0, 10).map(summarizeLog), next_offset: data.length > 10 ? 10 : null } : summarizeLog(data);
2945
2989
  return JSON.stringify({ output_file: outputFile, ...result }, null, 2);
@@ -4658,13 +4702,18 @@ var trackKernelDownload = async (fnc, args) => {
4658
4702
  var handleAction = async (params, options, command, fnc) => {
4659
4703
  const isRun = await hasRunning(options);
4660
4704
  if (!isRun) {
4705
+ if (isClientMode()) {
4706
+ logError("[!] No saved client connection. Run ads login first.");
4707
+ process.exitCode = 1;
4708
+ return;
4709
+ }
4661
4710
  logError("[!] Adspower runtime is not running");
4662
4711
  const info = `[i] Please run "${(0, import_colors2.green)("adspower-browser start -k <apiKey>")}" to start the adspower runtime`;
4663
4712
  console.log(info);
4664
4713
  return;
4665
4714
  }
4666
- const { apiKey, port } = getApiKeyAndPort(options);
4667
- updateConfig(apiKey, port, options.rpaPort);
4715
+ const { apiKey, port, rpaPort } = getApiKeyAndPort(options);
4716
+ updateConfig(apiKey, port, rpaPort);
4668
4717
  const commandName = command.name();
4669
4718
  const isRpaCommand = Object.prototype.hasOwnProperty.call(RPA_HANDLERS, commandName);
4670
4719
  const resolved = resolveStatelessCommandArgs(commandName, params);
@@ -4688,7 +4737,7 @@ ${out}
4688
4737
  } else if (commandName === "update-patch") {
4689
4738
  const result = await fnc(args);
4690
4739
  const out = typeof result === "string" ? result : JSON.stringify(result, null, 2);
4691
- if (!out.includes("The client is already on the latest patch version. No update is required")) {
4740
+ if (!isClientMode() && !out.includes("The client is already on the latest patch version. No update is required")) {
4692
4741
  await sleepTime(1e3 * 60);
4693
4742
  loading.stop();
4694
4743
  await restartChild();
@@ -4793,8 +4842,8 @@ var getRuntimeExecArgv = () => {
4793
4842
  if (process.platform !== "win32") {
4794
4843
  return [];
4795
4844
  }
4796
- const preload = path5.join(__dirname, "core/winHideChildProcess.js");
4797
- if (!fs4.existsSync(preload)) {
4845
+ const preload = path7.join(__dirname, "core/winHideChildProcess.js");
4846
+ if (!fs6.existsSync(preload)) {
4798
4847
  return [];
4799
4848
  }
4800
4849
  return ["--require", preload];
@@ -4833,7 +4882,7 @@ var startChild = (type) => {
4833
4882
  Object.entries(getEnv()).map(([key, value]) => [key, value == null ? value : String(value)])
4834
4883
  );
4835
4884
  try {
4836
- const mainJs = path5.join(__dirname, "../cwd/lib", "main.min.js");
4885
+ const mainJs = path7.join(__dirname, "../cwd/lib", "main.min.js");
4837
4886
  const forkOptions = {
4838
4887
  env,
4839
4888
  detached: true,
@@ -5114,37 +5163,43 @@ function wrapShellScriptOutput(shell) {
5114
5163
  // src/index.ts
5115
5164
  var program = new import_commander2.Command();
5116
5165
  program.description("CLI and runtime for adspower-browser").version(VERSION);
5117
- program.command("login").description("Authorize AdsPower CLI from WorkBuddy in your browser").action(login);
5118
- program.command("logstatus").description("Check the runtime status for login").action(async () => {
5119
- const authenticated = await getChildStatus();
5120
- console.log(JSON.stringify({ authenticated, state: authenticated ? "ready" : "logged_out" }));
5121
- process.exitCode = authenticated ? 0 : 1;
5122
- });
5123
- program.command("start").description("Start the adspower runtime").option("-k, --api-key <apiKey>", "Set the API key for the adspower runtime").addOption(new import_commander2.Option("--base-url <baseUrl>", "Set the base URL for the adspower runtime").hideHelp()).addOption(new import_commander2.Option("--node-env <nodeEnv>", "Set the node environment for the adspower runtime").hideHelp()).action(async (options) => {
5124
- const resolvedApiKey = resolveStartApiKey(options.apiKey, process.env);
5125
- if (!resolvedApiKey.ok) {
5126
- logError(resolvedApiKey.error);
5127
- process.exit(1);
5128
- }
5129
- store.setStoreValue("apiKey", resolvedApiKey.apiKey);
5130
- if (options.baseUrl) {
5131
- store.setStoreValue("baseUrl", options.baseUrl);
5132
- }
5133
- if (options.nodeEnv) {
5134
- store.setStoreValue("nodeEnv", options.nodeEnv);
5135
- }
5136
- await startChild();
5137
- });
5138
- program.command("stop").description("Stop the adspower runtime").action(async () => {
5139
- await cancelLogin();
5140
- await stopChild();
5141
- });
5142
- program.command("restart").description("Restart the adspower runtime").action(async () => {
5143
- await restartChild();
5144
- });
5145
- program.command("status").description("Get the status of the adspower runtime").action(async () => {
5146
- await getChildStatus();
5147
- });
5166
+ if (isClientMode()) {
5167
+ program.command("login").description("Authorize AdsPower CLI from WorkBuddy in your browser").option("--loginhost <loginhost>", "Set the authorization site origin (or /login URL)").action(login);
5168
+ program.command("logstatus").description("Check the saved client connection").action(async () => {
5169
+ const authenticated = !!readClientSession();
5170
+ console.log(JSON.stringify({ authenticated, state: authenticated ? "ready" : "logged_out" }));
5171
+ process.exitCode = authenticated ? 0 : 1;
5172
+ });
5173
+ program.command("logout").description("Remove the saved WorkBuddy client connection").action(async () => {
5174
+ await cancelLogin();
5175
+ removeClientSession();
5176
+ });
5177
+ } else {
5178
+ program.command("start").description("Start the adspower runtime").option("-k, --api-key <apiKey>", "Set the API key for the adspower runtime").addOption(new import_commander2.Option("--base-url <baseUrl>", "Set the base URL for the adspower runtime").hideHelp()).addOption(new import_commander2.Option("--node-env <nodeEnv>", "Set the node environment for the adspower runtime").hideHelp()).action(async (options) => {
5179
+ const resolvedApiKey = resolveStartApiKey(options.apiKey, process.env);
5180
+ if (!resolvedApiKey.ok) {
5181
+ logError(resolvedApiKey.error);
5182
+ process.exit(1);
5183
+ }
5184
+ store.setStoreValue("apiKey", resolvedApiKey.apiKey);
5185
+ if (options.baseUrl) {
5186
+ store.setStoreValue("baseUrl", options.baseUrl);
5187
+ }
5188
+ if (options.nodeEnv) {
5189
+ store.setStoreValue("nodeEnv", options.nodeEnv);
5190
+ }
5191
+ await startChild();
5192
+ });
5193
+ program.command("stop").description("Stop the adspower runtime").action(async () => {
5194
+ await stopChild();
5195
+ });
5196
+ program.command("restart").description("Restart the adspower runtime").action(async () => {
5197
+ await restartChild();
5198
+ });
5199
+ program.command("status").description("Get the status of the adspower runtime").action(async () => {
5200
+ await getChildStatus();
5201
+ });
5202
+ }
5148
5203
  for (const cmd of Object.keys(STATELESS_HANDLERS)) {
5149
5204
  const fnc = STATELESS_HANDLERS[cmd].fn;
5150
5205
  program.command(`${cmd}`).description(STATELESS_HANDLERS[cmd].description).option("-k, --api-key <apiKey>", "Set the API key for the adspower runtime").option("-p, --port <port>", "Set the port for the adspower runtime").addOption(Object.assign(new import_commander2.Option("--rpa-port <port>", "Set the port for the local RPA Plus service"), {