@causyne/agent 1.20.69 → 1.20.70

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.69",
3
+ "version": "1.20.70",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
@@ -0,0 +1,296 @@
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 { URL } from 'node:url';
11
+ import { loadConfig, saveConfig } from '../config.js';
12
+ import { openWithNativeOS } from '../tools/desktopOpen.js';
13
+ export const OPENROUTER_AUTH_URL = 'https://openrouter.ai/auth';
14
+ export const OPENROUTER_TOKEN_EXCHANGE_URL = 'https://openrouter.ai/api/v1/auth/keys';
15
+ export const OPENROUTER_FREE_MODEL = 'openrouter/free';
16
+ export class OpenRouterAuthError extends Error {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = 'OpenRouterAuthError';
20
+ }
21
+ }
22
+ /**
23
+ * Generate cryptographically secure PKCE verifier, S256 challenge, and CSRF state token.
24
+ */
25
+ export function generatePkceCodes() {
26
+ // 32 random bytes as base64url string yields 43 characters (RFC 7636 compliant: 43-128 chars)
27
+ const codeVerifier = crypto.randomBytes(32).toString('base64url');
28
+ const codeChallenge = crypto
29
+ .createHash('sha256')
30
+ .update(codeVerifier)
31
+ .digest('base64url');
32
+ const state = crypto.randomBytes(16).toString('hex');
33
+ return {
34
+ codeVerifier,
35
+ codeChallenge,
36
+ codeChallengeMethod: 'S256',
37
+ state
38
+ };
39
+ }
40
+ /**
41
+ * Build the official OpenRouter OAuth authorization URL.
42
+ */
43
+ export function buildAuthorizationUrl(callbackUrl, codeChallenge, state) {
44
+ const url = new URL(OPENROUTER_AUTH_URL);
45
+ url.searchParams.set('callback_url', callbackUrl);
46
+ url.searchParams.set('code_challenge', codeChallenge);
47
+ url.searchParams.set('code_challenge_method', 'S256');
48
+ url.searchParams.set('state', state);
49
+ return url.toString();
50
+ }
51
+ /**
52
+ * Exchange the authorization code for an OpenRouter API key using PKCE verifier.
53
+ */
54
+ export async function exchangeCodeForApiKey(code, codeVerifier, fetchFn = fetch) {
55
+ const cleanCode = (code || '').trim();
56
+ const cleanVerifier = (codeVerifier || '').trim();
57
+ if (!cleanCode) {
58
+ throw new OpenRouterAuthError('Authorization code cannot be empty.');
59
+ }
60
+ if (!cleanVerifier) {
61
+ throw new OpenRouterAuthError('PKCE code verifier cannot be empty.');
62
+ }
63
+ const payload = {
64
+ code: cleanCode,
65
+ code_verifier: cleanVerifier,
66
+ code_challenge_method: 'S256'
67
+ };
68
+ let response;
69
+ try {
70
+ response = await fetchFn(OPENROUTER_TOKEN_EXCHANGE_URL, {
71
+ method: 'POST',
72
+ headers: {
73
+ 'Content-Type': 'application/json',
74
+ 'HTTP-Referer': 'https://causyne.com',
75
+ 'X-Title': 'Causyne Agent'
76
+ },
77
+ body: JSON.stringify(payload)
78
+ });
79
+ }
80
+ catch (err) {
81
+ throw new OpenRouterAuthError(`Failed to reach OpenRouter token exchange: ${err?.message || err}`);
82
+ }
83
+ if (!response.ok) {
84
+ const errorBody = await response.text().catch(() => '');
85
+ throw new OpenRouterAuthError(`OpenRouter token exchange failed (HTTP ${response.status}): ${errorBody || 'Invalid code or verifier'}`);
86
+ }
87
+ const data = (await response.json().catch(() => null));
88
+ const apiKey = data?.key?.trim();
89
+ if (!apiKey) {
90
+ throw new OpenRouterAuthError('OpenRouter response did not contain an API key.');
91
+ }
92
+ return apiKey;
93
+ }
94
+ /**
95
+ * Start loopback HTTP server on 127.0.0.1 to receive the OAuth redirect code.
96
+ */
97
+ export async function startLoopbackAuth(options = {}) {
98
+ const timeoutMs = options.timeoutMs ?? 120_000;
99
+ const openBrowser = options.openBrowser ?? true;
100
+ const fetchFn = options.fetchFn ?? fetch;
101
+ const pkce = generatePkceCodes();
102
+ return new Promise((resolve, reject) => {
103
+ let resolved = false;
104
+ let timeoutTimer = null;
105
+ const cleanup = () => {
106
+ if (timeoutTimer) {
107
+ clearTimeout(timeoutTimer);
108
+ timeoutTimer = null;
109
+ }
110
+ try {
111
+ server.close();
112
+ }
113
+ catch {
114
+ // Ignore close errors
115
+ }
116
+ };
117
+ const server = http.createServer(async (req, res) => {
118
+ try {
119
+ const reqUrl = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
120
+ if (reqUrl.pathname !== '/callback') {
121
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
122
+ res.end('Not Found');
123
+ return;
124
+ }
125
+ const code = reqUrl.searchParams.get('code');
126
+ const state = reqUrl.searchParams.get('state');
127
+ if (!state || state !== pkce.state) {
128
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
129
+ res.end('<html><body style="font-family:sans-serif;padding:32px;background:#111;color:#eee;">' +
130
+ '<h2 style="color:#ef4444;">Authorization Error: State Mismatch</h2>' +
131
+ '<p>The received CSRF verification state did not match the session. Please try again.</p>' +
132
+ '</body></html>');
133
+ if (!resolved) {
134
+ resolved = true;
135
+ cleanup();
136
+ reject(new OpenRouterAuthError('State mismatch detected during OpenRouter callback.'));
137
+ }
138
+ return;
139
+ }
140
+ if (!code) {
141
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
142
+ res.end('<html><body style="font-family:sans-serif;padding:32px;background:#111;color:#eee;">' +
143
+ '<h2 style="color:#ef4444;">Authorization Failed</h2>' +
144
+ '<p>No authorization code was returned by OpenRouter.</p>' +
145
+ '</body></html>');
146
+ if (!resolved) {
147
+ resolved = true;
148
+ cleanup();
149
+ reject(new OpenRouterAuthError('No authorization code returned from callback.'));
150
+ }
151
+ return;
152
+ }
153
+ // Send friendly HTML response to user's browser
154
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
155
+ res.end('<html><body style="font-family:sans-serif;padding:40px;background:#0d1117;color:#c9d1d9;text-align:center;">' +
156
+ '<h2 style="color:#2ea043;margin-bottom:12px;">Causyne Agent Connected Successfully</h2>' +
157
+ '<p style="font-size:16px;color:#8b949e;">Your OpenRouter account has been authorized. You can close this window and return to your terminal.</p>' +
158
+ '</body></html>');
159
+ // Perform token exchange
160
+ const apiKey = await exchangeCodeForApiKey(code, pkce.codeVerifier, fetchFn);
161
+ if (!resolved) {
162
+ resolved = true;
163
+ cleanup();
164
+ resolve({ apiKey });
165
+ }
166
+ }
167
+ catch (err) {
168
+ if (!resolved) {
169
+ resolved = true;
170
+ cleanup();
171
+ reject(err);
172
+ }
173
+ }
174
+ });
175
+ server.on('error', (err) => {
176
+ if (!resolved) {
177
+ resolved = true;
178
+ cleanup();
179
+ reject(new OpenRouterAuthError(`Loopback server failed to bind: ${err.message}`));
180
+ }
181
+ });
182
+ server.listen(0, '127.0.0.1', () => {
183
+ const addr = server.address();
184
+ if (!addr || typeof addr === 'string') {
185
+ cleanup();
186
+ reject(new OpenRouterAuthError('Failed to retrieve loopback server port.'));
187
+ return;
188
+ }
189
+ const callbackUrl = `http://127.0.0.1:${addr.port}/callback`;
190
+ const authUrl = buildAuthorizationUrl(callbackUrl, pkce.codeChallenge, pkce.state);
191
+ if (options.onUrlReady) {
192
+ options.onUrlReady(authUrl);
193
+ }
194
+ if (openBrowser) {
195
+ openWithNativeOS(authUrl).catch(() => {
196
+ // If browser opening fails, user can copy URL manually
197
+ });
198
+ }
199
+ timeoutTimer = setTimeout(() => {
200
+ if (!resolved) {
201
+ resolved = true;
202
+ cleanup();
203
+ reject(new OpenRouterAuthError(`Authorization timed out after ${Math.round(timeoutMs / 1000)} seconds.`));
204
+ }
205
+ }, timeoutMs);
206
+ });
207
+ });
208
+ }
209
+ /**
210
+ * Mask an API key for safe display in logs and status screens.
211
+ */
212
+ export function maskApiKey(key) {
213
+ const clean = (key || '').trim();
214
+ if (!clean)
215
+ return 'none';
216
+ if (clean.length <= 8)
217
+ return '********';
218
+ return `${clean.slice(0, 7)}...${clean.slice(-4)}`;
219
+ }
220
+ /**
221
+ * Save user OpenRouter key into local encrypted configuration vault.
222
+ */
223
+ export function saveOpenRouterKey(apiKey, options = {}) {
224
+ const cleanKey = (apiKey || '').trim();
225
+ if (!cleanKey) {
226
+ throw new OpenRouterAuthError('Cannot save an empty OpenRouter API key.');
227
+ }
228
+ const store = options.store || { loadConfig, saveConfig };
229
+ const currentConfig = store.loadConfig() || {};
230
+ const providerKeys = {
231
+ ...(currentConfig.providerKeys && typeof currentConfig.providerKeys === 'object' ? currentConfig.providerKeys : {})
232
+ };
233
+ providerKeys['openrouter'] = cleanKey;
234
+ currentConfig.providerKeys = providerKeys;
235
+ if (options.dataCollection) {
236
+ currentConfig.openrouterDataCollection = options.dataCollection;
237
+ }
238
+ else if (!currentConfig.openrouterDataCollection) {
239
+ currentConfig.openrouterDataCollection = 'deny';
240
+ }
241
+ if (options.setAsActive) {
242
+ currentConfig.provider = 'openrouter';
243
+ currentConfig.model = OPENROUTER_FREE_MODEL;
244
+ currentConfig.apiKey = cleanKey;
245
+ }
246
+ store.saveConfig(currentConfig);
247
+ return currentConfig;
248
+ }
249
+ /**
250
+ * Disconnect OpenRouter credentials from local vault.
251
+ */
252
+ export function disconnectOpenRouter(store = { loadConfig, saveConfig }) {
253
+ const currentConfig = store.loadConfig() || {};
254
+ const providerKeys = {
255
+ ...(currentConfig.providerKeys && typeof currentConfig.providerKeys === 'object' ? currentConfig.providerKeys : {})
256
+ };
257
+ delete providerKeys['openrouter'];
258
+ currentConfig.providerKeys = providerKeys;
259
+ if (currentConfig.provider === 'openrouter') {
260
+ currentConfig.provider = 'deepseek';
261
+ currentConfig.model = 'deepseek-chat';
262
+ currentConfig.apiKey = providerKeys['deepseek'] || '';
263
+ }
264
+ store.saveConfig(currentConfig);
265
+ return currentConfig;
266
+ }
267
+ /**
268
+ * Retrieve live OpenRouter connection and privacy status.
269
+ */
270
+ export function getOpenRouterStatus(cfg) {
271
+ const config = cfg || loadConfig() || {};
272
+ const vaultKey = config.providerKeys?.openrouter || (config.provider === 'openrouter' ? config.apiKey : '');
273
+ const envKey = process.env.OPENROUTER_API_KEY;
274
+ const connectedKey = vaultKey || envKey || '';
275
+ const isConnected = Boolean(connectedKey);
276
+ const isActive = config.provider === 'openrouter';
277
+ const currentModel = isActive ? (config.model || OPENROUTER_FREE_MODEL) : OPENROUTER_FREE_MODEL;
278
+ const dataCollection = config.openrouterDataCollection === 'allow' ? 'allow' : 'deny';
279
+ return {
280
+ connected: isConnected,
281
+ active: isActive,
282
+ model: currentModel,
283
+ dataCollection,
284
+ maskedKey: isConnected ? maskApiKey(connectedKey) : undefined,
285
+ keySource: vaultKey ? 'vault' : (envKey ? 'environment' : undefined)
286
+ };
287
+ }
288
+ /**
289
+ * Update user's OpenRouter data collection preference.
290
+ */
291
+ export function setOpenRouterDataCollection(preference, store = { loadConfig, saveConfig }) {
292
+ const config = store.loadConfig() || {};
293
+ config.openrouterDataCollection = preference;
294
+ store.saveConfig(config);
295
+ return config;
296
+ }
@@ -0,0 +1,378 @@
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
+
9
+ import http from 'node:http';
10
+ import crypto from 'node:crypto';
11
+ import { URL } from 'node:url';
12
+ import { loadConfig, saveConfig } from '../config.js';
13
+ import { openWithNativeOS } from '../tools/desktopOpen.js';
14
+
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
+
19
+ export interface PkceCodes {
20
+ codeVerifier: string;
21
+ codeChallenge: string;
22
+ codeChallengeMethod: 'S256';
23
+ state: string;
24
+ }
25
+
26
+ export interface OpenRouterStatus {
27
+ connected: boolean;
28
+ active: boolean;
29
+ model: string;
30
+ dataCollection: 'deny' | 'allow';
31
+ maskedKey?: string | undefined;
32
+ keySource?: 'vault' | 'environment' | undefined;
33
+ }
34
+
35
+ export class OpenRouterAuthError extends Error {
36
+ constructor(message: string) {
37
+ super(message);
38
+ this.name = 'OpenRouterAuthError';
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Generate cryptographically secure PKCE verifier, S256 challenge, and CSRF state token.
44
+ */
45
+ export function generatePkceCodes(): PkceCodes {
46
+ // 32 random bytes as base64url string yields 43 characters (RFC 7636 compliant: 43-128 chars)
47
+ const codeVerifier = crypto.randomBytes(32).toString('base64url');
48
+ const codeChallenge = crypto
49
+ .createHash('sha256')
50
+ .update(codeVerifier)
51
+ .digest('base64url');
52
+ const state = crypto.randomBytes(16).toString('hex');
53
+
54
+ return {
55
+ codeVerifier,
56
+ codeChallenge,
57
+ codeChallengeMethod: 'S256',
58
+ state
59
+ };
60
+ }
61
+
62
+ /**
63
+ * Build the official OpenRouter OAuth authorization URL.
64
+ */
65
+ export function buildAuthorizationUrl(callbackUrl: string, codeChallenge: string, state: string): string {
66
+ const url = new URL(OPENROUTER_AUTH_URL);
67
+ url.searchParams.set('callback_url', callbackUrl);
68
+ url.searchParams.set('code_challenge', codeChallenge);
69
+ url.searchParams.set('code_challenge_method', 'S256');
70
+ url.searchParams.set('state', state);
71
+ return url.toString();
72
+ }
73
+
74
+ /**
75
+ * Exchange the authorization code for an OpenRouter API key using PKCE verifier.
76
+ */
77
+ export async function exchangeCodeForApiKey(
78
+ code: string,
79
+ codeVerifier: string,
80
+ fetchFn: typeof fetch = fetch
81
+ ): Promise<string> {
82
+ const cleanCode = (code || '').trim();
83
+ const cleanVerifier = (codeVerifier || '').trim();
84
+
85
+ if (!cleanCode) {
86
+ throw new OpenRouterAuthError('Authorization code cannot be empty.');
87
+ }
88
+ if (!cleanVerifier) {
89
+ throw new OpenRouterAuthError('PKCE code verifier cannot be empty.');
90
+ }
91
+
92
+ const payload = {
93
+ code: cleanCode,
94
+ code_verifier: cleanVerifier,
95
+ code_challenge_method: 'S256'
96
+ };
97
+
98
+ let response: Response;
99
+ try {
100
+ response = await fetchFn(OPENROUTER_TOKEN_EXCHANGE_URL, {
101
+ method: 'POST',
102
+ headers: {
103
+ 'Content-Type': 'application/json',
104
+ 'HTTP-Referer': 'https://causyne.com',
105
+ 'X-Title': 'Causyne Agent'
106
+ },
107
+ body: JSON.stringify(payload)
108
+ });
109
+ } catch (err: any) {
110
+ throw new OpenRouterAuthError(`Failed to reach OpenRouter token exchange: ${err?.message || err}`);
111
+ }
112
+
113
+ if (!response.ok) {
114
+ const errorBody = await response.text().catch(() => '');
115
+ throw new OpenRouterAuthError(
116
+ `OpenRouter token exchange failed (HTTP ${response.status}): ${errorBody || 'Invalid code or verifier'}`
117
+ );
118
+ }
119
+
120
+ const data = (await response.json().catch(() => null)) as { key?: string } | null;
121
+ const apiKey = data?.key?.trim();
122
+ if (!apiKey) {
123
+ throw new OpenRouterAuthError('OpenRouter response did not contain an API key.');
124
+ }
125
+
126
+ return apiKey;
127
+ }
128
+
129
+ /**
130
+ * Start loopback HTTP server on 127.0.0.1 to receive the OAuth redirect code.
131
+ */
132
+ export async function startLoopbackAuth(options: {
133
+ timeoutMs?: number;
134
+ openBrowser?: boolean;
135
+ fetchFn?: typeof fetch;
136
+ onUrlReady?: (url: string) => void;
137
+ } = {}): Promise<{ apiKey: string }> {
138
+ const timeoutMs = options.timeoutMs ?? 120_000;
139
+ const openBrowser = options.openBrowser ?? true;
140
+ const fetchFn = options.fetchFn ?? fetch;
141
+
142
+ const pkce = generatePkceCodes();
143
+
144
+ return new Promise<{ apiKey: string }>((resolve, reject) => {
145
+ let resolved = false;
146
+ let timeoutTimer: NodeJS.Timeout | null = null;
147
+
148
+ const cleanup = () => {
149
+ if (timeoutTimer) {
150
+ clearTimeout(timeoutTimer);
151
+ timeoutTimer = null;
152
+ }
153
+ try {
154
+ server.close();
155
+ } catch {
156
+ // Ignore close errors
157
+ }
158
+ };
159
+
160
+ const server = http.createServer(async (req, res) => {
161
+ try {
162
+ const reqUrl = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
163
+ if (reqUrl.pathname !== '/callback') {
164
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
165
+ res.end('Not Found');
166
+ return;
167
+ }
168
+
169
+ const code = reqUrl.searchParams.get('code');
170
+ const state = reqUrl.searchParams.get('state');
171
+
172
+ if (!state || state !== pkce.state) {
173
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
174
+ res.end(
175
+ '<html><body style="font-family:sans-serif;padding:32px;background:#111;color:#eee;">' +
176
+ '<h2 style="color:#ef4444;">Authorization Error: State Mismatch</h2>' +
177
+ '<p>The received CSRF verification state did not match the session. Please try again.</p>' +
178
+ '</body></html>'
179
+ );
180
+ if (!resolved) {
181
+ resolved = true;
182
+ cleanup();
183
+ reject(new OpenRouterAuthError('State mismatch detected during OpenRouter callback.'));
184
+ }
185
+ return;
186
+ }
187
+
188
+ if (!code) {
189
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
190
+ res.end(
191
+ '<html><body style="font-family:sans-serif;padding:32px;background:#111;color:#eee;">' +
192
+ '<h2 style="color:#ef4444;">Authorization Failed</h2>' +
193
+ '<p>No authorization code was returned by OpenRouter.</p>' +
194
+ '</body></html>'
195
+ );
196
+ if (!resolved) {
197
+ resolved = true;
198
+ cleanup();
199
+ reject(new OpenRouterAuthError('No authorization code returned from callback.'));
200
+ }
201
+ return;
202
+ }
203
+
204
+ // Send friendly HTML response to user's browser
205
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
206
+ res.end(
207
+ '<html><body style="font-family:sans-serif;padding:40px;background:#0d1117;color:#c9d1d9;text-align:center;">' +
208
+ '<h2 style="color:#2ea043;margin-bottom:12px;">Causyne Agent Connected Successfully</h2>' +
209
+ '<p style="font-size:16px;color:#8b949e;">Your OpenRouter account has been authorized. You can close this window and return to your terminal.</p>' +
210
+ '</body></html>'
211
+ );
212
+
213
+ // Perform token exchange
214
+ const apiKey = await exchangeCodeForApiKey(code, pkce.codeVerifier, fetchFn);
215
+
216
+ if (!resolved) {
217
+ resolved = true;
218
+ cleanup();
219
+ resolve({ apiKey });
220
+ }
221
+ } catch (err: any) {
222
+ if (!resolved) {
223
+ resolved = true;
224
+ cleanup();
225
+ reject(err);
226
+ }
227
+ }
228
+ });
229
+
230
+ server.on('error', (err) => {
231
+ if (!resolved) {
232
+ resolved = true;
233
+ cleanup();
234
+ reject(new OpenRouterAuthError(`Loopback server failed to bind: ${err.message}`));
235
+ }
236
+ });
237
+
238
+ server.listen(0, '127.0.0.1', () => {
239
+ const addr = server.address();
240
+ if (!addr || typeof addr === 'string') {
241
+ cleanup();
242
+ reject(new OpenRouterAuthError('Failed to retrieve loopback server port.'));
243
+ return;
244
+ }
245
+
246
+ const callbackUrl = `http://127.0.0.1:${addr.port}/callback`;
247
+ const authUrl = buildAuthorizationUrl(callbackUrl, pkce.codeChallenge, pkce.state);
248
+
249
+ if (options.onUrlReady) {
250
+ options.onUrlReady(authUrl);
251
+ }
252
+
253
+ if (openBrowser) {
254
+ openWithNativeOS(authUrl).catch(() => {
255
+ // If browser opening fails, user can copy URL manually
256
+ });
257
+ }
258
+
259
+ timeoutTimer = setTimeout(() => {
260
+ if (!resolved) {
261
+ resolved = true;
262
+ cleanup();
263
+ reject(new OpenRouterAuthError(`Authorization timed out after ${Math.round(timeoutMs / 1000)} seconds.`));
264
+ }
265
+ }, timeoutMs);
266
+ });
267
+ });
268
+ }
269
+
270
+ /**
271
+ * Mask an API key for safe display in logs and status screens.
272
+ */
273
+ export function maskApiKey(key: string): string {
274
+ const clean = (key || '').trim();
275
+ if (!clean) return 'none';
276
+ if (clean.length <= 8) return '********';
277
+ return `${clean.slice(0, 7)}...${clean.slice(-4)}`;
278
+ }
279
+
280
+ /**
281
+ * Save user OpenRouter key into local encrypted configuration vault.
282
+ */
283
+ export function saveOpenRouterKey(
284
+ apiKey: string,
285
+ options: {
286
+ dataCollection?: 'deny' | 'allow';
287
+ setAsActive?: boolean;
288
+ store?: { loadConfig(): any; saveConfig(cfg: any): void };
289
+ } = {}
290
+ ): Record<string, any> {
291
+ const cleanKey = (apiKey || '').trim();
292
+ if (!cleanKey) {
293
+ throw new OpenRouterAuthError('Cannot save an empty OpenRouter API key.');
294
+ }
295
+
296
+ const store = options.store || { loadConfig, saveConfig };
297
+ const currentConfig = store.loadConfig() || {};
298
+ const providerKeys = {
299
+ ...(currentConfig.providerKeys && typeof currentConfig.providerKeys === 'object' ? currentConfig.providerKeys : {})
300
+ };
301
+
302
+ providerKeys['openrouter'] = cleanKey;
303
+ currentConfig.providerKeys = providerKeys;
304
+
305
+ if (options.dataCollection) {
306
+ currentConfig.openrouterDataCollection = options.dataCollection;
307
+ } else if (!currentConfig.openrouterDataCollection) {
308
+ currentConfig.openrouterDataCollection = 'deny';
309
+ }
310
+
311
+ if (options.setAsActive) {
312
+ currentConfig.provider = 'openrouter';
313
+ currentConfig.model = OPENROUTER_FREE_MODEL;
314
+ currentConfig.apiKey = cleanKey;
315
+ }
316
+
317
+ store.saveConfig(currentConfig);
318
+ return currentConfig;
319
+ }
320
+
321
+ /**
322
+ * Disconnect OpenRouter credentials from local vault.
323
+ */
324
+ export function disconnectOpenRouter(store: { loadConfig(): any; saveConfig(cfg: any): void } = { loadConfig, saveConfig }): Record<string, any> {
325
+ const currentConfig = store.loadConfig() || {};
326
+ const providerKeys = {
327
+ ...(currentConfig.providerKeys && typeof currentConfig.providerKeys === 'object' ? currentConfig.providerKeys : {})
328
+ };
329
+
330
+ delete providerKeys['openrouter'];
331
+ currentConfig.providerKeys = providerKeys;
332
+
333
+ if (currentConfig.provider === 'openrouter') {
334
+ currentConfig.provider = 'deepseek';
335
+ currentConfig.model = 'deepseek-chat';
336
+ currentConfig.apiKey = providerKeys['deepseek'] || '';
337
+ }
338
+
339
+ store.saveConfig(currentConfig);
340
+ return currentConfig;
341
+ }
342
+
343
+ /**
344
+ * Retrieve live OpenRouter connection and privacy status.
345
+ */
346
+ export function getOpenRouterStatus(cfg?: Record<string, any>): OpenRouterStatus {
347
+ const config = cfg || loadConfig() || {};
348
+ const vaultKey = config.providerKeys?.openrouter || (config.provider === 'openrouter' ? config.apiKey : '');
349
+ const envKey = process.env.OPENROUTER_API_KEY;
350
+
351
+ const connectedKey = vaultKey || envKey || '';
352
+ const isConnected = Boolean(connectedKey);
353
+ const isActive = config.provider === 'openrouter';
354
+ const currentModel = isActive ? (config.model || OPENROUTER_FREE_MODEL) : OPENROUTER_FREE_MODEL;
355
+ const dataCollection: 'deny' | 'allow' = config.openrouterDataCollection === 'allow' ? 'allow' : 'deny';
356
+
357
+ return {
358
+ connected: isConnected,
359
+ active: isActive,
360
+ model: currentModel,
361
+ dataCollection,
362
+ maskedKey: isConnected ? maskApiKey(connectedKey) : undefined,
363
+ keySource: vaultKey ? 'vault' : (envKey ? 'environment' : undefined)
364
+ };
365
+ }
366
+
367
+ /**
368
+ * Update user's OpenRouter data collection preference.
369
+ */
370
+ export function setOpenRouterDataCollection(
371
+ preference: 'deny' | 'allow',
372
+ store: { loadConfig(): any; saveConfig(cfg: any): void } = { loadConfig, saveConfig }
373
+ ): Record<string, any> {
374
+ const config = store.loadConfig() || {};
375
+ config.openrouterDataCollection = preference;
376
+ store.saveConfig(config);
377
+ return config;
378
+ }