Catalyst / admin/AirportCyberSimulator 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / AirportCyberSimulator

public

Airport Cyber Attack Simulation Application

Code Issues Pull requests Pipelines Packages Security Insights Wiki Settings
AirportCyberSimulator / airport-cyber-sim-v2-exe / src / main.py 25004 B · main
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
"""
Airport Cyber Resilience Simulator — V2 Backend
================================================
FastAPI application with a server-authoritative simulation engine.

Key V2 upgrades over V1:
  * Airport profiling: the client picks a UK airport; all financials scale to
    that airport's economic profile (revenue/sec + regulatory fine multiplier).
  * Dynamic multiplier math engine: a 1-second asyncio loop recomputes
    Total_Loss = Operational_Cost + Regulatory_Fines + Mitigation_Costs live.
  * Crisis-communications state machine (proactive -> reactive -> blackout)
    driving a reputational-loss multiplier applied to the operational bleed.
  * 26 nodes, 9 playbooks — all data-driven from /data.

Everything remains data-driven: add airports, nodes, links or playbooks by
editing /data only.
"""

from __future__ import annotations

import asyncio
import json
import random
import sys
import time
from pathlib import Path
from typing import Any, Dict, List, Optional

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles

# When frozen by PyInstaller the bundled data/ and static/ folders are extracted
# under sys._MEIPASS; otherwise resolve them next to this file (Docker/dev).
if getattr(sys, "frozen", False):
    BASE_DIR = Path(getattr(sys, "_MEIPASS", Path(sys.executable).resolve().parent))
else:
    BASE_DIR = Path(__file__).resolve().parent
DATA_DIR = BASE_DIR / "data"
STATIC_DIR = BASE_DIR / "static"


def load_json(name: str) -> Any:
    with (DATA_DIR / name).open("r", encoding="utf-8") as fh:
        return json.load(fh)


AIRPORTS = load_json("airports.json")
INFRASTRUCTURE = load_json("infrastructure.json")
PLAYBOOKS = load_json("playbooks.json")

AIRPORT_INDEX = {a["airport_id"]: a for a in AIRPORTS["airports"]}
PLAYBOOK_INDEX = {p["playbook_id"]: p for p in PLAYBOOKS}
NODE_INDEX = {n["id"]: n for n in INFRASTRUCTURE["nodes"]}

# --------------------------------------------------------------------------- #
# Engine tuning constants
# --------------------------------------------------------------------------- #

# Downtime penalty per operational state. Spec-mandated values for
# normal/throttled/isolated; compromised/patching are engineering additions so
# an un-mitigated breach still bleeds.
DOWNTIME = {
    "normal": 0.0, "ingress": 0.0, "compromised": 0.8, "throttled": 0.6,
    "isolated": 1.0, "patching": 0.8, "patched": 0.0,
}
CAPACITY = {
    "normal": 100, "ingress": 100, "compromised": 70, "throttled": 40,
    "isolated": 0, "patching": 70, "patched": 100,
}

PATCH_FEE = 50_000          # £ flat emergency incident-response fee
PATCH_SECONDS = 5           # patch countdown — must beat the incoming spread
THROTTLE_SLOWDOWN = 5.0     # remaining spread delay multiplier (80% slower)
SECURITY_HIT = 12           # % security integrity lost per breached node

SPREAD_JITTER = 0.22        # ±% per-run randomisation of each spread interval
CONTAINMENT_QUIET = 5.0     # s of no new compromise before "Attack Contained"
MISS_NOTIFY_PENALTY = 500_000  # £ enforcement penalty per missed statutory notification

COMMS_PROACTIVE_WINDOW = 15  # s to release a proactive statement
COMMS_REACTIVE_WINDOW = 15   # s to answer the media barrage before blackout
REP_DEFAULT = 1.0
REP_PROACTIVE = 0.5
REP_REACTIVE = 1.0
REP_BLACKOUT = 3.0


def short_money(n: float) -> str:
    n = float(n)
    if abs(n) >= 1e6:
        return f{n / 1e6:.1f}M"
    if abs(n) >= 1e3:
        return f{n / 1e3:.0f}k"
    return f{n:.0f}"


# --------------------------------------------------------------------------- #
# Simulation
# --------------------------------------------------------------------------- #


