adspower-browser 2.1.6 → 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/cli/index.js CHANGED
@@ -23,6 +23,120 @@ 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
+
77
+ // src/auth.ts
78
+ var import_node_child_process = require("child_process");
79
+ var import_node_fs = require("fs");
80
+ var import_node_os = __toESM(require("os"));
81
+ var import_node_path2 = __toESM(require("path"));
82
+ var import_node_net = require("net");
83
+ var pendingPath = import_node_path2.default.join(import_node_os.default.homedir(), ".adspowerCli", "workbuddy-login.json");
84
+ async function cancelLogin() {
85
+ await import_node_fs.promises.rm(pendingPath, { force: true });
86
+ const deadline = Date.now() + 8e3;
87
+ while (await loginWorkerIsRunning()) {
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 });
90
+ await new Promise((resolve) => setTimeout(resolve, 100));
91
+ }
92
+ }
93
+ async function loginWorkerIsRunning() {
94
+ return new Promise((resolve) => {
95
+ const socket = (0, import_node_net.createConnection)({ host: "127.0.0.1", port: 59753 });
96
+ const done = (running) => {
97
+ socket.destroy();
98
+ resolve(running);
99
+ };
100
+ socket.once("connect", () => done(true));
101
+ socket.once("error", () => done(false));
102
+ socket.setTimeout(500, () => done(true));
103
+ });
104
+ }
105
+ async function login(input = {}) {
106
+ const options = {
107
+ detached: true,
108
+ windowsHide: true,
109
+ stdio: ["ignore", "ignore", "ignore", "ipc"]
110
+ };
111
+ const child = (0, import_node_child_process.fork)(import_node_path2.default.join(__dirname, "authWorker.js"), [input.loginhost || "https://app.adspower.com"], options);
112
+ await new Promise((resolve, reject) => {
113
+ const timer = setTimeout(() => {
114
+ child.kill();
115
+ reject(new Error("Login receiver startup timed out"));
116
+ }, 8e3);
117
+ child.once("error", () => {
118
+ clearTimeout(timer);
119
+ reject(new Error("Unable to start login receiver"));
120
+ });
121
+ child.once("exit", () => {
122
+ clearTimeout(timer);
123
+ reject(new Error("Login receiver exited before becoming ready"));
124
+ });
125
+ child.once("message", (message) => {
126
+ clearTimeout(timer);
127
+ if (!message.url) {
128
+ child.kill();
129
+ reject(new Error(message.error || "Unable to prepare login"));
130
+ return;
131
+ }
132
+ child.disconnect();
133
+ child.unref();
134
+ console.log(message.url);
135
+ resolve();
136
+ });
137
+ });
138
+ }
139
+
26
140
  // src/index.ts
27
141
  var import_commander2 = require("commander");
28
142
 
