-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.ts
More file actions
638 lines (543 loc) · 18.9 KB
/
server.ts
File metadata and controls
638 lines (543 loc) · 18.9 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
import "dotenv-flow/config";
import "./logs-setup"; // Set up OpenTelemetry logs (traces/metrics via auto-instrumentation)
const isDevelopment = process.env.NODE_ENV === "development";
import { Hono } from "hono";
import { cors } from "hono/cors";
import { bodyLimit } from "hono/body-limit";
import { trimTrailingSlash } from "hono/trailing-slash";
import { HTTPException } from "hono/http-exception";
import { createServer } from "http";
import { swaggerUI } from "@hono/swagger-ui";
import { WebSocketManager } from "./websocket";
import { authMiddleware } from "./middleware/auth";
import { securityHeaders } from "./middleware/security";
import { rateLimit, cleanup as rateLimitCleanup } from "./middleware/rate-limit";
import { closeCache } from "./lib/cache";
import foldersCrudRouter from "./routes/folders/crud";
import foldersActionsRouter from "./routes/folders/actions";
import crudRouter from "./routes/notes/crud";
import actionsRouter from "./routes/notes/actions";
import trashRouter from "./routes/notes/trash";
import countsRouter from "./routes/notes/counts";
import usersRouter from "./routes/users/crud";
import filesRouter from "./routes/files/crud";
import codeRouter from "./routes/code/crud";
import publicNotesRouter from "./routes/public-notes/crud";
import { VERSION } from "./version";
import { logger, sanitizeHeaders } from "./lib/logger";
// Type for OpenAPI routers - using permissive any to avoid type conflicts with library internals
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type OpenAPIRouter = any;
const maxFileSize = process.env.MAX_FILE_SIZE_MB ? parseInt(process.env.MAX_FILE_SIZE_MB) : 50;
const maxBodySize = Math.ceil(maxFileSize * 1.35);
const app = new Hono();
// Strip trailing slashes from all requests (fixes Swagger UI issue)
app.use("*", trimTrailingSlash());
// Apply security headers
app.use("*", securityHeaders);
// Add request logging middleware
app.use("*", async (c, next) => {
const start = Date.now();
const method = c.req.method;
const path = new URL(c.req.url).pathname;
// Capture and sanitize headers before processing (tokens will be redacted)
const headers = sanitizeHeaders(c.req.raw.headers);
// Add connection IP as fallback when no proxy headers are present (local dev)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const socket = (c.req.raw as any).socket;
if (socket?.remoteAddress && !headers["x-forwarded-for"] && !headers["x-real-ip"]) {
headers["x-real-ip"] = socket.remoteAddress;
}
await next();
const duration = Date.now() - start;
const status = c.res.status;
// Skip logging for health check and monitoring endpoints
const skipLogging = ["/health", "/", "/websocket/status", "/docs", "/api/openapi.json"].includes(
path
);
// Skip logging for 404s (scanner noise)
const is404 = status === 404;
// Log HTTP request with structured logging (sent to Grafana in both dev and prod)
if (!skipLogging && !is404) {
const userId = c.get("userId");
logger.httpRequest(method, path, status, duration, userId, headers);
}
});
// User context tracking (placeholder for future observability)
app.use("*", async (c, next) => {
return next();
});
// HTTP API Rate Limiting Configuration
const httpRateLimitWindow = process.env.HTTP_RATE_LIMIT_WINDOW_MS
? parseInt(process.env.HTTP_RATE_LIMIT_WINDOW_MS)
: 15 * 60 * 1000; // 15 minutes
const httpRateLimitMax = process.env.HTTP_RATE_LIMIT_MAX_REQUESTS
? parseInt(process.env.HTTP_RATE_LIMIT_MAX_REQUESTS)
: 1000;
const fileRateLimitMax = process.env.HTTP_FILE_RATE_LIMIT_MAX
? parseInt(process.env.HTTP_FILE_RATE_LIMIT_MAX)
: process.env.NODE_ENV === "development"
? 1000
: 100;
logger.info("HTTP rate limiting configured", {
windowMinutes: httpRateLimitWindow / 1000 / 60,
maxRequests: httpRateLimitMax,
fileMaxRequests: fileRateLimitMax,
});
// Apply rate limiting
app.use(
"*",
rateLimit({
windowMs: httpRateLimitWindow,
max: httpRateLimitMax,
})
);
// Rate limiting for file uploads
app.use(
"/api/files/*",
rateLimit({
windowMs: httpRateLimitWindow,
max: fileRateLimitMax,
})
);
// Code execution rate limiting will be applied AFTER auth middleware
app.use(
"*",
bodyLimit({
maxSize: maxBodySize * 1024 * 1024,
onError: (c) => {
return c.json(
{
error: `Request body too large. Maximum file size is ${maxFileSize}MB`,
status: 413,
},
413
);
},
})
);
const corsOrigins = process.env.CORS_ORIGINS
? process.env.CORS_ORIGINS.split(",").map((origin) => origin.trim())
: [];
if (corsOrigins.length === 0) {
logger.warn("CORS_ORIGINS not configured - all cross-origin requests will be blocked", {
recommendation: "Set CORS_ORIGINS environment variable with your frontend URLs",
});
}
app.use(
"*",
cors({
origin: corsOrigins,
credentials: true,
allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowHeaders: ["Content-Type", "Authorization", "Cookie", "X-Client-ID", "X-Client-Secret"],
exposeHeaders: ["Set-Cookie", "X-Auth-Refresh-Required", "WWW-Authenticate"],
})
);
app.get("/", (c) => {
return c.json({
message: "Typelets API",
status: "healthy",
version: VERSION,
docs: "https://github.com/typelets/typelets-api",
});
});
app.get("/health", (c) => {
return c.json({
status: "healthy",
version: VERSION,
timestamp: new Date().toISOString(),
uptime: process.uptime(),
});
});
// OpenAPI documentation
app.get(
"/docs",
swaggerUI({
url: "/api/openapi.json",
persistAuthorization: true, // Save token in browser
})
);
// Serve OpenAPI spec
app.get("/api/openapi.json", (c) => {
// Get OpenAPI documents from routers
const usersDoc = (usersRouter as OpenAPIRouter).getOpenAPIDocument({
openapi: "3.0.0",
info: {
title: "Typelets API",
version: VERSION,
description:
"A secure, encrypted notes management API with folder organization and file attachments",
contact: {
name: "Typelets API",
url: "https://github.com/typelets/typelets-api",
},
},
servers: [
{
url: process.env.API_URL || "http://localhost:3000",
description: "API Server",
},
],
});
const countsDoc = (countsRouter as OpenAPIRouter).getOpenAPIDocument({});
const crudDoc = (crudRouter as OpenAPIRouter).getOpenAPIDocument({});
const actionsDoc = (actionsRouter as OpenAPIRouter).getOpenAPIDocument({});
const trashDoc = (trashRouter as OpenAPIRouter).getOpenAPIDocument({});
const filesDoc = (filesRouter as OpenAPIRouter).getOpenAPIDocument({});
const codeDoc = (codeRouter as OpenAPIRouter).getOpenAPIDocument({});
const foldersCrudDoc = (foldersCrudRouter as OpenAPIRouter).getOpenAPIDocument({});
const foldersActionsDoc = (foldersActionsRouter as OpenAPIRouter).getOpenAPIDocument({});
const publicNotesDoc = (publicNotesRouter as OpenAPIRouter).getOpenAPIDocument({});
// Merge paths from all routers into usersDoc
if (!usersDoc.paths) {
usersDoc.paths = {};
}
// Prefix users paths with /api/users
const prefixedUsersPaths: Record<string, unknown> = {};
Object.keys(usersDoc.paths).forEach((path) => {
prefixedUsersPaths[`/api/users${path}`] = usersDoc.paths[path];
});
usersDoc.paths = prefixedUsersPaths;
// Merge counts paths with /api/notes/counts prefix
if (countsDoc.paths) {
Object.keys(countsDoc.paths).forEach((path) => {
const fullPath =
path === "" || path === "/" ? "/api/notes/counts" : `/api/notes/counts${path}`;
usersDoc.paths[fullPath] = countsDoc.paths[path];
});
}
// Merge crud paths with /api/notes prefix
if (crudDoc.paths) {
Object.keys(crudDoc.paths).forEach((path) => {
const fullPath = path === "" || path === "/" ? "/api/notes" : `/api/notes${path}`;
usersDoc.paths[fullPath] = crudDoc.paths[path];
});
}
// Merge actions paths with /api/notes prefix
if (actionsDoc.paths) {
Object.keys(actionsDoc.paths).forEach((path) => {
const fullPath = path === "" || path === "/" ? "/api/notes" : `/api/notes${path}`;
usersDoc.paths[fullPath] = actionsDoc.paths[path];
});
}
// Merge trash paths with /api/notes prefix
if (trashDoc.paths) {
Object.keys(trashDoc.paths).forEach((path) => {
const fullPath = path === "" || path === "/" ? "/api/notes" : `/api/notes${path}`;
usersDoc.paths[fullPath] = trashDoc.paths[path];
});
}
// Merge files paths with /api prefix
if (filesDoc.paths) {
Object.keys(filesDoc.paths).forEach((path) => {
const fullPath = path === "" || path === "/" ? "/api" : `/api${path}`;
usersDoc.paths[fullPath] = filesDoc.paths[path];
});
}
// Merge code paths with /api/code prefix
if (codeDoc.paths) {
Object.keys(codeDoc.paths).forEach((path) => {
const fullPath = path === "" || path === "/" ? "/api/code" : `/api/code${path}`;
usersDoc.paths[fullPath] = codeDoc.paths[path];
});
}
// Merge folders crud paths with /api/folders prefix
if (foldersCrudDoc.paths) {
Object.keys(foldersCrudDoc.paths).forEach((path) => {
const fullPath = path === "" || path === "/" ? "/api/folders" : `/api/folders${path}`;
usersDoc.paths[fullPath] = foldersCrudDoc.paths[path];
});
}
// Merge folders actions paths with /api/folders prefix
if (foldersActionsDoc.paths) {
Object.keys(foldersActionsDoc.paths).forEach((path) => {
const fullPath = path === "" || path === "/" ? "/api/folders" : `/api/folders${path}`;
usersDoc.paths[fullPath] = foldersActionsDoc.paths[path];
});
}
// Merge public-notes paths with /api/public-notes prefix
if (publicNotesDoc.paths) {
Object.keys(publicNotesDoc.paths).forEach((path) => {
const fullPath = path === "" || path === "/" ? "/api/public-notes" : `/api/public-notes${path}`;
usersDoc.paths[fullPath] = publicNotesDoc.paths[path];
});
}
// Merge schemas from all routers
if (!usersDoc.components) {
usersDoc.components = {};
}
if (!usersDoc.components.schemas) {
usersDoc.components.schemas = {};
}
if (countsDoc.components?.schemas) {
Object.assign(usersDoc.components.schemas, countsDoc.components.schemas);
}
if (crudDoc.components?.schemas) {
Object.assign(usersDoc.components.schemas, crudDoc.components.schemas);
}
if (actionsDoc.components?.schemas) {
Object.assign(usersDoc.components.schemas, actionsDoc.components.schemas);
}
if (trashDoc.components?.schemas) {
Object.assign(usersDoc.components.schemas, trashDoc.components.schemas);
}
if (filesDoc.components?.schemas) {
Object.assign(usersDoc.components.schemas, filesDoc.components.schemas);
}
if (codeDoc.components?.schemas) {
Object.assign(usersDoc.components.schemas, codeDoc.components.schemas);
}
if (foldersCrudDoc.components?.schemas) {
Object.assign(usersDoc.components.schemas, foldersCrudDoc.components.schemas);
}
if (foldersActionsDoc.components?.schemas) {
Object.assign(usersDoc.components.schemas, foldersActionsDoc.components.schemas);
}
if (publicNotesDoc.components?.schemas) {
Object.assign(usersDoc.components.schemas, publicNotesDoc.components.schemas);
}
// Manually add securitySchemes to components
usersDoc.components.securitySchemes = {
Bearer: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT",
description: "Clerk authentication token",
},
};
return c.json(usersDoc);
});
app.get("/websocket/status", (c) => {
if (!wsManager) {
return c.json({ error: "WebSocket not initialized" }, 500);
}
return c.json({
websocket: "operational",
stats: wsManager.getConnectionStats(),
timestamp: new Date().toISOString(),
});
});
// Public endpoint for viewing public notes (NO AUTH REQUIRED)
// Must be registered BEFORE auth middleware
app.get("/api/public-notes/:slug", async (c) => {
const slug = c.req.param("slug");
// Skip if slug looks like "note" (to allow /api/public-notes/note/:noteId to use auth)
if (slug === "note") {
return c.notFound();
}
// Forward to the router handler
const response = await publicNotesRouter.fetch(
new Request(`http://localhost/${slug}`, {
method: "GET",
headers: c.req.raw.headers,
})
);
return response;
});
app.use("*", authMiddleware);
// Code Execution Rate Limiting Configuration - AFTER auth so users are properly identified
const codeRateLimitMax = process.env.CODE_EXEC_RATE_LIMIT_MAX
? parseInt(process.env.CODE_EXEC_RATE_LIMIT_MAX)
: process.env.NODE_ENV === "development"
? 100
: 50;
const codeRateLimitWindow = process.env.CODE_EXEC_RATE_WINDOW_MS
? parseInt(process.env.CODE_EXEC_RATE_WINDOW_MS)
: 15 * 60 * 1000; // 15 minutes
logger.info("Code execution rate limiting configured", {
windowMinutes: codeRateLimitWindow / 1000 / 60,
maxRequests: codeRateLimitMax,
});
app.use(
"/api/code/*",
rateLimit({
windowMs: codeRateLimitWindow,
max: codeRateLimitMax,
})
);
app.route("/api/users", usersRouter);
app.route("/api/folders", foldersCrudRouter);
app.route("/api/folders", foldersActionsRouter);
app.route("/api/notes/counts", countsRouter);
app.route("/api/notes", trashRouter); // Register trash router before crud to avoid /{id} catching /empty-trash
app.route("/api/notes", crudRouter);
app.route("/api/notes", actionsRouter);
app.route("/api/code", codeRouter);
app.route("/api", filesRouter);
app.route("/api/public-notes", publicNotesRouter);
app.onError((err, c) => {
// Generate unique error ID for tracking
const errorId = crypto.randomUUID();
// Get user context
const userId = c.get("userId") || "anonymous";
// Log full error details server-side only
logger.error(
"API Error",
{
errorId,
message: err.message,
url: c.req.url,
method: c.req.method,
userId,
stack: err.stack ?? "no stack trace",
},
err
);
// Error context logged above
if (err instanceof HTTPException) {
// Log usage limit errors for billing analytics
if (err.status === 402 && err.cause) {
const userId = c.get("userId") || "anonymous";
const cause = err.cause as {
code: string;
currentCount?: number;
limit?: number;
currentStorageMB?: number;
fileSizeMB?: number;
expectedTotalMB?: number;
limitGB?: number;
};
if (cause.code === "NOTE_LIMIT_EXCEEDED") {
logger.businessEvent("note_limit_exceeded", userId, {
currentCount: cause.currentCount ?? 0,
limit: cause.limit ?? 0,
});
} else if (cause.code === "STORAGE_LIMIT_EXCEEDED") {
logger.businessEvent("storage_limit_exceeded", userId, {
currentStorageMB: cause.currentStorageMB ?? 0,
fileSizeMB: cause.fileSizeMB ?? 0,
expectedTotalMB: cause.expectedTotalMB ?? 0,
limitGB: cause.limitGB ?? 0,
});
}
}
// Return sanitized error response
return c.json(
{
error: err.message,
status: err.status,
timestamp: new Date().toISOString(),
...(process.env.NODE_ENV === "development" && { errorId }),
},
err.status
);
}
// For non-HTTP exceptions, return generic error in production
const isProduction = process.env.NODE_ENV === "production";
return c.json(
{
error: isProduction ? "Internal Server Error" : err.message,
status: 500,
timestamp: new Date().toISOString(),
...(process.env.NODE_ENV === "development" && {
errorId,
stack: err.stack ?? "no stack trace",
}),
},
500
);
});
app.notFound((c) => {
return c.json(
{
error: "Not Found",
status: 404,
path: c.req.url,
method: c.req.method,
timestamp: new Date().toISOString(),
},
404
);
});
const port = Number(process.env.PORT) || 3000;
const freeStorageGB = process.env.FREE_TIER_STORAGE_GB
? parseFloat(process.env.FREE_TIER_STORAGE_GB)
: 1;
const freeNoteLimit = process.env.FREE_TIER_NOTE_LIMIT
? parseInt(process.env.FREE_TIER_NOTE_LIMIT)
: 1000;
logger.info("Typelets API server starting", {
version: VERSION,
port,
maxFileSize,
maxBodySize,
freeStorageGB,
freeNoteLimit,
corsOrigins: corsOrigins.join(","),
environment: process.env.NODE_ENV || "development",
});
console.log("🚀 Typelets API v" + VERSION + " started at:", new Date().toISOString());
console.log(`📡 Listening on port ${port}`);
console.log(`📁 Max file size: ${maxFileSize}MB (body limit: ${maxBodySize}MB)`);
console.log(`💰 Free tier limits: ${freeStorageGB}GB storage, ${freeNoteLimit} notes`);
console.log(`🌐 CORS origins:`, corsOrigins);
const httpServer = createServer((req, res) => {
let body = Buffer.alloc(0);
req.on("data", (chunk: Buffer) => {
body = Buffer.concat([body, chunk]);
});
req.on("end", async () => {
try {
const requestInit: RequestInit = {
method: req.method,
headers: req.headers as Record<string, string>,
};
if (body.length > 0) {
requestInit.body = new Uint8Array(body) as BodyInit;
}
const response = await app.fetch(new Request(`http://localhost${req.url}`, requestInit));
res.statusCode = response.status;
response.headers.forEach((value, key) => {
res.setHeader(key, value);
});
const buffer = await response.arrayBuffer();
res.end(Buffer.from(buffer));
} catch (err) {
logger.error(
"Request handling error",
{
error: err instanceof Error ? err.message : String(err),
},
err instanceof Error ? err : undefined
);
res.statusCode = 500;
res.end("Internal Server Error");
}
});
req.on("error", (err: Error) => {
logger.error("Request error", { error: err.message }, err);
res.statusCode = 500;
res.end("Internal Server Error");
});
});
const wsManager = new WebSocketManager(httpServer);
// Graceful shutdown handling
const shutdown = async (signal: string) => {
logger.info(`Received ${signal}, starting graceful shutdown`);
// Stop accepting new connections
httpServer.close(async () => {
logger.info("HTTP server closed");
// Cleanup rate limiter
rateLimitCleanup();
logger.info("Rate limiter cleanup completed");
// Close cache connection
await closeCache();
logger.info("Graceful shutdown completed");
process.exit(0);
});
// Force shutdown after 10 seconds
setTimeout(() => {
logger.error("Forced shutdown after timeout");
process.exit(1);
}, 10000);
};
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));
httpServer.listen(port, () => {
console.log(`🚀 Typelets API v${VERSION} with WebSocket started at:`, new Date().toISOString());
console.log(`📡 HTTP & WebSocket server listening on port ${port}`);
console.log(`📁 Max file size: ${maxFileSize}MB (body limit: ${maxBodySize}MB)`);
console.log(`💰 Free tier limits: ${freeStorageGB}GB storage, ${freeNoteLimit} notes`);
console.log(`🌐 CORS origins:`, corsOrigins);
});