-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathacme.js
More file actions
228 lines (191 loc) · 7.57 KB
/
acme.js
File metadata and controls
228 lines (191 loc) · 7.57 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
import { readdirSync, readFileSync, writeFileSync, existsSync } from 'fs';
import { readdir, readFile } from 'fs/promises';
import { createServer as createServerHttp, IncomingMessage, ServerResponse } from 'http';
import { join, resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import { hostname } from 'os';
import config from './config.json' with {
type: "json"
};
import packageJson from './package.json' with {
type: "json"
};
import Greenlock from "greenlock";
import http01Lib from "acme-http-01-standalone";
const http01 = http01Lib.create({});
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
if (hostname() == "devserv.ht-dev.de") {
config.acme.staging = true;
config.acme.email = "noreply@ht-dev.de";
config.acme.domains = config.acme.domains.filter(domains => domains[0] !== "example.com");
if (config.acme.domains.length == 0) {
config.acme.domains = [["devserv.ht-dev.de"]];
}
config.acme.agreeToTerms = true;
}
export function runCertbot() {
const greenlock = Greenlock.create({
staging: config.acme.staging,
packageAgent: packageJson.name + '/' + packageJson.version,
packageRoot: __dirname,
configDir: config.acme.configDir,
maintainerEmail: config.acme.email,
notify: function (event, details) {
if ('error' === event) {
console.error(details);
} else if ('success' === event) {
console.log('Certificate issued successfully for', details.subject);
console.log('Certificate details:', details);
}
},
challenges: {
// 'http-01': getChallenges()
'http-01': {
module: join(__dirname, 'acme.js')
}
}
});
greenlock.manager.defaults({
agreeToTerms: config.acme.agreeToTerms,
subscriberEmail: config.acme.email
});
config.acme.domains.forEach(domains => {
console.log(`Processing domain: ${domains[0]}`);
if (domains[0] == "example.com") {
console.warn("Skipping example.com domain");
return;
} else if(domains[0] == "devserv.ht-dev.de" && hostname() != "devserv.ht-dev.de") {
// this is the development server and should never appear on anyones configuration
throw new Error("Invalid Configuration!");
} else if(domains[0] == "localhost") {
console.warn("Skipping localhost domain");
return;
}
greenlock.add({
subject: domains[0],
altnames: domains,
})
});
// const subject = config.acme.domains[0][0];
// greenlock
// .get({ servername: subject })
// .then(function (pems) {
// if (pems && pems.privkey && pems.cert && pems.chain) {
// console.info('Certificate issued successfully');
// console.log('Private Key:', pems.privkey);
// console.log('Certificate:', pems.cert);
// console.log('Chain:', pems.chain);
// // Store the certificates
// const certDir = join(config.acme.configDir, 'certs', subject);
// if (!existsSync(certDir)) {
// mkdirSync(certDir, { recursive: true });
// }
// writeFileSync(join(certDir, 'privkey.pem'), pems.privkey);
// writeFileSync(join(certDir, 'cert.pem'), pems.cert);
// writeFileSync(join(certDir, 'chain.pem'), pems.chain);
// }
// })
// .catch(function (e) {
// console.error('Error during certificate issuance:', e.code);
// console.error(e);
// });
return greenlock.renew({}).then(function(results) {
results.forEach(function(site) {
if (site.error) {
console.error(site.subject, site.error);
return;
}
console.log('Renewed certificate for', site.subject, site.altnames);
});
});
}
// if (config.acme.enabled) {
// runCertbot();
// }
// Run when file is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
runCertbot();
}
const challengeFile = join(config.acme.configDir, 'challenges.json');
/**
* Handle ACME challenge requests
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @return {boolean} True if the request was handled
*/
export function handleChallenge(req, res) {
const method = req.method;
const url = req.url;
const challenges = JSON.parse(readFileSync(challengeFile, 'utf8'));
console.log('Handle challenge', method, url);
const host = req.headers.host;
const challenge = host + url.replace("/.well-known/acme-challenge/", '#');
console.log("User-Agent", req.headers['user-agent']);
const isValidUserAgent = [`${packageJson.name}/${packageJson.version}`, "Let's Encrypt validation server"].some(ua => {
return req.headers['user-agent'].includes(ua);
});
console.debug("Valid User-Agent", isValidUserAgent);
if (!isValidUserAgent) {
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Forbidden' }));
return false;
}
if (challenges[challenge]) {
res.writeHead(200, { 'Content-Type': 'application/json' });
console.log('Challenge', challenge, challenges[challenge]);
res.end(challenges[challenge]);
console.log('Challenge sent');
// res.end(JSON.stringify({ keyAuthorization: challenges[challenge] }));
return true;
}
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
return false;
}
export function create() {
return {
init: function (opts) {
console.log('Init', opts);
if (!existsSync(challengeFile)) {
writeFileSync(challengeFile, '{}');
}
// request = opts.request;
return Promise.resolve(null);
},
set: function (data) {
return Promise.resolve().then(function () {
console.log('Add Key Auth URL', data);
const challenges = JSON.parse(readFileSync(challengeFile, 'utf8'));
const ch = data.challenge;
const key = ch.identifier.value + '#' + ch.token;
challenges[key] = ch.keyAuthorization;
writeFileSync(challengeFile, JSON.stringify(challenges, null, 3));
return null;
});
},
get: function (data) {
return Promise.resolve().then(function () {
console.log('List Key Auth URL', data);
const challenges = JSON.parse(readFileSync(challengeFile, 'utf8'));
const ch = data.challenge;
const key = ch.identifier.value + '#' + ch.token;
if (challenges[key]) {
return { keyAuthorization: challenges[key] };
}
return null;
});
},
remove: function (data) {
return Promise.resolve().then(function () {
console.log('Remove Key Auth URL', data);
const challenges = JSON.parse(readFileSync(challengeFile, 'utf8'));
const ch = data.challenge;
const key = ch.identifier.value + '#' + ch.token;
delete challenges[key];
writeFileSync(challengeFile, JSON.stringify(challenges, null, 3));
return null;
});
}
}
}