diff --git a/CRUX.md b/CRUX.md
index b403426..15fcc9d 100644
--- a/CRUX.md
+++ b/CRUX.md
@@ -1,141 +1,179 @@
-# OneHook — Complete Product & Technical Overview (Crux)
+# OneHook: Product and Technical Overview (Crux)
-This document provides a comprehensive overview of the OneHook platform's product philosophy, architecture, data flow, security posture, and engineering roadmap. It serves as the single source of truth for understanding how the different packages interact and the product problems they solve.
+This document summarizes what OneHook is, the problems it solves, how the product works, and how the
+repositories fit together. It is also the product context for Mr OneHook: the `push-context.yml`
+workflow uploads it to Azure Blob Storage (container `codecontext`, gamma resource group
+`onehook-chatbot-rg`), and the Mr OneHook backend adds it to the prompt of both the public product chat
+and the member chat. Keep it accurate and free of secrets or internal security findings.
+
+Detailed, maintained documentation lives in each repository's README (see section 7).
---
## 1. What is OneHook?
-OneHook is a premium, high-intent dating and connection platform built around the tagline **"One connection. Zero distractions."** It is positioned as an antidote to mainstream swipe-based dating apps — designed for people tired of endless swiping, ghosting, and low-intent matches.
+OneHook is a high-intent dating and connection platform built around the tagline **"One connection.
+Zero distractions."** It is meant for people tired of endless swiping, ghosting and low-intent matches.
+
+### Product philosophy
-### Core Product Philosophy
-- **Intentional matching over infinite choice** — the app pushes users toward fewer, higher-quality connections rather than an endless feed of options.
-- **Focused conversation over noise** — minimal feeds/stories/reels; the experience centers on private, structured chat rather than social-media-style browsing.
-- **One connection at a time (or very few)** — this constraint is meant to force deeper engagement instead of shallow, parallel conversations.
+- **Intentional matching over infinite choice.** Each member can hold only a small number of
+ connections ("hooks") at a time, so they engage with fewer, better matches.
+- **Focused conversation over noise.** There are no feeds, stories or reels. The experience centres on
+ private, end-to-end encrypted 1:1 chat and calls.
+- **Matching is optional.** A member can use OneHook for chat only and turn matching on when they want
+ to be discovered.
-## 2. Customer Problems OneHook Solves
+## 2. Customer problems OneHook solves
| Problem with mainstream dating apps | How OneHook addresses it |
|---|---|
-| Endless swiping fatigue, decision paralysis | Limits users to few/high-intent matches at a time |
-| Ghosting and low-intent matches | Structured, intent-driven matching reduces noise |
-| Superficial, low-quality conversations | Minimal distractions (no feeds/reels), focus on 1:1 private chat |
-| Privacy/security concerns in dating apps | End-to-end encrypted chat using a Signal-protocol-style pre-key exchange model |
-| Fake profiles / unverified users | Phone number verification and OTP-based identity checks baked into onboarding |
-| Poor-quality matchmaking logic | Production-grade, multi-feature scoring/ranking engine (not a simplistic swipe algorithm) |
-
----
-
-## 3. System Overview & Repositories
-
-OneHook is a distributed, multi-cloud ecosystem composed of five independently managed and deployed repositories. There is **no code coupling** between these repositories; they communicate strictly over network boundaries via APIs, WebSockets, and asynchronous events.
-
-| Repository | Purpose | Cloud/Infra | Primary Tech Stack |
-|---|---|---|---|
-| **OneHookBackend** | Core business logic, databases, auth, and microservices | AWS | Java 21, Spring Boot, Lambdas, DynamoDB, RDS PostgreSQL (PostGIS+pgvector) |
-| **OneHookClient** | Web-based user interface | AWS (S3+CloudFront) | React 19, Vite, Tailwind CSS 4, Zustand |
-| **OneHookPlatform** | Native mobile applications | App Stores | Swift (iOS), Kotlin (Android) |
-| **OneHookUxEnhancement** | AI-driven features, smart suggestions | Azure | Node.js, Azure OpenAI, Redis Cache, Blob Storage |
-| **OnehookIntelligence** | ML/Analytics for matching, behavioral scoring, semantic engine | GCP | Java 21, Cloud Run, Firestore, Pub/Sub |
-
----
+| Endless swiping, decision fatigue | A hook limit per tier (1 for Must and Super, 3 for Infinity); discovery pauses when a member is at capacity |
+| Ghosting and low-intent matches | A hook is a deliberate, limited commitment; members can be nudged when a conversation cools |
+| Superficial conversations | No social feeds; the product is built around 1:1 chat, voice notes and voice/video calls |
+| Privacy concerns | Messages, attachments and call signaling are end-to-end encrypted; the backend never sees content |
+| Fake or unsafe profiles | Phone OTP verification, Face Liveness checks, automated media and text moderation, blocks and reports |
+| Shallow matchmaking | A multi-signal ranking engine plus AI-assisted suggestions (Mr OneHook) |
-## 4. System Architecture (Backend Deep Dive)
+## 3. How the product works
-OneHook's core backend is a **serverless monorepo** built on Java (AWS Lambda), DynamoDB, AppSync/GraphQL, and AWS CDK for infrastructure-as-code. It is organized into five core microservices, each following a consistent layered pattern: **Controller → Handler → Service → Repository**, with its own CDK infra stack and dedicated test suite.
+### Accounts and sign-in
-### 4.1 Identity Service
-- Handles authentication using AWS Cognito and custom Lambda triggers.
-- Supports social login (Apple/Google Sign-In) with JWT/JWK signature, issuer, and audience validation via a `JwtVerifier` utility.
-- Implements phone number verification with OTP for onboarding and identity assurance.
-- *(Note: Historically had two parallel JWT verification implementations to consolidate).*
+Members sign up in the mobile apps with a phone number and OTP (invites are supported) and can add a
+username, email, password, passkeys and Apple or Google sign-in. The web app supports signing in, but
+new accounts are created in the apps.
-### 4.2 Chat Service
-- Real-time messaging built on AppSync/GraphQL and DynamoDB, exposed via Lambda handlers and REST/GraphQL endpoints.
-- Designed for **end-to-end encryption**, using a Signal-protocol-style pre-key bundle/pre-key record exchange system.
-- Uses a strategy-pattern handler design with sealed request types and contract tests that cross-validate GraphQL schema, Smithy models, Java code, and CDK infra definitions for consistency.
+### Membership tiers
-### 4.3 Matching Service
-- Implements a **Gale-Shapley-based ranking/matchmaking engine** — a stable-matching algorithm adapted with a feature-based scoring pipeline.
-- Scoring features include desirability, reciprocity, and proximity, combined into a weighted ranking pipeline (`ScoringFeature` implementations).
-- Has a `FilterRuleSetRepositoryImpl` intended for a real, tunable rule store (e.g., admin UI/DB-driven), rather than hardcoded rules.
-- Designed with experimentation in mind — algorithm labels and rule-set IDs are meant to be surfaced into analytics for A/B testing of weight/blend experiments.
+| Tier | Price | Hooks at a time | Notes |
+|---|---|---|---|
+| Must | Free | 1 | Mixed discovery deck; Mr OneHook limited to 10 messages per day |
+| Super | Paid | 1 | Choose a discovery category, save OneHook suggestions, saved Mr OneHook chats |
+| Infinity | Paid | 3 | Everything in Super, plus more connections and the option to hide past hooks from discovery |
-### 4.4 Profile Service
-- Manages user profile data and validation (including string-length limits shared with matching-side validators).
-- Works alongside identity/matching services to supply the attributes used in scoring and ranking.
+### Hooks
-### 4.5 State Service
-- Coordinates cross-service state (e.g., match lifecycle, connection state transitions) as part of the broader event-driven architecture using AWS EventBridge.
+Two members are hooked when they like each other in discovery (a mutual match) or when one sends a hook
+request (for example by username) and the other accepts. Releasing a hook ("unhook") ends the
+connection and deletes that conversation's messages, media and call history. Blocking someone also
+releases any hook between the two members. If a member moves to a tier with fewer hook slots, they choose
+which hooks to keep within 7 days; the others are released.
----
+### Discovery (matching on)
-## 5. Data Flow Architecture
-
-1. **Edge to Core**:
- - Clients send REST API and WebSocket requests to the AWS API Gateway (protected by AWS WAF and Cognito for JWT validation).
-2. **Synchronous Flow**:
- - API Gateway routes requests to Lambda functions (Identity, Profile, State, Chat) or to the ECS Fargate cluster via an internal ALB for the Matching Service.
- - Profile media is uploaded directly or handled via S3.
-3. **Asynchronous Event-Driven Flow (AWS)**:
- - Services emit domain events (e.g., `ProfileUpdated`) to an AWS EventBridge Bus.
- - SQS Queues consume these events and feed them to other internal consumers in an ordered manner. DynamoDB Streams-based replay is partially utilized for reliability.
-4. **Cross-Cloud Intelligence (AWS ↔ GCP)**:
- - Engagement events happening in AWS are forwarded (normalized) to GCP's `OnehookIntelligence` service via Cloud Run endpoints (`POST /engagement`).
- - The AWS Matching Service queries GCP (`GET /scores/{userId}` or `GET /intent/{userId}`) to construct optimized, intent-aware matching decks.
-5. **AI UX Enhancements (AWS/Clients ↔ Azure)**:
- - Clients or backend processes interact with `OneHookUxEnhancement`'s Node.js App Service on Azure to request AI-generated content or features. Rate limiting is enforced via Azure Redis.
+Matching is opt-in. When a member turns it on with a complete matching profile, they appear in
+discovery and get a discovery deck. Each card says who found it:
----
+- **OneHook Intelligence**: the candidate matches the member's details and preferences.
+- **Mr OneHook**: the candidate comes from a suggestion the member asked Mr OneHook for, or from an
+ inclination OneHook inferred from the member's recent likes.
-## 6. Matchmaking Algorithm — Is It Industry-Grade?
+Free members get one mixed deck (about 70% OneHook Intelligence, 30% Mr OneHook). Super and Infinity
+members can narrow it to one category. Ranking combines desirability, reciprocity, proximity and
+profile-embedding similarity, with a stable-matching (Gale-Shapley) step, plus engagement scores from
+the intelligence engines. Turning matching off erases the member's matching data; their hooks and chats
+stay.
-OneHook's matching system is **much closer to a production-grade matchmaking system than a simple swipe-based clone**. Supporting signals include:
+### Chat and calls
-- A feature-based scoring and ranking pipeline (desirability, reciprocity, proximity, etc.) via composable `ScoringFeature` implementations.
-- Use of the Gale-Shapley stable-matching algorithm as the theoretical backbone, adapted with real-world scoring weights.
-- Dedicated test coverage (e.g., `GaleShapleyRankingEngineTest`) validating matching logic correctness.
-- Architectural readiness for experimentation via algorithm labels and rule-set IDs designed to plug into analytics/experimentation systems.
-
----
+Chat is end-to-end encrypted across all of a member's devices, including a recoverable message
+history. It supports text, images, voice notes, stickers, GIFs and files, replies, reactions, typing
+indicators, last seen, read receipts, disappearing messages and screenshot alerts. Members can make 1:1
+voice and video calls; media and signaling are encrypted end to end.
-## 7. Privacy & Security Posture
+### Mr OneHook
-Multiple architectural reviews of the OneHook codebase surfaced and progressively resolved the following:
+Mr OneHook is OneHook's AI assistant (Azure OpenAI). On the website it answers product questions. In
+the apps, a signed-in member can ask about OneHook, about one of their connections, or for help writing
+a reply. Chat messages are only ever shared with Mr OneHook as excerpts the member reviews and confirms
+first; the excerpts are used for that one answer and are not stored. Super and Infinity members can
+choose to save their Mr OneHook conversations (their own questions and Mr OneHook's answers). In a
+product chat, Mr OneHook can also record a "find me ..." suggestion that feeds the member's discovery
+deck.
-### Authorization & Vulnerabilities
-- **Authorization gaps (IDOR)**: Missing ownership checks on REST handlers in the chat service (e.g., `GetChatHistoryHandler`, `DeleteMatchMessagesHandler`, `GetPreKeyBundleHandler`) were prioritized and fixed given the E2EE/PII sensitivity of the chat service. Following fixes, the chat service was assessed as reasonably ready for production traffic.
-- **Data Deletion Bug**: A DynamoDB batch-delete pagination bug (`DynamoMessageRepository.deleteMessagesForMatch`) that could silently violate the "message deleted" guarantee was identified and fixed.
+### Safety
-### Authentication Hardening
-- **AWS Cognito** provides the central identity provider. All client interactions with the core backend require valid JWTs.
-- **JWT/OTP hardening**: Verification logic for social sign-in was reviewed for missing audience (`aud`)/`azp` checks. OTPs need TTL/expiration checks and rate-limiting for resend requests.
+Profile photos, text and audio are moderated automatically, with an admin moderation queue behind it.
+Members can block and report each other. Account deletion erases the member's data in every service.
-### Data Segregation
-- **Personally Identifiable Information (PII)**: Core PII, user state, and chats are stored securely in AWS DynamoDB and S3 (for media).
-- **ML / Analytics Data**: `OnehookIntelligence` stores only derived behavioral data, engagement signals, and precomputed scores in GCP Firestore. It maintains its own isolated state with tight GCP IAM Auth.
-- **AI Context**: Azure Blob Storage (`OneHookUxEnhancement`) temporarily caches necessary context for OpenAI completion requests, ensuring data does not leak across sessions.
+## 4. Repositories
-### Network Protection
-- **AWS WAF**: Shields the main API Gateway against malicious payloads and DDoS attacks.
-- **Network security**: Uses an internal NLB (Network Load Balancer) pattern with Fargate tasks. Identified gap around Fargate task security groups being too permissive relative to the NLB's intended isolation.
-- **Secrets Management**: AWS Secrets Manager handles sensitive credentials like RDS passwords and JWT signing keys.
+OneHook is six independently built and deployed repositories. They share no code; they talk over
+HTTPS APIs, WebSockets and events. Generated artifacts (the API route manifest, the telemetry catalog
+and the membership catalog) are copied from the backend into the client repositories by sync scripts.
----
-
-## 8. Infrastructure & DevOps
+| Repository | Purpose | Hosting | Main technologies |
+|---|---|---|---|
+| **OneHookBackend** | Every core service, including intelligence | AWS (`ap-south-1`) | Java 21 (Lambda, Spring Boot on ECS Fargate), TypeScript and Python 3.12 Lambdas, DynamoDB, RDS PostgreSQL (PostGIS, pgvector), AppSync, EventBridge, AWS CDK |
+| **OneHookClient** | Web app and website `onehook.club` | AWS (S3 + CloudFront) | React 19, Vite 6, Tailwind CSS 4, Zustand 5, AWS Amplify |
+| **OneHookPlatform** | Native apps | App Store, Google Play | Swift 6, mostly UIKit (iOS 17+); Kotlin (Android, minSdk 26) |
+| **OneHookUXEnhancement** | Mr OneHook backend | Azure App Service | Node.js, Azure OpenAI (`gpt-4o`), Azure Blob and Table Storage, Terraform |
+| **OneHookAdminPortal** | Admin portal `admin.onehook.club`: moderation, admissions, scoring policy | AWS | TypeScript, React 19, AWS CDK |
-- **Infrastructure as Code**: Entire system provisioned via AWS CDK (per-service stacks) and Terraform (Azure/GCP).
-- **Decoupled Workflows**: Each repository manages its own build and CI/CD pipeline.
-- **CI/CD Pipelines**: Git-based workflows with GitHub Actions for build/test/deploy automation. AWS uses a multi-stage CodePipeline (Build -> Beta -> PreProd -> Manual Approval -> Prod) to deploy infrastructure as code.
+The former GCP repository `OnehookIntelligence` is archived. Its engines (scoring, intent, behavioral
+and temporal) now run on AWS inside OneHookBackend (`packages/intelligence`).
----
+## 5. Architecture
-## 9. Summary of Engineering Maturity
+### Backend services (OneHookBackend)
-| Layer | Status |
+| Service | Responsibility |
|---|---|
-| Identity/Auth (Cognito, JWT, OTP) | Functional; hardening recommended (JWT audience checks, OTP rate-limiting) |
-| Chat (E2EE, AppSync/GraphQL) | IDOR vulnerabilities found and fixed; contract tests keep schema layers in sync |
-| Matching (Gale-Shapley engine) | Production-grade design with feature-based scoring; needs operational tuning store |
-| Infra (CDK, Fargate/NLB, EventBridge) | Solid IaC foundation; network isolation and DLQ/retry configs need finishing touches |
\ No newline at end of file
+| Identity | Registration, phone/email OTP, Apple/Google sign-in, passkeys, usernames, invites, account state, account deletion |
+| Profile | Chat and matching profiles, media, moderation, Face Liveness |
+| State | Hooks and their lifecycle, hook requests, blocks, reports, tier capacity, matching on/off |
+| Matching | Discovery decks, swipes, mutual matches, profile embeddings (Amazon Bedrock Titan), OneHook suggestions |
+| Chat | Encrypted messaging (AppSync GraphQL over WebSockets), device keys, attachments, notifications, calls |
+| Analytics | Client telemetry ingest, data lake, social graph, reconciliation, dashboards |
+| Intelligence | Engagement scoring, intent and behavioral analysis; pushes scores to Matching |
+
+### Request and event flow
+
+1. **Clients to backend.** REST calls go to one CloudFront ingress (`api.onehook.club`, or
+ `api.gamma.onehook.club` for gamma) that routes by path to each service's API Gateway; every member
+ request carries a Cognito ID token. Chat uses AppSync GraphQL and WebSockets at `graphql.api...`.
+2. **Between services.** Services publish domain events (for example `ProfileUpdated`, `MutualMatch`,
+ `HookCreated`, `MessageSent`, `UserDeleted`) on one EventBridge bus per stage, and consumers react
+ asynchronously. Several services use a transactional outbox so an event is published only if its
+ database write committed.
+3. **Intelligence.** A forwarder takes engagement events (swipes, matches, conversation activity and
+ client telemetry) off the bus and feeds the Python engines. They publish `IntelligenceScoresUpdated`
+ back on the bus, and Matching keeps a local copy of the scores for ranking. Nothing calls the
+ engines on a request path. This all runs inside AWS; there is no cross-cloud hop.
+4. **Mr OneHook.** The apps and website call the Azure service directly. For member chats it reaches
+ OneHook data through a federated AWS role limited to a few read-only routes (match context,
+ matching status) and one route to record suggestions, plus an account-deletion queue.
+
+### Environments
+
+The backend has two stages, **gamma** (testing) and **prod**, each in its own AWS account with its own
+data. Today the website and local development use the gamma backend.
+
+## 6. Privacy and security posture
+
+- **End-to-end encryption.** Message content, reactions, attachments and call signaling are encrypted
+ on the device. The backend stores ciphertext and the minimum metadata needed to deliver it.
+- **Identity.** Amazon Cognito is the identity provider. APIs verify the member's token, and the
+ member's tier is read from the verified token, not from the request.
+- **Least privilege.** Service-to-service and admin calls use AWS IAM (SigV4). Every application role
+ is capped by a permissions boundary, and the deployment pipeline holds no long-lived credentials.
+- **Data minimization.** Unhooking deletes a conversation's messages, media and call history. Account
+ deletion triggers erasure in every service, including the data lake, the intelligence engines and
+ Mr OneHook. Turning matching off erases matching data.
+- **Edge protection.** AWS WAF protects the public authentication and chat routes in production, and
+ APIs are rate limited.
+
+## 7. Engineering practices
+
+- **Infrastructure as code.** AWS CDK for the backend, web client and admin portal; Terraform for the
+ Azure service.
+- **Contracts as code.** Every HTTP route is a Smithy operation; the route manifest, the TypeScript SDK
+ (`onehook-api-client`), the Java models and contract tests are generated or checked from it. Events and
+ client telemetry have their own catalogs with tests.
+- **Delivery.** The backend deploys through AWS CodePipeline: build and test, deploy to gamma, then a
+ separately built prod release after manual approval. The web client deploys through its own
+ CodePipeline with a production approval. The Mr OneHook backend deploys with GitHub Actions to gamma,
+ then prod after approval. Pull requests run CI in GitHub Actions.
+
+For details, read the README of each repository: OneHookBackend (with one README per package),
+OneHookClient, OneHookPlatform (`ios/` and `android/`), OneHookUXEnhancement and OneHookAdminPortal.
diff --git a/README.md b/README.md
index a8a52e7..18634a4 100644
--- a/README.md
+++ b/README.md
@@ -1,27 +1,35 @@
# OneHook Client
-React frontend application for the OneHook platform. Built with Vite, React 19, Tailwind CSS 4, and deployed via AWS CDK (S3 + CloudFront).
+React web application for the OneHook platform (`onehook.club`). Built with Vite, React 19 and
+Tailwind CSS 4, and deployed with AWS CDK (S3 + CloudFront) through an AWS CodePipeline.
## Tech Stack
-- **React 19** — UI framework
-- **Vite 6** — Build tool & dev server
-- **Tailwind CSS 4** — Utility-first styling
-- **Zustand** — State management
-- **Motion** — Animations
-- **Lucide React** — Icons
-- **React Router 7** — Client-side routing
-- **Vitest** — Testing
+Versions are the ranges declared in `package.json`.
+
+- **React 19** (`react`, `react-dom`): UI framework
+- **Vite 6**: build tool and dev server
+- **TypeScript 5.8**: `npm run lint` is `tsc --noEmit`
+- **Tailwind CSS 4** (`@tailwindcss/vite`): utility-first styling
+- **Zustand 5**: state management (`src/store/app-store.ts`)
+- **Motion 12**: animations
+- **Lucide React**: icons
+- **React Router 7** (`react-router-dom`): client-side routing
+- **AWS Amplify 6** (`aws-amplify`, `@aws-amplify/ui-react`, `@aws-amplify/ui-react-liveness`):
+ Cognito auth, AppSync GraphQL client and Face Liveness UI
+- **`onehook-api-client`**: Smithy-generated REST SDK for the OneHook backend, installed from the
+ npm registry at the version pinned in `package-lock.json` (currently 1.0.42)
+- **Vitest 4**: testing (`fake-indexeddb` for the E2EE key-store tests)
+- **AWS CDK 2** (`aws-cdk-lib`, `aws-cdk`): site and pipeline infrastructure under `infra/`
## Prerequisites
-- Node.js >= 20.0.0
-- npm >= 10.0.0
+- Node.js >= 20.0.0 and npm >= 10.0.0 (`package.json` `engines`). GitHub CI and CodeBuild run Node 22.
## Quick Start
```bash
-# Install dependencies
+# Install dependencies (also activates the telemetry pre-push hook, see "Telemetry contract")
npm install
# Start dev server (port 3000)
@@ -33,10 +41,32 @@ npm test
# Type-check
npm run lint
-# Build for production
+# Build for production (runs the telemetry contract gate first)
npm run build
```
+### npm scripts
+
+| Script | What it does |
+|---|---|
+| `dev` | `vite --port=3000 --mode development`; `predev` prints the telemetry contract banner |
+| `build` / `build:prod` | `vite build --mode production`; the `prebuild*` hooks run the telemetry contract gate |
+| `build:dev` | `vite build --mode development` (same gate) |
+| `preview` | `vite preview` |
+| `test` | `vitest run src/tests` |
+| `test:unit` / `test:integration` | single files `src/tests/unit.test.ts` / `src/tests/integration.test.ts` |
+| `test:watch` / `test:coverage` | Vitest watch / coverage over `src/tests` |
+| `lint` | `tsc --noEmit` |
+| `lint:fix` / `format` | type-check and/or Prettier write |
+| `validate` | `npm run lint && npm test` |
+| `telemetry:contract` | `node scripts/telemetry-contract.mjs` |
+| `synth:prod` | `cdk synth --context env=prod` (site stacks) |
+| `synth:pipeline` / `diff:pipeline` / `deploy:pipeline` | pipeline stack (`infra/pipeline/pipeline-app.ts`) |
+| `cdk:deploy` / `deploy:prod` | build, then deploy the site stacks directly (break-glass only) |
+
+`test:e2e` runs `playwright test`, but Playwright is not a dependency and there is no Playwright
+config in the repository.
+
## Local Development Setup
The application defaults to the real Gamma backend through the public, checked-in configuration in
@@ -46,6 +76,16 @@ The application defaults to the real Gamma backend through the public, checked-i
npm run dev
```
+On `localhost` the REST SDK sends requests to the dev-server origin (`src/api/sdk-client.ts`), and
+the Vite dev server proxies `/identity`, `/profile`, `/state`, `/matching`, `/chat` and `/signals` to
+`https://api.gamma.onehook.club` (`src/config/dev-proxy.ts`, used by `vite.config.ts`).
+`src/tests/dev-proxy.test.ts` fails when a Cognito or public route in the generated route manifest is
+not covered. The proxy target is hard-coded, so
+`VITE_API_BASE_URL` does not change where REST calls go on `localhost`. AppSync GraphQL, Cognito and
+the Mr OneHook chatbot are called directly at their configured URLs. `vite.config.ts` also defines
+proxy rules for a LocalStack backend under `/api/localstack/*` (and `/graphql` when a LocalStack
+AppSync API named `OneHook-Chat-local-ChatApi` is found); the default configuration does not use them.
+
If you need to point your local browser at different real infrastructure, copy `.env.example` to the
git-ignored `.env` and set only the overrides you need. Local scaffolding remains each developer's
responsibility: there is no mock server, mock scenario, or fixture data in the runtime tree.
@@ -54,32 +94,191 @@ responsibility: there is no mock server, mock scenario, or fixture data in the r
Public browser configuration is source-controlled in `src/config/deployment.config.ts`. The
production-site artifact and local development both select its `gamma` entry, which contains the
-unified REST URL, AppSync GraphQL URL, Cognito public identifiers, chatbot URL, feature defaults,
-timeout, and log level. Vite bundles these values into browser JavaScript, so this file must never
-contain a secret.
+unified REST URL, AppSync GraphQL URL, Mr OneHook chatbot URL, Cognito public identifiers, Google
+OAuth web client ID, admin-portal moderation base URL, feature defaults, timeout, and log level. Vite
+bundles these values into browser JavaScript, so this file must never contain a secret.
No GitHub `VITE_*` variables or local `.env` are required. The production CodeBuild project sets
-only the non-secret selector `VITE_BACKEND_STAGE=gamma`; an unknown selector fails the build.
-Developers may copy `.env.example` to ignored `.env` and override individual values for local
+only non-secret variables: `VITE_APP_ENV=production`, the backend selector `VITE_BACKEND_STAGE=gamma`,
+`CDK_DEFAULT_ACCOUNT`, `CDK_DEFAULT_REGION` and `SOURCE_COMMIT`. An unknown backend selector fails the
+build. Developers may copy `.env.example` to ignored `.env` and override individual values for local
work. Explicit boolean, timeout, and log-level overrides are validated, while blank values use
source defaults. The unused `VITE_WS_URL` setting has been removed.
+Overrides read by `src/utils/env.config.ts`:
+
+| Variable | Default |
+|---|---|
+| `VITE_APP_ENV` | Vite `MODE`, then hostname detection |
+| `VITE_BACKEND_STAGE` | `gamma` (the only entry) |
+| `VITE_API_BASE_URL` | stage `apiBaseUrl`; empty in development |
+| `VITE_GRAPHQL_URL`, `VITE_CHATBOT_URL`, `VITE_PORTAL_MODERATION_BASE_URL` | stage values |
+| `VITE_COGNITO_REGION`, `VITE_COGNITO_USER_POOL_ID`, `VITE_COGNITO_CLIENT_ID`, `VITE_COGNITO_IDENTITY_POOL_ID`, `VITE_COGNITO_DOMAIN` | stage values |
+| `VITE_COGNITO_ENDPOINT` | `https://cognito-idp..amazonaws.com` |
+| `VITE_COGNITO_REDIRECT_SIGN_IN`, `VITE_COGNITO_REDIRECT_SIGN_OUT` | browser origin |
+| `VITE_GOOGLE_CLIENT_ID` | stage value; must match the backend `GOOGLE_CLIENT_ID` |
+| `VITE_ENABLE_ANALYTICS`, `VITE_ENABLE_DEBUG` | `false` |
+| `VITE_API_TIMEOUT_MS` | `30000` |
+| `VITE_LOG_LEVEL` | `error` |
+
Gamma Cognito is in `ap-south-1`. Its IDP endpoint is derived from that region. User Pool, app-client
and Identity Pool IDs are public routing identifiers rather than credentials. Redirects default to
the browser origin, but Amplify Hosted UI OAuth is enabled only when domain, sign-in redirect, and
sign-out redirect are all non-empty; direct Cognito authentication remains available without it.
+The Gamma entry has an empty `cognitoDomain`, so Hosted UI OAuth is currently off.
When the production backend has been deployed and validated, add a source-controlled `prod` entry,
then change only the production build's `VITE_BACKEND_STAGE` selector. Do not switch production URLs
independently in pipeline settings.
-## Mr OneHook member chat
+## Application Overview
+
+### Routes
+
+Defined in `src/App.tsx`.
+
+| Path | Page | Guard |
+|---|---|---|
+| `/` | Landing | public |
+| `/messenger`, `/science`, `/pricing`, `/careers`, `/contact`, `/privacy`, `/terms` | marketing and legal pages | public |
+| `/login` | sign in | signed-out only (`GuestOnlyRoute`) |
+| `/redeem` | invite redemption; shows the "sign up in the app" notice because web sign-up is off | signed-out only |
+| `/auth/setup` | post-sign-in email verification and passkey setup (`AuthSetupWizard`) | signed in |
+| `/onboarding` | profile onboarding (`OnboardingWizard`) | signed in, still `ONBOARDING`, and registration prerequisites met |
+| `/app` | the member app (`src/app/AppContent.tsx`) | signed in and past onboarding (`OnboardedRoute`, fails closed) |
+| `*` | not-found page | public |
+
+Inside `/app` the tabs depend on the matching mode (`src/lib/app-mode.ts`). With matching on:
+Discover, Likes, Chat, Profile and Settings. A chat-only member gets the Matching intro (unless hidden
+in Settings), Chat, Profile and Settings, and nothing that calls `/matching/*` is mounted.
+
+### Backend interfaces
+
+- **Every OneHook API call goes through the `onehook-api-client` package; nothing builds a URL or a
+ request by hand.** `npm test` fails otherwise (`src/tests/api-route-contract.test.ts`): a raw
+ `fetch`/XHR to a OneHook API fails whatever its path, and each SDK call must be an operation of the
+ service its client serves (checked against each owner's route manifest: the synced backend one, and
+ `onehook-mr-onehook-client/manifest` / `saha-equation-admin-portal-client/manifest`). The only raw requests
+ are to presigned S3 URLs an API returned, each listed with a reason. A missing operation is added to
+ its owner's Smithy model and published, never written in the client.
+- **REST**: the generated `OneHook` client in `src/api/sdk-client.ts` against the single REST domain,
+ with the Cognito ID token (falling back to the access token) as a Bearer header. SigV4 signing is
+ removed. Service wrappers live in `src/api/`; `callSdk` turns SDK errors into the shared `ApiError`.
+- **AppSync GraphQL**: chat messages, voice/video call signalling and in-app notifications use the
+ Amplify GraphQL client with `userPool` auth (`src/api/chat.ts`, `src/api/calls.ts`,
+ `src/api/notifications.ts`).
+- **Mr OneHook chatbot**: `mrOneHookClient` from `onehook-mr-onehook-client` (published by
+ OneHookUXEnhancement) at `chatbotUrl` (Azure App Service, see "Mr OneHook member chat"), in
+ `src/api/external-sdk-clients.ts`.
+- **Admin portal moderation gateway**: report evidence presign/complete through
+ `saha-equation-admin-portal-client` (published by OneHookAdminPortal for every tenant).
+ `createModerationEvidenceClient` binds OneHook's tenant (`{service, stage}` from
+ `portalModerationBaseUrl`) and sends the member ID token (`src/features/moderation/report/`).
+- **Cognito Identity Pool**: temporary credentials for Rekognition Face Liveness streaming
+ (`src/api/liveness.ts`, `src/components/profile/LivenessVerification.tsx`).
+
+## Authentication and Sessions
+
+`src/lib/cognito-auth.ts` configures Amplify and wraps every sign-in method:
+
+- **Phone or email one-time code**: Cognito custom auth (`CUSTOM_WITHOUT_SRP`) with
+ `clientMetadata.authStrategy` set to `email` or `phone`, finished with `confirmSignIn`.
+- **Password**: `USER_AUTH` with `PASSWORD_SRP`. Phone, email or username (`preferred_username`
+ alias) can sign in with a password; a username has no code flow.
+- **Set or reset a password**: Cognito `resetPassword` / `confirmResetPassword`.
+- **Google**: Google Identity Services returns an ID token in-page, `POST /identity/auth/social`
+ resolves the linked account, then a Cognito custom-auth `PROVIDE_SOCIAL_TOKEN` challenge is
+ answered with the same token. No Hosted UI is involved.
+- **Apple**: `signInWithRedirect({ provider: 'Apple' })`, which needs Hosted UI OAuth (currently
+ not configured, see "Prerequisites if A or B is ever adopted").
+- **Passkeys**: registered with `associateWebAuthnCredential` from `/auth/setup` or the profile
+ account settings (`AccountSettingsCard`).
+
+**Sign-up is app-only.** `WEB_SIGNUP_ENABLED` is `false` in `src/config/signup.config.ts`: the first
+device must put the account history key into platform escrow (iCloud Keychain or Android Block
+Store), which the web cannot do. `/onboarding` verifies this with `useRegistrationPrerequisites`
+(an `ESCROW` wrap is required; a passkey PRF wrap is recommended) and otherwise shows
+`FinishSetupInAppNotice`.
+
+**Sign-out** (`CognitoAuthService.logout`) first secures and removes this browser's history key (see
+below), resets the shared encryption state, then calls Amplify `signOut`. The "sign out to set a
+password" action in `src/components/profile/SetPasswordCard.tsx` calls the full store `logout()`, so
+the next account signed in from that tab does not inherit the previous member's profile, state or
+view passes.
+
+## End-to-End Encrypted Chat (web)
+
+Implemented in `src/lib/chat-encryption.ts` (wire format in `src/lib/chat-wire-v2.ts`). Wire v1 has
+been removed; a v1 envelope fails with an "old encryption format" error.
+
+- Each browser has a non-extractable P-256 ECDH device key stored in IndexedDB (`onehook-e2ee`,
+ store `identity-keys`) and registered with `POST /chat/devices`. A message is encrypted once with
+ AES-256-GCM (AAD bound to the `matchId`) and its content key is wrapped for every registered device
+ of both members plus each member's account-history key.
+- **One device per login.** All `ChatEncryptionManager` instances for a user share one identity load
+ per page, and identity creation runs under a Web Lock (`onehook-e2ee-identity:`), so
+ concurrent components and tabs no longer each register a device.
+- **History unlock ladder** (`src/hooks/use-history-unlock.ts`): a device wrap sealed to this device
+ (silent), then a passkey PRF wrap (biometric prompt, only when one exists and PRF is supported).
+ QR transfer between devices (`KeyRecoveryResponder`, `HistoryRecoveryModal`, `QrCameraScanner`)
+ is the manual fallback. Platform escrow is written only by the native apps.
+- **Sign-out key hygiene** (`secureHistoryKeyForSignOut`): confirms or publishes a device wrap for
+ this browser, then deletes the history private key (CryptoKey and PKCS#8 bytes) from IndexedDB.
+ If the wrap cannot be confirmed the key is kept, because it may be the only copy. The step is
+ bounded to 4 seconds and never throws. The device key stays, so the next sign-in re-opens history
+ silently. Covered by `src/tests/sign-out-key-hygiene.test.ts`.
+- Settings and the account recovery dialog list registered devices and allow revoking one
+ (`DeviceManagementCard`, `DELETE /chat/devices/{deviceId}`).
+- Voice/video call SDP and ICE payloads are sealed with the same v2 envelope, to the peer's devices
+ only (`src/lib/call-signal.ts`).
+- There is no forward secrecy and no safety-number verification of peer keys; history recovery shows
+ a 6-digit code to compare across devices.
-The signed-in chat surface uses `POST /api/member/product-connection-chat` with the Cognito **ID token** (the member route verifies `aud` and reads the member's `roles`/tier from claims the access token does not carry). Members can choose product-only mode or one active match. Match messages remain end-to-end encrypted and are searched only after local decryption; when the service returns `needsMoreContext`, the browser selects bounded readable excerpts, displays the exact excerpt review panel, and sends them only after confirmation. Excerpts carry only `speaker`, `sentAt`, and `text` and are never persisted in the local Mr OneHook transcript.
-
-Paid (Super / Infinity) tiers request server-side AI-session persistence, while the server remains authoritative. Returned session IDs are stored per user and product/match scope; stale, expired, denied, or unavailable sessions are forgotten and the same question is retried without persistence. The public landing widget remains separate on `POST /api/public/product-chat` without an authorization header.
+## Mr OneHook member chat
-**Entitlement.** Mr OneHook is gated by the `context.chat` permission, granted to members in the `mr-onehook` Cognito group (the backend returns `403 INSUFFICIENT_PERMISSION` otherwise). The client classifies terminal availability — `NOT_ENTITLED` (403), `NOT_AUTHENTICATED` (401 `AUTH_REQUIRED`/`INVALID_ACCESS_TOKEN`), `NOT_CONFIGURED` (404/503) — via `classifyMemberChatAvailability`, surfaces a clear one-time message, and disables the composer rather than showing a retryable error. A recognised-but-unrelated code (e.g. a session or per-request validation code) is handled on its own path and never gates the feature.
+The signed-in chat surface uses `POST ${chatbotUrl}/api/member/product-connection-chat` with the
+Cognito **ID token** (the member route verifies `aud` and reads the member's `roles`/tier from claims
+the access token does not carry). `chatbotUrl` is `https://chatbot.gamma.onehook.club`, an Azure App
+Service from OneHookUXEnhancement. Members can choose product-only mode or one active match. Match
+messages remain end-to-end encrypted and are searched only after local decryption; when the service
+returns `needsMoreContext`, the browser selects bounded readable excerpts, displays the exact excerpt
+review panel, and sends them only after confirmation. Excerpts carry only `speaker`, `sentAt`, and
+`text` and are never persisted in the local Mr OneHook transcript.
+
+Free (Must) members get 10 messages per UTC day, and their transcript lives only in memory. Paid
+(Super / Infinity) tiers keep the transcript in `localStorage` per user and scope and request
+server-side AI-session persistence (`GET`/`DELETE .../sessions[/:id]`), while the server remains
+authoritative. Returned session IDs are stored per user and product/match scope; stale, expired,
+denied, or unavailable sessions are forgotten and the same question is retried without persistence.
+The public landing widget (`src/components/Chatbot/ChatbotWidget.tsx`, shown on `/`, `/pricing` and
+`/science`) remains separate on `POST ${chatbotUrl}/api/public/product-chat` without an authorization
+header.
+
+**Availability.** There is no group or permission gate; every member can chat. The client
+classifies terminal availability with `classifyMemberChatAvailability`
+(`src/lib/mr-onehook-contract.ts`): `LIMIT_REACHED` (402 `MESSAGE_LIMIT_REACHED`), `NOT_AUTHENTICATED`
+(401 `AUTH_REQUIRED`/`INVALID_ACCESS_TOKEN`) and `NOT_CONFIGURED` (404 `ENDPOINT_NOT_FOUND`/503
+`CONTEXT_NOT_CONFIGURED`). The structured error code wins; the HTTP status (402, 401 or 404) is used
+only when no code is present. The UI shows a clear message and disables the composer rather than
+showing a retryable error. A recognised-but-unrelated code (e.g. a session or per-request validation
+code, including any 403) is handled on its own path and never gates the feature.
+
+## Telemetry Contract
+
+`TELEMETRY_CONTRACT.txt` (synced from OneHookBackend) is a hard rule: every user interaction emits
+one `ui_interaction` with a backend-generated `UiElement` id via `trackProps` / `trackUi`
+(`src/lib/analytics/`). The generated catalog `src/lib/analytics/generated/telemetryCatalog.ts`
+must not be edited by hand.
+
+`scripts/telemetry-contract.mjs` prints the contract, checks the catalog's sha256 integrity stamp,
+and runs the `telemetry-coverage`, `telemetry-guard`, `telemetry-sdk` and `telemetry-standard`
+tests. It runs before every build (`prebuild*`), in GitHub CI, in the CodePipeline `Verify` stage,
+and in the `.githooks/pre-push` hook, which `scripts/install-git-hooks.mjs` activates
+(`core.hooksPath=.githooks`) on `npm install` and on build.
+
+Events are batched to `POST /signals` with the caller's Cognito JWT. Emission is gated by
+`enableAnalytics` and the user's stored consent; the Gamma entry sets `enableAnalytics: false`, so the
+current artifact sends nothing until that flag is turned on.
## Engineering Policy: No Test Code in Production (strict)
@@ -99,28 +298,31 @@ What this forbids:
What this requires instead:
- **Fail loudly.** Missing prerequisites (e.g. the generated SDK) must break the build with an
- actionable message — never degrade to a stub.
+ actionable message, never degrade to a stub.
- **Real backends for real behaviour.** Develop against a deployed environment; keep that wiring in untracked files.
- **Tests stay, mocks go.** Unit/integration tests under `src/tests` are *not* shipped (Vitest files
are never bundled) and remain first-class. What is banned is test-support code living in the
application's runtime path.
- **Tests must be hermetic.** A committed test must not depend on a developer's local `.env`; stub
every variable it reads. (A previously committed env test silently passed only on machines with no
- local `.env` — exactly the failure mode this rule prevents.)
+ local `.env`, which is exactly the failure mode this rule prevents.)
Anything test-related that must exist locally belongs in your own untracked working files.
### Deployments are gated on tests
-`.github/workflows/ci.yml` remains a pull-request-only GitHub check. Deployment is independently
-gated inside the AWS pipeline because pull-request and `main` push events are separate: the
-CodePipeline `Verify` stage runs `npm run lint` and `npm test` against the exact CodeConnections
-source revision before any deployment-capable CodeBuild project runs.
+`.github/workflows/ci.yml` remains a pull-request-only GitHub check (pull requests to `main` and
+`develop`) that runs `npm run lint`, `npm run telemetry:contract` and `npm test`. Deployment is
+independently gated inside the AWS pipeline because pull-request and `main` push events are
+separate: the CodePipeline `Verify` stage runs `npm run lint`, `npm test` and
+`npm run telemetry:contract` against the exact CodeConnections source revision before any
+deployment-capable CodeBuild project runs.
On every push to `main`, `BuildProduction` repeats type checking and tests, builds the production
-bundle, verifies its bundled endpoints, and synthesizes a complete CDK cloud assembly. Only that
-immutable pipeline artifact reaches AWS manual approval. The post-approval project deploys the
-stored assembly with `--app cdk.out.prod`; it never runs Vite or CDK synthesis again.
+bundle (which runs the telemetry gate again), verifies its bundled endpoints (Gamma REST and GraphQL
+URLs present, `https://api.onehook.club` absent), and synthesizes a complete CDK cloud assembly.
+Only that immutable pipeline artifact reaches AWS manual approval. The post-approval project deploys
+the stored assembly with `--app cdk.out.prod`; it never runs Vite or CDK synthesis again.
A failed check, build, synth, or deployment therefore cannot reach production approval.
@@ -130,21 +332,31 @@ A failed check, build, synth, or deployment therefore cannot reach production ap
## Rendering Model & Tier Personalization (SSR tradeoffs)
-Today this app is a **client-rendered SPA**: Vite builds static assets, S3 serves them, CloudFront
-caches them. There is no server-side rendering tier and no edge compute in the request path.
+Today this app is a **client-rendered SPA** with **build-time pre-rendering**: Vite builds static
+assets, S3 serves them, CloudFront caches them. There is no server-side rendering tier and no
+Lambda@Edge. The only edge compute is CloudFront Functions on viewer request (see "Infrastructure").
+
+After the client build, the `prerender-pages` plugin in `vite.config.ts` writes
+`dist//index.html` for every route in `src/config/seo-routes.ts`, plus `dist/404.html` and
+`sitemap.xml`. Each file carries the route's own title, description, robots, canonical, Open Graph /
+Twitter tags and JSON-LD. Public pages (`src/prerender-entry.tsx`) also get their body rendered with
+React at build time. `/app`, `/onboarding` and `/auth/setup` are `noindex` and left out of the
+sitemap. In the browser, `createRoot` replaces the pre-rendered markup.
### How the subscription tier is resolved (implemented)
The tier is **server-authoritative**. It is read from the State service (`GET /state/{userId}`),
which owns the connection state machine and the entitlement, and published to the Zustand store as
-`userState`; the UI derives `isPremium` from it.
+`userState`; the UI derives paid status with the `isPaidTier` selector (`src/store/app-store.ts`),
+which uses `isPaidSubscriptionTier` from the backend-owned membership catalogue in
+`onehook-api-client/membership` (tiers `MUST`, `SUPER`, `INFINITY`).
It is deliberately **not** read from the profile: the Profile service intentionally omits
-`subscriptionTier` from its read model, so reading it off a profile silently yields `undefined` —
+`subscriptionTier` from its read model, so reading it off a profile silently yields `undefined`,
which previously made *every* user render as a paid tier and hid the upgrade CTA from free users.
-`isPremium` **fails closed**: until the snapshot loads the UI shows `BASIC`, so it never briefly
-promises premium.
+`isPaidTier` **fails closed**: until the snapshot loads it returns `false`, so the UI shows the free
+`MUST` tier and never briefly promises a paid one.
> **The UI is not a security boundary.** A user can edit their own browser and reveal a premium
> control; clicking it still fails, because entitlement is enforced independently server-side (State
@@ -161,17 +373,18 @@ promises premium.
| **C — Server-authoritative bootstrap** ✅ | Keep the SPA; render from the tier the server reports | ~1 day | Generic, then corrects |
**We chose C.** Rationale: the goal was correctness of the rendered value, and enforcement was
-already server-side — so A and B would have added infrastructure without adding security. A/B only
+already server-side, so A and B would have added infrastructure without adding security. A/B only
become worthwhile for first-paint/SEO reasons (no flicker, correct HTML for crawlers).
### Prerequisites if A or B is ever adopted
Real blockers found while scoping; they apply regardless of which option:
-1. **No Cognito hosted-UI domain exists**, and the app client's callback URL is still the CDK
- placeholder (`https://example.com`). The OAuth *code* flow this client already configures cannot
- work in deployed environments until a `UserPoolDomain` and real callback/logout URLs are added —
- social sign-in is affected today.
+1. **No Cognito hosted-UI domain exists**, and the backend app client defines no OAuth settings, so
+ its callback URL is the CDK default placeholder (`https://example.com`). The OAuth *code* flow
+ this client configures when a domain is set cannot work in deployed environments until a
+ `UserPoolDomain` and real callback/logout URLs are added. Apple sign-in (`signInWithRedirect`) is
+ affected today; Google sign-in uses Google Identity Services plus Cognito custom auth and is not.
2. **Tokens are invisible to the server.** Amplify keeps them in browser storage, so an origin never
receives them. Server-side tier reading needs an httpOnly session cookie (a BFF), not
JS-readable cookie storage.
@@ -179,27 +392,33 @@ Real blockers found while scoping; they apply regardless of which option:
personalized HTML would be served across users. Any per-tier rendering must add the tier to the
cache key (coarse buckets) or mark authenticated HTML `private, no-store`.
4. **Drop the `implicit` OAuth flow** (currently enabled by CDK default) and keep `code` only.
-5. **Staleness**: the JWT claim is only as fresh as the token (~1h). After a purchase, force a token
- refresh and re-read `GET /state/{userId}` — `POST /state/upgrade` already returns the freshly
- reconciled state for this purpose.
+5. **Staleness**: the JWT claim is only as fresh as the token (ID and access tokens are valid for 60
+ minutes). After a purchase, force a token refresh and re-read `GET /state/{userId}`.
+ `POST /state/upgrade` already returns the freshly reconciled state for this purpose; the current
+ upgrade handler in `src/app/AppContent.tsx` calls it, refreshes the session and refetches state
+ and profile.
## Deployment
A push to protected `main` is delivered directly to AWS through the CDK-managed GitHub
-CodeConnection. A queued CodePipeline V2 execution then deploys the production site into frontend
-account `851725215059`; GitHub Actions and GitHub OIDC are not in the deployment path. The frontend
-lives in Mumbai (`ap-south-1`). Backend account `627367419734` owns **only** the API zones
-(`api.gamma.onehook.club`, `api.onehook.club`); the pipeline never deploys backend resources.
-
-There is a single deployed site — production `onehook.club`. Both it and local development point
+CodeConnection. A CodePipeline V2 execution then deploys the production site into frontend account
+`851725215059`; GitHub Actions and GitHub OIDC are not in the deployment path. The pipeline uses
+`SUPERSEDED` execution mode: a newer push replaces an older execution still waiting (for example at
+manual approval), so only the latest tested assembly is deployed. The frontend lives in Mumbai
+(`ap-south-1`). The backend accounts own **only** the API zones (`api.gamma.onehook.club` in gamma
+account `627367419734`, `api.onehook.club` in prod account `934140897625`); this pipeline never deploys
+backend resources.
+
+There is a single deployed site, production `onehook.club`. Both it and local development point
their browser traffic at the Gamma backend for now (see "Runtime Configuration"). There is no
separate `gamma.onehook.club` frontend website.
| Stage | AWS account | Site | Runtime backend used by current artifact | Hosted zone | CloudFront certificate |
|---|---|---|---|---|---|
-| **production** | `851725215059` (owns the `onehook.club` zone) | `onehook.club` (+ `www`) | **temporarily the Gamma REST/GraphQL backend** (`api.gamma.onehook.club` / `graphql.api.gamma.onehook.club`); switch to `api.onehook.club` / `graphql.api.onehook.club` only after backend production promotion | existing `onehook.club` zone | dedicated `OneHook-Certificate-prod` stack in `us-east-1` (ownership preserved) |
+| **production** | `851725215059` (owns the `onehook.club` zone) | `onehook.club` (+ `www`, which redirects to the apex) | **temporarily the Gamma REST/GraphQL backend** (`api.gamma.onehook.club` / `graphql.api.gamma.onehook.club`); switch to `api.onehook.club` / `graphql.api.onehook.club` only after backend production promotion | existing `onehook.club` zone | dedicated `OneHook-Certificate-prod` stack in `us-east-1` (ownership preserved) |
-The pipeline is strictly sequential:
+The pipeline is strictly sequential (`Source`, `Verify`, `BuildProduction`, `ApproveProduction`,
+`DeployProduction`, `SmokeProduction`):
```text
Source (exact main commit)
@@ -207,9 +426,12 @@ Source (exact main commit)
→ Build/test/check + synthesize production cloud assembly
→ AWS manual approval
→ Deploy the exact approved assembly without rebuilding or re-synthesizing
-→ Smoke-test production
+→ Smoke-test production (https://onehook.club/ must return HTTP 200 within 10 attempts)
```
+`DeployProduction` deploys three stacks from the stored assembly: `OneHook-Certificate-prod`,
+`OneHook-Frontend-prod` and `OneHook-ChatbotDns-prod`.
+
CodePipeline stores source and build outputs in its encrypted, private, versioned S3 artifact
bucket. `BuildProduction` has only pipeline-required artifact-bucket and build-log access; it has no
infrastructure API or role-assumption permission. The stable public `onehook.club` hosted-zone ID is
@@ -228,15 +450,17 @@ add a `prod` entry to `src/config/deployment.config.ts` and change only the prod
### AWS pipeline infrastructure
The delivery plane is defined in `infra/pipeline/frontend-pipeline-stack.ts` and its source-controlled
-buildspecs. It provisions:
+buildspecs in `infra/pipeline/buildspecs/` (`verify.yml`, `production-build.yml`,
+`production-deploy.yml`, `smoke.yml`). It provisions:
- A GitHub `AWS::CodeConnections::Connection`; IAM permits `UseConnection` only on its exact ARN,
the source action fixes `pushpsood/OneHookClient` branch `main`, and the GitHub App installation
is granted access only to that repository.
-- A queued CodePipeline V2 pipeline named `OneHook-Frontend`.
+- A CodePipeline V2 pipeline named `OneHook-Frontend` in `SUPERSEDED` execution mode.
- Separate CodeBuild projects and service roles for verification, smoke tests, production
build/synth and production deployment.
-- A private, encrypted, versioned S3 artifact bucket with lifecycle cleanup.
+- A private, encrypted, versioned S3 artifact bucket with lifecycle cleanup (objects expire after 30
+ days, noncurrent versions after 7).
- CloudWatch build logs retained for one month.
- An SNS production-approval topic.
- An unattached managed policy granting only the exact production `PutApprovalResult` action; attach
@@ -312,36 +536,53 @@ The frontend account `851725215059` hosts the Route53 zone for the site domain:
`onehook.club` zone. The backend account keeps only the `api.gamma.onehook.club` /
`api.onehook.club` API zones. If you are migrating a domain, point the registrar's nameservers at
the corresponding Route53 hosted zone. During deployment CDK provisions the CloudFront certificate
-in `us-east-1` for production (dedicated `OneHook-Certificate-prod` stack, DNS-validated in the
-`onehook.club` zone).
+in `us-east-1` for production (dedicated `OneHook-Certificate-prod` stack, covering `onehook.club`
+and `*.onehook.club`, DNS-validated in the `onehook.club` zone).
## Infrastructure
The production site is deployed as a static site via:
-- **S3 (ap-south-1)** — Hosts the built assets
-- **CloudFront (Global)** — CDN with HTTPS, caching, and security headers
-- **Route53** — A + AAAA alias records for CloudFront, in the frontend account's `onehook.club`
- zone (apex + `www`)
-- **AWS Certificate Manager (us-east-1)** — CloudFront TLS cert; a dedicated `OneHook-Certificate-prod`
+- **S3 (ap-south-1)**: hosts the built assets; private, encrypted, versioned and retained on stack
+ deletion; read by CloudFront through an Origin Access Identity
+- **CloudFront (Global)**: CDN with HTTPS (TLS 1.2 minimum), caching, security headers (HSTS,
+ `X-Frame-Options: DENY`, nosniff, referrer policy, `Permissions-Policy`) and access logging. A
+ viewer-request CloudFront Function redirects `www` to the apex with a 301 and maps
+ `/` to `//index.html`. Missing objects (S3 404 or 403) return `/404.html` with a
+ real 404 status.
+- **`app.onehook.club` smart link**: a second CloudFront distribution whose viewer-request function
+ 302-redirects to the App Store or Play Store by User-Agent. Both store links are `null` today
+ (`src/config/app-store-links.ts`), so every device goes to `https://onehook.club/login`.
+- **Route53**: A + AAAA alias records for CloudFront, in the frontend account's `onehook.club`
+ zone (apex, `www` and `app`)
+- **AWS Certificate Manager (us-east-1)**: CloudFront TLS cert; a dedicated `OneHook-Certificate-prod`
stack (ownership preserved)
-
-Stage infrastructure is defined in `infra/stacks/frontend-app.ts` and
-`infra/stacks/frontend-stack.ts`; delivery infrastructure is defined separately in
-`infra/pipeline/pipeline-app.ts` and `infra/pipeline/frontend-pipeline-stack.ts`. Synthesize the
-production stage with `npm run synth:prod` and the pipeline with
+- **Mr OneHook chatbot DNS** (`OneHook-ChatbotDns-prod`, `infra/stacks/chatbot-dns-stack.ts`): CNAME
+ and `asuid` TXT records for `chatbot.gamma.onehook.club` and `chatbot.onehook.club`, pointing at
+ the Azure App Service hosts
+
+Stage infrastructure is defined in `infra/stacks/frontend-app.ts`, `infra/stacks/frontend-stack.ts`,
+`infra/stacks/chatbot-dns-stack.ts` and `infra/stacks/constants.ts`; delivery infrastructure is
+defined separately in `infra/pipeline/pipeline-app.ts` and `infra/pipeline/frontend-pipeline-stack.ts`.
+Synthesize the production stage with `npm run synth:prod` and the pipeline with
`AWS_PROFILE=pushp-sde-aws npm run synth:pipeline`. The direct `npm run deploy:prod` script remains
available for break-glass recovery, not the normal release path.
## Related Repositories
-- **OneHookBackend** — Backend microservices (provides API + Cognito)
-- **OneHookPlatform** — iOS and Android mobile applications
-
-## Azure OIDC Setup (For Azure Deployments)
+- **OneHookBackend**: backend microservices (REST API, AppSync, Cognito, intelligence, telemetry
+ catalog) and the source of `onehook-api-client`
+- **OneHookPlatform**: iOS and Android mobile applications (where sign-up happens)
+- **OneHookUXEnhancement**: the Mr OneHook chatbot API on Azure App Service
+- **OneHookAdminPortal**: admin portal, including the public member moderation gateway used for report evidence
-If you are migrating this frontend to Azure (e.g., Azure Static Web Apps) or need to deploy resources to Azure via GitHub Actions, you can establish a secretless trust using Azure Managed Identities and OpenID Connect (OIDC).
+## Azure OIDC Setup (GitHub Actions to Azure)
-To set this up, a script has been provided: `setup-azure-oidc.sh` (specifically for Azure).
+`.github/workflows/push-context.yml` uploads `CRUX.md` to the `codecontext` container of the first
+storage account in resource group `onehook-chatbot-rg` on pushes to `main` that change `CRUX.md` (or
+the workflow), or on manual dispatch. It signs in to Azure with OIDC using the
+`AZURE_CLIENT_ID_CLIENT`, `AZURE_TENANT_ID_CLIENT` and `AZURE_SUBSCRIPTION_ID_CLIENT` secrets, which
+`setup-azure-oidc.sh` creates. This is the only GitHub workflow that talks to a cloud provider; it
+does not deploy the website.
### Prerequisites
1. **Azure CLI**: `az login`
@@ -358,7 +599,7 @@ To set this up, a script has been provided: `setup-azure-oidc.sh` (specifically
```
### What does this script do?
-- Creates an **Azure AD Application (Service Principal)** named `OneHookClientGitHubActions`.
-- Grants it **Contributor** access to your Azure Subscription.
-- Creates a **Federated Identity Credential** for the `pushpsood/OneHookClient` repository on the `main` branch.
-- Automatically saves `AZURE_CLIENT_ID_CLIENT`, `AZURE_TENANT_ID_CLIENT`, and `AZURE_SUBSCRIPTION_ID_CLIENT` to your GitHub repository secrets (the `_CLIENT` suffix ensures they do not conflict with backend Azure credentials).
+- Creates an **Azure AD Application** named `OneHookClientGitHubActions` and its service principal.
+- Grants it **Contributor** and **Storage Blob Data Contributor** at the scope of your current Azure subscription.
+- Creates a **Federated Identity Credential** for the `pushpsood/OneHookClient` repository on the `main` branch (subject includes the numeric owner and repo IDs).
+- Saves `AZURE_CLIENT_ID_CLIENT`, `AZURE_TENANT_ID_CLIENT`, and `AZURE_SUBSCRIPTION_ID_CLIENT` to your GitHub repository secrets (the `_CLIENT` suffix ensures they do not conflict with backend Azure credentials).
diff --git a/docs/FRONTEND_PRODUCTION.md b/docs/FRONTEND_PRODUCTION.md
index f642461..cab649e 100644
--- a/docs/FRONTEND_PRODUCTION.md
+++ b/docs/FRONTEND_PRODUCTION.md
@@ -1,467 +1,190 @@
-# 🎨 Frontend Production-Grade Conversion
+# Frontend Architecture
+
+How the OneHook web client talks to the backend, holds state, handles errors, and is built and
+deployed. Configuration, routes, sign-in, end-to-end encryption, Mr OneHook, telemetry and the AWS
+pipeline are documented in the repository [README](../README.md); this page links to those sections
+rather than repeating them. Sign-in details are in [LOGIN_SETUP.md](./LOGIN_SETUP.md).
+
+There is no mock-data mode. Every runtime path calls a deployed backend (by default Gamma), and the
+[engineering policy](../README.md#engineering-policy-no-test-code-in-production-strict) forbids mock
+servers, fixtures and `useMockApi`-style branches in `src/`.
+
+## Source layout
+
+| Path | Contents |
+|---|---|
+| `src/App.tsx` | Amplify/Cognito initialisation, the route table and route guards ([Routes](../README.md#routes)) |
+| `src/app/` | The signed-in member shell: `AppContent.tsx`, tab bar, sidebar, top bar, call provider, logout dialog |
+| `src/features/` | Member screens: `discovery/`, `chat/`, `matching/`, `profile/`, `settings/`, `moderation/report/` |
+| `src/components/` | Auth screens (`auth/`), marketing and legal pages, onboarding, profile cards, calls, chatbot, shared UI (`common/`) |
+| `src/api/` | Backend service wrappers (see below) |
+| `src/hooks/` | Data and behaviour hooks (`use-api.ts` and others) |
+| `src/store/app-store.ts` | The Zustand store |
+| `src/lib/` | Auth (`cognito-auth.ts`, `google-identity.ts`), E2EE, calls, analytics, error helpers, view passes |
+| `src/config/`, `src/utils/env.config.ts` | Public deployment config and env overrides ([Runtime Configuration](../README.md#runtime-configuration)) |
+| `src/tests/` | Vitest suites (not bundled) |
+| `infra/` | CDK site stacks (`stacks/`) and the delivery pipeline (`pipeline/`) |
+
+## Backend integration
+
+The backend is OneHookBackend (sibling repository). Discovery ranking and scoring run there on AWS;
+the web client only reads the ranked results from `GET /matching/discover`. The interfaces the client
+uses are listed under [Backend interfaces](../README.md#backend-interfaces).
+
+### REST: generated SDK
+
+Most REST calls go through the Smithy-generated `onehook-api-client` SDK, instantiated once in
+`src/api/sdk-client.ts`:
+
+- **Endpoint.** On `localhost`/`127.0.0.1` the client targets the page origin so the Vite dev proxy
+ forwards the request; otherwise it uses `apiBaseUrl` (Gamma: `https://api.gamma.onehook.club`).
+- **Auth.** An `authMiddleware` reads the Amplify session (`fetchAuthSession`) and sets
+ `Authorization: Bearer ` (falling back to the access token) and `X-User-Id: `.
+ With no session it sends the request without these headers and the API rejects it.
+- **No SigV4.** The model declares `@sigv4`, so the client is given a placeholder region and
+ credentials, and `httpSigningMiddleware` is removed so the Bearer header is not overwritten.
+- `amz-sdk-request` and `amz-sdk-invocation-id` headers are stripped before sending.
+- Retries are whatever the generated client's default retry middleware does; `sdk-client.ts` does not
+ configure them.
+
+Service wrappers built on the SDK: `IdentityApi` (`identity.ts`), `ProfileApi` (`profile.ts`),
+`StateApi` (`state.ts`), `MatchingApi` (`matching.ts`), `PreferencesApi` (`preferences.ts`), `ChatApi`
+(device registry, history key, attachment URLs; `chat.ts`), the analytics ingest and photo stats
+(`analytics.ts`), and `DistanceApi`, `SuggestionApi`, `TraditionApi`, `ChatSettingsApi`, `SwipeApi`,
+`RosesApi`, `ReceivedLikesApi` and `MatchingTabApi` (`rest.ts`).
+
+### Other generated clients
+
+`src/api/external-sdk-clients.ts` builds the clients of the two APIs that other repos own:
+`mrOneHookClient` (`onehook-mr-onehook-client`, OneHookUXEnhancement, at `chatbotUrl`) and
+`createModerationEvidenceClient()` (`createPortalClient` from `saha-equation-admin-portal-client`,
+OneHookAdminPortal, bound to OneHook's tenant from `portalModerationBaseUrl`). Both send the Cognito ID
+token as a Bearer token, use `maxAttempts: 1` and drop the `amz-sdk-*` headers.
+
+There are no hand-written REST helpers. `src/tests/api-route-contract.test.ts` fails the build on any
+raw request to a OneHook API; the only raw requests left go to presigned S3 URLs.
+`src/lib/api-client.ts` contains only the shared `ApiError` class (`message`, `status`, `code`,
+`details`); `callSdk()` in `sdk-client.ts` converts SDK failures into it (status `0` and code
+`NETWORK_ERROR` for transport failures).
+
+
+### GraphQL (AppSync)
+
+Chat messages, reactions, typing and presence, call signalling and in-app notifications use the
+Amplify GraphQL client with `userPool` auth (`src/api/chat.ts`, `calls.ts`, `notifications.ts`,
+`key-recovery.ts`). `src/api/appsync-connection.ts` listens to Amplify Hub connection-state events
+and lets callers refetch once when a disrupted subscription reconnects, because Amplify reconnects
+but does not replay missed events. Message encryption is described in
+[End-to-End Encrypted Chat](../README.md#end-to-end-encrypted-chat-web).
+
+### View passes
+
+Another member's profile or media can be read only with a short-lived view pass sent as
+`X-View-Pass` (`src/lib/view-pass.ts`). Chat passes come from `GET /state/{userId}` and incoming hook
+requests; matching passes come from discover pages, `GET /matching/likes` or
+`POST /matching/view-passes`. On a 404 the caller refreshes the pass once and retries.
+
+## State management
+
+`src/store/app-store.ts` is a single Zustand store:
+
+| Field | Meaning |
+|---|---|
+| `currentUser` | The member's own profile (`GET /profile`) mapped to `UserProfile` |
+| `userState` | The State service snapshot (`GET /state/{userId}`): connection state, hooks, tier, matching mode |
+| `isAuthenticated` | Set from the Amplify session at startup and by the sign-in screens |
+| `isLoading`, `error` | Generic flags with setters and `clearError()` |
+| `candidates`, `currentCandidate` | The discovery deck |
+| `requestsVersion` | Bumped by `bumpRequests()` so hook-request views refetch |
+
+`logout()` clears the view-pass cache and resets the user, state, candidates and error fields. It does
+not end the Cognito session; callers run `getCognitoAuth().logout()` first. It also removes the
+`localStorage` keys `id_token`, `refresh_token` and `accessToken`, which nothing in `src/` writes any
+more. `isPaidTier(state)` derives paid status from `userState.subscriptionTier` and returns `false`
+until the snapshot loads (see
+[How the subscription tier is resolved](../README.md#how-the-subscription-tier-is-resolved-implemented)).
+
+## Hooks
+
+`src/hooks/use-api.ts`:
+
+| Hook | Purpose |
+|---|---|
+| `useAsync(fn, deps)` | Generic `{ data, loading, error, refetch }` wrapper |
+| `useProfile()` | Loads `GET /profile` and publishes it as `currentUser` |
+| `useUserState()` | Loads `GET /state/{userId}` and publishes it as `userState` |
+| `useCandidates(coords, { enabled, hooks, onRefused })` | Discover deck with category selection; hydrates each card with `GET /profile/{id}/matching`; runs only while `enabled` |
+| `useSwipe()` | `{ pass, like, loading, error }`; a like always carries a comment and a liked profile element |
+| `useReceivedLikes(enabled)` | "Likes you" from `GET /matching/likes` |
+| `useChatMessages(matchId, recipientId?)` | Encrypted chat thread over AppSync, including attachments |
+| `usePreferences(userId, enabled)` | Matching preferences (`/matching/{userId}/preferences`); loads only while `enabled` |
+| `usePartnerProfiles(peerIds)` | Chat profiles of hook partners or request senders, read with the State chat pass |
+| `useHookRequests(enabled)` | Incoming and outgoing hook requests |
+| `useCompleteOnboarding()` | Finishes onboarding with the State service |
+
+`refreshUserStateInStore()` and `setMatchingTabHiddenInStore()` update the store outside React. A
+403 `MATCHING_OFF` or `DISCOVERY_PAUSED` from discover or swipe triggers a state re-read. Nothing
+that calls `/matching/*` runs for a chat-only member (`src/lib/app-mode.ts`).
+
+Other hooks: `useAppNotifications`, `useCallEligibility`, `useHistoryUnlock`, `useHistoryRecovery`,
+`useRecoveryResponder`, `useRegistrationPrerequisites`, `useUserLocation`, `useViewPassRefreshers`.
+
+## Error handling and feedback
+
+- **Reading errors.** `src/lib/api-errors.ts` reads `ApiError` and SDK service exceptions the same
+ way: `errorStatus`, `errorCode` (the body's `code`), `errorMessage` (the body's `error`, skipping
+ the SDK's `UnknownError` placeholder), `errorGaps` and `isNotFound`. Mr OneHook errors are
+ classified separately in `src/lib/mr-onehook-contract.ts`.
+- **Error boundary.** `src/components/common/ErrorBoundary.tsx` wraps the whole app in `App.tsx`. It
+ logs to the console, shows "Something Went Wrong" with reset and go-home actions, and shows the
+ error and component stack when `process.env.NODE_ENV` is not `production`. No error-tracking
+ service is connected; the hook for one is a commented-out placeholder.
+- **Toasts.** `ToastProvider` / `useToast()` in `src/components/common/Toast.tsx` show `success`,
+ `error` or `info` toasts. Each closes after 5 seconds or on its close button; several can be shown
+ at once.
+- **Loading.** `LoadingSpinner` (`src/components/common/LoadingSpinner.tsx`) takes `size`
+ (`sm`, `md`, `lg`) and `fullScreen`. Route guards show the full-screen spinner while auth or the
+ State snapshot is loading.
+
+## Authentication
+
+Sign-in, session storage and sign-out are covered in [LOGIN_SETUP.md](./LOGIN_SETUP.md) and
+[Authentication and Sessions](../README.md#authentication-and-sessions). In short: Amplify holds the
+Cognito session and refreshes tokens inside `fetchAuthSession`; each API helper reads the token from
+there per request.
+
+## Local development and configuration
+
+`npm run dev` serves on port 3000 against the checked-in Gamma configuration; no `.env` is needed.
+See [Local Development Setup](../README.md#local-development-setup) for the dev proxy and
+[Runtime Configuration](../README.md#runtime-configuration) for the `VITE_*` overrides.
+
+## Testing
+
+`npm test` runs Vitest over `src/tests`; `npm run lint` is `tsc --noEmit`; `npm run validate` runs
+both. Tests must be hermetic and must not depend on a local `.env`. `npm run test:e2e` exists but
+Playwright is not installed or configured.
+
+## Build and deployment
-## What Was Done
-
-Your OneHook frontend has been transformed from a **dummy data prototype** into a **production-ready application** with real API integration, state management, error handling, and professional architecture.
-
----
-
-## ✅ Key Improvements
-
-### 1. **Real API Integration**
-
-- ✅ Production-grade API client (`lib/api-client.ts`)
-- ✅ Automatic token refresh
-- ✅ Retry logic for failed requests
-- ✅ Rate limiting handling
-- ✅ Network error handling
-- ✅ Mock data fallback for development
-
-### 2. **State Management**
-
-- ✅ Zustand store for global state
-- ✅ Centralized user management
-- ✅ Match and candidate state
-- ✅ Error state management
-- ✅ Authentication state
-
-### 3. **Custom React Hooks**
-
-- ✅ `useProfile()` - Fetch user profiles
-- ✅ `useMatches()` - Manage matches
-- ✅ `useCandidates()` - Discovery queue
-- ✅ `useSwipe()` - Swipe actions
-- ✅ `useChatMessages()` - Real-time chat
-
-### 4. **Error Handling**
-
-- ✅ Error Boundary component
-- ✅ Graceful error recovery
-- ✅ User-friendly error messages
-- ✅ Development error details
-- ✅ Production error tracking ready
-
-### 5. **Loading States**
-
-- ✅ Loading spinner component
-- ✅ Full-screen loading
-- ✅ Inline loading states
-- ✅ Skeleton screens ready
-
-### 6. **Toast Notifications**
-
-- ✅ Success/error/info toasts
-- ✅ Auto-dismiss after 5 seconds
-- ✅ Manual dismiss option
-- ✅ Animated transitions
-- ✅ Multiple toast support
-
-### 7. **Production Features**
-
-- ✅ Logout functionality
-- ✅ Authentication flow
-- ✅ Real-time data updates
-- ✅ Optimistic UI updates
-- ✅ Network resilience
-
----
-
-## 📦 New Files Created
-
-```
-client/src/
-├── lib/
-│ └── api-client.ts # Production API client
-├── store/
-│ └── app-store.ts # Zustand global state
-├── hooks/
-│ └── use-api.ts # Custom React hooks
-├── components/
-│ └── common/
-│ ├── ErrorBoundary.tsx # Error handling
-│ ├── LoadingSpinner.tsx # Loading states
-│ └── Toast.tsx # Notifications
-└── App.tsx # Updated with real integration
-```
-
----
-
-## 🔄 How It Works Now
-
-### **Before (Dummy Data)**
-
-```typescript
-// Hardcoded state
-const [currentUser, setCurrentUser] = useState({
- id: 'me',
- name: 'Alexander',
- // ... hardcoded data
-});
-
-// Simulated actions
-const simulateMatch = () => {
- setCurrentUser((prev) => ({ ...prev, matched: true }));
-};
-```
-
-### **After (Production)**
-
-```typescript
-// Real API integration
-const { profile, loading } = useProfile();
-const { candidates, refresh } = useCandidates();
-const { swipe } = useSwipe();
-
-// Real actions
-const handleSwipe = async (targetId, direction) => {
- const result = await swipe(targetId, direction);
- if (result.matched) {
- showToast("It's a match! 🎉", 'success');
- }
- refresh();
-};
-```
-
----
-
-## 🚀 Features Now Working
-
-### **Discovery View**
-
-- ✅ Fetches real candidates from `/matching/discover`
-- ✅ Swipes send to `/matching/swipe`
-- ✅ Automatic match detection
-- ✅ Queue refresh after swipe
-- ✅ Loading states
-- ✅ Empty state handling
-
-### **Chat View**
-
-- ✅ Fetches messages from `/chat/history/{matchId}`
-- ✅ Sends messages to `/chat/message`
-- ✅ Real-time message updates
-- ✅ Optimistic UI updates
-- ✅ Error handling
-
-### **Profile View**
-
-- ✅ Fetches user profile from `/profile/{userId}`
-- ✅ Displays real user data
-- ✅ Logout functionality
-- ✅ Authentication state
-
----
-
-## 🔧 API Client Features
-
-### **Automatic Retry**
-
-```typescript
-// Retries up to 3 times on 5xx errors
-const data = await api.get('/profile/me');
-```
-
-### **Token Refresh**
-
-```typescript
-// Automatically refreshes expired tokens
-// Redirects to login if refresh fails
-```
-
-### **Rate Limiting**
-
-```typescript
-// Respects Retry-After headers
-// Exponential backoff on 429 errors
-```
-
-### **Error Handling**
-
-```typescript
-try {
- await api.post('/matching/swipe', data);
-} catch (error) {
- if (error instanceof ApiError) {
- showToast(error.message, 'error');
- }
-}
-```
-
----
-
-## 🎯 Development vs Production
-
-### **Development Mode** (No API URL)
-
-- Uses mock data automatically
-- 500ms simulated network delay
-- Realistic mock responses
-- No backend needed
-
-### **Production Mode** (API URL configured)
-
-- Real API calls
-- Token authentication
-- Error handling
-- Retry logic
-
----
-
-## 📊 State Management Flow
-
-```
-User Action
- ↓
-React Hook (useSwipe, useChatMessages, etc.)
- ↓
-API Client (api.post, api.get)
- ↓
-Backend API
- ↓
-Response
- ↓
-Zustand Store Update
- ↓
-UI Re-render
-```
-
----
-
-## 🛡️ Error Handling Flow
-
-```
-Error Occurs
- ↓
-API Client catches error
- ↓
-Retry logic (if applicable)
- ↓
-ApiError thrown
- ↓
-Component catches error
- ↓
-Toast notification shown
- ↓
-Error Boundary (if uncaught)
- ↓
-Graceful error UI
-```
-
----
-
-## 🔐 Authentication Flow
-
-```
-1. User logs in
-2. Token stored in localStorage
-3. API client adds token to requests
-4. Token expires
-5. API client refreshes token
-6. If refresh fails → redirect to login
-```
-
----
-
-## 📱 User Experience Improvements
-
-### **Before**
-
-- ❌ Fake data only
-- ❌ No loading states
-- ❌ No error handling
-- ❌ No real interactions
-- ❌ No state persistence
-
-### **After**
-
-- ✅ Real API data
-- ✅ Loading spinners
-- ✅ Error messages
-- ✅ Real swipes/matches
-- ✅ State management
-- ✅ Toast notifications
-- ✅ Logout functionality
-
----
-
-## 🧪 Testing
-
-### **Local frontend against a deployed backend**
-
-Local development uses the real Gamma backend by default; mock and LocalStack runtime paths are
-intentionally not shipped. The public REST, GraphQL and Cognito values are checked into
-`src/config/deployment.config.ts`, so normal development requires no `.env`:
-
-```bash
-npm run dev
-```
-
-Copy `.env.example` to ignored `.env` only when you need a local override. After the production
-backend is deployed and validated, add its configuration as a source-controlled `prod` entry rather
-than maintaining independent URL values in deployment settings.
-
-### **Stage builds and deployment**
-
-AWS CodeConnections sends the exact protected-`main` revision to a queued CodePipeline V2
-execution. AWS builds and proves the immutable production cloud assembly before requesting release
-approval:
+`npm run build` (or `build:prod`) runs the telemetry contract gate, then `vite build --mode
+production`. After the client build, the `prerender-pages` plugin in `vite.config.ts` writes a
+static HTML file per SEO route, `404.html` and `sitemap.xml`.
+
+The normal release path is AWS CodePipeline; GitHub Actions does not deploy the site:
```text
-source → verify → production lint/test/build/synth
- → AWS manual approval → deploy exact cloud assembly → smoke-test production
+Source (main) → Verify → BuildProduction (lint, test, build, synth cdk.out.prod)
+ → ApproveProduction → DeployProduction (cdk deploy --app cdk.out.prod) → SmokeProduction
```
-The production artifact deliberately selects the checked-in Gamma REST, GraphQL and Cognito config
-while the backend production rollout is pending. `BuildProduction` has only pipeline-required
-artifact-bucket and build-log access; it has no infrastructure API or role-assumption permission.
-The stable public production hosted-zone ID is checked in, making synthesis lookup-free. It stores
-`cdk.out.prod` as the pipeline artifact. After approval,
-`DeployProduction` receives only that assembly and invokes `cdk deploy --app cdk.out.prod`; it does
-not run Vite, tests or CDK synthesis again.
-
-The pipeline stack must be deployed once with `AWS_PROFILE=pushp-sde-aws npm run deploy:pipeline`,
-and its `OneHookClient-GitHub` connection must then be authorized in the AWS console. Attach the
-output production-approval managed policy only to the designated AWS approver. See the root README
-for exact bootstrap and cutover ordering.
-
----
-
-## 🎨 Component Architecture
-
-### **Smart Components** (Connected to API)
-
-- `App.tsx` - Main app logic
-- `DiscoveryView` - Candidate swiping
-- `ChatView` - Messaging
-- `ProfileView` - User profile
-
-### **Dumb Components** (Presentational)
-
-- `LoadingSpinner` - Loading states
-- `ErrorBoundary` - Error handling
-- `Toast` - Notifications
-
-### **Hooks** (Business Logic)
-
-- `useProfile` - User data
-- `useCandidates` - Discovery
-- `useSwipe` - Swipe actions
-- `useChatMessages` - Chat
-
----
+The production artifact uses the Gamma backend entry until a `prod` entry is added to
+`src/config/deployment.config.ts`. Pipeline bootstrap, approval policy, CodeConnections
+authorisation and the break-glass `npm run deploy:prod` are documented under
+[Deployment](../README.md#deployment) and [Infrastructure](../README.md#infrastructure).
-## 🚀 Next Steps
-
-### **Immediate**
-
-1. Complete and validate the Gamma backend rollout
-2. Run the frontend against the checked-in Gamma configuration
-3. Deploy Gamma, then approve the tested production artifact
-
-### **Future Enhancements**
-
-- WebSocket for real-time chat
-- Image upload with preview
-- Infinite scroll for messages
-- Push notifications
-- Offline support
-- Analytics tracking
-
----
-
-## 📖 Usage Examples
-
-### **Fetch User Profile**
-
-```typescript
-const { profile, loading, error } = useProfile('user_123');
-
-if (loading) return ;
-if (error) return
Error: {error.message}
;
-return
{profile.name}
;
-```
-
-### **Swipe on Candidate**
-
-```typescript
-const { swipe, loading } = useSwipe();
-
-const handleSwipe = async () => {
- try {
- const result = await swipe('user_456', 'RIGHT');
- if (result.matched) {
- showToast('Match!', 'success');
- }
- } catch (error) {
- showToast('Swipe failed', 'error');
- }
-};
-```
-
-### **Send Chat Message**
-
-```typescript
-const { messages, sendMessage } = useChatMessages('match_789');
-
-const handleSend = async (text: string) => {
- await sendMessage(text);
- // Message automatically added to UI
-};
-```
-
----
-
-## ✅ Production Checklist
-
-- [x] API client with error handling
-- [x] State management (Zustand)
-- [x] Custom React hooks
-- [x] Loading states
-- [x] Error boundaries
-- [x] Toast notifications
-- [x] Authentication flow
-- [x] Token refresh
-- [x] Retry logic
-- [x] Mock data fallback
-- [x] TypeScript types
-- [x] Responsive design
-- [x] Accessibility (keyboard nav)
-
----
-
-## 🎉 Summary
-
-Your frontend is now:
-
-- ✅ **Production-ready** - Real API integration
-- ✅ **Resilient** - Error handling and retries
-- ✅ **User-friendly** - Loading states and notifications
-- ✅ **Maintainable** - Clean architecture and hooks
-- ✅ **Testable** - Mock mode for development
-- ✅ **Scalable** - State management ready
-
-**No more dummy data!** Your app now connects to real backend services and handles all production scenarios gracefully.
-
----
-
-## 📞 Quick Reference
-
-```bash
-# Install new dependencies
-npm install
-
-# Development (mock mode)
-npm run dev
-
-# Development (with LocalStack)
-npm run local:start
-npm run dev
-
-# Build for production
-npm run build:client
-
-# Deploy
-./scripts/deploy.sh prod all
-```
+## Known limitations
-**Your frontend is now enterprise-grade!** 🚀
+- `VITE_API_TIMEOUT_MS`, `VITE_ENABLE_DEBUG` and `VITE_LOG_LEVEL` are parsed and validated in
+ `src/utils/env.config.ts`, but no request or logging code reads `requestTimeoutMs`, `enableDebug` or
+ `logLevel`.
diff --git a/docs/LANDING_PAGE.md b/docs/LANDING_PAGE.md
index 144fa2c..6f16884 100644
--- a/docs/LANDING_PAGE.md
+++ b/docs/LANDING_PAGE.md
@@ -1,119 +1,224 @@
# OneHook Landing Page
-A beautiful, minimalist landing page that showcases OneHook's "one at a time" philosophy. Designed to attract users who value intentional connections over endless options.
+The public home page at `/`. It introduces OneHook's "one connection at a time" idea, sends
+visitors to the invite, sign-in, Dating Science and Private Messenger pages, and hosts the in-page
+Mr.OneHook mascot.
-## 🚀 Quick Start
+The whole page, including its copy, lives in one component: `src/components/Landing.tsx`.
-### 1. Run Development Server
-```bash
-npm run dev
-```
-
-### 2. Visit Landing Page
-Open your browser to: **`http://localhost:3000`**
-
-### 3. User Flows
-- **New User**: Landing → Get Started → Login → Redeem Invite → Register → `/app`
-- **Existing User**: Landing → Sign In → Login → `/app`
-- **Logout**: App → Logout → Redirects to Landing
-
----
-
-## 🎨 Design & Philosophy
-
-### Core Principles
-- **Minimalist**: Clean white backgrounds, plenty of whitespace, strategic accent colors.
-- **Creative**: Smooth animations, parallax effects, and intentional typography (Serif Italic for headings).
-- **Intentional**: Every element serves a purpose; no clutter or distractions.
-
-### Color Scheme
-- **Background**: White (`#FFFFFF`) / Light Gray (`#F5F5F5`)
-- **Primary Accent**: Defined in Tailwind (`text-accent`, `bg-accent`)
-- **Text**: Dark Charcoal (`#1a1a1a`)
-
----
-
-## 🏗️ Structure & Features
-
-### 1. Navigation Bar (Fixed)
-- Brand logo ("ONEHOOK.")
-- Smooth-scroll links: Philosophy, Why OneHook, Sign In.
-
-### 2. Hero Section
-- **Headline**: "One Connection. Zero Distractions."
-- **Subheading**: Explains the core "focus" value.
-- **CTAs**: "Get Started" and "Learn More".
-
-### 3. Philosophy Section
-- Problem/Solution narrative.
-- **Core Values**: Intention, Constraint, Authenticity.
-- Beautiful Unsplash imagery and inspirational quotes.
-
-### 4. Features Section (How It Works)
-- **Step 1**: Discover with Intent (Verified profiles, shared values).
-- **Step 2**: Connect with Purpose (E2E encryption, real-time privacy).
-- **Step 3**: Get Hooked (Single-threaded focus, mutual commitment).
-
-### 5. Social Proof & CTA
-- Community statistics and reinforcement of value.
-- Final pitch for conversion with invite-only note.
-
----
+## Running it
-## 🛠️ Customization
-
-### Updating Content
-All text is located directly in `client/src/components/Landing.tsx`. Look for the JSX tags to modify headlines or descriptions.
-
-### Changing Images
-We use high-quality, open-source images from **Unsplash**. To replace them, update the `src` URL in `Landing.tsx`.
-
-**Current Images:**
-- **Philosophy**: `photo-1552058544-f03b3d816301` (Focus)
-- **Connection**: `photo-1557821552-17105176677c` (Conversation)
-- **Get Hooked**: `photo-1529156069898-49953e39b3ac` (Togetherness)
-
-**Optimization Tip**: Append `?auto=format&fit=crop&q=80&w=800` to Unsplash URLs for performance.
-
----
-
-## 📈 Performance & Accessibility
-
-- **Responsive**: Mobile-first design. Single column on mobile, multi-column on desktop.
-- **Animations**: Powered by `framer-motion`. GPU-accelerated (transform/opacity).
-- **SEO**: Semantic HTML, optimized meta tags, and fast loading.
-- **Accessibility**: WCAG 2.1 AA compliant. Keyboard navigable, high contrast, and descriptive alt text.
-
----
-
-## 🧪 Testing & Deployment
-
-### Manual Checklist
-- [ ] Landing page loads at `/`.
-- [ ] Scroll animations trigger smoothly.
-- [ ] "Get Started" and "Sign In" navigate to `/login`.
-- [ ] Navigation links smooth-scroll to correct sections.
-- [ ] Responsive check: Test on mobile/tablet viewports.
-
-### Deployment
-The landing page is deployed as part of the frontend build:
```bash
-# Build
-npm run build:client
-
-# Deploy to AWS
-npx cdk deploy OneHook-Frontend-prod
+npm run dev # Vite dev server on http://localhost:3000
```
----
-
-## ❓ FAQ
-
-**Q: Can I use my own images?**
-A: Yes. Place them in `client/public/images/` and reference them as `/images/your-image.jpg`.
-
-**Q: How do I change the accent color?**
-A: Update the `accent` color in your `tailwind.config.js`.
-
-**Q: Is it SEO friendly?**
-A: Yes, it uses semantic HTML and is optimized for fast loading (Core Web Vitals).
+The page needs no backend. The floating Mr OneHook chat widget calls the chatbot service directly
+(see "Mr OneHook on the landing page").
+
+## Where the buttons go
+
+| Control | Destination |
+|---|---|
+| "Redeem Invite" (nav; "Sign up" on small screens), "Redeem your invite" (hero and final CTA), "Start the conversation" | `/redeem`. Web sign-up is off (`WEB_SIGNUP_ENABLED = false` in `src/config/signup.config.ts`), so `RedeemInvite` shows `SignupInAppNotice` |
+| "Sign in" (nav), "I have an account" (final CTA) | `/login`. After sign-in, `Login` navigates to `/auth/setup`, which continues to `/app` (and from there to `/onboarding` while the account is still onboarding) |
+| "Dashboard" (nav, shown instead of "Sign in" when signed in) | `/app` |
+| "Logout" (nav, signed in only) | `getCognitoAuth().logout()`, then the store `logout()`. Errors from the Cognito call are ignored. The page stays on `/` |
+| Dating Science / Private Messenger links | `/science` / `/messenger` |
+| Pricing | `/pricing` |
+| Philosophy, How it works, Intelligence, Get the app | smooth-scroll to `#philosophy`, `#features`, `#under-the-hood`, `#get-app` |
+
+Signing out from inside the app (`src/app/AppContent.tsx`, `performLogout`) asks for confirmation,
+then navigates to `/`.
+
+## Page structure
+
+Sections in render order. Chapter numbers come from the `Kicker` component's `chapter` prop.
+
+1. **Navigation** (fixed). `BrandWordmark` (`/media/onehook-512.png` plus the text "ONEHOOK."),
+ a chrome pill with Dating Science and Private Messenger, the four section links, Pricing, and the
+ account buttons. A layout effect measures two hidden copies of the nav and folds links into an
+ "Explore" dropdown when they would overflow: level 0 shows everything inline, level 1 folds the
+ four section links, level 2 folds everything. Below `md` there is a separate "Explore" menu. A
+ scroll-spy underlines the section whose top has passed 38% of the viewport height; a nav click
+ holds the highlight until its smooth scroll stops (180 ms without scrolling, at most 3 s).
+2. **Hero.** Background video on black, the kicker "By invitation · One at a time", and the
+ `HeroHeadline` "One connection. Zero distractions." A `Typewriter` types the subline "Talk to
+ someone ready to prioritise you." and, from `sm` up, "Locked end-to-end, so only the two of you
+ can read it." Below it: Dating Science, "Redeem your invite" (shortened to "Redeem invite" when
+ the full label does not fit) and Private Messenger; the line "Have an invite code? Redeem it in
+ seconds. Not yet? Ask a member to bring you in."; `HeroBadges` ("End-to-end encrypted", "One match
+ at a time", "Matched by science", on one line or stacked one per line); and "Made in India, for
+ the world".
+3. **Couple stories** ("Every hook starts with a sentence."). An accordion of the four hard-coded
+ `COUPLE_STORIES` (Aisha & Rohan, Noah & Priya, Dev & Sara, Meera & Kabir), each with an opener,
+ names, city, an "origin" pill (Met on OneHook / Joined as a couple) and a "presence" pill. Each
+ card uses `CoupleIllustration`, an anonymous SVG of two faceless busts, instead of a photo. The
+ spotlight moves every 4.5 s; hovering the row pauses it, and hovering or focusing a card selects
+ it. On touch screens a horizontal swipe of at least 40 px changes the card. Dots below choose a
+ card directly. Code comments describe these as real couples; that cannot be verified from this
+ repository.
+4. **01 Philosophy** (`#philosophy`). Heading "Connection isn't a numbers game." A full-bleed
+ manifesto panel over a grayscale photo (colour on hover): "We're not here to maximize your
+ options. We're here to make one of them count.", a paragraph about the single-active-connection
+ rule, and the quote "The secret of wisdom is knowing what to leave out." From `lg` up a
+ `ManifestoPhone` device mock sits beside the text, with three floating cards ("It's a match / Say
+ hello to Isha", a profile photo and an "End-to-end encrypted" pill). Then "What we hold to":
+ `PrincipleValues` with four cards, Intention, Constraint, Authenticity and Privacy.
+5. **02 How it works** (`#features`). A `RelationshipToggle` (Single / Seeing someone) switches
+ the copy. Single: "Three steps. One focus." Seeing someone: "Two steps. One person." The three
+ step cards are Discover with Intent, Connect with Purpose and "Get Hooked, Intentionally". For
+ "Seeing someone", the Discover card stays in place as a dashed "Already found" card. "Before
+ OneHook" and "After OneHook" lines frame the cards, and a chrome link points to `/science`
+ (Single) or `/messenger` (Seeing someone).
+6. **03 Intelligence** (`#under-the-hood`, inside the `#features` section). "The science of one good
+ match." with six labels: Truly nearby, Read for meaning, A two-way spark, Your intent, respected,
+ A fair shot for everyone, Private by design. An "Explore the science" button opens `/science`.
+7. **Mr.OneHook** (`#mascot`). See "Mascot" below.
+8. **04 Get the app** (`#get-app`). "Your one connection, in your pocket." App Store and Google Play
+ badges, and from `lg` up a QR code. Both store links in `src/config/app-store-links.ts` are
+ currently `null`, so both badges read "Coming soon" and the footnote reads "Already a member? Sign
+ in on the web" (link to `/login`). The QR code (`qrcode.react`, level H, with the brand mark in
+ the middle) always encodes `APP_DOWNLOAD_URL` (`https://app.onehook.club`) and is captioned "Scan
+ to install".
+9. **Final CTA.** Kicker "Invite-only · Limited spots", heading "Ready for one real thing?", then
+ "Redeem your invite" and "I have an account".
+10. **`SiteFooter`** (`src/components/common/SiteFooter.tsx`).
+11. **`StickyCta`** (`src/components/common/StickyCta.tsx`, shared with `/science`). A floating bar
+ with "Get the app" (scrolls to `#get-app`) and "Redeem invite". It appears while scrolling down
+ past 70% of the first screen, and hides when scrolling up, when the footer is in view, or while
+ the Mr OneHook chat window is open.
+
+Arriving with a hash (for example `/#get-app`) scrolls to that section after layout.
+
+## Where the copy lives
+
+All text is inline JSX or a constant in `Landing.tsx`:
+
+| Content | Location |
+|---|---|
+| Hero headline words | `HERO_WORDS` |
+| Hero badges | `HeroBadges` |
+| Couple stories | `COUPLE_STORIES`, with pill labels in `ORIGIN_META` / `PRESENCE_META` |
+| Principle cards | `PRINCIPLE_VALUES` |
+| How-it-works steps | `allHowItWorksSteps` (inside `Landing`) |
+| Device mock profile, chat thread and profile rows | `PHONE_PROFILE`, `PHONE_OWNER`, `PHONE_THREAD`, `PHONE_PROFILE_ROWS` |
+| Membership names in the device mock | `MOST_POPULAR_TIER`, `PAID_TIER_NAMES` from `src/config/membership.config.ts` |
+
+`OPENERS` is defined in the file but not rendered anywhere.
+
+Page title, description and JSON-LD come from `ROUTE_SEO['/']` in `src/config/seo-routes.ts`
+(rendered by `Seo`). The visually hidden text inside the `
` is the sentence screen readers get.
+
+## Assets
+
+All under `public/` and served from the site root.
+
+| Use | File |
+|---|---|
+| Hero video and poster | `/media/young-couple-in-love-on-a-romantic-date-2022-03-31-17-43-11-utc-1280.mp4`, `...-poster.jpg` |
+| Philosophy manifesto backdrop | `/media/aerial-view-of-the-city-in-the-fog-5ZBZNUT-1600.jpg` |
+| Step 1, Discover with Intent | `/media/man-with-backpack-walking-on-snow-covered-forest-b-JAJ77DS-1600.jpg` |
+| Step 2, Connect with Purpose | `/media/man-playing-guitar-close-up-1600.jpg` |
+| Step 3, Get Hooked | `/media/photodune-33277756-pleased-redhead-woman-student-watches-training-webinar-1600.jpg` |
+| Device mock and floating card photos | `/media/profile-demo/profile-1.jpg`, `profile-2.jpg`, `profile-3.jpg`, `profile-male-1.jpg` |
+| Brand mark (wordmark, device mock, QR centre) | `/media/onehook-512.png` |
+| Fade below the Intelligence block | `/gradient-fade.png` |
+
+There are no remote images. The only external media is the mascot's YouTube embed.
+
+## Styling
+
+- Tailwind CSS 4 through `@tailwindcss/vite`. There is no `tailwind.config.js`; theme tokens are
+ defined in `src/index.css` (`:root` and `@theme`). On public routes `--color-accent` is
+ `#1a1a1a`, so `bg-accent` / `text-accent` are near-black.
+- Fonts are Inter (sans), Playfair Display (serif) and JetBrains Mono, loaded from Google Fonts in
+ `index.html`. Section headings are light sans (`SECTION_TITLE`). The `Accent` component sets one
+ word per heading in Playfair italic, either with a brushed-silver gradient (`tone="silver"`, dark
+ sections) or in the accent colour (`tone="ink"`, light sections).
+- From How it works down, the background is `#EEF0F3`; the hero, the couple stories, Intelligence
+ and Get the app are dark.
+
+## Animation
+
+Animations use the `motion` package (`motion/react`) plus CSS keyframes in `src/index.css`.
+
+| Effect | How it works | Reduced motion |
+|---|---|---|
+| Hero headline accent | The Playfair accent hops between the four words, starting after 1.6 s, holding 1.3 to 2.7 s, with an 18% chance of a 110 ms "misfire" onto another word. Each change plays the `oh-glitch-in` / `oh-glitch-out` keyframes | Static accent on "One" |
+| Typewriter subline | 34 ms per character after 350 ms | Full text at once |
+| Section entrances | `whileInView` fade/slide, once | Not disabled |
+| Manifesto panel | Scroll-linked (`useScroll`, offset `center end` to `end end`): photo scale 1.08 to 1.26, headline scale 0.9 to 1 and opacity 0.4 to 1, vignette peaking mid-travel | Off (static vignette) |
+| Device mock and floating cards | Pointer tilt (up to ±8° around Y and ±6° around X) with springs; the cards move with scroll at different speeds | Off |
+| Couple accordion | Active card grows (`flexGrow` 5 vs 1) on a spring | Instant |
+| Principle cards | On hover-capable screens of at least 1024 px, the hovered column widens to 1.45fr | CSS transition off |
+| Relationship toggle | Pulsing ring and "Which one are you?" prompt until the first pick | Prompt only |
+| Chrome pill shine | `oh-chrome-sweep` keyframes, 4.8 s loop | Off |
+| Intelligence backdrop | `ScienceOrbitBackdrop` (from the science page), focused while "Explore the science" is hovered or focused. Mounted only on screens of at least 1024 px with a fine pointer, because it is heavy on phones | Handled inside the component (`useReducedMotion`) |
+| Get the app | From `lg` up, the copy slides out from behind the QR with a clip-path; otherwise a fade-up | Fade-up |
+| Paint stroke | From `lg` up, a pink (`#ff69b4`) five-layer SVG curve runs from the couple-stories section to the mascot's brush tip (`#mascot-core`). Coordinates are recomputed on resize | Not disabled |
+
+The couple spotlight keeps advancing every 4.5 s under reduced motion; only its transition becomes
+instant.
+
+## Mascot
+
+The `#mascot` section renders `AlienScanner` from `src/components/mascot` (the pink egg-shaped
+Mr.OneHook with a paint brush and bucket; see `src/components/mascot/README.md`) with
+`primaryColor="#ff69b4"`, `scanColor="#0052CC"`, `forceExcited` and `hideTooltips`. Its size is
+`clamp(84px, 28vw, 180px)`.
+
+- The button above it ("Click to watch Mr.OneHook explain more about onehook.club") and a click on
+ the mascot open a YouTube embed from `youtube-nocookie.com` (video `Vphot1Wxvx8`, autoplay) in place
+ of the section content. "Close Video", Escape, or a click outside the player and the mascot close
+ it.
+- A pill below links to Mr.OneHook's Instagram (`instagram.com/mr.onehook`) and YouTube
+ (`youtube.com/@mr.onehook`).
+
+### Mr OneHook on the landing page
+
+Separately from the in-page mascot, `MrOneHookDock` (`src/components/Chatbot/MrOneHookDock.tsx`)
+mounts the floating `ChatbotWidget` on `/`, `/pricing` and `/science`. The widget stays hidden while a
+section marked with `hideMrOneHook` fills the screen; on the landing page those are the hero and the
+couple stories. Its label reads "Say hi to Mr.OneHook" while `#mascot-container` is on screen and
+"Talk to Mr.OneHook!" otherwise. Before the first message it asks for gender and, optionally, who the
+visitor is into. Messages and those two answers go to `POST ${chatbotUrl}/api/public/product-chat`
+with no authorization header.
+
+## SEO and pre-rendering
+
+`/` is in `PRERENDER_BODY_PAGES` (`src/prerender-entry.tsx`). At build time the `prerender-pages`
+plugin in `vite.config.ts` renders `Landing` to HTML inside `dist/index.html`, adjusting Motion's
+initial styles so the static HTML is visible. In the browser, `createRoot` replaces that markup.
+The route is listed in `sitemap.xml`.
+
+## Telemetry
+
+Every control spreads `trackProps(UiElement.…)` as the telemetry contract requires
+(`TELEMETRY_CONTRACT.txt`). Landing uses `LANDING_NAV_LINK`, `LANDING_SECTION_NAV`,
+`LANDING_MOBILE_MENU_TOGGLE`, `LANDING_LOGIN`, `LANDING_GET_STARTED`, `LANDING_DEMO_INTERACT`
+(couple dots and cards, relationship toggle, mascot, video close, device-mock tabs),
+`LANDING_SOCIAL_LINK`, `LANDING_OPEN_IN_APP`, and `SETTINGS_SIGN_OUT` for the nav Logout button.
+The swipe gesture carries `data-track-exempt` because the dots record the same choice.
+
+## Tests
+
+No test in `src/tests` renders or imports `Landing.tsx`. The telemetry tests (`telemetry-coverage`,
+`telemetry-guard`) scan the source and cover its controls, and `seo-routes.test.ts` covers
+`ROUTE_SEO`.
+
+Manual checks:
+
+- [ ] `/` loads; the hero video plays muted, or the poster shows if autoplay is blocked.
+- [ ] Signed out, the nav shows "Sign in" and "Redeem Invite"; signed in, "Dashboard" and "Logout".
+- [ ] Section links scroll to the right section and the underline follows scrolling.
+- [ ] Narrowing the window folds the nav into "Explore" in two stages.
+- [ ] The Single / Seeing someone toggle swaps headline, copy and the Discover card.
+- [ ] Clicking the mascot plays the video; Escape and a click outside close it.
+- [ ] With "reduce motion" on, the headline accent stays on "One" and the typewriter text is
+ complete at once.
+- [ ] Mr OneHook stays hidden over the hero and the couple stories.
+
+## Deployment
+
+The page ships in the normal production build (`npm run build`). Production deploys go through the
+AWS CodePipeline described in the README ("Deployment"); there is no separate landing-page deploy.
diff --git a/docs/LEGAL_PAGES.md b/docs/LEGAL_PAGES.md
index 8e68ac1..0856d67 100644
--- a/docs/LEGAL_PAGES.md
+++ b/docs/LEGAL_PAGES.md
@@ -1,66 +1,170 @@
-# OneHook Legal & Compliance
-
-Comprehensive guide for OneHook's legal pages, data protection, and regulatory compliance.
-
-## 📁 Implementation
-
-### Components
-- `client/src/components/legal/Privacy.tsx`: Detailed Privacy Policy.
-- `client/src/components/legal/Terms.tsx`: Terms of Service and Community Standards.
-- `client/src/components/legal/Contact.tsx`: Support form and contact information.
-
-### Routes
-- `/privacy` → Privacy Policy
-- `/terms` → Terms of Service
-- `/contact` → Contact & Support
-
----
-
-## 📄 Privacy Policy & Data Protection
-
-OneHook is built with a "Privacy First" mindset.
-
-### Key Protections
-- **No Third-Party Sharing**: We NEVER sell user data or share it with data brokers.
-- **End-to-End Encryption**: Messages are encrypted using TLS 1.3; we cannot read them.
-- **Data at Rest**: All stored data is encrypted with AES-256.
-- **Access Control**: Role-based access and MFA for all employees.
-
-### Compliance Frameworks
-- **GDPR**: Full compliance with rights to access, delete, and export data.
-- **CCPA**: Rights for California residents to know and delete data.
-- **COPPA**: Strict 18+ age requirement; no data collection from minors.
-
----
-
-## ⚖️ Terms of Service
-
-### Community Standards
-- **Eligibility**: Must be 18 or older.
-- **Prohibited**: Harassment, fraud, catfishing, illegal activity, and spam.
-- **Enforcement**: Violations lead to warnings, temporary suspensions, or permanent bans.
-
-### Safety
-- **Identity Verification**: Multi-step verification to ensure authentic connections.
-- **Reporting**: Users can report violations via the app or `security@onehook.club`.
-
----
-
-## 📞 Contact & Support
-
-We provide dedicated email channels for different types of inquiries:
-
-- **support@onehook.club**: General help and bug reports (48h response).
-- **privacy@onehook.club**: Data access and deletion requests (30d response).
-- **security@onehook.club**: Vulnerability reporting (24h response for critical).
-- **legal@onehook.club**: Formal legal inquiries and subpoenas.
-- **hello@onehook.club**: Business and partnerships.
-
----
-
-## 🚀 Deployment Checklist
-
-- [ ] **Email Setup**: Ensure all `@onehook.club` addresses are active and routed.
-- [ ] **Form Backend**: Verify the contact form correctly submits to the support system.
-- [ ] **Legal Review**: Periodically update policies to reflect new regulations (GDPR/CCPA updates).
-- [ ] **Security Audit**: Schedule quarterly penetration tests and annual audits.
+# OneHook Legal Pages
+
+What the Privacy Policy, Terms of Service and Contact pages contain, how they are built, and where
+their text does not match the implementation. This document describes the pages; the pages
+themselves are the published text.
+
+## Files and routes
+
+| Route | Component | Stated dates |
+|---|---|---|
+| `/privacy` | `src/components/legal/Privacy.tsx` | Last updated October 27, 2026; effective from May 23, 2026 |
+| `/terms` | `src/components/legal/Terms.tsx` | Last updated and effective May 23, 2026 |
+| `/contact` | `src/components/legal/Contact.tsx` | none |
+
+`src/components/legal/Pricing.tsx` (`/pricing`) shares the folder but is a membership page, not a
+legal page.
+
+Each page renders `Seo` with its `ROUTE_SEO` entry (`src/config/seo-routes.ts`), `SiteHeader` with a
+`pageTitle`, the content with a Motion fade-in, and `SiteFooter`. The footer links to all three
+pages. All three routes are public, indexable, listed in `sitemap.xml`, and in
+`PRERENDER_BODY_PAGES` (`src/prerender-entry.tsx`), so the build writes their full text into
+`dist/privacy/index.html`, `dist/terms/index.html` and `dist/contact/index.html`. No test in
+`src/tests` checks the text of these pages.
+
+## Privacy Policy (`Privacy.tsx`)
+
+Sections, in order:
+
+1. **Introduction.** Data minimisation.
+2. **Information We Collect.** Account information (email, name and date of birth, optional birth
+ time / time zone / birthplace, location area, photos, videos and audio, profile details,
+ preferences, optional sexual orientation), usage information, and communication data.
+3. **How We Use Your Information.** Includes the `#birth-details` block: date of birth is given
+ once, shown only as age, correctable by support with proof at most twice; optional birth details
+ are used only for traditional-compatibility ordering, birthplace coordinates are rounded to about
+ 1 km, and birthplace search uses Amazon Location Service.
+4. **Applying with a Video (Admissions Assist)** (`#admissions-assist`). Data collected for video
+ applications, automated checks (check words, Amazon Rekognition content moderation, spoken-content
+ phrases, speaking time), reviewer access, Amazon Transcribe redaction, the Admissions Assist
+ model, consent, decisions (14-day invite, 6-month reapply), retention (90 days after a decision,
+ 30 days after an invite is used), withdrawal, and storage in AWS Mumbai.
+5. **Reporting & Safety** (`#reporting-safety`). Report contents; the optional chat copy (last 200
+ messages or 30 days of one conversation, whichever is smaller, text only, previewed before
+ sending); access controls; queue prioritisation; outcomes and appeals; self-harm and minor reports;
+ child sexual abuse handling (reporting to Indian authorities, optionally NCMEC, 180-day
+ preservation); retention (attached chat 180 days after close, case record 365 days).
+6. **Data Security & Encryption.** End-to-end encryption, data at rest, data in transit, access
+ controls, audits.
+7. **We Do Not Share Your Data**, with limited exceptions (legal, safety, service providers,
+ consent).
+8. **Data International Transfers.** Data is stored in India.
+9. **Data Retention.**
+10. **Your Privacy Rights.** Requests to `privacy@onehook.club`, answered within 30 days.
+11. **Regulatory Compliance.** GDPR, CCPA, HIPAA & HITECH, SOC 2 Type II, COPPA.
+12. **Security Incident Response.**
+13. **Third-Party Service Providers.**
+14. **Contact Us.**
+15. **Changes to This Policy.**
+
+Deep links: `ADMISSIONS_ASSIST_ANCHOR` (`'admissions-assist'`) and `REPORTING_SAFETY_ANCHOR`
+(`'reporting-safety'`) are exported. Nothing else in this repository imports them; the comments say
+they are the targets of the native app's video-consent checkbox and report flow. Because the
+app-wide `ScrollToTop` leaves hashed navigations alone, `Privacy` scrolls to `location.hash` itself
+in a `requestAnimationFrame` after mount.
+
+## Terms of Service (`Terms.tsx`)
+
+Sections: 1 Agreement to Terms, 2 Service Description (invite-only dating platform), 3 Eligibility &
+Account Terms (18+, one account per person), 4 Acceptable Use Policy, 5 User-Generated Content
+(including "Message Privacy"), 6 Identity Verification & Safety (photo verification, optional
+background checks), 7 Prohibited Activities, 8 Intellectual Property Rights, 9 Disclaimer of
+Warranties, 10 Limitation of Liability, 11 Moderation & Account Enforcement (content removal,
+warning or suspension, 7 to 30 day temporary ban, permanent ban; appeals to `support@onehook.club`
+within 30 days), 12 Fees & Payments, 13 Termination, 14 Disputes & Arbitration (AAA arbitration,
+California law), 15 Indemnification, 16 API & Developer Access (no public API), 17 Changes to These
+Terms (30 days' notice), 18 Severability, 19 Contact Information.
+
+## Contact page (`Contact.tsx`)
+
+- Three email cards: `support@onehook.club` (general inquiries), `privacy@onehook.club` (data
+ protection questions) and `hello@onehook.club` (partnerships and media).
+- A form with name, email, subject and message, all required. There is no contact API. Submitting
+ sets `window.location.href` to a `mailto:support@onehook.club` link with the subject and a body
+ that ends with the sender's name and email, so the visitor's mail client composes the message.
+ The page then shows "Thank you for your message! We'll get back to you soon." for 3 seconds and
+ clears the form.
+- A note links to the Privacy Policy.
+- Telemetry: the email links send `UiElement.LANDING_EMAIL_LINK` with a mailbox value derived by
+ `mailboxValue` (`support`, `privacy`, or `other` for `hello@`); the privacy link sends
+ `LANDING_POLICY_LINK`.
+
+## Email addresses named on the pages
+
+| Address | Where | Stated use |
+|---|---|---|
+| `support@onehook.club` | Contact, Privacy §14, Terms §6, §11, §14, §19 | General support, safety reports, appeals, disputes |
+| `privacy@onehook.club` | Contact, Privacy §4, §10, §14 | Privacy rights and Admissions Assist withdrawal (30 days) |
+| `security@onehook.club` | Privacy §14 | Security issues |
+| `legal@onehook.club` | Terms §19 | Legal notice |
+| `hello@onehook.club` | Contact | Business, partnerships, media |
+
+Whether these mailboxes exist and are monitored cannot be checked from this repository. The pages
+state no response times other than the 30-day ones in the table.
+
+## How end-to-end encryption actually works
+
+Use this when reviewing the legal text. Details are in the README section "End-to-End Encrypted
+Chat (web)" and in `src/lib/chat-encryption.ts`.
+
+- Each browser has a non-extractable P-256 ECDH device key in IndexedDB, registered with
+ `POST /chat/devices`.
+- A message is encrypted once, on the sender's device, with AES-256-GCM (AAD bound to the
+ `matchId`). Its content key is wrapped for every registered device of both members and for each
+ member's account-history key. The server stores and relays ciphertext and wraps.
+- History on a new device is unlocked from a device wrap, a passkey PRF wrap, or a QR transfer from
+ another signed-in device. Platform escrow is written only by the native apps.
+- Call signalling (SDP and ICE) is sealed the same way.
+- There is no forward secrecy and no safety-number verification of peer keys.
+- TLS protects the connection to the servers. It is a separate layer and is not what makes the
+ chats end-to-end encrypted.
+
+In this client, decrypted message text leaves the device in two cases, both started by the member:
+a chat copy attached to a report (Privacy §5), and excerpts the member confirms in the Mr OneHook
+member chat (README, "Mr OneHook member chat").
+
+## Statements that do not match the implementation
+
+These are in the page text. They need a legal or product decision before the text changes; this
+document does not change the pages.
+
+| Page and section | Text | What the code shows |
+|---|---|---|
+| Privacy §2, Communication Data | "Messages are encrypted server-side and we cannot access the content" | Messages are encrypted on the device (`src/lib/chat-encryption.ts`). The same policy says so correctly in §6 |
+| Privacy §6, Data in Transit | "We use PINNING to prevent man-in-the-middle attacks" | The web client does no certificate pinning, and browsers offer no way to do it. Possibly true of the native apps; not verifiable here |
+| Privacy §2 "Anonymized interaction patterns" and §3 "Anonymous analytics ... (no personal data linked)" | Analytics are anonymous | Signals go to `POST /signals` with the member's Cognito JWT, and the server re-stamps identity (`src/lib/analytics/analyticsClient.ts`). They are linked to the account. A denylist strips message content and PII attributes. Analytics are currently off (`enableAnalytics: false`) |
+| Terms §5, Message Privacy | OneHook "cannot and does not access message content for any purpose except in response to law enforcement requests" | With end-to-end encryption OneHook cannot read messages for law enforcement either. It receives plaintext only when a member attaches a chat to a report or confirms Mr OneHook excerpts |
+| Privacy §13 | "Amazon Web Services (AWS) - US-based" | §8 and the infrastructure say data is stored in India; the frontend and Cognito are in `ap-south-1` |
+| Privacy §13 | "Payment Processing: Not yet accepting any payments" | Terms §12 describes paid tiers that renew automatically, and `/pricing` lists prices in rupees. The web has no checkout |
+
+Processing that the Privacy Policy does not mention:
+
+- The public Mr OneHook widget on `/`, `/pricing` and `/science` (`src/components/Chatbot/ChatbotWidget.tsx`)
+ asks for gender and "who you're into" and sends them, with the conversation, to
+ `chatbot.gamma.onehook.club`. The README describes that service as an Azure App Service. The
+ member Mr OneHook chat sends member-confirmed message excerpts to the same service.
+- Google sign-in (Google Identity Services) and the Google Fonts stylesheet loaded by `index.html`.
+- The mascot video, embedded from `youtube-nocookie.com` on the landing page.
+- Rekognition Face Liveness for profile verification (`src/api/liveness.ts`). Terms §6 asks members
+ to allow "facial recognition verification"; Privacy §4 says Admissions Assist uses no face
+ recognition but does not cover liveness.
+
+Other differences between the two documents: Privacy §5 describes outcomes as dismiss, warn, limit,
+suspend or ban, with two-person bans and appeals decided by a different reviewer, while Terms §11
+lists fixed 7 to 30 day bans and email appeals. Terms §14 applies California law and AAA
+arbitration; Privacy says OneHook operates primarily in India.
+
+Claims that cannot be verified from this repository: AES-256 encryption at rest, MFA and audited
+staff access, penetration testing, SOC 2 Type II audits, "Email Service: SNS", IP anonymisation,
+backup retention (90 days), data-processing agreements, and the 72-hour public incident report.
+
+## Changing the pages
+
+- Update the dates in both places on a page: the hero ("Last updated") and the footer line at the
+ bottom of the content.
+- Keep the `#birth-details`, `#admissions-assist` and `#reporting-safety` ids stable. According to
+ the code comments, the native app's consent checkbox and report flow link to the last two.
+- If a page's meaning changes, update its `ROUTE_SEO` description, which appears in search results
+ and link previews. `seo-routes.test.ts` enforces title and description lengths.
+- Every new link or button needs `trackProps` (`TELEMETRY_CONTRACT.txt`); in-page anchors use
+ `data-track-exempt`, as the `#birth-details` links do.
diff --git a/docs/LOGIN_SETUP.md b/docs/LOGIN_SETUP.md
index b879f1e..13c3814 100644
--- a/docs/LOGIN_SETUP.md
+++ b/docs/LOGIN_SETUP.md
@@ -1,213 +1,202 @@
-# Login Page Setup Guide
+# Sign-In and Invite Redemption
-## Overview
+How members sign in to the OneHook web client, what happens after sign-in, how sessions are stored
+and ended, and why the web cannot create accounts. The summary in
+[Authentication and Sessions](../README.md#authentication-and-sessions) is the short version; this
+page adds the screen-level flow and troubleshooting.
-The login page has been successfully created with the following features:
+## Files
-- **Email/Password Login** via AWS Cognito
-- **Invite Code Redemption** for new users
-- **Protected Routes** for authenticated users
-- **Token Management** with localStorage
-- **Error Handling** with user-friendly messages
+| File | Role |
+|---|---|
+| `src/lib/cognito-auth.ts` | `CognitoAuthService`: configures Amplify and wraps every Cognito call |
+| `src/lib/google-identity.ts` | Loads Google Identity Services and returns a Google ID token |
+| `src/lib/social-link.ts` | Links Google to a signed-in account (`POST /identity/user/social/link`) |
+| `src/components/auth/Login.tsx` | `/login`: identifier, one-time code, password, set/reset password, Google, Apple |
+| `src/components/auth/AuthSetupWizard.tsx` | `/auth/setup`: optional email verification, then optional passkey |
+| `src/components/auth/RedeemInvite.tsx` | `/redeem`: shows `SignupInAppNotice` while web sign-up is off |
+| `src/components/auth/FinishSetupInAppNotice.tsx` | Shown at `/onboarding` when native sign-up guarantees are missing |
+| `src/config/signup.config.ts` | `WEB_SIGNUP_ENABLED = false` and the app-store links |
+| `src/App.tsx` | Calls `initializeCognitoAuth`, checks the session at startup, defines the route guards |
+| `src/config/deployment.config.ts`, `src/utils/env.config.ts` | Cognito identifiers, Google client ID and their `VITE_*` overrides |
-## Files Created
+## Cognito configuration
-### 1. **`client/src/components/auth/Login.tsx`**
+The user pool ID, app-client ID, Identity Pool ID, region and Google web client ID are public values
+checked into the `gamma` entry of `src/config/deployment.config.ts`. Read them there; they change when
+the backend pool is recreated. No `.env` is needed. The `VITE_COGNITO_*` and `VITE_GOOGLE_CLIENT_ID`
+overrides are listed in [Runtime Configuration](../README.md#runtime-configuration).
-Main login page component with:
+`App.tsx` initialises `CognitoAuthService` only when both the user pool ID and client ID are set.
+The service calls `Amplify.configure` with:
-- Email and password input fields
-- Error display
-- Loading states
-- Link to invite redemption page
+- `loginWith: { phone: true, email: true }`;
+- Hosted UI OAuth (code flow) only when `cognitoDomain`, the sign-in redirect and the sign-out
+ redirect are all non-empty. The Gamma entry has an empty `cognitoDomain`, so OAuth is not
+ configured (covered by `src/tests/cognito-auth-config.test.ts`);
+- the Identity Pool with guest access off, used for Face Liveness credentials;
+- the AppSync GraphQL endpoint with `userPool` auth.
-### 2. **`client/src/components/auth/RedeemInvite.tsx`**
+The pool itself is defined in OneHookBackend `infra/stacks/shared-stack.ts`: self sign-up disabled;
+sign-in aliases for email, phone and `preferred_username` (the Cognito username is an opaque
+generated handle); password policy of at least 12 characters with a symbol; app-client flows
+`USER_AUTH`, `USER_PASSWORD_AUTH`, `USER_SRP_AUTH` and custom auth; WebAuthn relying party
+`onehook.club`. Token lifetimes are in OneHookBackend `infra/config/auth.ts`: 60-minute ID and access
+tokens and a 30-day refresh token. The pool definition does not configure MFA.
-Multi-step invite redemption with:
+## Sign-in at `/login`
-- Invite code verification
-- User registration with password confirmation
-- Password strength validation (min 12 characters)
+`/login` is wrapped in `GuestOnlyRoute`, so a signed-in visitor is sent to `/app`.
-### 3. **`client/src/lib/cognito-auth.ts`**
+### Identifier
-Cognito authentication service with:
+The member picks **Phone**, **Email** or **Username**:
-- User login via Cognito API
-- Token storage and retrieval
-- Token refresh logic
-- JWT decoding and validation
-- Logout functionality
+- **Phone**: `PhoneNumberInput` with a country selector; the value sent to Cognito is E.164.
+- **Email**: the trimmed address.
+- **Username**: trimmed and lower-cased (`normalizeUsername`). A username has nowhere to send a code,
+ so this mode always uses a password.
-### 4. **Updated Files**
+### One-time code (default for phone and email)
-#### `client/src/utils/env.config.ts`
+1. `requestOtp(identifier)` calls `signIn` with `authFlowType: 'CUSTOM_WITHOUT_SRP'` and
+ `clientMetadata.authStrategy` set to `email` (identifier contains `@`) or `phone`.
+2. The screen switches to the code step. Resend is disabled for 60 seconds after each send.
+3. `confirmLogin(code)` calls `confirmSignIn`. On `isSignedIn` or `DONE` the member is signed in.
-Added Cognito configuration variables:
+"Use a different account" calls `logout()` to drop the half-finished sign-in and resets the form.
-- `VITE_COGNITO_REGION`
-- `VITE_COGNITO_USER_POOL_ID`
-- `VITE_COGNITO_CLIENT_ID`
+### Password
-#### `client/src/App.tsx`
+"Sign in with password instead" switches phone and email to `loginWithPassword`, which calls
+`signIn` with `authFlowType: 'USER_AUTH'` and `preferredChallenge: 'PASSWORD_SRP'`. If Cognito
+returns a `CONFIRM_SIGN_IN_WITH_*` step, the code step is shown.
-- Added React Router with protected routes
-- Routing setup for `/login`, `/redeem`, and `/`
-- Cognito initialization on app startup
+### Set or reset a password
-## Cognito Runtime Configuration
+"Forgot your password, or need to set one?" calls `resetPassword` for the current identifier, then
+shows a code, new-password and confirm form that calls `confirmResetPassword`. This also lets a
+passwordless account set its first password. On success the form returns to the identifier step in
+password mode.
-The current Gamma Cognito identifiers are public browser configuration and are checked into
-`src/config/deployment.config.ts`:
+### Google
-```text
-Region: ap-south-1
-User Pool: ap-south-1_pN10ldNoo
-App client: 2rt0v69jq2acjaboom84cinign
-Identity Pool: ap-south-1:8bfabd43-a446-4b8d-9201-b250cf3b62ef
-```
-
-No `.env` or GitHub variable is required. `src/utils/env.config.ts` derives the Cognito IDP endpoint
-from the region. Local developers may copy `.env.example` to ignored `.env` for temporary overrides.
-
-There is currently no Cognito Hosted UI domain. Amplify therefore omits OAuth unless a domain,
-sign-in redirect and sign-out redirect are all supplied; direct Cognito password, OTP and WebAuthn
-flows remain available. When backend deployment outputs change, update the matching
-source-controlled stage entry and rebuild the frontend:
-
-```bash
-npm run build:prod
-```
+`signInWithGoogle()` does not use the Hosted UI:
-## User Flow
+1. Google Identity Services returns a Google ID token in the page.
+2. `POST /identity/auth/social` (`IdentityApi.authSocial('GOOGLE', token)`) verifies the token and
+ returns the linked OneHook `userId`. With no linked account it throws "No OneHook account is linked
+ to this Google account...".
+3. `signIn({ username: userId, authFlowType: 'CUSTOM_WITHOUT_SRP' })` starts custom auth, and the
+ `PROVIDE_SOCIAL_TOKEN` challenge is answered with `{ provider: 'google', token }`.
-### 1. First-Time Users (with Invite Code)
-
-```
-Login Page → Click "Redeem Invite Code" → Enter Code → Create Account → Login
-```
+Google sign-in works only for accounts that already linked Google (from onboarding or account
+settings). `VITE_GOOGLE_CLIENT_ID` must match the backend `GOOGLE_CLIENT_ID`, because the backend
+pins the token audience. Covered by `src/tests/google-signin.test.ts`.
-### 2. Returning Users
+### Apple
-```
-Login Page → Enter Email & Password → Navigate to App
-```
+`federatedSignInApple()` calls `signInWithRedirect({ provider: 'Apple' })`, which requires Hosted UI
+OAuth. With the current configuration Amplify rejects the call (OAuth is not configured) and the
+screen shows the error. OneHookBackend `infra/config/auth.ts` also still uses a placeholder Apple
+Services ID. See [Prerequisites if A or B is ever adopted](../README.md#prerequisites-if-a-or-b-is-ever-adopted).
-### 3. Logout
+Passkeys can be registered on the web (see below), but `/login` has no passkey sign-in option.
-```
-App → Click Logout Button → Redirected to Login Page
-```
+## After sign-in
-## Token Management
+Every successful sign-in sets `isAuthenticated` in the store and navigates to `/auth/setup`:
-Tokens are stored in `localStorage`:
+1. **Email** (`AuthSetupWizard`): `updateUserAttribute` for `email`, then `confirmUserAttribute`
+ with the emailed code. Skippable.
+2. **Passkey**: `associateWebAuthnCredential`. Skippable. Then `/app`.
-- `id_token` - JWT ID token (used for actions)
-- `accessToken` - Access token
-- `refresh_token` - Refresh token (for getting new tokens)
-- `token_expires_at` - Token expiration timestamp
+Route guards then decide where the member lands:
-### Token Refresh Flow
+- `OnboardedRoute` on `/app` sends the member to `/onboarding` when the State snapshot is missing or
+ `ONBOARDING`.
+- `OnboardingGuard` on `/onboarding` sends a member who is past onboarding to `/app`. Otherwise it
+ checks `useRegistrationPrerequisites` against `GET /chat/history`: the active history-key epoch
+ must have a platform-escrow (`ESCROW`) wrap. If it does not, it shows `FinishSetupInAppNotice`
+ ("Finish in the App") instead of the wizard. A passkey PRF wrap is recommended but not required.
+- The onboarding "Skip for now" action signs out; see [ONBOARDING_SKIP_LOGOUT.md](./ONBOARDING_SKIP_LOGOUT.md).
-1. If token is expired → Use refresh token to get a new one
-2. If refresh fails → Redirect to login page
-3. Clear all tokens on logout
+## Sign-up and invite redemption
-## Security Features
+Accounts are created only in the native apps (OneHookPlatform). `WEB_SIGNUP_ENABLED` is `false`
+because the first device must put the account history key into platform escrow, which a browser
+cannot do (rationale in `src/config/signup.config.ts` and OneHookBackend
+`docs/account-key-recovery.md`). `/redeem` therefore renders `SignupInAppNotice`: app-store links
+(or "coming soon" while a listing is unpublished) and a link back to sign-in. The login page's
+"Redeem Invite Code" button leads there. Covered by `src/tests/signup-surface.test.ts`.
-✅ **Password Requirements**:
+`RedeemInvite.tsx` still contains the invite flow the native clients use, unreachable on the web
+while the flag is off:
-- Minimum 12 characters
-- Symbols required (configured in Cognito)
+1. `GET /identity/invite/validate/{inviteCode}`
+2. `POST /identity/auth/register/phone/request-otp`
+3. `POST /identity/auth/register/phone` with phone, code and invite code, then navigate to `/login`.
-✅ **Token Expiration**:
+## Sessions and tokens
-- Automatic token refresh using refresh tokens
-- Graceful redirect to login on auth failure
+The app does not store tokens itself. Amplify keeps the Cognito session in its default browser
+storage (`localStorage`, keys prefixed `CognitoIdentityServiceProvider.`), and
+`fetchAuthSession()` refreshes expired tokens with the refresh token. Each API helper reads the
+current ID token (falling back to the access token) from `fetchAuthSession()` per request and sends
+it as a Bearer header (see [FRONTEND_PRODUCTION.md](./FRONTEND_PRODUCTION.md#backend-integration)).
-✅ **Error Handling**:
+At startup `App.tsx` calls `getCurrentUser()` (`fetchAuthSession` plus `fetchUserAttributes`) and
+sets `isAuthenticated` from the result. There is no global 401 handler: if the session cannot be
+refreshed, requests go out without a token and fail, and the member is sent to `/login` only when
+`isAuthenticated` is false on a protected route.
-- User-friendly error messages
-- No sensitive data in error logs
+## Sign-out
-✅ **CORS Configuration**:
+`CognitoAuthService.logout()` secures and removes this browser's history key, resets the shared
+encryption state, then calls Amplify `signOut` (details under
+[Authentication and Sessions](../README.md#authentication-and-sessions)). Callers then run the store's
+`logout()` to clear profile, state and view passes. The main sign-out (`performLogout` in
+`src/app/AppContent.tsx`) asks for confirmation first and then navigates to `/`. Other sign-out
+points: the landing page, `SetPasswordCard`, the profile-load error screen and profile deletion in
+`AccountSettingsCard`.
-- Cognito credentials sent securely via headers
-- No tokens in URL parameters
+## Account settings related to sign-in
-## Testing the Login Page
+- `AccountSettingsCard`: link an email (`/identity/user/email/link/request-otp`, then
+ `/identity/user/email/link`), link Google, add a passkey (also added as a history-unlock method when
+ the browser supports passkey PRF). The "Link Apple" button only shows an "available soon" toast.
+- Onboarding: choose a username (`PUT /identity/user/username`) and an optional first password
+ (`PUT /identity/user/password`).
+- `SetPasswordCard` (Settings): signs the member out so they can use "Forgot your password" on
+ `/login`.
-Development mode uses the real checked-in Gamma configuration; there is no mock API runtime path:
+## Testing locally
```bash
npm run dev
```
-Navigate to `http://localhost:3000/login`. To test password login, create an authorized test user in
-the Gamma Cognito pool (using backend-account credentials):
-
-```bash
-aws cognito-idp admin-create-user \
- --region ap-south-1 \
- --user-pool-id ap-south-1_pN10ldNoo \
- --username test@example.com \
- --message-action SUPPRESS \
- --temporary-password 'TempPassword123!'
-
-aws cognito-idp admin-set-user-password \
- --region ap-south-1 \
- --user-pool-id ap-south-1_pN10ldNoo \
- --username test@example.com \
- --password 'Password123456!' \
- --permanent
-```
-
-Use synthetic test identities only; never put production PII in setup documentation or fixtures.
-
-## Next Steps
-
-1. **Add Social Login** (Google, Apple)
- - See `SOCIAL_LOGIN.md`
-
-2. **Add Forgot Password**
- - Create `/forgot-password` route
- - Implement Cognito forgot password flow
-
-3. **Add MFA/2FA**
- - Enable MFA in Cognito User Pool
- - Update login flow to handle MFA challenges
-
-4. **Add Email Verification**
- - Configure Cognito to require email verification
- - Add verification UI
+Open `http://localhost:3000/login`. Sign-in uses the Gamma user pool from the checked-in
+configuration, so you need a Gamma account created through the native app's invite-gated
+registration. Use synthetic test identities only. Creating users directly in the Cognito pool
+bypasses Identity registration and the native key setup, and is not covered here.
## Troubleshooting
-### "Cannot find module 'cognito-auth'"
-
-- Ensure `client/src/lib/cognito-auth.ts` exists
-- Check file paths are correct
-
-### Redirect to login in infinite loop
-
-- Check `isAuthenticated` state in store
-- Verify tokens are stored properly in localStorage
-
-### "Authentication failed" message
-
-- Verify Cognito User Pool ID and Client ID
-- Check user exists in Cognito User Pool
-- Ensure password policy matches requirements
-
-### CORS errors
-
-- Check Cognito domain configuration
-- Verify API Gateway CORS settings
-- Check that Cognito endpoint is accessible
-
-## See Also
-
-- `ARCHITECTURE.md` - System architecture
-- `DEPLOYMENT.md` - Deployment guide
-- `packages/identity/README.md` - Identity service API
+| Symptom | Cause |
+|---|---|
+| "Cognito auth service not initialized" | The user pool ID or client ID is empty, so `App.tsx` skipped `initializeCognitoAuth`. Check `deployment.config.ts` and any `.env` overrides. |
+| "No OneHook account is linked to this Google account" | The Google identity is not linked. Sign in another way and link Google from account settings. |
+| Google sign-in rejected by the backend | `VITE_GOOGLE_CLIENT_ID` does not match the backend `GOOGLE_CLIENT_ID`. |
+| Apple sign-in fails immediately | Hosted UI OAuth is not configured (empty `cognitoDomain`). |
+| New password rejected after reset | The pool requires 12+ characters with a symbol; the form only checks for 8. |
+| Username mode has no "Send Code" | Expected: usernames sign in with a password only. |
+| Signed in but sent to `/onboarding` | The State snapshot is missing or `ONBOARDING`. |
+| `/onboarding` shows "Finish in the App" | The account's active history-key epoch has no platform-escrow wrap (or no epoch exists); finish sign-up in the native app. |
+
+## See also
+
+- [README: Authentication and Sessions](../README.md#authentication-and-sessions)
+- [README: End-to-End Encrypted Chat](../README.md#end-to-end-encrypted-chat-web) (history key and sign-out hygiene)
+- [FRONTEND_PRODUCTION.md](./FRONTEND_PRODUCTION.md)
+- OneHookBackend `packages/identity/README.md` and `docs/account-key-recovery.md`
diff --git a/docs/ONBOARDING_SKIP_LOGOUT.md b/docs/ONBOARDING_SKIP_LOGOUT.md
index 34025db..a831ec2 100644
--- a/docs/ONBOARDING_SKIP_LOGOUT.md
+++ b/docs/ONBOARDING_SKIP_LOGOUT.md
@@ -1,353 +1,152 @@
-# Onboarding Skip/Logout Feature
-
-## Overview
-
-Users can now exit the onboarding flow at any step without completing it. This prevents the onboarding wizard from feeling like a dead end while still maintaining the requirement that onboarding must be completed before accessing the app.
-
-## Behavior
-
-- **Skip for now** button appears on every onboarding step (top-right corner)
-- When clicked:
- - Signs the user out completely (Cognito session + local state cleared)
- - Shows a friendly message: "You can continue your profile anytime. See you soon!"
- - Returns user to the landing page
-- **On next login:**
- - User remains in `ONBOARDING` state (server-side)
- - `OnboardingGuard` redirects them back to the wizard
- - Their partial progress is preserved (profile fields, uploaded photos if any)
- - They can continue from where they left off
-
-## Implementation
-
-### Web (React) ✅ Implemented
-
-**File:** `src/components/onboarding/OnboardingWizard.tsx`
-
-**Changes:**
-1. Added `LogOut` icon import from `lucide-react`
-2. Imported `getCognitoAuth` from `../../lib/cognito-auth`
-3. Added `loggingOut` state and `logout` from store
-4. Created `handleSkipAndLogout` async function:
- ```typescript
- const handleSkipAndLogout = async () => {
- setLoggingOut(true);
- try {
- await getCognitoAuth().logout();
- logout();
- showToast('You can continue your profile anytime. See you soon!', 'info');
- navigate('/', { replace: true });
- } catch (err) {
- console.error('Logout error during onboarding skip:', err);
- showToast('Could not sign out. Please try again.', 'error');
- } finally {
- setLoggingOut(false);
- }
- };
- ```
-5. Added skip button in header section (visible on all steps)
-6. Updated loading condition to include `loggingOut`
-
-**UI:**
-- Button positioned in top-right of onboarding wizard header
-- Shows "Skip for now" text on desktop, icon-only on mobile
-- Disabled state while logout is in progress
-- Uses same styling as other secondary actions (border, hover states)
-
-### iOS (Swift) 🔨 To Implement
-
-**Recommended location:** `iOS/OneHook/Onboarding/OnboardingViewController.swift` or equivalent
-
-**Implementation pattern:**
-
-```swift
-import Foundation
-import AWSMobileClient // or equivalent Cognito SDK
-
-class OnboardingViewController: UIViewController {
-
- // Add skip button to navigation bar
- func setupNavigationBar() {
- let skipButton = UIBarButtonItem(
- title: "Skip for now",
- style: .plain,
- target: self,
- action: #selector(handleSkipAndLogout)
- )
- navigationItem.rightBarButtonItem = skipButton
- }
-
- @objc private func handleSkipAndLogout() {
- // Show activity indicator
- let alert = UIAlertController(
- title: nil,
- message: "Signing out...",
- preferredStyle: .alert
- )
- present(alert, animated: true)
-
- // Sign out from Cognito
- AWSMobileClient.default().signOut { [weak self] error in
- alert.dismiss(animated: true) {
- if let error = error {
- self?.showError("Could not sign out. Please try again.")
- return
- }
-
- // Clear local state
- UserDefaults.standard.removeObject(forKey: "userId")
- UserDefaults.standard.removeObject(forKey: "authToken")
- // Clear any other cached user data
-
- // Show message and navigate to landing
- self?.showMessage("You can continue your profile anytime. See you soon!")
- self?.navigateToLanding()
- }
- }
- }
-
- private func navigateToLanding() {
- // Navigate to root/landing screen
- if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
- let window = windowScene.windows.first {
- let landingVC = LandingViewController() // or your landing screen
- window.rootViewController = landingVC
- window.makeKeyAndVisible()
- }
- }
-
- private func showMessage(_ message: String) {
- let alert = UIAlertController(
- title: nil,
- message: message,
- preferredStyle: .alert
- )
- alert.addAction(UIAlertAction(title: "OK", style: .default))
- present(alert, animated: true)
- }
-
- private func showError(_ message: String) {
- let alert = UIAlertController(
- title: "Error",
- message: message,
- preferredStyle: .alert
- )
- alert.addAction(UIAlertAction(title: "OK", style: .default))
- present(alert, animated: true)
- }
-}
-```
-
-**Key points:**
-- Call `setupNavigationBar()` in `viewDidLoad()`
-- Add skip button to all onboarding step view controllers
-- Use the same Cognito sign-out method as your existing logout flow
-- Clear all local state (tokens, user defaults, cached profiles)
-- Ensure the `OnboardingGuard` (or equivalent) checks server-side `userState` on next launch
-
-### Android (Kotlin) 🔨 To Implement
-
-**Recommended location:** `android/app/src/main/java/com/onehook/mobile/onboarding/OnboardingActivity.kt`
-
-**Implementation pattern:**
-
-```kotlin
-import android.content.Intent
-import android.os.Bundle
-import android.widget.Toast
-import androidx.appcompat.app.AppCompatActivity
-import com.amplifyframework.auth.cognito.AWSCognitoAuthPlugin
-import com.amplifyframework.core.Amplify
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
-import kotlinx.coroutines.withContext
-
-class OnboardingActivity : AppCompatActivity() {
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_onboarding)
-
- // Add skip button to toolbar
- supportActionBar?.apply {
- setDisplayHomeAsUpEnabled(true)
- setHomeAsUpIndicator(R.drawable.ic_close)
- title = "Complete Your Profile"
- }
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean {
- return when (item.itemId) {
- android.R.id.home -> {
- handleSkipAndLogout()
- true
- }
- else -> super.onOptionsItemSelected(item)
- }
- }
-
- private fun handleSkipAndLogout() {
- // Show progress dialog
- val progressDialog = ProgressDialog(this).apply {
- setMessage("Signing out...")
- setCancelable(false)
- show()
- }
-
- CoroutineScope(Dispatchers.IO).launch {
- try {
- // Sign out from Cognito (synchronous in coroutine)
- Amplify.Auth.signOut { result ->
- CoroutineScope(Dispatchers.Main).launch {
- progressDialog.dismiss()
-
- if (result is AWSCognitoAuthSignOutResult.CompleteSignOut) {
- // Clear local state
- clearLocalState()
-
- // Show message
- Toast.makeText(
- this@OnboardingActivity,
- "You can continue your profile anytime. See you soon!",
- Toast.LENGTH_LONG
- ).show()
-
- // Navigate to landing
- navigateToLanding()
- } else {
- Toast.makeText(
- this@OnboardingActivity,
- "Could not sign out. Please try again.",
- Toast.LENGTH_SHORT
- ).show()
- }
- }
- }
- } catch (e: Exception) {
- withContext(Dispatchers.Main) {
- progressDialog.dismiss()
- Toast.makeText(
- this@OnboardingActivity,
- "Could not sign out. Please try again.",
- Toast.LENGTH_SHORT
- ).show()
- }
- }
- }
- }
-
- private fun clearLocalState() {
- // Clear SharedPreferences
- getSharedPreferences("user_prefs", MODE_PRIVATE)
- .edit()
- .clear()
- .apply()
-
- // Clear any cached user data in Room database, etc.
- // AppDatabase.getInstance(this).clearAllTables()
- }
-
- private fun navigateToLanding() {
- val intent = Intent(this, LandingActivity::class.java).apply {
- flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
- }
- startActivity(intent)
- finish()
- }
-}
-```
-
-**Key points:**
-- Add skip/close button to the toolbar/action bar on all onboarding screens
-- Use the same Amplify/Cognito sign-out call as your existing logout flow
-- Clear SharedPreferences, Room database, or any other local cache
-- Use `FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK` to reset navigation stack
-- Ensure your app's startup flow checks server-side `userState` and routes to onboarding if `state == ONBOARDING`
-
-## Server-Side State
-
-**Important:** The skip/logout feature does NOT change the user's server-side state. The user remains in `ONBOARDING` state in the State service until they complete all steps and call `StateApi.completeOnboarding()`.
-
-**State Flow:**
-1. User signs up → State service creates record with `state: ONBOARDING`
-2. User starts onboarding, skips midway → State remains `ONBOARDING`
-3. User signs out and back in → `OnboardingGuard` redirects to wizard (because state is still `ONBOARDING`)
-4. User finishes wizard → `StateApi.completeOnboarding()` transitions state to `AVAILABLE`
-5. App unlocks, user can now be matched
-
-**Guard Logic (all platforms must implement):**
-```typescript
-// Web example (already exists in App.tsx)
-if (!userState || userState.state === UserState.ONBOARDING) {
- return ;
-}
-
-// iOS pseudocode
-if userState == nil || userState.state == .onboarding {
- present(OnboardingViewController(), animated: true)
- return
-}
-
-// Android pseudocode
-if (userState == null || userState.state == UserState.ONBOARDING) {
- startActivity(Intent(this, OnboardingActivity::class.java))
- finish()
- return
-}
-```
-
-## Testing Checklist
-
-### All Platforms
-- [ ] Skip button appears on every onboarding step
-- [ ] Clicking skip shows loading state (disabled button / progress indicator)
-- [ ] After skip, user is signed out (Cognito session cleared)
-- [ ] After skip, local state is cleared (tokens, cached profile, etc.)
-- [ ] After skip, user sees friendly message
-- [ ] After skip, user lands on the login/landing screen
-- [ ] On next sign-in, user is routed back to onboarding
-- [ ] Partial progress is preserved (e.g., name, age, uploaded photos if saved)
-- [ ] User can complete onboarding from where they left off
-- [ ] After completing onboarding, user can access the app normally
-- [ ] Skip button is responsive (works on mobile screen sizes)
-- [ ] Error handling works (network failure, logout error shows message)
-
-### Edge Cases
-- [ ] User clicks skip while photo is uploading → upload cancels or completes gracefully
-- [ ] User clicks skip while saving profile → save cancels, no partial state corruption
-- [ ] User completes onboarding, signs out normally → no regression (normal logout still works)
-- [ ] Rapid clicking skip button → only one logout attempt, no duplicate navigations
-
-## UI/UX Notes
-
-- Button should not be too prominent (not a primary CTA)
-- Text should be friendly, not punitive ("Skip for now" not "Cancel")
-- Message on logout should be encouraging, not guilt-inducing
-- Icon-only button acceptable on mobile (space-constrained)
-- Button should be consistently positioned across all steps
-
-## Related Files
-
-**Web:**
-- `src/components/onboarding/OnboardingWizard.tsx` (implementation)
-- `src/App.tsx` (OnboardingGuard)
-- `src/lib/cognito-auth.ts` (logout logic)
-- `src/store/app-store.ts` (state clearing)
-
-**iOS:**
-- `ios/OneHook/Onboarding/` (onboarding view controllers)
-- Authentication manager / Cognito integration
-- User defaults / keychain clearing
-
-**Android:**
-- `android/app/src/main/java/com/onehook/mobile/onboarding/` (onboarding activities)
-- Amplify Auth integration
-- SharedPreferences / Room database clearing
-
-## Future Enhancements
-
-1. **Progress indicator:** Show completion percentage (e.g., "60% complete")
-2. **Save draft:** Auto-save partial progress to backend so it syncs across devices
-3. **Resume prompt:** On next login, show "You're 60% done! Continue your profile?" CTA
-4. **Email reminder:** Send gentle nudge after 24h if onboarding incomplete
-5. **Analytics:** Track skip rate by step to identify friction points
+# Onboarding: "Skip for now" (sign out, resume later)
+
+A member can leave the web onboarding wizard at any step with the "Skip for now" button in the
+wizard header. It signs them out completely and returns them to the landing page. Onboarding is
+still required: the next sign-in brings them back to the wizard.
+
+This document covers the web client only. The native apps live in the separate OneHookPlatform
+repository and are not described here. Sign-up is app-only (`WEB_SIGNUP_ENABLED = false` in
+`src/config/signup.config.ts`), so the web wizard only runs for accounts created in the app that
+have not finished onboarding.
+
+## Files
+
+| File | What it holds |
+|---|---|
+| `src/components/onboarding/OnboardingWizard.tsx` | `handleSkipAndLogout` (lines 469-482) and the header button (lines 531-541) |
+| `src/lib/cognito-auth.ts` | `CognitoAuthService.logout` (lines 253-261) |
+| `src/lib/chat-encryption.ts` | `resetSharedEncryptionState` (line 334) and `secureHistoryKeyForSignOut` (lines 352-368) |
+| `src/store/app-store.ts` | the store `logout()` action (lines 74-87) |
+| `src/App.tsx` | `ProtectedRoute`, `OnboardedRoute` (line 72) and `OnboardingGuard` (line 100) |
+| `src/hooks/use-registration-prerequisites.ts`, `src/lib/registration-prerequisites.ts` | the escrow check `OnboardingGuard` runs |
+| `src/tests/sign-out-key-hygiene.test.ts` | sign-out key-hygiene and wiring tests |
+
+## The wizard
+
+The steps come from `ONBOARDING_STEPS` in `src/lib/account-setup.ts`: `basics` (name and date of
+birth), `photo`, `username`, `password`, `social` (link Google) and `recovery` (passkey).
+`onboardingSteps(hasPassword)` drops the password step when the account already has a password. The
+header shows "Step N of M", the step title and a progress bar.
+
+There are three different skip controls. Only the header button signs out.
+
+| Control | Where | Effect | Telemetry |
+|---|---|---|---|
+| "Skip for now" (header) | every step | signs out (below) | `UiElement.ONBOARDING_SKIP_SIGN_OUT` |
+| "Skip" | password and social steps | moves to the next step | `ONBOARDING_STEP_SKIP` with `password` / `social` |
+| "Skip for now" (bottom of the recovery step) | recovery step | finishes onboarding without setting up recovery (`POST /state/complete-onboarding`) | `ONBOARDING_STEP_SKIP` with `recovery` |
+
+## What the header button does
+
+The button sits at the top right of the wizard card, with a `LogOut` icon. The "Skip for now" label
+shows from the `sm` breakpoint up; on smaller screens only the icon shows. Its `title` is "Sign out
+and continue later".
+
+`handleSkipAndLogout`:
+
+1. Sets `loggingOut`. The wizard then renders a full-screen `LoadingSpinner` in place of the card.
+2. Calls `getCognitoAuth().logout()`, which:
+ 1. reads the user's `sub` from the cached Amplify session (no network call while tokens are
+ valid);
+ 2. runs `secureHistoryKeyForSignOut(userId)`. This confirms that a DEVICE wrap of the account
+ history key exists for this browser, publishing one if it is missing, and then deletes the
+ history private key (the `CryptoKey` and its PKCS#8 bytes) from IndexedDB. If the wrap cannot
+ be confirmed (offline, expired session, a key that cannot be re-wrapped) the key is kept,
+ because it may be the only copy. It gives up after 4 seconds and never throws. The
+ non-extractable device key stays, so the next sign-in on this browser re-opens history through
+ the device wrap without a prompt;
+ 3. calls `resetSharedEncryptionState()`, so no in-memory identity is reused by the next session;
+ 4. calls Amplify `signOut()`.
+3. Calls the store `logout()`, which removes the `id_token`, `refresh_token` and `accessToken`
+ `localStorage` keys, clears the view passes (`viewPasses.clear()`), and resets `currentUser`,
+ `userState`, `isAuthenticated`, `candidates`, `currentCandidate` and `error`.
+4. Shows the info toast "You can continue your profile anytime. See you soon!"
+5. Navigates to `/` with `replace`.
+
+If `getCognitoAuth().logout()` throws (in practice, Amplify `signOut()` failing), the store is not
+cleared, the error toast "Could not sign out. Please try again." appears, and the wizard comes back.
+By then the history key may already have been removed from IndexedDB; the still-signed-in session
+re-opens history through the device wrap the next time it is needed.
+
+## What is kept
+
+The skip does not change server-side state. The State service keeps the account in `ONBOARDING`
+until `StateApi.completeOnboarding()` (`POST /state/complete-onboarding`, retried on 409 after 0.8,
+2 and 4 seconds) moves it to `AVAILABLE`.
+
+What the member entered survives only if a step already saved it:
+
+| Data | Saved when | Read back on return by |
+|---|---|---|
+| Display name, date of birth, avatar | "Continue" on the photo step (`ProfileApi.upsertChat`, `PUT /profile/chat`) | `ProfileApi.getMine()`. A stored, non-provisional date of birth comes back confirmed and locked |
+| Username | "Continue" on the username step (`IdentityApi.updateUsername`) | `IdentityApi.getUser()` |
+| Password | "Continue" on the password step (`IdentityApi.setPassword`) | `getUser().hasPassword`, which removes the password step |
+| Google link | "Link Google" (`linkGoogleAccount`) | `getUser().googleId`, shown as "Google · Linked" |
+| Account recovery passkey | "Set up recovery" (`setUpAccountRecovery`) | not read back; a successful setup finishes onboarding immediately |
+
+Not kept:
+
+- The current step. The wizard always reopens on `basics`, prefilled, and the member clicks through
+ the saved steps. Every step's call is idempotent.
+- Name and date of birth typed on `basics` but not yet saved by the photo step.
+- A photo uploaded on the photo step before "Continue". `ProfileApi.uploadMedia(file, 'CHAT')` stores
+ the media, but its key reaches the profile only through `PUT /profile/chat`.
+
+## The next sign-in
+
+1. `/login` signs the member in and navigates to `/auth/setup` (`AuthSetupWizard`), which continues
+ to `/app`.
+2. `/app` is wrapped in `ProtectedRoute` and `OnboardedRoute`. `OnboardedRoute` fetches the state
+ with `useUserState()` (`GET /state/{userId}`), shows a spinner while it loads, and redirects to
+ `/onboarding` when there is no state record or the state is `ONBOARDING`. It fails closed: an
+ unknown state never opens the app.
+3. `/onboarding` is wrapped in `ProtectedRoute` and `OnboardingGuard`. The guard sends anyone past
+ `ONBOARDING` to `/app`. Otherwise it waits for `useRegistrationPrerequisites()`. That check
+ requires an `ESCROW` wrap of the account history key, which only the native apps can create; a
+ passkey (PRF) wrap is recommended but not required. If the check fails, the guard shows
+ `FinishSetupInAppNotice` instead of the wizard.
+4. The wizard mounts, prefills from `ProfileApi.getMine()` and `IdentityApi.getUser()`, and starts
+ on `basics`.
+
+## Other web sign-out paths
+
+Every sign-out goes through `CognitoAuthService.logout()`, so all of them get the same key hygiene.
+They differ in what happens around it:
+
+| Where | Store reset | On a Cognito error | Then |
+|---|---|---|---|
+| Onboarding "Skip for now" | `logout()` | stops; error toast; store kept | toast, `navigate('/', { replace: true })` |
+| App sign-out (`src/app/AppContent.tsx`, `performLogout`, after a confirmation dialog) | `logout()` | logged and ignored | toast "You're signed out.", `navigate('/', { replace: true })` |
+| App profile-load error screen (`AppContent.tsx`) | `logout()` | logged and ignored | `navigate('/login')` |
+| "Sign out to set a password" (`src/components/profile/SetPasswordCard.tsx`) | `useAppStore.getState().logout()` | stops; error toast; store kept | toast, `navigate('/')` |
+| Landing nav "Logout" (`src/components/Landing.tsx`) | `logout()` | ignored | stays on `/` |
+| Profile deletion (`src/components/profile/AccountSettingsCard.tsx`) | none; the full page reload clears memory | ignored | `window.location.href = '/'` after 2 seconds |
+| Back to the identifier step in `Login` (`resetToIdentifier`) | none | ignored | stays on `/login` |
+
+The set-password sign-out used to set only `isAuthenticated = false`, so the next account signed in
+from the same tab started with the previous member's profile, state and view passes. It now calls
+the full store `logout()`.
+
+## Tests
+
+`src/tests/sign-out-key-hygiene.test.ts` covers:
+
+- sign-out drops the history private key when a DEVICE wrap exists and keeps the device key;
+- it publishes a missing DEVICE wrap first, then drops the key;
+- it keeps the key when the wrap cannot be published or history state cannot be read, and returns
+ within the timeout;
+- it leaves other accounts on the same browser alone;
+- wiring: `CognitoAuthService.logout` calls `secureHistoryKeyForSignOut` before `signOut()`, and
+ `SetPasswordCard` calls `useAppStore.getState().logout()` and not `setAuthenticated(false)`.
+
+No automated test covers the onboarding header button itself. Manual checks:
+
+- [ ] The header button shows on every step: label from `sm` up, icon only below.
+- [ ] Clicking it shows the spinner, then the landing page with the info toast.
+- [ ] Afterwards the landing nav shows "Sign in", not "Dashboard".
+- [ ] Signing in again leads through `/auth/setup` to `/onboarding`, starting on step 1.
+- [ ] After leaving past the photo step, name, date of birth (locked) and avatar are prefilled.
+- [ ] After setting a password, the password step no longer appears.
+- [ ] The recovery step's own "Skip for now" finishes onboarding and opens `/app`, without signing
+ out.
+- [ ] Back in the app, chat history opens without a prompt on the same browser.
diff --git a/docs/README.md b/docs/README.md
index 523bfbd..509e39a 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -2,16 +2,27 @@
OneHook is an intentional dating platform designed for meaningful connections, one at a time.
+The current, maintained reference for this web client is the repository [README](../README.md)
+(configuration, routes, auth, E2EE, Mr OneHook, telemetry, deployment and infrastructure).
+
## 📚 Documents
-- [FRONTEND_PRODUCTION.md](./FRONTEND_PRODUCTION.md) — Technical guide on API integration, state management (Zustand), and production-ready architecture.
-- [LANDING_PAGE.md](./LANDING_PAGE.md) — Overview of the landing page design, philosophy, and customization.
-- [LEGAL_PAGES.md](./LEGAL_PAGES.md) — Comprehensive guide on Privacy Policy, Terms of Service, and Compliance (GDPR/CCPA).
-- [LOGIN_SETUP.md](./LOGIN_SETUP.md) — Documentation for the authentication flow and login setup.
+These notes cover single topics in more depth than the README and were checked against `src/`.
+The README stays the reference for configuration, auth, E2EE, Mr OneHook, telemetry and deployment.
+
+- [FRONTEND_PRODUCTION.md](./FRONTEND_PRODUCTION.md): Frontend architecture: source layout, backend integration (SDK, `fetch` helpers, GraphQL, view passes), state, hooks, error handling, build and deployment.
+- [LOGIN_SETUP.md](./LOGIN_SETUP.md): Sign-in methods (one-time code, password, Google, Apple), sessions and tokens, sign-out, and why invite redemption on the web shows an "install the app" notice.
+- [ONBOARDING_SKIP_LOGOUT.md](./ONBOARDING_SKIP_LOGOUT.md): The onboarding "Skip for now" action, which signs the user out (including E2EE key hygiene) and reopens onboarding on the next sign-in.
+- [LANDING_PAGE.md](./LANDING_PAGE.md): The landing page sections, copy sources, assets, animations, the mascot and the public Mr OneHook widget.
+- [LEGAL_PAGES.md](./LEGAL_PAGES.md): What the Privacy Policy, Terms and Contact pages contain, and where their text disagrees with the implementation.
+- [CRUX.md](../CRUX.md): Product and technical overview across all OneHook repositories; also the product context uploaded for Mr OneHook.
-## 🛠️ Related Resources
+## 🛠 Related Resources
-- **App Code**: `../src/App.tsx`
+- **App routes**: `../src/App.tsx` (member app shell: `../src/app/AppContent.tsx`)
- **Global Store**: `../src/store/app-store.ts`
-- **API Client**: `../src/lib/api-client.ts`
+- **API Client**: `../src/api/sdk-client.ts` (generated `onehook-api-client` SDK; service wrappers in `../src/api/`). `../src/lib/api-client.ts` now holds only the shared `ApiError` type.
+- **Runtime Config**: `../src/config/deployment.config.ts` and `../src/utils/env.config.ts`
+- **Auth**: `../src/lib/cognito-auth.ts`
+- **E2EE**: `../src/lib/chat-encryption.ts`
- **Build Config**: `../vite.config.ts`
diff --git a/package-lock.json b/package-lock.json
index e827912..f0ec4fd 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -20,11 +20,13 @@
"jsqr": "1.4.0",
"lucide-react": "^0.546.0",
"motion": "^12.23.24",
- "onehook-api-client": "^1.0.42",
+ "onehook-api-client": "^1.0.44",
+ "onehook-mr-onehook-client": "^1.0.0",
"qrcode.react": "^4.2.0",
"react": "^19.0.1",
"react-dom": "^19.0.1",
"react-router-dom": "^7.1.3",
+ "saha-equation-admin-portal-client": "^1.0.0",
"vite": "^6.2.3",
"vitest": "^4.1.6",
"zustand": "^5.0.2"
@@ -5715,9 +5717,9 @@
}
},
"node_modules/onehook-api-client": {
- "version": "1.0.42",
- "resolved": "https://registry.npmjs.org/onehook-api-client/-/onehook-api-client-1.0.42.tgz",
- "integrity": "sha512-krhD0/seRJQH9aMAoQGcXbRbDfALK6adHDpuIPltQNphsNHGhewpWMCPqkfrWyWKavmiXmqb2OJvHYQPM3NG8Q==",
+ "version": "1.0.44",
+ "resolved": "https://registry.npmjs.org/onehook-api-client/-/onehook-api-client-1.0.44.tgz",
+ "integrity": "sha512-OxpmjKtVXdhZjThj7d7V8x0Xh/C+jjIDakN87pH0YomoM6kXYs8klu7vweHET+Ia1XDZRKqvGAj+P8UHN3rjDQ==",
"license": "UNLICENSED",
"dependencies": {
"@aws-crypto/sha256-browser": "5.2.0",
@@ -6072,6 +6074,159 @@
],
"license": "MIT"
},
+ "node_modules/onehook-mr-onehook-client": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/onehook-mr-onehook-client/-/onehook-mr-onehook-client-1.0.0.tgz",
+ "integrity": "sha512-D1fRNz3Nty6XIIt9mGso8kbsR++vHqWMOfxUePhdZ9FJVNpj78HUYEU3I4kIjYt5WZa7XTAohxZmjraKIRtwvA==",
+ "license": "UNLICENSED",
+ "dependencies": {
+ "@aws-crypto/sha256-browser": "5.2.0",
+ "@aws-crypto/sha256-js": "5.2.0",
+ "@aws-sdk/core": "3.775.0",
+ "@aws-sdk/middleware-host-header": "3.775.0",
+ "@aws-sdk/middleware-logger": "3.775.0",
+ "@aws-sdk/middleware-recursion-detection": "3.775.0",
+ "@aws-sdk/middleware-user-agent": "3.787.0",
+ "@aws-sdk/types": "3.775.0",
+ "@aws-sdk/util-user-agent-browser": "3.775.0",
+ "@aws-sdk/util-user-agent-node": "3.787.0",
+ "@smithy/config-resolver": "^4.1.0",
+ "@smithy/core": "^3.2.0",
+ "@smithy/fetch-http-handler": "^5.0.2",
+ "@smithy/hash-node": "^4.0.2",
+ "@smithy/invalid-dependency": "^4.0.2",
+ "@smithy/middleware-content-length": "^4.0.2",
+ "@smithy/middleware-retry": "^4.1.0",
+ "@smithy/middleware-serde": "^4.0.3",
+ "@smithy/middleware-stack": "^4.0.2",
+ "@smithy/node-config-provider": "^4.0.2",
+ "@smithy/node-http-handler": "^4.0.4",
+ "@smithy/protocol-http": "^5.1.0",
+ "@smithy/smithy-client": "^4.2.0",
+ "@smithy/types": "^4.2.0",
+ "@smithy/url-parser": "^4.0.2",
+ "@smithy/util-base64": "^4.0.0",
+ "@smithy/util-body-length-browser": "^4.0.0",
+ "@smithy/util-body-length-node": "^4.0.0",
+ "@smithy/util-defaults-mode-browser": "^4.0.8",
+ "@smithy/util-defaults-mode-node": "^4.0.8",
+ "@smithy/util-middleware": "^4.0.2",
+ "@smithy/util-retry": "^4.0.2",
+ "@smithy/util-utf8": "^4.0.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/onehook-mr-onehook-client/node_modules/@aws-sdk/core": {
+ "version": "3.775.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.775.0.tgz",
+ "integrity": "sha512-8vpW4WihVfz0DX+7WnnLGm3GuQER++b0IwQG35JlQMlgqnc44M//KbJPsIHA0aJUJVwJAEShgfr5dUbY8WUzaA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/types": "3.775.0",
+ "@smithy/core": "^3.2.0",
+ "@smithy/node-config-provider": "^4.0.2",
+ "@smithy/property-provider": "^4.0.2",
+ "@smithy/protocol-http": "^5.1.0",
+ "@smithy/signature-v4": "^5.0.2",
+ "@smithy/smithy-client": "^4.2.0",
+ "@smithy/types": "^4.2.0",
+ "@smithy/util-middleware": "^4.0.2",
+ "fast-xml-parser": "4.4.1",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/onehook-mr-onehook-client/node_modules/@aws-sdk/types": {
+ "version": "3.775.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.775.0.tgz",
+ "integrity": "sha512-ZoGKwa4C9fC9Av6bdfqcW6Ix5ot05F/S4VxWR2nHuMv7hzfmAjTOcUiWT7UR4hM/U0whf84VhDtXN/DWAk52KA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/types": "^4.2.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/onehook-mr-onehook-client/node_modules/@smithy/protocol-http": {
+ "version": "5.6.2",
+ "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.6.2.tgz",
+ "integrity": "sha512-Asd04MaxODN6FNY8EPTeCAM4kPNi3jDUAjZU0Y4F9rHvpLUrrUo7KLcxFgSthywFr6dZfIyDLIJda6jxmVTk5w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.33.2",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/onehook-mr-onehook-client/node_modules/@smithy/util-base64": {
+ "version": "4.6.2",
+ "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.6.2.tgz",
+ "integrity": "sha512-wTQX1hPfElIqY6AzM/s6c4UgpMxCL4MwJ5u6340ksLPq78lur6Y+keheIDk5gMX4G3KFh4MERcDt6xhRq+ie1Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.33.2",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/onehook-mr-onehook-client/node_modules/@smithy/util-utf8": {
+ "version": "4.5.2",
+ "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.5.2.tgz",
+ "integrity": "sha512-7wNWV7SugHpcMA7uzEawJNpE0GrasXM7a9E+1+Wm6NxVuDClESac/AKt+G7jMZNUz5vBLWqKlqVV7Sv7AtUr6Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.33.2",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/onehook-mr-onehook-client/node_modules/fast-xml-parser": {
+ "version": "4.4.1",
+ "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz",
+ "integrity": "sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/NaturalIntelligence"
+ },
+ {
+ "type": "paypal",
+ "url": "https://paypal.me/naturalintelligence"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "strnum": "^1.0.5"
+ },
+ "bin": {
+ "fxparser": "src/cli/cli.js"
+ }
+ },
+ "node_modules/onehook-mr-onehook-client/node_modules/strnum": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz",
+ "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/NaturalIntelligence"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/p-locate": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
@@ -6584,6 +6739,159 @@
"tslib": "^2.1.0"
}
},
+ "node_modules/saha-equation-admin-portal-client": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/saha-equation-admin-portal-client/-/saha-equation-admin-portal-client-1.0.0.tgz",
+ "integrity": "sha512-K0rBrYbiBzRkPfryKlRyQww//G1kj/GX0cF2Px7tUTNFr2FLOtNVrto2JhBDxp9giEIgI58603WSsnk8rcm0WQ==",
+ "license": "UNLICENSED",
+ "dependencies": {
+ "@aws-crypto/sha256-browser": "5.2.0",
+ "@aws-crypto/sha256-js": "5.2.0",
+ "@aws-sdk/core": "3.775.0",
+ "@aws-sdk/middleware-host-header": "3.775.0",
+ "@aws-sdk/middleware-logger": "3.775.0",
+ "@aws-sdk/middleware-recursion-detection": "3.775.0",
+ "@aws-sdk/middleware-user-agent": "3.787.0",
+ "@aws-sdk/types": "3.775.0",
+ "@aws-sdk/util-user-agent-browser": "3.775.0",
+ "@aws-sdk/util-user-agent-node": "3.787.0",
+ "@smithy/config-resolver": "^4.1.0",
+ "@smithy/core": "^3.2.0",
+ "@smithy/fetch-http-handler": "^5.0.2",
+ "@smithy/hash-node": "^4.0.2",
+ "@smithy/invalid-dependency": "^4.0.2",
+ "@smithy/middleware-content-length": "^4.0.2",
+ "@smithy/middleware-retry": "^4.1.0",
+ "@smithy/middleware-serde": "^4.0.3",
+ "@smithy/middleware-stack": "^4.0.2",
+ "@smithy/node-config-provider": "^4.0.2",
+ "@smithy/node-http-handler": "^4.0.4",
+ "@smithy/protocol-http": "^5.1.0",
+ "@smithy/smithy-client": "^4.2.0",
+ "@smithy/types": "^4.2.0",
+ "@smithy/url-parser": "^4.0.2",
+ "@smithy/util-base64": "^4.0.0",
+ "@smithy/util-body-length-browser": "^4.0.0",
+ "@smithy/util-body-length-node": "^4.0.0",
+ "@smithy/util-defaults-mode-browser": "^4.0.8",
+ "@smithy/util-defaults-mode-node": "^4.0.8",
+ "@smithy/util-middleware": "^4.0.2",
+ "@smithy/util-retry": "^4.0.2",
+ "@smithy/util-utf8": "^4.0.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/saha-equation-admin-portal-client/node_modules/@aws-sdk/core": {
+ "version": "3.775.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.775.0.tgz",
+ "integrity": "sha512-8vpW4WihVfz0DX+7WnnLGm3GuQER++b0IwQG35JlQMlgqnc44M//KbJPsIHA0aJUJVwJAEShgfr5dUbY8WUzaA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/types": "3.775.0",
+ "@smithy/core": "^3.2.0",
+ "@smithy/node-config-provider": "^4.0.2",
+ "@smithy/property-provider": "^4.0.2",
+ "@smithy/protocol-http": "^5.1.0",
+ "@smithy/signature-v4": "^5.0.2",
+ "@smithy/smithy-client": "^4.2.0",
+ "@smithy/types": "^4.2.0",
+ "@smithy/util-middleware": "^4.0.2",
+ "fast-xml-parser": "4.4.1",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/saha-equation-admin-portal-client/node_modules/@aws-sdk/types": {
+ "version": "3.775.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.775.0.tgz",
+ "integrity": "sha512-ZoGKwa4C9fC9Av6bdfqcW6Ix5ot05F/S4VxWR2nHuMv7hzfmAjTOcUiWT7UR4hM/U0whf84VhDtXN/DWAk52KA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/types": "^4.2.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/saha-equation-admin-portal-client/node_modules/@smithy/protocol-http": {
+ "version": "5.6.2",
+ "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.6.2.tgz",
+ "integrity": "sha512-Asd04MaxODN6FNY8EPTeCAM4kPNi3jDUAjZU0Y4F9rHvpLUrrUo7KLcxFgSthywFr6dZfIyDLIJda6jxmVTk5w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.33.2",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/saha-equation-admin-portal-client/node_modules/@smithy/util-base64": {
+ "version": "4.6.2",
+ "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.6.2.tgz",
+ "integrity": "sha512-wTQX1hPfElIqY6AzM/s6c4UgpMxCL4MwJ5u6340ksLPq78lur6Y+keheIDk5gMX4G3KFh4MERcDt6xhRq+ie1Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.33.2",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/saha-equation-admin-portal-client/node_modules/@smithy/util-utf8": {
+ "version": "4.5.2",
+ "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.5.2.tgz",
+ "integrity": "sha512-7wNWV7SugHpcMA7uzEawJNpE0GrasXM7a9E+1+Wm6NxVuDClESac/AKt+G7jMZNUz5vBLWqKlqVV7Sv7AtUr6Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.33.2",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/saha-equation-admin-portal-client/node_modules/fast-xml-parser": {
+ "version": "4.4.1",
+ "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz",
+ "integrity": "sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/NaturalIntelligence"
+ },
+ {
+ "type": "paypal",
+ "url": "https://paypal.me/naturalintelligence"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "strnum": "^1.0.5"
+ },
+ "bin": {
+ "fxparser": "src/cli/cli.js"
+ }
+ },
+ "node_modules/saha-equation-admin-portal-client/node_modules/strnum": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz",
+ "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/NaturalIntelligence"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/scheduler": {
"version": "0.27.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
diff --git a/package.json b/package.json
index 9723cec..509c74e 100644
--- a/package.json
+++ b/package.json
@@ -47,11 +47,13 @@
"jsqr": "1.4.0",
"lucide-react": "^0.546.0",
"motion": "^12.23.24",
- "onehook-api-client": "^1.0.42",
+ "onehook-api-client": "^1.0.44",
+ "onehook-mr-onehook-client": "^1.0.0",
"qrcode.react": "^4.2.0",
"react": "^19.0.1",
"react-dom": "^19.0.1",
"react-router-dom": "^7.1.3",
+ "saha-equation-admin-portal-client": "^1.0.0",
"vite": "^6.2.3",
"vitest": "^4.1.6",
"zustand": "^5.0.2"
diff --git a/public/media/og/onehook-og-science.png b/public/media/og/onehook-og-science.png
new file mode 100644
index 0000000..bab4455
Binary files /dev/null and b/public/media/og/onehook-og-science.png differ
diff --git a/src/api/analytics.ts b/src/api/analytics.ts
index 02e3a05..e20f00a 100644
--- a/src/api/analytics.ts
+++ b/src/api/analytics.ts
@@ -1,95 +1,40 @@
/**
- * Analytics client-signal ingest transport (`POST /signals`).
+ * Analytics client-signal ingest (`IngestSignals`, `POST /signals`) and photo stats (`GetMediaStats`).
*
- * This is the analytics counterpart to {@link file://./rest.ts}: the generated Smithy SDK
- * (`onehook-api-client`) does not model the ingest endpoint, so — exactly like the block/distance/
- * swipe endpoints — the call goes through a thin authenticated REST helper that authenticates
- * IDENTICALLY to `sdk-client.ts` (the Cognito **ID token**, falling back to the access token, is
- * read from the Amplify auth session and attached as a `Bearer` token). Because the ingest is now
- * routed under the unified `api..onehook.club` domain (see api-stack's `signals*` behavior),
- * the request rides the same base URL + Cognito authorizer as every other onehook-api-client call.
- *
- * The server re-stamps identity and time and marks every signal `unverified`, so the client only
- * has to be well-behaved: send the caller's JWT, name the platform via `X-OneHook-Platform`, and
- * POST `{ signals: [...] }`. On any failure this throws {@link ApiError} so the batching client
+ * Both go through the generated `onehook-api-client` SDK (`sdkClient`, analytics.smithy), so they use
+ * the same base URL and Cognito authorizer as every other call. The server re-stamps identity and time
+ * and marks every signal `unverified`; the client sends the caller's JWT (SDK middleware), names the
+ * platform (the `X-OneHook-Platform` header, `platform` in the model) and the batch. On any failure
+ * this throws {@link ApiError} so the batching client
* ({@link file://../lib/analytics/analyticsClient.ts}) re-queues and retries.
*/
-import { apiBaseUrl } from '../utils/env.config';
+import type { RawSignal } from 'onehook-api-client';
import { ApiError } from '../lib/api-client';
import type { AnalyticsTransport, Signal } from '../lib/analytics/analyticsClient';
-
-/**
- * Reads the caller's Cognito JWT the same way `sdk-client.ts`/`rest.ts` do: the ID token first (the
- * API Gateway Cognito authorizer validates it), falling back to the access token. Returns null when
- * unauthenticated so the request is still attempted (and rejected by the server) rather than
- * throwing here.
- */
-async function getAuthToken(): Promise {
- if (typeof window === 'undefined') return null;
- try {
- const { fetchAuthSession } = await import('aws-amplify/auth');
- const session = await fetchAuthSession();
- return session.tokens?.idToken?.toString() || session.tokens?.accessToken?.toString() || null;
- } catch {
- return null;
- }
-}
-
-/**
- * Resolve `/signals` against the configured base URL, mirroring `rest.ts`: on localhost the dev
- * origin is used (the Vite proxy forwards to the backend), otherwise the absolute `apiBaseUrl`.
- */
-function resolveUrl(path: string): string {
- const suffix = path.startsWith('/') ? path : `/${path}`;
- if (
- typeof window !== 'undefined' &&
- (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1')
- ) {
- return window.location.origin + suffix;
- }
- if (apiBaseUrl) {
- if (apiBaseUrl.startsWith('http')) return apiBaseUrl + suffix;
- if (typeof window !== 'undefined' && window.location?.origin) {
- return window.location.origin + suffix;
- }
- return apiBaseUrl + suffix;
- }
- if (typeof window !== 'undefined' && window.location?.origin) {
- return window.location.origin + suffix;
- }
- return `http://localhost:3000${suffix}`;
-}
+import { callSdk, sdkClient } from './sdk-client';
/**
* POST a batch of behavioural signals to the ingest. Throws {@link ApiError} on transport failure
* or a non-2xx response so the caller re-queues.
*/
export async function sendSignals(batch: Signal[]): Promise {
- const token = await getAuthToken();
- const headers: Record = {
- 'Content-Type': 'application/json',
- Accept: 'application/json',
- // Lets the server attribute the platform without trusting the body.
- 'X-OneHook-Platform': 'web',
- };
- if (token) headers['Authorization'] = `Bearer ${token}`;
-
- let res: Response;
try {
- res = await fetch(resolveUrl('/signals'), {
- method: 'POST',
- headers,
- body: JSON.stringify({ signals: batch }),
+ await sdkClient.ingestSignals({
+ // Lets the server attribute the platform without trusting the body.
+ platform: 'web',
+ signals: batch.map((s) => ({
+ clientEventId: s.clientEventId,
+ type: s.type,
+ timestamp: s.timestamp,
+ attributes: s.attributes as RawSignal['attributes'],
+ })),
});
} catch (err) {
- throw new ApiError(
- err instanceof Error ? err.message : 'Network request failed',
- 0,
- 'NETWORK_ERROR'
- );
- }
- if (!res.ok) {
- throw new ApiError('analytics ingest failed', res.status, 'ANALYTICS_INGEST_FAILED');
+ const status = (err as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode;
+ if (status === undefined) {
+ throw new ApiError(err instanceof Error ? err.message : 'Network request failed', 0, 'NETWORK_ERROR', err);
+ }
+ throw new ApiError('analytics ingest failed', status, 'ANALYTICS_INGEST_FAILED', err);
}
}
@@ -118,12 +63,7 @@ export interface PhotoStats {
* Cognito JWT, so a client can never read someone else's stats. Returns mediaId → stats.
*/
export async function getMyPhotoStats(): Promise> {
- const token = await getAuthToken();
- const res = await fetch(resolveUrl('/signals/media-stats'), {
- method: 'GET',
- headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
- });
- if (!res.ok) throw new ApiError(`media stats failed: ${res.status}`, res.status);
- const body = (await res.json()) as { photos?: PhotoStats[] };
- return Object.fromEntries((body.photos ?? []).map((p) => [p.mediaId, p]));
+ const out = await callSdk(() => sdkClient.getMediaStats({}));
+ const photos = (out.photos ?? []) as unknown as PhotoStats[];
+ return Object.fromEntries(photos.map((p) => [p.mediaId, p]));
}
diff --git a/src/api/chat.ts b/src/api/chat.ts
index a5361d7..c53208a 100644
--- a/src/api/chat.ts
+++ b/src/api/chat.ts
@@ -1,6 +1,6 @@
import { generateClient } from 'aws-amplify/api';
-import { sdkClient } from './sdk-client';
-import { apiBaseUrl } from '../utils/env.config';
+import type { MediaKind, Platform } from 'onehook-api-client';
+import { callSdk, sdkClient } from './sdk-client';
import { hasGraphQLErrors, toGraphQLError } from './graphql-error';
import type {
Message as ChatMessage,
@@ -608,11 +608,9 @@ export const ChatMessagingApi = {
// ─────────────────────────────────────────────────────────────────────────────
// Multi-device registry (wire v2)
//
-// The generated Smithy SDK does not (yet) model the `/chat/devices` routes, so these are issued as
-// raw authenticated REST calls against the same API domain and Cognito authorizer the SDK uses. The
-// request shape mirrors the SDK's `sdk-client.ts` middleware exactly: a Cognito JWT Bearer token and
-// an `X-User-Id` header derived from its `sub`. Kept deliberately thin — no plaintext ever crosses
-// this boundary; only public device/history keys and ciphertext envelopes do.
+// Device registry, history-key lifecycle and attachment URLs, all through the generated SDK (Chat
+// operations in chat.smithy). No plaintext ever crosses this boundary; only public device/history keys
+// and ciphertext envelopes do.
// ─────────────────────────────────────────────────────────────────────────────
export interface DeviceRecord {
@@ -720,10 +718,9 @@ export interface PutWrapRequest {
}
/**
- * The two attachment media endpoints (see OneHookBackend/docs/chat-attachments.md). Like the device
- * registry above, they are not yet modelled by the generated SDK, so they ride the same authenticated
- * `chatRest` helper. Only the presigned URL and object key cross this boundary — the content key lives
- * exclusively inside the E2EE message envelope and never touches these calls.
+ * The two attachment media endpoints (see OneHookBackend/docs/chat-attachments.md). Only the
+ * presigned URL and object key cross this boundary — the content key lives exclusively inside the
+ * E2EE message envelope and never touches these calls.
*/
export interface MediaUploadUrlResponse {
/** S3 key the server assigned, always "/". Goes into the attachment envelope. */
@@ -738,54 +735,13 @@ export interface MediaDownloadUrlResponse {
expiresInSeconds: number;
}
-async function chatRestBaseUrl(): Promise { if (apiBaseUrl && apiBaseUrl.startsWith('http')) return apiBaseUrl.replace(/\/+$/, '');
- if (typeof window !== 'undefined' && window.location?.origin) {
- const origin = window.location.origin;
- return apiBaseUrl ? `${origin}/${apiBaseUrl.replace(/^\/+|\/+$/g, '')}` : origin;
- }
- return apiBaseUrl || '';
-}
-
-async function chatAuthHeaders(): Promise> {
- const headers: Record = { 'Content-Type': 'application/json' };
- if (typeof window === 'undefined') return headers;
- try {
- const { fetchAuthSession } = await import('aws-amplify/auth');
- const session = await fetchAuthSession();
- const token =
- session.tokens?.idToken?.toString() || session.tokens?.accessToken?.toString() || null;
- if (token) {
- headers['Authorization'] = `Bearer ${token}`;
- const sub =
- (session.tokens?.idToken?.payload?.sub as string) ||
- (session.tokens?.accessToken?.payload?.sub as string) ||
- '';
- if (sub) headers['X-User-Id'] = sub;
- }
- } catch {
- // Unauthenticated callers get no Authorization header; the API rejects them, which surfaces as
- // a thrown error below rather than a silent success.
- }
- return headers;
-}
-
-async function chatRest(method: string, path: string, body?: unknown): Promise {
- const base = await chatRestBaseUrl();
- const headers = await chatAuthHeaders();
- const response = await fetch(`${base}${path}`, {
- method,
- headers,
- body: body === undefined ? undefined : JSON.stringify(body),
- });
- if (!response.ok) {
- const text = await response.text().catch(() => '');
- throw new Error(
- `chat device request failed (${response.status} ${response.statusText})${text ? `: ${text}` : ''}`
- );
- }
- if (response.status === 204) return undefined as T;
- const text = await response.text();
- return (text ? JSON.parse(text) : undefined) as T;
+/**
+ * The SDK output without its `$metadata`, typed as the app's shape. The app types mirror the Smithy
+ * shapes (chat.smithy); the SDK marks required members `| undefined`, which the server never omits.
+ */
+function body(out: object): T {
+ const { $metadata: _metadata, ...rest } = out as { $metadata?: unknown };
+ return rest as T;
}
/**
@@ -812,18 +768,20 @@ export const ChatApi = {
contentLength: number,
kind: string
): Promise =>
- chatRest('POST', '/chat/media/upload-url', {
- matchId,
- contentLength,
- kind,
- }),
+ callSdk(async () =>
+ body(
+ await sdkClient.createMediaUploadUrl({ matchId, contentLength, kind: kind as MediaKind })
+ )
+ ),
/**
* Request a presigned GET URL for an attachment. The server only issues one for a key under the
* caller's own match, so a guessed key from another conversation is rejected here, not just hidden.
*/
getMediaDownloadUrl: (matchId: string, objectKey: string): Promise =>
- chatRest('POST', '/chat/media/download-url', { matchId, objectKey }),
+ callSdk(async () =>
+ body(await sdkClient.createMediaDownloadUrl({ matchId, objectKey }))
+ ),
// --- Multi-device registry (wire v2) ---
@@ -838,24 +796,28 @@ export const ChatApi = {
* messages to history right away.
*/
registerDevice: (request: RegisterDeviceRequest): Promise =>
- chatRest('POST', '/chat/devices', request),
+ callSdk(async () =>
+ body(
+ await sdkClient.registerDevice({ ...request, platform: request.platform as Platform })
+ )
+ ),
/** Fetch the caller's own device registry. */
- getSelfDevices: (): Promise => chatRest('GET', '/chat/devices'),
+ getSelfDevices: (): Promise =>
+ callSdk(async () => body(await sdkClient.listMyDevices({}))),
/**
* Fetch a peer's device registry for a shared match. The server authorizes the read against a
* State-verified mutual match, so `matchId` is required.
*/
getPeerDevices: (userId: string, matchId: string): Promise =>
- chatRest(
- 'GET',
- `/chat/registry/${encodeURIComponent(userId)}?matchId=${encodeURIComponent(matchId)}`
- ),
+ callSdk(async () => body(await sdkClient.getParticipantRegistry({ userId, matchId }))),
/** Revoke (remove) a device from the caller's registry. */
revokeDevice: (deviceId: string): Promise =>
- chatRest('DELETE', `/chat/devices/${encodeURIComponent(deviceId)}`),
+ callSdk(async () => {
+ await sdkClient.revokeDevice({ deviceId });
+ }),
// --- Account history-key lifecycle (epochs + wraps) ---
@@ -866,7 +828,8 @@ export const ChatApi = {
* PRF, then a device wrap, then QR, then reset. Wrap ciphertext is returned because only this
* account can open it; the server holds no key that would let it do so.
*/
- getHistoryState: (): Promise => chatRest('GET', '/chat/history'),
+ getHistoryState: (): Promise =>
+ callSdk(async () => body(await sdkClient.getHistoryState({}))),
/**
* Establish a history epoch and make it active.
@@ -879,19 +842,18 @@ export const ChatApi = {
* `getHistoryState` and unlock against the epoch that won rather than retrying.
*/
establishHistoryEpoch: (request: EstablishEpochRequest): Promise =>
- chatRest('POST', '/chat/history/epochs', request),
+ callSdk(async () => body(await sdkClient.establishHistoryEpoch(request))),
/**
* Add or replace one wrap. Idempotent on (epoch, method, wrapId), so re-approving a device or
* re-deriving a PRF wrap refreshes rather than accumulating rows.
*/
putHistoryWrap: (request: PutWrapRequest): Promise<{ wraps: AhkWrapRecord }> =>
- chatRest<{ wraps: AhkWrapRecord }>('POST', '/chat/history/wraps', request),
+ callSdk(async () => body<{ wraps: AhkWrapRecord }>(await sdkClient.putHistoryWrap(request))),
/** Revoke one unlock method — a retired device, or a passkey the user deleted. */
revokeHistoryWrap: (epoch: number, method: WrapMethod, wrapId: string): Promise =>
- chatRest(
- 'DELETE',
- `/chat/history/wraps/${epoch}/${encodeURIComponent(method)}/${encodeURIComponent(wrapId)}`
- ),
+ callSdk(async () => {
+ await sdkClient.revokeHistoryWrap({ epoch, method, wrapId });
+ }),
};
diff --git a/src/api/external-sdk-clients.ts b/src/api/external-sdk-clients.ts
new file mode 100644
index 0000000..9ca1b58
--- /dev/null
+++ b/src/api/external-sdk-clients.ts
@@ -0,0 +1,125 @@
+/**
+ * Clients for the two APIs the web app calls that are not OneHook backend APIs, each from the package its
+ * owner publishes:
+ *
+ * - `onehook-mr-onehook-client` (OneHookUXEnhancement, MrOneHookService): Mr OneHook on Azure at
+ * `chatbotUrl`. Member routes take the Cognito ID token as a Bearer token; the public product chat
+ * and health routes take none.
+ * - `saha-equation-admin-portal-client` (OneHookAdminPortal): the portal's public feature APIs for any tenant.
+ * OneHook is the tenant `{service, stage}` read from `portalModerationBaseUrl`
+ * (https://admin.onehook.club/api/p/onehook//moderation); the portal client binds it.
+ *
+ * Both are built with `maxAttempts: 1`: a Mr OneHook turn counts against the member's daily quota, and
+ * the evidence flow does its own bounded retry of `complete`. The `amz-sdk-*` and `x-amz-user-agent`
+ * headers are dropped so neither service has to allow them in CORS.
+ */
+import { MrOneHookService } from 'onehook-mr-onehook-client';
+import { createPortalClient, portalTenantFromUrl, type PortalClient } from 'saha-equation-admin-portal-client';
+import { FetchHttpHandler } from '@smithy/fetch-http-handler';
+import { chatbotUrl, portalModerationBaseUrl } from '../utils/env.config';
+
+/** The member's Cognito ID token, or null when signed out. */
+export async function fetchIdToken(): Promise {
+ if (typeof window === 'undefined') return null;
+ try {
+ const { fetchAuthSession } = await import('aws-amplify/auth');
+ const session = await fetchAuthSession();
+ return session.tokens?.idToken?.toString() || null;
+ } catch {
+ return null;
+ }
+}
+
+/** Bearer token provider for the generated clients; a missing token fails the call before it is sent. */
+async function bearerToken(): Promise<{ token: string }> {
+ const token = await fetchIdToken();
+ if (!token) throw new Error('NOT_AUTHENTICATED');
+ return { token };
+}
+
+const SDK_HEADERS = ['amz-sdk-request', 'amz-sdk-invocation-id', 'x-amz-user-agent'];
+
+type StrippableClient = {
+ middlewareStack: {
+ add: (
+ mw: (next: (args: { request: unknown }) => Promise) => (args: { request: unknown }) => Promise,
+ opts: { step: 'finalizeRequest'; name: string; priority: 'low' }
+ ) => void;
+ };
+};
+
+function stripSdkHeaders(client: StrippableClient): void {
+ client.middlewareStack.add(
+ (next) => async (args) => {
+ const headers = (args.request as { headers?: Record })?.headers;
+ if (headers) for (const h of SDK_HEADERS) delete headers[h];
+ return next(args);
+ },
+ { step: 'finalizeRequest', name: 'stripSdkHeaders', priority: 'low' }
+ );
+}
+
+/** The Smithy client needs an absolute endpoint at construction; tests and SSR get a placeholder. */
+function absolute(url: string): string {
+ return /^https?:\/\//.test(url) ? url : 'http://localhost:3000';
+}
+
+export const mrOneHookClient = new MrOneHookService({
+ endpoint: absolute(chatbotUrl),
+ requestHandler: new FetchHttpHandler(),
+ token: bearerToken,
+ maxAttempts: 1,
+});
+stripSdkHeaders(mrOneHookClient as unknown as StrippableClient);
+
+/** The OneHook tenant's moderation-evidence API: `presignEvidence` / `completeEvidence` with the tenant bound. */
+export type EvidenceClient = PortalClient['moderationEvidence'];
+
+export function createModerationEvidenceClient(
+ baseUrl: string = portalModerationBaseUrl,
+ getToken: () => Promise = fetchIdToken,
+ /** Tests pass a handler over a fake `fetch`; the app uses the browser `fetch`. */
+ requestHandler: NonNullable[0]['clientConfig']>['requestHandler'] = new FetchHttpHandler()
+): EvidenceClient {
+ const { endpoint, tenant, feature } = portalTenantFromUrl(absolute(baseUrl));
+ if (feature !== 'moderation') throw new Error(`portalModerationBaseUrl must end in /moderation, got ${baseUrl}`);
+ const portal = createPortalClient({
+ endpoint,
+ tenant,
+ tokens: {
+ moderationEvidence: async () => {
+ const token = await getToken();
+ if (!token) throw new Error('NOT_AUTHENTICATED');
+ return { token };
+ },
+ },
+ clientConfig: { requestHandler, maxAttempts: 1 },
+ });
+ stripSdkHeaders(portal.clients.moderationEvidence as unknown as StrippableClient);
+ return portal.moderationEvidence;
+}
+
+/** A failed call's HTTP status and its error body fields (the SDK copies the body onto the exception). */
+export interface SdkFailure {
+ status: number;
+ body: Record;
+}
+
+const NON_BODY_KEYS = new Set(['name', 'message', 'stack', '$fault', '$metadata', '$response', '$retryable']);
+
+/** The HTTP failure inside an SDK exception, or null for a network or client-side error. */
+export function sdkFailure(err: unknown): SdkFailure | null {
+ const status = (err as { $metadata?: { httpStatusCode?: number } } | null)?.$metadata?.httpStatusCode;
+ if (typeof status !== 'number') return null;
+ const body: Record = {};
+ for (const [k, v] of Object.entries(err as Record)) {
+ if (!NON_BODY_KEYS.has(k)) body[k] = v;
+ }
+ return { status, body };
+}
+
+/** An SDK output without `$metadata`. */
+export function withoutMetadata(out: T): Omit {
+ const { $metadata: _metadata, ...rest } = out as T & { $metadata?: unknown };
+ return rest;
+}
diff --git a/src/api/live-location.ts b/src/api/live-location.ts
index b548105..e2e1e76 100644
--- a/src/api/live-location.ts
+++ b/src/api/live-location.ts
@@ -2,20 +2,21 @@
* Live-location AppSync operations (OneHookBackend/packages/api-models/model/schema.graphql, "Live
* location sharing"; contract in OneHookBackend/docs/chat-location-contact.md).
*
- * Web receives and opens only, so it reads running shares on open (`getLiveLocations`) and follows
- * `onLiveLocation`. It never publishes or stops a share. Every selection set carries all seven
- * `LiveLocationUpdate` fields. `ciphertext` is the sealed `live_location_update` payload: it is opened
- * with the same wire-v2 envelope and `matchId` AAD as a message body, on device.
+ * Receiving: running shares on open (`getLiveLocations`), then `onLiveLocation`. Sending: the sharer
+ * publishes sealed positions (`publishLiveLocation`) and ends its own share (`stopLiveLocation`).
+ * Every selection set carries all seven `LiveLocationUpdate` fields: subscribers only receive the
+ * fields the triggering mutation selected, so a publish without `ciphertext` would reach peers empty.
+ * `ciphertext` is the sealed `live_location_update` payload, sealed and opened with the same wire-v2
+ * envelope and `matchId` AAD as a message body, on device.
*/
+import { Amplify } from 'aws-amplify';
import { appSyncClient } from './chat';
import { hasGraphQLErrors, toGraphQLError } from './graphql-error';
import type { LiveLocationRow } from '../lib/live-location';
export type LiveLocationUpdate = LiveLocationRow;
-export const GET_LIVE_LOCATIONS = /* GraphQL */ `
- query GetLiveLocations($matchId: ID!) {
- getLiveLocations(matchId: $matchId) {
+const ROW_FIELDS = /* GraphQL */ `
matchId
userId
sessionId
@@ -23,21 +24,29 @@ export const GET_LIVE_LOCATIONS = /* GraphQL */ `
at
expiresAt
ended
- }
+`;
+
+export const GET_LIVE_LOCATIONS = /* GraphQL */ `
+ query GetLiveLocations($matchId: ID!) {
+ getLiveLocations(matchId: $matchId) {${ROW_FIELDS} }
}
`;
export const ON_LIVE_LOCATION = /* GraphQL */ `
subscription OnLiveLocation($matchId: ID!) {
- onLiveLocation(matchId: $matchId) {
- matchId
- userId
- sessionId
- ciphertext
- at
- expiresAt
- ended
- }
+ onLiveLocation(matchId: $matchId) {${ROW_FIELDS} }
+ }
+`;
+
+export const PUBLISH_LIVE_LOCATION = /* GraphQL */ `
+ mutation PublishLiveLocation($matchId: ID!, $sessionId: ID!, $ciphertext: String!, $expiresAt: AWSTimestamp!) {
+ publishLiveLocation(matchId: $matchId, sessionId: $sessionId, ciphertext: $ciphertext, expiresAt: $expiresAt) {${ROW_FIELDS} }
+ }
+`;
+
+export const STOP_LIVE_LOCATION = /* GraphQL */ `
+ mutation StopLiveLocation($matchId: ID!, $sessionId: ID!) {
+ stopLiveLocation(matchId: $matchId, sessionId: $sessionId) {${ROW_FIELDS} }
}
`;
@@ -55,22 +64,119 @@ function isRow(value: unknown): value is LiveLocationUpdate {
);
}
+/** One GraphQL call over the shared Cognito-authorized client, with the server's errors preserved. */
+async function run(query: string, variables: Record): Promise {
+ let res: unknown;
+ try {
+ res = await appSyncClient().graphql({ query, variables });
+ } catch (raw) {
+ throw toGraphQLError(raw, 'The chat service could not be reached.');
+ }
+ if (hasGraphQLErrors(res)) {
+ throw toGraphQLError(res, 'The chat service rejected the request.');
+ }
+ return res;
+}
+
+// ── Stop on tab close ────────────────────────────────────────────────────────
+//
+// When the tab closes, the page cannot await anything: Amplify's client resolves the auth token
+// asynchronously, so a request started from `pagehide` through it is usually never sent. The only
+// request that reliably outlives the page is a `fetch` with `keepalive: true` issued synchronously in
+// the handler. `navigator.sendBeacon` cannot be used: it cannot set the `Authorization` header AppSync
+// needs. So the sharer keeps a copy of the current Cognito access token (refreshed on every publish,
+// through Amplify, which refreshes it when it expires) and the unload path posts `stopLiveLocation`
+// with it directly. Best effort by nature: if the browser drops the request, the share still ends at
+// `expiresAt` and receivers stop showing it then.
+
+interface UnloadAuth {
+ endpoint: string;
+ token: string;
+ /** Epoch ms after which the token is no longer accepted. */
+ expiresAt: number;
+}
+
+let unloadAuth: UnloadAuth | null = null;
+
+/** Refreshes the token copy the unload path uses. Never throws. */
+async function primeUnloadAuth(): Promise {
+ try {
+ const endpoint = (Amplify.getConfig() as { API?: { GraphQL?: { endpoint?: string } } }).API?.GraphQL?.endpoint;
+ if (!endpoint) return;
+ const { fetchAuthSession } = await import('aws-amplify/auth');
+ const session = await fetchAuthSession();
+ const access = session.tokens?.accessToken;
+ if (!access) return;
+ const exp = typeof access.payload?.exp === 'number' ? access.payload.exp * 1000 : Date.now() + 5 * 60_000;
+ unloadAuth = { endpoint, token: access.toString(), expiresAt: exp };
+ } catch {
+ /* the unload stop is best effort; expiry ends the share anyway */
+ }
+}
+
+/** Forgets the token copy (signed out, or nothing left to stop). */
+function clearUnloadAuth(): void {
+ unloadAuth = null;
+}
+
+/**
+ * Sends `stopLiveLocation` from a `pagehide` handler. Synchronous: it only starts a keepalive fetch.
+ * Returns false when it could not even be attempted (no fresh token, no fetch keepalive support).
+ */
+function stopOnUnload(matchId: string, sessionId: string, now = Date.now()): boolean {
+ const auth = unloadAuth;
+ if (!auth || auth.expiresAt - 10_000 <= now) return false;
+ try {
+ // A direct request to the AppSync endpoint (not a Smithy route), listed in the EXCEPTIONS of
+ // src/tests/api-route-contract.test.ts.
+ void fetch(auth.endpoint, {
+ method: 'POST',
+ keepalive: true,
+ headers: { 'Content-Type': 'application/json', Authorization: auth.token },
+ body: JSON.stringify({ query: STOP_LIVE_LOCATION, variables: { matchId, sessionId } }),
+ }).catch(() => undefined);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
export const LiveLocationApi = {
/** Running shares of both members (not ended, not expired). Empty while the chat is suspended. */
getLiveLocations: async (matchId: string): Promise => {
- let res: unknown;
- try {
- res = await appSyncClient().graphql({ query: GET_LIVE_LOCATIONS, variables: { matchId } });
- } catch (raw) {
- throw toGraphQLError(raw, 'The chat service could not be reached.');
- }
- if (hasGraphQLErrors(res)) {
- throw toGraphQLError(res, 'The chat service rejected the request.');
- }
+ const res = await run(GET_LIVE_LOCATIONS, { matchId });
const rows = (res as { data?: { getLiveLocations?: unknown[] | null } }).data?.getLiveLocations ?? [];
return rows.filter(isRow);
},
+ /**
+ * Stores the caller's latest sealed position for one share and fans it out. The first accepted
+ * publish of a `sessionId` starts the share. Errors keep their `errorType` (`Throttled`,
+ * `LIVE_LOCATION_ENDED`, `CONVERSATION_SUSPENDED`, `Unauthorized`, `BadRequest`).
+ */
+ publishLiveLocation: async (
+ matchId: string,
+ sessionId: string,
+ ciphertext: string,
+ expiresAt: number
+ ): Promise => {
+ const res = await run(PUBLISH_LIVE_LOCATION, { matchId, sessionId, ciphertext, expiresAt });
+ void primeUnloadAuth();
+ const row = (res as { data?: { publishLiveLocation?: unknown } }).data?.publishLiveLocation;
+ return isRow(row) ? row : null;
+ },
+
+ /** Ends one of the caller's own shares. Idempotent, and allowed while the chat is suspended. */
+ stopLiveLocation: async (matchId: string, sessionId: string): Promise => {
+ const res = await run(STOP_LIVE_LOCATION, { matchId, sessionId });
+ const row = (res as { data?: { stopLiveLocation?: unknown } }).data?.stopLiveLocation;
+ return isRow(row) ? row : null;
+ },
+
+ primeUnloadAuth,
+ clearUnloadAuth,
+ stopOnUnload,
+
/** Follows live-location updates and ends for a match. Returns an unsubscribe function. */
subscribe: (matchId: string, onUpdate: (row: LiveLocationUpdate) => void): (() => void) => {
const sub = (
diff --git a/src/api/rest.ts b/src/api/rest.ts
index e9b4efa..e6d71cf 100644
--- a/src/api/rest.ts
+++ b/src/api/rest.ts
@@ -1,121 +1,27 @@
/**
- * Thin authenticated REST helper for the Matching endpoints whose request bodies the generated
- * Smithy SDK does not serialise the way the service expects (comment-to-like swipes, received likes,
- * roses, suggestions, traditions) and for the partner distance, which is not modelled:
+ * Matching and State endpoints with app-level types: partner distance, suggestions, traditions, chat
+ * settings, swipes, roses, received likes and the matching-tab flag.
*
- * • GET /matching/distance/{userId}
- * • POST /matching/swipe, GET /matching/likes, GET /matching/roses
- * • /matching/suggestions, /matching/traditions
+ * Every call goes through the generated `onehook-api-client` SDK (`sdkClient`); nothing here builds a
+ * URL or a request. `callSdk` turns SDK failures into the shared {@link ApiError}, so UI error handling
+ * can keep matching on it. `src/tests/api-route-contract.test.ts` fails the build on a hand-built
+ * request to a OneHook API.
*
* Every /matching/* route answers 403 MATCHING_OFF unless the caller's matching is ON, so nothing here
* may be called for a chat-only member (docs/chat-only-profiles.md §12). Blocks, reports and hook
- * requests are State routes and live in api/state.ts. The one State route here is
- * `PUT /state/matching/tab-hidden` (SetMatchingTabHidden), which the SDK does not model yet.
- *
- * It authenticates exactly like `sdk-client.ts` does — the Cognito **ID token** (falling back to the
- * access token) is read from the Amplify auth session and attached as a `Bearer` token — and it
- * throws the shared {@link ApiError} shape so existing UI error handling can pattern-match on it.
+ * requests are State routes and live in api/state.ts.
*/
-import { apiBaseUrl } from '../utils/env.config';
import { ApiError } from '../lib/api-client';
-import { bodyCode } from '../lib/api-errors';
-import { sdkClient } from './sdk-client';
+import { callSdk, sdkClient } from './sdk-client';
/**
- * Reads the caller's Cognito JWT the same way `sdk-client.ts` does: the ID token first (the API
- * Gateway Cognito authorizer validates it), falling back to the access token. Returns null when
- * unauthenticated so the request can still be attempted (and rejected by the server) rather than
- * throwing here.
+ * The SDK output without its `$metadata`, typed as the app's shape. The app types mirror the Smithy
+ * shapes (matching.smithy, state.smithy); the SDK marks required members `| undefined`, which the
+ * server never omits.
*/
-async function getAuthToken(): Promise {
- if (typeof window === 'undefined') return null;
- try {
- const { fetchAuthSession } = await import('aws-amplify/auth');
- const session = await fetchAuthSession();
- return session.tokens?.idToken?.toString() || session.tokens?.accessToken?.toString() || null;
- } catch {
- return null;
- }
-}
-
-/**
- * Resolve a relative API path against the configured base URL. Mirrors `sdk-client.ts`'s endpoint
- * resolution: on localhost the dev origin is used (the Vite proxy forwards `/matching`, `/chat`,
- * … to the backend), otherwise the absolute `apiBaseUrl` is used.
- */
-function resolveUrl(path: string): string {
- const suffix = path.startsWith('/') ? path : `/${path}`;
- if (
- typeof window !== 'undefined' &&
- (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1')
- ) {
- return window.location.origin + suffix;
- }
- if (apiBaseUrl) {
- if (apiBaseUrl.startsWith('http')) return apiBaseUrl + suffix;
- if (typeof window !== 'undefined' && window.location?.origin) {
- return window.location.origin + suffix;
- }
- return apiBaseUrl + suffix;
- }
- if (typeof window !== 'undefined' && window.location?.origin) {
- return window.location.origin + suffix;
- }
- return `http://localhost:3000${suffix}`;
-}
-
-async function request(
- method: 'GET' | 'POST' | 'PUT' | 'DELETE',
- path: string,
- body?: unknown
-): Promise {
- const token = await getAuthToken();
- const headers: Record = { Accept: 'application/json' };
- if (body !== undefined) headers['Content-Type'] = 'application/json';
- if (token) {
- headers['Authorization'] = `Bearer ${token}`;
- }
-
- let res: Response;
- try {
- res = await fetch(resolveUrl(path), {
- method,
- headers,
- body: body !== undefined ? JSON.stringify(body) : undefined,
- });
- } catch (err) {
- // Network/transport failure — surface as a 0-status ApiError so callers can distinguish it from
- // a server rejection.
- throw new ApiError(
- err instanceof Error ? err.message : 'Network request failed',
- 0,
- 'NETWORK_ERROR'
- );
- }
-
- // Parse the body once; tolerate empty (204) and non-JSON responses.
- const text = await res.text().catch(() => '');
- let parsed: unknown = undefined;
- if (text) {
- try {
- parsed = JSON.parse(text);
- } catch {
- parsed = text;
- }
- }
-
- if (!res.ok) {
- // Every OneHook API answers `{error: , code: }` (common.smithy ErrorBody).
- const error =
- parsed && typeof parsed === 'object' ? (parsed as { error?: unknown }).error : undefined;
- const message =
- (typeof error === 'string' && error) ||
- (typeof parsed === 'string' && parsed) ||
- `Request failed with status ${res.status}`;
- throw new ApiError(message, res.status, bodyCode(parsed), parsed);
- }
-
- return parsed as T;
+function body(out: object): T {
+ const { $metadata: _metadata, ...rest } = out as { $metadata?: unknown };
+ return rest as T;
}
// ── Distance ────────────────────────────────────────────────────────────────
@@ -132,7 +38,7 @@ export interface DistanceResponse {
export const DistanceApi = {
get: (userId: string): Promise =>
- request('GET', `/matching/distance/${encodeURIComponent(userId)}`),
+ callSdk(async () => body(await sdkClient.getPartnerDistance({ userId }))),
};
// ── Mr. OneHook suggestion ────────────────────────────────────────────────────
@@ -157,11 +63,18 @@ export interface MemberSuggestions {
/** The member's two asked-for suggestions (Super and above); each removable on its own. */
export const SuggestionApi = {
- get: (): Promise => request('GET', '/matching/suggestions'),
+ get: (): Promise =>
+ callSdk(async () => body(await sdkClient.getSuggestions({}))),
saveOwn: (prompt: string, reasoning: string): Promise<{ suggestionId: string }> =>
- request('POST', '/matching/suggestions', { prompt, reasoning }),
- removeOwn: (): Promise => request('DELETE', '/matching/suggestions'),
- removeOneHook: (): Promise => request('DELETE', '/matching/suggestions/onehook'),
+ callSdk(async () => body<{ suggestionId: string }>(await sdkClient.recordSuggestion({ prompt, reasoning }))),
+ removeOwn: (): Promise =>
+ callSdk(async () => {
+ await sdkClient.removeSuggestion({});
+ }),
+ removeOneHook: (): Promise =>
+ callSdk(async () => {
+ await sdkClient.removeOneHookSuggestion({});
+ }),
};
// ── Traditional matching systems (opt out per tradition) ──────────────────────
@@ -176,10 +89,17 @@ export interface TraditionSetting {
}
export const TraditionApi = {
- get: (): Promise<{ traditions: TraditionSetting[] }> => request('GET', '/matching/traditions'),
+ get: (): Promise<{ traditions: TraditionSetting[] }> =>
+ callSdk(async () =>
+ body<{ traditions: TraditionSetting[] }>(await sdkClient.getTraditionPreferences({}))
+ ),
/** Replaces the opt-outs; an empty list re-enrols in every tradition. */
setDisabled: (disabled: string[]): Promise<{ traditions: TraditionSetting[] }> =>
- request('PUT', '/matching/traditions', { disabled }),
+ callSdk(async () =>
+ body<{ traditions: TraditionSetting[] }>(
+ await sdkClient.updateTraditionPreferences({ disabled })
+ )
+ ),
};
// ── Chat settings ─────────────────────────────────────────────────────────────
@@ -231,26 +151,17 @@ export const ChatSettingsApi = {
// Backed by the generated SDK (GetChatSettings / UpdateChatSettings). The SDK serialiser only sends
// modelled members, so the SDK must model every field sent here (connectionNotifications and
// likeNotifications need the client generated from the current chat.smithy).
- get: async (): Promise => unwrapSettings(await sdkClient.getChatSettings({})),
+ get: (): Promise =>
+ callSdk(async () => unwrapSettings(await sdkClient.getChatSettings({}))),
/** Partial update: send only the fields that changed. */
- update: async (patch: Partial): Promise =>
- unwrapSettings(await sdkClient.updateChatSettings(patch)),
+ update: (patch: Partial): Promise =>
+ callSdk(async () => unwrapSettings(await sdkClient.updateChatSettings(patch))),
};
// ── Swipe (Hinge-style comment-to-like) & received likes ──────────────────────
-/**
- * The service now requires a comment + a liked profile element for every LIKE (RIGHT) and exposes a
- * "likes you" read side (GET /matching/likes). BUT the installed generated SDK
- * (`onehook-api-client@1.0.14`) still models `SwipeRequest` with only
- * `{ targetId, direction, viewedSection }` — it has NO `comment`, `likeTargetType` or
- * `likeTargetRef`, and no `GetReceivedLikes` operation at all. Rather than force the new fields
- * through the stale SDK (they would be silently dropped by the generated serializer), both calls go
- * through this thin REST helper — like the distance endpoint above — until a newer
- * SDK models them. The caller's identity is the verified Cognito sub that API Gateway injects as
- * `X-User-Id`; the Bearer token attached by {@link getAuthToken} is all this helper needs to send.
- */
+/** Every LIKE (RIGHT) carries a comment and the liked profile element. */
export type LikeTargetType = 'PHOTO' | 'VIDEO' | 'VOICE' | 'PROMPT' | 'INTEREST' | 'BIO';
/** Backend cap on a like comment (MatchingConstants.LIKE_COMMENT_MAX_CHARS). Enforced client-side. */
@@ -291,11 +202,9 @@ export const SwipeApi = {
* PASS (LEFT). Carries no comment or target — the server ignores both for LEFT anyway.
*/
pass: (targetId: string, viewedSection?: string): Promise =>
- request('POST', '/matching/swipe', {
- targetId,
- direction: 'LEFT',
- viewedSection,
- }),
+ callSdk(async () =>
+ body(await sdkClient.swipe({ targetId, direction: 'LEFT', viewedSection }))
+ ),
/**
* LIKE (RIGHT) — Hinge-style: always carries a comment plus the specific element being liked.
@@ -312,15 +221,19 @@ export const SwipeApi = {
/** ROSE = a daily-limited super-like (mirrors iOS `likeKind:"ROSE"`); defaults to a normal LIKE. */
likeKind?: 'LIKE' | 'ROSE';
}): Promise =>
- request('POST', '/matching/swipe', {
- targetId: input.targetId,
- direction: 'RIGHT',
- comment: input.comment,
- likeTargetType: input.likeTargetType,
- likeTargetRef: input.likeTargetRef,
- viewedSection: input.viewedSection,
- likeKind: input.likeKind,
- }),
+ callSdk(async () =>
+ body(
+ await sdkClient.swipe({
+ targetId: input.targetId,
+ direction: 'RIGHT',
+ comment: input.comment,
+ likeTargetType: input.likeTargetType,
+ likeTargetRef: input.likeTargetRef,
+ viewedSection: input.viewedSection,
+ likeKind: input.likeKind,
+ })
+ )
+ ),
};
/** Remaining daily rose (super-like) quota. Mirrors iOS `GET /matching/roses`. */
@@ -331,7 +244,8 @@ export interface RoseQuota {
}
export const RosesApi = {
- remaining: (): Promise => request('GET', '/matching/roses'),
+ remaining: (): Promise =>
+ callSdk(async () => body(await sdkClient.getRoses({}))),
};
export const ReceivedLikesApi = {
@@ -340,7 +254,7 @@ export const ReceivedLikesApi = {
* newest first. No input — identity is the injected `X-User-Id`.
*/
list: (): Promise =>
- request('GET', '/matching/likes'),
+ callSdk(async () => body(await sdkClient.getReceivedLikes({}))),
};
// ── Member reports (POST /state/reports) ───────────────────────────────────────
@@ -390,8 +304,7 @@ export interface CreateReportResponse {
/**
* State operation SetMatchingTabHidden (state.smithy): `PUT /state/matching/tab-hidden`
- * `{hidden}` -> 200 `{hidden}`; 400 on a missing or non-boolean `hidden`, 500 otherwise. It goes
- * through this helper because the installed `onehook-api-client` does not model the operation yet.
+ * `{hidden}` -> 200 `{hidden}`; 400 on a missing or non-boolean `hidden`, 500 otherwise.
* Callers use `StateApi.setMatchingTabHidden` (api/state.ts).
*/
export interface MatchingTabHiddenResponse {
@@ -399,13 +312,10 @@ export interface MatchingTabHiddenResponse {
}
export const MatchingTabApi = {
- setHidden: async (hidden: boolean): Promise => {
- const res = await request | undefined>(
- 'PUT',
- '/state/matching/tab-hidden',
- { hidden }
- );
- // The answer is authoritative; a body without it means the server stored what was sent.
- return { hidden: typeof res?.hidden === 'boolean' ? res.hidden : hidden };
- },
+ setHidden: (hidden: boolean): Promise =>
+ callSdk(async () => {
+ const res = await sdkClient.setMatchingTabHidden({ hidden });
+ // The answer is authoritative; a body without it means the server stored what was sent.
+ return { hidden: typeof res?.hidden === 'boolean' ? res.hidden : hidden };
+ }),
};
diff --git a/src/api/sdk-client.ts b/src/api/sdk-client.ts
index c8b1a73..ec29ccb 100644
--- a/src/api/sdk-client.ts
+++ b/src/api/sdk-client.ts
@@ -1,6 +1,8 @@
import { OneHook } from 'onehook-api-client';
import { apiBaseUrl, cognitoRegion } from '../utils/env.config';
import { FetchHttpHandler } from '@smithy/fetch-http-handler';
+import { ApiError } from '../lib/api-client';
+import { errorCode, errorMessage, errorStatus } from '../lib/api-errors';
async function getAuthToken(): Promise {
if (typeof window === 'undefined') return null;
@@ -111,3 +113,31 @@ sdkClient.middlewareStack.add(
},
{ step: 'finalizeRequest', name: 'stripAmzSdkHeaders', priority: 'low' }
);
+
+/**
+ * Runs one SDK call and rethrows any failure as the shared {@link ApiError}, so UI code that matches
+ * on `ApiError` (status, `code`, message) behaves the same whichever API it called. The SDK exception
+ * is kept as `details`, so `errorGaps` and other body fields stay readable.
+ */
+export async function callSdk(call: () => Promise): Promise {
+ try {
+ return await call();
+ } catch (err) {
+ throw toApiError(err);
+ }
+}
+
+export function toApiError(err: unknown): ApiError {
+ if (err instanceof ApiError) return err;
+ const status = errorStatus(err);
+ if (status === undefined) {
+ // No HTTP response: a network or transport failure.
+ return new ApiError(errorMessage(err, 'Network request failed'), 0, 'NETWORK_ERROR', err);
+ }
+ return new ApiError(
+ errorMessage(err, `Request failed with status ${status}`),
+ status,
+ errorCode(err),
+ err
+ );
+}
diff --git a/src/components/Chatbot/ChatbotWidget.tsx b/src/components/Chatbot/ChatbotWidget.tsx
index 2e1b21f..f8c4fd0 100644
--- a/src/components/Chatbot/ChatbotWidget.tsx
+++ b/src/components/Chatbot/ChatbotWidget.tsx
@@ -1,7 +1,6 @@
import React, { useState, useRef, useEffect } from 'react';
import { Mascot } from './Mascot';
-import { chatbotUrl } from '../../utils/env.config';
-import { PUBLIC_PRODUCT_CHAT_PATH } from '../../lib/mr-onehook-contract';
+import { mrOneHookClient } from '../../api/external-sdk-clients';
import { Maximize2, Minimize2, X } from 'lucide-react';
import { UiElement, trackProps } from '../../lib/analytics/analytics';
import './ChatbotWidget.css'; // Add a little standard CSS or use tailwind
@@ -208,18 +207,17 @@ export const ChatbotWidget: React.FC = ({ isVisible = true }
setMood('Thinking');
try {
- const response = await fetch(`${chatbotUrl}${PUBLIC_PRODUCT_CHAT_PATH}`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- messages: newMessages,
- userDemographics: { gender, sexualPreference },
- }),
- });
+ // PublicProductChat through the generated SDK (no auth). An HTTP failure is the "overwhelmed"
+ // reply below; a network error is the "can't connect" one.
+ const data = await mrOneHookClient
+ .publicProductChat({ messages: newMessages, userDemographics: { gender, sexualPreference } })
+ .catch((err: unknown) => {
+ if ((err as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode) return null;
+ throw err;
+ });
- if (response.ok) {
- const data = await response.json();
- setMessages([...newMessages, { role: 'assistant', content: data.reply }]);
+ if (data) {
+ setMessages([...newMessages, { role: 'assistant', content: data.reply ?? '' }]);
setMood(data.mood as Mood);
setHasError(false);
} else {
diff --git a/src/components/auth/Login.tsx b/src/components/auth/Login.tsx
index 9cd3b2e..27341fb 100644
--- a/src/components/auth/Login.tsx
+++ b/src/components/auth/Login.tsx
@@ -12,7 +12,7 @@ import { Seo } from '../common/Seo';
import { ROUTE_SEO } from '../../config/seo-routes';
import { SOCIALS } from '../common/socials';
import { useAppStore } from '../../store/app-store';
-import { normalizeUsername } from '../../lib/account-setup';
+import { normalizeUsername, passwordError, PASSWORD_RULES_COPY } from '../../lib/account-setup';
import { UiElement, trackProps, trackScreenView, Screen } from '../../lib/analytics/analytics';
/**
@@ -231,8 +231,10 @@ export function Login() {
setError(null);
try {
if (!code.trim()) throw new Error('Please enter the verification code');
- if (password.length < 8) throw new Error('Password must be at least 8 characters');
- if (password !== confirmPassword) throw new Error('Passwords do not match');
+ // Same rule as the user pool (12+ characters with a symbol), so a password the form accepts
+ // is never rejected by Cognito afterwards.
+ const invalid = passwordError(password, confirmPassword);
+ if (invalid) throw new Error(invalid);
setLoading(true);
await getCognitoAuth().confirmPasswordSet(submittedIdentifier, code.trim(), password);
showToast('Password set. Sign in with your new password.', 'success');
@@ -653,7 +655,7 @@ export function Login() {
id="new-password"
type="password"
autoComplete="new-password"
- placeholder="At least 8 characters"
+ placeholder={PASSWORD_RULES_COPY}
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={loading}
diff --git a/src/components/chat/AttachmentComposer.tsx b/src/components/chat/AttachmentComposer.tsx
index 820f045..19cbc60 100644
--- a/src/components/chat/AttachmentComposer.tsx
+++ b/src/components/chat/AttachmentComposer.tsx
@@ -1,11 +1,12 @@
import { useCallback, useEffect, useRef, useState, type ChangeEvent, type ReactNode, type RefObject } from 'react';
-import { Film, ImageIcon, Mic, Paperclip, Square, Trash2 } from 'lucide-react';
+import { Film, ImageIcon, MapPin, Mic, Paperclip, Square, Trash2, UserRound } from 'lucide-react';
import type { AttachmentKind } from '../../lib/chat-attachments';
import { downsampleWaveform } from '../../lib/attachment-media';
import { UiElement, trackProps } from '../../lib/analytics/analytics';
/**
- * Composer controls for attachments: a picker (image / video / file) and a voice-note recorder.
+ * Composer controls for attachments: a picker (image / video / file, plus location and contact cards
+ * when the conversation offers them) and a voice-note recorder.
*
* The voice-note affordance is feature-detected and HIDDEN where MediaRecorder or getUserMedia is
* unavailable (older Safari, insecure contexts), rather than shown and then failing at click time — a
@@ -16,6 +17,10 @@ interface AttachmentComposerProps {
disabled?: boolean;
onPickFile: (file: File, kind: AttachmentKind) => void;
onVoiceNote: (blob: Blob, mime: string, durationMs: number, waveform: number[]) => void;
+ /** Opens the location sheet (current location or a live share). Hidden when absent. */
+ onPickLocation?: () => void;
+ /** Opens the contact flow. Hidden when absent. */
+ onPickContact?: () => void;
}
/** MediaRecorder + microphone access are required to record; both must exist for the mic to appear. */
@@ -28,7 +33,7 @@ function voiceNotesSupported(): boolean {
);
}
-export function AttachmentComposer({ disabled, onPickFile, onVoiceNote }: AttachmentComposerProps) {
+export function AttachmentComposer({ disabled, onPickFile, onVoiceNote, onPickLocation, onPickContact }: AttachmentComposerProps) {
const [menuOpen, setMenuOpen] = useState(false);
const imageInputRef = useRef(null);
const videoInputRef = useRef(null);
@@ -67,11 +72,34 @@ export function AttachmentComposer({ disabled, onPickFile, onVoiceNote }: Attach
setMenuOpen(false)} aria-hidden="true" data-track-exempt="backdrop: click-away that closes the attachment menu." />
);
}
diff --git a/src/components/mascot/README.md b/src/components/mascot/README.md
index 3a73df1..fe54006 100644
--- a/src/components/mascot/README.md
+++ b/src/components/mascot/README.md
@@ -1,7 +1,7 @@
# OneHook Mascot
-The official OneHook mascot — a friendly pink, egg‑shaped character with big
-expressive eyes and a cheerful wave. It adds warmth and personality next to
+The official OneHook mascot (Mr.OneHook): a friendly pink, egg‑shaped character with big
+expressive eyes, holding a paint brush and a paint bucket. It adds warmth and personality next to
product copy without distracting from it.
> Note: the source files are still named `AlienScanner.tsx` /
@@ -12,14 +12,17 @@ product copy without distracting from it.
## 🎨 Design Concept
- **Pink egg body** with a soft top‑left gloss highlight.
-- **Big friendly eyes** — white sclera, blue iris, dark pupil and a white
+- **Big friendly eyes**: white sclera, blue iris, dark pupil and a white
catch‑light. On the web the eyes softly track the cursor.
-- **Happy open mouth** that gently animates (breathing).
-- **Waving hand** — the raised right arm waves on a loop for engagement.
-- **Little arms & legs** with rounded hands and feet.
-- **Gentle breathing** — the body subtly scales for life.
-
-There is **no** floating/teleporting movement, no lasers, and no antennae — the
+- **Happy open mouth** that gently animates.
+- **Raised right arm holding a paint brush**, swaying gently on a 4 s loop.
+- **Left arm holding a paint bucket**, which swings only in the excited state.
+- **Little legs** with rounded feet, and a soft ground shadow.
+- **Gentle breathing**: the body subtly scales for life.
+- **Silver sparkle ring** (`AiSparkle`) behind the character, with the labels "AI Inside",
+ "Understanding", "Privacy Intact" and "100% encrypted". It animates in when scrolled into view.
+
+There is **no** floating/teleporting movement, no lasers, and no antennae; the
mascot is placed statically beside content.
---
@@ -39,8 +42,17 @@ import { AlienScanner } from '@/components/mascot';
+
+// Interactive (excited on hover / keyboard focus, clickable)
+ setOpen(true)} />
+
+// Just the character, no brush, bucket, shadow or sparkle ring
+
```
+Current call sites: `src/components/Landing.tsx` (interactive, `forceExcited`, `hideTooltips`) and
+`src/components/messenger/Messenger.tsx` (`hideTooltips`, mostly `bare`).
+
### Props
| Prop | Type | Default | Description |
@@ -50,18 +62,40 @@ import { AlienScanner } from '@/components/mascot';
| `scanColor` | `string` | `#0052CC` | Eye iris colour. |
| `className` | `string` | – | Class applied to the wrapper `div`. |
| `style` | `React.CSSProperties` | – | Inline style for the wrapper `div`. |
+| `onClick` | `() => void` | – | Makes the mascot interactive: renders a `
)}
+ {myShare && (
+
+
+
+
+ Sharing your live location with {peerName} until {formatClockTime(myShare.expiresAt, Date.now())}.
+ {' '}
+ {TAB_BOUND_COPY}
+