Catalyst / admin/Synapse-Sonar 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / Synapse-Sonar

public

Attack Surface Simulation

Code Issues Pull requests Pipelines Packages Security Insights Wiki Settings
Synapse-Sonar / synapse-sonar / docs / generate_guides.py 29952 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
590
591
#!/usr/bin/env python3
"""Generate the Synapse Sonar User/Admin guide and Agent guide as branded PDFs."""
import os
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_LEFT
from reportlab.platypus import (
    BaseDocTemplate, PageTemplate, Frame, Paragraph, Spacer, Table, TableStyle,
    Preformatted, PageBreak, ListFlowable, ListItem,
)

# Output PDFs next to this script (the docs folder).
OUT_DIR = os.path.dirname(os.path.abspath(__file__))
os.makedirs(OUT_DIR, exist_ok=True)

VERSION = "MVP 0.1"
DATE = "30 June 2026"

# --- brand palette ---
SPACE = colors.HexColor("#05080f")
SLATE = colors.HexColor("#0f172a")
SLATE2 = colors.HexColor("#1e293b")
CYAN = colors.HexColor("#06b6d4")
VIOLET = colors.HexColor("#8b5cf6")
BLUE = colors.HexColor("#3b82f6")
IRON = colors.HexColor("#475569")
INK = colors.HexColor("#1e293b")
MUTED = colors.HexColor("#64748b")
LIGHTBG = colors.HexColor("#f1f5f9")
CODEBG = colors.HexColor("#0f172a")
CODEFG = colors.HexColor("#e2e8f0")

PAGE_W, PAGE_H = A4
LMARGIN = RMARGIN = 20 * mm
TMARGIN = 22 * mm
BMARGIN = 18 * mm
CONTENT_W = PAGE_W - LMARGIN - RMARGIN

# --- styles ---
ss = getSampleStyleSheet()
styles = {
    "h1": ParagraphStyle("h1", parent=ss["Heading1"], fontName="Helvetica-Bold",
                         fontSize=18, leading=22, spaceBefore=18, spaceAfter=8,
                         textColor=SLATE),
    "h2": ParagraphStyle("h2", parent=ss["Heading2"], fontName="Helvetica-Bold",
                         fontSize=13, leading=17, spaceBefore=14, spaceAfter=5,
                         textColor=BLUE),
    "h3": ParagraphStyle("h3", parent=ss["Heading3"], fontName="Helvetica-Bold",
                         fontSize=11, leading=14, spaceBefore=10, spaceAfter=3,
                         textColor=SLATE2),
    "body": ParagraphStyle("body", parent=ss["BodyText"], fontName="Helvetica",
                           fontSize=9.5, leading=14, textColor=INK, spaceAfter=6,
                           alignment=TA_LEFT),
    "bullet": ParagraphStyle("bullet", parent=ss["BodyText"], fontName="Helvetica",
                             fontSize=9.5, leading=13.5, textColor=INK),
    "code": ParagraphStyle("code", fontName="Courier", fontSize=8.3, leading=11.5,
                           textColor=CODEFG),
    "note": ParagraphStyle("note", fontName="Helvetica", fontSize=9, leading=13,
                           textColor=SLATE2),
    "th": ParagraphStyle("th", fontName="Helvetica-Bold", fontSize=9, leading=12,
                         textColor=colors.white),
    "td": ParagraphStyle("td", fontName="Helvetica", fontSize=9, leading=12,
                         textColor=INK),
    "tdmono": ParagraphStyle("tdmono", fontName="Courier", fontSize=8.5, leading=12,
                             textColor=INK),
    "cover_title": ParagraphStyle("ct", fontName="Helvetica-Bold", fontSize=26,
                                  leading=30, textColor=colors.white),
    "cover_sub": ParagraphStyle("cs", fontName="Helvetica", fontSize=13,
                                leading=18, textColor=colors.HexColor("#94a3b8")),
}


def H1(t): return Paragraph(t, styles["h1"])
def H2(t): return Paragraph(t, styles["h2"])
def H3(t): return Paragraph(t, styles["h3"])
def P(t): return Paragraph(t, styles["body"])


