AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat: add local login for make dev and link the owner at setup (#218)
Rufusa8efeeddf3f9
diff --git a/.env.example b/.env.exampleindex 8c920ed5..ba4e9e20 100644--- a/.env.example+++ b/.env.example@@ -9,6 +9,10 @@ ANTHROPIC_API_KEY=sk-ant-your-key-here# ANTHROPIC_WORKSPACE_ID=# --- Auth (UI: Auth.js / NextAuth v5 with Google) -----------------------------+# Trying it alone? Leave AUTH_GOOGLE_ID blank: `make dev` then uses local+# login — no sign-in, reachable only from this computer, and you+# are the owner (docs/auth.md). Fill in this block to invite your team or to+# run it on a server; `make docker` always needs it.# Generate AUTH_SECRET with: openssl rand -base64 32# AUTH_GOOGLE_ID / AUTH_GOOGLE_SECRET come from a Google Cloud OAuth Client# (Web application). Authorized redirect URIs must include:diff --git a/Makefile b/Makefileindex 0ed162bc..12582121 100644--- a/Makefile+++ b/Makefile@@ -4,7 +4,7 @@ install:cd packages/core && uv synccd packages/ui && npm install-# Both dev recipe lines source the repo-root .env into the process env:+# The dev recipe sources the repo-root .env into the process env of both apps:# - the UI needs it because Next.js only auto-loads packages/ui/.env*, so# Auth.js never saw AUTH_SECRET etc. (issue #44);# - the API needs it because BACKEND_SHARED_SECRET / BACKEND_ALLOWED_ORIGINS@@ -12,10 +12,35 @@ install:# surface them, silently leaving the API gate open.# Note: exported values win over packages/ui/.env.local for duplicate keys.# .env values must be shell-safe: quote anything containing spaces or `$`.+#+# Local login: when Google sign-in isn't set up the UI has no sign-in at+# all, so it binds to 127.0.0.1 (nobody else on the network can reach it), and+# both apps get OE_LOCAL_LOGIN=1: the UI requires it before offering the+# "Open" button, and the API then refuses requests not addressed to this+# computer (DNS rebinding). The flag and the loopback bind must travel+# together — the flag alone would hand the owner's seat to the whole network —+# so this recipe is the only thing that sets it, and otherwise it exports the+# flag EMPTY, which also shadows any value in packages/ui/.env*.+# scripts/devMode.mjs makes the call with the app's own rule over the settings+# the app will see (including packages/ui/.env.local). If AUTH_SECRET is blank+# everywhere, the run gets a throwaway one (you click "Open" again after a+# restart).dev:@echo "Starting Open Executive..."- @if [ -f .env ]; then set -a; . ./.env; set +a; fi; cd packages/core && uv run uvicorn openexecutive.api.main:app --reload --port 8000 &- @if [ -f .env ]; then set -a; . ./.env; set +a; fi; cd packages/ui && npm run dev+ @[ -d packages/ui/node_modules ] || { echo "Installing the web app's packages (first run only)..."; cd packages/ui && npm install; }+ @if [ -f .env ]; then set -a; . ./.env; set +a; fi; \+ mode=$$(cd packages/ui && node --no-warnings --experimental-strip-types scripts/devMode.mjs) || \+ { echo "Could not work out how to start the web app. Open Executive needs Node 22.6 or newer."; exit 1; }; \+ export OE_LOCAL_LOGIN=; ui_host=; \+ if [ "$$mode" != sign-in ]; then \+ echo "Google sign-in is not set up, so this uses local login: open http://localhost:3000 on this computer."; \+ export OE_LOCAL_LOGIN=1; ui_host="-H 127.0.0.1"; \+ fi; \+ if [ "$$mode" = local-login-no-secret ]; then \+ AUTH_SECRET=$$(node -e "process.stdout.write(require('crypto').randomBytes(32).toString('base64'))"); export AUTH_SECRET; \+ fi; \+ (cd packages/core && exec uv run uvicorn openexecutive.api.main:app --reload --port 8000) & \+ cd packages/ui && exec npm run dev -- $$ui_hoststop:@lsof -ti :8000 -ti :3000 2>/dev/null | xargs kill -9 2>/dev/null || truediff --git a/README.md b/README.mdindex 9c389ac6..19071298 100644--- a/README.md+++ b/README.md@@ -107,16 +107,24 @@ openexecutive/git clone https://github.com/SenteLabsAI/OpenExecutive.gitcd OpenExecutive+# Install the backend and web app dependencies+make install+# Set your Anthropic API keycp .env.example .env# Edit .env and add ANTHROPIC_API_KEY=sk-ant-...-# For the web UI's Google sign-in, also fill in the AUTH_* block-# (see docs/auth.md for the Google Cloud Console steps).# Start everythingmake dev```+**Trying it on your own computer needs no sign-in setup.** While+`AUTH_GOOGLE_ID` is blank, `make dev` uses local login: the web app+only accepts connections from this computer, you click **Open**, and you are+the owner. To invite your team, or to run it on a server or with `make docker`,+set up Google sign-in by filling in the `AUTH_*` block (see+[docs/auth.md](docs/auth.md) for the Google Cloud Console steps).+All configuration lives in that repo-root `.env` — `make dev` and `make docker`both load it for the API *and* the UI (Auth.js needs `AUTH_SECRET` /`AUTH_GOOGLE_ID` / `AUTH_GOOGLE_SECRET` at runtime). A@@ -125,7 +133,7 @@ in both files the root `.env` takes precedence.Open http://localhost:3000 to start chatting with your executive. The API runs on port 8000 and the UI on 3000.-> **First run:** requires Python 3.11+ and Node 22+. The initial `uv sync` pulls heavy+> **First run:** requires Python 3.11+ and Node 22.6+. The initial `uv sync` pulls heavy> ML dependencies (ChromaDB + sentence-transformers/PyTorch), and the first boot> downloads a small embedding model (~90 MB) to build the local vector index — so the> first `make dev` takes a few minutes before the app is ready. Subsequent starts are fast.diff --git a/docker/docker-compose.yml b/docker/docker-compose.ymlindex 7728af45..97cb65be 100644--- a/docker/docker-compose.yml+++ b/docker/docker-compose.yml@@ -21,6 +21,10 @@ services:ports:- "127.0.0.1:8000:8000"environment:+ # Local login is `make dev` only. Shadow any OE_LOCAL_LOGIN left in the+ # root .env: it would make the API refuse the UI's requests, which+ # arrive as Host api:8000.+ - OE_LOCAL_LOGIN=- VECTOR_STORE_PATH=/data/chroma_db- COMPANY_PROFILE_PATH=/data/company/profile.yaml- EPISODIC_DB_PATH=/data/episodic_memory.db@@ -60,6 +64,12 @@ services:- AUTH_URL=${AUTH_URL:-}- ALLOWED_EMAILS=${ALLOWED_EMAILS:-}- BACKEND_SHARED_SECRET=${BACKEND_SHARED_SECRET:-}+ # Local login (no sign-in) is `make dev` only: this port is published+ # on every interface. Set explicitly EMPTY because Next.js never lets a+ # dotenv file override a variable that is already set, so this also+ # shadows any OE_LOCAL_LOGIN left in the bind-mounted packages/ui/.env*.+ - OE_LOCAL_LOGIN=+ - OE_PUBLIC_DEPLOYMENT=${OE_PUBLIC_DEPLOYMENT:-}depends_on:- apidiff --git a/docs/auth.md b/docs/auth.mdindex 8908bf50..58afe494 100644--- a/docs/auth.md+++ b/docs/auth.md@@ -1,6 +1,6 @@# Authentication & Access Control-Open Executive is gated behind Google sign-in plus an email allow-list. This doc explains what's protected, how, and how to operate it (add/remove users, rotate secrets, debug failures).+Open Executive is gated behind Google sign-in plus an email allow-list — except with [local login](#local-login-no-google-sign-in), for trying it on your own computer. This doc explains what's protected, how, and how to operate it (add/remove users, rotate secrets, debug failures).---@@ -65,6 +65,45 @@ See [`_UNAUTHENTICATED_PATHS`](../packages/core/openexecutive/api/main.py) — a---+## Local login (no Google sign-in)++While `AUTH_GOOGLE_ID` is blank, `make dev` starts the web app with local+login. The sign-in page shows an **Open** button instead of Google, and whoever+clicks it is the owner (the principal). This is for trying Open Executive on+your own computer; it never runs anywhere else.++There is no password, so the protection is *where* a request can come from:++- **Only `make dev` turns it on.** The same command starts the UI on+ `127.0.0.1`, so other machines on your network cannot connect. It sets+ `OE_LOCAL_LOGIN=1` for the UI; don't set that yourself. It reads the+ same settings the app does (the root `.env` and `packages/ui/.env.local`),+ so if either one sets up Google sign-in, `make dev` starts as usual.+- **Never on a server.** A production build (`next build`, the deploy image)+ compiles the mode out, and it stays off whenever `AUTH_GOOGLE_ID` or+ `OE_PUBLIC_DEPLOYMENT` is set. `make docker` publishes port 3000 to your+ network, so it keeps Google sign-in.+- **Only from this computer's browser.** Signing in, and every request after,+ must be addressed to `localhost`, `127.0.0.1` or `[::1]`, and the API on+ port 8000 applies the same rule. That blocks a malicious website that+ re-points its own name at your computer to reach either one (DNS+ rebinding). Both also refuse writes that another page makes your browser+ send, such as a form posted from another site or another `localhost` port.+ A Telegram webhook arriving through a tunnel is accepted only when+ `TELEGRAM_WEBHOOK_SECRET` is set, so Telegram can prove it sent it.++The session has no email. The UI proxy then sends no `x-caller-email`, and the+API treats the request as the principal's, the same way it treats the CLI. If+`AUTH_SECRET` is blank in both files, `make dev` uses a temporary one for that+run, so you click **Open** again after a restart. `AUTH_TRUST_HOST` isn't+needed in this mode.++To invite your team, or to run on a server, set up Google sign-in (below). As+soon as `AUTH_GOOGLE_ID` is set, local login is off and any session it+created stops working.++---+## Required configuration### One-time: Google Cloud Console@@ -218,6 +257,9 @@ If `AUTH_GOOGLE_SECRET` is leaked, regenerate in Google Cloud Console (Clients| API returns `401` for every request | UI and API have different `BACKEND_SHARED_SECRET` values (very common after rotating in two separate terminal sessions) || API refuses to start with `RuntimeError: BACKEND_SHARED_SECRET is required` | `OE_PUBLIC_DEPLOYMENT` is set and the secret is missing. Set it; the next restart will boot || Sign-in works but the chat stays empty | Backend is auth'd but `ANTHROPIC_API_KEY` is missing on the API. Its logs will show the error |+| Signed in, but no past chats are listed | Your email isn't on your own People entry, so the API can't tell who you are. Setup saves it from the **Your sign-in email** field; to fix it afterwards, add the email to your row on the People page |+| **Open** says it only works on this computer | You opened the app by a network address. Use `http://localhost:3000` in a browser on the machine running `make dev` |+| Sign-in page shows Google, but you wanted local login | `AUTH_GOOGLE_ID` is set (in the root `.env` or `packages/ui/.env.local`), or the app was started some way other than `make dev` |### Useful commands@@ -242,11 +284,13 @@ curl -sv -H "x-api-key: $SHARED" https://api.example.com/sessions # 20- Direct API hits bypassing the UI (shared secret)- Cookie theft from one session leaking *another* user's data (each session is independent JWT; no shared state)- Missing-secret deploys silently exposing the API (the `OE_PUBLIC_DEPLOYMENT` fail-closed guard)+- Other pages on the same site — to a browser, every `localhost` port is one site — posting to the UI proxy with your cookie (it refuses writes whose `Sec-Fetch-Site` isn't `same-origin`)**Does not mitigate:**- A compromised `BACKEND_SHARED_SECRET` — anyone who learns it can hit the API as if they were the UI. Rotate if leaked.- A compromised Google account on the allow-list — that user has full access to all shared data. The product is currently a **shared workspace**; there is no per-user data isolation.- A compromised deploy credential — attacker can change secrets, redeploy, or read logs. Rotate deploy credentials if a CI workflow is compromised.- Browser-side XSS — Auth.js sessions are httpOnly cookies, so JS can't read them, but a successful XSS could make authenticated requests from the victim's browser. Standard same-origin protections apply.+- Other users or programs on the same computer while local login is on — anything that can reach `127.0.0.1:3000` can click **Open**. Use it only on a computer that is yours alone.If/when per-user data isolation matters (e.g. private sessions per teammate), the change is non-trivial — see the original plan note in [PR #86](https://github.com/SenteLabsAI/OpenExecutive/pull/86) about adding `user_id` to the sessions table.diff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.pyindex 20ea5635..7c5db10b 100644--- a/packages/core/openexecutive/api/main.py+++ b/packages/core/openexecutive/api/main.py@@ -5,6 +5,7 @@ import contextlibimport hmacimport loggingimport os+import reimport sysfrom collections.abc import AsyncIteratorfrom contextlib import asynccontextmanager@@ -764,6 +765,38 @@ def _is_public_deployment() -> bool:return os.environ.get("OE_PUBLIC_DEPLOYMENT", "").strip().lower() not in _FALSEY_ENV+def _is_local_login() -> bool:+ """Whether `make dev` started this API for local login (no sign-in; see+ packages/ui/src/lib/localLogin.ts). Never on a public deployment."""+ return os.environ.get("OE_LOCAL_LOGIN", "").strip() == "1" and not _is_public_deployment()+++# A raw Host header naming this machine, with an optional port — the same rule+# as isLoopbackHost in packages/ui/src/lib/localLogin.ts, and+# packages/ui/scripts/localLogin.test.mjs fails if the two ever disagree.+_LOOPBACK_HOST_RE = re.compile(r"(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?", re.IGNORECASE)++# Sec-Fetch-Site values a browser sends when the page's own origin (or a typed+# URL) made the request — the same set as OWN_PAGE_FETCH_SITES in+# packages/ui/src/lib/crossSite.ts, and packages/ui/scripts/crossSite.test.mjs+# fails if the two ever disagree.+_OWN_PAGE_FETCH_SITES = frozenset({"same-origin", "none"})+_READ_ONLY_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})+++def _webhook_verifies_its_caller(path: str) -> bool:+ """Whether this webhook authenticates its caller by itself. Google Chat+ always checks the signed JWT; Telegram only when TELEGRAM_WEBHOOK_SECRET is+ set — without it, it accepts anyone's update."""+ if path == "/webhook/google-chat":+ return True+ if path == "/webhook/telegram":+ from openexecutive.config import get_settings++ return bool(get_settings().telegram_webhook_secret)+ return False++def create_app() -> FastAPI:app = FastAPI(title="Open Executive API",@@ -815,6 +848,36 @@ def create_app() -> FastAPI:"public internet.")+ # Local login: the UI admits the owner with no password, guarded by where+ # requests come from, and this API needs the same guard — it usually has+ # no shared secret, and a request with no x-caller-email runs as the+ # principal. Two ways a web page could otherwise drive it from the+ # owner's browser:+ # - DNS rebinding: a page re-points its own hostname at 127.0.0.1 and+ # calls this API same-origin. A browser always sends the page's real+ # hostname as Host, and scripts cannot change it. A webhook that+ # verifies its caller may arrive via a tunnel under another name.+ # - A plain form POST from any other site or localhost port: no cookie+ # or preflight is needed. Browsers stamp Sec-Fetch-Site on it; the UI+ # proxy, the CLI and the webhook senders don't send it at all.+ if _is_local_login():+ @app.middleware("http")+ async def _local_login_gate(request: Request, call_next): # type: ignore[no-untyped-def]+ addressed_here = _LOOPBACK_HOST_RE.fullmatch(request.headers.get("host", "").strip())+ if not addressed_here and not _webhook_verifies_its_caller(request.url.path):+ return JSONResponse(+ {"error": "local login only accepts requests addressed to this computer"},+ status_code=403,+ )+ fetch_site = request.headers.get("sec-fetch-site", "").strip().lower()+ if (+ request.method not in _READ_ONLY_METHODS+ and fetch_site+ and fetch_site not in _OWN_PAGE_FETCH_SITES+ ):+ return JSONResponse({"error": "cross-site request refused"}, status_code=403)+ return await call_next(request)+app.include_router(auth_route.router, tags=["auth"])app.include_router(fixtures.router, tags=["fixtures"])app.include_router(clients.router, tags=["clients"])diff --git a/packages/core/openexecutive/api/models.py b/packages/core/openexecutive/api/models.pyindex 727cd5a5..2c11076e 100644--- a/packages/core/openexecutive/api/models.py+++ b/packages/core/openexecutive/api/models.py@@ -384,6 +384,12 @@ class OnboardCommitRequest(BaseModel):profile: CompanyProfileUpdateRequestpeople: list[OnboardPersonDraft] = Field(default_factory=list)departments: list[OnboardDepartmentDraft] = Field(default_factory=list)+ # The principal's sign-in email, confirmed by the user on the review+ # screen (pre-filled from their own login). The one contact detail setup+ # saves: without it the signed-in owner matches no Person, so their chat+ # history stays empty until they add it on the People page. Never taken+ # from the model's draft — the people drafts above still drop emails.+ owner_email: str | None = None# ── /workflows/designer/* (conversational "New workflow" wizard) ─────────────diff --git a/packages/core/openexecutive/api/routes/onboarding.py b/packages/core/openexecutive/api/routes/onboarding.pyindex fed3a9c3..55553710 100644--- a/packages/core/openexecutive/api/routes/onboarding.py+++ b/packages/core/openexecutive/api/routes/onboarding.py@@ -3,12 +3,13 @@ from __future__ import annotationsimport asyncioimport copyimport logging+import sqlite3import timeimport uuidfrom collections import OrderedDictfrom dataclasses import dataclass, field-from fastapi import APIRouter, File, Form, HTTPException, UploadFile+from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFilefrom openexecutive.api.intake_uploads import (_INTAKE_GEN_CHARS_PER_FILE,@@ -530,7 +531,7 @@ async def get_interview(session_id: str) -> OnboardSessionResponse:@router.post("/onboard/interview/commit", response_model=CompanyProfileResponse)-async def commit_interview(body: OnboardCommitRequest) -> CompanyProfileResponse:+async def commit_interview(body: OnboardCommitRequest, request: Request) -> CompanyProfileResponse:"""Save the reviewed draft. The single write in this whole flow.Ordering matters and is load-bearing — see the section header above.@@ -538,7 +539,11 @@ async def commit_interview(body: OnboardCommitRequest) -> CompanyProfileResponserejection leaves the session untouched and the user can edit and retry."""from openexecutive.onboarding.commit import (+ OwnerEmailError,+ check_owner_email,derive_org_structure,+ link_owner_email,+ owner_change_blocked,reconcile_onboarding_departments,save_onboarding_people,)@@ -593,6 +598,33 @@ async def commit_interview(body: OnboardCommitRequest) -> CompanyProfileResponselogger.info("onboarding commit: rejected draft (%d error(s))", len(errors))raise HTTPException(status_code=422, detail=errors[0].safe)+ # validate_draft guarantees exactly one principal. Their sign-in email is+ # checked now, while a rejection still leaves the draft editable.+ principal_name = next(p.full_name.strip() for p in people if p.is_principal)+ # Setup demotes the current owner when it drafts someone else, so only the+ # owner may do that (owner_change_blocked explains the rule).+ from openexecutive.api.routes.chat import _resolve_caller_person_id++ try:+ blocked = owner_change_blocked(principal_name, _resolve_caller_person_id(request))+ except (OSError, sqlite3.Error) as exc:+ logger.warning("onboarding commit: owner lookup failed (%s)", type(exc).__name__)+ raise HTTPException(+ status_code=503, detail="Could not check who owns this workspace. Try again."+ ) from exc+ if blocked:+ raise HTTPException(+ status_code=403,+ detail=(+ "Only the current owner can make someone else the owner. Mark the current "+ 'owner as "This is me", or ask them to run setup.'+ ),+ )+ try:+ owner_email = check_owner_email(body.owner_email, principal_name)+ except OwnerEmailError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+profile = derive_org_structure(profile, people, departments)# 2. is_empty() keys off the name — a nameless profile is invisible to@@ -616,6 +648,9 @@ async def commit_interview(body: OnboardCommitRequest) -> CompanyProfileResponse# 5-6. Best-effort seeding. Departments are reconciled additively — see# onboarding/commit.py for why this must not mirror the fixture loader.person_ids = save_onboarding_people(people)+ principal_id = person_ids.get(principal_name)+ if owner_email and principal_id is not None:+ link_owner_email(principal_id, owner_email)reconcile_onboarding_departments(departments, person_ids)# 7. Same post-onboarding research fire the wizard does, same dedup set.diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 924266e7..13731679 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -4066,7 +4066,54 @@ auth:than coasting until JWT expiry. Fails open ONLY for a sessionthat is not in ALLOWED_EMAILS and whose roster membership iscurrently unreadable; a definite miss (both lists readable,- neither matched) still revokes.+ neither matched) still revokes. It returns the refusal itself+ (JSON 401 for /api/*, a redirect to /signin for pages), and+ middleware.ts exports `auth` UNWRAPPED — next-auth ignores an+ `authorized` false whenever a wrapper `auth((req) => …)` is+ passed, which is how this re-check went unenforced until the+ local-login change: removed users kept working until their+ JWT expired. /signin bounces a visitor onward only when+ `sessionStillAllowed` agrees, or a refused session would loop.+ Local login (packages/ui/src/lib/localLogin.ts): `make dev` with+ Google sign-in not set up starts the UI with `-H 127.0.0.1` and+ OE_LOCAL_LOGIN=1 in one recipe line (the flag alone would hand+ the owner's seat to the network, so nothing else sets it). The recipe+ decides via scripts/devMode.mjs, which loads the env the way Next does+ (root .env exports plus packages/ui/.env*) and applies the app's own+ `localLoginEnabled`, so recipe and sign-in page cannot disagree;+ it also reports whether AUTH_SECRET is blank everywhere. The UI+ then offers a Credentials provider (`local-login`) instead of Google:+ an "Open" button with no password. Guards: the mode is compiled out+ of production builds (literal `process.env.NODE_ENV`, folded at build+ time), off whenever AUTH_GOOGLE_ID or OE_PUBLIC_DEPLOYMENT is set, and+ every sign-in and request must carry a loopback raw `Host` header —+ that stops DNS rebinding, since a browser cannot forge Host (it CAN+ set X-Forwarded-Host, which is why request.url is not used). The+ session has no email; the JWT carries `localLogin`, and it stops+ working the moment Google sign-in is set up. An AUTH_SECRET blank in+ every env file gets a throwaway per-run value from the Makefile, and+ trustHost is on in this mode without AUTH_TRUST_HOST (no OAuth redirect+ to steer; its checks read the raw Host). Docker (`make docker`)+ publishes port 3000 on all interfaces, so it never sets the flag — its+ ui service exports OE_LOCAL_LOGIN EMPTY, which (Next never lets a+ dotenv file override a set variable) also shadows any value in the+ bind-mounted packages/ui/.env*; `make dev` exports it empty outside the+ mode for the same reason; compose's api service shadows it empty too+ (from the root .env it would 403 the UI, which calls as Host api:8000).+ The API receives the same flag and then adds `_local_login_gate`+ (api/main.py), a 403 for (a) a raw Host that is not loopback, unless+ the path is a webhook that verifies its caller (Google Chat always;+ Telegram only with TELEGRAM_WEBHOOK_SECRET, since without it the+ webhook accepts anyone's update), and (b) a write whose Sec-Fetch-Site+ is present and not same-origin/none. Without it the owner's browser+ could drive :8000 as the principal (usually no shared secret; no+ x-caller-email = principal): a DNS-rebinding page calls it+ same-origin, and a plain multipart form from any site or localhost+ port needs neither a cookie nor a preflight. The UI proxy, the CLI and+ webhook senders send no Sec-Fetch-Site. Both rules are mirrored in the+ UI (isLoopbackHost, OWN_PAGE_FETCH_SITES) with tests that read the+ Python literals and fail on drift. scripts/devMode.mjs resolves+ @next/env through `next` itself and needs Node 22.6+ (type stripping).Both callbacks share one helper (`checkEmailAllowed`). The allowlistis the UNION of two additive sources — neither overrides the other:1. ALLOWED_EMAILS: comma-separated env var on the UI, parsed once@@ -4110,6 +4157,19 @@ auth:backend uses this header in /chat to resolve the caller to aPerson row for Honcho's per-person memory; future routes(audit/today filters etc.) can read the same signal.+ A request WITHOUT the header resolves to the principal (the CLI's+ fallback), so the proxy sends none only for a local-login+ session, re-checked there (mode on, loopback Host); any other+ session without an email gets a 401 rather than that fallback.+ The proxy also 403s a write (not GET/HEAD) whose Sec-Fetch-Site is+ anything but same-origin/none (lib/crossSite.ts): the SameSite=Lax+ cookie stops other websites, not other pages on the same site, and a+ browser treats every localhost port as one site, so any local dev+ server could otherwise post a multipart form (chat upload, documents)+ with the user's cookie.+ Onboarding saves the owner's sign-in email on the principal's row+ (company_onboarding.people_and_contacts), so a Google-signed-in+ owner resolves to themselves from the first turn.integrations:channel_access: |@@ -4838,9 +4898,11 @@ company_onboarding:write_once_commit: |The interview NEVER writes. POST /onboard/interview/commit is the singlewrite, ordered so nothing observable changes until the atomic save- succeeds: (1) validate profile + drafts, (2) reject an empty name,+ succeeds: (1) validate profile + drafts, then the owner email+ (commit.check_owner_email), (2) reject an empty name,(3) profile.save_to_yaml (write-then-rename, O_EXCL, fsync), (4) mark the- session saved, (5) seed people, (6) reconcile departments, (7) fire the+ session saved, (5) seed people, then link the owner email to the+ principal (best-effort), (6) reconcile departments, (7) fire thepost-onboarding research workflow. A failure at 1-3 leaves the sessionuntouched, so the user edits the draft and retries. This replaces thedeepcopy-snapshot rollback the wizard needs (process_answer mutates state@@ -4865,6 +4927,37 @@ company_onboarding:model boundary — OE never auto-imports contacts, matching the fixture andengagement-intake invariants. Channels, availability and scopes stay adeliberate action on /people.+ The one exception is the owner's OWN sign-in email, and it never comes+ from the model: OnboardCommitRequest.owner_email is a separate field the+ review screen pre-fills from the signed-in session and the user confirms+ (or changes, when setting up for someone else). On a re-run the field+ starts from the CURRENT owner's email, not the re-runner's login, and+ Save waits until both have loaded (the commit is once per session).+ check_owner_email lowercases it and 422s — with fixed, non-echoing+ messages — on a malformed address, one already held by a non-archived+ person other than the drafted principal (two rows sharing an email would+ resolve sign-in to the older one; when that holder is the current+ principal the message says so, since a renamed owner is a new row under+ the name-keyed upsert), one that differs from the drafted principal's+ existing email (setup only FILLS IN a missing email: replacing it would+ sign the owner out and hand their seat to whoever re-ran setup), or a+ roster it cannot read. link_owner_email then saves it on the principal's+ row after the people seed, re-checking that it replaces nothing. Before+ this, the signed-in owner+ matched no Person, so `x-caller-email` resolved to nobody and their chat+ list stayed empty until they found the People page. Optional with+ local login, whose email-less session already resolves to the+ principal. "The drafted principal's row" is matched BY ID against the+ same name-keyed dict save_onboarding_people builds (two rows can share+ a name; the upsert takes the last), and link_owner_email also refuses+ an email another active row holds.+ Owner changes: the seed demotes the old principal and grants WILDCARD+ to the drafted one, and any signed-in user can open /onboard, so the+ commit route calls commit.owner_change_blocked before any write: when a+ principal exists and the draft's principal maps to a different row (a+ renamed owner included), the caller — resolved from x-caller-email; no+ header means the principal — must be the principal, else 403. Keeping+ the owner, or a first setup, stays open.org_structure_is_derived: |profile.org_structure.departments and .leadership_team are computed fromthe reviewed people and department tables at commit timediff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex 6f6b1163..0457bb40 100644--- a/packages/core/openexecutive/architecture/prebuilt/api.json+++ b/packages/core/openexecutive/architecture/prebuilt/api.json@@ -1,7 +1,7 @@{"section_id": "api","title": "API Reference",- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while Google sign-in is not set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat always, Telegram only with `TELEGRAM_WEBHOOK_SECRET`), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |","mermaid": null,"generated_at": "2026-09-25T01:22:23.080573+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.jsonindex 227c012f..1aae5e43 100644--- a/packages/core/openexecutive/architecture/prebuilt/org.json+++ b/packages/core/openexecutive/architecture/prebuilt/org.json@@ -1,7 +1,7 @@{"section_id": "org","title": "Org Structure (Departments & People)",- "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which `create_department` (always `specialist_key =\nNULL`) cannot restore. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due, then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. A department may map to one of the 8 specialist agents via `specialist_key`, or stay informational. An assigned head gets a generated department-head voice persona.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page itself is unaffected.",+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which `create_department` (always `specialist_key =\nNULL`) cannot restore. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's, or different from the owner's existing\nemail is a 422 — setup only fills in a missing one) and then saves it on the\nprincipal's row. Without it the signed-in owner matched no Person,\nso their chat history stayed empty until they found the People page. With\nlocal login (`make dev` without Google sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due, then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. A department may map to one of the 8 specialist agents via `specialist_key`, or stay informational. An assigned head gets a generated department-head voice persona.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page itself is unaffected.","mermaid": "flowchart TD\n People[\"People registry (Person, is_principal)\"]\n Dept[\"Departments (8 seeded once)\"]\n GC[\"Goals / checklists / cadences\"]\n Head[\"Head + voice persona\"]\n Gate[\"Authority gate (propose_only vs autonomous)\"]\n Scope[\"AuthorityScope to find_approvers\"]\n Chan[\"Channel resolution (Discord / Telegram / email)\"]\n Dept --> GC\n Dept --> Head\n Dept -->|proposes action| Gate\n Gate -->|required_scope| Scope\n Scope -->|ranks approvers| People\n People --> Chan\n Dept -->|team room| Chan\n class People storage\n class Dept storage\n class GC storage\n class Gate compute\n class Scope compute\n class Chan compute\n class Head compute","generated_at": "2026-09-25T01:36:05.539643+00:00"}diff --git a/packages/core/openexecutive/guide/prebuilt/company_profile.json b/packages/core/openexecutive/guide/prebuilt/company_profile.jsonindex 5b04bb23..4f5c77ed 100644--- a/packages/core/openexecutive/guide/prebuilt/company_profile.json+++ b/packages/core/openexecutive/guide/prebuilt/company_profile.json@@ -1,7 +1,7 @@{"section_id": "company_profile","title": "Company Profile & Onboarding",- "markdown": "**What it is:** Your company's identity and strategy — mission, market, competitors, financials, and org structure — that grounds everything the Executive says.\n\n**What it does:**\n\n- **Describe your business in your own words** the first time — paste a paragraph, or attach a deck or one-pager. The Executive asks a few follow-up questions, then shows you a filled-in draft profile, team list, and departments.\n- Review and edit that draft before anything is saved; nothing is written until you hit save. Prefer a form? A step-by-step version is linked at the bottom of the setup screen.\n- View and edit every section of the profile inline, any time afterward.\n- Feed this context to all specialists so advice fits *your* company, not a generic one.\n- Kick off background research after setup to suggest things worth watching.\n\n**How to use:**\n\n*First-time setup*\n\n1. Click **Set up company** in the sidebar (or **Set up profile →** on the banner in chat).\n2. Describe your business — what you do, who you sell to, roughly how big you are. Optionally **Attach files** (up to 8: a deck, one-pager, or spreadsheet). Click **Get started**.\n3. Answer the follow-up questions (up to 8), or click **Skip ahead — draft my profile now**.\n4. On **Here's what I understood**, edit the profile, **Your team**, and **Departments**. Make sure exactly one person is marked as you. Click **Save & finish setup** — or **Not quite — ask me more questions**.\n\nPrefer filling in fields? Click **Prefer a form? Use the step-by-step version** for a 12-step wizard.\n\n*Afterwards*\n\n- Open **Company profile**, click **Edit** on any section (Company Basics, Mission & Vision, Target Customer, Competitive Landscape, Strategic Priorities, Financials, and more), make your changes, and click **Save**. List fields take one item per line.\n- **Re-run setup →** takes you back through the conversation.\n- Ask OE can fill in profile sections for you — you still click **Save**.\n\n**Example description:** *\"We're Northwind Tools — a 40-person B2B SaaS company selling inventory software to independent hardware stores in the US. About $6M ARR, growing 60% a year, Series A last spring. Our main competitors are Lightspeed and spreadsheets. This year's priorities are launching in Canada and getting net revenue retention above 110%.\"*\n\n*Note: until a profile exists, the app nudges you to set one up — it's the foundation the rest builds on.*",+ "markdown": "**What it is:** Your company's identity and strategy — mission, market, competitors, financials, and org structure — that grounds everything the Executive says.\n\n**What it does:**\n\n- **Describe your business in your own words** the first time — paste a paragraph, or attach a deck or one-pager. The Executive asks a few follow-up questions, then shows you a filled-in draft profile, team list, and departments.\n- Review and edit that draft before anything is saved; nothing is written until you hit save. Prefer a form? A step-by-step version is linked at the bottom of the setup screen.\n- View and edit every section of the profile inline, any time afterward.\n- Feed this context to all specialists so advice fits *your* company, not a generic one.\n- Kick off background research after setup to suggest things worth watching.\n\n**How to use:**\n\n*First-time setup*\n\n1. Click **Set up company** in the sidebar (or **Set up profile →** on the banner in chat).\n2. Describe your business — what you do, who you sell to, roughly how big you are. Optionally **Attach files** (up to 8: a deck, one-pager, or spreadsheet). Click **Get started**.\n3. Answer the follow-up questions (up to 8), or click **Skip ahead — draft my profile now**.\n4. On **Here's what I understood**, edit the profile, **Your team**, and **Departments**. Make sure exactly one person is marked as you. Check **Your sign-in email**: it's filled in with the account you're signed in with, and it's how the Executive knows the person marked as you is you — change it if you're setting this up for someone else. Click **Save & finish setup** — or **Not quite — ask me more questions**.\n\nPrefer filling in fields? Click **Prefer a form? Use the step-by-step version** for a 12-step wizard.\n\n*Afterwards*\n\n- Open **Company profile**, click **Edit** on any section (Company Basics, Mission & Vision, Target Customer, Competitive Landscape, Strategic Priorities, Financials, and more), make your changes, and click **Save**. List fields take one item per line.\n- **Re-run setup →** takes you back through the conversation. Only the current owner can mark someone else as \"This is me\" when re-running it, because saving makes that person the owner.\n- Ask OE can fill in profile sections for you — you still click **Save**.\n\n**Example description:** *\"We're Northwind Tools — a 40-person B2B SaaS company selling inventory software to independent hardware stores in the US. About $6M ARR, growing 60% a year, Series A last spring. Our main competitors are Lightspeed and spreadsheets. This year's priorities are launching in Canada and getting net revenue retention above 110%.\"*\n\n*Note: until a profile exists, the app nudges you to set one up — it's the foundation the rest builds on.*","mermaid": null,"generated_at": "2026-09-23T00:00:00+00:00"}diff --git a/packages/core/openexecutive/onboarding/commit.py b/packages/core/openexecutive/onboarding/commit.pyindex 60e62143..ac7bea43 100644--- a/packages/core/openexecutive/onboarding/commit.py+++ b/packages/core/openexecutive/onboarding/commit.py@@ -18,6 +18,8 @@ what is genuinely new.from __future__ import annotationsimport logging+import re+import sqlite3from typing import TYPE_CHECKINGfrom openexecutive.utils.slug import DEPARTMENT_SLUG_FALLBACK, slugify@@ -165,6 +167,121 @@ def _strip_wildcard(person_id: int, current: list[AuthorityScope]) -> None:set_authority_scope(person_id, remaining)+# Loose on purpose: Google checks the address for real at sign-in. This only+# stops a typo or a stray sentence from becoming the owner's roster address.+_OWNER_EMAIL_RE = re.compile(r"[^@\s]+@[^@\s]+\.[^@\s]+")+# RFC 5321's limit on a forward path.+_OWNER_EMAIL_MAX_LEN = 254+++class OwnerEmailError(ValueError):+ """The owner email from the review screen can't be saved. The message is a+ fixed, input-free string, safe to return as an HTTP detail."""+++def check_owner_email(raw: str | None, principal_name: str) -> str | None:+ """Normalise the owner's sign-in email, or return None when left blank.++ Runs BEFORE the commit writes anything, and setup only ever FILLS IN a+ missing email. Raises OwnerEmailError when the value is not one plausible+ address; when another non-archived person holds it (two rows sharing an+ email would resolve sign-in to the older one); when the drafted+ principal's own row already has a different email (replacing it would+ sign the owner out — web sign-in and caller resolution both key on it —+ so that change belongs on the People page); or when the roster can't be+ read. "The drafted principal's row" is the one save_onboarding_people's+ name-keyed upsert will update — compared by id, because two rows can+ share a name and the upsert then takes the last one.+ """+ email = (raw or "").strip().lower()+ if not email:+ return None+ if len(email) > _OWNER_EMAIL_MAX_LEN or not _OWNER_EMAIL_RE.fullmatch(email):+ raise OwnerEmailError("That email address doesn't look right. Check it and try again.")+ from openexecutive.people.store import find_person_by_email, list_people++ key = principal_name.strip().lower()+ try:+ holder = find_person_by_email(email)+ # The same dict save_onboarding_people builds, so the same row wins.+ own_row = {p.full_name.strip().lower(): p for p in list_people()}.get(key)+ except (OSError, sqlite3.Error) as exc:+ # Unknown is not "free": saving anyway could give two people one email.+ logger.warning("check_owner_email: lookup failed (%s)", type(exc).__name__)+ raise OwnerEmailError("Could not check that email just now. Try again.") from exc+ if holder is not None and (own_row is None or holder.id != own_row.id):+ if holder.is_principal:+ raise OwnerEmailError(+ "That email is on the current owner's People entry, but setup would update "+ "a different one (another name, or two entries share this name). Use the "+ "owner's name exactly as on the People page, or leave the email blank."+ )+ raise OwnerEmailError(+ "That email already belongs to someone else on the People page. "+ "Use a different one, or change theirs there first."+ )+ if own_row is not None and own_row.email and own_row.email.strip().lower() != email:+ raise OwnerEmailError(+ "Your People entry already has a different sign-in email, and setup never "+ "replaces it. Keep that one here, or change it on the People page."+ )+ return email+++def owner_change_blocked(principal_name: str, caller_person_id: int | None) -> bool:+ """Whether this commit would make a different person the owner while the+ caller is not the current owner.++ The seed demotes whoever was principal and grants WILDCARD to the drafted+ one, so re-running setup is also a way to take the owner's seat: any+ signed-in user can open /onboard. Keeping the current owner is open to+ everyone, as is a first setup (no principal yet); handing the role to+ another People row — including a new row, as a renamed owner becomes+ under the name-keyed upsert — takes the current owner. A caller with no+ x-caller-email (the CLI, local login) resolves to the principal already.+ Lookup errors propagate: the route turns them into a retryable 503.+ """+ from openexecutive.people.store import find_principal_person, is_principal_or_self, list_people++ current = find_principal_person()+ if current is None:+ return False+ # The same dict save_onboarding_people builds, so the same row wins.+ own_row = {p.full_name.strip().lower(): p for p in list_people()}.get(+ principal_name.strip().lower()+ )+ if own_row is not None and own_row.id == current.id:+ return False+ return caller_person_id is None or not is_principal_or_self(caller_person_id, None)+++def link_owner_email(person_id: int, email: str) -> bool:+ """Fill in the principal's sign-in email.++ Never replaces a different one, and never gives an email two owners:+ check_owner_email refuses both before anything is written, and this+ re-checks the row it is about to change. Best-effort, like the rest of+ this module — the profile is already saved, and a failure here only leaves+ the owner to add their email on the People page, as before this step+ existed.+ """+ try:+ from openexecutive.people.store import find_person_by_email, get_person, update_person++ person = get_person(person_id)+ holder = find_person_by_email(email)+ if (+ person is None+ or (person.email and person.email.strip().lower() != email)+ or (holder is not None and holder.id != person_id)+ ):+ return False+ return update_person(person_id, email=email)+ except Exception as exc:+ logger.warning("link_owner_email failed (%s)", type(exc).__name__)+ return False++def reconcile_onboarding_departments(drafts: list[DepartmentDraft],person_ids: dict[str, int],diff --git a/packages/core/tests/unit/test_local_login_host_gate.py b/packages/core/tests/unit/test_local_login_host_gate.pynew file mode 100644index 00000000..d0f6db6f--- /dev/null+++ b/packages/core/tests/unit/test_local_login_host_gate.py@@ -0,0 +1,130 @@+"""Local login's gate on the API.++`make dev` without Google sign-in runs the UI with no password, guarded by+where requests come from; the API gets the same guard. It usually has no+shared secret, and a request with no x-caller-email runs as the principal, so+without the gate a page in the owner's browser could drive it: by+DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from+any other site or localhost port.+"""++from __future__ import annotations++import httpx+import pytest+from fastapi.testclient import TestClient++from openexecutive.api.main import _is_local_login, create_app++_HOST_ERROR = "local login only accepts requests addressed to this computer"+_CROSS_SITE_ERROR = "cross-site request refused"++[email protected](autouse=True)+def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None:+ for var in ("OE_LOCAL_LOGIN", "OE_PUBLIC_DEPLOYMENT", "BACKEND_SHARED_SECRET"):+ monkeypatch.delenv(var, raising=False)+ # Settings also reads the repo .env, so pin the value rather than delete it.+ monkeypatch.setenv("TELEGRAM_WEBHOOK_SECRET", "")+++def _request(+ method: str, host: str, path: str, headers: dict[str, str] | None = None+) -> httpx.Response:+ # The Host header is set directly: TestClient cannot parse an IPv6 base_url.+ return TestClient(create_app()).request(+ method, path, headers={"host": host, **(headers or {})}+ )+++# ── addressed to this computer ───────────────────────────────────────────────++[email protected]("host", ["localhost:8000", "127.0.0.1:8000", "[::1]:8000", "LOCALHOST"])+def test_requests_addressed_to_this_computer_pass(+ monkeypatch: pytest.MonkeyPatch, host: str+) -> None:+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ assert _request("GET", host, "/openapi.json").status_code == 200+++ "host", ["evil.example:8000", "localhost.evil.example:8000", "192.168.1.20:8000"]+)+def test_a_rebinding_hostname_is_refused(monkeypatch: pytest.MonkeyPatch, host: str) -> None:+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ resp = _request("GET", host, "/sessions")+ assert resp.status_code == 403+ assert resp.json() == {"error": _HOST_ERROR}+++def test_google_chat_verifies_its_caller_and_may_come_through_a_tunnel(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ resp = _request("POST", "abc.tunnel.example", "/webhook/google-chat")+ assert _HOST_ERROR not in resp.text+++def test_telegram_passes_under_another_name_only_when_it_checks_its_secret(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Without TELEGRAM_WEBHOOK_SECRET the webhook accepts anyone's update, so+ a rebinding page could forge one; with it, the tunnel name is fine."""+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ resp = _request("POST", "abc.tunnel.example", "/webhook/telegram")+ assert resp.status_code == 403+ assert resp.json() == {"error": _HOST_ERROR}++ monkeypatch.setenv("TELEGRAM_WEBHOOK_SECRET", "s3cret")+ resp = _request("POST", "abc.tunnel.example", "/webhook/telegram")+ assert _HOST_ERROR not in resp.text+++# ── writes another page made the browser send ────────────────────────────────++[email protected]("site", ["same-site", "cross-site", "Same-Site"])+def test_a_form_posted_from_another_page_is_refused(+ monkeypatch: pytest.MonkeyPatch, site: str+) -> None:+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ resp = _request("POST", "localhost:8000", "/sessions", {"sec-fetch-site": site})+ assert resp.status_code == 403+ assert resp.json() == {"error": _CROSS_SITE_ERROR}++[email protected]("headers", [{}, {"sec-fetch-site": "same-origin"}, {"sec-fetch-site": "none"}])+def test_the_proxy_the_cli_and_same_origin_pages_may_write(+ monkeypatch: pytest.MonkeyPatch, headers: dict[str, str]+) -> None:+ """The UI proxy and the CLI send no Sec-Fetch-Site; the API's own pages+ (e.g. /docs) are same-origin. They reach the route, which answers 405 here."""+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ resp = _request("POST", "localhost:8000", "/sessions", headers)+ assert resp.status_code == 405+++def test_reads_are_not_refused_by_the_cross_site_check(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ resp = _request("GET", "localhost:8000", "/openapi.json", {"sec-fetch-site": "cross-site"})+ assert resp.status_code == 200+++# ── when the gate is off ─────────────────────────────────────────────────────+++def test_the_gate_is_off_outside_local_login() -> None:+ """Google-mode `make dev`, compose and tests keep reaching the API by any name."""+ assert _is_local_login() is False+ assert _request("GET", "api:8000", "/openapi.json").status_code == 200+ assert _request("POST", "api:8000", "/sessions", {"sec-fetch-site": "cross-site"}).status_code == 405+++def test_a_public_deployment_never_runs_local_login(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ monkeypatch.setenv("OE_PUBLIC_DEPLOYMENT", "1")+ monkeypatch.setenv("BACKEND_SHARED_SECRET", "s" * 32)+ assert _is_local_login() is False+ resp = _request("GET", "exec.example.com", "/openapi.json", {"x-api-key": "s" * 32})+ assert resp.status_code == 200diff --git a/packages/core/tests/unit/test_onboarding_commit.py b/packages/core/tests/unit/test_onboarding_commit.pyindex 1a3d0150..31dbb446 100644--- a/packages/core/tests/unit/test_onboarding_commit.py+++ b/packages/core/tests/unit/test_onboarding_commit.py@@ -9,13 +9,17 @@ behaviour so nobody "simplifies" it into the fixture seeder later."""from __future__ import annotations+import sqlite3from pathlib import Pathimport pytestfrom openexecutive.departments import store as dept_storefrom openexecutive.onboarding.commit import (+ OwnerEmailError,+ check_owner_email,derive_org_structure,+ link_owner_email,reconcile_onboarding_departments,save_onboarding_people,)@@ -480,3 +484,143 @@ def test_case_variant_names_collapse_onto_one_row_not_two(people_db: Path) -> Noassert len(set(ids.values())) == 1everyone = people_store.list_people(db_path=people_db)assert len(everyone) == 1, f"duplicate rows: {[p.full_name for p in everyone]}"+++# ── the owner's sign-in email ────────────────────────────────────────────────+# Setup collects no contact details, so without this step the signed-in owner+# matched no Person: their chat list stayed empty until they found the People+# page on their own.+++def test_blank_owner_email_means_none(people_db: Path) -> None:+ assert check_owner_email(None, "Dana Reyes") is None+ assert check_owner_email(" ", "Dana Reyes") is None+++def test_owner_email_is_trimmed_and_lowercased(people_db: Path) -> None:+ assert check_owner_email(" [email protected] ", "Dana Reyes") == "[email protected]"+++ "bad",+ [+ "dana",+ "dana@",+ "@example.com",+ "dana@example",+ "dana @example.com",+ "dana@exa mple.com",+ "a@[email protected]",+ f"{'d' * 250}@example.com",+ ],+)+def test_malformed_owner_email_is_rejected_without_echoing_it(+ people_db: Path, bad: str+) -> None:+ with pytest.raises(OwnerEmailError) as err:+ check_owner_email(bad, "Dana Reyes")+ assert bad.strip().lower() not in str(err.value)+++def test_owner_email_held_by_someone_else_is_rejected(people_db: Path) -> None:+ """Two rows with one email would make sign-in resolve to the older one."""+ people_store.upsert_person(full_name="Sam Okafor", email="[email protected]")+ with pytest.raises(OwnerEmailError) as err:+ check_owner_email("[email protected]", "Dana Reyes")+ assert "[email protected]" not in str(err.value)+++def test_owner_email_already_on_the_principals_own_row_is_fine(people_db: Path) -> None:+ """Re-running setup: the drafted principal maps onto their existing row by+ case-insensitive name, so their own email is not a conflict."""+ people_store.upsert_person(full_name="Dana Reyes", email="[email protected]", is_principal=True)+ assert check_owner_email("[email protected]", " dana reyes ") == "[email protected]"+++def test_an_archived_holder_does_not_block_the_owner_email(people_db: Path) -> None:+ pid = people_store.upsert_person(full_name="Former CEO", email="[email protected]")+ people_store.archive_person(pid)+ assert check_owner_email("[email protected]", "Dana Reyes") == "[email protected]"+++def test_an_unreadable_roster_rejects_rather_than_risking_a_duplicate(+ people_db: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ def _locked(email: str) -> None:+ raise sqlite3.OperationalError("database is locked")++ monkeypatch.setattr(people_store, "find_person_by_email", _locked)+ with pytest.raises(OwnerEmailError):+ check_owner_email("[email protected]", "Dana Reyes")+++def test_linking_makes_the_owner_resolvable_by_their_sign_in(people_db: Path) -> None:+ ids = save_onboarding_people(+ [PersonDraft(full_name="Dana Reyes", role="CEO", is_principal=True)]+ )+ assert link_owner_email(ids["Dana Reyes"], "[email protected]") is True++ found = people_store.find_person_by_email("[email protected]", db_path=people_db)+ assert found is not None and found.id == ids["Dana Reyes"]+ assert found.is_principal+++def test_link_failure_is_swallowed(people_db: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ pid = people_store.upsert_person(full_name="Dana Reyes", is_principal=True)++ def _boom(*a: object, **k: object) -> bool:+ raise sqlite3.OperationalError("disk I/O error")++ monkeypatch.setattr(people_store, "update_person", _boom)+ assert link_owner_email(pid, "[email protected]") is False+++def test_setup_never_replaces_the_principals_existing_email(people_db: Path) -> None:+ """Re-run by someone else who kept their own login in the field: replacing+ Dana's address would sign her out, since sign-in and caller resolution+ both key on it, and hand her seat to the re-runner."""+ people_store.upsert_person(full_name="Dana Reyes", email="[email protected]", is_principal=True)+ with pytest.raises(OwnerEmailError) as err:+ check_owner_email("[email protected]", "Dana Reyes")+ assert "People page" in str(err.value)+ assert "[email protected]" not in str(err.value)+++def test_a_renamed_owner_is_told_it_is_their_own_entry(people_db: Path) -> None:+ """The upsert keys on the name, so a renamed principal is a new row and+ their old one still holds the email. The message must not call that+ "someone else"."""+ people_store.upsert_person(full_name="Dana Reyes", email="[email protected]", is_principal=True)+ with pytest.raises(OwnerEmailError) as err:+ check_owner_email("[email protected]", "Dana Reyes-Kim")+ assert "current owner" in str(err.value)+ assert "someone else" not in str(err.value)+++def test_two_entries_sharing_the_owners_name_cannot_split_the_email(people_db: Path) -> None:+ """The name-keyed upsert updates the LAST row with that name. If that is+ not the row holding the email, linking would give two people one email+ and resolve the owner's sign-in to the row being demoted."""+ people_store.upsert_person(full_name="Ann Lee", email="[email protected]", is_principal=True)+ people_store.upsert_person(full_name="Ann Lee")+ with pytest.raises(OwnerEmailError) as err:+ check_owner_email("[email protected]", "Ann Lee")+ assert "current owner" in str(err.value)+++def test_link_refuses_an_email_another_entry_holds(people_db: Path) -> None:+ people_store.upsert_person(full_name="Sam Okafor", email="[email protected]")+ pid = people_store.upsert_person(full_name="Dana Reyes", is_principal=True)+ assert link_owner_email(pid, "[email protected]") is False+ person = people_store.get_person(pid, db_path=people_db)+ assert person is not None and person.email is None+++def test_link_never_replaces_a_different_email(people_db: Path) -> None:+ pid = people_store.upsert_person(+ full_name="Dana Reyes", email="[email protected]", is_principal=True+ )+ assert link_owner_email(pid, "[email protected]") is False+ person = people_store.get_person(pid, db_path=people_db)+ assert person is not None and person.email == "[email protected]"diff --git a/packages/core/tests/unit/test_onboarding_interview_route.py b/packages/core/tests/unit/test_onboarding_interview_route.pyindex 6f01cd7c..06c06e1d 100644--- a/packages/core/tests/unit/test_onboarding_interview_route.py+++ b/packages/core/tests/unit/test_onboarding_interview_route.py@@ -26,6 +26,9 @@ from openexecutive.api.models import ONBOARD_MESSAGE_MAX_CHARSfrom openexecutive.api.routes import onboarding as routefrom openexecutive.memory.company_profile import CompanyProfilefrom openexecutive.onboarding import interview as iv+from openexecutive.onboarding.commit import (+ save_onboarding_people as _real_save_onboarding_people,+)def _draft(**overrides: Any) -> iv.CompanyDraft:@@ -79,9 +82,14 @@ def seeded(monkeypatch: pytest.MonkeyPatch) -> list[Any]:@pytest.fixture()def client(- monkeypatch: pytest.MonkeyPatch, profile_path: Path+ monkeypatch: pytest.MonkeyPatch, profile_path: Path, tmp_path: Path) -> TestClient:fired: list[str] = []+ # An empty roster unless a test seeds one: the commit reads it to decide+ # who owns the workspace, and must never see the developer's real DB.+ from openexecutive.people import store as people_store++ monkeypatch.setattr(people_store, "DB_PATH", tmp_path / "no-people.db")async def _no_research(session_id: str) -> None:fired.append(session_id)@@ -695,3 +703,189 @@ def test_a_full_legal_start_does_not_lock_the_conversation("/onboard/interview/message", json={"session_id": sid, "message": "Series A."})assert follow_up.status_code == 200, follow_up.text+++# ── the owner's sign-in email ────────────────────────────────────────────────+++def people_db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """A real roster, and the real save_onboarding_people the client fixture stubs."""+ from openexecutive.people import store as people_store++ path = tmp_path / "people.db"+ monkeypatch.setattr(people_store, "DB_PATH", path)+ people_store.initialize_db(path)+ monkeypatch.setattr(+ "openexecutive.onboarding.commit.save_onboarding_people", _real_save_onboarding_people+ )+ return path+++def test_commit_links_the_owner_email_to_the_principal(+ client: TestClient, seeded: list[Any], people_db: Path+) -> None:+ from openexecutive.people import store as people_store++ seeded.append(_draft())+ sid = _start(client)+ body = _commit_body(sid)+ body["owner_email"] = " [email protected] "+ assert client.post("/onboard/interview/commit", json=body).status_code == 200++ owner = people_store.find_person_by_email("[email protected]", db_path=people_db)+ assert owner is not None+ assert owner.full_name == "Dana Reyes" and owner.is_principal+ assert owner.email == "[email protected]"+++def test_commit_without_an_owner_email_leaves_the_principal_without_one(+ client: TestClient, seeded: list[Any], people_db: Path+) -> None:+ from openexecutive.people import store as people_store++ seeded.append(_draft())+ sid = _start(client)+ assert client.post("/onboard/interview/commit", json=_commit_body(sid)).status_code == 200+ principal = people_store.find_principal_person(db_path=people_db)+ assert principal is not None and principal.email is None++[email protected]("taken", [False, True])+def test_a_rejected_owner_email_writes_nothing_and_stays_retryable(+ client: TestClient,+ seeded: list[Any],+ people_db: Path,+ profile_path: Path,+ taken: bool,+) -> None:+ from openexecutive.people import store as people_store++ if taken:+ people_store.upsert_person(full_name="Sam Okafor", email="[email protected]")+ bad = "[email protected]"+ else:+ bad = "secret-owner-at-example"+ seeded.append(_draft())+ sid = _start(client)+ body = _commit_body(sid)+ body["owner_email"] = bad++ resp = client.post("/onboard/interview/commit", json=body)+ assert resp.status_code == 422+ assert "secret-owner" not in resp.text+ assert not profile_path.exists()+ assert people_store.find_principal_person(db_path=people_db) is None++ # Fixed and resent, the same session saves.+ body["owner_email"] = "[email protected]"+ assert client.post("/onboard/interview/commit", json=body).status_code == 200+ assert profile_path.exists()+++def test_a_rerun_never_replaces_the_owners_existing_email(+ client: TestClient, seeded: list[Any], people_db: Path, profile_path: Path+) -> None:+ from openexecutive.people import store as people_store++ people_store.upsert_person(full_name="Dana Reyes", email="[email protected]", is_principal=True)+ seeded.append(_draft())+ sid = _start(client)+ body = _commit_body(sid)+ body["owner_email"] = "[email protected]"++ resp = client.post("/onboard/interview/commit", json=body)+ assert resp.status_code == 422+ assert not profile_path.exists()+ dana = people_store.find_principal_person(db_path=people_db)+ assert dana is not None and dana.email == "[email protected]"++ # Kept as it was (what the review screen now pre-fills on a re-run), it saves.+ body["owner_email"] = "[email protected]"+ assert client.post("/onboard/interview/commit", json=body).status_code == 200+ dana = people_store.find_principal_person(db_path=people_db)+ assert dana is not None and dana.email == "[email protected]"+++# ── who may change the owner ─────────────────────────────────────────────────+# Setup demotes the current owner when it drafts someone else as principal,+# and any signed-in user can open /onboard.+++def _seed_owner_and_teammate() -> None:+ from openexecutive.people import store as people_store++ people_store.upsert_person(full_name="Dana Reyes", email="[email protected]", is_principal=True)+ people_store.upsert_person(full_name="Bob Lin", email="[email protected]")+++def _bob_as_owner(sid: str) -> dict[str, Any]:+ body = _commit_body(sid)+ body["people"] = [{"full_name": "Bob Lin", "role": "COO", "is_principal": True}]+ body["departments"] = [{"title": "Operations"}]+ return body+++def test_a_teammate_cannot_take_the_owner_role_by_rerunning_setup(+ client: TestClient, seeded: list[Any], people_db: Path, profile_path: Path+) -> None:+ from openexecutive.people import store as people_store++ _seed_owner_and_teammate()+ seeded.append(_draft())+ sid = _start(client)+ resp = client.post(+ "/onboard/interview/commit",+ json=_bob_as_owner(sid),+ headers={"x-caller-email": "[email protected]"},+ )+ assert resp.status_code == 403+ assert not profile_path.exists()+ owner = people_store.find_principal_person(db_path=people_db)+ assert owner is not None and owner.full_name == "Dana Reyes"+++def test_the_owner_can_hand_the_role_on(+ client: TestClient, seeded: list[Any], people_db: Path+) -> None:+ from openexecutive.people import store as people_store++ _seed_owner_and_teammate()+ seeded.append(_draft())+ sid = _start(client)+ resp = client.post(+ "/onboard/interview/commit",+ json=_bob_as_owner(sid),+ headers={"x-caller-email": "[email protected]"},+ )+ assert resp.status_code == 200, resp.text+ owner = people_store.find_principal_person(db_path=people_db)+ assert owner is not None and owner.full_name == "Bob Lin"+++def test_anyone_may_rerun_setup_that_keeps_the_owner(+ client: TestClient, seeded: list[Any], people_db: Path+) -> None:+ _seed_owner_and_teammate()+ seeded.append(_draft())+ sid = _start(client)+ resp = client.post(+ "/onboard/interview/commit",+ json=_commit_body(sid),+ headers={"x-caller-email": "[email protected]"},+ )+ assert resp.status_code == 200, resp.text+++def test_local_login_and_the_cli_count_as_the_owner(+ client: TestClient, seeded: list[Any], people_db: Path+) -> None:+ """No x-caller-email resolves to the principal, as everywhere else."""+ from openexecutive.people import store as people_store++ _seed_owner_and_teammate()+ seeded.append(_draft())+ sid = _start(client)+ assert client.post("/onboard/interview/commit", json=_bob_as_owner(sid)).status_code == 200+ owner = people_store.find_principal_person(db_path=people_db)+ assert owner is not None and owner.full_name == "Bob Lin"diff --git a/packages/ui/scripts/crossSite.test.mjs b/packages/ui/scripts/crossSite.test.mjsnew file mode 100644index 00000000..7a56fcfe--- /dev/null+++ b/packages/ui/scripts/crossSite.test.mjs@@ -0,0 +1,38 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { OWN_PAGE_FETCH_SITES, isCrossSiteWrite } from "../src/lib/crossSite.ts";++test("the app's own requests pass", () => {+ for (const method of ["POST", "PUT", "PATCH", "DELETE", "GET"]) {+ assert.equal(isCrossSiteWrite(method, "same-origin"), false, method);+ }+});++test("a form another localhost port posts is refused", () => {+ // Every localhost port is one "site", so the browser attaches the cookie+ // and reports same-site; other websites report cross-site.+ for (const site of ["same-site", "cross-site", "SAME-SITE"]) {+ for (const method of ["POST", "PUT", "PATCH", "DELETE", "post"]) {+ assert.equal(isCrossSiteWrite(method, site), true, `${method} ${site}`);+ }+ }+});++test("reads are never refused — another site cannot read the response anyway", () => {+ assert.equal(isCrossSiteWrite("GET", "cross-site"), false);+ assert.equal(isCrossSiteWrite("HEAD", "same-site"), false);+});++test("a typed URL, a bookmark or a non-browser client is not refused", () => {+ assert.equal(isCrossSiteWrite("POST", "none"), false);+ assert.equal(isCrossSiteWrite("POST", null), false);+});++test("the API's local-login check allows exactly the same Sec-Fetch-Site values", () => {+ const mainPy = readFileSync(new URL("../../core/openexecutive/api/main.py", import.meta.url), "utf8");+ const literal = /_OWN_PAGE_FETCH_SITES = frozenset\(\{([^}]*)\}\)/.exec(mainPy);+ assert.ok(literal, "_OWN_PAGE_FETCH_SITES not found in api/main.py");+ const apiValues = [...literal[1].matchAll(/"([^"]*)"/g)].map((m) => m[1]);+ assert.deepEqual([...OWN_PAGE_FETCH_SITES].sort(), apiValues.sort());+});diff --git a/packages/ui/scripts/devMode.mjs b/packages/ui/scripts/devMode.mjsnew file mode 100644index 00000000..324dd144--- /dev/null+++ b/packages/ui/scripts/devMode.mjs@@ -0,0 +1,34 @@+// How `make dev` should start the UI. Decided from the settings the app+// itself will see — the root .env the recipe exported, plus+// packages/ui/.env*, loaded the way Next.js loads them — and with the app's+// own rule (lib/localLogin.ts), so the recipe and the sign-in page can never+// disagree about local login.+//+// Prints one word:+// sign-in start as usual (Google sign-in, or a server setting)+// local-login bind 127.0.0.1 and set OE_LOCAL_LOGIN+// local-login-no-secret the same, and AUTH_SECRET is blank everywhere, so+// the recipe supplies a throwaway one for this run+//+// Needs Node 22.6+ (it imports the TypeScript rule directly, as `npm test`+// does).+import { createRequire } from "node:module";+import { localLoginEnabled } from "../src/lib/localLogin.ts";++// @next/env is Next's own env loader, a dependency of `next` itself: resolved+// from there, so this is exactly the loader (and version) `next dev` runs.+const requireFromNext = createRequire(createRequire(import.meta.url).resolve("next/package.json"));+const { loadEnvConfig } = requireFromNext("@next/env");++loadEnvConfig(process.cwd(), true, { info() {}, error() {} });++const useLocalLogin = localLoginEnabled({+ devServer: true,+ flag: "1",+ googleClientId: process.env.AUTH_GOOGLE_ID,+ publicDeployment: process.env.OE_PUBLIC_DEPLOYMENT,+});++process.stdout.write(+ !useLocalLogin ? "sign-in" : process.env.AUTH_SECRET?.trim() ? "local-login" : "local-login-no-secret",+);diff --git a/packages/ui/scripts/localLogin.test.mjs b/packages/ui/scripts/localLogin.test.mjsnew file mode 100644index 00000000..0017f547--- /dev/null+++ b/packages/ui/scripts/localLogin.test.mjs@@ -0,0 +1,117 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import {+ FALSEY_ENV,+ isLoopbackHost,+ localLoginEnabled,+ localLoginSessionAllowed,+} from "../src/lib/localLogin.ts";++// `make dev` with Google sign-in not set up — the one configuration that opens+// local login. Each test below changes one thing about it.+const MAKE_DEV = {+ devServer: true,+ flag: "1",+ googleClientId: "",+ publicDeployment: undefined,+};++// --- localLoginEnabled -------------------------------------------------++test("make dev without Google sign-in turns local login on", () => {+ assert.equal(localLoginEnabled(MAKE_DEV), true);+});++test("a production build never runs local login", () => {+ assert.equal(localLoginEnabled({ ...MAKE_DEV, devServer: false }), false);+});++test("without the flag make dev sets (plain npm run dev, Docker) it stays off", () => {+ assert.equal(localLoginEnabled({ ...MAKE_DEV, flag: undefined }), false);+ assert.equal(localLoginEnabled({ ...MAKE_DEV, flag: "" }), false);+ assert.equal(localLoginEnabled({ ...MAKE_DEV, flag: "true" }), false);+});++test("once Google sign-in is set up it is the only way in", () => {+ assert.equal(localLoginEnabled({ ...MAKE_DEV, googleClientId: "123.apps.googleusercontent.com" }), false);+ // Whitespace alone is not a client id.+ assert.equal(localLoginEnabled({ ...MAKE_DEV, googleClientId: " " }), true);+});++test("OE_PUBLIC_DEPLOYMENT's off-values match the API's exactly", () => {+ // If the UI counted a value as "off" that the API counts as "on", an+ // internet-facing API could sit behind a UI that opens without sign-in.+ const mainPy = readFileSync(new URL("../../core/openexecutive/api/main.py", import.meta.url), "utf8");+ const literal = /_FALSEY_ENV = frozenset\(\{([^}]*)\}\)/.exec(mainPy);+ assert.ok(literal, "_FALSEY_ENV not found in api/main.py");+ const apiValues = [...literal[1].matchAll(/"([^"]*)"/g)].map((m) => m[1]);+ assert.deepEqual([...FALSEY_ENV].sort(), apiValues.sort());+});++test("a public deployment always requires sign-in, read like the API reads it", () => {+ for (const on of ["1", "true", "YES", " on "]) {+ assert.equal(localLoginEnabled({ ...MAKE_DEV, publicDeployment: on }), false, on);+ }+ for (const off of ["", "0", "false", "No", "off"]) {+ assert.equal(localLoginEnabled({ ...MAKE_DEV, publicDeployment: off }), true, off);+ }+});++// --- isLoopbackHost ---------------------------------------------------------++test("loopback names are accepted with or without a port", () => {+ for (const host of ["localhost", "localhost:3000", "LOCALHOST:3000", "127.0.0.1", "127.0.0.1:3000", "[::1]", "[::1]:3000"]) {+ assert.equal(isLoopbackHost(host), true, host);+ }+});++test("other machines and look-alike names are refused", () => {+ for (const host of [+ "192.168.1.20:3000", // the same laptop, reached over the LAN+ "exec.example.com",+ "localhost.example.com", // DNS rebinding keeps the attacker's own name+ "127.0.0.1.nip.io",+ "evil.com:3000",+ "localhost:[email protected]",+ "localhost:abc",+ "[::1]x",+ "::1", // an IPv6 Host header must be bracketed+ "[::ffff:192.168.1.20]:3000",+ ]) {+ assert.equal(isLoopbackHost(host), false, host);+ }+});++test("the API's loopback rule accepts exactly the hosts the UI's does", () => {+ // With local login both apps gate on "addressed to this computer". The API+ // keeps its own regex (api/main.py _LOOPBACK_HOST_RE, used with fullmatch+ // after strip); this runs one corpus through both so they cannot drift.+ const mainPy = readFileSync(new URL("../../core/openexecutive/api/main.py", import.meta.url), "utf8");+ const literal = /_LOOPBACK_HOST_RE = re\.compile\(r"([^"]+)", re\.IGNORECASE\)/.exec(mainPy);+ assert.ok(literal, "_LOOPBACK_HOST_RE not found in api/main.py");+ const apiRule = new RegExp(`^(?:${literal[1]})$`, "i");+ for (const host of [+ "localhost", "localhost:3000", "LOCALHOST:8000", "127.0.0.1", "127.0.0.1:8000", "[::1]", "[::1]:8000",+ " localhost:3000 ", "localhost:", "localhost:123456", "localhost.", "localhost.example.com",+ "127.0.0.1.nip.io", "127.0.0.2", "0.0.0.0", "::1", "[::ffff:127.0.0.1]", "192.168.1.20:3000",+ "evil.com", "localhost:[email protected]", "",+ ]) {+ assert.equal(apiRule.test(host.trim()), isLoopbackHost(host), JSON.stringify(host));+ }+});++test("a missing Host header is refused", () => {+ assert.equal(isLoopbackHost(null), false);+ assert.equal(isLoopbackHost(undefined), false);+ assert.equal(isLoopbackHost(""), false);+});++// --- localLoginSessionAllowed -----------------------------------------------++test("a local-login session works only while it is on and on this machine", () => {+ assert.equal(localLoginSessionAllowed(true, "localhost:3000"), true);+ assert.equal(localLoginSessionAllowed(true, "192.168.1.20:3000"), false);+ // Google sign-in was set up since: the old session stops working.+ assert.equal(localLoginSessionAllowed(false, "localhost:3000"), false);+});diff --git a/packages/ui/src/app/api/backend/[...path]/route.ts b/packages/ui/src/app/api/backend/[...path]/route.tsindex cb7e7d22..378b44ec 100644--- a/packages/ui/src/app/api/backend/[...path]/route.ts+++ b/packages/ui/src/app/api/backend/[...path]/route.ts@@ -1,5 +1,7 @@import { NextRequest } from "next/server";-import { auth } from "@/auth";+import { LOCAL_LOGIN, auth } from "@/auth";+import { isCrossSiteWrite } from "@/lib/crossSite";+import { localLoginSessionAllowed } from "@/lib/localLogin";// Streaming-aware proxy to the FastAPI backend. Replaces the `rewrites()` rule// in next.config.ts, which buffers SSE responses in dev so the chat stream@@ -16,10 +18,27 @@ const BACKEND_BASE = process.env.BACKEND_BASE_URL ?? "http://localhost:8000";const BACKEND_SHARED_SECRET = process.env.BACKEND_SHARED_SECRET ?? "";async function proxy(req: NextRequest, params: { path: string[] }): Promise<Response> {+ // Another page on this site (any localhost port counts) must not be able to+ // make the browser post here with the user's cookie — see lib/crossSite.ts.+ if (isCrossSiteWrite(req.method, req.headers.get("sec-fetch-site"))) {+ return new Response(JSON.stringify({ error: "cross-site request refused" }), {+ status: 403,+ headers: { "content-type": "application/json" },+ });+ }+// Belt-and-suspenders: middleware should have already rejected unauthenticated// traffic, but check here too so a stray client can't reach the backend.const session = await auth();- if (!session?.user) {+ // A local-login session has no email on purpose: the backend reads a+ // request with no `x-caller-email` as the principal (the CLI's fallback).+ // So it is re-checked here, where it reaches the API, and every OTHER+ // session must carry an email — without one it would be read the same way.+ const callerEmail = session?.user?.email?.toLowerCase();+ const allowed = session?.localLogin+ ? localLoginSessionAllowed(LOCAL_LOGIN, req.headers.get("host"))+ : Boolean(callerEmail);+ if (!allowed) {return new Response(JSON.stringify({ error: "unauthorized" }), {status: 401,headers: { "content-type": "application/json" },@@ -66,8 +85,7 @@ async function proxy(req: NextRequest, params: { path: string[] }): Promise<Resp// filtering on /audit, /today, etc.). Source: the verified NextAuth// session — clients have no way to set this themselves (stripped// above).- const callerEmail = session.user.email?.toLowerCase();- if (callerEmail) {+ if (callerEmail && !session?.localLogin) {headers.set("x-caller-email", callerEmail);}diff --git a/packages/ui/src/app/signin/page.tsx b/packages/ui/src/app/signin/page.tsxindex 6c21bcf8..584a8ec1 100644--- a/packages/ui/src/app/signin/page.tsx+++ b/packages/ui/src/app/signin/page.tsx@@ -1,5 +1,8 @@-import { signIn, auth } from "@/auth";+import { AuthError } from "next-auth";+import { headers } from "next/headers";import { redirect } from "next/navigation";+import { LOCAL_LOGIN, auth, sessionStillAllowed, signIn } from "@/auth";+import { LOCAL_LOGIN_PROVIDER_ID } from "@/lib/localLogin";type SearchParams = Promise<{ callbackUrl?: string; error?: string }>;@@ -15,19 +18,26 @@ export default async function SignInPage({ searchParams }: { searchParams: Searcconst { callbackUrl, error } = await searchParams;const safeDest = safeCallbackUrl(callbackUrl);- // If already signed in, bounce straight to the destination.+ // If already signed in, bounce straight to the destination — but only with a+ // session the middleware still accepts. A revoked one would be sent straight+ // back here, forever.const session = await auth();- if (session?.user) {+ if (session && (await sessionStillAllowed(session, (await headers()).get("host")))) {redirect(safeDest);}const errorMessage = error ? describeError(error) : null;+ const googleConfigured = Boolean(process.env.AUTH_GOOGLE_ID?.trim());return (<main className="min-h-screen flex items-center justify-center px-6"><div className="w-full max-w-sm rounded-2xl border border-line bg-surface/60 p-8 shadow-xl"><h1 className="text-xl font-semibold tracking-tight text-fg">Open Executive</h1>- <p className="mt-2 text-sm text-fg-muted">Sign in to continue.</p>+ <p className="mt-2 text-sm text-fg-muted">+ {LOCAL_LOGIN+ ? "This copy runs on your computer, and only you can reach it — so there’s no sign-in."+ : "Sign in to continue."}+ </p>{errorMessage && (<p className="mt-4 rounded-md border border-red-900/50 bg-red-950/40 px-3 py-2 text-sm text-red-200">@@ -35,20 +45,60 @@ export default async function SignInPage({ searchParams }: { searchParams: Searc</p>)}- <form- action={async () => {- "use server";- await signIn("google", { redirectTo: safeDest });- }}- className="mt-6"- >- <button- type="submit"- className="w-full rounded-md bg-white px-4 py-2 text-sm font-medium text-zinc-900 hover:bg-zinc-100 transition"- >- Sign in with Google- </button>- </form>+ {LOCAL_LOGIN ? (+ <>+ <form+ action={async () => {+ "use server";+ try {+ await signIn(LOCAL_LOGIN_PROVIDER_ID, { redirectTo: safeDest });+ } catch (err) {+ // A refused sign-in throws; success throws Next's redirect, which must pass through.+ if (err instanceof AuthError) {+ redirect(+ `/signin?error=${encodeURIComponent(err.type)}&callbackUrl=${encodeURIComponent(safeDest)}`,+ );+ }+ throw err;+ }+ }}+ className="mt-6"+ >+ <button+ type="submit"+ className="w-full rounded-md bg-white px-4 py-2 text-sm font-medium text-zinc-900 hover:bg-zinc-100 transition"+ >+ Open+ </button>+ </form>+ <p className="mt-4 text-xs text-fg-subtle">+ To invite your team, or to run it on a server, set up Google sign-in (see docs/auth.md).+ </p>+ </>+ ) : (+ <>+ <form+ action={async () => {+ "use server";+ await signIn("google", { redirectTo: safeDest });+ }}+ className="mt-6"+ >+ <button+ type="submit"+ className="w-full rounded-md bg-white px-4 py-2 text-sm font-medium text-zinc-900 hover:bg-zinc-100 transition"+ >+ Sign in with Google+ </button>+ </form>+ {!googleConfigured && (+ <p className="mt-4 text-xs text-fg-subtle">+ Google sign-in isn’t set up here yet (see docs/auth.md). On your own computer,+ start Open Executive with <code>make dev</code> to use it without signing in.+ </p>+ )}+ </>+ )}</div></main>);@@ -58,6 +108,8 @@ function describeError(code: string): string {switch (code) {case "AccessDenied":return "Your Google account is not on the allow-list for this workspace. Ask an admin to add you.";+ case "CredentialsSignin":+ return "Open only works in a browser on the computer running Open Executive, at http://localhost:3000.";case "Configuration":return "Authentication is misconfigured. Contact the administrator.";default:diff --git a/packages/ui/src/auth.ts b/packages/ui/src/auth.tsindex af980e21..e8a02cb9 100644--- a/packages/ui/src/auth.ts+++ b/packages/ui/src/auth.ts@@ -1,12 +1,21 @@-import NextAuth from "next-auth";+import NextAuth, { type Session } from "next-auth";+import Credentials from "next-auth/providers/credentials";import Google from "next-auth/providers/google";+import type { NextRequest } from "next/server";import {createRosterLoader,decideSessionAction,describeDenial,parseAllowedEmails,resolveAllowed,+ type AllowDecision,} from "@/lib/allowlist";+import {+ LOCAL_LOGIN_PROVIDER_ID,+ isLoopbackHost,+ localLoginEnabled,+ localLoginSessionAllowed,+} from "@/lib/localLogin";// Operator-controlled allowlist, read once at startup (docs/auth.md promises a// restart is what makes an edit live). ALWAYS honored: the backend People@@ -17,6 +26,31 @@ const ENV_ALLOWED = parseAllowedEmails(process.env.ALLOWED_EMAILS);const BACKEND_BASE = process.env.BACKEND_BASE_URL ?? "http://localhost:8000";const BACKEND_SHARED_SECRET = process.env.BACKEND_SHARED_SECRET ?? "";+// Local login — `make dev` with Google sign-in not set up (see+// lib/localLogin.ts for the whole guard). `process.env.NODE_ENV` is written out+// literally on purpose: Next.js folds it to a build-time constant, so a+// production build (`next build`, the deploy image) compiles the mode out+// whatever its runtime environment says.+export const LOCAL_LOGIN = localLoginEnabled({+ devServer: process.env.NODE_ENV !== "production",+ flag: process.env.OE_LOCAL_LOGIN,+ googleClientId: process.env.AUTH_GOOGLE_ID,+ publicDeployment: process.env.OE_PUBLIC_DEPLOYMENT,+});++// No password: `authorize` admits only a request whose raw Host header is+// loopback. It signs in one fixed user with no email, which the proxy turns+// into "no x-caller-email", i.e. the principal.+const localLogin = Credentials({+ id: LOCAL_LOGIN_PROVIDER_ID,+ name: "This computer",+ credentials: {},+ authorize: (_credentials, request) =>+ LOCAL_LOGIN && isLoopbackHost(request.headers.get("host"))+ ? { id: LOCAL_LOGIN_PROVIDER_ID }+ : null,+});+// How long a fetched roster is trusted. `authorized` runs on nearly every// gated request, so this is what keeps one page load from becoming N backend// calls — and it bounds how long an archived Person stays admitted. Quoted as@@ -71,6 +105,59 @@ function auditAuth(});}+type SessionVerdict =+ | { kind: "allow" }+ | { kind: "deny" }+ | { kind: "revoke"; email: string; decision: AllowDecision };++/**+ * May this existing session still be used? The per-request re-check behind+ * the `authorized` callback, and what /signin asks before bouncing a visitor+ * onward (bouncing a session the middleware refuses would loop).+ *+ * A local-login session is valid only while that mode is on and the+ * request comes from this machine. A Google session is re-checked against the+ * allow-list: it fails open ONLY when the user is not in ALLOWED_EMAILS and+ * their roster membership is currently unreadable, so a brief backend hiccup+ * doesn't sign out everyone — the strict `signIn` gate already vetted them+ * once. A *definite* miss (both lists readable, neither matched) revokes.+ */+async function judgeSession(session: Session | null, host: string | null): Promise<SessionVerdict> {+ if (session?.localLogin) {+ return localLoginSessionAllowed(LOCAL_LOGIN, host) ? { kind: "allow" } : { kind: "deny" };+ }+ const email = session?.user?.email?.toLowerCase();+ if (!email) return { kind: "deny" };+ const decision = await checkEmailAllowed(email);+ // Exhaustive on purpose: a `!== "revoke"` test would admit any future+ // SessionAction, i.e. fail open. This way adding one is a build error.+ switch (decideSessionAction(decision)) {+ case "allow":+ case "allow_roster_unknown":+ return { kind: "allow" };+ case "revoke":+ return { kind: "revoke", email, decision };+ }+}++export async function sessionStillAllowed(session: Session | null, host: string | null): Promise<boolean> {+ return (await judgeSession(session, host)).kind === "allow";+}++/**+ * The response a refused request gets: JSON 401 for API routes (a redirect+ * would be followed by fetch() and break the caller), otherwise a redirect to+ * /signin carrying a same-origin path the sign-in page's own check accepts.+ */+function refuse(request: NextRequest): Response {+ if (request.nextUrl.pathname.startsWith("/api/")) {+ return Response.json({ error: "unauthorized" }, { status: 401 });+ }+ const signInUrl = new URL("/signin", request.nextUrl.origin);+ signInUrl.searchParams.set("callbackUrl", request.nextUrl.pathname + request.nextUrl.search);+ return Response.redirect(signInUrl);+}+export const { handlers, auth, signIn, signOut } = NextAuth({// @auth/core auto-detects trustHost via `AUTH_URL ?? AUTH_TRUST_HOST ??// VERCEL ?? CF_PAGES ?? NODE_ENV !== "production"` — a chain of `??`@@ -95,10 +182,15 @@ export const { handlers, auth, signIn, signOut } = NextAuth({// setup already sets AUTH_TRUST_HOST=true explicitly and never relied on// that fallback anyway. A deployment that sets neither AUTH_URL nor// AUTH_TRUST_HOST gets `false` here — fail-closed, matching intent.+ // Local login trusts the host without being told: there is no OAuth+ // redirect to steer, only this machine can connect, and its own checks read+ // the raw Host header, never the forwarded one.trustHost:Boolean(process.env.AUTH_URL?.trim()) ||- process.env.AUTH_TRUST_HOST?.trim().toLowerCase() === "true",- providers: [Google],+ process.env.AUTH_TRUST_HOST?.trim().toLowerCase() === "true" ||+ LOCAL_LOGIN,+ // Never both: local login is only ever on while Google is not set up.+ providers: LOCAL_LOGIN ? [localLogin] : [Google],// 24h JWT TTL. Defence in depth alongside the `authorized` re-check// below — a session that somehow drifts out of sync with the roster// is corrected on next access, but also naturally expires within a@@ -111,8 +203,10 @@ export const { handlers, auth, signIn, signOut } = NextAuth({callbacks: {// Strict initial gate. Requires `email_verified === true` explicitly: a// missing / non-boolean value fails closed. Google always returns true- // for real accounts.- signIn: async ({ profile }) => {+ // for real accounts. A local-login sign-in was already vetted by the+ // provider's `authorize` (mode on, loopback Host).+ signIn: async ({ account, profile }) => {+ if (account?.provider === LOCAL_LOGIN_PROVIDER_ID) return LOCAL_LOGIN;const email = profile?.email?.toLowerCase();if (!email) {auditAuth("auth_login", "Login denied: no email", null, { denied: true, reason: "no_email" });@@ -139,55 +233,63 @@ export const { handlers, auth, signIn, signOut } = NextAuth({}return true;},- // Re-runs on every request gated by the middleware (see middleware.ts).- // Without this, a user removed from the roster mid-session — or one- // whose JWT predates the roster being installed — would keep coasting- // until their JWT expires.- //- // Fails open ONLY for a session that is not in ALLOWED_EMAILS and whose- // roster membership is currently unreadable, so a brief backend hiccup- // doesn't sign out everyone with a valid session — the strict `signIn`- // gate already vetted them once. A *definite* miss (both lists readable,- // neither matched) still revokes. `decideSessionAction` owns that- // ordering so it can be tested without importing this module.- authorized: async ({ auth }) => {- if (!auth?.user?.email) return false;- const email = auth.user.email.toLowerCase();- const decision = await checkEmailAllowed(email);- // Exhaustive on purpose: a `!== "revoke"` test would admit any future- // SessionAction, i.e. fail open. This way adding one is a build error.- switch (decideSessionAction(decision)) {- case "allow":- case "allow_roster_unknown":- return true;- case "revoke":- // Fire-and-forget audit so a mid-session eviction leaves a- // trail even if the user never re-attempts sign-in.- auditAuth(- "auth_logout",- `Session revoked: ${email} (${describeDenial(decision.source)})`,- email,- {- revoked: true,- reason: "not_in_allowlist",- source: decision.source,- // Always false on this branch; read off the decision anyway so- // it cannot silently desync from decideSessionAction.- roster_unavailable: decision.rosterUnknown,- },- );- return false;+ // `account` is present only on the sign-in request itself, so the flag is+ // set once and then rides the JWT.+ jwt: ({ token, account }) => {+ if (account) token.localLogin = account.provider === LOCAL_LOGIN_PROVIDER_ID;+ return token;+ },+ session: ({ session, token }) => {+ session.localLogin = token.localLogin === true;+ return session;+ },+ // Re-runs on every request gated by the middleware (see middleware.ts),+ // so a user removed from the roster mid-session — or one whose JWT+ // predates the roster being installed — is refused on their next request+ // instead of coasting until their JWT expires. Returns a Response rather+ // than `false` so API routes get JSON 401s instead of Auth.js's default+ // HTML redirect.+ authorized: async ({ auth, request }) => {+ const verdict = await judgeSession(auth, request.headers.get("host"));+ if (verdict.kind === "allow") return true;+ if (verdict.kind === "revoke") {+ // Fire-and-forget audit so a mid-session eviction leaves a+ // trail even if the user never re-attempts sign-in.+ auditAuth(+ "auth_logout",+ `Session revoked: ${verdict.email} (${describeDenial(verdict.decision.source)})`,+ verdict.email,+ {+ revoked: true,+ reason: "not_in_allowlist",+ source: verdict.decision.source,+ // Always false on this branch; read off the decision anyway so+ // it cannot silently desync from decideSessionAction.+ roster_unavailable: verdict.decision.rosterUnknown,+ },+ );}+ return refuse(request);},},events: {- signIn: ({ user }) => {+ signIn: ({ user, account }) => {+ if (account?.provider === LOCAL_LOGIN_PROVIDER_ID) {+ auditAuth("auth_login", "Login: the owner, on this computer (local login)", null, {+ provider: LOCAL_LOGIN_PROVIDER_ID,+ });+ return;+ }const email = user.email?.toLowerCase() ?? null;auditAuth("auth_login", `Login: ${email ?? "unknown"}`, email, { provider: "google" });},signOut: (message) => {// JWT strategy sends { token }, session strategy sends { session }.const token = "token" in message ? message.token : undefined;+ if (token?.localLogin === true) {+ auditAuth("auth_logout", "Logout: the owner, on this computer (local login)", null, {});+ return;+ }const email = typeof token?.email === "string" ? token.email.toLowerCase() : null;auditAuth("auth_logout", `Logout: ${email ?? "unknown"}`, email, {});},diff --git a/packages/ui/src/components/UserBadge.tsx b/packages/ui/src/components/UserBadge.tsxindex 6264f0dc..745d8b89 100644--- a/packages/ui/src/components/UserBadge.tsx+++ b/packages/ui/src/components/UserBadge.tsx@@ -28,6 +28,29 @@ export default function UserBadge({ variant = "compact" }: UserBadgeProps) {);}+ // Local login: no Google account and nothing to sign out of — the+ // sign-in page would just offer "Open" again.+ if (session?.localLogin) {+ return (+ <div+ className={+ variant === "sidebar"+ ? "px-3 py-3 border-t border-line flex items-center gap-2.5 flex-shrink-0"+ : "flex items-center gap-2 text-xs text-fg-muted"+ }+ title="Local login: only this computer can reach Open Executive"+ >+ <Avatar name="ME" size={variant === "sidebar" ? "w-7 h-7" : "w-6 h-6"} />+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-fg truncate">You (owner)</p>+ {variant === "sidebar" && (+ <p className="text-[10px] text-fg-muted truncate">On this computer</p>+ )}+ </div>+ </div>+ );+ }+const user = session?.user;if (!user?.email) {return null; // shouldn't happen post-middleware, but fail quietdiff --git a/packages/ui/src/components/onboard/OnboardDraftReview.tsx b/packages/ui/src/components/onboard/OnboardDraftReview.tsxindex 421e51b9..abea06e3 100644--- a/packages/ui/src/components/onboard/OnboardDraftReview.tsx+++ b/packages/ui/src/components/onboard/OnboardDraftReview.tsx@@ -1,12 +1,14 @@"use client";import { useCallback, useEffect, useState } from "react";+import { useSession } from "next-auth/react";import { ProfileSections } from "@/components/company-profile/ProfileSections";import OnboardDepartmentsDraft from "@/components/onboard/OnboardDepartmentsDraft";import OnboardPeopleDraft from "@/components/onboard/OnboardPeopleDraft";import {commitOnboardDraft,listDepartments,+ listPeople,type CompanyProfile,type OnboardDepartmentDraft,type OnboardPersonDraft,@@ -34,11 +36,26 @@ export default function OnboardDraftReview({const [existingTitles, setExistingTitles] = useState<string[]>([]);const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);+ // The owner's sign-in email. Pre-filled with the owner's current one when+ // setup is re-run — so whoever re-runs it doesn't silently take over the+ // owner's login — otherwise with the login doing the setup. Null until+ // edited, so the field follows both as they load.+ // Save waits for both: the commit runs once per setup session, so saving+ // before they load would send no email with no way to add it afterwards.+ const { data: session, status: sessionStatus } = useSession();+ const [currentOwnerEmail, setCurrentOwnerEmail] = useState<string | null>(null);+ const [ownerLookupDone, setOwnerLookupDone] = useState(false);+ const [ownerEmailEdit, setOwnerEmailEdit] = useState<string | null>(null);+ const ownerEmail = ownerEmailEdit ?? currentOwnerEmail ?? session?.user?.email ?? "";useEffect(() => {listDepartments().then((ds) => setExistingTitles(ds.map((d) => d.config.title))).catch(() => setExistingTitles([]));+ listPeople()+ .then((ps) => setCurrentOwnerEmail(ps.find((p) => p.is_principal && p.email)?.email ?? null))+ .catch(() => setCurrentOwnerEmail(null))+ .finally(() => setOwnerLookupDone(true));}, []);// The seam that lets the /company-profile section editors work here: they@@ -60,6 +77,8 @@ export default function OnboardDraftReview({new Set(namedDepartments.map((d) => d.title.trim().toLowerCase())).size !==namedDepartments.length;+ // The owner email is checked only by the server (check_owner_email): a+ // rejection comes back as the error below and leaves the draft editable.const blocker = !profile.name.trim()? "Your company needs a name.": namedPeople.length === 0@@ -70,14 +89,16 @@ export default function OnboardDraftReview({? "Two people have the same name — give them distinct names.": duplicateDepartments? "Two departments have the same name."- : null;+ : sessionStatus === "loading" || !ownerLookupDone+ ? "Loading your sign-in details…"+ : null;async function save() {if (blocker || saving) return;setSaving(true);setError(null);try {- await commitOnboardDraft(turn.session_id, profile, namedPeople, namedDepartments);+ await commitOnboardDraft(turn.session_id, profile, namedPeople, namedDepartments, ownerEmail);onSaved();} catch (err) {setError((err as Error).message);@@ -149,6 +170,27 @@ export default function OnboardDraftReview({setPeople(next);}}/>+ <div className="bg-surface-elevated border border-line rounded-xl p-5">+ <label htmlFor="owner-email" className="text-sm font-semibold text-fg">+ Your sign-in email+ </label>+ <p className="text-xs text-fg-muted mt-1 mb-3">+ Links the person marked “This is me” to this login, so your chats and+ owner rights work straight away. Setting this up for someone else? Enter the+ Google email they will sign in with.+ {session?.localLogin &&+ " Optional on this computer — add one if you set up Google sign-in later."}+ </p>+ <input+ id="owner-email"+ type="email"+ value={ownerEmail}+ onChange={(e) => setOwnerEmailEdit(e.target.value)}+ placeholder="[email protected]"+ autoComplete="email"+ className="w-full rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition-colors"+ />+ </div><OnboardDepartmentsDraftdepartments={departments}people={people}diff --git a/packages/ui/src/components/onboard/OnboardPeopleDraft.tsx b/packages/ui/src/components/onboard/OnboardPeopleDraft.tsxindex 5c8883d0..c6f8dee2 100644--- a/packages/ui/src/components/onboard/OnboardPeopleDraft.tsx+++ b/packages/ui/src/components/onboard/OnboardPeopleDraft.tsx@@ -8,7 +8,9 @@ interface Props {}/** The leadership roster. Deliberately has no contact columns: OE never- * auto-imports emails or chat handles — those are added on the People page. */+ * auto-imports emails or chat handles — those are added on the People page.+ * The one exception, the owner's own sign-in email, is its own field on the+ * review screen (OnboardDraftReview), confirmed by the person signing in. */export default function OnboardPeopleDraft({ people, onChange }: Props) {function update(i: number, patch: Partial<OnboardPersonDraft>) {onChange(people.map((p, j) => (j === i ? { ...p, ...patch } : p)));@@ -33,8 +35,8 @@ export default function OnboardPeopleDraft({ people, onChange }: Props) {</div><p className="text-xs text-fg-muted mb-4">Mark yourself with “This is me” — that’s who the Executive- reports to and escalates to. Contact details are added later on the People- page.+ reports to and escalates to. Other contact details are added later on the+ People page.</p>{people.length === 0 && (diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex 0ab9a9d0..c8119512 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -380,7 +380,9 @@ export async function commitOnboardDraft(sessionId: string,profile: CompanyProfile,people: OnboardPersonDraft[],- departments: OnboardDepartmentDraft[]+ departments: OnboardDepartmentDraft[],+ /** The principal's sign-in email, confirmed on the review screen. Blank = don't set one. */+ ownerEmail = ""): Promise<CompanyProfile> {const res = await fetch(`${API_BASE}/onboard/interview/commit`, {method: "POST",@@ -390,6 +392,7 @@ export async function commitOnboardDraft(profile,people,departments,+ owner_email: ownerEmail.trim() || null,}),});if (!res.ok) throw await onboardError(res, "Could not save your profile");diff --git a/packages/ui/src/lib/crossSite.ts b/packages/ui/src/lib/crossSite.tsnew file mode 100644index 00000000..c31fc0ca--- /dev/null+++ b/packages/ui/src/lib/crossSite.ts@@ -0,0 +1,28 @@+// Refuses state-changing requests to the backend proxy that another site made+// the browser send.+//+// The session cookie is SameSite=Lax, which stops other websites but not+// other pages on the same *site* — and to a browser every localhost port is+// one site. So any other local dev server (or a page a local tool serves)+// could otherwise post a form to /api/backend/* with the owner's cookie+// attached; the multipart routes (chat uploads, documents) would accept it.+// `Sec-Fetch-Site` is set by the browser itself and a page cannot forge it.+// A request without it (a non-browser client, or a browser from before 2023)+// is left to SameSite alone, as before.+//+// No imports, so `npm test` can exercise this under+// `node --experimental-strip-types` (see scripts/crossSite.test.mjs).++const READ_ONLY_METHODS = new Set(["GET", "HEAD"]);++/**+ * Sec-Fetch-Site values for a request the page's own origin (or a typed URL)+ * made. The API applies the same rule under local login (api/main.py+ * _OWN_PAGE_FETCH_SITES); scripts/crossSite.test.mjs fails if they drift.+ */+export const OWN_PAGE_FETCH_SITES: ReadonlySet<string> = new Set(["same-origin", "none"]);++export function isCrossSiteWrite(method: string, secFetchSite: string | null): boolean {+ if (READ_ONLY_METHODS.has(method.toUpperCase()) || secFetchSite === null) return false;+ return !OWN_PAGE_FETCH_SITES.has(secFetchSite.trim().toLowerCase());+}diff --git a/packages/ui/src/lib/localLogin.ts b/packages/ui/src/lib/localLogin.tsnew file mode 100644index 00000000..bbcde374--- /dev/null+++ b/packages/ui/src/lib/localLogin.ts@@ -0,0 +1,70 @@+// Local login: running Open Executive on your own computer without setting+// up Google sign-in. The sign-in page offers an "Open" button instead, and the+// session it creates carries no email — so the UI proxy sends no+// `x-caller-email`, and the backend treats the caller as the principal, exactly+// as it does for the CLI.+//+// There is no password, so the guard is WHERE a request can come from:+// 1. `make dev` is the only thing that sets OE_LOCAL_LOGIN, and the same+// recipe line starts the UI with `-H 127.0.0.1`, so nothing off this+// machine can connect. Docker (`make docker`) and deploy images never set+// it, and a production build compiles local login out (see auth.ts).+// 2. Every sign-in and every request must carry a loopback `Host` header.+// That stops a DNS-rebinding page — a site the owner visits that re-points+// its own hostname at 127.0.0.1 — because a browser always sends the+// page's real hostname as `Host` and scripts cannot override it. Scripts+// CAN set `X-Forwarded-Host`, which is why the raw header is read and not+// `request.url` (Auth.js rebuilds that from X-Forwarded-Host under+// trustHost).+//+// No imports, so `npm test` can exercise this under+// `node --experimental-strip-types` (see scripts/localLogin.test.mjs).++/** The Auth.js provider id, and the id of the one user it signs in. */+export const LOCAL_LOGIN_PROVIDER_ID = "local-login";++export interface LocalLoginEnv {+ /** False in a production build (`next build`); the mode never applies there. */+ devServer: boolean;+ /** OE_LOCAL_LOGIN — set only by `make dev`, with the loopback bind. */+ flag: string | undefined;+ /** AUTH_GOOGLE_ID — once Google sign-in is set up, it is the only way in. */+ googleClientId: string | undefined;+ /** OE_PUBLIC_DEPLOYMENT — an internet-facing instance always requires sign-in. */+ publicDeployment: string | undefined;+}++// Mirrors api/main.py's _FALSEY_ENV, so both apps read OE_PUBLIC_DEPLOYMENT+// alike; scripts/localLogin.test.mjs fails if the two drift apart.+export const FALSEY_ENV: ReadonlySet<string> = new Set(["", "0", "false", "no", "off"]);++export function localLoginEnabled(env: LocalLoginEnv): boolean {+ return (+ env.devServer &&+ env.flag?.trim() === "1" &&+ !env.googleClientId?.trim() &&+ FALSEY_ENV.has((env.publicDeployment ?? "").trim().toLowerCase())+ );+}++const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);++/**+ * True when a raw `Host` header names this machine: `localhost`,+ * `127.0.0.1` or `[::1]`, with or without a numeric port. Anything else —+ * a LAN address, `localhost.example.com`, a missing header — is false.+ */+export function isLoopbackHost(host: string | null | undefined): boolean {+ if (!host) return false;+ const match = /^(\[[0-9a-f:.]+\]|[^:[\]]+)(?::(\d{1,5}))?$/.exec(host.trim().toLowerCase());+ return match !== null && LOOPBACK_HOSTNAMES.has(match[1]);+}++/**+ * Whether a local-login session may be used for this request. It stays+ * valid only while the mode is on and the request still comes from this+ * machine — so setting up Google sign-in ends it on the next request.+ */+export function localLoginSessionAllowed(modeEnabled: boolean, host: string | null | undefined): boolean {+ return modeEnabled && isLoopbackHost(host);+}diff --git a/packages/ui/src/middleware.ts b/packages/ui/src/middleware.tsindex 9d13f9cc..5b729c0a 100644--- a/packages/ui/src/middleware.ts+++ b/packages/ui/src/middleware.ts@@ -1,21 +1,12 @@-import { auth } from "@/auth";--// Gate every page + non-auth API route. `auth` from NextAuth v5 wraps a-// handler that injects req.auth; here we use it directly as middleware, which-// makes unauthenticated requests redirect to the configured sign-in page.-export default auth((req) => {- if (req.auth) return;-- // For API routes, return JSON 401 instead of an HTML redirect so the- // browser doesn't follow it and break fetch() callers.- if (req.nextUrl.pathname.startsWith("/api/")) {- return Response.json({ error: "unauthorized" }, { status: 401 });- }-- const signInUrl = new URL("/signin", req.nextUrl.origin);- signInUrl.searchParams.set("callbackUrl", req.nextUrl.pathname + req.nextUrl.search);- return Response.redirect(signInUrl);-});+// Gate every page + non-auth API route. The decision, and the response a+// refused request gets (JSON 401 for /api/*, a redirect to /signin for+// pages), live in the `authorized` callback in auth.ts.+//+// `auth` is exported as-is, not wrapped as `auth((req) => …)`: when a wrapper+// is passed, next-auth runs it even after `authorized` returns false, so the+// per-request re-check never actually refused anyone — a user removed from+// the roster kept working until their 24h JWT expired.+export { auth as middleware } from "@/auth";// Exclude Auth.js's own routes, Next internals, static assets, and exactly// `/signin` (with optional trailing slash). Using `signin/?` rather than thediff --git a/packages/ui/src/types/next-auth.d.ts b/packages/ui/src/types/next-auth.d.tsnew file mode 100644index 00000000..090734d6--- /dev/null+++ b/packages/ui/src/types/next-auth.d.ts@@ -0,0 +1,10 @@+// Local login (see lib/localLogin.ts): the `jwt` callback in auth.ts marks+// the token at sign-in and `session` copies the mark here. Such a session has+// no email by design.+import "next-auth";++declare module "next-auth" {+ interface Session {+ localLogin?: boolean;+ }+}