Delete server.cjs with huggingface_hub
Browse files- server.cjs +0 -227
server.cjs
DELETED
|
@@ -1,227 +0,0 @@
|
|
| 1 |
-
const express = require('express');
|
| 2 |
-
const path = require('path');
|
| 3 |
-
const cookieParser = require('cookie-parser');
|
| 4 |
-
const crypto = require('crypto');
|
| 5 |
-
const fs = require('fs');
|
| 6 |
-
const app = express();
|
| 7 |
-
const port = 7860;
|
| 8 |
-
|
| 9 |
-
app.use(express.json({ limit: '50mb' }));
|
| 10 |
-
app.use(cookieParser());
|
| 11 |
-
app.use(express.static(path.join(__dirname, 'dist')));
|
| 12 |
-
|
| 13 |
-
const OAUTH_CLIENT_ID = process.env.OAUTH_CLIENT_ID;
|
| 14 |
-
const OAUTH_CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET;
|
| 15 |
-
const OAUTH_SCOPES = process.env.OAUTH_SCOPES || "openid profile";
|
| 16 |
-
const OPENID_PROVIDER_URL = process.env.OPENID_PROVIDER_URL || "https://huggingface.co";
|
| 17 |
-
const SPACE_HOST = process.env.SPACE_HOST;
|
| 18 |
-
|
| 19 |
-
const REDIRECT_URI = SPACE_HOST
|
| 20 |
-
? `https://${SPACE_HOST}/oauth/callback`
|
| 21 |
-
: `http://localhost:${port}/oauth/callback`;
|
| 22 |
-
|
| 23 |
-
app.post('/api/craft', async (req, res) => {
|
| 24 |
-
const { content, variation } = req.body;
|
| 25 |
-
const apiKey = process.env.BLABLADOR_API_KEY;
|
| 26 |
-
|
| 27 |
-
if (!apiKey) {
|
| 28 |
-
return res.status(500).json({ error: 'BLABLADOR_API_KEY is not configured on the server.' });
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
const model = content.length > 500 ? 'alias-large' : 'alias-fast';
|
| 32 |
-
const prompt = `You are a professional content creator. Help me craft a ${variation || 'social media post'} based on the following content:\n\n${content}\n\nProvide 3 distinct and engaging variations.`;
|
| 33 |
-
|
| 34 |
-
try {
|
| 35 |
-
const response = await fetch('https://api.helmholtz-blablador.fz-juelich.de/v1/chat/completions', {
|
| 36 |
-
method: 'POST',
|
| 37 |
-
headers: {
|
| 38 |
-
'Authorization': `Bearer ${apiKey}`,
|
| 39 |
-
'Content-Type': 'application/json'
|
| 40 |
-
},
|
| 41 |
-
body: JSON.stringify({
|
| 42 |
-
model: model,
|
| 43 |
-
messages: [
|
| 44 |
-
{ role: 'system', content: 'You are a helpful assistant that helps craft engaging marketing and social media content.' },
|
| 45 |
-
{ role: 'user', content: prompt }
|
| 46 |
-
],
|
| 47 |
-
temperature: 0.7
|
| 48 |
-
})
|
| 49 |
-
});
|
| 50 |
-
|
| 51 |
-
if (!response.ok) {
|
| 52 |
-
const errorData = await response.json();
|
| 53 |
-
return res.status(response.status).json(errorData);
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
const data = await response.json();
|
| 57 |
-
res.json({ result: data.choices[0].message.content });
|
| 58 |
-
} catch (error) {
|
| 59 |
-
console.error('Blablador API error:', error);
|
| 60 |
-
res.status(500).json({ error: 'Failed to connect to Blablador API.' });
|
| 61 |
-
}
|
| 62 |
-
});
|
| 63 |
-
|
| 64 |
-
app.get('/api/config', (req, res) => {
|
| 65 |
-
res.json({
|
| 66 |
-
clientId: OAUTH_CLIENT_ID,
|
| 67 |
-
scopes: OAUTH_SCOPES,
|
| 68 |
-
});
|
| 69 |
-
});
|
| 70 |
-
|
| 71 |
-
app.get('/login', (req, res) => {
|
| 72 |
-
if (!OAUTH_CLIENT_ID) {
|
| 73 |
-
return res.status(500).json({ error: "OAuth is not configured (missing OAUTH_CLIENT_ID)" });
|
| 74 |
-
}
|
| 75 |
-
|
| 76 |
-
const state = crypto.randomBytes(16).toString('hex');
|
| 77 |
-
res.cookie('oauth_state', state, { httpOnly: true, maxAge: 600000 }); // 10 mins
|
| 78 |
-
|
| 79 |
-
const authUrl = `${OPENID_PROVIDER_URL}/oauth/authorize` +
|
| 80 |
-
`?client_id=${OAUTH_CLIENT_ID}` +
|
| 81 |
-
`&redirect_uri=${encodeURIComponent(REDIRECT_URI)}` +
|
| 82 |
-
`&scope=${encodeURIComponent(OAUTH_SCOPES)}` +
|
| 83 |
-
`&response_type=code` +
|
| 84 |
-
`&state=${state}`;
|
| 85 |
-
|
| 86 |
-
res.redirect(authUrl);
|
| 87 |
-
});
|
| 88 |
-
|
| 89 |
-
app.get('/oauth/callback', async (req, res) => {
|
| 90 |
-
const { code, state } = req.query;
|
| 91 |
-
const savedState = req.cookies.oauth_state;
|
| 92 |
-
|
| 93 |
-
if (!state || state !== savedState) {
|
| 94 |
-
console.error("State mismatch:", { state, savedState });
|
| 95 |
-
return res.status(403).json({ error: "Invalid OAuth state" });
|
| 96 |
-
}
|
| 97 |
-
res.clearCookie('oauth_state');
|
| 98 |
-
const tokenUrl = `${OPENID_PROVIDER_URL}/oauth/token`;
|
| 99 |
-
|
| 100 |
-
const authStr = Buffer.from(`${OAUTH_CLIENT_ID}:${OAUTH_CLIENT_SECRET}`).toString('base64');
|
| 101 |
-
|
| 102 |
-
try {
|
| 103 |
-
const tokenResp = await fetch(tokenUrl, {
|
| 104 |
-
method: 'POST',
|
| 105 |
-
headers: {
|
| 106 |
-
'Authorization': `Basic ${authStr}`,
|
| 107 |
-
'Content-Type': 'application/x-www-form-urlencoded'
|
| 108 |
-
},
|
| 109 |
-
body: new URLSearchParams({
|
| 110 |
-
grant_type: 'authorization_code',
|
| 111 |
-
code: code,
|
| 112 |
-
redirect_uri: REDIRECT_URI,
|
| 113 |
-
client_id: OAUTH_CLIENT_ID,
|
| 114 |
-
})
|
| 115 |
-
});
|
| 116 |
-
|
| 117 |
-
if (!tokenResp.ok) {
|
| 118 |
-
const errorText = await tokenResp.text();
|
| 119 |
-
console.error("Token exchange failed:", errorText);
|
| 120 |
-
return res.status(400).json({ error: "Failed to retrieve access token" });
|
| 121 |
-
}
|
| 122 |
-
|
| 123 |
-
const tokenData = await tokenResp.json();
|
| 124 |
-
const accessToken = tokenData.access_token;
|
| 125 |
-
|
| 126 |
-
const userResp = await fetch("https://huggingface.co/api/whoami-v2", {
|
| 127 |
-
headers: { "Authorization": `Bearer ${accessToken}` }
|
| 128 |
-
});
|
| 129 |
-
const userInfo = await userResp.json();
|
| 130 |
-
|
| 131 |
-
// Set cookie and redirect back to app
|
| 132 |
-
res.cookie('hf_user', JSON.stringify(userInfo), { path: '/', httpOnly: false });
|
| 133 |
-
res.redirect('/');
|
| 134 |
-
} catch (error) {
|
| 135 |
-
console.error("OAuth callback error:", error);
|
| 136 |
-
res.status(500).json({ error: "Authentication failed" });
|
| 137 |
-
}
|
| 138 |
-
});
|
| 139 |
-
|
| 140 |
-
app.get('/api/user', (req, res) => {
|
| 141 |
-
if (req.cookies.hf_user) {
|
| 142 |
-
try {
|
| 143 |
-
res.json(JSON.parse(req.cookies.hf_user));
|
| 144 |
-
} catch (e) {
|
| 145 |
-
res.status(400).json({ error: "Invalid user cookie" });
|
| 146 |
-
}
|
| 147 |
-
} else {
|
| 148 |
-
res.status(401).json({ error: "Not authenticated" });
|
| 149 |
-
}
|
| 150 |
-
});
|
| 151 |
-
|
| 152 |
-
app.get('/api/logout', (req, res) => {
|
| 153 |
-
res.clearCookie('hf_user');
|
| 154 |
-
res.redirect('/');
|
| 155 |
-
});
|
| 156 |
-
|
| 157 |
-
app.post('/api/save-data', (req, res) => {
|
| 158 |
-
let { type, data, user } = req.body;
|
| 159 |
-
|
| 160 |
-
// Sanitize inputs to prevent path traversal
|
| 161 |
-
user = String(user).replace(/[^a-z0-9]/gi, '_');
|
| 162 |
-
type = String(type).replace(/[^a-z0-9]/gi, '_');
|
| 163 |
-
|
| 164 |
-
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
| 165 |
-
const filename = `${user}_${type}_${timestamp}.json`;
|
| 166 |
-
const dirPath = path.join(__dirname, 'data');
|
| 167 |
-
|
| 168 |
-
if (!fs.existsSync(dirPath)) {
|
| 169 |
-
fs.mkdirSync(dirPath, { recursive: true });
|
| 170 |
-
}
|
| 171 |
-
|
| 172 |
-
const filePath = path.join(dirPath, filename);
|
| 173 |
-
|
| 174 |
-
try {
|
| 175 |
-
fs.writeFileSync(filePath, JSON.stringify({ user, type, timestamp, data }, null, 2));
|
| 176 |
-
console.log(`Saved data to ${filePath}`);
|
| 177 |
-
res.json({ success: true, message: `Data saved as ${filename}` });
|
| 178 |
-
} catch (error) {
|
| 179 |
-
console.error('Failed to save data:', error);
|
| 180 |
-
res.status(500).json({ error: 'Failed to save data' });
|
| 181 |
-
}
|
| 182 |
-
});
|
| 183 |
-
|
| 184 |
-
app.get('/api/list-data', (req, res) => {
|
| 185 |
-
let { type, user } = req.query;
|
| 186 |
-
const dirPath = path.join(__dirname, 'data');
|
| 187 |
-
|
| 188 |
-
// Sanitize inputs
|
| 189 |
-
if (user) user = String(user).replace(/[^a-z0-9]/gi, '_');
|
| 190 |
-
if (type) type = String(type).replace(/[^a-z0-9]/gi, '_');
|
| 191 |
-
|
| 192 |
-
if (!fs.existsSync(dirPath)) {
|
| 193 |
-
return res.json([]);
|
| 194 |
-
}
|
| 195 |
-
|
| 196 |
-
try {
|
| 197 |
-
const files = fs.readdirSync(dirPath);
|
| 198 |
-
const results = files
|
| 199 |
-
.filter(f => f.endsWith('.json'))
|
| 200 |
-
.map(f => {
|
| 201 |
-
try {
|
| 202 |
-
const content = fs.readFileSync(path.join(dirPath, f), 'utf8');
|
| 203 |
-
return JSON.parse(content);
|
| 204 |
-
} catch (e) {
|
| 205 |
-
return null;
|
| 206 |
-
}
|
| 207 |
-
})
|
| 208 |
-
.filter(d => d && (!type || d.type === type) && (!user || d.user === user));
|
| 209 |
-
|
| 210 |
-
res.json(results);
|
| 211 |
-
} catch (error) {
|
| 212 |
-
console.error('Failed to list data:', error);
|
| 213 |
-
res.status(500).json({ error: 'Failed to list data' });
|
| 214 |
-
}
|
| 215 |
-
});
|
| 216 |
-
|
| 217 |
-
app.get('/health', (req, res) => {
|
| 218 |
-
res.status(200).send('OK');
|
| 219 |
-
});
|
| 220 |
-
|
| 221 |
-
app.use((req, res) => {
|
| 222 |
-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