@lightharu/krouter 1.8.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 (61) hide show
  1. package/LICENSE +679 -0
  2. package/README.md +238 -0
  3. package/dist-web/assets/index-CM4-0adf.css +1 -0
  4. package/dist-web/assets/index-DCslvfUR.js +139 -0
  5. package/dist-web/favicon.svg +9 -0
  6. package/dist-web/icon.svg +9 -0
  7. package/dist-web/index.html +19 -0
  8. package/out-server/main/kiroAuthSync.js +249 -0
  9. package/out-server/main/kproxy/certManager.js +262 -0
  10. package/out-server/main/kproxy/index.js +254 -0
  11. package/out-server/main/kproxy/mitmProxy.js +475 -0
  12. package/out-server/main/kproxy/types.js +23 -0
  13. package/out-server/main/proxy/accountPool.js +543 -0
  14. package/out-server/main/proxy/clientConfig.js +596 -0
  15. package/out-server/main/proxy/index.js +25 -0
  16. package/out-server/main/proxy/kiroApi.js +1996 -0
  17. package/out-server/main/proxy/logger.js +407 -0
  18. package/out-server/main/proxy/modelCatalog.js +75 -0
  19. package/out-server/main/proxy/promptCacheTracker.js +301 -0
  20. package/out-server/main/proxy/proxyServer.js +3543 -0
  21. package/out-server/main/proxy/selfSignedCert.js +179 -0
  22. package/out-server/main/proxy/systemProxy.js +250 -0
  23. package/out-server/main/proxy/tokenCounter.js +164 -0
  24. package/out-server/main/proxy/toolNameRegistry.js +57 -0
  25. package/out-server/main/proxy/translator.js +1084 -0
  26. package/out-server/main/proxy/types.js +3 -0
  27. package/out-server/main/registration/browser-identity.js +184 -0
  28. package/out-server/main/registration/chainProxy.js +349 -0
  29. package/out-server/main/registration/config.js +58 -0
  30. package/out-server/main/registration/email-service.js +801 -0
  31. package/out-server/main/registration/fingerprint.js +352 -0
  32. package/out-server/main/registration/http-utils.js +148 -0
  33. package/out-server/main/registration/jwe.js +74 -0
  34. package/out-server/main/registration/names.js +142 -0
  35. package/out-server/main/registration/proton-mail-window.js +339 -0
  36. package/out-server/main/registration/registrar.js +1715 -0
  37. package/out-server/main/registration/tlsClientPool.js +70 -0
  38. package/out-server/main/registration/xxtea.js +161 -0
  39. package/out-server/main/runtimePaths.js +19 -0
  40. package/out-server/main/utils/redact.js +95 -0
  41. package/out-server/server/index.js +1272 -0
  42. package/out-server/server/services/accountExtras.js +105 -0
  43. package/out-server/server/services/accountProfileHydration.js +95 -0
  44. package/out-server/server/services/authFlows.js +509 -0
  45. package/out-server/server/services/dashboardTunnel.js +315 -0
  46. package/out-server/server/services/diagnostics.js +326 -0
  47. package/out-server/server/services/kiroAccounts.js +431 -0
  48. package/out-server/server/services/kiroSettings.js +260 -0
  49. package/out-server/server/services/kproxyRuntime.js +264 -0
  50. package/out-server/server/services/localKiroCredentials.js +320 -0
  51. package/out-server/server/services/machineIdRuntime.js +327 -0
  52. package/out-server/server/services/protonBrowserRuntime.js +724 -0
  53. package/out-server/server/services/proxyRuntime.js +523 -0
  54. package/out-server/server/services/registrationRuntime.js +106 -0
  55. package/out-server/server/store.js +266 -0
  56. package/package.json +113 -0
  57. package/resources/tls-client-xgo-1.14.0-windows-amd64.dll +0 -0
  58. package/scripts/kiro-manager-cli.cjs +3 -0
  59. package/scripts/krouter-cli.cjs +509 -0
  60. package/src/renderer/src/assets/krouter-logo.svg +11 -0
  61. package/src/renderer/src/assets/krouter-mark.svg +9 -0
@@ -0,0 +1,523 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ProxyRuntime = void 0;
7
+ exports.getProxyRuntime = getProxyRuntime;
8
+ const crypto_1 = __importDefault(require("crypto"));
9
+ const proxyServer_1 = require("../../main/proxy/proxyServer");
10
+ const clientConfig_1 = require("../../main/proxy/clientConfig");
11
+ const logger_1 = require("../../main/proxy/logger");
12
+ const runtimePaths_1 = require("../../main/runtimePaths");
13
+ const kiroApi_1 = require("../../main/proxy/kiroApi");
14
+ const kiroAccounts_1 = require("./kiroAccounts");
15
+ const accountProfileHydration_1 = require("./accountProfileHydration");
16
+ const CLIENT_PROXY_API_KEY_NAME = 'OpenClaw - Krouter API Proxy';
17
+ function defaultProxyConfig(saved) {
18
+ return normalizeProxyConfig({
19
+ enabled: false,
20
+ port: 5580,
21
+ host: '127.0.0.1',
22
+ enableMultiAccount: true,
23
+ selectedAccountIds: [],
24
+ logRequests: true,
25
+ maxConcurrent: 10,
26
+ maxRetries: 3,
27
+ retryDelayMs: 1000,
28
+ tokenRefreshBeforeExpiry: 300,
29
+ clientDrivenToolExecution: true,
30
+ accountSelectionStrategy: 'round-robin',
31
+ sessionAffinityEnabled: false,
32
+ ...saved
33
+ });
34
+ }
35
+ function normalizeProxyConfig(config) {
36
+ const strategy = config.accountSelectionStrategy || 'round-robin';
37
+ const normalized = {
38
+ ...config,
39
+ accountSelectionStrategy: strategy
40
+ };
41
+ if (normalized.enableMultiAccount && strategy !== 'sticky') {
42
+ normalized.sessionAffinityEnabled = false;
43
+ }
44
+ return normalized;
45
+ }
46
+ function serializeStats(stats) {
47
+ return {
48
+ ...stats,
49
+ accountStats: Object.fromEntries(stats.accountStats),
50
+ endpointStats: Object.fromEntries(stats.endpointStats),
51
+ modelStats: Object.fromEntries(stats.modelStats)
52
+ };
53
+ }
54
+ function normalizeProxyAccount(account) {
55
+ return {
56
+ ...account,
57
+ authMethod: account.authMethod === 'idc' ? 'IdC' : account.authMethod
58
+ };
59
+ }
60
+ function resolveProxyProfileArn(account) {
61
+ const credentials = account.credentials || {};
62
+ return (0, kiroApi_1.resolveProfileArn)({
63
+ profileArn: account.profileArn || credentials.profileArn,
64
+ authMethod: credentials.authMethod,
65
+ provider: credentials.provider || account.idp
66
+ });
67
+ }
68
+ function newApiKey(input) {
69
+ return {
70
+ id: crypto_1.default.randomUUID(),
71
+ name: input.name || 'API Key',
72
+ key: input.key || `sk-${crypto_1.default.randomBytes(24).toString('base64url')}`,
73
+ format: input.format || 'sk',
74
+ enabled: true,
75
+ createdAt: Date.now(),
76
+ creditsLimit: input.creditsLimit,
77
+ usage: {
78
+ totalRequests: 0,
79
+ totalCredits: 0,
80
+ totalInputTokens: 0,
81
+ totalOutputTokens: 0,
82
+ daily: {}
83
+ }
84
+ };
85
+ }
86
+ function detectApiKeyFormat(key) {
87
+ if (key.includes(':'))
88
+ return 'token';
89
+ if (key.startsWith('sk-'))
90
+ return 'sk';
91
+ return 'simple';
92
+ }
93
+ class ProxyRuntime {
94
+ store;
95
+ userId;
96
+ emit;
97
+ server = null;
98
+ autoStartInFlight = null;
99
+ constructor(store, userId, emit) {
100
+ this.store = store;
101
+ this.userId = userId;
102
+ this.emit = emit;
103
+ logger_1.proxyLogStore.initialize((0, runtimePaths_1.getRuntimeUserDataPath)());
104
+ (0, logger_1.interceptConsole)();
105
+ }
106
+ get savedConfig() {
107
+ return defaultProxyConfig(this.store.getUserSetting(this.userId, 'proxyConfig', {}));
108
+ }
109
+ async persistConfig() {
110
+ if (this.server) {
111
+ await this.store.setUserSetting(this.userId, 'proxyConfig', this.server.getConfig());
112
+ }
113
+ }
114
+ wantsRunning(config) {
115
+ const lastRunning = this.store.getUserSetting(this.userId, 'proxyRunning', false);
116
+ return Boolean(config.autoStart || config.enabled || lastRunning);
117
+ }
118
+ async ensureAutoStarted(reason = 'auto') {
119
+ const server = this.getOrCreateServer();
120
+ if (server.isRunning())
121
+ return { success: true, port: server.getConfig().port };
122
+ if (!this.wantsRunning(server.getConfig()))
123
+ return { success: true };
124
+ if (this.autoStartInFlight)
125
+ return this.autoStartInFlight;
126
+ this.autoStartInFlight = (async () => {
127
+ try {
128
+ console.log(`[ProxyRuntime] Auto-starting proxy for user=${this.userId} (${reason})`);
129
+ await this.syncAccountsFromStoreAsync();
130
+ server.updateConfig({ enabled: true });
131
+ await server.start();
132
+ await this.persistConfig();
133
+ await this.store.setUserSetting(this.userId, 'proxyRunning', true);
134
+ return { success: true, port: server.getConfig().port };
135
+ }
136
+ catch (error) {
137
+ const message = error instanceof Error ? error.message : 'Failed to auto-start proxy server';
138
+ console.error('[ProxyRuntime] Auto-start failed:', message);
139
+ return { success: false, error: message };
140
+ }
141
+ finally {
142
+ this.autoStartInFlight = null;
143
+ }
144
+ })();
145
+ return this.autoStartInFlight;
146
+ }
147
+ getOrCreateServer() {
148
+ if (this.server)
149
+ return this.server;
150
+ this.server = new proxyServer_1.ProxyServer(this.savedConfig, {
151
+ onRequest: (info) => this.emit('proxy-request', info),
152
+ onResponse: (info) => this.emit('proxy-response', info),
153
+ onError: (error) => this.emit('proxy-error', error.message),
154
+ onStatusChange: (running, port) => this.emit('proxy-status-change', { running, port }),
155
+ onTokenRefresh: async (account) => {
156
+ const result = await (0, kiroAccounts_1.refreshTokenByMethod)({
157
+ refreshToken: account.refreshToken || '',
158
+ clientId: account.clientId,
159
+ clientSecret: account.clientSecret,
160
+ region: account.region || 'us-east-1',
161
+ authMethod: account.authMethod,
162
+ machineId: account.machineId
163
+ });
164
+ return {
165
+ success: result.success,
166
+ accessToken: result.accessToken,
167
+ refreshToken: result.refreshToken,
168
+ expiresAt: Date.now() + (result.expiresIn || 3600) * 1000,
169
+ error: result.error
170
+ };
171
+ },
172
+ onAccountUpdate: (account) => {
173
+ this.emit('proxy-account-update', account);
174
+ void this.updatePersistedAccountCredentials(account);
175
+ },
176
+ onAccountSuspended: (info) => {
177
+ this.emit('proxy-account-suspended', {
178
+ id: info.accountId,
179
+ email: info.email,
180
+ reason: info.reason,
181
+ message: info.message,
182
+ suspendedAt: Date.now()
183
+ });
184
+ },
185
+ onCreditsUpdate: (totalCredits) => void this.store.setUserSetting(this.userId, 'proxyTotalCredits', totalCredits),
186
+ onTokensUpdate: (inputTokens, outputTokens) => {
187
+ void this.store.setUserSetting(this.userId, 'proxyInputTokens', inputTokens);
188
+ void this.store.setUserSetting(this.userId, 'proxyOutputTokens', outputTokens);
189
+ },
190
+ onRequestStatsUpdate: (totalRequests, successRequests, failedRequests) => {
191
+ void this.store.setUserSetting(this.userId, 'proxyRequestStats', { totalRequests, successRequests, failedRequests });
192
+ },
193
+ onPoolEmpty: async () => {
194
+ await this.syncAccountsFromStoreAsync();
195
+ }
196
+ });
197
+ return this.server;
198
+ }
199
+ async updatePersistedAccountCredentials(account) {
200
+ const accountData = (this.store.getAccountData(this.userId) || {});
201
+ const existing = accountData.accounts?.[account.id];
202
+ if (!existing)
203
+ return;
204
+ existing.profileArn = account.profileArn || existing.profileArn;
205
+ existing.credentials = {
206
+ ...(existing.credentials || {}),
207
+ accessToken: account.accessToken,
208
+ refreshToken: account.refreshToken || existing.credentials?.refreshToken,
209
+ expiresAt: account.expiresAt
210
+ };
211
+ await this.store.setAccountData(this.userId, accountData);
212
+ }
213
+ syncAccountsFromStore() {
214
+ const server = this.getOrCreateServer();
215
+ const pool = server.getAccountPool();
216
+ const accountData = (this.store.getAccountData(this.userId) || {});
217
+ const accounts = Object.values(accountData.accounts || {});
218
+ const bindings = accountData.accountProxyBindings || {};
219
+ const proxyPool = accountData.proxyPool || {};
220
+ const proxyAccounts = [];
221
+ let skippedNoProfileArn = 0;
222
+ for (const account of accounts) {
223
+ if (account.status !== 'active' || !account.credentials?.accessToken)
224
+ continue;
225
+ const profileArn = resolveProxyProfileArn(account);
226
+ if (!profileArn) {
227
+ skippedNoProfileArn++;
228
+ continue;
229
+ }
230
+ const proxyId = bindings[account.id];
231
+ const boundProxy = proxyId ? proxyPool[proxyId] : undefined;
232
+ proxyAccounts.push(normalizeProxyAccount({
233
+ id: account.id,
234
+ email: account.email,
235
+ accessToken: account.credentials.accessToken,
236
+ refreshToken: account.credentials.refreshToken,
237
+ profileArn,
238
+ expiresAt: account.credentials.expiresAt,
239
+ clientId: account.credentials.clientId,
240
+ clientSecret: account.credentials.clientSecret,
241
+ region: account.credentials.region || 'us-east-1',
242
+ authMethod: account.credentials.authMethod,
243
+ provider: account.credentials.provider || account.idp,
244
+ machineId: account.machineId,
245
+ groupId: account.groupId,
246
+ proxyUrl: boundProxy?.enabled && boundProxy.status !== 'dead' ? boundProxy.url : undefined
247
+ }));
248
+ }
249
+ pool.replaceAccounts(proxyAccounts);
250
+ if (skippedNoProfileArn > 0) {
251
+ console.log(`[ProxyRuntime] Skipped ${skippedNoProfileArn} account(s) without profileArn`);
252
+ }
253
+ return { success: true, accountCount: pool.size };
254
+ }
255
+ async syncAccountsFromStoreAsync() {
256
+ const accountData = (this.store.getAccountData(this.userId) || {});
257
+ const hydrated = await (0, accountProfileHydration_1.hydrateAccountDataProfileArns)(accountData);
258
+ if (hydrated.changed) {
259
+ await this.store.setAccountData(this.userId, hydrated.data);
260
+ }
261
+ return this.syncAccountsFromStore();
262
+ }
263
+ async start(config) {
264
+ try {
265
+ const server = this.getOrCreateServer();
266
+ if (config)
267
+ server.updateConfig(config);
268
+ server.updateConfig({ enabled: true });
269
+ await this.syncAccountsFromStoreAsync();
270
+ await server.start();
271
+ await this.persistConfig();
272
+ await this.store.setUserSetting(this.userId, 'proxyRunning', true);
273
+ return { success: true, port: server.getConfig().port };
274
+ }
275
+ catch (error) {
276
+ return { success: false, error: error instanceof Error ? error.message : 'Failed to start proxy server' };
277
+ }
278
+ }
279
+ async stop() {
280
+ try {
281
+ const server = this.getOrCreateServer();
282
+ if (server.isRunning())
283
+ await server.stop();
284
+ server.updateConfig({ enabled: false });
285
+ await this.persistConfig();
286
+ await this.store.setUserSetting(this.userId, 'proxyRunning', false);
287
+ return { success: true };
288
+ }
289
+ catch (error) {
290
+ return { success: false, error: error instanceof Error ? error.message : 'Failed to stop proxy server' };
291
+ }
292
+ }
293
+ async getStatus() {
294
+ await this.ensureAutoStarted('status');
295
+ const server = this.getOrCreateServer();
296
+ return {
297
+ running: server.isRunning(),
298
+ config: server.getConfig(),
299
+ stats: serializeStats(server.getStats()),
300
+ sessionStats: server.getSessionStats()
301
+ };
302
+ }
303
+ async updateConfig(config) {
304
+ try {
305
+ const server = this.getOrCreateServer();
306
+ server.updateConfig(config);
307
+ await this.persistConfig();
308
+ if (!server.isRunning() && (config.autoStart === true || config.enabled === true)) {
309
+ const started = await this.ensureAutoStarted('config-update');
310
+ if (!started.success) {
311
+ return { success: false, config: server.getConfig(), error: started.error };
312
+ }
313
+ }
314
+ return { success: true, config: server.getConfig() };
315
+ }
316
+ catch (error) {
317
+ return { success: false, error: error instanceof Error ? error.message : 'Failed to update proxy config' };
318
+ }
319
+ }
320
+ needsRestart() {
321
+ return { needsRestart: this.server?.needsRestart() || false };
322
+ }
323
+ async restart() {
324
+ try {
325
+ const server = this.getOrCreateServer();
326
+ await this.syncAccountsFromStoreAsync();
327
+ await server.restartServer();
328
+ await this.persistConfig();
329
+ return { success: true };
330
+ }
331
+ catch (error) {
332
+ return { success: false, error: error instanceof Error ? error.message : 'Failed to restart proxy server' };
333
+ }
334
+ }
335
+ addAccount(account) {
336
+ try {
337
+ const pool = this.getOrCreateServer().getAccountPool();
338
+ pool.addAccount(normalizeProxyAccount(account));
339
+ return { success: true, accountCount: pool.size };
340
+ }
341
+ catch (error) {
342
+ return { success: false, error: error instanceof Error ? error.message : 'Failed to add account' };
343
+ }
344
+ }
345
+ removeAccount(accountId) {
346
+ try {
347
+ const pool = this.getOrCreateServer().getAccountPool();
348
+ pool.removeAccount(accountId);
349
+ return { success: true, accountCount: pool.size };
350
+ }
351
+ catch (error) {
352
+ return { success: false, error: error instanceof Error ? error.message : 'Failed to remove account' };
353
+ }
354
+ }
355
+ syncAccounts(accounts) {
356
+ try {
357
+ const pool = this.getOrCreateServer().getAccountPool();
358
+ pool.replaceAccounts(accounts.map(normalizeProxyAccount));
359
+ return { success: true, accountCount: pool.size };
360
+ }
361
+ catch (error) {
362
+ return { success: false, error: error instanceof Error ? error.message : 'Failed to sync accounts' };
363
+ }
364
+ }
365
+ getAccounts() {
366
+ const pool = this.getOrCreateServer().getAccountPool();
367
+ return { accounts: pool.getAllAccounts(), availableCount: pool.availableCount };
368
+ }
369
+ resetPool() {
370
+ this.getOrCreateServer().getAccountPool().reset();
371
+ return { success: true };
372
+ }
373
+ clearAccountSuspended(accountId) {
374
+ this.getOrCreateServer().getAccountPool().clearSuspended(accountId);
375
+ return { success: true };
376
+ }
377
+ async getModels() {
378
+ try {
379
+ const result = await this.getOrCreateServer().getAvailableModels();
380
+ return { success: true, ...result };
381
+ }
382
+ catch (error) {
383
+ return { success: false, models: [], error: error instanceof Error ? error.message : 'Failed to get models' };
384
+ }
385
+ }
386
+ refreshModels() {
387
+ this.getOrCreateServer().clearModelCache();
388
+ return { success: true };
389
+ }
390
+ selfSignedCertInfo() {
391
+ const cert = this.getOrCreateServer().getSelfSignedCertInfo();
392
+ return cert ? { success: true, ...cert } : { success: false, error: 'Failed to generate certificate' };
393
+ }
394
+ selfSignedCertRegenerate() {
395
+ const cert = this.getOrCreateServer().regenerateSelfSignedCert();
396
+ return cert ? { success: true, ...cert } : { success: false, error: 'Failed to regenerate certificate' };
397
+ }
398
+ getLogs(count) {
399
+ return count ? logger_1.proxyLogStore.getLast(count) : logger_1.proxyLogStore.getAll();
400
+ }
401
+ clearLogs() {
402
+ logger_1.proxyLogStore.clear();
403
+ return { success: true };
404
+ }
405
+ getLogsCount() {
406
+ return logger_1.proxyLogStore.count();
407
+ }
408
+ resetCredits() {
409
+ this.getOrCreateServer().resetTotalCredits();
410
+ return { success: true };
411
+ }
412
+ resetTokens() {
413
+ this.getOrCreateServer().resetTotalTokens();
414
+ return { success: true };
415
+ }
416
+ resetRequestStats() {
417
+ this.getOrCreateServer().resetRequestStats();
418
+ return { success: true };
419
+ }
420
+ getApiKeys() {
421
+ return { success: true, apiKeys: this.getOrCreateServer().getConfig().apiKeys || [] };
422
+ }
423
+ async getOrCreateClientApiKey() {
424
+ const server = this.getOrCreateServer();
425
+ const config = server.getConfig();
426
+ const apiKeys = [...(config.apiKeys || [])];
427
+ let apiKey = apiKeys.find((item) => item.name === CLIENT_PROXY_API_KEY_NAME);
428
+ let changed = false;
429
+ if (!apiKey) {
430
+ const legacyKey = (config.apiKey || '').trim();
431
+ apiKey = newApiKey({
432
+ name: CLIENT_PROXY_API_KEY_NAME,
433
+ key: legacyKey || undefined,
434
+ format: legacyKey ? detectApiKeyFormat(legacyKey) : 'sk'
435
+ });
436
+ apiKeys.unshift(apiKey);
437
+ changed = true;
438
+ }
439
+ if (!apiKey.enabled) {
440
+ apiKey.enabled = true;
441
+ changed = true;
442
+ }
443
+ if (changed) {
444
+ server.updateConfig({ apiKeys });
445
+ await this.persistConfig();
446
+ }
447
+ return apiKey;
448
+ }
449
+ async addApiKey(input) {
450
+ const server = this.getOrCreateServer();
451
+ const apiKeys = [...(server.getConfig().apiKeys || []), newApiKey(input || {})];
452
+ server.updateConfig({ apiKeys });
453
+ await this.persistConfig();
454
+ return { success: true, apiKey: apiKeys[apiKeys.length - 1] };
455
+ }
456
+ async updateApiKey(id, updates) {
457
+ const server = this.getOrCreateServer();
458
+ const apiKeys = [...(server.getConfig().apiKeys || [])];
459
+ const apiKey = apiKeys.find((item) => item.id === id);
460
+ if (!apiKey)
461
+ return { success: false, error: 'API key not found' };
462
+ Object.assign(apiKey, updates);
463
+ if (updates.creditsLimit === null)
464
+ delete apiKey.creditsLimit;
465
+ server.updateConfig({ apiKeys });
466
+ await this.persistConfig();
467
+ return { success: true, apiKey };
468
+ }
469
+ async deleteApiKey(id) {
470
+ const server = this.getOrCreateServer();
471
+ const apiKeys = (server.getConfig().apiKeys || []).filter((item) => item.id !== id);
472
+ server.updateConfig({ apiKeys });
473
+ await this.persistConfig();
474
+ return { success: true };
475
+ }
476
+ async resetApiKeyUsage(id) {
477
+ const server = this.getOrCreateServer();
478
+ const apiKeys = [...(server.getConfig().apiKeys || [])];
479
+ const apiKey = apiKeys.find((item) => item.id === id);
480
+ if (!apiKey)
481
+ return { success: false, error: 'API key not found' };
482
+ apiKey.usage = { totalRequests: 0, totalCredits: 0, totalInputTokens: 0, totalOutputTokens: 0, daily: {} };
483
+ apiKey.usageHistory = [];
484
+ server.updateConfig({ apiKeys });
485
+ await this.persistConfig();
486
+ return { success: true };
487
+ }
488
+ auditLog() {
489
+ return { entries: [...this.getOrCreateServer().getAuditLog()] };
490
+ }
491
+ async configureClients(input) {
492
+ const config = this.getOrCreateServer().getConfig();
493
+ const apiKey = await this.getOrCreateClientApiKey();
494
+ const result = await (0, clientConfig_1.configureProxyClients)({
495
+ clients: input.clients,
496
+ host: config.host,
497
+ port: config.port,
498
+ tlsEnabled: config.tls?.enabled,
499
+ apiKey: apiKey.key,
500
+ modelId: input.modelId,
501
+ modelName: input.modelName,
502
+ models: input.models
503
+ });
504
+ return {
505
+ ...result,
506
+ apiKey: {
507
+ id: apiKey.id,
508
+ name: apiKey.name,
509
+ key: apiKey.key
510
+ }
511
+ };
512
+ }
513
+ }
514
+ exports.ProxyRuntime = ProxyRuntime;
515
+ const runtimes = new Map();
516
+ function getProxyRuntime(store, userId, emit) {
517
+ const existing = runtimes.get(userId);
518
+ if (existing)
519
+ return existing;
520
+ const runtime = new ProxyRuntime(store, userId, emit);
521
+ runtimes.set(userId, runtime);
522
+ return runtime;
523
+ }
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registrationStartAuto = registrationStartAuto;
4
+ exports.registrationManualPhase1 = registrationManualPhase1;
5
+ exports.registrationManualPhase2 = registrationManualPhase2;
6
+ exports.registrationManualPhase3 = registrationManualPhase3;
7
+ exports.registrationCancel = registrationCancel;
8
+ exports.registrationStatus = registrationStatus;
9
+ exports.protonOpenLogin = protonOpenLogin;
10
+ exports.protonLoginStatus = protonLoginStatus;
11
+ exports.protonClose = protonClose;
12
+ const config_1 = require("../../main/registration/config");
13
+ const registrar_1 = require("../../main/registration/registrar");
14
+ const protonBrowserRuntime_1 = require("./protonBrowserRuntime");
15
+ const registrarPool = new Map();
16
+ const MANUAL_KEY = '__manual__';
17
+ function emitLog(emit, message, taskId) {
18
+ emit('registration-log', { message, taskId });
19
+ }
20
+ function emitStep(emit, event, taskId) {
21
+ emit('registration-step', { taskId, event });
22
+ }
23
+ async function registrationStartAuto(input, emit) {
24
+ const taskId = input.taskId || `auto-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
25
+ const prefix = input.taskId ? `[#${input.taskId.slice(0, 12)}] ` : '';
26
+ const cfg = (0, config_1.newConfig)(input);
27
+ cfg.manualMode = false;
28
+ const registrar = new registrar_1.Registrar(cfg, (message) => emitLog(emit, `${prefix}${message}`, input.taskId), (event) => emitStep(emit, event, input.taskId));
29
+ registrarPool.set(taskId, registrar);
30
+ try {
31
+ const result = await registrar.run();
32
+ registrarPool.delete(taskId);
33
+ if (!input.taskId)
34
+ emit('registration-complete', result);
35
+ return { success: true, result };
36
+ }
37
+ catch (error) {
38
+ registrarPool.delete(taskId);
39
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
40
+ }
41
+ }
42
+ async function registrationManualPhase1(input, emit) {
43
+ if (registrarPool.has(MANUAL_KEY))
44
+ return { success: false, error: 'A manual registration flow is already in progress' };
45
+ const cfg = (0, config_1.newConfig)(input);
46
+ cfg.manualMode = true;
47
+ const registrar = new registrar_1.Registrar(cfg, (message) => emitLog(emit, message), (event) => emitStep(emit, event));
48
+ registrarPool.set(MANUAL_KEY, registrar);
49
+ const result = await registrar.runManualPhase1();
50
+ if (!result.success) {
51
+ await registrar.destroy();
52
+ registrarPool.delete(MANUAL_KEY);
53
+ }
54
+ return result;
55
+ }
56
+ async function registrationManualPhase2(email, fullName) {
57
+ const registrar = registrarPool.get(MANUAL_KEY);
58
+ if (!registrar)
59
+ return { success: false, error: 'No manual registration flow is in progress' };
60
+ const result = await registrar.runManualPhase2(email, fullName);
61
+ if (!result.success) {
62
+ await registrar.destroy();
63
+ registrarPool.delete(MANUAL_KEY);
64
+ }
65
+ return result;
66
+ }
67
+ async function registrationManualPhase3(otp) {
68
+ const registrar = registrarPool.get(MANUAL_KEY);
69
+ if (!registrar)
70
+ return { success: false, error: 'No manual registration flow is in progress' };
71
+ const result = await registrar.runManualPhase3(otp);
72
+ await registrar.destroy();
73
+ registrarPool.delete(MANUAL_KEY);
74
+ return { success: true, result };
75
+ }
76
+ async function registrationCancel(taskId) {
77
+ if (taskId) {
78
+ const registrar = registrarPool.get(taskId);
79
+ if (registrar) {
80
+ registrar.abort();
81
+ await registrar.destroy();
82
+ registrarPool.delete(taskId);
83
+ }
84
+ return { success: true };
85
+ }
86
+ const tasks = Array.from(registrarPool.entries());
87
+ for (const [id, registrar] of tasks) {
88
+ registrar.abort();
89
+ await registrar.destroy();
90
+ registrarPool.delete(id);
91
+ }
92
+ return { success: true };
93
+ }
94
+ function registrationStatus() {
95
+ return { inProgress: registrarPool.size > 0, count: registrarPool.size };
96
+ }
97
+ function protonOpenLogin() {
98
+ return (0, protonBrowserRuntime_1.openProtonLogin)();
99
+ }
100
+ function protonLoginStatus() {
101
+ return (0, protonBrowserRuntime_1.getProtonLoginStatus)();
102
+ }
103
+ async function protonClose() {
104
+ await (0, protonBrowserRuntime_1.closeProtonWindow)();
105
+ return { success: true };
106
+ }