diff --git a/CHANGELOG.md b/CHANGELOG.md index ea5d320..df9f47c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,34 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels, Open buttons or map highlights. + +- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency. Local scrubbing adds no backbone-haul line, and distributed ingress no longer produces unrelated or repeated latency messages. + +- The NOC no longer shows the generic attack-rate note for networks without gaming customers. + +- Gaming customers now scale normal-mode DDoS sizes from three times the no-gaming average with one customer to eight times with 50. Adding more gamers continues to increase attack sizes, while frequency still rises gradually toward seven attacks per week. Flood Season keeps its existing escalation. + +- Normal-mode DDoS attacks now vary much more in size, with a 2% chance of a much larger flood. The long-run average still scales with demand, customer level and gaming customers; Flood Season keeps its existing size distribution and escalation. + +- Game server and cloud gaming customers now carry a “Gaming attracts attacks” note on their offers and customer lists, so you can see the DDoS risk before signing them. + +- Live attacks now show how much traffic Flowspec actually drops at the ingress routers. Routers without TCAM no longer claim to filter attacks, mixed router capabilities are called out, and Flowspec drops are counted separately from other edge filters. + +- Normal networks without gaming customers now average half a DDoS attack per week, with attacks ten times smaller than the ordinary baseline. Gaming customers gradually raise attack sizes and the expected rate toward seven attacks per week as your level and customer count grow. The size calculation accounts for the smaller RackNet and TeamSpooked floods so signing a gamer increases the overall average size. Flood Season keeps its separate escalation. + +- Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec, and their size stays within one third of the ordinary attack range at your current scale. + +- Gaming customers bring larger, longer and more frequent DDoS attacks as your level and customer count grow, with overlapping floods, at most 14 starts in any seven days and durations up to seven days. Attacks arrive across transit and peering ports in different regions, following normal traffic shares. Attack bandwidth grows with the whole network, with no fixed bandwidth ceiling. + +- Flood Season keeps sending larger, more frequent attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off. + +- Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through in its existing status lines. Bandwidth uses the usual Gbps and Tbps units, with no duplicate summary. “After upstream scrubbing” appears only while upstream scrubbing is active. Scrubbing lines show the city, current use and compact capacity, such as “Scrubbing in Frankfurt: 30.2 Gbps / 100G”. + +- DDoS bandwidth now adds up: upstream scrubbing, edge filters and scrubbing centers work in sequence. The NOC uses the same figures as traffic routing, including floods that cannot reach a remote center. + +- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter needs other defences. + - Pick a peering policy in the peering inbox: Open to all, Selective or Closed. Open accepts every request and keeps the route servers; Selective gets fewer requests but you answer them yourself and request peers at each exchange, without route servers; Closed gets no requests, and customers hear you are hard to reach. The inbox also gets a button to raise all max-prefix limits at once. - Brazil is slimmer: 15 small cities that sat right next to bigger ones are gone from new games, leaving 25 in Brazil. A small city no longer crowds a bigger one in the same country unless it is a cable landing or a capital. Saved games keep their POPs in those cities, and the Order and Progress scenario now asks for 15 IX.brrr ports instead of 20. ## [1.33.0] — 2026-10-27 diff --git a/site/i18n/fr.js b/site/i18n/fr.js index c06021c..7fcfb8f 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -923,10 +923,7 @@ "Live attack: {city}":"Attaque en cours : {city}", "{size} · {vec}{entry} · {n}d left":"{size} · {vec}{entry} · {n} j restants", "Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.":"Blackholé : les déchets ont disparu, et {city} aussi. L’attaque a obtenu ce qu’elle voulait.", -"Reaching your network: {g}":"Ce qui atteint ton réseau : {g}", "On-demand scrubbing diverting, live in {n}d":"Scrubbing à la demande en cours de redirection, actif dans {n} j", -"{tier} scrubbing in {city} is cleaning it":"Le scrubbing {tier} à {city} le nettoie", -"{net} is scrubbing it upstream (clean-pipe)":"{net} le nettoie en amont (clean-pipe)", "Contained on your sacrificial {net} PNI":"Contenu sur ton PNI sacrificiel {net}", "IX blackhole on ✓":"Blackhole IX actif ✓", "IX blackhole ~half honour it":"Blackhole IX ~la moitié le respecte", @@ -935,10 +932,7 @@ "Sacrificial choke ✓":"Goulot sacrificiel ✓", "Make sacrificial contains floods · ½ capacity":"Rendre sacrificiel contient les floods · ½ capacité", "No scrubbing center":"Pas de centre de scrubbing", -"Flowspec on your {model} is dropping {vec} at the edge":"Flowspec sur ton {model} élimine le trafic {vec} en bordure", -"Flowspec on your {model} trims {vec}, but its TCAM is small":"Flowspec sur ton {model} rogne le trafic {vec}, mais sa TCAM est petite", -"Your {model} here has no Flowspec TCAM":"Ton {model} ici n’a pas de TCAM Flowspec", -"Flowspec cannot catch an {vec} (application layer)":"Flowspec ne peut pas arrêter un {vec} (couche applicative)", +"Flowspec cannot catch {vec}":"Flowspec ne peut pas arrêter {vec}", "Stop blackholing":"Arrêter le blackholing", "Blackhole the target (RTBH)":"Blackholer la cible (RTBH)", "HackBack 3000™ $20k":"HackBack 3000™ $20k", @@ -2604,8 +2598,6 @@ "Attack hauled to scrubbing in {city}":"Attaque acheminée vers le scrubbing de {city}", "Wants a scrubbing center on its own continent, so attacks are not hauled across an ocean":"Veut un centre de scrubbing sur son continent, pour que les attaques ne traversent pas un océan", "Your backbone can only haul {g} of it to {city}: the rest is not scrubbed":"Ton backbone ne peut en acheminer que {g} jusqu’à {city} : le reste n’est pas nettoyé", -"{tier} scrubbing in {city} is cleaning it, hauled over your backbone (+{ms} ms)":"Le scrubbing {tier} à {city} le nettoie, acheminé par ton backbone (+{ms} ms)", -"Your scrubbing centers are full: {g} leaks past":"Tes centres de scrubbing sont pleins : {g} passent quand même", "Attacks go to your nearest scrubbing center. From here that is {city}, {km} km away: the flood rides your backbone there and back, which adds latency, and whatever your links cannot carry is not scrubbed. A center here cleans attacks on the spot.":"Les attaques vont vers ton centre de scrubbing le plus proche. D’ici, c’est {city}, à {km} km : le flot traverse ton backbone aller et retour, ce qui ajoute de la latence, et ce que tes liens ne peuvent pas porter n’est pas nettoyé. Un centre ici nettoie les attaques sur place.", "attacks on {city} are hauled to {to} for scrubbing: +{ms} ms":"les attaques sur {city} sont acheminées vers {to} pour le scrubbing : +{ms} ms", "Scrubbing centers":"Centres de scrubbing", @@ -2941,4 +2933,23 @@ "Raised {n} max-prefix limits.
{k} of them were route leaks. They are in the NOC now.":"{n} limites max-prefix relevées.
{k} d’entre elles étaient des fuites de routes. Elles sont dans le NOC maintenant.", "Raised {n} max-prefix limits.
All growth, no leaks. Lucky.":"{n} limites max-prefix relevées.
Que de la croissance, aucune fuite. Chanceux.", "Off while your peering policy is {pol}":"Désactivé tant que votre politique de peering est {pol}", +"Memcached amplification":"Amplification Memcached", +"ACK flood":"Flood ACK", +"Edge filters dropping: {g}":"Filtres en bordure : {g} supprimés", +"{g} is leaking through":"{g} passent encore", +"Attack fully mitigated":"Attaque entièrement neutralisée", +"Scrubbing centers unavailable or at capacity":"Centres de scrubbing indisponibles ou saturés", +"Distributed ingress":"Arrivée distribuée", +", across {n} transit and peering ports":", via {n} ports de transit et de peering", +"No scrubbing needed after edge mitigation":"Aucun scrubbing nécessaire après la protection en bordure", +"RackNet":"RackNet", +"TeamSpooked":"TeamSpooked", +"Scrubbing in {city}: {used} / {capacity}":"Scrubbing à {city} : {used} / {capacity}", +"This attack: {g}":"Cette attaque : {g}", +"Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)":"Trafic de scrubbing acheminé par ton backbone : {city} → {to} (+{ms} ms)", +"After upstream scrubbing: {g}":"Après le scrubbing en amont : {g}", +"No Flowspec filtering: ingress routers have no TCAM":"Aucun filtrage Flowspec : les routeurs d’entrée n’ont pas de TCAM", +"Flowspec dropping: {g}; some ingress routers have no TCAM":"Flowspec supprime {g} ; certains routeurs d’entrée n’ont pas de TCAM", +"Flowspec dropping: {g}":"Flowspec supprime {g}", +"Gaming attracts attacks":"Le gaming attire les attaques", }; diff --git a/site/i18n/it.js b/site/i18n/it.js index be339b0..ef9450b 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -924,10 +924,7 @@ "Live attack: {city}":"Attacco in corso: {city}", "{size} · {vec}{entry} · {n}d left":"{size} · {vec}{entry} · {n}g rimasti", "Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.":"In buco nero: la spazzatura è sparita, e anche {city}. L’attacco ha ottenuto ciò che voleva.", -"Reaching your network: {g}":"Arriva alla tua rete: {g}", "On-demand scrubbing diverting, live in {n}d":"Scrubbing on-demand in deviazione, attivo tra {n}g", -"{tier} scrubbing in {city} is cleaning it":"Lo scrubbing {tier} a {city} lo sta pulendo", -"{net} is scrubbing it upstream (clean-pipe)":"{net} lo sta ripulendo a monte (clean-pipe)", "Contained on your sacrificial {net} PNI":"Contenuto sulla tua PNI sacrificale {net}", "IX blackhole on ✓":"Blackhole IX attivo ✓", "IX blackhole ~half honour it":"Blackhole IX ~metà lo rispetta", @@ -936,10 +933,7 @@ "Sacrificial choke ✓":"Strozzatura sacrificale ✓", "Make sacrificial contains floods · ½ capacity":"Rendi sacrificale contiene i flood · ½ capacità", "No scrubbing center":"Nessun centro di scrubbing", -"Flowspec on your {model} is dropping {vec} at the edge":"Il Flowspec sul tuo {model} sta scartando {vec} all’edge", -"Flowspec on your {model} trims {vec}, but its TCAM is small":"Il Flowspec sul tuo {model} lima {vec}, ma la sua TCAM è piccola", -"Your {model} here has no Flowspec TCAM":"Il tuo {model} qui non ha TCAM per il Flowspec", -"Flowspec cannot catch an {vec} (application layer)":"Flowspec non può fermare un {vec} (livello applicativo)", +"Flowspec cannot catch {vec}":"Flowspec non può fermare {vec}", "Stop blackholing":"Togli il buco nero", "Blackhole the target (RTBH)":"Metti il bersaglio in buco nero (RTBH)", "HackBack 3000™ $20k":"HackBack 3000™ $20k", @@ -2607,8 +2601,6 @@ "Attack hauled to scrubbing in {city}":"Attacco portato allo scrubbing di {city}", "Wants a scrubbing center on its own continent, so attacks are not hauled across an ocean":"Vuole un centro di scrubbing nel suo continente, così gli attacchi non attraversano un oceano", "Your backbone can only haul {g} of it to {city}: the rest is not scrubbed":"Il tuo backbone riesce a portarne solo {g} a {city}: il resto non viene pulito", -"{tier} scrubbing in {city} is cleaning it, hauled over your backbone (+{ms} ms)":"Lo scrubbing {tier} a {city} lo sta pulendo, portato lì sul tuo backbone (+{ms} ms)", -"Your scrubbing centers are full: {g} leaks past":"I tuoi centri di scrubbing sono pieni: {g} passano lo stesso", "Attacks go to your nearest scrubbing center. From here that is {city}, {km} km away: the flood rides your backbone there and back, which adds latency, and whatever your links cannot carry is not scrubbed. A center here cleans attacks on the spot.":"Gli attacchi vanno al tuo centro di scrubbing più vicino. Da qui è {city}, a {km} km: il flusso viaggia sul tuo backbone fin lì e ritorno, il che aggiunge latenza, e quello che i tuoi link non riescono a portare non viene pulito. Un centro qui pulisce gli attacchi sul posto.", "attacks on {city} are hauled to {to} for scrubbing: +{ms} ms":"gli attacchi su {city} vengono portati a {to} per lo scrubbing: +{ms} ms", "Scrubbing centers":"Centri di scrubbing", @@ -2941,4 +2933,23 @@ "Raised {n} max-prefix limits.
{k} of them were route leaks. They are in the NOC now.":"Alzati {n} limiti max-prefix.
{k} erano route leak. Ora sono nel NOC.", "Raised {n} max-prefix limits.
All growth, no leaks. Lucky.":"Alzati {n} limiti max-prefix.
Tutta crescita, nessun leak. Fortuna.", "Off while your peering policy is {pol}":"Spento finché la tua politica di peering è {pol}", +"Memcached amplification":"Amplificazione Memcached", +"ACK flood":"Flood ACK", +"Edge filters dropping: {g}":"Filtri al bordo: {g} scartati", +"{g} is leaking through":"{g} superano le difese", +"Attack fully mitigated":"Attacco completamente mitigato", +"Scrubbing centers unavailable or at capacity":"Centri di scrubbing non disponibili o al completo", +"Distributed ingress":"Ingresso distribuito", +", across {n} transit and peering ports":", su {n} porte di transit e peering", +"No scrubbing needed after edge mitigation":"Nessuno scrubbing necessario dopo la mitigazione al bordo", +"RackNet":"RackNet", +"TeamSpooked":"TeamSpooked", +"Scrubbing in {city}: {used} / {capacity}":"Scrubbing a {city}: {used} / {capacity}", +"This attack: {g}":"Questo attacco: {g}", +"Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)":"Traffico di scrubbing trasportato sul tuo backbone: {city} → {to} (+{ms} ms)", +"After upstream scrubbing: {g}":"Dopo lo scrubbing a monte: {g}", +"No Flowspec filtering: ingress routers have no TCAM":"Nessun filtraggio Flowspec: i router di ingresso non hanno TCAM", +"Flowspec dropping: {g}; some ingress routers have no TCAM":"Flowspec scarta {g}; alcuni router di ingresso non hanno TCAM", +"Flowspec dropping: {g}":"Flowspec scarta {g}", +"Gaming attracts attacks":"Il gaming attira attacchi", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 215579b..9479de2 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -924,10 +924,7 @@ "Live attack: {city}":"Ataque ao vivo: {city}", "{size} · {vec}{entry} · {n}d left":"{size} · {vec}{entry} · faltam {n}d", "Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.":"Em blackhole: o lixo sumiu, e {city} também. O ataque conseguiu o que queria.", -"Reaching your network: {g}":"Chegando na sua rede: {g}", "On-demand scrubbing diverting, live in {n}d":"Scrubbing on-demand desviando, ativo em {n}d", -"{tier} scrubbing in {city} is cleaning it":"O scrubbing {tier} em {city} está limpando", -"{net} is scrubbing it upstream (clean-pipe)":"{net} está limpando upstream (clean-pipe)", "Contained on your sacrificial {net} PNI":"Contido no seu PNI sacrificial com {net}", "IX blackhole on ✓":"Blackhole IX ativo ✓", "IX blackhole ~half honour it":"Blackhole IX ~metade respeita", @@ -936,10 +933,7 @@ "Sacrificial choke ✓":"Gargalo sacrificial ✓", "Make sacrificial contains floods · ½ capacity":"Tornar sacrificial contém floods · ½ capacidade", "No scrubbing center":"Sem centro de scrubbing", -"Flowspec on your {model} is dropping {vec} at the edge":"O Flowspec no seu {model} está descartando {vec} na borda", -"Flowspec on your {model} trims {vec}, but its TCAM is small":"O Flowspec no seu {model} reduz {vec}, mas a TCAM é pequena", -"Your {model} here has no Flowspec TCAM":"Seu {model} aqui não tem TCAM para Flowspec", -"Flowspec cannot catch an {vec} (application layer)":"Flowspec não pega um {vec} (camada de aplicação)", +"Flowspec cannot catch {vec}":"Flowspec não consegue filtrar {vec}", "Stop blackholing":"Parar blackhole", "Blackhole the target (RTBH)":"Blackhole no alvo (RTBH)", "HackBack 3000™ $20k":"HackBack 3000™ $20k", @@ -2607,8 +2601,6 @@ "Attack hauled to scrubbing in {city}":"Ataque levado ao scrubbing em {city}", "Wants a scrubbing center on its own continent, so attacks are not hauled across an ocean":"Quer um centro de scrubbing no próprio continente, para que os ataques não atravessem um oceano", "Your backbone can only haul {g} of it to {city}: the rest is not scrubbed":"Seu backbone só consegue levar {g} até {city}: o resto não é limpo", -"{tier} scrubbing in {city} is cleaning it, hauled over your backbone (+{ms} ms)":"O scrubbing {tier} em {city} está limpando, levado pelo seu backbone (+{ms} ms)", -"Your scrubbing centers are full: {g} leaks past":"Seus centros de scrubbing estão cheios: {g} passam direto", "Attacks go to your nearest scrubbing center. From here that is {city}, {km} km away: the flood rides your backbone there and back, which adds latency, and whatever your links cannot carry is not scrubbed. A center here cleans attacks on the spot.":"Os ataques vão para o seu centro de scrubbing mais próximo. Daqui é {city}, a {km} km: a enxurrada viaja pelo seu backbone até lá e volta, o que aumenta a latência, e o que seus links não conseguem levar não é limpo. Um centro aqui limpa os ataques na hora.", "attacks on {city} are hauled to {to} for scrubbing: +{ms} ms":"os ataques em {city} são levados a {to} para scrubbing: +{ms} ms", "Scrubbing centers":"Centros de scrubbing", @@ -2941,4 +2933,23 @@ "Raised {n} max-prefix limits.
{k} of them were route leaks. They are in the NOC now.":"{n} limites de max-prefix aumentados.
{k} deles eram vazamentos de rotas. Estão no NOC agora.", "Raised {n} max-prefix limits.
All growth, no leaks. Lucky.":"{n} limites de max-prefix aumentados.
Tudo crescimento, nenhum vazamento. Sorte.", "Off while your peering policy is {pol}":"Desligado enquanto sua política de peering for {pol}", +"Memcached amplification":"Amplificação Memcached", +"ACK flood":"Flood ACK", +"Edge filters dropping: {g}":"Filtros de borda descartando: {g}", +"{g} is leaking through":"{g} estão passando", +"Attack fully mitigated":"Ataque totalmente mitigado", +"Scrubbing centers unavailable or at capacity":"Centros de scrubbing indisponíveis ou lotados", +"Distributed ingress":"Entrada distribuída", +", across {n} transit and peering ports":", por {n} portas de transit e peering", +"No scrubbing needed after edge mitigation":"Scrubbing desnecessário após a mitigação na borda", +"RackNet":"RackNet", +"TeamSpooked":"TeamSpooked", +"Scrubbing in {city}: {used} / {capacity}":"Scrubbing em {city}: {used} / {capacity}", +"This attack: {g}":"Este ataque: {g}", +"Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)":"Tráfego de scrubbing levado pelo seu backbone: {city} → {to} (+{ms} ms)", +"After upstream scrubbing: {g}":"Após o scrubbing upstream: {g}", +"No Flowspec filtering: ingress routers have no TCAM":"Sem filtragem Flowspec: os roteadores de entrada não têm TCAM", +"Flowspec dropping: {g}; some ingress routers have no TCAM":"Flowspec descarta {g}; alguns roteadores de entrada não têm TCAM", +"Flowspec dropping: {g}":"Flowspec descarta {g}", +"Gaming attracts attacks":"Gaming atrai ataques", }; diff --git a/site/index.html b/site/index.html index c003a61..b9c7a6f 100644 --- a/site/index.html +++ b/site/index.html @@ -637,9 +637,13 @@ const FS_RES=[1,0.4,0.15]; const DDOS_VEC={ dns:{n:tr('DNS reflection'),fs:true}, ntp:{n:tr('NTP amplification'),fs:true}, + memcached:{n:tr('Memcached amplification'),fs:true}, + ack:{n:tr('ACK flood'),fs:false}, cldap:{n:tr('CLDAP flood'),fs:true}, syn:{n:tr('SYN flood'),fs:true}, http:{n:tr('HTTP flood'),fs:false}, + racknet:{n:tr('RackNet'),fs:false,gaming:true}, + teamspooked:{n:tr('TeamSpooked'),fs:false,gaming:true}, }; const MYIX_COST=80000, MYIX_MO=3000, MYIX_FEE=1500, START_CASH=200000; // Your own exchange's switching fabric. Bigger fabrics carry more and attract more members. @@ -1441,7 +1445,7 @@ const initials=n=>n.name.replace(/[^A-Za-z ]/g,'').split(' ').filter(Boolean).ma /* ================= BUSINESSES ================= */ const BIZ_T={ dia:{l:tr('Enterprise DIA'),opts:[1,2,5,10],rate:600}, - game:{l:tr('Game servers'),opts:[5,10,20,40],rate:120}, + game:{l:tr('Game servers'),gaming:true,opts:[5,10,20,40],rate:120}, host:{l:tr('Hosting'),opts:[10,20,40,80],rate:60}, isp:{l:tr('Downstream ISP (buys transit)'),opts:[100,200,400,800],rate:15,lv:2}, l2vpn:{l:tr('L2VPN circuit'),opts:[1,10,40,100],rate:0,l2:true,km:1,lv:1}, @@ -1466,7 +1470,7 @@ const BIZ_T={ pairs:{l:tr('Hundreds of fiber pairs'),opts:[1],rate:0,fiber:true,mega:true,lv:4,names:['A Hyperscaler Who Shall Not Be Named','Planet-Scale AI WAN Team','The Fiber-Hungry Giant','Project Very Long Glass']}, esport:{l:tr('Esports world final'),opts:[400,800,1600,3200],rate:0,event:true,lv:5,names:['League of Lag Finals','Counter-Ping Major','Fortnightly World Cup','Dota Two Many Viewers','Rocket Leak Championship','Street Frighter Evo']}, sov:{l:tr('Sovereign cloud region'),opts:[400,800,1600],rate:0,l2:true,div:true,km:0.6,lv:6,names:['Gaia-Ex Sovereign Cloud','Bundeswolke (Very Secure)','Le Cloud Souverain','Datenschutz Deluxe','Your Data Stays Here, Probably','A Cloud With a Flag on It','Data Residency Is a State of Mind']}, - cgame:{l:tr('Cloud gaming platform'),opts:[800,1600,3200],rate:45,lv:8,names:['Stadia-ium (Back Again)','GeForce Later','Ping Station Now','Luna-tick Gaming','Shadow of a Doubt Cloud PC','Input Lag Arcade','Bufferbloat Bros. Streaming']}, + cgame:{l:tr('Cloud gaming platform'),gaming:true,opts:[800,1600,3200],rate:45,lv:8,names:['Stadia-ium (Back Again)','GeForce Later','Ping Station Now','Luna-tick Gaming','Shadow of a Doubt Cloud PC','Input Lag Arcade','Bufferbloat Bros. Streaming']}, metav:{l:tr('Metaverse platform'),opts:[1600,3200,6400],rate:35,lv:9,names:['Meh-taverse','Second Second Life','Horizon Worlds Apart','The Oasis (Ready Player Done)','Legs Finally Shipped Inc.','Decentra-landlocked']}, agi:{l:tr('AGI lab (allegedly)'),opts:[12800,25600],rate:0,l2:true,div:true,mega:true,km:0.4,lv:11,names:['Almost General Intelligence Inc.','Superintelligence Pending','The Lab That Said Two More Years','Paperclip Maximizer Labs','Deep Thought Two','Benevolent Overlord Research']}, mars:{l:tr('Mars mission ground station'),opts:[100,200,400],rate:0,l2:true,lat:true,km:4,lv:13,names:['Red Planet Relay','Ares Ground Segment','Olympus Mons Uplink','Mars or Bust Mission Control','Interplanetary Ping Society','Light-Minute Logistics','RFC 1149 Avian Carriers (Mars Division)']}, @@ -1794,7 +1798,7 @@ function scenarioModal(){const wk=weekly(),h=scnHof();let best=null;try{best=JSO function newGame(name,home){ S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, ltv:2,t1v:2,auV:1,seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{}, - done:{},inc:[],ev:{},priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}}; + done:{},inc:[],ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}}; } /* ================= HELPERS ================= */ @@ -2133,7 +2137,7 @@ function teOptimize(){const L=[tr('# Suggested by the optimizer from live traffi return L.join('\n');} // Ready-made RouteScripts, filled in from the live network. Players load them from the help; the AI button picks them too. const teUps=()=>[...new Set(S.transit.map(t=>t.net))].map(n=>({n,p:Math.min(...S.transit.filter(t=>t.net===n).map(t=>NET[n].price*regionMult(t.city)))})).sort((a,b)=>a.p-b.p); -const teNm=n=>NET[n].name.toLowerCase(),teAtk=()=>!!(S.ev.ddos&&S.ev.ddos.until>S.day); +const teNm=n=>NET[n].name.toLowerCase(),teAtk=()=>ddosAll().length>0; const teSad=()=>S.biz.some(b=>!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber&&!BIZ_T[b.type].event&&sfOf(R,b.city)<0.95); const TE_RECIPES=[ {id:'shield',n:N_('Shields Up'),d:N_('For a DDoS: drop the junk at the edge and keep business customers first. It costs a little real traffic, so remove it when the attack is over.'),fit:()=>teAtk()?9:0.3, @@ -2235,18 +2239,18 @@ function compute(){ // ok() cannot change during one compute, so ask each exit once per network, not once per flow and rank. // okBy[net] lists the exits that reach it in E's order, like E.filter(e=>e.ok(net)). const okBy={};for(const id of NET_IDS)okBy[id]=[]; - const ekN={};for(const e of E){e.ek=e.k+':'+e.id;ekN[e.ek]=(ekN[e.ek]||0)+1;} + R2.ingressPorts={};const ekN={};for(const e of E){e.ek=e.k+':'+e.id;if(e.k!=='c'){const p=R2.ingressPorts[e.ek]||(R2.ingressPorts[e.ek]={k:e.k,id:e.id,city:e.city,lab:e.lab,cap:0,traffic:0});p.cap+=e.cap;}ekN[e.ek]=(ekN[e.ek]||0)+1;} // dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last. for(const e of E){e.desc={lab:e.lab,city:e.city,k:e.k};e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;for(const n of e.nets||NET_IDS){const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}} for(const n of NETS){R2.reachable[n.id]=okBy[n.id].some(e=>e.rank>0);if(R2.reachable[n.id])R2.reach+=NSH[n.id];if(okBy[n.id].some(e=>e.rank>0&&e.k!=='t')){R2.nt[n.id]=1;R2.reachNT+=NSH[n.id];}} const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net)); const viral=(ev.viral>day?1.25:1)*(ev.php&&ev.php>day?0.7:1); // Every flow has the same shape and carries what routing asks about it again and again (nj: its network's index). - const NN=NETS.length,flows=[],flow=(c,ci,cn,j,rem,cache,junk,bz=false)=>{const n=NETS[j];flows.push({c,n:n.id,rem,cache,junk,bz,ci,cn,ncn:!!n.cn,nj:j,nr:junk?NN:j});}; + const NN=NETS.length,flows=[],flow=(c,ci,cn,j,rem,cache,junk,bz=false)=>{const n=NETS[j],f={c,n:n.id,rem,cache,junk,bz,ci,cn,ncn:!!n.cn,nj:j,nr:junk?NN:j};flows.push(f);return f;}; // Customer demand per city, added up in S.biz order (what filtering S.biz for each city would give). const bizBw={};for(const b of S.biz){const T=BIZ_T[b.type];if(!T.l2&&!T.fiber&&(!T.event||eventLive(b))){const v=bizBw[b.city];bizBw[b.city]=(v===undefined?0:v)+b.bw;}} // Traffic shares by network index, and their sums, for each share table (and with Russia's throttle). - const shArr=new Map(),shSum=new Map(),DEMTO=new Float64Array(NN),loc=scnRule('local'),HAUL=[];R2.haul=[]; + const shArr=new Map(),shSum=new Map(),DEMTO=new Float64Array(NN),loc=scnRule('local'),scrubRoom={},atkBy={},junkGroups=[],bhCities=new Set(ddosAll().filter(a=>a.bh).map(a=>a.city));R2.haul=[];R2.ddos=[];for(const a of ddosAll())for(const part of ddosSlices(a))(atkBy[part.city]||(atkBy[part.city]=[])).push(part); for(const c of Object.keys(S.pops)){ const p=S.pops[c],ci=CIDX[c],cn=cnCity(c),SH=cn?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH;const eye=(p.bb?p.bb.d:0)*viral*(cn&&ev.golden>day?1.4:1);const biz=bizBw[c]??0;const d0=eye+biz; // Goggle video is throttled in Russia (#70): people there get half of it, so they ask for half. It is not @@ -2255,26 +2259,18 @@ function compute(){ const tt=sm[+ru]||(sm[+ru]=[NETS.reduce((t,n,j)=>t+sa[j]*thr(n.id),0),NETS.reduce((t,n,j)=>t+sa[j],0)]),lf=loc?NETS.reduce((t,n,j)=>t+(R2.reachable[n.id]?sa[j]*thr(n.id):0),0)/(tt[0]||1):1,d=d0*tt[0]/(tt[1]||1)*lf; R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d; for(let j=0;jday?ev.ddos:null; - const rtbh=!!(atk&&atk.bh), edge=!!(atk&&TRX&&TRX.blackhole&&!rtbh); + const attacks=atkBy[c]||[],rtbh=bhCities.has(c),edge=!!(attacks.length&&TRX&&TRX.blackhole&&!rtbh); let dd=0; - if(atk&&!rtbh){let mult=1;const en=atk.entry||{}; - if(DDOS_VEC[atk.vec]&&DDOS_VEC[atk.vec].fs){const cap=fsAt(atk.city);if(cap)mult=Math.min(mult,FS_RES[cap]);} - if(en.k==='t'){const t=S.transit.find(x=>x.id===en.id);if(t&&t.clean)mult=Math.min(mult,0.1);} - if(atk.ixbh&&hasIxAt(atk.city))mult=Math.min(mult,0.5); - if(edge)mult=0; - // Scrubbing is used when it beats the edge tools; floods for a center in another city are hauled after the circuits below. - const sp=edge?null:scrubPlan(atk); - if(sp&&scrubIdeal(sp)x.id===en.id);if(p&&p.sacrif)dd=Math.min(dd,liveCap(pniG(p),p.city,p.site,p.n)*0.9);}} + for(const atk of attacks){const m=ddosMitigation(atk,{},bhCities.has((atk.parent||atk).city),false);R2.ddos.push(m);dd+=m.leak; + const group={m,flows:[]};junkGroups.push(group); + if(atk.entries?.length){for(const q of m.ingress){const f=flow(c,ci,cn,0,q.g,false,true);f.pin=q.entry.k+':'+q.entry.id;group.flows.push({f,share:m.leak>0?q.g/m.leak:0});}} + else for(let j=0;jm.attack.city===c))m.offline=true;continue;} const bh=rtbh||edge; - if(dd>0)for(let j=0;jn+a.gbps,0)+d*0.1;if(rtbh)R2.teBlack+=attacks.reduce((n,a)=>n+a.gbps,0)+d; R2.cityBlocked=R2.cityBlocked||{}; const mtuH=ev.pmtud&&ev.pmtud.until>day?ev.pmtud:null,kr=CITY[c].kr; for(let j=0;jday&&n.id==='fbk'?0.8:1);if(a<=0)continue; @@ -2337,18 +2333,28 @@ function compute(){ if((b.reqs||[]).includes('diverse')){const k=b.city+'>'+b.city2;R2.div[b.id]=divMemo[k]??(divMemo[k]=disjointI(b.city,b.city2));}} /* A flood for a scrubbing center elsewhere rides the backbone there, with the victim's own traffic (#117). What the links cannot carry is not scrubbed and lands on the city after all. */ - for(const H of HAUL){const A=H.c,B=H.to,Ai=CIDX[A],Bi=CIDX[B];let h=0,ms=null; - if(popUp(A)&&popUp(B)&&SPD[A]&&SPD[A][Bi]0?H.a*take/want:0;ms=path.reduce((x,e)=>x+e.lat,0)*2; - const ek='scrub:'+B;R2.egDesc[ek]={lab:labOf(N_('Attack hauled to scrubbing in {city}'),'city',CITY[B].name),city:A,k:'l2'}; - for(const i of ni)if(HAS[i])nodeTake(i,take);for(const l of path){l.res-=take;l.ld+=take;carry(l,ek,NN,Ai,take);}} - R2.haul.push({city:A,to:B,tier:H.tier,a:H.a,h,ms});const left=(H.a-h)*0.85;if(left>1e-6)for(let j=0;j0?scrubPlan(atk,m.leak,scrubRoom,(x,want)=>{const B=x.city,Bi=CIDX[B];if(A===B)return want;let h=0,ms=null; + if(popUp(A)&&popUp(B)&&SPD[A]&&SPD[A][Bi]0?want*take/total:0;ms=path.reduce((n,e)=>n+e.lat,0)*2; + // Sources sharing a center need separate labels in link breakdowns and map highlights. + const ek='scrub:'+A+'>'+B;R2.egDesc[ek]={lab:labOf(N_('Attack hauled to scrubbing in {city}'),'city',CITY[B].name),city:A,k:'l2'}; + for(const i of ni)if(HAS[i])nodeTake(i,take);for(const l of path){l.res-=take;l.ld+=take;carry(l,ek,NN,Ai,take);}} + R2.haul.push({city:A,to:B,tier:x.tier||0,a:want,h,ms,attack:atk.id});return h;}):null; + if(m.sp){m.leak=m.sp.leak; + // The card describes the victim's nearest center, separately from distributed ingress hauling above. + const c=(atk.parent||atk).city;let near=scrubNear.get(c);if(near===undefined){near=null; + for(const x of S.scrubs)if(popUp(x.city)&&SPD[c]&&SPD[c][CIDX[x.city]]n+e.lat,0);if(!near||ms{const key=src*NC+dst,c0=teCache.get(key); if(c0===false)return null;if(c0&&c0.path.every(l=>l.res>1e-3)&&c0.ni.every(i=>!HAS[i]||NRES[i]>1e-3))return c0; const {D,P}=dijkstra(adj,src,wW,(v,e)=>e.res<=1e-3||(HAS[v]&&NRES[v]<=1e-3),dst); if(D[dst]===Infinity||D[dst]>2*base+60){teCache.set(key,false);return null;} const Q=walkI(P,src,dst);teCache.set(key,Q);return Q;}; + const ingressE={};for(const e of E)(ingressE[e.ek]||(ingressE[e.ek]=[])).push(e); const base=e=>e.pref==='low'?4:e.rank; // LOCAL_PREF on an upstream moves it ahead of or behind the other transits, never ahead of peering (#96). const eff=(e,n)=>{let r=base(e);if(TR){if(e.k==='t'&&TR.up[e.net])r=TR.up[e.net]==='prefer'?2.9:3.5;if(e.prep)r=4.4;if(e.k!=='c'&&TR.drain.has(e.city))r=4.6;const o=TR.net[n];if(o){if(o.prefer===e.k)r=0.5;else if(o.avoid===e.k)r=4.5;}}return r;}; @@ -2374,7 +2380,7 @@ function compute(){ const ek=e.ek,nr=f.nr,ci=f.ci;if(!e.told||e.dup){R2.egDesc[ek]=e.desc;e.told=true;} for(const l of path){l.res-=amt;l.ld+=amt;carry(l,ek,nr,ci,amt);} e.used+=amt;f.rem-=amt; - if(!f.junk){let ok=amt;const cf=f.cn,ce=e.cn,cn=f.ncn; + if(!f.junk){if(e.k!=='c')R2.ingressPorts[ek].traffic+=amt;let ok=amt;const cf=f.cn,ce=e.cn,cn=f.ncn; if(cf!==ce||(cf&&!cn)||(!cf&&cn&&e.k==='t')){const prem=(e.k==='t'&&e.prem)||(e.k==='p'&&e.pnc)||path.some(x=>x.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);} SRV[f.ci]+=ok;R2.served+=ok;if(f.bz)R2.bizSrv[f.c]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const m=R2.tNet[e.id]||(R2.tNet[e.id]={});m[f.n]=(m[f.n]||0)+ok; // Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then @@ -2406,8 +2412,9 @@ function compute(){ // Index loops in here: plain for…of allocates an iterator per loop until V8 has optimised compute(). for(let fi=0,FN=flows.length;fix&&typeof x==='object'&&isCity(x.city)&&s.pops[x.city]&&!seen.has(x.city)&&seen.add(x.city)).map(x=>({city:x.city,tier:int(x.tier,0,SCRUB_TIERS.length-1,0)}));} s.scrubMode=s.scrubMode==='ondemand'?'ondemand':'always'; - if(s.ev&&s.ev.ddos){const a=s.ev.ddos; - if(!a||typeof a!=='object'||!isCity(a.city)||!own(DDOS_VEC,a.vec))delete s.ev.ddos; - else{a.gbps=num(a.gbps,2);a.until=num(a.until,s.day);a.bh=!!a.bh;a.ixbh=!!a.ixbh;a.start=num(a.start,s.day); - if(!a.entry||typeof a.entry!=='object')a.entry={k:'edge',lab:''};else{a.entry.lab=String(a.entry.lab||'').slice(0,60);a.entry.id=a.entry.id==null?undefined:String(a.entry.id).slice(0,40);}}} + // Keep the legacy primary attack so old saves and imports remain compatible; additional floods overlap it. + const repairAttack=a=>{if(!a||typeof a!=='object'||!isCity(a.city)||!s.pops[a.city]||!own(DDOS_VEC,a.vec))return null; + a.id=sid(a.id);a.gbps=Math.max(0,num(a.gbps,2));a.until=num(a.until,s.day);a.bh=!!a.bh;a.ixbh=!!a.ixbh;a.start=Math.max(0,Math.min(s.day,num(a.start,s.day)));a.until=Math.min(a.until,a.start+7); + if(Array.isArray(a.entries)){a.entries=a.entries.filter(en=>en&&['t','ix','p'].includes(en.k)&&isCity(en.city)&&typeof en.id==='string'&&Number.isFinite(+en.share)&&+en.share>0).slice(0,3000).map(en=>({k:en.k,id:en.id.slice(0,40),city:en.city,lab:String(en.lab||'').slice(0,60),share:+en.share}));const sum=a.entries.reduce((n,en)=>n+en.share,0);if(Number.isFinite(sum)&&sum>0)for(const en of a.entries)en.share/=sum;else delete a.entries;}else delete a.entries; + a.sla=Array.isArray(a.sla)?a.sla.filter(x=>typeof x==='string').slice(0,s.biz.length):[]; + if(!a.entry||typeof a.entry!=='object')a.entry={k:'edge',lab:''};else{a.entry.lab=String(a.entry.lab||'').slice(0,60);a.entry.id=a.entry.id==null?undefined:String(a.entry.id).slice(0,40);}return a;}; + const attacks=[s.ev.ddos,...(Array.isArray(s.ev.ddosMore)?s.ev.ddosMore:[])].map(repairAttack).filter(Boolean).slice(0,14); + if(attacks.length)s.ev.ddos=attacks[0];else delete s.ev.ddos;s.ev.ddosMore=attacks.slice(1); + s.ddosStarts=(Array.isArray(s.ddosStarts)?s.ddosStarts:attacks.map(a=>a.start)).filter(d=>typeof d==='number'||typeof d==='string').map(Number).filter(d=>Number.isFinite(d)&&d>s.day-7&&d<=s.day).sort((a,b)=>a-b).slice(-14); s.auV=s.auV===1?1:0;if(s.auNews!==true)delete s.auNews; if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}} return s;} @@ -2623,6 +2635,7 @@ function bizSfOf(r,c){const d=r.bizDem&&r.bizDem[c];return teRules()&&teRules(). function bCities(o){return o.sites?o.sites.slice():[o.city,o.city2].filter(Boolean);} function bHas(o){return bCities(o).every(c=>S.pops[c]);} function eventLive(b){return BIZ_T[b.type].event&&S.day>=b.start&&S.day⚠️ ${tr('Gaming attracts attacks')}`:'';} function bTerms(o){const T=BIZ_T[o.type]; if(T.event){const live=S.day>=o.start;return tr('{bw} extra for {d} days, {when} · pays {fee} when it is over',{bw:fmtG(o.bw),d:o.dur,when:live?tr('day {n} of {d}',{n:S.day-o.start+1,d:o.dur}):tr('starting in {n}d',{n:o.start-S.day}),fee:fmt$(o.fee)});} if(T.sdwan)return tr('{n} sites: {list} · {bw} per site · {price}/mo',{n:o.sites.length,list:o.sites.map(c=>CITY[c].name).join(', '),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)}); @@ -2753,59 +2766,83 @@ function lagsN(){const o=[];for(const t of S.transit)if((t.n||1)>=2&&!(t.down>S. for(const p of S.pni)if((p.n||1)>=2)o.push({k:'p',id:p.id,o:p,n:p.n,lab:tr('PNI LAG with {name} in {city}',{name:NET[p.net].name,city:CITY[p.city].name})}); for(const x in S.ixp){const n=(S.ixn||{})[x]||1;if(n>=2&&!S.myIx[x])o.push({k:'ix',id:x,n,lab:ixNamesCity(x)?tr('{ix} LAG',{ix:ixName(x)}):tr('{ix} LAG in {city}',{ix:ixName(x),city:CITY[ixCity(x)].name})});}return o;} // Where the junk comes in: one of the city's live uplinks, or just "the edge" if it has none yet. +// The primary slot remains compatible with older saves; every system uses the full live set. +function ddosAll(s=S,live=true){return [s.ev.ddos,...(s.ev.ddosMore||[])].filter(a=>a&&(!live||a.until>s.day));} +const ddosFind=id=>ddosAll().find(a=>id===undefined||a.id===id); +function ddosDrop(a){const left=ddosAll(S,false).filter(x=>x!==a);S.ev.ddos=left[0]||null;S.ev.ddosMore=left.slice(1);} +function ddosExpire(){for(const a of ddosAll(S,false))if(a.until<=S.day||!S.pops[a.city]){ddosDone(a);ddosDrop(a);}} +function ddosEntries(){const ports=Object.values(R.ingressPorts||{}).filter(p=>p.cap>0),busy=ports.some(p=>p.traffic>1e-6),weight=p=>busy?p.traffic:p.cap,total=ports.reduce((n,p)=>n+weight(p),0); + return total>0?ports.filter(p=>weight(p)>0).map(p=>({k:p.k,id:p.id,city:p.city,lab:p.lab,share:weight(p)/total})):[];} +function ddosSlices(a){if(!a.entries?.length)return [a];const groups={}; + for(const en of a.entries){const c=S.pops[en.city]?en.city:a.city;(groups[c]||(groups[c]=[])).push(en);} + return Object.entries(groups).map(([city,entries])=>({...a,parent:a,city,entries,gbps:a.gbps*entries.reduce((n,en)=>n+en.share,0)}));} +const ddosCities=a=>[...new Set([a.city,...(a.entries||[]).map(en=>en.city)])].filter(c=>S.pops[c]); +const ddosHasIx=a=>ddosCities(a).some(hasIxAt); +const ddosSf=a=>Math.min(1,...ddosCities(a).map(c=>sfOf(R,c))); +function ddosReport(a){const ms=(R.ddos||[]).filter(m=>m.attack===a||m.attack.parent===a);if(!ms.length)return ddosMitigation(a); + const parts={};for(const m of ms)for(const x of m.sp?.parts||[]){const q=parts[x.city]||(parts[x.city]={city:x.city,tier:x.tier,a:0,cleaned:0});q.a+=x.a;q.cleaned+=x.cleaned;} + return {attack:a,blackhole:ms.some(m=>m.blackhole),upstream:ms.some(m=>m.upstream),reaching:ms.reduce((n,m)=>n+m.reaching,0),flowspec:ms.reduce((n,m)=>n+m.flowspec,0),fsMissing:ms.some(m=>m.fsMissing),filtered:ms.reduce((n,m)=>n+m.filtered,0),sp:Object.keys(parts).length?{parts:Object.values(parts)}:null,near:ms.find(m=>m.near)?.near||null,leak:ms.reduce((n,m)=>n+m.leak,0)};} function ddosEntry(c){const o=[]; for(const t of S.transit)if(t.city===c&&!(t.down>S.day))o.push({k:'t',id:t.id,lab:tr('{net} transit',{net:NET[t.net].name})}); for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined)o.push({k:'ix',id:x,lab:tr('{ix} peering',{ix:ixName(x)})}); for(const p of S.pni)if(p.city===c)o.push({k:'p',id:p.id,lab:tr('PNI with {net}',{net:NET[p.net].name})}); return o.length?pick(o):{k:'edge',lab:''};} -// Flowspec capability of the router in a city: 0 none, 1 basic, 2 full. The flood is filtered where the -// victim POP's own router has the TCAM for it. +// Flowspec capability at each ingress POP: 0 none, 1 basic, 2 full. const fsAt=c=>{const p=S.pops[c];return p?(RG[p.rgen||0].fs||0):0;}; -// Scrubbing residual for an attack: clean up to the center's capacity (to 15%), overflow leaks. On-demand +// Scrubbing removes attack traffic up to the center's capacity; overflow leaks. On-demand // does nothing for the first couple of days while traffic is being diverted. -function scrubEngaged(atk){return hasScrub()&&(S.scrubMode==='always'||(S.day-(atk.start||S.day))>=SCRUB_DELAY);} +function scrubEngaged(atk){return hasScrub()&&(S.scrubMode==='always'||(S.day-(atk.start??S.day))>=SCRUB_DELAY);} // Several centers (#117): the flood goes to the nearest working one, and what it cannot take spills to the next. // A center in another city only helps if the backbone can carry the flood there; routing works that out. -const scrubFar=c=>{const a=S.ev&&S.ev.ddos;return a&&a.until>S.day&&a.city===c&&(R.haul||[]).find(q=>q.city===c&&q.ms!==null&&q.ms>=SCRUB_FAR_MS)||null;}; -function scrubPlan(atk){if(!scrubEngaged(atk))return null;const c=atk.city;let g=atk.gbps||0;const parts=[]; - for(const x of S.scrubs.filter(x=>popUp(x.city)&&(x.city===c||pathExists(c,x.city))).sort((a,b)=>(a.city===c?0:kmBetween(c,a.city))-(b.city===c?0:kmBetween(c,b.city)))){if(g<=0)break;const a=Math.min(g,SCRUB_TIERS[x.tier||0].g);parts.push({city:x.city,tier:x.tier||0,a});g-=a;} +const scrubFar=c=>ddosAll().some(a=>ddosCities(a).includes(c))&&(R.haul||[]).find(q=>q.city===c&&q.ms!==null&&q.ms>=SCRUB_FAR_MS)||null; +function scrubPlan(atk,g=atk.gbps||0,room={},take=null){if(!scrubEngaged(atk))return null;const c=atk.city;const parts=[]; + for(const x of S.scrubs.filter(x=>popUp(x.city)&&(x.city===c||pathExists(c,x.city))).sort((a,b)=>(a.city===c?0:kmBetween(c,a.city))-(b.city===c?0:kmBetween(c,b.city)))){if(g<=0)break;const cap=SCRUB_TIERS[x.tier||0].g,a=Math.min(g,room[x.city]??cap);if(a<=0)continue;const cleaned=take?take(x,a):a;room[x.city]=(room[x.city]??cap)-cleaned;parts.push({city:x.city,tier:x.tier||0,a,cleaned});g-=cleaned;} return parts.length?{parts,leak:g}:null;} -// What still lands on the city if every haul gets through: 15% of what is scrubbed, plus whatever no center can take. -const scrubIdeal=p=>p?p.parts.reduce((s,x)=>s+x.a*0.15,0)+p.leak:Infinity; +// One accounting pipeline for routing and the NOC: upstream -> edge -> scrubbing -> leakage. +function ddosMitigation(a,room={},blackhole=a.bh,plan=true){const entries=a.entries?.length?a.entries:[{...(a.entry||{}),share:1}],total=entries.reduce((n,en)=>n+en.share,0),ingress=[]; + let upstream=false,reaching=0,g=0,flowspec=0,fsMissing=false; + for(const en of entries){const t=en.k==='t'?S.transit.find(x=>x.id===en.id):null,p=en.k==='p'?S.pni.find(x=>x.id===en.id):null,clean=!!(t&&t.clean); + upstream=upstream||clean;let part=blackhole?0:a.gbps*en.share/total*(clean?0.1:1);reaching+=part; + if(DDOS_VEC[a.vec]?.fs){const cap=fsAt(S.pops[en.city]?en.city:a.city),before=part;part*=FS_RES[cap];flowspec+=before-part;if(cap===0&&before>0)fsMissing=true;} + if(a.ixbh&&hasIxAt(a.city))part*=0.5; + if(p&&p.sacrif)part=Math.min(part,liveCap(pniG(p),p.city,p.site,p.n)*0.9); + if(teRules()?.blackhole&&!blackhole)part=0; + g+=part;ingress.push({entry:en,g:part});} + const filtered=reaching-g,sp=plan&&g>0?scrubPlan(a,g,room):null; + return {attack:a,blackhole,upstream,reaching,flowspec,fsMissing,filtered,ingress,sp,leak:sp?sp.leak:g};} // The NOC's live attack view: what is hitting you, what each tool would do about it right now, and the buttons. -function ddosPanel(){ - const a=S&&S.ev&&S.ev.ddos;if(!a||a.until<=S.day||!S.pops[a.city])return ''; - const V=DDOS_VEC[a.vec]||{n:'?',fs:false},cap=fsAt(a.city),model=RG[(S.pops[a.city].rgen||0)].n,en=a.entry||{}; - const cleanT=en.k==='t'?S.transit.find(x=>x.id===en.id):null, sacP=en.k==='p'?S.pni.find(x=>x.id===en.id):null; - let mult=1; - if(V.fs&&cap)mult=Math.min(mult,FS_RES[cap]); - if(cleanT&&cleanT.clean)mult=Math.min(mult,0.1); - if(a.ixbh&&hasIxAt(a.city))mult=Math.min(mult,0.5); - const sp=scrubPlan(a),useS=!!sp&&scrubIdeal(sp)(R.haul||[]).find(q=>q.city===a.city&&q.to===x.city); - let land=a.bh?0:useS?sp.parts.reduce((t,x)=>{const q=x.city===a.city?null:hl(x);return t+x.a*0.15+(q?(q.a-q.h)*0.85:0);},sp.leak):a.gbps*mult; - if(sacP&&sacP.sacrif)land=Math.min(land,liveCap(PORT[sacP.tier].g,sacP.city,sacP.site,sacP.n)*0.9); - land=Math.round(land); - const fsLine=!V.fs?'— '+tr('Flowspec cannot catch an {vec} (application layer)',{vec:esc(V.n)}) - :cap>=2?'✓ '+tr('Flowspec on your {model} is dropping {vec} at the edge',{model:esc(model),vec:esc(V.n)}) - :cap===1?'~ '+tr('Flowspec on your {model} trims {vec}, but its TCAM is small',{model:esc(model),vec:esc(V.n)}) - :'— '+tr('Your {model} here has no Flowspec TCAM',{model:esc(model)}); - const scrOne=x=>{const T=SCRUB_TIERS[x.tier],q=x.city===a.city?null:hl(x); - return q&&q.hS.pops[a.city]).map(ddosOne).join(''):'';} +function ddosOne(a){ + const V=DDOS_VEC[a.vec]||{n:'?',fs:false},en=a.entry||{}; + const sacP=en.k==='p'?S.pni.find(x=>x.id===en.id):null; + const m=ddosReport(a),sp=m.sp,hl=x=>{const qs=(R.haul||[]).filter(q=>q.to===x.city&&q.attack===a.id);return qs.length?{a:qs.reduce((n,q)=>n+q.a,0),h:qs.reduce((n,q)=>n+q.h,0)}:null;}; + const landLine=m.blackhole?'~ '+tr('Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.',{city:esc(CITY[a.city].name)}) + :m.upstream?'✓ '+tr('After upstream scrubbing: {g}',{g:fmtG(m.reaching)}):''; + const fsLine=!V.fs?'— '+tr('Flowspec cannot catch {vec}',{vec:esc(V.n)}) + :m.flowspec<=1e-6?'— '+tr('No Flowspec filtering: ingress routers have no TCAM') + :m.fsMissing?'~ '+tr('Flowspec dropping: {g}; some ingress routers have no TCAM',{g:fmtG(m.flowspec)}) + :'✓ '+tr('Flowspec dropping: {g}',{g:fmtG(m.flowspec)}); + const used=c=>(R.ddos||[m]).reduce((n,q)=>n+(q.sp?.parts||[]).filter(x=>x.city===c).reduce((t,x)=>t+x.cleaned,0),0); + const scrOne=x=>{const T=SCRUB_TIERS[x.tier],q=hl(x),total=used(x.city); + return (x.cleaned>1e-6?'✓ ':'~ ')+tr('Scrubbing in {city}: {used} / {capacity}',{city:esc(CITY[x.city].name),used:fmtG(total),capacity:T.n}) + +(total>x.cleaned+1e-6?' · '+tr('This attack: {g}',{g:fmtG(x.cleaned)}):'') + +(q&&q.h~ '+tr('Your backbone can only haul {g} of it to {city}: the rest is not scrubbed',{g:fmtG(q.h),city:esc(CITY[x.city].name)}):'');}; const scrLine=!hasScrub()?'— '+tr('No scrubbing center') - :!scrubEngaged(a)?'… '+tr('On-demand scrubbing diverting, live in {n}d',{n:Math.max(1,SCRUB_DELAY-(S.day-(a.start||S.day)))}) - :!sp?'— '+tr('No scrubbing center') - :sp.parts.map(scrOne).join('
')+(sp.leak>0.5?'
~ '+tr('Your scrubbing centers are full: {g} leaks past',{g:fmtG(sp.leak)}):''); - const entryLine=cleanT&&cleanT.clean?'✓ '+tr('{net} is scrubbing it upstream (clean-pipe)',{net:esc(NET[cleanT.net].name)}) - :sacP&&sacP.sacrif?'✓ '+tr('Contained on your sacrificial {net} PNI',{net:esc(NET[sacP.net].name)}):''; + :!scrubEngaged(a)?'… '+tr('On-demand scrubbing diverting, live in {n}d',{n:Math.max(1,SCRUB_DELAY-(S.day-(a.start??S.day)))}) + :!sp?'— '+(m.leak<=1e-6?tr('No scrubbing needed after edge mitigation'):tr('Scrubbing centers unavailable or at capacity')) + :sp.parts.map(scrOne).join('
'); + const haulLine=m.near&&m.near.ms>0&&sp?.parts.some(x=>x.cleaned>1e-6)?'✓ '+tr('Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)',{city:esc(CITY[a.city].name),to:esc(CITY[m.near.city].name),ms:m.near.ms.toFixed(1)}):''; + const entryLine=sacP&&sacP.sacrif?'✓ '+tr('Contained on your sacrificial {net} PNI',{net:esc(NET[sacP.net].name)}):''; let h=`
🚨 ${tr('Live attack: {city}',{city:esc(CITY[a.city].name)})}
${tr('{size} · {vec}{entry} · {n}d left',{size:fmtG(a.gbps),vec:esc(V.n),entry:a.entry&&a.entry.lab?' · '+esc(a.entry.lab):'',n:a.until-S.day})}
-
${a.bh?tr('Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.',{city:esc(CITY[a.city].name)}):tr('Reaching your network: {g}',{g:fmtG(land)})}
+ ${landLine?`
${landLine}
`:''} + ${m.blackhole?'':`
${fsLine}
${entryLine?`
${entryLine}
`:''} + ${m.filtered-m.flowspec>1e-6?`
✓ ${tr('Edge filters dropping: {g}',{g:fmtG(m.filtered-m.flowspec)})}
`:''}
${scrLine}
-
${fsLine}
${entryLine?`\n
${entryLine}
`:''} -
${a.bh?btn(tr('Stop blackholing'),'unrtbh',{},'ghost sm'):btn(tr('Blackhole the target (RTBH)'),'rtbh',{},'red sm')}${hasIxAt(a.city)&&!a.bh?btn(a.ixbh?tr('IX blackhole on ✓'):tr('IX blackhole ~half honour it'),'ixbh',{},a.ixbh?'green sm':'sm'):''}${btn(tr('HackBack 3000™ $20k'),'hackback',{},'sm',S.cash<20000)}
+ ${haulLine?`
${haulLine}
`:''} +
${m.leak>1e-6?'~ '+tr('{g} is leaking through',{g:fmtG(m.leak)}):'✓ '+tr('Attack fully mitigated')}
`} +
${m.blackhole?btn(tr('Stop blackholing'),'unrtbh',{id:a.id},'ghost sm'):btn(tr('Blackhole the target (RTBH)'),'rtbh',{id:a.id},'red sm')}${ddosHasIx(a)&&!m.blackhole?btn(a.ixbh?tr('IX blackhole on ✓'):tr('IX blackhole ~half honour it'),'ixbh',{id:a.id},a.ixbh?'green sm':'sm'):''}${btn(tr('HackBack 3000™ $20k'),'hackback',{id:a.id},'sm',S.cash<20000)}

