magpie-gemini-web 0.4.0 → 0.5.0

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,377 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+ import {
6
+ studioDataDir,
7
+ localStudio,
8
+ installStudio,
9
+ ensureStudio,
10
+ studioAdmin,
11
+ studioAccounts,
12
+ stopStudio,
13
+ studioStatus,
14
+ validateConfig,
15
+ validateProxy,
16
+ generateEnv,
17
+ studioCommand
18
+ } from '../lib/studio-native.mjs';
19
+
20
+ const LOGIN_TIMEOUT_MS = 15 * 60 * 1000;
21
+
22
+ function printHelp() {
23
+ console.log(`magpie-gemini-web AI Studio management CLI
24
+
25
+ Usage:
26
+ node scripts/studio.mjs <command> [options]
27
+
28
+ Commands:
29
+ install [--archive <path>] [--proxy <url>] Install AIStudio2API binary and configure environment
30
+ start [--proxy <url>] Start local AIStudio2API service in the background
31
+ status Check service and accounts status
32
+ stop Stop local AIStudio2API service
33
+ login Open isolated browser login for a new Google account
34
+ relogin [<account>] Sign an account that needs it in again (its label or id)
35
+ import <auth-directory> Import accounts from an existing auth directory (service must be stopped)
36
+
37
+ Options:
38
+ --data-dir <path> Custom data directory
39
+ --proxy <url> HTTP, HTTPS, or SOCKS5 proxy URL
40
+ --archive <path> Local release archive file (.tar.gz or .zip)
41
+ `);
42
+ }
43
+
44
+ function parseArgs(args) {
45
+ const flags = { _: [] };
46
+ for (let i = 0; i < args.length; i++) {
47
+ const arg = args[i];
48
+ if (arg === '--help' || arg === '-h') {
49
+ flags.help = true;
50
+ } else if (arg === '--data-dir' || arg === '--proxy' || arg === '--archive') {
51
+ const next = args[i + 1];
52
+ if (!next || next.startsWith('--')) {
53
+ throw new Error(`Missing required value for option: ${arg}`);
54
+ }
55
+ const key = arg.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
56
+ flags[key] = args[++i];
57
+ } else if (arg.startsWith('--')) {
58
+ throw new Error(`Unknown option: ${arg}`);
59
+ } else {
60
+ flags._.push(arg);
61
+ }
62
+ }
63
+ return flags;
64
+ }
65
+
66
+ async function updateProxyConfig(dataDir, proxy) {
67
+ const configPath = path.join(dataDir, 'config.json');
68
+ if (!fs.existsSync(configPath)) return;
69
+ const config = validateConfig(JSON.parse(fs.readFileSync(configPath, 'utf8')));
70
+ config.proxy = validateProxy(proxy);
71
+ const tmp = `${configPath}.tmp.${Date.now()}.${crypto.randomBytes(4).toString('hex')}`;
72
+ fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
73
+ fs.renameSync(tmp, configPath);
74
+ fs.chmodSync(configPath, 0o600);
75
+
76
+ const envPath = path.join(dataDir, '.env');
77
+ const envContent = generateEnv(dataDir, config, { proxy: config.proxy });
78
+ const tmpEnv = `${envPath}.tmp.${Date.now()}.${crypto.randomBytes(4).toString('hex')}`;
79
+ fs.writeFileSync(tmpEnv, envContent, { mode: 0o600 });
80
+ fs.renameSync(tmpEnv, envPath);
81
+ fs.chmodSync(envPath, 0o600);
82
+ }
83
+
84
+ function validateStorageState(filePath) {
85
+ let content;
86
+ try {
87
+ content = JSON.parse(fs.readFileSync(filePath, 'utf8'));
88
+ } catch (err) {
89
+ throw new Error(`Invalid JSON in ${filePath}: ${err.message}`);
90
+ }
91
+
92
+ if (!content || typeof content !== 'object' || !Array.isArray(content.cookies) || !Array.isArray(content.origins)) {
93
+ throw new Error(`${filePath} must be an object with cookies and origins arrays`);
94
+ }
95
+
96
+ let hasAuthCookie = false;
97
+ for (const c of content.cookies) {
98
+ if (!c || typeof c !== 'object') {
99
+ throw new Error(`Invalid cookie entry in ${filePath}`);
100
+ }
101
+ if (typeof c.name !== 'string' || !c.name || typeof c.value !== 'string' || typeof c.domain !== 'string' || !c.domain) {
102
+ throw new Error(`Invalid cookie properties in ${filePath}`);
103
+ }
104
+ if (c.name === 'SAPISID' || c.name === '__Secure-3PAPISID') {
105
+ if (c.value.trim().length > 0) hasAuthCookie = true;
106
+ }
107
+ }
108
+
109
+ if (!hasAuthCookie) {
110
+ throw new Error(`${filePath} does not contain valid Google auth cookies (missing SAPISID or __Secure-3PAPISID)`);
111
+ }
112
+ }
113
+
114
+ async function main() {
115
+ const flags = parseArgs(process.argv.slice(2));
116
+ if (flags.help || flags._.length === 0) {
117
+ printHelp();
118
+ return;
119
+ }
120
+
121
+ const command = flags._[0];
122
+ const dataDir = flags.dataDir || studioDataDir();
123
+
124
+ switch (command) {
125
+ case 'install': {
126
+ const status = await studioStatus({ dataDir });
127
+ if (status.status === 'running' || status.status === 'outdated' || status.status === 'unresponsive') {
128
+ throw new Error('Cannot install or update AI Studio while service is running. Stop the service first.');
129
+ }
130
+ if (flags.proxy !== undefined) {
131
+ await updateProxyConfig(dataDir, flags.proxy);
132
+ }
133
+ console.log(`Installing AIStudio2API into ${dataDir}...`);
134
+ const local = await installStudio({
135
+ dataDir,
136
+ archivePath: flags.archive,
137
+ proxy: flags.proxy
138
+ });
139
+ console.log(`AIStudio2API installed successfully.`);
140
+ console.log(`Listen origin: ${local.origin}`);
141
+ console.log(`Data directory: ${local.dataDir}`);
142
+ break;
143
+ }
144
+ case 'start': {
145
+ const status = await studioStatus({ dataDir });
146
+ if (status.status === 'running') {
147
+ if (flags.proxy !== undefined) {
148
+ throw new Error('Cannot update proxy while service is running. Stop the service first.');
149
+ }
150
+ const local = await ensureStudio({ dataDir });
151
+ console.log(`AIStudio2API service is running.`);
152
+ console.log(`API Base URL: ${local.baseURL}`);
153
+ console.log(`Management URL: ${local.origin}`);
154
+ return;
155
+ }
156
+ if (flags.proxy !== undefined) {
157
+ await updateProxyConfig(dataDir, flags.proxy);
158
+ }
159
+ if (status.status === 'outdated') {
160
+ console.log(`Replacing AIStudio2API ${status.version} from an earlier install with ${status.expected}...`);
161
+ }
162
+ console.log(`Starting AIStudio2API service in ${dataDir}...`);
163
+ const local = await ensureStudio({ dataDir, proxy: flags.proxy });
164
+ console.log(`AIStudio2API service is running.`);
165
+ console.log(`API Base URL: ${local.baseURL}`);
166
+ console.log(`Management URL: ${local.origin}`);
167
+ break;
168
+ }
169
+ case 'status': {
170
+ const status = await studioStatus({ dataDir });
171
+ console.log(`Service status: ${status.status}`);
172
+ if (status.status === 'running') {
173
+ console.log(`State: ${status.state || 'RUNNING'}`);
174
+ console.log(`Listen port: ${status.port}`);
175
+ console.log(`Accounts: ready=${status.accounts?.ready ?? 0}, total=${status.accounts?.total ?? 0}`);
176
+ const accounts = await studioAccounts({ dataDir });
177
+ if (accounts.length > 0) {
178
+ console.log(`Enabled accounts:`);
179
+ for (const a of accounts) {
180
+ console.log(` - ${a.label || a.id} (${a.state || 'active'})`);
181
+ }
182
+ }
183
+ } else if (status.status === 'outdated') {
184
+ console.log(`Running version: ${status.version} from an earlier install (this plugin uses ${status.expected})`);
185
+ console.log(`To replace it, run: ${studioCommand('start')}`);
186
+ console.log(`To stop it, run: ${studioCommand('stop')}`);
187
+ } else if (status.status === 'unresponsive') {
188
+ console.log(`Port ${status.port} answers but not properly (${status.reason})`);
189
+ console.log(`If the service is stuck, run: ${studioCommand('stop')}`);
190
+ } else if (status.status === 'foreign') {
191
+ console.log(`Warning: Foreign listener on port ${status.port} (${status.reason})`);
192
+ } else {
193
+ console.log(`Data directory: ${status.dataDir}`);
194
+ }
195
+ break;
196
+ }
197
+ case 'stop': {
198
+ console.log(`Stopping AIStudio2API service in ${dataDir}...`);
199
+ const res = await stopStudio({ dataDir });
200
+ if (!res.stopped) {
201
+ throw new Error(res.reported || 'Failed to stop AI Studio service');
202
+ }
203
+ console.log(`AIStudio2API service stopped.`);
204
+ break;
205
+ }
206
+ case 'login': {
207
+ console.log(`Preparing login...`);
208
+ const local = await ensureStudio({ dataDir, managementOnly: true });
209
+ console.log(`Opening isolated browser window for Google AI Studio login...`);
210
+ const res = await studioAdmin(local, 'POST', '/api/accounts', {}, { timeoutMs: LOGIN_TIMEOUT_MS });
211
+ const account = res?.account || res;
212
+ console.log(`Login completed successfully.`);
213
+ console.log(`Account: ${account.label || account.id || 'new'}`);
214
+ break;
215
+ }
216
+ case 'relogin': {
217
+ const local = await ensureStudio({ dataDir, managementOnly: true });
218
+ const expired = (await studioAccounts({ dataDir })).filter(a => a.state === 'auth_required');
219
+ if (!expired.length) {
220
+ console.log('No account needs to sign in again.');
221
+ return;
222
+ }
223
+ const wanted = flags._[1];
224
+ const chosen = wanted
225
+ ? expired.find(a => a.id === wanted || a.label === wanted)
226
+ : expired.length === 1 ? expired[0] : undefined;
227
+ if (!chosen) {
228
+ const names = expired.map(a => a.label || a.id).join(', ');
229
+ throw new Error(wanted
230
+ ? `${wanted} doesn't need to sign in again; these do: ${names}`
231
+ : `Several accounts need to sign in again; name one: ${studioCommand('relogin <account>')} (${names})`);
232
+ }
233
+ console.log(`Opening isolated browser window to sign ${chosen.label || chosen.id} in again...`);
234
+ const res = await studioAdmin(local, 'POST', `/api/accounts/${encodeURIComponent(chosen.id)}/login`, {}, { timeoutMs: LOGIN_TIMEOUT_MS });
235
+ const account = res?.account || chosen;
236
+ console.log(`Signed in again: ${account.label || account.id} (${account.state || 'unknown'})`);
237
+ break;
238
+ }
239
+ case 'import': {
240
+ const sourceDir = flags._[1];
241
+ if (!sourceDir) {
242
+ throw new Error('Usage: node scripts/studio.mjs import <auth-directory>');
243
+ }
244
+ const resolvedSource = path.resolve(sourceDir);
245
+ if (!fs.existsSync(resolvedSource)) {
246
+ throw new Error(`Source auth directory not found: ${resolvedSource}`);
247
+ }
248
+ const srcLstat = fs.lstatSync(resolvedSource);
249
+ if (srcLstat.isSymbolicLink() || !srcLstat.isDirectory()) {
250
+ throw new Error(`Source auth directory must be a regular directory: ${resolvedSource}`);
251
+ }
252
+
253
+ const status = await studioStatus({ dataDir });
254
+ if (status.status === 'foreign') {
255
+ throw new Error(`Port ${status.port} is occupied by an unknown/foreign listener. Cannot import accounts.`);
256
+ }
257
+ if (status.status !== 'stopped' && status.status !== 'not_installed') {
258
+ throw new Error('Service is currently running. Stop the AI Studio service before importing accounts.');
259
+ }
260
+
261
+ const entries = fs.readdirSync(resolvedSource);
262
+ const accountDirs = [];
263
+ for (const entryName of entries) {
264
+ const fullEntry = path.join(resolvedSource, entryName);
265
+ const lstat = fs.lstatSync(fullEntry);
266
+ if (lstat.isSymbolicLink()) {
267
+ throw new Error(`Symlink rejected in source directory: ${fullEntry}`);
268
+ }
269
+ if (!lstat.isDirectory()) continue;
270
+
271
+ const storageState = path.join(fullEntry, 'storage-state.json');
272
+ if (!fs.existsSync(storageState)) continue;
273
+ const stateLstat = fs.lstatSync(storageState);
274
+ if (stateLstat.isSymbolicLink() || !stateLstat.isFile()) {
275
+ throw new Error(`storage-state.json must be a regular file: ${storageState}`);
276
+ }
277
+
278
+ validateStorageState(storageState);
279
+ accountDirs.push(entryName);
280
+ }
281
+
282
+ if (accountDirs.length === 0) {
283
+ throw new Error(`No account directories with valid storage-state.json found in ${resolvedSource}`);
284
+ }
285
+
286
+ const destAuthDir = path.join(dataDir, 'auth');
287
+ fs.mkdirSync(destAuthDir, { recursive: true, mode: 0o700 });
288
+ fs.chmodSync(destAuthDir, 0o700);
289
+
290
+ // Preflight ALL conflicts across all accounts before writing
291
+ for (const dirName of accountDirs) {
292
+ const srcAccPath = path.join(resolvedSource, dirName);
293
+ const destAccPath = path.join(destAuthDir, dirName);
294
+
295
+ if (fs.existsSync(destAccPath) && fs.lstatSync(destAccPath).isSymbolicLink()) {
296
+ throw new Error(`Destination account directory is a symlink: ${destAccPath}`);
297
+ }
298
+
299
+ const files = fs.readdirSync(srcAccPath);
300
+ for (const f of files) {
301
+ const srcFile = path.join(srcAccPath, f);
302
+ const flstat = fs.lstatSync(srcFile);
303
+ if (flstat.isSymbolicLink() || !flstat.isFile()) {
304
+ throw new Error(`Non-regular file or symlink in account directory rejected: ${srcFile}`);
305
+ }
306
+
307
+ if (fs.existsSync(destAccPath)) {
308
+ const destFile = path.join(destAccPath, f);
309
+ if (fs.existsSync(destFile)) {
310
+ if (fs.lstatSync(destFile).isSymbolicLink() || !fs.lstatSync(destFile).isFile()) {
311
+ throw new Error(`Destination file is not a regular file: ${destFile}`);
312
+ }
313
+ const srcBytes = fs.readFileSync(srcFile);
314
+ const destBytes = fs.readFileSync(destFile);
315
+ if (!srcBytes.equals(destBytes)) {
316
+ throw new Error(`Conflict: ${f} in account ${dirName} already exists with different contents. Overwrite refused.`);
317
+ }
318
+ }
319
+ }
320
+ }
321
+ }
322
+
323
+ // Safe stage-and-copy
324
+ const stageBase = path.join(dataDir, `.import.tmp.${crypto.randomBytes(4).toString('hex')}`);
325
+ fs.mkdirSync(stageBase, { recursive: true, mode: 0o700 });
326
+
327
+ let importedCount = 0;
328
+ try {
329
+ for (const dirName of accountDirs) {
330
+ const srcAccPath = path.join(resolvedSource, dirName);
331
+ const destAccPath = path.join(destAuthDir, dirName);
332
+ const stageAccPath = path.join(stageBase, dirName);
333
+ fs.mkdirSync(stageAccPath, { recursive: true, mode: 0o700 });
334
+ fs.chmodSync(stageAccPath, 0o700);
335
+
336
+ const files = fs.readdirSync(srcAccPath);
337
+ for (const f of files) {
338
+ const srcFile = path.join(srcAccPath, f);
339
+ const stageFile = path.join(stageAccPath, f);
340
+ const srcBytes = fs.readFileSync(srcFile);
341
+ fs.writeFileSync(stageFile, srcBytes, { mode: 0o600 });
342
+ fs.chmodSync(stageFile, 0o600);
343
+ }
344
+
345
+ if (!fs.existsSync(destAccPath)) {
346
+ fs.renameSync(stageAccPath, destAccPath);
347
+ fs.chmodSync(destAccPath, 0o700);
348
+ } else {
349
+ // Already existed with verified identical bytes, ensure modes
350
+ for (const f of files) {
351
+ const destFile = path.join(destAccPath, f);
352
+ if (!fs.existsSync(destFile)) {
353
+ fs.copyFileSync(path.join(stageAccPath, f), destFile);
354
+ }
355
+ fs.chmodSync(destFile, 0o600);
356
+ }
357
+ fs.chmodSync(destAccPath, 0o700);
358
+ }
359
+ importedCount++;
360
+ console.log(`Imported account: ${dirName}`);
361
+ }
362
+ } finally {
363
+ fs.rmSync(stageBase, { recursive: true, force: true });
364
+ }
365
+
366
+ console.log(`Successfully imported ${importedCount} account(s) into ${destAuthDir}.`);
367
+ break;
368
+ }
369
+ default:
370
+ throw new Error(`Unknown command: ${command}`);
371
+ }
372
+ }
373
+
374
+ main().catch(err => {
375
+ console.error(`Error: ${err.message}`);
376
+ process.exitCode = 1;
377
+ });