subconscious-cli 0.1.1 → 0.2.1

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/bin/auth.js ADDED
@@ -0,0 +1,366 @@
1
+ /**
2
+ * Authentication + credential storage for the Subconscious CLI.
3
+ *
4
+ * Login flow (localhost callback pattern, similar to Vercel/Supabase CLIs):
5
+ * 1. CLI generates a random `state` token (CSRF protection) and starts
6
+ * an ephemeral HTTP server on a random port bound to 127.0.0.1.
7
+ * 2. Opens the browser to {PLATFORM_URL}/cli/auth?port=...&state=...
8
+ * 3. The web app authenticates the user, generates an API key, and
9
+ * delivers it back to the CLI via a cross-origin fetch to
10
+ * localhost:{port}/callback?token=...&state=...
11
+ * 4. CLI verifies the `state` matches, saves the key to ~/.subcon/config.json.
12
+ *
13
+ * Override SUBCONSCIOUS_URL env var for local development.
14
+ */
15
+
16
+ import http from 'node:http';
17
+ import crypto from 'node:crypto';
18
+ import { exec } from 'node:child_process';
19
+ import fs from 'node:fs/promises';
20
+ import os from 'node:os';
21
+ import path from 'node:path';
22
+ import { c } from './colors.js';
23
+
24
+ const CONFIG_DIR = path.join(os.homedir(), '.subcon');
25
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
26
+ // Defaults to production. Developers set SUBCONSCIOUS_URL=http://localhost:3000 for local dev.
27
+ const PLATFORM_URL = process.env.SUBCONSCIOUS_URL || 'https://www.subconscious.dev';
28
+
29
+ // ── Config helpers ──────────────────────────────────────────────────────
30
+
31
+ async function loadConfig() {
32
+ try {
33
+ const content = await fs.readFile(CONFIG_FILE, 'utf-8');
34
+ return JSON.parse(content);
35
+ } catch {
36
+ return {};
37
+ }
38
+ }
39
+
40
+ async function saveConfig(config) {
41
+ await fs.mkdir(CONFIG_DIR, { recursive: true });
42
+ await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');
43
+ // 0o600 = owner read/write only — the file contains an API key
44
+ await fs.chmod(CONFIG_FILE, 0o600);
45
+ }
46
+
47
+ /**
48
+ * Resolve the active API key. The env var takes precedence over the saved
49
+ * config so CI and per-shell overrides win. Returns null when unauthenticated.
50
+ */
51
+ export async function getApiKey() {
52
+ const envKey = process.env.SUBCONSCIOUS_API_KEY?.trim();
53
+ if (envKey) return { key: envKey, source: 'SUBCONSCIOUS_API_KEY env var' };
54
+
55
+ const config = await loadConfig();
56
+ if (config.subconscious_api_key) {
57
+ return { key: config.subconscious_api_key, source: '~/.subcon/config.json' };
58
+ }
59
+ return null;
60
+ }
61
+
62
+ // ── Browser opener ──────────────────────────────────────────────────────
63
+
64
+ function openBrowser(url) {
65
+ const cmd =
66
+ process.platform === 'darwin'
67
+ ? `open "${url}"`
68
+ : process.platform === 'win32'
69
+ ? `start "" "${url}"`
70
+ : `xdg-open "${url}"`;
71
+ exec(cmd, (err) => {
72
+ if (err) {
73
+ console.log(
74
+ `\n${c.yellow}Could not open browser automatically.${c.reset}`,
75
+ );
76
+ console.log(`Please open this URL manually:\n`);
77
+ console.log(` ${c.underline}${c.cyan}${url}${c.reset}\n`);
78
+ }
79
+ });
80
+ }
81
+
82
+ // ── Localhost callback server ───────────────────────────────────────────
83
+
84
+ function startCallbackServer(expectedState) {
85
+ return new Promise((resolveSetup) => {
86
+ let resolveToken, rejectToken;
87
+ const tokenPromise = new Promise((resolve, reject) => {
88
+ resolveToken = resolve;
89
+ rejectToken = reject;
90
+ });
91
+
92
+ const server = http.createServer((req, res) => {
93
+ // CORS: only allow the web app's origin (production or localhost dev).
94
+ // This prevents arbitrary websites from hitting this callback.
95
+ const origin = req.headers.origin || '';
96
+ const allowed =
97
+ origin === PLATFORM_URL ||
98
+ origin.startsWith('http://localhost:');
99
+ res.setHeader(
100
+ 'Access-Control-Allow-Origin',
101
+ allowed ? origin : PLATFORM_URL,
102
+ );
103
+ res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
104
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
105
+ res.setHeader('Connection', 'close');
106
+
107
+ if (req.method === 'OPTIONS') {
108
+ res.writeHead(204);
109
+ res.end();
110
+ return;
111
+ }
112
+
113
+ const url = new URL(req.url, 'http://localhost');
114
+
115
+ if (url.pathname !== '/callback') {
116
+ res.writeHead(404);
117
+ res.end();
118
+ return;
119
+ }
120
+
121
+ const token = url.searchParams.get('token');
122
+ const state = url.searchParams.get('state');
123
+ const error = url.searchParams.get('error');
124
+
125
+ // The web app sends `Accept: application/json` via fetch(); direct
126
+ // browser visits get the HTML fallback page.
127
+ const wantsJson = (req.headers.accept || '').includes('application/json');
128
+ const respond = (ok, msg) => {
129
+ if (wantsJson) {
130
+ res.writeHead(ok ? 200 : 400, { 'Content-Type': 'application/json' });
131
+ res.end(JSON.stringify({ ok, error: msg || undefined }));
132
+ } else {
133
+ res.writeHead(200, { 'Content-Type': 'text/html' });
134
+ res.end(resultPage(ok, msg));
135
+ }
136
+ };
137
+
138
+ if (error) {
139
+ respond(false, error);
140
+ server.close();
141
+ rejectToken(new Error(error));
142
+ return;
143
+ }
144
+
145
+ // CSRF check: state token must match what the CLI generated
146
+ if (state !== expectedState) {
147
+ respond(false, 'State mismatch — possible CSRF attack. Please try again.');
148
+ server.close();
149
+ rejectToken(new Error('State mismatch'));
150
+ return;
151
+ }
152
+
153
+ if (!token) {
154
+ respond(false, 'No API key received.');
155
+ server.close();
156
+ rejectToken(new Error('No API key received'));
157
+ return;
158
+ }
159
+
160
+ respond(true);
161
+ server.close();
162
+ resolveToken({ token });
163
+ });
164
+
165
+ // Port 0 = OS assigns a random available port. Bound to 127.0.0.1 only.
166
+ server.listen(0, '127.0.0.1', () => {
167
+ const port = server.address().port;
168
+
169
+ const timeout = setTimeout(() => {
170
+ server.close();
171
+ rejectToken(new Error('Authentication timed out (5 min). Please try again.'));
172
+ }, 5 * 60 * 1000);
173
+
174
+ tokenPromise.finally(() => clearTimeout(timeout));
175
+
176
+ resolveSetup({ port, promise: tokenPromise });
177
+ });
178
+ });
179
+ }
180
+
181
+ function resultPage(success, message) {
182
+ const title = success ? 'Authenticated' : 'Authentication failed';
183
+ const subtitle = success
184
+ ? 'You can close this tab and return to your terminal.'
185
+ : message || 'Something went wrong.';
186
+
187
+ const logoSvg = `<svg viewBox="0 0 205 199" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M-4.33e-06 99.93C-4.96e-06 85.57 11.64 73.93 26 73.93c7.88 0 14.94 3.51 19.71 9.04 5.25 6.09 11.36 12.6 19.37 13.33l3.92.36v-.01c.03.01.06.01.09.01L72 96.93c12.69 0 23.98-10.28 24-22.96-.01-7.36-3.48-13.91-8.87-18.11l-1.08-.76c-6.52-4.6-15.3-3.65-23.19-2.46-7.28 1.1-14.97-.88-20.96-6.08C31.06 37.13 29.91 20.71 39.33 9.87 48.75-.96 65.18-2.11 76.01 7.31c5.99 5.21 9.02 12.55 8.94 19.91-.09 7.97.2 16.8 5.66 22.62l.94 1 .11.1.14.12c.22.19.45.37.68.55l.17.13c.25.18.5.36.75.53.64.42 1.31.8 2.01 1.14.48.23.98.44 1.49.62.21.07.42.14.63.21.32.1.64.19.97.27.4.1.8.18 1.2.25.34.06.69.11 1.03.14.58.06 1.17.09 1.77.09 4.2 0 8.03-1.57 10.95-4.16l.94-1c5.46-5.81 5.75-14.65 5.66-22.62-.08-7.36 2.95-14.71 8.94-19.91C139.82-2.11 156.25-.96 165.67 9.87c9.42 10.84 8.27 27.26-2.56 36.68-5.99 5.21-13.69 7.18-20.96 6.08-7.88-1.19-16.67-2.14-23.19 2.46l-1.08.76c-5.39 4.2-8.86 10.75-8.87 18.11.02 12.69 11.31 22.96 24 22.96l2.91-.26.09-.02v.01l3.93-.36c8.01-.73 14.12-7.23 19.37-13.33 4.77-5.54 11.83-9.04 19.71-9.04C193.36 73.93 205 85.57 205 99.93v.07c0 .01 0 .02 0 .03 0 14.36-11.64 26-26 26-7.88 0-14.94-3.51-19.71-9.04-5.25-6.09-11.36-12.6-19.37-13.33l-3.93-.36v.01c-.03-.01-.06-.01-.09-.01L133 103c-12.69 0-23.98 10.28-24 22.97.01 7.36 3.48 13.91 8.87 18.11l1.08.76c6.52 4.6 15.3 3.65 23.19 2.46 7.28-1.1 14.97.88 20.96 6.08 10.84 9.42 11.98 25.84 2.56 36.68-9.42 10.84-25.84 11.98-36.68 2.56-5.99-5.21-9.02-12.55-8.94-19.91.09-7.97-.2-16.8-5.66-22.62l-.94-1c-2.91-2.59-6.75-4.16-10.95-4.16-.6 0-1.19.03-1.77.09-.35.04-.69.09-1.03.14-.34.07-.69.15-1.03.25-.33.08-.65.17-.97.28-.21.07-.42.14-.62.21-.51.18-1.01.39-1.49.62-.7.33-1.37.71-2.01 1.14-.26.17-.5.35-.75.53l-.17.13a11 11 0 0 0-.68.55l-.14.12-.11.1-.94 1.01c-5.46 5.81-5.75 14.65-5.66 22.62.08 7.36-2.95 14.71-8.94 19.91-10.84 9.42-27.26 8.27-36.68-2.56-9.42-10.84-8.27-27.26 2.56-36.68 5.99-5.21 13.69-7.18 20.96-6.08 7.88 1.19 16.67 2.14 23.19-2.46l1.08-.76c5.39-4.2 8.86-10.75 8.87-18.11-.02-12.69-11.31-22.97-24-22.97l-2.91.27c-.03 0-.06.01-.09.01v-.01l-3.93.36c-8.01.73-14.12 7.23-19.37 13.33C40.94 122.49 33.88 126 26 126 11.64 126 0 114.36 0 100l-4.33e-06-.07Z" fill="#FF5C28"/></svg>`;
188
+
189
+ const statusIcon = success
190
+ ? `<div class="icon success"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#16a34a" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></div>`
191
+ : `<div class="icon error"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg></div>`;
192
+
193
+ return `<!DOCTYPE html><html lang="en"><head>
194
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
195
+ <title>Subconscious CLI</title>
196
+ <link rel="preconnect" href="https://fonts.googleapis.com">
197
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
198
+ <link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600&display=swap" rel="stylesheet">
199
+ <style>
200
+ *{margin:0;padding:0;box-sizing:border-box}
201
+ body{font-family:'Manrope',system-ui,sans-serif;min-height:100vh;background:#F6F3EF;color:#111}
202
+ header{display:flex;align-items:center;gap:10px;padding:20px 24px}
203
+ header svg{width:24px;height:24px}
204
+ header span{font-size:15px;font-weight:600;letter-spacing:-.01em}
205
+ main{display:flex;align-items:center;justify-content:center;min-height:calc(100vh - 160px)}
206
+ .wrap{width:100%;max-width:400px;padding:0 24px}
207
+ .label{text-align:center;font-size:11px;font-weight:500;text-transform:uppercase;
208
+ letter-spacing:.1em;color:#9ca3af;margin-bottom:16px}
209
+ .card{background:#fff;border:1px solid rgba(0,0,0,.08);border-radius:12px;
210
+ padding:32px;text-align:center}
211
+ .icon{width:40px;height:40px;border-radius:50%;display:flex;align-items:center;
212
+ justify-content:center;margin:0 auto 16px}
213
+ .icon.success{background:#f0fdf4}
214
+ .icon.error{background:#fef2f2}
215
+ h1{font-size:15px;font-weight:600;margin-bottom:4px;letter-spacing:-.01em}
216
+ .sub{color:#6b7280;font-size:13px;line-height:1.6;max-width:280px;margin:0 auto}
217
+ .footer{text-align:center;margin-top:16px;font-size:11px;color:#9ca3af}
218
+ </style></head><body>
219
+ <header>${logoSvg}<span>Subconscious</span></header>
220
+ <main><div class="wrap">
221
+ <div class="label">CLI Authentication</div>
222
+ <div class="card">
223
+ ${statusIcon}
224
+ <h1>${title}</h1>
225
+ <p class="sub">${subtitle}</p>
226
+ </div>
227
+ <div class="footer">subconscious.dev</div>
228
+ </div></main>
229
+ </body></html>`;
230
+ }
231
+
232
+ // ── Commands ────────────────────────────────────────────────────────────
233
+
234
+ export async function loginCommand() {
235
+ const existing = await getApiKey();
236
+
237
+ if (existing) {
238
+ const masked = existing.key.slice(0, 8) + '...' + existing.key.slice(-4);
239
+ console.log(`\n${c.yellow}Already logged in.${c.reset}`);
240
+ console.log(` Key: ${c.dim}${masked}${c.reset}`);
241
+ console.log(
242
+ `\n Run ${c.cyan}subconscious logout${c.reset} first to switch accounts.\n`,
243
+ );
244
+ return;
245
+ }
246
+
247
+ console.log();
248
+ console.log(
249
+ ` ${c.magenta}${c.bold}Subconscious${c.reset} ${c.dim}— CLI Login${c.reset}`,
250
+ );
251
+ console.log();
252
+
253
+ const state = crypto.randomBytes(16).toString('hex');
254
+ const { port, promise } = await startCallbackServer(state);
255
+
256
+ const authUrl = `${PLATFORM_URL}/cli/auth?port=${port}&state=${state}`;
257
+
258
+ console.log(` ${c.dim}Opening browser to sign in...${c.reset}`);
259
+ console.log();
260
+ console.log(` ${c.dim}If it doesn't open, visit:${c.reset}`);
261
+ console.log(` ${c.underline}${c.cyan}${authUrl}${c.reset}`);
262
+ console.log();
263
+
264
+ openBrowser(authUrl);
265
+
266
+ // Spinner while waiting
267
+ const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
268
+ let i = 0;
269
+ const spinner = setInterval(() => {
270
+ process.stdout.write(
271
+ `\r ${c.cyan}${frames[i++ % frames.length]}${c.reset} Waiting for authentication...`,
272
+ );
273
+ }, 80);
274
+
275
+ process.on('SIGINT', () => {
276
+ clearInterval(spinner);
277
+ process.stdout.write('\r' + ' '.repeat(50) + '\r');
278
+ console.log(`\n ${c.dim}Login cancelled.${c.reset}\n`);
279
+ process.exit(0);
280
+ });
281
+ try {
282
+ const result = await promise;
283
+ clearInterval(spinner);
284
+ process.stdout.write('\r' + ' '.repeat(50) + '\r');
285
+
286
+ const config = await loadConfig();
287
+ config.subconscious_api_key = result.token;
288
+ await saveConfig(config);
289
+
290
+ const masked = result.token.slice(0, 8) + '...' + result.token.slice(-4);
291
+ console.log(` ${c.green}${c.bold}✓ Logged in successfully!${c.reset}`);
292
+ console.log(` ${c.dim}Key: ${masked}${c.reset}`);
293
+ console.log(` ${c.dim}Saved to ~/.subcon/config.json${c.reset}`);
294
+ console.log();
295
+ } catch (error) {
296
+ clearInterval(spinner);
297
+ process.stdout.write('\r' + ' '.repeat(50) + '\r');
298
+ console.error(` ${c.red}✗ ${error.message}${c.reset}\n`);
299
+ process.exit(1);
300
+ }
301
+ }
302
+
303
+ export async function logoutCommand() {
304
+ const config = await loadConfig();
305
+
306
+ if (!config.subconscious_api_key) {
307
+ console.log(`\n ${c.dim}Not logged in.${c.reset}\n`);
308
+ return;
309
+ }
310
+
311
+ delete config.subconscious_api_key;
312
+ await saveConfig(config);
313
+
314
+ console.log(
315
+ `\n ${c.green}✓${c.reset} Logged out. API key removed from ${c.dim}~/.subcon/config.json${c.reset}\n`,
316
+ );
317
+ }
318
+
319
+ export async function whoamiCommand() {
320
+ const auth = await getApiKey();
321
+
322
+ if (!auth) {
323
+ console.log(`\n ${c.dim}Not logged in.${c.reset}`);
324
+ console.log(
325
+ ` Run ${c.cyan}subconscious login${c.reset} to get started.\n`,
326
+ );
327
+ return;
328
+ }
329
+
330
+ const { key, source } = auth;
331
+ const masked = key.slice(0, 8) + '...' + key.slice(-4);
332
+
333
+ console.log();
334
+
335
+ // Validate the key against the server; falls back to offline display if unreachable
336
+ try {
337
+ const res = await fetch(`${PLATFORM_URL}/api/cli/whoami`, {
338
+ headers: { Authorization: `Bearer ${key}` },
339
+ signal: AbortSignal.timeout(5000),
340
+ });
341
+
342
+ if (res.ok) {
343
+ const data = await res.json();
344
+ console.log(` ${c.green}✓ Authenticated${c.reset}`);
345
+ if (data.organization) {
346
+ console.log(` ${c.dim}Org: ${c.reset}${data.organization}`);
347
+ }
348
+ console.log(` ${c.dim}Key: ${masked}${c.reset}`);
349
+ console.log(` ${c.dim}Source: ${source}${c.reset}`);
350
+ } else {
351
+ console.log(` ${c.red}✗ Key is invalid or revoked${c.reset}`);
352
+ console.log(` ${c.dim}Key: ${masked}${c.reset}`);
353
+ console.log(` ${c.dim}Source: ${source}${c.reset}`);
354
+ console.log();
355
+ console.log(
356
+ ` Run ${c.cyan}subconscious logout${c.reset} then ${c.cyan}subconscious login${c.reset} to re-authenticate.`,
357
+ );
358
+ }
359
+ } catch {
360
+ console.log(` ${c.green}✓ Authenticated${c.reset} ${c.dim}(offline — key not verified)${c.reset}`);
361
+ console.log(` ${c.dim}Key: ${masked}${c.reset}`);
362
+ console.log(` ${c.dim}Source: ${source}${c.reset}`);
363
+ }
364
+
365
+ console.log();
366
+ }