def UL(items):
    return ListFlowable(
        [ListItem(Paragraph(i, styles["bullet"]), leftIndent=10,
                  value="•", bulletColor=CYAN) for i in items],
        bulletType="bullet", start="•", leftIndent=14, spaceAfter=6,
    )


def CODE(text):
    p = Preformatted(text, styles["code"])
    t = Table([[p]], colWidths=[CONTENT_W])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), CODEBG),
        ("LEFTPADDING", (0, 0), (-1, -1), 9),
        ("RIGHTPADDING", (0, 0), (-1, -1), 9),
        ("TOPPADDING", (0, 0), (-1, -1), 7),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 7),
        ("ROUNDEDCORNERS", [4, 4, 4, 4]),
    ]))
    return t


def NOTE(text, accent=CYAN, label="Note"):
    inner = Paragraph(f'<b>{label}.</b> {text}', styles["note"])
    t = Table([[inner]], colWidths=[CONTENT_W])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), LIGHTBG),
        ("LINEBEFORE", (0, 0), (0, -1), 3, accent),
        ("LEFTPADDING", (0, 0), (-1, -1), 10),
        ("RIGHTPADDING", (0, 0), (-1, -1), 10),
        ("TOPPADDING", (0, 0), (-1, -1), 7),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 7),
    ]))
    return t


def TABLE(header, rows, col_widths=None, mono_cols=()):
    data = [[Paragraph(h, styles["th"]) for h in header]]
    for r in rows:
        cells = []
        for ci, c in enumerate(r):
            st = styles["tdmono"] if ci in mono_cols else styles["td"]
            cells.append(Paragraph(c, st))
        data.append(cells)
    if col_widths is None:
        col_widths = [CONTENT_W / len(header)] * len(header)
    t = Table(data, colWidths=col_widths, repeatRows=1)
    ts = [
        ("BACKGROUND", (0, 0), (-1, 0), SLATE),
        ("LEFTPADDING", (0, 0), (-1, -1), 7),
        ("RIGHTPADDING", (0, 0), (-1, -1), 7),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("LINEBELOW", (0, 0), (-1, -1), 0.4, colors.HexColor("#cbd5e1")),
        ("BOX", (0, 0), (-1, -1), 0.4, colors.HexColor("#cbd5e1")),
    ]
    for ri in range(1, len(data)):
        if ri % 2 == 0:
            ts.append(("BACKGROUND", (0, ri), (-1, ri), colors.HexColor("#f8fafc")))
    t.setStyle(TableStyle(ts))
    return t


def draw_emblem(c, cx, cy, scale=1.0):
    """Simple radar emblem in brand colors."""
    c.saveState()
    rings = [(78, 40, 300), (60, 200, 250), (44, 120, 270)]
    c.setLineCap(1)
    for r, start, extent in rings:
        r *= scale
        c.setStrokeColor(BLUE if r > 55 * scale else CYAN)
        c.setLineWidth(4 * scale)
        c.arc(cx - r, cy - r, cx + r, cy + r, start, extent)
    # sweep needle
    c.setStrokeColor(colors.white)
    c.setLineWidth(5 * scale)
    c.line(cx, cy, cx + 70 * scale, cy + 60 * scale)
    # core
    c.setFillColor(colors.HexColor("#dbeafe"))
    c.circle(cx, cy, 20 * scale, fill=1, stroke=0)
    c.setFillColor(SLATE)
    c.setFont("Helvetica-Bold", 22 * scale)
    c.drawCentredString(cx, cy - 8 * scale, "S")
    c.restoreState()


