@causyne/agent 1.20.69 → 1.20.71
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/package.json +1 -1
- package/src/assets/logo.png +0 -0
- package/src/auth/openrouterAuth.js +489 -0
- package/src/auth/openrouterAuth.ts +588 -0
- package/src/commands.js +116 -0
- package/src/dynamicCatalogue.js +47 -0
- package/src/dynamicCatalogue.ts +47 -0
- package/src/modelCatalogue.js +5 -2
- package/src/providers/base.d.ts +2 -0
- package/src/providers/factory.js +2 -0
- package/src/providers/openrouter.js +316 -0
- package/src/providers/openrouter.ts +361 -0
- package/src/tui/home.js +1 -0
- package/src/tui/modelPicker.js +183 -21
- package/src/tui/modelPicker.ts +193 -26
package/package.json
CHANGED
|
Binary file
|
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — OpenRouter Free Authentication & OAuth PKCE Flow
|
|
3
|
+
*
|
|
4
|
+
* Implements the official OpenRouter OAuth PKCE authorization with S256,
|
|
5
|
+
* loopback callback server on ephemeral 127.0.0.1 port, headless/manual fallback,
|
|
6
|
+
* and secure credential storage in Causyne's encrypted configuration vault.
|
|
7
|
+
*/
|
|
8
|
+
import http from 'node:http';
|
|
9
|
+
import crypto from 'node:crypto';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { fileURLToPath, URL } from 'node:url';
|
|
13
|
+
import { loadConfig, saveConfig } from '../config.js';
|
|
14
|
+
import { openWithNativeOS } from '../tools/desktopOpen.js';
|
|
15
|
+
export const OPENROUTER_AUTH_URL = 'https://openrouter.ai/auth';
|
|
16
|
+
export const OPENROUTER_TOKEN_EXCHANGE_URL = 'https://openrouter.ai/api/v1/auth/keys';
|
|
17
|
+
export const OPENROUTER_FREE_MODEL = 'openrouter/free';
|
|
18
|
+
export class OpenRouterAuthError extends Error {
|
|
19
|
+
constructor(message) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = 'OpenRouterAuthError';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Generate cryptographically secure PKCE verifier, S256 challenge, and CSRF state token.
|
|
26
|
+
*/
|
|
27
|
+
export function generatePkceCodes() {
|
|
28
|
+
// 32 random bytes as base64url string yields 43 characters (RFC 7636 compliant: 43-128 chars)
|
|
29
|
+
const codeVerifier = crypto.randomBytes(32).toString('base64url');
|
|
30
|
+
const codeChallenge = crypto
|
|
31
|
+
.createHash('sha256')
|
|
32
|
+
.update(codeVerifier)
|
|
33
|
+
.digest('base64url');
|
|
34
|
+
const state = crypto.randomBytes(16).toString('hex');
|
|
35
|
+
return {
|
|
36
|
+
codeVerifier,
|
|
37
|
+
codeChallenge,
|
|
38
|
+
codeChallengeMethod: 'S256',
|
|
39
|
+
state
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Build the official OpenRouter OAuth authorization URL.
|
|
44
|
+
*/
|
|
45
|
+
export function buildAuthorizationUrl(callbackUrl, codeChallenge, state) {
|
|
46
|
+
const url = new URL(OPENROUTER_AUTH_URL);
|
|
47
|
+
url.searchParams.set('callback_url', callbackUrl);
|
|
48
|
+
url.searchParams.set('code_challenge', codeChallenge);
|
|
49
|
+
url.searchParams.set('code_challenge_method', 'S256');
|
|
50
|
+
url.searchParams.set('state', state);
|
|
51
|
+
return url.toString();
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Exchange the authorization code for an OpenRouter API key using PKCE verifier.
|
|
55
|
+
*/
|
|
56
|
+
export async function exchangeCodeForApiKey(code, codeVerifier, fetchFn = fetch) {
|
|
57
|
+
const cleanCode = (code || '').trim();
|
|
58
|
+
const cleanVerifier = (codeVerifier || '').trim();
|
|
59
|
+
if (!cleanCode) {
|
|
60
|
+
throw new OpenRouterAuthError('Authorization code cannot be empty.');
|
|
61
|
+
}
|
|
62
|
+
if (!cleanVerifier) {
|
|
63
|
+
throw new OpenRouterAuthError('PKCE code verifier cannot be empty.');
|
|
64
|
+
}
|
|
65
|
+
const payload = {
|
|
66
|
+
code: cleanCode,
|
|
67
|
+
code_verifier: cleanVerifier,
|
|
68
|
+
code_challenge_method: 'S256'
|
|
69
|
+
};
|
|
70
|
+
let response;
|
|
71
|
+
try {
|
|
72
|
+
response = await fetchFn(OPENROUTER_TOKEN_EXCHANGE_URL, {
|
|
73
|
+
method: 'POST',
|
|
74
|
+
headers: {
|
|
75
|
+
'Content-Type': 'application/json',
|
|
76
|
+
'HTTP-Referer': 'https://causyne.com',
|
|
77
|
+
'X-Title': 'Causyne Agent'
|
|
78
|
+
},
|
|
79
|
+
body: JSON.stringify(payload)
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
throw new OpenRouterAuthError(`Failed to reach OpenRouter token exchange: ${err?.message || err}`);
|
|
84
|
+
}
|
|
85
|
+
if (!response.ok) {
|
|
86
|
+
const errorBody = await response.text().catch(() => '');
|
|
87
|
+
throw new OpenRouterAuthError(`OpenRouter token exchange failed (HTTP ${response.status}): ${errorBody || 'Invalid code or verifier'}`);
|
|
88
|
+
}
|
|
89
|
+
const data = (await response.json().catch(() => null));
|
|
90
|
+
const apiKey = data?.key?.trim();
|
|
91
|
+
if (!apiKey) {
|
|
92
|
+
throw new OpenRouterAuthError('OpenRouter response did not contain an API key.');
|
|
93
|
+
}
|
|
94
|
+
return apiKey;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Retrieve the Causyne Agent emblem logo as a binary buffer if available.
|
|
98
|
+
*/
|
|
99
|
+
export function getLogoBuffer() {
|
|
100
|
+
try {
|
|
101
|
+
const currentDir = path.dirname(fileURLToPath(import.meta.url));
|
|
102
|
+
const assetPath = path.resolve(currentDir, '../assets/logo.png');
|
|
103
|
+
if (fs.existsSync(assetPath)) {
|
|
104
|
+
return fs.readFileSync(assetPath);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
// Ignore read errors
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Retrieve the Causyne Agent emblem logo encoded as Base64.
|
|
114
|
+
*/
|
|
115
|
+
export function getLogoBase64() {
|
|
116
|
+
const buf = getLogoBuffer();
|
|
117
|
+
return buf ? buf.toString('base64') : '';
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Render a professional branded HTML response page for OpenRouter OAuth callbacks.
|
|
121
|
+
*/
|
|
122
|
+
export function renderAuthPage(options) {
|
|
123
|
+
const isSuccess = options.status === 'success';
|
|
124
|
+
const base64Logo = getLogoBase64();
|
|
125
|
+
const logoSrc = base64Logo ? `data:image/png;base64,${base64Logo}` : '/logo.png';
|
|
126
|
+
const badgeHtml = isSuccess
|
|
127
|
+
? '<div style="display:inline-flex;align-items:center;gap:8px;' +
|
|
128
|
+
'background:rgba(46,160,67,0.15);border:1px solid #2ea043;color:#3fb950;' +
|
|
129
|
+
'padding:6px 18px;border-radius:24px;font-size:13px;font-weight:600;margin-bottom:20px;">' +
|
|
130
|
+
'✓ Connected Successfully</div>'
|
|
131
|
+
: '<div style="display:inline-flex;align-items:center;gap:8px;' +
|
|
132
|
+
'background:rgba(239,68,68,0.15);border:1px solid #ef4444;color:#f87171;' +
|
|
133
|
+
'padding:6px 18px;border-radius:24px;font-size:13px;font-weight:600;margin-bottom:20px;">' +
|
|
134
|
+
'✕ Authorization Failed</div>';
|
|
135
|
+
const title = options.title || (isSuccess ? 'OpenRouter Account Authorized' : 'Authorization Error');
|
|
136
|
+
const defaultMsg = isSuccess
|
|
137
|
+
? 'Your OpenRouter account has been connected to Causyne Agent. You can now close this tab and return to your terminal.'
|
|
138
|
+
: 'The authorization flow could not be completed.';
|
|
139
|
+
const message = options.message || defaultMsg;
|
|
140
|
+
const contentBox = isSuccess
|
|
141
|
+
? '<div style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);' +
|
|
142
|
+
'border-radius:10px;padding:14px 18px;margin-bottom:28px;text-align:left;font-family:monospace;' +
|
|
143
|
+
'font-size:13px;color:#cbd5e1;">' +
|
|
144
|
+
'<div style="display:flex;justify-content:space-between;margin-bottom:8px;">' +
|
|
145
|
+
'<span style="color:#64748b;">Active Model</span>' +
|
|
146
|
+
`<span style="color:#9df028;font-weight:600;">${options.model || OPENROUTER_FREE_MODEL}</span>` +
|
|
147
|
+
'</div>' +
|
|
148
|
+
'<div style="display:flex;justify-content:space-between;">' +
|
|
149
|
+
'<span style="color:#64748b;">Privacy Guard</span>' +
|
|
150
|
+
'<span style="color:#38bdf8;">provider.data_collection = "deny"</span>' +
|
|
151
|
+
'</div>' +
|
|
152
|
+
'</div>'
|
|
153
|
+
: '<div style="background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.25);' +
|
|
154
|
+
'border-radius:10px;padding:14px;color:#fca5a5;font-size:13px;line-height:1.5;margin-bottom:20px;' +
|
|
155
|
+
`text-align:left;">${options.errorDetail || 'An unexpected error occurred during authorization.'}</div>` +
|
|
156
|
+
'<div style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);' +
|
|
157
|
+
'border-radius:10px;padding:16px;margin-bottom:24px;text-align:left;">' +
|
|
158
|
+
'<div style="color:#ffffff;font-size:13px;font-weight:600;margin-bottom:8px;">Recommended Solutions:</div>' +
|
|
159
|
+
'<ol style="color:#94a3b8;font-size:13px;line-height:1.6;margin:0;padding-left:18px;">' +
|
|
160
|
+
'<li>Return to your terminal and select OpenRouter in the FREE tab again to retry.</li>' +
|
|
161
|
+
'<li>Or create a free API key at <a href="https://openrouter.ai/keys" target="_blank" ' +
|
|
162
|
+
'style="color:#38bdf8;text-decoration:none;">openrouter.ai/keys</a> and configure it via:</li>' +
|
|
163
|
+
'</ol>' +
|
|
164
|
+
'<pre style="background:#05070a;color:#9df028;padding:10px 14px;border-radius:6px;font-family:monospace;' +
|
|
165
|
+
'font-size:12px;margin-top:10px;overflow-x:auto;">causyne config set providerKeys.openrouter <your-key></pre>' +
|
|
166
|
+
'</div>';
|
|
167
|
+
const actionButton = isSuccess
|
|
168
|
+
? '<button onclick="window.close()" style="background:#9df028;color:#080b11;border:none;' +
|
|
169
|
+
'padding:12px 28px;border-radius:8px;font-size:14px;font-weight:700;cursor:pointer;font-family:inherit;">' +
|
|
170
|
+
'Return to Terminal</button>' +
|
|
171
|
+
'<div style="font-size:12px;color:#64748b;margin-top:14px;">You can safely close this browser window.</div>'
|
|
172
|
+
: '<button onclick="window.close()" style="background:#334155;color:#f8fafc;border:none;' +
|
|
173
|
+
'padding:10px 24px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;">' +
|
|
174
|
+
'Close Window</button>';
|
|
175
|
+
return `<!DOCTYPE html>
|
|
176
|
+
<html lang="en">
|
|
177
|
+
<head>
|
|
178
|
+
<meta charset="utf-8">
|
|
179
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
180
|
+
<title>Causyne Agent Connected Successfully</title>
|
|
181
|
+
<style>
|
|
182
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
183
|
+
body {
|
|
184
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
185
|
+
background: #080b11 radial-gradient(circle at 50% 20%, #152238 0%, #080b11 75%);
|
|
186
|
+
color: #c9d1d9;
|
|
187
|
+
min-height: 100vh;
|
|
188
|
+
display: flex;
|
|
189
|
+
align-items: center;
|
|
190
|
+
justify-content: center;
|
|
191
|
+
padding: 24px;
|
|
192
|
+
}
|
|
193
|
+
.container {
|
|
194
|
+
max-width: 540px;
|
|
195
|
+
width: 100%;
|
|
196
|
+
text-align: center;
|
|
197
|
+
}
|
|
198
|
+
.header {
|
|
199
|
+
display: flex;
|
|
200
|
+
align-items: center;
|
|
201
|
+
justify-content: center;
|
|
202
|
+
gap: 16px;
|
|
203
|
+
margin-bottom: 28px;
|
|
204
|
+
}
|
|
205
|
+
.logo {
|
|
206
|
+
width: 52px;
|
|
207
|
+
height: 52px;
|
|
208
|
+
object-fit: contain;
|
|
209
|
+
border-radius: 12px;
|
|
210
|
+
filter: drop-shadow(0 4px 16px rgba(157, 240, 40, 0.3));
|
|
211
|
+
}
|
|
212
|
+
.brand-title {
|
|
213
|
+
font-family: "JetBrains Mono", SFMono-Regular, Menlo, Consolas, monospace;
|
|
214
|
+
font-size: 24px;
|
|
215
|
+
font-weight: 800;
|
|
216
|
+
letter-spacing: 1.5px;
|
|
217
|
+
color: #ffffff;
|
|
218
|
+
line-height: 1.2;
|
|
219
|
+
}
|
|
220
|
+
.brand-subtitle {
|
|
221
|
+
font-size: 11px;
|
|
222
|
+
color: #8a99a8;
|
|
223
|
+
letter-spacing: 1px;
|
|
224
|
+
text-transform: uppercase;
|
|
225
|
+
margin-top: 2px;
|
|
226
|
+
text-align: left;
|
|
227
|
+
}
|
|
228
|
+
.card {
|
|
229
|
+
background: rgba(18, 25, 38, 0.95);
|
|
230
|
+
border: 1px solid rgba(157, 240, 40, 0.22);
|
|
231
|
+
border-radius: 16px;
|
|
232
|
+
padding: 36px 32px;
|
|
233
|
+
box-shadow: 0 24px 48px rgba(0, 0, 0, 0.6);
|
|
234
|
+
backdrop-filter: blur(16px);
|
|
235
|
+
}
|
|
236
|
+
h1 {
|
|
237
|
+
color: #ffffff;
|
|
238
|
+
font-size: 21px;
|
|
239
|
+
font-weight: 700;
|
|
240
|
+
margin-bottom: 12px;
|
|
241
|
+
}
|
|
242
|
+
p {
|
|
243
|
+
color: #94a3b8;
|
|
244
|
+
font-size: 14px;
|
|
245
|
+
line-height: 1.6;
|
|
246
|
+
margin-bottom: 24px;
|
|
247
|
+
}
|
|
248
|
+
</style>
|
|
249
|
+
</head>
|
|
250
|
+
<body>
|
|
251
|
+
<div class="container">
|
|
252
|
+
<div class="header">
|
|
253
|
+
<img src="${logoSrc}" alt="Causyne Agent Logo" class="logo" />
|
|
254
|
+
<div>
|
|
255
|
+
<div class="brand-title">CAUSYNE <span style="color:#9df028;">AGENT</span></div>
|
|
256
|
+
<div class="brand-subtitle">Autonomous AI Harness</div>
|
|
257
|
+
</div>
|
|
258
|
+
</div>
|
|
259
|
+
<div class="card">
|
|
260
|
+
${badgeHtml}
|
|
261
|
+
<h1>${title}</h1>
|
|
262
|
+
<p>${message}</p>
|
|
263
|
+
${contentBox}
|
|
264
|
+
${actionButton}
|
|
265
|
+
</div>
|
|
266
|
+
</div>
|
|
267
|
+
</body>
|
|
268
|
+
</html>`;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Start loopback HTTP server on 127.0.0.1 to receive the OAuth redirect code.
|
|
272
|
+
*/
|
|
273
|
+
export async function startLoopbackAuth(options = {}) {
|
|
274
|
+
const timeoutMs = options.timeoutMs ?? 120_000;
|
|
275
|
+
const openBrowser = options.openBrowser ?? true;
|
|
276
|
+
const fetchFn = options.fetchFn ?? fetch;
|
|
277
|
+
const pkce = generatePkceCodes();
|
|
278
|
+
return new Promise((resolve, reject) => {
|
|
279
|
+
let resolved = false;
|
|
280
|
+
let timeoutTimer = null;
|
|
281
|
+
const cleanup = () => {
|
|
282
|
+
if (timeoutTimer) {
|
|
283
|
+
clearTimeout(timeoutTimer);
|
|
284
|
+
timeoutTimer = null;
|
|
285
|
+
}
|
|
286
|
+
try {
|
|
287
|
+
server.close();
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
// Ignore close errors
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
const server = http.createServer(async (req, res) => {
|
|
294
|
+
try {
|
|
295
|
+
const reqUrl = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
|
|
296
|
+
if (reqUrl.pathname === '/logo.png') {
|
|
297
|
+
const logoBuf = getLogoBuffer();
|
|
298
|
+
if (logoBuf) {
|
|
299
|
+
res.writeHead(200, {
|
|
300
|
+
'Content-Type': 'image/png',
|
|
301
|
+
'Content-Length': logoBuf.length,
|
|
302
|
+
'Cache-Control': 'public, max-age=3600'
|
|
303
|
+
});
|
|
304
|
+
res.end(logoBuf);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
308
|
+
res.end('Not Found');
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (reqUrl.pathname !== '/callback') {
|
|
312
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
313
|
+
res.end('Not Found');
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
const code = reqUrl.searchParams.get('code');
|
|
317
|
+
const state = reqUrl.searchParams.get('state');
|
|
318
|
+
if (!state || state !== pkce.state) {
|
|
319
|
+
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
320
|
+
res.end(renderAuthPage({
|
|
321
|
+
status: 'error',
|
|
322
|
+
title: 'Authorization Error: State Mismatch',
|
|
323
|
+
errorDetail: 'The received CSRF verification state did not match the active session. This can happen if the authorization request timed out or was tampered with.'
|
|
324
|
+
}));
|
|
325
|
+
if (!resolved) {
|
|
326
|
+
resolved = true;
|
|
327
|
+
cleanup();
|
|
328
|
+
reject(new OpenRouterAuthError('State mismatch detected during OpenRouter callback.'));
|
|
329
|
+
}
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
if (!code) {
|
|
333
|
+
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
334
|
+
res.end(renderAuthPage({
|
|
335
|
+
status: 'error',
|
|
336
|
+
title: 'Authorization Failed',
|
|
337
|
+
errorDetail: 'No authorization code was returned by OpenRouter.'
|
|
338
|
+
}));
|
|
339
|
+
if (!resolved) {
|
|
340
|
+
resolved = true;
|
|
341
|
+
cleanup();
|
|
342
|
+
reject(new OpenRouterAuthError('No authorization code returned from callback.'));
|
|
343
|
+
}
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
// Send friendly HTML response to user's browser
|
|
347
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
348
|
+
res.end(renderAuthPage({
|
|
349
|
+
status: 'success',
|
|
350
|
+
model: OPENROUTER_FREE_MODEL
|
|
351
|
+
}));
|
|
352
|
+
// Perform token exchange
|
|
353
|
+
const apiKey = await exchangeCodeForApiKey(code, pkce.codeVerifier, fetchFn);
|
|
354
|
+
if (!resolved) {
|
|
355
|
+
resolved = true;
|
|
356
|
+
setTimeout(cleanup, 1200);
|
|
357
|
+
resolve({ apiKey });
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
catch (err) {
|
|
361
|
+
if (!resolved) {
|
|
362
|
+
resolved = true;
|
|
363
|
+
cleanup();
|
|
364
|
+
reject(err);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
server.on('error', (err) => {
|
|
369
|
+
if (!resolved) {
|
|
370
|
+
resolved = true;
|
|
371
|
+
cleanup();
|
|
372
|
+
reject(new OpenRouterAuthError(`Loopback server failed to bind: ${err.message}`));
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
server.listen(0, '127.0.0.1', () => {
|
|
376
|
+
const addr = server.address();
|
|
377
|
+
if (!addr || typeof addr === 'string') {
|
|
378
|
+
cleanup();
|
|
379
|
+
reject(new OpenRouterAuthError('Failed to retrieve loopback server port.'));
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
const callbackUrl = `http://127.0.0.1:${addr.port}/callback`;
|
|
383
|
+
const authUrl = buildAuthorizationUrl(callbackUrl, pkce.codeChallenge, pkce.state);
|
|
384
|
+
if (options.onUrlReady) {
|
|
385
|
+
options.onUrlReady(authUrl);
|
|
386
|
+
}
|
|
387
|
+
if (openBrowser) {
|
|
388
|
+
openWithNativeOS(authUrl).catch(() => {
|
|
389
|
+
// If browser opening fails, user can copy URL manually
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
timeoutTimer = setTimeout(() => {
|
|
393
|
+
if (!resolved) {
|
|
394
|
+
resolved = true;
|
|
395
|
+
cleanup();
|
|
396
|
+
reject(new OpenRouterAuthError(`Authorization timed out after ${Math.round(timeoutMs / 1000)} seconds.`));
|
|
397
|
+
}
|
|
398
|
+
}, timeoutMs);
|
|
399
|
+
});
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Mask an API key for safe display in logs and status screens.
|
|
404
|
+
*/
|
|
405
|
+
export function maskApiKey(key) {
|
|
406
|
+
const clean = (key || '').trim();
|
|
407
|
+
if (!clean)
|
|
408
|
+
return 'none';
|
|
409
|
+
if (clean.length <= 8)
|
|
410
|
+
return '********';
|
|
411
|
+
return `${clean.slice(0, 7)}...${clean.slice(-4)}`;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Save user OpenRouter key into local encrypted configuration vault.
|
|
415
|
+
*/
|
|
416
|
+
export function saveOpenRouterKey(apiKey, options = {}) {
|
|
417
|
+
const cleanKey = (apiKey || '').trim();
|
|
418
|
+
if (!cleanKey) {
|
|
419
|
+
throw new OpenRouterAuthError('Cannot save an empty OpenRouter API key.');
|
|
420
|
+
}
|
|
421
|
+
const store = options.store || { loadConfig, saveConfig };
|
|
422
|
+
const currentConfig = store.loadConfig() || {};
|
|
423
|
+
const providerKeys = {
|
|
424
|
+
...(currentConfig.providerKeys && typeof currentConfig.providerKeys === 'object' ? currentConfig.providerKeys : {})
|
|
425
|
+
};
|
|
426
|
+
providerKeys['openrouter'] = cleanKey;
|
|
427
|
+
currentConfig.providerKeys = providerKeys;
|
|
428
|
+
if (options.dataCollection) {
|
|
429
|
+
currentConfig.openrouterDataCollection = options.dataCollection;
|
|
430
|
+
}
|
|
431
|
+
else if (!currentConfig.openrouterDataCollection) {
|
|
432
|
+
currentConfig.openrouterDataCollection = 'deny';
|
|
433
|
+
}
|
|
434
|
+
if (options.setAsActive) {
|
|
435
|
+
currentConfig.provider = 'openrouter';
|
|
436
|
+
currentConfig.model = OPENROUTER_FREE_MODEL;
|
|
437
|
+
currentConfig.apiKey = cleanKey;
|
|
438
|
+
}
|
|
439
|
+
store.saveConfig(currentConfig);
|
|
440
|
+
return currentConfig;
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Disconnect OpenRouter credentials from local vault.
|
|
444
|
+
*/
|
|
445
|
+
export function disconnectOpenRouter(store = { loadConfig, saveConfig }) {
|
|
446
|
+
const currentConfig = store.loadConfig() || {};
|
|
447
|
+
const providerKeys = {
|
|
448
|
+
...(currentConfig.providerKeys && typeof currentConfig.providerKeys === 'object' ? currentConfig.providerKeys : {})
|
|
449
|
+
};
|
|
450
|
+
delete providerKeys['openrouter'];
|
|
451
|
+
currentConfig.providerKeys = providerKeys;
|
|
452
|
+
if (currentConfig.provider === 'openrouter') {
|
|
453
|
+
currentConfig.provider = 'deepseek';
|
|
454
|
+
currentConfig.model = 'deepseek-chat';
|
|
455
|
+
currentConfig.apiKey = providerKeys['deepseek'] || '';
|
|
456
|
+
}
|
|
457
|
+
store.saveConfig(currentConfig);
|
|
458
|
+
return currentConfig;
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Retrieve live OpenRouter connection and privacy status.
|
|
462
|
+
*/
|
|
463
|
+
export function getOpenRouterStatus(cfg) {
|
|
464
|
+
const config = cfg || loadConfig() || {};
|
|
465
|
+
const vaultKey = config.providerKeys?.openrouter || (config.provider === 'openrouter' ? config.apiKey : '');
|
|
466
|
+
const envKey = process.env.OPENROUTER_API_KEY;
|
|
467
|
+
const connectedKey = vaultKey || envKey || '';
|
|
468
|
+
const isConnected = Boolean(connectedKey);
|
|
469
|
+
const isActive = config.provider === 'openrouter';
|
|
470
|
+
const currentModel = isActive ? (config.model || OPENROUTER_FREE_MODEL) : OPENROUTER_FREE_MODEL;
|
|
471
|
+
const dataCollection = config.openrouterDataCollection === 'allow' ? 'allow' : 'deny';
|
|
472
|
+
return {
|
|
473
|
+
connected: isConnected,
|
|
474
|
+
active: isActive,
|
|
475
|
+
model: currentModel,
|
|
476
|
+
dataCollection,
|
|
477
|
+
maskedKey: isConnected ? maskApiKey(connectedKey) : undefined,
|
|
478
|
+
keySource: vaultKey ? 'vault' : (envKey ? 'environment' : undefined)
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Update user's OpenRouter data collection preference.
|
|
483
|
+
*/
|
|
484
|
+
export function setOpenRouterDataCollection(preference, store = { loadConfig, saveConfig }) {
|
|
485
|
+
const config = store.loadConfig() || {};
|
|
486
|
+
config.openrouterDataCollection = preference;
|
|
487
|
+
store.saveConfig(config);
|
|
488
|
+
return config;
|
|
489
|
+
}
|