devpass 0.0.0-stage → 0.1.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.
Files changed (3) hide show
  1. package/README.md +49 -2
  2. package/dist/index.js +1115 -0
  3. package/package.json +45 -4
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # devpass
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Официальный единый CLI экосистемы [DevPass](https://devpass.ru).
4
+
5
+ Использует общую авторизацию DevPass (`~/.config/devpass/credentials.json`) вместе с `runport` и `rundeploy`.
6
+
7
+ ## Настройка Claude Code одной командой
8
+
9
+ ```bash
10
+ npx devpass claude
11
+ ```
12
+
13
+ Что делает команда:
14
+
15
+ 1. Если вы ещё не вошли в DevPass — открывает браузерный вход на `id.devpass.ru`.
16
+ 2. Получает ваш персональный ключ подписки RunGate Claude Code (`sk-rg-cc-...`).
17
+ 3. Аккуратно добавляет `ANTHROPIC_BASE_URL` и `ANTHROPIC_AUTH_TOKEN` в `~/.claude/settings.json` (не затирая существующие настройки и плагины) и выставляет `hasCompletedOnboarding: true` в `~/.claude.json`.
18
+
19
+ ### Подкоманды и опции
20
+
21
+ ```bash
22
+ # Подключить через AI Gateway (оплата по балансу в рублях)
23
+ npx devpass claude --gateway
24
+
25
+ # Проверить локальный конфиг и остаток 5ч/7д лимитов
26
+ npx devpass claude status
27
+
28
+ # Перевыпустить ключ подписки и обновить локальный конфиг
29
+ npx devpass claude regenerate
30
+
31
+ # Удалить переменные RunGate из ~/.claude/settings.json
32
+ npx devpass claude reset
33
+
34
+ # Прописать готовый ключ без обращения к API
35
+ npx devpass claude --key sk-rg-cc-...
36
+ ```
37
+
38
+ ## Аккаунт
39
+
40
+ ```bash
41
+ npx devpass login [dp_live_...] # Единый вход в DevPass
42
+ npx devpass whoami # Текущий пользователь и подписка
43
+ npx devpass logout # Удалить локальные учётные данные
44
+ ```
45
+
46
+ ## Переменные окружения
47
+
48
+ - `DEVPASS_TOKEN` / `DEVPASS_API_KEY` / `RUNGATE_TOKEN` — токен авторизации `dp_live_...`
49
+ - `RUNGATE_API_URL` — URL API RunGate (по умолчанию `https://app.rungate.ru`)
50
+ - `CLAUDE_CONFIG_DIR` — альтернативная директория конфигурации Claude Code (вместо `~/.claude`)
package/dist/index.js ADDED
@@ -0,0 +1,1115 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { parseArgs } from "node:util";
5
+
6
+ // ../core/src/auth.ts
7
+ import { spawn } from "node:child_process";
8
+ import { randomBytes } from "node:crypto";
9
+ import { createServer } from "node:http";
10
+ import { hostname } from "node:os";
11
+ import { stdin as input, stdout as output } from "node:process";
12
+ import { createInterface } from "node:readline/promises";
13
+
14
+ // ../core/src/config.ts
15
+ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
16
+ import { homedir } from "node:os";
17
+ import { join, resolve } from "node:path";
18
+ var DEFAULT_AUTH_URL = "https://id.devpass.ru";
19
+ function getCredentialsPath() {
20
+ const xdgConfig = process.env.XDG_CONFIG_HOME;
21
+ const baseDir = xdgConfig ? resolve(xdgConfig) : join(homedir(), ".config");
22
+ return join(baseDir, "devpass", "credentials.json");
23
+ }
24
+ async function readCredentials() {
25
+ const path = getCredentialsPath();
26
+ try {
27
+ const raw = await readFile(path, "utf8");
28
+ const parsed = JSON.parse(raw);
29
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
30
+ } catch {
31
+ return {};
32
+ }
33
+ }
34
+ async function writeCredentials(creds) {
35
+ const path = getCredentialsPath();
36
+ const dir = resolve(path, "..");
37
+ await mkdir(dir, { recursive: true, mode: 448 });
38
+ const existing = await readCredentials();
39
+ const payload = JSON.stringify({
40
+ ...existing,
41
+ ...creds,
42
+ updatedAt: new Date().toISOString()
43
+ }, null, 2);
44
+ await writeFile(path, `${payload}
45
+ `, { encoding: "utf8", mode: 384 });
46
+ await chmod(path, 384).catch(() => {
47
+ return;
48
+ });
49
+ return path;
50
+ }
51
+ async function clearCredentials() {
52
+ const path = getCredentialsPath();
53
+ await rm(path, { force: true });
54
+ }
55
+ async function resolveAuthToken(explicitToken, extraEnvVars = []) {
56
+ if (explicitToken?.trim())
57
+ return explicitToken.trim();
58
+ for (const envName of extraEnvVars) {
59
+ const val = process.env[envName]?.trim();
60
+ if (val)
61
+ return val;
62
+ }
63
+ if (process.env.DEVPASS_TOKEN?.trim())
64
+ return process.env.DEVPASS_TOKEN.trim();
65
+ if (process.env.DEVPASS_API_KEY?.trim())
66
+ return process.env.DEVPASS_API_KEY.trim();
67
+ const creds = await readCredentials();
68
+ return creds.apiKey?.trim() || null;
69
+ }
70
+ function resolveAuthUrl(explicitAuthUrl) {
71
+ if (explicitAuthUrl?.trim())
72
+ return explicitAuthUrl.trim().replace(/\/+$/, "");
73
+ if (process.env.DEVPASS_AUTH_URL?.trim()) {
74
+ return process.env.DEVPASS_AUTH_URL.trim().replace(/\/+$/, "");
75
+ }
76
+ return DEFAULT_AUTH_URL;
77
+ }
78
+
79
+ // ../core/src/ui.ts
80
+ var useColor = process.stdout.isTTY && !process.env.NO_COLOR && process.env.TERM !== "dumb";
81
+ var wrap = (code, text) => useColor ? `\x1B[${code}m${text}\x1B[0m` : text;
82
+ var c = {
83
+ bold: (s) => wrap("1", s),
84
+ dim: (s) => wrap("2", s),
85
+ green: (s) => wrap("32", s),
86
+ red: (s) => wrap("31", s),
87
+ yellow: (s) => wrap("33", s),
88
+ cyan: (s) => wrap("36", s)
89
+ };
90
+ function printError(message) {
91
+ console.error(`${c.red("Ошибка:")} ${message}`);
92
+ }
93
+
94
+ // ../core/src/auth.ts
95
+ function renderCallbackHtml(params) {
96
+ const accent = params.ok ? "#f59e0b" : "#ef4444";
97
+ const badge = params.ok ? "✓" : "✕";
98
+ return `<!doctype html>
99
+ <html lang="ru">
100
+ <head>
101
+ <meta charset="utf-8" />
102
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
103
+ <title>${params.title} — DevPass CLI</title>
104
+ <style>
105
+ body { margin:0; min-height:100vh; display:flex; align-items:center; justify-content:center;
106
+ background:#0f1014; color:#f3f4f6; font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif; }
107
+ .card { max-width:420px; width:90%; background:#14151b; border:1px solid #252835;
108
+ border-radius:16px; padding:32px; text-align:center; box-shadow:0 20px 50px rgba(0,0,0,0.45); }
109
+ .icon { width:48px; height:48px; margin:0 auto 16px; border-radius:12px; display:flex;
110
+ align-items:center; justify-content:center; font-size:22px; font-weight:700;
111
+ background:${accent}22; color:${accent}; border:1px solid ${accent}44; }
112
+ h1 { font-size:18px; margin:0 0 8px; }
113
+ p { font-size:14px; color:#9ca3af; margin:0; line-height:1.5; }
114
+ </style>
115
+ </head>
116
+ <body>
117
+ <div class="card">
118
+ <div class="icon">${badge}</div>
119
+ <h1>${params.title}</h1>
120
+ <p>${params.message}</p>
121
+ </div>
122
+ </body>
123
+ </html>`;
124
+ }
125
+ async function openBrowser(url) {
126
+ const platform = process.platform;
127
+ let cmd = "xdg-open";
128
+ let args = [url];
129
+ if (platform === "darwin") {
130
+ cmd = "open";
131
+ args = [url];
132
+ } else if (platform === "win32") {
133
+ cmd = "cmd";
134
+ args = ["/c", "start", "", url];
135
+ }
136
+ return new Promise((resolve) => {
137
+ try {
138
+ const child = spawn(cmd, args, {
139
+ detached: true,
140
+ stdio: "ignore"
141
+ });
142
+ child.once("error", () => resolve(false));
143
+ child.once("spawn", () => {
144
+ child.unref();
145
+ resolve(true);
146
+ });
147
+ } catch {
148
+ resolve(false);
149
+ }
150
+ });
151
+ }
152
+ async function loginWithBrowser(options) {
153
+ const authUrl = (options.authUrl || DEFAULT_AUTH_URL).replace(/\/+$/, "");
154
+ const timeoutMs = options.timeoutMs ?? 5 * 60 * 1000;
155
+ const deviceName = options.deviceName || hostname();
156
+ const state = randomBytes(24).toString("hex");
157
+ return new Promise((resolve, reject) => {
158
+ let settled = false;
159
+ let timer;
160
+ const finish = (err, result) => {
161
+ if (settled)
162
+ return;
163
+ settled = true;
164
+ if (timer)
165
+ clearTimeout(timer);
166
+ server.close();
167
+ if (err)
168
+ reject(err);
169
+ else if (result)
170
+ resolve(result);
171
+ };
172
+ const server = createServer(async (req, res) => {
173
+ const reqUrl = new URL(req.url || "/", "http://127.0.0.1");
174
+ if (reqUrl.pathname !== "/callback") {
175
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
176
+ res.end("Not Found");
177
+ return;
178
+ }
179
+ const errorParam = reqUrl.searchParams.get("error");
180
+ const returnedState = reqUrl.searchParams.get("state");
181
+ const code = reqUrl.searchParams.get("code");
182
+ if (errorParam) {
183
+ const html = renderCallbackHtml({
184
+ ok: false,
185
+ title: "Вход отменён",
186
+ message: "Вы отменили авторизацию в браузере. Можете закрыть эту вкладку."
187
+ });
188
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
189
+ res.end(html);
190
+ finish(new Error("Авторизация отменена пользователем."));
191
+ return;
192
+ }
193
+ if (!returnedState || returnedState !== state || !code) {
194
+ const html = renderCallbackHtml({
195
+ ok: false,
196
+ title: "Ошибка проверки",
197
+ message: "Некорректный state или отсутствует код авторизации."
198
+ });
199
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
200
+ res.end(html);
201
+ finish(new Error("Некорректный ответ авторизации (state mismatch или отсутствует code)."));
202
+ return;
203
+ }
204
+ const address = server.address();
205
+ const redirectUri = `http://127.0.0.1:${address.port}/callback`;
206
+ try {
207
+ const tokenRes = await fetch(`${authUrl}/api/v1/cli/token`, {
208
+ method: "POST",
209
+ headers: { "Content-Type": "application/json" },
210
+ body: JSON.stringify({
211
+ code,
212
+ redirectUri,
213
+ deviceName
214
+ })
215
+ });
216
+ const tokenData = await tokenRes.json().catch(() => ({}));
217
+ if (!tokenRes.ok || !tokenData.apiKey || !tokenData.email || !tokenData.userId) {
218
+ throw new Error(tokenData.error || `HTTP ${tokenRes.status}`);
219
+ }
220
+ const html = renderCallbackHtml({
221
+ ok: true,
222
+ title: "Вход выполнен",
223
+ message: `Вы вошли как ${tokenData.email}. Можете закрыть эту вкладку и вернуться в терминал.`
224
+ });
225
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
226
+ res.end(html);
227
+ finish(null, {
228
+ apiKey: tokenData.apiKey,
229
+ email: tokenData.email,
230
+ userId: tokenData.userId
231
+ });
232
+ } catch (err) {
233
+ const message = err instanceof Error ? err.message : "Не удалось получить API-ключ";
234
+ const html = renderCallbackHtml({
235
+ ok: false,
236
+ title: "Ошибка авторизации",
237
+ message
238
+ });
239
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
240
+ res.end(html);
241
+ finish(new Error(message));
242
+ }
243
+ });
244
+ server.on("error", (err) => {
245
+ finish(err instanceof Error ? err : new Error(String(err)));
246
+ });
247
+ server.listen(0, "127.0.0.1", async () => {
248
+ const address = server.address();
249
+ const redirectUri = `http://127.0.0.1:${address.port}/callback`;
250
+ const loginUrl = new URL(`${authUrl}/cli/auth`);
251
+ loginUrl.searchParams.set("redirect_uri", redirectUri);
252
+ loginUrl.searchParams.set("state", state);
253
+ loginUrl.searchParams.set("client", options.client);
254
+ const urlString = loginUrl.toString();
255
+ console.log(`Откройте ссылку в браузере для входа в DevPass:`);
256
+ console.log(` ${c.cyan(urlString)}`);
257
+ const opener = options.openUrl || openBrowser;
258
+ const opened = await opener(urlString);
259
+ if (opened) {
260
+ console.log(c.dim("Браузер открыт. Ожидаем подтверждение..."));
261
+ } else {
262
+ console.log(c.dim("Не удалось открыть браузер автоматически — перейдите по ссылке выше."));
263
+ }
264
+ timer = setTimeout(() => {
265
+ finish(new Error("Истекло время ожидания авторизации в браузере (5 мин)."));
266
+ }, timeoutMs);
267
+ });
268
+ });
269
+ }
270
+ async function promptForToken(authUrl = DEFAULT_AUTH_URL) {
271
+ console.log(`Получите API-ключ (${c.cyan("dp_live_...")}) в настройках профиля: ${c.cyan(authUrl)}`);
272
+ const rl = createInterface({ input, output });
273
+ try {
274
+ return (await rl.question("Введите API-ключ: ")).trim();
275
+ } finally {
276
+ rl.close();
277
+ }
278
+ }
279
+ async function runUnifiedLogin(options) {
280
+ const authUrl = (options.authUrl || DEFAULT_AUTH_URL).replace(/\/+$/, "");
281
+ let token = options.tokenArg?.trim() || options.tokenFlag?.trim();
282
+ let email;
283
+ if (!token) {
284
+ console.log(c.bold(options.title));
285
+ if (options.noBrowser) {
286
+ token = await promptForToken(authUrl);
287
+ } else {
288
+ const res = await loginWithBrowser({
289
+ client: options.client,
290
+ authUrl
291
+ });
292
+ token = res.apiKey;
293
+ email = res.email;
294
+ }
295
+ }
296
+ if (!token) {
297
+ throw new Error("API-ключ не введен.");
298
+ }
299
+ let details;
300
+ if (options.verifyToken) {
301
+ const verified = await options.verifyToken(token);
302
+ email = verified.email || email;
303
+ details = verified.details;
304
+ }
305
+ const savedPath = await writeCredentials({
306
+ apiKey: token,
307
+ email
308
+ });
309
+ console.log(`${c.green("✓")} Вы вошли как ${c.bold(email || "пользователь DevPass")}${details ? ` (${details})` : ""}`);
310
+ console.log(c.dim(`Единый ключ DevPass сохранён в ${savedPath} (действует для всех CLI)`));
311
+ return { token, email, savedPath };
312
+ }
313
+ // src/api.ts
314
+ class ApiError extends Error {
315
+ status;
316
+ code;
317
+ constructor(status, message, code) {
318
+ super(message);
319
+ this.status = status;
320
+ this.code = code;
321
+ }
322
+ }
323
+
324
+ class RunGateClient {
325
+ baseUrl;
326
+ token;
327
+ constructor(params) {
328
+ this.baseUrl = params.baseUrl.replace(/\/+$/, "");
329
+ this.token = params.token;
330
+ }
331
+ async request(path, init = {}) {
332
+ const headers = new Headers(init.headers);
333
+ headers.set("Authorization", `Bearer ${this.token}`);
334
+ if (init.body && !headers.has("Content-Type")) {
335
+ headers.set("Content-Type", "application/json");
336
+ }
337
+ const res = await fetch(`${this.baseUrl}${path}`, {
338
+ ...init,
339
+ headers
340
+ });
341
+ const text = await res.text();
342
+ let json = {};
343
+ if (text) {
344
+ try {
345
+ json = JSON.parse(text);
346
+ } catch {}
347
+ }
348
+ if (!res.ok) {
349
+ const obj = typeof json === "object" && json !== null ? json : {};
350
+ const msg = typeof obj.error === "string" && obj.error || typeof obj.message === "string" && obj.message || `HTTP ${res.status} ${res.statusText}`;
351
+ const code = typeof obj.code === "string" ? obj.code : undefined;
352
+ throw new ApiError(res.status, msg, code);
353
+ }
354
+ return json;
355
+ }
356
+ me() {
357
+ return this.request("/api/me");
358
+ }
359
+ getClaudeCodeStatus() {
360
+ return this.request("/api/claude-code/status");
361
+ }
362
+ regenerateClaudeCodeKey() {
363
+ return this.request("/api/claude-code/key/regenerate", {
364
+ method: "POST"
365
+ });
366
+ }
367
+ listGatewayKeys() {
368
+ return this.request("/api/gateway/keys");
369
+ }
370
+ createGatewayKey(name) {
371
+ return this.request("/api/gateway/keys", {
372
+ method: "POST",
373
+ body: JSON.stringify({ name })
374
+ });
375
+ }
376
+ }
377
+
378
+ // src/commands/claude.ts
379
+ import { hostname as hostname2 } from "node:os";
380
+
381
+ // src/claude-settings.ts
382
+ import { chmod as chmod2, mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
383
+ import { homedir as homedir2 } from "node:os";
384
+ import { dirname, join as join2, resolve as resolve2 } from "node:path";
385
+ function getClaudeConfigDir(options) {
386
+ if (options?.configDir?.trim()) {
387
+ return resolve2(options.configDir.trim());
388
+ }
389
+ if (process.env.CLAUDE_CONFIG_DIR?.trim()) {
390
+ return resolve2(process.env.CLAUDE_CONFIG_DIR.trim());
391
+ }
392
+ return join2(options?.homeDir || homedir2(), ".claude");
393
+ }
394
+ function getClaudeSettingsPath(options) {
395
+ return join2(getClaudeConfigDir(options), "settings.json");
396
+ }
397
+ function getClaudeStatePath(options) {
398
+ const explicitConfigDir = options?.configDir?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim();
399
+ if (explicitConfigDir) {
400
+ return join2(resolve2(explicitConfigDir), ".claude.json");
401
+ }
402
+ return join2(options?.homeDir || homedir2(), ".claude.json");
403
+ }
404
+ function isPlainObject(value) {
405
+ return typeof value === "object" && value !== null && !Array.isArray(value);
406
+ }
407
+ async function readJsonObject(filePath) {
408
+ let raw;
409
+ try {
410
+ raw = await readFile2(filePath, "utf8");
411
+ } catch (err) {
412
+ const code = err?.code;
413
+ if (code === "ENOENT") {
414
+ return { exists: false, data: {} };
415
+ }
416
+ throw err;
417
+ }
418
+ if (!raw.trim()) {
419
+ return { exists: true, data: {} };
420
+ }
421
+ let parsed;
422
+ try {
423
+ parsed = JSON.parse(raw);
424
+ } catch (err) {
425
+ const msg = err instanceof Error ? err.message : String(err);
426
+ throw new Error(`Файл ${filePath} содержит некорректный JSON: ${msg}`);
427
+ }
428
+ if (!isPlainObject(parsed)) {
429
+ throw new Error(`Файл ${filePath} должен содержать JSON-объект.`);
430
+ }
431
+ return { exists: true, data: parsed };
432
+ }
433
+ async function writeJsonObject(filePath, data) {
434
+ const dir = dirname(filePath);
435
+ await mkdir2(dir, { recursive: true, mode: 448 });
436
+ const content = `${JSON.stringify(data, null, 2)}
437
+ `;
438
+ await writeFile2(filePath, content, { encoding: "utf8", mode: 384 });
439
+ await chmod2(filePath, 384).catch(() => {
440
+ return;
441
+ });
442
+ }
443
+ async function applyClaudeCodeConfig(params) {
444
+ const settingsPath = getClaudeSettingsPath(params);
445
+ const statePath = getClaudeStatePath(params);
446
+ const baseUrl = params.baseUrl.trim().replace(/\/+$/, "");
447
+ const authToken = params.authToken.trim();
448
+ const { data: settingsData } = await readJsonObject(settingsPath);
449
+ const existingEnv = isPlainObject(settingsData.env) ? { ...settingsData.env } : {};
450
+ let removedApiKey = false;
451
+ if ("ANTHROPIC_API_KEY" in existingEnv) {
452
+ delete existingEnv.ANTHROPIC_API_KEY;
453
+ removedApiKey = true;
454
+ }
455
+ existingEnv.ANTHROPIC_BASE_URL = baseUrl;
456
+ existingEnv.ANTHROPIC_AUTH_TOKEN = authToken;
457
+ const nextSettings = {
458
+ ...settingsData,
459
+ env: existingEnv
460
+ };
461
+ if (!params.dryRun) {
462
+ await writeJsonObject(settingsPath, nextSettings);
463
+ }
464
+ let updatedOnboarding = false;
465
+ if (!params.skipOnboarding) {
466
+ const { data: stateData } = await readJsonObject(statePath);
467
+ if (stateData.hasCompletedOnboarding !== true) {
468
+ updatedOnboarding = true;
469
+ if (!params.dryRun) {
470
+ await writeJsonObject(statePath, {
471
+ ...stateData,
472
+ hasCompletedOnboarding: true
473
+ });
474
+ }
475
+ }
476
+ }
477
+ return {
478
+ settingsPath,
479
+ statePath,
480
+ updatedOnboarding,
481
+ removedApiKey,
482
+ baseUrl
483
+ };
484
+ }
485
+ async function readClaudeCodeConfig(options) {
486
+ const settingsPath = getClaudeSettingsPath(options);
487
+ const { exists, data } = await readJsonObject(settingsPath);
488
+ if (!exists) {
489
+ return {
490
+ settingsPath,
491
+ exists: false,
492
+ baseUrl: null,
493
+ authToken: null,
494
+ hasApiKey: false
495
+ };
496
+ }
497
+ const env = isPlainObject(data.env) ? data.env : {};
498
+ const baseUrl = typeof env.ANTHROPIC_BASE_URL === "string" && env.ANTHROPIC_BASE_URL.trim() ? env.ANTHROPIC_BASE_URL.trim() : null;
499
+ const authToken = typeof env.ANTHROPIC_AUTH_TOKEN === "string" && env.ANTHROPIC_AUTH_TOKEN.trim() ? env.ANTHROPIC_AUTH_TOKEN.trim() : null;
500
+ const hasApiKey = typeof env.ANTHROPIC_API_KEY === "string" && env.ANTHROPIC_API_KEY.length > 0;
501
+ return {
502
+ settingsPath,
503
+ exists: true,
504
+ baseUrl,
505
+ authToken,
506
+ hasApiKey
507
+ };
508
+ }
509
+ async function resetClaudeCodeConfig(options) {
510
+ const settingsPath = getClaudeSettingsPath(options);
511
+ const { exists, data } = await readJsonObject(settingsPath);
512
+ if (!exists || !isPlainObject(data.env)) {
513
+ return { settingsPath, changed: false, removedKeys: [] };
514
+ }
515
+ const nextEnv = { ...data.env };
516
+ const removedKeys = [];
517
+ for (const key of ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN"]) {
518
+ if (key in nextEnv) {
519
+ delete nextEnv[key];
520
+ removedKeys.push(key);
521
+ }
522
+ }
523
+ if (removedKeys.length === 0) {
524
+ return { settingsPath, changed: false, removedKeys: [] };
525
+ }
526
+ const nextSettings = { ...data };
527
+ if (Object.keys(nextEnv).length === 0) {
528
+ delete nextSettings.env;
529
+ } else {
530
+ nextSettings.env = nextEnv;
531
+ }
532
+ if (!options?.dryRun) {
533
+ await writeJsonObject(settingsPath, nextSettings);
534
+ }
535
+ return { settingsPath, changed: true, removedKeys };
536
+ }
537
+ function maskSecret(secret) {
538
+ const trimmed = secret.trim();
539
+ if (trimmed.length <= 16) {
540
+ return "***";
541
+ }
542
+ return `${trimmed.slice(0, 10)}...${trimmed.slice(-4)}`;
543
+ }
544
+
545
+ // src/config.ts
546
+ var DEFAULT_RUNGATE_API_URL = "https://app.rungate.ru";
547
+ var DEFAULT_GATEWAY_BASE_URL = "https://api.rungate.ru";
548
+ function resolveRungateApiUrl(explicit) {
549
+ if (explicit?.trim()) {
550
+ return explicit.trim().replace(/\/+$/, "");
551
+ }
552
+ if (process.env.RUNGATE_API_URL?.trim()) {
553
+ return process.env.RUNGATE_API_URL.trim().replace(/\/+$/, "");
554
+ }
555
+ return DEFAULT_RUNGATE_API_URL;
556
+ }
557
+ async function resolveAuthToken2(explicit) {
558
+ return resolveAuthToken(explicit, ["RUNGATE_TOKEN"]);
559
+ }
560
+
561
+ // src/context.ts
562
+ async function ensureAuthenticatedClient(flags, options) {
563
+ const baseUrl = resolveRungateApiUrl(flags.apiUrl);
564
+ let token = await resolveAuthToken2(flags.token);
565
+ if (!token) {
566
+ if (options?.autoLogin && !flags.json) {
567
+ const loginRes = await runUnifiedLogin({
568
+ client: "devpass",
569
+ title: "Авторизация в DevPass",
570
+ noBrowser: flags.noBrowser,
571
+ authUrl: resolveAuthUrl(flags.authUrl)
572
+ });
573
+ token = loginRes.token;
574
+ } else {
575
+ throw new Error("Вы не авторизованы. Выполните `devpass login` или передайте `--token <dp_live_...>`.");
576
+ }
577
+ }
578
+ return new RunGateClient({ baseUrl, token });
579
+ }
580
+
581
+ // src/commands/claude.ts
582
+ var DEFAULT_SUBSCRIPTION_PROXY_URL = "https://app.rungate.ru/api/claude-code/proxy";
583
+ var CLAUDE_CODE_PAGE_URL = "https://app.rungate.ru/claude-code";
584
+ var GATEWAY_PAGE_URL = "https://app.rungate.ru/gateway";
585
+ function formatTokens(n) {
586
+ if (n >= 1e9)
587
+ return `${(n / 1e9).toFixed(2)}B`;
588
+ if (n >= 1e6)
589
+ return `${(n / 1e6).toFixed(2)}M`;
590
+ if (n >= 1000)
591
+ return `${(n / 1000).toFixed(1)}K`;
592
+ return n.toLocaleString("ru-RU");
593
+ }
594
+ function renderProgressBar(percent, width = 20) {
595
+ const clamped = Math.max(0, Math.min(100, percent));
596
+ const filled = Math.round(clamped / 100 * width);
597
+ const empty = Math.max(0, width - filled);
598
+ const bar = `${"█".repeat(filled)}${"░".repeat(empty)}`;
599
+ if (clamped >= 95)
600
+ return c.red(bar);
601
+ if (clamped >= 75)
602
+ return c.yellow(bar);
603
+ return c.green(bar);
604
+ }
605
+ function formatResetCountdown(resetAt) {
606
+ if (!resetAt)
607
+ return "запустится при первом запросе";
608
+ const diffMs = Date.parse(resetAt) - Date.now();
609
+ if (!Number.isFinite(diffMs) || diffMs <= 0) {
610
+ return "обновится при следующем запросе";
611
+ }
612
+ const totalMins = Math.floor(diffMs / 60000);
613
+ const days = Math.floor(totalMins / (60 * 24));
614
+ const hours = Math.floor(totalMins % (60 * 24) / 60);
615
+ const mins = totalMins % 60;
616
+ if (days >= 1)
617
+ return `сброс через ${days} дн. ${hours} ч.`;
618
+ if (hours >= 1)
619
+ return `сброс через ${hours} ч. ${mins} мин.`;
620
+ return `сброс через ${Math.max(1, mins)} мин.`;
621
+ }
622
+ function printWindowLine(label, win) {
623
+ const pct = win.percent.toFixed(1).padStart(5);
624
+ const bar = renderProgressBar(win.percent);
625
+ const counts = `${formatTokens(win.usedWeighted)} / ${formatTokens(win.limitWeighted)} взв.`;
626
+ const reset = formatResetCountdown(win.resetAt);
627
+ console.log(` ${label.padEnd(6)} [${bar}] ${pct}% ${c.dim(`(${counts} · ${reset})`)}`);
628
+ }
629
+ function classifyLocalMode(baseUrl) {
630
+ if (!baseUrl)
631
+ return "none";
632
+ if (baseUrl.includes("/api/claude-code/proxy") || baseUrl.endsWith("/claude")) {
633
+ return "subscription";
634
+ }
635
+ if (baseUrl.includes("api.rungate.ru")) {
636
+ return "gateway";
637
+ }
638
+ return "custom";
639
+ }
640
+ function formatLocalModeLabel(mode) {
641
+ switch (mode) {
642
+ case "subscription":
643
+ return "Подписка RunGate Claude Code";
644
+ case "gateway":
645
+ return "RunGate AI Gateway (по балансу)";
646
+ case "custom":
647
+ return "Сторонний / пользовательский URL";
648
+ case "none":
649
+ return "Не настроено";
650
+ }
651
+ }
652
+ async function runClaudeSetup(flags) {
653
+ if (flags.key?.trim()) {
654
+ const baseUrl = (flags.baseUrl || (flags.gateway ? DEFAULT_GATEWAY_BASE_URL : DEFAULT_SUBSCRIPTION_PROXY_URL)).trim().replace(/\/+$/, "");
655
+ const applied = await applyClaudeCodeConfig({
656
+ baseUrl,
657
+ authToken: flags.key.trim(),
658
+ skipOnboarding: flags.noOnboarding,
659
+ dryRun: flags.dryRun
660
+ });
661
+ if (flags.json) {
662
+ console.log(JSON.stringify({
663
+ ok: true,
664
+ mode: flags.gateway ? "gateway" : "manual",
665
+ dryRun: Boolean(flags.dryRun),
666
+ ...applied
667
+ }, null, 2));
668
+ return;
669
+ }
670
+ const prefix = flags.dryRun ? `${c.yellow("[dry-run]")} ` : "";
671
+ console.log(`${prefix}${c.green("✓")} Claude Code настроен.`);
672
+ console.log(` Base URL: ${c.cyan(applied.baseUrl)}`);
673
+ console.log(` Конфиг: ${c.dim(applied.settingsPath)}`);
674
+ if (applied.updatedOnboarding) {
675
+ console.log(c.dim(` Онбординг пропущен (${applied.statePath})`));
676
+ }
677
+ if (applied.removedApiKey) {
678
+ console.log(c.dim(" Удалён конфликтующий ANTHROPIC_API_KEY из settings.json"));
679
+ }
680
+ console.log(`
681
+ Готово! Запустите ${c.bold("claude")} в терминале.`);
682
+ return;
683
+ }
684
+ const client = await ensureAuthenticatedClient(flags, { autoLogin: !flags.json });
685
+ if (flags.gateway) {
686
+ const gatewayInfo = await client.listGatewayKeys();
687
+ const keyName = `Claude Code (${hostname2()})`.slice(0, 50);
688
+ const created = flags.dryRun ? {
689
+ id: 0,
690
+ name: keyName,
691
+ secretKey: "sk-rg-live-<dry-run>",
692
+ maskedKey: "sk-rg-live-***",
693
+ status: "active"
694
+ } : await client.createGatewayKey(keyName);
695
+ const baseUrl = (flags.baseUrl || DEFAULT_GATEWAY_BASE_URL).trim().replace(/\/+$/, "");
696
+ const applied = await applyClaudeCodeConfig({
697
+ baseUrl,
698
+ authToken: created.secretKey,
699
+ skipOnboarding: flags.noOnboarding,
700
+ dryRun: flags.dryRun
701
+ });
702
+ if (flags.json) {
703
+ console.log(JSON.stringify({
704
+ ok: true,
705
+ mode: "gateway",
706
+ dryRun: Boolean(flags.dryRun),
707
+ balanceRub: gatewayInfo.balanceRub,
708
+ discountPercent: gatewayInfo.discountPercent,
709
+ keyId: created.id,
710
+ maskedKey: created.maskedKey,
711
+ ...applied
712
+ }, null, 2));
713
+ return;
714
+ }
715
+ const prefix = flags.dryRun ? `${c.yellow("[dry-run]")} ` : "";
716
+ console.log(`${prefix}${c.green("✓")} Claude Code подключён к RunGate AI Gateway.`);
717
+ console.log(` Баланс: ${c.bold(`${gatewayInfo.balanceRub.toFixed(2)} ₽`)}${gatewayInfo.discountPercent > 0 ? c.green(` (скидка DevPass Pro −${gatewayInfo.discountPercent}%)`) : ""}`);
718
+ console.log(` Ключ: ${c.dim(created.maskedKey)}`);
719
+ console.log(` Base URL: ${c.cyan(applied.baseUrl)}`);
720
+ console.log(` Конфиг: ${c.dim(applied.settingsPath)}`);
721
+ if (applied.updatedOnboarding) {
722
+ console.log(c.dim(` Онбординг пропущен (${applied.statePath})`));
723
+ }
724
+ if (applied.removedApiKey) {
725
+ console.log(c.dim(" Удалён конфликтующий ANTHROPIC_API_KEY из settings.json"));
726
+ }
727
+ if (gatewayInfo.balanceRub <= 0) {
728
+ console.log(`
729
+ ${c.yellow("!")} На балансе AI Gateway сейчас ${gatewayInfo.balanceRub.toFixed(2)} ₽. Пополните баланс: ${c.cyan(GATEWAY_PAGE_URL)}`);
730
+ }
731
+ console.log(`
732
+ Готово! Запустите ${c.bold("claude")} в терминале.`);
733
+ return;
734
+ }
735
+ const status = await client.getClaudeCodeStatus();
736
+ if (!status.subscription?.active || !status.apiKey) {
737
+ if (flags.json) {
738
+ console.log(JSON.stringify({
739
+ ok: false,
740
+ error: "no_active_subscription",
741
+ expired: Boolean(status.subscription?.expired),
742
+ checkoutUrl: CLAUDE_CODE_PAGE_URL,
743
+ plans: status.plans
744
+ }, null, 2));
745
+ process.exitCode = 1;
746
+ return;
747
+ }
748
+ if (status.subscription?.expired) {
749
+ const expiredAt = new Date(status.subscription.expiresAt).toLocaleDateString("ru-RU");
750
+ console.log(`${c.yellow("!")} Подписка Claude Code (${c.bold(status.subscription.planName)}) истекла ${expiredAt}.`);
751
+ } else {
752
+ console.log(`${c.yellow("!")} У вашего аккаунта пока нет активной подписки Claude Code.`);
753
+ }
754
+ if (status.plans.length > 0) {
755
+ console.log(`
756
+ Доступные тарифы:`);
757
+ for (const plan of status.plans) {
758
+ console.log(` • ${c.bold(plan.name.padEnd(8))} ${c.cyan(`${plan.priceMonthlyRub.toLocaleString("ru-RU")} ₽/мес`)} — ${plan.subtitle}`);
759
+ }
760
+ }
761
+ console.log(`
762
+ Оформить подписку: ${c.cyan(CLAUDE_CODE_PAGE_URL)}`);
763
+ console.log(`Или подключить оплату по факту через AI Gateway: ${c.bold("npx devpass claude --gateway")}`);
764
+ process.exitCode = 1;
765
+ return;
766
+ }
767
+ const baseUrl = (flags.baseUrl || status.proxyBaseUrl || DEFAULT_SUBSCRIPTION_PROXY_URL).trim().replace(/\/+$/, "");
768
+ const applied = await applyClaudeCodeConfig({
769
+ baseUrl,
770
+ authToken: status.apiKey,
771
+ skipOnboarding: flags.noOnboarding,
772
+ dryRun: flags.dryRun
773
+ });
774
+ if (flags.json) {
775
+ console.log(JSON.stringify({
776
+ ok: true,
777
+ mode: "subscription",
778
+ dryRun: Boolean(flags.dryRun),
779
+ plan: status.subscription.planName,
780
+ expiresAt: status.subscription.expiresAt,
781
+ maskedKey: status.maskedKey,
782
+ windows: status.windows,
783
+ ...applied
784
+ }, null, 2));
785
+ return;
786
+ }
787
+ const prefix = flags.dryRun ? `${c.yellow("[dry-run]")} ` : "";
788
+ const expires = new Date(status.subscription.expiresAt).toLocaleDateString("ru-RU");
789
+ console.log(`${prefix}${c.green("✓")} Claude Code настроен (тариф ${c.bold(status.subscription.planName)}, до ${expires}).`);
790
+ if (status.windows) {
791
+ console.log("");
792
+ printWindowLine("5ч:", status.windows.window5h);
793
+ printWindowLine("7д:", status.windows.window7d);
794
+ }
795
+ console.log("");
796
+ console.log(` Base URL: ${c.cyan(applied.baseUrl)}`);
797
+ console.log(` Ключ: ${c.dim(status.maskedKey || maskSecret(status.apiKey))}`);
798
+ console.log(` Конфиг: ${c.dim(applied.settingsPath)}`);
799
+ if (applied.updatedOnboarding) {
800
+ console.log(c.dim(` Онбординг пропущен (${applied.statePath})`));
801
+ }
802
+ if (applied.removedApiKey) {
803
+ console.log(c.dim(" Удалён конфликтующий ANTHROPIC_API_KEY из settings.json"));
804
+ }
805
+ console.log(`
806
+ Готово! Запустите ${c.bold("claude")} в терминале.`);
807
+ }
808
+ async function runClaudeStatus(flags) {
809
+ const local = await readClaudeCodeConfig();
810
+ const mode = classifyLocalMode(local.baseUrl);
811
+ const token = await resolveAuthToken2(flags.token);
812
+ let remote = null;
813
+ let remoteError = null;
814
+ if (token) {
815
+ try {
816
+ const client = new RunGateClient({
817
+ baseUrl: resolveRungateApiUrl(flags.apiUrl),
818
+ token
819
+ });
820
+ remote = await client.getClaudeCodeStatus();
821
+ } catch (err) {
822
+ remoteError = err instanceof Error ? err.message : String(err);
823
+ }
824
+ }
825
+ if (flags.json) {
826
+ console.log(JSON.stringify({
827
+ local: {
828
+ settingsPath: local.settingsPath,
829
+ exists: local.exists,
830
+ mode,
831
+ baseUrl: local.baseUrl,
832
+ maskedToken: local.authToken ? maskSecret(local.authToken) : null,
833
+ hasApiKey: local.hasApiKey
834
+ },
835
+ remote: remote ? {
836
+ subscription: remote.subscription,
837
+ windows: remote.windows,
838
+ stats: remote.stats
839
+ } : null,
840
+ remoteError
841
+ }, null, 2));
842
+ return;
843
+ }
844
+ console.log(c.bold("Локальная конфигурация Claude Code"));
845
+ console.log(` Статус: ${mode === "none" ? c.dim("Не настроено") : c.green(formatLocalModeLabel(mode))}`);
846
+ console.log(` Конфиг: ${c.dim(local.settingsPath)}`);
847
+ if (local.baseUrl) {
848
+ console.log(` Base URL: ${c.cyan(local.baseUrl)}`);
849
+ }
850
+ if (local.authToken) {
851
+ console.log(` Токен: ${c.dim(maskSecret(local.authToken))}`);
852
+ }
853
+ if (local.hasApiKey) {
854
+ console.log(` ${c.yellow("!")} Обнаружен ANTHROPIC_API_KEY в settings.json — выполните \`devpass claude\` для очистки конфликта.`);
855
+ }
856
+ console.log("");
857
+ if (!token) {
858
+ console.log(c.dim("Выполните `devpass login` для просмотра лимитов подписки RunGate."));
859
+ return;
860
+ }
861
+ if (remoteError) {
862
+ console.log(`${c.yellow("!")} Не удалось загрузить статус подписки: ${remoteError}`);
863
+ return;
864
+ }
865
+ if (!remote?.subscription) {
866
+ console.log(`Подписка RunGate Claude Code: ${c.dim("не оформлена")} (${c.cyan(CLAUDE_CODE_PAGE_URL)})`);
867
+ return;
868
+ }
869
+ const sub = remote.subscription;
870
+ const expires = new Date(sub.expiresAt).toLocaleDateString("ru-RU");
871
+ const statusBadge = sub.active ? c.green("активна") : c.yellow("истекла");
872
+ console.log(`${c.bold(`Подписка ${sub.planName}`)} (${statusBadge} · до ${expires})`);
873
+ if (remote.windows) {
874
+ printWindowLine("5ч:", remote.windows.window5h);
875
+ printWindowLine("7д:", remote.windows.window7d);
876
+ }
877
+ if (remote.stats?.monthly) {
878
+ const m = remote.stats.monthly;
879
+ console.log(c.dim(` За 30 дней: ${m.requests.toLocaleString("ru-RU")} запр. · ${formatTokens(m.rawTokens)} сырых токенов · кэш ${m.cacheHitRatioPercent.toFixed(1)}%`));
880
+ }
881
+ }
882
+ async function runClaudeReset(flags) {
883
+ const res = await resetClaudeCodeConfig({ dryRun: flags.dryRun });
884
+ if (flags.json) {
885
+ console.log(JSON.stringify({ ok: true, dryRun: Boolean(flags.dryRun), ...res }, null, 2));
886
+ return;
887
+ }
888
+ if (!res.changed) {
889
+ console.log(`${c.dim("•")} В ${res.settingsPath} не найдены переменные RunGate (изменений не требуется).`);
890
+ return;
891
+ }
892
+ const prefix = flags.dryRun ? `${c.yellow("[dry-run]")} ` : "";
893
+ console.log(`${prefix}${c.green("✓")} Удалены переменные ${c.bold(res.removedKeys.join(", "))} из ${c.dim(res.settingsPath)}.`);
894
+ }
895
+ async function runClaudeRegenerate(flags) {
896
+ const client = await ensureAuthenticatedClient(flags, { autoLogin: !flags.json });
897
+ const regenerated = await client.regenerateClaudeCodeKey();
898
+ const status = await client.getClaudeCodeStatus();
899
+ const baseUrl = (flags.baseUrl || status.proxyBaseUrl || DEFAULT_SUBSCRIPTION_PROXY_URL).trim().replace(/\/+$/, "");
900
+ const applied = await applyClaudeCodeConfig({
901
+ baseUrl,
902
+ authToken: regenerated.apiKey,
903
+ skipOnboarding: flags.noOnboarding,
904
+ dryRun: flags.dryRun
905
+ });
906
+ if (flags.json) {
907
+ console.log(JSON.stringify({
908
+ ok: true,
909
+ dryRun: Boolean(flags.dryRun),
910
+ maskedKey: regenerated.maskedKey,
911
+ ...applied
912
+ }, null, 2));
913
+ return;
914
+ }
915
+ const prefix = flags.dryRun ? `${c.yellow("[dry-run]")} ` : "";
916
+ console.log(`${prefix}${c.green("✓")} Ключ подписки перевыпущен и обновлён в локальной конфигурации.`);
917
+ console.log(` Новый ключ: ${c.dim(regenerated.maskedKey)}`);
918
+ console.log(` Конфиг: ${c.dim(applied.settingsPath)}`);
919
+ }
920
+ async function runClaudeCommand(subcommand, flags) {
921
+ switch (subcommand) {
922
+ case undefined:
923
+ case "setup":
924
+ case "init":
925
+ await runClaudeSetup(flags);
926
+ break;
927
+ case "status":
928
+ await runClaudeStatus(flags);
929
+ break;
930
+ case "reset":
931
+ case "off":
932
+ await runClaudeReset(flags);
933
+ break;
934
+ case "regenerate":
935
+ case "rotate":
936
+ await runClaudeRegenerate(flags);
937
+ break;
938
+ default:
939
+ throw new Error(`Неизвестная подкоманда \`claude ${subcommand}\`. Доступны: setup, status, reset, regenerate.`);
940
+ }
941
+ }
942
+
943
+ // src/commands/login.ts
944
+ async function runLogin(flags) {
945
+ const apiUrl = resolveRungateApiUrl(flags.apiUrl);
946
+ const authUrl = resolveAuthUrl(flags.authUrl);
947
+ await runUnifiedLogin({
948
+ client: "devpass",
949
+ title: "Авторизация в DevPass",
950
+ tokenArg: flags.tokenArg,
951
+ tokenFlag: flags.token,
952
+ noBrowser: flags.noBrowser,
953
+ authUrl,
954
+ verifyToken: async (token) => {
955
+ const client = new RunGateClient({ baseUrl: apiUrl, token });
956
+ const me = await client.me();
957
+ return {
958
+ email: me.user?.email || "пользователь DevPass"
959
+ };
960
+ }
961
+ });
962
+ }
963
+ async function runLogout(flags) {
964
+ await clearCredentials();
965
+ if (flags?.json) {
966
+ console.log(JSON.stringify({ ok: true }));
967
+ return;
968
+ }
969
+ console.log(`${c.green("✓")} Локальные учетные данные DevPass удалены (для всех CLI).`);
970
+ }
971
+ async function runWhoami(flags) {
972
+ const client = await ensureAuthenticatedClient(flags, { autoLogin: false });
973
+ const [me, ccStatus] = await Promise.all([
974
+ client.me(),
975
+ client.getClaudeCodeStatus().catch(() => null)
976
+ ]);
977
+ if (flags.json) {
978
+ console.log(JSON.stringify({
979
+ user: me.user,
980
+ entitlements: me.entitlements,
981
+ claudeCode: ccStatus?.subscription ?? null
982
+ }, null, 2));
983
+ return;
984
+ }
985
+ console.log(`${c.bold(me.user?.email || "пользователь DevPass")} (${me.user?.id || "—"})`);
986
+ if (ccStatus?.subscription?.active) {
987
+ const expires = new Date(ccStatus.subscription.expiresAt).toLocaleDateString("ru-RU");
988
+ console.log(`Claude Code: ${c.green(ccStatus.subscription.planName)} · действует до ${expires}`);
989
+ } else {
990
+ console.log(`Claude Code: ${c.dim("нет активной подписки")}`);
991
+ }
992
+ }
993
+
994
+ // src/index.ts
995
+ var VERSION = "0.1.0";
996
+ function printHelp() {
997
+ console.log(`${c.bold("devpass")} v${VERSION} — единый CLI экосистемы DevPass (https://devpass.ru)
998
+
999
+ ${c.bold("Использование:")}
1000
+ devpass claude [опции] Настроить Claude Code одной командой (подписка RunGate)
1001
+ devpass claude status Статус локального конфига и 5ч/7д лимиты подписки
1002
+ devpass claude reset Удалить настройки RunGate из ~/.claude/settings.json
1003
+ devpass claude regenerate Перевыпустить ключ подписки и обновить локальный конфиг
1004
+ devpass login [token] Войти через браузер (или по ключу dp_live_...)
1005
+ devpass logout Удалить локальные учетные данные
1006
+ devpass whoami Показать текущий аккаунт и подписку
1007
+
1008
+ ${c.bold("Опции команды claude:")}
1009
+ --gateway Подключить через RunGate AI Gateway (оплата с баланса в ₽)
1010
+ -k, --key <sk-...> Прописать переданный API-ключ напрямую без запроса к API
1011
+ --base-url <url> Переопределить ANTHROPIC_BASE_URL
1012
+ --no-onboarding Не изменять ~/.claude.json (флаг hasCompletedOnboarding)
1013
+ --dry-run Показать результат без изменения локальных файлов
1014
+
1015
+ ${c.bold("Общие опции:")}
1016
+ -t, --token <token> API-ключ DevPass (dp_live_...)
1017
+ --api-url <url> URL API RunGate (по умолчанию https://app.rungate.ru)
1018
+ --auth-url <url> URL DevPass ID (по умолчанию https://id.devpass.ru)
1019
+ --no-browser Ввести API-ключ вручную вместо входа через браузер
1020
+ --json Вывод результата в формате JSON
1021
+ -v, --version Показать версию
1022
+ -h, --help Показать справку
1023
+ `);
1024
+ }
1025
+ var isJsonMode = false;
1026
+ async function main() {
1027
+ const { values, positionals } = parseArgs({
1028
+ args: process.argv.slice(2),
1029
+ allowPositionals: true,
1030
+ strict: false,
1031
+ options: {
1032
+ gateway: { type: "boolean" },
1033
+ key: { type: "string", short: "k" },
1034
+ "base-url": { type: "string" },
1035
+ "no-onboarding": { type: "boolean" },
1036
+ "dry-run": { type: "boolean" },
1037
+ json: { type: "boolean" },
1038
+ token: { type: "string", short: "t" },
1039
+ "api-url": { type: "string" },
1040
+ "auth-url": { type: "string" },
1041
+ "no-browser": { type: "boolean" },
1042
+ version: { type: "boolean", short: "v" },
1043
+ help: { type: "boolean", short: "h" }
1044
+ }
1045
+ });
1046
+ isJsonMode = Boolean(values.json);
1047
+ if (values.help) {
1048
+ printHelp();
1049
+ return;
1050
+ }
1051
+ if (values.version) {
1052
+ console.log(VERSION);
1053
+ return;
1054
+ }
1055
+ const commonFlags = {
1056
+ token: typeof values.token === "string" ? values.token : undefined,
1057
+ apiUrl: typeof values["api-url"] === "string" ? values["api-url"] : undefined,
1058
+ authUrl: typeof values["auth-url"] === "string" ? values["auth-url"] : undefined,
1059
+ noBrowser: Boolean(values["no-browser"]),
1060
+ json: isJsonMode
1061
+ };
1062
+ const claudeFlags = {
1063
+ ...commonFlags,
1064
+ gateway: Boolean(values.gateway),
1065
+ key: typeof values.key === "string" ? values.key : undefined,
1066
+ baseUrl: typeof values["base-url"] === "string" ? values["base-url"] : undefined,
1067
+ noOnboarding: Boolean(values["no-onboarding"]),
1068
+ dryRun: Boolean(values["dry-run"])
1069
+ };
1070
+ const [cmd, ...rest] = positionals;
1071
+ if (!cmd) {
1072
+ printHelp();
1073
+ return;
1074
+ }
1075
+ switch (cmd) {
1076
+ case "claude":
1077
+ case "claude-code":
1078
+ await runClaudeCommand(rest[0], claudeFlags);
1079
+ break;
1080
+ case "setup":
1081
+ if (rest[0] === "claude" || rest[0] === "claude-code") {
1082
+ await runClaudeCommand(rest[1], claudeFlags);
1083
+ } else {
1084
+ throw new Error(`Неизвестная цель настройки: "${rest[0] || ""}". Попробуйте \`devpass claude\`.`);
1085
+ }
1086
+ break;
1087
+ case "login":
1088
+ await runLogin({
1089
+ ...commonFlags,
1090
+ tokenArg: rest[0]
1091
+ });
1092
+ break;
1093
+ case "logout":
1094
+ await runLogout({ json: isJsonMode });
1095
+ break;
1096
+ case "whoami":
1097
+ await runWhoami(commonFlags);
1098
+ break;
1099
+ default:
1100
+ throw new Error(`Неизвестная команда: "${cmd}". Запустите \`devpass --help\`.`);
1101
+ }
1102
+ }
1103
+ main().catch((err) => {
1104
+ const message = err instanceof ApiError ? `${err.message} (HTTP ${err.status})` : err instanceof Error ? err.message : String(err);
1105
+ if (isJsonMode) {
1106
+ console.log(JSON.stringify({
1107
+ ok: false,
1108
+ error: message,
1109
+ ...err instanceof ApiError ? { status: err.status, code: err.code } : {}
1110
+ }, null, 2));
1111
+ } else {
1112
+ printError(message);
1113
+ }
1114
+ process.exit(1);
1115
+ });
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "devpass",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Официальный единый CLI экосистемы DevPass (devpass.ru) — вход и быстрая настройка Claude Code и сервисов RunGate",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": "./dist/index.js"
9
+ },
10
+ "bin": {
11
+ "devpass": "dist/index.js"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md"
16
+ ],
17
+ "keywords": [
18
+ "devpass",
19
+ "rungate",
20
+ "claude-code",
21
+ "claude",
22
+ "anthropic",
23
+ "ai",
24
+ "cli"
25
+ ],
26
+ "homepage": "https://devpass.ru",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/devpassru/cli.git",
30
+ "directory": "packages/cli"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public",
34
+ "registry": "https://registry.npmjs.org"
35
+ },
36
+ "engines": {
37
+ "node": ">=18.0.0"
38
+ },
39
+ "devDependencies": {
40
+ "@devpass/cli-core": "workspace:*"
41
+ },
42
+ "scripts": {
43
+ "build": "bun build src/index.ts --outfile dist/index.js --target node --format esm && chmod +x dist/index.js",
44
+ "typecheck": "tsc --noEmit",
45
+ "prepublishOnly": "bun run build"
46
+ }
47
+ }