adspower-browser 2.1.6-beta.0 → 2.1.7-beta.0

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
@@ -228,3 +228,41 @@ docker-compose -f ./docker-compose.yml up -d
228
228
 
229
229
  docker-compose exec adspower-cli /bin/bash
230
230
  ```
231
+
232
+
233
+ ## WorkBuddy browser login
234
+
235
+ ```bash
236
+ ads login
237
+ ads logstatus
238
+ ads stop
239
+ ```
240
+
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
+ ```
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+
25
+ // src/authWorker.ts
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");
30
+ var import_node_net2 = require("net");
31
+
32
+ // src/auth.ts
33
+ var import_node_child_process = require("child_process");
34
+ var import_node_fs = require("fs");
35
+ var import_node_os = __toESM(require("os"));
36
+ var import_node_path = __toESM(require("path"));
37
+ 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
+ var pendingPath = import_node_path.default.join(import_node_os.default.homedir(), ".adspowerCli", "workbuddy-login.json");
41
+
42
+ // src/loginReceiver.ts
43
+ 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");
47
+ let consumed = false;
48
+ const server = (0, import_node_http.createServer)(async (req, res) => {
49
+ 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") {
51
+ res.writeHead(403).end();
52
+ return;
53
+ }
54
+ res.setHeader("Access-Control-Allow-Origin", origin);
55
+ res.setHeader("Vary", "Origin");
56
+ res.setHeader("Cache-Control", "no-store");
57
+ if (req.method === "OPTIONS") {
58
+ res.setHeader("Access-Control-Allow-Methods", "POST");
59
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
60
+ res.setHeader("Access-Control-Allow-Private-Network", "true");
61
+ res.writeHead(204).end();
62
+ return;
63
+ }
64
+ if (req.method !== "POST" || req.headers["content-type"]?.split(";")[0] !== "application/json") {
65
+ res.writeHead(405).end();
66
+ return;
67
+ }
68
+ try {
69
+ 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) {
71
+ res.writeHead(403).end();
72
+ return;
73
+ }
74
+ if (typeof body.apiKey !== "string" || !body.apiKey.trim() || body.apiKey.length > 4096 || /[\r\n]/.test(body.apiKey)) {
75
+ res.writeHead(400).end();
76
+ return;
77
+ }
78
+ consumed = true;
79
+ await onKey(body.apiKey);
80
+ res.setHeader("Content-Type", "application/json");
81
+ res.end(JSON.stringify({ accepted: true }));
82
+ } catch {
83
+ res.writeHead(400).end();
84
+ }
85
+ });
86
+ server.requestTimeout = 1e4;
87
+ server.headersTimeout = 1e4;
88
+ await new Promise((resolve, reject) => {
89
+ server.once("error", reject);
90
+ server.listen(0, "127.0.0.1", resolve);
91
+ });
92
+ const address = server.address();
93
+ if (!address || typeof address === "string") throw new Error("Invalid receiver address");
94
+ const url = new URL("/login", origin);
95
+ url.searchParams.set("source", "workbuddy");
96
+ url.hash = new URLSearchParams({ workbuddy_port: String(address.port), workbuddy_state: state }).toString();
97
+ return { url: url.href, close: () => {
98
+ server.close();
99
+ server.closeAllConnections();
100
+ } };
101
+ }
102
+ async function readBody(req) {
103
+ let body = "";
104
+ for await (const chunk of req) {
105
+ body += chunk.toString();
106
+ if (Buffer.byteLength(body) > 8192) throw new Error("Body too large");
107
+ }
108
+ return JSON.parse(body);
109
+ }
110
+
111
+ // src/authWorker.ts
112
+ async function main() {
113
+ const lock = (0, import_node_net2.createServer)((socket) => socket.destroy());
114
+ await new Promise((resolve, reject) => {
115
+ lock.once("error", reject);
116
+ lock.listen({ host: "127.0.0.1", port: 59753, exclusive: true }, resolve);
117
+ });
118
+ const id = (0, import_node_crypto2.randomUUID)();
119
+ const ownsSession = async () => {
120
+ try {
121
+ return JSON.parse(await import_node_fs2.promises.readFile(pendingPath, "utf8")).id === id;
122
+ } catch {
123
+ return false;
124
+ }
125
+ };
126
+ let finishing = false;
127
+ let cancelling = false;
128
+ let starter;
129
+ let receiver;
130
+ let expiry;
131
+ let cancellation;
132
+ const finish = async () => {
133
+ if (finishing) return;
134
+ finishing = true;
135
+ clearTimeout(expiry);
136
+ clearInterval(cancellation);
137
+ receiver?.close();
138
+ try {
139
+ if (await ownsSession()) await import_node_fs2.promises.rm(pendingPath, { force: true });
140
+ } finally {
141
+ lock.close();
142
+ }
143
+ };
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
+ try {
156
+ await import_node_fs2.promises.mkdir(import_node_path2.default.dirname(pendingPath), { recursive: true, mode: 448 });
157
+ 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
+ });
175
+ });
176
+ expiry = setTimeout(() => {
177
+ void finish();
178
+ }, 3e5);
179
+ cancellation = setInterval(() => {
180
+ void ownsSession().then((owns) => {
181
+ if (!owns) cancel();
182
+ });
183
+ }, 500);
184
+ process.send?.({ url: receiver.url });
185
+ } catch {
186
+ await finish();
187
+ throw new Error("Unable to initialize login receiver");
188
+ }
189
+ }
190
+ 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." });
192
+ process.exitCode = 1;
193
+ });
package/cli/index.js CHANGED
@@ -23,6 +23,73 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  mod
24
24
  ));
