Intelligence, Advanced Charting & Trading Platform

1 /**
2 * Narrow, read-only ECB repository for /api/v2/history.
3 * Secret is server-side only; the existing PostgreSQL view enforces the scope.
4 * No OHLC reads and no DDL/INSERT/UPDATE/DELETE operations.
5 */
6 const UNITS=Object.freeze({EUR_USD_ECB:"USD_PER_EUR",EUR_GBP_ECB:"GBP_PER_EUR",EUR_CHF_ECB:"CHF_PER_EUR"});
7 const QUOTES=Object.freeze({EUR_USD_ECB:"USD",EUR_GBP_ECB:"GBP",EUR_CHF_ECB:"CHF"});
8 const SERIES=Object.freeze({EUR_USD_ECB:"EXR.D.USD.EUR.SP00.A",EUR_GBP_ECB:"EXR.D.GBP.EUR.SP00.A",EUR_CHF_ECB:"EXR.D.CHF.EUR.SP00.A"});
9 const PROVIDER_KIND="daily_reference_point_not_ohlc";
10 const has=(o,k)=>Object.prototype.hasOwnProperty.call(o,k);
11 export function buildNeonEcbHistoryLookup({databaseUrl,fetchImpl=fetch}={}){
12 if(typeof databaseUrl!=="string"||!databaseUrl)throw Error("history_reader_not_configured");
13 let uri;
14 try{uri=new URL(databaseUrl)}catch{throw Error("history_reader_not_configured")}
15 if(!["postgres:","postgresql:"].includes(uri.protocol)||
16 !/^[a-z0-9-]+(?:\.[a-z0-9-]+)*\.neon\.tech$/i.test(uri.hostname)||
17 !uri.username||!uri.password||uri.pathname!=="/neondb")throw Error("history_reader_not_configured");
18 if(decodeURIComponent(uri.username)!=="chartnova_history_ro")throw Error("restricted_history_reader_required");
19 if(typeof fetchImpl!=="function")throw Error("invalid_transport");
20 const endpoint="https://"+uri.hostname+"/sql";
21 return async function lookup(query){
22 if(!query||query.dataKind!=="reference_point"||query.timeframe!=="1d"||
23 !has(UNITS,query.symbol)||!Number.isSafeInteger(query.limit)||query.limit<1||query.limit>5000)return null;
24 const from=Date.parse(query.from+"T00:00:00Z"),to=Date.parse(query.to+"T00:00:00Z");
25 if(!Number.isFinite(from)||!Number.isFinite(to)||from>to||to-from>400*86400000)throw Error("invalid_window");
26 const limit=query.limit+1;
27 const sql=[
28 "SELECT symbol,quote_asset,source,observation_at,price,quality,flags",
29 "FROM public.chartnova_history_public",
30 "WHERE symbol=$1",
31 " AND observation_at >= $2::timestamptz",
32 " AND observation_at < $3::timestamptz",
33 " AND ($4::timestamptz IS NULL OR observation_at < $4::timestamptz)",
34 "ORDER BY observation_at DESC",
35 "LIMIT $5::integer"
36 ].join("\n");
37 const params=[query.symbol,new Date(from).toISOString(),new Date(to+86400000).toISOString(),query.cursor??null,limit];
38 const response=await fetchImpl(endpoint,{
39 method:"POST",headers:{
40 "content-type":"application/json",
41 "Neon-Connection-String":databaseUrl,
42 "Neon-Raw-Text-Output":"true",
43 "Neon-Array-Mode":"false",
44 },
45 body:JSON.stringify({query:sql,params}),
46 signal:AbortSignal.timeout(10000),
47 });
48 if(!response.ok)throw Error("history_storage_unavailable");
49 const json=await response.json();
50 if(!Array.isArray(json?.rows)||json.rows.length>limit)throw Error("history_storage_invalid_response");
51 const rows=json.rows.map(row=>{
52 const when=Date.parse(row?.observation_at??"");
53 if(!Number.isFinite(when))throw Error("history_storage_provenance_rejected");
54 const day=new Date(when).toISOString().slice(0,10);
55 const price=String(row.price??"");
56 if(row.symbol!==query.symbol||row.quote_asset!==QUOTES[query.symbol]||
57 row.source!=="ecb_exr"||
58 !/^(?:0|[1-9]\d{0,19})(?:\.\d{1,16})?$/.test(price)||
59 !(Number(price)>0)||!["GOOD","DEGRADED","STALE"].includes(row.quality)||
60 row.flags?.data_kind!==PROVIDER_KIND||row.flags?.observation_date!==day||
61 row.flags?.source_series!==SERIES[query.symbol]||
62 row.flags?.license!=="ECB/ESCB open statistics; attribution required"){
63 throw Error("history_storage_provenance_rejected");
64 }
65 return {symbol:query.symbol,unit:UNITS[query.symbol],
66 sourceTimestamp:new Date(when).toISOString(),price,quality:row.quality};
67 });
68 if(rows.some((r,i)=>i>0&&r.sourceTimestamp>=rows[i-1].sourceTimestamp))throw Error("history_storage_out_of_order");
69 return {rights:"approved_public",source:"ECB",dataKind:"reference_point",
70 attribution:"Source: European Central Bank (ECB), EXR daily euro foreign exchange reference rates",
71 unit:UNITS[query.symbol],rows,delayed:true};
72 };
73 }