class Simulation:
    def __init__(self, ws: WebSocket) -> None:
        self.ws = ws
        self.airport = AIRPORT_INDEX["LHR"]      # default until configured
        self.audio = True
        self.playbook: Optional[Dict[str, Any]] = None

        self.running = False
        self.tasks: List[asyncio.Task] = []

        self.node_state: Dict[str, str] = {}
        self.node_vector: Dict[str, str] = {}
        self.chain: List[Dict[str, Any]] = []
        self.patching: Dict[str, bool] = {}      # node -> patch failed flag

        # Financials
        self.operational = 0.0
        self.regulatory = 0.0
        self.mitigation = 0.0
        self.clock = 0

        # Crisis comms
        self.rep_mult = REP_DEFAULT
        self.comms_phase = "idle"                 # idle|proactive|reactive|handled|blackout|success

        self._reset_state()

    # -- helpers ----------------------------------------------------------- #

    def _reset_state(self) -> None:
        self.node_state = {nid: "normal" for nid in NODE_INDEX}
        self.node_vector = {}
        self.chain = []
        self.patching = {}
        self.operational = self.regulatory = self.mitigation = 0.0
        self.clock = 0
        self.rep_mult = REP_DEFAULT
        self.comms_phase = "idle"
        self.last_compromise = None          # monotonic time of the last breach
        self.contained_since = None          # monotonic time containment began
        self.attack_start = None             # monotonic time the spread clock began
        self.required_notify = {"caa": False, "dft": False}
        self.notified = {"caa": False, "dft": False}
        self.settled = False                 # notification duties reconciled at end

    async def send(self, payload: Dict[str, Any]) -> None:
        try:
            await self.ws.send_text(json.dumps(payload))
        except (WebSocketDisconnect, RuntimeError):
            self.running = False

    def _breached_count(self) -> int:
        return sum(1 for s in self.node_state.values()
                   if s in ("compromised", "throttled", "isolated", "patching"))

    def _capacity(self) -> float:
        tot_w = sum(n["impact"] for n in INFRASTRUCTURE["nodes"])
        weighted = sum(CAPACITY[self.node_state[n["id"]]] * n["impact"]
                       for n in INFRASTRUCTURE["nodes"])
        return round(weighted / tot_w, 1)

    def _bleed_per_sec(self) -> float:
        rev = self.airport["base_revenue_per_sec"]
        total = 0.0
        for n in INFRASTRUCTURE["nodes"]:
            total += rev * n["impact"] * DOWNTIME[self.node_state[n["id"]]]
        return total * self.rep_mult

    async def _emit_metrics(self) -> None:
        total = self.operational + self.regulatory + self.mitigation
        await self.send({
            "type": "metrics",
            "metrics": {
                "operational": round(self.operational),
                "regulatory": round(self.regulatory),
                "mitigation": round(self.mitigation),
                "total": round(total),
                "bleed_per_sec": round(self._bleed_per_sec()),
                "reputational_multiplier": self.rep_mult,
                "security_integrity": max(0, round(100 - SECURITY_HIT * self._breached_count(), 1)),
                "operational_capacity": self._capacity(),
                "clock": self.clock,
            },
        })

    # -- lifecycle --------------------------------------------------------- #

    async def configure(self, airport_id: str, audio: bool) -> None:
        self.airport = AIRPORT_INDEX.get(airport_id, self.airport)
        self.audio = bool(audio)
        await self.stop_tasks()
        self._reset_state()
        await self.send({"type": "config_ok", "airport": self.airport, "audio": self.audio})
        await self._emit_metrics()

    async def launch(self, playbook_id: str) -> None:
        """Called by the client once its 5-second countdown reaches zero."""
        await self.stop_tasks()
        pb = PLAYBOOK_INDEX.get(playbook_id)
        if not pb:
            await self.send({"type": "error", "message": f"Unknown playbook {playbook_id}"})
            return
        self._reset_state()
        self.playbook = pb
        self.running = True

        # Build the attack chain. Each scenario has its own base tempo (fast /
        # medium / slow); on top of that we jitter every spread interval a little
        # each run, so a borderline attack sometimes beats the patch and
        # sometimes does not. Intervals stay ordered and never drop below 1.5s.
        prev = pb["ingress_point"]
        prev_orig = 0.0
        prev_delay = 0.0
        for ev in pb["spread_events"]:
            orig = float(ev["delay_seconds"])
            interval = max(0.0, orig - prev_orig)
            jittered = interval * random.uniform(1 - SPREAD_JITTER, 1 + SPREAD_JITTER)
            delay = prev_delay + max(1.5, jittered)
            self.chain.append({
                "source": prev, "target": ev["target"],
                "delay": round(delay, 1), "vector": ev["vector"],
                "fired": False, "cancelled": False,
            })
            prev_orig = orig
            prev_delay = delay
            prev = ev["target"]

        notif = pb.get("notifications", {})
        self.required_notify = {
            "caa": bool(notif.get("caa", {}).get("required")),
            "dft": bool(notif.get("dft", {}).get("required")),
        }

        await self.send({"type": "launch", "playbook": pb, "ingress_node": pb["ingress_point"]})
        await self.send({
            "type": "notify_required",
            "caa": self.required_notify["caa"],
            "dft": self.required_notify["dft"],
            "caa_reason": notif.get("caa", {}).get("reason", ""),
            "dft_reason": notif.get("dft", {}).get("reason", ""),
        })
        self.tasks = [
            asyncio.create_task(self._clock_loop()),
            asyncio.create_task(self._attack_loop()),
            asyncio.create_task(self._comms_loop()),
            asyncio.create_task(self._containment_watch()),
        ]

    async def _clock_loop(self) -> None:
        """1 Hz math engine: accrue operational bleed and stream metrics."""
        while self.running:
            await asyncio.sleep(1.0)
            if not self.running:
                break
            self.clock += 1
            self.operational += self._bleed_per_sec()
            await self.send({"type": "tick", "t": self.clock})
            await self._emit_metrics()

    async def _attack_loop(self) -> None:
        pb = self.playbook
        assert pb is not None
        ingress = pb["ingress_point"]

        await self.send({"type": "ingress", "node": ingress,
                         "method": pb["ingress_method"], "icon": pb["ingress_icon"]})
        self.node_state[ingress] = "ingress"
        await asyncio.sleep(2.0)
        await self._compromise(ingress, pb["ingress_method"], initial=True)

        start_t = time.monotonic()
        self.attack_start = start_t
        idx = 0
        while self.running and idx < len(self.chain):
            hop = self.chain[idx]
            while self.running and not hop["cancelled"]:
                if time.monotonic() - start_t >= hop["delay"]:
                    break
                await asyncio.sleep(0.1)
            if not self.running:
                return
            # A hop can only fire if its source is a live threat. If the source
            # was isolated, patched, or never actually compromised (because an
            # upstream hop was blocked), the spread is contained here.
            if hop["cancelled"] or self.node_state[hop["source"]] not in ("compromised", "throttled", "patching"):
                hop["cancelled"] = True
                await self.send({"type": "spread_blocked", "source": hop["source"], "target": hop["target"]})
                idx += 1
                continue

            # A spread tick from a patching node overrides its patch (fails it).
            if self.node_state[hop["source"]] == "patching":
                self.patching[hop["source"]] = True  # mark failed

            await self.send({"type": "spread", "source": hop["source"],
                             "target": hop["target"], "vector": hop["vector"]})
            hop["fired"] = True
            await self._compromise(hop["target"], hop["vector"])
            idx += 1

        # If mitigation blocked part of the chain, the containment watcher owns
        # the terminal state ("Attack Contained"). Only announce a clean
        # completion when the attack ran its full course unhindered.
        if self.running and not any(h["cancelled"] for h in self.chain):
            await self._settle_notifications()
            await self.send({"type": "sim_complete"})

    async def _comms_loop(self) -> None:
        """Proactive window -> reactive barrage -> blackout escalation."""
        self.comms_phase = "proactive"
        await self.send({"type": "comms_state", "phase": "proactive",
                         "message": "Proactive media window open — release a statement within 15s.",
                         "reputational_multiplier": self.rep_mult})
        await asyncio.sleep(COMMS_PROACTIVE_WINDOW)
        if not self.running or self.comms_phase in ("success", "handled"):
            return

        # Ignored -> reactive barrage.
        self.comms_phase = "reactive"
        await self.send({"type": "comms_state", "phase": "reactive",
                         "message": "Proactive window missed — journalists are calling and emailing.",
                         "reputational_multiplier": self.rep_mult})
        await asyncio.sleep(COMMS_REACTIVE_WINDOW)
        if not self.running or self.comms_phase in ("handled", "success"):
            return

        # Ignored again -> communications blackout.
        self.comms_phase = "blackout"
        self.rep_mult = REP_BLACKOUT
        await self.send({"type": "comms_state", "phase": "blackout",
                         "message": "COMMUNICATIONS BLACKOUT — public panic; reputational bleed tripled.",
                         "reputational_multiplier": self.rep_mult})
        await self._emit_metrics()

    # -- containment ------------------------------------------------------- #

    def _spread_halted(self) -> bool:
        """True when no pending hop can still compromise another node."""
        for h in self.chain:
            if (not h["fired"] and not h["cancelled"]
                    and self.node_state.get(h["source"]) in ("ingress", "compromised", "throttled", "patching")):
                return False
        return True

    async def _containment_watch(self) -> None:
        """Declare 'Attack Contained' once mitigation halts the spread and no
        new node is compromised for CONTAINMENT_QUIET seconds."""
        while self.running:
            await asyncio.sleep(0.4)
            if not self.running:
                return
            if self.last_compromise is None:
                continue
            contained = self._spread_halted() and any(h["cancelled"] for h in self.chain)
            if contained:
                if self.contained_since is None:
                    self.contained_since = time.monotonic()
                elif time.monotonic() - self.contained_since >= CONTAINMENT_QUIET:
                    await self._declare_contained()
                    return
            else:
                self.contained_since = None

    async def _declare_contained(self) -> None:
        await self._settle_notifications()
        self.running = False
        await self.send({"type": "contained", "message": "Attack Contained"})
        await self._emit_metrics()

    # -- statutory notifications ------------------------------------------- #

    async def notify(self, kind: str) -> None:
        if kind not in ("caa", "dft") or not self.playbook:
            return
        agency = "Civil Aviation Authority" if kind == "caa" else "Department for Transport"
        if not self.required_notify.get(kind):
            await self.send({"type": "notify_ack", "kind": kind, "status": "not_required",
                             "message": f"No {agency} notification duty for this incident type."})
            return
        if self.notified.get(kind):
            return
        self.notified[kind] = True
        await self.send({"type": "notify_ack", "kind": kind, "status": "done",
                         "message": f"{agency} notified — statutory reporting duty satisfied."})
        await self._emit_metrics()

    async def _settle_notifications(self) -> None:
        """Penalise any required notification the player failed to make."""
        if self.settled:
            return
        self.settled = True
        for kind in ("caa", "dft"):
            if self.required_notify.get(kind) and not self.notified.get(kind):
                agency = "CAA" if kind == "caa" else "DfT"
                fine = MISS_NOTIFY_PENALTY * self.airport["regulatory_fine_multiplier"]
                self.regulatory += fine
                await self.send({"type": "notify_missed", "kind": kind,
                                 "amount": round(fine),
                                 "message": f"Failure to notify {agency} within the statutory window — enforcement penalty."})
        await self._emit_metrics()

    async def comms(self, kind: str) -> None:
        if kind == "proactive" and self.comms_phase == "proactive":
            self.comms_phase = "success"
            self.rep_mult = REP_PROACTIVE
            await self.send({"type": "comms_state", "phase": "success",
                             "message": "Proactive statement released — reputational impact halved.",
                             "reputational_multiplier": self.rep_mult})
            await self._emit_metrics()
        elif kind == "reactive" and self.comms_phase == "reactive":
            self.comms_phase = "handled"
            self.rep_mult = REP_REACTIVE
            await self.send({"type": "comms_state", "phase": "handled",
                             "message": "Media briefed reactively — baseline reputational penalty held.",
                             "reputational_multiplier": self.rep_mult})
            await self._emit_metrics()

    # -- node events ------------------------------------------------------- #

    async def _compromise(self, node: str, vector: str, initial: bool = False) -> None:
        if self.node_state.get(node) in ("compromised", "isolated", "throttled", "patched", "patching"):
            return
        self.node_state[node] = "compromised"
        self.node_vector[node] = vector
        self.last_compromise = time.monotonic()
        self.contained_since = None
        await self.send({"type": "compromised", "node": node, "vector": vector,
                         "initial": initial, "compliance": NODE_INDEX[node].get("compliance")})

        meta = NODE_INDEX[node]
        if meta.get("data_sensitive"):
            fine = meta["flat_fine"] * self.airport["regulatory_fine_multiplier"]
            self.regulatory += fine
            await self.send({"type": "fine", "node": node, "amount": round(fine),
                             "label": f"-{short_money(fine)} Regulatory Penalty"})
        await self._emit_metrics()

    # -- mitigations ------------------------------------------------------- #

    async def mitigate(self, node: str, option: str) -> None:
        if node not in self.node_state:
            return
        option = option.upper()

        if option == "ISOLATE":
            self.node_state[node] = "isolated"
            for hop in self.chain:
                if hop["source"] == node and not hop["fired"]:
                    hop["cancelled"] = True
            await self.send({"type": "mitigation", "node": node, "option": "ISOLATE",
                             "message": f"{NODE_INDEX[node]['name']} isolated — links severed, spread halted, capacity 0%."})

        elif option == "THROTTLE":
            self.node_state[node] = "throttled"
            for hop in self.chain:
                if hop["source"] == node and not hop["fired"] and not hop["cancelled"]:
                    hop["delay"] *= THROTTLE_SLOWDOWN
            await self.send({"type": "mitigation", "node": node, "option": "THROTTLE",
                             "message": f"{NODE_INDEX[node]['name']} throttled — spread slowed 80%, capacity 40%."})

        elif option == "STOP":
            self.mitigation += PATCH_FEE
            self.patching[node] = False
            self.node_state[node] = "patching"
            # Work out where the attack is heading from this node, and how long
            # until it arrives — so the client can show the spread closing in on
            # the next node while the patch counts down.
            approach_target = None
            approach_seconds = None
            for hop in self.chain:
                if hop["source"] == node and not hop["fired"] and not hop["cancelled"]:
                    approach_target = hop["target"]
                    if self.attack_start is not None:
                        approach_seconds = round(max(0.2, hop["delay"] - (time.monotonic() - self.attack_start)), 1)
                    break
            eta = f" — attack reaches {NODE_INDEX[approach_target]['name']} in {approach_seconds}s" if approach_target else ""
            await self.send({"type": "patch_start", "node": node, "seconds": PATCH_SECONDS,
                             "target": approach_target, "approach_seconds": approach_seconds,
                             "message": f"Emergency patch on {NODE_INDEX[node]['name']} (£50k) — {PATCH_SECONDS}s{eta}."})
            self.tasks.append(asyncio.create_task(self._patch(node)))
        else:
            return

        await self._emit_metrics()

    async def _patch(self, node: str) -> None:
        end = time.monotonic() + PATCH_SECONDS
        while self.running and time.monotonic() < end:
            if self.patching.get(node):  # overridden by a spread tick
                break
            await asyncio.sleep(0.1)
        if not self.running:
            return
        failed = self.patching.get(node, False)
        if failed:
            self.node_state[node] = "compromised"
            await self.send({"type": "patch_complete", "node": node, "success": False})
        else:
            self.node_state[node] = "patched"
            for hop in self.chain:
                if hop["source"] == node and not hop["fired"]:
                    hop["cancelled"] = True
            await self.send({"type": "patch_complete", "node": node, "success": True})
        await self._emit_metrics()

    # -- teardown ---------------------------------------------------------- #

    async def stop_tasks(self) -> None:
        self.running = False
        for t in self.tasks:
            if not t.done():
                t.cancel()
        for t in self.tasks:
            try:
                await t
            except asyncio.CancelledError:
                pass
        self.tasks = []

    async def reset(self) -> None:
        await self.stop_tasks()
        self._reset_state()
        await self.send({"type": "reset"})
        await self._emit_metrics()