25
25
 
26
+ // src/auth.ts
27
+ var import_node_child_process = require("child_process");
28
+ var import_node_fs = require("fs");
29
+ var import_node_os = __toESM(require("os"));
30
+ var import_node_path = __toESM(require("path"));
31
+ var import_node_net = require("net");
32
+ var pendingPath = import_node_path.default.join(import_node_os.default.homedir(), ".adspowerCli", "workbuddy-login.json");
33
+ async function cancelLogin() {
34
+ try {
35
+ await import_node_fs.promises.access(pendingPath);
36
+ } catch {
37
+ return;
38
+ }
39
+ await import_node_fs.promises.rm(pendingPath, { force: true });
40
+ const deadline = Date.now() + 8e3;
41
+ while (await loginWorkerIsRunning()) {
42
+ if (Date.now() >= deadline) throw new Error("Login cancellation timed out; retry ads stop");
43
+ await new Promise((resolve) => setTimeout(resolve, 100));
44
+ }
45
+ }
46
+ async function loginWorkerIsRunning() {
47
+ return new Promise((resolve) => {
48
+ const socket = (0, import_node_net.createConnection)({ host: "127.0.0.1", port: 59753 });
49
+ const done = (running) => {
50
+ socket.destroy();
51
+ resolve(running);
52
+ };
53
+ socket.once("connect", () => done(true));
54
+ socket.once("error", () => done(false));
55
+ socket.setTimeout(500, () => done(true));
56
+ });
57
+ }
58
+ async function login() {
59
+ const options = {
60
+ detached: true,
61
+ windowsHide: true,
62
+ stdio: ["ignore", "ignore", "ignore", "ipc"]
63
+ };
64
+ const child = (0, import_node_child_process.fork)(import_node_path.default.join(__dirname, "authWorker.js"), [], options);
65
+ await new Promise((resolve, reject) => {
66
+ const timer = setTimeout(() => {
67
+ child.kill();
68
+ reject(new Error("Login receiver startup timed out"));
69
+ }, 8e3);
70
+ child.once("error", () => {
71
+ clearTimeout(timer);
72
+ reject(new Error("Unable to start login receiver"));
73
+ });
74
+ child.once("exit", () => {
75
+ clearTimeout(timer);
76
+ reject(new Error("Login receiver exited before becoming ready"));
77
+ });
78
+ child.once("message", (message) => {
79
+ clearTimeout(timer);
80
+ if (!message.url) {
81
+ child.kill();
82
+ reject(new Error(message.error || "Unable to prepare login"));
83
+ return;
84
+ }
85
+ child.disconnect();
86
+ child.unref();
87
+ console.log(message.url);
88
+ resolve();
89
+ });
90
+ });
91
+ }
92
+
26
93
  // src/index.ts
27
94
  var import_commander2 = require("commander");
28
95
 