@@ -93,21 +207,20 @@ var Store = class {
93
207
  var store = new Store();
94
208
 
95
209
  // src/core/start.ts
96
- var fs3 = __toESM(require("fs"));
97
- var path4 = __toESM(require("path"));
98
- var import_node_child_process3 = require("child_process");
210
+ var fs6 = __toESM(require("fs"));
211
+ var path7 = __toESM(require("path"));
212
+ var import_node_child_process4 = require("child_process");
99
213
 
100
214
  // src/tools/index.ts
101
215
  var readline = __toESM(require("readline/promises"));
102
- var os = __toESM(require("os"));
103
- var path = __toESM(require("path"));
104
- var fs = __toESM(require("fs"));
216
+ var path4 = __toESM(require("path"));
217
+ var fs4 = __toESM(require("fs"));
105
218
  var crypto = __toESM(require("crypto"));
106
219
  var util = __toESM(require("util"));
107
- var import_node_child_process = require("child_process");
220
+ var import_node_child_process2 = require("child_process");
108
221
  var import_colors = require("colors");
109
- var import_fs_extra2 = require("fs-extra2");
110
- var VERSION = (0, import_fs_extra2.readJsonSync)(path.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;
111
224
  var VERSION_FILE = "1.0.0";
112
225
  var toTerminalLink = (url, label) => {
113
226
  const text = label || url;
@@ -136,7 +249,7 @@ var browsersKill = async () => {
136
249
  };
137
250
  var taskKillBrowser = () => new Promise((resolve) => {
138
251
  const cmd = ["linux", "darwin"].includes(process.platform) ? 'pkill -u `whoami` -f "SunBrowser"' : "taskkill -PID SunBrowser.exe";
139
- (0, import_node_child_process.exec)(cmd, { windowsHide: true }, (err) => {
252
+ (0, import_node_child_process2.exec)(cmd, { windowsHide: true }, (err) => {
140
253
  if (err) {
141
254
  }
142
255
  resolve();
@@ -144,47 +257,38 @@ var taskKillBrowser = () => new Promise((resolve) => {
144
257
  });
145
258
  var taskKillFlowser = () => new Promise((resolve) => {
146
259
  const cmd = ["linux", "darwin"].includes(process.platform) ? 'pkill -u `whoami` -f "FlowerBrowser"' : "taskkill -PID FlowerBrowser.exe";
147
- (0, import_node_child_process.exec)(cmd, { windowsHide: true }, (err) => {
260
+ (0, import_node_child_process2.exec)(cmd, { windowsHide: true }, (err) => {
148
261
  if (err) {
149
262
  }
150
263
  resolve();
151
264
  });
152
265
  });
153
- var getHomedir = () => {
154
- return (typeof os.homedir == "function" ? os.homedir() : process.env[process.platform == "win32" ? "USERPROFILE" : "HOME"]) || "~";
155
- };
156
- var getPidFileDir = () => {
157
- const dir = path.join(getHomedir(), ".adspowerCli");
158
- if (!fs.existsSync(dir)) {
159
- (0, import_fs_extra2.ensureDirSync)(dir);
160
- }
161
- return dir;
162
- };
163
266
  var pidFileName = () => {
164
267
  const md5 = crypto.createHash("md5").update(VERSION_FILE).digest("hex");
165
268
  return md5;
166
269
  };
167
270
  var writePidFile = (config2) => {
168
- const filePath = path.join(getPidFileDir(), pidFileName());
169
- (0, import_fs_extra2.outputJsonSync)(filePath, config2 || {});
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);
170
274
  };
171
275
  var readPidFile = () => {
172
- const filePath = path.join(getPidFileDir(), pidFileName());
173
- if (fs.existsSync(filePath)) {
174
- 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);
175
279
  }
176
280
  return {};
177
281
  };
178
282
  var removePidFile = () => {
179
- const filePath = path.join(getPidFileDir(), pidFileName());
180
- if (fs.existsSync(filePath)) {
181
- (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);
182
286
  }
183
287
  };
184
288
  var isRunning = (pid) => {
185
289
  return new Promise((resolve) => {
186
290
  if (pid) {
187
- (0, import_node_child_process.exec)(
291
+ (0, import_node_child_process2.exec)(
188
292
  util.format(process.platform === "win32" ? 'tasklist /fi "PID eq %s" | findstr /i "node.exe"' : 'ps -f -p %s | grep "node"', pid),
189
293
  { windowsHide: true },
190
294
  function(err, stdout, stderr) {
@@ -197,23 +301,30 @@ var isRunning = (pid) => {
197
301
  });
198
302
  };
199
303
  var ensureBrowserPath = () => {
200
- const dir = path.join(__dirname, "../cwd/source", ".browser");
201
- if (!fs.existsSync(dir)) {
202
- (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);
203
307
  }
204
308
  };
205
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
+ }
206
315
  const apiKey = options.apiKey;
207
316
  const port = options.port;
208
317
  if (port) {
209
318
  return {
210
319
  apiKey: apiKey || "",
211
- port
320
+ port,
321
+ rpaPort: options.rpaPort
212
322
  };
213
323
  }
214
324
  const result = {
215
325
  apiKey,
216
- port
326
+ port,
327
+ rpaPort: options.rpaPort
217
328
  };
218
329
  const processInstance = readPidFile();
219
330
  if (!apiKey) {
@@ -229,6 +340,7 @@ var getApiKeyAndPort = (options) => {
229
340
  return result;
230
341
  };
231
342
  var hasRunning = async (options) => {
343
+ if (isClientMode()) return !!readClientSession();
232
344
  const { port } = options;
233
345
  if (port) {
234
346
  return true;
@@ -266,8 +378,8 @@ var createLoading = (text) => {
266
378
  };
267
379
  };
268
380
  var initSqlite3 = () => {
269
- const sqliteFile = path.join(__dirname, "../cwd/lib", "node_sqlite3.node");
270
- if (fs.existsSync(sqliteFile)) {
381
+ const sqliteFile = path4.join(__dirname, "../cwd/lib", "node_sqlite3.node");
382
+ if (fs4.existsSync(sqliteFile)) {
271
383
  return;
272
384
  }
273
385
  const isMac = process.platform === "darwin";
@@ -279,13 +391,13 @@ var initSqlite3 = () => {
279
391
  const winFolder = is32 ? "ia32" : "x64";
280
392
  const linuxFolder = isLinux && isX64 && "linux";
281
393
  const sqliteFolder = isMac ? macFolder : isLinux ? linuxFolder : winFolder;
282
- const dir = path.join(__dirname, `../sqlite/${sqliteFolder}`);
283
- if (!fs.existsSync(dir)) {
394
+ const dir = path4.join(__dirname, `../sqlite/${sqliteFolder}`);
395
+ if (!fs4.existsSync(dir)) {
284
396
  throw new Error(`SQLite folder not found: ${dir}`);
285
397
  } else {
286
- const sqliteFile2 = path.join(dir, "node_sqlite3.node");
287
- const cwdPath = path.join(__dirname, "../cwd/lib");
288
- (0, import_fs_extra2.copySync)(sqliteFile2, path.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"));
289
401
  logSuccess(`[i] SQLite file initialized successfully!`);
290
402
  }
291
403
  };
@@ -318,7 +430,7 @@ async function promptYesNo(question) {
318
430
  var import_axios = __toESM(require("axios"));
319
431
  var import_fs = __toESM(require("fs"));
320
432
  var import_path = __toESM(require("path"));
321
- var import_node_child_process2 = require("child_process");
433
+ var import_node_child_process3 = require("child_process");
322
434
  var NPM_PACKAGE_NAME = "adspower-browser";
323
435
  var NPM_REGISTRY_URL = `https://registry.npmjs.org/${NPM_PACKAGE_NAME}/latest`;
324
436
  var checkUpdates = async (apiKey, baseUrl) => {
@@ -395,7 +507,7 @@ var checkUpdateNpmPackage = async () => {
395
507
  var updateNpmPackage = async () => {
396
508
  const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
397
509
  await new Promise((resolve, reject) => {
398
- const child = (0, import_node_child_process2.spawn)(npmCommand, ["install", "-g", `${NPM_PACKAGE_NAME}@latest`], {
510
+ const child = (0, import_node_child_process3.spawn)(npmCommand, ["install", "-g", `${NPM_PACKAGE_NAME}@latest`], {
399
511
  stdio: "inherit",
400
512
  windowsHide: true
401
513
  });
@@ -1388,7 +1500,7 @@ function buildCliCommandDescription(commandName, legacyFallback) {
1388
1500
  }
1389
1501
 
1390
1502
  // ../core/src/handlers/browser.ts
1391
- var import_node_os = __toESM(require("os"));
1503
+ var import_node_os2 = __toESM(require("os"));
1392
1504
 
1393
1505
  // ../core/src/utils/requestBuilder.ts
1394
1506
  function toContractValue(value) {
@@ -1531,7 +1643,7 @@ var browserHandlers = {
1531
1643
  const { params: resolvedParams, didAutoSetHeadless } = resolveOpenBrowserHeadless(
1532
1644
  params,
1533
1645
  process.env,
1534
- import_node_os.default.platform()
1646
+ import_node_os2.default.platform()
1535
1647
  );
1536
1648
  const requestBody = buildRequestBodyFor("open-browser", resolvedParams);
1537
1649
  const response = await getApiClient().post(`${getLocalApiBase()}${API_ENDPOINTS.START_BROWSER}`, requestBody);
@@ -2844,11 +2956,11 @@ var import_axios3 = __toESM(require("axios"));
2844
2956
 
2845
2957
  // ../core/src/rpa/local/fileTransport.ts
2846
2958
  var import_promises = require("fs/promises");
2847
- var import_node_path = require("path");
2959
+ var import_node_path3 = require("path");
2848
2960
  var import_node_zlib = require("zlib");
2849
2961
  var MAX_FLOW_BYTES = 32 * 1024 * 1024;
2850
2962
  async function readDebugProcess(filePath) {
2851
- if (!(0, import_node_path.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");
2852
2964
  const file = await (0, import_promises.open)(filePath, "r");
2853
2965
  let bytes;
2854
2966
  try {
@@ -2871,7 +2983,7 @@ async function readDebugProcess(filePath) {
2871
2983
  }
2872
2984
  async function writeRpaLogResult(data, outputFile) {
2873
2985
  if (!outputFile) return JSON.stringify(data, null, 2);
2874
- if (!(0, import_node_path.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");
2875
2987
  await (0, import_promises.writeFile)(outputFile, JSON.stringify(data), { flag: "wx", mode: 384 });
2876
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);
2877
2989
  return JSON.stringify({ output_file: outputFile, ...result }, null, 2);
@@ -4590,13 +4702,18 @@ var trackKernelDownload = async (fnc, args) => {
4590
4702
  var handleAction = async (params, options, command, fnc) => {
4591
4703
  const isRun = await hasRunning(options);
4592
4704
  if (!isRun) {
4705
+ if (isClientMode()) {
4706
+ logError("[!] No saved client connection. Run ads login first.");
4707
+ process.exitCode = 1;
4708
+ return;
4709
+ }
4593
4710
  logError("[!] Adspower runtime is not running");
4594
4711
  const info = `[i] Please run "${(0, import_colors2.green)("adspower-browser start -k <apiKey>")}" to start the adspower runtime`;
4595
4712
  console.log(info);
4596
4713
  return;
4597
4714
  }
4598
- const { apiKey, port } = getApiKeyAndPort(options);
4599
- updateConfig(apiKey, port, options.rpaPort);
4715
+ const { apiKey, port, rpaPort } = getApiKeyAndPort(options);
4716
+ updateConfig(apiKey, port, rpaPort);
4600
4717
  const commandName = command.name();
4601
4718
  const isRpaCommand = Object.prototype.hasOwnProperty.call(RPA_HANDLERS, commandName);
4602
4719
  const resolved = resolveStatelessCommandArgs(commandName, params);
@@ -4620,7 +4737,7 @@ ${out}
4620
4737
  } else if (commandName === "update-patch") {
4621
4738
  const result = await fnc(args);
4622
4739
  const out = typeof result === "string" ? result : JSON.stringify(result, null, 2);
4623
- 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")) {
4624
4741
  await sleepTime(1e3 * 60);
4625
4742
  loading.stop();
4626
4743
  await restartChild();
@@ -4725,8 +4842,8 @@ var getRuntimeExecArgv = () => {
4725
4842
  if (process.platform !== "win32") {
4726
4843
  return [];
4727
4844
  }
4728
- const preload = path4.join(__dirname, "core/winHideChildProcess.js");
4729
- if (!fs3.existsSync(preload)) {
4845
+ const preload = path7.join(__dirname, "core/winHideChildProcess.js");
4846
+ if (!fs6.existsSync(preload)) {
4730
4847
  return [];
4731
4848
  }
4732
4849
  return ["--require", preload];
@@ -4765,7 +4882,7 @@ var startChild = (type) => {
4765
4882
  Object.entries(getEnv()).map(([key, value]) => [key, value == null ? value : String(value)])
4766
4883
  );
4767
4884
  try {
4768
- const mainJs = path4.join(__dirname, "../cwd/lib", "main.min.js");
4885
+ const mainJs = path7.join(__dirname, "../cwd/lib", "main.min.js");
4769
4886
  const forkOptions = {
4770
4887
  env,
4771
4888
  detached: true,
@@ -4774,7 +4891,7 @@ var startChild = (type) => {
4774
4891
  stdio: ["ignore", "ignore", "ignore", "ipc"],
4775
4892
  execArgv: getRuntimeExecArgv()
4776
4893
  };
4777
- child = (0, import_node_child_process3.fork)(mainJs, [], forkOptions);
4894
+ child = (0, import_node_child_process4.fork)(mainJs, [], forkOptions);
4778
4895
  ensureBrowserPath();
4779
4896
  store.setStoreValue("status", "starting");
4780
4897
  logSuccess(`[i] Adspower program is starting...`);
@@ -4839,7 +4956,7 @@ var startChild = (type) => {
4839
4956
  if (serverMsg[1]) {
4840
4957
  logError(`ERROR - ${serverMsg[1]}`);
4841
4958
  }
4842
- process.exit(0);
4959
+ process.exit(1);
4843
4960
  }
4844
4961
  if (text === "start") {
4845
4962
  clearTimeout(timer);
@@ -4877,7 +4994,7 @@ var startChild = (type) => {
4877
4994
  store.setStoreValue("status", "stop");
4878
4995
  store.clear();
4879
4996
  removePidFile();
4880
- process.exit(0);
4997
+ process.exit(1);
4881
4998
  });
4882
4999
  child.on("exit", async (code, signal) => {
4883
5000
  await browsersKill();
@@ -4914,6 +5031,7 @@ var stopChild = async () => {
4914
5031
  removePidFile();
4915
5032
  } catch (error2) {
4916
5033
  logError(`[!] Stop child fail: ${error2 instanceof Error ? error2.message : JSON.stringify(error2)}`);
5034
+ process.exitCode = 1;
4917
5035
  if (isRun) {
4918
5036
  logWarning(`[!] Please manually close the browser process: ${processInstance.pid}`);
4919
5037
  }
@@ -4922,6 +5040,7 @@ var stopChild = async () => {
4922
5040
  }
4923
5041
  logSuccess("[i] Adspower program is stopped");
4924
5042
  } else {
5043
+ removePidFile();
4925
5044
  logInfo("[i] No running adspower program");
4926
5045
  }
4927
5046
  };
@@ -4952,14 +5071,16 @@ var getChildStatus = async () => {
4952
5071
  if (!isRun) {
4953
5072
  removePidFile();
4954
5073
  logInfo("[i] Adspower program is not running");
4955
- return;
5074
+ return false;
4956
5075
  }
4957
5076
  const status = processInstance.status;
4958
5077
  if (status === "starting") {
4959
5078
  logSuccess("[i] Adspower program is starting...");
5079
+ return true;
4960
5080
  } else if (status === "doing" && processInstance.apiPort) {
4961
5081
  logSuccess("[i] Adspower program is running at:");
4962
5082
  logSuccess(` - http://local.adspower.net:${processInstance.apiPort}`);
5083
+ return true;
4963
5084
  } else if (status === "stop") {
4964
5085
  logInfo("[i] Adspower program is stopped");
4965
5086
  } else {
@@ -4968,6 +5089,7 @@ var getChildStatus = async () => {
4968
5089
  } else {
4969
5090
  logInfo("[i] Adspower program is not running");
4970
5091
  }
5092
+ return false;
4971
5093
  };
4972
5094
 
4973
5095
  // src/startConfig.ts
@@ -5041,30 +5163,43 @@ function wrapShellScriptOutput(shell) {
5041
5163
  // src/index.ts
5042
5164
  var program = new import_commander2.Command();
5043
5165
  program.description("CLI and runtime for adspower-browser").version(VERSION);
5044
- 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) => {
5045
- const resolvedApiKey = resolveStartApiKey(options.apiKey, process.env);
5046
- if (!resolvedApiKey.ok) {
5047
- logError(resolvedApiKey.error);
5048
- process.exit(1);
5049
- }
5050
- store.setStoreValue("apiKey", resolvedApiKey.apiKey);
5051
- if (options.baseUrl) {
5052
- store.setStoreValue("baseUrl", options.baseUrl);
5053
- }
5054
- if (options.nodeEnv) {
5055
- store.setStoreValue("nodeEnv", options.nodeEnv);
5056
- }
5057
- await startChild();
5058
- });
5059
- program.command("stop").description("Stop the adspower runtime").action(async () => {
5060
- await stopChild();
5061
- });
5062
- program.command("restart").description("Restart the adspower runtime").action(async () => {
5063
- await restartChild();
5064
- });
5065
- program.command("status").description("Get the status of the adspower runtime").action(async () => {
5066
- getChildStatus();
5067
- });
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
+ }
5068
5203
  for (const cmd of Object.keys(STATELESS_HANDLERS)) {
5069
5204
  const fnc = STATELESS_HANDLERS[cmd].fn;
5070
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"), {