@abstractframework/code 0.3.7 → 0.3.8

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/README.md CHANGED
@@ -23,4 +23,14 @@ npm run dev
23
23
 
24
24
  In the UI:
25
25
  - set `Gateway URL` (blank = same origin / dev proxy; e.g. `http://127.0.0.1:8081`)
26
- - set `Auth token` if your gateway requires it
26
+ - in hosted user-auth mode, set `Gateway user` and that user's `Gateway token`
27
+
28
+ When a Gateway user is provided, the web server exchanges the token for a
29
+ Gateway browser session and stores only app-scoped session cookies. The raw
30
+ token is not persisted in browser settings. Direct bearer-token mode is kept for
31
+ local development only. When the web UI is served from a non-local hostname,
32
+ the server-configured Gateway URL is authoritative; browser-supplied Gateway URL
33
+ changes are rejected unless `ABSTRACTCODE_ALLOW_REMOTE_BROWSER_GATEWAY_CONFIG=1`
34
+ is set behind your own access control. If a reverse proxy rewrites `Host`, set
35
+ `ABSTRACTCODE_TRUST_PROXY_HEADERS=1` only when the proxy strips client-supplied
36
+ forwarded headers.
package/bin/cli.js CHANGED
@@ -5,7 +5,8 @@
5
5
  * Serves the browser-based coding assistant on a configurable port
6
6
  */
7
7
 
8
- import { createServer } from 'http';
8
+ import * as http from 'http';
9
+ import * as https from 'https';
9
10
  import { readFileSync, existsSync, statSync } from 'fs';
10
11
  import { join, extname, dirname } from 'path';
11
12
  import { fileURLToPath } from 'url';
@@ -14,6 +15,11 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
14
15
  const DIST_DIR = join(__dirname, '..', 'dist');
15
16
  const PORT = process.env.PORT || 3002;
16
17
  const HOST = process.env.HOST || '0.0.0.0';
18
+ const DEFAULT_GATEWAY_URL = String(process.env.ABSTRACTCODE_GATEWAY_URL || process.env.ABSTRACTGATEWAY_URL || 'http://127.0.0.1:8080').trim().replace(/\/+$/, '') || 'http://127.0.0.1:8080';
19
+ const GATEWAY_SESSION_URL_COOKIE = 'abstractcode_gateway_url';
20
+ const GATEWAY_SESSION_ID_COOKIE = 'abstractcode_gateway_session';
21
+ const GATEWAY_SESSION_CSRF_COOKIE = 'abstractcode_gateway_csrf';
22
+ const TRUE_VALUES = new Set(['1', 'true', 'yes', 'y', 'on']);
17
23
 
18
24
  // MIME types for common file extensions
19
25
  const MIME_TYPES = {
@@ -53,10 +59,328 @@ function serveFile(res, filePath) {
53
59
  }
54
60
  }
55
61
 
56
- const server = createServer((req, res) => {
62
+ function sendJson(res, status, payload) {
63
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
64
+ res.end(JSON.stringify(payload));
65
+ }
66
+
67
+ function envBool(name) {
68
+ const raw = process.env[name];
69
+ if (typeof raw !== 'string' || !raw.trim()) return false;
70
+ return TRUE_VALUES.has(raw.trim().toLowerCase());
71
+ }
72
+
73
+ function requestHostname(req) {
74
+ const trustProxyHeaders = envBool('ABSTRACTCODE_TRUST_PROXY_HEADERS') || envBool('ABSTRACTGATEWAY_TRUST_PROXY_HEADERS');
75
+ const headerValue = trustProxyHeaders ? (req?.headers?.['x-forwarded-host'] || req?.headers?.host) : req?.headers?.host;
76
+ const raw = String(headerValue || '').split(',', 1)[0].trim();
77
+ if (!raw) return '';
78
+ if (raw.startsWith('[')) return raw.slice(1).split(']', 1)[0].trim().toLowerCase();
79
+ if ((raw.match(/:/g) || []).length === 1) return raw.split(':')[0].trim().toLowerCase();
80
+ return raw.toLowerCase();
81
+ }
82
+
83
+ function isLoopbackHostname(hostname) {
84
+ const h = String(hostname || '').trim().toLowerCase();
85
+ return h === 'localhost' || h === 'localhost.localdomain' || h === '::1' || h.startsWith('127.');
86
+ }
87
+
88
+ function browserGatewayConnectionConfigAllowed(req) {
89
+ if (envBool('ABSTRACTCODE_ALLOW_REMOTE_BROWSER_GATEWAY_CONFIG')) return true;
90
+ if (envBool('ABSTRACTGATEWAY_ALLOW_REMOTE_BROWSER_GATEWAY_CONFIG')) return true;
91
+ return isLoopbackHostname(requestHostname(req));
92
+ }
93
+
94
+ function browserGatewayConnectionConfigDenial(req) {
95
+ const host = requestHostname(req) || 'unknown host';
96
+ return (
97
+ `Browser-supplied Gateway URL changes are disabled for this non-local Code host (${host}). ` +
98
+ 'Use the server-configured Gateway URL, or set ABSTRACTCODE_ALLOW_REMOTE_BROWSER_GATEWAY_CONFIG=1 behind your own access control.'
99
+ );
100
+ }
101
+
102
+ function parseCookies(req) {
103
+ const out = {};
104
+ for (const part of String(req?.headers?.cookie || '').split(';')) {
105
+ const idx = part.indexOf('=');
106
+ if (idx < 0) continue;
107
+ const key = part.slice(0, idx).trim();
108
+ const value = part.slice(idx + 1).trim();
109
+ if (!key) continue;
110
+ try {
111
+ out[key] = decodeURIComponent(value);
112
+ } catch {
113
+ out[key] = value;
114
+ }
115
+ }
116
+ return out;
117
+ }
118
+
119
+ function cookieSecure(req) {
120
+ return String(req?.headers?.['x-forwarded-proto'] || '').trim().toLowerCase() === 'https' ? '; Secure' : '';
121
+ }
122
+
123
+ function setSessionCookies(res, req, gatewayUrl, sessionId, csrfToken, persist) {
124
+ const secure = cookieSecure(req);
125
+ const maxAge = persist ? '; Max-Age=2592000' : '';
126
+ const attrs = `; Path=/; HttpOnly; SameSite=Lax${secure}${maxAge}`;
127
+ const csrfAttrs = `; Path=/; SameSite=Lax${secure}${maxAge}`;
128
+ res.setHeader('Set-Cookie', [
129
+ `${GATEWAY_SESSION_URL_COOKIE}=${encodeURIComponent(gatewayUrl)}${attrs}`,
130
+ `${GATEWAY_SESSION_ID_COOKIE}=${encodeURIComponent(sessionId)}${attrs}`,
131
+ `${GATEWAY_SESSION_CSRF_COOKIE}=${encodeURIComponent(csrfToken)}${csrfAttrs}`,
132
+ ]);
133
+ }
134
+
135
+ function clearSessionCookies(res, req) {
136
+ const secure = cookieSecure(req);
137
+ res.setHeader('Set-Cookie', [
138
+ `${GATEWAY_SESSION_URL_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure}`,
139
+ `${GATEWAY_SESSION_ID_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure}`,
140
+ `${GATEWAY_SESSION_CSRF_COOKIE}=; Path=/; SameSite=Lax; Max-Age=0${secure}`,
141
+ ]);
142
+ }
143
+
144
+ function browserSession(req) {
145
+ const cookies = parseCookies(req);
146
+ const cookieUrl = String(cookies[GATEWAY_SESSION_URL_COOKIE] || '').trim().replace(/\/+$/, '');
147
+ const allowCookieUrl =
148
+ envBool('ABSTRACTCODE_ALLOW_BROWSER_GATEWAY_URL_COOKIE') ||
149
+ envBool('ABSTRACTCODE_ALLOW_REMOTE_BROWSER_GATEWAY_CONFIG') ||
150
+ envBool('ABSTRACTGATEWAY_ALLOW_REMOTE_BROWSER_GATEWAY_CONFIG') ||
151
+ browserGatewayConnectionConfigAllowed(req);
152
+ return {
153
+ gatewayUrl: cookieUrl && (allowCookieUrl || cookieUrl === DEFAULT_GATEWAY_URL) ? cookieUrl : DEFAULT_GATEWAY_URL,
154
+ sessionId: String(cookies[GATEWAY_SESSION_ID_COOKIE] || '').trim(),
155
+ csrfToken: String(cookies[GATEWAY_SESSION_CSRF_COOKIE] || '').trim(),
156
+ };
157
+ }
158
+
159
+ function resolveBackend(gatewayUrl) {
160
+ const backend = new URL(String(gatewayUrl || DEFAULT_GATEWAY_URL).trim());
161
+ if (!backend.port) backend.port = backend.protocol === 'https:' ? '443' : '80';
162
+ return {
163
+ url: backend,
164
+ origin: `${backend.protocol}//${backend.host}`,
165
+ client: backend.protocol === 'https:' ? https : http,
166
+ };
167
+ }
168
+
169
+ function mutatingMethod(method) {
170
+ return ['POST', 'PUT', 'PATCH', 'DELETE'].includes(String(method || 'GET').toUpperCase());
171
+ }
172
+
173
+ function readRequestJson(req) {
174
+ return new Promise((resolve) => {
175
+ const chunks = [];
176
+ req.on('data', (chunk) => chunks.push(chunk));
177
+ req.on('end', () => {
178
+ try {
179
+ const raw = Buffer.concat(chunks).toString('utf8');
180
+ resolve(raw ? JSON.parse(raw) : {});
181
+ } catch {
182
+ resolve({});
183
+ }
184
+ });
185
+ req.on('error', () => resolve({}));
186
+ });
187
+ }
188
+
189
+ function gatewayRequest(gatewayUrl, options, body) {
190
+ return new Promise((resolve) => {
191
+ let backend;
192
+ try {
193
+ backend = resolveBackend(gatewayUrl);
194
+ } catch (err) {
195
+ resolve({ ok: false, status: 0, payload: { detail: `Invalid gateway URL: ${String(err?.message || err)}` } });
196
+ return;
197
+ }
198
+ const req = backend.client.request(
199
+ {
200
+ protocol: backend.url.protocol,
201
+ hostname: backend.url.hostname,
202
+ port: backend.url.port,
203
+ timeout: options.timeout || 4000,
204
+ ...options,
205
+ },
206
+ (resp) => {
207
+ const chunks = [];
208
+ resp.on('data', (chunk) => chunks.push(chunk));
209
+ resp.on('end', () => {
210
+ const text = Buffer.concat(chunks).toString('utf8');
211
+ let payload = {};
212
+ try {
213
+ payload = text ? JSON.parse(text) : {};
214
+ } catch {
215
+ payload = { detail: text };
216
+ }
217
+ const status = resp.statusCode || 0;
218
+ resolve({ ok: status >= 200 && status < 300, status, payload, headers: resp.headers, origin: backend.origin });
219
+ });
220
+ }
221
+ );
222
+ req.on('timeout', () => {
223
+ req.destroy();
224
+ resolve({ ok: false, status: 0, payload: { detail: 'Gateway request timed out' }, origin: backend?.origin });
225
+ });
226
+ req.on('error', (err) => resolve({ ok: false, status: 0, payload: { detail: String(err?.message || err) }, origin: backend?.origin }));
227
+ if (body) req.write(body);
228
+ req.end();
229
+ });
230
+ }
231
+
232
+ function cookieValueFromSetCookie(rawHeaders, name) {
233
+ const headers = Array.isArray(rawHeaders) ? rawHeaders : rawHeaders ? [rawHeaders] : [];
234
+ for (const header of headers) {
235
+ for (const candidate of String(header || '').split(/,(?=\s*[^;,=]+=)/)) {
236
+ const first = candidate.split(';', 1)[0];
237
+ const idx = first.indexOf('=');
238
+ if (idx < 0) continue;
239
+ if (first.slice(0, idx).trim() !== name) continue;
240
+ const raw = first.slice(idx + 1).trim();
241
+ try {
242
+ return decodeURIComponent(raw);
243
+ } catch {
244
+ return raw;
245
+ }
246
+ }
247
+ }
248
+ return '';
249
+ }
250
+
251
+ async function handleConnectionApi(req, res) {
252
+ if (req.method === 'GET') {
253
+ const session = browserSession(req);
254
+ if (!session.sessionId) {
255
+ sendJson(res, 200, { ok: false, gateway_url: session.gatewayUrl, has_session: false, gateway: { ok: false, error: 'Gateway sign-in required' } });
256
+ return;
257
+ }
258
+ const checked = await gatewayRequest(session.gatewayUrl, {
259
+ method: 'GET',
260
+ path: '/api/gateway/me',
261
+ headers: { Accept: 'application/json', 'X-AbstractGateway-Session': session.sessionId },
262
+ });
263
+ sendJson(res, 200, { ok: checked.ok, gateway_url: session.gatewayUrl, has_session: Boolean(session.sessionId), gateway: checked.payload });
264
+ return;
265
+ }
266
+ if (req.method === 'POST') {
267
+ const payload = await readRequestJson(req);
268
+ const gatewayUrl = String(payload.gateway_url || DEFAULT_GATEWAY_URL).trim().replace(/\/+$/, '') || DEFAULT_GATEWAY_URL;
269
+ if (!browserGatewayConnectionConfigAllowed(req) && gatewayUrl !== DEFAULT_GATEWAY_URL) {
270
+ sendJson(res, 403, { detail: browserGatewayConnectionConfigDenial(req) });
271
+ return;
272
+ }
273
+ const body = Buffer.from(JSON.stringify({
274
+ user_id: String(payload.gateway_user_id || '').trim(),
275
+ token: String(payload.gateway_token || '').trim(),
276
+ remember: payload.persist === true,
277
+ }));
278
+ const login = await gatewayRequest(gatewayUrl, {
279
+ method: 'POST',
280
+ path: '/api/gateway/session/login',
281
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Content-Length': String(body.length) },
282
+ }, body);
283
+ const session = login.payload && typeof login.payload.session === 'object' ? login.payload.session : {};
284
+ const setCookie = login.headers?.['set-cookie'];
285
+ const sessionId = cookieValueFromSetCookie(setCookie, 'abstractgateway_session') || String(session.session_id || '').trim();
286
+ const csrfToken = cookieValueFromSetCookie(setCookie, 'abstractgateway_csrf') || String(session.csrf_token || '').trim();
287
+ if (!login.ok || !sessionId || !csrfToken) {
288
+ sendJson(res, login.status || 401, { ok: false, detail: login.payload?.detail || 'Gateway browser session failed', gateway: login.payload });
289
+ return;
290
+ }
291
+ setSessionCookies(res, req, gatewayUrl, sessionId, csrfToken, payload.persist === true);
292
+ sendJson(res, 200, { ok: true, gateway_url: gatewayUrl, has_session: true, gateway: login.payload });
293
+ return;
294
+ }
295
+ if (req.method === 'DELETE') {
296
+ const session = browserSession(req);
297
+ if (session.sessionId) {
298
+ const body = Buffer.from('{}');
299
+ await gatewayRequest(session.gatewayUrl, {
300
+ method: 'POST',
301
+ path: '/api/gateway/session/logout',
302
+ headers: {
303
+ Accept: 'application/json',
304
+ 'Content-Type': 'application/json',
305
+ 'Content-Length': String(body.length),
306
+ 'X-AbstractGateway-Session': session.sessionId,
307
+ 'X-AbstractGateway-CSRF': session.csrfToken,
308
+ },
309
+ timeout: 2000,
310
+ }, body);
311
+ }
312
+ clearSessionCookies(res, req);
313
+ sendJson(res, 200, { ok: true });
314
+ return;
315
+ }
316
+ sendJson(res, 405, { detail: 'Method not allowed' });
317
+ }
318
+
319
+ const HOP_BY_HOP_HEADERS = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'trailers', 'transfer-encoding', 'upgrade']);
320
+
321
+ function proxyHeaders(headers) {
322
+ const out = {};
323
+ for (const [key, value] of Object.entries(headers || {})) {
324
+ const k = String(key).toLowerCase();
325
+ if (HOP_BY_HOP_HEADERS.has(k) || k === 'content-length') continue;
326
+ out[key] = value;
327
+ }
328
+ return out;
329
+ }
330
+
331
+ function proxyApiRequest(req, res) {
332
+ const session = browserSession(req);
333
+ if (!session.sessionId) {
334
+ sendJson(res, 401, { detail: 'Gateway sign-in required' });
335
+ return;
336
+ }
337
+ if (mutatingMethod(req.method)) {
338
+ const presented = String(req.headers['x-abstractcode-csrf'] || '').trim();
339
+ if (!session.csrfToken || presented !== session.csrfToken) {
340
+ sendJson(res, 403, { detail: 'Gateway browser session CSRF token missing or invalid', reason_code: 'csrf_required' });
341
+ return;
342
+ }
343
+ }
344
+ let backend;
345
+ try {
346
+ backend = resolveBackend(session.gatewayUrl);
347
+ } catch (err) {
348
+ sendJson(res, 500, { detail: `Invalid gateway URL: ${String(err?.message || err)}` });
349
+ return;
350
+ }
351
+ const headers = { ...req.headers, host: backend.url.host };
352
+ delete headers.cookie;
353
+ delete headers.authorization;
354
+ delete headers['x-forwarded-for'];
355
+ delete headers['x-forwarded-host'];
356
+ delete headers['x-forwarded-proto'];
357
+ headers['x-abstractgateway-session'] = session.sessionId;
358
+ if (mutatingMethod(req.method)) headers['x-abstractgateway-csrf'] = session.csrfToken;
359
+ const proxyReq = backend.client.request(
360
+ { protocol: backend.url.protocol, hostname: backend.url.hostname, port: backend.url.port, method: req.method, path: req.url, headers },
361
+ (proxyRes) => {
362
+ res.writeHead(proxyRes.statusCode || 502, proxyHeaders(proxyRes.headers));
363
+ proxyRes.pipe(res);
364
+ }
365
+ );
366
+ proxyReq.on('error', (err) => sendJson(res, 502, { detail: `Backend not reachable at ${backend.origin} (${String(err?.message || err)})` }));
367
+ req.pipe(proxyReq);
368
+ }
369
+
370
+ const server = http.createServer((req, res) => {
57
371
  // Remove query strings and normalize path
58
372
  const url = new URL(req.url, `http://${req.headers.host}`);
59
373
  let pathname = url.pathname;
374
+
375
+ if (pathname === '/api/connection/gateway') {
376
+ void handleConnectionApi(req, res);
377
+ return;
378
+ }
379
+
380
+ if (pathname.startsWith('/api/')) {
381
+ proxyApiRequest(req, res);
382
+ return;
383
+ }
60
384
 
61
385
  // Security: prevent directory traversal
62
386
  if (pathname.includes('..')) {