-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic-server.ts
More file actions
299 lines (261 loc) · 9.43 KB
/
static-server.ts
File metadata and controls
299 lines (261 loc) · 9.43 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
import { serve } from "https://deno.land/std@0.177.0/http/server.ts";
import { serveFile } from "https://deno.land/std@0.177.0/http/file_server.ts";
import { handleCorsProxyRequest } from "./cors-proxy.ts";
// --- Configuration ---
const PORT = 8081;
const CLAWDBOT_URL = "http://127.0.0.1:18789/tools/invoke";
const CLAWDBOT_CHAT_URL = "http://127.0.0.1:18789/v1/chat/completions";
const CLAWDBOT_TOKEN = Deno.env.get("CLAWDBOT_TOKEN") || "b888b285b8e6f2781e39fce4397bb6b5b25c00f389b28edc";
const VARGO_TOKEN = Deno.env.get("VARGO_TELEGRAM_TOKEN");
const GOOGLE_CLIENT_ID = Deno.env.get("GOOGLE_CLIENT_ID") || "671385367166-4118tll0ntluovkdm5agd85arvl1ml9h.apps.googleusercontent.com";
const GROUP_CHAT_ID = "-1003897324317";
const CORS_HEADERS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Clawd-Token",
};
// --- State ---
const clients = new Map<string, (msg: string) => void>();
// --- Helpers ---
/**
* Validates Google Access Token by calling userinfo endpoint
*/
async function verifyGoogleAccessToken(token: string) {
try {
const response = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
headers: { 'Authorization': `Bearer ${token}` }
});
if (!response.ok) return null;
const user = await response.json();
if (user.email.toLowerCase() !== "weolopez@gmail.com") return null;
return user;
} catch (error) {
console.error("[Bridge Auth] Token verification failed:", error);
return null;
}
}
const checkAuth = async (req: Request) => {
const authHeader = req.headers.get("Authorization");
let token = authHeader?.startsWith("Bearer ") ? authHeader.split(" ")[1] : null;
if (!token) {
token = new URL(req.url).searchParams.get("token");
}
if (!token) return null;
return await verifyGoogleAccessToken(token);
};
// --- Request Handlers ---
/**
* Handle Server-Sent Events (SSE) for real-time updates
*/
async function handleEventsRequest(request: Request): Promise<Response> {
const user = await checkAuth(request);
if (!user) {
return new Response("Unauthorized", { status: 401, headers: CORS_HEADERS });
}
const clientId = crypto.randomUUID();
const body = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
const send = (msg: string) => {
try {
controller.enqueue(encoder.encode(`data: ${msg}\n\n`));
} catch (e) {
console.error("[Bridge] SSE send error", e);
}
};
clients.set(clientId, send);
console.log(`[Bridge] ${user.email} connected (Total: ${clients.size})`);
const keepAlive = setInterval(() => {
try {
controller.enqueue(encoder.encode(": keepalive\n\n"));
} catch {
clearInterval(keepAlive);
}
}, 15000);
},
cancel() {
clients.delete(clientId);
console.log(`[Bridge] Client disconnected`);
},
});
return new Response(body, {
headers: {
...CORS_HEADERS,
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
},
});
}
/**
* Unified Bridge messaging handler
*/
async function handleClawdBridgeRequest(request: Request): Promise<Response> {
if (request.method === "OPTIONS") {
return new Response(null, { headers: CORS_HEADERS });
}
const user = await checkAuth(request);
if (!user) {
return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401, headers: CORS_HEADERS });
}
try {
const body = await request.json();
const { message, useCompletions, systemPrompt } = body;
// 1. Direct Chat Completion Proxy
if (useCompletions) {
console.log(`[Bridge] Proxying Chat Completion for ${user.email}`);
const response = await fetch(CLAWDBOT_CHAT_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${CLAWDBOT_TOKEN}`
},
body: JSON.stringify({
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: message }
],
model: "default"
})
});
if (!response.ok) {
const errorText = await response.text();
console.error(`[Bridge] Gemini Proxy error: ${errorText}`);
return new Response(JSON.stringify({ error: "Gemini Proxy error" }), { status: 500, headers: CORS_HEADERS });
}
const result = await response.json();
return new Response(JSON.stringify({
status: "success",
reply: result.choices[0].message.content
}), {
headers: { ...CORS_HEADERS, "Content-Type": "application/json" }
});
}
// 2. Default: Forward to the agent turn
console.log(`[Bridge] Forwarding message from ${user.email}: ${message}`);
const response = await fetch(CLAWDBOT_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${CLAWDBOT_TOKEN}`
},
body: JSON.stringify({
tool: "sessions_send",
args: {
sessionKey: "agent:main:main",
message: message
}
})
});
if (!response.ok) {
return new Response(JSON.stringify({ error: "Archie is busy" }), { status: 500, headers: CORS_HEADERS });
}
return new Response(JSON.stringify({ status: "success" }), {
headers: { ...CORS_HEADERS, "Content-Type": "application/json" }
});
} catch (err) {
return new Response(JSON.stringify({ error: "Invalid request" }), { status: 400, headers: CORS_HEADERS });
}
}
/**
* Vargo Telegram Relay
*/
async function handleVargoRelay(request: Request): Promise<Response> {
if (!VARGO_TOKEN) {
return new Response(JSON.stringify({ error: "Vargo identity not configured" }), { status: 500, headers: CORS_HEADERS });
}
try {
const body = await request.json();
const { message } = body;
if (!message) {
return new Response(JSON.stringify({ error: "No message provided" }), { status: 400, headers: CORS_HEADERS });
}
console.log(`[Relay] Vargo speaking: ${message}`);
const telegramUrl = `https://api.telegram.org/bot${VARGO_TOKEN}/sendMessage`;
const response = await fetch(telegramUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
chat_id: GROUP_CHAT_ID,
text: message
})
});
if (!response.ok) {
const errorText = await response.text();
console.error(`[Relay] Telegram error: ${errorText}`);
return new Response(JSON.stringify({ error: "Telegram delivery failed" }), { status: 500, headers: CORS_HEADERS });
}
return new Response(JSON.stringify({ status: "success" }), {
headers: { ...CORS_HEADERS, "Content-Type": "application/json" }
});
} catch (err) {
return new Response(JSON.stringify({ error: "Invalid relay request" }), { status: 400, headers: CORS_HEADERS });
}
}
/**
* Internal Push (Broadcast to SSE clients)
*/
async function handlePushRequest(request: Request): Promise<Response> {
try {
const body = await request.json();
const { message } = body;
const payload = JSON.stringify({ message, timestamp: new Date().toISOString() });
for (const send of clients.values()) {
send(payload);
}
return new Response(JSON.stringify({ ok: true }), { headers: CORS_HEADERS });
} catch (err) {
return new Response(JSON.stringify({ error: "Push failed" }), { status: 400, headers: CORS_HEADERS });
}
}
// --- Main Router ---
async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url);
console.log(`[server] ${request.method} ${url.pathname}`);
// 1. API Endpoints (Bridge & Relay)
if (url.pathname === "/clawd-bridge" || url.pathname === "/message" || url.pathname === "/clawd-bridge/message") {
return await handleClawdBridgeRequest(request);
}
if (url.pathname === "/events" || url.pathname === "/clawd-bridge/events") {
return await handleEventsRequest(request);
}
if (url.pathname === "/relay/vargo") {
const user = await checkAuth(request);
if (!user) {
return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401, headers: CORS_HEADERS });
}
return await handleVargoRelay(request);
}
if (url.pathname === "/push") {
return await handlePushRequest(request);
}
// 2. Utilities
if (url.pathname.startsWith('/cors-proxy')) {
return await handleCorsProxyRequest(request);
}
// 3. Static File Server
const hasExtension = /\.[a-z0-9]+$/i.test(url.pathname);
if (hasExtension) {
try {
const filePath = "." + url.pathname;
const fileExtension = url.pathname.split('.').pop()?.toLowerCase();
if (fileExtension === 'bjs' || fileExtension === 'js') {
const fileContent = await Deno.readFile(filePath);
return new Response(fileContent, {
headers: { "Content-Type": "application/javascript" },
});
}
return await serveFile(request, filePath);
} catch {
return new Response("File not found", { status: 404 });
}
}
// SPA routing: Serve index.html for root or extensionless paths
try {
return await serveFile(request, "./index.html");
} catch {
return new Response("Index not found", { status: 404 });
}
}
console.log(`Unified Static & Bridge Server running on http://localhost:${PORT}`);
serve(handleRequest, { port: PORT });