forked from serverless-dns/serverless-dns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.js
399 lines (370 loc) · 11.5 KB
/
env.js
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
/**
* Instantiation of EnvManager class makes env values available through a
* common interface.
*
* EnvManager.get() or EnvManager.set() allow manipulation of `env` object.
* Environment variables of runtime (deno, node, worker)
*
* @license
* Copyright (c) 2021 RethinkDNS and its authors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* @typedef {"number" | "string" | "boolean" | "csv"} EnvTyp
* @typedef {string | number | boolean} EnvDefTyp
* @typedef {EnvDefTyp|Set<string>} EnvConcreteTyp
* @typedef {{type: EnvTyp, default: EnvDefTyp}} EnvDefs
*/
/**
* @type {Map<String, EnvDefs>} defaults
*/
const defaults = new Map(
Object.entries({
// the env stage (production or development) workers is running in
// development is always "local" (a laptop /a server, for example)
WORKER_ENV: {
type: "string",
default: "development",
},
// the env stage deno is running in
DENO_ENV: {
type: "string",
default: "development",
},
// the env stage fastly is running in
FASTLY_ENV: {
type: "string",
default: "development",
},
// the env stage nodejs is running in
NODE_ENV: {
type: "string",
default: "development",
},
// the cloud-platform code is deployed on (cloudflare, fly, deno-deploy, fastly)
CLOUD_PLATFORM: {
type: "string",
// also ref: EnvManager.mostLikelyCloudPlatform()
default: "local",
},
// timeout for proc running on fly machines
MACHINES_TIMEOUT_SEC: {
type: "number",
default: -1,
},
// download blocklist files to disk, if any, and quit
BLOCKLIST_DOWNLOAD_ONLY: {
type: "boolean",
default: false,
},
// path to tls (private) key
TLS_KEY_PATH: {
type: "string",
default: "test/data/tls/dns.rethinkdns.localhost.key",
},
// path to tls (public) cert chain
TLS_CRT_PATH: {
type: "string",
default: "test/data/tls/dns.rethinkdns.localhost.crt",
},
// indicate if tls termination is offload to an external process; for ex
// <appname>.fly.dev as primary access-point w fly.io edge terminating tls.
TLS_OFFLOAD: {
type: "boolean",
default: false,
},
// global log level (debug, info, warn, error)
LOG_LEVEL: {
type: "string",
default: "debug",
},
// set via secret, cloudflare account-id
CF_ACCOUNT_ID: {
type: "string",
default: "",
},
// set via secret, api-token with permissions for analytics and logpush
CF_API_TOKEN: {
type: "string",
default: "",
},
// set via secret, access-key with permissions to read logpush r2 bucket
CF_LOGPUSH_R2_ACCESS_KEY: {
type: "string",
default: "",
},
// set via secret, secret-key with permissions to read logpush r2 bucket
CF_LOGPUSH_R2_SECRET_KEY: {
type: "string",
default: "",
},
// r2 loc where logpush writes logs; ex: bucket-name/ or bucket-name/dir
CF_LOGPUSH_R2_PATH: {
type: "string",
default: "",
},
// url to blocklist files: trie (td), rank-dir (rd), metadata: (filetag)
CF_BLOCKLIST_URL: {
type: "string",
default: "https://cfstore.rethinkdns.com/blocklists/",
},
// primary doh upstream
CF_DNS_RESOLVER_URL: {
type: "string",
default: "https://cloudflare-dns.com/dns-query",
},
// secondary doh upstream
CF_DNS_RESOLVER_URL_2: {
type: "string",
default: "https://dns.google/dns-query",
},
// upstream recursive rethinkdns resolver running on Fly.io
MAX_DNS_RESOLVER_URL: {
type: "string",
// must always end with a trailing slash
default: "https://max.rethinkdns.com/",
},
// max doh request processing timeout some requests may have to wait
// for blocklists to download before being responded to.
WORKER_TIMEOUT: {
type: "number",
default: "10000", // 10s
},
// max blocklist files download timeout
CF_BLOCKLIST_DOWNLOAD_TIMEOUT: {
type: "number",
default: "7500", // 7.5s
},
// ttl for dns answers, overrides ttls in dns answers
CACHE_TTL: {
type: "number",
default: "1800", // 30m
},
// disable downloading blocklists altogether
DISABLE_BLOCKLISTS: {
type: "boolean",
default: false,
},
// courtesy db-ip.com/db/download/ip-to-country-lite
GEOIP_URL: {
type: "string",
default: "https://cfstore.rethinkdns.com/geoip/2022/1667349639157/",
},
// treat all blocklists as wildcards, this means
// if abc.xyz.com is in any blocklist, then
// <*>.abc.xyz.com will also get blocked
BLOCK_SUBDOMAINS: {
type: "boolean",
default: true,
},
// run in profiler mode
PROFILE_DNS_RESOLVES: {
type: "boolean",
default: false,
},
// serve dns only when given a msgsecret sent in the request uri,
// domain.tld|hash('msgsecret|domain.tld') equals ACCESS_KEY
// multiple keys separated by a comma make up ACCESS_KEYS
// Must be a hex string; see: auth-token.js
ACCESS_KEYS: {
type: "csv",
// for msg/key: 1123213213 and hostname: localhost
// v = localhost|77bd7ed4709cb09bb7d67545218e27cf39346f7b6c36f366d0631d5ee4739a3c
// For ex, DoH = 1:-J8AEH8Dv73_8______-___z6f9eagBA:1123213213
// DoT = 1-7cpqaed7ao73377t777777767777h2p7lzvaaqa-1123213213
// calc access-key, v = domain.tld|hex(hmac-sha256(key, msg))
// where msg = "sdns-public-auth-info"; key="1123213213|localhost"
// nb, ACCESS_KEY, v, must be hex and upto 64 chars in length
// while, 'msgsecret' must be a valid DNS name (alphanum + hyphen)
// ACCESS_KEY, v, could be shorter (12 to 24 to 32 to 64 chars)
// ACCESS_KEY, v, can be public (better if private / secret)
// default: "localhost|1e84b3c687,rethinkdns.localhost|c9de656fd9",
default: "", // no auth when empty
},
// avoid using the (slow) fetch polyfill if on nodejs
NODE_AVOID_FETCH: {
type: "boolean",
default: false,
},
// use only doh upstream on nodejs (udp/tcp is the default on nodejs)
NODE_DOH_ONLY: {
type: "boolean",
default: false,
},
// use hostname as log-id if log-id is not set in the request
LOGPUSH_HOSTNAME_AS_LOGID: {
type: "boolean",
default: false,
},
// cloudflare logpush: developers.cloudflare.com/workers/platform/logpush
LOGPUSH_SRC: {
type: "csv",
// ex: pro,one,log,local,localhost
// empty string means allow all hosts / sources
default: "",
},
// Return 'Gateway IPs' for ALL eligible reqs (ref util.js:isGatewayRequest)
GW_IP4: {
type: "string",
default: "",
},
GW_IP6: {
type: "string",
default: "",
},
})
);
/**
* cast string x to type typ
* @param {EnvDefTyp} x
* @param {EnvTyp} typ
* @returns {EnvConcreteTyp} casted value
* @throws {Error}
*/
function caststr(x, typ) {
if (typeof x === typ) return x;
if (typ === "boolean") {
return x === "true";
} else if (typ === "number") {
return Number(x);
} else if (typ === "string") {
return (x && x + "") || "";
} else if (typ === "csv" && x instanceof Set) {
return x;
} else if (typ === "csv" && typeof x === "string") {
if (!x) return new Set();
return new Set(x.split(",").map((x) => x.trim()));
} else {
throw new Error(`unsupported type: ${typ}`);
}
}
/**
* @returns {string} runtime name
*/
function _determineRuntime() {
if (typeof fastly !== "undefined") {
return "fastly";
}
if (typeof Deno !== "undefined") {
return "deno";
}
if (globalThis.wenv) return "worker";
if (typeof process !== "undefined") {
// process also exists in Workers (miniflare), where wenv is defined
if (process.env) return process.env.RUNTIME || "node";
}
return null;
}
export default class EnvManager {
/**
* Initializes the env manager.
*/
constructor() {
/** @type {string} */
this.runtime = _determineRuntime();
/** @type {Map<string, EnvConcreteTyp>} */
this.envMap = new Map();
this.load();
}
/**
* Loads env variables from runtime env. and is made globally available
* through `env` namespace. Existing env variables will be overwritten.
*/
load() {
this.envMap = this.defaultEnv();
// verbose log:
// console.debug("env defaults", this.envMap);
}
determineEnvStage() {
if (this.runtime === "node") return this.get("NODE_ENV");
if (this.runtime === "worker") return this.get("WORKER_ENV");
if (this.runtime === "deno") return this.get("DENO_ENV");
if (this.runtime === "fastly") return this.get("FASTLY_ENV");
return null;
}
// most-likely but not definitive platform this code is running on
mostLikelyCloudPlatform() {
const isDev = this.determineEnvStage() === "development";
// FLY_ALLOC_ID=5778f6b7-3cc2-d011-36b1-dfe057b0dc79 is set on fly-vms
const hasFlyAllocId = this.get("FLY_ALLOC_ID") != null;
// github.com/denoland/deploy_feedback/issues/73
const hasDenoDeployId = this.get("DENO_DEPLOYMENT_ID") != null;
const hasWorkersUa =
typeof navigator !== "undefined" &&
navigator.userAgent === "Cloudflare-Workers";
if (hasFlyAllocId) return "fly";
if (hasDenoDeployId) return "deno-deploy";
if (hasWorkersUa) return "cloudflare";
// if dev, then whatever is running is likely local
if (isDev) return "local";
// if prod, then node is likely running on fly
if (this.runtime === "node") return "fly";
// if prod, then deno is likely running on deno-deploy
if (this.runtime === "deno") return "deno-deploy";
// if prod, then worker is likely running on cloudflare
if (this.runtime === "worker") return "cloudflare";
if (this.runtime === "fastly") return "fastly";
return null;
}
/**
* Makes default env values.
* @return {Map} Runtime environment defaults.
*/
defaultEnv() {
const env = new Map();
for (const [key, mappedKey] of defaults) {
if (typeof mappedKey !== "object") continue;
const type = mappedKey.type;
const val = mappedKey.default;
if (!type || val == null) {
console.debug(key, "incomplete env val:", mappedKey);
continue;
}
env.set(key, caststr(val, type));
}
env.set("CLOUD_PLATFORM", this.mostLikelyCloudPlatform());
return env;
}
// one of deno, nodejs, fastly, or cloudflare workers
r() {
return this.runtime;
}
/**
* Gets the value of an env variable.
* @param {String} k - env variable name
* @return {EnvConcreteTyp} - env variable value
*/
get(k) {
let v = null;
if (this.runtime === "node") {
v = process.env[k];
} else if (this.runtime === "deno") {
v = Deno.env.get(k);
} else if (this.runtime === "fastly") {
v = fastlyEnv.get(k);
} else if (this.runtime === "worker") {
v = globalThis.wenv[k];
}
if (v == null) {
v = this.envMap.get(k);
}
const m = defaults.get(k);
// set default v when env var for k is not set
if (m && v == null) v = m.default;
// type-cast v as approp if k is among the defaults
if (m && v != null) v = caststr(v, m.type);
return v;
}
/**
* @param {String} k - env name
* @param {EnvDefTyp} v - env value
* @param {EnvTyp} typ - env type, one of boolean, string, number, or csv
*/
set(k, v, typ) {
typ = typ || "string";
this.envMap.set(k, caststr(v, typ));
}
}