@gruu6y/page-clean-login 0.2.2 → 0.2.3

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.en.md CHANGED
@@ -232,6 +232,7 @@ Accounts and exits are fully drivable from the command line, with no page open:
232
232
 
233
233
  ```sh
234
234
  bun bin/clean-login.mjs proxies add home-01 http 127.0.0.1 7102 # store an exit
235
+ bun bin/clean-login.mjs proxies update <proxyId> --host 10.0.0.2 --exit-port 1080 # change an exit (a connection change clears probe results)
235
236
  bun bin/clean-login.mjs accounts import plan # preview magpie's accounts
236
237
  bun bin/clean-login.mjs accounts import run --only <provider>#<recordId>
237
238
  bun bin/clean-login.mjs accounts exit <provider> <key> --mode custom --proxy <proxyId>
package/README.md CHANGED
@@ -233,6 +233,7 @@ bun bin/clean-login.mjs assets # 只看已登记的资产(邮箱、手机
233
233
 
234
234
  ```sh
235
235
  bun bin/clean-login.mjs proxies add 家宽01 http 127.0.0.1 7102 # 存一条出口
236
+ bun bin/clean-login.mjs proxies update <proxyId> --host 10.0.0.2 --exit-port 1080 # 改一条出口(改连接会清空探测结果)
236
237
  bun bin/clean-login.mjs accounts import plan # 预览 magpie 已有的账号
237
238
  bun bin/clean-login.mjs accounts import run --only <provider>#<recordId>
238
239
  bun bin/clean-login.mjs accounts exit <provider> <key> --mode custom --proxy <proxyId>
package/lib/agent-cli.mjs CHANGED
@@ -98,6 +98,9 @@ const VALUE_FLAGS = new Set([
98
98
  "text",
99
99
  "input",
100
100
  "only",
101
+ "name",
102
+ "host",
103
+ "exit-port",
101
104
  ]);
102
105
 
