| 1 | import { randomUUID } from "node:crypto"; |
| 2 | |
| 3 | const world = "cage-password-vault"; |
| 4 | const binding = "cageVaultSubmitted"; |
| 5 | |
| 6 | |
| 7 | |
| 8 | export function vaultPage() { |
| 9 | if (window !== window.top || globalThis.cageVault) return; |
| 10 | const visible = el => el instanceof HTMLInputElement && !el.disabled && !el.readOnly && |
| 11 | el.type !== "hidden" && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== "hidden"; |
| 12 | const fields = root => [...root.querySelectorAll("input")].filter(visible); |
| 13 | const username = list => list.find(el => el.autocomplete === "username") || |
| 14 | list.find(el => el.type === "email") || list.find(el => |
| 15 | ["text", "tel"].includes(el.type) && !/one-time-code|otp|search|captcha/i.test(`${el.autocomplete} ${el.name} ${el.id}`)); |
| 16 | const state = globalThis.cageVault = { |
| 17 | document: crypto.randomUUID(), deadline: 0, lease: "", previousUsername: "", previousAt: 0, |
| 18 | fill(value) { |
| 19 | if (Date.now() >= state.deadline || value.lease !== state.lease || location.origin !== value.origin || |
| 20 | location.protocol !== "https:" || value.document !== state.document) return false; |
| 21 | const list = fields(document); |
| 22 | const passwords = list.filter(el => el.type === "password" && el.autocomplete !== "new-password"); |
| 23 | |
| 24 | let password = passwords.includes(document.activeElement) ? document.activeElement : null; |
| 25 | if (!password && document.activeElement?.form) password = passwords.find(el => el.form === document.activeElement.form); |
| 26 | if (!password && passwords.length === 1) password = passwords[0]; |
| 27 | if (!password && passwords.length > 1) return false; |
| 28 | const user = username(password?.form ? fields(password.form) : list); |
| 29 | if (!password && !user) return false; |
| 30 | const set = (el, text) => { |
| 31 | Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(el, text); |
| 32 | el.dispatchEvent(new Event("input", { bubbles: true })); |
| 33 | el.dispatchEvent(new Event("change", { bubbles: true })); |
| 34 | }; |
| 35 | if (user) set(user, value.username); |
| 36 | if (password) set(password, value.password); |
| 37 | state.previousUsername = value.username; |
| 38 | state.previousAt = Date.now(); |
| 39 | (password || user).focus(); |
| 40 | return true; |
| 41 | }, |
| 42 | }; |
| 43 | let last = "", lastAt = 0; |
| 44 | function capture(root) { |
| 45 | if (location.protocol !== "https:" || Date.now() >= state.deadline) return; |
| 46 | const list = fields(root || document), user = username(list); |
| 47 | if (user?.value) { state.previousUsername = user.value; state.previousAt = Date.now(); } |
| 48 | const passwords = list.filter(el => el.type === "password" && el.value); |
| 49 | const password = passwords.at(-1)?.value || ""; |
| 50 | if (!password && !user?.value) return; |
| 51 | const account = user?.value || (Date.now() - state.previousAt < 120000 ? state.previousUsername : ""); |
| 52 | if (password.length > 8192 || account.length > 1024) return; |
| 53 | const payload = JSON.stringify({ origin: location.origin, username: account, password, |
| 54 | document: state.document, lease: state.lease }); |
| 55 | |
| 56 | const signature = `${state.document}:${account}:${password.length}`; |
| 57 | if (signature === last && Date.now() - lastAt < 800) return; |
| 58 | last = signature; lastAt = Date.now(); |
| 59 | globalThis.cageVaultSubmitted(payload); |
| 60 | } |
| 61 | document.addEventListener("submit", event => { if (event.isTrusted) capture(event.target); }, true); |
| 62 | document.addEventListener("click", event => { |
| 63 | if (!event.isTrusted) return; |
| 64 | const button = event.target.closest?.("button, input[type=submit], [role=button]"); |
| 65 | if (!button) return; |
| 66 | const label = `${button.textContent || ""} ${button.value || ""} ${button.getAttribute("aria-label") || ""}`; |
| 67 | if (button.type === "submit" || /log\s*in|sign\s*in|登录|登入|下一步|继续|next|continue|修改密码|保存密码|change password/i.test(label)) capture(button.form || document); |
| 68 | }, true); |
| 69 | document.addEventListener("keydown", event => { |
| 70 | if (event.isTrusted && event.key === "Enter" && event.target instanceof HTMLInputElement) |
| 71 | capture(event.target.form || document); |
| 72 | }, true); |
| 73 | } |
| 74 | const source = `(${vaultPage.toString()})()`; |
| 75 | |
| 76 | export class BrowserVault { |
| 77 | constructor({ cdp, active, tab, now = () => Date.now() }) { |
| 78 | Object.assign(this, { cdp, active, tab, now }); |
| 79 | this.sessions = new Map(); |
| 80 | this.pending = new Map(); |
| 81 | this.usernames = new Map(); |
| 82 | this.lease = ""; |
| 83 | this.deadline = 0; |
| 84 | this.blocked = []; |
| 85 | this.timer = setInterval(() => this.prune(), 1000); |
| 86 | this.timer.unref(); |
| 87 | } |
| 88 | prune() { |
| 89 | if (this.now() >= this.deadline) { this.pending.clear(); this.usernames.clear(); this.lease = ""; } |
| 90 | for (const [id, item] of this.usernames) if (this.now() >= item.expires) this.usernames.delete(id); |
| 91 | for (const [id, item] of this.pending) if (this.now() >= item.expires) this.pending.delete(id); |
| 92 | } |
| 93 | async attach(tab, sid) { |
| 94 | if (this.tab(tab)?.login || this.tab(tab)?.incognito) return; |
| 95 | const entry = { tab, sid, top: "", contexts: new Map() }; |
| 96 | this.sessions.set(sid, entry); |
| 97 | await this.cdp("Runtime.enable", {}, sid); |
| 98 | const { frameTree } = await this.cdp("Page.getFrameTree", {}, sid); |
| 99 | entry.top = frameTree.frame.id; |
| 100 | await this.cdp("Runtime.addBinding", { name: binding, executionContextName: world }, sid); |
| 101 | await this.cdp("Page.addScriptToEvaluateOnNewDocument", { source, worldName: world }, sid); |
| 102 | const { executionContextId } = await this.cdp("Page.createIsolatedWorld", { frameId: entry.top, worldName: world }, sid); |
| 103 | entry.contexts.set(executionContextId, entry.top); |
| 104 | await this.cdp("Runtime.evaluate", { expression: source, contextId: executionContextId }, sid); |
| 105 | } |
| 106 | remove(tab) { |
| 107 | this.usernames.delete(tab); |
| 108 | for (const [sid, value] of this.sessions) if (value.tab === tab) this.sessions.delete(sid); |
| 109 | for (const [id, value] of this.pending) if (value.tab === tab) this.pending.delete(id); |
| 110 | } |
| 111 | event(event) { |
| 112 | const entry = this.sessions.get(event.sessionId); |
| 113 | if (!entry) return; |
| 114 | const p = event.params || {}; |
| 115 | if (event.method === "Runtime.executionContextCreated" && p.context.name === world) |
| 116 | entry.contexts.set(p.context.id, p.context.auxData?.frameId); |
| 117 | if (event.method === "Runtime.executionContextDestroyed") entry.contexts.delete(p.executionContextId); |
| 118 | if (event.method === "Runtime.executionContextsCleared") entry.contexts.clear(); |
| 119 | if (event.method === "Page.frameNavigated" && !p.frame.parentId) entry.top = p.frame.id; |
| 120 | if (event.method !== "Runtime.bindingCalled" || p.name !== binding || |
| 121 | entry.contexts.get(p.executionContextId) !== entry.top) return; |
| 122 | this.prune(); |
| 123 | if (!this.lease || entry.tab !== this.active() || (this.tab(entry.tab)?.login || this.tab(entry.tab)?.incognito) || p.payload.length > 16000) return; |
| 124 | try { |
| 125 | const value = JSON.parse(p.payload); |
| 126 | const origin = new URL(value.origin).origin; |
| 127 | if (!origin.startsWith("https://") || origin !== value.origin || value.lease !== this.lease || |
| 128 | typeof value.password !== "string" || value.password.length > 8192 || |
| 129 | typeof value.username !== "string" || value.username.length > 1024 || this.blocked.includes(origin)) return; |
| 130 | if (value.username) this.usernames.set(entry.tab, { origin, username: value.username, expires: this.now() + 120000 }); |
| 131 | if (!value.password) return; |
| 132 | const previous = this.usernames.get(entry.tab); |
| 133 | if (!value.username && previous?.origin === origin) value.username = previous.username; |
| 134 | |
| 135 | |
| 136 | for (const [id, old] of this.pending) if (old.tab === entry.tab) this.pending.delete(id); |
| 137 | const id = randomUUID(); |
| 138 | this.pending.set(id, { id, tab: entry.tab, origin, username: value.username, |
| 139 | password: value.password, expires: this.now() + 120000 }); |
| 140 | while (this.pending.size > 8) this.pending.delete(this.pending.keys().next().value); |
| 141 | } catch {} |
| 142 | } |
| 143 | context(entry) { |
| 144 | return [...entry.contexts].find(([, frame]) => frame === entry.top)?.[0]; |
| 145 | } |
| 146 | async evaluate(entry, expression) { |
| 147 | const contextId = this.context(entry); |
| 148 | if (!contextId) throw new Error("登录页面已变化,请稍后重试"); |
| 149 | const result = await this.cdp("Runtime.evaluate", { expression, contextId, returnByValue: true }, entry.sid); |
| 150 | if (result.exceptionDetails) throw new Error("网页未能处理密码操作"); |
| 151 | return result.result?.value; |
| 152 | } |
| 153 | async request(input) { |
| 154 | this.prune(); |
| 155 | if (input.action === "lock") { |
| 156 | if (input.lease === this.lease) { this.pending.clear(); this.usernames.clear(); this.lease = ""; this.deadline = 0; } |
| 157 | return { ok: true }; |
| 158 | } |
| 159 | if (input.action === "status") { |
| 160 | if (!/^[a-f0-9]{64}$/.test(input.lease)) throw new Error("解锁状态无效"); |
| 161 | if (this.lease !== input.lease) { this.pending.clear(); this.usernames.clear(); } |
| 162 | this.lease = input.lease; |
| 163 | this.deadline = this.now() + 6500; |
| 164 | this.blocked = Array.isArray(input.blocked) ? input.blocked : []; |
| 165 | for (const [id, value] of this.pending) if (this.blocked.includes(value.origin)) this.pending.delete(id); |
| 166 | const result = { available: true, origin: "", document: "", candidates: [], entries: [] }; |
| 167 | await Promise.all([...this.sessions.values()].map(async entry => { |
| 168 | try { |
| 169 | const value = await this.evaluate(entry, `(() => { |
| 170 | const v = globalThis.cageVault; |
| 171 | if (!v || location.protocol !== 'https:') return null; |
| 172 | if (v.lease !== ${JSON.stringify(this.lease)}) { v.previousUsername = ""; v.previousAt = 0; } |
| 173 | v.lease = ${JSON.stringify(this.lease)}; v.deadline = Date.now() + 6500; |
| 174 | return {origin: location.origin, document: v.document}; |
| 175 | })()`); |
| 176 | if (value && entry.tab === input.tab && entry.tab === this.active() && !(this.tab(entry.tab)?.login || this.tab(entry.tab)?.incognito)) |
| 177 | Object.assign(result, value); |
| 178 | } catch {} |
| 179 | })); |
| 180 | result.candidates = [...this.pending.values()].map(({ expires, ...value }) => value); |
| 181 | return result; |
| 182 | } |
| 183 | if (!this.lease || input.lease !== this.lease) throw new Error("保险箱已锁定,请重试"); |
| 184 | if (input.action === "candidate") { |
| 185 | const value = this.pending.get(input.candidate); |
| 186 | if (!value) throw new Error("登录记录已过期,请重新登录"); |
| 187 | return value; |
| 188 | } |
| 189 | if (input.action === "dismiss") { this.pending.delete(input.candidate); return { ok: true }; } |
| 190 | if (input.action === "fill") { |
| 191 | const entry = [...this.sessions.values()].find(value => value.tab === input.tab); |
| 192 | if (!entry || input.tab !== this.active() || (this.tab(input.tab)?.login || this.tab(input.tab)?.incognito)) throw new Error("当前网页已切换"); |
| 193 | const filled = await this.evaluate(entry, `globalThis.cageVault?.fill(${JSON.stringify(input)}) === true`); |
| 194 | if (filled) this.usernames.set(entry.tab, { origin: input.origin, username: input.username, expires: this.now() + 120000 }); |
| 195 | if (!filled) throw new Error("未找到可填写的登录框,或页面已变化"); |
| 196 | return { ok: true }; |
| 197 | } |
| 198 | throw new Error("密码操作无效"); |
| 199 | } |
| 200 | } |