def make_cover(title_lines, subtitle):
    def _cover(c, doc):
        c.saveState()
        c.setFillColor(SPACE)
        c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)
        # subtle panel
        c.setFillColor(SLATE)
        c.rect(0, 0, PAGE_W, 150 * mm, fill=1, stroke=0)
        c.setFillColor(SPACE)
        c.rect(0, 0, PAGE_W, 95 * mm, fill=1, stroke=0)
        draw_emblem(c, PAGE_W / 2, PAGE_H - 78 * mm, scale=1.15)
        # wordmark
        c.setFont("Helvetica-Bold", 30)
        c.setFillColor(colors.white)
        c.drawCentredString(PAGE_W / 2, PAGE_H - 118 * mm, "SYNAPSE")
        c.setFillColor(CYAN)
        c.drawCentredString(PAGE_W / 2, PAGE_H - 130 * mm, "SONAR")
        # title
        c.setFillColor(colors.white)
        c.setFont("Helvetica-Bold", 22)
        y = PAGE_H - 168 * mm
        for ln in title_lines:
            c.drawCentredString(PAGE_W / 2, y, ln)
            y -= 11 * mm
        c.setFont("Helvetica", 12)
        c.setFillColor(colors.HexColor("#94a3b8"))
        c.drawCentredString(PAGE_W / 2, y - 2 * mm, subtitle)
        # footer meta
        c.setFont("Helvetica", 10)
        c.setFillColor(colors.HexColor("#64748b"))
        c.drawCentredString(PAGE_W / 2, 22 * mm, f"Version {VERSION}    ·    {DATE}")
        c.drawCentredString(PAGE_W / 2, 16 * mm, "Synapse IronNode product family")
        c.restoreState()
    return _cover


def make_chrome(guide_name):
    def _chrome(c, doc):
        c.saveState()
        # header rule + small mark
        c.setStrokeColor(colors.HexColor("#e2e8f0"))
        c.setLineWidth(0.6)
        c.line(LMARGIN, PAGE_H - 14 * mm, PAGE_W - RMARGIN, PAGE_H - 14 * mm)
        c.setFont("Helvetica-Bold", 8)
        c.setFillColor(SLATE)
        c.drawString(LMARGIN, PAGE_H - 12.5 * mm, "SYNAPSE")
        c.setFillColor(CYAN)
        c.drawString(LMARGIN + 38, PAGE_H - 12.5 * mm, "SONAR")
        c.setFont("Helvetica", 8)
        c.setFillColor(MUTED)
        c.drawRightString(PAGE_W - RMARGIN, PAGE_H - 12.5 * mm, guide_name)
        # footer
        c.setStrokeColor(colors.HexColor("#e2e8f0"))
        c.line(LMARGIN, 13 * mm, PAGE_W - RMARGIN, 13 * mm)
        c.setFont("Helvetica", 8)
        c.setFillColor(MUTED)
        c.drawString(LMARGIN, 9 * mm, f"Synapse Sonar · {guide_name}")
        c.drawRightString(PAGE_W - RMARGIN, 9 * mm, f"Page {doc.page}")
        c.restoreState()
    return _chrome


def build(filename, guide_name, title_lines, subtitle, story):
    doc = BaseDocTemplate(
        os.path.join(OUT_DIR, filename), pagesize=A4,
        leftMargin=LMARGIN, rightMargin=RMARGIN, topMargin=TMARGIN, bottomMargin=BMARGIN,
        title=guide_name, author="Synapse Sonar",
    )
    frame = Frame(LMARGIN, BMARGIN, CONTENT_W, PAGE_H - TMARGIN - BMARGIN, id="main")
    cover_tpl = PageTemplate(id="cover", frames=[frame], onPage=make_cover(title_lines, subtitle))
    body_tpl = PageTemplate(id="body", frames=[frame], onPage=make_chrome(guide_name))
    doc.addPageTemplates([cover_tpl, body_tpl])
    from reportlab.platypus import NextPageTemplate
    full = [NextPageTemplate("body"), PageBreak()] + story
    doc.build(full)
    print("wrote", os.path.join(OUT_DIR, filename))


