-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckpoint401.ts
554 lines (498 loc) · 22.2 KB
/
checkpoint401.ts
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
import {DB} from "https://deno.land/x/[email protected]/mod.ts";
const VERSION: number = 4;
/*
to run:
deno run --allow-net --allow-read --allow-write checkpoint401.ts --db-filename my_database.db
to compile:
deno compile checkpoint401.ts
to run:
./checkpoint401
Optional Arguments:
The provided code supports command-line arguments for configuration. You can pass these arguments when running the binary:
--config-dir <config-dir>: Path to the directory containing configuration files (default: .)
--db-filename <database_path>: Path to the SQLite database file (default: route_stats_counters.db)
--update-period <update_period_in_milliseconds>: Period in milliseconds to update the database and write counters to disk (default: 10000)
--disable-stats: Disable the stats feature
--header-name-uri <header_name>: Name of the header for URI (default: X-Forwarded-Uri)
--header-name-method <header_name>: Name of the header for method (default: X-Forwarded-Method)
--version: Display server version
--help: Show help message
./checkpoint401 --dir custom_config --disable-stats
*/
type EndpointFunction = (req: Request, match: URLPatternResult | null) => Promise<{ success: boolean; errorMessage?: string; }>;
interface RouteItem {
method: string;
routeURLPattern: string;
routeEndpointTypeScriptFile: string;
passCount?: number;
failCount?: number;
}
class DatabaseManager {
private db: DB;
constructor(dbFilename: string) {
this.db = new DB(dbFilename);
}
async createTableIfNotExists() {
try {
this.db.query(`
CREATE TABLE IF NOT EXISTS route_stats_counters
(
method TEXT NOT NULL,
route TEXT NOT NULL,
passCount INTEGER NOT NULL DEFAULT 0,
failCount INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (method, route)
)
`);
console.log("Table route_stats_counters created or already exists.");
} catch (error) {
console.error("Error creating table:", error);
}
}
async insertInitialStats(routes: RouteItem[]) {
const insertStmt = `
INSERT OR IGNORE INTO route_stats_counters (method, route, passCount, failCount)
VALUES (?, ?, 0, 0)
`;
try {
for (const routeConfig of routes) {
this.db.query(insertStmt, [routeConfig.method, routeConfig.routeURLPattern]);
}
console.log("Initial stats inserted into database.");
} catch (error) {
console.error("Error inserting initial stats:", error);
}
}
async updateDatabase(routes: RouteItem[]) {
const updateStmt = `
UPDATE route_stats_counters
SET passCount = passCount + ?,
failCount = failCount + ?
WHERE method = ?
AND route = ?
`;
try {
for (const routeConfig of routes) {
this.db.query(updateStmt, [routeConfig.passCount, routeConfig.failCount, routeConfig.method, routeConfig.routeURLPattern]);
}
} catch (error) {
console.error("Error updating database:", error);
}
}
close() {
this.db.close();
}
}
async function loadAdditionalTsFiles(applicationOptions: ApplicationOptions): Promise<void> {
try {
const routesJson = await Deno.readTextFile(`${applicationOptions.currentWorkingDir}/routes.json`);
const routes = JSON.parse(routesJson);
const excludeFiles = new Set(routes.map((route: { file: string }) => route.file));
const directory = await Deno.readDir(applicationOptions.currentWorkingDir);
console.log(`Importing non-router TypeScript files from ${applicationOptions.currentWorkingDir}`);
let totalImported = 0;
for await (const dirEntry of directory) {
if (dirEntry.isFile && dirEntry.name.endsWith('.ts') && !excludeFiles.has(dirEntry.name)) {
try {
const filePath = `${applicationOptions.currentWorkingDir}/${dirEntry.name}`;
await import(filePath);
totalImported++
console.log(`File ${filePath} loaded successfully.`);
} catch (error) {
console.error(`Error importing non-router file '${dirEntry.name}': ${error.message}`);
}
}
}
if (totalImported === 0) {
console.log(`No non-router TypeScript files found in ${applicationOptions.currentWorkingDir}`);
}
} catch (error) {
console.error(`Error loading non-router TypeScript files: ${error}`);
Deno.exit(1);
}
}
async function setupRoutes(
applicationOptions: ApplicationOptions,
dbManager: DatabaseManager,
): Promise<URLPatternRouter> {
try {
const routesJson = await Deno.readTextFile(`${applicationOptions.currentWorkingDir}/routes.json`);
let routeItems: RouteItem[] = JSON.parse(routesJson);
routeItems = routeItems.map(route => ({
...route,
passCount: 0,
failCount: 0,
}));
const urlPatternRouter: URLPatternRouter = new URLPatternRouter(applicationOptions)
for (const routeConfig of routeItems) {
const filePath = `./config/${routeConfig.routeEndpointTypeScriptFile}`;
try {
console.log(`Importing ${filePath} .....`);
const endpointModule = await import(filePath);
if (!endpointModule.default) {
throw new Error(`The file '${filePath}' does not export a valid default handler.`);
}
const endpointFunctionProxy = createEndpointFunctionProxy(endpointModule.default, routeConfig, applicationOptions) as EndpointFunction;
console.log(routeConfig.method, routeConfig.routeURLPattern, endpointFunctionProxy);
urlPatternRouter.addRoute(routeConfig.method, routeConfig.routeURLPattern, endpointFunctionProxy);
console.log(`Route ${routeConfig.method} ${routeConfig.routeURLPattern} loaded successfully, endpoint is: ${filePath}`);
} catch (error) {
console.trace(`Error importing endpoint '${filePath}': ${error.message}`);
throw new Error(`Error importing endpoint '${filePath}': ${error.message}`);
}
}
if (!applicationOptions.disableStats) updateDatabasePeriodically(dbManager, routeItems, applicationOptions);
await dbManager.insertInitialStats(routeItems);
return urlPatternRouter;
} catch (error) {
console.error('Failed to set up routes:', error);
throw error;
}
}
async function updateDatabasePeriodically(
dbManager: DatabaseManager,
routes: RouteItem[],
applicationOptions: ApplicationOptions,
) {
const {updatePeriod} = applicationOptions;
if (!dbManager || !(dbManager instanceof DatabaseManager)) {
throw new Error('Invalid dbManager argument. It must be an instance of DatabaseManager.');
}
if (typeof updatePeriod !== 'number' || updatePeriod <= 0) {
throw new Error('Invalid updatePeriod argument. It must be a positive number.');
}
try {
await dbManager.updateDatabase(routes);
// Reset the counters
for (const route of routes) {
route.passCount = 0;
route.failCount = 0;
}
} catch (error) {
console.error('Error updating database:', error);
} finally {
// Schedule the next update after the current one has completed
setTimeout(() => updateDatabasePeriodically(dbManager, routes, applicationOptions), updatePeriod);
}
}
const makeResponse = (
statusCode: 401 | 200 | 404,
applicationOptions: ApplicationOptions,
request: Request,
URLPatternPathname: string | null,
errorMessage?: string,
): Response => {
if (applicationOptions.verbose) {
console.log(`[${new Date().toISOString()}] status: ${statusCode} method: ${request.method} pattern: ${URLPatternPathname} request.url: ${request.url}`);
}
const body = statusCode === 401 && errorMessage ? JSON.stringify({error: errorMessage}) : null;
return new Response(body, {status: statusCode});
}
interface routerInternalRoute {
pattern: URLPattern;
method: string;
endpointFunction: EndpointFunction,
}
function getInboundUriFromHeaders(request: Request, headerNameUri: string): string {
try {
const xForwardedUri = request.headers.get(headerNameUri);
if (xForwardedUri === null) {
throw new Error(`AUTH: ${headerNameUri} not found in headers`);
}
return xForwardedUri;
} catch (error) {
throw error;
}
}
function getInboundMethodFromHeaders(request: Request, headerNameMethod: string): string {
try {
const xForwardedMethod = request.headers.get(headerNameMethod);
if (xForwardedMethod === null) {
throw new Error(`AUTH: ${headerNameMethod} not found in headers`);
}
return xForwardedMethod;
} catch (error) {
throw error;
}
}
class URLPatternRouter {
private routerInternalRoute: routerInternalRoute[] = [];
private applicationOptions: ApplicationOptions;
constructor(applicationOptions: ApplicationOptions) {
this.applicationOptions = applicationOptions;
}
addRoute(
method: string,
routeURLPattern: string,
endpointFunction: EndpointFunction,
) {
this.routerInternalRoute.push(
{pattern: new URLPattern({pathname: routeURLPattern}), method, endpointFunction}
);
}
async handleRequest(request: Request) {
try {
for (const routerInternalRoute of this.routerInternalRoute) {
// this MEANT to be http://www.example.org yes even for your application
// it is a dummy base URL, as we are only interested in the pathname
const dummyBaseURL = "http://www.example.org"
const found = routerInternalRoute.pattern.test(request.url, dummyBaseURL);
const match = routerInternalRoute.pattern.exec(request.url, dummyBaseURL);
if (request.method === routerInternalRoute.method && found) {
const result: { success: boolean; errorMessage?: string; } = await routerInternalRoute.endpointFunction(request, match);
if (result.success) {
return makeResponse(200, this.applicationOptions, request, routerInternalRoute.pattern.pathname);
} else {
return makeResponse(401, this.applicationOptions, request, routerInternalRoute.pattern.pathname, result.errorMessage);
}
}
}
return makeResponse(404, this.applicationOptions, request, null);
} catch (error) {
console.error('Error handling request:', error);
return makeResponse(401, this.applicationOptions, request, null);
}
}
}
// this wraps the endpoints and ensures only boolean is returned
function createEndpointFunctionProxy(fn: Function, routeConfig: RouteItem, applicationOptions: ApplicationOptions): EndpointFunction {
return new Proxy(fn, {
async apply(target, thisArg, argumentsList) {
try {
const result = await target(...argumentsList);
if (typeof result !== "object" || typeof result.success !== "boolean" || (result.errorMessage && typeof result.errorMessage !== "string")) {
routeConfig.failCount = (routeConfig.failCount || 0) + 1; // Increment fail count
throw new Error(`[${new Date().toISOString()}] YOUR TYPESCRIPT ENDPOINT FUNCTION DID NOT RETURN AN OBJECT WITH A BOOLEAN 'success' PROPERTY AND AN OPTIONAL 'errorMessage' STRING PROPERTY! Method: ${routeConfig.method}, Route: ${routeConfig.routeURLPattern}, Function: ${routeConfig.routeURLPattern}`);
}
// Update the stats
result.success ? (routeConfig.passCount = (routeConfig.passCount || 0) + 1) : (routeConfig.failCount = (routeConfig.failCount || 0) + 1);
return result;
} catch (error) {
console.error(error);
return {success: false, errorMessage: "Unknown auth error"};
}
},
}) as EndpointFunction;
}
function displayHelp() {
console.log(`
Server usage:
server --config-dir <config_directory> [--db-filename <database_path>] [--update-period <update_period_in_milliseconds>] [--disable-stats] [--version] [--help] [--port <port_number>] [--listen-address <listen_address>] [--header-name-uri <header_name>] [--header-name-method <header_name>]
--config-dir: Path to the directory containing configuration files (default: .)
--db-filename: Path to the SQLite database file (default: route_stats_counters.db)
--update-period: Period in milliseconds to update the database and write counters to disk (default: 10000)
--disable-stats: Disable the stats feature
--verbose: Enable verbose logging
--version: Display server version
--help: Show help message
--port: Port number to listen on (default: 3000 or PORT environment variable). If both are set, the server will exit with an error.
--listen-address: Address to listen on (default: 0.0.0.0 or LISTEN_ADDRESS environment variable). If both are set, the server will exit with an error.
--header-name-uri: Name of the header for URI (default: X-Forwarded-Uri)
--header-name-method: Name of the header for method (default: X-Forwarded-Method)
**Configuration Files:**
- routes.json: This file defines the routes for the server. It should be a JSON array with each object containing the following properties:
- method: HTTP method (GET, POST, etc.)
- route: The route path for the request
- file: The filename of the TypeScript endpoint handler located in the "endpoints" directory
- auth/<function_name>.ts: These files define the authentication logic. Each file should export a default function that takes a Request object as input and returns a Promise that resolves to true if the request is authorized, false otherwise.
- endpoints/<file_name>.ts: These files define the endpoint handlers for specific routes. Each file should export a default function that takes a Request object as input and returns a Response object or a value that will be converted to a Response.
`);
}
interface ApplicationOptions {
currentWorkingDir: string;
dbFilename: string;
disableStats: boolean;
hostname: string;
port: number;
updatePeriod: number;
verbose: boolean;
headerNameUri: string;
headerNameMethod: string;
}
function printApplicationOptions(options: ApplicationOptions) {
console.log(`currentWorkingDir: ${options.currentWorkingDir}`);
console.log(`dbFilename: ${options.dbFilename}`);
console.log(`disableStats: ${options.disableStats}`);
console.log(`hostname: ${options.hostname}`);
console.log(`port: ${options.port}`);
console.log(`updatePeriod: ${options.updatePeriod}`);
console.log(`verbose: ${options.verbose}`);
console.log(`headerNameUri: ${options.headerNameUri}`);
console.log(`headerNameMethod: ${options.headerNameMethod}`);
}
function parseArgs(args: string[]): ApplicationOptions {
const applicationOptions: ApplicationOptions = {
dbFilename: "route_stats_counters.db",
currentWorkingDir: Deno.cwd(),
disableStats: false,
hostname: `127.0.0.1`,
port: 3000,
updatePeriod: 10000,
verbose: true,
headerNameUri: "X-Forwarded-Uri",
headerNameMethod: "X-Forwarded-Method",
};
function validatePort(port: string): number {
const parsedPort = Number(port);
if (isNaN(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
console.error("Error: --port option requires a valid port number between 1 and 65535.");
Deno.exit(1);
}
return parsedPort;
}
function validateUpdatePeriod(period: string): number {
const parsedPeriod = Number(period);
if (isNaN(parsedPeriod) || parsedPeriod < 1000) {
console.error("Error: --update-period option requires a number greater than or equal to 1000.");
Deno.exit(1);
}
return parsedPeriod;
}
for (let i = 0; i < args.length; i++) {
const arg = args[i];
switch (arg) {
case "--version":
printVersion()
Deno.exit(0);
break;
case "--verbose":
applicationOptions.verbose = true;
break;
case "--db-filename":
if (i + 1 < args.length) {
applicationOptions.dbFilename = args[i + 1];
i++;
} else {
console.error("Error: --db-filename option requires a database filename.");
Deno.exit(1);
}
break;
case "--update-period":
if (i + 1 < args.length) {
applicationOptions.updatePeriod = validateUpdatePeriod(args[i + 1]);
i++;
} else {
console.error("Error: --update-period option requires a number.");
Deno.exit(1);
}
break;
case "--disable-stats":
applicationOptions.disableStats = true;
break;
case "--port":
if (i + 1 < args.length) {
applicationOptions.port = validatePort(args[i + 1]);
i++;
} else {
console.error("Error: --port option requires a number.");
Deno.exit(1);
}
break;
case "--listen-address":
if (i + 1 < args.length) {
applicationOptions.hostname = args[i + 1];
i++;
} else {
console.error("Error: --listen-address option requires an address.");
Deno.exit(1);
}
break;
case "--header-name-uri":
if (i + 1 < args.length) {
applicationOptions.headerNameUri = args[i + 1];
i++;
} else {
console.error("Error: --header-name-uri option requires a header name.");
Deno.exit(1);
}
break;
case "--header-name-method":
if (i + 1 < args.length) {
applicationOptions.headerNameMethod = args[i + 1];
i++;
} else {
console.error("Error: --header-name-method option requires a header name.");
Deno.exit(1);
}
break;
case "--help":
displayHelp();
Deno.exit(0);
break;
default:
console.error(`Unknown argument: ${arg}`);
Deno.exit(1);
}
}
// Check if both command-line argument and environment variable are set for port
const envPort = Deno.env.get("PORT");
if (applicationOptions.port !== 3000 && envPort) {
console.error("Error: Both command-line argument and environment variable are set for port.");
Deno.exit(1);
}
// Check if both command-line argument and environment variable are set for listen address
const envhostname = Deno.env.get("LISTEN_ADDRESS");
if (applicationOptions.hostname !== "127.0.0.1" && envhostname) {
console.error("Error: Both command-line argument and environment variable are set for listen address.");
Deno.exit(1);
}
// If only environment variables are set, apply them
if (!args.includes("--port") && envPort) {
applicationOptions.port = validatePort(envPort);
}
if (!args.includes("--listen-address") && envhostname) {
applicationOptions.hostname = envhostname;
}
return applicationOptions;
}
function printVersion() {
console.log(`checkpoint401 version ${VERSION}`);
}
function patchMethodAndUriIntoRequest(request: Request, applicationOptions: ApplicationOptions): Request {
// This function is a workaround to patch the method and URL into the request object
// because the web server sends us the method and url in headers
try {
const method = getInboundMethodFromHeaders(request, applicationOptions.headerNameMethod);
const url = getInboundUriFromHeaders(request, applicationOptions.headerNameUri);
const handler = {
get: function(target: Request, prop: string) {
if (prop === 'method') {
return method;
}
if (prop === 'url') {
return url;
}
return (target as any)[prop];
}
};
return new Proxy(request, handler);
} catch (error) {
throw new Error(`Error modifying request: ${error.message}`);
}
}
async function runServer(): Promise<void> {
try {
printVersion()
const args = Deno.args;
const applicationOptions: ApplicationOptions = parseArgs(args);
printApplicationOptions(applicationOptions);
const dbManager = new DatabaseManager(applicationOptions.dbFilename);
await dbManager.createTableIfNotExists();
const router = await setupRoutes(applicationOptions, dbManager);
await loadAdditionalTsFiles(applicationOptions);
const shutdown = () => {
dbManager.close();
Deno.exit();
}
Deno.addSignalListener("SIGTERM", shutdown);
Deno.addSignalListener("SIGINT", shutdown);
Deno.serve(
{hostname: applicationOptions.hostname, port: applicationOptions.port},
(req) => router.handleRequest(patchMethodAndUriIntoRequest(req, applicationOptions))
);
} catch (error) {
console.error("Server startup failed:", error.message);
Deno.exit(1);
}
}
runServer();