-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
359 lines (312 loc) · 10.1 KB
/
server.js
File metadata and controls
359 lines (312 loc) · 10.1 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
/**
* Node Text Intelligence Starter - Backend Server
*
* Simple REST API server providing text intelligence analysis
* powered by Deepgram's Text Intelligence service.
*
* Key Features:
* - Contract-compliant API endpoint: POST /api/text-intelligence
* - Accepts text or URL in JSON body
* - Supports multiple intelligence features: summarization, topics, sentiment, intents
* - CORS-enabled for frontend communication
* - JWT session auth with rate limiting (production only)
*/
require("dotenv").config();
const { createClient } = require("@deepgram/sdk");
const cors = require("cors");
const crypto = require("crypto");
const express = require("express");
const fs = require("fs");
const jwt = require("jsonwebtoken");
const path = require("path");
const toml = require("toml");
// ============================================================================
// CONFIGURATION
// ============================================================================
const CONFIG = {
port: process.env.PORT || 8081,
host: process.env.HOST || '0.0.0.0',
};
// ============================================================================
// SESSION AUTH - JWT tokens for production security
// ============================================================================
/**
* Session secret for signing JWTs.
*/
const SESSION_SECRET =
process.env.SESSION_SECRET || crypto.randomBytes(32).toString("hex");
/** JWT expiry time (1 hour) */
const JWT_EXPIRY = "1h";
/**
* Express middleware that validates JWT from Authorization header.
* Returns 401 with JSON error if token is missing or invalid.
*/
function requireSession(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return res.status(401).json({
error: {
type: "AuthenticationError",
code: "MISSING_TOKEN",
message: "Authorization header with Bearer token is required",
},
});
}
try {
const token = authHeader.slice(7);
jwt.verify(token, SESSION_SECRET);
next();
} catch (err) {
return res.status(401).json({
error: {
type: "AuthenticationError",
code: "INVALID_TOKEN",
message:
err.name === "TokenExpiredError"
? "Session expired, please refresh the page"
: "Invalid session token",
},
});
}
}
// ============================================================================
// API KEY LOADING
// ============================================================================
function loadApiKey() {
const apiKey = process.env.DEEPGRAM_API_KEY;
if (!apiKey) {
console.error('\n❌ ERROR: Deepgram API key not found!\n');
console.error('Please set your API key in .env file:');
console.error(' DEEPGRAM_API_KEY=your_api_key_here\n');
console.error('Get your API key at: https://console.deepgram.com\n');
process.exit(1);
}
return apiKey;
}
const apiKey = loadApiKey();
// Initialize Deepgram client
const deepgram = createClient(apiKey);
// Initialize Express app
const app = express();
// Middleware for parsing JSON request bodies
app.use(express.json());
// Enable CORS (wildcard is safe -- same-origin via Vite proxy / Caddy in production)
app.use(cors());
// ============================================================================
// SESSION ROUTES - Auth endpoints (unprotected)
// ============================================================================
/**
* GET /api/session — Issues a signed JWT for session authentication.
*/
app.get("/api/session", (req, res) => {
const token = jwt.sign(
{ iat: Math.floor(Date.now() / 1000) },
SESSION_SECRET,
{ expiresIn: JWT_EXPIRY }
);
res.json({ token });
});
// ============================================================================
// API ROUTES
// ============================================================================
/**
* POST /api/text-intelligence
*
* Contract-compliant text intelligence endpoint per starter-contracts specification.
* Accepts:
* - Query parameters: summarize, topics, sentiment, intents, language (all optional)
* - Body: JSON with either text or url field (required, not both)
*
* Returns:
* - Success (200): JSON with results object containing requested intelligence features
* - Error (4XX): JSON error response matching contract format
*/
app.post('/api/text-intelligence', requireSession, async (req, res) => {
try {
// Extract text or url from JSON body
const { text, url } = req.body;
// Validate that exactly one of text or url is provided
if (!text && !url) {
return res.status(400).json({
error: {
type: "validation_error",
code: "INVALID_TEXT",
message: "Request must contain either 'text' or 'url' field",
details: {}
}
});
}
if (text && url) {
return res.status(400).json({
error: {
type: "validation_error",
code: "INVALID_TEXT",
message: "Request must contain either 'text' or 'url', not both",
details: {}
}
});
}
// Get the text content (either directly or from URL)
let textContent;
if (url) {
// Validate URL format
try {
new URL(url);
} catch (e) {
return res.status(400).json({
error: {
type: "validation_error",
code: "INVALID_URL",
message: "Invalid URL format",
details: {}
}
});
}
// Fetch text from URL
try {
const response = await fetch(url);
if (!response.ok) {
return res.status(400).json({
error: {
type: "validation_error",
code: "INVALID_URL",
message: `Failed to fetch URL: ${response.statusText}`,
details: {}
}
});
}
textContent = await response.text();
} catch (e) {
return res.status(400).json({
error: {
type: "validation_error",
code: "INVALID_URL",
message: `Failed to fetch URL: ${e.message}`,
details: {}
}
});
}
} else {
textContent = text;
}
// Check for empty text
if (!textContent || textContent.trim().length === 0) {
return res.status(400).json({
error: {
type: "validation_error",
code: "EMPTY_TEXT",
message: "Text content cannot be empty",
details: {}
}
});
}
// Extract query parameters for intelligence features
const { language, summarize, topics, sentiment, intents } = req.query;
// Build Deepgram options
const options = {
language: language || 'en'
};
// Handle summarize parameter (boolean or string)
if (summarize === 'true' || summarize === true) {
options.summarize = true;
} else if (summarize === 'v2') {
options.summarize = summarize;
} else if (summarize === 'v1') {
// v1 is no longer supported
return res.status(400).json({
error: {
type: "validation_error",
code: "INVALID_TEXT",
message: "Summarization v1 is no longer supported. Please use v2 or true.",
details: {}
}
});
}
// Handle topics parameter
if (topics === 'true' || topics === true) {
options.topics = true;
}
// Handle sentiment parameter
if (sentiment === 'true' || sentiment === true) {
options.sentiment = true;
}
// Handle intents parameter
if (intents === 'true' || intents === true) {
options.intents = true;
}
// Call Deepgram API (SDK v4 returns { result, error })
const { result, error } = await deepgram.read.analyzeText({ text: textContent }, options);
// Handle SDK errors
if (error) {
console.error('Deepgram API Error:', error);
return res.status(400).json({
error: {
type: "processing_error",
code: "INVALID_TEXT",
message: error.message || 'Failed to process text',
details: {}
}
});
}
// Return full results object (includes all requested features)
res.json({
results: result.results || {}
});
} catch (err) {
console.error('Text Intelligence Error:', err);
// Determine appropriate error code
let errorCode = "INVALID_TEXT";
let statusCode = 500;
if (err.message && err.message.includes('text')) {
errorCode = "INVALID_TEXT";
statusCode = 400;
} else if (err.message && err.message.includes('too long')) {
errorCode = "TEXT_TOO_LONG";
statusCode = 400;
}
res.status(statusCode).json({
error: {
type: "processing_error",
code: errorCode,
message: err.message || "Text processing failed",
details: {}
}
});
}
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok', service: 'text-intelligence' });
});
// Metadata endpoint (required for standardization)
app.get('/api/metadata', (req, res) => {
try {
const tomlPath = path.join(__dirname, 'deepgram.toml');
const tomlContent = fs.readFileSync(tomlPath, 'utf-8');
const config = toml.parse(tomlContent);
if (!config.meta) {
return res.status(500).json({
error: 'INTERNAL_SERVER_ERROR',
message: 'Missing [meta] section in deepgram.toml'
});
}
res.json(config.meta);
} catch (error) {
console.error('Error reading metadata:', error);
res.status(500).json({
error: 'INTERNAL_SERVER_ERROR',
message: 'Failed to read metadata from deepgram.toml'
});
}
});
// ============================================================================
// SERVER START
// ============================================================================
app.listen(CONFIG.port, CONFIG.host, () => {
console.log("\n" + "=".repeat(70));
console.log(`🚀 Backend API running at http://localhost:${CONFIG.port}`);
console.log(`📡 GET /api/session`);
console.log(`📡 POST /api/text-intelligence (auth required)`);
console.log(`📡 GET /api/metadata`);
console.log("=".repeat(70) + "\n");
});