@gruu6y/page-clean-login 0.2.5 → 0.2.7

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/lib/server.mjs CHANGED
@@ -5,7 +5,10 @@ import { extname, join, normalize, sep } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { pluginDataDir, magpieConfigDir } from "./paths.mjs";
7
7
  import {
8
+ PROXY_BULK_LIMIT,
8
9
  createProxyStore,
10
+ parseBulkProxies,
11
+ proxyConnectionKey,
9
12
  publicProxy,
10
13
  validateCreate,
11
14
  validateProbe,
@@ -72,7 +75,7 @@ import {
72
75
  readAccountExit,
73
76
  writeAccountExit,
74
77
  } from "./account-proxies.mjs";
75
- import { readAuthEntries } from "./signin-writeback.mjs";
78
+ import { readAuthEntries, readAuthExpiries } from "./signin-writeback.mjs";
76
79
  import { createProviderRegistration } from "./provider-registration.mjs";
77
80
  import {
78
81
  agentDigest,
@@ -190,12 +193,12 @@ function applyCors(res, origin) {
190
193
  res.setHeader("vary", "Origin");
191
194
  }
192
195
 
193
- async function readJson(req, { optional = false } = {}) {
196
+ async function readJson(req, { optional = false, maxBytes = MAX_BODY } = {}) {
194
197
  const chunks = [];
195
198
  let size = 0;
196
199
  for await (const chunk of req) {
197
200
  size += chunk.length;
198
- if (size > MAX_BODY) {
201
+ if (size > maxBytes) {
199
202
  throw new HttpError(413, "payload_too_large", "Request body is too large.");
200
203
  }
201
204
  chunks.push(chunk);
@@ -639,7 +642,7 @@ export async function startServer({
639
642
  // is a short digest, never the identity object or the directory path.
640
643
  // `hostingById` lets the list read the policy file once for every row; a
641
644
  // single-account response reads just its own entry.
642
- async function accountView(entry, keys, hostingById = null, exitFallback = undefined) {
645
+ async function accountView(entry, keys, hostingById = null, exitFallback = undefined, authContext = null) {
643
646
  const hosting = hostingById
644
647
  ? hostingById.get(`${entry.provider}\u0000${entry.key}`) ?? offView(entry.provider, entry.key)
645
648
  : await renewHosting.viewOf(entry.provider, entry.key);
@@ -649,12 +652,27 @@ export async function startServer({
649
652
  // a whitelisted fallback snapshot so the node reads as used; it is only a
650
653
  // display projection, never the stored URL.
651
654
  if (!extras.exit && exitFallback !== undefined) extras.exit = exitFallback;
655
+ const runtimeEnv = env ?? process.env;
656
+ const authEntries = authContext?.authEntries ?? readAuthEntries(runtimeEnv);
657
+ const authExpiries = authContext?.authExpiries ?? readAuthExpiries(runtimeEnv);
658
+ const email =
659
+ (typeof entry.meta.email === "string" && entry.meta.email) ||
660
+ (typeof authEntries?.[entry.key]?.email === "string" && authEntries[entry.key].email) ||
661
+ null;
662
+ const methodLabel =
663
+ typeof entry.meta.methodLabel === "string" && entry.meta.methodLabel
664
+ ? entry.meta.methodLabel
665
+ : null;
666
+ const expiresAt = authExpiries?.[entry.key] ?? hosting?.expiresAt ?? null;
652
667
  return {
653
668
  provider: entry.provider,
654
669
  key: entry.key,
655
670
  accountId: entry.meta.accountId ?? null,
656
671
  uid: entry.meta.uid ?? null,
672
+ ...(email ? { email } : {}),
673
+ ...(methodLabel ? { methodLabel } : {}),
657
674
  signedInAt: entry.meta.signedInAt ?? null,
675
+ ...(expiresAt ? { expiresAt } : {}),
658
676
  signedIn: keys.has(entry.key),
659
677
  ...extras,
660
678
  fingerprint: await readFingerprintSummary(entry.dir),
@@ -896,6 +914,7 @@ export async function startServer({
896
914
  // whose ledger has no `exit` snapshot, consult magpie's providers.json for
897
915
  // the exit it is bound to and project it into the view.
898
916
  const authEntries = readAuthEntries(effectiveEnv);
917
+ const authExpiries = readAuthExpiries(effectiveEnv);
899
918
  const nativeEntries = readNativeLoginsResult(effectiveEnv).entries ?? [];
900
919
  let proxyByUrl = null;
901
920
  const accounts = [];
@@ -926,7 +945,9 @@ export async function startServer({
926
945
  fallback = loginSnapshot(null, null);
927
946
  }
928
947
  }
929
- accounts.push(await accountView(entry, keys, hostingById, fallback));
948
+ accounts.push(
949
+ await accountView(entry, keys, hostingById, fallback, { authEntries, authExpiries }),
950
+ );
930
951
  }
931
952
  // Deterministic order: provider, then account key.
932
953
  accounts.sort((a, b) => {
@@ -1000,6 +1021,17 @@ export async function startServer({
1000
1021
  };
1001
1022
  };
1002
1023
 
1024
+ const PROXY_FATAL_ERRORS = new Set([
1025
+ "proxy_auth",
1026
+ "proxy_refused",
1027
+ "proxy_connect",
1028
+ "proxy_dns",
1029
+ "socks_auth",
1030
+ "socks_error",
1031
+ ]);
1032
+
1033
+ let lastMagpieProviders;
1034
+
1003
1035
  const runProxyTest = async (proxy, providerId = "") => {
1004
1036
  const { target, error } = resolveProxyTarget(providerId, pluginScanner.get().providers);
1005
1037
  if (error) throw new HttpError(400, error, "Unknown proxy test target.");
@@ -1013,6 +1045,27 @@ export async function startServer({
1013
1045
  // not the IP service's. Sequential on purpose: a sweep then holds at most
1014
1046
  // one connection per proxy at a time, as it always did.
1015
1047
  const exit = await proxyTester(proxy, { endpoint: proxyEndpoint, timeoutMs: proxyTimeoutMs });
1048
+ const exitOk = exit?.ok === true;
1049
+ const exitFatal =
1050
+ !exitOk && typeof exit?.errorCode === "string" && PROXY_FATAL_ERRORS.has(exit.errorCode);
1051
+ if (exitFatal) {
1052
+ return {
1053
+ ok: false,
1054
+ latency: null,
1055
+ exitIp: "",
1056
+ region: "",
1057
+ exitLatency: null,
1058
+ exitOk: false,
1059
+ provider: target.provider,
1060
+ host: target.host,
1061
+ statusCode: 0,
1062
+ tlsOnly: false,
1063
+ checkedAt: exit?.checkedAt || new Date().toISOString(),
1064
+ target: { kind: "provider", provider: target.provider, host: target.host },
1065
+ error: exit?.error || "Could not reach the proxy.",
1066
+ errorCode: exit.errorCode,
1067
+ };
1068
+ }
1016
1069
  const probe = await proxyTester(proxy, {
1017
1070
  endpoint: target.url,
1018
1071
  timeoutMs: proxyTimeoutMs,
@@ -1021,12 +1074,13 @@ export async function startServer({
1021
1074
  const summary = {
1022
1075
  ok: probe?.ok === true,
1023
1076
  latency: probe?.ok === true && Number.isFinite(probe.latency) ? probe.latency : null,
1024
- exitIp: exit?.ok === true ? exit.exitIp || "" : "",
1025
- region: exit?.ok === true ? exit.region || "" : "",
1077
+ exitIp: exitOk ? exit.exitIp || "" : "",
1078
+ region: exitOk ? exit.region || "" : "",
1026
1079
  // Both legs are measured. `latency` is the number the user asked about
1027
1080
  // (the selected provider), while the row's historical `latency` field
1028
1081
  // keeps meaning "exit -> ipinfo" so switching back to Generic is honest.
1029
- exitLatency: exit?.ok === true && Number.isFinite(exit.latency) ? exit.latency : null,
1082
+ exitLatency: exitOk && Number.isFinite(exit.latency) ? exit.latency : null,
1083
+ exitOk,
1030
1084
  provider: target.provider,
1031
1085
  host: target.host,
1032
1086
  statusCode: Number.isFinite(probe?.statusCode) ? probe.statusCode : 0,
@@ -1216,6 +1270,9 @@ export async function startServer({
1216
1270
  if (req.method !== "POST") return methodNotAllowed(res, "POST");
1217
1271
  const body = await readJson(req, { optional: true });
1218
1272
  const magpiePayload = body && typeof body === "object" ? body.magpie : undefined;
1273
+ if (magpiePayload !== undefined) {
1274
+ lastMagpieProviders = magpiePayload;
1275
+ }
1219
1276
  // `providers:list` is read by the launcher frame and handed over here.
1220
1277
  // Its real payload shape has never been observed on a real machine, so
1221
1278
  // the raw value is logged once per request (bounded, and it carries
@@ -1288,7 +1345,19 @@ export async function startServer({
1288
1345
  // An unknown id still produces a usable report: the reporter's own words
1289
1346
  // matter more than the card metadata, so the row simply falls back to the
1290
1347
  // bare id instead of failing the request.
1291
- const merged = mergeProviderSources({ local: listProviders(), plugins });
1348
+ const runtimeEnv = env ?? process.env;
1349
+ const state = readProviderState(runtimeEnv);
1350
+ const names = new Map();
1351
+ for (const item of state.providers) names.set(item.id, item.name);
1352
+ const catalog = readMarketCatalog(runtimeEnv, { names });
1353
+ const reportMagpie =
1354
+ body && typeof body === "object" && "magpie" in body ? body.magpie : lastMagpieProviders;
1355
+ const merged = mergeProviderSources({
1356
+ local: listProviders(),
1357
+ magpie: reportMagpie,
1358
+ plugins,
1359
+ catalog,
1360
+ });
1292
1361
  const provider =
1293
1362
  (requestedId && merged.providers.find((item) => item && item.id === requestedId)) || {
1294
1363
  id: requestedId,
@@ -1436,6 +1505,51 @@ export async function startServer({
1436
1505
  return;
1437
1506
  }
1438
1507
 
1508
+ if (url.pathname === "/api/proxies/bulk") {
1509
+ if (req.method !== "POST") return methodNotAllowed(res, "POST");
1510
+ const body = await readJson(req, { maxBytes: 128 * 1024 });
1511
+ if (!body || typeof body !== "object" || typeof body.text !== "string") {
1512
+ throw new HttpError(400, "invalid_body", "text is required.");
1513
+ }
1514
+ if (Buffer.byteLength(body.text, "utf8") > 100 * 1024) {
1515
+ throw new HttpError(400, "bulk_too_large", "Bulk proxy text must not exceed 100 KB.");
1516
+ }
1517
+ const existingProxies = await store.list();
1518
+ const existingNames = existingProxies.map((item) => item.name);
1519
+ const existingKeys =
1520
+ body.skipDuplicates === false
1521
+ ? []
1522
+ : existingProxies.map(proxyConnectionKey).filter(Boolean);
1523
+ const parsed = parseBulkProxies(body.text, {
1524
+ defaultType: typeof body.defaultType === "string" ? body.defaultType : "http",
1525
+ prefix: typeof body.prefix === "string" ? body.prefix : "",
1526
+ existingNames,
1527
+ existingKeys,
1528
+ limit: PROXY_BULK_LIMIT,
1529
+ });
1530
+ const created = [];
1531
+ const errors = [...parsed.invalid];
1532
+ for (const item of parsed.items) {
1533
+ try {
1534
+ const input = validateCreate(item);
1535
+ const record = await store.create(input);
1536
+ created.push(publicProxy(record));
1537
+ } catch (error) {
1538
+ errors.push({
1539
+ name: item.name,
1540
+ reason: error instanceof ProxyInputError ? error.code : "create_failed",
1541
+ });
1542
+ }
1543
+ }
1544
+ json(res, 200, {
1545
+ created,
1546
+ skipped: parsed.duplicates,
1547
+ errors,
1548
+ truncated: parsed.truncated > 0,
1549
+ });
1550
+ return;
1551
+ }
1552
+
1439
1553
  const route = proxyIdFromPath(url.pathname);
1440
1554
  if (route) {
1441
1555
  const existing = await store.get(route.id);
@@ -1447,7 +1561,7 @@ export async function startServer({
1447
1561
  const candidate = body && Object.keys(body).length
1448
1562
  ? validateProbe(body, existing)
1449
1563
  : { ...existing };
1450
- const expectedUpdatedAt = existing.updatedAt;
1564
+ const expectedUpdatedAt = existing.connectionUpdatedAt || existing.updatedAt;
1451
1565
  const result = await runProxyTest(
1452
1566
  candidate,
1453
1567
  body && typeof body.provider === "string" ? body.provider : "",
@@ -1476,7 +1590,7 @@ export async function startServer({
1476
1590
  id: existing.id,
1477
1591
  name: existing.name,
1478
1592
  proxy: existing,
1479
- expectedUpdatedAt: existing.updatedAt,
1593
+ expectedUpdatedAt: existing.connectionUpdatedAt || existing.updatedAt,
1480
1594
  });
1481
1595
  json(res, 202, { ok: true, job });
1482
1596
  return;
@@ -1490,6 +1604,16 @@ export async function startServer({
1490
1604
  const changes = validateUpdate(await readJson(req));
1491
1605
  const updated = await store.update(route.id, changes);
1492
1606
  if (!updated) throw new HttpError(404, "not_found", "Proxy not found.");
1607
+ const connectionChanged =
1608
+ proxyConnectionKey(existing) !== proxyConnectionKey(updated) ||
1609
+ (existing.password || "") !== (updated.password || "");
1610
+ if (connectionChanged && typeof accountProxySync.syncProxyUpdate === "function") {
1611
+ try {
1612
+ await accountProxySync.syncProxyUpdate(updated);
1613
+ } catch {
1614
+ // Best effort sync of bound accounts in providers.json.
1615
+ }
1616
+ }
1493
1617
  json(res, 200, { proxy: publicProxy(updated) });
1494
1618
  return;
1495
1619
  }
@@ -1879,6 +2003,23 @@ export async function startServer({
1879
2003
  throw new HttpError(409, "signed_in", "This account is still signed in; sign out first.");
1880
2004
  }
1881
2005
  await removeAccountDir(dir);
2006
+ try {
2007
+ if (typeof renewHosting.removeAccount === "function") {
2008
+ await renewHosting.removeAccount(accountTarget.provider, accountTarget.key);
2009
+ }
2010
+ } catch {
2011
+ // Best effort removal of the deleted account's hosting policy.
2012
+ }
2013
+ try {
2014
+ if (typeof accountProxySync.clearAccountProxy === "function") {
2015
+ await accountProxySync.clearAccountProxy({
2016
+ provider: accountTarget.provider,
2017
+ accountId: meta?.accountId ?? null,
2018
+ });
2019
+ }
2020
+ } catch {
2021
+ // Best effort cleanup of providers.json.
2022
+ }
1882
2023
  json(res, 200, { ok: true });
1883
2024
  return;
1884
2025
  }
@@ -2090,15 +2231,20 @@ export async function startServer({
2090
2231
  "cache-control": "no-store",
2091
2232
  "x-content-type-options": "nosniff",
2092
2233
  "referrer-policy": "no-referrer",
2093
- // Same-origin assets and API calls only; connect-src "'self'"
2094
- // already covers the relative /api/* fetches the page makes. No
2095
- // frame-ancestors: the launcher's sandboxed document is an opaque
2096
- // origin and matches no ancestor source, so any list would block
2097
- // magpie itself. Embedding is gated by the Sec-Fetch stub above
2098
- // and the document's own embed gate instead.
2234
+ // magpie mounts this UI in `<iframe sandbox="allow-scripts">` (opaque
2235
+ // origin `null`). Apple WKWebView/Safari evaluates CSP `connect-src 'self'`
2236
+ // against that opaque origin and blocks relative `/api/*` fetches (both
2237
+ // desktop `wails://wails` loopback and `magpie web` reverse-proxy hosts),
2238
+ // so pair `'self'` with `http: https:`. `default-src 'self'`,
2239
+ // `object-src 'none'`, `base-uri 'none'`, and `form-action 'none'` stay
2240
+ // strict, and non-HTTP schemes (`ws:`, `data:`, `blob:`, `file:`) remain
2241
+ // blocked. No frame-ancestors: the launcher's sandboxed document is an
2242
+ // opaque origin and matches no ancestor source, so any list would block
2243
+ // magpie itself. Embedding is gated by the Sec-Fetch stub above and the
2244
+ // document's own embed gate instead.
2099
2245
  "content-security-policy":
2100
2246
  "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; " +
2101
- "connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; " +
2247
+ "connect-src 'self' http: https:; font-src 'self'; object-src 'none'; base-uri 'none'; " +
2102
2248
  "form-action 'none'",
2103
2249
  });
2104
2250
  res.end(req.method === "HEAD" ? undefined : html);
@@ -51,9 +51,10 @@ export function signInProxyUrl(proxy) {
51
51
  if (typeof proxy !== "object") return undefined;
52
52
  const type = typeof proxy.type === "string" ? proxy.type.toLowerCase() : "http";
53
53
  if (type === "socks5" || type === "socks4" || type === "socks") return undefined;
54
- const host = typeof proxy.host === "string" ? proxy.host.trim() : "";
54
+ const rawHost = typeof proxy.host === "string" ? proxy.host.trim() : "";
55
55
  const port = Number(proxy.port);
56
- if (!host || !Number.isInteger(port) || port <= 0 || port > 65535) return undefined;
56
+ if (!rawHost || !Number.isInteger(port) || port <= 0 || port > 65535) return undefined;
57
+ const host = rawHost.includes(":") && !rawHost.startsWith("[") ? `[${rawHost}]` : rawHost;
57
58
  const scheme = type === "https" ? "https" : "http";
58
59
  const user = typeof proxy.username === "string" ? proxy.username : "";
59
60
  const password = typeof proxy.password === "string" ? proxy.password : "";
@@ -21,7 +21,7 @@ import { isAbsolute, join, relative } from "node:path";
21
21
  import { pathToFileURL } from "node:url";
22
22
  import { readAuthKeys } from "./account-keys.mjs";
23
23
  import { readAuthEntries, signInKey, writeBack } from "./signin-writeback.mjs";
24
- import { withSignInEgress } from "./signin-egress.mjs";
24
+ import { signInProxyUrl, withSignInEgress } from "./signin-egress.mjs";
25
25
  import { LOCAL_HINT, classifyMethod, pluginRootDir, requiresFormInput, requiresSecretInput } from "./magpie-plugins.mjs";
26
26
  import {
27
27
  SIGNIN_FLOW_MARKER,
@@ -393,12 +393,25 @@ function publicFlow(flow) {
393
393
  createdAt: flow.createdAt,
394
394
  finishedAt: flow.finishedAt,
395
395
  error: flow.error ? { ...flow.error } : null,
396
+ // Non-fatal compatibility note when the picked browser proxy cannot carry
397
+ // the provider plugin's direct HTTP requests (e.g. SOCKS5 in Bun fetch).
398
+ egressWarning: flow.egressWarning ? { ...flow.egressWarning } : null,
396
399
  // Summaries of post-login actions (exit sync and magpie provider registration).
397
400
  // Safe fields only: no exit URL, no credential, no stack trace.
398
401
  proxySync: flow.proxySync ? { ...flow.proxySync } : null,
399
402
  };
400
403
  }
401
404
 
405
+ function isHttpUrl(value) {
406
+ if (typeof value !== "string" || !value.trim()) return false;
407
+ try {
408
+ const { protocol } = new URL(value);
409
+ return protocol === "http:" || protocol === "https:";
410
+ } catch {
411
+ return false;
412
+ }
413
+ }
414
+
402
415
  // A hosted renewal runs with nobody at the keyboard. If the vendor still asks
403
416
  // for a login, waiting the full interactive six minutes only burns the exit and
404
417
  // the account's goodwill, so a silent flow gives up much sooner. It stays well
@@ -515,7 +528,9 @@ export function createSignInFlow(options = {}) {
515
528
  current.codeRequired = false;
516
529
  current.error = { code: "code_timeout", message: "No code was submitted in time." };
517
530
  current.finishedAt = now();
518
- clearInFlight(current).finally(() => current.resolveSettled());
531
+ safeClose(current.browser).finally(() =>
532
+ clearInFlight(current).finally(() => current.resolveSettled()),
533
+ );
519
534
  }, current.silent ? silentCallbackTimeoutMs : callbackTimeoutMs);
520
535
  current.codeTimer.unref?.();
521
536
  }
@@ -634,12 +649,23 @@ export function createSignInFlow(options = {}) {
634
649
  if (existingMeta && typeof existingMeta.note === "string") {
635
650
  carried.note = existingMeta.note;
636
651
  }
637
- if (existingMeta && Array.isArray(existingMeta.checks)) {
652
+ if (!current.pinRotated && existingMeta && Array.isArray(existingMeta.checks)) {
638
653
  carried.checks = existingMeta.checks;
639
654
  }
640
655
  if (existingMeta && Array.isArray(existingMeta.loginHistory)) {
641
656
  carried.loginHistory = existingMeta.loginHistory;
642
657
  }
658
+ const resultEmail =
659
+ typeof result?.email === "string" && result.email
660
+ ? result.email
661
+ : typeof result?.metadata?.email === "string" && result.metadata.email
662
+ ? result.metadata.email
663
+ : null;
664
+ const accountEmail =
665
+ resultEmail ??
666
+ (typeof existingMeta?.email === "string" && existingMeta.email
667
+ ? existingMeta.email
668
+ : null);
643
669
  await writeAccountMeta(
644
670
  current.dir,
645
671
  withLogin(
@@ -649,6 +675,7 @@ export function createSignInFlow(options = {}) {
649
675
  key: written.key,
650
676
  accountId: written.entry?.accountId ?? null,
651
677
  uid: written.entry?.uid ?? null,
678
+ ...(accountEmail ? { email: accountEmail } : {}),
652
679
  signedInAt: signedAt,
653
680
  // The method this account signed in through. A multi-method
654
681
  // provider needs it at renewal time to replay the same one
@@ -871,6 +898,14 @@ export function createSignInFlow(options = {}) {
871
898
  pid: null,
872
899
  error: null,
873
900
  warning: null,
901
+ egressWarning:
902
+ proxy && signInProxyUrl(proxy) === undefined
903
+ ? {
904
+ code: "proxy_not_supported_for_plugin",
905
+ message:
906
+ "The selected proxy routes the login browser, while the provider plugin's own HTTP requests cannot use SOCKS proxies.",
907
+ }
908
+ : null,
874
909
  createdAt: now(),
875
910
  finishedAt: null,
876
911
  browser: null,
@@ -897,42 +932,42 @@ export function createSignInFlow(options = {}) {
897
932
  // The set the allocation used is the one the write-back must use too, so
898
933
  // the two cannot disagree about which keys are taken.
899
934
  current.takenKeys = allocationKeys;
900
- // (b) One account directory, one persistent pin.
935
+ // (b) One account directory, one persistent pin. Drawing / rotating the
936
+ // fingerprint (which removes the old profile on rotation) is deferred
937
+ // until plugin loading, method inputs, authorize() and executable
938
+ // resolution have all succeeded, so a failed preflight never destroys an
939
+ // existing profile.
901
940
  const dir = accountDir(env, provider, key);
902
- // A rotation redraws the pin in the directory the account already owns,
903
- // and takes its profile with it. Doing it here -- on the claimed key,
904
- // before any provisional directory exists -- is what keeps it out of
905
- // `reconcile`'s way: the write-back lands on the same key it started on,
906
- // so there is no move to make and no fresh pin to throw away.
907
- let identity;
908
- if (rotatePin) {
909
- try {
910
- ({ identity } = await rotateAccountIdentity(
941
+ let identityReady = false;
942
+ let identity = null;
943
+ const prepareIdentity = async () => {
944
+ if (identityReady) return identity;
945
+ if (rotatePin) {
946
+ try {
947
+ ({ identity } = await rotateAccountIdentity(
948
+ dir,
949
+ identityGenerator ? { generate: identityGenerator } : {},
950
+ ));
951
+ } catch (error) {
952
+ throw new SignInFlowError(
953
+ "rotate_failed",
954
+ `The account's fingerprint could not be renewed: ${String(error?.message ?? error)}`,
955
+ 500,
956
+ );
957
+ }
958
+ current.pinRotated = true;
959
+ current.identityCreated = true;
960
+ } else {
961
+ const ensured = await ensureAccountIdentity(
911
962
  dir,
912
963
  identityGenerator ? { generate: identityGenerator } : {},
913
- ));
914
- } catch (error) {
915
- throw new SignInFlowError(
916
- "rotate_failed",
917
- `The account's fingerprint could not be renewed: ${String(error?.message ?? error)}`,
918
- 500,
919
964
  );
965
+ identity = ensured.identity;
966
+ current.identityCreated = ensured.created;
920
967
  }
921
- current.pinRotated = true;
922
- current.identityCreated = true;
923
- } else {
924
- const ensured = await ensureAccountIdentity(
925
- dir,
926
- identityGenerator ? { generate: identityGenerator } : {},
927
- );
928
- identity = ensured.identity;
929
- current.identityCreated = ensured.created;
930
- }
931
- current.dir = dir;
932
- // The directory now exists but carries no credential. Mark it as in
933
- // flight before the browser opens so a concurrent/next-startup orphan
934
- // sweep does not mistake it for an abandoned one.
935
- await markInFlight(current);
968
+ identityReady = true;
969
+ return identity;
970
+ };
936
971
  throwIfCancelled(current);
937
972
 
938
973
  // (c) Import the provider plugin and ask its browser method for the URL
@@ -966,6 +1001,10 @@ export function createSignInFlow(options = {}) {
966
1001
  if (!answers.ok) {
967
1002
  throw new SignInFlowError(answers.code, answers.message, 400);
968
1003
  }
1004
+ await mkdir(dir, { recursive: true });
1005
+ current.dir = dir;
1006
+ await markInFlight(current);
1007
+ throwIfCancelled(current);
969
1008
  // A method that declares no prompts is called the way it always was, with
970
1009
  // no arguments: an empty object would look like the page sent answers.
971
1010
  // The plugin mints the link, sends the SMS and exchanges the code from
@@ -1022,9 +1061,8 @@ export function createSignInFlow(options = {}) {
1022
1061
  current.instructions = typeof auth.instructions === "string" ? auth.instructions : "";
1023
1062
 
1024
1063
  // A plugin with `method: "code"` (for example Loomy's SMS code flow)
1025
- // returns no URL because there is no page to open: it sent a code to the
1026
- // destination the user typed and asks for that code back. It waits in
1027
- // `waiting-code` until `submitCode()` hands the code to `callback(input)`.
1064
+ // either returns no URL (SMS/email OTP) or returns an interactive page URL
1065
+ // alongside a one-time code entry (when `!current.silent` and HTTP/HTTPS).
1028
1066
  const isCodeMethod = auth?.method === "code";
1029
1067
  if (isCodeMethod && current.silent) {
1030
1068
  throw new SignInFlowError(
@@ -1036,6 +1074,33 @@ export function createSignInFlow(options = {}) {
1036
1074
  if (isCodeMethod) {
1037
1075
  current.codeRequired = true;
1038
1076
  current.url = typeof auth.url === "string" ? auth.url : "";
1077
+ if (isHttpUrl(current.url)) {
1078
+ const executablePath = await resolveExecutable({ env, environment });
1079
+ if (!executablePath) {
1080
+ throw new SignInFlowError(
1081
+ "browser_missing",
1082
+ "The login browser is not installed; prepare it on the Providers page first.",
1083
+ 503,
1084
+ );
1085
+ }
1086
+ await prepareIdentity();
1087
+ current.browser = await launchBrowser({
1088
+ executablePath,
1089
+ url: current.url,
1090
+ profileDir: accountProfileDir(dir),
1091
+ identity,
1092
+ proxy,
1093
+ ...(navTimeoutMs ? { navTimeoutMs } : {}),
1094
+ });
1095
+ current.pid = current.browser?.pid ?? null;
1096
+ current.warning = navigationWarning(current.browser?.warning);
1097
+ if (current.cancelled) {
1098
+ await safeClose(current.browser);
1099
+ throw new SignInFlowError("cancelled", "The sign-in was cancelled.", 409);
1100
+ }
1101
+ } else {
1102
+ await prepareIdentity();
1103
+ }
1039
1104
  current.state = "waiting-code";
1040
1105
  throwIfCancelled(current);
1041
1106
  armCodeTimeout(current);
@@ -1056,6 +1121,7 @@ export function createSignInFlow(options = {}) {
1056
1121
  // callback straight away instead: it either reports the credential or
1057
1122
  // fails honestly with `callback_failed`.
1058
1123
  if (authorized.category === "local") {
1124
+ await prepareIdentity();
1059
1125
  current.url = "";
1060
1126
  current.state = "waiting-login";
1061
1127
  throwIfCancelled(current);
@@ -1084,6 +1150,7 @@ export function createSignInFlow(options = {}) {
1084
1150
  503,
1085
1151
  );
1086
1152
  }
1153
+ await prepareIdentity();
1087
1154
  current.browser = await launchBrowser({
1088
1155
  executablePath,
1089
1156
  url: auth.url,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gruu6y/page-clean-login",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "在 magpie 中管理代理 IP 与供应商登录,每个账号通过独立浏览器身份登录;一个带仅回环主机服务的页面插件。",
5
5
  "license": "MIT",
6
6
  "publishConfig": {