Commit 9c360e12 authored by ThinhNC's avatar ThinhNC

fix(redis): auto-sanitize REDIS_URL and enable TLS options for Upstash

parent 93afa9e7
......@@ -9,12 +9,14 @@ export function getRedisClientOptions(customOpts: RedisOptions = {}): {
url?: string;
options: RedisOptions;
} {
const isTls = envConfig.redis.url.startsWith("rediss://");
const commonOpts: RedisOptions = {
maxRetriesPerRequest: 1,
lazyConnect: true,
connectTimeout: 5000,
retryStrategy: () => null,
enableOfflineQueue: false,
...(isTls ? { tls: { rejectUnauthorized: false } } : {}),
...customOpts,
};
......@@ -42,8 +44,10 @@ export function getBullMQConnection(
extraOpts: Record<string, unknown> = {},
): ConnectionOptions {
if (envConfig.redis.url) {
const isTls = envConfig.redis.url.startsWith("rediss://");
return {
url: envConfig.redis.url,
...(isTls ? { tls: { rejectUnauthorized: false } } : {}),
...extraOpts,
};
}
......
function sanitizeRedisUrl(rawUrl: string | undefined): string {
if (!rawUrl) return "";
let url = rawUrl.trim();
if (
(url.startsWith('"') && url.endsWith('"')) ||
(url.startsWith("'") && url.endsWith("'"))
) {
url = url.slice(1, -1).trim();
}
const match = url.match(/rediss?:\/\/[^\s'"]+/i);
if (match) {
url = match[0];
}
if (
url.startsWith("redis://") &&
(url.includes("upstash.io") || rawUrl.includes("--tls"))
) {
url = url.replace(/^redis:\/\//i, "rediss://");
}
return url;
}
export const envConfig = {
nodeEnv: process.env.NODE_ENV || "development",
port: parseInt(process.env.PORT || "9898", 10),
......@@ -52,12 +74,13 @@ export const envConfig = {
),
},
redis: {
url: process.env.REDIS_URL || "",
url: sanitizeRedisUrl(process.env.REDIS_URL),
host: process.env.REDIS_HOST || "127.0.0.1",
port: parseInt(process.env.REDIS_PORT || "6379", 10),
password: process.env.REDIS_PASSWORD || undefined,
enabled:
process.env.REDIS_ENABLED === "true" || Boolean(process.env.REDIS_URL),
process.env.REDIS_ENABLED === "true" ||
Boolean(sanitizeRedisUrl(process.env.REDIS_URL)),
},
rateLimit: {
windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS || "900000", 10),
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment