Elffuss BraidHub

kikocis/osiris public

fix: address SSRF, rate-limit spoofing, and implement edge cache reliability
Changesetfb5eac4377997dceb9cff15ae2a43eb2179e57f6ba842251ae0e59df81c03638
AuthorGemini CLI <gemini@example.com> · 2026-05-21 17:05 -04:00
CommitterGemini CLI <gemini@example.com> · 2026-05-21 17:05 -04:00
Parentsa0e9742ea516

Browse the files at this changeset

14 files changed

modified src/app/api/cctv/stream-status/route.ts +2 −1
@@ -1,4 +1,5 @@
11 import { NextResponse } from 'next/server';
2+import { safeFetch } from '@/lib/ssrf-guard';
23
34 export const dynamic = 'force-dynamic';
45
@@ -13,7 +14,7 @@
1314 }
1415
1516 try {
16- const res = await fetch(url, {
17+ const res = await safeFetch(url, {
1718 signal: AbortSignal.timeout(8000),
1819 headers: {
1920 'User-Agent': 'Mozilla/5.0 (compatible; OSIRIS/1.0; +https://github.com/simplifaisoul/osiris)',
modified src/app/api/earthquakes/route.ts +2 −0
@@ -1,3 +1,4 @@
1+export const revalidate = 300;
12 import { NextResponse } from 'next/server';
23
34 /**
@@ -54,3 +55,4 @@
5455 return NextResponse.json({ earthquakes: [], error: 'Failed to fetch earthquake data' }, { status: 500 });
5556 }
5657 }
58+
modified src/app/api/fires/route.ts +2 −0
@@ -1,3 +1,4 @@
1+export const revalidate = 900;
12 import { NextResponse } from 'next/server';
23
34 export const dynamic = 'force-dynamic';
@@ -119,3 +120,4 @@
119120
120121 return fires;
121122 }
123+
modified src/app/api/flights/route.ts +2 −0
@@ -1,3 +1,4 @@
1+export const revalidate = 60;
12 import { NextResponse } from 'next/server';
23
34 /**
@@ -272,3 +273,4 @@
272273 count: z.count,
273274 }));
274275 }
276+
modified src/app/api/frontlines/route.ts +2 −0
@@ -1,3 +1,4 @@
1+export const revalidate = 3600;
12 import { NextResponse } from 'next/server';
23
34 /**
@@ -32,3 +33,4 @@
3233 return NextResponse.json({ frontlines: null, error: 'Failed to fetch frontline data' }, { status: 500 });
3334 }
3435 }
36+
modified src/app/api/live-news/route.ts +2 −0
@@ -1,3 +1,4 @@
1+export const revalidate = 3600;
12 import { NextResponse } from 'next/server';
23
34 /**
@@ -59,3 +60,4 @@
5960 headers: { 'Cache-Control': 'public, s-maxage=86400, stale-while-revalidate=172800' },
6061 });
6162 }
63+
modified src/app/api/markets/route.ts +2 −0
@@ -1,3 +1,4 @@
1+export const revalidate = 300;
12 import { NextResponse } from 'next/server';
23
34 /**
@@ -148,3 +149,4 @@
148149 return NextResponse.json({ stocks: {}, oil: {}, commodities: {}, crypto: {}, indices: {}, error: 'Failed' }, { status: 500 });
149150 }
150151 }
152+
modified src/app/api/news/route.ts +2 −0
@@ -1,3 +1,4 @@
1+export const revalidate = 900;
12 import { NextResponse } from 'next/server';
23
34 /**
@@ -157,3 +158,4 @@
157158 return NextResponse.json({ news: [], error: 'Failed to fetch news' }, { status: 500 });
158159 }
159160 }
161+
modified src/app/api/region-dossier/route.ts +149 −149
@@ -1,149 +1,149 @@
1-import { NextResponse } from 'next/server';
2-
3-/**
4- * OSIRIS — Region Dossier API
5- * Provides country intelligence for any coordinate (right-click on map)
6- * Fix #115: Steps 2-4 now run in parallel via Promise.allSettled
7- */
8-
9-export async function GET(request: Request) {
10- const { searchParams } = new URL(request.url);
11- const lat = parseFloat(searchParams.get('lat') || '0');
12- const lng = parseFloat(searchParams.get('lng') || '0');
13-
14- try {
15- // Step 1: Reverse geocode to get country (must complete first — other steps depend on it)
16- const geoRes = await fetch(
17- `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&zoom=5&addressdetails=1`,
18- {
19- signal: AbortSignal.timeout(8000),
20- headers: { 'User-Agent': 'OsirisIntelPlatform/1.0' },
21- }
22- );
23-
24- let countryName = '';
25- let countryCode = '';
26- let locationInfo: any = {};
27-
28- if (geoRes.ok) {
29- const geoData = await geoRes.json();
30- const addr = geoData.address || {};
31- countryName = addr.country || '';
32- countryCode = addr.country_code?.toUpperCase() || '';
33- locationInfo = {
34- city: addr.city || addr.town || addr.village || '',
35- state: addr.state || addr.region || '',
36- country: countryName,
37- country_code: countryCode,
38- display_name: geoData.display_name,
39- };
40- }
41-
42- // Steps 2–4: Run in PARALLEL after geocode (Fixes #115 — was a sequential waterfall)
43- const [countryResult, wikiResult, hosResult] = await Promise.allSettled([
44-
45- // Step 2: Fetch country details from RestCountries
46- (async () => {
47- if (!countryCode) return null;
48- try {
49- const res = await fetch(
50- `https://restcountries.com/v3.1/alpha/${countryCode}?fields=name,capital,population,area,region,subregion,languages,currencies,flag,flags,timezones`,
51- { signal: AbortSignal.timeout(5000) }
52- );
53- if (res.ok) return await res.json();
54- } catch (e) { console.warn('[OSIRIS] Country fetch error:', e instanceof Error ? e.message : e); }
55- return null;
56- })(),
57-
58- // Step 3: Fetch Wikipedia summary
59- (async () => {
60- const wikiQuery = locationInfo.city || countryName;
61- if (!wikiQuery) return null;
62- try {
63- const res = await fetch(
64- `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(wikiQuery)}`,
65- { signal: AbortSignal.timeout(5000) }
66- );
67- if (res.ok) {
68- const wiki = await res.json();
69- return {
70- title: wiki.title,
71- extract: wiki.extract?.substring(0, 500),
72- thumbnail: wiki.thumbnail?.source,
73- };
74- }
75- } catch (e) { console.warn('[OSIRIS] Wikipedia fetch error:', e instanceof Error ? e.message : e); }
76- return null;
77- })(),
78-
79- // Step 4: Fetch head of state from Wikidata SPARQL
80- (async () => {
81- if (!countryName) return null;
82- try {
83- // Sanitize country name for SPARQL string literal
84- const safe = countryName.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
85- const sparql = `SELECT ?leader ?leaderLabel ?positionLabel WHERE {
86- ?country wdt:P31 wd:Q6256;
87- rdfs:label "${safe}"@en;
88- wdt:P6 ?leader.
89- OPTIONAL { ?leader wdt:P39 ?position. }
90- SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
91- } LIMIT 1`;
92- const res = await fetch(
93- `https://query.wikidata.org/sparql?format=json&query=${encodeURIComponent(sparql)}`,
94- {
95- signal: AbortSignal.timeout(5000),
96- headers: { 'User-Agent': 'OsirisIntelPlatform/1.0' },
97- }
98- );
99- if (res.ok) {
100- const wd = await res.json();
101- const binding = wd.results?.bindings?.[0];
102- if (binding) {
103- return {
104- name: binding.leaderLabel?.value,
105- position: binding.positionLabel?.value || 'Head of State',
106- };
107- }
108- }
109- } catch (e) { console.warn('[OSIRIS] Wikidata fetch error:', e instanceof Error ? e.message : e); }
110- return null;
111- })(),
112- ]);
113-
114- const countryData = countryResult.status === 'fulfilled' ? countryResult.value : null;
115- const wikiSummary = wikiResult.status === 'fulfilled' ? wikiResult.value : null;
116- const headOfState = hosResult.status === 'fulfilled' ? hosResult.value : null;
117-
118- return NextResponse.json({
119- coordinates: { lat, lng },
120- location: locationInfo,
121- country: countryData ? {
122- name: countryData.name?.common,
123- official_name: countryData.name?.official,
124- capital: countryData.capital?.[0],
125- population: countryData.population,
126- area: countryData.area,
127- region: countryData.region,
128- subregion: countryData.subregion,
129- languages: countryData.languages ? Object.values(countryData.languages) : [],
130- currencies: countryData.currencies
131- ? Object.entries(countryData.currencies).map(([code, info]: [string, any]) => `${info.name} (${info.symbol || code})`)
132- : [],
133- flag: countryData.flag,
134- flag_url: countryData.flags?.svg,
135- timezones: countryData.timezones,
136- } : null,
137- head_of_state: headOfState,
138- wikipedia: wikiSummary,
139- timestamp: new Date().toISOString(),
140- }, {
141- headers: {
142- 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=7200',
143- },
144- });
145- } catch (error) {
146- console.error('Region dossier error:', error);
147- return NextResponse.json({ error: 'Failed to fetch region data' }, { status: 500 });
148- }
149-}
1+import { NextResponse } from 'next/server';
2+
3+/**
4+ * OSIRIS — Region Dossier API
5+ * Provides country intelligence for any coordinate (right-click on map)
6+ * Fix #115: Steps 2-4 now run in parallel via Promise.allSettled
7+ */
8+
9+export async function GET(request: Request) {
10+ const { searchParams } = new URL(request.url);
11+ const lat = parseFloat(searchParams.get('lat') || '0');
12+ const lng = parseFloat(searchParams.get('lng') || '0');
13+
14+ try {
15+ // Step 1: Reverse geocode to get country (must complete first — other steps depend on it)
16+ const geoRes = await fetch(
17+ `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&zoom=5&addressdetails=1`,
18+ {
19+ signal: AbortSignal.timeout(8000),
20+ headers: { 'User-Agent': 'OsirisIntelPlatform/1.0' },
21+ }
22+ );
23+
24+ let countryName = '';
25+ let countryCode = '';
26+ let locationInfo: any = {};
27+
28+ if (geoRes.ok) {
29+ const geoData = await geoRes.json();
30+ const addr = geoData.address || {};
31+ countryName = addr.country || '';
32+ countryCode = addr.country_code?.toUpperCase() || '';
33+ locationInfo = {
34+ city: addr.city || addr.town || addr.village || '',
35+ state: addr.state || addr.region || '',
36+ country: countryName,
37+ country_code: countryCode,
38+ display_name: geoData.display_name,
39+ };
40+ }
41+
42+ // Steps 2–4: Run in PARALLEL after geocode (Fixes #115 — was a sequential waterfall)
43+ const [countryResult, wikiResult, hosResult] = await Promise.allSettled([
44+
45+ // Step 2: Fetch country details from RestCountries
46+ (async () => {
47+ if (!countryCode) return null;
48+ try {
49+ const res = await fetch(
50+ `https://restcountries.com/v3.1/alpha/${countryCode}?fields=name,capital,population,area,region,subregion,languages,currencies,flag,flags,timezones`,
51+ { signal: AbortSignal.timeout(5000) }
52+ );
53+ if (res.ok) return await res.json();
54+ } catch (e) { console.warn('[OSIRIS] Country fetch error:', e instanceof Error ? e.message : e); }
55+ return null;
56+ })(),
57+
58+ // Step 3: Fetch Wikipedia summary
59+ (async () => {
60+ const wikiQuery = locationInfo.city || countryName;
61+ if (!wikiQuery) return null;
62+ try {
63+ const res = await fetch(
64+ `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(wikiQuery)}`,
65+ { signal: AbortSignal.timeout(5000) }
66+ );
67+ if (res.ok) {
68+ const wiki = await res.json();
69+ return {
70+ title: wiki.title,
71+ extract: wiki.extract?.substring(0, 500),
72+ thumbnail: wiki.thumbnail?.source,
73+ };
74+ }
75+ } catch (e) { console.warn('[OSIRIS] Wikipedia fetch error:', e instanceof Error ? e.message : e); }
76+ return null;
77+ })(),
78+
79+ // Step 4: Fetch head of state from Wikidata SPARQL
80+ (async () => {
81+ if (!countryName) return null;
82+ try {
83+ // Sanitize country name for SPARQL string literal
84+ const safe = countryName.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
85+ const sparql = `SELECT ?leader ?leaderLabel ?positionLabel WHERE {
86+ ?country wdt:P31 wd:Q6256;
87+ rdfs:label "${safe}"@en;
88+ wdt:P6 ?leader.
89+ OPTIONAL { ?leader wdt:P39 ?position. }
90+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
91+ } LIMIT 1`;
92+ const res = await fetch(
93+ `https://query.wikidata.org/sparql?format=json&query=${encodeURIComponent(sparql)}`,
94+ {
95+ signal: AbortSignal.timeout(5000),
96+ headers: { 'User-Agent': 'OsirisIntelPlatform/1.0' },
97+ }
98+ );
99+ if (res.ok) {
100+ const wd = await res.json();
101+ const binding = wd.results?.bindings?.[0];
102+ if (binding) {
103+ return {
104+ name: binding.leaderLabel?.value,
105+ position: binding.positionLabel?.value || 'Head of State',
106+ };
107+ }
108+ }
109+ } catch (e) { console.warn('[OSIRIS] Wikidata fetch error:', e instanceof Error ? e.message : e); }
110+ return null;
111+ })(),
112+ ]);
113+
114+ const countryData = countryResult.status === 'fulfilled' ? countryResult.value : null;
115+ const wikiSummary = wikiResult.status === 'fulfilled' ? wikiResult.value : null;
116+ const headOfState = hosResult.status === 'fulfilled' ? hosResult.value : null;
117+
118+ return NextResponse.json({
119+ coordinates: { lat, lng },
120+ location: locationInfo,
121+ country: countryData ? {
122+ name: countryData.name?.common,
123+ official_name: countryData.name?.official,
124+ capital: countryData.capital?.[0],
125+ population: countryData.population,
126+ area: countryData.area,
127+ region: countryData.region,
128+ subregion: countryData.subregion,
129+ languages: countryData.languages ? Object.values(countryData.languages) : [],
130+ currencies: countryData.currencies
131+ ? Object.entries(countryData.currencies).map(([code, info]: [string, any]) => `${info.name} (${info.symbol || code})`)
132+ : [],
133+ flag: countryData.flag,
134+ flag_url: countryData.flags?.svg,
135+ timezones: countryData.timezones,
136+ } : null,
137+ head_of_state: headOfState,
138+ wikipedia: wikiSummary,
139+ timestamp: new Date().toISOString(),
140+ }, {
141+ headers: {
142+ 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=7200',
143+ },
144+ });
145+ } catch (error) {
146+ console.error('Region dossier error:', error);
147+ return NextResponse.json({ error: 'Failed to fetch region data' }, { status: 500 });
148+ }
149+}
modified src/app/api/satellites/route.ts +2 −0
@@ -1,3 +1,4 @@
1+export const revalidate = 600;
12 import { NextResponse } from 'next/server';
23
34 /**
@@ -243,3 +244,4 @@
243244 return NextResponse.json({ satellites: [], error: 'Failed to fetch satellite data' }, { status: 500 });
244245 }
245246 }
247+
modified src/app/api/sentinel/route.ts +135 −135
@@ -1,135 +1,135 @@
1-import { NextResponse } from 'next/server';
2-
3-// Sentinel-1 SAR Satellite — STAC Catalog via Element84 Earth Search + Copernicus fallback
4-export async function GET(req: Request) {
5- const { searchParams } = new URL(req.url);
6- const lat = parseFloat(searchParams.get('lat') || '0');
7- const lng = parseFloat(searchParams.get('lng') || '0');
8- const radius = parseFloat(searchParams.get('radius') || '2');
9- const days = parseInt(searchParams.get('days') || '30'); // Expanded to 30 days for more results
10-
11- if (isNaN(lat) || isNaN(lng)) {
12- return NextResponse.json({ error: 'Missing lat/lng parameters' }, { status: 400 });
13- }
14-
15- try {
16- const bbox = [lng - radius, lat - radius, lng + radius, lat + radius];
17- const now = new Date();
18- const from = new Date(now.getTime() - days * 86400000);
19- const datetime = `${from.toISOString().split('.')[0]}Z/${now.toISOString().split('.')[0]}Z`;
20-
21- let scenes: any[] = [];
22- let source = '';
23- let total = 0;
24-
25- // Source 1: Element84 Earth Search v1
26- try {
27- const res = await fetch('https://earth-search.aws.element84.com/v1/search', {
28- method: 'POST',
29- headers: { 'Content-Type': 'application/json' },
30- signal: AbortSignal.timeout(12000),
31- body: JSON.stringify({
32- collections: ['sentinel-1-grd'],
33- bbox,
34- datetime,
35- limit: 20,
36- sortby: [{ field: 'datetime', direction: 'desc' }],
37- }),
38- });
39- if (res.ok) {
40- const data = await res.json();
41- scenes = (data.features || []).map(formatScene);
42- total = data.numberMatched || scenes.length;
43- source = 'element84';
44- }
45- } catch (e) { console.warn('[OSIRIS] Suppressed error:', e instanceof Error ? e.message : e); }
46-
47- // Source 2: Try sentinel-2 if sentinel-1 is empty
48- if (scenes.length === 0) {
49- try {
50- const res = await fetch('https://earth-search.aws.element84.com/v1/search', {
51- method: 'POST',
52- headers: { 'Content-Type': 'application/json' },
53- signal: AbortSignal.timeout(12000),
54- body: JSON.stringify({
55- collections: ['sentinel-2-l2a'],
56- bbox,
57- datetime,
58- limit: 20,
59- sortby: [{ field: 'datetime', direction: 'desc' }],
60- }),
61- });
62- if (res.ok) {
63- const data = await res.json();
64- scenes = (data.features || []).map(formatScene);
65- total = data.numberMatched || scenes.length;
66- source = 'element84-s2';
67- }
68- } catch (e) { console.warn('[OSIRIS] Suppressed error:', e instanceof Error ? e.message : e); }
69- }
70-
71- // Source 3: Copernicus STAC fallback
72- if (scenes.length === 0) {
73- try {
74- const fallbackRes = await fetch('https://catalogue.dataspace.copernicus.eu/stac/search', {
75- method: 'POST',
76- headers: { 'Content-Type': 'application/json' },
77- signal: AbortSignal.timeout(12000),
78- body: JSON.stringify({
79- collections: ['SENTINEL-1'],
80- bbox,
81- datetime,
82- limit: 10,
83- }),
84- });
85- if (fallbackRes.ok) {
86- const data = await fallbackRes.json();
87- scenes = (data.features || []).map(formatScene);
88- total = data.numberMatched || scenes.length;
89- source = 'copernicus';
90- }
91- } catch (e) { console.warn('[OSIRIS] Suppressed error:', e instanceof Error ? e.message : e); }
92- }
93-
94- return NextResponse.json({
95- source,
96- scenes,
97- total,
98- bbox,
99- datetime,
100- timestamp: new Date().toISOString(),
101- }, {
102- headers: { 'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600' },
103- });
104- } catch (e) {
105- return NextResponse.json({ error: 'Sentinel lookup failed', scenes: [] }, { status: 500 });
106- }
107-}
108-
109-function formatScene(feature: any) {
110- const props = feature.properties || {};
111- return {
112- id: feature.id,
113- datetime: props.datetime,
114- platform: props.platform || props['sar:instrument_mode'] || 'Sentinel',
115- orbit: props['sat:orbit_state'] || props.orbitDirection,
116- polarization: props['sar:polarizations'] || props.polarisation,
117- mode: props['sar:instrument_mode'] || props.productType,
118- resolution: props['sar:resolution_range'] || null,
119- pass_direction: props['sat:relative_orbit'] || null,
120- cloud_cover: props['eo:cloud_cover'] ?? null,
121- bbox: feature.bbox,
122- thumbnail: feature.assets?.thumbnail?.href || null,
123- preview: feature.assets?.preview?.href || null,
124- geometry_type: feature.geometry?.type,
125- area_km2: feature.bbox ? estimateArea(feature.bbox) : null,
126- };
127-}
128-
129-function estimateArea(bbox: number[]): number {
130- if (bbox.length < 4) return 0;
131- const [minLng, minLat, maxLng, maxLat] = bbox;
132- const latDiff = Math.abs(maxLat - minLat) * 111;
133- const lngDiff = Math.abs(maxLng - minLng) * 111 * Math.cos((minLat + maxLat) / 2 * Math.PI / 180);
134- return Math.round(latDiff * lngDiff);
135-}
1+import { NextResponse } from 'next/server';
2+
3+// Sentinel-1 SAR Satellite — STAC Catalog via Element84 Earth Search + Copernicus fallback
4+export async function GET(req: Request) {
5+ const { searchParams } = new URL(req.url);
6+ const lat = parseFloat(searchParams.get('lat') || '0');
7+ const lng = parseFloat(searchParams.get('lng') || '0');
8+ const radius = parseFloat(searchParams.get('radius') || '2');
9+ const days = parseInt(searchParams.get('days') || '30'); // Expanded to 30 days for more results
10+
11+ if (isNaN(lat) || isNaN(lng)) {
12+ return NextResponse.json({ error: 'Missing lat/lng parameters' }, { status: 400 });
13+ }
14+
15+ try {
16+ const bbox = [lng - radius, lat - radius, lng + radius, lat + radius];
17+ const now = new Date();
18+ const from = new Date(now.getTime() - days * 86400000);
19+ const datetime = `${from.toISOString().split('.')[0]}Z/${now.toISOString().split('.')[0]}Z`;
20+
21+ let scenes: any[] = [];
22+ let source = '';
23+ let total = 0;
24+
25+ // Source 1: Element84 Earth Search v1
26+ try {
27+ const res = await fetch('https://earth-search.aws.element84.com/v1/search', { next: { revalidate: 3600 },
28+ method: 'POST',
29+ headers: { 'Content-Type': 'application/json' },
30+ signal: AbortSignal.timeout(12000),
31+ body: JSON.stringify({
32+ collections: ['sentinel-1-grd'],
33+ bbox,
34+ datetime,
35+ limit: 20,
36+ sortby: [{ field: 'datetime', direction: 'desc' }],
37+ }),
38+ });
39+ if (res.ok) {
40+ const data = await res.json();
41+ scenes = (data.features || []).map(formatScene);
42+ total = data.numberMatched || scenes.length;
43+ source = 'element84';
44+ }
45+ } catch (e) { console.warn('[OSIRIS] Suppressed error:', e instanceof Error ? e.message : e); }
46+
47+ // Source 2: Try sentinel-2 if sentinel-1 is empty
48+ if (scenes.length === 0) {
49+ try {
50+ const res = await fetch('https://earth-search.aws.element84.com/v1/search', { next: { revalidate: 3600 },
51+ method: 'POST',
52+ headers: { 'Content-Type': 'application/json' },
53+ signal: AbortSignal.timeout(12000),
54+ body: JSON.stringify({
55+ collections: ['sentinel-2-l2a'],
56+ bbox,
57+ datetime,
58+ limit: 20,
59+ sortby: [{ field: 'datetime', direction: 'desc' }],
60+ }),
61+ });
62+ if (res.ok) {
63+ const data = await res.json();
64+ scenes = (data.features || []).map(formatScene);
65+ total = data.numberMatched || scenes.length;
66+ source = 'element84-s2';
67+ }
68+ } catch (e) { console.warn('[OSIRIS] Suppressed error:', e instanceof Error ? e.message : e); }
69+ }
70+
71+ // Source 3: Copernicus STAC fallback
72+ if (scenes.length === 0) {
73+ try {
74+ const fallbackRes = await fetch('https://catalogue.dataspace.copernicus.eu/stac/search', { next: { revalidate: 3600 },
75+ method: 'POST',
76+ headers: { 'Content-Type': 'application/json' },
77+ signal: AbortSignal.timeout(12000),
78+ body: JSON.stringify({
79+ collections: ['SENTINEL-1'],
80+ bbox,
81+ datetime,
82+ limit: 10,
83+ }),
84+ });
85+ if (fallbackRes.ok) {
86+ const data = await fallbackRes.json();
87+ scenes = (data.features || []).map(formatScene);
88+ total = data.numberMatched || scenes.length;
89+ source = 'copernicus';
90+ }
91+ } catch (e) { console.warn('[OSIRIS] Suppressed error:', e instanceof Error ? e.message : e); }
92+ }
93+
94+ return NextResponse.json({
95+ source,
96+ scenes,
97+ total,
98+ bbox,
99+ datetime,
100+ timestamp: new Date().toISOString(),
101+ }, {
102+ headers: { 'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600' },
103+ });
104+ } catch (e) {
105+ return NextResponse.json({ error: 'Sentinel lookup failed', scenes: [] }, { status: 500 });
106+ }
107+}
108+
109+function formatScene(feature: any) {
110+ const props = feature.properties || {};
111+ return {
112+ id: feature.id,
113+ datetime: props.datetime,
114+ platform: props.platform || props['sar:instrument_mode'] || 'Sentinel',
115+ orbit: props['sat:orbit_state'] || props.orbitDirection,
116+ polarization: props['sar:polarizations'] || props.polarisation,
117+ mode: props['sar:instrument_mode'] || props.productType,
118+ resolution: props['sar:resolution_range'] || null,
119+ pass_direction: props['sat:relative_orbit'] || null,
120+ cloud_cover: props['eo:cloud_cover'] ?? null,
121+ bbox: feature.bbox,
122+ thumbnail: feature.assets?.thumbnail?.href || null,
123+ preview: feature.assets?.preview?.href || null,
124+ geometry_type: feature.geometry?.type,
125+ area_km2: feature.bbox ? estimateArea(feature.bbox) : null,
126+ };
127+}
128+
129+function estimateArea(bbox: number[]): number {
130+ if (bbox.length < 4) return 0;
131+ const [minLng, minLat, maxLng, maxLat] = bbox;
132+ const latDiff = Math.abs(maxLat - minLat) * 111;
133+ const lngDiff = Math.abs(maxLng - minLng) * 111 * Math.cos((minLat + maxLat) / 2 * Math.PI / 180);
134+ return Math.round(latDiff * lngDiff);
135+}
modified src/app/api/space-weather/route.ts +2 −0
@@ -1,3 +1,4 @@
1+export const revalidate = 900;
12 import { NextResponse } from 'next/server';
23
34 /**
@@ -86,3 +87,4 @@
8687 }, { status: 500 });
8788 }
8889 }
90+
modified src/app/api/weather/route.ts +2 −0
@@ -1,3 +1,4 @@
1+export const revalidate = 900;
12 import { NextResponse } from 'next/server';
23
34 /**
@@ -76,3 +77,4 @@
7677 return NextResponse.json({ events: [], error: 'Failed to fetch NASA EONET data' }, { status: 500 });
7778 }
7879 }
80+
modified src/middleware.ts +4 −2
@@ -14,8 +14,10 @@
1414 return NextResponse.next();
1515 }
1616
17- // request.ip is not available in all Next.js runtimes, safely fallback
18- const ip = request.headers.get('x-forwarded-for') || 'unknown';
17+ // request.ip is populated securely by the hosting platform (Vercel).
18+ // Fallback to the leftmost x-forwarded-for if running locally/custom node server.
19+ const forwarded = request.headers.get('x-forwarded-for');
20+ const ip = (request as any).ip || (forwarded ? forwarded.split(',')[0].trim() : 'unknown');
1921 const now = Date.now();
2022
2123 let limitData = rateLimitMap.get(ip);