@@ -93,21 +160,21 @@ var Store = class {
93
160
  var store = new Store();
94
161
 
95
162
  // 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");
163
+ var fs4 = __toESM(require("fs"));
164
+ var path5 = __toESM(require("path"));
165
+ var import_node_child_process4 = require("child_process");
99
166
 
100
167
  // src/tools/index.ts
101
168
  var readline = __toESM(require("readline/promises"));
102
- var os = __toESM(require("os"));
103
- var path = __toESM(require("path"));
104
- var fs = __toESM(require("fs"));
169
+ var os2 = __toESM(require("os"));
170
+ var path2 = __toESM(require("path"));
171
+ var fs2 = __toESM(require("fs"));
105
172
  var crypto = __toESM(require("crypto"));
106
173
  var util = __toESM(require("util"));
107
- var import_node_child_process = require("child_process");
174
+ var import_node_child_process2 = require("child_process");
108
175
  var import_colors = require("colors");
109
176
  var import_fs_extra2 = require("fs-extra2");
110
- var VERSION = (0, import_fs_extra2.readJsonSync)(path.join(__dirname, "../package.json")).version;
177
+ var VERSION = (0, import_fs_extra2.readJsonSync)(path2.join(__dirname, "../package.json")).version;
111
178
  var VERSION_FILE = "1.0.0";
112
179
  var toTerminalLink = (url, label) => {
113
180
  const text = label || url;
@@ -136,7 +203,7 @@ var browsersKill = async () => {
136
203
  };
137
204
  var taskKillBrowser = () => new Promise((resolve) => {
138
205
  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) => {
206
+ (0, import_node_child_process2.exec)(cmd, { windowsHide: true }, (err) => {
140
207
  if (err) {
141
208
  }
142
209
  resolve();
@@ -144,18 +211,18 @@ var taskKillBrowser = () => new Promise((resolve) => {
144
211
  });
145
212
  var taskKillFlowser = () => new Promise((resolve) => {
146
213
  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) => {
214
+ (0, import_node_child_process2.exec)(cmd, { windowsHide: true }, (err) => {
148
215
  if (err) {
149
216
  }
150
217
  resolve();
151
218
  });
152
219
  });
153
220
  var getHomedir = () => {
154
- return (typeof os.homedir == "function" ? os.homedir() : process.env[process.platform == "win32" ? "USERPROFILE" : "HOME"]) || "~";
221
+ return (typeof os2.homedir == "function" ? os2.homedir() : process.env[process.platform == "win32" ? "USERPROFILE" : "HOME"]) || "~";
155
222
  };
156
- var getPidFileDir = () => {
157
- const dir = path.join(getHomedir(), ".adspowerCli");
158
- if (!fs.existsSync(dir)) {
223
+ var getPidFileDir = (create = true) => {
224
+ const dir = path2.join(getHomedir(), ".adspowerCli");
225
+ if (create && !fs2.existsSync(dir)) {
159
226
  (0, import_fs_extra2.ensureDirSync)(dir);
160
227
  }
161
228
  return dir;
@@ -165,26 +232,27 @@ var pidFileName = () => {
165
232
  return md5;
166
233
  };
167
234
  var writePidFile = (config2) => {
168
- const filePath = path.join(getPidFileDir(), pidFileName());
169
- (0, import_fs_extra2.outputJsonSync)(filePath, 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);
170
238
  };
171
239
  var readPidFile = () => {
172
- const filePath = path.join(getPidFileDir(), pidFileName());
173
- if (fs.existsSync(filePath)) {
240
+ const filePath = path2.join(getPidFileDir(false), pidFileName());
241
+ if (fs2.existsSync(filePath)) {
174
242
  return (0, import_fs_extra2.readJsonSync)(filePath);
175
243
  }
176
244
  return {};
177
245
  };
178
246
  var removePidFile = () => {
179
- const filePath = path.join(getPidFileDir(), pidFileName());
180
- if (fs.existsSync(filePath)) {
247
+ const filePath = path2.join(getPidFileDir(), pidFileName());
248
+ if (fs2.existsSync(filePath)) {
181
249
  (0, import_fs_extra2.removeSync)(filePath);
182
250
  }
183
251
  };
184
252
  var isRunning = (pid) => {
185
253
  return new Promise((resolve) => {
186
254
  if (pid) {
187
- (0, import_node_child_process.exec)(
255
+ (0, import_node_child_process2.exec)(
188
256
  util.format(process.platform === "win32" ? 'tasklist /fi "PID eq %s" | findstr /i "node.exe"' : 'ps -f -p %s | grep "node"', pid),
189
257
  { windowsHide: true },
190
258
  function(err, stdout, stderr) {
@@ -197,8 +265,8 @@ var isRunning = (pid) => {
197
265
  });
198
266
  };
199
267
  var ensureBrowserPath = () => {
200
- const dir = path.join(__dirname, "../cwd/source", ".browser");
201
- if (!fs.existsSync(dir)) {
268
+ const dir = path2.join(__dirname, "../cwd/source", ".browser");
269
+ if (!fs2.existsSync(dir)) {
202
270
  (0, import_fs_extra2.ensureDirSync)(dir);
203
271
  }
204
272
  };
@@ -266,8 +334,8 @@ var createLoading = (text) => {
266
334
  };
267
335
  };
268
336
  var initSqlite3 = () => {
269
- const sqliteFile = path.join(__dirname, "../cwd/lib", "node_sqlite3.node");
270
- if (fs.existsSync(sqliteFile)) {
337
+ const sqliteFile = path2.join(__dirname, "../cwd/lib", "node_sqlite3.node");
338
+ if (fs2.existsSync(sqliteFile)) {
271
339
  return;
272
340
  }
273
341
  const isMac = process.platform === "darwin";
@@ -279,13 +347,13 @@ var initSqlite3 = () => {
279
347
  const winFolder = is32 ? "ia32" : "x64";
280
348
  const linuxFolder = isLinux && isX64 && "linux";
281
349
  const sqliteFolder = isMac ? macFolder : isLinux ? linuxFolder : winFolder;
282
- const dir = path.join(__dirname, `../sqlite/${sqliteFolder}`);
283
- if (!fs.existsSync(dir)) {
350
+ const dir = path2.join(__dirname, `../sqlite/${sqliteFolder}`);
351
+ if (!fs2.existsSync(dir)) {
284
352
  throw new Error(`SQLite folder not found: ${dir}`);
285
353
  } 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"));
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"));
289
357
  logSuccess(`[i] SQLite file initialized successfully!`);
290
358
  }
291
359
  };
@@ -318,7 +386,7 @@ async function promptYesNo(question) {
318
386
  var import_axios = __toESM(require("axios"));
319
387
  var import_fs = __toESM(require("fs"));
320
388
  var import_path = __toESM(require("path"));
321
- var import_node_child_process2 = require("child_process");
389
+ var import_node_child_process3 = require("child_process");
322
390
  var NPM_PACKAGE_NAME = "adspower-browser";
323
391
  var NPM_REGISTRY_URL = `https://registry.npmjs.org/${NPM_PACKAGE_NAME}/latest`;
324
392
  var checkUpdates = async (apiKey, baseUrl) => {
@@ -395,7 +463,7 @@ var checkUpdateNpmPackage = async () => {
395
463
  var updateNpmPackage = async () => {
396
464
  const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
397
465
  await new Promise((resolve, reject) => {
398
- const child = (0, import_node_child_process2.spawn)(npmCommand, ["install", "-g", `${NPM_PACKAGE_NAME}@latest`], {
466
+ const child = (0, import_node_child_process3.spawn)(npmCommand, ["install", "-g", `${NPM_PACKAGE_NAME}@latest`], {
399
467
  stdio: "inherit",
400
468
  windowsHide: true
401
469
  });
@@ -1388,7 +1456,7 @@ function buildCliCommandDescription(commandName, legacyFallback) {
1388
1456
  }
1389
1457
 
1390
1458
  // ../core/src/handlers/browser.ts
1391
- var import_node_os = __toESM(require("os"));
1459
+ var import_node_os2 = __toESM(require("os"));
1392
1460
 
1393
1461
  // ../core/src/utils/requestBuilder.ts
1394
1462
  function toContractValue(value) {
@@ -1531,7 +1599,7 @@ var browserHandlers = {
1531
1599
  const { params: resolvedParams, didAutoSetHeadless } = resolveOpenBrowserHeadless(
1532
1600
  params,
1533
1601
  process.env,
1534
- import_node_os.default.platform()
1602
+ import_node_os2.default.platform()
1535
1603
  );
1536
1604
  const requestBody = buildRequestBodyFor("open-browser", resolvedParams);
1537
1605
  const response = await getApiClient().post(`${getLocalApiBase()}${API_ENDPOINTS.START_BROWSER}`, requestBody);
@@ -2844,11 +2912,11 @@ var import_axios3 = __toESM(require("axios"));
2844
2912
 
2845
2913
  // ../core/src/rpa/local/fileTransport.ts
2846
2914
  var import_promises = require("fs/promises");
2847
- var import_node_path = require("path");
2915
+ var import_node_path2 = require("path");
2848
2916
  var import_node_zlib = require("zlib");
2849
2917
  var MAX_FLOW_BYTES = 32 * 1024 * 1024;
2850
2918
  async function readDebugProcess(filePath) {
2851
- if (!(0, import_node_path.isAbsolute)(filePath)) throw new Error("process_file must be an absolute local path");
2919
+ if (!(0, import_node_path2.isAbsolute)(filePath)) throw new Error("process_file must be an absolute local path");
2852
2920
  const file = await (0, import_promises.open)(filePath, "r");
2853
2921
  let bytes;
2854
2922
  try {
@@ -2871,7 +2939,7 @@ async function readDebugProcess(filePath) {
2871
2939
  }
2872
2940
  async function writeRpaLogResult(data, outputFile) {
2873
2941
  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");
2942
+ if (!(0, import_node_path2.isAbsolute)(outputFile)) throw new Error("output_file must be an absolute local path");
2875
2943
  await (0, import_promises.writeFile)(outputFile, JSON.stringify(data), { flag: "wx", mode: 384 });
2876
2944
  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
2945
  return JSON.stringify({ output_file: outputFile, ...result }, null, 2);
@@ -3794,7 +3862,7 @@ var flowQueryShape = {
3794
3862
  ...pagination,
3795
3863
  access_link: import_zod7.z.union([import_zod7.z.literal(0), import_zod7.z.literal(1)]).default(0).describe("Defaults to 0; set to 1 only when a process file download link is needed."),
3796
3864
  origin: import_zod7.z.literal("0").default("0").describe("Process origin; fixed to string 0."),
3797
- block_expired_paid_template_process: import_zod7.z.literal(1).default(1).describe("Expired paid-template filtering option; fixed to 1.")
3865
+ block_expired_paid_template_process: import_zod7.z.union([import_zod7.z.literal(0), import_zod7.z.literal(1)]).default(0).describe("Expired paid-template processes: 0 includes them (default); 1 excludes them.")
3798
3866
  };
3799
3867
  var rpaRemoteSchemas = {
3800
3868
  updateProcessSchema: import_zod7.z.object({
@@ -4024,14 +4092,14 @@ var rpaRemoteTools = [
4024
4092
  },
4025
4093
  {
4026
4094
  name: "get-process-list",
4027
- description: "Get the list of RPA processes with optional filters and pagination.",
4095
+ description: "List RPA processes with optional filters and pagination. Includes expired paid-template processes by default. Disclose any exclusion of expired processes when summarizing results.",
4028
4096
  schema: rpaRemoteSchemas.getProcessListSchema,
4029
4097
  handler: rpaRemoteHandlers.getProcessList,
4030
4098
  readOnly: true
4031
4099
  },
4032
4100
  {
4033
4101
  name: "get-process-list-count",
4034
- description: "Get the number of RPA processes matching the filters.",
4102
+ description: "Count RPA processes matching the filters. Includes expired paid-template processes by default. If the list excludes them, use the same other filters with this option set to 0 and 1 to report the total and the number excluded.",
4035
4103
  schema: rpaRemoteSchemas.getProcessListCountSchema,
4036
4104
  handler: rpaRemoteHandlers.getProcessListCount,
4037
4105
  readOnly: true
@@ -4725,8 +4793,8 @@ var getRuntimeExecArgv = () => {
4725
4793
  if (process.platform !== "win32") {
4726
4794
  return [];
4727
4795
  }
4728
- const preload = path4.join(__dirname, "core/winHideChildProcess.js");
4729
- if (!fs3.existsSync(preload)) {
4796
+ const preload = path5.join(__dirname, "core/winHideChildProcess.js");
4797
+ if (!fs4.existsSync(preload)) {
4730
4798
  return [];
4731
4799
  }
4732
4800
  return ["--require", preload];
@@ -4765,7 +4833,7 @@ var startChild = (type) => {
4765
4833
  Object.entries(getEnv()).map(([key, value]) => [key, value == null ? value : String(value)])
4766
4834
  );
4767
4835
  try {
4768
- const mainJs = path4.join(__dirname, "../cwd/lib", "main.min.js");
4836
+ const mainJs = path5.join(__dirname, "../cwd/lib", "main.min.js");
4769
4837
  const forkOptions = {
4770
4838
  env,
4771
4839
  detached: true,
@@ -4774,7 +4842,7 @@ var startChild = (type) => {
4774
4842
  stdio: ["ignore", "ignore", "ignore", "ipc"],
4775
4843
  execArgv: getRuntimeExecArgv()
4776
4844
  };
4777
- child = (0, import_node_child_process3.fork)(mainJs, [], forkOptions);
4845
+ child = (0, import_node_child_process4.fork)(mainJs, [], forkOptions);
4778
4846
  ensureBrowserPath();
4779
4847
  store.setStoreValue("status", "starting");
4780
4848
  logSuccess(`[i] Adspower program is starting...`);
@@ -4839,7 +4907,7 @@ var startChild = (type) => {
4839
4907
  if (serverMsg[1]) {
4840
4908
  logError(`ERROR - ${serverMsg[1]}`);
4841
4909
  }
4842
- process.exit(0);
4910
+ process.exit(1);
4843
4911
  }
4844
4912
  if (text === "start") {
4845
4913
  clearTimeout(timer);
@@ -4877,7 +4945,7 @@ var startChild = (type) => {
4877
4945
  store.setStoreValue("status", "stop");
4878
4946
  store.clear();
4879
4947
  removePidFile();
4880
- process.exit(0);
4948
+ process.exit(1);
4881
4949
  });
4882
4950
  child.on("exit", async (code, signal) => {
4883
4951
  await browsersKill();
@@ -4914,6 +4982,7 @@ var stopChild = async () => {
4914
4982
  removePidFile();
4915
4983
  } catch (error2) {
4916
4984
  logError(`[!] Stop child fail: ${error2 instanceof Error ? error2.message : JSON.stringify(error2)}`);
4985
+ process.exitCode = 1;
4917
4986
  if (isRun) {
4918
4987
  logWarning(`[!] Please manually close the browser process: ${processInstance.pid}`);
4919
4988
  }
@@ -4922,6 +4991,7 @@ var stopChild = async () => {
4922
4991
  }
4923
4992
  logSuccess("[i] Adspower program is stopped");
4924
4993
  } else {
4994
+ removePidFile();
4925
4995
  logInfo("[i] No running adspower program");
4926
4996
  }
4927
4997
  };
@@ -4952,14 +5022,16 @@ var getChildStatus = async () => {
4952
5022
  if (!isRun) {
4953
5023
  removePidFile();
4954
5024
  logInfo("[i] Adspower program is not running");
4955
- return;
5025
+ return false;
4956
5026
  }
4957
5027
  const status = processInstance.status;
4958
5028
  if (status === "starting") {
4959
5029
  logSuccess("[i] Adspower program is starting...");
5030
+ return true;
4960
5031
  } else if (status === "doing" && processInstance.apiPort) {
4961
5032
  logSuccess("[i] Adspower program is running at:");
4962
5033
  logSuccess(` - http://local.adspower.net:${processInstance.apiPort}`);
5034
+ return true;
4963
5035
  } else if (status === "stop") {
4964
5036
  logInfo("[i] Adspower program is stopped");
4965
5037
  } else {
@@ -4968,6 +5040,7 @@ var getChildStatus = async () => {
4968
5040
  } else {
4969
5041
  logInfo("[i] Adspower program is not running");
4970
5042
  }
5043
+ return false;
4971
5044
  };
4972
5045
 
4973
5046
  // src/startConfig.ts
@@ -5041,6 +5114,12 @@ function wrapShellScriptOutput(shell) {
5041
5114
  // src/index.ts
5042
5115
  var program = new import_commander2.Command();
5043
5116
  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
+ });
5044
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) => {
5045
5124
  const resolvedApiKey = resolveStartApiKey(options.apiKey, process.env);
5046
5125
  if (!resolvedApiKey.ok) {
@@ -5057,13 +5136,14 @@ program.command("start").description("Start the adspower runtime").option("-k, -
5057
5136
  await startChild();
5058
5137
  });
5059
5138
  program.command("stop").description("Stop the adspower runtime").action(async () => {
5139
+ await cancelLogin();
5060
5140
  await stopChild();
5061
5141
  });
5062
5142
  program.command("restart").description("Restart the adspower runtime").action(async () => {
5063
5143
  await restartChild();
5064
5144
  });
5065
5145
  program.command("status").description("Get the status of the adspower runtime").action(async () => {
5066
- getChildStatus();
5146
+ await getChildStatus();
5067
5147
  });
5068
5148
  for (const cmd of Object.keys(STATELESS_HANDLERS)) {
5069
5149
  const fnc = STATELESS_HANDLERS[cmd].fn;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "adspower-browser",
3
- "version": "2.1.6-beta.0",
3
+ "version": "2.1.7-beta.0",
4
4
  "main": "cli/index.js",
5
5
  "type": "commonjs",
6
6
  "bin": {