@gruu6y/page-clean-login 0.2.9 → 0.2.10

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.
@@ -29,12 +29,14 @@
29
29
 
30
30
  import { randomUUID } from "node:crypto";
31
31
  import { chmod, mkdir, open, readFile, rename, rm } from "node:fs/promises";
32
- import { dirname, join } from "node:path";
32
+ import { basename, dirname, join } from "node:path";
33
33
  import { magpieConfigDir, pluginDataDir } from "./paths.mjs";
34
34
  import { listAccountDirsWithMeta } from "./account-identity.mjs";
35
35
 
36
36
  export const PROVIDERS_FILE_NAME = "providers.json";
37
- const URL_TYPES = new Set(["http", "https", "socks5"]);
37
+ export const ACCOUNT_PROXY_BACKFILL_FILE = "account-proxy-backfill.json";
38
+ const URL_TYPES = new Set(["http", "https", "socks5", "socks4"]);
39
+ const DEFAULT_PROXY_PORTS = { http: 80, https: 443 };
38
40
  const SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
39
41
  // A user name that is also an object key with special meaning must never be
40
42
  // written into magpie's map; such an account is left on the provider proxy.
@@ -50,6 +52,95 @@ export function accountProxyKey(user) {
50
52
  return String(user ?? "").trim().toLowerCase();
51
53
  }
52
54
 
55
+ function safeDecodeComponent(value) {
56
+ if (!value) return "";
57
+ try {
58
+ return decodeURIComponent(value);
59
+ } catch {
60
+ return value;
61
+ }
62
+ }
63
+
64
+ // A display-only view of an exit URL: scheme, host and port, never the
65
+ // credentials. `providers.json` stores a custom exit as a full URL and
66
+ // `provider.proxy` may carry one too, but HTTP/UI/CLI responses may only ever
67
+ // carry `scheme://host:port`. Unparseable text yields null rather than an echo,
68
+ // so this can never leak credentials.
69
+ export function exitDisplayUrl(value) {
70
+ if (typeof value !== "string") return null;
71
+ const trimmed = value.trim();
72
+ if (!trimmed || trimmed.toLowerCase() === "direct") return null;
73
+ try {
74
+ const url = new URL(trimmed);
75
+ return url.host ? `${url.protocol}//${url.host}` : null;
76
+ } catch {
77
+ return null;
78
+ }
79
+ }
80
+
81
+ // Parses a proxy URL (`http://`, `https://`, `socks5://`, `socks4://`) into the
82
+ // normalized shape `browser-launcher.mjs` and `signin-egress.mjs` consume.
83
+ // Handles IPv6 literals (`[::1]`) and percent-encoded credentials. `server`
84
+ // intentionally omits `username`/`password` because Playwright requires them as
85
+ // separate fields. Invalid or non-proxy inputs return null.
86
+ export function parseProxyUrl(rawUrl) {
87
+ if (typeof rawUrl !== "string") return null;
88
+ const trimmed = rawUrl.trim();
89
+ if (!trimmed || trimmed.toLowerCase() === "direct") return null;
90
+ let parsed;
91
+ try {
92
+ parsed = new URL(trimmed);
93
+ } catch {
94
+ return null;
95
+ }
96
+ const type = parsed.protocol.replace(/:$/, "").toLowerCase();
97
+ if (!URL_TYPES.has(type)) return null;
98
+ if ((parsed.pathname && parsed.pathname !== "/") || parsed.search || parsed.hash) {
99
+ return null;
100
+ }
101
+ const rawHostname = parsed.hostname;
102
+ if (!rawHostname) return null;
103
+ const host =
104
+ rawHostname.startsWith("[") && rawHostname.endsWith("]")
105
+ ? rawHostname.slice(1, -1)
106
+ : rawHostname;
107
+ if (!host || /\s/.test(host)) return null;
108
+
109
+ let port;
110
+ if (parsed.port) {
111
+ if (!/^\d+$/.test(parsed.port)) return null;
112
+ port = Number(parsed.port);
113
+ } else if (Object.hasOwn(DEFAULT_PROXY_PORTS, type)) {
114
+ port = DEFAULT_PROXY_PORTS[type];
115
+ } else {
116
+ return null;
117
+ }
118
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
119
+
120
+ const username = safeDecodeComponent(parsed.username);
121
+ const password = safeDecodeComponent(parsed.password);
122
+ const address = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
123
+ const server = `${type}://${address}:${port}`;
124
+ return { type, host, port, username, password, server };
125
+ }
126
+
127
+ // Canonical proxy URL text used for matching equivalent URLs (e.g. trailing
128
+ // slash, uppercase scheme, or encoding differences) between `proxies.json` and
129
+ // `providers.json`.
130
+ export function canonicalProxyUrl(rawUrl) {
131
+ const parsed = parseProxyUrl(rawUrl);
132
+ if (!parsed) return null;
133
+ const auth =
134
+ parsed.username || parsed.password
135
+ ? `${encodeURIComponent(parsed.username)}:${encodeURIComponent(parsed.password)}@`
136
+ : "";
137
+ const address =
138
+ parsed.host.includes(":") && !parsed.host.startsWith("[")
139
+ ? `[${parsed.host}]`
140
+ : parsed.host;
141
+ return `${parsed.type}://${auth}${address}:${parsed.port}`;
142
+ }
143
+
53
144
  // The stored proxy record carries credentials; magpie's own editor expects
