@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,459 @@
1
+ // Per-account fingerprint browser controller.
2
+ //
3
+ // Lets a user open an account's own persistent Camoufox profile with its pinned
4
+ // fingerprint and live effective exit (from magpie's `providers.json`, with
5
+ // ledger fallback when `providers.json` is unavailable) outside of a sign-in or
6
+ // hosted renewal flow.
7
+ //
8
+ // Invariants enforced here:
9
+ // * Read-only on account state: NEVER calls `ensureIdentity`, NEVER mutates
10
+ // `providers.json`, `account.json`, `identity.json`, or magpie auth files.
11
+ // * Strict exit boundary: a corrupt `providers.json` or invalid/missing exit
12
+ // fails explicitly (409) and never silently degrades to direct. Direct exits
13
+ // configured explicitly or inherited with no provider proxy are allowed.
14
+ // * Credential boundary: proxy credentials reach `launchBrowser` in memory
15
+ // only. All returned views (`open`, `status`, `listOpen`) carry only the
16
+ // whitelisted `publicAccountExit` projection; the exit change detector keeps
17
+ // only a SHA-256 digest in memory and never returns it.
18
+ // * Per-account isolation & mutex: different accounts may open browsers at
19
+ // the same time; the same account allows at most one browser (including
20
+ // in-flight starts) and cannot overlap with its own sign-in or hosted
21
+ // renewal.
22
+
23
+ import { createHash } from "node:crypto";
24
+ import { EXECUTABLE_ENV } from "./browser-environment.mjs";
25
+ import {
26
+ accountDir,
27
+ accountProfileDir,
28
+ readAccountMeta,
29
+ readIdentity as defaultReadIdentity,
30
+ } from "./account-identity.mjs";
31
+ import {
32
+ parseProxyUrl,
33
+ publicAccountExit,
34
+ resolveEffectiveAccountExit,
35
+ } from "./account-exit.mjs";
36
+ import {
37
+ launchSignInBrowser,
38
+ navigationWarning,
39
+ toPlaywrightProxy,
40
+ } from "./browser-launcher.mjs";
41
+
42
+ const BLANK_URL = "about:blank";
43
+ const NON_AUTHORITATIVE_PROVIDERS_REASONS = new Set([
44
+ "providers_missing",
45
+ "provider_missing",
46
+ "account_name_unknown",
47
+ ]);
48
+
49
+ export class AccountBrowserError extends Error {
50
+ constructor(code, message, status = 500) {
51
+ super(message);
52
+ this.name = "AccountBrowserError";
53
+ this.code = code;
54
+ this.status = status;
55
+ }
56
+ }
57
+
58
+ export function normalizeOpenUrl(rawUrl) {
59
+ if (rawUrl === undefined || rawUrl === null) return BLANK_URL;
60
+ if (typeof rawUrl !== "string") {
61
+ throw new AccountBrowserError("invalid_url", "The browser URL must be a string.", 400);
62
+ }
63
+ const trimmed = rawUrl.trim();
64
+ if (!trimmed || trimmed.toLowerCase() === BLANK_URL) return BLANK_URL;
65
+ if (/[\u0000-\u001f\u007f]/.test(trimmed)) {
66
+ throw new AccountBrowserError("invalid_url", "The browser URL is invalid.", 400);
67
+ }
68
+ let parsed;
69
+ try {
70
+ parsed = new URL(trimmed);
71
+ } catch {
72
+ throw new AccountBrowserError("invalid_url", "The browser URL is invalid.", 400);
73
+ }
74
+ if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || !parsed.hostname) {
75
+ throw new AccountBrowserError(
76
+ "invalid_url",
77
+ "Only http:, https:, or about:blank URLs are allowed.",
78
+ 400,
79
+ );
80
+ }
81
+ if (parsed.username || parsed.password) {
82
+ throw new AccountBrowserError(
83
+ "invalid_url",
84
+ "Browser URLs must not contain embedded credentials.",
85
+ 400,
86
+ );
87
+ }
88
+ return parsed.href;
89
+ }
90
+
91
+ function entryId(provider, key) {
92
+ return `${provider}\u0000${key}`;
93
+ }
94
+
95
+ function closedStatus() {
96
+ return { open: false, openedAt: null, exit: null, exitChanged: false };
97
+ }
98
+
99
+ function normalizeProxyForDigest(proxy) {
100
+ if (!proxy || typeof proxy !== "object") return null;
101
+ if (typeof proxy.server === "string" && proxy.server) {
102
+ return toPlaywrightProxy(proxy);
103
+ }
104
+ let normalized = null;
105
+ if (typeof proxy.type === "string") {
106
+ normalized = toPlaywrightProxy({ ...proxy, type: proxy.type.trim().toLowerCase() });
107
+ } else {
108
+ normalized = toPlaywrightProxy(proxy);
109
+ }
110
+ if (!normalized && typeof proxy.url === "string") {
111
+ normalized = toPlaywrightProxy(parseProxyUrl(proxy.url));
112
+ }
113
+ return normalized;
114
+ }
115
+
116
+ // Internal SHA-256 fingerprint of the effective exit used to launch a browser.
117
+ // Kept strictly in process memory and never serialized to callers.
118
+ function computeExitDigest(resolved) {
119
+ if (!resolved || typeof resolved !== "object" || !resolved.ok) return null;
120
+ const pw = normalizeProxyForDigest(resolved.proxy);
121
+ const effectiveMode = resolved.effectiveMode ?? (pw ? "proxy" : "direct");
122
+ if (effectiveMode === "proxy" && !pw) return null;
123
+ const payload = {
124
+ effectiveMode,
125
+ mode: resolved.mode ?? null,
126
+ proxyId: resolved.proxyId ?? null,
127
+ server: effectiveMode === "proxy" ? (pw?.server ?? null) : null,
128
+ username: effectiveMode === "proxy" ? (pw?.username ?? "") : "",
129
+ password: effectiveMode === "proxy" ? (pw?.password ?? "") : "",
130
+ };
131
+ return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
132
+ }
133
+
134
+ function translateLaunchError(error) {
135
+ const code = typeof error?.code === "string" ? error.code : "";
136
+ if (code === "executable_missing") {
137
+ return new AccountBrowserError(
138
+ "executable_missing",
139
+ "The fingerprint browser is not installed; prepare it on the Providers page first.",
140
+ 503,
141
+ );
142
+ }
143
+ if (code === "runtime_missing") {
144
+ return new AccountBrowserError(
145
+ "runtime_missing",
146
+ "The fingerprint browser runtime is unavailable; prepare it on the Providers page first.",
147
+ 503,
148
+ );
149
+ }
150
+ if (code === "launch_timeout") {
151
+ return new AccountBrowserError(
152
+ "launch_timeout",
153
+ "The account browser did not open in time.",
154
+ 504,
155
+ );
156
+ }
157
+ if (code === "invalid_url") {
158
+ return new AccountBrowserError(
159
+ "invalid_url",
160
+ "Only http:, https:, or about:blank URLs are allowed.",
161
+ 400,
162
+ );
163
+ }
164
+ return new AccountBrowserError(
165
+ "launch_failed",
166
+ "The account browser could not be opened.",
167
+ 502,
168
+ );
169
+ }
170
+
171
+ function exitFailureMessage(reason, store) {
172
+ if (reason === "providers_invalid") {
173
+ return "magpie's providers.json is malformed, so the account exit cannot be resolved.";
174
+ }
175
+ if (reason === "providers_unreadable") {
176
+ return "magpie's providers.json could not be read, so the account exit cannot be resolved.";
177
+ }
178
+ if (reason === "invalid_exit_url") {
179
+ return "The proxy address configured in magpie's providers.json is invalid; fix it before opening the account browser.";
180
+ }
181
+ if (reason === "exit_missing") {
182
+ return !store || typeof store.get !== "function"
183
+ ? "The proxy list is unavailable, so the account exit cannot be resolved."
184
+ : "The exit assigned to this account is no longer in the proxy list. Restore it or assign another exit first.";
185
+ }
186
+ return "This account has no resolvable exit; configure an exit or sign in through clean-login first.";
187
+ }
188
+
189
+ export function createAccountBrowserController({
190
+ env = process.env,
191
+ store = null,
192
+ signIn = null,
193
+ renewHosting = null,
194
+ resolveExecutable,
195
+ launchBrowser = launchSignInBrowser,
196
+ readMeta = readAccountMeta,
197
+ readIdentity = defaultReadIdentity,
198
+ resolveExit = resolveEffectiveAccountExit,
199
+ now = () => new Date().toISOString(),
200
+ } = {}) {
201
+ const active = new Map();
202
+ const starting = new Set();
203
+ let shutdownGeneration = 0;
204
+
205
+ const getExecutable =
206
+ typeof resolveExecutable === "function"
207
+ ? resolveExecutable
208
+ : async () => env?.[EXECUTABLE_ENV] || null;
209
+
210
+ function assertNoConflict(provider, key) {
211
+ const renewal = typeof renewHosting?.running === "function" ? renewHosting.running() : null;
212
+ if (renewal && renewal.provider === provider && renewal.key === key) {
213
+ throw new AccountBrowserError(
214
+ "renewal_running",
215
+ "Hosted renewal is currently running for this account; wait for it to finish before opening the browser.",
216
+ 409,
217
+ );
218
+ }
219
+ const activeSignIn =
220
+ typeof signIn?.activeAccount === "function" ? signIn.activeAccount() : null;
221
+ if (activeSignIn && activeSignIn.provider === provider && activeSignIn.key === key) {
222
+ throw new AccountBrowserError(
223
+ "signin_running",
224
+ "A sign-in or fingerprint rotation is currently running for this account; wait for it to finish before opening the browser.",
225
+ 409,
226
+ );
227
+ }
228
+ }
229
+
230
+ function isOpen(provider, key) {
231
+ if (typeof provider !== "string" || !provider || typeof key !== "string" || !key) {
232
+ return false;
233
+ }
234
+ const id = entryId(provider, key);
235
+ return starting.has(id) || active.has(id);
236
+ }
237
+
238
+ function listOpen() {
239
+ return [...active.values()].map((entry) => ({
240
+ provider: entry.provider,
241
+ key: entry.key,
242
+ openedAt: entry.openedAt,
243
+ exit: { ...entry.exitPublic },
244
+ }));
245
+ }
246
+
247
+ async function status(provider, key, { liveResolved = null } = {}) {
248
+ if (typeof provider !== "string" || !provider || typeof key !== "string" || !key) {
249
+ return closedStatus();
250
+ }
251
+ const entry = active.get(entryId(provider, key));
252
+ if (!entry) return closedStatus();
253
+
254
+ let live = liveResolved;
255
+ const needsFallbackResolve =
256
+ live === null ||
257
+ live === undefined ||
258
+ (!live.ok && NON_AUTHORITATIVE_PROVIDERS_REASONS.has(live.reason));
259
+ if (needsFallbackResolve) {
260
+ try {
261
+ const dir = accountDir(env, provider, key);
262
+ const meta = await readMeta(dir);
263
+ live = await resolveExit({
264
+ env,
265
+ provider,
266
+ key,
267
+ meta,
268
+ store,
269
+ fallbackToLedger: true,
270
+ });
271
+ } catch {
272
+ live = null;
273
+ }
274
+ }
275
+
276
+ const liveDigest = computeExitDigest(live);
277
+ const exitChanged = liveDigest === null || liveDigest !== entry.exitDigest;
278
+ return {
279
+ open: true,
280
+ openedAt: entry.openedAt,
281
+ exit: { ...entry.exitPublic },
282
+ exitChanged,
283
+ ...(entry.warning ? { warning: { ...entry.warning } } : {}),
284
+ };
285
+ }
286
+
287
+ async function open({ provider, key, url } = {}) {
288
+ if (typeof provider !== "string" || !provider.trim() || typeof key !== "string" || !key.trim()) {
289
+ throw new AccountBrowserError("invalid_account", "Provider and account key are required.", 400);
290
+ }
291
+ const targetUrl = normalizeOpenUrl(url);
292
+ const id = entryId(provider, key);
293
+ if (active.has(id) || starting.has(id)) {
294
+ throw new AccountBrowserError(
295
+ "browser_already_open",
296
+ "A fingerprint browser is already open for this account.",
297
+ 409,
298
+ );
299
+ }
300
+
301
+ starting.add(id);
302
+ const gen = shutdownGeneration;
303
+ try {
304
+ const dir = accountDir(env, provider, key);
305
+ const meta = await readMeta(dir);
306
+ if (!meta || meta.provider !== provider) {
307
+ throw new AccountBrowserError("not_found", "This account was not found.", 404);
308
+ }
309
+
310
+ assertNoConflict(provider, key);
311
+
312
+ // Strictly read-only: NEVER call ensureIdentity or synthesize a new pin.
313
+ const identity = await readIdentity(dir);
314
+ if (!identity || typeof identity !== "object" || Array.isArray(identity)) {
315
+ throw new AccountBrowserError(
316
+ "identity_missing",
317
+ "This account has no pinned fingerprint; sign in through clean-login first.",
318
+ 409,
319
+ );
320
+ }
321
+
322
+ const resolved = await resolveExit({
323
+ env,
324
+ provider,
325
+ key,
326
+ meta,
327
+ store,
328
+ fallbackToLedger: true,
329
+ });
330
+ if (!resolved?.ok) {
331
+ const reason = resolved?.reason || "exit_unknown";
332
+ throw new AccountBrowserError(reason, exitFailureMessage(reason, store), 409);
333
+ }
334
+
335
+ const exitDigest = computeExitDigest(resolved);
336
+ if (!exitDigest) {
337
+ throw new AccountBrowserError(
338
+ "invalid_exit_url",
339
+ exitFailureMessage("invalid_exit_url", store),
340
+ 409,
341
+ );
342
+ }
343
+
344
+ let executablePath;
345
+ try {
346
+ executablePath = await getExecutable();
347
+ } catch {
348
+ executablePath = null;
349
+ }
350
+ if (typeof executablePath !== "string" || !executablePath.trim()) {
351
+ throw new AccountBrowserError(
352
+ "executable_missing",
353
+ "The fingerprint browser is not installed; prepare it on the Providers page first.",
354
+ 503,
355
+ );
356
+ }
357
+
358
+ assertNoConflict(provider, key);
359
+
360
+ let handle;
361
+ try {
362
+ handle = await launchBrowser({
363
+ executablePath,
364
+ url: targetUrl,
365
+ profileDir: accountProfileDir(dir),
366
+ identity,
367
+ proxy: resolved.effectiveMode === "proxy" ? resolved.proxy : null,
368
+ headless: false,
369
+ purpose: "account",
370
+ env,
371
+ });
372
+ } catch (error) {
373
+ throw translateLaunchError(error);
374
+ }
375
+
376
+ if (gen !== shutdownGeneration) {
377
+ try {
378
+ await handle?.close?.();
379
+ } catch {
380
+ // Best-effort cleanup if closeAll() raced with an in-flight launch.
381
+ }
382
+ throw new AccountBrowserError(
383
+ "browser_closed",
384
+ "The account browser was closed during shutdown.",
385
+ 409,
386
+ );
387
+ }
388
+
389
+ const openedAt = now();
390
+ const exitPublic = publicAccountExit(resolved);
391
+ const warning = navigationWarning(handle?.warning);
392
+ const entry = {
393
+ provider,
394
+ key,
395
+ openedAt,
396
+ exitPublic,
397
+ exitDigest,
398
+ warning,
399
+ handle,
400
+ };
401
+ active.set(id, entry);
402
+
403
+ if (handle?.closed && typeof handle.closed.then === "function") {
404
+ const onClosed = () => {
405
+ if (active.get(id)?.handle === handle) {
406
+ active.delete(id);
407
+ }
408
+ };
409
+ handle.closed.then(onClosed, onClosed);
410
+ }
411
+
412
+ return {
413
+ open: true,
414
+ openedAt,
415
+ exit: { ...exitPublic },
416
+ exitChanged: false,
417
+ ...(warning ? { warning: { ...warning } } : {}),
418
+ };
419
+ } finally {
420
+ starting.delete(id);
421
+ }
422
+ }
423
+
424
+ async function close(provider, key) {
425
+ if (typeof provider !== "string" || !provider || typeof key !== "string" || !key) {
426
+ return { closed: false, browser: closedStatus() };
427
+ }
428
+ const id = entryId(provider, key);
429
+ const entry = active.get(id);
430
+ if (!entry) {
431
+ return { closed: false, browser: closedStatus() };
432
+ }
433
+ active.delete(id);
434
+ try {
435
+ await entry.handle?.close?.();
436
+ } catch {
437
+ // Closing an already-closed window is not an error worth surfacing.
438
+ }
439
+ return { closed: true, browser: closedStatus() };
440
+ }
441
+
442
+ async function closeAll() {
443
+ shutdownGeneration += 1;
444
+ const entries = [...active.values()];
445
+ active.clear();
446
+ await Promise.allSettled(
447
+ entries.map((entry) => Promise.resolve().then(() => entry.handle?.close?.())),
448
+ );
449
+ }
450
+
451
+ return {
452
+ isOpen,
453
+ listOpen,
454
+ status,
455
+ open,
456
+ close,
457
+ closeAll,
458
+ };
459
+ }