@dorokuma/magpie-gemini-web 0.18.0 → 0.18.2

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,343 @@
1
+ // Local sign-in wizard for the one-click Gemini Web setup. Magpie opens this page instead of
2
+ // gemini.google.com so the flow unfolds in the right order: open a private window first (the
3
+ // backend rotates this session and a shared one would sign the user's daily browser out of
4
+ // Google), sign in there and copy the Cookie, then tell us the /u/N index that same window
5
+ // shows — asking for the index before the window exists was guesswork.
6
+ import http from 'node:http';
7
+ import crypto from 'node:crypto';
8
+ import { launchPrivateBrowser } from './private-browser.mjs';
9
+ import { parseCookieInput, parseAuthuser, validateProxyURL } from './setup.mjs';
10
+
11
+ const GEMINI_APP = 'https://gemini.google.com/app';
12
+ const LINGER_MS = 2 * 60 * 1000;
13
+ const MAX_BODY = 256 * 1024;
14
+ const TIMEOUT_MS = 10 * 60 * 1000;
15
+ const TIMEOUT_MESSAGE = '本次登录等待已到 10 分钟,页面已失效;请在 Magpie 中重新发起登录。已安装的本地后端会保留。';
16
+
17
+ // esc is the only interpolation into the page template; every user- or config-derived string
18
+ // reaches the DOM through textContent / pre-filled values escaped here, never as markup.
19
+ const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
20
+
21
+ // startWebConnect serves the wizard on 127.0.0.1 behind a random token path. submit() runs the
22
+ // import pipeline (parse → wait for backend → import → sign-in result) injected by index.mjs so
23
+ // this module stays testable without a backend; the resolved value is what wait() hands Magpie.
24
+ export async function startWebConnect({ proxy = '', submit, privateBrowser = launchPrivateBrowser, timeoutMs = TIMEOUT_MS } = {}) {
25
+ if (typeof submit !== 'function') throw new Error('startWebConnect requires a submit handler');
26
+ const token = crypto.randomBytes(24).toString('hex');
27
+ const nonce = crypto.randomBytes(16).toString('base64');
28
+ let origin, ended = false, resultValue, error = '', linger, timer, closing, submitting = false;
29
+
30
+ let resolveResult, rejectResult;
31
+ const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject; });
32
+ result.catch(() => {}); // wait() may never be called if Magpie abandons the sign-in
33
+
34
+ function finish(err, value) {
35
+ if (ended) return;
36
+ ended = true;
37
+ clearTimeout(timer);
38
+ error = err?.message || '';
39
+ resultValue = value;
40
+ if (err) rejectResult(err); else resolveResult(value);
41
+ // Leave the page up briefly so the user can read the outcome before it goes away.
42
+ linger = setTimeout(close, LINGER_MS);
43
+ linger.unref();
44
+ }
45
+ function close() {
46
+ if (closing) return closing;
47
+ if (!ended) finish(new Error('登录页面已关闭,请在 Magpie 中重新登录。'));
48
+ clearTimeout(linger);
49
+ server.close();
50
+ server.closeAllConnections?.();
51
+ closing = Promise.resolve();
52
+ return closing;
53
+ }
54
+
55
+ const headers = { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' };
56
+ const json = (res, status, data) => res.writeHead(status, { ...headers, 'Content-Type': 'application/json' }).end(JSON.stringify(data));
57
+ const server = http.createServer((req, res) => {
58
+ handle(req, res).catch(err => {
59
+ if (!res.headersSent) json(res, 502, { error: err.message });
60
+ else res.end();
61
+ });
62
+ });
63
+
64
+ async function handle(req, res) {
65
+ const base = `/${token}`;
66
+ const route = req.url;
67
+ if (req.headers.host !== new URL(origin).host ||
68
+ ![base, `${base}/state`, `${base}/open-private`, `${base}/submit`, `${base}/cancel`].includes(route)) {
69
+ res.writeHead(404, headers).end();
70
+ return;
71
+ }
72
+ if (req.method === 'POST' && (req.headers.origin !== origin ||
73
+ (req.headers['sec-fetch-site'] && req.headers['sec-fetch-site'] !== 'same-origin'))) {
74
+ res.writeHead(403, headers).end();
75
+ return;
76
+ }
77
+ if (req.method === 'GET' && route === base) {
78
+ res.writeHead(200, {
79
+ ...headers, 'Content-Type': 'text/html; charset=utf-8',
80
+ 'Content-Security-Policy': `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; connect-src 'self'; form-action 'none'; base-uri 'none'; frame-ancestors 'none'`
81
+ }).end(PAGE
82
+ // Function replacers: a literal replacement string would re-expand $$ $' $& $` in a
83
+ // proxy password into template metacharacters and corrupt the rendered DOM.
84
+ .replace('NONCE', () => nonce)
85
+ .replace('GEMINI_URL', () => GEMINI_APP)
86
+ .replace('PREFILL_PROXY', () => esc(proxy)));
87
+ return;
88
+ }
89
+ if (req.method === 'GET' && route === `${base}/state`) {
90
+ json(res, 200, { done: ended, error, email: resultValue?.email || '' });
91
+ return;
92
+ }
93
+ if (req.method !== 'POST') { res.writeHead(405, headers).end(); return; }
94
+ if (route === `${base}/cancel`) {
95
+ finish(new Error('已取消登录。'));
96
+ res.writeHead(204, headers).end();
97
+ return;
98
+ }
99
+ if (route === `${base}/open-private`) {
100
+ // Read (and drain) the small body so the socket state stays clean.
101
+ await readBody(req);
102
+ if (ended) { json(res, 410, { error: error || '登录已经结束,请回到 Magpie。' }); return; }
103
+ json(res, 200, await privateBrowser(GEMINI_APP));
104
+ return;
105
+ }
106
+ if (route === `${base}/submit`) {
107
+ if (ended) { json(res, 410, { error: error || '登录已经结束,请回到 Magpie。' }); return; }
108
+ // Single-flight, claimed before the first await so a second POST can never race the
109
+ // import pipeline: it gets a 409 while the first submit is still running. The flag is
110
+ // released on failure so the user can fix the fields and retry in place.
111
+ if (submitting) { json(res, 409, { error: '正在验证中,请稍候…' }); return; }
112
+ submitting = true;
113
+ try {
114
+ const body = await readBody(req);
115
+ if (ended) { json(res, 410, { error: error || '登录已经结束,请回到 Magpie。' }); return; }
116
+ let input;
117
+ try {
118
+ input = JSON.parse(body);
119
+ } catch {
120
+ json(res, 400, { error: '请求格式不正确' });
121
+ return;
122
+ }
123
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
124
+ json(res, 400, { error: '请求格式不正确' });
125
+ return;
126
+ }
127
+ // Parse and validate every field before the backend sees anything: a bad cookie or index
128
+ // is reported in place, and the form keeps its values for a retry.
129
+ let cookie, authuser, proxyURL;
130
+ try {
131
+ cookie = parseCookieInput(input.cookie);
132
+ authuser = parseAuthuser(input.authuser);
133
+ proxyURL = validateProxyURL(input.proxy);
134
+ } catch (err) {
135
+ json(res, 400, { error: err.message });
136
+ return;
137
+ }
138
+ try {
139
+ const value = await submit({ cookie, authuser, proxy: proxyURL, isEnded: () => ended });
140
+ if (ended) { json(res, 410, { error: error || '登录已经结束,请回到 Magpie。' }); return; }
141
+ finish(null, value || {});
142
+ json(res, 200, { ok: true, email: resultValue?.email || '' });
143
+ } catch (err) {
144
+ // The import failed (bad cookie, backend unreachable, unsupported build): the page
145
+ // shows the message in place and the user can fix the fields and submit again.
146
+ json(res, ended ? 410 : 400, { error: ended ? (error || '登录已经结束,请回到 Magpie。') : err.message });
147
+ }
148
+ return;
149
+ } finally {
150
+ // A session that is still open retries in place after a failed submit; once it has
151
+ // ended the flag no longer matters (the 410 check above runs first).
152
+ if (!ended) submitting = false;
153
+ }
154
+ }
155
+ res.writeHead(404, headers).end();
156
+ }
157
+
158
+ function readBody(req) {
159
+ return new Promise((resolve, reject) => {
160
+ let size = 0, tooBig = false;
161
+ const chunks = [];
162
+ req.on('data', chunk => {
163
+ size += chunk.length;
164
+ if (size > MAX_BODY && !tooBig) {
165
+ // Drain the rest instead of destroying the socket, so the error answer still
166
+ // reaches the client.
167
+ tooBig = true;
168
+ reject(new Error('提交内容过大'));
169
+ return;
170
+ }
171
+ if (!tooBig) chunks.push(chunk);
172
+ });
173
+ req.on('end', () => { if (!tooBig) resolve(Buffer.concat(chunks).toString('utf8')); });
174
+ req.on('error', () => { if (!tooBig) reject(new Error('请求中断')); });
175
+ });
176
+ }
177
+
178
+ await new Promise((resolve, reject) => {
179
+ server.once('error', reject);
180
+ server.listen(0, '127.0.0.1', resolve);
181
+ });
182
+ server.unref();
183
+ origin = `http://127.0.0.1:${server.address().port}`;
184
+ timer = setTimeout(() => finish(new Error(TIMEOUT_MESSAGE)), Math.max(1, timeoutMs));
185
+ timer.unref();
186
+ return { url: `${origin}/${token}`, wait: () => result, close };
187
+ }
188
+
189
+ const PAGE = `<!doctype html>
190
+ <html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
191
+ <title>登录 Gemini Web</title>
192
+ <style>
193
+ :root { color-scheme: light dark; font: 16px/1.7 system-ui, sans-serif; }
194
+ body { max-width: 640px; margin: 6vh auto; padding: 0 24px 48px; }
195
+ h1 { font-size: 24px; } h2 { font-size: 18px; margin-top: 2em; }
196
+ p, li { opacity: .88; }
197
+ button { font: inherit; padding: 8px 18px; border-radius: 8px; cursor: pointer; }
198
+ textarea, input[type=text] { width: 100%; box-sizing: border-box; font: 13px/1.5 ui-monospace, monospace; padding: 8px; border-radius: 6px; border: 1px solid #8884; background: transparent; color: inherit; }
199
+ textarea { min-height: 96px; resize: vertical; }
200
+ label { display: block; margin: 14px 0 4px; font-weight: 600; }
201
+ .hint { font-size: 13px; opacity: .65; margin-top: 2px; }
202
+ .status { min-height: 1.5em; }
203
+ .error { color: #d33; }
204
+ .ok { color: #187a2e; }
205
+ code { user-select: all; }
206
+ [hidden] { display: none; }
207
+ </style></head><body>
208
+ <h1>登录 Gemini Web</h1>
209
+
210
+ <h2>第 1 步:用无痕窗口打开 Gemini 并登录</h2>
211
+ <p>必须使用无痕 / 隐私窗口(推荐 Firefox),不要用平时登录着 Google 的窗口:本地后端会定时刷新这份登录来保活,和日常浏览器共用同一会话会被 Google 整个踢出登录。无痕窗口关掉后会话只留给后端。</p>
212
+ <p><button id="open">打开无痕窗口登录 Gemini</button> <button id="cancel" type="button">取消登录</button></p>
213
+ <p id="open-status" class="status" role="status" aria-live="polite"></p>
214
+ <p id="manual">也可以手动开一个无痕窗口,访问<br><code>GEMINI_URL</code></p>
215
+
216
+ <h2>第 2 步:复制 Cookie</h2>
217
+ <ol>
218
+ <li>在无痕窗口里登录要使用的 Google 账号。</li>
219
+ <li>按 <kbd>F12</kbd>(macOS 按 <kbd>⌥⌘I</kbd>)打开开发者工具,切到 <b>Network(网络)</b>,刷新页面。</li>
220
+ <li>点列表里任意一个 <code>gemini.google.com</code> 请求 → <b>Headers</b> → <b>Request Headers</b>,复制 <code>cookie</code> 一行的完整值。</li>
221
+ </ol>
222
+ <label for="cookie">Cookie(必填)</label>
223
+ <textarea id="cookie" spellcheck="false" placeholder="cookie 请求头的值;也支持 DevTools 表格复制或 JSON 导出"></textarea>
224
+ <label for="authuser">Google 账号索引(authuser,可选)</label>
225
+ <input type="text" id="authuser" spellcheck="false" placeholder="0">
226
+ <p class="hint">对照无痕窗口登录后的地址栏 <code>/u/N/app</code> 填写 <code>N</code>;单账号留空即可(按 0 处理)。无痕窗口的索引可能和日常窗口不同。</p>
227
+ <label for="proxy">代理地址(可选)</label>
228
+ <input type="text" id="proxy" spellcheck="false" value="PREFILL_PROXY" placeholder="http://127.0.0.1:7890">
229
+ <p class="hint">访问 Google 需要代理时填写(http / https / socks5 / socks5h),会绑定到这个账号;留空则不在本次登录指定代理,若本地后端已配置代理池,仍会按后端规则生效。</p>
230
+
231
+ <h2>第 3 步:验证并完成登录</h2>
232
+ <p><button id="submit">验证并完成登录</button></p>
233
+ <p id="submit-status" class="status" role="status" aria-live="polite"></p>
234
+ <p>Cookie 只保存在本机的 Gemini Web 后端里,不会发到别处。完成后<b>直接关闭无痕窗口,不要点「退出登录」</b>(退出会让这份 Cookie 失效)。</p>
235
+
236
+ <script nonce="NONCE">
237
+ const base = location.pathname;
238
+ const openBtn = document.getElementById('open');
239
+ const openStatus = document.getElementById('open-status');
240
+ const manual = document.getElementById('manual');
241
+ const submitBtn = document.getElementById('submit');
242
+ const submitStatus = document.getElementById('submit-status');
243
+ const cancelBtn = document.getElementById('cancel');
244
+ let done = false;
245
+
246
+ async function post(route, data) {
247
+ const res = await fetch(base + route, {
248
+ method: 'POST',
249
+ headers: { 'Content-Type': 'application/json' },
250
+ body: JSON.stringify(data || {})
251
+ });
252
+ const body = res.status === 204 ? null : await res.json().catch(() => null);
253
+ // 410 means the session is over (cancel, timeout, Magpie gave up): nothing on the page can
254
+ // still change that, and a retried submit would be refused the same way.
255
+ if (res.status === 410) {
256
+ done = true;
257
+ submitBtn.disabled = openBtn.disabled = true;
258
+ throw new Error((body && body.error) || '登录已经结束,请回到 Magpie 重新发起登录。');
259
+ }
260
+ if (!res.ok) throw new Error((body && body.error) || '本地服务暂时不可用,请重试。');
261
+ return body;
262
+ }
263
+
264
+ openBtn.onclick = async () => {
265
+ openBtn.disabled = true;
266
+ openStatus.className = 'status';
267
+ try {
268
+ const r = await post('/open-private');
269
+ // The manual link stays visible either way: an opened window may be hidden behind others
270
+ // (or refused by an already-running Firefox on macOS), and 'opened: false' explains itself.
271
+ if (r && r.opened) {
272
+ openStatus.textContent = '已用 ' + r.browser + ' 打开无痕窗口。如果窗口没有弹到最前,请在任务栏 / Dock 里找到它,或使用下方链接手动打开。';
273
+ } else {
274
+ openStatus.textContent = (r && r.reason) || '没有找到可启动无痕窗口的浏览器。';
275
+ }
276
+ } catch (err) {
277
+ openStatus.className = 'status error';
278
+ openStatus.textContent = err.message;
279
+ } finally {
280
+ if (!done) openBtn.disabled = false;
281
+ }
282
+ };
283
+
284
+ submitBtn.onclick = async () => {
285
+ submitBtn.disabled = true;
286
+ submitStatus.className = 'status';
287
+ submitStatus.textContent = '正在验证登录…首次使用会先下载并启动本地后端,可能需要几分钟,请不要关闭本页。';
288
+ try {
289
+ const r = await post('/submit', {
290
+ cookie: document.getElementById('cookie').value,
291
+ authuser: document.getElementById('authuser').value,
292
+ proxy: document.getElementById('proxy').value
293
+ });
294
+ done = true;
295
+ submitStatus.className = 'status ok';
296
+ submitStatus.textContent = '登录成功' + (r && r.email ? ',已绑定 ' + r.email : '') + '。现在可以关闭无痕窗口和本页面,回到 Magpie 使用。';
297
+ submitBtn.hidden = true;
298
+ openBtn.disabled = true;
299
+ } catch (err) {
300
+ // An in-place retry is only offered while the session still lives: once done is set
301
+ // (submit succeeded, cancel clicked, or the server answered 410) the form stays down.
302
+ if (done) {
303
+ submitStatus.className = 'status';
304
+ submitStatus.textContent = err.message;
305
+ } else {
306
+ submitStatus.className = 'status error';
307
+ submitStatus.textContent = err.message + '(可修改上方内容后直接重试)';
308
+ }
309
+ } finally {
310
+ if (!done) submitBtn.disabled = false;
311
+ }
312
+ };
313
+
314
+ cancelBtn.onclick = async () => {
315
+ cancelBtn.disabled = true;
316
+ // The session is over the moment the user asks: lock the form now so a submit already in
317
+ // flight cannot light the fields back up or offer a retry that the server would refuse.
318
+ done = true;
319
+ submitBtn.disabled = openBtn.disabled = true;
320
+ try { await post('/cancel'); } catch {}
321
+ submitStatus.className = 'status';
322
+ submitStatus.textContent = '已取消登录,可以关闭本页面。';
323
+ };
324
+
325
+ // If the session ends another way (timeout, Magpie giving up), say so instead of hanging.
326
+ async function poll() {
327
+ if (done) return;
328
+ try {
329
+ const r = await fetch(base + '/state', { cache: 'no-store' });
330
+ if (!r.ok) return;
331
+ const state = await r.json();
332
+ if (state.done) {
333
+ done = true;
334
+ submitBtn.disabled = openBtn.disabled = true;
335
+ submitStatus.className = 'status ' + (state.error ? 'error' : 'ok');
336
+ submitStatus.textContent = state.error || '登录已完成,可以关闭本页面。';
337
+ return;
338
+ }
339
+ } catch { return; }
340
+ setTimeout(poll, 2000);
341
+ }
342
+ poll();
343
+ </script></body></html>`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dorokuma/magpie-gemini-web",
3
- "version": "0.18.0",
3
+ "version": "0.18.2",
4
4
  "description": "Google AI Studio and Gemini Web provider for Magpie (Gemini 4 Neon / Carbon / Hydrogen in Chat & Task modes, Nano Banana image generation, Deep Research), backed by AIStudio2API and gemini-web2api-go",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -93,6 +93,11 @@
93
93
  },
94
94
  "magpie": {
95
95
  "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ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