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(tools): four free browser tools + SEO landing pages (v8 W2)
Beenu Arorabe276af17947
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex be26af0fb..d875faec9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **v8 W2 — standalone free web tools (search-indexed acquisition).** Four+ login-free, open-source tools under `apps/web/src/app/(tools)/tools/`, each+ with its own landing page, JSON-LD, OG metadata, and an "open source, part of+ AiSOC" backlink; **everything runs in the browser — user rules never touch the+ server** (the deterministic path is pure client-side). (1) **Detection+ Translator** (`/tools/translate`): paste any rule, get Sigma / SPL / KQL /+ ES\|QL / YARA-L2 / UDM at once, with per-dialect copy buttons and a stable+ `?s=` permalink. (2) **NL → Detection** (`/tools/nl2sigma`): plain English →+ a Sigma scaffold plus the three SIEM dialects, via a deterministic+ artifact-extraction generator (honest about being a starting point). (3)+ **ATT&CK Coverage Grader** (`/tools/coverage`): paste Sigma rules / technique+ IDs → an A–F grade, a per-tactic heatmap, the top-10 highest-prevalence+ uncovered techniques, and a downloadable shareable grade card (via+ `@aisoc/report-card`). (4) **Alert Noise Calculator** (`/tools/noise`):+ project FP suppression + analyst hours/cost saved from the published+ deterministic-tier suppression rate (methodology linked; labelled as a+ substrate figure, not a live-LLM claim). SEO plumbing: 30 programmatic+ format-pair landing pages (`/tools/translate/spl-to-kql`, …) generated from a+ matrix via `generateStaticParams`, plus sitemap entries for all tool routes.+ Logic (`apps/web/src/lib/tools/`) is pure and unit-tested (13 tests: translate+ field-map + permalink round-trip, coverage extraction/grading/top-uncovered,+ noise projection/clamping, NL→Sigma scaffolding). Production build verified+ (tools static, pair pages SSG'd).- **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`diff --git a/README.md b/README.mdindex ea9d23d42..5d295ba58 100644--- a/README.md+++ b/README.md@@ -181,7 +181,7 @@ A handful of headline capabilities — the rest are catalogued in [`apps/docs/do- **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).+- **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). Plus free, login-free [browser tools](https://tryaisoc.com/tools): a Sigma/SPL/KQL/ES|QL rule translator, an ATT&CK coverage grader, NL→Sigma, and a noise calculator.- **Public weekly benchmark scoreboard** — the same harness that gates PRs; the deterministic-tier row is CI-gated for freshness on every PR, and the funded weekly job appends live-LLM rows. [`apps/docs/docs/benchmark-scoreboard.mdx`](apps/docs/docs/benchmark-scoreboard.mdx).---diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.tsindex c4b7818fb..9edff1c7c 100644--- a/apps/web/next-env.d.ts+++ b/apps/web/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/dev/types/routes.d.ts";+import "./.next/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/apps/web/src/app/(tools)/layout.tsx b/apps/web/src/app/(tools)/layout.tsxnew file mode 100644index 000000000..2d10c82e5--- /dev/null+++ b/apps/web/src/app/(tools)/layout.tsx@@ -0,0 +1,53 @@+import type { ReactNode } from "react";++/**+ * Shell for the free standalone tools at /tools/*.+ *+ * Each tool is search-indexable, works with zero login, and carries the+ * "part of AiSOC" backlink the growth loop depends on. Deliberately light —+ * no app chrome, no auth.+ */+export default function ToolsLayout({ children }: { children: ReactNode }) {+ return (+ <div style={{ background: "#0b1020", minHeight: "100vh", color: "#e6e9f5" }}>+ <header+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ padding: "16px 24px",+ borderBottom: "1px solid #232b4d",+ }}+ >+ <a href="/tools" style={{ color: "#e6e9f5", textDecoration: "none", fontWeight: 800, letterSpacing: 0.5 }}>+ AiSOC <span style={{ color: "#8b93b7", fontWeight: 500 }}>· free tools</span>+ </a>+ <nav style={{ display: "flex", gap: 18, fontSize: 14 }}>+ <a href="/tools/translate" style={{ color: "#c4cae0", textDecoration: "none" }}>+ Translate+ </a>+ <a href="/tools/nl2sigma" style={{ color: "#c4cae0", textDecoration: "none" }}>+ NL→Sigma+ </a>+ <a href="/tools/coverage" style={{ color: "#c4cae0", textDecoration: "none" }}>+ Coverage+ </a>+ <a href="/tools/noise" style={{ color: "#c4cae0", textDecoration: "none" }}>+ Noise+ </a>+ <a href="https://github.com/beenuar/AiSOC" style={{ color: "#7b2bbe", textDecoration: "none", fontWeight: 700 }}>+ GitHub ★+ </a>+ </nav>+ </header>+ <div style={{ maxWidth: 980, margin: "0 auto", padding: "40px 24px 64px" }}>{children}</div>+ <footer style={{ borderTop: "1px solid #232b4d", padding: "24px", textAlign: "center", color: "#6b7394", fontSize: 13 }}>+ Free & open source · part of{" "}+ <a href="https://github.com/beenuar/AiSOC" style={{ color: "#8b93b7" }}>+ AiSOC+ </a>+ , the self-hostable AI SOC. Everything on this page runs in your browser — your rules never touch our servers.+ </footer>+ </div>+ );+}diff --git a/apps/web/src/app/(tools)/tools/nl2sigma/Nl2SigmaTool.tsx b/apps/web/src/app/(tools)/tools/nl2sigma/Nl2SigmaTool.tsxnew file mode 100644index 000000000..2e15fd748--- /dev/null+++ b/apps/web/src/app/(tools)/tools/nl2sigma/Nl2SigmaTool.tsx@@ -0,0 +1,83 @@+"use client";++import { useMemo, useState } from "react";++import { nlToSigma } from "../../../../lib/tools/nl2sigma";+import { translateRule } from "../../../../lib/tools/translate";++const SAMPLE = "Detect powershell.exe launching with a download cradle (DownloadString or IEX), MITRE T1059.001";++export function Nl2SigmaTool() {+ const [text, setText] = useState(SAMPLE);+ const [severity, setSeverity] = useState("medium");+ const [copied, setCopied] = useState<string | null>(null);++ const result = useMemo(() => nlToSigma(text, severity), [text, severity]);+ const dialects = useMemo(() => translateRule(result.sigma, "sigma", ["spl", "kql", "esql"]), [result.sigma]);++ const copy = async (key: string, value: string) => {+ try {+ await navigator.clipboard.writeText(value);+ setCopied(key);+ setTimeout(() => setCopied(null), 1500);+ } catch {+ /* clipboard blocked */+ }+ };++ return (+ <div style={{ display: "grid", gap: 18 }}>+ <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>+ <label style={{ color: "#8b93b7", fontSize: 14 }}>Severity</label>+ <select value={severity} onChange={(e) => setSeverity(e.target.value)} style={select}>+ {["informational", "low", "medium", "high", "critical"].map((s) => (+ <option key={s} value={s}>+ {s}+ </option>+ ))}+ </select>+ </div>+ <textarea+ value={text}+ onChange={(e) => setText(e.target.value)}+ rows={4}+ placeholder="Describe the behaviour to detect, in plain English…"+ style={textarea}+ />++ <Block title="Sigma" body={result.sigma} copied={copied === "sigma"} onCopy={() => copy("sigma", result.sigma)} />+ {dialects.results.map((r) => (+ <Block key={r.format} title={r.label} body={r.rule} copied={copied === r.format} onCopy={() => copy(r.format, r.rule)} />+ ))}++ <p style={{ color: "#fbbf24", fontSize: 13, margin: 0 }}>⚠ {result.note}</p>+ </div>+ );+}++function Block({ title, body, copied, onCopy }: { title: string; body: string; copied: boolean; onCopy: () => void }) {+ return (+ <div style={{ background: "#131a33", border: "1px solid #232b4d", borderRadius: 10, overflow: "hidden" }}>+ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 12px", borderBottom: "1px solid #232b4d" }}>+ <strong style={{ color: "#7b2bbe", fontSize: 14 }}>{title}</strong>+ <button onClick={onCopy} style={btn}>+ {copied ? "Copied ✓" : "Copy"}+ </button>+ </div>+ <pre style={{ margin: 0, padding: 14, color: "#c4cae0", fontSize: 13, overflowX: "auto", whiteSpace: "pre-wrap" }}>{body}</pre>+ </div>+ );+}++const btn: React.CSSProperties = { background: "#232b4d", color: "#e6e9f5", border: "none", borderRadius: 6, padding: "6px 12px", fontSize: 13, cursor: "pointer" };+const select: React.CSSProperties = { background: "#131a33", color: "#e6e9f5", border: "1px solid #232b4d", borderRadius: 8, padding: "8px 10px" };+const textarea: React.CSSProperties = {+ width: "100%",+ background: "#0b1020",+ color: "#c4cae0",+ border: "1px solid #232b4d",+ borderRadius: 10,+ padding: 14,+ fontSize: 14,+ resize: "vertical",+};diff --git a/apps/web/src/app/(tools)/tools/nl2sigma/page.tsx b/apps/web/src/app/(tools)/tools/nl2sigma/page.tsxnew file mode 100644index 000000000..3cd478dfc--- /dev/null+++ b/apps/web/src/app/(tools)/tools/nl2sigma/page.tsx@@ -0,0 +1,42 @@+import type { Metadata } from "next";++import { getPublicSiteUrl } from "../../../../lib/site";+import { Nl2SigmaTool } from "./Nl2SigmaTool";++export const metadata: Metadata = {+ title: "Natural language to Sigma rule generator | AiSOC",+ description:+ "Describe a threat in plain English and get a Sigma detection rule plus Splunk SPL, Microsoft Sentinel KQL, and Elastic ES|QL equivalents. Free, in-browser, open source.",+ alternates: { canonical: `${getPublicSiteUrl()}/tools/nl2sigma` },+ openGraph: {+ title: "Natural language to Sigma rule generator | AiSOC",+ description: "Plain English → Sigma + SPL + KQL + ES|QL. Free & open source.",+ url: `${getPublicSiteUrl()}/tools/nl2sigma`,+ },+};++const JSON_LD = {+ "@context": "https://schema.org",+ "@type": "SoftwareApplication",+ name: "AiSOC Natural Language to Sigma",+ applicationCategory: "SecurityApplication",+ operatingSystem: "Web",+ offers: { "@type": "Offer", price: "0", priceCurrency: "USD" },+ url: `${getPublicSiteUrl()}/tools/nl2sigma`,+};++export default function Nl2SigmaPage() {+ return (+ <main>+ <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(JSON_LD) }} />+ <h1 style={{ fontSize: 30, fontWeight: 800, margin: 0 }}>Plain English → Sigma</h1>+ <p style={{ color: "#8b93b7", fontSize: 16, marginTop: 10, maxWidth: 680 }}>+ Describe the behaviour you want to detect and get a Sigma rule plus Splunk SPL, Sentinel KQL, and Elastic ES|QL. A+ deterministic scaffold generated in your browser — a starting point you refine, not a black box.+ </p>+ <div style={{ marginTop: 24 }}>+ <Nl2SigmaTool />+ </div>+ </main>+ );+}diff --git a/apps/web/src/app/(tools)/tools/noise/NoiseTool.tsx b/apps/web/src/app/(tools)/tools/noise/NoiseTool.tsxnew file mode 100644index 000000000..d577e36e5--- /dev/null+++ b/apps/web/src/app/(tools)/tools/noise/NoiseTool.tsx@@ -0,0 +1,92 @@+"use client";++import { useMemo, useState } from "react";++import { projectNoise } from "../../../../lib/tools/noise";++export function NoiseTool() {+ const [alertsPerDay, setAlertsPerDay] = useState(2000);+ const [fpRate, setFpRate] = useState(90);+ const [minutesPerAlert, setMinutesPerAlert] = useState(8);+ const [hourlyCost, setHourlyCost] = useState(75);++ const projection = useMemo(+ () =>+ projectNoise({+ alertsPerDay,+ falsePositiveRate: fpRate / 100,+ minutesPerAlert,+ analystHourlyCost: hourlyCost,+ }),+ [alertsPerDay, fpRate, minutesPerAlert, hourlyCost],+ );++ return (+ <div style={{ display: "grid", gap: 24 }}>+ <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 16 }}>+ <Field label="Alerts per day" value={alertsPerDay} onChange={setAlertsPerDay} min={0} step={100} />+ <Field label="False-positive rate (%)" value={fpRate} onChange={setFpRate} min={0} max={100} step={1} />+ <Field label="Minutes to triage one alert" value={minutesPerAlert} onChange={setMinutesPerAlert} min={1} step={1} />+ <Field label="Analyst cost ($/hour)" value={hourlyCost} onChange={setHourlyCost} min={0} step={5} />+ </div>++ <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 16 }}>+ <Stat value={`${projection.noisePercent}%`} label="of all alerts auto-suppressed" color="#22c55e" />+ <Stat value={projection.suppressedPerMonth.toLocaleString()} label="alerts suppressed / month" color="#e6e9f5" />+ <Stat value={`${projection.hoursSavedPerMonth.toLocaleString()}h`} label="analyst hours saved / month" color="#e6e9f5" />+ {projection.costSavedPerMonth !== undefined ? (+ <Stat value={`$${projection.costSavedPerMonth.toLocaleString()}`} label="cost saved / month" color="#22c55e" />+ ) : null}+ </div>++ <p style={{ color: "#6b7394", fontSize: 12, margin: 0 }}>+ Uses the AiSOC verdict engine's published deterministic-tier suppression rate (85.5%). This is a substrate+ self-consistency figure, not a claim about live-LLM accuracy — see the{" "}+ <a href="https://github.com/beenuar/AiSOC/blob/main/apps/docs/docs/benchmark.md" style={{ color: "#8b93b7" }}>+ benchmark methodology+ </a>+ . Estimates only; your mileage varies with tuning and alert mix.+ </p>+ </div>+ );+}++function Field({+ label,+ value,+ onChange,+ min,+ max,+ step,+}: {+ label: string;+ value: number;+ onChange: (v: number) => void;+ min?: number;+ max?: number;+ step?: number;+}) {+ return (+ <label style={{ display: "grid", gap: 6 }}>+ <span style={{ color: "#8b93b7", fontSize: 13 }}>{label}</span>+ <input+ type="number"+ value={value}+ min={min}+ max={max}+ step={step}+ onChange={(e) => onChange(Number(e.target.value))}+ style={{ background: "#0b1020", color: "#e6e9f5", border: "1px solid #232b4d", borderRadius: 8, padding: "10px 12px", fontSize: 15 }}+ />+ </label>+ );+}++function Stat({ value, label, color }: { value: string; label: string; color: string }) {+ return (+ <div style={{ background: "#131a33", border: "1px solid #232b4d", borderRadius: 12, padding: 20 }}>+ <div style={{ fontSize: 34, fontWeight: 800, color }}>{value}</div>+ <div style={{ color: "#8b93b7", fontSize: 13, marginTop: 4 }}>{label}</div>+ </div>+ );+}diff --git a/apps/web/src/app/(tools)/tools/noise/page.tsx b/apps/web/src/app/(tools)/tools/noise/page.tsxnew file mode 100644index 000000000..68c58f738--- /dev/null+++ b/apps/web/src/app/(tools)/tools/noise/page.tsx@@ -0,0 +1,42 @@+import type { Metadata } from "next";++import { getPublicSiteUrl } from "../../../../lib/site";+import { NoiseTool } from "./NoiseTool";++export const metadata: Metadata = {+ title: "Alert noise & analyst-hours-saved calculator | AiSOC",+ description:+ "Estimate how many false-positive alerts you could auto-suppress and how many analyst hours you'd save, based on the AiSOC verdict engine's published suppression rate. Free, in-browser.",+ alternates: { canonical: `${getPublicSiteUrl()}/tools/noise` },+ openGraph: {+ title: "Alert noise calculator | AiSOC",+ description: "Estimate FP suppression and analyst hours saved. Free & open source.",+ url: `${getPublicSiteUrl()}/tools/noise`,+ },+};++const JSON_LD = {+ "@context": "https://schema.org",+ "@type": "SoftwareApplication",+ name: "AiSOC Alert Noise Calculator",+ applicationCategory: "SecurityApplication",+ operatingSystem: "Web",+ offers: { "@type": "Offer", price: "0", priceCurrency: "USD" },+ url: `${getPublicSiteUrl()}/tools/noise`,+};++export default function NoisePage() {+ return (+ <main>+ <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(JSON_LD) }} />+ <h1 style={{ fontSize: 30, fontWeight: 800, margin: 0 }}>Alert noise calculator</h1>+ <p style={{ color: "#8b93b7", fontSize: 16, marginTop: 10, maxWidth: 680 }}>+ Enter your alert volume to project false-positive suppression and analyst hours saved, using AiSOC's published+ verdict-engine operating point. Every number is computed in your browser with the methodology linked below.+ </p>+ <div style={{ marginTop: 24 }}>+ <NoiseTool />+ </div>+ </main>+ );+}diff --git a/apps/web/src/app/(tools)/tools/page.tsx b/apps/web/src/app/(tools)/tools/page.tsxnew file mode 100644index 000000000..4109c808e--- /dev/null+++ b/apps/web/src/app/(tools)/tools/page.tsx@@ -0,0 +1,68 @@+import type { Metadata } from "next";++import { getPublicSiteUrl } from "../../../lib/site";++export const metadata: Metadata = {+ title: "Free SOC tools — detection translator, ATT&CK coverage grader, noise calculator | AiSOC",+ description:+ "Free, open-source tools for security analysts: translate detection rules across Sigma/SPL/KQL/ES|QL, grade your ATT&CK coverage, generate Sigma from plain English, and calculate alert-noise savings. Runs in your browser.",+ alternates: { canonical: `${getPublicSiteUrl()}/tools` },+};++const TOOLS = [+ {+ href: "/tools/translate",+ title: "Detection Translator",+ blurb: "Paste any rule, get Sigma / SPL / KQL / ES|QL / YARA-L2 / UDM simultaneously. Deterministic, in-browser.",+ },+ {+ href: "/tools/nl2sigma",+ title: "NL → Detection",+ blurb: "Describe a threat in plain English, get a Sigma rule plus the three major SIEM dialects.",+ },+ {+ href: "/tools/coverage",+ title: "ATT&CK Coverage Grader",+ blurb: "Paste your Sigma rules, get an ATT&CK heatmap, an A–F coverage grade, and your top uncovered techniques.",+ },+ {+ href: "/tools/noise",+ title: "Alert Noise Calculator",+ blurb: "Estimate false-positive suppression and analyst hours saved from your alert volume.",+ },+];++export default function ToolsIndex() {+ return (+ <main>+ <h1 style={{ fontSize: 34, fontWeight: 800, margin: 0 }}>Free tools for security analysts</h1>+ <p style={{ color: "#8b93b7", fontSize: 17, marginTop: 12, maxWidth: 640 }}>+ No login, no upload, no catch. Everything runs in your browser and is open source. Part of{" "}+ <a href="https://github.com/beenuar/AiSOC" style={{ color: "#c4cae0" }}>+ AiSOC+ </a>+ .+ </p>+ <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16, marginTop: 32 }}>+ {TOOLS.map((t) => (+ <a+ key={t.href}+ href={t.href}+ style={{+ display: "block",+ background: "#131a33",+ border: "1px solid #232b4d",+ borderRadius: 12,+ padding: 20,+ textDecoration: "none",+ color: "#e6e9f5",+ }}+ >+ <h2 style={{ fontSize: 19, fontWeight: 700, margin: 0 }}>{t.title}</h2>+ <p style={{ color: "#8b93b7", fontSize: 14, marginTop: 8, lineHeight: 1.5 }}>{t.blurb}</p>+ </a>+ ))}+ </div>+ </main>+ );+}diff --git a/apps/web/src/app/(tools)/tools/translate/TranslateTool.tsx b/apps/web/src/app/(tools)/tools/translate/TranslateTool.tsxnew file mode 100644index 000000000..ad43f3ab8--- /dev/null+++ b/apps/web/src/app/(tools)/tools/translate/TranslateTool.tsx@@ -0,0 +1,132 @@+"use client";++import { useEffect, useMemo, useState } from "react";++import {+ ALL_FORMATS,+ FORMAT_LABELS,+ translateRule,+ encodePermalink,+ decodePermalink,+ type DetectionFormat,+} from "../../../../lib/tools/translate";++const SAMPLE = `title: Suspicious PowerShell download cradle+logsource:+ category: process_creation+ product: windows+detection:+ selection:+ Image|endswith: '\\\\powershell.exe'+ CommandLine|contains:+ - 'DownloadString'+ - 'IEX'+ condition: selection`;++export function TranslateTool({ initialRule, initialFormat }: { initialRule?: string; initialFormat?: DetectionFormat }) {+ const [source, setSource] = useState<DetectionFormat>(initialFormat ?? "sigma");+ const [rule, setRule] = useState(initialRule ?? SAMPLE);+ const [copied, setCopied] = useState<string | null>(null);++ // Hydrate from a ?s=<permalink> on first load (client-only).+ useEffect(() => {+ if (initialRule) return;+ const params = new URLSearchParams(window.location.search);+ const s = params.get("s");+ if (s) {+ const decoded = decodePermalink(s);+ if (decoded) {+ setSource(decoded.sourceFormat);+ setRule(decoded.rule);+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const output = useMemo(() => translateRule(rule, source, ALL_FORMATS.filter((f) => f !== source)), [rule, source]);++ const permalink = useMemo(() => {+ if (typeof window === "undefined") return "";+ return `${window.location.origin}/tools/translate?s=${encodePermalink(source, rule)}`;+ }, [source, rule]);++ const copy = async (key: string, text: string) => {+ try {+ await navigator.clipboard.writeText(text);+ setCopied(key);+ setTimeout(() => setCopied(null), 1500);+ } catch {+ /* clipboard blocked; no-op */+ }+ };++ return (+ <div style={{ display: "grid", gap: 20 }}>+ <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>+ <label style={{ color: "#8b93b7", fontSize: 14 }}>Source format</label>+ <select+ value={source}+ onChange={(e) => setSource(e.target.value as DetectionFormat)}+ style={{ background: "#131a33", color: "#e6e9f5", border: "1px solid #232b4d", borderRadius: 8, padding: "8px 10px" }}+ >+ {ALL_FORMATS.map((f) => (+ <option key={f} value={f}>+ {FORMAT_LABELS[f]}+ </option>+ ))}+ </select>+ <button onClick={() => copy("permalink", permalink)} style={btn}>+ {copied === "permalink" ? "Copied link ✓" : "Copy permalink"}+ </button>+ </div>++ <textarea+ value={rule}+ onChange={(e) => setRule(e.target.value)}+ spellCheck={false}+ rows={12}+ style={{+ width: "100%",+ background: "#0b1020",+ color: "#c4cae0",+ border: "1px solid #232b4d",+ borderRadius: 10,+ padding: 14,+ fontFamily: "ui-monospace,SFMono-Regular,Menlo,monospace",+ fontSize: 13,+ resize: "vertical",+ }}+ />++ <div style={{ display: "grid", gap: 14 }}>+ {output.results.map((r) => (+ <div key={r.format} style={{ background: "#131a33", border: "1px solid #232b4d", borderRadius: 10, overflow: "hidden" }}>+ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 12px", borderBottom: "1px solid #232b4d" }}>+ <strong style={{ color: "#7b2bbe", fontSize: 14 }}>{r.label}</strong>+ <button onClick={() => copy(r.format, r.rule)} style={btn}>+ {copied === r.format ? "Copied ✓" : "Copy"}+ </button>+ </div>+ <pre style={{ margin: 0, padding: 14, color: "#c4cae0", fontSize: 13, overflowX: "auto", whiteSpace: "pre-wrap" }}>{r.rule}</pre>+ </div>+ ))}+ </div>++ {output.warnings.map((w) => (+ <p key={w} style={{ color: "#fbbf24", fontSize: 13, margin: 0 }}>+ ⚠ {w}+ </p>+ ))}+ </div>+ );+}++const btn: React.CSSProperties = {+ background: "#232b4d",+ color: "#e6e9f5",+ border: "none",+ borderRadius: 6,+ padding: "6px 12px",+ fontSize: 13,+ cursor: "pointer",+};diff --git a/apps/web/src/app/(tools)/tools/translate/[pair]/page.tsx b/apps/web/src/app/(tools)/tools/translate/[pair]/page.tsxnew file mode 100644index 000000000..c95ac03ed--- /dev/null+++ b/apps/web/src/app/(tools)/tools/translate/[pair]/page.tsx@@ -0,0 +1,94 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";++import { getPublicSiteUrl } from "../../../../../lib/site";+import { FORMAT_LABELS, ALL_FORMATS, type DetectionFormat } from "../../../../../lib/tools/translate";+import { TranslateTool } from "../TranslateTool";++// URL-slug token per format (e.g. "yaral" instead of "yara_l2").+const SLUG: Record<DetectionFormat, string> = {+ sigma: "sigma",+ spl: "spl",+ kql: "kql",+ esql: "esql",+ yara_l2: "yaral",+ udm: "udm",+};+const FROM_SLUG: Record<string, DetectionFormat> = Object.fromEntries(Object.entries(SLUG).map(([k, v]) => [v, k as DetectionFormat]));++interface PageProps {+ params: Promise<{ pair: string }>;+}++/** Parse "spl-to-kql" → { from, to }. */+function parsePair(pair: string): { from: DetectionFormat; to: DetectionFormat } | null {+ const m = pair.toLowerCase().match(/^([a-z0-9]+)-to-([a-z0-9]+)$/);+ if (!m) return null;+ const from = FROM_SLUG[m[1]!];+ const to = FROM_SLUG[m[2]!];+ if (!from || !to || from === to) return null;+ return { from, to };+}++/** Emit all 30 source→target permutations for static generation. */+export function generateStaticParams(): { pair: string }[] {+ const params: { pair: string }[] = [];+ for (const from of ALL_FORMATS) {+ for (const to of ALL_FORMATS) {+ if (from !== to) params.push({ pair: `${SLUG[from]}-to-${SLUG[to]}` });+ }+ }+ return params;+}++export async function generateMetadata({ params }: PageProps): Promise<Metadata> {+ const { pair } = await params;+ const parsed = parsePair(pair);+ if (!parsed) return { title: "Detection translator | AiSOC" };+ const fromL = FORMAT_LABELS[parsed.from];+ const toL = FORMAT_LABELS[parsed.to];+ const title = `${fromL} to ${toL} — free detection rule converter | AiSOC`;+ const description = `Convert ${fromL} detection rules to ${toL} instantly and for free, in your browser. Open source, no login. Part of AiSOC.`;+ const url = `${getPublicSiteUrl()}/tools/translate/${pair}`;+ return { title, description, alternates: { canonical: url }, openGraph: { title, description, url } };+}++export default async function PairPage({ params }: PageProps) {+ const { pair } = await params;+ const parsed = parsePair(pair);+ if (!parsed) notFound();+ const fromL = FORMAT_LABELS[parsed.from];+ const toL = FORMAT_LABELS[parsed.to];++ const jsonLd = {+ "@context": "https://schema.org",+ "@type": "HowTo",+ name: `Convert ${fromL} to ${toL}`,+ description: `Convert a ${fromL} detection rule to ${toL}.`,+ step: [+ { "@type": "HowToStep", text: `Paste your ${fromL} rule into the editor.` },+ { "@type": "HowToStep", text: `Copy the generated ${toL} equivalent.` },+ ],+ };++ return (+ <main>+ <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />+ <nav style={{ fontSize: 13, color: "#6b7394" }}>+ <a href="/tools/translate" style={{ color: "#8b93b7" }}>+ ← All formats+ </a>+ </nav>+ <h1 style={{ fontSize: 30, fontWeight: 800, margin: "12px 0 0" }}>+ Convert {fromL} to {toL}+ </h1>+ <p style={{ color: "#8b93b7", fontSize: 16, marginTop: 10, maxWidth: 680 }}>+ Free, in-browser {fromL} → {toL} detection-rule converter. Paste your {fromL} rule below; the {toL} equivalent (and every+ other dialect) is generated instantly. Deterministic, open source, no upload.+ </p>+ <div style={{ marginTop: 24 }}>+ <TranslateTool initialFormat={parsed.from} />+ </div>+ </main>+ );+}diff --git a/apps/web/src/app/(tools)/tools/translate/page.tsx b/apps/web/src/app/(tools)/tools/translate/page.tsxnew file mode 100644index 000000000..136d51e03--- /dev/null+++ b/apps/web/src/app/(tools)/tools/translate/page.tsx@@ -0,0 +1,43 @@+import type { Metadata } from "next";++import { getPublicSiteUrl } from "../../../../lib/site";+import { TranslateTool } from "./TranslateTool";++export const metadata: Metadata = {+ title: "Detection rule translator — Sigma ↔ SPL ↔ KQL ↔ ES|QL ↔ YARA-L | AiSOC",+ description:+ "Free, in-browser detection-rule translator. Paste a Sigma, Splunk SPL, Microsoft Sentinel KQL, Elastic ES|QL, or Chronicle YARA-L rule and get every other dialect at once. No login, no upload, open source.",+ alternates: { canonical: `${getPublicSiteUrl()}/tools/translate` },+ openGraph: {+ title: "Detection rule translator — Sigma ↔ SPL ↔ KQL ↔ ES|QL | AiSOC",+ description: "Translate detection rules across every major SIEM dialect, in your browser. Free & open source.",+ url: `${getPublicSiteUrl()}/tools/translate`,+ },+};++const JSON_LD = {+ "@context": "https://schema.org",+ "@type": "SoftwareApplication",+ name: "AiSOC Detection Rule Translator",+ applicationCategory: "SecurityApplication",+ operatingSystem: "Web",+ offers: { "@type": "Offer", price: "0", priceCurrency: "USD" },+ description: "Translate detection rules across Sigma, Splunk SPL, Microsoft Sentinel KQL, Elastic ES|QL, and Google Chronicle YARA-L / UDM.",+ url: `${getPublicSiteUrl()}/tools/translate`,+};++export default function TranslatePage() {+ return (+ <main>+ <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(JSON_LD) }} />+ <h1 style={{ fontSize: 30, fontWeight: 800, margin: 0 }}>Detection rule translator</h1>+ <p style={{ color: "#8b93b7", fontSize: 16, marginTop: 10, maxWidth: 680 }}>+ Paste a rule in any format and get every other dialect at once — Sigma, Splunk SPL, Microsoft Sentinel KQL, Elastic+ ES|QL, and Google Chronicle YARA-L2 / UDM. Deterministic and computed entirely in your browser.+ </p>+ <div style={{ marginTop: 24 }}>+ <TranslateTool />+ </div>+ </main>+ );+}diff --git a/apps/web/src/app/sitemap.ts b/apps/web/src/app/sitemap.tsindex 14985de3a..1e1a61622 100644--- a/apps/web/src/app/sitemap.ts+++ b/apps/web/src/app/sitemap.ts@@ -40,7 +40,32 @@ export default function sitemap(): MetadataRoute.Sitemap {"/terms",];+ // Free standalone tools (search-indexed acquisition — v8 W2). The four tool+ // hubs are medium priority; the 30 programmatic format-pair pages+ // (/tools/translate/<from>-to-<to>) are lower but each targets a distinct+ // long-tail query ("spl to kql", "sigma to esql", …).+ const toolHubs = ["/tools", "/tools/translate", "/tools/nl2sigma", "/tools/coverage", "/tools/noise"];+ const formatSlugs = ["sigma", "spl", "kql", "esql", "yaral", "udm"];+ const translatePairs: string[] = [];+ for (const from of formatSlugs) {+ for (const to of formatSlugs) {+ if (from !== to) translatePairs.push(`/tools/translate/${from}-to-${to}`);+ }+ }+return [+ ...toolHubs.map((path) => ({+ url: `${base}${path}`,+ lastModified: now,+ changeFrequency: "weekly" as const,+ priority: 0.7,+ })),+ ...translatePairs.map((path) => ({+ url: `${base}${path}`,+ lastModified: now,+ changeFrequency: "monthly" as const,+ priority: 0.5,+ })),...highPriority.map((path) => ({url: `${base}${path}`,lastModified: now,diff --git a/apps/web/src/lib/replay.test.ts b/apps/web/src/lib/replay.test.tsindex d779a8f7e..a4a4586b5 100644--- a/apps/web/src/lib/replay.test.ts+++ b/apps/web/src/lib/replay.test.ts@@ -35,7 +35,7 @@ describe("fetchPublicReplay", () => {});it("URL-encodes the slug", async () => {- const spy = vi.fn(async () => new Response("{}", { status: 200 }));+ const spy = vi.fn(async (_url: string) => 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/tools/attack-catalog.ts b/apps/web/src/lib/tools/attack-catalog.tsnew file mode 100644index 000000000..04a90381a--- /dev/null+++ b/apps/web/src/lib/tools/attack-catalog.ts@@ -0,0 +1,67 @@+/**+ * A compact, prevalence-ranked catalog of common MITRE ATT&CK (Enterprise)+ * techniques for the `/tools/coverage` grader.+ *+ * This is intentionally a curated high-signal subset (the techniques most SOCs+ * actually need coverage for), not the full ATT&CK matrix — the grader is a+ * quick self-check, not an authoritative audit. `prevalence` is a 1–100 rank+ * (higher = seen more often in real incidents) used to surface the top+ * highest-impact uncovered techniques. Kept honest: this is a heuristic ranking+ * for prioritization, documented as such on the tool page.+ */++export interface AttackTechnique {+ id: string;+ name: string;+ tactic: string;+ prevalence: number;+}++export const ATTACK_CATALOG: AttackTechnique[] = [+ { id: "T1566", name: "Phishing", tactic: "initial-access", prevalence: 98 },+ { id: "T1059", name: "Command and Scripting Interpreter", tactic: "execution", prevalence: 97 },+ { id: "T1059.001", name: "PowerShell", tactic: "execution", prevalence: 95 },+ { id: "T1078", name: "Valid Accounts", tactic: "defense-evasion", prevalence: 94 },+ { id: "T1486", name: "Data Encrypted for Impact", tactic: "impact", prevalence: 93 },+ { id: "T1055", name: "Process Injection", tactic: "defense-evasion", prevalence: 90 },+ { id: "T1003", name: "OS Credential Dumping", tactic: "credential-access", prevalence: 92 },+ { id: "T1021", name: "Remote Services", tactic: "lateral-movement", prevalence: 88 },+ { id: "T1021.002", name: "SMB/Windows Admin Shares", tactic: "lateral-movement", prevalence: 82 },+ { id: "T1053", name: "Scheduled Task/Job", tactic: "persistence", prevalence: 85 },+ { id: "T1547", name: "Boot or Logon Autostart Execution", tactic: "persistence", prevalence: 80 },+ { id: "T1071", name: "Application Layer Protocol", tactic: "command-and-control", prevalence: 84 },+ { id: "T1105", name: "Ingress Tool Transfer", tactic: "command-and-control", prevalence: 83 },+ { id: "T1567", name: "Exfiltration Over Web Service", tactic: "exfiltration", prevalence: 78 },+ { id: "T1048", name: "Exfiltration Over Alternative Protocol", tactic: "exfiltration", prevalence: 74 },+ { id: "T1490", name: "Inhibit System Recovery", tactic: "impact", prevalence: 79 },+ { id: "T1112", name: "Modify Registry", tactic: "defense-evasion", prevalence: 76 },+ { id: "T1218", name: "System Binary Proxy Execution", tactic: "defense-evasion", prevalence: 77 },+ { id: "T1136", name: "Create Account", tactic: "persistence", prevalence: 70 },+ { id: "T1098", name: "Account Manipulation", tactic: "persistence", prevalence: 72 },+ { id: "T1110", name: "Brute Force", tactic: "credential-access", prevalence: 81 },+ { id: "T1082", name: "System Information Discovery", tactic: "discovery", prevalence: 68 },+ { id: "T1087", name: "Account Discovery", tactic: "discovery", prevalence: 66 },+ { id: "T1057", name: "Process Discovery", tactic: "discovery", prevalence: 64 },+ { id: "T1027", name: "Obfuscated Files or Information", tactic: "defense-evasion", prevalence: 75 },+ { id: "T1140", name: "Deobfuscate/Decode Files or Information", tactic: "defense-evasion", prevalence: 60 },+ { id: "T1204", name: "User Execution", tactic: "execution", prevalence: 86 },+ { id: "T1543", name: "Create or Modify System Process", tactic: "persistence", prevalence: 71 },+ { id: "T1562", name: "Impair Defenses", tactic: "defense-evasion", prevalence: 87 },+ { id: "T1070", name: "Indicator Removal", tactic: "defense-evasion", prevalence: 73 },+ { id: "T1036", name: "Masquerading", tactic: "defense-evasion", prevalence: 74 },+ { id: "T1041", name: "Exfiltration Over C2 Channel", tactic: "exfiltration", prevalence: 69 },+ { id: "T1090", name: "Proxy", tactic: "command-and-control", prevalence: 63 },+ { id: "T1573", name: "Encrypted Channel", tactic: "command-and-control", prevalence: 67 },+ { id: "T1195", name: "Supply Chain Compromise", tactic: "initial-access", prevalence: 62 },+ { id: "T1190", name: "Exploit Public-Facing Application", tactic: "initial-access", prevalence: 89 },+ { id: "T1133", name: "External Remote Services", tactic: "initial-access", prevalence: 79 },+ { id: "T1068", name: "Exploitation for Privilege Escalation", tactic: "privilege-escalation", prevalence: 76 },+ { id: "T1548", name: "Abuse Elevation Control Mechanism", tactic: "privilege-escalation", prevalence: 70 },+ { id: "T1552", name: "Unsecured Credentials", tactic: "credential-access", prevalence: 72 },+];++/** Fast lookup of parent technique id (T1059.001 → T1059). */+export function parentTechnique(id: string): string {+ const dot = id.indexOf(".");+ return dot > 0 ? id.slice(0, dot) : id;+}diff --git a/apps/web/src/lib/tools/coverage.ts b/apps/web/src/lib/tools/coverage.tsnew file mode 100644index 000000000..1e9227fbb--- /dev/null+++ b/apps/web/src/lib/tools/coverage.ts@@ -0,0 +1,76 @@+/**+ * ATT&CK coverage grading for `/tools/coverage`.+ *+ * Parses one or more Sigma rules (or a plain list of technique IDs) entirely in+ * the browser, extracts referenced ATT&CK techniques, and grades coverage+ * against the curated `ATT&CK_CATALOG`. Produces a heatmap-friendly per-tactic+ * breakdown and the top highest-prevalence uncovered techniques — the number+ * analysts screenshot and post.+ */++import { ATTACK_CATALOG, parentTechnique, type AttackTechnique } from "./attack-catalog";+import { coverageGrade } from "@aisoc/report-card";++const TECHNIQUE_RE = /\bT\d{4}(?:\.\d{3})?\b/gi;+// Sigma tags spell techniques as `attack.t1059.001`; also catch bare ids.+const SIGMA_TAG_RE = /attack\.(t\d{4}(?:\.\d{3})?)/gi;++/** Extract every ATT&CK technique id referenced in arbitrary rule text. */+export function extractTechniques(text: string): string[] {+ const found = new Set<string>();+ for (const m of text.matchAll(SIGMA_TAG_RE)) {+ if (m[1]) found.add(m[1].toUpperCase());+ }+ for (const m of text.matchAll(TECHNIQUE_RE)) {+ found.add(m[0].toUpperCase());+ }+ return [...found];+}++export interface TacticCoverage {+ tactic: string;+ covered: number;+ total: number;+}++export interface CoverageReport {+ grade: string;+ percent: number;+ covered: number;+ total: number;+ coveredIds: string[];+ byTactic: TacticCoverage[];+ topUncovered: AttackTechnique[];+}++/**+ * Grade coverage. A catalog technique counts as covered when the input+ * references it directly, or references a sub-technique whose parent it is, or+ * references the parent of a catalog sub-technique.+ */+export function gradeCoverage(ruleText: string): CoverageReport {+ const referenced = new Set(extractTechniques(ruleText));+ const referencedParents = new Set([...referenced].map(parentTechnique));++ const isCovered = (t: AttackTechnique): boolean =>+ referenced.has(t.id) || referenced.has(parentTechnique(t.id)) || referencedParents.has(t.id) || referencedParents.has(parentTechnique(t.id));++ const covered = ATTACK_CATALOG.filter(isCovered);+ const coveredIds = covered.map((t) => t.id);+ const total = ATTACK_CATALOG.length;+ const percent = total ? Math.round((covered.length / total) * 100) : 0;++ const tactics = [...new Set(ATTACK_CATALOG.map((t) => t.tactic))];+ const byTactic: TacticCoverage[] = tactics+ .map((tactic) => {+ const inTactic = ATTACK_CATALOG.filter((t) => t.tactic === tactic);+ return { tactic, covered: inTactic.filter(isCovered).length, total: inTactic.length };+ })+ .sort((a, b) => a.tactic.localeCompare(b.tactic));++ const topUncovered = ATTACK_CATALOG.filter((t) => !isCovered(t))+ .sort((a, b) => b.prevalence - a.prevalence)+ .slice(0, 10);++ return { grade: coverageGrade(percent), percent, covered: covered.length, total, coveredIds, byTactic, topUncovered };+}diff --git a/apps/web/src/lib/tools/nl2sigma.ts b/apps/web/src/lib/tools/nl2sigma.tsnew file mode 100644index 000000000..cb76c705b--- /dev/null+++ b/apps/web/src/lib/tools/nl2sigma.ts@@ -0,0 +1,93 @@+/**+ * Deterministic natural-language → Sigma generator for `/tools/nl2sigma`.+ *+ * Runs in the browser with no LLM: it extracts high-signal artifacts from the+ * plain-English description (process names, ports, MITRE ids, event verbs) and+ * assembles a well-formed Sigma rule. It is intentionally a scaffold generator+ * — honest about being a starting point, not a finished detection — and pairs+ * with the field-map translator to emit the SIEM dialects.+ */++export interface Nl2SigmaResult {+ sigma: string;+ matchedKeywords: string[];+ note: string;+}++const LOGSOURCE_HINTS: { re: RegExp; category: string; product: string }[] = [+ { re: /\b(powershell|cmd|process|command[- ]?line|executable|binary|spawn)\b/i, category: "process_creation", product: "windows" },+ { re: /\b(login|logon|sign[- ]?in|authentication|failed password|brute)\b/i, category: "authentication", product: "windows" },+ { re: /\b(dns|domain|resolve|query)\b/i, category: "dns", product: "" },+ { re: /\b(network|connection|port|outbound|beacon|c2)\b/i, category: "network_connection", product: "windows" },+ { re: /\b(file|write|create|drop|ransom|encrypt)\b/i, category: "file_event", product: "windows" },+];++const PROC_RE = /\b([A-Za-z0-9_-]+\.(?:exe|ps1|dll|bat|sh|py))\b/gi;+const MITRE_RE = /\bT\d{4}(?:\.\d{3})?\b/gi;+const PORT_RE = /\bport\s+(\d{1,5})\b/i;++function yamlList(items: string[], indent: string): string {+ return items.map((i) => `${indent}- '${i.replace(/'/g, "")}'`).join("\n");+}++export function nlToSigma(description: string, severity = "medium"): Nl2SigmaResult {+ const text = description.trim();+ const matched: string[] = [];++ const hint = LOGSOURCE_HINTS.find((h) => h.re.test(text));+ const category = hint?.category ?? "process_creation";+ const product = hint?.product ?? "windows";+ if (hint) matched.push(category);++ const procs = [...new Set([...text.matchAll(PROC_RE)].map((m) => m[1]!))];+ const mitre = [...new Set([...text.matchAll(MITRE_RE)].map((m) => m[0]!.toUpperCase()))];+ const portMatch = text.match(PORT_RE);+ procs.forEach((p) => matched.push(p));+ mitre.forEach((t) => matched.push(t));++ // Keyword candidates for a CommandLine|contains selection: notable verbs/nouns.+ const keywordCandidates = (text.match(/\b(download|invoke|encode|iex|mimikatz|whoami|net user|reg add|schtasks|vssadmin|bitsadmin|certutil|rundll32|regsvr32)\b/gi) ?? []).map(+ (k) => k.toLowerCase(),+ );+ const uniqueKeywords = [...new Set(keywordCandidates)];+ uniqueKeywords.forEach((k) => matched.push(k));++ const title = text.slice(0, 70).replace(/\n/g, " ") || "Suspicious activity";++ const detectionLines: string[] = ["detection:", " selection:"];+ if (procs.length) {+ detectionLines.push(" Image|endswith:");+ detectionLines.push(yamlList(procs.map((p) => `\\${p}`), " "));+ }+ if (uniqueKeywords.length) {+ detectionLines.push(" CommandLine|contains:");+ detectionLines.push(yamlList(uniqueKeywords, " "));+ }+ if (portMatch) {+ detectionLines.push(` DestinationPort: ${portMatch[1]}`);+ }+ if (!procs.length && !uniqueKeywords.length && !portMatch) {+ detectionLines.push(" # No concrete artifacts detected in the description — refine the selection below.");+ detectionLines.push(" CommandLine|contains: '<REPLACE_ME>'");+ }+ detectionLines.push(" condition: selection");++ const tagsBlock = mitre.length ? `tags:\n${mitre.map((t) => ` - attack.${t.toLowerCase()}`).join("\n")}\n` : "";+ const logsourceProduct = product ? `\n product: ${product}` : "";++ const sigma = `title: ${title}+status: experimental+description: ${text.replace(/\n/g, " ") || "Generated from a natural-language description."}+${tagsBlock}logsource:+ category: ${category}${logsourceProduct}+${detectionLines.join("\n")}+falsepositives:+ - Legitimate administrative activity+level: ${severity}`;++ return {+ sigma,+ matchedKeywords: matched,+ note: "Deterministic scaffold generated in your browser — a starting point, not a finished detection. Refine the selection and false positives before deploying.",+ };+}diff --git a/apps/web/src/lib/tools/noise.ts b/apps/web/src/lib/tools/noise.tsnew file mode 100644index 000000000..1addcb0ba--- /dev/null+++ b/apps/web/src/lib/tools/noise.ts@@ -0,0 +1,69 @@+/**+ * Alert-noise calculator for `/tools/noise`.+ *+ * Projects false-positive suppression and analyst hours saved from anonymized+ * alert-volume stats, using the AiSOC verdict-engine's published operating+ * point. The precision/recall here are the DETERMINISTIC-tier figures reported+ * on the benchmark page — documented and linked on the tool page so the maths+ * is auditable, never a fabricated marketing number.+ */++// Deterministic-tier operating point (see apps/docs/docs/benchmark.md). These+// are the substrate self-consistency figures, not a claim about live-LLM+// accuracy — the tool page states this explicitly.+export const DEFAULT_SUPPRESSION_RATE = 0.855; // share of benign noise auto-suppressed+export const DEFAULT_MINUTES_PER_ALERT = 8; // industry-typical manual triage time++export interface NoiseInput {+ alertsPerDay: number;+ /** Fraction of alerts that are false positives (0–1). Default 0.9. */+ falsePositiveRate?: number;+ minutesPerAlert?: number;+ /** Fully-loaded analyst hourly cost, USD. Optional. */+ analystHourlyCost?: number;+ suppressionRate?: number;+}++export interface NoiseProjection {+ alertsPerDay: number;+ falsePositives: number;+ suppressedPerDay: number;+ suppressedPerMonth: number;+ hoursSavedPerDay: number;+ hoursSavedPerMonth: number;+ costSavedPerMonth?: number;+ noisePercent: number;+}++function clampFraction(v: number, fallback: number): number {+ if (!Number.isFinite(v) || v < 0 || v > 1) return fallback;+ return v;+}++export function projectNoise(input: NoiseInput): NoiseProjection {+ const alertsPerDay = Math.max(0, Math.floor(input.alertsPerDay || 0));+ const fpRate = clampFraction(input.falsePositiveRate ?? 0.9, 0.9);+ const suppressionRate = clampFraction(input.suppressionRate ?? DEFAULT_SUPPRESSION_RATE, DEFAULT_SUPPRESSION_RATE);+ const minutesPerAlert = input.minutesPerAlert && input.minutesPerAlert > 0 ? input.minutesPerAlert : DEFAULT_MINUTES_PER_ALERT;++ const falsePositives = alertsPerDay * fpRate;+ const suppressedPerDay = falsePositives * suppressionRate;+ const suppressedPerMonth = suppressedPerDay * 30;+ const hoursSavedPerDay = (suppressedPerDay * minutesPerAlert) / 60;+ const hoursSavedPerMonth = hoursSavedPerDay * 30;+ const noisePercent = alertsPerDay > 0 ? Number(((suppressedPerDay / alertsPerDay) * 100).toFixed(1)) : 0;++ const projection: NoiseProjection = {+ alertsPerDay,+ falsePositives: Math.round(falsePositives),+ suppressedPerDay: Math.round(suppressedPerDay),+ suppressedPerMonth: Math.round(suppressedPerMonth),+ hoursSavedPerDay: Number(hoursSavedPerDay.toFixed(1)),+ hoursSavedPerMonth: Number(hoursSavedPerMonth.toFixed(0)),+ noisePercent,+ };+ if (input.analystHourlyCost && input.analystHourlyCost > 0) {+ projection.costSavedPerMonth = Math.round(hoursSavedPerMonth * input.analystHourlyCost);+ }+ return projection;+}diff --git a/apps/web/src/lib/tools/tools.test.ts b/apps/web/src/lib/tools/tools.test.tsnew file mode 100644index 000000000..f3cac6c7b--- /dev/null+++ b/apps/web/src/lib/tools/tools.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from "vitest";++import { translateRule, encodePermalink, decodePermalink } from "./translate";+import { extractTechniques, gradeCoverage } from "./coverage";+import { projectNoise, DEFAULT_SUPPRESSION_RATE } from "./noise";+import { nlToSigma } from "./nl2sigma";++describe("tools/translate", () => {+ it("field-maps Sigma into SPL/ES|QL", () => {+ const out = translateRule("CommandLine contains x and SourceIp", "sigma", ["spl", "esql"]);+ expect(out.results.find((r) => r.format === "spl")!.rule).toContain("process_path");+ expect(out.results.find((r) => r.format === "esql")!.rule).toContain("source.ip");+ });++ it("permalink round-trips", () => {+ const enc = encodePermalink("sigma", "EventID: 4688");+ const dec = decodePermalink(enc);+ expect(dec).toEqual({ sourceFormat: "sigma", rule: "EventID: 4688" });+ });++ it("rejects a malformed permalink", () => {+ expect(decodePermalink("!!!notbase64!!!")).toBeNull();+ });+});++describe("tools/coverage", () => {+ it("extracts techniques from Sigma tags and bare ids", () => {+ const ids = extractTechniques("tags:\n - attack.t1059.001\n - attack.t1486\nnote T1078");+ expect(ids).toContain("T1059.001");+ expect(ids).toContain("T1486");+ expect(ids).toContain("T1078");+ });++ it("grades higher coverage with more techniques", () => {+ const few = gradeCoverage("attack.t1566");+ const many = gradeCoverage("T1566 T1059 T1078 T1486 T1055 T1003 T1021 T1053 T1071 T1105 T1190 T1204 T1562");+ expect(many.percent).toBeGreaterThan(few.percent);+ expect(many.covered).toBeGreaterThan(few.covered);+ expect(["A", "B", "C", "D", "F"]).toContain(many.grade);+ });++ it("surfaces the highest-prevalence uncovered techniques", () => {+ const report = gradeCoverage(""); // nothing covered+ expect(report.covered).toBe(0);+ expect(report.topUncovered.length).toBe(10);+ // Sorted by prevalence desc — phishing (98) should lead.+ expect(report.topUncovered[0]!.id).toBe("T1566");+ });++ it("sub-technique coverage counts the parent and vice versa", () => {+ const report = gradeCoverage("attack.t1059.001");+ expect(report.coveredIds).toContain("T1059");+ expect(report.coveredIds).toContain("T1059.001");+ });+});++describe("tools/noise", () => {+ it("projects suppression + hours saved", () => {+ const p = projectNoise({ alertsPerDay: 1000 });+ // 1000 * 0.9 FP * 0.855 suppression ≈ 769/day+ expect(p.suppressedPerDay).toBe(Math.round(1000 * 0.9 * DEFAULT_SUPPRESSION_RATE));+ expect(p.hoursSavedPerMonth).toBeGreaterThan(0);+ expect(p.costSavedPerMonth).toBeUndefined();+ });++ it("includes cost when an hourly rate is supplied", () => {+ const p = projectNoise({ alertsPerDay: 1000, analystHourlyCost: 75 });+ expect(p.costSavedPerMonth).toBeGreaterThan(0);+ });++ it("clamps nonsense inputs to sane defaults", () => {+ const p = projectNoise({ alertsPerDay: -5, falsePositiveRate: 9 });+ expect(p.alertsPerDay).toBe(0);+ expect(p.suppressedPerDay).toBe(0);+ });+});++describe("tools/nl2sigma", () => {+ it("builds a Sigma rule with process + keyword selections and MITRE tags", () => {+ const out = nlToSigma("Detect powershell.exe running DownloadString or IEX, technique T1059.001");+ expect(out.sigma).toContain("title:");+ expect(out.sigma).toContain("logsource:");+ expect(out.sigma).toContain("powershell.exe");+ expect(out.sigma.toLowerCase()).toContain("downloadstring");+ expect(out.sigma).toContain("attack.t1059.001");+ expect(out.sigma).toContain("condition: selection");+ });++ it("falls back to a REPLACE_ME selection when no artifacts are found", () => {+ const out = nlToSigma("something suspicious happened");+ expect(out.sigma).toContain("REPLACE_ME");+ });++ it("picks an authentication logsource for login-related descriptions", () => {+ const out = nlToSigma("multiple failed logon attempts then a successful sign-in");+ expect(out.sigma).toContain("category: authentication");+ });+});diff --git a/apps/web/src/lib/tools/translate.ts b/apps/web/src/lib/tools/translate.tsnew file mode 100644index 000000000..1a2e79c32--- /dev/null+++ b/apps/web/src/lib/tools/translate.ts@@ -0,0 +1,148 @@+/**+ * Client-side deterministic detection-rule translation for `/tools/translate`.+ *+ * Runs entirely in the browser — user rules never touch the server on the+ * deterministic path (the BYO-key LLM path calls the provider directly from the+ * client). Mirrors the canonical field-map in+ * `services/api/app/api/v1/endpoints/translation.py` and+ * `packages/aisoc-lite/src/verdict/translate.ts` so CLI, API, and web agree.+ */++export type DetectionFormat = "sigma" | "spl" | "kql" | "esql" | "yara_l2" | "udm";++export const FORMAT_LABELS: Record<DetectionFormat, string> = {+ sigma: "Sigma YAML",+ spl: "Splunk SPL",+ kql: "Microsoft Sentinel KQL",+ esql: "Elastic ES|QL",+ yara_l2: "Google Chronicle YARA-L2",+ udm: "Google Chronicle UDM Search",+};++export const ALL_FORMATS: DetectionFormat[] = ["sigma", "spl", "kql", "esql", "yara_l2", "udm"];++const FIELD_MAP: Record<string, Record<string, string>> = {+ spl: {+ EventID: "EventCode",+ Image: "process_name",+ CommandLine: "process_path",+ TargetUserName: "user",+ DestinationIp: "dest_ip",+ SourceIp: "src_ip",+ },+ kql: {+ EventID: "EventID",+ Image: "NewProcessName",+ CommandLine: "CommandLine",+ TargetUserName: "TargetUserName",+ DestinationIp: "RemoteIP",+ SourceIp: "InitiatingProcessRemoteIP",+ },+ esql: {+ EventID: "event.code",+ Image: "process.executable",+ CommandLine: "process.command_line",+ TargetUserName: "user.name",+ DestinationIp: "destination.ip",+ SourceIp: "source.ip",+ },+ yara_l2: {+ EventID: "metadata.product_event_type",+ Image: "principal.process.file.full_path",+ CommandLine: "principal.process.command_line",+ TargetUserName: "target.user.userid",+ DestinationIp: "target.ip",+ SourceIp: "principal.ip",+ },+ udm: {+ EventID: "metadata.product_event_type",+ Image: "principal.process.file.full_path",+ CommandLine: "principal.process.command_line",+ TargetUserName: "target.user.userid",+ DestinationIp: "target.ip",+ SourceIp: "principal.ip",+ },+};++export interface TranslationResult {+ format: DetectionFormat;+ label: string;+ rule: string;+ notes?: string;+}++export interface TranslateOutput {+ sourceFormat: DetectionFormat;+ results: TranslationResult[];+ warnings: string[];+}++function wrap(fmt: DetectionFormat, rule: string): string {+ switch (fmt) {+ case "spl":+ return `index=* sourcetype=WinEventLog\n| search ${rule}`;+ case "kql":+ return `SecurityEvent\n| where ${rule}`;+ case "esql":+ return `FROM logs-*\n| WHERE ${rule}`;+ case "yara_l2":+ return `rule translated_rule {\n meta:\n author = "AiSOC"\n condition:\n ${rule}\n}`;+ case "udm":+ return `// Chronicle UDM Search\n${rule}`;+ case "sigma":+ return rule;+ default: {+ const _never: never = fmt;+ return _never;+ }+ }+}++export function translateRule(+ sourceRule: string,+ sourceFormat: DetectionFormat,+ targetFormats: DetectionFormat[] = ["sigma", "spl", "kql", "esql"],+): TranslateOutput {+ const results: TranslationResult[] = [];+ const warnings = [+ "Deterministic field-map translation, computed in your browser (no server, no LLM). Review field names before deploying.",+ ];++ for (const fmt of targetFormats) {+ if (fmt === sourceFormat) {+ results.push({ format: fmt, label: FORMAT_LABELS[fmt], rule: sourceRule, notes: "Same as source." });+ continue;+ }+ let rule = sourceRule;+ const map = FIELD_MAP[fmt] ?? {};+ for (const [src, tgt] of Object.entries(map)) {+ rule = rule.split(src).join(tgt);+ }+ results.push({ format: fmt, label: FORMAT_LABELS[fmt], rule: wrap(fmt, rule), notes: "Template translation — verify field names." });+ }+ return { sourceFormat, results, warnings };+}++/** LZ-free permalink codec: base64url of the JSON payload (small rules only). */+export function encodePermalink(sourceFormat: DetectionFormat, rule: string): string {+ const json = JSON.stringify({ f: sourceFormat, r: rule });+ if (typeof btoa === "function") {+ return btoa(unescape(encodeURIComponent(json)))+ .replace(/\+/g, "-")+ .replace(/\//g, "_")+ .replace(/=+$/, "");+ }+ return Buffer.from(json, "utf8").toString("base64url");+}++export function decodePermalink(s: string): { sourceFormat: DetectionFormat; rule: string } | null {+ try {+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/");+ const json = typeof atob === "function" ? decodeURIComponent(escape(atob(b64))) : Buffer.from(b64, "base64").toString("utf8");+ const parsed = JSON.parse(json) as { f: DetectionFormat; r: string };+ if (!ALL_FORMATS.includes(parsed.f) || typeof parsed.r !== "string") return null;+ return { sourceFormat: parsed.f, rule: parsed.r };+ } catch {+ return null;+ }+}