AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix: union ALLOWED_EMAILS with the People roster instead of letting the roster win
Rufusc5f70991095f
diff --git a/.env.example b/.env.exampleindex 84dbbcca..67bee9a1 100644--- a/.env.example+++ b/.env.example@@ -15,7 +15,11 @@ ANTHROPIC_API_KEY=sk-ant-your-key-here# - http://localhost:3000/api/auth/callback/google# - https://<your-ui-host>/api/auth/callback/google# ALLOWED_EMAILS = comma-separated list of Google-account emails permitted to-# sign in. Other emails (even with a valid Google login) are rejected.+# sign in. Always honored, and always sufficient on its own. People in the+# backend roster (non-archived Person rows with an email) are allowed IN+# ADDITION to this list, never instead of it — so roster changes cannot+# lock out an operator listed here. Any other email is rejected, even with+# a valid Google login.# AUTH_TRUST_HOST = "true" is required when running behind a reverse proxy.# AUTH_URL = public origin of the UI. LEAVE BLANK for local dev (localhost is# inferred). Required on any public deployment; AUTH_TRUST_HOST alonediff --git a/docs/auth.md b/docs/auth.mdindex 4c490788..9720933e 100644--- a/docs/auth.md+++ b/docs/auth.md@@ -10,9 +10,32 @@ Two independent layers. Either one alone would be insufficient; together they fa| Layer | What it does | Where ||---|---|---|-| **UI: Auth.js v5 + Google OAuth** | Anyone hitting the public UI is redirected to `/signin`. Only Google accounts in `ALLOWED_EMAILS` can complete sign-in. | [packages/ui/src/auth.ts](../packages/ui/src/auth.ts), [packages/ui/src/middleware.ts](../packages/ui/src/middleware.ts), [packages/ui/src/app/signin/page.tsx](../packages/ui/src/app/signin/page.tsx) |+| **UI: Auth.js v5 + Google OAuth** | Anyone hitting the public UI is redirected to `/signin`. Only Google accounts on the allow-list can complete sign-in — the **union** of `ALLOWED_EMAILS` and the People roster (see below). | [packages/ui/src/auth.ts](../packages/ui/src/auth.ts), [packages/ui/src/middleware.ts](../packages/ui/src/middleware.ts), [packages/ui/src/app/signin/page.tsx](../packages/ui/src/app/signin/page.tsx) || **API: shared-secret header** | The FastAPI backend is reachable over the network. It rejects every request whose `x-api-key` header doesn't match `BACKEND_SHARED_SECRET`. The UI proxy stamps this header on every upstream call. | [packages/core/openexecutive/api/main.py](../packages/core/openexecutive/api/main.py), [packages/ui/src/app/api/backend/[...path]/route.ts](../packages/ui/src/app/api/backend/%5B...path%5D/route.ts) |+### Who is on the allow-list++Two **additive** sources. An email is admitted if it appears in *either*:++1. **`ALLOWED_EMAILS`** — the comma-separated env var on the UI, read once at startup.+ Checked first, and a hit short-circuits: a configured operator signs in even when the+ API is completely down, and pays no roster-fetch latency.+2. **The People roster** — every non-archived Person with an email, served by+ `GET /auth/allowed-emails` and cached for 5 minutes per UI instance.++Neither one overrides the other. Adding people to the roster cannot revoke an+`ALLOWED_EMAILS` entry, and leaving `ALLOWED_EMAILS` blank is fine once the roster is+populated.++Membership is re-checked on every request the middleware gates, not just at sign-in, so a+roster removal takes effect within the cache window rather than waiting out the 24h JWT.++If the roster fetch fails, `ALLOWED_EMAILS` users are unaffected (their check never+consults the roster). Roster-only users with an existing session keep working — the UI+fails open rather than signing everyone out over a brief backend hiccup, since the strict+sign-in gate already vetted them — but a *new* roster-only sign-in is denied until the+backend answers.+### Request flow```@@ -136,16 +159,29 @@ OE_PUBLIC_DEPLOYMENT=1### Add or remove a user-Update `ALLOWED_EMAILS` on the UI and restart it:+Access comes from two additive sources, so there are two ways in — and removal means+taking the person out of **both**.++**Add via the roster (no restart).** Create a Person with that email in People. It goes+live within the 5-minute roster cache window. This is the normal path for teammates.++**Add via `ALLOWED_EMAILS` (restart).** Append the email and restart the UI:``````The list is read once at startup, so the new entry goes live when the restart finishes.+Recommended for your own operator/break-glass account: nothing that writes the roster —+a fixture load, an onboarding run, someone editing People — can take it away.Rules: comma-separated, case-insensitive, whitespace around entries is stripped, trailing commas are harmless.+**Remove a user.** Archive or delete their Person **and** drop them from+`ALLOWED_EMAILS`. Removing only one leaves the other still granting access. The roster+half lands on their next gated request once the cache expires; the env half needs a UI+restart.+### Rotate the shared secretDo this if anyone with deployment access leaves, or on a regular cadence. Generate one value and set it on both containers, then restart both:@@ -177,7 +213,8 @@ If `AUTH_GOOGLE_SECRET` is leaked, regenerate in Google Cloud Console (Clients| `OAuth client was not found` / `invalid_client` | `AUTH_GOOGLE_ID` typo, swapped with `AUTH_GOOGLE_SECRET`, or the client lives in a different GCP project || `redirect_uri_mismatch` | The Authorized redirect URI in Google Console doesn't exactly match `<origin>/api/auth/callback/google`. Wait 5 min for Google to propagate after edits || Browser tries to load `0.0.0.0` after sign-in | `AUTH_URL` not set on the UI |-| `AccessDenied` page after Google login | Email not in `ALLOWED_EMAILS`, or Google returned `email_verified !== true` |+| `AccessDenied` page after Google login | Email is in neither `ALLOWED_EMAILS` nor the People roster (the two are unioned), or Google returned `email_verified !== true`. Check the `auth_login` audit row's `source`: `env_and_roster` = genuinely not listed; `env_only_roster_unavailable` = the roster fetch failed and the email isn't in the env list |+| A removed teammate can still sign in | Their email is still in `ALLOWED_EMAILS`. The roster is additive, so archiving the Person alone doesn't revoke access || 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 |diff --git a/packages/core/openexecutive/api/routes/auth.py b/packages/core/openexecutive/api/routes/auth.pyindex e42278ba..9f711995 100644--- a/packages/core/openexecutive/api/routes/auth.py+++ b/packages/core/openexecutive/api/routes/auth.py@@ -1,11 +1,13 @@-"""Auth-facing surface — the People roster as the source of truth for who+"""Auth-facing surface — the People roster as one of two inputs to whocan sign in via Google OAuth on the UI.The Next.js layer's ``auth.ts`` calls ``GET /auth/allowed-emails`` duringthe NextAuth ``signIn`` callback to decide whether to admit a logged-in-Google user. Previously the allowlist lived in the ``ALLOWED_EMAILS``-env var on the UI; pulling it from the people store means managing-access is the same operation as managing your team.+Google user. Serving the roster here means adding someone to your team is+also how you grant them access — but it is **additive**, not a+replacement: the UI unions this list with its own ``ALLOWED_EMAILS`` env+var, so a roster change can never revoke an email the operator configured+through the environment (issue #132).This route is still gated by the shared-secret middleware — the UI'sserver-side fetch carries ``x-api-key`` so an unauthenticated caller@@ -30,10 +32,15 @@ class AllowedEmail(BaseModel):def allowed_emails() -> list[AllowedEmail]:"""Return ``[{email, person_id}]`` for every non-archived Person with an email.- Empty list when no people are seeded yet (fresh install). In that case the- UI's ``auth.ts`` is expected to fall back to its ``ALLOWED_EMAILS`` env- var so a brand-new operator can sign in and run onboarding. Once any- Person exists with an email, this endpoint becomes authoritative.+ Empty list when no people are seeded yet (fresh install); the UI then+ relies on ``ALLOWED_EMAILS`` alone, so a brand-new operator can sign in+ and run onboarding.++ This list is **additive**. The UI admits an email that appears here *or*+ in its ``ALLOWED_EMAILS`` env var — this endpoint reports the roster and+ nothing else, and the union happens in ``auth.ts``. Removing a Person+ therefore does not revoke access on its own if their email is also in+ that env var."""return [AllowedEmail(email=p.email.lower(), person_id=p.id) # type: ignore[arg-type]diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 5933bc77..ab3eb4c6 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -2615,17 +2615,34 @@ auth:- `authorized` callback: re-runs on every middleware-gated request.A user removed from the roster mid-session (or one whose JWTpredates the roster) is bounced on their next request rather- than coasting until JWT expiry. Fail-open on backend-fetch- errors so a brief outage doesn't sign everyone out.- Both callbacks share one helper (`checkEmailAllowed`). Allowlist is- two-tier:- 1. Roster (authoritative): GET /auth/allowed-emails returns- every non-archived Person with a non-null email; sign-in /- re-validation succeeds iff the Google email matches a row.- 2. Env fallback: ALLOWED_EMAILS comma-separated env var, used- only when the roster is empty (fresh-install bootstrap).- Once any Person has an email, the env var is ignored.- Roster fetch is cached for 5 minutes per Next.js server instance.+ than coasting until JWT expiry. Fails open ONLY for a session+ that is not in ALLOWED_EMAILS and whose roster membership is+ currently unreadable; a definite miss (both lists readable,+ neither matched) still revokes.+ Both callbacks share one helper (`checkEmailAllowed`). The allowlist+ is the UNION of two additive sources — neither overrides the other:+ 1. ALLOWED_EMAILS: comma-separated env var on the UI, parsed once+ at module scope. Checked FIRST and a hit short-circuits, so the+ roster is never fetched for a configured operator: they sign in+ with the backend down, at no fetch latency. Revocable only by+ editing the env and restarting.+ 2. Roster: GET /auth/allowed-emails returns every non-archived+ Person with a non-null email. Consulted only on an env miss,+ and purely additive.+ Roster fetch is cached for 5 minutes per Next.js server instance;+ a failed fetch returns null ("unknown") and is deliberately not+ cached, and a stale success is not served past its TTL.+ The old rule made the roster authoritative as soon as it held one+ email, which was issue #132: anything that wrote a Person row —+ including a fixture load, which wipes `people` and inserts its own+ addresses — silently evicted the operator from their own instance.+ Decision helpers are pure and live in packages/ui/src/lib/allowlist.ts+ (parseAllowedEmails / decideAllowed / resolveAllowed /+ createRosterLoader / describeDenial), unit-tested by+ packages/ui/scripts/allowlist.test.mjs; auth.ts keeps only the+ wiring, the audit calls and the NextAuth config. The decision's+ `source` — env | roster | env_and_roster | env_only_roster_unavailable+ — is recorded in the audit-log `details`.backend_gate: |BACKEND_SHARED_SECRET via x-api-key header gates every API route(see api.main._shared_secret_gate). The Next.js proxy atdiff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex 64685142..19dec293 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` | 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. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\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` | Roster CRUD and scope lookups. |\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. |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\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`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\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| `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). |\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` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\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` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\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| `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` | Allowed sign-in emails. |\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). 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` | 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. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\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` | Roster CRUD and scope lookups. |\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. |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\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`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\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| `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). |\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` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\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` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\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| `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. |","mermaid": null,- "generated_at": "2026-09-17T14:16:08.593444+00:00"+ "generated_at": "2026-09-17T21:21:41.954624+00:00"}diff --git a/packages/ui/scripts/allowlist.test.mjs b/packages/ui/scripts/allowlist.test.mjsnew file mode 100644index 00000000..cddb8520--- /dev/null+++ b/packages/ui/scripts/allowlist.test.mjs@@ -0,0 +1,275 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ createRosterLoader,+ decideAllowed,+ describeDenial,+ normalizeEmail,+ parseAllowedEmails,+ resolveAllowed,+} from "../src/lib/allowlist.ts";++const set = (...emails) => new Set(emails);+const NONE = set();++// --- parseAllowedEmails ----------------------------------------------------++test("parseAllowedEmails trims, lowercases, and drops blanks", () => {+ const parsed = parseAllowedEmails(" [email protected] , [email protected] ,, ");+ assert.deepEqual([...parsed].sort(), ["[email protected]", "[email protected]"]);+});++test("parseAllowedEmails treats missing and empty config as no entries", () => {+ assert.equal(parseAllowedEmails(undefined).size, 0);+ assert.equal(parseAllowedEmails(null).size, 0);+ assert.equal(parseAllowedEmails("").size, 0);+ assert.equal(parseAllowedEmails(",, ,").size, 0);+});++test("normalizeEmail lowercases and trims, and survives null", () => {+ assert.equal(normalizeEmail(" [email protected] "), "[email protected]");+ assert.equal(normalizeEmail(null), "");+ assert.equal(normalizeEmail(undefined), "");+});++// --- decideAllowed: the union rule -----------------------------------------++test("issue #132: an ALLOWED_EMAILS entry survives a roster full of other people", () => {+ // The exact reported scenario: operator in the env list, roster populated by+ // a fixture load that knows nothing about them. Before the union fix this+ // returned { allowed: false }, locking the operator out of their own box.+ const decision = decideAllowed(+ "[email protected]",+ set("[email protected]"),+ set("[email protected]", "[email protected]"),+ );+ assert.deepEqual(decision, { allowed: true, source: "env", rosterUnknown: false });+});++test("a roster member not in ALLOWED_EMAILS is admitted", () => {+ const decision = decideAllowed("[email protected]", NONE, set("[email protected]"));+ assert.deepEqual(decision, { allowed: true, source: "roster", rosterUnknown: false });+});++test("an email in neither list is denied, with both lists readable", () => {+ const decision = decideAllowed("[email protected]", set("[email protected]"), set("[email protected]"));+ assert.deepEqual(decision, {+ allowed: false,+ source: "env_and_roster",+ rosterUnknown: false,+ });+});++test("an empty but readable roster revokes rather than failing open", () => {+ const decision = decideAllowed("[email protected]", NONE, NONE);+ assert.deepEqual(decision, {+ allowed: false,+ source: "env_and_roster",+ rosterUnknown: false,+ });+});++test("an unreadable roster does not make an env entry uncertain", () => {+ // rosterUnknown stays false: the decision never consulted the roster, so+ // this is a definite allow, not a fail-open.+ const decision = decideAllowed("[email protected]", set("[email protected]"), null);+ assert.deepEqual(decision, { allowed: true, source: "env", rosterUnknown: false });+});++test("an unreadable roster leaves a non-env email unknown, not denied outright", () => {+ const decision = decideAllowed("[email protected]", set("[email protected]"), null);+ assert.deepEqual(decision, {+ allowed: false,+ source: "env_only_roster_unavailable",+ rosterUnknown: true,+ });+});++test("an email in both lists is attributed to env", () => {+ const both = decideAllowed("[email protected]", set("[email protected]"), set("[email protected]"));+ assert.equal(both.source, "env");+ assert.equal(both.allowed, true);+});++test("matching is case-insensitive against both lists", () => {+ assert.equal(decideAllowed("[email protected]", set("[email protected]"), NONE).allowed, true);+ assert.equal(decideAllowed("[email protected]", NONE, set("[email protected]")).allowed, true);+});++test("an empty email is never admitted by an empty-string list entry", () => {+ // parseAllowedEmails drops blanks, but decideAllowed is exported, so guard+ // the case where a caller hands it a hand-built set containing "".+ const decision = decideAllowed("", set(""), set(""));+ assert.equal(decision.allowed, false);+});++// --- resolveAllowed: lazy roster fetch --------------------------------------++test("an ALLOWED_EMAILS hit never touches the roster", async () => {+ // This is what makes the env list work with the backend completely down.+ let calls = 0;+ const loadRoster = async () => {+ calls += 1;+ return NONE;+ };+ const decision = await resolveAllowed("[email protected]", set("[email protected]"), loadRoster);+ assert.deepEqual(decision, { allowed: true, source: "env", rosterUnknown: false });+ assert.equal(calls, 0);+});++test("an ALLOWED_EMAILS miss fetches the roster exactly once", async () => {+ let calls = 0;+ const loadRoster = async () => {+ calls += 1;+ return set("[email protected]");+ };+ const decision = await resolveAllowed("[email protected]", NONE, loadRoster);+ assert.equal(decision.source, "roster");+ assert.equal(decision.allowed, true);+ assert.equal(calls, 1);+});++test("resolveAllowed normalizes before matching either list", async () => {+ const decision = await resolveAllowed(" [email protected] ", set("[email protected]"), async () => NONE);+ assert.equal(decision.allowed, true);+});++// --- createRosterLoader -----------------------------------------------------++const okResponse = (rows) => ({ ok: true, status: 200, json: async () => rows });++/** Records every call so header/URL/cache assertions can inspect them. */+const recordingFetch = (responder) => {+ const calls = [];+ const impl = async (url, init) => {+ calls.push({ url, init });+ return responder(calls.length);+ };+ impl.calls = calls;+ return impl;+};++test("the loader hits /auth/allowed-emails with the shared secret and no caching", async () => {+ const fetchImpl = recordingFetch(() => okResponse([{ email: "[email protected]", person_id: 1 }]));+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "s3cret",+ ttlMs: 1000,+ fetchImpl,+ });+ assert.deepEqual([...(await load())], ["[email protected]"]);+ assert.equal(fetchImpl.calls[0].url, "http://api:8000/auth/allowed-emails");+ assert.equal(fetchImpl.calls[0].init.cache, "no-store");+ assert.equal(fetchImpl.calls[0].init.headers["x-api-key"], "s3cret");+});++test("the loader omits x-api-key when no shared secret is configured", async () => {+ const fetchImpl = recordingFetch(() => okResponse([]));+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 1000,+ fetchImpl,+ });+ await load();+ assert.equal("x-api-key" in fetchImpl.calls[0].init.headers, false);+});++test("a successful roster is cached for its TTL and refetched after it expires", async () => {+ let clock = 0;+ const fetchImpl = recordingFetch((n) => okResponse([{ email: `p${n}@corp.com`, person_id: n }]));+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 1000,+ fetchImpl,+ now: () => clock,+ });+ assert.deepEqual([...(await load())], ["[email protected]"]);+ clock = 999;+ assert.deepEqual([...(await load())], ["[email protected]"]);+ assert.equal(fetchImpl.calls.length, 1, "served from cache inside the TTL");+ clock = 1000;+ assert.deepEqual([...(await load())], ["[email protected]"]);+ assert.equal(fetchImpl.calls.length, 2, "refetched once the TTL elapsed");+});++test("an HTTP error yields null, warns, and is not cached", async () => {+ const warnings = [];+ const fetchImpl = recordingFetch((n) =>+ n === 1 ? { ok: false, status: 500, json: async () => [] } : okResponse([{ email: "[email protected]", person_id: 1 }]),+ );+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 60_000,+ fetchImpl,+ now: () => 0,+ onWarn: (m) => warnings.push(m),+ });+ assert.equal(await load(), null);+ assert.equal(warnings.length, 1);+ assert.match(warnings[0], /HTTP 500/);+ // Same instant, well inside the TTL: a failure must not poison the cache.+ assert.deepEqual([...(await load())], ["[email protected]"]);+});++test("a rejecting fetch yields null instead of throwing into NextAuth", async () => {+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 1000,+ fetchImpl: async () => {+ throw new Error("ECONNREFUSED");+ },+ });+ assert.equal(await load(), null);+});++test("a non-array body yields null rather than an empty roster", async () => {+ // An empty roster revokes; "unparseable" must not masquerade as that.+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 1000,+ fetchImpl: async () => ({ ok: true, status: 200, json: async () => ({ detail: "nope" }) }),+ });+ assert.equal(await load(), null);+});++test("a row with a null email is skipped without nulling the whole roster", async () => {+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 1000,+ fetchImpl: async () =>+ okResponse([{ email: null, person_id: 1 }, { email: "[email protected]", person_id: 2 }, {}]),+ });+ assert.deepEqual([...(await load())], ["[email protected]"]);+});++test("a body that fails to parse as JSON yields null", async () => {+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 1000,+ fetchImpl: async () => ({+ ok: true,+ status: 200,+ json: async () => {+ throw new SyntaxError("Unexpected token <");+ },+ }),+ });+ assert.equal(await load(), null);+});++// --- describeDenial ---------------------------------------------------------++test("denial clauses read as audit summaries and match docs/auth.md", () => {+ assert.equal(describeDenial("env_and_roster"), "not in ALLOWED_EMAILS or the people roster");+ assert.equal(+ describeDenial("env_only_roster_unavailable"),+ "not in ALLOWED_EMAILS; people roster unavailable",+ );+});diff --git a/packages/ui/src/auth.ts b/packages/ui/src/auth.tsindex c2fb5b52..caab94f3 100644--- a/packages/ui/src/auth.ts+++ b/packages/ui/src/auth.ts@@ -1,78 +1,45 @@import NextAuth from "next-auth";import Google from "next-auth/providers/google";+import {+ createRosterLoader,+ describeDenial,+ parseAllowedEmails,+ resolveAllowed,+} from "@/lib/allowlist";-// Env-var fallback for the bootstrap case (fresh install, roster still-// empty). Once any Person row exists with an email, the backend's-// /auth/allowed-emails endpoint becomes authoritative and this list is-// only consulted to admit the first operator.-const ALLOWED_EMAILS_FALLBACK: ReadonlySet<string> = new Set(- (process.env.ALLOWED_EMAILS ?? "")- .split(",")- .map((e) => e.trim().toLowerCase())- .filter((e) => e.length > 0),-);+// Operator-controlled allowlist, read once at startup (docs/auth.md promises a+// restart is what makes an edit live). ALWAYS honored: the backend People+// roster is ADDITIVE on top of it, never a replacement — see lib/allowlist.ts+// for why (issue #132).+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 ?? "";// 5-minute cache. Cheap insurance against hammering the backend on every-// sign-in attempt and keeps sign-in latency bounded if the backend is-// momentarily slow. NextAuth's signIn callback is server-side (Node-// runtime) so this module-level cache is per-server-instance.-const ROSTER_TTL_MS = 5 * 60 * 1000;-let rosterCache: { fetchedAt: number; emails: Set<string> } | null = null;--async function fetchRosterEmails(): Promise<Set<string> | null> {- const now = Date.now();- if (rosterCache && now - rosterCache.fetchedAt < ROSTER_TTL_MS) {- return rosterCache.emails;- }- try {- const headers: Record<string, string> = {};- if (BACKEND_SHARED_SECRET) headers["x-api-key"] = BACKEND_SHARED_SECRET;- const res = await fetch(`${BACKEND_BASE}/auth/allowed-emails`, {- headers,- // Sign-in is rare; don't let stale Next.js fetch caches gate access.- cache: "no-store",- });- if (!res.ok) {- console.warn(`[auth] roster fetch failed (HTTP ${res.status}); falling back to ALLOWED_EMAILS env`);- return null;- }- const rows = (await res.json()) as Array<{ email: string; person_id: number }>;- const emails = new Set(rows.map((r) => r.email.toLowerCase()));- rosterCache = { fetchedAt: now, emails };- return emails;- } catch (err) {- console.warn(`[auth] roster fetch error; falling back to ALLOWED_EMAILS env: ${String(err)}`);- return null;- }-}+// sign-in attempt, and it keeps sign-in latency bounded if the backend is+// momentarily slow. Both NextAuth callbacks are server-side (Node runtime), so+// the loader's cache is per-server-instance.+const loadRoster = createRosterLoader({+ baseUrl: BACKEND_BASE,+ sharedSecret: BACKEND_SHARED_SECRET,+ ttlMs: 5 * 60 * 1000,+ // Wrapped rather than passed bare: `fetch` must keep its own receiver.+ fetchImpl: (input, init) => fetch(input, init),+ onWarn: (message) => console.warn(message),+});/**- * Resolve whether an email is permitted by the current allowlist regime.- *- * Returns `{ allowed, source }`. `source` is one of:- * - `roster` — the People table is populated and authoritative; matched.- * - `env_empty_roster` — roster has no email-bearing rows yet; env fallback used.- * - `env_after_fetch_error` — backend fetch failed; env fallback used.+ * Resolve whether an email is on the allowlist — the union of ALLOWED_EMAILS+ * and the People roster. An env hit short-circuits, so the roster is never+ * fetched for a configured operator.** Called by both the NextAuth `signIn` callback (strict, denies on miss) and- * the `authorized` callback (re-runs on every gated request so a user- * removed from the roster mid-session is bounced on next request).+ * the `authorized` callback (re-runs on every gated request so a user removed+ * from the roster mid-session is bounced on next request).*/-async function checkEmailAllowed(- email: string,-): Promise<{ allowed: boolean; source: string }> {- const roster = await fetchRosterEmails();- if (roster && roster.size > 0) {- return { allowed: roster.has(email), source: "roster" };- }- return {- allowed: ALLOWED_EMAILS_FALLBACK.has(email),- source: roster === null ? "env_after_fetch_error" : "env_empty_roster",- };-}+const checkEmailAllowed = (email: string) =>+ resolveAllowed(email, ENV_ALLOWED, loadRoster);// Fire-and-forget audit call to the backend. Never awaited — auth must never// block or expose errors due to audit failures.@@ -144,13 +111,18 @@ export const { handlers, auth, signIn, signOut } = NextAuth({auditAuth("auth_login", `Login denied: ${email} (email not verified)`, email, { denied: true, reason: "email_not_verified" });return false;}- const { allowed, source } = await checkEmailAllowed(email);+ const { allowed, source, rosterUnknown } = await checkEmailAllowed(email);if (!allowed) {auditAuth("auth_login",- `Login denied: ${email} (not in ${source})`,+ `Login denied: ${email} (${describeDenial(source)})`,email,- { denied: true, reason: "not_in_allowlist", source },+ {+ denied: true,+ reason: "not_in_allowlist",+ source,+ roster_unavailable: rosterUnknown,+ },);return false;}@@ -159,26 +131,35 @@ export const { handlers, auth, signIn, signOut } = NextAuth({// 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. Fail-open on roster-fetch errors (signal:- // source === "env_after_fetch_error") so a brief backend hiccup- // doesn't lock out everyone with a valid session — the strict- // `signIn` gate already vetted them once.+ // until their JWT expires.+ //+ // Fails open ONLY for a session that is not in ALLOWED_EMAILS and whose+ // roster membership is currently unreadable (`rosterUnknown`), 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. `allowed` is checked+ // first so env and roster members never route through the fail-open+ // branch at all.authorized: async ({ auth }) => {if (!auth?.user?.email) return false;const email = auth.user.email.toLowerCase();- const { allowed, source } = await checkEmailAllowed(email);- if (source === "env_after_fetch_error") return true;- if (!allowed) {- // 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} (not in ${source})`,- email,- { revoked: true, reason: "not_in_allowlist", source },- );- }- return allowed;+ const { allowed, source, rosterUnknown } = await checkEmailAllowed(email);+ if (allowed) return true;+ if (rosterUnknown) return true;+ // 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(source)})`,+ email,+ {+ revoked: true,+ reason: "not_in_allowlist",+ source,+ roster_unavailable: false,+ },+ );+ return false;},},events: {diff --git a/packages/ui/src/lib/allowlist.ts b/packages/ui/src/lib/allowlist.tsnew file mode 100644index 00000000..83a23dc3--- /dev/null+++ b/packages/ui/src/lib/allowlist.ts@@ -0,0 +1,190 @@+// Who may sign in. Two ADDITIVE sources, never one overriding the other+// (issue #132): the operator's ALLOWED_EMAILS env list is always honored, and+// the backend People roster grants access on top of it.+//+// The previous rule made the roster authoritative the moment it held a single+// email, so anything that wrote a Person row — including a fixture load, which+// wipes `people` and inserts its own @example.com addresses — silently evicted+// the operator from their own instance, with recovery requiring direct DB+// access. Under the union that cannot happen: an env entry is revocable only+// by editing the env.+//+// No imports here (not React, not next-auth) so `npm test` can exercise this+// directly under `node --experimental-strip-types` — see+// scripts/allowlist.test.mjs. auth.ts keeps only the wiring and audit calls.++/** Where an allow/deny decision came from. Recorded in audit-log `details`. */+export type AllowSource =+ /** Matched ALLOWED_EMAILS. The roster was not consulted. */+ | "env"+ /** Missed ALLOWED_EMAILS, matched the People roster. */+ | "roster"+ /** Definite miss: both lists were readable and neither had the email. */+ | "env_and_roster"+ /** Missed ALLOWED_EMAILS; the roster was unreadable, so membership is unknown. */+ | "env_only_roster_unavailable";++export type AllowDecision = {+ allowed: boolean;+ source: AllowSource;+ /** True only when the answer is "no" AND the roster could not be read. */+ rosterUnknown: boolean;+};++export function normalizeEmail(email: string | null | undefined): string {+ return (email ?? "").trim().toLowerCase();+}++/**+ * Parse a comma-separated ALLOWED_EMAILS value. Trims, lowercases, drops+ * blanks — so whitespace around entries and trailing commas are harmless,+ * as docs/auth.md promises.+ */+export function parseAllowedEmails(+ raw: string | null | undefined,+): ReadonlySet<string> {+ return new Set(+ (raw ?? "")+ .split(",")+ .map(normalizeEmail)+ .filter((e) => e.length > 0),+ );+}++/**+ * The union rule, as a pure function. `roster === null` means the roster could+ * not be read; an empty set means it was read and is genuinely empty.+ *+ * Note that an env hit yields `rosterUnknown: false` even when the roster is+ * unreadable — the decision never depended on the roster, so there is nothing+ * unknown about it.+ */+export function decideAllowed(+ email: string,+ envAllowed: ReadonlySet<string>,+ roster: ReadonlySet<string> | null,+): AllowDecision {+ const normalized = normalizeEmail(email);+ if (normalized.length > 0 && envAllowed.has(normalized)) {+ return { allowed: true, source: "env", rosterUnknown: false };+ }+ if (roster === null) {+ return {+ allowed: false,+ source: "env_only_roster_unavailable",+ rosterUnknown: true,+ };+ }+ if (normalized.length > 0 && roster.has(normalized)) {+ return { allowed: true, source: "roster", rosterUnknown: false };+ }+ // Both lists readable and neither matched — a definite no. An empty roster+ // lands here too, so it revokes rather than failing open.+ return { allowed: false, source: "env_and_roster", rosterUnknown: false };+}++/**+ * `decideAllowed` with the roster fetched lazily: an env hit short-circuits+ * before `loadRoster` is ever called, so an operator listed in ALLOWED_EMAILS+ * signs in with the backend completely down and pays no fetch latency.+ *+ * The flip side is that env-listed users never warm the roster cache, so the+ * first roster-only request after a restart pays the fetch. That is the right+ * trade: it buys the guarantee that the env list works when nothing else does.+ */+export async function resolveAllowed(+ email: string,+ envAllowed: ReadonlySet<string>,+ loadRoster: () => Promise<ReadonlySet<string> | null>,+): Promise<AllowDecision> {+ const normalized = normalizeEmail(email);+ if (normalized.length > 0 && envAllowed.has(normalized)) {+ return { allowed: true, source: "env", rosterUnknown: false };+ }+ return decideAllowed(normalized, envAllowed, await loadRoster());+}++/** Human clause for audit summaries. Mirrored in docs/auth.md's Debugging table. */+export function describeDenial(source: AllowSource): string {+ switch (source) {+ case "env_and_roster":+ return "not in ALLOWED_EMAILS or the people roster";+ case "env_only_roster_unavailable":+ return "not in ALLOWED_EMAILS; people roster unavailable";+ default:+ // Unreachable: `env` and `roster` are allow outcomes.+ return "not allowed";+ }+}++export type RosterLoaderOptions = {+ baseUrl: string;+ sharedSecret: string;+ ttlMs: number;+ fetchImpl: typeof fetch;+ now?: () => number;+ onWarn?: (message: string) => void;+};++/**+ * Build a cached loader for GET /auth/allowed-emails. The cache lives in the+ * returned closure (one per Next.js server instance — both NextAuth callbacks+ * run in the Node runtime), which keeps sign-in from hammering the backend and+ * bounds sign-in latency when the backend is momentarily slow.+ *+ * Returns `null` on any failure, which callers read as "roster unknown". A+ * failure is deliberately NOT cached, so the next attempt retries; and a stale+ * success is deliberately NOT served past its TTL, because "serve stale on+ * refresh failure" is a different revocation contract than the one documented.+ */+export function createRosterLoader(+ opts: RosterLoaderOptions,+): () => Promise<ReadonlySet<string> | null> {+ const { baseUrl, sharedSecret, ttlMs, fetchImpl } = opts;+ const now = opts.now ?? (() => Date.now());+ const warn = opts.onWarn ?? (() => {});+ let cache: { fetchedAt: number; emails: ReadonlySet<string> } | null = null;++ return async function loadRoster(): Promise<ReadonlySet<string> | null> {+ const at = now();+ if (cache && at - cache.fetchedAt < ttlMs) return cache.emails;+ try {+ const headers: Record<string, string> = {};+ if (sharedSecret) headers["x-api-key"] = sharedSecret;+ const res = await fetchImpl(`${baseUrl}/auth/allowed-emails`, {+ headers,+ // Sign-in is rare; don't let stale Next.js fetch caches gate access.+ cache: "no-store",+ });+ if (!res.ok) {+ warn(+ `[auth] roster fetch failed (HTTP ${res.status}); ALLOWED_EMAILS still applies, ` ++ `roster-only sign-ins are denied until the backend answers`,+ );+ return null;+ }+ // Parsing stays inside the try: a malformed body degrades to "unknown"+ // rather than throwing into NextAuth's callback.+ const body = (await res.json()) as unknown;+ if (!Array.isArray(body)) {+ warn(`[auth] roster fetch returned a non-array body; treating the roster as unavailable`);+ return null;+ }+ const emails: ReadonlySet<string> = new Set(+ body+ // One row with a null email must not null out the whole roster.+ .filter((r): r is { email: string } => typeof r?.email === "string")+ .map((r) => normalizeEmail(r.email))+ .filter((e) => e.length > 0),+ );+ cache = { fetchedAt: at, emails };+ return emails;+ } catch (err) {+ warn(+ `[auth] roster fetch error; ALLOWED_EMAILS still applies, ` ++ `roster-only sign-ins are denied until the backend answers: ${String(err)}`,+ );+ return null;+ }+ };+}