# =====================================================================
# GUIDE 1 — USER & ADMINISTRATOR GUIDE
# =====================================================================
def admin_guide():
    s = []
    s += [H1("1. Introduction")]
    s += [P("Synapse Sonar is a self-hosted, agentless <b>Dynamic Internal Attack Surface &amp; "
            "Dependency Mapper</b>. It builds a live map of your internal network from observed "
            "traffic flows, overlays vulnerability data to highlight real-world risk, and enforces "
            "Zero-Trust segmentation by detecting architectural drift.")]
    s += [P("This guide covers day-to-day use and administration of the web application. For "
            "deploying the data collectors, see the companion <b>Agent Setup &amp; Configuration "
            "Guide</b>.")]
    s += [H3("Key capabilities")]
    s += [UL([
        "Interactive force-directed topology map with hover detail and a deep-dive sidebar.",
        "Vulnerability overlay (CVE badges, CVSS) driven by the NetscanXi feed.",
        "Blast-radius simulation: highlight every asset reachable within two hops of a compromised node.",
        "Zero-Trust drift &amp; rogue/shadow-IT detection on ingested flows.",
        "Multi-tenant isolation, role-based access control, optional TOTP MFA.",
    ])]

    s += [H1("2. Architecture at a glance")]
    s += [P("Synapse Sonar runs as two containers orchestrated by Docker Compose:")]
    s += [UL([
        "<b>Application</b> &mdash; the Next.js web app and API (default port 3000).",
        "<b>Database</b> &mdash; PostgreSQL, storing all tenant data (JSONB for dynamic asset metadata).",
    ])]
    s += [P("Network visibility is provided by <b>collectors</b> you deploy separately (host "
            "agents or a passive sensor) that push observed flows to the application's ingestion "
            "API. The application never scans the network itself.")]
    s += [NOTE("All data is strictly scoped to a tenant. Every query is filtered by the signed-in "
               "user's tenant; there is no cross-tenant read path.", accent=CYAN, label="Isolation")]

    s += [H1("3. First-run setup")]
    s += [P("On a fresh installation the database has no users, so any visit redirects to the "
            "<b>setup</b> screen. Create the first administrator with a username and password "
            "(an optional display name). A default organization is created automatically &mdash; "
            "you can rename it later under User Administration.")]
    s += [CODE("docker compose up -d --build      # start the stack (auto-applies migrations)\n"
               "# then open http://<host>:3000  ->  redirected to /setup")]
    s += [NOTE("Setup is one-shot: once the first account exists, the setup endpoint refuses "
               "further use. There is no built-in default/backdoor account.", accent=VIOLET,
               label="Security")]

    s += [H1("4. Signing in")]
    s += [P("Log in with your <b>username and password</b>. There is no organization field &mdash; "
            "your tenant is derived from your account. If multi-factor authentication is enabled on "
            "your account, you are prompted for a 6-digit code; accounts without MFA are never asked "
            "for one.")]

    s += [H1("5. Roles &amp; access control")]
    s += [P("Synapse Sonar has three roles. Permissions are enforced on every API route.")]
    s += [TABLE(
        ["Capability", "Read-Only Viewer", "Security Analyst", "Tenant Admin"],
        [
            ["View topology &amp; assets", "Yes", "Yes", "Yes"],
            ["Run blast-radius simulation", "&mdash;", "Yes", "Yes"],
            ["Edit assets / segmentation rules", "&mdash;", "Yes", "Yes"],
            ["View integrations", "Yes", "Yes", "Yes"],
            ["Configure integrations &amp; keys", "&mdash;", "&mdash;", "Yes"],
            ["Manage users &amp; org settings", "&mdash;", "&mdash;", "Yes"],
        ],
        col_widths=[CONTENT_W * 0.40, CONTENT_W * 0.20, CONTENT_W * 0.20, CONTENT_W * 0.20],
    )]

    s += [H1("6. The topology map")]
    s += [P("The map is the home screen. Nodes are assets; edges are observed connections with "
            "directional flow animation whose thickness scales with traffic volume.")]
    s += [H3("Interactions")]
    s += [UL([
        "<b>Pan / zoom / drag</b> &mdash; click-drag the canvas to pan, scroll to zoom, drag a node to reposition.",
        "<b>Hover</b> &mdash; a lightweight tooltip shows hostname, internal IP, criticality tier and a "
        "risk badge (e.g. ⚠ 3 Critical CVEs). It disappears the moment you move away.",
        "<b>Click</b> &mdash; opens the deep-dive sidebar with full metadata, all open ports, and the "
        "vulnerability list (when NetscanXi is enabled).",
    ])]
    s += [H3("Blast-radius simulation")]
    s += [P("In the deep-dive sidebar, <b>Simulate Blast Radius</b> treats the selected node as "
            "compromised and highlights every downstream asset reachable within two hops in neon "
            "violet, so you can see the lateral-movement path. Requires the Security Analyst role "
            "or higher.")]
    s += [H3("Map legend")]
    s += [UL([
        "<b>Cyan</b> edges &mdash; data flow.",
        "<b>Red</b> ring &mdash; node has critical CVEs.",
        "<b>Rose</b> &mdash; rogue / shadow-IT asset (not in known inventory).",
        "<b>Violet</b> &mdash; blast-radius path.",
    ])]

    s += [H1("7. Integrations")]
    s += [P("Open <b>Integrations</b> (Tenant Admin). Each integration has a master on/off toggle "
            "that takes effect immediately.")]
    s += [H3("NetscanXi &mdash; vulnerability feed")]
    s += [P("When enabled, the card shows the <b>Endpoint URL</b> and an <b>API key (Bearer token)</b> "
            "to configure in your NetscanXi scanner so it pushes scan results to Synapse Sonar. "
            "While enabled, vulnerability indicators appear on the map and in the sidebar; when "
            "disabled, the feed is rejected and indicators are hidden.")]
    s += [H3("Synapse IronNode &mdash; SOAR alerting")]
    s += [P("When enabled, reveals a <b>Webhook Receiver URL</b> and a <b>Secret Signing Key</b>. "
            "Segmentation violations and rogue-asset detections are dispatched to that webhook as "
            "signed JSON (HMAC-SHA256). When disabled, the alerting pipeline pauses.")]
    s += [NOTE("Integration secrets are encrypted at rest with AES-256-GCM. The UI only ever "
               "displays masked values; ingest keys are stored only as a SHA-256 hash and the "
               "plaintext is shown exactly once at generation.", accent=CYAN, label="Security")]

    s += [H1("8. User administration")]
    s += [P("Tenant Admins manage members under <b>User Administration</b>:")]
    s += [UL([
        "<b>Organization name</b> &mdash; edit the display name shown across the app and on invitations.",
        "<b>Add user</b> &mdash; enter a username and role; an invite link is generated for them to "
        "set their own password (no email service is required in the MVP &mdash; copy the link).",
        "<b>Roles &amp; status</b> &mdash; change a member's role inline, or disable/enable an account.",
        "<b>Require MFA for all members</b> &mdash; an org-wide policy (see next section).",
    ])]

    s += [H1("9. Multi-factor authentication (MFA)")]
    s += [P("MFA is optional and TOTP-based (any authenticator app).")]
    s += [UL([
        "<b>Self-enrolment</b> &mdash; each user enables MFA on <b>Profile &amp; Security</b>: scan the "
        "QR code, confirm a 6-digit code. From then on, sign-in requires the code.",
        "<b>Org-wide enforcement</b> &mdash; a Tenant Admin can turn on <b>Require MFA for all "
        "members</b>. Any member without MFA is then sent to a mandatory enrolment screen before "
        "they can use the app.",
    ])]
    s += [NOTE("Enabling the org-wide policy also applies to the admin who set it &mdash; you cannot "
               "require MFA of others while exempting yourself.", accent=VIOLET, label="Note")]

    s += [H1("10. Security &amp; data handling")]
    s += [UL([
        "Passwords are hashed with bcrypt; TOTP secrets and integration secrets are encrypted (AES-256-GCM).",
        "Collector / ingest keys are stored as SHA-256 hashes and matched by hash.",
        "Tenant isolation is enforced on every query by the authenticated tenant id.",
        "IronNode webhook payloads are signed with HMAC-SHA256 (header X-Sonar-Signature).",
        "Set strong NEXTAUTH_SECRET and INTEGRATION_ENCRYPTION_KEY values in the environment.",
    ])]

    s += [H1("11. Troubleshooting")]
    s += [TABLE(
        ["Symptom", "Likely cause &amp; fix"],
        [
            ["Redirected to /setup", "No users exist yet &mdash; create the first admin."],
            ["“Invalid username or password”", "Check the username (not email). If upgraded from an "
             "older build, your username may be your former email address."],
            ["Asked for an MFA code unexpectedly", "MFA is enabled on that account, or the org-wide policy is on."],
            ["No vulnerabilities on the map", "Enable the NetscanXi integration; data is hidden while it is off."],
            ["No nodes appear", "No collector is sending flows yet &mdash; deploy an agent or sensor."],
        ],
        col_widths=[CONTENT_W * 0.38, CONTENT_W * 0.62],
    )]

    s += [H1("12. API reference (summary)")]
    s += [TABLE(
        ["Endpoint", "Purpose"],
        [
            ["POST /api/ingest/flow-logs", "Ingest observed flows (assets + connections)."],
            ["POST /api/ingest/vulnerabilities", "Ingest NetscanXi findings (CVEs)."],
            ["GET /api/graph", "Tenant topology for the map."],
            ["GET /api/assets/:id/blast-radius", "Downstream reachable assets (2 hops)."],
            ["GET/PATCH /api/integrations", "Read / configure integrations."],
            ["GET/POST/PATCH /api/users", "List, add, update users."],
        ],
        col_widths=[CONTENT_W * 0.46, CONTENT_W * 0.54], mono_cols=(0,),
    )]
    s += [Spacer(1, 8)]
    s += [P("<i>Ingestion endpoints authenticate with a Bearer ingest key; all others require an "
            "authenticated session.</i>")]

    build("Synapse-Sonar-User-Admin-Guide.pdf", "User & Administrator Guide",
          ["User &amp; Administrator", "Guide"],
          "Operating and administering Synapse Sonar", s)