103
106
  export function parseArgs(argv) {
@@ -281,6 +284,8 @@ export function usage() {
281
284
  " providers Merged provider cards, compact.",
282
285
  " proxies Stored proxies, compact (no credentials).",
283
286
  " proxies add <name> <type> <host> <port> Store an exit (type http|https|socks5).",
287
+ " proxies update <id> [--name N] [--type T] [--host H] [--exit-port P] [--user U] [--pass P]",
288
+ " Change an exit; a connection change clears its per-provider latency and score.",
284
289
  " proxies delete <proxyId> Remove a stored exit.",
285
290
  " proxies targets The endpoints a proxy probe can be aimed at.",
286
291
  " accounts Known accounts and their signed-in state.",
@@ -329,7 +334,8 @@ export function usage() {
329
334
  " --only KEY Pick one account out of an import plan (repeatable).",
330
335
  " --mode M Exit mode for accounts exit: inherit, direct or custom.",
331
336
  " --note TEXT Note for assets add/update, or the report note.",
332
- " --user / --pass Optional credentials for proxies add.",
337
+ " --user / --pass Optional credentials for proxies add and update.",
338
+ " --exit-port N Exit port for proxies update (--port is the service port).",
333
339
  " --single Replace the single stored account for this provider.",
334
340
  "",
335
341
  ].join("\n");
@@ -403,6 +409,30 @@ export async function runCli(argv, {
403
409
  noSurplus(positional, 3);
404
410
  return emit(await del(`/api/proxies/${encodeURIComponent(required(positional[2] ?? options.id, "<proxyId>"))}`), options, write);
405
411
  }
412
+ if (action === "update") {
413
+ // Only fields the caller spelled out are sent, so a later read cannot
414
+ // mistake an omitted flag for a request to clear it. The exit's port
415
+ // goes through --exit-port because --port already means the service
416
+ // port (the same ambiguity the positional port on `proxies add`
417
+ // avoids). The id is required first so a bare `proxies update` reports
418
+ // the missing argument, not "nothing to update".
419
+ const id = required(positional[2] ?? options.id, "<proxyId>");
420
+ const body = {};
421
+ if (Object.prototype.hasOwnProperty.call(options, "name")) body.name = String(options.name);
422
+ if (Object.prototype.hasOwnProperty.call(options, "type")) body.type = String(options.type);
423
+ if (Object.prototype.hasOwnProperty.call(options, "host")) body.host = String(options.host);
424
+ if (Object.prototype.hasOwnProperty.call(options, "exit-port")) body.port = String(options["exit-port"]);
425
+ if (Object.prototype.hasOwnProperty.call(options, "user")) body.username = String(options.user);
426
+ if (Object.prototype.hasOwnProperty.call(options, "pass")) body.password = String(options.pass);
427
+ if (!Object.keys(body).length) {
428
+ throw new CliError(
429
+ "Nothing to update; pass --name, --type, --host, --exit-port, --user or --pass.",
430
+ { code: "bad_command" },
431
+ );
432
+ }
433
+ noSurplus(positional, 3);
434
+ return emit(await patch(`/api/proxies/${encodeURIComponent(id)}`, body), options, write);
435
+ }
406
436
  if (action === "targets") {
407
437
  noSurplus(positional, 2);
408
438
  return emit(await get("/api/proxy-targets"), options, write);
@@ -811,6 +811,29 @@ export function createEnvironmentManager({
811
811
  : null,
812
812
  modelVerified: result?.modelVerified === true,
813
813
  };
814
+ // The installer's byte total was measured before this record existed, so
815
+ // the stored count must add the record's own size — otherwise the
816
+ // reported installedBytes sits ~350 B short of what is actually on disk.
817
+ // An older record being replaced was part of that measurement and has to
818
+ // come back out. The file grows with the digit count of `bytes`, so the
819
+ // corrected value is solved to a fixed point in a couple of render rounds.
820
+ if (payload.bytes !== null) {
821
+ let previousSize = 0;
822
+ try {
823
+ previousSize = (await stat(recordFile)).size;
824
+ } catch {
825
+ // No record on disk yet: nothing was counted twice.
826
+ }
827
+ const base = payload.bytes - previousSize;
828
+ let bytes = base;
829
+ for (let round = 0; round < 3; round += 1) {
830
+ payload.bytes = bytes;
831
+ const size = Buffer.byteLength(`${JSON.stringify(payload, null, 2)}\n`);
832
+ if (base + size === bytes) break;
833
+ bytes = base + size;
834
+ }
835
+ payload.bytes = bytes;
836
+ }
814
837
  await mkdir(dir, { recursive: true, mode: 0o700 });
815
838
  const temp = join(dir, `.${INSTALL_RECORD_NAME}.${process.pid}.${randomUUID()}.tmp`);
816
839
  await writeFile(temp, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
@@ -22,8 +22,8 @@
22
22
  import { fork } from "node:child_process";
23
23
  import { mkdir, stat } from "node:fs/promises";
24
24
  import { fileURLToPath } from "node:url";
25
- import { browserEnvironmentRoot, fingerprintModelDir } from "./browser-environment.mjs";
26
- import { loadCamoufoxSandboxed } from "./camoufox-loader.mjs";
25
+ import { BROWSER_DIR_ENV, browserEnvironmentRoot, fingerprintModelDir } from "./browser-environment.mjs";
26
+ import { camoufoxCacheEnv, loadCamoufoxSandboxed } from "./camoufox-loader.mjs";
27
27
 
28
28
  const HOST_PATH = fileURLToPath(new URL("./signin-browser-host.mjs", import.meta.url));
29
29
  const SCORE_HOST_PATH = fileURLToPath(new URL("./score-browser-host.mjs", import.meta.url));
@@ -55,6 +55,23 @@ export function navigationWarning(error) {
55
55
  };
56
56
  }
57
57
 
58
+ // The env the forked browser hosts run under. FPGEN_DATA_DIR is the name
59
+ // fpgen-js actually reads (only a fallback — the host also calls setModelDir
60
+ // from its launch input). camoufoxCacheEnv repeats the import-time cache
61
+ // redirect inside the child: without it the spawned process resolves the real
62
+ // user cache (LOCALAPPDATA / XDG_CACHE_HOME) and runtime writes like
63
+ // fontconfig's escape the sandbox. Because those overrides would also move
64
+ // browserEnvironmentRoot() inside the host, BROWSER_DIR_ENV is pinned so the
65
+ // host still finds the same sandbox root the parent computed.
66
+ function hostEnv(env, sandboxRoot, modelDir, platform = process.platform) {
67
+ return {
68
+ ...env,
69
+ ...camoufoxCacheEnv(sandboxRoot, platform),
70
+ [BROWSER_DIR_ENV]: sandboxRoot,
71
+ FPGEN_DATA_DIR: modelDir,
72
+ };
73
+ }
74
+
58
75
  export class SignInBrowserError extends Error {
59
76
  constructor(code, message, status = 500) {
60
77
  super(message);
@@ -347,10 +364,7 @@ export async function launchSignInBrowser({
347
364
  child = spawnHost(deps.hostPath ?? HOST_PATH, [], {
348
365
  stdio: ["pipe", "ignore", "pipe", "ipc"],
349
366
  windowsHide: false,
350
- // FPGEN_DATA_DIR is the name fpgen-js actually reads. It is only a
351
- // fallback: the host also receives the directory in its launch input and
352
- // calls setModelDir, because importing camoufox overwrites configuredDir.
353
- env: { ...env, FPGEN_DATA_DIR: resolvedModelDir },
367
+ env: hostEnv(env, browserEnvironmentRoot(env), resolvedModelDir),
354
368
  });
355
369
  } catch (error) {
356
370
  throw new SignInBrowserError(
@@ -503,6 +517,11 @@ export async function launchScoreBrowser({
503
517
  // start must not eat the page's own deadline.
504
518
  launchTimeoutMs = 60_000,
505
519
  env = process.env,
520
+ platform = process.platform,
521
+ // A display-less Linux box cannot show a window; the headed launch fails
522
+ // there outright. Headless is the default in that case only — wherever a
523
+ // display exists (and on win32/darwin always) the window still opens.
524
+ headless = platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY,
506
525
  deps = {},
507
526
  } = {}) {
508
527
  if (typeof url !== "string" || !url) {
@@ -527,6 +546,7 @@ export async function launchScoreBrowser({
527
546
  timeoutMs,
528
547
  // Never reuse timeoutMs: this is the first-navigation deadline.
529
548
  navTimeoutMs: navigationTimeoutMs,
549
+ headless: Boolean(headless),
530
550
  });
531
551
 
532
552
  const spawnHost = deps.fork ?? fork;
@@ -535,7 +555,7 @@ export async function launchScoreBrowser({
535
555
  child = spawnHost(deps.hostPath ?? SCORE_HOST_PATH, [], {
536
556
  stdio: ["pipe", "ignore", "pipe", "ipc"],
537
557
  windowsHide: false,
538
- env: { ...env, FPGEN_DATA_DIR: resolvedModelDir },
558
+ env: hostEnv(env, browserEnvironmentRoot(env), resolvedModelDir, platform),
539
559
  });
540
560
  } catch (error) {
541
561
  throw new ScoreBrowserError(
@@ -732,7 +752,7 @@ export async function launchIdentityCheckBrowser({
732
752
  child = spawnHost(deps.hostPath ?? IDENTITY_HOST_PATH, [], {
733
753
  stdio: ["pipe", "ignore", "pipe", "ipc"],
734
754
  windowsHide: false,
735
- env: { ...env, FPGEN_DATA_DIR: resolvedModelDir },
755
+ env: hostEnv(env, browserEnvironmentRoot(env), resolvedModelDir),
736
756
  });
737
757
  } catch (error) {
738
758
  throw new SignInBrowserError(
@@ -30,13 +30,24 @@ import { basename, dirname, join, resolve, sep } from "node:path";
30
30
  // (~/Library/Caches/camoufox) is made a symlink to <sandbox>/camoufox;
31
31
  // a pre-existing real directory is migrated into the sandbox first so its
32
32
  // bytes stay reachable through the link.
33
+ // The env-var half of the redirect, with no side effects. Forked browser
34
+ // hosts need exactly these overrides in their process env so a runtime write
35
+ // (fontconfig, camoufox's own cache) lands under the same sandbox root the
36
+ // import-time redirect uses. darwin returns {} because homedir is
37
+ // unredirectable — the install symlink does the work there.
38
+ export function camoufoxCacheEnv(dir, platform = process.platform) {
39
+ if (platform === "darwin") return {};
40
+ if (platform === "win32") return { LOCALAPPDATA: dir };
41
+ return { XDG_CACHE_HOME: dir };
42
+ }
43
+
33
44
  function cacheRedirect(dir, env, platform) {
34
45
  if (platform === "darwin") {
35
46
  ensureDarwinInstallSymlink(dir);
36
47
  return null; // homedir is unredirectable; the symlink does the work
37
48
  }
38
- if (platform === "win32") return { key: "LOCALAPPDATA", value: dir };
39
- return { key: "XDG_CACHE_HOME", value: dir };
49
+ const [key, value] = Object.entries(camoufoxCacheEnv(dir, platform))[0];
50
+ return { key, value };
40
51
  }
41
52
 
42
53
  export class CamoufoxSandboxError extends Error {
@@ -31,7 +31,9 @@ export const SCORE_TIMEOUT_ENV = "MAGPIE_CLEAN_LOGIN_SCORE_TIMEOUT_MS";
31
31
  export const DEFAULT_SCORE_TIMEOUT_MS = 90_000;
32
32
  export const SCORE_LABEL_MAX = 40;
33
33
  export const SCORE_IP_MAX = 80;
34
- export const SCORE_ERROR_MAX = 240;
34
+ // Long enough to keep a full browser-launch failure, including playwright's
35
+ // own "missing display / xvfb" hints which run well past a UI-sized cap.
36
+ export const SCORE_ERROR_MAX = 2000;
35
37
  export const SCORE_ERROR_CODE_MAX = 48;
36
38
 
37
39
  // The page's own element ids.
package/lib/server.mjs CHANGED
@@ -33,7 +33,7 @@ import {
33
33
  userIcon,
34
34
  userIconType,
35
35
  } from "./provider-icons.mjs";
36
- import { createPluginScanner } from "./magpie-plugins.mjs";
36
+ import { createPluginScanner, scanMagpiePlugins } from "./magpie-plugins.mjs";
37
37
  import { MarketInstallError, createMarketInstaller } from "./market-install.mjs";
38
38
  import { RenewHostingError, createRenewHosting, offView } from "./renew-hosting.mjs";
39
39
  import { buildIssueRequest, isAllowedIssueUrl } from "./issue-report.mjs";
@@ -530,7 +530,10 @@ export async function startServer({
530
530
  // The asset registry shares the plugin's private data directory but keeps
531
531
  // its own file, so it never has to migrate the proxy store's shape.
532
532
  const assetStore = createAssetStore({ dataDir });
533
- const environment = environmentManager || createEnvironmentManager();
533
+ // `env` is the caller's contract: no factory below may fall back to
534
+ // process.env when an env was handed in (the environment root and the
535
+ // plugin scan root both derive from it).
536
+ const environment = environmentManager || createEnvironmentManager({ env });
534
537
  // Keeps magpie's providers.json in step with the exits accounts signed in
535
538
  // through, so each account really runs through the exit the user picked.
536
539
  const accountProxySync =
@@ -544,7 +547,11 @@ export async function startServer({
544
547
  // cached with a TTL and warmed in the background only after the service is
545
548
  // listening, so it can never delay startup. `createPluginScanner` disables
546
549
  // itself under NODE_ENV=test unless a scanner is injected.
547
- const pluginScanner = pluginScannerOption || createPluginScanner();
550
+ const scannerEnv = env ?? process.env;
551
+ const pluginScanner = pluginScannerOption || createPluginScanner({
552
+ scan: () => scanMagpiePlugins({ env: scannerEnv }),
553
+ enabled: scannerEnv.NODE_ENV !== "test",
554
+ });
548
555
  const providerRegistration =
549
556
  providerRegistrationOption ||
550
557
  createProviderRegistration({ env: env ?? process.env, pluginScanner });
@@ -1392,8 +1399,12 @@ export async function startServer({
1392
1399
 
1393
1400
  if (url.pathname === "/api/proxies") {
1394
1401
  if (req.method === "GET") {
1402
+ // The recovery flag is only set while the store loads, so read it
1403
+ // after list() has resolved — before the fix the first request
1404
+ // against a corrupt proxies.json missed it.
1405
+ const proxies = await store.list();
1395
1406
  const recovered = typeof store.recovered === "function" ? store.recovered() : null;
1396
- json(res, 200, { proxies: await store.list(), ...(recovered ? { recovered } : {}) });
1407
+ json(res, 200, { proxies, ...(recovered ? { recovered } : {}) });
1397
1408
  return;
1398
1409
  }
1399
1410
  if (req.method === "POST") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gruu6y/page-clean-login",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "在 magpie 中管理代理 IP 与供应商登录,每个账号通过独立浏览器身份登录;一个带仅回环主机服务的页面插件。",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
package/ui/app.js CHANGED
@@ -326,6 +326,7 @@ const messages = {
326
326
  errorInvalidPort: "The port must be between 1 and 65535.",
327
327
  errorInvalidUsername: "The username is not valid.",
328
328
  errorInvalidPassword: "The password is not valid.",
329
+ errorNameTaken: "A proxy with that name already exists.",
329
330
  errorNotFound: "This proxy no longer exists.",
330
331
  errorInvalidJson: "The request was not valid JSON.",
331
332
  errorTooLarge: "The request was too large.",
@@ -853,6 +854,7 @@ const messages = {
853
854
  errorInvalidPort: "端口应在 1 到 65535 之间。",
854
855
  errorInvalidUsername: "用户名无效。",
855
856
  errorInvalidPassword: "密码无效。",
857
+ errorNameTaken: "已存在同名的代理。",
856
858
  errorNotFound: "这个代理已不存在。",
857
859
  errorInvalidJson: "请求不是有效的 JSON。",
858
860
  errorTooLarge: "请求内容过大。",
@@ -1380,6 +1382,7 @@ const messages = {
1380
1382
  errorInvalidPort: "連接埠應在 1 到 65535 之間。",
1381
1383
  errorInvalidUsername: "使用者名稱無效。",
1382
1384
  errorInvalidPassword: "密碼無效。",
1385
+ errorNameTaken: "已存在同名的代理。",
1383
1386
  errorNotFound: "這個代理已不存在。",
1384
1387
  errorInvalidJson: "請求不是有效的 JSON。",
1385
1388
  errorTooLarge: "請求內容過大。",
@@ -1907,6 +1910,7 @@ const messages = {
1907
1910
  errorInvalidPort: "ポートは 1 から 65535 の範囲で入力してください。",
1908
1911
  errorInvalidUsername: "ユーザー名が無効です。",
1909
1912
  errorInvalidPassword: "パスワードが無効です。",
1913
+ errorNameTaken: "同名のプロキシがすでに存在します。",
1910
1914
  errorNotFound: "このプロキシは存在しません。",
1911
1915
  errorInvalidJson: "リクエストが有効な JSON ではありません。",
1912
1916
  errorTooLarge: "リクエストが大きすぎます。",
@@ -2385,6 +2389,7 @@ const errorKeys = {
2385
2389
  identity_mismatch: "errorAccountMismatch",
2386
2390
  invalid_account: "errorAccountInvalid",
2387
2391
  invalid_name: "errorInvalidName",
2392
+ name_taken: "errorNameTaken",
2388
2393
  invalid_type: "errorInvalidType",
2389
2394
  invalid_host: "errorInvalidHost",
2390
2395
  invalid_port: "errorInvalidPort",
@@ -2417,7 +2422,13 @@ const testErrorKeys = {
2417
2422
  unknown: "testUnknown",
2418
2423
  };
2419
2424
 
2420
- function apiErrorText(code) {
2425
+ function apiErrorText(error) {
2426
+ const code = error?.code;
2427
+ // The proxy store returns one code for every name failure ("Name is
2428
+ // required.", "...too long.", "Name must not contain < or >."). A single
2429
+ // localized string cannot say which one happened, so the server's own
2430
+ // message is the honest answer whenever it exists.
2431
+ if (code === "invalid_name" && error?.serverMessage) return String(error.serverMessage);
2421
2432
  return text[errorKeys[code]] || text.errorGeneric;
2422
2433
  }
2423
2434
 
@@ -4343,7 +4354,7 @@ function serverErrorText(error) {
4343
4354
  if (code === "network") return text.errorNetwork;
4344
4355
  const key = (code !== "not_found" ? errorKeys[code] : undefined) || checkErrorKeys[code];
4345
4356
  if (key && text[key]) return text[key];
4346
- return [code, message].filter(Boolean).join(" · ") || apiErrorText(error?.code);
4357
+ return [code, message].filter(Boolean).join(" · ") || apiErrorText(error);
4347
4358
  }
4348
4359
 
4349
4360
  function signInStateLabel(state) {
@@ -5307,7 +5318,7 @@ function environmentChecksumVerified(env) {
5307
5318
  function environmentRequestErrorText(error) {
5308
5319
  const code = error?.code;
5309
5320
  if (code && environmentErrorKeys[code]) return text[environmentErrorKeys[code]];
5310
- return apiErrorText(code);
5321
+ return apiErrorText(error);
5311
5322
  }
5312
5323
 
5313
5324
  function stopEnvironmentPolling() {
@@ -5772,7 +5783,7 @@ async function testDialogProxy() {
5772
5783
  return;
5773
5784
  }
5774
5785
  context.lastTest = null;
5775
- setTestResult("error", text.testFailure.replace("{error}", apiErrorText(error.code)));
5786
+ setTestResult("error", text.testFailure.replace("{error}", apiErrorText(error)));
5776
5787
  } finally {
5777
5788
  if (dialogContext === context) {
5778
5789
  context.testing = false;
@@ -5812,7 +5823,7 @@ async function saveProxy() {
5812
5823
  if (testedValues && saved.status !== "ok") testRowProxy(saved.id);
5813
5824
  } catch (error) {
5814
5825
  if (dialogContext === context && byId("proxy-dialog").open) {
5815
- setFormError(apiErrorText(error.code));
5826
+ setFormError(apiErrorText(error));
5816
5827
  context.saving = false;
5817
5828
  setDialogBusy(false);
5818
5829
  }
@@ -5881,7 +5892,7 @@ async function confirmDelete() {
5881
5892
  } catch (error) {
5882
5893
  deleting = false;
5883
5894
  if (byId("confirm-dialog").open) {
5884
- setConfirmError(apiErrorText(error.code));
5895
+ setConfirmError(apiErrorText(error));
5885
5896
  setConfirmBusy(false);
5886
5897
  } else {
5887
5898
  confirmController.cancel();