@gruu6y/page-clean-login 0.2.9 → 0.2.11

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.
@@ -0,0 +1,604 @@
1
+ // Unified effective-exit resolution for clean-login, using magpie's
2
+ // `providers.json` as the single source of truth (SSOT).
3
+ //
4
+ // Shared by the accounts list, the account detail exit dialog, hosted renewal,
5
+ // agent/CLI output, and downstream features (such as opening a provider
6
+ // account's fingerprint browser) so every consumer resolves the exact same
7
+ // network exit and obeys the same credential boundary.
8
+ //
9
+ // Boundary note: clean-login only reads `<MAGPIE_CONFIG_DIR>/providers.json`
10
+ // (not magpie's other global proxy configuration files). When an account is in
11
+ // `inherit` mode and the provider's own `proxy` field is empty or `"direct"`,
12
+ // the effective exit resolves as `"direct"`.
13
+
14
+ import {
15
+ accountProxyKey,
16
+ canonicalProxyUrl,
17
+ exitDisplayUrl,
18
+ extractAccountExitFromDoc,
19
+ parseProxyUrl,
20
+ providersFile,
21
+ proxyUrlFor,
22
+ readAccountExit,
23
+ readProvidersSnapshot,
24
+ } from "./account-proxies.mjs";
25
+ import { readAuthEntries } from "./signin-writeback.mjs";
26
+ import { readNativeLoginsResult } from "./magpie-logins.mjs";
27
+
28
+ export {
29
+ accountProxyKey,
30
+ canonicalProxyUrl,
31
+ exitDisplayUrl,
32
+ parseProxyUrl,
33
+ proxyUrlFor,
34
+ readProvidersSnapshot,
35
+ };
36
+
37
+ // Derives the account name that magpie keys `providers[].accountProxies` by.
38
+ // Preference order matches clean-login's ledger and magpie's auth stores:
39
+ // 1. `meta.accountId`
40
+ // 2. `authEntries[key].accountId`
41
+ // 3. `authEntries[key].email`
42
+ // 4. `nativeEntries.find(e => e.key === key).email`
43
+ // Returns `""` when no name is known so callers receive `account_name_unknown`.
44
+ export function resolveAccountProxyName({
45
+ meta = null,
46
+ key = "",
47
+ authEntries,
48
+ nativeEntries,
49
+ env = process.env,
50
+ } = {}) {
51
+ const fromMeta = typeof meta?.accountId === "string" ? meta.accountId.trim() : "";
52
+ if (fromMeta) return fromMeta;
53
+ const k = typeof key === "string" ? key : "";
54
+ if (!k) return "";
55
+ const auth = authEntries !== undefined ? authEntries : readAuthEntries(env);
56
+ const authEntry = auth && typeof auth === "object" ? auth[k] : null;
57
+ const fromAuthId = typeof authEntry?.accountId === "string" ? authEntry.accountId.trim() : "";
58
+ if (fromAuthId) return fromAuthId;
59
+ const fromAuthEmail = typeof authEntry?.email === "string" ? authEntry.email.trim() : "";
60
+ if (fromAuthEmail) return fromAuthEmail;
61
+ const native =
62
+ nativeEntries !== undefined
63
+ ? nativeEntries
64
+ : (readNativeLoginsResult(env)?.entries ?? []);
65
+ if (Array.isArray(native)) {
66
+ const match = native.find((entry) => entry?.key === k);
67
+ const fromNative = typeof match?.email === "string" ? match.email.trim() : "";
68
+ if (fromNative) return fromNative;
69
+ }
70
+ return "";
71
+ }
72
+
73
+ // Builds a URL -> stored proxy record lookup map once for batch resolution,
74
+ // indexing both the exact URL emitted by `proxyUrlFor()` and its canonical form
75
+ // (e.g. default port / percent-encoding normalization). Safe when `store` only
76
+ // implements `get()` (e.g. minimal unit-test fakes without `list()`).
77
+ export async function buildProxyUrlMap(store) {
78
+ const map = new Map();
79
+ if (!store || typeof store.list !== "function" || typeof store.get !== "function") {
80
+ return map;
81
+ }
82
+ let items;
83
+ try {
84
+ items = await store.list();
85
+ } catch {
86
+ return map;
87
+ }
88
+ for (const item of Array.isArray(items) ? items : []) {
89
+ if (!item?.id) continue;
90
+ let record = null;
91
+ try {
92
+ record = await store.get(item.id);
93
+ } catch {
94
+ record = null;
95
+ }
96
+ const raw = proxyUrlFor(record);
97
+ if (!raw) continue;
98
+ if (!map.has(raw)) map.set(raw, record);
99
+ const canonical = canonicalProxyUrl(raw);
100
+ if (canonical && !map.has(canonical)) map.set(canonical, record);
101
+ }
102
+ return map;
103
+ }
104
+
105
+ export function lookupProxyByUrl(proxyByUrl, rawUrl) {
106
+ if (!proxyByUrl || typeof rawUrl !== "string") return null;
107
+ const trimmed = rawUrl.trim();
108
+ if (!trimmed) return null;
109
+ if (proxyByUrl.has(trimmed)) return proxyByUrl.get(trimmed);
110
+ const canonical = canonicalProxyUrl(trimmed);
111
+ if (canonical && proxyByUrl.has(canonical)) return proxyByUrl.get(canonical);
112
+ return null;
113
+ }
114
+
115
+ // Pure credential-free public projection of a `resolveEffectiveAccountExit()`
116
+ // result. Safe to serialize in HTTP responses, CLI output, UI state, and logs:
117
+ // never contains `proxy`, `username`, `password`, raw URLs, or OS error paths.
118
+ export function publicAccountExit(resolved) {
119
+ if (!resolved || typeof resolved !== "object") {
120
+ return {
121
+ ok: false,
122
+ reason: "exit_unknown",
123
+ mode: null,
124
+ accountKey: null,
125
+ providerProxy: null,
126
+ };
127
+ }
128
+ if (!resolved.ok) {
129
+ return {
130
+ ok: false,
131
+ reason: resolved.reason ?? "exit_unknown",
132
+ mode: resolved.mode ?? null,
133
+ accountKey: resolved.accountKey ?? null,
134
+ providerProxy: exitDisplayUrl(resolved.providerProxy),
135
+ };
136
+ }
137
+ return {
138
+ ok: true,
139
+ mode: resolved.mode ?? null,
140
+ effectiveMode: resolved.effectiveMode ?? null,
141
+ source: resolved.source ?? null,
142
+ accountKey: resolved.accountKey ?? null,
143
+ matchedStore: Boolean(resolved.matchedStore),
144
+ proxyId: resolved.proxyId ?? null,
145
+ proxyName: resolved.proxyName ?? "",
146
+ region: resolved.region ?? "",
147
+ type: resolved.type ?? null,
148
+ displayUrl: exitDisplayUrl(resolved.displayUrl),
149
+ providerProxy: exitDisplayUrl(resolved.providerProxy),
150
+ };
151
+ }
152
+
153
+ function attachPublic(result) {
154
+ return { ...result, public: publicAccountExit(result) };
155
+ }
156
+
157
+ function ledgerExitSnapshot(meta) {
158
+ if (meta?.exit && typeof meta.exit === "object") {
159
+ return { ledger: meta.exit, source: "ledger_exit" };
160
+ }
161
+ if (meta?.lastLogin && typeof meta.lastLogin === "object") {
162
+ return { ledger: meta.lastLogin, source: "ledger_last_login" };
163
+ }
164
+ return { ledger: null, source: null };
165
+ }
166
+
167
+ // Resolves the effective network exit for one account.
168
+ //
169
+ // Returns an internal runtime result containing:
170
+ // - `ok`: boolean
171
+ // - `mode`: `"custom" | "direct" | "inherit" | null`
172
+ // - `effectiveMode`: `"proxy" | "direct" | null`
173
+ // - `source`: `"providers_account" | "providers_provider" | "providers_direct" | "ledger_exit" | "ledger_last_login" | "providers_error" | null`
174
+ // - `accountKey`: lower-cased magpie accountProxies key (or `""`)
175
+ // - `matchedStore`: whether the effective proxy matched a stored node in `proxies.json`
176
+ // - `proxy`: full runtime proxy object (stored node record or `parseProxyUrl()` output) when `effectiveMode === "proxy"`, else `null`
177
+ // - `proxyMeta`: credential-free `{ id, name, region, type }` for `signin-flow` / ledger writes, else `null`
178
+ // - `proxyId`, `proxyName`, `region`, `type`, `displayUrl`, `providerProxy`
179
+ // - `reason`: error code when `ok === false` (`"providers_invalid"`, `"providers_unreadable"`, `"invalid_exit_url"`, `"exit_missing"`, `"exit_unknown"`, or providers read reason when `fallbackToLedger === false`)
180
+ // - `public`: strictly credential-free projection from `publicAccountExit()`
181
+ export async function resolveEffectiveAccountExit({
182
+ env = process.env,
183
+ provider,
184
+ key = "",
185
+ meta = null,
186
+ store = null,
187
+ authEntries,
188
+ nativeEntries,
189
+ proxyByUrl = null,
190
+ providersDoc = null,
191
+ file = providersFile(env),
192
+ fallbackToLedger = true,
193
+ } = {}) {
194
+ const accountId = resolveAccountProxyName({ meta, key, authEntries, nativeEntries, env });
195
+ const accountKey = accountProxyKey(accountId);
196
+ const read =
197
+ providersDoc !== null && providersDoc !== undefined
198
+ ? extractAccountExitFromDoc(providersDoc, provider, accountId)
199
+ : await readAccountExit({ env, provider, accountId, file });
200
+
201
+ let urlMap = proxyByUrl;
202
+ async function ensureUrlMap() {
203
+ if (!urlMap) {
204
+ urlMap = await buildProxyUrlMap(store);
205
+ }
206
+ return urlMap;
207
+ }
208
+
209
+ async function resolveProxyUrl(rawUrl, { mode, source, providerProxy }) {
210
+ const safeProviderProxy = exitDisplayUrl(providerProxy);
211
+ const matched = lookupProxyByUrl(await ensureUrlMap(), rawUrl);
212
+ if (matched) {
213
+ const type = String(matched.type ?? "http").toLowerCase();
214
+ const displayUrl = exitDisplayUrl(rawUrl) ?? exitDisplayUrl(proxyUrlFor(matched));
215
+ return attachPublic({
216
+ ok: true,
217
+ mode,
218
+ effectiveMode: "proxy",
219
+ source,
220
+ accountKey: read.key ?? accountKey,
221
+ matchedStore: true,
222
+ proxy: matched,
223
+ proxyId: matched.id,
224
+ proxyName: matched.name ?? "",
225
+ region: matched.region ?? "",
226
+ type,
227
+ displayUrl,
228
+ providerProxy: safeProviderProxy,
229
+ proxyMeta: {
230
+ id: matched.id,
231
+ name: matched.name ?? "",
232
+ region: matched.region ?? "",
233
+ type,
234
+ },
235
+ reason: null,
236
+ });
237
+ }
238
+
239
+ const parsed = parseProxyUrl(rawUrl);
240
+ if (!parsed) {
241
+ return attachPublic({
242
+ ok: false,
243
+ mode,
244
+ effectiveMode: null,
245
+ source,
246
+ accountKey: read.key ?? accountKey,
247
+ matchedStore: false,
248
+ proxy: null,
249
+ proxyId: null,
250
+ proxyName: "",
251
+ region: "",
252
+ type: null,
253
+ displayUrl: null,
254
+ providerProxy: safeProviderProxy,
255
+ proxyMeta: null,
256
+ reason: "invalid_exit_url",
257
+ });
258
+ }
259
+
260
+ const displayUrl = exitDisplayUrl(rawUrl) ?? parsed.server;
261
+ return attachPublic({
262
+ ok: true,
263
+ mode,
264
+ effectiveMode: "proxy",
265
+ source,
266
+ accountKey: read.key ?? accountKey,
267
+ matchedStore: false,
268
+ proxy: parsed,
269
+ proxyId: null,
270
+ proxyName: "",
271
+ region: "",
272
+ type: parsed.type,
273
+ displayUrl,
274
+ providerProxy: safeProviderProxy,
275
+ proxyMeta: {
276
+ id: null,
277
+ name: "",
278
+ region: "",
279
+ type: parsed.type,
280
+ },
281
+ reason: null,
282
+ });
283
+ }
284
+
285
+ if (read.ok) {
286
+ const safeProviderProxy = exitDisplayUrl(read.providerProxy);
287
+ if (read.mode === "custom") {
288
+ return resolveProxyUrl(read.url, {
289
+ mode: "custom",
290
+ source: "providers_account",
291
+ providerProxy: read.providerProxy,
292
+ });
293
+ }
294
+ if (read.mode === "direct") {
295
+ return attachPublic({
296
+ ok: true,
297
+ mode: "direct",
298
+ effectiveMode: "direct",
299
+ source: "providers_direct",
300
+ accountKey: read.key,
301
+ matchedStore: false,
302
+ proxy: null,
303
+ proxyId: null,
304
+ proxyName: "",
305
+ region: "",
306
+ type: null,
307
+ displayUrl: null,
308
+ providerProxy: safeProviderProxy,
309
+ proxyMeta: null,
310
+ reason: null,
311
+ });
312
+ }
313
+ // `mode === "inherit"`: follow provider-level proxy if configured.
314
+ const providerRaw = typeof read.providerProxy === "string" ? read.providerProxy.trim() : "";
315
+ if (providerRaw && providerRaw !== "direct") {
316
+ return resolveProxyUrl(providerRaw, {
317
+ mode: "inherit",
318
+ source: "providers_provider",
319
+ providerProxy: read.providerProxy,
320
+ });
321
+ }
322
+ return attachPublic({
323
+ ok: true,
324
+ mode: "inherit",
325
+ effectiveMode: "direct",
326
+ source: "providers_provider",
327
+ accountKey: read.key,
328
+ matchedStore: false,
329
+ proxy: null,
330
+ proxyId: null,
331
+ proxyName: "",
332
+ region: "",
333
+ type: null,
334
+ displayUrl: null,
335
+ providerProxy: safeProviderProxy,
336
+ proxyMeta: null,
337
+ reason: null,
338
+ });
339
+ }
340
+
341
+ // Corrupt or unreadable providers.json must fail explicitly and never degrade
342
+ // to direct or silently trust stale ledger state.
343
+ if (read.reason === "providers_invalid" || read.reason === "providers_unreadable") {
344
+ return attachPublic({
345
+ ok: false,
346
+ mode: null,
347
+ effectiveMode: null,
348
+ source: "providers_error",
349
+ accountKey: read.key ?? accountKey,
350
+ matchedStore: false,
351
+ proxy: null,
352
+ proxyId: null,
353
+ proxyName: "",
354
+ region: "",
355
+ type: null,
356
+ displayUrl: null,
357
+ providerProxy: null,
358
+ proxyMeta: null,
359
+ reason: read.reason,
360
+ });
361
+ }
362
+
363
+ if (!fallbackToLedger) {
364
+ return attachPublic({
365
+ ok: false,
366
+ mode: null,
367
+ effectiveMode: null,
368
+ source: null,
369
+ accountKey: read.key ?? accountKey,
370
+ matchedStore: false,
371
+ proxy: null,
372
+ proxyId: null,
373
+ proxyName: "",
374
+ region: "",
375
+ type: null,
376
+ displayUrl: null,
377
+ providerProxy: null,
378
+ proxyMeta: null,
379
+ reason: read.reason ?? "exit_unknown",
380
+ });
381
+ }
382
+
383
+ // Fallback to account ledger only when providers.json is missing, lacks this
384
+ // provider, or the account name is unknown.
385
+ const { ledger, source } = ledgerExitSnapshot(meta);
386
+ if (!ledger) {
387
+ return attachPublic({
388
+ ok: false,
389
+ mode: null,
390
+ effectiveMode: null,
391
+ source: null,
392
+ accountKey: read.key ?? accountKey,
393
+ matchedStore: false,
394
+ proxy: null,
395
+ proxyId: null,
396
+ proxyName: "",
397
+ region: "",
398
+ type: null,
399
+ displayUrl: null,
400
+ providerProxy: null,
401
+ proxyMeta: null,
402
+ reason: "exit_unknown",
403
+ });
404
+ }
405
+ if (ledger.proxyId === null) {
406
+ return attachPublic({
407
+ ok: true,
408
+ mode: "direct",
409
+ effectiveMode: "direct",
410
+ source,
411
+ accountKey: read.key ?? accountKey,
412
+ matchedStore: false,
413
+ proxy: null,
414
+ proxyId: null,
415
+ proxyName: "",
416
+ region: "",
417
+ type: null,
418
+ displayUrl: null,
419
+ providerProxy: null,
420
+ proxyMeta: null,
421
+ reason: null,
422
+ });
423
+ }
424
+ if (typeof ledger.proxyId === "string" && ledger.proxyId) {
425
+ let stored = null;
426
+ try {
427
+ stored = await store?.get?.(ledger.proxyId);
428
+ } catch {
429
+ stored = null;
430
+ }
431
+ if (!stored) {
432
+ return attachPublic({
433
+ ok: false,
434
+ mode: "custom",
435
+ effectiveMode: null,
436
+ source,
437
+ accountKey: read.key ?? accountKey,
438
+ matchedStore: false,
439
+ proxy: null,
440
+ proxyId: ledger.proxyId,
441
+ proxyName: "",
442
+ region: "",
443
+ type: null,
444
+ displayUrl: null,
445
+ providerProxy: null,
446
+ proxyMeta: null,
447
+ reason: "exit_missing",
448
+ });
449
+ }
450
+ const type = String(stored.type ?? "http").toLowerCase();
451
+ const displayUrl = exitDisplayUrl(proxyUrlFor(stored));
452
+ return attachPublic({
453
+ ok: true,
454
+ mode: "custom",
455
+ effectiveMode: "proxy",
456
+ source,
457
+ accountKey: read.key ?? accountKey,
458
+ matchedStore: true,
459
+ proxy: stored,
460
+ proxyId: stored.id,
461
+ proxyName: stored.name ?? "",
462
+ region: stored.region ?? "",
463
+ type,
464
+ displayUrl,
465
+ providerProxy: null,
466
+ proxyMeta: {
467
+ id: stored.id,
468
+ name: stored.name ?? "",
469
+ region: stored.region ?? "",
470
+ type,
471
+ },
472
+ reason: null,
473
+ });
474
+ }
475
+
476
+ return attachPublic({
477
+ ok: false,
478
+ mode: null,
479
+ effectiveMode: null,
480
+ source: null,
481
+ accountKey: read.key ?? accountKey,
482
+ matchedStore: false,
483
+ proxy: null,
484
+ proxyId: null,
485
+ proxyName: "",
486
+ region: "",
487
+ type: null,
488
+ displayUrl: null,
489
+ providerProxy: null,
490
+ proxyMeta: null,
491
+ reason: "exit_unknown",
492
+ });
493
+ }
494
+
495
+ // Projects a `resolveEffectiveAccountExit()` result into the credential-free
496
+ // `account.exit` view shape used by `GET /api/accounts`, `PATCH /exit`,
497
+ // `PATCH /accounts/:provider/:key`, and `GET /api/agent`.
498
+ //
499
+ // Returns `undefined` when providers.json could not authoritatively resolve the
500
+ // account (missing file / provider / account name / corrupt file), so callers
501
+ // keep any existing ledger `extras.exit` unchanged.
502
+ export function accountExitProjection(resolved, ledgerExit = null) {
503
+ if (!resolved || typeof resolved !== "object") return undefined;
504
+
505
+ if (!resolved.ok) {
506
+ if (resolved.reason === "invalid_exit_url") {
507
+ return {
508
+ at: null,
509
+ proxyId: null,
510
+ proxyName: "",
511
+ region: "",
512
+ type: null,
513
+ ...(resolved.mode === "inherit" ? { mode: "inherit" } : {}),
514
+ custom: true,
515
+ displayUrl: null,
516
+ };
517
+ }
518
+ return undefined;
519
+ }
520
+
521
+ const fromProviders =
522
+ resolved.source === "providers_account" ||
523
+ resolved.source === "providers_provider" ||
524
+ resolved.source === "providers_direct";
525
+ if (!fromProviders) return undefined;
526
+
527
+ if (resolved.mode === "custom") {
528
+ if (resolved.matchedStore) {
529
+ const sameNode =
530
+ ledgerExit &&
531
+ typeof ledgerExit === "object" &&
532
+ ledgerExit.proxyId === resolved.proxyId;
533
+ return {
534
+ at: sameNode ? (ledgerExit.at ?? null) : null,
535
+ proxyId: resolved.proxyId,
536
+ proxyName: resolved.proxyName ?? "",
537
+ region: resolved.region ?? "",
538
+ type: resolved.type ?? null,
539
+ };
540
+ }
541
+ return {
542
+ at: null,
543
+ proxyId: null,
544
+ proxyName: "",
545
+ region: "",
546
+ type: resolved.type ?? null,
547
+ custom: true,
548
+ displayUrl: exitDisplayUrl(resolved.displayUrl),
549
+ };
550
+ }
551
+
552
+ if (resolved.mode === "direct") {
553
+ const ledgerWasDirect =
554
+ ledgerExit &&
555
+ typeof ledgerExit === "object" &&
556
+ ledgerExit.proxyId === null &&
557
+ !ledgerExit.custom &&
558
+ ledgerExit.mode !== "inherit";
559
+ return {
560
+ at: ledgerWasDirect ? (ledgerExit.at ?? null) : null,
561
+ proxyId: null,
562
+ proxyName: "",
563
+ region: "",
564
+ type: null,
565
+ };
566
+ }
567
+
568
+ if (resolved.mode === "inherit") {
569
+ if (resolved.effectiveMode === "proxy") {
570
+ const displayUrl = exitDisplayUrl(resolved.displayUrl ?? resolved.providerProxy);
571
+ if (resolved.matchedStore) {
572
+ return {
573
+ at: null,
574
+ proxyId: resolved.proxyId,
575
+ proxyName: resolved.proxyName ?? "",
576
+ region: resolved.region ?? "",
577
+ type: resolved.type ?? null,
578
+ mode: "inherit",
579
+ displayUrl,
580
+ };
581
+ }
582
+ return {
583
+ at: null,
584
+ proxyId: null,
585
+ proxyName: "",
586
+ region: "",
587
+ type: resolved.type ?? null,
588
+ mode: "inherit",
589
+ custom: true,
590
+ displayUrl,
591
+ };
592
+ }
593
+ return {
594
+ at: null,
595
+ proxyId: null,
596
+ proxyName: "",
597
+ region: "",
598
+ type: null,
599
+ mode: "inherit",
600
+ };
601
+ }
602
+
603
+ return undefined;
604
+ }