-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
807 lines (686 loc) · 28.8 KB
/
Copy pathmain.ts
File metadata and controls
807 lines (686 loc) · 28.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
import { Hono } from "@hono/hono";
import { streamSSE } from "@hono/hono/streaming";
import Anthropic from "@anthropic-ai/sdk";
import OpenAI from "openai";
import { load } from "@std/dotenv";
import { verify } from "@hono/hono/jwt";
import { getCookie } from "@hono/hono/cookie";
import { loginHandler, logoutHandler, authMiddleware, requireRoot, requireAppAccess, generateMagicLinkToken, magicLinkHandler } from "./auth.ts";
import { listAppsWithCredentials, getApp, deleteApp, updateAppCredentials, deleteAppCredentials, getAppCredentials, updateAppTitle, updateAppPrd, updateAppErd, updateAppPocPlan, saveEditRequest, listEditRequests, listAllEditRequests, deleteEditRequest, saveUxLesson, listUxLessons, listUxLessonsForApp, deleteUxLesson, logUsage, getAllAppSpends, disableApp, enableApp, isAppDisabled, createAppPlaceholder, getAppBuildStatus, updateAppBuildStatus, getAppConnection, updateAppConnectionOAuthTokens } from "./db.ts";
import { generateApp, editApp, extractUxLesson, generatePrd, generateErd, regenerateApp, generatePocPlan, backgroundGenerate, type EditProgressEvent } from "./generate.ts";
import { runWidgetAgent, type WidgetSSEEvent } from "./widget-agent.ts";
import { crud } from "./crud.ts";
import { createChatRoutes } from "./chat.ts";
import { createAgentRoutes } from "./agents.ts";
import { createExternalApiRoutes } from "./external-api.ts";
import { createConnectionRoutes } from "./connections-api.ts";
import { createMcpHandler } from "./mcp-server.ts";
// Load environment variables from .env file (local dev only)
try {
const env = await load();
for (const [k, v] of Object.entries(env)) {
Deno.env.set(k, v);
}
console.log(`[startup] Loaded ${Object.keys(env).length} vars from .env`);
} catch {
console.log("[startup] No .env file found, using system environment");
}
const anthropicKey = Deno.env.get("ANTHROPIC_API_KEY");
const openaiKey = Deno.env.get("OPENAI_API_KEY");
console.log(`[startup] ANTHROPIC_API_KEY: ${anthropicKey ? "set (" + anthropicKey.slice(0, 10) + "...)" : "MISSING"}`);
console.log(`[startup] OPENAI_API_KEY: ${openaiKey ? "set (" + openaiKey.slice(0, 10) + "...)" : "MISSING"}`);
if (!anthropicKey) throw new Error("ANTHROPIC_API_KEY is not set");
if (!openaiKey) throw new Error("OPENAI_API_KEY is not set");
const client = new Anthropic({ apiKey: anthropicKey });
const openaiClient = new OpenAI({ apiKey: openaiKey });
type AppEnv = {
Variables: {
user: string;
role: string;
appId: string;
};
};
const app = new Hono<AppEnv>();
// Global error handler — always return JSON for API routes
app.onError((err, c) => {
console.error(`[server] Unhandled error:`, err);
const msg = err instanceof Error ? err.message : "Internal Server Error";
return c.json({ error: msg }, 500);
});
// 404 handler — return JSON for API routes
app.notFound((c) => {
if (c.req.path.startsWith("/api/")) {
return c.json({ error: "Not found" }, 404);
}
return c.text("Not Found", 404);
});
// --- Public routes ---
app.get("/login", async (c) => {
const html = await Deno.readTextFile("static/login.html");
return c.html(html);
});
app.post("/auth/login", loginHandler);
app.get("/auth/logout", logoutHandler);
// --- Public per-app routes (no auth) ---
app.get("/apps/:appId/magic", magicLinkHandler);
app.get("/apps/:appId/login", async (c) => {
const appId = c.req.param("appId");
const creds = getAppCredentials(appId);
if (!creds) return c.redirect(`/apps/${appId}`);
const record = getApp(appId);
const title = record?.title ?? "App";
let html = await Deno.readTextFile("static/app-login.html");
html = html.replace(/\{\{APP_ID\}\}/g, appId);
html = html.replace(/\{\{APP_TITLE\}\}/g, title);
return c.html(html);
});
// --- Dashboard: root only ---
app.use("/dashboard", authMiddleware, requireRoot);
app.get("/", (c) => c.redirect("/dashboard"));
app.get("/dashboard", async (c) => {
const html = await Deno.readTextFile("static/dashboard.html");
return c.html(html);
});
// --- Dashboard app detail page: root only ---
app.use("/dashboard/apps/*", authMiddleware, requireRoot);
app.get("/dashboard/apps/:appId", async (c) => {
const html = await Deno.readTextFile("static/app-detail.html");
return c.html(html);
});
app.get("/dashboard/apps/:appId/prd", async (c) => {
const html = await Deno.readTextFile("static/app-prd.html");
return c.html(html);
});
app.get("/dashboard/apps/:appId/erd", async (c) => {
const html = await Deno.readTextFile("static/app-erd.html");
return c.html(html);
});
app.get("/dashboard/apps/:appId/poc-plan", async (c) => {
const html = await Deno.readTextFile("static/app-poc-plan.html");
return c.html(html);
});
// --- API routes: root only ---
app.get("/api/apps", authMiddleware, requireRoot, (c) => {
const spends = getAllAppSpends();
const apps = listAppsWithCredentials().map(a => ({ ...a, spend: spends[a.id] || 0 }));
return c.json(apps);
});
app.post("/api/apps", authMiddleware, requireRoot, async (c) => {
let body: { title?: string; body?: string; context?: string };
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
if (!body.body) {
return c.json({ error: "body (app description) is required" }, 400);
}
const title = body.title || body.body.split("\n")[0].replace(/^#+\s*/, "").slice(0, 100) || "Untitled App";
const description = body.body;
const context = body.context;
const appId = crypto.randomUUID();
createAppPlaceholder(appId, title, description);
backgroundGenerate(appId, title, description, client, context);
return c.json({ appId });
});
// Build status polling endpoint
app.get("/api/apps/:appId/build-status", authMiddleware, requireRoot, (c) => {
const appId = c.req.param("appId");
const status = getAppBuildStatus(appId);
if (!status) return c.json({ error: "App not found" }, 404);
return c.json({
build_status: status.build_status || "ready",
failure_reason: status.failure_reason || "",
has_prd: status.has_prd,
has_erd: status.has_erd,
});
});
// Retry build endpoint
app.post("/api/apps/:appId/retry", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const app_record = getApp(appId);
if (!app_record) return c.json({ error: "App not found" }, 404);
updateAppBuildStatus(appId, "building_prd");
backgroundGenerate(appId, app_record.title, app_record.description, client);
return c.json({ ok: true });
});
app.post("/api/apps/:appId/edit", authMiddleware, requireAppAccess, async (c) => {
const appId = c.req.param("appId");
const role = c.get("role");
if (role !== "root") {
const disabledStatus = isAppDisabled(appId);
if (disabledStatus.disabled) return c.json({ error: "App is disabled: " + disabledStatus.reason }, 403);
}
let body: { description?: string };
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
if (!body.description) {
return c.json({ error: "description is required" }, 400);
}
// Non-root users: save the request for tracking, then execute the edit
if (role !== "root") {
const username = c.get("user") || "unknown";
saveEditRequest(appId, username, body.description);
}
const description = body.description;
return streamSSE(c, async (stream) => {
try {
await editApp(appId, description, client, async (event: EditProgressEvent) => {
await stream.writeSSE({ event: event.step, data: JSON.stringify(event) });
});
// Fire-and-forget: extract UX lesson from this edit
extractUxLesson(description, client, appId).then((lesson) => {
if (lesson) {
saveUxLesson(lesson, appId, description);
console.log(`[ux-lessons] Learned: "${lesson}"`);
}
}).catch(() => {});
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "Edit failed";
await stream.writeSSE({ event: "error", data: JSON.stringify({ step: "error", message: msg }) });
}
});
});
// --- Root-only: view edit requests ---
app.get("/api/apps/:appId/edit-requests", authMiddleware, requireRoot, (c) => {
const appId = c.req.param("appId");
return c.json(listEditRequests(appId));
});
app.get("/api/edit-requests", authMiddleware, requireRoot, (c) => {
return c.json(listAllEditRequests());
});
app.post("/api/apps/:appId/edit-requests/:requestId/delete", authMiddleware, requireRoot, (c) => {
const requestId = parseInt(c.req.param("requestId"), 10);
if (isNaN(requestId)) return c.json({ error: "Invalid request ID" }, 400);
deleteEditRequest(requestId);
return c.json({ ok: true });
});
// --- Root-only: AI summary of edit requests ---
app.post("/api/apps/:appId/edit-requests/summary", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
const requests = listEditRequests(appId);
if (requests.length === 0) {
return c.json({ summary: "No edit requests to analyze." });
}
const requestList = requests.map((r, i) =>
`${i + 1}. [${r.username}, ${r.created_at}] ${r.description}`
).join("\n");
const message = await client.messages.create({
model: "claude-opus-4-6",
max_tokens: 1024,
messages: [{
role: "user",
content: `You are analyzing edit requests from users of a demo app called "${record.title}". These users are prospects evaluating our platform.
Here are all the edit requests:
${requestList}
Analyze these requests to help us understand this prospect:
1. **Features & Capabilities** — What features/capabilities is this prospect looking for? What do they need the app to do?
2. **UX Friction** — What UX patterns are causing friction? What expectations aren't being met?
3. **Prospect Needs** — What does this tell us about the prospect's business needs and whether they'd convert to a paying customer?
4. **Actionable Recommendations** — What should our product team prioritize based on this feedback?
Be concise and actionable. Use bullet points and markdown formatting.`,
}],
});
logUsage(appId, "edit-summary", "claude-opus-4-6", message.usage.input_tokens, message.usage.output_tokens);
const summary = message.content[0].type === "text" ? message.content[0].text : "Unable to generate summary.";
return c.json({ summary });
});
// --- Root-only: UX lessons management ---
app.get("/api/ux-lessons", authMiddleware, requireRoot, (c) => {
return c.json(listUxLessons());
});
app.get("/api/apps/:appId/ux-lessons", authMiddleware, requireRoot, (c) => {
const appId = c.req.param("appId");
return c.json(listUxLessonsForApp(appId));
});
app.post("/api/ux-lessons/:id/delete", authMiddleware, requireRoot, (c) => {
const id = parseInt(c.req.param("id"), 10);
if (isNaN(id)) return c.json({ error: "Invalid lesson ID" }, 400);
deleteUxLesson(id);
return c.json({ ok: true });
});
// --- Root-only: delete app ---
app.post("/api/apps/:appId/delete", authMiddleware, requireRoot, (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
try {
deleteApp(appId);
return c.json({ ok: true });
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "Delete failed";
return c.json({ error: msg }, 500);
}
});
// --- Root-only: update app metadata (title) ---
app.post("/api/apps/:appId/title", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
let body: { title?: string };
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
if (!body.title || !body.title.trim()) {
return c.json({ error: "title is required" }, 400);
}
try {
updateAppTitle(appId, body.title.trim());
return c.json({ ok: true, title: body.title.trim() });
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "Update failed";
return c.json({ error: msg }, 500);
}
});
// --- Root-only: credential management ---
app.post("/api/apps/:appId/credentials", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
let body: { username?: string; password?: string };
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
if (!body.username || !body.password) {
return c.json({ error: "username and password are required" }, 400);
}
try {
updateAppCredentials(appId, body.username, body.password);
return c.json({ ok: true, username: body.username, password: body.password });
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "Credential update failed";
return c.json({ error: msg }, 500);
}
});
app.post("/api/apps/:appId/credentials/delete", authMiddleware, requireRoot, (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
try {
deleteAppCredentials(appId);
return c.json({ ok: true });
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "Delete credentials failed";
return c.json({ error: msg }, 500);
}
});
// --- Root-only: generate magic link ---
app.post("/api/apps/:appId/magic-link", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const creds = getAppCredentials(appId);
if (!creds) {
return c.json({ error: "No credentials set for this app. Add credentials first." }, 400);
}
const token = await generateMagicLinkToken(appId, creds.username, creds.password);
const host = c.req.header("Host") ?? "localhost";
const proto = c.req.header("X-Forwarded-Proto") ?? "http";
const url = `${proto}://${host}/apps/${appId}/magic?token=${token}`;
return c.json({ url });
});
// --- Root-only: PRD/ERD/POC management ---
app.post("/api/apps/:appId/prd", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
let body: { prd?: string };
try { body = await c.req.json(); } catch { return c.json({ error: "Invalid JSON body" }, 400); }
if (body.prd === undefined) return c.json({ error: "prd is required" }, 400);
updateAppPrd(appId, body.prd);
return c.json({ ok: true });
});
app.post("/api/apps/:appId/erd", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
let body: { erd?: string };
try { body = await c.req.json(); } catch { return c.json({ error: "Invalid JSON body" }, 400); }
if (body.erd === undefined) return c.json({ error: "erd is required" }, 400);
updateAppErd(appId, body.erd);
return c.json({ ok: true });
});
app.post("/api/apps/:appId/generate-prd", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
try {
const prd = await generatePrd(record.description, record.title, client, appId);
updateAppPrd(appId, prd);
return c.json({ ok: true, prd });
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "PRD generation failed";
return c.json({ error: msg }, 500);
}
});
app.post("/api/apps/:appId/generate-erd", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
try {
// Auto-generate PRD first if none exists
let prd = record.prd;
let prdGenerated = false;
if (!prd) {
prd = await generatePrd(record.description, record.title, client, appId);
updateAppPrd(appId, prd);
prdGenerated = true;
}
const erd = await generateErd(prd, record.title, client, appId);
updateAppErd(appId, erd);
return c.json({ ok: true, erd, ...(prdGenerated ? { prd } : {}) });
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "ERD generation failed";
return c.json({ error: msg }, 500);
}
});
app.post("/api/apps/:appId/regenerate", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
let body: { prd?: string; erd?: string } = {};
try { body = await c.req.json(); } catch { /* use stored values */ }
const prd = body.prd || record.prd;
const erd = body.erd || record.erd;
if (!prd || !erd) return c.json({ error: "Both PRD and ERD are required to regenerate" }, 400);
// Save any updated PRD/ERD
if (body.prd) updateAppPrd(appId, body.prd);
if (body.erd) updateAppErd(appId, body.erd);
return streamSSE(c, async (stream) => {
try {
await stream.writeSSE({ event: "generating", data: JSON.stringify({ step: "generating", message: "Regenerating app from PRD + ERD..." }) });
await regenerateApp(appId, prd, erd, client);
await stream.writeSSE({ event: "complete", data: JSON.stringify({ step: "complete", message: "App regenerated successfully" }) });
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "Regeneration failed";
await stream.writeSSE({ event: "error", data: JSON.stringify({ step: "error", message: msg }) });
}
});
});
app.get("/api/apps/:appId/poc-plan", authMiddleware, requireRoot, (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
return c.json({ poc_plan: record.poc_plan || "" });
});
app.post("/api/apps/:appId/poc-plan", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
try {
const pocPlan = await generatePocPlan(appId, client);
return c.json({ ok: true, poc_plan: pocPlan });
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "POC plan generation failed";
return c.json({ error: msg }, 500);
}
});
app.put("/api/apps/:appId/poc-plan", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
let body: { poc_plan?: string };
try { body = await c.req.json(); } catch { return c.json({ error: "Invalid JSON body" }, 400); }
if (body.poc_plan === undefined) return c.json({ error: "poc_plan is required" }, 400);
updateAppPocPlan(appId, body.poc_plan);
return c.json({ ok: true });
});
// --- Root-only: enable/disable apps ---
app.post("/api/apps/:appId/disable", authMiddleware, requireRoot, async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
let body: { reason?: string } = {};
try { body = await c.req.json(); } catch { /* empty body is fine */ }
disableApp(appId, body.reason || "manual");
return c.json({ ok: true });
});
app.post("/api/apps/:appId/enable", authMiddleware, requireRoot, (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
enableApp(appId);
return c.json({ ok: true });
});
// --- Disabled app page (public, no auth) ---
app.get("/apps/:appId/disabled", async (c) => {
const html = await Deno.readTextFile("static/app-disabled.html");
return c.html(html);
});
// --- Per-app routes: open if no credentials, otherwise require auth ---
import type { Context, Next } from "@hono/hono";
const openOrAuth = async (c: Context, next: Next) => {
const appId = c.req.param("appId");
if (!appId) { await next(); return; }
// Check if app is disabled (root users bypass this check)
const disabledStatus = isAppDisabled(appId);
const creds = getAppCredentials(appId);
if (!creds) {
// Open app — still check disabled
if (disabledStatus.disabled) {
return c.json({ error: "App is disabled: " + disabledStatus.reason }, 403);
}
await next(); return;
}
const token = getCookie(c, "auth_token");
if (!token) return c.json({ error: "Unauthorized" }, 401);
try {
const secret = Deno.env.get("JWT_SECRET") ?? "";
const payload = await verify(token, secret, "HS256");
c.set("user", payload.sub as string);
c.set("role", payload.role as string);
if (payload.appId) c.set("appId", payload.appId as string);
if (payload.role === "root") { await next(); return; }
// Non-root: check disabled
if (disabledStatus.disabled) {
return c.json({ error: "App is disabled: " + disabledStatus.reason }, 403);
}
if (payload.role === "app" && payload.appId === appId) { await next(); return; }
return c.json({ error: "Forbidden" }, 403);
} catch {
return c.json({ error: "Unauthorized" }, 401);
}
};
app.use("/api/apps/:appId/tables/*", openOrAuth);
app.use("/api/apps/:appId/chat", openOrAuth);
app.use("/api/apps/:appId/conversations/*", openOrAuth);
app.use("/api/apps/:appId/conversations", openOrAuth);
app.use("/api/apps/:appId/ai/*", openOrAuth);
app.use("/api/apps/:appId/agents/*", openOrAuth);
app.use("/api/apps/:appId/agents", openOrAuth);
app.use("/api/apps/:appId/guidelines/*", openOrAuth);
app.use("/api/apps/:appId/guidelines", openOrAuth);
app.use("/api/apps/:appId/mcp-servers/*", openOrAuth);
app.use("/api/apps/:appId/mcp-servers", openOrAuth);
app.use("/api/apps/:appId/connections/*", openOrAuth);
app.use("/api/apps/:appId/connections", openOrAuth);
app.use("/api/apps/:appId/widget-chat", openOrAuth);
// --- Models endpoint: any authenticated user ---
app.use("/api/models", authMiddleware);
// --- Widget conversational chat (SSE streaming) ---
app.post("/api/apps/:appId/widget-chat", async (c) => {
const appId = c.req.param("appId");
const appRecord = getApp(appId);
if (!appRecord) return c.json({ error: "App not found" }, 404);
let body: { message?: string; conversation_id?: string };
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
if (!body.message?.trim()) {
return c.json({ error: "message is required" }, 400);
}
// Determine role from auth context
const role = c.get("role") || "";
const isRoot = role === "root";
// Build base URL for OAuth callback
const host = c.req.header("Host") ?? "localhost:8000";
const proto = c.req.header("X-Forwarded-Proto") ?? "http";
const baseUrl = `${proto}://${host}`;
return streamSSE(c, async (stream) => {
try {
await runWidgetAgent({
client,
appId,
message: body.message!.trim(),
conversationId: body.conversation_id,
isRoot,
baseUrl,
onEvent: async (event: WidgetSSEEvent) => {
await stream.writeSSE({
event: event.event,
data: JSON.stringify(event.data),
});
},
});
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "Widget chat failed";
await stream.writeSSE({
event: "error",
data: JSON.stringify({ text: msg }),
});
}
});
});
// --- OAuth callback (public, no auth) ---
app.get("/api/apps/:appId/oauth/callback", async (c) => {
const appId = c.req.param("appId");
const code = c.req.query("code");
const state = c.req.query("state"); // connection ID
if (!code || !state) {
return c.html("<h2>Error</h2><p>Missing code or state parameter.</p>", 400);
}
const conn = getAppConnection(state);
if (!conn || conn.app_id !== appId) {
return c.html("<h2>Error</h2><p>Invalid state — connection not found.</p>", 400);
}
const config = JSON.parse(conn.config || "{}") as Record<string, unknown>;
const tokenUrl = config.token_url as string;
const clientId = config.client_id as string;
const clientSecret = config.client_secret as string;
if (!tokenUrl || !clientId || !clientSecret) {
return c.html("<h2>Error</h2><p>OAuth configuration incomplete.</p>", 400);
}
const host = c.req.header("Host") ?? "localhost:8000";
const proto = c.req.header("X-Forwarded-Proto") ?? "http";
const redirectUri = `${proto}://${host}/api/apps/${appId}/oauth/callback`;
try {
const tokenRes = await fetch(tokenUrl, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: redirectUri,
client_id: clientId,
client_secret: clientSecret,
}),
});
if (!tokenRes.ok) {
const errText = await tokenRes.text();
console.error(`[oauth] Token exchange failed: ${tokenRes.status} ${errText}`);
return c.html(`<h2>Authorization Failed</h2><p>Token exchange failed. Please try again.</p>`, 500);
}
const tokens = await tokenRes.json() as {
access_token: string;
refresh_token?: string;
expires_in?: number;
};
const expiresAt = tokens.expires_in
? new Date(Date.now() + tokens.expires_in * 1000).toISOString()
: null;
updateAppConnectionOAuthTokens(
conn.id,
tokens.access_token,
tokens.refresh_token ?? null,
expiresAt,
);
return c.html(`<!DOCTYPE html>
<html><head><title>Authorization Successful</title>
<style>body{font-family:sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#f0f7ff}
.card{background:#fff;padding:40px;border-radius:12px;box-shadow:0 4px 24px rgba(0,0,0,0.1);text-align:center;max-width:400px}
h2{color:#2e7d32;margin-bottom:8px}p{color:#555}</style></head>
<body><div class="card"><h2>Authorization Successful!</h2><p>You can close this tab and return to the app.</p></div></body></html>`);
} catch (e) {
console.error(`[oauth] Token exchange error:`, e);
return c.html(`<h2>Authorization Failed</h2><p>An error occurred during authorization. Please try again.</p>`, 500);
}
});
// --- LLM chat routes (structured conversations + stateless) ---
app.route("/", createChatRoutes(client, openaiClient));
// --- Agent routes ---
app.route("/", createAgentRoutes(client));
// --- Connection routes ---
app.route("/", createConnectionRoutes());
// --- CRUD routes ---
app.route("/", crud);
// --- Serve generated apps ---
app.get("/apps/:appId", async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
const creds = getAppCredentials(appId);
// No credentials → serve directly to anyone (open access, no widget)
if (!creds) {
// Check disabled for open apps (no auth to check role)
const disabledStatus = isAppDisabled(appId);
if (disabledStatus.disabled) return c.redirect(`/apps/${appId}/disabled`);
return c.html(record.html);
}
// Has credentials → try to authenticate via JWT cookie
let role: string | undefined;
let tokenAppId: string | undefined;
const token = getCookie(c, "auth_token");
if (token) {
try {
const secret = Deno.env.get("JWT_SECRET") ?? "";
const payload = await verify(token, secret, "HS256");
role = payload.role as string;
tokenAppId = payload.appId as string | undefined;
} catch {
// Invalid/expired token — treat as unauthenticated
}
}
// Check access: root or matching app user
const hasAccess = role === "root" || (role === "app" && tokenAppId === appId);
if (!hasAccess) {
return c.redirect(`/apps/${appId}/login`);
}
// Check disabled — root users bypass
if (role !== "root") {
const disabledStatus = isAppDisabled(appId);
if (disabledStatus.disabled) return c.redirect(`/apps/${appId}/disabled`);
}
const isRoot = role === "root";
// Embed mode: serve raw app HTML for iframe loading
if (c.req.query("embed") === "1") {
return c.html(record.html);
}
// Serve wrapper page with iframe + persistent chat widget
let wrapper = await Deno.readTextFile("static/widget-wrapper.html");
const headerText = isRoot ? 'Edit this app' : 'Suggest changes';
const safeTitle = record.title.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
wrapper = wrapper
.replace(/\{\{APP_ID\}\}/g, appId)
.replace(/\{\{TITLE\}\}/g, safeTitle)
.replace(/\{\{HEADER_TEXT\}\}/g, headerText)
.replace(/\{\{IS_ROOT\}\}/g, isRoot ? 'true' : 'false')
.replace(/\{\{SYSTEM_MSG\}\}/g, isRoot
? "Ask questions about this app or describe changes you'd like to make."
: 'Ask questions or suggest changes to this app.')
.replace(/\{\{PLACEHOLDER\}\}/g, isRoot ? 'Ask a question or describe a change...' : 'Ask a question or suggest a change...');
return c.html(wrapper);
});
// External API for Swerk integration (X-API-Key auth)
app.route("/", createExternalApiRoutes(client));
// MCP server endpoint
app.post("/mcp", createMcpHandler(client));
Deno.serve({ port: 8000, hostname: "0.0.0.0" }, app.fetch);