| 1 | |
| 2 | |
| 3 | export class LoginBrowser { |
| 4 | constructor(cdp) { |
| 5 | this.cdp = cdp; |
| 6 | this.contexts = new Map(); |
| 7 | } |
| 8 | |
| 9 | tab(raw, previous) { |
| 10 | if (!previous?.login && !this.contexts.has(raw.browserContextId)) return raw; |
| 11 | let origin = "about:blank"; |
| 12 | try { |
| 13 | const url = new URL(raw.url); |
| 14 | if (["https:", "http:"].includes(url.protocol)) origin = url.origin; |
| 15 | } catch {} |
| 16 | return { ...raw, login: true, url: origin, title: "账号授权" }; |
| 17 | } |
| 18 | |
| 19 | async open(login, address, activate) { |
| 20 | if (typeof login !== "string" || !/^[a-f0-9-]{16,64}$/.test(login)) throw new Error("登录任务无效"); |
| 21 | const url = new URL(address); |
| 22 | if (url.protocol !== "https:" || url.username || url.password || |
| 23 | !["claude.ai", "claude.com", "console.anthropic.com", "platform.claude.com", "platform.anthropic.com"].includes(url.hostname)) |
| 24 | throw new Error("仅可打开官方登录地址"); |
| 25 | await this.finish(login); |
| 26 | const { browserContextId } = await this.cdp("Target.createBrowserContext", { disposeOnDetach: true }); |
| 27 | const expiry = setTimeout(() => this.close(browserContextId).catch(() => {}), 15 * 60_000); |
| 28 | expiry.unref(); |
| 29 | this.contexts.set(browserContextId, { login, expiry }); |
| 30 | try { |
| 31 | const { targetId } = await this.cdp("Target.createTarget", { browserContextId, url: "about:blank", newWindow: true }); |
| 32 | const sessionId = await activate({ targetId, browserContextId, type: "page", url: url.href }); |
| 33 | await this.cdp("Page.navigate", { url: url.href }, sessionId); |
| 34 | return { id: targetId }; |
| 35 | } catch { |
| 36 | await this.close(browserContextId); |
| 37 | throw new Error("临时登录页面未能打开"); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | async finish(login) { |
| 42 | for (const [id, entry] of this.contexts) { |
| 43 | if (entry.login === login) await this.close(id); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | async close(id) { |
| 48 | const entry = this.contexts.get(id); |
| 49 | if (!entry) return; |
| 50 | await this.cdp("Target.disposeBrowserContext", { browserContextId: id }); |
| 51 | clearTimeout(entry.expiry); |
| 52 | this.contexts.delete(id); |
| 53 | } |
| 54 | } |