summaryrefslogtreecommitdiff
path: root/src/api.js
blob: 4e1e6f8e0e60ac177527d44ca3bca96d4f1ab71f (plain) (blame)
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
const express = require("express"); // from npm registry
const mysql = require("mysql"); // from npm registry
const https = require("https"); // built-in
const api = express();

if (process.env.npm_package_config_port === undefined) {
    console.error("Please run this package with `npm start`");
    process.exit(1);
}



// config common to all routers:
api.locals = Object.assign({
    rate_limiting: new Set(), // XXX: or do we want routers to each have their own rate limiter?
}, api.locals);



/*******************************
    BEGIN MIDDLEWARES
********************************/

const checkRateLimiting = (req, res, next) => {
    if (req.app.locals.rate_limiting.has(req.ip)) {
        res.status(429).json({
            status: "error",
            error: "too many requests"
        });
    } else {
        next();
    }
    return;
};

const checkCaptcha = (req, res, next) => {
    const token = String(req.get("X-CAPTCHA-TOKEN") || "");

    if (!token.match(/^[a-zA-Z0-9-_]{20,800}$/)) {
        res.status(403).json({
            status: "error",
            error: "no token sent"
        });
        req.app.locals.rate_limiting.add(req.ip);
        setTimeout(() => req.app.locals.rate_limiting.delete(req.ip), 300000);
        return false;
    }

    https.get(`https://www.google.com/recaptcha/api/siteverify?secret=${process.env.npm_package_config_recaptcha_secret}&response=${token}`, re => {
        re.setEncoding("utf8");
        re.on("data", response => {
            const data = JSON.parse(response);
            if (!Reflect.has(data, "success") || data.success !== true) {
                if (Reflect.has(data, "error-codes")) {
                    const error_codes = data["error-codes"].toString();
                    if (error_codes !== "invalid-input-response") {
                        console.error("reCAPTCHA returned an error: %s", error_codes);
                    }
                }
                res.status(403).json({
                    status: "error",
                    error: "captcha validation failed"
                });
                req.app.locals.rate_limiting.add(req.ip);
                setTimeout(() => req.app.locals.rate_limiting.delete(req.ip), 300000);
                return false;
            }

            next(); // challenge passed, so process the request
        });
    }).on("error", error => {
        console.error(error);
        res.status(403).json({
            status: "error",
            error: "reCAPTCHA couldn't be reached"
        });
        console.warn("reCAPTCHA couldn't be reached");
        return false;
    })
};

/*******************************
    END MIDDLEWARES
********************************/



/*******************************
    BEGIN ROUTERS
********************************/

const global_router = express.Router(["caseSensitive", "strict"]);

const tmwa_router = new (require("./routers/tmwa"))({
    timezone: process.env.npm_package_config_timezone,
    name: process.env.npm_package_config_tmwa_name,
    url: process.env.npm_package_config_tmwa_url,
    db_pool: mysql.createPool({
        connectionLimit: 10,
        host           : process.env.npm_package_config_sql_host,
        user           : process.env.npm_package_config_sql_user,
        password       : process.env.npm_package_config_sql_password,
        database       : process.env.npm_package_config_sql_database
    }),
    db_tables: {
        register: process.env.npm_package_config_sql_table,
    },
}, api, checkCaptcha, checkRateLimiting);

global_router.use("/tmwa", tmwa_router);
api.use("/api", global_router);

/*******************************
    END ROUTERS
********************************/



// default endpoint:
api.use((req, res, next) => {
    res.status(404).json({
        status: "error",
        error: "unknown endpoint"
    });
});

api.set("trust proxy", "loopback"); // only allow localhost to communicate with the API
api.disable("x-powered-by"); // we don't need this header
api.listen(process.env.npm_package_config_port, () => console.info("Listening on port %d", process.env.npm_package_config_port));