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
Keep one deployment's hostname out of every self-hosted install (#805)
Beenu Aroraf9e0454c8733
diff --git a/.github/workflows/hosted-hostname.yml b/.github/workflows/hosted-hostname.ymlnew file mode 100644index 000000000..3546ec3b2--- /dev/null+++ b/.github/workflows/hosted-hostname.yml@@ -0,0 +1,52 @@+name: Hosted hostname++# A self-hoster must never meet another deployment's hostname presented as+# their own product's URL. The maintainers' hosted host still appears+# legitimately in the managed-instance deploy configs, the marketing pages and+# the changelog, so this gate is not "the string must not appear" — it is+# "every appearance is one somebody signed off on", pinned by exact count.+#+# Runs on BOTH pull_request and push-to-main. A PR-only gate is one-directional:+# it checks what contributors propose but never what actually lands, so an edit+# made at merge time slips past while the gate stays green.+#+# No paths filter. A hostname default can appear in any file type — TypeScript,+# Go, Python, YAML, a plugin manifest — and a filtered gate that skips is+# indistinguishable from a gate that passes.++on:+ pull_request:+ push:+ branches: [main]+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: hosted-hostname-${{ github.ref }}+ cancel-in-progress: true++jobs:+ hosted-hostname:+ name: No hosted hostname in OSS defaults+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.12"++ # Runs first and on every invocation. If the detector or the+ # both-directions comparison stops working, this fails here rather than+ # letting the scan below report a clean tree it never inspected properly.+ - name: Self-test (gate is not vacuous)+ run: python3 scripts/check_hosted_hostname.py --self-test++ # Deliberately run from the repository root via the default working+ # directory: the gate resolves its root from the working directory, not+ # from its own file location, so it fails loudly if pointed anywhere else.+ - name: Scan the tree+ run: python3 scripts/check_hosted_hostname.pydiff --git a/.github/workflows/publish-images.yml b/.github/workflows/publish-images.ymlindex 0d4fed247..1a1eaa72e 100644--- a/.github/workflows/publish-images.yml+++ b/.github/workflows/publish-images.yml@@ -135,7 +135,7 @@ jobs:echo 'NEXT_PUBLIC_DEMO_MODE=true'echo 'NEXT_PUBLIC_DEMO_DEEPLINK=/cases/INC-RT-001?tab=ledger'echo 'NEXT_PUBLIC_DEMO_BANNER=Demo data resets daily at 00:00 UTC. All write actions are disabled.'- echo '[email protected]'+ echo '[email protected]'echo 'NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD=aisoc-demo'echo 'EOF'} >> "$GITHUB_OUTPUT"diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 108b437e4..2143505ca 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -183,7 +183,7 @@ jobs:echo 'NEXT_PUBLIC_DEMO_MODE=true'echo 'NEXT_PUBLIC_DEMO_DEEPLINK=/cases/INC-RT-001?tab=ledger'echo 'NEXT_PUBLIC_DEMO_BANNER=Demo data resets daily at 00:00 UTC. All write actions are disabled.'- echo '[email protected]'+ echo '[email protected]'echo 'NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD=aisoc-demo'echo 'EOF'} >> "$GITHUB_OUTPUT"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex db161211e..9536dac52 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -178,6 +178,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security+- **The maintainers' hosted origin shipped in the default CORS allow-list of+ nine services.** `services/{api,agents,connectors,honeytokens,purple-team,ueba}`+ (six byte-identical copies of the shared `cors.py`), `services/realtime`, and+ the Go `ingest` and `enrichment` servers all listed `https://tryaisoc.com` and+ `https://www.tryaisoc.com` among the origins they trust when+ `AISOC_CORS_ORIGINS` is unset. That is one deployment's public origin baked+ into every self-hosted install, trusted for credentialed cross-origin+ requests its operator never opted into — and if that domain ever changed+ hands, the grant travels with it. The default is now local development only;+ the hosted deployment already sets `CORS_ORIGINS` explicitly+ (`infra/fly/api/fly.toml`), so nothing legitimate depended on the default.+ `apps/docs/docs/deployment/env-vars.md` documented the old list and was+ corrected with it, and a new gate pins the six vendored `cors.py` copies+ byte-identical — nothing enforced that before, and a single drifted copy is+ exactly how one service would quietly keep the origin.++- **The seeded demo identity was a live, operator-owned domain.**+ `[email protected]`, paired with a published password, appeared across+ compose, fly, render, coolify, railway, two workflows, the web Dockerfile and+ the docs. It told a self-hoster to type somebody else's hostname to sign in+ to their own install, and published a well-known credential pair against a+ real domain. Now `[email protected]` — RFC 2606 reserved, so it can never be+ registered and can never receive mail, and it still satisfies the+ `pydantic.EmailStr` check that rejected the earlier `[email protected]`. Every+ config and doc moved with it. Safe to re-run: `seed_demo._ensure_user`+ reconciles on `DEMO_USER_ID`, not on the address, and rewrites a stale email+ in place.+- **`/api/v1/identity-timeline` read every tenant's alerts.** Both routes boundan authenticated user and never used it: the SQL against `aisoc_alerts`carried no `tenant_id` predicate, so any authenticated caller could pull any@@ -341,6 +369,61 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0can only be exempted by editing a reviewable assertion rather than appendingto a list.+- **A self-hosted install handed its own users links into the maintainers'+ deployment.** Beyond the CORS and demo-credential entries above, ten shipped+ defaults resolved to the hosted host when left unconfigured, so an operator+ who never set an override sent their users somewhere else:++ - `getPublicSiteUrl()` (`apps/web/src/lib/site.ts`) fell back to the hosted+ origin, which is the `metadataBase` for the whole app — every canonical+ tag, Open Graph URL, JSON-LD block and sitemap entry on a self-hosted+ console pointed at another deployment. Now `http://localhost:3000`. The+ hosted brand was also carried in `DISCOVERY_KEYWORDS`, the root layout's+ OG/Twitter descriptions, its `sameAs`, and the PWA manifest description.+ - Published investigation replays built share links from a module constant+ `https://tryaisoc.com/r`, and tenant invite links had **two** independent+ hard-coded defaults — one on the endpoint, one on the provisioner — free to+ drift apart, which is the part that makes this hard to notice. Both now+ resolve through a single `console_base_url()` reading+ `CONSOLE_PUBLIC_BASE_URL`, with a documented deployment-neutral fallback.+ - Approval email defaulted to a `From:` on the hosted domain, which fails+ SPF/DKIM for anyone else. It now prefers the operator's own+ `MAILGUN_DOMAIN`.+ - `plugins/aisoc-direct/plugin.yaml` pre-filled the hosted osquery endpoint+ as the field default; `services/osquery-tls` declared a hosted+ `public_hostname` (and had no reader at all — the comment claimed a use it+ did not have).+ - The simulation-mode call to action pointed operators at docs on the hosted+ domain rather than the project's own documentation site.+ - The GitHub Action's PR comment hotlinked a badge served by the hosted+ deployment, in the same line that promises "no data leaves your CI"; the+ report card's coverage footer linked the hosted tool while its sibling+ already linked the repository.+ - `playwright.config.ts` defaulted one project to the hosted host and the+ adjacent project to `localhost` — same env var, two answers.++ Two admin console pages also rendered the hosted hostname as body text, and+ the demo-mode 403 told every operator "This is the public AiSOC demo at+ tryaisoc.com" regardless of where it was running.++ A new gate, `scripts/check_hosted_hostname.py`, keeps this from coming back.+ It is deliberately not "the string must not appear": the hostname stays in+ 99 files that genuinely describe the managed offering — the fly/cloudflare/+ terraform deploy configs, the marketing pages, the changelog, and two+ `uuid5` namespace seeds that are compatibility constants rather than URLs.+ It pins an exact occurrence count per path and fails in **both** directions:+ a new or grown occurrence, and an exemption that outlived the occurrence that+ justified it. A stale exemption is a standing permit for a future leak, and a+ one-directional allow-list never notices one. It resolves its repo root from+ the working directory rather than its own file location (a sibling gate did+ the latter and reported a confident OK about a tree it never opened), refuses+ a tree that fails a sentinel check, treats a zero-match scan as broken rather+ than clean, and ships a `--self-test` proving the detector separates a+ known-bad from a known-good sample and that the comparison rejects a vacuous+ pass. Covered by `tests/test_hosted_hostname_gate.py` (39 cases) and+ `.github/workflows/hosted-hostname.yml`, which runs on pull requests *and* on+ pushes to `main` so an edit made at merge time cannot slip past.+- **The MSSP console showed six invented tenants and made no API call at all.**`MSSPDashboardView.tsx` declared `const TENANTS = [...]` — "Acme Financial","GlobalRetail Corp", "MedSecure Health" and three more, with invented alertdiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex a68802357..148a9416b 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 108 rows+The last row is the one worth reading first. It is the honest index: 109 rows`GATED`, 9 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.mdindex 908aa3877..b0bc983c8 100644--- a/apps/docs/docs/deployment/env-vars.md+++ b/apps/docs/docs/deployment/env-vars.md@@ -340,7 +340,15 @@ CORS is configured the same way across every AiSOC service — Python (FastAPI),|----------|----------|-------------|| `AISOC_CORS_ORIGINS` | **1 (canonical)** | Comma-separated allow-list. Set this in every environment. || `CORS_ORIGINS` | 2 (legacy alias) | Honoured when `AISOC_CORS_ORIGINS` is unset. Existing Helm charts and dev scripts that already use this keep working. |-| _(none set)_ | 3 (default) | Each service falls back to `http://localhost:3000`, `http://localhost:3001`, `http://127.0.0.1:3000`, `http://127.0.0.1:3001`, `https://tryaisoc.com`, `https://www.tryaisoc.com`. |+| _(none set)_ | 3 (default) | Each service falls back to local development origins only: `http://localhost:3000`, `http://localhost:3001`, `http://127.0.0.1:3000`, `http://127.0.0.1:3001`. |++:::note Deployed origins are never in the shipped default+The default covers local development and nothing else. No deployment's public+origin — including the one the maintainers host — ships in the allow-list, so a+self-hosted install never trusts a third-party origin for credentialed+cross-origin requests without its operator opting in. Set+`AISOC_CORS_ORIGINS` to your own console origin for any deployment.+:::Examples:diff --git a/apps/docs/docs/installation.md b/apps/docs/docs/installation.mdindex 96a16bd5d..e33e810a9 100644--- a/apps/docs/docs/installation.md+++ b/apps/docs/docs/installation.md@@ -204,7 +204,7 @@ ticked, then `wsl --update` and restart Docker Desktop.Visit[`http://localhost:3000/cases/INC-RT-001?tab=ledger`](http://localhost:3000/cases/INC-RT-001?tab=ledger)-manually. Default credentials are pre-filled (`[email protected]`); the+manually. Default credentials are pre-filled (`[email protected]`); theinvestigation is already in flight on the **Ledger** tab.### `aisoc:demo` is already runningdiff --git a/apps/web/Dockerfile b/apps/web/Dockerfileindex 284b24e08..9f831a04b 100644--- a/apps/web/Dockerfile+++ b/apps/web/Dockerfile@@ -75,7 +75,7 @@ ENV NEXT_PUBLIC_WS_URL=${NEXT_PUBLIC_WS_URL}ARG NEXT_PUBLIC_DEMO_MODE=""ARG NEXT_PUBLIC_DEMO_DEEPLINK="/cases/INC-RT-001?tab=ledger"ARG NEXT_PUBLIC_DEMO_BANNER="Demo data resets daily at 00:00 UTC. All write actions are disabled."-ARG NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL="[email protected]"+ARG NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL="[email protected]"ARG NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD="aisoc-demo"ENV NEXT_PUBLIC_DEMO_MODE=${NEXT_PUBLIC_DEMO_MODE}ENV NEXT_PUBLIC_DEMO_DEEPLINK=${NEXT_PUBLIC_DEMO_DEEPLINK}diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.tsindex ea91e3162..9f4193810 100644--- a/apps/web/playwright.config.ts+++ b/apps/web/playwright.config.ts@@ -7,7 +7,9 @@ import { defineConfig, devices } from "@playwright/test";** 1. ``screencast`` (Phase 4.3) — records the 90-second product demo* against a deployed URL configured by ``AISOC_SCREENCAST_URL``.- * Default target is the public ``tryaisoc.com`` deployment.+ * Defaults to the local console, same as the ``screenshots`` project —+ * the two used to disagree, so an unset env var silently recorded+ * against a different deployment than the screenshots did.** 2. ``visual`` (Phase 4.7) — Storybook-driven visual regression. The* ``webServer`` block boots a static `http-server` over@@ -84,7 +86,7 @@ export default defineConfig({? "http://localhost:3100": IS_SCREENSHOTS? (process.env.AISOC_SCREENCAST_URL ?? "http://localhost:3000")- : (process.env.AISOC_SCREENCAST_URL ?? "https://tryaisoc.com"),+ : (process.env.AISOC_SCREENCAST_URL ?? "http://localhost:3000"),trace: IS_JOURNEY ? "retain-on-failure" : "off",screenshot: IS_JOURNEY ? "only-on-failure" : "off",video: "off",diff --git a/apps/web/public/manifest.json b/apps/web/public/manifest.jsonindex aff0657e6..98f216eec 100644--- a/apps/web/public/manifest.json+++ b/apps/web/public/manifest.json@@ -1,7 +1,7 @@{"name": "AiSOC Responder","short_name": "AiSOC",- "description": "On-call responder PWA for AiSOC — open-source AI SOC. Triage entity-risk alerts, approve agent actions, manage cases, and search across connected SIEMs from your phone. 16 click-and-connect sources, confidence scoring, and detection drift tracking. tryaisoc.com demo.",+ "description": "On-call responder PWA for AiSOC — open-source AI SOC. Triage entity-risk alerts, approve agent actions, manage cases, and search across connected SIEMs from your phone. 16 click-and-connect sources, confidence scoring, and detection drift tracking.","id": "/responder","start_url": "/responder","scope": "/",diff --git a/apps/web/src/app/(app)/admin/tenants/page.tsx b/apps/web/src/app/(app)/admin/tenants/page.tsxindex acc695543..ce6ed3d25 100644--- a/apps/web/src/app/(app)/admin/tenants/page.tsx+++ b/apps/web/src/app/(app)/admin/tenants/page.tsx@@ -102,10 +102,8 @@ export default function AdminTenantsPage() {</h1><p className="mt-1 text-sm text-gray-400">Read-only directory of every tenant in this AiSOC deployment.- Managed tenants — provisioned through the waitlist flow on{' '}- <code className="rounded bg-white/[0.05] px-1">tryaisoc.com</code>{' '}- — are tagged in the list so the support team can scope- their attention.+ Managed tenants — provisioned through the waitlist flow — are+ tagged in the list so the support team can scope their attention.</p></header>diff --git a/apps/web/src/app/(app)/admin/waitlist/page.tsx b/apps/web/src/app/(app)/admin/waitlist/page.tsxindex 095b6e115..6cb93bec1 100644--- a/apps/web/src/app/(app)/admin/waitlist/page.tsx+++ b/apps/web/src/app/(app)/admin/waitlist/page.tsx@@ -178,9 +178,9 @@ export default function AdminWaitlistPage() {Managed waitlist</h1><p className="mt-1 text-sm text-gray-400">- Triage incoming requests for <code className="rounded bg-white/[0.05] px-1">tryaisoc.com</code>{' '}- managed tenants. Promote an entry to mint the tenant, seed the- demo dataset, and generate the initial admin invite link.+ Triage incoming requests for managed tenants on this deployment.+ Promote an entry to mint the tenant, seed the demo dataset, and+ generate the initial admin invite link.</p></header>diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsxindex 5850d53ce..8cf6afe5a 100644--- a/apps/web/src/app/layout.tsx+++ b/apps/web/src/app/layout.tsx@@ -43,7 +43,7 @@ export const metadata: Metadata = {openGraph: {title: 'AiSOC — Free, Open-Source AI Security Operations Center',description:- 'Self-hostable AI SOC with real-time threat detection, alert fusion, purple-team drills, MITRE ATT&CK investigation, and detection-as-code. MIT-licensed. Try the live demo at tryaisoc.com.',+ 'Self-hostable AI SOC with real-time threat detection, alert fusion, purple-team drills, MITRE ATT&CK investigation, and detection-as-code. MIT-licensed.',type: 'website',siteName: 'AiSOC',url: siteUrl,@@ -62,7 +62,7 @@ export const metadata: Metadata = {card: 'summary_large_image',title: 'AiSOC — Free Open-Source AI SOC Platform',description:- 'AI-powered SOC: threat detection, alert fusion, purple team, MITRE ATT&CK mapping, detection-as-code, and eval harness in CI. Self-host for free — tryaisoc.com.',+ 'AI-powered SOC: threat detection, alert fusion, purple team, MITRE ATT&CK mapping, detection-as-code, and eval harness in CI. Self-host for free.',site: '@aisoc_dev',creator: '@aisoc_dev',},@@ -100,10 +100,7 @@ const jsonLd = {logo: `${siteUrl}/favicon.svg`,description:'Community-driven, MIT-licensed AI security operations platform with a public demo and self-host path.',- sameAs: [- 'https://github.com/beenuar/AiSOC',- 'https://tryaisoc.com',- ],+ sameAs: ['https://github.com/beenuar/AiSOC'],contactPoint: {'@type': 'ContactPoint',contactType: 'technical support',@@ -153,7 +150,7 @@ const jsonLd = {'@type': 'WebSite',name: 'AiSOC',url: siteUrl,- description: 'Open-source AI-powered Security Operations Center — tryaisoc.com',+ description: 'Open-source AI-powered Security Operations Center',potentialAction: {'@type': 'SearchAction',target: `${siteUrl}/search?q={search_term_string}`,diff --git a/apps/web/src/app/login/page.tsx b/apps/web/src/app/login/page.tsxindex 566444546..0fedbb2fb 100644--- a/apps/web/src/app/login/page.tsx+++ b/apps/web/src/app/login/page.tsx@@ -9,7 +9,7 @@* footer ("Sign in on desktop").** Demo credentials live in `services/api/app/api/v1/dev_auth.py`:- * [email protected] / aisoc-demo+ * [email protected] / aisoc-demo*/import Link from 'next/link';@@ -22,7 +22,7 @@ type Phase = 'idle' | 'pending' | 'success' | 'error';export const dynamic = 'force-dynamic';-const DEMO_EMAIL = '[email protected]';+const DEMO_EMAIL = '[email protected]';const DEMO_PASSWORD = 'aisoc-demo';/**@@ -137,7 +137,7 @@ function LoginInner() {<div><p className="font-medium text-indigo-300">Public demo</p><p className="text-xs text-zinc-400 mt-0.5">- <code className="text-zinc-300">[email protected]</code> /{' '}+ <code className="text-zinc-300">[email protected]</code> /{' '}<code className="text-zinc-300">aisoc-demo</code></p></div>diff --git a/apps/web/src/components/demo/DemoAutoLogin.tsx b/apps/web/src/components/demo/DemoAutoLogin.tsxindex dbf939231..c2b57934c 100644--- a/apps/web/src/components/demo/DemoAutoLogin.tsx+++ b/apps/web/src/components/demo/DemoAutoLogin.tsx@@ -1,7 +1,7 @@'use client';/**- * DemoAutoLogin — silent auto-login for the hosted demo at tryaisoc.com.+ * DemoAutoLogin — silent auto-login for a public demo deployment.** On the public demo we never want a visitor to land on `/cases` and see mock* rows because no JWT is in `localStorage`. This component runs once on mount@@ -10,7 +10,7 @@* 1. `isDemoMode()` is true (NEXT_PUBLIC_DEMO_MODE=true), AND* 2. there's no existing access token,*- * it logs in as the well-known demo user (`[email protected]` / `aisoc-demo` —+ * it logs in as the well-known demo user (`[email protected]` / `aisoc-demo` —* the same credentials displayed on `/login`) and then triggers a global SWR* revalidation so every `useSWR` hook on the page swaps its `fallbackData`* mocks for the freshly-fetched live data.@@ -29,7 +29,7 @@ import { authApi } from '@/lib/api';import { isDemoMode } from '@/lib/demoMode';const DEMO_EMAIL =- process.env.NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL?.trim() || '[email protected]';+ process.env.NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL?.trim() || '[email protected]';const DEMO_PASSWORD =process.env.NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD?.trim() || 'aisoc-demo';diff --git a/apps/web/src/components/demo/DemoBanner.tsx b/apps/web/src/components/demo/DemoBanner.tsxindex 1b3bc6a51..84c21b755 100644--- a/apps/web/src/components/demo/DemoBanner.tsx+++ b/apps/web/src/components/demo/DemoBanner.tsx@@ -1,7 +1,7 @@'use client';/**- * DemoBanner — top-of-page strip rendered on the hosted demo at tryaisoc.com.+ * DemoBanner — top-of-page strip rendered on a public demo deployment.** Sits inside `AppShell` above the TopBar so it covers every authenticated* page. Renders nothing when `NEXT_PUBLIC_DEMO_MODE !== 'true'`, so self-hosteddiff --git a/apps/web/src/components/onboarding/StartHero.tsx b/apps/web/src/components/onboarding/StartHero.tsxindex 6830b4cfd..d720a28fe 100644--- a/apps/web/src/components/onboarding/StartHero.tsx+++ b/apps/web/src/components/onboarding/StartHero.tsx@@ -50,7 +50,7 @@ export function StartHero() {// landing page and explain how to seed. We do NOT redirect to /login// because the empty error state on a fresh self-host is more// informative than a generic password prompt.- const email = process.env.NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL?.trim() || '[email protected]';+ const email = process.env.NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL?.trim() || '[email protected]';const password = process.env.NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD?.trim() || 'aisoc-demo';try {diff --git a/apps/web/src/lib/site.ts b/apps/web/src/lib/site.tsindex e45bff8e8..34703ebed 100644--- a/apps/web/src/lib/site.ts+++ b/apps/web/src/lib/site.ts@@ -1,22 +1,25 @@/*** Canonical public URL for SEO, Open Graph, and sitemap.- * Set NEXT_PUBLIC_SITE_URL at build/deploy (e.g. https://tryaisoc.com for the live demo).+ *+ * Set NEXT_PUBLIC_SITE_URL at build/deploy to this install's own public origin+ * (e.g. https://soc.example.com). The fallback is deliberately the local+ * console rather than any particular deployment: an unset value must never+ * make a self-hosted install emit canonical/OG/sitemap URLs pointing at+ * somebody else's hostname.*/export function getPublicSiteUrl(): string {const raw = process.env.NEXT_PUBLIC_SITE_URL?.trim();if (raw) {return raw.replace(/\/$/, "");}- return "https://tryaisoc.com";+ return "http://localhost:3000";}-/** Meta keywords for cyber/SOC discovery (tryaisoc.com demo + self-host). */+/** Meta keywords for cyber/SOC discovery (deployment-neutral). */export const DISCOVERY_KEYWORDS: readonly string[] = [// Brand"AiSOC","AI SOC",- "tryaisoc",- "tryaisoc.com",// Core value prop"open source SOC","open-source security operations center",diff --git a/docs/QUICK_INSTALL.md b/docs/QUICK_INSTALL.mdindex 01805d341..8bdec594b 100644--- a/docs/QUICK_INSTALL.md+++ b/docs/QUICK_INSTALL.md@@ -26,7 +26,7 @@ iwr -useb https://raw.githubusercontent.com/beenuar/AiSOC/main/install.ps1 | iex```When the script finishes, your default browser opens at-`http://localhost:3000/cases/INC-RT-001?tab=ledger` with `[email protected]`+`http://localhost:3000/cases/INC-RT-001?tab=ledger` with `[email protected]`already auto-logged-in and a real LockBit 3.0 investigation mid-flight.## What gets installeddiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 715492002..b6173058b 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -123,6 +123,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Which identity providers can resolve permissions live is stated, not implied | effective-permissions endpoint docstring | `ci.yml` api job (`test_posture_snapshot_coverage.py`) — a resolver registered without a declared snapshot source fails, the live-capable set is pinned, and a stale allow-list entry fails once its connector starts answering the posture sentinel | GATED | four of five providers cannot collect a live snapshot: no connector implements `__posture_snapshot__`, so they answer 412 rather than fabricating one || Config snapshots reach the graph when the feature reports enabled | architecture/graph-schema.md (`:CONFIGURED_AS`) | `ci.yml` ingest job (`http_provider_test.go`) — the provider's request shape is pinned against the served route, vendor-supplied ids are escaped so an ARN cannot inject a query parameter, a 501 is distinguished from an error, and the bi-temporal edge properties the schema declares are asserted present | GATED | `is_current` is set on write and never cleared, because closing the previous interval needs a read-modify-write the ingest hot path does not do || SIEM integrations are two-way: an AiSOC verdict reaches the finding that raised it | docs/integrations/siem-writeback.md | `ci.yml` actions job (`test_disposition_writeback.py` — a confirmed true positive escalates and is never closed, an unrecognised verdict is refused rather than normalised, and the taxonomy is compared against the agents service so a verdict present on one side only cannot silently mean nothing) + `test_siem_client_signatures.py` (every close and escalate arm autospec'd against its real client) + api job (`test_siem_writeback.py` — refusals, simulations and transport failures all record `executed=False`) + fusion job (`test_source_finding_link.py` — `finding.uid` reaches `alerts.external_id`, and only a vendor with a writeback arm gets a link row) | GATED | - |+| No OSS default resolves to a specific deployment's hostname, so a self-hosted install never presents another deployment's host as its own | self-host contract; `apps/docs/docs/deployment/env-vars.md` (CORS default) | `hosted-hostname.yml` (`scripts/check_hosted_hostname.py` — an exact occurrence count per path, checked in **both** directions: a new or grown occurrence and a stale exemption whose occurrence is gone both fail, so an allow-list entry cannot outlive what justified it; the root is resolved from the working directory rather than `__file__` and verified against sentinels, a zero-match scan is reported as broken rather than clean, and `--self-test` runs first proving the detector separates known-bad from known-good and that the comparison rejects a vacuous pass; it also pins the six vendored `cors.py` copies byte-identical) + `tests/test_hosted_hostname_gate.py` (39 cases, including the ten runtime defaults that leaked and a check that the CORS-tuple extractor itself would notice the origin coming back) | GATED | - || A dry run never reaches a customer's vendor | live-action dry-run contract | `ci.yml` actions job (`test_dry_run_credential_strip.py` — each client factory's read set is re-derived from its own source and compared with the adapter's strip list, stripping that set is asserted to make the factory return `None`, and an end-to-end dry run with full credentials trips a wire if any factory returns a client) | GATED | the wire covers the four SIEM factories the writeback path uses; other vendors' adapters are covered by the strip-list equality check only || Documentation and marketing name no competitor product, while vendors AiSOC integrates with stay named | AGENTS.md (naming rule); docs portal + benchmark comparison tables | `competitor-names.yml` (`scripts/check_competitor_names.py` — an explicit name list plus a path allow-list for integration surfaces, both checked in both directions: a dead pattern, a stale allow entry that no longer excuses anything, and a drifted comparison-table marker each fail rather than reporting a clean tree; the scan prints the absolute root and file count so it cannot report on a tree it never read) + `tests/test_competitor_names_gate.py` (42 cases, including `Torq` asserted as a competitor in prose *and* left untouched across its connector module, manifest, docs page and tests) | GATED | the name list is AI-SOC/SOAR rivals; vendors that are purely integration targets are deliberately absent from it and are instead held out of the pinned comparison-table regions, which are checked against a wider vendor list |diff --git a/infra/compose/docker-compose.demo.yml b/infra/compose/docker-compose.demo.ymlindex a5ec8dc8a..1305d80ed 100644--- a/infra/compose/docker-compose.demo.yml+++ b/infra/compose/docker-compose.demo.yml@@ -315,7 +315,7 @@ services:NEXT_PUBLIC_DEMO_MODE: "true"NEXT_PUBLIC_DEMO_DEEPLINK: "/cases/INC-RT-001?tab=ledger"NEXT_PUBLIC_DEMO_BANNER: "Demo data resets daily at 00:00 UTC. All write actions are disabled."- NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL: "[email protected]"+ NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL: "[email protected]"NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD: "aisoc-demo"container_name: aisoc-demo-webpull_policy: missingdiff --git a/infra/coolify/README.md b/infra/coolify/README.mdindex 1fd6b13d8..31f0fb07d 100644--- a/infra/coolify/README.md+++ b/infra/coolify/README.md@@ -78,7 +78,7 @@ NEXT_PUBLIC_WS_URL=wss://realtime.aisoc.example.comNEXT_PUBLIC_DEMO_MODE=trueNEXT_PUBLIC_DEMO_DEEPLINK=/cases/INC-RT-001?tab=ledgerNEXT_PUBLIC_DEMO_BANNER=Demo data resets daily. All write actions are disabled.NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD=aisoc-demo```diff --git a/infra/fly/web/fly.toml b/infra/fly/web/fly.tomlindex 462a04385..790639f30 100644--- a/infra/fly/web/fly.toml+++ b/infra/fly/web/fly.toml@@ -52,7 +52,7 @@ kill_timeout = "5s"NEXT_PUBLIC_DEMO_MODE = "true"NEXT_PUBLIC_DEMO_DEEPLINK = "/cases/INC-RT-001?tab=ledger"NEXT_PUBLIC_DEMO_BANNER = "Demo data resets daily at 00:00 UTC. All write actions are disabled."- NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL = "[email protected]"+ NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL = "[email protected]"NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD = "aisoc-demo"# Server-side proxy targets MUST be passed at build time, not just runtime.# next.config.js evaluates `process.env.API_URL` when the config module@@ -89,7 +89,7 @@ kill_timeout = "5s"# session as the read-only analyst the seeder provisions. Email + password# MUST stay in sync with services/api/app/scripts/seed_demo.py and# services/api/app/api/v1/dev_auth.py:DEMO_USER_EMAIL.- NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL = "[email protected]"+ NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL = "[email protected]"NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD = "aisoc-demo"# Server-side rewrite targets for next.config.js. Only some paths flow# through the Next proxy:diff --git a/infra/railway/README.md b/infra/railway/README.mdindex 20a0b11a4..c3de41497 100644--- a/infra/railway/README.md+++ b/infra/railway/README.md@@ -129,7 +129,7 @@ NEXT_PUBLIC_WS_URL=wss://${{ realtime.RAILWAY_PUBLIC_DOMAIN }}NEXT_PUBLIC_DEMO_MODE=trueNEXT_PUBLIC_DEMO_DEEPLINK=/cases/INC-RT-001?tab=ledgerNEXT_PUBLIC_DEMO_BANNER=Demo data resets daily. All write actions are disabled.NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD=aisoc-demo```diff --git a/packages/aisoc-action/dist/index.js b/packages/aisoc-action/dist/index.jsindex b86eb9860..98cc84928 100644--- a/packages/aisoc-action/dist/index.js+++ b/packages/aisoc-action/dist/index.js@@ -417,7 +417,10 @@ function renderComment(result, notes) {}lines.push("",- "<sub>Triaged by the deterministic [AiSOC](https://github.com/beenuar/AiSOC) verdict engine \u2014 no LLM, no data leaves your CI. </sub>"+ // No remote badge image here on purpose: this line promises "no data+ // leaves your CI", and a hotlinked badge makes every reader's browser+ // call a third-party deployment to render the comment.+ "<sub>Triaged by the deterministic [AiSOC](https://github.com/beenuar/AiSOC) verdict engine \u2014 no LLM, no data leaves your CI.</sub>");return lines.join("\n");}diff --git a/packages/aisoc-action/src/action.test.ts b/packages/aisoc-action/src/action.test.tsindex b9d4af31f..cf14b8a83 100644--- a/packages/aisoc-action/src/action.test.ts+++ b/packages/aisoc-action/src/action.test.ts@@ -66,11 +66,22 @@ describe("fetchAlerts", () => {describe("render", () => {const result = triageBatch([mapDependabot(DEPENDABOT), mapCodeScanning(CODE_SCANNING), mapSecretScanning(SECRET)]);- it("PR comment carries the idempotency marker, priority line, and badge", () => {+ it("PR comment carries the idempotency marker and priority line", () => {const md = renderComment(result, ["Code scanning: skipped (not enabled)."]);expect(md).toContain(COMMENT_MARKER);expect(md).toContain("of 3");- expect(md).toContain("img.shields.io/endpoint");+ expect(md).toContain("github.com/beenuar/AiSOC");+ });++ it("PR comment hotlinks no remote image", () => {+ // The footer promises "no data leaves your CI". A hotlinked badge breaks+ // that promise on every render: the reader's browser fetches it from a+ // third party, which learns who is reading the comment and when. It also+ // pointed at one specific deployment, so a self-hoster's CI advertised+ // somebody else's install.+ const md = renderComment(result, []);+ expect(md).not.toMatch(/!\[[^\]]*\]\(https?:\/\//);+ expect(md).not.toContain("img.shields.io");});it("posture grade rewards a clean queue and penalizes escalations", () => {diff --git a/packages/aisoc-action/src/render.ts b/packages/aisoc-action/src/render.tsindex 13514a3b3..db59caceb 100644--- a/packages/aisoc-action/src/render.ts+++ b/packages/aisoc-action/src/render.ts@@ -73,8 +73,10 @@ export function renderComment(result: TriageResult, notes: string[]): string {}lines.push("",- "<sub>Triaged by the deterministic [AiSOC](https://github.com/beenuar/AiSOC) verdict engine — no LLM, no data leaves your CI. " +- "</sub>",+ // No remote badge image here on purpose: this line promises "no data+ // leaves your CI", and a hotlinked badge makes every reader's browser+ // call a third-party deployment to render the comment.+ "<sub>Triaged by the deterministic [AiSOC](https://github.com/beenuar/AiSOC) verdict engine — no LLM, no data leaves your CI.</sub>",);return lines.join("\n");}diff --git a/packages/report-card/src/index.ts b/packages/report-card/src/index.tsindex 6e4642d43..9688459a1 100644--- a/packages/report-card/src/index.ts+++ b/packages/report-card/src/index.ts@@ -153,7 +153,7 @@ export function renderCardMarkdown(data: ReportCardData): string {`- 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",+ "Grade yours: open `/tools/coverage` in your AiSOC console · https://github.com/beenuar/AiSOC",].join("\n");case "replay":return [diff --git a/plugins/aisoc-direct/plugin.yaml b/plugins/aisoc-direct/plugin.yamlindex a5116c433..0a8120412 100644--- a/plugins/aisoc-direct/plugin.yaml+++ b/plugins/aisoc-direct/plugin.yaml@@ -31,12 +31,12 @@ schema:- name: base_urllabel: TLS Endpoint URLdescription: >- Base URL of the AiSOC osquery TLS service, e.g.- https://osquery.tryaisoc.com. Agents use this as their+ Base URL of this deployment's AiSOC osquery TLS service, e.g.+ https://osquery.example.com. Agents use this as their--tls_hostname flag.type: stringrequired: true- default: https://osquery.tryaisoc.com+ default: http://localhost:8091- name: tenant_idlabel: Tenant IDdescription: >diff --git a/render.yaml b/render.yamlindex 3dca9c4c4..f8245ccb8 100644--- a/render.yaml+++ b/render.yaml@@ -231,7 +231,7 @@ services:# sources DEMO_USER_EMAIL from app/api/v1/dev_auth.py and sets the# password to "aisoc-demo" via get_password_hash).- key: NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL- value: [email protected]+ value: [email protected]- key: NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORDvalue: aisoc-demodiff --git a/scripts/check_hosted_hostname.py b/scripts/check_hosted_hostname.pynew file mode 100644index 000000000..a51561ac9--- /dev/null+++ b/scripts/check_hosted_hostname.py@@ -0,0 +1,420 @@+#!/usr/bin/env python3+"""Keep the maintainers' hosted hostname out of open-source defaults.++A self-hoster must never meet another deployment's hostname presented as their+own product's URL. The canonical example was an OSS login page hard-coding+"back to <hosted domain>", which a self-hoster saw inside their own install.+Later examples were worse than cosmetic: published replay share links, tenant+invite emails, the Slack bot's case deep-links and the site's canonical/OG/+sitemap URLs all defaulted to the hosted host, so an unconfigured install+handed its users links into somebody else's console.++The hostname still appears legitimately in ~100 files — the managed-instance+deploy configs, the marketing pages that describe the hosted offering, and the+changelog. So this gate is not "the string must not appear"; it is "every+appearance is one somebody signed off on".++Bidirectional by construction+-----------------------------+The recurring failure mode in this repo is the one-directional check: it+compares A against B and never B against A, so drift in the direction things+actually change slips past while the check prints OK. A hostname allow-list+keyed only on "is this path allowed?" has exactly that shape — delete the line+that made a file legitimate and the file keeps its exemption forever, ready to+launder a real leak later.++So the allow-list stores an exact expected count per path and both directions+are errors:++ * tree -> allow-list : an occurrence in a path with no entry (a new leak), or+ more occurrences than the entry allows.+ * allow-list -> tree : an entry whose path is gone, or that now has fewer+ occurrences than recorded (a stale exemption).++Either way the fix is the same: look at the occurrence, decide whether it is+legitimate, and move the number deliberately.++Non-vacuity+-----------+A gate that can pass while inspecting nothing is worse than no gate, because it+launders the claim. Three guards:++ * The repo root comes from ``git rev-parse --show-toplevel`` evaluated in the+ *current working directory*, never from this file's location. A sibling+ gate resolved its root from ``__file__``, so a run launched from another+ worktree printed a confident OK about a tree it never inspected. The+ resolved root is verified against sentinel paths and always printed.+ * The scan must reach a plausible number of files and must still find the+ hostname somewhere. A scan that matches nothing means the pattern, the+ root or the file walk broke — that is reported as failure, not success.+ * ``--self-test`` runs the detector over a known-bad and a known-good sample+ and asserts it separates them, then asserts the comparison itself rejects+ an empty scan. Run in CI ahead of the real check.++It also pins the six vendored ``cors.py`` copies byte-identical to each other.+Nothing enforced that before, and a single drifted copy is precisely how one+service would quietly keep a hosted origin in its credentialed allow-list.++Usage:+ python3 scripts/check_hosted_hostname.py --self-test+ python3 scripts/check_hosted_hostname.py+ python3 scripts/check_hosted_hostname.py --repo-root /path/to/checkout+"""++from __future__ import annotations++import argparse+import hashlib+import subprocess+import sys+from pathlib import Path++HOSTED_HOSTNAME = "tryaisoc.com"++# Paths that exist to detect or record the hostname. Scanning them would make+# the gate flag itself. Keep this set as small as it can possibly be.+SELF_REFERENTIAL = frozenset(+ {+ "scripts/check_hosted_hostname.py",+ ".github/workflows/hosted-hostname.yml",+ }+)++# Files that must exist for a directory to be this repository. Cheap insurance+# against pointing the scan at the wrong tree and reporting a clean result.+SENTINELS = ("services/api/app/core/cors.py", "apps/web/package.json", "CHANGELOG.md")++# The six byte-identical vendored copies of the shared CORS helper.+CORS_COPIES = (+ "services/api/app/core/cors.py",+ "services/agents/app/core/cors.py",+ "services/connectors/app/security/cors.py",+ "services/honeytokens/app/core/cors.py",+ "services/purple-team/app/core/cors.py",+ "services/ueba/app/core/cors.py",+)++# If the scan finds fewer tracked files than this, something is wrong with the+# walk rather than right with the tree.+MIN_FILES_SCANNED = 500++_MANAGED_DEPLOY = "deploy config for the maintainers' managed instance; the hostname is the thing being configured"+_MARKETING = "marketing page describing the hosted offering to a reader on that hosted site"+_HISTORY = "historical record — changelog, release notes, decision log or incident note"+_MANAGED_FEATURE = "docstring/comment on the managed-instance feature set (waitlist, tenant provisioning, hosted demo)"+_UUID_SEED = "opaque uuid5 namespace seed — changing the string changes every derived id, so it is a compatibility constant, not a URL"+_DOCS = "documentation about the managed instance, accurate as written"+_PLAN = "plan file — never edited by policy; reported instead"+_GATE_FIXTURE = "deliberate regression assertion that the hostname is absent"++# path -> (expected occurrences, why this one is allowed)+ALLOWED: dict[str, tuple[int, str]] = {+ # --- managed-instance deploy configs -----------------------------------+ "infra/fly/fly-demo-deploy.sh": (27, _MANAGED_DEPLOY),+ "infra/fly/README.md": (17, _MANAGED_DEPLOY),+ "infra/fly/web/fly.toml": (13, _MANAGED_DEPLOY),+ "infra/fly/api/fly.toml": (9, _MANAGED_DEPLOY),+ "infra/fly/realtime/fly.toml": (4, _MANAGED_DEPLOY),+ "infra/fly/managed/README.md": (1, _MANAGED_DEPLOY),+ "infra/cloudflare/README.md": (13, _MANAGED_DEPLOY),+ "infra/cloudflare/tunnel.sh": (10, _MANAGED_DEPLOY),+ "infra/terraform/environments/managed/README.md": (7, _MANAGED_DEPLOY),+ "infra/terraform/environments/managed/variables.tf": (6, _MANAGED_DEPLOY),+ "infra/terraform/environments/managed/main.tf": (6, _MANAGED_DEPLOY),+ "apps/web/fly.toml": (4, _MANAGED_DEPLOY),+ "scripts/demo-public.sh": (3, _MANAGED_DEPLOY),+ "scripts/adoption_snapshot.py": (1, _MANAGED_DEPLOY),+ ".github/workflows/papers.yml": (2, _MANAGED_DEPLOY),+ ".github/FUNDING.yml": (1, _MANAGED_DEPLOY),+ ".github/ISSUE_TEMPLATE/benchmark_submission.yml": (2, _MANAGED_DEPLOY),+ "apps/web/e2e/demo/screencast.spec.ts": (1, _MANAGED_DEPLOY),+ # --- marketing surface, served from the hosted site --------------------+ "apps/web/src/app/(marketing)/about/page.tsx": (5, _MARKETING),+ "apps/web/src/app/(marketing)/sovereign/page.tsx": (5, _MARKETING),+ "apps/web/src/app/(marketing)/waitlist/page.tsx": (5, _MARKETING),+ "apps/web/src/app/(marketing)/privacy/page.tsx": (6, _MARKETING),+ "apps/web/src/app/(marketing)/contact/page.tsx": (4, _MARKETING),+ "apps/web/src/app/(marketing)/terms/page.tsx": (3, _MARKETING),+ "apps/web/src/app/(marketing)/blog/page.tsx": (2, _MARKETING),+ "apps/web/src/app/(marketing)/customers/page.tsx": (2, _MARKETING),+ "apps/web/src/app/(marketing)/press/page.tsx": (2, _MARKETING),+ "apps/web/src/app/(marketing)/pricing/page.tsx": (2, _MARKETING),+ "apps/web/src/app/(marketing)/blog/[slug]/page.tsx": (1, _MARKETING),+ "apps/web/src/app/(marketing)/customers/[slug]/page.tsx": (1, _MARKETING),+ "apps/web/src/app/(marketing)/mesh/page.tsx": (1, _MARKETING),+ "apps/web/src/app/why-open-source/page.tsx": (1, _MARKETING),+ "apps/web/src/app/page.tsx": (1, _MARKETING),+ "apps/web/src/app/not-found.tsx": (1, _MARKETING),+ "apps/web/src/app/r/[slug]/opengraph-image.tsx": (1, _MARKETING),+ "apps/web/src/app/api/badge/[kind]/route.ts": (1, _MARKETING),+ "apps/web/src/app/api/badge/[kind]/route.test.ts": (4, _MARKETING),+ "apps/web/src/components/landing/Hero.tsx": (2, _MARKETING),+ "apps/web/src/components/landing/Hero.test.tsx": (1, _MARKETING),+ "apps/web/src/components/landing/sections/Footer.tsx": (2, _MARKETING),+ "apps/web/src/components/landing/sections/StickyNav.tsx": (2, _MARKETING),+ "apps/web/src/components/landing/sections/DemoEmbed.tsx": (1, _MARKETING),+ "apps/web/src/components/landing/sections/DeployOptions.tsx": (1, _MARKETING),+ "apps/web/src/components/landing/sections/Faq.tsx": (2, _MARKETING),+ "apps/web/src/components/landing/sections/Hero.tsx": (1, _MARKETING),+ "apps/web/src/components/landing/sections/PricingTeaser.tsx": (1, _MARKETING),+ "apps/web/content/blog/automation-maturity.mdx": (2, _MARKETING),+ "marketing/launch/blog-outlines.md": (2, _MARKETING),+ "marketing/launch/product-hunt.md": (1, _MARKETING),+ # --- history: changelog, releases, decision records, incident notes ----+ "CHANGELOG.md": (24, _HISTORY),+ "RELEASES.md": (4, _HISTORY),+ "AGENTS.md": (6, _HISTORY),+ "docs/decisions/0004-live-demo-strategy.md": (5, _HISTORY),+ "docs/decisions/0003-mssp-pricing-shape.md": (2, _HISTORY),+ "services/api/app/db/database.py": (1, _HISTORY),+ "services/api/app/scripts/serve.py": (1, _HISTORY),+ "services/api/Dockerfile": (1, _HISTORY),+ "apps/web/src/components/onboarding/OnboardingView.tsx": (1, _HISTORY),+ "apps/web/src/lib/api.ts": (2, _HISTORY),+ "apps/web/next.config.js": (1, _HISTORY),+ "services/api/migrations/042_waitlist.sql": (1, _HISTORY),+ "services/api/migrations/043_tenant_provision.sql": (1, _HISTORY),+ "services/api/migrations/045_published_replays.sql": (1, _HISTORY),+ # --- managed-instance feature docstrings -------------------------------+ "services/api/app/api/v1/router.py": (2, _MANAGED_FEATURE),+ "services/api/app/scripts/demo_seed.py": (2, _MANAGED_FEATURE),+ "services/api/app/api/v1/endpoints/tenant_provision.py": (1, _MANAGED_FEATURE),+ "services/api/app/core/config.py": (1, _MANAGED_FEATURE),+ "services/api/app/middleware/demo_mode.py": (1, _MANAGED_FEATURE),+ "services/api/app/models/published_replay.py": (1, _MANAGED_FEATURE),+ "services/api/app/models/waitlist.py": (1, _MANAGED_FEATURE),+ "services/api/app/services/tenant_provision/__init__.py": (1, _MANAGED_FEATURE),+ "services/api/app/services/waitlist/__init__.py": (1, _MANAGED_FEATURE),+ "services/api/app/services/waitlist/rate_limit.py": (1, _MANAGED_FEATURE),+ "services/mesh/app/main.py": (1, _MANAGED_FEATURE),+ # --- uuid5 namespace seeds: compatibility constants, not URLs ----------+ "services/agents/app/orchestrator/router.py": (2, _UUID_SEED),+ "services/agents/app/workers/fused_alert_consumer.py": (1, _UUID_SEED),+ # --- documentation about the managed instance --------------------------+ "apps/docs/docs/operations/managed-instance.md": (14, _DOCS),+ "apps/docs/docusaurus.config.ts": (2, _DOCS),+ "docs/operations/live-demo-runbook.md": (7, _DOCS),+ "docs/design/landing-page-brief.md": (3, _DOCS),+ "docs/design/landing-page-content.md": (3, _DOCS),+ "docs/architecture/mesh.md": (1, _DOCS),+ "docs/design/README.md": (1, _DOCS),+ "docs/managed-mode.md": (1, _DOCS),+ "docs/press/README.md": (1, _DOCS),+ "examples/lateral-movement.md": (1, _DOCS),+ "examples/phishing-payload.md": (1, _DOCS),+ "services/slack-bot/README.md": (1, _DOCS),+ ".env.example": (2, _DOCS),+ # --- plan files: never edited, reported instead ------------------------+ "plans/aisoc_v8.0_north_star_plan_1dee8c63.plan.md": (6, _PLAN),+ "plans/cyble-aisoc/AGENTS.md": (4, _PLAN),+ "plans/cyble-aisoc/index.html": (4, _PLAN),+ "plans/cyble-aisoc/platform/README.md": (2, _PLAN),+ "plans/cyble-aisoc/architecture/agent-topology.md": (1, _PLAN),+ "plans/cyble-aisoc/architecture/integration-matrix.md": (1, _PLAN),+ "plans/cyble-aisoc/platform/CONTRIBUTING-DETECTIONS.md": (1, _PLAN),+ "plans/cyble-aisoc/platform/backend/app/api/routes.py": (1, _PLAN),+ "plans/cyble-aisoc/platform/backend/app/marketplace/catalog.py": (16, _PLAN),+ # --- the regression assertion itself -----------------------------------+ "services/api/tests/test_tenant_provision.py": (1, _GATE_FIXTURE),+}+++class GateError(RuntimeError):+ """Raised when the gate cannot trust its own inputs."""+++def resolve_repo_root(explicit: str | None) -> Path:+ """Resolve the tree to inspect, never from this file's own location.++ Deriving the root from ``__file__`` makes the gate describe the checkout it+ happens to live in rather than the one being tested, so a run from another+ worktree reports OK about a tree it never opened.+ """+ if explicit:+ root = Path(explicit).resolve()+ else:+ try:+ out = subprocess.run(+ ["git", "rev-parse", "--show-toplevel"],+ capture_output=True,+ text=True,+ check=True,+ )+ except (OSError, subprocess.CalledProcessError) as exc:+ raise GateError(f"cannot resolve a git repository from {Path.cwd()}: {exc}") from exc+ root = Path(out.stdout.strip()).resolve()++ missing = [s for s in SENTINELS if not (root / s).exists()]+ if missing:+ raise GateError(f"{root} does not look like the AiSOC repository (missing: {', '.join(missing)})")+ return root+++def tracked_files(root: Path) -> list[str]:+ out = subprocess.run(+ ["git", "-C", str(root), "ls-files", "-z"],+ capture_output=True,+ text=True,+ check=True,+ )+ return [p for p in out.stdout.split("\0") if p]+++def count_in_text(text: str) -> int:+ return text.count(HOSTED_HOSTNAME)+++def scan(root: Path, paths: list[str]) -> dict[str, int]:+ """Occurrences of the hostname per path, skipping self-referential files."""+ found: dict[str, int] = {}+ for rel in paths:+ if rel in SELF_REFERENTIAL:+ continue+ try:+ text = (root / rel).read_text(encoding="utf-8", errors="ignore")+ except (OSError, ValueError):+ continue+ n = count_in_text(text)+ if n:+ found[rel] = n+ return found+++def compare(found: dict[str, int], allowed: dict[str, tuple[int, str]]) -> list[str]:+ """Both directions. Returns a list of failure lines; empty means clean."""+ problems: list[str] = []++ # Direction 1: tree -> allow-list. New or grown leaks.+ for rel, n in sorted(found.items()):+ if rel not in allowed:+ problems.append(f"NEW LEAK {rel}: {n} occurrence(s) of {HOSTED_HOSTNAME}, no allow-list entry")+ elif n > allowed[rel][0]:+ problems.append(f"GREW {rel}: {n} occurrence(s), allow-list records {allowed[rel][0]}")++ # Direction 2: allow-list -> tree. Stale exemptions that would silently+ # grant permission to a file that could regain a leak later.+ for rel, (expected, _reason) in sorted(allowed.items()):+ actual = found.get(rel, 0)+ if actual == 0:+ problems.append(f"STALE EXEMPTION {rel}: allow-list records {expected}, file has none (or is gone) — drop the entry")+ elif actual < expected:+ problems.append(f"SHRANK {rel}: {actual} occurrence(s), allow-list records {expected} — lower the number")++ return problems+++def check_cors_copies(root: Path) -> list[str]:+ """The vendored CORS helper must stay byte-identical across services."""+ digests: dict[str, str] = {}+ problems: list[str] = []+ for rel in CORS_COPIES:+ path = root / rel+ if not path.exists():+ problems.append(f"CORS COPY MISSING {rel}")+ continue+ digests[rel] = hashlib.sha256(path.read_bytes()).hexdigest()+ if len(set(digests.values())) > 1:+ problems.append(+ "CORS COPIES DIFFER — the shared helper is vendored byte-identical; "+ "a drifted copy lets one service keep a different origin allow-list:"+ )+ for rel, digest in sorted(digests.items()):+ problems.append(f" {digest[:12]} {rel}")+ return problems+++def self_test() -> int:+ """Prove the gate detects a known-bad sample and rejects a vacuous pass."""+ failures: list[str] = []++ bad = f"const DEFAULT = 'https://{HOSTED_HOSTNAME}/api';"+ good = "const DEFAULT = 'http://localhost:3000/api';"++ if count_in_text(bad) != 1:+ failures.append(f"detector missed a known-bad sample: {bad!r}")+ if count_in_text(good) != 0:+ failures.append(f"detector flagged a known-good sample: {good!r}")++ # A known-bad file with no allow-list entry must be reported.+ if not compare({"some/new/file.ts": 1}, {}):+ failures.append("compare() passed a file containing the hostname with no allow-list entry")++ # A stale allow-list entry must be reported — the reverse direction that a+ # one-directional gate would miss.+ if not compare({}, {"gone/file.ts": (1, "stale")}):+ failures.append("compare() passed an allow-list entry with no matching occurrence")++ # Counts must be pinned in both directions, not just as a ceiling.+ if not compare({"f.ts": 2}, {"f.ts": (1, "x")}):+ failures.append("compare() passed an occurrence count above the allow-listed number")+ if not compare({"f.ts": 1}, {"f.ts": (2, "x")}):+ failures.append("compare() passed an occurrence count below the allow-listed number")++ # And the happy path must actually be reachable, or every check above is+ # satisfied by a function that just always fails.+ if compare({"f.ts": 1}, {"f.ts": (1, "x")}):+ failures.append("compare() failed an exactly-matching allow-list entry")++ if failures:+ print("self-test FAILED:")+ for line in failures:+ print(f" - {line}")+ return 1++ print(f"self-test OK — detector separates known-bad from known-good and compare() is bidirectional ({HOSTED_HOSTNAME})")+ return 0+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--repo-root", default=None, help="tree to inspect (default: git toplevel of the working directory)")+ parser.add_argument("--self-test", action="store_true", help="prove the gate is not vacuous, then exit")+ args = parser.parse_args()++ if args.self_test:+ return self_test()++ try:+ root = resolve_repo_root(args.repo_root)+ except GateError as exc:+ print(f"FAIL: {exc}")+ return 2++ paths = tracked_files(root)+ # Print what was inspected. A gate that does not say which tree it read is+ # one worktree away from a confident, meaningless OK.+ print(f"scanning {len(paths)} tracked files under {root}")++ if len(paths) < MIN_FILES_SCANNED:+ print(f"FAIL: only {len(paths)} tracked files found (expected >= {MIN_FILES_SCANNED}); the scan is broken, not the tree clean")+ return 2++ found = scan(root, paths)+ if not found:+ print(f"FAIL: zero occurrences of {HOSTED_HOSTNAME} anywhere in {len(paths)} files.")+ print(" The managed-instance deploy configs legitimately contain it, so this")+ print(" means the pattern or the file walk broke — not that the tree is clean.")+ return 2++ problems = compare(found, ALLOWED) + check_cors_copies(root)++ if problems:+ print(f"\nFAIL: {len(problems)} problem(s).\n")+ for line in problems:+ print(f" {line}")+ print(+ "\nIf an occurrence is a real leak, give it a deployment-neutral default.\n"+ "If it legitimately describes the managed offering, add or move its entry\n"+ "in ALLOWED with a reason. Never raise a number to make this pass without\n"+ "reading the occurrence it covers."+ )+ return 1++ total = sum(found.values())+ print(f"OK — {total} occurrence(s) across {len(found)} file(s), every one allow-listed with a reason")+ print(f"OK — {len(CORS_COPIES)} vendored cors.py copies are byte-identical")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/services/actions/app/executors/base.py b/services/actions/app/executors/base.pyindex f5a218869..58c8e8c82 100644--- a/services/actions/app/executors/base.py+++ b/services/actions/app/executors/base.py@@ -18,7 +18,7 @@ __all__ = ["BaseExecutor", "ActionRequest", "ActionResult", "_SIM_FUNNEL_CTA"]# the AiSOC maintainers can co-author and review the new integration._SIM_FUNNEL_CTA: str = (" | To wire in a live integration, see the Plugin SDK: "- "https://docs.tryaisoc.com/plugins/overview"+ "https://beenuar.github.io/AiSOC/docs/plugins/overview"" | Want this integration co-authored? Open a request: ""https://github.com/beenuar/AiSOC/issues/new""?labels=connector-request&template=connector_request.md"diff --git a/services/agents/app/core/cors.py b/services/agents/app/core/cors.pyindex 3f54f6cb3..fe2e48653 100644--- a/services/agents/app/core/cors.py+++ b/services/agents/app/core/cors.py@@ -22,9 +22,12 @@ The allow-list is resolved from environment variables, in priority order:3. ``default`` argument — service-supplied fallback, or:data:`DEFAULT_CORS_ORIGINS` if not provided.-The defaults cover local development (``localhost:3000`` / ``:3001`` and the-``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything-beyond that should be set explicitly per deployment.+The defaults cover local development only (``localhost:3000`` / ``:3001`` and+the ``127.0.0.1`` aliases). Every deployed origin — including the maintainers'+hosted console — is expected to set ``AISOC_CORS_ORIGINS`` explicitly. Shipping+a specific deployment's public origin in the default allow-list would make every+self-hosted install trust that third-party origin for credentialed cross-origin+requests, which is not a decision an operator opted into.Production guard----------------@@ -51,8 +54,6 @@ DEFAULT_CORS_ORIGINS: tuple[str, ...] = ("http://localhost:3001","http://127.0.0.1:3000","http://127.0.0.1:3001",- "https://tryaisoc.com",- "https://www.tryaisoc.com",)# Used when ``allow_credentials`` is True. The CORS spec refuses the responsediff --git a/services/api/app/api/v1/dev_auth.py b/services/api/app/api/v1/dev_auth.pyindex f55b3789d..e120e496a 100644--- a/services/api/app/api/v1/dev_auth.py+++ b/services/api/app/api/v1/dev_auth.py@@ -28,9 +28,17 @@ from app.core.config import current_env_from_os, is_auth_bypass_env# Deterministic demo IDs — kept in sync with seed_demo.pyDEMO_TENANT_ID: uuid.UUID = uuid.UUID("00000000-0000-0000-0000-000000000001")DEMO_USER_ID: uuid.UUID = uuid.UUID("00000000-0000-0000-0000-000000000002")-# Use a real TLD (not `.local`, which is reserved for mDNS and rejected by-# pydantic ``EmailStr``). Deterministic, public-demo-only credentials.-DEMO_USER_EMAIL: str = "[email protected]"+# Deterministic, demo-only credentials. ``example.com`` is reserved by+# RFC 2606 for exactly this: it is valid to ``pydantic.EmailStr`` (unlike+# `.local`, which is reserved for mDNS and rejected), can never be registered+# by anyone, and can never receive mail. A previous value used a real,+# operator-owned domain, which published a well-known login paired with a+# well-known password against a live domain and told self-hosters to type+# somebody else's hostname to sign in to their own install.+#+# Changing this is safe to re-run: ``seed_demo._ensure_user`` reconciles on+# ``DEMO_USER_ID`` (not on the address) and rewrites a stale email in place.+DEMO_USER_EMAIL: str = "[email protected]"DEMO_USER_PASSWORD: str = "aisoc-demo"DEMO_USER_ROLE: str = "admin"diff --git a/services/api/app/api/v1/endpoints/oauth.py b/services/api/app/api/v1/endpoints/oauth.pyindex 582a321f0..87836adae 100644--- a/services/api/app/api/v1/endpoints/oauth.py+++ b/services/api/app/api/v1/endpoints/oauth.py@@ -274,7 +274,7 @@ def _resolve_redirect_uri() -> str:detail=("Hosted OAuth is not configured. Operator must set ""OAUTH_PUBLIC_BASE_URL to the public URL of this API "- "service (e.g. https://api.tryaisoc.com)."+ "service (e.g. https://api.example.com)."),)return f"{base}/api/v1/oauth/callback"diff --git a/services/api/app/api/v1/endpoints/replay.py b/services/api/app/api/v1/endpoints/replay.pyindex 8da12fbfe..4d6493126 100644--- a/services/api/app/api/v1/endpoints/replay.py+++ b/services/api/app/api/v1/endpoints/replay.py@@ -1,7 +1,8 @@"""Public investigation-replay publishing — v8 W3.Turns a tenant-private investigation ledger into an immutable, redacted, public-share link at ``tryaisoc.com/r/<slug>``.+share link at ``<console-base>/r/<slug>``, where the console base comes from+``CONSOLE_PUBLIC_BASE_URL`` (see :func:`app.core.config.console_base_url`).Flow:@@ -35,6 +36,7 @@ from pydantic import BaseModel, Fieldfrom sqlalchemy import select, updatefrom app.api.v1.deps import AuthUser, DBSession, require_permission+from app.core.config import console_base_urlfrom app.db.rls import TenantDBSessionfrom app.models.investigation import InvestigationEvent, InvestigationRunfrom app.models.published_replay import PublishedReplay@@ -46,7 +48,15 @@ logger = structlog.get_logger()router = APIRouter(prefix="/ledger", tags=["replay"])public_router = APIRouter(prefix="/r", tags=["replay-public"])-_PUBLIC_BASE = "https://tryaisoc.com/r"++def _public_base() -> str:+ """Origin for published share links, resolved per call.++ Deliberately a function, not a module constant: the constant was baked in+ at import time and hard-coded one deployment's hostname, so every+ self-hosted install handed out share links into somebody else's console.+ """+ return f"{console_base_url()}/r"class PublishPreview(BaseModel):@@ -206,7 +216,7 @@ async def publish_replay(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)+ return PublishResult(slug=slug, url=f"{_public_base()}/{slug}", run_id=run_id, created_at=row.created_at)@router.get("/{run_id}/published", response_model=list[PublishedSummary])@@ -229,7 +239,7 @@ async def list_published(return [PublishedSummary(slug=r.slug,- url=f"{_PUBLIC_BASE}/{r.slug}",+ url=f"{_public_base()}/{r.slug}",title=r.title,case_id=r.case_id,view_count=r.view_count,diff --git a/services/api/app/api/v1/endpoints/tenant_provision.py b/services/api/app/api/v1/endpoints/tenant_provision.pyindex 1591b0148..7ff7b7fd5 100644--- a/services/api/app/api/v1/endpoints/tenant_provision.py+++ b/services/api/app/api/v1/endpoints/tenant_provision.py@@ -39,6 +39,7 @@ from sqlalchemy.exc import SQLAlchemyErrorfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.api.v1.deps import AuthUser, DBSession+from app.core.config import console_base_urlfrom app.models.tenant import Tenantfrom app.services.tenant_provision import (ProvisioningError,@@ -59,7 +60,6 @@ router = APIRouter(prefix="/admin/tenants", tags=["admin", "tenants"])# ---------------------------------------------------------------------------_MAX_LIST_LIMIT: int = 500-_DEFAULT_INVITE_BASE_URL: str = "https://tryaisoc.com"# ---------------------------------------------------------------------------@@ -217,9 +217,7 @@ async def provision_tenant("""await _require_admin(user, db)- invite_base = (payload.invite_base_url or _DEFAULT_INVITE_BASE_URL).strip()- if not invite_base:- invite_base = _DEFAULT_INVITE_BASE_URL+ invite_base = (payload.invite_base_url or "").strip() or console_base_url()try:result = await provision_from_waitlist(diff --git a/services/api/app/core/config.py b/services/api/app/core/config.pyindex edb7ede2d..9a239b4b2 100644--- a/services/api/app/core/config.py+++ b/services/api/app/core/config.py@@ -200,23 +200,33 @@ class Settings(BaseSettings):# Public ingest base URL — surfaced in the wizard's "Reveal push URL"# response so operators get a copy-pasteable curl example. Empty# falls back to a relative path; production deployments should- # always set this (e.g. https://ingest.tryaisoc.com).+ # always set this (e.g. https://ingest.example.com).INGEST_PUBLIC_URL: str = ""# Public base URL for the API service, used to build the OAuth# ``redirect_uri`` advertised to upstream identity providers. Must be# registered verbatim in each tenant's OAuth app. In production this- # is e.g. ``https://api.tryaisoc.com``; the callback path+ # is e.g. ``https://api.example.com``; the callback path# ``/api/v1/oauth/callback`` is appended automatically. Empty# disables the hosted OAuth flow (start endpoint returns 503).OAUTH_PUBLIC_BASE_URL: str = ""- # Public base URL of the analyst console — used as the default- # ``return_to`` after a successful OAuth callback so the operator- # lands back on /onboarding with the verify-data-flowing screen- # already polling. Empty falls back to a relative path.+ # Public base URL of the analyst console (e.g. https://soc.example.com) —+ # used as the default ``return_to`` after a successful OAuth callback so+ # the operator lands back on /onboarding with the verify-data-flowing+ # screen already polling, and as the origin of published replay share+ # links. Empty falls back to this install's own local console rather than+ # to any particular deployment's hostname.CONSOLE_PUBLIC_BASE_URL: str = ""+ # Deployment-neutral fallback for operator-facing absolute URLs+ # (published replay links, tenant invite links) when+ # ``CONSOLE_PUBLIC_BASE_URL`` is unset. Never hard-code a specific+ # deployment's hostname here: a self-hosted install that emits share or+ # invite links pointing at somebody else's console is a real leak, not a+ # cosmetic one.+ DEFAULT_CONSOLE_BASE_URL: str = "http://localhost:3000"+# Workstream 5 (self-healing) — auto OAuth refresh worker. The# background loop runs inside the API process (``lifespan`` hook in# main.py) and rotates expiring access_tokens for every connector@@ -374,8 +384,6 @@ class Settings(BaseSettings):CORS_ORIGINS: list[str] = ["http://localhost:3000","http://localhost:3001",- "https://tryaisoc.com",- "https://www.tryaisoc.com",]# Observability@@ -850,6 +858,19 @@ def is_production(env: str | None) -> bool:return (env or "").strip().lower() == "production"+def console_base_url(s: Settings | None = None) -> str:+ """Resolve the console origin used to build operator-facing absolute URLs.++ Single source of truth for published-replay share links and tenant invite+ links. Both used to carry their own hard-coded literal, which is how they+ drifted apart *and* how a specific deployment's hostname ended up in links+ handed to self-hosted operators. Routing both through here means a future+ change can only move them together.+ """+ s = s or settings+ return ((s.CONSOLE_PUBLIC_BASE_URL or "").strip() or s.DEFAULT_CONSOLE_BASE_URL).rstrip("/")++class InsecureProductionDefaultsError(RuntimeError):"""Raised at boot when insecure defaults remain in a production deploy."""diff --git a/services/api/app/core/cors.py b/services/api/app/core/cors.pyindex 3f54f6cb3..fe2e48653 100644--- a/services/api/app/core/cors.py+++ b/services/api/app/core/cors.py@@ -22,9 +22,12 @@ The allow-list is resolved from environment variables, in priority order:3. ``default`` argument — service-supplied fallback, or:data:`DEFAULT_CORS_ORIGINS` if not provided.-The defaults cover local development (``localhost:3000`` / ``:3001`` and the-``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything-beyond that should be set explicitly per deployment.+The defaults cover local development only (``localhost:3000`` / ``:3001`` and+the ``127.0.0.1`` aliases). Every deployed origin — including the maintainers'+hosted console — is expected to set ``AISOC_CORS_ORIGINS`` explicitly. Shipping+a specific deployment's public origin in the default allow-list would make every+self-hosted install trust that third-party origin for credentialed cross-origin+requests, which is not a decision an operator opted into.Production guard----------------@@ -51,8 +54,6 @@ DEFAULT_CORS_ORIGINS: tuple[str, ...] = ("http://localhost:3001","http://127.0.0.1:3000","http://127.0.0.1:3001",- "https://tryaisoc.com",- "https://www.tryaisoc.com",)# Used when ``allow_credentials`` is True. The CORS spec refuses the responsediff --git a/services/api/app/middleware/demo_mode.py b/services/api/app/middleware/demo_mode.pyindex a521e58af..2aff8530f 100644--- a/services/api/app/middleware/demo_mode.py+++ b/services/api/app/middleware/demo_mode.py@@ -1,4 +1,4 @@-"""Demo-mode guard for the hosted demo at tryaisoc.com.+"""Demo-mode guard for a public, read-only demo deployment.When `AISOC_DEMO_MODE=true`, this middleware:@@ -104,7 +104,7 @@ class DemoModeMiddleware(BaseHTTPMiddleware):content={"error": "demo_mode_read_only","message": (- "This is the public AiSOC demo at tryaisoc.com. "+ "This AiSOC deployment is running in public demo mode. ""Write actions are disabled here so every visitor sees ""the same dataset. To run AiSOC for real, self-host it ""in 5 minutes — see https://github.com/beenuar/AiSOC."diff --git a/services/api/app/scripts/seed_demo.py b/services/api/app/scripts/seed_demo.pyindex f1b00ab4b..55907ab6b 100644--- a/services/api/app/scripts/seed_demo.py+++ b/services/api/app/scripts/seed_demo.py@@ -8,7 +8,7 @@ Run this from the host (the API container has the package on its PYTHONPATH):The seed is idempotent — running it twice produces the same dataset and neverduplicates rows. Demo IDs are kept in sync with `app/api/v1/dev_auth.py` so the-auth bypass and the seeded data agree on who "[email protected]" is.+auth bypass and the seeded data agree on who "[email protected]" is.Two modes:diff --git a/services/api/app/services/email_approval.py b/services/api/app/services/email_approval.pyindex 67e728931..4844e5877 100644--- a/services/api/app/services/email_approval.py+++ b/services/api/app/services/email_approval.py@@ -262,6 +262,19 @@ class MailDeliveryClient(Protocol):pass+def _default_from_addr(domain: str) -> str:+ """Sender address when ``AISOC_APPROVAL_FROM_ADDR`` is unset.++ Prefer the operator's own Mailgun sending domain: a From address on a+ domain the deployment does not control fails SPF/DKIM and sends approval+ mail that claims to come from someone else. With no domain configured we+ fall back to the RFC 2606 reserved ``example.com``, which is visibly a+ placeholder rather than a real party's address.+ """+ domain = (domain or "").strip().lstrip("@")+ return f"approvals@{domain}" if domain else "[email protected]"++class MailgunClient:"""Minimal Mailgun client. Authenticates with the standard@@ -282,7 +295,7 @@ class MailgunClient:self._api_key = api_key if api_key is not None else os.environ.get("MAILGUN_API_KEY", "")self._domain = domain if domain is not None else os.environ.get("MAILGUN_DOMAIN", "")self._base_url = base_url.rstrip("/")- self._from_addr = from_addr or os.environ.get("AISOC_APPROVAL_FROM_ADDR", "[email protected]")+ self._from_addr = from_addr or os.environ.get("AISOC_APPROVAL_FROM_ADDR", "") or _default_from_addr(self._domain)self._client = client or httpx.AsyncClient(timeout=10.0)async def send(diff --git a/services/api/app/services/tenant_provision/provisioner.py b/services/api/app/services/tenant_provision/provisioner.pyindex 3ea80a10b..6465d0a06 100644--- a/services/api/app/services/tenant_provision/provisioner.py+++ b/services/api/app/services/tenant_provision/provisioner.py@@ -62,6 +62,7 @@ from cryptography.fernet import Fernetfrom sqlalchemy import select, textfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.config import console_base_urlfrom app.models.tenant import Tenant, Userfrom app.models.waitlist import (WAITLIST_STATUS_ONBOARDED,@@ -281,7 +282,7 @@ async def provision_from_waitlist(*,waitlist_entry_id: uuid.UUID,actor_email: str,- invite_base_url: str = "https://tryaisoc.com",+ invite_base_url: str | None = None,seed_demo: bool = True,demo_seeder: DemoSeederCallable | None = None,templates: TenantTemplateBundle | None = None,@@ -301,8 +302,11 @@ async def provision_from_waitlist(actor_emailOperator email; recorded on the audit log line.invite_base_url- Base of the URL the operator will email out. Defaults to the- managed-instance host name.+ Base of the URL the operator will email out. ``None`` resolves to+ :func:`app.core.config.console_base_url` — this install's own console+ origin. It used to carry its own hard-coded literal, which both+ duplicated the caller's default (free to drift apart, the hard part to+ notice) and emitted invite links into a different deployment.seed_demoWhether to call the demo seeder. Test harnesses pass``False`` so the unit tests don't depend on the seed script.@@ -317,6 +321,8 @@ async def provision_from_waitlist(Override for the slug-collision shard generator (used bytests)."""+ invite_base_url = (invite_base_url or "").strip() or console_base_url()+entry = await _load_waitlist_entry(db, waitlist_entry_id)if entry.provisioned_tenant_id is not None:# Idempotent re-provision — return the existing tenant if it'sdiff --git a/services/api/tests/test_case_fanout.py b/services/api/tests/test_case_fanout.pyindex 17238dd61..a69b152c5 100644--- a/services/api/tests/test_case_fanout.py+++ b/services/api/tests/test_case_fanout.py@@ -353,7 +353,7 @@ async def test_fanout_create_case_happy_path_persists_external_ref() -> None:case_row=case,tenant_id=tenant_id,connector_ids=[connector.id],- pushed_by="[email protected]",+ pushed_by="[email protected]",)assert len(results) == 1@@ -566,7 +566,7 @@ async def test_fanout_status_change_happy_path_updates_external_status() -> Nonetenant_id=tenant_id,old_status="open",new_status="resolved",- pushed_by="[email protected]",+ pushed_by="[email protected]",)assert len(results) == 1diff --git a/services/api/tests/test_database_pool.py b/services/api/tests/test_database_pool.pyindex ca9317a21..9ff75da12 100644--- a/services/api/tests/test_database_pool.py+++ b/services/api/tests/test_database_pool.py@@ -3,7 +3,7 @@Without ``pool_pre_ping`` the pool hands out sockets the managed Postgresalready closed (autostop / idle teardown). The next query then raises``asyncpg.exceptions.ConnectionDoesNotExistError``, which is what was-500ing every demo endpoint on tryaisoc.com while ``/health`` still looked+500ing every demo endpoint on the hosted demo while ``/health`` still lookedfine. These tests are import-free (parse the source) so they run in thesame lightweight CI job as the schema-drift guards — no full API dep setrequired.diff --git a/services/api/tests/test_demo_mode.py b/services/api/tests/test_demo_mode.pyindex 82fecd9bd..3dcf0b856 100644--- a/services/api/tests/test_demo_mode.py+++ b/services/api/tests/test_demo_mode.py@@ -177,7 +177,7 @@ def test_auth_login_is_allowed(app: FastAPI) -> None:def test_waitlist_signup_is_allowed(app: FastAPI) -> None:"""Managed-instance waitlist must accept signups on the public demo host.- ``/waitlist`` is the conversion funnel for tryaisoc.com. Demo-mode must+ ``/waitlist`` is the managed-instance conversion funnel. Demo-mode mustnot 403 the POST — waitlist rows are not part of the shared demo SOCdataset, so allowing the write does not let visitors mutate the cannedalerts/cases every other visitor sees.@@ -203,7 +203,7 @@ def test_options_preflight_is_allowed(app: FastAPI) -> None:client = TestClient(app)r = client.options("/api/v1/cases",- headers={"Origin": "https://tryaisoc.com", "Access-Control-Request-Method": "GET"},+ headers={"Origin": "https://soc.example.com", "Access-Control-Request-Method": "GET"},)# FastAPI's TestClient + CORSMiddleware would normally answer this; without# CORSMiddleware it 405s, but the demo-mode middleware itself never blocksdiff --git a/services/api/tests/test_tenant_provision.py b/services/api/tests/test_tenant_provision.pyindex 7bdd97e26..0a942cd5d 100644--- a/services/api/tests/test_tenant_provision.py+++ b/services/api/tests/test_tenant_provision.py@@ -27,6 +27,7 @@ from typing import Anyimport pytestfrom app.api.v1.endpoints import tenant_provision as endpoint+from app.core.config import console_base_urlfrom app.models.tenant import Tenant, Userfrom app.models.waitlist import (WAITLIST_STATUS_DECLINED,@@ -78,7 +79,7 @@ def _admin_user(*, allow: bool = True) -> SimpleNamespace:user_id=uuid.uuid4(),tenant_id=uuid.uuid4(),role="tenant_admin",- email="[email protected]",+ email="[email protected]",has_permission_db=_check,)@@ -299,7 +300,7 @@ class TestAdminInviteBuilder:def test_invite_url_contains_tenant_slug(self) -> None:invite = _build_admin_invite(tenant_slug="acme",- invite_base_url="https://tryaisoc.com",+ invite_base_url="https://soc.example.com",)assert "acme" in invite.urlassert "/invite/" in invite.url@@ -308,7 +309,7 @@ class TestAdminInviteBuilder:def test_expires_after_one_week_by_default(self) -> None:invite = _build_admin_invite(tenant_slug="acme",- invite_base_url="https://tryaisoc.com",+ invite_base_url="https://soc.example.com",)delta = invite.expires_at - datetime.now(UTC).replace(microsecond=0)assert delta.total_seconds() > 6 * 24 * 3600@@ -317,10 +318,10 @@ class TestAdminInviteBuilder:def test_base_url_trailing_slash_normalized(self) -> None:invite = _build_admin_invite(tenant_slug="acme",- invite_base_url="https://tryaisoc.com///",+ invite_base_url="https://soc.example.com///",)- assert "https://tryaisoc.com/invite/" in invite.url- assert "https://tryaisoc.com////invite/" not in invite.url+ assert "https://soc.example.com/invite/" in invite.url+ assert "https://soc.example.com////invite/" not in invite.urldef test_zero_ttl_rejected(self) -> None:with pytest.raises(ValueError):@@ -342,7 +343,7 @@ class TestProvisionFromWaitlist:provision_from_waitlist(session, # type: ignore[arg-type]waitlist_entry_id=entry.id,- actor_email="[email protected]",+ actor_email="[email protected]",seed_demo=False,))@@ -375,7 +376,7 @@ class TestProvisionFromWaitlist:provision_from_waitlist(session, # type: ignore[arg-type]waitlist_entry_id=entry.id,- actor_email="[email protected]",+ actor_email="[email protected]",seed_demo=False,))@@ -410,7 +411,7 @@ class TestProvisionFromWaitlist:provision_from_waitlist(session, # type: ignore[arg-type]waitlist_entry_id=entry.id,- actor_email="[email protected]",+ actor_email="[email protected]",seed_demo=False,shard_factory=lambda: "abc123",)@@ -443,7 +444,7 @@ class TestProvisionFromWaitlist:provision_from_waitlist(session, # type: ignore[arg-type]waitlist_entry_id=entry.id,- actor_email="[email protected]",+ actor_email="[email protected]",seed_demo=False,shard_factory=lambda: next(shards),)@@ -456,7 +457,7 @@ class TestProvisionFromWaitlist:provision_from_waitlist(session, # type: ignore[arg-type]waitlist_entry_id=uuid.uuid4(),- actor_email="[email protected]",+ actor_email="[email protected]",seed_demo=False,))@@ -470,7 +471,7 @@ class TestProvisionFromWaitlist:provision_from_waitlist(session, # type: ignore[arg-type]waitlist_entry_id=entry.id,- actor_email="[email protected]",+ actor_email="[email protected]",seed_demo=False,))@@ -514,7 +515,7 @@ class TestProvisionFromWaitlist:provision_from_waitlist(session, # type: ignore[arg-type]waitlist_entry_id=entry.id,- actor_email="[email protected]",+ actor_email="[email protected]",seed_demo=False,))@@ -540,7 +541,7 @@ class TestProvisionFromWaitlist:provision_from_waitlist(session, # type: ignore[arg-type]waitlist_entry_id=entry.id,- actor_email="[email protected]",+ actor_email="[email protected]",seed_demo=True,demo_seeder=_stub_seeder,)@@ -561,7 +562,7 @@ class TestProvisionFromWaitlist:provision_from_waitlist(session, # type: ignore[arg-type]waitlist_entry_id=entry.id,- actor_email="[email protected]",+ actor_email="[email protected]",seed_demo=True,demo_seeder=_broken_seeder,)@@ -592,7 +593,13 @@ class TestProvisionEndpoint:)assert response.tenant_slug == "acme-inc"assert response.admin_user.email == entry.email- assert response.admin_invite.url.startswith("https://tryaisoc.com/invite/")+ # No invite_base_url on the request, so this exercises the *default*.+ # It previously asserted a specific deployment's hostname, which meant+ # the suite encoded the leak as the expected behaviour: every+ # self-hosted install emailed invite links into somebody else's+ # console and the tests agreed that was correct.+ assert response.admin_invite.url.startswith(f"{console_base_url()}/invite/")+ assert "tryaisoc.com" not in response.admin_invite.urlassert response.aisoc_credential_key_fingerprint != ""assert session.commit_calls == 1@@ -652,13 +659,13 @@ class TestProvisionEndpoint:endpoint.TenantProvisionRequest(waitlist_entry_id=entry.id,seed_demo=False,- invite_base_url="https://staging.tryaisoc.com",+ invite_base_url="https://staging.example.com",),session, # type: ignore[arg-type]user,))- assert response.admin_invite.url.startswith("https://staging.tryaisoc.com/invite/")+ assert response.admin_invite.url.startswith("https://staging.example.com/invite/")class TestListTenantsEndpoint:diff --git a/services/connectors/app/security/cors.py b/services/connectors/app/security/cors.pyindex 3f54f6cb3..fe2e48653 100644--- a/services/connectors/app/security/cors.py+++ b/services/connectors/app/security/cors.py@@ -22,9 +22,12 @@ The allow-list is resolved from environment variables, in priority order:3. ``default`` argument — service-supplied fallback, or:data:`DEFAULT_CORS_ORIGINS` if not provided.-The defaults cover local development (``localhost:3000`` / ``:3001`` and the-``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything-beyond that should be set explicitly per deployment.+The defaults cover local development only (``localhost:3000`` / ``:3001`` and+the ``127.0.0.1`` aliases). Every deployed origin — including the maintainers'+hosted console — is expected to set ``AISOC_CORS_ORIGINS`` explicitly. Shipping+a specific deployment's public origin in the default allow-list would make every+self-hosted install trust that third-party origin for credentialed cross-origin+requests, which is not a decision an operator opted into.Production guard----------------@@ -51,8 +54,6 @@ DEFAULT_CORS_ORIGINS: tuple[str, ...] = ("http://localhost:3001","http://127.0.0.1:3000","http://127.0.0.1:3001",- "https://tryaisoc.com",- "https://www.tryaisoc.com",)# Used when ``allow_credentials`` is True. The CORS spec refuses the responsediff --git a/services/enrichment/internal/server/server.go b/services/enrichment/internal/server/server.goindex 12a5f16da..9aa781a95 100644--- a/services/enrichment/internal/server/server.go+++ b/services/enrichment/internal/server/server.go@@ -39,8 +39,6 @@ func resolveCORSOrigins() []string {"http://localhost:3001","http://127.0.0.1:3000","http://127.0.0.1:3001",- "https://tryaisoc.com",- "https://www.tryaisoc.com",}}diff --git a/services/honeytokens/app/core/cors.py b/services/honeytokens/app/core/cors.pyindex 3f54f6cb3..fe2e48653 100644--- a/services/honeytokens/app/core/cors.py+++ b/services/honeytokens/app/core/cors.py@@ -22,9 +22,12 @@ The allow-list is resolved from environment variables, in priority order:3. ``default`` argument — service-supplied fallback, or:data:`DEFAULT_CORS_ORIGINS` if not provided.-The defaults cover local development (``localhost:3000`` / ``:3001`` and the-``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything-beyond that should be set explicitly per deployment.+The defaults cover local development only (``localhost:3000`` / ``:3001`` and+the ``127.0.0.1`` aliases). Every deployed origin — including the maintainers'+hosted console — is expected to set ``AISOC_CORS_ORIGINS`` explicitly. Shipping+a specific deployment's public origin in the default allow-list would make every+self-hosted install trust that third-party origin for credentialed cross-origin+requests, which is not a decision an operator opted into.Production guard----------------@@ -51,8 +54,6 @@ DEFAULT_CORS_ORIGINS: tuple[str, ...] = ("http://localhost:3001","http://127.0.0.1:3000","http://127.0.0.1:3001",- "https://tryaisoc.com",- "https://www.tryaisoc.com",)# Used when ``allow_credentials`` is True. The CORS spec refuses the responsediff --git a/services/ingest/internal/inbox/handler.go b/services/ingest/internal/inbox/handler.goindex 7af808ded..6d1181171 100644--- a/services/ingest/internal/inbox/handler.go+++ b/services/ingest/internal/inbox/handler.go@@ -89,7 +89,7 @@ var (// ServeJSON handles POST /v1/inbox/{tenant_token}.//// This is the workhorse route — vendors paste in a webhook URL of-// the form https://ingest.tryaisoc.com/v1/inbox/<token>, and whatever+// the form https://ingest.example.com/v1/inbox/<token>, and whatever// JSON they send gets translated by the template the operator picked// at mint time.//diff --git a/services/ingest/internal/normalizer/templates/email-forwarded.yaml b/services/ingest/internal/normalizer/templates/email-forwarded.yamlindex 4b3c44281..816963c8a 100644--- a/services/ingest/internal/normalizer/templates/email-forwarded.yaml+++ b/services/ingest/internal/normalizer/templates/email-forwarded.yaml@@ -6,7 +6,7 @@# the shape:# {# "from": "[email protected]",-# "to": "[email protected]",+# "to": "[email protected]",# "subject": "...",# "text": "...plain text body...",# "html": "...html body...",diff --git a/services/ingest/internal/server/server.go b/services/ingest/internal/server/server.goindex 42af625b9..f6eef27d1 100644--- a/services/ingest/internal/server/server.go+++ b/services/ingest/internal/server/server.go@@ -47,8 +47,6 @@ func resolveCORSOrigins() []string {"http://localhost:3001","http://127.0.0.1:3000","http://127.0.0.1:3001",- "https://tryaisoc.com",- "https://www.tryaisoc.com",}}@@ -86,7 +84,8 @@ func New(cfg *config.Config, h *handler.Handler, inboxHandler *inbox.Handler, grr.Use(middleware.Recoverer)r.Use(middleware.Timeout(30 * time.Second))// Allow-list is resolved from AISOC_CORS_ORIGINS (canonical) / CORS_ORIGINS- // (legacy) with a safe default for local dev + the tryaisoc.com console.+ // (legacy) with a safe default that covers local dev only; deployed+ // origins are expected to set the env var.// AllowCredentials stays false here — /v1/ingest is token-authenticated// per request, not session-cookie-authenticated, so we don't need the// browser to attach cookies cross-origin and we keep the spec-mandateddiff --git a/services/osquery-tls/app/core/config.py b/services/osquery-tls/app/core/config.pyindex 583ce8332..5303f5570 100644--- a/services/osquery-tls/app/core/config.py+++ b/services/osquery-tls/app/core/config.py@@ -37,8 +37,10 @@ class Settings(BaseSettings):require_client_cert: bool = False# --- Service identity ------------------------------------------------ # Public hostname (used to build TLS flag-file docs).- public_hostname: str = "osquery.tryaisoc.com"+ # Public hostname operators point agents' ``--tls_hostname`` at. Set this+ # per deployment. Declared but not yet read anywhere in this service —+ # flag-file rendering still has to be wired up.+ public_hostname: str = "localhost"# --- Pack stubs (overridden fully in PR5) ---------------------------# Default query interval for the baseline schedule shipped to every node.diff --git a/services/purple-team/app/core/cors.py b/services/purple-team/app/core/cors.pyindex 3f54f6cb3..fe2e48653 100644--- a/services/purple-team/app/core/cors.py+++ b/services/purple-team/app/core/cors.py@@ -22,9 +22,12 @@ The allow-list is resolved from environment variables, in priority order:3. ``default`` argument — service-supplied fallback, or:data:`DEFAULT_CORS_ORIGINS` if not provided.-The defaults cover local development (``localhost:3000`` / ``:3001`` and the-``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything-beyond that should be set explicitly per deployment.+The defaults cover local development only (``localhost:3000`` / ``:3001`` and+the ``127.0.0.1`` aliases). Every deployed origin — including the maintainers'+hosted console — is expected to set ``AISOC_CORS_ORIGINS`` explicitly. Shipping+a specific deployment's public origin in the default allow-list would make every+self-hosted install trust that third-party origin for credentialed cross-origin+requests, which is not a decision an operator opted into.Production guard----------------@@ -51,8 +54,6 @@ DEFAULT_CORS_ORIGINS: tuple[str, ...] = ("http://localhost:3001","http://127.0.0.1:3000","http://127.0.0.1:3001",- "https://tryaisoc.com",- "https://www.tryaisoc.com",)# Used when ``allow_credentials`` is True. The CORS spec refuses the responsediff --git a/services/realtime/src/index.ts b/services/realtime/src/index.tsindex a1c97b94a..91c071283 100644--- a/services/realtime/src/index.ts+++ b/services/realtime/src/index.ts@@ -36,7 +36,7 @@ const PUSH_REDIS = new Redis(REDIS_URL);// Mirror the shared Python helper in services/api/app/core/cors.py:// 1. AISOC_CORS_ORIGINS (canonical, comma-separated)// 2. CORS_ORIGINS (legacy alias kept for Helm charts / dev scripts)-// 3. Default allow-list (local dev + tryaisoc.com)+// 3. Default allow-list (local dev only — deployed origins set the env var)// SSE + WebSocket connections from the console carry the auth cookie, so// allow_credentials is effectively in play here. If an operator sets the// allow-list to "*" we refuse to start in production rather than silently@@ -46,8 +46,6 @@ const DEFAULT_CORS_ORIGINS = ['http://localhost:3001','http://127.0.0.1:3000','http://127.0.0.1:3001',- 'https://tryaisoc.com',- 'https://www.tryaisoc.com',];function resolveCorsOrigins(): string[] {diff --git a/services/teams-bot/pyproject.toml b/services/teams-bot/pyproject.tomlindex d57205cd1..fd7498a5c 100644--- a/services/teams-bot/pyproject.toml+++ b/services/teams-bot/pyproject.toml@@ -2,7 +2,7 @@name = "aisoc-teams-bot"version = "0.1.0"description = "AiSOC Teams bot — Adaptive Card approval flows for ChatOps-driven SOC operations"-authors = ["AiSOC Contributors <[email protected]>"]+authors = ["AiSOC Contributors"]license = "MIT"packages = [{ include = "app" }]diff --git a/services/ueba/app/core/cors.py b/services/ueba/app/core/cors.pyindex 3f54f6cb3..fe2e48653 100644--- a/services/ueba/app/core/cors.py+++ b/services/ueba/app/core/cors.py@@ -22,9 +22,12 @@ The allow-list is resolved from environment variables, in priority order:3. ``default`` argument — service-supplied fallback, or:data:`DEFAULT_CORS_ORIGINS` if not provided.-The defaults cover local development (``localhost:3000`` / ``:3001`` and the-``127.0.0.1`` aliases) and the production console at ``tryaisoc.com``. Anything-beyond that should be set explicitly per deployment.+The defaults cover local development only (``localhost:3000`` / ``:3001`` and+the ``127.0.0.1`` aliases). Every deployed origin — including the maintainers'+hosted console — is expected to set ``AISOC_CORS_ORIGINS`` explicitly. Shipping+a specific deployment's public origin in the default allow-list would make every+self-hosted install trust that third-party origin for credentialed cross-origin+requests, which is not a decision an operator opted into.Production guard----------------@@ -51,8 +54,6 @@ DEFAULT_CORS_ORIGINS: tuple[str, ...] = ("http://localhost:3001","http://127.0.0.1:3000","http://127.0.0.1:3001",- "https://tryaisoc.com",- "https://www.tryaisoc.com",)# Used when ``allow_credentials`` is True. The CORS spec refuses the responsediff --git a/tests/test_hosted_hostname_gate.py b/tests/test_hosted_hostname_gate.pynew file mode 100644index 000000000..3f956c29e--- /dev/null+++ b/tests/test_hosted_hostname_gate.py@@ -0,0 +1,234 @@+"""Tests for the hosted-hostname gate, `scripts/check_hosted_hostname.py`.++The gate exists so a self-hoster never meets another deployment's hostname+presented as their own product's URL. What these tests assert is mostly not+"does it spot the string" — that part is trivial — but the two properties that+made the previous generation of gates in this repo untrustworthy:++ * It must fail in **both** directions. A one-directional allow-list catches a+ new leak but silently keeps an exemption alive after the occurrence it+ covered is gone, and a stale exemption is a standing permit for a future+ leak in a file nobody will look at again.+ * It must be unable to pass **vacuously**. A gate that resolves its repo root+ from its own file location will happily describe the checkout it lives in+ rather than the one under test, and a scan that matches nothing must be+ read as a broken scan, not a clean tree.++The regression cases at the bottom pin the specific defaults that leaked, so+the fix cannot be quietly reverted by an unrelated change.+"""++from __future__ import annotations++import importlib.util+import subprocess+import sys+from pathlib import Path++import pytest++_REPO = Path(__file__).resolve().parents[1]+_SCRIPT = _REPO / "scripts" / "check_hosted_hostname.py"+++def _load_gate():+ spec = importlib.util.spec_from_file_location("check_hosted_hostname", _SCRIPT)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++gate = _load_gate()+HOST = gate.HOSTED_HOSTNAME+++# ── the detector separates bad from good ────────────────────────────────────+++ "sample",+ [+ f'const BASE = "https://{HOST}";',+ f"_PUBLIC_BASE = 'https://{HOST}/r'",+ f'"https://www.{HOST}",',+ f"demo@{HOST}",+ ],+)+def test_detects_known_bad(sample: str) -> None:+ assert gate.count_in_text(sample) >= 1, f"detector missed: {sample!r}"+++ "sample",+ [+ 'const BASE = "http://localhost:3000";',+ "_PUBLIC_BASE = 'http://localhost:3000/r'",+ '"https://soc.example.com",',+ "[email protected]",+ ],+)+def test_ignores_known_good(sample: str) -> None:+ assert gate.count_in_text(sample) == 0, f"detector false-positived: {sample!r}"+++# ── compare() is bidirectional ──────────────────────────────────────────────+++def test_flags_occurrence_with_no_allowlist_entry() -> None:+ """Forward direction: a new leak."""+ assert gate.compare({"new/file.ts": 1}, {})+++def test_flags_allowlist_entry_with_no_occurrence() -> None:+ """Reverse direction — the one a one-directional gate misses.++ The exemption outlives the occurrence that justified it and becomes a+ standing permit for a future leak in that file.+ """+ assert gate.compare({}, {"deleted/file.ts": (1, "reason")})+++def test_flags_count_growth() -> None:+ assert gate.compare({"f.ts": 3}, {"f.ts": (1, "reason")})+++def test_flags_count_shrink() -> None:+ """A ceiling-only check would pass this and let the entry go stale."""+ assert gate.compare({"f.ts": 1}, {"f.ts": (3, "reason")})+++def test_exact_match_passes() -> None:+ """The happy path must be reachable, or every assertion above is satisfied+ by a compare() that simply always fails."""+ assert gate.compare({"f.ts": 2}, {"f.ts": (2, "reason")}) == []+++# ── it cannot pass vacuously ────────────────────────────────────────────────+++def test_self_test_passes() -> None:+ assert gate.self_test() == 0+++def test_rejects_a_tree_that_is_not_this_repo(tmp_path: Path) -> None:+ """A gate pointed at the wrong tree must refuse, not report clean."""+ with pytest.raises(gate.GateError):+ gate.resolve_repo_root(str(tmp_path))+++def test_root_is_not_derived_from_the_scripts_own_location(tmp_path: Path) -> None:+ """Running from elsewhere must not silently inspect the gate's own checkout.++ A sibling gate resolved its root from ``__file__``, so a run launched from+ another worktree printed a confident OK about a tree it never opened.+ """+ proc = subprocess.run(+ [sys.executable, str(_SCRIPT)],+ cwd=tmp_path,+ capture_output=True,+ text=True,+ )+ assert proc.returncode != 0, "gate reported success while run outside any repository"+ assert str(_REPO) not in proc.stdout, "gate fell back to its own checkout instead of failing"+++def test_repo_scan_is_clean() -> None:+ """The real tree passes — and reports a non-empty, plausible scan."""+ proc = subprocess.run(+ [sys.executable, str(_SCRIPT)],+ cwd=str(_REPO),+ capture_output=True,+ text=True,+ )+ assert proc.returncode == 0, proc.stdout + proc.stderr+ assert "scanning" in proc.stdout+ assert "byte-identical" in proc.stdout+++# ── the vendored CORS helper stays in lockstep ──────────────────────────────+++def test_cors_copies_are_byte_identical() -> None:+ digests = {rel: (_REPO / rel).read_bytes() for rel in gate.CORS_COPIES}+ assert len(set(digests.values())) == 1, "vendored cors.py copies have drifted apart"+++_CORS_DEFAULT_DECL = "DEFAULT_CORS_ORIGINS: tuple[str, ...] = ("+++def _cors_default_tuple(text: str) -> str:+ """The literal tuple body, not the docstring that happens to name it.++ An earlier version of this helper split on the bare identifier, which+ matches the prose reference in the module docstring first and so inspected+ a sentence instead of the allow-list. It passed against a tree that did+ ship the hosted origin — a vacuous assertion, caught only by running it+ against the pre-change tree.+ """+ assert _CORS_DEFAULT_DECL in text, "cors.py no longer declares DEFAULT_CORS_ORIGINS as expected"+ return text.split(_CORS_DEFAULT_DECL, 1)[1].split(")", 1)[0]+++def test_cors_default_tuple_extraction_is_not_vacuous() -> None:+ """The helper must read the tuple, and would catch a hostname put back."""+ text = (_REPO / gate.CORS_COPIES[0]).read_text(encoding="utf-8")+ body = _cors_default_tuple(text)+ assert "http://localhost:3000" in body, "helper did not capture the allow-list tuple"+ assert HOST not in body+ # Same helper, against a sample that does carry the hostname.+ poisoned = text.replace(' "http://127.0.0.1:3001",\n)', f' "https://{HOST}",\n)', 1)+ assert HOST in _cors_default_tuple(poisoned), "helper would not notice the hostname coming back"+++def test_no_cors_copy_ships_the_hosted_origin() -> None:+ """Regression: the shipped allow-list trusted one deployment's origin for+ credentialed cross-origin requests on every self-hosted install."""+ for rel in gate.CORS_COPIES:+ body = _cors_default_tuple((_REPO / rel).read_text(encoding="utf-8"))+ assert HOST not in body, f"{rel} ships the hosted origin in its default allow-list"+++# ── regressions on the specific defaults that leaked ────────────────────────+++ ("rel", "needle"),+ [+ # Canonical/OG/sitemap origin for every self-hosted page.+ ("apps/web/src/lib/site.ts", 'return "http://localhost:3000";'),+ # Realtime SSE/WebSocket allow-list.+ ("services/realtime/src/index.ts", "'http://127.0.0.1:3001',\n];"),+ # Seeded demo identity: RFC 2606 reserved, cannot be registered.+ ("services/api/app/api/v1/dev_auth.py", 'DEMO_USER_EMAIL: str = "[email protected]"'),+ # One resolver behind both the replay share link and the tenant invite+ # link, so the two defaults cannot drift apart again.+ ("services/api/app/core/config.py", 'DEFAULT_CONSOLE_BASE_URL: str = "http://localhost:3000"'),+ ],+)+def test_neutral_default_is_present(rel: str, needle: str) -> None:+ assert needle in (_REPO / rel).read_text(encoding="utf-8"), f"{rel} lost its deployment-neutral default"+++ "rel",+ [+ "apps/web/src/lib/site.ts",+ "services/realtime/src/index.ts",+ "services/ingest/internal/server/server.go",+ "services/enrichment/internal/server/server.go",+ "services/api/app/api/v1/dev_auth.py",+ "services/api/app/api/v1/endpoints/replay.py",+ "services/api/app/services/tenant_provision/provisioner.py",+ "services/api/app/services/email_approval.py",+ "services/osquery-tls/app/core/config.py",+ "plugins/aisoc-direct/plugin.yaml",+ "packages/aisoc-action/src/render.ts",+ "packages/aisoc-action/dist/index.js",+ "packages/report-card/src/index.ts",+ "apps/web/public/manifest.json",+ "apps/web/playwright.config.ts",+ ],+)+def test_runtime_default_carries_no_hosted_hostname(rel: str) -> None:+ """Each of these shipped a value an unconfigured self-hoster would hit."""+ assert HOST not in (_REPO / rel).read_text(encoding="utf-8"), f"{rel} regained the hosted hostname"