Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(replay): public redacted investigation-replay permalinks (v8 W3)
Beenu Arora7678d8301a20
diff --git a/.github/workflows/aisoc-cli.yml b/.github/workflows/aisoc-cli.ymlindex a0449c5e1..5241dbe69 100644--- a/.github/workflows/aisoc-cli.yml+++ b/.github/workflows/aisoc-cli.yml@@ -39,6 +39,10 @@ jobs:cache: pnpmcache-dependency-path: pnpm-lock.yaml- run: pnpm install --frozen-lockfile+ # The CLI bundles @aisoc/report-card at build time and imports it in tests,+ # so the shared package must be built first.+ - run: pnpm --filter @aisoc/report-card build+ - run: pnpm --filter @aisoc/report-card test- name: Fixture is up to date (regenerate and diff)run: |node packages/aisoc-lite/scripts/gen-fixtures.mjs@@ -66,6 +70,7 @@ jobs:cache: pnpmcache-dependency-path: pnpm-lock.yaml- run: pnpm install --frozen-lockfile+ - run: pnpm --filter @aisoc/report-card build- run: pnpm --filter aisoc build- name: triage --demo finishes fast with the documented headlinerun: |diff --git a/.github/workflows/publish-cli.yml b/.github/workflows/publish-cli.ymlindex 2dcfdd655..a561360dd 100644--- a/.github/workflows/publish-cli.yml+++ b/.github/workflows/publish-cli.yml@@ -57,6 +57,7 @@ jobs:- name: Build + testrun: |+ pnpm --filter @aisoc/report-card buildpnpm --filter aisoc testpnpm --filter aisoc builddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex bbe3030e0..be26af0fb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **v8 W3 — shareable investigation artifacts (the screenshot loop).** Public,+ immutable, redacted investigation-replay permalinks. New+ `services/api/app/api/v1/endpoints/replay.py`: `POST /ledger/{run_id}/publish/preview`+ builds a redacted snapshot **and returns the alias map** so the publisher+ reviews exactly what will be hidden (the pre-publish diff) before confirming;+ `POST /ledger/{run_id}/publish` (needs `confirm=true`) re-builds server-side+ and stores an immutable `published_replays` row (migration `045`, with an+ UPDATE-blocking trigger that only allows the view counter to change); public+ `GET /r/{slug}` serves the snapshot without auth from a non-RLS session+ (the data is post-redaction and non-identifying by design). Redaction reuses+ the reversible `Pseudonymizer` (vendored into the API via+ `scripts/sync_vendored_redactor.py`): internal IPs / emails / paths / secrets+ / internal hostnames / usernames become aliases, while public IOCs + ATT&CK+ techniques are preserved as the shareable value; only the redacted snapshot is+ persisted, never the alias map (`services/api/app/services/replay_redaction.py`).+ Web: a public `/r/[slug]` page renders an animated playback (timeline scrubber,+ evidence cards, growing attack graph, verdict stamp with elapsed time) with a+ dynamic `next/og` Open Graph image for X/LinkedIn/Slack unfurls;+ shields.io-compatible badge endpoints at `/api/badge/<kind>`. New shared+ `packages/@aisoc/report-card` renders triage / coverage-grade / replay share+ cards (SVG + Markdown) and is now the canonical renderer behind the CLI+ `--share` flag (bundled into `aisoc` at build time). The seeded LockBit case+ `INC-RT-001` is published as the canonical demo replay at `/r/demo-lockbit`.+ Tests: redaction (no raw PII survives, public IOCs preserved), report-card+ renderers, badge endpoint, and the replay fetch client. `docs/openapi.yaml`+ regenerated (+284 lines, additions only).- **v8 W1 — `npx aisoc` wedge CLI (the 60-second wow).** New `packages/aisoc-lite/` (TypeScript, published to npm as `aisoc`, one runtime dependency): a zero-install front door that triages a batch of alerts to verdicts in under a minute with **no credentials and no LLM key**. `npx aisoc triage --demo` runs a bundled, fully-deterministic 200-alert fixture in ~50 ms and prints a terminal verdict table plus the copy-pasteable headline "AiSOC triaged 200 alerts: 12 TP, 171 FP suppressed (85.5% noise), 17 need review". The verdict engine (`src/verdict/stages.ts`) is a faithful port of the production triage scorer `services/agents/app/confidence/scoring.py` — the weight stack and band thresholds (≥.80 TP, ≥.60 likely-TP, ≥.40 review, else benign; clamp [0.05, 0.95]) are pinned by a parity test so a CLI verdict lands where the full stack would. `--file alerts.jsonl` triages a local export (Splunk / Sentinel / Elastic ECS / CrowdStrike field spellings auto-detected); `--llm` refines only the ambiguous `needs_review` middle using the user's **own** `ANTHROPIC_API_KEY`/`OPENAI_API_KEY` called directly (never proxied); `--share` writes a redacted, aggregate-only report card (Markdown + 1200×630 SVG, no alert content); `translate` is a CLI front for the deterministic detection-rule field-map translator (Sigma/SPL/KQL/ES\|QL/YARA-L2/UDM); `up` boots the full demo stack from a pinned Compose bundle. Telemetry is strictly opt-in (`--telemetry` / `AISOC_TELEMETRY=1`, default off), aggregate counts only, documented in `packages/aisoc-lite/TELEMETRY.md` and asserted content-free by a unit test. 22 vitest tests. New CI: `aisoc-cli.yml` (build + typecheck + tests + a cross-platform cold `triage --demo` e2e asserting the headline and a <60 s bound + a fixture-staleness diff gate) and `publish-cli.yml` (npm publish with build provenance on a `cli-v*` tag; no-ops safely until `NPM_TOKEN` is configured — we never fake a publish). README top fold rewritten around the one-liner (guarded "lands on npm with the v8.0 launch; today it builds from `packages/aisoc-lite/`").## [7.6.0] — 2026-07-13diff --git a/README.md b/README.mdindex 4473babb5..ea9d23d42 100644--- a/README.md+++ b/README.md@@ -178,7 +178,7 @@ A handful of headline capabilities — the rest are catalogued in [`apps/docs/do- **End-to-end SIEM spine** — a cold `docker compose up` ingests connector data → lands it in the ClickHouse event lake → the executable detection corpus (947 rules) fires on the live stream → a fused alert is created, all asserted by an extended integration gate. [`apps/docs/docs/architecture.md`](apps/docs/docs/architecture.md).- **Autonomous triage + governed response** — every fused alert is auto-triaged by the agent (copilot/read-only by default); approved actions execute against real connector credentials through a per-action, blast-radius-scoped autonomy policy with real rollback + post-action verification. [`apps/docs/docs/concepts/automation-maturity.md`](apps/docs/docs/concepts/automation-maturity.md).- **Advanced Data Explorer** — one investigation surface (NL + SQL over the lake, plus pivots to identity/graph/intel), replacing the SIEM context-switch. `/explore`.-- **Investigation Rail + replayable Investigation Ledger** — every prompt, tool call, evidence chip, and rationale stored against a case, replayable in the UI. [`apps/docs/docs/console/investigation-rail.md`](apps/docs/docs/console/investigation-rail.md).+- **Investigation Rail + replayable Investigation Ledger** — every prompt, tool call, evidence chip, and rationale stored against a case, replayable in the UI and shareable as a redacted public permalink ([live demo replay](https://tryaisoc.com/r/demo-lockbit)). [`apps/docs/docs/console/investigation-rail.md`](apps/docs/docs/console/investigation-rail.md).- **Detection-as-Code lifecycle** — propose → review → eval-gate → promote; CI rejects any candidate that fails its own positive/negative fixtures (the non-circular gate) or regresses MITRE accuracy. [`apps/docs/docs/concepts/detections.md`](apps/docs/docs/concepts/detections.md) — and the 869 native rules live in [`detections/`](detections/).- **Three-model AI** — Semantic (graph-at-ingest), Behavioral (UEBA fused into alert scoring), and Knowledge (LLM), with fuse-time attack-chain grouping so related alerts auto-collapse into one ordered incident.- **Hunt-as-Code** — YAML hypotheses with MITRE tags, cron schedules, and natural-language `/hunt` workbench. [`hunts/`](hunts/) + [`apps/docs/docs/console/rule-tuning.md`](apps/docs/docs/console/rule-tuning.md).diff --git a/apps/docs/docs/console/public-replay.md b/apps/docs/docs/console/public-replay.mdnew file mode 100644index 000000000..ca43ac0cb--- /dev/null+++ b/apps/docs/docs/console/public-replay.md@@ -0,0 +1,81 @@+---+title: Public investigation replays+sidebar_label: Public replays+---++# Public investigation replays++Turn any investigation ledger into an **immutable, redacted, public share link**+at `tryaisoc.com/r/<slug>` so you can show how the agent reasoned through a case —+in a blog post, an incident write-up, or a talk — without exposing your+environment.++The canonical demo replay is the seeded LockBit 3.0 case:+[`tryaisoc.com/r/demo-lockbit`](https://tryaisoc.com/r/demo-lockbit).++## What a viewer sees++A read-only animated playback:++- a **timeline scrubber** over the LangGraph traversal (play / pause / seek),+- **evidence cards** appearing per step,+- the **attack graph** growing as techniques are discovered,+- a **verdict stamp** with the elapsed time, step count, tool-call count, and+ evidence-source count ("Investigated in 94s, 14 tool calls, 3 evidence+ sources").++Links unfurl on X / LinkedIn / Slack via a dynamically-generated Open Graph+image.++## Publishing (with a redaction review)++Publishing is a two-step, opt-in flow — nothing is ever published automatically.++1. **Preview the redaction.**+ `POST /api/v1/ledger/{run_id}/publish/preview` returns the redacted snapshot+ **plus the alias map** (`{ "HOST_1": "WIN-FIN-DB01", ... }`) so you can review+ exactly what will be hidden before anything is stored.+2. **Confirm.**+ `POST /api/v1/ledger/{run_id}/publish` with `{ "confirm": true }` re-builds+ the snapshot server-side (the client preview is never trusted), stores an+ **immutable** row, and returns the public slug + URL.++Unpublish at any time with `DELETE /api/v1/ledger/publish/{slug}`.++## What is redacted++Redaction reuses the same reversible pseudonymizer the LLM egress path uses+(`services/agents/app/privacy/redactor.py`, vendored into the API):++| Redacted → alias | Preserved |+|---|---|+| Internal IPs, emails, file paths, secrets, internal hostnames, usernames | Public IOCs (external domains / IPs), MITRE technique IDs |++Public IOCs and ATT&CK techniques are intentionally preserved — they are the+shareable threat-intelligence value of a replay, not customer PII. Only the+redacted snapshot is persisted; the alias map is returned in the preview and is+**never stored**.++## Guarantees++- **Immutable.** A published snapshot never changes (a DB trigger blocks+ UPDATEs to every field except the view counter). Re-publishing mints a new+ slug.+- **Public-by-design.** The `/r/<slug>` read is unauthenticated and served from+ a non-RLS session because the stored data is post-redaction and+ non-identifying. Writes remain tenant-scoped.+- **CDN-cacheable.** The replay page and OG image are static-friendly and do not+ depend on the demo box being up.++## Badges++shields.io-compatible endpoint badges live at `tryaisoc.com/api/badge/<kind>`+(`triaged`, `noise-suppressed`, `benchmark`, `verified-detection`, `self-play`).+Embed one in a README:++```markdown++```++Callers can override the message/label/color via query params (e.g. the GitHub+Action passes its per-run triaged count).diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex 12c89363e..de79b2108 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -46,6 +46,7 @@ const sidebars: SidebarsConfig = {"console/queue","console/rule-tuning","console/investigation-rail",+ "console/public-replay",],},{diff --git a/apps/web/next.config.js b/apps/web/next.config.jsindex f31fb0e92..ebb340eb0 100644--- a/apps/web/next.config.js+++ b/apps/web/next.config.js@@ -29,7 +29,7 @@ const OSQUERY_TLS_HOST = process.env.OSQUERY_TLS_URL || 'http://localhost:8090';const nextConfig = {reactStrictMode: true,- transpilePackages: ['@aisoc/ui', '@aisoc/types'],+ transpilePackages: ['@aisoc/ui', '@aisoc/types', '@aisoc/report-card'],// pnpm monorepo: anchor Turbopack at the repository root so it can resolve// the hoisted `next` package via apps/web/node_modules/next (symlink into// the root .pnpm store). Setting this to __dirname caused Turbopack todiff --git a/apps/web/package.json b/apps/web/package.jsonindex d6b53677c..136054d2d 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -22,6 +22,7 @@"e2e": "PLAYWRIGHT_PROJECT=journey playwright test --project=journey"},"dependencies": {+ "@aisoc/report-card": "workspace:*","@aisoc/types": "workspace:*","@aisoc/ui": "workspace:*","@monaco-editor/react": "^4.6.0",diff --git a/apps/web/src/app/api/badge/[kind]/route.test.ts b/apps/web/src/app/api/badge/[kind]/route.test.tsnew file mode 100644index 000000000..0bc7c6667--- /dev/null+++ b/apps/web/src/app/api/badge/[kind]/route.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest";++import { GET } from "./route";++function req(url: string): Request {+ return new Request(url);+}++async function call(kind: string, url: string) {+ const res = await GET(req(url), { params: Promise.resolve({ kind }) });+ return { status: res.status, body: await res.json() };+}++describe("shields.io badge endpoint", () => {+ it("returns the shields endpoint schema for a known kind", async () => {+ const { status, body } = await call("triaged", "https://tryaisoc.com/api/badge/triaged");+ expect(status).toBe(200);+ expect(body.schemaVersion).toBe(1);+ expect(body.label).toBe("AiSOC");+ expect(body.color).toBe("7b2bbe");+ });++ it("allows message/label/color overrides", async () => {+ const { body } = await call(+ "triaged",+ "https://tryaisoc.com/api/badge/triaged?message=41%20triaged&label=repo&color=22c55e",+ );+ expect(body.message).toBe("41 triaged");+ expect(body.label).toBe("repo");+ expect(body.color).toBe("22c55e");+ });++ it("rejects an unsafe color override, falling back to the default", async () => {+ const { body } = await call("triaged", "https://tryaisoc.com/api/badge/triaged?color=red%3Bevil");+ expect(body.color).toBe("7b2bbe");+ });++ it("404s an unknown badge kind", async () => {+ const { status, body } = await call("nope", "https://tryaisoc.com/api/badge/nope");+ expect(status).toBe(404);+ expect(body.isError).toBe(true);+ });+});diff --git a/apps/web/src/app/api/badge/[kind]/route.ts b/apps/web/src/app/api/badge/[kind]/route.tsnew file mode 100644index 000000000..5f60c0c4c--- /dev/null+++ b/apps/web/src/app/api/badge/[kind]/route.ts@@ -0,0 +1,62 @@+import { NextResponse } from "next/server";++/**+ * shields.io-compatible endpoint badges (v8 W3.4).+ *+ * Embed anywhere shields renders, e.g. in a README:+ * + *+ * Badges are backlinks that live in other people's READMEs. The GitHub Action+ * (W4) links its "triaged" badge here with a per-run `?message=` override; the+ * eval leaderboard links the "benchmark" badge; marketplace rules that pass the+ * eval gate carry the "verified-detection" badge.+ *+ * Response follows the shields "endpoint" schema:+ * { schemaVersion: 1, label, message, color }+ * `label`, `message`, and `color` are overridable via query params so callers+ * can reflect their own numbers (kept honest by the caller, not fabricated here).+ */++interface BadgeSpec {+ label: string;+ message: string;+ color: string;+}++const DEFAULTS: Record<string, BadgeSpec> = {+ triaged: { label: "AiSOC", message: "alerts triaged", color: "7b2bbe" },+ "noise-suppressed": { label: "AiSOC noise", message: "suppressed", color: "22c55e" },+ benchmark: { label: "AiSOC benchmark", message: "see scoreboard", color: "3b82f6" },+ "verified-detection": { label: "AiSOC", message: "verified detection", color: "22c55e" },+ "self-play": { label: "AiSOC self-play", message: "nightly", color: "ec4899" },+};++const ALLOWED_COLOR = /^[0-9a-zA-Z]+$/;++export async function GET(request: Request, { params }: { params: Promise<{ kind: string }> }) {+ const { kind } = await params;+ const spec = DEFAULTS[kind];+ if (!spec) {+ return NextResponse.json(+ { schemaVersion: 1, label: "AiSOC", message: "unknown badge", color: "inactive", isError: true },+ { status: 404 },+ );+ }++ const url = new URL(request.url);+ const label = (url.searchParams.get("label") || spec.label).slice(0, 64);+ const message = (url.searchParams.get("message") || spec.message).slice(0, 64);+ const colorParam = url.searchParams.get("color");+ const color = colorParam && ALLOWED_COLOR.test(colorParam) ? colorParam : spec.color;++ return NextResponse.json(+ { schemaVersion: 1, label, message, color, namedLogo: "target", labelColor: "0b1020" },+ {+ headers: {+ // Cacheable at the CDN; shields also caches. Short enough that a+ // per-run override reflects quickly.+ "Cache-Control": "public, max-age=300, s-maxage=300",+ },+ },+ );+}diff --git a/apps/web/src/app/r/[slug]/ReplayPlayer.tsx b/apps/web/src/app/r/[slug]/ReplayPlayer.tsxnew file mode 100644index 000000000..e3b5bc846--- /dev/null+++ b/apps/web/src/app/r/[slug]/ReplayPlayer.tsx@@ -0,0 +1,228 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import type { ReplaySnapshot } from "../../../lib/replay";++/**+ * Read-only animated playback of a redacted investigation replay.+ *+ * Timeline scrubber over the ledger traversal: evidence cards appear per step,+ * the attack graph grows, and a verdict stamp lands at the end with the elapsed+ * time. Dependency-free (hand-rolled SVG) so the public page stays lightweight+ * and CDN-cacheable.+ */++const KIND_COLOR: Record<string, string> = {+ recon: "#38bdf8",+ forensic: "#a78bfa",+ tool_call: "#22c55e",+ llm_call: "#f59e0b",+ llm_response: "#f59e0b",+ evidence_cited: "#ec4899",+ responder: "#f87171",+ report: "#e6e9f5",+ reporter: "#e6e9f5",+ decision_reason: "#94a3b8",+};++function verdictTone(verdict: string): { label: string; color: string } {+ const v = verdict.toLowerCase();+ if (/true|confirmed|incident|positive/.test(v)) return { label: verdict.replace(/_/g, " "), color: "#f87171" };+ if (/review|needs/.test(v)) return { label: verdict.replace(/_/g, " "), color: "#fbbf24" };+ return { label: verdict.replace(/_/g, " "), color: "#22c55e" };+}++export function ReplayPlayer({ snapshot }: { snapshot: ReplaySnapshot }) {+ const total = snapshot.steps.length;+ const [cursor, setCursor] = useState(total); // start fully revealed+ const [playing, setPlaying] = useState(false);++ useEffect(() => {+ if (!playing) return;+ if (cursor >= total) {+ setPlaying(false);+ return;+ }+ const t = setTimeout(() => setCursor((c) => Math.min(c + 1, total)), 700);+ return () => clearTimeout(t);+ }, [playing, cursor, total]);++ const visibleSteps = snapshot.steps.slice(0, cursor);+ const revealedTechniques = useMemo(() => {+ // Techniques aren't per-step in the redacted snapshot, so reveal them+ // proportionally to scrubber progress for the "graph growing" effect.+ const shown = Math.ceil((cursor / Math.max(total, 1)) * snapshot.techniques.length);+ return snapshot.techniques.slice(0, shown);+ }, [cursor, total, snapshot.techniques]);++ const tone = verdictTone(snapshot.verdict);+ const elapsedSec = (snapshot.elapsedMs / 1000).toFixed(0);+ const graphVisibleNodes = Math.ceil((cursor / Math.max(total, 1)) * snapshot.attackGraph.nodes.length);++ const play = () => {+ if (cursor >= total) setCursor(0);+ setPlaying(true);+ };++ return (+ <div style={{ display: "grid", gap: 24 }}>+ {/* Controls */}+ <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>+ <button+ onClick={() => (playing ? setPlaying(false) : play())}+ style={{+ background: "#7b2bbe",+ color: "white",+ border: "none",+ borderRadius: 8,+ padding: "8px 18px",+ fontWeight: 700,+ cursor: "pointer",+ }}+ >+ {playing ? "❚❚ Pause" : cursor >= total ? "↻ Replay" : "▶ Play"}+ </button>+ <input+ type="range"+ min={0}+ max={total}+ value={cursor}+ onChange={(e) => {+ setPlaying(false);+ setCursor(Number(e.target.value));+ }}+ style={{ flex: 1, minWidth: 200 }}+ aria-label="Investigation timeline scrubber"+ />+ <span style={{ color: "#8b93b7", fontVariantNumeric: "tabular-nums", minWidth: 90, textAlign: "right" }}>+ step {Math.min(cursor, total)} / {total}+ </span>+ </div>++ <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>+ {/* Timeline */}+ <section style={{ minWidth: 0 }}>+ <h2 style={{ fontSize: 14, textTransform: "uppercase", letterSpacing: 1, color: "#8b93b7", margin: "0 0 12px" }}>+ Ledger traversal+ </h2>+ <ol style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 8 }}>+ {visibleSteps.map((s) => (+ <li+ key={s.seq}+ style={{+ background: "#131a33",+ border: "1px solid #232b4d",+ borderLeft: `3px solid ${KIND_COLOR[s.kind] ?? "#475569"}`,+ borderRadius: 8,+ padding: "10px 12px",+ animation: "aisoc-fade 0.4s ease",+ }}+ >+ <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>+ <strong style={{ color: "#e6e9f5", fontSize: 13 }}>{s.agent}</strong>+ <code style={{ color: KIND_COLOR[s.kind] ?? "#94a3b8", fontSize: 12 }}>{s.kind}</code>+ </div>+ <p style={{ margin: "4px 0 0", color: "#c4cae0", fontSize: 13, lineHeight: 1.4 }}>{s.summary}</p>+ {s.decision?.reason ? (+ <p style={{ margin: "6px 0 0", color: "#8b93b7", fontSize: 12, fontStyle: "italic" }}>+ ↳ {s.decision.reason}+ {typeof s.decision.confidence === "number" ? ` (conf ${(s.decision.confidence * 100).toFixed(0)}%)` : ""}+ </p>+ ) : null}+ </li>+ ))}+ </ol>+ </section>++ {/* Right column: attack graph + evidence + verdict */}+ <section style={{ display: "grid", gap: 20, alignContent: "start" }}>+ <div>+ <h2 style={{ fontSize: 14, textTransform: "uppercase", letterSpacing: 1, color: "#8b93b7", margin: "0 0 12px" }}>+ Attack graph+ </h2>+ <AttackGraph+ nodes={snapshot.attackGraph.nodes.slice(0, graphVisibleNodes)}+ edges={snapshot.attackGraph.edges}+ />+ </div>++ <div>+ <h2 style={{ fontSize: 14, textTransform: "uppercase", letterSpacing: 1, color: "#8b93b7", margin: "0 0 12px" }}>+ Techniques+ </h2>+ <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>+ {revealedTechniques.length === 0 ? (+ <span style={{ color: "#64748b", fontSize: 13 }}>—</span>+ ) : (+ revealedTechniques.map((t) => (+ <span key={t} style={{ background: "#232b4d", color: "#c4cae0", borderRadius: 6, padding: "3px 8px", fontSize: 12 }}>+ {t}+ </span>+ ))+ )}+ </div>+ </div>++ {cursor >= total ? (+ <div+ style={{+ border: `2px solid ${tone.color}`,+ borderRadius: 12,+ padding: "16px 20px",+ animation: "aisoc-stamp 0.5s ease",+ }}+ >+ <div style={{ color: "#8b93b7", fontSize: 12, textTransform: "uppercase", letterSpacing: 1 }}>Verdict</div>+ <div style={{ color: tone.color, fontSize: 28, fontWeight: 800, textTransform: "uppercase" }}>{tone.label}</div>+ <div style={{ color: "#8b93b7", fontSize: 13, marginTop: 6 }}>+ Investigated in {elapsedSec}s · {snapshot.stepCount} steps · {snapshot.toolCallCount} tool calls ·{" "}+ {snapshot.evidenceSourceCount} evidence sources+ </div>+ </div>+ ) : null}+ </section>+ </div>++ <style>{`+ @keyframes aisoc-fade { from { opacity: 0; transform: translateY(6px);} to { opacity: 1; transform: none; } }+ @keyframes aisoc-stamp { from { opacity: 0; transform: scale(0.9);} to { opacity: 1; transform: none; } }+ `}</style>+ </div>+ );+}++function AttackGraph({+ nodes,+ edges,+}: {+ nodes: ReplaySnapshot["attackGraph"]["nodes"];+ edges: ReplaySnapshot["attackGraph"]["edges"];+}) {+ const width = 520;+ const rowH = 54;+ const height = Math.max(120, nodes.length * rowH + 20);+ const pos = new Map(nodes.map((n, i) => [n.id, { x: 90 + (i % 2) * 240, y: 30 + i * rowH }]));++ return (+ <svg width="100%" viewBox={`0 0 ${width} ${height}`} style={{ background: "#0b1020", border: "1px solid #232b4d", borderRadius: 8 }}>+ {edges.map((e, i) => {+ const a = pos.get(e.source);+ const b = pos.get(e.target);+ if (!a || !b) return null;+ return <line key={i} x1={a.x} y1={a.y} x2={b.x} y2={b.y} stroke="#334155" strokeWidth={1.5} />;+ })}+ {nodes.map((n) => {+ const p = pos.get(n.id)!;+ const isAlert = n.kind === "alert";+ return (+ <g key={n.id} style={{ animation: "aisoc-fade 0.4s ease" }}>+ <circle cx={p.x} cy={p.y} r={isAlert ? 16 : 12} fill={isAlert ? "#f87171" : "#7b2bbe"} />+ <text x={p.x + 22} y={p.y + 4} fill="#c4cae0" fontSize={13} fontFamily="ui-sans-serif,system-ui">+ {n.label}+ </text>+ </g>+ );+ })}+ </svg>+ );+}diff --git a/apps/web/src/app/r/[slug]/opengraph-image.tsx b/apps/web/src/app/r/[slug]/opengraph-image.tsxnew file mode 100644index 000000000..0a86b861f--- /dev/null+++ b/apps/web/src/app/r/[slug]/opengraph-image.tsx@@ -0,0 +1,68 @@+import { ImageResponse } from "next/og";++import { fetchPublicReplay } from "../../../lib/replay";++// Dynamic OG image for public replay unfurls on X / LinkedIn / Slack.+export const runtime = "nodejs";+export const alt = "AiSOC investigation replay";+export const size = { width: 1200, height: 630 };+export const contentType = "image/png";++function verdictColor(verdict: string): string {+ const v = verdict.toLowerCase();+ if (/true|confirmed|incident|positive/.test(v)) return "#f87171";+ if (/review|needs/.test(v)) return "#fbbf24";+ return "#22c55e";+}++export default async function Image({ params }: { params: Promise<{ slug: string }> }) {+ const { slug } = await params;+ const replay = await fetchPublicReplay(slug);+ const s = replay?.snapshot;+ const verdict = s?.verdict ?? "unknown";+ const title = replay?.title ?? "Investigation replay";+ const elapsed = s ? `${(s.elapsedMs / 1000).toFixed(0)}s` : "—";+ const techniques = (s?.techniques ?? []).slice(0, 6).join(" · ");++ return new ImageResponse(+ (+ <div+ style={{+ width: "100%",+ height: "100%",+ display: "flex",+ flexDirection: "column",+ background: "linear-gradient(135deg, #0b1020, #131a33)",+ color: "#e6e9f5",+ fontFamily: "sans-serif",+ padding: 64,+ }}+ >+ <div style={{ display: "flex", height: 8, width: "100%", background: "#7b2bbe", position: "absolute", top: 0, left: 0 }} />+ <div style={{ fontSize: 32, fontWeight: 700 }}>AiSOC · investigation replay</div>+ <div style={{ fontSize: 26, color: "#8b93b7", marginTop: 12 }}>{title.slice(0, 64)}</div>+ <div style={{ fontSize: 84, fontWeight: 800, color: verdictColor(verdict), marginTop: 40, textTransform: "uppercase" }}>+ {verdict.replace(/_/g, " ")}+ </div>+ <div style={{ fontSize: 26, color: "#8b93b7", marginTop: 12 }}>{techniques || "no techniques"}</div>+ <div style={{ display: "flex", gap: 56, marginTop: "auto" }}>+ <Stat value={elapsed} label="to verdict" />+ <Stat value={String(s?.stepCount ?? 0)} label="steps" />+ <Stat value={String(s?.toolCallCount ?? 0)} label="tool calls" />+ <Stat value={String(s?.evidenceSourceCount ?? 0)} label="evidence" />+ </div>+ <div style={{ fontSize: 22, color: "#6b7394", marginTop: 24 }}>tryaisoc.com · github.com/beenuar/AiSOC</div>+ </div>+ ),+ size,+ );+}++function Stat({ value, label }: { value: string; label: string }) {+ return (+ <div style={{ display: "flex", flexDirection: "column" }}>+ <div style={{ fontSize: 40, fontWeight: 700 }}>{value}</div>+ <div style={{ fontSize: 22, color: "#8b93b7" }}>{label}</div>+ </div>+ );+}diff --git a/apps/web/src/app/r/[slug]/page.tsx b/apps/web/src/app/r/[slug]/page.tsxnew file mode 100644index 000000000..2e0d1a838--- /dev/null+++ b/apps/web/src/app/r/[slug]/page.tsx@@ -0,0 +1,68 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";++import { fetchPublicReplay } from "../../../lib/replay";+import { getPublicSiteUrl } from "../../../lib/site";+import { ReplayPlayer } from "./ReplayPlayer";++interface PageProps {+ params: Promise<{ slug: string }>;+}++export async function generateMetadata({ params }: PageProps): Promise<Metadata> {+ const { slug } = await params;+ const replay = await fetchPublicReplay(slug);+ if (!replay) {+ return { title: "Replay not found · AiSOC" };+ }+ const s = replay.snapshot;+ const title = `${replay.title} · AiSOC investigation replay`;+ const description = `Verdict: ${s.verdict.replace(/_/g, " ")} · investigated in ${(s.elapsedMs / 1000).toFixed(+ 0,+ )}s across ${s.stepCount} steps and ${s.toolCallCount} tool calls. Watch the agent reason through it step-by-step.`;+ const url = `${getPublicSiteUrl()}/r/${slug}`;+ return {+ title,+ description,+ alternates: { canonical: url },+ openGraph: { title, description, url, type: "article" },+ twitter: { card: "summary_large_image", title, description },+ };+}++export default async function ReplayPage({ params }: PageProps) {+ const { slug } = await params;+ const replay = await fetchPublicReplay(slug);+ if (!replay) notFound();++ const s = replay.snapshot;+ return (+ <main style={{ background: "#0b1020", minHeight: "100vh", color: "#e6e9f5", padding: "48px 24px" }}>+ <div style={{ maxWidth: 1040, margin: "0 auto" }}>+ <a href="/" style={{ color: "#8b93b7", textDecoration: "none", fontSize: 14 }}>+ ← AiSOC+ </a>+ <header style={{ margin: "16px 0 32px" }}>+ <div style={{ color: "#8b93b7", fontSize: 13, textTransform: "uppercase", letterSpacing: 1 }}>+ Public investigation replay · redacted+ </div>+ <h1 style={{ fontSize: 30, fontWeight: 800, margin: "8px 0 0" }}>{replay.title}</h1>+ <p style={{ color: "#8b93b7", fontSize: 14, marginTop: 8 }}>+ {s.model} · {s.stepCount} steps · {s.toolCallCount} tool calls · {(s.elapsedMs / 1000).toFixed(0)}s ·{" "}+ {replay.view_count.toLocaleString()} views+ </p>+ </header>++ <ReplayPlayer snapshot={s} />++ <footer style={{ marginTop: 48, borderTop: "1px solid #232b4d", paddingTop: 20, color: "#64748b", fontSize: 13 }}>+ Entity names, IPs, and identities are redacted. This is a read-only snapshot of an{" "}+ <a href="https://github.com/beenuar/AiSOC" style={{ color: "#8b93b7" }}>+ open-source AiSOC+ </a>{" "}+ investigation. Reproduce the demo with <code>npx aisoc triage --demo</code>.+ </footer>+ </div>+ </main>+ );+}diff --git a/apps/web/src/lib/replay.test.ts b/apps/web/src/lib/replay.test.tsnew file mode 100644index 000000000..d779a8f7e--- /dev/null+++ b/apps/web/src/lib/replay.test.ts@@ -0,0 +1,43 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { fetchPublicReplay } from "./replay";++describe("fetchPublicReplay", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it("returns the parsed replay on 200", async () => {+ const payload = { slug: "abc123def456", title: "T", case_id: "INC-1", snapshot: { stepCount: 3 }, view_count: 5, created_at: "x" };+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(JSON.stringify(payload), { status: 200, headers: { "content-type": "application/json" } })),+ );+ const result = await fetchPublicReplay("abc123def456");+ expect(result?.slug).toBe("abc123def456");+ expect(result?.snapshot.stepCount).toBe(3);+ });++ it("returns null on 404", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response("nope", { status: 404 })));+ expect(await fetchPublicReplay("missing")).toBeNull();+ });++ it("returns null on network error (never throws)", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => {+ throw new Error("boom");+ }),+ );+ expect(await fetchPublicReplay("x")).toBeNull();+ });++ it("URL-encodes the slug", async () => {+ const spy = vi.fn(async () => new Response("{}", { status: 200 }));+ vi.stubGlobal("fetch", spy);+ await fetchPublicReplay("a/b");+ expect(String(spy.mock.calls[0]?.[0])).toContain("a%2Fb");+ });+});diff --git a/apps/web/src/lib/replay.ts b/apps/web/src/lib/replay.tsnew file mode 100644index 000000000..f4b1b2513--- /dev/null+++ b/apps/web/src/lib/replay.ts@@ -0,0 +1,90 @@+/**+ * Client + server helpers for the public investigation-replay page (`/r/<slug>`).+ *+ * The snapshot shape mirrors `services/api/app/services/replay_redaction.py`.+ * Everything here is already redacted server-side, so it is safe to render+ * publicly and to embed in OG cards.+ */++export interface ReplayStepDecision {+ reason?: string | null;+ tool?: string | null;+ confidence?: number | null;+}++export interface ReplayStep {+ seq: number;+ kind: string;+ agent: string;+ summary: string;+ durationMs: number;+ decision?: ReplayStepDecision | null;+}++export interface ReplayEvidenceCard {+ seq: number;+ summary: string;+ source: string;+}++export interface ReplayGraphNode {+ id: string;+ label: string;+ kind: string;+}++export interface ReplayGraphEdge {+ source: string;+ target: string;+ label?: string;+}++export interface ReplaySnapshot {+ schemaVersion: number;+ caseId: string;+ title: string;+ verdict: string;+ model: string;+ elapsedMs: number;+ stepCount: number;+ toolCallCount: number;+ llmCallCount: number;+ evidenceSourceCount: number;+ techniques: string[];+ steps: ReplayStep[];+ evidenceCards: ReplayEvidenceCard[];+ attackGraph: { nodes: ReplayGraphNode[]; edges: ReplayGraphEdge[] };+}++export interface PublicReplay {+ slug: string;+ title: string;+ case_id: string;+ snapshot: ReplaySnapshot;+ view_count: number;+ created_at: string;+}++/** Internal API origin for server-side fetches (mirrors next.config rewrites). */+function apiBase(): string {+ return (+ process.env.API_URL ||+ process.env.INTERNAL_API_URL ||+ process.env.NEXT_PUBLIC_API_URL ||+ "http://localhost:8000"+ ).replace(/\/$/, "");+}++/** Server-side fetch of a published replay. Returns null on 404 / error. */+export async function fetchPublicReplay(slug: string): Promise<PublicReplay | null> {+ try {+ const res = await fetch(`${apiBase()}/api/v1/r/${encodeURIComponent(slug)}`, {+ // Public, cacheable content; revalidate periodically at the edge.+ next: { revalidate: 300 },+ });+ if (!res.ok) return null;+ return (await res.json()) as PublicReplay;+ } catch {+ return null;+ }+}diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 04b986dc9..d1d14222d 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -6715,6 +6715,165 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/ledger/{run_id}/publish/preview:+ post:+ tags:+ - replay+ summary: Preview Publish+ description: Build the redacted snapshot + alias map for the pre-publish review.+ operationId: preview_publish_api_v1_ledger__run_id__publish_preview_post+ security:+ - HTTPBearer: []+ parameters:+ - name: run_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Run Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/PublishPreview'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/ledger/{run_id}/publish:+ post:+ tags:+ - replay+ summary: Publish Replay+ description: Persist an immutable, redacted public snapshot and return its share+ URL.+ operationId: publish_replay_api_v1_ledger__run_id__publish_post+ security:+ - HTTPBearer: []+ parameters:+ - name: run_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Run Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/PublishRequest'+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/PublishResult'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/ledger/{run_id}/published:+ get:+ tags:+ - replay+ summary: List Published+ operationId: list_published_api_v1_ledger__run_id__published_get+ security:+ - HTTPBearer: []+ parameters:+ - name: run_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Run Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: array+ items:+ $ref: '#/components/schemas/PublishedSummary'+ title: Response List Published Api V1 Ledger Run Id Published Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/ledger/publish/{slug}:+ delete:+ tags:+ - replay+ summary: Unpublish Replay+ operationId: unpublish_replay_api_v1_ledger_publish__slug__delete+ security:+ - HTTPBearer: []+ parameters:+ - name: slug+ in: path+ required: true+ schema:+ type: string+ title: Slug+ responses:+ '204':+ description: Successful Response+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/r/{slug}:+ get:+ tags:+ - replay-public+ summary: Get Public Replay+ description: 'Public, unauthenticated read of a redacted replay snapshot.+++ Uses a non-RLS session because ``published_replays`` is intentionally++ public-by-design (post-redaction, non-identifying). Increments a++ best-effort view counter (the only mutation the immutability trigger++ permits).'+ operationId: get_public_replay_api_v1_r__slug__get+ parameters:+ - name: slug+ in: path+ required: true+ schema:+ type: string+ title: Slug+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/PublicReplay'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/identity/effective-permissions/providers:get:tags:@@ -21765,6 +21924,101 @@ components:- created_at- updated_attitle: ProposalResponse+ PublicReplay:+ properties:+ slug:+ type: string+ title: Slug+ title:+ type: string+ title: Title+ case_id:+ type: string+ title: Case Id+ snapshot:+ additionalProperties: true+ type: object+ title: Snapshot+ view_count:+ type: integer+ title: View Count+ created_at:+ type: string+ format: date-time+ title: Created At+ type: object+ required:+ - slug+ - title+ - case_id+ - snapshot+ - view_count+ - created_at+ title: PublicReplay+ PublishPreview:+ properties:+ run_id:+ type: string+ format: uuid+ title: Run Id+ title:+ type: string+ title: Title+ snapshot:+ additionalProperties: true+ type: object+ title: Snapshot+ alias_map:+ additionalProperties:+ type: string+ type: object+ title: Alias Map+ type: object+ required:+ - run_id+ - title+ - snapshot+ - alias_map+ title: PublishPreview+ description: 'Pre-publish diff: what the public will see + what will be hidden.'+ PublishRequest:+ properties:+ confirm:+ type: boolean+ title: Confirm+ description: Must be true to publish.+ default: false+ title_override:+ anyOf:+ - type: string+ maxLength: 200+ - type: 'null'+ title: Title Override+ type: object+ title: PublishRequest+ PublishResult:+ properties:+ slug:+ type: string+ title: Slug+ url:+ type: string+ title: Url+ run_id:+ type: string+ format: uuid+ title: Run Id+ created_at:+ type: string+ format: date-time+ title: Created At+ type: object+ required:+ - slug+ - url+ - run_id+ - created_at+ title: PublishResultPublishStatus:type: stringenum:@@ -21772,6 +22026,36 @@ components:- approved- rejectedtitle: PublishStatus+ PublishedSummary:+ properties:+ slug:+ type: string+ title: Slug+ url:+ type: string+ title: Url+ title:+ type: string+ title: Title+ case_id:+ type: string+ title: Case Id+ view_count:+ type: integer+ title: View Count+ created_at:+ type: string+ format: date-time+ title: Created At+ type: object+ required:+ - slug+ - url+ - title+ - case_id+ - view_count+ - created_at+ title: PublishedSummaryQueryRequest:properties:question:diff --git a/packages/aisoc-lite/package.json b/packages/aisoc-lite/package.jsonindex f9c77ad5c..4e731d216 100644--- a/packages/aisoc-lite/package.json+++ b/packages/aisoc-lite/package.json@@ -48,6 +48,7 @@"picocolors": "^1.1.1"},"devDependencies": {+ "@aisoc/report-card": "workspace:*","@types/node": "^25.9.2","tsup": "^8.3.0","typescript": "^6.0.3",diff --git a/packages/aisoc-lite/src/share.ts b/packages/aisoc-lite/src/share.tsindex dcbcaad4d..a96104591 100644--- a/packages/aisoc-lite/src/share.ts+++ b/packages/aisoc-lite/src/share.ts@@ -6,12 +6,13 @@* never alert titles, IOCs, hostnames, or usernames. Nothing here can leak* environment specifics, so it's safe to post without a redaction review.*- * The SVG format is intentionally identical in spirit to the W3- * `packages/report-card` web renderer so a CLI card and a dashboard "share- * results" card look the same. Kept dependency-free so `npx aisoc` stays tiny.+ * Rendering is delegated to the shared `@aisoc/report-card` package (the same+ * renderer the noise-tuning dashboard and the web OG routes use), bundled into+ * the CLI at build time so `npx aisoc` stays a single self-contained artifact.*/import { writeFile } from "node:fs/promises";+import { renderCardMarkdown, renderCardSvg, type ReportCardData } from "@aisoc/report-card";import type { TriageResult } from "./verdict/types.js";export interface ShareArtifacts {@@ -19,71 +20,27 @@ export interface ShareArtifacts {svg: string;}-export function renderMarkdownCard(result: TriageResult): string {+function toCardData(result: TriageResult): ReportCardData {const s = result.summary;- const seconds = (s.elapsedMs / 1000).toFixed(2);- return [- "## AiSOC triage report card",- "",- `> ${s.headline}`,- "",- "| Metric | Value |",- "|---|---|",- `| Alerts triaged | **${s.total}** |`,- `| Escalated (TP / likely-TP) | **${s.truePositive}** |`,- `| Needs review | **${s.needsReview}** |`,- `| Suppressed as noise | **${s.suppressed}** |`,- `| Noise suppressed | **${s.noisePercent}%** |`,- `| Wall-clock | **${seconds}s** |`,- `| Mode | ${result.deterministic ? "deterministic (no LLM key)" : "LLM-assisted"} |`,- "",- "Aggregate counts only — no alert content, IOCs, or identities are included.",- "",- "Reproduce: `npx aisoc triage --demo` · Open source: https://github.com/beenuar/AiSOC",- "",- ].join("\n");+ return {+ kind: "triage",+ total: s.total,+ escalate: s.truePositive,+ review: s.needsReview,+ suppress: s.suppressed,+ noisePercent: s.noisePercent,+ elapsedSeconds: s.elapsedMs / 1000,+ deterministic: result.deterministic,+ };}-function esc(s: string): string {- return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+export function renderMarkdownCard(result: TriageResult): string {+ return renderCardMarkdown(toCardData(result));}/** A 1200×630 share card (X/LinkedIn/Slack unfurl aspect ratio) as standalone SVG. */export function renderSvgCard(result: TriageResult): string {- const s = result.summary;- const seconds = (s.elapsedMs / 1000).toFixed(1);- const bigNoise = `${s.noisePercent}%`;- return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="AiSOC triage report card">- <defs>- <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">- <stop offset="0" stop-color="#0b1020"/>- <stop offset="1" stop-color="#131a33"/>- </linearGradient>- </defs>- <rect width="1200" height="630" fill="url(#bg)"/>- <rect x="0" y="0" width="1200" height="8" fill="#7b2bbe"/>- <text x="64" y="96" fill="#e6e9f5" font-family="ui-sans-serif,system-ui,Segoe UI,Roboto,Arial" font-size="34" font-weight="700">AiSOC · alert triage</text>- <text x="64" y="150" fill="#8b93b7" font-family="ui-sans-serif,system-ui,Segoe UI,Roboto,Arial" font-size="24">${esc(result.deterministic ? "deterministic verdict engine · no LLM key" : "LLM-assisted verdict engine")}</text>-- <text x="64" y="300" fill="#22c55e" font-family="ui-sans-serif,system-ui,Segoe UI,Roboto,Arial" font-size="150" font-weight="800">${bigNoise}</text>- <text x="64" y="356" fill="#8b93b7" font-family="ui-sans-serif,system-ui,Segoe UI,Roboto,Arial" font-size="28">of alert noise suppressed</text>-- <g font-family="ui-sans-serif,system-ui,Segoe UI,Roboto,Arial">- <text x="64" y="470" fill="#e6e9f5" font-size="30" font-weight="700">${s.total}</text>- <text x="64" y="506" fill="#8b93b7" font-size="22">triaged</text>- <text x="320" y="470" fill="#f87171" font-size="30" font-weight="700">${s.truePositive}</text>- <text x="320" y="506" fill="#8b93b7" font-size="22">escalate</text>- <text x="560" y="470" fill="#fbbf24" font-size="30" font-weight="700">${s.needsReview}</text>- <text x="560" y="506" fill="#8b93b7" font-size="22">review</text>- <text x="800" y="470" fill="#94a3b8" font-size="30" font-weight="700">${s.suppressed}</text>- <text x="800" y="506" fill="#8b93b7" font-size="22">suppressed</text>- <text x="1040" y="470" fill="#e6e9f5" font-size="30" font-weight="700">${seconds}s</text>- <text x="1040" y="506" fill="#8b93b7" font-size="22">elapsed</text>- </g>-- <text x="64" y="590" fill="#6b7394" font-family="ui-monospace,SFMono-Regular,Menlo,monospace" font-size="22">npx aisoc triage --demo · github.com/beenuar/AiSOC</text>-</svg>-`;+ return renderCardSvg(toCardData(result));}export function renderShareArtifacts(result: TriageResult): ShareArtifacts {diff --git a/packages/aisoc-lite/tsup.config.ts b/packages/aisoc-lite/tsup.config.tsindex 57489ff90..29426059e 100644--- a/packages/aisoc-lite/tsup.config.ts+++ b/packages/aisoc-lite/tsup.config.ts@@ -15,4 +15,7 @@ export default defineConfig({sourcemap: false,minify: false,splitting: false,+ // Bundle the shared report-card renderer INTO dist so the published `aisoc`+ // package has no unpublished workspace dependency at install time.+ noExternal: ["@aisoc/report-card"],});diff --git a/packages/report-card/package.json b/packages/report-card/package.jsonnew file mode 100644index 000000000..eb27804e3--- /dev/null+++ b/packages/report-card/package.json@@ -0,0 +1,32 @@+{+ "name": "@aisoc/report-card",+ "version": "0.1.0",+ "description": "Shared, dependency-free renderer for AiSOC share cards (triage summaries, ATT&CK coverage grades, investigation-replay verdicts) as SVG + Markdown. Used by the aisoc CLI --share flag, the noise-tuning dashboard, and the web OG image routes.",+ "license": "MIT",+ "type": "module",+ "main": "./dist/index.js",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js"+ }+ },+ "files": ["dist", "src"],+ "scripts": {+ "build": "tsup src/index.ts --format esm --dts --clean",+ "dev": "tsup src/index.ts --format esm --dts --watch",+ "type-check": "tsc --noEmit",+ "test": "vitest run",+ "clean": "rm -rf dist"+ },+ "devDependencies": {+ "tsup": "^8.3.0",+ "typescript": "^6.0.3",+ "vitest": "^4.1.10"+ },+ "publishConfig": {+ "access": "public"+ }+}diff --git a/packages/report-card/src/index.test.ts b/packages/report-card/src/index.test.tsnew file mode 100644index 000000000..9aa7226c1--- /dev/null+++ b/packages/report-card/src/index.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it } from "vitest";+import { renderCardSvg, renderCardMarkdown, coverageGrade, esc, type ReportCardData } from "./index.js";++describe("report-card renderers", () => {+ const triage: ReportCardData = {+ kind: "triage",+ total: 200,+ escalate: 12,+ review: 17,+ suppress: 171,+ noisePercent: 85.5,+ elapsedSeconds: 0.1,+ deterministic: true,+ };++ it("triage SVG is a valid 1200x630 card with the headline numbers", () => {+ const svg = renderCardSvg(triage);+ expect(svg).toContain("<svg");+ expect(svg).toContain('width="1200"');+ expect(svg).toContain('height="630"');+ expect(svg).toContain("85.5%");+ expect(svg).toContain(">200<");+ });++ it("coverage grade thresholds", () => {+ expect(coverageGrade(95)).toBe("A");+ expect(coverageGrade(80)).toBe("B");+ expect(coverageGrade(65)).toBe("C");+ expect(coverageGrade(45)).toBe("D");+ expect(coverageGrade(20)).toBe("F");+ });++ it("coverage SVG shows the grade + percent", () => {+ const svg = renderCardSvg({ kind: "coverage", grade: "B", covered: 80, total: 100, percent: 80 });+ expect(svg).toContain(">B<");+ expect(svg).toContain("80%");+ });++ it("replay card escapes and renders verdict + techniques", () => {+ const svg = renderCardSvg({+ kind: "replay",+ caseTitle: "Ransomware on HOST_1",+ verdict: "true_positive",+ techniques: ["T1486", "T1490"],+ elapsedSeconds: 94,+ stepCount: 14,+ toolCalls: 6,+ });+ expect(svg).toContain("TRUE POSITIVE");+ expect(svg).toContain("T1486");+ });++ it("markdown mirrors the card and is postable", () => {+ expect(renderCardMarkdown(triage)).toContain("npx aisoc triage --demo");+ });++ it("esc neutralizes angle brackets and ampersands", () => {+ expect(esc("<b>&")).toBe("<b>&");+ });+});diff --git a/packages/report-card/src/index.ts b/packages/report-card/src/index.tsnew file mode 100644index 000000000..6e4642d43--- /dev/null+++ b/packages/report-card/src/index.ts@@ -0,0 +1,180 @@+/**+ * @aisoc/report-card — dependency-free share-card renderer.+ *+ * One visual language for every shareable AiSOC artifact:+ * - `triage` — the `aisoc triage --share` card and the noise-tuning+ * dashboard's "share results" button.+ * - `coverage` — an ATT&CK coverage grade (A–F) for the /tools/coverage grader.+ * - `replay` — an investigation-replay verdict card for `/r/<slug>` unfurls.+ *+ * Outputs a standalone 1200×630 SVG (X/LinkedIn/Slack unfurl ratio) and a+ * Markdown block. All aggregate/taxonomy data only — never customer PII.+ */++export type ReportCardData =+ | {+ kind: "triage";+ total: number;+ escalate: number;+ review: number;+ suppress: number;+ noisePercent: number;+ elapsedSeconds: number;+ deterministic: boolean;+ }+ | {+ kind: "coverage";+ grade: string;+ covered: number;+ total: number;+ percent: number;+ topUncovered?: string[];+ }+ | {+ kind: "replay";+ caseTitle: string;+ verdict: string;+ techniques: string[];+ elapsedSeconds: number;+ stepCount: number;+ toolCalls: number;+ };++const BRAND = "#7b2bbe";+const FG = "#e6e9f5";+const MUTED = "#8b93b7";+const GREEN = "#22c55e";+const RED = "#f87171";+const AMBER = "#fbbf24";++const FONT = "ui-sans-serif,system-ui,Segoe UI,Roboto,Arial";+const MONO = "ui-monospace,SFMono-Regular,Menlo,monospace";++export function esc(s: string): string {+ return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+}++function frame(inner: string): string {+ return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="AiSOC report card">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="#0b1020"/>+ <stop offset="1" stop-color="#131a33"/>+ </linearGradient>+ </defs>+ <rect width="1200" height="630" fill="url(#bg)"/>+ <rect x="0" y="0" width="1200" height="8" fill="${BRAND}"/>+${inner}+ <text x="64" y="590" fill="#6b7394" font-family="${MONO}" font-size="22">github.com/beenuar/AiSOC</text>+</svg>+`;+}++function stat(x: number, value: string, label: string, color: string): string {+ return ` <text x="${x}" y="470" fill="${color}" font-family="${FONT}" font-size="30" font-weight="700">${esc(value)}</text>+ <text x="${x}" y="506" fill="${MUTED}" font-family="${FONT}" font-size="22">${esc(label)}</text>`;+}++function gradeColor(grade: string): string {+ const g = grade.toUpperCase()[0] ?? "F";+ if (g === "A" || g === "B") return GREEN;+ if (g === "C" || g === "D") return AMBER;+ return RED;+}++export function renderCardSvg(data: ReportCardData): string {+ switch (data.kind) {+ case "triage": {+ const inner = ` <text x="64" y="96" fill="${FG}" font-family="${FONT}" font-size="34" font-weight="700">AiSOC · alert triage</text>+ <text x="64" y="150" fill="${MUTED}" font-family="${FONT}" font-size="24">${esc(+ data.deterministic ? "deterministic verdict engine · no LLM key" : "LLM-assisted verdict engine",+ )}</text>+ <text x="64" y="300" fill="${GREEN}" font-family="${FONT}" font-size="150" font-weight="800">${data.noisePercent}%</text>+ <text x="64" y="356" fill="${MUTED}" font-family="${FONT}" font-size="28">of alert noise suppressed</text>+${stat(64, String(data.total), "triaged", FG)}+${stat(320, String(data.escalate), "escalate", RED)}+${stat(560, String(data.review), "review", AMBER)}+${stat(800, String(data.suppress), "suppressed", MUTED)}+${stat(1040, `${data.elapsedSeconds.toFixed(1)}s`, "elapsed", FG)}`;+ return frame(inner);+ }+ case "coverage": {+ const inner = ` <text x="64" y="96" fill="${FG}" font-family="${FONT}" font-size="34" font-weight="700">AiSOC · ATT&CK coverage grade</text>+ <text x="64" y="290" fill="${gradeColor(data.grade)}" font-family="${FONT}" font-size="200" font-weight="800">${esc(+ data.grade,+ )}</text>+ <text x="420" y="230" fill="${FG}" font-family="${FONT}" font-size="60" font-weight="700">${data.percent}%</text>+ <text x="420" y="280" fill="${MUTED}" font-family="${FONT}" font-size="26">${data.covered} / ${data.total} techniques covered</text>+${stat(64, String(data.covered), "covered", GREEN)}+${stat(320, String(data.total - data.covered), "uncovered", RED)}+${stat(560, `${data.percent}%`, "coverage", FG)}`;+ return frame(inner);+ }+ case "replay": {+ const verdictColor = /true|confirmed|incident|positive/i.test(data.verdict) ? RED : GREEN;+ const inner = ` <text x="64" y="96" fill="${FG}" font-family="${FONT}" font-size="34" font-weight="700">AiSOC · investigation replay</text>+ <text x="64" y="170" fill="${MUTED}" font-family="${FONT}" font-size="26">${esc(data.caseTitle.slice(0, 60))}</text>+ <text x="64" y="300" fill="${verdictColor}" font-family="${FONT}" font-size="72" font-weight="800">${esc(+ data.verdict.replace(/_/g, " ").toUpperCase(),+ )}</text>+ <text x="64" y="356" fill="${MUTED}" font-family="${FONT}" font-size="24">${esc(+ data.techniques.slice(0, 6).join(" · ") || "no techniques",+ )}</text>+${stat(64, `${data.elapsedSeconds.toFixed(0)}s`, "to verdict", FG)}+${stat(320, String(data.stepCount), "steps", FG)}+${stat(560, String(data.toolCalls), "tool calls", FG)}`;+ return frame(inner);+ }+ default: {+ const _never: never = data;+ return _never;+ }+ }+}++export function renderCardMarkdown(data: ReportCardData): string {+ switch (data.kind) {+ case "triage":+ return [+ "## AiSOC triage report card",+ "",+ `- **${data.total}** alerts triaged`,+ `- **${data.noisePercent}%** noise suppressed`,+ `- **${data.escalate}** escalate · **${data.review}** review · **${data.suppress}** suppressed`,+ `- **${data.elapsedSeconds.toFixed(1)}s** elapsed (${data.deterministic ? "deterministic, no LLM" : "LLM-assisted"})`,+ "",+ "Reproduce: `npx aisoc triage --demo` · https://github.com/beenuar/AiSOC",+ ].join("\n");+ case "coverage":+ return [+ "## AiSOC ATT&CK coverage grade",+ "",+ `- Grade: **${data.grade}**`,+ `- Covered: **${data.covered} / ${data.total}** techniques (**${data.percent}%**)`,+ ...(data.topUncovered?.length ? [`- Top uncovered: ${data.topUncovered.slice(0, 10).join(", ")}`] : []),+ "",+ "Grade yours: https://tryaisoc.com/tools/coverage",+ ].join("\n");+ case "replay":+ return [+ `## AiSOC investigation replay — ${data.caseTitle}`,+ "",+ `- Verdict: **${data.verdict}**`,+ `- To verdict: **${data.elapsedSeconds.toFixed(0)}s**, ${data.stepCount} steps, ${data.toolCalls} tool calls`,+ ...(data.techniques.length ? [`- Techniques: ${data.techniques.slice(0, 12).join(", ")}`] : []),+ ].join("\n");+ default: {+ const _never: never = data;+ return _never;+ }+ }+}++/** Coverage grade helper shared by the grader tool + card. */+export function coverageGrade(percent: number): string {+ if (percent >= 90) return "A";+ if (percent >= 75) return "B";+ if (percent >= 60) return "C";+ if (percent >= 40) return "D";+ return "F";+}diff --git a/packages/report-card/tsconfig.json b/packages/report-card/tsconfig.jsonnew file mode 100644index 000000000..9cf9e5e54--- /dev/null+++ b/packages/report-card/tsconfig.json@@ -0,0 +1,20 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "ignoreDeprecations": "6.0",+ "lib": ["ES2022"],+ "declaration": true,+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "verbatimModuleSyntax": true,+ "isolatedModules": true,+ "forceConsistentCasingInFileNames": true,+ "outDir": "dist"+ },+ "include": ["src"],+ "exclude": ["dist", "node_modules", "**/*.test.ts"]+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 82069cbc2..1ab298b78 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -63,6 +63,9 @@ importers:apps/web:dependencies:+ '@aisoc/report-card':+ specifier: workspace:*+ version: link:../../packages/report-card'@aisoc/types':specifier: workspace:*version: link:../../packages/types@@ -224,6 +227,9 @@ importers:specifier: ^1.1.1version: 1.1.1devDependencies:+ '@aisoc/report-card':+ specifier: workspace:*+ version: link:../report-card'@types/node':specifier: ^25.9.2version: 25.9.2@@ -243,6 +249,18 @@ importers:specifier: ^6.0.3version: 6.0.3+ packages/report-card:+ devDependencies:+ tsup:+ specifier: ^8.3.0+ version: 8.5.1([email protected])([email protected])+ typescript:+ specifier: ^6.0.3+ version: 6.0.3+ vitest:+ specifier: ^4.1.10+ version: 4.1.10(@types/[email protected])([email protected])+packages/sdk-ts:dependencies:openapi-fetch:diff --git a/scripts/sync_vendored_redactor.py b/scripts/sync_vendored_redactor.pynew file mode 100644index 000000000..cfc54c0dc--- /dev/null+++ b/scripts/sync_vendored_redactor.py@@ -0,0 +1,80 @@+#!/usr/bin/env python3+"""Keep ``services/api/app/_vendor/redactor.py`` in lockstep with its source.++The reversible pseudonymizer lives canonically under+``services/agents/app/privacy/redactor.py``. The public-replay publish flow in+the API service (``services/api/app/services/replay_redaction.py``) reuses it to+strip customer PII before a ledger snapshot is served at ``/r/<slug>``. Because+the ``aisoc-api`` Docker image is built with ``services/api`` as its build+context, anything under ``services/agents`` is unavailable at runtime, so we+ship a vendored mirror inside the API package.++Run modes+---------+* ``python scripts/sync_vendored_redactor.py`` — copy source → vendored.+* ``python scripts/sync_vendored_redactor.py --check`` — fail (exit 1) if the+ vendored file is missing or differs from the source. CI uses this mode.++The script is intentionally tiny and dependency-free so it can run in any CI+runner.++AiSOC — open-source AI Security Operations Center (MIT License).+"""++from __future__ import annotations++import argparse+import filecmp+import shutil+import sys+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]+SOURCE_FILE = REPO_ROOT / "services" / "agents" / "app" / "privacy" / "redactor.py"+VENDORED_FILE = REPO_ROOT / "services" / "api" / "app" / "_vendor" / "redactor.py"+++def _check() -> int:+ if not SOURCE_FILE.is_file():+ print(f"FAIL: source file missing: {SOURCE_FILE}", file=sys.stderr)+ return 1+ if not VENDORED_FILE.is_file():+ print(f"FAIL: vendored file missing: {VENDORED_FILE}", file=sys.stderr)+ return 1+ if not filecmp.cmp(SOURCE_FILE, VENDORED_FILE, shallow=False):+ print(+ "FAIL: vendored redactor.py is out of sync with source.\n"+ f" Source: {SOURCE_FILE.relative_to(REPO_ROOT)}\n"+ f" Vendored: {VENDORED_FILE.relative_to(REPO_ROOT)}\n\n"+ "Re-run: python scripts/sync_vendored_redactor.py",+ file=sys.stderr,+ )+ return 1+ print("OK: vendored redactor.py matches source.")+ return 0+++def _sync() -> int:+ if not SOURCE_FILE.is_file():+ print(f"FAIL: source file missing: {SOURCE_FILE}", file=sys.stderr)+ return 1+ VENDORED_FILE.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(SOURCE_FILE, VENDORED_FILE)+ print(f"copied {SOURCE_FILE.relative_to(REPO_ROOT)} → {VENDORED_FILE.relative_to(REPO_ROOT)}")+ print("\nDone. Don't forget to commit services/api/app/_vendor/redactor.py.")+ return 0+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--check",+ action="store_true",+ help="Fail with a non-zero exit code if the vendored file is out of sync.",+ )+ args = parser.parse_args()+ return _check() if args.check else _sync()+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/services/api/app/_vendor/redactor.py b/services/api/app/_vendor/redactor.pynew file mode 100644index 000000000..7c1fe65f0--- /dev/null+++ b/services/api/app/_vendor/redactor.py@@ -0,0 +1,168 @@+"""Reversible pseudonymization of evidence before it leaves the process.++Phase 1.4 of the world-class program. The README promises "no data+exfiltration", yet the default path sends raw evidence to a third-party LLM.+This module pseudonymizes the *customer's* identifying data — internal IPs,+emails, file paths, secrets, internal hostnames, usernames — through a per-run,+per-tenant, in-memory-only bidirectional map. The LLM reasons over ``USER_1``,+``HOST_2``, ``IP_3``; the ledger and console re-hydrate the real values locally+via :meth:`Pseudonymizer.rehydrate`.++Public threat indicators (external domains/IPs) are intentionally *not*+redacted by default: they are IOCs, not customer PII, and the agent needs them+to reason. This is a deliberate, documented trade-off (see docs/trust/).++Pure/synchronous, stdlib only, so it is unit-testable offline and gated: a+golden-corpus test asserts zero raw customer PII survives redaction.+"""++from __future__ import annotations++import ipaddress+import re+from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from typing import Any++__all__ = ["RedactionConfig", "Pseudonymizer", "default_pseudonymizer"]++# Field-name hints whose *values* are treated as usernames when redacting+# structured evidence.+_USER_FIELD_HINTS = frozenset({"user", "username", "user_name", "account", "actor", "principal", "samaccountname", "upn", "subject"})++_EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b")+# Windows (C:\...), UNC (\\host\share), and multi-segment unix paths.+_WIN_PATH_RE = re.compile(r"[A-Za-z]:\\[^\s\"']+")+_UNC_PATH_RE = re.compile(r"\\\\[^\s\"']+")+_UNIX_PATH_RE = re.compile(r"(?:/[A-Za-z0-9._\-]+){2,}/?")+# DOMAIN\user (down-level logon name).+_DOMAIN_USER_RE = re.compile(r"\b[A-Za-z0-9.\-]+\\[A-Za-z0-9._\-]+")+# Common secret shapes: AWS keys, OpenAI-style, bearer/JWT, private key headers.+_SECRET_RES: tuple[re.Pattern[str], ...] = (+ re.compile(r"\bAKIA[0-9A-Z]{16}\b"),+ re.compile(r"\b(?:sk|rk)-[A-Za-z0-9]{20,}\b"),+ re.compile(r"\bghp_[A-Za-z0-9]{36}\b"),+ re.compile(r"\beyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\b"), # JWT+ re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"),+)+_IPV4_RE = re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b")+# FQDNs; only redacted when the suffix is in the internal set.+_FQDN_RE = re.compile(r"\b(?:[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}\b")++_DEFAULT_INTERNAL_SUFFIXES = (".local", ".internal", ".corp", ".lan", ".intranet", ".home.arpa")+++@dataclass(frozen=True)+class RedactionConfig:+ """What to pseudonymize. Defaults are on (fail-safe for the no-exfil claim)."""++ redact_internal_ips: bool = True+ redact_emails: bool = True+ redact_paths: bool = True+ redact_secrets: bool = True+ redact_internal_hostnames: bool = True+ redact_usernames: bool = True+ # Extra domain suffixes considered internal (customer-configurable).+ internal_domain_suffixes: tuple[str, ...] = _DEFAULT_INTERNAL_SUFFIXES+++def _is_internal_ip(value: str) -> bool:+ try:+ ip = ipaddress.ip_address(value)+ except ValueError:+ return False+ return ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved+++class Pseudonymizer:+ """Per-run, per-tenant reversible entity map held only in memory."""++ def __init__(self, *, tenant_id: str = "", config: RedactionConfig | None = None) -> None:+ self.tenant_id = tenant_id+ self.config = config or RedactionConfig()+ self._to_token: dict[str, str] = {}+ self._to_original: dict[str, str] = {}+ self._counters: dict[str, int] = {}++ # -- public API ------------------------------------------------------------++ @property+ def mapping(self) -> dict[str, str]:+ """token -> original, for local (never-egress) re-hydration."""+ return dict(self._to_original)++ def redact(self, text: str) -> str:+ if not text or not isinstance(text, str):+ return text if isinstance(text, str) else ""+ out = text+ # Order matters: secrets/emails/paths/domain-user before bare IPs/hosts,+ # so a token like EMAIL_1 is never re-matched by a later pattern.+ if self.config.redact_secrets:+ for pat in _SECRET_RES:+ out = pat.sub(lambda m: self._token("SECRET", m.group(0)), out)+ if self.config.redact_emails:+ out = _EMAIL_RE.sub(lambda m: self._token("EMAIL", m.group(0)), out)+ # Paths before DOMAIN\user: a Windows path (C:\Users\alice\...) contains+ # backslash-separated segments that would otherwise be mis-matched as a+ # down-level logon name and fragment the path.+ if self.config.redact_paths:+ out = _WIN_PATH_RE.sub(lambda m: self._token("PATH", m.group(0)), out)+ out = _UNC_PATH_RE.sub(lambda m: self._token("PATH", m.group(0)), out)+ out = _UNIX_PATH_RE.sub(lambda m: self._token("PATH", m.group(0)), out)+ if self.config.redact_usernames:+ out = _DOMAIN_USER_RE.sub(lambda m: self._token("USER", m.group(0)), out)+ if self.config.redact_internal_hostnames:+ out = _FQDN_RE.sub(self._maybe_internal_host, out)+ if self.config.redact_internal_ips:+ out = _IPV4_RE.sub(self._maybe_internal_ip, out)+ return out++ def redact_value(self, value: Any, *, _key: str | None = None) -> Any:+ """Recursively redact a JSON-like value. Values under user-ish keys are+ pseudonymized as usernames even if they are plain identifiers."""+ if isinstance(value, str):+ if _key and self.config.redact_usernames and _key.lower() in _USER_FIELD_HINTS and "@" not in value:+ return self._token("USER", value)+ return self.redact(value)+ if isinstance(value, Mapping):+ return {k: self.redact_value(v, _key=str(k)) for k, v in value.items()}+ if isinstance(value, Sequence) and not isinstance(value, str | bytes):+ return [self.redact_value(v) for v in value]+ return value++ def rehydrate(self, text: str) -> str:+ """Reverse redaction locally (never send the result to the LLM)."""+ if not text:+ return text+ out = text+ # Replace longer tokens first to avoid USER_1 clobbering USER_10.+ for token in sorted(self._to_original, key=len, reverse=True):+ out = out.replace(token, self._to_original[token])+ return out++ # -- internals -------------------------------------------------------------++ def _token(self, kind: str, original: str) -> str:+ if original in self._to_token:+ return self._to_token[original]+ self._counters[kind] = self._counters.get(kind, 0) + 1+ token = f"{kind}_{self._counters[kind]}"+ self._to_token[original] = token+ self._to_original[token] = original+ return token++ def _maybe_internal_ip(self, m: re.Match[str]) -> str:+ val = m.group(0)+ return self._token("IP", val) if _is_internal_ip(val) else val++ def _maybe_internal_host(self, m: re.Match[str]) -> str:+ host = m.group(0)+ lowered = host.lower()+ if any(lowered.endswith(sfx) for sfx in self.config.internal_domain_suffixes):+ return self._token("HOST", host)+ return host+++def default_pseudonymizer(tenant_id: str = "") -> Pseudonymizer:+ """A pseudonymizer with all redaction on (the safe default for no-exfil)."""+ return Pseudonymizer(tenant_id=tenant_id, config=RedactionConfig())diff --git a/services/api/app/api/v1/endpoints/replay.py b/services/api/app/api/v1/endpoints/replay.pynew file mode 100644index 000000000..df9f352e6--- /dev/null+++ b/services/api/app/api/v1/endpoints/replay.py@@ -0,0 +1,294 @@+"""Public investigation-replay publishing — v8 W3.++Turns a tenant-private investigation ledger into an immutable, redacted, public+share link at ``tryaisoc.com/r/<slug>``.++Flow:++1. ``POST /ledger/{run_id}/publish/preview`` (auth ``cases:read``) — build the+ redacted snapshot and return it **with the alias map** so the publisher can+ review exactly what will be hidden (the pre-publish diff).+2. ``POST /ledger/{run_id}/publish`` (auth ``cases:write``) — re-build the+ snapshot server-side (the client-supplied preview is never trusted), persist+ an immutable ``published_replays`` row, and return the public slug + URL.+3. ``GET /r/{slug}`` — **public, no auth** — return the redacted snapshot for+ the replay page. Increments a best-effort view counter.+4. ``DELETE /ledger/publish/{slug}`` (auth ``cases:write``) — unpublish+ (tenant-scoped).+5. ``GET /ledger/{run_id}/published`` (auth ``cases:read``) — list a run's+ published replays.++Only the redacted snapshot is persisted; the alias map is preview-only and is+never stored.+"""++from __future__ import annotations++import secrets+import uuid+from datetime import datetime+from typing import Annotated++import structlog+from fastapi import APIRouter, Depends, HTTPException, status+from pydantic import BaseModel, Field+from sqlalchemy import select, update++from app.api.v1.deps import AuthUser, DBSession, require_permission+from app.db.rls import TenantDBSession+from app.models.investigation import InvestigationEvent, InvestigationRun+from app.models.published_replay import PublishedReplay+from app.services.replay_redaction import build_redacted_snapshot++logger = structlog.get_logger()++# Public-share operations hang off /ledger; the public read hangs off /r.+router = APIRouter(prefix="/ledger", tags=["replay"])+public_router = APIRouter(prefix="/r", tags=["replay-public"])++_PUBLIC_BASE = "https://tryaisoc.com/r"+++class PublishPreview(BaseModel):+ """Pre-publish diff: what the public will see + what will be hidden."""++ run_id: uuid.UUID+ title: str+ snapshot: dict+ # alias -> original, so the publisher can confirm the redaction. Never stored.+ alias_map: dict[str, str]+++class PublishRequest(BaseModel):+ confirm: bool = Field(default=False, description="Must be true to publish.")+ title_override: str | None = Field(default=None, max_length=200)+++class PublishResult(BaseModel):+ slug: str+ url: str+ run_id: uuid.UUID+ created_at: datetime+++class PublishedSummary(BaseModel):+ slug: str+ url: str+ title: str+ case_id: str+ view_count: int+ created_at: datetime+++class PublicReplay(BaseModel):+ slug: str+ title: str+ case_id: str+ snapshot: dict+ view_count: int+ created_at: datetime+++def _sanitize(value: object, limit: int = 64) -> str:+ """Inline log sanitization (CodeQL py/log-injection): strip CR/LF + clamp."""+ return str(value).replace("\r", "").replace("\n", " ")[:limit]+++async def _load_run_and_events(+ db: TenantDBSession, run_id: uuid.UUID, tenant_id: uuid.UUID+) -> tuple[InvestigationRun, list[InvestigationEvent]]:+ run = (+ await db.execute(+ select(InvestigationRun).where(+ InvestigationRun.id == run_id,+ InvestigationRun.tenant_id == tenant_id,+ )+ )+ ).scalar_one_or_none()+ if run is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Investigation run not found")+ events = list(+ (+ await db.execute(+ select(InvestigationEvent)+ .where(InvestigationEvent.run_id == run_id)+ .order_by(InvestigationEvent.seq.asc())+ .limit(10000)+ )+ )+ .scalars()+ .all()+ )+ return run, events+++def _run_to_dict(run: InvestigationRun) -> dict:+ return {+ "case_id": run.case_id,+ "alert_summary": run.alert_summary,+ "raw_alert": run.raw_alert,+ "model_used": run.model_used,+ "status": run.status,+ "started_at": run.started_at,+ "completed_at": run.completed_at,+ }+++def _events_to_dicts(events: list[InvestigationEvent]) -> list[dict]:+ return [+ {+ "seq": e.seq,+ "kind": e.kind,+ "agent": e.agent,+ "summary": e.summary,+ "payload": e.payload,+ "ts": e.ts,+ "duration_ms": e.duration_ms,+ }+ for e in events+ ]++[email protected]("/{run_id}/publish/preview", response_model=PublishPreview)+async def preview_publish(+ run_id: uuid.UUID,+ current_user: Annotated[AuthUser, Depends(require_permission("cases:read"))],+ db: TenantDBSession,+) -> PublishPreview:+ """Build the redacted snapshot + alias map for the pre-publish review."""+ run, events = await _load_run_and_events(db, run_id, current_user.tenant_id)+ result = build_redacted_snapshot(run=_run_to_dict(run), events=_events_to_dicts(events))+ return PublishPreview(+ run_id=run_id,+ title=result.title,+ snapshot=result.snapshot,+ alias_map=result.alias_map,+ )+++async def _unique_slug(db: DBSession) -> str:+ """Mint a short, URL-safe slug, retrying on the (rare) collision."""+ for _ in range(6):+ slug = secrets.token_urlsafe(8).replace("-", "").replace("_", "")[:12].lower()+ if len(slug) < 8:+ continue+ exists = (await db.execute(select(PublishedReplay.id).where(PublishedReplay.slug == slug))).first()+ if not exists:+ return slug+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Could not allocate a unique slug; retry.")++[email protected]("/{run_id}/publish", response_model=PublishResult, status_code=status.HTTP_201_CREATED)+async def publish_replay(+ run_id: uuid.UUID,+ body: PublishRequest,+ current_user: Annotated[AuthUser, Depends(require_permission("cases:write"))],+ db: TenantDBSession,+) -> PublishResult:+ """Persist an immutable, redacted public snapshot and return its share URL."""+ if not body.confirm:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Set confirm=true to publish. Review the /publish/preview diff first.",+ )+ run, events = await _load_run_and_events(db, run_id, current_user.tenant_id)+ result = build_redacted_snapshot(run=_run_to_dict(run), events=_events_to_dicts(events))+ title = (body.title_override or result.title)[:200]++ slug = await _unique_slug(db)+ row = PublishedReplay(+ slug=slug,+ run_id=run_id,+ tenant_id=current_user.tenant_id,+ case_id=run.case_id,+ title=title,+ snapshot=result.snapshot,+ published_by=current_user.id,+ )+ db.add(row)+ await db.commit()+ await db.refresh(row)+ logger.info("replay.published", slug=_sanitize(slug), run_id=_sanitize(run_id), tenant=_sanitize(current_user.tenant_id))+ return PublishResult(slug=slug, url=f"{_PUBLIC_BASE}/{slug}", run_id=run_id, created_at=row.created_at)++[email protected]("/{run_id}/published", response_model=list[PublishedSummary])+async def list_published(+ run_id: uuid.UUID,+ current_user: Annotated[AuthUser, Depends(require_permission("cases:read"))],+ db: TenantDBSession,+) -> list[PublishedSummary]:+ rows = (+ (+ await db.execute(+ select(PublishedReplay)+ .where(PublishedReplay.run_id == run_id, PublishedReplay.tenant_id == current_user.tenant_id)+ .order_by(PublishedReplay.created_at.desc())+ )+ )+ .scalars()+ .all()+ )+ return [+ PublishedSummary(+ slug=r.slug,+ url=f"{_PUBLIC_BASE}/{r.slug}",+ title=r.title,+ case_id=r.case_id,+ view_count=r.view_count,+ created_at=r.created_at,+ )+ for r in rows+ ]++[email protected]("/publish/{slug}", status_code=status.HTTP_204_NO_CONTENT)+async def unpublish_replay(+ slug: str,+ current_user: Annotated[AuthUser, Depends(require_permission("cases:write"))],+ db: TenantDBSession,+) -> None:+ row = (+ await db.execute(+ select(PublishedReplay).where(+ PublishedReplay.slug == slug,+ PublishedReplay.tenant_id == current_user.tenant_id,+ )+ )+ ).scalar_one_or_none()+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Published replay not found")+ await db.delete(row)+ await db.commit()+++@public_router.get("/{slug}", response_model=PublicReplay)+async def get_public_replay(slug: str, db: DBSession) -> PublicReplay:+ """Public, unauthenticated read of a redacted replay snapshot.++ Uses a non-RLS session because ``published_replays`` is intentionally+ public-by-design (post-redaction, non-identifying). Increments a+ best-effort view counter (the only mutation the immutability trigger+ permits).+ """+ row = (await db.execute(select(PublishedReplay).where(PublishedReplay.slug == slug))).scalar_one_or_none()+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Replay not found")++ # Best-effort view bump; never fail the read on a counter error.+ try:+ await db.execute(+ update(PublishedReplay).where(PublishedReplay.id == row.id).values(view_count=PublishedReplay.view_count + 1)+ )+ await db.commit()+ except Exception: # pragma: no cover - counter is best-effort only+ await db.rollback()++ return PublicReplay(+ slug=row.slug,+ title=row.title,+ case_id=row.case_id,+ snapshot=row.snapshot,+ view_count=row.view_count + 1,+ created_at=row.created_at,+ )diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex e3c30ec1a..21725aec9 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -61,6 +61,7 @@ from app.api.v1.endpoints import (rbac,realtime,remediation,+ replay,reports,rule_tuning,saved_hunts,@@ -130,6 +131,14 @@ api_router.include_router(health.router)api_router.include_router(insights.router)api_router.include_router(sla.router)api_router.include_router(investigations.router)++# Public investigation-replay publishing — v8 W3.+# /ledger/{run_id}/publish[/preview] (auth) turns a tenant-private ledger into+# an immutable, redacted snapshot; /r/{slug} serves it publicly (no auth,+# non-RLS by design — the data is post-redaction and non-identifying) for the+# tryaisoc.com/r/<slug> replay page. Only the redacted snapshot is stored.+api_router.include_router(replay.router)+api_router.include_router(replay.public_router)# Effective permissions resolver (T3.2 — v8.0 parallel team plan).# Resolves "what can principal X actually do?" across AWS / Azure / GCP /# Okta / Google Workspace and caches the result as :EFFECTIVE_PERMISSIONdiff --git a/services/api/app/models/__init__.py b/services/api/app/models/__init__.pyindex 81c972087..de8ee2d5d 100644--- a/services/api/app/models/__init__.py+++ b/services/api/app/models/__init__.py@@ -29,6 +29,7 @@ from app.models.mssp import ()from app.models.oauth import OAuthAppCredential, OAuthStatefrom app.models.posture import PostureDriftEvent, PostureFinding, PostureScanRun+from app.models.published_replay import PublishedReplayfrom app.models.remediation import RemediationGateLog, RemediationMaturity, RemediationWhitelistfrom app.models.report import ReportArtefact, ReportTemplatefrom app.models.responder import (@@ -85,6 +86,7 @@ __all__ = ["PostureDriftEvent","PostureFinding","PostureScanRun",+ "PublishedReplay","RemediationGateLog","RemediationMaturity","RemediationWhitelist",diff --git a/services/api/app/models/published_replay.py b/services/api/app/models/published_replay.pynew file mode 100644index 000000000..490325e75--- /dev/null+++ b/services/api/app/models/published_replay.py@@ -0,0 +1,62 @@+"""Published (public) investigation-replay snapshots — v8 W3.++A published replay is an **immutable, redacted** snapshot of an investigation+ledger, served without authentication at ``tryaisoc.com/r/<slug>`` so analysts+can share how the agent reasoned through a case.++Design decisions:++* **Immutable.** Once published, the snapshot never changes. A re-publish mints+ a new slug. The SQL migration adds an UPDATE-blocking trigger; the app layer+ never issues UPDATEs (view-count is a separate best-effort increment column+ that the trigger explicitly allows).+* **Redacted at publish time.** Only the already-redacted ``snapshot`` JSON is+ stored — the original entity values and the alias→original map are *never*+ persisted. Redaction runs in ``app/services/replay_redaction.py`` using the+ vendored :class:`Pseudonymizer`, and the publisher reviews the alias map in a+ pre-publish diff before confirming.+* **Public-by-design, so no RLS.** Unlike every other tenant table, this one is+ intentionally readable without a tenant context (that's the whole point). The+ data it holds is post-redaction and non-identifying. Writes are still scoped+ to the publishing tenant in the application layer, and ``tenant_id`` is+ retained purely for the publisher's own audit / unpublish path.+"""++from __future__ import annotations++import uuid+from datetime import datetime++from sqlalchemy import DateTime, ForeignKey, Integer, String, Text, func+from sqlalchemy.dialects.postgresql import JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base+++class PublishedReplay(Base):+ """One row per published, redacted investigation replay."""++ __tablename__ = "published_replays"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ # URL-safe short slug served at /r/<slug>. Unique across all tenants.+ slug: Mapped[str] = mapped_column(String(32), nullable=False, unique=True, index=True)+ # The source run. No FK cascade delete — a published replay is a durable+ # artifact that must survive the run being pruned.+ run_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False, index=True)+ tenant_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("tenants.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )+ case_id: Mapped[str] = mapped_column(String(200), nullable=False)+ # Redacted, display-safe title (e.g. "Ransomware on HOST_1").+ title: Mapped[str] = mapped_column(Text, nullable=False)+ # The immutable, fully-redacted replay snapshot (verdict, techniques,+ # elapsed, step count, evidence cards, attack-graph nodes/edges).+ snapshot: Mapped[dict] = mapped_column(JSONB, nullable=False)+ published_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True))+ view_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())diff --git a/services/api/app/scripts/seed_demo.py b/services/api/app/scripts/seed_demo.pyindex 42cbac6e1..084c54b18 100644--- a/services/api/app/scripts/seed_demo.py+++ b/services/api/app/scripts/seed_demo.py@@ -54,7 +54,9 @@ from app.models.investigation import (InvestigationEvent,InvestigationRun,)+from app.models.published_replay import PublishedReplayfrom app.models.tenant import Tenant, User+from app.services.replay_redaction import build_redacted_snapshot# Deterministic random for reproducible seeds._rng = random.Random(42)@@ -2226,6 +2228,72 @@ async def _seed_in_flight_investigation(session, tenant: Tenant) -> int:session.add_all(artifacts)await session.flush()+ await _seed_published_replay(session, tenant, run, events)++ return 1+++# Stable slug for the canonical public demo replay (linked from the README /+# marketing site). Re-seeding is idempotent on this slug.+CANONICAL_REPLAY_SLUG = "demo-lockbit"+++async def _seed_published_replay(+ session,+ tenant: Tenant,+ run: InvestigationRun,+ events: list[InvestigationEvent],+) -> int:+ """Publish INC-RT-001 as the canonical public replay at /r/demo-lockbit.++ Uses the same redaction pipeline as the live publish flow so the demo+ snapshot is byte-for-byte what an operator would get. Idempotent on the+ fixed slug.+ """+ existing = await session.execute(select(PublishedReplay).where(PublishedReplay.slug == CANONICAL_REPLAY_SLUG).limit(1))+ if existing.scalar_one_or_none() is not None:+ return 0++ last_ts = events[-1].ts if events else run.started_at+ run_dict = {+ "case_id": run.case_id,+ "alert_summary": run.alert_summary,+ "raw_alert": run.raw_alert,+ "model_used": run.model_used,+ "status": run.status,+ "started_at": run.started_at,+ "completed_at": last_ts,+ }+ event_dicts = [+ {+ "seq": e.seq,+ "kind": e.kind,+ "agent": e.agent,+ "summary": e.summary,+ "payload": e.payload,+ "ts": e.ts,+ "duration_ms": e.duration_ms,+ }+ for e in events+ ]+ result = build_redacted_snapshot(run=run_dict, events=event_dicts)+ snapshot = result.snapshot+ # The seeded run is still "running", but the decision step establishes a+ # confirmed LockBit incident at 0.96 confidence — reflect that in the+ # public verdict stamp (this is clearly-labelled demo data).+ snapshot["verdict"] = "confirmed_incident"++ session.add(+ PublishedReplay(+ slug=CANONICAL_REPLAY_SLUG,+ run_id=run.id,+ tenant_id=tenant.id,+ case_id=run.case_id,+ title=result.title or "Ransomware investigation",+ snapshot=snapshot,+ )+ )+ await session.flush()return 1diff --git a/services/api/app/services/replay_redaction.py b/services/api/app/services/replay_redaction.pynew file mode 100644index 000000000..909e415de--- /dev/null+++ b/services/api/app/services/replay_redaction.py@@ -0,0 +1,187 @@+"""Build a redacted, immutable public snapshot from an investigation ledger.++Powers the v8 W3 public-replay publish flow. Given a run + its events, this+produces:++* a **redacted snapshot** (safe to serve at ``/r/<slug>``) — the animated+ playback the web page renders: verdict stamp, MITRE techniques, elapsed time,+ step count, an ordered step list, evidence cards, and a small attack graph;+* an **alias map** (``{token: original}``) so the publisher can review exactly+ what will be hidden in a pre-publish diff before confirming.++Only the redacted snapshot is ever persisted — the alias map stays in the+preview response and is never stored. Redaction reuses the vendored+:class:`Pseudonymizer` (internal IPs / emails / paths / secrets / internal+hostnames / usernames → opaque tokens); public IOCs (external domains/IPs) are+intentionally preserved because they are the shareable threat-intelligence+value of a replay, not customer PII.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++from app._vendor.redactor import Pseudonymizer, RedactionConfig++# MITRE tactic ordering for laying out a simple left-to-right kill-chain graph.+_TACTIC_ORDER = [+ "reconnaissance",+ "resource-development",+ "initial-access",+ "execution",+ "persistence",+ "privilege-escalation",+ "defense-evasion",+ "credential-access",+ "discovery",+ "lateral-movement",+ "collection",+ "command-and-control",+ "exfiltration",+ "impact",+]+++@dataclass+class ReplaySnapshot:+ """The redacted, display-safe snapshot + the review-only alias map."""++ snapshot: dict[str, Any]+ alias_map: dict[str, str] = field(default_factory=dict)+ title: str = ""+++def _collect_techniques(raw_alert: dict | None, events: list[dict]) -> list[str]:+ seen: list[str] = []++ def add(values: Any) -> None:+ if isinstance(values, str):+ values = [values]+ if isinstance(values, (list, tuple)):+ for v in values:+ tid = str(v).upper().strip()+ if tid and tid.startswith("T") and tid not in seen:+ seen.append(tid)++ if raw_alert:+ add(raw_alert.get("mitre_techniques") or raw_alert.get("techniques"))+ for ev in events:+ payload = ev.get("payload") or {}+ add(payload.get("techniques") or payload.get("mitre") or payload.get("technique"))+ return seen+++def _build_attack_graph(techniques: list[str], case_title: str) -> dict[str, Any]:+ """A minimal, deterministic attack graph: an alert node feeding a+ technique chain. Enough for the replay page's "graph growing" animation+ without exposing any entity data (techniques are public taxonomy)."""+ nodes: list[dict[str, Any]] = [{"id": "alert", "label": "Alert", "kind": "alert"}]+ edges: list[dict[str, Any]] = []+ prev = "alert"+ for i, tid in enumerate(techniques[:10]):+ node_id = f"technique-{i}"+ nodes.append({"id": node_id, "label": tid, "kind": "technique"})+ edges.append({"source": prev, "target": node_id, "label": "leads_to"})+ prev = node_id+ return {"nodes": nodes, "edges": edges}+++def build_redacted_snapshot(+ *,+ run: dict[str, Any],+ events: list[dict[str, Any]],+ config: RedactionConfig | None = None,+) -> ReplaySnapshot:+ """Assemble and redact a public replay snapshot.++ ``run`` keys used: ``case_id``, ``alert_summary``, ``raw_alert``,+ ``model_used``, ``status``, ``started_at``, ``completed_at``.+ ``events`` are ledger event dicts with ``seq``/``kind``/``agent``/+ ``summary``/``payload``/``ts``/``duration_ms``.+ """+ pseudo = Pseudonymizer(config=config or RedactionConfig())++ def r(text: Any) -> str:+ return pseudo.redact(str(text)) if text is not None else ""++ raw_alert = run.get("raw_alert") or {}+ techniques = _collect_techniques(raw_alert, events)++ # Counts + timing.+ tool_calls = sum(1 for e in events if e.get("kind") == "tool_call")+ evidence_events = [e for e in events if e.get("kind") == "evidence_cited"]+ llm_calls = sum(1 for e in events if e.get("kind") in ("llm_call", "llm_response"))++ started = run.get("started_at")+ completed = run.get("completed_at")+ elapsed_ms = 0+ if started and completed:+ try:+ elapsed_ms = int((completed - started).total_seconds() * 1000)+ except (TypeError, AttributeError):+ elapsed_ms = 0++ # Verdict: prefer a structured verdict in a report/decision event.+ verdict = ""+ for ev in reversed(events):+ payload = ev.get("payload") or {}+ v = payload.get("verdict")+ if v:+ verdict = str(v)+ break+ if not verdict:+ verdict = str(run.get("status") or "completed")++ redacted_title = r(run.get("alert_summary") or run.get("case_id") or "Investigation")++ steps = []+ for ev in events:+ payload = ev.get("payload") or {}+ decision = None+ reason = payload.get("reason") or payload.get("rationale")+ tool = payload.get("tool") or payload.get("tool_name")+ if reason or tool:+ decision = {+ "reason": r(reason) if reason else None,+ "tool": pseudo.redact(str(tool)) if tool else None,+ "confidence": payload.get("confidence"),+ }+ steps.append(+ {+ "seq": ev.get("seq"),+ "kind": ev.get("kind"),+ "agent": ev.get("agent"),+ "summary": r(ev.get("summary")),+ "durationMs": ev.get("duration_ms") or 0,+ "decision": decision,+ }+ )++ evidence_cards = [+ {+ "seq": ev.get("seq"),+ "summary": r(ev.get("summary")),+ "source": (ev.get("payload") or {}).get("source", "evidence"),+ }+ for ev in evidence_events+ ]++ snapshot = {+ "schemaVersion": 1,+ "caseId": r(run.get("case_id")),+ "title": redacted_title,+ "verdict": verdict,+ "model": run.get("model_used") or "deterministic",+ "elapsedMs": elapsed_ms,+ "stepCount": len(events),+ "toolCallCount": tool_calls,+ "llmCallCount": llm_calls,+ "evidenceSourceCount": len(evidence_events),+ "techniques": techniques,+ "steps": steps,+ "evidenceCards": evidence_cards,+ "attackGraph": _build_attack_graph(techniques, redacted_title),+ }++ return ReplaySnapshot(snapshot=snapshot, alias_map=pseudo.mapping, title=redacted_title)diff --git a/services/api/migrations/045_published_replays.sql b/services/api/migrations/045_published_replays.sqlnew file mode 100644index 000000000..059d590d9--- /dev/null+++ b/services/api/migrations/045_published_replays.sql@@ -0,0 +1,44 @@+-- 045_published_replays.sql+-- v8 W3 — public, immutable, redacted investigation-replay snapshots served at+-- tryaisoc.com/r/<slug>.+--+-- Intentionally NOT under Row-Level Security: this table holds post-redaction,+-- non-identifying data and is meant to be read without a tenant context (the+-- public share link). Writes are scoped to the publishing tenant in the+-- application layer; tenant_id is kept for the publisher's audit / unpublish.++CREATE TABLE IF NOT EXISTS published_replays (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ slug VARCHAR(32) NOT NULL UNIQUE,+ run_id UUID NOT NULL,+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ case_id VARCHAR(200) NOT NULL,+ title TEXT NOT NULL,+ snapshot JSONB NOT NULL,+ published_by UUID,+ view_count INTEGER NOT NULL DEFAULT 0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_published_replays_slug ON published_replays (slug);+CREATE INDEX IF NOT EXISTS idx_published_replays_tenant ON published_replays (tenant_id);+CREATE INDEX IF NOT EXISTS idx_published_replays_run ON published_replays (run_id);++-- Immutability: block UPDATEs to every column except the best-effort+-- view_count bump, so a published snapshot can never be silently altered.+CREATE OR REPLACE FUNCTION published_replays_block_update() RETURNS TRIGGER AS $$+BEGIN+ IF (NEW.slug, NEW.run_id, NEW.tenant_id, NEW.case_id, NEW.title, NEW.snapshot, NEW.published_by, NEW.created_at)+ IS DISTINCT FROM+ (OLD.slug, OLD.run_id, OLD.tenant_id, OLD.case_id, OLD.title, OLD.snapshot, OLD.published_by, OLD.created_at)+ THEN+ RAISE EXCEPTION 'published_replays rows are immutable (only view_count may change)';+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++DROP TRIGGER IF EXISTS trg_published_replays_immutable ON published_replays;+CREATE TRIGGER trg_published_replays_immutable+ BEFORE UPDATE ON published_replays+ FOR EACH ROW EXECUTE FUNCTION published_replays_block_update();diff --git a/services/api/tests/test_replay_publish.py b/services/api/tests/test_replay_publish.pynew file mode 100644index 000000000..556e1da47--- /dev/null+++ b/services/api/tests/test_replay_publish.py@@ -0,0 +1,109 @@+"""Tests for the v8 W3 public-replay publish flow.++Focus on the two things that carry the correctness + safety contract without a+live DB: the redaction snapshot builder (no raw customer PII may survive) and+the route registration (public + authed surfaces are wired).+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++import pytest++from app.services.replay_redaction import build_redacted_snapshot+++def _sample_run_events() -> tuple[dict, list[dict]]:+ started = datetime(2026, 1, 1, 12, 0, 0, tzinfo=UTC)+ run = {+ "case_id": "INC-RT-001",+ "alert_summary": "Ransomware on WIN-FIN-DB01.corp for user j.doe ([email protected])",+ "raw_alert": {"mitre_techniques": ["T1486", "T1490"], "src_ip": "10.0.0.5"},+ "model_used": "gpt-4o-mini",+ "status": "completed",+ "started_at": started,+ "completed_at": started + timedelta(seconds=94),+ }+ events = [+ {+ "seq": 0,+ "kind": "recon",+ "agent": "TriageAgent",+ "summary": "Investigating host WIN-FIN-DB01.corp, internal IP 10.0.0.5",+ "payload": {"reason": "host WIN-FIN-DB01.corp shows mass encryption", "confidence": 0.9},+ "ts": started,+ "duration_ms": 1200,+ },+ {+ "seq": 1,+ "kind": "tool_call",+ "agent": "HuntAgent",+ "summary": "Queried EDR for user [email protected] from C:\\Users\\jdoe\\ransom.exe",+ "payload": {"tool": "edr_search", "techniques": ["T1021.002"]},+ "ts": started + timedelta(seconds=10),+ "duration_ms": 800,+ },+ {+ "seq": 2,+ "kind": "evidence_cited",+ "agent": "HuntAgent",+ "summary": "Beacon to malware-c2.example.com confirmed",+ "payload": {"source": "threat-intel", "verdict": "true_positive"},+ "ts": started + timedelta(seconds=40),+ "duration_ms": 100,+ },+ ]+ return run, events+++def test_redaction_hides_customer_pii_but_keeps_public_iocs() -> None:+ run, events = _sample_run_events()+ result = build_redacted_snapshot(run=run, events=events)+ serialized = str(result.snapshot)++ # Customer PII must be gone from the stored snapshot.+ assert "[email protected]" not in serialized+ assert "WIN-FIN-DB01.corp" not in serialized+ assert "10.0.0.5" not in serialized+ assert "C:\\Users\\jdoe" not in serialized++ # Aliases must appear instead, and the alias map (preview-only) must carry+ # the originals so the publisher can review the diff.+ assert any(tok.startswith(("HOST_", "USER_", "IP_", "EMAIL_", "PATH_")) for tok in result.alias_map)+ assert "WIN-FIN-DB01.corp" in result.alias_map.values()++ # Public IOCs (external domain) are intentionally preserved — they are the+ # shareable threat-intel value, not customer PII.+ assert "malware-c2.example.com" in serialized+++def test_snapshot_shape_and_counts() -> None:+ run, events = _sample_run_events()+ result = build_redacted_snapshot(run=run, events=events)+ snap = result.snapshot++ assert snap["schemaVersion"] == 1+ assert snap["stepCount"] == 3+ assert snap["toolCallCount"] == 1+ assert snap["evidenceSourceCount"] == 1+ assert snap["elapsedMs"] == 94_000+ assert snap["verdict"] == "true_positive"+ # Techniques collected from raw_alert + event payloads, de-duplicated.+ assert "T1486" in snap["techniques"]+ assert "T1021.002" in snap["techniques"]+ # Attack graph seeds an alert node feeding a technique chain.+ assert snap["attackGraph"]["nodes"][0]["id"] == "alert"+ assert len(snap["attackGraph"]["edges"]) >= 1+++def test_routes_registered() -> None:+ try:+ from app.api.v1.router import api_router+ except ModuleNotFoundError as exc: # pragma: no cover - local envs missing runtime deps+ pytest.skip(f"API runtime dependency unavailable in this environment: {exc.name}")++ paths = {getattr(r, "path", "") for r in api_router.routes}+ assert "/api/v1/ledger/{run_id}/publish" in paths+ assert "/api/v1/ledger/{run_id}/publish/preview" in paths+ assert "/api/v1/r/{slug}" in paths