http-middleware.js
5.78 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
"use strict";
var HttpMiddleware = module.exports;
var servernameRe = /^[a-z0-9\.\-]+$/i;
var challengePrefix = "/.well-known/acme-challenge/";
HttpMiddleware.create = function(gl, defaultApp) {
if (defaultApp && "function" !== typeof defaultApp) {
throw new Error("use greenlock.httpMiddleware() or greenlock.httpMiddleware(function (req, res) {})");
}
return function(req, res, next) {
var hostname = HttpMiddleware.sanitizeHostname(req);
req.on("error", function(err) {
explainError(gl, err, "http_01_middleware_socket", hostname);
});
// Skip unless the path begins with /.well-known/acme-challenge/
if (!hostname || 0 !== req.url.indexOf(challengePrefix)) {
skipChallenge(req, res, next, defaultApp);
return;
}
// HEADERS SENT DEBUG NOTE #2
// at this point, it's most likely Let's Encrypt server
// (or greenlock itself) performing the verification process
// Hmmm... perhaps we should change the greenlock prefix to test
// Anyway, we just got fast the first place where we could
// be sending headers.
var token = req.url.slice(challengePrefix.length);
var done = false;
var countA = 0;
var countB = 0;
gl.getAcmeHttp01ChallengeResponse({ type: "http-01", servername: hostname, token: token })
.catch(function(err) {
countA += 1;
// HEADERS SENT DEBUG NOTE #3
// This is the second possible time we could be sending headers
respondToError(gl, res, err, "http_01_middleware_challenge_response", hostname);
done = true;
return { __done: true };
})
.then(function(result) {
countB += 1;
if (result && result.__done) {
return;
}
if (done) {
console.error("Sanity check fail: `done` is in a quantum state of both true and false... huh?");
return;
}
// HEADERS SENT DEBUG NOTE #4b
// This is the third/fourth possible time send headers
return respondWithGrace(res, result, hostname, token);
})
.catch(function(err) {
// HEADERS SENT DEBUG NOTE #5
// I really don't see how this can be possible.
// Every case appears to be accounted for
console.error();
console.error("[warning] Developer Error:" + (err.code || err.context || ""), countA, countB);
console.error(err.stack);
console.error();
console.error(
"This is probably the error that happens routinely on http2 connections, but we're not sure why."
);
console.error("To track the status or help contribute,");
console.error("visit: https://git.rootprojects.org/root/greenlock-express.js/issues/9");
console.error();
try {
res.end("Internal Server Error [1003]: See logs for details.");
} catch (e) {
// ignore
}
});
};
};
function skipChallenge(req, res, next, defaultApp) {
if ("function" === typeof defaultApp) {
defaultApp(req, res, next);
} else if ("function" === typeof next) {
next();
} else {
res.statusCode = 500;
res.end("[500] Developer Error: app.use('/', greenlock.httpMiddleware()) or greenlock.httpMiddleware(app)");
}
}
function respondWithGrace(res, result, hostname, token) {
var keyAuth = result && result.keyAuthorization;
// HEADERS SENT DEBUG NOTE #4b
// This is (still) the third/fourth possible time we could be sending headers
if (keyAuth && "string" === typeof keyAuth) {
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end(keyAuth);
return;
}
res.statusCode = 404;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(JSON.stringify({ error: { message: "domain '" + hostname + "' has no token '" + token + "'." } }));
}
function explainError(gl, err, ctx, hostname) {
if (!err.servername) {
err.servername = hostname;
}
if (!err.context) {
err.context = ctx;
}
// leaving this in the build for now because it will help with existing error reports
console.error("[warning] network connection error:", (err.context || "") + " " + err.message);
(gl.notify || gl._notify)("error", err);
return err;
}
function respondToError(gl, res, err, ctx, hostname) {
// HEADERS SENT DEBUG NOTE #3b
// This is (still) the second possible time we could be sending headers
err = explainError(gl, err, ctx, hostname);
res.statusCode = 500;
res.end("Internal Server Error [1004]: See logs for details.");
}
HttpMiddleware.getHostname = function(req) {
return req.hostname || req.headers["x-forwarded-host"] || (req.headers.host || "");
};
HttpMiddleware.sanitizeHostname = function(req) {
// we can trust XFH because spoofing causes no ham in this limited use-case scenario
// (and only telebit would be legitimately setting XFH)
var servername = HttpMiddleware.getHostname(req)
.toLowerCase()
.replace(/:.*/, "");
try {
req.hostname = servername;
} catch (e) {
// read-only express property
}
if (req.headers["x-forwarded-host"]) {
req.headers["x-forwarded-host"] = servername;
}
try {
req.headers.host = servername;
} catch (e) {
// TODO is this a possible error?
}
return (servernameRe.test(servername) && -1 === servername.indexOf("..") && servername) || "";
};