-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
196 lines (167 loc) · 6.45 KB
/
Copy pathindex.ts
File metadata and controls
196 lines (167 loc) · 6.45 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
import http from 'http';
import z from 'zod';
import { config } from '../config';
import { getWsInfo } from '../helpers/get-ws-info';
import { logger } from '../logger';
import { healthRouteHandler } from './healthz';
import {
buildCsp,
getRequestPathname,
hasPrefixPathSegment,
type HttpRouteHandler
} from './helpers';
import { infoRouteHandler } from './info';
import { interfaceRouteHandler } from './interface';
import { loginRouteHandler } from './login';
import { login2faRouteHandler } from './login-2fa';
import { logoutRouteHandler } from './logout';
import { publicRouteHandler } from './public';
import { uploadFileRouteHandler } from './upload';
import { HttpValidationError } from './utils';
type RouteContext = {
info: ReturnType<typeof getWsInfo>;
};
type SupportedMethod = 'GET' | 'POST';
const routeHandlers: Partial<
Record<
SupportedMethod,
{
exact: Record<string, HttpRouteHandler<RouteContext>>;
prefix: Record<string, HttpRouteHandler<RouteContext>>;
}
>
> = {
GET: {
exact: {
'/healthz': (req, res) => healthRouteHandler(req, res),
'/info': (req, res) => infoRouteHandler(req, res)
},
prefix: {
'/public': (req, res) => publicRouteHandler(req, res)
}
},
POST: {
exact: {
'/upload': (req, res) => uploadFileRouteHandler(req, res),
'/login': (req, res) => loginRouteHandler(req, res),
'/login/2fa': (req, res) => login2faRouteHandler(req, res),
'/logout': (req, res) => logoutRouteHandler(req, res)
},
prefix: {}
}
};
// this http server implementation is temporary and will be moved to a more capable framework later
const createHttpServer = async (port: number = config.server.port) => {
return new Promise<http.Server>((resolve) => {
const server = http.createServer(
async (req: http.IncomingMessage, res: http.ServerResponse) => {
const host = req.headers.host;
// Security headers. caesar is same-origin only (client + API behind
// the same Caddy host), so no CORS allow-* is needed. Dropping
// them reduces attack surface for cross-origin probes.
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains'
);
res.setHeader('Content-Security-Policy', buildCsp());
// Restrict powerful features. caesar uses mic + cam + screen
// capture; everything else is explicitly denied so nested iframes
// (e.g. the youtube embed) can't request them.
res.setHeader(
'Permissions-Policy',
'camera=(self), microphone=(self), display-capture=(self), geolocation=(), payment=(), usb=(), midi=()'
);
// Process isolation + resource scope. COOP isolates the browsing
// context from cross-origin openers; CORP prevents other origins
// from loading caesar resources via <img>/<script>/etc.
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
// Redirect HTTP to HTTPS when behind a reverse proxy
const forwardedProto = req.headers['x-forwarded-proto'];
if (forwardedProto === 'http' && host) {
res.writeHead(301, { Location: `https://${host}${req.url}` });
res.end();
return;
}
const info = getWsInfo(undefined, req);
logger.debug(`[HTTP] ${req.method} ${req.url} - ${info?.ip}`);
if (req.method === 'OPTIONS') {
res.writeHead(204);
res.end();
return;
}
const pathname = getRequestPathname(req);
if (!pathname) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Bad request' }));
return;
}
try {
const method = req.method as SupportedMethod | undefined;
if (method) {
const methodHandlers = routeHandlers[method];
if (methodHandlers) {
const exactHandler = methodHandlers.exact[pathname];
if (exactHandler) {
return await exactHandler(req, res, { info });
}
for (const [prefix, prefixHandler] of Object.entries(
methodHandlers.prefix
)) {
if (hasPrefixPathSegment(pathname, prefix)) {
return await prefixHandler(req, res, { info });
}
}
}
}
// fallback to interface route handler for GET requests
if (method === 'GET') {
return await interfaceRouteHandler(req, res);
}
} catch (error) {
const errorsMap: Record<string, string> = {};
if (error instanceof z.ZodError) {
for (const issue of error.issues) {
const field = issue.path[0];
if (typeof field === 'string') {
errorsMap[field] = issue.message;
}
}
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ errors: errorsMap }));
return;
} else if (error instanceof HttpValidationError) {
errorsMap[error.field] = error.message;
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ errors: errorsMap }));
return;
}
logger.error('HTTP route error:', error);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Internal server error' }));
return;
}
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
}
);
server.on('listening', () => {
logger.debug('HTTP server is listening on port %d', port);
resolve(server);
});
server.on('close', () => {
logger.debug('HTTP server closed');
// Under vitest, the worker reuses one server across test files; the
// server may close during teardown/restart cycles. Exiting on close
// there kills the worker mid-suite and aborts remaining files.
if (process.env.NODE_ENV !== 'test') {
process.exit(0);
}
});
server.listen(port);
});
};
export { createHttpServer };