Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const axiosInstance = axios.create();

const eventTriggerPath = '/v1/events/trigger';
const USER_MAIL_DOMAIN = 'mail.domain.com';
const USER_PARSE_WEBHOOK = 'user-parse.com/webhook/{{compiledVariable}}';
const USER_PARSE_WEBHOOK = 'https://example.com/webhook/{{compiledVariable}}';

describe('Should handle the new arrived mail', () => {
let inboundEmailParseUsecase: InboundEmailParse;
Expand Down Expand Up @@ -171,7 +171,7 @@ const getEntitiesStubObject = {
active: true,
replyCallback: {
active: true,
url: 'user-parse.com/webhook/{{compiledVariable}}',
url: 'https://example.com/webhook/{{compiledVariable}}',
},
shouldStopOnFail: false,
filters: [],
Expand Down Expand Up @@ -238,7 +238,7 @@ const getEntitiesStubObject = {
step: {
replyCallback: {
active: true,
url: 'user-parse.com/webhook/{{compiledVariable}}',
url: 'https://example.com/webhook/{{compiledVariable}}',
},
metadata: {
timed: {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { CompileTemplate, createHash } from '@novu/application-generic';
import { CompileTemplate, createHash, normalizeOutboundHttpUrl, validateUrlSsrf } from '@novu/application-generic';
import {
JobEntity,
JobRepository,
Expand Down Expand Up @@ -50,6 +50,18 @@ export class ReplyToStrategy {
data: job.payload,
});

const requestUrl = normalizeOutboundHttpUrl(compiledDomain);

if (!requestUrl) {
this.throwError('Reply callback URL blocked (SSRF): Invalid URL format.');
}

const ssrfError = await validateUrlSsrf(requestUrl);

if (ssrfError) {
this.throwError(`Reply callback URL blocked (SSRF): ${ssrfError}`);
}

const userPayload: IUserWebhookPayload = {
hmac: createHash(environment?.apiKeys[0]?.key, subscriber.subscriberId) || '',
transactionId,
Expand All @@ -61,7 +73,7 @@ export class ReplyToStrategy {
mail: command,
};

await axios.post(compiledDomain, userPayload);
await axios.post(requestUrl, userPayload);
}

private splitTo(address: string) {
Expand Down
40 changes: 40 additions & 0 deletions libs/application-generic/src/utils/ssrf-url-validation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,46 @@
import * as dns from 'node:dns';
import { LRUCache } from 'lru-cache';

/* Keep in sync with packages/shared/src/utils/ssrf-url-validation.ts */

/**
* Resolves a webhook-style URL for outbound HTTP requests.
* Host-only or path-first values (no scheme) are treated as https, matching axios behavior.
*/
export function normalizeOutboundHttpUrl(raw: string): string | null {
const trimmed = raw.trim();

if (!trimmed) {
return null;
}

try {
const parsed = new URL(trimmed);

if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
return trimmed;
}

return null;
} catch {
// Continue: scheme-less host/path (e.g. example.com/hook)
}

const withHttps = `https://${trimmed}`;

try {
const parsed = new URL(withHttps);

if (!parsed.hostname) {
return null;
}

return withHttps;
} catch {
return null;
}
}

const DNS_CACHE = new LRUCache<string, dns.LookupAddress[]>({
max: 500,
ttl: 1000 * 60 * 5, // 5 minutes
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ChatProviderIdEnum } from '@novu/shared';
import { normalizeOutboundHttpUrl, validateUrlSsrf } from '@novu/shared/utils/ssrf-url-validation';
import {
ChannelTypeEnum,
ENDPOINT_TYPES,
Expand Down Expand Up @@ -51,7 +52,20 @@ export class ChatWebhookProvider extends BaseProvider implements IChatProvider {
delete data.body.hmacSecretKey;
}

const response = await axios.create().post((data?.body?.webhookUrl as string) || endpoint.url, body, {
const targetUrlRaw = (data?.body?.webhookUrl as string) || endpoint.url;
const targetUrl = normalizeOutboundHttpUrl(targetUrlRaw);

if (!targetUrl) {
throw new Error('Chat webhook URL blocked: Invalid URL format.');
}

const ssrfError = await validateUrlSsrf(targetUrl);

if (ssrfError) {
throw new Error(`Chat webhook URL blocked: ${ssrfError}`);
}

const response = await axios.create().post(targetUrl, body, {
headers: {
'content-type': 'application/json',
'X-Novu-Signature': hmacValue,
Expand Down
8 changes: 8 additions & 0 deletions packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,16 @@
"require": "./dist/cjs/utils/index.js",
"import": "./dist/esm/utils/index.js",
"types": "./dist/esm/utils/index.d.js"
},
"./utils/ssrf-url-validation": {
"require": "./dist/cjs/utils/ssrf-url-validation.js",
"import": "./dist/esm/utils/ssrf-url-validation.js",
"types": "./dist/esm/utils/ssrf-url-validation.d.ts"
}
},
"dependencies": {
"lru-cache": "^11.2.4"
},
"devDependencies": {
"madge": "^8.0.0",
"rimraf": "^3.0.2",
Expand Down
113 changes: 113 additions & 0 deletions packages/shared/src/utils/ssrf-url-validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import * as dns from 'node:dns';
import { LRUCache } from 'lru-cache';

/* Keep in sync with libs/application-generic/src/utils/ssrf-url-validation.ts (normalizeOutboundHttpUrl + validateUrlSsrf) */

/**
* Resolves a webhook-style URL for outbound HTTP requests.
* Host-only or path-first values (no scheme) are treated as https, matching axios behavior.
*/
export function normalizeOutboundHttpUrl(raw: string): string | null {
const trimmed = raw.trim();

if (!trimmed) {
return null;
}

try {
const parsed = new URL(trimmed);

if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
return trimmed;
}

return null;
} catch {
// Continue: scheme-less host/path (e.g. example.com/hook)
}

const withHttps = `https://${trimmed}`;

try {
const parsed = new URL(withHttps);

if (!parsed.hostname) {
return null;
}

return withHttps;
} catch {
return null;
}
}

const DNS_CACHE = new LRUCache<string, dns.LookupAddress[]>({
max: 500,
ttl: 1000 * 60 * 5, // 5 minutes
});

function isPrivateIp(ip: string): boolean {
const privateRanges = [
/^0\.0\.0\.0$/i,
/^127\./,
/^10\./,
/^172\.(1[6-9]|2[0-9]|3[01])\./,
/^192\.168\./,
/^169\.254\./,
/^::ffff:127\./i,
/^::ffff:10\./i,
/^::ffff:172\.(1[6-9]|2[0-9]|3[01])\./i,
/^::ffff:192\.168\./i,
/^::ffff:169\.254\./i,
/^::1$/,
/^fc00:/i,
/^fe80:/i,
];
Comment thread
coderabbitai[bot] marked this conversation as resolved.

return privateRanges.some((range) => range.test(ip));
}

/**
* Validates that a URL is safe to fetch server-side (http/https only, no private IPs after DNS resolution).
* Returns an error message string if blocked, or null if allowed.
*/
export async function validateUrlSsrf(url: string): Promise<string | null> {
let parsed: URL;

try {
parsed = new URL(url);
} catch {
return 'Invalid URL format.';
}

if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
return `URL scheme "${parsed.protocol}" is not allowed. Only http and https are permitted.`;
}

const hostname = parsed.hostname.toLowerCase();

const blockedHostnames = ['localhost', 'metadata.google.internal'];

if (blockedHostnames.includes(hostname)) {
return `Requests to "${hostname}" are not allowed.`;
}

let addresses = DNS_CACHE.get(hostname);

if (!addresses) {
try {
addresses = await dns.promises.lookup(hostname, { all: true });
DNS_CACHE.set(hostname, addresses);
} catch {
return `Unable to resolve hostname "${hostname}".`;
}
}

for (const { address } of addresses) {
if (isPrivateIp(address)) {
return `Requests to private or reserved IP addresses are not allowed (resolved: ${address}).`;
}
}

return null;
Comment thread
scopsy marked this conversation as resolved.
}
22 changes: 8 additions & 14 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading