@pixelbyte-software/pixcode 1.33.8 → 1.33.10

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 (67) hide show
  1. package/dist/api-docs.html +395 -879
  2. package/dist/assets/{index-JU38YIxa.js → index-B_dU5AHA.js} +153 -165
  3. package/dist/favicon.svg +8 -8
  4. package/dist/icons/icon-128x128.svg +9 -9
  5. package/dist/icons/icon-144x144.svg +9 -9
  6. package/dist/icons/icon-152x152.svg +9 -9
  7. package/dist/icons/icon-192x192.svg +9 -9
  8. package/dist/icons/icon-384x384.svg +9 -9
  9. package/dist/icons/icon-512x512.svg +9 -9
  10. package/dist/icons/icon-72x72.svg +9 -9
  11. package/dist/icons/icon-96x96.svg +9 -9
  12. package/dist/icons/icon-template.svg +9 -9
  13. package/dist/index.html +1 -1
  14. package/dist/logo.svg +12 -12
  15. package/dist/openapi.yaml +1311 -0
  16. package/dist-server/server/gemini-cli.js +59 -0
  17. package/dist-server/server/gemini-cli.js.map +1 -1
  18. package/dist-server/server/index.js +6 -1
  19. package/dist-server/server/index.js.map +1 -1
  20. package/dist-server/server/middleware/auth.js +51 -9
  21. package/dist-server/server/middleware/auth.js.map +1 -1
  22. package/dist-server/server/modules/providers/list/opencode/opencode-sessions.provider.js +54 -15
  23. package/dist-server/server/modules/providers/list/opencode/opencode-sessions.provider.js.map +1 -1
  24. package/dist-server/server/modules/providers/list/qwen/qwen-sessions.provider.js +46 -0
  25. package/dist-server/server/modules/providers/list/qwen/qwen-sessions.provider.js.map +1 -1
  26. package/dist-server/server/modules/providers/provider.routes.js +32 -1
  27. package/dist-server/server/modules/providers/provider.routes.js.map +1 -1
  28. package/dist-server/server/opencode-cli.js +37 -1
  29. package/dist-server/server/opencode-cli.js.map +1 -1
  30. package/dist-server/server/opencode-response-handler.js +36 -34
  31. package/dist-server/server/opencode-response-handler.js.map +1 -1
  32. package/dist-server/server/routes/agent.js +187 -56
  33. package/dist-server/server/routes/agent.js.map +1 -1
  34. package/dist-server/server/routes/projects.js +134 -8
  35. package/dist-server/server/routes/projects.js.map +1 -1
  36. package/dist-server/server/services/provider-credentials.js +42 -8
  37. package/dist-server/server/services/provider-credentials.js.map +1 -1
  38. package/package.json +178 -178
  39. package/scripts/rest-sweep.mjs +93 -0
  40. package/server/database/db.js +794 -794
  41. package/server/database/json-store.js +194 -194
  42. package/server/gemini-cli.js +60 -0
  43. package/server/index.js +6 -1
  44. package/server/middleware/auth.js +50 -9
  45. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +130 -130
  46. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  47. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -193
  48. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  49. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +145 -145
  50. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  51. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -218
  52. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  53. package/server/modules/providers/provider.routes.ts +37 -4
  54. package/server/modules/providers/shared/provider-configs.ts +142 -142
  55. package/server/opencode-cli.js +37 -1
  56. package/server/opencode-response-handler.js +107 -100
  57. package/server/qwen-code-cli.js +395 -395
  58. package/server/qwen-response-handler.js +73 -73
  59. package/server/routes/agent.js +178 -58
  60. package/server/routes/projects.js +136 -8
  61. package/server/routes/qwen.js +27 -27
  62. package/server/services/external-access.js +171 -171
  63. package/server/services/provider-credentials.js +189 -155
  64. package/server/services/provider-models.js +381 -381
  65. package/server/services/telegram/telegram-http-client.js +130 -130
  66. package/server/services/vapid-keys.js +36 -36
  67. package/server/utils/port-access.js +209 -209
@@ -1,194 +1,194 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- /**
5
- * Minimal JSON-backed store with atomic writes.
6
- *
7
- * Replaces the `better-sqlite3` auth/session/telegram DB from previous
8
- * releases. The backing store is kilobytes, not gigabytes — a SQL engine
9
- * was overkill and the native compile dragged install-time warnings +
10
- * on-disk WAL files that confused users. This impl:
11
- *
12
- * - Loads the entire store into memory on first access (synchronous
13
- * readFileSync) and keeps it cached; all subsequent reads hit the
14
- * in-memory structure.
15
- * - Every write flushes the whole document via write-to-tmp + rename
16
- * so a crash mid-write can never truncate the file; either the
17
- * old file survives or the new one is fully written.
18
- * - All operations are synchronous and rely on Node's single-threaded
19
- * JS execution for concurrency safety. No async queue, no locks.
20
- *
21
- * The schema is a flat object with one array per "table":
22
- * { _version, _sequences: {<table>: nextId}, users: [...], ... }
23
- *
24
- * Callers use helpers like `insert`, `updateWhere`, `findWhere`,
25
- * `deleteWhere` rather than composing queries — this is a key/value map
26
- * with filter helpers, not a SQL engine.
27
- */
28
-
29
- const CURRENT_VERSION = 1;
30
-
31
- // Tables the store manages — empty arrays on a fresh file.
32
- const EMPTY_STORE = () => ({
33
- _version: CURRENT_VERSION,
34
- _sequences: {
35
- users: 0,
36
- api_keys: 0,
37
- user_credentials: 0,
38
- vapid_keys: 0,
39
- push_subscriptions: 0,
40
- },
41
- users: [],
42
- api_keys: [],
43
- user_credentials: [],
44
- user_notification_preferences: [], // each row: { user_id, preferences_json, updated_at }
45
- vapid_keys: [],
46
- push_subscriptions: [],
47
- session_names: [], // each row: { session_id, provider, custom_name, created_at, updated_at }
48
- app_config: [], // each row: { key, value, created_at }
49
- telegram_config: [], // 0 or 1 row: { id=1, bot_token, bot_username, updated_at }
50
- telegram_links: [], // each row: { user_id, chat_id, ... }
51
- });
52
-
53
- export class JsonStore {
54
- constructor(filePath) {
55
- this.filePath = filePath;
56
- this.tmpPath = `${filePath}.tmp`;
57
- this.data = null;
58
- this._ensureLoaded();
59
- }
60
-
61
- _ensureLoaded() {
62
- if (this.data) return;
63
-
64
- // Ensure parent directory exists — matches the old better-sqlite3
65
- // behavior where the directory was created during initialization.
66
- const dir = path.dirname(this.filePath);
67
- if (!fs.existsSync(dir)) {
68
- fs.mkdirSync(dir, { recursive: true });
69
- }
70
-
71
- if (!fs.existsSync(this.filePath)) {
72
- this.data = EMPTY_STORE();
73
- this._flush();
74
- return;
75
- }
76
-
77
- try {
78
- const raw = fs.readFileSync(this.filePath, 'utf8');
79
- const parsed = JSON.parse(raw);
80
- // Fill missing keys from EMPTY_STORE so adding a new "table" in a
81
- // later schema doesn't crash a fresh deploy reading an old file.
82
- this.data = { ...EMPTY_STORE(), ...parsed };
83
- // Ensure each well-known array key is actually an array — defends
84
- // against a hand-edited file that set one to null or an object.
85
- const empty = EMPTY_STORE();
86
- for (const key of Object.keys(empty)) {
87
- if (key === '_version' || key === '_sequences') continue;
88
- if (!Array.isArray(this.data[key])) {
89
- this.data[key] = [];
90
- }
91
- }
92
- this.data._sequences = { ...empty._sequences, ...(parsed._sequences || {}) };
93
- } catch (err) {
94
- // Corrupted file — back up and start fresh. Never hide this; it's
95
- // very likely user-visible (logins will reset).
96
- const backup = `${this.filePath}.corrupt-${Date.now()}`;
97
- console.error(`[JsonStore] Failed to read ${this.filePath}: ${err.message}. Backing up to ${backup}.`);
98
- try { fs.renameSync(this.filePath, backup); } catch { /* noop */ }
99
- this.data = EMPTY_STORE();
100
- this._flush();
101
- }
102
- }
103
-
104
- _flush() {
105
- const serialized = JSON.stringify(this.data, null, 2);
106
- fs.writeFileSync(this.tmpPath, serialized, 'utf8');
107
- fs.renameSync(this.tmpPath, this.filePath);
108
- }
109
-
110
- // ---------- Raw access ----------
111
- get raw() {
112
- this._ensureLoaded();
113
- return this.data;
114
- }
115
-
116
- save() { this._flush(); }
117
-
118
- // ---------- Sequence (AUTOINCREMENT) ----------
119
- nextId(table) {
120
- this._ensureLoaded();
121
- this.data._sequences[table] = (this.data._sequences[table] || 0) + 1;
122
- return this.data._sequences[table];
123
- }
124
-
125
- // ---------- Query helpers ----------
126
- findWhere(table, predicate) {
127
- this._ensureLoaded();
128
- return this.data[table].find(predicate) || null;
129
- }
130
-
131
- filterWhere(table, predicate) {
132
- this._ensureLoaded();
133
- return this.data[table].filter(predicate);
134
- }
135
-
136
- count(table, predicate) {
137
- this._ensureLoaded();
138
- if (!predicate) return this.data[table].length;
139
- return this.data[table].filter(predicate).length;
140
- }
141
-
142
- // ---------- Mutation helpers ----------
143
- insert(table, row, { autoId = true, sequenceKey } = {}) {
144
- this._ensureLoaded();
145
- const finalRow = { ...row };
146
- if (autoId && finalRow.id === undefined) {
147
- finalRow.id = this.nextId(sequenceKey || table);
148
- }
149
- this.data[table].push(finalRow);
150
- this._flush();
151
- return finalRow;
152
- }
153
-
154
- updateWhere(table, predicate, updater) {
155
- this._ensureLoaded();
156
- let changed = 0;
157
- for (const row of this.data[table]) {
158
- if (predicate(row)) {
159
- const patch = typeof updater === 'function' ? updater(row) : updater;
160
- Object.assign(row, patch);
161
- changed += 1;
162
- }
163
- }
164
- if (changed > 0) this._flush();
165
- return changed;
166
- }
167
-
168
- upsertWhere(table, predicate, row) {
169
- this._ensureLoaded();
170
- const existing = this.data[table].find(predicate);
171
- if (existing) {
172
- Object.assign(existing, row);
173
- this._flush();
174
- return existing;
175
- }
176
- return this.insert(table, row);
177
- }
178
-
179
- deleteWhere(table, predicate) {
180
- this._ensureLoaded();
181
- const before = this.data[table].length;
182
- this.data[table] = this.data[table].filter((row) => !predicate(row));
183
- const removed = before - this.data[table].length;
184
- if (removed > 0) this._flush();
185
- return removed;
186
- }
187
- }
188
-
189
- /**
190
- * Helper — ISO timestamp matching the DATETIME format SQLite used to
191
- * write. Stored as a plain ISO string; no one actually parses it beyond
192
- * displaying "last login X hours ago".
193
- */
194
- export const nowIso = () => new Date().toISOString();
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /**
5
+ * Minimal JSON-backed store with atomic writes.
6
+ *
7
+ * Replaces the `better-sqlite3` auth/session/telegram DB from previous
8
+ * releases. The backing store is kilobytes, not gigabytes — a SQL engine
9
+ * was overkill and the native compile dragged install-time warnings +
10
+ * on-disk WAL files that confused users. This impl:
11
+ *
12
+ * - Loads the entire store into memory on first access (synchronous
13
+ * readFileSync) and keeps it cached; all subsequent reads hit the
14
+ * in-memory structure.
15
+ * - Every write flushes the whole document via write-to-tmp + rename
16
+ * so a crash mid-write can never truncate the file; either the
17
+ * old file survives or the new one is fully written.
18
+ * - All operations are synchronous and rely on Node's single-threaded
19
+ * JS execution for concurrency safety. No async queue, no locks.
20
+ *
21
+ * The schema is a flat object with one array per "table":
22
+ * { _version, _sequences: {<table>: nextId}, users: [...], ... }
23
+ *
24
+ * Callers use helpers like `insert`, `updateWhere`, `findWhere`,
25
+ * `deleteWhere` rather than composing queries — this is a key/value map
26
+ * with filter helpers, not a SQL engine.
27
+ */
28
+
29
+ const CURRENT_VERSION = 1;
30
+
31
+ // Tables the store manages — empty arrays on a fresh file.
32
+ const EMPTY_STORE = () => ({
33
+ _version: CURRENT_VERSION,
34
+ _sequences: {
35
+ users: 0,
36
+ api_keys: 0,
37
+ user_credentials: 0,
38
+ vapid_keys: 0,
39
+ push_subscriptions: 0,
40
+ },
41
+ users: [],
42
+ api_keys: [],
43
+ user_credentials: [],
44
+ user_notification_preferences: [], // each row: { user_id, preferences_json, updated_at }
45
+ vapid_keys: [],
46
+ push_subscriptions: [],
47
+ session_names: [], // each row: { session_id, provider, custom_name, created_at, updated_at }
48
+ app_config: [], // each row: { key, value, created_at }
49
+ telegram_config: [], // 0 or 1 row: { id=1, bot_token, bot_username, updated_at }
50
+ telegram_links: [], // each row: { user_id, chat_id, ... }
51
+ });
52
+
53
+ export class JsonStore {
54
+ constructor(filePath) {
55
+ this.filePath = filePath;
56
+ this.tmpPath = `${filePath}.tmp`;
57
+ this.data = null;
58
+ this._ensureLoaded();
59
+ }
60
+
61
+ _ensureLoaded() {
62
+ if (this.data) return;
63
+
64
+ // Ensure parent directory exists — matches the old better-sqlite3
65
+ // behavior where the directory was created during initialization.
66
+ const dir = path.dirname(this.filePath);
67
+ if (!fs.existsSync(dir)) {
68
+ fs.mkdirSync(dir, { recursive: true });
69
+ }
70
+
71
+ if (!fs.existsSync(this.filePath)) {
72
+ this.data = EMPTY_STORE();
73
+ this._flush();
74
+ return;
75
+ }
76
+
77
+ try {
78
+ const raw = fs.readFileSync(this.filePath, 'utf8');
79
+ const parsed = JSON.parse(raw);
80
+ // Fill missing keys from EMPTY_STORE so adding a new "table" in a
81
+ // later schema doesn't crash a fresh deploy reading an old file.
82
+ this.data = { ...EMPTY_STORE(), ...parsed };
83
+ // Ensure each well-known array key is actually an array — defends
84
+ // against a hand-edited file that set one to null or an object.
85
+ const empty = EMPTY_STORE();
86
+ for (const key of Object.keys(empty)) {
87
+ if (key === '_version' || key === '_sequences') continue;
88
+ if (!Array.isArray(this.data[key])) {
89
+ this.data[key] = [];
90
+ }
91
+ }
92
+ this.data._sequences = { ...empty._sequences, ...(parsed._sequences || {}) };
93
+ } catch (err) {
94
+ // Corrupted file — back up and start fresh. Never hide this; it's
95
+ // very likely user-visible (logins will reset).
96
+ const backup = `${this.filePath}.corrupt-${Date.now()}`;
97
+ console.error(`[JsonStore] Failed to read ${this.filePath}: ${err.message}. Backing up to ${backup}.`);
98
+ try { fs.renameSync(this.filePath, backup); } catch { /* noop */ }
99
+ this.data = EMPTY_STORE();
100
+ this._flush();
101
+ }
102
+ }
103
+
104
+ _flush() {
105
+ const serialized = JSON.stringify(this.data, null, 2);
106
+ fs.writeFileSync(this.tmpPath, serialized, 'utf8');
107
+ fs.renameSync(this.tmpPath, this.filePath);
108
+ }
109
+
110
+ // ---------- Raw access ----------
111
+ get raw() {
112
+ this._ensureLoaded();
113
+ return this.data;
114
+ }
115
+
116
+ save() { this._flush(); }
117
+
118
+ // ---------- Sequence (AUTOINCREMENT) ----------
119
+ nextId(table) {
120
+ this._ensureLoaded();
121
+ this.data._sequences[table] = (this.data._sequences[table] || 0) + 1;
122
+ return this.data._sequences[table];
123
+ }
124
+
125
+ // ---------- Query helpers ----------
126
+ findWhere(table, predicate) {
127
+ this._ensureLoaded();
128
+ return this.data[table].find(predicate) || null;
129
+ }
130
+
131
+ filterWhere(table, predicate) {
132
+ this._ensureLoaded();
133
+ return this.data[table].filter(predicate);
134
+ }
135
+
136
+ count(table, predicate) {
137
+ this._ensureLoaded();
138
+ if (!predicate) return this.data[table].length;
139
+ return this.data[table].filter(predicate).length;
140
+ }
141
+
142
+ // ---------- Mutation helpers ----------
143
+ insert(table, row, { autoId = true, sequenceKey } = {}) {
144
+ this._ensureLoaded();
145
+ const finalRow = { ...row };
146
+ if (autoId && finalRow.id === undefined) {
147
+ finalRow.id = this.nextId(sequenceKey || table);
148
+ }
149
+ this.data[table].push(finalRow);
150
+ this._flush();
151
+ return finalRow;
152
+ }
153
+
154
+ updateWhere(table, predicate, updater) {
155
+ this._ensureLoaded();
156
+ let changed = 0;
157
+ for (const row of this.data[table]) {
158
+ if (predicate(row)) {
159
+ const patch = typeof updater === 'function' ? updater(row) : updater;
160
+ Object.assign(row, patch);
161
+ changed += 1;
162
+ }
163
+ }
164
+ if (changed > 0) this._flush();
165
+ return changed;
166
+ }
167
+
168
+ upsertWhere(table, predicate, row) {
169
+ this._ensureLoaded();
170
+ const existing = this.data[table].find(predicate);
171
+ if (existing) {
172
+ Object.assign(existing, row);
173
+ this._flush();
174
+ return existing;
175
+ }
176
+ return this.insert(table, row);
177
+ }
178
+
179
+ deleteWhere(table, predicate) {
180
+ this._ensureLoaded();
181
+ const before = this.data[table].length;
182
+ this.data[table] = this.data[table].filter((row) => !predicate(row));
183
+ const removed = before - this.data[table].length;
184
+ if (removed > 0) this._flush();
185
+ return removed;
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Helper — ISO timestamp matching the DATETIME format SQLite used to
191
+ * write. Stored as a plain ISO string; no one actually parses it beyond
192
+ * displaying "last login X hours ago".
193
+ */
194
+ export const nowIso = () => new Date().toISOString();
@@ -15,6 +15,48 @@ import { createNormalizedMessage } from './shared/utils.js';
15
15
 
16
16
  let activeGeminiProcesses = new Map(); // Track active processes by session ID
17
17
 
18
+ /**
19
+ * Auto-create `~/.gemini/settings.json` when the user has signed in via OAuth
20
+ * (so `oauth_creds.json` exists) but never opened the Gemini TUI to write the
21
+ * `selectedAuthType` field. Without this, `gemini --prompt … --output-format
22
+ * stream-json --yolo` exits 41 with "Please set an Auth method in your
23
+ * settings.json" — even though credentials are perfectly valid. We respect a
24
+ * pre-existing `settings.json` and never overwrite a chosen auth type.
25
+ *
26
+ * Triggered every spawn (cheap: one fs.access + maybe one tiny write).
27
+ */
28
+ async function ensureGeminiSettingsJson() {
29
+ const home = os.homedir();
30
+ const dir = path.join(home, '.gemini');
31
+ const settingsPath = path.join(dir, 'settings.json');
32
+ const oauthPath = path.join(dir, 'oauth_creds.json');
33
+ const apiKey = process.env.GEMINI_API_KEY;
34
+
35
+ try {
36
+ await fs.access(settingsPath);
37
+ return; // user-managed, leave it.
38
+ } catch { /* missing — we may create it */ }
39
+
40
+ let selectedAuthType = null;
41
+ if (apiKey && apiKey.trim()) {
42
+ selectedAuthType = 'gemini-api-key';
43
+ } else {
44
+ try {
45
+ await fs.access(oauthPath);
46
+ selectedAuthType = 'oauth-personal';
47
+ } catch { /* no oauth either */ }
48
+ }
49
+ if (!selectedAuthType) return;
50
+
51
+ try {
52
+ await fs.mkdir(dir, { recursive: true });
53
+ await fs.writeFile(settingsPath, JSON.stringify({ selectedAuthType }, null, 2), { mode: 0o600 });
54
+ console.log(`[gemini] auto-bootstrapped ~/.gemini/settings.json with selectedAuthType="${selectedAuthType}"`);
55
+ } catch (error) {
56
+ console.warn('[gemini] failed to bootstrap settings.json:', error?.message || error);
57
+ }
58
+ }
59
+
18
60
  async function spawnGemini(command, options = {}, ws) {
19
61
  const { sessionId, projectPath, cwd, toolsSettings, permissionMode, images, sessionSummary } = options;
20
62
  let capturedSessionId = sessionId; // Track session ID throughout the process
@@ -174,6 +216,24 @@ async function spawnGemini(command, options = {}, ws) {
174
216
  // exporting GEMINI_API_KEY in their shell.
175
217
  const spawnEnv = await buildSpawnEnv('gemini');
176
218
 
219
+ // OAuth-only users never opened the TUI → no settings.json → spawn dies
220
+ // with exit 41. Bootstrap it once.
221
+ await ensureGeminiSettingsJson();
222
+
223
+ // Headless OAuth handshake. Without this Gemini exits 41 with "Please
224
+ // set an Auth method..." even when ~/.gemini/oauth_creds.json is fully
225
+ // valid — the CLI gates oauth-personal mode behind GOOGLE_GENAI_USE_GCA
226
+ // when running non-interactively. Only set when the user hasn't supplied
227
+ // an API key (which has its own auth path).
228
+ if (!spawnEnv.GEMINI_API_KEY) {
229
+ spawnEnv.GOOGLE_GENAI_USE_GCA = 'true';
230
+ }
231
+ // `--yolo` skips approval prompts but Gemini still refuses to operate
232
+ // on directories it doesn't recognise as trusted. There's no
233
+ // interactive prompt available in our pty-less spawn, so we set the
234
+ // documented headless escape hatch.
235
+ spawnEnv.GEMINI_CLI_TRUST_WORKSPACE = 'true';
236
+
177
237
  return new Promise((resolve, reject) => {
178
238
  const geminiProcess = spawnFunction(spawnCmd, spawnArgs, {
179
239
  cwd: workingDir,
package/server/index.js CHANGED
@@ -866,7 +866,12 @@ app.delete('/api/projects/:projectName', authenticateToken, async (req, res) =>
866
866
  await deleteProject(projectName, force, deleteData);
867
867
  res.json({ success: true });
868
868
  } catch (error) {
869
- res.status(500).json({ error: error.message });
869
+ // "Cannot delete project with existing sessions" is a precondition
870
+ // failure, not a server fault — surface it as 409 so clients can
871
+ // catch it and prompt the user to pass `?force=true` (or clean
872
+ // sessions first) instead of treating it like a crash.
873
+ const conflict = typeof error?.message === 'string' && error.message.includes('existing sessions');
874
+ res.status(conflict ? 409 : 500).json({ error: error.message });
870
875
  }
871
876
  });
872
877
 
@@ -1,5 +1,5 @@
1
1
  import jwt from 'jsonwebtoken';
2
- import { userDb, appConfigDb } from '../database/db.js';
2
+ import { userDb, appConfigDb, apiKeysDb } from '../database/db.js';
3
3
  import { IS_PLATFORM } from '../constants/config.js';
4
4
 
5
5
  // Use env var if set, otherwise auto-generate a unique secret per installation
@@ -36,21 +36,47 @@ const authenticateToken = async (req, res, next) => {
36
36
  }
37
37
  }
38
38
 
39
- // Normal OSS JWT validation
39
+ // Pull credentials from any of the supported transports.
40
+ // - Authorization: Bearer <jwt-or-apikey>
41
+ // - X-API-Key: <apikey> (legacy, kept for /api/agent compatibility)
42
+ // - ?token=<jwt> (EventSource workaround — can't set headers)
43
+ // - ?apiKey=<apikey> (EventSource workaround)
44
+ // Auth-token mode is decided by the prefix: keys generated by Pixcode start
45
+ // with `ck_` (see apiKeysDb.generateApiKey) — anything else falls through
46
+ // to JWT verification.
40
47
  const authHeader = req.headers['authorization'];
41
- let token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
48
+ const bearerToken = authHeader && authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : null;
49
+ const apiKeyHeader = req.headers['x-api-key'];
50
+ const queryToken = typeof req.query.token === 'string' ? req.query.token : null;
51
+ const queryApiKey = typeof req.query.apiKey === 'string' ? req.query.apiKey : null;
42
52
 
43
- // Also check query param for SSE endpoints (EventSource can't set headers)
44
- if (!token && req.query.token) {
45
- token = req.query.token;
53
+ // Try API-key paths first when the credential is unambiguously an API key.
54
+ const explicitApiKey = apiKeyHeader || queryApiKey
55
+ || (bearerToken && bearerToken.startsWith('ck_') ? bearerToken : null)
56
+ || (queryToken && queryToken.startsWith('ck_') ? queryToken : null);
57
+
58
+ if (explicitApiKey) {
59
+ try {
60
+ const user = apiKeysDb.validateApiKey(explicitApiKey);
61
+ if (!user) {
62
+ return res.status(401).json({ error: 'Invalid or inactive API key' });
63
+ }
64
+ req.user = user;
65
+ return next();
66
+ } catch (error) {
67
+ console.error('API key validation error:', error);
68
+ return res.status(500).json({ error: 'Authentication backend error' });
69
+ }
46
70
  }
47
71
 
48
- if (!token) {
72
+ // Otherwise fall back to JWT.
73
+ const jwtToken = bearerToken || queryToken;
74
+ if (!jwtToken) {
49
75
  return res.status(401).json({ error: 'Access denied. No token provided.' });
50
76
  }
51
77
 
52
78
  try {
53
- const decoded = jwt.verify(token, JWT_SECRET);
79
+ const decoded = jwt.verify(jwtToken, JWT_SECRET);
54
80
 
55
81
  // Verify user still exists and is active
56
82
  const user = userDb.getUserById(decoded.userId);
@@ -104,11 +130,26 @@ const authenticateWebSocket = (token) => {
104
130
  }
105
131
  }
106
132
 
107
- // Normal OSS JWT validation
133
+ // Normal OSS validation — accept either an API key (`ck_…`) or a JWT.
134
+ // Mirrors the REST `authenticateToken` middleware so any tool that has
135
+ // a `ck_` key (CI scripts, the api-tester subagent, the user's own
136
+ // automation, ...) can also open a WebSocket without first exchanging
137
+ // the key for a JWT.
108
138
  if (!token) {
109
139
  return null;
110
140
  }
111
141
 
142
+ if (typeof token === 'string' && token.startsWith('ck_')) {
143
+ try {
144
+ const user = apiKeysDb.validateApiKey(token);
145
+ if (!user) return null;
146
+ return { userId: user.id, username: user.username };
147
+ } catch (error) {
148
+ console.error('WebSocket API key validation error:', error);
149
+ return null;
150
+ }
151
+ }
152
+
112
153
  try {
113
154
  const decoded = jwt.verify(token, JWT_SECRET);
114
155
  // Verify user actually exists in database (matches REST authenticateToken behavior)