# --------------------------------------------------------------------------- #
# FastAPI wiring
# --------------------------------------------------------------------------- #

app = FastAPI(title="Airport Cyber Resilience Simulator V2")


@app.get("/api/bootstrap")
async def api_bootstrap() -> JSONResponse:
    return JSONResponse({
        "airports": AIRPORTS,
        "infrastructure": INFRASTRUCTURE,
        "playbooks": PLAYBOOKS,
    })


@app.get("/api/airports")
async def api_airports() -> JSONResponse:
    return JSONResponse(AIRPORTS)


@app.get("/api/infrastructure")
async def api_infrastructure() -> JSONResponse:
    return JSONResponse(INFRASTRUCTURE)


@app.get("/api/playbooks")
async def api_playbooks() -> JSONResponse:
    return JSONResponse(PLAYBOOKS)


@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket) -> None:
    await ws.accept()
    sim = Simulation(ws)
    await sim._emit_metrics()
    try:
        while True:
            msg = json.loads(await ws.receive_text())
            action = msg.get("action")
            if action == "configure":
                await sim.configure(msg.get("airport_id", "LHR"), msg.get("audio", True))
            elif action == "launch":
                await sim.launch(msg.get("playbook_id", ""))
            elif action == "mitigate":
                await sim.mitigate(msg.get("node", ""), msg.get("option", ""))
            elif action == "comms":
                await sim.comms(msg.get("kind", ""))
            elif action == "notify":
                await sim.notify(msg.get("kind", ""))
            elif action == "reset":
                await sim.reset()
            elif action == "ping":
                await sim.send({"type": "pong"})
    except WebSocketDisconnect:
        await sim.stop_tasks()
    except Exception:
        await sim.stop_tasks()


app.mount("/", StaticFiles(directory=str(STATIC_DIR), html=True), name="static")