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
43 changes: 42 additions & 1 deletion app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,47 @@
// src/app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import type { NextRequest } from "next/server";
import { authOptions } from "@/lib/authOptions";

const handler = NextAuth(authOptions);
const nextAuthHandler = NextAuth(authOptions);

const PROD_FALLBACK_HOST = "tradiaai.app";

const resolveRequestBase = (request: NextRequest): string | null => {
const forwardedHost = request.headers.get("x-forwarded-host");
const host = forwardedHost || request.headers.get("host");
if (!host) return null;

const cleanHost = host.trim().toLowerCase();
if (!cleanHost) return null;

const forwardedProto = request.headers.get("x-forwarded-proto");
const protocol = forwardedProto || (cleanHost.includes("localhost") ? "http" : "https");

return `${protocol}://${cleanHost}`;
};

const applySafeNextAuthUrl = (request: NextRequest) => {
const requestBase = resolveRequestBase(request);
const isProd = process.env.NODE_ENV === "production";

if (isProd) {
if (requestBase && !requestBase.includes("localhost")) {
process.env.NEXTAUTH_URL = requestBase;
Comment on lines +29 to +30

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Stop trusting forwarded host for NEXTAUTH_URL

In production this sets process.env.NEXTAUTH_URL directly from x-forwarded-host/host on every request, which is global mutable state and can be poisoned by a crafted host header in deployments where forwarded headers are not strictly sanitized. That can send auth redirects/callback bases to an attacker-controlled or wrong domain for concurrent users. NEXTAUTH_URL should come from a fixed allow-listed config, not per-request header mutation.

Useful? React with 👍 / 👎.

return;
}
process.env.NEXTAUTH_URL = `https://${PROD_FALLBACK_HOST}`;
return;
}

if (requestBase) {
process.env.NEXTAUTH_URL = requestBase;
}
};

const handler = async (request: NextRequest, context: unknown) => {
applySafeNextAuthUrl(request);
return nextAuthHandler(request, context as any);
};

export { handler as GET, handler as POST };
170 changes: 170 additions & 0 deletions app/api/economic-events/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/authOptions";
import { createClient } from "@/utils/supabase/server";
import type { EventImpact } from "@/types/eventAwareness";

export const dynamic = "force-dynamic";

type EventIngestItem = {
providerEventId: string;
title: string;
country?: string;
currency: string;
impact: EventImpact;
scheduledAt: string;
actual?: string | null;
forecast?: string | null;
previous?: string | null;
eventType?: string | null;
};

const normalizeImpact = (value: unknown): EventImpact | null => {
const normalized = String(value || "").trim().toLowerCase();
if (normalized === "low" || normalized === "medium" || normalized === "high") return normalized;
return null;
};

const normalizeIso = (value: unknown): string | null => {
if (value === null || value === undefined) return null;
const parsed = new Date(String(value));
return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
};

const isAuthorized = async (request: NextRequest): Promise<boolean> => {
const bearer = request.headers.get("authorization") || "";
const token = bearer.startsWith("Bearer ") ? bearer.slice(7).trim() : "";
const configuredToken = process.env.ECONOMIC_EVENTS_INGEST_TOKEN?.trim();

if (configuredToken && token && token === configuredToken) {
return true;
}

const session = await getServerSession(authOptions);
return Boolean(session?.user?.id);
};

export async function GET(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

const currency = request.nextUrl.searchParams.get("currency")?.trim().toUpperCase();
const from = normalizeIso(request.nextUrl.searchParams.get("from")) || new Date().toISOString();
const to =
normalizeIso(request.nextUrl.searchParams.get("to")) ||
new Date(Date.now() + 48 * 60 * 60 * 1000).toISOString();

const supabase = createClient();
let query = supabase
.from("economic_events")
.select("id, provider_event_id, title, country, currency, impact, scheduled_at, actual, forecast, previous, event_type")
.gte("scheduled_at", from)
.lte("scheduled_at", to)
.order("scheduled_at", { ascending: true })
.limit(100);

if (currency) {
query = query.eq("currency", currency);
}

const { data, error } = await query;
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}

return NextResponse.json({ events: data || [] });
} catch (error) {
console.error("GET /api/economic-events failed:", error);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}

