8421bit commited on
Commit
bddc111
·
verified ·
1 Parent(s): 91e52d9

Create server.js

Browse files
Files changed (1) hide show
  1. server.js +454 -0
server.js ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from "express";
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ import dotenv from "dotenv";
5
+ import cookieParser from "cookie-parser";
6
+ import {
7
+ createRepo,
8
+ uploadFiles,
9
+ whoAmI,
10
+ spaceInfo,
11
+ } from "@huggingface/hub";
12
+ import { InferenceClient } from "@huggingface/inference";
13
+ import bodyParser from "body-parser";
14
+
15
+ import checkUser from "./middlewares/checkUser.js"; // Assuming this middleware exists
16
+ // Removed PROVIDERS import
17
+ import { COLORS } from "./utils/colors.js"; // Assuming this utility exists
18
+
19
+ // Load environment variables from .env file
20
+ dotenv.config();
21
+
22
+ const app = express();
23
+
24
+ const ipAddresses = new Map(); // For rate limiting unauthenticated users
25
+
26
+ const __filename = fileURLToPath(import.meta.url);
27
+ const __dirname = path.dirname(__filename);
28
+
29
+ const PORT = process.env.APP_PORT || 3000;
30
+ const REDIRECT_URI =
31
+ process.env.REDIRECT_URI || `http://localhost:${PORT}/auth/login`;
32
+ // --- Updated Model ID ---
33
+ const MODEL_ID = "deepseek-ai/deepseek-llm-7b-chat"; // Using the chat model
34
+ const MAX_NEW_TOKENS = 512; // Default max tokens for generation
35
+ const MAX_REQUESTS_PER_IP = 5; // Rate limit for unauthenticated users
36
+
37
+ app.use(cookieParser());
38
+ app.use(bodyParser.json());
39
+ // Serve static files from 'dist' and also the root for the new index.html
40
+ app.use(express.static(path.join(__dirname, "dist")));
41
+ app.use(express.static(path.join(__dirname))); // Serve index.html from root
42
+
43
+ // --- Helper Function (Keep as is) ---
44
+ const getPTag = (repoId) => {
45
+ // ... (keep the original getPTag function)
46
+ return `<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - <a href="https://enzostvs-deepsite.hf.space?remix=${repoId}" style="color: #fff;text-decoration: underline;" target="_blank" >🧬 Remix</a></p>`;
47
+ };
48
+
49
+ // --- Auth Routes (Keep as is) ---
50
+ app.get("/api/login", (_req, res) => {
51
+ // ... (keep original /api/login)
52
+ res.redirect(
53
+ 302,
54
+ `https://huggingface.co/oauth/authorize?client_id=${process.env.OAUTH_CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=openid%20profile%20write-repos%20manage-repos%20inference-api&prompt=consent&state=1234567890`
55
+ );
56
+ });
57
+ app.get("/auth/login", async (req, res) => {
58
+ // ... (keep original /auth/login)
59
+ const { code } = req.query;
60
+
61
+ if (!code) {
62
+ return res.redirect(302, "/");
63
+ }
64
+ const Authorization = `Basic ${Buffer.from(
65
+ `${process.env.OAUTH_CLIENT_ID}:${process.env.OAUTH_CLIENT_SECRET}`
66
+ ).toString("base64")}`;
67
+
68
+ try {
69
+ const request_auth = await fetch("https://huggingface.co/oauth/token", {
70
+ method: "POST",
71
+ headers: {
72
+ "Content-Type": "application/x-www-form-urlencoded",
73
+ Authorization,
74
+ },
75
+ body: new URLSearchParams({
76
+ grant_type: "authorization_code",
77
+ code: code,
78
+ redirect_uri: REDIRECT_URI,
79
+ }),
80
+ });
81
+
82
+ const response = await request_auth.json();
83
+
84
+ if (!response.access_token) {
85
+ console.error("OAuth Error:", response);
86
+ return res.redirect(302, "/?error=auth_failed");
87
+ }
88
+
89
+ res.cookie("hf_token", response.access_token, {
90
+ httpOnly: false, // Set to true if JS doesn't need to read it directly
91
+ secure: process.env.NODE_ENV === 'production', // Use secure cookies in production
92
+ sameSite: "lax", // More common default than 'none' unless cross-site needed
93
+ maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
94
+ });
95
+
96
+ return res.redirect(302, "/");
97
+
98
+ } catch(err) {
99
+ console.error("Error during OAuth token exchange:", err);
100
+ return res.redirect(302, "/?error=auth_exception");
101
+ }
102
+ });
103
+ app.get("/auth/logout", (req, res) => {
104
+ // ... (keep original /auth/logout)
105
+ res.clearCookie("hf_token", {
106
+ httpOnly: false,
107
+ secure: process.env.NODE_ENV === 'production',
108
+ sameSite: "lax",
109
+ });
110
+ return res.redirect(302, "/");
111
+ });
112
+
113
+ // --- User Info Route (Keep as is) ---
114
+ app.get("/api/@me", checkUser, async (req, res) => {
115
+ // ... (keep original /api/@me)
116
+ const { hf_token } = req.cookies;
117
+ try {
118
+ const request_user = await fetch("https://huggingface.co/oauth/userinfo", {
119
+ headers: {
120
+ Authorization: `Bearer ${hf_token}`,
121
+ },
122
+ });
123
+
124
+ if (!request_user.ok) {
125
+ throw new Error(`User info request failed with status ${request_user.status}`);
126
+ }
127
+
128
+ const user = await request_user.json();
129
+ res.send(user);
130
+ } catch (err) {
131
+ console.error("Error fetching user info:", err.message);
132
+ // Don't clear cookie on transient errors, only perhaps on 401?
133
+ // res.clearCookie("hf_token", { ... });
134
+ res.status(401).send({
135
+ ok: false,
136
+ message: err.message,
137
+ });
138
+ }
139
+ });
140
+
141
+ // --- Deploy Route (Keep as is, maybe update html replace logic if needed) ---
142
+ app.post("/api/deploy", checkUser, async (req, res) => {
143
+ // ... (keep original /api/deploy, ensure getPTag logic matches if you modify it)
144
+ const { html, title, path } = req.body;
145
+ if (!html || !title) {
146
+ return res.status(400).send({
147
+ ok: false,
148
+ message: "Missing required fields",
149
+ });
150
+ }
151
+
152
+ const { hf_token } = req.cookies;
153
+ try {
154
+ const repo = {
155
+ type: "space",
156
+ name: path ?? "",
157
+ };
158
+
159
+ let readme;
160
+ let newHtml = html;
161
+
162
+ if (!path || path === "") {
163
+ const { name: username } = await whoAmI({ accessToken: hf_token });
164
+ const newTitle = title
165
+ .toLowerCase()
166
+ .replace(/[^a-z0-9]+/g, "-")
167
+ .split("-")
168
+ .filter(Boolean)
169
+ .join("-")
170
+ .slice(0, 96);
171
+
172
+ const repoId = `${username}/${newTitle}`;
173
+ repo.name = repoId;
174
+
175
+ // Check if repo exists before creating? Might need adjustment
176
+ await createRepo({
177
+ repo,
178
+ accessToken: hf_token,
179
+ spaceSdk: "static", // Explicitly set SDK for new repos
180
+ });
181
+ const colorFrom = COLORS[Math.floor(Math.random() * COLORS.length)];
182
+ const colorTo = COLORS[Math.floor(Math.random() * COLORS.length)];
183
+ readme = `---
184
+ title: ${newTitle}
185
+ emoji: 🐳
186
+ colorFrom: ${colorFrom}
187
+ colorTo: ${colorTo}
188
+ sdk: static
189
+ pinned: false
190
+ tags:
191
+ - deepsite
192
+ ---
193
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference`;
194
+ }
195
+
196
+ // Ensure the p-tag replacement is robust
197
+ const pTag = getPTag(repo.name); // Generate the tag to add/replace
198
+ // Remove existing tag if present before adding
199
+ newHtml = newHtml.replace(/<p style=.*?enzostvs-deepsite\.hf\.space.*?<\/p>/s, "");
200
+ newHtml = newHtml.replace(/<\/body>/i, `${pTag}</body>`); // Add before closing body
201
+
202
+ const file = new Blob([newHtml], { type: "text/html" });
203
+ file.name = "index.html"; // Add name property to the Blob
204
+
205
+ const files = [file];
206
+ if (readme) {
207
+ const readmeFile = new Blob([readme], { type: "text/markdown" });
208
+ readmeFile.name = "README.md"; // Add name property to the Blob
209
+ files.push(readmeFile);
210
+ }
211
+ await uploadFiles({
212
+ repo,
213
+ files,
214
+ accessToken: hf_token,
215
+ commitMessage: "Update website via DeepSite" // Add commit message
216
+ });
217
+ return res.status(200).send({ ok: true, path: repo.name });
218
+ } catch (err) {
219
+ console.error("Deploy Error:", err);
220
+ return res.status(500).send({
221
+ ok: false,
222
+ message: err.message,
223
+ });
224
+ }
225
+ });
226
+
227
+ // --- *** UPDATED /api/ask-ai Route *** ---
228
+ app.post("/api/ask-ai", async (req, res) => {
229
+ // Removed 'provider' from destructuring
230
+ const { prompt, html, previousPrompt } = req.body;
231
+ if (!prompt) {
232
+ return res.status(400).send({
233
+ ok: false,
234
+ message: "Missing prompt field",
235
+ });
236
+ }
237
+
238
+ const { hf_token } = req.cookies;
239
+ let token = hf_token;
240
+
241
+ // --- Token & Rate Limiting Logic (Keep similar logic) ---
242
+ const ip = req.headers['x-forwarded-for']?.split(',')[0].trim() || req.socket.remoteAddress || 'unknown';
243
+
244
+ if (!token) {
245
+ const currentCount = (ipAddresses.get(ip) || 0) + 1;
246
+ if (currentCount > MAX_REQUESTS_PER_IP) {
247
+ console.warn(`Rate limit exceeded for IP: ${ip}`);
248
+ return res.status(429).send({
249
+ ok: false,
250
+ openLogin: true, // Keep this flag for the frontend
251
+ message: "Rate limit exceeded. Please log in to continue.",
252
+ });
253
+ }
254
+ ipAddresses.set(ip, currentCount);
255
+ console.log(`Anonymous request from ${ip}, count: ${currentCount}`);
256
+
257
+ token = process.env.DEFAULT_HF_TOKEN;
258
+ if (!token) {
259
+ console.error("DEFAULT_HF_TOKEN is not set. Cannot process anonymous requests.");
260
+ return res.status(503).send({ // 503 Service Unavailable might be better
261
+ ok: false,
262
+ message: "Service is temporarily unavailable for anonymous users.",
263
+ });
264
+ }
265
+ }
266
+ // --- End Token Logic ---
267
+
268
+ // Set up response headers for streaming
269
+ res.setHeader("Content-Type", "text/plain; charset=utf-8"); // Explicitly set UTF-8
270
+ res.setHeader("Cache-Control", "no-cache");
271
+ res.setHeader("Connection", "keep-alive");
272
+ res.setHeader("X-Content-Type-Options", "nosniff"); // Security header
273
+
274
+ try {
275
+ const client = new InferenceClient(token);
276
+
277
+ // Construct messages array (Keep context logic)
278
+ const messages = [
279
+ {
280
+ role: "system",
281
+ content: `ONLY USE HTML, CSS AND JAVASCRIPT. If you want to use ICON make sure to import the library first. Try to create the best UI possible by using only HTML, CSS and JAVASCRIPT. Use as much as you can TailwindCSS for the CSS, if you can't do something with TailwindCSS, then use custom CSS (make sure to import <script src="https://cdn.tailwindcss.com"></script> in the head). Also, try to ellaborate as much as you can, to create something unique. ALWAYS GIVE THE RESPONSE INTO A SINGLE HTML FILE`,
282
+ },
283
+ // Conditionally add previous user prompt if it exists
284
+ ...(previousPrompt ? [{ role: "user", content: previousPrompt }] : []),
285
+ // Conditionally add previous assistant response (current HTML) if it exists
286
+ ...(html ? [{ role: "assistant", content: `The current HTML code is:\n\`\`\`html\n${html}\n\`\`\`` }] : []),
287
+ // The new user prompt
288
+ {
289
+ role: "user",
290
+ content: prompt,
291
+ },
292
+ ];
293
+
294
+ console.log(`Calling model ${MODEL_ID} for IP ${ip}. Prompt: "${prompt.substring(0, 60)}..."`);
295
+
296
+ // --- Call chatCompletionStream without provider ---
297
+ const stream = client.chatCompletionStream({
298
+ model: MODEL_ID,
299
+ messages: messages,
300
+ max_tokens: MAX_NEW_TOKENS, // Use defined max tokens
301
+ // Optional: Add temperature, top_p if needed
302
+ // temperature: 0.7,
303
+ // top_p: 0.95,
304
+ });
305
+
306
+ // --- Process the stream ---
307
+ let responseText = ""; // To potentially check for end tags if needed
308
+ for await (const chunk of stream) {
309
+ // Check for content in the delta
310
+ if (chunk.choices && chunk.choices[0]?.delta?.content) {
311
+ const contentChunk = chunk.choices[0].delta.content;
312
+ res.write(contentChunk); // Send chunk to client
313
+ responseText += contentChunk;
314
+ // Example: Optional early exit if a specific tag is found
315
+ // if (responseText.includes("</html>")) {
316
+ // console.log("Detected </html>, ending stream early.");
317
+ // break;
318
+ // }
319
+ }
320
+ // Handle potential errors within the stream if the library provides them
321
+ if (chunk.error) {
322
+ console.error(`Error during stream for IP ${ip}:`, chunk.error);
323
+ // Decide if you want to send an error marker to the client
324
+ // res.write(`\n[Stream Error: ${chunk.error}]\n`);
325
+ // break; // Stop processing the stream on error
326
+ }
327
+ }
328
+
329
+ console.log(`Finished streaming response for IP ${ip}. Prompt: "${prompt.substring(0, 60)}..."`);
330
+ res.end(); // End the response stream properly
331
+
332
+ } catch (error) {
333
+ console.error(`Error in /api/ask-ai for IP ${ip}:`, error);
334
+
335
+ // Specific error handling (e.g., credits)
336
+ if (error.message && error.message.includes("exceeded your monthly included credits")) {
337
+ if (!res.headersSent) {
338
+ res.status(402).send({ // Payment Required
339
+ ok: false,
340
+ openProModal: true, // Keep this flag for frontend
341
+ message: "API call failed: " + error.message,
342
+ });
343
+ } else {
344
+ // Stream already started, append error and end
345
+ res.write("\n[Error: API Credit Limit Exceeded]\n");
346
+ res.end();
347
+ }
348
+ return;
349
+ }
350
+ // Handle other potential InferenceClient errors (e.g., 401 Unauthorized, 404 Model Not Found)
351
+ if (error.code) { // InferenceClient often includes error codes
352
+ if (!res.headersSent) {
353
+ let statusCode = 500;
354
+ if (error.code === 'ERR_INFERENCE_AUTH') statusCode = 401;
355
+ if (error.code === 'ERR_INFERENCE_NOT_FOUND') statusCode = 404;
356
+ res.status(statusCode).send({
357
+ ok: false,
358
+ message: `API Error (${error.code}): ${error.message}`,
359
+ });
360
+ } else {
361
+ res.write(`\n[Error: ${error.message}]\n`);
362
+ res.end();
363
+ }
364
+ return;
365
+ }
366
+
367
+
368
+ // Generic error handling if headers haven't been sent
369
+ if (!res.headersSent) {
370
+ res.status(500).send({
371
+ ok: false,
372
+ message: error.message || "An internal server error occurred.",
373
+ });
374
+ } else {
375
+ // If headers were sent, we can't change status code, just end the stream.
376
+ // Optionally try to write an error marker if the stream is still writable.
377
+ if (!res.writableEnded) {
378
+ res.write("\n[Error: Server failed to process the request fully]\n");
379
+ res.end();
380
+ }
381
+ }
382
+ }
383
+ });
384
+
385
+ // --- Remix Route (Keep as is, maybe adjust html cleaning) ---
386
+ app.get("/api/remix/:username/:repo", async (req, res) => {
387
+ // ... (keep original /api/remix, ensure getPTag logic matches for cleaning)
388
+ const { username, repo } = req.params;
389
+ const { hf_token } = req.cookies;
390
+
391
+ // Using default token for read-only operation is fine if repo is public
392
+ const token = hf_token || process.env.DEFAULT_HF_TOKEN;
393
+
394
+ const repoId = `${username}/${repo}`;
395
+
396
+ try {
397
+ // Check space exists and is static/public first (optional but good practice)
398
+ // const space = await spaceInfo({ repo: { type: "space", name: repoId }, accessToken: token });
399
+ // if (!space || space.sdk !== "static" || space.private) {
400
+ // return res.status(404).send({ ok: false, message: "Static public space not found" });
401
+ // }
402
+
403
+ const url = `https://huggingface.co/spaces/${repoId}/raw/main/index.html`;
404
+ const response = await fetch(url); // No token needed for public raw files
405
+
406
+ if (!response.ok) {
407
+ if (response.status === 404) {
408
+ return res.status(404).send({ ok: false, message: "index.html not found in the space" });
409
+ }
410
+ throw new Error(`Failed to fetch raw file: ${response.statusText}`);
411
+ }
412
+
413
+ let html = await response.text();
414
+ // Clean the specific p tag added by this tool
415
+ const pTagToRemove = getPTag(repoId); // Generate the exact tag to remove
416
+ html = html.replace(pTagToRemove, "");
417
+
418
+ res.status(200).send({
419
+ ok: true,
420
+ html,
421
+ });
422
+ } catch(err) {
423
+ console.error("Remix Error:", err);
424
+ // Don't expose internal errors directly unless needed
425
+ res.status(500).send({ ok: false, message: "Failed to remix the content." });
426
+ }
427
+ });
428
+
429
+
430
+ // --- Catch-all for Frontend Routing (Keep as is if using client-side router in 'dist') ---
431
+ // Make sure this is AFTER all API routes
432
+ app.get("*", (req, res) => {
433
+ // Check if the request looks like a file extension, if so, maybe 404?
434
+ if (path.extname(req.path).length > 0 && req.path !== "/index.html") {
435
+ res.status(404).send("Not found");
436
+ } else {
437
+ // Send the main HTML file for SPA routing
438
+ res.sendFile(path.join(__dirname, "dist", "index.html"));
439
+ // OR if the new HTML below is the main entry point:
440
+ // res.sendFile(path.join(__dirname, "index.html"));
441
+ }
442
+ });
443
+
444
+ // --- Server Start ---
445
+ app.listen(PORT, () => {
446
+ console.log(`Server listening on port ${PORT}`);
447
+ console.log(`Using model: ${MODEL_ID}`);
448
+ if (!process.env.OAUTH_CLIENT_ID || !process.env.OAUTH_CLIENT_SECRET) {
449
+ console.warn("Warning: OAuth environment variables (OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET) are not set. Login will not work.");
450
+ }
451
+ if (!process.env.DEFAULT_HF_TOKEN) {
452
+ console.warn("Warning: DEFAULT_HF_TOKEN is not set. Anonymous requests will fail.");
453
+ }
454
+ });