${tr('RTBH is free and instant, but it drops everything to the victim, attack and customer alike. An IX blackhole keeps the customer up but only about half the members honour it. HackBack 3000™ by Skynot AI sometimes ends it, and sometimes flattens an innocent and earns you a fine.')}

`; return h;} function fireFailure(){ @@ -2817,7 +2854,7 @@ function fireFailure(){ if(S.transit.some(t=>!(t.down>S.day)))opts.push(['transit',3]); if(Object.keys(S.ixp).length)opts.push(['ixloop',2]); if(S.transit.length&&S.day>60)opts.push(['leak',2]); - if(S.day>40&&!scnRule('ddos'))opts.push(['ddos',2]); // Flood Season brings its own + // DDoS has its own schedule, so other incidents cannot bypass the weekly limit. if(fabsUsed.length)opts.push(['fabric',1.5]); const lit=S.links.filter(l=>l.kind==='df'&&dfCap(l)>0&&!linkDown(l));if(lit.length)opts.push(['amp',1.5+lit.length*0.3],['optic',1.5+lit.length*0.3]); opts.push(['funny',4]); @@ -2921,27 +2958,49 @@ function fireFailure(){ else{const paused=pref('pauseIncident')&&autoPause();toast(`${incTitle(type)}
${esc(last.msg)}${paused?`
${tr('Game paused.')}`:''}`,'bad',(last.cost?[{l:`${last.fix||tr('Rush repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));} sfx('alert'); } -// A DDoS attack: mostly short, modest spikes; now and then a "botnet of toasters" monster into the terabits. -// In Flood Season (scenario rule ddos) they come more often, a third are monsters, and they grow over the year. -function ddosAttack(){const type='ddos',fl=scnRule('ddos'),grow=fl?1+S.day/180:1;if(S.ev.ddos&&S.ev.ddos.until>S.day)ddosDone(S.ev.ddos); - const c=pick(Object.keys(S.pops)),vec=pick(Object.keys(DDOS_VEC)),V=DDOS_VEC[vec]; - const monster=Math.random()<(fl?0.33:0.15),base=Math.max(R.cityDem[c]||0,4); - const gbps=Math.round((monster?800+Math.random()*2600:2+Math.random()*Math.max(18,base*0.9))*grow); - const dur=2+Math.floor(Math.random()*4),entry=ddosEntry(c); - S.ev.ddos={city:c,vec,gbps,until:S.day+dur,entry,bh:false,start:S.day}; +const gamingCount=()=>S.biz.reduce((n,b)=>n+(BIZ_T[b.type]?.gaming?1:0),0); +const ddosVectors=()=>Object.keys(DDOS_VEC).filter(k=>!DDOS_VEC[k].gaming||gamingCount()>0); +// Expected starts per week in normal play; the rolling 14-start limit is a separate ceiling. +// Spread gaming exposure over dozens of customers, including the first, rather than switching baselines. +const ddosRate=()=>0.5+6.5*(1-Math.exp(-gamingCount()/50*(1+Math.max(1,S.lvl||1)/LEVELS.length))); +const ddosPressure=()=>1-Math.exp(-(.01+Math.max(0,(S.lvl||1)-1)/12+gamingCount()/10+(scnRule('ddos')?.2+S.day/365:0))); +// Normalize the vector mix so smaller gaming-only floods do not lower the advertised overall mean. +function ddosSizeMean(){const stage=Math.max(1,S.lvl||1)/LEVELS.length,games=gamingCount(),fl=scnRule('ddos'); + const base=Math.max(10,(R.demand||0)*4/3*stage,fl?1400:0); + if(fl)return base*(1+0.2*games/(games+10))*(1+S.day/365); + // Relative to no gaming: 3x at one customer, 8x at 50, approaching the existing 12x balance. + const mean=base*(games?1.2-0.9*Math.pow(4/9,(games-1)/49):0.1),vectors=ddosVectors(),weight=vectors.reduce((n,k)=>n+(DDOS_VEC[k].gaming?1/3:1),0)/vectors.length; + return mean/weight;} +// Normal rolls: 98% uniform 0.2–2, 2% uniform 8–12. Their mean is 1.278, so spikes do not inflate the balance. +const ddosSizeMax=()=>ddosSizeMean()*(scnRule('ddos')?1.5:12/1.278); +function ddosSize(vec){const fl=scnRule('ddos'),r=Math.random(),roll=fl?1/3+r*2/3:(r<.98?.2+1.8*r/.98:8+4*(r-.98)/.02)/12; + const raw=ddosSizeMax()*(DDOS_VEC[vec].gaming?1/3:1)*roll; + return fl?Math.max(2,Math.floor(raw)):Math.max(0.001,Math.floor(raw*1000)/1000);} +function ddosTick(){if(S.mode==='sandbox')return;if(scnRule('ddos')){let next=+S.scn.nextDdos||3,n=0; + while(S.day>=next&&n++<2){ddosAttack(false);next+=floodGap();}S.scn.nextDdos=next40||gamingCount())for(let i=0;i<2;i++)if(Math.random()d>S.day-7&&d<=S.day);if(S.ddosStarts.length>=14||!Object.keys(S.pops).length)return;S.ddosStarts.push(S.day); + const c=pick(Object.keys(S.pops)),vec=pick(ddosVectors()),V=DDOS_VEC[vec]; + const gbps=ddosSize(vec); + const dur=1+Math.floor(Math.random()*(1+6*ddosPressure())),entry=ddosEntry(c); + const entries=ddosEntries(),a={id:uid(),city:c,vec,gbps,until:S.day+dur,entry:entries.length>1?{k:'distributed',lab:tr('Distributed ingress')}:entries[0]||entry,entries,bh:false,start:S.day}; + if(!S.ev.ddos)S.ev.ddos=a;else(S.ev.ddosMore||(S.ev.ddosMore=[])).push(a); const soaked=(V.fs&&fsAt(c))||hasScrub(); - const how=entry&&entry.lab?tr(', in via {e}',{e:entry.lab}):''; + const how=entries.length>1?tr(', across {n} transit and peering ports',{n:entries.length}):entry&&entry.lab?tr(', in via {e}',{e:entry.lab}):''; const msg=tr('A {size} {vec} attack is hitting {city}{how}.',{size:fmtG(gbps),vec:V.n,city:CITY[c].name,how})+' '+(soaked?tr('Your mitigation is eating most of it.'):tr('Junk traffic is eating your capacity. Open the NOC to fight back.')); - if(fl)S.ev.ddos.who=pick(FLOOD_WHO); - addInc({type,ref:c,until:S.day+dur,msg:fl?msg+' '+tr('Attacker: {who}.',{who:tr(S.ev.ddos.who)}):msg,cost:0}); + if(fl)a.who=pick(FLOOD_WHO); + addInc({type,ref:c,atk:a.id,until:S.day+dur,msg:fl?msg+' '+tr('Attacker: {who}.',{who:tr(a.who)}):msg,cost:0}); if(soaked){S.stats.survived++;S.stats.ddosHeld=(S.stats.ddosHeld||0)+1;if(gbps>=1000)S.stats.ddosMonster=(S.stats.ddosMonster||0)+1;} - compute(); - toast(`${incTitle('ddos')}: ${esc(CITY[c].name)}
${esc(msg)}${fl?`
${esc(tr('Attacker: {who}.',{who:tr(S.ev.ddos.who)}))}`:''}`,soaked?'goal':'bad',[{l:tr('Open NOC'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:c}); + if(recompute){compute();a.worst=ddosSf(a);} + toast(`${incTitle('ddos')}: ${esc(CITY[c].name)}
${esc(msg)}${fl?`
${esc(tr('Attacker: {who}.',{who:tr(a.who)}))}`:''}`,soaked?'goal':'bad',[{l:tr('Open NOC'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:c}); sfx('alert');} // When an attack is over: was it held? Held means the city under attack got at least 97% of its traffic every day. -function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pops[a.city])a.worst=sfOf(R,a.city);const ok=(a.worst===undefined?1:a.worst)>=0.97; +function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pops[a.city])a.worst=ddosSf(a);const ok=(a.worst===undefined?1:a.worst)>=0.97; if(ok){S.stats.ddosOk=(S.stats.ddosOk||0)+1;if(a.gbps>=1000)S.stats.ddosOkBig=(S.stats.ddosOkBig||0)+1;}else S.stats.ddosLost=(S.stats.ddosLost||0)+1; if(scnRule('ddos')){const who=tr(a.who||FLOOD_WHO[0]);toast(ok?tr('Flood held: {g}.
{who} gave up and went back to mining crypto.',{g:fmtG(a.gbps),who:who.charAt(0).toUpperCase()+who.slice(1)}):tr('That one got through: {g}.
{city} sank to {p}. Somewhere, {who} is very proud of itself.',{g:fmtG(a.gbps),city:CITY[a.city]?CITY[a.city].name:tr('Your network'),p:pct(a.worst||0),who}),ok?'goal':'bad');}} +const floodGap=()=>Math.max(0.05,(3+Math.random()*5)/(Math.sqrt(1+S.day/180)*(1+gamingCount()/10+Math.max(0,(S.lvl||1)-1)/12))); const FLOOD_WHO=[N_('a botnet of 40,000 smart toasters'),N_('every unpatched baby monitor in Europe'),N_('a gaming clan that lost one match'),N_('a fridge that achieved sentience and chose violence'),N_('a crypto bro shorting your stock'),N_('a teenager with a stolen credit card and a grudge'),N_('a rival ISP’s “stress test”'),N_('ten thousand smart light bulbs, blinking in unison'),N_('a printer. Just one printer. Nobody knows how'),N_('a botnet run from a cloud you also host'),N_('somebody who did not like your network name'),N_('the internet-connected kettles of a whole country')]; function incTitle(t){return {ring:tr('Metro ring cut'),site:tr('Site outage'),cut:tr('Fiber cut'),crash:tr('Router crash'),power:tr('Power outage'),transit:tr('Upstream outage'),ixloop:tr('IX meltdown'),leak:tr('Route leak'),ddos:tr('DDoS attack'),fabric:tr('Fabric outage'),depeer:tr('Peering spat'),fatwave:tr('Fat-fingered wave'),label:tr('Patch panel mishap'),mtu:tr('MTU mismatch'),krroute:tr('Rerouted via Hong Kong'),ctrlplane:tr('Control plane meltdown'),lacp:tr('LACP trouble'),loss:tr('Packet loss'),pmtud:tr('PMTUD black hole'),oops:tr('Oops'),cleaner:tr('Vacuum incident'),maxpfx:tr('Max-prefix meltdown'),prepend:tr('Prepend-ageddon'),rpki:tr('RPKI invalid'),amp:tr('Amplifier failure'),roadmff:tr('Fat-fingered ROADM'),optic:tr('Dead optic'),maint:tr('Maintenance window'),ac:tr('Cooling failure'),hijack:tr('BGP hijack'),shutdown:tr('Government shutdown'),redsea:tr('Geopolitical cable cut')}[t]||tr('Incident');} const LINKCUT_TR=['cut','redsea'],LINKCUT_ID=['fatwave','label'],POPDOWN=['crash','power','oops','cleaner','maint','shutdown'],IXDOWN=['ixloop','maxpfx'],TDOWN=['transit','prepend'],LINKEQ=['mtu','amp','roadmff','optic']; @@ -2956,7 +3015,7 @@ function clearInc(i){ else if(TDOWN.includes(T)){const t=S.transit.find(x=>x.id===i.ref);if(t)t.down=remainUntil(x=>TDOWN.includes(x.type)&&x.ref===i.ref);} else if(T==='rpki'||T==='hijack'){if(!S.inc.some(x=>x.type==='rpki'||x.type==='hijack'))S.ev.rpki=null;} else if(T==='leak'){S.ev.leak=null;} - else if(T==='ddos'){const a=S.ev.ddos;if(a&&a.city===i.ref&&(a.start===undefined||a.start===i.start)){ddosDone(a);S.ev.ddos=null;}} + else if(T==='ddos'){const a=ddosAll(S,false).find(a=>i.atk?a.id===i.atk:a.city===i.ref&&(a.start===undefined||a.start===i.start));if(a){ddosDone(a);ddosDrop(a);}} else if(T==='fabric'){if(S.ev.fab)S.ev.fab[i.ref]=remainUntil(x=>x.type==='fabric'&&x.ref===i.ref);} else if(T==='mtu'){const l=S.links.find(x=>x.id===i.ref);if(l)l.deg=remainUntil(x=>x.type==='mtu'&&x.ref===i.ref);} else if(T==='loss'){const l=S.links.find(x=>x.id===i.ref);if(l&&!S.inc.some(x=>x.type==='loss'&&x.ref===i.ref))l.loss=null;} @@ -3034,8 +3093,9 @@ function dayTick(){ if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved); {const t1=!!S.won&&isTier1();if(S.t1Now&&!t1)toast(tr('You are no longer Tier 1.
Because {why}. Your Tier 1 badge stays; win the status back to show it again.',{why:t1Why()}),'bad');S.t1Now=t1;} if(S.grace&&S.grace.until===d){toast(tr('The courtesy route has ended.
New networks you have not connected to are now only reachable through your own peering and transit.'),'bad',[{l:tr('Open NOC'),act:'leftTab',args:{t:'noc'}}]);} - {const a=S.ev.ddos;if(a&&a.until>d&&R&&S.pops[a.city])a.worst=Math.min(a.worst===undefined?1:a.worst,sfOf(R,a.city));} - if(scnRule('ddos')&&!(S.scn.done||S.scn.failed)&&d>=(+S.scn.nextDdos||3)&&!(S.ev.ddos&&S.ev.ddos.until>d)){ddosAttack();S.scn.nextDdos=d+3+Math.floor(Math.random()*5);} + for(const a of ddosAll(S,false))if(a.until>=d&&R&&S.pops[a.city])a.worst=Math.min(a.worst===undefined?1:a.worst,ddosSf(a)); + ddosExpire(); + ddosTick(); if(R&&R.demand>0)S.stats.clean=R.served/R.demand>=0.995?(S.stats.clean||0)+1:0; if(S.scn&&S.scn.id==='redsea')S.stats.asiaRun=asiaG()>=RS_G?(S.stats.asiaRun||0)+1:0; if(S.ev.php===d)toast(tr('The internet is back.
Half of it, anyway. Everything was patched in a hurry and nobody learned anything.'),'good'); @@ -3050,6 +3110,7 @@ function dayTick(){ if(sf>=0.9){const g=(CITY[c].be&&!(p.boost>d)?0.35:1)*0.025*(scnRule('boom')?1.5:1)*(p.boost>d?2:1)*sf*(0.7+0.6*(R.peerShare||0))*(CITY[c].reg==='AS'&&!CITY[c].cn?1.6:1);p.bb.d+=g*p.bb.d*(1-p.bb.d/P);} else p.bb.d=Math.max(Math.min(3,P),p.bb.d*(1-(0.9-sf)*0.04));} compute(); + for(const a of ddosAll())a.worst=Math.min(a.worst??1,ddosSf(a)); for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();} S.cash+=(R.revMo-R.costMo)/30; S.stats.peak=Math.max(S.stats.peak,R.served); @@ -3059,9 +3120,9 @@ function dayTick(){ if(l.ready===d){toast(`${l.own?tr('Your fiber is finished: {a}–{b}',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('Dark fiber handed over: {a}–{b}',{a:CITY[l.a].name,b:CITY[l.b].name})}
${(l.ch||[]).length?tr('Channels are lighting up now.'):tr('It is dark. Add optics to light it up.')}`,'goal',[{l:tr('Open'),act:'selLink',args:{id:l.id}}]);sfx('coin');} if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);setCableReady(l,l.ready+extra);toast(tr('Construction delay: +{n} days
{why} ({a}–{b})',{n:extra,why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('Archaeologists found a Roman bathhouse on your route.'),tr('A protected hamster species lives along the right-of-way.'),tr('The railway changed its mind about the easement.'),tr('The drilling crew hit a granite boulder the size of a bus.'),tr('A town council wants a public hearing. About the color of the manhole covers.'),tr('Somebody else’s gas main was exactly where the map said it was not.'),tr('The permit office lost your permit. And then the replacement.')]),a:CITY[l.a].name,b:CITY[l.b].name}),'bad');}} // DDoS protection SLA: if a protected customer's own city is hit and still goes down, you pay out (once per attack). - if(S.ev.ddos&&S.ev.ddos.until>d){const a=S.ev.ddos; - for(const b of S.biz)if(b.type==='scrub'&&b.city===a.city&&b.slaFor!==a.start&&sfOf(R,b.city)<0.85){ - b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1; + for(const a of ddosAll()){ + for(const b of S.biz)if(b.type==='scrub'&&ddosCities(a).includes(b.city)&&!(a.sla||[]).includes(b.id)&&(a.id||b.slaFor!==a.start)&&sfOf(R,b.city)<0.85){ + (a.sla||(a.sla=[])).push(b.id);b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1; toast(tr('SLA breach: {name}.
The attack on {city} got through and your protected customer went down. You owe {pen} in SLA credits.',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}} // businesses mood for(const b of S.biz.slice()){if(eventTick(b,d))continue;b.pm=b.mood;const sf=bizSf(b),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b); @@ -3425,10 +3486,10 @@ const ACT={ rmScrub:({city})=>{if(!S.scrubs.some(x=>x.city===city))return;if(UI.confirm!=='scrub:'+city){UI.confirm='scrub:'+city;renderAll();return;}S.scrubs=S.scrubs.filter(x=>x.city!==city);if(!hasScrub())S.scrubMode='always';UI.confirm=null;after();}, cleanPipe:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;t.clean=!t.clean;toast(t.clean?tr('Clean-pipe add-on enabled on {net}.
They scrub a flood before it reaches your port here, for {mo}/mo.',{net:NET[t.net].name,mo:fmt$(cleanMo(t))}):tr('Clean-pipe add-on removed from {net}.',{net:NET[t.net].name}),t.clean?'good':'');after();}, sacrif:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p)return;p.sacrif=!p.sacrif;toast(p.sacrif?tr('{net} PNI is now a sacrificial choke point.
A flood from there dies on the small port instead of inside your network, but legit traffic over it runs at half capacity.',{net:NET[p.net].name}):tr('{net} PNI is back to normal.',{net:NET[p.net].name}),p.sacrif?'good':'');after();}, - ixbh:()=>{const a=S.ev.ddos;if(!a){toast(tr('No attack to blackhole right now.'),'');return;}if(!hasIxAt(a.city)){toast(tr('No IX in {city} to announce a blackhole to.',{city:CITY[a.city].name}),'bad');sfx('err');return;}a.ixbh=!a.ixbh;toast(a.ixbh?tr('IX blackhole announced in {city}.
About half the members honour the /32 and drop the junk. The customer stays up.',{city:CITY[a.city].name}):tr('IX blackhole withdrawn.'),a.ixbh?'good':'');sfx('alert');after();}, - rtbh:()=>{const a=S.ev.ddos;if(!a){toast(tr('No attack to blackhole right now.'),'');return;}a.bh=true;S.stats.rtbh=(S.stats.rtbh||0)+1;toast(tr('RTBH announced.
You blackholed the target in {city}. The flood stops, and so does everyone there.',{city:CITY[a.city].name}),'bad');sfx('alert');after();}, - unrtbh:()=>{const a=S.ev.ddos;if(!a||!a.bh)return;a.bh=false;toast(tr('Blackhole withdrawn.
{city} is reachable again. Brace for the junk.',{city:CITY[a.city].name}),'');after();}, - hackback:()=>{const a=S.ev.ddos;if(!a||a.until<=S.day){toast(tr('Nothing to hack back right now.'),'');return;}if(!spend(20000))return;S.stats.hackback=(S.stats.hackback||0)+1; + ixbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('No attack to blackhole right now.'),'');return;}if(!ddosHasIx(a)){toast(tr('No IX in {city} to announce a blackhole to.',{city:CITY[a.city].name}),'bad');sfx('err');return;}a.ixbh=!a.ixbh;toast(a.ixbh?tr('IX blackhole announced in {city}.
About half the members honour the /32 and drop the junk. The customer stays up.',{city:ddosCities(a).filter(hasIxAt).map(c=>CITY[c].name).join(', ')}):tr('IX blackhole withdrawn.'),a.ixbh?'good':'');sfx('alert');after();}, + rtbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('No attack to blackhole right now.'),'');return;}a.bh=true;S.stats.rtbh=(S.stats.rtbh||0)+1;toast(tr('RTBH announced.
You blackholed the target in {city}. The flood stops, and so does everyone there.',{city:CITY[a.city].name}),'bad');sfx('alert');after();}, + unrtbh:({id}={})=>{const a=ddosFind(id);if(!a)return;for(const x of ddosAll())if(x.city===a.city)x.bh=false;toast(tr('Blackhole withdrawn.
{city} is reachable again. Brace for the junk.',{city:CITY[a.city].name}),'');after();}, + hackback:({id}={})=>{const a=ddosFind(id);if(!a||a.until<=S.day){toast(tr('Nothing to hack back right now.'),'');return;}if(!spend(20000))return;S.stats.hackback=(S.stats.hackback||0)+1; if(Math.random()<0.35){a.until=S.day;a.bh=false;S.stats.hackWin=(S.stats.hackWin||0)+1;toast(tr('HackBack 3000™ strikes back!
Skynot AI traced the botnet and politely bricked it. The attack on {city} stops cold.',{city:CITY[a.city].name}),'goal');sfx('coin');} else{const fine=15000+Math.floor(Math.random()*35000);S.cash-=fine;S.stats.vigilante=(S.stats.vigilante||0)+1; toast(tr('HackBack 3000™ hit the wrong target.
{who} A regulator sends you a {fine} fine, and the attack rolls on.',{who:pick([tr("Skynot AI flattened a grandma's internet-connected fridge."),tr('You counter-flooded a hospital in a country you cannot pronounce.'),tr('The botnet was already someone else’s botnet. They are furious.')]),fine:fmt$(fine)}),'bad');sfx('err');} @@ -3697,7 +3758,7 @@ function renderLeft(){checkLayer(); {const lv=S.lvl||1,nx=LEVELS[lv];h+=`
${tr('Customer level {lv}: {name}',{lv,name:LEVELS[lv-1].n})}
${nx?tr('Next: {req} unlocks {what}',{req:nx.req,what:lc1(nx.unlock)}):tr('Every customer type is unlocked. Go get those terabits.')}
`;} if(!S.offers.length)h+=`

${tr('No open offers right now. Businesses look for networks with POPs in their city. New ones pop up every few weeks.')}

`; for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); - h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('{n} special requirement','{n} special requirements',o.reqs.length)}`:''}
${reqList(o)} + h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('{n} special requirement','{n} special requirements',o.reqs.length)}`:''}
${bRisk(o)}${reqList(o)}
${has?btn(tr('Accept'),'accept',{id:o.id},'green sm'):btn(tr('Go there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('Decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('Needs a POP in {cities}',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} }else if(UI.left==='noc'){ h+=`
${btn(tr('Open NOC dashboard'),'dash',{},'pink')}${btn(tr('Connections'),'connOpen',{},'')}${btn(tr('Traceroute'),'trace',{},'')}
`; @@ -3781,7 +3842,7 @@ function cityPanel(c){ h+=`

${tr('Business customers')}

`; const bz=S.biz.filter(b=>bCities(b).includes(c)); if(!bz.length)h+=`

${tr('No businesses yet. Offers pop up as $ bubbles on the map.')}

`; - for(const b of bz)h+=`
${esc(b.name)}
${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${BIZ_T[b.type].l2?` · ${b.sites?tr('carrying {g} per site',{g:fmtG(R.l2[b.id]||0)}):tr('carrying {g}',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('fiber is down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('serving {v}',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('needs a scrubbing center')+'':''}${S.day-(b.since||0)<15?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('Really drop?'):tr('Drop'),'dropBiz',{id:b.id},'ghost sm')}
`; + for(const b of bz)h+=`
${esc(b.name)}
${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${BIZ_T[b.type].l2?` · ${b.sites?tr('carrying {g} per site',{g:fmtG(R.l2[b.id]||0)}):tr('carrying {g}',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('fiber is down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('serving {v}',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('needs a scrubbing center')+'':''}${S.day-(b.since||0)<15?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('Really drop?'):tr('Drop'),'dropBiz',{id:b.id},'ghost sm')}
`; h+=`
`+offersHere(c); }else if(UI.tab==='up'){ h+=portNote(c)+latNote(c); @@ -3973,7 +4034,7 @@ function dfPanel(l){ } function offersHere(c){ const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return ''; - return `

${tr('Offers here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('They need the full internet. Your reach is {pct}.',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('Needs your own scrubbing center (Infra tab).')}
`:''}${reqList(o)}${bHas(o)?'':`
${tr('Needs a POP in {cities} too.',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('Accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('No'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; + return `

${tr('Offers here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('They need the full internet. Your reach is {pct}.',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('Needs your own scrubbing center (Infra tab).')}
`:''}${bRisk(o)}${reqList(o)}${bHas(o)?'':`
${tr('Needs a POP in {cities} too.',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('Accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('No'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; } function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} @@ -4031,8 +4092,8 @@ const SCN_PROG={stg:()=>[{l:tr('Reach'),v:R.reach,max:0.45,txt:`${pct(R.reach)} darien:()=>[...['bog','lim','scl','sao'].map(c=>pChk(tr('POP in {city}',{city:CITY[c].name}),!!S.pops[c])),pSrv(150)], gangnam:()=>[pReach(),pSrv(200)], fttb:()=>[...AU_BB.map(c=>pChk(tr('Broadband in {city}',{city:CITY[c].name}),!!(S.pops[c]&&S.pops[c].bb))),{l:tr('Cables overseas'),v:Math.min(2,auExits()),max:2,txt:`${auExits()} / 2`}], - flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,a=S.ev.ddos&&S.ev.ddos.until>S.day?S.ev.ddos:null; - return [{l:tr('Floods held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('Terabit floods held'),v:big,max:5,txt:`${big} / 5`},{l:tr('Floods that got through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(a?[{l:tr('Under attack now'),v:0,max:0,txt:`${fmtG(a.gbps)} · ${CITY[a.city].name} · ${pct(a.worst===undefined?1:a.worst)}`}]:[]);},baltic:()=>[{l:tr('Days in a row with 99.5% served'),v:S.stats.clean||0,max:90,txt:tr('{n} of {m}',{n:S.stats.clean||0,m:90})}]}; + flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,attacks=ddosAll(); + return [{l:tr('Floods held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('Terabit floods held'),v:big,max:5,txt:`${big} / 5`},{l:tr('Floods that got through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(attacks.map(a=>({l:tr('Under attack now'),v:0,max:0,txt:`${fmtG(a.gbps)} · ${CITY[a.city].name} · ${pct(a.worst===undefined?1:a.worst)}`})));},baltic:()=>[{l:tr('Days in a row with 99.5% served'),v:S.stats.clean||0,max:90,txt:tr('{n} of {m}',{n:S.stats.clean||0,m:90})}]}; function scnProg(){const sc=S&&S.scn;if(!sc)return null; if(sc.id==='weekly')return {goal:tr('Serve as much traffic as you can in one year.'),items:[{l:tr('Your score: peak traffic'),v:0,max:0,txt:fmtG(S.stats.peak||0)}],f:Math.min(1,S.day/sc.days)}; const def=SCN.find(x=>x.id===sc.id),fn=SCN_PROG[sc.id];if(!def)return null;let items=[];try{items=fn?fn():[];}catch(e){items=[];} @@ -4110,7 +4171,7 @@ function custSection(){const F=UI.kf||{};let h=`
b.pm===undefined||Math.abs(b.mood-b.pm)<0.05?'':b.mood>b.pm?' ▲':' ▼'; const sorts=[['mood',tr('Happiness')],['mo',tr('Per month')],['name',tr('Name')],['city',tr('Where')]]; h+=`
${sorts.map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'custSort',{k},sk===k?'pink sm':'ghost sm')).join('')}
`; - h+=rows.slice(0,listN('cust')).map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `
${esc(b.name)} ${esc(BIZ_T[b.type].l)}
${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('{price}/mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${why.length?`
${why.map(esc).join(' · ')}
`:''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}${trend(b)}
${btn(tr('Open'),'custGo',{id:b.id},'ghost sm')}
`;}).join(''); + h+=rows.slice(0,listN('cust')).map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `
${esc(b.name)} ${esc(BIZ_T[b.type].l)}
${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('{price}/mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${why.length?`
${why.map(esc).join(' · ')}
`:''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}${trend(b)}
${btn(tr('Open'),'custGo',{id:b.id},'ghost sm')}
`;}).join(''); return h+listMore('cust',rows.length,n=>trn('+{n} more customer','+{n} more customers',n))+`
`;} /* ---------- connections overview (#31, #33, #38) ---------- Every transit port, PNI, IX port, cache and fabric port in one list, filterable by type, city and diff --git a/tests/game.test.js b/tests/game.test.js index e6d0d16..1047b19 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -2,6 +2,15 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const { load, seed } = require('./harness'); +test('daily DDoS spawns share one routing calculation and score their first active day', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.day=50;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();window.__compute=compute;window.__random=Math.random;window.__computes=0;compute=()=>{window.__computes++;window.__compute()};Math.random=()=>0;dayTick();compute=window.__compute;Math.random=window.__random"); + assert.equal(ev('ddosAll().length'), 2, 'both daily spawn opportunities were used'); + assert.equal(ev('window.__computes'), 1, 'daily spawns do not reroute the whole network individually'); + assert.ok(ev('ddosAll().every(a=>a.worst===ddosSf(a))'), 'first-day service is recorded after routing'); + assert.deepEqual(errors, []); +}); + test('page boots to the title screen without errors', () => { const { ev, errors } = load(); assert.equal(ev("document.getElementById('modal').hidden"), false); @@ -197,6 +206,52 @@ test('Flowspec is a router-model capability, and each tool answers a flood', () assert.deepEqual(errors, []); }); +test('a distributed SYN flood reports actual Flowspec drops and sends only the remainder to scrubbing', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.scrubs=[{city:'fra',tier:0}];S.scrubMode='always';S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entries:[{k:'edge',city:'fra',share:1}]};compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2); + assert.match(ev('ddosPanel()'), /— No Flowspec filtering: ingress routers have no TCAM/); + assert.match(ev('ddosPanel()'), /✓ Scrubbing in Frankfurt: 30\.2 Gbps \/ 100G/); + assert.doesNotMatch(ev('ddosPanel()'), /✓ Flowspec|After upstream scrubbing|Reaching your network/); + for (const [router, dropped, scrubbed] of [[1,18.12,12.08], [3,25.67,4.53]]) { + ev(`S.pops.fra.rgen=${router};compute()`); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-dropped)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned')-scrubbed)<1e-9); + assert.match(ev('ddosPanel()'), new RegExp('✓ Flowspec dropping: '+dropped.toFixed(1).replace('.', '\\.')+' Gbps')); + assert.match(ev('ddosPanel()'), new RegExp('Scrubbing in Frankfurt: '+scrubbed.toFixed(1).replace('.', '\\.')+' Gbps / 100G')); + assert.doesNotMatch(ev('ddosPanel()'), /no TCAM|Edge filters dropping/); + } + ev("S.ev.ddos.vec='ack';compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2); + assert.match(ev('ddosPanel()'), /— Flowspec cannot catch ACK flood/); + assert.deepEqual(errors, []); +}); + +test('Flowspec accounts for each ingress router, upstream cleaning and other edge filters separately', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});S.pops.nyc.rgen=3;S.transit=[{id:'tf',city:'fra',net:'cog',tier:1},{id:'tn',city:'nyc',net:'cog',tier:1}];S.scrubs=[{city:'fra',tier:0},{city:'nyc',tier:0}];S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entries:[{k:'t',id:'tf',city:'fra',share:0.5},{k:'t',id:'tn',city:'nyc',share:0.5}]};compute()"); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-12.835)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts.reduce((n,x)=>n+x.cleaned,0)')-17.365)<1e-9); + assert.match(ev('ddosPanel()'), /~ Flowspec dropping: 12\.8 Gbps; some ingress routers have no TCAM/); + assert.match(ev('ddosPanel()'), /Scrubbing in Frankfurt: 15\.1 Gbps \/ 100G/); + assert.match(ev('ddosPanel()'), /Scrubbing in New York: 2\.3 Gbps \/ 100G/); + assert.equal(ev('ddosMitigation(S.ev.ddos).flowspec'), ev('ddosReport(S.ev.ddos).flowspec'), 'uncached reports also filter at the ingress instead of the target'); + ev('S.transit[1].clean=true;compute()'); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).reaching')-16.61)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-1.2835)<1e-9); + assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 16\.6 Gbps/); + assert.match(ev('ddosPanel()'), /~ Flowspec dropping: 1\.3 Gbps/); + ev("S.pops.fra.rgen=3;S.ixp={fra:1,nyc:1};S.ev.ddos.ixbh=true;compute()"); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-14.1185)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).flowspec')-1.24575)<1e-9); + assert.match(ev('ddosPanel()'), /✓ Flowspec dropping: 14\.1 Gbps/); + assert.match(ev('ddosPanel()'), /✓ Edge filters dropping: 1\.2 Gbps/); + assert.ok(ev('Math.abs(ddosReport(S.ev.ddos).reaching-ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).sp.parts.reduce((n,x)=>n+x.cleaned,0)-ddosReport(S.ev.ddos).leak)<1e-9')); + assert.deepEqual(errors, []); +}); + test('RTBH blackholes the victim, and HackBack 3000 is a gamble', () => { const { ev } = load(); ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=120;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()"); @@ -478,3 +533,468 @@ test('the broadband panel shows what homes in that city really pay, not the base assert.ok(ev("cityPanel('del')").includes(rev + '/mo'), `revenue line matches what the month pays (${rev})`); assert.deepEqual(errors, []); }); + + +test('Memcached amplification and ACK flood are available without gaming customers and respect Flowspec', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});RG[0].fs=2"); + assert.equal(ev('S.biz.length'), 0); + assert.equal(ev('DDOS_VEC.memcached.fs'), true); + assert.equal(ev('DDOS_VEC.ack.fs'), false); + ev("S.ev.ddos={city:'fra',vec:'ack',gbps:300,until:S.day+3,start:S.day};compute()"); + const ack = ev('R.served'); + assert.match(ev('ddosPanel()'), /ACK flood/); + assert.doesNotMatch(ev('ddosPanel()'), /application layer/); + ev("S.ev.ddos.vec='memcached';compute()"); + assert.ok(ev('R.served') > ack, 'Flowspec filters Memcached but cannot filter ACK'); + for (const vec of ['memcached', 'ack']) { + ev(`const old=Math.random;Math.random=()=>(${['dns','ntp','memcached','ack'].indexOf(vec)}+0.1)/ddosVectors().length;ddosAttack();Math.random=old`); + assert.equal(ev('ddosAll().at(-1).vec'), vec, 'the generator can select each new vector'); + } + assert.deepEqual(errors, []); +}); + + +test('DDoS accounting conserves attack bandwidth through upstream, edge and local scrubbing', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.bb.d=100;S.scrubs=[{city:'fra',tier:1}];S.transit[0].clean=true;S.ev.ddos={city:'fra',vec:'http',gbps:1842,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute()"); + assert.ok(Math.abs(ev('R.ddos[0].reaching') - 184.2) < 1e-9); + assert.equal(ev('R.ddos[0].sp.parts[0].cleaned'), ev('R.ddos[0].reaching')); + assert.equal(ev('R.ddos[0].leak'), 0, 'the 1T center cleans the upstream remainder'); + assert.doesNotMatch(ev('ddosPanel()'), /842 Gbps of attack traffic leaks/); + ev('S.transit[0].clean=false;compute()'); + assert.equal(ev('R.ddos[0].reaching'), 1842); + assert.equal(ev('R.ddos[0].leak'), 842); + for (const setup of ["S.transit[0].clean=true", "RG[0].fs=2;S.ev.ddos.vec='dns'", "S.scrubs=[]"]) { + ev(setup+';compute()'); + assert.ok(ev('Math.abs(R.ddos[0].reaching-R.ddos[0].filtered-(R.ddos[0].sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0)-R.ddos[0].leak)<1e-9')); + assert.ok(ev('R.ddos[0].leak<=R.ddos[0].reaching')); + } + // On-demand diversion must also work for an attack which began on day zero. + ev("S.scrubs=[{city:'fra',tier:1}];S.scrubMode='ondemand';S.day=2;compute()"); + assert.equal(ev('R.ddos[0].leak'), 0); + assert.deepEqual(errors, []); +}); + + +test('the NOC integrates DDoS mitigation totals into each live attack card without duplicate summaries on phones', () => { + const { ev, errors, dom } = load(); + ev('ACT.start({})'); + Object.defineProperty(dom.window, 'innerWidth', { value: 360, configurable: true }); + ev("S.cash=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.transit[0].clean=true;S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={city:'fra',vec:'http',gbps:3840,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute();UI.left='noc';UI.leftOpen=true;renderLeft()"); + const card = () => dom.window.document.querySelector('[data-act="rtbh"], [data-act="unrtbh"]').closest('.inc'); + const text = () => card().textContent; + assert.match(card().querySelector('.nm').textContent, /🚨 Live attack: Frankfurt/); + assert.equal(dom.window.document.querySelector('.ddos-stats'), null, 'use the existing attack card'); + assert.doesNotMatch(text(), /DDoS mitigation status|Attack size:|3840 Gbps|This attack:/); + assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'the attack size appears once'); + assert.match(text(), /✓ After upstream scrubbing: 384 Gbps/); + assert.equal(text().match(/After upstream scrubbing/g).length, 1, 'show the upstream remainder once'); + assert.doesNotMatch(text(), /Reaching your network|reaching your network|Upstream scrubbing active/); + assert.match(text(), /✓ Scrubbing in Frankfurt: 384 Gbps \/ 1T/); + assert.match(text(), /✓ Attack fully mitigated/); + ev('S.transit[0].clean=false;compute();renderLeft()'); + assert.doesNotMatch(text(), /After upstream scrubbing|Reaching your network/); + assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'inactive upstream scrubbing does not repeat the attack size'); + assert.match(text(), /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T/); + assert.match(text(), /~ 2\.84 Tbps is leaking through/); + assert.equal(text().match(/leaking through/g).length, 1, 'show the mitigation outcome once'); + assert.doesNotMatch(text(), /Upstream scrubbing|Attack fully mitigated|leaks past mitigation/); + ev("S.transit[0].clean=true;S.pops.fra.rgen=3;S.ev.ddos.vec='dns';compute();renderLeft()"); + assert.match(text(), /✓ Flowspec dropping: 326 Gbps/); + assert.doesNotMatch(text(), /Edge filters dropping/); + assert.match(text(), /✓ Scrubbing in Frankfurt: 57\.6 Gbps \/ 1T/); + assert.match(text(), /✓ Attack fully mitigated/); + ev('ACT.rtbh();renderLeft()'); + assert.match(text(), /~ Blackholed: the junk is gone, and so is Frankfurt/); + assert.equal(text().match(/Blackholed:/g).length, 1); + assert.doesNotMatch(text(), /After upstream scrubbing|reaching your network|scrubbing in Frankfurt|Attack fully mitigated|leaking through/i); + assert.ok(card().querySelector('[data-act="unrtbh"]'), 'the existing controls stay in the card'); + assert.deepEqual(errors, []); +}); + +test('overlapping floods share scrubbing capacity, have separate controls, and finish independently', () => { + const { ev, errors, dom } = load(); + ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:700,start:0,until:3};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:700,start:0,until:5}];compute();UI.left='noc';UI.leftOpen=true;renderLeft()"); + assert.equal(ev('R.ddos.length'), 2); + assert.equal(ev('R.ddos.reduce((n,m)=>n+(m.sp?.parts.reduce((v,x)=>v+x.cleaned,0)||0),0)'), 1000); + assert.equal(ev('R.ddos.reduce((n,m)=>n+m.leak,0)'), 400, 'one center cannot spend its capacity twice'); + const cards = [...dom.window.document.querySelectorAll('[data-act="rtbh"]')].map(b=>b.closest('.inc')); + assert.equal(cards.length, 2); + assert.match(cards[1].textContent, /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T · This attack: 300 Gbps/); + ev("ACT.rtbh({id:'two'})"); + assert.equal(ev("S.ev.ddos.bh||false"), false, 'the selected attack gets the control'); + assert.equal(ev('S.ev.ddosMore[0].bh'), true); + assert.ok(ev('R.ddos.every(m=>m.leak===0)'), 'blackholing a target city drops every flood to it'); + ev("ACT.unrtbh({id:'one'});const old=Math.random;Math.random=()=>0.1;ACT.hackback({id:'two'});Math.random=old"); + assert.equal(ev('ddosAll().length'), 1, 'hack-back ends only the selected attack'); + ev('S.day=3;ddosExpire();compute()'); + assert.equal(ev('ddosAll().length'), 0); + assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2, 'both attacks scored once'); + ev('ddosExpire()'); + assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2); + assert.deepEqual(errors, []); +}); + +test('overlapping DDoS saves round trip and legacy attacks migrate safely', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.ev.ddos={city:'fra',vec:'dns',gbps:'80',until:7,start:0};delete S.ev.ddosMore;delete S.ddosStarts;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('ddosAll().length'), 1); + assert.equal(ev('S.ev.ddos.gbps'), 80); + assert.equal(ev('S.ev.ddosMore.length'), 0); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosStarts)')), [0]); + ev("S.ev.ddosMore=[{id:'overlap',city:'fra',vec:'ack',gbps:50,until:5,start:0,sla:['customer']},null,{city:'bad',vec:'dns'}, {city:'fra',vec:'unknown'}];S.ddosStarts=[0,'bad',Infinity,-9,99];S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('ddosAll().length'), 2); + assert.equal(ev('S.ev.ddosMore[0].id'), 'overlap'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosStarts)')), [0]); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('R.ddos.length'), 2); + assert.deepEqual(errors, []); +}); + +test('simultaneous attacks each bill their protected customer only once', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.biz=[{id:'protected',name:'Shield',city:'fra',type:'scrub',bw:5,rate:900,mood:100,since:0,reqs:[]}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:6000,start:0,until:7};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:6000,start:0,until:7}];compute();dayTick()"); + assert.equal(ev('S.stats.sla'), 2, 'same-day attacks have separate SLA identities'); + ev('S=migrate(JSON.parse(JSON.stringify(S)));dayTick()'); + assert.equal(ev('S.stats.sla'), 2, 'reloading does not pay the same credits twice'); + assert.deepEqual(errors, []); +}); + +test('DDoS frequency rises with level and signed gaming customers, with a rolling weekly ceiling', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.day=50;S.lvl=1;S.biz=[]"); + const base = ev('ddosRate()'); + assert.equal(base, 0.5); + ev('S.lvl=13'); + assert.equal(ev('ddosRate()'), base, 'level alone does not increase the non-gaming rate'); + ev("S.biz=[{type:'game',city:'fra'}];S.lvl=1"); + const early = ev('ddosRate()'); + ev('S.lvl=13'); + const level = ev('ddosRate()'); + ev("S.biz=Array.from({length:20},(_,i)=>({type:i%2?'cgame':'game',city:'fra'}))"); + const gaming = ev('ddosRate()'); + assert.ok(base < early && early < level && level < gaming && gaming <= 7); + ev("S.offers=Array.from({length:50},()=>({type:'game'}));S.biz=[];S.lvl=1"); + assert.equal(ev('ddosRate()'), base, 'unsigned offers do not attract attacks'); + // Force every random spawn opportunity, then verify each rolling seven-day window. + ev('window.__starts=[];window.__oldRandom=Math.random;Math.random=()=>0'); + for (let day = 50; day < 66; day++) { + ev(`S.day=${day};ddosTick();window.__starts.push(...ddosAll().filter(a=>a.start===S.day).map(a=>a.start))`); + assert.ok(ev('S.ddosStarts.length') <= 14); + } + ev('Math.random=window.__oldRandom'); + const starts = JSON.parse(ev('JSON.stringify(window.__starts)')); + for (let day = 50; day < 66; day++) assert.ok(starts.filter(d=>d>day-7&&d<=day).length <= 14); + assert.ok(starts.length > 14, 'the allowance renews as starts leave the rolling window'); + ev('for(let i=0;i<30;i++)ddosAttack()'); + assert.equal(ev('S.ddosStarts.length'), 14, 'manual and incident starts cannot bypass the cap'); + assert.deepEqual(errors, []); +}); + +test('DDoS sizes use a smaller non-gaming baseline and preserve unbounded Flood Season scaling', () => { + const { ev, errors } = load(); + ev('ACT.start({});S.lvl=13;R.demand=150000;S.biz=[]'); + assert.equal(ev('ddosSizeMean()'), 20000); + ev("S.scn={id:'flood',rules:{ddos:true}};S.day=365"); + assert.equal(ev('ddosSizeMean()'), 400000); + ev('S.day=730'); + assert.equal(ev('ddosSizeMean()'), 600000, 'Flood Season keeps growing after completion'); + ev('S.scn=null;R.demand=300000'); + assert.equal(ev('ddosSizeMean()'), 40000, 'larger networks can draw still larger attacks'); + ev('S.lvl=1'); + const early = ev('ddosSizeMax()'); + ev('S.lvl=13'); + const late = ev('ddosSizeMax()'); + ev("S.biz=[{type:'game',city:'fra'}]"); + assert.ok(early < late && late < ev('ddosSizeMax()')); + // Fixed quantiles show longer durations as both level and gaming exposure rise. + ev('window.__oldRandom=Math.random;Math.random=()=>0.95;S.lvl=1;S.biz=[];ddosAttack();window.__earlyDur=ddosAll().at(-1).until-S.day;S.lvl=13;S.biz=Array.from({length:40},()=>({type:\'game\',city:\'fra\',bw:0,rate:0}));ddosAttack();Math.random=window.__oldRandom'); + assert.ok(ev('ddosAll().at(-1).until-S.day') > ev('window.__earlyDur')); + assert.equal(ev('ddosAll().at(-1).until-S.day'), 7); + assert.deepEqual(errors, []); +}); + +test('distributed attacks follow normal transit and peering traffic across regions', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].rgen=3;S.pops[c].bb={d:c==='fra'?100:300}}S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:2}];S.pni=[{id:'pf',city:'fra',net:'ggl',tier:1}];S.ixp={nyc:1};S.rs={nyc:true};compute();window.__normal=JSON.stringify(R.ingressPorts);ddosAttack()"); + const normal = JSON.parse(ev('window.__normal')); + const entries = JSON.parse(ev('JSON.stringify(ddosAll()[0].entries)')); + const total = Object.values(normal).reduce((n,p)=>n+p.traffic,0); + assert.ok(entries.some(p=>p.k==='t') && entries.some(p=>p.k==='p') && entries.some(p=>p.k==='ix')); + assert.deepEqual([...new Set(entries.map(p=>p.city))].sort(), ['fra','nyc']); + for (const en of entries) assert.ok(Math.abs(en.share-normal[en.k+':'+en.id].traffic/total)<1e-9); + assert.ok(Math.abs(entries.reduce((n,en)=>n+en.share,0)-1)<1e-9); + assert.match(ev('ddosPanel()'), /Live attack:/); + assert.doesNotMatch(ev('ddosPanel()'), /ports: .*regions:/, 'keep regional detail out of the live attack card'); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('S.ev.ddos.entries.length'), entries.length, 'distributed shares survive a save round trip'); + assert.deepEqual(errors, []); +}); + +test('distributed ingress applies upstream scrubbing only to its own port and uses regional centers', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].rgen=3;S.pops[c].bb={d:100}}S.transit=[{id:'tf',city:'fra',net:'cog',tier:2,clean:true},{id:'tn',city:'nyc',net:'cog',tier:2}];S.scrubs=[{city:'fra',tier:0}];S.ev.ddos={id:'spread',city:'fra',vec:'http',gbps:1000,start:0,until:7,entries:[{k:'t',id:'tf',city:'fra',share:0.25},{k:'t',id:'tn',city:'nyc',share:0.75}]};compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).reaching'), 775); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 750); + assert.equal(ev('R.useT.tn'), 400, 'the uncleaned flood fills its own ingress port'); + assert.ok(ev('R.useT.tf') < 200, 'it cannot spill into the cleaned port'); + assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 775 Gbps/); + assert.match(ev('ddosPanel()'), /~ 750 Gbps is leaking through/); + ev("S.scrubs.push({city:'nyc',tier:1});compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 0); + assert.match(ev('ddosPanel()'), /✓ Scrubbing in Frankfurt: 25\.0 Gbps \/ 100G/); + assert.match(ev('ddosPanel()'), /✓ Scrubbing in New York: 750 Gbps \/ 1T/); + assert.deepEqual(errors, []); +}); + +test('scrubbing hauls retain their real source on each link when several cities use one center', () => { + const { ev, errors, dom } = load(); + ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['prg','ber'])ACT.buildPop({city:c}); + for(const c in S.pops)S.pops[c].rgen=3; + S.links=[{id:'fp1',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100}, + {id:'fp2',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100}, + {id:'fb',a:'fra',b:'ber',kind:'wave',tier:2,km:420,mo:100}, + {id:'pb',a:'prg',b:'ber',kind:'wave',tier:2,km:280,mo:100}]; + S.transit=[{id:'tp',city:'prg',net:'cog',tier:2},{id:'tb',city:'ber',net:'cog',tier:2}]; + S.scrubs=[{city:'fra',tier:1}]; + S.ev.ddos={id:'spread',city:'ber',vec:'ack',gbps:100,start:0,until:7, + entries:[{k:'t',id:'tp',city:'prg',share:.5},{k:'t',id:'tb',city:'ber',share:.5}]};compute()`); + const sources = id => JSON.parse(ev(`JSON.stringify(Object.entries(R.ef[edgeKey(S.links.find(l=>l.id==='${id}'))].eg) + .filter(([key])=>key.startsWith('scrub:')).map(([key,g])=>({city:R.egDesc[key].city,g})).sort((a,b)=>a.city.localeCompare(b.city)))`)); + assert.equal(ev('R.load.pb||0'), 0, 'Berlin does not feed the Prague link'); + assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']); + assert.deepEqual(sources('fb').map(x=>x.city), ['ber']); + assert.ok(sources('fp1')[0].g>0 && sources('fb')[0].g>0); + assert.ok(Math.abs(sources('fp1')[0].g-ev('R.load.fp1+R.load.fp2'))<1e-9, 'the grouped record covers both parallel links exactly'); + ev("selectLink('fp1');draw(0)"); + const row = [...dom.window.document.querySelectorAll('#panelBody .row')].find(x=>x.querySelector('.nm')?.textContent==='Attack hauled to scrubbing in Frankfurt'); + assert.ok(row); + assert.match(row.querySelector('.meta').textContent, /^Prague · /); + assert.equal(JSON.parse(row.querySelector('[data-act="goEgress"]').dataset.args).city, 'prg'); + assert.deepEqual(JSON.parse(ev('JSON.stringify([...UI.feed])')), ['prg'], 'the map highlights the same source as the inspected link'); + row.querySelector('[data-act="goEgress"]').click(); + assert.equal(ev('UI.sel.id'), 'prg', 'Open goes to the actual source city'); + // Reordering ingress and adding an overlapping flood must not change the attribution. + ev("S.ev.ddos.entries.reverse();S.ev.ddosMore=[{...S.ev.ddos,id:'overlap',gbps:20,entries:S.ev.ddos.entries.slice().reverse()}];compute()"); + assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']); + assert.deepEqual(sources('fb').map(x=>x.city), ['ber']); + // When Berlin's direct link fails, its haul really does join Prague's route. + ev('S.links.find(l=>l.id==="fb").cut=S.day+1;compute()'); + assert.ok(ev('R.load.pb')>0); + assert.deepEqual(sources('fp1').map(x=>x.city), ['ber','prg']); + assert.deepEqual(sources('pb').map(x=>x.city), ['ber']); + assert.ok(Math.abs(sources('fp1').reduce((n,x)=>n+x.g,0)-ev('R.load.fp1+R.load.fp2'))<1e-9, 'shared-path totals still equal the actual link load'); + assert.deepEqual(errors, []); +}); + +function setupScrubLatency(ev) { + ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['par','nyc','ams'])ACT.buildPop({city:c}); + for(const c in S.pops)S.pops[c].rgen=RG.findIndex(g=>g.fs===1); + S.links=[{id:'pf',a:'par',b:'fra',kind:'wave',tier:3,km:620/1.3,mo:100}, + {id:'fn',a:'fra',b:'nyc',kind:'wave',tier:3,km:6000,mo:100}, + {id:'fa',a:'fra',b:'ams',kind:'wave',tier:3,km:200,mo:100}]; + S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:2}]; + S.scrubs=[{city:'fra',tier:0},{city:'par',tier:0}]; + S.ev.ddos={id:'par-flood',city:'par',vec:'dns',gbps:33.8,start:0,until:7, + entries:[{k:'t',id:'tf',city:'fra',share:0.65},{k:'t',id:'tn',city:'nyc',share:0.35}]};compute()`); +} + +test('distributed ingress does not give a locally protected victim a remote scrubbing latency', () => { + const { ev, errors, dom } = load(); + setupScrubLatency(ev); + assert.ok(ev("R.haul.some(q=>q.city==='nyc'&&q.to==='par'&&q.ms>60)"), 'the remote ingress still travels to its scrubbing center'); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts.length'), 2, 'both centers clean the distributed flood'); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-20.28)<1e-9); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 0); + Object.defineProperty(dom.window, 'innerWidth', { value: 360, configurable: true }); + ev("UI.left='noc';UI.leftOpen=true;renderLeft()"); + const text = dom.window.document.getElementById('left').textContent; + assert.match(text, /Live attack: Paris/); + assert.match(text, /Scrubbing in Frankfurt: 8\.8 Gbps/); + assert.match(text, /Scrubbing in Paris: 4\.7 Gbps/); + assert.doesNotMatch(text, /Scrubbing traffic hauled over your backbone|\+\d+(\.\d+)? ms/); + // A local center is still nearest when it is full and other centers take overflow. + ev("S.ev.ddos.vec='ack';S.ev.ddos.gbps=300;compute()"); + assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/); + assert.deepEqual(errors, []); +}); + +test('each attack shows only the nearest scrubbing detour using precise one-way link latency', () => { + const { ev, errors } = load(); + setupScrubLatency(ev); + ev("for(const c in S.pops)S.pops[c].rgen=3;S.scrubs=[{city:'fra',tier:0},{city:'ams',tier:0}];S.ev.ddos.vec='ack';S.ev.ddos.gbps=230;compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts.length'), 2, 'capacity spills between centers'); + const card = ev('ddosOne(S.ev.ddos)'); + assert.equal((card.match(/Scrubbing traffic hauled over your backbone/g)||[]).length, 1); + assert.match(card, /✓ Scrubbing traffic hauled over your backbone: Paris → Frankfurt \(\+3\.1 ms\)/); + // An overlapping attack has its own victim and nearest center. + ev("S.ev.ddosMore=[{id:'other',city:'ams',vec:'ack',gbps:10,start:0,until:7,entries:[{k:'t',id:'tn',city:'nyc',share:1}]}];compute()"); + assert.doesNotMatch(ev('ddosOne(S.ev.ddosMore[0])'), /Scrubbing traffic hauled over your backbone/); + assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Frankfurt \(\+3\.1 ms\)/); + // Ignore a failed nearby center and use the live path to Amsterdam. + ev("S.pops.fra.down=10;S.links.push({id:'pa',a:'par',b:'ams',kind:'wave',tier:3,km:2000,mo:100});S.ev.ddos.entries=[{k:'edge',city:'par',share:1}];compute()"); + assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Amsterdam \(\+13\.0 ms\)/); + ev('S.ev.ddos.bh=true;compute()'); + assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/); + ev('S.ev.ddos.bh=false;S.scrubMode="ondemand";compute()'); + assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/); + assert.deepEqual(errors, []); +}); + +test('a constrained remote haul leaves scrubbing capacity for the next overlapping flood', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc'])S.pops[c].rgen=3;S.links=[{id:'thin',a:'nyc',b:'fra',kind:'wave',tier:1,km:6000,mo:100}];S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'far',city:'nyc',vec:'http',gbps:600,start:0,until:7};S.ev.ddosMore=[{id:'near',city:'fra',vec:'http',gbps:900,start:0,until:7}];compute()"); + const clean = JSON.parse(ev('JSON.stringify(R.ddos.map(m=>({id:m.attack.id,clean:m.sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0,leak:m.leak})))')); + assert.equal(clean.find(m=>m.id==='near').clean, 900); + assert.ok(clean.find(m=>m.id==='far').clean <= 100); + assert.ok(clean.reduce((n,m)=>n+m.clean,0) <= 1000); + for (const m of clean) assert.equal(m.clean+m.leak, m.id==='near'?900:600); + assert.deepEqual(errors, []); +}); + +test('distributed attack statistics survive an ingress outage and corrupted saved shares', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});S.ev.ddos={id:'spread',city:'fra',vec:'http',gbps:1000,start:0,until:7,entries:[{k:'t',id:'a',city:'fra',share:0.25},{k:'t',id:'b',city:'nyc',share:0.75}]};S.pops.nyc.down=5;compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).reaching'), 1000); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 1000); + ev("S.ev.ddos.entries.push({k:'t',id:'bad',city:'unknown',share:5},{k:'t',id:'bad2',city:'fra',share:-1});S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + assert.equal(ev('S.ev.ddos.entries.length'), 2); + assert.equal(ev('S.ev.ddos.entries.reduce((n,en)=>n+en.share,0)'), 1); + assert.deepEqual(errors, []); +}); + +test('RackNet and TeamSpooked require signed gaming customers, bypass Flowspec, and stay within a third of the current size range', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=13;S.pops.fra.bb={d:150000};ACT.buyTransit({city:'fra',net:'cog',tier:2});compute()"); + assert.equal(ev("ddosVectors().includes('racknet')||ddosVectors().includes('teamspooked')"), false); + ev("S.offers=[{type:'game'}]"); + assert.equal(ev("ddosVectors().includes('racknet')"), false, 'an unsigned offer does not introduce gaming attacks'); + ev("S.biz=[{type:'game',id:'gamer',name:'Gamer',city:'fra',bw:0,rate:0}];compute()"); + for (const vec of ['racknet','teamspooked']) { + assert.equal(ev(`DDOS_VEC.${vec}.fs`), false); + const sizeMax = ev('ddosSizeMax()/3'); + ev(`const old=Math.random;let n=0;Math.random=()=>n++===1?(ddosVectors().indexOf('${vec}')+0.5)/ddosVectors().length:0.999999;ddosAttack();Math.random=old`); + assert.equal(ev('ddosAll().at(-1).vec'), vec); + assert.ok(ev('ddosAll().at(-1).gbps') <= sizeMax); + assert.ok(ev('ddosAll().at(-1).gbps') > sizeMax*(1-0.00002), 'the upper randomized quantile approaches the one-third limit, including rare spikes'); + } + ev("S.biz[0].type='cgame'"); + assert.equal(ev("ddosVectors().includes('teamspooked')"), true, 'cloud gaming also attracts these vectors'); + ev('S.biz=[]'); + assert.equal(ev("ddosVectors().includes('teamspooked')"), false); + assert.equal(ev('ddosAll().length'), 2, 'existing attacks finish naturally after the gaming customer leaves'); + assert.deepEqual(errors, []); +}); + +test('normal DDoS starts average half an attack per week without gaming and never exceed a seven-per-week expected rate', () => { + const { ev, errors } = load(); + ev('ACT.start({});S.day=50'); + const checks = JSON.parse(ev(` + const oldAttack=ddosAttack,oldRandom=Math.random,out=[]; + try { + for(const [level,games] of [[1,0],[13,0],[1,1],[13,1],[13,10],[13,1000]]){ + S.lvl=level;S.biz=Array.from({length:games},()=>({type:'game'})); + let starts=0,draw=0;ddosAttack=()=>{starts++};Math.random=()=>((draw++)+0.5)/14000; + for(let day=0;day<7000;day++)ddosTick(); + out.push({level,games,expected:ddosRate(),observed:starts/1000}); + } + } finally {ddosAttack=oldAttack;Math.random=oldRandom;} + JSON.stringify(out) + `)); + for(const row of checks){ + assert.ok(Math.abs(row.observed-row.expected)<=0.0011, JSON.stringify(row)); + if(row.games===0)assert.equal(row.observed,0.5); + else assert.ok(row.expected>0.5&&row.expected<=7); + } + assert.ok(checks[3].expected>checks[2].expected, 'level increases gaming frequency'); + assert.ok(checks[4].expected>checks[3].expected, 'more gaming customers increase frequency'); + assert.ok(checks[3].expected<0.8, 'one gaming customer does not suddenly add several attacks per week, even at the last level'); + assert.deepEqual(errors, []); +}); + +test('normal attack sizes match the one- and fifty-gamer targets while frequency rises gradually', () => { + const { ev, errors } = load(); + ev('ACT.start({})'); + const samples = JSON.parse(ev(` + const oldRandom=Math.random,out=[]; + try { + for(const [level,demand] of [[1,0],[3,1850],[LEVELS.length,LV_REQ.at(-1).pk]]){ + const counts=[]; + for(const games of [0,1,2,5,10,20,50,100,1000]){ + S.lvl=level;S.biz=Array.from({length:games},(_,i)=>({id:'g'+i,type:i%2?'cgame':'game',city:'fra',bw:0,rate:0})); + const vectors=ddosVectors();let sum=0; + for(let i=0;idraw++===1?(i+0.5)/vectors.length:roll; + ddosAttack(false);sum+=weight*S.ev.ddos.gbps; + } + counts.push({games,mean:sum/vectors.length,rate:ddosRate()}); + } + out.push({level,demand,counts}); + } + } finally {Math.random=oldRandom;} + JSON.stringify(out) + `)); + for(const row of samples){ + const [plain,first]=row.counts,fifty=row.counts.find(c=>c.games===50),hundred=row.counts.find(c=>c.games===100),many=row.counts.at(-1); + assert.ok(Math.abs(first.mean-plain.mean*3)<0.003, 'the first gamer triples the overall mean, allowing only bandwidth rounding: '+JSON.stringify(row)); + assert.ok(Math.abs(fifty.mean-plain.mean*8)<0.01, 'fifty gamers bring eightfold sizes, allowing only bandwidth rounding'); + assert.ok(hundred.mean>first.mean*3, 'growth continues across dozens of gaming customers'); + assert.ok(hundred.mean>plain.mean*10 && hundred.mean6 && many.rate<=7); + for(let i=1;irow.counts[i-1].mean, 'each sampled count increases actual spawned attack sizes'); + assert.ok(row.counts[i].rate>row.counts[i-1].rate, 'each sampled count increases frequency'); + } + } + assert.ok(Math.abs(samples[0].counts[0].mean-1)<0.001, 'the minimum-demand baseline still permits small attacks'); + assert.ok(Math.abs(samples[1].counts[0].mean-740/13)<0.001, 'the 1.85 Tbps non-gaming example keeps its average'); + assert.ok(Math.abs(samples[2].counts[0].mean-samples[2].demand*4/3/10)<0.001); + assert.deepEqual(errors, []); +}); + +test('normal attack sizes cover a broad ordinary range and a two-percent large tail without raising the mean', () => { + const { ev, errors } = load(); + ev('ACT.start({});S.lvl=3;S.biz=[];R.demand=1850'); + const distribution = JSON.parse(ev(` + const oldRandom=Math.random,ordinary=[],large=[];let sum=0; + try { + for(let i=0;i<10000;i++){ + Math.random=()=>(i+0.5)/10000; + const g=ddosSize('syn');sum+=g;(g>100?large:ordinary).push(g); + } + } finally {Math.random=oldRandom;} + JSON.stringify({ordinary:{n:ordinary.length,min:Math.min(...ordinary),max:Math.max(...ordinary)}, + large:{n:large.length,min:Math.min(...large),max:Math.max(...large),near500:large.some(g=>g>=490&&g<=510)},mean:sum/10000}) + `)); + assert.equal(distribution.ordinary.n, 9800); + assert.equal(distribution.large.n, 200); + assert.ok(distribution.ordinary.min>=8.9 && distribution.ordinary.min<10); + assert.ok(distribution.ordinary.max>85 && distribution.ordinary.max<=89.1); + assert.ok(distribution.ordinary.max/distribution.ordinary.min>9.9); + assert.ok(distribution.large.min>=356 && distribution.large.max<=535); + assert.ok(distribution.large.near500, 'the example network can occasionally face a roughly 500 Gbps flood'); + assert.ok(Math.abs(distribution.mean-740/13)<0.001, 'the rare tail preserves the previous 56.923 Gbps average'); + // Verify that real spawns use both bands, not just the standalone sampler. + for (const [roll,minimum,maximum] of [[0.49,8.9,89.1],[0.99,356,535]]) { + ev(`S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];R.demand=1850;const old=Math.random;let n=0;Math.random=()=>{const i=n++;return i===1?(ddosVectors().indexOf('syn')+0.5)/ddosVectors().length:i===2?${roll}:0.5};try{ddosAttack()}finally{Math.random=old}`); + assert.equal(ev('S.ev.ddos.vec'), 'syn'); + assert.ok(ev('S.ev.ddos.gbps')>=minimum && ev('S.ev.ddos.gbps')<=maximum); + } + assert.deepEqual(errors, []); +}); + +test('Flood Season retains its existing size quantiles and escalation when normal attacks gain rare spikes', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.scn={id:'flood',rules:{ddos:true}};S.lvl=3;S.biz=[];R.demand=1850"); + for (const [day,expected] of [[0,[700,1400,2099]],[365,[1400,2800,4199]],[730,[2100,4200,6299]]]) { + ev(`S.day=${day}`); + const actual = JSON.parse(ev("const old=Math.random;let sizes;try{sizes=[0,0.5,0.999999].map(r=>{Math.random=()=>r;return ddosSize('syn')})}finally{Math.random=old}JSON.stringify(sizes)")); + assert.deepEqual(actual, expected); + } + assert.deepEqual(errors, []); +}); diff --git a/tests/helpers/reference-allocation.js b/tests/helpers/reference-allocation.js index a5c557c..52e6af4 100644 --- a/tests/helpers/reference-allocation.js +++ b/tests/helpers/reference-allocation.js @@ -5,8 +5,8 @@ module.exports = ` for(f of flows){ if(f.rem<=1e-6||(rank===0&&!f.cache)||(pass&&!pass(f)))continue; Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++; - const candidates=E.filter(e=>e.usede.used(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||Dv[CIDX[a.city]]-Dv[CIDX[b.city]]); for(let i=0;i1e-6;){ let j=i+1;while(j= 3, 'starts with bigger gear unlocked'); // a few weeks in: several attacks start on their own schedule let n = 0; - for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('!!(S.ev.ddos&&S.ev.ddos.start===S.day)')) n++; } + for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('ddosAll().some(a=>a.start===S.day)')) n++; } assert.ok(n >= 4, `attacks keep coming (${n} in 40 days)`); assert.ok(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)') >= 3, 'finished attacks are scored'); // scoring: held only if service stayed at 97%+ @@ -468,3 +468,27 @@ test('RouteScript: help, ready-made scripts and the AI button', () => { ev("UI.dtab='overview';renderAll()"); assert.deepEqual(errors, []); }); + + +test('Flood Season keeps attacking and escalating after both success and timeout', () => { + for (const outcome of ['done', 'failed']) { + const { ev, errors, dom } = load(); + ev("ACT.startScn({id:'flood',sure:1});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9"); + if (outcome === 'done') ev('S.stats.ddosOk=20;S.stats.ddosOkBig=5;S.day=100'); + else ev('S.day=365'); + ev('scnTick(S.day)'); + assert.ok(ev(`!!S.scn.${outcome}`)); + assert.ok([...dom.window.document.querySelectorAll('#modal [data-act="closeModal"]')].some(b=>b.textContent==='Keep playing')); + ev('ACT.closeModal();S.scn.nextDdos=S.day+1;dayTick()'); + assert.equal(ev('S.ev.ddos.start'), ev('S.day'), 'Keep playing still spawns attacks'); + const before = ev('S.day'); + ev('S.scn.nextDdos=S.day+1;S.day+=8;dayTick()'); + assert.ok(ev('ddosAll().at(-1).start') > before, 'subsequent attacks keep coming'); + const gaps = JSON.parse(ev('const old=Math.random;Math.random=()=>0.5;S.day=0;const early=floodGap();S.day=1000;const late=floodGap();Math.random=old;JSON.stringify([early,late])')); + assert.ok(gaps[1] < gaps[0], 'frequency keeps increasing with scenario age'); + const sizes = JSON.parse(ev('const old=Math.random;Math.random=()=>0.9;S.day=0;ddosAttack();const early=ddosAll().at(-1).gbps;S.day=1000;ddosAttack();const late=ddosAll().at(-1).gbps;Math.random=old;JSON.stringify([early,late])')); + assert.ok(sizes[1] > sizes[0], 'intensity keeps increasing with scenario age'); + assert.deepEqual(errors, []); + dom.window.close(); + } +}); diff --git a/tests/routing-reference.test.js b/tests/routing-reference.test.js index 8742007..8a239ad 100644 --- a/tests/routing-reference.test.js +++ b/tests/routing-reference.test.js @@ -38,6 +38,7 @@ test('indexed routing matches the simple allocation loop across network changes' "S.te.script='prefer transit Cogentle\\nprepend transit Cogentle 2\\nprotect customers'", "S.ev.rpki={nets:['ggl','nfx'],until:S.day+3};S.ev.depeer=S.day+3", "S.ev.ddos={city:'fra',until:S.day+3,gbps:300,vec:'syn',entry:{k:'edge'}}", + "S.ev.ddos.entries=[{k:'t',id:'transit0',city:'fra',share:.4},{k:'t',id:'transit4',city:'nyc',share:.6}]", "S.links[0].eqDown=S.day+2;S.links[1].cut=S.day+2;S.links[2].loss={until:S.day+2,f:0.5}", "S.links[4].chFail={until:S.day+2,o:'tp16'};S.links[6].ch.push('zr4');S.links[8].regen=2", "S.day+=4;S.pni.splice(0,20);S.caches.splice(0,10);S.transit[0].pref='high'", diff --git a/tests/services.test.js b/tests/services.test.js index 5379cdc..9ba8bc5 100644 --- a/tests/services.test.js +++ b/tests/services.test.js @@ -9,6 +9,30 @@ function network(ev) { ev("const L=(a,b,t,v)=>{UI.via=v||null;openLinkModal(a,b);ACT.buildLink({tier:t});};L('fra','ams',3);L('fra','par',3);L('ams','lon',2,'uly');closeModal()"); } +test('gaming offers and signed customers show their DDoS risk in Deals, city panels and customer lists', () => { + const { ev, errors, dom } = load(); + ev("ACT.start({});S.cash=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.offers=['game','cgame','host'].map(type=>({id:type,city:'fra',name:type,bw:5,rate:100,reqs:[],exp:S.day+30,type}));UI.left='deals';UI.leftOpen=true;renderLeft()"); + const notes = (root, action) => { + const buttons = [...root.querySelectorAll(`[data-act="${action}"]`)]; + assert.equal(buttons.length, 3); + for (const button of buttons) { + const id = JSON.parse(button.dataset.args).id; + const count = (button.closest('.row').textContent.match(/Gaming attracts attacks/g)||[]).length; + assert.equal(count, id==='game'||id==='cgame'?1:0, `risk note for ${id}`); + } + }; + assert.equal(ev('gamingCount()'), 0, 'offers disclose future risk before signing'); + notes(dom.window.document.getElementById('leftBody'), 'accept'); + ev("selectCity('fra');ACT.tab({t:'cust'})"); + notes(dom.window.document.getElementById('panelBody'), 'accept'); + ev("for(const id of ['game','cgame','host'])ACT.accept({id});UI.tab='cust';renderPanel()"); + assert.equal(ev('gamingCount()'), 2, 'the note uses the same customer classification as the attack calculation'); + notes(dom.window.document.getElementById('panelBody'), 'dropBiz'); + ev('ACT.custOpen({})'); + notes(dom.window.document.getElementById('custSec'), 'custGo'); + assert.deepEqual(errors, []); +}); + test('event networks pay in full when the crowd is served, nothing up front', () => { const { ev, errors } = load(); seed(ev, 4);