export async function POST(request: NextRequest) {
try {
const allowed = await isAuthorized(request);
if (!allowed) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

const body = await request.json().catch(() => null);
if (!body || typeof body !== "object" || Array.isArray(body)) {
return NextResponse.json({ error: "Invalid request payload" }, { status: 400 });
}

const inputItems = Array.isArray((body as { events?: unknown[] }).events)
? ((body as { events: unknown[] }).events as unknown[])
: [];
if (!inputItems.length) {
return NextResponse.json({ error: "events[] is required" }, { status: 400 });
}

const validRows: EventIngestItem[] = [];
for (const item of inputItems) {
const row = item as Partial<EventIngestItem>;
const providerEventId = String(row.providerEventId || "").trim();
const title = String(row.title || "").trim();
const currency = String(row.currency || "").trim().toUpperCase();
const impact = normalizeImpact(row.impact);
const scheduledAt = normalizeIso(row.scheduledAt);

if (!providerEventId || !title || !currency || !impact || !scheduledAt) {
continue;
}

validRows.push({
providerEventId,
title,
country: row.country ? String(row.country).trim() : undefined,
currency,
impact,
scheduledAt,
actual: row.actual ? String(row.actual) : null,
forecast: row.forecast ? String(row.forecast) : null,
previous: row.previous ? String(row.previous) : null,
eventType: row.eventType ? String(row.eventType) : null,
});
}

if (!validRows.length) {
return NextResponse.json({ error: "No valid events found in payload" }, { status: 400 });
}

const supabase = createClient();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use service-role client for event-ingest upserts

This write path uses createClient() (cookie/anon credentials) even when authorization is via the bearer ingest token, so the upsert executes without a privileged role. In the same commit, economic_events is put under RLS with only a SELECT policy, so POST /api/economic-events will fail writes with RLS errors in production instead of ingesting events. Use an admin/service-role client for this endpoint (or add explicit write policies).

Useful? React with 👍 / 👎.

const payload = validRows.map((row) => ({
provider_event_id: row.providerEventId,
title: row.title,
country: row.country || null,
currency: row.currency,
impact: row.impact,
scheduled_at: row.scheduledAt,
actual: row.actual || null,
forecast: row.forecast || null,
previous: row.previous || null,
event_type: row.eventType || null,
updated_at: new Date().toISOString(),
}));

const { data, error } = await supabase
.from("economic_events")
.upsert(payload, { onConflict: "provider_event_id" })
.select("id, provider_event_id, title, currency, impact, scheduled_at");

if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}

return NextResponse.json(
{
ingested: data?.length || 0,
events: data || [],
},
{ status: 201 }
);
} catch (error) {
console.error("POST /api/economic-events failed:", error);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}

Check notice on line 170 in app/api/economic-events/route.ts

View check run for this annotation

codefactor.io / CodeFactor

app/api/economic-events/route.ts#L85-L170

Complex Method
101 changes: 101 additions & 0 deletions app/api/event-awareness/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/authOptions";
import { createClient } from "@/utils/supabase/server";
import { evaluateEventRisk } from "@/lib/forex/eventAwarenessService";
import type { EconomicEvent } from "@/types/eventAwareness";

export const dynamic = "force-dynamic";

const normalizePlannedAt = (value: string | null): string => {
if (!value) return new Date().toISOString();
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) return new Date().toISOString();
return parsed.toISOString();
};

const mapImpact = (value: unknown): EconomicEvent["impact"] => {
const candidate = String(value || "").trim().toLowerCase();
if (candidate === "high" || candidate === "medium" || candidate === "low") return candidate;
return "medium";
};

export async function GET(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

const pairSymbol = String(request.nextUrl.searchParams.get("pairSymbol") || "")
.trim()
.toUpperCase();
if (!pairSymbol) {
return NextResponse.json({ error: "pairSymbol is required" }, { status: 400 });
}

const plannedAt = normalizePlannedAt(request.nextUrl.searchParams.get("plannedAt"));
const plannedDate = new Date(plannedAt);
const windowStart = new Date(plannedDate.getTime() - 2 * 60 * 60 * 1000);
const windowEnd = new Date(plannedDate.getTime() + 6 * 60 * 60 * 1000);

const supabase = createClient();
const { data: pairData, error: pairError } = await supabase
.from("forex_pairs")
.select("base_currency, quote_currency")
.eq("symbol", pairSymbol)
.eq("is_active", true)
.single();

if (pairError || !pairData) {
return NextResponse.json({ error: "Selected forex pair is not available" }, { status: 400 });
}

const currencies = [pairData.base_currency, pairData.quote_currency];
const eventsResult = await supabase
.from("economic_events")
.select("id, title, currency, country, impact, scheduled_at")
.in("currency", currencies)
.gte("scheduled_at", windowStart.toISOString())
.lte("scheduled_at", windowEnd.toISOString())
.order("scheduled_at", { ascending: true });

// Gracefully fallback if this table is not yet migrated in some envs.
if (eventsResult.error) {
const fallback = evaluateEventRisk([], plannedAt, pairSymbol);
return NextResponse.json({
plannedAt,
pairSymbol,
action: fallback.action,
summary: fallback.summary,
windowStart: fallback.windowStart,
windowEnd: fallback.windowEnd,
events: [],
});
}

const mappedEvents: EconomicEvent[] = (eventsResult.data || []).map((event) => ({
id: String(event.id),
title: String(event.title || "Untitled event"),
currency: String(event.currency || "").toUpperCase(),
country: event.country ? String(event.country) : null,
impact: mapImpact(event.impact),
scheduled_at: String(event.scheduled_at),
}));

const report = evaluateEventRisk(mappedEvents, plannedAt, pairSymbol);

return NextResponse.json({
plannedAt,
pairSymbol,
action: report.action,
summary: report.summary,
windowStart: report.windowStart,
windowEnd: report.windowEnd,
events: report.relevantEvents,
});
} catch (error) {
console.error("GET /api/event-awareness failed:", error);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}
Loading
Loading