54
145
  // them inline in the URL (`http://user:pass@host:port`), so they are encoded
55
146
  // rather than dropped. A record without a usable address yields null and the
@@ -93,7 +184,7 @@ function serialized(file, work) {
93
184
  async function writeAtomic(file, text) {
94
185
  const dir = dirname(file);
95
186
  await mkdir(dir, { recursive: true });
96
- const temp = join(dir, `.${PROVIDERS_FILE_NAME}.${process.pid}.${randomUUID()}.tmp`);
187
+ const temp = join(dir, `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
97
188
  let handle;
98
189
  try {
99
190
  handle = await open(temp, "wx", 0o600);
@@ -253,6 +344,113 @@ function accountProxyMap(entry) {
253
344
  : {};
254
345
  }
255
346
 
347
+ // Tracks accounts that have already been synchronized with magpie at least once
348
+ // so that a user explicitly switching an account back to `inherit` in magpie
349
+ // (which deletes `accountProxies[key]`) does not rebound to historical
350
+ // `lastLogin` on the next clean-login restart. Stores only provider/account
351
+ // keys and timestamps — never proxy URLs or credentials.
352
+ function backfillStateKey(provider, accountId) {
353
+ const p = String(provider ?? "").trim();
354
+ const k = accountProxyKey(accountId);
355
+ if (!p || !k || RESERVED_KEYS.has(k)) return null;
356
+ return `${p}\u0000${k}`;
357
+ }
358
+
359
+ export function resolveBackfillStateFile({
360
+ env = process.env,
361
+ file = providersFile(env),
362
+ dataDir = null,
363
+ stateFile = null,
364
+ } = {}) {
365
+ if (typeof stateFile === "string" && stateFile) return stateFile;
366
+ if (typeof dataDir === "string" && dataDir) {
367
+ return join(dataDir, ACCOUNT_PROXY_BACKFILL_FILE);
368
+ }
369
+ const defaultProviders = providersFile(env);
370
+ if (file && file !== defaultProviders) {
371
+ return join(dirname(file), "magpie-clean-login", ACCOUNT_PROXY_BACKFILL_FILE);
372
+ }
373
+ return join(pluginDataDir(env), ACCOUNT_PROXY_BACKFILL_FILE);
374
+ }
375
+
376
+ async function readBackfillState(stateFile) {
377
+ try {
378
+ const text = await readFile(stateFile, "utf8");
379
+ const doc = JSON.parse(text);
380
+ const raw = doc?.synced;
381
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return Object.create(null);
382
+ const out = Object.create(null);
383
+ for (const [k, v] of Object.entries(raw)) {
384
+ if (typeof v === "string" && v) out[k] = v;
385
+ }
386
+ return out;
387
+ } catch {
388
+ return Object.create(null);
389
+ }
390
+ }
391
+
392
+ async function markBackfilledKeys(stateFile, keys) {
393
+ const valid = [...new Set(keys.filter((k) => typeof k === "string" && k))];
394
+ if (!valid.length) return;
395
+ await serialized(stateFile, async () => {
396
+ const synced = await readBackfillState(stateFile);
397
+ let changed = false;
398
+ const now = new Date().toISOString();
399
+ for (const key of valid) {
400
+ if (!Object.hasOwn(synced, key)) {
401
+ synced[key] = now;
402
+ changed = true;
403
+ }
404
+ }
405
+ if (!changed) return;
406
+ await writeAtomic(stateFile, `${JSON.stringify({ version: 1, synced }, null, 2)}\n`);
407
+ });
408
+ }
409
+
410
+ async function unmarkBackfilledKey(stateFile, key) {
411
+ if (typeof key !== "string" || !key) return;
412
+ await serialized(stateFile, async () => {
413
+ const synced = await readBackfillState(stateFile);
414
+ if (!Object.hasOwn(synced, key)) return;
415
+ delete synced[key];
416
+ await writeAtomic(stateFile, `${JSON.stringify({ version: 1, synced }, null, 2)}\n`);
417
+ });
418
+ }
419
+
420
+ // Reads providers.json once under the file lock so batch callers (such as
421
+ // account list projection) avoid N+1 reads while staying serialized against
422
+ // concurrent writers in this process.
423
+ export async function readProvidersSnapshot({
424
+ env = process.env,
425
+ file = providersFile(env),
426
+ } = {}) {
427
+ return serialized(file, () => readProvidersDoc(file));
428
+ }
429
+
430
+ // Pure lookup against a snapshot returned by `readProvidersSnapshot()`.
431
+ export function extractAccountExitFromDoc(loaded, provider, accountId) {
432
+ const key = accountProxyKey(accountId);
433
+ if (!key || RESERVED_KEYS.has(key)) {
434
+ return { ok: false, reason: "account_name_unknown", key };
435
+ }
436
+ if (!loaded || typeof loaded !== "object") {
437
+ return { ok: false, reason: "providers_missing", key };
438
+ }
439
+ if (!loaded.ok) return { ...loaded, key };
440
+ const entry = findProvider(loaded.doc, provider);
441
+ if (!entry) return { ok: false, reason: "provider_missing", key };
442
+ const providerProxy = entry.proxy ?? null;
443
+ const map = accountProxyMap(entry);
444
+ const value = Object.hasOwn(map, key) ? map[key] : undefined;
445
+ if (value === "direct") {
446
+ return { ok: true, mode: "direct", url: "direct", key, providerProxy };
447
+ }
448
+ if (typeof value === "string") {
449
+ return { ok: true, mode: "custom", url: value, key, providerProxy };
450
+ }
451
+ return { ok: true, mode: "inherit", url: null, key, providerProxy };
452
+ }
453
+
256
454
  // Reads the exit an account currently follows, for the page's "change exit"
257
455
  // dialog. `inherit` means no entry, so the account follows `providerProxy`.
258
456
  // Read failures return a structured reason instead of throwing, because the
@@ -270,19 +468,7 @@ export async function readAccountExit({
270
468
 
271
469
  return serialized(file, async () => {
272
470
  const loaded = await readProvidersDoc(file);
273
- if (!loaded.ok) return { ...loaded, key };
274
- const entry = findProvider(loaded.doc, provider);
275
- if (!entry) return { ok: false, reason: "provider_missing", key };
276
- const providerProxy = entry.proxy ?? null;
277
- const map = accountProxyMap(entry);
278
- const value = Object.hasOwn(map, key) ? map[key] : undefined;
279
- if (value === "direct") {
280
- return { ok: true, mode: "direct", url: "direct", key, providerProxy };
281
- }
282
- if (typeof value === "string") {
283
- return { ok: true, mode: "custom", url: value, key, providerProxy };
284
- }
285
- return { ok: true, mode: "inherit", url: null, key, providerProxy };
471
+ return extractAccountExitFromDoc(loaded, provider, accountId);
286
472
  });
287
473
  }
288
474
 
@@ -299,6 +485,8 @@ export async function writeAccountExit({
299
485
  mode,
300
486
  url = null,
301
487
  file = providersFile(env),
488
+ dataDir = null,
489
+ stateFile = null,
302
490
  } = {}) {
303
491
  const key = accountProxyKey(accountId);
304
492
  if (!key || RESERVED_KEYS.has(key)) {
@@ -320,7 +508,8 @@ export async function writeAccountExit({
320
508
  return { ok: false, reason: "invalid_mode", key };
321
509
  }
322
510
 
323
- return serialized(file, async () => {
511
+ const resolvedStateFile = resolveBackfillStateFile({ env, file, dataDir, stateFile });
512
+ const result = await serialized(file, async () => {
324
513
  const loaded = await readProvidersDoc(file);
325
514
  if (!loaded.ok) return { ...loaded, key };
326
515
  const entry = findProvider(loaded.doc, provider);
@@ -361,6 +550,12 @@ export async function writeAccountExit({
361
550
 
362
551
  return { ok: true, mode, url: after, key, before, after, changed: true, reason: "written" };
363
552
  });
553
+
554
+ if (result.ok) {
555
+ const bKey = backfillStateKey(provider, accountId);
556
+ if (bKey) await markBackfilledKeys(resolvedStateFile, [bKey]);
557
+ }
558
+ return result;
364
559
  }
365
560
 
366
561
  // A finished sign-in: the account's own entry follows the exit it just used.
@@ -375,19 +570,31 @@ export async function syncSignInProxy({
375
570
  accountId,
376
571
  proxy,
377
572
  file = providersFile(env),
573
+ dataDir = null,
574
+ stateFile = null,
378
575
  } = {}) {
379
576
  const url = proxyUrlFor(proxy);
380
577
  const key = accountProxyKey(accountId);
381
578
  if (!key || RESERVED_KEYS.has(key) || !provider) {
382
579
  return { ok: true, changed: [], skipped: [], reason: "no_proxy" };
383
580
  }
581
+ const resolvedStateFile = resolveBackfillStateFile({ env, file, dataDir, stateFile });
582
+ const bKey = backfillStateKey(provider, accountId);
384
583
  if (!url) {
385
584
  if (proxy === null || proxy === undefined) {
386
585
  const loaded = await readProvidersDoc(file);
387
586
  const entry = loaded.ok ? findProvider(loaded.doc, provider) : null;
388
- const map = accountProxyMap(entry);
587
+ const map = entry ? accountProxyMap(entry) : {};
389
588
  if (entry && Object.hasOwn(map, key) && map[key] !== "direct") {
390
- const res = await writeAccountExit({ env, provider, accountId, mode: "direct", file });
589
+ const res = await writeAccountExit({
590
+ env,
591
+ provider,
592
+ accountId,
593
+ mode: "direct",
594
+ file,
595
+ dataDir,
596
+ stateFile: resolvedStateFile,
597
+ });
391
598
  return {
392
599
  ok: res.ok,
393
600
  changed: res.changed ? [{ provider, accountId, key: res.key, url: "direct" }] : [],
@@ -395,10 +602,22 @@ export async function syncSignInProxy({
395
602
  reason: res.changed ? "cleared_to_direct" : (res.reason ?? "no_proxy"),
396
603
  };
397
604
  }
605
+ if (entry && bKey) {
606
+ await markBackfilledKeys(resolvedStateFile, [bKey]);
607
+ }
398
608
  }
399
609
  return { ok: true, changed: [], skipped: [], reason: "no_proxy" };
400
610
  }
401
- return writeAccountProxies({ env, entries: [{ provider, accountId, url }], file });
611
+ const res = await writeAccountProxies({ env, entries: [{ provider, accountId, url }], file });
612
+ if (
613
+ res.ok &&
614
+ bKey &&
615
+ (res.changed.length > 0 ||
616
+ res.skipped.some((s) => s.reason === "unchanged" || s.reason === "already_set"))
617
+ ) {
618
+ await markBackfilledKeys(resolvedStateFile, [bKey]);
619
+ }
620
+ return res;
402
621
  }
403
622
 
404
623
  function accountActiveProxyId(meta) {
@@ -407,13 +626,18 @@ function accountActiveProxyId(meta) {
407
626
  }
408
627
 
409
628
  // Startup backfill: every ledger that remembers which exit it is bound to
410
- // (`exit`, falling back to `lastLogin`) gets that exit into magpie, but only
411
- // where magpie has no entry yet.
629
+ // (`exit`, falling back to `lastLogin`) gets that exit into magpie at most
630
+ // once, and only where magpie has no entry yet. Already-synced accounts are
631
+ // recorded in `account-proxy-backfill.json` so switching an account back to
632
+ // `inherit` in magpie (which deletes `accountProxies[key]`) does not rebound
633
+ // to historical `lastLogin` on the next restart.
412
634
  export async function backfillAccountProxies({
413
635
  env = process.env,
414
636
  store,
415
637
  listAccounts = listAccountDirsWithMeta,
416
638
  file = providersFile(env),
639
+ dataDir = null,
640
+ stateFile = null,
417
641
  } = {}) {
418
642
  const report = { ok: false, file, changed: [], skipped: [], reason: null, ledgers: 0 };
419
643
  let accounts;
@@ -425,15 +649,27 @@ export async function backfillAccountProxies({
425
649
  return report;
426
650
  }
427
651
 
652
+ const resolvedStateFile = resolveBackfillStateFile({ env, file, dataDir, stateFile });
653
+ const synced = await readBackfillState(resolvedStateFile);
654
+
428
655
  const wanted = [];
429
656
  const seen = new Set();
657
+ let alreadyBackfilled = 0;
430
658
  for (const account of Array.isArray(accounts) ? accounts : []) {
431
659
  const meta = account?.meta;
432
660
  const proxyId = accountActiveProxyId(meta);
433
661
  const accountId = meta?.accountId;
434
662
  const provider = meta?.provider ?? account?.provider;
435
- if (!proxyId || !accountProxyKey(accountId) || !provider) continue;
663
+ const bKey = backfillStateKey(provider, accountId);
664
+ if (!proxyId || !bKey) continue;
436
665
  report.ledgers += 1;
666
+ if (seen.has(bKey)) continue;
667
+ seen.add(bKey);
668
+ if (Object.hasOwn(synced, bKey)) {
669
+ alreadyBackfilled += 1;
670
+ report.skipped.push({ provider, accountId, reason: "already_backfilled" });
671
+ continue;
672
+ }
437
673
  let url = null;
438
674
  try {
439
675
  url = proxyUrlFor(await store?.get?.(proxyId));
@@ -446,27 +682,49 @@ export async function backfillAccountProxies({
446
682
  report.skipped.push({ provider, accountId, reason: "proxy_missing" });
447
683
  continue;
448
684
  }
449
- const key = `${provider}\u0000${accountProxyKey(accountId)}`;
450
- if (seen.has(key)) continue;
451
- seen.add(key);
452
685
  wanted.push({ provider, accountId, url });
453
686
  }
454
687
 
455
688
  if (!wanted.length) {
456
689
  report.ok = true;
457
- report.reason = report.ledgers ? "no_usable_exit" : "nothing_to_sync";
690
+ report.reason =
691
+ alreadyBackfilled > 0
692
+ ? "up_to_date"
693
+ : report.ledgers
694
+ ? "no_usable_exit"
695
+ : "nothing_to_sync";
458
696
  return report;
459
697
  }
460
698
  const written = await writeAccountProxies({ env, entries: wanted, onlyMissing: true, file });
699
+ if (written.ok) {
700
+ const keysToMark = [];
701
+ for (const item of written.changed) {
702
+ const k = backfillStateKey(item.provider, item.key);
703
+ if (k) keysToMark.push(k);
704
+ }
705
+ for (const item of written.skipped) {
706
+ if (item.reason === "already_set" || item.reason === "unchanged") {
707
+ const k = backfillStateKey(item.provider, item.key);
708
+ if (k) keysToMark.push(k);
709
+ }
710
+ }
711
+ if (keysToMark.length) await markBackfilledKeys(resolvedStateFile, keysToMark);
712
+ }
461
713
  return { ...written, ledgers: report.ledgers, skipped: [...report.skipped, ...written.skipped] };
462
714
  }
463
715
 
464
- // Re-sync every account whose active exit points to `proxyId` after that
465
- // proxy's connection or credentials are updated.
716
+ // Re-sync every account pointing at a proxy after its connection or credentials
717
+ // change. When `previousUrl` is supplied (the normal HTTP path), magpie's
718
+ // `providers.json` is scanned directly and every `accountProxies` entry matching
719
+ // the old URL (exact or canonical) is updated — catching accounts bound directly
720
+ // in magpie while never overwriting accounts switched to `direct`, `inherit`, or
721
+ // another proxy. When `previousUrl` is omitted (legacy callers), falls back to
722
+ // scanning account ledgers bound to `proxyId`.
466
723
  export async function syncProxyUpdate({
467
724
  env = process.env,
468
725
  store,
469
726
  proxyId,
727
+ previousUrl = null,
470
728
  listAccounts = listAccountDirsWithMeta,
471
729
  file = providersFile(env),
472
730
  } = {}) {
@@ -480,6 +738,70 @@ export async function syncProxyUpdate({
480
738
  record = null;
481
739
  }
482
740
  const url = proxyUrlFor(record);
741
+ const prevRaw = typeof previousUrl === "string" ? previousUrl.trim() : "";
742
+
743
+ if (prevRaw) {
744
+ if (!url) {
745
+ return { ok: false, file, changed: [], skipped: [], reason: "proxy_missing" };
746
+ }
747
+ if (prevRaw === url) {
748
+ return { ok: true, file, changed: [], skipped: [], reason: "up_to_date" };
749
+ }
750
+ const prevCanonical = canonicalProxyUrl(prevRaw);
751
+ return serialized(file, async () => {
752
+ const loaded = await readProvidersDoc(file);
753
+ if (!loaded.ok) {
754
+ return {
755
+ ok: false,
756
+ file,
757
+ changed: [],
758
+ skipped: [],
759
+ reason: loaded.reason,
760
+ ...(loaded.error ? { error: loaded.error } : {}),
761
+ };
762
+ }
763
+ const changed = [];
764
+ const skipped = [];
765
+ for (const providerEntry of loaded.doc.providers) {
766
+ if (!providerEntry || typeof providerEntry !== "object" || Array.isArray(providerEntry)) {
767
+ continue;
768
+ }
769
+ const providerId = typeof providerEntry.id === "string" ? providerEntry.id : "";
770
+ if (!providerId) continue;
771
+ const map = accountProxyMap(providerEntry);
772
+ for (const [key, current] of Object.entries(map)) {
773
+ if (RESERVED_KEYS.has(key) || typeof current !== "string" || current === "direct") {
774
+ continue;
775
+ }
776
+ const matched =
777
+ current === prevRaw ||
778
+ (prevCanonical !== null && canonicalProxyUrl(current) === prevCanonical);
779
+ if (!matched) continue;
780
+ if (current === url) {
781
+ skipped.push({ provider: providerId, key, url, reason: "unchanged" });
782
+ continue;
783
+ }
784
+ if (!Object.hasOwn(providerEntry, "accountProxies") || providerEntry.accountProxies !== map) {
785
+ providerEntry.accountProxies = { ...map };
786
+ }
787
+ providerEntry.accountProxies[key] = url;
788
+ changed.push({ provider: providerId, key, url });
789
+ }
790
+ }
791
+ if (!changed.length) {
792
+ return {
793
+ ok: true,
794
+ file,
795
+ changed,
796
+ skipped,
797
+ reason: skipped.length ? "up_to_date" : "nothing_to_sync",
798
+ };
799
+ }
800
+ await writeAtomic(file, `${JSON.stringify(loaded.doc, null, 2)}\n`);
801
+ return { ok: true, file, changed, skipped, reason: "written" };
802
+ });
803
+ }
804
+
483
805
  let accounts;
484
806
  try {
485
807
  accounts = await listAccounts(env);
@@ -533,24 +855,42 @@ export async function clearAccountProxy({
533
855
  provider,
534
856
  accountId,
535
857
  file = providersFile(env),
858
+ dataDir = null,
859
+ stateFile = null,
536
860
  } = {}) {
537
861
  const key = accountProxyKey(accountId);
538
862
  if (!provider || !key || RESERVED_KEYS.has(key)) {
539
863
  return { ok: true, changed: false, reason: "account_name_unknown" };
540
864
  }
865
+ const resolvedStateFile = resolveBackfillStateFile({ env, file, dataDir, stateFile });
866
+ const bKey = backfillStateKey(provider, accountId);
541
867
  const loaded = await readProvidersDoc(file);
542
868
  if (!loaded.ok) {
869
+ if (bKey) await unmarkBackfilledKey(resolvedStateFile, bKey);
543
870
  return loaded.reason === "providers_missing"
544
871
  ? { ok: true, changed: false, reason: "providers_missing" }
545
872
  : { ok: false, changed: false, reason: loaded.reason };
546
873
  }
547
874
  const entry = findProvider(loaded.doc, provider);
548
- if (!entry) return { ok: true, changed: false, reason: "provider_missing" };
875
+ if (!entry) {
876
+ if (bKey) await unmarkBackfilledKey(resolvedStateFile, bKey);
877
+ return { ok: true, changed: false, reason: "provider_missing" };
878
+ }
549
879
  const map = accountProxyMap(entry);
550
880
  if (!Object.hasOwn(map, key)) {
881
+ if (bKey) await unmarkBackfilledKey(resolvedStateFile, bKey);
551
882
  return { ok: true, changed: false, reason: "unchanged" };
552
883
  }
553
- const res = await writeAccountExit({ env, provider, accountId, mode: "inherit", file });
884
+ const res = await writeAccountExit({
885
+ env,
886
+ provider,
887
+ accountId,
888
+ mode: "inherit",
889
+ file,
890
+ dataDir,
891
+ stateFile: resolvedStateFile,
892
+ });
893
+ if (res.ok && bKey) await unmarkBackfilledKey(resolvedStateFile, bKey);
554
894
  return { ok: res.ok, changed: Boolean(res.changed), reason: res.reason };
555
895
  }
556
896
 
@@ -572,13 +912,13 @@ export function createAccountProxySync({ env = process.env, store, dataDir = plu
572
912
  if (record && !proxyUrlFor(record) && typeof record.id === "string" && record.id) {
573
913
  record = await (await ensureStore()).get(record.id);
574
914
  }
575
- return syncSignInProxy({ env, provider, accountId, proxy: record });
915
+ return syncSignInProxy({ env, provider, accountId, proxy: record, dataDir });
576
916
  },
577
- syncProxyUpdate: async ({ proxyId }) =>
578
- syncProxyUpdate({ env, store: await ensureStore(), proxyId }),
917
+ syncProxyUpdate: async ({ proxyId, previousUrl } = {}) =>
918
+ syncProxyUpdate({ env, store: await ensureStore(), proxyId, previousUrl }),
579
919
  clearAccountProxy: async ({ provider, accountId }) =>
580
- clearAccountProxy({ env, provider, accountId }),
920
+ clearAccountProxy({ env, provider, accountId, dataDir }),
581
921
  backfill: async () =>
582
- backfillAccountProxies({ env, store: await ensureStore() }),
922
+ backfillAccountProxies({ env, store: await ensureStore(), dataDir }),
583
923
  };
584
924
  }
@@ -20,6 +20,8 @@
20
20
  // request block inside the service until the job settles (or a bound elapses)
21
21
  // and answer once.
22
22
 
23
+ import { exitDisplayUrl } from "./account-proxies.mjs";
24
+
23
25
  // The longest a single request may block. A caller can ask for more; the
24
26
  // service clamps to this so one request cannot hold a connection open
25
27
  // indefinitely.
@@ -182,9 +184,33 @@ export function compactProxy(proxy) {
182
184
  };
183
185
  }
184
186
 
185
- // One account, compact: identity, whether it is signed in, and its note. No
186
- // path, no fingerprint detail, no history arrays.
187
+ // Credential-free projection of an account's current effective exit.
188
+ // `displayUrl` is re-sanitized through `exitDisplayUrl` so credentials can
189
+ // never slip into `/api/agent` or CLI output.
190
+ function compactExit(exit) {
191
+ if (!exit || typeof exit !== "object") return null;
192
+ const displayUrl = exitDisplayUrl(exit.displayUrl);
193
+ return {
194
+ mode:
195
+ exit.mode === "inherit"
196
+ ? "inherit"
197
+ : exit.custom || (typeof exit.proxyId === "string" && exit.proxyId)
198
+ ? "custom"
199
+ : "direct",
200
+ proxyId: typeof exit.proxyId === "string" && exit.proxyId ? exit.proxyId : null,
201
+ proxyName: typeof exit.proxyName === "string" ? exit.proxyName : "",
202
+ region: typeof exit.region === "string" ? exit.region : "",
203
+ type: typeof exit.type === "string" && exit.type ? exit.type : null,
204
+ ...(exit.custom ? { custom: true } : {}),
205
+ ...(displayUrl ? { displayUrl } : {}),
206
+ };
207
+ }
208
+
209
+ // One account, compact: identity, whether it is signed in, its note, and its
210
+ // current credential-free exit (when present). No path, no fingerprint detail,
211
+ // no history arrays.
187
212
  export function compactAccount(account) {
213
+ const exit = compactExit(account?.exit);
188
214
  return {
189
215
  provider: account?.provider ?? "",
190
216
  key: account?.key ?? "",
@@ -194,6 +220,7 @@ export function compactAccount(account) {
194
220
  accountId: account?.accountId ?? null,
195
221
  note: account?.note ?? "",
196
222
  lastCheckedAt: account?.lastCheck?.at ?? null,
223
+ ...(exit ? { exit } : {}),
197
224
  };
198
225
  }
199
226