# =====================================================================
# GUIDE 2 — AGENT SETUP & CONFIGURATION GUIDE
# =====================================================================
def agent_guide():
    s = []
    s += [H1("1. Overview")]
    s += [P("Synapse Sonar is agentless at its core: it <b>receives</b> network flow data pushed to "
            "it by collectors you deploy. This guide covers the three collectors and the NetscanXi "
            "vulnerability connector.")]
    s += [TABLE(
        ["Collector", "Runs on", "Sees", "Use when"],
        [
            ["Linux host agent", "Each Debian/Ubuntu host", "That host's own connections",
             "You can install software on the host"],
            ["Windows host agent", "Each Windows host", "That host's own TCP connections",
             "You can install software on the host"],
            ["Passive sensor", "A host on a SPAN/mirror port", "All mirrored traffic",
             "The device cannot take an agent"],
        ],
        col_widths=[CONTENT_W * 0.22, CONTENT_W * 0.24, CONTENT_W * 0.27, CONTENT_W * 0.27],
    )]
    s += [P("The Linux agent and sensor are pure Python 3 standard library; the Windows agent uses "
            "built-in PowerShell. No third-party packages are required on the endpoints.")]

    s += [H1("2. Prerequisites")]
    s += [UL([
        "A running Synapse Sonar instance reachable from your hosts (e.g. https://sonar:3000).",
        "The <b>NetscanXi integration enabled</b> in Synapse Sonar &mdash; this provides the ingest key.",
        "Network egress from each host to the Sonar address/port.",
    ])]

    s += [H1("3. Get the ingest key")]
    s += [P("All collectors authenticate with a single <b>ingest key</b>:")]
    s += [UL([
        "Sign in as a Tenant Admin and open <b>Integrations</b>.",
        "Toggle <b>NetscanXi</b> on and click <b>Generate API key</b>.",
        "Copy the key immediately &mdash; it is shown only once. Regenerating revokes the old key.",
    ])]
    s += [NOTE("The same key is used by the host agents, the passive sensor, and the NetscanXi "
               "vulnerability feed.", accent=CYAN, label="Note")]

    s += [H1("4. Download from the Agents tab (recommended)")]
    s += [P("The fastest path is the built-in <b>Agents &amp; Collectors</b> tab (Tenant Admin only):")]
    s += [UL([
        "Pick a platform, confirm the <b>Sonar address</b> and paste/generate the <b>ingest key</b>.",
        "Click <b>Download bundle (.zip)</b>. The zip contains the agent, installer, your "
        "pre-filled config, and a QUICKSTART.",
    ])]
    s += [P("Or download the raw files directly from <font face='Courier'>/agents/</font> on the server.")]

    s += [H1("5. Linux host agent (Debian / Ubuntu)")]
    s += [P("Reports the host's own established connections via <font face='Courier'>ss</font>. Runs "
            "unprivileged as a systemd service.")]
    s += [CODE("unzip synapse-sonar-linux-agent.zip -d sonar-agent\n"
               "cd sonar-agent\n"
               "sudo ./install.sh\n"
               "sudo cp sonar-agent.env /etc/sonar-agent/sonar-agent.env\n"
               "sudo systemctl enable --now sonar-agent\n"
               "journalctl -u sonar-agent -f          # watch it push flows")]
    s += [P("If the installer is not executable after transfer, run "
            "<font face='Courier'>sudo bash install.sh</font> instead.")]
    s += [H3("Configuration (/etc/sonar-agent/sonar-agent.env)")]
    s += [TABLE(
        ["Key", "Meaning", "Default"],
        [
            ["SONAR_URL", "Synapse Sonar base URL", "&mdash;"],
            ["SONAR_INGEST_KEY", "Ingest key (Bearer)", "&mdash;"],
            ["SONAR_INTERVAL", "Seconds between pushes", "30"],
            ["SONAR_VERIFY_TLS", "Verify TLS cert (false for self-signed)", "true"],
        ],
        col_widths=[CONTENT_W * 0.30, CONTENT_W * 0.50, CONTENT_W * 0.20], mono_cols=(0,),
    )]

    s += [H1("6. Windows host agent")]
    s += [P("Reports the host's own TCP connections via <font face='Courier'>Get-NetTCPConnection</font>. "
            "Installs as a SYSTEM scheduled task that starts at boot. From an <b>elevated</b> PowerShell:")]
    s += [CODE("Expand-Archive synapse-sonar-windows-agent.zip -DestinationPath sonar-agent\n"
               "cd sonar-agent\n"
               "powershell -ExecutionPolicy Bypass -File .\\install.ps1\n"
               "copy config.json \"$env:ProgramData\\SonarAgent\\config.json\"\n"
               "Restart-ScheduledTask -TaskName SynapseSonarAgent")]
    s += [H3("Configuration (%ProgramData%\\SonarAgent\\config.json)")]
    s += [TABLE(
        ["Key", "Meaning", "Default"],
        [
            ["SonarUrl", "Synapse Sonar base URL", "&mdash;"],
            ["IngestKey", "Ingest key (Bearer)", "&mdash;"],
            ["IntervalSeconds", "Seconds between pushes", "30"],
            ["VerifyTls", "Verify TLS cert", "true"],
        ],
        col_widths=[CONTENT_W * 0.30, CONTENT_W * 0.50, CONTENT_W * 0.20], mono_cols=(0,),
    )]
    s += [P("Logs: <font face='Courier'>%ProgramData%\\SonarAgent\\sonar-agent.log</font>. "
            "Remove with <font face='Courier'>Unregister-ScheduledTask -TaskName SynapseSonarAgent -Confirm:$false</font>.")]

    s += [H1("7. Passive sensor (agentless devices)")]
    s += [P("For devices that cannot run an agent (appliances, IoT, printers, OT). Deploy on a Linux "
            "host attached to a switch <b>SPAN / mirror port</b> (or inline tap / gateway) so it can "
            "observe traffic to and from those devices. It sniffs IPv4 TCP/UDP, aggregates flows "
            "with byte counts, and excludes its own traffic to Sonar.")]
    s += [CODE("unzip synapse-sonar-sensor-agent.zip -d sonar-sensor\n"
               "cd sonar-sensor\n"
               "sudo ./install.sh\n"
               "sudo cp sonar-sensor.env /etc/sonar-sensor/sonar-sensor.env\n"
               "sudo systemctl enable --now sonar-sensor\n"
               "journalctl -u sonar-sensor -f")]
    s += [P("Docker alternative (host networking is required to see the mirrored interface):")]
    s += [CODE("docker run -d --name sonar-sensor --network host \\\n"
               "  --cap-add NET_RAW --cap-add NET_ADMIN \\\n"
               "  -e SONAR_URL=https://sonar:3000 -e SONAR_INGEST_KEY=nsx_sensor_xxxx \\\n"
               "  -e SONAR_IFACE=eth1 \\\n"
               "  -v \"$PWD/sonar-sensor.py:/app/sonar-sensor.py:ro\" \\\n"
               "  python:3.12-alpine python /app/sonar-sensor.py")]
    s += [H3("Configuration (/etc/sonar-sensor/sonar-sensor.env)")]
    s += [TABLE(
        ["Key", "Meaning", "Default"],
        [
            ["SONAR_URL", "Synapse Sonar base URL", "&mdash;"],
            ["SONAR_INGEST_KEY", "Ingest key (Bearer)", "&mdash;"],
            ["SONAR_IFACE", "Interface on the mirror port", "(all)"],
            ["SONAR_FLUSH", "Aggregation window (seconds)", "30"],
            ["SONAR_VERIFY_TLS", "Verify TLS cert", "true"],
        ],
        col_widths=[CONTENT_W * 0.30, CONTENT_W * 0.50, CONTENT_W * 0.20], mono_cols=(0,),
    )]
    s += [NOTE("The sensor only sees what the mirror port forwards. Size the SPAN session and the "
               "sensor NIC for the mirrored volume, or flows will be dropped upstream.",
               accent=VIOLET, label="Sizing")]

    s += [H1("8. NetscanXi vulnerability feed")]
    s += [P("NetscanXi pushes scan results to Synapse Sonar (push model). In the NetscanXi card, copy "
            "the <b>Endpoint URL</b> and <b>API key</b>, then configure your scanner to POST findings "
            "on each scan. Expected payload:")]
    s += [CODE('POST /api/ingest/vulnerabilities\n'
               'Authorization: Bearer <ingest-key>\n\n'
               '{ "findings": [\n'
               '    { "ip": "10.0.3.30", "cveId": "CVE-2024-1234",\n'
               '      "cvssScore": 9.8, "severity": "CRITICAL",\n'
               '      "title": "PostgreSQL RCE" } ] }')]
    s += [P("If the scanner cannot post in this format, run the connector script "
            "(<font face='Courier'>netscan-connector</font>) on a schedule to translate its export "
            "and forward it. Findings are matched to assets by IP and upserted by CVE.")]

    s += [H1("9. Verifying data flow")]
    s += [UL([
        "Agent/sensor: <font face='Courier'>systemctl status</font> should show <b>active (running)</b>, "
        "and the logs should report <font face='Courier'>pushed N flows</font>.",
        "In Synapse Sonar, hosts appear as nodes on the <b>Topology Map</b> within a minute or two.",
        "Vulnerabilities appear once the NetscanXi feed sends data (and the toggle is on).",
    ])]

    s += [H1("10. Troubleshooting")]
    s += [TABLE(
        ["Symptom", "Likely cause &amp; fix"],
        [
            ["HTTP 401 from ingest", "Wrong/expired ingest key, or NetscanXi integration disabled."],
            ["Service won't start (Linux)", "Check SONAR_URL/SONAR_INGEST_KEY are set; review journalctl."],
            ["TLS errors", "Self-signed cert &mdash; set verify-TLS to false, or install a trusted cert."],
            ["No flows from sensor", "Confirm the mirror port forwards traffic and SONAR_IFACE is correct."],
            ["Nodes but no vulns", "Enable NetscanXi and confirm findings include the host IP."],
        ],
        col_widths=[CONTENT_W * 0.34, CONTENT_W * 0.66],
    )]

    build("Synapse-Sonar-Agent-Setup-Guide.pdf", "Agent Setup & Configuration Guide",
          ["Agent Setup &amp;", "Configuration Guide"],
          "Deploying collectors that feed Synapse Sonar", s)


if __name__ == "__main__":
    admin_guide()
    agent_guide()
    print("done")