Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions src/config/env-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ const baseSchema = z.object({
// ── Markets CORS ─────────────────────────────────────────
MARKETS_CORS_ALLOWED_ORIGINS: z.string().default(""),

// ── Notifications CORS ──────────────────────────────────
NOTIFICATIONS_CORS_ALLOWED_ORIGINS: z.string().default(""),

// ── Geo-blocking ──────────────────────────────────────────
GEO_BLOCKED_COUNTRIES: z.string().default("").transform((val) =>
val.split(",").map((s) => s.trim().toUpperCase()).filter(Boolean),
Expand Down
23 changes: 23 additions & 0 deletions src/middleware/cors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,4 +136,27 @@ export function marketsCors(): ReturnType<typeof createCorsAllowlistMiddleware>
return marketsCorsMiddleware;
}

/**
* Pre-configured CORS middleware for the notifications endpoint.
* Reads allowed origins from the `NOTIFICATIONS_CORS_ALLOWED_ORIGINS` env variable.
* When the allowlist is empty, all cross-origin requests to /api/notifications are denied.
*/
let notificationsCorsMiddleware: ReturnType<typeof createCorsAllowlistMiddleware> | null = null;

export function notificationsCors(): ReturnType<typeof createCorsAllowlistMiddleware> {
if (!notificationsCorsMiddleware) {
const raw = env.NOTIFICATIONS_CORS_ALLOWED_ORIGINS ?? "";
const allowedOrigins = raw
.split(",")
.map((o) => o.trim())
.filter((o) => o.length > 0);
notificationsCorsMiddleware = createCorsAllowlistMiddleware({
allowedOrigins,
allowCredentials: true,
maxAgeSeconds: 600,
});
}
return notificationsCorsMiddleware;
}

export const enforceCors = marketsCors();
7 changes: 6 additions & 1 deletion src/routes/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
} from "../services/notificationPrefs";
import { markNotificationsAsRead } from "../services/notificationService";
import { idempotency } from "../middleware/idempotency";
import { RouteErrorFactory } from "../errors";
import { notificationsCors } from "../middleware/cors";
import { notificationsMetricsMiddleware } from "../metrics/notificationsMetrics";

const notificationCategorySchema = z.enum(notificationCategories);
Expand Down Expand Up @@ -51,6 +53,9 @@ const markReadBodySchema = z

export const notificationsRouter = Router();

// Enforce CORS allowlist early so unapproved origins are rejected
// before any processing (preflight responses cached via Access-Control-Max-Age).
notificationsRouter.use(notificationsCors());
notificationsRouter.use(requireAuth);
notificationsRouter.use(notificationsMetricsMiddleware);

Expand Down Expand Up @@ -94,7 +99,7 @@ notificationsRouter.patch(
},
"notification_preferences_validation_failed",
);
throw RouteErrorFactory.validation("Invalid request body");
return next(RouteErrorFactory.validation("Invalid request body"));
}

try {
Expand Down
7 changes: 5 additions & 2 deletions tests/notifications.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
jest.mock("../src/middleware/cors", () => ({
notificationsCors: () => (_req: any, _res: any, next: any) => next(),
}));

jest.mock("../src/middleware/requireAuth", () => ({
requireAuth: (req: any, _res: any, next: any) => {
req.user = { id: "user-123", stellarAddress: "GTEST" };
Expand Down Expand Up @@ -76,9 +80,8 @@ describe("notifications preferences routes", () => {
.patch("/api/notifications/preferences")
.send({ preferences: [{ category: "nope", channel: "email", enabled: true }] });

expect(res.status).toBe(400);
expect(res.status).toBe(422);
expect(res.body.error.code).toBe("validation_error");
expect(Array.isArray(res.body.error.details)).toBe(true);
expect(mockPatchNotificationPreferences).not.toHaveBeenCalled();
});

Expand Down
Loading