@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.
package/lib/native.mjs CHANGED
@@ -171,7 +171,7 @@ export async function installBackend(options = {}) {
171
171
  }
172
172
  }
173
173
 
174
- const files = ensureDataFiles(dataDir);
174
+ const files = ensureDataFiles(dataDir, options.rateLimit);
175
175
  // A local custom build keeps the user's channel. Official installs record their
176
176
  // selection only after verification and replacement succeeded.
177
177
  if ((!options.expectedHash && !options.url) || options.channel !== undefined) saveBackendChannel(dataDir, channel);
@@ -180,7 +180,12 @@ export async function installBackend(options = {}) {
180
180
  }
181
181
 
182
182
  // ensureDataFiles creates config.json and secrets.json when missing; existing ones are kept.
183
- function ensureDataFiles(dataDir) {
183
+ // rateLimit carries the per_ip_* limits declared in the plugin options: a new config.json
184
+ // records them, and an existing one is merged key by key only when a passed value differs,
185
+ // so port, multi_turn and every other field the user set stay exactly as they were.
186
+ const RATE_LIMIT_CONFIG_KEYS = ['per_ip_concurrent', 'per_ip_rpm', 'per_ip_rph'];
187
+
188
+ function ensureDataFiles(dataDir, rateLimit = {}) {
184
189
  const configPath = path.join(dataDir, 'config.json');
185
190
  if (!fs.existsSync(configPath)) {
186
191
  const defaultConfig = {
@@ -193,10 +198,13 @@ function ensureDataFiles(dataDir) {
193
198
  // 索引残片);auto_delete 让后端收尾统一 GzXR5e 删掉,双保险。
194
199
  auto_delete_conversation: true
195
200
  };
196
- fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2) + '\n', { mode: 0o600 });
197
- fs.chmodSync(configPath, 0o600);
201
+ for (const key of RATE_LIMIT_CONFIG_KEYS) {
202
+ if (rateLimit[key] !== undefined) defaultConfig[key] = rateLimit[key];
203
+ }
204
+ writeJsonFile(configPath, defaultConfig);
198
205
  console.log(`Created default config: ${configPath}`);
199
206
  } else {
207
+ mergeRateLimitConfig(configPath, rateLimit);
200
208
  fs.chmodSync(configPath, 0o600);
201
209
  }
202
210
 
@@ -216,6 +224,36 @@ function ensureDataFiles(dataDir) {
216
224
  return { configPath, secretsPath };
217
225
  }
218
226
 
227
+ // writeJsonFile replaces file atomically (temp file + rename) with 0600 permissions.
228
+ function writeJsonFile(file, data) {
229
+ const temp = `${file}.${crypto.randomBytes(4).toString('hex')}.tmp`;
230
+ try {
231
+ fs.writeFileSync(temp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
232
+ fs.renameSync(temp, file);
233
+ } finally {
234
+ fs.rmSync(temp, { force: true });
235
+ }
236
+ fs.chmodSync(file, 0o600);
237
+ }
238
+
239
+ // mergeRateLimitConfig rewrites configPath only when a passed rateLimit value differs from
240
+ // what is already stored; a file that fails to parse is left untouched and the caller's
241
+ // own error handling decides.
242
+ function mergeRateLimitConfig(configPath, rateLimit) {
243
+ const wanted = RATE_LIMIT_CONFIG_KEYS.filter(key => rateLimit[key] !== undefined);
244
+ if (!wanted.length) return;
245
+ let config;
246
+ try {
247
+ config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
248
+ } catch {
249
+ return;
250
+ }
251
+ if (!config || typeof config !== 'object' || Array.isArray(config)) return;
252
+ if (!wanted.some(key => config[key] !== rateLimit[key])) return;
253
+ for (const key of wanted) config[key] = rateLimit[key];
254
+ writeJsonFile(configPath, config);
255
+ }
256
+
219
257
  export function startBackend(options = {}) {
220
258
  const dataDir = options.dataDir || getDataDir();
221
259
  const expectedHash = options.expectedHash || pinnedBinary(process.platform, process.arch, backendChannel(dataDir)).sha256;
@@ -376,6 +414,62 @@ async function backendState(setup, fetchFn) {
376
414
  return res.ok ? 'up' : 'foreign';
377
415
  }
378
416
 
417
+ // syncBackendRateLimit applies the plugin's per_ip_* limits to a healthy managed backend
418
+ // through its admin API: GET the full runtime config, PUT it back with only the passed
419
+ // limits changed (PUT persists to the backend's runtime_config store and takes effect at
420
+ // once). Values already matching skip the PUT; a missing adminToken or a non-2xx answer
421
+ // fails loudly instead of leaving the impression the limits applied.
422
+ async function syncBackendRateLimit(setup, rateLimit, fetchFn) {
423
+ const wanted = Object.entries(rateLimit || {}).filter(([, v]) => v !== undefined);
424
+ if (!wanted.length) return;
425
+ if (typeof setup.adminToken !== 'string' || !setup.adminToken) {
426
+ throw new Error(`Cannot apply per-IP rate limits to ${setup.origin}: the managed backend has no admin token`);
427
+ }
428
+ const url = `${setup.origin}/admin/api/config`;
429
+ const headers = { Authorization: `Bearer ${setup.adminToken}` };
430
+ let res;
431
+ try {
432
+ res = await fetchFn(url, { headers, signal: AbortSignal.timeout(5000) });
433
+ } catch (err) {
434
+ throw new Error(`Cannot apply per-IP rate limits to ${setup.origin}: failed to read runtime config: ${err?.message || err}`);
435
+ }
436
+ if (!res.ok) {
437
+ throw new Error(`Cannot apply per-IP rate limits to ${setup.origin}: GET /admin/api/config returned HTTP ${res.status}`);
438
+ }
439
+ let body;
440
+ try {
441
+ body = await res.json();
442
+ } catch {
443
+ throw new Error(`Cannot apply per-IP rate limits to ${setup.origin}: invalid runtime config response`);
444
+ }
445
+ const config = body?.config;
446
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
447
+ throw new Error(`Cannot apply per-IP rate limits to ${setup.origin}: runtime config response has no "config" object`);
448
+ }
449
+ if (!wanted.some(([key, value]) => config[key] !== value)) return;
450
+ const next = { ...config };
451
+ for (const [key, value] of wanted) next[key] = value;
452
+ let put;
453
+ try {
454
+ put = await fetchFn(url, {
455
+ method: 'PUT',
456
+ headers: { ...headers, 'Content-Type': 'application/json' },
457
+ body: JSON.stringify(next),
458
+ signal: AbortSignal.timeout(5000)
459
+ });
460
+ } catch (err) {
461
+ throw new Error(`Cannot apply per-IP rate limits to ${setup.origin}: failed to write runtime config: ${err?.message || err}`);
462
+ }
463
+ if (!put.ok) {
464
+ let detail = '';
465
+ try {
466
+ const errBody = await put.json();
467
+ if (typeof errBody?.error === 'string') detail = `: ${errBody.error}`;
468
+ } catch {}
469
+ throw new Error(`Cannot apply per-IP rate limits to ${setup.origin}: PUT /admin/api/config returned HTTP ${put.status}${detail}`);
470
+ }
471
+ }
472
+
379
473
 
380
474
  // backendVersion asks the backend at setup for its self-reported version (the same string
381
475
  // --version prints). Returns null when the backend is down, foreign, or too old to answer.
@@ -555,6 +649,17 @@ export async function ensureBackend(options = {}) {
555
649
  const spawnFn = options.spawnFn || spawn;
556
650
  const verify = options.verifyIdentity || verifyProcessIdentity;
557
651
  const startTimeoutMs = options.startTimeoutMs ?? 20000;
652
+ const rateLimit = options.rateLimit;
653
+
654
+ // A healthy managed backend gets the plugin's per_ip_* limits synced into its live
655
+ // runtime config (see syncBackendRateLimit below); once the hot apply succeeded the
656
+ // same keys are merged into the on-disk config.json so a later cold start keeps them.
657
+ const settle = async () => {
658
+ await syncBackendRateLimit(setup, rateLimit, fetchFn);
659
+ if (rateLimit && RATE_LIMIT_CONFIG_KEYS.some(key => rateLimit[key] !== undefined)) {
660
+ ensureDataFiles(dataDir, rateLimit);
661
+ }
662
+ };
558
663
 
559
664
  // Adoption is version-aware. A healthy backend is only reused when it reports the version
560
665
  // the binary on disk should run; a stale one — including the case where it answers with a
@@ -581,15 +686,16 @@ export async function ensureBackend(options = {}) {
581
686
  const state = await backendState(setup, fetchFn);
582
687
  if (state === 'up') {
583
688
  const verdict = binTrusted ? await matchesExpected() : 'stale';
584
- if (verdict === 'match' || verdict === 'unknown') return setup;
689
+ if (verdict === 'match' || verdict === 'unknown') { await settle(); return setup; }
585
690
  // Version mismatch or untrusted binary: kill whatever holds the port before the
586
691
  // pinned build is installed and respawned. Nothing killed = the listener is not
587
692
  // ours to swap, so keep adopting rather than break a working install.
588
693
  const killed = await stopStaleBackend(setup, dataDir, platform, verify, fetchFn);
589
- if (!killed) return setup;
694
+ if (!killed) { await settle(); return setup; }
590
695
  if (await backendState(setup, fetchFn) === 'up') {
591
696
  // Port still claimed by something we could not identify; never stack a second
592
697
  // backend behind it.
698
+ await settle();
593
699
  return setup;
594
700
  }
595
701
  } else if (state === 'foreign' && fs.existsSync(binPath)) {
@@ -608,16 +714,16 @@ export async function ensureBackend(options = {}) {
608
714
  }
609
715
  if (after === 'up') {
610
716
  const verdict = binTrusted ? await matchesExpected() : 'stale';
611
- if (verdict === 'match' || verdict === 'unknown') return setup;
717
+ if (verdict === 'match' || verdict === 'unknown') { await settle(); return setup; }
612
718
  await stopStaleBackend(setup, dataDir, platform, verify, fetchFn);
613
719
  }
614
720
  }
615
721
  }
616
722
 
617
723
  if (!binTrusted) {
618
- await installBackend({ dataDir, platform, arch, fetchFn, channel: backendChannel(dataDir), proxy: options.proxy });
724
+ await installBackend({ dataDir, platform, arch, fetchFn, channel: backendChannel(dataDir), proxy: options.proxy, rateLimit });
619
725
  } else {
620
- ensureDataFiles(dataDir);
726
+ ensureDataFiles(dataDir, rateLimit);
621
727
  }
622
728
  setup = readLocalSetup(dataDir);
623
729
  if (!setup) throw new Error(`Invalid Gemini Web backend config in ${dataDir}`);
@@ -645,7 +751,10 @@ export async function ensureBackend(options = {}) {
645
751
 
646
752
  const deadline = Date.now() + startTimeoutMs;
647
753
  while (Date.now() < deadline) {
648
- if (await backendState(setup, fetchFn) === 'up') return setup;
754
+ if (await backendState(setup, fetchFn) === 'up') {
755
+ await settle();
756
+ return setup;
757
+ }
649
758
  await sleep(300);
650
759
  }
651
760
  try { child?.kill?.('SIGTERM'); } catch {}
@@ -0,0 +1,147 @@
1
+ // Launch the Gemini app in a private/incognito browser window. The sign-in session the backend
2
+ // keeps alive must not be shared with the user's daily browser: Google would revoke it on both
3
+ // sides. Firefox is preferred because Chrome's DBSC can re-bind a copied session to a profile
4
+ // the user already closed.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { spawn } from 'node:child_process';
8
+
9
+ const GEMINI_HOST = /^(www\.)?gemini\.google\.com$/i;
10
+ // Firefox takes -private-window on macOS/Windows and --private-window on Linux; both spellings
11
+ // work everywhere, but each platform's conventional one is used.
12
+ const privateArg = { darwin: '-private-window', win32: '-private-window', linux: '--private-window' };
13
+ const PRIVATE_ARG = {
14
+ firefox: platform => privateArg[platform] || '--private-window',
15
+ chromium: '--incognito',
16
+ edge: '--inprivate'
17
+ };
18
+
19
+ // geminiURL restricts launches to the Gemini app: the wizard only ever sends users to Google,
20
+ // and a token-guessed local page must not be turned into an open-anything primitive.
21
+ export function geminiURL(value) {
22
+ let parsed;
23
+ try {
24
+ parsed = new URL(String(value ?? ''));
25
+ } catch {
26
+ return null;
27
+ }
28
+ if (parsed.protocol !== 'https:' || !GEMINI_HOST.test(parsed.hostname) ||
29
+ parsed.username || parsed.password) return null;
30
+ return parsed.href;
31
+ }
32
+
33
+ // Per-platform candidate lists, in priority order: Firefox first, then the Chromium family,
34
+ // Edge last. The first binary that exists wins; args never go through a shell.
35
+ function candidates(platform, env) {
36
+ if (platform === 'darwin') {
37
+ const home = env.HOME || '';
38
+ const app = (browser, appName, binary, flag) => [
39
+ { browser, bin: `/Applications/${appName}.app/Contents/MacOS/${binary}`, flag },
40
+ ...(home ? [{ browser, bin: path.join(home, 'Applications', `${appName}.app`, 'Contents', 'MacOS', binary), flag }] : [])
41
+ ];
42
+ return [
43
+ ...app('Firefox', 'Firefox', 'firefox', PRIVATE_ARG.firefox('darwin')),
44
+ ...app('Google Chrome', 'Google Chrome', 'Google Chrome', PRIVATE_ARG.chromium),
45
+ ...app('Brave', 'Brave Browser', 'Brave Browser', PRIVATE_ARG.chromium),
46
+ ...app('Chromium', 'Chromium', 'Chromium', PRIVATE_ARG.chromium),
47
+ ...app('Microsoft Edge', 'Microsoft Edge', 'Microsoft Edge', PRIVATE_ARG.edge)
48
+ ];
49
+ }
50
+ if (platform === 'win32') {
51
+ const dirs = [env['ProgramFiles'], env['ProgramFiles(x86)'], env.LOCALAPPDATA].filter(Boolean);
52
+ const found = (name, rel, flag) => dirs.map(dir => ({ name, bin: path.join(dir, rel), flag }));
53
+ return [
54
+ ...found('Firefox', path.join('Mozilla Firefox', 'firefox.exe'), PRIVATE_ARG.firefox('win32')),
55
+ ...found('Google Chrome', path.join('Google', 'Chrome', 'Application', 'chrome.exe'), PRIVATE_ARG.chromium),
56
+ ...found('Brave', path.join('BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'), PRIVATE_ARG.chromium),
57
+ ...found('Chromium', path.join('Chromium', 'Application', 'chrome.exe'), PRIVATE_ARG.chromium),
58
+ ...found('Microsoft Edge', path.join('Microsoft', 'Edge', 'Application', 'msedge.exe'), PRIVATE_ARG.edge)
59
+ ].map(c => ({ ...c, browser: c.name }));
60
+ }
61
+ const dirs = (env.PATH || '').split(path.delimiter).filter(Boolean);
62
+ const inPath = (browser, bins, flag) => bins.map(bin => ({ browser, bin, flag, lookup: true, dirs }));
63
+ return [
64
+ ...inPath('Firefox', ['firefox', 'firefox-esr'], PRIVATE_ARG.firefox('linux')),
65
+ ...inPath('Google Chrome', ['google-chrome', 'google-chrome-stable'], PRIVATE_ARG.chromium),
66
+ ...inPath('Chromium', ['chromium', 'chromium-browser'], PRIVATE_ARG.chromium),
67
+ ...inPath('Brave', ['brave-browser'], PRIVATE_ARG.chromium),
68
+ ...inPath('Microsoft Edge', ['microsoft-edge', 'microsoft-edge-stable'], PRIVATE_ARG.edge)
69
+ ];
70
+ }
71
+
72
+ function resolveBin(candidate, existsSync, injected) {
73
+ // With the real filesystem an existing path is not enough: a same-named directory cannot
74
+ // be exec'd, and on POSIX a file without +x fails spawn with EACCES. Both are skipped here
75
+ // so the next candidate still gets its turn. An injected existsSync keeps its plain truth
76
+ // table so unit tests needn't emulate stat/access too.
77
+ const usable = p => {
78
+ if (!existsSync(p)) return false;
79
+ if (injected) return true;
80
+ try {
81
+ if (!fs.statSync(p).isFile()) return false;
82
+ if (process.platform !== 'win32') fs.accessSync(p, fs.constants.X_OK);
83
+ } catch {
84
+ return false;
85
+ }
86
+ return true;
87
+ };
88
+ if (!candidate.lookup) return usable(candidate.bin) ? candidate.bin : null;
89
+ for (const dir of candidate.dirs) {
90
+ const full = path.join(dir, candidate.bin);
91
+ if (usable(full)) return full;
92
+ }
93
+ return null;
94
+ }
95
+
96
+ // launchPrivateBrowser spawns the first detected browser detached so the window outlives the
97
+ // plugin process. deps injects platform/env/existsSync/spawn so tests never open a real window.
98
+ // It is async because spawn() reports a bad binary asynchronously ('error' on the next tick):
99
+ // catching it synchronously both crashed the host on an unhandled 'error' and reported a
100
+ // phantom success instead of falling through to the next candidate.
101
+ export async function launchPrivateBrowser(url, deps = {}) {
102
+ const target = geminiURL(url);
103
+ if (!target) return { opened: false, reason: '只允许打开 https://gemini.google.com/ 的链接' };
104
+ const env = deps.env || process.env;
105
+ const injected = typeof deps.existsSync === 'function';
106
+ const existsSync = injected ? deps.existsSync : (p => fs.existsSync(p));
107
+ const spawnFn = deps.spawn || spawn;
108
+ for (const candidate of candidates(deps.platform || process.platform, env)) {
109
+ const bin = resolveBin(candidate, existsSync, injected);
110
+ if (!bin) continue;
111
+ let child;
112
+ try {
113
+ child = spawnFn(bin, [candidate.flag, target], { detached: true, stdio: 'ignore' });
114
+ } catch {
115
+ // A binary that exists but cannot spawn (broken install, permissions) is skipped the
116
+ // same as one that was never found; the next candidate still gets its turn.
117
+ continue;
118
+ }
119
+ if (typeof child?.once !== 'function') {
120
+ child?.unref?.();
121
+ return { opened: true, browser: candidate.browser };
122
+ }
123
+ // 'spawn' and 'error' are attached before yielding, so an async ENOENT/EACCES is claimed
124
+ // here and never reaches the process as an unhandled error.
125
+ const opened = await new Promise(resolve => {
126
+ let settled = false;
127
+ const settle = value => {
128
+ if (settled) return;
129
+ settled = true;
130
+ resolve(value);
131
+ };
132
+ child.once('error', () => settle(false));
133
+ child.once('spawn', () => {
134
+ // Keep an error sink after spawn too: a process that spawned may still emit 'error'
135
+ // later (stream failures etc.) and an unhandled one would crash the host.
136
+ child.on('error', () => {});
137
+ settle(true);
138
+ });
139
+ });
140
+ if (opened) {
141
+ child.unref?.();
142
+ return { opened: true, browser: candidate.browser };
143
+ }
144
+ // This binary failed to spawn (async EACCES/ENOENT); try the next candidate.
145
+ }
146
+ return { opened: false, reason: '没有找到可启动无痕窗口的浏览器' };
147
+ }
package/lib/setup.mjs CHANGED
@@ -230,11 +230,13 @@ export async function importCookie(setup, cookie, options = {}) {
230
230
  const authuser = parseAuthuser(options.authuser);
231
231
  const fetchFn = options.fetchFn || globalThis.fetch;
232
232
  await requireLoginBackend(setup, options);
233
+ if (options.isEnded?.()) throw new Error('登录已取消。');
233
234
  let proxyId = Number.isInteger(options.proxyId) ? options.proxyId : undefined;
234
235
  if (options.proxy) {
235
236
  const ensured = await ensureProxy(setup, options.proxy, { fetchFn });
236
237
  if (ensured && Number.isInteger(ensured.id)) proxyId = ensured.id;
237
238
  }
239
+ if (options.isEnded?.()) throw new Error('登录已取消。');
238
240
  const label = options.label || `Magpie ${new Date().toISOString().slice(0, 10)}`;
239
241
  const added = await adminCall(setup, fetchFn, 'POST', 'cookies', {
240
242
  label,
@@ -245,6 +247,13 @@ export async function importCookie(setup, cookie, options = {}) {
245
247
  });
246
248
  if (!Number.isInteger(added.id)) throw new Error('本地后端没有返回新账号的 id');
247
249
 
250
+ // The sign-in may have been cancelled or timed out while the account was being created:
251
+ // remove the account this call just added — never anybody else's — then report the cancel.
252
+ if (options.isEnded?.()) {
253
+ await adminCall(setup, fetchFn, 'DELETE', `cookies/${added.id}`).catch(() => {});
254
+ throw new Error('登录已取消。');
255
+ }
256
+
248
257
  let check;
249
258
  try {
250
259
  check = await adminCall(setup, fetchFn, 'POST', `cookies/${added.id}/check`, undefined,
@@ -253,9 +262,23 @@ export async function importCookie(setup, cookie, options = {}) {
253
262
  await adminCall(setup, fetchFn, 'DELETE', `cookies/${added.id}`).catch(() => {});
254
263
  throw err;
255
264
  }
265
+ // A cancel that arrived while the check was in flight gets the same rollback: the session
266
+ // is over, so the verified account would sit in the pool with nobody signed in to it.
267
+ if (options.isEnded?.()) {
268
+ await adminCall(setup, fetchFn, 'DELETE', `cookies/${added.id}`).catch(() => {});
269
+ throw new Error('登录已取消。');
270
+ }
256
271
  if (!check.ok) {
257
272
  await adminCall(setup, fetchFn, 'DELETE', `cookies/${added.id}`).catch(() => {});
258
273
  throw checkFailure(setup, check.detail || '');
259
274
  }
260
275
  return { id: added.id, detail: check.detail || '' };
261
276
  }
277
+
278
+ // removeAccount deletes one account of the backend's pool by id: the rollback step for a
279
+ // sign-in session that ended after importCookie returned. Its caller created the account and
280
+ // is responsible for never naming anybody else's.
281
+ export async function removeAccount(setup, id, options = {}) {
282
+ const fetchFn = options.fetchFn || globalThis.fetch;
283
+ return adminCall(setup, fetchFn, 'DELETE', `cookies/${id}`);
284
+ }