From 9250c714ebdc6bab777f18042c27742e2d6d8787 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 30 Oct 2026 15:04:54 +1100 Subject: [PATCH 001/435] chore(porch): 329 PR #331 merged --- codev/projects/329-apps-auth-service-api-keys-bet/status.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml b/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml index 1b8a769d..7746e4a8 100644 --- a/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml +++ b/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml @@ -47,7 +47,7 @@ iteration: 1 build_complete: false history: [] started_at: '2026-10-28T04:31:56.766Z' -updated_at: '2026-10-30T00:41:11.575Z' +updated_at: '2026-10-30T04:04:54.462Z' context_refreshes: - boundary: plan-phase:phase_2 at: '2026-10-28T06:20:23.009Z' @@ -78,4 +78,6 @@ pr_history: pr_number: 331 branch: builder/spir-329 created_at: '2026-10-28T09:44:41.643Z' + merged: true + merged_at: '2026-10-30T04:04:54.461Z' pr_ready_for_human: false From d153b79492037e3d5eca8b1b1db9ea4da1d9d63d Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 30 Oct 2026 15:05:00 +1100 Subject: [PATCH 002/435] chore(porch): 329 verify phase-transition --- codev/projects/329-apps-auth-service-api-keys-bet/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml b/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml index 7746e4a8..dcd339f5 100644 --- a/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml +++ b/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml @@ -1,7 +1,7 @@ id: '329' title: apps-auth-service-api-keys-bet protocol: spir -phase: review +phase: verify plan_phases: - id: phase_1 title: Plugin, schema and migration 0001, blocked key surface, library probes @@ -47,7 +47,7 @@ iteration: 1 build_complete: false history: [] started_at: '2026-10-28T04:31:56.766Z' -updated_at: '2026-10-30T04:04:54.462Z' +updated_at: '2026-10-30T04:05:00.473Z' context_refreshes: - boundary: plan-phase:phase_2 at: '2026-10-28T06:20:23.009Z' From 6f7db157b42b82f1bff46176d5e31104d7b9ad1e Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 30 Oct 2026 15:05:15 +1100 Subject: [PATCH 003/435] chore(porch): 329 verify-approval gate-requested --- codev/projects/329-apps-auth-service-api-keys-bet/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml b/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml index dcd339f5..d8830f64 100644 --- a/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml +++ b/codev/projects/329-apps-auth-service-api-keys-bet/status.yaml @@ -43,11 +43,12 @@ gates: approved_at: '2026-10-30T00:41:11.575Z' verify-approval: status: pending + requested_at: '2026-10-30T04:05:15.672Z' iteration: 1 build_complete: false history: [] started_at: '2026-10-28T04:31:56.766Z' -updated_at: '2026-10-30T04:05:00.473Z' +updated_at: '2026-10-30T04:05:15.672Z' context_refreshes: - boundary: plan-phase:phase_2 at: '2026-10-28T06:20:23.009Z' From d9299f704ee5cc47eed659b9960b64ab7963460b Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Fri, 30 Oct 2026 09:10:14 +0200 Subject: [PATCH 004/435] [Spec 321] Follow-up #336: handle apps/auth statuses by meaning, re-exchange once on an apps/api 401, pin uv, watch .dockerignore, Dependabot for legacy/whatsapp Type each apps/auth refusal: 400 (our bug), 401 (our key, operator), 403 (banned user), 429 (per-user budget, with a local cool-down) and 500 (outage), none retried per message. On a 401 from apps/api, drop the cached token, exchange once more and retry once. Pin setup-uv to 0.9.13 like the Dockerfile. Add .dockerignore to the service's watch paths. Add a uv Dependabot entry for legacy/whatsapp and narrow the legacy comment. Amend spec 321. The phone number is not sent to apps/auth: spec 329 amendment 2 says apps/auth ignores it. --- .github/dependabot.yml | 10 +- .github/workflows/ci.yml | 3 + RELEASE.md | 3 +- codev/resources/arch.md | 2 +- .../321-rfc-whatsapp-support-in-the-mo.md | 13 +- legacy/whatsapp/README.md | 14 +- legacy/whatsapp/railway.toml | 2 + .../services/ansari_client_real.py | 16 +- .../services/auth_client_base.py | 5 +- .../services/auth_client_real.py | 72 +++- .../services/whatsapp_conversation_manager.py | 100 ++++- .../src/ansari_whatsapp/utils/exceptions.py | 26 +- legacy/whatsapp/tests/test_auth_statuses.py | 404 ++++++++++++++++++ 13 files changed, 629 insertions(+), 41 deletions(-) create mode 100644 legacy/whatsapp/tests/test_auth_statuses.py diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 929632a6..b495293a 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,7 +11,7 @@ updates: # Note: there is no "pnpm" package-ecosystem value; pnpm is handled by "npm". - package-ecosystem: "npm" directory: "/" - # legacy/ holds archived snapshots of the pre-monorepo frontend (issue #150). + # legacy/frontend-* hold archived snapshots of the pre-monorepo frontend (issue #150). # They sit outside the pnpm workspace and are never built or deployed, but # each keeps its own npm/yarn lockfile as a reference for the track merge — # without this, Dependabot opens update PRs against code nothing runs. @@ -21,6 +21,14 @@ updates: interval: "weekly" open-pull-requests-limit: 10 + # legacy/whatsapp is NOT archived: it is a Python service that is built and deployed (spec 321), + # with its own uv.lock. The npm entry above skips legacy/**, so it needs its own entry here. + - package-ecosystem: "uv" + directory: "/legacy/whatsapp" + schedule: + interval: "weekly" + open-pull-requests-limit: 10 + # GitHub Actions used by the workflows in .github/workflows. - package-ecosystem: "github-actions" directory: "/" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index be74e7a3..2c20b4de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -191,6 +191,9 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + # Same uv as legacy/whatsapp/Dockerfile, so CI tests what ships. Change both together. + version: "0.9.13" - name: Install run: uv sync --frozen --extra dev diff --git a/RELEASE.md b/RELEASE.md index 358de981..51735f9a 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -47,7 +47,7 @@ migration runbook were both proven in real releases on 2026-08-02. > backend: apps/api/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml > frontend: apps/frontend/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml > auth: apps/auth/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml -> whatsapp: legacy/whatsapp/** +> whatsapp: legacy/whatsapp/** .dockerignore > ``` > > For backend, frontend and auth, `packages/**` is **not optional**. The shared config packages are copied into those @@ -55,6 +55,7 @@ migration runbook were both proven in real releases on 2026-08-02. > that change ships nothing — no rebuild, no deploy, and no error. The image simply > drifts from the repo. **whatsapp is the exception:** it is a Python service outside the pnpm workspace, so its image contains nothing from > `packages/`, the root lockfile or `package.json`; watching them would only rebuild it for changes it does not ship. +> It does add `.dockerignore`: the image builds from the repo root, so that file decides what the build can see. > > **Deploy settings** — backend healthcheck `/api/health` (timeout 300s), frontend > healthcheck `/`, whatsapp healthcheck `/`, auth healthcheck `/health` (200 only when the auth database diff --git a/codev/resources/arch.md b/codev/resources/arch.md index 0fcd478c..fd0cbcbc 100644 --- a/codev/resources/arch.md +++ b/codev/resources/arch.md @@ -64,7 +64,7 @@ The repo is a pnpm workspace of `apps/*` and `packages/*`, driven by Turborepo. **The frontend app (`apps/frontend`, since #262).** The former SDK 54 prototype (outside the workspace until #262) is now the workspace member `ansari-frontend`, on Expo SDK 57 / RN 0.86 / React 19.2, with a vitest suite that CI runs in the `frontend` job (job name frozen). Its store identity is the **legacy app's** (`legacy/frontend-app/app.json`): name "Ansari", slug `ansari-chat`, `chat.ansari.app`, EAS project `e2f465a7-…`, **scheme `ansarichat`**. That scheme is coupled to `packages/auth`'s Better Auth `trustedOrigins` (`'ansarichat://'`); change both together, or native sign-in fails origin validation later with nothing failing at build time. `auth.http.test.ts` pins the pair: it reads `apps/frontend/app.json` and asserts `${expo.scheme}://` is trusted, and it rejects the old `askansari://`. `packages/auth/turbo.json` declares that manifest as a `test` input (`$TURBO_ROOT$/apps/frontend/app.json`), because a file outside the package is not hashed by default and a warm cache would replay the guard instead of running it. The app's whole env surface is `EXPO_PUBLIC_API_URL` (default api-staging), the only ARG in `Dockerfile.web`. Uniwind is installed and wired (metro `withUniwindConfig`, `src/global.css`, `gen:types`) but **unused**: the UI is StyleSheet-only, and `app/_layout.tsx` deliberately does not import `global.css` because Tailwind's preflight reset would restyle the web. `vendor/api-client-react/` keeps only `custom-fetch.ts` (the fetch runtime) and `generated/api.schemas.ts` (types); retiring both is #264. -**The WhatsApp service (`legacy/whatsapp`, spec 321).** A Python (uv, FastAPI) service outside the pnpm/turbo graph, with its own CI job (`whatsapp`) and its own Dockerfile built from the repo root (`-f legacy/whatsapp/Dockerfile .`). It identifies a user by BSUID only (`from_user_id`; it never reads or forwards the phone number), asks apps/auth for a JWT (`POST /api/whatsapp/session`, header `Authorization: Bearer `, body `{bsuid}`, per issue #329: the route does not exist yet, so sign-in is mocked in practice; the token is cached per BSUID for 14 minutes). Sign-in runs in the background task, after Meta has its 200, so a slow apps/auth cannot cause a redelivery. It refuses to start without `META_ANSARI_APP_SECRET`, or with any `MOCK_*` switch outside `DEPLOYMENT_TYPE=local`. It then calls apps/api with that JWT: `GET/POST/DELETE /api/v2/threads` and the SSE `POST /api/v2/threads/{id}/chat`. Each user has one thread (`source: whatsapp`), deleted and recreated after `WHATSAPP_CHAT_RETENTION_HOURS` (3) of silence; a race between two first messages can create two (accepted, swept by hand). It logs one JSON line per entry on stdout with only `request_id` (Railway indexes `@request_id:`), and never logs phone numbers, BSUIDs, message text or the webhook verify token. It reads `PORT` (default 8001) and its Railway settings are recorded in `legacy/whatsapp/railway.toml` (not read by Railway). Its environments share a Meta setup: each environment needs its own Meta app credentials, and the staging `!d ` prefix keeps a developer's local messages from being answered by staging. +**The WhatsApp service (`legacy/whatsapp`, spec 321).** A Python (uv, FastAPI) service outside the pnpm/turbo graph, with its own CI job (`whatsapp`) and its own Dockerfile built from the repo root (`-f legacy/whatsapp/Dockerfile .`). It identifies a user by BSUID only (`from_user_id`; it never reads or forwards the phone number), asks apps/auth for a JWT (`POST /api/whatsapp/session`, header `Authorization: Bearer `, body `{bsuid}`, per issue #329: the route does not exist yet, so sign-in is mocked in practice; the token is cached per BSUID for 14 minutes; each refusal is typed: 401 is our key (Sentry `auth_key_rejected`), 403 a banned user, 429 a spent per-user budget with a local cool-down, 500 an outage, none retried per message; one re-exchange and one retry on an apps/api 401). Sign-in runs in the background task, after Meta has its 200, so a slow apps/auth cannot cause a redelivery. It refuses to start without `META_ANSARI_APP_SECRET`, or with any `MOCK_*` switch outside `DEPLOYMENT_TYPE=local`. It then calls apps/api with that JWT: `GET/POST/DELETE /api/v2/threads` and the SSE `POST /api/v2/threads/{id}/chat`. Each user has one thread (`source: whatsapp`), deleted and recreated after `WHATSAPP_CHAT_RETENTION_HOURS` (3) of silence; a race between two first messages can create two (accepted, swept by hand). It logs one JSON line per entry on stdout with only `request_id` (Railway indexes `@request_id:`), and never logs phone numbers, BSUIDs, message text or the webhook verify token. It reads `PORT` (default 8001) and its Railway settings are recorded in `legacy/whatsapp/railway.toml` (not read by Railway). Its environments share a Meta setup: each environment needs its own Meta app credentials, and the staging `!d ` prefix keeps a developer's local messages from being answered by staging. **Health endpoint.** `/api/health` returns `service: 'ansari-backend'` — a pinned public contract (spec 3), unrelated to the `apps/api` directory name. It performs a live DB ping with a 2s cap, so a cold process can legitimately 503 on its first request. diff --git a/codev/specs/321-rfc-whatsapp-support-in-the-mo.md b/codev/specs/321-rfc-whatsapp-support-in-the-mo.md index 226f3af6..623053c1 100644 --- a/codev/specs/321-rfc-whatsapp-support-in-the-mo.md +++ b/codev/specs/321-rfc-whatsapp-support-in-the-mo.md @@ -75,7 +75,18 @@ Other constraints: - `apps/auth` provides the `/whatsapp` endpoint and handles the fact that a WhatsApp user has no email (owned by Amr). - Ansari uses a single Meta business portfolio and is not enrolled in parent BSUIDs, so the regular BSUID suffices (to be confirmed). -- The `/whatsapp` contract follows issue #329: `POST /api/whatsapp/session`, authenticated with `Authorization: Bearer ` where the key is an `apps/auth` API key (env name `AUTH_WHATSAPP_API_KEY`), request `{ "bsuid": "US.…" }`, response `{ "token": "" }` in the format `apps/auth` already issues, errors as `{ message }` (400 malformed BSUID, 401 one identical body for every key failure, 500). +- The `/whatsapp` contract follows issue #329: `POST /api/whatsapp/session`, authenticated with `Authorization: Bearer ` where the key is an `apps/auth` API key (env name `AUTH_WHATSAPP_API_KEY`), request `{ "bsuid": "US.…" }`, response `{ "token": "" }` in the format `apps/auth` already issues, errors as `{ message }`. The statuses mean different things, and the service treats them differently (follow-up #336): + + | Status | Meaning | What the service does | + |---|---|---| + | 400 | The request failed `apps/auth`'s sanity bounds on the BSUID (there is no format check). A bug here | Tell the user sign-in failed; report to Sentry as `auth_bad_request`; no retry | + | 401 | Our API key is bad (one identical body for every key refusal) | Tell the user sign-in failed; report as `auth_key_rejected` so an operator is paged and it does not look like an outage; no retry per message | + | 403 | This user is banned | Tell the user the account cannot be answered; log only, no operator alert | + | 429 + `X-Retry-After` | This user's exchange budget is spent (6 per 15 minutes); the key is fine | Tell the user to wait about that long; remember the cool-down and do not ask `apps/auth` for that user again until it ends; log only | + | 500 | An outage, or a permanent fault for this one user | Tell the user sign-in failed; report as `auth_token_failure`; **no retry per message**; alert on a sustained rate, not on isolated 500s | + +- A session can end after its token was signed (a ban or a deletion), so `apps/api` can answer 401 to a token that is still cached. On a 401 from any `apps/api` call the service drops that BSUID's cached token, exchanges once more, and retries the message once. A second 401, or a refused exchange (for example the user is now banned), ends the attempt with a notice and a Sentry event (`api_unauthorized_after_reexchange` for the second 401). +- **No phone number is sent to `apps/auth` (decided against #336 item 1).** #336 asked for `phone_number` in the exchange body, but spec 329 amendment 2 (2026-10-30) reversed that: `apps/auth` accepts the field and ignores it, never stores or logs it, and asks this service to stop sending it. So baked decision 2 stands: this service sends the BSUID only, and no phone number leaves it. A BSUID change (a user changing number) is a new user; Meta's `previous_user_id` system message, not the phone number, would be the link if that continuity is ever wanted. - The key is a revocable, permission-scoped client credential, not a shared secret: a leaked key can mint tokens only for WhatsApp users, within a per-key budget. Each WhatsApp user reuses one session, so this service caches the token per BSUID for a little under the token's 15-minute life. `apps/auth` applies per-key limits instead of per-IP ones. - The `preferences` table (one row per setting keyed by GUID) is the home for user settings; today that is only preferred language, and expiry stays global. - Meta's own throughput limits and webhook retry behaviour sufficiently bound traffic (see Baked Decision 7); this has not been load tested. diff --git a/legacy/whatsapp/README.md b/legacy/whatsapp/README.md index a112a6e9..4bf911e0 100644 --- a/legacy/whatsapp/README.md +++ b/legacy/whatsapp/README.md @@ -10,7 +10,17 @@ The WhatsApp front door for Ansari. It receives webhooks from Meta, signs the us 4. The service finds the user's newest thread in `apps/api` (`GET /api/v2/threads`). If it is older than `WHATSAPP_CHAT_RETENTION_HOURS` it is deleted and a new one is created (`source: "whatsapp"`). 5. The message goes to `POST /api/v2/threads/{id}/chat`. The server-sent-event stream is collected and the answer is sent back to the user's BSUID, split to fit WhatsApp's 4,000-character limit. -If sign-in fails, the user gets a short apology and the failure goes to Sentry. Meta still gets its 200, because sign-in runs after the reply. +If sign-in fails, the user is told, and Meta still gets its 200, because sign-in runs after the reply. What the user is told and what reaches Sentry depend on why it failed: + +| pps/auth answered | Meaning | User is told | Sentry error_type | +|---|---|---|---| +| 400 | Our request was malformed (a bug here) | Sign-in failed | uth_bad_request | +| 401 | Our API key is bad: needs an operator | Sign-in failed | uth_key_rejected | +| 403 | The user is banned | The account cannot be answered | none (log only) | +| 429 | The user's budget is spent (6 per 15 minutes) | To wait about X-Retry-After | none (log only); the user is not asked again until it ends | +| 500 or no answer | An outage, or a fault for this one user | Sign-in failed | uth_token_failure | + +None of these is retried per message. If pps/api itself answers 401 to a cached token (the session ended after the token was signed, for example a ban), the service drops that token, exchanges once more and retries the message once; a second 401 gives up with pi_unauthorized_after_reexchange. ## Layout @@ -106,7 +116,7 @@ Only the facts below come from this repo. The dashboard settings themselves are - Build with the repository root as the root directory and `legacy/whatsapp/Dockerfile` as the Dockerfile path. Locally, from the repo root: `docker build -f legacy/whatsapp/Dockerfile -t ansari-whatsapp .` - `legacy/whatsapp/railway.toml` records these settings in git; Railway does not read it (same as `apps/api/railway.toml`). -- Set a watch path so only changes under `legacy/whatsapp/**` rebuild this service (see the "Railway service configuration" block in `RELEASE.md`). +- Set a watch path so only changes under `legacy/whatsapp/**` and `.dockerignore` (the build context is the repo root, so that file decides what the build sees) rebuild this service (see the "Railway service configuration" block in `RELEASE.md`). - Health check path: `/`. - The app binds `PORT` when Railway provides it. If the public domain is given a fixed target port, it must match. - Each environment needs its own Meta credentials and its own webhook callback URL (`https:///whatsapp/v2`). diff --git a/legacy/whatsapp/railway.toml b/legacy/whatsapp/railway.toml index 8bc1f8a6..980b121a 100644 --- a/legacy/whatsapp/railway.toml +++ b/legacy/whatsapp/railway.toml @@ -14,6 +14,8 @@ builder = "dockerfile" dockerfilePath = "legacy/whatsapp/Dockerfile" watchPatterns = [ "legacy/whatsapp/**", + # The image builds from the repo root, so this file decides what the build can see. + ".dockerignore", ] [deploy] diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/ansari_client_real.py b/legacy/whatsapp/src/ansari_whatsapp/services/ansari_client_real.py index 2c7962bb..0165a61b 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/ansari_client_real.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/ansari_client_real.py @@ -9,6 +9,7 @@ from ansari_whatsapp.utils.config import get_settings from ansari_whatsapp.utils.exceptions import ( + ApiUnauthorizedError, ThreadCreationError, ThreadDeletionError, ThreadInfoError, @@ -57,6 +58,13 @@ def __init__(self): def _auth(token: str) -> dict: return {"Authorization": f"Bearer {token}"} + @staticmethod + def _refuse_if_unauthorized(status_code: int) -> None: + # apps/api refused the token itself, which a fresh token can fix; any other status is a different fault + if status_code == 401: + logger.warning("apps/api refused the user's token (HTTP 401)") + raise ApiUnauthorizedError("apps/api refused the user's token") + async def close(self): """Close the HTTP client connection and release resources. @@ -89,6 +97,7 @@ async def create_thread(self, token: str, title: str) -> dict: json={"name": title, "source": "whatsapp"}, headers=self._auth(token), ) + self._refuse_if_unauthorized(response.status_code) response.raise_for_status() return {"thread_id": response.json()["thread_id"]} except httpx.HTTPStatusError as e: @@ -118,6 +127,7 @@ async def delete_thread(self, token: str, thread_id: str) -> None: response = await self.client.delete(f"{self.base_url}/api/v2/threads/{thread_id}", headers=self._auth(token)) if response.status_code == 404: return + self._refuse_if_unauthorized(response.status_code) response.raise_for_status() except httpx.HTTPStatusError as e: logger.error(f"HTTP error deleting thread: {e.response.status_code}") @@ -145,6 +155,7 @@ async def get_last_thread_info(self, token: str) -> dict: """ try: response = await self.client.get(f"{self.base_url}/api/v2/threads", headers=self._auth(token)) + self._refuse_if_unauthorized(response.status_code) response.raise_for_status() threads = [t for t in response.json() if t.get("source") == "whatsapp"] if not threads: @@ -186,6 +197,7 @@ async def process_message(self, token: str, thread_id: str, message: str) -> str # Use stream=True to receive the response as a stream async with self.client.stream("POST", url, json=data, headers=self._auth(token)) as response: + self._refuse_if_unauthorized(response.status_code) if response.status_code != 200: logger.error(f"Error from backend API: HTTP {response.status_code}") raise MessageProcessingError(f"Backend returned HTTP {response.status_code}") @@ -226,8 +238,8 @@ async def process_message(self, token: str, thread_id: str, message: str) -> str except httpx.RequestError as e: logger.error(f"Network error processing message: {type(e).__name__}") raise MessageProcessingError("Network error during message processing") from e - except MessageProcessingError: - # Re-raise our custom exception without wrapping + except (MessageProcessingError, ApiUnauthorizedError): + # Re-raise our custom exceptions without wrapping raise except Exception as e: logger.error(f"Unexpected error processing message: {type(e).__name__}") diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_base.py b/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_base.py index e755bfea..5ca46722 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_base.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_base.py @@ -18,6 +18,9 @@ async def get_token(self, bsuid: str) -> str: str: The JWT, sent as the bearer token on every apps/api call. Raises: - AuthTokenError: If the exchange fails. + AuthTokenError: If the exchange fails (a subclass says why). """ pass + + def forget(self, bsuid: str) -> None: + """Drop any token kept for this BSUID, so the next get_token asks apps/auth for a fresh one.""" diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_real.py b/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_real.py index 211110aa..16d9d579 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_real.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_real.py @@ -8,16 +8,27 @@ from ansari_whatsapp.services.auth_client_base import AuthClientBase from ansari_whatsapp.utils.config import get_settings -from ansari_whatsapp.utils.exceptions import AuthTokenError +from ansari_whatsapp.utils.exceptions import ( + AuthBadRequestError, + AuthKeyRejectedError, + AuthRateLimitedError, + AuthTokenError, + AuthUserBannedError, +) # Contract (issue #329): POST /api/whatsapp/session with `Authorization: Bearer `, {"bsuid": ...} -> {"token": ...}. -# Errors are {"message"} bodies: 400 malformed BSUID, 401 any key failure, 500 otherwise. +# Errors are {"message"} bodies: 400 the request failed apps/auth's sanity bounds on the BSUID (a bug here), 401 one +# identical body for every key refusal, 403 this user is banned, 429 this user's budget is spent (X-Retry-After), +# 500 an outage or a permanent fault for this one user. SESSION_PATH = "/api/whatsapp/session" # The token lives 15 minutes; reuse it for a bit less so a cached one never expires mid-request TOKEN_CACHE_SECONDS = 14 * 60 TOKEN_CACHE_MAX_ENTRIES = 10_000 +# Used when a 429 carries no usable X-Retry-After; apps/auth's per-user window is 15 minutes +DEFAULT_RETRY_AFTER_SECONDS = 60 + class AuthClientReal(AuthClientBase): """Calls apps/auth over HTTP, authenticated with AUTH_WHATSAPP_API_KEY.""" @@ -30,18 +41,31 @@ def __init__(self): timeout=5.0, ) self._cache: dict[str, tuple[str, float]] = {} # bsuid -> (token, expiry on the monotonic clock) + self._cooldown: dict[str, float] = {} # bsuid -> when its 429 ends, on the monotonic clock async def close(self) -> None: await self.client.aclose() async def get_token(self, bsuid: str) -> str: + now = time.monotonic() cached = self._cache.get(bsuid) - if cached and cached[1] > time.monotonic(): + if cached and cached[1] > now: return cached[0] + + # A user whose budget is spent is not asked again until it frees up: every ask would only be refused + until = self._cooldown.get(bsuid) + if until and until > now: + raise AuthRateLimitedError("Token exchange refused: user is cooling down", retry_after=int(until - now) + 1) + self._cooldown.pop(bsuid, None) + token = await self._exchange(bsuid) self._remember(bsuid, token) return token + def forget(self, bsuid: str) -> None: + """Drop this user's cached token, e.g. after apps/api refused it.""" + self._cache.pop(bsuid, None) + def _remember(self, bsuid: str, token: str) -> None: now = time.monotonic() if len(self._cache) >= TOKEN_CACHE_MAX_ENTRIES: @@ -49,17 +73,49 @@ def _remember(self, bsuid: str, token: str) -> None: if len(self._cache) < TOKEN_CACHE_MAX_ENTRIES: self._cache[bsuid] = (token, now + TOKEN_CACHE_SECONDS) + def _start_cooldown(self, bsuid: str, retry_after: int) -> None: + now = time.monotonic() + if len(self._cooldown) >= TOKEN_CACHE_MAX_ENTRIES: + self._cooldown = {k: v for k, v in self._cooldown.items() if v > now} + if len(self._cooldown) < TOKEN_CACHE_MAX_ENTRIES: + self._cooldown[bsuid] = now + retry_after + + @staticmethod + def _retry_after(response: httpx.Response) -> int: + try: + value = int(response.headers.get("X-Retry-After", "")) + except ValueError: + return DEFAULT_RETRY_AFTER_SECONDS + return value if value > 0 else DEFAULT_RETRY_AFTER_SECONDS + async def _exchange(self, bsuid: str) -> str: try: response = await self.client.post(self.url, json={"bsuid": bsuid}) - response.raise_for_status() - token = response.json().get("token") - except httpx.HTTPStatusError as e: - logger.error(f"apps/auth rejected the token exchange: HTTP {e.response.status_code}") - raise AuthTokenError(f"Token exchange failed: HTTP {e.response.status_code}") from e except httpx.RequestError as e: logger.error(f"Network error during token exchange: {type(e).__name__}") raise AuthTokenError("Network error during token exchange") from e + + status = response.status_code + if status == 400: + logger.error("apps/auth refused the request as malformed (HTTP 400): a bug in this service") + raise AuthBadRequestError("Token exchange failed: HTTP 400") + if status == 401: + logger.error("apps/auth rejected this service's API key (HTTP 401): the key needs an operator") + raise AuthKeyRejectedError("Token exchange failed: HTTP 401") + if status == 403: + logger.warning("apps/auth says this user is banned (HTTP 403)") + raise AuthUserBannedError("Token exchange refused: user is banned") + if status == 429: + retry_after = self._retry_after(response) + self._start_cooldown(bsuid, retry_after) + logger.warning(f"apps/auth says this user's exchange budget is spent (HTTP 429), retry in {retry_after}s") + raise AuthRateLimitedError("Token exchange refused: user budget spent", retry_after=retry_after) + if status != 200: + logger.error(f"apps/auth failed the token exchange: HTTP {status}") + raise AuthTokenError(f"Token exchange failed: HTTP {status}") + + try: + token = response.json().get("token") except ValueError as e: logger.error("apps/auth returned a non-JSON token response") raise AuthTokenError("Invalid token response") from e diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py b/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py index 4c41409e..da0f3339 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py @@ -2,6 +2,7 @@ """Service for orchestrating WhatsApp conversations and message handling.""" import asyncio +import math import time from datetime import datetime @@ -12,7 +13,12 @@ from ansari_whatsapp.services.meta_service_provider import get_meta_api_service from ansari_whatsapp.utils.app_logger import request_id_var from ansari_whatsapp.utils.exceptions import ( + ApiUnauthorizedError, + AuthBadRequestError, + AuthKeyRejectedError, + AuthRateLimitedError, AuthTokenError, + AuthUserBannedError, ThreadCreationError, ThreadDeletionError, ThreadInfoError, @@ -22,6 +28,15 @@ from ansari_whatsapp.presenters.whatsapp_message_formatter import format_for_whatsapp from ansari_whatsapp.utils.whatsapp_message_splitter import split_message +SIGN_IN_FAILED_NOTICE = "Sorry, we couldn't sign you in. Please try again later." +BANNED_NOTICE = "Sorry, we can't answer messages from this account." + + +def _rate_limited_notice(retry_after_seconds: int) -> str: + minutes = max(1, math.ceil(retry_after_seconds / 60)) + unit = "minute" if minutes == 1 else "minutes" + return f"You are sending messages too quickly. Please try again in about {minutes} {unit}." + class WhatsAppConversationManager: """Orchestrates WhatsApp conversation workflows. @@ -53,6 +68,7 @@ def __init__( """ self.bsuid = bsuid self.token = None # The user's JWT, set by authenticate_user() + self.auth_failure_notice = SIGN_IN_FAILED_NOTICE # What to tell the user if authenticate_user() fails self.incoming_msg_type = incoming_msg_type self.incoming_msg_body = incoming_msg_body self.message_id = message_id @@ -106,6 +122,10 @@ async def _typing_indicator_loop(self) -> None: logger.error(f"Error in typing indicator loop: {e}") logger.exception(e) + def _stop_typing_indicator(self) -> None: + if self.typing_indicator_task and not self.typing_indicator_task.done(): + self.typing_indicator_task.cancel() + @staticmethod def _capture(error: Exception, error_type: str) -> None: """Report an error to Sentry, tagged with its kind and this request's id (never any user content).""" @@ -121,14 +141,31 @@ async def authenticate_user(self) -> bool: for the later apps/api calls. Returns: - bool: True if a token was obtained, False if the exchange failed. + bool: True if a token was obtained. If False, `auth_failure_notice` says what to tell the user. + + Each refusal means something different, so each is reported differently: our own key being refused or our + request being malformed are bugs for an operator (Sentry, with their own tags); a banned or rate-limited user + is expected and only logged; anything else is an outage. """ + self.auth_failure_notice = SIGN_IN_FAILED_NOTICE if not self.bsuid: logger.error("Cannot authenticate user: bsuid is not set") return False try: self.token = await self.auth_client.get_token(self.bsuid) + except AuthUserBannedError: + self.auth_failure_notice = BANNED_NOTICE + return False + except AuthRateLimitedError as e: + self.auth_failure_notice = _rate_limited_notice(e.retry_after) + return False + except AuthKeyRejectedError as e: + self._capture(e, "auth_key_rejected") + return False + except AuthBadRequestError as e: + self._capture(e, "auth_bad_request") + return False except AuthTokenError as e: logger.error(f"Failed to get a token for the user: {e}") self._capture(e, "auth_token_failure") @@ -261,7 +298,7 @@ async def _resolve_thread(self, first_message: str) -> str | None: async def sign_in_and_handle_text_message(self) -> None: """Background entry point for a text message: sign in, show typing, then answer.""" if not await self.authenticate_user(): - await self.send_whatsapp_message("Sorry, we couldn't sign you in. Please try again later.") + await self.send_whatsapp_message(self.auth_failure_notice) return # Only handle_text_message cancels the typing loop, so it starts only for a signed-in user @@ -278,27 +315,44 @@ async def handle_text_message(self) -> None: incoming_txt_msg = self.incoming_msg_body["body"] logger.debug(f"Whatsapp user sent a text message ({len(incoming_txt_msg)} characters)") - thread_id = await self._resolve_thread(incoming_txt_msg) - if thread_id is None: - if self.typing_indicator_task and not self.typing_indicator_task.done(): - self.typing_indicator_task.cancel() - return - - # Process the message using the Ansari backend API - try: - response = await self.ansari_client.process_message( - token=self.token, - thread_id=thread_id, - message=incoming_txt_msg, - ) - except MessageProcessingError as e: - logger.error(f"Failed to process message: {e}") - self._capture(e, "message_processing_failure") - await self.send_whatsapp_message("An error occurred while processing your message. Please try again later.") - # Cancel typing indicator if running - if self.typing_indicator_task and not self.typing_indicator_task.done(): - self.typing_indicator_task.cancel() - return + # Two attempts at most: if apps/api refuses the token (a session can end after its token was signed, + # e.g. a ban or a deletion), the cached token is dropped, apps/auth is asked once more, and the + # message is tried once more. A 401 on the second attempt, or a refused exchange, ends it. + for attempt in (1, 2): + try: + thread_id = await self._resolve_thread(incoming_txt_msg) + if thread_id is None: + self._stop_typing_indicator() + return + + response = await self.ansari_client.process_message( + token=self.token, + thread_id=thread_id, + message=incoming_txt_msg, + ) + break + except ApiUnauthorizedError as e: + if attempt == 1: + self.auth_client.forget(self.bsuid) + if await self.authenticate_user(): + continue + await self.send_whatsapp_message(self.auth_failure_notice) + else: + logger.error("apps/api refused a freshly exchanged token; giving up") + self._capture(e, "api_unauthorized_after_reexchange") + await self.send_whatsapp_message( + "An error occurred while processing your message. Please try again later." + ) + self._stop_typing_indicator() + return + except MessageProcessingError as e: + logger.error(f"Failed to process message: {e}") + self._capture(e, "message_processing_failure") + await self.send_whatsapp_message( + "An error occurred while processing your message. Please try again later." + ) + self._stop_typing_indicator() + return # Cancel the typing indicator task if it's still running if self.typing_indicator_task and not self.typing_indicator_task.done(): diff --git a/legacy/whatsapp/src/ansari_whatsapp/utils/exceptions.py b/legacy/whatsapp/src/ansari_whatsapp/utils/exceptions.py index 785b6ffd..fa675d89 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/utils/exceptions.py +++ b/legacy/whatsapp/src/ansari_whatsapp/utils/exceptions.py @@ -12,17 +12,41 @@ def __init__(self, message: str, reply_to: str | None = None): class AuthTokenError(Exception): - """Exchanging a BSUID for a JWT with apps/auth failed.""" + """Exchanging a BSUID for a JWT with apps/auth failed (an outage, a 500, or a network fault).""" pass +class AuthBadRequestError(AuthTokenError): + """apps/auth answered 400: our request was malformed, which is a bug here. Never retried.""" + + +class AuthKeyRejectedError(AuthTokenError): + """apps/auth answered 401: our API key is bad (missing, revoked, expired, out of budget). Needs an operator.""" + + +class AuthUserBannedError(AuthTokenError): + """apps/auth answered 403: this user is banned.""" + + +class AuthRateLimitedError(AuthTokenError): + """apps/auth answered 429: this user's exchange budget is spent. The key is fine.""" + + def __init__(self, message: str, retry_after: int): + super().__init__(message) + self.retry_after = retry_after # Seconds until the user's budget frees up + + class AnsariClientError(Exception): """Base exception for Ansari client errors.""" pass +class ApiUnauthorizedError(AnsariClientError): + """apps/api answered 401: it refused this user's token (a session can end after the token was signed).""" + + class ThreadCreationError(AnsariClientError): """Thread creation failed.""" diff --git a/legacy/whatsapp/tests/test_auth_statuses.py b/legacy/whatsapp/tests/test_auth_statuses.py new file mode 100644 index 00000000..5d609b79 --- /dev/null +++ b/legacy/whatsapp/tests/test_auth_statuses.py @@ -0,0 +1,404 @@ +"""Tests for issue #336: each apps/auth refusal means something different, and apps/api's 401 is retried once.""" + +import asyncio +import json +import time + +import httpx +import pytest +from fastapi.testclient import TestClient + +from ansari_whatsapp.app.main import app +from ansari_whatsapp.services.ansari_client_mock import AnsariClientMock +from ansari_whatsapp.services.auth_client_mock import AuthClientMock +from ansari_whatsapp.services.auth_client_real import DEFAULT_RETRY_AFTER_SECONDS, AuthClientReal +from ansari_whatsapp.services.meta_api_service_mock import MetaApiServiceMock +from ansari_whatsapp.services.service_provider import reset_ansari_client, reset_auth_client +from ansari_whatsapp.services.whatsapp_conversation_manager import ( + BANNED_NOTICE, + SIGN_IN_FAILED_NOTICE, + WhatsAppConversationManager, +) +from ansari_whatsapp.utils.exceptions import ( + ApiUnauthorizedError, + AuthBadRequestError, + AuthKeyRejectedError, + AuthRateLimitedError, + AuthTokenError, + AuthUserBannedError, +) + +BSUID = "US.13491208655302741918" + +_RealAsyncClient = httpx.AsyncClient +client = TestClient(app) + + +@pytest.fixture(autouse=True) +def fresh_singletons(monkeypatch): + reset_ansari_client() + reset_auth_client() + monkeypatch.setattr("ansari_whatsapp.services.ansari_client_mock.random.uniform", lambda a, b: 0) + yield + reset_ansari_client() + reset_auth_client() + + +def _auth_client_answering(monkeypatch, handler) -> AuthClientReal: + monkeypatch.setattr( + "ansari_whatsapp.services.auth_client_real.httpx.AsyncClient", + lambda **kw: _RealAsyncClient(transport=httpx.MockTransport(handler), **kw), + ) + return AuthClientReal() + + +# ---------- the exchange's statuses, by meaning ---------- + + +@pytest.mark.parametrize( + ("status", "expected"), + [(400, AuthBadRequestError), (401, AuthKeyRejectedError), (403, AuthUserBannedError), (500, AuthTokenError)], +) +def test_each_status_raises_its_own_error(monkeypatch, status, expected): + auth = _auth_client_answering(monkeypatch, lambda r: httpx.Response(status, json={"message": "x"})) + + with pytest.raises(expected) as raised: + asyncio.run(auth.get_token(BSUID)) + + assert type(raised.value) is expected + + +def test_a_500_is_not_mistaken_for_a_more_specific_refusal(monkeypatch): + auth = _auth_client_answering(monkeypatch, lambda r: httpx.Response(500, json={"message": "Internal error"})) + + with pytest.raises(AuthTokenError) as raised: + asyncio.run(auth.get_token(BSUID)) + + assert not isinstance(raised.value, (AuthBadRequestError, AuthKeyRejectedError, AuthUserBannedError, AuthRateLimitedError)) + + +def test_a_429_carries_how_long_to_wait(monkeypatch): + auth = _auth_client_answering( + monkeypatch, lambda r: httpx.Response(429, json={"message": "Too many requests"}, headers={"X-Retry-After": "420"}) + ) + + with pytest.raises(AuthRateLimitedError) as raised: + asyncio.run(auth.get_token(BSUID)) + + assert raised.value.retry_after == 420 + + +@pytest.mark.parametrize("header", [None, "soon", "0", "-5"]) +def test_a_429_without_a_usable_wait_falls_back_to_a_default(monkeypatch, header): + headers = {} if header is None else {"X-Retry-After": header} + auth = _auth_client_answering(monkeypatch, lambda r: httpx.Response(429, json={}, headers=headers)) + + with pytest.raises(AuthRateLimitedError) as raised: + asyncio.run(auth.get_token(BSUID)) + + assert raised.value.retry_after == DEFAULT_RETRY_AFTER_SECONDS + + +def test_a_user_with_a_spent_budget_is_not_asked_again_until_it_frees_up(monkeypatch): + calls = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request) + if len(calls) == 1: + return httpx.Response(429, json={}, headers={"X-Retry-After": "120"}) + return httpx.Response(200, json={"token": "jwt-after-cooldown"}) + + auth = _auth_client_answering(monkeypatch, handler) + now = [1000.0] + monkeypatch.setattr("ansari_whatsapp.services.auth_client_real.time.monotonic", lambda: now[0]) + + with pytest.raises(AuthRateLimitedError): + asyncio.run(auth.get_token(BSUID)) + now[0] += 30 + with pytest.raises(AuthRateLimitedError) as still: + asyncio.run(auth.get_token(BSUID)) + assert len(calls) == 1, "a cooling-down user must not reach apps/auth again" + assert 0 < still.value.retry_after <= 91 + + now[0] += 91 + assert asyncio.run(auth.get_token(BSUID)) == "jwt-after-cooldown" + assert len(calls) == 2 + + +def test_one_users_cooldown_does_not_affect_another(monkeypatch): + def handler(request: httpx.Request) -> httpx.Response: + if json.loads(request.content)["bsuid"] == BSUID: + return httpx.Response(429, json={}, headers={"X-Retry-After": "600"}) + return httpx.Response(200, json={"token": "jwt-other"}) + + auth = _auth_client_answering(monkeypatch, handler) + + with pytest.raises(AuthRateLimitedError): + asyncio.run(auth.get_token(BSUID)) + + assert asyncio.run(auth.get_token("US.99999999999999999999")) == "jwt-other" + + +def test_a_banned_user_is_not_cached_or_cooled_down(monkeypatch): + answers = [httpx.Response(403, json={}), httpx.Response(200, json={"token": "jwt-unbanned"})] + auth = _auth_client_answering(monkeypatch, lambda r: answers.pop(0)) + + with pytest.raises(AuthUserBannedError): + asyncio.run(auth.get_token(BSUID)) + + assert asyncio.run(auth.get_token(BSUID)) == "jwt-unbanned" + + +def test_forget_drops_only_that_users_cached_token(monkeypatch): + calls = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(json.loads(request.content)["bsuid"]) + return httpx.Response(200, json={"token": f"jwt-{len(calls)}"}) + + auth = _auth_client_answering(monkeypatch, handler) + asyncio.run(auth.get_token(BSUID)) + asyncio.run(auth.get_token("US.99999999999999999999")) + + auth.forget(BSUID) + + assert asyncio.run(auth.get_token(BSUID)) == "jwt-3" + assert asyncio.run(auth.get_token("US.99999999999999999999")) == "jwt-2" + assert calls == [BSUID, "US.99999999999999999999", BSUID] + + +# ---------- what the user and the operator are told ---------- + + +def _manager() -> WhatsAppConversationManager: + return WhatsAppConversationManager( + bsuid=BSUID, + incoming_msg_type="text", + incoming_msg_body={"body": "hello"}, + message_id="wamid.TEST", + message_unix_time=int(time.time()), + ) + + +def _capturing(monkeypatch) -> list: + """Record every Sentry error_type tag set by the manager.""" + seen = [] + monkeypatch.setattr( + WhatsAppConversationManager, "_capture", staticmethod(lambda error, error_type: seen.append(error_type)) + ) + return seen + + +def _failing_exchange(monkeypatch, error: Exception) -> None: + async def failing(self, bsuid): + raise error + + monkeypatch.setattr(AuthClientMock, "get_token", failing) + + +@pytest.mark.parametrize( + ("error", "reported_as"), + [ + (AuthKeyRejectedError("401"), "auth_key_rejected"), + (AuthBadRequestError("400"), "auth_bad_request"), + (AuthTokenError("500"), "auth_token_failure"), + ], +) +def test_our_key_being_refused_does_not_look_like_an_outage(monkeypatch, error, reported_as): + seen = _capturing(monkeypatch) + _failing_exchange(monkeypatch, error) + + assert asyncio.run(_manager().authenticate_user()) is False + + assert seen == [reported_as] + + +@pytest.mark.parametrize("error", [AuthUserBannedError("403"), AuthRateLimitedError("429", retry_after=300)]) +def test_a_banned_or_rate_limited_user_is_not_an_operator_alert(monkeypatch, error): + seen = _capturing(monkeypatch) + _failing_exchange(monkeypatch, error) + + assert asyncio.run(_manager().authenticate_user()) is False + + assert seen == [] + + +def test_the_user_is_told_the_right_thing_for_each_refusal(monkeypatch): + _capturing(monkeypatch) + notices = {} + for name, error in { + "banned": AuthUserBannedError("403"), + "limited": AuthRateLimitedError("429", retry_after=300), + "key": AuthKeyRejectedError("401"), + "outage": AuthTokenError("500"), + }.items(): + _failing_exchange(monkeypatch, error) + manager = _manager() + asyncio.run(manager.authenticate_user()) + notices[name] = manager.auth_failure_notice + + assert notices["banned"] == BANNED_NOTICE + assert "5 minutes" in notices["limited"] + assert notices["key"] == SIGN_IN_FAILED_NOTICE + assert notices["outage"] == SIGN_IN_FAILED_NOTICE + assert len(set(notices.values())) == 3 + + +def test_a_stale_notice_is_not_reused_for_a_later_failure(monkeypatch): + _capturing(monkeypatch) + manager = _manager() + _failing_exchange(monkeypatch, AuthUserBannedError("403")) + asyncio.run(manager.authenticate_user()) + assert manager.auth_failure_notice == BANNED_NOTICE + + _failing_exchange(monkeypatch, AuthTokenError("500")) + asyncio.run(manager.authenticate_user()) + + assert manager.auth_failure_notice == SIGN_IN_FAILED_NOTICE + + +# ---------- one re-exchange on an apps/api 401 ---------- + + +def _spy_on_replies(monkeypatch) -> list: + replies = [] + original = MetaApiServiceMock.send_message + + async def spy(self, recipient_phone, message_parts): + replies.extend(message_parts) + return await original(self, recipient_phone, message_parts) + + monkeypatch.setattr(MetaApiServiceMock, "send_message", spy) + return replies + + +def _api_refusing_first_tokens(monkeypatch, refused: int) -> dict: + """apps/api refuses the first `refused` chat calls with a 401, then answers.""" + state = {"chat_calls": 0, "tokens_seen": []} + original = AnsariClientMock.process_message + + async def process_message(self, token, thread_id, message): + state["chat_calls"] += 1 + state["tokens_seen"].append(token) + if state["chat_calls"] <= refused: + raise ApiUnauthorizedError("apps/api refused the user's token") + return await original(self, token, thread_id, message) + + monkeypatch.setattr(AnsariClientMock, "process_message", process_message) + return state + + +def _counting_exchanges(monkeypatch) -> list: + tokens = [] + + async def get_token(self, bsuid): + tokens.append(bsuid) + return f"token-{len(tokens)}" + + monkeypatch.setattr(AuthClientMock, "get_token", get_token) + return tokens + + +def test_an_api_401_triggers_one_fresh_exchange_and_the_message_is_answered(monkeypatch): + _capturing(monkeypatch) + replies = _spy_on_replies(monkeypatch) + exchanges = _counting_exchanges(monkeypatch) + api = _api_refusing_first_tokens(monkeypatch, refused=1) + + asyncio.run(_manager().sign_in_and_handle_text_message()) + + assert len(exchanges) == 2, "one exchange to start, one after the 401" + assert api["tokens_seen"] == ["token-1", "token-2"], "the retry must use the fresh token" + assert api["chat_calls"] == 2 + assert replies and not any("error" in part.lower() or "sign you in" in part for part in replies) + + +def test_a_second_api_401_gives_up_instead_of_looping(monkeypatch): + seen = _capturing(monkeypatch) + replies = _spy_on_replies(monkeypatch) + exchanges = _counting_exchanges(monkeypatch) + api = _api_refusing_first_tokens(monkeypatch, refused=99) + + asyncio.run(_manager().sign_in_and_handle_text_message()) + + assert len(exchanges) == 2, "never a third exchange" + assert api["chat_calls"] == 2, "never a third attempt" + assert seen == ["api_unauthorized_after_reexchange"] + assert len(replies) == 1 and "error occurred" in replies[0] + + +def test_a_banned_user_found_on_the_api_401_is_told_so_and_not_retried(monkeypatch): + _capturing(monkeypatch) + replies = _spy_on_replies(monkeypatch) + api = _api_refusing_first_tokens(monkeypatch, refused=99) + state = {"exchanges": 0} + + async def get_token(self, bsuid): + state["exchanges"] += 1 + if state["exchanges"] == 1: + return "token-1" + raise AuthUserBannedError("403") + + monkeypatch.setattr(AuthClientMock, "get_token", get_token) + + asyncio.run(_manager().sign_in_and_handle_text_message()) + + assert api["chat_calls"] == 1, "no retry once the exchange says the user is banned" + assert replies == [BANNED_NOTICE] + + +def test_the_stale_token_is_dropped_before_the_second_exchange(monkeypatch): + _capturing(monkeypatch) + _spy_on_replies(monkeypatch) + _counting_exchanges(monkeypatch) + _api_refusing_first_tokens(monkeypatch, refused=1) + forgotten = [] + monkeypatch.setattr(AuthClientMock, "forget", lambda self, bsuid: forgotten.append(bsuid)) + + asyncio.run(_manager().sign_in_and_handle_text_message()) + + assert forgotten == [BSUID] + + +def test_a_non_401_failure_is_not_retried(monkeypatch): + _capturing(monkeypatch) + _spy_on_replies(monkeypatch) + exchanges = _counting_exchanges(monkeypatch) + state = {"chat_calls": 0} + + async def failing(self, token, thread_id, message): + from ansari_whatsapp.utils.exceptions import MessageProcessingError + + state["chat_calls"] += 1 + raise MessageProcessingError("apps/api is down") + + monkeypatch.setattr(AnsariClientMock, "process_message", failing) + + asyncio.run(_manager().sign_in_and_handle_text_message()) + + assert state["chat_calls"] == 1 + assert len(exchanges) == 1 + + +def test_only_a_401_from_apps_api_raises_the_unauthorized_error(monkeypatch): + from ansari_whatsapp.services.ansari_client_real import AnsariClientReal + from ansari_whatsapp.utils.exceptions import ThreadInfoError + + def build(status): + monkeypatch.setattr( + "ansari_whatsapp.services.ansari_client_real.httpx.AsyncClient", + lambda **kw: _RealAsyncClient(transport=httpx.MockTransport(lambda r: httpx.Response(status, json={})), **kw), + ) + return AnsariClientReal() + + with pytest.raises(ApiUnauthorizedError): + asyncio.run(build(401).get_last_thread_info("jwt")) + with pytest.raises(ApiUnauthorizedError): + asyncio.run(build(401).create_thread("jwt", "t")) + with pytest.raises(ApiUnauthorizedError): + asyncio.run(build(401).delete_thread("jwt", "t1")) + with pytest.raises(ApiUnauthorizedError): + asyncio.run(build(401).process_message("jwt", "t1", "hi")) + for status in (403, 500): + with pytest.raises(ThreadInfoError): + asyncio.run(build(status).get_last_thread_info("jwt")) From 7b9aad8cb778c80dfa1805bc99571b96d89a4467 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Sat, 31 Oct 2026 13:54:31 +0200 Subject: [PATCH 005/435] [Spec 321] WhatsApp: reply to the phone on local/staging (test number allowed list), log Meta errors, 20 s send timeout, Graph API v26.0 Production still replies to the BSUID (verified live: Meta accepted a BSUID send from the production number). Local and staging reply to the sender's phone when the webhook has one, since the test number's allowed-recipient list holds phone numbers only (error 131030). Identity stays the BSUID everywhere. Also: add type text to the send payload, always log Meta's error reply (request details only on a 400 outside production, token masked), explicit httpx timeout, rename send_whatsapp_message's recipient_bsuid to recipient_bsuid_or_phone, bump META_API_VERSION to v26.0, add scripts/check_meta_subscriptions.py and .env.example docs. --- legacy/whatsapp/.env.example | 41 +- .../scripts/check_meta_subscriptions.py | 770 ++++++++++++++++++ .../whatsapp/src/ansari_whatsapp/app/main.py | 2 + .../services/meta_api_service_real.py | 32 +- .../services/meta_service_provider.py | 2 + .../services/whatsapp_conversation_manager.py | 14 +- .../src/ansari_whatsapp/utils/config.py | 6 +- .../utils/whatsapp_webhook_utils.py | 15 +- legacy/whatsapp/tests/test_bsuid_auth_flow.py | 31 +- .../tests/test_meta_sender_logging.py | 109 ++- .../whatsapp/tests/test_thread_lifecycle.py | 6 +- 11 files changed, 993 insertions(+), 35 deletions(-) create mode 100644 legacy/whatsapp/scripts/check_meta_subscriptions.py diff --git a/legacy/whatsapp/.env.example b/legacy/whatsapp/.env.example index 64bf4f2e..884fbbdc 100644 --- a/legacy/whatsapp/.env.example +++ b/legacy/whatsapp/.env.example @@ -75,13 +75,14 @@ META_WEBHOOK_ZROK_SHARE_TOKEN="<>"` # where XXXX is your new port number (which correspond to the PORT variable found in `.env` file) -META_API_VERSION="v22.0" + +META_API_VERSION="v26.0" # Phone number ID (from Meta Dashboard) # NOTE 1: Contact the team to see whatsapp's 2 phone nums -> one for prod. env. and the other for local/stage testing # NOTE 2: If you encounter this error: -# "Client error '400 Bad Request' for url 'https://graph.facebook.com/v22.0//messages'" +# "Client error '400 Bad Request' for url 'https://graph.facebook.com/v26.0//messages'" # then either: # (1) the got deleted by Meta due to inactive use for a long time. # If this happens, then open the page in source 3 (i.e., youtube video URL above) @6:11. @@ -116,6 +117,42 @@ META_WEBHOOK_VERIFY_TOKEN="</subscribed_apps) takes this ID, and a +# webhook only reaches the Meta apps subscribed to it. When messages to META_BUSINESS_PHONE_NUMBER_ID do not arrive, +# the script lists the subscribed apps (e.g. "Ansari - Staging") and can subscribe or unsubscribe the app your access +# token belongs to. It also shows the token's app and expiry, and lists the phone numbers. +# (Meta's API docs and the script's own text may still say "WABA ID"; it is the same value.) +# +# Two alternative methods to find it (it is not secret btw, but it differs per Messaging account): +# 1) developers.facebook.com: https://developers.facebook.com/apps/ -> your app -> WhatsApp -> "Step 1. Try it out" +# -> "Claim a WhatsApp test number" section -> "Messaging account ID". For the production number instead, open +# "Step 2. Production setup" -> "Register your WhatsApp phone number" and read it under "Ansari Chat". +# 2) business.facebook.com: https://business.facebook.com/ -> left side, under "Accounts" click "Messaging accounts" +# -> choose the one to inspect (e.g. "Test Messaging Account" or "Ansari Chat") -> its "ID" is shown directly +# below its name. +# Leave the placeholder (or omit it) if you never run that script; the script also asks for it at runtime. +META_MESSAGING_ACCOUNT_ID="your_messaging_account_id_here" + +# # Meta Developer App ID of the app whose access token and app secret are used above. NOT read by this service. +# # It is only a reference, to remember which app ("Ansari - Test", "Ansari - Staging" or "Ansari") the credentials belong to, +# # because a token, an app secret and a verify token from different apps will not work together. +# # Location: Meta Developer Dashboard (https://developers.facebook.com/) → My Apps → Select your app → App Settings → Basic → App ID +# # Optional. The App ID is not secret. +# META_ANSARI_APP_ID="your_app_id_here" + ###################################### Related to Chat Settings ###################################### diff --git a/legacy/whatsapp/scripts/check_meta_subscriptions.py b/legacy/whatsapp/scripts/check_meta_subscriptions.py new file mode 100644 index 00000000..1d57560d --- /dev/null +++ b/legacy/whatsapp/scripts/check_meta_subscriptions.py @@ -0,0 +1,770 @@ +""" +Script to check WhatsApp Business Account subscriptions and phone numbers. + +Usage: + python path/to/this/file.py + +Requirements: + - Set up your .env file with META_ACCESS_TOKEN_FROM_SYS_USER / WABA ID + (otherwise you'll be prompted at runtime) + +Features: + - Understand the big picture (relation between WABA, apps, etc) + - Get WABA details (name, ID, etc.) + - List subscribed apps + - List phone numbers + - Subscribe WABA to app + - Unsubscribe WABA from app +""" + +import os +import requests +from dotenv import load_dotenv + +# Load environment variables +dotenv_loaded = load_dotenv() + +# Configuration +META_API_VERSION = "v26.0" + +# Check if .env file was loaded +if dotenv_loaded: + ACCESS_TOKEN = os.getenv("META_ACCESS_TOKEN_FROM_SYS_USER") + WABA_ID = os.getenv("META_MESSAGING_ACCOUNT_ID") # Can be None, will prompt if not set +else: + # No .env file found, will prompt user for values + ACCESS_TOKEN = None + WABA_ID = None + + +def get_waba_details(): + """Get WABA details including name and other information.""" + print("\n" + "=" * 60) + print("FETCHING WABA DETAILS") + print("=" * 60) + + url = f"https://graph.facebook.com/{META_API_VERSION}/{WABA_ID}" + params = {"fields": "id,name,timezone_id,message_template_namespace,account_review_status"} + headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"} + + try: + response = requests.get(url, headers=headers, params=params) + response.raise_for_status() + data = response.json() + + print("\nWABA Details:") + print(f" ID: {data.get('id', 'N/A')}") + print(f" Name: {data.get('name', 'N/A')}") + print(f" Timezone: {data.get('timezone_id', 'N/A')}") + print(f" Namespace: {data.get('message_template_namespace', 'N/A')}") + print(f" Review Status: {data.get('account_review_status', 'N/A')}") + + return data + + except requests.exceptions.HTTPError as e: + print(f"\nHTTP Error: {e}") + print(f" Response: {e.response.text}") + return None + except Exception as e: + print(f"\nError: {e}") + return None + + +def debug_access_token(): + """View the access token details including app, permissions, and expiration.""" + print("\n" + "=" * 60) + print("VIEWING ACCESS TOKEN DETAILS") + print("=" * 60) + + url = f"https://graph.facebook.com/{META_API_VERSION}/debug_token" + params = { + "input_token": ACCESS_TOKEN, + "access_token": ACCESS_TOKEN, # Can use the same token to debug itself + } + + try: + response = requests.get(url, params=params) + response.raise_for_status() + result = response.json() + + if "data" in result: + data = result["data"] + from datetime import datetime + + print("\nAccess Token Details:") + + # Basic app info + print(f" App ID: {data.get('app_id', 'N/A')}") + print(f" Application: {data.get('application', 'N/A')}") + print(f" Type: {data.get('type', 'N/A')}") + print(f" Is Valid: {data.get('is_valid', 'N/A')}") + + # Time-related fields + issued_at = data.get("issued_at") + if issued_at: + issued_date = datetime.fromtimestamp(issued_at) + print(f" Issued At: {issued_date} ({issued_at})") + else: + print(" Issued At: N/A") + + # Check expiration + expires_at = data.get("expires_at", 0) + if expires_at == 0: + print(" Expires At: Never (permanent token)") + else: + expiry_date = datetime.fromtimestamp(expires_at) + print(f" Expires At: {expiry_date} ({expires_at})") + + # Data access expiration + data_access_expires = data.get("data_access_expires_at") + if data_access_expires: + data_expiry = datetime.fromtimestamp(data_access_expires) + print(f" Data Access Expires At: {data_expiry} ({data_access_expires})") + + # User/Profile info + if "user_id" in data: + print(f" User ID: {data.get('user_id')}") + if "profile_id" in data: + print(f" Profile ID: {data.get('profile_id')}") + + # Show scopes/permissions + scopes = data.get("scopes", []) + if scopes: + print(f" Permissions/Scopes ({len(scopes)}):") + for scope in scopes: + print(f" - {scope}") + else: + print(" Permissions/Scopes: None (may be an app token)") + + # Granular scopes (more detailed permissions) + granular_scopes = data.get("granular_scopes", []) + if granular_scopes: + print(f" Granular Scopes ({len(granular_scopes)}):") + for scope in granular_scopes: + if isinstance(scope, dict): + print(f" - {scope.get('scope', 'N/A')}: {scope.get('target_ids', [])}") + else: + print(f" - {scope}") + + # Metadata (additional info like SSO) + metadata = data.get("metadata") + if metadata: + print(" Metadata:") + if isinstance(metadata, dict): + for key, value in metadata.items(): + print(f" {key}: {value}") + else: + print(f" {metadata}") + + # Error field (if token is invalid) + if "error" in data: + print(f" Error: {data.get('error')}") + + # Show any additional fields not explicitly handled + handled_keys = { + "app_id", + "application", + "type", + "is_valid", + "issued_at", + "expires_at", + "data_access_expires_at", + "user_id", + "profile_id", + "scopes", + "granular_scopes", + "metadata", + "error", + } + additional_fields = {k: v for k, v in data.items() if k not in handled_keys} + if additional_fields: + print(" Additional Fields:") + for key, value in additional_fields.items(): + print(f" {key}: {value}") + + return result + + except requests.exceptions.HTTPError as e: + print(f"\nHTTP Error: {e}") + print(f" Response: {e.response.text}") + print("\n Note: debug_token may not work on development/test apps.") + print(" Try checking your token at: https://developers.facebook.com/tools/debug/accesstoken/") + return None + except Exception as e: + print(f"\nError: {e}") + return None + + +def check_subscribed_apps(): + """Check which apps are subscribed to the WABA.""" + print("\n" + "=" * 60) + print("CHECKING SUBSCRIBED APPS") + print("=" * 60) + + url = f"https://graph.facebook.com/{META_API_VERSION}/{WABA_ID}/subscribed_apps" + headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"} + + try: + response = requests.get(url, headers=headers) + response.raise_for_status() + data = response.json() + + print("\nSuccessfully retrieved subscribed apps") + + if "data" in data: + if len(data["data"]) == 0: + print("\nWARNING: No apps are subscribed to this WABA!") + print(" This means webhooks won't be delivered to your app.") + else: + # Extract app names for summary + app_names = [] + for app in data["data"]: + if "whatsapp_business_api_data" in app: + app_name = app["whatsapp_business_api_data"].get("name", "Unknown App") + app_names.append(app_name) + + # Show summary with app names + print(f"\nFound {len(data['data'])} subscribed app(s) to the WABA: {', '.join(app_names)}") + + # Show detailed information for each app + for app in data["data"]: + print("\n App Details:") + for key, value in app.items(): + print(f" {key}: {value}") + + return data + + except requests.exceptions.HTTPError as e: + print(f"\nHTTP Error: {e}") + print(f" Response: {e.response.text}") + return None + except Exception as e: + print(f"\nError: {e}") + return None + + +def show_miscellaneous_info(): + """Display side notes that do not fit another menu option (unverified guesses are labelled as such).""" + print("\n" + "=" * 60) + print("MISCELLANEOUS INFO") + print("=" * 60) + + print("\n1. 'WA DevX Webhook Events 1P App' shows up in option 3 (apps subscribed to the WABA). What is it?") + print(" It is not one of our apps, and we found no Meta documentation that names it. Our best guess (UNVERIFIED):") + print(" it is a Meta-owned app that Meta adds to WhatsApp accounts created through its dashboard test setup.") + print(" The name reads as 'WhatsApp developer experience' + '1P' (first-party, i.e. Meta's own app).") + print(" Meta's docs say a WABA sends webhooks to every subscribed app, so an extra subscriber should not stop") + print(" ours from receiving them. The real question is whether OUR app (the one in 'CURRENT CONTEXT') is listed.") + print(" If it is the only app listed, our app is NOT subscribed: use option 5 (it changes Meta's state).") + print(" The 'link' field (facebook.com/games/?app_id=...) is just Meta's generic URL format for any app.") + print(" Only source found, a single user's claim (it also guesses the app may intercept messages, unproven):") + print(" https://www.reddit.com/r/MetaAppDevelopers/comments/1qi2jqa/whatsapp_cloud_api_webhook_works_on_new_business") + print(" Subscribed-apps API: https://developers.facebook.com/docs/whatsapp/embedded-signup/webhooks") + + print("\n" + "=" * 60) + input("\nPress Enter to return to menu...") + + +def list_phone_numbers(): + """List all phone numbers registered to the WABA.""" + print("\n" + "=" * 60) + print("LISTING PHONE NUMBERS") + print("=" * 60) + + url = f"https://graph.facebook.com/{META_API_VERSION}/{WABA_ID}/phone_numbers" + headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"} + + try: + response = requests.get(url, headers=headers) + response.raise_for_status() + data = response.json() + + print(f"\nSuccessfully retrieved phone numbers for WABA: {WABA_ID}") + + if "data" in data: + print(f"\nFound {len(data['data'])} phone number(s):") + for phone in data["data"]: + print(f"\n Phone Number ID: {phone.get('id')}") + print(f" Display Name: {phone.get('display_phone_number', 'N/A')}") + print(f" Verified Name: {phone.get('verified_name', 'N/A')}") + print(f" Quality Rating: {phone.get('quality_rating', 'N/A')}") + print(f" Status: {phone.get('code_verification_status', 'N/A')}") + else: + print("\nNo phone numbers found for this WABA") + + return data + + except requests.exceptions.HTTPError as e: + print(f"\nHTTP Error: {e}") + print(f" Response: {e.response.text}") + return None + except Exception as e: + print(f"\nError: {e}") + return None + + +def subscribe_waba(): + """Subscribe the WABA to receive webhooks in this app.""" + print("\n" + "=" * 60) + print("SUBSCRIBING WABA TO APP") + print("=" * 60) + + url = f"https://graph.facebook.com/{META_API_VERSION}/{WABA_ID}/subscribed_apps" + headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"} + + print("\nThis will subscribe your WABA to the app associated with your access token.") + print(" Webhooks from this WABA will be sent to this app's webhook URL.") + user_response = input("\n Do you want to proceed? (yes/no): ").strip().lower() + + if user_response != "yes": + print(" Subscription cancelled.") + return None + + try: + response = requests.post(url, headers=headers) + response.raise_for_status() + data = response.json() + + print("\nSuccessfully subscribed WABA to app!") + if data.get("success"): + print(" Status: Subscription active") + + return data + + except requests.exceptions.HTTPError as e: + print(f"\nHTTP Error: {e}") + print(f" Response: {e.response.text}") + return None + except Exception as e: + print(f"\nError: {e}") + return None + + +def unsubscribe_waba(): + """Unsubscribe the WABA from receiving webhooks in this app.""" + print("\n" + "=" * 60) + print("UNSUBSCRIBING WABA FROM APP") + print("=" * 60) + + # Step 1: Get the current access token's app name + print("\n→ Step 1: Identifying your access token's app...") + token_debug_url = f"https://graph.facebook.com/{META_API_VERSION}/debug_token" + token_params = {"input_token": ACCESS_TOKEN, "access_token": ACCESS_TOKEN} + headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"} + + try: + token_response = requests.get(token_debug_url, params=token_params) + token_response.raise_for_status() + token_data = token_response.json() + + if "data" not in token_data: + print(" ERROR: Unable to debug access token.") + return None + + token_app_name = token_data["data"].get("application", "Unknown") + token_app_id = token_data["data"].get("app_id", "Unknown") + print(f" Your access token is associated with: {token_app_name} (ID: {token_app_id})") + + except Exception as e: + print(f" ERROR: Failed to get token details: {e}") + return None + + # Step 2: Get WABA name + print("\n→ Step 2: Getting WABA details...") + waba_url = f"https://graph.facebook.com/{META_API_VERSION}/{WABA_ID}" + waba_params = {"fields": "name"} + + try: + waba_response = requests.get(waba_url, headers=headers, params=waba_params) + waba_response.raise_for_status() + waba_data = waba_response.json() + waba_name = waba_data.get("name", f"WABA {WABA_ID}") + print(f" WABA Name: {waba_name}") + + except Exception as e: + print(f" Warning: Could not get WABA name: {e}") + waba_name = f"WABA {WABA_ID}" + + # Step 3: Get currently subscribed apps + print("\n→ Step 3: Checking currently subscribed apps...") + subscribed_url = f"https://graph.facebook.com/{META_API_VERSION}/{WABA_ID}/subscribed_apps" + + try: + subscribed_response = requests.get(subscribed_url, headers=headers) + subscribed_response.raise_for_status() + subscribed_data = subscribed_response.json() + + if "data" not in subscribed_data or len(subscribed_data["data"]) == 0: + print(" No apps are currently subscribed to this WABA.") + print("\n Nothing to unsubscribe. Exiting.") + return None + + # Extract subscribed app names + subscribed_app_names = [] + for app in subscribed_data["data"]: + if "whatsapp_business_api_data" in app: + app_name = app["whatsapp_business_api_data"].get("name", "Unknown App") + subscribed_app_names.append(app_name) + + print(f" Currently subscribed apps: {', '.join(subscribed_app_names) if subscribed_app_names else 'None found'}") + + except Exception as e: + print(f" ERROR: Failed to get subscribed apps: {e}") + return None + + # Step 4: Check if token's app is in the subscribed list + print("\n→ Step 4: Verifying subscription match...") + + if token_app_name not in subscribed_app_names: + print("\n WARNING: Your access token's app is NOT in the subscribed list!") + print("\n Details:") + print(f" * Your token is for: {token_app_name}") + print(f" * WABA '{waba_name}' is subscribed to: {', '.join(subscribed_app_names)}") + print("\n Cannot proceed with unsubscription.") + print("\n → Solution: Change your access token to one bound to an app in the subscribed list.") + print(" Apps you need a token for:") + for app_name in subscribed_app_names: + print(f" - {app_name}") + return None + + # Step 5: Confirm unsubscription + print(f"\n Match found: {token_app_name} app is subscribed to {waba_name} WABA") + print("\n→ Step 5: Confirming unsubscription...") + print(f"\n WARNING: This will unsubscribe '{token_app_name}' from '{waba_name}'") + print(f" * Webhooks will STOP being sent to {token_app_name}'s webhook URL") + other_apps = [n for n in subscribed_app_names if n != token_app_name] + print(f" * Other subscribed apps will remain unaffected: {', '.join(other_apps)}") + + user_response = input("\n Are you sure you want to proceed? (yes/no): ").strip().lower() + + if user_response != "yes": + print(" Unsubscription cancelled.") + return None + + # Step 6: Perform unsubscription + print("\n→ Step 6: Performing unsubscription...") + try: + response = requests.delete(subscribed_url, headers=headers) + response.raise_for_status() + data = response.json() + + print(f"\n Successfully unsubscribed '{token_app_name}' from '{waba_name}'!") + if data.get("success"): + print(" Status: Subscription removed") + + return data + + except requests.exceptions.HTTPError as e: + print(f"\n HTTP Error: {e}") + print(f" Response: {e.response.text}") + return None + except Exception as e: + print(f"\n Error: {e}") + return None + + +def show_prerequisite_knowledge(): + """Display prerequisite knowledge about Meta's WhatsApp Business architecture.""" + print("\n" + "=" * 60) + print("PREREQUISITE KNOWLEDGE: Meta WhatsApp Business Architecture") + print("=" * 60) + + print("\n📚 THE BIG PICTURE\n") + + print("1. HIERARCHY OF META ASSETS:") + print(" " + "-" * 56) + print(" Meta Business Manager (business.facebook.com)") + print(" ↓") + print(" WhatsApp Business Account (WABA)") + print(" ↓") + print(" Phone Numbers (up to 20 per WABA)") + print("\n Developer App (developers.facebook.com)") + print(" ↓") + print(" App Secret + Access Token") + print(" ↓") + print(" Webhook URL (receives messages)") + + print("\n2. HOW THEY CONNECT:") + print(" " + "-" * 56) + print(" • A WABA can be SUBSCRIBED to multiple Developer Apps") + print(" • When someone messages your WhatsApp number:") + print(" 1. Meta finds which WABA owns that phone number") + print(" 2. Meta checks which Developer Apps are subscribed to that WABA") + print(" 3. Meta sends webhooks to ALL subscribed apps' webhook URLs") + print(" 4. Meta signs each webhook with the app's App Secret") + + print("\n3. KEY CONCEPTS:") + print(" " + "-" * 56) + print(" • WABA (WhatsApp Business Account):") + print(" - Container for your WhatsApp phone numbers") + print(" - Managed in Meta Business Manager") + print(" - Can have multiple phone numbers") + print("\n • Developer App (e.g., 'Ansari - Test'):") + print(" - Created at developers.facebook.com") + print(" - Has unique App ID and App Secret") + print(" - Needs to be SUBSCRIBED to a WABA to receive webhooks") + print("\n • Access Token:") + print(" - Generated for a specific Developer App") + print(" - Used to authenticate API calls") + print(" - Token is tied to ONE app only (cannot be shared)") + print("\n • App Secret:") + print(" - Secret key unique to each Developer App") + print(" - Used by Meta to sign webhook payloads") + print(" - Your server verifies signatures to ensure authenticity") + print("\n • Subscription:") + print(" - Links a WABA to a Developer App") + print(" - Required for webhooks to be delivered") + print(" - One WABA can subscribe to multiple apps") + + print("\n4. COMMON SETUP (3 ENVIRONMENTS):") + print(" " + "-" * 56) + print(" • Test/Local Environment:") + print(" - Developer App: 'Ansari - Test'") + print(" - WABA: 'Test WhatsApp Business Account'") + print(" - Phone Number: Test number (90-day expiry)") + print(" - Webhook: zrok tunnel (e.g., https://xxx.share.zrok.io)") + print("\n • Staging Environment:") + print(" - Developer App: 'Ansari - Staging'") + print(" - WABA: Also 'Test WhatsApp Business Account'") + print(" - Phone Number: Same Test number (nuisance though, as sending a msg to it hits both apps)") + print(" - Webhook: Staging server URL") + print("\n • Production Environment:") + print(" - Developer App: 'Ansari' (production)") + print(" - WABA: Production WABA") + print(" - Phone Number: Official business phone") + print(" - Webhook: Production server URL") + + print("\n5. WHY THIS MATTERS:") + print(" " + "-" * 56) + print(" • Access tokens are APP-SPECIFIC") + print(" → You need separate tokens for test/staging/production") + print("\n • Subscriptions control webhook delivery") + print(" → If not subscribed, you won't receive messages") + print("\n • App Secrets must match for signature verification") + print(" → Wrong secret = webhooks rejected by your server") + print("\n • Multiple apps can subscribe to the same WABA") + print(" → Useful for routing to different environments") + + print("\n6. VISUAL EXAMPLE:") + print(" " + "-" * 56) + print(" WABA: 'Test WhatsApp Business Account'") + print(" ├─ Phone: +1234567890 (test)") + print(" └─ Subscribed to:") + print(" ├─ App: 'Ansari - Test'") + print(" │ ├─ Access Token: EAAMf...") + print(" │ ├─ App Secret: abc123...") + print(" │ └─ Webhook: https://xxx.share.zrok.io/whatsapp/v2") + print(" └─ App: 'Ansari - Staging'") + print(" ├─ Access Token: EAAMf...") + print(" ├─ App Secret: def456...") + print(" └─ Webhook: https://staging-api.ansari.chat/whatsapp/v2") + print("\n When user sends message to +1234567890:") + print(" → Both 'Ansari - Test' AND 'Ansari - Staging' receive webhooks!") + + print("\n7. USEFUL RESOURCES:") + print(" " + "-" * 56) + print(" • Debug Access Token:") + print(" https://developers.facebook.com/tools/debug/accesstoken/") + print(" • Meta Business Manager:") + print(" https://business.facebook.com/") + print(" • Developer Apps:") + print(" https://developers.facebook.com/apps/") + print(" • WhatsApp API Documentation:") + print(" https://developers.facebook.com/docs/whatsapp/") + print(" • NEXT STEP - get your WABA ID (every menu choice from 1 to 7 needs it):") + print(" 1. Open https://developers.facebook.com/apps/ and click the app your access token belongs to") + print(" (e.g. 'Ansari - Staging'; the 'CURRENT CONTEXT' box in the menu shows which app that is).") + print(" 2. In the app's left-hand menu open the 'WhatsApp' use case, then 'Step 1. Try it out'.") + print(" 3. Under the 'Claim a WhatsApp test number' section, copy the 'Messaging account ID'.") + print(" (Meta's new name for the WhatsApp Business Account ID; it is the value of META_MESSAGING_ACCOUNT_ID.)") + print(" It sits near the phone number ID in that panel.") + print(" 4. Check it is the right one: the phone number selected there must be the number whose ID is in") + print(" META_BUSINESS_PHONE_NUMBER_ID (a different number can belong to a different WABA).") + print(" 5. Put it in your .env as META_MESSAGING_ACCOUNT_ID=, or paste it when this script asks for it.") + print(" Want the Messaging account ID of the PRODUCTION number instead of the test number?") + print(" On the same app page, open 'Step 2. Production setup' → 'Register your WhatsApp phone number';") + print(" the Messaging account ID is shown there under 'Ansari Chat' (the production account).") + print(" Use the production app's token for it (e.g. 'Ansari'), and re-check step 4 for the production number ID.") + print(" Alternative (from memory, not checked against Meta's docs): https://business.facebook.com/latest/settings") + print(" → Accounts → WhatsApp accounts → select the account → its ID is in the details panel.") + print(" Menu names change; if one is missing, look for 'WhatsApp Business Account ID' on those pages.") + + print("\n" + "=" * 60) + print("NEXT STEP: copy your WABA ID as described in section 7, then run option 3 (subscribed apps).") + input("\nPress Enter to return to menu...") + + +def get_current_context(): + """Get and return current WABA name and App name for context display.""" + waba_name = "Unknown" + app_name = "Unknown" + + # Get WABA name + try: + waba_url = f"https://graph.facebook.com/{META_API_VERSION}/{WABA_ID}" + waba_params = {"fields": "name"} + headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"} + + waba_response = requests.get(waba_url, headers=headers, params=waba_params) + if waba_response.status_code == 200: + waba_data = waba_response.json() + waba_name = waba_data.get("name", "Unknown (probably invalid WABA ID)") + except Exception: + pass # Keep default "Unknown" + + # Get App name from token + try: + token_debug_url = f"https://graph.facebook.com/{META_API_VERSION}/debug_token" + token_params = {"input_token": ACCESS_TOKEN, "access_token": ACCESS_TOKEN} + + token_response = requests.get(token_debug_url, params=token_params) + if token_response.status_code == 200: + token_data = token_response.json() + if "data" in token_data: + app_name = token_data["data"].get("application", "Unknown (probably invalid token)") + except Exception: + pass # Keep default "Unknown" + + return waba_name, app_name + + +def show_menu(): + """Display interactive menu for user actions.""" + # Get current context + waba_name, app_name = get_current_context() + + print("\n" + "=" * 60) + print("CURRENT CONTEXT") + print("=" * 60) + print(f" WABA: {waba_name}") + print(f" App: {app_name}") + print("=" * 60) + print("AVAILABLE ACTIONS") + print("=" * 60) + print("\n0. 📚 Show prerequisite knowledge (understand the big picture)") + print("1. View WABA details") + print("2. View access token details for debugging") + print("3. Check apps subscribed to the WABA") + print("4. List phone numbers registered to the WABA") + print("5. Subscribe WABA to app (enable webhooks)") + print("6. Unsubscribe WABA from app (disable webhooks)") + print("7. Run all checks (view everything)") + print("8. Miscellaneous info (e.g., what is 'WA DevX Webhook Events 1P App' in option 3's list?)") + print("9. Exit") + + while True: + try: + choice = input("\nEnter your choice (0-9): ").strip() + if choice in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]: + return choice + else: + print(" Invalid choice. Please enter a number between 0 and 9.") + except KeyboardInterrupt: + print("\n\nInterrupted by user. Exiting...") + return "9" + + +def main(): + global ACCESS_TOKEN, WABA_ID # Allow modification if not set in .env + + print("=" * 60) + print("WhatsApp Business Account Subscription Manager") + print("=" * 60) + + # Check if .env file was loaded + if not dotenv_loaded: + print("\n No .env file found in the current directory") + print(" You can either:") + print(" 1. Create a .env file with META_ACCESS_TOKEN_FROM_SYS_USER and META_MESSAGING_ACCOUNT_ID") + print(" 2. Enter the values manually now (they won't be saved)") + + use_manual = input("\n Enter values manually? (yes/no): ").strip().lower() + if use_manual != "yes": + print("\n Please create a .env file and try again.") + print("\n Example .env file:") + print(" META_ACCESS_TOKEN_FROM_SYS_USER=your_token_here") + print(" META_MESSAGING_ACCOUNT_ID=your_id_here") + return + + # Check for access token + if not ACCESS_TOKEN: + print("\n→ Access Token Configuration") + print(" You can find your token at:") + print(" 1. Go to business.facebook.com → Business Settings → System Users") + print(" 2. Select your System User → Generate New Token") + print(" 3. Select your app and required permissions") + print(" 4. Copy the generated token") + + ACCESS_TOKEN = input("\n Enter your META_ACCESS_TOKEN_FROM_SYS_USER: ").strip() + + if not ACCESS_TOKEN: + print("\n ERROR: Access token is required. Exiting...") + return + + # Check for WABA ID (prompt if not set) + if not WABA_ID: + print("\n→ WABA ID Configuration") + print(" Get it from https://developers.facebook.com/apps/ → your app → WhatsApp → API Setup") + print(" Look for 'WhatsApp Business Account ID' (called 'Messaging account ID' in Meta's newer docs).") + print(" Step-by-step: the last bullet of '7. USEFUL RESOURCES' in this script (menu option 0).") + print(" Tip: save it as META_MESSAGING_ACCOUNT_ID in .env so you are not asked next time.") + + WABA_ID = input("\n Enter your WABA ID: ").strip() + + if not WABA_ID: + print("\n ERROR: WABA ID is required. Exiting...") + return + + print("\nConfiguration:") + print(f" WABA ID: {WABA_ID}") + print(f" Access Token: {ACCESS_TOKEN[:20]}...{ACCESS_TOKEN[-10:]}") + + # Interactive menu loop + while True: + choice = show_menu() + + if choice == "0": + show_prerequisite_knowledge() + elif choice == "1": + get_waba_details() + elif choice == "2": + debug_access_token() + elif choice == "3": + check_subscribed_apps() + elif choice == "4": + list_phone_numbers() + elif choice == "5": + response = subscribe_waba() + if response: + print("\n → Verifying subscription...") + check_subscribed_apps() + elif choice == "6": + response = unsubscribe_waba() + if response: + print("\n → Verifying unsubscription...") + check_subscribed_apps() + elif choice == "7": + get_waba_details() + debug_access_token() + check_subscribed_apps() + list_phone_numbers() + elif choice == "8": + show_miscellaneous_info() + elif choice == "9": + print("\n" + "=" * 60) + print("Done! Exiting...") + print("=" * 60) + break + + # Ask if user wants to continue + if choice not in ("8", "9"): + continue_choice = input("\n Press Enter to return to menu (or 'q' to quit): ").strip().lower() + if continue_choice == "q": + print("\n" + "=" * 60) + print("Done! Exiting...") + print("=" * 60) + break + + +if __name__ == "__main__": + main() diff --git a/legacy/whatsapp/src/ansari_whatsapp/app/main.py b/legacy/whatsapp/src/ansari_whatsapp/app/main.py index 08f30152..89295e3a 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/app/main.py +++ b/legacy/whatsapp/src/ansari_whatsapp/app/main.py @@ -259,6 +259,7 @@ async def main_webhook( incoming_msg_body, message_id, message_unix_time, + sender_phone, ) = await parse_meta_payload(data) # Check if this webhook is intended for our WhatsApp business phone number @@ -330,6 +331,7 @@ async def main_webhook( incoming_msg_body=incoming_msg_body, message_id=message_id, message_unix_time=message_unix_time, + sender_phone=sender_phone, ) # Check if the WhatsApp service is enabled diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_real.py b/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_real.py index a0affa04..36041196 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_real.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_real.py @@ -11,6 +11,10 @@ from ansari_whatsapp.services.meta_api_service_base import MetaApiServiceBase +# Why longer timeout? As Meta can take over 5 s (httpx's default) to answer a send-message request from us. +REQUEST_TIMEOUT = httpx.Timeout(20.0, connect=10.0) + + class MetaApiServiceReal(MetaApiServiceBase): """Real Meta WhatsApp API service that makes actual HTTP requests.""" @@ -31,6 +35,18 @@ def _get_headers(self) -> dict: "Content-Type": "application/json", } + @staticmethod + def _log_bad_request_details(error: httpx.HTTPStatusError) -> None: + """Always log Meta's reply; log the request we sent too, but only for a 400 outside production.""" + logger.error(f"Meta's reply ({error.response.status_code}): {error.response.text}") + if error.response.status_code != 400 or get_settings().DEPLOYMENT_TYPE == "production": + return + headers = {k: ("Bearer ***" if k.lower() == "authorization" else v) for k, v in error.request.headers.items()} + logger.error( + f"Meta rejected the request (400). URL: {error.request.url} | Headers: {headers} | " + f"Body: {error.request.content.decode('utf-8', errors='replace')}" + ) + async def send_typing_indicator(self, recipient_phone: str, message_id: str) -> None: """Send typing indicator via Meta API. @@ -54,7 +70,7 @@ async def send_typing_indicator(self, recipient_phone: str, message_id: str) -> } try: - async with httpx.AsyncClient() as client: + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client: logger.debug("Sending typing indicator") response = await client.post(self.api_url, headers=self._get_headers(), json=json_data) @@ -63,6 +79,7 @@ async def send_typing_indicator(self, recipient_phone: str, message_id: str) -> except httpx.HTTPStatusError as e: logger.error(f"HTTP error sending typing indicator: {e.response.status_code}") + self._log_bad_request_details(e) # Only capture 5xx errors (Meta's fault, not ours) if e.response.status_code >= 500: sentry_sdk.set_tag("error_type", "meta_api_failure") @@ -77,7 +94,7 @@ async def send_typing_indicator(self, recipient_phone: str, message_id: str) -> sentry_sdk.capture_exception(e) raise except httpx.RequestError as e: - logger.error(f"Network error sending typing indicator: {e}") + logger.error(f"Network error sending typing indicator ({type(e).__name__}): {e}") raise except Exception as e: logger.exception(f"Unexpected error sending typing indicator: {e}") @@ -97,9 +114,8 @@ async def send_message(self, recipient_phone: str, message_parts: list[str]) -> Note: Per Meta, a phone number goes in `to`, while a BSUID goes in `recipient` (with `to` omitted; - if both are sent, `to` takes precedence). Meta's page marks BSUID sending as "coming soon" - in one place and as supported from July 2026 in another, and this hasn't been tested against - the live API. + if both are sent, `to` takes precedence). Meta's changelog says BSUID sending is supported + since July 2026. https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids#send-message-requests """ if not recipient_phone: @@ -111,12 +127,13 @@ async def send_message(self, recipient_phone: str, message_parts: list[str]) -> return try: - async with httpx.AsyncClient() as client: + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client: logger.debug(f"Sending {len(message_parts)} message part(s)") for i, part in enumerate(message_parts, 1): json_data = { "messaging_product": "whatsapp", + "type": "text", "text": {"body": part}, } if recipient_phone.isdigit(): @@ -139,6 +156,7 @@ async def send_message(self, recipient_phone: str, message_parts: list[str]) -> except httpx.HTTPStatusError as e: logger.error(f"HTTP error sending message: {e.response.status_code}") + self._log_bad_request_details(e) # Only capture 5xx errors (Meta's fault, not ours) if e.response.status_code >= 500: sentry_sdk.set_tag("error_type", "meta_api_failure") @@ -153,7 +171,7 @@ async def send_message(self, recipient_phone: str, message_parts: list[str]) -> sentry_sdk.capture_exception(e) raise except httpx.RequestError as e: - logger.error(f"Network error sending message: {e}") + logger.error(f"Network error sending message ({type(e).__name__}): {e}") raise except Exception as e: logger.exception(f"Unexpected error sending message: {e}") diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/meta_service_provider.py b/legacy/whatsapp/src/ansari_whatsapp/services/meta_service_provider.py index bc6e637b..dc8c2634 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/meta_service_provider.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/meta_service_provider.py @@ -15,6 +15,8 @@ def get_meta_api_service() -> MetaApiServiceBase: This function implements the Service Provider pattern, returning either: - MetaApiServiceReal: Makes actual HTTP calls to Meta WhatsApp API (production) - MetaApiServiceMock: Simulates API responses without network calls (development/testing) + - Side note: By "production" we mean "not mocked", + so if you want, you could disable mocking and still be in a staging/test environment. The choice is controlled by the MOCK_META_API environment variable. diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py b/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py index da0f3339..73499bd2 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py @@ -12,6 +12,7 @@ from ansari_whatsapp.services.service_provider import get_ansari_client, get_auth_client from ansari_whatsapp.services.meta_service_provider import get_meta_api_service from ansari_whatsapp.utils.app_logger import request_id_var +from ansari_whatsapp.utils.config import get_settings from ansari_whatsapp.utils.exceptions import ( ApiUnauthorizedError, AuthBadRequestError, @@ -56,6 +57,7 @@ def __init__( incoming_msg_body: dict = None, message_id: str = None, message_unix_time: int = None, + sender_phone: str = None, ): """Initialize the conversation manager with user-specific details. @@ -65,8 +67,13 @@ def __init__( incoming_msg_body (dict, optional): The body content of the incoming message. message_id (str, optional): The ID of the incoming message. message_unix_time (int, optional): The timestamp of the incoming message in Unix format. + sender_phone (str, optional): The sender's phone number from the webhook, used only to address replies + on local and staging, where Meta's test number accepts recipients by phone number only + (i.e., doesn't accept BSUIDs). """ self.bsuid = bsuid + use_phone = bool(sender_phone) and get_settings().DEPLOYMENT_TYPE in ("local", "staging") + self.reply_to = sender_phone if use_phone else bsuid self.token = None # The user's JWT, set by authenticate_user() self.auth_failure_notice = SIGN_IN_FAILED_NOTICE # What to tell the user if authenticate_user() fails self.incoming_msg_type = incoming_msg_type @@ -192,15 +199,16 @@ async def _send_whatsapp_typing_indicator(self) -> None: async def send_whatsapp_message( self, msg_body: str, - recipient_bsuid: str = None, + recipient_bsuid_or_phone: str = None, ) -> None: """Send a message to the WhatsApp recipient. Args: msg_body (str): The message body to be sent. - recipient_bsuid (str, optional): The recipient's BSUID. Defaults to self.bsuid if not provided. + recipient_bsuid_or_phone (str, optional): A BSUID or a phone number to send to. Defaults to + self.reply_to if not provided (i.e., the BSUID on prod, or the sender's phone on local/staging). """ - recipient = recipient_bsuid or self.bsuid + recipient = recipient_bsuid_or_phone or self.reply_to if not recipient: logger.error("Cannot send WhatsApp message: No recipient provided") diff --git a/legacy/whatsapp/src/ansari_whatsapp/utils/config.py b/legacy/whatsapp/src/ansari_whatsapp/utils/config.py index b4c3865c..afc72cf1 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/utils/config.py +++ b/legacy/whatsapp/src/ansari_whatsapp/utils/config.py @@ -27,8 +27,8 @@ class WhatsAppSettings(BaseSettings): 5. Variables from the secrets directory. 6. Default field values in the WhatsAppSettings model. - E.g., if you set the variable `META_API_VERSION` in .env file to `v22.xyz`, - it will override the default value of `v22.0` defined in the WhatsAppSettings model. + E.g., if you set the variable `META_API_VERSION` in .env file to `v26.xyz`, + it will override the default value of `v26.0` defined in the WhatsAppSettings model. For more details, refer to the Pydantic documentation: [https://docs.pydantic.dev/latest/concepts/pydantic_settings/#field-value-priority]. @@ -52,7 +52,7 @@ class WhatsAppSettings(BaseSettings): ########### Meta Business API settings ########### - META_API_VERSION: str = "v22.0" + META_API_VERSION: str = "v26.0" META_BUSINESS_PHONE_NUMBER_ID: SecretStr META_ACCESS_TOKEN_FROM_SYS_USER: SecretStr META_WEBHOOK_VERIFY_TOKEN: SecretStr diff --git a/legacy/whatsapp/src/ansari_whatsapp/utils/whatsapp_webhook_utils.py b/legacy/whatsapp/src/ansari_whatsapp/utils/whatsapp_webhook_utils.py index 5d061be3..2941ae7f 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/utils/whatsapp_webhook_utils.py +++ b/legacy/whatsapp/src/ansari_whatsapp/utils/whatsapp_webhook_utils.py @@ -152,7 +152,7 @@ def _redact_for_logging(obj, key: str | None = None): async def parse_meta_payload( body: dict[str, dict], -) -> tuple[bool, bool, str | None, str | None, dict | None, str | None, int | None]: +) -> tuple[bool, bool, str | None, str | None, dict | None, str | None, int | None, str | None]: """ Parse the webhook payload received from Meta to extract relevant message details. @@ -161,8 +161,9 @@ async def parse_meta_payload( Returns: tuple: A tuple of (is_status, is_target_business_number, bsuid, - incoming_msg_type, incoming_msg_body, message_id, message_unix_time). - `bsuid` is the sender's business-scoped user ID; the phone number is never used. + incoming_msg_type, incoming_msg_body, message_id, message_unix_time, sender_phone). + `bsuid` is the sender's business-scoped user ID and the only identity we use. `sender_phone` is + the webhook's `from` (None when Meta omits it) and is only used to address replies on test numbers. Raises: Exception: If the payload structure is invalid or unsupported. @@ -194,11 +195,11 @@ async def parse_meta_payload( is_target_business_number = incoming_phone_number_id == configured_phone_number_id if not is_target_business_number: - return None, is_target_business_number, None, None, None, None, None + return None, is_target_business_number, None, None, None, None, None, None if "statuses" in value: # This is a status update (delivered, read, etc.), not a user message - return True, is_target_business_number, None, None, None, None, None + return True, is_target_business_number, None, None, None, None, None, None is_status = False @@ -211,9 +212,10 @@ async def parse_meta_payload( try: # Extract message details. `from_user_id` (the BSUID) is always present; `from` (the phone number) may - # be missing, and is deliberately never read. + # be missing, and is never used to identify the user. message_id = incoming_msg.get("id") bsuid = incoming_msg["from_user_id"] + sender_phone = incoming_msg.get("from") message_unix_time_str = incoming_msg.get("timestamp") message_unix_time = int(message_unix_time_str) if message_unix_time_str is not None else None @@ -240,4 +242,5 @@ async def parse_meta_payload( incoming_msg_body, message_id, message_unix_time, + sender_phone, ) diff --git a/legacy/whatsapp/tests/test_bsuid_auth_flow.py b/legacy/whatsapp/tests/test_bsuid_auth_flow.py index b4c08873..405b0214 100644 --- a/legacy/whatsapp/tests/test_bsuid_auth_flow.py +++ b/legacy/whatsapp/tests/test_bsuid_auth_flow.py @@ -356,7 +356,8 @@ def test_ansari_client_error_status_raises(monkeypatch): # ---------- webhook flow ---------- -def test_phone_visible_user_is_identified_and_replied_to_by_bsuid_only(monkeypatch): +def _spy_identity_and_reply_target(monkeypatch): + """Record which id is exchanged for a token and which recipient each reply is addressed to.""" tokens_requested = [] recipients = [] @@ -374,6 +375,24 @@ async def spy_send(self, recipient_phone, message_parts): monkeypatch.setattr(AuthClientMock, "get_token", spy_get_token) monkeypatch.setattr(MetaApiServiceMock, "send_message", spy_send) + return tokens_requested, recipients + + +@pytest.mark.parametrize("deployment_type", ["local", "staging"]) +def test_test_environments_reply_to_the_phone_but_identify_by_bsuid(monkeypatch, deployment_type): + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", deployment_type) + tokens_requested, recipients = _spy_identity_and_reply_target(monkeypatch) + + response = _post_signed_webhook(_text_message(**{"from": PHONE, "from_user_id": BSUID})) + + assert response.status_code == 200 + assert tokens_requested == [BSUID] + assert recipients and set(recipients) == {PHONE} + + +def test_production_replies_to_the_bsuid_even_when_the_phone_is_visible(monkeypatch): + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", "production") + tokens_requested, recipients = _spy_identity_and_reply_target(monkeypatch) response = _post_signed_webhook(_text_message(**{"from": PHONE, "from_user_id": BSUID})) @@ -383,6 +402,16 @@ async def spy_send(self, recipient_phone, message_parts): assert PHONE not in tokens_requested + recipients +def test_test_environment_falls_back_to_the_bsuid_when_the_phone_is_hidden(monkeypatch): + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", "staging") + _, recipients = _spy_identity_and_reply_target(monkeypatch) + + response = _post_signed_webhook(_text_message(from_user_id=BSUID)) + + assert response.status_code == 200 + assert recipients and set(recipients) == {BSUID} + + def test_no_phone_number_reaches_apps_api(monkeypatch): requests = [] diff --git a/legacy/whatsapp/tests/test_meta_sender_logging.py b/legacy/whatsapp/tests/test_meta_sender_logging.py index 52014f95..f8d8686d 100644 --- a/legacy/whatsapp/tests/test_meta_sender_logging.py +++ b/legacy/whatsapp/tests/test_meta_sender_logging.py @@ -1,42 +1,131 @@ -"""The Meta sender must not write Meta's error body to the logs (spec 321, phase 4 review).""" +"""The Meta sender always logs Meta's error reply, and the request we sent only outside production.""" import asyncio +import json import httpx import pytest from loguru import logger from ansari_whatsapp.services.meta_api_service_real import MetaApiServiceReal +from ansari_whatsapp.utils.config import get_settings BSUID = "US.13491208655302741918" -ECHOED_BODY = '{"error":{"message":"Recipient US.13491208655302741918 is not allowed"}}' +PHONE = "201234567899" +MESSAGE_TEXT = "a-very-distinctive-reply-text" +META_REPLY = '{"error":{"message":"(#131030) Recipient phone number not in allowed list","code":131030}}' _RealAsyncClient = httpx.AsyncClient -def _failing_meta(monkeypatch): +def _meta_answers(monkeypatch, response: httpx.Response, seen: list | None = None): + def handler(request: httpx.Request) -> httpx.Response: + if seen is not None: + seen.append(json.loads(request.content)) + return response + monkeypatch.setattr( "ansari_whatsapp.services.meta_api_service_real.httpx.AsyncClient", - lambda **kw: _RealAsyncClient(transport=httpx.MockTransport(lambda r: httpx.Response(400, text=ECHOED_BODY)), **kw), + lambda **kw: _RealAsyncClient(transport=httpx.MockTransport(handler), **kw), ) -@pytest.mark.parametrize("method", ["send_message", "send_typing_indicator"]) -def test_a_failed_send_logs_the_status_but_never_meta_error_body(monkeypatch, method): - _failing_meta(monkeypatch) +def _failed_send_log(method: str) -> str: service = MetaApiServiceReal() captured = [] sink_id = logger.add(lambda m: captured.append(str(m)), level="DEBUG") try: with pytest.raises(httpx.HTTPStatusError): if method == "send_message": - asyncio.run(service.send_message(BSUID, ["hello"])) + asyncio.run(service.send_message(BSUID, [MESSAGE_TEXT])) else: asyncio.run(service.send_typing_indicator(BSUID, "wamid.T")) finally: logger.remove(sink_id) + return "\n".join(captured) + + +@pytest.mark.parametrize("deployment_type", ["local", "staging", "production"]) +@pytest.mark.parametrize("method", ["send_message", "send_typing_indicator"]) +def test_meta_reply_is_logged_in_every_environment(monkeypatch, method, deployment_type): + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", deployment_type) + _meta_answers(monkeypatch, httpx.Response(400, text=META_REPLY)) + + log_text = _failed_send_log(method) - log_text = "\n".join(captured) assert "400" in log_text + assert "Recipient phone number not in allowed list" in log_text + + +@pytest.mark.parametrize("deployment_type", ["local", "staging"]) +def test_request_details_are_logged_outside_production_without_the_token(monkeypatch, deployment_type): + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", deployment_type) + _meta_answers(monkeypatch, httpx.Response(400, text=META_REPLY)) + + log_text = _failed_send_log("send_message") + + assert MESSAGE_TEXT in log_text + assert BSUID in log_text + assert "Bearer ***" in log_text + assert get_settings().META_ACCESS_TOKEN_FROM_SYS_USER.get_secret_value() not in log_text + + +@pytest.mark.parametrize("method", ["send_message", "send_typing_indicator"]) +def test_production_never_logs_the_request_we_sent(monkeypatch, method): + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", "production") + _meta_answers(monkeypatch, httpx.Response(400, text=META_REPLY)) + + log_text = _failed_send_log(method) + + assert MESSAGE_TEXT not in log_text assert BSUID not in log_text - assert "is not allowed" not in log_text + assert "Bearer" not in log_text + + +def test_request_details_are_only_logged_for_a_400(monkeypatch): + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", "staging") + _meta_answers(monkeypatch, httpx.Response(403, text=META_REPLY)) + + log_text = _failed_send_log("send_message") + + assert "Recipient phone number not in allowed list" in log_text + assert MESSAGE_TEXT not in log_text + + +@pytest.mark.parametrize( + ("recipient", "expected"), + [ + (PHONE, {"to": PHONE}), + (BSUID, {"recipient_type": "individual", "recipient": BSUID}), + ], +) +def test_text_payload_addresses_phone_in_to_and_bsuid_in_recipient(monkeypatch, recipient, expected): + sent = [] + _meta_answers(monkeypatch, httpx.Response(200, json={"messages": [{"id": "wamid.X"}]}), sent) + + asyncio.run(MetaApiServiceReal().send_message(recipient, [MESSAGE_TEXT])) + + assert len(sent) == 1 + assert sent[0]["type"] == "text" + assert sent[0]["text"] == {"body": MESSAGE_TEXT} + assert {k: v for k, v in sent[0].items() if k in ("to", "recipient", "recipient_type")} == expected + + +@pytest.mark.parametrize("method", ["send_message", "send_typing_indicator"]) +def test_sender_uses_an_explicit_timeout_longer_than_httpx_default(monkeypatch, method): + seen = {} + + def fake_client(**kw): + seen.update(kw) + return _RealAsyncClient(transport=httpx.MockTransport(lambda r: httpx.Response(200, json={})), **kw) + + monkeypatch.setattr("ansari_whatsapp.services.meta_api_service_real.httpx.AsyncClient", fake_client) + service = MetaApiServiceReal() + + if method == "send_message": + asyncio.run(service.send_message(PHONE, [MESSAGE_TEXT])) + else: + asyncio.run(service.send_typing_indicator(PHONE, "wamid.T")) + + assert seen["timeout"].read == 20.0 + assert seen["timeout"].connect == 10.0 diff --git a/legacy/whatsapp/tests/test_thread_lifecycle.py b/legacy/whatsapp/tests/test_thread_lifecycle.py index ce7edf2d..ce93acc2 100644 --- a/legacy/whatsapp/tests/test_thread_lifecycle.py +++ b/legacy/whatsapp/tests/test_thread_lifecycle.py @@ -194,7 +194,7 @@ def test_creation_response_without_a_thread_id_is_a_failure_the_user_hears_about async def no_id(self, token, title): return {} - async def spy_send(self, msg_body, recipient_bsuid=None): + async def spy_send(self, msg_body, recipient_bsuid_or_phone=None): sent.append(msg_body) monkeypatch.setattr(AnsariClientMock, "create_thread", no_id) @@ -215,7 +215,7 @@ def sentry_calls(monkeypatch): def _silence_user_messages(monkeypatch): - async def ignore(self, msg_body, recipient_bsuid=None): + async def ignore(self, msg_body, recipient_bsuid_or_phone=None): return None monkeypatch.setattr(WhatsAppConversationManager, "send_whatsapp_message", ignore) @@ -298,7 +298,7 @@ async def failing_delete(self, token, thread_id): sent = [] - async def spy_send(self, msg_body, recipient_bsuid=None): + async def spy_send(self, msg_body, recipient_bsuid_or_phone=None): sent.append(msg_body) monkeypatch.setattr(AnsariClientMock, "delete_thread", failing_delete) From 2be8230ac1b16213db4f7561424c2c42cff27581 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Sun, 1 Nov 2026 13:09:39 +0200 Subject: [PATCH 006/435] [Spec 321] Address #339 review: mask Meta error logs, META_REPLY_BY_PHONE (off by default, refused in production), 429-after-401 notice, 15 min fallback, rename recipient param, script token in header --- codev/resources/arch.md | 2 +- .../321-rfc-whatsapp-support-in-the-mo.md | 4 +- legacy/whatsapp/.env.example | 6 +- legacy/whatsapp/README.md | 15 +- .../scripts/check_meta_subscriptions.py | 21 ++- .../services/auth_client_real.py | 4 +- .../services/meta_api_service_base.py | 8 +- .../services/meta_api_service_mock.py | 8 +- .../services/meta_api_service_real.py | 98 +++++++--- .../services/whatsapp_conversation_manager.py | 25 +-- .../src/ansari_whatsapp/utils/config.py | 10 + .../src/ansari_whatsapp/utils/log_masking.py | 30 +++ .../utils/whatsapp_webhook_utils.py | 23 +-- legacy/whatsapp/tests/test_auth_statuses.py | 28 ++- legacy/whatsapp/tests/test_bsuid_auth_flow.py | 107 +++++++++-- .../tests/test_environment_behaviour.py | 4 +- .../tests/test_meta_sender_logging.py | 172 ++++++++++++++++-- 17 files changed, 448 insertions(+), 117 deletions(-) create mode 100644 legacy/whatsapp/src/ansari_whatsapp/utils/log_masking.py diff --git a/codev/resources/arch.md b/codev/resources/arch.md index fd0cbcbc..db8dd95b 100644 --- a/codev/resources/arch.md +++ b/codev/resources/arch.md @@ -64,7 +64,7 @@ The repo is a pnpm workspace of `apps/*` and `packages/*`, driven by Turborepo. **The frontend app (`apps/frontend`, since #262).** The former SDK 54 prototype (outside the workspace until #262) is now the workspace member `ansari-frontend`, on Expo SDK 57 / RN 0.86 / React 19.2, with a vitest suite that CI runs in the `frontend` job (job name frozen). Its store identity is the **legacy app's** (`legacy/frontend-app/app.json`): name "Ansari", slug `ansari-chat`, `chat.ansari.app`, EAS project `e2f465a7-…`, **scheme `ansarichat`**. That scheme is coupled to `packages/auth`'s Better Auth `trustedOrigins` (`'ansarichat://'`); change both together, or native sign-in fails origin validation later with nothing failing at build time. `auth.http.test.ts` pins the pair: it reads `apps/frontend/app.json` and asserts `${expo.scheme}://` is trusted, and it rejects the old `askansari://`. `packages/auth/turbo.json` declares that manifest as a `test` input (`$TURBO_ROOT$/apps/frontend/app.json`), because a file outside the package is not hashed by default and a warm cache would replay the guard instead of running it. The app's whole env surface is `EXPO_PUBLIC_API_URL` (default api-staging), the only ARG in `Dockerfile.web`. Uniwind is installed and wired (metro `withUniwindConfig`, `src/global.css`, `gen:types`) but **unused**: the UI is StyleSheet-only, and `app/_layout.tsx` deliberately does not import `global.css` because Tailwind's preflight reset would restyle the web. `vendor/api-client-react/` keeps only `custom-fetch.ts` (the fetch runtime) and `generated/api.schemas.ts` (types); retiring both is #264. -**The WhatsApp service (`legacy/whatsapp`, spec 321).** A Python (uv, FastAPI) service outside the pnpm/turbo graph, with its own CI job (`whatsapp`) and its own Dockerfile built from the repo root (`-f legacy/whatsapp/Dockerfile .`). It identifies a user by BSUID only (`from_user_id`; it never reads or forwards the phone number), asks apps/auth for a JWT (`POST /api/whatsapp/session`, header `Authorization: Bearer `, body `{bsuid}`, per issue #329: the route does not exist yet, so sign-in is mocked in practice; the token is cached per BSUID for 14 minutes; each refusal is typed: 401 is our key (Sentry `auth_key_rejected`), 403 a banned user, 429 a spent per-user budget with a local cool-down, 500 an outage, none retried per message; one re-exchange and one retry on an apps/api 401). Sign-in runs in the background task, after Meta has its 200, so a slow apps/auth cannot cause a redelivery. It refuses to start without `META_ANSARI_APP_SECRET`, or with any `MOCK_*` switch outside `DEPLOYMENT_TYPE=local`. It then calls apps/api with that JWT: `GET/POST/DELETE /api/v2/threads` and the SSE `POST /api/v2/threads/{id}/chat`. Each user has one thread (`source: whatsapp`), deleted and recreated after `WHATSAPP_CHAT_RETENTION_HOURS` (3) of silence; a race between two first messages can create two (accepted, swept by hand). It logs one JSON line per entry on stdout with only `request_id` (Railway indexes `@request_id:`), and never logs phone numbers, BSUIDs, message text or the webhook verify token. It reads `PORT` (default 8001) and its Railway settings are recorded in `legacy/whatsapp/railway.toml` (not read by Railway). Its environments share a Meta setup: each environment needs its own Meta app credentials, and the staging `!d ` prefix keeps a developer's local messages from being answered by staging. +**The WhatsApp service (`legacy/whatsapp`, spec 321).** A Python (uv, FastAPI) service outside the pnpm/turbo graph, with its own CI job (`whatsapp`) and its own Dockerfile built from the repo root (`-f legacy/whatsapp/Dockerfile .`). It identifies a user by BSUID only (`from_user_id`; it never forwards, stores or logs the phone number; it reads it only when the off-by-default `META_REPLY_BY_PHONE` setting is on, only to address a reply to a Meta test number, and the service refuses to start with it in production), asks apps/auth for a JWT (`POST /api/whatsapp/session`, header `Authorization: Bearer `, body `{bsuid}`, per issue #329: the route does not exist yet, so sign-in is mocked in practice; the token is cached per BSUID for 14 minutes; each refusal is typed: 401 is our key (Sentry `auth_key_rejected`), 403 a banned user, 429 a spent per-user budget with a local cool-down, 500 an outage, none retried per message; one re-exchange and one retry on an apps/api 401). Sign-in runs in the background task, after Meta has its 200, so a slow apps/auth cannot cause a redelivery. It refuses to start without `META_ANSARI_APP_SECRET`, or with any `MOCK_*` switch outside `DEPLOYMENT_TYPE=local`. It then calls apps/api with that JWT: `GET/POST/DELETE /api/v2/threads` and the SSE `POST /api/v2/threads/{id}/chat`. Each user has one thread (`source: whatsapp`), deleted and recreated after `WHATSAPP_CHAT_RETENTION_HOURS` (3) of silence; a race between two first messages can create two (accepted, swept by hand). It logs one JSON line per entry on stdout with only `request_id` (Railway indexes `@request_id:`), and never logs phone numbers, BSUIDs, message text or the webhook verify token. It reads `PORT` (default 8001) and its Railway settings are recorded in `legacy/whatsapp/railway.toml` (not read by Railway). Its environments share a Meta setup: each environment needs its own Meta app credentials, and the staging `!d ` prefix keeps a developer's local messages from being answered by staging. **Health endpoint.** `/api/health` returns `service: 'ansari-backend'` — a pinned public contract (spec 3), unrelated to the `apps/api` directory name. It performs a live DB ping with a 2s cap, so a cold process can legitimately 503 on its first request. diff --git a/codev/specs/321-rfc-whatsapp-support-in-the-mo.md b/codev/specs/321-rfc-whatsapp-support-in-the-mo.md index 623053c1..fcb6265e 100644 --- a/codev/specs/321-rfc-whatsapp-support-in-the-mo.md +++ b/codev/specs/321-rfc-whatsapp-support-in-the-mo.md @@ -26,7 +26,7 @@ Affected: all WhatsApp users who currently cannot use Ansari on WhatsApp at all; ## Desired State - WhatsApp is served from this monorepo by a separate WhatsApp service that talks to `apps/api` over HTTP. It begins as the existing Python service, imported as is as much as possible. -- Every WhatsApp user, including phone-hidden users, gets answers. Users are recognised by BSUID only; the phone number is never sent to or stored in this app. +- Every WhatsApp user, including phone-hidden users, gets answers. Users are recognised by BSUID only; the phone number is never sent to or stored in this app (the only use is the off-by-default `META_REPLY_BY_PHONE` setting, refused in production, which addresses replies to a Meta test number). - The WhatsApp service exchanges the user's BSUID for a JWT through a new `/whatsapp` endpoint in `apps/auth`, then calls `apps/api` with the message text and that JWT. `apps/api` identifies the user by the GUID in the JWT, exactly as for other users. - This app stores only the user's GUID and settings (in the existing `preferences` table), not the BSUID or phone number. - Each WhatsApp user has exactly one thread, the current conversation. When a message arrives after the expiry time (3 hours, global), the old thread and its messages are deleted and a new thread starts. @@ -129,7 +129,7 @@ Recommended: Approach 1. ## Test Scenarios - Phone-visible user sends text: registered via token exchange, answered. -- Phone-hidden user sends text: answered; no phone number in any outgoing call or log. +- Phone-hidden user sends text: answered; no phone number in any outgoing call or log; with `META_REPLY_BY_PHONE` on (never in production) the phone is read only to address the reply, and is still not logged or sent to `apps/auth` or `apps/api`. - Two consecutive messages within 3 hours: same user, same thread, context retained. - Message after 3 hours: old thread and messages deleted, new thread created. - Same user with a new BSUID: treated as a new user. diff --git a/legacy/whatsapp/.env.example b/legacy/whatsapp/.env.example index 884fbbdc..4ae487c3 100644 --- a/legacy/whatsapp/.env.example +++ b/legacy/whatsapp/.env.example @@ -220,4 +220,8 @@ MOCK_AUTH_CLIENT="False" # - Avoiding Meta API quota consumption during development # - Debugging issues without affecting real WhatsApp users # When False (default), real HTTP calls are made to Meta WhatsApp Cloud API -MOCK_META_API="False" \ No newline at end of file +MOCK_META_API="False" + +# Address replies to the sender's phone number instead of the BSUID. Only for a Meta test number, which cannot +# message BSUIDs. The service refuses to start with this set when DEPLOYMENT_TYPE=production. +META_REPLY_BY_PHONE="False" \ No newline at end of file diff --git a/legacy/whatsapp/README.md b/legacy/whatsapp/README.md index 4bf911e0..bb8c479a 100644 --- a/legacy/whatsapp/README.md +++ b/legacy/whatsapp/README.md @@ -5,22 +5,22 @@ The WhatsApp front door for Ansari. It receives webhooks from Meta, signs the us ## How a message flows 1. Meta posts a webhook to `POST /whatsapp/v2`. The `X-Hub-Signature-256` header is checked against `META_ANSARI_APP_SECRET`, which has no default: the service will not start without it. Meta gets its 200 reply straight away; everything below runs in the background. -2. The user is identified by their BSUID (Meta's per-user id), read from `from_user_id`. The phone number is never read, stored, logged or sent on. +2. The user is identified by their BSUID (Meta's per-user id), read from `from_user_id`. The phone number is never stored, logged, or sent to `apps/auth` or `apps/api`. It is read from the webhook only when `META_REPLY_BY_PHONE` is on (off by default, refused in production), and only to address the reply. 3. `apps/auth` (`POST /api/whatsapp/session`, header `Authorization: Bearer `, body `{bsuid}`) returns a token for that user (contract: issue #329). The token is reused for the same user for 14 minutes, a little under its 15-minute life. 4. The service finds the user's newest thread in `apps/api` (`GET /api/v2/threads`). If it is older than `WHATSAPP_CHAT_RETENTION_HOURS` it is deleted and a new one is created (`source: "whatsapp"`). 5. The message goes to `POST /api/v2/threads/{id}/chat`. The server-sent-event stream is collected and the answer is sent back to the user's BSUID, split to fit WhatsApp's 4,000-character limit. If sign-in fails, the user is told, and Meta still gets its 200, because sign-in runs after the reply. What the user is told and what reaches Sentry depend on why it failed: -| pps/auth answered | Meaning | User is told | Sentry error_type | +| apps/auth answered | Meaning | User is told | Sentry error_type | |---|---|---|---| -| 400 | Our request was malformed (a bug here) | Sign-in failed | uth_bad_request | -| 401 | Our API key is bad: needs an operator | Sign-in failed | uth_key_rejected | +| 400 | Our request was malformed (a bug here) | Sign-in failed | auth_bad_request | +| 401 | Our API key is bad: needs an operator | Sign-in failed | auth_key_rejected | | 403 | The user is banned | The account cannot be answered | none (log only) | | 429 | The user's budget is spent (6 per 15 minutes) | To wait about X-Retry-After | none (log only); the user is not asked again until it ends | -| 500 or no answer | An outage, or a fault for this one user | Sign-in failed | uth_token_failure | +| 500 or no answer | An outage, or a fault for this one user | Sign-in failed | auth_token_failure | -None of these is retried per message. If pps/api itself answers 401 to a cached token (the session ended after the token was signed, for example a ban), the service drops that token, exchanges once more and retries the message once; a second 401 gives up with pi_unauthorized_after_reexchange. +None of these is retried per message. If apps/api itself answers 401 to a cached token (the session ended after the token was signed, for example a ban), the service drops that token, exchanges once more and retries the message once; a second 401 gives up with api_unauthorized_after_reexchange. ## Layout @@ -80,6 +80,7 @@ Staging shares the same test number, so start every message you send while testi | `META_ACCESS_TOKEN_FROM_SYS_USER` | Meta API token (belongs to one Meta app) | | `META_ANSARI_APP_SECRET` | Verifies webhook signatures (must be the same app as the token) | | `META_WEBHOOK_VERIFY_TOKEN` | One-time webhook URL verification | +| `META_REPLY_BY_PHONE` | Default `False`. When `True`, replies are addressed to the sender's phone number instead of the BSUID, for a Meta test number that cannot message BSUIDs. The service refuses to start with it if `DEPLOYMENT_TYPE=production` | | `WA_MAINTENANCE_MODE` | See above | | `WHATSAPP_CHAT_RETENTION_HOURS` | How long a conversation continues before a fresh thread (default 3) | | `SENTRY_DSN` | Empty disables Sentry | @@ -108,7 +109,7 @@ In Railway's log search: - one request: `@request_id:` (the id is also returned in the `X-Request-ID` response header) - all errors: `@level:error` -Logs deliberately contain no phone numbers, BSUIDs or message text. Railway caps logging at 500 lines per second per replica, and retention depends on the plan. +Outside `DEPLOYMENT_TYPE=local`, logs contain no phone numbers, BSUIDs or message text; text copied from Meta's error replies is masked, and production logs no request details at all. `local` logs the full request body for debugging, never the access token. Railway caps logging at 500 lines per second per replica, and retention depends on the plan. ## Deploying (Railway) diff --git a/legacy/whatsapp/scripts/check_meta_subscriptions.py b/legacy/whatsapp/scripts/check_meta_subscriptions.py index 1d57560d..eb1dbb01 100644 --- a/legacy/whatsapp/scripts/check_meta_subscriptions.py +++ b/legacy/whatsapp/scripts/check_meta_subscriptions.py @@ -17,6 +17,7 @@ - Unsubscribe WABA from app """ +import getpass import os import requests from dotenv import load_dotenv @@ -77,13 +78,13 @@ def debug_access_token(): print("=" * 60) url = f"https://graph.facebook.com/{META_API_VERSION}/debug_token" - params = { - "input_token": ACCESS_TOKEN, - "access_token": ACCESS_TOKEN, # Can use the same token to debug itself - } + # The token that does the asking goes in the header, not the URL (URLs end up in proxy logs); it can debug itself. + # `input_token` is a GET parameter on this endpoint (a POST is refused), so the token still appears in that URL. + headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"} + params = {"input_token": ACCESS_TOKEN} try: - response = requests.get(url, params=params) + response = requests.get(url, headers=headers, params=params) response.raise_for_status() result = response.json() @@ -349,11 +350,11 @@ def unsubscribe_waba(): # Step 1: Get the current access token's app name print("\n→ Step 1: Identifying your access token's app...") token_debug_url = f"https://graph.facebook.com/{META_API_VERSION}/debug_token" - token_params = {"input_token": ACCESS_TOKEN, "access_token": ACCESS_TOKEN} + token_params = {"input_token": ACCESS_TOKEN} headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"} try: - token_response = requests.get(token_debug_url, params=token_params) + token_response = requests.get(token_debug_url, headers=headers, params=token_params) token_response.raise_for_status() token_data = token_response.json() @@ -615,9 +616,9 @@ def get_current_context(): # Get App name from token try: token_debug_url = f"https://graph.facebook.com/{META_API_VERSION}/debug_token" - token_params = {"input_token": ACCESS_TOKEN, "access_token": ACCESS_TOKEN} + token_params = {"input_token": ACCESS_TOKEN} - token_response = requests.get(token_debug_url, params=token_params) + token_response = requests.get(token_debug_url, headers=headers, params=token_params) if token_response.status_code == 200: token_data = token_response.json() if "data" in token_data: @@ -695,7 +696,7 @@ def main(): print(" 3. Select your app and required permissions") print(" 4. Copy the generated token") - ACCESS_TOKEN = input("\n Enter your META_ACCESS_TOKEN_FROM_SYS_USER: ").strip() + ACCESS_TOKEN = getpass.getpass("\n Enter your META_ACCESS_TOKEN_FROM_SYS_USER (typing is hidden): ").strip() if not ACCESS_TOKEN: print("\n ERROR: Access token is required. Exiting...") diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_real.py b/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_real.py index 16d9d579..c697386d 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_real.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/auth_client_real.py @@ -26,8 +26,8 @@ TOKEN_CACHE_SECONDS = 14 * 60 TOKEN_CACHE_MAX_ENTRIES = 10_000 -# Used when a 429 carries no usable X-Retry-After; apps/auth's per-user window is 15 minutes -DEFAULT_RETRY_AFTER_SECONDS = 60 +# Used when a 429 carries no usable X-Retry-After: assume the user's whole 15-minute window in apps/auth +DEFAULT_RETRY_AFTER_SECONDS = 15 * 60 class AuthClientReal(AuthClientBase): diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_base.py b/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_base.py index 481a7c52..6b6ef76b 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_base.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_base.py @@ -12,11 +12,11 @@ class MetaApiServiceBase(ABC): """ @abstractmethod - async def send_typing_indicator(self, recipient_phone: str, message_id: str) -> None: + async def send_typing_indicator(self, recipient_bsuid_or_phone: str, message_id: str) -> None: """Send typing indicator to WhatsApp recipient. Args: - recipient_phone (str): WhatsApp phone number of recipient + recipient_bsuid_or_phone (str): BSUID or phone number of the recipient message_id (str): Message ID for the typing indicator Raises: @@ -25,11 +25,11 @@ async def send_typing_indicator(self, recipient_phone: str, message_id: str) -> pass @abstractmethod - async def send_message(self, recipient_phone: str, message_parts: list[str]) -> None: + async def send_message(self, recipient_bsuid_or_phone: str, message_parts: list[str]) -> None: """Send WhatsApp message(s) to recipient. Args: - recipient_phone (str): WhatsApp phone number of recipient + recipient_bsuid_or_phone (str): BSUID or phone number of the recipient message_parts (list[str]): List of message parts (already split by length) Raises: diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_mock.py b/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_mock.py index dd508ba1..bad8d845 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_mock.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_mock.py @@ -15,21 +15,21 @@ def __init__(self): """Initialize mock Meta API service.""" logger.info("Initialized MetaApiServiceMock - Meta API calls will be simulated") - async def send_typing_indicator(self, recipient_phone: str, message_id: str) -> None: + async def send_typing_indicator(self, recipient_bsuid_or_phone: str, message_id: str) -> None: """Simulate sending typing indicator. Args: - recipient_phone: WhatsApp phone number of recipient + recipient_bsuid_or_phone: BSUID or phone number of the recipient message_id: Message ID for the typing indicator """ logger.info(f"[MOCK META API] Typing indicator simulated (msg_id: {message_id})") await asyncio.sleep(0.05) # Simulate minimal network delay - async def send_message(self, recipient_phone: str, message_parts: list[str]) -> None: + async def send_message(self, recipient_bsuid_or_phone: str, message_parts: list[str]) -> None: """Simulate sending WhatsApp message. Args: - recipient_phone: WhatsApp phone number of recipient + recipient_bsuid_or_phone: BSUID or phone number of the recipient message_parts: List of message parts (already split by length) """ logger.info(f"[MOCK META API] Sending {len(message_parts)} message part(s)") diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_real.py b/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_real.py index 36041196..6ca57d88 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_real.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/meta_api_service_real.py @@ -1,6 +1,8 @@ # Real Meta WhatsApp API service implementation """Real client implementation for Meta WhatsApp API via HTTP.""" +import json + import httpx import sentry_sdk @@ -8,12 +10,46 @@ from ansari_whatsapp.utils.app_logger import request_id_var from ansari_whatsapp.utils.config import get_settings +from ansari_whatsapp.utils.log_masking import mask_identifiers, redact_values from ansari_whatsapp.services.meta_api_service_base import MetaApiServiceBase # Why longer timeout? As Meta can take over 5 s (httpx's default) to answer a send-message request from us. REQUEST_TIMEOUT = httpx.Timeout(20.0, connect=10.0) +# String values of a send payload that describe its shape and name nobody (the rest is masked outside local) +_SAFE_REQUEST_KEYS = {"messaging_product", "type", "recipient_type", "status"} + + +def _meta_error_summary(response: httpx.Response) -> str: + """The structured part of Meta's error reply, with anything shaped like an identifier masked. + + Meta documents the error object as `code`, `type`, `error_subcode`, `fbtrace_id`, `message` (the code and its + title) and `error_data.details`, but not that none of them can name the recipient, so the two texts are masked. + https://developers.facebook.com/documentation/business-messaging/whatsapp/support/error-codes + """ + try: + body = response.json() + except ValueError: + body = None + error = body.get("error") if isinstance(body, dict) else None + if not isinstance(error, dict): + return f"no standard error object ({len(response.content)} bytes)" + error_data = error.get("error_data") if isinstance(error.get("error_data"), dict) else {} + + def number(value): + return value if isinstance(value, int) and not isinstance(value, bool) else None + + fields = { + "code": number(error.get("code")), + "error_subcode": number(error.get("error_subcode")), + "type": mask_identifiers(str(error.get("type") or "")[:64]), + "fbtrace_id": mask_identifiers(str(error.get("fbtrace_id") or "")[:64]), + "message": mask_identifiers(str(error.get("message") or "")[:300]), + "details": mask_identifiers(str(error_data.get("details") or "")[:300]), + } + return " ".join(f"{name}={value!r}" for name, value in fields.items() if value not in (None, "")) + class MetaApiServiceReal(MetaApiServiceBase): """Real Meta WhatsApp API service that makes actual HTTP requests.""" @@ -36,30 +72,48 @@ def _get_headers(self) -> dict: } @staticmethod - def _log_bad_request_details(error: httpx.HTTPStatusError) -> None: - """Always log Meta's reply; log the request we sent too, but only for a 400 outside production.""" - logger.error(f"Meta's reply ({error.response.status_code}): {error.response.text}") - if error.response.status_code != 400 or get_settings().DEPLOYMENT_TYPE == "production": + def _log_meta_error(error: httpx.HTTPStatusError) -> None: + """Log what Meta said, and for a 400 what we sent. + + Meta's raw body is never logged, only its structured fields with identifiers masked. For a 400 the payload's + keys are logged everywhere; their values too, masked on staging and development and unmasked only on local. + """ + logger.error(f"Meta's reply ({error.response.status_code}): {_meta_error_summary(error.response)}") + if error.response.status_code != 400: + return + try: + sent = json.loads(error.request.content) + except ValueError: + logger.error("Meta rejected the request (400); the request body was not JSON") + return + if not isinstance(sent, dict): + logger.error("Meta rejected the request (400); the request body was not a JSON object") return - headers = {k: ("Bearer ***" if k.lower() == "authorization" else v) for k, v in error.request.headers.items()} - logger.error( - f"Meta rejected the request (400). URL: {error.request.url} | Headers: {headers} | " - f"Body: {error.request.content.decode('utf-8', errors='replace')}" - ) - async def send_typing_indicator(self, recipient_phone: str, message_id: str) -> None: + deployment = get_settings().DEPLOYMENT_TYPE + line = f"Meta rejected the request (400). URL: {error.request.url} | Payload keys: {sorted(sent)}" + if deployment != "production": + headers = {k: ("Bearer ***" if k.lower() == "authorization" else v) for k, v in error.request.headers.items()} + line += f" | Headers: {headers}" + if deployment == "local": + line += f" | Body: {json.dumps(sent, ensure_ascii=False)}" + else: + line += f" | Body with values masked: {redact_values(sent, _SAFE_REQUEST_KEYS)}" + logger.error(line) + + async def send_typing_indicator(self, recipient_bsuid_or_phone: str, message_id: str) -> None: """Send typing indicator via Meta API. Args: - recipient_phone: WhatsApp phone number of recipient + recipient_bsuid_or_phone: Who the typing indicator is for (not sent: Meta ties it to `message_id`) message_id: Message ID for the typing indicator Raises: httpx.HTTPStatusError: If Meta API returns error status httpx.RequestError: If network error occurs """ - if not recipient_phone or not message_id: - logger.error("Cannot send typing indicator: missing recipient_phone or message_id") + if not recipient_bsuid_or_phone or not message_id: + logger.error("Cannot send typing indicator: missing recipient_bsuid_or_phone or message_id") return json_data = { @@ -79,7 +133,7 @@ async def send_typing_indicator(self, recipient_phone: str, message_id: str) -> except httpx.HTTPStatusError as e: logger.error(f"HTTP error sending typing indicator: {e.response.status_code}") - self._log_bad_request_details(e) + self._log_meta_error(e) # Only capture 5xx errors (Meta's fault, not ours) if e.response.status_code >= 500: sentry_sdk.set_tag("error_type", "meta_api_failure") @@ -100,12 +154,12 @@ async def send_typing_indicator(self, recipient_phone: str, message_id: str) -> logger.exception(f"Unexpected error sending typing indicator: {e}") raise - async def send_message(self, recipient_phone: str, message_parts: list[str]) -> None: + async def send_message(self, recipient_bsuid_or_phone: str, message_parts: list[str]) -> None: """Send WhatsApp message(s) via Meta API. Args: - recipient_phone: WhatsApp phone number of recipient, or a business-scoped user ID (BSUID, - e.g., "US.13491208655302741918") if the user's phone number is hidden + recipient_bsuid_or_phone: A phone number (digits only, sent as `to`) or a business-scoped user ID + (BSUID, e.g., "US.13491208655302741918", sent as `recipient`) message_parts: List of message parts (already split by length) Raises: @@ -118,7 +172,7 @@ async def send_message(self, recipient_phone: str, message_parts: list[str]) -> since July 2026. https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids#send-message-requests """ - if not recipient_phone: + if not recipient_bsuid_or_phone: logger.error("Cannot send message: No recipient") return @@ -136,12 +190,12 @@ async def send_message(self, recipient_phone: str, message_parts: list[str]) -> "type": "text", "text": {"body": part}, } - if recipient_phone.isdigit(): - json_data["to"] = recipient_phone + if recipient_bsuid_or_phone.isdigit(): + json_data["to"] = recipient_bsuid_or_phone else: # Not a phone number, so it's a business-scoped user ID (e.g., US.1349...) json_data["recipient_type"] = "individual" - json_data["recipient"] = recipient_phone + json_data["recipient"] = recipient_bsuid_or_phone response = await client.post(self.api_url, headers=self._get_headers(), json=json_data) response.raise_for_status() @@ -156,7 +210,7 @@ async def send_message(self, recipient_phone: str, message_parts: list[str]) -> except httpx.HTTPStatusError as e: logger.error(f"HTTP error sending message: {e.response.status_code}") - self._log_bad_request_details(e) + self._log_meta_error(e) # Only capture 5xx errors (Meta's fault, not ours) if e.response.status_code >= 500: sentry_sdk.set_tag("error_type", "meta_api_failure") diff --git a/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py b/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py index 73499bd2..fd79c6e2 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py +++ b/legacy/whatsapp/src/ansari_whatsapp/services/whatsapp_conversation_manager.py @@ -12,7 +12,6 @@ from ansari_whatsapp.services.service_provider import get_ansari_client, get_auth_client from ansari_whatsapp.services.meta_service_provider import get_meta_api_service from ansari_whatsapp.utils.app_logger import request_id_var -from ansari_whatsapp.utils.config import get_settings from ansari_whatsapp.utils.exceptions import ( ApiUnauthorizedError, AuthBadRequestError, @@ -44,7 +43,7 @@ class WhatsAppConversationManager: This service manages the lifecycle of WhatsApp conversations, coordinating between apps/auth, apps/api and the Meta WhatsApp API to handle: - - User identification by BSUID (exchanged for a JWT; the phone number is never used) + - User identification by BSUID (exchanged for a JWT; a phone number never identifies anyone) - Message processing and response generation - Typing indicators and user experience features - Thread/conversation management @@ -67,13 +66,12 @@ def __init__( incoming_msg_body (dict, optional): The body content of the incoming message. message_id (str, optional): The ID of the incoming message. message_unix_time (int, optional): The timestamp of the incoming message in Unix format. - sender_phone (str, optional): The sender's phone number from the webhook, used only to address replies - on local and staging, where Meta's test number accepts recipients by phone number only - (i.e., doesn't accept BSUIDs). + sender_phone (str, optional): The sender's phone number, set by the webhook parser only when + META_REPLY_BY_PHONE is on (Meta's free test number cannot message a BSUID). Used only to address + the reply. """ self.bsuid = bsuid - use_phone = bool(sender_phone) and get_settings().DEPLOYMENT_TYPE in ("local", "staging") - self.reply_to = sender_phone if use_phone else bsuid + self.reply_to = sender_phone or bsuid self.token = None # The user's JWT, set by authenticate_user() self.auth_failure_notice = SIGN_IN_FAILED_NOTICE # What to tell the user if authenticate_user() fails self.incoming_msg_type = incoming_msg_type @@ -192,7 +190,7 @@ async def _send_whatsapp_typing_indicator(self) -> None: return try: - await self.meta_api_service.send_typing_indicator(recipient_phone=self.bsuid, message_id=self.message_id) + await self.meta_api_service.send_typing_indicator(recipient_bsuid_or_phone=self.bsuid, message_id=self.message_id) except Exception as e: logger.exception(f"Error sending typing indicator: {e}") @@ -206,7 +204,7 @@ async def send_whatsapp_message( Args: msg_body (str): The message body to be sent. recipient_bsuid_or_phone (str, optional): A BSUID or a phone number to send to. Defaults to - self.reply_to if not provided (i.e., the BSUID on prod, or the sender's phone on local/staging). + self.reply_to if not provided (the BSUID, or the sender's phone when META_REPLY_BY_PHONE is on). """ recipient = recipient_bsuid_or_phone or self.reply_to @@ -218,8 +216,8 @@ async def send_whatsapp_message( message_parts = split_message(msg_body) try: - # Delegate to Meta API service (its `recipient_phone` argument also accepts a BSUID) - await self.meta_api_service.send_message(recipient_phone=recipient, message_parts=message_parts) + # Delegate to Meta API service (its `recipient_bsuid_or_phone` argument also accepts a BSUID) + await self.meta_api_service.send_message(recipient_bsuid_or_phone=recipient, message_parts=message_parts) except Exception as e: logger.exception(f"Error sending WhatsApp message: {e}") @@ -344,7 +342,10 @@ async def handle_text_message(self) -> None: self.auth_client.forget(self.bsuid) if await self.authenticate_user(): continue - await self.send_whatsapp_message(self.auth_failure_notice) + # A user who sent one message must not be told they are sending too quickly, which is what + # a 429 on this second exchange would otherwise say + notice = BANNED_NOTICE if self.auth_failure_notice == BANNED_NOTICE else SIGN_IN_FAILED_NOTICE + await self.send_whatsapp_message(notice) else: logger.error("apps/api refused a freshly exchanged token; giving up") self._capture(e, "api_unauthorized_after_reexchange") diff --git a/legacy/whatsapp/src/ansari_whatsapp/utils/config.py b/legacy/whatsapp/src/ansari_whatsapp/utils/config.py index afc72cf1..6f69fad6 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/utils/config.py +++ b/legacy/whatsapp/src/ansari_whatsapp/utils/config.py @@ -61,6 +61,9 @@ class WhatsAppSettings(BaseSettings): # NOTE: We add a default value here, since we never set this in staging/production/etc. environments # I.e., this token is only used for local development with zrok (check .env.example for more details) META_WEBHOOK_ZROK_SHARE_TOKEN: SecretStr = SecretStr("your_token") + # Reply to the sender's phone number instead of their BSUID. Only for Meta's free test number, whose allowed-recipient + # list holds phone numbers, so it cannot message a BSUID (error 131030). A real number accepts BSUID replies. + META_REPLY_BY_PHONE: bool = False @property def META_API_URL(self) -> str: @@ -119,6 +122,13 @@ def refuse_mocks_outside_local(self): raise ValueError(f"{', '.join(enabled)} only allowed when DEPLOYMENT_TYPE=local (got {self.DEPLOYMENT_TYPE})") return self + @model_validator(mode="after") + def refuse_phone_replies_in_production(self): + """Production answers on a real number, which takes BSUIDs, so no phone number should be read there.""" + if self.META_REPLY_BY_PHONE and self.DEPLOYMENT_TYPE == "production": + raise ValueError("META_REPLY_BY_PHONE is not allowed when DEPLOYMENT_TYPE=production") + return self + @model_validator(mode="after") def default_logging_level(self): if not self.LOGGING_LEVEL: diff --git a/legacy/whatsapp/src/ansari_whatsapp/utils/log_masking.py b/legacy/whatsapp/src/ansari_whatsapp/utils/log_masking.py new file mode 100644 index 00000000..455f959f --- /dev/null +++ b/legacy/whatsapp/src/ansari_whatsapp/utils/log_masking.py @@ -0,0 +1,30 @@ +# Masking for values about to be logged +"""Hide phone numbers, BSUIDs and message ids in text and structures that are about to be logged.""" + +import re + +# A BSUID is a two-letter country code, a dot, then up to 128 letters or digits ("US.1349..."); a parent BSUID has +# ".ENT." after the country code. A message id is "wamid." plus base64 that carries the user's phone number. A phone +# number may contain spaces, hyphens, dots and parentheses. Meta's formats: business-scoped-user-ids and phone-numbers docs. +_MESSAGE_ID = re.compile(r"wamid\.[A-Za-z0-9+/=_-]+") +_BSUID = re.compile(r"\b[A-Z]{2}\.(?:ENT\.)?[A-Za-z0-9]{1,128}\b") +# Eight digits or more, so a 6 or 7 digit Meta error code stays readable +_PHONE = re.compile(r"[+(]?\d(?:[\s().-]{0,2}\d){7,}") + + +def mask_identifiers(text: str) -> str: + """Replace anything shaped like a message id, BSUID or phone number with a placeholder.""" + text = _MESSAGE_ID.sub("", text) + text = _BSUID.sub("", text) + return _PHONE.sub("", text) + + +def redact_values(obj, safe_keys: set[str], key: str | None = None): + """Return obj with its structure intact but every string value masked as ``, except under `safe_keys`.""" + if isinstance(obj, dict): + return {k: redact_values(v, safe_keys, k) for k, v in obj.items()} + if isinstance(obj, list): + return [redact_values(v, safe_keys, key) for v in obj] + if isinstance(obj, str) and key not in safe_keys: + return f"" + return obj diff --git a/legacy/whatsapp/src/ansari_whatsapp/utils/whatsapp_webhook_utils.py b/legacy/whatsapp/src/ansari_whatsapp/utils/whatsapp_webhook_utils.py index 2941ae7f..8a611c8e 100644 --- a/legacy/whatsapp/src/ansari_whatsapp/utils/whatsapp_webhook_utils.py +++ b/legacy/whatsapp/src/ansari_whatsapp/utils/whatsapp_webhook_utils.py @@ -15,6 +15,7 @@ from ansari_whatsapp.utils.config import get_settings from ansari_whatsapp.utils.exceptions import UnexpectedMetaPayloadError +from ansari_whatsapp.utils.log_masking import redact_values settings = get_settings() @@ -134,20 +135,15 @@ def create_response_for_meta( return JSONResponse(content=response_body, status_code=200) -# Keys whose string values are safe to log as-is (everything else is masked, e.g., phone numbers, names, text) -_UNREDACTED_KEYS = {"object", "field", "messaging_product", "type", "id", "timestamp"} +# Keys whose string values are safe to log as-is (everything else is masked, e.g., phone numbers, names, text, and +# ids: a message id is base64 that carries the sender's phone number) +_UNREDACTED_KEYS = {"object", "field", "messaging_product", "type", "timestamp"} def _redact_for_logging(obj, key: str | None = None): """Return obj with its structure intact but string values masked as ``, except for safe keys (i.e., keys in _UNREDACTED_KEYS).""" - if isinstance(obj, dict): - return {k: _redact_for_logging(v, k) for k, v in obj.items()} - if isinstance(obj, list): - return [_redact_for_logging(v, key) for v in obj] - if isinstance(obj, str) and key not in _UNREDACTED_KEYS: - return f"" - return obj + return redact_values(obj, _UNREDACTED_KEYS, key) async def parse_meta_payload( @@ -163,7 +159,8 @@ async def parse_meta_payload( tuple: A tuple of (is_status, is_target_business_number, bsuid, incoming_msg_type, incoming_msg_body, message_id, message_unix_time, sender_phone). `bsuid` is the sender's business-scoped user ID and the only identity we use. `sender_phone` is - the webhook's `from` (None when Meta omits it) and is only used to address replies on test numbers. + the webhook's `from`, read only when META_REPLY_BY_PHONE is on (None otherwise, or when Meta omits + it), and used only to address the reply. Raises: Exception: If the payload structure is invalid or unsupported. @@ -211,11 +208,11 @@ async def parse_meta_payload( incoming_msg = value["messages"][0] try: - # Extract message details. `from_user_id` (the BSUID) is always present; `from` (the phone number) may - # be missing, and is never used to identify the user. + # Extract message details. `from_user_id` (the BSUID) is always present and is the only identity used. + # `from` (the phone number) may be missing, and is read only when replies go to the phone (test numbers). message_id = incoming_msg.get("id") bsuid = incoming_msg["from_user_id"] - sender_phone = incoming_msg.get("from") + sender_phone = incoming_msg.get("from") if get_settings().META_REPLY_BY_PHONE else None message_unix_time_str = incoming_msg.get("timestamp") message_unix_time = int(message_unix_time_str) if message_unix_time_str is not None else None diff --git a/legacy/whatsapp/tests/test_auth_statuses.py b/legacy/whatsapp/tests/test_auth_statuses.py index 5d609b79..e1af3791 100644 --- a/legacy/whatsapp/tests/test_auth_statuses.py +++ b/legacy/whatsapp/tests/test_auth_statuses.py @@ -99,6 +99,10 @@ def test_a_429_without_a_usable_wait_falls_back_to_a_default(monkeypatch, header assert raised.value.retry_after == DEFAULT_RETRY_AFTER_SECONDS +def test_the_fallback_wait_is_the_users_whole_fifteen_minute_window(): + assert DEFAULT_RETRY_AFTER_SECONDS == 15 * 60 + + def test_a_user_with_a_spent_budget_is_not_asked_again_until_it_frees_up(monkeypatch): calls = [] @@ -264,9 +268,9 @@ def _spy_on_replies(monkeypatch) -> list: replies = [] original = MetaApiServiceMock.send_message - async def spy(self, recipient_phone, message_parts): + async def spy(self, recipient_bsuid_or_phone, message_parts): replies.extend(message_parts) - return await original(self, recipient_phone, message_parts) + return await original(self, recipient_bsuid_or_phone, message_parts) monkeypatch.setattr(MetaApiServiceMock, "send_message", spy) return replies @@ -347,6 +351,26 @@ async def get_token(self, bsuid): assert replies == [BANNED_NOTICE] +def test_a_429_after_an_api_401_tells_the_user_sign_in_failed_not_to_slow_down(monkeypatch): + _capturing(monkeypatch) + replies = _spy_on_replies(monkeypatch) + _api_refusing_first_tokens(monkeypatch, refused=99) + state = {"exchanges": 0} + + async def get_token(self, bsuid): + state["exchanges"] += 1 + if state["exchanges"] == 1: + return "token-1" + raise AuthRateLimitedError("429", retry_after=300) + + monkeypatch.setattr(AuthClientMock, "get_token", get_token) + + asyncio.run(_manager().sign_in_and_handle_text_message()) + + assert replies == [SIGN_IN_FAILED_NOTICE] + assert "minutes" not in replies[0] + + def test_the_stale_token_is_dropped_before_the_second_exchange(monkeypatch): _capturing(monkeypatch) _spy_on_replies(monkeypatch) diff --git a/legacy/whatsapp/tests/test_bsuid_auth_flow.py b/legacy/whatsapp/tests/test_bsuid_auth_flow.py index 405b0214..6d9428fb 100644 --- a/legacy/whatsapp/tests/test_bsuid_auth_flow.py +++ b/legacy/whatsapp/tests/test_bsuid_auth_flow.py @@ -369,49 +369,124 @@ async def spy_get_token(self, bsuid): original_send = MetaApiServiceMock.send_message - async def spy_send(self, recipient_phone, message_parts): - recipients.append(recipient_phone) - return await original_send(self, recipient_phone, message_parts) + async def spy_send(self, recipient_bsuid_or_phone, message_parts): + recipients.append(recipient_bsuid_or_phone) + return await original_send(self, recipient_bsuid_or_phone, message_parts) monkeypatch.setattr(AuthClientMock, "get_token", spy_get_token) monkeypatch.setattr(MetaApiServiceMock, "send_message", spy_send) return tokens_requested, recipients -@pytest.mark.parametrize("deployment_type", ["local", "staging"]) -def test_test_environments_reply_to_the_phone_but_identify_by_bsuid(monkeypatch, deployment_type): - monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", deployment_type) +def test_the_phone_is_not_read_or_used_by_default(monkeypatch): + + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", "staging") + tokens_requested, recipients = _spy_identity_and_reply_target(monkeypatch) response = _post_signed_webhook(_text_message(**{"from": PHONE, "from_user_id": BSUID})) assert response.status_code == 200 + assert tokens_requested == [BSUID] - assert recipients and set(recipients) == {PHONE} + assert recipients and set(recipients) == {BSUID} + + +@pytest.mark.parametrize("deployment_type", ["local", "development", "staging"]) +def test_reply_by_phone_addresses_the_reply_to_the_phone_and_still_identifies_by_bsuid(monkeypatch, deployment_type): + + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", deployment_type) + + monkeypatch.setattr(get_settings(), "META_REPLY_BY_PHONE", True) -def test_production_replies_to_the_bsuid_even_when_the_phone_is_visible(monkeypatch): - monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", "production") tokens_requested, recipients = _spy_identity_and_reply_target(monkeypatch) response = _post_signed_webhook(_text_message(**{"from": PHONE, "from_user_id": BSUID})) assert response.status_code == 200 + assert tokens_requested == [BSUID] - assert recipients and set(recipients) == {BSUID} - assert PHONE not in tokens_requested + recipients + assert recipients and set(recipients) == {PHONE} + + +def test_reply_by_phone_falls_back_to_the_bsuid_when_the_phone_is_hidden(monkeypatch): + + monkeypatch.setattr(get_settings(), "META_REPLY_BY_PHONE", True) -def test_test_environment_falls_back_to_the_bsuid_when_the_phone_is_hidden(monkeypatch): - monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", "staging") _, recipients = _spy_identity_and_reply_target(monkeypatch) response = _post_signed_webhook(_text_message(from_user_id=BSUID)) assert response.status_code == 200 + assert recipients and set(recipients) == {BSUID} +def test_the_phone_never_reaches_apps_auth_even_with_reply_by_phone(monkeypatch): + + monkeypatch.setattr(get_settings(), "META_REPLY_BY_PHONE", True) + + monkeypatch.setattr(get_settings(), "MOCK_AUTH_CLIENT", False) + + sent_to_auth = [] + + def handler(request: httpx.Request) -> httpx.Response: + + sent_to_auth.append(f"{request.url} {dict(request.headers)} {request.content.decode()}") + + return httpx.Response(200, json={"token": "jwt"}) + + _use_transport(monkeypatch, "ansari_whatsapp.services.auth_client_real", handler) + + response = _post_signed_webhook(_text_message(**{"from": PHONE, "from_user_id": BSUID})) + + assert response.status_code == 200 + + assert sent_to_auth and not any(PHONE in r for r in sent_to_auth) + + +def test_reply_by_phone_is_refused_in_production(monkeypatch): + + from ansari_whatsapp.utils.config import WhatsAppSettings + + monkeypatch.setenv("DEPLOYMENT_TYPE", "production") + + monkeypatch.setenv("META_REPLY_BY_PHONE", "True") + + for flag in ("MOCK_ANSARI_CLIENT", "MOCK_AUTH_CLIENT", "MOCK_META_API"): + monkeypatch.setenv(flag, "False") + + get_settings.cache_clear() + + try: + with pytest.raises(ValueError, match="META_REPLY_BY_PHONE"): + WhatsAppSettings() + + finally: + monkeypatch.undo() + + get_settings.cache_clear() + + +def test_reply_by_phone_defaults_to_off(monkeypatch): + + from ansari_whatsapp.utils.config import WhatsAppSettings + + monkeypatch.delenv("META_REPLY_BY_PHONE", raising=False) + + get_settings.cache_clear() + + try: + assert WhatsAppSettings().META_REPLY_BY_PHONE is False + + finally: + monkeypatch.undo() + + get_settings.cache_clear() + + def test_no_phone_number_reaches_apps_api(monkeypatch): requests = [] @@ -448,10 +523,10 @@ def test_token_exchange_failure_notifies_user_and_is_reported(monkeypatch): async def failing_get_token(self, bsuid): raise AuthTokenError("apps/auth is down") - async def spy_send(self, recipient_phone, message_parts): - recipients.append(recipient_phone) + async def spy_send(self, recipient_bsuid_or_phone, message_parts): + recipients.append(recipient_bsuid_or_phone) sent.extend(message_parts) - return await original_send(self, recipient_phone, message_parts) + return await original_send(self, recipient_bsuid_or_phone, message_parts) monkeypatch.setattr(AuthClientMock, "get_token", failing_get_token) monkeypatch.setattr(MetaApiServiceMock, "send_message", spy_send) diff --git a/legacy/whatsapp/tests/test_environment_behaviour.py b/legacy/whatsapp/tests/test_environment_behaviour.py index cd90aa68..9b3188e1 100644 --- a/legacy/whatsapp/tests/test_environment_behaviour.py +++ b/legacy/whatsapp/tests/test_environment_behaviour.py @@ -68,9 +68,9 @@ def _spy_on_replies(monkeypatch) -> list: replies = [] original = MetaApiServiceMock.send_message - async def spy(self, recipient_phone, message_parts): + async def spy(self, recipient_bsuid_or_phone, message_parts): replies.extend(message_parts) - return await original(self, recipient_phone, message_parts) + return await original(self, recipient_bsuid_or_phone, message_parts) monkeypatch.setattr(MetaApiServiceMock, "send_message", spy) return replies diff --git a/legacy/whatsapp/tests/test_meta_sender_logging.py b/legacy/whatsapp/tests/test_meta_sender_logging.py index f8d8686d..276278a6 100644 --- a/legacy/whatsapp/tests/test_meta_sender_logging.py +++ b/legacy/whatsapp/tests/test_meta_sender_logging.py @@ -1,4 +1,5 @@ -"""The Meta sender always logs Meta's error reply, and the request we sent only outside production.""" +"""The Meta sender logs Meta's error as structured, masked fields, and never a phone number, BSUID or message text +outside local (spec 321, follow-up #339 review).""" import asyncio import json @@ -9,11 +10,39 @@ from ansari_whatsapp.services.meta_api_service_real import MetaApiServiceReal from ansari_whatsapp.utils.config import get_settings +from ansari_whatsapp.utils.log_masking import mask_identifiers BSUID = "US.13491208655302741918" PHONE = "201234567899" MESSAGE_TEXT = "a-very-distinctive-reply-text" -META_REPLY = '{"error":{"message":"(#131030) Recipient phone number not in allowed list","code":131030}}' +TRACE_ID = "Axly7O1UTgCLGu6n8EXWWTD" +# What Meta sent for a recipient who was not on the test number's list +META_REPLY = json.dumps( + { + "error": { + "message": "(#131030) Recipient phone number not in allowed list", + "type": "OAuthException", + "code": 131030, + "error_data": { + "messaging_product": "whatsapp", + "details": "Recipient phone number not in allowed list: Add recipient phone number to recipient list.", + }, + "fbtrace_id": TRACE_ID, + } + } +) +# A reply that echoes the recipient, which Meta's docs do not rule out +ECHOING_REPLY = json.dumps( + { + "error": { + "message": f"(#131030) Recipient {PHONE} is not allowed", + "type": "OAuthException", + "code": 131030, + "error_data": {"messaging_product": "whatsapp", "details": f"Cannot send to +{PHONE} or {BSUID}"}, + "fbtrace_id": TRACE_ID, + } + } +) _RealAsyncClient = httpx.AsyncClient @@ -30,66 +59,149 @@ def handler(request: httpx.Request) -> httpx.Response: ) -def _failed_send_log(method: str) -> str: +def _failed_send_log(method: str, recipient: str = BSUID) -> str: service = MetaApiServiceReal() captured = [] sink_id = logger.add(lambda m: captured.append(str(m)), level="DEBUG") try: with pytest.raises(httpx.HTTPStatusError): if method == "send_message": - asyncio.run(service.send_message(BSUID, [MESSAGE_TEXT])) + asyncio.run(service.send_message(recipient, [MESSAGE_TEXT])) else: - asyncio.run(service.send_typing_indicator(BSUID, "wamid.T")) + asyncio.run(service.send_typing_indicator(recipient, "wamid.HBgLMTY1MDM4Nzk0MzkVAgARGBI1RjQy")) finally: logger.remove(sink_id) return "\n".join(captured) -@pytest.mark.parametrize("deployment_type", ["local", "staging", "production"]) +@pytest.mark.parametrize("deployment_type", ["local", "staging", "development", "production"]) @pytest.mark.parametrize("method", ["send_message", "send_typing_indicator"]) -def test_meta_reply_is_logged_in_every_environment(monkeypatch, method, deployment_type): +def test_meta_error_fields_are_logged_in_every_environment(monkeypatch, method, deployment_type): monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", deployment_type) _meta_answers(monkeypatch, httpx.Response(400, text=META_REPLY)) log_text = _failed_send_log(method) - assert "400" in log_text + assert "code=131030" in log_text + assert "type='OAuthException'" in log_text + assert f"fbtrace_id='{TRACE_ID}'" in log_text assert "Recipient phone number not in allowed list" in log_text -@pytest.mark.parametrize("deployment_type", ["local", "staging"]) -def test_request_details_are_logged_outside_production_without_the_token(monkeypatch, deployment_type): +@pytest.mark.parametrize("deployment_type", ["local", "staging", "development", "production"]) +@pytest.mark.parametrize("method", ["send_message", "send_typing_indicator"]) +def test_an_error_that_echoes_the_recipient_is_masked_in_every_environment(monkeypatch, method, deployment_type): + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", deployment_type) + _meta_answers(monkeypatch, httpx.Response(400, text=ECHOING_REPLY)) + + log_text = _failed_send_log(method, recipient="US.99999999999999999999") + meta_line = next(line for line in log_text.splitlines() if "Meta's reply" in line) + + assert PHONE not in meta_line + assert BSUID not in meta_line + assert "code=131030" in meta_line + assert "" in meta_line and "" in meta_line + + +@pytest.mark.parametrize("deployment_type", ["staging", "development", "production"]) +@pytest.mark.parametrize("recipient", [PHONE, BSUID]) +@pytest.mark.parametrize("method", ["send_message", "send_typing_indicator"]) +def test_no_phone_bsuid_message_text_or_message_id_is_logged_outside_local(monkeypatch, method, recipient, deployment_type): + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", deployment_type) + _meta_answers(monkeypatch, httpx.Response(400, text=ECHOING_REPLY)) + + log_text = _failed_send_log(method, recipient) + + assert PHONE not in log_text + assert BSUID not in log_text + assert MESSAGE_TEXT not in log_text + assert "wamid" not in log_text + assert get_settings().META_ACCESS_TOKEN_FROM_SYS_USER.get_secret_value() not in log_text + + +@pytest.mark.parametrize("deployment_type", ["staging", "development", "production"]) +def test_a_400_logs_which_keys_were_sent_but_not_their_values(monkeypatch, deployment_type): monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", deployment_type) _meta_answers(monkeypatch, httpx.Response(400, text=META_REPLY)) - log_text = _failed_send_log("send_message") + log_text = _failed_send_log("send_message", PHONE) + + assert "Payload keys: ['messaging_product', 'text', 'to', 'type']" in log_text + + +def test_local_logs_the_full_request_body_but_never_the_token(monkeypatch): + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", "local") + _meta_answers(monkeypatch, httpx.Response(400, text=META_REPLY)) + + log_text = _failed_send_log("send_message", PHONE) assert MESSAGE_TEXT in log_text - assert BSUID in log_text + assert PHONE in log_text assert "Bearer ***" in log_text assert get_settings().META_ACCESS_TOKEN_FROM_SYS_USER.get_secret_value() not in log_text -@pytest.mark.parametrize("method", ["send_message", "send_typing_indicator"]) -def test_production_never_logs_the_request_we_sent(monkeypatch, method): +@pytest.mark.parametrize("deployment_type", ["staging", "development"]) +def test_non_local_test_environments_log_a_masked_body_with_the_safe_fields_readable(monkeypatch, deployment_type): + monkeypatch.setattr(get_settings(), "DEPLOYMENT_TYPE", deployment_type) + _meta_answers(monkeypatch, httpx.Response(400, text=META_REPLY)) + + log_text = _failed_send_log("send_message", PHONE) + + assert "Body with values masked" in log_text + assert "'type': 'text'" in log_text + assert "")) + + log_text = _failed_send_log("send_message", PHONE) + + assert "no standard error object" in log_text + assert PHONE not in log_text + assert BSUID not in log_text + + +@pytest.mark.parametrize( + ("text", "masked"), + [ + ("Recipient 201234567899 not allowed", "Recipient not allowed"), + ("Recipient +20 123 456-7899 not allowed", "Recipient not allowed"), + ("Recipient (631) 555-1234 not allowed", "Recipient not allowed"), + ("user EG.3225570644499982 blocked", "user blocked"), + ("user US.ENT.11815799212886844830 blocked", "user blocked"), + ("id wamid.HBgLMTY1MDM4Nzk0MzkVAgARGBI1RjQy= end", "id end"), + ("(#131030) Recipient phone number not in allowed list", "(#131030) Recipient phone number not in allowed list"), + ("code 2655007 and trace Axly7O1UTgCLGu6n8EXWWTD", "code 2655007 and trace Axly7O1UTgCLGu6n8EXWWTD"), + ], +) +def test_masking_hides_identifier_shapes_and_leaves_ordinary_text(text, masked): + assert mask_identifiers(text) == masked @pytest.mark.parametrize( @@ -129,3 +241,25 @@ def fake_client(**kw): assert seen["timeout"].read == 20.0 assert seen["timeout"].connect == 10.0 + + +def test_webhook_error_logs_mask_the_ids_in_the_payload(): + from ansari_whatsapp.utils.whatsapp_webhook_utils import _redact_for_logging + + payload = { + "object": "whatsapp_business_account", + "entry": [ + { + "id": "102290129340398", + "changes": [ + {"value": {"messages": [{"from": PHONE, "from_user_id": BSUID, "id": "wamid.HBgL", "type": "text"}]}} + ], + } + ], + } + + logged = str(_redact_for_logging(payload)) + + for secret in (PHONE, BSUID, "102290129340398", "wamid.HBgL"): + assert secret not in logged + assert "whatsapp_business_account" in logged and "'type': 'text'" in logged From 2953cfcf7e4df8123d74ebc367728a6b4dfd96d6 Mon Sep 17 00:00:00 2001 From: Younes Abouelnagah Date: Thu, 5 Nov 2026 14:25:47 -0500 Subject: [PATCH 007/435] docs(mcp): add Claude and ChatGPT web screenshots on SAGA 1.0.1 Co-Authored-By: Claude Opus 5.5 --- apps/mcp/README.md | 18 ++++++++++++++---- .../docs/screenshots/chatgpt-web-saga-1.0.jpg | Bin 0 -> 165486 bytes .../docs/screenshots/claude-web-saga-1.0.jpg | Bin 0 -> 197622 bytes 3 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 apps/mcp/docs/screenshots/chatgpt-web-saga-1.0.jpg create mode 100644 apps/mcp/docs/screenshots/claude-web-saga-1.0.jpg diff --git a/apps/mcp/README.md b/apps/mcp/README.md index 0e15ee73..30bf3eb1 100644 --- a/apps/mcp/README.md +++ b/apps/mcp/README.md @@ -8,23 +8,33 @@ A standalone MCP application. `answer_islamic_question` calls the Ansari API and ## Screenshots +### Web, on SAGA 1.0.1 + +New conversations in Claude web and ChatGPT web on November 5, 2026. The card was served by the Dev deployment of this application on SAGA `1.0.1` (release `68dba3e8ce291be7c3c4c35d995fe9a7c8a1e84b`), at its stable address `ui://views/answer-card.v1.html`. Each host shows the card and then its own text reply with Ansari's attribution. + +![Answer card in Claude web on SAGA 1.0.1, with the complete answer, floral branding, attribution and SAGA credit](docs/screenshots/claude-web-saga-1.0.jpg) + +![Answer card in ChatGPT web on SAGA 1.0.1, with the complete answer, floral branding, attribution and SAGA credit](docs/screenshots/chatgpt-web-saga-1.0.jpg) + +### Earlier baseline + English and Arabic answer cards rendered in ChatGPT desktop web through the Dev connection on October 23, 2026. Both rendered on first load with application revision `ee7ea4a78933544c4a96577d7ffd7276df8ae037` and public npm SAGA SDK `0.7.6-rc.1`. Arabic headings, paragraphs and lists use RTL layout and the embedded Kitab fonts. The application owner also supplied the ChatGPT and Claude mobile captures below. These captures retain their original revision identity. The application owner accepts the existing ChatGPT, Claude and earlier Alexa baseline; the [consolidated host and release evidence](https://github.com/MachineWisdomAI/saga-a2ui/pull/321) records each observation and its limits. Earlier Alexa evidence is not presented as a fresh stable-version run, and the 239 successful RC HTTP requests measure transport activity rather than rendered answers. -### English +#### English ![English answer card in ChatGPT Dev, showing the complete answer, floral branding, attribution and SAGA credit](docs/screenshots/chatgpt-dev-english.jpg) -### Arabic +#### Arabic ![Arabic answer card in ChatGPT Dev, showing RTL text, numbered floral markers and attribution](docs/screenshots/chatgpt-dev-arabic.jpg) -### ChatGPT mobile +#### ChatGPT mobile User-provided capture of the Dev answer card in ChatGPT, showing English text and floral branding. ![Ansari MCP Dev card in ChatGPT mobile](docs/screenshots/chatgpt-dev-mobile.jpg) -### Claude mobile +#### Claude mobile User-provided capture of the Dev answer card in Claude, showing Arabic text, RTL layout and numbered floral markers. diff --git a/apps/mcp/docs/screenshots/chatgpt-web-saga-1.0.jpg b/apps/mcp/docs/screenshots/chatgpt-web-saga-1.0.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d962903ba5db7220738a799f92c23f50ffe27e04 GIT binary patch literal 165486 zcmeFZcUaTUwl^9n(t9rwq(}#)Nk>GQhzO!IAu1vuBGQ9|L_m561qCEXS4yOJBGObu zI!LHVK%@i`)DTGF=C{w;`@GM-_mB79=bYy}=e>K#WWMCvX04f7Yt3h^nd9%rs{r21 zmNu4v6DI%wYx*DH7!9~$0rtBO0NB|9lmP$$E8s+;AApH|M85jVQM z6Z1(HRyKAH`UNe#0EQEcj0{YS%*=ni=0r68Jb;Ohng8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qXE2;bwS_@b?>jht(^^?7qab{YH7FlyEP;OmgkhZ8K(arXS)hOKF%>pP=-#%8pIJS+blBx#~+aS^^*PVjmhsRLs4TEn@h@-YS$=MgGh};ps-{#M9Up0&m^H zOQBqDGjl^R^_-@D*HEgcld0w|=U5{C_s3h?ZW!EG+)@%Ii4WLhy5_Vg7256Hc1^!_ z#q)O;%@evrT|;ZqB~)i=-T4*}C)S@2r)s~~IGp{ZAhy-;sH7LuhFQE#tmA z72jIxUffRQR%s=AN zu&S(ARp(yFRT!bRWC>^fJYoG?`sQDg{t-yLY-DCEgt`uNjUQWuueW9`1t#v|4z6Rd z0#D|i$3ze(Eck5;Qx2CZy=INI0fY7veUX62PKZC%`N!Lgllc|-^I{ue^7WilO{{V^3EM5Qr literal 0 HcmV?d00001 diff --git a/apps/mcp/docs/screenshots/claude-web-saga-1.0.jpg b/apps/mcp/docs/screenshots/claude-web-saga-1.0.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d308de12a7936bfe3523906a86e5cea9141495fb GIT binary patch literal 197622 zcmeFZcT`i`yC@opbfotZ6%eFKS6V=%$;K!uAT1)&g@}j*2#JD#G(%BPktQHwq4yT) zASlwC5E4`rh$MhvX$o)cea`)zJMMeqj&tr`_lC$G@)8e?PcShMYJTh`fc22t?jEq_2G(a^jSO6X)Nvf$g7bm47aUrxeoX zagaLBA9r{kZvv+<`|ltkJe+7wH4e5T5OxtZ4iUEfJ_rfwcQfV z;}m86t2g6$`6Q*JWn@*3s;V7RH!w6ZK5^2-`m~L$oxQ`E3l}fBxVl|-_r2!l9}pN6 z9C0i1b`&Z)CgEOUQu6(j)a;yxk8<-KKY9ARw5Z9Tnx{R4wT z!|x|1r>19S=jIoPq}4B9zpZ`$u}$C)|+D6*mceHdpUBByL$Y;ANju#FS#1|_vLPBzmLm+#7s-P5B#%pmNc`sr6|z} zFR7}!!>9KApAOsq^k3r}jdZG0Z*`C##uvE2T_S8yd zi4ScbvRQ2bYmCMqb6TPcy~Ep)UahMq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m(PG?hQBBh@SJnkkI0=(}2Hj&w_?*Y7}uYL8m0SFiGQvlD&XY&Yp zdh;)q%hbNEdj3V!@jLkDu=M^Oa}%N0$0CeHx$%BD&yTz#NOzm)B#J-FYA}ult>2f) zgk!xvrS*MB)y#(d=4)+cHGPN6uBL~a!Io3)* z?YNPcLMZbV_t_6jl)DV$QCio=ftplZxa|Fm``4>x8oa%a%z7S}rk$)fM=tRQzHLR` z10r6@&x%agds$)$J8@YkU(U=1`#@_WTkqlEuasxZnpQPgP-zUI6kd{8@Xqmol_>;f zkL&dH>6fXhx07$#Nd`!sm*#TE=9VA@T>!YJ&L1kJ*j=Tz5c zrKx7==6zir-ty@-myzSGY~^rLfet-?0B&vE3t*?Ai`Q)S0o+6R#zQhJ+S#x-ju_>fAIy!z4f< zC?9fbD52mW<8fBWC;#%Vdf$S%Ir~!f7ExuNs+Xy5uARwT4-5=ct6*)jFC(X^PAL>z z6toT+cXLAbH($c6WaIecDptA2NXzO&jGgj}W0uoj7I&8u`%3P%Q9)eY&nqk}y{-$l z=Y2>?Lp?(;C!`dn1OKLwx~ZJ-{9*Tb-(;V0QVpV#3@%H#r;H=9%+ZWsQiTF-mU*0hLKDVxSkn^6c zpR-XH+#2=@(2-8K11%EeNI52teL2bgN$13M&!wq#c}s($tU$ZQZ_(~duup_f8lN7 Date: Tue, 10 Nov 2026 14:39:09 +0200 Subject: [PATCH 008/435] chore(porch): 358 init spir --- .../358-whatsapp-typescript/status.yaml | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 codev/projects/358-whatsapp-typescript/status.yaml diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml new file mode 100644 index 00000000..2e2e6c56 --- /dev/null +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -0,0 +1,20 @@ +id: '358' +title: whatsapp-typescript +protocol: spir +phase: specify +plan_phases: [] +current_plan_phase: null +gates: + spec-approval: + status: pending + plan-approval: + status: pending + pr: + status: pending + verify-approval: + status: pending +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-10T12:39:08.669Z' +updated_at: '2026-11-10T12:39:08.675Z' From 09f62bbeef58e821e7c256399f9c2683fa133b08 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 14:43:21 +0200 Subject: [PATCH 009/435] chore(porch): 358 specify build-complete --- codev/projects/358-whatsapp-typescript/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 2e2e6c56..d74a12b3 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -14,7 +14,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T12:39:08.675Z' +updated_at: '2026-11-10T12:43:21.267Z' From e06095a71acc22dd5812d47c161e051631c33808 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 15:37:13 +0200 Subject: [PATCH 010/435] chore(porch): 358 spec-approval gate-approved --- codev/projects/358-whatsapp-typescript/status.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index d74a12b3..e6718281 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -6,7 +6,8 @@ plan_phases: [] current_plan_phase: null gates: spec-approval: - status: pending + status: approved + approved_at: '2026-11-10T13:37:12.921Z' plan-approval: status: pending pr: @@ -17,4 +18,4 @@ iteration: 1 build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T12:43:21.267Z' +updated_at: '2026-11-10T13:37:12.922Z' From 4407ea30fc86a80fa86d2bd8ad8a4de3488ba510 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 15:37:26 +0200 Subject: [PATCH 011/435] chore(porch): 358 plan phase-transition --- codev/projects/358-whatsapp-typescript/status.yaml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index e6718281..771fc7a3 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -1,7 +1,7 @@ id: '358' title: whatsapp-typescript protocol: spir -phase: specify +phase: plan plan_phases: [] current_plan_phase: null gates: @@ -15,7 +15,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T13:37:12.922Z' +updated_at: '2026-11-10T13:37:26.337Z' +context_refreshes: + - boundary: enter:plan + at: '2026-11-10T13:37:26.336Z' From 30beee606ac7b44e58b54cafb612dc2a3af85eac Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 15:37:36 +0200 Subject: [PATCH 012/435] chore(porch): 358 acknowledge context refresh --- codev/projects/358-whatsapp-typescript/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 771fc7a3..95f71102 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -18,7 +18,8 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T13:37:26.337Z' +updated_at: '2026-11-10T13:37:36.559Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' + acknowledged_at: '2026-11-10T13:37:36.557Z' From 54af88437f499738056cf4647cd92a01a7451dc6 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 15:39:28 +0200 Subject: [PATCH 013/435] chore(porch): 358 plan build-complete --- codev/projects/358-whatsapp-typescript/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 95f71102..6a594dcb 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -15,10 +15,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T13:37:36.559Z' +updated_at: '2026-11-10T13:39:27.983Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' From 06d1501bfa791693f8d85190a2c6c4747af86978 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 16:06:42 +0200 Subject: [PATCH 014/435] chore(porch): 358 plan-approval gate-approved --- codev/projects/358-whatsapp-typescript/status.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 6a594dcb..67915474 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -9,7 +9,8 @@ gates: status: approved approved_at: '2026-11-10T13:37:12.921Z' plan-approval: - status: pending + status: approved + approved_at: '2026-11-10T14:06:42.538Z' pr: status: pending verify-approval: @@ -18,7 +19,7 @@ iteration: 1 build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T13:39:27.983Z' +updated_at: '2026-11-10T14:06:42.539Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' From db9a67c45b6284ef7dca01dd88de10d54352dbe5 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 16:06:46 +0200 Subject: [PATCH 015/435] chore(porch): 358 implement phase-transition --- .../358-whatsapp-typescript/status.yaml | 33 ++++++++++++++++--- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 67915474..ab6e0644 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -1,9 +1,30 @@ id: '358' title: whatsapp-typescript protocol: spir -phase: plan -plan_phases: [] -current_plan_phase: null +phase: implement +plan_phases: + - id: phase_1 + title: Scaffold apps/whatsapp, config, masked logging + status: in_progress + - id: phase_2 + title: 'Pure logic: formatter, splitter, webhook parser, language and time helpers' + status: pending + - id: phase_3 + title: 'Service clients: apps/auth exchange, apps/api streaming, Meta API' + status: pending + - id: phase_4 + title: Conversation manager + status: pending + - id: phase_5 + title: 'HTTP app: webhook verification, signature check, immediate 200' + status: pending + - id: phase_6 + title: Docker, Railway config, CI, turbo and documentation + status: pending + - id: phase_7 + title: Staging redeploy, smoke test and legacy rollback note + status: pending +current_plan_phase: phase_1 gates: spec-approval: status: approved @@ -16,11 +37,13 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T14:06:42.539Z' +updated_at: '2026-11-10T14:06:46.785Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' acknowledged_at: '2026-11-10T13:37:36.557Z' + - boundary: enter:implement + at: '2026-11-10T14:06:46.783Z' From 34c823eeeeb588dbbce4222eac9d0a0c834fe1c3 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 16:07:00 +0200 Subject: [PATCH 016/435] chore(porch): 358 acknowledge context refresh --- codev/projects/358-whatsapp-typescript/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index ab6e0644..f0babd8c 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -40,10 +40,11 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T14:06:46.785Z' +updated_at: '2026-11-10T14:07:00.689Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' acknowledged_at: '2026-11-10T13:37:36.557Z' - boundary: enter:implement at: '2026-11-10T14:06:46.783Z' + acknowledged_at: '2026-11-10T14:07:00.688Z' From 9225fa04b853bd1dcefe1e45fa1e650348eb57f2 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 17:15:13 +0200 Subject: [PATCH 017/435] [Spec 358] Spec and plan for the TypeScript WhatsApp service --- codev/plans/358-whatsapp-typescript.md | 183 ++++++++++++++++++ .../358-specify-iter1-gemini.txt | 10 + codev/specs/358-whatsapp-typescript.md | 139 +++++++++++++ 3 files changed, 332 insertions(+) create mode 100644 codev/plans/358-whatsapp-typescript.md create mode 100644 codev/projects/358-whatsapp-typescript/358-specify-iter1-gemini.txt create mode 100644 codev/specs/358-whatsapp-typescript.md diff --git a/codev/plans/358-whatsapp-typescript.md b/codev/plans/358-whatsapp-typescript.md new file mode 100644 index 00000000..8a24f8f3 --- /dev/null +++ b/codev/plans/358-whatsapp-typescript.md @@ -0,0 +1,183 @@ +# Plan: Translate the WhatsApp service to TypeScript + +**Specification**: [codev/specs/358-whatsapp-typescript.md](../specs/358-whatsapp-typescript.md) + +## Executive Summary + +A new app, `apps/whatsapp`, re-implements the Python service in `legacy/whatsapp` with the same externally visible behaviour. `legacy/whatsapp` stays untouched as the behavioural reference until staging is verified (spec: no production migration in this issue). + +The Python tests (197) are the oracle: each phase ports one layer bottom-up, together with the tests for that layer, so every phase ends green and nothing is written without a test that can fail. + +### Stack, chosen to match `apps/auth` (the closest sibling) + +| Concern | Choice | Python counterpart | Why | +|---|---|---|---| +| Runtime | Node.js >= 22.18 | CPython 3.13 | Same engine as `apps/auth`; `engines` and the Docker base image are already settled | +| HTTP framework | Express 5 | FastAPI | Already used by `apps/auth`; small, well known | +| Runtime validation | Zod 4 | Pydantic | Already used by `apps/api` and `packages/auth` | +| Outbound HTTP | Node's built-in `fetch` | httpx | No extra dependency; supports streamed bodies | +| Tests | Vitest | pytest | Same as every other app | +| Dev / build | `tsx` / `tsdown` | `uvicorn` / none | Same as `apps/auth` | +| Errors | `@sentry/node` | `sentry-sdk` | Same as `apps/auth` | +| Logging | Small in-app JSON logger with the masking rules ported from `log_masking.py` | loguru + `log_masking.py` | Masking is behaviour we must keep exactly; a library would not remove that work | +| Markdown to WhatsApp text | Port the 99-line formatter by hand | `whatsapp_message_formatter.py` | Exact output must match the Python tests; a library would change it | + +### TypeScript notes for the reader (Python to TypeScript) + +- **Types vanish at runtime.** `type Foo = {...}` is checked by the compiler, then erased. A JSON body from Meta is `unknown` until a Zod schema parses it. This is the TypeScript counterpart of a Pydantic model, with one difference: Pydantic validates automatically, Zod only when you call `.parse()`/`.safeParse()`. +- **`async`/`await` and Promises.** Same keywords as Python, but a Promise starts running immediately when created (a Python coroutine does not run until awaited). The "answer Meta 200 first, then process" pattern is therefore just `res.sendStatus(200)` followed by an un-awaited call whose failures we catch ourselves: an un-awaited Promise that rejects crashes or goes unnoticed, so every background task gets a top-level `.catch` that logs and reports to Sentry. +- **Streams.** `fetch` returns `response.body`, a web `ReadableStream` of byte chunks. We read it with `for await`, decode with `TextDecoder` (chunk boundaries can split a multi-byte character, so decode with `{stream: true}`), then apply the same aggregation as the Python client. +- **Modules.** `package.json` has `"type": "module"`, so files use `import`/`export` (not `require`). Local imports end in `.ts`/`.js` according to the repo's tsconfig; follow `apps/auth`. +- **`null` vs `undefined`.** Both mean "no value"; JSON only has `null`. The code uses `undefined` for "absent" and `null` only when a wire format says so. +- **Config.** There is no Pydantic `BaseSettings`; a Zod schema parses `process.env` once at startup and exports a frozen object. All values arrive as strings, so booleans and numbers need explicit parsing (`"False"` is a truthy string). +- **Dependency injection.** FastAPI uses `Depends`; here the services are plain objects created in one `buildApp(deps)` function, so tests pass mock clients instead of patching modules (the base/real/mock trio becomes one interface plus a real and a mock implementation). + +## Phases (Machine Readable) + +```json +{ + "phases": [ + {"id": "phase_1", "title": "Scaffold apps/whatsapp, config, masked logging"}, + {"id": "phase_2", "title": "Pure logic: formatter, splitter, webhook parser, language and time helpers"}, + {"id": "phase_3", "title": "Service clients: apps/auth exchange, apps/api streaming, Meta API"}, + {"id": "phase_4", "title": "Conversation manager"}, + {"id": "phase_5", "title": "HTTP app: webhook verification, signature check, immediate 200"}, + {"id": "phase_6", "title": "Docker, Railway config, CI, turbo and documentation"}, + {"id": "phase_7", "title": "Operator script port, staging redeploy, smoke test and legacy rollback note"} + ] +} +``` + +**The green command for every phase**, run from the worktree root: `pnpm --filter ansari-whatsapp test && pnpm --filter ansari-whatsapp typecheck && pnpm --filter ansari-whatsapp lint`. Phase 6 widens it to the root `pnpm test && pnpm typecheck && pnpm lint`. Each phase is one commit prefixed `[Spec 358][Phase: ...]`, adding files by explicit path (never `git add -A`). + +**Test discipline (from the repo's lessons):** every new test must be shown able to fail by temporarily breaking the code it covers, then restoring it. The Python mapping is recorded per phase. + +**Comment discipline (success criterion):** carry over the Python docstrings and comments, with Meta reference URLs, as TSDoc (`/** ... */`). Every setting in `.env.example` and in the config module documents purpose, allowed values, default and which environments use it. + +## Phase Breakdown + +### Phase 1: Scaffold apps/whatsapp, config, masked logging + +**Dependencies**: None + +**Objective**: A buildable, testable empty app that loads and validates configuration and logs safely. + +**Files to create** (modelled on `apps/auth`): `package.json` (name `ansari-whatsapp`, `"type": "module"`, same scripts), `tsconfig.json`, `eslint.config.mjs`, `vitest.config.ts`, `tsdown.config.ts`, `.env.example`, `.env.ci`, `src/config.ts`, `src/logger.ts`, `src/logMasking.ts`, `src/errors.ts`, `tests/config.test.ts`, `tests/logMasking.test.ts`. + +**Behaviour to port**: every setting of `utils/config.py` (same names, so Railway variables carry over unchanged): `BACKEND_SERVER_URL`, `AUTH_SERVER_URL`, `AUTH_WHATSAPP_API_KEY`, `META_API_VERSION`, `META_BUSINESS_PHONE_NUMBER_ID`, `META_ACCESS_TOKEN_FROM_SYS_USER`, `META_WEBHOOK_VERIFY_TOKEN`, `META_ANSARI_APP_SECRET` (no default, on purpose), `META_REPLY_BY_PHONE`, `DEPLOYMENT_TYPE` (local, development, staging, production), `ALWAYS_RETURN_OK_TO_META`, `ORIGINS` (CORS), `WA_MAINTENANCE_MODE`, `WHATSAPP_CHAT_RETENTION_HOURS`, `WHATSAPP_MESSAGE_AGE_THRESHOLD_SECONDS`, `LOGGING_LEVEL`, `SENTRY_DSN`, and the mock flags `MOCK_ANSARI_CLIENT`, `MOCK_AUTH_CLIENT`, `MOCK_AUTH_TOKEN`, `MOCK_META_API`. Secrets are held so they never print (the counterpart of Pydantic's `SecretStr`). Switches accept the same spellings as apps/api's `MAINTENANCE_MODE` (`true`, `false`, `True`, `False`, `1`, `0`; owner decision) and refuse anything else, so `yes`, `on` and `TRUE`, which Pydantic accepted, now stop start-up; phase 7 checks the Railway values. The entry points are named like apps/api's (`getEnv`, `resetEnvCache`, type `Env`), with `buildConfig(env)` added so tests pass an object instead of patching `process.env`. **`LOG_TEST_FILES_ONLY` is deliberately not ported** (owner decision): in Python it silenced every log line not coming from a test file, which was only a way to quiet the test output; the Node test runner already hides logs from passing tests, and Node cannot cheaply see the calling file. **`META_WEBHOOK_ZROK_SHARE_TOKEN` is deliberately not ported** (owner decision): in Python it is read only by `config.py`, to add `.share.zrok.io` to the CORS allow-list in local mode, and Meta's server-to-server webhooks send no `Origin` header, so that entry has no functional effect. Its setup notes (the zrok reserve/release steps and callback-URL explanation) move into `.env.example` as commented-out information so local developers keep them. The rule that `META_REPLY_BY_PHONE` is off by default and refused when `DEPLOYMENT_TYPE` is production; `utils/log_masking.py` and `app_logger.py` (per-environment detail: local full, staging masked, production keys only; request ID and user ID on every line). + +**Python tests mapped**: `test_environment_behaviour.py`, `test_railway_logging.py`, part of `test_meta_sender_logging.py`. + +**Done when**: green command passes; `.env.example` documents every setting; a negative control proves the production refusal and the masking tests can fail. + +### Phase 2: Pure logic + +**Dependencies**: Phase 1 + +**Objective**: The side-effect-free pieces, easiest to verify against Python. + +**Files**: `src/formatting/whatsappMessageFormatter.ts`, `src/formatting/messageSplitter.ts`, `src/webhook/parseWebhook.ts` (Zod schema plus extraction; reads `from` only when `META_REPLY_BY_PHONE` is on, read at call time, not at import), `src/utils/language.ts`, `src/utils/time.ts` and matching tests. + +**Python tests mapped**: `test_message_splitter.py`, formatter and webhook-parser cases in `test_whatsapp_service.py`, `test_meta_sender_logging.py`. + +**Done when**: all mapped cases pass with identical expected strings, including the 4000-character split, RTL handling, status/wrong-number/unsupported/stale webhook classification. + +### Phase 3: Service clients + +**Dependencies**: Phase 2 + +**Objective**: The three outbound clients, each behind an interface with a real and a mock implementation. + +**Files**: `src/services/authClient.ts` (`POST /api/whatsapp/session`, per-BSUID token cache for a little under 15 minutes, the 400/401/403/429+`X-Retry-After`/500 handling and per-user cool-down from spec 321), `src/services/ansariClient.ts` (streaming chat endpoints, trailing `Error:` detection after HTTP 200, 401 then one re-exchange and one retry), `src/services/metaApiService.ts` (typing indicator, send; `reply_to` BSUID or phone), mocks, tests using a local fake HTTP server or injected `fetch`. + +**Python tests mapped**: `test_auth_statuses.py`, `test_bsuid_auth_flow.py`, client parts of `test_thread_lifecycle.py`. + +**Done when**: the status table in spec 321 is fully covered, including: no phone number ever in an `apps/auth` or `apps/api` request body or log; a second 401 ends with the right Sentry event name. + +### Phase 4: Conversation manager + +**Dependencies**: Phase 3 + +**Objective**: The orchestration: user registration via token exchange, the thread lifecycle (one thread per user, 3-hour expiry), maintenance mode (`WA_MAINTENANCE_MODE`), the staging `!d ` prefix filter, message-age check, notices. + +**Files**: `src/conversationManager.ts`, `tests/conversationManager.test.ts`. + +**Python tests mapped**: `test_thread_lifecycle.py`, orchestration parts of `test_whatsapp_service.py`, `test_bsuid_auth_flow.py`. + +**Done when**: all Python lifecycle and notice scenarios pass; negative controls for expiry, maintenance and the `!d ` filter. + +### Phase 5: HTTP app + +**Dependencies**: Phase 4 + +**Objective**: The Express app and server entry. + +**Files**: `src/app.ts` (`buildApp(deps)`), `src/index.ts`, `tests/app.test.ts`. Routes: `GET /` health, `GET /whatsapp/v3` verification handshake, `POST /whatsapp/v3`. The signature check needs the raw request bytes, so the JSON body parser must keep them (Express `express.json({ verify })`) and the HMAC-SHA256 comparison must be constant-time (`crypto.timingSafeEqual`). The handler responds 200, then runs processing un-awaited with a top-level catch. Request-ID middleware; `ALWAYS_RETURN_OK_TO_META` behaviour preserved, including the unsupported-message path (error code `UNSUPPORTED_MESSAGE_TYPE`, status 415 when the flag is off); CORS from `ORIGINS`; the verification handshake compares tokens in constant time like `hmac.compare_digest`; graceful shutdown; binds `PORT` (default **3200** for local runs; Railway injects its own `PORT`). Express has no default port (8001 was a choice in the Python service, not a FastAPI rule; 8000 is only uvicorn's default). 3000 is `apps/api`, 3100 is `apps/auth`, and nothing in the repo uses 3200, so the next free number in the same series is used. The local zrok command changes from `localhost:8001` to `localhost:3200`. + +**Note on `scripts/check_meta_subscriptions.py`** (644 lines, an operator tool, not part of the service): it is ported separately, in phase 7. + +**Python tests mapped**: `test_whatsapp_service.py`, `test_utils.py`. + +**Done when**: acknowledgment timing is tested independently of background work (the 200 is observed before a deliberately slow mock finishes); invalid or missing signature rejected; handshake passes and fails correctly. + +### Phase 6: Docker, Railway config, CI, turbo and documentation + +**Dependencies**: Phase 5 + +**Objective**: Make the app shippable by the repo's tooling. + +**Files**: `apps/whatsapp/Dockerfile` (same shape as `apps/auth/Dockerfile`), `apps/whatsapp/railway.toml` (health check `/`; the same "record, not read by Railway" header as the legacy file), `apps/whatsapp/README.md`, root `turbo.json` `globalEnv` additions for the new variables (the file explains why every variable must be listed), a CI job for the new app, and the architecture notes under `codev/resources/`. + +**Done when**: root green command passes from a cold cache (`--force`); Docker image builds locally if Docker is available (otherwise recorded as **not verified**, never as passed). + +### Phase 7: Operator script port, staging redeploy, smoke test and legacy rollback note + +**Dependencies**: Phase 6 + +**Why the script is here and not its own phase:** porch fixes the list of plan phases when the plan is approved, so a new numbered phase would need a rollback to the plan phase and a second approval. The script is first in this phase, because the staging steps below use it. + +**Part A: port `legacy/whatsapp/scripts/check_meta_subscriptions.py`** (644 lines, an interactive operator tool) to `apps/whatsapp/scripts/checkMetaSubscriptions.ts`. It inspects the Meta Messaging account (WABA): its details, the apps subscribed to it, its phone numbers and the access token's app and expiry, and can subscribe or unsubscribe the app the token belongs to. A webhook only reaches the Meta apps subscribed to the account, so it is the tool for "messages to the staging number do not arrive". +- Same menu, same explanatory text (the prerequisite-knowledge section and the WABA/app/token relations), same confirmations before the two changing actions (POST and DELETE on `subscribed_apps`), same fallback to prompting when `.env` has no token or account id. +- Counterparts: `requests` becomes the built-in `fetch`; `input()` and `getpass` become `node:readline/promises` (the token prompt hides what is typed); `load_dotenv` becomes `dotenv`. Reads `META_ACCESS_TOKEN_FROM_SYS_USER`, `META_MESSAGING_ACCOUNT_ID` and `META_API_VERSION` (Python hard-coded `v26.0`; same default here). Run with `pnpm --filter ansari-whatsapp meta:subscriptions`. +- The Python script has no tests. The TypeScript one gets tests for its pure parts with an injected `fetch`: how each Meta response is read, that only the token's own app is ever unsubscribed, and that the token is never printed. Each is shown able to fail. +- `.env.example`: the commented `META_MESSAGING_ACCOUNT_ID` and `META_ANSARI_APP_ID` entries now say this script reads them. +- **Verified** only against mocked responses. Live checks (read-only options) run against staging in Part B. The two changing actions are not run without the owner's go-ahead. + +**Part B: staging.** Replace the Python build on the existing Railway staging `whatsapp` service. No production change. + +**Steps**: +1. Compare the staging service's variables with `.env.example` (names only; never print values or the token `ASH_RAILWAY_PAT`). Also check that every True/False variable uses `true`, `false`, `True`, `False`, `1` or `0`: the TypeScript service refuses `yes`, `on` and `TRUE`, which the Python service accepted. +2. Point the staging `whatsapp` service at `apps/whatsapp/Dockerfile` and redeploy. **Done by the user or with the user's explicit go-ahead**, because it changes a shared service. +3. Smoke test: visible-phone user, hidden-phone (BSUID-only) user, a long answer, and error paths (maintenance mode, `apps/auth` refusal). +3a. Change the webhook callback URL in the staging Meta app's webhook settings from `.../whatsapp/v2` to `.../whatsapp/v3` (owner-made change in Meta's dashboard; re-run the verification handshake and confirm Meta shows the subscription as active). Until this is done, Meta still posts to `/v2`, which the TypeScript service does not serve. +4. Add a brief rollback note to `legacy/whatsapp/README.md` (rolling back also means setting Meta's callback URL back to `/whatsapp/v2`): the Python image and Dockerfile are unchanged, so rollback is repointing the staging service at `legacy/whatsapp/Dockerfile` and redeploying. + +**Done when**: smoke results are listed in the review as verified or not, with evidence. + +## Risks and Mitigation + +| Risk | Mitigation | +|---|---| +| Acknowledgment delayed by processing | Phase 5 timing test | +| Types give false confidence about Meta JSON | Zod parsing at every boundary (phases 2, 3) | +| Streaming aggregation differs from Python | Chunk-boundary and trailing-error tests (phase 3) | +| Formatter output drifts | Port Python expectations verbatim before refactoring (phase 2) | +| Un-awaited background Promise fails silently | Single wrapper with catch, log and Sentry; test that a failure is reported (phase 5) | +| Windows test flakiness (CRLF fixtures, POSIX paths) | No fixture files read from disk; paths built with `node:path` | + +## Self-review (agent, no external consultation) + +The owner chose agent self-review followed by owner review; Codex and Gemini are not installed and the Claude consult hung. Checked against the Python source: + +- **Fixed:** the plan omitted the CORS `ORIGINS` setting, the four mock flags, the 415 unsupported-message reply, and the default port (now 3200, not Python's 8001). +- **Decided:** `META_WEBHOOK_ZROK_SHARE_TOKEN` is not ported; its notes live in `.env.example` as comments. Verified by search: the only code reading it is `config.py`; the other mentions are docs, `.env.example`, the README and printed hints in `check_meta_subscriptions.py`. Not verified live: that Meta never sends an `Origin` header (inferred from webhooks being server-to-server and from the code only checking `Origin`). +- **Fixed:** settings must keep their Python names so Railway staging needs no variable changes. +- **Verified:** route list (`GET /`, `GET /whatsapp/v2`, `POST /whatsapp/v2`) and the constant-time token and signature comparison match `main.py`. The TypeScript service deliberately renames the two webhook routes to `/whatsapp/v3` (owner decision), so the port is not byte-for-byte identical there. +- **Changed after owner review of phase 1:** booleans use apps/api's six spellings; `getEnv`, `resetEnvCache` and `Env` replace `getConfig`, `resetConfigCache` and `Config`; `LOG_TEST_FILES_ONLY` is dropped; the Meta script is ported in phase 7. +- **Not verified:** exact Markdown formatter output and splitter edge cases are only confirmed once the Python tests are ported (phase 2). +- **Not verified:** whether `apps/auth`'s tsconfig and eslint presets apply unchanged to a second Express app; phase 1 finds out. + +## Open items for the owner + +- Confirm the directory name `apps/whatsapp` (the spec said "likely"). +- Staging variable changes and the Railway repoint in phase 7 need the owner's go-ahead at that time. diff --git a/codev/projects/358-whatsapp-typescript/358-specify-iter1-gemini.txt b/codev/projects/358-whatsapp-typescript/358-specify-iter1-gemini.txt new file mode 100644 index 00000000..68efa4d9 --- /dev/null +++ b/codev/projects/358-whatsapp-typescript/358-specify-iter1-gemini.txt @@ -0,0 +1,10 @@ +--- +VERDICT: COMMENT +SUMMARY: Gemini lane skipped — agy CLI not found (install: https://antigravity.google/cli/install.sh) +CONFIDENCE: LOW +--- + +The Gemini (Antigravity `agy`) reviewer was skipped: agy CLI not found (install: https://antigravity.google/cli/install.sh). +This is a non-blocking skip; the remaining reviewers still apply. To enable the +Gemini lane, install the CLI (https://antigravity.google/cli/install.sh) and run +`agy` once to sign in. \ No newline at end of file diff --git a/codev/specs/358-whatsapp-typescript.md b/codev/specs/358-whatsapp-typescript.md new file mode 100644 index 00000000..c6b88181 --- /dev/null +++ b/codev/specs/358-whatsapp-typescript.md @@ -0,0 +1,139 @@ +# Specification: Translate the WhatsApp service to TypeScript + + + +## Problem Statement + +The WhatsApp service currently lives in `legacy/whatsapp` as a Python/FastAPI application. The monorepo's application stack is TypeScript, so maintaining the WhatsApp service separately increases operational, deployment, and testing complexity. + +Issue #358 translates the service to TypeScript while preserving the behavior established by spec 321, PR #327, and follow-up PR #339. The existing Python implementation and its 197 passing tests are the behavioral reference during the migration. + +## Current State + +The Python service: + +- Receives Meta webhooks at `POST /whatsapp/v2`. +- Verifies Meta signatures and answers Meta with HTTP 200 immediately. +- Identifies users by BSUID and exchanges it for a JWT through `POST /api/whatsapp/session` in `apps/auth`. +- Calls `apps/api` using the JWT and streaming endpoints. +- Aggregates streaming responses into complete WhatsApp messages. +- Converts Markdown to WhatsApp-compatible text. +- Splits messages at 4000 characters. +- Supports `WA_MAINTENANCE_MODE`. +- Supports `META_REPLY_BY_PHONE`, disabled by default and refused in production. +- Provides masked, environment-specific logging. +- Runs as the Railway `whatsapp` service. + +The monorepo uses TypeScript applications, `pnpm`, and Turbo. The exact TypeScript HTTP framework and runtime should follow the repository's existing conventions and will be selected in the plan after inspection. + +## Desired State + +A TypeScript WhatsApp service replaces the Python implementation while preserving its externally observable behavior and service contracts. + +The service must: + +- Receive and verify Meta webhooks at `POST /whatsapp/v3` (owner decision, 2026-11-10: the TypeScript service upgrades the route from `/whatsapp/v2`; the webhook callback URL must then be changed in each Meta app's webhook settings when that environment is switched over). `GET /whatsapp/v3` answers the verification handshake. The Python service keeps `/whatsapp/v2`. +- Return success to Meta immediately after validating the webhook request. +- Process supported messages asynchronously after acknowledgment. +- Exchange BSUID identity for a JWT through `apps/auth`. +- Call `apps/api` using the JWT and existing streaming endpoints. +- Preserve authentication, thread, maintenance, error, retry, and message-age behavior. +- Convert Markdown and split responses exactly as required for WhatsApp. +- Preserve masked, per-environment logging and request correlation. +- Integrate with the monorepo's `pnpm` and Turbo workflows. +- Include a TypeScript port of the operator script `legacy/whatsapp/scripts/check_meta_subscriptions.py` (owner decision, 2026-11-10), which lists and changes the Meta apps subscribed to the Messaging account. +- Redeploy the existing Railway staging `whatsapp` service with the TypeScript implementation. No production migration is part of this issue. + +The Python service remains available as a behavioral reference until the TypeScript service has passed staging verification. A brief rollback note will be added to the legacy Python WhatsApp folder when the migration reaches deployment readiness. + +## TypeScript Learning Notes + +The implementation process should explain these concepts when they become relevant: + +- **TypeScript:** JavaScript with a static type system. Types help catch invalid values before runtime, but they are removed when the code is compiled and do not validate incoming webhook JSON by themselves. +- **Runtime:** The program that executes the compiled or directly interpreted TypeScript. The plan must identify whether this service uses Node.js or another repository-supported runtime. +- **Framework:** The HTTP library that handles routes, request bodies, responses, middleware, and server startup. It is the TypeScript counterpart to FastAPI's application and route layer. +- **Types versus schemas:** Type annotations describe what code expects at compile time. Runtime schemas validate untrusted Meta and service responses while the program is running; webhook and API boundaries need runtime validation. +- **Promises and async/await:** TypeScript uses JavaScript Promises for asynchronous work. `async`/`await` is conceptually close to Python's `async`/`await`, but errors and response-body handling follow JavaScript Promise conventions. +- **Streams:** A streaming HTTP response arrives in chunks. The TypeScript client must consume all chunks, detect API-level errors reported after HTTP 200, and then apply the same aggregation and formatting rules as Python. +- **Modules and packages:** TypeScript source is organized into modules, and `package.json` declares dependencies and scripts. The migration should use existing monorepo package conventions rather than introducing a separate package-management style. +- **Middleware and dependency injection:** Framework middleware is commonly used for cross-cutting behavior such as signature verification, request IDs, logging, and error handling. The implementation should preserve ownership boundaries without copying FastAPI-specific patterns mechanically. + +Each design choice in the plan and implementation should state the relevant Python behavior, the TypeScript equivalent, and any meaningful semantic difference. + +## Compatibility Requirements + +The TypeScript implementation must preserve: + +- Meta webhook signature verification and webhook verification handshake. +- Immediate HTTP 200 acknowledgment for valid deliveries. +- BSUID-only identity handling; phone numbers must not be sent to `apps/auth` or `apps/api`. +- JWT caching, re-exchange after an `apps/api` 401, and one retry behavior. +- Conversation expiry and thread lifecycle. +- Unsupported-message, stale-message, banned-user, maintenance, and failure notices. +- 4000-character splitting and Markdown conversion. +- `META_REPLY_BY_PHONE` semantics, including refusal in production, while the setting remains needed. +- Structured masked logging by environment. +- Ignoring Meta status webhooks. +- Staging `!d ` filtering, if still required by the current Python behavior. + +## Open Decisions + +1. **Service location:** Create a new application under `apps/`, likely `apps/whatsapp`, while retaining `legacy/whatsapp` as the reference during migration. The plan should confirm the final directory and package naming against existing monorepo conventions. +2. **Runtime and HTTP framework:** Select the repository-consistent TypeScript runtime and HTTP framework. The plan must explain the Python/FastAPI comparison and why the selected tools fit this service. +3. **Phone-number reply behavior:** Retain `META_REPLY_BY_PHONE` during the migration for local/staging compatibility. Remove it only in a later change after issue #362 confirms that it is no longer needed. +4. **Railway deployment:** Redeploy the existing staging `whatsapp` service in place. Production deployment is out of scope. +5. **Deferred work:** Issues #359, #360, and #361 remain separate and must not be exposed as dependencies of this migration. + +## Success Criteria + +- [ ] A TypeScript WhatsApp application exists in the agreed monorepo location and runs with the repository's standard package and task tooling. +- [ ] The Python behavior tests are mapped to focused TypeScript tests covering webhook handling, signatures, authentication, streaming, formatting, splitting, maintenance, and failures. +- [ ] Phone-hidden BSUID users receive replies without phone numbers being sent to `apps/auth` or `apps/api`. +- [ ] Meta receives an immediate successful response for valid deliveries. +- [ ] Duplicate and status webhook behavior remains unchanged. +- [ ] Logging does not expose BSUIDs, phone numbers, tokens, or message content beyond the existing environment policy. +- [ ] `META_REPLY_BY_PHONE` remains disabled by default and refused in production. +- [ ] The Meta subscription script runs from `apps/whatsapp` with the same menu, explanations and confirmations as the Python script, and its read-only options work against staging. +- [ ] True/False settings accept the same spellings as apps/api (`true`, `false`, `True`, `False`, `1`, `0`) and refuse anything else; the Railway staging values are checked against that before the redeploy. +- [ ] Railway staging redeploys the existing `whatsapp` service with the TypeScript implementation. +- [ ] Staging smoke tests pass for visible-phone and hidden-phone users, including long responses and error paths. +- [ ] A brief rollback note is added to the legacy Python WhatsApp folder before staging migration is considered complete. +- [ ] The implementation documentation explains relevant TypeScript concepts and meaningful differences from the Python service. +- [ ] Code comments, doc comments (TSDoc) and configuration documentation are carried over from the Python service and kept as detailed: functions that deal with Meta logic keep their reference URLs to Meta's documentation and explain the why; `.env.example` and the TypeScript config module (the counterpart of `config.py`) document every setting, its allowed values, its default and which environments use it. + +## Test Scenarios + +- Phone-visible user sends text and receives an answer. +- Phone-hidden user sends text and receives an answer without phone-number propagation. +- Two messages within the conversation window retain the same user and thread. +- A message after the expiry window starts the expected new thread behavior. +- A long answer is split in order at WhatsApp-compatible boundaries. +- Status, wrong-number, stale, unsupported, and malformed webhooks follow existing behavior. +- Invalid or missing Meta signatures are rejected. +- Webhook verification succeeds and fails appropriately. +- Maintenance mode sends the maintenance notice without chat processing. +- Staging `!d ` filtering remains unchanged if retained. +- `apps/auth` and `apps/api` failures produce the existing user notices while Meta still receives the immediate acknowledgment. + +## Risks and Mitigation + +| Risk | Mitigation | +|------|------------| +| Webhook acknowledgment is delayed by asynchronous work | Test acknowledgment timing independently from background processing. | +| TypeScript types create false confidence for untrusted JSON | Validate webhook and service-boundary data at runtime. | +| Streaming aggregation differs from Python | Reuse behavior cases and test chunk boundaries, trailing errors, and completion. | +| Markdown or splitting behavior regresses | Port the existing tests before changing implementation details. | +| Railway environment configuration differs | Compare staging variables and perform a staging smoke test before considering the migration complete. | +| The team loses the proven Python reference too early | Keep `legacy/whatsapp` intact until staging verification and add the brief rollback note there. | + +## References + +- Issue iaser-ai/ansari#358 +- Spec 321: `codev/specs/321-rfc-whatsapp-support-in-the-mo.md` +- Follow-up issues #359, #360, and #361 +- Issue #362 regarding real phone-number requirements +- Python reference implementation: `legacy/whatsapp` From 1d4b6c1965657df1e12dfae0f35b64552c4e479e Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 17:15:43 +0200 Subject: [PATCH 018/435] [Spec 358][Phase: phase_1] feat: scaffold apps/whatsapp with config, masked logging and errors --- apps/whatsapp/.env.ci | 12 + apps/whatsapp/.env.example | 192 +++++++++++ apps/whatsapp/.gitignore | 4 + apps/whatsapp/eslint.config.mjs | 17 + apps/whatsapp/package.json | 34 ++ apps/whatsapp/src/config.ts | 221 +++++++++++++ apps/whatsapp/src/errors.ts | 59 ++++ apps/whatsapp/src/logMasking.ts | 44 +++ apps/whatsapp/src/logger.ts | 162 ++++++++++ apps/whatsapp/tests/config.test.ts | 201 ++++++++++++ apps/whatsapp/tests/envTemplates.test.ts | 39 +++ apps/whatsapp/tests/logMasking.test.ts | 53 +++ apps/whatsapp/tests/logger.test.ts | 134 ++++++++ apps/whatsapp/tsconfig.json | 14 + apps/whatsapp/tsdown.config.ts | 9 + apps/whatsapp/vitest.config.ts | 7 + pnpm-lock.yaml | 390 ++++++++++------------- 17 files changed, 1372 insertions(+), 220 deletions(-) create mode 100644 apps/whatsapp/.env.ci create mode 100644 apps/whatsapp/.env.example create mode 100644 apps/whatsapp/.gitignore create mode 100644 apps/whatsapp/eslint.config.mjs create mode 100644 apps/whatsapp/package.json create mode 100644 apps/whatsapp/src/config.ts create mode 100644 apps/whatsapp/src/errors.ts create mode 100644 apps/whatsapp/src/logMasking.ts create mode 100644 apps/whatsapp/src/logger.ts create mode 100644 apps/whatsapp/tests/config.test.ts create mode 100644 apps/whatsapp/tests/envTemplates.test.ts create mode 100644 apps/whatsapp/tests/logMasking.test.ts create mode 100644 apps/whatsapp/tests/logger.test.ts create mode 100644 apps/whatsapp/tsconfig.json create mode 100644 apps/whatsapp/tsdown.config.ts create mode 100644 apps/whatsapp/vitest.config.ts diff --git a/apps/whatsapp/.env.ci b/apps/whatsapp/.env.ci new file mode 100644 index 00000000..3eb8f631 --- /dev/null +++ b/apps/whatsapp/.env.ci @@ -0,0 +1,12 @@ +# CI dummy environment for apps/whatsapp, mirroring apps/auth/.env.ci. Every value is +# deliberately, obviously fake; no repository secrets. CI loads this file: +# grep -v '^#' apps/whatsapp/.env.ci >> "$GITHUB_ENV" +# Not auto-loaded by any runtime (only .env is). The tests pass their own environment +# to buildConfig(); these values exist so every variable the service requires is present +# in CI (tests/envTemplates.test.ts checks that this file is a valid configuration). +DEPLOYMENT_TYPE=local +AUTH_WHATSAPP_API_KEY=placeholder-not-a-real-key +META_BUSINESS_PHONE_NUMBER_ID=000000000000000 +META_ACCESS_TOKEN_FROM_SYS_USER=placeholder-not-a-real-token +META_WEBHOOK_VERIFY_TOKEN=placeholder-not-a-real-verify-token +META_ANSARI_APP_SECRET=placeholder-not-a-real-app-secret diff --git a/apps/whatsapp/.env.example b/apps/whatsapp/.env.example new file mode 100644 index 00000000..ef411a7b --- /dev/null +++ b/apps/whatsapp/.env.example @@ -0,0 +1,192 @@ +# Copy this file to .env (apps/whatsapp/.env) and fill in the values. Never commit .env. +# Real environment variables (Railway) win over the file. +# +# Every variable keeps the name it had in legacy/whatsapp, so values already set on Railway +# work unchanged. src/config.ts validates all of this at start-up and names each bad variable. +# +# Booleans: write True or False (also accepted: true, false, 1, 0, the same as apps/api's MAINTENANCE_MODE). +# Anything else, such as yes, on or TRUE, stops start-up with an error naming the variable. + +# Where the service is deployed: local, development, staging or production. +# - local: the only environment where the MOCK_* switches may be used. +# - production: META_REPLY_BY_PHONE is refused. +# - everything but local and development logs one JSON object per line (Railway's format). +DEPLOYMENT_TYPE="local" + +# The port to listen on. Railway sets this itself; do not set it there. +# 3200 follows apps/api (3000) and apps/auth (3100). Local zrok tunnels must point here. +PORT="3200" + +# Sentry DSN for error tracking. +# 1. Log in at https://sentry.io, select your organization and project +# 2. Settings > Projects > [Your Project Name] > Client Keys (DSN) +# 3. Copy the DSN (https://xxxxx@xxxxx.ingest.sentry.io/xxxxx) +# Leave empty or omit to disable Sentry. +SENTRY_DSN="" + +###################################### Related to apps/api and apps/auth ###################################### + +# apps/api's base URL (WITHOUT any path). The client appends /api/v2/* to it. +# if local: "http://localhost:3000" +BACKEND_SERVER_URL="http://localhost:3000" + +# apps/auth's base URL (WITHOUT any path). The auth client appends /api/whatsapp/session to it. +# if local: "http://localhost:3100" +AUTH_SERVER_URL="http://localhost:3100" + +# API key that authenticates this service to apps/auth's /whatsapp endpoint. +# Sent as `Authorization: Bearer ` (issue #329). MUST be a key issued by apps/auth for this service. +AUTH_WHATSAPP_API_KEY="your_generated_secret_key_here" + +###################################### Related to CORS ###################################### + +# Comma-separated origins allowed to call this service. Usually not needed: BACKEND_SERVER_URL, +# "testserver" (GitHub Actions) and https://web.whatsapp.com are added automatically. +ORIGINS="https://api.ansari.chat,https://web.whatsapp.com" + +###################################### Related to WhatsApp Business and Meta ###################################### + +# Preface: you might be asking yourself: "ALL OF THESE CONFIGS JUST TO SET UP WHATSAPP?!" +# Yes :'D Meta's API/setup process is a bit complicated, which is why BSPs exist. +# https://www.reddit.com/r/WhatsappBusinessAPI/comments/1mwa0r6/difference_between_using_meta_whatsapp_cloud_api/ +# We decided to do it the old-fashioned way: straight to the main API. + +# Source 0: https://developers.facebook.com/docs/whatsapp/cloud-api/get-started +# Source 1: https://www.youtube.com/watch?v=KP6_BUw3i0U +# Watch until 32:25, skimming past the non-TypeScript code parts (the video's code is Python/Node) +# Source 2 (from the video): https://glitch.com/edit/#!/insidious-tartan-alvarezsaurus +# (the GET /whatsapp/v3 verification handshake in src/app.ts follows the same idea) + +# Testing the webhook locally (information only: this service does not read any variable for it). +# Meta needs a public URL, so a reserved zrok share forwards one to your machine. You need a zrok +# "share token" from its current holder: https://github.com/OdyAsh (sources 1 and 2). +# Alternatively, change the webhook URL altogether (sources 3 and 4). +# Source 1: https://dev.to/odyash/quickly-share-your-app-with-zrok-4ihp +# Source 2: https://openziti.discourse.group/t/how-do-i-use-a-reserved-share-on-different-devices/2379/2 +# Source 3: https://youtu.be/KP6_BUw3i0U?t=1294 +# (@21:33 and 25:30; they use glitch instead of zrok, so it only shows how to set up a webhook) +# Source 4 (where you change the callback URL, if the app's admins gave your Facebook account access): +# https://developers.facebook.com/apps/871020755148175/whatsapp-business/wa-settings/ +# NOTE 1: 871020755148175 is the test app's public id. If the link still fails after you get access, +# the admins most probably created a new test app. +# NOTE 2: the Callback URL looks like "https://.share.zrok.io/whatsapp/v3" +# This zrok URL is only for the "Ansari - Test" app, so use it only for local development, +# never in staging or production. (Python used /whatsapp/v2; the TypeScript service serves /whatsapp/v3.) +# NOTE 3: if a third party discovers the share token, generate a new one and put it in the callback URL of the +# *test* app. (The production app's callback URL differs, so that party cannot reach it, but we still do not +# want random calls hitting the test app.) +# The reserved share maps to your local port. To change it, release and reserve again: +# zrok release +# zrok reserve public localhost:3200 --unique-name "" +# (3200 is the PORT above; the Python service used 8001.) +# Why this is not a setting here: the Python config read META_WEBHOOK_ZROK_SHARE_TOKEN only to add +# ".share.zrok.io" to the CORS allow-list in local mode. Meta's webhooks are server-to-server and send no +# Origin header, so the entry did nothing and was not ported. + +META_API_VERSION="v26.0" + +# Phone number ID (from the Meta dashboard) +# NOTE 1: contact the team to see WhatsApp's 2 phone numbers: one for production, one for local/staging testing. +# NOTE 2: if you get this error: +# "Client error '400 Bad Request' for url 'https://graph.facebook.com/v26.0//messages'" +# then either: +# (1) Meta deleted the phone number id after long inactivity. Open source 1's video @6:11. Under "step 1" in the +# middle of the page, click the selection box with the live WhatsApp number, then "Get new test number". +# Wait a while, then copy the new number's id into META_BUSINESS_PHONE_NUMBER_ID. +# (2) Meta updated its API version and META_API_VERSION is outdated. Check source 1 @26:13 for the version +# shown next to `messages`. +# (3) you sent a message in an incorrect format. Check source 1, 26:10 -> 26:28, and click `messages`. +# Reference: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages +META_BUSINESS_PHONE_NUMBER_ID="your_phone_number_id_here" + +# System User access token (from the Meta dashboard) +# NOTE 1: source 1's video, 30:45 -> 32:15, shows where the access token comes from. +# NOTE 2: contact the team for their 3 access tokens: production app (Ansari), staging app (Ansari - Staging) +# and local/dev app (Ansari - Test). +# NOTE 3: to debug a token, open https://developers.facebook.com/tools/debug/accesstoken/?access_token= +META_ACCESS_TOKEN_FROM_SYS_USER="your_access_token_here" + +# Token for webhook verification (from the Meta dashboard): Meta sends it in the GET handshake and the service +# compares it in constant time. +META_WEBHOOK_VERIFY_TOKEN="<>" + +# Meta App Secret, used to verify the X-Hub-Signature-256 header on incoming webhooks, so only Meta can trigger +# the service. There is deliberately no default: a public default would let anyone forge signed webhooks. +# References: +# - https://developers.facebook.com/docs/graph-api/webhooks/getting-started#validate-payloads +# - https://developers.facebook.com/docs/facebook-login/security/ +# - https://stackoverflow.com/questions/76898751/how-to-find-app-secret-for-whatsapp-business-api +# Location: https://developers.facebook.com/ -> My Apps -> your app -> App Settings -> Basic -> App Secret ("Show") +# "Your app" is one of "Ansari - Test", "Ansari - Staging" or "Ansari". "Ansari - Test" is the one used for +# local development with a zrok webhook URL. +META_ANSARI_APP_SECRET="your_app_secret_here" + +# Address replies to the sender's phone number instead of their BSUID. Only for Meta's free test number, whose +# allowed-recipient list holds phone numbers, so it cannot message a BSUID (error 131030). A real number accepts +# BSUID replies. The service refuses to start with this set when DEPLOYMENT_TYPE=production. +META_REPLY_BY_PHONE="False" + +# Not read by the service. Only the operator script scripts/checkMetaSubscriptions.ts needs these (added in the +# plan's phase 7, the port of legacy/whatsapp/scripts/check_meta_subscriptions.py). See legacy/whatsapp/.env.example +# for the Messaging account ID and App ID notes, which move here with the script. +# META_MESSAGING_ACCOUNT_ID="your_messaging_account_id_here" +# META_ANSARI_APP_ID="your_app_id_here" + +###################################### Related to Chat Settings ###################################### + +# When True, every message gets a "down for maintenance" reply and is not processed. +# This is the WhatsApp service's own switch; it does NOT follow apps/api's MAINTENANCE_MODE. +WA_MAINTENANCE_MODE="False" + +# Hours of silence after which the next message starts a new thread +WHATSAPP_CHAT_RETENTION_HOURS="3" + +# Maximum age in seconds for incoming WhatsApp messages to be processed (24 hours = 86400 seconds). +# Older messages are rejected to avoid answering outdated messages. +WHATSAPP_MESSAGE_AGE_THRESHOLD_SECONDS="86400" + +###################################### Related to Test/Development/Logging ###################################### + +# Optional. Only needed for one manual check: "does Meta really accept a message sent to a BSUID?" +# A BSUID is Meta's per-user ID that replaces the phone number when a user hides it (looks like +# EG.1234567890123456789). You cannot make one up: it must belong to a real WhatsApp user who already messaged +# OUR business number. BSUIDs are per business portfolio, so yours only works with phone numbers owned by the same +# portfolio. Keep it private: never commit it, paste it in an issue or print it in logs. +# REAL_TEST_BSUID="" + +# Meta webhook response behavior +# Meta's webhooks require HTTP 200 responses to acknowledge receipt. +# True (production/staging/development/local): always return HTTP 200 to Meta, whatever went wrong inside. +# False (automated tests only): return real status codes (400, 500, ...) so tests can assert on them. +# NOTE: this should ALWAYS be True in production. +ALWAYS_RETURN_OK_TO_META="True" + +# Optional. Leave unset for DEBUG when DEPLOYMENT_TYPE=local and INFO everywhere else. +# Accepts DEBUG, INFO, WARNING or ERROR. +# LOGGING_LEVEL="INFO" + +###################################### Related to Service Provider Settings ###################################### + +# If True, use a mock Ansari client instead of real HTTP calls to apps/api. Useful for: +# - development without apps/api running +# - unit tests with simulated responses and realistic latency/errors +# - offline development, and no AI API cost +# Only allowed when DEPLOYMENT_TYPE=local. +MOCK_ANSARI_CLIENT="False" + +# If True, use a mock apps/auth client that issues fake tokens instead of calling apps/auth. +# Useful while apps/auth's /whatsapp endpoint is not available. Only allowed when DEPLOYMENT_TYPE=local. +MOCK_AUTH_CLIENT="False" + +# Optional, only with MOCK_AUTH_CLIENT=True: a real apps/auth JWT that the mock returns for every BSUID, so a mocked +# sign-in can talk to a real apps/api. Get one by logging in through apps/api (POST /api/v2/users/login). +# Leave unset to get fake tokens (which a real apps/api rejects). Every user would share this one account and +# thread, so the service refuses to start with it unless DEPLOYMENT_TYPE="local". +# MOCK_AUTH_TOKEN="" + +# If True, use a mock Meta API service instead of real HTTP calls to Meta's WhatsApp Cloud API. Useful for: +# - development when Meta credentials are not configured or invalid +# - testing the webhook flow without sending real WhatsApp messages +# - avoiding Meta API quota use and not affecting real users +# Only allowed when DEPLOYMENT_TYPE=local. +MOCK_META_API="False" diff --git a/apps/whatsapp/.gitignore b/apps/whatsapp/.gitignore new file mode 100644 index 00000000..2a470c6b --- /dev/null +++ b/apps/whatsapp/.gitignore @@ -0,0 +1,4 @@ +.env +.env.local +dist +node_modules diff --git a/apps/whatsapp/eslint.config.mjs b/apps/whatsapp/eslint.config.mjs new file mode 100644 index 00000000..f5c05f44 --- /dev/null +++ b/apps/whatsapp/eslint.config.mjs @@ -0,0 +1,17 @@ +import tseslint from 'typescript-eslint'; +import ansari from '@ansari/eslint-config/base'; + +// Same setup as apps/auth: the shared base is ignores-only, and ESLint 9 flat +// config needs an explicit `files` glob + TS parser or it lints nothing and +// still reports success. +export default [ + ...ansari, + ...tseslint.configs.recommended, + { + files: ['**/*.ts'], + languageOptions: { + parser: tseslint.parser, + parserOptions: { projectService: false, sourceType: 'module' }, + }, + }, +]; diff --git a/apps/whatsapp/package.json b/apps/whatsapp/package.json new file mode 100644 index 00000000..57e8d2f4 --- /dev/null +++ b/apps/whatsapp/package.json @@ -0,0 +1,34 @@ +{ + "name": "ansari-whatsapp", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "WhatsApp service for the Ansari monorepo: a TypeScript port of legacy/whatsapp (issue #358).", + "main": "src/index.ts", + "engines": { + "node": ">=22.18.0" + }, + "scripts": { + "dev": "tsx watch src/index.ts", + "build": "tsdown", + "start": "node dist/index.mjs", + "lint": "eslint .", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "dotenv": "^17.2.3", + "zod": "^4.3.5" + }, + "devDependencies": { + "@ansari/eslint-config": "workspace:*", + "@ansari/tsconfig": "workspace:*", + "@types/node": "^25.0.10", + "eslint": "catalog:", + "tsdown": "^0.22.14", + "tsx": "^4.21.0", + "typescript": "catalog:", + "typescript-eslint": "catalog:", + "vitest": "^4.1.11" + } +} diff --git a/apps/whatsapp/src/config.ts b/apps/whatsapp/src/config.ts new file mode 100644 index 00000000..2b68e70e --- /dev/null +++ b/apps/whatsapp/src/config.ts @@ -0,0 +1,221 @@ +/** + * Configuration for the WhatsApp service. + * + * Python counterpart: `legacy/whatsapp/src/ansari_whatsapp/utils/config.py` + * (Pydantic `BaseSettings`). Every variable keeps its Python name, so the values + * already set on Railway work unchanged. + * + * IMPORTANT: `.env.example` explains each setting (what it is for, allowed values, + * default, which environments use it). Keep the two in step. + * + * How this differs from Pydantic Settings: + * - Everything in `process.env` is a STRING. Pydantic turns "False" into `False`; + * here `"False"` would be a truthy string, so booleans go through `envBoolean`. + * - Nothing reads `.env` automatically. `index.ts` loads it once with `dotenv` + * (real environment variables win over the file, as in Pydantic). + * - Nothing validates by itself: `buildConfig()` runs the schema and throws a + * readable error naming each bad variable. + */ +import { z } from 'zod'; + +/** Mocks answer with canned data, so only `DEPLOYMENT_TYPE=local` may switch them on. */ +export const MOCK_FLAGS = ['MOCK_ANSARI_CLIENT', 'MOCK_AUTH_CLIENT', 'MOCK_META_API'] as const; + +/** + * A True/False switch, with the same spellings as apps/api's `MAINTENANCE_MODE`: + * true, false, True, False, 1, 0. Anything else ("yes", "TRUE", "") stops start-up + * instead of being guessed. `fallback` is the value when the variable is unset. + * + * Pydantic also accepted yes/no/on/off; check Railway's values use the spellings above. + */ +const envBoolean = (fallback: 'true' | 'false' = 'false') => + z + .enum(['true', 'false', 'True', 'False', '1', '0']) + .default(fallback) + .transform((v) => v.toLowerCase() === 'true' || v === '1'); + +/** + * A secret value that never prints. + * + * Python counterpart: Pydantic's `SecretStr`. `String(secret)`, `JSON.stringify(secret)`, + * template strings and `console.log(secret)` all show `**********`. Call `.reveal()` at + * the single place that really needs the value (an `Authorization` header, an HMAC key). + */ +export class Secret { + readonly #value: string; + + constructor(value: string) { + this.#value = value; + } + + reveal(): string { + return this.#value; + } + + toString(): string { + return '**********'; + } + + toJSON(): string { + return '**********'; + } + + [Symbol.for('nodejs.util.inspect.custom')](): string { + return 'Secret(**********)'; + } +} + +const secret = z.string().min(1).transform((raw) => new Secret(raw)); + +const rawSchema = z.object({ + // ---------- apps/api and apps/auth ---------- + /** apps/api's base URL, no path. The client appends /api/v2/*. */ + BACKEND_SERVER_URL: z.string().default('http://localhost:3000'), + /** apps/auth's base URL, no path. The auth client appends /api/whatsapp/session. */ + AUTH_SERVER_URL: z.string().default('http://localhost:3100'), + /** Authenticates this service to apps/auth's /whatsapp endpoint (`Authorization: Bearer `, issue #329). */ + AUTH_WHATSAPP_API_KEY: secret, + + // ---------- Meta Business API ---------- + META_API_VERSION: z.string().default('v26.0'), + META_BUSINESS_PHONE_NUMBER_ID: secret, + META_ACCESS_TOKEN_FROM_SYS_USER: secret, + META_WEBHOOK_VERIFY_TOKEN: secret, + /** + * Verifies webhook signatures (X-Hub-Signature-256). + * No default: a public default would let anyone forge signed webhooks. + * https://developers.facebook.com/docs/graph-api/webhooks/getting-started#validate-payloads + */ + META_ANSARI_APP_SECRET: secret, + /** + * Reply to the sender's phone number instead of their BSUID. Only for Meta's free test + * number, whose allowed-recipient list holds phone numbers, so it cannot message a BSUID + * (error 131030). A real number accepts BSUID replies. Refused in production. + */ + META_REPLY_BY_PHONE: envBoolean(), + + // ---------- this service ---------- + DEPLOYMENT_TYPE: z.enum(['local', 'development', 'staging', 'production']), + /** + * Meta needs an HTTP 200 for every webhook delivery. True: always answer 200, whatever + * went wrong inside. False (automated tests only): return real error statuses. + */ + ALWAYS_RETURN_OK_TO_META: envBoolean('true'), + /** Comma-separated CORS origins. BACKEND_SERVER_URL and a few fixed origins are added automatically. */ + ORIGINS: z.string().default(''), + + // ---------- chat ---------- + /** This service's own maintenance switch, independent of apps/api's MAINTENANCE_MODE. */ + WA_MAINTENANCE_MODE: envBoolean(), + /** Hours of silence after which the next message starts a new thread. */ + WHATSAPP_CHAT_RETENTION_HOURS: z.coerce.number().int().positive().default(3), + /** Messages older than this are rejected instead of answered (default one day). */ + WHATSAPP_MESSAGE_AGE_THRESHOLD_SECONDS: z.coerce.number().int().positive().default(86400), + + // ---------- logging ---------- + /** Empty means DEBUG when DEPLOYMENT_TYPE is local, INFO everywhere else. */ + LOGGING_LEVEL: z.string().default(''), + + // ---------- service providers ---------- + /** Optional Sentry DSN; unset disables error reporting. */ + SENTRY_DSN: z + .string() + .optional() + .transform((raw) => (raw && raw.length > 0 ? raw : undefined)) + .pipe(z.url('SENTRY_DSN must be a valid URL').optional()), + MOCK_ANSARI_CLIENT: envBoolean(), + MOCK_AUTH_CLIENT: envBoolean(), + /** A real JWT the mock auth client returns for every BSUID, so a mocked sign-in can talk to a real apps/api. */ + // Unset and "" both mean "not set": an empty string is falsy. + MOCK_AUTH_TOKEN: z + .string() + .optional() + .transform((raw) => (raw ? new Secret(raw) : undefined)), + MOCK_META_API: envBoolean(), + /** The port to listen on. Railway sets it; 3200 follows apps/api (3000) and apps/auth (3100). */ + PORT: z.coerce.number().int().min(1).max(65535).default(3200), +}); + +/** + * The cross-field rules. Python counterpart: the `@model_validator(mode="after")` methods. + * Each one reports against the variable the operator has to change. + */ +const schema = rawSchema + .superRefine((cfg, ctx) => { + if (cfg.DEPLOYMENT_TYPE === 'local') return; + // Mocks answer with canned data (and MOCK_AUTH_TOKEN puts every user in one + // account), so only local may use them. + const enabled: string[] = MOCK_FLAGS.filter((name) => cfg[name]); + if (cfg.MOCK_AUTH_TOKEN) enabled.push('MOCK_AUTH_TOKEN'); + if (enabled.length > 0) { + ctx.addIssue({ + code: 'custom', + path: [enabled[0]!], + message: `${enabled.join(', ')} only allowed when DEPLOYMENT_TYPE=local (got ${cfg.DEPLOYMENT_TYPE})`, + }); + } + }) + .superRefine((cfg, ctx) => { + // Production answers on a real number, which takes BSUIDs, so no phone number should be read there. + if (cfg.META_REPLY_BY_PHONE && cfg.DEPLOYMENT_TYPE === 'production') { + ctx.addIssue({ + code: 'custom', + path: ['META_REPLY_BY_PHONE'], + message: 'META_REPLY_BY_PHONE is not allowed when DEPLOYMENT_TYPE=production', + }); + } + }) + .transform((cfg) => { + const loggingLevel = cfg.LOGGING_LEVEL || (cfg.DEPLOYMENT_TYPE === 'local' ? 'DEBUG' : 'INFO'); + + const origins = cfg.ORIGINS.replace(/^"|"$/g, '') + .split(',') + .map((o) => o.trim()) + .filter((o) => o.length > 0); + // BACKEND_SERVER_URL, the GitHub Actions testserver and WhatsApp Web are always allowed. + for (const extra of [cfg.BACKEND_SERVER_URL, 'testserver', 'https://web.whatsapp.com']) { + if (!origins.includes(extra)) origins.push(extra); + } + + return { + ...cfg, + LOGGING_LEVEL: loggingLevel, + ORIGINS: origins, + /** https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages */ + META_API_URL: `https://graph.facebook.com/${cfg.META_API_VERSION}/${cfg.META_BUSINESS_PHONE_NUMBER_ID.reveal()}/messages`, + }; + }); + +export type Env = z.output; + +/** Every variable the service reads. The env-template test checks each one is documented in `.env.example`. */ +export const CONFIG_KEYS = Object.keys(rawSchema.shape); + +/** + * Validate an environment and return the settings, or throw one error that names every bad variable. + * + * Takes the environment as an argument (default: the real one) so tests can pass their own + * object. Python counterpart: `WhatsAppSettings()`; there the tests had to patch + * `os.environ` and clear an `lru_cache`. + */ +export function buildConfig(env: NodeJS.ProcessEnv = process.env): Env { + const result = schema.safeParse(env); + if (!result.success) { + const problems = result.error.issues.map((i) => `${i.path.join('.') || '(config)'}: ${i.message}`); + throw new Error(`WhatsApp service configuration is invalid (see apps/whatsapp/.env.example):\n ${problems.join('\n ')}`); + } + return result.data; +} + +let cached: Env | undefined; + +/** The process-wide settings, validated on first use. Python counterpart: `get_settings()`. */ +export function getEnv(): Env { + cached ??= buildConfig(); + return cached; +} + +/** Test-only: forget the cached settings. Python counterpart: `get_settings.cache_clear()`. */ +export function resetEnvCache(): void { + cached = undefined; +} diff --git a/apps/whatsapp/src/errors.ts b/apps/whatsapp/src/errors.ts new file mode 100644 index 00000000..57308955 --- /dev/null +++ b/apps/whatsapp/src/errors.ts @@ -0,0 +1,59 @@ +/** + * Custom errors for the WhatsApp service. + * + * Python counterpart: `legacy/whatsapp/src/ansari_whatsapp/utils/exceptions.py`. + * + * `class X extends Error` is the TypeScript form of `class X(Exception)`. Each class sets + * `name` so a log line or Sentry event shows `AuthKeyRejectedError`, not just `Error`. + */ + +/** Meta sent a message payload that is missing an expected key. */ +export class UnexpectedMetaPayloadError extends Error { + override readonly name = 'UnexpectedMetaPayloadError'; + + /** Phone number or BSUID we can still use to reach the sender, if the payload had one. */ + readonly replyTo: string | undefined; + + constructor(message: string, replyTo?: string) { + super(message); + this.replyTo = replyTo; + } +} + +/** Exchanging a BSUID for a JWT with apps/auth failed (an outage, a 500, or a network fault). */ +export class AuthTokenError extends Error { + override readonly name: string = 'AuthTokenError'; +} + +/** apps/auth answered 400: our request was malformed, which is a bug here. Never retried. */ +export class AuthBadRequestError extends AuthTokenError { + override readonly name = 'AuthBadRequestError'; +} + +/** apps/auth answered 401: our API key is bad (missing, revoked, expired, out of budget). Needs an operator. */ +export class AuthKeyRejectedError extends AuthTokenError { + override readonly name = 'AuthKeyRejectedError'; +} + +/** apps/auth answered 403: this user is banned. */ +export class AuthUserBannedError extends AuthTokenError { + override readonly name = 'AuthUserBannedError'; +} + +/** apps/auth answered 429: this user's exchange budget is spent. The key is fine. */ +export class AuthRateLimitedError extends AuthTokenError { + override readonly name = 'AuthRateLimitedError'; + + /** Seconds until the user's budget frees up. */ + readonly retryAfter: number; + + constructor(message: string, retryAfter: number) { + super(message); + this.retryAfter = retryAfter; + } +} + +/** Base error for Ansari client (apps/api) failures. */ +export class AnsariClientError extends Error { + override readonly name: string = 'AnsariClientError'; +} diff --git a/apps/whatsapp/src/logMasking.ts b/apps/whatsapp/src/logMasking.ts new file mode 100644 index 00000000..4a8ee6bc --- /dev/null +++ b/apps/whatsapp/src/logMasking.ts @@ -0,0 +1,44 @@ +/** + * Masking for values about to be logged: hide phone numbers, BSUIDs and message ids in + * text and structures. + * + * Python counterpart: `legacy/whatsapp/src/ansari_whatsapp/utils/log_masking.py`. + */ + +// A BSUID is a two-letter country code, a dot, then up to 128 letters or digits ("US.1349..."); +// a parent BSUID has ".ENT." after the country code. A message id is "wamid." plus base64 that +// carries the user's phone number. A phone number may contain spaces, hyphens, dots and +// parentheses. Meta's formats: business-scoped-user-ids and phone-numbers docs. +// https://developers.facebook.com/docs/whatsapp/business-scoped-user-ids +// +// The `g` flag makes `replace` change every match, like Python's `re.sub`. A regex with `g` +// remembers its position between `.test()` calls, which is why these are only used with `replace`. +const MESSAGE_ID = /wamid\.[A-Za-z0-9+/=_-]+/g; +const BSUID = /\b[A-Z]{2}\.(?:ENT\.)?[A-Za-z0-9]{1,128}\b/g; +// Eight digits or more, so a 6 or 7 digit Meta error code stays readable +const PHONE = /[+(]?\d(?:[\s().-]{0,2}\d){7,}/g; + +/** Replace anything shaped like a message id, BSUID or phone number with a placeholder. */ +export function maskIdentifiers(text: string): string { + return text.replace(MESSAGE_ID, '').replace(BSUID, '').replace(PHONE, ''); +} + +/** + * Return `value` with its structure intact but every string masked as ``, + * except under `safeKeys`. + * + * `unknown` is TypeScript's "could be anything, check before use" type; the `typeof` and + * `Array.isArray` checks below narrow it, as `isinstance` does in Python. + */ +export function redactValues(value: unknown, safeKeys: ReadonlySet, key?: string): unknown { + if (Array.isArray(value)) { + return value.map((item) => redactValues(item, safeKeys, key)); + } + if (value !== null && typeof value === 'object') { + return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redactValues(v, safeKeys, k)])); + } + if (typeof value === 'string' && !(key !== undefined && safeKeys.has(key))) { + return ``; + } + return value; +} diff --git a/apps/whatsapp/src/logger.ts b/apps/whatsapp/src/logger.ts new file mode 100644 index 00000000..1b52b36e --- /dev/null +++ b/apps/whatsapp/src/logger.ts @@ -0,0 +1,162 @@ +/** + * Logging for the WhatsApp service. + * + * Python counterpart: `legacy/whatsapp/src/ansari_whatsapp/utils/app_logger.py` (Loguru). + * + * Railway: outside local development, every log line is one JSON object on stdout, which + * Railway parses into searchable fields (https://docs.railway.com/guides/logs#structured-logs). + * To find everything one message did, search `@request_id:` in the log explorer (the id + * is also returned to the caller as the `X-Request-ID` header). + * + * Differences from the Python version: + * - Loguru is a global you configure on import. Here `createLogger()` returns an object, so + * a test can build one with its own sinks and nothing global changes. + * - Python's `contextvars.ContextVar` becomes Node's `AsyncLocalStorage`: a value that follows + * an async call chain, including work started after the HTTP response was sent. + * - The JSON entry has no `file`, `line` or `function` keys: Loguru read them from the call + * stack, and Node has no cheap equivalent. The keys Railway reads (`level`, `message`) and + * `request_id` are unchanged. + */ +import { AsyncLocalStorage } from 'node:async_hooks'; + +export type LogLevel = 'debug' | 'info' | 'warn' | 'error'; + +/** One log call, before formatting. Python counterpart: Loguru's `record`. */ +export interface LogRecord { + level: LogLevel; + message: string; + requestId: string; + error?: unknown; +} + +/** The JSON object Railway expects. */ +export interface LogEntry { + level: LogLevel; + message: string; + request_id: string; + exception?: { type: string | null; value: string | null }; +} + +const LEVEL_ORDER: Record = { debug: 10, info: 20, warn: 30, error: 40 }; + +/** LOGGING_LEVEL accepts the Python spellings too (WARNING, CRITICAL). */ +const LEVEL_NAMES: Record = { + TRACE: 'debug', + DEBUG: 'debug', + INFO: 'info', + SUCCESS: 'info', + WARN: 'warn', + WARNING: 'warn', + ERROR: 'error', + CRITICAL: 'error', +}; + +// ---------- request id (Python: request_id_var) ---------- + +const requestIdStorage = new AsyncLocalStorage(); + +/** The id of the HTTP request being handled, or "none" outside a request. */ +export function getRequestId(): string { + return requestIdStorage.getStore() ?? 'none'; +} + +/** Run `fn` (and everything it awaits) with `requestId` attached to every log line. */ +export function runWithRequestId(requestId: string, fn: () => T): T { + return requestIdStorage.run(requestId, fn); +} + +// ---------- formatting ---------- + +/** JSON lines everywhere except local development and GitHub Actions. */ +export function shouldUseJsonLogs(deploymentType: string, githubActions: string | undefined): boolean { + return !['local', 'development'].includes(deploymentType) && githubActions !== 'true'; +} + +/** + * Turn a record into the JSON object Railway expects. + * + * `message` and `level` are the two keys Railway reads; every other key becomes a field you + * can search with `@name:value`. Railway adds the timestamp itself, so none is included. + */ +export function buildLogEntry(record: LogRecord): LogEntry { + const entry: LogEntry = { + level: record.level, + message: record.message, + request_id: record.requestId, + }; + if (record.error !== undefined && record.error !== null) { + const err = record.error; + entry.exception = { + type: err instanceof Error ? err.name : typeof err, + value: err instanceof Error ? err.message : String(err), + }; + } + return entry; +} + +/** Format for local development: one readable line. */ +export function formatReadableLine(record: LogRecord, now: Date = new Date()): string { + const time = now.toISOString().replace('T', ' ').slice(0, 19); + const base = `${time} | ${record.level.toUpperCase().padEnd(5)} | ${record.message}`; + if (record.error === undefined || record.error === null) return base; + const detail = record.error instanceof Error ? `${record.error.name}: ${record.error.message}` : String(record.error); + return `${base} | ${detail}`; +} + +// ---------- logger ---------- + +/** Where log lines go. Injectable so tests can capture them. */ +export interface LogSinks { + /** Railway marks everything on stderr as an error, so JSON lines must go to stdout. */ + stdout: (line: string) => void; + stderr: (line: string) => void; +} + +const processSinks: LogSinks = { + stdout: (line) => process.stdout.write(line), + stderr: (line) => process.stderr.write(line), +}; + +export interface LoggerOptions { + deploymentType: string; + /** DEBUG, INFO, WARNING or ERROR (any case). */ + level: string; + /** Value of the GITHUB_ACTIONS environment variable. */ + githubActions?: string | undefined; + sinks?: LogSinks; +} + +export interface Logger { + debug(message: string): void; + info(message: string): void; + warn(message: string, error?: unknown): void; + error(message: string, error?: unknown): void; +} + +export function createLogger(options: LoggerOptions): Logger { + const threshold = LEVEL_NAMES[options.level.toUpperCase()]; + if (threshold === undefined) { + throw new Error(`Unknown LOGGING_LEVEL "${options.level}" (use DEBUG, INFO, WARNING or ERROR)`); + } + const useJson = shouldUseJsonLogs(options.deploymentType, options.githubActions); + const sinks = options.sinks ?? processSinks; + + function log(level: LogLevel, message: string, error?: unknown): void { + if (LEVEL_ORDER[level] < LEVEL_ORDER[threshold!]) return; + const record: LogRecord = { level, message, requestId: getRequestId(), ...(error !== undefined ? { error } : {}) }; + if (useJson) { + // JSON.stringify escapes an embedded newline, so the whole object stays on one line + // (Railway cannot parse an object split over lines). + sinks.stdout(JSON.stringify(buildLogEntry(record)) + '\n'); + } else { + sinks.stderr(formatReadableLine(record) + '\n'); + } + } + + return { + debug: (message) => log('debug', message), + info: (message) => log('info', message), + warn: (message, error) => log('warn', message, error), + error: (message, error) => log('error', message, error), + }; +} diff --git a/apps/whatsapp/tests/config.test.ts b/apps/whatsapp/tests/config.test.ts new file mode 100644 index 00000000..b97fe6d9 --- /dev/null +++ b/apps/whatsapp/tests/config.test.ts @@ -0,0 +1,201 @@ +/** + * Config rules. + * + * Python tests ported: test_bsuid_auth_flow.py (mock flags and MOCK_AUTH_TOKEN refused outside + * local, META_REPLY_BY_PHONE off by default and refused in production) and + * test_environment_behaviour.py (app secret required, log level defaults). + * + * `buildConfig(env)` takes the environment as an object, so no test touches `process.env` + * (the Python tests patched `os.environ` and cleared an `lru_cache` around every case). + * `getEnv`/`resetEnvCache` are named like apps/api's. + */ +import { describe, expect, it } from 'vitest'; +import { buildConfig, getEnv, MOCK_FLAGS, resetEnvCache, Secret } from '../src/config'; + +/** The smallest valid environment: every variable without a default. */ +function env(overrides: Record = {}): NodeJS.ProcessEnv { + const base: Record = { + DEPLOYMENT_TYPE: 'local', + AUTH_WHATSAPP_API_KEY: 'test-key', + META_BUSINESS_PHONE_NUMBER_ID: '123456', + META_ACCESS_TOKEN_FROM_SYS_USER: 'test-token', + META_WEBHOOK_VERIFY_TOKEN: 'test-verify', + META_ANSARI_APP_SECRET: 'test-secret', + }; + return { ...base, ...overrides }; +} + +describe('defaults', () => { + it('uses the documented defaults', () => { + const cfg = buildConfig(env()); + expect(cfg.BACKEND_SERVER_URL).toBe('http://localhost:3000'); + expect(cfg.AUTH_SERVER_URL).toBe('http://localhost:3100'); + expect(cfg.META_API_VERSION).toBe('v26.0'); + expect(cfg.WHATSAPP_CHAT_RETENTION_HOURS).toBe(3); + expect(cfg.WHATSAPP_MESSAGE_AGE_THRESHOLD_SECONDS).toBe(86400); + expect(cfg.ALWAYS_RETURN_OK_TO_META).toBe(true); + expect(cfg.WA_MAINTENANCE_MODE).toBe(false); + expect(cfg.PORT).toBe(3200); + }); + + it('builds the Meta send URL from the version and the phone number id', () => { + expect(buildConfig(env()).META_API_URL).toBe('https://graph.facebook.com/v26.0/123456/messages'); + }); +}); + +describe('booleans', () => { + it('reads "False" as false (a plain string check would call it true)', () => { + expect(buildConfig(env({ WA_MAINTENANCE_MODE: 'False' })).WA_MAINTENANCE_MODE).toBe(false); + }); + + it.each(['True', 'true', '1'])('reads %s as true', (value) => { + expect(buildConfig(env({ WA_MAINTENANCE_MODE: value })).WA_MAINTENANCE_MODE).toBe(true); + }); + + it.each(['False', 'false', '0'])('reads %s as false', (value) => { + expect(buildConfig(env({ WA_MAINTENANCE_MODE: value })).WA_MAINTENANCE_MODE).toBe(false); + }); + + // Pydantic accepted these; apps/api's switches do not, and neither does this service. + it.each(['yes', 'on', 'TRUE', 'maybe', ''])('refuses "%s" instead of guessing', (value) => { + expect(() => buildConfig(env({ WA_MAINTENANCE_MODE: value }))).toThrow(/WA_MAINTENANCE_MODE/); + }); + + it('ALWAYS_RETURN_OK_TO_META is on unless set to false', () => { + expect(buildConfig(env()).ALWAYS_RETURN_OK_TO_META).toBe(true); + expect(buildConfig(env({ ALWAYS_RETURN_OK_TO_META: 'False' })).ALWAYS_RETURN_OK_TO_META).toBe(false); + }); +}); + +describe('required settings', () => { + it.each(['local', 'staging', 'production'])('fails without the app secret (%s)', (deploymentType) => { + expect(() => buildConfig(env({ DEPLOYMENT_TYPE: deploymentType, META_ANSARI_APP_SECRET: undefined }))).toThrow( + /META_ANSARI_APP_SECRET/, + ); + }); + + it('names every bad variable in one error, whatever order they are listed in', () => { + const message = (() => { + try { + buildConfig({ DEPLOYMENT_TYPE: 'moon' }); + } catch (error) { + return (error as Error).message; + } + return ''; + })(); + for (const name of ['DEPLOYMENT_TYPE', 'AUTH_WHATSAPP_API_KEY', 'META_ANSARI_APP_SECRET']) { + expect(message).toContain(name); + } + }); +}); + +describe('secrets', () => { + it('never prints a secret, however it is logged', () => { + const cfg = buildConfig(env({ META_ANSARI_APP_SECRET: 'super-secret-value' })); + expect(cfg.META_ANSARI_APP_SECRET).toBeInstanceOf(Secret); + expect(String(cfg.META_ANSARI_APP_SECRET)).not.toContain('super-secret-value'); + expect(`${cfg.META_ANSARI_APP_SECRET}`).not.toContain('super-secret-value'); + expect(JSON.stringify(cfg)).not.toContain('super-secret-value'); + }); + + it('reveals the value only on request', () => { + expect(buildConfig(env({ META_ANSARI_APP_SECRET: 'super-secret-value' })).META_ANSARI_APP_SECRET.reveal()).toBe( + 'super-secret-value', + ); + }); +}); + +describe('mocks are only for local', () => { + it.each(MOCK_FLAGS)('%s is allowed locally', (flag) => { + expect(buildConfig(env({ DEPLOYMENT_TYPE: 'local', [flag]: 'True' }))[flag]).toBe(true); + }); + + it.each(MOCK_FLAGS.flatMap((flag) => ['development', 'staging', 'production'].map((type) => [flag, type] as const)))( + '%s is refused when DEPLOYMENT_TYPE=%s', + (flag, deploymentType) => { + expect(() => buildConfig(env({ DEPLOYMENT_TYPE: deploymentType, [flag]: 'True' }))).toThrow(new RegExp(flag)); + }, + ); + + it.each([ + ['local', true], + ['staging', false], + ['production', false], + ] as const)('a shared mock token in %s is allowed: %s', (deploymentType, allowed) => { + const attempt = () => buildConfig(env({ DEPLOYMENT_TYPE: deploymentType, MOCK_AUTH_TOKEN: 'a.real.jwt' })); + if (allowed) { + expect(attempt().MOCK_AUTH_TOKEN?.reveal()).toBe('a.real.jwt'); + } else { + expect(attempt).toThrow(/MOCK_AUTH_TOKEN/); + } + }); + + it('an empty mock token is fine in any environment', () => { + expect(buildConfig(env({ DEPLOYMENT_TYPE: 'production', MOCK_AUTH_TOKEN: '' })).DEPLOYMENT_TYPE).toBe('production'); + }); +}); + +describe('META_REPLY_BY_PHONE', () => { + it('defaults to off', () => { + expect(buildConfig(env()).META_REPLY_BY_PHONE).toBe(false); + }); + + it.each(['local', 'development', 'staging'])('is allowed in %s', (deploymentType) => { + expect(buildConfig(env({ DEPLOYMENT_TYPE: deploymentType, META_REPLY_BY_PHONE: 'True' })).META_REPLY_BY_PHONE).toBe(true); + }); + + it('is refused in production', () => { + expect(() => buildConfig(env({ DEPLOYMENT_TYPE: 'production', META_REPLY_BY_PHONE: 'True' }))).toThrow( + /META_REPLY_BY_PHONE is not allowed when DEPLOYMENT_TYPE=production/, + ); + }); +}); + +describe('log level', () => { + it.each([ + ['local', 'DEBUG'], + ['staging', 'INFO'], + ['production', 'INFO'], + ])('defaults to the right level in %s', (deploymentType, expected) => { + expect(buildConfig(env({ DEPLOYMENT_TYPE: deploymentType })).LOGGING_LEVEL).toBe(expected); + }); + + it('an explicit level wins', () => { + expect(buildConfig(env({ LOGGING_LEVEL: 'WARNING' })).LOGGING_LEVEL).toBe('WARNING'); + }); +}); + +describe('ORIGINS', () => { + it('always allows the backend, the CI test server and WhatsApp Web', () => { + expect(buildConfig(env()).ORIGINS).toEqual(['http://localhost:3000', 'testserver', 'https://web.whatsapp.com']); + }); + + it('keeps configured origins first and does not repeat one', () => { + const cfg = buildConfig(env({ ORIGINS: '"https://api.ansari.chat, https://web.whatsapp.com"' })); + expect(cfg.ORIGINS).toEqual(['https://api.ansari.chat', 'https://web.whatsapp.com', 'http://localhost:3000', 'testserver']); + }); +}); + +describe('MAINTENANCE_MODE is not this service\'s switch', () => { + it('ignores the variable apps/api uses', () => { + expect(buildConfig(env({ MAINTENANCE_MODE: 'true' })).WA_MAINTENANCE_MODE).toBe(false); + }); +}); + +describe('getEnv cache', () => { + it('validates the real environment once and can be reset', () => { + resetEnvCache(); + const saved = { ...process.env }; + Object.assign(process.env, env()); + try { + const first = getEnv(); + expect(getEnv()).toBe(first); + resetEnvCache(); + expect(getEnv()).not.toBe(first); + } finally { + for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key]; + Object.assign(process.env, saved); + resetEnvCache(); + } + }); +}); diff --git a/apps/whatsapp/tests/envTemplates.test.ts b/apps/whatsapp/tests/envTemplates.test.ts new file mode 100644 index 00000000..4d670266 --- /dev/null +++ b/apps/whatsapp/tests/envTemplates.test.ts @@ -0,0 +1,39 @@ +/** + * The two environment templates stay in step with the config. + * + * Python counterpart: none (the Python `.env.example` was never checked). apps/auth has the + * same kind of test, `tests/env-templates.test.ts`. + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { parse } from 'dotenv'; +import { describe, expect, it } from 'vitest'; +import { buildConfig, CONFIG_KEYS } from '../src/config'; + +const root = join(import.meta.dirname, '..'); +const read = (name: string) => readFileSync(join(root, name), 'utf8'); + +describe('.env.example', () => { + it('is a valid configuration as written', () => { + expect(() => buildConfig(parse(read('.env.example')))).not.toThrow(); + }); + + it('documents every setting, active or as a commented example', () => { + const text = read('.env.example'); + const missing = CONFIG_KEYS.filter((key) => !new RegExp(`^#?\\s*${key}=`, 'm').test(text)); + expect(missing).toEqual([]); + }); + + it('does not set the retired zrok variable', () => { + expect(read('.env.example')).not.toMatch(/^META_WEBHOOK_ZROK_SHARE_TOKEN=/m); + }); +}); + +describe('.env.ci', () => { + it('is a valid configuration (every required variable is present)', () => { + const lines = read('.env.ci') + .split(/\r?\n/) + .filter((line) => line.trim() !== '' && !line.startsWith('#')); + expect(() => buildConfig(parse(lines.join('\n')))).not.toThrow(); + }); +}); diff --git a/apps/whatsapp/tests/logMasking.test.ts b/apps/whatsapp/tests/logMasking.test.ts new file mode 100644 index 00000000..a1940869 --- /dev/null +++ b/apps/whatsapp/tests/logMasking.test.ts @@ -0,0 +1,53 @@ +/** + * Masking of identifiers before they reach a log. + * + * Python tests ported: the `test_masking_hides_identifier_shapes_and_leaves_ordinary_text` + * table in test_meta_sender_logging.py (identical inputs and expected outputs), plus cases + * for `redact_values`, which the Python suite only exercised through the Meta sender. + */ +import { describe, expect, it } from 'vitest'; +import { maskIdentifiers, redactValues } from '../src/logMasking'; + +describe('maskIdentifiers', () => { + it.each([ + ['Recipient 201234567899 not allowed', 'Recipient not allowed'], + ['Recipient +20 123 456-7899 not allowed', 'Recipient not allowed'], + ['Recipient (631) 555-1234 not allowed', 'Recipient not allowed'], + ['user EG.3225570644499982 blocked', 'user blocked'], + ['user US.ENT.11815799212886844830 blocked', 'user blocked'], + ['id wamid.HBgLMTY1MDM4Nzk0MzkVAgARGBI1RjQy= end', 'id end'], + ['(#131030) Recipient phone number not in allowed list', '(#131030) Recipient phone number not in allowed list'], + ['code 2655007 and trace Axly7O1UTgCLGu6n8EXWWTD', 'code 2655007 and trace Axly7O1UTgCLGu6n8EXWWTD'], + ])('%s', (text, masked) => { + expect(maskIdentifiers(text)).toBe(masked); + }); + + it('masks every occurrence, not just the first', () => { + expect(maskIdentifiers('US.111 and US.222 and 201234567899 and 201234567800')).toBe(' and and and '); + }); + + it('gives the same answer when called twice (a shared regex must not remember its position)', () => { + const text = 'user US.13491208655302741918'; + expect(maskIdentifiers(text)).toBe(maskIdentifiers(text)); + }); +}); + +describe('redactValues', () => { + const safe = new Set(['type', 'messaging_product']); + + it('keeps the structure and replaces strings with their length', () => { + expect(redactValues({ to: '201234567899', text: { body: 'hello' }, type: 'text' }, safe)).toEqual({ + to: '', + text: { body: '' }, + type: 'text', + }); + }); + + it('applies the parent key to every item of a list', () => { + expect(redactValues({ type: ['a', 'b'], other: ['c'] }, safe)).toEqual({ type: ['a', 'b'], other: [''] }); + }); + + it('leaves numbers, booleans and null alone', () => { + expect(redactValues({ code: 131030, ok: false, none: null }, safe)).toEqual({ code: 131030, ok: false, none: null }); + }); +}); diff --git a/apps/whatsapp/tests/logger.test.ts b/apps/whatsapp/tests/logger.test.ts new file mode 100644 index 00000000..4abd11bb --- /dev/null +++ b/apps/whatsapp/tests/logger.test.ts @@ -0,0 +1,134 @@ +/** + * Railway-style JSON logs. + * + * Python tests ported: test_railway_logging.py. Cases that depended on Loguru's call-stack + * fields (file, line, function) are dropped on purpose; see src/logger.ts. + */ +import { describe, expect, it } from 'vitest'; +import { + buildLogEntry, + createLogger, + getRequestId, + runWithRequestId, + shouldUseJsonLogs, + type LogRecord, + type LogSinks, +} from '../src/logger'; + +function record(overrides: Partial = {}): LogRecord { + return { level: 'info', message: 'hello', requestId: 'req-123', ...overrides }; +} + +function capture(): { sinks: LogSinks; out: string[]; err: string[] } { + const out: string[] = []; + const err: string[] = []; + return { out, err, sinks: { stdout: (l) => out.push(l), stderr: (l) => err.push(l) } }; +} + +describe('log entry', () => { + it('has the message and level keys Railway reads', () => { + const entry = buildLogEntry(record({ message: 'Created a new thread' })); + expect(entry.message).toBe('Created a new thread'); + expect(entry.level).toBe('info'); + }); + + it('carries the request id as a searchable field', () => { + expect(buildLogEntry(record()).request_id).toBe('req-123'); + }); + + it('has no user id field', () => { + expect(buildLogEntry(record())).not.toHaveProperty('user_id'); + }); + + it('includes exception details as type and value', () => { + const entry = buildLogEntry(record({ level: 'error', error: new TypeError('bad') })); + expect(entry.exception).toEqual({ type: 'TypeError', value: 'bad' }); + }); +}); + +describe('JSON vs readable logs', () => { + it.each([ + ['local', undefined, false], + ['development', undefined, false], + ['staging', undefined, true], + ['production', undefined, true], + ['staging', 'true', false], // CI never emits JSON, whatever the deployment type + ['production', 'false', true], + ] as const)('%s with GITHUB_ACTIONS=%s uses JSON: %s', (deploymentType, githubActions, expected) => { + expect(shouldUseJsonLogs(deploymentType, githubActions)).toBe(expected); + }); + + it('writes one JSON object on one line to stdout, nothing to stderr', () => { + const { sinks, out, err } = capture(); + createLogger({ deploymentType: 'production', level: 'INFO', sinks }).info('line one\nline two'); + + expect(err).toEqual([]); // stderr would make Railway show it as an error + expect(out).toHaveLength(1); + expect(out[0]!.match(/\n/g)).toHaveLength(1); // an embedded newline is escaped inside the JSON + expect(JSON.parse(out[0]!).message).toBe('line one\nline two'); + }); + + it('writes readable lines to stderr in local development', () => { + const { sinks, out, err } = capture(); + createLogger({ deploymentType: 'local', level: 'DEBUG', sinks }).info('hello'); + + expect(out).toEqual([]); + expect(err[0]).toMatch(/\| INFO {2}\| hello\n$/); + }); +}); + +describe('levels', () => { + it('drops messages below the configured level', () => { + const { sinks, out } = capture(); + const logger = createLogger({ deploymentType: 'production', level: 'WARNING', sinks }); + logger.debug('d'); + logger.info('i'); + logger.warn('w'); + logger.error('e'); + expect(out.map((l) => JSON.parse(l).level)).toEqual(['warn', 'error']); + }); + + it('refuses an unknown level instead of logging nothing', () => { + expect(() => createLogger({ deploymentType: 'local', level: 'LOUD' })).toThrow(/LOGGING_LEVEL/); + }); +}); + +describe('request id', () => { + it('defaults to "none" outside a request', () => { + expect(getRequestId()).toBe('none'); + }); + + it('follows the async chain, including work after an await', async () => { + const { sinks, out } = capture(); + const logger = createLogger({ deploymentType: 'production', level: 'INFO', sinks }); + + await runWithRequestId('req-abc', async () => { + await new Promise((resolve) => setTimeout(resolve, 5)); + logger.info('after the await'); + }); + logger.info('outside'); + + expect(out.map((l) => JSON.parse(l).request_id)).toEqual(['req-abc', 'none']); + }); + + it('keeps two overlapping requests apart', async () => { + const { sinks, out } = capture(); + const logger = createLogger({ deploymentType: 'production', level: 'INFO', sinks }); + + await Promise.all([ + runWithRequestId('one', async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + logger.info('a'); + }), + runWithRequestId('two', async () => { + await new Promise((resolve) => setTimeout(resolve, 1)); + logger.info('b'); + }), + ]); + + expect(out.map((l) => JSON.parse(l))).toEqual([ + { level: 'info', message: 'b', request_id: 'two' }, + { level: 'info', message: 'a', request_id: 'one' }, + ]); + }); +}); diff --git a/apps/whatsapp/tsconfig.json b/apps/whatsapp/tsconfig.json new file mode 100644 index 00000000..d265b0ce --- /dev/null +++ b/apps/whatsapp/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "@ansari/tsconfig/base.json", + "compilerOptions": { + "noEmit": true, + "target": "es2022", + "module": "esnext", + "moduleResolution": "bundler", + "lib": ["esnext"], + "types": ["node"], + "isolatedModules": true, + "verbatimModuleSyntax": true + }, + "include": ["src/**/*.ts", "tests/**/*.ts", "tsdown.config.ts", "vitest.config.ts"] +} diff --git a/apps/whatsapp/tsdown.config.ts b/apps/whatsapp/tsdown.config.ts new file mode 100644 index 00000000..15a31cbf --- /dev/null +++ b/apps/whatsapp/tsdown.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'tsdown'; + +// One bundled ESM file, so `node dist/index.mjs` runs without a TypeScript step. +export default defineConfig({ + entry: './src/index.ts', + format: 'esm', + outDir: './dist', + clean: true, +}); diff --git a/apps/whatsapp/vitest.config.ts b/apps/whatsapp/vitest.config.ts new file mode 100644 index 00000000..4a58023e --- /dev/null +++ b/apps/whatsapp/vitest.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['tests/**/*.test.ts'], + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b2fc9094..0d6a2997 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -449,6 +449,43 @@ importers: specifier: 4.151.3 version: 4.151.3(@types/node@22.20.5) + apps/whatsapp: + dependencies: + dotenv: + specifier: ^17.2.3 + version: 17.4.2 + zod: + specifier: ^4.3.5 + version: 4.6.7 + devDependencies: + '@ansari/eslint-config': + specifier: workspace:* + version: link:../../packages/eslint-config + '@ansari/tsconfig': + specifier: workspace:* + version: link:../../packages/tsconfig + '@types/node': + specifier: ^25.0.10 + version: 25.9.8 + eslint: + specifier: 'catalog:' + version: 9.39.5(jiti@2.7.0) + tsdown: + specifier: ^0.22.14 + version: 0.22.14(tsx@4.22.0)(typescript@6.0.3) + tsx: + specifier: ^4.21.0 + version: 4.22.0 + typescript: + specifier: 'catalog:' + version: 6.0.3 + typescript-eslint: + specifier: 'catalog:' + version: 8.70.1(eslint@9.39.5(jiti@2.7.0))(typescript@6.0.3) + vitest: + specifier: ^4.1.11 + version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@25.9.8)(@vitest/coverage-v8@4.1.11)(jsdom@26.1.0)(vite@8.2.1(@types/node@25.9.8)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.1)) + packages/auth: dependencies: '@ansari/types': @@ -2176,9 +2213,6 @@ packages: resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==} engines: {node: '>=14'} - '@oxc-project/types@0.143.0': - resolution: {integrity: sha512-u6JZdLBTLotrNC9Vd6vPssINdzcCzleKAH6EJKImQb7GtYvX5keN2dxkoK44stCc4tffE6QQRtZTXVSzsLUlWA==} - '@oxc-project/types@0.151.0': resolution: {integrity: sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==} @@ -2606,60 +2640,30 @@ packages: cpu: [arm64] os: [android] - '@rolldown/binding-android-arm64@1.2.3': - resolution: {integrity: sha512-zrJtHDcaZJ1Fp7xf4hNl+7seH9Cn/N5TwLYkhgXREtBwAd/jaqW3uqeHxpDugJLVICWg4eW44kOQEGJ1r6jCGw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [android] - '@rolldown/binding-darwin-arm64@1.2.11': resolution: {integrity: sha512-jShvqNtP6vDC6/A5JOAzbVV+DkgHqhl/ScVCJEbt+TUY6QYz7YnXcrg3sLtFBniro0f/Ld50ZwCWA6f7KYD1nQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@rolldown/binding-darwin-arm64@1.2.3': - resolution: {integrity: sha512-ieIiibVCp0tX7TLu2cafoNPv8wJyYi01ekXpbf8q2j7F4rGAhhXb/eQh7ge9DRBY78GwmRQtvjZDux7EDbA8kA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [darwin] - '@rolldown/binding-darwin-x64@1.2.11': resolution: {integrity: sha512-f2i2xiNWq1Z1l2++q2fuhZRdLAT3aqxD6vRNm1RAxpUoBcdqNB3C0s1Bt+K+PbEx2F5F4gQp6hqKkphCY/xF9w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@rolldown/binding-darwin-x64@1.2.3': - resolution: {integrity: sha512-Zh9tCon19eDXJoihx0rqKhMUlMYqzwj3aPsSuHmI4RWZh62dWUL+DJN4C5YQya5TcQBJU/Fe8+rY0jhXTQITqA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [darwin] - '@rolldown/binding-freebsd-x64@1.2.11': resolution: {integrity: sha512-4Ir5FSOKIAMr4r0kExpt1s3bMgzJU3rA45AYOHtQpls0oNeqcYBKrWMlckrYH4KCfGLfkfn1tN1dmZPMVsdXow==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@rolldown/binding-freebsd-x64@1.2.3': - resolution: {integrity: sha512-nGbJWewA1wrXXZiQhjAT5rhibGfns5ZNkDVqxsO6zJ3f3YvpoDNNmGMSbbhLuXKjNScaBJVOAboztAWVespQMg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [freebsd] - '@rolldown/binding-linux-arm-gnueabihf@1.2.11': resolution: {integrity: sha512-/gnRDM+39BROzAN/k1OZjDPnDMcZxB/0EUxKjONO5yVkNEvlsoMDrxGNKgZi/ttFriS2gwlDNzB65pvNbFOXIQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@rolldown/binding-linux-arm-gnueabihf@1.2.3': - resolution: {integrity: sha512-QNniJr5Kml0kDEB98jiDOJjXNroxIIi0IXIbdYzY26Xt1pVbeP62+KnoIZLwirOymX/0jDk/2gI/bNUv7A7OIw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [linux] - '@rolldown/binding-linux-arm64-gnu@1.2.11': resolution: {integrity: sha512-PFaK8HwvAHbaKbBcDNQihjMKYvFnA5hiENx/l5tphTDz1E0WFp32l0A7aq7lyUwGsRw/xSrNIy/gIK4thrSCrw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -2667,13 +2671,6 @@ packages: os: [linux] libc: [glibc] - '@rolldown/binding-linux-arm64-gnu@1.2.3': - resolution: {integrity: sha512-TkqEAcmmvH3I/q4114NB4RVt6241Dao48pF45uLcFGrwAaIn0iITgTAKP/dLjbN0R4buJjGb91+UHSoFmpgIWw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [glibc] - '@rolldown/binding-linux-arm64-musl@1.2.11': resolution: {integrity: sha512-AskzJUIKRLPxkruR1wLKewGbOw+EYfU/9lOrBFj4AFrEA8hPpKFnODWNu2WLaNs0QNkEb9QIJufmVZZIL/bJlg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -2681,13 +2678,6 @@ packages: os: [linux] libc: [musl] - '@rolldown/binding-linux-arm64-musl@1.2.3': - resolution: {integrity: sha512-NHqjnxpsndf4MPymxteFAWHHfkTL8HjWh1KB7z23ofZ6QO2euONuxDXjat69dKZRALnGypg8k8SsK8vZJoXv1Q==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [musl] - '@rolldown/binding-linux-ppc64-gnu@1.2.11': resolution: {integrity: sha512-qlUGAheh2yh8afH7QBgx0PrRHN85hKnNd78x8MeMhXivuevgd8vgf6/CstOzmNKY/lLTHvNTrPy98cLnAugzJw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -2695,13 +2685,6 @@ packages: os: [linux] libc: [glibc] - '@rolldown/binding-linux-ppc64-gnu@1.2.3': - resolution: {integrity: sha512-6tbrbwfz5GB9DQ4Jwo6hy9v+vR31xZlvzZ6n5Xut6Hhx5PvrA9q/HsK8KMaYQp063iqZGXwNvZtYNLD7EM/x0w==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [ppc64] - os: [linux] - libc: [glibc] - '@rolldown/binding-linux-s390x-gnu@1.2.11': resolution: {integrity: sha512-secpEad+0vCbSfn8upFySkDskv+bGPk3THSDS9Y89yc4rb4kzqHp8Dmyd9BkQW4SnhNXBZCl/6CrO//hZahNJQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -2709,13 +2692,6 @@ packages: os: [linux] libc: [glibc] - '@rolldown/binding-linux-s390x-gnu@1.2.3': - resolution: {integrity: sha512-oyuXxXmoZHjXC917IAPFAAv4wWAa0cM9afk8nx1+9/jNNOX1uPf8yDA6p7G0RypOfw/X0PQt5IfoquY1um+zSg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [s390x] - os: [linux] - libc: [glibc] - '@rolldown/binding-linux-x64-gnu@1.2.11': resolution: {integrity: sha512-mOVBT3dPpkWm8XBWPmU4bf+U6dYDLeMo/9ojUmis4N0L5uu10qra5vOyngZ7/PSdoE4G9KvRt4bloRxNjLas7A==} engines: {node: ^20.19.0 || >=22.12.0} @@ -2723,13 +2699,6 @@ packages: os: [linux] libc: [glibc] - '@rolldown/binding-linux-x64-gnu@1.2.3': - resolution: {integrity: sha512-TytMwF2KVGqP2tgd0I1OY0PAv78dZRAYcF5ssDzjM34SUXCED3uXvSd5+lHoC0bTD6eEdFz7LdQNCO1y0oVk9w==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [glibc] - '@rolldown/binding-linux-x64-musl@1.2.11': resolution: {integrity: sha512-Is78i9A8Ui4SqcxUwFJ9uMmjDn58IbVTjFWYdQestFEgeuEmHMLGNriXnVJKkwG2YiZjw8cP0zCTyDMdDGtOOg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -2737,49 +2706,24 @@ packages: os: [linux] libc: [musl] - '@rolldown/binding-linux-x64-musl@1.2.3': - resolution: {integrity: sha512-/E9m3qstrJFVPoULV25mVQblSNExY2+kBsYe4sy0Tn0yOOgJ8wZbZt3KnRbF/XeU2Gl1STKUQnDNTqhIE5MD4A==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [musl] - '@rolldown/binding-openharmony-arm64@1.2.11': resolution: {integrity: sha512-dUCXneZ87INUMyQ0D+C0HrEBNUPNXHaPmU5GTjyKTJEiussw9Kaj5Ln8UztPe4epV/ffvgNBEadksdYhmW6xJA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@rolldown/binding-openharmony-arm64@1.2.3': - resolution: {integrity: sha512-Kr0OcsoQI816i6HOl3vFHpd1K0eZyh76zgfj4c1nTyaTsd5r2Mj1lwM4R90y/qaCfmTn9eHy0SKwi98eitRxug==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [openharmony] - '@rolldown/binding-win32-arm64-msvc@1.2.11': resolution: {integrity: sha512-jByxb6qfd+bH1xUd0qnfFnb17i9sWBPY2tOavJ0l3tdr3OTu+Kvtm8cd/JV5nFt657b1VqGltxg9olOEfofXWw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@rolldown/binding-win32-arm64-msvc@1.2.3': - resolution: {integrity: sha512-hOtMwTqnME+/gJcH/PCZ0wn0zPUjiWOgkHpxbSJpfGKMezHltx1S7/k1SitzVa7Ww2cqrDDaFbZEhcJZO8o+Jw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [win32] - '@rolldown/binding-win32-x64-msvc@1.2.11': resolution: {integrity: sha512-/PzKqzAJ03i19oy2ItPvyvaVjOjBCNnfaJs8yvUdGBKmiESgnrJSQ2awd81QzFbbnAmu7YO9ZnJrDCb9VSJPRA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] - '@rolldown/binding-win32-x64-msvc@1.2.3': - resolution: {integrity: sha512-ekcqMMkI2PlhYnfzQnB/cEdYUVVJViWvoUyLrbzgDoi3Snfc1mVBwdnc306ufA5ejy8JSPjT2RlW1nQSjW7efg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [win32] - '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} @@ -7466,11 +7410,6 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} hasBin: true - rolldown@1.2.3: - resolution: {integrity: sha512-rn9wpmxplLf7NLNyCk9FyWh3FM43DbY8jOzCdEPzH7uflhTftRbCEpqi6Ly2osgoU8OwObtmavMbWLaWy4LX7A==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - rollup@4.62.4: resolution: {integrity: sha512-RXOqwaPsBGjMNMa4sQjDjHieHEZDFoj/Rdr46l2MU5DfEs16wHJPC2RPTPHWhNl+M3aI472LLqFkFKut4SblOg==} engines: {node: '>=18.0.0', npm: '>=8.0.0'} @@ -8608,9 +8547,6 @@ packages: zod@4.4.3: resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} - zod@4.6.5: - resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==} - zod@4.6.7: resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} @@ -9197,13 +9133,13 @@ snapshots: optionalDependencies: '@opentelemetry/api': 1.9.1 - '@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2)': + '@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2)': dependencies: '@better-auth/utils': 0.4.2 '@better-fetch/fetch': 1.3.2 '@opentelemetry/semantic-conventions': 1.43.0 '@standard-schema/spec': 1.1.0 - better-call: 1.4.0(zod@4.6.5) + better-call: 1.4.0(zod@4.6.7) jose: 6.2.9 kysely: 0.29.5 nanostores: 1.5.2 @@ -9218,9 +9154,9 @@ snapshots: optionalDependencies: drizzle-orm: 0.45.2(@electric-sql/pglite@0.5.4)(@opentelemetry/api@1.9.1)(@types/pg@8.21.0)(kysely@0.29.5)(pg@8.22.0) - '@better-auth/drizzle-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@electric-sql/pglite@0.5.4)(@opentelemetry/api@1.9.1)(@types/pg@8.21.0)(kysely@0.29.5)(pg@8.22.0))': + '@better-auth/drizzle-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@electric-sql/pglite@0.5.4)(@opentelemetry/api@1.9.1)(@types/pg@8.21.0)(kysely@0.29.5)(pg@8.22.0))': dependencies: - '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) + '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) '@better-auth/utils': 0.4.2 optionalDependencies: drizzle-orm: 0.45.2(@electric-sql/pglite@0.5.4)(@opentelemetry/api@1.9.1)(@types/pg@8.21.0)(kysely@0.29.5)(pg@8.22.0) @@ -9230,8 +9166,8 @@ snapshots: '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) '@better-fetch/fetch': 1.3.2 better-auth: 1.7.7(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@electric-sql/pglite@0.5.4)(@opentelemetry/api@1.9.1)(@types/pg@8.21.0)(kysely@0.29.5)(pg@8.22.0))(next@15.5.25(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@playwright/test@1.64.0)(@types/node@25.9.5)(babel-plugin-react-compiler@1.0.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(pg@8.22.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(vitest@4.1.11) - better-call: 1.4.0(zod@4.6.5) - zod: 4.6.5 + better-call: 1.4.0(zod@4.6.7) + zod: 4.6.7 optionalDependencies: expo-constants: 57.0.21(expo@57.0.27)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.1)) expo-linking: 57.0.12(expo@57.0.27)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.1))(react@19.3.1) @@ -9245,9 +9181,9 @@ snapshots: optionalDependencies: kysely: 0.29.5 - '@better-auth/kysely-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(kysely@0.29.5)': + '@better-auth/kysely-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(kysely@0.29.5)': dependencies: - '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) + '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) '@better-auth/utils': 0.4.2 optionalDependencies: kysely: 0.29.5 @@ -9257,9 +9193,9 @@ snapshots: '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) '@better-auth/utils': 0.4.2 - '@better-auth/memory-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)': + '@better-auth/memory-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)': dependencies: - '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) + '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) '@better-auth/utils': 0.4.2 '@better-auth/mongo-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)': @@ -9267,9 +9203,9 @@ snapshots: '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) '@better-auth/utils': 0.4.2 - '@better-auth/mongo-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)': + '@better-auth/mongo-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)': dependencies: - '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) + '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) '@better-auth/utils': 0.4.2 '@better-auth/prisma-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)': @@ -9277,9 +9213,9 @@ snapshots: '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) '@better-auth/utils': 0.4.2 - '@better-auth/prisma-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)': + '@better-auth/prisma-adapter@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)': dependencies: - '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) + '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) '@better-auth/utils': 0.4.2 '@better-auth/telemetry@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)': @@ -9288,9 +9224,9 @@ snapshots: '@better-auth/utils': 0.4.2 '@better-fetch/fetch': 1.3.2 - '@better-auth/telemetry@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)': + '@better-auth/telemetry@1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)': dependencies: - '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) + '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) '@better-auth/utils': 0.4.2 '@better-fetch/fetch': 1.3.2 @@ -10516,8 +10452,6 @@ snapshots: '@opentelemetry/semantic-conventions@1.43.0': {} - '@oxc-project/types@0.143.0': {} - '@oxc-project/types@0.151.0': {} '@playwright/test@1.64.0': @@ -11135,87 +11069,45 @@ snapshots: '@rolldown/binding-android-arm64@1.2.11': optional: true - '@rolldown/binding-android-arm64@1.2.3': - optional: true - '@rolldown/binding-darwin-arm64@1.2.11': optional: true - '@rolldown/binding-darwin-arm64@1.2.3': - optional: true - '@rolldown/binding-darwin-x64@1.2.11': optional: true - '@rolldown/binding-darwin-x64@1.2.3': - optional: true - '@rolldown/binding-freebsd-x64@1.2.11': optional: true - '@rolldown/binding-freebsd-x64@1.2.3': - optional: true - '@rolldown/binding-linux-arm-gnueabihf@1.2.11': optional: true - '@rolldown/binding-linux-arm-gnueabihf@1.2.3': - optional: true - '@rolldown/binding-linux-arm64-gnu@1.2.11': optional: true - '@rolldown/binding-linux-arm64-gnu@1.2.3': - optional: true - '@rolldown/binding-linux-arm64-musl@1.2.11': optional: true - '@rolldown/binding-linux-arm64-musl@1.2.3': - optional: true - '@rolldown/binding-linux-ppc64-gnu@1.2.11': optional: true - '@rolldown/binding-linux-ppc64-gnu@1.2.3': - optional: true - '@rolldown/binding-linux-s390x-gnu@1.2.11': optional: true - '@rolldown/binding-linux-s390x-gnu@1.2.3': - optional: true - '@rolldown/binding-linux-x64-gnu@1.2.11': optional: true - '@rolldown/binding-linux-x64-gnu@1.2.3': - optional: true - '@rolldown/binding-linux-x64-musl@1.2.11': optional: true - '@rolldown/binding-linux-x64-musl@1.2.3': - optional: true - '@rolldown/binding-openharmony-arm64@1.2.11': optional: true - '@rolldown/binding-openharmony-arm64@1.2.3': - optional: true - '@rolldown/binding-win32-arm64-msvc@1.2.11': optional: true - '@rolldown/binding-win32-arm64-msvc@1.2.3': - optional: true - '@rolldown/binding-win32-x64-msvc@1.2.11': optional: true - '@rolldown/binding-win32-x64-msvc@1.2.3': - optional: true - '@rolldown/pluginutils@1.0.1': {} '@rollup/plugin-commonjs@28.0.1(rollup@4.62.4)': @@ -11223,10 +11115,10 @@ snapshots: '@rollup/pluginutils': 5.4.0(rollup@4.62.4) commondir: 1.0.1 estree-walker: 2.0.2 - fdir: 6.5.0(picomatch@4.0.5) + fdir: 6.5.0(picomatch@4.0.7) is-reference: 1.2.1 magic-string: 0.30.21 - picomatch: 4.0.5 + picomatch: 4.0.7 optionalDependencies: rollup: 4.62.4 @@ -11234,7 +11126,7 @@ snapshots: dependencies: '@types/estree': 1.0.9 estree-walker: 2.0.2 - picomatch: 4.0.5 + picomatch: 4.0.7 optionalDependencies: rollup: 4.62.4 @@ -11719,12 +11611,12 @@ snapshots: '@types/bcrypt@6.0.0': dependencies: - '@types/node': 25.9.5 + '@types/node': 25.9.8 '@types/body-parser@1.19.6': dependencies: '@types/connect': 3.4.38 - '@types/node': 25.9.5 + '@types/node': 25.9.8 '@types/chai@5.2.3': dependencies: @@ -11733,11 +11625,11 @@ snapshots: '@types/connect@3.4.38': dependencies: - '@types/node': 25.9.5 + '@types/node': 25.9.8 '@types/cors@2.8.19': dependencies: - '@types/node': 25.9.5 + '@types/node': 25.9.8 '@types/d3-array@3.2.2': {} @@ -11769,7 +11661,7 @@ snapshots: '@types/express-serve-static-core@5.1.3': dependencies: - '@types/node': 25.9.5 + '@types/node': 25.9.8 '@types/qs': 6.15.1 '@types/range-parser': 1.2.7 '@types/send': 1.2.1 @@ -11812,7 +11704,7 @@ snapshots: '@types/pg@8.21.0': dependencies: - '@types/node': 25.9.5 + '@types/node': 25.9.8 pg-protocol: 1.15.0 pg-types: 2.2.0 @@ -11844,12 +11736,12 @@ snapshots: '@types/send@1.2.1': dependencies: - '@types/node': 25.9.5 + '@types/node': 25.9.8 '@types/serve-static@2.2.0': dependencies: '@types/http-errors': 2.0.5 - '@types/node': 25.9.5 + '@types/node': 25.9.8 '@types/trusted-types@2.0.7': {} @@ -12127,7 +12019,7 @@ snapshots: obug: 2.1.4 std-env: 4.2.0 tinyrainbow: 3.1.1 - vitest: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@25.9.5)(@vitest/coverage-v8@4.1.11)(jsdom@26.1.0)(vite@8.2.1(@types/node@25.9.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.11)(yaml@2.9.1)) + vitest: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@25.9.8)(@vitest/coverage-v8@4.1.11)(jsdom@26.1.0)(vite@8.2.1(@types/node@25.9.8)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.1)) '@vitest/expect@3.2.7': dependencies: @@ -12162,6 +12054,14 @@ snapshots: optionalDependencies: vite: 8.2.1(@types/node@25.9.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.11)(yaml@2.9.1) + '@vitest/mocker@4.1.11(vite@8.2.1(@types/node@25.9.8)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.1))': + dependencies: + '@vitest/spy': 4.1.11 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.2.1(@types/node@25.9.8)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.1) + '@vitest/pretty-format@3.2.7': dependencies: tinyrainbow: 2.0.0 @@ -12678,12 +12578,12 @@ snapshots: '@better-fetch/fetch': 1.3.2 '@noble/ciphers': 2.3.0 '@noble/hashes': 2.3.0 - better-call: 1.4.0(zod@4.6.5) + better-call: 1.4.0(zod@4.6.7) defu: 6.1.7 jose: 6.2.9 kysely: 0.29.5 nanostores: 1.5.2 - zod: 4.6.5 + zod: 4.6.7 optionalDependencies: drizzle-kit: 0.31.10 drizzle-orm: 0.45.2(@electric-sql/pglite@0.5.4)(@opentelemetry/api@1.9.1)(@types/pg@8.21.0)(kysely@0.29.5)(pg@8.22.0) @@ -12697,23 +12597,23 @@ snapshots: better-auth@1.7.7(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@electric-sql/pglite@0.5.4)(@opentelemetry/api@1.9.1)(@types/pg@8.21.0)(kysely@0.29.5)(pg@8.22.0))(next@15.5.25(@opentelemetry/api@1.9.1)(@playwright/test@1.64.0)(@types/node@25.9.5)(babel-plugin-react-compiler@1.0.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(pg@8.22.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(vitest@4.1.11): dependencies: - '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) - '@better-auth/drizzle-adapter': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@electric-sql/pglite@0.5.4)(@opentelemetry/api@1.9.1)(@types/pg@8.21.0)(kysely@0.29.5)(pg@8.22.0)) - '@better-auth/kysely-adapter': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(kysely@0.29.5) - '@better-auth/memory-adapter': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2) - '@better-auth/mongo-adapter': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2) - '@better-auth/prisma-adapter': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2) - '@better-auth/telemetry': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.5))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2) + '@better-auth/core': 1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2) + '@better-auth/drizzle-adapter': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@electric-sql/pglite@0.5.4)(@opentelemetry/api@1.9.1)(@types/pg@8.21.0)(kysely@0.29.5)(pg@8.22.0)) + '@better-auth/kysely-adapter': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(kysely@0.29.5) + '@better-auth/memory-adapter': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2) + '@better-auth/mongo-adapter': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2) + '@better-auth/prisma-adapter': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2) + '@better-auth/telemetry': 1.7.7(@better-auth/core@1.7.7(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.6.7))(jose@6.2.9)(kysely@0.29.5)(nanostores@1.5.2))(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2) '@better-auth/utils': 0.4.2 '@better-fetch/fetch': 1.3.2 '@noble/ciphers': 2.3.0 '@noble/hashes': 2.3.0 - better-call: 1.4.0(zod@4.6.5) + better-call: 1.4.0(zod@4.6.7) defu: 6.1.7 jose: 6.2.9 kysely: 0.29.5 nanostores: 1.5.2 - zod: 4.6.5 + zod: 4.6.7 optionalDependencies: drizzle-kit: 0.31.10 drizzle-orm: 0.45.2(@electric-sql/pglite@0.5.4)(@opentelemetry/api@1.9.1)(@types/pg@8.21.0)(kysely@0.29.5)(pg@8.22.0) @@ -12734,14 +12634,14 @@ snapshots: optionalDependencies: zod: 4.4.3 - better-call@1.4.0(zod@4.6.5): + better-call@1.4.0(zod@4.6.7): dependencies: '@better-auth/utils': 0.5.0 '@better-fetch/fetch': 1.3.2 rou3: 0.9.2 set-cookie-parser: 3.1.2 optionalDependencies: - zod: 4.6.5 + zod: 4.6.7 big-integer@1.6.52: {} @@ -13191,7 +13091,7 @@ snapshots: '@drizzle-team/brocli': 0.10.2 '@esbuild-kit/esm-loader': 2.6.5 esbuild: 0.28.2 - tsx: 4.23.11 + tsx: 4.22.0 drizzle-orm@0.45.2(@electric-sql/pglite@0.5.4)(@opentelemetry/api@1.9.1)(@types/pg@8.21.0)(kysely@0.29.5)(pg@8.22.0): optionalDependencies: @@ -13458,7 +13358,7 @@ snapshots: tinyglobby: 0.2.17 unrs-resolver: 1.12.2 optionalDependencies: - eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.66.0(eslint@9.39.5(jiti@2.7.0))(typescript@6.0.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.5(jiti@2.7.0)) + eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.70.1(eslint@9.39.5(jiti@2.7.0))(typescript@6.0.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.5(jiti@2.7.0)) transitivePeerDependencies: - supports-color @@ -13580,8 +13480,8 @@ snapshots: '@babel/parser': 7.29.8 eslint: 9.39.5(jiti@2.7.0) hermes-parser: 0.25.1 - zod: 4.6.5 - zod-validation-error: 4.0.2(zod@4.6.5) + zod: 4.6.7 + zod-validation-error: 4.0.2(zod@4.6.7) transitivePeerDependencies: - supports-color @@ -16063,7 +15963,7 @@ snapshots: '@protobufjs/path': 1.1.2 '@protobufjs/pool': 1.1.0 '@protobufjs/utf8': 1.1.2 - '@types/node': 25.9.5 + '@types/node': 25.9.8 long: 5.3.2 proxy-addr@2.0.7: @@ -16594,12 +16494,12 @@ snapshots: reusify@1.1.0: {} - rolldown-plugin-dts@0.27.14(rolldown@1.2.3)(typescript@6.0.3): + rolldown-plugin-dts@0.27.14(rolldown@1.2.11)(typescript@6.0.3): dependencies: dts-resolver: 3.0.0 get-tsconfig: 5.0.0-beta.5 obug: 2.1.4 - rolldown: 1.2.3 + rolldown: 1.2.11 yuku-ast: 0.8.7 yuku-codegen: 0.8.7 yuku-parser: 0.8.7 @@ -16629,26 +16529,6 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.2.11 '@rolldown/binding-win32-x64-msvc': 1.2.11 - rolldown@1.2.3: - dependencies: - '@oxc-project/types': 0.143.0 - '@rolldown/pluginutils': 1.0.1 - optionalDependencies: - '@rolldown/binding-android-arm64': 1.2.3 - '@rolldown/binding-darwin-arm64': 1.2.3 - '@rolldown/binding-darwin-x64': 1.2.3 - '@rolldown/binding-freebsd-x64': 1.2.3 - '@rolldown/binding-linux-arm-gnueabihf': 1.2.3 - '@rolldown/binding-linux-arm64-gnu': 1.2.3 - '@rolldown/binding-linux-arm64-musl': 1.2.3 - '@rolldown/binding-linux-ppc64-gnu': 1.2.3 - '@rolldown/binding-linux-s390x-gnu': 1.2.3 - '@rolldown/binding-linux-x64-gnu': 1.2.3 - '@rolldown/binding-linux-x64-musl': 1.2.3 - '@rolldown/binding-openharmony-arm64': 1.2.3 - '@rolldown/binding-win32-arm64-msvc': 1.2.3 - '@rolldown/binding-win32-x64-msvc': 1.2.3 - rollup@4.62.4: dependencies: '@types/estree': 1.0.9 @@ -17236,6 +17116,32 @@ snapshots: minimist: 1.2.8 strip-bom: 3.0.0 + tsdown@0.22.14(tsx@4.22.0)(typescript@6.0.3): + dependencies: + ansis: 4.3.1 + cac: 7.0.0 + defu: 6.1.7 + empathic: 2.0.1 + hookable: 6.1.1 + import-without-cache: 0.4.0 + obug: 2.1.4 + picomatch: 4.0.7 + rolldown: 1.2.11 + rolldown-plugin-dts: 0.27.14(rolldown@1.2.11)(typescript@6.0.3) + tinyexec: 1.3.0 + tinyglobby: 0.2.17 + tree-kill: 1.2.2 + unconfig-core: 7.5.0 + verkit: 0.3.2 + optionalDependencies: + tsx: 4.22.0 + typescript: 6.0.3 + transitivePeerDependencies: + - '@typescript/native-preview' + - '@volar/typescript' + - oxc-resolver + - vue-tsc + tsdown@0.22.14(tsx@4.23.11)(typescript@6.0.3): dependencies: ansis: 4.3.1 @@ -17245,9 +17151,9 @@ snapshots: hookable: 6.1.1 import-without-cache: 0.4.0 obug: 2.1.4 - picomatch: 4.0.5 - rolldown: 1.2.3 - rolldown-plugin-dts: 0.27.14(rolldown@1.2.3)(typescript@6.0.3) + picomatch: 4.0.7 + rolldown: 1.2.11 + rolldown-plugin-dts: 0.27.14(rolldown@1.2.11)(typescript@6.0.3) tinyexec: 1.3.0 tinyglobby: 0.2.17 tree-kill: 1.2.2 @@ -17587,6 +17493,22 @@ snapshots: tsx: 4.23.11 yaml: 2.9.1 + vite@8.2.1(@types/node@25.9.8)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.1): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.28 + rolldown: 1.2.11 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 25.9.8 + esbuild: 0.28.2 + fsevents: 2.3.3 + jiti: 2.7.0 + terser: 5.51.2 + tsx: 4.22.0 + yaml: 2.9.1 + vitest@3.2.7(@types/node@25.9.8)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(terser@5.51.2)(tsx@4.23.11)(yaml@2.9.1): dependencies: '@types/chai': 5.2.3 @@ -17659,6 +17581,36 @@ snapshots: transitivePeerDependencies: - msw + vitest@4.1.11(@opentelemetry/api@1.9.1)(@types/node@25.9.8)(@vitest/coverage-v8@4.1.11)(jsdom@26.1.0)(vite@8.2.1(@types/node@25.9.8)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.1)): + dependencies: + '@vitest/expect': 4.1.11 + '@vitest/mocker': 4.1.11(vite@8.2.1(@types/node@25.9.8)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.1)) + '@vitest/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 0.30.21 + obug: 2.1.4 + pathe: 2.0.3 + picomatch: 4.0.7 + std-env: 4.2.0 + tinybench: 2.9.0 + tinyexec: 1.3.0 + tinyglobby: 0.2.17 + tinyrainbow: 3.1.1 + vite: 8.2.1(@types/node@25.9.8)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.1) + why-is-node-running: 2.3.0 + optionalDependencies: + '@opentelemetry/api': 1.9.1 + '@types/node': 25.9.8 + '@vitest/coverage-v8': 4.1.11(vitest@4.1.11) + jsdom: 26.1.0 + transitivePeerDependencies: + - msw + vlq@1.0.1: {} w3c-xmlserializer@5.0.0: @@ -17938,14 +17890,12 @@ snapshots: dependencies: zod: 3.25.76 - zod-validation-error@4.0.2(zod@4.6.5): + zod-validation-error@4.0.2(zod@4.6.7): dependencies: - zod: 4.6.5 + zod: 4.6.7 zod@3.25.76: {} zod@4.4.3: {} - zod@4.6.5: {} - zod@4.6.7: {} From 29314b91bfbd82f1c8497ae0223e86cabf726810 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 17:18:26 +0200 Subject: [PATCH 019/435] chore(porch): 358 implement build-complete --- codev/projects/358-whatsapp-typescript/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index f0babd8c..fc85a654 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T14:07:00.689Z' +updated_at: '2026-11-10T15:18:26.007Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' From 685714b50b832ae99e40fea7e3e09c252fbed807 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 19:46:31 +0200 Subject: [PATCH 020/435] [Spec 358][Phase: phase_1] docs: fix buildConfig error claim, add agent self-review --- apps/whatsapp/src/config.ts | 5 +++- .../358-phase_1-iter1-claude.txt | 30 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 codev/projects/358-whatsapp-typescript/358-phase_1-iter1-claude.txt diff --git a/apps/whatsapp/src/config.ts b/apps/whatsapp/src/config.ts index 2b68e70e..66ae0aea 100644 --- a/apps/whatsapp/src/config.ts +++ b/apps/whatsapp/src/config.ts @@ -192,7 +192,10 @@ export type Env = z.output; export const CONFIG_KEYS = Object.keys(rawSchema.shape); /** - * Validate an environment and return the settings, or throw one error that names every bad variable. + * Validate an environment and return the settings, or throw one error that names every variable + * failing its own check. The cross-field rules (mocks outside local, phone replies in production) + * only run once every variable passes on its own, as with Pydantic's `mode="after"` validators, so + * fixing the first round of errors can reveal one more. * * Takes the environment as an argument (default: the real one) so tests can pass their own * object. Python counterpart: `WhatsAppSettings()`; there the tests had to patch diff --git a/codev/projects/358-whatsapp-typescript/358-phase_1-iter1-claude.txt b/codev/projects/358-whatsapp-typescript/358-phase_1-iter1-claude.txt new file mode 100644 index 00000000..f7ccb699 --- /dev/null +++ b/codev/projects/358-whatsapp-typescript/358-phase_1-iter1-claude.txt @@ -0,0 +1,30 @@ +AGENT SELF-REVIEW, NOT A CONSULT RUN. Written by the implementing agent (GitHub Copilot) because Codex and +Gemini are not installed here and the Claude consult hung. The owner reviews after this. Findings below were +checked by running code, not by reading alone. + +Scope: plan phase_1, commit 1d4b6c19 (apps/whatsapp scaffold, config, masking, logger, errors). + +Verified (ran it): +- typecheck, lint and 84 vitest tests pass. +- Six rules were broken on purpose, one at a time, and a test failed each time; files restored byte-for-byte: + production refusal of META_REPLY_BY_PHONE, mocks refused outside local, phone masking, secret never printing + through JSON.stringify, JSON log lines going to stdout, and a setting missing from .env.example. Three boolean + mutations (accept any string, wrong default, "1" read as false) were caught as well. +- A Secret prints as "Secret(**********)" under console.log and as "{}" when spread, so it cannot leak by accident. +- A message-id, BSUID and phone number are masked in every case from the Python table. + +Found and fixed: +- buildConfig's doc comment claimed it names every bad variable. With PORT=abc and a mock in production only PORT + is reported; the cross-field rules run once every variable passes on its own (same as Pydantic's after-validators). + The comment now says so. No behaviour change. + +Not verified / known differences from Python: +- The JSON log line has no file, line or function fields: Node has no cheap way to read the caller. level, message + and request_id, which Railway reads, are unchanged. Owner agreed in review. +- LOG_TEST_FILES_ONLY and META_WEBHOOK_ZROK_SHARE_TOKEN are not ported (owner decisions, recorded in the plan). +- Booleans now refuse yes/on/TRUE, which Pydantic accepted. Railway staging values are not yet checked; plan + phase_7 step 1 does that before the redeploy. +- pnpm-lock.yaml also dropped rolldown 1.2.3 (deduplicated to 1.2.11). apps/auth's build was NOT re-run after that. +- The Docker image and a cold-cache root build are not run until plan phase_6. + +VERDICT: COMMENT From 036918fa3eaa191ebcdde16dac595ba31c1bae67 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 19:47:59 +0200 Subject: [PATCH 021/435] =?UTF-8?q?chore(porch):=20358=20advance=20plan=20?= =?UTF-8?q?phase=20=E2=86=92=20phase=5F2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codev/projects/358-whatsapp-typescript/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index fc85a654..fde13261 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -5,10 +5,10 @@ phase: implement plan_phases: - id: phase_1 title: Scaffold apps/whatsapp, config, masked logging - status: in_progress + status: complete - id: phase_2 title: 'Pure logic: formatter, splitter, webhook parser, language and time helpers' - status: pending + status: in_progress - id: phase_3 title: 'Service clients: apps/auth exchange, apps/api streaming, Meta API' status: pending @@ -24,7 +24,7 @@ plan_phases: - id: phase_7 title: Staging redeploy, smoke test and legacy rollback note status: pending -current_plan_phase: phase_1 +current_plan_phase: phase_2 gates: spec-approval: status: approved @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T15:18:26.007Z' +updated_at: '2026-11-10T17:47:59.161Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -48,3 +48,5 @@ context_refreshes: - boundary: enter:implement at: '2026-11-10T14:06:46.783Z' acknowledged_at: '2026-11-10T14:07:00.688Z' + - boundary: plan-phase:phase_2 + at: '2026-11-10T17:47:59.160Z' From 8bd813ce98f2497d37503016382b40b3a2abc9b2 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 19:48:30 +0200 Subject: [PATCH 022/435] chore(porch): 358 acknowledge context refresh --- codev/projects/358-whatsapp-typescript/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index fde13261..23f3e8e3 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -40,7 +40,7 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T17:47:59.161Z' +updated_at: '2026-11-10T17:48:30.126Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -50,3 +50,4 @@ context_refreshes: acknowledged_at: '2026-11-10T14:07:00.688Z' - boundary: plan-phase:phase_2 at: '2026-11-10T17:47:59.160Z' + acknowledged_at: '2026-11-10T17:48:30.123Z' From c5ad83504fcb407f93be2371ed48fd8195c29899 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 20:30:40 +0200 Subject: [PATCH 023/435] [Spec 358][Phase: phase_2] feat: port formatter, splitter, webhook parser and time/language helpers --- apps/whatsapp/src/errors.ts | 9 + .../src/formatting/messageSplitter.ts | 173 ++ .../formatting/whatsappMessageFormatter.ts | 109 + apps/whatsapp/src/utils/language.ts | 38 + apps/whatsapp/src/utils/time.ts | 117 ++ apps/whatsapp/src/webhook/parseWebhook.ts | 226 +++ .../tests/fixtures/generate_python_oracle.py | 428 ++++ apps/whatsapp/tests/fixtures/pythonOracle.ts | 1787 +++++++++++++++++ apps/whatsapp/tests/formatter.test.ts | 90 + apps/whatsapp/tests/language.test.ts | 30 + apps/whatsapp/tests/messageSplitter.test.ts | 133 ++ apps/whatsapp/tests/parseWebhook.test.ts | 151 ++ apps/whatsapp/tests/time.test.ts | 93 + .../358-phase_2-iter1-claude.txt | 60 + 14 files changed, 3444 insertions(+) create mode 100644 apps/whatsapp/src/formatting/messageSplitter.ts create mode 100644 apps/whatsapp/src/formatting/whatsappMessageFormatter.ts create mode 100644 apps/whatsapp/src/utils/language.ts create mode 100644 apps/whatsapp/src/utils/time.ts create mode 100644 apps/whatsapp/src/webhook/parseWebhook.ts create mode 100644 apps/whatsapp/tests/fixtures/generate_python_oracle.py create mode 100644 apps/whatsapp/tests/fixtures/pythonOracle.ts create mode 100644 apps/whatsapp/tests/formatter.test.ts create mode 100644 apps/whatsapp/tests/language.test.ts create mode 100644 apps/whatsapp/tests/messageSplitter.test.ts create mode 100644 apps/whatsapp/tests/parseWebhook.test.ts create mode 100644 apps/whatsapp/tests/time.test.ts create mode 100644 codev/projects/358-whatsapp-typescript/358-phase_2-iter1-claude.txt diff --git a/apps/whatsapp/src/errors.ts b/apps/whatsapp/src/errors.ts index 57308955..cc8047a9 100644 --- a/apps/whatsapp/src/errors.ts +++ b/apps/whatsapp/src/errors.ts @@ -20,6 +20,15 @@ export class UnexpectedMetaPayloadError extends Error { } } +/** + * The webhook body is not the shape Meta documents (no entries, no metadata, a timestamp that is not a number...). + * Python raised a bare `Exception` (or an IndexError/ValueError) for all of these; the HTTP layer answers them with + * `INVALID_PAYLOAD`. Distinct from `UnexpectedMetaPayloadError`, which is the one case where the user can be told. + */ +export class InvalidMetaPayloadError extends Error { + override readonly name = 'InvalidMetaPayloadError'; +} + /** Exchanging a BSUID for a JWT with apps/auth failed (an outage, a 500, or a network fault). */ export class AuthTokenError extends Error { override readonly name: string = 'AuthTokenError'; diff --git a/apps/whatsapp/src/formatting/messageSplitter.ts b/apps/whatsapp/src/formatting/messageSplitter.ts new file mode 100644 index 00000000..88ffd39a --- /dev/null +++ b/apps/whatsapp/src/formatting/messageSplitter.ts @@ -0,0 +1,173 @@ +/** + * Split a long answer into WhatsApp-sized messages. + * + * Python counterpart: `legacy/whatsapp/src/ansari_whatsapp/utils/whatsapp_message_splitter.py`. + * + * Lengths are counted in code points, as Python's `len()` does, not in UTF-16 units. A JavaScript string is a sequence + * of 16-bit units, so an emoji (one code point) has `.length === 2`. Counting units would cut answers short, or in the + * middle of an emoji. `length()` below is the one place that decides how a length is measured. + */ + +/** WhatsApp's character limit per message, as set by the Python service. */ +export const WHATSAPP_MAX_MESSAGE_LENGTH = 4000; + +/** Length in code points. `[...text]` splits a string into code points; `text.length` counts UTF-16 units. */ +function length(text: string): number { + return [...text].length; +} + +/** + * Split a message that exceeds the limit, trying three strategies in turn: + * 1. at formatted headers (`*_HEADER_*`); + * 2. at bold text (`*BOLD*`); + * 3. at paragraphs, falling back to fixed-size pieces cut at a space. + * + * A message within the limit comes back unchanged, as a list of one. + */ +export function splitMessage(msgBody: string): string[] { + if (length(msgBody) <= WHATSAPP_MAX_MESSAGE_LENGTH) return [msgBody]; + + const headerChunks = splitByHeaders(msgBody, WHATSAPP_MAX_MESSAGE_LENGTH); + if (headerChunks.length > 1) return headerChunks; + + const boldChunks = splitByBoldText(msgBody, WHATSAPP_MAX_MESSAGE_LENGTH); + if (boldChunks.length > 1) return boldChunks; + + return splitByParagraphs(msgBody, WHATSAPP_MAX_MESSAGE_LENGTH); +} + +/** Where each match of `pattern` starts. Positions are UTF-16 offsets, which is fine for slicing the same string. */ +function startsOf(pattern: RegExp, text: string): number[] { + return Array.from(text.matchAll(pattern), (match) => match.index); +} + +const HEADER = /\*_[^*_]+_\*/g; + +/** Split at formatted headers (`*_HEADER_*`), each header starting a new chunk. */ +export function splitByHeaders(text: string, maxLength: number): string[] { + const starts = startsOf(HEADER, text); + // One header or none: there is nothing to split on + if (starts.length <= 1) return [text]; + + const chunks: string[] = []; + for (let i = 0; i < starts.length; i++) { + const start = starts[i]; + + // Text before the first header goes in its own message(s) + if (i === 0 && start > 0) { + const prefix = text.slice(0, start); + if (length(prefix) <= maxLength) chunks.push(prefix); + else chunks.push(...splitByParagraphs(prefix, maxLength)); + } + + const end = i < starts.length - 1 ? starts[i + 1] : text.length; + const chunk = text.slice(start, end); + if (length(chunk) <= maxLength) chunks.push(chunk); + // A section still too long: try bold text, then paragraphs + else chunks.push(...splitByBoldText(chunk, maxLength)); + } + return chunks; +} + +const BOLD = /\*[^*]+\*/g; + +/** Split at bold text (`*TEXT*`), each bold phrase starting a new chunk. */ +export function splitByBoldText(text: string, maxLength: number): string[] { + if (length(text) <= maxLength) return [text]; + + const starts = startsOf(BOLD, text); + if (starts.length <= 1) return splitByParagraphs(text, maxLength); + + const chunks: string[] = []; + for (let i = 0; i < starts.length; i++) { + const start = starts[i]; + + if (i === 0 && start > 0) { + const prefix = text.slice(0, start); + if (length(prefix) <= maxLength) chunks.push(prefix); + else chunks.push(...splitByParagraphs(prefix, maxLength)); + } + + const end = i < starts.length - 1 ? starts[i + 1] : text.length; + const chunk = text.slice(start, end); + if (length(chunk) <= maxLength) chunks.push(chunk); + else chunks.push(...splitByParagraphs(chunk, maxLength)); + } + return chunks; +} + +/** + * Split at blank lines, packing as many paragraphs as fit into each chunk. A single paragraph over the limit is cut + * into fixed-size pieces. Runs of blank lines count as one separator and come back as exactly one blank line. + */ +export function splitByParagraphs(text: string, maxLength: number): string[] { + if (length(text) <= maxLength) return [text]; + + const paragraphs = text.split(/\n\n+/); + // No blank lines at all: nothing to split on but size + if (paragraphs.length <= 1) return splitByFixedChunks(text, maxLength); + + const chunks: string[] = []; + let current = ''; + // Kept as a running total: Python's `len()` is instant, but counting code points here walks the whole string, and + // recounting a growing chunk for every paragraph made a very long answer take seconds + let currentLength = 0; + for (const paragraph of paragraphs) { + const paragraphLength = length(paragraph); + + // Adding this paragraph (plus the two newlines that join it) would pass the limit + if (current && currentLength + paragraphLength + 2 > maxLength) { + chunks.push(current); + current = ''; + currentLength = 0; + } + + if (paragraphLength > maxLength) { + if (current) { + chunks.push(current); + current = ''; + currentLength = 0; + } + chunks.push(...splitByFixedChunks(paragraph, maxLength)); + } else if (current) { + current = `${current}\n\n${paragraph}`; + currentLength += paragraphLength + 2; + } else { + current = paragraph; + currentLength = paragraphLength; + } + } + if (current) chunks.push(current); + return chunks; +} + +/** The position of the last space or newline in `chars[start, end)`, or -1 if there is none. */ +function lastWhitespace(chars: string[], start: number, end: number): number { + for (let i = end - 1; i >= start; i--) { + if (chars[i] === ' ' || chars[i] === '\n') return i; + } + return -1; +} + +/** + * Cut into pieces of at most `maxLength`. Each piece ends after the last space or newline in the second half of its + * window, so a word, a URL or a `*bold*` pair is not split when it can be avoided. + * + * Works on an array of code points, so a cut can never fall inside an emoji. + */ +export function splitByFixedChunks(text: string, maxLength: number): string[] { + const chars = [...text]; + if (chars.length <= maxLength) return [text]; + + const chunks: string[] = []; + let start = 0; + while (chars.length - start > maxLength) { + let end = start + maxLength; + const cut = lastWhitespace(chars, start, end) + 1; + if (cut > start + Math.floor(maxLength / 2)) end = cut; + chunks.push(chars.slice(start, end).join('')); + start = end; + } + chunks.push(chars.slice(start).join('')); + return chunks; +} diff --git a/apps/whatsapp/src/formatting/whatsappMessageFormatter.ts b/apps/whatsapp/src/formatting/whatsappMessageFormatter.ts new file mode 100644 index 00000000..57d13d35 --- /dev/null +++ b/apps/whatsapp/src/formatting/whatsappMessageFormatter.ts @@ -0,0 +1,109 @@ +/** + * Convert conventional markdown (what the model writes) into WhatsApp's own formatting. + * + * Python counterpart: `legacy/whatsapp/src/ansari_whatsapp/presenters/whatsapp_message_formatter.py`. + * + * That module has no tests of its own, so `tests/fixtures/pythonOracle.ts` holds what it actually returns for a table of + * inputs, and the tests here compare against that. + * + * Every regular expression is copied from Python. Three things change because the two languages differ: + * - `.` becomes `[^\n]`. Python's `.` matches `\r` and JavaScript's does not, so a Windows line ending (`\r\n`) after a + * header would otherwise be handled differently. + * - `\d` becomes `\p{Nd}` with the `u` flag. Python's `\d` matches digits of any script (Arabic-Indic digits, U+0660 to + * U+0669, included); JavaScript's only matches 0-9. Arabic answers can number their lists with Arabic-Indic digits. + * - Replacement text says `$1` where Python says `\1`. + * + * Known oddities, kept on purpose because the job here is to port behaviour, not to redesign it: + * - Any pair of lone `*` becomes italics, even in arithmetic: "2 * 3 and 4 * 5" turns into "2 _ 3 and 4 _ 5". + * - `***both***` becomes `**both**`: the italic step consumes nothing, then bold turns `**` into `*`, leaving two stars. + * - The italic step can pair a `*` across lines, so a `* item` bullet list loses its bullets (`_ item`). + */ +import { getLanguageDirectionFromText } from '../utils/language'; + +/** + * Convert conventional markdown to WhatsApp's markdown. + * + * Order matters: italic (`*x*` -> `_x_`) must run before bold (`**x**` -> `*x*`), or the new single stars would be + * read as italics. + */ +export function formatForWhatsApp(msg: string): string { + const direction = getLanguageDirectionFromText(msg); + + let result = convertItalicSyntax(msg); + result = convertBoldSyntax(result); + result = convertHeaders(result); + + // Python only formats lists when the direction is known. `getLanguageDirectionFromText` never answers 'unknown' + // today, so this is always true; the guard is kept so the two stay identical if that ever changes. + if (direction === 'ltr' || direction === 'rtl') { + result = formatNestedLists(result); + } + return result; +} + +/** + * `(? `1 - `. Replaces every match on the line, as Python's `re.sub` does, not just the first. */ +const NUMBERED_PREFIX = /(\s*)(\p{Nd}+)(\.) /gu; +/** `- ` or `* ` -> `-- `. Also every match on the line. */ +const BULLET_PREFIX = /(\s*)[*-] /g; + +/** + * Reformat only nested list items (indented ones) for WhatsApp, which renders them badly: + * - nested numbered item ` 1. Item` becomes ` 1 - Item` + * - nested bullet ` - Item` or ` * Item` becomes ` -- Item` + * + * Top-level lists keep their original formatting. + * + * Python also tracked an "inside a nested section" flag here, which was set and cleared but never changed the output, + * so it is not ported. + */ +export function formatNestedLists(text: string): string { + return text + .split('\n') + .map((line) => { + // An indent only counts on a line with something on it + const indent = line.trim() ? INDENT.exec(line) : null; + const currentIndent = indent ? indent[1].length : 0; + if (currentIndent === 0) return line; + + if (NUMBERED_ITEM.test(line)) return line.replace(NUMBERED_PREFIX, '$1$2 - '); + if (BULLET_ITEM.test(line)) return line.replace(BULLET_PREFIX, '$1-- '); + return line; + }) + .join('\n'); +} diff --git a/apps/whatsapp/src/utils/language.ts b/apps/whatsapp/src/utils/language.ts new file mode 100644 index 00000000..b1f0b5e8 --- /dev/null +++ b/apps/whatsapp/src/utils/language.ts @@ -0,0 +1,38 @@ +/** + * Text direction detection. + * + * Python counterpart: `legacy/whatsapp/src/ansari_whatsapp/utils/language_utils.py`. Its other function, + * `get_language_from_text`, is an unused placeholder that always returns "en", so it is not ported. + */ + +/** + * Right-to-left script ranges: Arabic, Arabic Supplement, Arabic Extended-A, and Arabic Presentation Forms-A and -B. + * The `g` flag makes `String.match` return every match; the `u` flag makes the pattern read code points. + */ +const RTL_CHARS = /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/gu; + +/** More than this share of right-to-left characters makes the whole text right-to-left. */ +const RTL_SHARE_THRESHOLD = 0.3; + +/** + * `'unknown'` is in the type because the Python signature promises it, but nothing returns it today. + * A string literal union like this is how TypeScript spells Python's `Literal["ltr", "rtl", "unknown"]`. + */ +export type TextDirection = 'ltr' | 'rtl' | 'unknown'; + +/** + * Detect whether `text` reads left-to-right or right-to-left. + * + * Length is counted in code points, as Python's `len()` does: `[...text]` splits a string into code points, whereas + * `text.length` counts UTF-16 units and would count an emoji as 2. With emoji in the text the two give different + * answers (4 Arabic letters among 8 emoji is 33% in Python and 20% by `.length`). + * + * Empty text: Python raises `ZeroDivisionError`, JavaScript would quietly divide to `NaN`. The callers never pass + * empty text (they check first), so the difference cannot be reached; it is made explicit here as `'ltr'`. + */ +export function getLanguageDirectionFromText(text: string): TextDirection { + const total = [...text].length; + if (total === 0) return 'ltr'; + const rtlCount = text.match(RTL_CHARS)?.length ?? 0; + return rtlCount / total > RTL_SHARE_THRESHOLD ? 'rtl' : 'ltr'; +} diff --git a/apps/whatsapp/src/utils/time.ts b/apps/whatsapp/src/utils/time.ts new file mode 100644 index 00000000..f6cf5a17 --- /dev/null +++ b/apps/whatsapp/src/utils/time.ts @@ -0,0 +1,117 @@ +/** + * Time helpers: elapsed-time text for logs, the conversation expiry, and the stale-message check. + * + * Python counterpart: `legacy/whatsapp/src/ansari_whatsapp/utils/time_utils.py`. + * + * Differences from Python, all deliberate: + * - The clock and the settings are arguments, not globals. Python read `get_settings()` and `datetime.now()` inside + * each function, so its tests had to patch both; here a test passes the instant and the threshold it wants. + * - `Date` replaces `datetime`. A JavaScript `Date` is a count of milliseconds since 1970-01-01 UTC, so there is no + * time zone to get wrong (Python needed `timezone.utc` everywhere). + */ +import type { Logger } from '../logger'; + +/** + * Format a number the way Python's `f"{value:.1f}"` does. JavaScript's `toFixed(1)` differs in two ways: + * - A value exactly halfway between two outputs rounds to the even digit in Python (0.25 -> "0.2", 0.75 -> "0.8") but + * always up in JavaScript (0.25 -> "0.3"). With one decimal this happens exactly when the value is an odd multiple + * of 0.25, which is exact in binary, so it can be detected without rounding error. + * - Infinity prints as "inf" (Python) rather than "Infinity". + */ +function formatOneDecimal(value: number): string { + if (Number.isNaN(value)) return 'nan'; + if (!Number.isFinite(value)) return value > 0 ? 'inf' : '-inf'; + const sign = value < 0 || Object.is(value, -0) ? '-' : ''; + const magnitude = Math.abs(value); + const quarters = magnitude * 4; + if (Number.isInteger(quarters) && quarters % 2 === 1) { + const tenths = Math.floor(magnitude * 10); + return sign + ((tenths % 2 === 0 ? tenths : tenths + 1) / 10).toFixed(1); + } + return sign + magnitude.toFixed(1); +} + +/** Format a time delta in seconds as text, e.g. "5.2 seconds", "3.1 minutes", "2.5 hours", "1.2 days". */ +export function formatTimeDelta(seconds: number): string { + if (seconds < 60) return `${formatOneDecimal(seconds)} seconds`; + if (seconds < 3600) return `${formatOneDecimal(seconds / 60)} minutes`; + if (seconds < 86400) return `${formatOneDecimal(seconds / 3600)} hours`; + return `${formatOneDecimal(seconds / 86400)} days`; +} + +/** + * Time since the last message, in seconds, and a compact form for logging ("5.2sec", "3.1mins", "2.5hours", "1.2days"). + * + * No previous message gives `Infinity` seconds (Python: `float("inf")`), which is longer than any retention time, so the + * conversation starts a new thread. Its logging text is "infdays", as in Python. + * + * @param lastMessageTime When the user last wrote, or `null` if they never did. + * @param now The current time; only tests pass it. + */ +export function calculateTimePassed( + lastMessageTime: Date | null, + now: Date = new Date(), +): { seconds: number; forLogging: string } { + const seconds = lastMessageTime === null ? Infinity : (now.getTime() - lastMessageTime.getTime()) / 1000; + + let forLogging: string; + if (seconds < 60) forLogging = `${formatOneDecimal(seconds)}sec`; + else if (seconds < 3600) forLogging = `${formatOneDecimal(seconds / 60)}mins`; + else if (seconds < 86400) forLogging = `${formatOneDecimal(seconds / 3600)}hours`; + else forLogging = `${formatOneDecimal(seconds / 86400)}days`; + + return { seconds, forLogging }; +} + +/** The chat retention time in seconds, from `WHATSAPP_CHAT_RETENTION_HOURS`. After this much silence a new thread starts. */ +export function getRetentionTimeSeconds(retentionHours: number): number { + return retentionHours * 60 * 60; +} + +/** + * The range of unix seconds Python's `datetime.fromtimestamp(..., tz=utc)` accepts on Linux (where Railway runs): the + * years 1 to 9999. Beyond it Python raises `ValueError`, which `is_message_too_old` catches and answers "not too old". + */ +const MIN_PYTHON_UNIX_TIME = -62135596800; +const MAX_PYTHON_UNIX_TIME = 253402300799; + +/** + * Is an incoming message older than the allowed threshold? + * + * Uses the message's own timestamp (unix seconds, as Meta sends it) rather than the arrival time. + * + * When the age cannot be worked out, the message is treated as NOT too old and gets answered: + * - no timestamp at all, including `0` (Python's `if not message_unix_time` treats epoch zero as missing too); + * - a timestamp that is not a finite number, or lies outside the years 1 to 9999. + * + * @param messageUnixTime Seconds since 1970-01-01 UTC, from Meta's `timestamp` field. + * @param thresholdSeconds `WHATSAPP_MESSAGE_AGE_THRESHOLD_SECONDS`. + * @param options.now The current time; only tests pass it. + * @param options.logger Receives the same debug and error lines as the Python service. + */ +export function isMessageTooOld( + messageUnixTime: number | null | undefined, + thresholdSeconds: number, + options: { now?: Date; logger?: Pick } = {}, +): boolean { + const { now = new Date(), logger } = options; + + // Not `!messageUnixTime`: NaN is falsy in JavaScript but truthy in Python, and belongs in the unusable-timestamp branch + if (messageUnixTime === null || messageUnixTime === undefined || messageUnixTime === 0) { + logger?.debug('No timestamp available, cannot determine message age'); + return false; + } + + if ( + !Number.isFinite(messageUnixTime) || + messageUnixTime < MIN_PYTHON_UNIX_TIME || + messageUnixTime > MAX_PYTHON_UNIX_TIME + ) { + logger?.error(`Error parsing message timestamp: ${messageUnixTime} is not a usable unix time`); + return false; + } + + const ageSeconds = now.getTime() / 1000 - messageUnixTime; + logger?.debug(`Message age: ${formatTimeDelta(ageSeconds)}`); + return ageSeconds > thresholdSeconds; +} diff --git a/apps/whatsapp/src/webhook/parseWebhook.ts b/apps/whatsapp/src/webhook/parseWebhook.ts new file mode 100644 index 00000000..08d3a933 --- /dev/null +++ b/apps/whatsapp/src/webhook/parseWebhook.ts @@ -0,0 +1,226 @@ +/** + * Read what Meta's webhook says: which number it is for, whether it is a delivery receipt or a message, and who wrote it. + * + * Python counterpart: `parse_meta_payload` in `legacy/whatsapp/src/ansari_whatsapp/utils/whatsapp_webhook_utils.py`. + * (Its signature check and response helper belong to the HTTP layer and are ported with it.) + * + * A TypeScript type is erased when the program is compiled, so nothing about the type of `body` is checked while the + * service runs. That is why the parameter is `unknown` ("could be anything; look before you use it") and every step + * below narrows it with a check, much as Python's `dict.get` calls and `isinstance` checks do. + * + * Differences from Python: + * - It returns a tagged union (`ParsedWebhook`) instead of an 8-tuple of flags. The `kind` field tells the compiler + * which other fields exist, so `message.bsuid` only type-checks once `kind === 'message'` has been checked. + * - It is synchronous (the Python one was `async` but never awaited anything) and takes the settings it needs as an + * argument instead of reading them from a global. + * - Python raised a bare `Exception`, `IndexError` or `ValueError` for malformed bodies. All of those are + * `InvalidMetaPayloadError` here; the one case where the user can still be told is `UnexpectedMetaPayloadError`. + * - Errors and log lines carry the payload with its text masked (``), never the raw message or numbers. + * - A `from_user_id` that is not a non-empty string is refused. Python passed any value along and failed later. + */ +import type { Env } from '../config'; +import { InvalidMetaPayloadError, UnexpectedMetaPayloadError } from '../errors'; +import type { Logger } from '../logger'; +import { redactValues } from '../logMasking'; + +/** What a webhook turned out to be. */ +export type ParsedWebhook = + /** Meant for another business number on the same app; ignore. */ + | { kind: 'other_number' } + /** A delivery receipt (sent, delivered, read), not a user message; ignore. */ + | { kind: 'status' } + /** A message from a user. */ + | { + kind: 'message'; + /** The sender's business-scoped user ID: the only identity this service uses. */ + bsuid: string; + /** `text`, `image`, ... or `errors` when Meta sent an unsupported type (video note, gif, poll). */ + messageType: string; + /** Whatever Meta put under that type; `{ body: '...' }` for text, a list for `errors`. */ + messageBody: unknown; + messageId: string | null; + /** Unix seconds, or `null` when Meta sent none. */ + messageUnixTime: number | null; + /** The webhook's `from`, only read when `META_REPLY_BY_PHONE` is on, and used only to address the reply. */ + senderPhone: string | null; + }; + +/** What `parseMetaPayload` needs from the settings. `Pick` takes just those two fields of the full `Env` type. */ +export type WebhookConfig = Pick; + +/** + * Keys whose string values are safe to log as they are. Everything else is masked: phone numbers, names, text, and ids + * (a message id is base64 that carries the sender's phone number). + */ +const UNREDACTED_KEYS: ReadonlySet = new Set(['object', 'field', 'messaging_product', 'type', 'timestamp']); + +function redactForLogging(value: unknown): string { + return JSON.stringify(redactValues(value, UNREDACTED_KEYS)); +} + +/** + * A type guard: when it returns true, TypeScript treats `value` as a plain object in the code that follows. + * (Python: `isinstance(value, dict)`.) Arrays and `null` are objects in JavaScript, so they are excluded explicitly. + */ +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** + * Does `obj` have its own property `key`? (Python: `key in dict`.) JavaScript's `in` operator also finds inherited + * names such as `constructor` and `toString`, so a message declaring `"type": "constructor"` would be taken for a + * message that has a `constructor` field. `Object.hasOwn` looks only at the object's own keys. + */ +function has(obj: object, key: string): boolean { + return Object.hasOwn(obj, key); +} + +/** Python's `list` repr, `['a', 'b']`, so error messages read the same as before. */ +function pythonList(items: string[]): string { + return `[${items.map((item) => `'${item}'`).join(', ')}]`; +} + +function invalidPayload(message: string, logger?: Pick): InvalidMetaPayloadError { + logger?.error(message); + return new InvalidMetaPayloadError(message); +} + +/** `entry[0].changes[0].value`, if the envelope is shaped as Meta documents it and the value is not empty. */ +function findValue(body: unknown): Record | undefined { + if (!isRecord(body) || !body.object) return undefined; + + const entry = body.entry; + if (!Array.isArray(entry) || entry.length === 0) return undefined; + const firstEntry: unknown = entry[0]; + if (!isRecord(firstEntry)) return undefined; + + const changes = firstEntry.changes; + if (!Array.isArray(changes) || changes.length === 0) return undefined; + const firstChange: unknown = changes[0]; + if (!isRecord(firstChange)) return undefined; + + const value = firstChange.value; + return isRecord(value) && Object.keys(value).length > 0 ? value : undefined; +} + +/** + * Python's `int(timestamp)` for what Meta sends: a string of digits. A missing or null timestamp is `null`. + * (Python's `int()` also accepts underscores and non-ASCII digits; Meta sends neither.) + */ +function parseUnixTime(raw: unknown): number | null { + if (raw === undefined || raw === null) return null; + if (typeof raw === 'number' && Number.isFinite(raw)) return Math.trunc(raw); + if (typeof raw === 'string' && /^\s*[+-]?\d+\s*$/.test(raw)) return Number.parseInt(raw, 10); + throw new InvalidMetaPayloadError(`The message timestamp is not an integer (it is ${typeof raw})`); +} + +/** A message whose payload lacks `key`: the user can still be told, so the sender is worked out for the reply. */ +function missingKey( + key: string, + message: Record, + value: Record, + logger?: Pick, +): UnexpectedMetaPayloadError { + logger?.error(`Missing key '${key}' in messages[0]; redacted webhook value: ${redactForLogging(value)}`); + + const contacts = value.contacts; + const contact = Array.isArray(contacts) && contacts.length > 0 && isRecord(contacts[0]) ? contacts[0] : {}; + const fromMessage = typeof message.from_user_id === 'string' ? message.from_user_id : ''; + const fromContact = typeof contact.user_id === 'string' ? contact.user_id : ''; + + return new UnexpectedMetaPayloadError( + `Missing key '${key}' in messages[0]; keys present: ${pythonList(Object.keys(message).sort())}`, + fromMessage || fromContact || undefined, + ); +} + +/** + * Parse the JSON body of a webhook request from Meta. + * + * @throws {UnexpectedMetaPayloadError} `messages[0]` lacks a key we need; carries who to tell, if known. + * @throws {InvalidMetaPayloadError} The body is not shaped as Meta documents it. + */ +export function parseMetaPayload( + body: unknown, + config: WebhookConfig, + logger?: Pick, +): ParsedWebhook { + const value = findValue(body); + if (value === undefined) { + throw invalidPayload( + `Invalid received payload from WhatsApp user and/or problem with Meta's API:\n${redactForLogging(body)}`, + logger, + ); + } + + // Metadata is always present in a valid webhook; it says which of our numbers the webhook is for + if (!has(value, 'metadata')) { + throw invalidPayload(`Missing metadata in webhook payload from WhatsApp API:\n${redactForLogging(value)}`, logger); + } + const metadata = value.metadata; + if (!isRecord(metadata) || !has(metadata, 'phone_number_id')) { + throw invalidPayload( + `Missing phone_number_id in webhook payload metadata:\n${redactForLogging(metadata)}`, + logger, + ); + } + + if (metadata.phone_number_id !== config.META_BUSINESS_PHONE_NUMBER_ID.reveal()) { + return { kind: 'other_number' }; + } + + // A delivery receipt (delivered, read, ...), not a message from a user + if (has(value, 'statuses')) return { kind: 'status' }; + + if (!has(value, 'messages')) { + throw invalidPayload(`Unsupported message type received from WhatsApp user:\n${redactForLogging(body)}`, logger); + } + const messages = value.messages; + if (!Array.isArray(messages) || messages.length === 0) { + throw invalidPayload(`The webhook has no message to read:\n${redactForLogging(value)}`, logger); + } + const message: unknown = messages[0]; + if (!isRecord(message)) { + throw invalidPayload(`messages[0] is not an object:\n${redactForLogging(value)}`, logger); + } + + // `from_user_id` (the BSUID) is always present and is the only identity used. + // `from` (the phone number) may be missing, and is read only when replies go to the phone (test numbers). + const messageId = typeof message.id === 'string' ? message.id : null; + + if (!has(message, 'from_user_id')) throw missingKey('from_user_id', message, value, logger); + const bsuid = message.from_user_id; + if (typeof bsuid !== 'string' || bsuid === '') { + throw new UnexpectedMetaPayloadError( + `Key 'from_user_id' in messages[0] must be a non-empty string; keys present: ${pythonList(Object.keys(message).sort())}`, + typeof message.from === 'string' && config.META_REPLY_BY_PHONE ? message.from : undefined, + ); + } + + const senderPhone = config.META_REPLY_BY_PHONE && typeof message.from === 'string' ? message.from : null; + const messageUnixTime = parseUnixTime(message.timestamp); + + if (!has(message, 'type')) throw missingKey('type', message, value, logger); + const declaredType = message.type; + // Python raises TypeError for a list or dict here (it cannot be looked up as a key) + if (Array.isArray(declaredType) || isRecord(declaredType)) { + throw invalidPayload(`messages[0].type is not a string:\n${redactForLogging(value)}`, logger); + } + + // Meta API note: Meta sends an "errors" key when receiving unsupported message types + // (e.g., video notes, gifs sent from giphy, or polls) + const messageType = typeof declaredType === 'string' && has(message, declaredType) ? declaredType : 'errors'; + if (!has(message, messageType)) throw missingKey(messageType, message, value, logger); + + logger?.info(`Received a supported whatsapp message (type: ${messageType})`); + + return { + kind: 'message', + bsuid, + messageType, + messageBody: message[messageType], + messageId, + messageUnixTime, + senderPhone, + }; +} diff --git a/apps/whatsapp/tests/fixtures/generate_python_oracle.py b/apps/whatsapp/tests/fixtures/generate_python_oracle.py new file mode 100644 index 00000000..f38e3131 --- /dev/null +++ b/apps/whatsapp/tests/fixtures/generate_python_oracle.py @@ -0,0 +1,428 @@ +"""Regenerate `pythonOracle.ts` from the legacy Python service (issue #358, plan phase 2). + +Why this exists: the Python test suite covers the message splitter well, but barely touches the markdown +formatter, the time helpers or the webhook parser. So that "the TypeScript port behaves like Python" is checked +rather than assumed, this script runs the legacy code on a table of inputs and writes the answers into a TypeScript +module that the Vitest tests import. The expected values in `pythonOracle.ts` are therefore Python's real output, +including its quirks (they are kept on purpose; see the comments in the TypeScript tests). + +Run from the repo root, with a Python that has the legacy service's dependencies (the `legacy/whatsapp` uv env): + + cd legacy/whatsapp + uv run python ../../apps/whatsapp/tests/fixtures/generate_python_oracle.py ../../apps/whatsapp/tests/fixtures/pythonOracle.ts + +It never talks to the network. Delete this file together with `legacy/whatsapp` once the Python service is gone; +`pythonOracle.ts` stays valid because it is plain data. +""" + +import asyncio +import copy +import datetime as _dt +import hashlib +import json +import math +import os +import sys + +# Dummy credentials, as in legacy/whatsapp/tests/conftest.py. Nothing here is a real secret. +for key, value in { + "DEPLOYMENT_TYPE": "local", + "MOCK_META_API": "True", + "MOCK_ANSARI_CLIENT": "True", + "MOCK_AUTH_CLIENT": "True", + "ALWAYS_RETURN_OK_TO_META": "False", + "AUTH_WHATSAPP_API_KEY": "test", + "META_BUSINESS_PHONE_NUMBER_ID": "123456789", + "META_WEBHOOK_VERIFY_TOKEN": "test", + "META_ANSARI_APP_SECRET": "test", + "META_ACCESS_TOKEN_FROM_SYS_USER": "test", + "MOCK_AUTH_TOKEN": "", +}.items(): + os.environ[key] = value + +from loguru import logger # noqa: E402 + +from ansari_whatsapp.presenters.whatsapp_message_formatter import ( # noqa: E402 + convert_bold_syntax, + convert_headers, + convert_italic_syntax, + format_for_whatsapp, + format_nested_lists, +) +from ansari_whatsapp.utils.config import get_settings # noqa: E402 +from ansari_whatsapp.utils.exceptions import UnexpectedMetaPayloadError # noqa: E402 +from ansari_whatsapp.utils.language_utils import get_language_direction_from_text # noqa: E402 +from ansari_whatsapp.utils import time_utils # noqa: E402 +from ansari_whatsapp.utils.time_utils import calculate_time_passed, format_time_delta, is_message_too_old # noqa: E402 +from ansari_whatsapp.utils.whatsapp_message_splitter import split_message # noqa: E402 +from ansari_whatsapp.utils.whatsapp_webhook_utils import parse_meta_payload # noqa: E402 + +logger.remove() # the parser logs the payloads it rejects; keep this script quiet + +# A frozen clock, so "how old is this message" has one answer. The TypeScript tests pass the same instant in. +FIXED_NOW = _dt.datetime(2026, 11, 10, 12, 0, 0, tzinfo=_dt.timezone.utc) +FIXED_NOW_UNIX = int(FIXED_NOW.timestamp()) + + +class _FrozenDatetime(_dt.datetime): + @classmethod + def now(cls, tz=None): + return FIXED_NOW + + +time_utils.datetime = _FrozenDatetime + +AR = "\u0645\u0631\u062d\u0628\u0627" # an Arabic word, written as escapes so this file stays ASCII +BSUID = "US.13491208655302741918" +PHONE_ID = "123456789" + +# --------------------------------------------------------------------------------------------------------------------- +# Formatter +# --------------------------------------------------------------------------------------------------------------------- + +FORMATTER_INPUTS = [ + "plain text", + "Hello **bold** world", + "Hello *italic* world", + "Mix **bold** and *italic* together", + "***both***", + "***bold italic***", + "_*mixed*_", + "**a** and **b**", + "*a*b*c*", + "*a\nb*", + "snake_case and *it_alic* here", + "a * b * c", + "2 * 3 = 6 and 4 * 5 = 20", + "## Title\n\nBody text", + "## Title\nBody text right after", + "# Big\n\n## Medium\n\n### Small\n\nEnd", + "## **Bold header**\n\nText", + "## _Italic header_\n\nText", + "Text before\n\n## Header\n\nText after", + "text ## inline header\nnext line", + "## H1\n## H2\n\nbody", + "## \nempty header text", + "#hashtag not a header", + "1. one\n2. two\n3. three", + "- a\n- b\n- c", + "* a\n* b", + "1. one\n - nested a\n - nested b\n2. two", + "- bullet\n 1. nested one\n 2. nested two\n- bullet two", + "- a\n - b\n - c\n- d", + "1. a\n 1. b\n 2. c\n2. d", + "* a\n * b\n * c", + "- a\n * b\n * c", + " - indented first\n - indented second", + "- a\n - deep\n - mid\n- back", + "- item\n\n - after blank\n- end", + "- a - b - c\n - d - e", + "1. x 2. y\n 3. z 4. w", + "tabs\there\n\t- tab nested\n\t- tab nested 2", + "\u00a0\u00a0- nbsp nested\n\u2003- emsp nested", + "**unclosed bold", + "*unclosed italic", + "line one\r\nline two\r\n## Header\r\n\r\nbody", + "- a\r\n - b\r\n- c", + "emoji \U0001f600 **bold** \U0001f600", + # Arabic (right-to-left) text goes through the list formatter; Python's \d also matches Arabic-Indic digits + AR + " **" + AR + "** " + AR, + "## \u0639\u0646\u0648\u0627\u0646\n\n\u0646\u0635", + "\u0627\u0644\u0646\u0642\u0627\u0637:\n1. \u0623\u0648\u0644\n - \u0641\u0631\u0639\u064a\n2. \u062b\u0627\u0646\u064a", + "\u0661. \u0623\u0648\u0644\n \u0662. \u0641\u0631\u0639\u064a\n\u0662. \u062b\u0627\u0646\u064a", + "- " + AR + "\n \u0661. " + AR + "\n \u0662. " + AR, + "Mostly English with " + AR, + AR + AR + " mostly english text here to push the RTL share under the threshold, so lists stay as they are", +] + +ITALIC_INPUTS = ["*a*", "**a**", "*a* and *b*", "_*a*_", "*a b c*", "*a_b*", "x*y*z", "*", "**", "* a *", "*a\n*"] +BOLD_INPUTS = ["**a**", "**a** **b**", "***a***", "*a*", "****", "**", "*"] +HEADER_INPUTS = [ + "# H\nbody", + "# H\n\nbody", + "## H\n\n\nbody", + "### *_H_*\nx", + "text\n# H\n", + "# H", + "#### deep\nx", + "#nospace\nx", + "# H\r\nbody", + "# H\r\n\r\nbody", +] +NESTED_INPUTS = [ + "- a\n - b", + "1. a\n 2. b", + " * a", + "- a\n - b\n- c\n - d", + "text\n - a", + "- a\n\n - b", + "\u0661. a\n \u0662. b", + " - a - b", + " 1. a 2. b", +] + +# One bold-or-italic marker per case would hide Unicode bugs, so the direction cases lean on Arabic and emoji. +# 4 right-to-left characters out of 12 code points is 33% (RTL); counted as UTF-16 units it would be 20% (LTR). +DIRECTION_INPUTS = [ + "hello", + AR, + "ab " + AR, + AR + " a", + " ", + "12345", + "\u0645" * 3 + "a" * 7, + "\u0645" * 4 + "a" * 6, + "\u0645" * 31 + "a" * 69, + "\u0645" * 30 + "a" * 70, + "\u0645" * 300 + "a" * 700, + "\ufb50\ufb51 test", + "\u0750\u0751\u0752 x", + "\u08a0\u08a1 x", + "\u0645\u0631\u062d\u0628" + "\U0001f600" * 8, + "\u0645\u0631\u062d\u0628" + "\U0001f600" * 12, +] + +TIME_DELTA_INPUTS = [0, 0.04, 0.05, 0.25, 1, 5.25, 5.35, 59.94, 59.95, 59.99, 60, 61.5, 90, 3599, 3599.99, 3600, 5400, + 86399, 86400, 129600, 1e9] + +# Seconds since the last message; None means "never". Negative means a message from the future. +TIME_PASSED_INPUTS = [None, 0, 0.25, 5.25, 59.94, 59.95, 60, 90, 3599.99, 3600, 5400, 86399, 86400, 129600, 1e7, -30] + + +def _num(x: float): + """JSON has no infinity; spell it the way the TypeScript test reads it.""" + return "inf" if math.isinf(x) else x + + +def time_passed_case(seconds_ago): + last = None if seconds_ago is None else FIXED_NOW - _dt.timedelta(seconds=seconds_ago) + passed, logging_text = calculate_time_passed(last) + return [seconds_ago, _num(passed), logging_text] + + +# Message ages are given as seconds before FIXED_NOW (the retention threshold is the default, 86400). +# Timestamps beyond year 9999 are deliberately NOT here: CPython raises ValueError on Linux (caught, so "not too +# old") but OSError on Windows (not caught, so the call crashes), so this machine cannot give Railway's answer. +# The TypeScript tests cover that case on their own and say so. +MESSAGE_AGE_INPUTS = [None, 0, 100, 86399, 86400, 86401, -3600] + + +def message_age_case(age): + unix = None if age is None else FIXED_NOW_UNIX - age + return [age, unix, is_message_too_old(unix)] + + +# --------------------------------------------------------------------------------------------------------------------- +# Splitter: inputs are described by a recipe both languages can rebuild; the expected answer is a summary +# --------------------------------------------------------------------------------------------------------------------- + +LIMIT = 4000 + + +def _paragraphs(count: int, size: int = 500) -> str: + return "\n\n".join(f"{i:03d} " + "w" * (size - 4) for i in range(count)) + + +URL = "https://example.org/" + "u" * 200 +BOLD = "*" + "b" * 100 + "*" +SECTION = "*_Title_*\n" + "x" * 2500 + +SPLITTER_RECIPES = { + "short": "hello", + "exactly_the_limit": "a" * LIMIT, + "one_over_the_limit_without_spaces": "a" * (LIMIT + 1), + "thirty_paragraphs": _paragraphs(30), + "giant_unbroken": "".join(chr(97 + i % 26) for i in range(LIMIT * 2 + 123)), + "three_header_sections": "\n\n".join([SECTION, SECTION, SECTION]), + "long_prefix_then_headers": "\n\n".join(["q" * 1500] * 4) + "\n\n*_H1_*\n" + "x" * 100 + "\n\n*_H2_*\n" + "y" * 100, + "header_section_too_long": "*_A_*\n" + "z" * 4500 + "\n\n*_B_*\n" + "z" * 100, + "bold_sections": "\n\n".join(f"*Item {i}* " + "word " * 700 for i in range(4)), + "long_bold_phrase": "\n\n".join([BOLD + " " + "a" * 3500, BOLD + " " + "c" * 3500]), + "url_at_the_boundary": "a" * (LIMIT - 50) + " " + URL + " " + "z" * 500, + "words_without_paragraphs": "lorem ipsum dolor " * 600, + "lines_without_blank_lines": "line of text\n" * 400, + "emoji_only_over_the_limit": "\U0001f600" * (LIMIT + 1), + "emoji_at_the_boundary": "a" * (LIMIT - 1) + "\U0001f600" * 3, + "emoji_and_spaces": "\U0001f600 " * 3000, + # 1500 emoji is 1500 code points but 3000 UTF-16 units: two such paragraphs pack together only when counted the + # way Python counts (1500 + 1500 + 2 <= 4000) + "emoji_paragraphs": "\n\n".join(["\U0001f600" * 1500] * 3), + "arabic_words": "\u0643\u0644\u0645\u0629 " * 2000, + "one_paragraph_too_long_in_the_middle": "short\n\n" + "x" * 4500 + "\n\nshort two", + "several_blank_lines": "a" * 2000 + "\n\n\n\n" + "b" * 2500, + # Python returns NO chunks for an answer that is only newlines (the split leaves one empty paragraph) + "only_newlines": "\n" * 5000, + "only_spaces": " " * 4001, +} + + +def summarise(chunks: list[str]) -> dict: + return { + "count": len(chunks), + "lengths": [len(c) for c in chunks], # code points, the way Python counts + "sha256": hashlib.sha256("\x00".join(chunks).encode("utf-8")).hexdigest(), + } + + +# --------------------------------------------------------------------------------------------------------------------- +# Webhook parser +# --------------------------------------------------------------------------------------------------------------------- + + +def meta(phone_id: str = PHONE_ID) -> dict: + return {"phone_number_id": phone_id, "display_phone_number": "+1234567890"} + + +def payload(value) -> dict: + return {"object": "whatsapp_business_account", "entry": [{"changes": [{"value": value}]}]} + + +def text_message(**extra) -> dict: + msg = {"from_user_id": BSUID, "id": "wamid.TEST", "timestamp": "1700000000", "type": "text", "text": {"body": "hello"}} + msg.update(extra) + return msg + + +def without(msg: dict, *keys: str) -> dict: + return {k: v for k, v in msg.items() if k not in keys} + + +PARSER_CASES = [ + # (name, payload, META_REPLY_BY_PHONE) + ("text message", payload({"metadata": meta(), "messages": [text_message()]}), False), + ("sender phone ignored when replies by phone are off", payload({"metadata": meta(), "messages": [text_message(**{"from": "201234567899"})]}), False), + ("sender phone read when replies by phone are on", payload({"metadata": meta(), "messages": [text_message(**{"from": "201234567899"})]}), True), + ("replies by phone on but no sender phone", payload({"metadata": meta(), "messages": [text_message()]}), True), + ("status update", payload({"metadata": meta(), "statuses": [{"id": "wamid.S", "status": "delivered"}]}), False), + ("another business number", payload({"metadata": meta("999"), "messages": [text_message()]}), False), + ("status for another business number", payload({"metadata": meta("999"), "statuses": [{"id": "x"}]}), False), + ("unsupported message type", payload({"metadata": meta(), "messages": [{"from_user_id": BSUID, "id": "wamid.U", "timestamp": "1700000000", "type": "unsupported", "errors": [{"code": 131051, "title": "Message type is not supported"}]}]}), False), + ("image message", payload({"metadata": meta(), "messages": [{"from_user_id": BSUID, "id": "wamid.I", "timestamp": "1700000000", "type": "image", "image": {"id": "1", "mime_type": "image/jpeg"}}]}), False), + ("no timestamp", payload({"metadata": meta(), "messages": [without(text_message(), "timestamp")]}), False), + ("timestamp as a number", payload({"metadata": meta(), "messages": [text_message(timestamp=1700000000)]}), False), + ("timestamp that is not a number", payload({"metadata": meta(), "messages": [text_message(timestamp="abc")]}), False), + ("missing from_user_id, contact has user_id", payload({"metadata": meta(), "messages": [without(text_message(), "from_user_id")], "contacts": [{"user_id": "US.999"}]}), False), + ("missing from_user_id, no contacts", payload({"metadata": meta(), "messages": [without(text_message(), "from_user_id")]}), False), + ("missing type", payload({"metadata": meta(), "messages": [without(text_message(), "type")]}), False), + ("declared type has no matching key and no errors key", payload({"metadata": meta(), "messages": [without(text_message(), "text")]}), False), + ("declared type that is an object property name", payload({"metadata": meta(), "messages": [text_message(type="constructor")]}), False), + ("empty body", {}, False), + ("no object key", {"entry": [{"changes": [{"value": {"metadata": meta(), "messages": [text_message()]}}]}]}, False), + ("empty entry list", {"object": "whatsapp_business_account", "entry": []}, False), + ("empty changes list", {"object": "whatsapp_business_account", "entry": [{"changes": []}]}, False), + ("empty value", payload({}), False), + ("no metadata", payload({"messages": [text_message()]}), False), + ("no phone_number_id in metadata", payload({"metadata": {"display_phone_number": "+1"}, "messages": [text_message()]}), False), + ("neither messages nor statuses", payload({"metadata": meta()}), False), + ("empty messages list", payload({"metadata": meta(), "messages": []}), False), + ("only the first entry is read", {"object": "whatsapp_business_account", "entry": [ + {"changes": [{"value": {"metadata": meta(), "messages": [text_message()]}}]}, "garbage"]}, False), +] + + +def run_parser(body: dict, reply_by_phone: bool) -> dict: + get_settings().META_REPLY_BY_PHONE = reply_by_phone + try: + result = asyncio.run(parse_meta_payload(copy.deepcopy(body))) + except UnexpectedMetaPayloadError as e: + return {"error": "unexpected_payload", "pythonClass": type(e).__name__, "replyTo": e.reply_to, "message": str(e)} + except Exception as e: # noqa: BLE001 - main.py also catches everything else the same way + return {"error": "invalid_payload", "pythonClass": type(e).__name__} + is_status, is_target, bsuid, msg_type, msg_body, msg_id, unix_time, sender_phone = result + if not is_target: + return {"kind": "other_number"} + if is_status: + return {"kind": "status"} + return { + "kind": "message", + "bsuid": bsuid, + "messageType": msg_type, + "messageBody": msg_body, + "messageId": msg_id, + "messageUnixTime": unix_time, + "senderPhone": sender_phone, + } + + +def expect_error(fn, *args) -> str: + try: + fn(*args) + except Exception as e: # noqa: BLE001 + return type(e).__name__ + return "no error" + + +def main(out_path: str) -> None: + data = { + "FORMATTER_CASES": [[t, format_for_whatsapp(t)] for t in FORMATTER_INPUTS], + "ITALIC_CASES": [[t, convert_italic_syntax(t)] for t in ITALIC_INPUTS], + "BOLD_CASES": [[t, convert_bold_syntax(t)] for t in BOLD_INPUTS], + "HEADER_CASES": [[t, convert_headers(t)] for t in HEADER_INPUTS], + "NESTED_LIST_CASES": [[t, format_nested_lists(t)] for t in NESTED_INPUTS], + "DIRECTION_CASES": [[t, get_language_direction_from_text(t)] for t in DIRECTION_INPUTS], + "TIME_DELTA_CASES": [[s, format_time_delta(s)] for s in TIME_DELTA_INPUTS], + "TIME_PASSED_CASES": [time_passed_case(s) for s in TIME_PASSED_INPUTS], + "MESSAGE_AGE_CASES": [message_age_case(a) for a in MESSAGE_AGE_INPUTS], + "SPLITTER_CASES": {name: summarise(split_message(text)) for name, text in SPLITTER_RECIPES.items()}, + "PARSER_CASES": [ + {"name": name, "replyByPhone": by_phone, "payload": body, "expected": run_parser(body, by_phone)} + for name, body, by_phone in PARSER_CASES + ], + # Python crashes on the empty string (ZeroDivisionError). Nothing can send one: the callers check first. + "EMPTY_TEXT": { + "direction": expect_error(get_language_direction_from_text, ""), + "format": expect_error(format_for_whatsapp, ""), + }, + } + + types = { + "FORMATTER_CASES": "Cases", + "ITALIC_CASES": "Cases", + "BOLD_CASES": "Cases", + "HEADER_CASES": "Cases", + "NESTED_LIST_CASES": "Cases", + "DIRECTION_CASES": "Cases", + "TIME_DELTA_CASES": "Array<[seconds: number, formatted: string]>", + "TIME_PASSED_CASES": "Array<[secondsAgo: number | null, passed: number | 'inf', logging: string]>", + "MESSAGE_AGE_CASES": "Array<[secondsAgo: number | null, unixTime: number | null, tooOld: boolean]>", + "SPLITTER_CASES": "Record", + "PARSER_CASES": "ParserCase[]", + "EMPTY_TEXT": "{ direction: string; format: string }", + } + + lines = [ + f"// Frozen clock used for the time cases: unix {FIXED_NOW_UNIX} ({FIXED_NOW.isoformat()}).", + "// GENERATED by tests/fixtures/generate_python_oracle.py from legacy/whatsapp. Do not edit by hand.", + "// Every expected value below is what the legacy Python service returned, quirks included.", + "// Regenerate with the command in the script's docstring.", + "", + "/** [input, what Python produced]. Mutable tuples, because Vitest's it.each does not accept readonly ones. */", + "type Cases = Array<[input: string, expected: string]>;", + "", + "/** Chunk count, each chunk's length in code points (how Python counts), and a hash of the chunks joined by NUL. */", + "export interface SplitSummary {", + " count: number;", + " lengths: number[];", + " sha256: string;", + "}", + "", + f"export const FIXED_NOW_UNIX = {FIXED_NOW_UNIX};", + "", + "export interface ParserCase {", + " name: string;", + " replyByPhone: boolean;", + " payload: unknown;", + " expected: Record;", + "}", + "", + ] + for name, body in data.items(): + lines.append(f"export const {name}: {types[name]} = {json.dumps(body, ensure_ascii=True, indent=2)};") + lines.append("") + with open(out_path, "w", encoding="utf-8", newline="\n") as f: + f.write("\n".join(lines)) + print("wrote", out_path) + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/apps/whatsapp/tests/fixtures/pythonOracle.ts b/apps/whatsapp/tests/fixtures/pythonOracle.ts new file mode 100644 index 00000000..7c0f34f5 --- /dev/null +++ b/apps/whatsapp/tests/fixtures/pythonOracle.ts @@ -0,0 +1,1787 @@ +// Frozen clock used for the time cases: unix 1794312000 (2026-11-10T12:00:00+00:00). +// GENERATED by tests/fixtures/generate_python_oracle.py from legacy/whatsapp. Do not edit by hand. +// Every expected value below is what the legacy Python service returned, quirks included. +// Regenerate with the command in the script's docstring. + +/** [input, what Python produced]. Mutable tuples, because Vitest's it.each does not accept readonly ones. */ +type Cases = Array<[input: string, expected: string]>; + +/** Chunk count, each chunk's length in code points (how Python counts), and a hash of the chunks joined by NUL. */ +export interface SplitSummary { + count: number; + lengths: number[]; + sha256: string; +} + +export const FIXED_NOW_UNIX = 1794312000; + +export interface ParserCase { + name: string; + replyByPhone: boolean; + payload: unknown; + expected: Record; +} + +export const FORMATTER_CASES: Cases = [ + [ + "plain text", + "plain text" + ], + [ + "Hello **bold** world", + "Hello *bold* world" + ], + [ + "Hello *italic* world", + "Hello _italic_ world" + ], + [ + "Mix **bold** and *italic* together", + "Mix *bold* and _italic_ together" + ], + [ + "***both***", + "**both**" + ], + [ + "***bold italic***", + "**bold italic**" + ], + [ + "_*mixed*_", + "_*mixed*_" + ], + [ + "**a** and **b**", + "*a* and *b*" + ], + [ + "*a*b*c*", + "_a_b_c_" + ], + [ + "*a\nb*", + "_a\nb_" + ], + [ + "snake_case and *it_alic* here", + "snake_case and *it_alic* here" + ], + [ + "a * b * c", + "a _ b _ c" + ], + [ + "2 * 3 = 6 and 4 * 5 = 20", + "2 _ 3 = 6 and 4 _ 5 = 20" + ], + [ + "## Title\n\nBody text", + "*_Title_*\n\nBody text" + ], + [ + "## Title\nBody text right after", + "*_Title_*\n\nBody text right after" + ], + [ + "# Big\n\n## Medium\n\n### Small\n\nEnd", + "*_Big_*\n\n*_Medium_*\n\n*_Small_*\n\nEnd" + ], + [ + "## **Bold header**\n\nText", + "*_Bold header_*\n\nText" + ], + [ + "## _Italic header_\n\nText", + "*_Italic header_*\n\nText" + ], + [ + "Text before\n\n## Header\n\nText after", + "Text before\n\n*_Header_*\n\nText after" + ], + [ + "text ## inline header\nnext line", + "text *_inline header_*\n\nnext line" + ], + [ + "## H1\n## H2\n\nbody", + "*_H1_*\n\n*_H2_*\n\nbody" + ], + [ + "## \nempty header text", + "*__*\n\nempty header text" + ], + [ + "#hashtag not a header", + "#hashtag not a header" + ], + [ + "1. one\n2. two\n3. three", + "1. one\n2. two\n3. three" + ], + [ + "- a\n- b\n- c", + "- a\n- b\n- c" + ], + [ + "* a\n* b", + "_ a\n_ b" + ], + [ + "1. one\n - nested a\n - nested b\n2. two", + "1. one\n -- nested a\n -- nested b\n2. two" + ], + [ + "- bullet\n 1. nested one\n 2. nested two\n- bullet two", + "- bullet\n 1 - nested one\n 2 - nested two\n- bullet two" + ], + [ + "- a\n - b\n - c\n- d", + "- a\n -- b\n -- c\n- d" + ], + [ + "1. a\n 1. b\n 2. c\n2. d", + "1. a\n 1 - b\n 2 - c\n2. d" + ], + [ + "* a\n * b\n * c", + "_ a\n _ b\n -- c" + ], + [ + "- a\n * b\n * c", + "- a\n _ b\n _ c" + ], + [ + " - indented first\n - indented second", + " -- indented first\n -- indented second" + ], + [ + "- a\n - deep\n - mid\n- back", + "- a\n -- deep\n -- mid\n- back" + ], + [ + "- item\n\n - after blank\n- end", + "- item\n\n -- after blank\n- end" + ], + [ + "- a - b - c\n - d - e", + "- a - b - c\n -- d -- e" + ], + [ + "1. x 2. y\n 3. z 4. w", + "1. x 2. y\n 3 - z 4 - w" + ], + [ + "tabs\there\n\t- tab nested\n\t- tab nested 2", + "tabs\there\n\t-- tab nested\n\t-- tab nested 2" + ], + [ + "\u00a0\u00a0- nbsp nested\n\u2003- emsp nested", + "\u00a0\u00a0-- nbsp nested\n\u2003-- emsp nested" + ], + [ + "**unclosed bold", + "*unclosed bold" + ], + [ + "*unclosed italic", + "*unclosed italic" + ], + [ + "line one\r\nline two\r\n## Header\r\n\r\nbody", + "line one\r\nline two\r\n*_Header\r_*\n\n\r\nbody" + ], + [ + "- a\r\n - b\r\n- c", + "- a\r\n -- b\r\n- c" + ], + [ + "emoji \ud83d\ude00 **bold** \ud83d\ude00", + "emoji \ud83d\ude00 *bold* \ud83d\ude00" + ], + [ + "\u0645\u0631\u062d\u0628\u0627 **\u0645\u0631\u062d\u0628\u0627** \u0645\u0631\u062d\u0628\u0627", + "\u0645\u0631\u062d\u0628\u0627 *\u0645\u0631\u062d\u0628\u0627* \u0645\u0631\u062d\u0628\u0627" + ], + [ + "## \u0639\u0646\u0648\u0627\u0646\n\n\u0646\u0635", + "*_\u0639\u0646\u0648\u0627\u0646_*\n\n\u0646\u0635" + ], + [ + "\u0627\u0644\u0646\u0642\u0627\u0637:\n1. \u0623\u0648\u0644\n - \u0641\u0631\u0639\u064a\n2. \u062b\u0627\u0646\u064a", + "\u0627\u0644\u0646\u0642\u0627\u0637:\n1. \u0623\u0648\u0644\n -- \u0641\u0631\u0639\u064a\n2. \u062b\u0627\u0646\u064a" + ], + [ + "\u0661. \u0623\u0648\u0644\n \u0662. \u0641\u0631\u0639\u064a\n\u0662. \u062b\u0627\u0646\u064a", + "\u0661. \u0623\u0648\u0644\n \u0662 - \u0641\u0631\u0639\u064a\n\u0662. \u062b\u0627\u0646\u064a" + ], + [ + "- \u0645\u0631\u062d\u0628\u0627\n \u0661. \u0645\u0631\u062d\u0628\u0627\n \u0662. \u0645\u0631\u062d\u0628\u0627", + "- \u0645\u0631\u062d\u0628\u0627\n \u0661 - \u0645\u0631\u062d\u0628\u0627\n \u0662 - \u0645\u0631\u062d\u0628\u0627" + ], + [ + "Mostly English with \u0645\u0631\u062d\u0628\u0627", + "Mostly English with \u0645\u0631\u062d\u0628\u0627" + ], + [ + "\u0645\u0631\u062d\u0628\u0627\u0645\u0631\u062d\u0628\u0627 mostly english text here to push the RTL share under the threshold, so lists stay as they are", + "\u0645\u0631\u062d\u0628\u0627\u0645\u0631\u062d\u0628\u0627 mostly english text here to push the RTL share under the threshold, so lists stay as they are" + ] +]; + +export const ITALIC_CASES: Cases = [ + [ + "*a*", + "_a_" + ], + [ + "**a**", + "**a**" + ], + [ + "*a* and *b*", + "_a_ and _b_" + ], + [ + "_*a*_", + "_*a*_" + ], + [ + "*a b c*", + "_a b c_" + ], + [ + "*a_b*", + "*a_b*" + ], + [ + "x*y*z", + "x_y_z" + ], + [ + "*", + "*" + ], + [ + "**", + "**" + ], + [ + "* a *", + "_ a _" + ], + [ + "*a\n*", + "_a\n_" + ] +]; + +export const BOLD_CASES: Cases = [ + [ + "**a**", + "*a*" + ], + [ + "**a** **b**", + "*a* *b*" + ], + [ + "***a***", + "**a**" + ], + [ + "*a*", + "*a*" + ], + [ + "****", + "**" + ], + [ + "**", + "*" + ], + [ + "*", + "*" + ] +]; + +export const HEADER_CASES: Cases = [ + [ + "# H\nbody", + "*_H_*\n\nbody" + ], + [ + "# H\n\nbody", + "*_H_*\n\nbody" + ], + [ + "## H\n\n\nbody", + "*_H_*\n\n\nbody" + ], + [ + "### *_H_*\nx", + "*_H__*\n\nx" + ], + [ + "text\n# H\n", + "text\n*_H_*\n\n" + ], + [ + "# H", + "# H" + ], + [ + "#### deep\nx", + "*_deep_*\n\nx" + ], + [ + "#nospace\nx", + "#nospace\nx" + ], + [ + "# H\r\nbody", + "*_H\r_*\n\nbody" + ], + [ + "# H\r\n\r\nbody", + "*_H\r_*\n\n\r\nbody" + ] +]; + +export const NESTED_LIST_CASES: Cases = [ + [ + "- a\n - b", + "- a\n -- b" + ], + [ + "1. a\n 2. b", + "1. a\n 2 - b" + ], + [ + " * a", + " -- a" + ], + [ + "- a\n - b\n- c\n - d", + "- a\n -- b\n- c\n -- d" + ], + [ + "text\n - a", + "text\n -- a" + ], + [ + "- a\n\n - b", + "- a\n\n -- b" + ], + [ + "\u0661. a\n \u0662. b", + "\u0661. a\n \u0662 - b" + ], + [ + " - a - b", + " -- a -- b" + ], + [ + " 1. a 2. b", + " 1 - a 2 - b" + ] +]; + +export const DIRECTION_CASES: Cases = [ + [ + "hello", + "ltr" + ], + [ + "\u0645\u0631\u062d\u0628\u0627", + "rtl" + ], + [ + "ab \u0645\u0631\u062d\u0628\u0627", + "rtl" + ], + [ + "\u0645\u0631\u062d\u0628\u0627 a", + "rtl" + ], + [ + " ", + "ltr" + ], + [ + "12345", + "ltr" + ], + [ + "\u0645\u0645\u0645aaaaaaa", + "ltr" + ], + [ + "\u0645\u0645\u0645\u0645aaaaaa", + "rtl" + ], + [ + "\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "rtl" + ], + [ + "\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "ltr" + ], + [ + "\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645\u0645aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "ltr" + ], + [ + "\ufb50\ufb51 test", + "ltr" + ], + [ + "\u0750\u0751\u0752 x", + "rtl" + ], + [ + "\u08a0\u08a1 x", + "rtl" + ], + [ + "\u0645\u0631\u062d\u0628\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00", + "rtl" + ], + [ + "\u0645\u0631\u062d\u0628\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00", + "ltr" + ] +]; + +export const TIME_DELTA_CASES: Array<[seconds: number, formatted: string]> = [ + [ + 0, + "0.0 seconds" + ], + [ + 0.04, + "0.0 seconds" + ], + [ + 0.05, + "0.1 seconds" + ], + [ + 0.25, + "0.2 seconds" + ], + [ + 1, + "1.0 seconds" + ], + [ + 5.25, + "5.2 seconds" + ], + [ + 5.35, + "5.3 seconds" + ], + [ + 59.94, + "59.9 seconds" + ], + [ + 59.95, + "60.0 seconds" + ], + [ + 59.99, + "60.0 seconds" + ], + [ + 60, + "1.0 minutes" + ], + [ + 61.5, + "1.0 minutes" + ], + [ + 90, + "1.5 minutes" + ], + [ + 3599, + "60.0 minutes" + ], + [ + 3599.99, + "60.0 minutes" + ], + [ + 3600, + "1.0 hours" + ], + [ + 5400, + "1.5 hours" + ], + [ + 86399, + "24.0 hours" + ], + [ + 86400, + "1.0 days" + ], + [ + 129600, + "1.5 days" + ], + [ + 1000000000.0, + "11574.1 days" + ] +]; + +export const TIME_PASSED_CASES: Array<[secondsAgo: number | null, passed: number | 'inf', logging: string]> = [ + [ + null, + "inf", + "infdays" + ], + [ + 0, + 0.0, + "0.0sec" + ], + [ + 0.25, + 0.25, + "0.2sec" + ], + [ + 5.25, + 5.25, + "5.2sec" + ], + [ + 59.94, + 59.94, + "59.9sec" + ], + [ + 59.95, + 59.95, + "60.0sec" + ], + [ + 60, + 60.0, + "1.0mins" + ], + [ + 90, + 90.0, + "1.5mins" + ], + [ + 3599.99, + 3599.99, + "60.0mins" + ], + [ + 3600, + 3600.0, + "1.0hours" + ], + [ + 5400, + 5400.0, + "1.5hours" + ], + [ + 86399, + 86399.0, + "24.0hours" + ], + [ + 86400, + 86400.0, + "1.0days" + ], + [ + 129600, + 129600.0, + "1.5days" + ], + [ + 10000000.0, + 10000000.0, + "115.7days" + ], + [ + -30, + -30.0, + "-30.0sec" + ] +]; + +export const MESSAGE_AGE_CASES: Array<[secondsAgo: number | null, unixTime: number | null, tooOld: boolean]> = [ + [ + null, + null, + false + ], + [ + 0, + 1794312000, + false + ], + [ + 100, + 1794311900, + false + ], + [ + 86399, + 1794225601, + false + ], + [ + 86400, + 1794225600, + false + ], + [ + 86401, + 1794225599, + true + ], + [ + -3600, + 1794315600, + false + ] +]; + +export const SPLITTER_CASES: Record = { + "short": { + "count": 1, + "lengths": [ + 5 + ], + "sha256": "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" + }, + "exactly_the_limit": { + "count": 1, + "lengths": [ + 4000 + ], + "sha256": "82396ec9191a22922e88923ef14b5d225e26e7fc2d1571d0d6cd51920f83880b" + }, + "one_over_the_limit_without_spaces": { + "count": 2, + "lengths": [ + 4000, + 1 + ], + "sha256": "e0d8792a9fe43c5cd8ebe4abc2f51cf4736ac593855342989155f62f9ff7d0ef" + }, + "thirty_paragraphs": { + "count": 5, + "lengths": [ + 3512, + 3512, + 3512, + 3512, + 1002 + ], + "sha256": "247a2def436ec5cd3cf9b55fbd3ae1b5c3842b673a6f29a52584af02bf573e70" + }, + "giant_unbroken": { + "count": 3, + "lengths": [ + 4000, + 4000, + 123 + ], + "sha256": "3f0825e6b26eb418415c792adaed8b506b229fa0fe13e1715d11cdd68ef8159f" + }, + "three_header_sections": { + "count": 3, + "lengths": [ + 2512, + 2512, + 2510 + ], + "sha256": "423fd73c060e616e52d9c30b65a8deb2e18c3596857b69d8e7e988389034397c" + }, + "long_prefix_then_headers": { + "count": 4, + "lengths": [ + 3002, + 3004, + 109, + 107 + ], + "sha256": "67618dd77bd952e37d8583f86d7bada140c81b19cf628b6c5e41b7d1f70feeff" + }, + "header_section_too_long": { + "count": 3, + "lengths": [ + 4000, + 506, + 106 + ], + "sha256": "469db3a16f7d53aa16470d6084c61d7d1aefec5dc00f49bf9187541a5eabe1a5" + }, + "bold_sections": { + "count": 4, + "lengths": [ + 3511, + 3511, + 3511, + 3509 + ], + "sha256": "b5ed4cf4a2ac1a5264d8bab3976ce0f5daa74cdc32c56c399fee7ea5c893e110" + }, + "long_bold_phrase": { + "count": 2, + "lengths": [ + 3605, + 3603 + ], + "sha256": "0a1d5e4cb9f7d7c1bf0d111a6ae77cdfd35348edbcd3a6004b2d3974375fee32" + }, + "url_at_the_boundary": { + "count": 2, + "lengths": [ + 3951, + 721 + ], + "sha256": "4a3b105c0cb50e3082a690e618e59085c148404eaa7d15308c1d8f4210abf619" + }, + "words_without_paragraphs": { + "count": 3, + "lengths": [ + 3996, + 3996, + 2808 + ], + "sha256": "de0507993a38fa7d423ef57501e5e6131e12882e21eb4208f43f7ebe202168a9" + }, + "lines_without_blank_lines": { + "count": 2, + "lengths": [ + 3999, + 1201 + ], + "sha256": "b53740550a212a733f0d98bfcd30d26d9726caeb0cccddaf069faeae87f39a17" + }, + "emoji_only_over_the_limit": { + "count": 2, + "lengths": [ + 4000, + 1 + ], + "sha256": "a9b2940779cce93156b19887ac744c31d6586684e998aa193ec92789d61e0979" + }, + "emoji_at_the_boundary": { + "count": 2, + "lengths": [ + 4000, + 2 + ], + "sha256": "03493783d08e4321c5fd9046bc7c2f14f2666ee2868237871eecb1c52d993ac5" + }, + "emoji_and_spaces": { + "count": 2, + "lengths": [ + 4000, + 2000 + ], + "sha256": "5b84bcf98f0a363dc6eec0781e294f9bf9c298cd715da735155838269870f78a" + }, + "emoji_paragraphs": { + "count": 2, + "lengths": [ + 3002, + 1500 + ], + "sha256": "24e6a076a0b6afe361b450ba77e35132e9ef2b67be0fac2a30bd3eccebeafe4f" + }, + "arabic_words": { + "count": 3, + "lengths": [ + 4000, + 4000, + 2000 + ], + "sha256": "30a54ff2c6e0c3b7f80670aa7facd5be13bdc455ffb7a63f891954f69d686ac9" + }, + "one_paragraph_too_long_in_the_middle": { + "count": 4, + "lengths": [ + 5, + 4000, + 500, + 9 + ], + "sha256": "c85e982f1aaa702f54ea1b8f71e7bfa6aa8da9c7743810243c3f0e69fd7d77b3" + }, + "several_blank_lines": { + "count": 2, + "lengths": [ + 2000, + 2500 + ], + "sha256": "deacc7b9b5b20b5fba8675390811339f94c2ab5e36f4018cfc4913e686ec0cab" + }, + "only_newlines": { + "count": 0, + "lengths": [], + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "only_spaces": { + "count": 2, + "lengths": [ + 4000, + 1 + ], + "sha256": "74d2888cb13684d21db5787021288b7280639b903bcd7edfe5fa78f147f293fc" + } +}; + +export const PARSER_CASES: ParserCase[] = [ + { + "name": "text message", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "kind": "message", + "bsuid": "US.13491208655302741918", + "messageType": "text", + "messageBody": { + "body": "hello" + }, + "messageId": "wamid.TEST", + "messageUnixTime": 1700000000, + "senderPhone": null + } + }, + { + "name": "sender phone ignored when replies by phone are off", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text", + "text": { + "body": "hello" + }, + "from": "201234567899" + } + ] + } + } + ] + } + ] + }, + "expected": { + "kind": "message", + "bsuid": "US.13491208655302741918", + "messageType": "text", + "messageBody": { + "body": "hello" + }, + "messageId": "wamid.TEST", + "messageUnixTime": 1700000000, + "senderPhone": null + } + }, + { + "name": "sender phone read when replies by phone are on", + "replyByPhone": true, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text", + "text": { + "body": "hello" + }, + "from": "201234567899" + } + ] + } + } + ] + } + ] + }, + "expected": { + "kind": "message", + "bsuid": "US.13491208655302741918", + "messageType": "text", + "messageBody": { + "body": "hello" + }, + "messageId": "wamid.TEST", + "messageUnixTime": 1700000000, + "senderPhone": "201234567899" + } + }, + { + "name": "replies by phone on but no sender phone", + "replyByPhone": true, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "kind": "message", + "bsuid": "US.13491208655302741918", + "messageType": "text", + "messageBody": { + "body": "hello" + }, + "messageId": "wamid.TEST", + "messageUnixTime": 1700000000, + "senderPhone": null + } + }, + { + "name": "status update", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "statuses": [ + { + "id": "wamid.S", + "status": "delivered" + } + ] + } + } + ] + } + ] + }, + "expected": { + "kind": "status" + } + }, + { + "name": "another business number", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "999", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "kind": "other_number" + } + }, + { + "name": "status for another business number", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "999", + "display_phone_number": "+1234567890" + }, + "statuses": [ + { + "id": "x" + } + ] + } + } + ] + } + ] + }, + "expected": { + "kind": "other_number" + } + }, + { + "name": "unsupported message type", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.U", + "timestamp": "1700000000", + "type": "unsupported", + "errors": [ + { + "code": 131051, + "title": "Message type is not supported" + } + ] + } + ] + } + } + ] + } + ] + }, + "expected": { + "kind": "message", + "bsuid": "US.13491208655302741918", + "messageType": "errors", + "messageBody": [ + { + "code": 131051, + "title": "Message type is not supported" + } + ], + "messageId": "wamid.U", + "messageUnixTime": 1700000000, + "senderPhone": null + } + }, + { + "name": "image message", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.I", + "timestamp": "1700000000", + "type": "image", + "image": { + "id": "1", + "mime_type": "image/jpeg" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "kind": "message", + "bsuid": "US.13491208655302741918", + "messageType": "image", + "messageBody": { + "id": "1", + "mime_type": "image/jpeg" + }, + "messageId": "wamid.I", + "messageUnixTime": 1700000000, + "senderPhone": null + } + }, + { + "name": "no timestamp", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "type": "text", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "kind": "message", + "bsuid": "US.13491208655302741918", + "messageType": "text", + "messageBody": { + "body": "hello" + }, + "messageId": "wamid.TEST", + "messageUnixTime": null, + "senderPhone": null + } + }, + { + "name": "timestamp as a number", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": 1700000000, + "type": "text", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "kind": "message", + "bsuid": "US.13491208655302741918", + "messageType": "text", + "messageBody": { + "body": "hello" + }, + "messageId": "wamid.TEST", + "messageUnixTime": 1700000000, + "senderPhone": null + } + }, + { + "name": "timestamp that is not a number", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "abc", + "type": "text", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "error": "invalid_payload", + "pythonClass": "ValueError" + } + }, + { + "name": "missing from_user_id, contact has user_id", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text", + "text": { + "body": "hello" + } + } + ], + "contacts": [ + { + "user_id": "US.999" + } + ] + } + } + ] + } + ] + }, + "expected": { + "error": "unexpected_payload", + "pythonClass": "UnexpectedMetaPayloadError", + "replyTo": "US.999", + "message": "Missing key 'from_user_id' in messages[0]; keys present: ['id', 'text', 'timestamp', 'type']" + } + }, + { + "name": "missing from_user_id, no contacts", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "error": "unexpected_payload", + "pythonClass": "UnexpectedMetaPayloadError", + "replyTo": null, + "message": "Missing key 'from_user_id' in messages[0]; keys present: ['id', 'text', 'timestamp', 'type']" + } + }, + { + "name": "missing type", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "error": "unexpected_payload", + "pythonClass": "UnexpectedMetaPayloadError", + "replyTo": "US.13491208655302741918", + "message": "Missing key 'type' in messages[0]; keys present: ['from_user_id', 'id', 'text', 'timestamp']" + } + }, + { + "name": "declared type has no matching key and no errors key", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text" + } + ] + } + } + ] + } + ] + }, + "expected": { + "error": "unexpected_payload", + "pythonClass": "UnexpectedMetaPayloadError", + "replyTo": "US.13491208655302741918", + "message": "Missing key 'errors' in messages[0]; keys present: ['from_user_id', 'id', 'timestamp', 'type']" + } + }, + { + "name": "declared type that is an object property name", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "constructor", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "error": "unexpected_payload", + "pythonClass": "UnexpectedMetaPayloadError", + "replyTo": "US.13491208655302741918", + "message": "Missing key 'errors' in messages[0]; keys present: ['from_user_id', 'id', 'text', 'timestamp', 'type']" + } + }, + { + "name": "empty body", + "replyByPhone": false, + "payload": {}, + "expected": { + "error": "invalid_payload", + "pythonClass": "Exception" + } + }, + { + "name": "no object key", + "replyByPhone": false, + "payload": { + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "error": "invalid_payload", + "pythonClass": "Exception" + } + }, + { + "name": "empty entry list", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [] + }, + "expected": { + "error": "invalid_payload", + "pythonClass": "Exception" + } + }, + { + "name": "empty changes list", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [] + } + ] + }, + "expected": { + "error": "invalid_payload", + "pythonClass": "Exception" + } + }, + { + "name": "empty value", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": {} + } + ] + } + ] + }, + "expected": { + "error": "invalid_payload", + "pythonClass": "Exception" + } + }, + { + "name": "no metadata", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "error": "invalid_payload", + "pythonClass": "Exception" + } + }, + { + "name": "no phone_number_id in metadata", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "display_phone_number": "+1" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text", + "text": { + "body": "hello" + } + } + ] + } + } + ] + } + ] + }, + "expected": { + "error": "invalid_payload", + "pythonClass": "Exception" + } + }, + { + "name": "neither messages nor statuses", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + } + } + } + ] + } + ] + }, + "expected": { + "error": "invalid_payload", + "pythonClass": "Exception" + } + }, + { + "name": "empty messages list", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [] + } + } + ] + } + ] + }, + "expected": { + "error": "invalid_payload", + "pythonClass": "IndexError" + } + }, + { + "name": "only the first entry is read", + "replyByPhone": false, + "payload": { + "object": "whatsapp_business_account", + "entry": [ + { + "changes": [ + { + "value": { + "metadata": { + "phone_number_id": "123456789", + "display_phone_number": "+1234567890" + }, + "messages": [ + { + "from_user_id": "US.13491208655302741918", + "id": "wamid.TEST", + "timestamp": "1700000000", + "type": "text", + "text": { + "body": "hello" + } + } + ] + } + } + ] + }, + "garbage" + ] + }, + "expected": { + "kind": "message", + "bsuid": "US.13491208655302741918", + "messageType": "text", + "messageBody": { + "body": "hello" + }, + "messageId": "wamid.TEST", + "messageUnixTime": 1700000000, + "senderPhone": null + } + } +]; + +export const EMPTY_TEXT: { direction: string; format: string } = { + "direction": "ZeroDivisionError", + "format": "ZeroDivisionError" +}; diff --git a/apps/whatsapp/tests/formatter.test.ts b/apps/whatsapp/tests/formatter.test.ts new file mode 100644 index 00000000..97cf4d29 --- /dev/null +++ b/apps/whatsapp/tests/formatter.test.ts @@ -0,0 +1,90 @@ +/** + * Markdown to WhatsApp formatting. Python has no test for the formatter, so every expected value here is what the + * Python formatter returned (`tests/fixtures/pythonOracle.ts`), including its oddities. The extra tests below name the + * ones that surprise. + */ +import { describe, expect, it } from 'vitest'; +import { + convertBoldSyntax, + convertHeaders, + convertItalicSyntax, + formatForWhatsApp, + formatNestedLists, +} from '../src/formatting/whatsappMessageFormatter'; +import { + BOLD_CASES, + EMPTY_TEXT, + FORMATTER_CASES, + HEADER_CASES, + ITALIC_CASES, + NESTED_LIST_CASES, +} from './fixtures/pythonOracle'; + +describe('formatForWhatsApp (whole pipeline)', () => { + it.each(FORMATTER_CASES)('%j', (input, expected) => { + expect(formatForWhatsApp(input)).toBe(expected); + }); + + it('formats a typical answer end to end', () => { + const answer = '## Ruling\n\nThe **majority** hold it is *recommended*.\n\n1. First\n - detail a\n - detail b\n2. Second'; + expect(formatForWhatsApp(answer)).toBe( + '*_Ruling_*\n\nThe *majority* hold it is _recommended_.\n\n1. First\n -- detail a\n -- detail b\n2. Second', + ); + }); + + // Python raises ZeroDivisionError on empty text (inside the direction check). Callers return before formatting an + // empty answer, so this is unreachable; the port answers with the empty text. + it('returns empty text for empty text where Python raised ZeroDivisionError', () => { + expect(EMPTY_TEXT.format).toBe('ZeroDivisionError'); + expect(formatForWhatsApp('')).toBe(''); + }); +}); + +describe('the steps on their own', () => { + it.each(ITALIC_CASES)('italic %j', (input, expected) => { + expect(convertItalicSyntax(input)).toBe(expected); + }); + it.each(BOLD_CASES)('bold %j', (input, expected) => { + expect(convertBoldSyntax(input)).toBe(expected); + }); + it.each(HEADER_CASES)('headers %j', (input, expected) => { + expect(convertHeaders(input)).toBe(expected); + }); + it.each(NESTED_LIST_CASES)('nested lists %j', (input, expected) => { + expect(formatNestedLists(input)).toBe(expected); + }); +}); + +// These behaviours look like bugs. They are Python's, and the port keeps them until the owner decides otherwise. +describe('behaviour kept from Python on purpose', () => { + it('turns arithmetic stars into italics', () => { + expect(formatForWhatsApp('2 * 3 = 6 and 4 * 5 = 20')).toBe('2 _ 3 = 6 and 4 _ 5 = 20'); + }); + + it('turns *** into ** (a stray double star)', () => { + expect(formatForWhatsApp('***both***')).toBe('**both**'); + }); + + it('loses the bullets of a * list', () => { + expect(formatForWhatsApp('* a\n* b')).toBe('_ a\n_ b'); + }); + + it('puts a carriage return inside the header when the line ends in \\r\\n', () => { + expect(formatForWhatsApp('## Header\r\n\r\nbody')).toBe('*_Header\r_*\n\n\r\nbody'); + }); +}); + +describe('where JavaScript and Python differ, and the port follows Python', () => { + it('numbers nested items written with Arabic-Indic digits (JavaScript \\d would miss them)', () => { + expect(/\d/.test('\u0661')).toBe(false); + expect(formatNestedLists(' \u0661. item')).toBe(' \u0661 - item'); + }); + + it('rewrites every list marker on a line, not just the first', () => { + expect(formatNestedLists(' - a - b')).toBe(' -- a -- b'); + }); + + it('treats a no-break space as indentation, like Python', () => { + expect(formatNestedLists('\u00a0\u00a0- a')).toBe('\u00a0\u00a0-- a'); + }); +}); diff --git a/apps/whatsapp/tests/language.test.ts b/apps/whatsapp/tests/language.test.ts new file mode 100644 index 00000000..52afa67a --- /dev/null +++ b/apps/whatsapp/tests/language.test.ts @@ -0,0 +1,30 @@ +/** + * Text direction. Python has no test for it; the expected values are what the Python function returned + * (`tests/fixtures/pythonOracle.ts`). + */ +import { describe, expect, it } from 'vitest'; +import { getLanguageDirectionFromText } from '../src/utils/language'; +import { DIRECTION_CASES, EMPTY_TEXT } from './fixtures/pythonOracle'; + +describe('getLanguageDirectionFromText', () => { + it.each(DIRECTION_CASES)('%j -> %s', (text, expected) => { + expect(getLanguageDirectionFromText(text)).toBe(expected); + }); + + it('counts code points, not UTF-16 units, so emoji do not skew the share', () => { + // 4 Arabic letters and 8 emoji: 4/12 = 33% (right-to-left). By `.length` the emoji count double: 4/20 = 20% (ltr). + const text = '\u0645\u0631\u062d\u0628' + '\u{1F600}'.repeat(8); + expect(text.length).toBe(20); + expect(getLanguageDirectionFromText(text)).toBe('rtl'); + }); + + it('is left-to-right at exactly 30%, as in Python (the rule is "more than 30%")', () => { + expect(getLanguageDirectionFromText('\u0645'.repeat(3) + 'a'.repeat(7))).toBe('ltr'); + }); + + // Python raises ZeroDivisionError here. Callers never pass empty text, so this is a documented difference. + it('answers ltr for empty text where Python raised ZeroDivisionError', () => { + expect(EMPTY_TEXT.direction).toBe('ZeroDivisionError'); + expect(getLanguageDirectionFromText('')).toBe('ltr'); + }); +}); diff --git a/apps/whatsapp/tests/messageSplitter.test.ts b/apps/whatsapp/tests/messageSplitter.test.ts new file mode 100644 index 00000000..922e0834 --- /dev/null +++ b/apps/whatsapp/tests/messageSplitter.test.ts @@ -0,0 +1,133 @@ +/** + * Splitting an answer longer than WhatsApp's 4000-character limit. + * + * Python tests ported: `test_message_splitter.py`, with the same inputs and assertions. Added: a table of inputs that + * both languages split, checked against what Python produced (chunk count, each chunk's length in code points, and a + * hash of the text), because the Python tests only check properties, not exact cuts. + */ +import { createHash } from 'node:crypto'; +import { describe, expect, it } from 'vitest'; +import { splitMessage, WHATSAPP_MAX_MESSAGE_LENGTH } from '../src/formatting/messageSplitter'; +import { SPLITTER_CASES } from './fixtures/pythonOracle'; + +const LIMIT = WHATSAPP_MAX_MESSAGE_LENGTH; +const codePoints = (text: string) => [...text].length; + +function paragraphs(count: number, size = 500): string { + return Array.from({ length: count }, (_, i) => `${String(i).padStart(3, '0')} ${'w'.repeat(size - 4)}`).join('\n\n'); +} + +describe('ported from test_message_splitter.py', () => { + it('does not split a short message', () => { + expect(splitMessage('hello')).toEqual(['hello']); + }); + + it('does not split a message of exactly the limit', () => { + expect(splitMessage('a'.repeat(LIMIT))).toEqual(['a'.repeat(LIMIT)]); + }); + + it('splits a long message into chunks within the limit, in order', () => { + const chunks = splitMessage(paragraphs(30)); + expect(chunks.length).toBeGreaterThan(1); + expect(chunks.every((chunk) => codePoints(chunk) <= LIMIT)).toBe(true); + const order = chunks.flatMap((chunk) => chunk.match(/^\d{3}/gm) ?? []); + expect(order).toEqual(Array.from({ length: 30 }, (_, i) => String(i).padStart(3, '0'))); + }); + + it('loses no text when splitting by paragraphs', () => { + const text = paragraphs(30); + expect(splitMessage(text).join('\n\n')).toBe(text); + }); + + it('cuts one giant unbroken message into limit-sized pieces, in order', () => { + const text = Array.from({ length: LIMIT * 2 + 123 }, (_, i) => String.fromCharCode(97 + (i % 26))).join(''); + const chunks = splitMessage(text); + expect(chunks.every((chunk) => codePoints(chunk) <= LIMIT)).toBe(true); + expect(chunks.join('')).toBe(text); + }); + + it('starts a new chunk at each header', () => { + const section = `*_Title_*\n${'x'.repeat(2500)}`; + const chunks = splitMessage([section, section, section].join('\n\n')); + expect(chunks).toHaveLength(3); + expect(chunks.every((chunk) => chunk.startsWith('*_Title_*'))).toBe(true); + }); + + it('does not cut a long bold phrase in half', () => { + const bold = `*${'b'.repeat(100)}*`; + const chunks = splitMessage([`${bold} ${'a'.repeat(3500)}`, `${bold} ${'c'.repeat(3500)}`].join('\n\n')); + expect(chunks.every((chunk) => (chunk.match(/\*/g) ?? []).length % 2 === 0)).toBe(true); + }); + + it('does not cut a URL in half', () => { + const url = `https://example.org/${'u'.repeat(200)}`; + const chunks = splitMessage(`${'a'.repeat(LIMIT - 50)} ${url} ${'z'.repeat(500)}`); + expect(chunks.some((chunk) => chunk.includes(url))).toBe(true); + }); +}); + +/** The same inputs `generate_python_oracle.py` gave Python. Keep the two lists in step. */ +const url = `https://example.org/${'u'.repeat(200)}`; +const bold = `*${'b'.repeat(100)}*`; +const section = `*_Title_*\n${'x'.repeat(2500)}`; +const INPUTS: Record = { + short: 'hello', + exactly_the_limit: 'a'.repeat(LIMIT), + one_over_the_limit_without_spaces: 'a'.repeat(LIMIT + 1), + thirty_paragraphs: paragraphs(30), + giant_unbroken: Array.from({ length: LIMIT * 2 + 123 }, (_, i) => String.fromCharCode(97 + (i % 26))).join(''), + three_header_sections: [section, section, section].join('\n\n'), + long_prefix_then_headers: `${Array(4).fill('q'.repeat(1500)).join('\n\n')}\n\n*_H1_*\n${'x'.repeat(100)}\n\n*_H2_*\n${'y'.repeat(100)}`, + header_section_too_long: `*_A_*\n${'z'.repeat(4500)}\n\n*_B_*\n${'z'.repeat(100)}`, + bold_sections: Array.from({ length: 4 }, (_, i) => `*Item ${i}* ${'word '.repeat(700)}`).join('\n\n'), + long_bold_phrase: [`${bold} ${'a'.repeat(3500)}`, `${bold} ${'c'.repeat(3500)}`].join('\n\n'), + url_at_the_boundary: `${'a'.repeat(LIMIT - 50)} ${url} ${'z'.repeat(500)}`, + words_without_paragraphs: 'lorem ipsum dolor '.repeat(600), + lines_without_blank_lines: 'line of text\n'.repeat(400), + emoji_only_over_the_limit: '\u{1F600}'.repeat(LIMIT + 1), + emoji_at_the_boundary: `${'a'.repeat(LIMIT - 1)}${'\u{1F600}'.repeat(3)}`, + emoji_and_spaces: '\u{1F600} '.repeat(3000), + emoji_paragraphs: Array(3).fill('\u{1F600}'.repeat(1500)).join('\n\n'), + arabic_words: '\u0643\u0644\u0645\u0629 '.repeat(2000), + one_paragraph_too_long_in_the_middle: `short\n\n${'x'.repeat(4500)}\n\nshort two`, + several_blank_lines: `${'a'.repeat(2000)}\n\n\n\n${'b'.repeat(2500)}`, + only_newlines: '\n'.repeat(5000), + only_spaces: ' '.repeat(4001), +}; + +describe('splits exactly where Python splits', () => { + it('covers every input the Python side was given', () => { + expect(Object.keys(INPUTS).sort()).toEqual(Object.keys(SPLITTER_CASES).sort()); + }); + + it.each(Object.entries(SPLITTER_CASES))('%s', (name, expected) => { + const chunks = splitMessage(INPUTS[name]!); + expect(chunks.map(codePoints)).toEqual(expected.lengths); + expect(chunks).toHaveLength(expected.count); + expect(createHash('sha256').update(chunks.join('\u0000'), 'utf8').digest('hex')).toBe(expected.sha256); + }); +}); + +describe('emoji', () => { + // A JavaScript string is 16-bit units; an emoji outside the basic plane is two of them (a surrogate pair). + // Cutting between the two leaves a broken character that WhatsApp would show as a replacement mark. + const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + for (const name of ['emoji_only_over_the_limit', 'emoji_at_the_boundary', 'emoji_and_spaces']) { + for (const chunk of splitMessage(INPUTS[name]!)) expect(LONE_SURROGATE.test(chunk)).toBe(false); + } + }); + + // Counting by `.length` would call each paragraph 3000 long and send three messages, not two + it('packs emoji paragraphs by code points, so two 1500-emoji paragraphs share a message', () => { + const chunks = splitMessage(INPUTS.emoji_paragraphs!); + expect(chunks.map(codePoints)).toEqual([3002, 1500]); + }); + + it('counts an emoji as one character, so 4000 emoji fit in one message', () => { + const text = '\u{1F600}'.repeat(LIMIT); + expect(text.length).toBe(LIMIT * 2); + expect(splitMessage(text)).toEqual([text]); + }); +}); diff --git a/apps/whatsapp/tests/parseWebhook.test.ts b/apps/whatsapp/tests/parseWebhook.test.ts new file mode 100644 index 00000000..931dbefa --- /dev/null +++ b/apps/whatsapp/tests/parseWebhook.test.ts @@ -0,0 +1,151 @@ +/** + * Reading Meta's webhook body. + * + * Python tests ported: the webhook cases in `test_whatsapp_service.py` (phone-hidden user, missing `from` and + * `from_user_id`) and `test_meta_sender_logging.py` (no phone number or BSUID in log text). Those tests drove the whole + * FastAPI app; here the parser is tested on its own, against what Python's `parse_meta_payload` returned for a table of + * bodies (`tests/fixtures/pythonOracle.ts`). The HTTP responses built from these results are tested with the app. + */ +import { describe, expect, it } from 'vitest'; +import { Secret } from '../src/config'; +import { InvalidMetaPayloadError, UnexpectedMetaPayloadError } from '../src/errors'; +import { parseMetaPayload, type WebhookConfig } from '../src/webhook/parseWebhook'; +import { PARSER_CASES } from './fixtures/pythonOracle'; + +function config(replyByPhone: boolean): WebhookConfig { + return { META_BUSINESS_PHONE_NUMBER_ID: new Secret('123456789'), META_REPLY_BY_PHONE: replyByPhone }; +} + +/** Run the parser and describe the outcome in the same words the fixture uses for Python's. */ +function outcome(body: unknown, replyByPhone: boolean): Record { + try { + return { ...parseMetaPayload(body, config(replyByPhone)) }; + } catch (error) { + if (error instanceof UnexpectedMetaPayloadError) { + return { error: 'unexpected_payload', replyTo: error.replyTo ?? null, message: error.message }; + } + if (error instanceof InvalidMetaPayloadError) return { error: 'invalid_payload' }; + throw error; + } +} + +describe('parseMetaPayload agrees with Python', () => { + it.each(PARSER_CASES)('$name', ({ payload, replyByPhone, expected }) => { + const actual = outcome(payload, replyByPhone); + // Python also reports the class of exception it raised (Exception, IndexError, ValueError); that has no meaning here + const wanted = Object.fromEntries(Object.entries(expected).filter(([key]) => key !== 'pythonClass')); + expect(actual).toEqual(wanted); + }); +}); + +const BSUID = 'US.13491208655302741918'; +const PHONE = '201234567899'; +const meta = { phone_number_id: '123456789', display_phone_number: '+1234567890' }; +const wrap = (value: unknown) => ({ object: 'whatsapp_business_account', entry: [{ changes: [{ value }] }] }); + +describe('identity', () => { + it('uses the BSUID only, and never reads the phone number unless replies go to the phone', () => { + const body = wrap({ + metadata: meta, + messages: [{ from: PHONE, from_user_id: BSUID, id: 'wamid.X', timestamp: '1', type: 'text', text: { body: 'hi' } }], + }); + const off = parseMetaPayload(body, config(false)); + const on = parseMetaPayload(body, config(true)); + expect(off).toMatchObject({ kind: 'message', bsuid: BSUID, senderPhone: null }); + expect(on).toMatchObject({ kind: 'message', bsuid: BSUID, senderPhone: PHONE }); + }); + + it('answers a phone-hidden user (no `from`) like any other', () => { + const body = wrap({ + metadata: meta, + contacts: [{ profile: { name: 'Test User', username: 'testuser' }, user_id: BSUID }], + messages: [{ from_user_id: BSUID, id: 'wamid.X', timestamp: '1', type: 'text', text: { body: 'Assalamu alaikum' } }], + }); + expect(parseMetaPayload(body, config(true))).toMatchObject({ kind: 'message', bsuid: BSUID, senderPhone: null }); + }); + + it('reports a message with neither `from` nor `from_user_id` as an unexpected format', () => { + const body = wrap({ + metadata: meta, + contacts: [], + messages: [{ id: 'wamid.X', timestamp: '1', type: 'text', text: { body: 'hi' } }], + }); + expect(() => parseMetaPayload(body, config(false))).toThrow(UnexpectedMetaPayloadError); + }); + + // Python passed any value along and failed later; refusing early keeps a non-text id out of the rest of the service. + it.each([42, null, '', ['US.1'], { id: 'US.1' }])('refuses a from_user_id that is %j', (bad) => { + const body = wrap({ + metadata: meta, + messages: [{ from_user_id: bad, id: 'wamid.X', timestamp: '1', type: 'text', text: { body: 'hi' } }], + }); + expect(() => parseMetaPayload(body, config(false))).toThrow(UnexpectedMetaPayloadError); + }); +}); + +describe('what reaches the logs and error messages', () => { + function logged(body: unknown): string { + const lines: string[] = []; + const logger = { info: (m: string) => lines.push(m), error: (m: string) => lines.push(m) }; + try { + parseMetaPayload(body, config(true), logger); + } catch (error) { + lines.push((error as Error).message); + } + return lines.join('\n'); + } + + const noType = wrap({ + metadata: meta, + contacts: [{ profile: { name: 'Secret Name' }, user_id: BSUID }], + messages: [{ from: PHONE, from_user_id: BSUID, id: 'wamid.HBgLMTY1MDM4', timestamp: '1', text: { body: 'private words' } }], + }); + + it('never contains a phone number, BSUID, message id, name or message text', () => { + const text = logged(noType); + for (const secret of [PHONE, BSUID, 'wamid.HBgLMTY1MDM4', 'Secret Name', 'private words']) { + expect(text).not.toContain(secret); + } + expect(text).toContain(' { + const text = logged(noType); + expect(text).toContain('"timestamp":"1"'); + expect(text).toContain("Missing key 'type'"); + }); + + it('masks an invalid body too', () => { + const text = logged({ object: 'whatsapp_business_account', entry: [{ changes: [{ value: { note: `call ${PHONE}` } }] }] }); + expect(text).not.toContain(PHONE); + expect(text).toContain('Missing metadata'); + }); + + it('logs the type of an accepted message and nothing else about it', () => { + const lines: string[] = []; + parseMetaPayload( + wrap({ metadata: meta, messages: [{ from_user_id: BSUID, id: 'wamid.X', timestamp: '1', type: 'text', text: { body: 'hi' } }] }), + config(false), + { info: (m) => lines.push(m), error: (m) => lines.push(m) }, + ); + expect(lines).toEqual(['Received a supported whatsapp message (type: text)']); + }); +}); + +describe('who can be told when a message is malformed', () => { + it('prefers the id in the message, then the contact, then nobody', () => { + const message = { id: 'wamid.X', timestamp: '1', text: { body: 'hi' } }; + const contacts = [{ user_id: 'US.FROM.CONTACT' }]; + const replyTo = (value: unknown) => { + try { + parseMetaPayload(wrap(value), config(false)); + } catch (error) { + return (error as UnexpectedMetaPayloadError).replyTo; + } + return 'no error'; + }; + expect(replyTo({ metadata: meta, messages: [{ ...message, from_user_id: BSUID }], contacts })).toBe(BSUID); + expect(replyTo({ metadata: meta, messages: [message], contacts })).toBe('US.FROM.CONTACT'); + expect(replyTo({ metadata: meta, messages: [message] })).toBeUndefined(); + }); +}); diff --git a/apps/whatsapp/tests/time.test.ts b/apps/whatsapp/tests/time.test.ts new file mode 100644 index 00000000..981a9b41 --- /dev/null +++ b/apps/whatsapp/tests/time.test.ts @@ -0,0 +1,93 @@ +/** + * Elapsed-time text, conversation expiry and the stale-message check. Python tests only touch + * `get_retention_time_seconds`; everything else is compared with what Python returned on a frozen clock + * (`tests/fixtures/pythonOracle.ts`). + */ +import { describe, expect, it } from 'vitest'; +import { calculateTimePassed, formatTimeDelta, getRetentionTimeSeconds, isMessageTooOld } from '../src/utils/time'; +import { + FIXED_NOW_UNIX, + MESSAGE_AGE_CASES, + TIME_DELTA_CASES, + TIME_PASSED_CASES, +} from './fixtures/pythonOracle'; + +const NOW = new Date(FIXED_NOW_UNIX * 1000); +const THRESHOLD = 86400; + +describe('formatTimeDelta', () => { + it.each(TIME_DELTA_CASES)('%s seconds -> %s', (seconds, expected) => { + expect(formatTimeDelta(seconds)).toBe(expected); + }); + + // JavaScript's toFixed(1) rounds an exact tie up; Python's format rounds it to the even digit. 0.25 is exact in binary. + it('rounds ties to even like Python, not up like toFixed', () => { + expect((0.25).toFixed(1)).toBe('0.3'); + expect(formatTimeDelta(0.25)).toBe('0.2 seconds'); + expect(formatTimeDelta(0.75)).toBe('0.8 seconds'); + }); +}); + +describe('calculateTimePassed', () => { + it.each(TIME_PASSED_CASES)('%s seconds ago -> %s, %s', (secondsAgo, passed, logging) => { + const last = secondsAgo === null ? null : new Date(NOW.getTime() - secondsAgo * 1000); + const result = calculateTimePassed(last, NOW); + expect(result.seconds).toBe(passed === 'inf' ? Infinity : passed); + expect(result.forLogging).toBe(logging); + }); + + it('reads the real clock when none is given', () => { + const result = calculateTimePassed(new Date(Date.now() - 5000)); + expect(result.seconds).toBeGreaterThanOrEqual(5); + expect(result.seconds).toBeLessThan(10); + }); +}); + +describe('getRetentionTimeSeconds', () => { + it('turns hours into seconds', () => { + expect(getRetentionTimeSeconds(3)).toBe(10800); + }); +}); + +describe('isMessageTooOld', () => { + it.each(MESSAGE_AGE_CASES)('%s seconds old (unix %s) -> too old: %s', (_secondsAgo, unixTime, tooOld) => { + expect(isMessageTooOld(unixTime, THRESHOLD, { now: NOW })).toBe(tooOld); + }); + + it('treats exactly the threshold as not too old, and one second more as too old', () => { + expect(isMessageTooOld(FIXED_NOW_UNIX - THRESHOLD, THRESHOLD, { now: NOW })).toBe(false); + expect(isMessageTooOld(FIXED_NOW_UNIX - THRESHOLD - 1, THRESHOLD, { now: NOW })).toBe(true); + }); + + it('uses the threshold it is given', () => { + expect(isMessageTooOld(FIXED_NOW_UNIX - 100, 50, { now: NOW })).toBe(true); + expect(isMessageTooOld(FIXED_NOW_UNIX - 100, 500, { now: NOW })).toBe(false); + }); + + // `if not message_unix_time` in Python is also true for 0 + it.each([null, undefined, 0])('cannot judge a missing timestamp (%s), so the message is answered', (value) => { + expect(isMessageTooOld(value, THRESHOLD, { now: NOW })).toBe(false); + }); + + // Not from the oracle: CPython raises ValueError for these on Railway's Linux (caught: "not too old") but OSError on + // Windows (not caught), so this machine cannot produce Python's answer. The TypeScript follows Linux. + it.each([Number.NaN, Infinity, -Infinity, 253402300800, -62135596801])( + 'cannot judge an unusable timestamp (%s), so the message is answered', + (value) => { + expect(isMessageTooOld(value, THRESHOLD, { now: NOW })).toBe(false); + }, + ); + + it('logs why a timestamp was not judged', () => { + const lines: string[] = []; + const logger = { debug: (m: string) => lines.push(`debug: ${m}`), error: (m: string) => lines.push(`error: ${m}`) }; + isMessageTooOld(null, THRESHOLD, { now: NOW, logger }); + isMessageTooOld(Number.NaN, THRESHOLD, { now: NOW, logger }); + isMessageTooOld(FIXED_NOW_UNIX - 90, THRESHOLD, { now: NOW, logger }); + expect(lines).toEqual([ + 'debug: No timestamp available, cannot determine message age', + 'error: Error parsing message timestamp: NaN is not a usable unix time', + 'debug: Message age: 1.5 minutes', + ]); + }); +}); diff --git a/codev/projects/358-whatsapp-typescript/358-phase_2-iter1-claude.txt b/codev/projects/358-whatsapp-typescript/358-phase_2-iter1-claude.txt new file mode 100644 index 00000000..872c9771 --- /dev/null +++ b/codev/projects/358-whatsapp-typescript/358-phase_2-iter1-claude.txt @@ -0,0 +1,60 @@ +AGENT SELF-REVIEW, NOT A CONSULT RUN. Written by the implementing agent (GitHub Copilot) because Codex and +Gemini are not installed here and the Claude consult hung. The owner reviews after this. Findings below were +checked by running code, not by reading alone. + +Scope: plan phase_2 (pure logic): language.ts, time.ts, whatsappMessageFormatter.ts, messageSplitter.ts, +parseWebhook.ts, InvalidMetaPayloadError, and their tests. + +Method: the Python suite barely covers the formatter, the time helpers and the parser, so the legacy Python code +was run (main checkout's virtualenv, this worktree's source, verified by printing the module path) on a table of +inputs, and its answers were written to tests/fixtures/pythonOracle.ts by tests/fixtures/generate_python_oracle.py. +The TypeScript tests compare against that file, so "same as Python" is checked, not assumed. 197 oracle cases +(51 formatter, 27 parser, 22 splitter, 21+16+7 time, 16 direction, 11+7+10+9 formatter steps). + +Verified (ran it): +- typecheck, lint and 332 vitest tests pass (84 from phase 1). +- 13 rules were broken on purpose, one at a time, and a test failed each time; files restored byte-for-byte: + direction counted in UTF-16 units, direction threshold, tie rounding, message exactly at the threshold, NaN + timestamp, bold-before-italic, ASCII-only digits, first-marker-only rewrite, splitter without space preference, + splitter counting UTF-16 units, phone number read when replies by phone are off, inherited object keys read as + message keys, raw payload logged instead of the masked one. +- A mutation that slipped through the first time (splitter counting UTF-16 units) exposed a missing case; an + emoji-paragraph input was added and the mutation is now caught. +- Hostile input timing (20k to 1M characters): no catastrophic regex backtracking in the formatter or the splitter. + Not fixed: 20,000 header-like lines without a closing newline ("# x" repeated) take 1.4 s in the formatter, which + is quadratic. Python uses the same pattern; a real answer is far smaller. Recorded, not changed. + +Found and fixed while porting (JavaScript differs from Python): +- toFixed(1) rounds ties up, Python's format rounds to even (0.25 -> "0.2"): own formatter, tested on ties. +- String .length counts UTF-16 units, Python's len() counts code points: emoji skewed the direction share and the + splitter's limit and could be cut in half. Counting and cutting use code points now. +- Python's \d matches Arabic-Indic digits, JavaScript's does not: \p{Nd} with the u flag. +- Python's . matches \r, JavaScript's does not: [^\n] in the header patterns (CRLF input matched against Python). +- `x in obj` finds inherited names ("constructor"): Object.hasOwn. +- `!timestamp` is true for NaN in JavaScript but not in Python: explicit null/undefined/0 check. +- Python's re.sub rewrites every list marker on a line; a JavaScript regex without the g flag rewrites one. +- A splitter performance bug of my own: recounting the growing chunk per paragraph took 2.2 s on 130k paragraphs. + A running total makes it 67 ms with identical output. + +Behaviour kept from Python on purpose (looks like a bug, is not changed here; each is pinned by a test): +- "2 * 3 and 4 * 5" becomes "2 _ 3 and 4 _ 5"; "***x***" becomes "**x**"; a "* a / * b" bullet list loses its bullets. +- A CRLF header gets the \r inside the bold-italic markers. +- An answer made only of newlines splits into NO chunks (callers must not rely on at least one). + +Differences from Python, deliberate: +- Empty text: Python raises ZeroDivisionError in the direction check (and so in format_for_whatsapp); the port answers + "ltr" / the empty text. Unreachable (callers check first). +- A from_user_id that is not a non-empty string is refused up front; Python passed any value along and failed later. +- Timestamps outside years 1-9999 are "not too old". CPython raises ValueError on Linux (caught) but OSError on + Windows (not caught), so this machine cannot produce Railway's answer; the port follows Linux. Not in the oracle. +- The parser returns a tagged union instead of an 8-tuple and is synchronous; the clock and settings are arguments. +- get_language_from_text (an unused placeholder returning "en") and the dead in_nested_section state in + format_nested_lists are not ported. + +Not verified: +- Python's int() accepts forms like "1_000" and non-ASCII digits in a timestamp; the port accepts ASCII digits only. + Meta sends plain digits. +- The signature check, the response builder and the Meta sender are the next phases. +- Cold-cache root build and the Docker image are plan phase_6. + +VERDICT: COMMENT From 7514e184f44e01b7c61f563292a6273efb3243d7 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 20:31:57 +0200 Subject: [PATCH 024/435] chore(porch): 358 implement build-complete --- codev/projects/358-whatsapp-typescript/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 23f3e8e3..8f632e37 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T17:48:30.126Z' +updated_at: '2026-11-10T18:31:56.861Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' From 06bd5267cdb9f2d96fbafbc83ca08bab55cd0b88 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 20:32:16 +0200 Subject: [PATCH 025/435] =?UTF-8?q?chore(porch):=20358=20advance=20plan=20?= =?UTF-8?q?phase=20=E2=86=92=20phase=5F3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codev/projects/358-whatsapp-typescript/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 8f632e37..ccb2e11c 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -8,10 +8,10 @@ plan_phases: status: complete - id: phase_2 title: 'Pure logic: formatter, splitter, webhook parser, language and time helpers' - status: in_progress + status: complete - id: phase_3 title: 'Service clients: apps/auth exchange, apps/api streaming, Meta API' - status: pending + status: in_progress - id: phase_4 title: Conversation manager status: pending @@ -24,7 +24,7 @@ plan_phases: - id: phase_7 title: Staging redeploy, smoke test and legacy rollback note status: pending -current_plan_phase: phase_2 +current_plan_phase: phase_3 gates: spec-approval: status: approved @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T18:31:56.861Z' +updated_at: '2026-11-10T18:32:16.131Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -51,3 +51,5 @@ context_refreshes: - boundary: plan-phase:phase_2 at: '2026-11-10T17:47:59.160Z' acknowledged_at: '2026-11-10T17:48:30.123Z' + - boundary: plan-phase:phase_3 + at: '2026-11-10T18:32:16.131Z' From dc1128930d6c4cbd1ab8075b7d36ee5bcadb2f4c Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 21:36:31 +0200 Subject: [PATCH 026/435] [Spec 358][Phase: phase_2] fix: lone stars, triple-star bold italic and whitespace-only replies --- .../src/formatting/messageSplitter.ts | 9 ++ .../formatting/whatsappMessageFormatter.ts | 37 +++++++-- .../tests/fixtures/generate_python_oracle.py | 6 ++ apps/whatsapp/tests/fixtures/pythonOracle.ts | 24 ++++++ apps/whatsapp/tests/formatter.test.ts | 82 ++++++++++++++++--- apps/whatsapp/tests/messageSplitter.test.ts | 35 +++++++- codev/plans/358-whatsapp-typescript.md | 5 ++ .../358-phase_2-iter1-claude.txt | 21 +++-- 8 files changed, 191 insertions(+), 28 deletions(-) diff --git a/apps/whatsapp/src/formatting/messageSplitter.ts b/apps/whatsapp/src/formatting/messageSplitter.ts index 88ffd39a..f1ed4b1d 100644 --- a/apps/whatsapp/src/formatting/messageSplitter.ts +++ b/apps/whatsapp/src/formatting/messageSplitter.ts @@ -23,8 +23,17 @@ function length(text: string): number { * 3. at paragraphs, falling back to fixed-size pieces cut at a space. * * A message within the limit comes back unchanged, as a list of one. + * + * Text with nothing but whitespace gives an empty list, and a whitespace-only piece is dropped from a longer message: + * WhatsApp refuses to send them. Python returned zero pieces for an answer of only newlines, and pieces of only spaces + * for an answer of only spaces, so the user got silence or an error (owner decision, 2026-11-10). The caller must treat + * an empty list as "nothing to send" and tell the user, not stay quiet. */ export function splitMessage(msgBody: string): string[] { + return splitMessageUnchecked(msgBody).filter((chunk) => chunk.trim() !== ''); +} + +function splitMessageUnchecked(msgBody: string): string[] { if (length(msgBody) <= WHATSAPP_MAX_MESSAGE_LENGTH) return [msgBody]; const headerChunks = splitByHeaders(msgBody, WHATSAPP_MAX_MESSAGE_LENGTH); diff --git a/apps/whatsapp/src/formatting/whatsappMessageFormatter.ts b/apps/whatsapp/src/formatting/whatsappMessageFormatter.ts index 57d13d35..87844339 100644 --- a/apps/whatsapp/src/formatting/whatsappMessageFormatter.ts +++ b/apps/whatsapp/src/formatting/whatsappMessageFormatter.ts @@ -13,23 +13,26 @@ * U+0669, included); JavaScript's only matches 0-9. Arabic answers can number their lists with Arabic-Indic digits. * - Replacement text says `$1` where Python says `\1`. * - * Known oddities, kept on purpose because the job here is to port behaviour, not to redesign it: - * - Any pair of lone `*` becomes italics, even in arithmetic: "2 * 3 and 4 * 5" turns into "2 _ 3 and 4 _ 5". - * - `***both***` becomes `**both**`: the italic step consumes nothing, then bold turns `**` into `*`, leaving two stars. - * - The italic step can pair a `*` across lines, so a `* item` bullet list loses its bullets (`_ item`). + * Three Python bugs are fixed here on purpose (owner decision, 2026-11-10), so the output differs from Python for them: + * - A lone `*` next to a space is no longer an italic marker. Python turned "2 * 3 and 4 * 5" into "2 _ 3 and 4 _ 5" and a + * `* item` bullet list into `_ item` lines. An italic marker must now touch the text it wraps, as in markdown. + * - `***both***` becomes `*_both_*` (bold and italic). Python left a stray `**both**`. + * - (In the splitter) an answer with nothing but whitespace is no longer "sent" as zero messages; see messageSplitter.ts. + * `tests/formatter.test.ts` lists each changed input beside the output Python gave. */ import { getLanguageDirectionFromText } from '../utils/language'; /** * Convert conventional markdown to WhatsApp's markdown. * - * Order matters: italic (`*x*` -> `_x_`) must run before bold (`**x**` -> `*x*`), or the new single stars would be - * read as italics. + * Order matters: bold-italic (`***x***`) goes first, then italic (`*x*` -> `_x_`), then bold (`**x**` -> `*x*`). + * Bold must come after italic, or the single stars it produces would be read as italics. */ export function formatForWhatsApp(msg: string): string { const direction = getLanguageDirectionFromText(msg); - let result = convertItalicSyntax(msg); + let result = convertBoldItalicSyntax(msg); + result = convertItalicSyntax(result); result = convertBoldSyntax(result); result = convertHeaders(result); @@ -41,14 +44,32 @@ export function formatForWhatsApp(msg: string): string { return result; } +/** + * `\*\*\*` three stars + * `(?=\S)` the text must start right after them (so a `***` line on its own is left alone) + * `([^*]+?)` the shortest run of characters that are not `*`, captured + * `(?<=\S)` and end right before the closing stars + * `\*\*\*` three stars + */ +const BOLD_ITALIC = /\*\*\*(?=\S)([^*]+?)(?<=\S)\*\*\*/g; + +/** Convert markdown bold-italic (`***text***`) to WhatsApp's `*_text_*`. Python left `**text**`. */ +export function convertBoldItalicSyntax(text: string): string { + return text.replace(BOLD_ITALIC, '*_$1_*'); +} + /** * `(? what the port returns now. Python's answer for each is + * still in the oracle, and the tests below check that it really is different. + */ +const FIXED: Record = { + // A lone * next to a space is not an italic marker (Python: "a _ b _ c") + 'a * b * c': 'a * b * c', + '2 * 3 = 6 and 4 * 5 = 20': '2 * 3 = 6 and 4 * 5 = 20', + // A * bullet list keeps its bullets (Python: "_ a\n_ b"), and nested * bullets are reformatted like - bullets + '* a\n* b': '* a\n* b', + '* a\n * b\n * c': '* a\n -- b\n -- c', + '- a\n * b\n * c': '- a\n -- b\n -- c', + '* a\n* b\n* c': '* a\n* b\n* c', + '1 * 2 * 3 and *real*': '1 * 2 * 3 and _real_', + // *** is bold and italic (Python: "**both**") + '***both***': '*_both_*', + '***bold italic***': '*_bold italic_*', + '***a*** and **b** and *c*': '*_a_* and *b* and _c_', +}; + +/** The same idea for the italic step on its own. */ +const FIXED_ITALIC: Record = { + '* a *': '* a *', + '*a\n*': '*a\n*', +}; + describe('formatForWhatsApp (whole pipeline)', () => { - it.each(FORMATTER_CASES)('%j', (input, expected) => { + it.each(FORMATTER_CASES.filter(([input]) => !(input in FIXED)))('%j (same as Python)', (input, expected) => { + expect(formatForWhatsApp(input)).toBe(expected); + }); + + it.each(Object.entries(FIXED))('%j (fixed, differs from Python)', (input, expected) => { + const python = FORMATTER_CASES.find(([candidate]) => candidate === input)?.[1]; + expect(python).toBeDefined(); + expect(python).not.toBe(expected); expect(formatForWhatsApp(input)).toBe(expected); }); @@ -41,7 +75,12 @@ describe('formatForWhatsApp (whole pipeline)', () => { }); describe('the steps on their own', () => { - it.each(ITALIC_CASES)('italic %j', (input, expected) => { + it.each(ITALIC_CASES.filter(([input]) => !(input in FIXED_ITALIC)))('italic %j (same as Python)', (input, expected) => { + expect(convertItalicSyntax(input)).toBe(expected); + }); + it.each(Object.entries(FIXED_ITALIC))('italic %j (fixed, differs from Python)', (input, expected) => { + const python = ITALIC_CASES.find(([candidate]) => candidate === input)?.[1]; + expect(python).not.toBe(expected); expect(convertItalicSyntax(input)).toBe(expected); }); it.each(BOLD_CASES)('bold %j', (input, expected) => { @@ -55,20 +94,37 @@ describe('the steps on their own', () => { }); }); -// These behaviours look like bugs. They are Python's, and the port keeps them until the owner decides otherwise. -describe('behaviour kept from Python on purpose', () => { - it('turns arithmetic stars into italics', () => { - expect(formatForWhatsApp('2 * 3 = 6 and 4 * 5 = 20')).toBe('2 _ 3 = 6 and 4 _ 5 = 20'); +describe('the italic and bold fixes do not break real markdown', () => { + it('still italicises text that a star touches', () => { + expect(formatForWhatsApp('a *b c* d')).toBe('a _b c_ d'); + }); + + it('leaves lone stars alone while italicising a real pair on the same line', () => { + expect(formatForWhatsApp('1 * 2 * 3 and *real*')).toBe('1 * 2 * 3 and _real_'); + }); + + it('handles bold-italic, bold and italic together', () => { + expect(formatForWhatsApp('***a*** and **b** and *c*')).toBe('*_a_* and *b* and _c_'); }); - it('turns *** into ** (a stray double star)', () => { - expect(formatForWhatsApp('***both***')).toBe('**both**'); + it('keeps italic inside bold', () => { + expect(formatForWhatsApp('**bold with *italic* inside**')).toBe('*bold with _italic_ inside*'); }); - it('loses the bullets of a * list', () => { - expect(formatForWhatsApp('* a\n* b')).toBe('_ a\n_ b'); + it('does not italicise across a line break, so two bullet lines never pair up', () => { + expect(formatForWhatsApp('* a\n* b\n* c')).toBe('* a\n* b\n* c'); }); + // A line of three stars is a markdown rule, not bold-italic. Both Python and the port turn it into two stars (the bold + // step); the point of this test is that the new bold-italic step does not pair the two lines up. + it('does not treat a line of stars as bold-italic', () => { + expect(formatForWhatsApp('***\ntext\n***')).toBe('**\ntext\n**'); + expect(FORMATTER_CASES.find(([input]) => input === '***\ntext\n***')?.[1]).toBe('**\ntext\n**'); + }); +}); + +// Python's behaviour, kept: it looks odd but nothing here is a bug the owner asked to fix. +describe('behaviour kept from Python on purpose', () => { it('puts a carriage return inside the header when the line ends in \\r\\n', () => { expect(formatForWhatsApp('## Header\r\n\r\nbody')).toBe('*_Header\r_*\n\n\r\nbody'); }); diff --git a/apps/whatsapp/tests/messageSplitter.test.ts b/apps/whatsapp/tests/messageSplitter.test.ts index 922e0834..39503237 100644 --- a/apps/whatsapp/tests/messageSplitter.test.ts +++ b/apps/whatsapp/tests/messageSplitter.test.ts @@ -95,12 +95,15 @@ const INPUTS: Record = { only_spaces: ' '.repeat(4001), }; +/** Inputs where the port differs from Python on purpose: a text that is only whitespace has nothing to send. */ +const FIXED = new Set(['only_spaces']); + describe('splits exactly where Python splits', () => { it('covers every input the Python side was given', () => { expect(Object.keys(INPUTS).sort()).toEqual(Object.keys(SPLITTER_CASES).sort()); }); - it.each(Object.entries(SPLITTER_CASES))('%s', (name, expected) => { + it.each(Object.entries(SPLITTER_CASES).filter(([name]) => !FIXED.has(name)))('%s', (name, expected) => { const chunks = splitMessage(INPUTS[name]!); expect(chunks.map(codePoints)).toEqual(expected.lengths); expect(chunks).toHaveLength(expected.count); @@ -108,6 +111,36 @@ describe('splits exactly where Python splits', () => { }); }); +describe('text with nothing to send (fixed, differs from Python)', () => { + it('gives no messages for an empty answer', () => { + expect(splitMessage('')).toEqual([]); + }); + + // Python: an answer of only newlines gave no messages (matched here), and only spaces gave pieces of spaces, + // which WhatsApp rejects as an empty message + it.each([' ', ' ', '\n', '\n\n\n', ' \n \t \r\n', ' '.repeat(LIMIT + 1), '\n'.repeat(5000)])( + 'gives no messages for whitespace only (%j)', + (text) => { + expect(splitMessage(text)).toEqual([]); + }, + ); + + it('keeps the oracle honest: Python did send pieces of spaces', () => { + expect(SPLITTER_CASES.only_spaces!.count).toBe(2); + }); + + // The three paragraphs are too big to share a message (3000 + 3000 > 4000), so the spaces become a piece of their own + it('drops a whitespace-only piece from a longer answer but keeps the text around it', () => { + const text = `${'a'.repeat(3000)}\n\n${' '.repeat(3000)}\n\n${'b'.repeat(1500)}`; + const chunks = splitMessage(text); + expect(chunks).toEqual(['a'.repeat(3000), 'b'.repeat(1500)]); + }); + + it('does not trim or change a normal message', () => { + expect(splitMessage(' hello \n')).toEqual([' hello \n']); + }); +}); + describe('emoji', () => { // A JavaScript string is 16-bit units; an emoji outside the basic plane is two of them (a surrogate pair). // Cutting between the two leaves a broken character that WhatsApp would show as a replacement mark. diff --git a/codev/plans/358-whatsapp-typescript.md b/codev/plans/358-whatsapp-typescript.md index 8a24f8f3..3448e930 100644 --- a/codev/plans/358-whatsapp-typescript.md +++ b/codev/plans/358-whatsapp-typescript.md @@ -82,6 +82,11 @@ The Python tests (197) are the oracle: each phase ports one layer bottom-up, tog **Done when**: all mapped cases pass with identical expected strings, including the 4000-character split, RTL handling, status/wrong-number/unsupported/stale webhook classification. +**Deliberate differences from Python (owner decision, 2026-11-10)**: the Python formatter and splitter had three bugs that the port fixes instead of copying. Each is pinned by a test that shows Python's answer beside the new one. +- A lone `*` beside a space is not an italic marker: `2 * 3 and 4 * 5` stays as written (Python: `2 _ 3 and 4 _ 5`) and a `* item` list keeps its bullets (Python: `_ item`). +- `***text***` becomes `*_text_*` (Python: a stray `**text**`). +- A reply with nothing but whitespace gives an empty list from `splitMessage` (Python: no pieces for newlines, pieces of spaces for spaces, which WhatsApp rejects). **Phase 4 must treat an empty list as "nothing to send" and send the user the same "couldn't process your message" notice as for an empty answer**, not stay silent. + ### Phase 3: Service clients **Dependencies**: Phase 2 diff --git a/codev/projects/358-whatsapp-typescript/358-phase_2-iter1-claude.txt b/codev/projects/358-whatsapp-typescript/358-phase_2-iter1-claude.txt index 872c9771..b21c0ce9 100644 --- a/codev/projects/358-whatsapp-typescript/358-phase_2-iter1-claude.txt +++ b/codev/projects/358-whatsapp-typescript/358-phase_2-iter1-claude.txt @@ -8,11 +8,11 @@ parseWebhook.ts, InvalidMetaPayloadError, and their tests. Method: the Python suite barely covers the formatter, the time helpers and the parser, so the legacy Python code was run (main checkout's virtualenv, this worktree's source, verified by printing the module path) on a table of inputs, and its answers were written to tests/fixtures/pythonOracle.ts by tests/fixtures/generate_python_oracle.py. -The TypeScript tests compare against that file, so "same as Python" is checked, not assumed. 197 oracle cases -(51 formatter, 27 parser, 22 splitter, 21+16+7 time, 16 direction, 11+7+10+9 formatter steps). +The TypeScript tests compare against that file, so "same as Python" is checked, not assumed. About 205 oracle +cases (formatter, parser, splitter, time, direction, formatter steps), plus the fixed inputs listed below. Verified (ran it): -- typecheck, lint and 332 vitest tests pass (84 from phase 1). +- typecheck, lint and 351 vitest tests pass (84 from phase 1). - 13 rules were broken on purpose, one at a time, and a test failed each time; files restored byte-for-byte: direction counted in UTF-16 units, direction threshold, tie rounding, message exactly at the threshold, NaN timestamp, bold-before-italic, ASCII-only digits, first-marker-only rewrite, splitter without space preference, @@ -36,10 +36,19 @@ Found and fixed while porting (JavaScript differs from Python): - A splitter performance bug of my own: recounting the growing chunk per paragraph took 2.2 s on 130k paragraphs. A running total makes it 67 ms with identical output. -Behaviour kept from Python on purpose (looks like a bug, is not changed here; each is pinned by a test): -- "2 * 3 and 4 * 5" becomes "2 _ 3 and 4 _ 5"; "***x***" becomes "**x**"; a "* a / * b" bullet list loses its bullets. +Python bugs FIXED on the owner's instruction (2026-11-10), each pinned by a test showing Python's answer beside the new one: +- A lone * beside a space is no longer an italic marker: "2 * 3 and 4 * 5" and "* a / * b" lists stay as written + (Python: "2 _ 3 and 4 _ 5", "_ a / _ b"). A nested "* b" now becomes "-- b" like a nested "- b". +- "***x***" becomes "*_x_*" (Python: "**x**"). +- A reply of only whitespace gives an EMPTY list from splitMessage, and a whitespace-only piece is dropped from a + longer reply (Python: nothing for newlines, pieces of spaces for spaces, which WhatsApp rejects). The caller + (plan phase_4) must send the "couldn't process your message" notice for an empty list. + Verified by mutation: 6 deliberate breakages of the three fixes, each caught (two slipped through once and led + to a better test). + +Behaviour kept from Python on purpose (looks odd, not changed here; pinned by a test): - A CRLF header gets the \r inside the bold-italic markers. -- An answer made only of newlines splits into NO chunks (callers must not rely on at least one). +- A line of three stars (a markdown rule) becomes two stars, as in Python. Differences from Python, deliberate: - Empty text: Python raises ZeroDivisionError in the direction check (and so in format_for_whatsapp); the port answers From d856ce19430b0c011d1e2cba7790dfd313cc18a9 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 22:01:42 +0200 Subject: [PATCH 027/435] [Spec 358][Phase: phase_3] feat: service clients for apps/auth, Meta Graph API and apps/api --- apps/whatsapp/src/errorReporter.ts | 17 + apps/whatsapp/src/errors.ts | 41 ++ apps/whatsapp/src/services/ansariClient.ts | 362 ++++++++++++++++ apps/whatsapp/src/services/authClient.ts | 222 ++++++++++ apps/whatsapp/src/services/http.ts | 121 ++++++ apps/whatsapp/src/services/metaApiService.ts | 253 +++++++++++ apps/whatsapp/src/utils/pythonRepr.ts | 67 +++ apps/whatsapp/src/webhook/parseWebhook.ts | 6 +- apps/whatsapp/tests/ansariClient.test.ts | 398 ++++++++++++++++++ apps/whatsapp/tests/authClient.test.ts | 323 ++++++++++++++ .../tests/fixtures/generate_python_oracle.py | 39 ++ apps/whatsapp/tests/fixtures/pythonOracle.ts | 144 +++++++ apps/whatsapp/tests/helpers/network.ts | 124 ++++++ apps/whatsapp/tests/http.test.ts | 150 +++++++ apps/whatsapp/tests/metaApiService.test.ts | 357 ++++++++++++++++ apps/whatsapp/tests/pythonRepr.test.ts | 21 + .../358-phase_3-iter1-claude.txt | 28 ++ 17 files changed, 2668 insertions(+), 5 deletions(-) create mode 100644 apps/whatsapp/src/errorReporter.ts create mode 100644 apps/whatsapp/src/services/ansariClient.ts create mode 100644 apps/whatsapp/src/services/authClient.ts create mode 100644 apps/whatsapp/src/services/http.ts create mode 100644 apps/whatsapp/src/services/metaApiService.ts create mode 100644 apps/whatsapp/src/utils/pythonRepr.ts create mode 100644 apps/whatsapp/tests/ansariClient.test.ts create mode 100644 apps/whatsapp/tests/authClient.test.ts create mode 100644 apps/whatsapp/tests/helpers/network.ts create mode 100644 apps/whatsapp/tests/http.test.ts create mode 100644 apps/whatsapp/tests/metaApiService.test.ts create mode 100644 apps/whatsapp/tests/pythonRepr.test.ts create mode 100644 codev/projects/358-whatsapp-typescript/358-phase_3-iter1-claude.txt diff --git a/apps/whatsapp/src/errorReporter.ts b/apps/whatsapp/src/errorReporter.ts new file mode 100644 index 00000000..67f48f1f --- /dev/null +++ b/apps/whatsapp/src/errorReporter.ts @@ -0,0 +1,17 @@ +/** + * How the services tell an operator about a fault (Python: `sentry_sdk.set_tag` + `set_context` + `capture_exception`). + * + * The services only know this small shape. The HTTP layer (plan phase 5) passes in the function that sends it to Sentry, + * so no service imports Sentry and a test can hand in a function that just records the call. + */ +export interface ErrorReport { + /** Sentry's `error_type` tag: what kind of fault this is, e.g. `meta_api_failure`. */ + errorType: string; + /** Extra fields shown with the event. Never put a phone number, BSUID, token or message text here. */ + context?: Record; +} + +export type ErrorReporter = (error: unknown, report: ErrorReport) => void; + +/** Reports nothing. The default until a real reporter is wired in. */ +export const noopErrorReporter: ErrorReporter = () => {}; diff --git a/apps/whatsapp/src/errors.ts b/apps/whatsapp/src/errors.ts index cc8047a9..54756e91 100644 --- a/apps/whatsapp/src/errors.ts +++ b/apps/whatsapp/src/errors.ts @@ -66,3 +66,44 @@ export class AuthRateLimitedError extends AuthTokenError { export class AnsariClientError extends Error { override readonly name: string = 'AnsariClientError'; } + +/** apps/api answered 401: it refused this user's token (a session can end after the token was signed). */ +export class ApiUnauthorizedError extends AnsariClientError { + override readonly name = 'ApiUnauthorizedError'; +} + +/** Thread creation failed. */ +export class ThreadCreationError extends AnsariClientError { + override readonly name = 'ThreadCreationError'; +} + +/** Deleting an expired thread failed. */ +export class ThreadDeletionError extends AnsariClientError { + override readonly name = 'ThreadDeletionError'; +} + +/** Retrieving thread info failed. */ +export class ThreadInfoError extends AnsariClientError { + override readonly name = 'ThreadInfoError'; +} + +/** Message processing failed. */ +export class MessageProcessingError extends AnsariClientError { + override readonly name = 'MessageProcessingError'; +} + +/** + * A call to Meta's API failed. Python let httpx's `HTTPStatusError` and `RequestError` escape from the Meta service; + * callers only ever caught `Exception`, so one class carries both: `status` is Meta's HTTP status, or `undefined` for a + * network fault or timeout. + */ +export class MetaApiError extends Error { + override readonly name = 'MetaApiError'; + + readonly status: number | undefined; + + constructor(message: string, status?: number, options?: { cause?: unknown }) { + super(message, options); + this.status = status; + } +} diff --git a/apps/whatsapp/src/services/ansariClient.ts b/apps/whatsapp/src/services/ansariClient.ts new file mode 100644 index 00000000..3e82e07f --- /dev/null +++ b/apps/whatsapp/src/services/ansariClient.ts @@ -0,0 +1,362 @@ +/** + * The apps/api client: threads and the streamed chat answer. + * + * Python counterparts: `ansari_client_base.py` (the interface), `ansari_client_real.py` and `ansari_client_mock.py`. + * + * How a chat answer arrives: `POST /api/v2/threads/{id}/chat` is a Server-Sent Events stream, the same route the web app + * uses. Lines starting with `:` are keep-alives; each `data:` line is a JSON event: `text` (a piece of the answer), + * `tool_call` / `tool_result` (ignored), `error`, and a final `done`. A stream with an `error` event, or one that ends + * without `done`, is a failure, so a half answer is never passed on as complete. (HTTP status is 200 even for those, because + * the status line is sent before the answer starts.) + * + * Differences from Python: + * - `fetch` does not follow Python's rule "a timeout applies to each wait". The chat call uses an idle timer that restarts on + * every chunk (see `IdleTimeout`), which is what httpx's 60 s read timeout meant for a stream. + * - A body is read with `readLines` over a `ReadableStream`, because `fetch` hands over bytes, not lines. + */ +import { z } from 'zod'; +import { + ApiUnauthorizedError, + MessageProcessingError, + ThreadCreationError, + ThreadDeletionError, + ThreadInfoError, +} from '../errors'; +import type { Logger } from '../logger'; +import { describeNetworkError, discardBody, IdleTimeout, readLines, trimTrailingSlashes, type FetchLike } from './http'; + +/** Per-client attribution id sent to apps/api (lowercase, per packages/types attribution). */ +export const CLIENT_ID = 'askansari-whatsapp'; + +/** Ordinary calls (threads) give up after this long without an answer. */ +const REQUEST_TIMEOUT_MS = 60_000; +/** The chat stream gives up after this long without a single byte (apps/api sends `: ping` lines to stay under it). */ +const CHAT_IDLE_TIMEOUT_MS = 60_000; + +export interface ThreadInfo { + /** `null` when the user has no thread yet. */ + threadId: string | null; + /** ISO timestamp of the thread's last activity; `null` when there is no thread. */ + lastMessageTime: string | null; +} + +export interface AnsariClient { + /** + * Create a thread for the user this JWT belongs to. + * @throws {ThreadCreationError} + */ + createThread(token: string, title: string): Promise<{ threadId: string }>; + /** + * Delete a thread and, with it, all of its messages. A thread that is already gone is not an error. + * @throws {ThreadDeletionError} + */ + deleteThread(token: string, threadId: string): Promise; + /** + * The user's most recently active thread, or nulls if they have none. + * @throws {ThreadInfoError} + */ + getLastThreadInfo(token: string): Promise; + /** + * Send a message and collect the complete answer (WhatsApp cannot stream, so the whole stream is read first). + * An empty string means apps/api finished without saying anything. + * @throws {MessageProcessingError} + */ + processMessage(token: string, threadId: string, message: string): Promise; + /** Every method also throws `ApiUnauthorizedError` on a 401, which a fresh token can fix. */ +} + +export interface AnsariClientOptions { + /** apps/api's base URL, no path. */ + baseUrl: string; + logger: Logger; + fetch?: FetchLike; + /** How long the chat stream may stay silent before it is given up on. Only tests change it. */ + chatIdleTimeoutMs?: number; +} + +/** One entry of `GET /api/v2/threads`: only the fields this client reads. */ +const threadListSchema = z.array( + z.looseObject({ thread_id: z.unknown().optional(), source: z.unknown().optional(), updated_at: z.unknown().optional() }), +); + +/** Calls apps/api over HTTP, with the user's JWT as the bearer token on every request. */ +export class AnsariClientReal implements AnsariClient { + readonly #baseUrl: string; + readonly #logger: Logger; + readonly #fetch: FetchLike; + readonly #chatIdleTimeoutMs: number; + + constructor(options: AnsariClientOptions) { + this.#baseUrl = trimTrailingSlashes(options.baseUrl); + this.#logger = options.logger; + this.#fetch = options.fetch ?? fetch; + this.#chatIdleTimeoutMs = options.chatIdleTimeoutMs ?? CHAT_IDLE_TIMEOUT_MS; + } + + #headers(token: string): Record { + return { Authorization: `Bearer ${token}`, 'X-Ansari-Client': CLIENT_ID, 'Content-Type': 'application/json' }; + } + + /** apps/api refused the token itself, which a fresh token can fix; any other status is a different fault. */ + #refuseIfUnauthorized(status: number): void { + if (status === 401) { + this.#logger.warn("apps/api refused the user's token (HTTP 401)"); + throw new ApiUnauthorizedError("apps/api refused the user's token"); + } + } + + /** + * One ordinary request. A network fault becomes `onNetworkError`'s error, so each method keeps its own error class. + * A redirect is a failure here (see http.ts), reported with its status like any other. + */ + async #request( + method: string, + path: string, + token: string, + what: string, + onNetworkError: (cause: unknown) => Error, + body?: unknown, + ): Promise { + try { + return await this.#fetch(`${this.#baseUrl}${path}`, { + method, + headers: this.#headers(token), + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + redirect: 'manual', + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + } catch (error) { + this.#logger.error(`Network error ${what}: ${describeNetworkError(error)}`); + throw onNetworkError(error); + } + } + + async createThread(token: string, title: string): Promise<{ threadId: string }> { + const response = await this.#request( + 'POST', + '/api/v2/threads', + token, + 'creating thread', + (cause) => new ThreadCreationError('Network error during thread creation', { cause }), + { name: title, source: 'whatsapp' }, + ); + if (response.status === 401) await discardBody(response); + this.#refuseIfUnauthorized(response.status); + if (!response.ok) { + await discardBody(response); + this.#logger.error(`HTTP error creating thread: ${response.status}`); + throw new ThreadCreationError(`Failed to create thread: HTTP ${response.status}`); + } + try { + const body: unknown = await response.json(); + const threadId = typeof body === 'object' && body !== null ? (body as { thread_id?: unknown }).thread_id : undefined; + if (typeof threadId !== 'string' || threadId === '') throw new TypeError('no thread_id'); + return { threadId }; + } catch (error) { + this.#logger.error('apps/api returned an unexpected thread-creation response'); + throw new ThreadCreationError('Unexpected thread-creation response', { cause: error }); + } + } + + async deleteThread(token: string, threadId: string): Promise { + const response = await this.#request( + 'DELETE', + `/api/v2/threads/${encodeURIComponent(threadId)}`, + token, + 'deleting thread', + (cause) => new ThreadDeletionError('Network error during thread deletion', { cause }), + ); + await discardBody(response); + // The thread is already gone, which is the outcome we wanted + if (response.status === 404) return; + this.#refuseIfUnauthorized(response.status); + if (!response.ok) { + this.#logger.error(`HTTP error deleting thread: ${response.status}`); + throw new ThreadDeletionError(`Failed to delete thread: HTTP ${response.status}`); + } + } + + /** + * apps/api lists a user's threads newest-first by `updated_at`, which it bumps on every message. Only threads this + * service created (`source` is `whatsapp`) count, so an expired one is never mistaken for, or deleted in place of, a + * thread from another client. + */ + async getLastThreadInfo(token: string): Promise { + const response = await this.#request( + 'GET', + '/api/v2/threads', + token, + 'getting last thread info', + (cause) => new ThreadInfoError('Network error during thread info retrieval', { cause }), + ); + if (response.status === 401) await discardBody(response); + this.#refuseIfUnauthorized(response.status); + if (!response.ok) { + await discardBody(response); + this.#logger.error(`HTTP error getting last thread info: ${response.status}`); + throw new ThreadInfoError(`Failed to get last thread info: HTTP ${response.status}`); + } + try { + const threads = threadListSchema.parse(await response.json()).filter((thread) => thread.source === 'whatsapp'); + const latest = threads[0]; + if (!latest) return { threadId: null, lastMessageTime: null }; + if (typeof latest.thread_id !== 'string' || typeof latest.updated_at !== 'string') throw new TypeError('bad thread'); + return { threadId: latest.thread_id, lastMessageTime: latest.updated_at }; + } catch (error) { + this.#logger.error('apps/api returned an unexpected thread-list response'); + throw new ThreadInfoError('Unexpected thread-list response', { cause: error }); + } + } + + async processMessage(token: string, threadId: string, message: string): Promise { + const idle = new IdleTimeout(this.#chatIdleTimeoutMs); + try { + let response: Response; + try { + response = await this.#fetch(`${this.#baseUrl}/api/v2/threads/${encodeURIComponent(threadId)}/chat`, { + method: 'POST', + headers: this.#headers(token), + body: JSON.stringify({ message }), + redirect: 'manual', + signal: idle.signal, + }); + } catch (error) { + throw this.#streamFailure(error, idle); + } + + if (response.status === 401) await discardBody(response); + this.#refuseIfUnauthorized(response.status); + if (response.status !== 200 || !response.body) { + await discardBody(response); + this.#logger.error(`Error from backend API: HTTP ${response.status}`); + throw new MessageProcessingError(`Backend returned HTTP ${response.status}`); + } + + // Accumulate the answer from the `text` events + let fullResponse = ''; + let done = false; + try { + for await (const line of readLines(response.body, () => idle.reset())) { + if (!line.startsWith('data:')) continue; // keep-alive comments and blank separator lines + let event: unknown; + try { + event = JSON.parse(line.slice('data:'.length)); + } catch (error) { + this.#logger.error('apps/api sent a chat event that is not JSON'); + throw new MessageProcessingError('Malformed chat event', { cause: error }); + } + const type = typeof event === 'object' && event !== null ? (event as { type?: unknown }).type : undefined; + if (type === 'text') { + const content = (event as { content?: unknown }).content; + fullResponse += typeof content === 'string' ? content : ''; + } else if (type === 'error') { + // The message is apps/api's own text, never user content, so it is safe to log + this.#logger.error(`apps/api reported a chat error: ${String((event as { message?: unknown }).message)}`); + throw new MessageProcessingError('apps/api reported an error while answering'); + } else if (type === 'done') { + done = true; + } + } + } catch (error) { + if (error instanceof MessageProcessingError) throw error; + throw this.#streamFailure(error, idle); + } + + if (!done) { + this.#logger.error('The chat stream from apps/api ended before it was complete'); + throw new MessageProcessingError('Chat stream ended before completion'); + } + if (fullResponse === '') { + this.#logger.warn('Received empty response from backend'); + return ''; + } + return fullResponse; + } finally { + idle.stop(); + } + } + + /** Turn a `fetch` or stream fault into a `MessageProcessingError` without leaking a URL or body. */ + #streamFailure(error: unknown, idle: IdleTimeout): MessageProcessingError { + if (idle.timedOut) { + this.#logger.error('Timeout processing message: no data from apps/api'); + return new MessageProcessingError('Request timed out while processing message', { cause: error }); + } + this.#logger.error(`Network error processing message: ${describeNetworkError(error)}`); + return new MessageProcessingError('Network error during message processing', { cause: error }); + } +} + +/** + * A stand-in for apps/api that keeps threads in memory, for local development (`MOCK_ANSARI_CLIENT`). + * Threads belong to a token, mirroring apps/api, where the token alone identifies the user. The mock auth client gives + * each BSUID its own stable token. + * + * Python's version slept 1 to 2 seconds per call and could be told to fail at random. Neither is kept: the delay slowed every + * test, and tests that need a failure throw their own. + */ +export class AnsariClientMock implements AnsariClient { + readonly #threads = new Map; updatedAt: string }>(); + #counter = 0; + readonly #logger: Logger; + readonly #now: () => Date; + + constructor(options: { logger: Logger; now?: () => Date }) { + this.#logger = options.logger; + this.#now = options.now ?? (() => new Date()); + this.#logger.info('Initialized AnsariClientMock - using mock backend'); + } + + #user(token: string, error: new (message: string) => Error): string { + if (!token) throw new error('Invalid token'); + return token; + } + + async createThread(token: string, title: string): Promise<{ threadId: string }> { + const user = this.#user(token, ThreadCreationError); + this.#counter += 1; + const threadId = `mock_thread_${this.#counter}`; + this.#threads.set(threadId, { user, title, messages: [], updatedAt: this.#now().toISOString() }); + this.#logger.info(`Mock: Created thread ${threadId}`); + return { threadId }; + } + + async deleteThread(token: string, threadId: string): Promise { + const user = this.#user(token, ThreadDeletionError); + const thread = this.#threads.get(threadId); + if (!thread) return; + if (thread.user !== user) throw new ThreadDeletionError('Thread access denied'); + this.#threads.delete(threadId); + this.#logger.info(`Mock: Deleted thread ${threadId}`); + } + + async getLastThreadInfo(token: string): Promise { + const user = this.#user(token, ThreadInfoError); + const mine = [...this.#threads].filter(([, thread]) => thread.user === user); + if (mine.length === 0) { + this.#logger.debug('Mock: No threads found for user'); + return { threadId: null, lastMessageTime: null }; + } + const [threadId, latest] = mine.reduce((best, entry) => (entry[1].updatedAt > best[1].updatedAt ? entry : best)); + return { threadId, lastMessageTime: latest.updatedAt }; + } + + async processMessage(token: string, threadId: string, message: string): Promise { + const user = this.#user(token, MessageProcessingError); + const thread = this.#threads.get(threadId); + if (!thread) { + this.#logger.error(`Mock: Thread ${threadId} not found for message processing`); + throw new MessageProcessingError('Thread not found'); + } + if (thread.user !== user) { + this.#logger.error(`Mock: Thread ${threadId} does not belong to this user`); + throw new MessageProcessingError('Thread access denied'); + } + thread.messages.push({ role: 'user', content: message }); + const response = `This is a *mock AI assistant* running in test mode.\n\nYour message: ${[...message].slice(0, 100).join('')}`; + thread.messages.push({ role: 'assistant', content: response }); + thread.updatedAt = this.#now().toISOString(); + this.#logger.info(`Mock: Processed message for thread ${threadId}, response length: ${[...response].length}`); + return response; + } +} diff --git a/apps/whatsapp/src/services/authClient.ts b/apps/whatsapp/src/services/authClient.ts new file mode 100644 index 00000000..ba121f28 --- /dev/null +++ b/apps/whatsapp/src/services/authClient.ts @@ -0,0 +1,222 @@ +/** + * The apps/auth client: exchanges a WhatsApp user's BSUID for a JWT that apps/api accepts. + * + * Python counterparts: `auth_client_base.py` (the interface), `auth_client_real.py` and `auth_client_mock.py`. + * + * Differences from Python: + * - `AuthClient` is an `interface`, a type with no code. Python's abstract base class (`ABC`) enforced the same promise + * at runtime; TypeScript checks it while compiling. `AuthClientReal implements AuthClient` makes the compiler refuse a + * class that misses a method. + * - Times are milliseconds on `performance.now()`, a clock that only moves forward (Python: `time.monotonic()`). + * - The clock, `fetch` and the settings are options rather than module globals, so a test passes its own. + */ +import { createHash } from 'node:crypto'; +import type { Secret } from '../config'; +import { + AuthBadRequestError, + AuthKeyRejectedError, + AuthRateLimitedError, + AuthTokenError, + AuthUserBannedError, +} from '../errors'; +import type { Logger } from '../logger'; +import { describeNetworkError, discardBody, trimTrailingSlashes, type FetchLike } from './http'; + +/** + * Contract (issue #329): `POST /api/whatsapp/session` with `Authorization: Bearer ` and `{"bsuid": ...}` answers + * `{"token": ...}`. Errors are `{"message"}` bodies: 400 the request failed apps/auth's sanity bounds on the BSUID (a bug + * here), 401 one identical body for every key refusal, 403 this user is banned, 429 this user's budget is spent + * (`X-Retry-After`), 500 an outage or a permanent fault for this one user. + */ +export const SESSION_PATH = '/api/whatsapp/session'; + +/** The token lives 15 minutes; reuse it for a bit less so a cached one never expires mid-request. */ +export const TOKEN_CACHE_SECONDS = 14 * 60; +export const TOKEN_CACHE_MAX_ENTRIES = 10_000; + +/** Used when a 429 carries no usable `X-Retry-After`: assume the user's whole 15-minute window in apps/auth. */ +export const DEFAULT_RETRY_AFTER_SECONDS = 15 * 60; + +const REQUEST_TIMEOUT_MS = 5000; + +/** Exchanges a WhatsApp user's BSUID for a JWT that apps/api accepts. */ +export interface AuthClient { + /** + * Get a JWT for the user identified by this BSUID (never a phone number). It is sent as the bearer token on every + * apps/api call. + * + * @throws {AuthTokenError} or one of its subclasses, each meaning something different (see `errors.ts`). + */ + getToken(bsuid: string): Promise; + /** Drop this user's cached token, e.g. after apps/api refused it. */ + forget(bsuid: string): void; +} + +export interface AuthClientOptions { + /** apps/auth's base URL, no path. */ + baseUrl: string; + /** Authenticates this service to apps/auth. */ + apiKey: Secret; + logger: Logger; + fetch?: FetchLike; + /** A clock that only moves forward, in milliseconds. Only tests pass it. */ + now?: () => number; + /** How many tokens (and cool-downs) to remember. Only tests pass it. */ + maxEntries?: number; +} + +/** Python's `int(header)` for a plain whole number, else `undefined`. */ +function parseWholeNumber(text: string | null): number | undefined { + if (text === null || !/^\s*[+-]?\d+\s*$/.test(text)) return undefined; + return Number.parseInt(text, 10); +} + +/** Calls apps/auth over HTTP, authenticated with `AUTH_WHATSAPP_API_KEY`. */ +export class AuthClientReal implements AuthClient { + readonly #url: string; + readonly #apiKey: Secret; + readonly #logger: Logger; + readonly #fetch: FetchLike; + readonly #now: () => number; + readonly #maxEntries: number; + /** bsuid -> its token and when it stops being reused. */ + #cache = new Map(); + /** bsuid -> when its 429 ends. */ + #cooldown = new Map(); + + constructor(options: AuthClientOptions) { + this.#url = `${trimTrailingSlashes(options.baseUrl)}${SESSION_PATH}`; + this.#apiKey = options.apiKey; + this.#logger = options.logger; + this.#fetch = options.fetch ?? fetch; + this.#now = options.now ?? (() => performance.now()); + this.#maxEntries = options.maxEntries ?? TOKEN_CACHE_MAX_ENTRIES; + } + + async getToken(bsuid: string): Promise { + const now = this.#now(); + const cached = this.#cache.get(bsuid); + if (cached && cached.expiresAt > now) return cached.token; + + // A user whose budget is spent is not asked again until it frees up: every ask would only be refused + const until = this.#cooldown.get(bsuid); + if (until !== undefined && until > now) { + throw new AuthRateLimitedError('Token exchange refused: user is cooling down', Math.floor((until - now) / 1000) + 1); + } + this.#cooldown.delete(bsuid); + + const token = await this.#exchange(bsuid); + this.#remember(bsuid, token); + return token; + } + + forget(bsuid: string): void { + this.#cache.delete(bsuid); + } + + #remember(bsuid: string, token: string): void { + const now = this.#now(); + if (this.#cache.size >= this.#maxEntries) { + this.#cache = new Map([...this.#cache].filter(([, entry]) => entry.expiresAt > now)); + } + if (this.#cache.size < this.#maxEntries) { + this.#cache.set(bsuid, { token, expiresAt: now + TOKEN_CACHE_SECONDS * 1000 }); + } + } + + #startCooldown(bsuid: string, retryAfterSeconds: number): void { + const now = this.#now(); + if (this.#cooldown.size >= this.#maxEntries) { + this.#cooldown = new Map([...this.#cooldown].filter(([, ends]) => ends > now)); + } + if (this.#cooldown.size < this.#maxEntries) { + this.#cooldown.set(bsuid, now + retryAfterSeconds * 1000); + } + } + + static #retryAfter(response: Response): number { + const value = parseWholeNumber(response.headers.get('X-Retry-After')); + return value !== undefined && value > 0 ? value : DEFAULT_RETRY_AFTER_SECONDS; + } + + async #exchange(bsuid: string): Promise { + let response: Response; + try { + response = await this.#fetch(this.#url, { + method: 'POST', + headers: { Authorization: `Bearer ${this.#apiKey.reveal()}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ bsuid }), + redirect: 'manual', + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + } catch (error) { + this.#logger.error(`Network error during token exchange: ${describeNetworkError(error)}`); + throw new AuthTokenError('Network error during token exchange', { cause: error }); + } + + const status = response.status; + if (status !== 200) await discardBody(response); + + if (status === 400) { + this.#logger.error('apps/auth refused the request as malformed (HTTP 400): a bug in this service'); + throw new AuthBadRequestError('Token exchange failed: HTTP 400'); + } + if (status === 401) { + this.#logger.error("apps/auth rejected this service's API key (HTTP 401): the key needs an operator"); + throw new AuthKeyRejectedError('Token exchange failed: HTTP 401'); + } + if (status === 403) { + this.#logger.warn('apps/auth says this user is banned (HTTP 403)'); + throw new AuthUserBannedError('Token exchange refused: user is banned'); + } + if (status === 429) { + const retryAfter = AuthClientReal.#retryAfter(response); + this.#startCooldown(bsuid, retryAfter); + this.#logger.warn(`apps/auth says this user's exchange budget is spent (HTTP 429), retry in ${retryAfter}s`); + throw new AuthRateLimitedError('Token exchange refused: user budget spent', retryAfter); + } + if (status !== 200) { + this.#logger.error(`apps/auth failed the token exchange: HTTP ${status}`); + throw new AuthTokenError(`Token exchange failed: HTTP ${status}`); + } + + let body: unknown; + try { + body = await response.json(); + } catch (error) { + this.#logger.error('apps/auth returned a non-JSON token response'); + throw new AuthTokenError('Invalid token response', { cause: error }); + } + + // `typeof body === 'object'` is true for null and arrays too, so both are excluded by hand + const token = typeof body === 'object' && body !== null && !Array.isArray(body) ? (body as { token?: unknown }).token : undefined; + if (typeof token !== 'string' || token === '') { + this.#logger.error('apps/auth token response had no token'); + throw new AuthTokenError('Token response had no token'); + } + return token; + } +} + +/** + * A stand-in for apps/auth that makes up tokens, for local development (`MOCK_AUTH_CLIENT`). + * Each BSUID gets its own stable fake token, so one BSUID is one user and a new BSUID is a new user. + * With `MOCK_AUTH_TOKEN` set, every BSUID gets that one real JWT, so a mocked sign-in can talk to a real apps/api. + * + * The fake token is `mock-token-` plus a hash of the BSUID. Python used a UUID; nothing compares the two. + */ +export class AuthClientMock implements AuthClient { + readonly #fixedToken: Secret | undefined; + + constructor(options: { fixedToken?: Secret } = {}) { + this.#fixedToken = options.fixedToken; + } + + async getToken(bsuid: string): Promise { + if (!bsuid) throw new AuthTokenError('Missing BSUID'); + if (this.#fixedToken) return this.#fixedToken.reveal(); + return `mock-token-${createHash('sha256').update(`mock-bsuid:${bsuid}`).digest('hex').slice(0, 32)}`; + } + + forget(): void {} +} diff --git a/apps/whatsapp/src/services/http.ts b/apps/whatsapp/src/services/http.ts new file mode 100644 index 00000000..6cf85c51 --- /dev/null +++ b/apps/whatsapp/src/services/http.ts @@ -0,0 +1,121 @@ +/** + * Small helpers shared by the three HTTP clients. + * + * Python used `httpx`; Node ships `fetch`. Three differences that the clients have to handle: + * - `httpx` does not follow redirects, `fetch` does. Every call here passes `redirect: 'manual'` and treats a 3xx as a + * failure, so a token is never sent to a place the operator did not configure. + * - `httpx`'s timeout is per wait (connecting, then each read). `fetch` has none, only an `AbortSignal` you build yourself. + * A plain deadline is right for a short call; a streamed answer needs `IdleTimeout` below. + * - A `fetch` response whose body is never read keeps its connection busy until it is garbage-collected, so every + * response a client gives up on goes through `discardBody`. + */ + +/** The type of `fetch`. Clients take it as an option so tests can hand in a fake. */ +export type FetchLike = typeof fetch; + +/** Release a response we will not read. Errors are ignored: the body may already be consumed or locked. */ +export async function discardBody(response: Response): Promise { + try { + await response.body?.cancel(); + } catch { + // already consumed or locked + } +} + +/** + * A short, safe description of why a `fetch` failed, for logs: the error's class, plus the system error code when there + * is one (`TypeError/ECONNREFUSED`). Never the message: Node's can include the URL. + */ +export function describeNetworkError(error: unknown): string { + if (!(error instanceof Error)) return typeof error; + const cause: unknown = error.cause; + const code = cause instanceof Error && 'code' in cause ? String((cause as { code: unknown }).code) : undefined; + return code ? `${error.name}/${code}` : error.name; +} + +/** + * An abort signal that fires after `ms` of silence rather than after `ms` in total: call `reset()` whenever something + * arrives. This is what `httpx`'s per-read timeout gave the Python client, and what lets a chat answer stream for + * minutes as long as apps/api keeps sending its `: ping` lines. + */ +export class IdleTimeout { + readonly signal: AbortSignal; + /** True once the timer, not the caller, aborted the request. */ + timedOut = false; + + readonly #controller = new AbortController(); + readonly #ms: number; + #timer: ReturnType | undefined; + + constructor(ms: number) { + this.#ms = ms; + this.signal = this.#controller.signal; + this.reset(); + } + + reset(): void { + clearTimeout(this.#timer); + this.#timer = setTimeout(() => { + this.timedOut = true; + this.#controller.abort(); + }, this.#ms); + } + + /** Stop the timer. Always call it when the request is over, or the timer keeps the process alive. */ + stop(): void { + clearTimeout(this.#timer); + } +} + +/** + * Read a response body line by line (Python: `response.aiter_lines()`). + * + * A body arrives in chunks that can end anywhere: in the middle of a line, in the middle of a multi-byte character, or + * between the `\r` and the `\n` of a line ending. So the bytes go through a streaming `TextDecoder` (which holds back an + * unfinished character), and a trailing `\r` is held until the next chunk shows whether a `\n` follows. + * + * Lines end at `\n`, `\r\n` or `\r`, as the Server-Sent Events standard says. Python's `str.splitlines()` also splits at + * U+2028 and a few other characters; apps/api's JSON can contain a raw U+2028 inside a string, which would cut that + * event in two, so this does not split there. `onChunk` is called for every chunk, so a caller can restart an idle timer. + */ +export async function* readLines( + body: ReadableStream, + onChunk: () => void = () => {}, +): AsyncGenerator { + const decoder = new TextDecoder('utf-8'); + const reader = body.getReader(); + let buffer = ''; + const LINE_END = /\r\n|\n|\r/; + + function* drain(final: boolean): Generator { + for (;;) { + const match = LINE_END.exec(buffer); + if (!match) return; + // A \r at the very end might be the first half of \r\n: wait, unless nothing more can arrive + if (match[0] === '\r' && match.index === buffer.length - 1 && !final) return; + yield buffer.slice(0, match.index); + buffer = buffer.slice(match.index + match[0].length); + } + } + + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + onChunk(); + buffer += decoder.decode(value, { stream: true }); + yield* drain(false); + } + buffer += decoder.decode(); + yield* drain(true); + if (buffer !== '') yield buffer; + } finally { + // Stop reading if the caller left early (an error event, a failed check): the connection is released + await reader.cancel().catch(() => {}); + } +} + +/** Remove trailing slashes, so `http://host/` + `/path` does not become `http://host//path`. */ +export function trimTrailingSlashes(url: string): string { + return url.replace(/\/+$/, ''); +} diff --git a/apps/whatsapp/src/services/metaApiService.ts b/apps/whatsapp/src/services/metaApiService.ts new file mode 100644 index 00000000..71d616db --- /dev/null +++ b/apps/whatsapp/src/services/metaApiService.ts @@ -0,0 +1,253 @@ +/** + * Sending messages to WhatsApp users through Meta's Cloud API. + * + * Python counterparts: `meta_api_service_base.py` (the interface), `meta_api_service_real.py` and + * `meta_api_service_mock.py`. + * + * Differences from Python: + * - One `MetaApiError` replaces httpx's two exceptions (`HTTPStatusError` for a bad status, `RequestError` for a network + * fault); its `status` is Meta's HTTP status, or `undefined` for a network fault. Callers only ever caught `Exception`. + * - `fetch` has no per-phase timeouts like httpx's `Timeout(20, connect=10)`: each request gets one 20 s deadline. + * - What Sentry gets is handed in as a function (`reportError`), so this file never imports Sentry. + */ +import type { Secret } from '../config'; +import { MetaApiError } from '../errors'; +import type { ErrorReporter } from '../errorReporter'; +import { noopErrorReporter } from '../errorReporter'; +import { getRequestId, type Logger } from '../logger'; +import { maskIdentifiers, redactValues } from '../logMasking'; +import { pythonList, pythonRepr } from '../utils/pythonRepr'; +import { describeNetworkError, discardBody, type FetchLike } from './http'; + +/** Sending to a user is the answer they are waiting for; Meta can take longer than a few seconds to accept one. */ +const REQUEST_TIMEOUT_MS = 20_000; + +/** String values of a send payload that describe its shape and name nobody (the rest is masked outside local). */ +const SAFE_REQUEST_KEYS: ReadonlySet = new Set(['messaging_product', 'type', 'recipient_type', 'status']); + +export interface MetaApiService { + /** + * Show the "typing..." indicator for a message the user sent. `recipient` is not sent: Meta ties the indicator to + * `messageId`. + * + * @throws {MetaApiError} if Meta refuses or cannot be reached. + */ + sendTypingIndicator(recipient: string, messageId: string): Promise; + /** + * Send already-split message parts, in order. + * + * @throws {MetaApiError} if Meta refuses or cannot be reached; parts after the failed one are not sent. + */ + sendMessage(recipient: string, messageParts: string[]): Promise; +} + +/** A number, but not `true`/`false` (Python's `isinstance(value, int) and not isinstance(value, bool)`). */ +function integerOrNull(value: unknown): number | null { + return typeof value === 'number' && Number.isInteger(value) ? value : null; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** `String(value or "")` cut to `max` characters. Python's `str[:n]` counts code points. */ +function clip(value: unknown, max: number): string { + if (value === null || value === undefined || value === '' || value === false || value === 0) return ''; + return [...String(value)].slice(0, max).join(''); +} + +/** + * The structured part of Meta's error reply, with anything shaped like an identifier masked. + * + * Meta documents the error object as `code`, `type`, `error_subcode`, `fbtrace_id`, `message` (the code and its title) and + * `error_data.details`, but not that none of them can name the recipient, so the two texts are masked. + * https://developers.facebook.com/documentation/business-messaging/whatsapp/support/error-codes + */ +export async function metaErrorSummary(response: Response): Promise { + const raw = await response.text().catch(() => ''); + let body: unknown; + try { + body = JSON.parse(raw); + } catch { + body = undefined; + } + const error = isRecord(body) ? body.error : undefined; + if (!isRecord(error)) return `no standard error object (${new TextEncoder().encode(raw).length} bytes)`; + const errorData = isRecord(error.error_data) ? error.error_data : {}; + + const fields: Array<[string, unknown]> = [ + ['code', integerOrNull(error.code)], + ['error_subcode', integerOrNull(error.error_subcode)], + ['type', maskIdentifiers(clip(error.type, 64))], + ['fbtrace_id', maskIdentifiers(clip(error.fbtrace_id, 64))], + ['message', maskIdentifiers(clip(error.message, 300))], + ['details', maskIdentifiers(clip(errorData.details, 300))], + ]; + return fields + .filter(([, value]) => value !== null && value !== '') + .map(([name, value]) => `${name}=${pythonRepr(value)}`) + .join(' '); +} + +export interface MetaApiOptions { + /** `https://graph.facebook.com/{version}/{phone-number-id}/messages`, from the settings. */ + apiUrl: string; + accessToken: Secret; + /** Decides how much of a rejected request is logged. */ + deploymentType: 'local' | 'development' | 'staging' | 'production'; + logger: Logger; + reportError?: ErrorReporter; + fetch?: FetchLike; +} + +/** The real service: calls Meta's Cloud API. */ +export class MetaApiServiceReal implements MetaApiService { + readonly #options: MetaApiOptions; + readonly #fetch: FetchLike; + readonly #reportError: ErrorReporter; + + constructor(options: MetaApiOptions) { + this.#options = options; + this.#fetch = options.fetch ?? fetch; + this.#reportError = options.reportError ?? noopErrorReporter; + } + + #headers(): Record { + return { Authorization: `Bearer ${this.#options.accessToken.reveal()}`, 'Content-Type': 'application/json' }; + } + + /** POST one JSON payload to Meta. Anything but a 2xx raises, after logging what Meta said. */ + async #post(payload: Record, what: string, endpoint: string): Promise { + const { logger } = this.#options; + let response: Response; + try { + response = await this.#fetch(this.#options.apiUrl, { + method: 'POST', + headers: this.#headers(), + body: JSON.stringify(payload), + redirect: 'manual', + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + } catch (error) { + logger.error(`Network error sending ${what} (${describeNetworkError(error)})`); + throw new MetaApiError(`Network error sending ${what}`, undefined, { cause: error }); + } + + if (response.ok) { + await discardBody(response); + return; + } + + logger.error(`HTTP error sending ${what}: ${response.status}`); + await this.#logMetaError(response, payload); + const error = new MetaApiError(`Meta answered HTTP ${response.status} to ${what}`, response.status); + // Only report 5xx errors (Meta's fault, not ours) + if (response.status >= 500) { + this.#reportError(error, { + errorType: 'meta_api_failure', + context: { status_code: response.status, endpoint, request_id: getRequestId() }, + }); + } + throw error; + } + + /** + * Log what Meta said, and for a 400 what we sent. + * + * Meta's raw body is never logged, only its structured fields with identifiers masked. For a 400 the payload's keys are + * logged everywhere; their values too, masked on staging and development and unmasked only on local. + */ + async #logMetaError(response: Response, sent: Record): Promise { + const { logger, deploymentType } = this.#options; + logger.error(`Meta's reply (${response.status}): ${await metaErrorSummary(response)}`); + if (response.status !== 400) return; + + let line = `Meta rejected the request (400). URL: ${this.#options.apiUrl} | Payload keys: ${pythonList(Object.keys(sent).sort())}`; + if (deploymentType !== 'production') { + const headers = Object.fromEntries( + Object.entries(this.#headers()).map(([key, value]) => [key, key.toLowerCase() === 'authorization' ? 'Bearer ***' : value]), + ); + line += ` | Headers: ${pythonRepr(headers)}`; + line += + deploymentType === 'local' + ? ` | Body: ${JSON.stringify(sent)}` + : ` | Body with values masked: ${pythonRepr(redactValues(sent, SAFE_REQUEST_KEYS))}`; + } + logger.error(line); + } + + async sendTypingIndicator(recipient: string, messageId: string): Promise { + const { logger } = this.#options; + if (!recipient || !messageId) { + logger.error('Cannot send typing indicator: missing recipient or message id'); + return; + } + logger.debug('Sending typing indicator'); + await this.#post( + { messaging_product: 'whatsapp', status: 'read', message_id: messageId, typing_indicator: { type: 'text' } }, + 'typing indicator', + 'send_typing_indicator', + ); + logger.info('Typing indicator sent successfully'); + } + + /** + * Per Meta, a phone number goes in `to`, while a BSUID goes in `recipient` (with `to` omitted; if both are sent, `to` + * takes precedence). Meta's changelog says BSUID sending is supported since July 2026. + * https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids#send-message-requests + */ + async sendMessage(recipient: string, messageParts: string[]): Promise { + const { logger } = this.#options; + if (!recipient) { + logger.error('Cannot send message: No recipient'); + return; + } + if (messageParts.length === 0) { + logger.warn('No message parts to send'); + return; + } + + logger.debug(`Sending ${messageParts.length} message part(s)`); + for (const [index, part] of messageParts.entries()) { + const payload: Record = { messaging_product: 'whatsapp', type: 'text', text: { body: part } }; + // Digits only is a phone number; anything else is a business-scoped user ID (e.g. US.1349...) + if (/^[0-9]+$/.test(recipient)) { + payload.to = recipient; + } else { + payload.recipient_type = 'individual'; + payload.recipient = recipient; + } + await this.#post(payload, 'message', 'send_message'); + logger.info(`Sent message part ${index + 1}/${messageParts.length}: ${[...part].length} characters`); + } + logger.info(`All ${messageParts.length} message part(s) sent successfully`); + } +} + +/** A stand-in for Meta that sends nothing, for local development (`MOCK_META_API`). Records what it was asked to send. */ +export class MetaApiServiceMock implements MetaApiService { + /** Every `sendMessage` call, so a test can assert on who was written to and what. */ + readonly sent: Array<{ recipient: string; messageParts: string[] }> = []; + readonly #logger: Logger; + readonly #delayMs: number; + + constructor(options: { logger: Logger; delayMs?: number }) { + this.#logger = options.logger; + this.#delayMs = options.delayMs ?? 50; + this.#logger.info('Initialized MetaApiServiceMock - Meta API calls will be simulated'); + } + + async sendTypingIndicator(_recipient: string, messageId: string): Promise { + this.#logger.info(`[MOCK META API] Typing indicator simulated (msg_id: ${messageId})`); + // A minimal network delay + await new Promise((resolve) => setTimeout(resolve, this.#delayMs)); + } + + async sendMessage(recipient: string, messageParts: string[]): Promise { + this.#logger.info(`[MOCK META API] Sending ${messageParts.length} message part(s)`); + this.sent.push({ recipient, messageParts: [...messageParts] }); + for (const [index, part] of messageParts.entries()) { + this.#logger.info(`[MOCK META API] Part ${index + 1}/${messageParts.length}: ${[...part].length} characters`); + } + } +} diff --git a/apps/whatsapp/src/utils/pythonRepr.ts b/apps/whatsapp/src/utils/pythonRepr.ts new file mode 100644 index 00000000..785d4fbc --- /dev/null +++ b/apps/whatsapp/src/utils/pythonRepr.ts @@ -0,0 +1,67 @@ +/** + * Python's `repr()` for the few shapes that reach a log line: strings, numbers, booleans, null, lists and dicts. + * + * Why it exists: the Python service logged values with `!r` and f-strings of lists and dicts, so a line looked like + * `code=131030 type='OAuthException'` or `Payload keys: ['messaging_product', 'text']`. People search the Railway logs for + * exactly those shapes, and the Python tests assert them, so the TypeScript service prints the same text. + * + * `tests/fixtures/pythonOracle.ts` holds what Python's `repr()` returned for a table of values, and + * `tests/pythonRepr.test.ts` compares against it. + */ + +/** + * Characters Python's `repr()` writes as an escape instead of showing. Python's rule is "not printable": control + * characters, unassigned code points, and every separator except the plain space (no-break space, line and paragraph + * separators, zero-width and other format characters). JavaScript's Unicode classes cover the same ground: + * `Cc` control, `Cf` format, `Cs` surrogate, `Co` private use, `Cn` unassigned, `Zl`/`Zp` line and paragraph separator, + * and `Zs` space separators. + */ +const UNPRINTABLE = /[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}\p{Zs}]/u; + +/** One character the way Python escapes it: `\t`, `\n`, `\r`, `\xNN`, `\uNNNN` or `\UNNNNNNNN`. */ +function escapeCodePoint(char: string): string { + const code = char.codePointAt(0)!; + if (code === 0x09) return '\\t'; + if (code === 0x0a) return '\\n'; + if (code === 0x0d) return '\\r'; + const hex = code.toString(16); + if (code <= 0xff) return `\\x${hex.padStart(2, '0')}`; + if (code <= 0xffff) return `\\u${hex.padStart(4, '0')}`; + return `\\U${hex.padStart(8, '0')}`; +} + +/** + * A string the way Python prints it. It uses single quotes, unless the text holds a `'` and no `"`, and escapes the + * quote it chose, backslashes, and anything not printable. + */ +function repr(text: string): string { + const quote = text.includes("'") && !text.includes('"') ? '"' : "'"; + let out = ''; + // `for...of` walks code points, so an emoji is one step, not two halves + for (const char of text) { + if (char === '\\') out += '\\\\'; + else if (char === quote) out += `\\${quote}`; + else if (char === ' ') out += ' '; + else if (UNPRINTABLE.test(char)) out += escapeCodePoint(char); + else out += char; + } + return `${quote}${out}${quote}`; +} + +export function pythonRepr(value: unknown): string { + if (value === null || value === undefined) return 'None'; + if (typeof value === 'string') return repr(value); + if (typeof value === 'boolean') return value ? 'True' : 'False'; + if (typeof value === 'number') return String(value); + if (Array.isArray(value)) return `[${value.map(pythonRepr).join(', ')}]`; + if (typeof value === 'object') { + const entries = Object.entries(value).map(([key, item]) => `${repr(key)}: ${pythonRepr(item)}`); + return `{${entries.join(', ')}}`; + } + return repr(String(value)); +} + +/** `['a', 'b']`, like Python prints a list of strings. */ +export function pythonList(items: readonly string[]): string { + return pythonRepr([...items]); +} diff --git a/apps/whatsapp/src/webhook/parseWebhook.ts b/apps/whatsapp/src/webhook/parseWebhook.ts index 08d3a933..50be3a5c 100644 --- a/apps/whatsapp/src/webhook/parseWebhook.ts +++ b/apps/whatsapp/src/webhook/parseWebhook.ts @@ -22,6 +22,7 @@ import type { Env } from '../config'; import { InvalidMetaPayloadError, UnexpectedMetaPayloadError } from '../errors'; import type { Logger } from '../logger'; import { redactValues } from '../logMasking'; +import { pythonList } from '../utils/pythonRepr'; /** What a webhook turned out to be. */ export type ParsedWebhook = @@ -75,11 +76,6 @@ function has(obj: object, key: string): boolean { return Object.hasOwn(obj, key); } -/** Python's `list` repr, `['a', 'b']`, so error messages read the same as before. */ -function pythonList(items: string[]): string { - return `[${items.map((item) => `'${item}'`).join(', ')}]`; -} - function invalidPayload(message: string, logger?: Pick): InvalidMetaPayloadError { logger?.error(message); return new InvalidMetaPayloadError(message); diff --git a/apps/whatsapp/tests/ansariClient.test.ts b/apps/whatsapp/tests/ansariClient.test.ts new file mode 100644 index 00000000..dce304d7 --- /dev/null +++ b/apps/whatsapp/tests/ansariClient.test.ts @@ -0,0 +1,398 @@ +/** + * The apps/api client. + * + * Python tests ported: the apps/api cases of `test_bsuid_auth_flow.py` (JWT on every call, the event stream, an `error` + * event or a missing `done` is a failure, no body in logs) and the 401 case of `test_auth_statuses.py`. The Python tests + * patched `httpx.AsyncClient`; here the client takes `fetch`, so a test hands in a fake and nothing touches the network. + * + * Streams are cut in awkward places on purpose (mid-line, mid-character), because real connections do that and the + * Python tests could not. + */ +import { describe, expect, it } from 'vitest'; +import { + ApiUnauthorizedError, + MessageProcessingError, + ThreadCreationError, + ThreadDeletionError, + ThreadInfoError, +} from '../src/errors'; +import { AnsariClientMock, AnsariClientReal, CLIENT_ID } from '../src/services/ansariClient'; +import { + bytesInChunks, + capturingLogger, + fakeFetch, + jsonResponse, + sse, + streamedResponse, + type Handler, +} from './helpers/network'; + +const TOKEN = 'jwt-of-the-user'; + +function setup(handler: Handler, options: { chatIdleTimeoutMs?: number } = {}) { + const net = fakeFetch(handler); + const log = capturingLogger(); + const client = new AnsariClientReal({ baseUrl: 'http://api.test/', logger: log.logger, fetch: net.fetch, ...options }); + return { client, log, ...net }; +} + +async function thrown(promise: Promise): Promise { + try { + await promise; + } catch (error) { + return error; + } + throw new Error('expected an error, but the call succeeded'); +} + +const ANSWER = sse([{ type: 'text', content: 'As-salamu ' }, { type: 'text', content: 'alaykum' }, { type: 'done' }]); + +describe('every request', () => { + it('carries the user\'s JWT and the client id, and never follows a redirect', async () => { + const { client, calls } = setup((request) => { + if (request.method === 'GET') return jsonResponse(200, []); + if (request.path.endsWith('/chat')) return new Response(ANSWER, { status: 200 }); + if (request.method === 'DELETE') return new Response(null, { status: 204 }); + return jsonResponse(200, { thread_id: 't2' }); + }); + + await client.getLastThreadInfo(TOKEN); + await client.createThread(TOKEN, 'title'); + await client.processMessage(TOKEN, 't1', 'hi'); + await client.deleteThread(TOKEN, 't1'); + + expect(calls).toHaveLength(4); + for (const call of calls) { + expect(call.headers.authorization).toBe(`Bearer ${TOKEN}`); + expect(call.headers['x-ansari-client']).toBe(CLIENT_ID); + expect(call.redirect).toBe('manual'); + expect(call.signal).toBeInstanceOf(AbortSignal); + } + }); + + it('uses the lowercase attribution id apps/api expects', () => { + expect(CLIENT_ID).toBe('askansari-whatsapp'); + }); + + it('builds URLs from the base URL without doubling the slash', async () => { + const { client, calls } = setup(() => jsonResponse(200, [])); + await client.getLastThreadInfo(TOKEN); + expect(calls[0]!.url).toBe('http://api.test/api/v2/threads'); + }); + + it('keeps a thread id from changing the path', async () => { + const { client, calls } = setup(() => new Response(null, { status: 204 })); + await client.deleteThread(TOKEN, '../../admin?x=1'); + expect(calls[0]!.url).toBe('http://api.test/api/v2/threads/..%2F..%2Fadmin%3Fx%3D1'); + }); +}); + +describe('threads', () => { + it('finds the newest thread this service created, ignoring other clients\' threads', async () => { + const { client } = setup(() => + jsonResponse(200, [ + { thread_id: 'web-1', source: 'web', updated_at: '2026-10-26T10:00:00.000Z' }, + { thread_id: 't1', source: 'whatsapp', updated_at: '2026-10-25T10:00:00.000Z' }, + { thread_id: 't0', source: 'whatsapp', updated_at: '2026-10-24T10:00:00.000Z' }, + ]), + ); + expect(await client.getLastThreadInfo(TOKEN)).toEqual({ threadId: 't1', lastMessageTime: '2026-10-25T10:00:00.000Z' }); + }); + + it.each([[[]], [[{ thread_id: 'w', source: 'web', updated_at: 'x' }]]])('reports no thread for %j', async (list) => { + const { client } = setup(() => jsonResponse(200, list)); + expect(await client.getLastThreadInfo(TOKEN)).toEqual({ threadId: null, lastMessageTime: null }); + }); + + it('creates a thread named by the title, marked as coming from WhatsApp', async () => { + const { client, calls } = setup(() => jsonResponse(200, { thread_id: 't2' })); + expect(await client.createThread(TOKEN, 'my title')).toEqual({ threadId: 't2' }); + expect(calls[0]!.method).toBe('POST'); + expect(calls[0]!.json).toEqual({ name: 'my title', source: 'whatsapp' }); + }); + + it('deletes a thread, and treats a thread that is already gone as done', async () => { + const { client } = setup(() => new Response(null, { status: 404 })); + await expect(client.deleteThread(TOKEN, 't1')).resolves.toBeUndefined(); + }); + + it.each([ + ['listing', (c: AnsariClientReal) => c.getLastThreadInfo(TOKEN), ThreadInfoError], + ['creating', (c: AnsariClientReal) => c.createThread(TOKEN, 't'), ThreadCreationError], + ['deleting', (c: AnsariClientReal) => c.deleteThread(TOKEN, 't'), ThreadDeletionError], + ] as const)('%s: a server error, a network fault and a redirect each raise the method\'s own error', async (_name, call, expected) => { + for (const handler of [ + () => jsonResponse(500, { detail: 'boom' }), + () => { + throw new TypeError('fetch failed'); + }, + () => new Response(null, { status: 302, headers: { Location: 'http://evil.test/' } }), + ] as Handler[]) { + const { client } = setup(handler); + const error = await thrown(call(client)); + expect(error).toBeInstanceOf(expected); + } + }); + + it.each([ + ['listing', (c: AnsariClientReal) => c.getLastThreadInfo(TOKEN)], + ['creating', (c: AnsariClientReal) => c.createThread(TOKEN, 't')], + ['deleting', (c: AnsariClientReal) => c.deleteThread(TOKEN, 't')], + ['chatting', (c: AnsariClientReal) => c.processMessage(TOKEN, 't', 'hi')], + ] as const)('%s: a 401 is "refresh the token", not a generic failure', async (_name, call) => { + const { client } = setup(() => jsonResponse(401, { message: 'expired' })); + expect(await thrown(call(client))).toBeInstanceOf(ApiUnauthorizedError); + }); + + it.each([ + ['not JSON', () => new Response('', { status: 200 })], + ['not an object', () => jsonResponse(200, 'thread')], + ['no thread_id', () => jsonResponse(200, {})], + ['an empty thread_id', () => jsonResponse(200, { thread_id: '' })], + ['a numeric thread_id', () => jsonResponse(200, { thread_id: 7 })], + ] as const)('creating: an answer that is %s raises ThreadCreationError', async (_name, answer) => { + const { client } = setup(answer); + expect(await thrown(client.createThread(TOKEN, 't'))).toBeInstanceOf(ThreadCreationError); + }); + + it.each([ + ['not JSON', () => new Response('', { status: 200 })], + ['not a list', () => jsonResponse(200, { threads: [] })], + ['a thread without an id', () => jsonResponse(200, [{ source: 'whatsapp', updated_at: 'x' }])], + ['a thread without a time', () => jsonResponse(200, [{ thread_id: 't', source: 'whatsapp' }])], + ['a list holding null', () => jsonResponse(200, [null])], + ] as const)('listing: an answer that is %s raises ThreadInfoError', async (_name, answer) => { + const { client } = setup(answer); + expect(await thrown(client.getLastThreadInfo(TOKEN))).toBeInstanceOf(ThreadInfoError); + }); +}); + +describe('the chat stream', () => { + it('sends the message in the body and joins the text events into one answer', async () => { + const { client, calls } = setup(() => new Response(ANSWER, { status: 200 })); + expect(await client.processMessage(TOKEN, 't1', 'hi there')).toBe('As-salamu alaykum'); + expect(calls[0]!.method).toBe('POST'); + expect(calls[0]!.path).toBe('/api/v2/threads/t1/chat'); + expect(calls[0]!.json).toEqual({ message: 'hi there' }); + }); + + it('ignores tool events, keep-alive comments and blank lines', async () => { + const stream = ': ping\n\n' + sse([{ type: 'tool_call', name: 'search_quran' }, { type: 'tool_result', resultCount: 3 }, { type: 'text', content: 'ok' }, { type: 'done' }], { ping: false }) + ': ping\n\n\n'; + const { client } = setup(() => new Response(stream, { status: 200 })); + expect(await client.processMessage(TOKEN, 't1', 'hi')).toBe('ok'); + }); + + it('gives an empty answer when apps/api finishes without saying anything', async () => { + const { client } = setup(() => new Response(sse([{ type: 'done' }]), { status: 200 })); + expect(await client.processMessage(TOKEN, 't1', 'hi')).toBe(''); + }); + + it('ignores a text event without content', async () => { + const { client } = setup(() => new Response(sse([{ type: 'text' }, { type: 'text', content: null }, { type: 'text', content: 5 }, { type: 'text', content: 'x' }, { type: 'done' }]), { status: 200 })); + expect(await client.processMessage(TOKEN, 't1', 'hi')).toBe('x'); + }); + + // `done` follows the error, so only the error event itself can make this fail (not the missing-done check) + it('treats an error event as a failure, not as an answer', async () => { + const stream = sse([{ type: 'text', content: 'partial' }, { type: 'error', message: 'model overloaded' }, { type: 'done' }]); + const { client } = setup(() => new Response(stream, { status: 200 })); + expect(await thrown(client.processMessage(TOKEN, 't1', 'hi'))).toBeInstanceOf(MessageProcessingError); + }); + + it('treats a stream cut off before done as a failure, so half an answer is never sent on', async () => { + const { client } = setup(() => new Response(sse([{ type: 'text', content: 'half an ans' }]), { status: 200 })); + expect(await thrown(client.processMessage(TOKEN, 't1', 'hi'))).toBeInstanceOf(MessageProcessingError); + }); + + it('treats a malformed event as a failure', async () => { + const { client } = setup(() => new Response('data: this is not json\n\n', { status: 200 })); + expect(await thrown(client.processMessage(TOKEN, 't1', 'hi'))).toBeInstanceOf(MessageProcessingError); + }); + + it.each([[500], [400], [503], [302]])('treats HTTP %s as a failure', async (status) => { + const { client } = setup(() => new Response('boom', { status })); + const error = (await thrown(client.processMessage(TOKEN, 't1', 'hi'))) as Error; + expect(error).toBeInstanceOf(MessageProcessingError); + expect(error.message).toContain(String(status)); + }); + + it('treats a 200 with no body as a failure', async () => { + const { client } = setup(() => new Response(null, { status: 200 })); + expect(await thrown(client.processMessage(TOKEN, 't1', 'hi'))).toBeInstanceOf(MessageProcessingError); + }); + + it('never lets an error body reach the logs or the raised error', async () => { + const { client, log } = setup(() => new Response('{"detail":"echo of the user: a-very-distinctive-question"}', { status: 400 })); + const error = (await thrown(client.processMessage(TOKEN, 't1', 'hi'))) as Error; + expect(error.message).toContain('400'); + expect(error.message).not.toContain('a-very-distinctive-question'); + expect(log.text()).not.toContain('a-very-distinctive-question'); + }); + + it('keeps the user\'s message and the answer out of the logs', async () => { + const stream = sse([{ type: 'text', content: 'the-secret-answer' }, { type: 'done' }]); + const { client, log } = setup(() => new Response(stream, { status: 200 })); + await client.processMessage(TOKEN, 't1', 'the-secret-question'); + expect(log.text()).not.toContain('the-secret-answer'); + expect(log.text()).not.toContain('the-secret-question'); + expect(log.text()).not.toContain(TOKEN); + }); + + it('reports the chat error text apps/api sent, which is its own text', async () => { + const stream = sse([{ type: 'error', message: 'model overloaded' }]); + const { client, log } = setup(() => new Response(stream, { status: 200 })); + await thrown(client.processMessage(TOKEN, 't1', 'hi')); + expect(log.text()).toContain('apps/api reported a chat error: model overloaded'); + }); +}); + +describe('a stream that arrives in pieces', () => { + it('reads the same answer however the bytes are cut, even inside a multi-byte character', async () => { + const text = 'As-salamu alaykum \u0645\u0631\u062d\u0628\u0627 \u{1F600} caf\u00e9'; + const stream = sse([{ type: 'text', content: text }, { type: 'done' }]); + for (const size of [1, 2, 3, 5, 7, 64]) { + const { client } = setup(() => streamedResponse(bytesInChunks(stream, size))); + expect(await client.processMessage(TOKEN, 't1', 'hi')).toBe(text); + } + }); + + it('reads CRLF line endings, including one split between \\r and \\n', async () => { + const stream = sse([{ type: 'text', content: 'ab' }, { type: 'done' }]).replaceAll('\n', '\r\n'); + for (const size of [1, 2, 3, 11]) { + const { client } = setup(() => streamedResponse(bytesInChunks(stream, size))); + expect(await client.processMessage(TOKEN, 't1', 'hi')).toBe('ab'); + } + }); + + it('reads a final event that has no trailing newline', async () => { + const stream = 'data: {"type":"text","content":"x"}\n\ndata: {"type":"done"}'; + const { client } = setup(() => new Response(stream, { status: 200 })); + expect(await client.processMessage(TOKEN, 't1', 'hi')).toBe('x'); + }); + + it('is not cut in two by a raw U+2028 inside the answer', async () => { + const text = 'before\u2028after'; + const stream = `data: ${JSON.stringify({ type: 'text', content: text }).replace('\\u2028', '\u2028')}\n\ndata: {"type":"done"}\n\n`; + const { client } = setup(() => new Response(stream, { status: 200 })); + expect(await client.processMessage(TOKEN, 't1', 'hi')).toBe(text); + }); + + it('stays open past the idle timeout while data keeps arriving', async () => { + const chunks = [': ping\n\n', 'data: {"type":"text","content":"a"}\n\n', ': ping\n\n', 'data: {"type":"text","content":"b"}\n\n', 'data: {"type":"done"}\n\n']; + const { client } = setup((request) => streamedResponse(chunks, { delayMs: 40, signal: request.signal }), { chatIdleTimeoutMs: 100 }); + // 5 chunks x 40 ms = 200 ms in total, over the 100 ms idle limit, but never silent for 100 ms + expect(await client.processMessage(TOKEN, 't1', 'hi')).toBe('ab'); + }); + + it('gives up when apps/api goes silent, and says it timed out', async () => { + const { client, log } = setup((request) => streamedResponse(['data: {"type":"text","content":"a"}\n\n'], { hangAfter: true, signal: request.signal }), { + chatIdleTimeoutMs: 80, + }); + const error = (await thrown(client.processMessage(TOKEN, 't1', 'hi'))) as Error; + expect(error).toBeInstanceOf(MessageProcessingError); + expect(error.message).toContain('timed out'); + expect(log.text()).toContain('Timeout processing message'); + }); + + it('gives up when apps/api never starts to answer', async () => { + const { client } = setup( + (request) => + new Promise((_resolve, reject) => { + request.signal?.addEventListener('abort', () => reject(request.signal?.reason ?? new Error('aborted')), { once: true }); + }), + { chatIdleTimeoutMs: 60 }, + ); + const error = (await thrown(client.processMessage(TOKEN, 't1', 'hi'))) as Error; + expect(error).toBeInstanceOf(MessageProcessingError); + expect(error.message).toContain('timed out'); + }); + + it('raises a network error, without leaking the URL, when the connection drops mid-answer', async () => { + const { client, log } = setup(() => { + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('data: {"type":"text","content":"a"}\n\n')); + controller.error(Object.assign(new TypeError('terminated'), { cause: Object.assign(new Error('read ECONNRESET http://api.test'), { code: 'ECONNRESET' }) })); + }, + }); + return new Response(body, { status: 200 }); + }); + const error = (await thrown(client.processMessage(TOKEN, 't1', 'hi'))) as Error; + expect(error).toBeInstanceOf(MessageProcessingError); + expect(error.message).toContain('Network error'); + expect(log.text()).toContain('TypeError/ECONNRESET'); + expect(log.text()).not.toContain('api.test'); + }); + + it('raises a network error when the request cannot be made at all', async () => { + const { client } = setup(() => { + throw new TypeError('fetch failed'); + }); + expect(await thrown(client.processMessage(TOKEN, 't1', 'hi'))).toBeInstanceOf(MessageProcessingError); + }); + + it('stops reading as soon as it has failed, so the connection is released', async () => { + let cancelled = false; + const { client } = setup(() => { + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode(sse([{ type: 'error', message: 'x' }]))); + }, + cancel() { + cancelled = true; + }, + }); + return new Response(body, { status: 200 }); + }); + await thrown(client.processMessage(TOKEN, 't1', 'hi')); + expect(cancelled).toBe(true); + }); +}); + +describe('AnsariClientMock', () => { + function mock() { + return new AnsariClientMock({ logger: capturingLogger().logger, now: (() => { let t = Date.UTC(2026, 10, 10); return () => new Date((t += 1000)); })() }); + } + + it('keeps one user\'s threads apart from another\'s', async () => { + const m = mock(); + const { threadId } = await m.createThread('alice', 'a'); + expect(await m.getLastThreadInfo('bob')).toEqual({ threadId: null, lastMessageTime: null }); + expect((await m.getLastThreadInfo('alice')).threadId).toBe(threadId); + expect(await thrown(m.processMessage('bob', threadId, 'hi'))).toBeInstanceOf(MessageProcessingError); + expect(await thrown(m.deleteThread('bob', threadId))).toBeInstanceOf(ThreadDeletionError); + }); + + it('answers a message and moves the thread\'s last activity forward', async () => { + const m = mock(); + const { threadId } = await m.createThread('alice', 'a'); + const before = (await m.getLastThreadInfo('alice')).lastMessageTime!; + expect(await m.processMessage('alice', threadId, 'hello')).toContain('hello'); + expect((await m.getLastThreadInfo('alice')).lastMessageTime! > before).toBe(true); + }); + + it('picks the most recently active of a user\'s threads', async () => { + const m = mock(); + const first = await m.createThread('alice', '1'); + const second = await m.createThread('alice', '2'); + await m.processMessage('alice', first.threadId, 'x'); + expect((await m.getLastThreadInfo('alice')).threadId).toBe(first.threadId); + await m.processMessage('alice', second.threadId, 'y'); + expect((await m.getLastThreadInfo('alice')).threadId).toBe(second.threadId); + }); + + it('deletes a thread and its messages, and a missing thread is not an error', async () => { + const m = mock(); + const { threadId } = await m.createThread('alice', 'a'); + await m.deleteThread('alice', threadId); + expect(await m.getLastThreadInfo('alice')).toEqual({ threadId: null, lastMessageTime: null }); + await expect(m.deleteThread('alice', threadId)).resolves.toBeUndefined(); + }); + + it('refuses a missing token and an unknown thread', async () => { + const m = mock(); + expect(await thrown(m.createThread('', 'a'))).toBeInstanceOf(ThreadCreationError); + expect(await thrown(m.getLastThreadInfo(''))).toBeInstanceOf(ThreadInfoError); + expect(await thrown(m.processMessage('alice', 'nope', 'hi'))).toBeInstanceOf(MessageProcessingError); + }); +}); diff --git a/apps/whatsapp/tests/authClient.test.ts b/apps/whatsapp/tests/authClient.test.ts new file mode 100644 index 00000000..48b65c3a --- /dev/null +++ b/apps/whatsapp/tests/authClient.test.ts @@ -0,0 +1,323 @@ +/** + * The apps/auth client. + * + * Python tests ported: `test_auth_statuses.py` (each status means something different, the 429 cool-down, `forget`) and the + * auth-client cases of `test_bsuid_auth_flow.py` (bearer key, one token per BSUID, failures not cached, no token in the + * answer). The Python tests patched `httpx.AsyncClient` and `time.monotonic`; here the client takes `fetch` and a clock. + */ +import { describe, expect, it } from 'vitest'; +import { Secret } from '../src/config'; +import { + AuthBadRequestError, + AuthKeyRejectedError, + AuthRateLimitedError, + AuthTokenError, + AuthUserBannedError, +} from '../src/errors'; +import { + AuthClientMock, + AuthClientReal, + DEFAULT_RETRY_AFTER_SECONDS, + SESSION_PATH, + TOKEN_CACHE_SECONDS, +} from '../src/services/authClient'; +import { capturingLogger, fakeFetch, jsonResponse, type Handler } from './helpers/network'; + +const BSUID = 'US.13491208655302741918'; +const OTHER = 'US.99999999999999999999'; + +function setup(handler: Handler, options: { maxEntries?: number } = {}) { + const net = fakeFetch(handler); + const log = capturingLogger(); + const clock = { now: 1_000_000 }; + const client = new AuthClientReal({ + baseUrl: 'http://auth.test/', + apiKey: new Secret('the-service-key'), + logger: log.logger, + fetch: net.fetch, + now: () => clock.now, + ...options, + }); + return { client, clock, log, ...net }; +} + +/** Run `promise` and return what it threw. */ +async function thrown(promise: Promise): Promise { + try { + await promise; + } catch (error) { + return error; + } + throw new Error('expected an error, but the call succeeded'); +} + +describe('the exchange', () => { + it('sends the BSUID with the service key as a bearer token, and returns the token', async () => { + const { client, calls } = setup(() => jsonResponse(200, { token: 'jwt-123' })); + + expect(await client.getToken(BSUID)).toBe('jwt-123'); + + expect(calls).toHaveLength(1); + expect(calls[0]!.url).toBe(`http://auth.test${SESSION_PATH}`); + expect(calls[0]!.method).toBe('POST'); + expect(calls[0]!.headers.authorization).toBe('Bearer the-service-key'); + expect(calls[0]!.headers['x-whatsapp-api-key']).toBeUndefined(); + expect(calls[0]!.json).toEqual({ bsuid: BSUID }); + }); + + it('never follows a redirect, so the key is not sent anywhere else', async () => { + const { client, calls } = setup(() => new Response(null, { status: 302, headers: { Location: 'http://evil.test/' } })); + expect(await thrown(client.getToken(BSUID))).toBeInstanceOf(AuthTokenError); + expect(calls[0]!.redirect).toBe('manual'); + expect(calls).toHaveLength(1); + }); + + it('gives the request a deadline', async () => { + const { client, calls } = setup(() => jsonResponse(200, { token: 't' })); + await client.getToken(BSUID); + expect(calls[0]!.signal).toBeInstanceOf(AbortSignal); + }); + + it('never logs the service key or the token', async () => { + const { client, log } = setup(() => jsonResponse(200, { token: 'jwt-secret-value' })); + await client.getToken(BSUID); + expect(log.text()).not.toContain('the-service-key'); + expect(log.text()).not.toContain('jwt-secret-value'); + }); +}); + +describe('the token cache', () => { + it('reuses a token per BSUID until it is nearly expired', async () => { + const seen: string[] = []; + const { client, clock } = setup((request) => { + seen.push((request.json as { bsuid: string }).bsuid); + return jsonResponse(200, { token: `jwt-${seen.length}` }); + }); + + const first = await client.getToken(BSUID); + const again = await client.getToken(BSUID); + const other = await client.getToken(OTHER); + clock.now += (TOKEN_CACHE_SECONDS + 1) * 1000; + const renewed = await client.getToken(BSUID); + + expect([first, again]).toEqual(['jwt-1', 'jwt-1']); + expect(other).toBe('jwt-2'); + expect(renewed).toBe('jwt-3'); + expect(seen).toEqual([BSUID, OTHER, BSUID]); + }); + + it('reuses a token for a bit less than the 15 minutes it lives', () => { + expect(TOKEN_CACHE_SECONDS).toBe(14 * 60); + }); + + it('does not cache a failure', async () => { + const answers = [jsonResponse(500, { message: 'boom' }), jsonResponse(200, { token: 'jwt-ok' })]; + const { client } = setup(() => answers.shift()!); + + expect(await thrown(client.getToken(BSUID))).toBeInstanceOf(AuthTokenError); + expect(await client.getToken(BSUID)).toBe('jwt-ok'); + }); + + it('drops only that user\'s token on forget()', async () => { + const asked: string[] = []; + const { client } = setup((request) => { + asked.push((request.json as { bsuid: string }).bsuid); + return jsonResponse(200, { token: `jwt-${asked.length}` }); + }); + await client.getToken(BSUID); + await client.getToken(OTHER); + + client.forget(BSUID); + + expect(await client.getToken(BSUID)).toBe('jwt-3'); + expect(await client.getToken(OTHER)).toBe('jwt-2'); + expect(asked).toEqual([BSUID, OTHER, BSUID]); + }); + + it('stops remembering new users once the cache is full of live entries, instead of growing', async () => { + const { client, calls } = setup(() => jsonResponse(200, { token: 't' }), { maxEntries: 2 }); + for (const id of ['US.1', 'US.2', 'US.3']) await client.getToken(id); + const callsBefore = calls.length; + await client.getToken('US.1'); + await client.getToken('US.3'); + expect(calls.length - callsBefore).toBe(1); + }); + + it('makes room by dropping expired tokens first', async () => { + const { client, clock, calls } = setup(() => jsonResponse(200, { token: 't' }), { maxEntries: 2 }); + await client.getToken('US.1'); + await client.getToken('US.2'); + clock.now += (TOKEN_CACHE_SECONDS + 1) * 1000; + await client.getToken('US.3'); + const callsBefore = calls.length; + await client.getToken('US.3'); + expect(calls.length).toBe(callsBefore); + }); +}); + +describe('each status means something different', () => { + it.each([ + [400, AuthBadRequestError], + [401, AuthKeyRejectedError], + [403, AuthUserBannedError], + [500, AuthTokenError], + ] as const)('HTTP %s raises exactly its own error', async (status, expected) => { + const { client } = setup(() => jsonResponse(status, { message: 'x' })); + const error = await thrown(client.getToken(BSUID)); + expect(error).toBeInstanceOf(expected); + expect((error as Error).constructor).toBe(expected); + }); + + it('does not mistake a 500 for a more specific refusal', async () => { + const { client } = setup(() => jsonResponse(500, { message: 'Internal error' })); + const error = await thrown(client.getToken(BSUID)); + for (const specific of [AuthBadRequestError, AuthKeyRejectedError, AuthUserBannedError, AuthRateLimitedError]) { + expect(error).not.toBeInstanceOf(specific); + } + }); + + it('treats any other failing status as a plain exchange failure', async () => { + const { client } = setup(() => jsonResponse(502, {})); + const error = await thrown(client.getToken(BSUID)); + expect((error as Error).constructor).toBe(AuthTokenError); + }); + + it('keeps every refusal an AuthTokenError, so a caller can catch them all', async () => { + for (const status of [400, 401, 403, 429, 500]) { + const { client } = setup(() => jsonResponse(status, {})); + expect(await thrown(client.getToken(BSUID))).toBeInstanceOf(AuthTokenError); + } + }); +}); + +describe('a spent budget (HTTP 429)', () => { + it('carries how long to wait', async () => { + const { client } = setup(() => jsonResponse(429, { message: 'Too many requests' }, { 'X-Retry-After': '420' })); + const error = (await thrown(client.getToken(BSUID))) as AuthRateLimitedError; + expect(error).toBeInstanceOf(AuthRateLimitedError); + expect(error.retryAfter).toBe(420); + }); + + // Python's int() accepts these shapes too; a header of "12.5", "1e3" or "" is not a whole number in either language + it.each([[null], ['soon'], ['0'], ['-5'], [''], ['12.5'], ['1e3']])( + 'falls back to a default when the wait is %j', + async (header) => { + const headers: Record = header === null ? {} : { 'X-Retry-After': header }; + const { client } = setup(() => jsonResponse(429, {}, headers)); + const error = (await thrown(client.getToken(BSUID))) as AuthRateLimitedError; + expect(error.retryAfter).toBe(DEFAULT_RETRY_AFTER_SECONDS); + }, + ); + + it('reads a wait padded with spaces, like Python', async () => { + const { client } = setup(() => jsonResponse(429, {}, { 'X-Retry-After': ' 90 ' })); + expect(((await thrown(client.getToken(BSUID))) as AuthRateLimitedError).retryAfter).toBe(90); + }); + + it('falls back to the user\'s whole fifteen-minute window', () => { + expect(DEFAULT_RETRY_AFTER_SECONDS).toBe(15 * 60); + }); + + it('does not ask apps/auth again for that user until the budget frees up', async () => { + const answers = [jsonResponse(429, {}, { 'X-Retry-After': '120' }), jsonResponse(200, { token: 'jwt-after-cooldown' })]; + const { client, clock, calls } = setup(() => answers.shift()!); + + expect(await thrown(client.getToken(BSUID))).toBeInstanceOf(AuthRateLimitedError); + clock.now += 30_000; + const still = (await thrown(client.getToken(BSUID))) as AuthRateLimitedError; + expect(calls).toHaveLength(1); // a cooling-down user must not reach apps/auth again + expect(still.retryAfter).toBeGreaterThan(0); + expect(still.retryAfter).toBeLessThanOrEqual(91); + + clock.now += 91_000; + expect(await client.getToken(BSUID)).toBe('jwt-after-cooldown'); + expect(calls).toHaveLength(2); + }); + + it('does not let one user\'s cool-down affect another', async () => { + const { client } = setup((request) => + (request.json as { bsuid: string }).bsuid === BSUID + ? jsonResponse(429, {}, { 'X-Retry-After': '600' }) + : jsonResponse(200, { token: 'jwt-other' }), + ); + expect(await thrown(client.getToken(BSUID))).toBeInstanceOf(AuthRateLimitedError); + expect(await client.getToken(OTHER)).toBe('jwt-other'); + }); + + it('bounds how many cool-downs it remembers', async () => { + const { client, calls } = setup(() => jsonResponse(429, {}, { 'X-Retry-After': '600' }), { maxEntries: 2 }); + for (const id of ['US.1', 'US.2', 'US.3']) await thrown(client.getToken(id)); + const before = calls.length; + await thrown(client.getToken('US.1')); + await thrown(client.getToken('US.3')); + // US.1 is cooling down (no call); US.3 was not remembered (one call) + expect(calls.length - before).toBe(1); + }); +}); + +describe('a banned user', () => { + it('is not cached or cooled down, so being unbanned takes effect at once', async () => { + const answers = [jsonResponse(403, {}), jsonResponse(200, { token: 'jwt-unbanned' })]; + const { client } = setup(() => answers.shift()!); + expect(await thrown(client.getToken(BSUID))).toBeInstanceOf(AuthUserBannedError); + expect(await client.getToken(BSUID)).toBe('jwt-unbanned'); + }); +}); + +describe('answers that are not a token', () => { + it('raises on a network fault, without leaking the URL', async () => { + const { client, log } = setup(() => { + throw Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error('connect ECONNREFUSED http://auth.test'), { code: 'ECONNREFUSED' }) }); + }); + const error = await thrown(client.getToken(BSUID)); + expect(error).toBeInstanceOf(AuthTokenError); + expect(log.text()).toContain('TypeError/ECONNREFUSED'); + expect(log.text()).not.toContain('auth.test'); + }); + + it('raises when the request times out', async () => { + const { client } = setup(() => { + throw new DOMException('The operation was aborted due to timeout', 'TimeoutError'); + }); + expect(await thrown(client.getToken(BSUID))).toBeInstanceOf(AuthTokenError); + }); + + it.each([ + ['an empty object', () => jsonResponse(200, {})], + ['a null token', () => jsonResponse(200, { token: null })], + ['an empty token', () => jsonResponse(200, { token: '' })], + ['a numeric token', () => jsonResponse(200, { token: 42 })], + ['JSON null', () => jsonResponse(200, null)], + ['a JSON list', () => jsonResponse(200, ['jwt'])], + ['text that is not JSON', () => new Response('not json', { status: 200 })], + ] as const)('raises on %s', async (_name, answer) => { + const { client } = setup(answer); + expect(await thrown(client.getToken(BSUID))).toBeInstanceOf(AuthTokenError); + }); +}); + +describe('AuthClientMock', () => { + const log = capturingLogger(); + void log; + + it('gives the same BSUID the same token and a new BSUID a new one', async () => { + const mock = new AuthClientMock(); + const first = await mock.getToken(BSUID); + expect(await mock.getToken(BSUID)).toBe(first); + expect(await mock.getToken(OTHER)).not.toBe(first); + }); + + it('returns the one configured JWT for every BSUID when MOCK_AUTH_TOKEN is set', async () => { + const mock = new AuthClientMock({ fixedToken: new Secret('a.real.jwt') }); + expect(await mock.getToken(BSUID)).toBe('a.real.jwt'); + expect(await mock.getToken(OTHER)).toBe('a.real.jwt'); + }); + + it('refuses a missing BSUID', async () => { + expect(await thrown(new AuthClientMock().getToken(''))).toBeInstanceOf(AuthTokenError); + }); + + it('keeps forget() harmless', () => { + expect(() => new AuthClientMock().forget()).not.toThrow(); + }); +}); diff --git a/apps/whatsapp/tests/fixtures/generate_python_oracle.py b/apps/whatsapp/tests/fixtures/generate_python_oracle.py index c53899e1..0fe9cb02 100644 --- a/apps/whatsapp/tests/fixtures/generate_python_oracle.py +++ b/apps/whatsapp/tests/fixtures/generate_python_oracle.py @@ -218,6 +218,43 @@ def message_age_case(age): return [age, unix, is_message_too_old(unix)] +# Values the services print with !r or inside an f-string of a list or dict (the Meta error summary and payload keys). +# JSON-shaped, so the same value can be written on both sides. +REPR_INPUTS = [ + "plain", + "it's", + 'say "hi"', + "it's \"both\"", + "line\nbreak", + "tab\there", + "back\\slash", + "", + " ", + "carriage\rreturn", + "\u00e9 accent", + "\u0645\u0631\u062d\u0628\u0627", + "\U0001f600 emoji", + "nul\x00byte", + "del\x7fchar", + "zero\u200bwidth", + "no\u00a0break space", + "line\u2028separator", + 131030, + -5, + 0, + 1.5, + True, + False, + None, + [], + ["a", "b"], + ["it's", 1, None], + {}, + {"k": "v"}, + {"a": [1, "x"], "it's": {"n": None}}, +] + + # --------------------------------------------------------------------------------------------------------------------- # Splitter: inputs are described by a recipe both languages can rebuild; the expected answer is a summary # --------------------------------------------------------------------------------------------------------------------- @@ -366,6 +403,7 @@ def main(out_path: str) -> None: "HEADER_CASES": [[t, convert_headers(t)] for t in HEADER_INPUTS], "NESTED_LIST_CASES": [[t, format_nested_lists(t)] for t in NESTED_INPUTS], "DIRECTION_CASES": [[t, get_language_direction_from_text(t)] for t in DIRECTION_INPUTS], + "REPR_CASES": [[value, repr(value)] for value in REPR_INPUTS], "TIME_DELTA_CASES": [[s, format_time_delta(s)] for s in TIME_DELTA_INPUTS], "TIME_PASSED_CASES": [time_passed_case(s) for s in TIME_PASSED_INPUTS], "MESSAGE_AGE_CASES": [message_age_case(a) for a in MESSAGE_AGE_INPUTS], @@ -388,6 +426,7 @@ def main(out_path: str) -> None: "HEADER_CASES": "Cases", "NESTED_LIST_CASES": "Cases", "DIRECTION_CASES": "Cases", + "REPR_CASES": "Array<[value: unknown, python: string]>", "TIME_DELTA_CASES": "Array<[seconds: number, formatted: string]>", "TIME_PASSED_CASES": "Array<[secondsAgo: number | null, passed: number | 'inf', logging: string]>", "MESSAGE_AGE_CASES": "Array<[secondsAgo: number | null, unixTime: number | null, tooOld: boolean]>", diff --git a/apps/whatsapp/tests/fixtures/pythonOracle.ts b/apps/whatsapp/tests/fixtures/pythonOracle.ts index 5ab5fe8f..0c654862 100644 --- a/apps/whatsapp/tests/fixtures/pythonOracle.ts +++ b/apps/whatsapp/tests/fixtures/pythonOracle.ts @@ -480,6 +480,150 @@ export const DIRECTION_CASES: Cases = [ ] ]; +export const REPR_CASES: Array<[value: unknown, python: string]> = [ + [ + "plain", + "'plain'" + ], + [ + "it's", + "\"it's\"" + ], + [ + "say \"hi\"", + "'say \"hi\"'" + ], + [ + "it's \"both\"", + "'it\\'s \"both\"'" + ], + [ + "line\nbreak", + "'line\\nbreak'" + ], + [ + "tab\there", + "'tab\\there'" + ], + [ + "back\\slash", + "'back\\\\slash'" + ], + [ + "", + "''" + ], + [ + " ", + "' '" + ], + [ + "carriage\rreturn", + "'carriage\\rreturn'" + ], + [ + "\u00e9 accent", + "'\u00e9 accent'" + ], + [ + "\u0645\u0631\u062d\u0628\u0627", + "'\u0645\u0631\u062d\u0628\u0627'" + ], + [ + "\ud83d\ude00 emoji", + "'\ud83d\ude00 emoji'" + ], + [ + "nul\u0000byte", + "'nul\\x00byte'" + ], + [ + "del\u007fchar", + "'del\\x7fchar'" + ], + [ + "zero\u200bwidth", + "'zero\\u200bwidth'" + ], + [ + "no\u00a0break space", + "'no\\xa0break space'" + ], + [ + "line\u2028separator", + "'line\\u2028separator'" + ], + [ + 131030, + "131030" + ], + [ + -5, + "-5" + ], + [ + 0, + "0" + ], + [ + 1.5, + "1.5" + ], + [ + true, + "True" + ], + [ + false, + "False" + ], + [ + null, + "None" + ], + [ + [], + "[]" + ], + [ + [ + "a", + "b" + ], + "['a', 'b']" + ], + [ + [ + "it's", + 1, + null + ], + "[\"it's\", 1, None]" + ], + [ + {}, + "{}" + ], + [ + { + "k": "v" + }, + "{'k': 'v'}" + ], + [ + { + "a": [ + 1, + "x" + ], + "it's": { + "n": null + } + }, + "{'a': [1, 'x'], \"it's\": {'n': None}}" + ] +]; + export const TIME_DELTA_CASES: Array<[seconds: number, formatted: string]> = [ [ 0, diff --git a/apps/whatsapp/tests/helpers/network.ts b/apps/whatsapp/tests/helpers/network.ts new file mode 100644 index 00000000..25064f8d --- /dev/null +++ b/apps/whatsapp/tests/helpers/network.ts @@ -0,0 +1,124 @@ +/** + * Test helpers for the HTTP clients: a fake `fetch`, streamed responses, and a logger that keeps what it is told. + * + * Python counterpart: `httpx.MockTransport(handler)` plus Loguru sinks. The clients take `fetch` as an option, so a test + * hands in `fakeFetch(...).fetch` and nothing touches the network or patches a module. + */ +import { createLogger, type Logger } from '../../src/logger'; + +/** `fetch`'s own parameter types: this project has no DOM library, so names like `RequestInfo` are not defined. */ +type FetchInput = Parameters[0]; +type FetchInit = NonNullable[1]>; + +/** What a client sent, in a form a test can assert on. */ +export interface SentRequest { + url: string; + path: string; + method: string; + headers: Record; + /** The body as text, or `undefined` when none was sent. */ + body: string | undefined; + /** The body parsed as JSON, or `undefined` when there is none or it is not JSON. */ + json: unknown; + redirect: FetchInit['redirect']; + signal: AbortSignal | null | undefined; +} + +export type Handler = (request: SentRequest) => Response | Promise; + +/** A `fetch` that answers from `handler` and records every request. */ +export function fakeFetch(handler: Handler): { fetch: typeof fetch; calls: SentRequest[] } { + const calls: SentRequest[] = []; + const fakeFetchFn = async (input: FetchInput, init?: FetchInit): Promise => { + const url = input instanceof Request ? input.url : String(input); + const headers = Object.fromEntries(new Headers(init?.headers).entries()); + const body = typeof init?.body === 'string' ? init.body : undefined; + let json: unknown; + try { + json = body === undefined ? undefined : JSON.parse(body); + } catch { + json = undefined; + } + const request: SentRequest = { + url, + path: new URL(url).pathname, + method: init?.method ?? 'GET', + headers, + body, + json, + redirect: init?.redirect, + signal: init?.signal, + }; + calls.push(request); + return handler(request); + }; + return { fetch: fakeFetchFn as typeof fetch, calls }; +} + +/** Answers every request with the same JSON. */ +export function jsonResponse(status: number, body: unknown, headers: Record = {}): Response { + return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', ...headers } }); +} + +/** An apps/api `/chat` stream: optional keep-alive comment lines, then one `data:` line per event. */ +export function sse(events: unknown[], options: { ping?: boolean } = {}): string { + const ping = options.ping ?? true ? ': ping\n\n' : ''; + return ping + events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(''); +} + +/** + * A response whose body arrives in the given chunks, optionally with a pause before each. A chunk is text (encoded as + * UTF-8) or raw bytes. Honours the request's abort signal like a real connection: aborting errors the stream. + */ +export function streamedResponse( + chunks: Array, + options: { status?: number; delayMs?: number; hangAfter?: boolean; signal?: AbortSignal | null } = {}, +): Response { + const encoder = new TextEncoder(); + let index = 0; + const body = new ReadableStream({ + async pull(controller) { + if (options.delayMs) await new Promise((resolve) => setTimeout(resolve, options.delayMs)); + if (options.signal?.aborted) { + controller.error(options.signal.reason ?? new Error('aborted')); + return; + } + if (index < chunks.length) { + const chunk = chunks[index++]!; + controller.enqueue(typeof chunk === 'string' ? encoder.encode(chunk) : chunk); + return; + } + if (options.hangAfter) { + // Stay silent until the request is aborted + await new Promise((resolve) => { + if (!options.signal) return; + options.signal.addEventListener('abort', () => resolve(), { once: true }); + }); + controller.error(options.signal?.reason ?? new Error('aborted')); + return; + } + controller.close(); + }, + }); + return new Response(body, { status: options.status ?? 200 }); +} + +/** Cut text into chunks of `size` UTF-8 BYTES, so a chunk can end inside a multi-byte character. */ +export function bytesInChunks(text: string, size: number): Uint8Array[] { + const bytes = new TextEncoder().encode(text); + const chunks: Uint8Array[] = []; + for (let i = 0; i < bytes.length; i += size) chunks.push(bytes.slice(i, i + size)); + return chunks; +} + +/** A logger that keeps everything it is told. `text()` is all of it, `lines()` one entry per log call. */ +export function capturingLogger(): { logger: Logger; text: () => string; lines: () => Array<{ level: string; message: string }> } { + const out: string[] = []; + const logger = createLogger({ + deploymentType: 'production', + level: 'DEBUG', + sinks: { stdout: (line) => out.push(line), stderr: (line) => out.push(line) }, + }); + const lines = () => out.map((line) => JSON.parse(line) as { level: string; message: string }); + return { logger, text: () => out.join(''), lines }; +} diff --git a/apps/whatsapp/tests/http.test.ts b/apps/whatsapp/tests/http.test.ts new file mode 100644 index 00000000..0792eed7 --- /dev/null +++ b/apps/whatsapp/tests/http.test.ts @@ -0,0 +1,150 @@ +/** + * The line reader and idle timer shared by the clients. + * + * Python counterpart: `response.aiter_lines()` and httpx's read timeout. The chat client skips blank lines, so a wrong split of + * `\r\n` or a lost chunk boundary can hide there; these tests read the lines themselves. + */ +import { describe, expect, it } from 'vitest'; +import { describeNetworkError, IdleTimeout, readLines, trimTrailingSlashes } from '../src/services/http'; +import { bytesInChunks, streamedResponse } from './helpers/network'; + +async function linesOf(chunks: Array): Promise { + const out: string[] = []; + for await (const line of readLines(streamedResponse(chunks).body!)) out.push(line); + return out; +} + +describe('readLines', () => { + it('splits at \\n, \\r\\n and \\r, as the Server-Sent Events standard says', async () => { + expect(await linesOf(['a\nb\r\nc\rd'])).toEqual(['a', 'b', 'c', 'd']); + }); + + it('gives a blank line for each blank separator', async () => { + expect(await linesOf(['a\n\nb\n'])).toEqual(['a', '', 'b']); + }); + + it('does not add a line after a final newline', async () => { + expect(await linesOf(['a\n'])).toEqual(['a']); + }); + + it('returns a last line that has no newline', async () => { + expect(await linesOf(['a\nb'])).toEqual(['a', 'b']); + }); + + it('returns nothing for an empty body', async () => { + expect(await linesOf([])).toEqual([]); + }); + + it('joins a line cut between chunks', async () => { + expect(await linesOf(['data: hel', 'lo\nnext'])).toEqual(['data: hello', 'next']); + }); + + // A \r at the end of a chunk may be half of \r\n. Treating it as a whole line end would invent a blank line. + it('does not turn \\r\\n into two line ends when the chunk ends between them', async () => { + expect(await linesOf(['a\r', '\nb'])).toEqual(['a', 'b']); + expect(await linesOf(['a\r', '\r\nb'])).toEqual(['a', '', 'b']); + }); + + it('ends a line at a \\r that really is alone, once the next chunk shows it', async () => { + expect(await linesOf(['a\r', 'b'])).toEqual(['a', 'b']); + }); + + it('ends a line at a final \\r when nothing more arrives', async () => { + expect(await linesOf(['a\r'])).toEqual(['a']); + }); + + it('gives the same lines however the bytes are cut, even inside a multi-byte character', async () => { + const text = 'caf\u00e9 \u0645\u0631\u062d\u0628\u0627\r\n\u{1F600} done\n'; + const expected = ['caf\u00e9 \u0645\u0631\u062d\u0628\u0627', '\u{1F600} done']; + for (const size of [1, 2, 3, 4, 5, 9, 100]) { + expect(await linesOf(bytesInChunks(text, size))).toEqual(expected); + } + }); + + it('does not split at U+2028 or other characters Python\'s splitlines would', async () => { + expect(await linesOf(['one\u2028two\u0085three\u000bfour\u000cfive\n'])).toEqual(['one\u2028two\u0085three\u000bfour\u000cfive']); + }); + + it('calls onChunk for every chunk', async () => { + let chunks = 0; + const body = streamedResponse(['a\n', 'b\n', 'c\n']).body!; + for await (const line of readLines(body, () => (chunks += 1))) void line; + expect(chunks).toBe(3); + }); + + it('releases the connection when the caller stops early', async () => { + let cancelled = false; + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('a\nb\nc\n')); + }, + cancel() { + cancelled = true; + }, + }); + for await (const line of readLines(body)) { + void line; + break; + } + expect(cancelled).toBe(true); + }); +}); + +describe('IdleTimeout', () => { + const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + + it('aborts after the idle time and says the timer did it', async () => { + const idle = new IdleTimeout(30); + await wait(80); + expect(idle.signal.aborted).toBe(true); + expect(idle.timedOut).toBe(true); + idle.stop(); + }); + + it('is pushed back by reset()', async () => { + const idle = new IdleTimeout(60); + for (let i = 0; i < 4; i++) { + await wait(30); + idle.reset(); + } + expect(idle.signal.aborted).toBe(false); + idle.stop(); + }); + + it('does not fire after stop()', async () => { + const idle = new IdleTimeout(20); + idle.stop(); + await wait(60); + expect(idle.signal.aborted).toBe(false); + expect(idle.timedOut).toBe(false); + }); +}); + +describe('describeNetworkError', () => { + it('names the error class and the system code, never the message', () => { + const error = Object.assign(new TypeError('fetch failed for http://secret.test'), { + cause: Object.assign(new Error('connect ECONNREFUSED http://secret.test'), { code: 'ECONNREFUSED' }), + }); + expect(describeNetworkError(error)).toBe('TypeError/ECONNREFUSED'); + }); + + it('gives just the class when there is no code', () => { + expect(describeNetworkError(new TypeError('boom http://secret.test'))).toBe('TypeError'); + }); + + it('copes with a value that is not an Error', () => { + expect(describeNetworkError('text')).toBe('string'); + expect(describeNetworkError(undefined)).toBe('undefined'); + }); +}); + +describe('trimTrailingSlashes', () => { + it.each([ + ['http://h/', 'http://h'], + ['http://h///', 'http://h'], + ['http://h', 'http://h'], + ['http://h/a/', 'http://h/a'], + ])('%s -> %s', (input, expected) => { + expect(trimTrailingSlashes(input)).toBe(expected); + }); +}); diff --git a/apps/whatsapp/tests/metaApiService.test.ts b/apps/whatsapp/tests/metaApiService.test.ts new file mode 100644 index 00000000..4e24f435 --- /dev/null +++ b/apps/whatsapp/tests/metaApiService.test.ts @@ -0,0 +1,357 @@ +/** + * Sending to Meta. + * + * Python tests ported: `test_meta_sender_logging.py` (what is logged when Meta refuses, in every environment, and that no + * phone number, BSUID, message text or token reaches a log outside local) and the Meta-payload cases of + * `test_bsuid_auth_flow.py` (a phone goes in `to`, a BSUID in `recipient`). + */ +import { describe, expect, it } from 'vitest'; +import { Secret } from '../src/config'; +import { MetaApiError } from '../src/errors'; +import { MetaApiServiceMock, MetaApiServiceReal, metaErrorSummary } from '../src/services/metaApiService'; +import { runWithRequestId } from '../src/logger'; +import { capturingLogger, fakeFetch, jsonResponse, type Handler } from './helpers/network'; + +const BSUID = 'US.13491208655302741918'; +const PHONE = '201234567899'; +const MESSAGE_TEXT = 'a-very-distinctive-reply-text'; +const TRACE_ID = 'Axly7O1UTgCLGu6n8EXWWTD'; +const TOKEN = 'the-meta-access-token'; +const API_URL = 'https://graph.facebook.com/v26.0/123456/messages'; + +/** What Meta sent for a recipient who was not on the test number's list. */ +const META_REPLY = { + error: { + message: '(#131030) Recipient phone number not in allowed list', + type: 'OAuthException', + code: 131030, + error_data: { + messaging_product: 'whatsapp', + details: 'Recipient phone number not in allowed list: Add recipient phone number to recipient list.', + }, + fbtrace_id: TRACE_ID, + }, +}; + +/** A reply that echoes the recipient, which Meta's docs do not rule out. */ +const ECHOING_REPLY = { + error: { + message: `(#131030) Recipient ${PHONE} is not allowed`, + type: 'OAuthException', + code: 131030, + error_data: { messaging_product: 'whatsapp', details: `Cannot send to +${PHONE} or ${BSUID}` }, + fbtrace_id: TRACE_ID, + }, +}; + +type Deployment = 'local' | 'development' | 'staging' | 'production'; + +function setup(handler: Handler, deploymentType: Deployment = 'production') { + const net = fakeFetch(handler); + const log = capturingLogger(); + const reports: Array<{ error: unknown; errorType: string; context?: Record }> = []; + const service = new MetaApiServiceReal({ + apiUrl: API_URL, + accessToken: new Secret(TOKEN), + deploymentType, + logger: log.logger, + fetch: net.fetch, + reportError: (error, report) => reports.push({ error, ...report }), + }); + return { service, log, reports, ...net }; +} + +async function thrown(promise: Promise): Promise { + try { + await promise; + } catch (error) { + return error; + } + throw new Error('expected an error, but the call succeeded'); +} + +const ok = () => jsonResponse(200, { messages: [{ id: 'wamid.X' }] }); + +describe('what is sent', () => { + it('sends a phone number as `to`, with no `recipient`', async () => { + const { service, calls } = setup(ok); + await service.sendMessage(PHONE, ['hello']); + expect(calls[0]!.json).toEqual({ messaging_product: 'whatsapp', type: 'text', text: { body: 'hello' }, to: PHONE }); + }); + + it('sends a BSUID as `recipient`, with no `to`', async () => { + const { service, calls } = setup(ok); + await service.sendMessage(BSUID, ['hello']); + expect(calls[0]!.json).toEqual({ + messaging_product: 'whatsapp', + type: 'text', + text: { body: 'hello' }, + recipient_type: 'individual', + recipient: BSUID, + }); + }); + + it('treats only digits as a phone number', async () => { + const { service, calls } = setup(ok); + for (const recipient of ['+201234567899', '20123 456', 'US.123', '١٢٣']) await service.sendMessage(recipient, ['x']); + expect(calls.map((call) => 'recipient' in (call.json as object))).toEqual([true, true, true, true]); + }); + + it('authenticates with the access token and posts to the configured URL', async () => { + const { service, calls } = setup(ok); + await service.sendMessage(PHONE, ['hello']); + expect(calls[0]!.url).toBe(API_URL); + expect(calls[0]!.method).toBe('POST'); + expect(calls[0]!.headers.authorization).toBe(`Bearer ${TOKEN}`); + expect(calls[0]!.redirect).toBe('manual'); + }); + + it('sends the parts one after another, in order, each as its own message', async () => { + const { service, calls } = setup(ok); + await service.sendMessage(BSUID, ['one', 'two', 'three']); + expect(calls.map((call) => (call.json as { text: { body: string } }).text.body)).toEqual(['one', 'two', 'three']); + }); + + it('stops at the first part Meta refuses, so later parts are not sent out of order', async () => { + let n = 0; + const { service, calls } = setup(() => (++n === 2 ? jsonResponse(400, META_REPLY) : ok())); + expect(await thrown(service.sendMessage(BSUID, ['one', 'two', 'three']))).toBeInstanceOf(MetaApiError); + expect(calls).toHaveLength(2); + }); + + it.each([ + ['no recipient', '', ['hello']], + ['no parts', BSUID, []], + ] as const)('sends nothing for %s', async (_name, recipient, parts) => { + const { service, calls } = setup(ok); + await service.sendMessage(recipient, [...parts]); + expect(calls).toHaveLength(0); + }); + + it('sends the typing indicator for the message, without naming the recipient', async () => { + const { service, calls } = setup(ok); + await service.sendTypingIndicator(BSUID, 'wamid.HBgLMTY1'); + expect(calls[0]!.json).toEqual({ + messaging_product: 'whatsapp', + status: 'read', + message_id: 'wamid.HBgLMTY1', + typing_indicator: { type: 'text' }, + }); + }); + + it.each([ + [BSUID, ''], + ['', 'wamid.X'], + ])('sends no typing indicator without both a recipient and a message id (%j, %j)', async (recipient, messageId) => { + const { service, calls } = setup(ok); + await service.sendTypingIndicator(recipient, messageId); + expect(calls).toHaveLength(0); + }); +}); + +describe('when Meta refuses', () => { + it.each(['local', 'staging', 'development', 'production'] as const)( + 'logs Meta\'s error fields in %s', + async (deployment) => { + const { service, log } = setup(() => jsonResponse(400, META_REPLY), deployment); + await thrown(service.sendMessage(BSUID, [MESSAGE_TEXT])); + expect(log.text()).toContain('code=131030'); + expect(log.text()).toContain("type='OAuthException'"); + expect(log.text()).toContain(`fbtrace_id='${TRACE_ID}'`); + expect(log.text()).toContain('Recipient phone number not in allowed list'); + }, + ); + + it.each(['local', 'staging', 'development', 'production'] as const)( + 'masks an error that echoes the recipient, in %s', + async (deployment) => { + const { service, log } = setup(() => jsonResponse(400, ECHOING_REPLY), deployment); + await thrown(service.sendMessage('US.99999999999999999999', [MESSAGE_TEXT])); + const metaLine = log.lines().find((line) => line.message.includes("Meta's reply"))!.message; + expect(metaLine).not.toContain(PHONE); + expect(metaLine).not.toContain(BSUID); + expect(metaLine).toContain('code=131030'); + expect(metaLine).toContain(''); + expect(metaLine).toContain(''); + }, + ); + + it.each(['staging', 'development', 'production'] as const)( + 'logs no phone, BSUID, message text, message id or token outside local (%s)', + async (deployment) => { + for (const recipient of [PHONE, BSUID]) { + for (const method of ['message', 'typing'] as const) { + const { service, log } = setup(() => jsonResponse(400, ECHOING_REPLY), deployment); + await thrown( + method === 'message' + ? service.sendMessage(recipient, [MESSAGE_TEXT]) + : service.sendTypingIndicator(recipient, 'wamid.HBgLMTY1MDM4Nzk0MzkVAgARGBI1RjQy'), + ); + const text = log.text(); + expect(text).not.toContain(PHONE); + expect(text).not.toContain(BSUID); + expect(text).not.toContain(MESSAGE_TEXT); + expect(text).not.toContain('wamid'); + expect(text).not.toContain(TOKEN); + } + } + }, + ); + + it.each(['staging', 'development', 'production'] as const)( + 'logs which keys a rejected request had, but not their values (%s)', + async (deployment) => { + const { service, log } = setup(() => jsonResponse(400, META_REPLY), deployment); + await thrown(service.sendMessage(PHONE, [MESSAGE_TEXT])); + expect(log.text()).toContain("Payload keys: ['messaging_product', 'text', 'to', 'type']"); + }, + ); + + it('logs the full request body in local, but never the token', async () => { + const { service, log } = setup(() => jsonResponse(400, META_REPLY), 'local'); + await thrown(service.sendMessage(PHONE, [MESSAGE_TEXT])); + expect(log.text()).toContain(MESSAGE_TEXT); + expect(log.text()).toContain(PHONE); + expect(log.text()).toContain('Bearer ***'); + expect(log.text()).not.toContain(TOKEN); + }); + + it.each(['staging', 'development'] as const)( + 'logs a masked body with the safe fields readable in %s', + async (deployment) => { + const { service, log } = setup(() => jsonResponse(400, META_REPLY), deployment); + await thrown(service.sendMessage(PHONE, [MESSAGE_TEXT])); + expect(log.text()).toContain('Body with values masked'); + expect(log.text()).toContain("'type': 'text'"); + expect(log.text()).toContain(' { + const { service, log } = setup(() => jsonResponse(400, META_REPLY), 'production'); + await thrown(service.sendMessage(PHONE, [MESSAGE_TEXT])); + expect(log.text()).not.toContain('Body'); + expect(log.text()).not.toContain('Headers'); + expect(log.text()).not.toContain('Bearer'); + }); + + it('logs request details only for a 400', async () => { + const { service, log } = setup(() => jsonResponse(403, META_REPLY), 'local'); + await thrown(service.sendMessage(BSUID, [MESSAGE_TEXT])); + expect(log.text()).toContain('code=131030'); + expect(log.text()).not.toContain(MESSAGE_TEXT); + expect(log.text()).not.toContain('Payload keys'); + }); + + it('logs only the size of a reply that is not the standard error object', async () => { + const { service, log } = setup(() => new Response(`upstream said ${PHONE} ${BSUID} `, { status: 400 }), 'production'); + await thrown(service.sendMessage(PHONE, [MESSAGE_TEXT])); + expect(log.text()).toContain('no standard error object'); + expect(log.text()).not.toContain(PHONE); + expect(log.text()).not.toContain(BSUID); + }); + + it('raises a MetaApiError carrying Meta\'s status', async () => { + const { service } = setup(() => jsonResponse(400, META_REPLY)); + const error = (await thrown(service.sendMessage(BSUID, ['x']))) as MetaApiError; + expect(error).toBeInstanceOf(MetaApiError); + expect(error.status).toBe(400); + expect(error.message).not.toContain(PHONE); + }); +}); + +describe('what the operator is told', () => { + it('reports a 5xx, with the request id, as Meta\'s fault', async () => { + const { service, reports } = setup(() => jsonResponse(503, {})); + await runWithRequestId('req-77', async () => { + await thrown(service.sendMessage(BSUID, ['x'])); + }); + expect(reports).toHaveLength(1); + expect(reports[0]).toMatchObject({ + errorType: 'meta_api_failure', + context: { status_code: 503, endpoint: 'send_message', request_id: 'req-77' }, + }); + }); + + it('names the endpoint for the typing indicator', async () => { + const { service, reports } = setup(() => jsonResponse(500, {})); + await thrown(service.sendTypingIndicator(BSUID, 'wamid.X')); + expect(reports[0]!.context).toMatchObject({ endpoint: 'send_typing_indicator' }); + }); + + it.each([400, 401, 403, 404, 429])('does not report a %s (our fault or the user\'s, not an outage)', async (status) => { + const { service, reports } = setup(() => jsonResponse(status, META_REPLY)); + await thrown(service.sendMessage(BSUID, ['x'])); + expect(reports).toEqual([]); + }); + + it('puts no phone number, BSUID or message text in what it reports', async () => { + const { service, reports } = setup(() => jsonResponse(500, ECHOING_REPLY)); + await thrown(service.sendMessage(PHONE, [MESSAGE_TEXT])); + const reported = JSON.stringify(reports[0]!.context); + for (const secret of [PHONE, BSUID, MESSAGE_TEXT, TOKEN]) expect(reported).not.toContain(secret); + }); +}); + +describe('network faults', () => { + it('raises a MetaApiError with no status, and does not log the URL or token', async () => { + const { service, log, reports } = setup(() => { + throw Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error(`connect ECONNRESET ${API_URL}`), { code: 'ECONNRESET' }) }); + }); + const error = (await thrown(service.sendMessage(BSUID, ['x']))) as MetaApiError; + expect(error).toBeInstanceOf(MetaApiError); + expect(error.status).toBeUndefined(); + expect(log.text()).toContain('TypeError/ECONNRESET'); + expect(log.text()).not.toContain('graph.facebook.com'); + expect(log.text()).not.toContain(TOKEN); + expect(reports).toEqual([]); + }); + + it('gives each request a deadline', async () => { + const { service, calls } = setup(ok); + await service.sendMessage(BSUID, ['x']); + expect(calls[0]!.signal).toBeInstanceOf(AbortSignal); + }); +}); + +describe('metaErrorSummary', () => { + const summary = (body: unknown) => metaErrorSummary(jsonResponse(400, body)); + + it('keeps the numeric and short text fields, masked', async () => { + expect(await summary(META_REPLY)).toBe( + `code=131030 type='OAuthException' fbtrace_id='${TRACE_ID}' message='(#131030) Recipient phone number not in allowed list' details='Recipient phone number not in allowed list: Add recipient phone number to recipient list.'`, + ); + }); + + it('leaves out fields that are missing or empty', async () => { + expect(await summary({ error: { code: 1 } })).toBe('code=1'); + }); + + it('does not take a boolean or a string for a number', async () => { + expect(await summary({ error: { code: true, error_subcode: '5', message: 'm' } })).toBe("message='m'"); + }); + + it('cuts long texts, counting characters not bytes', async () => { + const out = await summary({ error: { message: '\u{1F600}'.repeat(400) } }); + expect([...out.replace(/^message='|'$/g, '')].length).toBe(300); + }); + + it.each([[null], [[1, 2]], ['text'], [{ error: 'boom' }], [{ error: [1] }]])('reports only a size for %j', async (body) => { + expect(await summary(body)).toMatch(/^no standard error object \(\d+ bytes\)$/); + }); + + it('counts the size of a non-JSON reply in bytes', async () => { + expect(await metaErrorSummary(new Response('\u00e9\u00e9', { status: 500 }))).toBe('no standard error object (4 bytes)'); + }); +}); + +describe('MetaApiServiceMock', () => { + it('records what it was asked to send and sends nothing', async () => { + const log = capturingLogger(); + const mock = new MetaApiServiceMock({ logger: log.logger, delayMs: 0 }); + await mock.sendMessage(BSUID, ['one', 'two']); + await mock.sendTypingIndicator(BSUID, 'wamid.X'); + expect(mock.sent).toEqual([{ recipient: BSUID, messageParts: ['one', 'two'] }]); + }); +}); diff --git a/apps/whatsapp/tests/pythonRepr.test.ts b/apps/whatsapp/tests/pythonRepr.test.ts new file mode 100644 index 00000000..1c0e0f97 --- /dev/null +++ b/apps/whatsapp/tests/pythonRepr.test.ts @@ -0,0 +1,21 @@ +/** + * `pythonRepr` prints values the way Python's `repr()` does, because log lines and the Python tests rely on that shape + * (`code=131030 type='OAuthException'`, `['messaging_product', 'text']`). The expected text is what `repr()` returned + * (`tests/fixtures/pythonOracle.ts`). + */ +import { describe, expect, it } from 'vitest'; +import { pythonList, pythonRepr } from '../src/utils/pythonRepr'; +import { REPR_CASES } from './fixtures/pythonOracle'; + +describe('pythonRepr', () => { + it.each(REPR_CASES)('%j', (value, python) => { + expect(pythonRepr(value)).toBe(python); + }); +}); + +describe('pythonList', () => { + it('prints a list of strings like Python', () => { + expect(pythonList(['messaging_product', 'text'])).toBe("['messaging_product', 'text']"); + expect(pythonList([])).toBe('[]'); + }); +}); diff --git a/codev/projects/358-whatsapp-typescript/358-phase_3-iter1-claude.txt b/codev/projects/358-whatsapp-typescript/358-phase_3-iter1-claude.txt new file mode 100644 index 00000000..09c89595 --- /dev/null +++ b/codev/projects/358-whatsapp-typescript/358-phase_3-iter1-claude.txt @@ -0,0 +1,28 @@ +NOTE: This is an agent self-review written by the implementing agent. It is NOT the output of a `consult` run; no external model was consulted (owner instruction: "don't consult; just self review"). + +Phase 3 (service clients): apps/auth token exchange, Meta Graph API sender, apps/api chat client. + +VERIFIED (by running it) +- `pnpm --filter ansari-whatsapp typecheck` exit 0, `lint` exit 0, `test` exit 0: 559 tests pass (536 before the stream-reader tests were added). +- Mutation controls, one rule broken at a time, tests run, file restored and compared to the original: + - Run 1: 23 mutations. 21 caught, 1 not caught, 1 skipped because my search pattern did not match. + - Not caught: a `\r` at the end of a stream chunk being treated as a whole line end. Fixed by adding tests/http.test.ts (line reader, idle timer, error describer, slash trimming). + - Skipped: "redirects followed" for the apps/auth client. Re-run with a corrected pattern. + - Run 2: 8 mutations (redirect following in all three clients, the `\r` case, a held final `\r`, a dropped last line, no reader cancel on early exit, an idle timer that ignores reset). All 8 caught. + - After each run the final test count was unchanged and `git status` showed only intended files. +- `pythonRepr` was compared with real Python `repr` through the oracle (REPR_CASES). + +DIFFERENCES FROM PYTHON (deliberate or unavoidable) +- fetch vs httpx: fetch has no per-phase timeouts, so each call has one overall deadline (5 s auth, 20 s Meta); chat streams use an idle timer that restarts on every chunk (60 s). +- fetch follows redirects unless told otherwise, so every call sets `redirect: 'manual'`; a redirect counts as a failure, as httpx's default does. +- One `MetaApiError` (with optional `status`) replaces httpx's two exception types. +- The mock apps/api client has no random latency or injected errors; the mock token is sha256-based, not a UUID. +- `readLines` splits only on \n, \r\n and \r (the SSE rule). Python's `splitlines` also splits on U+2028 and similar; this is intentional and tested. +- The "401 -> forget token, re-exchange once, retry once" flow is not in these clients. They raise `ApiUnauthorizedError`; the conversation manager (phase 4) does the retry. +- Errors are sent to Sentry through an injected `ErrorReporter`; the real Sentry sender is wired in phase 5. Until then the default is a no-op. + +NOT VERIFIED +- No real network call was made. The real apps/auth, apps/api and Meta contracts are checked only through fakes written from the Python code and the Meta docs. +- Behaviour of the real fetch implementation on a mid-stream connection reset (only simulated). + +VERDICT: COMMENT From ebf5901bd4d750ab27b8c77d523bfc7dded819f0 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 22:02:11 +0200 Subject: [PATCH 028/435] chore(porch): 358 implement build-complete --- codev/projects/358-whatsapp-typescript/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index ccb2e11c..945f4196 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T18:32:16.131Z' +updated_at: '2026-11-10T20:02:10.747Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' From 7397d9fa5ff4645a8dacb538f6f482af6774d090 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 22:02:57 +0200 Subject: [PATCH 029/435] chore(porch): 358 acknowledge context refresh --- codev/projects/358-whatsapp-typescript/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 945f4196..bace0e92 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -40,7 +40,7 @@ iteration: 1 build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T20:02:10.747Z' +updated_at: '2026-11-10T20:02:57.127Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -53,3 +53,4 @@ context_refreshes: acknowledged_at: '2026-11-10T17:48:30.123Z' - boundary: plan-phase:phase_3 at: '2026-11-10T18:32:16.131Z' + acknowledged_at: '2026-11-10T20:02:57.123Z' From 6ea41fa83c795e9622f64fc3c1d41e8684f1492e Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 22:03:04 +0200 Subject: [PATCH 030/435] =?UTF-8?q?chore(porch):=20358=20advance=20plan=20?= =?UTF-8?q?phase=20=E2=86=92=20phase=5F4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codev/projects/358-whatsapp-typescript/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index bace0e92..6d4bf905 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -11,10 +11,10 @@ plan_phases: status: complete - id: phase_3 title: 'Service clients: apps/auth exchange, apps/api streaming, Meta API' - status: in_progress + status: complete - id: phase_4 title: Conversation manager - status: pending + status: in_progress - id: phase_5 title: 'HTTP app: webhook verification, signature check, immediate 200' status: pending @@ -24,7 +24,7 @@ plan_phases: - id: phase_7 title: Staging redeploy, smoke test and legacy rollback note status: pending -current_plan_phase: phase_3 +current_plan_phase: phase_4 gates: spec-approval: status: approved @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T20:02:57.127Z' +updated_at: '2026-11-10T20:03:04.358Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -54,3 +54,5 @@ context_refreshes: - boundary: plan-phase:phase_3 at: '2026-11-10T18:32:16.131Z' acknowledged_at: '2026-11-10T20:02:57.123Z' + - boundary: plan-phase:phase_4 + at: '2026-11-10T20:03:04.356Z' From 9a262b46b6fdd4e81aa7b78b1f2e605d72f4d743 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 22:09:01 +0200 Subject: [PATCH 031/435] chore(porch): 358 acknowledge context refresh --- codev/projects/358-whatsapp-typescript/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 6d4bf905..1116e723 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -40,7 +40,7 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T20:03:04.358Z' +updated_at: '2026-11-10T20:09:01.447Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -56,3 +56,4 @@ context_refreshes: acknowledged_at: '2026-11-10T20:02:57.123Z' - boundary: plan-phase:phase_4 at: '2026-11-10T20:03:04.356Z' + acknowledged_at: '2026-11-10T20:09:01.441Z' From 9c919df91db0edec8b19517a1b1d794fc755d3c5 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 22:46:58 +0200 Subject: [PATCH 032/435] [Spec 358][Phase: phase_4] feat: conversation manager (triage, sign-in, thread lifecycle, typing, notices) --- apps/whatsapp/src/conversationManager.ts | 527 ++++++++ apps/whatsapp/src/utils/pythonText.ts | 17 + .../tests/conversationManager.test.ts | 1197 +++++++++++++++++ .../tests/fixtures/generate_python_oracle.py | 85 ++ apps/whatsapp/tests/fixtures/pythonOracle.ts | 281 ++++ apps/whatsapp/tests/pythonText.test.ts | 32 + .../358-phase_4-iter1-claude.txt | 35 + 7 files changed, 2174 insertions(+) create mode 100644 apps/whatsapp/src/conversationManager.ts create mode 100644 apps/whatsapp/src/utils/pythonText.ts create mode 100644 apps/whatsapp/tests/conversationManager.test.ts create mode 100644 apps/whatsapp/tests/pythonText.test.ts create mode 100644 codev/projects/358-whatsapp-typescript/358-phase_4-iter1-claude.txt diff --git a/apps/whatsapp/src/conversationManager.ts b/apps/whatsapp/src/conversationManager.ts new file mode 100644 index 00000000..148a5361 --- /dev/null +++ b/apps/whatsapp/src/conversationManager.ts @@ -0,0 +1,527 @@ +/** + * The conversation manager: what happens between "Meta delivered a message" and "the user has an answer". + * + * Python counterpart: `services/whatsapp_conversation_manager.py`, plus the checks that lived in the webhook route of + * `app/main.py` (maintenance mode, the staging `!d ` filter, the message-age check, the unsupported-type check). + * + * The flow for a text message: + * + * triage() -> sign in (apps/auth) -> typing indicator -> find or start the user's thread (apps/api) + * -> ask apps/api -> format for WhatsApp -> split -> send (Meta) + * + * Every refusal along the way is told to the user in plain words, and the ones an operator must act on are also reported + * (see `ErrorReporter`). The notice texts are copied from Python word for word, including the odd ".." in the thread-deletion one, + * because a user may report one by its wording. + * + * Differences from Python: + * - One `ConversationManager` serves every message. Python built a new manager object per webhook and kept the user's token + * and typing task on it; here that per-message state lives in a small `Turn` object that is passed along. + * - `triage()` is a plain function that answers "what should happen to this message?". The HTTP layer (phase 5) turns the + * answer into a status code and then calls `dispatch()`. Python mixed the checks and the status codes in one route. + * - Everything the manager needs (settings, the three clients, the clock) is passed in, not looked up in globals. + * - Two Python branches are gone because they cannot happen here: the notice for a thread-creation reply without an id (the + * apps/api client already refuses one) and the notice for an answer that formatted to nothing (the formatter never turns + * non-empty text into empty text). + * - A `last_message_time` must carry a time-zone marker (`Z` or `+hh:mm`). JavaScript would read a bare timestamp as local + * time without complaint; Python raised an error, so this does too. + * - A reply that is only whitespace splits into nothing; the user then gets the "couldn't process" notice (spec decision). + */ +import type { Env } from './config'; +import type { ErrorReporter } from './errorReporter'; +import { noopErrorReporter } from './errorReporter'; +import { + ApiUnauthorizedError, + AuthBadRequestError, + AuthKeyRejectedError, + AuthRateLimitedError, + AuthTokenError, + AuthUserBannedError, + MessageProcessingError, + ThreadCreationError, + ThreadDeletionError, + ThreadInfoError, +} from './errors'; +import { formatForWhatsApp } from './formatting/whatsappMessageFormatter'; +import { splitMessage } from './formatting/messageSplitter'; +import { getRequestId, type Logger } from './logger'; +import type { AnsariClient } from './services/ansariClient'; +import type { AuthClient } from './services/authClient'; +import type { MetaApiService } from './services/metaApiService'; +import { pythonSplitWords } from './utils/pythonText'; +import { calculateTimePassed, getRetentionTimeSeconds, isMessageTooOld } from './utils/time'; +import type { ParsedWebhook } from './webhook/parseWebhook'; + +/** A message from a user, as the webhook parser hands it over. */ +export type IncomingMessage = Extract; + +/** The settings the manager reads. `Pick` takes just these fields of the full `Env` type. */ +export type ManagerConfig = Pick< + Env, + 'WA_MAINTENANCE_MODE' | 'DEPLOYMENT_TYPE' | 'WHATSAPP_CHAT_RETENTION_HOURS' | 'WHATSAPP_MESSAGE_AGE_THRESHOLD_SECONDS' +>; + +/** + * What should happen to an incoming message. The HTTP layer answers Meta according to this (Python's status codes: + * `maintenance` 503, `dev_filter` 202, `too_old` 422, `unsupported` 415, `text` 200) and then calls `dispatch`. + */ +export type TriageAction = 'maintenance' | 'dev_filter' | 'too_old' | 'unsupported' | 'text'; + +export const SIGN_IN_FAILED_NOTICE = "Sorry, we couldn't sign you in. Please try again later."; +export const BANNED_NOTICE = "Sorry, we can't answer messages from this account."; +export const MAINTENANCE_NOTICE = + 'Ansari for WhatsApp is down for maintenance, please try again later or visit our website at https://ansari.chat.'; +const PROCESSING_FAILED_NOTICE = 'An error occurred while processing your message. Please try again later.'; +const UNEXPECTED_FAILURE_NOTICE = 'An unexpected error occurred while processing your message. Please try again later.'; +const EMPTY_ANSWER_NOTICE = "Sorry, we couldn't process your message. Please try again later."; +const THREAD_INFO_FAILED_NOTICE = "Sorry, we're having trouble accessing your chat history. Please try again later."; +const THREAD_DELETE_FAILED_NOTICE = + 'An unexpected error occurred while starting a new chat session.. Please try again later.'; +const THREAD_CREATE_FAILED_NOTICE = + 'An unexpected error occurred while creating a new chat session. Please try again later.'; + +/** "...in about 5 minutes." The wait is rounded up to whole minutes and is never less than one. */ +export function rateLimitedNotice(retryAfterSeconds: number): string { + const minutes = Math.max(1, Math.ceil(retryAfterSeconds / 60)); + return `You are sending messages too quickly. Please try again in about ${minutes} ${minutes === 1 ? 'minute' : 'minutes'}.`; +} + +/** The text of a "can't process this type" notice for a message type like `image` (nothing is sent for an empty type). */ +export function unsupportedTypeNotice(messageType: string): string { + const plural = messageType.endsWith('s') ? messageType : `${messageType}s`; + const named = plural.replaceAll('unsupporteds', 'this media type'); + return `Sorry, I can't process ${named} yet. Please send me a text message.`; +} + +/** `Z` or `+hh:mm`, as apps/api sends it. Anything else is refused rather than guessed (see the file header). */ +const TIMESTAMP_WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/; + +function parseLastMessageTime(text: string): Date { + const date = TIMESTAMP_WITH_OFFSET.test(text) ? new Date(text) : new Date(Number.NaN); + if (Number.isNaN(date.getTime())) throw new TypeError('last message time is not an ISO timestamp with a time zone'); + return date; +} + +/** The text of a text message: `{ body: '...' }`. Anything else is a fault in what Meta sent. */ +function incomingText(message: IncomingMessage): string { + const body = message.messageBody; + const text = typeof body === 'object' && body !== null ? (body as { body?: unknown }).body : undefined; + if (typeof text !== 'string') throw new TypeError('text message has no body'); + return text; +} + +/** Wait `ms`, or until `signal` aborts. Resolves `true` after the full wait and `false` if it was cut short. */ +function delay(ms: number, signal: AbortSignal): Promise { + if (signal.aborted) return Promise.resolve(false); + return new Promise((resolve) => { + const finish = (completed: boolean) => { + clearTimeout(timer); + signal.removeEventListener('abort', onAbort); + resolve(completed); + }; + const onAbort = () => finish(false); + const timer = setTimeout(() => finish(true), ms); + signal.addEventListener('abort', onAbort, { once: true }); + }); +} + +/** What the manager keeps while it handles one message. */ +interface Turn { + message: IncomingMessage; + /** Who replies go to: the sender's phone when `META_REPLY_BY_PHONE` put it there, else the BSUID. */ + replyTo: string; + /** The user's JWT; empty until sign-in succeeds. */ + token: string; + typing: TypingIndicator | undefined; +} + +export interface ConversationManagerOptions { + config: ManagerConfig; + ansariClient: AnsariClient; + authClient: AuthClient; + metaApi: MetaApiService; + logger: Logger; + reportError?: ErrorReporter; + /** The clock. Only tests pass it. */ + now?: () => Date; + /** Pause between typing indicators (Python: 26 s; WhatsApp shows one for about 25 s). Only tests change it. */ + typingIntervalMs?: number; + /** Stop sending typing indicators after this long (Python: 5 minutes). Only tests change it. */ + typingMaxMs?: number; +} + +/** + * Keeps "typing..." showing while the answer is prepared. WhatsApp hides the indicator after about 25 seconds, so a new one + * is sent every 26 s, for at most 5 minutes in all, until `stop()` is called. + */ +class TypingIndicator { + readonly #abort = new AbortController(); + readonly #send: () => Promise; + readonly #logger: Logger; + readonly #now: () => Date; + readonly #intervalMs: number; + readonly #maxMs: number; + #startedAt = 0; + + constructor(options: { send: () => Promise; logger: Logger; now: () => Date; intervalMs: number; maxMs: number }) { + this.#send = options.send; + this.#logger = options.logger; + this.#now = options.now; + this.#intervalMs = options.intervalMs; + this.#maxMs = options.maxMs; + } + + /** Send the first indicator now, then keep sending in the background. Returns once the first one is sent. */ + async start(): Promise { + this.#startedAt = this.#now().getTime(); + await this.#send(); + void this.#loop(); + } + + /** Stop for good. Safe to call more than once. */ + stop(): void { + this.#abort.abort(); + } + + /** Never throws: it runs un-awaited, so a failure here would otherwise go unseen. */ + async #loop(): Promise { + try { + for (;;) { + this.#logger.debug('Currently in typing indicator loop (i.e., Ansari is taking longer than usual to respond)'); + if (!(await delay(this.#intervalMs, this.#abort.signal))) { + this.#logger.debug('Typing indicator task cancelled'); + return; + } + const elapsedMs = this.#now().getTime() - this.#startedAt; + if (elapsedMs > this.#maxMs) { + this.#logger.warn(`Typing indicator loop exceeded maximum duration of ${this.#maxMs / 1000}s. Stopping.`); + return; + } + this.#logger.debug(`Sending follow-up typing indicator after ${(elapsedMs / 1000).toFixed(1)}s`); + await this.#send(); + } + } catch (error) { + this.#logger.error('Error in typing indicator loop', error); + } + } +} + +export class ConversationManager { + readonly #options: ConversationManagerOptions; + readonly #now: () => Date; + + constructor(options: ConversationManagerOptions) { + this.#options = options; + this.#now = options.now ?? (() => new Date()); + } + + /** + * Decide what should happen to a message, without doing it. The order matters and is Python's: the service being down + * beats everything; then the staging filter; then age; then the message type. + */ + triage(message: IncomingMessage): TriageAction { + const { config, logger } = this.#options; + + if (config.WA_MAINTENANCE_MODE) return 'maintenance'; + + // While a developer tests locally on the same WhatsApp test number, the always-running staging server must ignore + // what is meant for their laptop: they prefix such messages with "!d " (e.g. "!d what is ansari?"). A temporary + // workaround until staging has a number of its own. Only a text body can carry the prefix (an unsupported type arrives + // as a list, not an object). + if (config.DEPLOYMENT_TYPE === 'staging') { + const body = message.messageBody; + const text = typeof body === 'object' && body !== null ? (body as { body?: unknown }).body : undefined; + if (typeof text === 'string' && text.startsWith('!d ')) { + logger.debug("Incoming message is meant for a dev who's testing locally now, so will not process it in staging..."); + return 'dev_filter'; + } + } + + // Meta redelivers old webhooks after an outage; answering a day-old question is worse than ignoring it + if (isMessageTooOld(message.messageUnixTime, config.WHATSAPP_MESSAGE_AGE_THRESHOLD_SECONDS, { now: this.#now(), logger })) { + return 'too_old'; + } + + return message.messageType === 'text' ? 'text' : 'unsupported'; + } + + /** + * Carry out what `triage` decided. Meant to run after Meta has been answered: signing in and asking apps/api can take + * long enough that Meta would redeliver the message, and nothing dedupes a redelivery. It does not throw: every failure + * inside is logged and, where it matters, reported and told to the user. + */ + async dispatch(message: IncomingMessage, action: TriageAction): Promise { + const turn: Turn = { message, replyTo: message.senderPhone || message.bsuid, token: '', typing: undefined }; + switch (action) { + case 'maintenance': + await this.notify(turn.replyTo, MAINTENANCE_NOTICE); + return; + case 'unsupported': + await this.#handleUnsupported(turn); + return; + case 'text': + await this.#signInAndHandleText(turn); + return; + case 'dev_filter': + case 'too_old': + return; // ignored on purpose; Meta was answered with the reason + } + } + + /** + * Send a text to a user: split it to fit WhatsApp's limit and send the parts in order. Never throws: a failure is logged + * (Meta reports it too), because the user has no one left to tell. + */ + async notify(recipient: string, text: string): Promise { + await this.#deliver(recipient, splitMessage(text)); + } + + async #deliver(recipient: string, parts: string[]): Promise { + const { logger, metaApi } = this.#options; + if (!recipient) { + logger.error('Cannot send WhatsApp message: No recipient provided'); + return; + } + try { + await metaApi.sendMessage(recipient, parts); + } catch (error) { + logger.error('Error sending WhatsApp message', error); + } + } + + #report(error: unknown, errorType: string): void { + // Only the request id travels with the event, never a BSUID, phone number, token or any message text + (this.#options.reportError ?? noopErrorReporter)(error, { errorType, context: { request_id: getRequestId() } }); + } + + // ---------- sign-in ---------- + + /** + * Exchange the sender's BSUID for a JWT with apps/auth, and keep it on the turn. apps/auth creates the account on first + * use, so there is no separate sign-up. The same BSUID is always the same account; a new BSUID is a new user. + * + * Returns `null` on success, otherwise the notice to show the user. Each refusal means something different, so each is + * handled differently: our own key being refused or our request being malformed are bugs for an operator (reported, with + * their own tags); a banned or rate-limited user is expected (only logged); anything else is an outage (reported). + */ + async #authenticate(turn: Turn): Promise { + const { authClient, logger } = this.#options; + if (!turn.message.bsuid) { + logger.error('Cannot authenticate user: bsuid is not set'); + return SIGN_IN_FAILED_NOTICE; + } + + try { + turn.token = await authClient.getToken(turn.message.bsuid); + } catch (error) { + if (error instanceof AuthUserBannedError) return BANNED_NOTICE; + if (error instanceof AuthRateLimitedError) return rateLimitedNotice(error.retryAfter); + if (error instanceof AuthKeyRejectedError) { + this.#report(error, 'auth_key_rejected'); + } else if (error instanceof AuthBadRequestError) { + this.#report(error, 'auth_bad_request'); + } else if (error instanceof AuthTokenError) { + logger.error('Failed to get a token for the user', error); + this.#report(error, 'auth_token_failure'); + } else { + logger.error(`Unexpected error getting a token for the user: ${error instanceof Error ? error.name : typeof error}`); + this.#report(error, 'auth_token_failure'); + } + return SIGN_IN_FAILED_NOTICE; + } + + logger.debug('Authenticated whatsapp user'); + return null; + } + + async #signInAndHandleText(turn: Turn): Promise { + const notice = await this.#authenticate(turn); + if (notice !== null) { + await this.notify(turn.replyTo, notice); + return; + } + + // Started only for a signed-in user, because #handleText is what stops it + await this.#startTyping(turn); + await this.#handleText(turn); + } + + // ---------- typing indicator ---------- + + async #startTyping(turn: Turn): Promise { + const { logger, metaApi } = this.#options; + const { bsuid, messageId } = turn.message; + if (!bsuid || !messageId) { + logger.error('Cannot start typing indicator loop: missing bsuid or message_id'); + return; + } + turn.typing = new TypingIndicator({ + send: async () => { + try { + await metaApi.sendTypingIndicator(bsuid, messageId); + } catch (error) { + logger.error('Error sending typing indicator', error); + } + }, + logger, + now: this.#now, + intervalMs: this.#options.typingIntervalMs ?? 26_000, + maxMs: this.#options.typingMaxMs ?? 300_000, + }); + await turn.typing.start(); + } + + // ---------- the user's thread ---------- + + /** + * The id of the user's one current thread, replacing it when it has expired. Each user has exactly one thread. When the + * last message is older than the retention time (3 hours by default) the old thread and its messages are deleted and a + * new thread starts. Returns `null` when something failed and the user has already been told. + * + * Known corner case, deliberately NOT handled (spec 321): if a user's first message after the expiry is followed by a + * second one before the first has finished deleting and creating, both can see the expired thread and each create a new + * one, leaving the user with two. A per-user lock was considered and rejected: + * - two messages back to back from one user are unlikely, and delete-and-create takes well under a second; + * - the damage is small: the newest thread is always the one used, so replies still work; + * - it is easy to clean up: a manual sweep deletes all but the newest `whatsapp` thread of each user. + * A lock around this step would also not stop two answers streaming into one thread at once, which is accepted too. + */ + async #resolveThread(turn: Turn, firstMessage: string): Promise { + const { ansariClient, config, logger } = this.#options; + + let info; + try { + info = await ansariClient.getLastThreadInfo(turn.token); + } catch (error) { + if (!(error instanceof ThreadInfoError)) throw error; + logger.error('Failed to get thread info', error); + this.#report(error, 'thread_info_failure'); + await this.notify(turn.replyTo, THREAD_INFO_FAILED_NOTICE); + return null; + } + + const lastMessageTime = info.lastMessageTime === null ? null : parseLastMessageTime(info.lastMessageTime); + const passed = calculateTimePassed(lastMessageTime, this.#now()); + logger.debug(`Time passed since user's last whatsapp message: ${passed.forLogging}`); + + if (info.threadId !== null && passed.seconds <= getRetentionTimeSeconds(config.WHATSAPP_CHAT_RETENTION_HOURS)) { + return info.threadId; + } + + if (info.threadId !== null) { + try { + await ansariClient.deleteThread(turn.token, info.threadId); + logger.info("Deleted the user's expired thread"); + } catch (error) { + if (!(error instanceof ThreadDeletionError)) throw error; + // Keep one thread per user: do not start a second one next to an expired thread we could not delete + logger.error('Failed to delete the expired thread', error); + this.#report(error, 'thread_deletion_failure'); + await this.notify(turn.replyTo, THREAD_DELETE_FAILED_NOTICE); + return null; + } + } + + try { + // The thread's title is the first six words of the message + const created = await ansariClient.createThread(turn.token, pythonSplitWords(firstMessage).slice(0, 6).join(' ')); + logger.info('Created a new thread for the whatsapp user'); + return created.threadId; + } catch (error) { + if (!(error instanceof ThreadCreationError)) throw error; + logger.error('Failed to create thread', error); + this.#report(error, 'thread_creation_failure'); + await this.notify(turn.replyTo, THREAD_CREATE_FAILED_NOTICE); + return null; + } + } + + // ---------- answering ---------- + + /** + * Ask apps/api for the answer. Two attempts at most: if apps/api refuses the token (a session can end after its token was + * signed, e.g. a ban or a deletion), the cached token is dropped, apps/auth is asked once more, and the message is tried + * once more. A second refusal, or a refused exchange, ends it. Returns `null` when the user has already been told. + */ + async #answer(turn: Turn, text: string, attempt: 1 | 2): Promise { + const { ansariClient, authClient, logger } = this.#options; + try { + const threadId = await this.#resolveThread(turn, text); + if (threadId === null) return null; + return await ansariClient.processMessage(turn.token, threadId, text); + } catch (error) { + if (error instanceof ApiUnauthorizedError) { + if (attempt === 1) { + authClient.forget(turn.message.bsuid); + const notice = await this.#authenticate(turn); + if (notice === null) return this.#answer(turn, text, 2); + // A user who sent one message must not be told they are sending too quickly, which is what a 429 on this + // second exchange would otherwise say + await this.notify(turn.replyTo, notice === BANNED_NOTICE ? BANNED_NOTICE : SIGN_IN_FAILED_NOTICE); + } else { + logger.error('apps/api refused a freshly exchanged token; giving up'); + this.#report(error, 'api_unauthorized_after_reexchange'); + await this.notify(turn.replyTo, PROCESSING_FAILED_NOTICE); + } + return null; + } + if (error instanceof MessageProcessingError) { + logger.error('Failed to process message', error); + this.#report(error, 'message_processing_failure'); + await this.notify(turn.replyTo, PROCESSING_FAILED_NOTICE); + return null; + } + throw error; + } + } + + /** Process an incoming text message and send the answer to the sender. */ + async #handleText(turn: Turn): Promise { + const { logger } = this.#options; + if (!turn.message.bsuid || !turn.token) { + logger.error('Cannot process text message: the user is not authenticated'); + return; + } + + try { + const text = incomingText(turn.message); + logger.debug(`Whatsapp user sent a text message (${[...text].length} characters)`); + + const answer = await this.#answer(turn, text, 1); + if (answer === null) return; + turn.typing?.stop(); + + if (answer === '') { + logger.warn('Received an empty response from the backend'); + await this.notify(turn.replyTo, EMPTY_ANSWER_NOTICE); + return; + } + + // Convert conventional markdown syntax to WhatsApp's markdown syntax + logger.debug(`Response received for markdown conversion (${[...answer].length} characters)`); + // An answer of only whitespace has nothing to send (WhatsApp rejects a blank message): same notice as an empty one + const parts = splitMessage(formatForWhatsApp(answer)); + if (parts.length === 0) { + logger.warn('Response had no text to send after splitting'); + await this.notify(turn.replyTo, EMPTY_ANSWER_NOTICE); + return; + } + await this.#deliver(turn.replyTo, parts); + } catch (error) { + logger.error('Unexpected error processing text message', error); + await this.notify(turn.replyTo, UNEXPECTED_FAILURE_NOTICE); + } finally { + // Every way out of here ends the typing indicator, so none is left running + turn.typing?.stop(); + } + } + + /** Tell the sender that this kind of message (image, audio, ...) is not understood yet. Needs no sign-in. */ + async #handleUnsupported(turn: Turn): Promise { + const { messageType, bsuid } = turn.message; + if (!bsuid || !messageType) { + this.#options.logger.error('Cannot process unsupported message: missing bsuid or incoming_msg_type'); + return; + } + await this.notify(turn.replyTo, unsupportedTypeNotice(messageType)); + } +} diff --git a/apps/whatsapp/src/utils/pythonText.ts b/apps/whatsapp/src/utils/pythonText.ts new file mode 100644 index 00000000..d84ab200 --- /dev/null +++ b/apps/whatsapp/src/utils/pythonText.ts @@ -0,0 +1,17 @@ +/** + * Split text into words the way Python's `str.split()` does. + * + * Why not `text.split(/\s+/)`: JavaScript's `\s` and Python's whitespace are different sets of characters. JavaScript counts the + * byte-order mark U+FEFF as whitespace, Python does not; Python counts U+001C to U+001F (the file, group, record and unit + * separators) and U+0085 (next line) as whitespace, JavaScript does not. A thread title built from the first words of a message + * must be cut at the same places as before, so the set is spelled out and `tests/pythonText.test.ts` checks it against the + * full list of code points Python's `str.isspace()` accepts (`tests/fixtures/pythonOracle.ts`, `PYTHON_WHITESPACE`). + */ + +/** Tab, line feed, vertical tab, form feed, carriage return (U+0009 to U+000D), then U+001C to U+0020 (including space). */ +const PYTHON_WHITESPACE = /[\t-\r\u001c-\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/u; + +/** The words of `text`, with no empty strings (Python: `text.split()`). Leading and trailing whitespace is ignored. */ +export function pythonSplitWords(text: string): string[] { + return text.split(PYTHON_WHITESPACE).filter((word) => word !== ''); +} diff --git a/apps/whatsapp/tests/conversationManager.test.ts b/apps/whatsapp/tests/conversationManager.test.ts new file mode 100644 index 00000000..c4b098f9 --- /dev/null +++ b/apps/whatsapp/tests/conversationManager.test.ts @@ -0,0 +1,1197 @@ +/** + * The conversation manager. + * + * Python tests ported: + * - `test_thread_lifecycle.py`: one thread per user, three-hour expiry, the `Z` timestamp apps/api sends, a failed delete + * never leaves two threads, each thread failure is reported under its own name. + * - `test_auth_statuses.py` (last half): what the user is told for each sign-in refusal, what the operator is told, one + * re-exchange after an apps/api 401 and never a third. + * - `test_environment_behaviour.py`: maintenance mode, the staging `!d ` filter, an unsupported type in staging. + * - `test_bsuid_auth_flow.py`: who a reply is addressed to, and that the phone never reaches apps/auth or apps/api. + * - `test_whatsapp_service.py`: a message with no timestamp or an old one. + * + * The Python tests built a manager and reached into its private methods; here the manager is driven through its two public + * steps (`triage` and `dispatch`), which is also what the HTTP layer will do. + * + * Expected notice texts come from `tests/fixtures/pythonOracle.ts`, which ran the Python manager. + */ +import { describe, expect, it } from 'vitest'; +import { + BANNED_NOTICE, + ConversationManager, + MAINTENANCE_NOTICE, + rateLimitedNotice, + SIGN_IN_FAILED_NOTICE, + unsupportedTypeNotice, + type IncomingMessage, + type ManagerConfig, +} from '../src/conversationManager'; +import type { ErrorReport } from '../src/errorReporter'; +import { + ApiUnauthorizedError, + AuthBadRequestError, + AuthKeyRejectedError, + AuthRateLimitedError, + AuthTokenError, + AuthUserBannedError, + MessageProcessingError, + MetaApiError, + ThreadCreationError, + ThreadDeletionError, + ThreadInfoError, +} from '../src/errors'; +import { runWithRequestId } from '../src/logger'; +import { AnsariClientMock, type AnsariClient, type ThreadInfo } from '../src/services/ansariClient'; +import { AuthClientMock, type AuthClient } from '../src/services/authClient'; +import { MetaApiServiceMock, type MetaApiService } from '../src/services/metaApiService'; +import { + FIXED_NOW_UNIX, + RATE_LIMITED_NOTICE_CASES, + THREAD_TITLE_CASES, + UNSUPPORTED_NOTICE_CASES, +} from './fixtures/pythonOracle'; +import { capturingLogger } from './helpers/network'; + +const BSUID = 'US.13491208655302741918'; +const OTHER_BSUID = 'US.99999999999999999999'; +const PHONE = '201234567899'; +const NOW = new Date(FIXED_NOW_UNIX * 1000); +const HOUR = 3600; + +const baseConfig: ManagerConfig = { + WA_MAINTENANCE_MODE: false, + DEPLOYMENT_TYPE: 'local', + WHATSAPP_CHAT_RETENTION_HOURS: 3, + WHATSAPP_MESSAGE_AGE_THRESHOLD_SECONDS: 86400, +}; + +function textMessage(overrides: Partial = {}, text = 'hello'): IncomingMessage { + return { + kind: 'message', + bsuid: BSUID, + messageType: 'text', + messageBody: { body: text }, + messageId: 'wamid.TEST', + messageUnixTime: FIXED_NOW_UNIX, + senderPhone: null, + ...overrides, + }; +} + +/** A manager wired to the in-memory mocks, with every error report and every sent message recorded. */ +function setup( + options: { + config?: Partial; + ansariClient?: AnsariClient; + authClient?: AuthClient; + metaApi?: MetaApiService; + clock?: { now: Date }; + typingIntervalMs?: number; + typingMaxMs?: number; + } = {}, +) { + const log = capturingLogger(); + const clock = options.clock ?? { now: NOW }; + const ansariClient = options.ansariClient ?? new AnsariClientMock({ logger: log.logger, now: () => clock.now }); + const authClient = options.authClient ?? new AuthClientMock(); + const metaApi = options.metaApi ?? new MetaApiServiceMock({ logger: log.logger, delayMs: 0 }); + const reports: Array<{ error: unknown; report: ErrorReport }> = []; + const manager = new ConversationManager({ + config: { ...baseConfig, ...options.config }, + ansariClient, + authClient, + metaApi, + logger: log.logger, + reportError: (error, report) => reports.push({ error, report }), + now: () => clock.now, + ...(options.typingIntervalMs === undefined ? {} : { typingIntervalMs: options.typingIntervalMs }), + ...(options.typingMaxMs === undefined ? {} : { typingMaxMs: options.typingMaxMs }), + }); + const mock = metaApi as MetaApiServiceMock; + return { + manager, + ansariClient, + authClient, + metaApi, + log, + clock, + reports, + /** Every message part sent, in order, flattened. */ + replies: () => mock.sent.flatMap((call) => call.messageParts), + /** Who each send was addressed to. */ + recipients: () => mock.sent.map((call) => call.recipient), + reportedAs: () => reports.map((entry) => entry.report.errorType), + /** Triage and then carry out whatever it decided, as the HTTP layer will. */ + async handle(message: IncomingMessage) { + const action = manager.triage(message); + await manager.dispatch(message, action); + return action; + }, + }; +} + +/** Wraps an apps/api client so a test can make one call fail, count calls, or watch which token was used. */ +function wrappedAnsari(inner: AnsariClient, overrides: Partial): AnsariClient { + return { + createThread: (...args) => inner.createThread(...args), + deleteThread: (...args) => inner.deleteThread(...args), + getLastThreadInfo: (...args) => inner.getLastThreadInfo(...args), + processMessage: (...args) => inner.processMessage(...args), + ...overrides, + }; +} + +/** The mock auth client, with the token exchange replaced. */ +function authAnswering(getToken: (bsuid: string) => Promise, forget: (bsuid: string) => void = () => {}): AuthClient { + return { getToken, forget }; +} + +/** The thread the mock holds for a user: used to see how many threads a user has. */ +async function threadIdOf(ansari: AnsariClient, bsuid: string): Promise { + const token = await new AuthClientMock().getToken(bsuid); + return (await ansari.getLastThreadInfo(token)).threadId; +} + +// --------------------------------------------------------------------------------------------------------------------- +describe('triage: what happens to a message', () => { + it('answers a text message', () => { + expect(setup().manager.triage(textMessage())).toBe('text'); + }); + + it.each(['image', 'audio', 'errors', 'unsupported'])('says an %s message is unsupported', (messageType) => { + expect(setup().manager.triage(textMessage({ messageType }))).toBe('unsupported'); + }); + + it('puts maintenance mode before everything else', () => { + const { manager } = setup({ config: { WA_MAINTENANCE_MODE: true, DEPLOYMENT_TYPE: 'staging' } }); + // Also a dev-prefixed message, an old one and an image: maintenance still wins + const message = textMessage({ messageType: 'image', messageBody: { body: '!d hi' }, messageUnixTime: 1 }); + expect(manager.triage(message)).toBe('maintenance'); + }); + + describe('the staging "!d " filter', () => { + it('ignores a message starting with "!d " in staging', () => { + expect(setup({ config: { DEPLOYMENT_TYPE: 'staging' } }).manager.triage(textMessage({}, '!d what is ansari?'))).toBe('dev_filter'); + }); + + it('answers a message without the prefix in staging', () => { + expect(setup({ config: { DEPLOYMENT_TYPE: 'staging' } }).manager.triage(textMessage({}, 'what is ansari?'))).toBe('text'); + }); + + it.each(['!d', '!dx hello', ' !d hello', '!D hello'])('does not treat "%s" as the prefix', (text) => { + expect(setup({ config: { DEPLOYMENT_TYPE: 'staging' } }).manager.triage(textMessage({}, text))).toBe('text'); + }); + + it.each(['local', 'development', 'production'] as const)('answers a "!d " message in %s', (deploymentType) => { + expect(setup({ config: { DEPLOYMENT_TYPE: deploymentType } }).manager.triage(textMessage({}, '!d what is ansari?'))).toBe('text'); + }); + + // Meta sends an unsupported type (video note, poll...) as an `errors` list, not an object with a body + it('does not crash on an unsupported type, whose body is a list', () => { + const message = textMessage({ messageType: 'errors', messageBody: [{ code: 131051, title: 'Message type is not supported' }] }); + expect(setup({ config: { DEPLOYMENT_TYPE: 'staging' } }).manager.triage(message)).toBe('unsupported'); + }); + + it('does not crash on a body that is null or a string', () => { + const { manager } = setup({ config: { DEPLOYMENT_TYPE: 'staging' } }); + expect(manager.triage(textMessage({ messageType: 'image', messageBody: null }))).toBe('unsupported'); + expect(manager.triage(textMessage({ messageType: 'image', messageBody: 'x' }))).toBe('unsupported'); + }); + }); + + describe('message age', () => { + it('ignores a message older than the threshold', () => { + expect(setup().manager.triage(textMessage({ messageUnixTime: FIXED_NOW_UNIX - 86401 }))).toBe('too_old'); + }); + + it('answers a message exactly at the threshold, and one a second newer', () => { + const { manager } = setup(); + expect(manager.triage(textMessage({ messageUnixTime: FIXED_NOW_UNIX - 86400 }))).toBe('text'); + expect(manager.triage(textMessage({ messageUnixTime: FIXED_NOW_UNIX - 86399 }))).toBe('text'); + }); + + it('answers a message with no timestamp rather than ignoring it', () => { + expect(setup().manager.triage(textMessage({ messageUnixTime: null }))).toBe('text'); + }); + + it('reads the threshold from the settings', () => { + const { manager } = setup({ config: { WHATSAPP_MESSAGE_AGE_THRESHOLD_SECONDS: 60 } }); + expect(manager.triage(textMessage({ messageUnixTime: FIXED_NOW_UNIX - 61 }))).toBe('too_old'); + expect(manager.triage(textMessage({ messageUnixTime: FIXED_NOW_UNIX - 59 }))).toBe('text'); + }); + + it('checks age before type, so an old image is ignored, not answered', () => { + expect(setup().manager.triage(textMessage({ messageType: 'image', messageUnixTime: 1 }))).toBe('too_old'); + }); + + it('checks the filter before age, so an old dev message is a filter hit', () => { + const { manager } = setup({ config: { DEPLOYMENT_TYPE: 'staging' } }); + expect(manager.triage(textMessage({ messageUnixTime: 1 }, '!d old'))).toBe('dev_filter'); + }); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('dispatch: the non-text actions', () => { + it('tells the user the service is down for maintenance, and signs nobody in', async () => { + let exchanges = 0; + const t = setup({ + config: { WA_MAINTENANCE_MODE: true }, + authClient: authAnswering(async () => { + exchanges += 1; + return 'x'; + }), + }); + + expect(await t.handle(textMessage())).toBe('maintenance'); + + expect(t.replies()).toEqual([MAINTENANCE_NOTICE]); + expect(exchanges).toBe(0); + }); + + it('sends nothing for a dev-filtered or too-old message', async () => { + const t = setup({ config: { DEPLOYMENT_TYPE: 'staging' } }); + await t.handle(textMessage({}, '!d hi')); + await t.handle(textMessage({ messageUnixTime: 1 })); + expect(t.replies()).toEqual([]); + }); + + it.each(UNSUPPORTED_NOTICE_CASES.filter(([type]) => type !== ''))('tells the user about a "%s" message as Python did', async (type, python) => { + const t = setup(); + await t.manager.dispatch(textMessage({ messageType: type }), 'unsupported'); + expect(t.replies()).toEqual(python); + }); + + it('sends nothing for a message with an empty type, as Python did', async () => { + const t = setup(); + await t.manager.dispatch(textMessage({ messageType: '' }), 'unsupported'); + expect(t.replies()).toEqual([]); + expect(UNSUPPORTED_NOTICE_CASES.find(([type]) => type === '')![1]).toEqual([]); + }); + + it('needs no sign-in to refuse an unsupported type', async () => { + let exchanges = 0; + const t = setup({ + authClient: authAnswering(async () => { + exchanges += 1; + return 'x'; + }), + }); + await t.handle(textMessage({ messageType: 'image' })); + expect(exchanges).toBe(0); + expect(t.replies()).toHaveLength(1); + }); + + it('exposes the notice builders the oracle checked', () => { + expect(unsupportedTypeNotice('unsupported')).toBe("Sorry, I can't process this media type yet. Please send me a text message."); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('who a reply goes to, and what identifies the user', () => { + it('replies to the BSUID by default, and signs in with it', async () => { + const exchanged: string[] = []; + const mock = new AuthClientMock(); + const t = setup({ + authClient: authAnswering(async (bsuid) => { + exchanged.push(bsuid); + return mock.getToken(bsuid); + }), + }); + + await t.handle(textMessage({ senderPhone: null })); + + expect(exchanged).toEqual([BSUID]); + expect(new Set(t.recipients())).toEqual(new Set([BSUID])); + }); + + it('replies to the phone when the parser supplied one, but still signs in with the BSUID', async () => { + const exchanged: string[] = []; + const mock = new AuthClientMock(); + const t = setup({ + authClient: authAnswering(async (bsuid) => { + exchanged.push(bsuid); + return mock.getToken(bsuid); + }), + }); + + await t.handle(textMessage({ senderPhone: PHONE })); + + expect(exchanged).toEqual([BSUID]); + expect(new Set(t.recipients())).toEqual(new Set([PHONE])); + }); + + it('sends the typing indicator to the BSUID even when replies go to the phone', async () => { + const typing: string[] = []; + const metaApi: MetaApiService = { + sendTypingIndicator: async (recipient) => { + typing.push(recipient); + }, + sendMessage: async () => {}, + }; + const t = setup({ metaApi }); + + await t.handle(textMessage({ senderPhone: PHONE })); + + expect(typing).toEqual([BSUID]); + }); + + it('never puts the phone number in any call to apps/auth or apps/api, or in a log line', async () => { + const seen: string[] = []; + const log = capturingLogger(); + const mockAuth = new AuthClientMock(); + const inner = new AnsariClientMock({ logger: log.logger, now: () => NOW }); + const record = (...args: unknown[]) => seen.push(JSON.stringify(args)); + const t = setup({ + authClient: authAnswering(async (bsuid) => { + record('auth', bsuid); + return mockAuth.getToken(bsuid); + }), + ansariClient: wrappedAnsari(inner, { + createThread: async (...args) => (record('create', ...args), inner.createThread(...args)), + getLastThreadInfo: async (...args) => (record('list', ...args), inner.getLastThreadInfo(...args)), + processMessage: async (...args) => (record('chat', ...args), inner.processMessage(...args)), + }), + }); + + await t.handle(textMessage({ senderPhone: PHONE }, 'a-very-distinctive-question')); + + expect(seen.length).toBeGreaterThanOrEqual(4); + expect(seen.some((line) => line.includes(PHONE))).toBe(false); + expect(t.log.text()).not.toContain(PHONE); + }); + + it('writes no BSUID, phone number or message text to the logs', async () => { + const t = setup(); + await t.handle(textMessage({ senderPhone: PHONE }, 'a-very-distinctive-question')); + const text = t.log.text(); + expect(text.length).toBeGreaterThan(0); + expect(text).not.toContain(BSUID); + expect(text).not.toContain(PHONE); + expect(text).not.toContain('a-very-distinctive-question'); + }); + + it('does not answer a message with no recipient at all, and says so in the log', async () => { + const t = setup(); + await t.manager.notify('', 'hello'); + expect(t.replies()).toEqual([]); + expect(t.log.text()).toContain('No recipient'); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('a normal answer', () => { + it('signs in, shows typing, asks apps/api and sends the formatted answer', async () => { + const t = setup(); + + expect(await t.handle(textMessage({}, 'hello there'))).toBe('text'); + + // The mock answers "This is a *mock AI assistant* ...", which the formatter turns into WhatsApp italics + expect(t.replies()).toEqual(['This is a _mock AI assistant_ running in test mode.\n\nYour message: hello there']); + expect(t.reports).toEqual([]); + }); + + it('formats the answer for WhatsApp before sending it', async () => { + const answer = '## Title\n\nSome **bold** and *italic* text'; + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger, now: () => NOW }); + const t = setup({ ansariClient: wrappedAnsari(inner, { processMessage: async () => answer }) }); + + await t.handle(textMessage()); + + expect(t.replies()).toEqual(['*_Title_*\n\nSome *bold* and _italic_ text']); + }); + + it('splits a long answer into parts that each fit WhatsApp, in order', async () => { + const paragraph = (n: number) => `Paragraph ${n} ${'x'.repeat(1500)}`; + const answer = [1, 2, 3, 4, 5].map(paragraph).join('\n\n'); + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger, now: () => NOW }); + const t = setup({ ansariClient: wrappedAnsari(inner, { processMessage: async () => answer }) }); + + await t.handle(textMessage()); + + expect(t.replies().length).toBeGreaterThan(1); + expect(t.replies().every((part) => [...part].length <= 4000)).toBe(true); + expect(t.replies().join('\n\n')).toContain('Paragraph 1'); + expect(t.replies().join('\n\n').indexOf('Paragraph 5')).toBeGreaterThan(t.replies().join('\n\n').indexOf('Paragraph 1')); + }); + + it('is the same user across messages: the second message finds the first one\'s thread', async () => { + const t = setup(); + await t.handle(textMessage({}, 'first')); + const first = await threadIdOf(t.ansariClient, BSUID); + await t.handle(textMessage({}, 'second')); + expect(await threadIdOf(t.ansariClient, BSUID)).toBe(first); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('an answer with nothing to send', () => { + const notice = "Sorry, we couldn't process your message. Please try again later."; + + async function answerWith(answer: string) { + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger, now: () => NOW }); + const t = setup({ ansariClient: wrappedAnsari(inner, { processMessage: async () => answer }) }); + await t.handle(textMessage()); + return t; + } + + it('tells the user when apps/api finished without saying anything', async () => { + expect((await answerWith('')).replies()).toEqual([notice]); + }); + + // Phase 2 made splitMessage return [] for blank text (Python sent nothing, or spaces WhatsApp refuses). Staying silent + // would leave the user waiting for nothing, so they get the same notice as for an empty answer. + it.each([' ', '\n\n\n', ' \n \t \n', '\u3000'])('tells the user when the answer is only whitespace (%j)', async (blank) => { + expect((await answerWith(blank)).replies()).toEqual([notice]); + }); + + it('does not report an empty answer as an operator error', async () => { + expect((await answerWith('')).reports).toEqual([]); + }); + + it('stops the typing indicator for an empty answer too', async () => { + const t = await answerWith(''); + const sentBefore = t.recipients().length; + await new Promise((resolve) => setTimeout(resolve, 30)); + expect(t.recipients().length).toBe(sentBefore); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('sign-in: what the user and the operator are told', () => { + function failingExchange(error: unknown) { + return setup({ + authClient: authAnswering(async () => { + throw error; + }), + }); + } + + it.each([ + [new AuthKeyRejectedError('401'), 'auth_key_rejected'], + [new AuthBadRequestError('400'), 'auth_bad_request'], + [new AuthTokenError('500'), 'auth_token_failure'], + [new TypeError('something else entirely'), 'auth_token_failure'], + ])('reports %s to the operator as "%s"', async (error, reportedAs) => { + const t = failingExchange(error); + await t.handle(textMessage()); + expect(t.reportedAs()).toEqual([reportedAs]); + expect(t.reports[0]!.error).toBe(error); + }); + + it.each([new AuthUserBannedError('403'), new AuthRateLimitedError('429', 300)])('does not report %s as an operator alert', async (error) => { + const t = failingExchange(error); + await t.handle(textMessage()); + expect(t.reports).toEqual([]); + }); + + it('tells the user the right thing for each refusal, and a different thing for three of the four', async () => { + const notices: Record = {}; + for (const [name, error] of Object.entries({ + banned: new AuthUserBannedError('403'), + limited: new AuthRateLimitedError('429', 300), + key: new AuthKeyRejectedError('401'), + outage: new AuthTokenError('500'), + })) { + const t = failingExchange(error); + await t.handle(textMessage()); + notices[name] = t.replies().join(''); + } + + expect(notices.banned).toBe(BANNED_NOTICE); + expect(notices.limited).toContain('5 minutes'); + expect(notices.key).toBe(SIGN_IN_FAILED_NOTICE); + expect(notices.outage).toBe(SIGN_IN_FAILED_NOTICE); + expect(new Set(Object.values(notices)).size).toBe(3); + }); + + it('does not start the typing indicator, or ask apps/api anything, when sign-in fails', async () => { + let typing = 0; + let apiCalls = 0; + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger }); + const t = setup({ + authClient: authAnswering(async () => { + throw new AuthTokenError('500'); + }), + ansariClient: wrappedAnsari(inner, { + getLastThreadInfo: async (...args) => (apiCalls++, inner.getLastThreadInfo(...args)), + }), + metaApi: { + sendTypingIndicator: async () => { + typing += 1; + }, + sendMessage: async () => {}, + }, + }); + + await t.handle(textMessage()); + + expect(typing).toBe(0); + expect(apiCalls).toBe(0); + }); + + it('a stale notice is not reused: each message gets the notice for its own failure', async () => { + let failure: Error = new AuthUserBannedError('403'); + const t = setup({ + authClient: authAnswering(async () => { + throw failure; + }), + }); + await t.handle(textMessage()); + failure = new AuthTokenError('500'); + await t.handle(textMessage()); + expect(t.replies()).toEqual([BANNED_NOTICE, SIGN_IN_FAILED_NOTICE]); + }); + + it('an empty BSUID cannot sign in and nothing is sent to an empty recipient', async () => { + const t = setup(); + await t.manager.dispatch(textMessage({ bsuid: '' }), 'text'); + expect(t.replies()).toEqual([]); + expect(t.log.text()).toContain('bsuid is not set'); + }); + + describe('the rate-limit notice', () => { + it.each(RATE_LIMITED_NOTICE_CASES)('a wait of %s seconds reads as Python did', (seconds, python) => { + expect(rateLimitedNotice(seconds)).toBe(python); + }); + }); + + it('keeps the reports free of the BSUID, the token and the message text', async () => { + const t = failingExchange(new AuthTokenError('apps/auth is down')); + await runWithRequestId('req-123', () => t.handle(textMessage({}, 'a-very-distinctive-question'))); + const report = JSON.stringify(t.reports[0]!.report); + expect(report).toContain('req-123'); + expect(report).not.toContain(BSUID); + expect(report).not.toContain('a-very-distinctive-question'); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('one re-exchange after an apps/api 401', () => { + /** apps/api refuses the first `refused` chat calls with a 401, then answers from the mock. */ + function apiRefusing(refused: number) { + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger, now: () => NOW }); + const state = { chatCalls: 0, tokens: [] as string[] }; + const client = wrappedAnsari(inner, { + processMessage: async (token, threadId, message) => { + state.chatCalls += 1; + state.tokens.push(token); + if (state.chatCalls <= refused) throw new ApiUnauthorizedError("apps/api refused the user's token"); + return inner.processMessage(token, threadId, message); + }, + // Threads belong to a token in the mock, so a fresh token is a fresh user. Keep one user across tokens. + getLastThreadInfo: async () => ({ threadId: null, lastMessageTime: null }), + createThread: async () => ({ threadId: 'mock_thread_fixed' }), + }); + return { client, state, inner }; + } + + /** An exchange that hands out token-1, token-2, ... and counts calls. */ + function countingExchange() { + const exchanges: string[] = []; + const forgotten: string[] = []; + const client = authAnswering( + async (bsuid) => { + exchanges.push(bsuid); + return `token-${exchanges.length}`; + }, + (bsuid) => { + forgotten.push(bsuid); + }, + ); + return { client, exchanges, forgotten }; + } + + it('drops the stale token, exchanges once more, and answers the message with the fresh token', async () => { + const api = apiRefusing(1); + const auth = countingExchange(); + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger, now: () => NOW }); + // After the 401 the retry must reach a thread the fresh token can use + const t = setup({ + ansariClient: wrappedAnsari(api.client, { + processMessage: async (token, threadId, message) => { + api.state.chatCalls += 1; + api.state.tokens.push(token); + if (api.state.chatCalls === 1) throw new ApiUnauthorizedError("apps/api refused the user's token"); + return inner.processMessage(token, (await inner.createThread(token, 'x')).threadId, message); + }, + }), + authClient: auth.client, + }); + + await t.handle(textMessage()); + + expect(auth.exchanges).toEqual([BSUID, BSUID]); + expect(auth.forgotten).toEqual([BSUID]); + expect(api.state.tokens).toEqual(['token-1', 'token-2']); + expect(t.replies()).toHaveLength(1); + expect(t.replies()[0]).toContain('mock AI assistant'); + expect(t.reports).toEqual([]); + }); + + it('forgets the stale token before asking again, not after', async () => { + const order: string[] = []; + const api = apiRefusing(1); + const t = setup({ + ansariClient: api.client, + authClient: authAnswering( + async () => { + order.push('exchange'); + return `token-${order.length}`; + }, + () => { + order.push('forget'); + }, + ), + }); + await t.handle(textMessage()); + expect(order).toEqual(['exchange', 'forget', 'exchange']); + }); + + it('gives up after a second 401: never a third exchange or a third attempt', async () => { + const api = apiRefusing(99); + const auth = countingExchange(); + const t = setup({ ansariClient: api.client, authClient: auth.client }); + + await t.handle(textMessage()); + + expect(auth.exchanges).toHaveLength(2); + expect(api.state.chatCalls).toBe(2); + expect(t.reportedAs()).toEqual(['api_unauthorized_after_reexchange']); + expect(t.replies()).toEqual(['An error occurred while processing your message. Please try again later.']); + }); + + it('tells a user found banned on the re-exchange so, and does not retry', async () => { + const api = apiRefusing(99); + let exchanges = 0; + const t = setup({ + ansariClient: api.client, + authClient: authAnswering(async () => { + exchanges += 1; + if (exchanges === 1) return 'token-1'; + throw new AuthUserBannedError('403'); + }), + }); + + await t.handle(textMessage()); + + expect(api.state.chatCalls).toBe(1); + expect(t.replies()).toEqual([BANNED_NOTICE]); + }); + + // The user sent one message. A 429 on the second exchange would say "you are sending too quickly", which is false. + it('does not tell the user they are sending too quickly when the re-exchange is rate limited', async () => { + const api = apiRefusing(99); + let exchanges = 0; + const t = setup({ + ansariClient: api.client, + authClient: authAnswering(async () => { + exchanges += 1; + if (exchanges === 1) return 'token-1'; + throw new AuthRateLimitedError('429', 300); + }), + }); + + await t.handle(textMessage()); + + expect(t.replies()).toEqual([SIGN_IN_FAILED_NOTICE]); + expect(t.replies()[0]).not.toContain('minutes'); + }); + + it('reports a failed re-exchange the same way a failed first exchange is reported', async () => { + const api = apiRefusing(99); + let exchanges = 0; + const t = setup({ + ansariClient: api.client, + authClient: authAnswering(async () => { + exchanges += 1; + if (exchanges === 1) return 'token-1'; + throw new AuthKeyRejectedError('401'); + }), + }); + + await t.handle(textMessage()); + + expect(t.reportedAs()).toEqual(['auth_key_rejected']); + expect(t.replies()).toEqual([SIGN_IN_FAILED_NOTICE]); + }); + + it('does not retry a failure that is not a 401', async () => { + const exchanges = countingExchange(); + let chatCalls = 0; + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger }); + const t = setup({ + authClient: exchanges.client, + ansariClient: wrappedAnsari(inner, { + processMessage: async () => { + chatCalls += 1; + throw new MessageProcessingError('apps/api is down'); + }, + }), + }); + + await t.handle(textMessage()); + + expect(chatCalls).toBe(1); + expect(exchanges.exchanges).toHaveLength(1); + }); + + it('a 401 while listing threads is retried too, not only one on the chat call', async () => { + let listCalls = 0; + const auth = countingExchange(); + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger, now: () => NOW }); + const t = setup({ + authClient: auth.client, + ansariClient: wrappedAnsari(inner, { + getLastThreadInfo: async (token) => { + listCalls += 1; + if (listCalls === 1) throw new ApiUnauthorizedError('refused'); + return inner.getLastThreadInfo(token); + }, + }), + }); + + await t.handle(textMessage()); + + expect(auth.exchanges).toHaveLength(2); + expect(t.replies()[0]).toContain('mock AI assistant'); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('the user\'s one thread', () => { + async function userThreads(ansari: AnsariClientMock, bsuid: string): Promise { + const token = await new AuthClientMock().getToken(bsuid); + // The mock lists only the newest thread, so count them by probing each id it may have made + const ids: string[] = []; + for (let n = 1; n <= 20; n++) { + const id = `mock_thread_${n}`; + try { + await ansari.processMessage(token, id, ''); + ids.push(id); + } catch { + // not this user's, or not there + } + } + return ids; + } + + function withMock(config: Partial = {}) { + const log = capturingLogger(); + const clock = { now: NOW }; + const ansari = new AnsariClientMock({ logger: log.logger, now: () => clock.now }); + const t = setup({ ansariClient: ansari, clock, config }); + return { ...t, ansari, clock }; + } + + it('creates the only thread on the first message', async () => { + const t = withMock(); + await t.handle(textMessage()); + expect(await userThreads(t.ansari, BSUID)).toEqual(['mock_thread_1']); + }); + + it('reuses the thread inside the expiry and keeps its history', async () => { + const t = withMock(); + await t.handle(textMessage({}, 'remember me')); + t.clock.now = new Date(NOW.getTime() + (3 * HOUR - 60) * 1000); // just inside + await t.handle(textMessage({}, 'hello again')); + expect(await userThreads(t.ansari, BSUID)).toEqual(['mock_thread_1']); + }); + + it('deletes the old thread and starts a new one after the expiry', async () => { + const t = withMock(); + await t.handle(textMessage({}, 'old message')); + t.clock.now = new Date(NOW.getTime() + (3 * HOUR + 60) * 1000); // just outside + await t.handle(textMessage({}, 'hello again')); + expect(await userThreads(t.ansari, BSUID)).toEqual(['mock_thread_2']); + }); + + it('reads the expiry from the settings', async () => { + const t = withMock({ WHATSAPP_CHAT_RETENTION_HOURS: 1 }); + await t.handle(textMessage()); + t.clock.now = new Date(NOW.getTime() + (HOUR + 60) * 1000); + await t.handle(textMessage()); + expect(await userThreads(t.ansari, BSUID)).toEqual(['mock_thread_2']); + }); + + it('treats a thread exactly at the retention time as still current', async () => { + const t = withMock(); + await t.handle(textMessage()); + t.clock.now = new Date(NOW.getTime() + 3 * HOUR * 1000); + await t.handle(textMessage()); + expect(await userThreads(t.ansari, BSUID)).toEqual(['mock_thread_1']); + }); + + it('never touches another user\'s thread', async () => { + const t = withMock(); + await t.handle(textMessage({ bsuid: OTHER_BSUID })); + await t.handle(textMessage()); + t.clock.now = new Date(NOW.getTime() + (3 * HOUR + 60) * 1000); + await t.handle(textMessage()); + expect(await userThreads(t.ansari, OTHER_BSUID)).toEqual(['mock_thread_1']); + }); + + // apps/api sends `...Z`, while the mock stores its own format, so this is the form production depends on + describe('with the timestamp apps/api really sends', () => { + function calls(info: ThreadInfo, options: { failDelete?: boolean } = {}) { + const log: string[] = []; + const client: AnsariClient = { + getLastThreadInfo: async () => info, + deleteThread: async (_token, id) => { + log.push(`delete ${id}`); + if (options.failDelete) throw new ThreadDeletionError('apps/api is down'); + }, + createThread: async (_token, title) => { + log.push(`create ${title}`); + return { threadId: 'new' }; + }, + processMessage: async (_token, id) => { + log.push(`chat ${id}`); + return 'ok'; + }, + }; + return { client, log }; + } + const fourHoursAgo = new Date(NOW.getTime() - 4 * HOUR * 1000).toISOString(); + + it('reads a Z timestamp: deletes the expired thread, then creates one titled by the first words', async () => { + const { client, log } = calls({ threadId: 'old', lastMessageTime: fourHoursAgo }); + const t = setup({ ansariClient: client }); + await t.handle(textMessage({}, 'hello there')); + expect(log).toEqual(['delete old', 'create hello there', 'chat new']); + }); + + it('reads a +00:00 timestamp and one with an offset', async () => { + for (const stamp of ['2026-11-10T08:00:00.000+00:00', '2026-11-10T10:00:00+02:00']) { + const { client, log } = calls({ threadId: 'old', lastMessageTime: stamp }); + await setup({ ansariClient: client }).handle(textMessage()); + expect(log).toEqual(['delete old', 'create hello', 'chat new']); + } + }); + + it('keeps a thread whose Z timestamp is recent', async () => { + const { client, log } = calls({ threadId: 'cur', lastMessageTime: new Date(NOW.getTime() - 60_000).toISOString() }); + await setup({ ansariClient: client }).handle(textMessage()); + expect(log).toEqual(['chat cur']); + }); + + it('starts a thread when there is none', async () => { + const { client, log } = calls({ threadId: null, lastMessageTime: null }); + await setup({ ansariClient: client }).handle(textMessage()); + expect(log).toEqual(['create hello', 'chat new']); + }); + + it('creates a thread without deleting when a thread exists but has no time', async () => { + const { client, log } = calls({ threadId: 'odd', lastMessageTime: null }); + await setup({ ansariClient: client }).handle(textMessage()); + expect(log).toEqual(['delete odd', 'create hello', 'chat new']); + }); + + // JavaScript would read this as local time and move the thread by the server's offset; Python refused it + it.each(['2026-11-10T08:00:00', '2026-11-10', 'yesterday', ''])('refuses a timestamp without a time zone (%j) rather than guessing', async (stamp) => { + const { client, log } = calls({ threadId: 'old', lastMessageTime: stamp }); + const t = setup({ ansariClient: client }); + await t.handle(textMessage()); + expect(log).toEqual([]); + expect(t.replies()).toEqual(['An unexpected error occurred while processing your message. Please try again later.']); + }); + }); + + describe('the thread title', () => { + it.each(THREAD_TITLE_CASES)('titles a thread from %j as Python did', async (message, python) => { + const titles: string[] = []; + const client: AnsariClient = { + getLastThreadInfo: async () => ({ threadId: null, lastMessageTime: null }), + deleteThread: async () => {}, + createThread: async (_token, title) => { + titles.push(title); + return { threadId: 'new' }; + }, + processMessage: async () => 'ok', + }; + await setup({ ansariClient: client }).handle(textMessage({}, message)); + expect(titles).toEqual([python]); + }); + }); + + describe('failures, each reported under its own name', () => { + function failing(overrides: Partial) { + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger, now: () => NOW }); + return setup({ ansariClient: wrappedAnsari(inner, overrides) }); + } + + it('a failed thread list is reported, and the user is told about chat history', async () => { + const t = failing({ + getLastThreadInfo: async () => { + throw new ThreadInfoError('apps/api is down'); + }, + }); + await t.handle(textMessage()); + expect(t.reportedAs()).toEqual(['thread_info_failure']); + expect(t.replies()).toEqual(["Sorry, we're having trouble accessing your chat history. Please try again later."]); + }); + + it('a failed delete is reported, the user is told, and no second thread is created', async () => { + const log = capturingLogger(); + const clock = { now: NOW }; + const inner = new AnsariClientMock({ logger: log.logger, now: () => clock.now }); + let creates = 0; + const t = setup({ + clock, + ansariClient: wrappedAnsari(inner, { + deleteThread: async () => { + throw new ThreadDeletionError('apps/api is down'); + }, + createThread: async (...args) => (creates++, inner.createThread(...args)), + }), + }); + await t.handle(textMessage()); + expect(creates).toBe(1); + clock.now = new Date(NOW.getTime() + (3 * HOUR + 60) * 1000); + + await t.handle(textMessage()); + + expect(creates).toBe(1); // still exactly one thread + expect(t.reportedAs()).toEqual(['thread_deletion_failure']); + expect(t.replies().at(-1)).toBe('An unexpected error occurred while starting a new chat session.. Please try again later.'); + }); + + it('a failed create is reported and the user is told', async () => { + const t = failing({ + createThread: async () => { + throw new ThreadCreationError('apps/api is down'); + }, + }); + await t.handle(textMessage()); + expect(t.reportedAs()).toEqual(['thread_creation_failure']); + expect(t.replies()).toEqual(['An unexpected error occurred while creating a new chat session. Please try again later.']); + }); + + it('a failed chat call is reported and the user is told', async () => { + const t = failing({ + processMessage: async () => { + throw new MessageProcessingError('stream cut off'); + }, + }); + await t.handle(textMessage()); + expect(t.reportedAs()).toEqual(['message_processing_failure']); + expect(t.replies()).toEqual(['An error occurred while processing your message. Please try again later.']); + }); + + it('an unexpected fault gets the "unexpected" notice, is logged, and is not an uncaught error', async () => { + const t = failing({ + processMessage: async () => { + throw new RangeError('a bug'); + }, + }); + await t.handle(textMessage()); + expect(t.replies()).toEqual(['An unexpected error occurred while processing your message. Please try again later.']); + expect(t.log.lines().some((line) => line.level === 'error' && line.message.includes('Unexpected error processing'))).toBe(true); + }); + + it('a text message without a body gets the "unexpected" notice', async () => { + const t = setup(); + await t.manager.dispatch(textMessage({ messageBody: { nothing: true } }), 'text'); + expect(t.replies()).toEqual(['An unexpected error occurred while processing your message. Please try again later.']); + }); + + it('reports a thread failure with the request id and nothing else identifying', async () => { + const t = failing({ + getLastThreadInfo: async () => { + throw new ThreadInfoError('apps/api is down'); + }, + }); + await runWithRequestId('req-9', () => t.handle(textMessage({}, 'a-very-distinctive-question'))); + expect(t.reports[0]!.report.context).toEqual({ request_id: 'req-9' }); + }); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('sending', () => { + it('survives Meta refusing the answer: logs it and does not throw', async () => { + const metaApi: MetaApiService = { + sendTypingIndicator: async () => {}, + sendMessage: async () => { + throw new MetaApiError('Meta said no', 400); + }, + }; + const t = setup({ metaApi }); + await expect(t.handle(textMessage())).resolves.toBe('text'); + expect(t.log.lines().some((line) => line.level === 'error' && line.message.includes('Error sending WhatsApp message'))).toBe(true); + }); + + it('survives Meta refusing a notice', async () => { + const metaApi: MetaApiService = { + sendTypingIndicator: async () => {}, + sendMessage: async () => { + throw new MetaApiError('Meta said no', 400); + }, + }; + const t = setup({ metaApi, config: { WA_MAINTENANCE_MODE: true } }); + await expect(t.handle(textMessage())).resolves.toBe('maintenance'); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('the typing indicator', () => { + const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + + /** An apps/api whose chat answer arrives only when the test lets it. */ + function slowAnswer() { + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger, now: () => NOW }); + let release: () => void = () => {}; + const gate = new Promise((resolve) => (release = resolve)); + return { release: () => release(), client: wrappedAnsari(inner, { processMessage: async (...args) => (await gate, inner.processMessage(...args)) }) }; + } + + function typingCounter() { + const state = { typing: 0, ids: [] as string[] }; + const metaApi = new MetaApiServiceMock({ logger: capturingLogger().logger, delayMs: 0 }); + const counting: MetaApiService = { + sendTypingIndicator: async (recipient, messageId) => { + state.typing += 1; + state.ids.push(`${recipient}/${messageId}`); + }, + sendMessage: (recipient, parts) => metaApi.sendMessage(recipient, parts), + }; + return { state, counting, mock: metaApi }; + } + + it('sends one indicator at once and more while the answer is slow, then stops when it arrives', async () => { + const slow = slowAnswer(); + const counter = typingCounter(); + const t = setup({ ansariClient: slow.client, metaApi: counter.counting, typingIntervalMs: 10 }); + + const done = t.handle(textMessage()); + await wait(60); + expect(counter.state.typing).toBeGreaterThan(2); + + slow.release(); + await done; + const atFinish = counter.state.typing; + await wait(60); + expect(counter.state.typing).toBe(atFinish); + }); + + it('shows the indicator for the sender\'s own message id', async () => { + const counter = typingCounter(); + const t = setup({ metaApi: counter.counting }); + await t.handle(textMessage()); + expect(counter.state.ids[0]).toBe(`${BSUID}/wamid.TEST`); + }); + + it('stops after the maximum duration even if the answer never comes', async () => { + const slow = slowAnswer(); + const counter = typingCounter(); + const clock = { now: NOW }; + const t = setup({ ansariClient: slow.client, metaApi: counter.counting, typingIntervalMs: 10, typingMaxMs: 25, clock }); + + const done = t.handle(textMessage()); + // Move the clock past the limit as real time passes + const ticker = setInterval(() => (clock.now = new Date(clock.now.getTime() + 10)), 5); + await wait(120); + clearInterval(ticker); + const atLimit = counter.state.typing; + await wait(60); + expect(counter.state.typing).toBe(atLimit); + expect(t.log.text()).toContain('exceeded maximum duration'); + + slow.release(); + await done; + }); + + it('stops when the answer fails', async () => { + const counter = typingCounter(); + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger }); + const t = setup({ + metaApi: counter.counting, + typingIntervalMs: 10, + ansariClient: wrappedAnsari(inner, { + processMessage: async () => { + throw new MessageProcessingError('boom'); + }, + }), + }); + await t.handle(textMessage()); + const atFinish = counter.state.typing; + await wait(60); + expect(counter.state.typing).toBe(atFinish); + }); + + it('stops when a thread step fails', async () => { + const counter = typingCounter(); + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger }); + const t = setup({ + metaApi: counter.counting, + typingIntervalMs: 10, + ansariClient: wrappedAnsari(inner, { + getLastThreadInfo: async () => { + throw new ThreadInfoError('boom'); + }, + }), + }); + await t.handle(textMessage()); + const atFinish = counter.state.typing; + await wait(60); + expect(counter.state.typing).toBe(atFinish); + }); + + it('stops after an unexpected fault', async () => { + const counter = typingCounter(); + const log = capturingLogger(); + const inner = new AnsariClientMock({ logger: log.logger }); + const t = setup({ + metaApi: counter.counting, + typingIntervalMs: 10, + ansariClient: wrappedAnsari(inner, { + processMessage: async () => { + throw new RangeError('bug'); + }, + }), + }); + await t.handle(textMessage()); + const atFinish = counter.state.typing; + await wait(60); + expect(counter.state.typing).toBe(atFinish); + }); + + it('keeps going when one indicator fails to send', async () => { + const slow = slowAnswer(); + let attempts = 0; + const metaApi: MetaApiService = { + sendTypingIndicator: async () => { + attempts += 1; + throw new MetaApiError('Meta said no', 500); + }, + sendMessage: async () => {}, + }; + const t = setup({ ansariClient: slow.client, metaApi, typingIntervalMs: 10 }); + const done = t.handle(textMessage()); + await wait(60); + expect(attempts).toBeGreaterThan(2); + slow.release(); + await done; + }); + + it('is not started when the message has no id to attach it to', async () => { + const counter = typingCounter(); + const t = setup({ metaApi: counter.counting }); + await t.handle(textMessage({ messageId: null })); + expect(counter.state.typing).toBe(0); + expect(t.log.text()).toContain('missing bsuid or message_id'); + expect(counter.mock.sent).toHaveLength(1); // the answer is still sent + }); +}); diff --git a/apps/whatsapp/tests/fixtures/generate_python_oracle.py b/apps/whatsapp/tests/fixtures/generate_python_oracle.py index 0fe9cb02..3f1a26e0 100644 --- a/apps/whatsapp/tests/fixtures/generate_python_oracle.py +++ b/apps/whatsapp/tests/fixtures/generate_python_oracle.py @@ -23,6 +23,7 @@ import math import os import sys +import types # Dummy credentials, as in legacy/whatsapp/tests/conftest.py. Nothing here is a real secret. for key, value in { @@ -49,6 +50,10 @@ format_for_whatsapp, format_nested_lists, ) +from ansari_whatsapp.services.whatsapp_conversation_manager import ( # noqa: E402 + WhatsAppConversationManager, + _rate_limited_notice, +) from ansari_whatsapp.utils.config import get_settings # noqa: E402 from ansari_whatsapp.utils.exceptions import UnexpectedMetaPayloadError # noqa: E402 from ansari_whatsapp.utils.language_utils import get_language_direction_from_text # noqa: E402 @@ -255,6 +260,77 @@ def message_age_case(age): ] +# --------------------------------------------------------------------------------------------------------------------- +# Conversation manager: the notices that depend on an input, and the thread title +# --------------------------------------------------------------------------------------------------------------------- + +RETRY_AFTER_INPUTS = [-5, 0, 1, 59, 60, 61, 119, 120, 121, 300, 899, 900, 3599, 3600, 86400] + +# What Meta calls the type of a message that is not text. "errors" is what the parser reports for an unsupported one; +# "unsupported" (with the replace in handle_unsupported_message) is kept to show that branch. +MEDIA_TYPE_INPUTS = [ + "image", "audio", "video", "sticker", "document", "location", "contacts", "reaction", "interactive", "button", + "order", "system", "errors", "unsupported", "images", "text", "s", "Image", "", +] + +THREAD_TITLE_INPUTS = [ + "", + " ", + "hello", + "what is ansari", + "one two three four five six seven eight nine", + "one two three four five six", + "one two three four five six seven", + " lead and trail ", + "tab\there\nnew\r\nline", + "no\u00a0break\u2003em\u3000ideographic space", + "line\u2028separator\u2029paragraph", + "c0\x1cfile\x1dgroup\x1erecord\x1funit\x85next", + "\ufeffbom is not whitespace", + "zero\u200bwidth stays", + "\u0645\u0631\u062d\u0628\u0627 \u0643\u064a\u0641 \u062d\u0627\u0644\u0643 \u064a\u0627 \u0623\u062e\u064a \u0627\u0644\u0643\u0631\u064a\u0645 \u0623\u0631\u064a\u062f \u0627\u0644\u0633\u0624\u0627\u0644", + "\U0001f600 emoji \U0001f600 words", + "x" * 500, +] + + +def _manager(message_type: str = "text") -> WhatsAppConversationManager: + return WhatsAppConversationManager( + bsuid=BSUID, incoming_msg_type=message_type, incoming_msg_body={}, message_id="wamid.ORACLE" + ) + + +def unsupported_notice_case(message_type: str): + """What the user is sent for a message of this type (nothing at all when the type is empty).""" + sent = [] + manager = _manager(message_type) + + async def capture(msg_body, recipient_bsuid_or_phone=None): + sent.append(msg_body) + + manager.send_whatsapp_message = capture + asyncio.run(manager.handle_unsupported_message()) + return [message_type, sent] + + +def thread_title_case(first_message: str): + """The title the manager gives a new thread, taken from the real _resolve_thread.""" + titles = [] + manager = _manager() + manager.token = "oracle-token" + + async def no_thread_yet(token): + return {"thread_id": None, "last_message_time": None} + + async def create_thread(token, title): + titles.append(title) + return {"thread_id": "t1"} + + manager.ansari_client = types.SimpleNamespace(get_last_thread_info=no_thread_yet, create_thread=create_thread) + asyncio.run(manager._resolve_thread(first_message)) + return [first_message, titles[0]] + + # --------------------------------------------------------------------------------------------------------------------- # Splitter: inputs are described by a recipe both languages can rebuild; the expected answer is a summary # --------------------------------------------------------------------------------------------------------------------- @@ -407,6 +483,11 @@ def main(out_path: str) -> None: "TIME_DELTA_CASES": [[s, format_time_delta(s)] for s in TIME_DELTA_INPUTS], "TIME_PASSED_CASES": [time_passed_case(s) for s in TIME_PASSED_INPUTS], "MESSAGE_AGE_CASES": [message_age_case(a) for a in MESSAGE_AGE_INPUTS], + "RATE_LIMITED_NOTICE_CASES": [[s, _rate_limited_notice(s)] for s in RETRY_AFTER_INPUTS], + "UNSUPPORTED_NOTICE_CASES": [unsupported_notice_case(t) for t in MEDIA_TYPE_INPUTS], + "THREAD_TITLE_CASES": [thread_title_case(t) for t in THREAD_TITLE_INPUTS], + # Every code point str.split() treats as a separator: the thread title is cut at these. + "PYTHON_WHITESPACE": [i for i in range(0x110000) if chr(i).isspace()], "SPLITTER_CASES": {name: summarise(split_message(text)) for name, text in SPLITTER_RECIPES.items()}, "PARSER_CASES": [ {"name": name, "replyByPhone": by_phone, "payload": body, "expected": run_parser(body, by_phone)} @@ -430,6 +511,10 @@ def main(out_path: str) -> None: "TIME_DELTA_CASES": "Array<[seconds: number, formatted: string]>", "TIME_PASSED_CASES": "Array<[secondsAgo: number | null, passed: number | 'inf', logging: string]>", "MESSAGE_AGE_CASES": "Array<[secondsAgo: number | null, unixTime: number | null, tooOld: boolean]>", + "RATE_LIMITED_NOTICE_CASES": "Array<[retryAfterSeconds: number, notice: string]>", + "UNSUPPORTED_NOTICE_CASES": "Array<[messageType: string, sent: string[]]>", + "THREAD_TITLE_CASES": "Cases", + "PYTHON_WHITESPACE": "number[]", "SPLITTER_CASES": "Record", "PARSER_CASES": "ParserCase[]", "EMPTY_TEXT": "{ direction: string; format: string }", diff --git a/apps/whatsapp/tests/fixtures/pythonOracle.ts b/apps/whatsapp/tests/fixtures/pythonOracle.ts index 0c654862..4ac39126 100644 --- a/apps/whatsapp/tests/fixtures/pythonOracle.ts +++ b/apps/whatsapp/tests/fixtures/pythonOracle.ts @@ -832,6 +832,287 @@ export const MESSAGE_AGE_CASES: Array<[secondsAgo: number | null, unixTime: numb ] ]; +export const RATE_LIMITED_NOTICE_CASES: Array<[retryAfterSeconds: number, notice: string]> = [ + [ + -5, + "You are sending messages too quickly. Please try again in about 1 minute." + ], + [ + 0, + "You are sending messages too quickly. Please try again in about 1 minute." + ], + [ + 1, + "You are sending messages too quickly. Please try again in about 1 minute." + ], + [ + 59, + "You are sending messages too quickly. Please try again in about 1 minute." + ], + [ + 60, + "You are sending messages too quickly. Please try again in about 1 minute." + ], + [ + 61, + "You are sending messages too quickly. Please try again in about 2 minutes." + ], + [ + 119, + "You are sending messages too quickly. Please try again in about 2 minutes." + ], + [ + 120, + "You are sending messages too quickly. Please try again in about 2 minutes." + ], + [ + 121, + "You are sending messages too quickly. Please try again in about 3 minutes." + ], + [ + 300, + "You are sending messages too quickly. Please try again in about 5 minutes." + ], + [ + 899, + "You are sending messages too quickly. Please try again in about 15 minutes." + ], + [ + 900, + "You are sending messages too quickly. Please try again in about 15 minutes." + ], + [ + 3599, + "You are sending messages too quickly. Please try again in about 60 minutes." + ], + [ + 3600, + "You are sending messages too quickly. Please try again in about 60 minutes." + ], + [ + 86400, + "You are sending messages too quickly. Please try again in about 1440 minutes." + ] +]; + +export const UNSUPPORTED_NOTICE_CASES: Array<[messageType: string, sent: string[]]> = [ + [ + "image", + [ + "Sorry, I can't process images yet. Please send me a text message." + ] + ], + [ + "audio", + [ + "Sorry, I can't process audios yet. Please send me a text message." + ] + ], + [ + "video", + [ + "Sorry, I can't process videos yet. Please send me a text message." + ] + ], + [ + "sticker", + [ + "Sorry, I can't process stickers yet. Please send me a text message." + ] + ], + [ + "document", + [ + "Sorry, I can't process documents yet. Please send me a text message." + ] + ], + [ + "location", + [ + "Sorry, I can't process locations yet. Please send me a text message." + ] + ], + [ + "contacts", + [ + "Sorry, I can't process contacts yet. Please send me a text message." + ] + ], + [ + "reaction", + [ + "Sorry, I can't process reactions yet. Please send me a text message." + ] + ], + [ + "interactive", + [ + "Sorry, I can't process interactives yet. Please send me a text message." + ] + ], + [ + "button", + [ + "Sorry, I can't process buttons yet. Please send me a text message." + ] + ], + [ + "order", + [ + "Sorry, I can't process orders yet. Please send me a text message." + ] + ], + [ + "system", + [ + "Sorry, I can't process systems yet. Please send me a text message." + ] + ], + [ + "errors", + [ + "Sorry, I can't process errors yet. Please send me a text message." + ] + ], + [ + "unsupported", + [ + "Sorry, I can't process this media type yet. Please send me a text message." + ] + ], + [ + "images", + [ + "Sorry, I can't process images yet. Please send me a text message." + ] + ], + [ + "text", + [ + "Sorry, I can't process texts yet. Please send me a text message." + ] + ], + [ + "s", + [ + "Sorry, I can't process s yet. Please send me a text message." + ] + ], + [ + "Image", + [ + "Sorry, I can't process Images yet. Please send me a text message." + ] + ], + [ + "", + [] + ] +]; + +export const THREAD_TITLE_CASES: Cases = [ + [ + "", + "" + ], + [ + " ", + "" + ], + [ + "hello", + "hello" + ], + [ + "what is ansari", + "what is ansari" + ], + [ + "one two three four five six seven eight nine", + "one two three four five six" + ], + [ + "one two three four five six", + "one two three four five six" + ], + [ + "one two three four five six seven", + "one two three four five six" + ], + [ + " lead and trail ", + "lead and trail" + ], + [ + "tab\there\nnew\r\nline", + "tab here new line" + ], + [ + "no\u00a0break\u2003em\u3000ideographic space", + "no break em ideographic space" + ], + [ + "line\u2028separator\u2029paragraph", + "line separator paragraph" + ], + [ + "c0\u001cfile\u001dgroup\u001erecord\u001funit\u0085next", + "c0 file group record unit next" + ], + [ + "\ufeffbom is not whitespace", + "\ufeffbom is not whitespace" + ], + [ + "zero\u200bwidth stays", + "zero\u200bwidth stays" + ], + [ + "\u0645\u0631\u062d\u0628\u0627 \u0643\u064a\u0641 \u062d\u0627\u0644\u0643 \u064a\u0627 \u0623\u062e\u064a \u0627\u0644\u0643\u0631\u064a\u0645 \u0623\u0631\u064a\u062f \u0627\u0644\u0633\u0624\u0627\u0644", + "\u0645\u0631\u062d\u0628\u0627 \u0643\u064a\u0641 \u062d\u0627\u0644\u0643 \u064a\u0627 \u0623\u062e\u064a \u0627\u0644\u0643\u0631\u064a\u0645" + ], + [ + "\ud83d\ude00 emoji \ud83d\ude00 words", + "\ud83d\ude00 emoji \ud83d\ude00 words" + ], + [ + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + ] +]; + +export const PYTHON_WHITESPACE: number[] = [ + 9, + 10, + 11, + 12, + 13, + 28, + 29, + 30, + 31, + 32, + 133, + 160, + 5760, + 8192, + 8193, + 8194, + 8195, + 8196, + 8197, + 8198, + 8199, + 8200, + 8201, + 8202, + 8232, + 8233, + 8239, + 8287, + 12288 +]; + export const SPLITTER_CASES: Record = { "short": { "count": 1, diff --git a/apps/whatsapp/tests/pythonText.test.ts b/apps/whatsapp/tests/pythonText.test.ts new file mode 100644 index 00000000..e4cdbf9f --- /dev/null +++ b/apps/whatsapp/tests/pythonText.test.ts @@ -0,0 +1,32 @@ +/** + * `pythonSplitWords` must cut at exactly the characters Python's `str.split()` cuts at. The list of those characters is not + * written by hand: `generate_python_oracle.py` asks Python's `isspace()` about every code point from 0 to 0x10FFFF. + */ +import { describe, expect, it } from 'vitest'; +import { pythonSplitWords } from '../src/utils/pythonText'; +import { PYTHON_WHITESPACE } from './fixtures/pythonOracle'; + +describe('pythonSplitWords', () => { + it('treats exactly the code points Python treats as whitespace as separators', () => { + const python = new Set(PYTHON_WHITESPACE); + const wrong: string[] = []; + for (let codePoint = 0; codePoint <= 0x10ffff; codePoint++) { + if (codePoint >= 0xd800 && codePoint <= 0xdfff) continue; // lone surrogates are not characters + const text = `a${String.fromCodePoint(codePoint)}b`; + const split = pythonSplitWords(text).length === 2; + if (split !== python.has(codePoint)) wrong.push(`U+${codePoint.toString(16).padStart(4, '0')}`); + } + expect(wrong).toEqual([]); + }); + + it('is not JavaScript\'s \\s: the byte-order mark stays, the control separators and U+0085 split', () => { + expect(pythonSplitWords('a\ufeffb')).toEqual(['a\ufeffb']); + expect(pythonSplitWords('a\u001cb\u0085c')).toEqual(['a', 'b', 'c']); + }); + + it('ignores leading, trailing and repeated whitespace, and gives nothing for blank text', () => { + expect(pythonSplitWords(' a b\t\nc ')).toEqual(['a', 'b', 'c']); + expect(pythonSplitWords('')).toEqual([]); + expect(pythonSplitWords(' \u3000\u2028 ')).toEqual([]); + }); +}); diff --git a/codev/projects/358-whatsapp-typescript/358-phase_4-iter1-claude.txt b/codev/projects/358-whatsapp-typescript/358-phase_4-iter1-claude.txt new file mode 100644 index 00000000..af42b025 --- /dev/null +++ b/codev/projects/358-whatsapp-typescript/358-phase_4-iter1-claude.txt @@ -0,0 +1,35 @@ +NOTE: This is an agent self-review written by the implementing agent. It is NOT the output of a `consult` run; no external model was consulted (owner instruction: "don't consult; just self review"). + +Phase 4 (conversation manager): src/conversationManager.ts, src/utils/pythonText.ts, tests/conversationManager.test.ts, tests/pythonText.test.ts, and new Python-oracle tables. + +VERIFIED (by running it) +- `pnpm --filter ansari-whatsapp typecheck` exit 0, `lint` exit 0, `test` exit 0: 708 tests in 16 files (559 before this phase). +- The full suite was run 5 times and the manager tests 3 more times under 4 busy CPU loops: no failure, so the timing-based typing-indicator tests are not flaky on this machine. +- Mutation controls, one rule broken at a time, whole suite run, file restored and compared to the original: 37 mutations, 37 caught, 0 not caught, 0 skipped, 0 restore mismatches. They cover: maintenance mode, the staging "!d " filter (every-environment, no-space prefix), message age and threshold, type triage, reply addressing (phone ignored, no-recipient guard), Meta failure containment, each sign-in notice, rounding of the rate-limit minutes, the unsupported-type wording, each operator report tag and what travels with it, the 401 retry (forget, third attempt, 429 wording, second-401 report), thread expiry (boundary, retention setting), thread title (word count, whitespace set), timestamps without a time zone, a failed delete still creating a thread, whitespace-only answers, markdown conversion, and the typing indicator (stop, failed answer, maximum duration, a failed indicator, start before sign-in). +- Python's real answers, taken by running the legacy code (generate_python_oracle.py, new tables): the rate-limit notice for 15 waits, the unsupported-type notice for 19 message types, the thread title for 17 messages, and the full list of 29 code points `str.isspace()` accepts (checked against all 1,114,112 code points by tests/pythonText.test.ts). + +PORTED FROM PYTHON +- `WhatsAppConversationManager` and the checks in the webhook route of `main.py` (maintenance mode 503, "!d " filter 202, too old 422, unsupported 415, text 200). Notice texts are copied word for word, including the ".." in the thread-deletion notice. +- Python scenarios from test_thread_lifecycle.py, test_auth_statuses.py (last half), test_environment_behaviour.py (maintenance, "!d ", unsupported in staging), test_bsuid_auth_flow.py (reply addressing, no phone to apps/auth or apps/api, no identifiers in logs). + +DIFFERENCES FROM PYTHON (deliberate) +- One `ConversationManager` serves every message; per-message state (token, typing indicator) is a `Turn` object. Python built a manager per webhook. +- `triage()` returns what should happen and the HTTP layer (phase 5) maps it to status codes, then calls `dispatch()`. Python mixed both in the route. +- Settings, clients and the clock are passed in, not read from globals. +- A whitespace-only answer splits into nothing (phase 2 fix); the user gets "Sorry, we couldn't process your message. Please try again later." as for an empty answer. This is the phase-2 requirement, now implemented and tested. +- Two Python branches are not ported because they cannot be reached here: a thread-creation reply without an id (the apps/api client already refuses it) and an answer that formats to empty text (the formatter never empties non-empty text). +- Python's `isoformat` read of `last_message_time` refused a timestamp with no time zone; JavaScript would read it as server-local time. A regular expression requires `Z` or an offset and anything else is treated as an unexpected fault (user gets the "unexpected error" notice). +- Python's `str.split()` and JavaScript's `\s` differ (BOM, U+001C-U+001F, U+0085); a hand-written `pythonSplitWords` is used for the thread title and checked against Python's full list. +- The typing indicator is an `AbortController`-driven loop instead of an asyncio task. Python's "cancel" ends the sleep at once; so does `abort()` here. +- Python caught `Exception` in `handle_text_message`; here an unexpected fault is caught by the same outer handler, logged with its error, and gets the "unexpected" notice. The typing indicator is now stopped in a `finally`, so every exit ends it (Python cancelled it only on some exits). + +KNOWN LIMITS +- `dispatch()` is awaited by its caller. The un-awaited call with a catch-all (so a failure is never lost) is phase 5's job, as the plan says. Nothing here throws in normal use, but I did not prove that for every possible fault, only for the ones in the tests (including a RangeError from apps/api). +- Mock-only: the in-memory clients do not behave like the real services when a token changes (the mock gives each token its own threads), so the retry tests replace the thread calls to isolate the retry rule. +- The "Sentry" reporter is a function passed in; the real Sentry sender is wired in phase 5. + +NOT VERIFIED +- No real network call, no real apps/auth, apps/api or Meta behaviour (all fakes). +- The corner case in the thread-expiry comment (two quick messages after expiry giving two threads) was kept as a documented decision from spec 321; no test exercises it. + +VERDICT: COMMENT From 71f9a2c951255cd43504f3650bef6231ef155b0e Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 22:47:22 +0200 Subject: [PATCH 033/435] chore(porch): 358 implement build-complete --- codev/projects/358-whatsapp-typescript/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 1116e723..9b38a36e 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T20:09:01.447Z' +updated_at: '2026-11-10T20:47:22.364Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' From 7bf256ff365b48cdeae1e5d6dd02b68be211a914 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Tue, 10 Nov 2026 22:48:04 +0200 Subject: [PATCH 034/435] =?UTF-8?q?chore(porch):=20358=20advance=20plan=20?= =?UTF-8?q?phase=20=E2=86=92=20phase=5F5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codev/projects/358-whatsapp-typescript/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 9b38a36e..72240a24 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -14,17 +14,17 @@ plan_phases: status: complete - id: phase_4 title: Conversation manager - status: in_progress + status: complete - id: phase_5 title: 'HTTP app: webhook verification, signature check, immediate 200' - status: pending + status: in_progress - id: phase_6 title: Docker, Railway config, CI, turbo and documentation status: pending - id: phase_7 title: Staging redeploy, smoke test and legacy rollback note status: pending -current_plan_phase: phase_4 +current_plan_phase: phase_5 gates: spec-approval: status: approved @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T20:47:22.364Z' +updated_at: '2026-11-10T20:48:04.354Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -57,3 +57,5 @@ context_refreshes: - boundary: plan-phase:phase_4 at: '2026-11-10T20:03:04.356Z' acknowledged_at: '2026-11-10T20:09:01.441Z' + - boundary: plan-phase:phase_5 + at: '2026-11-10T20:48:04.354Z' From 2503663660d9022647c468200c9495ebb4c626f8 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 09:47:14 +1100 Subject: [PATCH 035/435] chore(porch): 364 init air --- .../364-apps-mcp-railway-staging-recor/status.yaml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 codev/projects/364-apps-mcp-railway-staging-recor/status.yaml diff --git a/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml b/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml new file mode 100644 index 00000000..99779b2c --- /dev/null +++ b/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml @@ -0,0 +1,14 @@ +id: '364' +title: apps-mcp-railway-staging-recor +protocol: air +phase: implement +plan_phases: [] +current_plan_phase: null +gates: + pr: + status: pending +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-10T22:47:14.565Z' +updated_at: '2026-11-10T22:47:14.566Z' From 28c9359c3d6b4d102bebbaab0a8127eb5ffbd0a6 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 09:51:19 +1100 Subject: [PATCH 036/435] [Air #364] feat: apps/mcp Railway staging record (railway.toml + RELEASE.md) --- RELEASE.md | 24 ++++++++++-- apps/api/tests/release-doc.test.ts | 59 +++++++++++++++++++++++++++++- apps/mcp/README.md | 2 + apps/mcp/railway.toml | 39 ++++++++++++++++++++ codev/resources/arch-critical.md | 2 +- codev/resources/arch.md | 2 +- codev/state/air-364_thread.md | 7 ++++ 7 files changed, 129 insertions(+), 6 deletions(-) create mode 100644 apps/mcp/railway.toml create mode 100644 codev/state/air-364_thread.md diff --git a/RELEASE.md b/RELEASE.md index 51735f9a..d28b8c62 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -39,6 +39,7 @@ migration runbook were both proven in real releases on 2026-08-02. > | frontend (web) | `apps/frontend/Dockerfile.web` | > | auth | `apps/auth/Dockerfile` | > | whatsapp | `legacy/whatsapp/Dockerfile` | +> | mcp | `apps/mcp/Dockerfile` | > > **Watch paths** — set these per service, or Railway rebuilds *both* on every push > (any commit touches the root lockfile): @@ -48,18 +49,19 @@ migration runbook were both proven in real releases on 2026-08-02. > frontend: apps/frontend/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml > auth: apps/auth/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml > whatsapp: legacy/whatsapp/** .dockerignore +> mcp: apps/mcp/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml .dockerignore > ``` > -> For backend, frontend and auth, `packages/**` is **not optional**. The shared config packages are copied into those +> For backend, frontend, auth and mcp, `packages/**` is **not optional**. The shared config packages are copied into those > images, so a packages-only change alters the built artifact. Omit the pattern and > that change ships nothing — no rebuild, no deploy, and no error. The image simply > drifts from the repo. **whatsapp is the exception:** it is a Python service outside the pnpm workspace, so its image contains nothing from > `packages/`, the root lockfile or `package.json`; watching them would only rebuild it for changes it does not ship. -> It does add `.dockerignore`: the image builds from the repo root, so that file decides what the build can see. +> whatsapp and mcp add `.dockerignore`: their images build from the repo root, so that file decides what the build can see. > > **Deploy settings** — backend healthcheck `/api/health` (timeout 300s), frontend > healthcheck `/`, whatsapp healthcheck `/`, auth healthcheck `/health` (200 only when the auth database -> answers; timeout 300s); restart ON_FAILURE, max 3 retries. +> answers; timeout 300s), mcp healthcheck `/health` (timeout 300s); restart ON_FAILURE, max 3 retries. > > > **whatsapp service (spec 321, interim Python import; lives in `legacy/` because `apps/*` is reserved for the @@ -75,6 +77,22 @@ migration runbook were both proven in real releases on 2026-08-02. > The service refuses to start if a secret above is missing, or if any `MOCK_*` switch is set outside > `DEPLOYMENT_TYPE=local`. > +> **mcp service (issue #364; staging only for now)** — one listener on `PORT` (3000 by default; the public domain's +> target port must match). Build: repo-root context, `apps/mcp/Dockerfile`, which copies `package.json`, the lockfile, +> the workspace file and `packages/` and runs the root `mcp` script. Health check `/health`. Hosts connect at +> `https:///mcp`. Its settings are recorded in `apps/mcp/railway.toml`. Environment, for staging +> (`mcp-staging.askansari.ai`; full list in `apps/mcp/README.md`): +> +> | Variable | Value | +> |---|---| +> | `MCP_ALLOWED_HOSTS` | `mcp-staging.askansari.ai` (the server refuses any other Host on `/mcp`) | +> | `ANSARI_API_BASE_URL` | `https://api-staging.askansari.ai` (the default is production) | +> | `ANSARI_CLIENT` | `ansari-mcp-staging` | +> +> `ANSARI_RELEASE` is **not** set: the release falls back to `RAILWAY_GIT_COMMIT_SHA`. `MCP_ALLOWED_ORIGINS` is left +> unset at first: it defaults to the allowed hosts, and requests without an Origin pass. The Cloudflare Workers path +> (`apps/mcp/wrangler.jsonc`) is not this deployment. +> > **auth service (spec 300)** — one listener: the public domain > (`auth.askansari.ai`, `auth-staging.askansari.ai`) targets `PORT` (3100); set it as > a service variable. `backend` reaches it at that domain too (`AUTH_URL`), like any diff --git a/apps/api/tests/release-doc.test.ts b/apps/api/tests/release-doc.test.ts index 095622f0..cd06a337 100644 --- a/apps/api/tests/release-doc.test.ts +++ b/apps/api/tests/release-doc.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -125,6 +125,63 @@ describe('RELEASE.md consistency', () => { expect(existsSync(resolve(apiDir, 'scripts/grant-admin.ts'))).toBe(false); }); + describe('Railway service records match the RELEASE.md block', () => { + // The tomls are not read by Railway; RELEASE.md and the tomls are two records of + // one dashboard, so each toml's Dockerfile, watch paths and health check must + // appear in RELEASE.md exactly. Service names are the RELEASE.md (dashboard) names. + const services: Record = { + backend: 'apps/api/railway.toml', + frontend: 'apps/frontend/railway.toml', + auth: 'apps/auth/railway.toml', + whatsapp: 'legacy/whatsapp/railway.toml', + mcp: 'apps/mcp/railway.toml', + }; + + function readToml(rel: string) { + // Comments dropped first, so a commented-out pattern never counts. + const text = readFileSync(resolve(repoRoot, rel), 'utf8').replace(/#.*$/gm, ''); + const value = (key: string) => text.match(new RegExp(`^${key} = "([^"]*)"`, 'm'))?.[1]; + const block = text.match(/^watchPatterns = \[([\s\S]*?)\]/m)?.[1] ?? ''; + return { + dockerfilePath: value('dockerfilePath'), + healthcheckPath: value('healthcheckPath'), + watchPatterns: [...block.matchAll(/"([^"]+)"/g)].map((m) => m[1]), + restart: value('restartPolicyType'), + }; + } + + it('lists every railway.toml in the repo', () => { + const tomls = ['apps', 'legacy'] + .flatMap((dir) => readdirSync(resolve(repoRoot, dir)).map((name) => `${dir}/${name}/railway.toml`)) + .filter((rel) => existsSync(resolve(repoRoot, rel))); + expect(tomls.sort()).toEqual(Object.values(services).sort()); + }); + + for (const [service, rel] of Object.entries(services)) { + it(`${service}: Dockerfile row, watch-path line and health check match ${rel}`, () => { + const toml = readToml(rel); + expect(toml.dockerfilePath).toBeTruthy(); + expect(toml.restart).toBe('ON_FAILURE'); + expect(doc).toMatch(new RegExp(`^> \\| ${service}( \\(web\\))? \\| \`${toml.dockerfilePath}\` \\|$`, 'm')); + + const line = doc.match(new RegExp(`^> ${service}:(.*)$`, 'm'))?.[1]; + expect(line, `no watch-path line for ${service}`).toBeDefined(); + expect(line!.trim().split(/\s+/)).toEqual(toml.watchPatterns); + + // The deploy-settings sentence wraps across quoted lines; read it as one line. + expect(doc.replace(/\n> /g, ' ')).toContain(`${service} healthcheck \`${toml.healthcheckPath}\``); + }); + } + + it('records the mcp staging environment (issue #364)', () => { + expect(doc).toContain('| `MCP_ALLOWED_HOSTS` | `mcp-staging.askansari.ai`'); + expect(doc).toContain('| `ANSARI_API_BASE_URL` | `https://api-staging.askansari.ai`'); + expect(doc).toContain('| `ANSARI_CLIENT` | `ansari-mcp-staging` |'); + expect(doc).toContain('`ANSARI_RELEASE` is **not** set'); + expect(doc).toContain('`https:///mcp`'); + }); + }); + it('pins exactly the two production health-check domains', () => { expect(doc).toContain('https://api.askansari.ai/api/health'); expect(doc).toContain('https://api-35.ansari.chat/api/health'); diff --git a/apps/mcp/README.md b/apps/mcp/README.md index b983f99b..16f1009d 100644 --- a/apps/mcp/README.md +++ b/apps/mcp/README.md @@ -131,6 +131,8 @@ Artwork is embedded as actual SVG/PNG data in application-local TypeScript modul The `MCP application` workflow runs for app, lockfile, workspace, root manifest/ignore, workflow and shared lint configuration changes on PRs and develop/main pushes. It installs the root lockfile frozen, then runs app lint, typechecking, both builds, tests and browser checks. `bash apps/mcp/scripts/verify-container.sh` performs one uncached root-context Docker build and verifies health, synthetic tool calls, full attribution, safe failure/recovery and resource identity in a container with no external network or mounted files. It removes its container and image on exit. Node 22, pnpm 10.33, Docker and Chromium system dependencies are required. +The Docker image is deployed to Railway **staging** only (`mcp-staging.askansari.ai`; hosts connect at `https:///mcp`). Its settings are recorded in `apps/mcp/railway.toml` (not read by Railway: the dashboard is the live configuration) and its staging environment in `RELEASE.md`. The Workers path is not deployed. + This job needs no host credentials. Deployment and actual ChatGPT, Claude and Alexa rendering remain separate integration checks. diff --git a/apps/mcp/railway.toml b/apps/mcp/railway.toml new file mode 100644 index 00000000..084d3241 --- /dev/null +++ b/apps/mcp/railway.toml @@ -0,0 +1,39 @@ +# Railway settings for the `mcp` service (apps/mcp), kept in version control. +# +# NOT READ BY RAILWAY IN THIS PROJECT (the same as apps/api/railway.toml; see the +# "Railway service configuration" block in RELEASE.md). The dashboard is the live +# configuration; this file is the reviewable record of what it should contain. +# The service exists in Railway's staging environment only +# (mcp-staging.askansari.ai), not in production: confirm every value there. +# The Cloudflare Workers target (wrangler.jsonc) is not this deployment. +# +# Keep the two in sync: if you change a dashboard setting, update this file in the +# same PR. +# +# Build context: the repo root (docker build -f apps/mcp/Dockerfile .), never +# apps/mcp: the Dockerfile copies the root manifest, lockfile and workspace file +# and packages/, and the build runs the root `mcp` script. + +[build] +builder = "dockerfile" +dockerfilePath = "apps/mcp/Dockerfile" +watchPatterns = [ + "apps/mcp/**", + # Shared workspace packages are COPYied into this image (see the Dockerfile), + # so a packages-only change alters the built artifact. Without this pattern the + # change ships nothing: no rebuild, no deploy, no error. + "packages/**", + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + # The image builds from the repo root, so this file decides what the build can see. + ".dockerignore", +] + +[deploy] +# /health answers {ok, mcp, release}. The app listens on PORT (3000 by default); +# the domain's target port must match. +healthcheckPath = "/health" +healthcheckTimeout = 300 +restartPolicyType = "ON_FAILURE" +restartPolicyMaxRetries = 3 diff --git a/codev/resources/arch-critical.md b/codev/resources/arch-critical.md index e67b75fa..46d66f93 100644 --- a/codev/resources/arch-critical.md +++ b/codev/resources/arch-critical.md @@ -15,7 +15,7 @@ STARTER: replace the examples below with YOUR project's facts and arch.md sectio - DB schema changes: `drizzle-kit generate` → review SQL → human-applied at deploy. NEVER `db:push`. Apply with `psql -v ON_ERROR_STOP=1 --single-transaction`, naming the database. Deploy order: migration → admin bootstrap (`apps/auth/scripts/grant-admin.ts`) → deploy. A PR whose tested DB paths name a new column fails `apps/api/tests/migration/migration-schema-parity.test.ts` until it bumps `DEPLOYED_THROUGH`. The bump is a human ASSERTION that the migration will be applied before deploy, NOT proof that it was. Nothing checks the target DB yet (#176), so the #165 outage class (code shipped, migration never run) is still possible. - Turborepo runs STRICT env mode: a var missing from `turbo.json` `globalEnv` is invisible to tasks AND absent from the cache key — a cached artifact can ship wrong values while reporting a hit. Derive additions four ways (Zod schema, static `process.env.X`, dynamic `process.env[`, documented env surface). - A `workspace:*` dependency does NOT put a package's contents in a consumer's cache hash; shared packages must ALSO be listed in `globalDependencies`, or a warm cache replays stale results against changed shared config. -- Railway deploy config is the DASHBOARD, not `apps/*/railway.toml` — the tomls are the reviewable git record only. Watch paths must include `packages/**`, since both images copy it. +- Railway deploy config is the DASHBOARD, not `apps/*/railway.toml` — the tomls are the reviewable git record only. Watch paths of the TypeScript services (api, auth, frontend, mcp) must include `packages/**`, since their images copy it. - Vertex rejects any turn after a `functionCall` model turn that lacks EXACTLY matching `functionResponse` parts; `messages.raw_payload` therefore stores only the FINAL model turn, guard-checked to carry zero functionCall parts. Tool history lives in `messages.tool_calls` (+ `tool_call_orphans` for error turns). NO API response may serialize raw tool records or `raw_payload`: the thread read helpers project `tool_calls` out, and `raw_payload` stays in `messageReadColumns` for replay only. The ONE serving reader of `tool_calls` is `lib/db/citable-documents.ts`, which returns derived `document` blocks only, served by the separate `/documents` endpoints (spec 168). Thread GET and share GET carry no documents. The mobile contract is frozen: single-text `content` must stay a bare string. ## Map of arch.md (consult when…) diff --git a/codev/resources/arch.md b/codev/resources/arch.md index db8dd95b..da3d3f98 100644 --- a/codev/resources/arch.md +++ b/codev/resources/arch.md @@ -60,7 +60,7 @@ The repo is a pnpm workspace of `apps/*` and `packages/*`, driven by Turborepo. **Shared packages in the cache hash.** A `workspace:*` dependency does not put a package's contents into a consumer's cache hash. Shared packages must also be listed in `globalDependencies`, or a warm cache replays stale results against changed shared config. **Refinement (spec 59):** this bites per-task, gated by the `^` prefix in `dependsOn`. A task with a `^`-prefixed dependency (e.g. `build`'s `^build`) *does* traverse its internal dependencies' package hashes and busts on their edits without a `globalDependencies` line; a task with only un-prefixed deps (this repo's `typecheck` → `["gen:types"]`, `lint` → none) does **not** traverse them and needs the `globalDependencies` entry. Verified per-task in both directions: `apps/auth#typecheck` needed `packages/auth/src/**` listed to bust on `@ansari/auth` edits, while `apps/auth#build` busted either way. Listing a shared package is never wrong, so the prescriptive rule stands; this explains why some tasks appear "already covered". -**Railway deployment.** Deploy configuration lives in the Railway dashboard, not in `apps/*/railway.toml` — the tomls are the reviewable git record only. Watch paths must include `packages/**`, since both images copy it. +**Railway deployment.** Deploy configuration lives in the Railway dashboard, not in `apps/*/railway.toml` — the tomls are the reviewable git record only (`apps/api`, `apps/auth`, `apps/frontend`, `apps/mcp`, `legacy/whatsapp`). Watch paths of the TypeScript services must include `packages/**`, since their images copy it; `apps/mcp` runs in Railway staging only (issue #364), and its Workers target (`wrangler.jsonc`) is not deployed. **The frontend app (`apps/frontend`, since #262).** The former SDK 54 prototype (outside the workspace until #262) is now the workspace member `ansari-frontend`, on Expo SDK 57 / RN 0.86 / React 19.2, with a vitest suite that CI runs in the `frontend` job (job name frozen). Its store identity is the **legacy app's** (`legacy/frontend-app/app.json`): name "Ansari", slug `ansari-chat`, `chat.ansari.app`, EAS project `e2f465a7-…`, **scheme `ansarichat`**. That scheme is coupled to `packages/auth`'s Better Auth `trustedOrigins` (`'ansarichat://'`); change both together, or native sign-in fails origin validation later with nothing failing at build time. `auth.http.test.ts` pins the pair: it reads `apps/frontend/app.json` and asserts `${expo.scheme}://` is trusted, and it rejects the old `askansari://`. `packages/auth/turbo.json` declares that manifest as a `test` input (`$TURBO_ROOT$/apps/frontend/app.json`), because a file outside the package is not hashed by default and a warm cache would replay the guard instead of running it. The app's whole env surface is `EXPO_PUBLIC_API_URL` (default api-staging), the only ARG in `Dockerfile.web`. Uniwind is installed and wired (metro `withUniwindConfig`, `src/global.css`, `gen:types`) but **unused**: the UI is StyleSheet-only, and `app/_layout.tsx` deliberately does not import `global.css` because Tailwind's preflight reset would restyle the web. `vendor/api-client-react/` keeps only `custom-fetch.ts` (the fetch runtime) and `generated/api.schemas.ts` (types); retiring both is #264. diff --git a/codev/state/air-364_thread.md b/codev/state/air-364_thread.md new file mode 100644 index 00000000..7717a946 --- /dev/null +++ b/codev/state/air-364_thread.md @@ -0,0 +1,7 @@ +# air-364 thread — apps/mcp Railway staging record + +- 2026-11-11: Added `apps/mcp/railway.toml` (dockerfile build, repo-root context, watch paths incl. `packages/**` and `.dockerignore`, `/health`, ON_FAILURE x3; healthcheckTimeout 300 like the others — the issue did not name a timeout). +- RELEASE.md: mcp Dockerfile row, watch-path line, `/health` in deploy settings, mcp service paragraph with the staging env table. +- Fixed "both images copy it" (stale: four TS images now) in arch.md and arch-critical.md; added a staging deployment note to apps/mcp/README.md. +- New test in `apps/api/tests/release-doc.test.ts`: every `apps/*|legacy/*/railway.toml` must be listed, and its dockerfilePath, watchPatterns and healthcheckPath must match RELEASE.md. Negative-tested: dropping `packages/**` from the RELEASE mcp line fails, changing the toml health path fails; restored passes. +- No apps/mcp code touched. From 4d851ad8076ae8c996c3e33b65d8b88c44321e9a Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 09:53:29 +1100 Subject: [PATCH 037/435] chore(porch): 364 pr phase-transition --- codev/projects/364-apps-mcp-railway-staging-recor/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml b/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml index 99779b2c..b39863f0 100644 --- a/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml +++ b/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml @@ -1,7 +1,7 @@ id: '364' title: apps-mcp-railway-staging-recor protocol: air -phase: implement +phase: pr plan_phases: [] current_plan_phase: null gates: @@ -11,4 +11,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-10T22:47:14.565Z' -updated_at: '2026-11-10T22:47:14.566Z' +updated_at: '2026-11-10T22:53:29.233Z' From 93b8acded78151774c5b2dc78f2f1af549ae3f05 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 09:53:53 +1100 Subject: [PATCH 038/435] chore(porch): 364 record PR #365 --- .../364-apps-mcp-railway-staging-recor/status.yaml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml b/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml index b39863f0..f6f34d9b 100644 --- a/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml +++ b/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml @@ -11,4 +11,9 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-10T22:47:14.565Z' -updated_at: '2026-11-10T22:53:29.233Z' +updated_at: '2026-11-10T22:53:53.565Z' +pr_history: + - phase: pr + pr_number: 365 + branch: builder/air-364 + created_at: '2026-11-10T22:53:53.565Z' From 1bad891309554eb374ed1e34f7c3e7d7c601ddd1 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 09:53:56 +1100 Subject: [PATCH 039/435] chore(porch): 364 pr gate-requested --- codev/projects/364-apps-mcp-railway-staging-recor/status.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml b/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml index f6f34d9b..e7f4b9c8 100644 --- a/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml +++ b/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml @@ -7,13 +7,15 @@ current_plan_phase: null gates: pr: status: pending + requested_at: '2026-11-10T22:53:56.452Z' iteration: 1 build_complete: false history: [] started_at: '2026-11-10T22:47:14.565Z' -updated_at: '2026-11-10T22:53:53.565Z' +updated_at: '2026-11-10T22:53:56.453Z' pr_history: - phase: pr pr_number: 365 branch: builder/air-364 created_at: '2026-11-10T22:53:53.565Z' +pr_ready_for_human: true From 7568ab2dbe4b01a732dcc6bb4c92bebb24bcbc24 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 10:02:16 +1100 Subject: [PATCH 040/435] [Air #364] fix: address PR #365 review (turbo inputs, defensive packages wording, PORT=3000, stale 'both') --- RELEASE.md | 13 ++++++++----- apps/api/tests/release-doc.test.ts | 4 +++- apps/api/turbo.json | 8 +++++++- apps/mcp/railway.toml | 13 ++++++++----- codev/resources/arch-critical.md | 2 +- codev/resources/arch.md | 2 +- codev/state/air-364_thread.md | 1 + 7 files changed, 29 insertions(+), 14 deletions(-) diff --git a/RELEASE.md b/RELEASE.md index d28b8c62..107e734d 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -41,7 +41,7 @@ migration runbook were both proven in real releases on 2026-08-02. > | whatsapp | `legacy/whatsapp/Dockerfile` | > | mcp | `apps/mcp/Dockerfile` | > -> **Watch paths** — set these per service, or Railway rebuilds *both* on every push +> **Watch paths** — set these per service, or Railway rebuilds *every* service on every push > (any commit touches the root lockfile): > > ``` @@ -52,10 +52,13 @@ migration runbook were both proven in real releases on 2026-08-02. > mcp: apps/mcp/** packages/** package.json pnpm-lock.yaml pnpm-workspace.yaml .dockerignore > ``` > -> For backend, frontend, auth and mcp, `packages/**` is **not optional**. The shared config packages are copied into those +> For backend, frontend and auth, `packages/**` is **not optional**. The shared config packages are copied into those > images, so a packages-only change alters the built artifact. Omit the pattern and > that change ships nothing — no rebuild, no deploy, and no error. The image simply -> drifts from the repo. **whatsapp is the exception:** it is a Python service outside the pnpm workspace, so its image contains nothing from +> drifts from the repo. **mcp watches it defensively:** its build stage copies `packages/` and installs from it, but +> its only workspace dependency is a devDependency (`@ansari/eslint-config`) and its final image is `dist` plus +> `package.json`, so today a packages-only change does not alter the shipped image. The pattern stays so that a future +> runtime dependency cannot ship silently. **whatsapp is the exception:** it is a Python service outside the pnpm workspace, so its image contains nothing from > `packages/`, the root lockfile or `package.json`; watching them would only rebuild it for changes it does not ship. > whatsapp and mcp add `.dockerignore`: their images build from the repo root, so that file decides what the build can see. > @@ -77,8 +80,8 @@ migration runbook were both proven in real releases on 2026-08-02. > The service refuses to start if a secret above is missing, or if any `MOCK_*` switch is set outside > `DEPLOYMENT_TYPE=local`. > -> **mcp service (issue #364; staging only for now)** — one listener on `PORT` (3000 by default; the public domain's -> target port must match). Build: repo-root context, `apps/mcp/Dockerfile`, which copies `package.json`, the lockfile, +> **mcp service (issue #364; staging only for now)** — one listener on `PORT` (3000): set `PORT=3000` as a +> service variable so Railway does not assign its own, and make the public domain's target port match. Build: repo-root context, `apps/mcp/Dockerfile`, which copies `package.json`, the lockfile, > the workspace file and `packages/` and runs the root `mcp` script. Health check `/health`. Hosts connect at > `https:///mcp`. Its settings are recorded in `apps/mcp/railway.toml`. Environment, for staging > (`mcp-staging.askansari.ai`; full list in `apps/mcp/README.md`): diff --git a/apps/api/tests/release-doc.test.ts b/apps/api/tests/release-doc.test.ts index cd06a337..9bf89297 100644 --- a/apps/api/tests/release-doc.test.ts +++ b/apps/api/tests/release-doc.test.ts @@ -162,7 +162,8 @@ describe('RELEASE.md consistency', () => { const toml = readToml(rel); expect(toml.dockerfilePath).toBeTruthy(); expect(toml.restart).toBe('ON_FAILURE'); - expect(doc).toMatch(new RegExp(`^> \\| ${service}( \\(web\\))? \\| \`${toml.dockerfilePath}\` \\|$`, 'm')); + const dockerfile = toml.dockerfilePath!.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + expect(doc).toMatch(new RegExp(`^> \\| ${service}( \\(web\\))? \\| \`${dockerfile}\` \\|$`, 'm')); const line = doc.match(new RegExp(`^> ${service}:(.*)$`, 'm'))?.[1]; expect(line, `no watch-path line for ${service}`).toBeDefined(); @@ -179,6 +180,7 @@ describe('RELEASE.md consistency', () => { expect(doc).toContain('| `ANSARI_CLIENT` | `ansari-mcp-staging` |'); expect(doc).toContain('`ANSARI_RELEASE` is **not** set'); expect(doc).toContain('`https:///mcp`'); + expect(doc.replace(/\n> /g, ' ')).toContain('set `PORT=3000` as a service variable so Railway does not assign its own'); }); }); diff --git a/apps/api/turbo.json b/apps/api/turbo.json index b72610cd..dd6d7a26 100644 --- a/apps/api/turbo.json +++ b/apps/api/turbo.json @@ -19,6 +19,10 @@ // The root package.json is here for root-test-script.test.ts (issue #330), // which pins the root `test` script's worker cap: without it, removing the // cap left this task at the same hash and a warm cache replayed the pin green. + // + // The railway tomls are here for release-doc.test.ts (issue #364), which + // checks each one against RELEASE.md: without them a toml-only edit left this + // task at the same hash and a warm cache replayed the check green. "test": { "inputs": [ "$TURBO_DEFAULT$", @@ -37,7 +41,9 @@ "$TURBO_ROOT$/.github/workflows/**", "$TURBO_ROOT$/.gitleaksignore", "$TURBO_ROOT$/.gitleaks.toml", - "$TURBO_ROOT$/package.json" + "$TURBO_ROOT$/package.json", + "$TURBO_ROOT$/apps/*/railway.toml", + "$TURBO_ROOT$/legacy/*/railway.toml" ] }, diff --git a/apps/mcp/railway.toml b/apps/mcp/railway.toml index 084d3241..7900b5d8 100644 --- a/apps/mcp/railway.toml +++ b/apps/mcp/railway.toml @@ -19,9 +19,11 @@ builder = "dockerfile" dockerfilePath = "apps/mcp/Dockerfile" watchPatterns = [ "apps/mcp/**", - # Shared workspace packages are COPYied into this image (see the Dockerfile), - # so a packages-only change alters the built artifact. Without this pattern the - # change ships nothing: no rebuild, no deploy, no error. + # Defensive: the build stage copies packages/ and installs from it, but the + # only workspace dependency is a devDependency (@ansari/eslint-config) and the + # final image is dist plus package.json, so today a packages-only change does + # not alter the shipped image. Kept so a future runtime dependency on a shared + # package cannot ship silently. "packages/**", "package.json", "pnpm-lock.yaml", @@ -31,8 +33,9 @@ watchPatterns = [ ] [deploy] -# /health answers {ok, mcp, release}. The app listens on PORT (3000 by default); -# the domain's target port must match. +# /health answers {ok, mcp, release}. The app listens on PORT: set PORT=3000 as +# a service variable so Railway does not assign its own, and make the domain's +# target port match. healthcheckPath = "/health" healthcheckTimeout = 300 restartPolicyType = "ON_FAILURE" diff --git a/codev/resources/arch-critical.md b/codev/resources/arch-critical.md index 46d66f93..a42f651b 100644 --- a/codev/resources/arch-critical.md +++ b/codev/resources/arch-critical.md @@ -15,7 +15,7 @@ STARTER: replace the examples below with YOUR project's facts and arch.md sectio - DB schema changes: `drizzle-kit generate` → review SQL → human-applied at deploy. NEVER `db:push`. Apply with `psql -v ON_ERROR_STOP=1 --single-transaction`, naming the database. Deploy order: migration → admin bootstrap (`apps/auth/scripts/grant-admin.ts`) → deploy. A PR whose tested DB paths name a new column fails `apps/api/tests/migration/migration-schema-parity.test.ts` until it bumps `DEPLOYED_THROUGH`. The bump is a human ASSERTION that the migration will be applied before deploy, NOT proof that it was. Nothing checks the target DB yet (#176), so the #165 outage class (code shipped, migration never run) is still possible. - Turborepo runs STRICT env mode: a var missing from `turbo.json` `globalEnv` is invisible to tasks AND absent from the cache key — a cached artifact can ship wrong values while reporting a hit. Derive additions four ways (Zod schema, static `process.env.X`, dynamic `process.env[`, documented env surface). - A `workspace:*` dependency does NOT put a package's contents in a consumer's cache hash; shared packages must ALSO be listed in `globalDependencies`, or a warm cache replays stale results against changed shared config. -- Railway deploy config is the DASHBOARD, not `apps/*/railway.toml` — the tomls are the reviewable git record only. Watch paths of the TypeScript services (api, auth, frontend, mcp) must include `packages/**`, since their images copy it. +- Railway deploy config is the DASHBOARD, not `apps/*/railway.toml` — the tomls are the reviewable git record only. Watch paths of api, auth, frontend and mcp must include `packages/**`: the api, auth and frontend images ship `packages/`; mcp watches it defensively. - Vertex rejects any turn after a `functionCall` model turn that lacks EXACTLY matching `functionResponse` parts; `messages.raw_payload` therefore stores only the FINAL model turn, guard-checked to carry zero functionCall parts. Tool history lives in `messages.tool_calls` (+ `tool_call_orphans` for error turns). NO API response may serialize raw tool records or `raw_payload`: the thread read helpers project `tool_calls` out, and `raw_payload` stays in `messageReadColumns` for replay only. The ONE serving reader of `tool_calls` is `lib/db/citable-documents.ts`, which returns derived `document` blocks only, served by the separate `/documents` endpoints (spec 168). Thread GET and share GET carry no documents. The mobile contract is frozen: single-text `content` must stay a bare string. ## Map of arch.md (consult when…) diff --git a/codev/resources/arch.md b/codev/resources/arch.md index da3d3f98..db8869b3 100644 --- a/codev/resources/arch.md +++ b/codev/resources/arch.md @@ -60,7 +60,7 @@ The repo is a pnpm workspace of `apps/*` and `packages/*`, driven by Turborepo. **Shared packages in the cache hash.** A `workspace:*` dependency does not put a package's contents into a consumer's cache hash. Shared packages must also be listed in `globalDependencies`, or a warm cache replays stale results against changed shared config. **Refinement (spec 59):** this bites per-task, gated by the `^` prefix in `dependsOn`. A task with a `^`-prefixed dependency (e.g. `build`'s `^build`) *does* traverse its internal dependencies' package hashes and busts on their edits without a `globalDependencies` line; a task with only un-prefixed deps (this repo's `typecheck` → `["gen:types"]`, `lint` → none) does **not** traverse them and needs the `globalDependencies` entry. Verified per-task in both directions: `apps/auth#typecheck` needed `packages/auth/src/**` listed to bust on `@ansari/auth` edits, while `apps/auth#build` busted either way. Listing a shared package is never wrong, so the prescriptive rule stands; this explains why some tasks appear "already covered". -**Railway deployment.** Deploy configuration lives in the Railway dashboard, not in `apps/*/railway.toml` — the tomls are the reviewable git record only (`apps/api`, `apps/auth`, `apps/frontend`, `apps/mcp`, `legacy/whatsapp`). Watch paths of the TypeScript services must include `packages/**`, since their images copy it; `apps/mcp` runs in Railway staging only (issue #364), and its Workers target (`wrangler.jsonc`) is not deployed. +**Railway deployment.** Deploy configuration lives in the Railway dashboard, not in `apps/*/railway.toml` — the tomls are the reviewable git record only (`apps/api`, `apps/auth`, `apps/frontend`, `apps/mcp`, `legacy/whatsapp`). Watch paths of the TypeScript services must include `packages/**`: the api, auth and frontend images ship `packages/`, and mcp watches it defensively (its build stage installs from it, but no runtime dependency on it ships today); `apps/mcp` runs in Railway staging only (issue #364), and its Workers target (`wrangler.jsonc`) is not deployed. **The frontend app (`apps/frontend`, since #262).** The former SDK 54 prototype (outside the workspace until #262) is now the workspace member `ansari-frontend`, on Expo SDK 57 / RN 0.86 / React 19.2, with a vitest suite that CI runs in the `frontend` job (job name frozen). Its store identity is the **legacy app's** (`legacy/frontend-app/app.json`): name "Ansari", slug `ansari-chat`, `chat.ansari.app`, EAS project `e2f465a7-…`, **scheme `ansarichat`**. That scheme is coupled to `packages/auth`'s Better Auth `trustedOrigins` (`'ansarichat://'`); change both together, or native sign-in fails origin validation later with nothing failing at build time. `auth.http.test.ts` pins the pair: it reads `apps/frontend/app.json` and asserts `${expo.scheme}://` is trusted, and it rejects the old `askansari://`. `packages/auth/turbo.json` declares that manifest as a `test` input (`$TURBO_ROOT$/apps/frontend/app.json`), because a file outside the package is not hashed by default and a warm cache would replay the guard instead of running it. The app's whole env surface is `EXPO_PUBLIC_API_URL` (default api-staging), the only ARG in `Dockerfile.web`. Uniwind is installed and wired (metro `withUniwindConfig`, `src/global.css`, `gen:types`) but **unused**: the UI is StyleSheet-only, and `app/_layout.tsx` deliberately does not import `global.css` because Tailwind's preflight reset would restyle the web. `vendor/api-client-react/` keeps only `custom-fetch.ts` (the fetch runtime) and `generated/api.schemas.ts` (types); retiring both is #264. diff --git a/codev/state/air-364_thread.md b/codev/state/air-364_thread.md index 7717a946..a1bd03a8 100644 --- a/codev/state/air-364_thread.md +++ b/codev/state/air-364_thread.md @@ -5,3 +5,4 @@ - Fixed "both images copy it" (stale: four TS images now) in arch.md and arch-critical.md; added a staging deployment note to apps/mcp/README.md. - New test in `apps/api/tests/release-doc.test.ts`: every `apps/*|legacy/*/railway.toml` must be listed, and its dockerfilePath, watchPatterns and healthcheckPath must match RELEASE.md. Negative-tested: dropping `packages/**` from the RELEASE mcp line fails, changing the toml health path fails; restored passes. - No apps/mcp code touched. +- 2026-11-11 review round 1 (architect, PR #365): (1) added `$TURBO_ROOT$/apps/*/railway.toml` and `legacy/*/railway.toml` to ansari-api#test inputs — verified the hash did NOT move on a toml edit before, moves after (both globs), returns on restore; (2) mcp `packages/**` reworded as defensive (only workspace dep is the eslint-config devDependency; final image is dist + package.json) in RELEASE.md, toml, arch.md, arch-critical.md; (3) `PORT=3000` as a service variable, auth's phrasing, pinned in the test; (4) RELEASE.md "rebuilds *both*" → "*every* service"; optional: dockerfilePath regex-escaped. From 10f304bd29363a95c274cbc0d6e196e85b9f85a8 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 13:24:04 +1100 Subject: [PATCH 041/435] chore(porch): 364 pr gate-approved --- .../364-apps-mcp-railway-staging-recor/status.yaml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml b/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml index e7f4b9c8..52f55338 100644 --- a/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml +++ b/codev/projects/364-apps-mcp-railway-staging-recor/status.yaml @@ -6,16 +6,17 @@ plan_phases: [] current_plan_phase: null gates: pr: - status: pending + status: approved requested_at: '2026-11-10T22:53:56.452Z' + approved_at: '2026-11-11T02:24:04.945Z' iteration: 1 build_complete: false history: [] started_at: '2026-11-10T22:47:14.565Z' -updated_at: '2026-11-10T22:53:56.453Z' +updated_at: '2026-11-11T02:24:04.946Z' pr_history: - phase: pr pr_number: 365 branch: builder/air-364 created_at: '2026-11-10T22:53:53.565Z' -pr_ready_for_human: true +pr_ready_for_human: false From cfb09e3a73ae6d71f60bcba92b6cce926cabbb81 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 13:46:41 +1100 Subject: [PATCH 042/435] chore(porch): bugfix-366 init bugfix --- .../status.yaml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml diff --git a/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml new file mode 100644 index 00000000..f326662a --- /dev/null +++ b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml @@ -0,0 +1,14 @@ +id: bugfix-366 +title: mcp-complete-attribution-link- +protocol: bugfix +phase: investigate +plan_phases: [] +current_plan_phase: null +gates: + pr: + status: pending +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-11T02:46:41.302Z' +updated_at: '2026-11-11T02:46:41.303Z' From aaddd979ff4a682703b055e8dcb156240475fc7c Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 13:47:01 +1100 Subject: [PATCH 043/435] chore(porch): bugfix-366 fix phase-transition --- .../bugfix-366-mcp-complete-attribution-link-/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml index f326662a..b079d72c 100644 --- a/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml +++ b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml @@ -1,7 +1,7 @@ id: bugfix-366 title: mcp-complete-attribution-link- protocol: bugfix -phase: investigate +phase: fix plan_phases: [] current_plan_phase: null gates: @@ -11,4 +11,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-11T02:46:41.302Z' -updated_at: '2026-11-11T02:46:41.303Z' +updated_at: '2026-11-11T02:47:01.800Z' From d5f4d64127e34fb5f8a91b8d72806d06198a5a49 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:03:59 +1100 Subject: [PATCH 044/435] Fix #366: link mcp-complete attribution to askansari.ai --- apps/api/src/app/api/v2/mcp-complete/route.ts | 2 +- apps/api/tests/mcp-complete.test.ts | 22 ++++++++++++++++++- codev/state/bugfix-366_thread.md | 13 +++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 codev/state/bugfix-366_thread.md diff --git a/apps/api/src/app/api/v2/mcp-complete/route.ts b/apps/api/src/app/api/v2/mcp-complete/route.ts index ab321d90..a85dc0d1 100644 --- a/apps/api/src/app/api/v2/mcp-complete/route.ts +++ b/apps/api/src/app/api/v2/mcp-complete/route.ts @@ -18,7 +18,7 @@ const CONCISE_INSTRUCTION = 'Please provide a concise and brief answer. References are not required unless specifically asked for. Focus on delivering key information clearly and succinctly.'; const ATTRIBUTION = - '\n\n---\n**This information came from [ansari.chat](https://ansari.chat). Full references and citations are available upon request.**'; + '\n\n---\n**This information came from [askansari.ai](https://askansari.ai). Full references and citations are available upon request.**'; // Cached system user ID to avoid repeated DB lookups let cachedSystemUserId: string | null = null; diff --git a/apps/api/tests/mcp-complete.test.ts b/apps/api/tests/mcp-complete.test.ts index 80ae312f..03b0a95a 100644 --- a/apps/api/tests/mcp-complete.test.ts +++ b/apps/api/tests/mcp-complete.test.ts @@ -382,7 +382,27 @@ describe('mcp-complete empty-answer backstop (issue #60)', () => { expect(response.status).toBe(200); const text = await response.text(); expect(text).toContain('Patience (sabr)'); - expect(text).toContain('ansari.chat'); + expect(text).toContain('askansari.ai'); + }); + + it('appends the exact askansari.ai attribution to the answer (issue #366)', async () => { + const response = await POST( + makePostRequest({ messages: [{ role: 'user', content: 'What is sabr?' }] }) + ); + expect(response.status).toBe(200); + expect(await response.text()).toBe( + 'Patience (sabr) is mentioned many times in the Quran.' + + '\n\n---\n**This information came from [askansari.ai](https://askansari.ai). Full references and citations are available upon request.**' + ); + const assistantCall = mockCreateMessage.mock.calls.find(([m]) => m.role === 'assistant'); + expect(assistantCall?.[0].content).toEqual([ + { + type: 'text', + text: + 'Patience (sabr) is mentioned many times in the Quran.' + + '\n\n---\n**This information came from [askansari.ai](https://askansari.ai). Full references and citations are available upon request.**', + }, + ]); }); }); diff --git a/codev/state/bugfix-366_thread.md b/codev/state/bugfix-366_thread.md new file mode 100644 index 00000000..a3246361 --- /dev/null +++ b/codev/state/bugfix-366_thread.md @@ -0,0 +1,13 @@ +# bugfix-366 thread + +## Investigate +- Root cause: `ATTRIBUTION` constant in `apps/api/src/app/api/v2/mcp-complete/route.ts:20` hardcodes `[ansari.chat](https://ansari.chat)`; appended to every answer at line 219 (response body and persisted assistant message). +- Only live test touching it (`apps/api/tests/mcp-complete.test.ts` "a normal answer still returns 200 with the attribution footer") asserts loosely `toContain('ansari.chat')`. Two other attribution tests are `it.skip` (pre-existing, JSON shape). Nothing pins the exact text. +- apps/mcp footer regex (`src/view/attribution.ts:16`) already accepts `askansari.ai`; `test/react-answers.ts` ANSWER_B covers it. No change needed there. +- Scope: ~1-line fix + exact-text test. Well within BUGFIX. + +## Fix +- `ATTRIBUTION` now links `[askansari.ai](https://askansari.ai)`; rest of sentence unchanged. +- New test pins the exact response body and the persisted assistant content. It fails on HEAD's route (verified by reverting the route) and passes with the fix. The old loose `toContain('ansari.chat')` check now checks `askansari.ai`. +- api: typecheck clean, 87 files / 1147 tests pass. apps/mcp untouched; its suite needs `dist/` (a fresh worktree has none → 10 ENOENT failures until `pnpm build`). +- Architect/owner addition: commit `apps/mcp/.env.example` unchanged (PORT=3000; everything else commented out because set-but-empty MCP_ALLOWED_HOSTS/ORIGINS means allow none). Contents reviewed before committing: no secrets. From 19430a6d7ff42da5ac257e0a820f321fa25011ce Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:04:01 +1100 Subject: [PATCH 045/435] [Bugfix #366] chore: add apps/mcp/.env.example (owner request) --- apps/mcp/.env.example | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 apps/mcp/.env.example diff --git a/apps/mcp/.env.example b/apps/mcp/.env.example new file mode 100644 index 00000000..0b24c0cf --- /dev/null +++ b/apps/mcp/.env.example @@ -0,0 +1,33 @@ +# apps/mcp environment. Full descriptions: apps/mcp/README.md (Environment). +# Staging values: RELEASE.md (mcp service). +# +# Leave a variable commented out to use its default. Do NOT uncomment one with an +# empty value: for MCP_ALLOWED_HOSTS and MCP_ALLOWED_ORIGINS, set-but-empty means +# "allow none", not "use the default". + +# HTTP port. Default 3000. On Railway, set it explicitly (3000) so Railway does +# not assign its own, and make the domain's target port match. +PORT=3000 + +# Ansari API origin. Default https://api.askansari.ai (PRODUCTION). +# ANSARI_API_BASE_URL=https://api-staging.askansari.ai + +# Optional upstream Authorization header. Never commit a value. +# ANSARI_API_AUTHORIZATION= + +# Upstream client label. Default ansari-mcp. +# ANSARI_CLIENT=ansari-mcp-staging + +# Comma-separated allowed Host names, without scheme. Default localhost,127.0.0.1. +# MCP_ALLOWED_HOSTS=mcp-staging.askansari.ai + +# Comma-separated allowed browser Origin hostnames. Default: the allowed hosts. +# Requests without an Origin header always pass. +# MCP_ALLOWED_ORIGINS= + +# json = final-answer-only responses; unset = SSE (supports progress updates). +# MCP_RESPONSE_MODE=json + +# Optional release id shown in /health, logs and the served HTML. On Railway, +# leave unset: it falls back to RAILWAY_GIT_COMMIT_SHA. +# ANSARI_RELEASE= From 15f3022071a4f4672c1964741778a78ca8b0e70d Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 05:07:41 +0200 Subject: [PATCH 046/435] chore(porch): 358 acknowledge context refresh --- codev/projects/358-whatsapp-typescript/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 72240a24..82366752 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -40,7 +40,7 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-10T20:48:04.354Z' +updated_at: '2026-11-11T03:07:41.502Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -59,3 +59,4 @@ context_refreshes: acknowledged_at: '2026-11-10T20:09:01.441Z' - boundary: plan-phase:phase_5 at: '2026-11-10T20:48:04.354Z' + acknowledged_at: '2026-11-11T03:07:41.500Z' From 1a3ac7d5a4da189b5c4c08c5c5f023ce7a3d0924 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:15:04 +1100 Subject: [PATCH 047/435] chore(porch): bugfix-366 pr phase-transition --- .../bugfix-366-mcp-complete-attribution-link-/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml index b079d72c..d24f6edb 100644 --- a/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml +++ b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml @@ -1,7 +1,7 @@ id: bugfix-366 title: mcp-complete-attribution-link- protocol: bugfix -phase: fix +phase: pr plan_phases: [] current_plan_phase: null gates: @@ -11,4 +11,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-11T02:46:41.302Z' -updated_at: '2026-11-11T02:47:01.800Z' +updated_at: '2026-11-11T03:15:04.205Z' From e8717b72f01461a16d7f9dac46a5ad09cfd34772 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:18:15 +1100 Subject: [PATCH 048/435] [Bugfix #366] chore: thread log CMAP outcome --- codev/state/bugfix-366_thread.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/codev/state/bugfix-366_thread.md b/codev/state/bugfix-366_thread.md index a3246361..05174979 100644 --- a/codev/state/bugfix-366_thread.md +++ b/codev/state/bugfix-366_thread.md @@ -11,3 +11,8 @@ - New test pins the exact response body and the persisted assistant content. It fails on HEAD's route (verified by reverting the route) and passes with the fix. The old loose `toContain('ansari.chat')` check now checks `askansari.ai`. - api: typecheck clean, 87 files / 1147 tests pass. apps/mcp untouched; its suite needs `dist/` (a fresh worktree has none → 10 ENOENT failures until `pnpm build`). - Architect/owner addition: commit `apps/mcp/.env.example` unchanged (PORT=3000; everything else commented out because set-but-empty MCP_ALLOWED_HOSTS/ORIGINS means allow none). Contents reviewed before committing: no secrets. + +## PR #368 +- CMAP: gemini=APPROVE, codex=APPROVE, claude=APPROVE (all HIGH, no key issues). CI gitleaks passed. +- Claude's non-blocking follow-ups, deliberately not done here (out of scope): `apps/mcp/test/browser.ts` openLink fixtures still use `https://ansari.chat/`, so no fixture exercises the production `askansari.ai` link target; mcp env vars (`PORT`, `MCP_ALLOWED_*`, etc.) are not in `turbo.json` `globalEnv` (pre-existing). +- Gotchas: `consult --type pr` needs `--issue ` when many projects exist; `porch` must run from the worktree root (from `apps/api` it says "not found" yet exits 0); the apps/mcp suite needs `pnpm build` first in a fresh worktree. From 1e708e36990102dc4ba4e0260549c8f0c3c5a5d5 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:18:17 +1100 Subject: [PATCH 049/435] chore(porch): bugfix-366 pr gate-requested --- .../bugfix-366-mcp-complete-attribution-link-/status.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml index d24f6edb..93be63c3 100644 --- a/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml +++ b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml @@ -7,8 +7,10 @@ current_plan_phase: null gates: pr: status: pending + requested_at: '2026-11-11T03:18:17.751Z' iteration: 1 build_complete: false history: [] started_at: '2026-11-11T02:46:41.302Z' -updated_at: '2026-11-11T03:15:04.205Z' +updated_at: '2026-11-11T03:18:17.751Z' +pr_ready_for_human: true From ed6a894c5957757124c4991219bd1c9f8b41b92f Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:25:47 +1100 Subject: [PATCH 050/435] chore(porch): bugfix-366 pr gate-approved --- .../bugfix-366-mcp-complete-attribution-link-/status.yaml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml index 93be63c3..f47ce5d3 100644 --- a/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml +++ b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml @@ -6,11 +6,12 @@ plan_phases: [] current_plan_phase: null gates: pr: - status: pending + status: approved requested_at: '2026-11-11T03:18:17.751Z' + approved_at: '2026-11-11T03:25:47.118Z' iteration: 1 build_complete: false history: [] started_at: '2026-11-11T02:46:41.302Z' -updated_at: '2026-11-11T03:18:17.751Z' -pr_ready_for_human: true +updated_at: '2026-11-11T03:25:47.119Z' +pr_ready_for_human: false From c47843478f7f21a7a443e23e996cc45185144c08 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:25:49 +1100 Subject: [PATCH 051/435] chore(porch): bugfix-366 protocol complete --- .../bugfix-366-mcp-complete-attribution-link-/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml index f47ce5d3..383af717 100644 --- a/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml +++ b/codev/projects/bugfix-366-mcp-complete-attribution-link-/status.yaml @@ -1,7 +1,7 @@ id: bugfix-366 title: mcp-complete-attribution-link- protocol: bugfix -phase: pr +phase: verified plan_phases: [] current_plan_phase: null gates: @@ -13,5 +13,5 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-11T02:46:41.302Z' -updated_at: '2026-11-11T03:25:47.119Z' +updated_at: '2026-11-11T03:25:49.318Z' pr_ready_for_human: false From 1fd786538ed5b7c9a66b7f32d1a0985813f0801e Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:33:19 +1100 Subject: [PATCH 052/435] chore(porch): bugfix-369 init bugfix --- .../status.yaml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml diff --git a/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml new file mode 100644 index 00000000..f31ba8ac --- /dev/null +++ b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml @@ -0,0 +1,14 @@ +id: bugfix-369 +title: apps-mcp-tests-ansari-attribut +protocol: bugfix +phase: investigate +plan_phases: [] +current_plan_phase: null +gates: + pr: + status: pending +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-11T03:33:19.479Z' +updated_at: '2026-11-11T03:33:19.480Z' From 5cce1fbef4a462a4543937f39e78eec229fd071d Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:33:43 +1100 Subject: [PATCH 053/435] chore(porch): 370 init air --- .../370-apps-mcp-declare-its-env-vars-/status.yaml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml diff --git a/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml b/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml new file mode 100644 index 00000000..615cd0d8 --- /dev/null +++ b/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml @@ -0,0 +1,14 @@ +id: '370' +title: apps-mcp-declare-its-env-vars- +protocol: air +phase: implement +plan_phases: [] +current_plan_phase: null +gates: + pr: + status: pending +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-11T03:33:43.743Z' +updated_at: '2026-11-11T03:33:43.744Z' From 50f5f3ff9649cc576075e9b88be17e65ded4471b Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:33:52 +1100 Subject: [PATCH 054/435] chore(porch): bugfix-369 fix phase-transition --- .../bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml index f31ba8ac..f197a4f9 100644 --- a/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml +++ b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml @@ -1,7 +1,7 @@ id: bugfix-369 title: apps-mcp-tests-ansari-attribut protocol: bugfix -phase: investigate +phase: fix plan_phases: [] current_plan_phase: null gates: @@ -11,4 +11,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-11T03:33:19.479Z' -updated_at: '2026-11-11T03:33:19.480Z' +updated_at: '2026-11-11T03:33:52.818Z' From 65b050c59a64e99b125c46b1239bda4c41e6beaf Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:37:12 +1100 Subject: [PATCH 055/435] [Air #370] feat: pin apps/mcp turbo env declarations to README and source reads --- apps/mcp/README.md | 3 ++ apps/mcp/test/turbo-env.test.ts | 89 +++++++++++++++++++++++++++++++++ codev/state/air-370_thread.md | 7 +++ 3 files changed, 99 insertions(+) create mode 100644 apps/mcp/test/turbo-env.test.ts create mode 100644 codev/state/air-370_thread.md diff --git a/apps/mcp/README.md b/apps/mcp/README.md index 16f1009d..22e97878 100644 --- a/apps/mcp/README.md +++ b/apps/mcp/README.md @@ -95,6 +95,9 @@ The Worker takes the variables in the table below as Wrangler `vars` or secrets, | `MCP_ALLOWED_ORIGINS` | Comma-separated allowed browser origin hostnames. A configured list replaces defaults; an explicitly empty list permits no Origin header value. Requests without Origin remain supported. | | `MCP_RESPONSE_MODE` | `json` for modern MCP final-answer-only responses; otherwise SSE, which supports client-requested progress notifications. Older-host compatibility responses may use SSE. | | `ANSARI_RELEASE` | Optional safe release identifier, embedded in served HTML and health/log records. | +| `RAILWAY_GIT_COMMIT_SHA` | Set by Railway, not by hand. The release used when `ANSARI_RELEASE` is absent or not a safe identifier. | + +Each variable in this table is declared by name on the `dev` and `start` tasks in `apps/mcp/turbo.json`: Turborepo runs in strict env mode and hides an undeclared variable from the task. `test/turbo-env.test.ts` keeps the table, those declarations and the source's reads in step. `build` and `test` declare none of them: the build bundles no setting, and the tests set the values they depend on themselves. Declaring the variables on `test` would let a shell's value leak into tests that spread `process.env`. `POST /mcp` serves stateless MCP requests through Hono and the official MCP request handler. Modern requests need no initialization; older hosts can use the handler’s stateless compatibility path. No MCP session IDs, session map, expiry timer or replay store are retained. `GET /mcp` and `DELETE /mcp` return 405. `/health` exposes the release. The HTML is supplied by the hosting target (read from `dist/` at Node start, bundled into the Worker), revision-stamped and fingerprinted once before the first request is served: the release is stamped first, so equal final bytes have equal identities and a release change legitimately changes the hash. Each request creates its own lightweight MCP server using that prepared view; resource bytes and identity stay fixed until restart. No demo, font server, alternative renderer or historical resource is served. Tool calls have a fresh 60-second budget; timeout yields a safe error and leaves subsequent calls usable. The same lifetime signal aborts the upstream fetch and response-body read when the request ends or the budget expires. diff --git a/apps/mcp/test/turbo-env.test.ts b/apps/mcp/test/turbo-env.test.ts new file mode 100644 index 00000000..235012d1 --- /dev/null +++ b/apps/mcp/test/turbo-env.test.ts @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict'; +import {test} from 'node:test'; +import {readFileSync, readdirSync} from 'node:fs'; +import {join} from 'node:path'; +import {fileURLToPath} from 'node:url'; + +// Turborepo runs in strict env mode: a variable a task does not declare is hidden from it and left out of its hash. +// The tasks that run the server (`dev`, `start`) must declare every variable the source reads, the README documents. +const root = fileURLToPath(new URL('../', import.meta.url)); +const RUNNING_TASKS = ['dev', 'start'] as const; + +type TurboTask = {env?: string[]}; +const turbo = JSON.parse(readFileSync(join(root, 'turbo.json'), 'utf8')) as {tasks: Record}; + +/** Variable names in the README's `| Variable | Meaning |` table. */ +function readmeVariables(markdown: string): string[] { + const lines = markdown.split('\n'); + const start = lines.findIndex(line => /^\|\s*Variable\s*\|\s*Meaning\s*\|/.test(line)); + assert.notEqual(start, -1, 'README has a Variable | Meaning table'); + const names: string[] = []; + for (const line of lines.slice(start + 2)) { + if (!line.startsWith('|')) break; + const match = /^\|\s*`([A-Z][A-Z0-9_]*)`\s*\|/.exec(line); + assert.ok(match, `table row names one variable: ${line}`); + names.push(match[1]!); + } + return names; +} + +/** Environment names the source reads: `process.env.X`, `env.X` and runtime-config's `setting(env, 'X')`. */ +function sourceVariables(source: string): string[] { + const names = new Set(); + for (const match of source.matchAll(/\benv\.([A-Z][A-Z0-9_]*)\b/g)) names.add(match[1]!); + for (const match of source.matchAll(/\bsetting\(\s*env\s*,\s*['"]([A-Z][A-Z0-9_]*)['"]\s*\)/g)) names.add(match[1]!); + return [...names]; +} + +function sourceFiles(dir: string): string[] { + return readdirSync(dir, {withFileTypes: true}).flatMap(entry => { + const path = join(dir, entry.name); + if (entry.isDirectory()) return sourceFiles(path); + return /\.tsx?$/.test(entry.name) ? [path] : []; + }); +} + +const sorted = (names: Iterable) => [...new Set(names)].sort(); + +test('the readme table parser reads names and rejects a malformed row', () => { + const table = '| Variable | Meaning |\n| --- | --- |\n| `PORT` | port |\n| `A_B2` | x |\n\nprose'; + assert.deepEqual(readmeVariables(table), ['PORT', 'A_B2']); + assert.throws(() => readmeVariables('| Variable | Meaning |\n| --- | --- |\n| PORT | unquoted |')); + assert.throws(() => readmeVariables('no table here')); +}); + +test('the source scan finds every read form and ignores near misses', () => { + const hits = sourceVariables([ + 'process.env.PORT', + 'allowedList(env.MCP_ALLOWED_HOSTS, x)', + "setting(env, 'ANSARI_RELEASE')", + 'setting( env , "RAILWAY_GIT_COMMIT_SHA" )', + ].join('\n')); + assert.deepEqual(sorted(hits), ['ANSARI_RELEASE', 'MCP_ALLOWED_HOSTS', 'PORT', 'RAILWAY_GIT_COMMIT_SHA']); + assert.deepEqual(sourceVariables(['myenv.PORT', 'env.lowercase', "setting(other, 'PORT')", "settings(env, 'PORT')"].join('\n')), []); +}); + +test('the source scan sees the real configuration reads', () => { + const found = sorted(sourceFiles(join(root, 'src')).flatMap(file => sourceVariables(readFileSync(file, 'utf8')))); + // A floor, so a scan that silently matches nothing fails loudly instead of passing. + for (const name of ['PORT', 'MCP_ALLOWED_HOSTS', 'ANSARI_API_AUTHORIZATION', 'RAILWAY_GIT_COMMIT_SHA']) { + assert.ok(found.includes(name), `scan finds ${name}`); + } +}); + +test('dev and start declare exactly the README table, which covers every variable the source reads', () => { + const documented = sorted(readmeVariables(readFileSync(join(root, 'README.md'), 'utf8'))); + const read = sorted(sourceFiles(join(root, 'src')).flatMap(file => sourceVariables(readFileSync(file, 'utf8')))); + assert.deepEqual(read.filter(name => !documented.includes(name)), [], 'every variable the source reads is in the README table'); + for (const task of RUNNING_TASKS) { + const declared = turbo.tasks[task]?.env ?? []; + assert.deepEqual(sorted(declared), documented, `${task}.env matches the README table`); + assert.equal(declared.length, new Set(declared).size, `${task}.env has no duplicates`); + } +}); + +test('turbo declares variable names only, never a value or a wildcard', () => { + for (const [task, config] of Object.entries(turbo.tasks)) { + for (const entry of config.env ?? []) assert.match(entry, /^[A-Z][A-Z0-9_]*$/, `${task}.env entry ${entry} is a bare name`); + } +}); diff --git a/codev/state/air-370_thread.md b/codev/state/air-370_thread.md new file mode 100644 index 00000000..21b74e59 --- /dev/null +++ b/codev/state/air-370_thread.md @@ -0,0 +1,7 @@ +# air-370 thread — apps/mcp turbo env declarations + +- Premise check: the issue says apps/mcp's env vars are "not declared anywhere". In fact `apps/mcp/turbo.json` has declared all nine on `dev` and `start` since c639f7aa (2026-10-28). Real gaps: the README table lacked `RAILWAY_GIT_COMMIT_SHA`, nothing pinned the list, and no proof of hash behaviour existed. +- Derivation: no Zod env schema in apps/mcp (the only z.object is the tool I/O schema). Static reads: `process.env.PORT` and `env.MCP_ALLOWED_HOSTS` / `env.MCP_ALLOWED_ORIGINS`. Dynamic: `setting(env, '...')` in runtime-config.ts (ANSARI_RELEASE, RAILWAY_GIT_COMMIT_SHA, MCP_RESPONSE_MODE, ANSARI_API_BASE_URL, ANSARI_CLIENT, ANSARI_API_AUTHORIZATION). README table: the same set, minus RAILWAY_GIT_COMMIT_SHA (now added). +- Decision: keep per-task `env` on dev/start only, and add no globalEnv. `build` reads none of them (scripts/build.ts bundles no setting). `test` deliberately declares none: tests set what they need, and strict mode keeps a shell's values out of the tests that spread process.env. +- Proof (turbo --dry=json, ansari-mcp#start and #dev): setting MCP_RESPONSE_MODE, RAILWAY_GIT_COMMIT_SHA or ANSARI_API_AUTHORIZATION moves the hash. With MCP_RESPONSE_MODE removed from start.env, the hash is identical set vs unset; restored, it moves again. The dry-run shows ANSARI_API_AUTHORIZATION only as a sha256, never as plaintext. +- Test: apps/mcp/test/turbo-env.test.ts pins dev.env == start.env == README table ⊇ source reads, and bare names only. Negative-tested: dropping a turbo entry, dropping a README row and adding an undeclared source read each fail it. From f84a28e7a3e9bc8d8ec71cb4df49470e688ba0d5 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:39:17 +1100 Subject: [PATCH 056/435] chore(porch): 370 pr phase-transition --- codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml b/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml index 615cd0d8..9b239d7b 100644 --- a/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml +++ b/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml @@ -1,7 +1,7 @@ id: '370' title: apps-mcp-declare-its-env-vars- protocol: air -phase: implement +phase: pr plan_phases: [] current_plan_phase: null gates: @@ -11,4 +11,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-11T03:33:43.743Z' -updated_at: '2026-11-11T03:33:43.744Z' +updated_at: '2026-11-11T03:39:17.876Z' From 1f22020b3725a385713b40adf59be20e969d3b12 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:39:55 +1100 Subject: [PATCH 057/435] chore(porch): 370 record PR #371 --- .../370-apps-mcp-declare-its-env-vars-/status.yaml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml b/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml index 9b239d7b..10fb021b 100644 --- a/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml +++ b/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml @@ -11,4 +11,9 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-11T03:33:43.743Z' -updated_at: '2026-11-11T03:39:17.876Z' +updated_at: '2026-11-11T03:39:54.917Z' +pr_history: + - phase: pr + pr_number: 371 + branch: builder/air-370 + created_at: '2026-11-11T03:39:54.916Z' From 0b905bc58172b963d48f4dc1a6431501792c9d30 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:40:03 +1100 Subject: [PATCH 058/435] chore(porch): 370 pr gate-requested --- codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml b/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml index 10fb021b..0be5a8bf 100644 --- a/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml +++ b/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml @@ -7,13 +7,15 @@ current_plan_phase: null gates: pr: status: pending + requested_at: '2026-11-11T03:40:03.895Z' iteration: 1 build_complete: false history: [] started_at: '2026-11-11T03:33:43.743Z' -updated_at: '2026-11-11T03:39:54.917Z' +updated_at: '2026-11-11T03:40:03.895Z' pr_history: - phase: pr pr_number: 371 branch: builder/air-370 created_at: '2026-11-11T03:39:54.916Z' +pr_ready_for_human: true From 641731f0a53bcabe124e0ab273b0480daa574fa6 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:46:18 +1100 Subject: [PATCH 059/435] [Air #370] docs: move turbo env rationale from README into the test --- apps/mcp/README.md | 2 -- apps/mcp/test/turbo-env.test.ts | 8 +++++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/mcp/README.md b/apps/mcp/README.md index 22e97878..ddfaa46f 100644 --- a/apps/mcp/README.md +++ b/apps/mcp/README.md @@ -97,8 +97,6 @@ The Worker takes the variables in the table below as Wrangler `vars` or secrets, | `ANSARI_RELEASE` | Optional safe release identifier, embedded in served HTML and health/log records. | | `RAILWAY_GIT_COMMIT_SHA` | Set by Railway, not by hand. The release used when `ANSARI_RELEASE` is absent or not a safe identifier. | -Each variable in this table is declared by name on the `dev` and `start` tasks in `apps/mcp/turbo.json`: Turborepo runs in strict env mode and hides an undeclared variable from the task. `test/turbo-env.test.ts` keeps the table, those declarations and the source's reads in step. `build` and `test` declare none of them: the build bundles no setting, and the tests set the values they depend on themselves. Declaring the variables on `test` would let a shell's value leak into tests that spread `process.env`. - `POST /mcp` serves stateless MCP requests through Hono and the official MCP request handler. Modern requests need no initialization; older hosts can use the handler’s stateless compatibility path. No MCP session IDs, session map, expiry timer or replay store are retained. `GET /mcp` and `DELETE /mcp` return 405. `/health` exposes the release. The HTML is supplied by the hosting target (read from `dist/` at Node start, bundled into the Worker), revision-stamped and fingerprinted once before the first request is served: the release is stamped first, so equal final bytes have equal identities and a release change legitimately changes the hash. Each request creates its own lightweight MCP server using that prepared view; resource bytes and identity stay fixed until restart. No demo, font server, alternative renderer or historical resource is served. Tool calls have a fresh 60-second budget; timeout yields a safe error and leaves subsequent calls usable. The same lifetime signal aborts the upstream fetch and response-body read when the request ends or the budget expires. Closing a request server releases its budget even if it was never connected to a transport. On SIGINT or SIGTERM the listener stops accepting requests, closes MCP handlers and HTTP connections, and exits; unfinished calls are interrupted, including older-host SSE calls. Fetch cancellation does not guarantee that the remote backend has stopped processing. Caller-disconnect propagation depends on the host transport; the local Workers runtime does not establish immediate upstream cancellation from a client disconnect. Actual fetch cancellation at the request deadline is covered on both hosting targets. diff --git a/apps/mcp/test/turbo-env.test.ts b/apps/mcp/test/turbo-env.test.ts index 235012d1..797ff086 100644 --- a/apps/mcp/test/turbo-env.test.ts +++ b/apps/mcp/test/turbo-env.test.ts @@ -5,7 +5,13 @@ import {join} from 'node:path'; import {fileURLToPath} from 'node:url'; // Turborepo runs in strict env mode: a variable a task does not declare is hidden from it and left out of its hash. -// The tasks that run the server (`dev`, `start`) must declare every variable the source reads, the README documents. +// So the tasks that run the server (`dev`, `start` in turbo.json) must declare, by name, every variable in the +// README's environment table, and that table must cover every variable src/ reads. This test keeps the three in step: +// a new `setting(env, 'X')` that is missing from turbo.json would otherwise be dropped silently under `turbo run`. +// +// `build` and `test` deliberately declare none of them. The build bundles no setting, and the tests set the values +// they depend on themselves. Declaring the variables on `test` would let a shell's value leak into tests that spread +// `process.env`. const root = fileURLToPath(new URL('../', import.meta.url)); const RUNNING_TASKS = ['dev', 'start'] as const; From df639b4a6cf360467fb2708cc42a9cc612a41d4b Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:48:45 +1100 Subject: [PATCH 060/435] [Air #370] chore: thread log before merge --- codev/state/air-370_thread.md | 1 + 1 file changed, 1 insertion(+) diff --git a/codev/state/air-370_thread.md b/codev/state/air-370_thread.md index 21b74e59..2aaf46b8 100644 --- a/codev/state/air-370_thread.md +++ b/codev/state/air-370_thread.md @@ -5,3 +5,4 @@ - Decision: keep per-task `env` on dev/start only, and add no globalEnv. `build` reads none of them (scripts/build.ts bundles no setting). `test` deliberately declares none: tests set what they need, and strict mode keeps a shell's values out of the tests that spread process.env. - Proof (turbo --dry=json, ansari-mcp#start and #dev): setting MCP_RESPONSE_MODE, RAILWAY_GIT_COMMIT_SHA or ANSARI_API_AUTHORIZATION moves the hash. With MCP_RESPONSE_MODE removed from start.env, the hash is identical set vs unset; restored, it moves again. The dry-run shows ANSARI_API_AUTHORIZATION only as a sha256, never as plaintext. - Test: apps/mcp/test/turbo-env.test.ts pins dev.env == start.env == README table ⊇ source reads, and bare names only. Negative-tested: dropping a turbo entry, dropping a README row and adding an undeclared source read each fail it. +- PR #371 opened. On owner review, the README paragraph about turbo/test internals was cut: its rationale now lives in the header comment of `test/turbo-env.test.ts` (641731f0). The README keeps only the `RAILWAY_GIT_COMMIT_SHA` row. PR gate approved by the human (relayed by the architect on 2026-11-11), merged as a merge commit. From 1a9f054a8483205172471298833f688ce7a232d0 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 14:48:50 +1100 Subject: [PATCH 061/435] chore(porch): 370 pr gate-approved --- .../370-apps-mcp-declare-its-env-vars-/status.yaml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml b/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml index 0be5a8bf..5fb4fc44 100644 --- a/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml +++ b/codev/projects/370-apps-mcp-declare-its-env-vars-/status.yaml @@ -6,16 +6,17 @@ plan_phases: [] current_plan_phase: null gates: pr: - status: pending + status: approved requested_at: '2026-11-11T03:40:03.895Z' + approved_at: '2026-11-11T03:48:50.635Z' iteration: 1 build_complete: false history: [] started_at: '2026-11-11T03:33:43.743Z' -updated_at: '2026-11-11T03:40:03.895Z' +updated_at: '2026-11-11T03:48:50.636Z' pr_history: - phase: pr pr_number: 371 branch: builder/air-370 created_at: '2026-11-11T03:39:54.916Z' -pr_ready_for_human: true +pr_ready_for_human: false From 17dbf4159ad948ab30de897a19198077451cf7f3 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 05:55:41 +0200 Subject: [PATCH 062/435] [Spec 358][Phase: phase_5] feat: HTTP app (webhook, handshake, signature, background work, Sentry, shutdown) --- apps/whatsapp/package.json | 5 + apps/whatsapp/src/app.ts | 309 +++++++ apps/whatsapp/src/background.ts | 73 ++ apps/whatsapp/src/index.ts | 65 ++ apps/whatsapp/src/sentry.ts | 70 ++ apps/whatsapp/src/server.ts | 47 + apps/whatsapp/src/services/createServices.ts | 58 ++ apps/whatsapp/src/webhook/metaResponse.ts | 49 ++ apps/whatsapp/src/webhook/signature.ts | 46 + apps/whatsapp/tests/app.test.ts | 822 ++++++++++++++++++ apps/whatsapp/tests/appParserFault.test.ts | 45 + .../tests/backgroundAndServer.test.ts | 480 ++++++++++ apps/whatsapp/tests/helpers/app.ts | 188 ++++ apps/whatsapp/tests/listenHelper.test.ts | 51 ++ apps/whatsapp/tests/signatureTiming.test.ts | 50 ++ apps/whatsapp/tests/webhookHelpers.test.ts | 170 ++++ .../358-phase_5-iter1-claude.txt | 48 + pnpm-lock.yaml | 15 + 18 files changed, 2591 insertions(+) create mode 100644 apps/whatsapp/src/app.ts create mode 100644 apps/whatsapp/src/background.ts create mode 100644 apps/whatsapp/src/index.ts create mode 100644 apps/whatsapp/src/sentry.ts create mode 100644 apps/whatsapp/src/server.ts create mode 100644 apps/whatsapp/src/services/createServices.ts create mode 100644 apps/whatsapp/src/webhook/metaResponse.ts create mode 100644 apps/whatsapp/src/webhook/signature.ts create mode 100644 apps/whatsapp/tests/app.test.ts create mode 100644 apps/whatsapp/tests/appParserFault.test.ts create mode 100644 apps/whatsapp/tests/backgroundAndServer.test.ts create mode 100644 apps/whatsapp/tests/helpers/app.ts create mode 100644 apps/whatsapp/tests/listenHelper.test.ts create mode 100644 apps/whatsapp/tests/signatureTiming.test.ts create mode 100644 apps/whatsapp/tests/webhookHelpers.test.ts create mode 100644 codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt diff --git a/apps/whatsapp/package.json b/apps/whatsapp/package.json index 57e8d2f4..a7f5148d 100644 --- a/apps/whatsapp/package.json +++ b/apps/whatsapp/package.json @@ -17,12 +17,17 @@ "test": "vitest run" }, "dependencies": { + "@sentry/node": "^10.69.0", + "cors": "^2.8.5", "dotenv": "^17.2.3", + "express": "^5.1.0", "zod": "^4.3.5" }, "devDependencies": { "@ansari/eslint-config": "workspace:*", "@ansari/tsconfig": "workspace:*", + "@types/cors": "^2.8.17", + "@types/express": "^5.0.0", "@types/node": "^25.0.10", "eslint": "catalog:", "tsdown": "^0.22.14", diff --git a/apps/whatsapp/src/app.ts b/apps/whatsapp/src/app.ts new file mode 100644 index 00000000..ffa3dbd0 --- /dev/null +++ b/apps/whatsapp/src/app.ts @@ -0,0 +1,309 @@ +/** + * The Express app: the three routes Meta and the platform call, built without listening so tests can drive it. + * + * Python counterpart: `app/main.py` (FastAPI). The checks that used to sit in its webhook route (maintenance, the staging + * `!d ` filter, message age, message type) moved to `ConversationManager.triage`; this file only turns each answer into the + * HTTP reply Meta gets. + * + * GET / health probe + * GET /whatsapp/v3 Meta's one-time handshake when the callback URL is saved in its dashboard + * POST /whatsapp/v3 every message and delivery receipt + * + * The routes are `/whatsapp/v3` where the Python service served `/whatsapp/v2`: the two services share one Meta callback URL + * at a time, so the version in the path says which of them Meta is talking to. + * + * What a POST goes through: + * read the raw bytes -> check the signature -> parse the JSON -> work out what it is -> answer Meta -> (afterwards) + * sign in, ask apps/api and reply to the user + * + * Differences from Python: + * - The body is read as raw bytes and parsed by hand, after the signature check. `express.json()` would parse (and reject bad + * JSON with a 400) before the signature is looked at, so an unsigned caller could tell valid JSON from invalid. FastAPI + * checked the signature in a dependency that ran first; this keeps that order. + * - CORS is the `cors` package, not Starlette's. A request from an origin that is not allowed is still handled, as in Python, + * but a preflight from one gets no CORS headers (Python answered it with a 400). Meta's servers send no `Origin` header at all. + * - There is no 405 for a wrong method on a known path: Express answers 404, as it does for any route it does not have. + * - An error that escapes a route is reported and answered with a 500, as before; Express 5 passes the failure of an `async` + * handler to the error handler by itself, so no wrapper is needed. + */ +import { randomUUID } from 'node:crypto'; +import cors from 'cors'; +import express, { type Express, type NextFunction, type Request, type Response } from 'express'; +import type { BackgroundTasks } from './background'; +import type { Env } from './config'; +import type { ConversationManager, TriageAction } from './conversationManager'; +import type { ErrorReporter } from './errorReporter'; +import { noopErrorReporter } from './errorReporter'; +import { InvalidMetaPayloadError, UnexpectedMetaPayloadError } from './errors'; +import { getRequestId, runWithRequestId, type Logger } from './logger'; +import { createResponseForMeta, type MetaResponseInput } from './webhook/metaResponse'; +import { parseMetaPayload } from './webhook/parseWebhook'; +import { constantTimeEquals, isValidSignature } from './webhook/signature'; + +/** Python served `/whatsapp/v2`; see the file header for why this is `v3`. */ +export const WEBHOOK_PATH = '/whatsapp/v3'; + +/** Meta's webhook bodies are a few kilobytes. A larger one is refused before anyone is asked to sign it. */ +const BODY_LIMIT = '1mb'; + +const UNEXPECTED_FORMAT_NOTICE = + 'It seems Meta sent your message in an unexpected format. This is not a problem in what you wrote, ' + + 'so please send this chat as screenshot to the developers to investigate further'; + +/** The settings the app reads. `Pick` takes just these fields of the full `Env` type. */ +export type AppConfig = Pick< + Env, + | 'META_ANSARI_APP_SECRET' + | 'META_WEBHOOK_VERIFY_TOKEN' + | 'META_BUSINESS_PHONE_NUMBER_ID' + | 'META_REPLY_BY_PHONE' + | 'ALWAYS_RETURN_OK_TO_META' + | 'DEPLOYMENT_TYPE' + | 'ORIGINS' +>; + +export interface AppDeps { + config: AppConfig; + /** Only the three methods the routes call. */ + manager: Pick; + background: BackgroundTasks; + logger: Logger; + reportError?: ErrorReporter; +} + +/** How Meta is answered for each thing `triage` can decide (Python's status codes and `error_code`s). */ +const TRIAGE_REPLIES: Record = { + maintenance: { success: false, message: 'Service under maintenance', statusCode: 503, errorCode: 'MAINTENANCE_MODE' }, + dev_filter: { + success: false, + message: 'Message filtered for local development', + statusCode: 202, + errorCode: 'DEV_FILTER', + }, + too_old: { success: false, message: 'Message too old, ignored', statusCode: 422, errorCode: 'MESSAGE_TOO_OLD' }, + unsupported: { + success: false, + message: 'Unsupported message type handled', + statusCode: 415, + errorCode: 'UNSUPPORTED_MESSAGE_TYPE', + }, + text: { success: true, message: 'Message processed successfully' }, +}; + +/** Query values arrive as a string, a list (`?a=1&a=2`) or nothing; the last one wins, as in Starlette. */ +function queryValue(value: unknown): string | undefined { + if (typeof value === 'string') return value; + if (Array.isArray(value)) return queryValue(value[value.length - 1]); + return undefined; +} + +export function buildApp(deps: AppDeps): Express { + const { config, manager, background, logger } = deps; + const reportError = deps.reportError ?? noopErrorReporter; + const app = express(); + app.disable('x-powered-by'); + + /** Meta's reply is built from one place so the "always 200" rule cannot be forgotten on one path. */ + function answerMeta(res: Response, input: MetaResponseInput): void { + const { status, body } = createResponseForMeta(input, config.ALWAYS_RETURN_OK_TO_META); + res.status(status).json(body); + } + + function report(error: unknown, errorType: string): void { + // Only the request id travels with the event, never a BSUID, phone number, token or message text + reportError(error, { errorType, context: { request_id: getRequestId() } }); + } + + // A fresh id per request, on every log line it causes (Python: `request_id_var`) and on the response, so one message can + // be followed through the logs. The caller's own `X-Request-ID` is ignored: it is untrusted text going into the logs. + app.use((_req, res, next) => { + const requestId = randomUUID(); + res.setHeader('X-Request-ID', requestId); + runWithRequestId(requestId, () => { + logger.debug('Request started'); + res.once('finish', () => runWithRequestId(requestId, () => logger.debug('Request ended'))); + next(); + }); + }); + + const allowedOrigins = new Set(config.ORIGINS); + app.use( + cors({ + origin: (origin, callback) => { + if (origin !== undefined && !allowedOrigins.has(origin)) { + logger.error(`CORS Origin Error: ${origin} is not one of the allowed origins ${JSON.stringify(config.ORIGINS)}`); + } + callback(null, origin !== undefined && allowedOrigins.has(origin) ? origin : false); + }, + credentials: true, + }), + ); + + app.get('/', (_req, res) => { + logger.info('Health check endpoint called'); + res.json({ status: 'ok', message: 'Ansari WhatsApp service is running' }); + }); + + // Crashes on purpose, to prove errors reach Sentry. Open to anyone who finds it, so never in production. + if (config.DEPLOYMENT_TYPE !== 'production') { + app.get('/sentry-debug', () => { + throw new Error('Deliberate error to test Sentry (GET /sentry-debug)'); + }); + } + + /** + * Meta's verification handshake: when the callback URL is saved in the dashboard, Meta sends `hub.mode=subscribe`, our + * verify token and a random `hub.challenge`, and expects the challenge back. + * https://developers.facebook.com/docs/graph-api/webhooks/getting-started#verification-requests + */ + app.get(WEBHOOK_PATH, (req, res) => { + const mode = queryValue(req.query['hub.mode']); + const verifyToken = queryValue(req.query['hub.verify_token']); + const challenge = queryValue(req.query['hub.challenge']); + + logger.debug(`Verification webhook received: mode=${mode ?? 'none'}, token_present=${Boolean(verifyToken)}`); + + if (!mode || !verifyToken) { + res.status(400).json({ detail: 'Bad Request' }); + return; + } + if (mode === 'subscribe' && constantTimeEquals(config.META_WEBHOOK_VERIFY_TOKEN.reveal(), verifyToken)) { + logger.info('WHATSAPP WEBHOOK VERIFIED SUCCESSFULLY!'); + // Sent as HTML, as Meta's own sample does and as the Python service did. Only reached once the secret token matched, so + // nobody but Meta (or the operator) can make this service echo text into a page. + res.status(200).type('html').send(challenge ?? ''); + return; + } + logger.error('Verification failed: Invalid token or mode'); + res.status(403).json({ detail: 'Forbidden' }); + }); + + app.post(WEBHOOK_PATH, express.raw({ type: () => true, limit: BODY_LIMIT }), (req: Request, res: Response) => { + // `req.body` is a Buffer once the raw parser ran, and undefined when the request carried no body at all + const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0); + + // ---- 1. Is it from Meta? (403) ---- + const signatureHeader = req.get('X-Hub-Signature-256'); + if (!isValidSignature(rawBody, signatureHeader, config.META_ANSARI_APP_SECRET)) { + if (!signatureHeader?.startsWith('sha256=')) { + logger.warn('Missing or invalid X-Hub-Signature-256 header format'); + logger.error('Webhook signature verification failed - rejecting request'); + } else { + logger.error("Invalid webhook signature; request isn't from Meta or you have misconfigured META_ANSARI_APP_SECRET"); + } + res.setHeader('WWW-Authenticate', 'HMAC-SHA256').status(403).json({ detail: 'Invalid signature' }); + return; + } + logger.debug('Webhook signature verified successfully'); + + // ---- 2. Read the JSON ---- + let payload: unknown; + try { + payload = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(rawBody)); + } catch { + // Not the parser's own message: a JSON syntax error quotes the start of the body, which is the user's text + logger.error('Webhook body is not valid JSON'); + report(new Error('Webhook body is not valid JSON'), 'webhook_processing_failure'); + answerMeta(res, { + success: false, + message: 'Error processing webhook payload', + statusCode: 400, + errorCode: 'INVALID_PAYLOAD', + details: { error: 'Webhook body is not valid JSON' }, + }); + return; + } + + // ---- 3. What is it? ---- + let parsed; + try { + parsed = parseMetaPayload(payload, config, logger); + } catch (error) { + if (error instanceof UnexpectedMetaPayloadError) { + logger.error(`Unexpected Meta payload format: ${error.message}`); + report(error, 'unexpected_meta_payload'); + const { replyTo } = error; + if (replyTo) { + background.run(() => manager.notify(replyTo, UNEXPECTED_FORMAT_NOTICE)); + } else { + logger.error('No phone number or BSUID in the payload, so the user could not be notified'); + } + answerMeta(res, { + success: false, + message: 'Unexpected message format received from Meta', + statusCode: 400, + errorCode: 'UNEXPECTED_PAYLOAD_FORMAT', + details: { error: error.message }, + }); + return; + } + logger.error('Error extracting message details', error); + report(error, 'webhook_processing_failure'); + answerMeta(res, { + success: false, + message: 'Error processing webhook payload', + statusCode: 400, + errorCode: 'INVALID_PAYLOAD', + // The parser's own errors carry the payload with every value masked; anything else might not + details: { error: error instanceof InvalidMetaPayloadError ? error.message : 'Unexpected error reading the payload' }, + }); + return; + } + + if (parsed.kind === 'other_number') { + logger.debug('Ignoring webhook not intended for our WhatsApp business number'); + answerMeta(res, { + message: 'Skipping, as this webhook is not intended for our WhatsApp business number', + statusCode: 200, + }); + return; + } + if (parsed.kind === 'status') { + logger.debug('Ignoring status update message (e.g., delivered, read)'); + answerMeta(res, { message: 'Status message processed (ignored)', errorCode: 'STATUS_MESSAGE' }); + return; + } + + // ---- 4. What should be done with the message? Answer Meta first, do it afterwards ---- + const action = manager.triage(parsed); + answerMeta(res, TRIAGE_REPLIES[action]); + // Signing in and asking apps/api can take long enough for Meta to resend the message, and nothing here detects a resend + background.run(() => manager.dispatch(parsed, action)); + }); + + app.use((_req, res) => { + res.status(404).json({ detail: 'Not Found' }); + }); + + // Express recognises an error handler by its four parameters, so `_next` must stay even though it is not used + // eslint-disable-next-line @typescript-eslint/no-unused-vars + app.use((error: unknown, _req: Request, res: Response, _next: NextFunction) => { + const status = httpStatusOf(error); + if (status >= 500) { + logger.error('Unhandled exception', error); + report(error, 'unhandled_exception'); + } else { + logger.error(`HTTP exception: ${status}`); + } + if (res.headersSent) { + res.end(); + return; + } + // Never the error's own text: it can quote part of the request + res.status(status).json({ detail: status >= 500 ? 'Internal server error' : (STATUS_TEXT[status] ?? 'Bad Request') }); + }); + + return app; +} + +/** The status an error from the body parser carries (413 too large, 400 aborted, 415 unsupported encoding); 500 for any other. */ +function httpStatusOf(error: unknown): number { + const status = typeof error === 'object' && error !== null ? (error as { status?: unknown }).status : undefined; + return typeof status === 'number' && status >= 400 && status < 600 ? status : 500; +} + +const STATUS_TEXT: Record = { + 400: 'Bad Request', + 413: 'Payload Too Large', + 415: 'Unsupported Media Type', +}; diff --git a/apps/whatsapp/src/background.ts b/apps/whatsapp/src/background.ts new file mode 100644 index 00000000..86b56a85 --- /dev/null +++ b/apps/whatsapp/src/background.ts @@ -0,0 +1,73 @@ +/** + * Work that runs after Meta has been answered. + * + * Python counterpart: FastAPI's `BackgroundTasks`. Meta wants its HTTP 200 quickly, but signing in and asking apps/api can take + * a minute, so the route replies first and starts the work afterwards. + * + * A promise nobody awaits fails silently in JavaScript: its error goes nowhere (and in Node an unhandled rejection can even end + * the process). Every task therefore runs inside `run()`, the single place that catches, logs and reports what escapes it. The + * tasks are also counted so a shutdown can wait for the answers still being prepared (`idle`). + */ +import type { ErrorReporter } from './errorReporter'; +import { noopErrorReporter } from './errorReporter'; +import { getRequestId, type Logger } from './logger'; + +export class BackgroundTasks { + readonly #running = new Set>(); + readonly #logger: Logger; + readonly #reportError: ErrorReporter; + + constructor(options: { logger: Logger; reportError?: ErrorReporter }) { + this.#logger = options.logger; + this.#reportError = options.reportError ?? noopErrorReporter; + } + + /** How many tasks have started and not yet finished. */ + get pending(): number { + return this.#running.size; + } + + /** + * Start `task` after the current code has finished, so the route's reply is already on its way. Never throws, and neither + * does the promise it starts. + * + * The task writes its log lines under the request id of the request that started it without any help from here: the id lives + * in an `AsyncLocalStorage`, which follows every promise continuation created inside the request. + */ + run(task: () => Promise): void { + const requestId = getRequestId(); + const tracked: Promise = Promise.resolve() + .then(task) + .catch((error: unknown) => { + // Only the request id travels with the report: never a BSUID, phone number, token or message text + this.#logger.error('Unhandled error in background processing', error); + this.#reportError(error, { errorType: 'background_processing_failure', context: { request_id: requestId } }); + }) + .finally(() => { + this.#running.delete(tracked); + }); + this.#running.add(tracked); + } + + /** + * Wait until no task is running, or `timeoutMs` has passed. + * + * @returns `true` if everything finished in time, `false` if some task was still running when the wait ended. + */ + async idle(timeoutMs: number): Promise { + let timer: NodeJS.Timeout | undefined; + const timedOut = new Promise((resolve) => { + timer = setTimeout(() => resolve(false), timeoutMs); + }); + try { + // A finished task can start another (none does today), so look again after each wait + while (this.#running.size > 0) { + const settled = await Promise.race([Promise.allSettled([...this.#running]).then(() => true as const), timedOut]); + if (!settled) return false; + } + return true; + } finally { + clearTimeout(timer); + } + } +} diff --git a/apps/whatsapp/src/index.ts b/apps/whatsapp/src/index.ts new file mode 100644 index 00000000..d3813ff8 --- /dev/null +++ b/apps/whatsapp/src/index.ts @@ -0,0 +1,65 @@ +/** + * apps/whatsapp: the runnable service. Wires the pieces together and listens. + * + * Python counterpart: the module-level code and the `if __name__ == "__main__"` block of `app/main.py`. + * + * Start it with `pnpm --filter ansari-whatsapp dev` (restarts on change) or `start` (runs the built file). + */ +import 'dotenv/config'; +import { BackgroundTasks } from './background'; +import { buildApp } from './app'; +import { getEnv } from './config'; +import { ConversationManager } from './conversationManager'; +import { createLogger } from './logger'; +import { flushSentry, initSentry, sentryReporter } from './sentry'; +import { createServices } from './services/createServices'; +import { gracefulShutdown } from './server'; + +/** Railway waits about this long after SIGTERM before it kills the process. */ +const SHUTDOWN_GRACE_MS = 8_000; + +const env = getEnv(); +const logger = createLogger({ + deploymentType: env.DEPLOYMENT_TYPE, + level: env.LOGGING_LEVEL, + githubActions: process.env.GITHUB_ACTIONS, +}); + +// Sentry stays off for local development, with or without a DSN +if (env.DEPLOYMENT_TYPE !== 'local') initSentry(env.SENTRY_DSN, env.DEPLOYMENT_TYPE); + +const services = createServices(env, logger, sentryReporter); +const background = new BackgroundTasks({ logger, reportError: sentryReporter }); +const manager = new ConversationManager({ + config: env, + ...services, + logger, + reportError: sentryReporter, +}); +const app = buildApp({ config: env, manager, background, logger, reportError: sentryReporter }); + +// Python: "localhost" when developing (not reachable from other machines), every interface when deployed (a container's +// platform proxy reaches it from outside). +const host = env.DEPLOYMENT_TYPE === 'local' ? 'localhost' : '0.0.0.0'; +const server = app.listen(env.PORT, host, () => { + logger.info(`WhatsApp service (${env.DEPLOYMENT_TYPE}) listening on ${host}:${env.PORT}`); +}); + +let stopping = false; +function stop(signal: string): void { + if (stopping) return; + stopping = true; + logger.info(`Received ${signal}`); + void gracefulShutdown({ server, background, logger, graceMs: SHUTDOWN_GRACE_MS, flush: () => flushSentry(2_000) }).then( + () => process.exit(0), + ); +} +process.on('SIGTERM', () => stop('SIGTERM')); +process.on('SIGINT', () => stop('SIGINT')); + +// A fault nobody caught anywhere else: say so, tell the operator, and carry on (the tasks have their own catch, so this is +// for bugs in code that runs outside them) +process.on('unhandledRejection', (reason) => { + logger.error('Unhandled promise rejection', reason); + sentryReporter(reason, { errorType: 'unhandled_rejection' }); +}); diff --git a/apps/whatsapp/src/sentry.ts b/apps/whatsapp/src/sentry.ts new file mode 100644 index 00000000..d53ac165 --- /dev/null +++ b/apps/whatsapp/src/sentry.ts @@ -0,0 +1,70 @@ +/** + * Sentry: how this service tells an operator about a fault. + * + * Python counterpart: the `sentry_sdk.init(...)` block at the top of `app/main.py` and the `set_tag` / `set_context` / + * `capture_exception` calls spread through the services. Here the services only know the small `ErrorReporter` function + * (`errorReporter.ts`); `sentryReporter` below is the one that really sends. + * + * The scrubbing follows `apps/auth/src/alerts.ts`, which has the reasoning and a test that proves it. Sentry's request-data + * integration attaches the in-flight request (headers, cookies, query string, body) to every event raised while that request + * is handled, and `sendDefaultPii: false` covers neither bodies nor the `Authorization` header. A webhook body carries the + * sender's BSUID, phone number and message text, and the handshake's query string carries the verify token, so every event + * keeps only the request's method, path and a few harmless headers. + * + * Differences from Python: + * - Python also sampled traces and profiles (20% in production). Not ported: a trace records each request's URL, and the + * handshake URL holds the verify token. Error reporting is what the service used Sentry for. + * - Python filtered out log events containing "HTTP exception: 401" and "403", which its Sentry logging integration would + * otherwise have sent. Nothing here sends log lines to Sentry, so there is nothing to filter. + */ +import * as Sentry from '@sentry/node'; +import type { ErrorReporter } from './errorReporter'; + +/** Headers an event may keep: none is a credential, and the user agent says who is calling. */ +const KEPT_HEADERS = new Set(['host', 'user-agent', 'content-type']); + +/** Reduce an event's request to its method, its URL without the query string, and the headers in `KEPT_HEADERS`. */ +export function scrubRequestEvent(event: E): E { + const request = event.request; + if (!request) return event; + const headers = Object.fromEntries( + Object.entries(request.headers ?? {}).filter(([name]) => KEPT_HEADERS.has(name.toLowerCase())), + ); + event.request = { method: request.method, url: request.url?.split('?')[0], headers }; + return event; +} + +/** + * Everything this service sets besides the DSN and the environment (tests add only a transport). + * No breadcrumbs: an HTTP breadcrumb carries its request's query string, and every console line would ride along on the next + * event. + */ +export const SENTRY_OPTIONS = { + sendDefaultPii: false, + maxBreadcrumbs: 0, + beforeBreadcrumb: () => null, + beforeSend: scrubRequestEvent, +} as const; + +/** + * Start Sentry. Without a DSN it stays off (Python: `if SENTRY_DSN and deployment_type != "local"`; the caller checks the + * deployment type). + */ +export function initSentry(dsn: string | undefined, environment: string): void { + if (!dsn) return; + Sentry.init({ dsn, environment, ...SENTRY_OPTIONS }); +} + +/** One Sentry event per call, tagged `error_type` and carrying the context (Python: `set_tag` + `set_context`). */ +export const sentryReporter: ErrorReporter = (error, report) => { + Sentry.withScope((scope) => { + scope.setTag('error_type', report.errorType); + if (report.context) scope.setContext('details', report.context); + Sentry.captureException(error); + }); +}; + +/** Send what is still queued, for the moments before the process exits. */ +export async function flushSentry(timeoutMs: number): Promise { + await Sentry.flush(timeoutMs); +} diff --git a/apps/whatsapp/src/server.ts b/apps/whatsapp/src/server.ts new file mode 100644 index 00000000..0307ee57 --- /dev/null +++ b/apps/whatsapp/src/server.ts @@ -0,0 +1,47 @@ +/** + * Stopping the service cleanly. + * + * Python counterpart: none of its own (uvicorn did it). Railway stops a service by sending SIGTERM and killing it after a grace + * period, and a deploy happens while users are mid-conversation. A message Meta has already been answered for lives only in + * a background task, so killing the process at once would drop that user's reply with nobody left to tell them. Shutdown + * therefore stops accepting new requests, waits (up to a limit) for the tasks already started, sends what Sentry still holds, + * and only then lets the process end. + */ +import type { Server } from 'node:http'; +import type { BackgroundTasks } from './background'; +import type { Logger } from './logger'; + +export interface ShutdownOptions { + server: Server; + background: BackgroundTasks; + logger: Logger; + /** How long to wait for running tasks before giving up on them. Railway's own limit is shorter than a chat answer can be. */ + graceMs: number; + /** Runs last, e.g. sending queued Sentry events. A failure here is logged, never thrown. */ + flush?: () => Promise; +} + +/** Stop taking requests, wait for background work, flush. Never throws. Resolves when it is safe to exit. */ +export async function gracefulShutdown(options: ShutdownOptions): Promise { + const { server, background, logger, graceMs, flush } = options; + logger.info(`Shutting down: no new requests, waiting up to ${graceMs / 1000}s for ${background.pending} running task(s)`); + + // Stop listening. Since Node 19 this also closes idle keep-alive connections, which would otherwise delay the callback. + const closed = new Promise((resolve) => server.close(() => resolve())); + + const finished = await background.idle(graceMs); + if (!finished) logger.warn(`Gave up on ${background.pending} task(s) still running after ${graceMs / 1000}s`); + + // Anything still open now is a client that has not finished reading, and the work behind it is over + server.closeAllConnections(); + await closed; + + if (flush) { + try { + await flush(); + } catch (error) { + logger.error('Could not flush error reports before exit', error); + } + } + logger.info('Shutdown complete'); +} diff --git a/apps/whatsapp/src/services/createServices.ts b/apps/whatsapp/src/services/createServices.ts new file mode 100644 index 00000000..27114103 --- /dev/null +++ b/apps/whatsapp/src/services/createServices.ts @@ -0,0 +1,58 @@ +/** + * Choose, for each outside service, the real client or its stand-in. + * + * Python counterparts: `service_provider.py` and `meta_service_provider.py`, which kept a module-level singleton for each and a + * `reset_*` function for tests. Here the choice is made once, at start-up, and the result is passed to whoever needs it, so + * there is nothing global to reset. + * + * The `MOCK_*` switches are refused outside `DEPLOYMENT_TYPE=local` by the configuration itself (`config.ts`), so a stand-in + * can never be chosen on a deployed service. + */ +import type { Env } from '../config'; +import type { ErrorReporter } from '../errorReporter'; +import type { Logger } from '../logger'; +import { AnsariClientMock, AnsariClientReal, type AnsariClient } from './ansariClient'; +import { AuthClientMock, AuthClientReal, type AuthClient } from './authClient'; +import { MetaApiServiceMock, MetaApiServiceReal, type MetaApiService } from './metaApiService'; + +export type ServicesConfig = Pick< + Env, + | 'MOCK_ANSARI_CLIENT' + | 'MOCK_AUTH_CLIENT' + | 'MOCK_AUTH_TOKEN' + | 'MOCK_META_API' + | 'BACKEND_SERVER_URL' + | 'AUTH_SERVER_URL' + | 'AUTH_WHATSAPP_API_KEY' + | 'META_API_URL' + | 'META_ACCESS_TOKEN_FROM_SYS_USER' + | 'DEPLOYMENT_TYPE' +>; + +export interface Services { + ansariClient: AnsariClient; + authClient: AuthClient; + metaApi: MetaApiService; +} + +export function createServices(config: ServicesConfig, logger: Logger, reportError: ErrorReporter): Services { + const ansariClient = config.MOCK_ANSARI_CLIENT + ? new AnsariClientMock({ logger }) + : new AnsariClientReal({ baseUrl: config.BACKEND_SERVER_URL, logger }); + + const authClient = config.MOCK_AUTH_CLIENT + ? new AuthClientMock(config.MOCK_AUTH_TOKEN ? { fixedToken: config.MOCK_AUTH_TOKEN } : {}) + : new AuthClientReal({ baseUrl: config.AUTH_SERVER_URL, apiKey: config.AUTH_WHATSAPP_API_KEY, logger }); + + const metaApi = config.MOCK_META_API + ? new MetaApiServiceMock({ logger }) + : new MetaApiServiceReal({ + apiUrl: config.META_API_URL, + accessToken: config.META_ACCESS_TOKEN_FROM_SYS_USER, + deploymentType: config.DEPLOYMENT_TYPE, + logger, + reportError, + }); + + return { ansariClient, authClient, metaApi }; +} diff --git a/apps/whatsapp/src/webhook/metaResponse.ts b/apps/whatsapp/src/webhook/metaResponse.ts new file mode 100644 index 00000000..76cddde2 --- /dev/null +++ b/apps/whatsapp/src/webhook/metaResponse.ts @@ -0,0 +1,49 @@ +/** + * The JSON body this service answers Meta with, and the HTTP status that goes with it. + * + * Python counterpart: `create_response_for_meta` in `whatsapp_webhook_utils.py`. + * + * Meta wants an HTTP 200 for every webhook it delivers. Any other status (or a reply that takes too long) counts as a failed + * delivery, and Meta then resends it with growing delays for up to 24 hours, which would answer the same user several times. + * https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview#webhook-delivery-failure + * + * So in real use (`ALWAYS_RETURN_OK_TO_META` true) the status is always 200 and only the body says what happened. Automated tests + * turn the flag off to see the real status. + */ + +export interface MetaResponseInput { + success?: boolean; + message?: string; + /** The status to use when the flag is off and `success` is false. */ + statusCode?: number; + /** A machine-readable reason, such as `MAINTENANCE_MODE`. */ + errorCode?: string; + /** Goes under the `detail` key. */ + details?: Record; +} + +export interface MetaResponse { + status: number; + body: Record; +} + +/** + * Build the status and body for one answer to Meta. + * + * @param alwaysOk `ALWAYS_RETURN_OK_TO_META`. + * @param nowSeconds The current unix time; only tests pass it. + */ +export function createResponseForMeta( + input: MetaResponseInput, + alwaysOk: boolean, + nowSeconds: number = Math.floor(Date.now() / 1000), +): MetaResponse { + const { success = true, message = 'OK', statusCode = 200, errorCode, details } = input; + + const body: Record = { success, message, timestamp: nowSeconds }; + // Python's `if error_code:` and `if details:`: an empty string or an empty object is left out + if (errorCode) body.error_code = errorCode; + if (details && Object.keys(details).length > 0) body.detail = details; + + return { status: alwaysOk || success ? 200 : statusCode, body }; +} diff --git a/apps/whatsapp/src/webhook/signature.ts b/apps/whatsapp/src/webhook/signature.ts new file mode 100644 index 00000000..de57b80b --- /dev/null +++ b/apps/whatsapp/src/webhook/signature.ts @@ -0,0 +1,46 @@ +/** + * Proof that a webhook really came from Meta, and the check Meta's one-time handshake uses. + * + * Python counterpart: `verify_meta_signature` in `whatsapp_webhook_utils.py`, and the token comparison in the `GET` route of + * `main.py`. + * + * Meta signs every webhook body with the app secret (HMAC-SHA256) and sends the result in `X-Hub-Signature-256: sha256=`. + * The signature covers the exact bytes Meta sent, so the check must run on the raw body, before any JSON parsing could change + * a single byte. + * https://developers.facebook.com/docs/graph-api/webhooks/getting-started#validate-payloads + * + * Differences from Python: + * - `crypto.timingSafeEqual` replaces `hmac.compare_digest`. Both take the same time however many leading characters match, so + * an attacker cannot learn a signature one character at a time. `timingSafeEqual` throws if its two inputs differ in length, + * so the lengths are compared first (a length is not a secret: a SHA-256 hex digest is always 64 characters). + * - Python compared the hex text after lower-casing nothing, so an upper-case signature never matched. The same here, on purpose: + * Meta sends lower-case hex. + */ +import { createHmac, timingSafeEqual } from 'node:crypto'; +import type { Secret } from '../config'; + +const PREFIX = 'sha256='; + +/** + * Is `signatureHeader` the right signature of `rawBody` under `appSecret`? + * + * @param rawBody The request body exactly as received. + * @param signatureHeader The value of `X-Hub-Signature-256`, or `undefined` if the header is missing. + * @param appSecret Meta's app secret (`META_ANSARI_APP_SECRET`). + */ +export function isValidSignature(rawBody: Buffer, signatureHeader: string | undefined, appSecret: Secret): boolean { + if (!signatureHeader?.startsWith(PREFIX)) return false; + const received = signatureHeader.slice(PREFIX.length); + const computed = createHmac('sha256', appSecret.reveal()).update(rawBody).digest('hex'); + return constantTimeEquals(computed, received); +} + +/** + * Compare two strings in time that does not depend on where they first differ. Python: `hmac.compare_digest` on the UTF-8 + * bytes, which also copes with a non-ASCII token (the comparison happens on bytes, so it never raises). + */ +export function constantTimeEquals(expected: string, actual: string): boolean { + const a = Buffer.from(expected, 'utf8'); + const b = Buffer.from(actual, 'utf8'); + return a.length === b.length && timingSafeEqual(a, b); +} diff --git a/apps/whatsapp/tests/app.test.ts b/apps/whatsapp/tests/app.test.ts new file mode 100644 index 00000000..a881586f --- /dev/null +++ b/apps/whatsapp/tests/app.test.ts @@ -0,0 +1,822 @@ +/** + * The HTTP app: what Meta sees when it calls the service. + * + * Python tests ported (all through a real listening server and `fetch`, where Python used `TestClient`): + * - `test_whatsapp_service.py`: health, the handshake, a basic webhook, missing and wrong signatures, a phone-hidden user, + * a message with neither `from` nor `from_user_id`. + * - `test_environment_behaviour.py`: a signed body that is not JSON is a 400, the handshake accepts the right token and refuses + * others (a non-ASCII token included), maintenance mode, the staging `!d ` filter, an unsupported type. + * - `test_bsuid_auth_flow.py`: the webhook flow (who is signed in, who is replied to), and that no log line holds a phone number, + * BSUID, message text or the verify token. + * + * New here, because Express differs from FastAPI: the 200 is observed while slow background work is still running (the plan's + * acknowledgment test), a failing background task is reported, and the signature is checked before the body is parsed. + * + * Meta's webhook statuses only show with `ALWAYS_RETURN_OK_TO_META=false`, which is how these tests run unless stated. + */ +import { afterEach, describe, expect, it } from 'vitest'; +import { WEBHOOK_PATH } from '../src/app'; +import { AuthTokenError, MetaApiError } from '../src/errors'; +import { AnsariClientMock, type AnsariClient } from '../src/services/ansariClient'; +import { AuthClientMock, type AuthClient } from '../src/services/authClient'; +import type { MetaApiService } from '../src/services/metaApiService'; +import { FIXED_NOW_UNIX } from './fixtures/pythonOracle'; +import { capturingLogger } from './helpers/network'; +import { + APP_SECRET, + BSUID, + NOW, + PHONE, + PHONE_NUMBER_ID, + VERIFY_TOKEN, + messageOf, + sign, + startApp, + webhookPayload, + type TestApp, +} from './helpers/app'; + +let app: TestApp | undefined; + +afterEach(async () => { + await app?.close(); + app = undefined; +}); + +async function started(options: Parameters[0] = {}): Promise { + app = await startApp(options); + return app; +} + +function handshake(t: TestApp, query: Record) { + return fetch(`${t.url}${WEBHOOK_PATH}?${new URLSearchParams(query)}`); +} + +// --------------------------------------------------------------------------------------------------------------------- +describe('health', () => { + it('answers GET / with ok', async () => { + const t = await started(); + const response = await fetch(`${t.url}/`); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ status: 'ok', message: 'Ansari WhatsApp service is running' }); + }); + + it('does not say what it runs on', async () => { + const t = await started(); + expect((await fetch(`${t.url}/`)).headers.get('x-powered-by')).toBeNull(); + }); +}); + +describe('request ids', () => { + it('gives each response its own id', async () => { + const t = await started(); + const first = (await fetch(`${t.url}/`)).headers.get('x-request-id'); + const second = (await fetch(`${t.url}/`)).headers.get('x-request-id'); + expect(first).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + expect(second).not.toBe(first); + }); + + it('ignores an id the caller supplies, since it would go into the logs unchecked', async () => { + const t = await started(); + const response = await fetch(`${t.url}/`, { headers: { 'X-Request-ID': 'attacker-INJECTED' } }); + expect(response.headers.get('x-request-id')).not.toContain('INJECTED'); + expect(t.log.text()).not.toContain('INJECTED'); + }); + + it('puts the response id on that request\'s log lines', async () => { + const t = await started(); + const id = (await fetch(`${t.url}/`)).headers.get('x-request-id'); + const lines = t.log.lines().filter((line) => line.message === 'Health check endpoint called'); + expect(lines).toHaveLength(1); + expect((lines[0] as unknown as { request_id: string }).request_id).toBe(id); + }); + + it('keeps the request id on the lines the background work writes after the reply', async () => { + const t = await started(); + const response = await t.post(webhookPayload()); + await t.settle(); + const id = response.headers.get('x-request-id'); + const backgroundLine = t.log.lines().find((line) => line.message.startsWith('Authenticated whatsapp user')); + expect((backgroundLine as unknown as { request_id: string }).request_id).toBe(id); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('the verification handshake', () => { + it('echoes the challenge for the right token', async () => { + const t = await started(); + const response = await handshake(t, { 'hub.mode': 'subscribe', 'hub.verify_token': VERIFY_TOKEN, 'hub.challenge': 'abc123' }); + expect(response.status).toBe(200); + expect(await response.text()).toBe('abc123'); + }); + + it('answers as html, as Meta\'s own sample and the Python service did', async () => { + const t = await started(); + const response = await handshake(t, { 'hub.mode': 'subscribe', 'hub.verify_token': VERIFY_TOKEN, 'hub.challenge': 'abc123' }); + expect(response.headers.get('content-type')).toContain('text/html'); + }); + + it.each([VERIFY_TOKEN + 'x', VERIFY_TOKEN.slice(0, -1), 'wrong', 't\u00e9st', '\u0645\u0631\u062d\u0628\u0627'])( + 'refuses the token %j with a 403, not a crash', + async (token) => { + const t = await started(); + const response = await handshake(t, { 'hub.mode': 'subscribe', 'hub.verify_token': token, 'hub.challenge': 'abc123' }); + expect(response.status).toBe(403); + expect(await response.json()).toEqual({ detail: 'Forbidden' }); + }, + ); + + it('refuses the right token with a mode other than subscribe', async () => { + const t = await started(); + const response = await handshake(t, { 'hub.mode': 'unsubscribe', 'hub.verify_token': VERIFY_TOKEN, 'hub.challenge': 'abc123' }); + expect(response.status).toBe(403); + }); + + it.each([ + [{}], + [{ 'hub.mode': 'subscribe' }], + [{ 'hub.verify_token': VERIFY_TOKEN }], + [{ 'hub.mode': '', 'hub.verify_token': VERIFY_TOKEN }], + [{ 'hub.mode': 'subscribe', 'hub.verify_token': '' }], + ])('answers 400 when the mode or the token is missing: %j', async (query) => { + const t = await started(); + expect((await handshake(t, query)).status).toBe(400); + }); + + it('answers an empty challenge when Meta sends none, as Python did', async () => { + const t = await started(); + const response = await handshake(t, { 'hub.mode': 'subscribe', 'hub.verify_token': VERIFY_TOKEN }); + expect(response.status).toBe(200); + expect(await response.text()).toBe(''); + }); + + it('uses the last value when a parameter is repeated, as Starlette did', async () => { + const t = await started(); + const response = await fetch( + `${t.url}${WEBHOOK_PATH}?hub.mode=subscribe&hub.verify_token=wrong&hub.verify_token=${VERIFY_TOKEN}&hub.challenge=c1`, + ); + expect(await response.text()).toBe('c1'); + }); + + it('never writes the right token, or a wrong one, to the logs', async () => { + const t = await started(); + await handshake(t, { 'hub.mode': 'subscribe', 'hub.verify_token': VERIFY_TOKEN, 'hub.challenge': 'c1' }); + await handshake(t, { 'hub.mode': 'subscribe', 'hub.verify_token': 'a-wrong-token-value', 'hub.challenge': 'c2' }); + const text = t.log.text(); + expect(text.length).toBeGreaterThan(0); + expect(text).not.toContain(VERIFY_TOKEN); + expect(text).not.toContain('a-wrong-token-value'); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('the signature', () => { + it('rejects a webhook with no signature header', async () => { + const t = await started(); + const response = await t.post(webhookPayload(), { secret: false }); + expect(response.status).toBe(403); + expect(response.json).toEqual({ detail: 'Invalid signature' }); + expect(response.headers.get('www-authenticate')).toBe('HMAC-SHA256'); + }); + + it('rejects a webhook signed with the wrong secret', async () => { + const t = await started(); + expect((await t.post(webhookPayload(), { secret: 'not-the-app-secret' })).status).toBe(403); + }); + + it.each(['', 'sha256=', 'sha1=abcd', 'abcd', 'SHA256=abcd', 'sha256=zzzz', 'sha256= '])('rejects the header %j', async (signature) => { + const t = await started(); + expect((await t.post(webhookPayload(), { signature })).status).toBe(403); + }); + + it('rejects the right digest in upper case, as Python did', async () => { + const t = await started(); + const body = JSON.stringify(webhookPayload()); + const upper = `sha256=${sign(body).slice('sha256='.length).toUpperCase()}`; + expect((await t.post(null, { raw: body, signature: upper })).status).toBe(403); + }); + + it('rejects a signature made for a different body', async () => { + const t = await started(); + const body = JSON.stringify(webhookPayload()); + const other = JSON.stringify(webhookPayload({ id: 'wamid.OTHER' })); + expect((await t.post(null, { raw: body, signature: sign(other) })).status).toBe(403); + }); + + it('checks the exact bytes: the same JSON with different spacing no longer matches', async () => { + const t = await started(); + const compact = JSON.stringify(webhookPayload()); + const spaced = JSON.stringify(webhookPayload(), null, 2); + expect((await t.post(null, { raw: spaced, signature: sign(compact) })).status).toBe(403); + expect((await t.post(null, { raw: spaced })).status).toBe(200); + }); + + it('accepts a body with non-ASCII text signed over its UTF-8 bytes', async () => { + const t = await started(); + const body = webhookPayload({ text: { body: '\u0645\u0631\u062d\u0628\u0627 \u{1F600}' } }); + expect((await t.post(body)).status).toBe(200); + }); + + it('answers 403 before looking at the body, so an unsigned caller cannot tell good JSON from bad', async () => { + const t = await started(); + const good = await t.post(null, { raw: '{}', secret: false }); + const bad = await t.post(null, { raw: 'this is not json', secret: false }); + expect([good.status, bad.status]).toEqual([403, 403]); + expect(good.text).toBe(bad.text); + }); + + it('checks the signature even when the content type is not JSON, since Meta\'s is the only thing that vouches for the bytes', async () => { + const t = await started(); + const body = JSON.stringify(webhookPayload()); + expect((await t.post(null, { raw: body, contentType: 'text/plain', secret: false })).status).toBe(403); + expect((await t.post(null, { raw: body, contentType: 'text/plain' })).status).toBe(200); + expect((await t.post(null, { raw: body, contentType: null })).status).toBe(200); + }); + + it('a request with no body at all is rejected for its signature, not a crash', async () => { + const t = await started(); + const response = await fetch(`${t.url}${WEBHOOK_PATH}`, { method: 'POST' }); + expect(response.status).toBe(403); + }); + + it('refuses a body over the size limit before anything else', async () => { + const t = await started(); + const huge = 'x'.repeat(1_200_000); + const response = await t.post(null, { raw: huge }); + expect(response.status).toBe(413); + expect(response.json).toEqual({ detail: 'Payload Too Large' }); + }); + + it('keeps the signature and the app secret out of the logs', async () => { + const t = await started(); + const body = JSON.stringify(webhookPayload()); + const signature = sign(body, 'not-the-app-secret'); + await t.post(null, { raw: body, signature }); + const text = t.log.text(); + expect(text).toContain('Invalid webhook signature'); + expect(text).not.toContain(signature.slice('sha256='.length)); + expect(text).not.toContain(APP_SECRET); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('answering Meta before the work is done', () => { + /** A Meta stand-in whose reply to the user stalls until the test releases it. */ + function stalledMeta() { + let release: () => void = () => {}; + const gate = new Promise((resolve) => (release = resolve)); + const state = { sendStarted: false, sendFinished: false, typing: 0 }; + const metaApi: MetaApiService = { + sendTypingIndicator: async () => { + state.typing += 1; + }, + sendMessage: async () => { + state.sendStarted = true; + await gate; + state.sendFinished = true; + }, + }; + return { metaApi, state, release: () => release() }; + } + + it('sends the 200 while the user\'s reply is still stalled', async () => { + const stalled = stalledMeta(); + const t = await started({ metaApi: stalled.metaApi }); + + const response = await t.post(webhookPayload()); + + expect(response.status).toBe(200); + expect(response.json).toMatchObject({ success: true, message: 'Message processed successfully' }); + expect(stalled.state.sendFinished).toBe(false); + expect(t.background.pending).toBe(1); + + stalled.release(); + await t.settle(); + expect(stalled.state.sendFinished).toBe(true); + expect(t.background.pending).toBe(0); + }); + + it('answers Meta while apps/auth is still working, so a slow sign-in cannot make Meta resend', async () => { + let release: () => void = () => {}; + const gate = new Promise((resolve) => (release = resolve)); + const slowAuth: AuthClient = { + getToken: async () => { + await gate; + return new AuthClientMock().getToken(BSUID); + }, + forget: () => {}, + }; + const t = await started({ authClient: slowAuth }); + + const response = await t.post(webhookPayload()); + + expect(response.status).toBe(200); + expect(t.replies()).toEqual([]); + release(); + await t.settle(); + expect(t.replies()).toHaveLength(1); + }); + + it('answers Meta while apps/api is still working', async () => { + let release: () => void = () => {}; + const gate = new Promise((resolve) => (release = resolve)); + const inner = new AnsariClientMock({ logger: capturingLogger().logger, now: () => NOW }); + const slowApi: AnsariClient = { + createThread: (...args) => inner.createThread(...args), + deleteThread: (...args) => inner.deleteThread(...args), + getLastThreadInfo: (...args) => inner.getLastThreadInfo(...args), + processMessage: async (...args) => (await gate, inner.processMessage(...args)), + }; + const t = await started({ ansariClient: slowApi }); + + expect((await t.post(webhookPayload())).status).toBe(200); + expect(t.replies()).toEqual([]); + release(); + await t.settle(); + expect(t.replies()).toHaveLength(1); + }); + + it('answers the maintenance notice after the reply too', async () => { + const stalled = stalledMeta(); + const t = await started({ metaApi: stalled.metaApi, env: { WA_MAINTENANCE_MODE: 'true' } }); + const response = await t.post(webhookPayload()); + expect(response.status).toBe(503); + expect(stalled.state.sendFinished).toBe(false); + stalled.release(); + await t.settle(); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('a message', () => { + it('is answered, with the 200 body Meta expects', async () => { + const t = await started(); + const response = await t.post(webhookPayload({}, {})); + await t.settle(); + + expect(response.status).toBe(200); + expect(response.json.success).toBe(true); + expect(response.json.message).toBe('Message processed successfully'); + expect(typeof response.json.timestamp).toBe('number'); + expect(t.replies()).toHaveLength(1); + expect(t.replies()[0]).toContain('mock AI assistant'); + }); + + it('answers a phone-hidden user (a BSUID and no phone) like any other', async () => { + const t = await started(); + const body = webhookPayload( + { from_user_id: BSUID }, + { contacts: [{ profile: { name: 'Test User', username: 'testuser' }, user_id: BSUID }] }, + ); + const response = await t.post(body); + await t.settle(); + expect(response.status).toBe(200); + expect(response.json.success).toBe(true); + expect(t.recipients()).toEqual([BSUID]); + }); + + it('replies to the BSUID even when the webhook carries a phone', async () => { + const t = await started(); + await t.post(webhookPayload({ from: PHONE })); + await t.settle(); + expect(new Set(t.recipients())).toEqual(new Set([BSUID])); + }); + + it('replies to the phone when META_REPLY_BY_PHONE is on', async () => { + const t = await started({ env: { META_REPLY_BY_PHONE: 'true' } }); + await t.post(webhookPayload({ from: PHONE })); + await t.settle(); + expect(new Set(t.recipients())).toEqual(new Set([PHONE])); + }); + + it('falls back to the BSUID when the phone is hidden and META_REPLY_BY_PHONE is on', async () => { + const t = await started({ env: { META_REPLY_BY_PHONE: 'true' } }); + await t.post(webhookPayload()); + await t.settle(); + expect(new Set(t.recipients())).toEqual(new Set([BSUID])); + }); + + it('tells the user when signing in fails, after Meta has its 200', async () => { + const t = await started({ + authClient: { + getToken: async () => { + throw new AuthTokenError('apps/auth is down'); + }, + forget: () => {}, + }, + }); + const response = await t.post(webhookPayload()); + await t.settle(); + expect(response.status).toBe(200); + expect(t.recipients()).toEqual([BSUID]); + expect(t.replies().join('')).toContain('sign you in'); + expect(t.reports.map((r) => r.report.errorType)).toEqual(['auth_token_failure']); + }); + + it('writes no phone number, BSUID or message text to the logs', async () => { + const t = await started({ env: { META_REPLY_BY_PHONE: 'true' } }); + await t.post(webhookPayload({ from: PHONE, text: { body: 'a-very-distinctive-question' } })); + await t.settle(); + const text = t.log.text(); + expect(text.length).toBeGreaterThan(0); + expect(text).not.toContain(PHONE); + expect(text).not.toContain(BSUID); + expect(text).not.toContain('a-very-distinctive-question'); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('what is not a message', () => { + it('skips a webhook meant for another business number', async () => { + const t = await started(); + const response = await t.post(webhookPayload({}, { phoneNumberId: '999' })); + expect(response.status).toBe(200); + expect(response.json).toMatchObject({ + success: true, + message: 'Skipping, as this webhook is not intended for our WhatsApp business number', + }); + await t.settle(); + expect(t.replies()).toEqual([]); + }); + + it('acknowledges a delivery receipt and does nothing', async () => { + const t = await started(); + const body = { + object: 'whatsapp_business_account', + entry: [{ changes: [{ value: { metadata: { phone_number_id: PHONE_NUMBER_ID }, statuses: [{ status: 'delivered' }] } }] }], + }; + const response = await t.post(body); + expect(response.status).toBe(200); + expect(response.json).toMatchObject({ success: true, message: 'Status message processed (ignored)', error_code: 'STATUS_MESSAGE' }); + await t.settle(); + expect(t.replies()).toEqual([]); + expect(t.background.pending).toBe(0); + }); +}); + +describe('what Meta is told for each kind of message (ALWAYS_RETURN_OK_TO_META off)', () => { + it('maintenance mode: 503 MAINTENANCE_MODE, the notice is sent and nobody is signed in', async () => { + let exchanges = 0; + const t = await started({ + env: { WA_MAINTENANCE_MODE: 'true' }, + authClient: { + getToken: async () => { + exchanges += 1; + return 'x'; + }, + forget: () => {}, + }, + }); + const response = await t.post(webhookPayload()); + await t.settle(); + expect(response.status).toBe(503); + expect(response.json).toMatchObject({ success: false, error_code: 'MAINTENANCE_MODE', message: 'Service under maintenance' }); + expect(t.replies().join('')).toContain('down for maintenance'); + expect(exchanges).toBe(0); + }); + + it('maintenance mode off: answered normally', async () => { + const t = await started({ env: { WA_MAINTENANCE_MODE: 'false' } }); + const response = await t.post(webhookPayload()); + await t.settle(); + expect(response.status).toBe(200); + expect(t.replies().join('')).toContain('mock AI assistant'); + }); + + it('staging "!d " message: 202 DEV_FILTER and no chat call', async () => { + const t = await started({ env: { DEPLOYMENT_TYPE: 'staging', MOCK_ANSARI_CLIENT: undefined } }); + const response = await t.post(webhookPayload({ text: { body: '!d what is ansari?' } })); + await t.settle(); + expect(response.status).toBe(202); + expect(response.json).toMatchObject({ success: false, error_code: 'DEV_FILTER' }); + expect(t.replies()).toEqual([]); + }); + + it('staging message without the prefix: answered', async () => { + const t = await started({ env: { DEPLOYMENT_TYPE: 'staging' } }); + const response = await t.post(webhookPayload({ text: { body: 'what is ansari?' } })); + await t.settle(); + expect(response.status).toBe(200); + expect(t.replies()).toHaveLength(1); + }); + + it('local message with the prefix: answered', async () => { + const t = await started({ env: { DEPLOYMENT_TYPE: 'local' } }); + const response = await t.post(webhookPayload({ text: { body: '!d what is ansari?' } })); + await t.settle(); + expect(response.status).toBe(200); + expect(t.replies()).toHaveLength(1); + }); + + it('a message older than the threshold: 422 MESSAGE_TOO_OLD and nothing sent', async () => { + const t = await started(); + const old = String(Math.floor(Date.now() / 1000) - 3 * 86400); + const response = await t.post(webhookPayload({ timestamp: old })); + await t.settle(); + expect(response.status).toBe(422); + expect(response.json).toMatchObject({ success: false, error_code: 'MESSAGE_TOO_OLD' }); + expect(t.replies()).toEqual([]); + }); + + it('an unsupported type: 415 UNSUPPORTED_MESSAGE_TYPE and the user is told', async () => { + const t = await started(); + const response = await t.post( + webhookPayload({ type: 'image', image: { id: 'media1' }, timestamp: String(Math.floor(Date.now() / 1000)) }), + ); + await t.settle(); + expect(response.status).toBe(415); + expect(response.json).toMatchObject({ success: false, error_code: 'UNSUPPORTED_MESSAGE_TYPE' }); + expect(t.replies()).toEqual(["Sorry, I can't process images yet. Please send me a text message."]); + }); + + // Meta sends an unsupported type (video note, poll...) as an `errors` list, not an object with a body + it('an unsupported type in staging does not crash the filter', async () => { + const t = await started({ env: { DEPLOYMENT_TYPE: 'staging' } }); + const body = webhookPayload({ + type: 'unsupported', + errors: [{ code: 131051, title: 'Message type is not supported' }], + timestamp: String(Math.floor(Date.now() / 1000)), + }); + delete messageOf(body).text; + const response = await t.post(body); + await t.settle(); + expect(response.json.error_code).toBe('UNSUPPORTED_MESSAGE_TYPE'); + }); +}); + +describe('with ALWAYS_RETURN_OK_TO_META on (what Meta really gets)', () => { + it.each([ + ['maintenance mode', { WA_MAINTENANCE_MODE: 'true' }, webhookPayload(), 'MAINTENANCE_MODE'], + ['the staging filter', { DEPLOYMENT_TYPE: 'staging' }, webhookPayload({ text: { body: '!d hi' } }), 'DEV_FILTER'], + ['an unsupported type', {}, webhookPayload({ type: 'image', image: { id: 'm' } }), 'UNSUPPORTED_MESSAGE_TYPE'], + ])('answers 200 for %s, and the body still says why', async (_name, env, payload, errorCode) => { + const t = await started({ env: { ALWAYS_RETURN_OK_TO_META: 'true', ...env } }); + const response = await t.post(payload); + await t.settle(); + expect(response.status).toBe(200); + expect(response.json).toMatchObject({ success: false, error_code: errorCode }); + }); + + it('answers 200 for a body that is not JSON', async () => { + const t = await started({ env: { ALWAYS_RETURN_OK_TO_META: 'true' } }); + const response = await t.post(null, { raw: 'this is not json' }); + expect(response.status).toBe(200); + expect(response.json).toMatchObject({ success: false, error_code: 'INVALID_PAYLOAD' }); + }); + + it('still answers 403 for a bad signature: that is not a delivery to acknowledge', async () => { + const t = await started({ env: { ALWAYS_RETURN_OK_TO_META: 'true' } }); + expect((await t.post(webhookPayload(), { secret: false })).status).toBe(403); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('a signed body that cannot be read', () => { + it.each([ + ['text that is not JSON', 'this is not json'], + ['an empty body', ''], + ['bytes that are not UTF-8', Buffer.from([0xff, 0xfe])], + ['a JSON string', '"hello"'], + ['a JSON number', '5'], + ['JSON null', 'null'], + ['an empty list', '[]'], + ['an empty object', '{}'], + ])('%s is a 400 INVALID_PAYLOAD, not a crash', async (_name, raw) => { + const t = await started(); + const response = await t.post(null, { raw }); + expect(response.status).toBe(400); + expect(response.json.error_code).toBe('INVALID_PAYLOAD'); + expect(response.json.success).toBe(false); + }); + + // Python's json.loads raises UnicodeDecodeError on bytes that are not UTF-8 (checked on the legacy interpreter). A lenient + // decoder would turn the bad byte into U+FFFD and go on to read, and answer, a message Meta never sent. + it('refuses JSON that is well formed except for one byte that is not UTF-8', async () => { + const t = await started(); + const text = JSON.stringify(webhookPayload({ text: { body: 'before-after' } })); + const raw = Buffer.concat([ + Buffer.from(text.slice(0, text.indexOf('before-') + 'before-'.length)), + Buffer.from([0xff]), + Buffer.from(text.slice(text.indexOf('before-') + 'before-'.length)), + ]); + expect(JSON.parse(raw.toString('utf8'))).toBeTruthy(); // a lenient reader would accept it + + const response = await t.post(null, { raw }); + await t.settle(); + + expect(response.status).toBe(400); + expect(response.json.error_code).toBe('INVALID_PAYLOAD'); + expect(t.replies()).toEqual([]); + }); + + it('does not echo the body in the answer, the log or the report: a JSON syntax error quotes it', async () => { + const t = await started(); + const response = await t.post(null, { raw: '{"text": a-very-distinctive-question' }); + expect(response.status).toBe(400); + expect(response.text).not.toContain('a-very-distinctive-question'); + expect(t.log.text()).not.toContain('a-very-distinctive-question'); + expect(JSON.stringify(t.reports.map((r) => r.report))).not.toContain('a-very-distinctive-question'); + expect(t.reports.map((r) => r.report.errorType)).toEqual(['webhook_processing_failure']); + }); + + it('reports an invalid payload, with the request id', async () => { + const t = await started(); + const response = await t.post({ object: 'whatsapp_business_account', entry: [] }); + expect(response.status).toBe(400); + expect(t.reports.map((r) => r.report.errorType)).toEqual(['webhook_processing_failure']); + expect(t.reports[0]!.report.context).toEqual({ request_id: response.headers.get('x-request-id') }); + }); + + it('keeps the payload with its text masked in the answer', async () => { + const t = await started(); + const body = webhookPayload({ from_user_id: 42, text: { body: 'a-very-distinctive-question' } }); + const response = await t.post(body); + expect(response.status).toBe(400); + expect(response.text).not.toContain('a-very-distinctive-question'); + }); +}); + +describe('a message with no one to answer', () => { + it('without `from_user_id` is an unexpected format, reported, and nobody can be told', async () => { + const t = await started(); + const body = webhookPayload(); + delete messageOf(body).from_user_id; + const response = await t.post(body); + await t.settle(); + expect(response.status).toBe(400); + expect(response.json.error_code).toBe('UNEXPECTED_PAYLOAD_FORMAT'); + expect(t.reports.map((r) => r.report.errorType)).toEqual(['unexpected_meta_payload']); + expect(t.replies()).toEqual([]); + expect(t.log.text()).toContain('No phone number or BSUID in the payload'); + }); + + // Python worked out whom to tell from `from_user_id` or the contact's `user_id`, never from the phone + it('with only a phone, even with META_REPLY_BY_PHONE on: nobody is told, and no phone number is logged', async () => { + const t = await started({ env: { META_REPLY_BY_PHONE: 'true' } }); + const body = webhookPayload({ from: PHONE }); + delete messageOf(body).from_user_id; + const response = await t.post(body); + await t.settle(); + expect(response.json.error_code).toBe('UNEXPECTED_PAYLOAD_FORMAT'); + expect(t.replies()).toEqual([]); + expect(t.log.text()).not.toContain(PHONE); + }); + + it('missing a key but with the sender in the contacts list: the user is told the format was unexpected', async () => { + const t = await started(); + const body = webhookPayload({}, { contacts: [{ profile: { name: 'Test User' }, user_id: BSUID }] }); + delete messageOf(body).from_user_id; + const response = await t.post(body); + await t.settle(); + expect(response.json.error_code).toBe('UNEXPECTED_PAYLOAD_FORMAT'); + expect(t.recipients()).toEqual([BSUID]); + expect(t.replies().join('')).toContain('unexpected format'); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('a fault in the background work', () => { + it('is logged and reported, never an unhandled rejection, and the server keeps working', async () => { + const rejections: unknown[] = []; + const listener = (reason: unknown) => rejections.push(reason); + process.on('unhandledRejection', listener); + try { + const sent: string[] = []; + const metaApi: MetaApiService = { + sendTypingIndicator: async () => {}, + sendMessage: async (_recipient, parts) => { + sent.push(...parts); + }, + }; + const broken: AnsariClient = { + createThread: async () => { + throw new RangeError('a bug inside the thread code'); + }, + deleteThread: async () => {}, + getLastThreadInfo: async () => { + throw new RangeError('a bug inside the thread code'); + }, + processMessage: async () => '', + }; + const t = await started({ metaApi, ansariClient: broken }); + + const response = await t.post(webhookPayload()); + await t.settle(); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(response.status).toBe(200); + expect(rejections).toEqual([]); + // The manager catches it and tells the user; Meta's own refusal is not what is tested here + expect(sent.join('')).toContain('unexpected error'); + expect((await fetch(`${t.url}/`)).status).toBe(200); + } finally { + process.off('unhandledRejection', listener); + } + }); + + it('a task that throws is reported under background_processing_failure with the request id', async () => { + const t = await started(); + t.background.run(async () => { + throw new MetaApiError('this escaped everything', 500); + }); + await t.settle(); + expect(t.reports.map((r) => r.report.errorType)).toEqual(['background_processing_failure']); + expect(t.reports[0]!.error).toBeInstanceOf(MetaApiError); + expect(t.log.lines().some((line) => line.level === 'error' && line.message.includes('Unhandled error in background'))).toBe(true); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('CORS', () => { + it('lets an allowed origin read the answer', async () => { + const t = await started(); + const response = await fetch(`${t.url}/`, { headers: { Origin: 'https://allowed.example' } }); + expect(response.headers.get('access-control-allow-origin')).toBe('https://allowed.example'); + }); + + it('gives a disallowed origin no CORS headers, and logs it', async () => { + const t = await started(); + const response = await fetch(`${t.url}/`, { headers: { Origin: 'https://evil.example' } }); + expect(response.status).toBe(200); + expect(response.headers.get('access-control-allow-origin')).toBeNull(); + expect(t.log.lines().some((line) => line.level === 'error' && line.message.includes('CORS Origin Error'))).toBe(true); + }); + + it('adds no CORS headers to a call with no Origin, which is how Meta\'s servers call', async () => { + const t = await started(); + const response = await fetch(`${t.url}/`); + expect(response.headers.get('access-control-allow-origin')).toBeNull(); + expect(t.log.text()).not.toContain('CORS Origin Error'); + }); + + it('always allows the backend URL and WhatsApp Web, which the configuration adds', async () => { + const t = await started(); + for (const origin of ['http://localhost:3000', 'https://web.whatsapp.com']) { + const response = await fetch(`${t.url}/`, { headers: { Origin: origin } }); + expect(response.headers.get('access-control-allow-origin')).toBe(origin); + } + }); + + it('answers a preflight from an allowed origin', async () => { + const t = await started(); + const response = await fetch(`${t.url}${WEBHOOK_PATH}`, { + method: 'OPTIONS', + headers: { + Origin: 'https://allowed.example', + 'Access-Control-Request-Method': 'POST', + 'Access-Control-Request-Headers': 'content-type', + }, + }); + expect(response.status).toBe(204); + expect(response.headers.get('access-control-allow-origin')).toBe('https://allowed.example'); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('everything else', () => { + it('serves the new path only: the old /whatsapp/v2 is not found', async () => { + const t = await started(); + expect((await fetch(`${t.url}/whatsapp/v2`)).status).toBe(404); + expect((await fetch(`${t.url}/whatsapp/v2`, { method: 'POST', body: '{}' })).status).toBe(404); + }); + + it('answers an unknown path with 404 JSON', async () => { + const t = await started(); + const response = await fetch(`${t.url}/nope`); + expect(response.status).toBe(404); + expect(await response.json()).toEqual({ detail: 'Not Found' }); + }); + + it.each(['local', 'development', 'staging'])('serves /sentry-debug in %s, and it fails on purpose', async (deploymentType) => { + const t = await started({ env: { DEPLOYMENT_TYPE: deploymentType, MOCK_ANSARI_CLIENT: undefined } }); + const response = await fetch(`${t.url}/sentry-debug`); + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ detail: 'Internal server error' }); + expect(t.reports.map((r) => r.report.errorType)).toEqual(['unhandled_exception']); + }); + + it('does not serve /sentry-debug in production', async () => { + const t = await started({ + env: { + DEPLOYMENT_TYPE: 'production', + MOCK_ANSARI_CLIENT: 'false', + MOCK_AUTH_CLIENT: 'false', + MOCK_META_API: 'false', + }, + }); + expect((await fetch(`${t.url}/sentry-debug`)).status).toBe(404); + expect(t.reports).toEqual([]); + }); + + it('never shows the text of an unexpected error to the caller', async () => { + const t = await started(); + const response = await fetch(`${t.url}/sentry-debug`); + expect(await response.text()).not.toContain('Deliberate'); + }); +}); + +describe('the settings the app reads', () => { + it('uses the payload timestamp the tests froze, so the age check is not time-dependent here', () => { + expect(FIXED_NOW_UNIX).toBeGreaterThan(0); + }); +}); diff --git a/apps/whatsapp/tests/appParserFault.test.ts b/apps/whatsapp/tests/appParserFault.test.ts new file mode 100644 index 00000000..7502f3c5 --- /dev/null +++ b/apps/whatsapp/tests/appParserFault.test.ts @@ -0,0 +1,45 @@ +/** + * What the app answers when the payload parser fails in a way it was never written to: a bug, not Meta's mistake. + * + * Its own file because it replaces the parser for the whole file (`vi.mock`). The real parser only ever throws its own two error + * classes, so there is no payload that reaches this branch; the test makes one. + * + * Python counterpart: the `except Exception` branch of `main_webhook`, which answered `INVALID_PAYLOAD` with `str(e)`. + */ +import { afterEach, expect, it, vi } from 'vitest'; +import { startApp, webhookPayload, type TestApp } from './helpers/app'; + +vi.mock('../src/webhook/parseWebhook', () => ({ + parseMetaPayload: () => { + throw new TypeError('a bug that mentions a-very-distinctive-question'); + }, +})); + +let app: TestApp | undefined; + +afterEach(async () => { + await app?.close(); + app = undefined; +}); + +it('answers INVALID_PAYLOAD without the error\'s own text, which could quote the payload', async () => { + app = await startApp(); + + const response = await app.post(webhookPayload()); + + expect(response.status).toBe(400); + expect(response.json.error_code).toBe('INVALID_PAYLOAD'); + expect(response.json.detail).toEqual({ error: 'Unexpected error reading the payload' }); + expect(response.text).not.toContain('a-very-distinctive-question'); +}); + +it('reports it to the operator with the real error, so the bug can be found', async () => { + app = await startApp(); + + const response = await app.post(webhookPayload()); + + expect(app.reports).toHaveLength(1); + expect(app.reports[0]!.report.errorType).toBe('webhook_processing_failure'); + expect(app.reports[0]!.report.context).toEqual({ request_id: response.headers.get('x-request-id') }); + expect(app.reports[0]!.error).toBeInstanceOf(TypeError); +}); diff --git a/apps/whatsapp/tests/backgroundAndServer.test.ts b/apps/whatsapp/tests/backgroundAndServer.test.ts new file mode 100644 index 00000000..ed6e64ff --- /dev/null +++ b/apps/whatsapp/tests/backgroundAndServer.test.ts @@ -0,0 +1,480 @@ +/** + * Background tasks, graceful shutdown, Sentry scrubbing and the choice of real or mock services. + * + * Python counterparts: FastAPI's `BackgroundTasks` and uvicorn's shutdown (neither tested in Python), the `sentry_sdk.init` block + * of `main.py`, and `service_provider.py`. + */ +import { Agent, createServer, get, type Server } from 'node:http'; +import type { Socket } from 'node:net'; +import * as Sentry from '@sentry/node'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { BackgroundTasks } from '../src/background'; +import { Secret } from '../src/config'; +import type { ErrorReport } from '../src/errorReporter'; +import { runWithRequestId } from '../src/logger'; +import { SENTRY_OPTIONS, scrubRequestEvent, sentryReporter } from '../src/sentry'; +import { gracefulShutdown } from '../src/server'; +import { AnsariClientMock, AnsariClientReal } from '../src/services/ansariClient'; +import { AuthClientMock, AuthClientReal } from '../src/services/authClient'; +import { createServices, type ServicesConfig } from '../src/services/createServices'; +import { MetaApiServiceMock, MetaApiServiceReal } from '../src/services/metaApiService'; +import { listenOnFetchablePort } from './helpers/app'; +import { capturingLogger } from './helpers/network'; + +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** Timers currently keeping the process alive. */ +const activeTimers = () => process.getActiveResourcesInfo().filter((name) => name === 'Timeout').length; + +function tasks() { + const log = capturingLogger(); + const reports: Array<{ error: unknown; report: ErrorReport }> = []; + const background = new BackgroundTasks({ logger: log.logger, reportError: (error, report) => reports.push({ error, report }) }); + return { background, log, reports }; +} + +// --------------------------------------------------------------------------------------------------------------------- +describe('BackgroundTasks', () => { + it('starts a task after the current code, not during the call to run()', async () => { + const { background } = tasks(); + const order: string[] = []; + background.run(async () => { + order.push('task'); + }); + order.push('after run()'); + await background.idle(1000); + expect(order).toEqual(['after run()', 'task']); + }); + + it('counts a task as pending until it finishes', async () => { + const { background } = tasks(); + let release: () => void = () => {}; + background.run(() => new Promise((resolve) => (release = resolve))); + expect(background.pending).toBe(1); + await wait(0); // the task starts one tick after run(), and only then can it be released + release(); + await background.idle(1000); + expect(background.pending).toBe(0); + }); + + it('catches a task that throws: logs it, reports it with the request id, and does not reject', async () => { + const { background, log, reports } = tasks(); + await runWithRequestId('req-77', async () => { + background.run(async () => { + throw new RangeError('boom'); + }); + }); + await background.idle(1000); + expect(reports).toHaveLength(1); + expect(reports[0]!.report).toEqual({ errorType: 'background_processing_failure', context: { request_id: 'req-77' } }); + expect(log.lines().some((line) => line.level === 'error' && line.message.includes('Unhandled error in background'))).toBe(true); + }); + + it('catches a task that throws before its first await', async () => { + const { background, reports } = tasks(); + background.run(() => { + throw new TypeError('synchronous'); + }); + await background.idle(1000); + expect(reports).toHaveLength(1); + }); + + it('gives the task the request id of the request that started it', async () => { + const { background, log } = tasks(); + await runWithRequestId('req-abc', async () => { + background.run(async () => { + await wait(5); + log.logger.info('written by the task'); + }); + }); + await background.idle(1000); + const line = log.lines().find((l) => l.message === 'written by the task') as unknown as { request_id: string }; + expect(line.request_id).toBe('req-abc'); + }); + + it('keeps tasks apart: one failing does not stop another', async () => { + const { background, reports } = tasks(); + let finished = false; + background.run(async () => { + throw new Error('first'); + }); + background.run(async () => { + await wait(10); + finished = true; + }); + await background.idle(1000); + expect(finished).toBe(true); + expect(reports).toHaveLength(1); + }); + + describe('idle()', () => { + it('is true at once when nothing is running', async () => { + expect(await tasks().background.idle(1000)).toBe(true); + }); + + it('is true when the tasks finish within the time', async () => { + const { background } = tasks(); + background.run(() => wait(20)); + expect(await background.idle(2000)).toBe(true); + }); + + it('is false when a task is still running at the limit, and leaves it running', async () => { + const { background } = tasks(); + let release: () => void = () => {}; + background.run(() => new Promise((resolve) => (release = resolve))); + expect(await background.idle(30)).toBe(false); + expect(background.pending).toBe(1); + release(); + expect(await background.idle(1000)).toBe(true); + }); + + it('does not leave its time limit running, which would keep the process alive', async () => { + const { background } = tasks(); + const before = activeTimers(); + background.run(() => wait(5)); + await background.idle(60_000); + expect(activeTimers()).toBe(before); + }); + + it('does not leave its time limit running when it gives up either', async () => { + const { background } = tasks(); + let release: () => void = () => {}; + background.run(() => new Promise((resolve) => (release = resolve))); + const before = activeTimers(); + await background.idle(20); + expect(activeTimers()).toBe(before); + release(); + await background.idle(1000); + }); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('gracefulShutdown', () => { + const servers: Server[] = []; + afterEach(async () => { + for (const server of servers.splice(0)) { + server.closeAllConnections(); + if (server.listening) await new Promise((resolve) => server.close(() => resolve())); + } + }); + + async function listening(handler?: Parameters[1]): Promise<{ server: Server; url: string }> { + const created = createServer(handler ?? ((_req, res) => res.end('ok'))); + const server = await listenOnFetchablePort(created); + servers.push(server); + const address = server.address(); + return { server, url: `http://127.0.0.1:${typeof address === 'object' && address ? address.port : 0}` }; + } + + it('stops accepting new connections', async () => { + const { server, url } = await listening(); + const { background, log } = tasks(); + await gracefulShutdown({ server, background, logger: log.logger, graceMs: 200 }); + await expect(fetch(url)).rejects.toThrow(); + }); + + it('waits for a running task before it finishes', async () => { + const { server } = await listening(); + const { background, log } = tasks(); + let done = false; + background.run(async () => { + await wait(60); + done = true; + }); + await gracefulShutdown({ server, background, logger: log.logger, graceMs: 2000 }); + expect(done).toBe(true); + expect(log.text()).toContain('Shutdown complete'); + }); + + it('gives up on a task that outlasts the grace period, and says so', async () => { + const { server } = await listening(); + const { background, log } = tasks(); + background.run(() => new Promise(() => {})); // never finishes + const started = Date.now(); + await gracefulShutdown({ server, background, logger: log.logger, graceMs: 50 }); + expect(Date.now() - started).toBeLessThan(2000); + expect(log.text()).toContain('Gave up on 1 task(s)'); + }); + + it('does not hang on an idle keep-alive connection', async () => { + const { server, url } = await listening(); + const { background, log } = tasks(); + await fetch(url, { headers: { Connection: 'keep-alive' } }); // leaves a connection open on the client side + await Promise.race([ + gracefulShutdown({ server, background, logger: log.logger, graceMs: 100 }), + wait(3000).then(() => { + throw new Error('shutdown hung on a keep-alive connection'); + }), + ]); + }); + + // Without this, an idle connection a browser or proxy keeps open would stay until the grace period ended + it('closes an idle keep-alive connection at once, without waiting for the running tasks', async () => { + const { server, url } = await listening(); + const { background, log } = tasks(); + const agent = new Agent({ keepAlive: true }); + try { + // The socket is only reachable while the request is open: once the response ends it is handed back to the agent + const socket = await new Promise((resolve) => { + const request = get(url, { agent }, (response) => response.resume()); + request.once('socket', (opened) => { + request.once('response', () => resolve(opened)); + }); + }); + await wait(20); // let the response finish, so the connection is idle and kept alive + const closed = new Promise((resolve) => socket.once('close', () => resolve())); + background.run(() => new Promise(() => {})); // a task that never ends keeps the grace period running + + const shutdown = gracefulShutdown({ server, background, logger: log.logger, graceMs: 600 }); + const outcome = await Promise.race([closed.then(() => 'closed'), wait(250).then(() => 'still open')]); + await shutdown; + + expect(outcome).toBe('closed'); + } finally { + agent.destroy(); + } + }); + + it('does not hang on a client that never finishes its request', async () => { + const { server, url } = await listening(() => { + /* never answers */ + }); + const { background, log } = tasks(); + const pending = fetch(url).catch(() => 'closed'); + await wait(30); + await Promise.race([ + gracefulShutdown({ server, background, logger: log.logger, graceMs: 50 }), + wait(3000).then(() => { + throw new Error('shutdown hung on an unanswered request'); + }), + ]); + expect(await pending).toBe('closed'); + }); + + it('flushes last, after the tasks', async () => { + const { server } = await listening(); + const { background, log } = tasks(); + const order: string[] = []; + background.run(async () => { + await wait(30); + order.push('task'); + }); + await gracefulShutdown({ + server, + background, + logger: log.logger, + graceMs: 2000, + flush: async () => { + order.push('flush'); + }, + }); + expect(order).toEqual(['task', 'flush']); + }); + + it('does not throw when the flush fails, and logs it', async () => { + const { server } = await listening(); + const { background, log } = tasks(); + await expect( + gracefulShutdown({ + server, + background, + logger: log.logger, + graceMs: 100, + flush: async () => { + throw new Error('sentry is down'); + }, + }), + ).resolves.toBeUndefined(); + expect(log.text()).toContain('Could not flush error reports'); + expect(log.text()).toContain('Shutdown complete'); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('Sentry', () => { + describe('scrubRequestEvent', () => { + it('keeps the method, the URL without its query string, and only the harmless headers', () => { + const event = scrubRequestEvent({ + request: { + method: 'GET', + url: 'https://whatsapp.example/whatsapp/v3?hub.verify_token=SECRETTOKEN&hub.challenge=c', + headers: { + Host: 'whatsapp.example', + 'User-Agent': 'facebookexternalua', + 'Content-Type': 'application/json', + 'X-Hub-Signature-256': 'sha256=SIGNATURE', + Authorization: 'Bearer BEARER', + Cookie: 'a=COOKIE', + }, + data: '{"text":"BODYTEXT"}', + query_string: 'hub.verify_token=SECRETTOKEN', + }, + }); + expect(Object.keys(event.request!).sort()).toEqual(['headers', 'method', 'url']); + expect(event.request!.url).toBe('https://whatsapp.example/whatsapp/v3'); + expect(Object.keys(event.request!.headers!).sort()).toEqual(['Content-Type', 'Host', 'User-Agent']); + const text = JSON.stringify(event); + for (const marker of ['SECRETTOKEN', 'SIGNATURE', 'BEARER', 'COOKIE', 'BODYTEXT']) expect(text).not.toContain(marker); + }); + + it('returns an event with no request untouched', () => { + const event = { message: 'hi' }; + expect(scrubRequestEvent(event)).toEqual({ message: 'hi' }); + }); + + it('copes with a request that has no headers or no URL', () => { + expect(scrubRequestEvent({ request: { method: 'POST' } }).request).toEqual({ method: 'POST', url: undefined, headers: {} }); + }); + + it('matches header names in any case', () => { + const event = scrubRequestEvent({ request: { headers: { host: 'h', HOST2: 'x', 'USER-AGENT': 'u', authorization: 'a' } } }); + expect(Object.keys(event.request!.headers!).sort()).toEqual(['USER-AGENT', 'host']); + }); + }); + + describe('the options', () => { + it('do not send personal data by default, keep no breadcrumbs, and scrub every event', () => { + expect(SENTRY_OPTIONS.sendDefaultPii).toBe(false); + expect(SENTRY_OPTIONS.maxBreadcrumbs).toBe(0); + expect(SENTRY_OPTIONS.beforeBreadcrumb()).toBeNull(); + expect(SENTRY_OPTIONS.beforeSend).toBe(scrubRequestEvent); + }); + }); + + describe('sentryReporter, through a real client with a spy transport', () => { + afterEach(async () => { + await Sentry.close(); + }); + + /** The parts of a Sentry event these tests read. */ + interface SentEvent { + tags: Record; + contexts?: { details?: Record }; + exception: { values: Array<{ value: string }> }; + } + + async function capture(run: () => void): Promise { + const envelopes: unknown[] = []; + Sentry.init({ + dsn: 'https://public@o0.ingest.sentry.io/0', + environment: 'test', + ...SENTRY_OPTIONS, + transport: () => ({ + send: async (envelope) => { + envelopes.push(envelope); + return {}; + }, + flush: async () => true, + }), + }); + run(); + await Sentry.flush(2000); + return envelopes + .flatMap((e) => (e as [unknown, Array<[{ type: string }, SentEvent]>])[1]) + .filter(([header]) => header.type === 'event') + .map(([, event]) => event); + } + + it('sends one event tagged with the error type and carrying the context', async () => { + const events = await capture(() => + sentryReporter(new Error('a failure'), { errorType: 'meta_api_failure', context: { request_id: 'req-1', status_code: 500 } }), + ); + expect(events).toHaveLength(1); + expect(events[0]!.tags).toMatchObject({ error_type: 'meta_api_failure' }); + expect(events[0]!.contexts?.details).toEqual({ request_id: 'req-1', status_code: 500 }); + expect(events[0]!.exception.values[0]!.value).toBe('a failure'); + }); + + it('does not let one event\'s tag leak onto the next', async () => { + const events = await capture(() => { + sentryReporter(new Error('one'), { errorType: 'first' }); + sentryReporter(new Error('two'), { errorType: 'second', context: { request_id: 'r' } }); + }); + expect(events.map((e) => e.tags.error_type).sort()).toEqual(['first', 'second']); + const first = events.find((e) => e.tags.error_type === 'first')!; + expect(first.contexts?.details).toBeUndefined(); + }); + + it('sends no-error values too (a thrown string or null) rather than failing', async () => { + const events = await capture(() => { + sentryReporter('just a string', { errorType: 'odd' }); + sentryReporter(null, { errorType: 'odd2' }); + }); + expect(events).toHaveLength(2); + }); + }); +}); + +// --------------------------------------------------------------------------------------------------------------------- +describe('createServices', () => { + const real: ServicesConfig = { + MOCK_ANSARI_CLIENT: false, + MOCK_AUTH_CLIENT: false, + MOCK_AUTH_TOKEN: undefined, + MOCK_META_API: false, + BACKEND_SERVER_URL: 'http://api.test', + AUTH_SERVER_URL: 'http://auth.test', + AUTH_WHATSAPP_API_KEY: new Secret('key'), + META_API_URL: 'https://graph.facebook.com/v26.0/1/messages', + META_ACCESS_TOKEN_FROM_SYS_USER: new Secret('token'), + DEPLOYMENT_TYPE: 'production', + }; + const log = () => capturingLogger().logger; + + it('uses the real client for each service when no mock flag is on', () => { + const services = createServices(real, log(), () => {}); + expect(services.ansariClient).toBeInstanceOf(AnsariClientReal); + expect(services.authClient).toBeInstanceOf(AuthClientReal); + expect(services.metaApi).toBeInstanceOf(MetaApiServiceReal); + }); + + it('uses the mock for exactly the services whose flag is on', () => { + const services = createServices( + { ...real, MOCK_ANSARI_CLIENT: true, MOCK_META_API: true, DEPLOYMENT_TYPE: 'local' }, + log(), + () => {}, + ); + expect(services.ansariClient).toBeInstanceOf(AnsariClientMock); + expect(services.authClient).toBeInstanceOf(AuthClientReal); + expect(services.metaApi).toBeInstanceOf(MetaApiServiceMock); + }); + + // Each real client takes the global `fetch` when it is built, so stubbing it first records where each one calls + it('points each real client at its own address', async () => { + const urls: string[] = []; + vi.stubGlobal('fetch', async (input: string | URL | Request) => { + urls.push(String(input instanceof Request ? input.url : input)); + return new Response('{}', { status: 200 }); + }); + try { + const services = createServices(real, log(), () => {}); + await services.authClient.getToken('US.1').catch(() => {}); + await services.ansariClient.getLastThreadInfo('t').catch(() => {}); + await services.metaApi.sendMessage('US.1', ['hi']).catch(() => {}); + } finally { + vi.unstubAllGlobals(); + } + expect(urls).toEqual([ + 'http://auth.test/api/whatsapp/session', + 'http://api.test/api/v2/threads', + 'https://graph.facebook.com/v26.0/1/messages', + ]); + }); + + it('gives the mock auth client the configured token, so every user shares one real account', async () => { + const { authClient } = createServices( + { ...real, MOCK_AUTH_CLIENT: true, MOCK_AUTH_TOKEN: new Secret('a.real.jwt'), DEPLOYMENT_TYPE: 'local' }, + log(), + () => {}, + ); + expect(authClient).toBeInstanceOf(AuthClientMock); + expect(await authClient.getToken('US.1')).toBe('a.real.jwt'); + expect(await authClient.getToken('US.2')).toBe('a.real.jwt'); + }); + + it('gives each user a token of their own when no mock token is configured', async () => { + const { authClient } = createServices({ ...real, MOCK_AUTH_CLIENT: true, DEPLOYMENT_TYPE: 'local' }, log(), () => {}); + expect(await authClient.getToken('US.1')).not.toBe(await authClient.getToken('US.2')); + }); +}); diff --git a/apps/whatsapp/tests/helpers/app.ts b/apps/whatsapp/tests/helpers/app.ts new file mode 100644 index 00000000..2e145bf0 --- /dev/null +++ b/apps/whatsapp/tests/helpers/app.ts @@ -0,0 +1,188 @@ +/** + * Test helper for the HTTP layer: the real app, listening on a free port, with the in-memory clients behind it. + * + * Python counterpart: FastAPI's `TestClient(app)`. Express has no built-in test client, so the app really listens (on port 0, + * which the operating system turns into any free port) and a test calls it with `fetch`, exactly as Meta would over a network. + * Nothing leaves the machine. + */ +import { createHmac } from 'node:crypto'; +import type { Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { buildApp } from '../../src/app'; +import { BackgroundTasks } from '../../src/background'; +import { buildConfig, type Env } from '../../src/config'; +import { ConversationManager } from '../../src/conversationManager'; +import type { ErrorReport } from '../../src/errorReporter'; +import type { AnsariClient } from '../../src/services/ansariClient'; +import { AnsariClientMock } from '../../src/services/ansariClient'; +import { AuthClientMock, type AuthClient } from '../../src/services/authClient'; +import { MetaApiServiceMock, type MetaApiService } from '../../src/services/metaApiService'; +import { FIXED_NOW_UNIX } from '../fixtures/pythonOracle'; +import { capturingLogger } from './network'; + +/** + * Ports `fetch` refuses to call (the Fetch standard's "bad ports", at 1024 and above; the rest are below any port the system hands + * out). Port 0 lets the system choose, and on a machine whose automatic range includes one of these, a test would fail now and then + * with `bad port` for no reason connected to the code. + * https://fetch.spec.whatwg.org/#port-blocking + */ +const FETCH_BAD_PORTS = new Set([1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669, 6679, 6697, 10080]); + +/** Listen on 127.0.0.1 on a port chosen by the system, asking again whenever it picks one `fetch` will not call. */ +export async function listenOnFetchablePort(app: { listen: (port: number, host: string, cb: () => void) => Server }): Promise { + for (;;) { + const server: Server = await new Promise((resolve) => { + const listening = app.listen(0, '127.0.0.1', () => resolve(listening)); + }); + const port = (server.address() as AddressInfo).port; + if (!FETCH_BAD_PORTS.has(port)) return server; + await new Promise((resolve) => server.close(() => resolve())); + } +} + +export const APP_SECRET = 'test-app-secret'; +export const VERIFY_TOKEN = 'test-verify-token'; +export const PHONE_NUMBER_ID = '123456789'; +export const BSUID = 'US.13491208655302741918'; +export const PHONE = '201234567899'; +export const NOW = new Date(FIXED_NOW_UNIX * 1000); + +/** The smallest valid environment, with the mocks on (as in CI) and `ALWAYS_RETURN_OK_TO_META` off so statuses are real. */ +export function testEnv(overrides: Record = {}): Env { + return buildConfig({ + DEPLOYMENT_TYPE: 'local', + AUTH_WHATSAPP_API_KEY: 'test-key', + META_BUSINESS_PHONE_NUMBER_ID: PHONE_NUMBER_ID, + META_ACCESS_TOKEN_FROM_SYS_USER: 'test-token', + META_WEBHOOK_VERIFY_TOKEN: VERIFY_TOKEN, + META_ANSARI_APP_SECRET: APP_SECRET, + ALWAYS_RETURN_OK_TO_META: 'false', + ORIGINS: 'https://allowed.example', + ...overrides, + }); +} + +/** What Meta sends for one text message from `from_user_id` to our number. */ +export function webhookPayload( + message: Record = {}, + options: { phoneNumberId?: string; contacts?: unknown[] } = {}, +): Record { + const value: Record = { + metadata: { phone_number_id: options.phoneNumberId ?? PHONE_NUMBER_ID, display_phone_number: '+1234567890' }, + messages: [ + { + from_user_id: BSUID, + id: 'wamid.TEST', + timestamp: String(FIXED_NOW_UNIX), + type: 'text', + text: { body: 'hello' }, + ...message, + }, + ], + }; + if (options.contacts) value.contacts = options.contacts; + return { object: 'whatsapp_business_account', entry: [{ changes: [{ value }] }] }; +} + +/** The message object inside a payload built by `webhookPayload`, so a test can remove or add a key. */ +export function messageOf(payload: Record): Record { + const entry = (payload.entry as Array<{ changes: Array<{ value: { messages: Array> } }> }>)[0]!; + return entry.changes[0]!.value.messages[0]!; +} + +/** `sha256=`, the value Meta puts in `X-Hub-Signature-256`. */ +export function sign(body: string | Buffer, secret = APP_SECRET): string { + return `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`; +} + +export interface TestApp { + url: string; + env: Env; + background: BackgroundTasks; + log: ReturnType; + /** Error reports sent to the operator. */ + reports: Array<{ error: unknown; report: ErrorReport }>; + /** Every message part sent to a user, flattened, in order. */ + replies: () => string[]; + /** Who each send was addressed to. */ + recipients: () => string[]; + /** Wait for the work started after Meta was answered. Fails the test if it does not finish. */ + settle: () => Promise; + /** POST a body to the webhook, signed unless told otherwise. */ + post: (body: unknown, options?: PostOptions) => Promise<{ status: number; json: Record; headers: Headers; text: string }>; + close: () => Promise; +} + +export interface PostOptions { + /** Sign with this secret. `false` sends no signature at all. */ + secret?: string | false; + /** Replace the signature header outright. */ + signature?: string; + /** The body as bytes or text, instead of the JSON of `body`. */ + raw?: string | Buffer; + contentType?: string | null; + headers?: Record; +} + +export async function startApp( + options: { + env?: Record; + ansariClient?: AnsariClient; + authClient?: AuthClient; + metaApi?: MetaApiService; + } = {}, +): Promise { + const env = testEnv(options.env); + const log = capturingLogger(); + const reports: TestApp['reports'] = []; + const reportError = (error: unknown, report: ErrorReport) => reports.push({ error, report }); + + const metaMock = new MetaApiServiceMock({ logger: log.logger, delayMs: 0 }); + const background = new BackgroundTasks({ logger: log.logger, reportError }); + const manager = new ConversationManager({ + config: env, + ansariClient: options.ansariClient ?? new AnsariClientMock({ logger: log.logger, now: () => NOW }), + authClient: options.authClient ?? new AuthClientMock(), + metaApi: options.metaApi ?? metaMock, + logger: log.logger, + reportError, + now: () => NOW, + }); + const app = buildApp({ config: env, manager, background, logger: log.logger, reportError }); + + const server = await listenOnFetchablePort(app); + const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + + return { + url, + env, + background, + log, + reports, + replies: () => metaMock.sent.flatMap((call) => call.messageParts), + recipients: () => metaMock.sent.map((call) => call.recipient), + async settle() { + if (!(await background.idle(5_000))) throw new Error('background work did not finish within 5 s'); + }, + async post(body, postOptions = {}) { + const raw = postOptions.raw ?? JSON.stringify(body); + const headers: Record = { ...postOptions.headers }; + if (postOptions.contentType !== null) headers['Content-Type'] = postOptions.contentType ?? 'application/json'; + if (postOptions.signature !== undefined) headers['X-Hub-Signature-256'] = postOptions.signature; + else if (postOptions.secret !== false) headers['X-Hub-Signature-256'] = sign(raw, postOptions.secret ?? APP_SECRET); + const response = await fetch(`${url}/whatsapp/v3`, { method: 'POST', headers, body: raw }); + const text = await response.text(); + let json: Record = {}; + try { + json = JSON.parse(text) as Record; + } catch { + // not JSON: the caller reads `text` + } + return { status: response.status, json, headers: response.headers, text }; + }, + async close() { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }, + }; +} diff --git a/apps/whatsapp/tests/listenHelper.test.ts b/apps/whatsapp/tests/listenHelper.test.ts new file mode 100644 index 00000000..9b55d6ad --- /dev/null +++ b/apps/whatsapp/tests/listenHelper.test.ts @@ -0,0 +1,51 @@ +/** + * The test helper that avoids the ports `fetch` refuses. Without it the app tests failed now and then with `bad port`, which + * looks like a fault in the service but is the test machine picking port 6000 or similar. + */ +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { afterEach, expect, it } from 'vitest'; +import { listenOnFetchablePort } from './helpers/app'; + +const open: Server[] = []; +afterEach(async () => { + for (const server of open.splice(0)) { + if (server.listening) await new Promise((resolve) => server.close(() => resolve())); + } +}); + +it('closes a server on a port fetch refuses and asks again, until it gets a port fetch will call', async () => { + // A stand-in for the system's choice of port: the first two servers claim to be on bad ports (the sockets really are on free ones) + const claimed = [6000, 6667]; + const created: Server[] = []; + const app = { + listen: (_port: number, host: string, cb: () => void): Server => { + const server = createServer((_req, res) => res.end('ok')); + created.push(server); + const bad = claimed.shift(); + const listening = server.listen(0, host, cb); + if (bad !== undefined) { + const realAddress = listening.address.bind(listening); + listening.address = () => ({ ...(realAddress() as AddressInfo), port: bad }); + } + return listening; + }, + }; + + const server = await listenOnFetchablePort(app); + open.push(...created); + + expect(created).toHaveLength(3); + expect(server).toBe(created[2]); + expect(created[0]!.listening).toBe(false); + expect(created[1]!.listening).toBe(false); + expect(server.listening).toBe(true); +}); + +it('returns the first server when its port is fine', async () => { + const real = createServer((_req, res) => res.end('ok')); + const server = await listenOnFetchablePort(real); + open.push(server); + expect(server).toBe(real); + expect((await fetch(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`)).status).toBe(200); +}); diff --git a/apps/whatsapp/tests/signatureTiming.test.ts b/apps/whatsapp/tests/signatureTiming.test.ts new file mode 100644 index 00000000..2f438a96 --- /dev/null +++ b/apps/whatsapp/tests/signatureTiming.test.ts @@ -0,0 +1,50 @@ +/** + * The signature and token comparisons must go through `crypto.timingSafeEqual`. + * + * Its own file because it wraps `node:crypto` for the whole file (`vi.mock`). The behaviour of `===` and `timingSafeEqual` is the + * same on every input, so no result can tell them apart: only whether the safe function is called can. A comparison that stops at + * the first differing character lets an attacker guess a signature one character at a time by timing the answers. + */ +import { createHmac } from 'node:crypto'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { Secret } from '../src/config'; +import { constantTimeEquals, isValidSignature } from '../src/webhook/signature'; + +const spy = vi.hoisted(() => ({ calls: 0 })); + +vi.mock('node:crypto', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + timingSafeEqual: (a: Parameters[0], b: Parameters[1]) => { + spy.calls += 1; + return actual.timingSafeEqual(a, b); + }, + }; +}); + +beforeEach(() => { + spy.calls = 0; +}); + +describe('constant-time comparison', () => { + it('compares equal text with timingSafeEqual', () => { + expect(constantTimeEquals('abc', 'abc')).toBe(true); + expect(spy.calls).toBe(1); + }); + + it('compares different text of the same length with timingSafeEqual too, not an early exit', () => { + expect(constantTimeEquals('abc', 'abd')).toBe(false); + expect(spy.calls).toBe(1); + }); + + it('checks a webhook signature with it, whether the signature is right or wrong', () => { + const secret = new Secret('app-secret'); + const body = Buffer.from('{"a":1}'); + const good = createHmac('sha256', 'app-secret').update(body).digest('hex'); + + expect(isValidSignature(body, `sha256=${good}`, secret)).toBe(true); + expect(isValidSignature(body, `sha256=${'0'.repeat(64)}`, secret)).toBe(false); + expect(spy.calls).toBe(2); + }); +}); diff --git a/apps/whatsapp/tests/webhookHelpers.test.ts b/apps/whatsapp/tests/webhookHelpers.test.ts new file mode 100644 index 00000000..2b93793a --- /dev/null +++ b/apps/whatsapp/tests/webhookHelpers.test.ts @@ -0,0 +1,170 @@ +/** + * The small pure pieces of the webhook path: the signature check, the token comparison and Meta's reply body. + * + * Python counterparts: `verify_meta_signature` and `create_response_for_meta` (which had no direct tests; the signature was only + * tried through the route). The expected digests come from Python's own `hmac`, run once (see the comment on `KNOWN`). + */ +import { createHmac } from 'node:crypto'; +import { describe, expect, it } from 'vitest'; +import { Secret } from '../src/config'; +import { createResponseForMeta } from '../src/webhook/metaResponse'; +import { constantTimeEquals, isValidSignature } from '../src/webhook/signature'; + +const SECRET = new Secret('app-secret'); + +/** Independent of the code under test: Node's own `createHmac`. */ +function hmacHex(body: string | Buffer, key = 'app-secret'): string { + return createHmac('sha256', key).update(body).digest('hex'); +} + +/** + * What Python's `hmac.new(b"app-secret", body, hashlib.sha256).hexdigest()` returned for each body, run on the legacy service's + * interpreter. The TypeScript check is held against the real implementation, not only against Node's. + */ +const PYTHON_DIGESTS: Array<[name: string, body: Buffer, hex: string]> = [ + ['JSON', Buffer.from('{"a":1}'), 'a2ac6607a24977f9757e6d78319ae1660ad42ffeee0ee3f0dff30a92bcf85448'], + ['an empty body', Buffer.alloc(0), 'f685db4c946698bf105ff5b62e30bc1f78216f3914b12bb750f8992aa6748824'], + [ + 'Arabic and an emoji', + Buffer.from('\u0645\u0631\u062d\u0628\u0627 \u{1F600}', 'utf8'), + '2b5ebaae1080aa1f923b4f58e6a066ef9d95c0f652598dcb8883f715ccce7298', + ], + ['5000 bytes', Buffer.from('x'.repeat(5000)), '85980d1bf475e247d436b8a48f404e96fd761a5f4a1b315e8bac54f81b4068c9'], +]; + +describe('isValidSignature', () => { + const body = Buffer.from('{"a":1}'); + + it.each(PYTHON_DIGESTS)('accepts the digest Python computed for %s', (_name, bytes, hex) => { + expect(hmacHex(bytes)).toBe(hex); + expect(isValidSignature(bytes, `sha256=${hex}`, SECRET)).toBe(true); + }); + + it('accepts the right signature', () => { + expect(isValidSignature(body, `sha256=${hmacHex(body)}`, SECRET)).toBe(true); + }); + + it('accepts an empty body signed correctly', () => { + expect(isValidSignature(Buffer.alloc(0), `sha256=${hmacHex('')}`, SECRET)).toBe(true); + }); + + it('refuses a missing header', () => { + expect(isValidSignature(body, undefined, SECRET)).toBe(false); + }); + + // The check cuts off the first seven characters and compares the rest, so a valid digest behind seven characters of anything + // else would pass if the prefix itself were not checked + it.each(['sha256:', 'sha1===', 'xxxxxxx', 'SHA256=', ' sha256', '\u0000\u0000\u0000\u0000\u0000\u0000\u0000'])( + 'refuses a valid digest behind the wrong seven-character prefix %j', + (prefix) => { + expect(isValidSignature(body, `${prefix}${hmacHex(body)}`, SECRET)).toBe(false); + }, + ); + + it.each(['', 'sha256', 'sha256:abc', 'SHA256=abc', 'sha1=abc', ' sha256=abc'])('refuses the prefix in %j', (header) => { + expect(isValidSignature(body, header, SECRET)).toBe(false); + }); + + it('refuses a digest of the wrong length without throwing (timingSafeEqual throws on unequal lengths)', () => { + const good = hmacHex(body); + for (const header of [`sha256=${good.slice(0, -1)}`, `sha256=${good}0`, 'sha256=', `sha256=${'a'.repeat(1000)}`]) { + expect(isValidSignature(body, header, SECRET)).toBe(false); + } + }); + + it('refuses the right digest in upper case', () => { + expect(isValidSignature(body, `sha256=${hmacHex(body).toUpperCase()}`, SECRET)).toBe(false); + }); + + it('refuses a digest that differs in only the last character, and in only the first', () => { + const good = hmacHex(body); + const flip = (c: string) => (c === '0' ? '1' : '0'); + expect(isValidSignature(body, `sha256=${good.slice(0, -1)}${flip(good.at(-1)!)}`, SECRET)).toBe(false); + expect(isValidSignature(body, `sha256=${flip(good[0]!)}${good.slice(1)}`, SECRET)).toBe(false); + }); + + it('refuses a signature under another secret', () => { + expect(isValidSignature(body, `sha256=${hmacHex(body, 'other')}`, SECRET)).toBe(false); + }); + + it('refuses a signature of a different body', () => { + expect(isValidSignature(body, `sha256=${hmacHex('{"a":2}')}`, SECRET)).toBe(false); + }); + + it('refuses a digest with non-ASCII characters without throwing', () => { + expect(isValidSignature(body, `sha256=${'\u00e9'.repeat(32)}`, SECRET)).toBe(false); + }); + + it('is not fooled by two characters that are different bytes but the same length as characters', () => { + // 64 characters, but more than 64 bytes: the length check must compare bytes, or timingSafeEqual would throw + expect(isValidSignature(body, `sha256=${'\u00e9'.repeat(64)}`, SECRET)).toBe(false); + }); +}); + +describe('constantTimeEquals', () => { + it('is true for equal text and false for different text', () => { + expect(constantTimeEquals('abc', 'abc')).toBe(true); + expect(constantTimeEquals('abc', 'abd')).toBe(false); + expect(constantTimeEquals('abc', 'ab')).toBe(false); + expect(constantTimeEquals('', '')).toBe(true); + expect(constantTimeEquals('', 'a')).toBe(false); + }); + + it('copes with non-ASCII text on either side, comparing UTF-8 bytes', () => { + expect(constantTimeEquals('t\u00e9st', 't\u00e9st')).toBe(true); + expect(constantTimeEquals('t\u00e9st', 'test')).toBe(false); + expect(constantTimeEquals('test', 't\u00e9st')).toBe(false); + expect(constantTimeEquals('\u{1F600}', '\u{1F600}')).toBe(true); + }); + + it('does not equate two strings that are the same length in characters but not in bytes', () => { + expect(constantTimeEquals('ab', '\u00e9')).toBe(false); + }); +}); + +describe('createResponseForMeta', () => { + const NOW = 1_794_312_000; + + it('is a 200 success with the three base keys by default', () => { + expect(createResponseForMeta({}, true, NOW)).toEqual({ status: 200, body: { success: true, message: 'OK', timestamp: NOW } }); + }); + + it('puts the error code and details under error_code and detail', () => { + const { body } = createResponseForMeta({ success: false, errorCode: 'X', details: { error: 'why' } }, true, NOW); + expect(body).toEqual({ success: false, message: 'OK', timestamp: NOW, error_code: 'X', detail: { error: 'why' } }); + }); + + it('leaves out an empty error code and empty details, as Python did', () => { + const { body } = createResponseForMeta({ errorCode: '', details: {} }, true, NOW); + expect(Object.keys(body).sort()).toEqual(['message', 'success', 'timestamp']); + }); + + describe('the status', () => { + it('is always 200 when ALWAYS_RETURN_OK_TO_META is on, whatever the failure', () => { + for (const statusCode of [202, 400, 415, 422, 503]) { + expect(createResponseForMeta({ success: false, statusCode }, true, NOW).status).toBe(200); + } + }); + + it('is the real status for a failure when the flag is off', () => { + for (const statusCode of [202, 400, 415, 422, 503]) { + expect(createResponseForMeta({ success: false, statusCode }, false, NOW).status).toBe(statusCode); + } + }); + + it('is 200 for a success when the flag is off, whatever status was passed', () => { + expect(createResponseForMeta({ success: true, statusCode: 503 }, false, NOW).status).toBe(200); + }); + + it('defaults a failure to 200 when no status is given', () => { + expect(createResponseForMeta({ success: false }, false, NOW).status).toBe(200); + }); + }); + + it('stamps the current time when none is passed', () => { + const before = Math.floor(Date.now() / 1000); + const { body } = createResponseForMeta({}, true); + expect(body.timestamp).toBeGreaterThanOrEqual(before); + expect(body.timestamp).toBeLessThanOrEqual(before + 2); + }); +}); diff --git a/codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt b/codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt new file mode 100644 index 00000000..d90ffd7b --- /dev/null +++ b/codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt @@ -0,0 +1,48 @@ +NOTE: This is an agent self-review written by the implementing agent. It is NOT the output of a `consult` run; no external model was consulted (owner instruction: "don't consult; just self review"). + +Phase 5 (HTTP app): src/app.ts, src/index.ts, src/server.ts, src/background.ts, src/sentry.ts, src/services/createServices.ts, src/webhook/signature.ts, src/webhook/metaResponse.ts; dependencies express, cors, @sentry/node (+ @types) added with the same specifiers as apps/auth. + +VERIFIED (by running it) +- `pnpm --filter ansari-whatsapp typecheck` exit 0, `lint` exit 0, `build` exit 0 (tsdown, dist/index.mjs 111 kB), `test` exit 0: 880 tests in 22 files (708 in 16 files before this phase). Three further full runs after the last edit were stable. +- A real end-to-end check on the BUILT file (node dist/index.mjs on port 3299, mock clients): health 200, handshake right token echoes the challenge, wrong token 403, no parameters 400, old /whatsapp/v2 404, /sentry-debug 500 in local, a signed webhook 200 with an X-Request-ID, an unsigned one 403, and the log showed the typing indicator and the message being handled after the reply. +- Mutation controls, one rule broken at a time, whole suite run, file restored and compared to the original: + - Run 1: 73 mutations ran (2 skipped because they changed nothing). 63 caught, 8 not caught, 0 restore mismatches (the count is from the results file; a first count of "7" was mid-run). + - The 8 not caught were looked at one by one. Five were real gaps and got tests: a signature header with a wrong 7-character prefix (the check cuts the prefix off blindly), a plain `===` token comparison (needed a test that proves `timingSafeEqual` is called: tests/signatureTiming.test.ts mocks `node:crypto`), JSON with one non-UTF-8 byte (Python's json.loads raises, checked on the legacy interpreter; the lenient decoder accepted it), a non-parser error being shown to the caller (a parser bug is simulated in tests/appParserFault.test.ts), and a CORS refusal not being logged at error level (the old test matched the text at any level). Two were wrong URLs in createServices (auth and apps/api, now tested by recording where each real client calls). One more (an idle keep-alive connection) and one (request id lost in the background) are the equivalent mutants below. + - Run 2: 14 mutations covering those gaps, plus two for the new test helper. 12 caught, 2 not caught (the two equivalent mutants), 0 restore mismatches. + - Equivalent mutants (a change that cannot alter behaviour): `server.close()` already closes idle keep-alive connections on Node 22 (probed: closed in 1 ms with no extra call), so the explicit `closeIdleConnections()` was redundant and is removed; AsyncLocalStorage context already follows every promise, setImmediate, setTimeout and queueMicrotask hop (probed), so the `runWithRequestId` wrapper in background.ts was redundant and is removed. The tests for both behaviours stay and pass. +- A flaky test found and fixed: 2 of 878 failed once with `fetch failed: bad port`. `fetch` refuses certain ports (6000, 6667, ...) and port 0 can return one on this machine. tests/helpers/app.ts now asks again until it gets a port fetch will call (tests/listenHelper.test.ts proves the loop). Before the fix the run could not be repeated; it passed 6 of 6 and then 5 of 5 afterwards, which is evidence but not proof (the failure was random). +- Python's real answers where they mattered: HMAC digests for four bodies (JSON, empty, Arabic plus an emoji, 5000 bytes) computed by Python's `hmac`; the invalid-UTF-8 behaviour of `json.loads`. + +PORTED FROM PYTHON +- `main.py`: the three routes (now /whatsapp/v3), request-id middleware with an X-Request-ID header, CORS from ORIGINS with a log line for a refused origin, the Sentry init, /sentry-debug outside production, localhost vs 0.0.0.0 by DEPLOYMENT_TYPE, every status and error_code of the webhook route (MAINTENANCE_MODE 503, DEV_FILTER 202, MESSAGE_TOO_OLD 422, UNSUPPORTED_MESSAGE_TYPE 415, STATUS_MESSAGE, UNEXPECTED_PAYLOAD_FORMAT 400 with a notice to whoever can be reached, INVALID_PAYLOAD 400). +- `whatsapp_webhook_utils.py`: the signature check (403 with WWW-Authenticate) and `create_response_for_meta` (always 200 unless ALWAYS_RETURN_OK_TO_META is off). +- The Python tests listed in the test file header, driven through a real listening server with `fetch` instead of `TestClient`. + +DIFFERENCES FROM PYTHON (deliberate) +- The routes are /whatsapp/v3 (owner decision; Meta's callback URL must be changed at cutover, a phase 7 step). +- Raw bytes are read first and parsed by hand AFTER the signature check, so an unsigned caller learns nothing about the body. FastAPI checked the signature in a dependency before parsing; `express.json()` would parse first. +- Invalid UTF-8 is refused with a 400 (INVALID_PAYLOAD), as Python's json.loads does. +- The JSON parser's own error text is never returned or logged (it quotes the start of the body, i.e. the user's message). Python returned `str(e)`. The answer says only "Webhook body is not valid JSON". +- Any non-parser error in the read step is answered with a fixed text; Python returned `str(e)`. +- Body limit 1 MB (413). Python had none. +- Express has no 405: a wrong method on a known path is a 404. +- A preflight from a disallowed origin gets no CORS headers (Python's Starlette answered 400). Meta's servers send no Origin header. +- The caller's own X-Request-ID is ignored (it is untrusted text going into the logs). +- Sentry: Python sampled traces and profiles (20% in production) and filtered log events containing "HTTP exception: 401/403". Neither is ported: a trace records the request URL (the handshake URL holds the verify token), and nothing here sends log lines to Sentry. Events are scrubbed as in apps/auth (method, URL without query string, three harmless headers) and carry no breadcrumbs. +- Graceful shutdown on SIGTERM/SIGINT (stop accepting, wait up to 8 s for background work, flush Sentry) is new: uvicorn did this implicitly in Python. +- Background work runs in `BackgroundTasks`, the one place that catches, logs and reports (`background_processing_failure`); a failure there never becomes an unhandled rejection (tested). +- Python's `get_*` singletons and `reset_*` functions are gone; `createServices` chooses real or mock once at start-up. + +KNOWN LIMITS +- tests/app.test.ts is 96 tests in one file against the real app on a real port; it takes about 1 s but depends on the machine allowing 127.0.0.1 listeners. +- 8 s of grace on shutdown is a guess at Railway's limit (documented as about that), not measured. +- `index.ts` itself (the wiring, signal handlers and the unhandledRejection hook) is not unit tested: only run by hand against the built file. Its pieces (createServices, gracefulShutdown, BackgroundTasks, sentryReporter) are. +- The `unhandledRejection` hook logs and reports but does not exit; I chose that so one bug cannot take the whole service down, but it also hides a corrupt state. Open for the owner's view. +- The lockfile gained 15 lines for this app only (0 removed). + +NOT VERIFIED +- No real Meta, apps/auth or apps/api call; no real Sentry event was sent (a spy transport only). +- The Docker image and Railway behaviour (phase 6 and 7). +- Behaviour under Meta's real redelivery timing. + +VERDICT: COMMENT diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0d6a2997..33b877b4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -451,9 +451,18 @@ importers: apps/whatsapp: dependencies: + '@sentry/node': + specifier: ^10.69.0 + version: 10.69.0(@opentelemetry/core@2.10.0(@opentelemetry/api@1.9.1)) + cors: + specifier: ^2.8.5 + version: 2.8.6 dotenv: specifier: ^17.2.3 version: 17.4.2 + express: + specifier: ^5.1.0 + version: 5.2.1 zod: specifier: ^4.3.5 version: 4.6.7 @@ -464,6 +473,12 @@ importers: '@ansari/tsconfig': specifier: workspace:* version: link:../../packages/tsconfig + '@types/cors': + specifier: ^2.8.17 + version: 2.8.19 + '@types/express': + specifier: ^5.0.0 + version: 5.0.6 '@types/node': specifier: ^25.0.10 version: 25.9.8 From 405651a0d058f196561767454abf6c47957f4b8f Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 05:55:59 +0200 Subject: [PATCH 063/435] chore(porch): 358 implement build-complete --- codev/projects/358-whatsapp-typescript/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 82366752..4151a64d 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-11T03:07:41.502Z' +updated_at: '2026-11-11T03:55:59.327Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' From 5ec064aed0aa409bf377c273d68475041f4536dd Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 05:56:18 +0200 Subject: [PATCH 064/435] =?UTF-8?q?chore(porch):=20358=20advance=20plan=20?= =?UTF-8?q?phase=20=E2=86=92=20phase=5F6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codev/projects/358-whatsapp-typescript/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 4151a64d..bdd1c1e7 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -17,14 +17,14 @@ plan_phases: status: complete - id: phase_5 title: 'HTTP app: webhook verification, signature check, immediate 200' - status: in_progress + status: complete - id: phase_6 title: Docker, Railway config, CI, turbo and documentation - status: pending + status: in_progress - id: phase_7 title: Staging redeploy, smoke test and legacy rollback note status: pending -current_plan_phase: phase_5 +current_plan_phase: phase_6 gates: spec-approval: status: approved @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-11T03:55:59.327Z' +updated_at: '2026-11-11T03:56:18.758Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -60,3 +60,5 @@ context_refreshes: - boundary: plan-phase:phase_5 at: '2026-11-10T20:48:04.354Z' acknowledged_at: '2026-11-11T03:07:41.500Z' + - boundary: plan-phase:phase_6 + at: '2026-11-11T03:56:18.757Z' From 950a2d2b34ddd15bbf65dabfadfbf71302d007ca Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 05:56:49 +0200 Subject: [PATCH 065/435] [Spec 358][Phase: phase_5] docs: correct mutation counts in the phase 5 self-review --- .../358-whatsapp-typescript/358-phase_5-iter1-claude.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt b/codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt index d90ffd7b..083182cd 100644 --- a/codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt +++ b/codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt @@ -6,9 +6,9 @@ VERIFIED (by running it) - `pnpm --filter ansari-whatsapp typecheck` exit 0, `lint` exit 0, `build` exit 0 (tsdown, dist/index.mjs 111 kB), `test` exit 0: 880 tests in 22 files (708 in 16 files before this phase). Three further full runs after the last edit were stable. - A real end-to-end check on the BUILT file (node dist/index.mjs on port 3299, mock clients): health 200, handshake right token echoes the challenge, wrong token 403, no parameters 400, old /whatsapp/v2 404, /sentry-debug 500 in local, a signed webhook 200 with an X-Request-ID, an unsigned one 403, and the log showed the typing indicator and the message being handled after the reply. - Mutation controls, one rule broken at a time, whole suite run, file restored and compared to the original: - - Run 1: 73 mutations ran (2 skipped because they changed nothing). 63 caught, 8 not caught, 0 restore mismatches (the count is from the results file; a first count of "7" was mid-run). - - The 8 not caught were looked at one by one. Five were real gaps and got tests: a signature header with a wrong 7-character prefix (the check cuts the prefix off blindly), a plain `===` token comparison (needed a test that proves `timingSafeEqual` is called: tests/signatureTiming.test.ts mocks `node:crypto`), JSON with one non-UTF-8 byte (Python's json.loads raises, checked on the legacy interpreter; the lenient decoder accepted it), a non-parser error being shown to the caller (a parser bug is simulated in tests/appParserFault.test.ts), and a CORS refusal not being logged at error level (the old test matched the text at any level). Two were wrong URLs in createServices (auth and apps/api, now tested by recording where each real client calls). One more (an idle keep-alive connection) and one (request id lost in the background) are the equivalent mutants below. - - Run 2: 14 mutations covering those gaps, plus two for the new test helper. 12 caught, 2 not caught (the two equivalent mutants), 0 restore mismatches. + - Run 1: 73 entries in the script: 71 ran (63 caught, 8 not caught) and 2 were skipped because the change was a no-op (my script bug, not a result). 0 restore mismatches. Counts are from the results file; an earlier mid-run count of "7 not caught" was premature. + - The 8 not caught were looked at one by one. Five were real gaps and got tests: a signature header with a wrong 7-character prefix (the check cuts the prefix off blindly), a plain `===` token comparison (needed a test that proves `timingSafeEqual` is called: tests/signatureTiming.test.ts mocks `node:crypto`), JSON with one non-UTF-8 byte (Python's json.loads raises, checked on the legacy interpreter; the lenient decoder accepted it), a non-parser error being shown to the caller (a parser bug is simulated in tests/appParserFault.test.ts), and a CORS refusal not being logged at error level (the old test matched the text at any level). One was a wrong URL in createServices (the auth client pointed at apps/api's address); I then also tested the apps/api and Meta URLs, which were not among the 8, by recording where each real client calls. The last two (an idle keep-alive connection, and the request id lost in the background) are the equivalent mutants below. + - Run 2: 14 mutations (the 8 gaps, the two extra URL checks, a parser-bug-not-reported check, and two for the new test helper). 12 caught, 2 not caught (the two equivalent mutants), 0 restore mismatches. - Equivalent mutants (a change that cannot alter behaviour): `server.close()` already closes idle keep-alive connections on Node 22 (probed: closed in 1 ms with no extra call), so the explicit `closeIdleConnections()` was redundant and is removed; AsyncLocalStorage context already follows every promise, setImmediate, setTimeout and queueMicrotask hop (probed), so the `runWithRequestId` wrapper in background.ts was redundant and is removed. The tests for both behaviours stay and pass. - A flaky test found and fixed: 2 of 878 failed once with `fetch failed: bad port`. `fetch` refuses certain ports (6000, 6667, ...) and port 0 can return one on this machine. tests/helpers/app.ts now asks again until it gets a port fetch will call (tests/listenHelper.test.ts proves the loop). Before the fix the run could not be repeated; it passed 6 of 6 and then 5 of 5 afterwards, which is evidence but not proof (the failure was random). - Python's real answers where they mattered: HMAC digests for four bodies (JSON, empty, Arabic plus an emoji, 5000 bytes) computed by Python's `hmac`; the invalid-UTF-8 behaviour of `json.loads`. From 8c4c6034fb16703063298b0566dc11c52e84c3c5 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 15:32:17 +1100 Subject: [PATCH 066/435] Fix #369: move apps/mcp Ansari attribution fixtures to askansari.ai --- apps/mcp/test/browser.ts | 10 +++++----- apps/mcp/test/react-answers.ts | 5 +++-- codev/state/bugfix-369_thread.md | 19 +++++++++++++++++++ 3 files changed, 27 insertions(+), 7 deletions(-) create mode 100644 codev/state/bugfix-369_thread.md diff --git a/apps/mcp/test/browser.ts b/apps/mcp/test/browser.ts index 77f0a379..0fd672fc 100644 --- a/apps/mcp/test/browser.ts +++ b/apps/mcp/test/browser.ts @@ -238,7 +238,7 @@ async function main() { check('answer-A:question-and-text-in-order', () => { assert.equal(shownA.question, QUESTION_A); assert.equal(shownA.status, ''); - const order = ['Synthetic heading A', 'Synthetic answer A. التقوى', 'Third', 'Fourth point', 'nested one', 'nested two', 'a bullet', 'a quoted line', 'This information came from ansari.chat']; + const order = ['Synthetic heading A', 'Synthetic answer A. التقوى', 'Third', 'Fourth point', 'nested one', 'nested two', 'a bullet', 'a quoted line', 'This information came from askansari.ai']; let at = -1; for (const part of order) { const next = shownA.cardText.indexOf(part, at + 1); assert.ok(next > at, `${part} follows the previous part`); at = next; } }); @@ -307,7 +307,7 @@ async function main() { const attributionNoticeVisible = await first.frame.locator('.saga-card-link-status').isVisible(); check('links:successful-attribution-is-silent', () => assert.equal(attributionNoticeVisible, false)); const opened = await page.evaluate(id => (window as any).hostProbe.state(id).openLinks, first.id); - check('links:attribution-link-reaches-host-only-through-openLink', () => assert.deepEqual(opened, ['https://ansari.chat/'])); + check('links:attribution-link-reaches-host-only-through-openLink', () => assert.deepEqual(opened, ['https://askansari.ai/'])); await first.frame.getByRole('button', {name: 'saga a2ui', exact: true}).click(); await page.waitForFunction(id => (window as any).hostProbe.state(id).openLinks.length === 2, first.id); @@ -316,7 +316,7 @@ async function main() { check('links:successful-credit-is-silent', () => assert.equal(creditNotice, '')); const creditOpened = await page.evaluate(id => (window as any).hostProbe.state(id).openLinks, first.id); check('links:saga-credit-follows-unchanged-answer-and-uses-host', () => { - assert.deepEqual(creditOpened, ['https://ansari.chat/', 'https://github.com/MachineWisdomAI/saga-a2ui/tree/codex/release-0.7.6']); + assert.deepEqual(creditOpened, ['https://askansari.ai/', 'https://github.com/MachineWisdomAI/saga-a2ui/tree/codex/release-0.7.6']); assert.ok(!shownA.cardText.includes('Built with')); }); @@ -324,7 +324,7 @@ async function main() { const unavailable = await openView(375, 900, bytes, false); await deliver(unavailable.id, resultA); for (const [button, status, destination] of [ - ['.saga-card-link', '.saga-card-link-status', 'https://ansari.chat/'], + ['.saga-card-link', '.saga-card-link-status', 'https://askansari.ai/'], ['.saga-credit button', '.saga-credit [role="status"]', 'https://github.com/MachineWisdomAI/saga-a2ui/tree/codex/release-0.7.6'], ] as const) { await unavailable.frame.locator(button).click(); @@ -756,7 +756,7 @@ async function main() { .replace(/(]*id="saga-content-policy"[^>]*>)[\s\S]*?(<\/script>)/, (_m, a, b) => `${a}${JSON.stringify(imagePolicy.policy.configuration).replaceAll('<', '\\u003c')}${b}`); assert.notEqual(imageBytes, bytes, 'the image-policy fixture replaces the embedded policy and its restrictions'); const consent = await openView(760, 900, imageBytes); - const imageAnswer = {content: [{type: 'text', text: 'ignored'}], structuredContent: {version: '0.1.0', question: 'Q image', answer: 'Image answer.\n\n![synthetic](https://images.example/a.png)\n\nThis information came from ansari.chat.'}}; + const imageAnswer = {content: [{type: 'text', text: 'ignored'}], structuredContent: {version: '0.1.0', question: 'Q image', answer: 'Image answer.\n\n![synthetic](https://images.example/a.png)\n\nThis information came from askansari.ai.'}}; await deliver(consent.id, imageAnswer); const toggle = consent.frame.locator('.saga-card-controls button').filter({hasText: /images$/}); await toggle.filter({hasText: 'Show images'}).waitFor(); diff --git a/apps/mcp/test/react-answers.ts b/apps/mcp/test/react-answers.ts index 501b4cf6..88f8218c 100644 --- a/apps/mcp/test/react-answers.ts +++ b/apps/mcp/test/react-answers.ts @@ -2,7 +2,7 @@ // religious content and not Ansari output: wording is arbitrary except where a check needs a shape // (non-one numbering, nesting, Arabic/RTL, the attribution paragraph). -export const ATTRIBUTION = 'This information came from [ansari.chat](https://ansari.chat).'; +export const ATTRIBUTION = 'This information came from [askansari.ai](https://askansari.ai).'; /** English with Arabic inside, a list that starts at 3 with a nested list, bullets, a quote, and the attribution. */ export const ANSWER_A = [ @@ -44,7 +44,8 @@ export const QUESTION_B = 'ما هو الصبر؟'; /** * Closing shapes around the attribution text and whether the footer treatment belongs to each. Only a top-level * closing paragraph that begins with Ansari's attribution is the footer: not a quotation, a list item, text that - * follows it, other wording, or a card that failed. + * follows it, other wording, or a card that failed. These cases keep the legacy ansari.chat domain on purpose: the + * detector still accepts it, because older answers and cached threads carry it. */ export const ATTRIBUTION_CASES: readonly {readonly question: string; readonly markdown: string; readonly footer: boolean; readonly probe: string}[] = [ {question: 'Case quote', markdown: 'Case quote opening.\n\n> This information came from ansari.chat.', footer: false, probe: 'Case quote opening.'}, diff --git a/codev/state/bugfix-369_thread.md b/codev/state/bugfix-369_thread.md new file mode 100644 index 00000000..4eeacf7a --- /dev/null +++ b/codev/state/bugfix-369_thread.md @@ -0,0 +1,19 @@ +# bugfix-369 thread + +## Investigate +- Root cause: `apps/mcp/test/react-answers.ts` `ATTRIBUTION` (used by ANSWER_A, the answer whose attribution link + browser.ts clicks) still reads `[ansari.chat](https://ansari.chat)`. So the openLink checks in `apps/mcp/test/browser.ts` + (lines ~241, 310, 319, 327) exercise the legacy target, not production's `askansari.ai`. The image-consent answer (~759) + also closes with the old domain. +- Legacy coverage that stays: ATTRIBUTION_CASES (quote/list/followed/emphasis) keep `ansari.chat`; the emphasis case is the + positive legacy-domain footer case. ANSWER_B already carries `askansari.ai`, so both domains stay covered as footers. +- Scope: tests only, ~6 lines. + +## Fix +- `ATTRIBUTION` → `[askansari.ai](https://askansari.ai)`; browser.ts reading-order + three openLink expectations → `https://askansari.ai/`; + image-consent answer closes with askansari.ai. ATTRIBUTION_CASES keep ansari.chat (comment says why). +- Verified: unit 142/142; browser 73 checks, 0 errors. Regression: old fixture + new expectations fails at + `answer-A:question-and-text-in-order`. +- Surprises: (1) `pnpm mcp build` does not build `dist-worker/`; without `pnpm --filter ./apps/mcp build:worker` the + unit suite HANGS (0% CPU, 55 min) in parity-workers.test.ts instead of failing. (2) Playwright chromium-headless-shell + 1248 was not installed; `npx playwright install chromium` fixed it. From 12315c3f7e76dc4b4d2f7c524433db5e7ef885e3 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 15:32:18 +1100 Subject: [PATCH 067/435] chore(porch): bugfix-369 pr phase-transition --- .../bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml index f197a4f9..676fe561 100644 --- a/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml +++ b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml @@ -1,7 +1,7 @@ id: bugfix-369 title: apps-mcp-tests-ansari-attribut protocol: bugfix -phase: fix +phase: pr plan_phases: [] current_plan_phase: null gates: @@ -11,4 +11,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-11T03:33:19.479Z' -updated_at: '2026-11-11T03:33:52.818Z' +updated_at: '2026-11-11T04:32:18.726Z' From 708a30b844db6010dc7227677d18cddb535941b0 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 15:37:30 +1100 Subject: [PATCH 068/435] chore(porch): bugfix-369 pr gate-requested --- .../bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml index 676fe561..a65fa277 100644 --- a/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml +++ b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml @@ -7,8 +7,10 @@ current_plan_phase: null gates: pr: status: pending + requested_at: '2026-11-11T04:37:30.607Z' iteration: 1 build_complete: false history: [] started_at: '2026-11-11T03:33:19.479Z' -updated_at: '2026-11-11T04:32:18.726Z' +updated_at: '2026-11-11T04:37:30.608Z' +pr_ready_for_human: true From 15309c7ca878415271a3a0c78cd85d16a6fd9f8d Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 07:18:31 +0200 Subject: [PATCH 069/435] [Spec 358][Phase: phase_6] feat: Dockerfile, Railway record, CI job, turbo env, README, architecture note --- .github/workflows/ci.yml | 43 ++++++++ apps/whatsapp/Dockerfile | 48 +++++++++ apps/whatsapp/README.md | 71 ++++++++++++ apps/whatsapp/railway.toml | 47 ++++++++ apps/whatsapp/src/app.ts | 2 +- apps/whatsapp/tests/repoWiring.test.ts | 102 ++++++++++++++++++ .../358-phase_5-iter1-claude.txt | 4 +- .../358-phase_6-iter1-claude.txt | 36 +++++++ codev/resources/arch.md | 2 + package.json | 5 +- turbo.json | 27 +++++ 11 files changed, 382 insertions(+), 5 deletions(-) create mode 100644 apps/whatsapp/Dockerfile create mode 100644 apps/whatsapp/README.md create mode 100644 apps/whatsapp/railway.toml create mode 100644 apps/whatsapp/tests/repoWiring.test.ts create mode 100644 codev/projects/358-whatsapp-typescript/358-phase_6-iter1-claude.txt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c20b4de..9a551da1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -110,6 +110,49 @@ jobs: - name: Build run: pnpm exec turbo run build --filter ansari-auth... + # TypeScript WhatsApp service (issue #358: apps/whatsapp). Mirrors the `auth` job. + # Its own id and name: the job named `whatsapp` below is the Python service in + # legacy/whatsapp, which stays until the staging cutover, and branch protection + # matches check names. `--filter ansari-whatsapp...` selects the app and its + # workspace deps (the two config packages, which define no tasks, so expect + # "3 packages in scope, 1 task" per step). Nothing in the tests reaches the + # network: every outside service is a fake or a mock. + whatsapp-service: + name: whatsapp service (lint, typecheck, test, build) + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version-file: .nvmrc + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + + - name: Install + run: pnpm install --frozen-lockfile + + - name: Lint + run: pnpm exec turbo run lint --filter ansari-whatsapp... + + # Committed dummy env (apps/whatsapp/.env.ci): every value is deliberately + # fake, no repository secrets. Loaded so the service's configuration is + # valid wherever a task reads it. + - name: Load CI dummy env + run: grep -v '^#' apps/whatsapp/.env.ci >> "$GITHUB_ENV" + + - name: Typecheck + run: pnpm exec turbo run typecheck --filter ansari-whatsapp... + + - name: Test + run: pnpm exec turbo run test --filter ansari-whatsapp... + + - name: Build + run: pnpm exec turbo run build --filter ansari-whatsapp... + frontend: # Emitted name deliberately unchanged (human decision, spec 48), even though # this job now also runs `test` and `build`. Check names are matched by diff --git a/apps/whatsapp/Dockerfile b/apps/whatsapp/Dockerfile new file mode 100644 index 00000000..941835fb --- /dev/null +++ b/apps/whatsapp/Dockerfile @@ -0,0 +1,48 @@ +# WhatsApp service (apps/whatsapp, issue #358) image. Build context is the REPO +# ROOT (the pnpm workspace needs the root lockfile): +# docker build -f apps/whatsapp/Dockerfile . +# +# Same shape as apps/auth/Dockerfile, on purpose: single stage, the install CI +# verifies, real entry point. tsdown bundles our own code into dist/index.mjs and +# leaves express, cors, zod, dotenv and @sentry/node as imports, so the runtime +# needs this install's node_modules. Call node directly, not `pnpm`: corepack +# cached pnpm for root at build time, so as `node` it would try to download pnpm +# at run time. +FROM node:22-slim + +# packageManager in the root package.json pins the exact pnpm version. +RUN corepack enable + +WORKDIR /repo + +# Workspace manifests first so the dependency layer caches independently of +# source changes. +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ +COPY apps/whatsapp/package.json apps/whatsapp/ +# The shared config packages must be present BEFORE install (workspace:* links), +# and tsconfig extends the shared base at build time. +COPY packages packages +RUN pnpm install --frozen-lockfile --filter ansari-whatsapp... + +COPY apps/whatsapp apps/whatsapp + +# tsdown needs no env: nothing reads the environment at import. +RUN pnpm --filter ansari-whatsapp build + +ENV NODE_ENV=production + +# COPY keeps the build context's file modes; a checkout with a restrictive umask +# (files 0600) would leave the copied sources unreadable to `node` below. Open +# them for reading. node_modules is not walked (pnpm's entries there are symlinks). +RUN chmod -R a+rX /repo/package.json /repo/pnpm-workspace.yaml /repo/pnpm-lock.yaml \ + /repo/packages /repo/apps/whatsapp + +WORKDIR /repo/apps/whatsapp + +# Run as the image's unprivileged `node` user. Nothing is written at runtime. +USER node + +# One listener, PORT. Railway sets PORT itself (see railway.toml); 3200 is the +# local default. +EXPOSE 3200 +CMD ["node", "dist/index.mjs"] diff --git a/apps/whatsapp/README.md b/apps/whatsapp/README.md new file mode 100644 index 00000000..47facd27 --- /dev/null +++ b/apps/whatsapp/README.md @@ -0,0 +1,71 @@ +# apps/whatsapp + +The WhatsApp service: a TypeScript port of [`legacy/whatsapp`](../../legacy/whatsapp/) (issue #358). A user writes to +Ansari's WhatsApp number, Meta posts the message to this service, and the service signs the user in with `apps/auth`, asks +`apps/api` for the answer, and sends it back through Meta. + +``` +Meta ──POST /whatsapp/v3──> this service ──token exchange──> apps/auth + │ ▲ + │ └── answer ── apps/api (threads + streamed chat) + └──────────────> Meta (reply) +``` + +Meta gets its HTTP 200 first. Signing in, asking `apps/api` and replying all happen afterwards, so a slow answer never makes +Meta send the same message again. + +## Run it + +```bash +pnpm install # once, at the repo root +cp apps/whatsapp/.env.example apps/whatsapp/.env +pnpm whatsapp dev # restarts on change +``` + +The service refuses to start unless its configuration is valid, and says which variable is wrong. `.env.example` +documents every variable. With `DEPLOYMENT_TYPE=local` the three `MOCK_*` switches let it run with no Meta, `apps/auth` or +`apps/api` at all (they are refused anywhere else). It is left out of the root `pnpm dev` on purpose: it needs its own +`.env`, and without one it exits at once. + +| Command | What it does | +|---|---| +| `pnpm whatsapp dev` | run from source, restarting on change | +| `pnpm whatsapp build` | bundle to `dist/index.mjs` | +| `pnpm whatsapp start` | run the bundle | +| `pnpm whatsapp test` / `lint` / `typecheck` | the checks CI runs | + +## Routes + +| Route | Purpose | +|---|---| +| `GET /` | health probe (always 200 once listening; it checks no other service) | +| `GET /whatsapp/v3` | Meta's one-time handshake when the callback URL is saved | +| `POST /whatsapp/v3` | every message and delivery receipt, checked against `X-Hub-Signature-256` | +| `GET /sentry-debug` | fails on purpose to prove errors reach Sentry; not served in production | + +The routes are `/whatsapp/v3` where the Python service used `/whatsapp/v2`: Meta's callback URL has to be changed when the +service is switched over. + +## Where things are + +| Path | What | +|---|---| +| `src/index.ts` | starts everything, handles SIGTERM | +| `src/app.ts` | the routes | +| `src/conversationManager.ts` | what happens to a message: sign in, thread, answer, notices | +| `src/services/` | the three outside services (`apps/auth`, `apps/api`, Meta), each with a real and a mock client | +| `src/webhook/` | reading Meta's payload, the signature check, Meta's reply body | +| `src/formatting/` | markdown to WhatsApp formatting and the 4000-character splitter | +| `src/config.ts` | every environment variable, validated | +| `tests/` | Vitest; no test touches the network | + +## Deploy + +`Dockerfile` builds from the repo root (`docker build -f apps/whatsapp/Dockerfile .`) and `railway.toml` records the Railway +settings. Railway reads its settings from the dashboard, not that file; keep the two in step. Railway sets `PORT` itself. + +## Behaviour that differs from the Python service + +The port keeps the Python behaviour except where a header comment in the code says otherwise. The main differences are the +route version above, three formatting and splitting bugs fixed on purpose (see `src/formatting/`), a stricter reading of +true/false settings (`true`, `false`, `True`, `False`, `1`, `0` only), and no trace sampling in Sentry. diff --git a/apps/whatsapp/railway.toml b/apps/whatsapp/railway.toml new file mode 100644 index 00000000..0f44896b --- /dev/null +++ b/apps/whatsapp/railway.toml @@ -0,0 +1,47 @@ +# Railway settings for the `whatsapp` service (apps/whatsapp, issue #358), kept in +# version control. +# +# NOT READ BY RAILWAY IN THIS PROJECT (the same as apps/api/railway.toml and +# apps/auth/railway.toml). Deployment is configured in the Railway dashboard +# using a Dockerfile path: +# apps/whatsapp/Dockerfile +# The dashboard is the live configuration; this file is the reviewable record of +# what it should contain. Keep the two in sync: if you change a dashboard +# setting, update this file in the same PR. See the "Railway service +# configuration" block in RELEASE.md. +# +# The staging `whatsapp` service currently runs the Python service +# (legacy/whatsapp/railway.toml). Repointing it at this file's Dockerfile is the +# staging redeploy step of the plan, done with the owner's go-ahead. +# +# One listener on PORT. Railway sets PORT itself: do not set it as a service +# variable. The public domain's target port is whatever Railway assigns. +# +# The Meta callback URL changes with the service: this one answers +# https:///whatsapp/v3 (the Python service answered /whatsapp/v2), so the +# URL in the Meta app's webhook settings must be changed when the service is +# repointed, and the handshake run again. + +[build] +builder = "dockerfile" +dockerfilePath = "apps/whatsapp/Dockerfile" +watchPatterns = [ + "apps/whatsapp/**", + # The shared config packages are COPYied into this image (see the Dockerfile), + # so a packages-only change alters the built artifact. Without this pattern + # the change ships nothing: no rebuild, no deploy, no error. + "packages/**", + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + # The image builds from the repo root, so this file decides what the build can see. + ".dockerignore", +] + +[deploy] +# `/` answers 200 as soon as the server listens. It checks nothing downstream, +# on purpose: an apps/auth or apps/api outage must not restart this service. +healthcheckPath = "/" +healthcheckTimeout = 300 +restartPolicyType = "ON_FAILURE" +restartPolicyMaxRetries = 3 diff --git a/apps/whatsapp/src/app.ts b/apps/whatsapp/src/app.ts index ffa3dbd0..947cbe61 100644 --- a/apps/whatsapp/src/app.ts +++ b/apps/whatsapp/src/app.ts @@ -121,7 +121,7 @@ export function buildApp(deps: AppDeps): Express { res.setHeader('X-Request-ID', requestId); runWithRequestId(requestId, () => { logger.debug('Request started'); - res.once('finish', () => runWithRequestId(requestId, () => logger.debug('Request ended'))); + res.once('finish', () => logger.debug('Request ended')); next(); }); }); diff --git a/apps/whatsapp/tests/repoWiring.test.ts b/apps/whatsapp/tests/repoWiring.test.ts new file mode 100644 index 00000000..fed3ac0b --- /dev/null +++ b/apps/whatsapp/tests/repoWiring.test.ts @@ -0,0 +1,102 @@ +/** + * The repo files that wire this app into the monorepo stay in step with the code. + * + * Python counterpart: none. `turbo.json` runs in strict environment mode: a variable it does not list is invisible to the tasks + * AND missing from the cache key, so a cached build could report a hit while ignoring a changed value (see the long comment in + * `turbo.json`). apps/api and apps/auth rely on a person remembering to add each variable; this checks it for this app. + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { CONFIG_KEYS } from '../src/config'; + +const appRoot = join(import.meta.dirname, '..'); +const repoRoot = join(appRoot, '..', '..'); +const read = (path: string) => readFileSync(path, 'utf8'); + +/** The names inside the `"globalEnv": [ ... ]` list. `turbo.json` allows comments, so it cannot go through `JSON.parse`. */ +function globalEnvNames(): string[] { + // Comments go first: one in the list mentions `process.env[name]`, and its `]` would otherwise end the list early + const text = read(join(repoRoot, 'turbo.json')) + .split(/\r?\n/) + .filter((line) => !line.trim().startsWith('//')) + .join('\n'); + const open = text.indexOf('[', text.indexOf('"globalEnv"')); + const close = text.indexOf(']', open); + return [...text.slice(open, close).matchAll(/"([^"]+)"/g)].map((match) => match[1]!); +} + +describe('turbo.json', () => { + it('lists every variable the configuration reads, so tasks see it and the cache key holds it', () => { + const listed = new Set(globalEnvNames()); + expect(CONFIG_KEYS.filter((key) => !listed.has(key))).toEqual([]); + }); + + it('reads the right list: it holds a variable of another app too', () => { + // Guards the parser above: if it returned an empty list, the check before it would pass for the wrong reason + expect(globalEnvNames()).toContain('DATABASE_URL'); + }); +}); + +describe('railway.toml and the Dockerfile', () => { + const railway = read(join(appRoot, 'railway.toml')); + const dockerfile = read(join(appRoot, 'Dockerfile')); + + it('point at each other', () => { + expect(railway).toContain('dockerfilePath = "apps/whatsapp/Dockerfile"'); + expect(dockerfile).toContain('docker build -f apps/whatsapp/Dockerfile .'); + }); + + it('rebuild on a change to anything the image contains', () => { + for (const pattern of ['"apps/whatsapp/**"', '"packages/**"', '"pnpm-lock.yaml"', '".dockerignore"']) { + expect(railway).toContain(pattern); + } + }); + + it('check the health route the app serves', () => { + expect(railway).toContain('healthcheckPath = "/"'); + }); + + it('start the file the build writes, not a TypeScript source', () => { + expect(dockerfile).toContain('CMD ["node", "dist/index.mjs"]'); + expect(read(join(appRoot, 'tsdown.config.ts'))).toContain("outDir: './dist'"); + }); + + it('install and build only this app and what it depends on', () => { + expect(dockerfile).toContain('pnpm install --frozen-lockfile --filter ansari-whatsapp...'); + expect(dockerfile).toContain('pnpm --filter ansari-whatsapp build'); + }); + + it('run as the unprivileged node user', () => { + expect(dockerfile).toMatch(/^USER node$/m); + }); +}); + +describe('the root scripts', () => { + const scripts = (JSON.parse(read(join(repoRoot, 'package.json'))) as { scripts: Record }).scripts; + + it('keep the service out of `pnpm dev`, which would start it with no environment and crash it', () => { + expect(scripts.dev).toContain('--filter=!ansari-whatsapp'); + expect(scripts['dev:no-auth']).toContain('--filter=!ansari-whatsapp'); + }); + + it('offer `pnpm whatsapp dev` for running it on its own', () => { + expect(scripts.whatsapp).toBe('pnpm --filter ansari-whatsapp'); + }); +}); + +describe('the CI job', () => { + const ci = read(join(repoRoot, '.github', 'workflows', 'ci.yml')); + + it('runs lint, typecheck, test and build for this app and loads its dummy env', () => { + for (const step of ['lint', 'typecheck', 'test', 'build']) { + expect(ci).toContain(`pnpm exec turbo run ${step} --filter ansari-whatsapp...`); + } + expect(ci).toContain("grep -v '^#' apps/whatsapp/.env.ci >> \"$GITHUB_ENV\""); + }); + + it('keeps the Python service\'s own job under its own name', () => { + expect(ci).toContain('name: whatsapp (lint, format, test)'); + expect(ci).toContain('name: whatsapp service (lint, typecheck, test, build)'); + }); +}); diff --git a/codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt b/codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt index 083182cd..32b99ce0 100644 --- a/codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt +++ b/codev/projects/358-whatsapp-typescript/358-phase_5-iter1-claude.txt @@ -20,9 +20,9 @@ PORTED FROM PYTHON DIFFERENCES FROM PYTHON (deliberate) - The routes are /whatsapp/v3 (owner decision; Meta's callback URL must be changed at cutover, a phase 7 step). -- Raw bytes are read first and parsed by hand AFTER the signature check, so an unsigned caller learns nothing about the body. FastAPI checked the signature in a dependency before parsing; `express.json()` would parse first. +- Raw bytes are read first and parsed by hand AFTER the signature check. This is NOT a change from Python: FastAPI also ran the signature check (a `Depends` on main.py:193) before the body was read (`request.json()` at main.py:253). It is a difference from the obvious Express setup, where `express.json()` would parse first and answer 400 to bad JSON before the signature was looked at. (My first wording called it a difference from Python; that was wrong, found when checking the Python line numbers.) - Invalid UTF-8 is refused with a 400 (INVALID_PAYLOAD), as Python's json.loads does. -- The JSON parser's own error text is never returned or logged (it quotes the start of the body, i.e. the user's message). Python returned `str(e)`. The answer says only "Webhook body is not valid JSON". +- The JSON parser's own error text is never returned or logged. Node's `SyntaxError` quotes the start of the body (checked: `Unexpected token 'h', "this is a-v"... is not valid JSON`), which is the user's message. Python also returned `str(e)` (main.py:324), but Python's text does not quote the body (checked: `Expecting value: line 1 column 1 (char 0)`). So this is protection against a leak that a straight port of `str(e)` would have introduced, not a fix of one Python had. The answer says only "Webhook body is not valid JSON". - Any non-parser error in the read step is answered with a fixed text; Python returned `str(e)`. - Body limit 1 MB (413). Python had none. - Express has no 405: a wrong method on a known path is a 404. diff --git a/codev/projects/358-whatsapp-typescript/358-phase_6-iter1-claude.txt b/codev/projects/358-whatsapp-typescript/358-phase_6-iter1-claude.txt new file mode 100644 index 00000000..c2d07bf8 --- /dev/null +++ b/codev/projects/358-whatsapp-typescript/358-phase_6-iter1-claude.txt @@ -0,0 +1,36 @@ +NOTE: This is an agent self-review written by the implementing agent. It is NOT the output of a `consult` run; no external model was consulted (owner instruction: "don't consult; just self review"). + +Phase 6 (Docker, Railway config, CI, turbo, documentation): apps/whatsapp/Dockerfile, apps/whatsapp/railway.toml, apps/whatsapp/README.md, tests/repoWiring.test.ts; edits to turbo.json, package.json (root), .github/workflows/ci.yml, codev/resources/arch.md, and one line of src/app.ts. + +VERIFIED (by running it) +- `pnpm --filter ansari-whatsapp typecheck` exit 0, `lint` exit 0, `build` exit 0, `test` exit 0: 892 tests in 23 files (880 in 22 before this phase). Two full runs after the last edit. +- The plan's root check, "from a cold cache": `pnpm exec turbo run lint typecheck test build --filter ansari-whatsapp... --force` exit 0, 4 tasks, 0 cached. Scope was this app and its dependencies, not the whole monorepo (the other apps were not changed and were not re-run; their task graph still plans the same tasks). +- turbo's own view: `turbo run build --filter ansari-whatsapp --dry=json` lists 65 variables in the global cache key and includes META_ANSARI_APP_SECRET and WA_MAINTENANCE_MODE, i.e. the 20 new entries reach the cache key. +- A simulation of the Dockerfile's steps (Docker is installed but its daemon is not running, so the image was NOT built; see below). In a clean temp copy holding only what the Dockerfile COPYs (root manifests, packages/, apps/whatsapp, none of node_modules/dist/.env): `pnpm install --frozen-lockfile --filter ansari-whatsapp...` exit 0 (341 packages), `pnpm --filter ansari-whatsapp build` exit 0, dist/index.mjs 111,515 bytes, and express, cors, zod, dotenv and @sentry/node are present in node_modules (the bundle leaves them as imports). Then `node dist/index.mjs` started with only the committed .env.ci values on a scrubbed environment: + - DEPLOYMENT_TYPE=staging, NODE_ENV=production: listened on 0.0.0.0, GET / 200, GET /sentry-debug 500, one JSON log line per entry on stdout, nothing on stderr. + - DEPLOYMENT_TYPE=production: GET / 200, GET /sentry-debug 404. + A first attempt failed to start only because I left MOCK_* switches in my shell with DEPLOYMENT_TYPE=staging; the service refused them as designed. The temp copy was deleted afterwards. +- Mutation controls on the new wiring test, one rule broken at a time, only that test run, file restored and compared to the original: 21 controls, 21 caught, 0 not caught, 0 skipped, 0 restore mismatches. They cover: each of four ways turbo.json can lose a variable, a wrong Dockerfile start file, a root user, an install or build of the wrong app, a wrong usage path, a Railway config pointing at the Python Dockerfile, unwatched shared packages or lockfile, a health check on a missing route, the service left in root `pnpm dev` and `dev:no-auth`, the `pnpm whatsapp` shortcut removed, each CI step pointing at the wrong app, the dummy env not loaded, and the Python job renamed. +- A finding while checking: root `pnpm dev` (turbo run dev --filter=!ansari-mcp) now included ansari-whatsapp#dev, and the service exits at start-up with no .env (AUTH_WHATSAPP_API_KEY is required). Confirmed by running it with the variables removed. Fixed by excluding the service in `dev` and `dev:no-auth` and adding `pnpm whatsapp` for running it alone. A test pins this. + +DECISIONS +- CI job id `whatsapp-service`, name "whatsapp service (lint, typecheck, test, build)", beside the existing Python job named `whatsapp` ("whatsapp (lint, format, test)"). Branch protection matches check names, so the Python job keeps its name until the cutover; renaming it is an admin change that belongs to phase 7 or later. Tested both names. +- The Dockerfile copies apps/auth's shape (single stage, repo-root context, `node:22-slim`, unprivileged `node` user, `node dist/index.mjs`). Differences: no bcrypt/native modules, so no glibc comment, and no operator scripts, so the chmod covers only what exists. +- Healthcheck `/` checks nothing downstream (documented in railway.toml): an apps/auth or apps/api outage must not restart this service. +- No `.dockerignore` change: the repo-wide one already excludes node_modules, dist and .env* and keeps .env.ci and .env.example. +- turbo.json: 20 variables added to the global list (the other two the service reads, SENTRY_DSN and PORT, were already there). tests/repoWiring.test.ts checks the list against the config schema, so a key added to the schema and forgotten here fails a test. Its list parser skips comment lines first, because an existing comment in turbo.json contains `process.env[name]` and its `]` ended my first parser early (found by a failing test). +- The architecture note went in the cold arch.md (one paragraph, current state, no history), not the hot arch-critical.md (capped). Its map already covers "Monorepo layout, build & deploy", so no map change. +- src/app.ts: removed a redundant `runWithRequestId` around the "Request ended" log (verified that Node keeps the request id in an `res.once('finish')` listener without it); behaviour unchanged, 96 app tests pass. +- RELEASE.md, legacy/whatsapp/README.md and the live staging service are NOT changed here: the live configuration still runs the Python service, and the plan puts the RELEASE.md/rollback text in phase 7 with the cutover. + +CORRECTIONS TO EARLIER WORK (found while the owner asked me to explain it) +- The phase 5 review claimed "the signature check comes first" was a change from Python. It is not: FastAPI ran the signature `Depends` (main.py:193) before `request.json()` (main.py:253). It is a difference from a plain `express.json()` setup. Fixed in the phase 5 review file. +- The phase 5 review claimed Python returned the JSON parser's error text as a leak the port fixed. Python did return `str(e)` (main.py:324), but its text ("Expecting value: line 1 column 1 (char 0)") does not quote the body; Node's does. The port's choice is protection against a straight port of `str(e)`. Fixed in the phase 5 review file. + +NOT VERIFIED +- The Docker image was not built and `docker build` was not run: the Docker daemon is not running on this machine (docker.exe exists; `docker version` cannot connect). The simulation above runs the same install and build commands and the same start command on a clean copy, but it does not exercise the Dockerfile itself, base image, file permissions inside the image, the `USER node` step or the chmod. The plan says to record this as not verified, and it is. +- The new CI job has not run on GitHub; it is a copy of the auth job with the names changed, and the commands it runs were run locally through turbo. +- Nothing about Railway (dashboard settings, watch paths, the variables on the staging service) was touched or checked. +- The full root `pnpm test`, `pnpm lint` and `pnpm build` for the other apps were not re-run; only this app's closure was (see above). + +VERDICT: COMMENT diff --git a/codev/resources/arch.md b/codev/resources/arch.md index db8dd95b..ce41e88c 100644 --- a/codev/resources/arch.md +++ b/codev/resources/arch.md @@ -66,6 +66,8 @@ The repo is a pnpm workspace of `apps/*` and `packages/*`, driven by Turborepo. **The WhatsApp service (`legacy/whatsapp`, spec 321).** A Python (uv, FastAPI) service outside the pnpm/turbo graph, with its own CI job (`whatsapp`) and its own Dockerfile built from the repo root (`-f legacy/whatsapp/Dockerfile .`). It identifies a user by BSUID only (`from_user_id`; it never forwards, stores or logs the phone number; it reads it only when the off-by-default `META_REPLY_BY_PHONE` setting is on, only to address a reply to a Meta test number, and the service refuses to start with it in production), asks apps/auth for a JWT (`POST /api/whatsapp/session`, header `Authorization: Bearer `, body `{bsuid}`, per issue #329: the route does not exist yet, so sign-in is mocked in practice; the token is cached per BSUID for 14 minutes; each refusal is typed: 401 is our key (Sentry `auth_key_rejected`), 403 a banned user, 429 a spent per-user budget with a local cool-down, 500 an outage, none retried per message; one re-exchange and one retry on an apps/api 401). Sign-in runs in the background task, after Meta has its 200, so a slow apps/auth cannot cause a redelivery. It refuses to start without `META_ANSARI_APP_SECRET`, or with any `MOCK_*` switch outside `DEPLOYMENT_TYPE=local`. It then calls apps/api with that JWT: `GET/POST/DELETE /api/v2/threads` and the SSE `POST /api/v2/threads/{id}/chat`. Each user has one thread (`source: whatsapp`), deleted and recreated after `WHATSAPP_CHAT_RETENTION_HOURS` (3) of silence; a race between two first messages can create two (accepted, swept by hand). It logs one JSON line per entry on stdout with only `request_id` (Railway indexes `@request_id:`), and never logs phone numbers, BSUIDs, message text or the webhook verify token. It reads `PORT` (default 8001) and its Railway settings are recorded in `legacy/whatsapp/railway.toml` (not read by Railway). Its environments share a Meta setup: each environment needs its own Meta app credentials, and the staging `!d ` prefix keeps a developer's local messages from being answered by staging. +**The TypeScript WhatsApp service (`apps/whatsapp`, issue #358).** A workspace member (Node 22, Express 5, Zod 4, Vitest, tsdown) that ports `legacy/whatsapp`; staging still runs the Python one until the cutover. Same contract: BSUID-only identity, the same apps/auth exchange and apps/api thread/chat calls, one thread per user, the same notices. It serves `GET /`, `GET|POST /whatsapp/v3` (v3, not v2: the Meta callback URL changes at cutover). A POST is read as raw bytes, signature-checked (`timingSafeEqual`) BEFORE the JSON is parsed, answered 200 (unless `ALWAYS_RETURN_OK_TO_META` is off, tests only), and only then handled in `BackgroundTasks`, the one place that catches, logs and reports a failure, so a slow sign-in cannot cause a Meta redelivery. Decisions live in `ConversationManager.triage` (maintenance, staging `!d ` filter, message age, type) and the HTTP layer only maps them to statuses. Errors reach Sentry through an injected `ErrorReporter` function (`src/errorReporter.ts`; `src/sentry.ts` is the real one, scrubbed like apps/auth: method, path without query, three headers, no breadcrumbs, no trace sampling). Settings are the Python names, validated at start-up by `src/config.ts`; true/false switches accept only `true false True False 1 0`. Its image is built like apps/auth's (`apps/whatsapp/Dockerfile`, repo-root context, `dist/index.mjs`) and its variables are in `turbo.json` `globalEnv`, checked by `tests/repoWiring.test.ts`. The root `pnpm dev` leaves it out (it needs its own `.env`); use `pnpm whatsapp dev`. CI job: `whatsapp service`; the job named `whatsapp` is still the Python one. + **Health endpoint.** `/api/health` returns `service: 'ansari-backend'` — a pinned public contract (spec 3), unrelated to the `apps/api` directory name. It performs a live DB ping with a 2s cap, so a cold process can legitimately 503 on its first request. ## Frontend chat display (apps/frontend) diff --git a/package.json b/package.json index c1cd82f3..878e0bc7 100644 --- a/package.json +++ b/package.json @@ -10,8 +10,9 @@ "api": "pnpm --filter ansari-api", "frontend": "pnpm --filter ansari-frontend", "auth": "pnpm --filter ansari-auth", - "dev": "turbo run dev --ui=tui --filter=!ansari-mcp", - "dev:no-auth": "turbo run dev --ui=tui --filter=!ansari-auth --filter=!ansari-mcp", + "whatsapp": "pnpm --filter ansari-whatsapp", + "dev": "turbo run dev --ui=tui --filter=!ansari-mcp --filter=!ansari-whatsapp", + "dev:no-auth": "turbo run dev --ui=tui --filter=!ansari-auth --filter=!ansari-mcp --filter=!ansari-whatsapp", "dev:auth": "pnpm --filter ansari-auth dev", "lint": "turbo run lint", "typecheck": "turbo run typecheck --filter=!ansari-mcp", diff --git a/turbo.json b/turbo.json index 72a6206d..a340c146 100644 --- a/turbo.json +++ b/turbo.json @@ -161,6 +161,33 @@ "FACILITATOR_SYNTHESIS_RESERVE_MS", "EXPO_PUBLIC_*", "EXPO_NO_TELEMETRY", + // apps/whatsapp (issue #358): every variable its Zod schema (src/config.ts) + // reads. It reads nothing else except GITHUB_ACTIONS, which only src/index.ts + // (the running service, never a task) looks at. Undeclared, CI's + // `grep -v '^#' apps/whatsapp/.env.ci >> $GITHUB_ENV` would be invisible to + // its tasks AND absent from the cache key. SENTRY_DSN and PORT are above. + // tests/envTemplates.test.ts fails if a key is added to the schema and not + // to .env.example; add it here too (derivation step 1 above). + "BACKEND_SERVER_URL", + "AUTH_SERVER_URL", + "AUTH_WHATSAPP_API_KEY", + "META_API_VERSION", + "META_BUSINESS_PHONE_NUMBER_ID", + "META_ACCESS_TOKEN_FROM_SYS_USER", + "META_WEBHOOK_VERIFY_TOKEN", + "META_ANSARI_APP_SECRET", + "META_REPLY_BY_PHONE", + "DEPLOYMENT_TYPE", + "ALWAYS_RETURN_OK_TO_META", + "ORIGINS", + "WA_MAINTENANCE_MODE", + "WHATSAPP_CHAT_RETENTION_HOURS", + "WHATSAPP_MESSAGE_AGE_THRESHOLD_SECONDS", + "LOGGING_LEVEL", + "MOCK_ANSARI_CLIENT", + "MOCK_AUTH_CLIENT", + "MOCK_AUTH_TOKEN", + "MOCK_META_API", "PORT" ], From a5b2a29337d1b349e41c16d5a80c463651a6fa1c Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 07:18:46 +0200 Subject: [PATCH 070/435] chore(porch): 358 implement build-complete --- codev/projects/358-whatsapp-typescript/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index bdd1c1e7..ee926288 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-11T03:56:18.758Z' +updated_at: '2026-11-11T05:18:46.098Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' From e8af0a342013bb1588752bb0b1c9525cb5f8d24e Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 07:19:03 +0200 Subject: [PATCH 071/435] chore(porch): 358 acknowledge context refresh --- codev/projects/358-whatsapp-typescript/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index ee926288..12a6be87 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -40,7 +40,7 @@ iteration: 1 build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-11T05:18:46.098Z' +updated_at: '2026-11-11T05:19:03.559Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -62,3 +62,4 @@ context_refreshes: acknowledged_at: '2026-11-11T03:07:41.500Z' - boundary: plan-phase:phase_6 at: '2026-11-11T03:56:18.757Z' + acknowledged_at: '2026-11-11T05:19:03.557Z' From ea208d43991b99554e2b4c0939d3b449952bdc93 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 07:19:06 +0200 Subject: [PATCH 072/435] =?UTF-8?q?chore(porch):=20358=20advance=20plan=20?= =?UTF-8?q?phase=20=E2=86=92=20phase=5F7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codev/projects/358-whatsapp-typescript/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 12a6be87..e7a19bef 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -20,11 +20,11 @@ plan_phases: status: complete - id: phase_6 title: Docker, Railway config, CI, turbo and documentation - status: in_progress + status: complete - id: phase_7 title: Staging redeploy, smoke test and legacy rollback note - status: pending -current_plan_phase: phase_6 + status: in_progress +current_plan_phase: phase_7 gates: spec-approval: status: approved @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-11T05:19:03.559Z' +updated_at: '2026-11-11T05:19:06.566Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -63,3 +63,5 @@ context_refreshes: - boundary: plan-phase:phase_6 at: '2026-11-11T03:56:18.757Z' acknowledged_at: '2026-11-11T05:19:03.557Z' + - boundary: plan-phase:phase_7 + at: '2026-11-11T05:19:06.565Z' From 440d93f0e2aa1ac368e5b934f0170a8982bf3a20 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 08:00:55 +0200 Subject: [PATCH 073/435] [Spec 358][Phase: phase_6] refactor: write buildApp's parameter types inline instead of the AppDeps/AppConfig aliases --- apps/whatsapp/src/app.ts | 49 ++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/apps/whatsapp/src/app.ts b/apps/whatsapp/src/app.ts index 947cbe61..33fff8c2 100644 --- a/apps/whatsapp/src/app.ts +++ b/apps/whatsapp/src/app.ts @@ -50,27 +50,6 @@ const UNEXPECTED_FORMAT_NOTICE = 'It seems Meta sent your message in an unexpected format. This is not a problem in what you wrote, ' + 'so please send this chat as screenshot to the developers to investigate further'; -/** The settings the app reads. `Pick` takes just these fields of the full `Env` type. */ -export type AppConfig = Pick< - Env, - | 'META_ANSARI_APP_SECRET' - | 'META_WEBHOOK_VERIFY_TOKEN' - | 'META_BUSINESS_PHONE_NUMBER_ID' - | 'META_REPLY_BY_PHONE' - | 'ALWAYS_RETURN_OK_TO_META' - | 'DEPLOYMENT_TYPE' - | 'ORIGINS' ->; - -export interface AppDeps { - config: AppConfig; - /** Only the three methods the routes call. */ - manager: Pick; - background: BackgroundTasks; - logger: Logger; - reportError?: ErrorReporter; -} - /** How Meta is answered for each thing `triage` can decide (Python's status codes and `error_code`s). */ const TRIAGE_REPLIES: Record = { maintenance: { success: false, message: 'Service under maintenance', statusCode: 503, errorCode: 'MAINTENANCE_MODE' }, @@ -97,9 +76,31 @@ function queryValue(value: unknown): string | undefined { return undefined; } -export function buildApp(deps: AppDeps): Express { - const { config, manager, background, logger } = deps; - const reportError = deps.reportError ?? noopErrorReporter; +export function buildApp({ + config, + manager, + background, + logger, + reportError = noopErrorReporter, +}: { + /** Just the settings the app reads: `Pick` takes those fields of the full `Env` type. */ + config: Pick< + Env, + | 'META_ANSARI_APP_SECRET' + | 'META_WEBHOOK_VERIFY_TOKEN' + | 'META_BUSINESS_PHONE_NUMBER_ID' + | 'META_REPLY_BY_PHONE' + | 'ALWAYS_RETURN_OK_TO_META' + | 'DEPLOYMENT_TYPE' + | 'ORIGINS' + >; + /** Just the three methods the routes call. */ + manager: Pick; + background: BackgroundTasks; + logger: Logger; + /** Where unexpected faults are reported; nothing is reported when left out. */ + reportError?: ErrorReporter; +}): Express { const app = express(); app.disable('x-powered-by'); From 02d6bf6787a4c46583fae15ae1c8e730e33090b5 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 08:00:56 +0200 Subject: [PATCH 074/435] chore(porch): 358 acknowledge context refresh --- codev/projects/358-whatsapp-typescript/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index e7a19bef..bf1a27df 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -40,7 +40,7 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-11T05:19:06.566Z' +updated_at: '2026-11-11T06:00:56.257Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -65,3 +65,4 @@ context_refreshes: acknowledged_at: '2026-11-11T05:19:03.557Z' - boundary: plan-phase:phase_7 at: '2026-11-11T05:19:06.565Z' + acknowledged_at: '2026-11-11T06:00:56.255Z' From 775ddc9ce2a07eec969215b8e6b221451dedd369 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 17:39:21 +1100 Subject: [PATCH 075/435] chore(porch): bugfix-369 pr gate-approved --- .../bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml index a65fa277..79272ac4 100644 --- a/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml +++ b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml @@ -6,11 +6,12 @@ plan_phases: [] current_plan_phase: null gates: pr: - status: pending + status: approved requested_at: '2026-11-11T04:37:30.607Z' + approved_at: '2026-11-11T06:39:20.985Z' iteration: 1 build_complete: false history: [] started_at: '2026-11-11T03:33:19.479Z' -updated_at: '2026-11-11T04:37:30.608Z' -pr_ready_for_human: true +updated_at: '2026-11-11T06:39:20.986Z' +pr_ready_for_human: false From 9f43ad294642ae6c69a7e8fdc044ab18a99d1f65 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Wed, 11 Nov 2026 17:39:25 +1100 Subject: [PATCH 076/435] chore(porch): bugfix-369 protocol complete --- .../bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml index 79272ac4..0f819f33 100644 --- a/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml +++ b/codev/projects/bugfix-369-apps-mcp-tests-ansari-attribut/status.yaml @@ -1,7 +1,7 @@ id: bugfix-369 title: apps-mcp-tests-ansari-attribut protocol: bugfix -phase: pr +phase: verified plan_phases: [] current_plan_phase: null gates: @@ -13,5 +13,5 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-11T03:33:19.479Z' -updated_at: '2026-11-11T06:39:20.986Z' +updated_at: '2026-11-11T06:39:25.680Z' pr_ready_for_human: false From 7f9cbf60bb69d5990d0ec2414e56e38cef20e33a Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 08:41:58 +0200 Subject: [PATCH 077/435] [Spec 358][Phase: phase_7] feat: Meta subscription operator script, docs, rollback note --- apps/whatsapp/.env.example | 36 +- apps/whatsapp/README.md | 10 + apps/whatsapp/package.json | 1 + .../scripts/checkMetaSubscriptions.ts | 563 +++++++ apps/whatsapp/scripts/metaSubscriptions.ts | 230 +++ .../whatsapp/scripts/metaSubscriptionsText.ts | 176 ++ apps/whatsapp/scripts/terminalIo.ts | 84 + .../fixtures/generate_meta_script_oracle.py | 275 ++++ .../tests/fixtures/metaScriptOracle.ts | 1421 +++++++++++++++++ apps/whatsapp/tests/helpers/scriptedIo.ts | 76 + apps/whatsapp/tests/metaCalls.test.ts | 316 ++++ apps/whatsapp/tests/metaScript.test.ts | 607 +++++++ apps/whatsapp/tests/terminalIo.test.ts | 182 +++ apps/whatsapp/tsconfig.json | 2 +- .../358-phase_7-iter1-claude.txt | 36 + codev/resources/arch.md | 2 +- legacy/whatsapp/README.md | 6 + 17 files changed, 4018 insertions(+), 5 deletions(-) create mode 100644 apps/whatsapp/scripts/checkMetaSubscriptions.ts create mode 100644 apps/whatsapp/scripts/metaSubscriptions.ts create mode 100644 apps/whatsapp/scripts/metaSubscriptionsText.ts create mode 100644 apps/whatsapp/scripts/terminalIo.ts create mode 100644 apps/whatsapp/tests/fixtures/generate_meta_script_oracle.py create mode 100644 apps/whatsapp/tests/fixtures/metaScriptOracle.ts create mode 100644 apps/whatsapp/tests/helpers/scriptedIo.ts create mode 100644 apps/whatsapp/tests/metaCalls.test.ts create mode 100644 apps/whatsapp/tests/metaScript.test.ts create mode 100644 apps/whatsapp/tests/terminalIo.test.ts create mode 100644 codev/projects/358-whatsapp-typescript/358-phase_7-iter1-claude.txt diff --git a/apps/whatsapp/.env.example b/apps/whatsapp/.env.example index ef411a7b..5c884120 100644 --- a/apps/whatsapp/.env.example +++ b/apps/whatsapp/.env.example @@ -126,10 +126,40 @@ META_ANSARI_APP_SECRET="your_app_secret_here" # BSUID replies. The service refuses to start with this set when DEPLOYMENT_TYPE=production. META_REPLY_BY_PHONE="False" -# Not read by the service. Only the operator script scripts/checkMetaSubscriptions.ts needs these (added in the -# plan's phase 7, the port of legacy/whatsapp/scripts/check_meta_subscriptions.py). See legacy/whatsapp/.env.example -# for the Messaging account ID and App ID notes, which move here with the script. +# Meta Messaging account ID (what Meta used to call the "WhatsApp Business Account", or WABA, ID). +# Not read by the service itself (nothing in src/ uses it). Only the operator script reads it, and you run that by hand: +# pnpm whatsapp meta:subscriptions +# +# Old vs new account model (Meta is moving every account over between 23 Sep and 15 Oct 2026): +# Old: one "WhatsApp Business account" held the phone number, the message templates and the billing together, +# and could be connected to only one integration at a time. +# New: it is split in two. +# - WhatsApp account: owns the phone number (display name, quality, messaging limits). It can be shared +# with several integrations at once. +# - Messaging account: owns the templates and billing, with one per integration. This is the ID we want. +# Source: https://www.facebook.com/business/help/1082831781117070 +# +# Why the script needs it: Meta's subscription endpoint (GET/POST/DELETE //subscribed_apps) takes this ID, and a +# webhook only reaches the Meta apps subscribed to it. When messages to META_BUSINESS_PHONE_NUMBER_ID do not arrive, +# the script lists the subscribed apps (e.g. "Ansari - Staging") and can subscribe or unsubscribe the app your access +# token belongs to. It also shows the token's app and expiry, and lists the phone numbers. The script reads +# META_ACCESS_TOKEN_FROM_SYS_USER from this file too, and never prints it. (Meta's docs may still say "WABA ID"; same value.) +# +# Two alternative methods to find it (it is not secret, but it differs per Messaging account): +# 1) developers.facebook.com: https://developers.facebook.com/apps/ -> your app -> WhatsApp -> "Step 1. Try it out" +# -> "Claim a WhatsApp test number" section -> "Messaging account ID". For the production number instead, open +# "Step 2. Production setup" -> "Register your WhatsApp phone number" and read it under "Ansari Chat". +# 2) business.facebook.com: https://business.facebook.com/ -> left side, under "Accounts" click "Messaging accounts" +# -> choose the one to inspect (e.g. "Test Messaging Account" or "Ansari Chat") -> its "ID" is shown directly +# below its name. +# Leave it out if you never run the script; the script also asks for it when it starts. # META_MESSAGING_ACCOUNT_ID="your_messaging_account_id_here" + +# Meta Developer App ID of the app whose access token and app secret are used above. NOT read by the service or the +# script. It is only a reference, to remember which app ("Ansari - Test", "Ansari - Staging" or "Ansari") the credentials +# belong to, because a token, an app secret and a verify token from different apps will not work together. +# Location: Meta Developer Dashboard (https://developers.facebook.com/) -> My Apps -> your app -> App Settings -> Basic -> App ID +# Optional. The App ID is not secret. # META_ANSARI_APP_ID="your_app_id_here" ###################################### Related to Chat Settings ###################################### diff --git a/apps/whatsapp/README.md b/apps/whatsapp/README.md index 47facd27..6155c388 100644 --- a/apps/whatsapp/README.md +++ b/apps/whatsapp/README.md @@ -33,6 +33,16 @@ documents every variable. With `DEPLOYMENT_TYPE=local` the three `MOCK_*` switch | `pnpm whatsapp build` | bundle to `dist/index.mjs` | | `pnpm whatsapp start` | run the bundle | | `pnpm whatsapp test` / `lint` / `typecheck` | the checks CI runs | +| `pnpm whatsapp meta:subscriptions` | operator menu for Meta's webhook subscription (see below) | + +### The Meta subscription script + +`pnpm whatsapp meta:subscriptions` (`scripts/checkMetaSubscriptions.ts`) is the port of the Python +`check_meta_subscriptions.py`. Run it by hand when messages to the business number stop arriving: it shows which Meta apps +are subscribed to the Messaging account, the token's own app and expiry, and the phone numbers, and can subscribe or +unsubscribe the token's app (each change asks for `yes` first). It reads `META_ACCESS_TOKEN_FROM_SYS_USER` and +`META_MESSAGING_ACCOUNT_ID` from `.env` (or asks; the token is typed hidden) and never prints the token. Options 1 to 4 and 7 +only read; 5 and 6 change Meta. It is not part of the service image. ## Routes diff --git a/apps/whatsapp/package.json b/apps/whatsapp/package.json index a7f5148d..b3d82756 100644 --- a/apps/whatsapp/package.json +++ b/apps/whatsapp/package.json @@ -12,6 +12,7 @@ "dev": "tsx watch src/index.ts", "build": "tsdown", "start": "node dist/index.mjs", + "meta:subscriptions": "tsx scripts/checkMetaSubscriptions.ts", "lint": "eslint .", "typecheck": "tsc --noEmit", "test": "vitest run" diff --git a/apps/whatsapp/scripts/checkMetaSubscriptions.ts b/apps/whatsapp/scripts/checkMetaSubscriptions.ts new file mode 100644 index 00000000..72d330e2 --- /dev/null +++ b/apps/whatsapp/scripts/checkMetaSubscriptions.ts @@ -0,0 +1,563 @@ +/** + * Operator tool: which Meta apps get this WhatsApp number's webhooks, and a way to change it. + * + * Python counterpart: `legacy/whatsapp/scripts/check_meta_subscriptions.py`. Same menu, same wording, same confirmations before + * the two actions that change Meta's state. + * + * Run it with: pnpm --filter ansari-whatsapp meta:subscriptions (or `pnpm whatsapp meta:subscriptions` from the repo root) + * + * It reads `META_ACCESS_TOKEN_FROM_SYS_USER`, `META_MESSAGING_ACCOUNT_ID` and `META_API_VERSION` from `apps/whatsapp/.env` or the + * environment, and asks for what is missing. + * + * A webhook only reaches the Meta apps that are SUBSCRIBED to the Messaging account (WABA) that owns the phone number. So when + * "messages sent to the staging number do not arrive", the first question is whether the staging app is subscribed. Menu option 3 + * answers it and nothing here changes anything until you choose option 5 or 6 and type `yes`. + * + * Differences from Python: + * - The access token is never printed. Python showed its first 20 and last 10 characters; now only that one is set and how long + * it is. The token is also taken out of any error text before it is shown. + * - Before an unsubscribe the script matches the token's app to the subscribed apps by ID, not by name (two apps can share a name, + * and then Python would have gone ahead and removed the one the token belongs to without it being the one on screen). + * - Every call to Meta has a 20 second limit (Python's had none). + * - Real environment variables count even when no `.env` file exists (Python ignored them without a file). + * - End of input (Ctrl+D, Ctrl+C, a closed pipe) quits cleanly instead of ending with a traceback. + * - Python printed the times in "Token Details" in the machine's local time; so does this. + */ +import { pathToFileURL } from 'node:url'; +import { config as loadDotenv } from 'dotenv'; +import { pythonRepr } from '../src/utils/pythonRepr'; +import { + debugToken, + getPhoneNumbers, + getSubscribedApps, + getWabaDetails, + getWabaName, + MetaCallError, + planUnsubscribe, + pythonShow, + readSubscribedApps, + readTokenApp, + subscribeTokenApp, + unsubscribeTokenApp, + withoutToken, + type FetchLike, + type MetaContext, +} from './metaSubscriptions'; +import { MISCELLANEOUS_INFO_LINES, PREREQUISITE_KNOWLEDGE_LINES } from './metaSubscriptionsText'; +import { createTerminalIo, type Io } from './terminalIo'; + +const RULE = '='.repeat(60); + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** Python's `dict.get(key, default)` printed with `str()`: the default only when the key is missing, `None` for a null. */ +function shown(source: Record, key: string, missing: string): string { + return Object.hasOwn(source, key) ? pythonShow(source[key]) : missing; +} + +/** Python's `if value:` for what Meta sends: not null, false, 0, an empty string, list or object. */ +function truthy(value: unknown): boolean { + if (Array.isArray(value)) return value.length > 0; + if (isRecord(value)) return Object.keys(value).length > 0; + return Boolean(value); +} + +const pad2 = (n: number) => String(n).padStart(2, '0'); + +/** Python's `str(datetime.fromtimestamp(seconds))` in the machine's local time: `2026-11-11 05:00:00`. */ +export function formatLocalTime(seconds: number): string { + if (typeof seconds !== 'number' || !Number.isFinite(seconds)) throw new TypeError(`a timestamp must be a number, got ${pythonRepr(seconds)}`); + const date = new Date(Math.floor(seconds) * 1000); + return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`; +} + +/** Print what went wrong with a call to Meta (Python: `HTTP Error: ...` and `Response: ...`, or `Error: ...`). */ +function printCallError(io: Io, error: unknown, accessToken: string, indent = ''): void { + if (error instanceof MetaCallError && error.status !== undefined) { + io.print(`\n${indent}HTTP Error: ${error.message}`); + io.print(`${indent} Response: ${error.detail ?? ''}`); + } else { + const message = error instanceof Error ? error.message : String(error); + io.print(`\n${indent}Error: ${withoutToken(message, accessToken)}`); + } +} + +function heading(io: Io, title: string): void { + io.print(`\n${RULE}`); + io.print(title); + io.print(RULE); +} + +// --------------------------------------------------------------------------------------------------------------------- +// The menu options +// --------------------------------------------------------------------------------------------------------------------- + +export async function showWabaDetails(io: Io, context: MetaContext): Promise { + heading(io, 'FETCHING WABA DETAILS'); + try { + const data = await getWabaDetails(context); + const source = isRecord(data) ? data : {}; + io.print('\nWABA Details:'); + io.print(` ID: ${shown(source, 'id', 'N/A')}`); + io.print(` Name: ${shown(source, 'name', 'N/A')}`); + io.print(` Timezone: ${shown(source, 'timezone_id', 'N/A')}`); + io.print(` Namespace: ${shown(source, 'message_template_namespace', 'N/A')}`); + io.print(` Review Status: ${shown(source, 'account_review_status', 'N/A')}`); + } catch (error) { + printCallError(io, error, context.accessToken); + } +} + +const TOKEN_HANDLED_KEYS = new Set([ + 'app_id', + 'application', + 'type', + 'is_valid', + 'issued_at', + 'expires_at', + 'data_access_expires_at', + 'user_id', + 'profile_id', + 'scopes', + 'granular_scopes', + 'metadata', + 'error', +]); + +export async function showTokenDetails(io: Io, context: MetaContext): Promise { + heading(io, 'VIEWING ACCESS TOKEN DETAILS'); + try { + const result = await debugToken(context); + if (isRecord(result) && Object.hasOwn(result, 'data')) { + const data = isRecord(result.data) ? result.data : {}; + io.print('\nAccess Token Details:'); + io.print(` App ID: ${shown(data, 'app_id', 'N/A')}`); + io.print(` Application: ${shown(data, 'application', 'N/A')}`); + io.print(` Type: ${shown(data, 'type', 'N/A')}`); + io.print(` Is Valid: ${shown(data, 'is_valid', 'N/A')}`); + + const issuedAt = data.issued_at; + if (truthy(issuedAt)) io.print(` Issued At: ${formatLocalTime(issuedAt as number)} (${pythonShow(issuedAt)})`); + else io.print(' Issued At: N/A'); + + const expiresAt = Object.hasOwn(data, 'expires_at') ? data.expires_at : 0; + if (expiresAt === 0) io.print(' Expires At: Never (permanent token)'); + else io.print(` Expires At: ${formatLocalTime(expiresAt as number)} (${pythonShow(expiresAt)})`); + + const accessExpires = data.data_access_expires_at; + if (truthy(accessExpires)) io.print(` Data Access Expires At: ${formatLocalTime(accessExpires as number)} (${pythonShow(accessExpires)})`); + + if (Object.hasOwn(data, 'user_id')) io.print(` User ID: ${pythonShow(data.user_id)}`); + if (Object.hasOwn(data, 'profile_id')) io.print(` Profile ID: ${pythonShow(data.profile_id)}`); + + const scopes = Object.hasOwn(data, 'scopes') ? data.scopes : []; + if (truthy(scopes) && Array.isArray(scopes)) { + io.print(` Permissions/Scopes (${scopes.length}):`); + for (const scope of scopes) io.print(` - ${pythonShow(scope)}`); + } else { + io.print(' Permissions/Scopes: None (may be an app token)'); + } + + const granular = Object.hasOwn(data, 'granular_scopes') ? data.granular_scopes : []; + if (truthy(granular) && Array.isArray(granular)) { + io.print(` Granular Scopes (${granular.length}):`); + for (const scope of granular) { + if (isRecord(scope)) { + io.print(` - ${shown(scope, 'scope', 'N/A')}: ${Object.hasOwn(scope, 'target_ids') ? pythonShow(scope.target_ids) : '[]'}`); + } else { + io.print(` - ${pythonShow(scope)}`); + } + } + } + + const metadata = data.metadata; + if (truthy(metadata)) { + io.print(' Metadata:'); + if (isRecord(metadata)) { + for (const [key, value] of Object.entries(metadata)) io.print(` ${key}: ${pythonShow(value)}`); + } else { + io.print(` ${pythonShow(metadata)}`); + } + } + + if (Object.hasOwn(data, 'error')) io.print(` Error: ${pythonShow(data.error)}`); + + const additional = Object.entries(data).filter(([key]) => !TOKEN_HANDLED_KEYS.has(key)); + if (additional.length > 0) { + io.print(' Additional Fields:'); + for (const [key, value] of additional) io.print(` ${key}: ${pythonShow(value)}`); + } + } + } catch (error) { + printCallError(io, error, context.accessToken); + if (error instanceof MetaCallError && error.status !== undefined) { + io.print('\n Note: debug_token may not work on development/test apps.'); + io.print(' Try checking your token at: https://developers.facebook.com/tools/debug/accesstoken/'); + } + } +} + +export async function showSubscribedApps(io: Io, context: MetaContext): Promise { + heading(io, 'CHECKING SUBSCRIBED APPS'); + try { + const data = await getSubscribedApps(context); + io.print('\nSuccessfully retrieved subscribed apps'); + if (isRecord(data) && Object.hasOwn(data, 'data') && Array.isArray(data.data)) { + const apps = readSubscribedApps(data); + if (apps.length === 0) { + io.print('\nWARNING: No apps are subscribed to this WABA!'); + io.print(" This means webhooks won't be delivered to your app."); + } else { + const names = apps.flatMap((app) => (app.name === undefined ? [] : [app.name])); + io.print(`\nFound ${apps.length} subscribed app(s) to the WABA: ${names.join(', ')}`); + for (const app of apps) { + io.print('\n App Details:'); + for (const [key, value] of Object.entries(app.fields)) io.print(` ${key}: ${pythonShow(value)}`); + } + } + } + } catch (error) { + printCallError(io, error, context.accessToken); + } +} + +export async function showPhoneNumbers(io: Io, context: MetaContext): Promise { + heading(io, 'LISTING PHONE NUMBERS'); + try { + const data = await getPhoneNumbers(context); + io.print(`\nSuccessfully retrieved phone numbers for WABA: ${context.wabaId}`); + if (isRecord(data) && Object.hasOwn(data, 'data') && Array.isArray(data.data)) { + io.print(`\nFound ${data.data.length} phone number(s):`); + for (const entry of data.data) { + const phone = isRecord(entry) ? entry : {}; + io.print(`\n Phone Number ID: ${shown(phone, 'id', 'None')}`); + io.print(` Display Name: ${shown(phone, 'display_phone_number', 'N/A')}`); + io.print(` Verified Name: ${shown(phone, 'verified_name', 'N/A')}`); + io.print(` Quality Rating: ${shown(phone, 'quality_rating', 'N/A')}`); + io.print(` Status: ${shown(phone, 'code_verification_status', 'N/A')}`); + } + } else { + io.print('\nNo phone numbers found for this WABA'); + } + } catch (error) { + printCallError(io, error, context.accessToken); + } +} + +/** Python's `input(...).strip().lower() == "yes"`. */ +async function confirmed(io: Io, prompt: string): Promise { + const answer = await io.ask(prompt); + return (answer ?? '').trim().toLowerCase() === 'yes'; +} + +/** Subscribe the token's app. Returns whether Meta accepted it, so the caller can show the new list. */ +export async function subscribe(io: Io, context: MetaContext): Promise { + heading(io, 'SUBSCRIBING WABA TO APP'); + io.print('\nThis will subscribe your WABA to the app associated with your access token.'); + io.print(" Webhooks from this WABA will be sent to this app's webhook URL."); + if (!(await confirmed(io, '\n Do you want to proceed? (yes/no): '))) { + io.print(' Subscription cancelled.'); + return false; + } + try { + const data = await subscribeTokenApp(context); + io.print('\nSuccessfully subscribed WABA to app!'); + if (isRecord(data) && truthy(data.success)) io.print(' Status: Subscription active'); + return true; + } catch (error) { + printCallError(io, error, context.accessToken); + return false; + } +} + +/** + * Unsubscribe the token's app, in the six steps Python printed. Nothing is changed unless the token's app (matched by ID) is among + * the subscribed apps AND the operator types `yes`. Returns whether Meta accepted the removal. + */ +export async function unsubscribe(io: Io, context: MetaContext): Promise { + heading(io, 'UNSUBSCRIBING WABA FROM APP'); + + io.print("\n→ Step 1: Identifying your access token's app..."); + let tokenApp; + try { + tokenApp = readTokenApp(await debugToken(context)); + } catch (error) { + io.print(` ERROR: Failed to get token details: ${withoutToken(error instanceof Error ? error.message : String(error), context.accessToken)}`); + return false; + } + if (tokenApp === undefined) { + io.print(' ERROR: Unable to debug access token.'); + return false; + } + io.print(` Your access token is associated with: ${tokenApp.name ?? 'Unknown'} (ID: ${tokenApp.id ?? 'Unknown'})`); + + io.print('\n→ Step 2: Getting WABA details...'); + let wabaName = `WABA ${context.wabaId}`; + try { + const answer = await getWabaName(context); + if (isRecord(answer)) wabaName = Object.hasOwn(answer, 'name') ? pythonShow(answer.name) : wabaName; + io.print(` WABA Name: ${wabaName}`); + } catch (error) { + io.print(` Warning: Could not get WABA name: ${withoutToken(error instanceof Error ? error.message : String(error), context.accessToken)}`); + wabaName = `WABA ${context.wabaId}`; + } + + io.print('\n→ Step 3: Checking currently subscribed apps...'); + let subscribed; + try { + subscribed = readSubscribedApps(await getSubscribedApps(context)); + } catch (error) { + io.print(` ERROR: Failed to get subscribed apps: ${withoutToken(error instanceof Error ? error.message : String(error), context.accessToken)}`); + return false; + } + const plan = planUnsubscribe(tokenApp, subscribed); + if (plan.kind === 'nothing_subscribed') { + io.print(' No apps are currently subscribed to this WABA.'); + io.print('\n Nothing to unsubscribe. Exiting.'); + return false; + } + const subscribedNames = subscribed.flatMap((app) => (app.name === undefined ? [] : [app.name])); + io.print(` Currently subscribed apps: ${subscribedNames.length > 0 ? subscribedNames.join(', ') : 'None found'}`); + + io.print('\n→ Step 4: Verifying subscription match...'); + if (plan.kind === 'token_app_not_subscribed') { + io.print("\n WARNING: Your access token's app is NOT in the subscribed list!"); + io.print('\n Details:'); + io.print(` * Your token is for: ${tokenApp.name ?? 'Unknown'} (ID: ${tokenApp.id ?? 'Unknown'})`); + io.print(` * WABA '${wabaName}' is subscribed to: ${subscribedNames.join(', ')}`); + io.print('\n Cannot proceed with unsubscription.'); + io.print('\n → Solution: Change your access token to one bound to an app in the subscribed list.'); + io.print(' Apps you need a token for:'); + for (const name of subscribedNames) io.print(` - ${name}`); + return false; + } + + const tokenAppName = tokenApp.name ?? 'Unknown'; + io.print(`\n Match found: ${tokenAppName} app is subscribed to ${wabaName} WABA`); + io.print('\n→ Step 5: Confirming unsubscription...'); + io.print(`\n WARNING: This will unsubscribe '${tokenAppName}' from '${wabaName}'`); + io.print(` * Webhooks will STOP being sent to ${tokenAppName}'s webhook URL`); + const otherNames = plan.others.flatMap((app) => (app.name === undefined ? [] : [app.name])); + io.print(` * Other subscribed apps will remain unaffected: ${otherNames.join(', ')}`); + + if (!(await confirmed(io, '\n Are you sure you want to proceed? (yes/no): '))) { + io.print(' Unsubscription cancelled.'); + return false; + } + + io.print('\n→ Step 6: Performing unsubscription...'); + try { + const data = await unsubscribeTokenApp(context); + io.print(`\n Successfully unsubscribed '${tokenAppName}' from '${wabaName}'!`); + if (isRecord(data) && truthy(data.success)) io.print(' Status: Subscription removed'); + return true; + } catch (error) { + printCallError(io, error, context.accessToken, ' '); + return false; + } +} + +export function showLines(io: Io, lines: readonly string[]): void { + for (const line of lines) io.print(line); +} + +export async function showPrerequisiteKnowledge(io: Io): Promise { + showLines(io, PREREQUISITE_KNOWLEDGE_LINES); + await io.ask('\nPress Enter to return to menu...'); +} + +export async function showMiscellaneousInfo(io: Io): Promise { + showLines(io, MISCELLANEOUS_INFO_LINES); + await io.ask('\nPress Enter to return to menu...'); +} + +// --------------------------------------------------------------------------------------------------------------------- +// The menu +// --------------------------------------------------------------------------------------------------------------------- + +/** The WABA's and the token's app's names for the box above the menu. A failed call leaves `Unknown`, as in Python. */ +export async function currentContext(context: MetaContext): Promise<{ wabaName: string; appName: string }> { + let wabaName = 'Unknown'; + let appName = 'Unknown'; + try { + const answer = await getWabaName(context); + if (isRecord(answer)) wabaName = Object.hasOwn(answer, 'name') ? pythonShow(answer.name) : 'Unknown (probably invalid WABA ID)'; + } catch { + // keep "Unknown" + } + try { + const answer = await debugToken(context); + if (isRecord(answer) && isRecord(answer.data)) { + appName = Object.hasOwn(answer.data, 'application') ? pythonShow(answer.data.application) : 'Unknown (probably invalid token)'; + } + } catch { + // keep "Unknown" + } + return { wabaName, appName }; +} + +const CHOICES = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; + +/** Show the menu and return the chosen option. End of input is a choice to quit (`9`). */ +export async function askMenuChoice(io: Io, context: MetaContext): Promise { + const { wabaName, appName } = await currentContext(context); + io.print(`\n${RULE}`); + io.print('CURRENT CONTEXT'); + io.print(RULE); + io.print(` WABA: ${wabaName}`); + io.print(` App: ${appName}`); + io.print(RULE); + io.print('AVAILABLE ACTIONS'); + io.print(RULE); + io.print('\n0. 📚 Show prerequisite knowledge (understand the big picture)'); + io.print('1. View WABA details'); + io.print('2. View access token details for debugging'); + io.print('3. Check apps subscribed to the WABA'); + io.print('4. List phone numbers registered to the WABA'); + io.print('5. Subscribe WABA to app (enable webhooks)'); + io.print('6. Unsubscribe WABA from app (disable webhooks)'); + io.print('7. Run all checks (view everything)'); + io.print("8. Miscellaneous info (e.g., what is 'WA DevX Webhook Events 1P App' in option 3's list?)"); + io.print('9. Exit'); + + for (;;) { + const answer = await io.ask('\nEnter your choice (0-9): '); + if (answer === null) { + io.print('\n\nInterrupted by user. Exiting...'); + return '9'; + } + const choice = answer.trim(); + if (CHOICES.includes(choice)) return choice; + io.print(' Invalid choice. Please enter a number between 0 and 9.'); + } +} + +export interface ScriptOptions { + /** Usually `process.env` (after `.env` was loaded into it). */ + env: Record; + /** Whether a `.env` file was found; only changes what the script says when nothing is set. */ + envFileFound: boolean; + /** Only tests pass it. */ + fetch?: FetchLike; +} + +const goodbye = (io: Io) => { + io.print(`\n${RULE}`); + io.print('Done! Exiting...'); + io.print(RULE); +}; + +/** The whole script. Returns when the operator quits. */ +export async function runScript(io: Io, options: ScriptOptions): Promise { + io.print(RULE); + io.print('WhatsApp Business Account Subscription Manager'); + io.print(RULE); + + let accessToken = options.env.META_ACCESS_TOKEN_FROM_SYS_USER ?? ''; + let wabaId = options.env.META_MESSAGING_ACCOUNT_ID ?? ''; + const version = options.env.META_API_VERSION || 'v26.0'; + + if (!options.envFileFound && accessToken === '' && wabaId === '') { + io.print('\n No .env file found in the current directory'); + io.print(' You can either:'); + io.print(' 1. Create a .env file with META_ACCESS_TOKEN_FROM_SYS_USER and META_MESSAGING_ACCOUNT_ID'); + io.print(" 2. Enter the values manually now (they won't be saved)"); + if (!(await confirmed(io, '\n Enter values manually? (yes/no): '))) { + io.print('\n Please create a .env file and try again.'); + io.print('\n Example .env file:'); + io.print(' META_ACCESS_TOKEN_FROM_SYS_USER=your_token_here'); + io.print(' META_MESSAGING_ACCOUNT_ID=your_id_here'); + return; + } + } + + if (accessToken === '') { + io.print('\n→ Access Token Configuration'); + io.print(' You can find your token at:'); + io.print(' 1. Go to business.facebook.com → Business Settings → System Users'); + io.print(' 2. Select your System User → Generate New Token'); + io.print(' 3. Select your app and required permissions'); + io.print(' 4. Copy the generated token'); + accessToken = ((await io.askHidden('\n Enter your META_ACCESS_TOKEN_FROM_SYS_USER (typing is hidden): ')) ?? '').trim(); + if (accessToken === '') { + io.print('\n ERROR: Access token is required. Exiting...'); + return; + } + } + + if (wabaId === '') { + io.print('\n→ WABA ID Configuration'); + io.print(' Get it from https://developers.facebook.com/apps/ → your app → WhatsApp → API Setup'); + io.print(" Look for 'WhatsApp Business Account ID' (called 'Messaging account ID' in Meta's newer docs)."); + io.print(" Step-by-step: the last bullet of '7. USEFUL RESOURCES' in this script (menu option 0)."); + io.print(' Tip: save it as META_MESSAGING_ACCOUNT_ID in .env so you are not asked next time.'); + wabaId = ((await io.ask('\n Enter your WABA ID: ')) ?? '').trim(); + if (wabaId === '') { + io.print('\n ERROR: WABA ID is required. Exiting...'); + return; + } + } + + const context: MetaContext = { accessToken, wabaId, version, ...(options.fetch ? { fetch: options.fetch } : {}) }; + + io.print('\nConfiguration:'); + io.print(` WABA ID: ${wabaId}`); + io.print(` Access Token: set (${[...accessToken].length} characters, never shown)`); + + for (;;) { + const choice = await askMenuChoice(io, context); + + if (choice === '0') { + await showPrerequisiteKnowledge(io); + } else if (choice === '1') { + await showWabaDetails(io, context); + } else if (choice === '2') { + await showTokenDetails(io, context); + } else if (choice === '3') { + await showSubscribedApps(io, context); + } else if (choice === '4') { + await showPhoneNumbers(io, context); + } else if (choice === '5') { + if (await subscribe(io, context)) { + io.print('\n → Verifying subscription...'); + await showSubscribedApps(io, context); + } + } else if (choice === '6') { + if (await unsubscribe(io, context)) { + io.print('\n → Verifying unsubscription...'); + await showSubscribedApps(io, context); + } + } else if (choice === '7') { + await showWabaDetails(io, context); + await showTokenDetails(io, context); + await showSubscribedApps(io, context); + await showPhoneNumbers(io, context); + } else if (choice === '8') { + await showMiscellaneousInfo(io); + } else if (choice === '9') { + goodbye(io); + return; + } + + if (choice !== '8') { + const next = await io.ask("\n Press Enter to return to menu (or 'q' to quit): "); + if (next === null || next.trim().toLowerCase() === 'q') { + goodbye(io); + return; + } + } + } +} + +// Run only when started directly (`tsx scripts/checkMetaSubscriptions.ts`), not when a test imports this file +if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) { + const loaded = loadDotenv({ quiet: true }); + const io = createTerminalIo(); + try { + await runScript(io, { env: process.env, envFileFound: loaded.error === undefined }); + } finally { + io.close(); + } +} diff --git a/apps/whatsapp/scripts/metaSubscriptions.ts b/apps/whatsapp/scripts/metaSubscriptions.ts new file mode 100644 index 00000000..29765c00 --- /dev/null +++ b/apps/whatsapp/scripts/metaSubscriptions.ts @@ -0,0 +1,230 @@ +/** + * The Meta calls and the readers of Meta's answers behind the operator script `checkMetaSubscriptions.ts`. + * + * Python counterpart: the functions of `legacy/whatsapp/scripts/check_meta_subscriptions.py` that talk to Meta + * (`get_waba_details`, `debug_access_token`, `check_subscribed_apps`, `list_phone_numbers`, `subscribe_waba`, + * `unsubscribe_waba`). Python mixed three jobs in each function: asking Meta, reading the answer, and printing. Here they are + * split, so the reading and the safety rule can be tested with a fake `fetch` and no keyboard or network, and the printing + * lives in the script file. + * + * A web page called a Messaging account (WABA, WhatsApp Business Account) can be "subscribed" to Meta developer apps; Meta sends + * a webhook to every subscribed app. This is how an operator checks which apps those are, and changes it. + * https://developers.facebook.com/docs/whatsapp/embedded-signup/webhooks + * + * Differences from Python: + * - Every call has a 20 second limit. Python's `requests` calls had none, so a stalled connection hung the script. + * - A failed call is an error value (`MetaCallError`) that carries Meta's status and error text, instead of two printed lines + * and a `None`. The caller decides what to print. + * - The safety check before an unsubscribe compares the token's app ID with the subscribed apps' IDs. Python compared their + * NAMES, so two apps with the same name could let the script remove the wrong one. IDs are in both answers. + * - The access token never leaves the `Authorization` header, except in the one place Meta forces it into a URL (see + * `debugToken`), and it is never printed or put in an error. Python printed the token's first 20 and last 10 characters. + */ + +import { pythonRepr } from '../src/utils/pythonRepr'; + +export type FetchLike = typeof fetch; + +/** Which Graph API calls the script makes, and where. `version` is `META_API_VERSION`. */ +export interface MetaContext { + accessToken: string; + /** The Messaging account (WABA) ID, `META_MESSAGING_ACCOUNT_ID`. */ + wabaId: string; + version: string; + /** Only tests pass it. */ + fetch?: FetchLike; +} + +const GRAPH = 'https://graph.facebook.com'; +const TIMEOUT_MS = 20_000; + +/** A call to Meta that failed. The message never contains the access token. */ +export class MetaCallError extends Error { + override readonly name = 'MetaCallError'; + /** Meta's HTTP status, or `undefined` for a network fault or a timeout. */ + readonly status: number | undefined; + /** Meta's reply body, as text, with the access token removed and cut to 2000 characters. */ + readonly detail: string | undefined; + + constructor(message: string, status?: number, detail?: string, options?: { cause?: unknown }) { + super(message, options); + this.status = status; + this.detail = detail; + } +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** Replace every occurrence of the token in `text`, so no message can ever echo it. */ +export function withoutToken(text: string, accessToken: string): string { + return accessToken === '' ? text : text.split(accessToken).join('***'); +} + +async function call( + context: MetaContext, + method: 'GET' | 'POST' | 'DELETE', + path: string, + query: Record = {}, +): Promise { + const url = new URL(`${GRAPH}/${context.version}/${path}`); + for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value); + const doFetch = context.fetch ?? fetch; + + let response: Response; + try { + response = await doFetch(url, { + method, + headers: { Authorization: `Bearer ${context.accessToken}` }, + // A redirect would carry the Authorization header to another address + redirect: 'manual', + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + } catch (error) { + const timedOut = error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError'); + throw new MetaCallError(timedOut ? `No answer from Meta within ${TIMEOUT_MS / 1000} s` : 'Could not reach Meta', undefined, undefined, { + cause: error, + }); + } + + const text = await response.text().catch(() => ''); + if (!response.ok) { + throw new MetaCallError( + `Meta answered HTTP ${response.status}`, + response.status, + withoutToken([...text].slice(0, 2000).join(''), context.accessToken), + ); + } + try { + return JSON.parse(text) as unknown; + } catch (error) { + throw new MetaCallError('Meta answered with something that is not JSON', response.status, undefined, { cause: error }); + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// Readers: what Meta's answers mean. Pure, so each is tested with a canned answer. +// --------------------------------------------------------------------------------------------------------------------- + +/** One app subscribed to the Messaging account (an entry of `data`). */ +export interface SubscribedApp { + id: string | undefined; + /** + * The app's name, `Unknown App` when Meta sent the entry without one, and `undefined` when the entry has no + * `whatsapp_business_api_data` at all (Python listed names only for entries that have it). + */ + name: string | undefined; + /** Every field Meta sent for the entry, for the detail screen. */ + fields: Record; +} + +/** Text for a value the way Python's `str()` shows it: a string as it is, anything else as its repr (`True`, `None`, `{'a': 1}`). */ +export function pythonShow(value: unknown): string { + return typeof value === 'string' ? value : pythonRepr(value); +} + +/** + * The apps in a `GET //subscribed_apps` answer. An entry without `whatsapp_business_api_data` is kept (with no name or + * id) rather than dropped, as Python counted every entry in `data` but only named those with the key. + */ +export function readSubscribedApps(answer: unknown): SubscribedApp[] { + if (!isRecord(answer) || !Array.isArray(answer.data)) return []; + return answer.data.map((entry): SubscribedApp => { + const inner = isRecord(entry) && isRecord(entry.whatsapp_business_api_data) ? entry.whatsapp_business_api_data : undefined; + const fields = isRecord(entry) ? entry : {}; + return { + id: typeof inner?.id === 'string' ? inner.id : typeof inner?.id === 'number' ? String(inner.id) : undefined, + name: inner === undefined ? undefined : Object.hasOwn(inner, 'name') ? pythonShow(inner.name) : 'Unknown App', + fields, + }; + }); +} + +/** The app an access token belongs to, from a `GET /debug_token` answer. */ +export interface TokenApp { + /** Meta's `data.app_id`. */ + id: string | undefined; + /** Meta's `data.application`, the app's name. */ + name: string | undefined; +} + +export function readTokenApp(answer: unknown): TokenApp | undefined { + if (!isRecord(answer) || !isRecord(answer.data)) return undefined; + const { app_id: appId, application } = answer.data; + return { + id: typeof appId === 'string' ? appId : typeof appId === 'number' ? String(appId) : undefined, + name: typeof application === 'string' ? application : undefined, + }; +} + +/** What `planUnsubscribe` decided. */ +export type UnsubscribePlan = + /** Nothing is subscribed, so there is nothing to remove. */ + | { kind: 'nothing_subscribed' } + /** The token's app is not among the subscribed ones. The script refuses: the DELETE would remove a different app, or none. */ + | { kind: 'token_app_not_subscribed'; tokenApp: TokenApp; subscribed: SubscribedApp[] } + /** The token's app is subscribed. This is the only app a DELETE with this token removes. */ + | { kind: 'ready'; tokenApp: TokenApp; others: SubscribedApp[] }; + +/** + * Decide whether the unsubscribe may go ahead. + * + * `DELETE //subscribed_apps` removes the app the access token belongs to, and no other (the token names the app, the call + * does not). The script shows the operator what will happen first, and refuses when the token's app is not subscribed, so a + * mistaken token can never be taken for the one the operator meant. + * + * Apps are matched by ID. A name is not unique (two apps can share one), and the ID is in both answers. When the token's ID + * cannot be read, nothing matches, so the script refuses. + */ +export function planUnsubscribe(tokenApp: TokenApp, subscribed: SubscribedApp[]): UnsubscribePlan { + if (subscribed.length === 0) return { kind: 'nothing_subscribed' }; + const ours = tokenApp.id === undefined ? undefined : subscribed.find((app) => app.id === tokenApp.id); + if (!ours) return { kind: 'token_app_not_subscribed', tokenApp, subscribed }; + return { kind: 'ready', tokenApp, others: subscribed.filter((app) => app !== ours) }; +} + +// --------------------------------------------------------------------------------------------------------------------- +// Calls +// --------------------------------------------------------------------------------------------------------------------- + +/** `GET /`: its name, time zone and review status. */ +export function getWabaDetails(context: MetaContext): Promise { + return call(context, 'GET', context.wabaId, { fields: 'id,name,timezone_id,message_template_namespace,account_review_status' }); +} + +/** Just the account's name, for the context box and the unsubscribe screen. */ +export function getWabaName(context: MetaContext): Promise { + return call(context, 'GET', context.wabaId, { fields: 'name' }); +} + +/** + * `GET /debug_token`: which app a token belongs to, what it may do and when it expires. + * + * The token that does the asking goes in the header, as everywhere. `input_token`, the token being looked at, is a GET parameter + * on this endpoint (a POST is refused), so the token does appear in this one URL. That is Meta's design for the endpoint; the + * URL is never printed or logged here. + */ +export function debugToken(context: MetaContext): Promise { + return call(context, 'GET', 'debug_token', { input_token: context.accessToken }); +} + +/** `GET //subscribed_apps`. */ +export function getSubscribedApps(context: MetaContext): Promise { + return call(context, 'GET', `${context.wabaId}/subscribed_apps`); +} + +/** `GET //phone_numbers`. */ +export function getPhoneNumbers(context: MetaContext): Promise { + return call(context, 'GET', `${context.wabaId}/phone_numbers`); +} + +/** `POST //subscribed_apps`: subscribe the token's app. CHANGES META'S STATE. Only after the operator confirms. */ +export function subscribeTokenApp(context: MetaContext): Promise { + return call(context, 'POST', `${context.wabaId}/subscribed_apps`); +} + +/** `DELETE //subscribed_apps`: unsubscribe the token's app. CHANGES META'S STATE. Only after `planUnsubscribe` says ready and the operator confirms. */ +export function unsubscribeTokenApp(context: MetaContext): Promise { + return call(context, 'DELETE', `${context.wabaId}/subscribed_apps`); +} diff --git a/apps/whatsapp/scripts/metaSubscriptionsText.ts b/apps/whatsapp/scripts/metaSubscriptionsText.ts new file mode 100644 index 00000000..362f5461 --- /dev/null +++ b/apps/whatsapp/scripts/metaSubscriptionsText.ts @@ -0,0 +1,176 @@ +/** + * The two long text screens of the operator script: what the Meta assets are and how they connect, and a side note on an app + * that appears in the subscribed-apps list. + * + * Python counterpart: `show_prerequisite_knowledge` and `show_miscellaneous_info` in + * `legacy/whatsapp/scripts/check_meta_subscriptions.py`. The lines are Python's own output, one array entry per printed line + * (an empty entry is a blank line), so the two screens read exactly as before. The one change: the example callback URLs end in + * `/whatsapp/v3`, the path this service answers on (the Python service answered `/whatsapp/v2`). + * + * `tests/metaSubscriptions.test.ts` compares both arrays with what the Python script printed (recorded by + * `tests/fixtures/generate_meta_script_oracle.py`), so an accidental edit here fails a test. + */ + +/** Menu option 0. Python's last prompt for it: `\nPress Enter to return to menu...`. */ +export const PREREQUISITE_KNOWLEDGE_LINES: readonly string[] = [ + "", + "============================================================", + "PREREQUISITE KNOWLEDGE: Meta WhatsApp Business Architecture", + "============================================================", + "", + "📚 THE BIG PICTURE", + "", + "1. HIERARCHY OF META ASSETS:", + " --------------------------------------------------------", + " Meta Business Manager (business.facebook.com)", + " ↓", + " WhatsApp Business Account (WABA)", + " ↓", + " Phone Numbers (up to 20 per WABA)", + "", + " Developer App (developers.facebook.com)", + " ↓", + " App Secret + Access Token", + " ↓", + " Webhook URL (receives messages)", + "", + "2. HOW THEY CONNECT:", + " --------------------------------------------------------", + " • A WABA can be SUBSCRIBED to multiple Developer Apps", + " • When someone messages your WhatsApp number:", + " 1. Meta finds which WABA owns that phone number", + " 2. Meta checks which Developer Apps are subscribed to that WABA", + " 3. Meta sends webhooks to ALL subscribed apps' webhook URLs", + " 4. Meta signs each webhook with the app's App Secret", + "", + "3. KEY CONCEPTS:", + " --------------------------------------------------------", + " • WABA (WhatsApp Business Account):", + " - Container for your WhatsApp phone numbers", + " - Managed in Meta Business Manager", + " - Can have multiple phone numbers", + "", + " • Developer App (e.g., 'Ansari - Test'):", + " - Created at developers.facebook.com", + " - Has unique App ID and App Secret", + " - Needs to be SUBSCRIBED to a WABA to receive webhooks", + "", + " • Access Token:", + " - Generated for a specific Developer App", + " - Used to authenticate API calls", + " - Token is tied to ONE app only (cannot be shared)", + "", + " • App Secret:", + " - Secret key unique to each Developer App", + " - Used by Meta to sign webhook payloads", + " - Your server verifies signatures to ensure authenticity", + "", + " • Subscription:", + " - Links a WABA to a Developer App", + " - Required for webhooks to be delivered", + " - One WABA can subscribe to multiple apps", + "", + "4. COMMON SETUP (3 ENVIRONMENTS):", + " --------------------------------------------------------", + " • Test/Local Environment:", + " - Developer App: 'Ansari - Test'", + " - WABA: 'Test WhatsApp Business Account'", + " - Phone Number: Test number (90-day expiry)", + " - Webhook: zrok tunnel (e.g., https://xxx.share.zrok.io)", + "", + " • Staging Environment:", + " - Developer App: 'Ansari - Staging'", + " - WABA: Also 'Test WhatsApp Business Account'", + " - Phone Number: Same Test number (nuisance though, as sending a msg to it hits both apps)", + " - Webhook: Staging server URL", + "", + " • Production Environment:", + " - Developer App: 'Ansari' (production)", + " - WABA: Production WABA", + " - Phone Number: Official business phone", + " - Webhook: Production server URL", + "", + "5. WHY THIS MATTERS:", + " --------------------------------------------------------", + " • Access tokens are APP-SPECIFIC", + " → You need separate tokens for test/staging/production", + "", + " • Subscriptions control webhook delivery", + " → If not subscribed, you won't receive messages", + "", + " • App Secrets must match for signature verification", + " → Wrong secret = webhooks rejected by your server", + "", + " • Multiple apps can subscribe to the same WABA", + " → Useful for routing to different environments", + "", + "6. VISUAL EXAMPLE:", + " --------------------------------------------------------", + " WABA: 'Test WhatsApp Business Account'", + " ├─ Phone: +1234567890 (test)", + " └─ Subscribed to:", + " ├─ App: 'Ansari - Test'", + " │ ├─ Access Token: EAAMf...", + " │ ├─ App Secret: abc123...", + " │ └─ Webhook: https://xxx.share.zrok.io/whatsapp/v3", + " └─ App: 'Ansari - Staging'", + " ├─ Access Token: EAAMf...", + " ├─ App Secret: def456...", + " └─ Webhook: https://staging-api.ansari.chat/whatsapp/v3", + "", + " When user sends message to +1234567890:", + " → Both 'Ansari - Test' AND 'Ansari - Staging' receive webhooks!", + "", + "7. USEFUL RESOURCES:", + " --------------------------------------------------------", + " • Debug Access Token:", + " https://developers.facebook.com/tools/debug/accesstoken/", + " • Meta Business Manager:", + " https://business.facebook.com/", + " • Developer Apps:", + " https://developers.facebook.com/apps/", + " • WhatsApp API Documentation:", + " https://developers.facebook.com/docs/whatsapp/", + " • NEXT STEP - get your WABA ID (every menu choice from 1 to 7 needs it):", + " 1. Open https://developers.facebook.com/apps/ and click the app your access token belongs to", + " (e.g. 'Ansari - Staging'; the 'CURRENT CONTEXT' box in the menu shows which app that is).", + " 2. In the app's left-hand menu open the 'WhatsApp' use case, then 'Step 1. Try it out'.", + " 3. Under the 'Claim a WhatsApp test number' section, copy the 'Messaging account ID'.", + " (Meta's new name for the WhatsApp Business Account ID; it is the value of META_MESSAGING_ACCOUNT_ID.)", + " It sits near the phone number ID in that panel.", + " 4. Check it is the right one: the phone number selected there must be the number whose ID is in", + " META_BUSINESS_PHONE_NUMBER_ID (a different number can belong to a different WABA).", + " 5. Put it in your .env as META_MESSAGING_ACCOUNT_ID=, or paste it when this script asks for it.", + " Want the Messaging account ID of the PRODUCTION number instead of the test number?", + " On the same app page, open 'Step 2. Production setup' → 'Register your WhatsApp phone number';", + " the Messaging account ID is shown there under 'Ansari Chat' (the production account).", + " Use the production app's token for it (e.g. 'Ansari'), and re-check step 4 for the production number ID.", + " Alternative (from memory, not checked against Meta's docs): https://business.facebook.com/latest/settings", + " → Accounts → WhatsApp accounts → select the account → its ID is in the details panel.", + " Menu names change; if one is missing, look for 'WhatsApp Business Account ID' on those pages.", + "", + "============================================================", + "NEXT STEP: copy your WABA ID as described in section 7, then run option 3 (subscribed apps).", +]; + +/** Menu option 8. Python's last prompt for it: `\nPress Enter to return to menu...`. */ +export const MISCELLANEOUS_INFO_LINES: readonly string[] = [ + "", + "============================================================", + "MISCELLANEOUS INFO", + "============================================================", + "", + "1. 'WA DevX Webhook Events 1P App' shows up in option 3 (apps subscribed to the WABA). What is it?", + " It is not one of our apps, and we found no Meta documentation that names it. Our best guess (UNVERIFIED):", + " it is a Meta-owned app that Meta adds to WhatsApp accounts created through its dashboard test setup.", + " The name reads as 'WhatsApp developer experience' + '1P' (first-party, i.e. Meta's own app).", + " Meta's docs say a WABA sends webhooks to every subscribed app, so an extra subscriber should not stop", + " ours from receiving them. The real question is whether OUR app (the one in 'CURRENT CONTEXT') is listed.", + " If it is the only app listed, our app is NOT subscribed: use option 5 (it changes Meta's state).", + " The 'link' field (facebook.com/games/?app_id=...) is just Meta's generic URL format for any app.", + " Only source found, a single user's claim (it also guesses the app may intercept messages, unproven):", + " https://www.reddit.com/r/MetaAppDevelopers/comments/1qi2jqa/whatsapp_cloud_api_webhook_works_on_new_business", + " Subscribed-apps API: https://developers.facebook.com/docs/whatsapp/embedded-signup/webhooks", + "", + "============================================================", +]; diff --git a/apps/whatsapp/scripts/terminalIo.ts b/apps/whatsapp/scripts/terminalIo.ts new file mode 100644 index 00000000..42c652a9 --- /dev/null +++ b/apps/whatsapp/scripts/terminalIo.ts @@ -0,0 +1,84 @@ +/** + * The keyboard and screen of the operator script, behind one small interface. + * + * Python counterpart: `input()`, `getpass.getpass()` and `print()`. The script's flows talk only to `Io`, so a test drives them with + * scripted answers (see `tests/helpers/scriptedIo.ts`) and no terminal. + * + * Differences from Python: + * - `null` means "no more input" (the keyboard was closed with Ctrl+D, Ctrl+C, or a pipe ended). Python's `input()` raised + * `EOFError` and ended with a traceback; the script treats `null` as "quit". + * - Lines typed ahead of a question are kept for it. `readline`'s own `question()` loses a line that arrives before the question is + * asked (checked on Node 22: a piped-in second answer never reached its question). + */ +import { createInterface } from 'node:readline'; +import { Writable } from 'node:stream'; + +export interface Io { + /** Write `text` and a line break. */ + print(text: string): void; + /** Show `prompt` (no line break after it) and wait for a line. `null` when there is no more input. */ + ask(prompt: string): Promise; + /** Like `ask`, but what is typed is not shown (Python: `getpass.getpass`). */ + askHidden(prompt: string): Promise; +} + +/** An `Io` on real streams. Call `close()` when the script ends, or the keyboard keeps the process alive. */ +export function createTerminalIo( + input: NodeJS.ReadableStream & { isTTY?: boolean } = process.stdin, + output: NodeJS.WritableStream = process.stdout, +): Io & { close(): void } { + let hidden = false; + // readline echoes what is typed by writing to its output; this one stays silent while a hidden answer is being typed + const gated = new Writable({ + write(chunk: Buffer, _encoding, callback) { + if (!hidden) output.write(chunk); + callback(); + }, + }); + const reader = createInterface({ input, output: gated, terminal: input.isTTY === true }); + + const typedAhead: string[] = []; + const waiting: Array<(line: string | null) => void> = []; + let ended = false; + + reader.on('line', (line) => { + const next = waiting.shift(); + if (next) next(line); + else typedAhead.push(line); + }); + reader.on('close', () => { + ended = true; + for (const next of waiting.splice(0)) next(null); + }); + // Ctrl+C needs no code here: with no `SIGINT` listener, readline closes itself, which gives a question in progress `null` + // (tests/terminalIo.test.ts sends a real Ctrl+C keystroke). Adding a listener would take that default away. + + function nextLine(): Promise { + const line = typedAhead.shift(); + if (line !== undefined) return Promise.resolve(line); + if (ended) return Promise.resolve(null); + return new Promise((resolve) => waiting.push(resolve)); + } + + return { + print: (text) => { + output.write(`${text}\n`); + }, + ask: (prompt) => { + output.write(prompt); + return nextLine(); + }, + askHidden: async (prompt) => { + output.write(prompt); + hidden = true; + try { + return await nextLine(); + } finally { + hidden = false; + // The Enter that ended the answer was not echoed, so end the prompt's line ourselves + output.write('\n'); + } + }, + close: () => reader.close(), + }; +} diff --git a/apps/whatsapp/tests/fixtures/generate_meta_script_oracle.py b/apps/whatsapp/tests/fixtures/generate_meta_script_oracle.py new file mode 100644 index 00000000..be9eea7d --- /dev/null +++ b/apps/whatsapp/tests/fixtures/generate_meta_script_oracle.py @@ -0,0 +1,275 @@ +"""Regenerate `metaScriptOracle.ts` from the legacy operator script (issue #358, plan phase 7). + +Why this exists: the Python script `legacy/whatsapp/scripts/check_meta_subscriptions.py` has no tests, and what it PRINTS is the +whole product (an operator reads it to decide whether to change Meta's state). So that "the TypeScript script says the same thing" +is checked rather than assumed, this runs the legacy functions with a fake `requests` and scripted answers to `input()`, records +every screen and every call made, and writes them as data the Vitest tests compare with. + +Run from the repo root, with a Python that has `requests` and `python-dotenv` (the legacy service's environment): + + cd legacy/whatsapp + uv run python ../../apps/whatsapp/tests/fixtures/generate_meta_script_oracle.py ../../apps/whatsapp/tests/fixtures/metaScriptOracle.ts + +It never talks to the network. Delete this file together with `legacy/whatsapp`; `metaScriptOracle.ts` stays valid because it is +plain data. + +The recorded screens are Python's own output. Where the TypeScript script deliberately differs, the tests say so and name the +difference; the table `EXPECTED_DIFFERENCES` at the end lists them so the data and the tests cannot drift apart silently. +""" + +import builtins +import contextlib +import importlib.util +import io +import json +import os +import sys +import time + +SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "..", "legacy", "whatsapp", "scripts", "check_meta_subscriptions.py") + +os.environ["TZ"] = "UTC" +if hasattr(time, "tzset"): + time.tzset() + +spec = importlib.util.spec_from_file_location("legacy_script", os.path.abspath(SCRIPT)) +mod = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mod) + +TOKEN = "SECRET-TOKEN-VALUE-0123456789" +mod.ACCESS_TOKEN = TOKEN +mod.WABA_ID = "111" + + +class Resp: + def __init__(self, status, body, raw=None): + self.status_code = status + self._body = body + self.text = raw if raw is not None else json.dumps(body) + + def json(self): + if self._body is _NOT_JSON: + raise ValueError("not json") + return self._body + + def raise_for_status(self): + if self.status_code >= 400: + import requests + + error = requests.exceptions.HTTPError(f"{self.status_code} Client Error: for url: x") + error.response = self + raise error + + +_NOT_JSON = object() + + +def run(fn, answers, inputs=()): + """Run one legacy function. Returns the lines it printed, the prompts it asked and the calls it made.""" + calls = [] + prompts = [] + remaining = list(answers) + + class FakeRequests: + import requests as _real + + exceptions = _real.exceptions + + @staticmethod + def _do(method, url, headers=None, params=None): + query = "&".join(f"{k}={v}" for k, v in (params or {}).items()) + path = url.replace("https://graph.facebook.com/v26.0", "") + calls.append({"method": method, "path": path, "query": query, "bearer": (headers or {}).get("Authorization") == f"Bearer {TOKEN}"}) + answer = remaining.pop(0) + if isinstance(answer, Exception): + raise answer + return answer + + FakeRequests.get = staticmethod(lambda url, headers=None, params=None: FakeRequests._do("GET", url, headers, params)) + FakeRequests.post = staticmethod(lambda url, headers=None, params=None: FakeRequests._do("POST", url, headers, params)) + FakeRequests.delete = staticmethod(lambda url, headers=None, params=None: FakeRequests._do("DELETE", url, headers, params)) + mod.requests = FakeRequests + + typed = iter(inputs) + + def fake_input(prompt=""): + prompts.append(prompt) + return next(typed) + + real_input = builtins.input + builtins.input = fake_input + out = io.StringIO() + try: + with contextlib.redirect_stdout(out): + fn() + finally: + builtins.input = real_input + text = out.getvalue() + lines = text[:-1].split("\n") if text.endswith("\n") else text.split("\n") + return {"lines": lines, "prompts": prompts, "calls": calls} + + +def tok(app_id, name): + return Resp(200, {"data": {"app_id": app_id, "application": name}}) + + +APPS = { + "data": [ + {"whatsapp_business_api_data": {"id": "1", "name": "Ansari - Staging", "link": "https://www.facebook.com/games/?app_id=1"}}, + {"whatsapp_business_api_data": {"id": "2", "name": "WA DevX Webhook Events 1P App"}}, + ] +} +ONE_APP = {"data": [{"whatsapp_business_api_data": {"id": "1", "name": "Ansari - Staging"}}]} +SAME_NAME_OTHER_ID = {"data": [{"whatsapp_business_api_data": {"id": "2", "name": "Ansari - Staging"}}]} +NO_INNER = {"data": [{"something_else": {"id": "3"}}, {"whatsapp_business_api_data": {"id": "1"}}]} + +TOKEN_DETAILS = { + "data": { + "app_id": "1", + "application": "Ansari - Staging", + "type": "SYSTEM_USER", + "is_valid": True, + "issued_at": 1700000000, + "expires_at": 0, + "data_access_expires_at": 1800000000, + "user_id": "77", + "scopes": ["whatsapp_business_messaging", "business_management"], + "granular_scopes": [{"scope": "whatsapp_business_management", "target_ids": ["111"]}, "plain"], + "metadata": {"sso": "none", "n": 1}, + "extra_field": {"a": [1, None, True]}, + } +} +TOKEN_EXPIRING = {"data": {"app_id": "1", "application": "A", "issued_at": 0, "expires_at": 1900000000, "is_valid": False, "error": {"code": 190}}} +TOKEN_MINIMAL = {"data": {}} + +# (name, function, meta answers in order, typed inputs) +CASES = { + "waba_details": (mod.get_waba_details, [Resp(200, {"id": "111", "name": "Test WABA", "timezone_id": "1", "message_template_namespace": "ns", "account_review_status": "APPROVED"})], ()), + "waba_details_sparse": (mod.get_waba_details, [Resp(200, {"id": "111"})], ()), + "waba_details_http_error": (mod.get_waba_details, [Resp(400, {"error": {"message": "Bad token"}})], ()), + "token_full": (mod.debug_access_token, [Resp(200, TOKEN_DETAILS)], ()), + "token_expiring": (mod.debug_access_token, [Resp(200, TOKEN_EXPIRING)], ()), + "token_minimal": (mod.debug_access_token, [Resp(200, TOKEN_MINIMAL)], ()), + "token_http_error": (mod.debug_access_token, [Resp(400, {"error": {"message": "Nope"}})], ()), + "subscribed_two": (mod.check_subscribed_apps, [Resp(200, APPS)], ()), + "subscribed_none": (mod.check_subscribed_apps, [Resp(200, {"data": []})], ()), + "subscribed_entry_without_inner": (mod.check_subscribed_apps, [Resp(200, NO_INNER)], ()), + "subscribed_no_data_key": (mod.check_subscribed_apps, [Resp(200, {})], ()), + "subscribed_http_error": (mod.check_subscribed_apps, [Resp(403, {"error": {"message": "Forbidden"}})], ()), + "phones_two": (mod.list_phone_numbers, [Resp(200, {"data": [{"id": "9", "display_phone_number": "+1 555", "verified_name": "V", "quality_rating": "GREEN", "code_verification_status": "VERIFIED"}, {"id": "10"}]})], ()), + # Python prints `phone.get('id')` as it is: `None` when the id is missing or null + "phones_missing_id": (mod.list_phone_numbers, [Resp(200, {"data": [{}, {"id": None, "verified_name": None}]})], ()), + "phones_none": (mod.list_phone_numbers, [Resp(200, {})], ()), + "phones_empty_list": (mod.list_phone_numbers, [Resp(200, {"data": []})], ()), + "subscribe_yes": (mod.subscribe_waba, [Resp(200, {"success": True})], ["yes"]), + "subscribe_YES_spaces": (mod.subscribe_waba, [Resp(200, {"success": True})], [" YES "]), + "subscribe_no": (mod.subscribe_waba, [], ["no"]), + "subscribe_blank": (mod.subscribe_waba, [], [""]), + "subscribe_y": (mod.subscribe_waba, [], ["y"]), + "subscribe_success_false": (mod.subscribe_waba, [Resp(200, {"success": False})], ["yes"]), + "subscribe_http_error": (mod.subscribe_waba, [Resp(400, {"error": {"message": "Denied"}})], ["yes"]), + "unsub_ready_yes": (mod.unsubscribe_waba, [tok("1", "Ansari - Staging"), Resp(200, {"name": "Test WABA"}), Resp(200, APPS), Resp(200, {"success": True})], ["yes"]), + "unsub_ready_no": (mod.unsubscribe_waba, [tok("1", "Ansari - Staging"), Resp(200, {"name": "Test WABA"}), Resp(200, APPS)], ["no"]), + "unsub_ready_only_app": (mod.unsubscribe_waba, [tok("1", "Ansari - Staging"), Resp(200, {"name": "Test WABA"}), Resp(200, ONE_APP), Resp(200, {"success": True})], ["yes"]), + "unsub_token_app_not_subscribed": (mod.unsubscribe_waba, [tok("9", "Mine"), Resp(200, {"name": "Test WABA"}), Resp(200, APPS)], ()), + "unsub_nothing_subscribed": (mod.unsubscribe_waba, [tok("1", "Ansari - Staging"), Resp(200, {"name": "Test WABA"}), Resp(200, {"data": []})], ()), + "unsub_no_data_key": (mod.unsubscribe_waba, [tok("1", "Ansari - Staging"), Resp(200, {"name": "Test WABA"}), Resp(200, {})], ()), + "unsub_token_unreadable": (mod.unsubscribe_waba, [Resp(200, {})], ()), + "unsub_token_http_error": (mod.unsubscribe_waba, [Resp(401, {"error": {"message": "x"}})], ()), + "unsub_waba_name_fails": (mod.unsubscribe_waba, [tok("1", "Ansari - Staging"), Resp(400, {"error": {}}), Resp(200, APPS), Resp(200, {"success": True})], ["yes"]), + "unsub_subscribed_fails": (mod.unsubscribe_waba, [tok("1", "Ansari - Staging"), Resp(200, {"name": "Test WABA"}), Resp(500, {"error": {}})], ()), + "unsub_delete_fails": (mod.unsubscribe_waba, [tok("1", "Ansari - Staging"), Resp(200, {"name": "Test WABA"}), Resp(200, APPS), Resp(400, {"error": {"message": "cannot"}})], ["yes"]), + # Python matches by NAME. These two cases are the ones where matching by ID differs. + "unsub_same_name_other_id": (mod.unsubscribe_waba, [tok("1", "Ansari - Staging"), Resp(200, {"name": "Test WABA"}), Resp(200, SAME_NAME_OTHER_ID), Resp(200, {"success": True})], ["yes"]), + "unsub_same_id_other_name": (mod.unsubscribe_waba, [tok("1", "Renamed"), Resp(200, {"name": "Test WABA"}), Resp(200, ONE_APP)], ()), +} + + +def context_case(waba_answer, token_answer): + """What `get_current_context` returns for the two answers.""" + mod.requests = type( + "R", + (), + { + "get": staticmethod(lambda url, headers=None, params=None: waba_answer if "debug_token" not in url else token_answer), + }, + ) + return list(mod.get_current_context()) + + +def main(out_path): + data = {name: run(fn, answers, inputs) for name, (fn, answers, inputs) in CASES.items()} + + # Static screens, verbatim + for name, fn in (("prerequisite_knowledge", mod.show_prerequisite_knowledge), ("miscellaneous_info", mod.show_miscellaneous_info)): + data[name] = run(fn, [], [""]) + + contexts = { + "both_ok": context_case(Resp(200, {"name": "Test WABA"}), Resp(200, {"data": {"application": "Ansari - Staging"}})), + "no_name_keys": context_case(Resp(200, {}), Resp(200, {"data": {}})), + "no_data": context_case(Resp(200, {"name": "W"}), Resp(200, {})), + "both_failed": context_case(Resp(400, {}), Resp(400, {})), + } + + # The menu: its lines, and what it does with each typed answer + menu_text = [] + mod.requests = type("R", (), {"get": staticmethod(lambda url, headers=None, params=None: Resp(200, {"name": "Test WABA"}) if "debug_token" not in url else Resp(200, {"data": {"application": "Ansari - Staging"}}))}) + typed = iter(["x", "10", " 3 ", ""]) + real_input = builtins.input + prompts = [] + + def fake_input(prompt=""): + prompts.append(prompt) + return next(typed) + + builtins.input = fake_input + out = io.StringIO() + try: + with contextlib.redirect_stdout(out): + choice = mod.show_menu() + finally: + builtins.input = real_input + menu = {"lines": out.getvalue().split("\n")[:-1], "prompts": prompts, "choice": choice} + + # The token legitimately appears in the `input_token` query of a debug_token call (Meta takes it as a GET parameter), so only + # the PRINTED lines and the prompts count here. + token_shown = any(TOKEN[:12] in line for run_ in data.values() for line in run_["lines"] + run_["prompts"]) + lines = [ + "// GENERATED by tests/fixtures/generate_meta_script_oracle.py from legacy/whatsapp/scripts/check_meta_subscriptions.py. Do not edit by hand.", + "// Every screen below is what the legacy Python script printed (its real functions, a fake `requests`, scripted answers),", + "// and every call is what it asked Meta. Regenerate with the command in the script's docstring.", + "", + "export interface RecordedCall {", + " method: string;", + " path: string;", + " query: string;", + " /** Whether the call carried the access token as a bearer header. */", + " bearer: boolean;", + "}", + "", + "export interface RecordedRun {", + " /** What the function printed, one entry per line. */", + " lines: string[];", + " /** Each prompt it asked, in order. */", + " prompts: string[];", + " calls: RecordedCall[];", + "}", + "", + f"export const FAKE_TOKEN = {json.dumps(TOKEN)};", + "/** True when the legacy script printed (or prompted) any part of the token in these recordings. */", + f"export const LEGACY_PRINTED_TOKEN = {json.dumps(token_shown)};", + "", + f"export const RUNS: Record = {json.dumps(data, ensure_ascii=True, indent=2)};", + "", + f"export const CONTEXTS: Record = {json.dumps(contexts, ensure_ascii=True, indent=2)};", + "", + f"export const MENU: {{ lines: string[]; prompts: string[]; choice: string }} = {json.dumps(menu, ensure_ascii=True, indent=2)};", + "", + ] + with open(out_path, "w", encoding="utf-8", newline="\n") as f: + f.write("\n".join(lines)) + print("wrote", out_path, "|", len(data), "runs") + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/apps/whatsapp/tests/fixtures/metaScriptOracle.ts b/apps/whatsapp/tests/fixtures/metaScriptOracle.ts new file mode 100644 index 00000000..676222b9 --- /dev/null +++ b/apps/whatsapp/tests/fixtures/metaScriptOracle.ts @@ -0,0 +1,1421 @@ +// GENERATED by tests/fixtures/generate_meta_script_oracle.py from legacy/whatsapp/scripts/check_meta_subscriptions.py. Do not edit by hand. +// Every screen below is what the legacy Python script printed (its real functions, a fake `requests`, scripted answers), +// and every call is what it asked Meta. Regenerate with the command in the script's docstring. + +export interface RecordedCall { + method: string; + path: string; + query: string; + /** Whether the call carried the access token as a bearer header. */ + bearer: boolean; +} + +export interface RecordedRun { + /** What the function printed, one entry per line. */ + lines: string[]; + /** Each prompt it asked, in order. */ + prompts: string[]; + calls: RecordedCall[]; +} + +export const FAKE_TOKEN = "SECRET-TOKEN-VALUE-0123456789"; +/** True when the legacy script printed (or prompted) any part of the token in these recordings. */ +export const LEGACY_PRINTED_TOKEN = false; + +export const RUNS: Record = { + "waba_details": { + "lines": [ + "", + "============================================================", + "FETCHING WABA DETAILS", + "============================================================", + "", + "WABA Details:", + " ID: 111", + " Name: Test WABA", + " Timezone: 1", + " Namespace: ns", + " Review Status: APPROVED" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111", + "query": "fields=id,name,timezone_id,message_template_namespace,account_review_status", + "bearer": true + } + ] + }, + "waba_details_sparse": { + "lines": [ + "", + "============================================================", + "FETCHING WABA DETAILS", + "============================================================", + "", + "WABA Details:", + " ID: 111", + " Name: N/A", + " Timezone: N/A", + " Namespace: N/A", + " Review Status: N/A" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111", + "query": "fields=id,name,timezone_id,message_template_namespace,account_review_status", + "bearer": true + } + ] + }, + "waba_details_http_error": { + "lines": [ + "", + "============================================================", + "FETCHING WABA DETAILS", + "============================================================", + "", + "HTTP Error: 400 Client Error: for url: x", + " Response: {\"error\": {\"message\": \"Bad token\"}}" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111", + "query": "fields=id,name,timezone_id,message_template_namespace,account_review_status", + "bearer": true + } + ] + }, + "token_full": { + "lines": [ + "", + "============================================================", + "VIEWING ACCESS TOKEN DETAILS", + "============================================================", + "", + "Access Token Details:", + " App ID: 1", + " Application: Ansari - Staging", + " Type: SYSTEM_USER", + " Is Valid: True", + " Issued At: 2023-11-14 22:13:20 (1700000000)", + " Expires At: Never (permanent token)", + " Data Access Expires At: 2027-01-15 08:00:00 (1800000000)", + " User ID: 77", + " Permissions/Scopes (2):", + " - whatsapp_business_messaging", + " - business_management", + " Granular Scopes (2):", + " - whatsapp_business_management: ['111']", + " - plain", + " Metadata:", + " sso: none", + " n: 1", + " Additional Fields:", + " extra_field: {'a': [1, None, True]}" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + } + ] + }, + "token_expiring": { + "lines": [ + "", + "============================================================", + "VIEWING ACCESS TOKEN DETAILS", + "============================================================", + "", + "Access Token Details:", + " App ID: 1", + " Application: A", + " Type: N/A", + " Is Valid: False", + " Issued At: N/A", + " Expires At: 2030-03-17 17:46:40 (1900000000)", + " Permissions/Scopes: None (may be an app token)", + " Error: {'code': 190}" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + } + ] + }, + "token_minimal": { + "lines": [ + "", + "============================================================", + "VIEWING ACCESS TOKEN DETAILS", + "============================================================", + "", + "Access Token Details:", + " App ID: N/A", + " Application: N/A", + " Type: N/A", + " Is Valid: N/A", + " Issued At: N/A", + " Expires At: Never (permanent token)", + " Permissions/Scopes: None (may be an app token)" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + } + ] + }, + "token_http_error": { + "lines": [ + "", + "============================================================", + "VIEWING ACCESS TOKEN DETAILS", + "============================================================", + "", + "HTTP Error: 400 Client Error: for url: x", + " Response: {\"error\": {\"message\": \"Nope\"}}", + "", + " Note: debug_token may not work on development/test apps.", + " Try checking your token at: https://developers.facebook.com/tools/debug/accesstoken/" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + } + ] + }, + "subscribed_two": { + "lines": [ + "", + "============================================================", + "CHECKING SUBSCRIBED APPS", + "============================================================", + "", + "Successfully retrieved subscribed apps", + "", + "Found 2 subscribed app(s) to the WABA: Ansari - Staging, WA DevX Webhook Events 1P App", + "", + " App Details:", + " whatsapp_business_api_data: {'id': '1', 'name': 'Ansari - Staging', 'link': 'https://www.facebook.com/games/?app_id=1'}", + "", + " App Details:", + " whatsapp_business_api_data: {'id': '2', 'name': 'WA DevX Webhook Events 1P App'}" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "subscribed_none": { + "lines": [ + "", + "============================================================", + "CHECKING SUBSCRIBED APPS", + "============================================================", + "", + "Successfully retrieved subscribed apps", + "", + "WARNING: No apps are subscribed to this WABA!", + " This means webhooks won't be delivered to your app." + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "subscribed_entry_without_inner": { + "lines": [ + "", + "============================================================", + "CHECKING SUBSCRIBED APPS", + "============================================================", + "", + "Successfully retrieved subscribed apps", + "", + "Found 2 subscribed app(s) to the WABA: Unknown App", + "", + " App Details:", + " something_else: {'id': '3'}", + "", + " App Details:", + " whatsapp_business_api_data: {'id': '1'}" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "subscribed_no_data_key": { + "lines": [ + "", + "============================================================", + "CHECKING SUBSCRIBED APPS", + "============================================================", + "", + "Successfully retrieved subscribed apps" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "subscribed_http_error": { + "lines": [ + "", + "============================================================", + "CHECKING SUBSCRIBED APPS", + "============================================================", + "", + "HTTP Error: 403 Client Error: for url: x", + " Response: {\"error\": {\"message\": \"Forbidden\"}}" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "phones_two": { + "lines": [ + "", + "============================================================", + "LISTING PHONE NUMBERS", + "============================================================", + "", + "Successfully retrieved phone numbers for WABA: 111", + "", + "Found 2 phone number(s):", + "", + " Phone Number ID: 9", + " Display Name: +1 555", + " Verified Name: V", + " Quality Rating: GREEN", + " Status: VERIFIED", + "", + " Phone Number ID: 10", + " Display Name: N/A", + " Verified Name: N/A", + " Quality Rating: N/A", + " Status: N/A" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111/phone_numbers", + "query": "", + "bearer": true + } + ] + }, + "phones_missing_id": { + "lines": [ + "", + "============================================================", + "LISTING PHONE NUMBERS", + "============================================================", + "", + "Successfully retrieved phone numbers for WABA: 111", + "", + "Found 2 phone number(s):", + "", + " Phone Number ID: None", + " Display Name: N/A", + " Verified Name: N/A", + " Quality Rating: N/A", + " Status: N/A", + "", + " Phone Number ID: None", + " Display Name: N/A", + " Verified Name: None", + " Quality Rating: N/A", + " Status: N/A" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111/phone_numbers", + "query": "", + "bearer": true + } + ] + }, + "phones_none": { + "lines": [ + "", + "============================================================", + "LISTING PHONE NUMBERS", + "============================================================", + "", + "Successfully retrieved phone numbers for WABA: 111", + "", + "No phone numbers found for this WABA" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111/phone_numbers", + "query": "", + "bearer": true + } + ] + }, + "phones_empty_list": { + "lines": [ + "", + "============================================================", + "LISTING PHONE NUMBERS", + "============================================================", + "", + "Successfully retrieved phone numbers for WABA: 111", + "", + "Found 0 phone number(s):" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/111/phone_numbers", + "query": "", + "bearer": true + } + ] + }, + "subscribe_yes": { + "lines": [ + "", + "============================================================", + "SUBSCRIBING WABA TO APP", + "============================================================", + "", + "This will subscribe your WABA to the app associated with your access token.", + " Webhooks from this WABA will be sent to this app's webhook URL.", + "", + "Successfully subscribed WABA to app!", + " Status: Subscription active" + ], + "prompts": [ + "\n Do you want to proceed? (yes/no): " + ], + "calls": [ + { + "method": "POST", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "subscribe_YES_spaces": { + "lines": [ + "", + "============================================================", + "SUBSCRIBING WABA TO APP", + "============================================================", + "", + "This will subscribe your WABA to the app associated with your access token.", + " Webhooks from this WABA will be sent to this app's webhook URL.", + "", + "Successfully subscribed WABA to app!", + " Status: Subscription active" + ], + "prompts": [ + "\n Do you want to proceed? (yes/no): " + ], + "calls": [ + { + "method": "POST", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "subscribe_no": { + "lines": [ + "", + "============================================================", + "SUBSCRIBING WABA TO APP", + "============================================================", + "", + "This will subscribe your WABA to the app associated with your access token.", + " Webhooks from this WABA will be sent to this app's webhook URL.", + " Subscription cancelled." + ], + "prompts": [ + "\n Do you want to proceed? (yes/no): " + ], + "calls": [] + }, + "subscribe_blank": { + "lines": [ + "", + "============================================================", + "SUBSCRIBING WABA TO APP", + "============================================================", + "", + "This will subscribe your WABA to the app associated with your access token.", + " Webhooks from this WABA will be sent to this app's webhook URL.", + " Subscription cancelled." + ], + "prompts": [ + "\n Do you want to proceed? (yes/no): " + ], + "calls": [] + }, + "subscribe_y": { + "lines": [ + "", + "============================================================", + "SUBSCRIBING WABA TO APP", + "============================================================", + "", + "This will subscribe your WABA to the app associated with your access token.", + " Webhooks from this WABA will be sent to this app's webhook URL.", + " Subscription cancelled." + ], + "prompts": [ + "\n Do you want to proceed? (yes/no): " + ], + "calls": [] + }, + "subscribe_success_false": { + "lines": [ + "", + "============================================================", + "SUBSCRIBING WABA TO APP", + "============================================================", + "", + "This will subscribe your WABA to the app associated with your access token.", + " Webhooks from this WABA will be sent to this app's webhook URL.", + "", + "Successfully subscribed WABA to app!" + ], + "prompts": [ + "\n Do you want to proceed? (yes/no): " + ], + "calls": [ + { + "method": "POST", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "subscribe_http_error": { + "lines": [ + "", + "============================================================", + "SUBSCRIBING WABA TO APP", + "============================================================", + "", + "This will subscribe your WABA to the app associated with your access token.", + " Webhooks from this WABA will be sent to this app's webhook URL.", + "", + "HTTP Error: 400 Client Error: for url: x", + " Response: {\"error\": {\"message\": \"Denied\"}}" + ], + "prompts": [ + "\n Do you want to proceed? (yes/no): " + ], + "calls": [ + { + "method": "POST", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "unsub_ready_yes": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " Your access token is associated with: Ansari - Staging (ID: 1)", + "", + "\u2192 Step 2: Getting WABA details...", + " WABA Name: Test WABA", + "", + "\u2192 Step 3: Checking currently subscribed apps...", + " Currently subscribed apps: Ansari - Staging, WA DevX Webhook Events 1P App", + "", + "\u2192 Step 4: Verifying subscription match...", + "", + " Match found: Ansari - Staging app is subscribed to Test WABA WABA", + "", + "\u2192 Step 5: Confirming unsubscription...", + "", + " WARNING: This will unsubscribe 'Ansari - Staging' from 'Test WABA'", + " * Webhooks will STOP being sent to Ansari - Staging's webhook URL", + " * Other subscribed apps will remain unaffected: WA DevX Webhook Events 1P App", + "", + "\u2192 Step 6: Performing unsubscription...", + "", + " Successfully unsubscribed 'Ansari - Staging' from 'Test WABA'!", + " Status: Subscription removed" + ], + "prompts": [ + "\n Are you sure you want to proceed? (yes/no): " + ], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + }, + { + "method": "GET", + "path": "/111", + "query": "fields=name", + "bearer": true + }, + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + }, + { + "method": "DELETE", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "unsub_ready_no": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " Your access token is associated with: Ansari - Staging (ID: 1)", + "", + "\u2192 Step 2: Getting WABA details...", + " WABA Name: Test WABA", + "", + "\u2192 Step 3: Checking currently subscribed apps...", + " Currently subscribed apps: Ansari - Staging, WA DevX Webhook Events 1P App", + "", + "\u2192 Step 4: Verifying subscription match...", + "", + " Match found: Ansari - Staging app is subscribed to Test WABA WABA", + "", + "\u2192 Step 5: Confirming unsubscription...", + "", + " WARNING: This will unsubscribe 'Ansari - Staging' from 'Test WABA'", + " * Webhooks will STOP being sent to Ansari - Staging's webhook URL", + " * Other subscribed apps will remain unaffected: WA DevX Webhook Events 1P App", + " Unsubscription cancelled." + ], + "prompts": [ + "\n Are you sure you want to proceed? (yes/no): " + ], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + }, + { + "method": "GET", + "path": "/111", + "query": "fields=name", + "bearer": true + }, + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "unsub_ready_only_app": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " Your access token is associated with: Ansari - Staging (ID: 1)", + "", + "\u2192 Step 2: Getting WABA details...", + " WABA Name: Test WABA", + "", + "\u2192 Step 3: Checking currently subscribed apps...", + " Currently subscribed apps: Ansari - Staging", + "", + "\u2192 Step 4: Verifying subscription match...", + "", + " Match found: Ansari - Staging app is subscribed to Test WABA WABA", + "", + "\u2192 Step 5: Confirming unsubscription...", + "", + " WARNING: This will unsubscribe 'Ansari - Staging' from 'Test WABA'", + " * Webhooks will STOP being sent to Ansari - Staging's webhook URL", + " * Other subscribed apps will remain unaffected: ", + "", + "\u2192 Step 6: Performing unsubscription...", + "", + " Successfully unsubscribed 'Ansari - Staging' from 'Test WABA'!", + " Status: Subscription removed" + ], + "prompts": [ + "\n Are you sure you want to proceed? (yes/no): " + ], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + }, + { + "method": "GET", + "path": "/111", + "query": "fields=name", + "bearer": true + }, + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + }, + { + "method": "DELETE", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "unsub_token_app_not_subscribed": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " Your access token is associated with: Mine (ID: 9)", + "", + "\u2192 Step 2: Getting WABA details...", + " WABA Name: Test WABA", + "", + "\u2192 Step 3: Checking currently subscribed apps...", + " Currently subscribed apps: Ansari - Staging, WA DevX Webhook Events 1P App", + "", + "\u2192 Step 4: Verifying subscription match...", + "", + " WARNING: Your access token's app is NOT in the subscribed list!", + "", + " Details:", + " * Your token is for: Mine", + " * WABA 'Test WABA' is subscribed to: Ansari - Staging, WA DevX Webhook Events 1P App", + "", + " Cannot proceed with unsubscription.", + "", + " \u2192 Solution: Change your access token to one bound to an app in the subscribed list.", + " Apps you need a token for:", + " - Ansari - Staging", + " - WA DevX Webhook Events 1P App" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + }, + { + "method": "GET", + "path": "/111", + "query": "fields=name", + "bearer": true + }, + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "unsub_nothing_subscribed": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " Your access token is associated with: Ansari - Staging (ID: 1)", + "", + "\u2192 Step 2: Getting WABA details...", + " WABA Name: Test WABA", + "", + "\u2192 Step 3: Checking currently subscribed apps...", + " No apps are currently subscribed to this WABA.", + "", + " Nothing to unsubscribe. Exiting." + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + }, + { + "method": "GET", + "path": "/111", + "query": "fields=name", + "bearer": true + }, + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "unsub_no_data_key": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " Your access token is associated with: Ansari - Staging (ID: 1)", + "", + "\u2192 Step 2: Getting WABA details...", + " WABA Name: Test WABA", + "", + "\u2192 Step 3: Checking currently subscribed apps...", + " No apps are currently subscribed to this WABA.", + "", + " Nothing to unsubscribe. Exiting." + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + }, + { + "method": "GET", + "path": "/111", + "query": "fields=name", + "bearer": true + }, + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "unsub_token_unreadable": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " ERROR: Unable to debug access token." + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + } + ] + }, + "unsub_token_http_error": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " ERROR: Failed to get token details: 401 Client Error: for url: x" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + } + ] + }, + "unsub_waba_name_fails": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " Your access token is associated with: Ansari - Staging (ID: 1)", + "", + "\u2192 Step 2: Getting WABA details...", + " Warning: Could not get WABA name: 400 Client Error: for url: x", + "", + "\u2192 Step 3: Checking currently subscribed apps...", + " Currently subscribed apps: Ansari - Staging, WA DevX Webhook Events 1P App", + "", + "\u2192 Step 4: Verifying subscription match...", + "", + " Match found: Ansari - Staging app is subscribed to WABA 111 WABA", + "", + "\u2192 Step 5: Confirming unsubscription...", + "", + " WARNING: This will unsubscribe 'Ansari - Staging' from 'WABA 111'", + " * Webhooks will STOP being sent to Ansari - Staging's webhook URL", + " * Other subscribed apps will remain unaffected: WA DevX Webhook Events 1P App", + "", + "\u2192 Step 6: Performing unsubscription...", + "", + " Successfully unsubscribed 'Ansari - Staging' from 'WABA 111'!", + " Status: Subscription removed" + ], + "prompts": [ + "\n Are you sure you want to proceed? (yes/no): " + ], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + }, + { + "method": "GET", + "path": "/111", + "query": "fields=name", + "bearer": true + }, + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + }, + { + "method": "DELETE", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "unsub_subscribed_fails": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " Your access token is associated with: Ansari - Staging (ID: 1)", + "", + "\u2192 Step 2: Getting WABA details...", + " WABA Name: Test WABA", + "", + "\u2192 Step 3: Checking currently subscribed apps...", + " ERROR: Failed to get subscribed apps: 500 Client Error: for url: x" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + }, + { + "method": "GET", + "path": "/111", + "query": "fields=name", + "bearer": true + }, + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "unsub_delete_fails": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " Your access token is associated with: Ansari - Staging (ID: 1)", + "", + "\u2192 Step 2: Getting WABA details...", + " WABA Name: Test WABA", + "", + "\u2192 Step 3: Checking currently subscribed apps...", + " Currently subscribed apps: Ansari - Staging, WA DevX Webhook Events 1P App", + "", + "\u2192 Step 4: Verifying subscription match...", + "", + " Match found: Ansari - Staging app is subscribed to Test WABA WABA", + "", + "\u2192 Step 5: Confirming unsubscription...", + "", + " WARNING: This will unsubscribe 'Ansari - Staging' from 'Test WABA'", + " * Webhooks will STOP being sent to Ansari - Staging's webhook URL", + " * Other subscribed apps will remain unaffected: WA DevX Webhook Events 1P App", + "", + "\u2192 Step 6: Performing unsubscription...", + "", + " HTTP Error: 400 Client Error: for url: x", + " Response: {\"error\": {\"message\": \"cannot\"}}" + ], + "prompts": [ + "\n Are you sure you want to proceed? (yes/no): " + ], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + }, + { + "method": "GET", + "path": "/111", + "query": "fields=name", + "bearer": true + }, + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + }, + { + "method": "DELETE", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "unsub_same_name_other_id": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " Your access token is associated with: Ansari - Staging (ID: 1)", + "", + "\u2192 Step 2: Getting WABA details...", + " WABA Name: Test WABA", + "", + "\u2192 Step 3: Checking currently subscribed apps...", + " Currently subscribed apps: Ansari - Staging", + "", + "\u2192 Step 4: Verifying subscription match...", + "", + " Match found: Ansari - Staging app is subscribed to Test WABA WABA", + "", + "\u2192 Step 5: Confirming unsubscription...", + "", + " WARNING: This will unsubscribe 'Ansari - Staging' from 'Test WABA'", + " * Webhooks will STOP being sent to Ansari - Staging's webhook URL", + " * Other subscribed apps will remain unaffected: ", + "", + "\u2192 Step 6: Performing unsubscription...", + "", + " Successfully unsubscribed 'Ansari - Staging' from 'Test WABA'!", + " Status: Subscription removed" + ], + "prompts": [ + "\n Are you sure you want to proceed? (yes/no): " + ], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + }, + { + "method": "GET", + "path": "/111", + "query": "fields=name", + "bearer": true + }, + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + }, + { + "method": "DELETE", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "unsub_same_id_other_name": { + "lines": [ + "", + "============================================================", + "UNSUBSCRIBING WABA FROM APP", + "============================================================", + "", + "\u2192 Step 1: Identifying your access token's app...", + " Your access token is associated with: Renamed (ID: 1)", + "", + "\u2192 Step 2: Getting WABA details...", + " WABA Name: Test WABA", + "", + "\u2192 Step 3: Checking currently subscribed apps...", + " Currently subscribed apps: Ansari - Staging", + "", + "\u2192 Step 4: Verifying subscription match...", + "", + " WARNING: Your access token's app is NOT in the subscribed list!", + "", + " Details:", + " * Your token is for: Renamed", + " * WABA 'Test WABA' is subscribed to: Ansari - Staging", + "", + " Cannot proceed with unsubscription.", + "", + " \u2192 Solution: Change your access token to one bound to an app in the subscribed list.", + " Apps you need a token for:", + " - Ansari - Staging" + ], + "prompts": [], + "calls": [ + { + "method": "GET", + "path": "/debug_token", + "query": "input_token=SECRET-TOKEN-VALUE-0123456789", + "bearer": true + }, + { + "method": "GET", + "path": "/111", + "query": "fields=name", + "bearer": true + }, + { + "method": "GET", + "path": "/111/subscribed_apps", + "query": "", + "bearer": true + } + ] + }, + "prerequisite_knowledge": { + "lines": [ + "", + "============================================================", + "PREREQUISITE KNOWLEDGE: Meta WhatsApp Business Architecture", + "============================================================", + "", + "\ud83d\udcda THE BIG PICTURE", + "", + "1. HIERARCHY OF META ASSETS:", + " --------------------------------------------------------", + " Meta Business Manager (business.facebook.com)", + " \u2193", + " WhatsApp Business Account (WABA)", + " \u2193", + " Phone Numbers (up to 20 per WABA)", + "", + " Developer App (developers.facebook.com)", + " \u2193", + " App Secret + Access Token", + " \u2193", + " Webhook URL (receives messages)", + "", + "2. HOW THEY CONNECT:", + " --------------------------------------------------------", + " \u2022 A WABA can be SUBSCRIBED to multiple Developer Apps", + " \u2022 When someone messages your WhatsApp number:", + " 1. Meta finds which WABA owns that phone number", + " 2. Meta checks which Developer Apps are subscribed to that WABA", + " 3. Meta sends webhooks to ALL subscribed apps' webhook URLs", + " 4. Meta signs each webhook with the app's App Secret", + "", + "3. KEY CONCEPTS:", + " --------------------------------------------------------", + " \u2022 WABA (WhatsApp Business Account):", + " - Container for your WhatsApp phone numbers", + " - Managed in Meta Business Manager", + " - Can have multiple phone numbers", + "", + " \u2022 Developer App (e.g., 'Ansari - Test'):", + " - Created at developers.facebook.com", + " - Has unique App ID and App Secret", + " - Needs to be SUBSCRIBED to a WABA to receive webhooks", + "", + " \u2022 Access Token:", + " - Generated for a specific Developer App", + " - Used to authenticate API calls", + " - Token is tied to ONE app only (cannot be shared)", + "", + " \u2022 App Secret:", + " - Secret key unique to each Developer App", + " - Used by Meta to sign webhook payloads", + " - Your server verifies signatures to ensure authenticity", + "", + " \u2022 Subscription:", + " - Links a WABA to a Developer App", + " - Required for webhooks to be delivered", + " - One WABA can subscribe to multiple apps", + "", + "4. COMMON SETUP (3 ENVIRONMENTS):", + " --------------------------------------------------------", + " \u2022 Test/Local Environment:", + " - Developer App: 'Ansari - Test'", + " - WABA: 'Test WhatsApp Business Account'", + " - Phone Number: Test number (90-day expiry)", + " - Webhook: zrok tunnel (e.g., https://xxx.share.zrok.io)", + "", + " \u2022 Staging Environment:", + " - Developer App: 'Ansari - Staging'", + " - WABA: Also 'Test WhatsApp Business Account'", + " - Phone Number: Same Test number (nuisance though, as sending a msg to it hits both apps)", + " - Webhook: Staging server URL", + "", + " \u2022 Production Environment:", + " - Developer App: 'Ansari' (production)", + " - WABA: Production WABA", + " - Phone Number: Official business phone", + " - Webhook: Production server URL", + "", + "5. WHY THIS MATTERS:", + " --------------------------------------------------------", + " \u2022 Access tokens are APP-SPECIFIC", + " \u2192 You need separate tokens for test/staging/production", + "", + " \u2022 Subscriptions control webhook delivery", + " \u2192 If not subscribed, you won't receive messages", + "", + " \u2022 App Secrets must match for signature verification", + " \u2192 Wrong secret = webhooks rejected by your server", + "", + " \u2022 Multiple apps can subscribe to the same WABA", + " \u2192 Useful for routing to different environments", + "", + "6. VISUAL EXAMPLE:", + " --------------------------------------------------------", + " WABA: 'Test WhatsApp Business Account'", + " \u251c\u2500 Phone: +1234567890 (test)", + " \u2514\u2500 Subscribed to:", + " \u251c\u2500 App: 'Ansari - Test'", + " \u2502 \u251c\u2500 Access Token: EAAMf...", + " \u2502 \u251c\u2500 App Secret: abc123...", + " \u2502 \u2514\u2500 Webhook: https://xxx.share.zrok.io/whatsapp/v2", + " \u2514\u2500 App: 'Ansari - Staging'", + " \u251c\u2500 Access Token: EAAMf...", + " \u251c\u2500 App Secret: def456...", + " \u2514\u2500 Webhook: https://staging-api.ansari.chat/whatsapp/v2", + "", + " When user sends message to +1234567890:", + " \u2192 Both 'Ansari - Test' AND 'Ansari - Staging' receive webhooks!", + "", + "7. USEFUL RESOURCES:", + " --------------------------------------------------------", + " \u2022 Debug Access Token:", + " https://developers.facebook.com/tools/debug/accesstoken/", + " \u2022 Meta Business Manager:", + " https://business.facebook.com/", + " \u2022 Developer Apps:", + " https://developers.facebook.com/apps/", + " \u2022 WhatsApp API Documentation:", + " https://developers.facebook.com/docs/whatsapp/", + " \u2022 NEXT STEP - get your WABA ID (every menu choice from 1 to 7 needs it):", + " 1. Open https://developers.facebook.com/apps/ and click the app your access token belongs to", + " (e.g. 'Ansari - Staging'; the 'CURRENT CONTEXT' box in the menu shows which app that is).", + " 2. In the app's left-hand menu open the 'WhatsApp' use case, then 'Step 1. Try it out'.", + " 3. Under the 'Claim a WhatsApp test number' section, copy the 'Messaging account ID'.", + " (Meta's new name for the WhatsApp Business Account ID; it is the value of META_MESSAGING_ACCOUNT_ID.)", + " It sits near the phone number ID in that panel.", + " 4. Check it is the right one: the phone number selected there must be the number whose ID is in", + " META_BUSINESS_PHONE_NUMBER_ID (a different number can belong to a different WABA).", + " 5. Put it in your .env as META_MESSAGING_ACCOUNT_ID=, or paste it when this script asks for it.", + " Want the Messaging account ID of the PRODUCTION number instead of the test number?", + " On the same app page, open 'Step 2. Production setup' \u2192 'Register your WhatsApp phone number';", + " the Messaging account ID is shown there under 'Ansari Chat' (the production account).", + " Use the production app's token for it (e.g. 'Ansari'), and re-check step 4 for the production number ID.", + " Alternative (from memory, not checked against Meta's docs): https://business.facebook.com/latest/settings", + " \u2192 Accounts \u2192 WhatsApp accounts \u2192 select the account \u2192 its ID is in the details panel.", + " Menu names change; if one is missing, look for 'WhatsApp Business Account ID' on those pages.", + "", + "============================================================", + "NEXT STEP: copy your WABA ID as described in section 7, then run option 3 (subscribed apps)." + ], + "prompts": [ + "\nPress Enter to return to menu..." + ], + "calls": [] + }, + "miscellaneous_info": { + "lines": [ + "", + "============================================================", + "MISCELLANEOUS INFO", + "============================================================", + "", + "1. 'WA DevX Webhook Events 1P App' shows up in option 3 (apps subscribed to the WABA). What is it?", + " It is not one of our apps, and we found no Meta documentation that names it. Our best guess (UNVERIFIED):", + " it is a Meta-owned app that Meta adds to WhatsApp accounts created through its dashboard test setup.", + " The name reads as 'WhatsApp developer experience' + '1P' (first-party, i.e. Meta's own app).", + " Meta's docs say a WABA sends webhooks to every subscribed app, so an extra subscriber should not stop", + " ours from receiving them. The real question is whether OUR app (the one in 'CURRENT CONTEXT') is listed.", + " If it is the only app listed, our app is NOT subscribed: use option 5 (it changes Meta's state).", + " The 'link' field (facebook.com/games/?app_id=...) is just Meta's generic URL format for any app.", + " Only source found, a single user's claim (it also guesses the app may intercept messages, unproven):", + " https://www.reddit.com/r/MetaAppDevelopers/comments/1qi2jqa/whatsapp_cloud_api_webhook_works_on_new_business", + " Subscribed-apps API: https://developers.facebook.com/docs/whatsapp/embedded-signup/webhooks", + "", + "============================================================" + ], + "prompts": [ + "\nPress Enter to return to menu..." + ], + "calls": [] + } +}; + +export const CONTEXTS: Record = { + "both_ok": [ + "Test WABA", + "Ansari - Staging" + ], + "no_name_keys": [ + "Unknown (probably invalid WABA ID)", + "Unknown (probably invalid token)" + ], + "no_data": [ + "W", + "Unknown" + ], + "both_failed": [ + "Unknown", + "Unknown" + ] +}; + +export const MENU: { lines: string[]; prompts: string[]; choice: string } = { + "lines": [ + "", + "============================================================", + "CURRENT CONTEXT", + "============================================================", + " WABA: Test WABA", + " App: Ansari - Staging", + "============================================================", + "AVAILABLE ACTIONS", + "============================================================", + "", + "0. \ud83d\udcda Show prerequisite knowledge (understand the big picture)", + "1. View WABA details", + "2. View access token details for debugging", + "3. Check apps subscribed to the WABA", + "4. List phone numbers registered to the WABA", + "5. Subscribe WABA to app (enable webhooks)", + "6. Unsubscribe WABA from app (disable webhooks)", + "7. Run all checks (view everything)", + "8. Miscellaneous info (e.g., what is 'WA DevX Webhook Events 1P App' in option 3's list?)", + "9. Exit", + " Invalid choice. Please enter a number between 0 and 9.", + " Invalid choice. Please enter a number between 0 and 9." + ], + "prompts": [ + "\nEnter your choice (0-9): ", + "\nEnter your choice (0-9): ", + "\nEnter your choice (0-9): " + ], + "choice": "3" +}; diff --git a/apps/whatsapp/tests/helpers/scriptedIo.ts b/apps/whatsapp/tests/helpers/scriptedIo.ts new file mode 100644 index 00000000..6b3c915d --- /dev/null +++ b/apps/whatsapp/tests/helpers/scriptedIo.ts @@ -0,0 +1,76 @@ +/** + * Test helpers for the operator script: a keyboard that types scripted answers, a screen that keeps what was printed, and a + * Meta stand-in that answers from a list and records every call. + * + * Python counterpart: replacing `builtins.input` and `requests` by hand, as the oracle generator does. + */ +import type { Io } from '../../scripts/terminalIo'; + +export interface ScriptedIo extends Io { + /** Every printed line, in order; a `print` of text with line breaks counts as several lines, as on a screen. */ + lines: string[]; + /** Every prompt shown, in order, with whether it was a hidden one. */ + prompts: Array<{ text: string; hidden: boolean }>; + /** Answers not yet used. */ + remaining: () => number; +} + +/** Answers are used one per question, in order. `null` is "no more input". Running out of answers is a test error. */ +export function scriptedIo(answers: Array): ScriptedIo { + const queue = [...answers]; + const lines: string[] = []; + const prompts: ScriptedIo['prompts'] = []; + + function next(prompt: string, hidden: boolean): Promise { + prompts.push({ text: prompt, hidden }); + if (queue.length === 0) throw new Error(`the script asked ${JSON.stringify(prompt)} but the test has no answer left`); + return Promise.resolve(queue.shift() ?? null); + } + + return { + lines, + prompts, + remaining: () => queue.length, + print: (text) => { + lines.push(...text.split('\n')); + }, + ask: (prompt) => next(prompt, false), + askHidden: (prompt) => next(prompt, true), + }; +} + +export interface RecordedMetaCall { + method: string; + path: string; + query: string; + bearer: boolean; + redirect: NonNullable[1]>['redirect']; +} + +export type MetaAnswer = Response | Error; + +/** Answers Meta calls from a list, in order, and records them (path without the host and version). */ +export function metaStandIn(token: string, version: string, answers: MetaAnswer[]): { fetch: typeof fetch; calls: RecordedMetaCall[] } { + const calls: RecordedMetaCall[] = []; + const remaining = [...answers]; + const standIn = async (input: Parameters[0], init?: Parameters[1]): Promise => { + const url = new URL(input instanceof Request ? input.url : String(input)); + const headers = new Headers(init?.headers); + calls.push({ + method: init?.method ?? 'GET', + path: url.pathname.replace(`/${version}`, ''), + query: [...url.searchParams.entries()].map(([key, value]) => `${key}=${value}`).join('&'), + bearer: headers.get('authorization') === `Bearer ${token}`, + redirect: init?.redirect, + }); + const answer = remaining.shift(); + if (answer === undefined) throw new Error(`unexpected call ${init?.method ?? 'GET'} ${url.pathname}: the test has no answer left`); + if (answer instanceof Error) throw answer; + return answer; + }; + return { fetch: standIn as typeof fetch, calls }; +} + +export function json(status: number, body: unknown): Response { + return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); +} diff --git a/apps/whatsapp/tests/metaCalls.test.ts b/apps/whatsapp/tests/metaCalls.test.ts new file mode 100644 index 00000000..c1f5b14d --- /dev/null +++ b/apps/whatsapp/tests/metaCalls.test.ts @@ -0,0 +1,316 @@ +/** + * The Graph API layer of the operator script: how each call is made, how failures read, and how Meta's answers are understood. + * + * Python counterpart: none. The legacy script called `requests` inline in each function and had no timeout, no redirect rule and + * no limit on what an error could print. + */ +import { describe, expect, it } from 'vitest'; +import { + debugToken, + getPhoneNumbers, + getSubscribedApps, + getWabaDetails, + getWabaName, + MetaCallError, + planUnsubscribe, + pythonShow, + readSubscribedApps, + readTokenApp, + subscribeTokenApp, + unsubscribeTokenApp, + withoutToken, + type MetaContext, + type SubscribedApp, +} from '../scripts/metaSubscriptions'; +import { json, metaStandIn, type MetaAnswer } from './helpers/scriptedIo'; + +const TOKEN = 'EAAMf-token-0123456789-abcdef'; + +function ctx(answers: MetaAnswer[], overrides: Partial = {}) { + const meta = metaStandIn(TOKEN, 'v26.0', answers); + const context: MetaContext = { accessToken: TOKEN, wabaId: '111', version: 'v26.0', fetch: meta.fetch, ...overrides }; + return { context, meta }; +} + +async function thrown(promise: Promise): Promise { + try { + await promise; + } catch (error) { + expect(error).toBeInstanceOf(MetaCallError); + return error as MetaCallError; + } + throw new Error('expected the call to fail'); +} + +describe('each call', () => { + it.each([ + ['getWabaDetails', getWabaDetails, 'GET', '/111', 'fields=id,name,timezone_id,message_template_namespace,account_review_status'], + ['getWabaName', getWabaName, 'GET', '/111', 'fields=name'], + ['getSubscribedApps', getSubscribedApps, 'GET', '/111/subscribed_apps', ''], + ['getPhoneNumbers', getPhoneNumbers, 'GET', '/111/phone_numbers', ''], + ['subscribeTokenApp', subscribeTokenApp, 'POST', '/111/subscribed_apps', ''], + ['unsubscribeTokenApp', unsubscribeTokenApp, 'DELETE', '/111/subscribed_apps', ''], + ] as const)('%s makes one %s call to %s', async (_name, fn, method, path, query) => { + const { context, meta } = ctx([json(200, { ok: true })]); + await fn(context); + expect(meta.calls).toEqual([{ method, path, query, bearer: true, redirect: 'manual' }]); + }); + + it('debugToken sends the token as the bearer AND as input_token (Meta takes it as a GET parameter), nowhere else', async () => { + const { context, meta } = ctx([json(200, { data: {} })]); + await debugToken(context); + expect(meta.calls).toEqual([{ method: 'GET', path: '/debug_token', query: `input_token=${TOKEN}`, bearer: true, redirect: 'manual' }]); + }); + + it('builds the address from the version and the account id it was given', async () => { + const seen: string[] = []; + const fetchSpy = (async (input: Parameters[0]) => { + seen.push(String(input)); + return json(200, {}); + }) as typeof fetch; + await getSubscribedApps({ accessToken: TOKEN, wabaId: '999', version: 'v31.2', fetch: fetchSpy }); + expect(seen).toEqual(['https://graph.facebook.com/v31.2/999/subscribed_apps']); + }); + + it('puts no token in any address except debug_token\'s input_token', async () => { + const seen: string[] = []; + const fetchSpy = (async (input: Parameters[0]) => { + seen.push(String(input)); + return json(200, {}); + }) as typeof fetch; + const context: MetaContext = { accessToken: TOKEN, wabaId: '111', version: 'v26.0', fetch: fetchSpy }; + for (const fn of [getWabaDetails, getWabaName, getSubscribedApps, getPhoneNumbers, subscribeTokenApp, unsubscribeTokenApp]) await fn(context); + expect(seen.filter((url) => url.includes(TOKEN))).toEqual([]); + }); + + it('returns Meta\'s parsed answer', async () => { + const { context } = ctx([json(200, { data: [{ id: 'x' }] })]); + expect(await getSubscribedApps(context)).toEqual({ data: [{ id: 'x' }] }); + }); + + it('refuses a redirect instead of sending the token to wherever it points', async () => { + const { context } = ctx([new Response(null, { status: 302, headers: { Location: 'http://evil.test/' } })]); + const error = await thrown(getWabaName(context)); + expect(error.status).toBe(302); + }); + + it('gives each call a 20 second limit (an AbortSignal that is not yet aborted)', async () => { + let signal: AbortSignal | null | undefined; + const fetchSpy = (async (_input: Parameters[0], init?: Parameters[1]) => { + signal = init?.signal; + return json(200, {}); + }) as typeof fetch; + await getWabaName({ accessToken: TOKEN, wabaId: '1', version: 'v26.0', fetch: fetchSpy }); + expect(signal).toBeInstanceOf(AbortSignal); + expect(signal?.aborted).toBe(false); + }); +}); + +describe('a failed call', () => { + it.each([400, 401, 403, 404, 429, 500, 503])('HTTP %i is a MetaCallError with the status and Meta\'s text', async (status) => { + const { context } = ctx([json(status, { error: { message: 'Meta says no' } })]); + const error = await thrown(getWabaName(context)); + expect(error.status).toBe(status); + expect(error.message).toBe(`Meta answered HTTP ${status}`); + expect(error.detail).toBe('{"error":{"message":"Meta says no"}}'); + }); + + it('takes the access token out of Meta\'s reply, wherever it appears', async () => { + const { context } = ctx([json(400, { error: { message: `bad token ${TOKEN} and again ${TOKEN}` } })]); + const error = await thrown(getWabaName(context)); + expect(error.detail).not.toContain(TOKEN); + expect(error.detail).toContain('bad token *** and again ***'); + }); + + it('keeps the token out of the error message and the cause it carries for a network fault', async () => { + const { context } = ctx([new TypeError(`fetch failed ${TOKEN}`)]); + const error = await thrown(getWabaName(context)); + expect(error.status).toBeUndefined(); + expect(error.message).toBe('Could not reach Meta'); + expect(error.message).not.toContain(TOKEN); + expect(error.detail).toBeUndefined(); + }); + + it('says it timed out, without the token, when the 20 second limit fires', async () => { + const timeout = Object.assign(new Error(`The operation was aborted due to timeout ${TOKEN}`), { name: 'TimeoutError' }); + const { context } = ctx([timeout]); + const error = await thrown(getWabaName(context)); + expect(error.message).toBe('No answer from Meta within 20 s'); + expect(error.message).not.toContain(TOKEN); + }); + + it('cuts a very long reply to 2000 characters', async () => { + const { context } = ctx([new Response('x'.repeat(5000), { status: 500 })]); + expect((await thrown(getWabaName(context))).detail).toHaveLength(2000); + }); + + it('counts code points, not UTF-16 units, so a cut never splits an emoji', async () => { + const { context } = ctx([new Response('\u{1F600}'.repeat(2500), { status: 500 })]); + const detail = (await thrown(getWabaName(context))).detail!; + expect([...detail]).toHaveLength(2000); + expect(detail).not.toMatch(/[\ud800-\udbff](?![\udc00-\udfff])/); + }); + + it('is a MetaCallError for a 200 whose body is not JSON', async () => { + const { context } = ctx([new Response('', { status: 200 })]); + const error = await thrown(getWabaName(context)); + expect(error.message).toBe('Meta answered with something that is not JSON'); + expect(error.status).toBe(200); + }); + + it('is a MetaCallError for an empty 200 body', async () => { + const { context } = ctx([new Response('', { status: 200 })]); + expect((await thrown(getWabaName(context))).message).toBe('Meta answered with something that is not JSON'); + }); + + it('reads a reply whose body fails to arrive as an empty text, still a clean error', async () => { + const broken = new Response( + new ReadableStream({ + start(controller) { + controller.error(new Error(`reset ${TOKEN}`)); + }, + }), + { status: 502 }, + ); + const error = await thrown(getWabaName(ctx([broken]).context)); + expect(error.status).toBe(502); + expect(error.detail).toBe(''); + }); +}); + +describe('withoutToken', () => { + it('replaces every occurrence, including adjacent ones', () => { + expect(withoutToken(`${TOKEN}${TOKEN}-${TOKEN}`, TOKEN)).toBe('******-***'); + }); + + it('leaves text alone when the token is empty (an empty split would insert stars between every character)', () => { + expect(withoutToken('hello', '')).toBe('hello'); + }); + + it('does not treat the token as a pattern', () => { + expect(withoutToken('a.b*c+d', '.*')).toBe('a.b*c+d'); + expect(withoutToken('a.*b', '.*')).toBe('a***b'); + }); +}); + +describe('readSubscribedApps', () => { + it('reads id, name and the whole entry for each app', () => { + const apps = readSubscribedApps({ data: [{ whatsapp_business_api_data: { id: '1', name: 'A', link: 'L' } }] }); + expect(apps).toEqual([{ id: '1', name: 'A', fields: { whatsapp_business_api_data: { id: '1', name: 'A', link: 'L' } } }]); + }); + + it('keeps an entry with no whatsapp_business_api_data, with no name and no id, so the count stays right', () => { + const apps = readSubscribedApps({ data: [{ other: 1 }] }); + expect(apps).toHaveLength(1); + expect(apps[0]).toMatchObject({ id: undefined, name: undefined }); + }); + + it('names an app "Unknown App" when its data has no name, as Python did, but not when the name is null', () => { + expect(readSubscribedApps({ data: [{ whatsapp_business_api_data: { id: '1' } }] })[0]!.name).toBe('Unknown App'); + expect(readSubscribedApps({ data: [{ whatsapp_business_api_data: { id: '1', name: null } }] })[0]!.name).toBe('None'); + }); + + it('accepts a numeric id, as JSON numbers can arrive, as text', () => { + expect(readSubscribedApps({ data: [{ whatsapp_business_api_data: { id: 67084, name: 'A' } }] })[0]!.id).toBe('67084'); + }); + + it.each([undefined, null, 5, 'x', [], {}, { data: 5 }, { data: 'x' }, { data: null }])('reads %j as no apps', (answer) => { + expect(readSubscribedApps(answer)).toEqual([]); + }); + + it('copes with entries that are not objects', () => { + const apps = readSubscribedApps({ data: [null, 5, 'x', [], { whatsapp_business_api_data: 'nope' }] }); + expect(apps).toHaveLength(5); + expect(apps.every((app) => app.name === undefined && app.id === undefined)).toBe(true); + }); +}); + +describe('readTokenApp', () => { + it('reads app_id as id and application as name', () => { + expect(readTokenApp({ data: { app_id: '1', application: 'A' } })).toEqual({ id: '1', name: 'A' }); + }); + + it('accepts a numeric app_id as text', () => { + expect(readTokenApp({ data: { app_id: 123, application: 'A' } })).toEqual({ id: '123', name: 'A' }); + }); + + it('keeps what it can read when one field is missing', () => { + expect(readTokenApp({ data: { application: 'A' } })).toEqual({ id: undefined, name: 'A' }); + expect(readTokenApp({ data: { app_id: '1' } })).toEqual({ id: '1', name: undefined }); + }); + + it.each([undefined, null, 5, 'x', [], {}, { data: null }, { data: 'x' }, { data: [] }])('reads %j as no token info', (answer) => { + expect(readTokenApp(answer)).toBeUndefined(); + }); +}); + +describe('planUnsubscribe', () => { + const app = (id: string | undefined, name = 'N'): SubscribedApp => ({ id, name, fields: {} }); + + it('says nothing is subscribed for an empty list, whatever the token', () => { + expect(planUnsubscribe({ id: '1', name: 'A' }, [])).toEqual({ kind: 'nothing_subscribed' }); + expect(planUnsubscribe({ id: undefined, name: undefined }, [])).toEqual({ kind: 'nothing_subscribed' }); + }); + + it('is ready when the token\'s app ID is among them, and lists the others', () => { + const plan = planUnsubscribe({ id: '1', name: 'A' }, [app('2'), app('1'), app('3')]); + expect(plan.kind).toBe('ready'); + if (plan.kind === 'ready') expect(plan.others.map((other) => other.id)).toEqual(['2', '3']); + }); + + it('refuses when no subscribed app has the token\'s ID', () => { + expect(planUnsubscribe({ id: '9', name: 'A' }, [app('1'), app('2')]).kind).toBe('token_app_not_subscribed'); + }); + + it('refuses when the token\'s ID is unknown, even if a subscribed app also has no ID (undefined must not match undefined)', () => { + expect(planUnsubscribe({ id: undefined, name: 'A' }, [app(undefined, 'A')]).kind).toBe('token_app_not_subscribed'); + }); + + it('matches by ID, not by name', () => { + expect(planUnsubscribe({ id: '1', name: 'Same' }, [app('2', 'Same')]).kind).toBe('token_app_not_subscribed'); + expect(planUnsubscribe({ id: '1', name: 'Renamed' }, [app('1', 'Original')]).kind).toBe('ready'); + }); + + it('matches IDs exactly: no prefix, no number-vs-text confusion', () => { + expect(planUnsubscribe({ id: '1', name: 'A' }, [app('10')]).kind).toBe('token_app_not_subscribed'); + expect(planUnsubscribe({ id: '10', name: 'A' }, [app('1')]).kind).toBe('token_app_not_subscribed'); + expect(planUnsubscribe({ id: '01', name: 'A' }, [app('1')]).kind).toBe('token_app_not_subscribed'); + }); + + it('removes only the first app with that ID from "others" when two entries share it', () => { + const plan = planUnsubscribe({ id: '1', name: 'A' }, [app('1', 'first'), app('1', 'second')]); + expect(plan.kind).toBe('ready'); + if (plan.kind === 'ready') expect(plan.others.map((other) => other.name)).toEqual(['second']); + }); + + it('reports the apps it refused over, so the screen can name them', () => { + const plan = planUnsubscribe({ id: '9', name: 'Mine' }, [app('1', 'One')]); + expect(plan.kind === 'token_app_not_subscribed' && plan.subscribed.map((a) => a.name)).toEqual(['One']); + }); +}); + +describe('pythonShow (Python\'s str() of a JSON value)', () => { + it.each([ + ['text', 'text'], + [5, '5'], + [1.5, '1.5'], + [true, 'True'], + [false, 'False'], + [null, 'None'], + [['a', 1], "['a', 1]"], + [{ k: 'v' }, "{'k': 'v'}"], + [{ a: [1, null, true] }, "{'a': [1, None, True]}"], + [[], '[]'], + [{}, '{}'], + ])('%j -> %s', (value, text) => { + expect(pythonShow(value)).toBe(text); + }); +}); + +describe('MetaCallError', () => { + it('carries status and detail, and the original cause', () => { + const cause = new Error('inner'); + const error = new MetaCallError('m', 400, 'd', { cause }); + expect([error.name, error.status, error.detail, error.cause]).toEqual(['MetaCallError', 400, 'd', cause]); + }); +}); diff --git a/apps/whatsapp/tests/metaScript.test.ts b/apps/whatsapp/tests/metaScript.test.ts new file mode 100644 index 00000000..5c657f14 --- /dev/null +++ b/apps/whatsapp/tests/metaScript.test.ts @@ -0,0 +1,607 @@ +/** + * The operator script: every screen against what the legacy Python script printed, the safety rules, and whole sessions. + * + * Python counterpart: none (`check_meta_subscriptions.py` had no tests). `tests/fixtures/metaScriptOracle.ts` holds what the real + * legacy functions printed and which calls they made for each case, with a fake `requests` and scripted answers. Each case here + * feeds the TypeScript function the same Meta answers and the same typed answers and compares screen, prompts and calls. + * + * Where the TypeScript script deliberately differs the test says so: + * - the wording of a failed call's own error line (Python printed `requests`' text; the new text names Meta's status). Those lines + * are compared by their first words only, and the new text is asserted in the unit tests; + * - the unsubscribe safety check matches by app ID, not by name (two cases below); + * - the access token is never printed (a test runs a whole session and searches every line and prompt for it). + * + * Times print in the machine's local time, as in Python, so these tests fix the time zone to UTC. + */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { + askMenuChoice, + currentContext, + formatLocalTime, + runScript, + showMiscellaneousInfo, + showPhoneNumbers, + showPrerequisiteKnowledge, + showSubscribedApps, + showTokenDetails, + showWabaDetails, + subscribe, + unsubscribe, +} from '../scripts/checkMetaSubscriptions'; +import type { MetaContext } from '../scripts/metaSubscriptions'; +import { MISCELLANEOUS_INFO_LINES, PREREQUISITE_KNOWLEDGE_LINES } from '../scripts/metaSubscriptionsText'; +import type { Io } from '../scripts/terminalIo'; +import { CONTEXTS, FAKE_TOKEN, LEGACY_PRINTED_TOKEN, MENU, RUNS } from './fixtures/metaScriptOracle'; +import { json, metaStandIn, scriptedIo, type MetaAnswer } from './helpers/scriptedIo'; + +const TOKEN = FAKE_TOKEN; +const WABA = '111'; +const VERSION = 'v26.0'; + +let savedTz: string | undefined; +beforeAll(() => { + savedTz = process.env.TZ; + process.env.TZ = 'UTC'; +}); +afterAll(() => { + if (savedTz === undefined) delete process.env.TZ; + else process.env.TZ = savedTz; +}); + +function setup(answers: MetaAnswer[], inputs: Array = []) { + const meta = metaStandIn(TOKEN, VERSION, answers); + const io = scriptedIo(inputs); + const context: MetaContext = { accessToken: TOKEN, wabaId: WABA, version: VERSION, fetch: meta.fetch }; + return { meta, io, context }; +} + +/** Python's two failure-text styles differ from the new ones in wording only; compare such lines by their first words. */ +function normalise(line: string): string { + return line + // Deliberate: the refusal screen also shows the token app's ID, which the check now matches on (asserted in its own test) + .replace(/^(\s*\* Your token is for: .*?) \(ID: [^)]*\)$/, '$1') + .replace(/^(\s*HTTP Error:).*/, '$1') + .replace(/^(\s*Response:).*/, '$1') + .replace(/^(\s*Error:).*/, '$1') + .replace(/^(\s*ERROR: Failed to get token details:).*/, '$1') + .replace(/^(\s*ERROR: Failed to get subscribed apps:).*/, '$1') + .replace(/^(\s*Warning: Could not get WABA name:).*/, '$1'); +} + +// --------------------------------------------------------------------------------------------------------------------- +// The data the oracle was recorded with (the same answers Meta would give) +// --------------------------------------------------------------------------------------------------------------------- + +const APPS = { + data: [ + { whatsapp_business_api_data: { id: '1', name: 'Ansari - Staging', link: 'https://www.facebook.com/games/?app_id=1' } }, + { whatsapp_business_api_data: { id: '2', name: 'WA DevX Webhook Events 1P App' } }, + ], +}; +const ONE_APP = { data: [{ whatsapp_business_api_data: { id: '1', name: 'Ansari - Staging' } }] }; +const NO_INNER = { data: [{ something_else: { id: '3' } }, { whatsapp_business_api_data: { id: '1' } }] }; +const TOKEN_DETAILS = { + data: { + app_id: '1', + application: 'Ansari - Staging', + type: 'SYSTEM_USER', + is_valid: true, + issued_at: 1700000000, + expires_at: 0, + data_access_expires_at: 1800000000, + user_id: '77', + scopes: ['whatsapp_business_messaging', 'business_management'], + granular_scopes: [{ scope: 'whatsapp_business_management', target_ids: ['111'] }, 'plain'], + metadata: { sso: 'none', n: 1 }, + extra_field: { a: [1, null, true] }, + }, +}; +const tok = (id: string, name: string) => () => json(200, { data: { app_id: id, application: name } }); +const ok = (body: unknown) => () => json(200, body); +const bad = (status: number, body: unknown) => () => json(status, body); + +interface Case { + run: (io: Io, context: MetaContext) => Promise; + answers: Array<() => Response>; + inputs: string[]; +} + +const CASES: Record = { + waba_details: { + run: showWabaDetails, + answers: [ok({ id: '111', name: 'Test WABA', timezone_id: '1', message_template_namespace: 'ns', account_review_status: 'APPROVED' })], + inputs: [], + }, + waba_details_sparse: { run: showWabaDetails, answers: [ok({ id: '111' })], inputs: [] }, + waba_details_http_error: { run: showWabaDetails, answers: [bad(400, { error: { message: 'Bad token' } })], inputs: [] }, + token_full: { run: showTokenDetails, answers: [ok(TOKEN_DETAILS)], inputs: [] }, + token_expiring: { + run: showTokenDetails, + answers: [ok({ data: { app_id: '1', application: 'A', issued_at: 0, expires_at: 1900000000, is_valid: false, error: { code: 190 } } })], + inputs: [], + }, + token_minimal: { run: showTokenDetails, answers: [ok({ data: {} })], inputs: [] }, + token_http_error: { run: showTokenDetails, answers: [bad(400, { error: { message: 'Nope' } })], inputs: [] }, + subscribed_two: { run: showSubscribedApps, answers: [ok(APPS)], inputs: [] }, + subscribed_none: { run: showSubscribedApps, answers: [ok({ data: [] })], inputs: [] }, + subscribed_entry_without_inner: { run: showSubscribedApps, answers: [ok(NO_INNER)], inputs: [] }, + subscribed_no_data_key: { run: showSubscribedApps, answers: [ok({})], inputs: [] }, + subscribed_http_error: { run: showSubscribedApps, answers: [bad(403, { error: { message: 'Forbidden' } })], inputs: [] }, + phones_two: { + run: showPhoneNumbers, + answers: [ + ok({ + data: [ + { id: '9', display_phone_number: '+1 555', verified_name: 'V', quality_rating: 'GREEN', code_verification_status: 'VERIFIED' }, + { id: '10' }, + ], + }), + ], + inputs: [], + }, + phones_missing_id: { run: showPhoneNumbers, answers: [ok({ data: [{}, { id: null, verified_name: null }] })], inputs: [] }, + phones_none: { run: showPhoneNumbers, answers: [ok({})], inputs: [] }, + phones_empty_list: { run: showPhoneNumbers, answers: [ok({ data: [] })], inputs: [] }, + subscribe_yes: { run: subscribe, answers: [ok({ success: true })], inputs: ['yes'] }, + subscribe_YES_spaces: { run: subscribe, answers: [ok({ success: true })], inputs: [' YES '] }, + subscribe_no: { run: subscribe, answers: [], inputs: ['no'] }, + subscribe_blank: { run: subscribe, answers: [], inputs: [''] }, + subscribe_y: { run: subscribe, answers: [], inputs: ['y'] }, + subscribe_success_false: { run: subscribe, answers: [ok({ success: false })], inputs: ['yes'] }, + subscribe_http_error: { run: subscribe, answers: [bad(400, { error: { message: 'Denied' } })], inputs: ['yes'] }, + unsub_ready_yes: { + run: unsubscribe, + answers: [tok('1', 'Ansari - Staging'), ok({ name: 'Test WABA' }), ok(APPS), ok({ success: true })], + inputs: ['yes'], + }, + unsub_ready_no: { run: unsubscribe, answers: [tok('1', 'Ansari - Staging'), ok({ name: 'Test WABA' }), ok(APPS)], inputs: ['no'] }, + unsub_ready_only_app: { + run: unsubscribe, + answers: [tok('1', 'Ansari - Staging'), ok({ name: 'Test WABA' }), ok(ONE_APP), ok({ success: true })], + inputs: ['yes'], + }, + unsub_token_app_not_subscribed: { run: unsubscribe, answers: [tok('9', 'Mine'), ok({ name: 'Test WABA' }), ok(APPS)], inputs: [] }, + unsub_nothing_subscribed: { + run: unsubscribe, + answers: [tok('1', 'Ansari - Staging'), ok({ name: 'Test WABA' }), ok({ data: [] })], + inputs: [], + }, + unsub_no_data_key: { run: unsubscribe, answers: [tok('1', 'Ansari - Staging'), ok({ name: 'Test WABA' }), ok({})], inputs: [] }, + unsub_token_unreadable: { run: unsubscribe, answers: [ok({})], inputs: [] }, + unsub_token_http_error: { run: unsubscribe, answers: [bad(401, { error: { message: 'x' } })], inputs: [] }, + unsub_waba_name_fails: { + run: unsubscribe, + answers: [tok('1', 'Ansari - Staging'), bad(400, { error: {} }), ok(APPS), ok({ success: true })], + inputs: ['yes'], + }, + unsub_subscribed_fails: { run: unsubscribe, answers: [tok('1', 'Ansari - Staging'), ok({ name: 'Test WABA' }), bad(500, { error: {} })], inputs: [] }, + unsub_delete_fails: { + run: unsubscribe, + answers: [tok('1', 'Ansari - Staging'), ok({ name: 'Test WABA' }), ok(APPS), bad(400, { error: { message: 'cannot' } })], + inputs: ['yes'], + }, +}; + +/** Cases where the TypeScript script is meant to behave differently; they have their own tests below. */ +const DELIBERATELY_DIFFERENT = new Set(['unsub_same_name_other_id', 'unsub_same_id_other_name']); + +describe('every screen reads as the Python script printed it', () => { + it('has a TypeScript case for every recorded Python case (so a new recording cannot be skipped by accident)', () => { + const recorded = Object.keys(RUNS).filter((name) => name !== 'prerequisite_knowledge' && name !== 'miscellaneous_info'); + expect(recorded.filter((name) => !(name in CASES) && !DELIBERATELY_DIFFERENT.has(name))).toEqual([]); + expect(Object.keys(CASES).filter((name) => !(name in RUNS))).toEqual([]); + }); + + it.each(Object.keys(CASES))('%s: the same lines, prompts and Meta calls', async (name) => { + const recorded = RUNS[name]!; + const spec = CASES[name]!; + const { meta, io, context } = setup( + spec.answers.map((make) => make()), + spec.inputs, + ); + + await spec.run(io, context); + + expect(io.lines.map(normalise)).toEqual(recorded.lines.map(normalise)); + expect(io.prompts.map((prompt) => prompt.text)).toEqual(recorded.prompts); + expect(meta.calls.map(({ method, path, query, bearer }) => ({ method, path, query, bearer }))).toEqual(recorded.calls); + }); + + it('shows the prerequisite-knowledge screen as Python did, and waits for Enter', async () => { + const { io } = setup([], ['']); + await showPrerequisiteKnowledge(io); + const recorded = RUNS.prerequisite_knowledge!; + expect(io.lines.map((line) => line.replaceAll('/whatsapp/v3', '/whatsapp/v2'))).toEqual(recorded.lines); + expect(io.prompts.map((p) => p.text)).toEqual(recorded.prompts); + expect(PREREQUISITE_KNOWLEDGE_LINES.join('\n')).not.toContain('/whatsapp/v2'); + }); + + it('shows the miscellaneous-info screen as Python did, and waits for Enter', async () => { + const { io } = setup([], ['']); + await showMiscellaneousInfo(io); + const recorded = RUNS.miscellaneous_info!; + expect(io.lines).toEqual(recorded.lines); + expect(io.prompts.map((p) => p.text)).toEqual(recorded.prompts); + expect(MISCELLANEOUS_INFO_LINES.length).toBe(recorded.lines.length); + }); + + it('changes only the example callback paths of the long screen, from v2 to v3', () => { + const recorded = RUNS.prerequisite_knowledge!.lines; + const changed = PREREQUISITE_KNOWLEDGE_LINES.filter((line, index) => line !== recorded[index]); + expect(changed).toHaveLength(2); + for (const line of changed) expect(line).toContain('/whatsapp/v3'); + }); +}); + +describe('the menu', () => { + it('prints the same box and list as Python, rejects a bad choice and an out-of-range one, and trims spaces', async () => { + const { io, context } = setup([json(200, { name: 'Test WABA' }), json(200, { data: { application: 'Ansari - Staging' } })], ['x', '10', ' 3 ']); + + const choice = await askMenuChoice(io, context); + + expect(choice).toBe(MENU.choice); + expect(io.lines).toEqual(MENU.lines); + expect(io.prompts.map((p) => p.text)).toEqual(MENU.prompts.slice(0, 3)); + }); + + it.each(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])('accepts %s', async (digit) => { + const { io, context } = setup([json(200, { name: 'W' }), json(200, { data: { application: 'A' } })], [digit]); + expect(await askMenuChoice(io, context)).toBe(digit); + }); + + it.each(['', '-1', '01', 'a', '3x', '1'])('refuses %j and asks again', async (typed) => { + const { io, context } = setup([json(200, { name: 'W' }), json(200, { data: { application: 'A' } })], [typed, '9']); + expect(await askMenuChoice(io, context)).toBe('9'); + expect(io.lines).toContain(' Invalid choice. Please enter a number between 0 and 9.'); + }); + + it('treats the end of input as "exit", as Python treated Ctrl+C', async () => { + const { io, context } = setup([json(200, { name: 'W' }), json(200, { data: { application: 'A' } })], [null]); + expect(await askMenuChoice(io, context)).toBe('9'); + expect(io.lines).toContain('Interrupted by user. Exiting...'); + }); + + describe('the context box', () => { + const answers: Record = { + both_ok: [json(200, { name: 'Test WABA' }), json(200, { data: { application: 'Ansari - Staging' } })], + no_name_keys: [json(200, {}), json(200, { data: {} })], + no_data: [json(200, { name: 'W' }), json(200, {})], + both_failed: [json(400, {}), json(400, {})], + }; + it.each(Object.keys(CONTEXTS))('%s gives what Python gave', async (name) => { + const { context } = setup([...answers[name]!]); + const result = await currentContext(context); + expect([result.wabaName, result.appName]).toEqual(CONTEXTS[name]); + }); + + it('keeps "Unknown" when Meta cannot be reached at all', async () => { + const { context } = setup([new TypeError('fetch failed'), new TypeError('fetch failed')]); + expect(await currentContext(context)).toEqual({ wabaName: 'Unknown', appName: 'Unknown' }); + }); + }); +}); + +describe('the unsubscribe safety check: the token\'s own app, matched by ID', () => { + it('the legacy script matched by NAME: given two apps with one name it went ahead and deleted (the reason for the change)', () => { + const recorded = RUNS.unsub_same_name_other_id!; + expect(recorded.calls.some((call) => call.method === 'DELETE')).toBe(true); + expect(recorded.lines.join('\n')).toContain('Match found'); + }); + + it('refuses when a subscribed app has the token app\'s NAME but another ID, and never asks to confirm or deletes', async () => { + const sameName = { data: [{ whatsapp_business_api_data: { id: '2', name: 'Ansari - Staging' } }] }; + const { meta, io, context } = setup([tok('1', 'Ansari - Staging')(), json(200, { name: 'Test WABA' }), json(200, sameName)]); + + expect(await unsubscribe(io, context)).toBe(false); + + expect(meta.calls.map((call) => call.method)).toEqual(['GET', 'GET', 'GET']); + expect(io.prompts).toEqual([]); + const screen = io.lines.join('\n'); + expect(screen).toContain("WARNING: Your access token's app is NOT in the subscribed list!"); + expect(screen).toContain('Your token is for: Ansari - Staging (ID: 1)'); + expect(screen).toContain('Cannot proceed with unsubscription.'); + expect(screen).not.toContain('Match found'); + }); + + it('the legacy script refused when the token app was renamed (the ID still matches); this one goes on and asks', async () => { + expect(RUNS.unsub_same_id_other_name!.calls.some((call) => call.method === 'DELETE')).toBe(false); + const { meta, io, context } = setup([tok('1', 'Renamed')(), json(200, { name: 'Test WABA' }), json(200, ONE_APP)], ['no']); + + expect(await unsubscribe(io, context)).toBe(false); + + expect(io.lines.join('\n')).toContain('Match found: Renamed app is subscribed to Test WABA WABA'); + expect(io.prompts.map((p) => p.text)).toEqual(['\n Are you sure you want to proceed? (yes/no): ']); + expect(meta.calls.some((call) => call.method === 'DELETE')).toBe(false); + }); + + it('refuses when the token\'s ID cannot be read', async () => { + const { meta, io, context } = setup([json(200, { data: { application: 'Ansari - Staging' } }), json(200, { name: 'W' }), json(200, ONE_APP)]); + expect(await unsubscribe(io, context)).toBe(false); + expect(meta.calls.some((call) => call.method === 'DELETE')).toBe(false); + expect(io.prompts).toEqual([]); + }); + + it('deletes only after the operator types yes, and only with the token\'s own bearer, no app named in the call', async () => { + const { meta, io, context } = setup([tok('1', 'Ansari - Staging')(), json(200, { name: 'W' }), json(200, APPS), json(200, { success: true })], ['yes']); + + expect(await unsubscribe(io, context)).toBe(true); + + const deletes = meta.calls.filter((call) => call.method === 'DELETE'); + expect(deletes).toEqual([{ method: 'DELETE', path: '/111/subscribed_apps', query: '', bearer: true, redirect: 'manual' }]); + expect(io.lines.join('\n')).toContain('Other subscribed apps will remain unaffected: WA DevX Webhook Events 1P App'); + }); + + it.each(['', 'no', 'n', 'YES please', 'ye', 'yes!', null])('does not delete when the answer is %j', async (answer) => { + const { meta, io, context } = setup([tok('1', 'Ansari - Staging')(), json(200, { name: 'W' }), json(200, APPS)], [answer]); + expect(await unsubscribe(io, context)).toBe(false); + expect(meta.calls.some((call) => call.method === 'DELETE')).toBe(false); + expect(io.lines).toContain(' Unsubscription cancelled.'); + }); + + it('does not delete when Meta lists nothing, or the token cannot be read, or the list fails', async () => { + for (const answers of [ + [tok('1', 'A')(), json(200, { name: 'W' }), json(200, { data: [] })], + [json(200, {})], + [tok('1', 'A')(), json(200, { name: 'W' }), json(500, {})], + [new TypeError('fetch failed')], + ]) { + const { meta, io, context } = setup(answers); + expect(await unsubscribe(io, context)).toBe(false); + expect(meta.calls.some((call) => call.method === 'DELETE')).toBe(false); + } + }); +}); + +describe('subscribing changes Meta only after yes', () => { + it.each(['', 'no', 'n', 'y', 'sure', null])('does not call Meta when the answer is %j', async (answer) => { + const { meta, io, context } = setup([], [answer]); + expect(await subscribe(io, context)).toBe(false); + expect(meta.calls).toEqual([]); + expect(io.lines).toContain(' Subscription cancelled.'); + }); + + it('posts once, with the token as the bearer and no app named, after yes', async () => { + const { meta, io, context } = setup([json(200, { success: true })], ['yes']); + expect(await subscribe(io, context)).toBe(true); + expect(meta.calls).toEqual([{ method: 'POST', path: '/111/subscribed_apps', query: '', bearer: true, redirect: 'manual' }]); + }); +}); + +describe('the access token is never shown', () => { + it('the legacy script showed its first 20 and last 10 characters at start-up (source line 721)', () => { + // Not in the screens recorded here (they are single functions); this pins that the recordings hold no token, so the + // session test below is a fair check that nothing in the new script prints it either. + expect(LEGACY_PRINTED_TOKEN).toBe(false); + }); + + it('is in no line and no prompt of a session that visits every option and meets errors that echo it', async () => { + const echoing = bad(400, { error: { message: `Invalid OAuth access token ${TOKEN} for app` } }); + const ctx = () => [json(200, { name: 'Test WABA' }), json(200, { data: { application: 'Ansari - Staging' } })]; + const meta = metaStandIn(TOKEN, VERSION, [ + ...ctx(), // menu + ...[ok({ id: '111', name: 'W' })()], // option 1 + ...ctx(), + ...[echoing()], // option 2 fails with the token in Meta's text + ...ctx(), + ...[ok(APPS)()], // option 3 + ...ctx(), + ...[new TypeError(`fetch failed for ${TOKEN}`)], // option 4: a network error whose text holds the token + ...ctx(), + ...[tok('1', 'Ansari - Staging')(), json(200, { name: 'W' }), json(200, APPS), echoing()], // option 6, then DELETE fails echoing it + ...ctx(), + ]); + const io = scriptedIo(['1', '', '2', '', '3', '', '4', '', '6', 'yes', '', '9']); + + await runScript(io, { + env: { META_ACCESS_TOKEN_FROM_SYS_USER: TOKEN, META_MESSAGING_ACCOUNT_ID: WABA }, + envFileFound: true, + fetch: meta.fetch, + }); + + const everything = [...io.lines, ...io.prompts.map((p) => p.text)].join('\n'); + expect(everything).not.toContain(TOKEN); + expect(everything).not.toContain(TOKEN.slice(0, 12)); + expect(everything).toContain('***'); // where Meta's text echoed it + expect(io.lines).toContain(` Access Token: set (${TOKEN.length} characters, never shown)`); + expect(io.remaining()).toBe(0); + }); + + it('is also cut out of an error the script itself raises, such as a time field that holds the token', async () => { + // Meta's answer is odd on purpose: `issued_at` is the token, so formatting it as a time raises an error whose text names it + const { io, context } = setup([json(200, { data: { issued_at: TOKEN } })]); + await showTokenDetails(io, context); + const everything = io.lines.join('\n'); + expect(everything).not.toContain(TOKEN); + expect(everything).toContain('Error: a timestamp must be a number, got '); + expect(everything).toContain('***'); + }); +}); + +describe('a whole session', () => { + const ENV = { META_ACCESS_TOKEN_FROM_SYS_USER: TOKEN, META_MESSAGING_ACCOUNT_ID: WABA }; + const menuAnswers = () => [json(200, { name: 'Test WABA' }), json(200, { data: { application: 'Ansari - Staging' } })]; + + async function session(answers: MetaAnswer[], inputs: Array, options: { env?: Record; envFileFound?: boolean } = {}) { + const meta = metaStandIn(TOKEN, VERSION, answers); + const io = scriptedIo(inputs); + await runScript(io, { env: options.env ?? ENV, envFileFound: options.envFileFound ?? true, fetch: meta.fetch }); + return { io, meta }; + } + + it('starts with the title and the configuration, then the menu, and exits on 9', async () => { + const { io, meta } = await session(menuAnswers(), ['9']); + expect(io.lines.slice(0, 3)).toEqual(['='.repeat(60), 'WhatsApp Business Account Subscription Manager', '='.repeat(60)]); + expect(io.lines).toContain(' WABA ID: 111'); + expect(io.lines.slice(-3)).toEqual(['='.repeat(60), 'Done! Exiting...', '='.repeat(60)]); + expect(meta.calls.map((call) => call.path)).toEqual(['/111', '/debug_token']); + }); + + it('after an option, Enter returns to the menu and q quits', async () => { + const back = await session([...menuAnswers(), ...[json(200, { data: [] })], ...menuAnswers()], ['3', '', '9']); + expect(back.io.prompts.map((p) => p.text)).toContain("\n Press Enter to return to menu (or 'q' to quit): "); + expect(back.meta.calls.filter((call) => call.path === '/111/subscribed_apps')).toHaveLength(1); + + const quit = await session([...menuAnswers(), json(200, { data: [] })], ['3', ' Q ']); + expect(quit.io.lines).toContain('Done! Exiting...'); + expect(quit.io.remaining()).toBe(0); + }); + + it('quits cleanly when the input ends in the middle of the "press Enter" question', async () => { + const { io } = await session([...menuAnswers(), json(200, { data: [] })], ['3', null]); + expect(io.lines).toContain('Done! Exiting...'); + }); + + it('option 7 runs the four checks in order: details, token, apps, phones', async () => { + const { meta } = await session( + [...menuAnswers(), json(200, { id: '111' }), json(200, TOKEN_DETAILS), json(200, APPS), json(200, { data: [] }), ...menuAnswers()], + ['7', '', '9'], + ); + expect(meta.calls.map((call) => call.path).slice(2, 6)).toEqual(['/111', '/debug_token', '/111/subscribed_apps', '/111/phone_numbers']); + }); + + // Python: `if choice not in ("8", "9")` asks "press Enter or q" after every option except 8 and 9, so option 0 asks it too + it('options 0 and 8 each wait for Enter; only option 8 skips the "press Enter or q" question', async () => { + const { io } = await session([...menuAnswers(), ...menuAnswers(), ...menuAnswers()], ['0', '', '', '8', '', '9']); + const asked = io.prompts.map((p) => p.text); + expect(asked.filter((text) => text === '\nPress Enter to return to menu...')).toHaveLength(2); + expect(asked.filter((text) => text.includes("(or 'q' to quit)"))).toHaveLength(1); + expect(io.remaining()).toBe(0); + }); + + it('option 5 subscribes after yes and then shows the new list; after no it changes nothing and shows nothing', async () => { + const yes = await session([...menuAnswers(), json(200, { success: true }), json(200, ONE_APP), ...menuAnswers()], ['5', 'yes', '', '9']); + expect(yes.meta.calls.map((call) => `${call.method} ${call.path}`).slice(2, 4)).toEqual(['POST /111/subscribed_apps', 'GET /111/subscribed_apps']); + expect(yes.io.lines).toContain(' → Verifying subscription...'); + + const no = await session([...menuAnswers(), ...menuAnswers()], ['5', 'no', '', '9']); + expect(no.meta.calls.some((call) => call.method === 'POST')).toBe(false); + expect(no.io.lines).not.toContain(' → Verifying subscription...'); + }); + + it('option 6 removes after yes and then shows the new list; when it refuses it changes nothing', async () => { + const yes = await session( + [...menuAnswers(), tok('1', 'Ansari - Staging')(), json(200, { name: 'W' }), json(200, APPS), json(200, { success: true }), json(200, { data: [] }), ...menuAnswers()], + ['6', 'yes', '', '9'], + ); + expect(yes.io.lines).toContain(' → Verifying unsubscription...'); + expect(yes.meta.calls.filter((call) => call.method === 'DELETE')).toHaveLength(1); + + const refused = await session([...menuAnswers(), tok('9', 'Other')(), json(200, { name: 'W' }), json(200, APPS), ...menuAnswers()], ['6', '', '9']); + expect(refused.meta.calls.some((call) => call.method === 'DELETE')).toBe(false); + expect(refused.io.lines).not.toContain(' → Verifying unsubscription...'); + }); + + it('every call goes to Meta\'s Graph API at the configured version, carries the bearer token, and refuses redirects', async () => { + const seen: string[] = []; + const recording = (async (input: Parameters[0], init?: Parameters[1]) => { + seen.push(`${String(input)}|${new Headers(init?.headers).get('authorization')}|${init?.redirect}`); + return json(200, { name: 'W', data: { application: 'A' } }); + }) as typeof fetch; + const io = scriptedIo(['9']); + + await runScript(io, { env: { ...ENV, META_API_VERSION: 'v99.1' }, envFileFound: true, fetch: recording }); + + expect(seen).toHaveLength(2); + for (const entry of seen) { + expect(entry.startsWith('https://graph.facebook.com/v99.1/')).toBe(true); + expect(entry.endsWith(`|Bearer ${TOKEN}|manual`)).toBe(true); + } + }); + + it('defaults to v26.0 when META_API_VERSION is unset or empty', async () => { + for (const version of [undefined, '']) { + const seen: string[] = []; + const recording = (async (input: Parameters[0]) => { + seen.push(String(input)); + return json(200, {}); + }) as typeof fetch; + await runScript(scriptedIo(['9']), { env: { ...ENV, META_API_VERSION: version }, envFileFound: true, fetch: recording }); + expect(seen[0]).toContain('/v26.0/'); + } + }); + + describe('when something is missing', () => { + it('with no .env and nothing set, offers manual entry and stops on no, calling nothing', async () => { + const { io, meta } = await session([], ['no'], { env: {}, envFileFound: false }); + expect(io.lines).toContain(' No .env file found in the current directory'); + expect(io.lines).toContain(' META_ACCESS_TOKEN_FROM_SYS_USER=your_token_here'); + expect(meta.calls).toEqual([]); + }); + + it('with no .env, asks for the token HIDDEN and the account id in plain view', async () => { + const { io } = await session(menuAnswers(), ['yes', TOKEN, WABA, '9'], { env: {}, envFileFound: false }); + const tokenPrompt = io.prompts.find((p) => p.text.includes('META_ACCESS_TOKEN_FROM_SYS_USER (typing is hidden)')); + expect(tokenPrompt?.hidden).toBe(true); + expect(io.prompts.find((p) => p.text.includes('Enter your WABA ID'))?.hidden).toBe(false); + expect([...io.lines, ...io.prompts.map((p) => p.text)].join('\n')).not.toContain(TOKEN); + }); + + it('with a .env that lacks the token, asks for it hidden', async () => { + const { io } = await session(menuAnswers(), [TOKEN, '9'], { env: { META_MESSAGING_ACCOUNT_ID: WABA } }); + expect(io.lines).toContain('→ Access Token Configuration'); + expect(io.prompts[0]).toEqual({ text: '\n Enter your META_ACCESS_TOKEN_FROM_SYS_USER (typing is hidden): ', hidden: true }); + }); + + it('with real environment variables but no .env file, uses them without asking (Python ignored them)', async () => { + const { io } = await session(menuAnswers(), ['9'], { env: ENV, envFileFound: false }); + expect(io.lines).not.toContain(' No .env file found in the current directory'); + }); + + it('with a .env that lacks the account id, explains where to find it and asks', async () => { + const { io } = await session(menuAnswers(), [WABA, '9'], { env: { META_ACCESS_TOKEN_FROM_SYS_USER: TOKEN } }); + expect(io.lines).toContain('→ WABA ID Configuration'); + expect(io.prompts[0]!.text).toBe('\n Enter your WABA ID: '); + }); + + it.each([ + ['an empty token', [''], ' ERROR: Access token is required. Exiting...', { META_MESSAGING_ACCOUNT_ID: WABA }], + ['a blank token', [' '], ' ERROR: Access token is required. Exiting...', { META_MESSAGING_ACCOUNT_ID: WABA }], + ['no token (input ended)', [null], ' ERROR: Access token is required. Exiting...', { META_MESSAGING_ACCOUNT_ID: WABA }], + ['an empty account id', [''], ' ERROR: WABA ID is required. Exiting...', { META_ACCESS_TOKEN_FROM_SYS_USER: TOKEN }], + ['no account id (input ended)', [null], ' ERROR: WABA ID is required. Exiting...', { META_ACCESS_TOKEN_FROM_SYS_USER: TOKEN }], + ] as const)('stops with a message for %s, calling nothing', async (_name, inputs, message, env) => { + const { io, meta } = await session([], [...inputs], { env }); + expect(io.lines).toContain(message); + expect(meta.calls).toEqual([]); + }); + + it('trims what is typed for the token and the account id', async () => { + const { meta } = await session(menuAnswers(), [` ${TOKEN} `, ` ${WABA} `, '9'], { env: {} , envFileFound: true }); + expect(meta.calls[0]!.path).toBe('/111'); + expect(meta.calls[0]!.bearer).toBe(true); + }); + }); +}); + +describe('formatLocalTime (Python: str(datetime.fromtimestamp(...)) in local time)', () => { + it.each([ + [0, '1970-01-01 00:00:00'], + [1700000000, '2023-11-14 22:13:20'], + [1800000000, '2027-01-15 08:00:00'], + [1900000000, '2030-03-17 17:46:40'], + [86399, '1970-01-01 23:59:59'], + [1700000000.9, '2023-11-14 22:13:20'], + ])('%s -> %s', (seconds, text) => { + expect(formatLocalTime(seconds)).toBe(text); + }); + + it('follows the machine\'s time zone, as Python did', () => { + const before = process.env.TZ; + process.env.TZ = 'Asia/Tokyo'; + try { + expect(formatLocalTime(1700000000)).toBe('2023-11-15 07:13:20'); + } finally { + process.env.TZ = before ?? 'UTC'; + } + }); + + it.each([Number.NaN, Number.POSITIVE_INFINITY, '1700000000' as unknown as number])('refuses %j instead of printing a wrong date', (value) => { + expect(() => formatLocalTime(value)).toThrow(TypeError); + }); + + it('is what the token screen shows for the issue and expiry times (the recorded screen has the same text)', () => { + const recorded = RUNS.token_full!.lines.join('\n'); + expect(recorded).toContain(`Issued At: ${formatLocalTime(1700000000)} (1700000000)`); + expect(recorded).toContain(`Data Access Expires At: ${formatLocalTime(1800000000)} (1800000000)`); + }); +}); diff --git a/apps/whatsapp/tests/terminalIo.test.ts b/apps/whatsapp/tests/terminalIo.test.ts new file mode 100644 index 00000000..c4416be6 --- /dev/null +++ b/apps/whatsapp/tests/terminalIo.test.ts @@ -0,0 +1,182 @@ +/** + * The keyboard and screen of the operator script, on fake streams. + * + * Python counterpart: `input()` and `getpass.getpass()`. Two behaviours here exist because Node's own `readline.question` got them + * wrong in a probe on Node 22: a line typed before the question is asked is lost, and a question pending when the input ends + * never finishes. + */ +import { PassThrough } from 'node:stream'; +import { describe, expect, it } from 'vitest'; +import { createTerminalIo } from '../scripts/terminalIo'; + +function rig(options: { tty?: boolean } = {}) { + const input = Object.assign(new PassThrough(), { isTTY: options.tty === true }); + const output = new PassThrough(); + let written = ''; + output.on('data', (chunk: Buffer) => { + written += chunk.toString('utf8'); + }); + const io = createTerminalIo(input, output); + return { io, input, written: () => written }; +} + +const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); +const pending = (promise: Promise) => Promise.race([promise, settle().then(() => 'STILL PENDING' as const)]); + +describe('ask', () => { + it('shows the prompt without a line break and returns the line typed', async () => { + const { io, input, written } = rig(); + const answer = io.ask('Name: '); + input.write('Ansari\n'); + expect(await answer).toBe('Ansari'); + expect(written()).toBe('Name: '); + io.close(); + }); + + it('keeps lines typed BEFORE the question is asked, in order (readline.question loses them)', async () => { + const { io, input } = rig(); + input.write('first\nsecond\nthird\n'); + await settle(); + expect(await io.ask('1> ')).toBe('first'); + expect(await io.ask('2> ')).toBe('second'); + expect(await io.ask('3> ')).toBe('third'); + io.close(); + }); + + it('gives each question its own line when answers arrive one at a time', async () => { + const { io, input } = rig(); + const a = io.ask('a> '); + input.write('one\n'); + expect(await a).toBe('one'); + const b = io.ask('b> '); + input.write('two\n'); + expect(await b).toBe('two'); + io.close(); + }); + + it('returns an empty string for a bare Enter, not null', async () => { + const { io, input } = rig(); + const answer = io.ask('> '); + input.write('\n'); + expect(await answer).toBe(''); + io.close(); + }); + + it('answers a pending question with null when the input ends', async () => { + const { io, input } = rig(); + const answer = io.ask('> '); + input.end(); + expect(await pending(answer)).toBeNull(); + io.close(); + }); + + it('answers a pending question with null when the interface is closed (what Ctrl+C does)', async () => { + const { io } = rig(); + const answer = io.ask('> '); + io.close(); + expect(await pending(answer)).toBeNull(); + }); + + // On a real terminal Ctrl+C arrives as the character U+0003, and readline reports it as a SIGINT event instead of ending the line + it('answers a pending question with null on a real Ctrl+C keystroke, and later questions too', async () => { + const { io, input } = rig({ tty: true }); + const answer = io.ask('> '); + input.write('\u0003'); + expect(await pending(answer)).toBeNull(); + expect(await pending(io.ask('again> '))).toBeNull(); + io.close(); + }); + + it('answers with null at once for a question asked after the input has ended', async () => { + const { io, input } = rig(); + input.end(); + await settle(); + expect(await pending(io.ask('> '))).toBeNull(); + io.close(); + }); + + it('still hands over lines typed before the end of input, then null', async () => { + const { io, input } = rig(); + input.write('last\n'); + input.end(); + await settle(); + expect(await io.ask('> ')).toBe('last'); + expect(await pending(io.ask('> '))).toBeNull(); + io.close(); + }); + + it('answers every question waiting when the input ends', async () => { + const { io, input } = rig(); + const a = io.ask('a> '); + const b = io.ask('b> '); + input.end(); + expect(await pending(Promise.all([a, b]))).toEqual([null, null]); + io.close(); + }); + + it('can be closed twice', () => { + const { io } = rig(); + io.close(); + expect(() => io.close()).not.toThrow(); + }); +}); + +describe('askHidden', () => { + it('returns the line typed and does not echo it back', async () => { + const { io, input, written } = rig(); + const answer = io.askHidden('Token: '); + input.write('SECRET-TYPED-VALUE\n'); + expect(await answer).toBe('SECRET-TYPED-VALUE'); + expect(written()).not.toContain('SECRET-TYPED-VALUE'); + io.close(); + }); + + it('shows the prompt, and ends its line afterwards so the next text starts on a fresh one', async () => { + const { io, input, written } = rig(); + const answer = io.askHidden('Token: '); + input.write('x\n'); + await answer; + expect(written()).toBe('Token: \n'); + io.close(); + }); + + it('echoes again for the next, ordinary question', async () => { + const { io, input, written } = rig({ tty: true }); + const hidden = io.askHidden('Token: '); + input.write('HIDDENPART\n'); + await hidden; + const plain = io.ask('Name: '); + input.write('VISIBLEPART\n'); + await plain; + expect(written()).not.toContain('HIDDENPART'); + expect(written()).toContain('VISIBLEPART'); + io.close(); + }); + + it('returns null when the input ends during the hidden question, and still ends the prompt line', async () => { + const { io, input, written } = rig(); + const answer = io.askHidden('Token: '); + input.end(); + expect(await pending(answer)).toBeNull(); + expect(written()).toBe('Token: \n'); + io.close(); + }); + + it('keeps a line typed ahead for the hidden question too', async () => { + const { io, input } = rig(); + input.write('typed-ahead\n'); + await settle(); + expect(await io.askHidden('Token: ')).toBe('typed-ahead'); + io.close(); + }); +}); + +describe('print', () => { + it('writes the text and one line break', () => { + const { io, written } = rig(); + io.print('hello'); + io.print(''); + expect(written()).toBe('hello\n\n'); + io.close(); + }); +}); diff --git a/apps/whatsapp/tsconfig.json b/apps/whatsapp/tsconfig.json index d265b0ce..64579e7d 100644 --- a/apps/whatsapp/tsconfig.json +++ b/apps/whatsapp/tsconfig.json @@ -10,5 +10,5 @@ "isolatedModules": true, "verbatimModuleSyntax": true }, - "include": ["src/**/*.ts", "tests/**/*.ts", "tsdown.config.ts", "vitest.config.ts"] + "include": ["src/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts", "tsdown.config.ts", "vitest.config.ts"] } diff --git a/codev/projects/358-whatsapp-typescript/358-phase_7-iter1-claude.txt b/codev/projects/358-whatsapp-typescript/358-phase_7-iter1-claude.txt new file mode 100644 index 00000000..3b91052d --- /dev/null +++ b/codev/projects/358-whatsapp-typescript/358-phase_7-iter1-claude.txt @@ -0,0 +1,36 @@ +NOTE: This is an agent self-review written by the implementing agent. It is NOT the output of a `consult` run; no external model was consulted (owner instruction: "don't consult; just self review"). + +Phase 7 (operator script, hand-off, rollback note): apps/whatsapp/scripts/{metaSubscriptionsText,metaSubscriptions,terminalIo,checkMetaSubscriptions}.ts, tests/{metaScript,metaCalls,terminalIo}.test.ts, tests/helpers/scriptedIo.ts, tests/fixtures/{generate_meta_script_oracle.py,metaScriptOracle.ts}; edits to package.json (script `meta:subscriptions`), tsconfig.json, .env.example, README.md, codev/resources/arch.md, legacy/whatsapp/README.md. + +VERIFIED (by running it) +- From a cold cache: `pnpm exec turbo run lint typecheck test build --filter ansari-whatsapp... --force` exit 0, 4 tasks. Test run: 26 files, 1100 tests (892 before this phase), all passing. +- The three new test files: 208 tests passing (113+ for the screens and flows, plus the call layer and the keyboard layer). +- The script is not in the service bundle: `dist/index.mjs` contains neither `metaSubscriptions` nor `checkMeta` (tsdown entry is src/index.ts only). +- Screens compared with the Python script's own output: 38 recorded runs (every show/subscribe/unsubscribe flow, the menu, the two long text screens) generated by running the real Python functions against canned Meta answers (tests/fixtures/generate_meta_script_oracle.py). Wording differs only on the lines the test's `normalise` lists (error texts), plus the 2 example callback URLs v2 -> v3 in the long text. +- A live run against the real Graph API with a FAKE token (read-only calls): failed with Meta's own error, no token in any output. +- Mutation controls: first run 47 caught, 2 not caught, 7 skipped (broken patterns). Fixed, second run on the corrected patterns: 9 controls, 9 caught, 0 not caught, 0 skipped, 0 restore mismatches (results file counted, not eyeballed); the first run's 47 other controls stay caught (the sources they touch were not changed apart from a comment). They cover: token cut out of error text (script's own errors and network errors), subscribe sent as GET, unsubscribe sent as POST, wrong account in a path, scopes not listed, option 5 re-listing only on success, the phone-id default, and the Ctrl+C behaviour. +- Two real test gaps found by the mutation run and fixed: a phone entry with no `id` must print `None` (Python's recorded output, new oracle case); and Ctrl+C. Probing readline showed my SIGINT handler was redundant: with no listener readline closes itself and a pending question gets null; WITH a listener that does nothing, Ctrl+C is swallowed. I removed the handler and added a test that sends a real Ctrl+C character on a terminal-mode stream. A control that adds back a do-nothing listener is caught. +- Another gap found while fixing the patterns: the script's own error path (`Error: ...` via `withoutToken`) had no test that the token is cut out. Added one (a time field that holds the token); the control that removes the cleaning is caught. + +FINDINGS / DIFFERENCES FROM PYTHON +- Python matched the unsubscribe safety check by app NAME; the port matches by ID (a renamed app no longer blocks it; an app that only shares the name no longer passes). Both have tests. +- The Python script printed the first 20 and last 10 characters of the token at start-up (check_meta_subscriptions.py:721). The port never prints any part of it: banner is `Access Token: set (N characters, never shown)`. It is typed hidden when asked for, and removed from every error text. +- Every Graph call has a 20 s timeout and refuses redirects (a redirect would carry the Authorization header elsewhere). The debug_token call also carries the token as `input_token`, which is Meta's design for that endpoint. +- Node's readline.question loses typed-ahead lines and never answers when input ends (probed); hence the small `Io` layer in terminalIo.ts. + +DECISIONS +- RELEASE.md is NOT changed: the live configuration still runs the Python service until the owner repoints staging; the cutover steps are listed below instead. legacy/whatsapp/README.md got a short rollback note (repoint at legacy/whatsapp/Dockerfile, callback back to /whatsapp/v2); the Python image and Dockerfile are unchanged. +- The legacy dashboard notes for META_MESSAGING_ACCOUNT_ID and META_ANSARI_APP_ID were moved into apps/whatsapp/.env.example (the script reads the first; the second is only a reference). + +NOT VERIFIED +- No real token was used and nothing was subscribed or unsubscribed on Meta: the subscribe/unsubscribe calls are proven only against a stand-in (method, path, bearer, no app named) and the read-only live call with a fake token. +- Part B (the owner's cutover) was not done and I cannot do it: no Railway token in this session, Docker daemon not running (image never built), nothing touched on Meta. Owner checklist (names only, no values): + 1. Compare the staging variables with apps/whatsapp/.env.example. + 2. Booleans use only true false True False 1 0 (the TypeScript service refuses yes/on/TRUE). + 3. Repoint staging at apps/whatsapp/Dockerfile. + 4. Change Meta's callback URL to /whatsapp/v3 and run the handshake again. + 5. Smoke test: a visible-phone user, a hidden-phone user, a long answer, maintenance mode, the apps/auth refusal. + 6. Suggest running `pnpm whatsapp meta:subscriptions` option 3 (read-only) first. +- The new CI job has not run on GitHub. + +VERDICT: COMMENT diff --git a/codev/resources/arch.md b/codev/resources/arch.md index ce41e88c..a927a016 100644 --- a/codev/resources/arch.md +++ b/codev/resources/arch.md @@ -66,7 +66,7 @@ The repo is a pnpm workspace of `apps/*` and `packages/*`, driven by Turborepo. **The WhatsApp service (`legacy/whatsapp`, spec 321).** A Python (uv, FastAPI) service outside the pnpm/turbo graph, with its own CI job (`whatsapp`) and its own Dockerfile built from the repo root (`-f legacy/whatsapp/Dockerfile .`). It identifies a user by BSUID only (`from_user_id`; it never forwards, stores or logs the phone number; it reads it only when the off-by-default `META_REPLY_BY_PHONE` setting is on, only to address a reply to a Meta test number, and the service refuses to start with it in production), asks apps/auth for a JWT (`POST /api/whatsapp/session`, header `Authorization: Bearer `, body `{bsuid}`, per issue #329: the route does not exist yet, so sign-in is mocked in practice; the token is cached per BSUID for 14 minutes; each refusal is typed: 401 is our key (Sentry `auth_key_rejected`), 403 a banned user, 429 a spent per-user budget with a local cool-down, 500 an outage, none retried per message; one re-exchange and one retry on an apps/api 401). Sign-in runs in the background task, after Meta has its 200, so a slow apps/auth cannot cause a redelivery. It refuses to start without `META_ANSARI_APP_SECRET`, or with any `MOCK_*` switch outside `DEPLOYMENT_TYPE=local`. It then calls apps/api with that JWT: `GET/POST/DELETE /api/v2/threads` and the SSE `POST /api/v2/threads/{id}/chat`. Each user has one thread (`source: whatsapp`), deleted and recreated after `WHATSAPP_CHAT_RETENTION_HOURS` (3) of silence; a race between two first messages can create two (accepted, swept by hand). It logs one JSON line per entry on stdout with only `request_id` (Railway indexes `@request_id:`), and never logs phone numbers, BSUIDs, message text or the webhook verify token. It reads `PORT` (default 8001) and its Railway settings are recorded in `legacy/whatsapp/railway.toml` (not read by Railway). Its environments share a Meta setup: each environment needs its own Meta app credentials, and the staging `!d ` prefix keeps a developer's local messages from being answered by staging. -**The TypeScript WhatsApp service (`apps/whatsapp`, issue #358).** A workspace member (Node 22, Express 5, Zod 4, Vitest, tsdown) that ports `legacy/whatsapp`; staging still runs the Python one until the cutover. Same contract: BSUID-only identity, the same apps/auth exchange and apps/api thread/chat calls, one thread per user, the same notices. It serves `GET /`, `GET|POST /whatsapp/v3` (v3, not v2: the Meta callback URL changes at cutover). A POST is read as raw bytes, signature-checked (`timingSafeEqual`) BEFORE the JSON is parsed, answered 200 (unless `ALWAYS_RETURN_OK_TO_META` is off, tests only), and only then handled in `BackgroundTasks`, the one place that catches, logs and reports a failure, so a slow sign-in cannot cause a Meta redelivery. Decisions live in `ConversationManager.triage` (maintenance, staging `!d ` filter, message age, type) and the HTTP layer only maps them to statuses. Errors reach Sentry through an injected `ErrorReporter` function (`src/errorReporter.ts`; `src/sentry.ts` is the real one, scrubbed like apps/auth: method, path without query, three headers, no breadcrumbs, no trace sampling). Settings are the Python names, validated at start-up by `src/config.ts`; true/false switches accept only `true false True False 1 0`. Its image is built like apps/auth's (`apps/whatsapp/Dockerfile`, repo-root context, `dist/index.mjs`) and its variables are in `turbo.json` `globalEnv`, checked by `tests/repoWiring.test.ts`. The root `pnpm dev` leaves it out (it needs its own `.env`); use `pnpm whatsapp dev`. CI job: `whatsapp service`; the job named `whatsapp` is still the Python one. +**The TypeScript WhatsApp service (`apps/whatsapp`, issue #358).** A workspace member (Node 22, Express 5, Zod 4, Vitest, tsdown) that ports `legacy/whatsapp`; staging still runs the Python one until the cutover. Same contract: BSUID-only identity, the same apps/auth exchange and apps/api thread/chat calls, one thread per user, the same notices. It serves `GET /`, `GET|POST /whatsapp/v3` (v3, not v2: the Meta callback URL changes at cutover). A POST is read as raw bytes, signature-checked (`timingSafeEqual`) BEFORE the JSON is parsed, answered 200 (unless `ALWAYS_RETURN_OK_TO_META` is off, tests only), and only then handled in `BackgroundTasks`, the one place that catches, logs and reports a failure, so a slow sign-in cannot cause a Meta redelivery. Decisions live in `ConversationManager.triage` (maintenance, staging `!d ` filter, message age, type) and the HTTP layer only maps them to statuses. Errors reach Sentry through an injected `ErrorReporter` function (`src/errorReporter.ts`; `src/sentry.ts` is the real one, scrubbed like apps/auth: method, path without query, three headers, no breadcrumbs, no trace sampling). Settings are the Python names, validated at start-up by `src/config.ts`; true/false switches accept only `true false True False 1 0`. Its image is built like apps/auth's (`apps/whatsapp/Dockerfile`, repo-root context, `dist/index.mjs`) and its variables are in `turbo.json` `globalEnv`, checked by `tests/repoWiring.test.ts`. The root `pnpm dev` leaves it out (it needs its own `.env`); use `pnpm whatsapp dev`. `apps/whatsapp/scripts/` holds the operator menu `pnpm whatsapp meta:subscriptions` (Meta subscription check; run by hand, never bundled into the image, the token never printed, and its unsubscribe safety check matches the token's app by ID, where the Python script matched by name). CI job: `whatsapp service`; the job named `whatsapp` is still the Python one. **Health endpoint.** `/api/health` returns `service: 'ansari-backend'` — a pinned public contract (spec 3), unrelated to the `apps/api` directory name. It performs a live DB ping with a 2s cap, so a cold process can legitimately 503 on its first request. diff --git a/legacy/whatsapp/README.md b/legacy/whatsapp/README.md index bb8c479a..97c25188 100644 --- a/legacy/whatsapp/README.md +++ b/legacy/whatsapp/README.md @@ -124,6 +124,12 @@ Only the facts below come from this repo. The dashboard settings themselves are The Docker image has not been built or run by the author of this change. Do that first when preparing a deploy. +### Rolling back from `apps/whatsapp` + +The TypeScript port (`apps/whatsapp`, issue #358) is meant to replace this service. This image and Dockerfile are unchanged, so +rolling back is a settings change only: point the Railway service back at `legacy/whatsapp/Dockerfile` and set Meta's callback +URL back to `https:///whatsapp/v2` (the port serves `/whatsapp/v3`). + ### Staging smoke test 1. `GET /` returns 200. From 5b3e835e22a2d0e4e5b30bc3d9d1a8464702dc8f Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 08:42:20 +0200 Subject: [PATCH 078/435] chore(porch): 358 implement build-complete --- codev/projects/358-whatsapp-typescript/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index bf1a27df..e6af2f2c 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-11T06:00:56.257Z' +updated_at: '2026-11-11T06:42:19.960Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' From b9edff6b920b6efec88bd1d2c9af1ecb5d45d161 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 08:42:43 +0200 Subject: [PATCH 079/435] =?UTF-8?q?chore(porch):=20358=20all=20plan=20phas?= =?UTF-8?q?es=20complete=20=E2=86=92=20review?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codev/projects/358-whatsapp-typescript/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index e6af2f2c..1e0c2bfa 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -1,7 +1,7 @@ id: '358' title: whatsapp-typescript protocol: spir -phase: implement +phase: review plan_phases: - id: phase_1 title: Scaffold apps/whatsapp, config, masked logging @@ -23,8 +23,8 @@ plan_phases: status: complete - id: phase_7 title: Staging redeploy, smoke test and legacy rollback note - status: in_progress -current_plan_phase: phase_7 + status: complete +current_plan_phase: null gates: spec-approval: status: approved @@ -37,10 +37,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-11T06:42:19.960Z' +updated_at: '2026-11-11T06:42:43.146Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -66,3 +66,5 @@ context_refreshes: - boundary: plan-phase:phase_7 at: '2026-11-11T05:19:06.565Z' acknowledged_at: '2026-11-11T06:00:56.255Z' + - boundary: enter:review + at: '2026-11-11T06:42:43.146Z' From 720a7db75849c00602afc014250b89de8606d9e2 Mon Sep 17 00:00:00 2001 From: OdyAsh Date: Wed, 11 Nov 2026 08:42:52 +0200 Subject: [PATCH 080/435] chore(porch): 358 acknowledge context refresh --- codev/projects/358-whatsapp-typescript/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/358-whatsapp-typescript/status.yaml b/codev/projects/358-whatsapp-typescript/status.yaml index 1e0c2bfa..f5644072 100644 --- a/codev/projects/358-whatsapp-typescript/status.yaml +++ b/codev/projects/358-whatsapp-typescript/status.yaml @@ -40,7 +40,7 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-10T12:39:08.669Z' -updated_at: '2026-11-11T06:42:43.146Z' +updated_at: '2026-11-11T06:42:52.694Z' context_refreshes: - boundary: enter:plan at: '2026-11-10T13:37:26.336Z' @@ -68,3 +68,4 @@ context_refreshes: acknowledged_at: '2026-11-11T06:00:56.255Z' - boundary: enter:review at: '2026-11-11T06:42:43.146Z' + acknowledged_at: '2026-11-11T06:42:52.693Z' From bbc64002a2ec101d145dbc4c7ef19d42ed316905 Mon Sep 17 00:00:00 2001 From: Younes Abouelnagah Date: Wed, 11 Nov 2026 13:03:35 +0400 Subject: [PATCH 081/435] fix(mcp): scope the dompurify override, drop the @hono/node-server one, and document Refresh tools - dompurify 3.4.17 now applies only under @a2ui/markdown-it, which pins 3.4.11 exactly. The comment names GHSA-cg2g-xh64-v4q7 and GHSA-mrv2-3pqr-j5jr, so it is clear when the override can go. - The @hono/node-server override is removed: apps/mcp and @saga-a2ui/mcp both pin 2.1.5, so it changed nothing. - The README explains 'Unable to reach' after the first deploy of the v1 address: ChatGPT needs Refresh tools once; Claude needs a new conversation. - The README's SAGA paragraph names the subpaths and exports in use now, and says the siblings are versioned independently. Co-Authored-By: Claude Opus 5.5 --- apps/mcp/README.md | 18 ++++++++++++++---- apps/mcp/docs/show-me-ansari-mcp.html | 5 ++--- pnpm-lock.yaml | 3 +-- pnpm-workspace.yaml | 7 ++++--- 4 files changed, 21 insertions(+), 12 deletions(-) diff --git a/apps/mcp/README.md b/apps/mcp/README.md index 30bf3eb1..018ce5a6 100644 --- a/apps/mcp/README.md +++ b/apps/mcp/README.md @@ -46,7 +46,7 @@ SAGA is installed from the public npm registry: the stack `@saga-a2ui/react-mcp- `@saga-a2ui/core@1.0.0`, `@saga-a2ui/components@1.0.0`, `@saga-a2ui/mcp@1.0.2` and `@saga-a2ui/react@1.0.0`. SAGA versions its packages independently, so the siblings need not share the stack's version; each resolves to exactly the version the stack pins. No private registry, credential, SDK tarball, SDK workspace link or SDK-package override is involved, and the manifest pins an exact version rather than a tag or range. -The root `pnpm-workspace.yaml` keeps the SDK's documented `dompurify` and `@hono/node-server` overrides. +The root `pnpm-workspace.yaml` pins `dompurify` to 3.4.17 for `@a2ui/markdown-it` only, which otherwise pins 3.4.11 (GHSA-cg2g-xh64-v4q7, GHSA-mrv2-3pqr-j5jr). The card's address names its compatibility line, `ui://views/answer-card.v1.html` (`VIEW_MAJOR` in `src/server/view-artifact.ts`), not its bytes: every compatible release is served at the same address, and only a change an already-loaded card cannot handle increases it. `pnpm check:release --target beta` checks the pinned release against the registry and the lockfile, including that every SAGA package resolves to @@ -56,9 +56,10 @@ corresponding gate before any build or deployment. The application depends on one SAGA package, the stack `@saga-a2ui/react-mcp-stack`, plus React and React DOM, and imports only its subpaths: `/faithful-card` (`FaithfulCardApp`, `startFaithfulCardApp`, and the definition's one `.result(...)` reader that reads the whole delivered result, `useHostLink`, `readingProfile`) and its stylesheet in the view; `/content-policy` (`createContentPolicy`, `embedContentPolicy`) -in the build; `/server` (`registerPublicOperation`, `operationViewFromHtml`, `createServerBudgets`, `attachRequestLifetime`) in the -MCP server. The browser bundle holds no `/server` module. The stack's exact-version siblings come from the same release, -and its installed tree includes `@saga-a2ui/components` and `markdown-it`. SAGA owns its A2UI and Zod 3 dependency +in the build; `/server` (`registerPublicOperation`, `operationViewFromHtml`, the `RequestLifetime` type) and `/server/http` +(`createMcpFetchApp`) in the MCP server. The browser bundle holds no `/server` module. The stack pins each sibling to one exact +version, which need not be its own (SAGA versions its packages independently), and its installed tree includes +`@saga-a2ui/components` and `markdown-it`. SAGA owns its A2UI and Zod 3 dependency context; the application uses Zod 4 for MCP. Do not add direct `@a2ui/react` or `@a2ui/web_core` dependencies or cast between their schema types. The artwork owner has authorized contribution and redistribution with the application; see `assets/NOTICE.md`. @@ -223,3 +224,12 @@ Hono runs on Node through `@hono/node-server`; the official `@modelcontextprotoc ## MCP compatibility The tool retains the legacy server's `answer_islamic_question` name, detailed description and input help, and `readOnlyHint: true` / `openWorldHint: true` annotations. It accepts 1–4,000 characters, matching the Ansari API. The earlier experimental RC exposed `ask_ansari`; a deployment owner must refresh host discovery when adopting this tool name. The endpoint remains `/mcp`. Replacing the existing `mcp.ansari.chat` service and changing its DNS are separate rollout actions. + +### "Unable to reach" after a deploy + +The card is served at `ui://views/answer-card.v1.html` for every compatible release. Builds before SAGA 1.0 used a different address on every deploy, so a host connection created or last refreshed before this change still names an address the server no longer serves, and the card shows "Unable to reach" (the server answers that read with JSON-RPC `-32602`). + +- **ChatGPT:** in Settings → Apps (Plugins), open the app and choose **Refresh tools** once after the first deploy of this version. Later compatible deploys keep the address, so no further refresh is needed. +- **Claude:** start a new conversation. A conversation that loaded the card before the deploy may keep the old address. + +A change an already-loaded card cannot handle increases `VIEW_MAJOR` and moves the address to `v2`; refresh host connections the same way after that deploy. diff --git a/apps/mcp/docs/show-me-ansari-mcp.html b/apps/mcp/docs/show-me-ansari-mcp.html index a19c9bdf..f4227ad0 100644 --- a/apps/mcp/docs/show-me-ansari-mcp.html +++ b/apps/mcp/docs/show-me-ansari-mcp.html @@ -56,9 +56,8 @@ Siblings pinned by the stack: core 1.0.0 · components 1.0.0 mcp 1.0.2 · react 1.0.0 -SDK overrides: dompurify 3.4.17 - @hono/node-server 2.1.5 -@a2ui/markdown-it override: 0.2.1

The app imports only stack subpaths. SAGA is installed from the public npm registry: the stack @saga-a2ui/react-mcp-stack@1.0.1 plus the siblings it pins exactly. SAGA versions its packages independently, so the siblings need not share the stack’s version; each resolves to exactly the version the stack pins, and the repository root’s one committed lockfile records their registry integrity. No private registry, credential, SDK tarball, SDK workspace link or SDK-package override is involved. The root pnpm-workspace.yaml keeps the SDK’s documented dompurify and @hono/node-server overrides.

→
Build-time content policy

Produce self-contained HTML

Vite + single-file plugin
+Security override: @a2ui/markdown-it>dompurify 3.4.17
+@a2ui/markdown-it override: 0.2.1

The app imports only stack subpaths. SAGA is installed from the public npm registry: the stack @saga-a2ui/react-mcp-stack@1.0.1 plus the siblings it pins exactly. SAGA versions its packages independently, so the siblings need not share the stack’s version; each resolves to exactly the version the stack pins, and the repository root’s one committed lockfile records their registry integrity. No private registry, credential, SDK tarball, SDK workspace link or SDK-package override is involved. The root pnpm-workspace.yaml pins dompurify to 3.4.17 for @a2ui/markdown-it only, which otherwise pins 3.4.11 (GHSA-cg2g-xh64-v4q7, GHSA-mrv2-3pqr-j5jr).

→
Build-time content policy

Produce self-contained HTML

Vite + single-file plugin
   React + card code + CSS
   embedded Kitab + floral assets
   application + SDK identity
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 41e55152..dd632898 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -18,8 +18,7 @@ catalogs:
 
 overrides:
   '@a2ui/react@0.13.0>@a2ui/markdown-it': 0.2.1
-  dompurify: 3.4.17
-  '@hono/node-server': 2.1.5
+  '@a2ui/markdown-it>dompurify': 3.4.17
   sharp: ^0.35.0
   postcss: ^8.5.23
   esbuild: ^0.28.1
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 9d77ee2c..9a04f6d3 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -52,9 +52,10 @@ overrides:
   # Compatibility: A2UI React 0.13 needs adapter 0.2.1 (0.2.2 requires web_core 0.14).
   "@a2ui/react@0.13.0>@a2ui/markdown-it": "0.2.1"
 
-  # The SAGA SDK's documented overrides for its consumers; apps/mcp is their only consumer here.
-  dompurify: 3.4.17
-  "@hono/node-server": 2.1.5
+  # Security: @a2ui/markdown-it 0.2.1 (via the SAGA stack, apps/mcp) pins dompurify 3.4.11 exactly, which
+  # GHSA-cg2g-xh64-v4q7 and GHSA-mrv2-3pqr-j5jr affect (fixed in 3.4.17). Drop this once the adapter pins a
+  # patched dompurify.
+  "@a2ui/markdown-it>dompurify": "3.4.17"
 
   # Security overrides for transitive Dependabot alerts.
   # next@15.5 declares optionalDependencies.sharp ^0.34.3 — GHSA-f88m-g3jw-g9cj

From 58f669d7ce772907a723e2e31cabbac60151b302 Mon Sep 17 00:00:00 2001
From: Younes Abouelnagah 
Date: Wed, 11 Nov 2026 13:03:35 +0400
Subject: [PATCH 082/435] test(mcp): read the listed card address, and clear
 only the broken-bundle case's own errors

- The address check takes the address the server lists and compares it with
  VIEW_MAJOR, instead of comparing a literal with itself.
- After the broken-bundle case, only the SyntaxError that case caused is
  cleared. Errors from earlier cases still fail the run.
- Turbo's test task depends on build and build:worker again, without outputs.

Co-Authored-By: Claude Opus 5.5 
---
 apps/mcp/test/browser.ts | 12 ++++++++----
 apps/mcp/turbo.json      |  7 +++----
 2 files changed, 11 insertions(+), 8 deletions(-)

diff --git a/apps/mcp/test/browser.ts b/apps/mcp/test/browser.ts
index de564701..906ee0bf 100644
--- a/apps/mcp/test/browser.ts
+++ b/apps/mcp/test/browser.ts
@@ -9,7 +9,7 @@ import {chromium, type Frame, type Page} from '@playwright/test';
 import {build, preview} from 'vite';
 import {createHttpServer as createBaseHttpServer} from '../src/node/http-server.ts';
 import {stampHtmlRevision} from '../src/server/operation-log.ts';
-import {VIEW_DIAGNOSTICS_PATH, VIEW_FILENAME, prepareAnswerView} from '../src/server/view-artifact.ts';
+import {VIEW_DIAGNOSTICS_PATH, VIEW_FILENAME, VIEW_MAJOR, prepareAnswerView} from '../src/server/view-artifact.ts';
 import {parseViewReport} from '../src/server/view-report.ts';
 import {ANSWER_A, ANSWER_B, ANSWER_C, ANSWER_HOSTILE, ATTRIBUTION_CASES, QUESTION_A, QUESTION_B} from './react-answers.ts';
 
@@ -73,11 +73,13 @@ async function main() {
   await client.connect(transport);
 
   // ---- The served resource: exact bytes, identity, resource rules ---------------------------------
-  const viewUri = 'ui://views/answer-card.v1.html';
+  // The one address the server lists, read back: it must name the card's compatibility line, never its bytes.
+  const listed = (await client.listResources()).resources.map(entry => entry.uri);
+  const viewUri = listed[0];
   const resource = await client.readResource({uri: viewUri});
   const bytes = String((resource.contents[0] as {text: string}).text);
   check('resource:exact-served-bytes', () => assert.equal(bytes, stampHtmlRevision(html)));
-  check('resource:uri-names-the-compatibility-line', () => assert.equal(viewUri, `ui://views/${VIEW_FILENAME.replace(/\.html$/, '')}.v1.html`));
+  check('resource:uri-names-the-compatibility-line', () => assert.deepEqual(listed, [`ui://views/${VIEW_FILENAME.replace(/\.html$/, '')}.v${VIEW_MAJOR}.html`]));
   const meta = (resource.contents[0] as any)._meta;
   check('resource:closed-csp-no-origins', () => assert.deepEqual(meta.ui.csp, {connectDomains: [], resourceDomains: [], frameDomains: [], baseUriDomains: []}));
   const callTool = (question: string) => client.callTool({name: 'answer_islamic_question', arguments: {question}});
@@ -847,6 +849,7 @@ async function main() {
   const bundle = /(';
+    const res = await call(method, { clientHeader: raw });
+    expect(res.status).toBe(200);
+    expect(captureMessage).toHaveBeenCalledTimes(1);
+    expect(captureMessage).toHaveBeenCalledWith('mcp-complete client mismatch', {
+      level: 'warning',
+      tags: { client: KEY_CLIENT, header_client: 'invalid' },
+    });
+    expect(messagesCaptured()).not.toContain('invalid X-Ansari-Client header');
+    expect(JSON.stringify([captureMessage.mock.calls, setTag.mock.calls])).not.toContain('RAWMARKER');
+    const threads = await client.query<{ client: string }>('SELECT client FROM threads');
+    expect(threads.rows).toEqual([{ client: KEY_CLIENT }]);
+  });
+
+  it('scenario 5: a matching header (any case) → no event', async () => {
+    authAnswers(200, VALID);
+    const res = await call(method, { clientHeader: ' Ansari-MCP-Production ' });
+    expect(res.status).toBe(200);
+    expect(captureMessage).not.toHaveBeenCalled();
+  });
+
+  it("scenario 6: ?src=evil → the key's client, no event", async () => {
+    authAnswers(200, VALID);
+    const res = await call(method, { src: 'evil' });
+    expect(res.status).toBe(200);
+    const threads = await client.query<{ client: string }>('SELECT client FROM threads');
+    expect(threads.rows).toEqual([{ client: KEY_CLIENT }]);
+    expect(captureMessage).not.toHaveBeenCalled();
+    expect(setTag).not.toHaveBeenCalledWith('client', 'evil');
+  });
+
+  it.each([
+    ['a 500', 500, { message: 'Internal error' }],
+    ['a 429', 429, { message: 'Too many requests' }],
+    ['a 200 that is not JSON', 200, 'proxy error'],
+    ['a 200 of the wrong shape', 200, { ok: true }],
+    ['valid: true missing key_id', 200, { valid: true, client_id: KEY_CLIENT }],
+    ['valid: true missing client_id', 200, { valid: true, key_id: KEY_ID }],
+    ['valid: true with an off-pattern client_id', 200, { valid: true, client_id: 'claude-skill', key_id: KEY_ID }],
+    ['a refusal carrying an extra field', 200, { valid: false, reason: 'revoked' }],
+  ])('scenario 7: %s → 503, no thread, no facilitator call', async (_label, status, body) => {
+    authAnswers(status, body);
+    const res = await call(method);
+    expect(res.status).toBe(503);
+    expect(res.json()).toStrictEqual(UNAVAILABLE);
+    await expectNothingPersisted();
+    expect(verdictsRecorded()).toEqual(['unverified']);
+    expect(consoleSpies[1]).toHaveBeenCalledWith('[ai-skill] mcp-complete key verify unavailable', { status });
+    // Enforce mode fails closed quietly: the warning is log-only's.
+    expect(captureMessage).not.toHaveBeenCalled();
+  });
+
+  it('scenario 7: a network error → 503, the status null in the warning', async () => {
+    fetchMock.mockRejectedValue(new TypeError('fetch failed'));
+    const res = await call(method);
+    expect(res.status).toBe(503);
+    expect(res.json()).toStrictEqual(UNAVAILABLE);
+    await expectNothingPersisted();
+    expect(consoleSpies[1]).toHaveBeenCalledWith('[ai-skill] mcp-complete key verify unavailable', { status: null });
+  });
+
+  it(`scenario 7: apps/auth slower than ${AUTH_SERVICE_TIMEOUT_MS} ms → 503 at the timeout, not before`, async () => {
+    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+    // Node's AbortSignal.timeout runs on an internal timer fake timers cannot
+    // drive, so stand in one built on setTimeout and check the delay it is given.
+    const timeout = vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms: number) => {
+      const controller = new AbortController();
+      setTimeout(() => controller.abort(new DOMException('timed out', 'TimeoutError')), ms);
+      return controller.signal;
+    });
+    fetchMock.mockImplementation(
+      (_url: URL, init: RequestInit) =>
+        new Promise((_resolve, reject) => {
+          init.signal?.addEventListener('abort', () => reject(init.signal?.reason));
+        })
+    );
+
+    let settled = false;
+    const pending = call(method).finally(() => {
+      settled = true;
+    });
+    await vi.advanceTimersByTimeAsync(AUTH_SERVICE_TIMEOUT_MS - 1);
+    expect(settled).toBe(false);
+    await vi.advanceTimersByTimeAsync(1);
+    const res = await pending;
+    vi.useRealTimers();
+
+    expect(res.status).toBe(503);
+    expect(res.json()).toStrictEqual(UNAVAILABLE);
+    expect(timeout).toHaveBeenCalledWith(AUTH_SERVICE_TIMEOUT_MS);
+    await expectNothingPersisted();
+  });
+
+  it('scenario 9: the per-IP cap answers 429 before any verify', async () => {
+    mockCheckRateLimit.mockReturnValue({ allowed: false, retryAfter: 17 });
+    authAnswers(200, VALID);
+    const response = method === 'POST' ? await POST(postRequest()) : await GET(getRequest());
+    expect(response.status).toBe(429);
+    expect(response.headers.get('Retry-After')).toBe('17');
+    expect(fetchMock).not.toHaveBeenCalled();
+    await expectNothingPersisted();
+  });
+
+  it('an error other than apps/auth being unavailable falls into the route catch (500) and leaves no thread', async () => {
+    vi.stubEnv('AUTH_URL', '');
+    resetEnvCache();
+    const res = await call(method);
+    expect(res.status).toBe(500);
+    expect(fetchMock).not.toHaveBeenCalled();
+    expect(captureException).toHaveBeenCalledTimes(1);
+    await expectNothingPersisted();
+  });
+});
+
+describe('scenario 8: the key is checked before the body', () => {
+  it('a valid key with an invalid POST body → 400', async () => {
+    authAnswers(200, VALID);
+    const res = await call('POST', { body: { messages: [] } });
+    expect(res.status).toBe(400);
+    expect(fetchMock).toHaveBeenCalledTimes(1);
+    await expectNothingPersisted();
+  });
+
+  it('a valid key with no ?q= → 400', async () => {
+    authAnswers(200, VALID);
+    const res = await call('GET', { query: null });
+    expect(res.status).toBe(400);
+    await expectNothingPersisted();
+  });
+
+  it('no key with an invalid POST body → 401 (the body is never read)', async () => {
+    const request = postRequest({ authorization: null, body: { messages: [] } });
+    const read = vi.spyOn(request, 'json');
+    const response = await POST(request);
+    expect(response.status).toBe(401);
+    expect(await response.json()).toStrictEqual(UNAUTHORIZED);
+    expect(read).not.toHaveBeenCalled();
+  });
+
+  it('no key with no ?q= → 401', async () => {
+    const res = await call('GET', { authorization: null, query: null });
+    expect(res.status).toBe(401);
+    expect(res.json()).toStrictEqual(UNAUTHORIZED);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Log-only mode (the rollout week)
+
+describe.each(['POST', 'GET'] as const)('%s, log-only mode (scenario 10)', (method) => {
+  beforeEach(() => {
+    setEnv('log-only');
+  });
+
+  it('missing → served 200, verdict recorded, attributed by the header as today', async () => {
+    const res = await call(method, { authorization: null, clientHeader: 'muslimpedia' });
+    expect(res.status).toBe(200);
+    expect(fetchMock).not.toHaveBeenCalled();
+    expect(verdictsRecorded()).toEqual(['missing']);
+    expect(verdictLines()).toEqual([{ verdict: 'missing' }]);
+    const threads = await client.query<{ client: string | null }>('SELECT client FROM threads');
+    expect(threads.rows).toEqual([{ client: 'muslimpedia' }]);
+    expect(captureMessage).not.toHaveBeenCalled();
+  });
+
+  it('missing with ?src= → attributed by ?src= as today', async () => {
+    const res = await call(method, { authorization: null, src: 'jbprompt' });
+    expect(res.status).toBe(200);
+    const threads = await client.query<{ client: string | null }>('SELECT client FROM threads');
+    expect(threads.rows).toEqual([{ client: 'jbprompt' }]);
+  });
+
+  it('refused → served 200, verdict recorded, no warning', async () => {
+    authAnswers(200, { valid: false });
+    const res = await call(method);
+    expect(res.status).toBe(200);
+    expect(verdictsRecorded()).toEqual(['refused']);
+    expect(verdictLines()).toEqual([{ verdict: 'refused' }]);
+    const threads = await client.query<{ client: string | null }>('SELECT client FROM threads');
+    expect(threads.rows).toEqual([{ client: null }]);
+    expect(captureMessage).not.toHaveBeenCalled();
+  });
+
+  it.each([
+    ['a 500', () => authAnswers(500, { message: 'Internal error' }), 500],
+    ['a network error', () => fetchMock.mockRejectedValue(new TypeError('fetch failed')), null],
+  ])('unverified (%s) → served 200, verdict recorded, one Sentry warning', async (_label, script, status) => {
+    script();
+    const res = await call(method);
+    expect(res.status).toBe(200);
+    expect(mockRunFacilitator).toHaveBeenCalledTimes(1);
+    expect(verdictsRecorded()).toEqual(['unverified']);
+    expect(verdictLines()).toEqual([{ verdict: 'unverified' }]);
+    expect(captureMessage).toHaveBeenCalledTimes(1);
+    expect(captureMessage).toHaveBeenCalledWith('mcp-complete key unverified (log-only)', {
+      level: 'warning',
+      tags: { mcp_key_verdict: 'unverified' },
+      extra: { status },
+    });
+  });
+
+  it("valid → served, attributed by the key, a forged header still one mismatch warning", async () => {
+    authAnswers(200, VALID);
+    const res = await call(method, { clientHeader: 'claude-skill', src: 'evil' });
+    expect(res.status).toBe(200);
+    expect(verdictsRecorded()).toEqual(['valid']);
+    expect(verdictLines()).toEqual([{ verdict: 'valid', keyId: KEY_ID }]);
+    const threads = await client.query<{ client: string }>('SELECT client FROM threads');
+    expect(threads.rows).toEqual([{ client: KEY_CLIENT }]);
+    expect(messagesCaptured()).toEqual(['mcp-complete client mismatch']);
+  });
+});
+
+describe('mode', () => {
+  it('MCP_COMPLETE_KEY_MODE=enforce enforces like the default', async () => {
+    setEnv('enforce');
+    const res = await call('POST', { authorization: null });
+    expect(res.status).toBe(401);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Scenario 12: no key material anywhere. Runs last, over every capture above.
+
+describe('scenario 12: the leak scan', () => {
+  it('negative control: the scan finds a window of the key in a known-bad line', () => {
+    const badLine = `verify failed for ${KEY.slice(0, PREFIX.length + 20)}`;
+    expect(leakedWindows(badLine).length).toBeGreaterThan(0);
+    expect(leakedWindows(KEY)).toHaveLength(64 - LEAK_WINDOW + 1);
+  });
+
+  it('near miss: the bare public prefix, and a 15-character fragment, are not a leak', () => {
+    expect(leakedWindows(`${PREFIX}… key prefix`)).toEqual([]);
+    expect(leakedWindows(KEY.slice(PREFIX.length, PREFIX.length + LEAK_WINDOW - 1))).toEqual([]);
+  });
+
+  it.each(['POST', 'GET'] as const)('%s: every verdict, in both modes, captures no key material', async (method) => {
+    const scripts: Array<[string | undefined, () => void]> = [
+      [undefined, () => authAnswers(200, VALID)],
+      [undefined, () => authAnswers(200, { valid: false })],
+      [undefined, () => authAnswers(500, { message: 'Internal error' })],
+      [undefined, () => fetchMock.mockRejectedValue(new TypeError('fetch failed'))],
+      ['log-only', () => authAnswers(200, { valid: false })],
+      ['log-only', () => authAnswers(500, { message: 'Internal error' })],
+    ];
+    for (const [mode, script] of scripts) {
+      setEnv(mode);
+      script();
+      await call(method, { clientHeader: 'claude-skill' });
+    }
+    // The request reached apps/auth (so the key was in play) on every run.
+    expect(fetchMock).toHaveBeenCalledTimes(scripts.length);
+  });
+
+  it('the scan over every console line, Sentry call and response body in this file finds nothing', () => {
+    const text = [...captures, ...responseBodies].join('\n');
+    expect(captures.length).toBeGreaterThan(60);
+    expect(responseBodies.length).toBeGreaterThan(40);
+    expect(leakedWindows(text)).toEqual([]);
+  });
+});
diff --git a/apps/api/tests/mcp-complete.test.ts b/apps/api/tests/mcp-complete.test.ts
index 03b0a95a..9de7bf40 100644
--- a/apps/api/tests/mcp-complete.test.ts
+++ b/apps/api/tests/mcp-complete.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
 import { NextRequest } from 'next/server';
 
 // Mock DB operations
@@ -46,6 +46,20 @@ vi.mock('@/lib/rate-limit', () => ({
 
 // Import route handlers after mocks
 import { GET, POST } from '../src/app/api/v2/mcp-complete/route';
+import { resetEnvCache } from '@/lib/config';
+import { installMcpKeyStub, MCP_TEST_CLIENT_ID, withMcpKey } from './helpers/mcp-key';
+
+// Every request presents a valid key (#314); the gate itself is tested in
+// mcp-complete-key.test.ts.
+beforeEach(async () => {
+  await installMcpKeyStub();
+});
+
+afterEach(() => {
+  vi.unstubAllGlobals();
+  vi.unstubAllEnvs();
+  resetEnvCache();
+});
 
 const SYSTEM_USER = {
   id: 'system-user-id',
@@ -68,7 +82,7 @@ const MOCK_THREAD = {
 };
 
 function makePostRequest(body: unknown, clientId?: string): NextRequest {
-  const headers: Record = { 'Content-Type': 'application/json' };
+  const headers: Record = withMcpKey({ 'Content-Type': 'application/json' });
   if (clientId !== undefined) headers['X-Ansari-Client'] = clientId;
   return new NextRequest('http://localhost/api/v2/mcp-complete', {
     method: 'POST',
@@ -81,9 +95,9 @@ function makeGetRequest(query?: string, clientId?: string): NextRequest {
   const url = query
     ? `http://localhost/api/v2/mcp-complete?q=${encodeURIComponent(query)}`
     : 'http://localhost/api/v2/mcp-complete';
-  const init: { method: string; headers?: Record } = { method: 'GET' };
-  if (clientId !== undefined) init.headers = { 'X-Ansari-Client': clientId };
-  return new NextRequest(url, init);
+  const headers = withMcpKey();
+  if (clientId !== undefined) headers['X-Ansari-Client'] = clientId;
+  return new NextRequest(url, { method: 'GET', headers });
 }
 
 /** Creates a mock async generator that yields facilitator events */
@@ -223,7 +237,7 @@ describe('POST /api/v2/mcp-complete', () => {
       {
         userId: SYSTEM_USER.id,
         source: 'ai-skill',
-        client: null,
+        client: MCP_TEST_CLIENT_ID,
       },
       expect.anything() // tx executor (issue #20)
     );
@@ -406,7 +420,7 @@ describe('mcp-complete empty-answer backstop (issue #60)', () => {
   });
 });
 
-describe('mcp-complete client attribution (spec 56)', () => {
+describe('mcp-complete client attribution (#314: the key decides)', () => {
   beforeEach(() => {
     vi.clearAllMocks();
     setupSuccessfulMocks();
@@ -415,34 +429,36 @@ describe('mcp-complete client attribution (spec 56)', () => {
     mockCheckRateLimit.mockReturnValue({ allowed: true, retryAfter: 0 });
   });
 
-  it('POST attributes thread + all messages from X-Ansari-Client (source stays ai-skill)', async () => {
+  it("POST attributes thread + all messages to the key's client, not X-Ansari-Client (source stays ai-skill)", async () => {
     await POST(makePostRequest({ messages: [{ role: 'user', content: 'Q' }] }, 'muslimpedia'));
 
     expect(mockCreateThread).toHaveBeenCalledWith(
-      expect.objectContaining({ source: 'ai-skill', client: 'muslimpedia' }),
+      expect.objectContaining({ source: 'ai-skill', client: MCP_TEST_CLIENT_ID }),
       expect.anything()
     );
+    expect(mockCreateMessage).toHaveBeenCalled();
     for (const [arg] of mockCreateMessage.mock.calls) {
-      expect(arg).toEqual(expect.objectContaining({ source: 'ai-skill', client: 'muslimpedia' }));
+      expect(arg).toEqual(expect.objectContaining({ source: 'ai-skill', client: MCP_TEST_CLIENT_ID }));
     }
   });
 
-  it('GET attributes thread + messages from the header (distinct entrypoint from POST)', async () => {
+  it("GET attributes thread + messages to the key's client (distinct entrypoint from POST)", async () => {
     await GET(makeGetRequest('What is Islam?', 'muslimpedia'));
 
     expect(mockCreateThread).toHaveBeenCalledWith(
-      expect.objectContaining({ source: 'ai-skill', client: 'muslimpedia' }),
+      expect.objectContaining({ source: 'ai-skill', client: MCP_TEST_CLIENT_ID }),
       expect.anything()
     );
+    expect(mockCreateMessage).toHaveBeenCalled();
     for (const [arg] of mockCreateMessage.mock.calls) {
-      expect(arg).toEqual(expect.objectContaining({ client: 'muslimpedia' }));
+      expect(arg).toEqual(expect.objectContaining({ client: MCP_TEST_CLIENT_ID }));
     }
   });
 
-  it('client is null when the header is absent (unchanged behavior)', async () => {
+  it("client is the key's when the header is absent", async () => {
     await POST(makePostRequest({ messages: [{ role: 'user', content: 'Q' }] }));
     expect(mockCreateThread).toHaveBeenCalledWith(
-      expect.objectContaining({ source: 'ai-skill', client: null }),
+      expect.objectContaining({ source: 'ai-skill', client: MCP_TEST_CLIENT_ID }),
       expect.anything()
     );
   });
diff --git a/apps/api/tests/route-persistence-rollback.test.ts b/apps/api/tests/route-persistence-rollback.test.ts
index 1c90fd16..c48eab71 100644
--- a/apps/api/tests/route-persistence-rollback.test.ts
+++ b/apps/api/tests/route-persistence-rollback.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
+import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest';
 import { NextRequest } from 'next/server';
 
 // Issue #20 (PR #26): the first real Executor consumers. Both ingestion routes
@@ -43,9 +43,13 @@ vi.mock('@/lib/rate-limit', () => ({
 }));
 
 const API_KEY = 'rollback-test-leaderboard-key-at-least-32-chars';
-vi.mock('@/lib/config', () => ({
-  config: { leaderboard: { apiKey: 'rollback-test-leaderboard-key-at-least-32-chars' } },
-}));
+vi.mock('@/lib/config', async () => {
+  // mcp-complete's key gate (#314) reads authService and mcpCompleteKeyMode.
+  const { MCP_KEY_CONFIG } = await import('./helpers/mcp-key');
+  return {
+    config: { leaderboard: { apiKey: 'rollback-test-leaderboard-key-at-least-32-chars' }, ...MCP_KEY_CONFIG },
+  };
+});
 
 vi.mock('@/lib/ai/inkling-client', () => ({
   isInklingConfigured: () => false,
@@ -56,6 +60,7 @@ import { drizzle } from 'drizzle-orm/pglite';
 import * as schema from '@/db/schema';
 import { POST as mcpPost } from '../src/app/api/v2/mcp-complete/route';
 import { POST as chatPost } from '../src/app/api/v1/chat/completions/route';
+import { installMcpKeyStub, withMcpKey } from './helpers/mcp-key';
 
 let client: PGlite;
 
@@ -114,6 +119,14 @@ afterAll(async () => {
   await client.close();
 });
 
+beforeEach(async () => {
+  await installMcpKeyStub({ env: false });
+});
+
+afterEach(() => {
+  vi.unstubAllGlobals();
+});
+
 beforeEach(async () => {
   vi.clearAllMocks();
   mockRunFacilitator.mockImplementation(() => facilitatorEmits('A fine answer.'));
@@ -129,7 +142,7 @@ describe('POST /api/v2/mcp-complete — atomic inbound persistence', () => {
   function makeRequest(messages: Array<{ role: string; content: string }>): NextRequest {
     return new NextRequest('http://localhost/api/v2/mcp-complete', {
       method: 'POST',
-      headers: { 'Content-Type': 'application/json' },
+      headers: withMcpKey({ 'Content-Type': 'application/json' }),
       body: JSON.stringify({ messages }),
     });
   }
diff --git a/apps/api/tests/toolcalls-routes.test.ts b/apps/api/tests/toolcalls-routes.test.ts
index 2bd150b8..67cadd9d 100644
--- a/apps/api/tests/toolcalls-routes.test.ts
+++ b/apps/api/tests/toolcalls-routes.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
 import { NextRequest } from 'next/server';
 
 /**
@@ -81,6 +81,8 @@ import { SSE_HEARTBEAT } from '@/lib/streaming/heartbeat';
 import { POST as threadPost } from '../src/app/api/v2/threads/[id]/route';
 import { POST as chatPost } from '../src/app/api/v2/threads/[id]/chat/route';
 import { POST as mcpPost } from '../src/app/api/v2/mcp-complete/route';
+import { resetEnvCache } from '@/lib/config';
+import { installMcpKeyStub, MCP_TEST_CLIENT_ID, withMcpKey } from './helpers/mcp-key';
 
 let client: PGlite;
 let db: ReturnType>;
@@ -166,6 +168,17 @@ afterAll(async () => {
   await client.close();
 });
 
+// mcp-complete requires a valid key (#314): every mcpReq presents one.
+beforeEach(async () => {
+  await installMcpKeyStub();
+});
+
+afterEach(() => {
+  vi.unstubAllGlobals();
+  vi.unstubAllEnvs();
+  resetEnvCache();
+});
+
 beforeEach(async () => {
   vi.clearAllMocks();
   mockAuthenticateRequest.mockResolvedValue({ user: { id: USER_ID } });
@@ -198,7 +211,7 @@ function chatReq(message: string): NextRequest {
 function mcpReq(content: string): NextRequest {
   return new NextRequest('http://localhost/api/v2/mcp-complete', {
     method: 'POST',
-    headers: { 'Content-Type': 'application/json', 'X-Ansari-Client': 'ai-skill-v1' },
+    headers: withMcpKey({ 'Content-Type': 'application/json' }),
     body: JSON.stringify({ messages: [{ role: 'user', content }] }),
   });
 }
@@ -433,7 +446,7 @@ describe('POST /api/v2/mcp-complete (ai-skill)', () => {
     expect(await assistantRows()).toHaveLength(0);
     const orphans = await orphanRows();
     expect(orphans).toHaveLength(1);
-    expect(orphans[0]).toMatchObject({ reason: 'error', source: 'ai-skill', client: 'ai-skill-v1' });
+    expect(orphans[0]).toMatchObject({ reason: 'error', source: 'ai-skill', client: MCP_TEST_CLIENT_ID });
     expect(orphans[0].toolCalls).toEqual(RECORDS);
     // The orphan is attached to the thread this request created.
     const threadRows = await db.select().from(threads).where(eq(threads.id, orphans[0].threadId));
diff --git a/codev/state/spir-314_thread.md b/codev/state/spir-314_thread.md
index 9195ed8e..a7e9ea4b 100644
--- a/codev/state/spir-314_thread.md
+++ b/codev/state/spir-314_thread.md
@@ -53,3 +53,10 @@
 - Surprise: the plan assumed `self-hosting-docs.test.ts` already checked the whole env surface. It didn't. Added a check that every key of apps/api's `envSchema` (now exported) appears in docs/self-hosting.md; it fails without the new row and passes with it. All existing vars were already documented.
 - Flaky once: `tests/auth/require-user.test.ts` (13 tests, `sign-up failed: 404` from the in-process apps/auth) failed in one full `npm test` run, passed in isolation (18/18) and on a full rerun. The file isn't touched by this phase. I documented it rather than skipping it, because skipping would drop the admin-auth coverage. Exact record: `npm test -- --exclude='**/e2e/**'` from the worktree root, which runs `turbo run test --filter=!ansari-mcp -- --maxWorkers=4 --exclude=**/e2e/**`, so 4 vitest workers per package with all four packages running at once. ansari-api: 1 file failed / 87 passed, duration 65.7 s, the file took 27.0 s. The thrower is `signUpTokens` (`apps/auth/tests/helpers/service.ts:166`), which reports the status only, so the 404 body was not captured. The security architect classes it as the known under-load class (#330 lineage) and will raise it with the owner; not chasing it.
 - New orders for phase 5 (from main, via security): mcp-staging.askansari.ai needs its own key (`--client-id ansari-mcp-staging`) before apps/api staging deploys #314. The `Bearer ansari_mcp_<64 letters>` form goes in apps/mcp README, apps/mcp/.env.example (required once enforcing) and the RELEASE.md mcp rows. Rebase onto develop before phase 5.
+
+## 2026-11-11 phase 4 — the mcp-complete key gate
+- `authorizeMcpRequest` in the route, after the per-IP cap and before the body/query: bearer (case-insensitive scheme, one token, no whitespace) → `verifyServiceKey` → verdict `valid|missing|refused|unverified`. Enforce: 401 `{error:'Unauthorized'}` / 503 `{error:'Authentication service unavailable'}` + `console.warn` with the status only. Log-only: everything served, `unverified` raises a Sentry warning. Every verdict is a Sentry tag `mcp_key_verdict` plus one `[ai-skill] mcp-complete key verdict` log line `{verdict, keyId?}`.
+- Attribution on a valid key: the key's client id; header parsed alone (`parseClientId(header, null)`), one `mcp-complete client mismatch` warning with ids only; `?src=` ignored; `getClientId` not called. Without a valid key (log-only only): `getClientId` as today.
+- Surprise: of the 7 suites the plan named, only 3 call the route (mcp-complete, route-persistence-rollback, toolcalls-routes). attribution.test.ts, rate-limit.test.ts, facilitator-empty-final.test.ts and sentry/request-envelopes.ts test helpers directly and need no key. The mcp-complete attribution cases the plan put in attribution.test.ts live in mcp-complete.test.ts; rewritten there for key attribution.
+- Shared stub `apps/api/tests/helpers/mcp-key.ts` (fetch stub for the verify URL only, `vi.stubEnv` for absent vars, `MCP_KEY_CONFIG` for suites that mock config).
+- New `tests/mcp-complete-key.test.ts`: 72 tests, scenarios 1–10, 12, 13 (seam) on pglite with the real verifyServiceKey. Mutation-checked: logging the token fails the leak scan; disabling enforce fails 37 tests.

From 531ca255cb21d00f26a2a3dac005f078ead4dfd2 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:09:55 +1100
Subject: [PATCH 136/435] chore(porch): 314 implement build-complete

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 684175c5..f5140a8f 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -33,7 +33,7 @@ gates:
   verify-approval:
     status: pending
 iteration: 1
-build_complete: false
+build_complete: true
 history:
   - iteration: 1
     plan_phase: phase_2
@@ -72,7 +72,7 @@ history:
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:03:11.694Z'
+updated_at: '2026-11-11T04:09:55.591Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'

From ebdcc56f30621beac9a50ea05ef63f90029390d8 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:15:22 +1100
Subject: [PATCH 137/435] [Spec 314][Phase: 4] fix: count only served keys
 toward verify volume alerts; key-first attribution comment

---
 apps/api/src/app/api/v2/mcp-complete/route.ts |  6 ++--
 apps/api/tests/mcp-complete.test.ts           |  8 +++--
 apps/auth/src/routes/service-verify.ts        |  4 ++-
 apps/auth/tests/service-verify.test.ts        | 32 +++++++++++++++----
 codev/state/spir-314_thread.md                |  3 ++
 5 files changed, 41 insertions(+), 12 deletions(-)

diff --git a/apps/api/src/app/api/v2/mcp-complete/route.ts b/apps/api/src/app/api/v2/mcp-complete/route.ts
index 8276d5eb..34c6e15a 100644
--- a/apps/api/src/app/api/v2/mcp-complete/route.ts
+++ b/apps/api/src/app/api/v2/mcp-complete/route.ts
@@ -245,8 +245,10 @@ async function handleMcpComplete(
   const messages = prepareMessages(inputMessages);
 
   // Log to DB: create system user, thread, and user messages. `source` stays
-  // 'ai-skill' (product surface); `client` is the per-request X-Ansari-Client
-  // attribution (spec 56), NULL when the header is absent.
+  // 'ai-skill' (product surface). `client` is the key's client_id whenever a
+  // valid key was presented (#314, #320); the X-Ansari-Client header or
+  // `?src=` (spec 56, #87) decides only in log-only mode without a valid key,
+  // and is NULL when neither was sent.
   const systemUserId = await getSystemUserId();
 
   // Thread + inbound messages persist atomically (issue #20): a failed message
diff --git a/apps/api/tests/mcp-complete.test.ts b/apps/api/tests/mcp-complete.test.ts
index 9de7bf40..fb35afa8 100644
--- a/apps/api/tests/mcp-complete.test.ts
+++ b/apps/api/tests/mcp-complete.test.ts
@@ -216,14 +216,16 @@ describe('POST /api/v2/mcp-complete', () => {
     expect(body.error).toBe('Gemini API timeout');
   });
 
-  it('does not require authentication', async () => {
-    // No Authorization header — should still work
+  it('requires a key (#314): no Authorization header → 401, the facilitator never runs', async () => {
     const request = makePostRequest({
       messages: [{ role: 'user', content: 'Test' }],
     });
+    request.headers.delete('authorization');
 
     const response = await POST(request);
-    expect(response.status).toBe(200);
+    expect(response.status).toBe(401);
+    expect(await response.json()).toStrictEqual({ error: 'Unauthorized' });
+    expect(mockRunFacilitator).not.toHaveBeenCalled();
   });
 
   it('creates thread and messages in DB', async () => {
diff --git a/apps/auth/src/routes/service-verify.ts b/apps/auth/src/routes/service-verify.ts
index 7ef63990..3dfbb694 100644
--- a/apps/auth/src/routes/service-verify.ts
+++ b/apps/auth/src/routes/service-verify.ts
@@ -120,7 +120,6 @@ export function serviceVerifyRouter({ auth, db }: ServiceDeps, options: VerifyOp
         await checkApiKeyRelation();
         return refuse(res);
       }
-      alerts.keyVerified(verified.key);
 
       // Only after the plugin accepts: no state of the service user makes a refused key valid.
       const owner = await serviceUsers.findServiceUser(db, SERVICE);
@@ -135,6 +134,9 @@ export function serviceVerifyRouter({ auth, db }: ServiceDeps, options: VerifyOp
         alerts.clientIdInvalid(verified.key.id);
         return refuse(res);
       }
+      // Counted only for a key that is served: a wrong owner or a bad client id
+      // is a refusal, already counted by refuse() (security architect, #314).
+      alerts.keyVerified(verified.key);
       res.status(200).json({ valid: true, client_id: clientId, key_id: verified.key.id });
     } catch (err) {
       fail(res, err);
diff --git a/apps/auth/tests/service-verify.test.ts b/apps/auth/tests/service-verify.test.ts
index 8f4b638d..ef4e4c37 100644
--- a/apps/auth/tests/service-verify.test.ts
+++ b/apps/auth/tests/service-verify.test.ts
@@ -51,13 +51,14 @@ const alertsOf = (kind: McpVerifyAlert['kind']) => alerts.filter((a) => a.kind =
 /** A fresh alert window, so one test's counts never reach the next. */
 const nextAlertWindow = () => clock.advance(limits.EXCHANGE_ALERT_WINDOW * 1000);
 
+/** The tracker of the service started last, so a test can spy on what it is told. */
+let verifyAlerts: ReturnType;
+/** The tracker of the suite's main `service` (later services each get their own). */
+let serviceAlerts: ReturnType;
+
 function startVerifyService(): Promise {
-  return startService({
-    verify: {
-      alerts: createMcpVerifyAlerts({ send: (alert) => alerts.push(alert), now: clock.now }),
-      now: clock.now,
-    },
-  });
+  verifyAlerts = createMcpVerifyAlerts({ send: (alert) => alerts.push(alert), now: clock.now });
+  return startService({ verify: { alerts: verifyAlerts, now: clock.now } });
 }
 
 type ServiceName = serviceUsers.ServiceName;
@@ -146,6 +147,7 @@ let keyId: string;
 
 beforeAll(async () => {
   service = await startVerifyService();
+  serviceAlerts = verifyAlerts;
   mcpUserId = await serviceUserOf(service, 'ansari-mcp');
   ({ key, id: keyId } = await scriptKey());
 });
@@ -535,6 +537,24 @@ describe('transport (scenario 10)', () => {
 });
 
 describe('alerts (scenario 13)', () => {
+  it('only a served key counts toward the volume alerts: a wrong owner or a bad client id is a refusal', async () => {
+    const member = await signUpTokens(service, 'mcp-volume-member@example.com');
+    const wrongOwner = await outsideKey(member.id, { metadata: { clientId: 'ansari-mcp-production' } });
+    const badClientId = await outsideKey(mcpUserId, { metadata: { clientId: 'claude-skill' } });
+    const served = await scriptKey();
+    const counted = vi.spyOn(serviceAlerts, 'keyVerified');
+    try {
+      expectRefused(await verify(wrongOwner.key));
+      expectRefused(await verify(badClientId.key));
+      expect(counted).not.toHaveBeenCalled();
+      expect((await verify(served.key)).status).toBe(200);
+      expect(counted).toHaveBeenCalledTimes(1);
+      expect(counted.mock.calls[0][0]).toMatchObject({ id: served.id });
+    } finally {
+      counted.mockRestore();
+    }
+  });
+
   it('per-key window volume: one alert at MCP_VERIFY_KEY_ALERT, counts and the key id only', async () => {
     const made = await scriptKey();
     const sent = alertsOf('key-window-volume').length;
diff --git a/codev/state/spir-314_thread.md b/codev/state/spir-314_thread.md
index a7e9ea4b..36fd82ff 100644
--- a/codev/state/spir-314_thread.md
+++ b/codev/state/spir-314_thread.md
@@ -60,3 +60,6 @@
 - Surprise: of the 7 suites the plan named, only 3 call the route (mcp-complete, route-persistence-rollback, toolcalls-routes). attribution.test.ts, rate-limit.test.ts, facilitator-empty-final.test.ts and sentry/request-envelopes.ts test helpers directly and need no key. The mcp-complete attribution cases the plan put in attribution.test.ts live in mcp-complete.test.ts; rewritten there for key attribution.
 - Shared stub `apps/api/tests/helpers/mcp-key.ts` (fetch stub for the verify URL only, `vi.stubEnv` for absent vars, `MCP_KEY_CONFIG` for suites that mock config).
 - New `tests/mcp-complete-key.test.ts`: 72 tests, scenarios 1–10, 12, 13 (seam) on pglite with the real verifyServiceKey. Mutation-checked: logging the token fails the leak scan; disabling enforce fails 37 tests.
+- Phase 4 consults iter 1: codex APPROVE, gemini APPROVE (nit: a stale "does not require authentication" test in mcp-complete.test.ts, now replaced with "requires a key → 401").
+- Security architect (04:10Z) ordered two changes, both done: (1) apps/auth `alerts.keyVerified()` moved after the owner and client-id checks, so only a served key counts toward the volume alerts (refusals already count through refuse()). Pinned by a new service-verify test that fails under the old ordering. The WhatsApp exchange ordering is unchanged (not ordered). (2) The stale `client` comment in handleMcpComplete now says the key decides.
+- Flaky once: `apps/auth/tests/whatsapp-session.test.ts` > "auth.apikey dropped under the running service → 500 …" got 404 where it expected 401, in one full `npm test` run (4 packages in parallel, 4 workers each). It passed 3/3 in isolation and on a full rerun. The exchange route is untouched by this change. Same under-load 404 class as require-user (#330 lineage). Documented, not skipped.

From a467b7f2ac650df39f83a620e5bd3913ae33d348 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:15:22 +1100
Subject: [PATCH 138/435] =?UTF-8?q?chore(porch):=20314=20advance=20plan=20?=
 =?UTF-8?q?phase=20=E2=86=92=20phase=5F5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../314-protect-v2-mcp-complete-with-b/status.yaml   | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index f5140a8f..189fb076 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -14,11 +14,11 @@ plan_phases:
     status: complete
   - id: phase_4
     title: mcp-complete key gate, key attribution and log-only mode
-    status: in_progress
+    status: complete
   - id: phase_5
     title: Docs, runbook and architecture notes
-    status: pending
-current_plan_phase: phase_4
+    status: in_progress
+current_plan_phase: phase_5
 gates:
   spec-approval:
     status: approved
@@ -33,7 +33,7 @@ gates:
   verify-approval:
     status: pending
 iteration: 1
-build_complete: true
+build_complete: false
 history:
   - iteration: 1
     plan_phase: phase_2
@@ -72,7 +72,7 @@ history:
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:09:55.591Z'
+updated_at: '2026-11-11T04:15:22.154Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'
@@ -89,3 +89,5 @@ context_refreshes:
   - boundary: plan-phase:phase_4
     at: '2026-11-11T04:03:07.170Z'
     acknowledged_at: '2026-11-11T04:03:11.694Z'
+  - boundary: plan-phase:phase_5
+    at: '2026-11-11T04:15:22.154Z'

From 12603147101a6545bb7a3abf379e6ee2a504a340 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:15:29 +1100
Subject: [PATCH 139/435] chore(porch): 314 acknowledge context refresh

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 189fb076..3c01fba6 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -72,7 +72,7 @@ history:
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:15:22.154Z'
+updated_at: '2026-11-11T04:15:29.368Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'
@@ -91,3 +91,4 @@ context_refreshes:
     acknowledged_at: '2026-11-11T04:03:11.694Z'
   - boundary: plan-phase:phase_5
     at: '2026-11-11T04:15:22.154Z'
+    acknowledged_at: '2026-11-11T04:15:29.367Z'

From 59e7db4c7fc5be740511b0e3108b1d0746831164 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:17:44 +1100
Subject: [PATCH 140/435] [Spec 314][Phase: 5] test: follow #366's askansari.ai
 attribution link after rebase

---
 apps/api/tests/mcp-complete-key.test.ts | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/apps/api/tests/mcp-complete-key.test.ts b/apps/api/tests/mcp-complete-key.test.ts
index 31832d16..3d603e6b 100644
--- a/apps/api/tests/mcp-complete-key.test.ts
+++ b/apps/api/tests/mcp-complete-key.test.ts
@@ -342,7 +342,7 @@ describe.each(['POST', 'GET'] as const)('%s, enforce mode', (method) => {
     const res = await call(method);
     expect(res.status).toBe(200);
     expect(res.text).toContain('A fine answer.');
-    expect(res.text).toContain('ansari.chat');
+    expect(res.text).toContain('askansari.ai');
     expect(mockRunFacilitator).toHaveBeenCalledTimes(1);
 
     // The real verifyServiceKey asked apps/auth about this key, for mcp: complete.

From 709034588022ee5e566e59311f70906e42cd41c7 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:20:58 +1100
Subject: [PATCH 141/435] [Spec 314][Phase: 5] docs: ansari-mcp key runbook,
 self-hosting, READMEs, RELEASE staging row, arch notes

---
 RELEASE.md                           |   1 +
 apps/api/README.md                   |   2 +-
 apps/mcp/.env.example                |   6 +-
 apps/mcp/README.md                   |   2 +-
 codev/resources/arch-critical.md     |   4 +-
 codev/resources/arch.md              |   4 +-
 codev/state/spir-314_thread.md       |   6 ++
 docs/cutover/service-keys-runbook.md | 141 ++++++++++++++++++++++++++-
 docs/self-hosting.md                 |  25 ++++-
 9 files changed, 181 insertions(+), 10 deletions(-)

diff --git a/RELEASE.md b/RELEASE.md
index 107e734d..6702492d 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -91,6 +91,7 @@ migration runbook were both proven in real releases on 2026-08-02.
 > | `MCP_ALLOWED_HOSTS` | `mcp-staging.askansari.ai` (the server refuses any other Host on `/mcp`) |
 > | `ANSARI_API_BASE_URL` | `https://api-staging.askansari.ai` (the default is production) |
 > | `ANSARI_CLIENT` | `ansari-mcp-staging` |
+> | `ANSARI_API_AUTHORIZATION` | `Bearer ansari_mcp_<64 letters>`: the staging key, made with `--client-id ansari-mcp-staging` and set **before** apps/api staging deploys #314 (`docs/cutover/service-keys-runbook.md`) |
 >
 > `ANSARI_RELEASE` is **not** set: the release falls back to `RAILWAY_GIT_COMMIT_SHA`. `MCP_ALLOWED_ORIGINS` is left
 > unset at first: it defaults to the allowed hosts, and requests without an Origin pass. The Cloudflare Workers path
diff --git a/apps/api/README.md b/apps/api/README.md
index 3acd9eaf..dc640546 100644
--- a/apps/api/README.md
+++ b/apps/api/README.md
@@ -24,7 +24,7 @@ Responses stream over SSE, threads and messages persist to Postgres, and the sea
 | Feedback & prefs | `POST /api/v2/feedback`, `GET/POST /api/v2/preferences` |
 | App support | `GET /api/v2/app-check` (version/maintenance gate) |
 | OpenAI-compat | `POST /api/v1/chat/completions` (bearer-token gated, for evaluation harnesses) |
-| MCP-style | `POST /api/v2/mcp-complete` (stateless completion for AI-skill integrations) |
+| MCP-style | `POST /api/v2/mcp-complete` (stateless completion for AI-skill integrations; requires an `ansari-mcp` service key as `Authorization: Bearer `, verified at apps/auth, see `docs/self-hosting.md`) |
 | Admin | `GET /api/v2/admin/stats`, `/admin/analytics` dashboard |
 
 Auth is owned by `apps/auth` (Better Auth, spec 300): this service verifies its short-lived JWTs against the JWKS, and the `/v2/users/*` and password-reset routes are a compatibility layer over it with the legacy response shapes. No password, session or signing secret lives here.
diff --git a/apps/mcp/.env.example b/apps/mcp/.env.example
index 0b24c0cf..7d7208ee 100644
--- a/apps/mcp/.env.example
+++ b/apps/mcp/.env.example
@@ -12,7 +12,11 @@ PORT=3000
 # Ansari API origin. Default https://api.askansari.ai (PRODUCTION).
 # ANSARI_API_BASE_URL=https://api-staging.askansari.ai
 
-# Optional upstream Authorization header. Never commit a value.
+# Upstream Authorization header, sent verbatim. Required for a deployment that
+# calls a deployed Ansari API once /api/v2/mcp-complete enforces keys (#314);
+# optional only against a local API. The value is the whole header:
+# Bearer ansari_mcp_<64 letters> (this deployment's key, from the operator).
+# Never commit a value.
 # ANSARI_API_AUTHORIZATION=
 
 # Upstream client label. Default ansari-mcp.
diff --git a/apps/mcp/README.md b/apps/mcp/README.md
index ddfaa46f..8cbd44a9 100644
--- a/apps/mcp/README.md
+++ b/apps/mcp/README.md
@@ -89,7 +89,7 @@ The Worker takes the variables in the table below as Wrangler `vars` or secrets,
 | --- | --- |
 | `PORT` | HTTP port (default 3000). |
 | `ANSARI_API_BASE_URL` | Ansari API origin (default `https://api.askansari.ai`). |
-| `ANSARI_API_AUTHORIZATION` | Optional upstream Authorization header. Supply through the environment; never commit it. |
+| `ANSARI_API_AUTHORIZATION` | Upstream Authorization header, sent verbatim: `Bearer ansari_mcp_<64 letters>`, the word `Bearer`, a space, then this deployment's `ansari-mcp` service key. Required for any deployment that calls a deployed Ansari API: `/api/v2/mcp-complete` refuses a call without a valid key (401) once it enforces (#314). Optional only against a local API. Issued per deployment by the operator (`docs/cutover/service-keys-runbook.md`); set it with `wrangler secret put ANSARI_API_AUTHORIZATION --env ` on Workers or as a service variable on Railway, never commit it. |
 | `ANSARI_CLIENT` | Upstream client label (default `ansari-mcp`). |
 | `MCP_ALLOWED_HOSTS` | Comma-separated allowed HTTP Host names, without scheme. A configured list replaces local defaults; an explicitly empty list permits no Host. Only an absent variable defaults to localhost and 127.0.0.1. |
 | `MCP_ALLOWED_ORIGINS` | Comma-separated allowed browser origin hostnames. A configured list replaces defaults; an explicitly empty list permits no Origin header value. Requests without Origin remain supported. |
diff --git a/codev/resources/arch-critical.md b/codev/resources/arch-critical.md
index a42f651b..9f964fe3 100644
--- a/codev/resources/arch-critical.md
+++ b/codev/resources/arch-critical.md
@@ -10,7 +10,7 @@ STARTER: replace the examples below with YOUR project's facts and arch.md sectio
 - Admin authorization is `auth.users.role === 'admin'` in the AUTH database, asked of apps/auth's `GET /api/account/me` with the admin's OWN JWT on EVERY admin request (outage → 503, fail closed; a dead session → 403); NEVER an email match or a JWT claim. The role is the ONLY admin truth (no admin list anywhere in apps/auth, no boot check): it comes only from `apps/auth/scripts/grant-admin.ts`, which shows the account and grants by its id (`--confirm `), warning on a recent or unverified (squattable) account.
 - System accounts (`ai-skill`, `leaderboard`) are resolved by `users.system_key`, NEVER by email; `@system.ansari.chat` is reserved at registration.
 - Two databases, one owner each: only apps/auth connects to the auth database; apps/api reaches auth ONLY over HTTP at its PUBLIC origin (`AUTH_URL`, read through `config.authService`), like any client: public JWKS, account endpoints bound to the user's own JWT and a live `sid`, anonymous `/v2/users` pass-through. NO shared secret, NO internal listener (owner, 2026-10-17). No query crosses them; a user's id is the same UUID in both, and the app row is created on first use.
-- apps/api accepts only apps/auth's EdDSA JWT (15 min, `{sub, sid}`), verified via JWKS. Revocation = deleting sessions at apps/auth, so a minted JWT stays valid until it expires (≤15 min); never treat key rotation as revocation.
+- apps/api accepts only apps/auth's EdDSA JWT (15 min, `{sub, sid}`), verified via JWKS, except `/v2/mcp-complete`, which takes an `ansari-mcp` service key verified per request at apps/auth's `/api/service/verify-key` (401 refused / 503 outage). Revocation = deleting sessions at apps/auth, so a minted JWT stays valid until it expires (≤15 min); never treat key rotation as revocation.
 - The client IP is the single `X-Real-IP` Railway's edge stamps (never `X-Forwarded-For`); per-IP limits trust it. apps/auth sees apps/api's egress IP on every legacy call, so NO path the layer calls may carry a per-IP rule on apps/auth (`ROUTER_RULES` all `false`); those per-IP limits run in apps/api (`lib/auth-service/limits.ts`). TEMPORARY until the legacy system is replaced.
 - DB schema changes: `drizzle-kit generate` → review SQL → human-applied at deploy. NEVER `db:push`. Apply with `psql -v ON_ERROR_STOP=1 --single-transaction`, naming the database. Deploy order: migration → admin bootstrap (`apps/auth/scripts/grant-admin.ts`) → deploy. A PR whose tested DB paths name a new column fails `apps/api/tests/migration/migration-schema-parity.test.ts` until it bumps `DEPLOYED_THROUGH`. The bump is a human ASSERTION that the migration will be applied before deploy, NOT proof that it was. Nothing checks the target DB yet (#176), so the #165 outage class (code shipped, migration never run) is still possible.
 - Turborepo runs STRICT env mode: a var missing from `turbo.json` `globalEnv` is invisible to tasks AND absent from the cache key — a cached artifact can ship wrong values while reporting a hit. Derive additions four ways (Zod schema, static `process.env.X`, dynamic `process.env[`, documented env surface).
@@ -19,7 +19,7 @@ STARTER: replace the examples below with YOUR project's facts and arch.md sectio
 - Vertex rejects any turn after a `functionCall` model turn that lacks EXACTLY matching `functionResponse` parts; `messages.raw_payload` therefore stores only the FINAL model turn, guard-checked to carry zero functionCall parts. Tool history lives in `messages.tool_calls` (+ `tool_call_orphans` for error turns). NO API response may serialize raw tool records or `raw_payload`: the thread read helpers project `tool_calls` out, and `raw_payload` stays in `messageReadColumns` for replay only. The ONE serving reader of `tool_calls` is `lib/db/citable-documents.ts`, which returns derived `document` blocks only, served by the separate `/documents` endpoints (spec 168). Thread GET and share GET carry no documents. The mobile contract is frozen: single-text `content` must stay a bare string.
 
 ## Map of arch.md (consult when…)
-- Authentication & Authorization — consult when touching sign-in/sign-up/reset/delete, sessions or JWTs, the `/v2/users` layer, admin/system access, apps/auth's account endpoints, rate limits or the client IP.
+- Authentication & Authorization — consult when touching sign-in/sign-up/reset/delete, sessions or JWTs, the `/v2/users` layer, admin/system access, service keys (WhatsApp exchange, MCP verify), apps/auth's account endpoints, rate limits or the client IP.
 - Gemini facilitator & message history — consult when touching the facilitator loop, Gemini history building/replay, message persistence, or the repetition guard.
 - Monorepo layout, build & deploy — consult when changing the workspace layout, `turbo.json`, env vars, Docker builds, CI task wiring, or Railway deploy config.
 - Frontend chat display (apps/frontend) — consult when touching how answers render: citation markers/stripping, the streaming bubble, or the hand-off footer; text direction, Arabic passages, or the scripture box and its source pill; the web keyboard shim, `onShellResize`, and `keyboardDismissMode` on web lists; the Ansari mark, its brass emboss, or the generated icon rasters; the ambient palm-shadow layer's strength/grade, playback rate, or arrival fade; the About/Terms/Privacy reading pages and the verbatim legal text; or the sign-in sheet, or any web `Modal`/`Sheet` that holds fields (`fitToShell`).
diff --git a/codev/resources/arch.md b/codev/resources/arch.md
index db8869b3..e7cee8b4 100644
--- a/codev/resources/arch.md
+++ b/codev/resources/arch.md
@@ -22,7 +22,9 @@ Better Auth, in its own service (spec 300). `packages/auth` (`@ansari/auth`) is
 
 **Admin & system identity.** Admin = `auth.users.role === 'admin'` (and not banned), asked of `apps/auth`'s `GET /api/account/me` with the admin's own JWT on **every** admin request (`requireAdmin`): a demotion, a ban or a revoked session applies at once, an outage fails closed (503). Never an email match, never a JWT claim. Roles are granted by `apps/auth/scripts/grant-admin.ts`, which never creates an account or touches a password, in two steps: `` shows id, email, `created_at`, `email_verified` and role and grants nothing; ` --confirm ` grants exactly that account. It never grants to a system- or noreply-domain address (`--revoke`, a demotion, is allowed for any account: it is the repair for a WhatsApp user found holding `admin`) and warns on a recent or unverified account (no email verification exists, so an address can be squatted). There is no admin list and no boot check (owner amendment H-7). System identities (`ai-skill`, `leaderboard`) exist only as app rows found by `system_key` (`getOrCreateSystemUser`), with no auth row and no credential; `@system.ansari.chat` is reserved.
 
-**Service keys and the WhatsApp exchange (spec 329).** A **service** (`whatsapp`; `ansari-mcp` reserved for #314) is one auth user with no credential under `@noreply.askansari.ai`, found by its `{provider_id: 'service', account_id: }` row, never by email. Its keys come from `@better-auth/api-key` (pinned with core), rows in `auth.apikey` holding only the SHA-256 hash, each with its own per-window limit and daily refilled budget, no expiry, and fixed per-service permissions and prefix (`ansari_wa_`, `ansari_mcp_`), so a key for one service is refused at another's route. The plugin's HTTP surface is blocked; `apps/auth/scripts/service-keys.ts` is the only issuer (shown, then confirmed by id; the raw key printed once; a Sentry record of each write, with no key material). `enableSessionForAPIKeys` is off: a key is never a session. `POST /api/whatsapp/session` (mounted before CORS and outside Better Auth's router, so no per-IP rule and no CORS) verifies the key in process (`verifyApiKey` with `whatsapp: mint`), finds or creates the BSUID's user through `account (provider_id = 'whatsapp', account_id = )` (`unique (provider_id, account_id)` makes it one user under concurrency), checks eligibility under a lock on the user row (only that account row, its own `whatsapp-@noreply.askansari.ai` address, `registered_via = 'whatsapp'`, role exactly `user`, an allowlist; otherwise 500, never a token) and the ban (403, sessions deleted), reuses one session per user, and signs the ordinary `{sub, sid}` JWT after commit. So a key can only ever yield tokens for WhatsApp users: never an email user, an admin, a system or a service account. The BSUID lives only in `account.account_id` and reaches no log, response or `apps/api`. No phone number is stored anywhere (owner amendment 2): a `phone_number` the WhatsApp service sends is accepted and ignored. `@noreply.askansari.ai` is refused at sign-up (as a taken address), reset (as an unknown one), a grant by `grant-admin.ts`, and the `user.create.before` hook on every Better Auth path. **apps/api has no WhatsApp code** (a source scan); the exchange JWT passes `requireUser` unchanged. **Alert posture:** the exchange's alerts (per-key volume at one third of the caps, key refusals, 401 volume, ineligible users, an unresolvable service user) carry key ids, counts, thresholds and windows only in Sentry (a key id is a plugin-made UUID that names a credential, not a person, and matches `list`); user ids appear only in server log lines, and the service's Sentry keeps no breadcrumbs, so a logged id never rides on an event. `apps/auth` refuses to boot without `auth.apikey` or the constraint (migration `0001`). Operator procedure: `docs/cutover/service-keys-runbook.md`.
+**Service keys and the WhatsApp exchange (spec 329).** A **service** (`whatsapp`; `ansari-mcp`, #314) is one auth user with no credential under `@noreply.askansari.ai`, found by its `{provider_id: 'service', account_id: }` row, never by email. Its keys come from `@better-auth/api-key` (pinned with core), rows in `auth.apikey` holding only the SHA-256 hash, each with its own per-window limit and daily refilled budget, no expiry, and fixed per-service permissions and prefix (`ansari_wa_`, `ansari_mcp_`), so a key for one service is refused at another's route. The plugin's HTTP surface is blocked; `apps/auth/scripts/service-keys.ts` is the only issuer (shown, then confirmed by id; the raw key printed once; a Sentry record of each write, with no key material). `enableSessionForAPIKeys` is off: a key is never a session. `POST /api/whatsapp/session` (mounted before CORS and outside Better Auth's router, so no per-IP rule and no CORS) verifies the key in process (`verifyApiKey` with `whatsapp: mint`), finds or creates the BSUID's user through `account (provider_id = 'whatsapp', account_id = )` (`unique (provider_id, account_id)` makes it one user under concurrency), checks eligibility under a lock on the user row (only that account row, its own `whatsapp-@noreply.askansari.ai` address, `registered_via = 'whatsapp'`, role exactly `user`, an allowlist; otherwise 500, never a token) and the ban (403, sessions deleted), reuses one session per user, and signs the ordinary `{sub, sid}` JWT after commit. So a key can only ever yield tokens for WhatsApp users: never an email user, an admin, a system or a service account. The BSUID lives only in `account.account_id` and reaches no log, response or `apps/api`. No phone number is stored anywhere (owner amendment 2): a `phone_number` the WhatsApp service sends is accepted and ignored. `@noreply.askansari.ai` is refused at sign-up (as a taken address), reset (as an unknown one), a grant by `grant-admin.ts`, and the `user.create.before` hook on every Better Auth path. **apps/api has no WhatsApp code** (a source scan); the exchange JWT passes `requireUser` unchanged. **Alert posture:** the exchange's alerts (per-key volume at one third of the caps, key refusals, 401 volume, ineligible users, an unresolvable service user) carry key ids, counts, thresholds and windows only in Sentry (a key id is a plugin-made UUID that names a credential, not a person, and matches `list`); user ids appear only in server log lines, and the service's Sentry keeps no breadcrumbs, so a logged id never rides on an event. `apps/auth` refuses to boot without `auth.apikey` or the constraint (migration `0001`). Operator procedure: `docs/cutover/service-keys-runbook.md`.
+
+**The MCP key and its verify route (#314).** `/v2/mcp-complete` is apps/api's one route that takes something other than a JWT: `Authorization: Bearer ` (scheme case-insensitive). apps/api cannot verify the key itself (the hash lives in the auth database), so on every request it asks apps/auth at its public origin, `POST /api/service/verify-key` with `{key, permissions: {mcp: ['complete']}}` (`verifyServiceKey`, `lib/auth-service/client.ts`, 3 s timeout). The route calls `verifyApiKey` in process, mounted ahead of CORS and outside Better Auth's router (no per-IP rule, no credential but the key), and serves a **closed permission set**: exactly `{mcp: ['complete']}` for the `ansari-mcp` service user, anything else 400, so it can neither verify nor spend a WhatsApp key under its own permission. It answers `{valid: true, client_id, key_id}` or one byte-identical `{valid: false}` for every refusal, including a key whose `client_id` is not `ansari-mcp*` (the script refuses to make one; the `client-id-invalid` alert names it); apps/api accepts only those two shapes, anything else is an outage. **Fail closed:** refused → 401, outage or timeout → 503, before any persistence or model call. The thread's `client` is the key's `client_id`; `X-Ansari-Client` is ignored (Sentry warning on a mismatch). Each verify spends one unit of the key's own budget and window, which is the throttle (one key per MCP deployment, 120 per minute and 5,000 a day initially); the route's per-IP cap in apps/api stays. **Log-only transition:** `MCP_COMPLETE_KEY_MODE=log-only` verifies, records the verdict (`valid`/`missing`/`refused`/`unverified`, log line and Sentry tag `mcp_key_verdict`) and always serves; absent means `enforce`, anything else fails boot. The mode, its `turbo.json` entry and log-only itself are to be removed by a follow-up issue due one week after enforcement. Verify alerts mirror the exchange's under `auth: MCP key verify alert`. A plugin bump that ever routes `/api-key/verify` fails `apps/auth/tests/blocked-paths.test.ts`.
 
 **The legacy surface.** `/v2/users/*` and the two reset routes stay on `apps/api` for the released mobile app, as anonymous pass-through clients of `apps/auth`'s public endpoints (no credential, no forwarded IP), with frozen response shapes (a SHA-pinned contract suite). `register` and `login` return the JWT as `access_token` and the session token as `refresh_token`; `refresh_token` returns a new JWT for the same session. `DELETE /v2/users/me` deletes the app row and writes the tombstone in one transaction, then calls `DELETE /api/account` with the user's JWT (refused before any call unless the token's `sub` is that user). A user who calls `DELETE /api/account` directly leaves the app row and no tombstone: an owner-accepted residual whose operator response is in the runbook ("Orphan app rows").
 
diff --git a/codev/state/spir-314_thread.md b/codev/state/spir-314_thread.md
index 36fd82ff..845adcc5 100644
--- a/codev/state/spir-314_thread.md
+++ b/codev/state/spir-314_thread.md
@@ -63,3 +63,9 @@
 - Phase 4 consults iter 1: codex APPROVE, gemini APPROVE (nit: a stale "does not require authentication" test in mcp-complete.test.ts, now replaced with "requires a key → 401").
 - Security architect (04:10Z) ordered two changes, both done: (1) apps/auth `alerts.keyVerified()` moved after the owner and client-id checks, so only a served key counts toward the volume alerts (refusals already count through refuse()). Pinned by a new service-verify test that fails under the old ordering. The WhatsApp exchange ordering is unchanged (not ordered). (2) The stale `client` comment in handleMcpComplete now says the key decides.
 - Flaky once: `apps/auth/tests/whatsapp-session.test.ts` > "auth.apikey dropped under the running service → 500 …" got 404 where it expected 401, in one full `npm test` run (4 packages in parallel, 4 workers each). It passed 3/3 in isolation and on a full rerun. The exchange route is untouched by this change. Same under-load 404 class as require-user (#330 lineage). Documented, not skipped.
+
+## 2026-11-11 phase 5 — docs
+- Rebased onto develop (#365 mcp-staging, #368 apps/mcp/.env.example, #370 mcp turbo env pins): no conflicts. One break: #366 changed the mcp-complete attribution link to askansari.ai, and `mcp-complete-key.test.ts` scenario 4 still asserted `ansari.chat`. Fixed in its own commit.
+- Runbook: new `## The \`ansari-mcp\` key (#314)` with `###` subsections (issuance per deployment incl. mcp-staging `--client-id ansari-mcp-staging` before staging deploys #314, Bearer handoff for Worker/Railway/owner, rollout, limits, alerts incl. `client-id-invalid`, rotation, plugin-upgrade check). Kept `###` so `cutover-docs.test.ts`'s `section('Limits')`/`section('Alerts')` still read only the WhatsApp tables.
+- Surprise: the runbook path scan's regex reads `apps/mcp/wrangler.jsonc` as `apps/mcp/wrangler.json` (no end anchor after the extension), which does not exist. Reworded to "apps/mcp's `wrangler.jsonc`" rather than touch the scan.
+- self-hosting.md: new MCP key subsection; "ansari-mcp reserved" wording fixed there and in arch.md and the runbook intro. apps/mcp README + .env.example + RELEASE.md staging table: `Bearer ansari_mcp_<64 letters>`. arch-critical JWT fact amended in place; arch.md gains the verify-route paragraph.
diff --git a/docs/cutover/service-keys-runbook.md b/docs/cutover/service-keys-runbook.md
index 49014957..135ef96f 100644
--- a/docs/cutover/service-keys-runbook.md
+++ b/docs/cutover/service-keys-runbook.md
@@ -2,9 +2,12 @@
 
 How the operator issues, hands off, rotates, changes and revokes a service's API key, applies
 the migration they depend on, and answers the alerts the WhatsApp token exchange raises. The
-design and its reasons are in `codev/specs/329-apps-auth-service-api-keys-bet.md`.
+design and its reasons are in `codev/specs/329-apps-auth-service-api-keys-bet.md`. The
+`ansari-mcp` key (#314) has its own section,
+[The `ansari-mcp` key](#the-ansari-mcp-key-314): its issuance, handoff, limits and alerts differ;
+the script, revocation, the key log and secret scanning are shared.
 
-A **service** (the WhatsApp service; later `ansari-mcp`, #314) is one auth user with no
+A **service** (the WhatsApp service, or `ansari-mcp`, #314) is one auth user with no
 credential, under `@noreply.askansari.ai`, found by its `{provider_id: 'service', account_id:
 }` account row. Its **keys** are rows in `auth.apikey`, created through the
 `@better-auth/api-key` plugin in process. The plugin's HTTP surface is blocked, so
@@ -265,3 +268,137 @@ the hash of the whole key, so nothing breaks; but replace it: `rotate whatsapp`
 `ansari_wa_` key once), switch the consumer's variable to it, then `revoke` the old key. Keep the
 old organisation pattern (`wa_` followed by 64 letters) registered beside the new ones until the
 last `wa_` key is revoked, then remove it.
+
+## The `ansari-mcp` key (#314)
+
+`POST /api/v2/mcp-complete` on apps/api takes an `ansari-mcp` key as `Authorization: Bearer
+` and asks apps/auth whether it is good at `POST /api/service/verify-key` on every request.
+A missing or refused key is 401 `{"error":"Unauthorized"}`; apps/auth unreachable or slower than
+apps/api's client timeout (3 s) is 503 `{"error":"Authentication service unavailable"}`, with
+nothing persisted and no Gemini call. The design is in
+`codev/specs/314-protect-v2-mcp-complete-with-b.md`. The [script](#the-script),
+[revocation](#revocation-and-pruning), the [key log](#key-log) and
+[secret scanning](#secret-scanning) are the same as for WhatsApp; what differs is below.
+
+### Issuance
+
+**One key per MCP deployment** that calls a deployed apps/api, so each can be rotated or
+revoked alone and its traffic is attributed to it:
+
+| Deployment | Who sets its variable | `--client-id` |
+|---|---|---|
+| `mcp.ansari.chat` | the owner (owner-operated, outside this repository) | the owner's choice of `ansari-mcp*` id |
+| `mcp-staging.askansari.ai` (apps/mcp on Railway, see `RELEASE.md`) | the operator, as a Railway service variable | `ansari-mcp-staging` (its `ANSARI_CLIENT`) |
+| each apps/mcp Worker environment in use (apps/mcp's `wrangler.jsonc`) | the operator, as a Worker secret | its `ANSARI_CLIENT`: `ansari-mcp-dev`, `ansari-mcp-beta` or `ansari-mcp-production` |
+
+1. apps/auth is deployed with the verify route (it ships with this change; there is no new
+   migration: `auth.apikey` is spec 329's `0001`).
+2. Once: `create-service ansari-mcp`, then `create-service ansari-mcp --confirm ansari-mcp`.
+3. Per deployment: `create-key ansari-mcp --rate-max 120 --rate-window 60 --daily 5000 --name
+    --client-id `, read the shown user, then repeat with
+   `--confirm `. These are the initial values (`MCP_KEY_INITIAL`); see
+   [Limits](#limits-1).
+4. Hand the key off (next section) before you do anything else in the shell.
+
+`--client-id` is **required** for `ansari-mcp` and must be `ansari-mcp`, or `ansari-mcp-` and a
+suffix of lowercase letters, digits, dots, underscores and hyphens, 64 characters at most;
+anything else is refused with nothing written. It is what apps/api stores as the thread's
+`client`: a conflicting `X-Ansari-Client` header is ignored (Sentry warning
+`mcp-complete client mismatch`).
+
+**Staging order.** `mcp-staging.askansari.ai` sends no key today. Its key is created and set
+**before** apps/api on staging deploys #314: apps/api defaults to `enforce`, so a staging deploy
+without the key, or without `MCP_COMPLETE_KEY_MODE=log-only`, refuses every staging MCP call.
+
+### The handoff
+
+apps/mcp sends `ANSARI_API_AUTHORIZATION` **verbatim** as the `Authorization` header, so the
+value is the whole header: `Bearer ansari_mcp_<64 letters>`, the word `Bearer`, one space, then
+the key. A bare key is no bearer: apps/api answers 401 (verdict `missing` in log-only).
+
+- **Worker:** from `apps/mcp/`, `wrangler secret put ANSARI_API_AUTHORIZATION --env `, and
+  paste the value at its prompt, straight from the shell you created the key in. Never put it on
+  the command line, in `wrangler.jsonc` or in a `.dev.vars.` file.
+- **Railway (`mcp-staging`):** paste the value **straight into the mcp service's
+  `ANSARI_API_AUTHORIZATION` variable**, then let it redeploy.
+- **`mcp.ansari.chat`:** the owner sets their own upstream Authorization variable to the same
+  form.
+
+The rule of [The handoff](#the-handoff) holds: no chat, ticket, document or history file. Then
+clear the terminal.
+
+### Rollout: log-only, then enforce
+
+`MCP_COMPLETE_KEY_MODE` on apps/api: `enforce` (the default, and what an absent variable means)
+or `log-only`. Any other value stops apps/api at boot.
+
+1. Issue and hand off every deployment's key (above). Today's route ignores the header, so this
+   is safe at any time.
+2. Deploy apps/api with `MCP_COMPLETE_KEY_MODE=log-only`. It verifies every request, records the
+   verdict, and always serves, even with apps/auth down.
+3. Watch the verdicts for one week: the log line `[ai-skill] mcp-complete key verdict`
+   (`{verdict, keyId}`) and the Sentry tag `mcp_key_verdict`, one of `valid`, `missing` (no
+   bearer), `refused` (`valid: false`) or `unverified` (apps/auth gave no usable answer; also the
+   Sentry warning `mcp-complete key unverified (log-only)`). Expect no `missing` or `refused`
+   from the MCP servers.
+4. Remove the variable, which enforces.
+5. Open the follow-up issue due one week after the enforce date: remove log-only mode,
+   `MCP_COMPLETE_KEY_MODE` and its `turbo.json` entry, so a transition switch does not outlive
+   the transition as a way to turn auth off.
+
+In `enforce`, an apps/auth outage is a 503 for every MCP call (log line
+`[ai-skill] mcp-complete key verify unavailable`), never a 200 without a key.
+
+### Limits
+
+| Value | Initial | Meaning |
+|---|---|---|
+| `--rate-max` / `--rate-window` | 120 per 60 s | Per key, across all of that deployment's users together: the burst ceiling for its MCP traffic. |
+| `--daily` | 5,000 | The daily Gemini ceiling for the deployment, refilled every 24 h. |
+| apps/api per-IP cap | 120 per minute, per client IP | `RATE_LIMIT_PER_MINUTE` in `apps/api/src/app/api/v2/mcp-complete/route.ts`; a second layer, unchanged. |
+
+Every `mcp-complete` call is one verify, and each verify spends one unit of the key's budget and
+one slot of its window. A key at its cap answers `valid: false`, so its callers get 401. Like
+WhatsApp's, these values are **judgement, not measurement**, pending the owner's
+`threads.client` numbers; change them with `update-limits`. The accepted ranges
+(`MCP_KEY_BOUNDS` in `packages/auth/src/limits.ts`) equal WhatsApp's. The total ceiling is the
+sum over live keys.
+
+### Alerts
+
+Every verify alert is one Sentry event `auth: MCP key verify alert: `, tagged
+`alert: mcp-verify-`, with key ids, counts, thresholds and windows only, on the terms of
+the WhatsApp [Alerts](#alerts): at most once per 5-minute window, refusing nothing.
+
+| `kind` | Means | Do |
+|---|---|---|
+| `key-window-volume` | One key made `MCP_VERIFY_KEY_ALERT` (40) verifies inside its 60 s window: a third of its cap. At most once per key every 5 minutes. | Check that deployment for a loop. Expected only on a real surge. |
+| `key-daily-volume` | One key made `MCP_VERIFY_DAILY_ALERT` (1,666) verifies since its daily refill. | Compare with the deployment's traffic. A surge you trust: `update-limits`. Otherwise treat the key as leaked. |
+| `key-refused` (`USAGE_EXCEEDED` / `RATE_LIMITED`) | The key hit its budget or window; its callers are getting 401. | Users are affected now. Confirm the traffic is real, then `update-limits`; if not, rotate and revoke. |
+| `unauthorized-volume` | `valid: false` answers reached 20 in a window. | Outside a rotation a healthy MCP server sees none: a revoked key, a key without `Bearer ` in a deployment's variable, a WhatsApp key, or someone guessing. Check each deployment's variable against `list ansari-mcp`. |
+| `service-user-unresolvable` | The `ansari-mcp` service user is missing or not unique: every verify is a 500, so every MCP call is 503 (enforce). | `list ansari-mcp`; if it reports no or several service users, report to the security architect before changing anything. |
+| `client-id-invalid` | The plugin accepted a key whose `client_id` is missing or not `ansari-mcp*` (a key made outside the script); its caller got `valid: false`. The event names its `keyId`. | Revoke that key and issue a proper one with the script. Record how it came to exist in the key log. |
+
+### Rotation
+
+As [Rotation](#rotation), per deployment:
+
+1. `rotate ansari-mcp` with the same limit flags and **the same `--client-id`** as the current
+   key (see `list`), confirmed by id.
+2. Hand the new key off into that deployment's variable (`wrangler secret put … --env `, the
+   Railway variable, or the owner's), and redeploy it.
+3. `list ansari-mcp`: the new key's last request moves, the old key's stops.
+4. `revoke ansari-mcp --key `, confirmed by id.
+
+**While two keys are live, the deployment's ceiling doubles.** Keep the overlap to minutes.
+
+### Plugin upgrade check
+
+The verify route calls `verifyApiKey` in process; the plugin's own `POST /api-key/verify` must
+never be routed (its docs advertise one; 1.7.7, 1.7.20 and 1.8.0-beta.7 do not route it).
+Before any `@better-auth/api-key` bump, run apps/auth's tests: `apps/auth/tests/blocked-paths.test.ts`
+fails if `verifyApiKey` gains an HTTP path or the plugin's routed endpoints change, and asserts
+that `/api/auth/api-key/verify` (any case, trailing slash) is refused. A failure there blocks the
+bump until the blocked paths are re-checked by the security architect. Also re-read the plugin's
+changelog for verify's refusal codes and its expiry behaviour (it deletes an expired key on
+presentation, so expiry is never used on a key whose history matters).
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 44416a15..f968df51 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -229,8 +229,8 @@ Verify admins with `grant-admin.ts --list` from `apps/auth/`.
 
 ### Service keys and the WhatsApp exchange (spec 329)
 
-`apps/auth` issues API keys to services (the WhatsApp service today; `ansari-mcp` is reserved
-for #314) through `@better-auth/api-key`. A service is one auth user under
+`apps/auth` issues API keys to services (the WhatsApp service, and `ansari-mcp` for
+`/api/v2/mcp-complete`, #314) through `@better-auth/api-key`. A service is one auth user under
 `@noreply.askansari.ai` with no credential. Keys are stored hashed in `auth.apikey`; the
 plugin's HTTP surface is blocked, so keys are created, listed, rotated, changed and revoked only
 with `apps/auth/scripts/service-keys.ts`, run from `apps/auth/` in the auth service's shell
@@ -263,3 +263,24 @@ auth database (after the duplicate check in the runbook, in a quiet window: it l
 without it. On a deployment that tracks Ansari's own order: staging gets `0001` before the merge,
 and production gets the whole auth journal, in order, at its cutover
 (`docs/cutover/better-auth-cutover.md`).
+
+### MCP completions need a service key (#314)
+
+`POST /api/v2/mcp-complete` on `apps/api` requires `Authorization: Bearer ` (the scheme word
+in any case), where the key is an `ansari-mcp` service key made with `service-keys.ts`
+(`create-key ansari-mcp … --client-id `; the client id is required and must be
+`ansari-mcp` or `ansari-mcp-`). For every request, `apps/api` asks `apps/auth` at its
+public origin, `POST /api/service/verify-key` with `{"key": "...", "permissions": {"mcp":
+["complete"]}}`; the route serves that permission set only, so a WhatsApp key is refused. It
+answers `200 {valid: true, client_id, key_id}` or one `200 {valid: false}` for every refusal,
+`400` for a malformed body and `500` otherwise; it sits outside Better Auth's router (no per-IP
+rule, no CORS) and carries no credential but the key itself, which also spends one unit of the
+key's own budget and window.
+
+In `enforce` mode (`MCP_COMPLETE_KEY_MODE`, above) a missing or refused key is `401
+{"error":"Unauthorized"}`, and `apps/auth` unreachable, or slower than apps/api's client timeout
+(`AUTH_SERVICE_TIMEOUT_MS` in `apps/api/lib/auth-service/client.ts`, 3 s), is `503 {"error":"Authentication service unavailable"}`, with nothing persisted and no
+model call. The thread's `client` is the key's client id; a different `X-Ansari-Client` is
+ignored. The route's per-IP cap (120 a minute) stays. An MCP server built from `apps/mcp` sends
+its `ANSARI_API_AUTHORIZATION` verbatim, so that variable holds `Bearer ` and the key. Issuance,
+handoff, rollout, limits, alerts and rotation: `docs/cutover/service-keys-runbook.md`.

From cd24f5e7d621d1bc1d3a53e1c019471beee2c985 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:20:58 +1100
Subject: [PATCH 142/435] chore(porch): 314 implement build-complete

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 3c01fba6..cdf5f69c 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -33,7 +33,7 @@ gates:
   verify-approval:
     status: pending
 iteration: 1
-build_complete: false
+build_complete: true
 history:
   - iteration: 1
     plan_phase: phase_2
@@ -72,7 +72,7 @@ history:
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:15:29.368Z'
+updated_at: '2026-11-11T04:20:58.810Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'

From c4b4fe0f2be22e414585450754d1e5e9fefeb02c Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:22:31 +1100
Subject: [PATCH 143/435] [Spec 314][Phase: 5] docs: a bearer-less variable is
 apps/api's 'missing' verdict, not a verify 401 (codex)

---
 docs/cutover/service-keys-runbook.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/docs/cutover/service-keys-runbook.md b/docs/cutover/service-keys-runbook.md
index 135ef96f..87b92b13 100644
--- a/docs/cutover/service-keys-runbook.md
+++ b/docs/cutover/service-keys-runbook.md
@@ -375,7 +375,7 @@ the WhatsApp [Alerts](#alerts): at most once per 5-minute window, refusing nothi
 | `key-window-volume` | One key made `MCP_VERIFY_KEY_ALERT` (40) verifies inside its 60 s window: a third of its cap. At most once per key every 5 minutes. | Check that deployment for a loop. Expected only on a real surge. |
 | `key-daily-volume` | One key made `MCP_VERIFY_DAILY_ALERT` (1,666) verifies since its daily refill. | Compare with the deployment's traffic. A surge you trust: `update-limits`. Otherwise treat the key as leaked. |
 | `key-refused` (`USAGE_EXCEEDED` / `RATE_LIMITED`) | The key hit its budget or window; its callers are getting 401. | Users are affected now. Confirm the traffic is real, then `update-limits`; if not, rotate and revoke. |
-| `unauthorized-volume` | `valid: false` answers reached 20 in a window. | Outside a rotation a healthy MCP server sees none: a revoked key, a key without `Bearer ` in a deployment's variable, a WhatsApp key, or someone guessing. Check each deployment's variable against `list ansari-mcp`. |
+| `unauthorized-volume` | `valid: false` answers reached 20 in a window. | Outside a rotation a healthy MCP server sees none: a revoked key, a WhatsApp key, or someone guessing. Check each deployment's variable against `list ansari-mcp`. (A variable without `Bearer ` never reaches this route: apps/api records it as verdict `missing`.) |
 | `service-user-unresolvable` | The `ansari-mcp` service user is missing or not unique: every verify is a 500, so every MCP call is 503 (enforce). | `list ansari-mcp`; if it reports no or several service users, report to the security architect before changing anything. |
 | `client-id-invalid` | The plugin accepted a key whose `client_id` is missing or not `ansari-mcp*` (a key made outside the script); its caller got `valid: false`. The event names its `keyId`. | Revoke that key and issue a proper one with the script. Record how it came to exist in the key log. |
 

From 2c3a969f46f2fad240bea6b29c7e5e2224a7a632 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:22:33 +1100
Subject: [PATCH 144/435] chore(porch): 314 implement re-iter (iter 2)

---
 .../status.yaml                                | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index cdf5f69c..b96852c9 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -32,8 +32,8 @@ gates:
     status: pending
   verify-approval:
     status: pending
-iteration: 1
-build_complete: true
+iteration: 2
+build_complete: false
 history:
   - iteration: 1
     plan_phase: phase_2
@@ -71,8 +71,20 @@ history:
         verdict: APPROVE
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-gemini.txt
+  - iteration: 1
+    plan_phase: phase_5
+    build_output: ''
+    reviews:
+      - model: codex
+        verdict: REQUEST_CHANGES
+        file: >-
+          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-codex.txt
+      - model: gemini
+        verdict: APPROVE
+        file: >-
+          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:20:58.810Z'
+updated_at: '2026-11-11T04:22:33.745Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'

From ce9ca14f3227836be0cced86780b366a2815dcc7 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:23:42 +1100
Subject: [PATCH 145/435] chore(porch): 314 implement build-complete

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index b96852c9..ea071ed6 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -33,7 +33,7 @@ gates:
   verify-approval:
     status: pending
 iteration: 2
-build_complete: false
+build_complete: true
 history:
   - iteration: 1
     plan_phase: phase_2
@@ -84,7 +84,7 @@ history:
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:22:33.745Z'
+updated_at: '2026-11-11T04:23:42.410Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'

From 73c8c2111fe238cd1205e5f1ead64f1358bc5f69 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:24:44 +1100
Subject: [PATCH 146/435] =?UTF-8?q?chore(porch):=20314=20all=20plan=20phas?=
 =?UTF-8?q?es=20complete=20=E2=86=92=20review?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../314-protect-v2-mcp-complete-with-b/status.yaml | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index ea071ed6..926db032 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -1,7 +1,7 @@
 id: '314'
 title: protect-v2-mcp-complete-with-b
 protocol: spir
-phase: implement
+phase: review
 plan_phases:
   - id: phase_1
     title: 'ansari-mcp key rules: limits, client-id rule, script constraints'
@@ -17,8 +17,8 @@ plan_phases:
     status: complete
   - id: phase_5
     title: Docs, runbook and architecture notes
-    status: in_progress
-current_plan_phase: phase_5
+    status: complete
+current_plan_phase: null
 gates:
   spec-approval:
     status: approved
@@ -32,8 +32,8 @@ gates:
     status: pending
   verify-approval:
     status: pending
-iteration: 2
-build_complete: true
+iteration: 1
+build_complete: false
 history:
   - iteration: 1
     plan_phase: phase_2
@@ -84,7 +84,7 @@ history:
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:23:42.410Z'
+updated_at: '2026-11-11T04:24:44.938Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'
@@ -104,3 +104,5 @@ context_refreshes:
   - boundary: plan-phase:phase_5
     at: '2026-11-11T04:15:22.154Z'
     acknowledged_at: '2026-11-11T04:15:29.367Z'
+  - boundary: enter:review
+    at: '2026-11-11T04:24:44.938Z'

From 3674eb74c701579df83635044cf359c4ee91bcba Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:25:26 +1100
Subject: [PATCH 147/435] chore(porch): 314 acknowledge context refresh

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 926db032..561f218a 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -84,7 +84,7 @@ history:
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:24:44.938Z'
+updated_at: '2026-11-11T04:25:26.571Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'
@@ -106,3 +106,4 @@ context_refreshes:
     acknowledged_at: '2026-11-11T04:15:29.367Z'
   - boundary: enter:review
     at: '2026-11-11T04:24:44.938Z'
+    acknowledged_at: '2026-11-11T04:25:26.571Z'

From 53601f6474ad8b427e303e9d54b3494d54e62534 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:27:28 +1100
Subject: [PATCH 148/435] [Spec 314] Review: retrospective, lessons routed
 (cold + hot map line), thread

---
 codev/resources/lessons-critical.md           |   2 +-
 codev/resources/lessons-learned.md            |   4 +
 .../314-protect-v2-mcp-complete-with-b.md     | 170 ++++++++++++++++++
 codev/state/spir-314_thread.md                |   4 +
 4 files changed, 179 insertions(+), 1 deletion(-)
 create mode 100644 codev/reviews/314-protect-v2-mcp-complete-with-b.md

diff --git a/codev/resources/lessons-critical.md b/codev/resources/lessons-critical.md
index 971ea1c2..5b659356 100644
--- a/codev/resources/lessons-critical.md
+++ b/codev/resources/lessons-critical.md
@@ -31,4 +31,4 @@ STARTER: a few universal lessons are seeded; add your project's as you learn the
 - New Ansari logo — frontend (issue #223) — consult when changing an SVG mark or its viewBox, regenerating icon rasters, adding a test in a new directory, or taking screenshots without the Chrome extension.
 - Ambient shadow strength (issue #225) + jitter (issue #254) — frontend — consult when tuning a visual intensity constant (size it in ΔL*), turning a knob whose effect a solver may cancel, chasing a smoothness report from a phone, measuring on a real device without a cable, judging a visual change by eye (blind A/B), or changing a video's playback rate, loop encode or arrival.
 - Scripture in answer prose — frontend (issue #228) — consult when mixing Arabic and English in one text block, classifying text by script, keeping an inline control on its word's line, balancing centred lines, or asserting react-native-web styles in jsdom.
-- Better Auth migration (spec 300) + Service API keys / WhatsApp exchange (spec 329) — consult when testing a production-only rule, writing psql guard/copy scripts, guarding a first-use insert against a concurrent delete, caching a remote JWKS, reading better-auth internals or its plugins, locking a parent row (`FOR NO KEY UPDATE`), calling the pool inside a transaction, testing what Sentry sends, bundling native modules, building a service image, or recording an infrastructure inference.
+- Better Auth migration (spec 300) + Service API keys / WhatsApp exchange (spec 329) + MCP key verify (spec 314) — consult when gating a route on a remote key verify, testing a production-only rule, writing psql guard/copy scripts, guarding a first-use insert against a concurrent delete, caching a remote JWKS, reading better-auth internals or its plugins, locking a parent row (`FOR NO KEY UPDATE`), calling the pool inside a transaction, testing what Sentry sends, bundling native modules, building a service image, or recording an infrastructure inference.
diff --git a/codev/resources/lessons-learned.md b/codev/resources/lessons-learned.md
index d413fa9e..28cf41ed 100644
--- a/codev/resources/lessons-learned.md
+++ b/codev/resources/lessons-learned.md
@@ -245,3 +245,7 @@ See `codev/reviews/329-apps-auth-service-api-keys-bet.md` for the full context.
 - **A mutant can survive behind a cache.** A relation check cached for a TTL hid a reordering mutant, because an earlier test had warmed the cache. Advance the clock past the TTL in the test that counts queries.
 - **An auth plugin's routes are live even when its sender is a placeholder.** better-auth's phone-number plugin with a `sendOTP` that throws still stores a live code before the throw, creates a session on `/phone-number/verify`, signs in by phone and password without ever calling the sender, and sets a password through reset-by-phone, even on an account that had none. Probe a plugin's whole surface before relying on any option to neuter it, and close routes with a before hook (an after hook cannot fix the status line).
 - **porch: a rollback to plan resets every plan phase.** `porch rollback  plan` re-extracts the plan, and phases already built and approved come back pending. Parent consultation mode emits a `phase-review-*` gate that `porch approve` does not know, and `none` mode loops between `done` and `next`; both dead-end for plan phases (codev of 2026-10). Normal mode replays the recorded review files iteration by iteration, so a re-walk of unchanged phases costs checks only.
+- **(spec 314) An expired service key leaves no row behind.** `@better-auth/api-key` 1.7.7 deletes an expired key when it is presented, before refusing it. Never put an expiry on a key whose audit trail matters. Disable or revoke it instead. See `codev/reviews/314-protect-v2-mcp-complete-with-b.md`.
+- **(spec 314) Read the published package, not the plugin docs.** The docs' `POST /api-key/verify` comes only from a JSDoc comment. `verifyApiKey` is server-only, with no route, in 1.7.7, 1.7.20 and 1.8.0-beta.7. On any plugin bump, re-run the upgrade guard in `apps/auth/tests/blocked-paths.test.ts`, which checks the endpoint shapes and that a newly routed path is under the blocked prefix.
+- **(spec 314) In a verify path, count a success only after the last check.** Calling `keyVerified()` before the owner and client-id checks let refused keys inflate the volume alerts. Pin the order with a test that fails under the old order.
+- **(spec 314) Pin a remote verdict's refusal shape on both sides.** apps/auth asserts a byte-identical `{"valid":false}`. apps/api accepts only that shape and treats anything else as an outage (503). Adding a field on one side turns every bad key into a 503, so both sides must change together.
diff --git a/codev/reviews/314-protect-v2-mcp-complete-with-b.md b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
new file mode 100644
index 00000000..debea288
--- /dev/null
+++ b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
@@ -0,0 +1,170 @@
+# Review: Protect `/v2/mcp-complete` with Better Auth API keys issued by apps/auth
+
+## Summary
+
+`POST/GET /api/v2/mcp-complete` now requires `Authorization: Bearer `. apps/api checks the key on every request at a new public apps/auth route, `POST /api/service/verify-key`. That route is the second consumer of spec 329's api-key plugin. It answers `{valid, client_id, key_id}` or a byte-identical `{valid:false}`. The thread's `client` comes from the key's metadata. A missing or refused key gets 401. An apps/auth outage gets 503: fail closed, nothing persisted, no Gemini call. `MCP_COMPLETE_KEY_MODE=log-only` gives a one-week transition in which every verdict is recorded and every request is served. The work shipped in five plan phases, all on one branch: key rules, verify route, apps/api client and mode, route gate, docs.
+
+## Spec Compliance
+
+- [x] No `Authorization` → 401, no apps/auth call, no thread, no Gemini call, in enforce mode, POST and GET (Phase 4; `apps/api/tests/mcp-complete-key.test.ts` scenario 1).
+- [x] Revoked, disabled, expired, exhausted, rate-limited, wrong-permission (WhatsApp) and unknown keys → the same 401 body, no thread, no Gemini call (Phase 2 at the route, Phase 4 through apps/api).
+- [x] A valid `ansari-mcp` key → today's behaviour. The thread and its messages carry `client` = the key's `client_id` (Phase 4).
+- [x] Forged `X-Ansari-Client` with a valid key → the key's client, one `mcp-complete client mismatch` Sentry warning carrying ids only, request served (Phase 4).
+- [x] apps/auth unreachable, timing out (`AUTH_SERVICE_TIMEOUT_MS` 3000), 5xx or a malformed body → 503 within the timeout, nothing persisted, no Gemini call (Phase 3 client, Phase 4 route).
+- [x] The verify route answers `{valid:true, client_id, key_id}` or a byte-identical `{"valid":false}`. Any other permission set → 400, with a body that names no permission. A missing `auth.apikey`, a DB outage or an unresolvable service user → 500 (Phase 2).
+- [x] A WhatsApp key is refused by permission and by owner, and its `remaining` is not spent, at the route and through apps/api (Phases 2 and 4).
+- [x] A key owned by another user that carries `mcp: complete` is refused (Phase 2).
+- [x] An `ansari-mcp` key whose `client_id` is missing or not `ansari-mcp*` is refused and raises `client-id-invalid`. The script refuses to create one, and `list` prints each key's `client_id` (Phases 1 and 2).
+- [x] `MCP_COMPLETE_KEY_MODE` accepts exactly `log-only` and `enforce`, means `enforce` when absent, and is rejected at production boot for any other value (Phase 3).
+- [x] Log-only with apps/auth unreachable → served, verdict `unverified`, Sentry warning (Phase 4).
+- [x] Each verify spends one unit of budget. An exhausted key is refused until its daily refill, and the row is kept (Phase 2).
+- [x] No CORS headers on any verify response, preflight included (Phase 2: mounted ahead of `corsFor`).
+- [x] No raw key, and no substring of its random part, in any response, log line, Sentry event or DB column, in either app. Leak scans cover logs, Sentry transport events and the `apikey` row, using 16-char windows with the prefix exempt (Phases 2 and 4; mutation-checked).
+- [x] Log-only records every verdict and serves. Enforce is the behaviour when the setting is absent (Phases 3 and 4).
+- [x] pglite tests for the verify route (real plugin, real `auth.apikey`) and for the apps/api route (real app DB, apps/auth answered by a `fetch` stub of the verify contract, real `verifyServiceKey`), including the forged-header and WhatsApp-key cases (Phases 2 and 4).
+- [x] Docs (§5): `docs/self-hosting.md`, `docs/cutover/service-keys-runbook.md` (issuance per deployment, Bearer hand-off, rollout, limits, alerts, rotation, plugin-upgrade check), `apps/api/README.md`, `apps/mcp/README.md`, `apps/mcp/.env.example`, the RELEASE.md staging row (Phase 5).
+- [ ] **Operator steps, outside the repository. Not done by this PR; the owner must do them before enforce:**
+  1. Create one key per MCP deployment with `apps/auth/scripts/service-keys.ts` and `--client-id`. That means production `mcp.ansari.chat` (`ansari-mcp`) and `mcp-staging.askansari.ai` (`--client-id ansari-mcp-staging`). The staging key must exist **before apps/api staging deploys this change**, because the default mode is enforce.
+  2. Set each Worker's/service's `ANSARI_API_AUTHORIZATION` to `Bearer ansari_mcp_<64 letters>`, prefix included.
+  3. Update the published integration snippet and the MCP setup page on the public site. Their locations are still pending from the owner, via the security architect.
+  4. Run the rollout: deploy with `MCP_COMPLETE_KEY_MODE=log-only`, watch the `mcp_key_verdict` tag for a week, then remove the variable (enforce). At enforce, open the follow-up that removes log-only and the `turbo.json` hunk one week later.
+
+## Deviations from Plan
+
+- **Phase 1:** none.
+- **Phase 2:**
+  - The plan named `createKeyAlerts({ service, thresholds, message, tagPrefix, send, now })`. It was built as `createKeyAlerts({ thresholds, keyWindowFloorMs, send, now })` plus `keyAlertSender(message, tagPrefix)`. The behaviour is the same. `keyWindowFloorMs` came from codex iter 2 (MCP window alerts at most once per alert window).
+  - Extra file `apps/auth/src/routes/apikey-relation.ts`: the shared `auth.apikey` relation check, now also used by the WhatsApp exchange.
+  - **Spec Amendment 1:** the plugin deletes an expired key's row when the key is presented (`validateApiKey`, `@better-auth/api-key` 1.7.7). Spec scenario 2 was amended with the security architect's approval, and the test asserts that the row is gone.
+  - Plugin fact: in 1.7.7, `verifyApiKey` returns `metadata` as an object, although it is stored as JSON text. `clientIdOf` handles both forms and is pinned for both.
+- **Phase 3:** none in code. The removal follow-up is undated. It opens at enforce (rollout step 6), per the security architect.
+- **Phase 4:**
+  - The plan named 7 suites to move onto a key. Only 3 call the route: `mcp-complete`, `route-persistence-rollback` and `toolcalls-routes`. `attribution.test.ts`, `rate-limit.test.ts`, `facilitator-empty-final.test.ts` and `tests/sentry/request-envelopes.ts` test helpers directly and were left unchanged. The plan placed the MCP attribution cases in `attribution.test.ts`, but they lived in `mcp-complete.test.ts` and were rewritten there.
+  - The Bearer scheme is case-insensitive, as the plan says. apps/auth's account `bearerOf` is case-sensitive. The two differ deliberately and are not unified here.
+  - Scenario 11 (mode parsing, boot refusal) is covered by Phase 3's config and boot-check tests. Scenario 13 is covered at the seam.
+  - Security architect order (04:10Z): `alerts.keyVerified()` moved after the owner and client-id checks in `service-verify.ts`, so only a served key counts toward the volume alerts. A test pins the order and fails under the old one. The WhatsApp exchange order is unchanged.
+- **Phase 5:** rebased onto develop (#365, #368, #370) first. #366 had changed the attribution link to `askansari.ai`, so scenario 4's expectation followed it in its own commit. Architect orders added the `mcp-staging` key, the `Bearer` form in all three apps/mcp docs, and the RELEASE.md staging row.
+- **`turbo.json`:** this PR carries the `MCP_COMPLETE_KEY_MODE` `globalEnv` hunk, on main's instruction. Main reviews it on the PR.
+
+## Consultation Feedback
+
+### Specify (Round 1)
+
+#### Codex (REQUEST_CHANGES)
+- **Concern**: open-tier decision unresolved → **Addressed**: the spec proceeds on (a) "close", with (b) still specified. The owner approved (a) at the spec gate.
+- **Concern**: `key_id` missing in apps/api test 4 → **Addressed**: both fields are always present. A `valid:true` that lacks one is malformed (503).
+- **Concern**: service-user lookup order → **Addressed**: the lookup runs only after the plugin accepts the key.
+- **Concern**: the "no prefix in any column" rule conflicted with `apikey.prefix` → **Addressed**: the rule now covers the random part only, and the prefix is exempt.
+- **Concern**: byte and key bounds, and the `client_id` alert contract → **Addressed**: 1 KiB body, 1–256 printable ASCII key, `client-id-invalid` alert.
+
+#### Gemini (COMMENT)
+- **Concern**: `list` does not print `client_id` → **Addressed**.
+- **Concern**: semantics of the client-mismatch warning → **Addressed**: the header is parsed alone, one warning, ids only.
+- **Concern**: error envelope → **Addressed**: `{error:'Unauthorized'}` and `{error:'Authentication service unavailable'}`.
+- **Concern**: runtime type of `metadata` → **Addressed**: apps/auth test 15.
+- **Concern**: log-only latency on an apps/auth timeout → **Addressed**: noted in §3 as accepted for the transition week.
+
+### Plan (Round 1)
+
+#### Codex (REQUEST_CHANGES)
+- **Concern**: apps/auth has no `@ansari/types` dependency → **Addressed**: re-exported through `@ansari/auth`.
+- **Concern**: `packages/types` has no test runner → **Addressed**: tested in `packages/auth` and again in apps/api.
+- **Concern**: Phase 4 must stub `fetch`, not mock `verifyServiceKey` → **Addressed**.
+
+#### Gemini (APPROVE, with notes)
+- **Concern**: `service-keys.test.ts` `ansari-mcp` call sites need `--client-id` → **Addressed** in Phase 1.
+- **Concern**: the `cutover-docs.test.ts` section scans → **Addressed**: the MCP material sits under its own `##` heading with `###` subsections.
+- **Concern**: Sentry `client` tag parity on a valid key → **Addressed**.
+
+### Phase 1 (Round 1)
+No concerns raised. Codex and Gemini approved.
+
+### Phase 2 (Rounds 1–3)
+
+#### Codex
+- **Round 1, REQUEST_CHANGES**: an expired key's row is deleted, but scenario 2 said it is kept → **Addressed** by spec Amendment 1. This is a plugin fact. The test asserts the deletion, so a plugin change in either direction fails loudly.
+- **Round 2, REQUEST_CHANGES**: `key-window-volume` can fire every 60 s key window, up to 5× per alert window → **Addressed**: `keyWindowFloorMs` = `EXCHANGE_ALERT_WINDOW` for MCP, with a mutation-checked unit test.
+- **Round 3**: APPROVE.
+
+#### Gemini
+No concerns raised. Approved in all three rounds.
+
+### Phase 3 (Rounds 1–2)
+
+#### Codex
+- **Round 1, REQUEST_CHANGES**: `docs/self-hosting.md` said that an unreachable apps/auth gives 503 in both modes → **Addressed**: log-only serves and records `unverified`.
+- **Round 2**: APPROVE.
+
+#### Gemini
+- **Round 1, APPROVE with note**: the same docs sentence → **Addressed** by the same commit. Round 2: APPROVE.
+
+### Phase 4 (Round 1)
+- **Codex**: APPROVE, no concerns.
+- **Gemini**: APPROVE. Nit: a stale "does not require authentication" test → **Addressed**: replaced with "requires a key → 401".
+
+### Phase 5 (Rounds 1–2)
+
+#### Codex
+- **Round 1, REQUEST_CHANGES**: the runbook listed "a key without `Bearer `" as a cause of apps/auth's `unauthorized-volume` alert. It cannot be one, because apps/api classes such a value as `missing` and never calls verify → **Addressed**: the cause was removed and operators are pointed at the apps/api `missing` verdict.
+- **Round 2**: APPROVE.
+
+#### Gemini
+No concerns raised. Approved in both rounds.
+
+No `CONSULT_ERROR` occurred in any round.
+
+## Lessons Learned
+
+### What Went Well
+
+- **Reusing spec 329's machinery kept the surface small.** The plugin, the script, the alert pattern, the leak scans and the blocked `/api-key/*` paths were already there. This spec added one route and one consumer.
+- **Two-sided pins on the refusal shape.** apps/auth asserts a byte-identical `{"valid":false}`. apps/api accepts only that shape and treats anything else as 503. Neither side can drift silently.
+- **Mutation checks on every guard.** Each was removed in turn and failed tests: client-id rule, owner bind, relation check, permission check, missing-user 500, alert order, enforce, logging the token.
+- **Testing through the real client.** apps/api tests stub `fetch` at the apps/auth boundary rather than mocking `verifyServiceKey`, so the timeout, the malformed-body and the shape checks run in every route test.
+
+### Challenges Encountered
+
+- **Plugin behaviour differs from its docs and from the spec's assumption.** An expired key is deleted when presented, and there is no routed `/api-key/verify` endpoint in 1.7.7, 1.7.20 or 1.8.0-beta.7: the docs' path comes from a JSDoc comment only. Both were settled by reading the published package. The first needed a spec amendment.
+- **Alert ordering.** Counting `keyVerified` before the owner and client-id checks let a refused key inflate the volume alerts. The security architect caught it after the phase consults had approved it.
+- **The doc path scan.** The `namedRepoPaths` regex in `cutover-docs.test.ts` has no end anchor, so `apps/mcp/wrangler.jsonc` reads as `apps/mcp/wrangler.json`, which does not exist. The doc was reworded rather than the scan changed (follow-up below).
+- **Flakes under full parallel load.** Two pre-existing apps/auth-in-process tests failed once each, in the #330 lineage (see Flaky Tests).
+
+### What Would Be Done Differently
+
+- Grep a route's real callers before a plan names the suites a change touches. Four of the seven named suites never called the route.
+- Put every "count this as success" side effect after the last check in a verify path from the start, and pin the order with a test.
+
+### Methodology Improvements
+
+- A plan that names existing test files to change should list how each one calls the code under change (route vs helper), so the count is checked at plan review.
+- Doc-scan regexes in `cutover-docs.test.ts` should be negative-tested against near-miss paths (`.jsonc` vs `.json`) like any other verification pattern.
+
+## Architecture Updates
+
+- Routed: hot — `arch-critical.md` JWT fact — amended in place (Phase 5): apps/api accepts only apps/auth's JWT **except** `/v2/mcp-complete`, which takes an `ansari-mcp` service key verified on every request at `/api/service/verify-key` (401 refused, 503 outage). The map's Authentication line now names "service keys (WhatsApp exchange, MCP verify)". No fact was added, so no demotion was needed.
+- Routed: cold — `arch.md` Authentication & Authorization — new verify-route paragraph (Phase 5): the closed permission set, owner and client-id binding, refusal shape, no CORS, no per-IP rule, `MCP_COMPLETE_KEY_MODE`.
+
+## Lessons Learned Updates
+
+- Routed: cold — `lessons-learned.md` "Service API keys and the WhatsApp exchange (spec 329)" section, extended with spec 314 bullets:
+  - an expired service key leaves no row behind, because the plugin deletes it on presentation, so never put an expiry on a key whose audit trail matters;
+  - `verifyApiKey` has no HTTP route in any published version checked; read the published package, not the docs, and re-run the upgrade guard on any bump;
+  - count a success only after the last check in a verify path;
+  - pin a remote verdict's refusal shape on both sides.
+- Routed: hot — `lessons-critical.md` map line for spec 329 extended to "+ MCP key verify (spec 314)", with a consult trigger for gating a route on a remote verify. No lesson was added: the hot file is at its cap, and none of these is cross-cutting enough to displace an entry.
+
+## Flaky Tests
+
+Neither test was skipped. Both are pre-existing, outside this change, and passed in isolation and on a full rerun. The security architect owns this class (#330 lineage) and ordered that it not be chased here.
+
+- `apps/api/tests/auth/require-user.test.ts`: all 13 tests failed once in Phase 3 with `sign-up failed: 404` from the in-process apps/auth (`signUpTokens`, `apps/auth/tests/helpers/service.ts:166`). The run was a full `npm test -- --exclude='**/e2e/**'`: 4 packages in parallel, 4 workers each. The file passed 18/18 alone and on a full rerun.
+- `apps/auth/tests/whatsapp-session.test.ts` > "auth.apikey dropped under the running service → 500 …": got 404 where it expected 401, once, in Phase 4 under the same full parallel run. It passed 3/3 alone and on a full rerun.
+
+## Follow-up Items
+
+- **Remove log-only:** open the issue at enforce (rollout step 6). It removes `MCP_COMPLETE_KEY_MODE` from `config.ts` and the `turbo.json` `globalEnv` hunk one week after enforcement. The issue number is to be recorded when it exists.
+- **Limit sizing:** `MCP_KEY_INITIAL` (120/60 s, 5,000/day) and the alert thresholds are judgement values. The owner should resize them with `update-limits` (no deploy) once the `threads.client` query numbers are in.
+- **Owner steps outside the repository:** listed under Spec Compliance. The published snippet and MCP setup page locations are pending from the owner.
+- **`@better-auth/api-key` upgrade to 1.7.20:** out of scope. On any bump, re-run the upgrade guard in `apps/auth/tests/blocked-paths.test.ts` and the runbook's plugin-upgrade check.
+- **`cutover-docs.test.ts` `namedRepoPaths`:** add an end boundary after the extension so `.jsonc` is not read as `.json`. This is main's test infrastructure.
+- **Flaky in-process apps/auth tests under parallel load:** security owns them (#330 lineage).
diff --git a/codev/state/spir-314_thread.md b/codev/state/spir-314_thread.md
index 845adcc5..b54eed93 100644
--- a/codev/state/spir-314_thread.md
+++ b/codev/state/spir-314_thread.md
@@ -69,3 +69,7 @@
 - Runbook: new `## The \`ansari-mcp\` key (#314)` with `###` subsections (issuance per deployment incl. mcp-staging `--client-id ansari-mcp-staging` before staging deploys #314, Bearer handoff for Worker/Railway/owner, rollout, limits, alerts incl. `client-id-invalid`, rotation, plugin-upgrade check). Kept `###` so `cutover-docs.test.ts`'s `section('Limits')`/`section('Alerts')` still read only the WhatsApp tables.
 - Surprise: the runbook path scan's regex reads `apps/mcp/wrangler.jsonc` as `apps/mcp/wrangler.json` (no end anchor after the extension), which does not exist. Reworded to "apps/mcp's `wrangler.jsonc`" rather than touch the scan.
 - self-hosting.md: new MCP key subsection; "ansari-mcp reserved" wording fixed there and in arch.md and the runbook intro. apps/mcp README + .env.example + RELEASE.md staging table: `Bearer ansari_mcp_<64 letters>`. arch-critical JWT fact amended in place; arch.md gains the verify-route paragraph.
+
+## 2026-11-11 review
+- Review written (`codev/reviews/314-protect-v2-mcp-complete-with-b.md`). Spec 314 lessons appended to the spec 329 section of lessons-learned.md (expired key leaves no row; read the published package; count success after the last check; two-sided refusal pin). Hot map line extended; no hot lesson added (at cap).
+- Open owner items carried into the PR: keys per deployment (staging key before apps/api staging deploys, since default is enforce), the snippet and setup page locations, the threads.client numbers for limit sizing, and the log-only removal issue (opened at enforce).

From ba0f9dcd235e1aa9ca84193c5ebf3221315f15ee Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:27:48 +1100
Subject: [PATCH 149/435] chore(porch): 314 record PR #372

---
 .../314-protect-v2-mcp-complete-with-b/status.yaml         | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 561f218a..ae174484 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -84,7 +84,7 @@ history:
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:25:26.571Z'
+updated_at: '2026-11-11T04:27:48.853Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'
@@ -107,3 +107,8 @@ context_refreshes:
   - boundary: enter:review
     at: '2026-11-11T04:24:44.938Z'
     acknowledged_at: '2026-11-11T04:25:26.571Z'
+pr_history:
+  - phase: review
+    pr_number: 372
+    branch: builder/spir-314
+    created_at: '2026-11-11T04:27:48.853Z'

From bc456fd5c8430b678c48b7b4dffd15770b01d430 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:27:53 +1100
Subject: [PATCH 150/435] chore(porch): 314 review build-complete

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index ae174484..9513d225 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -33,7 +33,7 @@ gates:
   verify-approval:
     status: pending
 iteration: 1
-build_complete: false
+build_complete: true
 history:
   - iteration: 1
     plan_phase: phase_2
@@ -84,7 +84,7 @@ history:
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:27:48.853Z'
+updated_at: '2026-11-11T04:27:53.416Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'

From 430aa53417b254cea76726a6543bc117d5245948 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:33:02 +1100
Subject: [PATCH 151/435] [Spec 314][Phase: review] fix: refuse a bearer
 outside apps/auth's key envelope as missing (401), not an outage (codex)

---
 apps/api/lib/auth-service/client.ts                | 14 ++++++++++++++
 apps/api/src/app/api/v2/mcp-complete/route.ts      | 14 ++++++++++----
 apps/api/tests/mcp-complete-key.test.ts            | 11 +++++++++++
 .../reviews/314-protect-v2-mcp-complete-with-b.md  | 12 ++++++++++++
 4 files changed, 47 insertions(+), 4 deletions(-)

diff --git a/apps/api/lib/auth-service/client.ts b/apps/api/lib/auth-service/client.ts
index a34c96b6..7c7430fe 100644
--- a/apps/api/lib/auth-service/client.ts
+++ b/apps/api/lib/auth-service/client.ts
@@ -138,6 +138,20 @@ export async function deleteAuthUser(sub: string, jwt: string): Promise {
  */
 export const SERVICE_VERIFY_PATH = '/api/service/verify-key';
 
+/**
+ * The longest service key apps/auth's verify route reads (apps/auth
+ * `VERIFY_KEY_MAX_LENGTH`). apps/auth answers 400 to a key outside
+ * `[\x21-\x7E]{1,256}`, and a 400 here is an outage (503), so a token outside
+ * that envelope must be refused before the call. The two bounds change together.
+ */
+export const SERVICE_KEY_MAX_LENGTH = 256;
+const SERVICE_KEY_SHAPE = new RegExp(`^[\\x21-\\x7E]{1,${SERVICE_KEY_MAX_LENGTH}}$`);
+
+/** Whether `token` is inside the envelope apps/auth's verify route accepts (printable ASCII, 1–256 characters). */
+export function isServiceKeyShape(token: string): boolean {
+  return SERVICE_KEY_SHAPE.test(token);
+}
+
 const verifyServiceKeySchema = z.union([
   z.object({
     valid: z.literal(true),
diff --git a/apps/api/src/app/api/v2/mcp-complete/route.ts b/apps/api/src/app/api/v2/mcp-complete/route.ts
index 34c6e15a..5f5d3afb 100644
--- a/apps/api/src/app/api/v2/mcp-complete/route.ts
+++ b/apps/api/src/app/api/v2/mcp-complete/route.ts
@@ -14,7 +14,7 @@ import { createThread, createMessage, persistOrphanToolCalls } from '@/lib/db/th
 import { CLIENT_HEADER, getClientId } from '@/lib/attribution';
 import { checkRateLimit, getClientIp } from '@/lib/rate-limit';
 import { config } from '@/lib/config';
-import { AuthServiceUnavailableError, verifyServiceKey } from '@/lib/auth-service/client';
+import { AuthServiceUnavailableError, isServiceKeyShape, verifyServiceKey } from '@/lib/auth-service/client';
 import { parseClientId } from '@ansari/types/attribution';
 
 const CONCISE_INSTRUCTION =
@@ -76,12 +76,18 @@ function applyRateLimit(request: NextRequest): NextResponse | null {
  */
 type McpKeyVerdict = 'valid' | 'missing' | 'refused' | 'unverified';
 
-/** The bearer token, or null when the header is absent or malformed (case-insensitive scheme, one token, no whitespace). */
+/**
+ * The bearer token, or null when the header is absent or malformed
+ * (case-insensitive scheme, one token, no whitespace) or the token is outside
+ * the envelope apps/auth's verify route reads (printable ASCII, 1–256
+ * characters). Such a token can never be a key; sent on, apps/auth would answer
+ * 400 and the request would get a 503 instead of the 401 it deserves.
+ */
 function bearerOf(request: NextRequest): string | null {
   const header = request.headers.get('authorization');
   if (header === null) return null;
-  const match = /^Bearer ([^\s]+)$/i.exec(header);
-  return match?.[1] ?? null;
+  const token = /^Bearer ([^\s]+)$/i.exec(header)?.[1];
+  return token !== undefined && isServiceKeyShape(token) ? token : null;
 }
 
 /**
diff --git a/apps/api/tests/mcp-complete-key.test.ts b/apps/api/tests/mcp-complete-key.test.ts
index 3d603e6b..f850f1bc 100644
--- a/apps/api/tests/mcp-complete-key.test.ts
+++ b/apps/api/tests/mcp-complete-key.test.ts
@@ -317,6 +317,9 @@ describe.each(['POST', 'GET'] as const)('%s, enforce mode', (method) => {
     ['the bare scheme', 'Bearer'],
     ['a token containing whitespace', `Bearer ${KEY} extra`],
     ['the key with no scheme', KEY],
+    ['a token longer than 256 characters', `Bearer ${'a'.repeat(257)}`],
+    ['a token with a non-ASCII character', `Bearer ansari_mcp_\u00e9${'a'.repeat(10)}`],
+    ['a token with DEL (0x7F)', `Bearer ansari_mcp_\x7f${'a'.repeat(10)}`],
   ])('scenario 2: %s → 401, no fetch', async (_label, authorization) => {
     const res = await call(method, { authorization });
     expect(res.status).toBe(401);
@@ -326,6 +329,14 @@ describe.each(['POST', 'GET'] as const)('%s, enforce mode', (method) => {
     expect(verdictsRecorded()).toEqual(['missing']);
   });
 
+  it('a 256-character printable token is at the bound: it is sent to apps/auth', async () => {
+    authAnswers(200, { valid: false });
+    const res = await call(method, { authorization: `Bearer ${'a'.repeat(256)}` });
+    expect(res.status).toBe(401);
+    expect(fetchMock).toHaveBeenCalledTimes(1);
+    expect(verdictsRecorded()).toEqual(['refused']);
+  });
+
   it('scenarios 3 and 13: { valid: false } (unknown, revoked, WhatsApp, …) → the same 401, no thread, no facilitator call', async () => {
     authAnswers(200, { valid: false });
     const res = await call(method);
diff --git a/codev/reviews/314-protect-v2-mcp-complete-with-b.md b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
index debea288..98ddc4e8 100644
--- a/codev/reviews/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
@@ -44,6 +44,7 @@
   - Scenario 11 (mode parsing, boot refusal) is covered by Phase 3's config and boot-check tests. Scenario 13 is covered at the seam.
   - Security architect order (04:10Z): `alerts.keyVerified()` moved after the owner and client-id checks in `service-verify.ts`, so only a served key counts toward the volume alerts. A test pins the order and fails under the old one. The WhatsApp exchange order is unchanged.
 - **Phase 5:** rebased onto develop (#365, #368, #370) first. #366 had changed the attribution link to `askansari.ai`, so scenario 4's expectation followed it in its own commit. Architect orders added the `mcp-staging` key, the `Bearer` form in all three apps/mcp docs, and the RELEASE.md staging row.
+- **Review (PR consult):** the route checks the bearer token's shape (printable ASCII, 1–256 characters, apps/auth's bound) before calling apps/auth. The plan's bearer rule (one token, no whitespace) let an over-long or non-ASCII token through, and apps/auth's 400 turned it into a 503.
 - **`turbo.json`:** this PR carries the `MCP_COMPLETE_KEY_MODE` `globalEnv` hunk, on main's instruction. Main reviews it on the PR.
 
 ## Consultation Feedback
@@ -111,6 +112,15 @@ No concerns raised. Approved in all three rounds.
 #### Gemini
 No concerns raised. Approved in both rounds.
 
+### Review / PR #372 (Round 1)
+
+#### Codex (REQUEST_CHANGES)
+- **Concern**: a bearer token over 256 characters, or containing non-ASCII, was sent to apps/auth. apps/auth answered 400, which apps/api reported as a 503 outage instead of a 401 → **Addressed**: apps/api now refuses a token outside apps/auth's `[\x21-\x7E]{1,256}` envelope locally, as `missing` (401, no call). POST and GET tests cover it, including the 256-character bound, and a mutation check confirms the tests catch the old behaviour.
+- **Concern**: the phase consultation outputs were untracked → **Addressed**: committed, as other projects do.
+
+#### Gemini
+No concerns raised. Approved.
+
 No `CONSULT_ERROR` occurred in any round.
 
 ## Lessons Learned
@@ -131,6 +141,8 @@ No `CONSULT_ERROR` occurred in any round.
 
 ### What Would Be Done Differently
 
+- When one service validates an input that another forwards, give the caller the same bound. Otherwise the callee's 400 surfaces as the caller's outage. The apps/auth key bound was specified, but nobody mirrored it in apps/api until the PR consult.
+
 - Grep a route's real callers before a plan names the suites a change touches. Four of the seven named suites never called the route.
 - Put every "count this as success" side effect after the last check in a verify path from the start, and pin the order with a test.
 

From 53bde5e943568de14df24b19eb0844b633a500d3 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:33:02 +1100
Subject: [PATCH 152/435] [Spec 314] Consultation outputs and rebuttals, phases
 1-5 and PR review

---
 .../314-phase_1-iter1-codex.txt               |  7 +++
 .../314-phase_1-iter1-gemini.txt              | 28 +++++++++
 .../314-phase_2-iter1-codex.txt               |  7 +++
 .../314-phase_2-iter1-gemini.txt              | 26 ++++++++
 .../314-phase_2-iter1-rebuttals.md            | 24 ++++++++
 .../314-phase_2-iter2-codex.txt               |  7 +++
 .../314-phase_2-iter2-context.md              | 38 ++++++++++++
 .../314-phase_2-iter2-gemini.txt              | 15 +++++
 .../314-phase_2-iter2-rebuttals.md            | 15 +++++
 .../314-phase_2-iter3-codex.txt               |  7 +++
 .../314-phase_2-iter3-context.md              | 60 +++++++++++++++++++
 .../314-phase_2-iter3-gemini.txt              | 19 ++++++
 .../314-phase_3-iter1-codex.txt               |  7 +++
 .../314-phase_3-iter1-gemini.txt              | 39 ++++++++++++
 .../314-phase_3-iter1-rebuttals.md            | 23 +++++++
 .../314-phase_3-iter2-codex.txt               |  7 +++
 .../314-phase_3-iter2-context.md              | 37 ++++++++++++
 .../314-phase_3-iter2-gemini.txt              | 16 +++++
 .../314-phase_4-iter1-codex.txt               | 18 ++++++
 .../314-phase_4-iter1-gemini.txt              | 37 ++++++++++++
 .../314-phase_5-iter1-codex.txt               |  7 +++
 .../314-phase_5-iter1-gemini.txt              | 26 ++++++++
 .../314-phase_5-iter1-rebuttals.md            |  4 ++
 .../314-phase_5-iter2-codex.txt               |  7 +++
 .../314-phase_5-iter2-context.md              | 18 ++++++
 .../314-phase_5-iter2-gemini.txt              | 17 ++++++
 .../314-review-iter1-codex.txt                | 21 +++++++
 .../314-review-iter1-gemini.txt               | 46 ++++++++++++++
 .../314-review-iter1-rebuttals.md             | 14 +++++
 29 files changed, 597 insertions(+)
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_1-iter1-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_1-iter1-gemini.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-gemini.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-rebuttals.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-context.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-gemini.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-rebuttals.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-context.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-gemini.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-gemini.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-rebuttals.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-context.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-gemini.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_4-iter1-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_4-iter1-gemini.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-rebuttals.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-context.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-gemini.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-gemini.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-rebuttals.md

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_1-iter1-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_1-iter1-codex.txt
new file mode 100644
index 00000000..08395741
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_1-iter1-codex.txt
@@ -0,0 +1,7 @@
+---
+VERDICT: APPROVE
+SUMMARY: Phase 1 fully implements the planned MCP key rules, script constraints, metadata handling, and tests.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_1-iter1-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_1-iter1-gemini.txt
new file mode 100644
index 00000000..5d77d4f5
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_1-iter1-gemini.txt
@@ -0,0 +1,28 @@
+### Phase 1 Implementation Review
+
+The Phase 1 implementation is clean, well-structured, and matches all deliverables and acceptance criteria in the specification and plan.
+
+#### Verification Summary
+
+1. **Spec Adherence & Plan Alignment (`phase_1`)**:
+   - **Client ID Rule**: [`MCP_CLIENT_ID_PATTERN`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/types/src/attribution.ts#L45) and [`isMcpClientId`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/types/src/attribution.ts#L48-L55) in `packages/types/src/attribution.ts` enforce `^ansari-mcp(-[a-z0-9._-]+)?$`, length $\le 64$, and subset alignment with `CLIENT_ID_PATTERN`. Both are re-exported from [`packages/auth/src/index.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/auth/src/index.ts#L61) without altering `apps/auth/package.json`.
+   - **Limits & Thresholds**: [`packages/auth/src/limits.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/auth/src/limits.ts#L262-L303) defines `MCP_KEY_INITIAL` (120 / 60s, 5,000 / day), a standalone `MCP_KEY_BOUNDS`, one-third alert thresholds (`MCP_VERIFY_KEY_ALERT = 40`, `MCP_VERIFY_DAILY_ALERT = 1666`), `MCP_VERIFY_UNAUTHORIZED_ALERT` (20 per `EXCHANGE_ALERT_WINDOW`), `VERIFY_BODY_LIMIT` (1024), and `VERIFY_KEY_MAX_LENGTH` (256).
+   - **Service Users & Metadata**: [`packages/auth/src/service-users.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/auth/src/service-users.ts#L28-L31) binds `SERVICES['ansari-mcp'].bounds` to `MCP_KEY_BOUNDS`, selects `metadata` in [`listServiceKeys`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/auth/src/service-users.ts#L115-L138), and provides [`clientIdOf`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/auth/src/service-users.ts#L147-L159) supporting both JSON text (1.7.7) and parsed object (1.7.20) representations while safely returning `null` on malformed input.
+   - **Operator Script**: [`apps/auth/scripts/service-keys.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/scripts/service-keys.ts#L180-L186) enforces `--client-id` via `clientIdFor` in both `parseArgs` and `runServiceKeys` / `createKey`, never echoes rejected input values, preserves `whatsapp` default fallback behavior, and prints `client_id` in `list` output ([`keyLines`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/scripts/service-keys.ts#L289-L301)).
+
+2. **Code Quality & Error Handling**:
+   - Defense-in-depth checks in `parseArgs`, `runServiceKeys`, and `createKey` ensure direct programmatic calls to `runServiceKeys` cannot bypass `clientIdFor`.
+   - `MCP_CLIENT_ID_RULE` uses fixed refusal wording so invalid `--client-id` values (such as accidentally pasted secrets) are never echoed.
+
+3. **Test Coverage**:
+   - [`packages/auth/tests/unit/helpers.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/auth/tests/unit/helpers.test.ts#L155-L209) thoroughly covers `isMcpClientId` (valid cases, near misses, 64/65 char boundaries, non-strings) and `clientIdOf` (string JSON, object, malformed JSON, primitives, arrays, non-string `clientId`).
+   - [`apps/auth/tests/limits.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/limits.test.ts#L488-L523) verifies limit relationships, distinct object identity for `MCP_KEY_BOUNDS`, and body byte limits.
+   - [`apps/auth/tests/service-keys.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/service-keys.test.ts#L563-L643) covers `create-key`, `rotate`, and `list` for `ansari-mcp` against pglite, including non-echoing refusal assertions and `whatsapp` backwards compatibility.
+
+---
+VERDICT: APPROVE
+SUMMARY: Phase 1 cleanly implements the ansari-mcp limits, client-id rules, metadata extraction, and script constraints with thorough test coverage.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-codex.txt
new file mode 100644
index 00000000..73f293e8
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-codex.txt
@@ -0,0 +1,7 @@
+---
+VERDICT: REQUEST_CHANGES
+SUMMARY: Phase 2 is well implemented, but one approved acceptance criterion is explicitly weakened.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- `service-verify.test.ts` permits an expired key row to be deleted (`kept: false`), while spec scenario 2 requires every refusal row to remain. Since Better Auth deletes expired keys, reconcile this through an approved spec/plan amendment or preserve the row; do not claim scenarios 1–15 pass unchanged.
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-gemini.txt
new file mode 100644
index 00000000..19023ff1
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-gemini.txt
@@ -0,0 +1,26 @@
+### Phase 2 Review: `apps/auth` verify route `POST /api/service/verify-key`
+
+The Phase 2 implementation fulfills all specification and plan requirements cleanly:
+
+1. **Spec Adherence & Route Behavior**:
+   - [`serviceVerifyRouter`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/service-verify.ts#L79-L151) enforces the exact pipeline order specified: `requireJson` → `express.json({ limit: limits.VERIFY_BODY_LIMIT })` → `parseFailure` → body & closed permission-set validation (`{ mcp: ['complete'] }` via [`isServedPermissionSet`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/service-verify.ts#L53-L64)) → `auth.api.verifyApiKey` → [`createApiKeyRelationCheck`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/apikey-relation.ts#L11-L18) on refusal → service-user lookup & ownership check (`findServiceUser`) only after plugin acceptance → `client_id` validation (`clientIdOf` + `isMcpClientId`).
+   - Mounted at [`SERVICE_VERIFY_PATH`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/app.ts#L75) (`/api/service/verify-key`) ahead of `corsFor` and outside Better Auth's router, terminating all non-POST methods and sub-paths with a bare 404 so no response carries `Access-Control-*` headers.
+   - All refusals return the byte-identical `{"valid":false}` with status 200; malformed requests or disallowed permissions return 400 `{"message":"Invalid request"}` without touching the plugin; database/relation outages and unresolvable/duplicate service users return 500 `{"message":"Internal error"}`.
+
+2. **Code Quality & Alert Generalization**:
+   - [`createApiKeyRelationCheck`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/apikey-relation.ts#L11-L18) is cleanly extracted and shared between [`whatsappRouter`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/whatsapp.ts#L95) and [`serviceVerifyRouter`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/service-verify.ts#L81).
+   - [`createKeyAlerts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/alerts.ts#L213-L275) generalizes the per-key and fixed-window alert deduplication while keeping `ExchangeAlert` immediately above `KeyRefusalCode` to preserve the source-scan contract in `cutover-docs.test.ts`.
+   - Error logging uses `redactError` (`{name, code}`), and no key material or request body is logged or sent to Sentry.
+
+3. **Test Coverage**:
+   - [`service-verify.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/service-verify.test.ts#L1-L620) thoroughly covers spec scenarios 1–10, 12, 13, and 15 against PGlite and the real `api-key` plugin, including negative controls for [`leakedWindows`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/helpers/leak-scan.ts#L20-L25) and non-vacuity checks on the `verifyApiKey` spy.
+   - [`service-verify-sentry.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/service-verify-sentry.test.ts#L1-L102) verifies that captured Sentry envelopes and console logs under `SERVICE_SENTRY_OPTIONS` contain no key material, 16-char random windows, or request bodies.
+   - [`blocked-paths.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/blocked-paths.test.ts#L145-L163) adds the requested plugin-upgrade guard pinning `verifyApiKey` as server-only and verifying `/api/auth/api-key/verify` variants are blocked.
+
+---
+VERDICT: APPROVE
+SUMMARY: Phase 2 cleanly implements the `/api/service/verify-key` route, shared relation check, generalized alerts, and comprehensive PGlite/Sentry/upgrade-guard tests in full alignment with the spec and plan.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-rebuttals.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-rebuttals.md
new file mode 100644
index 00000000..d35ad532
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-rebuttals.md
@@ -0,0 +1,24 @@
+# Phase 2, iteration 1: rebuttals
+
+## Codex (REQUEST_CHANGES)
+
+**Point: an expired key's row is deleted (`kept: false`), while spec scenario 2 says each refused row is kept.**
+
+Agreed on the fact, and the test states it rather than hiding it. What I did not do is weaken the route: the deletion is the api-key plugin's own behaviour, not something the route chooses.
+
+- `@better-auth/api-key` 1.7.7 `validateApiKey` deletes a key whose `expiresAt` has passed, before throwing `KEY_EXPIRED` (`dist/index.mjs` L1635–1661). The only setting that changes this is `deferUpdates`, which still deletes, just in the background. Keeping the row would mean patching the plugin or swapping its storage, and neither is in scope.
+- The answer is unaffected: an expired key still gets the byte-identical `{"valid":false}`, which is what apps/api relies on.
+- In practice no `ansari-mcp` key expires. The script refuses any `--expir*` flag (spec 329), and keys are made only by the script. An expired key can exist only if someone edits the row by hand.
+- The row-kept rows that matter operationally are kept and tested: disabled, exhausted (and served again after its daily refill, per the success criterion "an exhausted key is refused until its daily refill, and the row is kept"), and rate-limited.
+
+**What changed:** nothing in code. The test pins the plugin's actual behaviour (`kept: false` for expired, with a comment saying why), so a plugin change that stopped deleting would show up there too.
+
+**Spec wording:** scenario 2's "with each row kept" is wrong for the expired case. Amending an approved spec is the architect's decision, so I have asked the security architect to approve a one-line correction: "with each row kept, except an expired key, which the plugin deletes when it is presented". The review will record this either way. Phase 2 does not claim scenario 2 passes word for word: it passes for every case except that one.
+
+## Gemini (APPROVE)
+
+No issues raised.
+
+## Resolution (2026-11-11, security architect)
+
+The security architect approved the amendment as a plugin fact needing no owner gate. Spec scenario 2 now reads "with each row kept, except an expired key, which the plugin deletes when it is presented (validateApiKey, @better-auth/api-key 1.7.7; pinned by test)", with a dated "Amendment 1" note under the spec's title and in its References. The test now asserts that the expired key's row is gone and every other refused row is kept, so a plugin change either way fails loudly.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-codex.txt
new file mode 100644
index 00000000..b65d4909
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-codex.txt
@@ -0,0 +1,7 @@
+---
+VERDICT: REQUEST_CHANGES
+SUMMARY: Phase 2 is solid, but MCP window-volume alert deduplication does not match the approved alert window.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- `createKeyAlerts` deduplicates `key-window-volume` for the key’s 60-second rate-limit window, allowing up to five alerts during the 5-minute `EXCHANGE_ALERT_WINDOW`. The spec requires each MCP alert kind to fire at most once per `EXCHANGE_ALERT_WINDOW`. Add MCP-specific deduplication and a test crossing multiple 60-second key windows within one alert window.
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-context.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-context.md
new file mode 100644
index 00000000..850e992a
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-context.md
@@ -0,0 +1,38 @@
+### Iteration 1 Reviews
+- codex: REQUEST_CHANGES — Phase 2 is well implemented, but one approved acceptance criterion is explicitly weakened.
+- gemini: APPROVE — Phase 2 cleanly implements the `/api/service/verify-key` route, shared relation check, generalized alerts, and comprehensive PGlite/Sentry/upgrade-guard tests in full alignment with the spec and plan.
+
+### Builder Response to Iteration 1
+# Phase 2, iteration 1: rebuttals
+
+## Codex (REQUEST_CHANGES)
+
+**Point: an expired key's row is deleted (`kept: false`), while spec scenario 2 says each refused row is kept.**
+
+Agreed on the fact, and the test states it rather than hiding it. What I did not do is weaken the route: the deletion is the api-key plugin's own behaviour, not something the route chooses.
+
+- `@better-auth/api-key` 1.7.7 `validateApiKey` deletes a key whose `expiresAt` has passed, before throwing `KEY_EXPIRED` (`dist/index.mjs` L1635–1661). The only setting that changes this is `deferUpdates`, which still deletes, just in the background. Keeping the row would mean patching the plugin or swapping its storage, and neither is in scope.
+- The answer is unaffected: an expired key still gets the byte-identical `{"valid":false}`, which is what apps/api relies on.
+- In practice no `ansari-mcp` key expires. The script refuses any `--expir*` flag (spec 329), and keys are made only by the script. An expired key can exist only if someone edits the row by hand.
+- The row-kept rows that matter operationally are kept and tested: disabled, exhausted (and served again after its daily refill, per the success criterion "an exhausted key is refused until its daily refill, and the row is kept"), and rate-limited.
+
+**What changed:** nothing in code. The test pins the plugin's actual behaviour (`kept: false` for expired, with a comment saying why), so a plugin change that stopped deleting would show up there too.
+
+**Spec wording:** scenario 2's "with each row kept" is wrong for the expired case. Amending an approved spec is the architect's decision, so I have asked the security architect to approve a one-line correction: "with each row kept, except an expired key, which the plugin deletes when it is presented". The review will record this either way. Phase 2 does not claim scenario 2 passes word for word: it passes for every case except that one.
+
+## Gemini (APPROVE)
+
+No issues raised.
+
+## Resolution (2026-11-11, security architect)
+
+The security architect approved the amendment as a plugin fact needing no owner gate. Spec scenario 2 now reads "with each row kept, except an expired key, which the plugin deletes when it is presented (validateApiKey, @better-auth/api-key 1.7.7; pinned by test)", with a dated "Amendment 1" note under the spec's title and in its References. The test now asserts that the expired key's row is gone and every other refused row is kept, so a plugin change either way fails loudly.
+
+
+### IMPORTANT: Stateful Review Context
+This is NOT the first review iteration. Previous reviewers raised concerns and the builder has responded.
+Before re-raising a previous concern:
+1. Check if the builder has already addressed it in code
+2. If the builder disputes a concern with evidence, verify the claim against actual project files before insisting
+3. Do not re-raise concerns that have been explained as false positives with valid justification
+4. Check package.json and config files for version numbers before flagging missing configuration
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-gemini.txt
new file mode 100644
index 00000000..054f859f
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-gemini.txt
@@ -0,0 +1,15 @@
+## Phase 2 Review (Iteration 2)
+
+The Iteration 1 concern regarding the expired-key row has been cleanly resolved:
+- [codev/specs/314-protect-v2-mcp-complete-with-b.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/specs/314-protect-v2-mcp-complete-with-b.md#L3) now includes the security-architect-approved Amendment 1 and updates Scenario 2 ([line 339](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/specs/314-protect-v2-mcp-complete-with-b.md#L339)) to reflect `@better-auth/api-key` 1.7.7's `validateApiKey` behavior of deleting expired keys upon presentation.
+- [apps/auth/tests/service-verify.test.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/service-verify.test.ts#L244-L248) explicitly asserts both sides (`toBeDefined()` for kept rows and `toBeUndefined()` for the expired key), ensuring any future plugin behavior change is caught immediately.
+
+All Phase 2 deliverables—the `POST /api/service/verify-key` router ([service-verify.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/service-verify.ts)), shared relation check ([apikey-relation.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/apikey-relation.ts)), generalized alert factory ([alerts.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/alerts.ts)), mount order ahead of `corsFor` ([app.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/app.ts)), and comprehensive PGlite/Sentry/upgrade-guard test suites—are complete and ready to proceed to Phase 3.
+
+---
+VERDICT: APPROVE
+SUMMARY: Phase 2 implementation and spec Amendment 1 for the expired-key plugin behavior are complete, well-tested, and ready for Phase 3.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-rebuttals.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-rebuttals.md
new file mode 100644
index 00000000..5086d9f8
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-rebuttals.md
@@ -0,0 +1,15 @@
+# Phase 2, iteration 2: rebuttals
+
+## Codex (REQUEST_CHANGES)
+
+**Point: `key-window-volume` repeats once per key rate-limit window (60 s), so it can fire up to five times in one 5-minute `EXCHANGE_ALERT_WINDOW`. The spec says each MCP kind fires at most once per alert window.**
+
+Accepted and fixed.
+
+- `createKeyAlerts` takes a `keyWindowFloorMs` option: the shortest gap between two window-volume alerts for one key is `max(key window, floor)`. The MCP alerts set it to `EXCHANGE_ALERT_WINDOW`. The WhatsApp exchange keeps 0, so spec 329's behaviour and its tests are unchanged (the whatsapp suites pass untouched).
+- New unit test (injected clock): a key over `MCP_VERIFY_KEY_ALERT` in every 60 s key window across one alert window raises exactly one alert, and the next alert window raises another. With the floor set to 0, that test fails (mutation-checked).
+- Kept as designed: the per-key kinds stay per key (they carry `keyId`), as in the exchange. During a rotation's overlap, two live keys can each raise their own alert, which is what the operator needs.
+
+## Gemini (APPROVE)
+
+No issues raised.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-codex.txt
new file mode 100644
index 00000000..eee6914d
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-codex.txt
@@ -0,0 +1,7 @@
+---
+VERDICT: APPROVE
+SUMMARY: Phase 2 fully matches the amended specification and plan, including corrected MCP alert deduplication and comprehensive tests.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-context.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-context.md
new file mode 100644
index 00000000..5c284579
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-context.md
@@ -0,0 +1,60 @@
+### Iteration 1 Reviews
+- codex: REQUEST_CHANGES — Phase 2 is well implemented, but one approved acceptance criterion is explicitly weakened.
+- gemini: APPROVE — Phase 2 cleanly implements the `/api/service/verify-key` route, shared relation check, generalized alerts, and comprehensive PGlite/Sentry/upgrade-guard tests in full alignment with the spec and plan.
+
+### Builder Response to Iteration 1
+# Phase 2, iteration 1: rebuttals
+
+## Codex (REQUEST_CHANGES)
+
+**Point: an expired key's row is deleted (`kept: false`), while spec scenario 2 says each refused row is kept.**
+
+Agreed on the fact, and the test states it rather than hiding it. What I did not do is weaken the route: the deletion is the api-key plugin's own behaviour, not something the route chooses.
+
+- `@better-auth/api-key` 1.7.7 `validateApiKey` deletes a key whose `expiresAt` has passed, before throwing `KEY_EXPIRED` (`dist/index.mjs` L1635–1661). The only setting that changes this is `deferUpdates`, which still deletes, just in the background. Keeping the row would mean patching the plugin or swapping its storage, and neither is in scope.
+- The answer is unaffected: an expired key still gets the byte-identical `{"valid":false}`, which is what apps/api relies on.
+- In practice no `ansari-mcp` key expires. The script refuses any `--expir*` flag (spec 329), and keys are made only by the script. An expired key can exist only if someone edits the row by hand.
+- The row-kept rows that matter operationally are kept and tested: disabled, exhausted (and served again after its daily refill, per the success criterion "an exhausted key is refused until its daily refill, and the row is kept"), and rate-limited.
+
+**What changed:** nothing in code. The test pins the plugin's actual behaviour (`kept: false` for expired, with a comment saying why), so a plugin change that stopped deleting would show up there too.
+
+**Spec wording:** scenario 2's "with each row kept" is wrong for the expired case. Amending an approved spec is the architect's decision, so I have asked the security architect to approve a one-line correction: "with each row kept, except an expired key, which the plugin deletes when it is presented". The review will record this either way. Phase 2 does not claim scenario 2 passes word for word: it passes for every case except that one.
+
+## Gemini (APPROVE)
+
+No issues raised.
+
+## Resolution (2026-11-11, security architect)
+
+The security architect approved the amendment as a plugin fact needing no owner gate. Spec scenario 2 now reads "with each row kept, except an expired key, which the plugin deletes when it is presented (validateApiKey, @better-auth/api-key 1.7.7; pinned by test)", with a dated "Amendment 1" note under the spec's title and in its References. The test now asserts that the expired key's row is gone and every other refused row is kept, so a plugin change either way fails loudly.
+
+
+### Iteration 2 Reviews
+- codex: REQUEST_CHANGES — Phase 2 is solid, but MCP window-volume alert deduplication does not match the approved alert window.
+- gemini: APPROVE — Phase 2 implementation and spec Amendment 1 for the expired-key plugin behavior are complete, well-tested, and ready for Phase 3.
+
+### Builder Response to Iteration 2
+# Phase 2, iteration 2: rebuttals
+
+## Codex (REQUEST_CHANGES)
+
+**Point: `key-window-volume` repeats once per key rate-limit window (60 s), so it can fire up to five times in one 5-minute `EXCHANGE_ALERT_WINDOW`. The spec says each MCP kind fires at most once per alert window.**
+
+Accepted and fixed.
+
+- `createKeyAlerts` takes a `keyWindowFloorMs` option: the shortest gap between two window-volume alerts for one key is `max(key window, floor)`. The MCP alerts set it to `EXCHANGE_ALERT_WINDOW`. The WhatsApp exchange keeps 0, so spec 329's behaviour and its tests are unchanged (the whatsapp suites pass untouched).
+- New unit test (injected clock): a key over `MCP_VERIFY_KEY_ALERT` in every 60 s key window across one alert window raises exactly one alert, and the next alert window raises another. With the floor set to 0, that test fails (mutation-checked).
+- Kept as designed: the per-key kinds stay per key (they carry `keyId`), as in the exchange. During a rotation's overlap, two live keys can each raise their own alert, which is what the operator needs.
+
+## Gemini (APPROVE)
+
+No issues raised.
+
+
+### IMPORTANT: Stateful Review Context
+This is NOT the first review iteration. Previous reviewers raised concerns and the builder has responded.
+Before re-raising a previous concern:
+1. Check if the builder has already addressed it in code
+2. If the builder disputes a concern with evidence, verify the claim against actual project files before insisting
+3. Do not re-raise concerns that have been explained as false positives with valid justification
+4. Check package.json and config files for version numbers before flagging missing configuration
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-gemini.txt
new file mode 100644
index 00000000..840b589a
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter3-gemini.txt
@@ -0,0 +1,19 @@
+Phase 2 implementation is complete and addresses the Iteration 2 feedback cleanly.
+
+### Assessment
+
+- **Spec Adherence & Iteration 2 Resolution**:
+  - [`createKeyAlerts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/alerts.ts#L220-L284) now accepts `keyWindowFloorMs` and sets `gapMs = Math.max(keyWindowMs, keyWindowFloorMs)`, with [`createMcpVerifyAlerts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/alerts.ts#L331-L351) configuring `keyWindowFloorMs: limits.EXCHANGE_ALERT_WINDOW * 1000` so `key-window-volume` fires at most once per `EXCHANGE_ALERT_WINDOW` per key while preserving WhatsApp exchange behavior (`keyWindowFloorMs = 0`).
+  - [`serviceVerifyRouter`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/service-verify.ts#L79-L151) enforces the closed `{ mcp: ['complete'] }` permission set, validates key bounds, runs [`createApiKeyRelationCheck`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/apikey-relation.ts#L11-L18) on plugin refusal, verifies `ansari-mcp` service-user ownership only after plugin acceptance, and validates `metadata.clientId` with `isMcpClientId`.
+  - [`createApp`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/app.ts#L67-L88) mounts `SERVICE_VERIFY_PATH` ahead of `corsFor`.
+- **Test Coverage**:
+  - [service-verify.test.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/service-verify.test.ts) covers all Phase 2 scenarios against PGlite, including the new unit test for `key-window-volume` deduplication across multiple 60 s key windows within a single `EXCHANGE_ALERT_WINDOW` ([L634-L659](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/service-verify.test.ts#L634-L659)).
+  - [service-verify-sentry.test.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/service-verify-sentry.test.ts) and [blocked-paths.test.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/blocked-paths.test.ts) cover key-leak scrubbing and the plugin-upgrade guard.
+
+---
+VERDICT: APPROVE
+SUMMARY: Phase 2 implementation and MCP window-volume alert deduplication match the spec and plan with full test coverage.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-codex.txt
new file mode 100644
index 00000000..92f196b9
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-codex.txt
@@ -0,0 +1,7 @@
+---
+VERDICT: REQUEST_CHANGES
+SUMMARY: Phase 3 implementation is sound, but its rollout-mode documentation contradicts the specification.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- `docs/self-hosting.md:113` incorrectly says apps/auth unavailability returns 503 in both modes. In `log-only`, it must record `unverified` and still serve. Correct the documentation.
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-gemini.txt
new file mode 100644
index 00000000..1acc665f
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-gemini.txt
@@ -0,0 +1,39 @@
+### Implementation Review — Phase 3: `apps/api` verify client and `MCP_COMPLETE_KEY_MODE` setting
+
+The Phase 3 implementation is clean, well-structured, and meets all acceptance criteria for this phase.
+
+#### 1. Spec & Plan Adherence
+- **Verify client ([`verifyServiceKey`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/auth-service/client.ts#L161-L170))**:
+  - Uses [`authServiceFetch`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/auth-service/client.ts#L50-L72) (3 s timeout, public origin, `Origin` header, no `Authorization` header) to `POST` `{ key, permissions: { mcp: ['complete'] } }` to [`SERVICE_VERIFY_PATH`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/auth-service/client.ts#L139) (`/api/service/verify-key`).
+  - Strictly validates 200 responses with [`verifyServiceKeySchema`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/auth-service/client.ts#L141-L148): `{ valid: true, client_id, key_id }` (enforcing [`isMcpClientId`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/types/src/attribution.ts#L48-L55) and non-empty `key_id`) or `.strict()` `{ valid: false }`.
+  - Fails closed by throwing [`AuthServiceUnavailableError`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/auth-service/client.ts#L24-L33) on any non-200 status, network/timeout error, invalid JSON, extra fields on `{ valid: false }`, or off-pattern `client_id`.
+  - Emits no logs, preserving the client module's no-logging rule.
+- **Rollout configuration ([`config.mcpCompleteKeyMode`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/config.ts#L280-L282))**:
+  - [`envSchema`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/config.ts#L120) accepts `z.enum(['log-only', 'enforce']).optional()`, defaulting to `'enforce'` when unset and failing loudly at parse/boot on any other value.
+  - Four-way derivation is complete across [`apps/api/lib/config.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/config.ts#L120), [`apps/api/.env.example`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/.env.example#L94-L95), [`docs/self-hosting.md`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/docs/self-hosting.md#L113), and [`turbo.json`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/turbo.json#L146).
+
+#### 2. Test Coverage
+- [`apps/api/tests/auth/verify-service-key.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/auth/verify-service-key.test.ts): Thoroughly covers request shape/headers, valid verdicts (base and suffixed `ansari-mcp*`), exact `{ valid: false }`, network errors, 3 s timeout via `AbortSignal.timeout`, non-200 statuses, non-JSON bodies, missing/empty fields, off-pattern client IDs, and extra fields on `{ valid: false }`.
+- [`apps/api/tests/config.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/config.test.ts#L308-L330) & [`apps/api/tests/boot-check.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/boot-check.test.ts#L69-L75): Cover absent default (`enforce`), valid values, invalid typos/casing/empty strings, and production boot rejection.
+- [`apps/api/tests/self-hosting-docs.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/self-hosting-docs.test.ts#L89-L96): Good addition verifying every key in `envSchema.shape` is documented in `docs/self-hosting.md`.
+
+#### 3. Minor Note (can be addressed now or in Phase 5 docs pass)
+- **Wording in [`docs/self-hosting.md`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/docs/self-hosting.md#L113)**:
+  - Line 113 currently states: *"An unreachable apps/auth is 503 in both modes."*
+  - Per Spec §3 ("In log-only mode the route verifies exactly as above, records the verdict, and then **always serves**, including when apps/auth is unreachable") and Phase 4 of the plan, an unreachable `apps/auth` returns 503 in `enforce` mode, whereas in `log-only` mode it records `unverified`, raises a Sentry warning, and still serves the request. Update that sentence in `docs/self-hosting.md` so it matches Spec §3 and Phase 4/5.
+
+---
+VERDICT: APPROVE
+SUMMARY: Phase 3 implementation and tests are complete, fail-closed, and aligned with the spec and plan; one minor doc wording fix noted for `docs/self-hosting.md`.
+CONFIDENCE: HIGH
+---
+
+KEY_ISSUES: None
+
+---
+
+## ⚠️ REPOSITORY MOVED during the gemini review (#1649).
+A consultant reviews the commit in front of it; it must never commit, or switch refs.
+  - HEAD: 32755a99b2269e99e35259bb8285c985823c8956 -> 8a2a4da3fa3e434053f8e71b0e82df600a9bc78e
+The files on disk may look untouched and still not be the ones this review describes.
+Check `git reflog` and `git status` before trusting this review or shipping the branch.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-rebuttals.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-rebuttals.md
new file mode 100644
index 00000000..e2e961d6
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-rebuttals.md
@@ -0,0 +1,23 @@
+# Phase 3, iteration 1: rebuttal
+
+## Codex (REQUEST_CHANGES)
+
+**`docs/self-hosting.md:113` says an unreachable apps/auth is 503 in both modes.** Accepted, fixed in 89f14233.
+Spec §3 says log-only "always serves, including when apps/auth is unreachable". Acceptance also requires
+log-only to record `unverified` and raise a Sentry warning. The row now reads: `enforce` refuses a missing
+or invalid key with 401 and answers 503 when apps/auth is unreachable; `log-only` verifies, records the
+verdict (`unverified` when apps/auth is unreachable, with a Sentry warning) and always serves. The wrong
+sentence appeared nowhere else (grepped apps/, docs/, the thread).
+
+## Gemini (APPROVE)
+
+Raised the same docs sentence as a note. Fixed by the same commit.
+
+## Changes since iteration 1 also made at the security architect's request (8a2a4da3)
+
+- The turbo.json and config.ts removal follow-up now says "one week after enforcement; the issue is
+  opened at enforce (rollout step 6)", not a calendar date. Enforcement waits on the apps/auth cutover,
+  which has no fixed date.
+- client.ts contract comment: the `{ valid: false }` refusal is pinned on both sides. apps/auth tests
+  assert the byte-identical body. apps/api accepts only that shape, so adding a field on apps/auth
+  turns every bad key into a 503 and both sides must change together.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-codex.txt
new file mode 100644
index 00000000..70471759
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-codex.txt
@@ -0,0 +1,7 @@
+---
+VERDICT: APPROVE
+SUMMARY: Phase 3 implementation, strict verification client, rollout configuration, documentation, and tests align with the plan and specification.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-context.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-context.md
new file mode 100644
index 00000000..91f231e8
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-context.md
@@ -0,0 +1,37 @@
+### Iteration 1 Reviews
+- codex: REQUEST_CHANGES — Phase 3 implementation is sound, but its rollout-mode documentation contradicts the specification.
+- gemini: APPROVE — Phase 3 implementation and tests are complete, fail-closed, and aligned with the spec and plan; one minor doc wording fix noted for `docs/self-hosting.md`.
+
+### Builder Response to Iteration 1
+# Phase 3, iteration 1: rebuttal
+
+## Codex (REQUEST_CHANGES)
+
+**`docs/self-hosting.md:113` says an unreachable apps/auth is 503 in both modes.** Accepted, fixed in 89f14233.
+Spec §3 says log-only "always serves, including when apps/auth is unreachable". Acceptance also requires
+log-only to record `unverified` and raise a Sentry warning. The row now reads: `enforce` refuses a missing
+or invalid key with 401 and answers 503 when apps/auth is unreachable; `log-only` verifies, records the
+verdict (`unverified` when apps/auth is unreachable, with a Sentry warning) and always serves. The wrong
+sentence appeared nowhere else (grepped apps/, docs/, the thread).
+
+## Gemini (APPROVE)
+
+Raised the same docs sentence as a note. Fixed by the same commit.
+
+## Changes since iteration 1 also made at the security architect's request (8a2a4da3)
+
+- The turbo.json and config.ts removal follow-up now says "one week after enforcement; the issue is
+  opened at enforce (rollout step 6)", not a calendar date. Enforcement waits on the apps/auth cutover,
+  which has no fixed date.
+- client.ts contract comment: the `{ valid: false }` refusal is pinned on both sides. apps/auth tests
+  assert the byte-identical body. apps/api accepts only that shape, so adding a field on apps/auth
+  turns every bad key into a 503 and both sides must change together.
+
+
+### IMPORTANT: Stateful Review Context
+This is NOT the first review iteration. Previous reviewers raised concerns and the builder has responded.
+Before re-raising a previous concern:
+1. Check if the builder has already addressed it in code
+2. If the builder disputes a concern with evidence, verify the claim against actual project files before insisting
+3. Do not re-raise concerns that have been explained as false positives with valid justification
+4. Check package.json and config files for version numbers before flagging missing configuration
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-gemini.txt
new file mode 100644
index 00000000..02ee1652
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter2-gemini.txt
@@ -0,0 +1,16 @@
+## Phase 3 Review (Iteration 2)
+
+The iteration 1 documentation finding in [`docs/self-hosting.md`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/docs/self-hosting.md#L113) has been cleanly resolved: the `MCP_COMPLETE_KEY_MODE` row now accurately describes `enforce` (401 for missing/invalid keys, 503 when `apps/auth` is unreachable) and `log-only` (verifies, records the verdict—including `unverified` with a Sentry warning when `apps/auth` is unreachable—and always serves).
+
+All Phase 3 deliverables and additional refinements from the security architect are in place and verified:
+- **Verify Client**: [`verifyServiceKey`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/auth-service/client.ts#L166-L175) in [`apps/api/lib/auth-service/client.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/auth-service/client.ts#L139-L175) strictly validates responses and includes the contract comment pinning the `{ valid: false }` refusal shape across `apps/auth` and `apps/api`.
+- **Configuration & Four-Way Derivation**: `MCP_COMPLETE_KEY_MODE` is configured in [`apps/api/lib/config.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/config.ts#L116-L122) and [`config.mcpCompleteKeyMode`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/config.ts#L281-L284), documented in [`apps/api/.env.example`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/.env.example#L94-L95) and [`docs/self-hosting.md`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/docs/self-hosting.md#L113), and added to [`turbo.json`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/turbo.json#L141-L147) with relative rollout follow-up notes.
+- **Test Coverage**: Unit and integration checks in [`apps/api/tests/auth/verify-service-key.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/auth/verify-service-key.test.ts), [`apps/api/tests/config.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/config.test.ts#L308-L330), [`apps/api/tests/boot-check.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/boot-check.test.ts#L69-L75), and [`apps/api/tests/self-hosting-docs.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/self-hosting-docs.test.ts#L89-L96) thoroughly cover all acceptance criteria.
+
+---
+VERDICT: APPROVE
+SUMMARY: Phase 3 implementation, tests, and documentation updates are complete and aligned with the specification and plan.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_4-iter1-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_4-iter1-codex.txt
new file mode 100644
index 00000000..60bec7df
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_4-iter1-codex.txt
@@ -0,0 +1,18 @@
+---
+VERDICT: APPROVE
+SUMMARY: Phase 4 correctly implements enforcement, log-only rollout, key-based attribution, failure handling, and comprehensive route-level coverage.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
+
+---
+
+## ⚠️ WORKING TREE CHANGED during the codex review (#1649).
+A consultant reviews the tree; it must never write to it. 3 paths changed while this lane was running:
+  - apps/api/src/app/api/v2/mcp-complete/route.ts
+  - apps/auth/src/routes/service-verify.ts
+  - apps/auth/tests/service-verify.test.ts
+Check `git status` and `git diff` before trusting this review or shipping the branch.
+Note: under cmap the lanes run concurrently in one worktree, so another lane — or you —
+may be the writer. This warning names what moved, not who moved it.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_4-iter1-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_4-iter1-gemini.txt
new file mode 100644
index 00000000..a1aa3666
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_4-iter1-gemini.txt
@@ -0,0 +1,37 @@
+### Phase 4 Review: `mcp-complete` key gate, key attribution, and log-only mode
+
+#### Assessment
+
+1. **Spec Adherence & Plan Alignment**
+   - **Request Ordering**: Both `POST` and `GET` in [`route.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/src/app/api/v2/mcp-complete/route.ts#L345-L393) run `applyRateLimit` first, then `authorizeMcpRequest`, and only parse/validate the body or query parameters after the gate passes.
+   - **Bearer & Verification**: [`bearerOf`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/src/app/api/v2/mcp-complete/route.ts#L80-L85) extracts a single non-whitespace token with a case-insensitive `Bearer` scheme, recording `missing` without calling `apps/auth` when absent or malformed. [`authorizeMcpRequest`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/src/app/api/v2/mcp-complete/route.ts#L115-L163) calls `verifyServiceKey(token)`, maps `AuthServiceUnavailableError` to `unverified`, and lets unexpected errors propagate to the route's 500 handler without persisting anything.
+   - **Enforce vs. Log-Only Modes**:
+     - In `enforce` mode (the default), `missing` and `refused` return 401 `{ "error": "Unauthorized" }`, and `unverified` logs the status via `console.warn` and returns 503 `{ "error": "Authentication service unavailable" }`.
+     - In `log-only` mode, all verdicts proceed to serve the request, `unverified` emits the `mcp-complete key unverified (log-only)` Sentry warning, and non-valid verdicts fall back to `getClientId(request)`.
+     - Every request records the `mcp_key_verdict` Sentry tag and `[ai-skill] mcp-complete key verdict` structured log with `{ verdict, keyId? }` (never the raw key).
+   - **Attribution**: [`keyAttribution`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/src/app/api/v2/mcp-complete/route.ts#L94-L104) sets the `client` Sentry tag to the key's `clientId`, parses `X-Ansari-Client` in isolation via `parseClientId(..., null)` (ignoring `?src=` and avoiding `getClientId`'s duplicate invalid-header warning), and emits a single `mcp-complete client mismatch` warning tagged with `{ client, header_client }` (`'invalid'` when malformed, never the raw header).
+
+2. **Code Quality & Test Coverage**
+   - [`mcp-complete-key.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/mcp-complete-key.test.ts) thoroughly exercises scenarios 1–10, 12, and 13 (at the seam) for both `POST` and `GET` against PGlite with the real `verifyServiceKey` and `authServiceFetch`, including fake-timer timeout verification at `AUTH_SERVICE_TIMEOUT_MS` and a 16-character sliding-window leak scan with negative and near-miss controls.
+   - Existing route test suites ([`mcp-complete.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/mcp-complete.test.ts), [`route-persistence-rollback.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/route-persistence-rollback.test.ts), [`toolcalls-routes.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/toolcalls-routes.test.ts)) are cleanly wired to [`helpers/mcp-key.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/helpers/mcp-key.ts).
+   - *Minor non-blocking note*: In [`mcp-complete.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/mcp-complete.test.ts#L219-L227), the legacy test `it('does not require authentication')` with comment `// No Authorization header — should still work` now actually sends an `Authorization: Bearer ...` key via `makePostRequest`. You may optionally remove it or update its description if touching that file again, though it is harmless.
+
+---
+VERDICT: APPROVE
+SUMMARY: Phase 4 cleanly implements the mcp-complete key gate, key-first attribution, and log-only mode with comprehensive PGlite and leak-scan test coverage.
+CONFIDENCE: HIGH
+---
+
+KEY_ISSUES:
+- None
+
+---
+
+## ⚠️ WORKING TREE CHANGED during the gemini review (#1649).
+A consultant reviews the tree; it must never write to it. 3 paths changed while this lane was running:
+  - apps/api/src/app/api/v2/mcp-complete/route.ts
+  - apps/auth/src/routes/service-verify.ts
+  - apps/auth/tests/service-verify.test.ts
+Check `git status` and `git diff` before trusting this review or shipping the branch.
+Note: under cmap the lanes run concurrently in one worktree, so another lane — or you —
+may be the writer. This warning names what moved, not who moved it.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-codex.txt
new file mode 100644
index 00000000..870c84e1
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-codex.txt
@@ -0,0 +1,7 @@
+---
+VERDICT: REQUEST_CHANGES
+SUMMARY: Documentation is comprehensive, but the MCP alert runbook contains one incorrect diagnostic.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- `docs/cutover/service-keys-runbook.md:378` says a key configured without `Bearer ` can trigger apps/auth’s `unauthorized-volume` alert. It cannot: apps/api classifies this as `missing` and never calls the verify route. Remove that cause or direct operators to the apps/api `missing` verdict instead.
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt
new file mode 100644
index 00000000..326b67f8
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt
@@ -0,0 +1,26 @@
+## Phase 5 Review: Docs, Runbook, and Architecture Notes
+
+### Assessment
+
+The Phase 5 documentation, operator runbook, and architecture updates are complete, accurate, and aligned with the implementation in Phases 1–4 as well as the spec and plan:
+
+1. **Service Keys Runbook ([docs/cutover/service-keys-runbook.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/docs/cutover/service-keys-runbook.md#L272-L404))**:
+   - Placed under its own `## The ansari-mcp key (#314)` heading with `###` subsections so [cutover-docs.test.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/cutover-docs.test.ts#L445-L551) continues to match the WhatsApp `## Limits` and `## Alerts` sections cleanly.
+   - Covers per-deployment issuance (including `mcp-staging.askansari.ai` with `--client-id ansari-mcp-staging` before staging deploys #314, Workers, and `mcp.ansari.chat`), the verbatim `Bearer ansari_mcp_<64 letters>` handoff, the `MCP_COMPLETE_KEY_MODE` rollout sequence and follow-up removal issue, the `MCP_KEY_INITIAL` / `MCP_KEY_BOUNDS` limits, all six `McpVerifyAlert` kinds (including `client-id-invalid`) under `auth: MCP key verify alert: ` / `mcp-verify-`, two-key rotation with `--client-id`, and the `@better-auth/api-key` upgrade guard.
+   - Avoids false-positive path matches in `namedRepoPaths` (referencing `wrangler.jsonc` without triggering a non-existent `.json` path check).
+
+2. **Self-Hosting Guide & READMEs ([docs/self-hosting.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/docs/self-hosting.md#L267-L286), [apps/mcp/README.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/mcp/README.md#L92), [apps/mcp/.env.example](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/mcp/.env.example#L15-L20), [apps/api/README.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/README.md#L27), [RELEASE.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/RELEASE.md#L94))**:
+   - Documents `POST /api/v2/mcp-complete` key requirements, `POST /api/service/verify-key`, `MCP_COMPLETE_KEY_MODE`, and the `Bearer ansari_mcp_<64 letters>` format across all operator and developer surfaces.
+   - Placeholder syntax (`ansari_mcp_<64 letters>`) is used consistently; no key-shaped string appears in any doc.
+
+3. **Architecture Documentation ([codev/resources/arch-critical.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/resources/arch-critical.md#L13), [codev/resources/arch.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/resources/arch.md#L25-L27))**:
+   - `arch-critical.md` amends the JWT-only fact in place to note the `/v2/mcp-complete` exception and updates the Authentication & Authorization map line while staying within the hot-tier line and fact caps.
+   - `arch.md` adds the **The MCP key and its verify route (#314)** subsection covering the closed permission set, fail-closed posture, key attribution, throttle semantics, log-only transition, and plugin-upgrade guard.
+
+---
+VERDICT: APPROVE
+SUMMARY: Phase 5 documentation, runbook, and architecture updates are complete and match the implementation and spec.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-rebuttals.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-rebuttals.md
new file mode 100644
index 00000000..adfbd996
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-rebuttals.md
@@ -0,0 +1,4 @@
+# Phase 5 iter 1 — responses
+
+- Codex (REQUEST_CHANGES): the `unauthorized-volume` row named "a key without `Bearer `" as a cause. Accepted: apps/api classes a bearer-less value as `missing` and never calls the verify route. Removed that cause and pointed operators at the apps/api `missing` verdict instead.
+- Gemini: APPROVE, no issues.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-codex.txt
new file mode 100644
index 00000000..c3bcee47
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-codex.txt
@@ -0,0 +1,7 @@
+---
+VERDICT: APPROVE
+SUMMARY: Phase 5 documentation and architecture updates accurately match the implementation and plan.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-context.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-context.md
new file mode 100644
index 00000000..3edf7c8e
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-context.md
@@ -0,0 +1,18 @@
+### Iteration 1 Reviews
+- codex: REQUEST_CHANGES — Documentation is comprehensive, but the MCP alert runbook contains one incorrect diagnostic.
+- gemini: APPROVE — Phase 5 documentation, runbook, and architecture updates are complete and match the implementation and spec.
+
+### Builder Response to Iteration 1
+# Phase 5 iter 1 — responses
+
+- Codex (REQUEST_CHANGES): the `unauthorized-volume` row named "a key without `Bearer `" as a cause. Accepted: apps/api classes a bearer-less value as `missing` and never calls the verify route. Removed that cause and pointed operators at the apps/api `missing` verdict instead.
+- Gemini: APPROVE, no issues.
+
+
+### IMPORTANT: Stateful Review Context
+This is NOT the first review iteration. Previous reviewers raised concerns and the builder has responded.
+Before re-raising a previous concern:
+1. Check if the builder has already addressed it in code
+2. If the builder disputes a concern with evidence, verify the claim against actual project files before insisting
+3. Do not re-raise concerns that have been explained as false positives with valid justification
+4. Check package.json and config files for version numbers before flagging missing configuration
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-gemini.txt
new file mode 100644
index 00000000..7af04857
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter2-gemini.txt
@@ -0,0 +1,17 @@
+### Phase 5 Review: Docs, Runbook, and Architecture Notes
+
+The iteration 1 finding in [service-keys-runbook.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/docs/cutover/service-keys-runbook.md#L378) has been cleanly resolved: the `unauthorized-volume` diagnostic now accurately lists causes that reach `/api/service/verify-key` and clarifies that a variable missing the `Bearer ` prefix is handled at `apps/api` with the `missing` verdict without calling `apps/auth`.
+
+All Phase 5 deliverables and acceptance criteria are fulfilled:
+- **Runbook ([service-keys-runbook.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/docs/cutover/service-keys-runbook.md#L272-L404))**: Covers `ansari-mcp` issuance, Worker/Railway/owner secret handoff, rollout (`log-only` → `enforce`), limits (`120` per `60 s`, `5,000` daily), alerts (including `client-id-invalid`), rotation, and the plugin upgrade check, structured under its own `##` heading so existing `cutover-docs.test.ts` section slices remain intact.
+- **Self-Hosting & Service Docs ([self-hosting.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/docs/self-hosting.md#L267-L286), [apps/mcp/README.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/mcp/README.md#L92), [apps/mcp/.env.example](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/mcp/.env.example#L15-L20), [apps/api/README.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/README.md#L27), [RELEASE.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/RELEASE.md#L94))**: Document the key requirement, `Bearer ansari_mcp_<64 letters>` format, verify contract, and `MCP_COMPLETE_KEY_MODE` setting.
+- **Architecture Notes ([arch-critical.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/resources/arch-critical.md#L13-L22), [arch.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/resources/arch.md#L27))**: Amend the JWT-only statement in `arch-critical.md` in place (preserving line/fact caps) and add the MCP verify subsection to `arch.md`.
+
+---
+VERDICT: APPROVE
+SUMMARY: Phase 5 documentation, runbook, and architecture updates are complete, accurate, and resolve the Iteration 1 feedback.
+CONFIDENCE: HIGH
+---
+
+KEY_ISSUES:
+- None
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-codex.txt
new file mode 100644
index 00000000..d62942a2
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-codex.txt
@@ -0,0 +1,21 @@
+---
+VERDICT: REQUEST_CHANGES
+SUMMARY: Strong security implementation, but malformed bearer values are misclassified as authentication-service outages and review artifacts are uncommitted.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- `route.ts:83` accepts any non-whitespace token. Tokens over 256 characters or containing non-ASCII reach apps/auth, which returns 400; `verifyServiceKey` then maps that to a 503 outage. The spec requires malformed bearers to return 401 without calling apps/auth. Validate the token’s printable-ASCII/length envelope locally and add POST/GET tests.
+- Twenty-six Phase 1–5 consultation artifacts remain untracked although `status.yaml` and the review reference those consultations. Commit the protocol evidence before PR completion.
+
+PR_SUMMARY: |
+  ## Summary
+  Protects `/api/v2/mcp-complete` with per-request `ansari-mcp` service-key verification and trusted key-based attribution. Adds a rollout mode that defaults to enforcement and fails closed on authentication-service outages.
+
+  ## Key Changes
+  - Adds the apps/auth service-key verification route, limits, alerts, and operator tooling.
+  - Adds apps/api authorization gating, attribution checks, rollout configuration, tests, and deployment documentation.
+
+  ## Test Plan
+  - Run `npm run build`.
+  - Run `npm test -- --exclude='**/e2e/**'`.
+  - Verify malformed, refused, valid, and unavailable-auth scenarios for both GET and POST.
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-gemini.txt
new file mode 100644
index 00000000..47b1eae6
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-gemini.txt
@@ -0,0 +1,46 @@
+### Review of PR #372 (`[Spec 314] Protect /v2/mcp-complete with ansari-mcp API keys`)
+
+#### 1. Code Quality & Correctness
+- **Shared Client-ID Rule & Service Limits ([attribution.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/types/src/attribution.ts), [limits.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/auth/src/limits.ts), [service-users.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/packages/auth/src/service-users.ts), [service-keys.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/scripts/service-keys.ts)):**
+  - `MCP_CLIENT_ID_PATTERN` (`/^ansari-mcp(-[a-z0-9._-]+)?$/`, ≤ 64 chars) is cleanly defined in `@ansari/types` as a strict subset of `CLIENT_ID_PATTERN` and re-exported through `@ansari/auth`.
+  - `clientIdOf` safely handles both JSON text (1.7.7 DB storage) and parsed object runtime shapes without throwing.
+  - `service-keys.ts` enforces `--client-id` matching `isMcpClientId` for `ansari-mcp` on both `create-key` and `rotate` (at CLI parse and execution), never echoes a rejected value, and prints `client_id` in `list`.
+- **Verify Endpoint ([service-verify.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/service-verify.ts), [alerts.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/alerts.ts), [app.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/app.ts), [apikey-relation.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/src/routes/apikey-relation.ts)):**
+  - Mounted ahead of `corsFor` and outside `/api/auth/*`, ensuring no CORS headers (including on `OPTIONS`) and no per-IP router limiter on `apps/api`'s egress IP.
+  - Enforces a 1 KiB body limit, `application/json`, key bounds (`^[\x21-\x7E]{1,256}$`), and a closed permission set (`{ mcp: ['complete'] }`) before touching any key or calling the plugin.
+  - Runs the shared `auth.apikey` relation check on plugin refusal so DB outages return `500` instead of `{"valid":false}`.
+  - Resolves the `ansari-mcp` service user only after plugin acceptance, verifies `referenceId` ownership and `isMcpClientId(clientId)`, and calls `alerts.keyVerified` only after all checks pass so refused keys cannot inflate volume alerts.
+- **API Client, Config & Route Gate ([client.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/auth-service/client.ts), [config.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/config.ts), [route.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/src/app/api/v2/mcp-complete/route.ts)):**
+  - `verifyServiceKey` pins both response shapes (`{ valid: true, client_id, key_id }` with `isMcpClientId` and `.strict()` on `{ valid: false }`), throwing `AuthServiceUnavailableError` on any non-200, timeout, or schema drift.
+  - `MCP_COMPLETE_KEY_MODE` accepts only `'log-only' | 'enforce'`, defaults to `'enforce'` when absent, and is wired across all four derivation points (`config.ts`, `.env.example`, `docs/self-hosting.md`, and `turbo.json` `globalEnv`).
+  - `authorizeMcpRequest` gates both `POST` and `GET` after the per-IP rate limit and before reading the request body or query parameters. In `enforce` mode, missing/refused keys return `401` and `apps/auth` outages return `503` with zero DB writes and no facilitator calls. Key attribution overrides `X-Ansari-Client` and `?src=`, emitting a single sanitized `mcp-complete client mismatch` warning when a header conflicts.
+
+#### 2. Alignment with Spec & Plan
+- All requirements in [314-protect-v2-mcp-complete-with-b.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/specs/314-protect-v2-mcp-complete-with-b.md) (including Amendment 1 regarding plugin deletion of expired keys on presentation) and all five phases of [314-protect-v2-mcp-complete-with-b.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/plans/314-protect-v2-mcp-complete-with-b.md) are complete.
+- The review document ([314-protect-v2-mcp-complete-with-b.md](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/reviews/314-protect-v2-mcp-complete-with-b.md)) thoroughly documents spec compliance, deviations, consultation rounds, lessons learned, and the out-of-repo operator deployment steps.
+
+#### 3. Test Coverage & Security Verification
+- **apps/auth ([service-verify.test.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/service-verify.test.ts), [service-verify-sentry.test.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/service-verify-sentry.test.ts), [blocked-paths.test.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/auth/tests/blocked-paths.test.ts)):** Tests run against pglite with the real `@better-auth/api-key` plugin, covering valid keys, byte-identical refusals, WhatsApp key presentation (confirming `remaining` is unspent), closed permission set 400s without plugin invocation, service-user missing/duplicate 500s, DB outages, CORS absence, alert deduplication, and the plugin-upgrade guard on `/api-key/verify`.
+- **apps/api ([verify-service-key.test.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/auth/verify-service-key.test.ts), [mcp-complete-key.test.ts](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/mcp-complete-key.test.ts)):** Tests run against pglite with the real `verifyServiceKey` client and an HTTP-boundary `fetch` stub, verifying 401/503 fail-closed behavior, zero persistence on failure, 3 s timeout handling, key attribution precedence, `log-only` fallback behavior, and 16-character sliding-window key leak scans (with negative controls).
+
+---
+VERDICT: APPROVE
+SUMMARY: Complete, well-tested implementation of ansari-mcp API key verification across apps/auth and apps/api with fail-closed semantics, strict attribution, and comprehensive documentation.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
+
+PR_SUMMARY: |
+  ## Summary
+  Protects `POST` and `GET /api/v2/mcp-complete` on `apps/api` with `Authorization: Bearer `, verified on every request at a new public `apps/auth` route (`POST /api/service/verify-key`). Enforces fail-closed semantics (401 on missing/refused keys, 503 on `apps/auth` outage with nothing persisted and no Gemini call), binds thread attribution to the key's `client_id`, and provides a `MCP_COMPLETE_KEY_MODE=log-only` rollout mode (defaulting to `enforce` when unset).
+
+  ## Key Changes
+  - **packages/types & packages/auth:** Added `MCP_CLIENT_ID_PATTERN` / `isMcpClientId`, `MCP_KEY_BOUNDS`, `MCP_KEY_INITIAL` (120/60s, 5,000/day), MCP verify alert thresholds, and `clientIdOf` metadata parsing.
+  - **apps/auth:** Added `POST /api/service/verify-key` (closed `{ mcp: ['complete'] }` permission set, owner and `ansari-mcp*` client-id binding, `auth.apikey` outage relation check, byte-identical `{"valid":false}` refusals, no CORS, no per-IP limit), generalized key alerts (`createMcpVerifyAlerts` including `client-id-invalid`), required `--client-id` for `ansari-mcp` in `service-keys.ts`, and added a plugin-upgrade guard in `blocked-paths.test.ts`.
+  - **apps/api:** Added `verifyServiceKey` in `lib/auth-service/client.ts` (3 s timeout, strict response schema), `MCP_COMPLETE_KEY_MODE` config validation (`enforce` default), and `authorizeMcpRequest` in `v2/mcp-complete/route.ts` with key-derived client attribution and mismatch warnings.
+  - **Docs & Config:** Updated `docs/cutover/service-keys-runbook.md`, `docs/self-hosting.md`, `RELEASE.md`, `apps/api` and `apps/mcp` READMEs/env examples, architecture/lessons docs, and `turbo.json` `globalEnv`.
+
+  ## Test Plan
+  - `apps/auth` pglite suites (`service-verify.test.ts`, `service-verify-sentry.test.ts`, `blocked-paths.test.ts`, `service-keys.test.ts`, `limits.test.ts`) covering real plugin verification, refusal parity, permission/owner/client-id guards, DB outages, alert deduplication, and 16-char window leak scans.
+  - `apps/api` pglite and unit suites (`mcp-complete-key.test.ts`, `verify-service-key.test.ts`, `config.test.ts`, `boot-check.test.ts`, plus existing route suites with `helpers/mcp-key.ts`) covering `enforce` and `log-only` modes, 401/503 zero-persistence guarantees, forged `X-Ansari-Client` handling, and key leak scans.
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-rebuttals.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-rebuttals.md
new file mode 100644
index 00000000..007229f4
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-rebuttals.md
@@ -0,0 +1,14 @@
+# Review (PR #372), iteration 1: responses
+
+## Codex (REQUEST_CHANGES)
+
+1. **A bearer token over 256 characters or containing non-ASCII reaches apps/auth, which answers 400. apps/api maps that to a 503 outage, but it should be a 401 with no call.** Accepted and fixed.
+   - `apps/api/lib/auth-service/client.ts` gains `SERVICE_KEY_MAX_LENGTH` (256, apps/auth's `VERIFY_KEY_MAX_LENGTH`) and `isServiceKeyShape` (`[\x21-\x7E]{1,256}`).
+   - The route's `bearerOf` treats any token outside that envelope as `missing`: 401, no apps/auth call.
+   - New POST and GET tests: a 257-character token, a non-ASCII token and a DEL token each get 401 with no fetch. A 256-character token at the bound is sent to apps/auth.
+   - Mutation check: with the shape check disabled, the 6 new refusal tests fail.
+2. **The Phase 1–5 consultation outputs were untracked.** Accepted. This repo commits them (other projects' `codev/projects/*` consult files are tracked). They are committed with this fix.
+
+## Gemini (APPROVE)
+
+No issues raised.

From ff07d696c927e0e3c11c109e59c1b87cf950c5f5 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:33:07 +1100
Subject: [PATCH 153/435] chore(porch): 314 review re-iter (iter 2)

---
 .../status.yaml                                 | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 9513d225..0d74da35 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -32,8 +32,8 @@ gates:
     status: pending
   verify-approval:
     status: pending
-iteration: 1
-build_complete: true
+iteration: 2
+build_complete: false
 history:
   - iteration: 1
     plan_phase: phase_2
@@ -83,8 +83,19 @@ history:
         verdict: APPROVE
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt
+  - iteration: 1
+    build_output: ''
+    reviews:
+      - model: codex
+        verdict: REQUEST_CHANGES
+        file: >-
+          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-codex.txt
+      - model: gemini
+        verdict: APPROVE
+        file: >-
+          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:27:53.416Z'
+updated_at: '2026-11-11T04:33:07.343Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'

From 95413efc08f678c35db0597655aa64c62fef6818 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:34:07 +1100
Subject: [PATCH 154/435] chore(porch): 314 review build-complete

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 0d74da35..c02838b5 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -33,7 +33,7 @@ gates:
   verify-approval:
     status: pending
 iteration: 2
-build_complete: false
+build_complete: true
 history:
   - iteration: 1
     plan_phase: phase_2
@@ -95,7 +95,7 @@ history:
         file: >-
           /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-gemini.txt
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:33:07.343Z'
+updated_at: '2026-11-11T04:34:07.259Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'

From 7abb9952932ae5d946214dc8d8e686f4a4c7ed51 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:36:24 +1100
Subject: [PATCH 155/435] [Spec 314] PR review iteration 2 consultation outputs
 (both APPROVE)

---
 .../314-review-iter2-codex.txt                | 21 ++++++++++++
 .../314-review-iter2-context.md               | 28 +++++++++++++++
 .../314-review-iter2-gemini.txt               | 34 +++++++++++++++++++
 3 files changed, 83 insertions(+)
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-context.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-gemini.txt

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-codex.txt
new file mode 100644
index 00000000..c683a53b
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-codex.txt
@@ -0,0 +1,21 @@
+---
+VERDICT: APPROVE
+SUMMARY: Prior bearer-shape issue is correctly fixed; implementation, tests, documentation, and review artifacts align with the spec.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
+
+PR_SUMMARY: |
+  ## Summary
+  Protects both `/api/v2/mcp-complete` methods using `ansari-mcp` service keys verified by apps/auth. Requests fail closed, and trusted client attribution comes from key metadata.
+
+  ## Key Changes
+  - Adds the service-key verification route, limits, alerts, and operator tooling.
+  - Adds enforce/log-only gating, strict bearer validation, attribution, and rollout documentation.
+  - Provides comprehensive pglite, boundary, failure-path, and leak-scan coverage.
+
+  ## Test Plan
+  - Run `npm run build`.
+  - Run `npm test -- --exclude='**/e2e/**'`.
+  - Verify malformed credentials return 401 without contacting apps/auth, while outages return 503.
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-context.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-context.md
new file mode 100644
index 00000000..e7114c4a
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-context.md
@@ -0,0 +1,28 @@
+### Iteration 1 Reviews
+- codex: REQUEST_CHANGES — Strong security implementation, but malformed bearer values are misclassified as authentication-service outages and review artifacts are uncommitted.
+- gemini: APPROVE — Complete, well-tested implementation of ansari-mcp API key verification across apps/auth and apps/api with fail-closed semantics, strict attribution, and comprehensive documentation.
+
+### Builder Response to Iteration 1
+# Review (PR #372), iteration 1: responses
+
+## Codex (REQUEST_CHANGES)
+
+1. **A bearer token over 256 characters or containing non-ASCII reaches apps/auth, which answers 400. apps/api maps that to a 503 outage, but it should be a 401 with no call.** Accepted and fixed.
+   - `apps/api/lib/auth-service/client.ts` gains `SERVICE_KEY_MAX_LENGTH` (256, apps/auth's `VERIFY_KEY_MAX_LENGTH`) and `isServiceKeyShape` (`[\x21-\x7E]{1,256}`).
+   - The route's `bearerOf` treats any token outside that envelope as `missing`: 401, no apps/auth call.
+   - New POST and GET tests: a 257-character token, a non-ASCII token and a DEL token each get 401 with no fetch. A 256-character token at the bound is sent to apps/auth.
+   - Mutation check: with the shape check disabled, the 6 new refusal tests fail.
+2. **The Phase 1–5 consultation outputs were untracked.** Accepted. This repo commits them (other projects' `codev/projects/*` consult files are tracked). They are committed with this fix.
+
+## Gemini (APPROVE)
+
+No issues raised.
+
+
+### IMPORTANT: Stateful Review Context
+This is NOT the first review iteration. Previous reviewers raised concerns and the builder has responded.
+Before re-raising a previous concern:
+1. Check if the builder has already addressed it in code
+2. If the builder disputes a concern with evidence, verify the claim against actual project files before insisting
+3. Do not re-raise concerns that have been explained as false positives with valid justification
+4. Check package.json and config files for version numbers before flagging missing configuration
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-gemini.txt
new file mode 100644
index 00000000..f609bea0
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter2-gemini.txt
@@ -0,0 +1,34 @@
+### Review Assessment (Iteration 2)
+
+All feedback from Iteration 1 has been cleanly resolved:
+
+1. **Bearer Token Envelope Validation (`isServiceKeyShape`)**:
+   - [`client.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/lib/auth-service/client.ts#L147-L153) defines `SERVICE_KEY_MAX_LENGTH = 256` and `isServiceKeyShape` (`^[\x21-\x7E]{1,256}$`), matching `apps/auth`'s `VERIFY_KEY_MAX_LENGTH` envelope.
+   - [`route.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/src/app/api/v2/mcp-complete/route.ts#L86-L91) uses `isServiceKeyShape` in `bearerOf` so overlong (>256 chars), non-ASCII, or control-character tokens are classified locally as `missing` (returning `401 Unauthorized` without calling `apps/auth`, rather than forwarding to `apps/auth` and mapping its `400` response to a `503` outage).
+   - [`mcp-complete-key.test.ts`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/apps/api/tests/mcp-complete-key.test.ts#L320-L338) covers 257-character, non-ASCII, and DEL (`0x7F`) tokens (`401` with no `fetch`) as well as a 256-character boundary token across both `POST` and `GET`.
+
+2. **Tracked Consultation Artifacts & Review Document**:
+   - All consultation artifacts under `codev/projects/314-protect-v2-mcp-complete-with-b/` are tracked, and [`314-protect-v2-mcp-complete-with-b.md`](file:///Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/reviews/314-protect-v2-mcp-complete-with-b.md) is complete and up to date.
+
+---
+VERDICT: APPROVE
+SUMMARY: Complete, well-tested implementation of ansari-mcp API key verification across apps/auth and apps/api, with Iteration 1's bearer token shape validation and artifact tracking cleanly resolved.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
+
+PR_SUMMARY: |
+  ## Summary
+  Protects `POST` and `GET /api/v2/mcp-complete` on `apps/api` with `ansari-mcp` service API keys issued by `apps/auth`, verified on every request via a new `POST /api/service/verify-key` endpoint. Enforces fail-closed semantics (`401` on missing/refused keys, `503` on `apps/auth` outages with nothing persisted and no model calls), binds thread/message `client` attribution strictly to the key's `client_id`, and supports a `MCP_COMPLETE_KEY_MODE` (`log-only` | `enforce`, defaulting to `enforce`) transition setting.
+
+  ## Key Changes
+  - **`packages/types` & `packages/auth`**: Add `MCP_CLIENT_ID_PATTERN` / `isMcpClientId` (`^ansari-mcp(-[a-z0-9._-]+)?$`, max 64 chars), `MCP_KEY_INITIAL` / `MCP_KEY_BOUNDS`, MCP verify alert thresholds, and `clientIdOf` metadata parsing.
+  - **`apps/auth`**: Add `POST /api/service/verify-key` (`apps/auth/src/routes/service-verify.ts`) locked to `{ mcp: ['complete'] }` and the `ansari-mcp` service user, returning `{ valid: true, client_id, key_id }` or a byte-identical `{"valid":false}` with rate-limited Sentry alerts, no CORS headers, and no per-IP router throttle. Require `--client-id` in `service-keys.ts` when issuing/rotating `ansari-mcp` keys.
+  - **`apps/api`**: Add `verifyServiceKey` (`3s` timeout, strict response schema, `isServiceKeyShape` pre-check) in `apps/api/lib/auth-service/client.ts`, `MCP_COMPLETE_KEY_MODE` config validation, and `authorizeMcpRequest` in `/api/v2/mcp-complete/route.ts`.
+  - **Docs & Runbook**: Document per-deployment key issuance, `Bearer ` handoff, rollout steps, alert table, rotation, and plugin-upgrade checks in `docs/cutover/service-keys-runbook.md`, `docs/self-hosting.md`, `RELEASE.md`, and app READMEs.
+
+  ## Test Plan
+  - Run `apps/auth` pglite & unit suites (`service-verify.test.ts`, `service-verify-sentry.test.ts`, `service-keys.test.ts`, `blocked-paths.test.ts`, `limits.test.ts`).
+  - Run `apps/api` pglite & unit suites (`mcp-complete-key.test.ts`, `verify-service-key.test.ts`, `config.test.ts`, `boot-check.test.ts`, `mcp-complete.test.ts`).
+  - Verify leak scans confirm no key material appears in logs, Sentry events, responses, or plaintext DB columns.
\ No newline at end of file

From 0798cfcea6d03fd970772feb8bc526c3fe8c5516 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Wed, 11 Nov 2026 15:36:26 +1100
Subject: [PATCH 156/435] chore(porch): 314 pr gate-requested

---
 .../status.yaml                               | 69 ++-----------------
 1 file changed, 6 insertions(+), 63 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index c02838b5..1c5defe9 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -30,72 +30,14 @@ gates:
     approved_at: '2026-11-11T03:20:48.411Z'
   pr:
     status: pending
+    requested_at: '2026-11-11T04:36:26.447Z'
   verify-approval:
     status: pending
-iteration: 2
-build_complete: true
-history:
-  - iteration: 1
-    plan_phase: phase_2
-    build_output: ''
-    reviews:
-      - model: codex
-        verdict: REQUEST_CHANGES
-        file: >-
-          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-codex.txt
-      - model: gemini
-        verdict: APPROVE
-        file: >-
-          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter1-gemini.txt
-  - iteration: 2
-    plan_phase: phase_2
-    build_output: ''
-    reviews:
-      - model: codex
-        verdict: REQUEST_CHANGES
-        file: >-
-          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-codex.txt
-      - model: gemini
-        verdict: APPROVE
-        file: >-
-          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_2-iter2-gemini.txt
-  - iteration: 1
-    plan_phase: phase_3
-    build_output: ''
-    reviews:
-      - model: codex
-        verdict: REQUEST_CHANGES
-        file: >-
-          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-codex.txt
-      - model: gemini
-        verdict: APPROVE
-        file: >-
-          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_3-iter1-gemini.txt
-  - iteration: 1
-    plan_phase: phase_5
-    build_output: ''
-    reviews:
-      - model: codex
-        verdict: REQUEST_CHANGES
-        file: >-
-          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-codex.txt
-      - model: gemini
-        verdict: APPROVE
-        file: >-
-          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-phase_5-iter1-gemini.txt
-  - iteration: 1
-    build_output: ''
-    reviews:
-      - model: codex
-        verdict: REQUEST_CHANGES
-        file: >-
-          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-codex.txt
-      - model: gemini
-        verdict: APPROVE
-        file: >-
-          /Users/amrmohamed/repos/iaser/ansari/.builders/spir-314/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter1-gemini.txt
+iteration: 1
+build_complete: false
+history: []
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:34:07.259Z'
+updated_at: '2026-11-11T04:36:26.447Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'
@@ -123,3 +65,4 @@ pr_history:
     pr_number: 372
     branch: builder/spir-314
     created_at: '2026-11-11T04:27:48.853Z'
+pr_ready_for_human: true

From 90bb9bc6837cc319310d6ba9b3eac0427de1b965 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 09:37:16 +1100
Subject: [PATCH 157/435] [Spec 314][Phase: review] feat: ENVIRONMENT in
 apps/api and apps/auth; environment-labelled service-key prefixes, refused
 across environments (Amendments 2-3, owner)

---
 apps/api/.env.ci                              |   3 +
 apps/api/.env.example                         |   9 +-
 apps/api/lib/config.ts                        |   7 ++
 apps/api/sentry.server.config.ts              |   5 +-
 apps/api/tests/boot-check.test.ts             |  27 ++++-
 apps/api/tests/config.test.ts                 |   1 +
 apps/api/tests/cutover-docs.test.ts           |   4 +-
 apps/api/tests/helpers/mcp-key.ts             |   2 +-
 apps/api/tests/mcp-complete-key.test.ts       |   2 +-
 apps/auth/.env.ci                             |   3 +
 apps/auth/.env.example                        |   5 +
 apps/auth/scripts/probes/service-keys-demo.ts |   5 +-
 apps/auth/scripts/service-keys.ts             |  43 +++++--
 apps/auth/src/app.ts                          |   9 +-
 apps/auth/src/index.ts                        |   2 +-
 apps/auth/src/routes/service-verify.ts        |  13 ++-
 apps/auth/src/routes/whatsapp.ts              |  13 ++-
 apps/auth/tests/environment.test.ts           |  78 +++++++++++++
 apps/auth/tests/helpers/leak-scan.ts          |  11 +-
 apps/auth/tests/helpers/service.ts            |   6 +
 apps/auth/tests/service-keys-no-dsn.test.ts   |   3 +-
 apps/auth/tests/service-keys-sentry.test.ts   |   3 +-
 apps/auth/tests/service-keys.test.ts          | 105 ++++++++++++++++--
 apps/auth/tests/service-verify.test.ts        |  69 +++++++++++-
 apps/auth/tests/whatsapp-session.test.ts      |  23 +++-
 packages/auth/src/env.ts                      |  13 ++-
 packages/auth/src/index.ts                    |   1 +
 packages/auth/src/service-users.ts            |  67 +++++++++--
 packages/types/package.json                   |   3 +-
 packages/types/src/environment.ts             |  26 +++++
 turbo.json                                    |   5 +
 31 files changed, 510 insertions(+), 56 deletions(-)
 create mode 100644 apps/auth/tests/environment.test.ts
 create mode 100644 packages/types/src/environment.ts

diff --git a/apps/api/.env.ci b/apps/api/.env.ci
index f37c47d5..17c56627 100644
--- a/apps/api/.env.ci
+++ b/apps/api/.env.ci
@@ -7,3 +7,6 @@ DATABASE_URL=postgresql://placeholder-user:placeholder-not-a-real-password@local
 KALEMAT_API_KEY=placeholder-not-a-real-key
 USUL_API_TOKEN=placeholder-not-a-real-token
 GEMINI_API_KEY=placeholder-not-a-real-key
+
+# The deployment label (#314 Amendment 3).
+ENVIRONMENT=development
diff --git a/apps/api/.env.example b/apps/api/.env.example
index 7104d531..996e1fa6 100644
--- a/apps/api/.env.example
+++ b/apps/api/.env.example
@@ -73,9 +73,7 @@ USUL_BASE_URL=https://api.usul.ai/v1/vector-search
 # Sentry
 SENTRY_DSN=https://examplePublicKey@o0.ingest.sentry.io/0
 SENTRY_AUTH_TOKEN=sntrys_...  # Optional — for source map uploads in production builds
-# RAILWAY_ENVIRONMENT is auto-injected by Railway and used as the Sentry environment tag.
-# Optional — falls back to NODE_ENV off-Railway; no need to set it manually.
-# RAILWAY_ENVIRONMENT=production
+# The Sentry environment tag is ENVIRONMENT (below), not Railway's RAILWAY_ENVIRONMENT (#314).
 
 # IslamicMMLU leaderboard bearer token for /api/v1/chat/completions (Spec 19).
 # Optional — when unset the OpenAI-compat endpoint returns 503. Generate with `openssl rand -hex 32`.
@@ -93,3 +91,8 @@ NODE_ENV=development
 
 # How /api/v2/mcp-complete treats its service key (#314): enforce (default) or log-only.
 # MCP_COMPLETE_KEY_MODE=enforce
+
+# The deployment label (#314 Amendment 3): development, staging or production. The Sentry
+# environment and the service-key prefix environment. Required, and staging or production,
+# when NODE_ENV=production; development otherwise.
+ENVIRONMENT=development
diff --git a/apps/api/lib/config.ts b/apps/api/lib/config.ts
index 490fa5ff..c30a083f 100644
--- a/apps/api/lib/config.ts
+++ b/apps/api/lib/config.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_ENVIRONMENT, ENVIRONMENTS, environmentIssue } from '@ansari/types/environment';
 import { z } from 'zod';
 
 const AUTH_SERVICE_VARS = [
@@ -133,7 +134,13 @@ export const envSchema = z.object({
 
   // Optional
   NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
+  // The deployment label (#314 Amendment 3): the Sentry environment. Required,
+  // and staging or production, under NODE_ENV=production (below); development
+  // otherwise. Enforced at production boot (lib/boot-check.ts), never at build.
+  ENVIRONMENT: z.enum(ENVIRONMENTS).default(DEFAULT_ENVIRONMENT),
 }).superRefine((env, ctx) => {
+  const environment = environmentIssue(env.NODE_ENV, env.ENVIRONMENT);
+  if (environment) ctx.addIssue({ code: 'custom', path: ['ENVIRONMENT'], message: environment });
   if (env.NODE_ENV === 'production') {
     for (const name of AUTH_SERVICE_VARS) {
       if (!env[name]) {
diff --git a/apps/api/sentry.server.config.ts b/apps/api/sentry.server.config.ts
index 87e493ac..c1140e21 100644
--- a/apps/api/sentry.server.config.ts
+++ b/apps/api/sentry.server.config.ts
@@ -5,7 +5,10 @@ import { SENTRY_REQUEST_PRIVACY } from "./lib/sentry-scrub";
 Sentry.init({
   dsn: process.env.SENTRY_DSN,
   enabled: process.env.NODE_ENV !== "test" && !process.env.VITEST,
-  environment: process.env.RAILWAY_ENVIRONMENT || process.env.NODE_ENV,
+  // The deployment label (#314 Amendment 3), the same vocabulary as apps/auth
+  // and the frontend. Validated at production boot (lib/boot-check.ts, which
+  // runs right after this file); unset only outside production.
+  environment: process.env.ENVIRONMENT || "development",
   tracesSampleRate: process.env.NODE_ENV === "production" ? 0.1 : 1.0,
   ...SENTRY_REQUEST_PRIVACY,
 });
diff --git a/apps/api/tests/boot-check.test.ts b/apps/api/tests/boot-check.test.ts
index 69ccb1b3..065cbb17 100644
--- a/apps/api/tests/boot-check.test.ts
+++ b/apps/api/tests/boot-check.test.ts
@@ -23,7 +23,7 @@ const AUTH_ENV = {
   AUTH_JWT_AUDIENCE: 'ansari-api-boot-check-value',
   AUTH_LAYER_ORIGIN: 'https://api.askansari.ai',
 };
-const SERVER = { NODE_ENV: 'production', NEXT_RUNTIME: 'nodejs' } as const;
+const SERVER = { NODE_ENV: 'production', NEXT_RUNTIME: 'nodejs', ENVIRONMENT: 'production' } as const;
 
 let saved: NodeJS.ProcessEnv;
 beforeEach(() => {
@@ -74,6 +74,31 @@ describe('validateEnvAtBoot', () => {
     expect(() => validateEnvAtBoot()).not.toThrow();
   });
 
+  it('a production boot without ENVIRONMENT, or labelled development, throws naming it (#314 Amendment 3)', () => {
+    for (const environment of [undefined, 'development', 'prod', 'test']) {
+      resetEnvCache();
+      process.env = { ...process.env, ...BASE_ENV, ...AUTH_ENV, ...SERVER };
+      if (environment === undefined) delete process.env.ENVIRONMENT;
+      else process.env.ENVIRONMENT = environment;
+      expect(() => validateEnvAtBoot(), String(environment)).toThrow(/ENVIRONMENT/);
+    }
+  });
+
+  it.each(['staging', 'production'])('a production boot with ENVIRONMENT=%s boots', (environment) => {
+    process.env = { ...process.env, ...BASE_ENV, ...AUTH_ENV, ...SERVER, ENVIRONMENT: environment };
+    expect(() => validateEnvAtBoot()).not.toThrow();
+  });
+
+  it('next build and dev run without ENVIRONMENT; outside production it defaults to development', async () => {
+    process.env = { ...process.env, ...SERVER, NEXT_PHASE: 'phase-production-build' };
+    delete process.env.ENVIRONMENT;
+    expect(() => validateEnvAtBoot()).not.toThrow();
+    process.env = { ...process.env, ...BASE_ENV, NODE_ENV: 'development', NEXT_PHASE: undefined };
+    resetEnvCache();
+    const { getEnv } = await import('@/lib/config');
+    expect(getEnv().ENVIRONMENT).toBe('development');
+  });
+
   it('a build or a dev server never parses the env', () => {
     process.env = { ...process.env, ...SERVER, NEXT_PHASE: 'phase-production-build' };
     delete process.env.DATABASE_URL;
diff --git a/apps/api/tests/config.test.ts b/apps/api/tests/config.test.ts
index a78ce9af..394d7618 100644
--- a/apps/api/tests/config.test.ts
+++ b/apps/api/tests/config.test.ts
@@ -280,6 +280,7 @@ describe('apps/auth config', () => {
     }
     setAuthEnv();
     process.env.NODE_ENV = 'production';
+    process.env.ENVIRONMENT = 'staging'; // required in production too (#314 Amendment 3)
     resetEnvCache();
     expect(() => getEnv()).not.toThrow();
   });
diff --git a/apps/api/tests/cutover-docs.test.ts b/apps/api/tests/cutover-docs.test.ts
index ee90ab80..f8c8031d 100644
--- a/apps/api/tests/cutover-docs.test.ts
+++ b/apps/api/tests/cutover-docs.test.ts
@@ -543,7 +543,9 @@ describe('the service-keys runbook (spec 329)', () => {
 
   it('gives exactly the secret-scanning patterns the code defines, and where the owner registers them', () => {
     const scanning = section('Secret scanning');
-    const rows = [...scanning.matchAll(/^\| `([a-z-]+)` \| `([^`]+)` \|$/gm)].map((m) => [m[1], m[2]]);
+    // A `|` inside a GFM table cell must be written `\|` (even in code), or it splits the cell;
+    // the owner copies the rendered text, so the escape is undone before comparing.
+    const rows = [...scanning.matchAll(/^\| `([a-z-]+)` \| `([^`]+)` \|$/gm)].map((m) => [m[1], m[2]?.replace(/\\\|/g, '|')]);
     expect(rows).toEqual(Object.entries(serviceUsers.SECRET_SCANNING_PATTERNS).map(([name, re]) => [name, re.source]));
     expect(scanning).toContain('Settings → Code security → Secret scanning → Custom patterns');
     expect(scanning).toMatch(/\*\*revoke the key at once\*\*/);
diff --git a/apps/api/tests/helpers/mcp-key.ts b/apps/api/tests/helpers/mcp-key.ts
index 4a7ddccc..cdb2475d 100644
--- a/apps/api/tests/helpers/mcp-key.ts
+++ b/apps/api/tests/helpers/mcp-key.ts
@@ -24,7 +24,7 @@ export const MCP_TEST_LAYER_ORIGIN = 'https://api.mcp-key-test.example';
 export const MCP_TEST_CLIENT_ID = 'ansari-mcp-test';
 export const MCP_TEST_KEY_ID = 'key-00000000-0000-4000-8000-000000000314';
 /** A key in the issued shape: the public prefix and 64 random letters. */
-export const MCP_TEST_KEY = `ansari_mcp_${'kQ'.repeat(32)}`;
+export const MCP_TEST_KEY = `ansari_mcp_prod_${'kQ'.repeat(32)}`;
 
 const VERIFY_PATH = '/api/service/verify-key';
 
diff --git a/apps/api/tests/mcp-complete-key.test.ts b/apps/api/tests/mcp-complete-key.test.ts
index f850f1bc..05f46167 100644
--- a/apps/api/tests/mcp-complete-key.test.ts
+++ b/apps/api/tests/mcp-complete-key.test.ts
@@ -64,7 +64,7 @@ const AUTH_URL = 'https://auth.mcp-gate-test.example';
 const VERIFY_URL = `${AUTH_URL}${SERVICE_VERIFY_PATH}`;
 const KEY_CLIENT = 'ansari-mcp-production';
 const KEY_ID = '7d0c2f4e-5b1a-4c3d-9e8f-0a1b2c3d4e5f';
-const PREFIX = 'ansari_mcp_';
+const PREFIX = 'ansari_mcp_prod_';
 const LEAK_WINDOW = 16;
 
 /** A key in the issued shape: the public prefix and 64 random letters, fresh per run. */
diff --git a/apps/auth/.env.ci b/apps/auth/.env.ci
index 7249123a..07ec761a 100644
--- a/apps/auth/.env.ci
+++ b/apps/auth/.env.ci
@@ -16,3 +16,6 @@ RESEND_API_KEY=re_placeholder-not-a-real-key
 FRONTEND_URL=http://localhost:8081
 PORT=3100
 NODE_ENV=test
+
+# The deployment label (#314 Amendment 3).
+ENVIRONMENT=development
diff --git a/apps/auth/.env.example b/apps/auth/.env.example
index 311e2a13..a107087f 100644
--- a/apps/auth/.env.example
+++ b/apps/auth/.env.example
@@ -33,3 +33,8 @@ FRONTEND_URL=http://localhost:8081
 
 # The one listener. apps/api reaches it here too (its AUTH_URL).
 PORT=3100
+
+# The deployment label (#314 Amendment 3): development, staging or production. The Sentry
+# environment and the service-key prefix environment. Required, and staging or production,
+# when NODE_ENV=production; development otherwise.
+ENVIRONMENT=development
diff --git a/apps/auth/scripts/probes/service-keys-demo.ts b/apps/auth/scripts/probes/service-keys-demo.ts
index 57f3f0dd..99b97e88 100644
--- a/apps/auth/scripts/probes/service-keys-demo.ts
+++ b/apps/auth/scripts/probes/service-keys-demo.ts
@@ -41,6 +41,7 @@ async function main(): Promise {
     console.log(`\n$ tsx scripts/service-keys.ts ${argv.join(' ')}`);
     const { lines, exitCode } = await serviceKeys(argv, {
       databaseUrl,
+      environment: 'development',
       connect: () => ({ db, auth }),
       recorder,
       print: (line) => console.log(line),
@@ -61,7 +62,7 @@ async function main(): Promise {
   await step(['create-service', 'whatsapp', '--confirm', 'whatsapp']);
   const shown = await step(['create-key', 'whatsapp', ...LIMITS, '--client-id', 'whatsapp-service']);
   const userId = idIn(shown, /^ {2}id {10}([0-9a-f-]{36})$/);
-  const first = idIn(await step(['create-key', 'whatsapp', ...LIMITS, '--client-id', 'whatsapp-service', '--confirm', userId]), /^Created key ([0-9a-f-]{36})/);
+  const first = idIn(await step(['create-key', 'whatsapp', ...LIMITS, '--client-id', 'whatsapp-service', '--confirm', userId]), /^Created \w+ key ([0-9a-f-]{36})/);
   await step(['list', 'whatsapp']);
   await step(['rotate', 'whatsapp', ...LIMITS, '--confirm', userId]);
   await step(['update-limits', 'whatsapp', '--key', first, '--rate-max', '120', '--rate-window', '60', '--daily', '6000', '--confirm', first]);
@@ -75,7 +76,7 @@ async function main(): Promise {
   const text = transcript.join('\n');
   const { username, password, pathname, protocol } = new URL(databaseUrl);
   const leaks = [databaseUrl, `${username}:${password}@`, `${pathname}`, `${protocol}//`].filter((s) => text.includes(s));
-  const keys = text.match(/ansari_wa_[A-Za-z]{64}/g) ?? [];
+  const keys = text.match(/ansari_wa_development_[A-Za-z]{64}/g) ?? [];
   console.log(`\nCHECK database printed as hostname:port only: ${leaks.length === 0 ? 'PASS' : `FAIL (${leaks.join(', ')})`}`);
   console.log(`CHECK two keys created, each printed once: ${keys.length === 2 && new Set(keys).size === 2 ? 'PASS' : `FAIL (${keys.length})`}`);
   process.exit(leaks.length === 0 && keys.length === 2 ? 0 : 1);
diff --git a/apps/auth/scripts/service-keys.ts b/apps/auth/scripts/service-keys.ts
index 35bda9f1..96e5d951 100644
--- a/apps/auth/scripts/service-keys.ts
+++ b/apps/auth/scripts/service-keys.ts
@@ -28,7 +28,12 @@
  * thread attribution apps/api stores for every request the key makes.
  *
  * - It prints the database as `hostname:port` only, never the URL.
- * - Permissions and the key prefix are fixed per service (SERVICES); limits are
+ * - The script reads `ENVIRONMENT` (development, staging or production; #314
+ *   Amendment 3) from its process env and refuses to run without it. It is
+ *   printed under the database line before anything connects, and a new key's
+ *   prefix carries it (`ansari___`); the routes refuse a
+ *   key labelled for another environment.
+ * - Permissions and the base key prefix are fixed per service (SERVICES); limits are
  *   required flags with no defaults, checked against limits.ts's bounds. The
  *   budget is daily and always refills: a budget without a refill deletes the
  *   key the first time it is exhausted. There is no expiry option: a key lives
@@ -46,6 +51,7 @@ import * as Sentry from '@sentry/node';
 import {
   createAuth,
   createDb,
+  ENVIRONMENTS,
   getEnv,
   isMcpClientId,
   limits,
@@ -53,8 +59,10 @@ import {
   serviceUsers,
   type Auth,
   type Db,
+  type Environment,
 } from '@ansari/auth';
 
+
 import { urlHostPort } from './url-host';
 
 type ServiceName = serviceUsers.ServiceName;
@@ -78,8 +86,16 @@ export const USAGE = [
   '       tsx scripts/service-keys.ts update-limits  --key  --rate-max  --rate-window  --daily  [--confirm ]',
   '       tsx scripts/service-keys.ts revoke  --key  [--confirm ]',
   `Services: ${Object.keys(serviceUsers.SERVICES).join(', ')}`,
+  `ENVIRONMENT (${ENVIRONMENTS.join(', ')}) must be set, as on the auth service: a new key's prefix carries it`,
+  '(ansari___), and each environment\'s routes refuse a key labelled for another. Check it against the',
+  'database line before --confirm.',
 ].join('\n');
 
+/** The refusal when ENVIRONMENT is absent or not one of ENVIRONMENTS: fixed words, never the value. */
+export const ENVIRONMENT_RULE = `ENVIRONMENT is not set to one of ${ENVIRONMENTS.join(', ')} (set it as on the auth service). Refusing to run.`;
+
+const isEnvironment = (value: string): value is Environment => (ENVIRONMENTS as readonly string[]).includes(value);
+
 /** The exit code of a run that wrote nothing on purpose (show step, confirm mismatch). */
 export const EXIT_NOTHING_WRITTEN = 2;
 /** The exit code of a write whose Sentry record could not be sent. */
@@ -142,7 +158,6 @@ function limitsFrom(flags: Map): KeyLimits {
   };
 }
 
-/** Parses the command line; throws RefusedError with the reason when it is not a valid command. */
 /** A key name or client id: printed by list and sent to Sentry, so a bounded, inert charset. */
 const LABEL = /^[A-Za-z0-9 ._-]{1,64}$/;
 
@@ -273,7 +288,8 @@ export type KeyEvent = {
 
 export type ScriptResult = { lines: string[]; exitCode: number; events: KeyEvent[] };
 
-export type ScriptContext = { db: Db; auth: Auth; now?: Date };
+/** `environment` is the validated ENVIRONMENT: a new key's prefix names it. */
+export type ScriptContext = { db: Db; auth: Auth; environment: Environment; now?: Date };
 
 const describeLimits = (l: {
   rateLimitMax: number | null;
@@ -343,7 +359,8 @@ async function createKey(
   flags: KeyFlags
 ): Promise<{ id: string; key: string; name: string }> {
   const checked = checkKeyLimits(service, flags.limits);
-  const { permissions, prefix } = serviceUsers.SERVICES[service];
+  const { permissions } = serviceUsers.SERVICES[service];
+  const prefix = serviceUsers.keyPrefix(service, ctx.environment);
   // Default name: the service and the minute it was created, so a rotation's two keys differ.
   const name = flags.name ?? `${service} ${(ctx.now ?? new Date()).toISOString().slice(0, 16)}Z`;
   const created = await ctx.auth.api.createApiKey({
@@ -430,7 +447,8 @@ export async function runServiceKeys(ctx: ScriptContext, cmd: ServiceKeysCommand
         ...userLines(cmd.service, user),
         `${live.length} live key(s): ${live.map((k) => k.id).join(', ') || 'none'}`,
         `This would create a key with ${describeLimits(cmd.limits)}.`,
-        'Nothing was written. If this is the service you mean, run:',
+        `  environment ${ctx.environment} (prefix ${serviceUsers.keyPrefix(cmd.service, ctx.environment)})`,
+        'Nothing was written. If this is the service and environment you mean, run:',
         command(`${cmd.kind} ${cmd.service} ${flagsText(cmd.limits)}${extra ? ` ${extra}` : ''} --confirm ${user.id}`),
       ]);
     }
@@ -447,7 +465,7 @@ export async function runServiceKeys(ctx: ScriptContext, cmd: ServiceKeysCommand
         : [];
     return {
       lines: [
-        `Created key ${created.id} (${created.name}) for ${cmd.service}: ${describeLimits(cmd.limits)}.`,
+        `Created ${ctx.environment} key ${created.id} (${created.name}) for ${cmd.service}: ${describeLimits(cmd.limits)}.`,
         ...rawKeyLines(created.key),
         ...rotated,
       ],
@@ -566,7 +584,9 @@ export function scriptError(err: unknown): string {
 
 export type ScriptDeps = {
   databaseUrl: string | undefined;
-  connect: () => ScriptContext;
+  /** ENVIRONMENT as the process has it, unvalidated: the script refuses an absent or unknown value. */
+  environment: string | undefined;
+  connect: () => Omit;
   recorder: Recorder;
   /** Prints one line at once (console.log in the script). */
   print: (line: string) => void;
@@ -597,10 +617,16 @@ export async function serviceKeys(argv: readonly string[], deps: ScriptDeps): Pr
     return { lines, exitCode: 1 };
   }
   emit(`Auth database: ${host}`);
+  const environment = deps.environment;
+  if (environment === undefined || !isEnvironment(environment)) {
+    emit(ENVIRONMENT_RULE);
+    return { lines, exitCode: 1 };
+  }
+  emit(`Environment: ${environment} (a new key's prefix carries it: ansari__${environment}_)`);
   let result: ScriptResult;
   try {
     const cmd = parseArgs(argv);
-    result = await runServiceKeys(deps.connect(), cmd);
+    result = await runServiceKeys({ ...deps.connect(), environment }, cmd);
   } catch (err) {
     emit(`service-keys refused: ${scriptError(err)}`);
     return { lines, exitCode: 1 };
@@ -641,6 +667,7 @@ async function main(): Promise {
   const recorder = scriptRecorder(process.env.SENTRY_DSN);
   const { exitCode } = await serviceKeys(process.argv.slice(2), {
     databaseUrl: process.env.DATABASE_URL,
+    environment: process.env.ENVIRONMENT,
     connect: () => {
       try {
         getEnv();
diff --git a/apps/auth/src/app.ts b/apps/auth/src/app.ts
index 7843f29a..2167269b 100644
--- a/apps/auth/src/app.ts
+++ b/apps/auth/src/app.ts
@@ -7,7 +7,7 @@
 //   /api/whatsapp/session  the WhatsApp token exchange, bound to a service key
 //   /api/service/verify-key  the MCP key verify route (#314), for apps/api
 //   /health and the diag route
-import { createAuth, getEnv, type Auth, type Db, type Mailer } from '@ansari/auth';
+import { createAuth, getEnv, type Auth, type Db, type Environment, type Mailer } from '@ansari/auth';
 import { toNodeHandler } from 'better-auth/node';
 import express, { type Express, type Request, type Response } from 'express';
 
@@ -30,6 +30,8 @@ export type AppOptions = {
   exchange?: ExchangeOptions;
   /** The MCP verify route's alerts and clock; the defaults in production. */
   verify?: VerifyOptions;
+  /** This deployment's ENVIRONMENT for both key routes (#314 Amendment 3); defaults to getEnv(). */
+  environment?: Environment;
 };
 
 const AUTH_ROUTE = '/api/auth{/*path}';
@@ -71,8 +73,9 @@ export function createApp({ auth, db }: ServiceDeps, options: AppOptions = {}):
   // OPTIONS itself, so a route after it would get CORS for the configured
   // origin. Each router answers every request to its path, so nothing reaches
   // corsFor; a browser can never read a response from either.
-  app.use(WHATSAPP_SESSION_PATH, whatsappRouter({ auth, db }, options.exchange));
-  app.use(SERVICE_VERIFY_PATH, serviceVerifyRouter({ auth, db }, options.verify));
+  const environment = options.environment;
+  app.use(WHATSAPP_SESSION_PATH, whatsappRouter({ auth, db }, { ...options.exchange, ...(environment && { environment }) }));
+  app.use(SERVICE_VERIFY_PATH, serviceVerifyRouter({ auth, db }, { ...options.verify, ...(environment && { environment }) }));
   app.use(corsFor(getEnv().CORS_ORIGIN));
   app.use(mergeExposedHeaders);
   app.use(blockedPaths);
diff --git a/apps/auth/src/index.ts b/apps/auth/src/index.ts
index 2d4aa069..05611425 100644
--- a/apps/auth/src/index.ts
+++ b/apps/auth/src/index.ts
@@ -11,7 +11,7 @@ import { createApp, createServiceAuth } from './app';
 import { assertSchema } from './boot';
 
 const env = getEnv();
-initSentry(env.SENTRY_DSN, env.NODE_ENV);
+initSentry(env.SENTRY_DSN, env.ENVIRONMENT);
 
 // No admin check at boot (owner amendment 2026-10-17): admin is the role in
 // auth.users alone, granted by scripts/grant-admin.ts, and the window audits it
diff --git a/apps/auth/src/routes/service-verify.ts b/apps/auth/src/routes/service-verify.ts
index 3dfbb694..1123e615 100644
--- a/apps/auth/src/routes/service-verify.ts
+++ b/apps/auth/src/routes/service-verify.ts
@@ -25,7 +25,7 @@
 // so no response carries an `Access-Control-*` header. It is outside Better
 // Auth's handler path, so no router per-IP rule applies: apps/api calls from
 // its egress IP.
-import { isMcpClientId, limits, redactError, serviceUsers } from '@ansari/auth';
+import { getEnv, isMcpClientId, limits, redactError, serviceUsers, type Environment } from '@ansari/auth';
 import express, { Router, type NextFunction, type Request, type Response } from 'express';
 
 import { createMcpVerifyAlerts, type KeyRefusalCode, type McpVerifyAlerts } from '../alerts';
@@ -44,6 +44,11 @@ const KEY = new RegExp(`^[\\x21-\\x7E]{1,${limits.VERIFY_KEY_MAX_LENGTH}}$`);
 const KEY_REFUSAL_CODES: readonly string[] = ['USAGE_EXCEEDED', 'RATE_LIMITED'] satisfies KeyRefusalCode[];
 
 export type VerifyOptions = {
+  /**
+   * This deployment's ENVIRONMENT (#314 Amendment 3): only a key whose stored
+   * prefix names it (or the legacy bare prefix) is served. Defaults to getEnv().
+   */
+  environment?: Environment;
   alerts?: McpVerifyAlerts;
   /** The clock for the relation-check cache; tests advance it. */
   now?: () => number;
@@ -79,6 +84,7 @@ const internalError = (res: Response) => res.status(500).json({ message: 'Intern
 export function serviceVerifyRouter({ auth, db }: ServiceDeps, options: VerifyOptions = {}): Router {
   const alerts = options.alerts ?? createMcpVerifyAlerts();
   const checkApiKeyRelation = createApiKeyRelationCheck(db, options.now ?? Date.now);
+  const environment = options.environment ?? getEnv().ENVIRONMENT;
   const permissions = { [SERVED_RESOURCE]: [...SERVED_ACTIONS] };
   const router = Router();
 
@@ -128,6 +134,11 @@ export function serviceVerifyRouter({ auth, db }: ServiceDeps, options: VerifyOp
         return fail(res, new Error('ansari-mcp service user unresolvable'));
       }
       if (verified.key.referenceId !== owner.user.id) return refuse(res);
+      // A key whose stored prefix is not this service's and this environment's
+      // (another environment's label, another service's, a hand-made one) is
+      // the same refusal (#314 Amendment 3). The legacy bare prefix is accepted
+      // while serviceUsers.LEGACY_UNLABELLED_KEYS holds.
+      if (!serviceUsers.isAcceptedKeyPrefix(SERVICE, environment, verified.key.prefix)) return refuse(res);
 
       const clientId = serviceUsers.clientIdOf(verified.key.metadata);
       if (clientId === null || !isMcpClientId(clientId)) {
diff --git a/apps/auth/src/routes/whatsapp.ts b/apps/auth/src/routes/whatsapp.ts
index 39795005..7d8b37aa 100644
--- a/apps/auth/src/routes/whatsapp.ts
+++ b/apps/auth/src/routes/whatsapp.ts
@@ -26,7 +26,7 @@
 // Better Auth's handler path, so no router per-IP rule applies: the WhatsApp
 // service calls from one egress IP, and the key's own limits and the per-user
 // budget are the throttle.
-import { consumeWindow, limits, redactError, serviceUsers, whatsapp } from '@ansari/auth';
+import { consumeWindow, limits, redactError, getEnv, serviceUsers, whatsapp, type Environment } from '@ansari/auth';
 import express, { Router, type NextFunction, type Request, type Response } from 'express';
 
 import {
@@ -54,6 +54,11 @@ const BSUID = /^[^\s\p{Cc}\p{Cf}]{1,256}$/u;
 export const exchangeLimitKey = (userId: string) => `sub:${userId}|${WHATSAPP_SESSION_PATH}`;
 
 export type ExchangeOptions = {
+  /**
+   * This deployment's ENVIRONMENT (#314 Amendment 3): only a key whose stored
+   * prefix names it (or the legacy bare prefix) is served. Defaults to getEnv().
+   */
+  environment?: Environment;
   alerts?: ExchangeAlerts;
   /** The clock for the relation-check cache; tests advance it. */
   now?: () => number;
@@ -90,6 +95,7 @@ const internalError = (res: Response) => res.status(500).json({ message: 'Intern
 export function whatsappRouter({ auth, db }: ServiceDeps, options: ExchangeOptions = {}): Router {
   const alerts = options.alerts ?? createExchangeAlerts();
   const now = options.now ?? Date.now;
+  const environment = options.environment ?? getEnv().ENVIRONMENT;
   const router = Router();
 
   const checkApiKeyRelation = createApiKeyRelationCheck(db, now);
@@ -125,6 +131,11 @@ export function whatsappRouter({ auth, db }: ServiceDeps, options: ExchangeOptio
         return fail(res, new Error('whatsapp service user unresolvable'));
       }
       if (verified.key.referenceId !== owner.user.id) return refuse(res);
+      // A key whose stored prefix is not this service's and this environment's
+      // (another environment's label, another service's, a hand-made one) is
+      // the same refusal (#314 Amendment 3). The legacy bare prefix is accepted
+      // while serviceUsers.LEGACY_UNLABELLED_KEYS holds.
+      if (!serviceUsers.isAcceptedKeyPrefix(SERVICE, environment, verified.key.prefix)) return refuse(res);
       next();
     } catch (err) {
       fail(res, err);
diff --git a/apps/auth/tests/environment.test.ts b/apps/auth/tests/environment.test.ts
new file mode 100644
index 00000000..b7d4acad
--- /dev/null
+++ b/apps/auth/tests/environment.test.ts
@@ -0,0 +1,78 @@
+// ENVIRONMENT (#314 Amendment 3, owner 2026-11-12): the deployment label, the
+// Sentry environment and the service-key prefix's environment. Under
+// NODE_ENV=production it is required and must be staging or production, so a
+// deployed apps/auth without it refuses to boot (src/index.ts calls getEnv()
+// before anything else) and names the variable, never a value. Outside
+// production it defaults to development. Nothing reads it at build time: the
+// image build runs tsc/tsdown, which never executes getEnv().
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+import { envSchema, getEnv, resetEnvCache } from '@ansari/auth/env';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+const COMPLETE = {
+  DATABASE_URL: 'postgres://u:p@localhost:5432/auth',
+  BETTER_AUTH_SECRET: 'x'.repeat(32),
+  BETTER_AUTH_URL: 'https://auth.example.test',
+  CORS_ORIGIN: 'https://app.example.test',
+  AUTH_LAYER_ORIGIN: 'https://api.example.test',
+  AUTH_JWT_ISSUER: 'https://auth.example.test',
+  AUTH_JWT_AUDIENCE: 'ansari-api',
+  RESEND_API_KEY: 'r'.repeat(20),
+  FRONTEND_URL: 'https://app.example.test',
+};
+
+const issuesOf = (env: Record) => {
+  const result = envSchema.safeParse(env);
+  return result.success ? [] : result.error.issues.map((i) => String(i.path[0]));
+};
+
+describe('ENVIRONMENT in the schema', () => {
+  it.each([[undefined], ['development'], ['prod'], ['test']])(
+    'NODE_ENV=production with ENVIRONMENT %j is refused, on ENVIRONMENT only',
+    (environment) => {
+      expect(issuesOf({ ...COMPLETE, NODE_ENV: 'production', ENVIRONMENT: environment })).toEqual(['ENVIRONMENT']);
+    }
+  );
+
+  it.each([['staging'], ['production']])('NODE_ENV=production with ENVIRONMENT=%s parses', (environment) => {
+    const result = envSchema.safeParse({ ...COMPLETE, NODE_ENV: 'production', ENVIRONMENT: environment });
+    expect(result.success && result.data.ENVIRONMENT).toBe(environment);
+  });
+
+  it.each([['development'], ['test'], [undefined]])('NODE_ENV=%s without ENVIRONMENT is development', (nodeEnv) => {
+    const result = envSchema.safeParse({ ...COMPLETE, NODE_ENV: nodeEnv });
+    expect(result.success && result.data.ENVIRONMENT).toBe('development');
+  });
+});
+
+describe('the boot path (getEnv, first call in src/index.ts)', () => {
+  let saved: NodeJS.ProcessEnv;
+  beforeEach(() => {
+    saved = { ...process.env };
+    resetEnvCache();
+  });
+  afterEach(() => {
+    process.env = saved;
+    resetEnvCache();
+  });
+
+  it('refuses a production boot without ENVIRONMENT, naming it and no value', () => {
+    process.env = { ...process.env, ...COMPLETE, NODE_ENV: 'production' };
+    delete process.env.ENVIRONMENT;
+    expect(() => getEnv()).toThrow(/env validation failed for: ENVIRONMENT\./);
+    try {
+      getEnv();
+    } catch (err) {
+      expect(String(err)).not.toContain(COMPLETE.BETTER_AUTH_SECRET);
+    }
+  });
+
+  it('boots with ENVIRONMENT=staging, and the value reaches Sentry init', () => {
+    process.env = { ...process.env, ...COMPLETE, NODE_ENV: 'production', ENVIRONMENT: 'staging' };
+    expect(getEnv().ENVIRONMENT).toBe('staging');
+    const index = readFileSync(fileURLToPath(new URL('../src/index.ts', import.meta.url)), 'utf8');
+    expect(index).toContain('initSentry(env.SENTRY_DSN, env.ENVIRONMENT);');
+  });
+});
diff --git a/apps/auth/tests/helpers/leak-scan.ts b/apps/auth/tests/helpers/leak-scan.ts
index 3f396027..1fff4d70 100644
--- a/apps/auth/tests/helpers/leak-scan.ts
+++ b/apps/auth/tests/helpers/leak-scan.ts
@@ -1,15 +1,18 @@
 // The key-material scan (#314): a raw key, or any 16-character window of its
-// random part, in some text. The public prefix (`ansari_mcp_`, stored in
+// random part, in some text. The public prefix (`ansari_mcp__`, stored in
 // `apikey.prefix` and published as the secret-scanning pattern) is exempt, so
 // the scan never keys on it. Negative-tested in service-verify.test.ts against
 // a known-bad line and the bare prefix (a verification pattern is code).
-import { serviceUsers } from '@ansari/auth';
+import { ENVIRONMENTS, serviceUsers } from '@ansari/auth';
 
 export const LEAK_WINDOW = 16;
 
-const PREFIXES = Object.values(serviceUsers.SERVICES).map((s) => s.prefix);
+// Longest first, so `ansari_mcp_staging_` is stripped whole, never just `ansari_mcp_`.
+const PREFIXES = (Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[])
+  .flatMap((name) => [serviceUsers.SERVICES[name].prefix, ...ENVIRONMENTS.map((env) => serviceUsers.keyPrefix(name, env))])
+  .sort((a, b) => b.length - a.length);
 
-/** Every 16-character window of the key's random part (the part after its service prefix). */
+/** Every 16-character window of the key's random part (the part after its prefix, environment included). */
 export function keyWindows(key: string): string[] {
   const prefix = PREFIXES.find((p) => key.startsWith(p)) ?? '';
   const random = key.slice(prefix.length);
diff --git a/apps/auth/tests/helpers/service.ts b/apps/auth/tests/helpers/service.ts
index ec0a075b..8c89edd5 100644
--- a/apps/auth/tests/helpers/service.ts
+++ b/apps/auth/tests/helpers/service.ts
@@ -58,6 +58,12 @@ function listen(app: { listen: (port: number, cb: () => void) => Server }): Prom
 
 const urlOf = (server: Server) => `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
 
+/** Serves another app (e.g. over the same db with other options) on an ephemeral port; close it when done. */
+export async function serveApp(app: { listen: (port: number, cb: () => void) => Server }): Promise<{ url: string; close: () => Promise }> {
+  const server = await listen(app);
+  return { url: urlOf(server), close: () => new Promise((resolve) => server.close(() => resolve())) };
+}
+
 export async function startService(options: ServiceOptions = {}): Promise {
   setAuthEnv(BASE);
   const client = await migrate();
diff --git a/apps/auth/tests/service-keys-no-dsn.test.ts b/apps/auth/tests/service-keys-no-dsn.test.ts
index 6f830aff..d1f88f20 100644
--- a/apps/auth/tests/service-keys-no-dsn.test.ts
+++ b/apps/auth/tests/service-keys-no-dsn.test.ts
@@ -21,6 +21,7 @@ async function run(argv: string[], recorder: ReturnType)
   const lines: string[] = [];
   const result = await serviceKeys(argv, {
     databaseUrl: 'postgres://db.example:6543/auth',
+    environment: 'staging',
     connect: () => ({ db: service.db, auth: service.auth }),
     recorder,
     print: (line) => lines.push(line),
@@ -46,7 +47,7 @@ it('no DSN: nothing is captured or flushed; the write stands, the banner names t
     recorder
   );
   expect(keyed.exitCode, keyed.text).toBe(EXIT_UNRECORDED);
-  const keyId = /Created key ([0-9a-f-]{36})/.exec(keyed.text)![1]!;
+  const keyId = /Created \w+ key ([0-9a-f-]{36})/.exec(keyed.text)![1]!;
   const banner = keyed.text.slice(keyed.text.indexOf('THE SENTRY RECORD'));
   expect(banner).toContain('SENTRY_DSN is not set: no record was attempted.');
   expect(banner).toContain(`key ${keyId}`);
diff --git a/apps/auth/tests/service-keys-sentry.test.ts b/apps/auth/tests/service-keys-sentry.test.ts
index a0ac7c73..35dfc6a0 100644
--- a/apps/auth/tests/service-keys-sentry.test.ts
+++ b/apps/auth/tests/service-keys-sentry.test.ts
@@ -53,12 +53,13 @@ beforeEach(() => {
 async function createKey(print: (line: string) => void) {
   const result = await serviceKeys(['create-key', 'whatsapp', ...LIMIT_FLAGS, '--confirm', userId], {
     databaseUrl: DB_URL,
+    environment: 'staging',
     connect: () => ({ db: service.db, auth: service.auth }),
     recorder: sentryRecorder,
     print,
   });
   expect(result.exitCode).toBe(0);
-  const key = result.lines.find((l) => /^ansari_wa_[A-Za-z]{64}$/.test(l));
+  const key = result.lines.find((l) => /^ansari_wa_staging_[A-Za-z]{64}$/.test(l));
   if (!key) throw new Error('no key in the output');
   return key;
 }
diff --git a/apps/auth/tests/service-keys.test.ts b/apps/auth/tests/service-keys.test.ts
index cebe6b4b..2edf974b 100644
--- a/apps/auth/tests/service-keys.test.ts
+++ b/apps/auth/tests/service-keys.test.ts
@@ -7,13 +7,14 @@ import { createHash } from 'node:crypto';
 import * as Sentry from '@sentry/node';
 import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
 
-import { limits, serviceUsers } from '@ansari/auth';
+import { ENVIRONMENTS, limits, serviceUsers } from '@ansari/auth';
 
 import {
   checkKeyLimits,
   EXIT_NOTHING_WRITTEN,
   EXIT_UNRECORDED,
   KEY_EVENT_MESSAGE,
+  ENVIRONMENT_RULE,
   MCP_CLIENT_ID_RULE,
   parseArgs,
   RefusedError,
@@ -36,7 +37,7 @@ const DB_URL_DISTINCT = 'postgres://opsname-zq:pw-zq-9@db.example:6543/authdb-zq
 
 const INITIAL = limits.WHATSAPP_KEY_INITIAL;
 const LIMIT_FLAGS = ['--rate-max', '60', '--rate-window', '60', '--daily', '3000'];
-const WA_KEY = /ansari_wa_[A-Za-z]{64}/g;
+const WA_KEY = /ansari_wa_staging_[A-Za-z]{64}/g;
 /** An ansari-mcp key's flags: its initial limits and the client id it must carry (#314). */
 const MCP_INITIAL = limits.MCP_KEY_INITIAL;
 const MCP_FLAGS = [
@@ -76,13 +77,17 @@ function memoryRecorder(flushed = true): Recorder & { events: KeyEvent[]; flushe
   };
 }
 
-type RunOptions = { url?: string | undefined; recorder?: Recorder; flushTimeoutMs?: number };
+type RunOptions = { url?: string | undefined; environment?: string | undefined; recorder?: Recorder; flushTimeoutMs?: number };
+
+/** The ENVIRONMENT these tests run the script under, unless a test says otherwise. */
+const SCRIPT_ENVIRONMENT = 'staging';
 
 async function run(argv: string[], opts: RunOptions = {}) {
   const connect = vi.fn(() => ({ db: service.db, auth: service.auth }));
   const print = vi.fn<(line: string) => void>();
   const result = await serviceKeys(argv, {
     databaseUrl: 'url' in opts ? opts.url : DB_URL,
+    environment: 'environment' in opts ? opts.environment : SCRIPT_ENVIRONMENT,
     connect,
     recorder: opts.recorder ?? memoryRecorder(),
     print,
@@ -110,7 +115,7 @@ async function createKey(kind: 'create-key' | 'rotate' = 'create-key', flags = L
   expect(result.exitCode, result.text).toBe(0);
   const prefix = serviceUsers.SERVICES[name as serviceUsers.ServiceName].prefix;
   const key = result.lines.find((l) => l.startsWith(prefix) && l.length > prefix.length + 60);
-  const id = /Created key ([0-9a-f-]{36})/.exec(result.text)?.[1];
+  const id = /Created \w+ key ([0-9a-f-]{36})/.exec(result.text)?.[1];
   if (!key || !id) throw new Error('no key in the output');
   return { ...result, key, id, userId };
 }
@@ -317,7 +322,7 @@ describe('every subcommand', () => {
     const userId = await createService();
     const first = await createKey();
     if (name === 'create-key') {
-      expect(first.text).toContain(`Created key ${first.id}`);
+      expect(first.text).toContain(`Created staging key ${first.id}`);
       return;
     }
     const argv =
@@ -330,7 +335,7 @@ describe('every subcommand', () => {
     const { text, exitCode } = await run([...argv, '--confirm', confirm]);
     expect(exitCode).toBe(0);
     expect(text).toContain(first.id);
-    if (name === 'rotate') expect(text).toMatch(/Created key [0-9a-f-]{36}/);
+    if (name === 'rotate') expect(text).toMatch(/Created staging key [0-9a-f-]{36}/);
   });
 });
 
@@ -521,7 +526,7 @@ describe('create-key', () => {
     expect(text).not.toContain(row!.key as string);
     expect(row).toMatchObject({
       reference_id: userId,
-      prefix: 'ansari_wa_',
+      prefix: 'ansari_wa_staging_',
       start: null,
       enabled: true,
       rate_limit_enabled: true,
@@ -595,7 +600,7 @@ describe('ansari-mcp keys: the client id (#314, scenario 14)', () => {
     for (const clientId of [null, 'claude-skill']) {
       await expect(
         runServiceKeys(
-          { db: service.db, auth: service.auth },
+          { db: service.db, auth: service.auth, environment: 'staging' },
           { kind: 'create-key', service: 'ansari-mcp', confirm: userId, limits: MCP_INITIAL, name: null, clientId }
         )
       ).rejects.toBeInstanceOf(RefusedError);
@@ -805,6 +810,84 @@ describe('SECRET_SCANNING_PATTERNS', () => {
     });
     expect(hits.filter(Boolean)).toHaveLength(2);
   });
+
+  it('the registered sources, derived from the prefix table (the runbook prints exactly these)', () => {
+    expect(serviceUsers.LEGACY_UNLABELLED_KEYS).toBe(true);
+    expect(serviceUsers.SECRET_SCANNING_PATTERNS.whatsapp.source).toBe(
+      'ansari_wa_(?:(?:development|staging|production)_)?[A-Za-z]{64}'
+    );
+    expect(serviceUsers.SECRET_SCANNING_PATTERNS['ansari-mcp'].source).toBe(
+      'ansari_mcp_(?:(?:development|staging|production)_)?[A-Za-z]{64}'
+    );
+  });
+
+  it('every labelled prefix and the legacy bare prefix are caught; an unknown environment is not', () => {
+    const body = 'Q'.repeat(64);
+    for (const name of Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[]) {
+      const pattern = serviceUsers.SECRET_SCANNING_PATTERNS[name];
+      const prefixes = [serviceUsers.SERVICES[name].prefix, ...ENVIRONMENTS.map((e) => serviceUsers.keyPrefix(name, e))];
+      for (const prefix of prefixes) expect(pattern.test(`${prefix}${body}`), prefix).toBe(true);
+      expect(pattern.test(`${serviceUsers.SERVICES[name].prefix}qa_${body}`)).toBe(false);
+    }
+  });
+
+  it('keyPrefix is ansari___ for every service and environment, all distinct', () => {
+    const all = (Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[]).flatMap((name) =>
+      ENVIRONMENTS.map((env) => serviceUsers.keyPrefix(name, env))
+    );
+    for (const prefix of all) expect(prefix).toMatch(/^ansari_[a-z]+_(development|staging|production)_$/);
+    expect(new Set(all).size).toBe(all.length);
+  });
+});
+
+describe('ENVIRONMENT (#314 Amendment 3)', () => {
+  it.each([[undefined], [''], ['prod'], ['live'], ['Production'], ['test']])(
+    'absent or not one of development, staging, production (%j) → refused before anything connects',
+    async (environment) => {
+      for (const argv of [['list', 'whatsapp'], ['create-key', 'whatsapp', ...LIMIT_FLAGS]]) {
+        const { exitCode, text, connect } = await run(argv, { environment });
+        expect(exitCode).toBe(1);
+        expect(text).toContain(ENVIRONMENT_RULE);
+        if (environment) expect(text.replace(ENVIRONMENT_RULE, '')).not.toContain(` ${environment} `);
+        expect(connect).not.toHaveBeenCalled();
+      }
+    }
+  );
+
+  it('--env is no longer an option: the environment comes from the process alone', () => {
+    expect(() => parseArgs(['create-key', 'whatsapp', '--env', 'production', ...LIMIT_FLAGS])).toThrow(/not an option/);
+  });
+
+  it.each(ENVIRONMENTS.map((environment) => [environment]))(
+    'under %s: printed under the database line, named with its prefix in the show step',
+    async (environment) => {
+      await createService();
+      const { exitCode, lines, text } = await run(['create-key', 'whatsapp', ...LIMIT_FLAGS], { environment });
+      expect(exitCode).toBe(2);
+      const at = lines.findIndex((l) => l.startsWith('Auth database: '));
+      expect(lines[at + 1]).toBe(`Environment: ${environment} (a new key's prefix carries it: ansari__${environment}_)`);
+      expect(text).toContain(`environment ${environment} (prefix ansari_wa_${environment}_)`);
+    }
+  );
+
+  it('a created key carries ENVIRONMENT in its prefix, the row and list', async () => {
+    const userId = await createService();
+    const result = await run(['create-key', 'whatsapp', ...LIMIT_FLAGS, '--confirm', userId], { environment: 'production' });
+    expect(result.exitCode, result.text).toBe(0);
+    expect(result.lines.some((l) => /^ansari_wa_production_[A-Za-z]{64}$/.test(l))).toBe(true);
+    const id = /Created production key ([0-9a-f-]{36})/.exec(result.text)?.[1];
+    expect((await keyRow(id!))!.prefix).toBe('ansari_wa_production_');
+    expect((await run(['list', 'whatsapp'])).text).toContain('prefix        ansari_wa_production_');
+  });
+
+  it('a pasted labelled key is refused in --name, without echoing it', async () => {
+    const userId = await createService();
+    const pasted = `ansari_wa_production_${'k'.repeat(40)}`; // within the 64-character label bound, so the key-shape check decides
+    const result = await run(['create-key', 'whatsapp', ...LIMIT_FLAGS, '--name', pasted, '--confirm', userId]);
+    expect(result.exitCode).toBe(1);
+    expect(result.text).toMatch(/looks like a key/);
+    expect(result.text).not.toContain(pasted);
+  });
 });
 
 describe('the durable record', () => {
@@ -839,12 +922,12 @@ describe('the durable record', () => {
       recorder: sentryRecorder,
     });
     const key1 = first.lines.find((l) => l.startsWith('ansari_wa_'))!;
-    const id1 = /Created key ([0-9a-f-]{36})/.exec(first.text)![1]!;
+    const id1 = /Created \w+ key ([0-9a-f-]{36})/.exec(first.text)![1]!;
     const rotated = await run(['rotate', 'whatsapp', ...LIMIT_FLAGS, '--name', 'wa-2', '--confirm', userId], {
       recorder: sentryRecorder,
     });
     const key2 = rotated.lines.find((l) => l.startsWith('ansari_wa_'))!;
-    const id2 = /Created key ([0-9a-f-]{36})/.exec(rotated.text)![1]!;
+    const id2 = /Created \w+ key ([0-9a-f-]{36})/.exec(rotated.text)![1]!;
     await run(['update-limits', 'whatsapp', '--key', id2, ...LIMIT_FLAGS, '--confirm', id2], { recorder: sentryRecorder });
     await run(['revoke', 'whatsapp', '--key', id1, '--confirm', id1], { recorder: sentryRecorder });
     await run(['list', 'whatsapp'], { recorder: sentryRecorder });
@@ -902,7 +985,7 @@ describe('the durable record', () => {
     expect(exitCode).not.toBe(0);
     expect(text).toMatch(/SENTRY RECORD OF THIS ACTION WAS NOT SENT/);
     expect(text).toMatch(/runbook's key log/);
-    const id = /Created key ([0-9a-f-]{36})/.exec(text)![1]!;
+    const id = /Created \w+ key ([0-9a-f-]{36})/.exec(text)![1]!;
     expect(text).toMatch(new RegExp(`action create-key, service whatsapp, user ${userId}, key ${id}`));
     // The write stands, and the key was still shown once (it is not stored anywhere else).
     expect(await keyRow(id)).toMatchObject({ enabled: true });
diff --git a/apps/auth/tests/service-verify.test.ts b/apps/auth/tests/service-verify.test.ts
index ef4e4c37..4d81d806 100644
--- a/apps/auth/tests/service-verify.test.ts
+++ b/apps/auth/tests/service-verify.test.ts
@@ -10,7 +10,7 @@ import { inspect } from 'node:util';
 
 import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
 
-import { limits, serviceUsers } from '@ansari/auth';
+import { ENVIRONMENTS, getEnv, limits, serviceUsers } from '@ansari/auth';
 
 import { createMcpVerifyAlerts, EXCHANGE_ALERT_MESSAGE, MCP_VERIFY_ALERT_MESSAGE, type McpVerifyAlert } from '../src/alerts';
 import { createApp } from '../src/app';
@@ -18,7 +18,7 @@ import { SERVICE_VERIFY_PATH } from '../src/routes/service-verify';
 import { WHATSAPP_SESSION_PATH } from '../src/routes/whatsapp';
 import { parseArgs, runServiceKeys } from '../scripts/service-keys';
 import { keyWindows, leakedWindows } from './helpers/leak-scan';
-import { BASE, signUpTokens, startService, type Service } from './helpers/service';
+import { BASE, serveApp, signUpTokens, startService, type Service } from './helpers/service';
 
 const MCP = { mcp: ['complete'] };
 
@@ -83,11 +83,13 @@ async function serviceUserOf(on: Service, name: ServiceName): Promise {
 /** A key made by the service-keys script's create-key, as an operator would; returns the raw key and its id. */
 async function scriptKey(name: ServiceName = 'ansari-mcp', on: Service = service, flags = LIMIT_FLAGS[name]) {
   const userId = await serviceUserOf(on, name);
-  const result = await runServiceKeys({ db: on.db, auth: on.auth }, parseArgs(['create-key', name, ...flags, '--confirm', userId]));
+  // The script issues under the same ENVIRONMENT the app under test serves (getEnv(): development here).
+  const environment = getEnv().ENVIRONMENT;
+  const result = await runServiceKeys({ db: on.db, auth: on.auth, environment }, parseArgs(['create-key', name, ...flags, '--confirm', userId]));
   expect(result.exitCode).toBe(0);
-  const { prefix } = serviceUsers.SERVICES[name];
+  const prefix = serviceUsers.keyPrefix(name, environment);
   const raw = result.lines.find((l) => l.startsWith(prefix) && l.length > prefix.length + 60);
-  const id = /Created key ([0-9a-f-]{36})/.exec(result.lines.join('\n'))?.[1];
+  const id = /Created \w+ key ([0-9a-f-]{36})/.exec(result.lines.join('\n'))?.[1];
   if (!raw || !id) throw new Error('no key in the script output');
   return { key: remember(raw), id };
 }
@@ -351,6 +353,63 @@ describe('the owner and the client id', () => {
   });
 });
 
+describe('the stored prefix (#314 Amendments 2 and 3)', () => {
+  const served = { metadata: { clientId: 'ansari-mcp-production' } };
+  const here = getEnv().ENVIRONMENT;
+
+  it.each([
+    ["this environment's label", serviceUsers.keyPrefix('ansari-mcp', here)],
+    ['the legacy bare prefix (compatibility window)', 'ansari_mcp_'],
+  ])('%s → served', async (_name, prefix) => {
+    const made = await outsideKey(mcpUserId, { ...served, prefix });
+    expect(made.key.startsWith(prefix)).toBe(true);
+    expect(JSON.parse((await verify(made.key)).text)).toEqual({
+      valid: true,
+      client_id: 'ansari-mcp-production',
+      key_id: made.id,
+    });
+  });
+
+  it('the longest prefix the table produces fits the plugin (created with it, not a cited limit)', async () => {
+    const all = (Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[]).flatMap((name) =>
+      ENVIRONMENTS.map((env) => serviceUsers.keyPrefix(name, env))
+    );
+    const longest = all.reduce((a, b) => (b.length > a.length ? b : a));
+    expect(longest).toBe('ansari_mcp_development_');
+    const made = await outsideKey(mcpUserId, { ...served, prefix: longest });
+    expect(made.key.startsWith(longest)).toBe(true);
+  });
+
+  it.each([
+    ...ENVIRONMENTS.filter((e) => e !== here).map((e) => [`another environment's label (${e})`, `ansari_mcp_${e}_`]),
+    ['a foreign prefix', 'evil_'],
+    ["a WhatsApp prefix for this environment", serviceUsers.keyPrefix('whatsapp', here)],
+    ['an unknown environment', 'ansari_mcp_qa_'],
+    ['no prefix', undefined],
+  ])('%s → the same { valid: false }', async (_name, prefix) => {
+    const made = await outsideKey(mcpUserId, { ...served, prefix });
+    expectRefused(await verify(made.key));
+  });
+
+  it('a staging-labelled key is refused by a production-configured app, and served by a staging one', async () => {
+    const made = await outsideKey(mcpUserId, { ...served, prefix: 'ansari_mcp_staging_' });
+    for (const [environment, valid] of [['production', false], ['staging', true]] as const) {
+      const app = await serveApp(createApp({ auth: service.auth, db: service.db }, { environment, production: false }));
+      try {
+        const res = await fetch(`${app.url}${SERVICE_VERIFY_PATH}`, {
+          method: 'POST',
+          headers: { 'content-type': 'application/json' },
+          body: JSON.stringify({ key: made.key, permissions: MCP }),
+        });
+        expect(res.status).toBe(200);
+        expect(((await res.json()) as { valid: boolean }).valid, environment).toBe(valid);
+      } finally {
+        await app.close();
+      }
+    }
+  });
+});
+
 describe('the service user (scenario 7)', () => {
   it('missing: a valid key → 500 and one alert per window; an unknown key → { valid: false }', async () => {
     const lone = await startVerifyService();
diff --git a/apps/auth/tests/whatsapp-session.test.ts b/apps/auth/tests/whatsapp-session.test.ts
index 3c085c90..8887af71 100644
--- a/apps/auth/tests/whatsapp-session.test.ts
+++ b/apps/auth/tests/whatsapp-session.test.ts
@@ -11,7 +11,7 @@ import { inspect } from 'node:util';
 import { createLocalJWKSet, jwtVerify } from 'jose';
 import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
 
-import { limits, serviceUsers } from '@ansari/auth';
+import { ENVIRONMENTS, getEnv, limits, serviceUsers, type Environment } from '@ansari/auth';
 
 import { TEST_JWT_AUDIENCE, TEST_JWT_ISSUER } from '../../../packages/auth/tests/helpers/auth-db';
 import {
@@ -24,6 +24,9 @@ import { createApp } from '../src/app';
 import { exchangeLimitKey, WHATSAPP_SESSION_PATH } from '../src/routes/whatsapp';
 import { BASE, rateLimitRow, send, signUpTokens, startService, type Service } from './helpers/service';
 
+/** The ENVIRONMENT the app under test runs as (the test env sets none, so the default); pinned in beforeAll. */
+const HERE: Environment = 'development';
+
 const WHATSAPP = { whatsapp: ['mint'] };
 
 /** The plugin's key hash: SHA-256, base64url (packages/auth's probe 1 pins it to defaultKeyHasher). */
@@ -78,6 +81,7 @@ function startExchangeService(): Promise {
 
 beforeAll(async () => {
   service = await startExchangeService();
+  expect(getEnv().ENVIRONMENT).toBe(HERE);
   serviceUserId = (await serviceUsers.createServiceUser(service.db, 'whatsapp')).id;
   key = await createKey();
 });
@@ -219,6 +223,14 @@ describe('key refusals: one byte-identical 401, no rows', () => {
     ],
     ['a key with mcp: complete only', async () => ({ bearer: await createKey({ permissions: { mcp: ['complete'] } }) })],
     ['a key with no permissions', async () => ({ bearer: await seededKey('update auth.apikey set permissions = null where key = $1') })],
+    // #314 Amendment 3: a stored prefix that is not this service's and this environment's.
+    ...ENVIRONMENTS.filter((e) => e !== HERE).map(
+      (e) => [`a key labelled for ${e}`, async () => ({ bearer: await createKey({ prefix: `ansari_wa_${e}_` }) })] as [string, () => Promise]
+    ),
+    ['a key with a foreign prefix', async () => ({ bearer: await createKey({ prefix: 'evil_' }) })],
+    ['a key with an MCP prefix', async () => ({ bearer: await createKey({ prefix: serviceUsers.keyPrefix('ansari-mcp', HERE) }) })],
+    ['a key with an unknown environment', async () => ({ bearer: await createKey({ prefix: 'ansari_wa_qa_' }) })],
+    ['a key with no prefix', async () => ({ bearer: await createKey({ prefix: undefined }) })],
     [
       "another service's whatsapp: mint key",
       async () => {
@@ -274,6 +286,15 @@ describe('key refusals: one byte-identical 401, no rows', () => {
 });
 
 describe('the exchange', () => {
+  it.each([...serviceUsers.acceptedKeyPrefixes('whatsapp', HERE)])(
+    'a key with the accepted prefix %s → 200 (this environment\'s label and, while legacy keys live, the bare prefix)',
+    async (prefix) => {
+      const labelled = await createKey({ prefix });
+      expect(labelled.startsWith(prefix)).toBe(true);
+      expect((await exchange(newBsuid(), newPhone(), { bearer: labelled })).status).toBe(200);
+    }
+  );
+
   it('a new BSUID → 200 with a JWT for a new WhatsApp user and its one session', async () => {
     const bsuid = newBsuid();
     const before = await rowCounts();
diff --git a/packages/auth/src/env.ts b/packages/auth/src/env.ts
index e52c87ce..4c4b46b2 100644
--- a/packages/auth/src/env.ts
+++ b/packages/auth/src/env.ts
@@ -10,6 +10,7 @@
 // env is absent (e.g. `tsc`/`tsdown` never execute the module; tests set env
 // explicitly). It runs the first time `getEnv()` is called — which is inside
 // `createAuth()`/`createDb()`.
+import { DEFAULT_ENVIRONMENT, ENVIRONMENTS, environmentIssue } from '@ansari/types/environment';
 import { z } from 'zod';
 
 /** Exported for the env-template test (apps/auth/tests/env-templates.test.ts). */
@@ -31,6 +32,10 @@ export const envSchema = z.object({
     )
     .pipe(z.array(z.url('CORS_ORIGIN must be a comma list of URLs')).min(1)),
   NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
+  // The deployment label (#314 Amendment 3): the Sentry environment and the
+  // service-key prefix's environment. Required, and staging or production,
+  // under NODE_ENV=production (the refinement below); development otherwise.
+  ENVIRONMENT: z.enum(ENVIRONMENTS).default(DEFAULT_ENVIRONMENT),
   // apps/api's own origin, sent as `Origin` by its /v2/users/* layer, whose
   // server-side fetch carries Sec-Fetch-Mode and so meets better-auth's CSRF
   // check. It joins trustedOrigins ONLY, never the CORS allowlist, so a
@@ -53,6 +58,11 @@ export const envSchema = z.object({
   PORT: z.coerce.number().int().min(1).max(65535).default(3100),
   // apps/auth's Sentry project (the list-walk alert). Unset disables sending.
   SENTRY_DSN: z.string().url('SENTRY_DSN must be a valid URL').optional(),
+}).superRefine((env, ctx) => {
+  // The default fills an absent value in before this runs, so an absent
+  // ENVIRONMENT in production reads as `development` here and is refused too.
+  const issue = environmentIssue(env.NODE_ENV, env.ENVIRONMENT);
+  if (issue) ctx.addIssue({ code: 'custom', path: ['ENVIRONMENT'], message: issue });
 });
 
 export type AuthEnv = z.output;
@@ -78,7 +88,8 @@ export function getEnv(): AuthEnv {
       `@ansari/auth env validation failed for: ${vars}. ` +
         `Set these before running the auth service — see apps/auth/.env.example ` +
         `(BETTER_AUTH_SECRET must be >= 32 chars, RESEND_API_KEY >= 20; ` +
-        `BETTER_AUTH_URL, AUTH_JWT_ISSUER and FRONTEND_URL must be URLs; CORS_ORIGIN a comma list of URLs).`
+        `BETTER_AUTH_URL, AUTH_JWT_ISSUER and FRONTEND_URL must be URLs; CORS_ORIGIN a comma list of URLs; ` +
+        `ENVIRONMENT staging or production when NODE_ENV=production).`
     );
   }
 
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index 12f773a4..a8e5d463 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -59,6 +59,7 @@ export {
   type Mailer,
 } from './reset-email';
 export { CLIENT_HEADER, isMcpClientId, MCP_CLIENT_ID_PATTERN } from '@ansari/types/attribution';
+export { ENVIRONMENTS, environmentIssue, type Environment } from '@ansari/types/environment';
 
 /** Same bounds as the legacy register schema, and better-auth's own defaults. */
 export const MIN_PASSWORD_LENGTH = 8;
diff --git a/packages/auth/src/service-users.ts b/packages/auth/src/service-users.ts
index 8e07fff8..feb1aa98 100644
--- a/packages/auth/src/service-users.ts
+++ b/packages/auth/src/service-users.ts
@@ -4,12 +4,14 @@
 // Only apps/auth's service-keys script creates one; its keys are created and
 // changed in process through the api-key plugin, whose HTTP surface is blocked.
 //
-// Permissions and key prefixes are fixed here, per service, so the script
+// Permissions and base key prefixes are fixed here, per service, so the script
 // takes no free-form permissions: a key for one service is refused at
-// another's route.
+// another's route. A key's full prefix adds its environment (keyPrefix).
 import { and, asc, eq } from 'drizzle-orm';
 
 import type { Db } from './db';
+import { ENVIRONMENTS, type Environment } from '@ansari/types/environment';
+
 import { MCP_KEY_BOUNDS, WHATSAPP_KEY_BOUNDS } from './limits';
 import { serviceAddress } from './reserved';
 import { account, apikey, users } from './schema';
@@ -37,13 +39,64 @@ export function isServiceName(name: string): name is ServiceName {
 }
 
 /**
- * GitHub custom secret-scanning patterns, one per key prefix: the prefix and
- * the plugin's 64-letter key. The runbook asks the owner to register exactly
- * these (`.source`) for the organisation.
+ * A key's prefix names the environment it was issued in (#314, owner
+ * 2026-11-12, Amendments 2 and 3): `ansari___`, e.g.
+ * `ansari_wa_production_`, `ansari_mcp_staging_`, where the environment is the
+ * issuing apps/auth's ENVIRONMENT (one vocabulary with apps/api, the frontend
+ * and Sentry). The script reads it from its process env; each route accepts
+ * only its own environment's prefix, so a key leaked from one environment is
+ * readable as such and refused in another.
+ */
+export function keyPrefix(service: ServiceName, environment: Environment): string {
+  return `${SERVICES[service].prefix}${environment}_`;
+}
+
+/**
+ * Keys issued before #314 carry the bare service prefix (`ansari_wa_`, no
+ * environment): at least one live staging WhatsApp key does. While this is
+ * true the routes still accept that prefix, the secret-scanning patterns
+ * still catch it and the script still refuses it pasted into a flag. The
+ * compatibility window closes when `list` shows no live unlabelled key on any
+ * database: set this to false and re-register the scanning patterns (the
+ * runbook's "Rotate legacy keys" step and its follow-up issue).
+ */
+export const LEGACY_UNLABELLED_KEYS = true;
+
+/**
+ * The prefixes a route of `service` running as `environment` accepts: that
+ * environment's, plus the bare legacy prefix while LEGACY_UNLABELLED_KEYS
+ * holds. Any other stored prefix (another environment's, another service's, a
+ * hand-made one) is the route's ordinary refusal.
+ */
+export function acceptedKeyPrefixes(service: ServiceName, environment: Environment): readonly string[] {
+  const own = keyPrefix(service, environment);
+  return LEGACY_UNLABELLED_KEYS ? [own, SERVICES[service].prefix] : [own];
+}
+
+/** True when a verified key's stored prefix is one `service`'s route in `environment` accepts. */
+export function isAcceptedKeyPrefix(service: ServiceName, environment: Environment, prefix: unknown): boolean {
+  return typeof prefix === 'string' && acceptedKeyPrefixes(service, environment).includes(prefix);
+}
+
+/** The plugin's key body: 64 letters (its default length and alphabet). */
+const KEY_BODY = '[A-Za-z]{64}';
+
+function scanningPattern(service: ServiceName): RegExp {
+  const envs = `(?:${ENVIRONMENTS.join('|')})_`;
+  return new RegExp(`${SERVICES[service].prefix}${LEGACY_UNLABELLED_KEYS ? `(?:${envs})?` : envs}${KEY_BODY}`);
+}
+
+/**
+ * GitHub custom secret-scanning patterns, one per service, derived from the
+ * same table as keyPrefix: the base prefix, any ENVIRONMENT segment (optional
+ * while LEGACY_UNLABELLED_KEYS holds), and the plugin's 64-letter key. The
+ * script's pasted-key refusal uses these too, so the three never disagree. The
+ * runbook asks the owner to register exactly these (`.source`) for the
+ * organisation.
  */
 export const SECRET_SCANNING_PATTERNS: Readonly> = {
-  whatsapp: /ansari_wa_[A-Za-z]{64}/,
-  'ansari-mcp': /ansari_mcp_[A-Za-z]{64}/,
+  whatsapp: scanningPattern('whatsapp'),
+  'ansari-mcp': scanningPattern('ansari-mcp'),
 };
 
 export type ServiceUser = { id: string; email: string; createdAt: Date };
diff --git a/packages/types/package.json b/packages/types/package.json
index e8b293f6..d3d54831 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -8,7 +8,8 @@
   "types": "./src/index.ts",
   "exports": {
     ".": "./src/index.ts",
-    "./attribution": "./src/attribution.ts"
+    "./attribution": "./src/attribution.ts",
+    "./environment": "./src/environment.ts"
   },
   "scripts": {
     "lint": "eslint .",
diff --git a/packages/types/src/environment.ts b/packages/types/src/environment.ts
new file mode 100644
index 00000000..5c3356b6
--- /dev/null
+++ b/packages/types/src/environment.ts
@@ -0,0 +1,26 @@
+/**
+ * The deployment label (#314 Amendment 3, owner 2026-11-12): `ENVIRONMENT`,
+ * named to match the frontend's `EXPO_PUBLIC_ENVIRONMENT`, in apps/api and
+ * apps/auth. It is the Sentry environment of both services and the
+ * environment segment of every service-key prefix (`ansari___`).
+ * NODE_ENV keeps its own jobs (test detection, production hardening);
+ * ENVIRONMENT says which deployment this is.
+ */
+export const ENVIRONMENTS = ['development', 'staging', 'production'] as const;
+
+export type Environment = (typeof ENVIRONMENTS)[number];
+
+/** Absent outside production: a local or CI process is `development`. */
+export const DEFAULT_ENVIRONMENT: Environment = 'development';
+
+/**
+ * Why `environment` is not acceptable for a process running with `nodeEnv`,
+ * or null when it is. Under NODE_ENV=production it is required and must be
+ * `staging` or `production`: a deployed service labelled `development` is a
+ * misconfiguration, so both services refuse to boot (names only, no values).
+ */
+export function environmentIssue(nodeEnv: string | undefined, environment: string | undefined): string | null {
+  if (nodeEnv !== 'production') return null;
+  if (environment === 'staging' || environment === 'production') return null;
+  return 'ENVIRONMENT must be set to staging or production when NODE_ENV=production';
+}
diff --git a/turbo.json b/turbo.json
index 323f59a9..24678ab4 100644
--- a/turbo.json
+++ b/turbo.json
@@ -145,6 +145,11 @@
     // variable and the log-only branch one week after enforcement; the issue
     // is opened at enforce (rollout step 6).
     "MCP_COMPLETE_KEY_MODE",
+    // #314 Amendment 3: the deployment label (development, staging,
+    // production) in apps/api and apps/auth's Zod schemas, the Sentry
+    // environment of both, and the service-key prefix's environment. Required
+    // under NODE_ENV=production; read at runtime only, never at build.
+    "ENVIRONMENT",
     "MAINTENANCE_MODE",
     "IOS_MINIMUM_BUILD_VERSION",
     "IOS_LATEST_BUILD_VERSION",

From 2c810659e748fce8c8500d85dd674de9ce19d41f Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 09:37:16 +1100
Subject: [PATCH 158/435] [Spec 314] docs: spec Amendments 2-3, plan addendum,
 ENVIRONMENT deploy order, runbook env labels and legacy-key window, review

---
 RELEASE.md                                    | 15 ++++-
 apps/mcp/.env.example                         |  2 +-
 apps/mcp/README.md                            |  2 +-
 .../314-protect-v2-mcp-complete-with-b.md     | 30 +++++++++
 codev/resources/arch.md                       |  4 +-
 .../314-protect-v2-mcp-complete-with-b.md     | 27 +++++++-
 .../314-protect-v2-mcp-complete-with-b.md     |  5 ++
 codev/state/spir-314_thread.md                |  7 ++
 docs/cutover/deploy-guide.md                  |  4 +-
 docs/cutover/service-keys-runbook.md          | 64 ++++++++++++++-----
 docs/self-hosting.md                          | 18 +++++-
 11 files changed, 153 insertions(+), 25 deletions(-)

diff --git a/RELEASE.md b/RELEASE.md
index 6702492d..a3de64f9 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -91,7 +91,7 @@ migration runbook were both proven in real releases on 2026-08-02.
 > | `MCP_ALLOWED_HOSTS` | `mcp-staging.askansari.ai` (the server refuses any other Host on `/mcp`) |
 > | `ANSARI_API_BASE_URL` | `https://api-staging.askansari.ai` (the default is production) |
 > | `ANSARI_CLIENT` | `ansari-mcp-staging` |
-> | `ANSARI_API_AUTHORIZATION` | `Bearer ansari_mcp_<64 letters>`: the staging key, made with `--client-id ansari-mcp-staging` and set **before** apps/api staging deploys #314 (`docs/cutover/service-keys-runbook.md`) |
+> | `ANSARI_API_AUTHORIZATION` | `Bearer ansari_mcp_staging_<64 letters>`: the staging key, made in the staging auth shell with `--client-id ansari-mcp-staging` and set **before** apps/api staging deploys #314 (`docs/cutover/service-keys-runbook.md`) |
 >
 > `ANSARI_RELEASE` is **not** set: the release falls back to `RAILWAY_GIT_COMMIT_SHA`. `MCP_ALLOWED_ORIGINS` is left
 > unset at first: it defaults to the allowed hosts, and requests without an Origin pass. The Cloudflare Workers path
@@ -111,6 +111,19 @@ migration runbook were both proven in real releases on 2026-08-02.
 > `… scripts/ban-user.ts …`), or in the image from `/repo/apps/auth` with
 > `./node_modules/.bin/tsx scripts/…` (tsx directly: the image has no pnpm for its non-root user).
 >
+> **`ENVIRONMENT` on `backend` and auth (#314 Amendment 3)** — the deployment label, also each
+> service's Sentry environment and the environment in every service key's prefix. Both refuse to
+> boot under `NODE_ENV=production` without it (or set to `development`):
+>
+> | Service | staging | production |
+> |---|---|---|
+> | `backend` (apps/api) | `ENVIRONMENT=staging` | `ENVIRONMENT=production` |
+> | auth (apps/auth) | `ENVIRONMENT=staging` | `ENVIRONMENT=production` |
+>
+> **Deploy order:** set `ENVIRONMENT` on `backend` and auth, in staging and in production,
+> **before** the deploy that carries #314. A deploy without it fails its healthcheck and Railway
+> keeps the previous deployment.
+>
 > **frontend (web) build variables** — `Dockerfile.web` bakes `EXPO_PUBLIC_API_URL`
 > and `EXPO_PUBLIC_AUTH_URL` into the bundle at build time, so both are set on the
 > Railway service and a change needs a redeploy. They name the SAME environment:
diff --git a/apps/mcp/.env.example b/apps/mcp/.env.example
index 7d7208ee..2e14969a 100644
--- a/apps/mcp/.env.example
+++ b/apps/mcp/.env.example
@@ -15,7 +15,7 @@ PORT=3000
 # Upstream Authorization header, sent verbatim. Required for a deployment that
 # calls a deployed Ansari API once /api/v2/mcp-complete enforces keys (#314);
 # optional only against a local API. The value is the whole header:
-# Bearer ansari_mcp_<64 letters> (this deployment's key, from the operator).
+# Bearer ansari_mcp__<64 letters> (this deployment's key, from the operator).
 # Never commit a value.
 # ANSARI_API_AUTHORIZATION=
 
diff --git a/apps/mcp/README.md b/apps/mcp/README.md
index 8cbd44a9..010ecd40 100644
--- a/apps/mcp/README.md
+++ b/apps/mcp/README.md
@@ -89,7 +89,7 @@ The Worker takes the variables in the table below as Wrangler `vars` or secrets,
 | --- | --- |
 | `PORT` | HTTP port (default 3000). |
 | `ANSARI_API_BASE_URL` | Ansari API origin (default `https://api.askansari.ai`). |
-| `ANSARI_API_AUTHORIZATION` | Upstream Authorization header, sent verbatim: `Bearer ansari_mcp_<64 letters>`, the word `Bearer`, a space, then this deployment's `ansari-mcp` service key. Required for any deployment that calls a deployed Ansari API: `/api/v2/mcp-complete` refuses a call without a valid key (401) once it enforces (#314). Optional only against a local API. Issued per deployment by the operator (`docs/cutover/service-keys-runbook.md`); set it with `wrangler secret put ANSARI_API_AUTHORIZATION --env ` on Workers or as a service variable on Railway, never commit it. |
+| `ANSARI_API_AUTHORIZATION` | Upstream Authorization header, sent verbatim: `Bearer ansari_mcp__<64 letters>`, the word `Bearer`, a space, then this deployment's `ansari-mcp` service key (its prefix names the environment it was issued in: `development`, `staging` or `production`, and only that environment's API accepts it). Required for any deployment that calls a deployed Ansari API: `/api/v2/mcp-complete` refuses a call without a valid key (401) once it enforces (#314). Optional only against a local API. Issued per deployment by the operator (`docs/cutover/service-keys-runbook.md`); set it with `wrangler secret put ANSARI_API_AUTHORIZATION --env ` on Workers or as a service variable on Railway, never commit it. |
 | `ANSARI_CLIENT` | Upstream client label (default `ansari-mcp`). |
 | `MCP_ALLOWED_HOSTS` | Comma-separated allowed HTTP Host names, without scheme. A configured list replaces local defaults; an explicitly empty list permits no Host. Only an absent variable defaults to localhost and 127.0.0.1. |
 | `MCP_ALLOWED_ORIGINS` | Comma-separated allowed browser origin hostnames. A configured list replaces defaults; an explicitly empty list permits no Origin header value. Requests without Origin remain supported. |
diff --git a/codev/plans/314-protect-v2-mcp-complete-with-b.md b/codev/plans/314-protect-v2-mcp-complete-with-b.md
index 3aff4f58..451d3827 100644
--- a/codev/plans/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/plans/314-protect-v2-mcp-complete-with-b.md
@@ -390,3 +390,33 @@ The order is the real protection: every MCP caller holds its key **before** apps
 - `codev/resources/arch-critical.md` (the amended JWT-only fact and its map line) and `codev/resources/arch.md` (Phase 5).
 - `codev/resources/lessons-learned.md` in the review phase.
 - Out of repository, as owner steps: the published snippet, the MCP setup page, and `mcp.ansari.chat`'s variable.
+
+## Addendum: Amendments 2 and 3 (2026-11-12, review phase, on PR #372)
+
+The owner expanded the scope after the PR consult. Following the security architect's porch route,
+this addendum is built as review-phase commits on #372 (no rollback), then the PR consult is re-run
+and the `pr` gate re-requested.
+
+1. **`ENVIRONMENT`** (`packages/types/src/environment.ts`: `ENVIRONMENTS`, `environmentIssue`),
+   re-exported by `@ansari/auth`. Added to `packages/auth/src/env.ts` and `apps/api/lib/config.ts`
+   (default `development`; under `NODE_ENV=production` required and `staging` or `production`).
+   Enforced only where each schema is already enforced: apps/api's `validateEnvAtBoot` (never
+   during `next build`), apps/auth's `getEnv()` at the top of `src/index.ts` (never at image build).
+2. **Sentry:** apps/auth `initSentry(env.SENTRY_DSN, env.ENVIRONMENT)`; apps/api
+   `sentry.server.config.ts` `environment: process.env.ENVIRONMENT || "development"`.
+3. **Prefixes:** `keyPrefix(service, environment)`, `acceptedKeyPrefixes`/`isAcceptedKeyPrefix`
+   (own environment, plus the bare prefix while `LEGACY_UNLABELLED_KEYS`), and the scanning
+   patterns derived from the same table.
+4. **Script:** reads `ENVIRONMENT` from its process env (no flag); refuses without it; prints it
+   under the database line; new keys carry it.
+5. **Routes:** the exchange and the verify route refuse a key whose stored prefix is not theirs
+   (`environment` option, default `getEnv().ENVIRONMENT`; `createApp` passes `options.environment`).
+6. **Tests:** schema and boot (both services), the script, both routes (own label served, legacy
+   served, other environments, foreign and absent prefixes refused, a staging key refused by a
+   production-configured app), the longest prefix created through the plugin, the derived scanning
+   sources. Mutation-checked: dropping the environment comparison fails 5 tests.
+7. **Surfaces:** `turbo.json` `globalEnv` (main's hunk), `.env.example` and `.env.ci` of apps/api
+   and apps/auth, `docs/self-hosting.md`, `docs/cutover/deploy-guide.md`, RELEASE.md (rows and a
+   deploy-order line), the runbook (scanning table, environment labels, existing keys unchanged,
+   rotate legacy keys), apps/mcp README and `.env.example`, `arch.md`.
+
diff --git a/codev/resources/arch.md b/codev/resources/arch.md
index e7cee8b4..62aa3c69 100644
--- a/codev/resources/arch.md
+++ b/codev/resources/arch.md
@@ -22,9 +22,9 @@ Better Auth, in its own service (spec 300). `packages/auth` (`@ansari/auth`) is
 
 **Admin & system identity.** Admin = `auth.users.role === 'admin'` (and not banned), asked of `apps/auth`'s `GET /api/account/me` with the admin's own JWT on **every** admin request (`requireAdmin`): a demotion, a ban or a revoked session applies at once, an outage fails closed (503). Never an email match, never a JWT claim. Roles are granted by `apps/auth/scripts/grant-admin.ts`, which never creates an account or touches a password, in two steps: `` shows id, email, `created_at`, `email_verified` and role and grants nothing; ` --confirm ` grants exactly that account. It never grants to a system- or noreply-domain address (`--revoke`, a demotion, is allowed for any account: it is the repair for a WhatsApp user found holding `admin`) and warns on a recent or unverified account (no email verification exists, so an address can be squatted). There is no admin list and no boot check (owner amendment H-7). System identities (`ai-skill`, `leaderboard`) exist only as app rows found by `system_key` (`getOrCreateSystemUser`), with no auth row and no credential; `@system.ansari.chat` is reserved.
 
-**Service keys and the WhatsApp exchange (spec 329).** A **service** (`whatsapp`; `ansari-mcp`, #314) is one auth user with no credential under `@noreply.askansari.ai`, found by its `{provider_id: 'service', account_id: }` row, never by email. Its keys come from `@better-auth/api-key` (pinned with core), rows in `auth.apikey` holding only the SHA-256 hash, each with its own per-window limit and daily refilled budget, no expiry, and fixed per-service permissions and prefix (`ansari_wa_`, `ansari_mcp_`), so a key for one service is refused at another's route. The plugin's HTTP surface is blocked; `apps/auth/scripts/service-keys.ts` is the only issuer (shown, then confirmed by id; the raw key printed once; a Sentry record of each write, with no key material). `enableSessionForAPIKeys` is off: a key is never a session. `POST /api/whatsapp/session` (mounted before CORS and outside Better Auth's router, so no per-IP rule and no CORS) verifies the key in process (`verifyApiKey` with `whatsapp: mint`), finds or creates the BSUID's user through `account (provider_id = 'whatsapp', account_id = )` (`unique (provider_id, account_id)` makes it one user under concurrency), checks eligibility under a lock on the user row (only that account row, its own `whatsapp-@noreply.askansari.ai` address, `registered_via = 'whatsapp'`, role exactly `user`, an allowlist; otherwise 500, never a token) and the ban (403, sessions deleted), reuses one session per user, and signs the ordinary `{sub, sid}` JWT after commit. So a key can only ever yield tokens for WhatsApp users: never an email user, an admin, a system or a service account. The BSUID lives only in `account.account_id` and reaches no log, response or `apps/api`. No phone number is stored anywhere (owner amendment 2): a `phone_number` the WhatsApp service sends is accepted and ignored. `@noreply.askansari.ai` is refused at sign-up (as a taken address), reset (as an unknown one), a grant by `grant-admin.ts`, and the `user.create.before` hook on every Better Auth path. **apps/api has no WhatsApp code** (a source scan); the exchange JWT passes `requireUser` unchanged. **Alert posture:** the exchange's alerts (per-key volume at one third of the caps, key refusals, 401 volume, ineligible users, an unresolvable service user) carry key ids, counts, thresholds and windows only in Sentry (a key id is a plugin-made UUID that names a credential, not a person, and matches `list`); user ids appear only in server log lines, and the service's Sentry keeps no breadcrumbs, so a logged id never rides on an event. `apps/auth` refuses to boot without `auth.apikey` or the constraint (migration `0001`). Operator procedure: `docs/cutover/service-keys-runbook.md`.
+**Service keys and the WhatsApp exchange (spec 329).** A **service** (`whatsapp`; `ansari-mcp`, #314) is one auth user with no credential under `@noreply.askansari.ai`, found by its `{provider_id: 'service', account_id: }` row, never by email. Its keys come from `@better-auth/api-key` (pinned with core), rows in `auth.apikey` holding only the SHA-256 hash, each with its own per-window limit and daily refilled budget, no expiry, and fixed per-service permissions and base prefix (`ansari_wa_`, `ansari_mcp_`), so a key for one service is refused at another's route. Since #314 (Amendments 2 and 3) the full prefix names the environment the key was issued in, `ansari___`, where `ENVIRONMENT` (`development|staging|production`, required under `NODE_ENV=production` in apps/auth and apps/api, also their Sentry environment) is read by the script from its process env; one table in `service-users.ts` derives the prefixes, the accepted set and the secret-scanning patterns. Both routes serve only a key whose stored `apikey.prefix` names their own service and their own `ENVIRONMENT`, so a key leaked from one environment is refused in another; the bare legacy prefix is accepted while `LEGACY_UNLABELLED_KEYS` holds (compatibility window, closed by a follow-up). The plugin's HTTP surface is blocked; `apps/auth/scripts/service-keys.ts` is the only issuer (shown, then confirmed by id; the raw key printed once; a Sentry record of each write, with no key material). `enableSessionForAPIKeys` is off: a key is never a session. `POST /api/whatsapp/session` (mounted before CORS and outside Better Auth's router, so no per-IP rule and no CORS) verifies the key in process (`verifyApiKey` with `whatsapp: mint`), finds or creates the BSUID's user through `account (provider_id = 'whatsapp', account_id = )` (`unique (provider_id, account_id)` makes it one user under concurrency), checks eligibility under a lock on the user row (only that account row, its own `whatsapp-@noreply.askansari.ai` address, `registered_via = 'whatsapp'`, role exactly `user`, an allowlist; otherwise 500, never a token) and the ban (403, sessions deleted), reuses one session per user, and signs the ordinary `{sub, sid}` JWT after commit. So a key can only ever yield tokens for WhatsApp users: never an email user, an admin, a system or a service account. The BSUID lives only in `account.account_id` and reaches no log, response or `apps/api`. No phone number is stored anywhere (owner amendment 2): a `phone_number` the WhatsApp service sends is accepted and ignored. `@noreply.askansari.ai` is refused at sign-up (as a taken address), reset (as an unknown one), a grant by `grant-admin.ts`, and the `user.create.before` hook on every Better Auth path. **apps/api has no WhatsApp code** (a source scan); the exchange JWT passes `requireUser` unchanged. **Alert posture:** the exchange's alerts (per-key volume at one third of the caps, key refusals, 401 volume, ineligible users, an unresolvable service user) carry key ids, counts, thresholds and windows only in Sentry (a key id is a plugin-made UUID that names a credential, not a person, and matches `list`); user ids appear only in server log lines, and the service's Sentry keeps no breadcrumbs, so a logged id never rides on an event. `apps/auth` refuses to boot without `auth.apikey` or the constraint (migration `0001`). Operator procedure: `docs/cutover/service-keys-runbook.md`.
 
-**The MCP key and its verify route (#314).** `/v2/mcp-complete` is apps/api's one route that takes something other than a JWT: `Authorization: Bearer ` (scheme case-insensitive). apps/api cannot verify the key itself (the hash lives in the auth database), so on every request it asks apps/auth at its public origin, `POST /api/service/verify-key` with `{key, permissions: {mcp: ['complete']}}` (`verifyServiceKey`, `lib/auth-service/client.ts`, 3 s timeout). The route calls `verifyApiKey` in process, mounted ahead of CORS and outside Better Auth's router (no per-IP rule, no credential but the key), and serves a **closed permission set**: exactly `{mcp: ['complete']}` for the `ansari-mcp` service user, anything else 400, so it can neither verify nor spend a WhatsApp key under its own permission. It answers `{valid: true, client_id, key_id}` or one byte-identical `{valid: false}` for every refusal, including a key whose `client_id` is not `ansari-mcp*` (the script refuses to make one; the `client-id-invalid` alert names it); apps/api accepts only those two shapes, anything else is an outage. **Fail closed:** refused → 401, outage or timeout → 503, before any persistence or model call. The thread's `client` is the key's `client_id`; `X-Ansari-Client` is ignored (Sentry warning on a mismatch). Each verify spends one unit of the key's own budget and window, which is the throttle (one key per MCP deployment, 120 per minute and 5,000 a day initially); the route's per-IP cap in apps/api stays. **Log-only transition:** `MCP_COMPLETE_KEY_MODE=log-only` verifies, records the verdict (`valid`/`missing`/`refused`/`unverified`, log line and Sentry tag `mcp_key_verdict`) and always serves; absent means `enforce`, anything else fails boot. The mode, its `turbo.json` entry and log-only itself are to be removed by a follow-up issue due one week after enforcement. Verify alerts mirror the exchange's under `auth: MCP key verify alert`. A plugin bump that ever routes `/api-key/verify` fails `apps/auth/tests/blocked-paths.test.ts`.
+**The MCP key and its verify route (#314).** `/v2/mcp-complete` is apps/api's one route that takes something other than a JWT: `Authorization: Bearer ` (scheme case-insensitive; a token outside apps/auth's `[\x21-\x7E]{1,256}` envelope is `missing`, no call). apps/api cannot verify the key itself (the hash lives in the auth database), so on every request it asks apps/auth at its public origin, `POST /api/service/verify-key` with `{key, permissions: {mcp: ['complete']}}` (`verifyServiceKey`, `lib/auth-service/client.ts`, 3 s timeout). The route calls `verifyApiKey` in process, mounted ahead of CORS and outside Better Auth's router (no per-IP rule, no credential but the key), and serves a **closed permission set**: exactly `{mcp: ['complete']}` for the `ansari-mcp` service user, anything else 400, so it can neither verify nor spend a WhatsApp key under its own permission. It answers `{valid: true, client_id, key_id}` or one byte-identical `{valid: false}` for every refusal, including a key whose `client_id` is not `ansari-mcp*` (the script refuses to make one; the `client-id-invalid` alert names it) and a key whose stored prefix is not in the `ansari-mcp` accepted set; apps/api accepts only those two shapes, anything else is an outage. **Fail closed:** refused → 401, outage or timeout → 503, before any persistence or model call. The thread's `client` is the key's `client_id`; `X-Ansari-Client` is ignored (Sentry warning on a mismatch). Each verify spends one unit of the key's own budget and window, which is the throttle (one key per MCP deployment, 120 per minute and 5,000 a day initially); the route's per-IP cap in apps/api stays. **Log-only transition:** `MCP_COMPLETE_KEY_MODE=log-only` verifies, records the verdict (`valid`/`missing`/`refused`/`unverified`, log line and Sentry tag `mcp_key_verdict`) and always serves; absent means `enforce`, anything else fails boot. The mode, its `turbo.json` entry and log-only itself are to be removed by a follow-up issue due one week after enforcement. Verify alerts mirror the exchange's under `auth: MCP key verify alert`. A plugin bump that ever routes `/api-key/verify` fails `apps/auth/tests/blocked-paths.test.ts`.
 
 **The legacy surface.** `/v2/users/*` and the two reset routes stay on `apps/api` for the released mobile app, as anonymous pass-through clients of `apps/auth`'s public endpoints (no credential, no forwarded IP), with frozen response shapes (a SHA-pinned contract suite). `register` and `login` return the JWT as `access_token` and the session token as `refresh_token`; `refresh_token` returns a new JWT for the same session. `DELETE /v2/users/me` deletes the app row and writes the tombstone in one transaction, then calls `DELETE /api/account` with the user's JWT (refused before any call unless the token's `sub` is that user). A user who calls `DELETE /api/account` directly leaves the app row and no tombstone: an owner-accepted residual whose operator response is in the runbook ("Orphan app rows").
 
diff --git a/codev/reviews/314-protect-v2-mcp-complete-with-b.md b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
index 98ddc4e8..3df9965e 100644
--- a/codev/reviews/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
@@ -2,7 +2,11 @@
 
 ## Summary
 
-`POST/GET /api/v2/mcp-complete` now requires `Authorization: Bearer `. apps/api checks the key on every request at a new public apps/auth route, `POST /api/service/verify-key`. That route is the second consumer of spec 329's api-key plugin. It answers `{valid, client_id, key_id}` or a byte-identical `{valid:false}`. The thread's `client` comes from the key's metadata. A missing or refused key gets 401. An apps/auth outage gets 503: fail closed, nothing persisted, no Gemini call. `MCP_COMPLETE_KEY_MODE=log-only` gives a one-week transition in which every verdict is recorded and every request is served. The work shipped in five plan phases, all on one branch: key rules, verify route, apps/api client and mode, route gate, docs.
+`POST/GET /api/v2/mcp-complete` now requires `Authorization: Bearer `. apps/api checks the key on every request at a new public apps/auth route, `POST /api/service/verify-key`. That route is the second consumer of spec 329's api-key plugin. It answers `{valid, client_id, key_id}` or a byte-identical `{valid:false}`. The thread's `client` comes from the key's metadata. A missing or refused key gets 401. An apps/auth outage gets 503: fail closed, nothing persisted, no Gemini call. `MCP_COMPLETE_KEY_MODE=log-only` gives a one-week transition in which every verdict is recorded and every request is served. The work shipped in five plan phases, all on one branch: key rules, verify route, apps/api client and mode, route gate, docs. During the PR review the owner widened the scope (spec Amendments 2 and 3):
+
+- every service key's prefix now names its environment (`ansari___`);
+- apps/api and apps/auth gain an `ENVIRONMENT` variable, which becomes their Sentry environment and is required in production;
+- each key route refuses a key labelled for another environment.
 
 ## Spec Compliance
 
@@ -23,10 +27,16 @@
 - [x] Log-only records every verdict and serves. Enforce is the behaviour when the setting is absent (Phases 3 and 4).
 - [x] pglite tests for the verify route (real plugin, real `auth.apikey`) and for the apps/api route (real app DB, apps/auth answered by a `fetch` stub of the verify contract, real `verifyServiceKey`), including the forged-header and WhatsApp-key cases (Phases 2 and 4).
 - [x] Docs (§5): `docs/self-hosting.md`, `docs/cutover/service-keys-runbook.md` (issuance per deployment, Bearer hand-off, rollout, limits, alerts, rotation, plugin-upgrade check), `apps/api/README.md`, `apps/mcp/README.md`, `apps/mcp/.env.example`, the RELEASE.md staging row (Phase 5).
+- [x] Amendment 2: one prefix table derives the prefixes, the accepted set, the scanning patterns and the pasted-key check. Existing keys are unchanged; unlabelled keys are accepted during a compatibility window (review phase).
+- [x] Amendment 3: `ENVIRONMENT` in both schemas, required in production. Both services refuse to boot without it, shown in tests and in recorded runs:
+  - apps/auth exits with "env validation failed for: ENVIRONMENT";
+  - apps/api's boot check logs the rule and `/api/health` answers 500.
+  `next build` and the auth build pass with it unset. It is the Sentry environment of both services and the prefix segment. Both routes refuse another environment's label, including a staging key presented to a production-configured app (review phase).
 - [ ] **Operator steps, outside the repository. Not done by this PR; the owner must do them before enforce:**
   1. Create one key per MCP deployment with `apps/auth/scripts/service-keys.ts` and `--client-id`. That means production `mcp.ansari.chat` (`ansari-mcp`) and `mcp-staging.askansari.ai` (`--client-id ansari-mcp-staging`). The staging key must exist **before apps/api staging deploys this change**, because the default mode is enforce.
   2. Set each Worker's/service's `ANSARI_API_AUTHORIZATION` to `Bearer ansari_mcp_<64 letters>`, prefix included.
   3. Update the published integration snippet and the MCP setup page on the public site. Their locations are still pending from the owner, via the security architect.
+  0. Set `ENVIRONMENT=staging` / `ENVIRONMENT=production` on `backend` and auth in each environment **before** this deploys (RELEASE.md), or both services refuse to boot.
   4. Run the rollout: deploy with `MCP_COMPLETE_KEY_MODE=log-only`, watch the `mcp_key_verdict` tag for a week, then remove the variable (enforce). At enforce, open the follow-up that removes log-only and the `turbo.json` hunk one week later.
 
 ## Deviations from Plan
@@ -45,6 +55,10 @@
   - Security architect order (04:10Z): `alerts.keyVerified()` moved after the owner and client-id checks in `service-verify.ts`, so only a served key counts toward the volume alerts. A test pins the order and fails under the old one. The WhatsApp exchange order is unchanged.
 - **Phase 5:** rebased onto develop (#365, #368, #370) first. #366 had changed the attribution link to `askansari.ai`, so scenario 4's expectation followed it in its own commit. Architect orders added the `mcp-staging` key, the `Bearer` form in all three apps/mcp docs, and the RELEASE.md staging row.
 - **Review (PR consult):** the route checks the bearer token's shape (printable ASCII, 1–256 characters, apps/auth's bound) before calling apps/auth. The plan's bearer rule (one token, no whitespace) let an over-long or non-ASCII token through, and apps/auth's 400 turned it into a 503.
+- **Review phase, Amendments 2 and 3 (owner, 2026-11-12):** the owner asked on the PR why the MCP client needed special handling, then directed that every service key's prefix carry its environment.
+  - The first design took the environment from an `--env` flag, with routes that would never compare the label to their own environment.
+  - The owner then directed an `ENVIRONMENT` variable (Amendment 3). With it, the script reads the environment from its process env, the label is the environment's own name, and each route compares the prefix to its own environment. That turns the label into real hardening.
+  - Built as review-phase commits on #372, on the security architect's porch route; the plan addendum lists the steps.
 - **`turbo.json`:** this PR carries the `MCP_COMPLETE_KEY_MODE` `globalEnv` hunk, on main's instruction. Main reviews it on the PR.
 
 ## Consultation Feedback
@@ -146,6 +160,8 @@ No `CONSULT_ERROR` occurred in any round.
 - Grep a route's real callers before a plan names the suites a change touches. Four of the seven named suites never called the route.
 - Put every "count this as success" side effect after the last check in a verify path from the start, and pin the order with a test.
 
+- The env-label design went through two shapes in an hour: a `--env` flag, then `ENVIRONMENT`. The first was built because apps/auth had no environment discriminator; the owner's answer was to add one. Next time, when a design needs a fact the system lacks, ask whether to add that fact before designing around its absence.
+
 ### Methodology Improvements
 
 - A plan that names existing test files to change should list how each one calls the code under change (route vs helper), so the count is checked at plan review.
@@ -154,6 +170,7 @@ No `CONSULT_ERROR` occurred in any round.
 ## Architecture Updates
 
 - Routed: hot — `arch-critical.md` JWT fact — amended in place (Phase 5): apps/api accepts only apps/auth's JWT **except** `/v2/mcp-complete`, which takes an `ansari-mcp` service key verified on every request at `/api/service/verify-key` (401 refused, 503 outage). The map's Authentication line now names "service keys (WhatsApp exchange, MCP verify)". No fact was added, so no demotion was needed.
+- Routed: cold — `arch.md` service-keys paragraph — key prefixes name `ENVIRONMENT`, routes refuse another environment's label, `LEGACY_UNLABELLED_KEYS` window (Amendments 2 and 3). The verify-route paragraph also records the bearer envelope (401, no call). No hot change: `arch-critical.md` is at its 10-fact cap, and `ENVIRONMENT` is a deployment setting documented in self-hosting and RELEASE.md.
 - Routed: cold — `arch.md` Authentication & Authorization — new verify-route paragraph (Phase 5): the closed permission set, owner and client-id binding, refusal shape, no CORS, no per-IP rule, `MCP_COMPLETE_KEY_MODE`.
 
 ## Lessons Learned Updates
@@ -165,6 +182,11 @@ No `CONSULT_ERROR` occurred in any round.
   - pin a remote verdict's refusal shape on both sides.
 - Routed: hot — `lessons-critical.md` map line for spec 329 extended to "+ MCP key verify (spec 314)", with a consult trigger for gating a route on a remote verify. No lesson was added: the hot file is at its cap, and none of these is cross-cutting enough to displace an entry.
 
+## Sentry environment continuity (Amendment 3)
+
+- **apps/api** sent `RAILWAY_ENVIRONMENT || NODE_ENV`, and now sends `ENVIRONMENT`. Railway's environment names are `staging` and `production`, so with `ENVIRONMENT` set to match, api events keep the same labels. RELEASE.md does not state these names; they come from the repository's Railway-created GitHub Environments (`ansari-backend / staging`, `ansari-backend / production`).
+- **apps/auth** sent `NODE_ENV`, which is `production` on both staging and production. Today its staging events are therefore labelled `production`. After this change they are labelled `staging`. This is a deliberate correction, and the owner should check the auth Sentry project's alert rules and filters.
+
 ## Flaky Tests
 
 Neither test was skipped. Both are pre-existing, outside this change, and passed in isolation and on a full rerun. The security architect owns this class (#330 lineage) and ordered that it not be chased here.
@@ -174,6 +196,9 @@ Neither test was skipped. Both are pre-existing, outside this change, and passed
 
 ## Follow-up Items
 
+- **Close the legacy-key compatibility window:** once `list` shows no live unlabelled key on any database, set `LEGACY_UNLABELLED_KEYS = false` and re-register the scanning patterns. The issue is opened at enforce, like the log-only removal.
+- **`RAILWAY_ENVIRONMENT` in `turbo.json` `globalEnv`:** no code reads it any more. Removing it is main's call.
+
 - **Remove log-only:** open the issue at enforce (rollout step 6). It removes `MCP_COMPLETE_KEY_MODE` from `config.ts` and the `turbo.json` `globalEnv` hunk one week after enforcement. The issue number is to be recorded when it exists.
 - **Limit sizing:** `MCP_KEY_INITIAL` (120/60 s, 5,000/day) and the alert thresholds are judgement values. The owner should resize them with `update-limits` (no deploy) once the `threads.client` query numbers are in.
 - **Owner steps outside the repository:** listed under Spec Compliance. The published snippet and MCP setup page locations are pending from the owner.
diff --git a/codev/specs/314-protect-v2-mcp-complete-with-b.md b/codev/specs/314-protect-v2-mcp-complete-with-b.md
index 86d74c0b..2b19c9cb 100644
--- a/codev/specs/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/specs/314-protect-v2-mcp-complete-with-b.md
@@ -1,6 +1,10 @@
 # Specification: Protect `/v2/mcp-complete` with Better Auth API keys issued by apps/auth
 
 > Amendment 1, 2026-11-11, security architect: scenario 2 expired-key row. The api-key plugin deletes an expired key when it is presented, so scenario 2's "each row kept" excludes it. A plugin fact, not a design change; no `ansari-mcp` key can expire (the script refuses `--expir*`).
+>
+> Amendment 2, 2026-11-12, owner (on PR #372; design accepted by the security architect): every service key's prefix names its environment, for WhatsApp and MCP alike: `ansari___`. Reason: the owner asked why the MCP client needed special handling. The client id is thread attribution; the environment in the prefix is key identification, so a leaked key reads as staging or production at a glance and secret scanning can tell them apart. One table in `packages/auth/src/service-users.ts` derives the prefixes, the accepted set, the secret-scanning patterns and the script's pasted-key check. Existing keys are unchanged (the plugin matches the hash; `apikey.prefix` is never rewritten): unlabelled `ansari_wa_` / `ansari_mcp_` keys stay accepted during a compatibility window (`LEGACY_UNLABELLED_KEYS`) and are rotated, never reissued in place. The MCP client-id rule is unchanged.
+>
+> Amendment 3, 2026-11-12, owner (supersedes Amendment 2's `--env` flag): apps/api and apps/auth gain `ENVIRONMENT` (`development` | `staging` | `production`, named to match the frontend's `EXPO_PUBLIC_ENVIRONMENT`). It is required, and `staging` or `production`, under `NODE_ENV=production` (both services refuse to boot otherwise, through the existing boot paths, never at build); it defaults to `development` elsewhere. It replaces `NODE_ENV` (apps/auth) and `RAILWAY_ENVIRONMENT || NODE_ENV` (apps/api) as the Sentry environment. It is the prefix's environment segment verbatim (`ansari_mcp_staging_`; longest `ansari_mcp_development_`, 23 characters, pinned by a test that creates a key with it). The service-keys script reads it from its process env and refuses to run without it. Both key routes serve only a key whose stored prefix names their own service and their own `ENVIRONMENT` (or the legacy bare prefix during the window); any other prefix is their ordinary refusal. Main's conditions (security architect, 2026-11-12): enforcement only on the existing boot paths, Sentry continuity stated in the PR, `ENVIRONMENT` in the `.env.example` and `.env.ci` files, RELEASE.md rows and a deploy-order line, and the unchanged-existing-keys note in the runbook.
 
 ## Problem Statement
 
@@ -394,3 +398,4 @@ Not recommended. If load later demands it, the TTL must stay within the plugin's
 - `apps/api/src/app/api/v2/mcp-complete/route.ts`, `apps/api/lib/auth-service/client.ts`, `apps/api/lib/auth/require-admin.ts`, `apps/api/lib/attribution.ts`.
 - `apps/mcp/src/server/ansari-client.ts`, `apps/mcp/src/server/runtime-config.ts`, `apps/mcp/wrangler.jsonc`.
 - Amendment 1 (2026-11-11, security architect): scenario 2 expired-key row; see the note under the title.
+- Amendments 2 and 3 (2026-11-12, owner): environment in every service-key prefix, and the `ENVIRONMENT` variable; see the notes under the title.
diff --git a/codev/state/spir-314_thread.md b/codev/state/spir-314_thread.md
index b54eed93..c41e03da 100644
--- a/codev/state/spir-314_thread.md
+++ b/codev/state/spir-314_thread.md
@@ -73,3 +73,10 @@
 ## 2026-11-11 review
 - Review written (`codev/reviews/314-protect-v2-mcp-complete-with-b.md`). Spec 314 lessons appended to the spec 329 section of lessons-learned.md (expired key leaves no row; read the published package; count success after the last check; two-sided refusal pin). Hot map line extended; no hot lesson added (at cap).
 - Open owner items carried into the PR: keys per deployment (staging key before apps/api staging deploys, since default is enforce), the snippet and setup page locations, the threads.client numbers for limit sizing, and the log-only removal issue (opened at enforce).
+
+## 2026-11-12 review — owner scope expansion (Amendments 2 and 3)
+- The owner asked on PR #372 why the MCP client needed special handling, then directed: environment in every service-key prefix, for all services, in this PR. First built with an `--env` flag (Amendment 2); the owner then directed an `ENVIRONMENT` var in apps/api + apps/auth, required in production, used as the Sentry environment and verbatim as the prefix segment (Amendment 3). Security relayed both; main set five conditions (boot-path-only enforcement, Sentry continuity, env templates, RELEASE.md rows + deploy order, existing-keys note).
+- Built: `packages/types/src/environment.ts`; both schemas; the script reads ENVIRONMENT (no flag); both routes refuse a key whose stored prefix is not theirs and their environment's (legacy bare prefix accepted while `LEGACY_UNLABELLED_KEYS`); scanning patterns derived from one table.
+- Proof: apps/auth real boot without ENVIRONMENT → "env validation failed for: ENVIRONMENT"; with staging it listens. apps/api `next start` without it → boot check logs the rule, health 500 (Next still prints Ready, as for any boot-check failure); with it, health 503 (no DB). `npm run build` green with ENVIRONMENT unset. Mutation: dropping the env comparison fails 5 tests.
+- Surprise: the runbook's scanning table needs `\|` inside code cells (GFM), so cutover-docs' exact-match test now unescapes before comparing.
+- Railway env names (`staging`/`production`) come from the repo's Railway GitHub Environments, not RELEASE.md.
diff --git a/docs/cutover/deploy-guide.md b/docs/cutover/deploy-guide.md
index d6f40ab2..3d09b2f0 100644
--- a/docs/cutover/deploy-guide.md
+++ b/docs/cutover/deploy-guide.md
@@ -21,7 +21,7 @@ is set at that point. In Railway, applying a variable change **redeploys** the s
 deployment, so the `backend` edits restart the legacy api: make them at a quiet hour the day
 before, and check that `backend` is healthy afterwards. Production values are shown; for staging, use the staging domains.
 
-- **`backend`: add** the four variables below. The new code does not start in production
+- **`backend`: add** the five variables below. The new code does not start in production
   without them.
 
   | Variable | Value |
@@ -30,6 +30,7 @@ before, and check that `backend` is healthy afterwards. Production values are sh
   | `AUTH_JWT_ISSUER` | `https://auth.askansari.ai` (set on its own) |
   | `AUTH_JWT_AUDIENCE` | `ansari-api` (the same as on `auth`) |
   | `AUTH_LAYER_ORIGIN` | `https://api.askansari.ai` (the same as on `auth`) |
+  | `ENVIRONMENT` | `production` (`staging` in staging; #314, also the Sentry environment) |
 
   Also on `backend`: `MAINTENANCE_MODE=false`. **Keep** `JWT_SECRET`,
   `ACCESS_TOKEN_EXPIRY_HOURS`, `REFRESH_TOKEN_EXPIRY_HOURS`, `ADMIN_EMAILS`, `RESEND_API_KEY` and
@@ -49,6 +50,7 @@ before, and check that `backend` is healthy afterwards. Production values are sh
   | `RESEND_API_KEY` | the Resend key (reset emails are now sent by `auth`) |
   | `FRONTEND_URL` | the web origin (reset links point here) |
   | `NODE_ENV` | `production` |
+  | `ENVIRONMENT` | `production` (`staging` in staging; #314: required, and the environment in every service key's prefix) |
   | `PORT` | `3100` |
 
   Optional on `auth`: `SENTRY_DSN`, and `MARKETMAKER_URL` (copy `backend`'s value if it has
diff --git a/docs/cutover/service-keys-runbook.md b/docs/cutover/service-keys-runbook.md
index 87b92b13..cdffd532 100644
--- a/docs/cutover/service-keys-runbook.md
+++ b/docs/cutover/service-keys-runbook.md
@@ -26,7 +26,7 @@ start without it), from `apps/auth/`:
 | Command | Does |
 |---|---|
 | `create-service ` | Creates the service user and its `service` account row, in one transaction. Refuses a second one. |
-| `create-key  --rate-max  --rate-window  --daily  [--name ] [--client-id ]` | Issues a key. Prints the raw key **once**. |
+| `create-key  --rate-max  --rate-window  --daily  [--name ] [--client-id ]` | Issues a key whose prefix names the environment (`ansari___`). Prints the raw key **once**. |
 | `list ` | Lists the service's keys: id, name, enabled, limits, budget left, last request. Never a key or a hash. |
 | `rotate ` (the `create-key` flags) | Issues a second live key beside the current one(s). Prints the new raw key once. |
 | `update-limits  --key  --rate-max  --rate-window  --daily ` | Changes one key's limits in place. |
@@ -40,7 +40,11 @@ and the service name for `create-service`, which has no user yet. `--name` and `
 1 to 64 letters, digits, spaces, dots, underscores and hyphens; a value that looks like a key is
 refused, since both are printed by `list` and sent to Sentry. Without `SENTRY_DSN` every write
 prints the key-log banner and exits 3 (no record is attempted). The script
-prints the database as `hostname:port` only. Limits have no defaults and are checked against the
+prints the database as `hostname:port` only, and under it `ENVIRONMENT`, which the script reads
+from its process env (the auth service's own variable, so the Railway shell has it) and refuses
+to run without (#314 Amendment 3). A new key's prefix carries it: `ansari_wa_production_`,
+`ansari_mcp_staging_`, …, and each environment's routes refuse a key labelled for another, so
+check the two lines agree before `--confirm`. Limits have no defaults and are checked against the
 bounds in `packages/auth/src/limits.ts`; there is no expiry option and no budget without a
 daily refill (a budget that does not refill deletes the key the first time it runs out).
 
@@ -255,8 +259,12 @@ per prefix, with exactly these patterns (the `.source` of `SECRET_SCANNING_PATTE
 
 | Service | Pattern |
 |---|---|
-| `whatsapp` | `ansari_wa_[A-Za-z]{64}` |
-| `ansari-mcp` | `ansari_mcp_[A-Za-z]{64}` |
+| `whatsapp` | `ansari_wa_(?:(?:development\|staging\|production)_)?[A-Za-z]{64}` |
+| `ansari-mcp` | `ansari_mcp_(?:(?:development\|staging\|production)_)?[A-Za-z]{64}` |
+
+These replace the patterns registered before #314 (`ansari_wa_[A-Za-z]{64}` and
+`ansari_mcp_[A-Za-z]{64}`), which miss an environment-labelled key: edit each pattern in place.
+The environment segment is optional while unlabelled keys are live (next paragraph).
 
 When one fires: **revoke the key at once** (`list`, then `revoke`), rotate so the consumer keeps
 working, check the alerts and the key's last request for use you cannot explain, and record it in
@@ -269,6 +277,31 @@ the hash of the whole key, so nothing breaks; but replace it: `rotate whatsapp`
 old organisation pattern (`wa_` followed by 64 letters) registered beside the new ones until the
 last `wa_` key is revoked, then remove it.
 
+**Environment labels (#314 Amendments 2 and 3, owner 2026-11-12).** Keys are now issued as
+`ansari___` followed by 64 letters, where `ENVIRONMENT` is the issuing auth
+service's (`development`, `staging` or `production`). Both routes (the WhatsApp exchange and the
+MCP verify route) serve only a key whose stored prefix names their own service and their own
+`ENVIRONMENT`; any other prefix (another environment's, another service's, a hand-made one) is
+their ordinary refusal (401 / `{"valid":false}`). The only exception is the compatibility window
+below.
+
+**Existing keys are unchanged.** A key's string is fixed when it is created, the plugin matches
+its hash, and `apikey.prefix` is written then and never rewritten. Adding the environment segment
+re-issues nothing: the staging `ansari_wa_` keys keep their format and keep verifying under the
+compatibility window.
+
+**Rotate legacy keys (the compatibility window).** An unlabelled key (`ansari_wa_` or
+`ansari_mcp_` followed directly by 64 letters; `list` shows its `prefix`) is still accepted while
+`LEGACY_UNLABELLED_KEYS` is `true`. Replace it, never reissue it in place: `rotate  …` in
+that environment's auth shell (a labelled key), hand it off to the consumer's variable, then
+`revoke` the old one. Staging has at least one (the
+WhatsApp smoke key). When `list whatsapp` and `list ansari-mcp` show no live unlabelled key on any
+database, retire the legacy form in one change: set `LEGACY_UNLABELLED_KEYS` to `false` in
+`packages/auth/src/service-users.ts` (the routes then refuse the bare prefix, and the script and
+the patterns stop accepting it), deploy, and re-register both patterns with the new `.source`
+(`ansari_wa_(?:development|staging|production)_[A-Za-z]{64}`, likewise for `ansari_mcp_`). The
+follow-up issue that closes the window is opened with this change's enforcement step.
+
 ## The `ansari-mcp` key (#314)
 
 `POST /api/v2/mcp-complete` on apps/api takes an `ansari-mcp` key as `Authorization: Bearer
@@ -285,25 +318,26 @@ nothing persisted and no Gemini call. The design is in
 **One key per MCP deployment** that calls a deployed apps/api, so each can be rotated or
 revoked alone and its traffic is attributed to it:
 
-| Deployment | Who sets its variable | `--client-id` |
-|---|---|---|
-| `mcp.ansari.chat` | the owner (owner-operated, outside this repository) | the owner's choice of `ansari-mcp*` id |
-| `mcp-staging.askansari.ai` (apps/mcp on Railway, see `RELEASE.md`) | the operator, as a Railway service variable | `ansari-mcp-staging` (its `ANSARI_CLIENT`) |
-| each apps/mcp Worker environment in use (apps/mcp's `wrangler.jsonc`) | the operator, as a Worker secret | its `ANSARI_CLIENT`: `ansari-mcp-dev`, `ansari-mcp-beta` or `ansari-mcp-production` |
+| Deployment | Who sets its variable | `--client-id` | Created in |
+|---|---|---|---|
+| `mcp.ansari.chat` | the owner (owner-operated, outside this repository) | the owner's choice of `ansari-mcp*` id | the production auth shell (`ansari_mcp_production_`) |
+| `mcp-staging.askansari.ai` (apps/mcp on Railway, see `RELEASE.md`) | the operator, as a Railway service variable | `ansari-mcp-staging` (its `ANSARI_CLIENT`) | the staging auth shell (`ansari_mcp_staging_`) |
+| each apps/mcp Worker environment in use (apps/mcp's `wrangler.jsonc`) | the operator, as a Worker secret | its `ANSARI_CLIENT`: `ansari-mcp-dev`, `ansari-mcp-beta` or `ansari-mcp-production` | the auth shell of the environment whose apps/api that Worker calls |
 
 1. apps/auth is deployed with the verify route (it ships with this change; there is no new
    migration: `auth.apikey` is spec 329's `0001`).
 2. Once: `create-service ansari-mcp`, then `create-service ansari-mcp --confirm ansari-mcp`.
-3. Per deployment: `create-key ansari-mcp --rate-max 120 --rate-window 60 --daily 5000 --name
-    --client-id `, read the shown user, then repeat with
+3. Per deployment, in the auth shell of the environment it calls: `create-key ansari-mcp
+   --rate-max 120 --rate-window 60 --daily 5000 --name  --client-id `, read the shown user, then repeat with
    `--confirm `. These are the initial values (`MCP_KEY_INITIAL`); see
    [Limits](#limits-1).
 4. Hand the key off (next section) before you do anything else in the shell.
 
 `--client-id` is **required** for `ansari-mcp` and must be `ansari-mcp`, or `ansari-mcp-` and a
 suffix of lowercase letters, digits, dots, underscores and hyphens, 64 characters at most;
-anything else is refused with nothing written. It is what apps/api stores as the thread's
-`client`: a conflicting `X-Ansari-Client` header is ignored (Sentry warning
+anything else is refused with nothing written. The client id is thread attribution; the
+prefix's environment is key identification: they answer different questions and are set apart.
+It is what apps/api stores as the thread's `client`: a conflicting `X-Ansari-Client` header is ignored (Sentry warning
 `mcp-complete client mismatch`).
 
 **Staging order.** `mcp-staging.askansari.ai` sends no key today. Its key is created and set
@@ -313,8 +347,8 @@ without the key, or without `MCP_COMPLETE_KEY_MODE=log-only`, refuses every stag
 ### The handoff
 
 apps/mcp sends `ANSARI_API_AUTHORIZATION` **verbatim** as the `Authorization` header, so the
-value is the whole header: `Bearer ansari_mcp_<64 letters>`, the word `Bearer`, one space, then
-the key. A bare key is no bearer: apps/api answers 401 (verdict `missing` in log-only).
+value is the whole header: `Bearer ansari_mcp__<64 letters>`, the word `Bearer`,
+one space, then the key. A key from another environment's auth shell is refused (401). A bare key is no bearer: apps/api answers 401 (verdict `missing` in log-only).
 
 - **Worker:** from `apps/mcp/`, `wrangler secret put ANSARI_API_AUTHORIZATION --env `, and
   paste the value at its prompt, straight from the shell you created the key in. Never put it on
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index f968df51..169756ae 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -117,13 +117,13 @@ empty-final retry ladder still applies as same-model retries.
 | `ANDROID_MINIMUM_BUILD_VERSION` | `1` | |
 | `ANDROID_LATEST_BUILD_VERSION` | `1` | |
 | `NODE_ENV` | `development` | `development` / `production` / `test` |
+| `ENVIRONMENT` | `development` | The deployment label (#314 Amendment 3): `development`, `staging` or `production`, the same vocabulary as `apps/auth` and the frontend's `EXPO_PUBLIC_ENVIRONMENT`. It is the Sentry environment. **Required when `NODE_ENV=production`**, and then only `staging` or `production`: a production boot without it, or labelled `development`, fails the boot check. `NODE_ENV` keeps its own jobs (test detection, production hardening) |
 
 ### Outside the config schema (direct `process.env` reads)
 
 | Variable | Where used | Notes |
 |----------|-----------|-------|
 | `SENTRY_DSN` | `sentry.*.config.ts` | Optional. Sentry is disabled when unset (and always disabled under test). No user content is ever sent to Sentry |
-| `RAILWAY_ENVIRONMENT` | `sentry.server.config.ts` | Auto-injected by Railway; used as the Sentry environment tag. Falls back to `NODE_ENV`; never set manually |
 | `SENTRY_AUTH_TOKEN` | build-time only | Optional — source-map uploads during `next build`. The build succeeds without it |
 
 ### Provisioning admins
@@ -227,6 +227,13 @@ Verify admins with `grant-admin.ts --list` from `apps/auth/`.
 
 `apps/api`'s own boot check is the environment validation above; it queries nothing.
 
+Both services require `ENVIRONMENT` (`staging` or `production`) when `NODE_ENV=production`
+(#314 Amendment 3): it labels their Sentry events and is the environment segment of every service
+key's prefix (`ansari___`). Set it on each deployed `apps/api` and `apps/auth`
+**before** deploying a version that requires it, or the new deployment fails its boot (on
+Railway, a failed healthcheck keeps the previous deployment serving). Nothing reads it at build
+time.
+
 ### Service keys and the WhatsApp exchange (spec 329)
 
 `apps/auth` issues API keys to services (the WhatsApp service, and `ansari-mcp` for
@@ -235,7 +242,12 @@ Verify admins with `grant-admin.ts --list` from `apps/auth/`.
 plugin's HTTP surface is blocked, so keys are created, listed, rotated, changed and revoked only
 with `apps/auth/scripts/service-keys.ts`, run from `apps/auth/` in the auth service's shell
 (`create-service`, `create-key`, `list`, `rotate`, `update-limits`, `revoke`; every write is
-shown first and confirmed by id). The create and rotate commands print the raw key once.
+shown first and confirmed by id). The create and rotate commands print the raw key once. The
+script reads `ENVIRONMENT` from its process env (it refuses to run without it) and puts it in the
+key's prefix: `ansari___`, e.g. `ansari_wa_production_`. Each route serves
+only a key whose stored prefix names its own service and its own `ENVIRONMENT`, so a key leaked
+from one environment is refused in another; a key issued before #314 (bare `ansari_wa_` /
+`ansari_mcp_`) is still accepted during the compatibility window the runbook describes.
 `docs/cutover/service-keys-runbook.md` is the operator's procedure: issuance, handoff, rotation,
 revocation, the alerts and the eligibility repair.
 
@@ -282,5 +294,5 @@ In `enforce` mode (`MCP_COMPLETE_KEY_MODE`, above) a missing or refused key is `
 (`AUTH_SERVICE_TIMEOUT_MS` in `apps/api/lib/auth-service/client.ts`, 3 s), is `503 {"error":"Authentication service unavailable"}`, with nothing persisted and no
 model call. The thread's `client` is the key's client id; a different `X-Ansari-Client` is
 ignored. The route's per-IP cap (120 a minute) stays. An MCP server built from `apps/mcp` sends
-its `ANSARI_API_AUTHORIZATION` verbatim, so that variable holds `Bearer ` and the key. Issuance,
+its `ANSARI_API_AUTHORIZATION` verbatim, so that variable holds `Bearer ` and the key (`Bearer ansari_mcp__<64 letters>`). Issuance,
 handoff, rollout, limits, alerts and rotation: `docs/cutover/service-keys-runbook.md`.

From 380c43a405af6fbe23eb3156e504a904869d0a1a Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 09:42:37 +1100
Subject: [PATCH 159/435] [Spec 314][Phase: review] fix: keep pre-rename wa_
 WhatsApp keys in the legacy compatibility window (codex)

---
 apps/auth/tests/service-verify.test.ts   |  1 +
 apps/auth/tests/whatsapp-session.test.ts |  8 +++++++-
 docs/cutover/service-keys-runbook.md     |  9 +++++----
 packages/auth/src/service-users.ts       | 17 ++++++++++++++---
 4 files changed, 27 insertions(+), 8 deletions(-)

diff --git a/apps/auth/tests/service-verify.test.ts b/apps/auth/tests/service-verify.test.ts
index 4d81d806..a22d2dcc 100644
--- a/apps/auth/tests/service-verify.test.ts
+++ b/apps/auth/tests/service-verify.test.ts
@@ -384,6 +384,7 @@ describe('the stored prefix (#314 Amendments 2 and 3)', () => {
     ...ENVIRONMENTS.filter((e) => e !== here).map((e) => [`another environment's label (${e})`, `ansari_mcp_${e}_`]),
     ['a foreign prefix', 'evil_'],
     ["a WhatsApp prefix for this environment", serviceUsers.keyPrefix('whatsapp', here)],
+    ["WhatsApp's pre-rename legacy prefix", 'wa_'],
     ['an unknown environment', 'ansari_mcp_qa_'],
     ['no prefix', undefined],
   ])('%s → the same { valid: false }', async (_name, prefix) => {
diff --git a/apps/auth/tests/whatsapp-session.test.ts b/apps/auth/tests/whatsapp-session.test.ts
index 8887af71..ef672dee 100644
--- a/apps/auth/tests/whatsapp-session.test.ts
+++ b/apps/auth/tests/whatsapp-session.test.ts
@@ -286,8 +286,14 @@ describe('key refusals: one byte-identical 401, no rows', () => {
 });
 
 describe('the exchange', () => {
+  it('a pre-rename wa_ key (issued before 2026-10-30) still exchanges during the compatibility window (codex, PR #372)', async () => {
+    const legacy = await createKey({ prefix: 'wa_' });
+    expect(legacy.startsWith('wa_')).toBe(true);
+    expect((await exchange(newBsuid(), newPhone(), { bearer: legacy })).status).toBe(200);
+  });
+
   it.each([...serviceUsers.acceptedKeyPrefixes('whatsapp', HERE)])(
-    'a key with the accepted prefix %s → 200 (this environment\'s label and, while legacy keys live, the bare prefix)',
+    'a key with the accepted prefix %s → 200 (this environment\'s label and, while legacy keys live, the bare and pre-rename wa_ prefixes)',
     async (prefix) => {
       const labelled = await createKey({ prefix });
       expect(labelled.startsWith(prefix)).toBe(true);
diff --git a/docs/cutover/service-keys-runbook.md b/docs/cutover/service-keys-runbook.md
index cdffd532..715f2184 100644
--- a/docs/cutover/service-keys-runbook.md
+++ b/docs/cutover/service-keys-runbook.md
@@ -271,7 +271,7 @@ working, check the alerts and the key's last request for use you cannot explain,
 the key log. Then remove the key from the repository's history; revoking first matters more.
 
 **The prefix change of 2026-10-30.** Keys were first issued as `wa_` followed by 64 letters, and
-are now `ansari_wa_` (and `ansari_mcp_`). A `wa_` key still verifies, because a key is checked by
+are now `ansari_wa_` (and `ansari_mcp_`). A `wa_` key still verifies during the compatibility window below, because a key is checked by
 the hash of the whole key, so nothing breaks; but replace it: `rotate whatsapp` (prints an
 `ansari_wa_` key once), switch the consumer's variable to it, then `revoke` the old key. Keep the
 old organisation pattern (`wa_` followed by 64 letters) registered beside the new ones until the
@@ -290,9 +290,10 @@ its hash, and `apikey.prefix` is written then and never rewritten. Adding the en
 re-issues nothing: the staging `ansari_wa_` keys keep their format and keep verifying under the
 compatibility window.
 
-**Rotate legacy keys (the compatibility window).** An unlabelled key (`ansari_wa_` or
-`ansari_mcp_` followed directly by 64 letters; `list` shows its `prefix`) is still accepted while
-`LEGACY_UNLABELLED_KEYS` is `true`. Replace it, never reissue it in place: `rotate  …` in
+**Rotate legacy keys (the compatibility window).** An unlabelled key (`ansari_wa_`, `ansari_mcp_`,
+or WhatsApp's pre-rename `wa_`, followed directly by 64 letters; `list` shows its `prefix`) is
+still accepted while `LEGACY_UNLABELLED_KEYS` is `true` (`LEGACY_PREFIXES` in
+`service-users.ts`). Replace it, never reissue it in place: `rotate  …` in
 that environment's auth shell (a labelled key), hand it off to the consumer's variable, then
 `revoke` the old one. Staging has at least one (the
 WhatsApp smoke key). When `list whatsapp` and `list ansari-mcp` show no live unlabelled key on any
diff --git a/packages/auth/src/service-users.ts b/packages/auth/src/service-users.ts
index feb1aa98..75b64a2e 100644
--- a/packages/auth/src/service-users.ts
+++ b/packages/auth/src/service-users.ts
@@ -64,15 +64,26 @@ export const LEGACY_UNLABELLED_KEYS = true;
 
 /**
  * The prefixes a route of `service` running as `environment` accepts: that
- * environment's, plus the bare legacy prefix while LEGACY_UNLABELLED_KEYS
- * holds. Any other stored prefix (another environment's, another service's, a
+ * environment's, plus the legacy unlabelled prefixes (LEGACY_PREFIXES) while
+ * LEGACY_UNLABELLED_KEYS holds. Any other stored prefix (another environment's, another service's, a
  * hand-made one) is the route's ordinary refusal.
  */
 export function acceptedKeyPrefixes(service: ServiceName, environment: Environment): readonly string[] {
   const own = keyPrefix(service, environment);
-  return LEGACY_UNLABELLED_KEYS ? [own, SERVICES[service].prefix] : [own];
+  return LEGACY_UNLABELLED_KEYS ? [own, ...LEGACY_PREFIXES[service]] : [own];
 }
 
+/**
+ * The unlabelled prefixes keys were issued with before #314, per service: the
+ * bare base prefix, and for WhatsApp also `wa_`, the prefix before the
+ * 2026-10-30 rename (the runbook's "prefix change"), since a live `wa_` key
+ * cannot be ruled out. Accepted only while LEGACY_UNLABELLED_KEYS holds.
+ */
+export const LEGACY_PREFIXES: Readonly> = {
+  whatsapp: ['ansari_wa_', 'wa_'],
+  'ansari-mcp': ['ansari_mcp_'],
+};
+
 /** True when a verified key's stored prefix is one `service`'s route in `environment` accepts. */
 export function isAcceptedKeyPrefix(service: ServiceName, environment: Environment, prefix: unknown): boolean {
   return typeof prefix === 'string' && acceptedKeyPrefixes(service, environment).includes(prefix);

From 512e7170a647f71b8054be2b2670a0cd7b88e2c2 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 09:42:37 +1100
Subject: [PATCH 160/435] [Spec 314] chore: drop RAILWAY_ENVIRONMENT from
 turbo.json globalEnv; nothing reads it now (main)

---
 turbo.json | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/turbo.json b/turbo.json
index 24678ab4..4dc89b00 100644
--- a/turbo.json
+++ b/turbo.json
@@ -78,7 +78,7 @@
   //      (apps/auth's env; apps/auth reads nothing else).
   //   2. STATIC reads:  grep -rn "process\.env\.[A-Z]" apps packages
   //      (DATABASE_URL in both drizzle configs, NEXT_RUNTIME, NODE_ENV,
-  //       RAILWAY_ENVIRONMENT, SENTRY_DSN, VITEST)
+  //       ENVIRONMENT in sentry.server.config.ts, SENTRY_DSN, VITEST)
   //   3. DYNAMIC reads: grep -rn "process\.env\[" apps  — then follow each
   //      call site to the string literals passed in. A static `process.env.X`
   //      pattern CANNOT see `process.env[name]`, and the failure is silent: the
@@ -159,7 +159,6 @@
     "FRONTEND_URL",
     "MARKETMAKER_URL",
     "NEXT_RUNTIME",
-    "RAILWAY_ENVIRONMENT",
     "RESEND_API_KEY",
     "SENTRY_DSN",
     // Build-time only, consumed by withSentryConfig (not by our source) for

From a5fb8cf6c0723bde5cb3cb28c803c9d379def748 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 09:49:10 +1100
Subject: [PATCH 161/435] [Spec 314][Phase: review] fix: derived legacy
 scanning pattern for wa_ keys; key script's Sentry environment is ENVIRONMENT
 (codex)

---
 apps/auth/scripts/service-keys.ts           | 15 +++++++++++---
 apps/auth/tests/service-keys-no-dsn.test.ts | 20 ++++++++++++++++---
 apps/auth/tests/service-keys.test.ts        | 22 +++++++++++++++++++++
 docs/cutover/service-keys-runbook.md        |  5 +++--
 packages/auth/src/service-users.ts          | 19 ++++++++++++++++++
 5 files changed, 73 insertions(+), 8 deletions(-)

diff --git a/apps/auth/scripts/service-keys.ts b/apps/auth/scripts/service-keys.ts
index 96e5d951..df45a04a 100644
--- a/apps/auth/scripts/service-keys.ts
+++ b/apps/auth/scripts/service-keys.ts
@@ -555,10 +555,19 @@ export const unrecordedRecorder: Recorder = {
   reason: 'SENTRY_DSN is not set: no record was attempted.',
 };
 
+/**
+ * The script's Sentry init: its events carry ENVIRONMENT, like apps/auth's own
+ * (#314 Amendment 3), never NODE_ENV, which is `production` on staging too. An
+ * absent ENVIRONMENT never reaches a write: serviceKeys refuses to run first.
+ */
+export function scriptSentryInit(dsn: string, environment: string | undefined) {
+  return { dsn, environment: environment ?? 'development', ...SCRIPT_SENTRY_OPTIONS };
+}
+
 /** The script's recorder: Sentry when a DSN is set (initialised here), otherwise none. */
-export function scriptRecorder(dsn: string | undefined): Recorder {
+export function scriptRecorder(dsn: string | undefined, environment: string | undefined): Recorder {
   if (!dsn) return unrecordedRecorder;
-  Sentry.init({ dsn, environment: process.env.NODE_ENV ?? 'development', ...SCRIPT_SENTRY_OPTIONS });
+  Sentry.init(scriptSentryInit(dsn, environment));
   return sentryRecorder;
 }
 
@@ -664,7 +673,7 @@ export function printLine(line: string): void {
 }
 
 async function main(): Promise {
-  const recorder = scriptRecorder(process.env.SENTRY_DSN);
+  const recorder = scriptRecorder(process.env.SENTRY_DSN, process.env.ENVIRONMENT);
   const { exitCode } = await serviceKeys(process.argv.slice(2), {
     databaseUrl: process.env.DATABASE_URL,
     environment: process.env.ENVIRONMENT,
diff --git a/apps/auth/tests/service-keys-no-dsn.test.ts b/apps/auth/tests/service-keys-no-dsn.test.ts
index d1f88f20..d48f621c 100644
--- a/apps/auth/tests/service-keys-no-dsn.test.ts
+++ b/apps/auth/tests/service-keys-no-dsn.test.ts
@@ -3,9 +3,9 @@
 // test shows the unrecorded path is taken on purpose, not because an
 // uninitialised Sentry's flush happens to answer false.
 import * as Sentry from '@sentry/node';
-import { afterAll, beforeAll, expect, it } from 'vitest';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
 
-import { EXIT_UNRECORDED, scriptRecorder, serviceKeys, unrecordedRecorder } from '../scripts/service-keys';
+import { EXIT_UNRECORDED, scriptRecorder, scriptSentryInit, serviceKeys, unrecordedRecorder } from '../scripts/service-keys';
 import { startService, type Service } from './helpers/service';
 
 let service: Service;
@@ -31,7 +31,7 @@ async function run(argv: string[], recorder: ReturnType)
 
 it('no DSN: nothing is captured or flushed; the write stands, the banner names the key id, exit 3', async () => {
   expect(Sentry.getClient()).toBeUndefined();
-  const recorder = scriptRecorder(undefined);
+  const recorder = scriptRecorder(undefined, 'staging');
   expect(recorder).toBe(unrecordedRecorder);
   expect(Sentry.getClient()).toBeUndefined();
 
@@ -59,3 +59,17 @@ it('no DSN: nothing is captured or flushed; the write stands, the banner names t
   // the old implicit path (an uninitialised flush answering false) never printed.
   expect(Sentry.getClient()).toBeUndefined();
 });
+
+describe('the script\'s Sentry environment (#314 Amendment 3, codex)', () => {
+  it('is ENVIRONMENT, never NODE_ENV', () => {
+    const before = process.env.NODE_ENV;
+    process.env.NODE_ENV = 'production';
+    try {
+      expect(scriptSentryInit('https://public@o0.ingest.sentry.io/0', 'staging').environment).toBe('staging');
+      expect(scriptSentryInit('https://public@o0.ingest.sentry.io/0', 'production').environment).toBe('production');
+    } finally {
+      process.env.NODE_ENV = before;
+    }
+  });
+});
+
diff --git a/apps/auth/tests/service-keys.test.ts b/apps/auth/tests/service-keys.test.ts
index 2edf974b..fcd103ef 100644
--- a/apps/auth/tests/service-keys.test.ts
+++ b/apps/auth/tests/service-keys.test.ts
@@ -3,6 +3,8 @@
 // posture, against the auth database on pglite. Script functions are driven
 // directly; Sentry through a spy transport.
 import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
 
 import * as Sentry from '@sentry/node';
 import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -831,6 +833,26 @@ describe('SECRET_SCANNING_PATTERNS', () => {
     }
   });
 
+  it('every prefix a route accepts, in any environment, is caught by the main or a legacy pattern (codex, PR #372)', () => {
+    const body = 'Q'.repeat(64);
+    for (const name of Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[]) {
+      const patterns = [serviceUsers.SECRET_SCANNING_PATTERNS[name], ...serviceUsers.LEGACY_SCANNING_PATTERNS[name]];
+      const accepted = new Set(ENVIRONMENTS.flatMap((e) => serviceUsers.acceptedKeyPrefixes(name, e)));
+      for (const prefix of accepted) {
+        expect(patterns.some((p) => p.test(`${prefix}${body}`)), `${name} ${prefix}`).toBe(true);
+      }
+    }
+    expect(serviceUsers.LEGACY_SCANNING_PATTERNS.whatsapp.map((p) => p.source)).toEqual(['wa_[A-Za-z]{64}']);
+    expect(serviceUsers.LEGACY_SCANNING_PATTERNS['ansari-mcp']).toEqual([]);
+  });
+
+  it('the runbook names every legacy pattern by its source', () => {
+    const runbook = readFileSync(fileURLToPath(new URL('../../../docs/cutover/service-keys-runbook.md', import.meta.url)), 'utf8');
+    for (const pattern of Object.values(serviceUsers.LEGACY_SCANNING_PATTERNS).flat()) {
+      expect(runbook).toContain(`\`${pattern.source}\``);
+    }
+  });
+
   it('keyPrefix is ansari___ for every service and environment, all distinct', () => {
     const all = (Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[]).flatMap((name) =>
       ENVIRONMENTS.map((env) => serviceUsers.keyPrefix(name, env))
diff --git a/docs/cutover/service-keys-runbook.md b/docs/cutover/service-keys-runbook.md
index 715f2184..42dfc1e5 100644
--- a/docs/cutover/service-keys-runbook.md
+++ b/docs/cutover/service-keys-runbook.md
@@ -274,8 +274,9 @@ the key log. Then remove the key from the repository's history; revoking first m
 are now `ansari_wa_` (and `ansari_mcp_`). A `wa_` key still verifies during the compatibility window below, because a key is checked by
 the hash of the whole key, so nothing breaks; but replace it: `rotate whatsapp` (prints an
 `ansari_wa_` key once), switch the consumer's variable to it, then `revoke` the old key. Keep the
-old organisation pattern (`wa_` followed by 64 letters) registered beside the new ones until the
-last `wa_` key is revoked, then remove it.
+old organisation pattern (`wa_[A-Za-z]{64}`, the `.source` of `LEGACY_SCANNING_PATTERNS.whatsapp`
+in `service-users.ts`) registered beside the new ones until the last `wa_` key is revoked, then
+remove it.
 
 **Environment labels (#314 Amendments 2 and 3, owner 2026-11-12).** Keys are now issued as
 `ansari___` followed by 64 letters, where `ENVIRONMENT` is the issuing auth
diff --git a/packages/auth/src/service-users.ts b/packages/auth/src/service-users.ts
index 75b64a2e..efcf87ba 100644
--- a/packages/auth/src/service-users.ts
+++ b/packages/auth/src/service-users.ts
@@ -110,6 +110,25 @@ export const SECRET_SCANNING_PATTERNS: Readonly> = {
   'ansari-mcp': scanningPattern('ansari-mcp'),
 };
 
+/**
+ * The extra patterns the legacy window needs, derived from LEGACY_PREFIXES: one
+ * per legacy prefix that the main pattern does not already cover (today only
+ * WhatsApp's pre-rename `wa_`). Registered beside the main ones until the
+ * window closes; empty once LEGACY_UNLABELLED_KEYS is false. Every prefix a
+ * route accepts is caught by one of the two lists (tested).
+ */
+export const LEGACY_SCANNING_PATTERNS: Readonly> = {
+  whatsapp: legacyScanningPatterns('whatsapp'),
+  'ansari-mcp': legacyScanningPatterns('ansari-mcp'),
+};
+
+function legacyScanningPatterns(service: ServiceName): RegExp[] {
+  if (!LEGACY_UNLABELLED_KEYS) return [];
+  return LEGACY_PREFIXES[service]
+    .filter((prefix) => prefix !== SERVICES[service].prefix)
+    .map((prefix) => new RegExp(`${prefix}${KEY_BODY}`));
+}
+
 export type ServiceUser = { id: string; email: string; createdAt: Date };
 
 export type ServiceUserLookup =

From c0a803215e83fee089276d8e37d22a1a5490bcb2 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 09:49:10 +1100
Subject: [PATCH 162/435] [Spec 314] Review rounds 3-4: consultation outputs,
 rebuttals, review record

---
 .../314-review-iter3-codex.txt                | 31 +++++++++++++++++++
 .../314-review-iter3-context.md               | 10 ++++++
 .../314-review-iter3-gemini-skipped.txt       | 10 ++++++
 .../314-review-iter3-gemini.txt               | 19 ++++++++++++
 .../314-review-iter3-rebuttals.md             | 18 +++++++++++
 .../314-review-iter4-codex.txt                | 26 ++++++++++++++++
 .../314-review-iter4-context.md               |  6 ++++
 .../314-review-iter4-rebuttals.md             | 15 +++++++++
 .../314-protect-v2-mcp-complete-with-b.md     | 27 ++++++++++++++--
 9 files changed, 160 insertions(+), 2 deletions(-)
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-context.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-gemini-skipped.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-gemini.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-rebuttals.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-context.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-rebuttals.md

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-codex.txt
new file mode 100644
index 00000000..e4c1967e
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-codex.txt
@@ -0,0 +1,31 @@
+---
+VERDICT: REQUEST_CHANGES
+SUMMARY: Prefix enforcement is sound, but it silently rejects a documented legacy key format.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- `acceptedKeyPrefixes()` accepts only environment-labelled and bare `ansari_wa_` keys, while `docs/cutover/service-keys-runbook.md:273-278` states older `wa_` keys still verify until rotated. Such keys now receive 401. Either include `wa_` in the compatibility window or confirm none remain and update the runbook/deploy prerequisites.
+- The branch is 9 commits behind `develop`; update it before merge. There is no changed-file overlap with those commits.
+
+PR_SUMMARY: |
+  ## Summary
+  Protects `/api/v2/mcp-complete` with environment-labelled service keys verified through apps/auth. Adds deployment-environment validation, Sentry labelling, key attribution, rollout controls, and operational documentation.
+
+  ## Key Changes
+  - Adds MCP service-key verification and fail-closed route authorization.
+  - Adds `ENVIRONMENT` enforcement and environment-specific service-key prefixes.
+  - Adds comprehensive route, boot, script, leak, and prefix tests.
+
+  ## Test Plan
+  - Run the full build and non-E2E test suite.
+  - Verify production boot rejection without a valid `ENVIRONMENT`.
+  - Test labelled, cross-environment, bare legacy, and older `wa_` key behavior.
+
+---
+
+## ⚠️ WORKING TREE CHANGED during the codex review (#1649).
+A consultant reviews the tree; it must never write to it. 1 path changed while this lane was running:
+  - turbo.json
+Check `git status` and `git diff` before trusting this review or shipping the branch.
+Note: under cmap the lanes run concurrently in one worktree, so another lane — or you —
+may be the writer. This warning names what moved, not who moved it.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-context.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-context.md
new file mode 100644
index 00000000..13868ad3
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-context.md
@@ -0,0 +1,10 @@
+# PR #372 re-review (iteration 3): owner scope expansion
+
+Iterations 1-2 approved the original change (iter1 codex's bearer-envelope fix landed in d88eb58e). Since then the owner widened scope during review (spec Amendments 2 and 3, under the spec's title), built as review-phase commits 2977d3d0 and 7f3ab68d:
+
+- `ENVIRONMENT` (development|staging|production) in apps/api and apps/auth Zod schemas; required and staging/production under NODE_ENV=production, enforced only on the existing boot paths; the Sentry environment of both services.
+- Every service-key prefix names its environment: `ansari___`. The service-keys script reads ENVIRONMENT from its process env (no flag) and refuses without it.
+- The WhatsApp exchange and the MCP verify route refuse, with their ordinary refusal, any verified key whose stored `apikey.prefix` is not their own service's and own ENVIRONMENT's; the legacy bare prefix is accepted while `LEGACY_UNLABELLED_KEYS` holds.
+- turbo.json globalEnv, env templates, RELEASE.md, runbook, self-hosting, deploy guide.
+
+Please review the whole PR, focusing on the new commits: correctness of the boot enforcement (never at build), the route prefix check, the derived scanning patterns, test coverage, and doc consistency.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-gemini-skipped.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-gemini-skipped.txt
new file mode 100644
index 00000000..610eddda
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-gemini-skipped.txt
@@ -0,0 +1,10 @@
+---
+VERDICT: COMMENT
+SUMMARY: Gemini lane skipped — agy exited with code 3
+CONFIDENCE: LOW
+---
+
+The Gemini (Antigravity `agy`) reviewer was skipped: agy exited with code 3.
+This is a non-blocking skip; the remaining reviewers still apply. To enable the
+Gemini lane, install the CLI (https://antigravity.google/cli/install.sh) and run
+`agy` once to sign in.
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-gemini.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-gemini.txt
new file mode 100644
index 00000000..65f50972
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-gemini.txt
@@ -0,0 +1,19 @@
+---
+VERDICT: COMMENT
+SUMMARY: Gemini lane skipped — agy exited with code 3
+CONFIDENCE: LOW
+---
+
+The Gemini (Antigravity `agy`) reviewer was skipped: agy exited with code 3.
+This is a non-blocking skip; the remaining reviewers still apply. To enable the
+Gemini lane, install the CLI (https://antigravity.google/cli/install.sh) and run
+`agy` once to sign in.
+
+---
+
+## ⚠️ WORKING TREE CHANGED during the gemini review (#1649).
+A consultant reviews the tree; it must never write to it. 1 path changed while this lane was running:
+  - codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-rebuttals.md
+Check `git status` and `git diff` before trusting this review or shipping the branch.
+Note: under cmap the lanes run concurrently in one worktree, so another lane — or you —
+may be the writer. This warning names what moved, not who moved it.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-rebuttals.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-rebuttals.md
new file mode 100644
index 00000000..e1d04cbe
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter3-rebuttals.md
@@ -0,0 +1,18 @@
+# Review (PR #372), iteration 3 (after the owner's Amendments 2 and 3): responses
+
+## Codex (REQUEST_CHANGES)
+
+1. **Pre-rename `wa_` keys would now be refused (401), though the runbook says they still verify.** Accepted and fixed.
+   - Nobody can confirm that no live `wa_` key remains, so `wa_` joins the compatibility window instead of being refused.
+   - `LEGACY_PREFIXES` in `service-users.ts` is `{ whatsapp: ['ansari_wa_', 'wa_'], 'ansari-mcp': ['ansari_mcp_'] }`, accepted only while `LEGACY_UNLABELLED_KEYS` holds.
+   - New explicit test: a `wa_` key exchanges, written independently of the list (removing `wa_` from the list fails it). The MCP verify route refuses `wa_`.
+   - Runbook: both the prefix-change paragraph and the "Rotate legacy keys" step name `wa_`.
+2. **The branch is 9 commits behind `develop`.** Rebased onto `origin/develop` with no conflicts; develop's changes touch only `apps/mcp/test/*`. Build, typecheck, lint and the full suite pass after the rebase.
+
+## Gemini (COMMENT: lane skipped)
+
+The first run did not review: `agy` exited with code 3 (output kept as `314-review-iter3-gemini-skipped.txt`). It was re-run against the pushed branch; see `314-review-iter3-gemini.txt`.
+
+## Also in this iteration (main, via the security architect)
+
+`RAILWAY_ENVIRONMENT` is removed from `turbo.json` `globalEnv`, and the static-read comment now lists `ENVIRONMENT` in its place. Nothing reads `RAILWAY_ENVIRONMENT` any more.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-codex.txt
new file mode 100644
index 00000000..6a15f610
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-codex.txt
@@ -0,0 +1,26 @@
+---
+VERDICT: REQUEST_CHANGES
+SUMMARY: Both requested code fixes landed, but the PR is again behind develop and has unresolved documentation/security consistency issues.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- `wa_` compatibility is correctly implemented and explicitly exchange-tested. However, `SECRET_SCANNING_PATTERNS.whatsapp` ignores `LEGACY_PREFIXES`, so its canonical pattern does not detect accepted `wa_<64 letters>` keys, contradicting the spec’s single-derived-table invariant and comments in `service-users.ts`.
+- `RAILWAY_ENVIRONMENT` is correctly removed from `turbo.json`. The branch was rebased, but `develop` subsequently advanced by eight commits (PR #376), so it is no longer current.
+- The committed review document does not contain the iteration-3 resolution. Its update, rebuttal, and consultation artifacts remain uncommitted, leaving the PR’s review record incomplete.
+- `apps/auth/scripts/service-keys.ts:561` still initializes Sentry with `NODE_ENV`, not `ENVIRONMENT`. Operator events in staging therefore remain labelled `production`, contrary to Amendment 3’s Sentry-environment requirement.
+
+PR_SUMMARY: |
+  ## Summary
+  Protects `/api/v2/mcp-complete` with environment-labelled `ansari-mcp` service keys verified through apps/auth. It adds fail-closed enforcement, rollout logging, trusted key attribution, operational tooling, and deployment documentation.
+
+  ## Key Changes
+  - Adds the apps/auth service-key verification route and MCP key lifecycle support.
+  - Gates GET and POST MCP completion requests with enforce/log-only modes.
+  - Adds environment-labelled prefixes while temporarily supporting legacy keys.
+  - Documents issuance, deployment, monitoring, rotation, and migration.
+
+  ## Test Plan
+  - Rebase onto current `develop` and run the full build and non-E2E test suite.
+  - Verify legacy `wa_`, unlabelled, labelled, and cross-environment key behavior.
+  - Test canonical secret-scanning patterns against every accepted legacy prefix.
+  - Confirm service-key script Sentry events use `ENVIRONMENT`.
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-context.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-context.md
new file mode 100644
index 00000000..190ca5d8
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-context.md
@@ -0,0 +1,6 @@
+# PR #372 re-review (iteration 4)
+
+Iteration 3 (codex REQUEST_CHANGES) asked for two things:
+(1) Pre-rename `wa_` keys would now be refused. Fixed: `LEGACY_PREFIXES` puts `wa_` in the WhatsApp compatibility window, with an explicit exchange test and runbook updates.
+(2) Rebase onto develop. Done, no conflicts.
+Main also had `RAILWAY_ENVIRONMENT` removed from turbo.json globalEnv. See 314-review-iter3-rebuttals.md. Please confirm both fixes and review the whole PR.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-rebuttals.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-rebuttals.md
new file mode 100644
index 00000000..80d119a0
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter4-rebuttals.md
@@ -0,0 +1,15 @@
+# Review (PR #372), iteration 4: responses
+
+## Codex (REQUEST_CHANGES)
+
+1. **`SECRET_SCANNING_PATTERNS.whatsapp` ignores `LEGACY_PREFIXES`, so an accepted `wa_` key goes undetected.** Accepted.
+   - `LEGACY_SCANNING_PATTERNS` is derived from `LEGACY_PREFIXES`, minus the prefixes the main pattern already covers. Today that is `{ whatsapp: [/wa_[A-Za-z]{64}/], 'ansari-mcp': [] }`, and it is empty once the window closes.
+   - New tests: every prefix any route accepts, in any environment, is caught by the main pattern or a legacy one; and the runbook names each legacy pattern by its exact source. Emptying the WhatsApp list fails the first.
+   - The main patterns are unchanged, because their sources are what the owner registers in the runbook's table.
+2. **`develop` advanced again (PR #376).** Rebased again.
+3. **The review document lacked iteration 3, and its artifacts were uncommitted.** Committed with this iteration: the iteration 3 and 4 outputs and rebuttals, and the review's consultation section.
+4. **`service-keys.ts` initialised Sentry with `NODE_ENV`.** Fixed. `scriptSentryInit(dsn, environment)` uses `ENVIRONMENT`, and `main` passes `process.env.ENVIRONMENT`. A test pins it under `NODE_ENV=production`.
+
+## Gemini
+
+Skipped twice: `agy` exits with code 3 (not installed or not signed in on this machine). No Gemini verdict exists for iterations 3 and 4.
diff --git a/codev/reviews/314-protect-v2-mcp-complete-with-b.md b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
index 3df9965e..9cad8273 100644
--- a/codev/reviews/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
@@ -135,7 +135,30 @@ No concerns raised. Approved in both rounds.
 #### Gemini
 No concerns raised. Approved.
 
-No `CONSULT_ERROR` occurred in any round.
+### Review / PR #372 (Round 2)
+Codex and Gemini approved with no issues.
+
+### Review / PR #372 (Round 3, after Amendments 2 and 3; run by hand on the security architect's porch route)
+
+#### Codex (REQUEST_CHANGES)
+- **Concern**: keys from before the 2026-10-30 prefix rename (`wa_`) would now be refused with 401, although the runbook says they still verify → **Addressed**: `wa_` joins the compatibility window (`LEGACY_PREFIXES`), with an explicit test written independently of the list and both runbook passages updated.
+- **Concern**: the branch was 9 commits behind `develop` → **Addressed**: rebased with no conflicts; develop's changes touch only `apps/mcp/test/*`. Everything passes after the rebase.
+
+#### Gemini
+- First run: **CONSULT_ERROR** (the `agy` CLI exited with code 3; the lane was skipped). Re-run against the pushed branch; its outcome is in `314-review-iter3-gemini.txt`.
+
+### Review / PR #372 (Round 4, codex only)
+
+#### Codex (REQUEST_CHANGES)
+- **Concern**: the scanning patterns ignored the accepted `wa_` prefix → **Addressed**: `LEGACY_SCANNING_PATTERNS` is derived from `LEGACY_PREFIXES`. Tests check that every accepted prefix is caught and that the runbook names each legacy source.
+- **Concern**: `develop` advanced again (PR #376) → **Addressed**: rebased.
+- **Concern**: the iteration-3 review record was uncommitted → **Addressed**: committed.
+- **Concern**: the key script's Sentry still used `NODE_ENV` → **Addressed**: `scriptSentryInit` uses `ENVIRONMENT`, pinned by a test.
+
+#### Gemini
+- **CONSULT_ERROR** in rounds 3 and 4: the `agy` CLI exits with code 3, so the lane is skipped. The owner can restore it by running `agy` once to sign in.
+
+Apart from those Gemini skips, no `CONSULT_ERROR` occurred.
 
 ## Lessons Learned
 
@@ -196,7 +219,7 @@ Neither test was skipped. Both are pre-existing, outside this change, and passed
 
 ## Follow-up Items
 
-- **Close the legacy-key compatibility window:** once `list` shows no live unlabelled key on any database, set `LEGACY_UNLABELLED_KEYS = false` and re-register the scanning patterns. The issue is opened at enforce, like the log-only removal.
+- **Close the legacy-key compatibility window:** once `list` shows no live unlabelled key (`ansari_wa_`, `ansari_mcp_`, or pre-rename `wa_`) on any database, set `LEGACY_UNLABELLED_KEYS = false` and re-register the scanning patterns. The issue is opened at enforce, like the log-only removal.
 - **`RAILWAY_ENVIRONMENT` in `turbo.json` `globalEnv`:** no code reads it any more. Removing it is main's call.
 
 - **Remove log-only:** open the issue at enforce (rollout step 6). It removes `MCP_COMPLETE_KEY_MODE` from `config.ts` and the `turbo.json` `globalEnv` hunk one week after enforcement. The issue number is to be recorded when it exists.

From b9391cc7128df22ef717651d2535b5159a6ccc26 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 09:52:59 +1100
Subject: [PATCH 163/435] [Spec 314] owner directive: no RAILWAY_* reads;
 .env.example names ENVIRONMENT as the Sentry environment

---
 apps/api/.env.example                               | 2 +-
 codev/reviews/314-protect-v2-mcp-complete-with-b.md | 4 ++--
 codev/specs/314-protect-v2-mcp-complete-with-b.md   | 2 +-
 3 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/apps/api/.env.example b/apps/api/.env.example
index 996e1fa6..274e1d19 100644
--- a/apps/api/.env.example
+++ b/apps/api/.env.example
@@ -73,7 +73,7 @@ USUL_BASE_URL=https://api.usul.ai/v1/vector-search
 # Sentry
 SENTRY_DSN=https://examplePublicKey@o0.ingest.sentry.io/0
 SENTRY_AUTH_TOKEN=sntrys_...  # Optional — for source map uploads in production builds
-# The Sentry environment tag is ENVIRONMENT (below), not Railway's RAILWAY_ENVIRONMENT (#314).
+# ENVIRONMENT (below) is the Sentry environment (#314).
 
 # IslamicMMLU leaderboard bearer token for /api/v1/chat/completions (Spec 19).
 # Optional — when unset the OpenAI-compat endpoint returns 503. Generate with `openssl rand -hex 32`.
diff --git a/codev/reviews/314-protect-v2-mcp-complete-with-b.md b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
index 9cad8273..c33e9342 100644
--- a/codev/reviews/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
@@ -55,6 +55,7 @@
   - Security architect order (04:10Z): `alerts.keyVerified()` moved after the owner and client-id checks in `service-verify.ts`, so only a served key counts toward the volume alerts. A test pins the order and fails under the old one. The WhatsApp exchange order is unchanged.
 - **Phase 5:** rebased onto develop (#365, #368, #370) first. #366 had changed the attribution link to `askansari.ai`, so scenario 4's expectation followed it in its own commit. Architect orders added the `mcp-staging` key, the `Bearer` form in all three apps/mcp docs, and the RELEASE.md staging row.
 - **Review (PR consult):** the route checks the bearer token's shape (printable ASCII, 1–256 characters, apps/auth's bound) before calling apps/auth. The plan's bearer rule (one token, no whitespace) let an over-long or non-ASCII token through, and apps/auth's 400 turned it into a 503.
+- **Owner directive (2026-11-12, via main): no code reads `RAILWAY_*` variables, only our own names.** `RAILWAY_ENVIRONMENT` is gone from `turbo.json` `globalEnv` and from its comment, and nothing in apps/api, apps/auth or packages reads `RAILWAY_*`. (apps/mcp's `RAILWAY_GIT_COMMIT_SHA` fallback belongs to main. The `RAILWAY_ENVIRONMENT_NAME` fixture in `apps/auth/tests/cutover/copy.test.ts` checks that the cutover script ignores Railway's variables.)
 - **Review phase, Amendments 2 and 3 (owner, 2026-11-12):** the owner asked on the PR why the MCP client needed special handling, then directed that every service key's prefix carry its environment.
   - The first design took the environment from an `--env` flag, with routes that would never compare the label to their own environment.
   - The owner then directed an `ENVIRONMENT` variable (Amendment 3). With it, the script reads the environment from its process env, the label is the environment's own name, and each route compares the prefix to its own environment. That turns the label into real hardening.
@@ -207,7 +208,7 @@ Apart from those Gemini skips, no `CONSULT_ERROR` occurred.
 
 ## Sentry environment continuity (Amendment 3)
 
-- **apps/api** sent `RAILWAY_ENVIRONMENT || NODE_ENV`, and now sends `ENVIRONMENT`. Railway's environment names are `staging` and `production`, so with `ENVIRONMENT` set to match, api events keep the same labels. RELEASE.md does not state these names; they come from the repository's Railway-created GitHub Environments (`ansari-backend / staging`, `ansari-backend / production`).
+- **apps/api** sent `RAILWAY_ENVIRONMENT || NODE_ENV`, and now sends `ENVIRONMENT`. The owner set `ENVIRONMENT` on `backend` and auth in staging and production (2026-11-12), so checking it against Railway's environment names no longer matters.
 - **apps/auth** sent `NODE_ENV`, which is `production` on both staging and production. Today its staging events are therefore labelled `production`. After this change they are labelled `staging`. This is a deliberate correction, and the owner should check the auth Sentry project's alert rules and filters.
 
 ## Flaky Tests
@@ -220,7 +221,6 @@ Neither test was skipped. Both are pre-existing, outside this change, and passed
 ## Follow-up Items
 
 - **Close the legacy-key compatibility window:** once `list` shows no live unlabelled key (`ansari_wa_`, `ansari_mcp_`, or pre-rename `wa_`) on any database, set `LEGACY_UNLABELLED_KEYS = false` and re-register the scanning patterns. The issue is opened at enforce, like the log-only removal.
-- **`RAILWAY_ENVIRONMENT` in `turbo.json` `globalEnv`:** no code reads it any more. Removing it is main's call.
 
 - **Remove log-only:** open the issue at enforce (rollout step 6). It removes `MCP_COMPLETE_KEY_MODE` from `config.ts` and the `turbo.json` `globalEnv` hunk one week after enforcement. The issue number is to be recorded when it exists.
 - **Limit sizing:** `MCP_KEY_INITIAL` (120/60 s, 5,000/day) and the alert thresholds are judgement values. The owner should resize them with `update-limits` (no deploy) once the `threads.client` query numbers are in.
diff --git a/codev/specs/314-protect-v2-mcp-complete-with-b.md b/codev/specs/314-protect-v2-mcp-complete-with-b.md
index 2b19c9cb..0ed8db37 100644
--- a/codev/specs/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/specs/314-protect-v2-mcp-complete-with-b.md
@@ -4,7 +4,7 @@
 >
 > Amendment 2, 2026-11-12, owner (on PR #372; design accepted by the security architect): every service key's prefix names its environment, for WhatsApp and MCP alike: `ansari___`. Reason: the owner asked why the MCP client needed special handling. The client id is thread attribution; the environment in the prefix is key identification, so a leaked key reads as staging or production at a glance and secret scanning can tell them apart. One table in `packages/auth/src/service-users.ts` derives the prefixes, the accepted set, the secret-scanning patterns and the script's pasted-key check. Existing keys are unchanged (the plugin matches the hash; `apikey.prefix` is never rewritten): unlabelled `ansari_wa_` / `ansari_mcp_` keys stay accepted during a compatibility window (`LEGACY_UNLABELLED_KEYS`) and are rotated, never reissued in place. The MCP client-id rule is unchanged.
 >
-> Amendment 3, 2026-11-12, owner (supersedes Amendment 2's `--env` flag): apps/api and apps/auth gain `ENVIRONMENT` (`development` | `staging` | `production`, named to match the frontend's `EXPO_PUBLIC_ENVIRONMENT`). It is required, and `staging` or `production`, under `NODE_ENV=production` (both services refuse to boot otherwise, through the existing boot paths, never at build); it defaults to `development` elsewhere. It replaces `NODE_ENV` (apps/auth) and `RAILWAY_ENVIRONMENT || NODE_ENV` (apps/api) as the Sentry environment. It is the prefix's environment segment verbatim (`ansari_mcp_staging_`; longest `ansari_mcp_development_`, 23 characters, pinned by a test that creates a key with it). The service-keys script reads it from its process env and refuses to run without it. Both key routes serve only a key whose stored prefix names their own service and their own `ENVIRONMENT` (or the legacy bare prefix during the window); any other prefix is their ordinary refusal. Main's conditions (security architect, 2026-11-12): enforcement only on the existing boot paths, Sentry continuity stated in the PR, `ENVIRONMENT` in the `.env.example` and `.env.ci` files, RELEASE.md rows and a deploy-order line, and the unchanged-existing-keys note in the runbook.
+> Amendment 3, 2026-11-12, owner (supersedes Amendment 2's `--env` flag): apps/api and apps/auth gain `ENVIRONMENT` (`development` | `staging` | `production`, named to match the frontend's `EXPO_PUBLIC_ENVIRONMENT`). It is required, and `staging` or `production`, under `NODE_ENV=production` (both services refuse to boot otherwise, through the existing boot paths, never at build); it defaults to `development` elsewhere. It replaces `NODE_ENV` (apps/auth) and `RAILWAY_ENVIRONMENT || NODE_ENV` (apps/api) as the Sentry environment. It is the prefix's environment segment verbatim (`ansari_mcp_staging_`; longest `ansari_mcp_development_`, 23 characters, pinned by a test that creates a key with it). The service-keys script reads it from its process env and refuses to run without it. Both key routes serve only a key whose stored prefix names their own service and their own `ENVIRONMENT` (or the legacy bare prefix during the window); any other prefix is their ordinary refusal. Main's conditions (security architect, 2026-11-12): enforcement only on the existing boot paths, Sentry continuity stated in the PR, `ENVIRONMENT` in the `.env.example` and `.env.ci` files, RELEASE.md rows and a deploy-order line, and the unchanged-existing-keys note in the runbook. Owner directive (2026-11-12, via main): no code reads `RAILWAY_*` variables, only our own names, so `RAILWAY_ENVIRONMENT` leaves `turbo.json`.
 
 ## Problem Statement
 

From a2ddf4867f4f6ef7afcc7f02c5bf0c50321a6762 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 09:54:02 +1100
Subject: [PATCH 164/435] [Spec 314] Review round 5: codex APPROVE

---
 .../314-review-iter5-codex.txt                | 28 +++++++++++++++++++
 .../314-review-iter5-context.md               |  8 ++++++
 .../314-protect-v2-mcp-complete-with-b.md     |  3 ++
 3 files changed, 39 insertions(+)
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter5-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter5-context.md

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter5-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter5-codex.txt
new file mode 100644
index 00000000..80629780
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter5-codex.txt
@@ -0,0 +1,28 @@
+---
+VERDICT: APPROVE
+SUMMARY: All iteration-4 fixes are present; the implementation, tests, documentation, and develop rebase are PR-ready.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
+
+PR_SUMMARY: |
+  ## Summary
+  Protects `/api/v2/mcp-complete` with environment-labelled `ansari-mcp` service keys verified through apps/auth. Requests fail closed while preserving a temporary log-only rollout mode.
+
+  ## Key Changes
+  - Adds service-key verification, client attribution, alerting, and legacy-prefix compatibility.
+  - Adds `ENVIRONMENT` validation, Sentry configuration, deployment documentation, and comprehensive tests.
+
+  ## Test Plan
+  - Run `npm run build`.
+  - Run `npm test -- --exclude='**/e2e/**'`.
+  - Verify valid, refused, unavailable-auth, cross-environment, and legacy-key scenarios.
+
+---
+
+## ⚠️ REPOSITORY MOVED during the codex review (#1649).
+A consultant reviews the commit in front of it; it must never commit, or switch refs.
+  - HEAD: c0a803215e83fee089276d8e37d22a1a5490bcb2 -> b9391cc7128df22ef717651d2535b5159a6ccc26
+The files on disk may look untouched and still not be the ones this review describes.
+Check `git reflog` and `git status` before trusting this review or shipping the branch.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter5-context.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter5-context.md
new file mode 100644
index 00000000..b3b22fb9
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter5-context.md
@@ -0,0 +1,8 @@
+# PR #372 re-review (iteration 5)
+
+Iteration 4 (codex REQUEST_CHANGES) raised four points, all addressed (see 314-review-iter4-rebuttals.md):
+(1) LEGACY_SCANNING_PATTERNS is derived from LEGACY_PREFIXES, with coverage and runbook tests.
+(2) Rebased onto develop.
+(3) The review record and consult artifacts are committed.
+(4) The key script's Sentry uses ENVIRONMENT (scriptSentryInit).
+Please confirm these and review the whole PR.
diff --git a/codev/reviews/314-protect-v2-mcp-complete-with-b.md b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
index c33e9342..61c9e895 100644
--- a/codev/reviews/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
@@ -159,6 +159,9 @@ Codex and Gemini approved with no issues.
 #### Gemini
 - **CONSULT_ERROR** in rounds 3 and 4: the `agy` CLI exits with code 3, so the lane is skipped. The owner can restore it by running `agy` once to sign in.
 
+### Review / PR #372 (Round 5, codex only)
+Codex: **APPROVE**, no issues. It confirmed all four round-4 fixes.
+
 Apart from those Gemini skips, no `CONSULT_ERROR` occurred.
 
 ## Lessons Learned

From e1894da0b545e07ca5394ae627badd4fa9b667df Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 09:59:10 +1100
Subject: [PATCH 165/435] =?UTF-8?q?[Spec=20314]=20docs:=20apps/mcp=20READM?=
 =?UTF-8?q?E=20=E2=80=94=20a=20local=20apps/api=20enforces=20the=20key=20t?=
 =?UTF-8?q?oo=20unless=20run=20log-only?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 apps/mcp/README.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/apps/mcp/README.md b/apps/mcp/README.md
index 010ecd40..b7332976 100644
--- a/apps/mcp/README.md
+++ b/apps/mcp/README.md
@@ -89,7 +89,7 @@ The Worker takes the variables in the table below as Wrangler `vars` or secrets,
 | --- | --- |
 | `PORT` | HTTP port (default 3000). |
 | `ANSARI_API_BASE_URL` | Ansari API origin (default `https://api.askansari.ai`). |
-| `ANSARI_API_AUTHORIZATION` | Upstream Authorization header, sent verbatim: `Bearer ansari_mcp__<64 letters>`, the word `Bearer`, a space, then this deployment's `ansari-mcp` service key (its prefix names the environment it was issued in: `development`, `staging` or `production`, and only that environment's API accepts it). Required for any deployment that calls a deployed Ansari API: `/api/v2/mcp-complete` refuses a call without a valid key (401) once it enforces (#314). Optional only against a local API. Issued per deployment by the operator (`docs/cutover/service-keys-runbook.md`); set it with `wrangler secret put ANSARI_API_AUTHORIZATION --env ` on Workers or as a service variable on Railway, never commit it. |
+| `ANSARI_API_AUTHORIZATION` | Upstream Authorization header, sent verbatim: `Bearer ansari_mcp__<64 letters>`, the word `Bearer`, a space, then this deployment's `ansari-mcp` service key (its prefix names the environment it was issued in: `development`, `staging` or `production`, and only that environment's API accepts it). Required for any deployment that calls a deployed Ansari API: `/api/v2/mcp-complete` refuses a call without a valid key (401) once it enforces (#314). A local apps/api enforces too (its default); leave it unset only against a local API run with `MCP_COMPLETE_KEY_MODE=log-only`. Issued per deployment by the operator (`docs/cutover/service-keys-runbook.md`); set it with `wrangler secret put ANSARI_API_AUTHORIZATION --env ` on Workers or as a service variable on Railway, never commit it. |
 | `ANSARI_CLIENT` | Upstream client label (default `ansari-mcp`). |
 | `MCP_ALLOWED_HOSTS` | Comma-separated allowed HTTP Host names, without scheme. A configured list replaces local defaults; an explicitly empty list permits no Host. Only an absent variable defaults to localhost and 127.0.0.1. |
 | `MCP_ALLOWED_ORIGINS` | Comma-separated allowed browser origin hostnames. A configured list replaces defaults; an explicitly empty list permits no Origin header value. Requests without Origin remain supported. |

From 1d4c440f8690187d1bc9841c4b7abd65ce5181f0 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:08:09 +1100
Subject: [PATCH 166/435] =?UTF-8?q?[Spec=20314]=20chore(mcp):=20runnable?=
 =?UTF-8?q?=20in=20local=20dev=20=E2=80=94=20pnpm=20dev=20includes=20it;?=
 =?UTF-8?q?=20dev=20entry=20loads=20.env,=20defaults=20to=20:3001=20and=20?=
 =?UTF-8?q?the=20local=20api,=20warns=20without=20a=20key=20(owner)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 apps/mcp/.env.example   |  4 ++++
 apps/mcp/README.md      | 21 +++++++++++++++++++--
 apps/mcp/package.json   |  2 +-
 apps/mcp/scripts/dev.ts | 26 ++++++++++++++++++++++++++
 package.json            |  3 ++-
 5 files changed, 52 insertions(+), 4 deletions(-)
 create mode 100644 apps/mcp/scripts/dev.ts

diff --git a/apps/mcp/.env.example b/apps/mcp/.env.example
index 2e14969a..d2aaf652 100644
--- a/apps/mcp/.env.example
+++ b/apps/mcp/.env.example
@@ -35,3 +35,7 @@ PORT=3000
 # Optional release id shown in /health, logs and the served HTML. On Railway,
 # leave unset: it falls back to RAILWAY_GIT_COMMIT_SHA.
 # ANSARI_RELEASE=
+
+# Local development (scripts/dev.ts, `pnpm dev`): PORT defaults to 3001 and ANSARI_API_BASE_URL to
+# http://localhost:3000 when unset. A local apps/api enforces the key: set ANSARI_API_AUTHORIZATION to
+# "Bearer ansari_mcp_development_<64 letters>" from apps/auth's service-keys script (see README, "Local development").
diff --git a/apps/mcp/README.md b/apps/mcp/README.md
index b7332976..f48ee678 100644
--- a/apps/mcp/README.md
+++ b/apps/mcp/README.md
@@ -49,7 +49,7 @@ schema types. The artwork owner has authorized contribution and redistribution w
 
 ## Development
 
-Requires Node 22.18 or later and pnpm 10.33. Install once from the repository root using its authoritative lockfile. Run the app explicitly; root build, test, typecheck and coverage retain their existing scope, while root lint includes this application.
+Requires Node 22.18 or later and pnpm 10.33. Install once from the repository root using its authoritative lockfile. Root build, test, typecheck and coverage retain their existing scope; root lint and root `pnpm dev` include this application.
 
 ```sh
 pnpm install --frozen-lockfile --strict-peer-dependencies --filter ansari-mcp...
@@ -62,7 +62,24 @@ pnpm mcp test:browser
 pnpm mcp start
 ```
 
-`build` writes `dist/view.html` and a bundled `dist/server/index.js`. No API/auth/frontend build or SDK source checkout is needed. `dev` runs the Node entry source (`src/node/index.ts`) after `build`. The synthetic browser harness is test-only and uses no credentials or live answers.
+`build` writes `dist/view.html` and a bundled `dist/server/index.js`. No API/auth/frontend build or SDK source checkout is needed. `dev` builds, then runs the Node entry source through `scripts/dev.ts` (see below). The synthetic browser harness is test-only and uses no credentials or live answers.
+
+### Local development
+
+The root `pnpm dev` starts this server beside apps/api, apps/auth and the frontend (`pnpm dev:mcp` starts it alone). `scripts/dev.ts` loads `apps/mcp/.env` when it exists (git-ignored), then fills only what is still unset: `PORT` 3001 (apps/api has 3000) and `ANSARI_API_BASE_URL` `http://localhost:3000`. Hosts connect at `http://localhost:3001/mcp`.
+
+A local apps/api enforces the `ansari-mcp` key like a deployed one (#314). Either issue a local key and put the whole header in `apps/mcp/.env`:
+
+```sh
+# from apps/auth/, against the local auth database (ENVIRONMENT=development): show, then confirm
+pnpm exec tsx scripts/service-keys.ts create-service ansari-mcp            # once, then again with --confirm ansari-mcp
+pnpm exec tsx scripts/service-keys.ts create-key ansari-mcp --rate-max 120 --rate-window 60 --daily 5000 \
+  --name "local dev" --client-id ansari-mcp-local                          # then again with --confirm 
+# apps/mcp/.env
+ANSARI_API_AUTHORIZATION=Bearer ansari_mcp_development_<64 letters>
+```
+
+or run apps/api with `MCP_COMPLETE_KEY_MODE=log-only`, which serves requests without a key and logs the verdict `missing`. Without either, every tool call fails: apps/api answers 401, and the dev server warns at start. The dev entry is for local work only; deployments run `pnpm start` (`dist/`) or the Worker entry.
 
 ### Two hosting targets, one application
 
diff --git a/apps/mcp/package.json b/apps/mcp/package.json
index 3033653b..df5add1c 100644
--- a/apps/mcp/package.json
+++ b/apps/mcp/package.json
@@ -11,7 +11,7 @@
   "scripts": {
     "build": "tsx scripts/build.ts",
     "start": "node dist/server/index.js",
-    "dev": "tsx src/node/index.ts",
+    "dev": "pnpm build && tsx scripts/dev.ts",
     "typecheck": "tsc --noEmit",
     "test": "tsx --test test/*.test.ts",
     "test:browser": "tsx test/browser.ts",
diff --git a/apps/mcp/scripts/dev.ts b/apps/mcp/scripts/dev.ts
new file mode 100644
index 00000000..23cebcbb
--- /dev/null
+++ b/apps/mcp/scripts/dev.ts
@@ -0,0 +1,26 @@
+// Local development entry (`pnpm mcp dev`, and the root `pnpm dev`): the Node
+// server from source, wired to the local stack. It loads `apps/mcp/.env` when
+// present (git-ignored), then fills only what is still unset:
+//   PORT 3001 (apps/api has 3000), ANSARI_API_BASE_URL the local apps/api.
+// A local apps/api enforces the `ansari-mcp` key like a deployed one (#314):
+// put `ANSARI_API_AUTHORIZATION=Bearer ansari_mcp_development_<64 letters>` in
+// `.env` (a key from apps/auth's service-keys script against the local auth
+// database), or run apps/api with MCP_COMPLETE_KEY_MODE=log-only. Deployments
+// never use this file: they run `pnpm start` (dist/) or the Worker entry.
+import {existsSync} from 'node:fs';
+import {fileURLToPath} from 'node:url';
+
+const envFile = fileURLToPath(new URL('../.env', import.meta.url));
+if (existsSync(envFile)) process.loadEnvFile(envFile);
+
+export const DEV_DEFAULTS = {PORT: '3001', ANSARI_API_BASE_URL: 'http://localhost:3000'} as const;
+for (const [name, value] of Object.entries(DEV_DEFAULTS)) process.env[name] ??= value;
+
+if (!process.env.ANSARI_API_AUTHORIZATION) {
+  console.warn(
+    '[mcp dev] ANSARI_API_AUTHORIZATION is not set: the local apps/api answers 401 unless it runs with ' +
+      'MCP_COMPLETE_KEY_MODE=log-only. See apps/mcp/README.md, "Local development".',
+  );
+}
+
+await import('../src/node/index.js');
diff --git a/package.json b/package.json
index c1cd82f3..743deb56 100644
--- a/package.json
+++ b/package.json
@@ -10,9 +10,10 @@
     "api": "pnpm --filter ansari-api",
     "frontend": "pnpm --filter ansari-frontend",
     "auth": "pnpm --filter ansari-auth",
-    "dev": "turbo run dev --ui=tui --filter=!ansari-mcp",
+    "dev": "turbo run dev --ui=tui",
     "dev:no-auth": "turbo run dev --ui=tui --filter=!ansari-auth --filter=!ansari-mcp",
     "dev:auth": "pnpm --filter ansari-auth dev",
+    "dev:mcp": "pnpm --filter ansari-mcp dev",
     "lint": "turbo run lint",
     "typecheck": "turbo run typecheck --filter=!ansari-mcp",
     "test": "turbo run test --filter=!ansari-mcp -- --maxWorkers=4",

From f3773a4f679386111f64de077681891de43f3704 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:08:11 +1100
Subject: [PATCH 167/435] [Spec 314] Thread: mcp local dev

---
 codev/state/spir-314_thread.md | 1 +
 1 file changed, 1 insertion(+)

diff --git a/codev/state/spir-314_thread.md b/codev/state/spir-314_thread.md
index c41e03da..8a958972 100644
--- a/codev/state/spir-314_thread.md
+++ b/codev/state/spir-314_thread.md
@@ -80,3 +80,4 @@
 - Proof: apps/auth real boot without ENVIRONMENT → "env validation failed for: ENVIRONMENT"; with staging it listens. apps/api `next start` without it → boot check logs the rule, health 500 (Next still prints Ready, as for any boot-check failure); with it, health 503 (no DB). `npm run build` green with ENVIRONMENT unset. Mutation: dropping the env comparison fails 5 tests.
 - Surprise: the runbook's scanning table needs `\|` inside code cells (GFM), so cutover-docs' exact-match test now unescapes before comparing.
 - Railway env names (`staging`/`production`) come from the repo's Railway GitHub Environments, not RELEASE.md.
+- 2026-11-12 owner asked to make apps/mcp runnable in local dev: root `pnpm dev` now includes it (+ `pnpm dev:mcp`); `apps/mcp/scripts/dev.ts` loads `apps/mcp/.env`, defaults PORT 3001 and ANSARI_API_BASE_URL http://localhost:3000, warns when ANSARI_API_AUTHORIZATION is unset; `dev` builds first. Verified: health 200 on :3001, tools/list, and a stub upstream received `Authorization: Bearer ansari_mcp_development_…` verbatim on /api/v2/mcp-complete. apps/mcp's Workers tests (parity-workers, worker bundle) time out locally on the unchanged tree too (environmental, not this change). Also fixed README's wrong "optional against a local API" (a local apps/api enforces too).

From 41c787d63fcbefcadf4a72a060ae309a885ca3b5 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:19:55 +1100
Subject: [PATCH 168/435] [Spec 314] chore(mcp): dev warns when PORT is 3000;
 README and .env.example say to use 3001 for local dev (main)

---
 apps/mcp/.env.example   | 2 ++
 apps/mcp/README.md      | 2 +-
 apps/mcp/scripts/dev.ts | 7 +++++++
 3 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/apps/mcp/.env.example b/apps/mcp/.env.example
index d2aaf652..debb3784 100644
--- a/apps/mcp/.env.example
+++ b/apps/mcp/.env.example
@@ -39,3 +39,5 @@ PORT=3000
 # Local development (scripts/dev.ts, `pnpm dev`): PORT defaults to 3001 and ANSARI_API_BASE_URL to
 # http://localhost:3000 when unset. A local apps/api enforces the key: set ANSARI_API_AUTHORIZATION to
 # "Bearer ansari_mcp_development_<64 letters>" from apps/auth's service-keys script (see README, "Local development").
+# For local dev, set PORT=3001 in your apps/mcp/.env or drop the PORT line: PORT=3000 above is for the
+# Railway service and collides with apps/api under the root `pnpm dev` (the dev server warns).
diff --git a/apps/mcp/README.md b/apps/mcp/README.md
index f48ee678..1ae57bf8 100644
--- a/apps/mcp/README.md
+++ b/apps/mcp/README.md
@@ -66,7 +66,7 @@ pnpm mcp start
 
 ### Local development
 
-The root `pnpm dev` starts this server beside apps/api, apps/auth and the frontend (`pnpm dev:mcp` starts it alone). `scripts/dev.ts` loads `apps/mcp/.env` when it exists (git-ignored), then fills only what is still unset: `PORT` 3001 (apps/api has 3000) and `ANSARI_API_BASE_URL` `http://localhost:3000`. Hosts connect at `http://localhost:3001/mcp`.
+The root `pnpm dev` starts this server beside apps/api, apps/auth and the frontend (`pnpm dev:mcp` starts it alone). `scripts/dev.ts` loads `apps/mcp/.env` when it exists (git-ignored), then fills only what is still unset: `PORT` 3001 (apps/api has 3000) and `ANSARI_API_BASE_URL` `http://localhost:3000`. `.env.example` sets `PORT=3000` for the Railway service, so if you copied it to `.env`, set `PORT=3001` there or drop the line; the dev server warns when `PORT` is 3000. Hosts connect at `http://localhost:3001/mcp`.
 
 A local apps/api enforces the `ansari-mcp` key like a deployed one (#314). Either issue a local key and put the whole header in `apps/mcp/.env`:
 
diff --git a/apps/mcp/scripts/dev.ts b/apps/mcp/scripts/dev.ts
index 23cebcbb..66ca1624 100644
--- a/apps/mcp/scripts/dev.ts
+++ b/apps/mcp/scripts/dev.ts
@@ -16,6 +16,13 @@ if (existsSync(envFile)) process.loadEnvFile(envFile);
 export const DEV_DEFAULTS = {PORT: '3001', ANSARI_API_BASE_URL: 'http://localhost:3000'} as const;
 for (const [name, value] of Object.entries(DEV_DEFAULTS)) process.env[name] ??= value;
 
+if (process.env.PORT === '3000') {
+  console.warn(
+    '[mcp dev] PORT is 3000, which apps/api uses under the root `pnpm dev`. Set PORT=3001 in apps/mcp/.env, or ' +
+      'drop its PORT line (the dev default is 3001). .env.example keeps PORT=3000 for the Railway service.',
+  );
+}
+
 if (!process.env.ANSARI_API_AUTHORIZATION) {
   console.warn(
     '[mcp dev] ANSARI_API_AUTHORIZATION is not set: the local apps/api answers 401 unless it runs with ' +

From 1f936578211a1681a57acd1cfa57dc97864aad99 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:19:55 +1100
Subject: [PATCH 169/435] =?UTF-8?q?[Spec=20314][Phase:=20review]=20fix:=20?=
 =?UTF-8?q?second=20external=20review=20=E2=80=94=20MCP=20legacy=20window?=
 =?UTF-8?q?=20closed,=20both=20window=20states=20tested,=20RAILWAY=5F*=20s?=
 =?UTF-8?q?can=206=20(+=20apps/mcp/src=20cache=20input),=20api=20Sentry=20?=
 =?UTF-8?q?env=20test,=20one=20environment=20knob,=20keyVerified=20after?=
 =?UTF-8?q?=20the=20prefix=20gate,=20ENVIRONMENT=20validated=20before=20Se?=
 =?UTF-8?q?ntry,=20issuable=20test=20keys,=20doc=20fixes,=20production=20b?=
 =?UTF-8?q?oot=20probes?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../scripts/probes/environment-boot-probe.ts  | 122 ++++++++++++++++++
 apps/api/tests/boot-check.test.ts             |   6 +-
 apps/api/tests/cutover-docs.test.ts           |  12 +-
 apps/api/tests/helpers/mcp-key.ts             |   5 +-
 apps/api/tests/mcp-complete-key.test.ts       |   2 +-
 apps/api/tests/sentry-environment.test.ts     |  29 +++++
 apps/api/tests/source-scan/scan.ts            |  24 ++++
 .../api/tests/source-scan/source-scan.test.ts |  46 +++++++
 apps/api/turbo.json                           |   7 +
 .../scripts/probes/environment-boot-probe.ts  |  92 +++++++++++++
 apps/auth/scripts/service-keys.ts             |  24 +++-
 apps/auth/src/app.ts                          |   7 +-
 apps/auth/src/routes/service-verify.ts        |  15 +--
 apps/auth/src/routes/whatsapp.ts              |  20 +--
 apps/auth/tests/helpers/leak-scan.ts          |   6 +-
 apps/auth/tests/service-keys-no-dsn.test.ts   |   5 +-
 apps/auth/tests/service-keys.test.ts          |  73 +++++++----
 apps/auth/tests/service-verify-sentry.test.ts |   6 +-
 apps/auth/tests/service-verify.test.ts        |  10 +-
 apps/auth/tests/whatsapp-session.test.ts      |  43 ++++--
 .../314-protect-v2-mcp-complete-with-b.md     |   2 +-
 docs/cutover/service-keys-runbook.md          |  36 ++++--
 docs/self-hosting.md                          |   2 +-
 packages/auth/src/index.ts                    |   2 +-
 packages/auth/src/service-users.ts            | 117 +++++++++--------
 packages/types/src/environment.ts             |   2 +-
 26 files changed, 572 insertions(+), 143 deletions(-)
 create mode 100644 apps/api/scripts/probes/environment-boot-probe.ts
 create mode 100644 apps/api/tests/sentry-environment.test.ts
 create mode 100644 apps/auth/scripts/probes/environment-boot-probe.ts

diff --git a/apps/api/scripts/probes/environment-boot-probe.ts b/apps/api/scripts/probes/environment-boot-probe.ts
new file mode 100644
index 00000000..92d9fc57
--- /dev/null
+++ b/apps/api/scripts/probes/environment-boot-probe.ts
@@ -0,0 +1,122 @@
+/**
+ * The production-shaped run for ENVIRONMENT (#314 Amendment 3; second review,
+ * finding 12): the BUILT apps/api started with `next start` and
+ * NODE_ENV=production, as Railway starts it, for each value of ENVIRONMENT.
+ * In-process tests (tests/boot-check.test.ts) call validateEnvAtBoot directly;
+ * this proves the rule on the real boot path, through instrumentation's
+ * register(). Operator-run, after `pnpm --filter ansari-api build`:
+ *
+ *   pnpm --filter ansari-api exec tsx scripts/probes/environment-boot-probe.ts 
+ *
+ * The database URL is an argument, never read from the environment, and
+ * should point at a port nothing listens on: the probe needs boot to get past
+ * the env check, not a database. Only the values below exist in the child.
+ *
+ * Next.js prints "Ready" even when register() throws, so the verdict is the
+ * healthcheck Railway runs: a refused boot answers /api/health 500 and logs
+ * the ENVIRONMENT rule (names only, no value); a good boot gets past the env
+ * check, answering 503 without a database (or 200 with one). Each case runs
+ * under a deadline (PASS or FAIL, never a hang). The output is pasted into the
+ * review (codev/reviews/314-*.md).
+ */
+import { spawn } from "node:child_process";
+import path from "node:path";
+
+const databaseUrl = process.argv[2];
+if (!databaseUrl) {
+  console.error("usage: environment-boot-probe.ts ");
+  process.exit(2);
+}
+
+const APP_DIR = path.resolve(__dirname, "../..");
+const PORT = "31996";
+const AUDIENCE = "ansari-api-probe-audience";
+const BASE: Record = {
+  PATH: process.env.PATH ?? "",
+  NODE_ENV: "production",
+  DATABASE_URL: databaseUrl,
+  KALEMAT_API_KEY: "probe",
+  USUL_API_TOKEN: "probe",
+  AUTH_URL: "https://auth.probe.test",
+  AUTH_JWT_ISSUER: "https://auth.probe.test",
+  AUTH_JWT_AUDIENCE: AUDIENCE,
+  AUTH_LAYER_ORIGIN: "https://api.probe.test",
+};
+
+type Outcome = { health: number | null; ruleLogged: boolean; leaked: boolean };
+
+async function healthAfterReady(
+  output: () => string,
+  deadline: number,
+): Promise {
+  while (Date.now() < deadline) {
+    if (/Ready in/.test(output())) {
+      try {
+        return (await fetch(`http://127.0.0.1:${PORT}/api/health`)).status;
+      } catch {
+        // not listening yet
+      }
+    }
+    await new Promise((r) => setTimeout(r, 250));
+  }
+  return null;
+}
+
+async function boot(
+  environment: string | undefined,
+  deadlineMs = 40_000,
+): Promise {
+  const env = {
+    ...BASE,
+    ...(environment === undefined ? {} : { ENVIRONMENT: environment }),
+  };
+  const child = spawn(
+    path.join(APP_DIR, "node_modules/.bin/next"),
+    ["start", "-p", PORT],
+    {
+      cwd: APP_DIR,
+      env,
+    },
+  );
+  let output = "";
+  for (const stream of [child.stdout, child.stderr])
+    stream.on("data", (chunk: Buffer) => (output += chunk.toString()));
+  const health = await healthAfterReady(() => output, Date.now() + deadlineMs);
+  await new Promise((r) => setTimeout(r, 300));
+  child.kill("SIGTERM");
+  await new Promise((r) => child.once("exit", r));
+  return {
+    health,
+    // The validation failure names ENVIRONMENT: the production rule for an
+    // absent or `development` value, Zod's enum message for any other.
+    ruleLogged: /Environment validation failed[\s\S]*ENVIRONMENT/.test(output),
+    leaked:
+      output.includes(AUDIENCE) ||
+      (environment !== undefined && output.includes(`"${environment}"`)),
+  };
+}
+
+async function main(): Promise {
+  let failed = 0;
+  for (const [environment, shouldBoot] of [
+    [undefined, false],
+    ["development", false],
+    ["prod", false],
+    ["staging", true],
+    ["production", true],
+  ] as const) {
+    const outcome = await boot(environment);
+    const ok = shouldBoot
+      ? outcome.health !== null && outcome.health !== 500 && !outcome.ruleLogged
+      : outcome.health === 500 && outcome.ruleLogged && !outcome.leaked;
+    if (!ok) failed++;
+    console.log(
+      `${ok ? "PASS" : "FAIL"}  NODE_ENV=production ENVIRONMENT=${environment ?? "(absent)"} → /api/health ${outcome.health ?? "no answer"}` +
+        `${outcome.ruleLogged ? ", ENVIRONMENT rule logged" : ""}`,
+    );
+  }
+  return failed;
+}
+
+// apps/api is CommonJS: no top-level await.
+void main().then((failed) => process.exit(failed === 0 ? 0 : 1));
diff --git a/apps/api/tests/boot-check.test.ts b/apps/api/tests/boot-check.test.ts
index 065cbb17..482f230e 100644
--- a/apps/api/tests/boot-check.test.ts
+++ b/apps/api/tests/boot-check.test.ts
@@ -93,7 +93,8 @@ describe('validateEnvAtBoot', () => {
     process.env = { ...process.env, ...SERVER, NEXT_PHASE: 'phase-production-build' };
     delete process.env.ENVIRONMENT;
     expect(() => validateEnvAtBoot()).not.toThrow();
-    process.env = { ...process.env, ...BASE_ENV, NODE_ENV: 'development', NEXT_PHASE: undefined };
+    process.env = { ...process.env, ...BASE_ENV, NODE_ENV: 'development' };
+    delete process.env.NEXT_PHASE; // absent, not the string 'undefined'
     resetEnvCache();
     const { getEnv } = await import('@/lib/config');
     expect(getEnv().ENVIRONMENT).toBe('development');
@@ -103,7 +104,8 @@ describe('validateEnvAtBoot', () => {
     process.env = { ...process.env, ...SERVER, NEXT_PHASE: 'phase-production-build' };
     delete process.env.DATABASE_URL;
     expect(() => validateEnvAtBoot()).not.toThrow();
-    process.env = { ...process.env, NODE_ENV: 'development', NEXT_PHASE: undefined };
+    process.env = { ...process.env, NODE_ENV: 'development' };
+    delete process.env.NEXT_PHASE; // absent, not the string 'undefined'
     expect(() => validateEnvAtBoot()).not.toThrow();
   });
 });
diff --git a/apps/api/tests/cutover-docs.test.ts b/apps/api/tests/cutover-docs.test.ts
index f8c8031d..a9c037c1 100644
--- a/apps/api/tests/cutover-docs.test.ts
+++ b/apps/api/tests/cutover-docs.test.ts
@@ -545,8 +545,16 @@ describe('the service-keys runbook (spec 329)', () => {
     const scanning = section('Secret scanning');
     // A `|` inside a GFM table cell must be written `\|` (even in code), or it splits the cell;
     // the owner copies the rendered text, so the escape is undone before comparing.
-    const rows = [...scanning.matchAll(/^\| `([a-z-]+)` \| `([^`]+)` \|$/gm)].map((m) => [m[1], m[2]?.replace(/\\\|/g, '|')]);
-    expect(rows).toEqual(Object.entries(serviceUsers.SECRET_SCANNING_PATTERNS).map(([name, re]) => [name, re.source]));
+    const rowsOf = (text: string) =>
+      [...text.matchAll(/^\| `([a-z-]+)` \| `([^`]+)` \|$/gm)].map((m) => [m[1], m[2]?.replace(/\\\|/g, '|')]);
+    // Two tables: the patterns to register now, and (#314) the ones for the day the
+    // legacy-key window closes, both derived from the code, never typed by hand.
+    const [now, closed] = scanning.split('| Service | Pattern after the window closes |');
+    expect(closed, 'the closed-window table').toBeDefined();
+    const names = Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[];
+    expect(rowsOf(now ?? '')).toEqual(names.map((name) => [name, serviceUsers.SECRET_SCANNING_PATTERNS[name].source]));
+    expect(rowsOf(closed ?? '')).toEqual(names.map((name) => [name, serviceUsers.scanningPatternFor(name, false).source]));
+    for (const legacy of Object.values(serviceUsers.LEGACY_SCANNING_PATTERNS).flat()) expect(now).toContain(`\`${legacy.source}\``);
     expect(scanning).toContain('Settings → Code security → Secret scanning → Custom patterns');
     expect(scanning).toMatch(/\*\*revoke the key at once\*\*/);
   });
diff --git a/apps/api/tests/helpers/mcp-key.ts b/apps/api/tests/helpers/mcp-key.ts
index cdb2475d..0482ef8a 100644
--- a/apps/api/tests/helpers/mcp-key.ts
+++ b/apps/api/tests/helpers/mcp-key.ts
@@ -24,7 +24,10 @@ export const MCP_TEST_LAYER_ORIGIN = 'https://api.mcp-key-test.example';
 export const MCP_TEST_CLIENT_ID = 'ansari-mcp-test';
 export const MCP_TEST_KEY_ID = 'key-00000000-0000-4000-8000-000000000314';
 /** A key in the issued shape: the public prefix and 64 random letters. */
-export const MCP_TEST_KEY = `ansari_mcp_prod_${'kQ'.repeat(32)}`;
+// A shape the service-keys script can issue: keyPrefix('ansari-mcp', 'staging')
+// in packages/auth/src/service-users.ts. A literal, since apps/api may not
+// import @ansari/auth (source-scan 3).
+export const MCP_TEST_KEY = `ansari_mcp_staging_${'kQ'.repeat(32)}`;
 
 const VERIFY_PATH = '/api/service/verify-key';
 
diff --git a/apps/api/tests/mcp-complete-key.test.ts b/apps/api/tests/mcp-complete-key.test.ts
index 05f46167..f4045b40 100644
--- a/apps/api/tests/mcp-complete-key.test.ts
+++ b/apps/api/tests/mcp-complete-key.test.ts
@@ -64,7 +64,7 @@ const AUTH_URL = 'https://auth.mcp-gate-test.example';
 const VERIFY_URL = `${AUTH_URL}${SERVICE_VERIFY_PATH}`;
 const KEY_CLIENT = 'ansari-mcp-production';
 const KEY_ID = '7d0c2f4e-5b1a-4c3d-9e8f-0a1b2c3d4e5f';
-const PREFIX = 'ansari_mcp_prod_';
+const PREFIX = 'ansari_mcp_staging_'; // keyPrefix('ansari-mcp', 'staging'): a shape the script can issue
 const LEAK_WINDOW = 16;
 
 /** A key in the issued shape: the public prefix and 64 random letters, fresh per run. */
diff --git a/apps/api/tests/sentry-environment.test.ts b/apps/api/tests/sentry-environment.test.ts
new file mode 100644
index 00000000..4739ff13
--- /dev/null
+++ b/apps/api/tests/sentry-environment.test.ts
@@ -0,0 +1,29 @@
+// apps/api's Sentry environment is ENVIRONMENT (#314 Amendment 3), as apps/auth's
+// is (apps/auth/tests/environment.test.ts): never Railway's RAILWAY_ENVIRONMENT
+// (owner directive: our own names only) and never NODE_ENV, which is
+// `production` on staging too. The file is read as text: it is a side-effect
+// module that calls Sentry.init, and boot-check.test.ts mocks it away.
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+import { describe, expect, it } from 'vitest';
+
+const config = readFileSync(fileURLToPath(new URL('../sentry.server.config.ts', import.meta.url)), 'utf8');
+const environmentLine = config.split('\n').find((line) => /^\s*environment\s*:/.test(line));
+
+describe('sentry.server.config.ts environment', () => {
+  it('is process.env.ENVIRONMENT', () => {
+    expect(environmentLine).toBeDefined();
+    expect(environmentLine).toContain('process.env.ENVIRONMENT');
+  });
+
+  it('reads neither RAILWAY_* nor NODE_ENV for it', () => {
+    expect(environmentLine).not.toMatch(/RAILWAY|NODE_ENV/);
+    expect(config).not.toMatch(/RAILWAY/);
+  });
+
+  it('the check bites: the pre-#314 line fails it', () => {
+    const old = '  environment: process.env.RAILWAY_ENVIRONMENT || process.env.NODE_ENV,';
+    expect(old).toMatch(/RAILWAY|NODE_ENV/);
+  });
+});
diff --git a/apps/api/tests/source-scan/scan.ts b/apps/api/tests/source-scan/scan.ts
index 12fbbe16..fc995f0b 100644
--- a/apps/api/tests/source-scan/scan.ts
+++ b/apps/api/tests/source-scan/scan.ts
@@ -173,3 +173,27 @@ export function whatsappHits(files: readonly { path: string; source: string }[])
   }
   return hits;
 }
+
+// ── Scan 6: no code reads a RAILWAY_* variable (owner directive 2026-11-12) ──
+
+/**
+ * Our code reads only our own names; the hosting platform's are mapped in its
+ * dashboard (owner, 2026-11-12, via main, #314). Any `RAILWAY_*` name in code
+ * counts, whatever the access path (`process.env.X`, `process.env['X']`, or a
+ * helper taking the name as a string, as apps/mcp's `setting(env, 'X')` does);
+ * comments do not, since docs explaining the rule name the variables.
+ */
+const RAILWAY_NAME = /\bRAILWAY_[A-Z0-9_]+\b/g;
+
+/** Each RAILWAY_* name the code (comments removed) mentions, in order. */
+export function railwayEnvHits(source: string): string[] {
+  return codeWithoutComments(source).match(RAILWAY_NAME) ?? [];
+}
+
+/**
+ * The declared exceptions, by file and name. apps/mcp's release fallback is
+ * main's lane; issue #377 removes the read and then this entry.
+ */
+export const RAILWAY_ALLOWLIST: Readonly> = {
+  'apps/mcp/src/server/runtime-config.ts': ['RAILWAY_GIT_COMMIT_SHA'], // #377
+};
diff --git a/apps/api/tests/source-scan/source-scan.test.ts b/apps/api/tests/source-scan/source-scan.test.ts
index 71e03e5b..85a007d4 100644
--- a/apps/api/tests/source-scan/source-scan.test.ts
+++ b/apps/api/tests/source-scan/source-scan.test.ts
@@ -12,6 +12,8 @@ import {
   databaseUrlHits,
   isExcludedFromDatabaseUrlScan,
   legacySqlHits,
+  RAILWAY_ALLOWLIST,
+  railwayEnvHits,
   readSource,
   removedHopHits,
   removedHopTextHits,
@@ -284,3 +286,47 @@ describe('scan 5: apps/api has no WhatsApp-specific code (spec 329)', () => {
     expect(hits).toEqual({});
   });
 });
+
+describe('scan 6: no code reads a RAILWAY_* variable (owner directive 2026-11-12, #314)', () => {
+  // apps/api, apps/auth (with packages/auth) and apps/mcp's server source.
+  const MCP_RUNTIME = sourceFiles('apps/mcp/src');
+
+  it('catches planted lines, whatever the access path', () => {
+    for (const bad of [
+      'const env = process.env.RAILWAY_ENVIRONMENT;',
+      "const name = process.env['RAILWAY_ENVIRONMENT_NAME'];",
+      'const sha = process.env[`RAILWAY_GIT_COMMIT_SHA`];',
+      "const release = setting(env, 'RAILWAY_GIT_COMMIT_SHA');",
+      "Sentry.init({ environment: process.env.RAILWAY_ENVIRONMENT || process.env.NODE_ENV });",
+    ]) {
+      expect(railwayEnvHits(bad), bad).not.toEqual([]);
+    }
+  });
+
+  it('ignores near-misses', () => {
+    for (const fine of [
+      '// Railway injects RAILWAY_ENVIRONMENT; we read ENVIRONMENT instead',
+      '/* RAILWAY_GIT_COMMIT_SHA is not read */ const x = 1;',
+      "const host = 'postgres.railway.internal';",
+      "const file = 'apps/api/railway.toml';",
+      'const environment = process.env.ENVIRONMENT;',
+      "const name = 'MY_RAILWAY';",
+    ]) {
+      expect(railwayEnvHits(fine), fine).toEqual([]);
+    }
+  });
+
+  it('the allowlist is exact: its one entry is present, and nothing else is', () => {
+    const files = [...API_RUNTIME, ...AUTH_RUNTIME, ...MCP_RUNTIME];
+    expect(MCP_RUNTIME.length).toBeGreaterThan(10);
+    expect(files.length).toBeGreaterThan(100);
+    const hits = scanTree(files, railwayEnvHits);
+    report('RAILWAY_* reads (apps/api + apps/auth + apps/mcp runtime)', files, hits);
+    // Every allowlisted read still exists (a stale entry would hide a regression)...
+    for (const [file, names] of Object.entries(RAILWAY_ALLOWLIST)) expect(hits[file], file).toEqual(names);
+    // ...and no read is outside it.
+    const unexpected = Object.fromEntries(Object.entries(hits).filter(([file]) => !(file in RAILWAY_ALLOWLIST)));
+    expect(unexpected).toEqual({});
+  });
+});
+
diff --git a/apps/api/turbo.json b/apps/api/turbo.json
index dd6d7a26..2ce19ed8 100644
--- a/apps/api/turbo.json
+++ b/apps/api/turbo.json
@@ -20,6 +20,12 @@
     // which pins the root `test` script's worker cap: without it, removing the
     // cap left this task at the same hash and a warm cache replayed the pin green.
     //
+    // apps/mcp/src is here for source-scan 6 (#314), which reads it for
+    // RAILWAY_* names: without it a RAILWAY_ read added there left this task at
+    // the same hash and a warm cache replayed the scan green. (The scan's other
+    // trees are already inputs: apps/auth/src and apps/auth/scripts here,
+    // packages/auth/src through globalDependencies.)
+    //
     // The railway tomls are here for release-doc.test.ts (issue #364), which
     // checks each one against RELEASE.md: without them a toml-only edit left this
     // task at the same hash and a warm cache replayed the check green.
@@ -29,6 +35,7 @@
         ".env.ci",
         "$TURBO_ROOT$/apps/auth/src/**",
         "$TURBO_ROOT$/apps/auth/scripts/**",
+        "$TURBO_ROOT$/apps/mcp/src/**",
         "$TURBO_ROOT$/apps/auth/tests/helpers/**",
         "$TURBO_ROOT$/packages/auth/drizzle/**",
         "$TURBO_ROOT$/packages/auth/tests/helpers/**",
diff --git a/apps/auth/scripts/probes/environment-boot-probe.ts b/apps/auth/scripts/probes/environment-boot-probe.ts
new file mode 100644
index 00000000..458f9aef
--- /dev/null
+++ b/apps/auth/scripts/probes/environment-boot-probe.ts
@@ -0,0 +1,92 @@
+/**
+ * The production-shaped run for ENVIRONMENT (#314 Amendment 3; second review,
+ * finding 12): the BUILT apps/auth (`dist/index.mjs`) started as its own
+ * process with NODE_ENV=production, as Railway starts it, for each value of
+ * ENVIRONMENT. In-process tests mutate process.env; this proves the rule on
+ * the real boot path. Operator-run, after `pnpm --filter ansari-auth build`:
+ *
+ *   pnpm --filter ansari-auth exec tsx scripts/probes/environment-boot-probe.ts 
+ *
+ * The database URL is an argument, never read from the environment, and
+ * should point at a port nothing listens on (e.g. 127.0.0.1:1): the probe
+ * needs boot to get past the env check, not a database (apps/auth starts on
+ * an unreachable database, by design). No .env is loaded (DOTENV_CONFIG_PATH
+ * is /dev/null), so only the values below exist.
+ *
+ * Expected: absent, `development` and `prod` refuse to boot, naming
+ * ENVIRONMENT and no value; `staging` and `production` listen. Each case runs
+ * under a deadline (PASS or FAIL, never a hang). The output is pasted into the
+ * review (codev/reviews/314-*.md).
+ */
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+const databaseUrl = process.argv[2];
+if (!databaseUrl) {
+  console.error('usage: environment-boot-probe.ts ');
+  process.exit(2);
+}
+
+const APP_DIR = fileURLToPath(new URL('../..', import.meta.url));
+const SECRET = 'probe-secret-'.padEnd(40, 'x');
+const BASE: Record = {
+  PATH: process.env.PATH ?? '',
+  DOTENV_CONFIG_PATH: '/dev/null',
+  NODE_ENV: 'production',
+  DATABASE_URL: databaseUrl,
+  BETTER_AUTH_SECRET: SECRET,
+  BETTER_AUTH_URL: 'https://auth.probe.test',
+  CORS_ORIGIN: 'https://app.probe.test',
+  AUTH_LAYER_ORIGIN: 'https://api.probe.test',
+  AUTH_JWT_ISSUER: 'https://auth.probe.test',
+  AUTH_JWT_AUDIENCE: 'ansari-api',
+  RESEND_API_KEY: 'r'.repeat(20),
+  FRONTEND_URL: 'https://app.probe.test',
+  PORT: '31997',
+};
+
+type Outcome = { listened: boolean; refusedOn: string | null; leaked: boolean };
+
+function boot(environment: string | undefined, deadlineMs = 20_000): Promise {
+  const env = { ...BASE, ...(environment === undefined ? {} : { ENVIRONMENT: environment }) };
+  return new Promise((resolve) => {
+    const child = spawn(process.execPath, ['dist/index.mjs'], { cwd: APP_DIR, env });
+    let output = '';
+    const finish = () => {
+      clearTimeout(timer);
+      child.kill('SIGTERM');
+      const refused = /env validation failed for: ([A-Z_, ]+)\./.exec(output);
+      resolve({
+        listened: /listening on port/.test(output),
+        refusedOn: refused?.[1] ?? null,
+        leaked: output.includes(SECRET) || (environment !== undefined && environment !== '' && output.includes(`ENVIRONMENT=${environment}`)),
+      });
+    };
+    const timer = setTimeout(finish, deadlineMs);
+    for (const stream of [child.stdout, child.stderr]) {
+      stream.on('data', (chunk: Buffer) => {
+        output += chunk.toString();
+        if (/listening on port|env validation failed/.test(output)) setTimeout(finish, 200);
+      });
+    }
+    child.on('exit', () => setTimeout(finish, 50));
+  });
+}
+
+let failed = 0;
+for (const [environment, shouldBoot] of [
+  [undefined, false],
+  ['development', false],
+  ['prod', false],
+  ['staging', true],
+  ['production', true],
+] as const) {
+  const outcome = await boot(environment);
+  const ok = shouldBoot
+    ? outcome.listened && outcome.refusedOn === null
+    : !outcome.listened && outcome.refusedOn === 'ENVIRONMENT' && !outcome.leaked;
+  if (!ok) failed++;
+  const what = outcome.listened ? 'listened' : outcome.refusedOn ? `refused (names: ${outcome.refusedOn})` : 'no answer';
+  console.log(`${ok ? 'PASS' : 'FAIL'}  NODE_ENV=production ENVIRONMENT=${environment ?? '(absent)'} → ${what}`);
+}
+process.exit(failed === 0 ? 0 : 1);
diff --git a/apps/auth/scripts/service-keys.ts b/apps/auth/scripts/service-keys.ts
index df45a04a..fe502ad2 100644
--- a/apps/auth/scripts/service-keys.ts
+++ b/apps/auth/scripts/service-keys.ts
@@ -558,14 +558,23 @@ export const unrecordedRecorder: Recorder = {
 /**
  * The script's Sentry init: its events carry ENVIRONMENT, like apps/auth's own
  * (#314 Amendment 3), never NODE_ENV, which is `production` on staging too. An
- * absent ENVIRONMENT never reaches a write: serviceKeys refuses to run first.
+ * absent or unknown ENVIRONMENT never gets here: main() refuses it first.
  */
-export function scriptSentryInit(dsn: string, environment: string | undefined) {
-  return { dsn, environment: environment ?? 'development', ...SCRIPT_SENTRY_OPTIONS };
+export function scriptSentryInit(dsn: string, environment: Environment) {
+  return { dsn, environment, ...SCRIPT_SENTRY_OPTIONS };
+}
+
+/**
+ * The validated ENVIRONMENT, or null when it is absent or not one of
+ * ENVIRONMENTS. main() checks it before scriptRecorder, so Sentry is never
+ * initialised under an operator's typo (second review, finding 8).
+ */
+export function validEnvironment(value: string | undefined): Environment | null {
+  return value !== undefined && isEnvironment(value) ? value : null;
 }
 
 /** The script's recorder: Sentry when a DSN is set (initialised here), otherwise none. */
-export function scriptRecorder(dsn: string | undefined, environment: string | undefined): Recorder {
+export function scriptRecorder(dsn: string | undefined, environment: Environment): Recorder {
   if (!dsn) return unrecordedRecorder;
   Sentry.init(scriptSentryInit(dsn, environment));
   return sentryRecorder;
@@ -673,7 +682,12 @@ export function printLine(line: string): void {
 }
 
 async function main(): Promise {
-  const recorder = scriptRecorder(process.env.SENTRY_DSN, process.env.ENVIRONMENT);
+  const environment = validEnvironment(process.env.ENVIRONMENT);
+  if (environment === null) {
+    printLine(ENVIRONMENT_RULE);
+    process.exit(1);
+  }
+  const recorder = scriptRecorder(process.env.SENTRY_DSN, environment);
   const { exitCode } = await serviceKeys(process.argv.slice(2), {
     databaseUrl: process.env.DATABASE_URL,
     environment: process.env.ENVIRONMENT,
diff --git a/apps/auth/src/app.ts b/apps/auth/src/app.ts
index 2167269b..f5b60767 100644
--- a/apps/auth/src/app.ts
+++ b/apps/auth/src/app.ts
@@ -73,9 +73,10 @@ export function createApp({ auth, db }: ServiceDeps, options: AppOptions = {}):
   // OPTIONS itself, so a route after it would get CORS for the configured
   // origin. Each router answers every request to its path, so nothing reaches
   // corsFor; a browser can never read a response from either.
-  const environment = options.environment;
-  app.use(WHATSAPP_SESSION_PATH, whatsappRouter({ auth, db }, { ...options.exchange, ...(environment && { environment }) }));
-  app.use(SERVICE_VERIFY_PATH, serviceVerifyRouter({ auth, db }, { ...options.verify, ...(environment && { environment }) }));
+  // The one environment knob for both key routes (second review, finding 7).
+  const environment = options.environment ?? getEnv().ENVIRONMENT;
+  app.use(WHATSAPP_SESSION_PATH, whatsappRouter({ auth, db }, options.exchange ?? {}, environment));
+  app.use(SERVICE_VERIFY_PATH, serviceVerifyRouter({ auth, db }, options.verify ?? {}, environment));
   app.use(corsFor(getEnv().CORS_ORIGIN));
   app.use(mergeExposedHeaders);
   app.use(blockedPaths);
diff --git a/apps/auth/src/routes/service-verify.ts b/apps/auth/src/routes/service-verify.ts
index 1123e615..95ccfc91 100644
--- a/apps/auth/src/routes/service-verify.ts
+++ b/apps/auth/src/routes/service-verify.ts
@@ -25,7 +25,7 @@
 // so no response carries an `Access-Control-*` header. It is outside Better
 // Auth's handler path, so no router per-IP rule applies: apps/api calls from
 // its egress IP.
-import { getEnv, isMcpClientId, limits, redactError, serviceUsers, type Environment } from '@ansari/auth';
+import { isMcpClientId, limits, redactError, serviceUsers, type Environment } from '@ansari/auth';
 import express, { Router, type NextFunction, type Request, type Response } from 'express';
 
 import { createMcpVerifyAlerts, type KeyRefusalCode, type McpVerifyAlerts } from '../alerts';
@@ -44,11 +44,6 @@ const KEY = new RegExp(`^[\\x21-\\x7E]{1,${limits.VERIFY_KEY_MAX_LENGTH}}$`);
 const KEY_REFUSAL_CODES: readonly string[] = ['USAGE_EXCEEDED', 'RATE_LIMITED'] satisfies KeyRefusalCode[];
 
 export type VerifyOptions = {
-  /**
-   * This deployment's ENVIRONMENT (#314 Amendment 3): only a key whose stored
-   * prefix names it (or the legacy bare prefix) is served. Defaults to getEnv().
-   */
-  environment?: Environment;
   alerts?: McpVerifyAlerts;
   /** The clock for the relation-check cache; tests advance it. */
   now?: () => number;
@@ -81,10 +76,14 @@ const REFUSED = { valid: false } as const;
 const invalidRequest = (res: Response) => res.status(400).json({ message: 'Invalid request' });
 const internalError = (res: Response) => res.status(500).json({ message: 'Internal error' });
 
-export function serviceVerifyRouter({ auth, db }: ServiceDeps, options: VerifyOptions = {}): Router {
+/**
+ * `environment` is this deployment's ENVIRONMENT (#314 Amendment 3): only a key
+ * whose stored prefix names it, or a legacy prefix while the window is open, is
+ * served. createApp passes it; it is the one place it is set.
+ */
+export function serviceVerifyRouter({ auth, db }: ServiceDeps, options: VerifyOptions, environment: Environment): Router {
   const alerts = options.alerts ?? createMcpVerifyAlerts();
   const checkApiKeyRelation = createApiKeyRelationCheck(db, options.now ?? Date.now);
-  const environment = options.environment ?? getEnv().ENVIRONMENT;
   const permissions = { [SERVED_RESOURCE]: [...SERVED_ACTIONS] };
   const router = Router();
 
diff --git a/apps/auth/src/routes/whatsapp.ts b/apps/auth/src/routes/whatsapp.ts
index 7d8b37aa..5dc51747 100644
--- a/apps/auth/src/routes/whatsapp.ts
+++ b/apps/auth/src/routes/whatsapp.ts
@@ -26,7 +26,7 @@
 // Better Auth's handler path, so no router per-IP rule applies: the WhatsApp
 // service calls from one egress IP, and the key's own limits and the per-user
 // budget are the throttle.
-import { consumeWindow, limits, redactError, getEnv, serviceUsers, whatsapp, type Environment } from '@ansari/auth';
+import { consumeWindow, limits, redactError, serviceUsers, whatsapp, type Environment } from '@ansari/auth';
 import express, { Router, type NextFunction, type Request, type Response } from 'express';
 
 import {
@@ -54,11 +54,6 @@ const BSUID = /^[^\s\p{Cc}\p{Cf}]{1,256}$/u;
 export const exchangeLimitKey = (userId: string) => `sub:${userId}|${WHATSAPP_SESSION_PATH}`;
 
 export type ExchangeOptions = {
-  /**
-   * This deployment's ENVIRONMENT (#314 Amendment 3): only a key whose stored
-   * prefix names it (or the legacy bare prefix) is served. Defaults to getEnv().
-   */
-  environment?: Environment;
   alerts?: ExchangeAlerts;
   /** The clock for the relation-check cache; tests advance it. */
   now?: () => number;
@@ -92,10 +87,14 @@ const unauthorized = (res: Response) => res.status(401).json({ message: 'Unautho
 const invalidRequest = (res: Response) => res.status(400).json({ message: 'Invalid request' });
 const internalError = (res: Response) => res.status(500).json({ message: 'Internal error' });
 
-export function whatsappRouter({ auth, db }: ServiceDeps, options: ExchangeOptions = {}): Router {
+/**
+ * `environment` is this deployment's ENVIRONMENT (#314 Amendment 3): only a key
+ * whose stored prefix names it, or a legacy prefix while the window is open, is
+ * served. createApp passes it; it is the one place it is set.
+ */
+export function whatsappRouter({ auth, db }: ServiceDeps, options: ExchangeOptions, environment: Environment): Router {
   const alerts = options.alerts ?? createExchangeAlerts();
   const now = options.now ?? Date.now;
-  const environment = options.environment ?? getEnv().ENVIRONMENT;
   const router = Router();
 
   const checkApiKeyRelation = createApiKeyRelationCheck(db, now);
@@ -124,7 +123,6 @@ export function whatsappRouter({ auth, db }: ServiceDeps, options: ExchangeOptio
         await checkApiKeyRelation();
         return refuse(res);
       }
-      alerts.keyVerified(verified.key);
       const owner = await serviceUsers.findServiceUser(db, SERVICE);
       if (owner.kind !== 'one') {
         alerts.serviceUserUnresolvable(owner.kind === 'many' ? owner.ids.length : 0);
@@ -136,6 +134,10 @@ export function whatsappRouter({ auth, db }: ServiceDeps, options: ExchangeOptio
       // the same refusal (#314 Amendment 3). The legacy bare prefix is accepted
       // while serviceUsers.LEGACY_UNLABELLED_KEYS holds.
       if (!serviceUsers.isAcceptedKeyPrefix(SERVICE, environment, verified.key.prefix)) return refuse(res);
+      // Counted only for a key that is served, as on the verify route: a wrong
+      // owner or prefix is a refusal, already counted by refuse() (second
+      // review, finding 6; supersedes leaving the exchange's order as it was).
+      alerts.keyVerified(verified.key);
       next();
     } catch (err) {
       fail(res, err);
diff --git a/apps/auth/tests/helpers/leak-scan.ts b/apps/auth/tests/helpers/leak-scan.ts
index 1fff4d70..5d547640 100644
--- a/apps/auth/tests/helpers/leak-scan.ts
+++ b/apps/auth/tests/helpers/leak-scan.ts
@@ -9,7 +9,11 @@ export const LEAK_WINDOW = 16;
 
 // Longest first, so `ansari_mcp_staging_` is stripped whole, never just `ansari_mcp_`.
 const PREFIXES = (Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[])
-  .flatMap((name) => [serviceUsers.SERVICES[name].prefix, ...ENVIRONMENTS.map((env) => serviceUsers.keyPrefix(name, env))])
+  .flatMap((name) => [
+    serviceUsers.SERVICES[name].prefix,
+    ...serviceUsers.LEGACY_PREFIXES[name],
+    ...ENVIRONMENTS.map((env) => serviceUsers.keyPrefix(name, env)),
+  ])
   .sort((a, b) => b.length - a.length);
 
 /** Every 16-character window of the key's random part (the part after its prefix, environment included). */
diff --git a/apps/auth/tests/service-keys-no-dsn.test.ts b/apps/auth/tests/service-keys-no-dsn.test.ts
index d48f621c..ee5aa19a 100644
--- a/apps/auth/tests/service-keys-no-dsn.test.ts
+++ b/apps/auth/tests/service-keys-no-dsn.test.ts
@@ -5,7 +5,7 @@
 import * as Sentry from '@sentry/node';
 import { afterAll, beforeAll, describe, expect, it } from 'vitest';
 
-import { EXIT_UNRECORDED, scriptRecorder, scriptSentryInit, serviceKeys, unrecordedRecorder } from '../scripts/service-keys';
+import { EXIT_UNRECORDED, scriptRecorder, scriptSentryInit, serviceKeys, unrecordedRecorder, validEnvironment } from '../scripts/service-keys';
 import { startService, type Service } from './helpers/service';
 
 let service: Service;
@@ -67,6 +67,9 @@ describe('the script\'s Sentry environment (#314 Amendment 3, codex)', () => {
     try {
       expect(scriptSentryInit('https://public@o0.ingest.sentry.io/0', 'staging').environment).toBe('staging');
       expect(scriptSentryInit('https://public@o0.ingest.sentry.io/0', 'production').environment).toBe('production');
+      // main() validates before scriptRecorder: a typo never reaches Sentry.init.
+      for (const bad of [undefined, '', 'prod', 'Production', 'test']) expect(validEnvironment(bad), String(bad)).toBeNull();
+      for (const good of ['development', 'staging', 'production']) expect(validEnvironment(good)).toBe(good);
     } finally {
       process.env.NODE_ENV = before;
     }
diff --git a/apps/auth/tests/service-keys.test.ts b/apps/auth/tests/service-keys.test.ts
index fcd103ef..06fd461d 100644
--- a/apps/auth/tests/service-keys.test.ts
+++ b/apps/auth/tests/service-keys.test.ts
@@ -813,37 +813,56 @@ describe('SECRET_SCANNING_PATTERNS', () => {
     expect(hits.filter(Boolean)).toHaveLength(2);
   });
 
-  it('the registered sources, derived from the prefix table (the runbook prints exactly these)', () => {
-    expect(serviceUsers.LEGACY_UNLABELLED_KEYS).toBe(true);
-    expect(serviceUsers.SECRET_SCANNING_PATTERNS.whatsapp.source).toBe(
-      'ansari_wa_(?:(?:development|staging|production)_)?[A-Za-z]{64}'
-    );
-    expect(serviceUsers.SECRET_SCANNING_PATTERNS['ansari-mcp'].source).toBe(
-      'ansari_mcp_(?:(?:development|staging|production)_)?[A-Za-z]{64}'
-    );
-  });
+  const NAMES = Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[];
+  const BODY = 'Q'.repeat(64);
+
+  // Both states of the legacy window are live code (second review, finding 2):
+  // the builders take the state, and every assertion below runs for both, so
+  // closing the window (LEGACY_UNLABELLED_KEYS = false) breaks nothing here.
+  describe.each([true, false])('the legacy window open: %s', (legacy) => {
+    it('the main pattern catches every labelled prefix, and the bare prefix only where the window accepts it', () => {
+      for (const name of NAMES) {
+        const pattern = serviceUsers.scanningPatternFor(name, legacy);
+        for (const env of ENVIRONMENTS) expect(pattern.test(`${serviceUsers.keyPrefix(name, env)}${BODY}`), `${name} ${env}`).toBe(true);
+        const bare = serviceUsers.SERVICES[name].prefix;
+        expect(pattern.test(`${bare}${BODY}`), `${name} bare`).toBe(legacy && serviceUsers.LEGACY_PREFIXES[name].includes(bare));
+        expect(pattern.test(`${bare}qa_${BODY}`)).toBe(false);
+      }
+    });
 
-  it('every labelled prefix and the legacy bare prefix are caught; an unknown environment is not', () => {
-    const body = 'Q'.repeat(64);
-    for (const name of Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[]) {
-      const pattern = serviceUsers.SECRET_SCANNING_PATTERNS[name];
-      const prefixes = [serviceUsers.SERVICES[name].prefix, ...ENVIRONMENTS.map((e) => serviceUsers.keyPrefix(name, e))];
-      for (const prefix of prefixes) expect(pattern.test(`${prefix}${body}`), prefix).toBe(true);
-      expect(pattern.test(`${serviceUsers.SERVICES[name].prefix}qa_${body}`)).toBe(false);
-    }
-  });
+    it('every prefix a route accepts, in every environment, is caught by the main or a legacy pattern (codex, PR #372)', () => {
+      for (const name of NAMES) {
+        const patterns = [serviceUsers.scanningPatternFor(name, legacy), ...serviceUsers.legacyScanningPatternsFor(name, legacy)];
+        for (const env of ENVIRONMENTS) {
+          for (const prefix of serviceUsers.acceptedKeyPrefixesFor(name, env, legacy)) {
+            expect(patterns.some((p) => p.test(`${prefix}${BODY}`)), `${name} ${env} ${prefix}`).toBe(true);
+          }
+        }
+      }
+    });
 
-  it('every prefix a route accepts, in any environment, is caught by the main or a legacy pattern (codex, PR #372)', () => {
-    const body = 'Q'.repeat(64);
-    for (const name of Object.keys(serviceUsers.SERVICES) as serviceUsers.ServiceName[]) {
-      const patterns = [serviceUsers.SECRET_SCANNING_PATTERNS[name], ...serviceUsers.LEGACY_SCANNING_PATTERNS[name]];
-      const accepted = new Set(ENVIRONMENTS.flatMap((e) => serviceUsers.acceptedKeyPrefixes(name, e)));
-      for (const prefix of accepted) {
-        expect(patterns.some((p) => p.test(`${prefix}${body}`)), `${name} ${prefix}`).toBe(true);
+    it('accepts exactly its own environment\'s prefix, plus the legacy prefixes only while open', () => {
+      for (const name of NAMES) {
+        for (const env of ENVIRONMENTS) {
+          expect(serviceUsers.acceptedKeyPrefixesFor(name, env, legacy)).toEqual(
+            legacy ? [serviceUsers.keyPrefix(name, env), ...serviceUsers.LEGACY_PREFIXES[name]] : [serviceUsers.keyPrefix(name, env)]
+          );
+        }
+        if (!legacy) expect(serviceUsers.legacyScanningPatternsFor(name, legacy)).toEqual([]);
       }
+    });
+  });
+
+  it('the window today: WhatsApp keeps ansari_wa_ and wa_, ansari-mcp has none (second review, finding 1)', () => {
+    expect(serviceUsers.LEGACY_PREFIXES).toEqual({ whatsapp: ['ansari_wa_', 'wa_'], 'ansari-mcp': [] });
+    expect(serviceUsers.legacyScanningPatternsFor('whatsapp', true).map((p) => p.source)).toEqual(['wa_[A-Za-z]{64}']);
+    expect(serviceUsers.legacyScanningPatternsFor('ansari-mcp', true)).toEqual([]);
+    // The exported constants are the builders under the current state, whatever it is.
+    for (const name of NAMES) {
+      expect(serviceUsers.SECRET_SCANNING_PATTERNS[name].source).toBe(
+        serviceUsers.scanningPatternFor(name, serviceUsers.LEGACY_UNLABELLED_KEYS).source
+      );
     }
-    expect(serviceUsers.LEGACY_SCANNING_PATTERNS.whatsapp.map((p) => p.source)).toEqual(['wa_[A-Za-z]{64}']);
-    expect(serviceUsers.LEGACY_SCANNING_PATTERNS['ansari-mcp']).toEqual([]);
   });
 
   it('the runbook names every legacy pattern by its source', () => {
diff --git a/apps/auth/tests/service-verify-sentry.test.ts b/apps/auth/tests/service-verify-sentry.test.ts
index 867b76ef..7eda528a 100644
--- a/apps/auth/tests/service-verify-sentry.test.ts
+++ b/apps/auth/tests/service-verify-sentry.test.ts
@@ -8,7 +8,7 @@ import { inspect } from 'node:util';
 import * as Sentry from '@sentry/node';
 import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
 
-import { limits, serviceUsers } from '@ansari/auth';
+import { getEnv, limits, serviceUsers } from '@ansari/auth';
 
 import { MCP_VERIFY_ALERT_MESSAGE, SERVICE_SENTRY_OPTIONS } from '../src/alerts';
 import { SERVICE_VERIFY_PATH } from '../src/routes/service-verify';
@@ -51,7 +51,7 @@ afterAll(async () => {
 
 async function mcpKey(userId: string, metadata: unknown = { clientId: 'ansari-mcp-production' }) {
   const { key } = await service.auth.api.createApiKey({
-    body: { userId, prefix: 'ansari_mcp_', permissions: MCP, metadata, rateLimitEnabled: false },
+    body: { userId, prefix: serviceUsers.keyPrefix('ansari-mcp', getEnv().ENVIRONMENT), permissions: MCP, metadata, rateLimitEnabled: false },
   });
   rawKeys.push(key);
   return key;
@@ -69,7 +69,7 @@ describe('Sentry events and logs from the verify route', () => {
     const owner = await serviceUsers.createServiceUser(service.db, 'ansari-mcp');
     const good = await mcpKey(owner.id);
     const offPattern = await mcpKey(owner.id, { clientId: 'claude-skill' });
-    const unknown = `ansari_mcp_${'Z'.repeat(64)}`;
+    const unknown = `${serviceUsers.keyPrefix('ansari-mcp', getEnv().ENVIRONMENT)}${'Z'.repeat(64)}`;
     rawKeys.push(unknown);
 
     expect((await post({ key: good, permissions: MCP })).status).toBe(200);
diff --git a/apps/auth/tests/service-verify.test.ts b/apps/auth/tests/service-verify.test.ts
index a22d2dcc..6b046534 100644
--- a/apps/auth/tests/service-verify.test.ts
+++ b/apps/auth/tests/service-verify.test.ts
@@ -97,7 +97,8 @@ async function scriptKey(name: ServiceName = 'ansari-mcp', on: Service = service
 /** A key the script would refuse to make (a key created outside it): in process, owned by `userId`. */
 async function outsideKey(userId: string, body: Record = {}, on: Service = service) {
   const created = await on.auth.api.createApiKey({
-    body: { userId, prefix: 'ansari_mcp_', name: 'outside', permissions: MCP, rateLimitEnabled: false, ...body },
+    // This environment's label by default, so the other checks are what the tests reach.
+    body: { userId, prefix: serviceUsers.keyPrefix('ansari-mcp', getEnv().ENVIRONMENT), name: 'outside', permissions: MCP, rateLimitEnabled: false, ...body },
   });
   return { key: remember(created.key), id: created.id };
 }
@@ -357,10 +358,7 @@ describe('the stored prefix (#314 Amendments 2 and 3)', () => {
   const served = { metadata: { clientId: 'ansari-mcp-production' } };
   const here = getEnv().ENVIRONMENT;
 
-  it.each([
-    ["this environment's label", serviceUsers.keyPrefix('ansari-mcp', here)],
-    ['the legacy bare prefix (compatibility window)', 'ansari_mcp_'],
-  ])('%s → served', async (_name, prefix) => {
+  it.each([["this environment's label", serviceUsers.keyPrefix('ansari-mcp', here)]])('%s → served', async (_name, prefix) => {
     const made = await outsideKey(mcpUserId, { ...served, prefix });
     expect(made.key.startsWith(prefix)).toBe(true);
     expect(JSON.parse((await verify(made.key)).text)).toEqual({
@@ -385,6 +383,8 @@ describe('the stored prefix (#314 Amendments 2 and 3)', () => {
     ['a foreign prefix', 'evil_'],
     ["a WhatsApp prefix for this environment", serviceUsers.keyPrefix('whatsapp', here)],
     ["WhatsApp's pre-rename legacy prefix", 'wa_'],
+    // No MCP window (second review, finding 1): no unlabelled MCP key can exist.
+    ['the bare ansari_mcp_ prefix', 'ansari_mcp_'],
     ['an unknown environment', 'ansari_mcp_qa_'],
     ['no prefix', undefined],
   ])('%s → the same { valid: false }', async (_name, prefix) => {
diff --git a/apps/auth/tests/whatsapp-session.test.ts b/apps/auth/tests/whatsapp-session.test.ts
index ef672dee..5c94a1d6 100644
--- a/apps/auth/tests/whatsapp-session.test.ts
+++ b/apps/auth/tests/whatsapp-session.test.ts
@@ -70,13 +70,12 @@ let key: string;
 /** A fresh exchange-alert window, so one test's counts never reach the next. */
 const nextAlertWindow = () => clock.advance(limits.EXCHANGE_ALERT_WINDOW * 1000);
 
+/** The alerts object of the service last started here, so a test can spy on what the route calls. */
+let exchangeAlerts: ReturnType;
+
 function startExchangeService(): Promise {
-  return startService({
-    exchange: {
-      alerts: createExchangeAlerts({ send: (alert) => alerts.push(alert), now: clock.now }),
-      now: clock.now,
-    },
-  });
+  exchangeAlerts = createExchangeAlerts({ send: (alert) => alerts.push(alert), now: clock.now });
+  return startService({ exchange: { alerts: exchangeAlerts, now: clock.now } });
 }
 
 beforeAll(async () => {
@@ -96,7 +95,9 @@ type KeyBody = Record;
 /** A key created in process, as the service-keys script does, owned by `userId`. */
 async function createKey(body: KeyBody = {}, on: Service = service, userId = serviceUserId) {
   const created = await on.auth.api.createApiKey({
-    body: { userId, prefix: 'ansari_wa_', name: 'test', permissions: WHATSAPP, rateLimitEnabled: false, ...body },
+    // This environment's label by default (second review, finding 2); the legacy
+    // prefixes have their own dedicated tests.
+    body: { userId, prefix: serviceUsers.keyPrefix('whatsapp', HERE), name: 'test', permissions: WHATSAPP, rateLimitEnabled: false, ...body },
   });
   remember(keyHash(created.key));
   return remember(created.key);
@@ -286,6 +287,30 @@ describe('key refusals: one byte-identical 401, no rows', () => {
 });
 
 describe('the exchange', () => {
+  it('keyVerified counts only a served key: never one refused for its prefix (second review, finding 6)', async () => {
+    const spy = vi.spyOn(exchangeAlerts, 'keyVerified');
+    try {
+      for (const prefix of [
+        ...ENVIRONMENTS.filter((e) => e !== HERE).map((e) => `ansari_wa_${e}_`),
+        'evil_',
+        serviceUsers.keyPrefix('ansari-mcp', HERE),
+      ]) {
+        const refused = await createKey({ prefix });
+        expect((await exchange(newBsuid(), newPhone(), { bearer: refused })).status, prefix).toBe(401);
+      }
+      expect(spy).not.toHaveBeenCalled();
+      expect((await exchange(newBsuid(), newPhone(), { bearer: await createKey() })).status).toBe(200);
+      expect(spy).toHaveBeenCalledTimes(1);
+    } finally {
+      spy.mockRestore();
+    }
+  });
+
+  it('a bare ansari_wa_ key (issued before #314) still exchanges during the compatibility window', async () => {
+    const legacy = await createKey({ prefix: 'ansari_wa_' });
+    expect((await exchange(newBsuid(), newPhone(), { bearer: legacy })).status).toBe(200);
+  });
+
   it('a pre-rename wa_ key (issued before 2026-10-30) still exchanges during the compatibility window (codex, PR #372)', async () => {
     const legacy = await createKey({ prefix: 'wa_' });
     expect(legacy.startsWith('wa_')).toBe(true);
@@ -686,7 +711,7 @@ describe('alerts', () => {
     const id = (await service.auth.api.createApiKey({
       body: {
         userId: serviceUserId,
-        prefix: 'ansari_wa_',
+        prefix: serviceUsers.keyPrefix('whatsapp', HERE),
         name: 'volume',
         permissions: WHATSAPP,
         rateLimitEnabled: true,
@@ -715,7 +740,7 @@ describe('alerts', () => {
     const created = await service.auth.api.createApiKey({
       body: {
         userId: serviceUserId,
-        prefix: 'ansari_wa_',
+        prefix: serviceUsers.keyPrefix('whatsapp', HERE),
         name: 'daily',
         permissions: WHATSAPP,
         rateLimitEnabled: false,
diff --git a/codev/specs/314-protect-v2-mcp-complete-with-b.md b/codev/specs/314-protect-v2-mcp-complete-with-b.md
index 0ed8db37..96977ec0 100644
--- a/codev/specs/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/specs/314-protect-v2-mcp-complete-with-b.md
@@ -4,7 +4,7 @@
 >
 > Amendment 2, 2026-11-12, owner (on PR #372; design accepted by the security architect): every service key's prefix names its environment, for WhatsApp and MCP alike: `ansari___`. Reason: the owner asked why the MCP client needed special handling. The client id is thread attribution; the environment in the prefix is key identification, so a leaked key reads as staging or production at a glance and secret scanning can tell them apart. One table in `packages/auth/src/service-users.ts` derives the prefixes, the accepted set, the secret-scanning patterns and the script's pasted-key check. Existing keys are unchanged (the plugin matches the hash; `apikey.prefix` is never rewritten): unlabelled `ansari_wa_` / `ansari_mcp_` keys stay accepted during a compatibility window (`LEGACY_UNLABELLED_KEYS`) and are rotated, never reissued in place. The MCP client-id rule is unchanged.
 >
-> Amendment 3, 2026-11-12, owner (supersedes Amendment 2's `--env` flag): apps/api and apps/auth gain `ENVIRONMENT` (`development` | `staging` | `production`, named to match the frontend's `EXPO_PUBLIC_ENVIRONMENT`). It is required, and `staging` or `production`, under `NODE_ENV=production` (both services refuse to boot otherwise, through the existing boot paths, never at build); it defaults to `development` elsewhere. It replaces `NODE_ENV` (apps/auth) and `RAILWAY_ENVIRONMENT || NODE_ENV` (apps/api) as the Sentry environment. It is the prefix's environment segment verbatim (`ansari_mcp_staging_`; longest `ansari_mcp_development_`, 23 characters, pinned by a test that creates a key with it). The service-keys script reads it from its process env and refuses to run without it. Both key routes serve only a key whose stored prefix names their own service and their own `ENVIRONMENT` (or the legacy bare prefix during the window); any other prefix is their ordinary refusal. Main's conditions (security architect, 2026-11-12): enforcement only on the existing boot paths, Sentry continuity stated in the PR, `ENVIRONMENT` in the `.env.example` and `.env.ci` files, RELEASE.md rows and a deploy-order line, and the unchanged-existing-keys note in the runbook. Owner directive (2026-11-12, via main): no code reads `RAILWAY_*` variables, only our own names, so `RAILWAY_ENVIRONMENT` leaves `turbo.json`.
+> Amendment 3, 2026-11-12, owner (supersedes Amendment 2's `--env` flag): apps/api and apps/auth gain `ENVIRONMENT` (`development` | `staging` | `production`, named after the legacy frontend's `EXPO_PUBLIC_ENVIRONMENT` (apps/frontend has no such variable; parity there is a separate follow-up)). It is required, and `staging` or `production`, under `NODE_ENV=production` (both services refuse to boot otherwise, through the existing boot paths, never at build); it defaults to `development` elsewhere. It replaces `NODE_ENV` (apps/auth) and `RAILWAY_ENVIRONMENT || NODE_ENV` (apps/api) as the Sentry environment. It is the prefix's environment segment verbatim (`ansari_mcp_staging_`; longest `ansari_mcp_development_`, 23 characters, pinned by a test that creates a key with it). The service-keys script reads it from its process env and refuses to run without it. Both key routes serve only a key whose stored prefix names their own service and their own `ENVIRONMENT` (or the legacy bare prefix during the window); any other prefix is their ordinary refusal. Main's conditions (security architect, 2026-11-12): enforcement only on the existing boot paths, Sentry continuity stated in the PR, `ENVIRONMENT` in the `.env.example` and `.env.ci` files, RELEASE.md rows and a deploy-order line, and the unchanged-existing-keys note in the runbook. Owner directive (2026-11-12, via main): no code reads `RAILWAY_*` variables, only our own names, so `RAILWAY_ENVIRONMENT` leaves `turbo.json`.
 
 ## Problem Statement
 
diff --git a/docs/cutover/service-keys-runbook.md b/docs/cutover/service-keys-runbook.md
index 42dfc1e5..b07defd9 100644
--- a/docs/cutover/service-keys-runbook.md
+++ b/docs/cutover/service-keys-runbook.md
@@ -260,11 +260,13 @@ per prefix, with exactly these patterns (the `.source` of `SECRET_SCANNING_PATTE
 | Service | Pattern |
 |---|---|
 | `whatsapp` | `ansari_wa_(?:(?:development\|staging\|production)_)?[A-Za-z]{64}` |
-| `ansari-mcp` | `ansari_mcp_(?:(?:development\|staging\|production)_)?[A-Za-z]{64}` |
+| `ansari-mcp` | `ansari_mcp_(?:development\|staging\|production)_[A-Za-z]{64}` |
 
 These replace the patterns registered before #314 (`ansari_wa_[A-Za-z]{64}` and
 `ansari_mcp_[A-Za-z]{64}`), which miss an environment-labelled key: edit each pattern in place.
-The environment segment is optional while unlabelled keys are live (next paragraph).
+The WhatsApp pattern's environment segment is optional while unlabelled WhatsApp keys are live
+(next paragraphs); the `ansari-mcp` pattern's is not, since no unlabelled MCP key can exist (its
+key path ships with #314).
 
 When one fires: **revoke the key at once** (`list`, then `revoke`), rotate so the consumer keeps
 working, check the alerts and the key's last request for use you cannot explain, and record it in
@@ -291,18 +293,27 @@ its hash, and `apikey.prefix` is written then and never rewritten. Adding the en
 re-issues nothing: the staging `ansari_wa_` keys keep their format and keep verifying under the
 compatibility window.
 
-**Rotate legacy keys (the compatibility window).** An unlabelled key (`ansari_wa_`, `ansari_mcp_`,
-or WhatsApp's pre-rename `wa_`, followed directly by 64 letters; `list` shows its `prefix`) is
-still accepted while `LEGACY_UNLABELLED_KEYS` is `true` (`LEGACY_PREFIXES` in
-`service-users.ts`). Replace it, never reissue it in place: `rotate  …` in
+**Rotate legacy keys (the compatibility window, WhatsApp only).** An unlabelled WhatsApp key
+(`ansari_wa_`, or the pre-rename `wa_`, followed directly by 64 letters; `list` shows its
+`prefix`) is still accepted while `LEGACY_UNLABELLED_KEYS` is `true` (`LEGACY_PREFIXES` in
+`service-users.ts`). `ansari-mcp` has no window: its verify route accepts only labelled keys.
+Before this deploys, `list ansari-mcp` on each auth database should show no key with the bare
+`ansari_mcp_` prefix; one made by hand on staging would be refused, so rotate it. Replace it, never reissue it in place: `rotate  …` in
 that environment's auth shell (a labelled key), hand it off to the consumer's variable, then
 `revoke` the old one. Staging has at least one (the
 WhatsApp smoke key). When `list whatsapp` and `list ansari-mcp` show no live unlabelled key on any
 database, retire the legacy form in one change: set `LEGACY_UNLABELLED_KEYS` to `false` in
-`packages/auth/src/service-users.ts` (the routes then refuse the bare prefix, and the script and
-the patterns stop accepting it), deploy, and re-register both patterns with the new `.source`
-(`ansari_wa_(?:development|staging|production)_[A-Za-z]{64}`, likewise for `ansari_mcp_`). The
-follow-up issue that closes the window is opened with this change's enforcement step.
+`packages/auth/src/service-users.ts` (the routes then refuse the legacy prefixes, and the script
+and the patterns stop accepting them), deploy, remove the `wa_` pattern, and re-register the
+patterns with their closed-window `.source` (`scanningPatternFor(service, false)`; tests pin
+these strings to the code):
+
+| Service | Pattern after the window closes |
+|---|---|
+| `whatsapp` | `ansari_wa_(?:development\|staging\|production)_[A-Za-z]{64}` |
+| `ansari-mcp` | `ansari_mcp_(?:development\|staging\|production)_[A-Za-z]{64}` |
+
+The follow-up issue that closes the window is opened with this change's enforcement step.
 
 ## The `ansari-mcp` key (#314)
 
@@ -326,6 +337,11 @@ revoked alone and its traffic is attributed to it:
 | `mcp-staging.askansari.ai` (apps/mcp on Railway, see `RELEASE.md`) | the operator, as a Railway service variable | `ansari-mcp-staging` (its `ANSARI_CLIENT`) | the staging auth shell (`ansari_mcp_staging_`) |
 | each apps/mcp Worker environment in use (apps/mcp's `wrangler.jsonc`) | the operator, as a Worker secret | its `ANSARI_CLIENT`: `ansari-mcp-dev`, `ansari-mcp-beta` or `ansari-mcp-production` | the auth shell of the environment whose apps/api that Worker calls |
 
+**Accepted residual: the label binds a key to its auth, not apps/api to its auth.** A production
+apps/api whose `AUTH_URL` points at staging auth (a dashboard mistake) verifies staging-labelled keys
+with every check passing, and nothing refuses or alerts. Check `AUTH_URL` against `ENVIRONMENT`
+on each apps/api deploy; a boot assertion pairing the two is a possible follow-up.
+
 1. apps/auth is deployed with the verify route (it ships with this change; there is no new
    migration: `auth.apikey` is spec 329's `0001`).
 2. Once: `create-service ansari-mcp`, then `create-service ansari-mcp --confirm ansari-mcp`.
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 169756ae..5fd870c5 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -117,7 +117,7 @@ empty-final retry ladder still applies as same-model retries.
 | `ANDROID_MINIMUM_BUILD_VERSION` | `1` | |
 | `ANDROID_LATEST_BUILD_VERSION` | `1` | |
 | `NODE_ENV` | `development` | `development` / `production` / `test` |
-| `ENVIRONMENT` | `development` | The deployment label (#314 Amendment 3): `development`, `staging` or `production`, the same vocabulary as `apps/auth` and the frontend's `EXPO_PUBLIC_ENVIRONMENT`. It is the Sentry environment. **Required when `NODE_ENV=production`**, and then only `staging` or `production`: a production boot without it, or labelled `development`, fails the boot check. `NODE_ENV` keeps its own jobs (test detection, production hardening) |
+| `ENVIRONMENT` | `development` | The deployment label (#314 Amendment 3): `development`, `staging` or `production`, the same vocabulary as `apps/auth`, named after the legacy frontend's `EXPO_PUBLIC_ENVIRONMENT` (apps/frontend has no such variable). It is the Sentry environment. **Required when `NODE_ENV=production`**, and then only `staging` or `production`: a production boot without it, or labelled `development`, fails the boot check. `NODE_ENV` keeps its own jobs (test detection, production hardening) |
 
 ### Outside the config schema (direct `process.env` reads)
 
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index a8e5d463..a8b6ea0b 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -59,7 +59,7 @@ export {
   type Mailer,
 } from './reset-email';
 export { CLIENT_HEADER, isMcpClientId, MCP_CLIENT_ID_PATTERN } from '@ansari/types/attribution';
-export { ENVIRONMENTS, environmentIssue, type Environment } from '@ansari/types/environment';
+export { DEFAULT_ENVIRONMENT, ENVIRONMENTS, environmentIssue, type Environment } from '@ansari/types/environment';
 
 /** Same bounds as the legacy register schema, and better-auth's own defaults. */
 export const MIN_PASSWORD_LENGTH = 8;
diff --git a/packages/auth/src/service-users.ts b/packages/auth/src/service-users.ts
index efcf87ba..ca84b344 100644
--- a/packages/auth/src/service-users.ts
+++ b/packages/auth/src/service-users.ts
@@ -42,8 +42,7 @@ export function isServiceName(name: string): name is ServiceName {
  * A key's prefix names the environment it was issued in (#314, owner
  * 2026-11-12, Amendments 2 and 3): `ansari___`, e.g.
  * `ansari_wa_production_`, `ansari_mcp_staging_`, where the environment is the
- * issuing apps/auth's ENVIRONMENT (one vocabulary with apps/api, the frontend
- * and Sentry). The script reads it from its process env; each route accepts
+ * issuing apps/auth's ENVIRONMENT (one vocabulary with apps/api and Sentry). The script reads it from its process env; each route accepts
  * only its own environment's prefix, so a key leaked from one environment is
  * readable as such and refused in another.
  */
@@ -52,38 +51,47 @@ export function keyPrefix(service: ServiceName, environment: Environment): strin
 }
 
 /**
- * Keys issued before #314 carry the bare service prefix (`ansari_wa_`, no
- * environment): at least one live staging WhatsApp key does. While this is
- * true the routes still accept that prefix, the secret-scanning patterns
- * still catch it and the script still refuses it pasted into a flag. The
- * compatibility window closes when `list` shows no live unlabelled key on any
- * database: set this to false and re-register the scanning patterns (the
- * runbook's "Rotate legacy keys" step and its follow-up issue).
+ * The compatibility window for keys issued before #314 (no environment in the
+ * prefix): at least one live staging WhatsApp key is one. While it is open the
+ * WhatsApp routes still accept LEGACY_PREFIXES, the secret-scanning patterns
+ * still catch them, and the script still refuses them pasted into a flag. It
+ * closes when `list` shows no live unlabelled key on any database: set this to
+ * false and re-register the scanning patterns (the runbook's "Rotate legacy
+ * keys" step and its follow-up issue). Typed `boolean`, so both states are
+ * live code: the pure builders below take the state as a parameter, and the
+ * tests run both.
  */
-export const LEGACY_UNLABELLED_KEYS = true;
+export const LEGACY_UNLABELLED_KEYS: boolean = true;
 
 /**
- * The prefixes a route of `service` running as `environment` accepts: that
- * environment's, plus the legacy unlabelled prefixes (LEGACY_PREFIXES) while
- * LEGACY_UNLABELLED_KEYS holds. Any other stored prefix (another environment's, another service's, a
- * hand-made one) is the route's ordinary refusal.
- */
-export function acceptedKeyPrefixes(service: ServiceName, environment: Environment): readonly string[] {
-  const own = keyPrefix(service, environment);
-  return LEGACY_UNLABELLED_KEYS ? [own, ...LEGACY_PREFIXES[service]] : [own];
-}
-
-/**
- * The unlabelled prefixes keys were issued with before #314, per service: the
- * bare base prefix, and for WhatsApp also `wa_`, the prefix before the
- * 2026-10-30 rename (the runbook's "prefix change"), since a live `wa_` key
- * cannot be ruled out. Accepted only while LEGACY_UNLABELLED_KEYS holds.
+ * The unlabelled prefixes keys were issued with before #314, per service:
+ * WhatsApp's bare base prefix and `wa_`, the prefix before the 2026-10-30
+ * rename (the runbook's "prefix change"), since a live `wa_` key cannot be
+ * ruled out. None for `ansari-mcp`: its key path ships with #314, so no
+ * unlabelled MCP key can exist, and the MCP window is closed from the start
+ * (second review, finding 1).
  */
 export const LEGACY_PREFIXES: Readonly> = {
   whatsapp: ['ansari_wa_', 'wa_'],
-  'ansari-mcp': ['ansari_mcp_'],
+  'ansari-mcp': [],
 };
 
+/**
+ * The prefixes a route of `service` running as `environment` accepts, with the
+ * window open (`legacy`) or closed: that environment's, plus LEGACY_PREFIXES
+ * while the window is open. Any other stored prefix (another environment's,
+ * another service's, a hand-made one) is the route's ordinary refusal.
+ */
+export function acceptedKeyPrefixesFor(service: ServiceName, environment: Environment, legacy: boolean): readonly string[] {
+  const own = keyPrefix(service, environment);
+  return legacy ? [own, ...LEGACY_PREFIXES[service]] : [own];
+}
+
+/** acceptedKeyPrefixesFor with the window as it stands (LEGACY_UNLABELLED_KEYS). */
+export function acceptedKeyPrefixes(service: ServiceName, environment: Environment): readonly string[] {
+  return acceptedKeyPrefixesFor(service, environment, LEGACY_UNLABELLED_KEYS);
+}
+
 /** True when a verified key's stored prefix is one `service`'s route in `environment` accepts. */
 export function isAcceptedKeyPrefix(service: ServiceName, environment: Environment, prefix: unknown): boolean {
   return typeof prefix === 'string' && acceptedKeyPrefixes(service, environment).includes(prefix);
@@ -92,42 +100,47 @@ export function isAcceptedKeyPrefix(service: ServiceName, environment: Environme
 /** The plugin's key body: 64 letters (its default length and alphabet). */
 const KEY_BODY = '[A-Za-z]{64}';
 
-function scanningPattern(service: ServiceName): RegExp {
+/**
+ * The GitHub custom secret-scanning pattern for `service`, window open
+ * (`legacy`) or closed: the base prefix, an ENVIRONMENT segment (optional only
+ * while the window is open and the bare base prefix is a legacy prefix of the
+ * service), and the plugin's 64-letter key.
+ */
+export function scanningPatternFor(service: ServiceName, legacy: boolean): RegExp {
+  const base = SERVICES[service].prefix;
   const envs = `(?:${ENVIRONMENTS.join('|')})_`;
-  return new RegExp(`${SERVICES[service].prefix}${LEGACY_UNLABELLED_KEYS ? `(?:${envs})?` : envs}${KEY_BODY}`);
+  const bareAccepted = legacy && LEGACY_PREFIXES[service].includes(base);
+  return new RegExp(`${base}${bareAccepted ? `(?:${envs})?` : envs}${KEY_BODY}`);
 }
 
 /**
- * GitHub custom secret-scanning patterns, one per service, derived from the
- * same table as keyPrefix: the base prefix, any ENVIRONMENT segment (optional
- * while LEGACY_UNLABELLED_KEYS holds), and the plugin's 64-letter key. The
- * script's pasted-key refusal uses these too, so the three never disagree. The
- * runbook asks the owner to register exactly these (`.source`) for the
- * organisation.
+ * The extra patterns the window needs for `service`: one per legacy prefix the
+ * main pattern does not already cover (today only WhatsApp's `wa_`); none
+ * once the window is closed.
  */
-export const SECRET_SCANNING_PATTERNS: Readonly> = {
-  whatsapp: scanningPattern('whatsapp'),
-  'ansari-mcp': scanningPattern('ansari-mcp'),
-};
+export function legacyScanningPatternsFor(service: ServiceName, legacy: boolean): RegExp[] {
+  if (!legacy) return [];
+  return LEGACY_PREFIXES[service].filter((prefix) => prefix !== SERVICES[service].prefix).map((prefix) => new RegExp(`${prefix}${KEY_BODY}`));
+}
 
 /**
- * The extra patterns the legacy window needs, derived from LEGACY_PREFIXES: one
- * per legacy prefix that the main pattern does not already cover (today only
- * WhatsApp's pre-rename `wa_`). Registered beside the main ones until the
- * window closes; empty once LEGACY_UNLABELLED_KEYS is false. Every prefix a
- * route accepts is caught by one of the two lists (tested).
+ * The patterns to register now (LEGACY_UNLABELLED_KEYS applied), derived from
+ * the same table as keyPrefix. The script's pasted-key refusal uses these too,
+ * so the three never disagree. The runbook asks the owner to register exactly
+ * these (`.source`) for the organisation, and prints the closed-window sources
+ * (scanningPatternFor(service, false)) for the day the window closes; tests
+ * assert both against the runbook.
  */
-export const LEGACY_SCANNING_PATTERNS: Readonly> = {
-  whatsapp: legacyScanningPatterns('whatsapp'),
-  'ansari-mcp': legacyScanningPatterns('ansari-mcp'),
+export const SECRET_SCANNING_PATTERNS: Readonly> = {
+  whatsapp: scanningPatternFor('whatsapp', LEGACY_UNLABELLED_KEYS),
+  'ansari-mcp': scanningPatternFor('ansari-mcp', LEGACY_UNLABELLED_KEYS),
 };
 
-function legacyScanningPatterns(service: ServiceName): RegExp[] {
-  if (!LEGACY_UNLABELLED_KEYS) return [];
-  return LEGACY_PREFIXES[service]
-    .filter((prefix) => prefix !== SERVICES[service].prefix)
-    .map((prefix) => new RegExp(`${prefix}${KEY_BODY}`));
-}
+/** The legacy patterns to register beside them now (empty once the window closes). Every accepted prefix is caught by one of the two lists (tested). */
+export const LEGACY_SCANNING_PATTERNS: Readonly> = {
+  whatsapp: legacyScanningPatternsFor('whatsapp', LEGACY_UNLABELLED_KEYS),
+  'ansari-mcp': legacyScanningPatternsFor('ansari-mcp', LEGACY_UNLABELLED_KEYS),
+};
 
 export type ServiceUser = { id: string; email: string; createdAt: Date };
 
diff --git a/packages/types/src/environment.ts b/packages/types/src/environment.ts
index 5c3356b6..457db0b4 100644
--- a/packages/types/src/environment.ts
+++ b/packages/types/src/environment.ts
@@ -1,6 +1,6 @@
 /**
  * The deployment label (#314 Amendment 3, owner 2026-11-12): `ENVIRONMENT`,
- * named to match the frontend's `EXPO_PUBLIC_ENVIRONMENT`, in apps/api and
+ * named after the legacy frontend's `EXPO_PUBLIC_ENVIRONMENT` (apps/frontend has no such variable; parity there is a separate follow-up), in apps/api and
  * apps/auth. It is the Sentry environment of both services and the
  * environment segment of every service-key prefix (`ansari___`).
  * NODE_ENV keeps its own jobs (test detection, production hardening);

From 790331f2712df097c4b48a81bd5c79336a8fe94b Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:20:45 +1100
Subject: [PATCH 170/435] [Spec 314] docs: no MCP legacy window everywhere it
 was stated; second-review record, probe output, lesson

---
 codev/resources/arch.md                       |  2 +-
 codev/resources/lessons-learned.md            |  1 +
 .../314-protect-v2-mcp-complete-with-b.md     | 40 ++++++++++++++++++-
 .../314-protect-v2-mcp-complete-with-b.md     |  2 +-
 docs/self-hosting.md                          |  5 ++-
 5 files changed, 45 insertions(+), 5 deletions(-)

diff --git a/codev/resources/arch.md b/codev/resources/arch.md
index 62aa3c69..a332c330 100644
--- a/codev/resources/arch.md
+++ b/codev/resources/arch.md
@@ -22,7 +22,7 @@ Better Auth, in its own service (spec 300). `packages/auth` (`@ansari/auth`) is
 
 **Admin & system identity.** Admin = `auth.users.role === 'admin'` (and not banned), asked of `apps/auth`'s `GET /api/account/me` with the admin's own JWT on **every** admin request (`requireAdmin`): a demotion, a ban or a revoked session applies at once, an outage fails closed (503). Never an email match, never a JWT claim. Roles are granted by `apps/auth/scripts/grant-admin.ts`, which never creates an account or touches a password, in two steps: `` shows id, email, `created_at`, `email_verified` and role and grants nothing; ` --confirm ` grants exactly that account. It never grants to a system- or noreply-domain address (`--revoke`, a demotion, is allowed for any account: it is the repair for a WhatsApp user found holding `admin`) and warns on a recent or unverified account (no email verification exists, so an address can be squatted). There is no admin list and no boot check (owner amendment H-7). System identities (`ai-skill`, `leaderboard`) exist only as app rows found by `system_key` (`getOrCreateSystemUser`), with no auth row and no credential; `@system.ansari.chat` is reserved.
 
-**Service keys and the WhatsApp exchange (spec 329).** A **service** (`whatsapp`; `ansari-mcp`, #314) is one auth user with no credential under `@noreply.askansari.ai`, found by its `{provider_id: 'service', account_id: }` row, never by email. Its keys come from `@better-auth/api-key` (pinned with core), rows in `auth.apikey` holding only the SHA-256 hash, each with its own per-window limit and daily refilled budget, no expiry, and fixed per-service permissions and base prefix (`ansari_wa_`, `ansari_mcp_`), so a key for one service is refused at another's route. Since #314 (Amendments 2 and 3) the full prefix names the environment the key was issued in, `ansari___`, where `ENVIRONMENT` (`development|staging|production`, required under `NODE_ENV=production` in apps/auth and apps/api, also their Sentry environment) is read by the script from its process env; one table in `service-users.ts` derives the prefixes, the accepted set and the secret-scanning patterns. Both routes serve only a key whose stored `apikey.prefix` names their own service and their own `ENVIRONMENT`, so a key leaked from one environment is refused in another; the bare legacy prefix is accepted while `LEGACY_UNLABELLED_KEYS` holds (compatibility window, closed by a follow-up). The plugin's HTTP surface is blocked; `apps/auth/scripts/service-keys.ts` is the only issuer (shown, then confirmed by id; the raw key printed once; a Sentry record of each write, with no key material). `enableSessionForAPIKeys` is off: a key is never a session. `POST /api/whatsapp/session` (mounted before CORS and outside Better Auth's router, so no per-IP rule and no CORS) verifies the key in process (`verifyApiKey` with `whatsapp: mint`), finds or creates the BSUID's user through `account (provider_id = 'whatsapp', account_id = )` (`unique (provider_id, account_id)` makes it one user under concurrency), checks eligibility under a lock on the user row (only that account row, its own `whatsapp-@noreply.askansari.ai` address, `registered_via = 'whatsapp'`, role exactly `user`, an allowlist; otherwise 500, never a token) and the ban (403, sessions deleted), reuses one session per user, and signs the ordinary `{sub, sid}` JWT after commit. So a key can only ever yield tokens for WhatsApp users: never an email user, an admin, a system or a service account. The BSUID lives only in `account.account_id` and reaches no log, response or `apps/api`. No phone number is stored anywhere (owner amendment 2): a `phone_number` the WhatsApp service sends is accepted and ignored. `@noreply.askansari.ai` is refused at sign-up (as a taken address), reset (as an unknown one), a grant by `grant-admin.ts`, and the `user.create.before` hook on every Better Auth path. **apps/api has no WhatsApp code** (a source scan); the exchange JWT passes `requireUser` unchanged. **Alert posture:** the exchange's alerts (per-key volume at one third of the caps, key refusals, 401 volume, ineligible users, an unresolvable service user) carry key ids, counts, thresholds and windows only in Sentry (a key id is a plugin-made UUID that names a credential, not a person, and matches `list`); user ids appear only in server log lines, and the service's Sentry keeps no breadcrumbs, so a logged id never rides on an event. `apps/auth` refuses to boot without `auth.apikey` or the constraint (migration `0001`). Operator procedure: `docs/cutover/service-keys-runbook.md`.
+**Service keys and the WhatsApp exchange (spec 329).** A **service** (`whatsapp`; `ansari-mcp`, #314) is one auth user with no credential under `@noreply.askansari.ai`, found by its `{provider_id: 'service', account_id: }` row, never by email. Its keys come from `@better-auth/api-key` (pinned with core), rows in `auth.apikey` holding only the SHA-256 hash, each with its own per-window limit and daily refilled budget, no expiry, and fixed per-service permissions and base prefix (`ansari_wa_`, `ansari_mcp_`), so a key for one service is refused at another's route. Since #314 (Amendments 2 and 3) the full prefix names the environment the key was issued in, `ansari___`, where `ENVIRONMENT` (`development|staging|production`, required under `NODE_ENV=production` in apps/auth and apps/api, also their Sentry environment) is read by the script from its process env; one table in `service-users.ts` derives the prefixes, the accepted set and the secret-scanning patterns. Both routes serve only a key whose stored `apikey.prefix` names their own service and their own `ENVIRONMENT`, so a key leaked from one environment is refused in another; WhatsApp's legacy prefixes (`ansari_wa_`, `wa_`) are accepted while `LEGACY_UNLABELLED_KEYS` holds (compatibility window, closed by a follow-up); MCP has no window. The plugin's HTTP surface is blocked; `apps/auth/scripts/service-keys.ts` is the only issuer (shown, then confirmed by id; the raw key printed once; a Sentry record of each write, with no key material). `enableSessionForAPIKeys` is off: a key is never a session. `POST /api/whatsapp/session` (mounted before CORS and outside Better Auth's router, so no per-IP rule and no CORS) verifies the key in process (`verifyApiKey` with `whatsapp: mint`), finds or creates the BSUID's user through `account (provider_id = 'whatsapp', account_id = )` (`unique (provider_id, account_id)` makes it one user under concurrency), checks eligibility under a lock on the user row (only that account row, its own `whatsapp-@noreply.askansari.ai` address, `registered_via = 'whatsapp'`, role exactly `user`, an allowlist; otherwise 500, never a token) and the ban (403, sessions deleted), reuses one session per user, and signs the ordinary `{sub, sid}` JWT after commit. So a key can only ever yield tokens for WhatsApp users: never an email user, an admin, a system or a service account. The BSUID lives only in `account.account_id` and reaches no log, response or `apps/api`. No phone number is stored anywhere (owner amendment 2): a `phone_number` the WhatsApp service sends is accepted and ignored. `@noreply.askansari.ai` is refused at sign-up (as a taken address), reset (as an unknown one), a grant by `grant-admin.ts`, and the `user.create.before` hook on every Better Auth path. **apps/api has no WhatsApp code** (a source scan); the exchange JWT passes `requireUser` unchanged. **Alert posture:** the exchange's alerts (per-key volume at one third of the caps, key refusals, 401 volume, ineligible users, an unresolvable service user) carry key ids, counts, thresholds and windows only in Sentry (a key id is a plugin-made UUID that names a credential, not a person, and matches `list`); user ids appear only in server log lines, and the service's Sentry keeps no breadcrumbs, so a logged id never rides on an event. `apps/auth` refuses to boot without `auth.apikey` or the constraint (migration `0001`). Operator procedure: `docs/cutover/service-keys-runbook.md`.
 
 **The MCP key and its verify route (#314).** `/v2/mcp-complete` is apps/api's one route that takes something other than a JWT: `Authorization: Bearer ` (scheme case-insensitive; a token outside apps/auth's `[\x21-\x7E]{1,256}` envelope is `missing`, no call). apps/api cannot verify the key itself (the hash lives in the auth database), so on every request it asks apps/auth at its public origin, `POST /api/service/verify-key` with `{key, permissions: {mcp: ['complete']}}` (`verifyServiceKey`, `lib/auth-service/client.ts`, 3 s timeout). The route calls `verifyApiKey` in process, mounted ahead of CORS and outside Better Auth's router (no per-IP rule, no credential but the key), and serves a **closed permission set**: exactly `{mcp: ['complete']}` for the `ansari-mcp` service user, anything else 400, so it can neither verify nor spend a WhatsApp key under its own permission. It answers `{valid: true, client_id, key_id}` or one byte-identical `{valid: false}` for every refusal, including a key whose `client_id` is not `ansari-mcp*` (the script refuses to make one; the `client-id-invalid` alert names it) and a key whose stored prefix is not in the `ansari-mcp` accepted set; apps/api accepts only those two shapes, anything else is an outage. **Fail closed:** refused → 401, outage or timeout → 503, before any persistence or model call. The thread's `client` is the key's `client_id`; `X-Ansari-Client` is ignored (Sentry warning on a mismatch). Each verify spends one unit of the key's own budget and window, which is the throttle (one key per MCP deployment, 120 per minute and 5,000 a day initially); the route's per-IP cap in apps/api stays. **Log-only transition:** `MCP_COMPLETE_KEY_MODE=log-only` verifies, records the verdict (`valid`/`missing`/`refused`/`unverified`, log line and Sentry tag `mcp_key_verdict`) and always serves; absent means `enforce`, anything else fails boot. The mode, its `turbo.json` entry and log-only itself are to be removed by a follow-up issue due one week after enforcement. Verify alerts mirror the exchange's under `auth: MCP key verify alert`. A plugin bump that ever routes `/api-key/verify` fails `apps/auth/tests/blocked-paths.test.ts`.
 
diff --git a/codev/resources/lessons-learned.md b/codev/resources/lessons-learned.md
index 28cf41ed..1aa68102 100644
--- a/codev/resources/lessons-learned.md
+++ b/codev/resources/lessons-learned.md
@@ -249,3 +249,4 @@ See `codev/reviews/329-apps-auth-service-api-keys-bet.md` for the full context.
 - **(spec 314) Read the published package, not the plugin docs.** The docs' `POST /api-key/verify` comes only from a JSDoc comment. `verifyApiKey` is server-only, with no route, in 1.7.7, 1.7.20 and 1.8.0-beta.7. On any plugin bump, re-run the upgrade guard in `apps/auth/tests/blocked-paths.test.ts`, which checks the endpoint shapes and that a newly routed path is under the blocked prefix.
 - **(spec 314) In a verify path, count a success only after the last check.** Calling `keyVerified()` before the owner and client-id checks let refused keys inflate the volume alerts. Pin the order with a test that fails under the old order.
 - **(spec 314) Pin a remote verdict's refusal shape on both sides.** apps/auth asserts a byte-identical `{"valid":false}`. apps/api accepts only that shape and treats anything else as an outage (503). Adding a field on one side turns every bad key into a 503, so both sides must change together.
+- **(spec 314) Scope a compatibility window to what it protects.** A legacy-prefix window meant for one live WhatsApp key was first applied to every service, which left the brand-new MCP route accepting a cross-environment prefix class that protected no key. Make the window's state a parameter of pure builders and test both states, so closing it is a one-line change that the tests already cover.
diff --git a/codev/reviews/314-protect-v2-mcp-complete-with-b.md b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
index 61c9e895..bd1fd880 100644
--- a/codev/reviews/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
@@ -162,8 +162,44 @@ Codex and Gemini approved with no issues.
 ### Review / PR #372 (Round 5, codex only)
 Codex: **APPROVE**, no issues. It confirmed all four round-4 fixes.
 
+### Second external review (security architect's reviewer, Claude; over 0798cfce..b9391cc7)
+
+REQUEST_CHANGES: eleven required fixes and one coverage item. The architect agreed with every one. All were **Addressed** in 1f936578:
+
+1. **The MCP legacy window protected no key, but kept a cross-environment prefix class open.** `LEGACY_PREFIXES['ansari-mcp'] = []`, so the bare `ansari_mcp_` prefix is now refused (tested), and the MCP scanning pattern has no optional segment.
+2. **The window's closed state was unreachable and untested.** The flag is now a parameter of `acceptedKeyPrefixesFor`, `scanningPatternFor` and `legacyScanningPatternsFor`, with both states tested and no pin on the flag's value. The runbook's post-window table is asserted against `scanningPatternFor(s, false)`. WhatsApp tests use a labelled key by default.
+3. **The no-`RAILWAY_*` rule was unguarded.** Source-scan 6 covers apps/api, apps/auth, packages/auth and apps/mcp/src (planted lines, near-misses, exact allowlist: apps/mcp's `RAILWAY_GIT_COMMIT_SHA`, #377). Main's requirement: `apps/mcp/src/**` is now an `ansari-api#test` input. Negative test: clean `6f4ceeadd09c4cad`, planted `f8a848194d5da3e2` (and scan 6 failed), restored byte-identically to `6f4ceeadd09c4cad`.
+4. **apps/api's Sentry environment was unasserted.** `tests/sentry-environment.test.ts` now checks it.
+5. **The label binds key to auth, not api to auth.** Recorded as an accepted residual in the runbook; a boot assertion pairing the two is a possible follow-up.
+6. **The exchange counted `keyVerified` before the owner and prefix gates.** Moved after them; a spy test proves it doesn't fire for refused prefixes, and it fails under the old order.
+7. **Two environment knobs.** The route options no longer take one; `createApp` passes it.
+8. **The script initialised Sentry before validating `ENVIRONMENT`.** It validates first now, and the hardcoded `'development'` is gone.
+9. **The api test key had a shape no script can issue.** It is now `ansari_mcp_staging_…`.
+10. **Docs named `EXPO_PUBLIC_ENVIRONMENT` as the frontend's.** Corrected to the legacy frontend's, in all three places.
+11. **Minor:** leak-scan includes `LEGACY_PREFIXES`; boot-check deletes `NEXT_PHASE` instead of setting it to undefined.
+12. **Spawned production boots.** Probes `apps/{auth,api}/scripts/probes/environment-boot-probe.ts`, output below.
+
 Apart from those Gemini skips, no `CONSULT_ERROR` occurred.
 
+## Production boot probes (finding 12)
+
+apps/auth (built `dist/index.mjs`, `NODE_ENV=production`, unreachable database):
+```
+PASS  NODE_ENV=production ENVIRONMENT=(absent) → refused (names: ENVIRONMENT)
+PASS  NODE_ENV=production ENVIRONMENT=development → refused (names: ENVIRONMENT)
+PASS  NODE_ENV=production ENVIRONMENT=prod → refused (names: ENVIRONMENT)
+PASS  NODE_ENV=production ENVIRONMENT=staging → listened
+PASS  NODE_ENV=production ENVIRONMENT=production → listened
+```
+apps/api (`next start` on the built app, `NODE_ENV=production`, unreachable database):
+```
+PASS  NODE_ENV=production ENVIRONMENT=(absent) → /api/health 500, ENVIRONMENT rule logged
+PASS  NODE_ENV=production ENVIRONMENT=development → /api/health 500, ENVIRONMENT rule logged
+PASS  NODE_ENV=production ENVIRONMENT=prod → /api/health 500, ENVIRONMENT rule logged
+PASS  NODE_ENV=production ENVIRONMENT=staging → /api/health 503
+PASS  NODE_ENV=production ENVIRONMENT=production → /api/health 503
+```
+
 ## Lessons Learned
 
 ### What Went Well
@@ -223,10 +259,12 @@ Neither test was skipped. Both are pre-existing, outside this change, and passed
 
 ## Follow-up Items
 
-- **Close the legacy-key compatibility window:** once `list` shows no live unlabelled key (`ansari_wa_`, `ansari_mcp_`, or pre-rename `wa_`) on any database, set `LEGACY_UNLABELLED_KEYS = false` and re-register the scanning patterns. The issue is opened at enforce, like the log-only removal.
+- **Close the legacy-key compatibility window (WhatsApp only):** once `list` shows no live unlabelled key (`ansari_wa_` or pre-rename `wa_`) on any database, set `LEGACY_UNLABELLED_KEYS = false` and re-register the scanning patterns. The issue is opened at enforce, like the log-only removal.
 
 - **Remove log-only:** open the issue at enforce (rollout step 6). It removes `MCP_COMPLETE_KEY_MODE` from `config.ts` and the `turbo.json` `globalEnv` hunk one week after enforcement. The issue number is to be recorded when it exists.
 - **Limit sizing:** `MCP_KEY_INITIAL` (120/60 s, 5,000/day) and the alert thresholds are judgement values. The owner should resize them with `update-limits` (no deploy) once the `threads.client` query numbers are in.
+- **Boot assertion pairing `ENVIRONMENT` with the `AUTH_URL` host:** closes the residual in the runbook (a production apps/api pointed at staging auth). This was not built in this PR.
+- **`ENVIRONMENT` parity in apps/frontend:** it has no such variable today; only the legacy frontend has `EXPO_PUBLIC_ENVIRONMENT`. That parity is app's lane, on the owner's word.
 - **Owner steps outside the repository:** listed under Spec Compliance. The published snippet and MCP setup page locations are pending from the owner.
 - **`@better-auth/api-key` upgrade to 1.7.20:** out of scope. On any bump, re-run the upgrade guard in `apps/auth/tests/blocked-paths.test.ts` and the runbook's plugin-upgrade check.
 - **`cutover-docs.test.ts` `namedRepoPaths`:** add an end boundary after the extension so `.jsonc` is not read as `.json`. This is main's test infrastructure.
diff --git a/codev/specs/314-protect-v2-mcp-complete-with-b.md b/codev/specs/314-protect-v2-mcp-complete-with-b.md
index 96977ec0..721b69cd 100644
--- a/codev/specs/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/specs/314-protect-v2-mcp-complete-with-b.md
@@ -2,7 +2,7 @@
 
 > Amendment 1, 2026-11-11, security architect: scenario 2 expired-key row. The api-key plugin deletes an expired key when it is presented, so scenario 2's "each row kept" excludes it. A plugin fact, not a design change; no `ansari-mcp` key can expire (the script refuses `--expir*`).
 >
-> Amendment 2, 2026-11-12, owner (on PR #372; design accepted by the security architect): every service key's prefix names its environment, for WhatsApp and MCP alike: `ansari___`. Reason: the owner asked why the MCP client needed special handling. The client id is thread attribution; the environment in the prefix is key identification, so a leaked key reads as staging or production at a glance and secret scanning can tell them apart. One table in `packages/auth/src/service-users.ts` derives the prefixes, the accepted set, the secret-scanning patterns and the script's pasted-key check. Existing keys are unchanged (the plugin matches the hash; `apikey.prefix` is never rewritten): unlabelled `ansari_wa_` / `ansari_mcp_` keys stay accepted during a compatibility window (`LEGACY_UNLABELLED_KEYS`) and are rotated, never reissued in place. The MCP client-id rule is unchanged.
+> Amendment 2, 2026-11-12, owner (on PR #372; design accepted by the security architect): every service key's prefix names its environment, for WhatsApp and MCP alike: `ansari___`. Reason: the owner asked why the MCP client needed special handling. The client id is thread attribution; the environment in the prefix is key identification, so a leaked key reads as staging or production at a glance and secret scanning can tell them apart. One table in `packages/auth/src/service-users.ts` derives the prefixes, the accepted set, the secret-scanning patterns and the script's pasted-key check. Existing keys are unchanged (the plugin matches the hash; `apikey.prefix` is never rewritten): unlabelled WhatsApp keys (`ansari_wa_`, and the pre-rename `wa_`) stay accepted during a compatibility window (`LEGACY_UNLABELLED_KEYS`) and are rotated, never reissued in place. No unlabelled MCP key can exist (its key path ships here), so the MCP route has no window (second external review, 2026-11-12). The MCP client-id rule is unchanged.
 >
 > Amendment 3, 2026-11-12, owner (supersedes Amendment 2's `--env` flag): apps/api and apps/auth gain `ENVIRONMENT` (`development` | `staging` | `production`, named after the legacy frontend's `EXPO_PUBLIC_ENVIRONMENT` (apps/frontend has no such variable; parity there is a separate follow-up)). It is required, and `staging` or `production`, under `NODE_ENV=production` (both services refuse to boot otherwise, through the existing boot paths, never at build); it defaults to `development` elsewhere. It replaces `NODE_ENV` (apps/auth) and `RAILWAY_ENVIRONMENT || NODE_ENV` (apps/api) as the Sentry environment. It is the prefix's environment segment verbatim (`ansari_mcp_staging_`; longest `ansari_mcp_development_`, 23 characters, pinned by a test that creates a key with it). The service-keys script reads it from its process env and refuses to run without it. Both key routes serve only a key whose stored prefix names their own service and their own `ENVIRONMENT` (or the legacy bare prefix during the window); any other prefix is their ordinary refusal. Main's conditions (security architect, 2026-11-12): enforcement only on the existing boot paths, Sentry continuity stated in the PR, `ENVIRONMENT` in the `.env.example` and `.env.ci` files, RELEASE.md rows and a deploy-order line, and the unchanged-existing-keys note in the runbook. Owner directive (2026-11-12, via main): no code reads `RAILWAY_*` variables, only our own names, so `RAILWAY_ENVIRONMENT` leaves `turbo.json`.
 
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 5fd870c5..4cfb2379 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -246,8 +246,9 @@ shown first and confirmed by id). The create and rotate commands print the raw k
 script reads `ENVIRONMENT` from its process env (it refuses to run without it) and puts it in the
 key's prefix: `ansari___`, e.g. `ansari_wa_production_`. Each route serves
 only a key whose stored prefix names its own service and its own `ENVIRONMENT`, so a key leaked
-from one environment is refused in another; a key issued before #314 (bare `ansari_wa_` /
-`ansari_mcp_`) is still accepted during the compatibility window the runbook describes.
+from one environment is refused in another; a WhatsApp key issued before #314 (bare `ansari_wa_`, or the
+pre-rename `wa_`) is still accepted during the compatibility window the runbook describes. MCP
+keys have no window: only labelled ones are served.
 `docs/cutover/service-keys-runbook.md` is the operator's procedure: issuance, handoff, rotation,
 revocation, the alerts and the eligibility repair.
 

From 5e47e104ffee83e2c154c83f3e71877a6fb8534e Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:23:42 +1100
Subject: [PATCH 171/435] [Spec 314][Phase: review] fix: scan 6 covers
 apps/api/scripts; comments match the closed MCP window and the
 legacy-frontend origin (codex)

---
 apps/api/sentry.server.config.ts               | 3 ++-
 apps/api/tests/source-scan/source-scan.test.ts | 6 +++++-
 apps/auth/src/routes/service-verify.ts         | 8 ++++----
 apps/auth/src/routes/whatsapp.ts               | 2 +-
 4 files changed, 12 insertions(+), 7 deletions(-)

diff --git a/apps/api/sentry.server.config.ts b/apps/api/sentry.server.config.ts
index c1140e21..602069c3 100644
--- a/apps/api/sentry.server.config.ts
+++ b/apps/api/sentry.server.config.ts
@@ -6,7 +6,8 @@ Sentry.init({
   dsn: process.env.SENTRY_DSN,
   enabled: process.env.NODE_ENV !== "test" && !process.env.VITEST,
   // The deployment label (#314 Amendment 3), the same vocabulary as apps/auth
-  // and the frontend. Validated at production boot (lib/boot-check.ts, which
+  // (named after the legacy frontend's EXPO_PUBLIC_ENVIRONMENT; apps/frontend
+  // has no such variable). Validated at production boot (lib/boot-check.ts, which
   // runs right after this file); unset only outside production.
   environment: process.env.ENVIRONMENT || "development",
   tracesSampleRate: process.env.NODE_ENV === "production" ? 0.1 : 1.0,
diff --git a/apps/api/tests/source-scan/source-scan.test.ts b/apps/api/tests/source-scan/source-scan.test.ts
index 85a007d4..bd7bb9d0 100644
--- a/apps/api/tests/source-scan/source-scan.test.ts
+++ b/apps/api/tests/source-scan/source-scan.test.ts
@@ -290,6 +290,9 @@ describe('scan 5: apps/api has no WhatsApp-specific code (spec 329)', () => {
 describe('scan 6: no code reads a RAILWAY_* variable (owner directive 2026-11-12, #314)', () => {
   // apps/api, apps/auth (with packages/auth) and apps/mcp's server source.
   const MCP_RUNTIME = sourceFiles('apps/mcp/src');
+  // apps/api's operator scripts too (codex): API_RUNTIME is what `next build`
+  // compiles, but a script reading RAILWAY_* breaks the rule just as well.
+  const API_SCRIPTS = sourceFiles('apps/api/scripts');
 
   it('catches planted lines, whatever the access path', () => {
     for (const bad of [
@@ -317,8 +320,9 @@ describe('scan 6: no code reads a RAILWAY_* variable (owner directive 2026-11-12
   });
 
   it('the allowlist is exact: its one entry is present, and nothing else is', () => {
-    const files = [...API_RUNTIME, ...AUTH_RUNTIME, ...MCP_RUNTIME];
+    const files = [...API_RUNTIME, ...API_SCRIPTS, ...AUTH_RUNTIME, ...MCP_RUNTIME];
     expect(MCP_RUNTIME.length).toBeGreaterThan(10);
+    expect(API_SCRIPTS.length).toBeGreaterThan(0);
     expect(files.length).toBeGreaterThan(100);
     const hits = scanTree(files, railwayEnvHits);
     report('RAILWAY_* reads (apps/api + apps/auth + apps/mcp runtime)', files, hits);
diff --git a/apps/auth/src/routes/service-verify.ts b/apps/auth/src/routes/service-verify.ts
index 95ccfc91..b4fc8c8e 100644
--- a/apps/auth/src/routes/service-verify.ts
+++ b/apps/auth/src/routes/service-verify.ts
@@ -78,8 +78,8 @@ const internalError = (res: Response) => res.status(500).json({ message: 'Intern
 
 /**
  * `environment` is this deployment's ENVIRONMENT (#314 Amendment 3): only a key
- * whose stored prefix names it, or a legacy prefix while the window is open, is
- * served. createApp passes it; it is the one place it is set.
+ * whose stored prefix names it is served. `ansari-mcp` has no legacy window
+ * (LEGACY_PREFIXES['ansari-mcp'] is empty). createApp passes it; it is the one place it is set.
  */
 export function serviceVerifyRouter({ auth, db }: ServiceDeps, options: VerifyOptions, environment: Environment): Router {
   const alerts = options.alerts ?? createMcpVerifyAlerts();
@@ -135,8 +135,8 @@ export function serviceVerifyRouter({ auth, db }: ServiceDeps, options: VerifyOp
       if (verified.key.referenceId !== owner.user.id) return refuse(res);
       // A key whose stored prefix is not this service's and this environment's
       // (another environment's label, another service's, a hand-made one) is
-      // the same refusal (#314 Amendment 3). The legacy bare prefix is accepted
-      // while serviceUsers.LEGACY_UNLABELLED_KEYS holds.
+      // the same refusal (#314 Amendment 3). No legacy prefix is accepted here:
+      // the MCP window is closed (second external review, finding 1).
       if (!serviceUsers.isAcceptedKeyPrefix(SERVICE, environment, verified.key.prefix)) return refuse(res);
 
       const clientId = serviceUsers.clientIdOf(verified.key.metadata);
diff --git a/apps/auth/src/routes/whatsapp.ts b/apps/auth/src/routes/whatsapp.ts
index 5dc51747..9e60532c 100644
--- a/apps/auth/src/routes/whatsapp.ts
+++ b/apps/auth/src/routes/whatsapp.ts
@@ -131,7 +131,7 @@ export function whatsappRouter({ auth, db }: ServiceDeps, options: ExchangeOptio
       if (verified.key.referenceId !== owner.user.id) return refuse(res);
       // A key whose stored prefix is not this service's and this environment's
       // (another environment's label, another service's, a hand-made one) is
-      // the same refusal (#314 Amendment 3). The legacy bare prefix is accepted
+      // the same refusal (#314 Amendment 3). The legacy prefixes (`ansari_wa_`, `wa_`) are accepted
       // while serviceUsers.LEGACY_UNLABELLED_KEYS holds.
       if (!serviceUsers.isAcceptedKeyPrefix(SERVICE, environment, verified.key.prefix)) return refuse(res);
       // Counted only for a key that is served, as on the verify route: a wrong

From 2e82ece5811df205c33aa616f06a800700156632 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:25:11 +1100
Subject: [PATCH 172/435] [Spec 314] Review rounds 6-7 (codex APPROVE),
 second-review record

---
 .../314-review-iter6-codex.txt                | 30 +++++++++++++++++++
 .../314-review-iter6-context.md               | 15 ++++++++++
 .../314-review-iter6-rebuttals.md             |  8 +++++
 .../314-review-iter7-codex.txt                | 19 ++++++++++++
 .../314-review-iter7-context.md               |  2 ++
 .../314-protect-v2-mcp-complete-with-b.md     |  4 +++
 6 files changed, 78 insertions(+)
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-context.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-rebuttals.md
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter7-codex.txt
 create mode 100644 codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter7-context.md

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-codex.txt
new file mode 100644
index 00000000..177d83a6
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-codex.txt
@@ -0,0 +1,30 @@
+---
+VERDICT: REQUEST_CHANGES
+SUMMARY: Core fixes are correct, but the required RAILWAY_* scan does not cover all apps/api code.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- `API_RUNTIME` omits `apps/api/scripts/**`, unlike the auth scan. Consequently, a `RAILWAY_*` read in an API operator script bypasses source-scan 6. Add `sourceFiles('apps/api/scripts')`.
+- Stale comments still imply MCP accepts a legacy prefix (`service-verify.ts:81,138`) and that apps/frontend shares `ENVIRONMENT` (`sentry.server.config.ts:9`). Update them to match the closed MCP window and legacy-frontend origin.
+
+PR_SUMMARY: |
+  ## Summary
+  Protects `/v2/mcp-complete` with environment-labelled MCP service keys verified through apps/auth. It also adds production environment validation, rollout documentation, source guards, and production-shaped boot probes.
+
+  ## Key Changes
+  - Adds MCP key verification, attribution, refusal handling, and log-only rollout mode.
+  - Adds environment-labelled service keys and closes the MCP legacy-prefix window.
+  - Adds source scans, Sentry assertions, boot probes, and operational documentation.
+
+  ## Test Plan
+  - Run API, auth, and shared-package unit/integration suites.
+  - Run both production boot probes against an unreachable database.
+  - Verify source-scan 6 fails for planted `RAILWAY_*` reads in every covered tree.
+
+---
+
+## ⚠️ REPOSITORY MOVED during the codex review (#1649).
+A consultant reviews the commit in front of it; it must never commit, or switch refs.
+  - HEAD: 1f936578211a1681a57acd1cfa57dc97864aad99 -> 790331f2712df097c4b48a81bd5c79336a8fe94b
+The files on disk may look untouched and still not be the ones this review describes.
+Check `git reflog` and `git status` before trusting this review or shipping the branch.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-context.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-context.md
new file mode 100644
index 00000000..dc1edcf8
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-context.md
@@ -0,0 +1,15 @@
+# PR #372 re-review (iteration 6): the second external review's fixes
+
+A second external review (security architect's reviewer, over 0798cfce..b9391cc7) returned REQUEST_CHANGES with eleven required fixes plus one coverage item. The fix is commit 1f936578, plus main's mcp dev PORT change in 41c787d6. Please confirm each item, and review the fix diff for regressions:
+1. LEGACY_PREFIXES['ansari-mcp'] = [] (the MCP window is closed; the bare ansari_mcp_ prefix is refused).
+2. The legacy flag is a parameter of the pure builders (acceptedKeyPrefixesFor, scanningPatternFor, legacyScanningPatternsFor). Both states are tested, and the runbook's post-window table is asserted against scanningPatternFor(s, false). WhatsApp tests use a labelled key by default.
+3. Source-scan 6 covers RAILWAY_* names in apps/api, apps/auth, packages/auth and apps/mcp/src, with planted lines, near-misses and an exact allowlist (apps/mcp RAILWAY_GIT_COMMIT_SHA, #377). apps/mcp/src is an ansari-api#test turbo input, negative-tested by hash.
+4. apps/api sentry.server.config.ts environment test.
+5. Runbook accepted residual: the label binds key to auth, not api to auth.
+6. The WhatsApp exchange's keyVerified() is after the owner and prefix gates; a spy test proves it doesn't fire for refused prefixes.
+7. One environment knob: removed from the route options; createApp passes it.
+8. service-keys.ts validates ENVIRONMENT before scriptRecorder/Sentry.init; no hardcoded 'development'.
+9. The apps/api test key is ansari_mcp_staging_.
+10. Docs: named after the LEGACY frontend's EXPO_PUBLIC_ENVIRONMENT.
+11. leak-scan includes LEGACY_PREFIXES; boot-check uses delete for NEXT_PHASE.
+12. Spawned NODE_ENV=production boot probes for both services (apps/auth and apps/api scripts/probes/environment-boot-probe.ts).
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-rebuttals.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-rebuttals.md
new file mode 100644
index 00000000..23555282
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter6-rebuttals.md
@@ -0,0 +1,8 @@
+# Review (PR #372), iteration 6 (second external review's fixes): responses
+
+## Codex (REQUEST_CHANGES)
+
+1. **Scan 6 omitted `apps/api/scripts/**`.** Accepted. It is now in scan 6's file set, with a floor asserting it is non-empty. It is not added to `API_RUNTIME`, which scans 1-3 share and which means "what `next build` compiles".
+2. **Stale comments** (`service-verify.ts`: an MCP legacy prefix; `sentry.server.config.ts`: "the frontend"). Accepted and fixed; the WhatsApp exchange comment names its two legacy prefixes.
+
+Fixed in 5e47e104.
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter7-codex.txt b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter7-codex.txt
new file mode 100644
index 00000000..84fa8d07
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter7-codex.txt
@@ -0,0 +1,19 @@
+---
+VERDICT: APPROVE
+SUMMARY: Iteration 6 findings are fixed; the reviewed 1f936578..HEAD changes introduce no new issues.
+CONFIDENCE: HIGH
+---
+KEY_ISSUES:
+- None
+
+PR_SUMMARY: |
+  ## Summary
+  Protects `/api/v2/mcp-complete` with environment-labelled `ansari-mcp` service keys verified through apps/auth. Requests fail closed while supporting a temporary log-only rollout mode.
+
+  ## Key Changes
+  - Adds service-key verification, trusted client attribution, environment validation, and operational documentation.
+  - Covers `apps/api/scripts` in the `RAILWAY_*` source scan and corrects legacy-window and frontend-origin comments.
+
+  ## Test Plan
+  - Run the API and auth unit/integration suites and production boot probes.
+  - Verify missing/refused keys return 401, auth outages return 503, and valid keys attribute requests correctly.
\ No newline at end of file
diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter7-context.md b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter7-context.md
new file mode 100644
index 00000000..3cd52f49
--- /dev/null
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/314-review-iter7-context.md
@@ -0,0 +1,2 @@
+# PR #372 re-review (iteration 7)
+Iteration 6 (codex REQUEST_CHANGES): (1) scan 6 now includes apps/api/scripts; (2) the stale comments are fixed (5e47e104). See 314-review-iter6-rebuttals.md. Please confirm, and review the fix diff (1f936578..HEAD) for anything else.
diff --git a/codev/reviews/314-protect-v2-mcp-complete-with-b.md b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
index bd1fd880..71e695dd 100644
--- a/codev/reviews/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
@@ -179,6 +179,10 @@ REQUEST_CHANGES: eleven required fixes and one coverage item. The architect agre
 11. **Minor:** leak-scan includes `LEGACY_PREFIXES`; boot-check deletes `NEXT_PHASE` instead of setting it to undefined.
 12. **Spawned production boots.** Probes `apps/{auth,api}/scripts/probes/environment-boot-probe.ts`, output below.
 
+### Review / PR #372 (Rounds 6-7, codex, on the second-review fixes)
+- **Round 6, REQUEST_CHANGES:** scan 6 missed `apps/api/scripts`, and three comments were stale → **Addressed** in 5e47e104.
+- **Round 7: APPROVE**, no issues.
+
 Apart from those Gemini skips, no `CONSULT_ERROR` occurred.
 
 ## Production boot probes (finding 12)

From 9937eb6f617aa9b16e8cf9d7836ba8088e897077 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:30:14 +1100
Subject: [PATCH 173/435] [Spec 314] chore(mcp): dev builds once, via turbo's
 cached build dependency; dev:mcp runs through turbo; clear message when dist
 is missing (owner)

---
 apps/mcp/README.md      | 2 +-
 apps/mcp/package.json   | 2 +-
 apps/mcp/scripts/dev.ts | 8 ++++++++
 package.json            | 2 +-
 4 files changed, 11 insertions(+), 3 deletions(-)

diff --git a/apps/mcp/README.md b/apps/mcp/README.md
index 1ae57bf8..6d21e711 100644
--- a/apps/mcp/README.md
+++ b/apps/mcp/README.md
@@ -62,7 +62,7 @@ pnpm mcp test:browser
 pnpm mcp start
 ```
 
-`build` writes `dist/view.html` and a bundled `dist/server/index.js`. No API/auth/frontend build or SDK source checkout is needed. `dev` builds, then runs the Node entry source through `scripts/dev.ts` (see below). The synthetic browser harness is test-only and uses no credentials or live answers.
+`build` writes `dist/view.html` and a bundled `dist/server/index.js`. No API/auth/frontend build or SDK source checkout is needed. `dev` runs the Node entry source through `scripts/dev.ts` (see below) and needs `dist/view.html`: under turbo (`pnpm dev`, `pnpm dev:mcp`) the cached `build` task runs first (it shows as its own task, `ansari-mcp#build`); run directly, `pnpm mcp build` first. The synthetic browser harness is test-only and uses no credentials or live answers.
 
 ### Local development
 
diff --git a/apps/mcp/package.json b/apps/mcp/package.json
index df5add1c..63d2617f 100644
--- a/apps/mcp/package.json
+++ b/apps/mcp/package.json
@@ -11,7 +11,7 @@
   "scripts": {
     "build": "tsx scripts/build.ts",
     "start": "node dist/server/index.js",
-    "dev": "pnpm build && tsx scripts/dev.ts",
+    "dev": "tsx scripts/dev.ts",
     "typecheck": "tsc --noEmit",
     "test": "tsx --test test/*.test.ts",
     "test:browser": "tsx test/browser.ts",
diff --git a/apps/mcp/scripts/dev.ts b/apps/mcp/scripts/dev.ts
index 66ca1624..d1997478 100644
--- a/apps/mcp/scripts/dev.ts
+++ b/apps/mcp/scripts/dev.ts
@@ -10,6 +10,14 @@
 import {existsSync} from 'node:fs';
 import {fileURLToPath} from 'node:url';
 
+// The built card (dist/view.html) is read at start. Under turbo (`pnpm dev`,
+// `pnpm dev:mcp`) apps/mcp/turbo.json's `dev` dependsOn `build`, a cached task;
+// run directly, build first.
+if (!existsSync(fileURLToPath(new URL('../dist/view.html', import.meta.url)))) {
+  console.error('[mcp dev] dist/view.html is missing: run `pnpm dev` or `pnpm dev:mcp` (they build first), or `pnpm mcp build`.');
+  process.exit(1);
+}
+
 const envFile = fileURLToPath(new URL('../.env', import.meta.url));
 if (existsSync(envFile)) process.loadEnvFile(envFile);
 
diff --git a/package.json b/package.json
index 743deb56..bd9491d6 100644
--- a/package.json
+++ b/package.json
@@ -13,7 +13,7 @@
     "dev": "turbo run dev --ui=tui",
     "dev:no-auth": "turbo run dev --ui=tui --filter=!ansari-auth --filter=!ansari-mcp",
     "dev:auth": "pnpm --filter ansari-auth dev",
-    "dev:mcp": "pnpm --filter ansari-mcp dev",
+    "dev:mcp": "turbo run dev --ui=tui --filter=ansari-mcp",
     "lint": "turbo run lint",
     "typecheck": "turbo run typecheck --filter=!ansari-mcp",
     "test": "turbo run test --filter=!ansari-mcp -- --maxWorkers=4",

From cd2c2a1d37546fccc47ce43d93c2d27631d5b328 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:35:50 +1100
Subject: [PATCH 174/435] [Spec 314][Phase: review] fix: apps/mcp/src in
 ansari-api#test:coverage inputs; Sentry env test matches reads only and bites
 on planted configs; service-keys forwards the validated ENVIRONMENT
 (security)

---
 apps/api/tests/sentry-environment.test.ts | 38 ++++++++++++++++-------
 apps/api/turbo.json                       |  3 +-
 apps/auth/scripts/service-keys.ts         |  2 +-
 3 files changed, 29 insertions(+), 14 deletions(-)

diff --git a/apps/api/tests/sentry-environment.test.ts b/apps/api/tests/sentry-environment.test.ts
index 4739ff13..d5bc2885 100644
--- a/apps/api/tests/sentry-environment.test.ts
+++ b/apps/api/tests/sentry-environment.test.ts
@@ -9,21 +9,35 @@ import { fileURLToPath } from 'node:url';
 import { describe, expect, it } from 'vitest';
 
 const config = readFileSync(fileURLToPath(new URL('../sentry.server.config.ts', import.meta.url)), 'utf8');
-const environmentLine = config.split('\n').find((line) => /^\s*environment\s*:/.test(line));
 
-describe('sentry.server.config.ts environment', () => {
-  it('is process.env.ENVIRONMENT', () => {
-    expect(environmentLine).toBeDefined();
-    expect(environmentLine).toContain('process.env.ENVIRONMENT');
-  });
+/** A READ of a RAILWAY_* variable (a comment naming one is fine). */
+const RAILWAY_READ = /process\.env\.RAILWAY_|process\.env\[\s*['"`]RAILWAY_/;
 
-  it('reads neither RAILWAY_* nor NODE_ENV for it', () => {
-    expect(environmentLine).not.toMatch(/RAILWAY|NODE_ENV/);
-    expect(config).not.toMatch(/RAILWAY/);
+/** The problems with a Sentry server config's environment; empty when it is right. */
+function environmentProblems(source: string): string[] {
+  const line = source.split('\n').find((l) => /^\s*environment\s*:/.test(l));
+  const problems: string[] = [];
+  if (line === undefined) return ['no environment line'];
+  if (!line.includes('process.env.ENVIRONMENT')) problems.push('environment is not process.env.ENVIRONMENT');
+  if (/NODE_ENV/.test(line)) problems.push('environment reads NODE_ENV');
+  if (RAILWAY_READ.test(source)) problems.push('reads a RAILWAY_* variable');
+  return problems;
+}
+
+describe('sentry.server.config.ts environment', () => {
+  it('is process.env.ENVIRONMENT, with no NODE_ENV and no RAILWAY_* read', () => {
+    expect(environmentProblems(config)).toEqual([]);
   });
 
-  it('the check bites: the pre-#314 line fails it', () => {
-    const old = '  environment: process.env.RAILWAY_ENVIRONMENT || process.env.NODE_ENV,';
-    expect(old).toMatch(/RAILWAY|NODE_ENV/);
+  it('the check bites on planted configs, and passes a comment that names the old variable', () => {
+    const planted = (environment: string, extra = '') => `Sentry.init({\n${extra}  environment: ${environment},\n});\n`;
+    expect(environmentProblems(planted('process.env.RAILWAY_ENVIRONMENT || process.env.NODE_ENV'))).toEqual([
+      'environment is not process.env.ENVIRONMENT',
+      'environment reads NODE_ENV',
+      'reads a RAILWAY_* variable',
+    ]);
+    expect(environmentProblems(planted('process.env.NODE_ENV'))).toContain('environment reads NODE_ENV');
+    expect(environmentProblems(planted("process.env['RAILWAY_ENVIRONMENT']"))).toContain('reads a RAILWAY_* variable');
+    expect(environmentProblems(planted('process.env.ENVIRONMENT', '  // not RAILWAY_ENVIRONMENT (#314)\n'))).toEqual([]);
   });
 });
diff --git a/apps/api/turbo.json b/apps/api/turbo.json
index 2ce19ed8..667eeea0 100644
--- a/apps/api/turbo.json
+++ b/apps/api/turbo.json
@@ -57,8 +57,9 @@
     // CI runs the same pin through test:coverage, so it needs the root
     // package.json too. Overriding `inputs` replaces the root task's list, so
     // the inherited entries are repeated.
+    // apps/mcp/src likewise, for source-scan 6 (#314): CI runs it through this task.
     "test:coverage": {
-      "inputs": ["$TURBO_DEFAULT$", ".env.ci", "$TURBO_ROOT$/package.json"]
+      "inputs": ["$TURBO_DEFAULT$", ".env.ci", "$TURBO_ROOT$/package.json", "$TURBO_ROOT$/apps/mcp/src/**"]
     }
   }
 }
diff --git a/apps/auth/scripts/service-keys.ts b/apps/auth/scripts/service-keys.ts
index fe502ad2..9cd2284a 100644
--- a/apps/auth/scripts/service-keys.ts
+++ b/apps/auth/scripts/service-keys.ts
@@ -690,7 +690,7 @@ async function main(): Promise {
   const recorder = scriptRecorder(process.env.SENTRY_DSN, environment);
   const { exitCode } = await serviceKeys(process.argv.slice(2), {
     databaseUrl: process.env.DATABASE_URL,
-    environment: process.env.ENVIRONMENT,
+    environment, // validated above: one validation
     connect: () => {
       try {
         getEnv();

From bc2b52424e6e5e6a761bd999235de3a4aba19fd6 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:42:08 +1100
Subject: [PATCH 175/435] [Spec 314] chore(mcp): pnpm mcp inspect opens the MCP
 Inspector on the local dev server (owner)

---
 apps/mcp/README.md    | 2 +-
 apps/mcp/package.json | 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/apps/mcp/README.md b/apps/mcp/README.md
index 6d21e711..c917d25f 100644
--- a/apps/mcp/README.md
+++ b/apps/mcp/README.md
@@ -79,7 +79,7 @@ pnpm exec tsx scripts/service-keys.ts create-key ansari-mcp --rate-max 120 --rat
 ANSARI_API_AUTHORIZATION=Bearer ansari_mcp_development_<64 letters>
 ```
 
-or run apps/api with `MCP_COMPLETE_KEY_MODE=log-only`, which serves requests without a key and logs the verdict `missing`. Without either, every tool call fails: apps/api answers 401, and the dev server warns at start. The dev entry is for local work only; deployments run `pnpm start` (`dist/`) or the Worker entry.
+or run apps/api with `MCP_COMPLETE_KEY_MODE=log-only`, which serves requests without a key and logs the verdict `missing`. To try the tools by hand, `pnpm mcp inspect` opens the MCP Inspector (latest, via npx) connected to `http://localhost:3001/mcp` over Streamable HTTP; call `answer_islamic_question` from its Tools tab. Without either, every tool call fails: apps/api answers 401, and the dev server warns at start. The dev entry is for local work only; deployments run `pnpm start` (`dist/`) or the Worker entry.
 
 ### Two hosting targets, one application
 
diff --git a/apps/mcp/package.json b/apps/mcp/package.json
index 63d2617f..b99ec0be 100644
--- a/apps/mcp/package.json
+++ b/apps/mcp/package.json
@@ -12,6 +12,7 @@
     "build": "tsx scripts/build.ts",
     "start": "node dist/server/index.js",
     "dev": "tsx scripts/dev.ts",
+    "inspect": "npx -y @modelcontextprotocol/inspector --web --transport http --server-url http://localhost:3001/mcp",
     "typecheck": "tsc --noEmit",
     "test": "tsx --test test/*.test.ts",
     "test:browser": "tsx test/browser.ts",

From 0de420ad4db37d98d4871cf41efd0543956f3dc2 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:42:43 +1100
Subject: [PATCH 176/435] [Spec 314] docs(mcp): inspector sentence in its own
 paragraph after 'Without either' (main)

---
 apps/mcp/README.md | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/apps/mcp/README.md b/apps/mcp/README.md
index c917d25f..36b063e0 100644
--- a/apps/mcp/README.md
+++ b/apps/mcp/README.md
@@ -79,7 +79,9 @@ pnpm exec tsx scripts/service-keys.ts create-key ansari-mcp --rate-max 120 --rat
 ANSARI_API_AUTHORIZATION=Bearer ansari_mcp_development_<64 letters>
 ```
 
-or run apps/api with `MCP_COMPLETE_KEY_MODE=log-only`, which serves requests without a key and logs the verdict `missing`. To try the tools by hand, `pnpm mcp inspect` opens the MCP Inspector (latest, via npx) connected to `http://localhost:3001/mcp` over Streamable HTTP; call `answer_islamic_question` from its Tools tab. Without either, every tool call fails: apps/api answers 401, and the dev server warns at start. The dev entry is for local work only; deployments run `pnpm start` (`dist/`) or the Worker entry.
+or run apps/api with `MCP_COMPLETE_KEY_MODE=log-only`, which serves requests without a key and logs the verdict `missing`. Without either, every tool call fails: apps/api answers 401, and the dev server warns at start. The dev entry is for local work only; deployments run `pnpm start` (`dist/`) or the Worker entry.
+
+To try the tools by hand, `pnpm mcp inspect` opens the MCP Inspector (latest, via npx) connected to `http://localhost:3001/mcp` over Streamable HTTP; call `answer_islamic_question` from its Tools tab.
 
 ### Two hosting targets, one application
 

From 49510dab934f034789d50f7cdfbfd45297af05f0 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:52:01 +1100
Subject: [PATCH 177/435] [Spec 314] ENVIRONMENT has no default anywhere
 (owner): required in every process; fixtures set development; Sentry reads it
 with no fallback

---
 apps/api/.env.example                           |  4 ++--
 apps/api/lib/config.ts                          | 11 ++++++-----
 apps/api/sentry.server.config.ts                |  6 +++---
 apps/api/tests/auth/helpers.ts                  |  1 +
 apps/api/tests/boot-check.test.ts               |  7 ++++++-
 apps/api/tests/config.test.ts                   |  1 +
 apps/api/tests/db-lazy-init.test.ts             |  1 +
 apps/api/tests/gemini-fast-failover.test.ts     |  1 +
 apps/api/tests/gemini-rawpayload.test.ts        |  1 +
 apps/api/tests/gemini-repetition.test.ts        |  1 +
 apps/api/tests/gemini-stream-retry.test.ts      |  1 +
 apps/api/tests/gemini-timeout.test.ts           |  1 +
 apps/api/tests/gemini-truncation.test.ts        |  1 +
 apps/api/tests/gemini.test.ts                   |  1 +
 apps/api/tests/hadith-lk-id.test.ts             |  1 +
 apps/api/tests/helpers/mcp-key.ts               |  1 +
 apps/api/tests/inkling-env-config.test.ts       |  1 +
 apps/api/tests/kalemat-resilience.test.ts       |  1 +
 apps/api/tests/mcp-complete-key.test.ts         |  1 +
 apps/api/tests/openai-compat.test.ts            |  1 +
 .../api/tests/threads-token-persistence.test.ts |  1 +
 apps/api/tests/tool-citability.test.ts          |  1 +
 apps/api/tests/tools.test.ts                    |  1 +
 apps/api/tests/usul-retry.test.ts               |  1 +
 apps/auth/.env.example                          |  4 ++--
 apps/auth/tests/environment.test.ts             | 17 ++++++++++++-----
 .../plans/314-protect-v2-mcp-complete-with-b.md |  2 +-
 .../specs/314-protect-v2-mcp-complete-with-b.md |  2 +-
 codev/state/spir-314_thread.md                  |  1 +
 docs/self-hosting.md                            |  2 +-
 packages/auth/src/env.ts                        | 12 +++++-------
 packages/auth/src/index.ts                      |  2 +-
 packages/auth/tests/helpers/auth-db.ts          |  1 +
 packages/types/src/environment.ts               |  7 +++----
 34 files changed, 65 insertions(+), 33 deletions(-)

diff --git a/apps/api/.env.example b/apps/api/.env.example
index 274e1d19..e5933b3c 100644
--- a/apps/api/.env.example
+++ b/apps/api/.env.example
@@ -93,6 +93,6 @@ NODE_ENV=development
 # MCP_COMPLETE_KEY_MODE=enforce
 
 # The deployment label (#314 Amendment 3): development, staging or production. The Sentry
-# environment and the service-key prefix environment. Required, and staging or production,
-# when NODE_ENV=production; development otherwise.
+# environment and the service-key prefix environment. Required everywhere, no default; staging or
+# production when NODE_ENV=production.
 ENVIRONMENT=development
diff --git a/apps/api/lib/config.ts b/apps/api/lib/config.ts
index c30a083f..df9f2179 100644
--- a/apps/api/lib/config.ts
+++ b/apps/api/lib/config.ts
@@ -1,4 +1,4 @@
-import { DEFAULT_ENVIRONMENT, ENVIRONMENTS, environmentIssue } from '@ansari/types/environment';
+import { ENVIRONMENTS, environmentIssue } from '@ansari/types/environment';
 import { z } from 'zod';
 
 const AUTH_SERVICE_VARS = [
@@ -134,10 +134,11 @@ export const envSchema = z.object({
 
   // Optional
   NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
-  // The deployment label (#314 Amendment 3): the Sentry environment. Required,
-  // and staging or production, under NODE_ENV=production (below); development
-  // otherwise. Enforced at production boot (lib/boot-check.ts), never at build.
-  ENVIRONMENT: z.enum(ENVIRONMENTS).default(DEFAULT_ENVIRONMENT),
+  // The deployment label (#314 Amendment 3): the Sentry environment. Required
+  // everywhere, no default (owner, 2026-11-12); staging or production under
+  // NODE_ENV=production (below). Checked at production boot
+  // (lib/boot-check.ts), at first config access elsewhere, never at build.
+  ENVIRONMENT: z.enum(ENVIRONMENTS),
 }).superRefine((env, ctx) => {
   const environment = environmentIssue(env.NODE_ENV, env.ENVIRONMENT);
   if (environment) ctx.addIssue({ code: 'custom', path: ['ENVIRONMENT'], message: environment });
diff --git a/apps/api/sentry.server.config.ts b/apps/api/sentry.server.config.ts
index 602069c3..8d896877 100644
--- a/apps/api/sentry.server.config.ts
+++ b/apps/api/sentry.server.config.ts
@@ -7,9 +7,9 @@ Sentry.init({
   enabled: process.env.NODE_ENV !== "test" && !process.env.VITEST,
   // The deployment label (#314 Amendment 3), the same vocabulary as apps/auth
   // (named after the legacy frontend's EXPO_PUBLIC_ENVIRONMENT; apps/frontend
-  // has no such variable). Validated at production boot (lib/boot-check.ts, which
-  // runs right after this file); unset only outside production.
-  environment: process.env.ENVIRONMENT || "development",
+  // has no such variable). Required everywhere, no default (owner, 2026-11-12);
+  // validated at production boot (lib/boot-check.ts, right after this file).
+  environment: process.env.ENVIRONMENT,
   tracesSampleRate: process.env.NODE_ENV === "production" ? 0.1 : 1.0,
   ...SENTRY_REQUEST_PRIVACY,
 });
diff --git a/apps/api/tests/auth/helpers.ts b/apps/api/tests/auth/helpers.ts
index a3fdc3e7..dcd57120 100644
--- a/apps/api/tests/auth/helpers.ts
+++ b/apps/api/tests/auth/helpers.ts
@@ -48,6 +48,7 @@ export function setApiEnv(authUrl: string): void {
   process.env.DATABASE_URL = 'postgres://test:test@localhost:5432/test';
   process.env.KALEMAT_API_KEY = 'placeholder';
   process.env.USUL_API_TOKEN = 'placeholder';
+  process.env.ENVIRONMENT = 'development';
   process.env.AUTH_URL = authUrl;
   process.env.AUTH_JWT_ISSUER = TEST_ISSUER;
   process.env.AUTH_JWT_AUDIENCE = TEST_AUDIENCE;
diff --git a/apps/api/tests/boot-check.test.ts b/apps/api/tests/boot-check.test.ts
index 482f230e..4b7d11ea 100644
--- a/apps/api/tests/boot-check.test.ts
+++ b/apps/api/tests/boot-check.test.ts
@@ -16,6 +16,7 @@ const BASE_ENV = {
   DATABASE_URL: 'postgresql://user:pass@localhost:5432/db',
   KALEMAT_API_KEY: 'placeholder',
   USUL_API_TOKEN: 'placeholder',
+  ENVIRONMENT: 'development',
 };
 const AUTH_ENV = {
   AUTH_URL: 'https://auth.askansari.ai',
@@ -89,7 +90,7 @@ describe('validateEnvAtBoot', () => {
     expect(() => validateEnvAtBoot()).not.toThrow();
   });
 
-  it('next build and dev run without ENVIRONMENT; outside production it defaults to development', async () => {
+  it('next build never parses the env; outside a build ENVIRONMENT is required, with no default (owner, 2026-11-12)', async () => {
     process.env = { ...process.env, ...SERVER, NEXT_PHASE: 'phase-production-build' };
     delete process.env.ENVIRONMENT;
     expect(() => validateEnvAtBoot()).not.toThrow();
@@ -98,6 +99,10 @@ describe('validateEnvAtBoot', () => {
     resetEnvCache();
     const { getEnv } = await import('@/lib/config');
     expect(getEnv().ENVIRONMENT).toBe('development');
+    // Absent in a dev process: the first config access fails, naming it.
+    delete process.env.ENVIRONMENT;
+    resetEnvCache();
+    expect(() => getEnv()).toThrow(/ENVIRONMENT/);
   });
 
   it('a build or a dev server never parses the env', () => {
diff --git a/apps/api/tests/config.test.ts b/apps/api/tests/config.test.ts
index 394d7618..4196c3ea 100644
--- a/apps/api/tests/config.test.ts
+++ b/apps/api/tests/config.test.ts
@@ -10,6 +10,7 @@ const REQUIRED_ENV: Record = {
   DATABASE_URL: 'postgresql://user:pass@localhost:5432/db',
   KALEMAT_API_KEY: 'placeholder-key',
   USUL_API_TOKEN: 'placeholder-token',
+  ENVIRONMENT: 'development',
 };
 
 let savedEnv: NodeJS.ProcessEnv;
diff --git a/apps/api/tests/db-lazy-init.test.ts b/apps/api/tests/db-lazy-init.test.ts
index c87e563d..2d1a3f77 100644
--- a/apps/api/tests/db-lazy-init.test.ts
+++ b/apps/api/tests/db-lazy-init.test.ts
@@ -10,6 +10,7 @@ const REQUIRED_ENV: Record = {
   DATABASE_URL: 'postgresql://user:pass@localhost:5432/db',
   KALEMAT_API_KEY: 'placeholder-key',
   USUL_API_TOKEN: 'placeholder-token',
+  ENVIRONMENT: 'development',
 };
 
 let savedEnv: NodeJS.ProcessEnv;
diff --git a/apps/api/tests/gemini-fast-failover.test.ts b/apps/api/tests/gemini-fast-failover.test.ts
index 2edbfe75..f14eca7e 100644
--- a/apps/api/tests/gemini-fast-failover.test.ts
+++ b/apps/api/tests/gemini-fast-failover.test.ts
@@ -74,6 +74,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
   process.env.GEMINI_MODEL = 'gemini-primary';
   process.env.GEMINI_FALLBACK_MODEL = 'gemini-fallback';
   sdk.establishCalls = 0;
diff --git a/apps/api/tests/gemini-rawpayload.test.ts b/apps/api/tests/gemini-rawpayload.test.ts
index 5ae249e1..1d2de426 100644
--- a/apps/api/tests/gemini-rawpayload.test.ts
+++ b/apps/api/tests/gemini-rawpayload.test.ts
@@ -60,6 +60,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
   process.env.GEMINI_MODEL = 'gemini-primary';
   process.env.GEMINI_FALLBACK_MODEL = 'gemini-fallback';
   sdk.scripts = [];
diff --git a/apps/api/tests/gemini-repetition.test.ts b/apps/api/tests/gemini-repetition.test.ts
index 766b51a8..76ec8c30 100644
--- a/apps/api/tests/gemini-repetition.test.ts
+++ b/apps/api/tests/gemini-repetition.test.ts
@@ -98,6 +98,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
   process.env.GEMINI_MODEL = 'gemini-primary';
   process.env.GEMINI_FALLBACK_MODEL = 'gemini-fallback';
   sdk.establishCalls = 0;
diff --git a/apps/api/tests/gemini-stream-retry.test.ts b/apps/api/tests/gemini-stream-retry.test.ts
index c4dfd12c..7481c5a8 100644
--- a/apps/api/tests/gemini-stream-retry.test.ts
+++ b/apps/api/tests/gemini-stream-retry.test.ts
@@ -80,6 +80,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
   process.env.GEMINI_MODEL = 'gemini-primary';
   process.env.GEMINI_FALLBACK_MODEL = 'gemini-fallback';
   sdk.primaryModel = 'gemini-primary';
diff --git a/apps/api/tests/gemini-timeout.test.ts b/apps/api/tests/gemini-timeout.test.ts
index 959dff13..4373ebfd 100644
--- a/apps/api/tests/gemini-timeout.test.ts
+++ b/apps/api/tests/gemini-timeout.test.ts
@@ -79,6 +79,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
   process.env.GEMINI_MODEL = 'gemini-primary';
   process.env.GEMINI_FALLBACK_MODEL = 'gemini-fallback';
   sdk.capturedSignal = undefined;
diff --git a/apps/api/tests/gemini-truncation.test.ts b/apps/api/tests/gemini-truncation.test.ts
index 3d2a6416..8d53930d 100644
--- a/apps/api/tests/gemini-truncation.test.ts
+++ b/apps/api/tests/gemini-truncation.test.ts
@@ -125,6 +125,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
   process.env.GEMINI_MODEL = 'gemini-primary';
   process.env.GEMINI_FALLBACK_MODEL = 'gemini-fallback';
   sdk.primaryModel = 'gemini-primary';
diff --git a/apps/api/tests/gemini.test.ts b/apps/api/tests/gemini.test.ts
index c69697e0..718fa00c 100644
--- a/apps/api/tests/gemini.test.ts
+++ b/apps/api/tests/gemini.test.ts
@@ -49,6 +49,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
 });
 
 describe('Gemini Client (Spec 0004)', () => {
diff --git a/apps/api/tests/hadith-lk-id.test.ts b/apps/api/tests/hadith-lk-id.test.ts
index c8a35abf..92c0f9a2 100644
--- a/apps/api/tests/hadith-lk-id.test.ts
+++ b/apps/api/tests/hadith-lk-id.test.ts
@@ -16,6 +16,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
 });
 
 function okJson(body: unknown) {
diff --git a/apps/api/tests/helpers/mcp-key.ts b/apps/api/tests/helpers/mcp-key.ts
index 0482ef8a..5f89bf07 100644
--- a/apps/api/tests/helpers/mcp-key.ts
+++ b/apps/api/tests/helpers/mcp-key.ts
@@ -46,6 +46,7 @@ const DEFAULT_ENV: Record = {
   DATABASE_URL: 'postgres://test:test@localhost:5432/test',
   KALEMAT_API_KEY: 'placeholder',
   USUL_API_TOKEN: 'placeholder',
+  ENVIRONMENT: 'development',
   AUTH_URL: MCP_TEST_AUTH_URL,
   AUTH_JWT_ISSUER: MCP_TEST_AUTH_URL,
   AUTH_JWT_AUDIENCE: 'ansari-api-mcp-key-test',
diff --git a/apps/api/tests/inkling-env-config.test.ts b/apps/api/tests/inkling-env-config.test.ts
index c0bf47ac..083ad779 100644
--- a/apps/api/tests/inkling-env-config.test.ts
+++ b/apps/api/tests/inkling-env-config.test.ts
@@ -26,6 +26,7 @@ const REQUIRED_ENV: Record = {
   DATABASE_URL: 'postgresql://user:pass@localhost:5432/db',
   KALEMAT_API_KEY: 'placeholder-key',
   USUL_API_TOKEN: 'placeholder-token',
+  ENVIRONMENT: 'development',
   TINKER_API_KEY: 'test-tinker-key',
 };
 
diff --git a/apps/api/tests/kalemat-resilience.test.ts b/apps/api/tests/kalemat-resilience.test.ts
index 42635dd6..643b2ee4 100644
--- a/apps/api/tests/kalemat-resilience.test.ts
+++ b/apps/api/tests/kalemat-resilience.test.ts
@@ -15,6 +15,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
 });
 
 function okJson(body: unknown) {
diff --git a/apps/api/tests/mcp-complete-key.test.ts b/apps/api/tests/mcp-complete-key.test.ts
index f4045b40..d2b5b126 100644
--- a/apps/api/tests/mcp-complete-key.test.ts
+++ b/apps/api/tests/mcp-complete-key.test.ts
@@ -104,6 +104,7 @@ function setEnv(mode?: string): void {
   vi.stubEnv('DATABASE_URL', 'postgres://test:test@localhost:5432/test');
   vi.stubEnv('KALEMAT_API_KEY', 'placeholder');
   vi.stubEnv('USUL_API_TOKEN', 'placeholder');
+  vi.stubEnv('ENVIRONMENT', 'development');
   vi.stubEnv('AUTH_URL', AUTH_URL);
   vi.stubEnv('AUTH_JWT_ISSUER', AUTH_URL);
   vi.stubEnv('AUTH_JWT_AUDIENCE', 'ansari-api-gate-test');
diff --git a/apps/api/tests/openai-compat.test.ts b/apps/api/tests/openai-compat.test.ts
index 0f3c3a7f..304ddd62 100644
--- a/apps/api/tests/openai-compat.test.ts
+++ b/apps/api/tests/openai-compat.test.ts
@@ -21,6 +21,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
   process.env.LEADERBOARD_API_KEY = API_KEY;
   // Inkling (issue #74) is opt-in per test; default = unset.
   delete process.env.TINKER_API_KEY;
diff --git a/apps/api/tests/threads-token-persistence.test.ts b/apps/api/tests/threads-token-persistence.test.ts
index 5532c91e..fea02a82 100644
--- a/apps/api/tests/threads-token-persistence.test.ts
+++ b/apps/api/tests/threads-token-persistence.test.ts
@@ -102,6 +102,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
   process.env.GEMINI_MODEL = 'gemini-primary';
   process.env.GEMINI_FALLBACK_MODEL = 'gemini-primary';
   sdk.scripts = [];
diff --git a/apps/api/tests/tool-citability.test.ts b/apps/api/tests/tool-citability.test.ts
index 3d0ff329..3778c711 100644
--- a/apps/api/tests/tool-citability.test.ts
+++ b/apps/api/tests/tool-citability.test.ts
@@ -24,6 +24,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
 });
 
 let originalFetch: typeof globalThis.fetch;
diff --git a/apps/api/tests/tools.test.ts b/apps/api/tests/tools.test.ts
index 7c68f243..6be54201 100644
--- a/apps/api/tests/tools.test.ts
+++ b/apps/api/tests/tools.test.ts
@@ -14,6 +14,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
 });
 
 describe('Islamic Tools', () => {
diff --git a/apps/api/tests/usul-retry.test.ts b/apps/api/tests/usul-retry.test.ts
index 4a5890bd..4d7451ea 100644
--- a/apps/api/tests/usul-retry.test.ts
+++ b/apps/api/tests/usul-retry.test.ts
@@ -16,6 +16,7 @@ beforeEach(() => {
   process.env.GEMINI_API_KEY = 'test-gemini-key';
   process.env.KALEMAT_API_KEY = 'test-kalemat-key';
   process.env.USUL_API_TOKEN = 'test-usul-token';
+  process.env.ENVIRONMENT = 'development';
 });
 
 const BASE_URL = 'https://api.usul.ai/v1/vector-search/book/version';
diff --git a/apps/auth/.env.example b/apps/auth/.env.example
index a107087f..8cf6a2be 100644
--- a/apps/auth/.env.example
+++ b/apps/auth/.env.example
@@ -35,6 +35,6 @@ FRONTEND_URL=http://localhost:8081
 PORT=3100
 
 # The deployment label (#314 Amendment 3): development, staging or production. The Sentry
-# environment and the service-key prefix environment. Required, and staging or production,
-# when NODE_ENV=production; development otherwise.
+# environment and the service-key prefix environment. Required everywhere, no default; staging or
+# production when NODE_ENV=production.
 ENVIRONMENT=development
diff --git a/apps/auth/tests/environment.test.ts b/apps/auth/tests/environment.test.ts
index b7d4acad..16e2a123 100644
--- a/apps/auth/tests/environment.test.ts
+++ b/apps/auth/tests/environment.test.ts
@@ -2,8 +2,8 @@
 // Sentry environment and the service-key prefix's environment. Under
 // NODE_ENV=production it is required and must be staging or production, so a
 // deployed apps/auth without it refuses to boot (src/index.ts calls getEnv()
-// before anything else) and names the variable, never a value. Outside
-// production it defaults to development. Nothing reads it at build time: the
+// before anything else) and names the variable, never a value. It has no
+// default (owner, 2026-11-12): every process sets it. Nothing reads it at build time: the
 // image build runs tsc/tsdown, which never executes getEnv().
 import { readFileSync } from 'node:fs';
 import { fileURLToPath } from 'node:url';
@@ -41,9 +41,16 @@ describe('ENVIRONMENT in the schema', () => {
     expect(result.success && result.data.ENVIRONMENT).toBe(environment);
   });
 
-  it.each([['development'], ['test'], [undefined]])('NODE_ENV=%s without ENVIRONMENT is development', (nodeEnv) => {
-    const result = envSchema.safeParse({ ...COMPLETE, NODE_ENV: nodeEnv });
-    expect(result.success && result.data.ENVIRONMENT).toBe('development');
+  it.each([['development'], ['test'], [undefined]])(
+    'NODE_ENV=%s without ENVIRONMENT is refused too: no default anywhere (owner, 2026-11-12)',
+    (nodeEnv) => {
+      expect(issuesOf({ ...COMPLETE, NODE_ENV: nodeEnv })).toEqual(['ENVIRONMENT']);
+    }
+  );
+
+  it.each([['development'], ['staging'], ['production']])('NODE_ENV=development with ENVIRONMENT=%s parses', (environment) => {
+    const result = envSchema.safeParse({ ...COMPLETE, NODE_ENV: 'development', ENVIRONMENT: environment });
+    expect(result.success && result.data.ENVIRONMENT).toBe(environment);
   });
 });
 
diff --git a/codev/plans/314-protect-v2-mcp-complete-with-b.md b/codev/plans/314-protect-v2-mcp-complete-with-b.md
index 451d3827..b9b3c298 100644
--- a/codev/plans/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/plans/314-protect-v2-mcp-complete-with-b.md
@@ -399,7 +399,7 @@ and the `pr` gate re-requested.
 
 1. **`ENVIRONMENT`** (`packages/types/src/environment.ts`: `ENVIRONMENTS`, `environmentIssue`),
    re-exported by `@ansari/auth`. Added to `packages/auth/src/env.ts` and `apps/api/lib/config.ts`
-   (default `development`; under `NODE_ENV=production` required and `staging` or `production`).
+   (required everywhere with no default, owner 2026-11-12; under `NODE_ENV=production` only `staging` or `production`).
    Enforced only where each schema is already enforced: apps/api's `validateEnvAtBoot` (never
    during `next build`), apps/auth's `getEnv()` at the top of `src/index.ts` (never at image build).
 2. **Sentry:** apps/auth `initSentry(env.SENTRY_DSN, env.ENVIRONMENT)`; apps/api
diff --git a/codev/specs/314-protect-v2-mcp-complete-with-b.md b/codev/specs/314-protect-v2-mcp-complete-with-b.md
index 721b69cd..53bdb81d 100644
--- a/codev/specs/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/specs/314-protect-v2-mcp-complete-with-b.md
@@ -4,7 +4,7 @@
 >
 > Amendment 2, 2026-11-12, owner (on PR #372; design accepted by the security architect): every service key's prefix names its environment, for WhatsApp and MCP alike: `ansari___`. Reason: the owner asked why the MCP client needed special handling. The client id is thread attribution; the environment in the prefix is key identification, so a leaked key reads as staging or production at a glance and secret scanning can tell them apart. One table in `packages/auth/src/service-users.ts` derives the prefixes, the accepted set, the secret-scanning patterns and the script's pasted-key check. Existing keys are unchanged (the plugin matches the hash; `apikey.prefix` is never rewritten): unlabelled WhatsApp keys (`ansari_wa_`, and the pre-rename `wa_`) stay accepted during a compatibility window (`LEGACY_UNLABELLED_KEYS`) and are rotated, never reissued in place. No unlabelled MCP key can exist (its key path ships here), so the MCP route has no window (second external review, 2026-11-12). The MCP client-id rule is unchanged.
 >
-> Amendment 3, 2026-11-12, owner (supersedes Amendment 2's `--env` flag): apps/api and apps/auth gain `ENVIRONMENT` (`development` | `staging` | `production`, named after the legacy frontend's `EXPO_PUBLIC_ENVIRONMENT` (apps/frontend has no such variable; parity there is a separate follow-up)). It is required, and `staging` or `production`, under `NODE_ENV=production` (both services refuse to boot otherwise, through the existing boot paths, never at build); it defaults to `development` elsewhere. It replaces `NODE_ENV` (apps/auth) and `RAILWAY_ENVIRONMENT || NODE_ENV` (apps/api) as the Sentry environment. It is the prefix's environment segment verbatim (`ansari_mcp_staging_`; longest `ansari_mcp_development_`, 23 characters, pinned by a test that creates a key with it). The service-keys script reads it from its process env and refuses to run without it. Both key routes serve only a key whose stored prefix names their own service and their own `ENVIRONMENT` (or the legacy bare prefix during the window); any other prefix is their ordinary refusal. Main's conditions (security architect, 2026-11-12): enforcement only on the existing boot paths, Sentry continuity stated in the PR, `ENVIRONMENT` in the `.env.example` and `.env.ci` files, RELEASE.md rows and a deploy-order line, and the unchanged-existing-keys note in the runbook. Owner directive (2026-11-12, via main): no code reads `RAILWAY_*` variables, only our own names, so `RAILWAY_ENVIRONMENT` leaves `turbo.json`.
+> Amendment 3, 2026-11-12, owner (supersedes Amendment 2's `--env` flag): apps/api and apps/auth gain `ENVIRONMENT` (`development` | `staging` | `production`, named after the legacy frontend's `EXPO_PUBLIC_ENVIRONMENT` (apps/frontend has no such variable; parity there is a separate follow-up)). It is required, and `staging` or `production`, under `NODE_ENV=production` (both services refuse to boot otherwise, through the existing boot paths, never at build); it has no default anywhere (owner, 2026-11-12, on the PR: every process sets it, `development` locally and in CI). It replaces `NODE_ENV` (apps/auth) and `RAILWAY_ENVIRONMENT || NODE_ENV` (apps/api) as the Sentry environment. It is the prefix's environment segment verbatim (`ansari_mcp_staging_`; longest `ansari_mcp_development_`, 23 characters, pinned by a test that creates a key with it). The service-keys script reads it from its process env and refuses to run without it. Both key routes serve only a key whose stored prefix names their own service and their own `ENVIRONMENT` (or the legacy bare prefix during the window); any other prefix is their ordinary refusal. Main's conditions (security architect, 2026-11-12): enforcement only on the existing boot paths, Sentry continuity stated in the PR, `ENVIRONMENT` in the `.env.example` and `.env.ci` files, RELEASE.md rows and a deploy-order line, and the unchanged-existing-keys note in the runbook. Owner directive (2026-11-12, via main): no code reads `RAILWAY_*` variables, only our own names, so `RAILWAY_ENVIRONMENT` leaves `turbo.json`.
 
 ## Problem Statement
 
diff --git a/codev/state/spir-314_thread.md b/codev/state/spir-314_thread.md
index 8a958972..6ff18185 100644
--- a/codev/state/spir-314_thread.md
+++ b/codev/state/spir-314_thread.md
@@ -81,3 +81,4 @@
 - Surprise: the runbook's scanning table needs `\|` inside code cells (GFM), so cutover-docs' exact-match test now unescapes before comparing.
 - Railway env names (`staging`/`production`) come from the repo's Railway GitHub Environments, not RELEASE.md.
 - 2026-11-12 owner asked to make apps/mcp runnable in local dev: root `pnpm dev` now includes it (+ `pnpm dev:mcp`); `apps/mcp/scripts/dev.ts` loads `apps/mcp/.env`, defaults PORT 3001 and ANSARI_API_BASE_URL http://localhost:3000, warns when ANSARI_API_AUTHORIZATION is unset; `dev` builds first. Verified: health 200 on :3001, tools/list, and a stub upstream received `Authorization: Bearer ansari_mcp_development_…` verbatim on /api/v2/mcp-complete. apps/mcp's Workers tests (parity-workers, worker bundle) time out locally on the unchanged tree too (environmental, not this change). Also fixed README's wrong "optional against a local API" (a local apps/api enforces too).
+- 2026-11-12 owner chose "option 2": ENVIRONMENT has NO default anywhere (DEFAULT_ENVIRONMENT removed; both schemas require it; apps/api Sentry reads process.env.ENVIRONMENT with no fallback). Test fixtures set ENVIRONMENT=development (shared helpers + api suites); tests assert absent is refused in every NODE_ENV. Build still green with ENVIRONMENT unset. Committed locally; held for the security architect go-ahead (no pushes without it).
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 4cfb2379..5797c461 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -50,6 +50,7 @@ calling its account endpoints with the user's own JWT.
 | `DATABASE_URL` | Postgres connection string |
 | `KALEMAT_API_KEY` | Non-empty required — see caveat above |
 | `USUL_API_TOKEN` | Non-empty required — see caveat above |
+| `ENVIRONMENT` | The deployment label (#314 Amendment 3): `development`, `staging` or `production`, the same vocabulary as `apps/auth`, named after the legacy frontend's `EXPO_PUBLIC_ENVIRONMENT` (apps/frontend has no such variable). It is the Sentry environment. **No default** (owner, 2026-11-12): local and CI processes set `development` (the `.env.example` and `.env.ci` files do). When `NODE_ENV=production` it must be `staging` or `production`: a production boot without it, or labelled `development`, fails the boot check. `NODE_ENV` keeps its own jobs (test detection, production hardening) |
 
 ### Auth service (`apps/auth`; required when `NODE_ENV=production`)
 
@@ -117,7 +118,6 @@ empty-final retry ladder still applies as same-model retries.
 | `ANDROID_MINIMUM_BUILD_VERSION` | `1` | |
 | `ANDROID_LATEST_BUILD_VERSION` | `1` | |
 | `NODE_ENV` | `development` | `development` / `production` / `test` |
-| `ENVIRONMENT` | `development` | The deployment label (#314 Amendment 3): `development`, `staging` or `production`, the same vocabulary as `apps/auth`, named after the legacy frontend's `EXPO_PUBLIC_ENVIRONMENT` (apps/frontend has no such variable). It is the Sentry environment. **Required when `NODE_ENV=production`**, and then only `staging` or `production`: a production boot without it, or labelled `development`, fails the boot check. `NODE_ENV` keeps its own jobs (test detection, production hardening) |
 
 ### Outside the config schema (direct `process.env` reads)
 
diff --git a/packages/auth/src/env.ts b/packages/auth/src/env.ts
index 4c4b46b2..0df9a638 100644
--- a/packages/auth/src/env.ts
+++ b/packages/auth/src/env.ts
@@ -10,7 +10,7 @@
 // env is absent (e.g. `tsc`/`tsdown` never execute the module; tests set env
 // explicitly). It runs the first time `getEnv()` is called — which is inside
 // `createAuth()`/`createDb()`.
-import { DEFAULT_ENVIRONMENT, ENVIRONMENTS, environmentIssue } from '@ansari/types/environment';
+import { ENVIRONMENTS, environmentIssue } from '@ansari/types/environment';
 import { z } from 'zod';
 
 /** Exported for the env-template test (apps/auth/tests/env-templates.test.ts). */
@@ -33,9 +33,9 @@ export const envSchema = z.object({
     .pipe(z.array(z.url('CORS_ORIGIN must be a comma list of URLs')).min(1)),
   NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
   // The deployment label (#314 Amendment 3): the Sentry environment and the
-  // service-key prefix's environment. Required, and staging or production,
-  // under NODE_ENV=production (the refinement below); development otherwise.
-  ENVIRONMENT: z.enum(ENVIRONMENTS).default(DEFAULT_ENVIRONMENT),
+  // service-key prefix's environment. Required everywhere, no default (owner,
+  // 2026-11-12); staging or production under NODE_ENV=production (below).
+  ENVIRONMENT: z.enum(ENVIRONMENTS),
   // apps/api's own origin, sent as `Origin` by its /v2/users/* layer, whose
   // server-side fetch carries Sec-Fetch-Mode and so meets better-auth's CSRF
   // check. It joins trustedOrigins ONLY, never the CORS allowlist, so a
@@ -59,8 +59,6 @@ export const envSchema = z.object({
   // apps/auth's Sentry project (the list-walk alert). Unset disables sending.
   SENTRY_DSN: z.string().url('SENTRY_DSN must be a valid URL').optional(),
 }).superRefine((env, ctx) => {
-  // The default fills an absent value in before this runs, so an absent
-  // ENVIRONMENT in production reads as `development` here and is refused too.
   const issue = environmentIssue(env.NODE_ENV, env.ENVIRONMENT);
   if (issue) ctx.addIssue({ code: 'custom', path: ['ENVIRONMENT'], message: issue });
 });
@@ -89,7 +87,7 @@ export function getEnv(): AuthEnv {
         `Set these before running the auth service — see apps/auth/.env.example ` +
         `(BETTER_AUTH_SECRET must be >= 32 chars, RESEND_API_KEY >= 20; ` +
         `BETTER_AUTH_URL, AUTH_JWT_ISSUER and FRONTEND_URL must be URLs; CORS_ORIGIN a comma list of URLs; ` +
-        `ENVIRONMENT staging or production when NODE_ENV=production).`
+        `ENVIRONMENT one of development, staging, production, and staging or production when NODE_ENV=production).`
     );
   }
 
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index a8b6ea0b..a8e5d463 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -59,7 +59,7 @@ export {
   type Mailer,
 } from './reset-email';
 export { CLIENT_HEADER, isMcpClientId, MCP_CLIENT_ID_PATTERN } from '@ansari/types/attribution';
-export { DEFAULT_ENVIRONMENT, ENVIRONMENTS, environmentIssue, type Environment } from '@ansari/types/environment';
+export { ENVIRONMENTS, environmentIssue, type Environment } from '@ansari/types/environment';
 
 /** Same bounds as the legacy register schema, and better-auth's own defaults. */
 export const MIN_PASSWORD_LENGTH = 8;
diff --git a/packages/auth/tests/helpers/auth-db.ts b/packages/auth/tests/helpers/auth-db.ts
index 096541fa..d483f11a 100644
--- a/packages/auth/tests/helpers/auth-db.ts
+++ b/packages/auth/tests/helpers/auth-db.ts
@@ -66,6 +66,7 @@ export function setAuthEnv(baseUrl: string): void {
   process.env.CORS_ORIGIN = 'http://localhost:3100';
   process.env.AUTH_LAYER_ORIGIN = TEST_LAYER_ORIGIN;
   process.env.NODE_ENV = 'test';
+  process.env.ENVIRONMENT = 'development'; // required everywhere, no default (#314, owner)
   process.env.AUTH_JWT_ISSUER = TEST_JWT_ISSUER;
   process.env.AUTH_JWT_AUDIENCE = TEST_JWT_AUDIENCE;
   process.env.RESEND_API_KEY = 're_test_key_at_least_20_chars';
diff --git a/packages/types/src/environment.ts b/packages/types/src/environment.ts
index 457db0b4..024c6f0d 100644
--- a/packages/types/src/environment.ts
+++ b/packages/types/src/environment.ts
@@ -4,15 +4,14 @@
  * apps/auth. It is the Sentry environment of both services and the
  * environment segment of every service-key prefix (`ansari___`).
  * NODE_ENV keeps its own jobs (test detection, production hardening);
- * ENVIRONMENT says which deployment this is.
+ * ENVIRONMENT says which deployment this is. It has NO default (owner,
+ * 2026-11-12): every process sets it, as it sets its secrets; local and CI
+ * processes say `development` (the .env.example and .env.ci files do).
  */
 export const ENVIRONMENTS = ['development', 'staging', 'production'] as const;
 
 export type Environment = (typeof ENVIRONMENTS)[number];
 
-/** Absent outside production: a local or CI process is `development`. */
-export const DEFAULT_ENVIRONMENT: Environment = 'development';
-
 /**
  * Why `environment` is not acceptable for a process running with `nodeEnv`,
  * or null when it is. Under NODE_ENV=production it is required and must be

From ccdcd763374649ae79ee874d8ce00e21c97abb2e Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 10:52:48 +1100
Subject: [PATCH 178/435] =?UTF-8?q?[Spec=20314]=20docs:=20ENVIRONMENT=20ha?=
 =?UTF-8?q?s=20no=20default=20in=20any=20process=20=E2=80=94=20services,?=
 =?UTF-8?q?=20operator=20shells,=20local=20dev=20(runbook,=20RELEASE.md)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 RELEASE.md                           | 6 ++++--
 docs/cutover/service-keys-runbook.md | 5 ++++-
 2 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/RELEASE.md b/RELEASE.md
index a3de64f9..a588ca56 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -112,8 +112,10 @@ migration runbook were both proven in real releases on 2026-08-02.
 > `./node_modules/.bin/tsx scripts/…` (tsx directly: the image has no pnpm for its non-root user).
 >
 > **`ENVIRONMENT` on `backend` and auth (#314 Amendment 3)** — the deployment label, also each
-> service's Sentry environment and the environment in every service key's prefix. Both refuse to
-> boot under `NODE_ENV=production` without it (or set to `development`):
+> service's Sentry environment and the environment in every service key's prefix. It has **no
+> default in any process** (owner, 2026-11-12): every deployed service, every operator shell that
+> runs an apps/auth script, and local dev (`development`) set it. Under `NODE_ENV=production` both
+> services refuse to boot without it, or with `development`:
 >
 > | Service | staging | production |
 > |---|---|---|
diff --git a/docs/cutover/service-keys-runbook.md b/docs/cutover/service-keys-runbook.md
index b07defd9..ca22a263 100644
--- a/docs/cutover/service-keys-runbook.md
+++ b/docs/cutover/service-keys-runbook.md
@@ -42,7 +42,10 @@ refused, since both are printed by `list` and sent to Sentry. Without `SENTRY_DS
 prints the key-log banner and exits 3 (no record is attempted). The script
 prints the database as `hostname:port` only, and under it `ENVIRONMENT`, which the script reads
 from its process env (the auth service's own variable, so the Railway shell has it) and refuses
-to run without (#314 Amendment 3). A new key's prefix carries it: `ansari_wa_production_`,
+to run without (#314 Amendment 3). `ENVIRONMENT` has **no default in any process** (owner,
+2026-11-12): each deployed service, every operator shell that runs this script (an off-Railway
+shell, e.g. a checkout over the Tailscale route, must export it as the service has it), and local
+dev (`development` in `apps/*/.env`). A new key's prefix carries it: `ansari_wa_production_`,
 `ansari_mcp_staging_`, …, and each environment's routes refuse a key labelled for another, so
 check the two lines agree before `--confirm`. Limits have no defaults and are checked against the
 bounds in `packages/auth/src/limits.ts`; there is no expiry option and no budget without a

From 2b29c9911009ca13e81ac4ba03ffea1588c4893d Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:17:07 +1100
Subject: [PATCH 179/435] chore(porch): 314 pr gate-approved

---
 .../314-protect-v2-mcp-complete-with-b/status.yaml         | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 1c5defe9..80ca15ce 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -29,15 +29,16 @@ gates:
     requested_at: '2026-11-11T03:17:11.104Z'
     approved_at: '2026-11-11T03:20:48.411Z'
   pr:
-    status: pending
+    status: approved
     requested_at: '2026-11-11T04:36:26.447Z'
+    approved_at: '2026-11-12T00:17:07.478Z'
   verify-approval:
     status: pending
 iteration: 1
 build_complete: false
 history: []
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-11T04:36:26.447Z'
+updated_at: '2026-11-12T00:17:07.478Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'
@@ -65,4 +66,4 @@ pr_history:
     pr_number: 372
     branch: builder/spir-314
     created_at: '2026-11-11T04:27:48.853Z'
-pr_ready_for_human: true
+pr_ready_for_human: false

From 0fa43d79d91406f4e7da86c25de71f5f62e35fd2 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:24:01 +1100
Subject: [PATCH 180/435] chore(porch): 314 PR #372 merged

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 80ca15ce..c96881e7 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -38,7 +38,7 @@ iteration: 1
 build_complete: false
 history: []
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-12T00:17:07.478Z'
+updated_at: '2026-11-12T00:24:01.620Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'
@@ -66,4 +66,6 @@ pr_history:
     pr_number: 372
     branch: builder/spir-314
     created_at: '2026-11-11T04:27:48.853Z'
+    merged: true
+    merged_at: '2026-11-12T00:24:01.619Z'
 pr_ready_for_human: false

From 9fdd47ec8ec24f487b982444ad7345530a56618a Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:24:05 +1100
Subject: [PATCH 181/435] chore(porch): 314 verify phase-transition

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index c96881e7..0a93a52c 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -1,7 +1,7 @@
 id: '314'
 title: protect-v2-mcp-complete-with-b
 protocol: spir
-phase: review
+phase: verify
 plan_phases:
   - id: phase_1
     title: 'ansari-mcp key rules: limits, client-id rule, script constraints'
@@ -38,7 +38,7 @@ iteration: 1
 build_complete: false
 history: []
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-12T00:24:01.620Z'
+updated_at: '2026-11-12T00:24:05.634Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'

From b66997059bcabff4e0e8d2a823e62b842b32a200 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:24:53 +1100
Subject: [PATCH 182/435] [Spec 314] Close-out: review merge and verification
 section, thread

---
 .../reviews/314-protect-v2-mcp-complete-with-b.md | 15 +++++++++++++++
 codev/state/spir-314_thread.md                    |  5 +++++
 2 files changed, 20 insertions(+)

diff --git a/codev/reviews/314-protect-v2-mcp-complete-with-b.md b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
index 71e695dd..906b87d6 100644
--- a/codev/reviews/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
@@ -273,3 +273,18 @@ Neither test was skipped. Both are pre-existing, outside this change, and passed
 - **`@better-auth/api-key` upgrade to 1.7.20:** out of scope. On any bump, re-run the upgrade guard in `apps/auth/tests/blocked-paths.test.ts` and the runbook's plugin-upgrade check.
 - **`cutover-docs.test.ts` `namedRepoPaths`:** add an end boundary after the extension so `.jsonc` is not read as `.json`. This is main's test infrastructure.
 - **Flaky in-process apps/auth tests under parallel load:** security owns them (#330 lineage).
+
+## Merge and verification
+
+- **Merged:** PR #372 into `develop`, merge commit `1de78ad51d3bcd406986174d6e279180aa83da8a` (2026-11-12). Head `2b29c991` (porch gate-approved); all six CI checks green on it. Issue #314 closed by the PR's `Closes #314`. The owner approved the `pr` gate in writing and the security architect ran it.
+- **Builder-side verification:** done before the merge, on the PR's own tree:
+  - full suite: api 1274, auth 635, @ansari/auth 289, frontend 774;
+  - production boot probes: 10/10;
+  - local end-to-end through `pnpm dev`, the MCP Inspector and a development key, run by the owner (2026-11-12): served with a `Bearer` key, refused without one.
+- **Not deployed by the builder.** These steps belong to the owner, in the PR body and the runbook:
+  - set `ENVIRONMENT` everywhere (done);
+  - give staging MCP a labelled key, or deploy with `MCP_COMPLETE_KEY_MODE=log-only` first;
+  - issue production keys and update the published snippet and MCP setup page;
+  - enforce after the log-only week, then open the removal follow-up.
+- **Follow-up PR:** the `CONTRIBUTING.md` update (MCP in `pnpm dev`, the required local `ENVIRONMENT`, the MCP key and `inspect`, the stale workspace list), as the owner chose, on a fresh branch from `develop`.
+
diff --git a/codev/state/spir-314_thread.md b/codev/state/spir-314_thread.md
index 6ff18185..45300aad 100644
--- a/codev/state/spir-314_thread.md
+++ b/codev/state/spir-314_thread.md
@@ -82,3 +82,8 @@
 - Railway env names (`staging`/`production`) come from the repo's Railway GitHub Environments, not RELEASE.md.
 - 2026-11-12 owner asked to make apps/mcp runnable in local dev: root `pnpm dev` now includes it (+ `pnpm dev:mcp`); `apps/mcp/scripts/dev.ts` loads `apps/mcp/.env`, defaults PORT 3001 and ANSARI_API_BASE_URL http://localhost:3000, warns when ANSARI_API_AUTHORIZATION is unset; `dev` builds first. Verified: health 200 on :3001, tools/list, and a stub upstream received `Authorization: Bearer ansari_mcp_development_…` verbatim on /api/v2/mcp-complete. apps/mcp's Workers tests (parity-workers, worker bundle) time out locally on the unchanged tree too (environmental, not this change). Also fixed README's wrong "optional against a local API" (a local apps/api enforces too).
 - 2026-11-12 owner chose "option 2": ENVIRONMENT has NO default anywhere (DEFAULT_ENVIRONMENT removed; both schemas require it; apps/api Sentry reads process.env.ENVIRONMENT with no fallback). Test fixtures set ENVIRONMENT=development (shared helpers + api suites); tests assert absent is refused in every NODE_ENV. Build still green with ENVIRONMENT unset. Committed locally; held for the security architect go-ahead (no pushes without it).
+
+## 2026-11-12 merged — close-out
+- PR #372 merged into develop as 1de78ad5 (merge commit), after the owner approved the pr gate in writing (the security architect ran it). CI 6/6 green on the gate-approved head 2b29c991. Issue #314 closed.
+- Owner tested locally end to end (pnpm dev + MCP Inspector + a development key). The one snag was a key without the `Bearer ` prefix, which gives verdict `missing`.
+- Nothing deployed by the builder; the owner steps are in the PR body and the runbook. Follow-up: CONTRIBUTING.md docs PR from a fresh develop branch (owner chose b), reviewed by main via security.

From 613cc31d65fb78cffe0305c9e5a135f7c14bb0c1 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:24:58 +1100
Subject: [PATCH 183/435] chore(porch): 314 verify-approval gate-requested

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 0a93a52c..211cbd05 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -34,11 +34,12 @@ gates:
     approved_at: '2026-11-12T00:17:07.478Z'
   verify-approval:
     status: pending
+    requested_at: '2026-11-12T00:24:58.407Z'
 iteration: 1
 build_complete: false
 history: []
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-12T00:24:05.634Z'
+updated_at: '2026-11-12T00:24:58.408Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'

From 0bbd61a3c11229c1496efbebfa7ad921b7242487 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:25:45 +1100
Subject: [PATCH 184/435] docs(contributing): pnpm dev includes the MCP server;
 ENVIRONMENT required in local .env; MCP key and inspect pointer; current
 workspace list (#314 follow-up)

---
 CONTRIBUTING.md | 27 +++++++++++++++++++++------
 1 file changed, 21 insertions(+), 6 deletions(-)

diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 21e97d04..0a2f124c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -34,9 +34,10 @@ You need **Node 22** (22.18 or newer; `.nvmrc` pins the major for `nvm use`).
 environment contract, and [`apps/api/README.md`](apps/api/README.md) covers the
 backend in more depth.
 
-This is a **pnpm workspace** (`apps/api/` + `apps/frontend/`) driven by
-**[Turborepo](https://turborepo.com)**: install once at the repo root, then run
-tasks from the root — `pnpm dev` brings up the whole stack (api, auth, frontend) at once.
+This is a **pnpm workspace** (`apps/api/`, `apps/auth/`, `apps/frontend/`, `apps/mcp/` and
+the shared `packages/*`) driven by **[Turborepo](https://turborepo.com)**: install once at the
+repo root, then run tasks from the root — `pnpm dev` brings up the whole stack (api, auth,
+frontend and the MCP server) at once.
 
 ```bash
 corepack enable         # provides pnpm (version pinned in package.json)
@@ -56,13 +57,26 @@ cp .env.example .env    # DATABASE_URL = the ansari_auth owner URL; the service'
 pnpm db:migrate         # applies packages/auth/drizzle/ to that DATABASE_URL
 cd ../..
 
-# Then, from the repo root: starts api (:3000), auth (:3100) and frontend together
+# Then, from the repo root: starts api (:3000), auth (:3100), the frontend and the
+# MCP server (:3001) together
 pnpm dev
 ```
 
+Both `.env` files need `ENVIRONMENT=development`. It has no default in any process
+(#314); the `.env.example` files set it, but a `.env` copied before then lacks it, and
+then api fails at its first config read and auth refuses to start, each naming
+`ENVIRONMENT`.
+
 `pnpm dev` includes `apps/auth`. Without its `.env`, auth's pane shows the
 env-validation error naming the missing variables and the other apps keep
-running; `pnpm dev:no-auth` starts api + frontend only. The frontend talks to
+running; `pnpm dev:no-auth` starts api + frontend only.
+
+`pnpm dev` also starts the MCP server (`apps/mcp`) on `:3001`, after a cached build
+that shows as its own `ansari-mcp#build` row. A local api refuses MCP calls without
+an `ansari-mcp` key, as a deployed one does: issue a development key and put
+`ANSARI_API_AUTHORIZATION=Bearer ` in `apps/mcp/.env`, or run api with
+`MCP_COMPLETE_KEY_MODE=log-only`. `pnpm mcp inspect` opens the MCP Inspector on it. The
+steps are in [`apps/mcp/README.md`](apps/mcp/README.md), under "Local development". The frontend talks to
 **staging** unless `EXPO_PUBLIC_API_URL=http://localhost:3000` and
 `EXPO_PUBLIC_AUTH_URL=http://localhost:3100` are set.
 
@@ -83,7 +97,8 @@ The test suites need neither database (they run on pglite).
 `pnpm dev` needs a real terminal: it runs Turbo's interactive UI so the Expo dev
 server keeps its keypress shortcuts (`i`, `a`, `w`, `r`) while sharing a console
 with the API and auth. To run one app on its own — or in a script or non-TTY shell — use
-`pnpm api dev`, `pnpm auth dev` or `pnpm frontend start`.
+`pnpm api dev`, `pnpm auth dev`, `pnpm frontend start` or, for the MCP server,
+`pnpm mcp build && pnpm mcp dev` (`pnpm dev:mcp` does both, in a real terminal).
 
 **Use pnpm, not npm or yarn.** The single authoritative lockfile is the root
 `pnpm-lock.yaml`; there are deliberately no per-package lockfiles. Shared

From 1506be63717b411dc349a94e5a3cbd028dc4cd00 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:24:01 +1100
Subject: [PATCH 185/435] chore(porch): 314 PR #372 merged

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 80ca15ce..c96881e7 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -38,7 +38,7 @@ iteration: 1
 build_complete: false
 history: []
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-12T00:17:07.478Z'
+updated_at: '2026-11-12T00:24:01.620Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'
@@ -66,4 +66,6 @@ pr_history:
     pr_number: 372
     branch: builder/spir-314
     created_at: '2026-11-11T04:27:48.853Z'
+    merged: true
+    merged_at: '2026-11-12T00:24:01.619Z'
 pr_ready_for_human: false

From b6488d928da4509eaa9050364cf2bd38edcd2dfc Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:24:05 +1100
Subject: [PATCH 186/435] chore(porch): 314 verify phase-transition

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index c96881e7..0a93a52c 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -1,7 +1,7 @@
 id: '314'
 title: protect-v2-mcp-complete-with-b
 protocol: spir
-phase: review
+phase: verify
 plan_phases:
   - id: phase_1
     title: 'ansari-mcp key rules: limits, client-id rule, script constraints'
@@ -38,7 +38,7 @@ iteration: 1
 build_complete: false
 history: []
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-12T00:24:01.620Z'
+updated_at: '2026-11-12T00:24:05.634Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'

From 4e43e6d0b8d2586b6428192437d0a447adf2d6f1 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:24:53 +1100
Subject: [PATCH 187/435] [Spec 314] Close-out: review merge and verification
 section, thread

---
 .../reviews/314-protect-v2-mcp-complete-with-b.md | 15 +++++++++++++++
 codev/state/spir-314_thread.md                    |  5 +++++
 2 files changed, 20 insertions(+)

diff --git a/codev/reviews/314-protect-v2-mcp-complete-with-b.md b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
index 71e695dd..906b87d6 100644
--- a/codev/reviews/314-protect-v2-mcp-complete-with-b.md
+++ b/codev/reviews/314-protect-v2-mcp-complete-with-b.md
@@ -273,3 +273,18 @@ Neither test was skipped. Both are pre-existing, outside this change, and passed
 - **`@better-auth/api-key` upgrade to 1.7.20:** out of scope. On any bump, re-run the upgrade guard in `apps/auth/tests/blocked-paths.test.ts` and the runbook's plugin-upgrade check.
 - **`cutover-docs.test.ts` `namedRepoPaths`:** add an end boundary after the extension so `.jsonc` is not read as `.json`. This is main's test infrastructure.
 - **Flaky in-process apps/auth tests under parallel load:** security owns them (#330 lineage).
+
+## Merge and verification
+
+- **Merged:** PR #372 into `develop`, merge commit `1de78ad51d3bcd406986174d6e279180aa83da8a` (2026-11-12). Head `2b29c991` (porch gate-approved); all six CI checks green on it. Issue #314 closed by the PR's `Closes #314`. The owner approved the `pr` gate in writing and the security architect ran it.
+- **Builder-side verification:** done before the merge, on the PR's own tree:
+  - full suite: api 1274, auth 635, @ansari/auth 289, frontend 774;
+  - production boot probes: 10/10;
+  - local end-to-end through `pnpm dev`, the MCP Inspector and a development key, run by the owner (2026-11-12): served with a `Bearer` key, refused without one.
+- **Not deployed by the builder.** These steps belong to the owner, in the PR body and the runbook:
+  - set `ENVIRONMENT` everywhere (done);
+  - give staging MCP a labelled key, or deploy with `MCP_COMPLETE_KEY_MODE=log-only` first;
+  - issue production keys and update the published snippet and MCP setup page;
+  - enforce after the log-only week, then open the removal follow-up.
+- **Follow-up PR:** the `CONTRIBUTING.md` update (MCP in `pnpm dev`, the required local `ENVIRONMENT`, the MCP key and `inspect`, the stale workspace list), as the owner chose, on a fresh branch from `develop`.
+
diff --git a/codev/state/spir-314_thread.md b/codev/state/spir-314_thread.md
index 6ff18185..45300aad 100644
--- a/codev/state/spir-314_thread.md
+++ b/codev/state/spir-314_thread.md
@@ -82,3 +82,8 @@
 - Railway env names (`staging`/`production`) come from the repo's Railway GitHub Environments, not RELEASE.md.
 - 2026-11-12 owner asked to make apps/mcp runnable in local dev: root `pnpm dev` now includes it (+ `pnpm dev:mcp`); `apps/mcp/scripts/dev.ts` loads `apps/mcp/.env`, defaults PORT 3001 and ANSARI_API_BASE_URL http://localhost:3000, warns when ANSARI_API_AUTHORIZATION is unset; `dev` builds first. Verified: health 200 on :3001, tools/list, and a stub upstream received `Authorization: Bearer ansari_mcp_development_…` verbatim on /api/v2/mcp-complete. apps/mcp's Workers tests (parity-workers, worker bundle) time out locally on the unchanged tree too (environmental, not this change). Also fixed README's wrong "optional against a local API" (a local apps/api enforces too).
 - 2026-11-12 owner chose "option 2": ENVIRONMENT has NO default anywhere (DEFAULT_ENVIRONMENT removed; both schemas require it; apps/api Sentry reads process.env.ENVIRONMENT with no fallback). Test fixtures set ENVIRONMENT=development (shared helpers + api suites); tests assert absent is refused in every NODE_ENV. Build still green with ENVIRONMENT unset. Committed locally; held for the security architect go-ahead (no pushes without it).
+
+## 2026-11-12 merged — close-out
+- PR #372 merged into develop as 1de78ad5 (merge commit), after the owner approved the pr gate in writing (the security architect ran it). CI 6/6 green on the gate-approved head 2b29c991. Issue #314 closed.
+- Owner tested locally end to end (pnpm dev + MCP Inspector + a development key). The one snag was a key without the `Bearer ` prefix, which gives verdict `missing`.
+- Nothing deployed by the builder; the owner steps are in the PR body and the runbook. Follow-up: CONTRIBUTING.md docs PR from a fresh develop branch (owner chose b), reviewed by main via security.

From e6bc3f5417811511a1bc16e31a2d25c1d34694dc Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:24:58 +1100
Subject: [PATCH 188/435] chore(porch): 314 verify-approval gate-requested

---
 codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
index 0a93a52c..211cbd05 100644
--- a/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
+++ b/codev/projects/314-protect-v2-mcp-complete-with-b/status.yaml
@@ -34,11 +34,12 @@ gates:
     approved_at: '2026-11-12T00:17:07.478Z'
   verify-approval:
     status: pending
+    requested_at: '2026-11-12T00:24:58.407Z'
 iteration: 1
 build_complete: false
 history: []
 started_at: '2026-11-11T02:47:51.234Z'
-updated_at: '2026-11-12T00:24:05.634Z'
+updated_at: '2026-11-12T00:24:58.408Z'
 context_refreshes:
   - boundary: enter:plan
     at: '2026-11-11T03:09:39.378Z'

From 05c67775d414be80b71846e865a15c25b2647c10 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:41:08 +1100
Subject: [PATCH 189/435] chore(porch): 377 init air

---
 .../377-mcp-stop-reading-railway-git-c/status.yaml | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
 create mode 100644 codev/projects/377-mcp-stop-reading-railway-git-c/status.yaml

diff --git a/codev/projects/377-mcp-stop-reading-railway-git-c/status.yaml b/codev/projects/377-mcp-stop-reading-railway-git-c/status.yaml
new file mode 100644
index 00000000..680eb5ca
--- /dev/null
+++ b/codev/projects/377-mcp-stop-reading-railway-git-c/status.yaml
@@ -0,0 +1,14 @@
+id: '377'
+title: mcp-stop-reading-railway-git-c
+protocol: air
+phase: implement
+plan_phases: []
+current_plan_phase: null
+gates:
+  pr:
+    status: pending
+iteration: 1
+build_complete: false
+history: []
+started_at: '2026-11-12T00:41:08.481Z'
+updated_at: '2026-11-12T00:41:08.481Z'

From cf23fe172bee4c81019d093f5c03b52648512e79 Mon Sep 17 00:00:00 2001
From: Amr Elsayed 
Date: Thu, 12 Nov 2026 11:45:20 +1100
Subject: [PATCH 190/435] [Air #377] feat: mcp reads ANSARI_RELEASE only;
 RAILWAY_* guard covers every app and package

---
 RELEASE.md                                    |  6 +-
 apps/api/tests/release-doc.test.ts            |  5 +-
 apps/api/tests/source-scan/scan.ts            | 28 ++++++++--
 .../api/tests/source-scan/source-scan.test.ts | 55 ++++++++++++-------
 apps/api/turbo.json                           | 27 ++++++---
 apps/mcp/.env.example                         |  4 +-
 apps/mcp/README.md                            |  3 +-
 apps/mcp/docs/show-me-ansari-mcp.html         |  2 +-
 apps/mcp/src/server/runtime-config.ts         |  8 +--
 apps/mcp/test/runtime-boundary.test.ts        |  8 ++-
 apps/mcp/test/turbo-env.test.ts               |  6 +-
 apps/mcp/turbo.json                           |  6 +-
 codev/state/air-377_thread.md                 |  7 +++
 13 files changed, 108 insertions(+), 57 deletions(-)
 create mode 100644 codev/state/air-377_thread.md

diff --git a/RELEASE.md b/RELEASE.md
index a588ca56..a7b7fe89 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -92,10 +92,10 @@ migration runbook were both proven in real releases on 2026-08-02.
 > | `ANSARI_API_BASE_URL` | `https://api-staging.askansari.ai` (the default is production) |
 > | `ANSARI_CLIENT` | `ansari-mcp-staging` |
 > | `ANSARI_API_AUTHORIZATION` | `Bearer ansari_mcp_staging_<64 letters>`: the staging key, made in the staging auth shell with `--client-id ansari-mcp-staging` and set **before** apps/api staging deploys #314 (`docs/cutover/service-keys-runbook.md`) |
+> | `ANSARI_RELEASE` | `${{RAILWAY_GIT_COMMIT_SHA}}`, a Railway reference variable: the commit is mapped here, in the dashboard, because the code reads no `RAILWAY_*` variable (#377). Unset, the release is the application version |
 >
-> `ANSARI_RELEASE` is **not** set: the release falls back to `RAILWAY_GIT_COMMIT_SHA`. `MCP_ALLOWED_ORIGINS` is left
-> unset at first: it defaults to the allowed hosts, and requests without an Origin pass. The Cloudflare Workers path
-> (`apps/mcp/wrangler.jsonc`) is not this deployment.
+> `MCP_ALLOWED_ORIGINS` is left unset at first: it defaults to the allowed hosts, and requests without an Origin
+> pass. The Cloudflare Workers path (`apps/mcp/wrangler.jsonc`) is not this deployment.
 >
 > **auth service (spec 300)** — one listener: the public domain
 > (`auth.askansari.ai`, `auth-staging.askansari.ai`) targets `PORT` (3100); set it as
diff --git a/apps/api/tests/release-doc.test.ts b/apps/api/tests/release-doc.test.ts
index 9bf89297..25c84d6f 100644
--- a/apps/api/tests/release-doc.test.ts
+++ b/apps/api/tests/release-doc.test.ts
@@ -178,7 +178,10 @@ describe('RELEASE.md consistency', () => {
       expect(doc).toContain('| `MCP_ALLOWED_HOSTS` | `mcp-staging.askansari.ai`');
       expect(doc).toContain('| `ANSARI_API_BASE_URL` | `https://api-staging.askansari.ai`');
       expect(doc).toContain('| `ANSARI_CLIENT` | `ansari-mcp-staging` |');
-      expect(doc).toContain('`ANSARI_RELEASE` is **not** set');
+      // The release maps the platform's commit in the dashboard, never in code (#377).
+      expect(doc).toContain('| `ANSARI_RELEASE` | `${{RAILWAY_GIT_COMMIT_SHA}}`');
+      expect(doc).not.toContain('`ANSARI_RELEASE` is **not** set');
+      expect(doc).not.toContain('falls back to `RAILWAY_GIT_COMMIT_SHA`');
       expect(doc).toContain('`https:///mcp`');
       expect(doc.replace(/\n> /g, ' ')).toContain('set `PORT=3000` as a service variable so Railway does not assign its own');
     });
diff --git a/apps/api/tests/source-scan/scan.ts b/apps/api/tests/source-scan/scan.ts
index fc995f0b..3033c23e 100644
--- a/apps/api/tests/source-scan/scan.ts
+++ b/apps/api/tests/source-scan/scan.ts
@@ -1,7 +1,7 @@
 // Source scans for spec 300 (plan phase 9): the legacy auth model is gone from
 // runtime code and stays gone. The scanner reads code through the TypeScript
 // parser, so comments never count: a column named in a comment is not a query.
-import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
 import path from 'node:path';
 import ts from 'typescript';
 
@@ -191,9 +191,25 @@ export function railwayEnvHits(source: string): string[] {
 }
 
 /**
- * The declared exceptions, by file and name. apps/mcp's release fallback is
- * main's lane; issue #377 removes the read and then this entry.
+ * The trees scan 6 covers (#377): every app's `src/` and `lib/`, and every
+ * package under `packages/`. A directory that does not exist is skipped, so
+ * a new app or package joins the scan without an edit here.
  */
-export const RAILWAY_ALLOWLIST: Readonly> = {
-  'apps/mcp/src/server/runtime-config.ts': ['RAILWAY_GIT_COMMIT_SHA'], // #377
-};
+export function railwayScanDirs(): string[] {
+  const dirs = (parent: string) =>
+    readdirSync(path.join(REPO_ROOT, parent))
+      .map((name) => path.join(parent, name))
+      .filter((rel) => statSync(path.join(REPO_ROOT, rel)).isDirectory());
+  const apps = dirs('apps').flatMap((app) => [path.join(app, 'src'), path.join(app, 'lib')]);
+  return [...apps, ...dirs('packages')].filter((rel) => existsSync(path.join(REPO_ROOT, rel)));
+}
+
+/** Each file whose code names a RAILWAY_* variable, with the names it names. No file is exempt. */
+export function railwayTreeHits(files: readonly { path: string; source: string }[]): Record {
+  const hits: Record = {};
+  for (const file of files) {
+    const found = railwayEnvHits(file.source);
+    if (found.length > 0) hits[file.path] = found;
+  }
+  return hits;
+}
diff --git a/apps/api/tests/source-scan/source-scan.test.ts b/apps/api/tests/source-scan/source-scan.test.ts
index bd7bb9d0..d40a0164 100644
--- a/apps/api/tests/source-scan/source-scan.test.ts
+++ b/apps/api/tests/source-scan/source-scan.test.ts
@@ -12,8 +12,9 @@ import {
   databaseUrlHits,
   isExcludedFromDatabaseUrlScan,
   legacySqlHits,
-  RAILWAY_ALLOWLIST,
   railwayEnvHits,
+  railwayScanDirs,
+  railwayTreeHits,
   readSource,
   removedHopHits,
   removedHopTextHits,
@@ -287,12 +288,20 @@ describe('scan 5: apps/api has no WhatsApp-specific code (spec 329)', () => {
   });
 });
 
-describe('scan 6: no code reads a RAILWAY_* variable (owner directive 2026-11-12, #314)', () => {
-  // apps/api, apps/auth (with packages/auth) and apps/mcp's server source.
-  const MCP_RUNTIME = sourceFiles('apps/mcp/src');
-  // apps/api's operator scripts too (codex): API_RUNTIME is what `next build`
-  // compiles, but a script reading RAILWAY_* breaks the rule just as well.
-  const API_SCRIPTS = sourceFiles('apps/api/scripts');
+describe('scan 6: no code reads a RAILWAY_* variable (owner directive 2026-11-12, #314, #377)', () => {
+  // Every app's src/ and lib/ and every package (#377), plus the operator
+  // scripts and config files apps/api and apps/auth run: a script reading
+  // RAILWAY_* breaks the rule just as well (codex).
+  const SCAN_DIRS = railwayScanDirs();
+  const FILES = [
+    ...new Set([
+      ...SCAN_DIRS.flatMap((dir) => sourceFiles(dir)),
+      ...API_RUNTIME,
+      ...sourceFiles('apps/api/scripts'),
+      ...AUTH_RUNTIME,
+    ]),
+  ];
+  const tree = () => FILES.map((file) => ({ path: file, source: readSource(file) }));
 
   it('catches planted lines, whatever the access path', () => {
     for (const bad of [
@@ -319,18 +328,26 @@ describe('scan 6: no code reads a RAILWAY_* variable (owner directive 2026-11-12
     }
   });
 
-  it('the allowlist is exact: its one entry is present, and nothing else is', () => {
-    const files = [...API_RUNTIME, ...API_SCRIPTS, ...AUTH_RUNTIME, ...MCP_RUNTIME];
-    expect(MCP_RUNTIME.length).toBeGreaterThan(10);
-    expect(API_SCRIPTS.length).toBeGreaterThan(0);
-    expect(files.length).toBeGreaterThan(100);
-    const hits = scanTree(files, railwayEnvHits);
-    report('RAILWAY_* reads (apps/api + apps/auth + apps/mcp runtime)', files, hits);
-    // Every allowlisted read still exists (a stale entry would hide a regression)...
-    for (const [file, names] of Object.entries(RAILWAY_ALLOWLIST)) expect(hits[file], file).toEqual(names);
-    // ...and no read is outside it.
-    const unexpected = Object.fromEntries(Object.entries(hits).filter(([file]) => !(file in RAILWAY_ALLOWLIST)));
-    expect(unexpected).toEqual({});
+  it('covers every app src/lib and every package', () => {
+    for (const dir of ['apps/api/src', 'apps/api/lib', 'apps/auth/src', 'apps/frontend/src', 'apps/frontend/lib', 'apps/mcp/src', 'packages/auth', 'packages/types']) {
+      expect(SCAN_DIRS, dir).toContain(dir);
+    }
+    for (const dir of ['apps/mcp', 'packages']) {
+      expect(FILES.some((file) => file.startsWith(`${dir}/`)), dir).toBe(true);
+    }
+    expect(FILES.length).toBeGreaterThan(200);
+  });
+
+  it('fails on a planted read in the tree, and passes once it is removed', () => {
+    const planted = { path: 'apps/mcp/src/planted.ts', source: 'export const sha = process.env.RAILWAY_X;\n' };
+    expect(railwayTreeHits([...tree(), planted])).toEqual({ 'apps/mcp/src/planted.ts': ['RAILWAY_X'] });
+    expect(railwayTreeHits(tree())).toEqual({});
+  });
+
+  it('the tree has no hits, and no file is exempt', () => {
+    const hits = railwayTreeHits(tree());
+    report('RAILWAY_* reads (apps/*/src + apps/*/lib + packages/* + api/auth scripts)', FILES, hits);
+    expect(hits).toEqual({});
   });
 });
 
diff --git a/apps/api/turbo.json b/apps/api/turbo.json
index 667eeea0..47ccb0d9 100644
--- a/apps/api/turbo.json
+++ b/apps/api/turbo.json
@@ -20,11 +20,11 @@
     // which pins the root `test` script's worker cap: without it, removing the
     // cap left this task at the same hash and a warm cache replayed the pin green.
     //
-    // apps/mcp/src is here for source-scan 6 (#314), which reads it for
-    // RAILWAY_* names: without it a RAILWAY_ read added there left this task at
-    // the same hash and a warm cache replayed the scan green. (The scan's other
-    // trees are already inputs: apps/auth/src and apps/auth/scripts here,
-    // packages/auth/src through globalDependencies.)
+    // Every app's src/ and lib/ and every package are here for source-scan 6
+    // (#314, widened by #377), which reads them for RAILWAY_* names: without
+    // them a RAILWAY_ read added there left this task at the same hash and a
+    // warm cache replayed the scan green. (apps/auth/scripts, also scanned, is
+    // listed above.)
     //
     // The railway tomls are here for release-doc.test.ts (issue #364), which
     // checks each one against RELEASE.md: without them a toml-only edit left this
@@ -33,9 +33,10 @@
       "inputs": [
         "$TURBO_DEFAULT$",
         ".env.ci",
-        "$TURBO_ROOT$/apps/auth/src/**",
         "$TURBO_ROOT$/apps/auth/scripts/**",
-        "$TURBO_ROOT$/apps/mcp/src/**",
+        "$TURBO_ROOT$/apps/*/src/**",
+        "$TURBO_ROOT$/apps/*/lib/**",
+        "$TURBO_ROOT$/packages/**",
         "$TURBO_ROOT$/apps/auth/tests/helpers/**",
         "$TURBO_ROOT$/packages/auth/drizzle/**",
         "$TURBO_ROOT$/packages/auth/tests/helpers/**",
@@ -57,9 +58,17 @@
     // CI runs the same pin through test:coverage, so it needs the root
     // package.json too. Overriding `inputs` replaces the root task's list, so
     // the inherited entries are repeated.
-    // apps/mcp/src likewise, for source-scan 6 (#314): CI runs it through this task.
+    // Source-scan 6's trees likewise (#314, #377): CI runs it through this task.
     "test:coverage": {
-      "inputs": ["$TURBO_DEFAULT$", ".env.ci", "$TURBO_ROOT$/package.json", "$TURBO_ROOT$/apps/mcp/src/**"]
+      "inputs": [
+        "$TURBO_DEFAULT$",
+        ".env.ci",
+        "$TURBO_ROOT$/package.json",
+        "$TURBO_ROOT$/apps/*/src/**",
+        "$TURBO_ROOT$/apps/*/lib/**",
+        "$TURBO_ROOT$/packages/**",
+        "$TURBO_ROOT$/apps/auth/scripts/**"
+      ]
     }
   }
 }
diff --git a/apps/mcp/.env.example b/apps/mcp/.env.example
index debb3784..245c2795 100644
--- a/apps/mcp/.env.example
+++ b/apps/mcp/.env.example
@@ -32,8 +32,8 @@ PORT=3000
 # json = final-answer-only responses; unset = SSE (supports progress updates).
 # MCP_RESPONSE_MODE=json
 
-# Optional release id shown in /health, logs and the served HTML. On Railway,
-# leave unset: it falls back to RAILWAY_GIT_COMMIT_SHA.
+# Optional release id shown in /health, logs and the served HTML. Unset, it is the
+# application version. On Railway, set it in the dashboard to ${{RAILWAY_GIT_COMMIT_SHA}}.
 # ANSARI_RELEASE=
 
 # Local development (scripts/dev.ts, `pnpm dev`): PORT defaults to 3001 and ANSARI_API_BASE_URL to
diff --git a/apps/mcp/README.md b/apps/mcp/README.md
index 36b063e0..fef58807 100644
--- a/apps/mcp/README.md
+++ b/apps/mcp/README.md
@@ -113,8 +113,7 @@ The Worker takes the variables in the table below as Wrangler `vars` or secrets,
 | `MCP_ALLOWED_HOSTS` | Comma-separated allowed HTTP Host names, without scheme. A configured list replaces local defaults; an explicitly empty list permits no Host. Only an absent variable defaults to localhost and 127.0.0.1. |
 | `MCP_ALLOWED_ORIGINS` | Comma-separated allowed browser origin hostnames. A configured list replaces defaults; an explicitly empty list permits no Origin header value. Requests without Origin remain supported. |
 | `MCP_RESPONSE_MODE` | `json` for modern MCP final-answer-only responses; otherwise SSE, which supports client-requested progress notifications. Older-host compatibility responses may use SSE. |
-| `ANSARI_RELEASE` | Optional safe release identifier, embedded in served HTML and health/log records. |
-| `RAILWAY_GIT_COMMIT_SHA` | Set by Railway, not by hand. The release used when `ANSARI_RELEASE` is absent or not a safe identifier. |
+| `ANSARI_RELEASE` | Optional safe release identifier, embedded in served HTML and health/log records. Absent or unsafe, the release is the application version. On Railway, set it in the dashboard to the reference `${{RAILWAY_GIT_COMMIT_SHA}}`; the code reads no `RAILWAY_*` variable. |
 
 `POST /mcp` serves stateless MCP requests through Hono and the official MCP request handler. Modern requests need no initialization; older hosts can use the handler’s stateless compatibility path. No MCP session IDs, session map, expiry timer or replay store are retained. `GET /mcp` and `DELETE /mcp` return 405. `/health` exposes the release. The HTML is supplied by the hosting target (read from `dist/` at Node start, bundled into the Worker), revision-stamped and fingerprinted once before the first request is served: the release is stamped first, so equal final bytes have equal identities and a release change legitimately changes the hash. Each request creates its own lightweight MCP server using that prepared view; resource bytes and identity stay fixed until restart. No demo, font server, alternative renderer or historical resource is served. Tool calls have a fresh 60-second budget; timeout yields a safe error and leaves subsequent calls usable. The same lifetime signal aborts the upstream fetch and response-body read when the request ends or the budget expires.
 
diff --git a/apps/mcp/docs/show-me-ansari-mcp.html b/apps/mcp/docs/show-me-ansari-mcp.html
index 3799d81b..d46c28b6 100644
--- a/apps/mcp/docs/show-me-ansari-mcp.html
+++ b/apps/mcp/docs/show-me-ansari-mcp.html
@@ -196,7 +196,7 @@
 FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
 OTHER DEALINGS IN THE FONT SOFTWARE.
 
-