Intelligence, Advanced Charting & Trading Platform
feature/chartnova-multimarket-chart-ws-foundation
diagnostics/chartnova-blank-screen-2026-10-15
diagnostics/chartnova-stage2-v27-preview-2026-10-15
docs/chartnova-stage1-reconcile-manifest-2026-10-15
feature/chartnova-ios-widget
feature/chartnova-light-catalog-lazy-series-2026-10-15
feature/chartnova-market-terminal
feature/chartnova-multimarket-chart-ws-foundation
feature/chartnova-neon-direct-history
feature/chartnova-neon-history
feature/paper-trading-risk-controls-2026-10-14
fix/alpha-vantage-live-payload
fix/chartnova-progressive-loading-2026-10-15
fix/live-proof-runner-cwd-2026-10-14
foundation/phase-0
foundation/postgres-core
main
ops/chartnova-emergency-rollback-2026-10-15
phase-1/candle-builder
phase-1/data-proof-artifact
phase-1/data-proof-metrics
phase-1/data-proof-report
phase-1/external-gates-state
phase-1/gold-api-fallback
phase-1/ingestion-pipeline
phase-1/live-proof-runner
phase-1/market-calendar
phase-1/market-domain
phase-1/neon-live-proof
phase-1/persistence-contract
phase-1/postgres-ci
phase-1/provider-adapters
phase-1/provider-recovery
phase-1/quality-propagation
phase-1/spike-detection
phase-1/xau-provider-adapter
risk/chartnova-alert-runtime-atomic-2026-10-22
risk/chartnova-atomic-outbox-2026-10-22
risk/chartnova-seven-track-safety-2026-10-21
safety/p0-triage-2026-10-13
| 1 | /** |
| 2 | * ChartNova WebSocket edge gateway (Cloudflare Durable Object design). |
| 3 | * NOT wired to the live velyqor-preview Worker. Deploy only after enabling |
| 4 | * Durable Objects, installing a server-side publish secret, and completing E2E tests. |
| 5 | * No upstream provider is connected; this code must never emit demo prices. |
| 6 | */ |
| 7 | import {canonicalReferencePoint,canonicalSourceCandle,transportFrame,DATA_KIND} from "../../packages/market-feed/src/contracts.mjs"; |
| 8 | import {validateSubscribeCommand} from "../../packages/market-feed/src/realtime-protocol.mjs"; |
| 9 | |
| 10 | const allowedOrigins=new Set(["https://app.chartnova.ir","https://chartnova.ir"]); |
| 11 | const json=(obj,status=200)=>Response.json(obj,{status,headers:{"cache-control":"no-store"}}); |
| 12 | const maxBody=16_384; |
| 13 | function sameSecret(a,b){ |
| 14 | if(typeof a!=="string"||typeof b!=="string"||b.length<32||a.length!==b.length)return false; |
| 15 | // Avoid direct string equality's early return. No secret is logged. |
| 16 | let acc=0;for(let i=0;i<b.length;i++)acc|=a.charCodeAt(i)^b.charCodeAt(i); |
| 17 | return acc===0; |
| 18 | } |
| 19 | export default { |
| 20 | async fetch(request,env){ |
| 21 | const url=new URL(request.url); |
| 22 | if(url.pathname==="/ws/market"){ |
| 23 | if(request.method!=="GET"||request.headers.get("Upgrade")?.toLowerCase()!=="websocket")return json({error:"websocket_upgrade_required"},426); |
| 24 | if(!allowedOrigins.has(request.headers.get("Origin")))return json({error:"origin_forbidden"},403); |
| 25 | if(!env.CHARTNOVA_REALTIME_HUB)return json({error:"gateway_not_configured"},503); |
| 26 | const stub=env.CHARTNOVA_REALTIME_HUB.get(env.CHARTNOVA_REALTIME_HUB.idFromName("public-market-v1")); |
| 27 | return stub.fetch(request); |
| 28 | } |
| 29 | if(url.pathname==="/internal/market-publish"&&request.method==="POST"){ |
| 30 | if(!sameSecret(request.headers.get("x-chartnova-publish-token"),env.CHARTNOVA_REALTIME_PUBLISH_TOKEN))return json({error:"unauthorized"},401); |
| 31 | if(Number(request.headers.get("content-length")||0)>maxBody)return json({error:"payload_too_large"},413); |
| 32 | if(!env.CHARTNOVA_REALTIME_HUB)return json({error:"gateway_not_configured"},503); |
| 33 | let record; |
| 34 | try{ |
| 35 | const text=await request.text(); |
| 36 | if(text.length>maxBody)throw Error("oversize"); |
| 37 | const item=JSON.parse(text); |
| 38 | record=item?.dataKind===DATA_KIND.REFERENCE?canonicalReferencePoint(item):canonicalSourceCandle(item); |
| 39 | // Never send unknown, invalid or unlicensed provider observations. |
| 40 | if(record.rights!=="approved_public"||record.quality==="INVALID")return json({error:"not_licensed_for_publication"},403); |
| 41 | }catch{return json({error:"invalid_market_record"},400)} |
| 42 | const stub=env.CHARTNOVA_REALTIME_HUB.get(env.CHARTNOVA_REALTIME_HUB.idFromName("public-market-v1")); |
| 43 | return stub.fetch(new Request("https://internal.chartnova.invalid/_publish",{ |
| 44 | method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(record), |
| 45 | })); |
| 46 | } |
| 47 | return json({error:"not_found"},404); |
| 48 | } |
| 49 | }; |
| 50 | // Durable Object Hibernation pattern; use Worker routing above as the only public entry. |
| 51 | export class ChartNovaRealtimeHub { |
| 52 | constructor(ctx,env){this.ctx=ctx;this.env=env;} |
| 53 | async fetch(request){ |
| 54 | const pathname=new URL(request.url).pathname; |
| 55 | if(pathname==="/ws/market"){ |
| 56 | if(request.headers.get("Upgrade")?.toLowerCase()!=="websocket")return json({error:"upgrade_required"},426); |
| 57 | if(this.ctx.getWebSockets().length>=500)return json({error:"connection_limit"},503); |
| 58 | const pair=new WebSocketPair(); |
| 59 | const [client,server]=Object.values(pair); |
| 60 | this.ctx.acceptWebSocket(server); |
| 61 | server.serializeAttachment({symbols:[],timeframe:"1m"}); |
| 62 | return new Response(null,{status:101,webSocket:client}); |
| 63 | } |
| 64 | if(pathname==="/_publish"&&request.method==="POST"){ |
| 65 | let item; |
| 66 | try{ |
| 67 | const raw=await request.text(); |
| 68 | if(raw.length>maxBody)throw Error("Too large"); |
| 69 | item=JSON.parse(raw); |
| 70 | item=item.dataKind===DATA_KIND.REFERENCE?canonicalReferencePoint(item):canonicalSourceCandle(item); |
| 71 | if(item.rights!=="approved_public"||item.quality==="INVALID")return json({error:"not_licensed"},403); |
| 72 | }catch{return json({error:"invalid_data"},400)} |
| 73 | const channel=item.symbol+"|"+(item.timeframe??"point")+"|"+item.source; |
| 74 | // Atomic sequence counters survive DO hibernation / restarts. |
| 75 | const sequence=await this.ctx.storage.transaction(async(tx)=>{ |
| 76 | const key="sequence:"+channel; |
| 77 | const current=(await tx.get(key))??0; |
| 78 | const next=current+1; |
| 79 | await tx.put(key,next); |
| 80 | return next; |
| 81 | }); |
| 82 | const frame=transportFrame(item,sequence,new Date().toISOString()); |
| 83 | let delivered=0; |
| 84 | for(const client of this.ctx.getWebSockets()){ |
| 85 | const state=client.deserializeAttachment(); |
| 86 | if(!state?.symbols?.includes(item.symbol))continue; |
| 87 | if(item.dataKind===DATA_KIND.CANDLE&&state.timeframe!==item.timeframe)continue; |
| 88 | try{client.send(JSON.stringify(frame));delivered++}catch{} |
| 89 | } |
| 90 | return json({ok:true,delivered,sequence}); |
| 91 | } |
| 92 | return json({error:"not_found"},404); |
| 93 | } |
| 94 | async webSocketMessage(ws,message){ |
| 95 | try{ |
| 96 | const command=validateSubscribeCommand(message); |
| 97 | ws.serializeAttachment({symbols:command.symbols,timeframe:command.timeframe}); |
| 98 | ws.send(JSON.stringify({type:"subscribed",version:1,symbols:command.symbols,timeframe:command.timeframe, |
| 99 | note:"Historical snapshots must be fetched via REST after any reconnect/gap."})); |
| 100 | }catch{ |
| 101 | try{ws.send(JSON.stringify({type:"error",code:"invalid_subscription"}))}catch{} |
| 102 | } |
| 103 | } |
| 104 | async webSocketClose(ws,code,reason){try{ws.close(code,reason)}catch{}} |
| 105 | } |