-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.js
More file actions
404 lines (404 loc) · 11 KB
/
Copy pathconfig.js
File metadata and controls
404 lines (404 loc) · 11 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
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
const ms = require('ms')
const bytes = require('bytes')
const dotenv = require('dotenv')
const https = require('https')
const http = require('http')
const path = require('path')
const fs = require('fs')
dotenv.config({ quiet: true })
/**
* @typedef {'array' | 'number' | 'boolean' | 'string' | 'object'} ExpectedType
*/
/**
* @typedef {{
* env: string | null,
* parse: (value: string | undefined) => unknown,
* type: ExpectedType | ExpectedType[],
* allowPromise?: boolean
* }} SchemaEntry
*/
/** @param {string | undefined} host */
function checkHostOnline(host) {
return new Promise((resolve) => {
if (!host) return resolve(false)
const url =
host.startsWith('http://') || host.startsWith('https://')
? host
: `http://${host}`
const protocol = url.startsWith('https') ? https : http
const req = protocol.get(url, (res) => {
const statusCode = res.statusCode ?? 0
return resolve(statusCode >= 200 && statusCode < 500)
})
req.on('error', () => resolve(false))
req.setTimeout(3000, () => {
req.destroy()
return resolve(false)
})
})
}
/** @returns {Promise<string | undefined>} */
async function getHost() {
const log = require('./utils/logHandler')
const host = process.env.HOST
const altHost = process.env.ALT_HOST
if (!host) return undefined
if (!altHost) return host
if (!host && !altHost) return undefined
if (host === altHost) return host
const hostOnline = await checkHostOnline(host)
const altHostOnline = await checkHostOnline(altHost)
try {
if (hostOnline) {
log.debug('Primary host is online:', host)
return host
}
if (altHostOnline) {
log.debug('Alternate host is online:', altHost)
return altHost
}
} catch (error) {
log.warn('Both hosts are offline:', error)
return undefined
}
}
/** @param {unknown} value */
function parseBooleanEnv(value) {
if (value === undefined || value === null) return false
const v = String(value).trim().toLowerCase()
switch (v) {
case '1':
case 'true':
case 'yes':
case 'y':
case 'on':
return true
case '0':
case 'false':
case 'no':
case 'n':
case 'off':
return false
}
throw new Error(`Invalid boolean value: ${value}`)
}
/** @param {unknown} value @param {string} envName */
function parseIntegerEnv(value, envName) {
const parsed = parseInt(String(value), 10)
if (!Number.isFinite(parsed)) {
throw new Error(`${envName} must be a valid integer`)
}
return parsed
}
/** @param {unknown} value @param {string} envName */
function parseNumberEnv(value, envName) {
const parsed = Number(value)
if (!Number.isFinite(parsed)) {
throw new Error(`${envName} must be a valid number`)
}
return parsed
}
/** @param {unknown} value @param {string} envName */
function parseJsonArrayEnv(value, envName) {
if (typeof value !== 'string') {
throw new Error(`${envName} must be a valid JSON array`)
}
let parsed
try {
parsed = JSON.parse(value)
} catch {
throw new Error(`${envName} must be a valid JSON array`)
}
if (!Array.isArray(parsed)) {
throw new Error(`${envName} must be a JSON array`)
}
return parsed
}
/** @param {unknown} value @param {string} envName */
function parseMsEnv(value, envName) {
if (typeof value !== 'string') {
throw new Error(`${envName} must be a valid duration string`)
}
const parsed = ms(/** @type {import('ms').StringValue} */ (value))
if (!Number.isFinite(parsed)) {
throw new Error(`${envName} must be a valid duration string`)
}
return parsed
}
/** @param {unknown} value */
function parseOptionalTrimmedString(value) {
if (typeof value !== 'string') return undefined
const trimmed = value.trim()
return trimmed ? trimmed : undefined
}
/**
* @param {string} key
* @param {unknown} value
* @param {ExpectedType | ExpectedType[]} expectedTypes
* @param {boolean} [allowPromise=false]
*/
function validateParsedEnvType(
key,
value,
expectedTypes,
allowPromise = false
) {
if (value === undefined || value === null) return
if (
allowPromise &&
typeof value === 'object' &&
value !== null &&
'then' in value &&
typeof value.then === 'function'
) {
return
}
const types = Array.isArray(expectedTypes) ? expectedTypes : [expectedTypes]
const isValid = types.some((expectedType) => {
switch (expectedType) {
case 'array':
return Array.isArray(value)
case 'number':
return Number.isFinite(value)
case 'boolean':
return typeof value === 'boolean'
case 'string':
return typeof value === 'string'
case 'object':
return value && typeof value === 'object' && !Array.isArray(value)
default:
return false
}
})
if (!isValid) {
throw new Error(
`${key} has invalid type after parsing. Expected ${types.join(' or ')}`
)
}
}
/** @param {unknown} baseDirPath */
function validatePath(baseDirPath) {
if (!baseDirPath || typeof baseDirPath !== 'string') {
throw new Error('BASE_DIR environment variable must be set and be a string')
}
try {
const resolvedPath = path.resolve(baseDirPath)
if (!fs.existsSync(resolvedPath)) {
throw new Error(`BASE_DIR does not exist: ${resolvedPath}`)
}
const stats = fs.statSync(resolvedPath)
if (!stats.isDirectory()) {
throw new Error(`BASE_DIR is not a directory: ${resolvedPath}`)
}
return resolvedPath
} catch (error) {
if (error instanceof Error && error.message.includes('BASE_DIR')) {
throw error
}
const message = error instanceof Error ? error.message : String(error)
throw new Error(`Invalid BASE_DIR configuration: ${message}`)
}
}
/** @type {Record<string, SchemaEntry>} */
const schema = {
NODE_ENV: { env: 'NODE_ENV', parse: (v) => v, type: 'string' },
PORT: {
env: 'PORT',
parse: (v) => parseIntegerEnv(v, 'PORT'),
type: 'number',
},
NAME: { env: 'NAME', parse: (v) => v, type: 'string' },
HOST: { env: null, parse: getHost, type: 'string', allowPromise: true },
BIND: { env: 'BIND', parse: (v) => v, type: 'string' },
BASE_PATH: { env: 'BASE_PATH', parse: (v) => v, type: 'string' },
BASE_DIR: { env: 'BASE_DIR', parse: validatePath, type: 'string' },
DISALLOWED_DIRS: {
env: 'DISALLOWED_DIRS',
parse: (v) => parseJsonArrayEnv(v, 'DISALLOWED_DIRS'),
type: 'array',
},
DISALLOWED_FILES: {
env: 'DISALLOWED_FILES',
parse: (v) => parseJsonArrayEnv(v, 'DISALLOWED_FILES'),
type: 'array',
},
DISALLOWED_EXTENSIONS: {
env: 'DISALLOWED_EXTENSIONS',
parse: (v) => parseJsonArrayEnv(v, 'DISALLOWED_EXTENSIONS'),
type: 'array',
},
MONGODB_URL: { env: 'MONGODB_URL', parse: (v) => v, type: 'string' },
REDIS_URL: {
env: 'REDIS_URL',
parse: parseOptionalTrimmedString,
type: 'string',
},
REDIS_CACHE_TTL_SECONDS: {
env: 'REDIS_CACHE_TTL_SECONDS',
parse: (v) => parseMsEnv(v, 'REDIS_CACHE_TTL_SECONDS'),
type: 'number',
},
REDIS_CACHE_PATCH_FLAG: {
env: 'REDIS_CACHE_PATCH_FLAG',
parse: (v) =>
typeof v === 'string' && v.trim()
? v.trim()
: 'gdl.redis.cache.layer.patched',
type: 'string',
},
SESSION_SECRET: { env: 'SESSION_SECRET', parse: (v) => v, type: 'string' },
COOKIE_MAX_AGE: {
env: 'COOKIE_MAX_AGE',
parse: (v) => parseMsEnv(v, 'COOKIE_MAX_AGE'),
type: 'number',
},
MAX_DEPTH: {
env: 'MAX_DEPTH',
parse: (v) => parseIntegerEnv(v, 'MAX_DEPTH'),
type: 'number',
},
STAT_DIRECTORY_SIZE: {
env: 'STAT_DIRECTORY_SIZE',
parse: parseBooleanEnv,
type: 'boolean',
},
STAT_FILE_SIZE: {
env: 'STAT_FILE_SIZE',
parse: parseBooleanEnv,
type: 'boolean',
},
PAGINATION_LIMIT: {
env: 'PAGINATION_LIMIT',
parse: (v) => parseIntegerEnv(v, 'PAGINATION_LIMIT'),
type: 'number',
},
RATE_LIMIT_WINDOW: {
env: 'RATE_LIMIT_WINDOW',
parse: (v) => parseMsEnv(v, 'RATE_LIMIT_WINDOW'),
type: 'number',
},
RATE_LIMIT_MAX: {
env: 'RATE_LIMIT_MAX',
parse: (v) => parseIntegerEnv(v, 'RATE_LIMIT_MAX'),
type: 'number',
},
SCAN_ON_STARTUP: {
env: 'SCAN_ON_STARTUP',
parse: parseBooleanEnv,
type: 'boolean',
},
UPSERT_ON_ACCESS: {
env: 'UPSERT_ON_ACCESS',
parse: (v) => v,
type: 'string',
},
OAUTH_PROVIDERS: {
env: 'OAUTH_PROVIDERS',
parse: (v) => parseJsonArrayEnv(v, 'OAUTH_PROVIDERS'),
type: 'array',
},
FILE_UPLOAD_LIMIT: {
env: 'FILE_UPLOAD_LIMIT',
parse: (v) => (typeof v === 'string' ? bytes(v) : undefined),
type: 'number',
},
HASH_ALGORITHM: { env: 'HASH_ALGORITHM', parse: (v) => v, type: 'string' },
MAX_PIXELS: {
env: 'MAX_PIXELS',
parse: (v) => parseIntegerEnv(v, 'MAX_PIXELS'),
type: 'number',
},
MAX_SCALE: {
env: 'MAX_SCALE',
parse: (v) => parseIntegerEnv(v, 'MAX_SCALE'),
type: 'number',
},
MAX_BUFFER_SIZE: {
env: 'MAX_BUFFER_SIZE',
parse: (v) => (typeof v === 'string' ? bytes(v) : undefined),
type: 'number',
},
MAX_SEARCH_RESULTS: {
env: 'MAX_SEARCH_RESULTS',
parse: (v) => parseIntegerEnv(v, 'MAX_SEARCH_RESULTS'),
type: 'number',
},
SIDECAR_FILE: {
env: 'SIDECAR_FILE',
parse: parseBooleanEnv,
type: 'boolean',
},
SIDECAR_FILE_EXTENSION: {
env: 'SIDECAR_FILE_EXTENSION',
parse: (v) => {
const extension =
typeof v === 'string' && v.trim() ? v.trim().toLowerCase() : '.json'
return extension.startsWith('.') ? extension : `.${extension}`
},
type: 'string',
},
LOG_LEVEL: {
env: 'LOG_LEVEL',
parse: (v) => {
const intValue = parseInt(String(v), 10)
return Number.isFinite(intValue) && String(intValue) === String(v).trim()
? intValue
: v
},
type: ['string', 'number'],
},
TRANSCODE_VIDEO: {
env: 'TRANSCODE_VIDEO',
parse: parseBooleanEnv,
type: 'boolean',
},
TRANSCODE_AUDIO: {
env: 'TRANSCODE_AUDIO',
parse: parseBooleanEnv,
type: 'boolean',
},
USE_SYSTEM_FFMPEG: {
env: 'USE_SYSTEM_FFMPEG',
parse: parseBooleanEnv,
type: 'boolean',
},
FFMPEG_PATH: {
env: 'FFMPEG_PATH',
parse: (v) => v,
type: 'string',
},
DISCORD_CLIENT_ID: {
env: 'DISCORD_CLIENT_ID',
parse: parseOptionalTrimmedString,
type: 'string',
},
DISCORD_CLIENT_SECRET: {
env: 'DISCORD_CLIENT_SECRET',
parse: parseOptionalTrimmedString,
type: 'string',
},
GITHUB_CLIENT_ID: {
env: 'GITHUB_CLIENT_ID',
parse: parseOptionalTrimmedString,
type: 'string',
},
GITHUB_CLIENT_SECRET: {
env: 'GITHUB_CLIENT_SECRET',
parse: parseOptionalTrimmedString,
type: 'string',
},
}
/** @type {Record<string, unknown>} */
const config = {}
for (const [key, entry] of Object.entries(schema)) {
const { env, parse, type, allowPromise } = entry
const value = env ? process.env[env] : undefined
const parsed = parse(value)
validateParsedEnvType(key, parsed, type, allowPromise)
config[key] = parsed
}
const hostValue = config['HOST']
config['HOST'] =
hostValue instanceof Promise ? hostValue.then((host) => host) : undefined
console.info('Config loaded successfully')
module.exports = config