adspower-browser 2.1.7-beta.0 → 2.1.7-beta.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/README.MD CHANGED
@@ -230,39 +230,65 @@ 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
+ API Keys are stored in macOS login Keychain or Windows Credential Manager, scoped to the
255
+ current OS user under `com.adspower.cli.client.v1`. The account identifier is SHA-256(userId).
256
+ `~/.adspowerCli/<md5(userId)>` contains only version-2 connection metadata (userId, ports,
257
+ credentialAccount), never the API Key. `client-user.json` selects the current user.
258
+
259
+ The native helper uses Koffi prebuilt binaries (macOS arm64/x64; Windows arm64/x64/ia32).
260
+ No compiler, PowerShell, shell command or key in process arguments is required. Keep the
261
+ `koffi` runtime dependency and `cli/credentialWorker.js` when packaging. The workspace
262
+ explicitly disables its install script because supported targets already ship prebuilds.
263
+ Native-library load failure is an error, not an invitation to use plaintext storage.
264
+
265
+ All credential operations are noninteractive and limited to five seconds per helper call.
266
+ macOS explicitly disables Keychain UI and restores the previous policy after each operation.
267
+ Windows uses generic CredReadW/CredWriteW/CredDeleteW credentials, without CredUI calls.
268
+ Run WorkBuddy and the CLI under the same OS account, with access to that account's credential
269
+ store. A locked Keychain, changed host trust, missing credential or unavailable store produces
270
+ an explicit error. This cannot guarantee successful access under every OS security policy;
271
+ it guarantees no interactive fallback. Windows generic credentials are limited to 2560 bytes.
272
+
273
+ `logstatus` reads the system credential and metadata, exits nonzero with an error if credential
274
+ access fails, and does not probe client liveness or validate the key remotely. Business commands
275
+ also fail before calling APIs if the credential cannot be read. `logout` first deletes the current
276
+ user's system credential, then the metadata/index. Failed deletion retains metadata for retry;
277
+ it does not stop the desktop client or revoke the server API Key.
278
+
279
+ Legacy files containing apiKey are rejected, not used as fallback or silently migrated. Run
280
+ `ads login` again to replace that user's legacy file only after a successful vault write/read-back,
281
+ or `ads logout` to remove it. Files of other previously authorized users are not automatically
282
+ removed; reauthorize or remove those accounts individually. Ordinary start/stop runtime mode
283
+ is outside this client-session storage change.
284
+
285
+ Verification: `node tests/login-process-smoke.cjs` (from this package after build) uses a unique
286
+ fake account and cleans up its OS credential. Run it under the same Node executable/account
287
+ used by WorkBuddy on each supported OS. Tests cannot override OS policies or unlock a store.
288
+
289
+ Native API references: [Apple Keychain UI control](https://developer.apple.com/documentation/security/seckeychainsetuserinteractionallowed(_:)),
290
+ [Windows CredReadW](https://learn.microsoft.com/en-us/windows/win32/api/wincred/nf-wincred-credreadw).
291
+
292
+ Deploy the matching frontend to both the authorization site and the desktop renderer site.
293
+ The native client must forward the complete protocol URL through renderer-scheme.
294
+ 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_path4 = __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,123 @@ 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_path3 = __toESM(require("path"));
42
+ var import_node_crypto = require("crypto");
43
+
44
+ // src/credentialVault.ts
45
+ var import_node_child_process2 = require("child_process");
46
+ var import_node_path2 = __toESM(require("path"));
47
+ var CredentialStoreError = class extends Error {
48
+ constructor(code) {
49
+ super(`System credential store unavailable (${code}). Use the same OS account and an accessible credential store, then run ads login again. No plaintext fallback is permitted.`);
50
+ this.name = "CredentialStoreError";
51
+ }
52
+ };
53
+ function invoke(operation, account, secret) {
54
+ if (!["darwin", "win32"].includes(process.platform)) throw new CredentialStoreError("UNSUPPORTED_PLATFORM");
55
+ if (!/^[a-f0-9]{64}$/.test(account)) throw new CredentialStoreError("INVALID_ACCOUNT");
56
+ let output;
57
+ try {
58
+ output = (0, import_node_child_process2.execFileSync)(process.execPath, [import_node_path2.default.join(__dirname, "credentialWorker.js")], {
59
+ input: JSON.stringify({ operation, account, secret }),
60
+ windowsHide: true,
61
+ timeout: 5e3,
62
+ killSignal: "SIGKILL",
63
+ maxBuffer: 32768,
64
+ stdio: ["pipe", "pipe", "pipe"]
65
+ });
66
+ } catch {
67
+ throw new CredentialStoreError("HELPER_FAILED_OR_TIMED_OUT");
68
+ }
69
+ try {
70
+ const result = JSON.parse(output.toString("utf8"));
71
+ if (result.ok !== true) {
72
+ const code = typeof result.code === "string" && /^[A-Z0-9_-]{1,64}$/.test(result.code) ? result.code : "NATIVE_FAILURE";
73
+ throw new CredentialStoreError(code);
74
+ }
75
+ if (operation === "read" && (typeof result.secret !== "string" || !result.secret.trim() || result.secret.length > 4096 || /[\r\n]/.test(result.secret))) throw new CredentialStoreError("INVALID_SECRET");
76
+ return result.secret;
77
+ } catch (error) {
78
+ if (error instanceof CredentialStoreError) throw error;
79
+ throw new CredentialStoreError("INVALID_HELPER_RESPONSE");
80
+ } finally {
81
+ output.fill(0);
82
+ }
83
+ }
84
+ var credentialVault = {
85
+ write: (account, secret) => {
86
+ invoke("write", account, secret);
87
+ },
88
+ read: (account) => invoke("read", account),
89
+ remove: (account) => {
90
+ invoke("delete", account);
91
+ }
92
+ };
93
+
94
+ // src/tools/paths.ts
95
+ var os2 = __toESM(require("os"));
96
+ var path3 = __toESM(require("path"));
97
+ var fs2 = __toESM(require("fs"));
98
+ var import_fs_extra2 = require("fs-extra2");
99
+ var getHomedir = () => {
100
+ return (typeof os2.homedir == "function" ? os2.homedir() : process.env[process.platform == "win32" ? "USERPROFILE" : "HOME"]) || "~";
101
+ };
102
+ var getPidFileDir = (create = true) => {
103
+ const dir = path3.join(getHomedir(), ".adspowerCli");
104
+ if (create && !fs2.existsSync(dir)) {
105
+ (0, import_fs_extra2.ensureDirSync)(dir);
106
+ }
107
+ return dir;
108
+ };
109
+
110
+ // src/clientSession.ts
111
+ var userFile = (userId) => import_node_path3.default.join(getPidFileDir(false), (0, import_node_crypto.createHash)("md5").update(userId).digest("hex"));
112
+ var indexFile = () => import_node_path3.default.join(getPidFileDir(false), "client-user.json");
113
+ var credentialAccount = (userId) => (0, import_node_crypto.createHash)("sha256").update(userId).digest("hex");
114
+ var validPort = (value) => Number.isInteger(value) && Number(value) > 0 && Number(value) <= 65535;
115
+ function isClientSession(value) {
116
+ if (!value || typeof value !== "object") return false;
117
+ const session = value;
118
+ 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);
119
+ }
120
+ function writePrivateJson(file, value) {
121
+ const temporary = `${file}.${(0, import_node_crypto.randomUUID)()}.tmp`;
122
+ try {
123
+ fs3.writeFileSync(temporary, JSON.stringify(value), { mode: 384, flag: "wx" });
124
+ fs3.renameSync(temporary, file);
125
+ } finally {
126
+ fs3.rmSync(temporary, { force: true });
127
+ }
128
+ }
129
+ function saveClientSession(session) {
130
+ if (!isClientSession(session)) throw new Error("Incomplete client connection");
131
+ const { apiKey, userId, apiPort, rpaPort } = session;
132
+ const account = credentialAccount(userId);
133
+ credentialVault.write(account, apiKey);
134
+ if (credentialVault.read(account) !== apiKey) throw new Error("System credential verification failed. No plaintext credentials were saved.");
135
+ getPidFileDir();
136
+ writePrivateJson(userFile(userId), { version: 2, userId, apiPort, rpaPort, credentialAccount: account });
137
+ writePrivateJson(indexFile(), { userId });
138
+ }
139
+
42
140
  // src/loginReceiver.ts
43
141
  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");
142
+ var import_node_crypto2 = require("crypto");
143
+ async function createLoginReceiver(origin, onKey, onAccepted) {
144
+ const allowedOrigins = /* @__PURE__ */ new Set([origin, "https://app.adspower.com", "https://app.adspower.net"]);
145
+ const state = (0, import_node_crypto2.randomBytes)(32).toString("base64url");
47
146
  let consumed = false;
48
147
  const server = (0, import_node_http.createServer)(async (req, res) => {
49
148
  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") {
149
+ if (!address2 || typeof address2 === "string" || req.headers.host !== `127.0.0.1:${address2.port}` || !allowedOrigins.has(req.headers.origin || "") || req.url !== "/callback") {
51
150
  res.writeHead(403).end();
52
151
  return;
53
152
  }
54
- res.setHeader("Access-Control-Allow-Origin", origin);
153
+ res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
55
154
  res.setHeader("Vary", "Origin");
56
155
  res.setHeader("Cache-Control", "no-store");
57
156
  if (req.method === "OPTIONS") {
@@ -67,16 +166,17 @@ async function createLoginReceiver(origin, onKey) {
67
166
  }
68
167
  try {
69
168
  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) {
169
+ 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
170
  res.writeHead(403).end();
72
171
  return;
73
172
  }
74
- if (typeof body.apiKey !== "string" || !body.apiKey.trim() || body.apiKey.length > 4096 || /[\r\n]/.test(body.apiKey)) {
173
+ if (!isClientSession(body)) {
75
174
  res.writeHead(400).end();
76
175
  return;
77
176
  }
78
177
  consumed = true;
79
- await onKey(body.apiKey);
178
+ await onKey(body);
179
+ if (onAccepted) res.once("finish", onAccepted);
80
180
  res.setHeader("Content-Type", "application/json");
81
181
  res.end(JSON.stringify({ accepted: true }));
82
182
  } catch {
@@ -110,12 +210,13 @@ async function readBody(req) {
110
210
 
111
211
  // src/authWorker.ts
112
212
  async function main() {
213
+ const origin = new URL(process.argv[2] || "https://app.adspower.com").origin;
113
214
  const lock = (0, import_node_net2.createServer)((socket) => socket.destroy());
114
215
  await new Promise((resolve, reject) => {
115
216
  lock.once("error", reject);
116
217
  lock.listen({ host: "127.0.0.1", port: 59753, exclusive: true }, resolve);
117
218
  });
118
- const id = (0, import_node_crypto2.randomUUID)();
219
+ const id = (0, import_node_crypto3.randomUUID)();
119
220
  const ownsSession = async () => {
120
221
  try {
121
222
  return JSON.parse(await import_node_fs2.promises.readFile(pendingPath, "utf8")).id === id;
@@ -124,8 +225,6 @@ async function main() {
124
225
  }
125
226
  };
126
227
  let finishing = false;
127
- let cancelling = false;
128
- let starter;
129
228
  let receiver;
130
229
  let expiry;
131
230
  let cancellation;
@@ -141,44 +240,21 @@ async function main() {
141
240
  lock.close();
142
241
  }
143
242
  };
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
243
  try {
156
- await import_node_fs2.promises.mkdir(import_node_path2.default.dirname(pendingPath), { recursive: true, mode: 448 });
244
+ await import_node_fs2.promises.mkdir(import_node_path4.default.dirname(pendingPath), { recursive: true, mode: 448 });
157
245
  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
- });
246
+ receiver = await createLoginReceiver(origin, async (session) => {
247
+ if (finishing || !await ownsSession()) throw new Error("Login cancelled");
248
+ saveClientSession(session);
249
+ }, () => {
250
+ void finish();
175
251
  });
176
252
  expiry = setTimeout(() => {
177
253
  void finish();
178
254
  }, 3e5);
179
255
  cancellation = setInterval(() => {
180
256
  void ownsSession().then((owns) => {
181
- if (!owns) cancel();
257
+ if (!owns) void finish();
182
258
  });
183
259
  }, 500);
184
260
  process.send?.({ url: receiver.url });
@@ -188,6 +264,6 @@ async function main() {
188
264
  }
189
265
  }
190
266
  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." });
267
+ process.send?.({ error: "Unable to start login. Check port 59753, or run ads logout to cancel a pending login." });
192
268
  process.exitCode = 1;
193
269
  });
@@ -0,0 +1,179 @@
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/credentialWorker.ts
26
+ var fs = __toESM(require("fs"));
27
+
28
+ // src/nativeCredentials.ts
29
+ var import_koffi = __toESM(require("koffi"));
30
+ var SERVICE = "com.adspower.cli.client.v1";
31
+ var NativeCredentialError = class extends Error {
32
+ };
33
+ var fail = (platform, code) => {
34
+ throw new NativeCredentialError(`${platform}_${code}`);
35
+ };
36
+ function macCredentials(request) {
37
+ const security = import_koffi.default.load("/System/Library/Frameworks/Security.framework/Security");
38
+ const core = import_koffi.default.load("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation");
39
+ const getInteraction = security.func("int32_t SecKeychainGetUserInteractionAllowed(_Out_ uint8_t *allowed)");
40
+ const setInteraction = security.func("int32_t SecKeychainSetUserInteractionAllowed(uint8_t allowed)");
41
+ const find = security.func("int32_t SecKeychainFindGenericPassword(void *keychain, uint32_t serviceLength, const char *service, uint32_t accountLength, const char *account, _Out_ uint32_t *length, _Out_ void **data, _Out_ void **item)");
42
+ const add = security.func("int32_t SecKeychainAddGenericPassword(void *keychain, uint32_t serviceLength, const char *service, uint32_t accountLength, const char *account, uint32_t length, const void *data, _Out_ void **item)");
43
+ const modify = security.func("int32_t SecKeychainItemModifyAttributesAndData(void *item, void *attributes, uint32_t length, const void *data)");
44
+ const remove = security.func("int32_t SecKeychainItemDelete(void *item)");
45
+ const free = security.func("int32_t SecKeychainItemFreeContent(void *attributes, void *data)");
46
+ const release = core.func("void CFRelease(void *value)");
47
+ const previous = [0];
48
+ let status = getInteraction(previous);
49
+ if (status) fail("MACOS", status);
50
+ status = setInteraction(0);
51
+ if (status) fail("MACOS", status);
52
+ const data = [null], item = [null], length = [0];
53
+ try {
54
+ status = find(
55
+ null,
56
+ Buffer.byteLength(SERVICE),
57
+ SERVICE,
58
+ request.account.length,
59
+ request.account,
60
+ request.operation === "read" ? length : null,
61
+ request.operation === "read" ? data : null,
62
+ item
63
+ );
64
+ const missing = status === -25300;
65
+ if (status && !missing) fail("MACOS", status);
66
+ if (request.operation === "delete") {
67
+ if (missing) return;
68
+ status = remove(item[0]);
69
+ } else if (request.operation === "write") {
70
+ const bytes = Buffer.from(request.secret, "utf8");
71
+ try {
72
+ status = missing ? add(null, Buffer.byteLength(SERVICE), SERVICE, request.account.length, request.account, bytes.length, bytes, null) : modify(item[0], null, bytes.length, bytes);
73
+ } finally {
74
+ bytes.fill(0);
75
+ }
76
+ } else {
77
+ if (missing) fail("MACOS", status);
78
+ if (!data[0] || length[0] < 1 || length[0] > 16384) throw new NativeCredentialError("INVALID_SECRET");
79
+ const bytes = Buffer.from(import_koffi.default.decode(data[0], "uint8_t", length[0]));
80
+ try {
81
+ return bytes.toString("utf8");
82
+ } finally {
83
+ bytes.fill(0);
84
+ }
85
+ }
86
+ if (status) fail("MACOS", status);
87
+ } finally {
88
+ if (data[0]) free(null, data[0]);
89
+ if (item[0]) release(item[0]);
90
+ const restored = setInteraction(previous[0]);
91
+ if (restored) fail("MACOS", restored);
92
+ }
93
+ }
94
+ function windowsCredentials(request) {
95
+ const advapi = import_koffi.default.load("advapi32.dll");
96
+ const kernel = import_koffi.default.load("kernel32.dll");
97
+ const credential = import_koffi.default.struct("AdsCredentialW", {
98
+ Flags: "uint32_t",
99
+ Type: "uint32_t",
100
+ TargetName: "str16",
101
+ Comment: "str16",
102
+ LastWritten: import_koffi.default.struct({ low: "uint32_t", high: "uint32_t" }),
103
+ CredentialBlobSize: "uint32_t",
104
+ CredentialBlob: "void *",
105
+ Persist: "uint32_t",
106
+ AttributeCount: "uint32_t",
107
+ Attributes: "void *",
108
+ TargetAlias: "str16",
109
+ UserName: "str16"
110
+ });
111
+ const read = advapi.func("int __stdcall CredReadW(const char16_t *target, uint32_t type, uint32_t flags, _Out_ void **result)");
112
+ const write = advapi.func("int __stdcall CredWriteW(const AdsCredentialW *credential, uint32_t flags)");
113
+ const remove = advapi.func("int __stdcall CredDeleteW(const char16_t *target, uint32_t type, uint32_t flags)");
114
+ const free = advapi.func("void __stdcall CredFree(void *buffer)");
115
+ const lastError = kernel.func("uint32_t __stdcall GetLastError()");
116
+ const target = `${SERVICE}/${request.account}`;
117
+ if (request.operation === "delete") {
118
+ if (!remove(target, 1, 0)) {
119
+ const code = lastError();
120
+ if (code !== 1168) fail("WINDOWS", code);
121
+ }
122
+ return;
123
+ }
124
+ if (request.operation === "write") {
125
+ const bytes = Buffer.from(request.secret, "utf8");
126
+ try {
127
+ if (bytes.length > 2560) throw new NativeCredentialError("WINDOWS_SECRET_TOO_LARGE");
128
+ if (!write({
129
+ Flags: 0,
130
+ Type: 1,
131
+ TargetName: target,
132
+ Comment: "AdsPower CLI client connection",
133
+ LastWritten: { low: 0, high: 0 },
134
+ CredentialBlobSize: bytes.length,
135
+ CredentialBlob: bytes,
136
+ Persist: 2,
137
+ AttributeCount: 0,
138
+ Attributes: null,
139
+ TargetAlias: null,
140
+ UserName: request.account
141
+ }, 0)) fail("WINDOWS", lastError());
142
+ } finally {
143
+ bytes.fill(0);
144
+ }
145
+ return;
146
+ }
147
+ const result = [null];
148
+ if (!read(target, 1, 0, result)) fail("WINDOWS", lastError());
149
+ try {
150
+ const value = import_koffi.default.decode(result[0], credential);
151
+ if (!value.CredentialBlob || value.CredentialBlobSize < 1 || value.CredentialBlobSize > 2560) throw new NativeCredentialError("INVALID_SECRET");
152
+ const bytes = Buffer.from(import_koffi.default.decode(value.CredentialBlob, "uint8_t", value.CredentialBlobSize));
153
+ try {
154
+ return bytes.toString("utf8");
155
+ } finally {
156
+ bytes.fill(0);
157
+ }
158
+ } finally {
159
+ free(result[0]);
160
+ }
161
+ }
162
+ function nativeCredentials(request) {
163
+ if (process.platform === "darwin") return macCredentials(request);
164
+ if (process.platform === "win32") return windowsCredentials(request);
165
+ throw new NativeCredentialError("UNSUPPORTED_PLATFORM");
166
+ }
167
+
168
+ // src/credentialWorker.ts
169
+ try {
170
+ const input = fs.readFileSync(0, "utf8");
171
+ if (Buffer.byteLength(input) > 32768) throw new Error("Invalid request");
172
+ const request = JSON.parse(input);
173
+ if (!["read", "write", "delete"].includes(request.operation) || !/^[a-f0-9]{64}$/.test(request.account) || request.operation === "write" && (typeof request.secret !== "string" || !request.secret.trim() || request.secret.length > 4096 || /[\r\n]/.test(request.secret))) throw new Error("Invalid request");
174
+ const secret = nativeCredentials(request);
175
+ process.stdout.write(JSON.stringify({ ok: true, ...request.operation === "read" ? { secret } : {} }));
176
+ } catch (error) {
177
+ const code = error instanceof NativeCredentialError ? error.message : "NATIVE_FAILURE";
178
+ process.stdout.write(JSON.stringify({ ok: false, code }));
179
+ }