From ba62b64648a03ccc1f6e213ffe794ecc57244cfc Mon Sep 17 00:00:00 2001 From: Pushp Date: Tue, 17 Nov 2026 18:11:07 +0530 Subject: [PATCH] feat(api): call the portal and Mr OneHook through their published SDKs; onehook-api-client 1.0.44 - saha-equation-admin-portal-client (renamed from onehook-admin-portal-client) and onehook-mr-onehook-client; onehook-api-client 1.0.44 (telemetry 1.24.0) - route contract: the live-location unload stop (AppSync keepalive fetch) is a listed exception - contact sheet test matches the checkbox attributes in any order --- CRUX.md | 248 ++++--- README.md | 401 ++++++++--- docs/FRONTEND_PRODUCTION.md | 643 +++++------------- docs/LANDING_PAGE.md | 327 ++++++--- docs/LEGAL_PAGES.md | 236 +++++-- docs/LOGIN_SETUP.md | 311 ++++----- docs/ONBOARDING_SKIP_LOGOUT.md | 505 +++++--------- docs/README.md | 25 +- package-lock.json | 316 ++++++++- package.json | 4 +- public/media/og/onehook-og-science.png | Bin 0 -> 73063 bytes src/api/analytics.ts | 110 +-- src/api/chat.ts | 120 ++-- src/api/external-sdk-clients.ts | 125 ++++ src/api/live-location.ts | 158 ++++- src/api/rest.ts | 222 ++---- src/api/sdk-client.ts | 30 + src/components/Chatbot/ChatbotWidget.tsx | 24 +- src/components/auth/Login.tsx | 10 +- src/components/chat/AttachmentComposer.tsx | 36 +- src/components/chat/ContactShareSheet.tsx | 504 ++++++++++++++ src/components/chat/LocationShareSheet.tsx | 324 +++++++++ .../chat/StructuredMessageBubble.tsx | 30 +- src/components/mascot/README.md | 90 ++- src/config/dev-proxy.ts | 42 ++ src/config/seo-routes.ts | 2 + src/features/chat/ChatView.tsx | 171 ++++- .../moderation/report/evidence-api.ts | 99 ++- src/hooks/use-api.ts | 15 + src/hooks/use-live-sharing.ts | 68 ++ src/hooks/use-user-location.ts | 19 +- src/lib/analytics/analyticsClient.ts | 31 - src/lib/analytics/generated/apiManifest.ts | 25 +- .../analytics/generated/telemetryCatalog.ts | 14 +- src/lib/browser-location.ts | 212 ++++++ src/lib/chat-structured.ts | 126 +++- src/lib/contact-share.ts | 244 +++++++ src/lib/live-location-sharing.ts | 639 +++++++++++++++++ src/lib/mr-onehook-contract.ts | 5 - src/lib/mr-onehook.ts | 113 +-- src/tests/api-route-contract.test.ts | 201 +++++- src/tests/api-route-scan.ts | 117 +++- src/tests/chat-location-contact.test.ts | 6 +- .../chat-settings-notifications.test.tsx | 2 +- src/tests/contact-share.test.ts | 202 ++++++ src/tests/dev-proxy.test.ts | 31 + src/tests/live-location-api.test.ts | 119 ++++ src/tests/live-location-sharing.test.ts | 552 +++++++++++++++ .../location-contact-send-render.test.tsx | 193 ++++++ src/tests/location-send.test.ts | 209 ++++++ src/tests/matching-tab.test.tsx | 31 +- src/tests/mr-onehook-contract.test.ts | 9 - src/tests/password-rule.test.ts | 37 + src/tests/photo-stats.test.ts | 46 +- src/tests/report-evidence-outcomes.test.ts | 6 +- src/tests/report-submit.test.ts | 7 + src/tests/support/sdk-fetch-handler.ts | 36 + src/tests/telemetry-sdk.test.ts | 40 +- vite.config.ts | 29 +- 59 files changed, 6420 insertions(+), 2077 deletions(-) create mode 100644 public/media/og/onehook-og-science.png create mode 100644 src/api/external-sdk-clients.ts create mode 100644 src/components/chat/ContactShareSheet.tsx create mode 100644 src/components/chat/LocationShareSheet.tsx create mode 100644 src/config/dev-proxy.ts create mode 100644 src/hooks/use-live-sharing.ts create mode 100644 src/lib/browser-location.ts create mode 100644 src/lib/contact-share.ts create mode 100644 src/lib/live-location-sharing.ts create mode 100644 src/tests/contact-share.test.ts create mode 100644 src/tests/dev-proxy.test.ts create mode 100644 src/tests/live-location-api.test.ts create mode 100644 src/tests/live-location-sharing.test.ts create mode 100644 src/tests/location-contact-send-render.test.tsx create mode 100644 src/tests/location-send.test.ts create mode 100644 src/tests/password-rule.test.ts create mode 100644 src/tests/support/sdk-fetch-handler.ts 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 0000000000000000000000000000000000000000..bab44556eb09bd4a214c1205838178af0f422065 GIT binary patch literal 73063 zcmeEuWmjC=7Ay&F!JXjlY24ji8n*;@2=4CgmWJRC!Gl|HcZZ^4Q7x+5Y|7x}h6r*nC65eDjxYXMf2tA2jeQ z|2`@{r6~Wtf)Y`ED~j-+*OEvu=HH(LP?**5h9q?q1;6?C2gX$2+)Ze={&#=>i{}63_Wz34 z|6iqi`){4R#mwe*@H?p;gxmOaP!KP4HAMN?c6V5kYgliNy8dSyuZzci?fY6=lilj= zMIYL1toS?L-9J0=7SB5ZvbjE|Hb%1?v7SAzFLzzw3eD4{+JgG}`tow?hnvH260d`k z<@#%%?;r8cJ0H&&Yuaa~rV@$$<$$XGqAVOXf~QAP3oIsPwaEiL!0A4F$&EmXy|oF zO;`;)Ds&tldqaxk(`O>ej>w{0CVFmV&lmT@Bq%OdY-&25Z&#U_nQ!1EDKNbF;{(!dmUhvNEfmzLpgH-5pf1yX=K(WhCzXJ5HX9Uxj-;lY~AfCb!UJ zkG~u$`|H+z3au}a6~VkLAbqAAABFdY^CGz0@Mcv!fG|UXejhJR<_hQDTy%rzAxfhr zOsuRH&|+_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)|N3AgQlne*PD)bpaJA#H=~sFQuwjwXR03liy^C`UFz|Ij(WEF58lm@# zICM*F9d|CdzhiG;!_adT7|t99aH}m3StzGo>nWd}nW4cK0_XyO5j83!;j#OY(KawL z()$zW$;$NVP)`}62eYLjw?z4jOk~o*x!D}yl<6wG|H|O73v7M=*%y?g!FHx5F5U$; zhVVNgagy97^I_@hDX_DHhB)gDBY^d{o9OD!1C~#t{UL2|H-I}`5pwgas|1$SM!mu!!me> z$Ox-|GX&e8J%P-Wk4CYzWA*}e`~%?nL*NDudQb-p9%Ajz4pKJ9A^g&TUcDhiW4A7c}nmntmMii#P-xI-u|hhTzh`$ zBQq-W2S&38gcGncT7q#@HCI;D%!zu(4$z@Gwj9+1`+Qy0jR*k|hKR7U#j_{YA})W|tS#$dp@wo& L%97>cZv+1q@F%gk literal 0 HcmV?d00001 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." />
} label="Photo" onClick={() => pick(imageInputRef)} trackAttrs={trackProps(UiElement.CHAT_ATTACH_OPTION, { value: 'photo_video' })} /> } label="Video" onClick={() => pick(videoInputRef)} trackAttrs={trackProps(UiElement.CHAT_ATTACH_OPTION, { value: 'photo_video' })} /> } label="File" onClick={() => pick(fileInputRef)} trackAttrs={trackProps(UiElement.CHAT_ATTACH_OPTION, { value: 'file' })} /> + {onPickLocation && ( + } + label="Location" + onClick={() => { + setMenuOpen(false); + onPickLocation(); + }} + trackAttrs={trackProps(UiElement.CHAT_ATTACH_OPTION, { value: 'location' })} + /> + )} + {onPickContact && ( + } + label="Contact" + onClick={() => { + setMenuOpen(false); + // Called inside the click: the browser only opens its contact picker on a gesture. + onPickContact(); + }} + trackAttrs={trackProps(UiElement.CHAT_ATTACH_OPTION, { value: 'contact' })} + /> + )}
)} diff --git a/src/components/chat/ContactShareSheet.tsx b/src/components/chat/ContactShareSheet.tsx new file mode 100644 index 0000000..ff55ab8 --- /dev/null +++ b/src/components/chat/ContactShareSheet.tsx @@ -0,0 +1,504 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { Loader2, Mail, Phone, Send, UserRound, X } from 'lucide-react'; +import { UiElement, trackProps } from '../../lib/analytics/analytics'; +import { + EMPTY_CONTACT_FORM, + MAX_CONTACT_TEXT, + buildSelectedContactPayload, + contactPickerProperties, + contactsManager, + draftFromForm, + normalizeRows, + pickContact, + selectAll, + validateContactForm, + type ContactDraft, + type ContactFormValues, + type ContactSelection, +} from '../../lib/contact-share'; + +/** + * Sending a contact card (attachment menu → Contact). + * + * Where the browser has the Contact Picker API (Chrome on Android) the menu opens the device's picker + * straight away; the picked card is then reviewed here, and the member unticks any phone or email they + * do not want to share (all are included by default). Everywhere else this sheet is a small form: + * a name (required), phones and emails; everything typed is sent. + * + * The card is sent like any message: framed as structured content and sealed end to end on device. + */ + +// ── Opening ────────────────────────────────────────────────────────────────── + +/** Square JPEG of the contact photo, base64 without the data: prefix. Null when it cannot be drawn. */ +async function encodeSquareJpeg(blob: Blob, size: number, quality: number): Promise { + if (typeof createImageBitmap !== 'function' || typeof document === 'undefined') return null; + const bitmap = await createImageBitmap(blob); + try { + const side = Math.min(bitmap.width, bitmap.height); + if (!side) return null; + const canvas = document.createElement('canvas'); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext('2d'); + if (!ctx) return null; + ctx.drawImage(bitmap, (bitmap.width - side) / 2, (bitmap.height - side) / 2, side, side, 0, 0, size, size); + const url = canvas.toDataURL('image/jpeg', quality); + const comma = url.indexOf(','); + return url.startsWith('data:image/jpeg') && comma > 0 ? url.slice(comma + 1) : null; + } finally { + bitmap.close?.(); + } +} + +export interface ContactShareState { + open: boolean; + /** The picked contact under review, or null for the manual form. */ + picked: ContactDraft | null; + pickerAvailable: boolean; +} + +/** + * Opens the contact flow. `openContact` must be called from the menu's click handler: the browser + * only opens its contact picker during a user gesture. + */ +export function useContactShare() { + const [state, setState] = useState({ open: false, picked: null, pickerAvailable: false }); + // The picker's supported properties are read ahead of time, so the click itself only calls select(). + const supported = useRef(null); + useEffect(() => { + const manager = contactsManager(); + if (!manager?.getProperties) return; + manager + .getProperties() + .then((props) => { + supported.current = props; + }) + .catch(() => undefined); + }, []); + + const runPicker = useCallback((keepOpenOnCancel: boolean) => { + const manager = contactsManager(); + if (!manager) { + setState({ open: true, picked: null, pickerAvailable: false }); + return; + } + void pickContact(manager, contactPickerProperties(supported.current), encodeSquareJpeg).then((result) => { + if (result.kind === 'picked') setState({ open: true, picked: result.draft, pickerAvailable: true }); + // The picker could not open here: fall back to typing the contact in. + else if (result.kind === 'failed') setState({ open: true, picked: null, pickerAvailable: false }); + // Cancelled: nothing to send. A sheet already open (choosing another contact) stays as it was. + else if (!keepOpenOnCancel) setState((prev) => ({ ...prev, open: false })); + }); + }, []); + + const openContact = useCallback(() => runPicker(false), [runPicker]); + const pickAgain = useCallback(() => runPicker(true), [runPicker]); + const close = useCallback(() => setState((prev) => ({ ...prev, open: false, picked: null })), []); + + return { state, openContact, pickAgain, close }; +} + +// ── The sheet ──────────────────────────────────────────────────────────────── + +interface ContactShareSheetProps { + state: ContactShareState; + peerName: string; + onPickAgain: () => void; + onClose: () => void; + /** Sends the framed card. Throws (with a message to show) when it could not be sent. */ + onSend: (payload: Record) => Promise; +} + +export function ContactShareSheet({ state, peerName, onPickAgain, onClose, onSend }: ContactShareSheetProps) { + const [values, setValues] = useState(EMPTY_CONTACT_FORM); + const [nameTouched, setNameTouched] = useState(false); + const [selection, setSelection] = useState({ phones: [], emails: [] }); + const [busy, setBusy] = useState(false); + const [sendError, setSendError] = useState(null); + + useEffect(() => { + if (!state.open) return; + setValues(EMPTY_CONTACT_FORM); + setNameTouched(false); + setBusy(false); + setSendError(null); + }, [state.open]); + + useEffect(() => { + setSelection(state.picked ? selectAll(state.picked) : { phones: [], emails: [] }); + }, [state.picked]); + + useEffect(() => { + if (!state.open) return; + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape' && !busy) onClose(); + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, [state.open, busy, onClose]); + + if (!state.open) return null; + + const send = async () => { + let payload: Record; + if (state.picked) { + payload = buildSelectedContactPayload(state.picked, selection); + } else { + setNameTouched(true); + if (!validateContactForm(values).valid) return; + const draft = draftFromForm(values); + payload = buildSelectedContactPayload(draft, selectAll(draft)); + } + setBusy(true); + setSendError(null); + try { + await onSend(payload); + onClose(); + } catch (err) { + setSendError(err instanceof Error && err.message ? err.message : "That contact couldn't be sent. Try again."); + } finally { + setBusy(false); + } + }; + + return ( + setValues({ ...next, phones: normalizeRows(next.phones), emails: normalizeRows(next.emails) })} + onTouchName={() => setNameTouched(true)} + onToggle={(field, index, included) => + setSelection((prev) => { + const list = [...prev[field]]; + list[index] = included; + return { ...prev, [field]: list }; + }) + } + onPickAgain={onPickAgain} + onClose={onClose} + onSend={() => void send()} + /> + ); +} + +export interface ContactShareSheetViewProps { + peerName: string; + picked: ContactDraft | null; + pickerAvailable: boolean; + values: ContactFormValues; + nameTouched: boolean; + selection: ContactSelection; + busy: boolean; + sendError: string | null; + onChangeValues: (values: ContactFormValues) => void; + onTouchName: () => void; + onToggle: (field: 'phones' | 'emails', index: number, included: boolean) => void; + onPickAgain: () => void; + onClose: () => void; + onSend: () => void; +} + +const INPUT = + 'w-full px-3 py-2 rounded-lg border border-border bg-surface text-sm text-text placeholder:text-text-secondary/60 focus:outline-none focus:border-accent'; + +/** The sheet's markup, without effects (rendered statically in tests). */ +export function ContactShareSheetView({ + peerName, + picked, + pickerAvailable, + values, + nameTouched, + selection, + busy, + sendError, + onChangeValues, + onTouchName, + onToggle, + onPickAgain, + onClose, + onSend, +}: ContactShareSheetViewProps) { + const validation = validateContactForm(values); + const canSend = !busy && (picked ? true : validation.valid); + const nameError = nameTouched ? validation.errors.name : undefined; + + return ( +
!busy && onClose()} + data-track-exempt="backdrop: click-away that closes the contact sheet; the close button (chat.attach_button dismiss) is tracked." + > +
e.stopPropagation()} + data-track-exempt="backdrop: dialog container; only stops clicks inside the sheet from closing it." + > +
+

+ Share a contact +

+ +
+ +
+ {picked ? ( + + ) : ( + + )} + + {picked && pickerAvailable && ( + + )} + + {sendError && ( +

+ {sendError} +

+ )} +

+ {peerName} gets these details as a contact card, end-to-end encrypted. +

+
+ +
+ +
+
+
+ ); +} + +function PickedReview({ + picked, + selection, + busy, + onToggle, +}: { + picked: ContactDraft; + selection: ContactSelection; + busy: boolean; + onToggle: (field: 'phones' | 'emails', index: number, included: boolean) => void; +}) { + const hasFields = picked.phones.length > 0 || picked.emails.length > 0; + return ( +
+
+ {picked.thumbnailBase64 ? ( + + ) : ( + + )} +
+

{picked.displayName}

+ {picked.organization &&

{picked.organization}

} +
+
+ {hasFields && ( +
+ Choose what to share + {picked.phones.map((phone, i) => ( + + ))} + {picked.emails.map((email, i) => ( + + ))} +
+ )} +
+ ); +} + +function ManualForm({ + values, + nameError, + rowErrors, + busy, + onChangeValues, + onTouchName, +}: { + values: ContactFormValues; + nameError?: string; + rowErrors: { phones: (string | undefined)[]; emails: (string | undefined)[] }; + busy: boolean; + onChangeValues: (values: ContactFormValues) => void; + onTouchName: () => void; +}) { + const setRow = (field: 'phones' | 'emails', index: number, value: string) => { + const rows = [...values[field]]; + rows[index] = value; + onChangeValues({ ...values, [field]: rows }); + }; + return ( +
+
+ + onChangeValues({ ...values, name: e.target.value })} + onBlur={onTouchName} + aria-invalid={Boolean(nameError)} + aria-describedby={nameError ? 'contact-share-name-error' : undefined} + className={INPUT} + /> + {nameError && ( +

+ {nameError} +

+ )} +
+
+ + onChangeValues({ ...values, organization: e.target.value })} + className={INPUT} + /> +
+ + +
+ ); +} + +function RowGroup({ + label, + field, + type, + rows, + errors, + onChange, +}: { + label: string; + field: 'phones' | 'emails'; + type: 'tel' | 'email'; + rows: string[]; + errors: (string | undefined)[]; + onChange: (field: 'phones' | 'emails', index: number, value: string) => void; +}) { + const singular = field === 'phones' ? 'Phone number' : 'Email address'; + return ( +
+

+ {label} (optional) +

+ {rows.map((value, i) => ( +
+ onChange(field, i, e.target.value)} + aria-label={`${singular} ${i + 1}`} + aria-invalid={Boolean(errors[i])} + placeholder={i === rows.length - 1 && rows.length > 1 ? `Add another ${singular.toLowerCase()}` : undefined} + className={INPUT} + /> + {errors[i] &&

{errors[i]}

} +
+ ))} +
+ ); +} diff --git a/src/components/chat/LocationShareSheet.tsx b/src/components/chat/LocationShareSheet.tsx new file mode 100644 index 0000000..768a3d5 --- /dev/null +++ b/src/components/chat/LocationShareSheet.tsx @@ -0,0 +1,324 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { ArrowLeft, Loader2, MapPin, Radio, Send, X } from 'lucide-react'; +import { UiElement, trackProps, trackUi } from '../../lib/analytics/analytics'; +import type { LocationFix } from '../../lib/chat-structured'; +import { LOCATION_ERROR_COPY, LocationReadError, getCurrentFix, type LocationErrorKind } from '../../lib/browser-location'; +import { formatClockTime } from '../../lib/live-location'; +import { LIVE_DURATIONS, TAB_BOUND_COPY, type LiveDurationValue, type LiveShareView } from '../../lib/live-location-sharing'; +import { formatAccuracy, formatCoordinatesForDisplay } from '../../lib/map-links'; + +/** + * The location sheet (attachment menu → Location): the member's current position as a tile-free card, + * "Send your current location", and "Share live location" for 15 minutes, 1 hour or 8 hours. + * + * PRIVACY: the position is read on device and only leaves it sealed, inside the message (or the live + * update) for this conversation. No map tiles, no geocoding: the preview is the coordinates and their + * accuracy. The web cannot share in the background, so every place a live share is started says + * "Location won't update if you close this tab." + */ + +export type LocationSheetPhase = + | { kind: 'locating' } + | { kind: 'ready'; fix: LocationFix } + | { kind: 'error'; error: LocationErrorKind }; + +export type LocationSheetStep = 'main' | 'duration'; + +interface LocationShareSheetProps { + open: boolean; + peerName: string; + /** This tab's running share in the conversation, if any: starting a new one replaces it. */ + runningShare?: LiveShareView; + onClose: () => void; + /** Sends the current position. Throws (with a message to show) when it could not be sent. */ + onSendCurrent: (fix: LocationFix) => Promise; + /** Starts a live share. Throws (with a message to show) when it could not be started. */ + onStartLive: (fix: LocationFix, durationMs: number) => Promise; +} + +export function LocationShareSheet({ open, peerName, runningShare, onClose, onSendCurrent, onStartLive }: LocationShareSheetProps) { + const [phase, setPhase] = useState({ kind: 'locating' }); + const [step, setStep] = useState('main'); + const [busy, setBusy] = useState(false); + const [sendError, setSendError] = useState(null); + const attempt = useRef(0); + + const locate = useCallback(() => { + const id = ++attempt.current; + setPhase({ kind: 'locating' }); + getCurrentFix() + .then((fix) => { + if (attempt.current === id) setPhase({ kind: 'ready', fix }); + }) + .catch((err: unknown) => { + if (attempt.current !== id) return; + setPhase({ kind: 'error', error: err instanceof LocationReadError ? err.kind : 'unavailable' }); + }); + }, []); + + useEffect(() => { + if (!open) { + attempt.current += 1; // a late answer for a closed sheet is ignored + return; + } + setStep('main'); + setBusy(false); + setSendError(null); + locate(); + }, [open, locate]); + + const close = useCallback(() => { + // Leaving the duration chooser without picking one is its `dismiss`. + if (step === 'duration') trackUi(UiElement.CHAT_LIVE_LOCATION_DURATION, { action: 'dismiss' }); + onClose(); + }, [step, onClose]); + + useEffect(() => { + if (!open) return; + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape' && !busy) close(); + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, [open, busy, close]); + + if (!open) return null; + + const run = async (action: () => Promise) => { + setBusy(true); + setSendError(null); + try { + await action(); + onClose(); + } catch (err) { + setSendError(err instanceof Error && err.message ? err.message : "That couldn't be sent. Try again."); + } finally { + setBusy(false); + } + }; + + return ( + phase.kind === 'ready' && void run(() => onSendCurrent(phase.fix))} + onChooseLive={() => setStep('duration')} + onBack={() => { + trackUi(UiElement.CHAT_LIVE_LOCATION_DURATION, { action: 'dismiss' }); + setStep('main'); + }} + onChooseDuration={(ms) => phase.kind === 'ready' && void run(() => onStartLive(phase.fix, ms))} + /> + ); +} + +const PRIMARY = + 'w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl bg-ig-blue text-white text-sm font-semibold hover:opacity-90 disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed'; +const SECONDARY = + 'w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl border border-border text-sm font-semibold hover:bg-surface-hover disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed'; + +export interface LocationShareSheetViewProps { + peerName: string; + phase: LocationSheetPhase; + step: LocationSheetStep; + busy: boolean; + sendError: string | null; + runningShare?: LiveShareView; + now: number; + onClose: () => void; + onRetry: () => void; + onSendCurrent: () => void; + onChooseLive: () => void; + onBack: () => void; + onChooseDuration: (ms: number, value: LiveDurationValue) => void; +} + +/** The sheet's markup, without effects (rendered statically in tests). */ +export function LocationShareSheetView({ + peerName, + phase, + step, + busy, + sendError, + runningShare, + now, + onClose, + onRetry, + onSendCurrent, + onChooseLive, + onBack, + onChooseDuration, +}: LocationShareSheetViewProps) { + const ready = phase.kind === 'ready' && !busy; + return ( +
!busy && onClose()} + data-track-exempt="backdrop: click-away that closes the location sheet; the close button (chat.attach_button dismiss) is tracked." + > +
e.stopPropagation()} + data-track-exempt="backdrop: dialog container; only stops clicks inside the sheet from closing it." + > +
+
+ {step === 'duration' && ( + + )} +

+ {step === 'duration' ? 'Share live location' : 'Share location'} +

+
+ +
+ +
+ + + {step === 'main' ? ( +
+ +
+ +

{TAB_BOUND_COPY}

+
+
+ ) : ( +
+

+ {peerName} sees your location move until the time runs out or you stop.{' '} + {TAB_BOUND_COPY} +

+ {runningShare && ( +

+ This replaces the live share running until {formatClockTime(runningShare.expiresAt, now)}. +

+ )} +
+ {LIVE_DURATIONS.map((d) => ( + + ))} +
+
+ )} + + {busy && ( +

+

+ )} + {sendError && ( +

+ {sendError} +

+ )} +

+ Only {peerName} can see it. It is end-to-end encrypted, and OneHook never sees where you are. +

+
+
+
+ ); +} + +function LocationPreview({ phase, onRetry }: { phase: LocationSheetPhase; onRetry: () => void }) { + if (phase.kind === 'locating') { + return ( +
+
+
+

Finding your location…

+
+ ); + } + if (phase.kind === 'error') { + return ( +
+

{LOCATION_ERROR_COPY[phase.error]}

+ {phase.error !== 'unsupported' && ( + + )} +
+ ); + } + const { fix } = phase; + return ( +
+ +
+

Your current location

+

{formatCoordinatesForDisplay(fix.lat, fix.lon)}

+ {fix.accuracyM !== undefined && ( +

Accuracy {formatAccuracy(fix.accuracyM)}

+ )} +
+
+ ); +} diff --git a/src/components/chat/StructuredMessageBubble.tsx b/src/components/chat/StructuredMessageBubble.tsx index 65280a3..de3c7fb 100644 --- a/src/components/chat/StructuredMessageBubble.tsx +++ b/src/components/chat/StructuredMessageBubble.tsx @@ -1,5 +1,5 @@ import { useState } from 'react'; -import { AlertTriangle, Download, Mail, MapPin, Navigation, Phone } from 'lucide-react'; +import { AlertTriangle, CircleStop, Download, Mail, MapPin, Navigation, Phone } from 'lucide-react'; import { UiElement, trackProps, trackUi } from '../../lib/analytics/analytics'; import type { ContactContent, @@ -27,11 +27,13 @@ import { type MapsApp, } from '../../lib/map-links'; import { buildVCard, vCardFileName } from '../../lib/vcard'; +import { TAB_BOUND_COPY } from '../../lib/live-location-sharing'; import { useNow } from '../../hooks/use-live-locations'; /** * Renders a structured-content message (OneHookBackend/docs/chat-location-contact.md): a current - * location, a live-location share or a contact card. Web receives and opens only. + * location, a live-location share or a contact card, from either member. The member's own running + * live share has a Stop button. * * PRIVACY: nothing here talks to a network. Maps are drawn on device as a tile-free card; the only way * coordinates leave the device is a link the user taps, to the maps app they picked. The vCard is built @@ -46,6 +48,13 @@ export interface LiveLocationContext { currentUserId: string; peerId?: string; peerName: string; + /** + * Stops one of the member's own shares (this tab's, or one started on another device: the backend + * lets the owner stop any of theirs). Own live bubbles show a Stop button when present. + */ + onStopShare?: (sessionId: string) => void; + /** The sessionId of the share this tab is running in the conversation, if any. */ + sharingHereSessionId?: string; } interface StructuredMessageBubbleProps { @@ -370,6 +379,23 @@ function LiveLocationCard({ )} + {mine && live.onStopShare && ( +
+ {live.sharingHereSessionId === start.sessionId && ( +

{TAB_BOUND_COPY}

+ )} + +
+ )}
); } 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 ` + )} + + )} + ); } if (decoded.type === 'attachment') { @@ -1125,19 +1171,36 @@ function MatchConversation({ hasUndecryptable, historyHorizon, decryptPayload, + sealPayload, } = useChatMessages(matchId, peerId); // Live-location shares: running shares on open, then onLiveLocation. Positions open on device. const liveLocations = useLiveLocations(matchId, decryptPayload); + // This tab's own sharing (the tab-bound engine): the running share here, and shares it just ended so + // their bubbles read "Ended" at once instead of after the server's echo. + const sharing = useLiveSharing(); + const myShare = sharing.shares[matchId]; + const sessions = useMemo( + () => withLocalEnds(liveLocations.sessions, sharing.ended, matchId, currentUserId, Date.now(), mergeLiveSession), + [liveLocations.sessions, sharing.ended, matchId, currentUserId] + ); + const stopShare = useCallback( + (sessionId: string) => void liveSharing().stopRemote(matchId, sessionId), + [matchId] + ); const liveContext: LiveLocationContext = useMemo( () => ({ - sessions: liveLocations.sessions, + sessions, loadedAt: liveLocations.loadedAt, currentUserId, peerId, peerName, + onStopShare: stopShare, + sharingHereSessionId: myShare?.sessionId, }), - [liveLocations.sessions, liveLocations.loadedAt, currentUserId, peerId, peerName] + [sessions, liveLocations.loadedAt, currentUserId, peerId, peerName, stopShare, myShare?.sessionId] ); + const [locationOpen, setLocationOpen] = useState(false); + const contactShare = useContactShare(); const [input, setInput] = useState(''); // Snapshot of decrypted messages for the optional evidence share. Text comes from the SAME local @@ -1312,6 +1375,54 @@ function MatchConversation({ [dispatchAttachment] ); + /** + * Sends a location or contact card: framed as structured content (0x03) and sealed by sendMessage + * like any text, with no contentType, so the backend cannot tell it from a typed message. Throws a + * message for the sheet to show. + */ + const sendStructured = useCallback( + async (payload: Record) => { + let sent: Awaited>; + try { + sent = await sendMessage(frameStructuredContent(payload)); + } catch (err) { + if (isConversationSuspended(err)) { + onSuspended?.(); + throw new Error(`${HOOK_COPY.suspendedTitle}.`); + } + throw err; + } + if (!sent) throw new Error("This chat isn't ready yet. Try again in a moment."); + eligibility.recheck(); + }, + [sendMessage, onSuspended, eligibility.recheck] + ); + + const sendCurrentLocation = useCallback( + (fix: LocationFix) => sendStructured(buildLocationPayload(fix)), + [sendStructured] + ); + + /** + * Starts a live share from this tab: stop the one running here first (one share per member per + * conversation), send the `live_location` message, then hand the share to the tab's engine, which + * publishes the first position at once and keeps publishing until it ends. + */ + const startLiveShare = useCallback( + async (fix: LocationFix, durationMs: number) => { + const engine = liveSharing(); + if (engine.share(matchId)) await engine.stop(matchId); + const sessionId = newLiveSessionId(); + const { startedAt, expiresAt } = makeLiveWindow(durationMs, Date.now()); + await sendStructured(buildLiveLocationStartPayload({ sessionId, startedAt, expiresAt, fix })); + await engine.begin( + { matchId, sessionId, startedAt, expiresAt, userId: currentUserId, peerName, seal: sealPayload }, + fix + ); + }, + [matchId, currentUserId, peerName, sealPayload, sendStructured] + ); + const handleDrop = useCallback( (event: DragEvent) => { event.preventDefault(); @@ -1361,6 +1472,29 @@ function MatchConversation({

)} + {myShare && ( +
+
+ )}
{peerId && ( void handlePickFile(file, kind)} onVoiceNote={handleVoiceNote} + onPickLocation={() => setLocationOpen(true)} + onPickContact={contactShare.openContact} /> } /> + setLocationOpen(false)} + onSendCurrent={sendCurrentLocation} + onStartLive={startLiveShare} + /> + + + {/* Recovery runs against the ACCOUNT, not this conversation: importing the history key unlocks every match at once, so a successful transfer refetches this thread and any other open one diff --git a/src/features/moderation/report/evidence-api.ts b/src/features/moderation/report/evidence-api.ts index 07513d3..053f1c3 100644 --- a/src/features/moderation/report/evidence-api.ts +++ b/src/features/moderation/report/evidence-api.ts @@ -1,18 +1,27 @@ /** * Evidence upload transport (OneHook moderation Phase 2 client contract). * - * Implements the three HTTP steps against the admin portal's PUBLIC member gateway + * Implements the three steps against the admin portal's PUBLIC member gateway * (features/moderation README "Evidence (decrypted-chat share) - client contract"): * - * 1. POST {base}/evidence/presign (Bearer member ID token) -> { evidenceId, upload, expiresAt } - * 2. PUT upload.url (EXACTLY upload.headers, no auth) with the canonical bytes - * 3. POST {base}/evidence/complete (Bearer member ID token) -> { status } + * 1. PresignEvidence (SDK, Bearer member ID token) -> { evidenceId, upload, expiresAt } + * 2. PUT upload.url (EXACTLY upload.headers, no auth) with the canonical bytes: a presigned S3 + * URL, the one raw request here + * 3. CompleteEvidence (SDK, Bearer member ID token) -> { status } * - * `complete` is retried on `503 EVIDENCE_FINALIZE_RETRY` with bounded backoff. Everything is - * dependency-injected (fetch, token provider, sleep) so the orchestration is unit-testable without a + * Steps 1 and 3 use the admin portal's published client (`saha-equation-admin-portal-client`), bound to the OneHook + * tenant. `complete` is + * retried on `503 EVIDENCE_FINALIZE_RETRY` with bounded backoff. Everything is dependency-injected + * (SDK client, S3 fetch, token provider, sleep) so the orchestration is unit-testable without a * browser or the network. No message text or user ids are ever logged here. */ import { portalModerationBaseUrl } from '../../../utils/env.config'; +import { + createModerationEvidenceClient, + sdkFailure, + withoutMetadata, + type EvidenceClient, +} from '../../../api/external-sdk-clients'; export class EvidenceError extends Error { constructor( @@ -30,6 +39,9 @@ export class EvidenceError extends Error { export interface EvidenceTransport { /** Portal moderation base URL (…/moderation). Defaults to the app's env config. */ baseUrl?: string; + /** The tenant-bound portal evidence client. Defaults to one built from `baseUrl` + `getToken`. */ + client?: Pick; + /** Used only for the PUT to the presigned S3 URL. */ fetchImpl?: typeof fetch; /** Returns the member's Cognito ID token, or null when unauthenticated. */ getToken: () => Promise; @@ -125,65 +137,37 @@ function resolveBaseUrl(t: EvidenceTransport): string { return (t.baseUrl ?? portalModerationBaseUrl).replace(/\/+$/, ''); } -/** - * Read the portal error envelope `{"error": {"code", "message", "retryable"}}` (Smithy - * `ModerationEvidenceErrorBody`). Anything else (a proxy HTML page, an empty body) yields no code. - */ -async function parseBody(res: Response): Promise<{ code?: string; message?: string; retryable?: boolean }> { - const text = await res.text().catch(() => ''); - let parsed: unknown = undefined; - if (text) { - try { - parsed = JSON.parse(text); - } catch { - parsed = undefined; - } - } - const envelope = typeof parsed === 'object' && parsed !== null ? (parsed as { error?: unknown }) : undefined; - const detail = - typeof envelope?.error === 'object' && envelope.error !== null - ? (envelope.error as Record) - : undefined; - return { - code: typeof detail?.code === 'string' ? detail.code : undefined, - message: typeof detail?.message === 'string' ? detail.message : undefined, - retryable: typeof detail?.retryable === 'boolean' ? detail.retryable : undefined, - }; +function clientOf(t: EvidenceTransport): NonNullable { + return t.client ?? createModerationEvidenceClient(resolveBaseUrl(t), t.getToken); } -async function postJson(t: EvidenceTransport, path: string, body: unknown): Promise { - const doFetch = t.fetchImpl ?? fetch; - const token = await t.getToken(); - const headers: Record = { - 'Content-Type': 'application/json', - Accept: 'application/json', - }; - if (token) headers['Authorization'] = `Bearer ${token}`; - - let res: Response; +/** + * Run one SDK call; a failure becomes an {@link EvidenceError} read from the portal envelope + * `{"error": {"code", "message", "retryable"}}` (Smithy `ModerationEvidenceErrorBody`, which the SDK + * copies onto the exception). A body without that envelope (a proxy HTML page) yields no code. + */ +async function evidenceCall(call: () => Promise): Promise> { try { - res = await doFetch(`${resolveBaseUrl(t)}${path}`, { - method: 'POST', - headers, - body: JSON.stringify(body), - }); + return withoutMetadata(await call()); } catch (err) { - throw new EvidenceError( - err instanceof Error ? err.message : 'Network request failed', - 0, - 'NETWORK_ERROR' - ); - } - if (!res.ok) { - const { code, message, retryable } = await parseBody(res); - throw new EvidenceError(message || `Evidence request failed (${res.status})`, res.status, code, retryable); + if (err instanceof EvidenceError) throw err; + const failure = sdkFailure(err); + if (!failure) { + throw new EvidenceError(err instanceof Error ? err.message : 'Network request failed', 0, 'NETWORK_ERROR'); + } + const envelope = failure.body.error; + const detail = typeof envelope === 'object' && envelope !== null ? (envelope as Record) : undefined; + const code = typeof detail?.code === 'string' ? detail.code : undefined; + const message = typeof detail?.message === 'string' ? detail.message : undefined; + const retryable = typeof detail?.retryable === 'boolean' ? detail.retryable : undefined; + throw new EvidenceError(message || `Evidence request failed (${failure.status})`, failure.status, code, retryable); } - return (await res.json()) as T; } /** Step 1: get a presigned PUT for the evidence object. */ export function presignEvidence(t: EvidenceTransport, req: PresignRequest): Promise { - return postJson(t, '/evidence/presign', req); + const evidenceClient = clientOf(t); + return evidenceCall(() => evidenceClient.presignEvidence(req)) as Promise; } /** @@ -235,7 +219,8 @@ export async function completeEvidence( // eslint-disable-next-line no-constant-condition while (true) { try { - return await postJson(t, '/evidence/complete', req); + const evidenceClient = clientOf(t); + return (await evidenceCall(() => evidenceClient.completeEvidence(req))) as CompleteResponse; } catch (err) { const retryable = err instanceof EvidenceError && err.status === 503 && err.code === FINALIZE_RETRY_CODE; diff --git a/src/hooks/use-api.ts b/src/hooks/use-api.ts index 733db1f..5328b8c 100644 --- a/src/hooks/use-api.ts +++ b/src/hooks/use-api.ts @@ -758,6 +758,16 @@ export function useChatMessages(matchId: string, recipientId?: string) { [createMessageId, myId, matchId, encryptionManager, recipientId] ); + const sealPayload = useCallback( + async (plaintext: string): Promise => { + if (!encryptionManager || !recipientId || !matchId) { + throw new Error('This conversation is not ready to send yet.'); + } + return encryptionManager.encryptMessage(recipientId, matchId, plaintext); + }, + [encryptionManager, recipientId, matchId] + ); + /** * Runs one outgoing-attachment attempt for an already-registered pending upload. Shared by the first * send and by retry so the two can never drift apart. @@ -981,6 +991,11 @@ export function useChatMessages(matchId: string, recipientId?: string) { * the same envelope, AAD and error mapping as message bodies. */ decryptPayload: decryptInbound, + /** + * Seals a plaintext for this conversation exactly like a message body (same wire-v2 envelope, + * targets and `matchId` AAD) without sending it: the `ciphertext` of a live-location update. + */ + sealPayload, }; } diff --git a/src/hooks/use-live-sharing.ts b/src/hooks/use-live-sharing.ts new file mode 100644 index 0000000..d5cc3f8 --- /dev/null +++ b/src/hooks/use-live-sharing.ts @@ -0,0 +1,68 @@ +import { useSyncExternalStore } from 'react'; +import { LiveLocationApi } from '../api/live-location'; +import { browserLocationSource, systemClock, windowPageLifecycle } from '../lib/browser-location'; +import { + LiveLocationSharing, + type LiveSharingSnapshot, + type LiveSharingTransport, +} from '../lib/live-location-sharing'; +import { useAppStore } from '../store/app-store'; + +/** + * The tab's one live-location sharing engine (lib/live-location-sharing.ts), wired to the browser and + * the app. It is a module singleton, not component state, because a share belongs to the tab: it keeps + * running while the member switches conversations or leaves the Chat screen, and ends when the tab + * closes. + * + * It follows the app store on its own, so the rules hold wherever the member is in the app: + * - a hook that leaves State (released, blocked) or becomes suspended ends its share; + * - signing out, or another account signing in, ends every share. + */ + +const transport: LiveSharingTransport = { + publish: (matchId, sessionId, ciphertext, expiresAt) => + LiveLocationApi.publishLiveLocation(matchId, sessionId, ciphertext, expiresAt), + stop: (matchId, sessionId) => LiveLocationApi.stopLiveLocation(matchId, sessionId), + stopOnUnload: (matchId, sessionId) => LiveLocationApi.stopOnUnload(matchId, sessionId), + subscribe: (matchId, onRow) => LiveLocationApi.subscribe(matchId, (row) => onRow(row)), + primeUnloadAuth: () => LiveLocationApi.primeUnloadAuth(), + clearUnloadAuth: () => LiveLocationApi.clearUnloadAuth(), +}; + +let engine: LiveLocationSharing | null = null; + +/** The engine, created (and attached to the app store) on first use. */ +export function liveSharing(): LiveLocationSharing { + if (engine) return engine; + const created = new LiveLocationSharing({ + transport, + location: browserLocationSource(), + clock: systemClock, + page: windowPageLifecycle(), + log: (message) => console.debug(`[chat] ${message}`), + }); + engine = created; + + let userId = useAppStore.getState().currentUser?.id ?? null; + let hooks = useAppStore.getState().userState?.hooks; + useAppStore.subscribe((state) => { + const nextUser = state.currentUser?.id ?? null; + if (nextUser !== userId) { + // Signed out, or a different account: none of the running shares belong to it. + if (userId !== null) created.endAll('signed_out'); + userId = nextUser; + } + const nextHooks = state.userState?.hooks; + if (nextHooks !== hooks) { + hooks = nextHooks; + created.reconcile(nextHooks); + } + }); + return created; +} + +/** The engine's state, for rendering (banner, Stop buttons, "Ended" before the server echo). */ +export function useLiveSharing(): LiveSharingSnapshot { + const instance = liveSharing(); + return useSyncExternalStore(instance.subscribe, instance.getSnapshot, instance.getSnapshot); +} diff --git a/src/hooks/use-user-location.ts b/src/hooks/use-user-location.ts index 9bc0b8f..7dd28b0 100644 --- a/src/hooks/use-user-location.ts +++ b/src/hooks/use-user-location.ts @@ -7,6 +7,7 @@ import { saveLastKnownLocation, } from '../utils/location'; import { MatchingApi } from '../api/matching'; +import { isPageForeground } from '../lib/browser-location'; export type CoordinateSource = 'LIVE_GPS' | 'LAST_KNOWN' | 'PROFILE_CITY' | 'DEFAULT'; @@ -59,6 +60,11 @@ export function useUserLocation( ); const requestLocation = useCallback(() => { + // Matching location is foreground-only: a hidden tab never prompts for, reads or sends it (the + // chat live-location share is separate, lib/browser-location.ts). The effect below retries once + // the page becomes visible. + if (!isPageForeground()) return; + // Check if running in browser with geolocation available if (typeof window === 'undefined' || !navigator?.geolocation) { const fallback = resolveFallbackCoordinates(profileCityText); @@ -135,7 +141,18 @@ export function useUserLocation( setLoading(false); return; } - requestLocation(); + if (isPageForeground()) { + requestLocation(); + return; + } + // Opened in a background tab: read the location the first time the member looks at the page. + const onVisible = () => { + if (!isPageForeground()) return; + document.removeEventListener('visibilitychange', onVisible); + requestLocation(); + }; + document.addEventListener('visibilitychange', onVisible); + return () => document.removeEventListener('visibilitychange', onVisible); }, [requestLocation, enabled]); return { diff --git a/src/lib/analytics/analyticsClient.ts b/src/lib/analytics/analyticsClient.ts index aaeec50..8d19438 100644 --- a/src/lib/analytics/analyticsClient.ts +++ b/src/lib/analytics/analyticsClient.ts @@ -192,34 +192,3 @@ export class AnalyticsClient { return this.queue.length; } } - -/** - * Build a fetch-based transport for `POST /signals`. `getToken` returns the current Cognito JWT; the - * SDK never stores it. `platform` is sent as a header so the server can attribute the platform - * without trusting body content. - */ -export function createFetchTransport(config: { - endpoint: string; - getToken: () => Promise; - platform: 'web' | 'ios' | 'android'; - fetchImpl?: typeof fetch; -}): AnalyticsTransport { - const doFetch = config.fetchImpl ?? fetch; - return { - async send(batch: Signal[]): Promise { - const token = await config.getToken(); - const res = await doFetch(config.endpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${token}`, - 'X-OneHook-Platform': config.platform, - }, - body: JSON.stringify({ signals: batch }), - }); - if (!res.ok) { - throw new Error(`analytics ingest failed: ${res.status}`); - } - }, - }; -} diff --git a/src/lib/analytics/generated/apiManifest.ts b/src/lib/analytics/generated/apiManifest.ts index 0f90bc6..91212b5 100644 --- a/src/lib/analytics/generated/apiManifest.ts +++ b/src/lib/analytics/generated/apiManifest.ts @@ -3,7 +3,7 @@ // Regenerate: (OneHookBackend) npm --prefix packages/api-models run build && npm run api:sync /* eslint-disable */ -export type ApiAuth = 'cognito' | 'iam' | 'none' | 'session'; +export type ApiAuth = 'cognito' | 'iam' | 'none'; export interface ApiOperation { readonly operationId: string; @@ -13,21 +13,8 @@ export interface ApiOperation { readonly auth: ApiAuth; } -/** Every OneHook HTTP operation, sorted by service, path, method. */ +/** Every OneHook backend HTTP operation, sorted by service, path, method. */ export const API_OPERATIONS: readonly ApiOperation[] = [ - { operationId: "GetAdmissionsApplication", method: "GET", path: "/api/p/{service}/{stage}/admissions/application", service: "admissions", auth: "session" }, - { operationId: "CreateAdmissionsApplication", method: "POST", path: "/api/p/{service}/{stage}/admissions/application", service: "admissions", auth: "session" }, - { operationId: "WithdrawAdmissionsApplication", method: "DELETE", path: "/api/p/{service}/{stage}/admissions/application/{applicationId}", service: "admissions", auth: "session" }, - { operationId: "CompleteApplicationUpload", method: "POST", path: "/api/p/{service}/{stage}/admissions/application/{applicationId}/upload/complete", service: "admissions", auth: "session" }, - { operationId: "GetUploadPartUrls", method: "POST", path: "/api/p/{service}/{stage}/admissions/application/{applicationId}/upload/parts", service: "admissions", auth: "session" }, - { operationId: "CreateAttestationChallenge", method: "POST", path: "/api/p/{service}/{stage}/admissions/attest/challenge", service: "admissions", auth: "none" }, - { operationId: "RegisterAttestationKey", method: "POST", path: "/api/p/{service}/{stage}/admissions/attest/register", service: "admissions", auth: "none" }, - { operationId: "CreateLivenessChallenge", method: "POST", path: "/api/p/{service}/{stage}/admissions/challenge", service: "admissions", auth: "session" }, - { operationId: "GetAdmissionsConfig", method: "GET", path: "/api/p/{service}/{stage}/admissions/config", service: "admissions", auth: "none" }, - { operationId: "RecordAdmissionsConsent", method: "POST", path: "/api/p/{service}/{stage}/admissions/consent", service: "admissions", auth: "session" }, - { operationId: "WithdrawTrainingConsent", method: "POST", path: "/api/p/{service}/{stage}/admissions/consent/withdraw", service: "admissions", auth: "session" }, - { operationId: "StartAdmissionsOtp", method: "POST", path: "/api/p/{service}/{stage}/admissions/otp/start", service: "admissions", auth: "none" }, - { operationId: "VerifyAdmissionsOtp", method: "POST", path: "/api/p/{service}/{stage}/admissions/otp/verify", service: "admissions", auth: "none" }, { operationId: "GetGraphMatch", method: "GET", path: "/graph/matches/{matchId}", service: "analytics", auth: "iam" }, { operationId: "GetGraphUser", method: "GET", path: "/graph/users/{userId}", service: "analytics", auth: "iam" }, { operationId: "GetGraphInvites", method: "GET", path: "/graph/users/{userId}/invites", service: "analytics", auth: "iam" }, @@ -98,14 +85,6 @@ export const API_OPERATIONS: readonly ApiOperation[] = [ { operationId: "IssueViewPasses", method: "POST", path: "/matching/view-passes", service: "matching", auth: "cognito" }, { operationId: "GetPreferences", method: "GET", path: "/matching/{userId}/preferences", service: "matching", auth: "cognito" }, { operationId: "UpdatePreferences", method: "PUT", path: "/matching/{userId}/preferences", service: "matching", auth: "cognito" }, - { operationId: "CompleteEvidence", method: "POST", path: "/api/p/{service}/{stage}/moderation/evidence/complete", service: "moderation-evidence", auth: "cognito" }, - { operationId: "PresignEvidence", method: "POST", path: "/api/p/{service}/{stage}/moderation/evidence/presign", service: "moderation-evidence", auth: "cognito" }, - { operationId: "ProductConnectionChat", method: "POST", path: "/api/member/product-connection-chat", service: "mr-onehook", auth: "cognito" }, - { operationId: "ListChatSessions", method: "GET", path: "/api/member/product-connection-chat/sessions", service: "mr-onehook", auth: "cognito" }, - { operationId: "DeleteChatSession", method: "DELETE", path: "/api/member/product-connection-chat/sessions/{sessionId}", service: "mr-onehook", auth: "cognito" }, - { operationId: "GetChatSession", method: "GET", path: "/api/member/product-connection-chat/sessions/{sessionId}", service: "mr-onehook", auth: "cognito" }, - { operationId: "PublicProductChat", method: "POST", path: "/api/public/product-chat", service: "mr-onehook", auth: "none" }, - { operationId: "GetHealth", method: "GET", path: "/health", service: "mr-onehook", auth: "none" }, { operationId: "GetMyProfile", method: "GET", path: "/profile", service: "profile", auth: "cognito" }, { operationId: "GetBirthDateStatus", method: "GET", path: "/profile-admin/{userId}/birth-date", service: "profile", auth: "iam" }, { operationId: "CorrectBirthDate", method: "PUT", path: "/profile-admin/{userId}/birth-date", service: "profile", auth: "iam" }, diff --git a/src/lib/analytics/generated/telemetryCatalog.ts b/src/lib/analytics/generated/telemetryCatalog.ts index 4904eb8..37bde7c 100644 --- a/src/lib/analytics/generated/telemetryCatalog.ts +++ b/src/lib/analytics/generated/telemetryCatalog.ts @@ -1,15 +1,15 @@ // GENERATED FILE - DO NOT EDIT. -// telemetry-integrity: sha256 340e30d11ba7361ca84e451fa11ea6b7b2cf2b2ba9682d26e8e3a8e7e96a220f +// telemetry-integrity: sha256 963a0e6c686534101845009a720ed931f8816e765ead51d78fce4706e8ac9258 // Source of truth: OneHookBackend/packages/telemetry/src/catalog.ts // Regenerate: (OneHookBackend) npm run telemetry:generate && npm run telemetry:sync -// Catalog version 1.23.0, hash 58e41d4e7844382f. +// Catalog version 1.24.0, hash 139c2761335ed6ce. // // HARD RULE: every user interaction MUST emit ui_interaction with an id from THIS file, and // ids are controlled by the backend. Read TELEMETRY_CONTRACT.txt (printed by every build). /* eslint-disable */ -export const TELEMETRY_CATALOG_VERSION = "1.23.0"; -export const TELEMETRY_CATALOG_HASH = "58e41d4e7844382f"; +export const TELEMETRY_CATALOG_VERSION = "1.24.0"; +export const TELEMETRY_CATALOG_HASH = "139c2761335ed6ce"; /** Every signal type the ingest accepts. */ export const SignalType = { @@ -712,9 +712,9 @@ export const UI_ELEMENTS: { readonly [K in UiElementId]: UiElementSpec } = { "chat.select_cancel": { screen: "CHAT", kind: "button", actions: ["tap"], values: null, platforms: ["ios"] }, "chat.select_ask_mr_onehook": { screen: "CHAT", kind: "button", actions: ["tap"], values: null, platforms: ["ios"] }, "chat.select_copy": { screen: "CHAT", kind: "button", actions: ["tap"], values: null, platforms: ["ios"] }, - "chat.location_share": { screen: "CHAT", kind: "button", actions: ["tap"], values: ["current", "live"], platforms: ["ios"] }, - "chat.live_location_duration": { screen: "CHAT", kind: "menu_item", actions: ["tap", "dismiss"], values: ["min_15", "hour_1", "hour_8"], platforms: ["ios"] }, - "chat.live_location_stop": { screen: "CHAT", kind: "button", actions: ["tap"], values: null, platforms: ["ios"] }, + "chat.location_share": { screen: "CHAT", kind: "button", actions: ["tap"], values: ["current", "live"], platforms: ["web", "ios", "android"] }, + "chat.live_location_duration": { screen: "CHAT", kind: "menu_item", actions: ["tap", "dismiss"], values: ["min_15", "hour_1", "hour_8"], platforms: ["web", "ios", "android"] }, + "chat.live_location_stop": { screen: "CHAT", kind: "button", actions: ["tap"], values: null, platforms: ["web", "ios", "android"] }, "chat.location_open": { screen: "CHAT", kind: "button", actions: ["tap"], values: ["in_app", "apple_maps", "google_maps"], platforms: ["web", "ios", "android"] }, "chat.location_directions": { screen: "CHAT", kind: "button", actions: ["tap"], values: ["apple_maps", "google_maps"], platforms: ["web", "ios", "android"] }, "chat.contact_open": { screen: "CHAT", kind: "button", actions: ["tap"], values: null, platforms: ["web", "ios", "android"] }, diff --git a/src/lib/browser-location.ts b/src/lib/browser-location.ts new file mode 100644 index 0000000..e995021 --- /dev/null +++ b/src/lib/browser-location.ts @@ -0,0 +1,212 @@ +/** + * The browser side of chat location sharing: reading positions from the Geolocation API, and the page + * lifecycle and clock the live-sharing engine (lib/live-location-sharing.ts) runs on. + * + * Two separate users of the Geolocation API exist in the app and they never share anything: + * - chat sharing (this file): a one-shot read for the location sheet, and a `watchPosition` that runs + * only while this tab has a live share running; + * - matching (hooks/use-user-location.ts): a one-shot read for Discover, made only while the page is + * visible ({@link isPageForeground}). The web has no background location at all, so "foreground + * only" here means "never while the tab is hidden". + * + * Everything takes its browser objects as parameters, so it is unit-testable under Node with fakes. + */ +import type { LocationFix } from './chat-structured'; +import type { LiveLocationSource, PageLifecycle, SharingClock } from './live-location-sharing'; + +/** Why a position could not be read. */ +export type LocationErrorKind = 'unsupported' | 'denied' | 'unavailable' | 'timeout'; + +export class LocationReadError extends Error { + readonly kind: LocationErrorKind; + constructor(kind: LocationErrorKind) { + super(LOCATION_ERROR_COPY[kind]); + this.name = 'LocationReadError'; + this.kind = kind; + } +} + +/** What the location sheet says for each failure. */ +export const LOCATION_ERROR_COPY: Record = { + unsupported: "This browser can't share your location.", + denied: 'Location access is off for this site. Turn it on in your browser settings to share your location.', + unavailable: "Your location isn't available right now.", + timeout: 'Finding your location took too long.', +}; + +/** The parts of `GeolocationPosition` used here (so tests can pass plain objects). */ +export interface PositionLike { + coords: { + latitude: number; + longitude: number; + accuracy?: number | null; + heading?: number | null; + speed?: number | null; + }; + timestamp: number; +} + +/** The parts of `navigator.geolocation` used here. */ +export interface GeolocationLike { + getCurrentPosition( + success: (position: PositionLike) => void, + error?: (error: { code: number }) => void, + options?: PositionOptions + ): void; + watchPosition( + success: (position: PositionLike) => void, + error?: (error: { code: number }) => void, + options?: PositionOptions + ): number; + clearWatch(id: number): void; +} + +/** `GeolocationPositionError` codes. */ +const PERMISSION_DENIED = 1; +const TIMEOUT = 3; + +export function errorKindFromCode(code: number): LocationErrorKind { + if (code === PERMISSION_DENIED) return 'denied'; + if (code === TIMEOUT) return 'timeout'; + return 'unavailable'; +} + +function finiteOrUndefined(value: number | null | undefined): number | undefined { + return typeof value === 'number' && Number.isFinite(value) ? value : undefined; +} + +/** + * A browser position as a fix. Heading is only meaningful while moving (browsers report NaN or null + * otherwise), so it is dropped when the speed is unknown or zero. Returns null for coordinates out of + * range, which some platforms report while they have no fix. + */ +export function fixFromPosition(position: PositionLike): LocationFix | null { + const { latitude, longitude } = position.coords; + if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null; + if (latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180) return null; + const fix: LocationFix = { + lat: latitude, + lon: longitude, + at: Number.isFinite(position.timestamp) && position.timestamp > 0 ? position.timestamp : Date.now(), + }; + const accuracy = finiteOrUndefined(position.coords.accuracy); + if (accuracy !== undefined && accuracy >= 0) fix.accuracyM = accuracy; + const speed = finiteOrUndefined(position.coords.speed); + if (speed !== undefined && speed >= 0) fix.speedMps = speed; + const heading = finiteOrUndefined(position.coords.heading); + if (heading !== undefined && heading >= 0 && heading < 360 && speed !== undefined && speed > 0) { + fix.headingDeg = heading; + } + return fix; +} + +/** The page's geolocation, or null where there is none (old browsers, insecure origins, SSR). */ +export function browserGeolocation(): GeolocationLike | null { + if (typeof navigator === 'undefined' || !navigator.geolocation) return null; + return navigator.geolocation as unknown as GeolocationLike; +} + +/** + * One fresh position for the location sheet. Prompts for permission the first time. A cached + * position up to 30 s old is accepted (it is what the member sees in the preview before sending). + */ +export function getCurrentFix( + geo: GeolocationLike | null = browserGeolocation(), + options: PositionOptions = { enableHighAccuracy: true, timeout: 20_000, maximumAge: 30_000 } +): Promise { + return new Promise((resolve, reject) => { + if (!geo) { + reject(new LocationReadError('unsupported')); + return; + } + try { + geo.getCurrentPosition( + (position) => { + const fix = fixFromPosition(position); + if (fix) resolve(fix); + else reject(new LocationReadError('unavailable')); + }, + (error) => reject(new LocationReadError(errorKindFromCode(error?.code ?? 0))), + options + ); + } catch { + reject(new LocationReadError('unsupported')); + } + }); +} + +/** + * Positions for a running live share (`watchPosition`). High accuracy asks for GPS and fresh fixes; + * low accuracy (the member has been still for a while) accepts network positions up to a minute old, + * which lets the device keep its GPS off. Permission refused or revoked calls `onDenied`; other errors + * are transient and ignored (the watch keeps running and the next fix arrives when it can). + */ +export function browserLocationSource(geo: GeolocationLike | null = browserGeolocation()): LiveLocationSource { + return { + watch(onFix, onDenied, { highAccuracy }) { + if (!geo) { + onDenied(); + return () => undefined; + } + let id: number | null = null; + try { + id = geo.watchPosition( + (position) => { + const fix = fixFromPosition(position); + if (fix) onFix(fix); + }, + (error) => { + if (error?.code === PERMISSION_DENIED) onDenied(); + }, + highAccuracy + ? { enableHighAccuracy: true, maximumAge: 0, timeout: 60_000 } + : { enableHighAccuracy: false, maximumAge: 60_000, timeout: 120_000 } + ); + } catch { + onDenied(); + } + return () => { + if (id !== null) geo.clearWatch(id); + id = null; + }; + }, + }; +} + +/** The parts of `window` the page lifecycle uses. */ +export interface WindowLike { + addEventListener(type: 'pagehide', listener: () => void): void; + removeEventListener(type: 'pagehide', listener: () => void): void; +} + +/** + * `pagehide` is the one event that fires reliably when a tab is closed, reloaded or navigated away + * (including on mobile, where `beforeunload` and `unload` often do not), and also when the page goes + * into the back/forward cache. `beforeunload` is not used: it fires before the member confirms + * leaving, and listening to it keeps some browsers from caching the page. + */ +export function windowPageLifecycle(win: WindowLike | null = typeof window !== 'undefined' ? window : null): PageLifecycle { + return { + onPageHide(fn) { + if (!win) return () => undefined; + const listener = () => fn(); + win.addEventListener('pagehide', listener); + return () => win.removeEventListener('pagehide', listener); + }, + }; +} + +export const systemClock: SharingClock = { + now: () => Date.now(), + setInterval: (fn, ms) => setInterval(fn, ms), + clearInterval: (handle) => clearInterval(handle as ReturnType), +}; + +/** + * Whether the page is in the foreground (visible). Matching location is only read then: a tab in the + * background never prompts for, refreshes or sends the matching location. + */ +export function isPageForeground(doc: { visibilityState?: string } | null = typeof document !== 'undefined' ? document : null): boolean { + // No document (SSR, tests) proves nothing either way; the callers only run in the browser. + return !doc || doc.visibilityState === undefined || doc.visibilityState === 'visible'; +} diff --git a/src/lib/chat-structured.ts b/src/lib/chat-structured.ts index baaf61d..e502df0 100644 --- a/src/lib/chat-structured.ts +++ b/src/lib/chat-structured.ts @@ -111,7 +111,7 @@ export function isStructuredFrame(plaintext: string): boolean { return plaintext.charCodeAt(0) === STRUCTURED_FRAME_BYTE; } -/** Produces a framed plaintext. Web does not send yet; this exists for tests and future senders. */ +/** Produces a framed plaintext: `0x03 || JSON(payload)`. Sealed afterwards like any message body. */ export function frameStructuredContent(payload: Record): string { return String.fromCharCode(STRUCTURED_FRAME_BYTE) + JSON.stringify(payload); } @@ -121,6 +121,130 @@ export function roundCoordinate(value: number): number { return Number(value.toFixed(COORDINATE_DECIMALS)); } +// ── Senders ────────────────────────────────────────────────────────────────── +// +// The builders below produce exactly the contract's JSON (chat-location-contact.md, "Payloads"): +// coordinates rounded to 6 decimals, optional fields omitted rather than null, `v: 1`. They throw on +// a coordinate out of range: sending a pin nobody can open is a bug, not something to round away. + +/** One position fix from the device, in the units the payloads carry. `at` is epoch ms. */ +export interface LocationFix { + lat: number; + lon: number; + accuracyM?: number; + headingDeg?: number; + speedMps?: number; + at: number; +} + +function requireCoordinates(lat: number, lon: number): { lat: number; lon: number } { + const la = latitude(lat); + const lo = longitude(lon); + if (la === null || lo === null) throw new Error('A location needs a valid latitude and longitude.'); + return { lat: la, lon: lo }; +} + +/** Accuracy is whole-ish metres on the wire; a negative or NaN value means "unknown" and is omitted. */ +function wireAccuracy(value: number | undefined): number | undefined { + const v = nonNegative(value); + return v === undefined ? undefined : Math.round(v * 10) / 10; +} + +/** The `location` message for the device's current position (web never sends a named place). */ +export function buildLocationPayload(fix: LocationFix): Record { + const { lat, lon } = requireCoordinates(fix.lat, fix.lon); + const out: Record = { v: STRUCTURED_CONTENT_VERSION, type: 'location', lat, lon }; + const accuracyM = wireAccuracy(fix.accuracyM); + if (accuracyM !== undefined) out.accuracyM = accuracyM; + out.capturedAt = Math.round(fix.at); + return out; +} + +/** The `live_location` message that starts a share (its bubble; later positions move its pin). */ +export function buildLiveLocationStartPayload(start: { + sessionId: string; + startedAt: number; + expiresAt: number; + fix: LocationFix; +}): Record { + if (!sessionId(start.sessionId)) throw new Error('A live share needs a valid sessionId.'); + if (!(start.expiresAt > start.startedAt)) throw new Error('A live share must end after it starts.'); + const { lat, lon } = requireCoordinates(start.fix.lat, start.fix.lon); + const out: Record = { + v: STRUCTURED_CONTENT_VERSION, + type: 'live_location', + sessionId: start.sessionId, + startedAt: Math.round(start.startedAt), + expiresAt: Math.round(start.expiresAt), + lat, + lon, + }; + const accuracyM = wireAccuracy(start.fix.accuracyM); + if (accuracyM !== undefined) out.accuracyM = accuracyM; + return out; +} + +/** The `live_location_update` sealed into `publishLiveLocation`'s ciphertext. Never a chat message. */ +export function buildLiveLocationUpdatePayload(sessionIdValue: string, fix: LocationFix): Record { + if (!sessionId(sessionIdValue)) throw new Error('A live update needs a valid sessionId.'); + const { lat, lon } = requireCoordinates(fix.lat, fix.lon); + const out: Record = { + v: STRUCTURED_CONTENT_VERSION, + type: 'live_location_update', + sessionId: sessionIdValue, + lat, + lon, + }; + const accuracyM = wireAccuracy(fix.accuracyM); + if (accuracyM !== undefined) out.accuracyM = accuracyM; + if (finite(fix.headingDeg) && fix.headingDeg >= 0 && fix.headingDeg < 360) { + // 359.6 rounds to 360, which the decoder rejects: wrap it to 0 (north) instead. + out.headingDeg = Math.round(fix.headingDeg) % 360; + } + const speedMps = nonNegative(fix.speedMps); + if (speedMps !== undefined) out.speedMps = Math.round(speedMps * 10) / 10; + out.at = Math.round(fix.at); + return out; +} + +/** + * The `contact` message. Only the phones and emails passed in are sent (the caller applies the + * member's selection first). Blank entries are dropped, strings are cleaned the same way the decoder + * cleans them, and a thumbnail over 24 KB of base64 (or not base64) is dropped rather than sent. + * Throws when nothing identifies the contact (no name, phone or email). + */ +export function buildContactPayload(contact: { + displayName?: string; + givenName?: string; + familyName?: string; + organization?: string; + phones: ContactEntry[]; + emails: ContactEntry[]; + thumbnailBase64?: string; +}): Record { + const givenName = text(contact.givenName); + const familyName = text(contact.familyName); + const organization = text(contact.organization); + const phones = contactEntries(contact.phones); + const emails = contactEntries(contact.emails); + const displayName = + text(contact.displayName) || + text([givenName, familyName].filter(Boolean).join(' ')) || + organization || + phones[0]?.value || + emails[0]?.value; + if (!displayName) throw new Error('A contact needs a name, a phone number or an email address.'); + const out: Record = { v: STRUCTURED_CONTENT_VERSION, type: 'contact', displayName }; + if (givenName) out.givenName = givenName; + if (familyName) out.familyName = familyName; + if (organization) out.organization = organization; + out.phones = phones; + out.emails = emails; + const thumb = thumbnail(contact.thumbnailBase64); + if (thumb) out.thumbnailBase64 = thumb; + return out; +} + function finite(value: unknown): value is number { return typeof value === 'number' && Number.isFinite(value); } diff --git a/src/lib/contact-share.ts b/src/lib/contact-share.ts new file mode 100644 index 0000000..4c02019 --- /dev/null +++ b/src/lib/contact-share.ts @@ -0,0 +1,244 @@ +/** + * Sending a contact card from the web (OneHookBackend/docs/chat-location-contact.md, "Contact"). + * + * Two sources feed the same review step: + * - the Contact Picker API (`navigator.contacts.select`), where the browser has it (Chrome on Android); + * - a small form (name required, any number of phones and emails) everywhere else. + * + * The member then chooses which phones and emails to include (all by default) and the card is sent as + * an ordinary E2EE message (`buildContactPayload` + `frameStructuredContent`). Nothing here talks to a + * network or touches the DOM, so it is unit-testable under Node. + */ +import { MAX_CONTACT_THUMBNAIL_BASE64, buildContactPayload, type ContactEntry } from './chat-structured'; + +/** The decoder keeps at most this many phones / emails, so the sender never offers more. */ +export const MAX_CONTACT_FIELDS = 20; +/** Same display cap the decoder applies to every string. */ +export const MAX_CONTACT_TEXT = 256; + +/** A contact as the member is about to share it, before field selection. */ +export interface ContactDraft { + displayName: string; + givenName?: string; + familyName?: string; + organization?: string; + phones: ContactEntry[]; + emails: ContactEntry[]; + thumbnailBase64?: string; +} + +/** Which of the draft's phones and emails go out, by index. */ +export interface ContactSelection { + phones: boolean[]; + emails: boolean[]; +} + +/** Everything is included until the member unticks it. */ +export function selectAll(draft: ContactDraft): ContactSelection { + return { phones: draft.phones.map(() => true), emails: draft.emails.map(() => true) }; +} + +/** The payload for the draft with only the selected phones and emails. */ +export function buildSelectedContactPayload(draft: ContactDraft, selection: ContactSelection): Record { + return buildContactPayload({ + displayName: draft.displayName, + givenName: draft.givenName, + familyName: draft.familyName, + organization: draft.organization, + phones: draft.phones.filter((_, i) => selection.phones[i] !== false), + emails: draft.emails.filter((_, i) => selection.emails[i] !== false), + thumbnailBase64: draft.thumbnailBase64, + }); +} + +// ── The manual form ────────────────────────────────────────────────────────── + +/** Raw form state: the phone and email lists always end with one empty row to type into. */ +export interface ContactFormValues { + name: string; + organization: string; + phones: string[]; + emails: string[]; +} + +export const EMPTY_CONTACT_FORM: ContactFormValues = { name: '', organization: '', phones: [''], emails: [''] }; + +export interface ContactFormErrors { + name?: string; + /** Per row, aligned with `values.phones`. */ + phones: (string | undefined)[]; + emails: (string | undefined)[]; +} + +const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; +/** Digits plus the usual separators, an optional leading +, and a sane digit count. */ +const PHONE_CHARS = /^\+?[0-9 ()./-]+$/; + +export function isPlausiblePhone(value: string): boolean { + const v = value.trim(); + if (!PHONE_CHARS.test(v)) return false; + const digits = v.replace(/\D/g, '').length; + return digits >= 3 && digits <= 17; +} + +export function isPlausibleEmail(value: string): boolean { + const v = value.trim(); + return v.length <= MAX_CONTACT_TEXT && EMAIL_PATTERN.test(v); +} + +/** + * Keeps exactly one trailing empty row (so a new row appears as soon as the last one is filled, with + * no "add" button), drops empty rows in the middle, and caps the list at {@link MAX_CONTACT_FIELDS}. + */ +export function normalizeRows(rows: string[]): string[] { + // Only truly empty rows go: a row holding just a space is one the member is still typing in. + const filled = rows.filter((r) => r !== '').slice(0, MAX_CONTACT_FIELDS); + return filled.length < MAX_CONTACT_FIELDS ? [...filled, ''] : filled; +} + +/** Validates the form. Empty rows are ignored; the name is required. */ +export function validateContactForm(values: ContactFormValues): { valid: boolean; errors: ContactFormErrors } { + const errors: ContactFormErrors = { phones: values.phones.map(() => undefined), emails: values.emails.map(() => undefined) }; + const name = values.name.trim(); + if (!name) errors.name = 'Enter a name'; + else if (name.length > MAX_CONTACT_TEXT) errors.name = 'That name is too long'; + values.phones.forEach((p, i) => { + if (p.trim() && !isPlausiblePhone(p)) errors.phones[i] = 'Enter a valid phone number'; + }); + values.emails.forEach((e, i) => { + if (e.trim() && !isPlausibleEmail(e)) errors.emails[i] = 'Enter a valid email address'; + }); + const valid = !errors.name && errors.phones.every((e) => !e) && errors.emails.every((e) => !e); + return { valid, errors }; +} + +/** A valid form as a draft (call {@link validateContactForm} first). */ +export function draftFromForm(values: ContactFormValues): ContactDraft { + const name = values.name.trim(); + const organization = values.organization.trim(); + const draft: ContactDraft = { + displayName: name, + phones: values.phones.map((p) => p.trim()).filter(Boolean).map((value) => ({ value })), + emails: values.emails.map((e) => e.trim()).filter(Boolean).map((value) => ({ value })), + }; + if (organization) draft.organization = organization; + return draft; +} + +// ── The Contact Picker API ─────────────────────────────────────────────────── + +/** What `navigator.contacts.select` resolves to per contact (every property is an array). */ +export interface PickedContact { + name?: string[]; + tel?: string[]; + email?: string[]; + icon?: Blob[]; +} + +export interface ContactsManagerLike { + select(properties: string[], options?: { multiple?: boolean }): Promise; + getProperties?(): Promise; +} + +/** The browser's contacts manager, when the Contact Picker API exists and the page is a secure context. */ +export function contactsManager(nav: unknown = typeof navigator !== 'undefined' ? navigator : undefined): ContactsManagerLike | null { + const contacts = (nav as { contacts?: Partial } | undefined)?.contacts; + return contacts && typeof contacts.select === 'function' ? (contacts as ContactsManagerLike) : null; +} + +/** What the picker is asked for. `icon` only where the browser said it supports it. */ +export function contactPickerProperties(supported: readonly string[] | null | undefined): string[] { + const base = ['name', 'tel', 'email']; + return supported?.includes('icon') ? [...base, 'icon'] : base; +} + +export type PickContactResult = + | { kind: 'picked'; draft: ContactDraft } + /** The member closed the picker without choosing anyone. */ + | { kind: 'cancelled' } + /** The picker refused (no user activation, not allowed here) or returned nothing usable. */ + | { kind: 'failed' }; + +/** + * Opens the device's contact picker for one contact and turns the answer into a draft. Must be called + * from a click handler (the browser requires a user gesture). `encodeIcon(blob, sizePx, quality)` + * shrinks the contact's photo to a square JPEG (base64), see {@link fitThumbnail}; without it, or when + * no size fits 24 KB, the card goes without a photo. + */ +export async function pickContact( + manager: ContactsManagerLike, + properties: string[], + encodeIcon?: (blob: Blob, sizePx: number, quality: number) => Promise +): Promise { + let picked: PickedContact[]; + try { + picked = await manager.select(properties, { multiple: false }); + } catch { + return { kind: 'failed' }; + } + if (!Array.isArray(picked) || picked.length === 0) return { kind: 'cancelled' }; + const draft = draftFromPicked(picked[0]); + if (!draft) return { kind: 'failed' }; + const icon = picked[0].icon?.[0]; + if (icon && encodeIcon) { + const thumb = await fitThumbnail((size, quality) => encodeIcon(icon, size, quality)); + if (thumb) draft.thumbnailBase64 = thumb; + } + return { kind: 'picked', draft }; +} + +/** + * A picked contact as a draft, or null when the picker returned nothing usable. Duplicate numbers and + * addresses (the picker often repeats them) are removed. The icon is handled separately (it needs a + * canvas to shrink), see {@link fitThumbnail}. + */ +export function draftFromPicked(picked: PickedContact | undefined): ContactDraft | null { + if (!picked) return null; + const unique = (values: string[] | undefined) => { + const seen = new Set(); + const out: ContactEntry[] = []; + for (const raw of values ?? []) { + const value = typeof raw === 'string' ? raw.trim() : ''; + const key = value.replace(/\s+/g, '').toLowerCase(); + if (!value || seen.has(key)) continue; + seen.add(key); + out.push({ value }); + if (out.length >= MAX_CONTACT_FIELDS) break; + } + return out; + }; + const name = (picked.name ?? []).map((n) => (typeof n === 'string' ? n.trim() : '')).find(Boolean) ?? ''; + const phones = unique(picked.tel); + const emails = unique(picked.email); + if (!name && phones.length === 0 && emails.length === 0) return null; + return { displayName: name || phones[0]?.value || emails[0]?.value || '', phones, emails }; +} + +/** + * Finds the largest thumbnail that fits the 24 KB cap. `encode(sizePx, quality)` renders the image as + * a square JPEG and returns its base64 (no data: prefix), or null when it cannot. Tries the sizes and + * qualities in order and returns the first that fits; undefined when none does (the card is sent + * without a photo rather than failing). + */ +export async function fitThumbnail( + encode: (sizePx: number, quality: number) => Promise, + cap = MAX_CONTACT_THUMBNAIL_BASE64 +): Promise { + const attempts: [number, number][] = [ + [160, 0.8], + [128, 0.7], + [96, 0.7], + [96, 0.5], + [64, 0.5], + ]; + for (const [size, quality] of attempts) { + let encoded: string | null = null; + try { + encoded = await encode(size, quality); + } catch { + encoded = null; + } + if (encoded && encoded.length <= cap) return encoded; + } + return undefined; +} diff --git a/src/lib/live-location-sharing.ts b/src/lib/live-location-sharing.ts new file mode 100644 index 0000000..69e26eb --- /dev/null +++ b/src/lib/live-location-sharing.ts @@ -0,0 +1,639 @@ +/** + * Live-location SHARING on the web (the sender side of OneHookBackend/docs/chat-location-contact.md, + * "Live-share lifecycle"). The receiving side is lib/live-location.ts + hooks/use-live-locations.ts. + * + * 1. Start: the chat mints a sessionId, sends the `live_location` message (contentType TEXT), then + * calls {@link LiveLocationSharing.begin}, which publishes the first position straight away (the + * first accepted publish creates the server row and fixes `startedAt`). + * 2. Update: each position fix that moved at least 25 m (or is much more accurate) becomes the share's + * pending update; it goes out when the 5-s window is open. Fixes in between replace it (coalesced, + * never queued). A member standing still publishes nothing. + * 3. Stop: Stop here, Stop on another device (`ended` on onLiveLocation), expiry, the hook released or + * suspended (State, or the server's `Unauthorized` / `CONVERSATION_SUSPENDED`), or the server + * refusing the share. Each one ends the share here; Stop also tells the server. + * + * THE TAB OWNS THE SHARE. Browsers give a web page no background location: there is no service-worker + * geolocation, and a closed tab runs nothing. So a share runs while this tab is open, keeps publishing + * while the tab is hidden for as long as the browser keeps delivering positions to it, and is stopped + * when the page goes away (`pagehide`: a best-effort keepalive `stopLiveLocation`; expiry ends it + * regardless). The UI says so: "Location won't update if you close this tab." + * + * This is NOT the matching location: Discover's coordinates come from hooks/use-user-location.ts, a + * one-shot read that only runs while the page is visible. This engine never touches it. + * + * Pure apart from the injected dependencies (transport, location source, clock, page lifecycle), so the + * throttle, coalescing and lifecycle rules are unit-tested without a browser. + */ +import { GraphQLOperationError } from '../api/graphql-error'; +import { isConversationSuspended } from './call-errors'; +import { buildLiveLocationUpdatePayload, frameStructuredContent, type LocationFix } from './chat-structured'; +import { MAX_LIVE_SHARE_MS } from './live-location'; +import { distanceMeters } from './map-links'; + +/** One accepted publish per 5 s per (match, user, session). */ +export const MIN_PUBLISH_INTERVAL_MS = 5_000; +/** Movement below this is not an update (the web has no OS distance filter, so this is it). */ +export const DISTANCE_FILTER_M = 25; +/** After this long without moving, positions are requested at low accuracy to save battery. */ +export const STATIONARY_AFTER_MS = 2 * 60_000; +/** The backend's ciphertext cap (16 KB). A sealed update is far smaller; bigger means a bug. */ +export const MAX_LIVE_CIPHERTEXT_CHARS = 16_384; +/** How often expiry and the pending update are checked while a share runs. */ +export const TICK_MS = 1_000; + +/** How often the token copy for the pagehide stop is refreshed while a share runs. */ +export const UNLOAD_AUTH_REFRESH_MS = 5 * 60_000; + +/** The duration choices, with their `chat.live_location_duration` values. */ +export const LIVE_DURATIONS = [ + { value: 'min_15', label: '15 minutes', ms: 15 * 60_000 }, + { value: 'hour_1', label: '1 hour', ms: 60 * 60_000 }, + { value: 'hour_8', label: '8 hours', ms: 8 * 60 * 60_000 }, +] as const; + +export type LiveDurationValue = (typeof LIVE_DURATIONS)[number]['value']; + +/** The copy shown everywhere a share is started and on the sharing banner. */ +export const TAB_BOUND_COPY = "Location won't update if you close this tab."; + +/** Why a share ended on this tab. */ +export type LiveShareEndReason = + /** The member tapped Stop here. */ + | 'stopped' + /** It reached `expiresAt`. */ + | 'expired' + /** Stopped on another device or tab, or the server says it is over (`LIVE_LOCATION_ENDED`). */ + | 'ended_elsewhere' + /** The hook was released or blocked (`Unauthorized`, or the hook left State). */ + | 'released' + /** The conversation became read-only (`CONVERSATION_SUSPENDED`, or State says suspended). */ + | 'suspended' + /** The server refused the share (`BadRequest`: a bug, logged). */ + | 'rejected' + /** Location permission was revoked while sharing. */ + | 'location_denied' + /** The page was closed, reloaded or navigated away. */ + | 'tab_closed' + /** The member signed out. */ + | 'signed_out'; + +/** The toast for a share that ended by itself; null when the member did it (nothing to explain). */ +export function endNotice(reason: LiveShareEndReason): string | null { + switch (reason) { + case 'expired': + return 'Live location ended'; + case 'ended_elsewhere': + return 'Live location stopped on another device'; + case 'released': + return "Live location stopped: you're no longer hooked"; + case 'suspended': + return 'Live location paused: this chat is read only'; + case 'rejected': + return "Live location couldn't continue"; + case 'location_denied': + return 'Live location stopped: location access was turned off for this site'; + default: + return null; + } +} + +/** What one publish attempt came to. */ +export type PublishOutcome = + | { kind: 'published' } + /** `Throttled`: drop this update (never queue it); the next fix goes out. */ + | { kind: 'throttled' } + /** Transport or encryption failure: keep sharing, the next fix tries again. */ + | { kind: 'failed' } + | { kind: 'ended'; reason: LiveShareEndReason }; + +/** Maps a publish error to what the sharer does (the contract's "Errors" table). */ +export function publishOutcomeFromError(err: unknown): PublishOutcome { + if (isConversationSuspended(err)) return { kind: 'ended', reason: 'suspended' }; + const type = err instanceof GraphQLOperationError ? err.errorType : undefined; + switch (type) { + case 'Throttled': + return { kind: 'throttled' }; + case 'LIVE_LOCATION_ENDED': + return { kind: 'ended', reason: 'ended_elsewhere' }; + case 'Unauthorized': + return { kind: 'ended', reason: 'released' }; + case 'BadRequest': + return { kind: 'ended', reason: 'rejected' }; + default: + return { kind: 'failed' }; + } +} + +/** A new share's window: now until `durationMs` from now, never past the backend's 8-hour ceiling. */ +export function makeLiveWindow(durationMs: number, now: number): { startedAt: number; expiresAt: number } { + const length = Math.max(1, Math.min(Math.round(durationMs), MAX_LIVE_SHARE_MS)); + return { startedAt: now, expiresAt: now + length }; +} + +/** A new share's sessionId: a UUID v4 (the backend accepts 8 to 64 of `A-Z a-z 0-9 -`). */ +export function newLiveSessionId( + rng: Pick & { randomUUID?: () => string } = globalThis.crypto +): string { + if (typeof rng.randomUUID === 'function') return rng.randomUUID(); + const bytes = rng.getRandomValues(new Uint8Array(16)); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + +/** + * Whether `next` is worth publishing after `reference` (the last position that counted): it moved at + * least 25 m and by more than its own accuracy radius (so GPS jitter while standing still is not + * movement), or it is a much better fix of about the same place. + */ +export function isSignificantMove(reference: LocationFix | undefined, next: LocationFix): boolean { + if (!reference) return true; + const moved = distanceMeters(reference, next); + if (moved >= DISTANCE_FILTER_M && moved >= (next.accuracyM ?? 0)) return true; + const before = reference.accuracyM; + const after = next.accuracyM; + return before !== undefined && after !== undefined && after <= before / 2 && before - after >= 10; +} + +// ── Dependencies ───────────────────────────────────────────────────────────── + +/** The GraphQL calls the engine makes (api/live-location.ts in the app; a fake in tests). */ +export interface LiveSharingTransport { + publish(matchId: string, sessionId: string, ciphertext: string, expiresAt: number): Promise; + stop(matchId: string, sessionId: string): Promise; + /** Synchronous best-effort stop from `pagehide`. Returns whether a request was attempted. */ + stopOnUnload(matchId: string, sessionId: string): boolean; + /** Follows `onLiveLocation` for a match; returns an unsubscribe function. */ + subscribe(matchId: string, onRow: (row: { matchId: string; userId: string; sessionId: string; ended: boolean }) => void): () => void; + /** Refreshes the token copy the unload stop uses. */ + primeUnloadAuth(): Promise; + clearUnloadAuth(): void; +} + +export interface LocationWatchOptions { + highAccuracy: boolean; +} + +/** Where positions come from while a share runs (`navigator.geolocation.watchPosition` in the app). */ +export interface LiveLocationSource { + /** Starts watching. `onDenied` fires when permission is refused or revoked. Returns a stop function. */ + watch(onFix: (fix: LocationFix) => void, onDenied: () => void, options: LocationWatchOptions): () => void; +} + +export interface SharingClock { + now(): number; + setInterval(fn: () => void, ms: number): unknown; + clearInterval(handle: unknown): void; +} + +/** The page's lifecycle (`window` in the app). */ +export interface PageLifecycle { + /** Calls `fn` when the page is being unloaded (or frozen into the back/forward cache). */ + onPageHide(fn: () => void): () => void; +} + +export interface LiveSharingDeps { + transport: LiveSharingTransport; + location: LiveLocationSource; + clock: SharingClock; + page: PageLifecycle; + log?: (message: string) => void; +} + +// ── State ──────────────────────────────────────────────────────────────────── + +/** Seals a plaintext for this conversation exactly like a message body (wire v2, `matchId` AAD). */ +export type SealForMatch = (plaintext: string) => Promise; + +export interface BeginShareInput { + matchId: string; + sessionId: string; + startedAt: number; + expiresAt: number; + /** The signed-in member (owner of the share), to recognise its own `ended` events. */ + userId: string; + peerName: string; + seal: SealForMatch; +} + +/** One share this tab runs, as the UI sees it. */ +export interface LiveShareView { + matchId: string; + sessionId: string; + peerName: string; + startedAt: number; + expiresAt: number; + /** The last position the server accepted. */ + latest?: LocationFix; + /** When it was accepted (local clock). */ + lastPublishedAt?: number; +} + +/** A share this tab ended, so its bubble shows as ended at once (before or without the server echo). */ +export interface EndedShare { + matchId: string; + sessionId: string; + expiresAt: number; + reason: LiveShareEndReason; +} + +export interface LiveSharingSnapshot { + /** Running shares, by matchId (at most one per conversation). */ + shares: Readonly>; + /** Recently ended shares, by sessionId. */ + ended: Readonly>; + /** True while positions are requested at low accuracy (standing still). */ + lowPower: boolean; +} + +interface ShareState extends LiveShareView { + userId: string; + seal: SealForMatch; + /** When the last publish was sent (accepted or not): the 5-s window counts from here. */ + lastAttemptAt?: number; + /** The newest fix not yet sent, waiting for the window. */ + pending?: LocationFix; + inFlight: boolean; + /** Failed publishes in a row (reset by a success or by a new fix). */ + failures: number; + unsubscribe: () => void; +} + +/** How many times one fix is re-sent after transport failures before waiting for the next fix. */ +export const MAX_RETRIES_PER_FIX = 3; + +const MAX_REMEMBERED_ENDS = 50; + +export class LiveLocationSharing { + private readonly deps: LiveSharingDeps; + private readonly shares = new Map(); + private ended: Record = {}; + private snapshot: LiveSharingSnapshot = { shares: {}, ended: {}, lowPower: false }; + private readonly listeners = new Set<() => void>(); + private readonly endListeners = new Set<(end: EndedShare) => void>(); + private stopWatch: (() => void) | null = null; + private highAccuracy = true; + private timer: unknown = null; + private removePageHide: (() => void) | null = null; + /** The last fix that counted as movement; later fixes are measured from it. */ + private reference: LocationFix | undefined; + private lastMoveAt = 0; + /** When the unload token copy was last refreshed. */ + private lastPrimeAt = 0; + + constructor(deps: LiveSharingDeps) { + this.deps = deps; + } + + // ── Observing ── + + /** For `useSyncExternalStore`. */ + subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + }; + + getSnapshot = (): LiveSharingSnapshot => this.snapshot; + + /** Called once per share that ends here, with the reason. */ + onEnd(listener: (end: EndedShare) => void): () => void { + this.endListeners.add(listener); + return () => { + this.endListeners.delete(listener); + }; + } + + share(matchId: string): LiveShareView | undefined { + return this.snapshot.shares[matchId]; + } + + isRunning(sessionId: string): boolean { + for (const share of this.shares.values()) if (share.sessionId === sessionId) return true; + return false; + } + + // ── Lifecycle ── + + /** + * The start message is on the server: run the share and publish `firstFix` at once. A previous share + * in the same conversation is stopped first, so each member has one running share per conversation. + */ + async begin(input: BeginShareInput, firstFix: LocationFix): Promise { + const now = this.deps.clock.now(); + if (input.expiresAt <= now) return; + const previous = this.shares.get(input.matchId); + if (previous && previous.sessionId !== input.sessionId) await this.stop(input.matchId); + if (this.shares.has(input.matchId)) return; + + const unsubscribe = this.deps.transport.subscribe(input.matchId, (row) => this.handleRow(row)); + this.shares.set(input.matchId, { + matchId: input.matchId, + sessionId: input.sessionId, + peerName: input.peerName, + startedAt: input.startedAt, + expiresAt: Math.min(input.expiresAt, input.startedAt + MAX_LIVE_SHARE_MS), + userId: input.userId, + seal: input.seal, + pending: firstFix, + inFlight: false, + failures: 0, + unsubscribe, + }); + if (!this.reference) { + this.reference = firstFix; + this.lastMoveAt = now; + } + void this.deps.transport.primeUnloadAuth(); + this.lastPrimeAt = now; + this.updateRunning(); + this.emit(); + await this.flush(input.matchId); + } + + /** A new position: when it counts as movement it becomes every share's pending update. */ + async handleFix(fix: LocationFix): Promise { + if (this.shares.size === 0) return; + if (!isSignificantMove(this.reference, fix)) return; + this.reference = fix; + this.lastMoveAt = this.deps.clock.now(); + if (!this.highAccuracy) this.setAccuracy(true); + for (const share of this.shares.values()) { + share.pending = fix; + share.failures = 0; + } + await Promise.all([...this.shares.keys()].map((matchId) => this.flush(matchId))); + } + + /** Ends expired shares, sends a pending update whose window opened, drops to low power when still. */ + async tick(): Promise { + const now = this.deps.clock.now(); + for (const share of [...this.shares.values()]) { + if (now >= share.expiresAt) this.end(share.matchId, 'expired'); + } + if (this.shares.size > 0 && this.highAccuracy && now - this.lastMoveAt >= STATIONARY_AFTER_MS) { + this.setAccuracy(false); + } + // Someone standing still publishes nothing, and publishing is what refreshes the token copy the + // pagehide stop needs. Refresh it on a timer too, so it has not expired when the tab closes. + if (this.shares.size > 0 && now - this.lastPrimeAt >= UNLOAD_AUTH_REFRESH_MS) { + this.lastPrimeAt = now; + void this.deps.transport.primeUnloadAuth(); + } + await Promise.all( + [...this.shares.values()].filter((s) => s.pending).map((s) => this.flush(s.matchId)) + ); + } + + /** The member tapped Stop on this tab's share: end it here, then tell the server (best effort). */ + async stop(matchId: string): Promise { + const share = this.shares.get(matchId); + if (!share) return; + this.end(matchId, 'stopped'); + await this.stopOnServer(matchId, share.sessionId); + } + + /** + * Stop for one of the member's shares this tab may not run (started on another device or tab). The + * server keys the row by the caller, so only the owner can stop it. + */ + async stopRemote(matchId: string, sessionId: string): Promise { + if (this.shares.get(matchId)?.sessionId === sessionId) { + await this.stop(matchId); + return; + } + this.remember({ matchId, sessionId, expiresAt: this.deps.clock.now(), reason: 'stopped' }); + this.emit(); + await this.stopOnServer(matchId, sessionId); + } + + /** An `onLiveLocation` row: this member's share ended elsewhere (another device, the backend). */ + handleRow(row: { matchId: string; userId: string; sessionId: string; ended: boolean }): void { + const share = this.shares.get(row.matchId); + if (!share || !row.ended || row.userId !== share.userId || row.sessionId !== share.sessionId) return; + this.end(row.matchId, 'ended_elsewhere'); + } + + /** + * State changed: a share whose hook is gone (released, blocked) or suspended ends. No network: the + * backend already ended it. `hooks` null means State has not loaded, which proves nothing. + */ + reconcile(hooks: readonly { matchId: string; suspended?: boolean }[] | null | undefined): void { + if (!hooks) return; + const byMatch = new Map(hooks.map((h) => [h.matchId, h])); + for (const matchId of [...this.shares.keys()]) { + const hook = byMatch.get(matchId); + if (!hook) this.end(matchId, 'released'); + else if (hook.suspended) this.end(matchId, 'suspended'); + } + } + + /** + * Signed out (or another account signed in): end everything. The stop goes out through the + * keepalive path first, because it carries its own copy of the token and still works when the + * sign-out has already cleared Amplify's session; the Amplify call is the fallback. + */ + endAll(reason: LiveShareEndReason): void { + for (const share of [...this.shares.values()]) { + this.end(share.matchId, reason); + if (!this.deps.transport.stopOnUnload(share.matchId, share.sessionId)) { + void this.stopOnServer(share.matchId, share.sessionId); + } + } + this.deps.transport.clearUnloadAuth(); + } + + /** + * The page is going away. Nothing can be awaited here, so each share gets a synchronous keepalive + * `stopLiveLocation` (best effort) and ends locally. If the browser drops the request the share + * still ends at `expiresAt`. + */ + handlePageHide(): void { + for (const share of [...this.shares.values()]) { + const attempted = this.deps.transport.stopOnUnload(share.matchId, share.sessionId); + if (!attempted) this.deps.log?.('live location: unload stop not attempted, the share ends at expiry'); + this.end(share.matchId, 'tab_closed'); + } + } + + // ── Publishing ── + + private async flush(matchId: string): Promise { + const now = this.deps.clock.now(); + const share = this.shares.get(matchId); + if (!share) return; + if (now >= share.expiresAt) { + this.end(matchId, 'expired'); + return; + } + const pending = share.pending; + if (!pending || share.inFlight) return; + if (share.lastAttemptAt !== undefined && now < share.lastAttemptAt + MIN_PUBLISH_INTERVAL_MS) return; + share.pending = undefined; + share.inFlight = true; + share.lastAttemptAt = now; + + const outcome = await this.publish(share, pending); + const after = this.shares.get(matchId); + // The share may have been stopped, or replaced by a new one, while the publish was in flight. + if (!after || after.sessionId !== share.sessionId) return; + after.inFlight = false; + switch (outcome.kind) { + case 'published': + after.latest = pending; + after.lastPublishedAt = this.deps.clock.now(); + after.failures = 0; + this.emit(); + break; + case 'throttled': + break; + case 'failed': + // A transient failure (network, the peer's devices not readable just now). Someone standing + // still produces no new fix, so the same one is retried after the 5-s window, a few times, + // unless a newer fix has replaced it meanwhile. Coalesced: still at most one pending update. + after.failures += 1; + if (!after.pending && after.failures <= MAX_RETRIES_PER_FIX) after.pending = pending; + break; + case 'ended': + this.end(matchId, outcome.reason); + break; + } + } + + private async publish(share: ShareState, fix: LocationFix): Promise { + let ciphertext: string; + try { + ciphertext = await share.seal(frameStructuredContent(buildLiveLocationUpdatePayload(share.sessionId, fix))); + } catch { + // The peer's devices could not be read just now, or the fix was unusable: try the next one. + return { kind: 'failed' }; + } + if (ciphertext.length > MAX_LIVE_CIPHERTEXT_CHARS) { + this.deps.log?.('live location: sealed update over 16 KB, share rejected'); + return { kind: 'ended', reason: 'rejected' }; + } + try { + await this.deps.transport.publish(share.matchId, share.sessionId, ciphertext, share.expiresAt); + return { kind: 'published' }; + } catch (err) { + const outcome = publishOutcomeFromError(err); + if (outcome.kind === 'ended' && outcome.reason === 'rejected') { + this.deps.log?.('live location: publish rejected (BadRequest)'); + } + return outcome; + } + } + + private async stopOnServer(matchId: string, sessionId: string): Promise { + try { + await this.deps.transport.stop(matchId, sessionId); + } catch { + this.deps.log?.('live location: stop failed, the share ends at expiry'); + } + } + + // ── Running state ── + + private end(matchId: string, reason: LiveShareEndReason): void { + const share = this.shares.get(matchId); + if (!share) return; + this.shares.delete(matchId); + share.unsubscribe(); + const ended: EndedShare = { matchId, sessionId: share.sessionId, expiresAt: share.expiresAt, reason }; + this.remember(ended); + this.updateRunning(); + this.emit(); + for (const listener of this.endListeners) listener(ended); + } + + private remember(ended: EndedShare): void { + const next = { ...this.ended, [ended.sessionId]: ended }; + const keys = Object.keys(next); + if (keys.length > MAX_REMEMBERED_ENDS) delete next[keys[0]]; + this.ended = next; + } + + /** Position updates, the tick and the pagehide hook run only while at least one share does. */ + private updateRunning(): void { + if (this.shares.size === 0) { + this.stopWatch?.(); + this.stopWatch = null; + if (this.timer !== null) this.deps.clock.clearInterval(this.timer); + this.timer = null; + this.removePageHide?.(); + this.removePageHide = null; + this.reference = undefined; + this.highAccuracy = true; + return; + } + if (!this.stopWatch) this.startWatch(); + if (this.timer === null) this.timer = this.deps.clock.setInterval(() => void this.tick(), TICK_MS); + if (!this.removePageHide) this.removePageHide = this.deps.page.onPageHide(() => this.handlePageHide()); + } + + private startWatch(): void { + this.stopWatch = this.deps.location.watch( + (fix) => void this.handleFix(fix), + () => { + for (const matchId of [...this.shares.keys()]) { + const share = this.shares.get(matchId); + this.end(matchId, 'location_denied'); + if (share) void this.stopOnServer(matchId, share.sessionId); + } + }, + { highAccuracy: this.highAccuracy } + ); + } + + /** Restarts the position watch at the new accuracy (the Geolocation API cannot change it in place). */ + private setAccuracy(high: boolean): void { + if (this.highAccuracy === high) return; + this.highAccuracy = high; + if (this.stopWatch) { + this.stopWatch(); + this.stopWatch = null; + this.startWatch(); + } + this.emit(); + } + + private emit(): void { + const shares: Record = {}; + for (const s of this.shares.values()) { + const view: LiveShareView = { + matchId: s.matchId, + sessionId: s.sessionId, + peerName: s.peerName, + startedAt: s.startedAt, + expiresAt: s.expiresAt, + }; + if (s.latest) view.latest = s.latest; + if (s.lastPublishedAt !== undefined) view.lastPublishedAt = s.lastPublishedAt; + shares[s.matchId] = view; + } + this.snapshot = { shares, ended: this.ended, lowPower: !this.highAccuracy && this.shares.size > 0 }; + for (const listener of this.listeners) listener(); + } +} + +/** + * The conversation's live sessions with this tab's own ended shares applied, so a bubble shows "Ended" + * the moment Stop is tapped (or the share ends here) instead of waiting for the server's echo. + */ +export function withLocalEnds>( + sessions: T, + ended: Readonly>, + matchId: string, + userId: string, + now: number, + merge: (sessions: T, incoming: { userId: string; sessionId: string; at: number; expiresAt: number; ended: boolean }) => T +): T { + let out = sessions; + for (const end of Object.values(ended)) { + if (end.matchId !== matchId) continue; + out = merge(out, { userId, sessionId: end.sessionId, at: now, expiresAt: end.expiresAt, ended: true }); + } + return out; +} diff --git a/src/lib/mr-onehook-contract.ts b/src/lib/mr-onehook-contract.ts index 373dbb5..fd73c53 100644 --- a/src/lib/mr-onehook-contract.ts +++ b/src/lib/mr-onehook-contract.ts @@ -23,11 +23,6 @@ export const MR_ONEHOOK_MOODS: readonly MrOneHookMood[] = [ 'Excited', ]; -/** Anonymous product chat used by the public landing widget. */ -export const PUBLIC_PRODUCT_CHAT_PATH = '/api/public/product-chat'; -/** Authenticated member product + connection chat (and its `/sessions` sub-routes). */ -export const MEMBER_CHAT_PATH = '/api/member/product-connection-chat'; - /** A single rendered turn in the local Mr.OneHook transcript. */ export interface MrOneHookMessage { role: 'user' | 'assistant'; diff --git a/src/lib/mr-onehook.ts b/src/lib/mr-onehook.ts index 1ab7ec2..c773fc3 100644 --- a/src/lib/mr-onehook.ts +++ b/src/lib/mr-onehook.ts @@ -2,9 +2,10 @@ * Mr.OneHook — the in-app, authenticated AI conversation. * * Mr.OneHook is NOT a person and has no match record: this transcript is local-only (React state + - * per-user/per-scope localStorage) and must never be surfaced as a match. The only network call is - * the authenticated member endpoint `POST ${chatbotUrl}/api/member/product-connection-chat`, sent - * with the Amplify Cognito ID token as a Bearer credential. + * per-user/per-scope localStorage) and must never be surfaced as a match. Every network call goes + * through the published `onehook-mr-onehook-client` (`mrOneHookClient`): the member chat + * turn (ProductConnectionChat) and the saved-chat routes, each with the Amplify Cognito ID token as a + * Bearer credential. * * A conversation has one scope: product-only (no matchId) or exactly one authorized match. Match * scope can ground answers in locally-decrypted history, but ONLY after the model asks for more @@ -17,14 +18,14 @@ * session so the user still gets an answer. */ import { useCallback, useEffect, useRef, useState } from 'react'; -import { chatbotUrl } from '../utils/env.config'; +import type { ProductConnectionChatCommandInput } from 'onehook-mr-onehook-client'; +import { fetchIdToken, mrOneHookClient, sdkFailure, withoutMetadata } from '../api/external-sdk-clients'; import { isPaidSubscriptionTier } from 'onehook-api-client/membership'; import type { SubscriptionTier } from '../types'; import { buildMemberChatRequestBody, classifyMemberChatAvailability, isSessionErrorCode, - MEMBER_CHAT_PATH, type MemberChatAvailability, parseMemberChatResponse, matchSuggestionNote, @@ -39,6 +40,20 @@ import { } from './mr-onehook-contract'; import type { ExcerptSelectionRequest, ExcerptSelectionResult } from './mr-onehook-excerpts'; + +/** A saved-chat call's result: the output, or the HTTP status of a failure (a network error throws). */ +type SessionCallResult = { ok: true; data: unknown } | { ok: false; status: number }; + +async function sessionCall(call: () => Promise): Promise { + try { + return { ok: true, data: withoutMetadata(await call()) }; + } catch (err) { + const failure = sdkFailure(err); + if (!failure) throw err; + return { ok: false, status: failure.status }; + } +} + export type { MrOneHookMessage, MrOneHookMood, SessionListItem } from './mr-onehook-contract'; // Mirrors ChatbotWidget's failure copy so the AI voice is consistent across surfaces. @@ -281,16 +296,6 @@ function persistSessionId(userId: string, scope: MrOneHookScope, sessionId: stri * token (it checks `aud` and reads the member's roles/tier from claims the ACCESS token does not * carry), so the ID token — not the access token — is the correct bearer here. */ -async function fetchIdToken(): Promise { - try { - const { fetchAuthSession } = await import('aws-amplify/auth'); - const session = await fetchAuthSession(); - return session.tokens?.idToken?.toString() || null; - } catch { - return null; - } -} - function toEpochMs(iso?: string): number | undefined { if (!iso) return undefined; const value = Date.parse(iso); @@ -397,7 +402,12 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook const token = await fetchIdToken(); if (!token) throw new Error('NOT_AUTHENTICATED'); - const attempt = async (useSession: boolean): Promise => { + // One generated-SDK call (ProductConnectionChat). An HTTP failure comes back as {status, body} so + // the session and availability rules below can read the error code; a network error throws. + type Attempt = + | { ok: true; data: unknown } + | { ok: false; status: number; body: { error?: unknown } & Record }; + const attempt = async (useSession: boolean): Promise => { const body = buildMemberChatRequestBody({ message: init.message, ...(matchId ? { matchId } : {}), @@ -415,16 +425,19 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook } : {}), }); - return fetch(`${chatbotUrl}${MEMBER_CHAT_PATH}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, - body: JSON.stringify(body), - }); + try { + const out = await mrOneHookClient.productConnectionChat(body as ProductConnectionChatCommandInput); + return { ok: true, data: withoutMetadata(out) }; + } catch (err) { + const failure = sdkFailure(err); + if (!failure) throw err; + return { ok: false, status: failure.status, body: failure.body }; + } }; let response = await attempt(persistAllowed); - if (!response.ok && persistAllowed) { - const errorBody = (await response.clone().json().catch(() => ({}))) as { error?: unknown }; + if (response.ok === false && persistAllowed) { + const errorBody = response.body; // A NEW saved chat at the limit: let the member choose (replace the least recent, or delete one). const limit = sessionLimitFromError(errorBody, Boolean(sessionIdRef.current)); if (limit) throw new SessionLimitReachedError(limit.maxSessions, limit.sessions); @@ -437,16 +450,16 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook } } - if (!response.ok) { + if (response.ok === false) { // Distinguish a terminal auth/permission/config outcome (not retryable, gates the entry) // from a transient server error (retryable bubble). The structured `error` code is the // tie-breaker over the HTTP status. - const errorBody = (await response.clone().json().catch(() => ({}))) as { error?: unknown }; + const errorBody = response.body; const outcome = classifyMemberChatAvailability(response.status, errorBody.error); if (outcome) throw new MemberChatTerminalError(outcome); throw new Error('SERVER_ERROR'); } - return parseMemberChatResponse(await response.json()); + return parseMemberChatResponse((response as { data: unknown }).data); }, // scope captured via key + matchId; persistAllowed derived from tier. // eslint-disable-next-line react-hooks/exhaustive-deps @@ -578,14 +591,16 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook // eslint-disable-next-line react-hooks/exhaustive-deps }, [userId, key]); - const authorizedFetch = useCallback(async (path: string, init?: RequestInit): Promise => { - const token = await fetchIdToken(); - if (!token) throw new Error('NOT_AUTHENTICATED'); - return fetch(`${chatbotUrl}${MEMBER_CHAT_PATH}${path}`, { - ...init, - headers: { ...(init?.headers ?? {}), Authorization: `Bearer ${token}` }, - }); - }, []); + // Saved-chat routes (ListChatSessions, GetChatSession, DeleteChatSession) through the generated SDK. + const listSessions = useCallback(() => sessionCall(() => mrOneHookClient.listChatSessions({})), []); + const getSession = useCallback( + (sessionId: string) => sessionCall(() => mrOneHookClient.getChatSession({ sessionId })), + [], + ); + const removeSession = useCallback( + (sessionId: string) => sessionCall(() => mrOneHookClient.deleteChatSession({ sessionId })), + [], + ); const refreshSessions = useCallback(async () => { if (!persistAllowed) { @@ -593,19 +608,19 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook return; } try { - const response = await authorizedFetch('/sessions'); - if (response.ok) setSessions(parseSessionList(await response.json())); + const response = await listSessions(); + if (response.ok === true) setSessions(parseSessionList(response.data)); } catch { /* the list is a convenience; chatting still works */ } - }, [authorizedFetch, persistAllowed]); + }, [listSessions, persistAllowed]); const resumeSession = useCallback( async (sessionId: string) => { if (!persistAllowed || loading) return; try { - const response = await authorizedFetch(`/sessions/${encodeURIComponent(sessionId)}`); - const detail = response.ok ? parseSessionDetail(await response.json()) : undefined; + const response = await getSession(sessionId); + const detail = response.ok === true ? parseSessionDetail(response.data) : undefined; if (!detail) throw new Error('SERVER_ERROR'); if ((detail.matchId ?? undefined) !== matchId) { // A chat from another scope: remember it there and let the host switch. @@ -630,14 +645,14 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook } }, // eslint-disable-next-line react-hooks/exhaustive-deps - [authorizedFetch, persistAllowed, loading, userId, key, pushError], + [getSession, persistAllowed, loading, userId, key, pushError], ); const deleteSession = useCallback( async (sessionId: string) => { if (!persistAllowed) return; - const response = await authorizedFetch(`/sessions/${encodeURIComponent(sessionId)}`, { method: 'DELETE' }); - if (!response.ok && response.status !== 404) throw new Error('SERVER_ERROR'); + const response = await removeSession(sessionId); + if (response.ok === false && response.status !== 404) throw new Error('SERVER_ERROR'); setSessions((prev) => prev.filter((s) => s.sessionId !== sessionId)); setSessionLimit((prev) => (prev ? { ...prev, sessions: prev.sessions.filter((s) => s.sessionId !== sessionId) } @@ -651,7 +666,7 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook } }, // eslint-disable-next-line react-hooks/exhaustive-deps - [authorizedFetch, persistAllowed, userId, key], + [removeSession, persistAllowed, userId, key], ); const replaceLeastRecentAndSend = useCallback(async () => { @@ -691,9 +706,9 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook let cancelled = false; void (async () => { try { - const response = await authorizedFetch('/sessions'); - if (!response.ok || cancelled) return; - const list = parseSessionList(await response.json()); + const response = await listSessions(); + if (response.ok === false || cancelled) return; + const list = parseSessionList(response.data); if (cancelled) return; setSessions(list); const remembered = sessionIdRef.current; @@ -713,8 +728,8 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook ?.sessionId : undefined); if (!wanted) return; - const detailResponse = await authorizedFetch(`/sessions/${encodeURIComponent(wanted)}`); - const detail = detailResponse.ok ? parseSessionDetail(await detailResponse.json()) : undefined; + const detailResponse = await getSession(wanted); + const detail = detailResponse.ok === true ? parseSessionDetail(detailResponse.data) : undefined; if (cancelled || !detail) return; sessionIdRef.current = detail.sessionId; persistSessionId(userId, scope, detail.sessionId); @@ -729,7 +744,7 @@ export function useMrOneHookChat(options: UseMrOneHookChatOptions): UseMrOneHook }; // scope is reconstructed each render; key is its stable identity. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [userId, key, persistAllowed, authorizedFetch, sessionsVersion]); + }, [userId, key, persistAllowed, listSessions, getSession, sessionsVersion]); return { messages, diff --git a/src/tests/api-route-contract.test.ts b/src/tests/api-route-contract.test.ts index 10c6c3b..bb80e8a 100644 --- a/src/tests/api-route-contract.test.ts +++ b/src/tests/api-route-contract.test.ts @@ -1,22 +1,42 @@ /** - * Route contract: the web app calls only HTTP routes that are Smithy operations. + * API contract: every request the web app makes to a OneHook API goes through the generated + * `onehook-api-client` package. Nothing in src/ builds a OneHook URL or request by hand. * - * Smithy (OneHookBackend/packages/api-models/model/smithy) is the single source of every API, and the - * synced manifest src/lib/analytics/generated/apiManifest.ts lists each operation's - * `{operationId, method, path, service}`. ./api-route-scan.ts finds every request in src/ (the REST - * helpers in src/api, raw fetches to the API or to Mr. OneHook, XHR uploads, and the - * `onehook-api-client` SDK calls) and resolves it. This test then requires: + * Each API's Smithy model is owned by the repo that serves it, and each owner's route manifest lists its + * operations as `{operationId, method, path, service}`: the backend's is synced to + * src/lib/analytics/generated/apiManifest.ts, Mr OneHook's and the portal's come from their packages + * (`/manifest`). ./api-route-scan.ts finds every request in src/ (raw + * fetches, XHR, and calls on the generated clients) and resolves it. This test then requires: * - * - every resolved `method + path` to be a manifest operation of that origin (path-parameter names - * ignored): the API base against the AWS services, `chatbotUrl` against MrOneHookService, and - * `portalModerationBaseUrl` against the admin portal's ModerationEvidenceService (the path joined to - * the configured base URL's path, e.g. /api/p/onehook/gamma/moderation + /evidence/presign); - * - every SDK call (`sdkClient.getState(...)` → GetState, `new XCommand`) to be a manifest operationId; - * - every call site to resolve. A site the scanner can't resolve fails here unless it is listed in - * {@link EXCEPTIONS} with a reason; an exception that no longer matches fails too. + * - NO hand-built request to an API: a raw `fetch`/XHR whose URL starts with the API base, + * `chatbotUrl` or `portalModerationBaseUrl` fails, whatever its path. Use the client from the package + * the API's owner publishes instead: `sdkClient` (`onehook-api-client`, OneHookBackend) for the backend, + * `mrOneHookClient` (`onehook-mr-onehook-client`, OneHookUXEnhancement) for Mr OneHook, + * `createModerationEvidenceClient` (`saha-equation-admin-portal-client`, OneHookAdminPortal) for the portal's + * evidence API. A missing operation is added to that owner's Smithy model and published, never written + * here; + * - every SDK call (`sdkClient.getState(...)` → GetState, `new XCommand`) to be a manifest operation + * of the service its client serves; + * - every raw request left to go to a URL the API returned (presigned S3), listed in + * {@link EXCEPTIONS} with a reason, and every call site to resolve. An exception that no longer + * matches fails too. */ import { describe, it, expect } from 'vitest'; -import { API_OPERATIONS, type ApiOperation } from '../lib/analytics/generated/apiManifest'; +import { API_OPERATIONS as BACKEND_OPERATIONS } from '../lib/analytics/generated/apiManifest'; +import { API_OPERATIONS as MR_ONEHOOK_OPERATIONS } from 'onehook-mr-onehook-client/manifest'; +import { API_OPERATIONS as PORTAL_OPERATIONS } from 'saha-equation-admin-portal-client/manifest'; + +/** One manifest entry; the owners' manifests share this shape (their `auth` values differ). */ +interface ApiOperation { + readonly operationId: string; + readonly method: string; + readonly path: string; + readonly service: string; + readonly auth: string; +} + +/** Every operation the web app may call, from each owner's manifest. */ +const API_OPERATIONS: readonly ApiOperation[] = [...BACKEND_OPERATIONS, ...MR_ONEHOOK_OPERATIONS, ...PORTAL_OPERATIONS]; import { portalModerationBaseUrl } from '../utils/env.config'; import { normalizePath, @@ -25,6 +45,7 @@ import { type Base, type ResolvedRoute, type ScanResult, + type SdkService, } from './api-route-scan'; const ROOT = new URL('../../', import.meta.url).pathname; @@ -94,16 +115,23 @@ const EXCEPTIONS: readonly Exception[] = [ reason: 'PUT of the report evidence bundle to the presigned S3 URL (and method) that the portal evidence presign returned. It goes to S3, not to a OneHook API.', }, + { + kind: 'site', + file: 'src/api/live-location.ts', + owner: 'stopOnUnload', + target: 'auth.endpoint', + count: 1, + reason: + 'The stopLiveLocation GraphQL mutation sent to the AppSync endpoint as a keepalive fetch from pagehide, because the Amplify client cannot send during unload. It is AppSync GraphQL, not a Smithy REST route.', + }, ]; /** * Exported request helpers that no file in src/ calls, so they make no request today. Pinned so that * the first caller makes the scanner resolve (or report) it. - * - * - createFetchTransport: the analytics SDK's generic transport factory. The app sends signals through - * api/analytics.ts (POST /signals, checked above) instead. + * (None today.) */ -const EXPECTED_UNCALLED_HELPERS = ['src/lib/analytics/analyticsClient.ts:createFetchTransport']; +const EXPECTED_UNCALLED_HELPERS: string[] = []; const routeKey = (method: string, path: string) => `${method.toUpperCase()} ${normalizePath(path)}`; @@ -154,6 +182,28 @@ const MANIFEST: Record> = Object.fromEntries( ) as Record>; const OPERATION_IDS = new Set(API_OPERATIONS.map((o) => o.operationId)); +/** Manifest services each generated client serves. */ +const SDK_SERVICES: Record boolean> = { + aws: ofBase('api'), + 'mr-onehook': (o) => o.service === 'mr-onehook', + 'moderation-evidence': (o) => o.service === 'moderation-evidence', +}; +const OPERATIONS_OF: Record> = Object.fromEntries( + (Object.keys(SDK_SERVICES) as SdkService[]).map((svc) => [ + svc, + new Set(API_OPERATIONS.filter(SDK_SERVICES[svc]).map((o) => o.operationId)), + ]) +) as Record>; + +/** The Smithy operation a hand-built route corresponds to, for the error message. */ +function operationFor(r: ResolvedRoute): string { + const op = API_OPERATIONS.filter(ofBase(r.base)).find((o) => { + const rel = relativeToBase(o.path, BASE_PATH[r.base]); + return rel !== null && routeKey(o.method, rel) === routeKey(r.method, r.path); + }); + return op ? `use the SDK operation ${op.operationId}` : 'not a Smithy operation either: add it to Smithy, then call it through the SDK'; +} + const isRouteException = (r: ResolvedRoute, e: Exception): e is RouteException => e.kind === 'route' && e.base === r.base && routeKey(e.method, e.path) === routeKey(r.method, r.path); @@ -166,9 +216,13 @@ function violations(scan: ScanResult, exceptions: readonly Exception[]) { .filter((r) => !exceptions.some((e) => isRouteException(r, e))) .map((r) => `${where(r)} ${r.base} ${routeKey(r.method, r.path)}${r.via ? ` (via ${r.via})` : ''}`); + const handBuilt = scan.routes + .filter((r) => !exceptions.some((e) => isRouteException(r, e))) + .map((r) => `${where(r)} ${r.base} ${routeKey(r.method, r.path)}${r.via ? ` (via ${r.via})` : ''}: ${operationFor(r)}`); + const unknownSdkCalls = scan.sdkCalls - .filter((c) => !OPERATION_IDS.has(c.operationId)) - .map((c) => `${where(c)} ${c.call} -> ${c.operationId}`); + .filter((c) => !OPERATIONS_OF[c.service].has(c.operationId)) + .map((c) => `${where(c)} ${c.call} -> ${c.operationId}${OPERATION_IDS.has(c.operationId) ? ` (an operation of another service than ${c.service})` : ''}`); const unresolved = scan.unresolved .filter((u) => !exceptions.some((e) => e.kind === 'site' && e.file === u.file && e.owner === u.owner && e.target === u.target)) @@ -182,7 +236,7 @@ function violations(scan: ScanResult, exceptions: readonly Exception[]) { return n === e.count ? [] : [`${e.file} ${e.owner}(${e.target}) matches ${n} call sites, expected ${e.count}`]; }); - return { unknownRoutes, unknownSdkCalls, unresolved, stale }; + return { unknownRoutes, handBuilt, unknownSdkCalls, unresolved, stale }; } describe('web → API route contract (Smithy manifest)', () => { @@ -193,11 +247,15 @@ describe('web → API route contract (Smithy manifest)', () => { expect(v.unresolved).toEqual([]); }); + it('no request to a OneHook API is built by hand: every one goes through the onehook-api-client SDK', () => { + expect(v.handBuilt).toEqual([]); + }); + it('every literal route is a Smithy operation of its origin', () => { expect(v.unknownRoutes).toEqual([]); }); - it('every SDK command is a Smithy operation', () => { + it('every SDK command is a Smithy operation of the service its client serves', () => { expect(v.unknownSdkCalls).toEqual([]); }); @@ -211,27 +269,28 @@ describe('web → API route contract (Smithy manifest)', () => { }); it('sees every request layer it is meant to check', () => { - const routesFrom = new Set(scan.routes.map((r) => `${r.file}${r.via ? `#${r.via}` : ''}`)); + const layers = new Set(scan.sdkCalls.map((c) => `${c.service} ${c.file}`)); for (const layer of [ - 'src/api/rest.ts#request', - 'src/api/chat.ts#chatRest', - 'src/api/analytics.ts', - 'src/lib/mr-onehook.ts', - 'src/lib/mr-onehook.ts#authorizedFetch', - 'src/components/Chatbot/ChatbotWidget.tsx', + 'aws src/api/rest.ts', + 'aws src/api/chat.ts', + 'aws src/api/analytics.ts', + 'aws src/api/state.ts', + 'aws src/api/identity.ts', + 'aws src/api/profile.ts', + 'aws src/api/matching.ts', + 'aws src/api/liveness.ts', + 'mr-onehook src/lib/mr-onehook.ts', + 'mr-onehook src/components/Chatbot/ChatbotWidget.tsx', + 'moderation-evidence src/features/moderation/report/evidence-api.ts', ]) { - expect(routesFrom, layer).toContain(layer); - } - const sdkFiles = new Set(scan.sdkCalls.map((c) => c.file)); - for (const f of ['src/api/state.ts', 'src/api/identity.ts', 'src/api/profile.ts', 'src/api/matching.ts', 'src/api/liveness.ts']) { - expect(sdkFiles, f).toContain(f); + expect(layers, layer).toContain(layer); } }); - it('checks the portal moderation evidence calls against ModerationEvidenceService', () => { + it('calls the portal moderation evidence API only through ModerationEvidenceService', () => { expect(BASE_PATH['admin-portal']).toMatch(/^\/api\/p\/[^/]+\/[^/]+\/moderation$/); - const portal = scan.routes.filter((r) => r.base === 'admin-portal').map((r) => routeKey(r.method, r.path)); - expect([...new Set(portal)].sort()).toEqual(['POST /evidence/complete', 'POST /evidence/presign']); + const ops = scan.sdkCalls.filter((c) => c.service === 'moderation-evidence').map((c) => c.operationId); + expect([...new Set(ops)].sort()).toEqual(['CompleteEvidence', 'PresignEvidence']); expect([...MANIFEST['admin-portal']].sort()).toEqual(['POST /evidence/complete', 'POST /evidence/presign']); }); }); @@ -262,6 +321,74 @@ describe('the route scanner itself', () => { expect(v.unresolved).toEqual([]); }); + it('fails a hand-built request even when its route IS a Smithy operation, naming the SDK operation', () => { + const v = violations( + fake(`${header} + export const Fake = { + unblock: (id: string) => request('DELETE', \`/state/blocks/\${encodeURIComponent(id)}\`), + sessions: () => fetch(\`\${chatbotUrl}/api/member/product-connection-chat/sessions\`, { method: 'GET' }), + };`), + [] + ); + expect(v.unknownRoutes).toEqual([]); + expect(v.handBuilt).toEqual([ + 'src/api/fake.ts:8 api DELETE /state/blocks/{} (via request): use the SDK operation UnblockUser', + 'src/api/fake.ts:9 mr-onehook GET /api/member/product-connection-chat/sessions: use the SDK operation ListChatSessions', + ]); + }); + + it('fails an SDK call on the wrong client for its service', () => { + const v = violations( + scanSources([ + { + path: 'src/lib/fake.ts', + text: ` + import { mrOneHookClient } from '../api/external-sdk-clients'; + import { sdkClient } from '../api/sdk-client'; + export const a = () => mrOneHookClient.getState({}); + export const b = () => sdkClient.listChatSessions({}); + export const c = () => mrOneHookClient.listChatSessions({}); + `, + }, + ]), + [] + ); + expect(v.unknownSdkCalls).toEqual([ + 'src/lib/fake.ts:4 mrOneHookClient.getState -> GetState (an operation of another service than mr-onehook)', + 'src/lib/fake.ts:5 sdkClient.listChatSessions -> ListChatSessions (an operation of another service than aws)', + ]); + }); + + it('reports a generated client constructed outside its module', () => { + const scan = scanSources([ + { + path: 'src/lib/fake.ts', + text: ` + import { MrOneHookService } from 'onehook-mr-onehook-client'; + export const mine = new MrOneHookService({ endpoint: 'https://x' }); + `, + }, + ]); + expect(scan.unresolved.map((u) => u.reason)).toContain( + 'a second MrOneHookService SDK client outside src/api/external-sdk-clients.ts' + ); + }); + + it('reports a portal client built outside its module', () => { + const scan = scanSources([ + { + path: 'src/lib/fake.ts', + text: ` + import { createPortalClient } from 'saha-equation-admin-portal-client'; + export const mine = createPortalClient({ endpoint: 'https://x', tenant: { service: 'onehook', stage: 'gamma' } }); + `, + }, + ]); + expect(scan.unresolved.map((u) => u.reason)).toContain( + 'a second createPortalClient() SDK client outside src/api/external-sdk-clients.ts' + ); + }); + it('fails a portal moderation route that is not a ModerationEvidenceService operation', () => { const v = violations( fake(` diff --git a/src/tests/api-route-scan.ts b/src/tests/api-route-scan.ts index eaa2afc..82775c9 100644 --- a/src/tests/api-route-scan.ts +++ b/src/tests/api-route-scan.ts @@ -9,8 +9,12 @@ * alias (`const doFetch = t.fetchImpl ?? fetch`). Any other use of `fetch` as a value is reported * as unresolved, so an untracked alias can't hide a request. * - `xhr.open(method, url)` on a `const xhr = new XMLHttpRequest()`. - * - `sdkClient.(...)` / `(sdkClient as any).(...)` / `sdkClient.send(new Command(...))` - * on the generated `onehook-api-client` (api/sdk-client.ts), and any `Command` imported from it. + * - a call on one of the generated clients ({@link SDK_CLIENTS}), each from the package its API's owner + * publishes: `.(...)` / `( as any).(...)` / `.send(new Command(...))`, + * and any `Command` imported from that package. Each client is tied to the service it may call: + * `sdkClient` (`onehook-api-client`, OneHookBackend) the backend services, `mrOneHookClient` + * (`onehook-mr-onehook-client`, OneHookUXEnhancement) MrOneHookService, `evidenceClient` + * (`saha-equation-admin-portal-client`, OneHookAdminPortal) the portal's ModerationEvidenceService. * - `navigator.sendBeacon`, `new EventSource`, `new WebSocket`: always unresolved (none exist today). * * How a URL resolves. The expression is evaluated into parts: @@ -56,9 +60,13 @@ export interface ResolvedRoute { via?: string; } +/** Which generated client a call went through: the Smithy service family it may reach. */ +export type SdkService = 'aws' | 'mr-onehook' | 'moderation-evidence'; + export interface SdkCall { file: string; line: number; + service: SdkService; operationId: string; /** Source text of the call, for messages. */ call: string; @@ -105,9 +113,44 @@ const BASE_FUNCTIONS: Readonly +> = { + // `ctors` are constructors (`new X(...)`) or factories (`X(...)`) that build the client: only `file` + // may call them. + sdkClient: { + service: 'aws', + module: /(^|\/)sdk-client$/, + file: 'src/api/sdk-client.ts', + ctors: ['OneHook', 'OneHookClient'], + subpath: SDK_PACKAGE, + }, + mrOneHookClient: { + service: 'mr-onehook', + module: /(^|\/)external-sdk-clients$/, + file: 'src/api/external-sdk-clients.ts', + ctors: ['MrOneHookService', 'MrOneHookServiceClient'], + subpath: 'onehook-mr-onehook-client', + }, + /** A local `const evidenceClient = ...` built by `createModerationEvidenceClient` (evidence-api.ts). */ + evidenceClient: { + service: 'moderation-evidence', + module: /(^|\/)external-sdk-clients$/, + file: 'src/api/external-sdk-clients.ts', + ctors: ['createPortalClient', 'ModerationEvidenceService', 'ModerationEvidenceServiceClient', 'AdmissionsService', 'AdmissionsServiceClient'], + subpath: 'saha-equation-admin-portal-client', + }, +}; +const SDK_SUBPATH_SERVICE: Readonly> = { + ...Object.fromEntries(Object.values(SDK_CLIENTS).map((c) => [c.subpath, c.service])), + 'saha-equation-admin-portal-client/moderation-evidence': 'moderation-evidence', +}; const REACT_DEPS_HOOKS = new Set(['useCallback', 'useEffect', 'useMemo', 'useLayoutEffect']); // ── Reading the sources ───────────────────────────────────────────────────────────────────────── @@ -484,15 +527,27 @@ export function scanSources(inputs: SourceInput[]): ScanResult { }; findAliases(file.sf); - const sdkImported = file.sf.statements.some( - (s) => - ts.isImportDeclaration(s) && - ts.isStringLiteral(s.moduleSpecifier) && - SDK_CLIENT_MODULE.test(s.moduleSpecifier.text) && - importedName(s, 'sdkClient') - ); + /** Whether `name` may be used in this file: imported from its module, or a local `const` built there. */ + const clientAvailable = (name: string): boolean => { + const spec = SDK_CLIENTS[name]; + if (file.path === spec.file) return true; + return file.sf.statements.some((s) => { + if (!ts.isImportDeclaration(s) || !ts.isStringLiteral(s.moduleSpecifier) || !spec.module.test(s.moduleSpecifier.text)) return false; + // `evidenceClient` is a local const initialised from an import of the module (clientOf/createModerationEvidenceClient). + return name === 'evidenceClient' ? true : Boolean(importedName(s, name)); + }); + }; const visit = (n: ts.Node) => { + // A client factory (e.g. createPortalClient) called outside the module that owns the client. + if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) { + for (const spec of Object.values(SDK_CLIENTS)) { + if (spec.ctors.includes(n.expression.text) && /^[a-z]/.test(n.expression.text) && file.path !== spec.file) { + unresolved(n, n, `a second ${n.expression.text}() SDK client outside ${spec.file}`); + } + } + } + // fetch(...) and its aliases if (ts.isCallExpression(n)) { const callee = unwrap(n.expression); @@ -559,24 +614,29 @@ export function scanSources(inputs: SourceInput[]): ScanResult { } } else if (ctor === 'EventSource' || ctor === 'WebSocket') { unresolved(n, n, `new ${ctor}() is not resolved by this scanner`); - } else if ((ctor === 'OneHook' || ctor === 'OneHookClient') && file.path !== SDK_CLIENT_FILE) { - unresolved(n, n, `a second ${ctor} SDK client outside ${SDK_CLIENT_FILE}`); + } else { + for (const spec of Object.values(SDK_CLIENTS)) { + if (spec.ctors.includes(ctor) && file.path !== spec.file) { + unresolved(n, n, `a second ${ctor} SDK client outside ${spec.file}`); + } + } } } - // The generated SDK client - if (ts.isIdentifier(n) && n.text === 'sdkClient' && isValueReference(n)) { + // The generated SDK clients + if (ts.isIdentifier(n) && Object.hasOwn(SDK_CLIENTS, n.text) && isValueReference(n)) { sdkReference(n); } - // `Command` imported from the SDK package - if (ts.isImportDeclaration(n) && ts.isStringLiteral(n.moduleSpecifier) && n.moduleSpecifier.text === SDK_PACKAGE) { + // `Command` imported from the SDK package or one of its client subpaths + if (ts.isImportDeclaration(n) && ts.isStringLiteral(n.moduleSpecifier) && SDK_SUBPATH_SERVICE[n.moduleSpecifier.text]) { + const service = SDK_SUBPATH_SERVICE[n.moduleSpecifier.text]; const named = n.importClause?.namedBindings; if (named && ts.isNamedImports(named)) { for (const el of named.elements) { const imported = (el.propertyName ?? el.name).text; if (/^[A-Z]\w*Command$/.test(imported) && !el.isTypeOnly && !n.importClause?.isTypeOnly) { - result.sdkCalls.push({ file: file.path, line: lineOf(el), operationId: imported.slice(0, -'Command'.length), call: `import ${imported}` }); + result.sdkCalls.push({ file: file.path, line: lineOf(el), service, operationId: imported.slice(0, -'Command'.length), call: `import ${imported}` }); } } } @@ -585,6 +645,8 @@ export function scanSources(inputs: SourceInput[]): ScanResult { }; const sdkReference = (n: ts.Identifier) => { + const name = n.text; + const spec = SDK_CLIENTS[name]; let expr: ts.Node = n; while ( (ts.isParenthesizedExpression(expr.parent) || ts.isAsExpression(expr.parent) || ts.isNonNullExpression(expr.parent) || ts.isTypeAssertionExpression(expr.parent)) && @@ -593,35 +655,38 @@ export function scanSources(inputs: SourceInput[]): ScanResult { expr = expr.parent; } const access = expr.parent; - if (file.path === SDK_CLIENT_FILE) { - // The declaration and the middleware setup in sdk-client.ts itself. + if (file.path === spec.file) { + // The declaration and the middleware setup in the declaring file itself. if (ts.isPropertyAccessExpression(access) && access.expression === expr && access.name.text === 'middlewareStack') return; - } else if (!sdkImported) { - unresolved(n, n, 'sdkClient is not imported from api/sdk-client'); + // stripSdkHeaders(mrOneHookClient as ...) in external-sdk-clients.ts. + if (ts.isCallExpression(access) && ts.isIdentifier(access.expression) && access.expression.text === 'stripSdkHeaders') return; + } else if (!clientAvailable(name)) { + unresolved(n, n, `${name} is not imported from its module`); return; } if (!ts.isPropertyAccessExpression(access) || access.expression !== expr) { - unresolved(n, n, 'sdkClient is used as a value; its calls cannot be traced'); + unresolved(n, n, `${name} is used as a value; its calls cannot be traced`); return; } const call = access.parent; if (!ts.isCallExpression(call) || call.expression !== access) { - unresolved(n, access, `sdkClient.${access.name.text} is not called directly`); + unresolved(n, access, `${name}.${access.name.text} is not called directly`); return; } const op = access.name.text; if (op === 'send') { const arg = call.arguments[0] && unwrap(call.arguments[0]); if (arg && ts.isNewExpression(arg) && ts.isIdentifier(arg.expression) && /Command$/.test(arg.expression.text)) { - result.sdkCalls.push({ file: file.path, line: lineOf(call), operationId: arg.expression.text.slice(0, -'Command'.length), call: call.getText(file.sf) }); + result.sdkCalls.push({ file: file.path, line: lineOf(call), service: spec.service, operationId: arg.expression.text.slice(0, -'Command'.length), call: call.getText(file.sf) }); } else { - unresolved(n, call, 'sdkClient.send() without a `new Command(...)` argument'); + unresolved(n, call, `${name}.send() without a \`new Command(...)\` argument`); } return; } result.sdkCalls.push({ file: file.path, line: lineOf(call), + service: spec.service, operationId: op.charAt(0).toUpperCase() + op.slice(1), call: access.getText(file.sf), }); diff --git a/src/tests/chat-location-contact.test.ts b/src/tests/chat-location-contact.test.ts index 31dd941..d699e33 100644 --- a/src/tests/chat-location-contact.test.ts +++ b/src/tests/chat-location-contact.test.ts @@ -465,10 +465,10 @@ describe('location and contact telemetry on web (catalog 1.23.0)', () => { } }); - it('leaves the send-side events as web gaps (web does not send yet)', () => { + it('emits the send-side events now that web sends locations (catalog 1.24.0)', () => { for (const name of ['CHAT_LOCATION_SHARE', 'CHAT_LIVE_LOCATION_DURATION', 'CHAT_LIVE_LOCATION_STOP'] as const) { - expect(webScope.has(UiElement[name])).toBe(false); - expect(referenced.has(name)).toBe(false); + expect(webScope.has(UiElement[name])).toBe(true); + expect(referenced.has(name)).toBe(true); } }); }); diff --git a/src/tests/chat-settings-notifications.test.tsx b/src/tests/chat-settings-notifications.test.tsx index 5fc7121..aa3945a 100644 --- a/src/tests/chat-settings-notifications.test.tsx +++ b/src/tests/chat-settings-notifications.test.tsx @@ -11,7 +11,7 @@ const sdk = vi.hoisted(() => ({ getChatSettings: vi.fn(), updateChatSettings: vi.fn(), })); -vi.mock('../api/sdk-client', () => ({ sdkClient: sdk })); +vi.mock('../api/sdk-client', () => ({ sdkClient: sdk, callSdk: (call: () => Promise) => call() })); import { ChatSettingsApi, type ChatSettings } from '../api/rest'; import { diff --git a/src/tests/contact-share.test.ts b/src/tests/contact-share.test.ts new file mode 100644 index 0000000..c0e8dca --- /dev/null +++ b/src/tests/contact-share.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, it, vi } from 'vitest'; +import { MAX_CONTACT_THUMBNAIL_BASE64, decodeStructuredFrame, frameStructuredContent } from '../lib/chat-structured'; +import { + EMPTY_CONTACT_FORM, + MAX_CONTACT_FIELDS, + buildSelectedContactPayload, + contactPickerProperties, + contactsManager, + draftFromForm, + draftFromPicked, + fitThumbnail, + isPlausibleEmail, + isPlausiblePhone, + normalizeRows, + pickContact, + selectAll, + validateContactForm, + type ContactDraft, + type ContactsManagerLike, +} from '../lib/contact-share'; + +/** + * Sending a contact card from the web (lib/contact-share.ts): the manual form's validation and rows, + * the Contact Picker answer, choosing which phones and emails go out, and the 24-KB thumbnail cap. + */ + +const DRAFT: ContactDraft = { + displayName: 'Asha Rao', + organization: 'Acme', + phones: [{ label: 'mobile', value: '+91 98450 12345' }, { value: '080 2222 3333' }], + emails: [{ label: 'home', value: 'asha@example.com' }, { value: 'asha@work.example' }], +}; + +describe('the manual form', () => { + it('requires a name and ignores empty rows', () => { + const empty = validateContactForm(EMPTY_CONTACT_FORM); + expect(empty.valid).toBe(false); + expect(empty.errors.name).toBe('Enter a name'); + expect(empty.errors.phones).toEqual([undefined]); + + const named = validateContactForm({ ...EMPTY_CONTACT_FORM, name: ' Asha ' }); + expect(named.valid).toBe(true); + }); + + it('flags an implausible phone or email on its own row', () => { + const result = validateContactForm({ + name: 'Asha', + organization: '', + phones: ['+91 98450 12345', 'call me', ''], + emails: ['asha@example', 'asha@example.com', ''], + }); + expect(result.valid).toBe(false); + expect(result.errors.phones).toEqual([undefined, 'Enter a valid phone number', undefined]); + expect(result.errors.emails).toEqual(['Enter a valid email address', undefined, undefined]); + }); + + it('accepts the usual phone formats and rejects too few or too many digits', () => { + expect(isPlausiblePhone('+1 (415) 555-0100')).toBe(true); + expect(isPlausiblePhone('080.2222.3333')).toBe(true); + expect(isPlausiblePhone('12')).toBe(false); + expect(isPlausiblePhone('1'.repeat(18))).toBe(false); + expect(isPlausiblePhone('555-CALL')).toBe(false); + expect(isPlausibleEmail('a@b.co')).toBe(true); + expect(isPlausibleEmail('a b@c.co')).toBe(false); + }); + + it('rejects a name over the display cap', () => { + expect(validateContactForm({ ...EMPTY_CONTACT_FORM, name: 'x'.repeat(257) }).errors.name).toBe('That name is too long'); + }); + + it('keeps exactly one empty row to type into, drops empty rows in the middle, caps the list', () => { + expect(normalizeRows([''])).toEqual(['']); + expect(normalizeRows(['123'])).toEqual(['123', '']); + expect(normalizeRows(['123', '', '456', ''])).toEqual(['123', '456', '']); + expect(normalizeRows([' '])).toEqual([' ', '']); + const full = Array.from({ length: MAX_CONTACT_FIELDS + 3 }, (_, i) => `${i}00`); + expect(normalizeRows(full)).toHaveLength(MAX_CONTACT_FIELDS); + }); + + it('turns a valid form into a draft with trimmed values and no empty entries', () => { + const draft = draftFromForm({ + name: ' Asha Rao ', + organization: ' ', + phones: [' +91 98450 12345 ', ''], + emails: ['', 'asha@example.com'], + }); + expect(draft).toEqual({ + displayName: 'Asha Rao', + phones: [{ value: '+91 98450 12345' }], + emails: [{ value: 'asha@example.com' }], + }); + }); +}); + +describe('choosing what to share', () => { + it('includes everything by default', () => { + const payload = buildSelectedContactPayload(DRAFT, selectAll(DRAFT)); + expect(payload).toEqual({ + v: 1, + type: 'contact', + displayName: 'Asha Rao', + organization: 'Acme', + phones: DRAFT.phones, + emails: DRAFT.emails, + }); + }); + + it('sends only the ticked phones and emails', () => { + const payload = buildSelectedContactPayload(DRAFT, { phones: [false, true], emails: [true, false] }); + expect(payload.phones).toEqual([{ value: '080 2222 3333' }]); + expect(payload.emails).toEqual([{ label: 'home', value: 'asha@example.com' }]); + }); + + it('can send a name with no phone or email at all', () => { + const payload = buildSelectedContactPayload(DRAFT, { phones: [false, false], emails: [false, false] }); + expect(payload).toMatchObject({ displayName: 'Asha Rao', phones: [], emails: [] }); + }); + + it('round-trips through the 0x03 frame to the card the receiver renders', () => { + const framed = frameStructuredContent(buildSelectedContactPayload(DRAFT, selectAll(DRAFT))); + expect(framed.charCodeAt(0)).toBe(0x03); + expect(decodeStructuredFrame(framed)).toMatchObject({ type: 'contact', displayName: 'Asha Rao', organization: 'Acme' }); + }); + + it('drops a thumbnail over 24 KB instead of sending it', () => { + const big = { ...DRAFT, thumbnailBase64: 'A'.repeat(MAX_CONTACT_THUMBNAIL_BASE64 + 4) }; + expect(buildSelectedContactPayload(big, selectAll(big)).thumbnailBase64).toBeUndefined(); + const ok = { ...DRAFT, thumbnailBase64: 'QUJD' }; + expect(buildSelectedContactPayload(ok, selectAll(ok)).thumbnailBase64).toBe('QUJD'); + }); +}); + +describe('the Contact Picker API', () => { + it('is used only where navigator.contacts.select exists', () => { + expect(contactsManager({})).toBeNull(); + expect(contactsManager({ contacts: {} })).toBeNull(); + const manager = { select: async () => [] }; + expect(contactsManager({ contacts: manager })).toBe(manager); + }); + + it('asks for the photo only where the browser supports it', () => { + expect(contactPickerProperties(null)).toEqual(['name', 'tel', 'email']); + expect(contactPickerProperties(['name', 'email', 'tel', 'icon'])).toEqual(['name', 'tel', 'email', 'icon']); + }); + + it('turns a picked contact into a draft without duplicates', () => { + expect( + draftFromPicked({ name: [' Asha Rao '], tel: ['+91 98450 12345', '+9198450 12345', ''], email: ['A@x.co', 'a@x.co'] }) + ).toEqual({ displayName: 'Asha Rao', phones: [{ value: '+91 98450 12345' }], emails: [{ value: 'A@x.co' }] }); + expect(draftFromPicked({ tel: ['123 456'] })?.displayName).toBe('123 456'); + expect(draftFromPicked({})).toBeNull(); + expect(draftFromPicked(undefined)).toBeNull(); + }); + + it('reports a cancelled picker, a refused picker, and a picked contact', async () => { + const cancelled: ContactsManagerLike = { select: async () => [] }; + expect(await pickContact(cancelled, ['name'])).toEqual({ kind: 'cancelled' }); + const refused: ContactsManagerLike = { + select: async () => { + throw new Error('NotAllowedError'); + }, + }; + expect(await pickContact(refused, ['name'])).toEqual({ kind: 'failed' }); + const picker: ContactsManagerLike = { select: vi.fn(async () => [{ name: ['Asha'], tel: ['12345'] }]) }; + expect(await pickContact(picker, ['name', 'tel', 'email'])).toEqual({ + kind: 'picked', + draft: { displayName: 'Asha', phones: [{ value: '12345' }], emails: [] }, + }); + expect(picker.select).toHaveBeenCalledWith(['name', 'tel', 'email'], { multiple: false }); + }); + + it('attaches the photo when it can be shrunk under the cap', async () => { + const icon = new Blob(['x']); + const picker: ContactsManagerLike = { select: async () => [{ name: ['Asha'], icon: [icon] }] }; + const encode = vi.fn(async (_blob: Blob, size: number) => (size <= 96 ? 'QUJD' : 'A'.repeat(MAX_CONTACT_THUMBNAIL_BASE64 + 1))); + const result = await pickContact(picker, ['name', 'icon'], encode); + expect(result).toMatchObject({ kind: 'picked', draft: { thumbnailBase64: 'QUJD' } }); + expect(encode.mock.calls[0][0]).toBe(icon); + }); +}); + +describe('fitThumbnail', () => { + it('returns the first size that fits 24 KB, largest first', async () => { + const sizes: number[] = []; + const out = await fitThumbnail(async (size) => { + sizes.push(size); + return size === 128 ? 'B'.repeat(1000) : 'A'.repeat(MAX_CONTACT_THUMBNAIL_BASE64 + 1); + }); + expect(out).toBe('B'.repeat(1000)); + expect(sizes).toEqual([160, 128]); + }); + + it('gives up (no photo) when nothing fits or encoding fails', async () => { + expect(await fitThumbnail(async () => 'A'.repeat(MAX_CONTACT_THUMBNAIL_BASE64 + 1))).toBeUndefined(); + expect( + await fitThumbnail(async () => { + throw new Error('no canvas'); + }) + ).toBeUndefined(); + expect(await fitThumbnail(async () => null)).toBeUndefined(); + }); +}); diff --git a/src/tests/dev-proxy.test.ts b/src/tests/dev-proxy.test.ts new file mode 100644 index 0000000..b800c4a --- /dev/null +++ b/src/tests/dev-proxy.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest'; +import { API_OPERATIONS } from '../lib/analytics/generated/apiManifest'; +import { devApiProxy, DEV_API_TARGET, isProxied } from '../config/dev-proxy'; + +/** + * On localhost the SDK calls the dev-server origin, so a REST prefix missing from the Vite proxy + * silently breaks that feature in local development (as `/signals` once did). Every operation a + * member's browser can call (Cognito or public auth) on the REST ingress must be proxied. + */ +describe('local dev proxy', () => { + // The backend's manifest lists only REST-ingress services (Mr OneHook and the portal have their own). + const browserCallable = API_OPERATIONS.filter((op) => op.auth === 'cognito' || op.auth === 'none'); + + it('covers every Cognito and public route of the REST ingress', () => { + const missing = browserCallable + .filter((op) => !isProxied(op.path)) + .map((op) => `${op.method} ${op.path} (${op.operationId})`); + expect(missing).toEqual([]); + }); + + it('forwards analytics ingest and photo stats', () => { + expect(isProxied('/signals')).toBe(true); + expect(isProxied('/signals/media-stats')).toBe(true); + }); + + it('sends every prefix to the Gamma ingress', () => { + for (const entry of Object.values(devApiProxy())) { + expect(entry).toEqual({ target: DEV_API_TARGET, changeOrigin: true, secure: true }); + } + }); +}); diff --git a/src/tests/live-location-api.test.ts b/src/tests/live-location-api.test.ts new file mode 100644 index 0000000..897ee52 --- /dev/null +++ b/src/tests/live-location-api.test.ts @@ -0,0 +1,119 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * The sharer's GraphQL calls (api/live-location.ts): every selection carries the seven + * LiveLocationUpdate fields (subscribers only get what the mutation selected), errors keep their + * errorType, and the best-effort stop sent from `pagehide` as a keepalive fetch. + */ + +const mocks = vi.hoisted(() => ({ + graphql: vi.fn(), + fetchAuthSession: vi.fn(), +})); + +vi.mock('../api/chat', () => ({ appSyncClient: () => ({ graphql: mocks.graphql }) })); +vi.mock('aws-amplify', () => ({ + Amplify: { getConfig: () => ({ API: { GraphQL: { endpoint: 'https://chat.example.test/graphql' } } }) }, +})); +vi.mock('aws-amplify/auth', () => ({ fetchAuthSession: mocks.fetchAuthSession })); + +import { GraphQLOperationError } from '../api/graphql-error'; +import { LiveLocationApi, PUBLISH_LIVE_LOCATION, STOP_LIVE_LOCATION } from '../api/live-location'; + +const MATCH = 'match-1'; +const SESSION = '3f6d2c1e-8a4b-4c3d-9e2f-1a2b3c4d5e6f'; +const NOW = 1_794_700_000_000; +const ROW = { matchId: MATCH, userId: 'me', sessionId: SESSION, ciphertext: 'c', at: NOW, expiresAt: NOW + 60_000, ended: false }; + +function session(expSeconds: number) { + return { tokens: { accessToken: { toString: () => 'jwt-access', payload: { exp: expSeconds } } } }; +} + +const fetchMock = vi.fn(() => Promise.resolve({ ok: true })); + +beforeEach(() => { + mocks.graphql.mockReset(); + mocks.fetchAuthSession.mockReset(); + fetchMock.mockClear(); + vi.stubGlobal('fetch', fetchMock); + LiveLocationApi.clearUnloadAuth(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('selection sets', () => { + it.each([ + ['publishLiveLocation', PUBLISH_LIVE_LOCATION], + ['stopLiveLocation', STOP_LIVE_LOCATION], + ])('%s selects all seven LiveLocationUpdate fields', (_name, query) => { + for (const field of ['matchId', 'userId', 'sessionId', 'ciphertext', 'at', 'expiresAt', 'ended']) { + expect(query).toMatch(new RegExp(`\\b${field}\\b`)); + } + }); +}); + +describe('publish and stop', () => { + it('publishes the sealed update with the share expiry, returns the row, and refreshes the unload token', async () => { + mocks.graphql.mockResolvedValue({ data: { publishLiveLocation: ROW } }); + // Rejecting keeps this test's token refresh from leaking a token copy into the next tests. + mocks.fetchAuthSession.mockRejectedValue(new Error('not needed here')); + await expect(LiveLocationApi.publishLiveLocation(MATCH, SESSION, 'sealed', NOW + 60_000)).resolves.toEqual(ROW); + expect(mocks.graphql).toHaveBeenCalledWith({ + query: PUBLISH_LIVE_LOCATION, + variables: { matchId: MATCH, sessionId: SESSION, ciphertext: 'sealed', expiresAt: NOW + 60_000 }, + }); + await vi.waitFor(() => expect(mocks.fetchAuthSession).toHaveBeenCalled()); + }); + + it('keeps the server errorType (the sharer acts on it)', async () => { + mocks.graphql.mockRejectedValue({ data: null, errors: [{ message: 'too soon', errorType: 'Throttled' }] }); + const err = await LiveLocationApi.publishLiveLocation(MATCH, SESSION, 'sealed', NOW).catch((e: unknown) => e); + expect(err).toBeInstanceOf(GraphQLOperationError); + expect((err as GraphQLOperationError).errorType).toBe('Throttled'); + }); + + it('stops one share', async () => { + mocks.graphql.mockResolvedValue({ data: { stopLiveLocation: { ...ROW, ciphertext: null, ended: true } } }); + await expect(LiveLocationApi.stopLiveLocation(MATCH, SESSION)).resolves.toMatchObject({ ended: true }); + expect(mocks.graphql).toHaveBeenCalledWith({ query: STOP_LIVE_LOCATION, variables: { matchId: MATCH, sessionId: SESSION } }); + }); +}); + +describe('the stop sent while the tab closes', () => { + it('is not attempted before a token copy exists', () => { + expect(LiveLocationApi.stopOnUnload(MATCH, SESSION, NOW)).toBe(false); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('posts stopLiveLocation as a keepalive fetch with the access token', async () => { + mocks.fetchAuthSession.mockResolvedValue(session(NOW / 1000 + 3600)); + await LiveLocationApi.primeUnloadAuth(); + expect(LiveLocationApi.stopOnUnload(MATCH, SESSION, NOW)).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; + expect(url).toBe('https://chat.example.test/graphql'); + expect(init).toMatchObject({ method: 'POST', keepalive: true }); + expect(init.headers).toMatchObject({ Authorization: 'jwt-access', 'Content-Type': 'application/json' }); + expect(JSON.parse(init.body as string)).toEqual({ query: STOP_LIVE_LOCATION, variables: { matchId: MATCH, sessionId: SESSION } }); + }); + + it('is not attempted with a token about to expire, or after sign-out cleared it', async () => { + mocks.fetchAuthSession.mockResolvedValue(session(NOW / 1000 + 5)); + await LiveLocationApi.primeUnloadAuth(); + expect(LiveLocationApi.stopOnUnload(MATCH, SESSION, NOW)).toBe(false); + + mocks.fetchAuthSession.mockResolvedValue(session(NOW / 1000 + 3600)); + await LiveLocationApi.primeUnloadAuth(); + LiveLocationApi.clearUnloadAuth(); + expect(LiveLocationApi.stopOnUnload(MATCH, SESSION, NOW)).toBe(false); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('never throws when the session cannot be read', async () => { + mocks.fetchAuthSession.mockRejectedValue(new Error('signed out')); + await expect(LiveLocationApi.primeUnloadAuth()).resolves.toBeUndefined(); + expect(LiveLocationApi.stopOnUnload(MATCH, SESSION, NOW)).toBe(false); + }); +}); diff --git a/src/tests/live-location-sharing.test.ts b/src/tests/live-location-sharing.test.ts new file mode 100644 index 0000000..3a4e39a --- /dev/null +++ b/src/tests/live-location-sharing.test.ts @@ -0,0 +1,552 @@ +import { describe, expect, it, vi } from 'vitest'; +import { GraphQLOperationError } from '../api/graphql-error'; +import { parseLiveLocationUpdate, type LocationFix } from '../lib/chat-structured'; +import { MAX_LIVE_SHARE_MS, liveSessionKey, mergeLiveSession, type LiveSessions } from '../lib/live-location'; +import { + DISTANCE_FILTER_M, + LIVE_DURATIONS, + LiveLocationSharing, + MAX_LIVE_CIPHERTEXT_CHARS, + MAX_RETRIES_PER_FIX, + MIN_PUBLISH_INTERVAL_MS, + STATIONARY_AFTER_MS, + TAB_BOUND_COPY, + UNLOAD_AUTH_REFRESH_MS, + endNotice, + isSignificantMove, + makeLiveWindow, + newLiveSessionId, + publishOutcomeFromError, + withLocalEnds, + type BeginShareInput, + type EndedShare, + type LocationWatchOptions, +} from '../lib/live-location-sharing'; + +/** + * The web sharer's engine (lib/live-location-sharing.ts) against fake transport, location, clock and + * page: the 5-s throttle, coalescing, the 25-m filter, the contract's error table, expiry, Stop, the + * end events (another device, State, sign-out) and the best-effort stop when the tab closes. + */ + +const T0 = 1_794_700_000_000; +const MATCH = 'match-1'; +const ME = 'me-id'; +const SESSION = '3f6d2c1e-8a4b-4c3d-9e2f-1a2b3c4d5e6f'; +const SESSION_2 = 'aaaaaaaa-1111-2222-3333-444444444444'; +const METRES_PER_DEG_LAT = 111_195; + +const BASE: LocationFix = { lat: 12.9716, lon: 77.5946, accuracyM: 5, at: T0 }; + +/** `fix` moved `metres` north. */ +function north(fix: LocationFix, metres: number, extra: Partial = {}): LocationFix { + return { ...fix, lat: fix.lat + metres / METRES_PER_DEG_LAT, ...extra }; +} + +interface Watch { + onFix: (fix: LocationFix) => void; + onDenied: () => void; + options: LocationWatchOptions; + stopped: boolean; +} + +function harness() { + let now = T0; + let publishImpl: () => Promise = async () => ({}); + let unloadAttempted = true; + const published: { matchId: string; sessionId: string; ciphertext: string; expiresAt: number }[] = []; + const subscriptions = new Map void>(); + const watches: Watch[] = []; + const pageHide = new Set<() => void>(); + const intervals = new Set(); + const transport = { + publish: vi.fn(async (matchId: string, sessionId: string, ciphertext: string, expiresAt: number) => { + published.push({ matchId, sessionId, ciphertext, expiresAt }); + return publishImpl(); + }), + stop: vi.fn(async () => ({})), + stopOnUnload: vi.fn(() => unloadAttempted), + subscribe: vi.fn((matchId: string, onRow: (row: { matchId: string; userId: string; sessionId: string; ended: boolean }) => void) => { + subscriptions.set(matchId, onRow); + return () => { + subscriptions.delete(matchId); + }; + }), + primeUnloadAuth: vi.fn(async () => undefined), + clearUnloadAuth: vi.fn(), + }; + const engine = new LiveLocationSharing({ + transport, + location: { + watch(onFix, onDenied, options) { + const watch: Watch = { onFix, onDenied, options, stopped: false }; + watches.push(watch); + return () => { + watch.stopped = true; + }; + }, + }, + clock: { + now: () => now, + setInterval: () => { + const handle = {}; + intervals.add(handle); + return handle; + }, + clearInterval: (handle) => { + intervals.delete(handle); + }, + }, + page: { + onPageHide(fn) { + pageHide.add(fn); + return () => { + pageHide.delete(fn); + }; + }, + }, + }); + const ends: EndedShare[] = []; + engine.onEnd((end) => ends.push(end)); + + const seal = vi.fn(async (plaintext: string) => `sealed:${plaintext}`); + const input = (overrides: Partial = {}): BeginShareInput => ({ + matchId: MATCH, + sessionId: SESSION, + startedAt: now, + expiresAt: now + 15 * 60_000, + userId: ME, + peerName: 'Riya', + seal, + ...overrides, + }); + + return { + engine, + transport, + published, + subscriptions, + watches, + pageHide, + intervals, + ends, + seal, + input, + advance: (ms: number) => { + now += ms; + }, + now: () => now, + setPublish: (fn: () => Promise) => { + publishImpl = fn; + }, + setUnloadAttempted: (value: boolean) => { + unloadAttempted = value; + }, + /** The live_location_update inside a published ciphertext. */ + update: (index: number) => { + const entry = published[index]; + const plaintext = entry.ciphertext.replace(/^sealed:/, ''); + return parseLiveLocationUpdate(plaintext, entry.sessionId); + }, + activeWatch: () => watches.filter((w) => !w.stopped), + }; +} + +const graphqlError = (errorType: string) => new GraphQLOperationError('refused', errorType); + +describe('starting a share', () => { + it('publishes the first position at once, sealed for the conversation, with the share expiry', async () => { + const h = harness(); + const start = h.input(); + await h.engine.begin(start, BASE); + expect(h.published).toHaveLength(1); + expect(h.published[0]).toMatchObject({ matchId: MATCH, sessionId: SESSION, expiresAt: start.expiresAt }); + expect(h.update(0)).toMatchObject({ type: 'live_location_update', sessionId: SESSION, lat: 12.9716, lon: 77.5946, accuracyM: 5, at: T0 }); + expect(h.seal).toHaveBeenCalledTimes(1); + expect(h.engine.share(MATCH)).toMatchObject({ sessionId: SESSION, peerName: 'Riya', latest: BASE }); + expect(h.engine.isRunning(SESSION)).toBe(true); + }); + + it('starts the position watch at high accuracy, the tick, the pagehide hook and the end subscription', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + expect(h.activeWatch()).toHaveLength(1); + expect(h.activeWatch()[0].options.highAccuracy).toBe(true); + expect(h.intervals.size).toBe(1); + expect(h.pageHide.size).toBe(1); + expect(h.subscriptions.has(MATCH)).toBe(true); + expect(h.transport.primeUnloadAuth).toHaveBeenCalled(); + }); + + it('never runs past the backend 8-hour ceiling and ignores a share that already expired', async () => { + const h = harness(); + await h.engine.begin(h.input({ expiresAt: h.now() + MAX_LIVE_SHARE_MS + 60_000 }), BASE); + expect(h.engine.share(MATCH)?.expiresAt).toBe(T0 + MAX_LIVE_SHARE_MS); + + const late = harness(); + await late.engine.begin(late.input({ expiresAt: late.now() - 1 }), BASE); + expect(late.published).toHaveLength(0); + expect(late.engine.share(MATCH)).toBeUndefined(); + }); + + it('stops the previous share in the same conversation before running a new one', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + h.advance(10_000); + await h.engine.begin(h.input({ sessionId: SESSION_2 }), BASE); + expect(h.transport.stop).toHaveBeenCalledWith(MATCH, SESSION); + expect(h.ends.map((e) => [e.sessionId, e.reason])).toEqual([[SESSION, 'stopped']]); + expect(h.engine.share(MATCH)?.sessionId).toBe(SESSION_2); + expect(h.published.map((p) => p.sessionId)).toEqual([SESSION, SESSION_2]); + }); +}); + +describe('throttle, coalescing and the distance filter', () => { + it('holds a move inside the 5-s window and sends it when the window opens', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + h.advance(2_000); + await h.engine.handleFix(north(BASE, 40, { at: h.now() })); + expect(h.published).toHaveLength(1); + h.advance(2_000); + await h.engine.tick(); + expect(h.published).toHaveLength(1); + h.advance(MIN_PUBLISH_INTERVAL_MS - 4_000); + await h.engine.tick(); + expect(h.published).toHaveLength(2); + }); + + it('coalesces: of several moves inside one window only the newest goes out', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + const a = north(BASE, 40, { at: T0 + 1_000 }); + const b = north(BASE, 80, { at: T0 + 2_000 }); + const c = north(BASE, 120, { at: T0 + 3_000 }); + for (const fix of [a, b, c]) { + h.advance(1_000); + await h.engine.handleFix(fix); + } + h.advance(MIN_PUBLISH_INTERVAL_MS); + await h.engine.tick(); + await h.engine.tick(); + expect(h.published).toHaveLength(2); + expect(h.update(1)?.lat).toBeCloseTo(c.lat, 5); + expect(h.update(1)?.at).toBe(c.at); + }); + + it('sends a move straight away once 5 s have passed since the last publish', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + h.advance(MIN_PUBLISH_INTERVAL_MS); + await h.engine.handleFix(north(BASE, 30, { at: h.now() })); + expect(h.published).toHaveLength(2); + }); + + it('ignores movement under 25 m, and jitter inside the accuracy radius', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + h.advance(MIN_PUBLISH_INTERVAL_MS); + await h.engine.handleFix(north(BASE, DISTANCE_FILTER_M - 5)); + await h.engine.handleFix(north(BASE, 40, { accuracyM: 60 })); + await h.engine.tick(); + expect(h.published).toHaveLength(1); + }); + + it('measures from the last position that counted, so slow drift still adds up', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + h.advance(MIN_PUBLISH_INTERVAL_MS); + await h.engine.handleFix(north(BASE, 15)); + await h.engine.handleFix(north(BASE, 30)); + expect(h.published).toHaveLength(2); + }); + + it('a fix arriving while a publish is in flight goes out after the window, not in parallel', async () => { + const h = harness(); + let release: () => void = () => undefined; + h.setPublish(() => new Promise((resolve) => (release = () => resolve({})))); + const first = h.engine.begin(h.input(), BASE); + await vi.waitFor(() => expect(h.transport.publish).toHaveBeenCalledTimes(1)); + h.advance(MIN_PUBLISH_INTERVAL_MS + 1); + await h.engine.handleFix(north(BASE, 50, { at: h.now() })); + expect(h.transport.publish).toHaveBeenCalledTimes(1); + h.setPublish(async () => ({})); + release(); + await first; + await h.engine.tick(); + expect(h.transport.publish).toHaveBeenCalledTimes(2); + }); + + it('switches to low accuracy after standing still, and back to high on the next move', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + h.advance(STATIONARY_AFTER_MS); + await h.engine.tick(); + expect(h.activeWatch()).toHaveLength(1); + expect(h.activeWatch()[0].options.highAccuracy).toBe(false); + expect(h.engine.getSnapshot().lowPower).toBe(true); + await h.engine.handleFix(north(BASE, 100, { at: h.now() })); + expect(h.activeWatch()).toHaveLength(1); + expect(h.activeWatch()[0].options.highAccuracy).toBe(true); + expect(h.engine.getSnapshot().lowPower).toBe(false); + }); + + it('refreshes the token copy for the unload stop while standing still', async () => { + const h = harness(); + await h.engine.begin(h.input({ expiresAt: h.now() + 60 * 60_000 }), BASE); + const before = h.transport.primeUnloadAuth.mock.calls.length; + h.advance(UNLOAD_AUTH_REFRESH_MS); + await h.engine.tick(); + expect(h.transport.primeUnloadAuth.mock.calls.length).toBe(before + 1); + await h.engine.tick(); + expect(h.transport.primeUnloadAuth.mock.calls.length).toBe(before + 1); + }); +}); + +describe('the contract error table', () => { + it('maps every errorType to what the sharer does', () => { + expect(publishOutcomeFromError(graphqlError('Throttled'))).toEqual({ kind: 'throttled' }); + expect(publishOutcomeFromError(graphqlError('LIVE_LOCATION_ENDED'))).toEqual({ kind: 'ended', reason: 'ended_elsewhere' }); + expect(publishOutcomeFromError(graphqlError('CONVERSATION_SUSPENDED'))).toEqual({ kind: 'ended', reason: 'suspended' }); + expect(publishOutcomeFromError(graphqlError('Unauthorized'))).toEqual({ kind: 'ended', reason: 'released' }); + expect(publishOutcomeFromError(graphqlError('BadRequest'))).toEqual({ kind: 'ended', reason: 'rejected' }); + expect(publishOutcomeFromError(new Error('network down'))).toEqual({ kind: 'failed' }); + }); + + it('Throttled drops that update (no retry); the next move goes out', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + h.setPublish(async () => { + throw graphqlError('Throttled'); + }); + h.advance(MIN_PUBLISH_INTERVAL_MS); + await h.engine.handleFix(north(BASE, 40, { at: h.now() })); + expect(h.published).toHaveLength(2); + h.setPublish(async () => ({})); + h.advance(MIN_PUBLISH_INTERVAL_MS); + await h.engine.tick(); + expect(h.published).toHaveLength(2); + await h.engine.handleFix(north(BASE, 90, { at: h.now() })); + expect(h.published).toHaveLength(3); + expect(h.engine.share(MATCH)).toBeDefined(); + }); + + it('a transport failure retries the same position a few times, one per window', async () => { + const h = harness(); + h.setPublish(async () => { + throw new Error('offline'); + }); + await h.engine.begin(h.input({ expiresAt: h.now() + 60 * 60_000 }), BASE); + for (let i = 0; i < MAX_RETRIES_PER_FIX + 2; i += 1) { + h.advance(MIN_PUBLISH_INTERVAL_MS); + await h.engine.tick(); + } + expect(h.published).toHaveLength(1 + MAX_RETRIES_PER_FIX); + expect(h.engine.share(MATCH)).toBeDefined(); + }); + + it.each([ + ['LIVE_LOCATION_ENDED', 'ended_elsewhere'], + ['CONVERSATION_SUSPENDED', 'suspended'], + ['Unauthorized', 'released'], + ['BadRequest', 'rejected'], + ])('%s ends the share (%s) and stops watching', async (errorType, reason) => { + const h = harness(); + h.setPublish(async () => { + throw graphqlError(errorType); + }); + await h.engine.begin(h.input(), BASE); + expect(h.ends).toEqual([{ matchId: MATCH, sessionId: SESSION, expiresAt: expect.any(Number), reason }]); + expect(h.engine.share(MATCH)).toBeUndefined(); + expect(h.activeWatch()).toHaveLength(0); + expect(h.intervals.size).toBe(0); + expect(h.pageHide.size).toBe(0); + expect(h.subscriptions.has(MATCH)).toBe(false); + // The server already ended it: no stop call. + expect(h.transport.stop).not.toHaveBeenCalled(); + }); + + it('a sealed update over 16 KB is never sent', async () => { + const h = harness(); + const seal = vi.fn(async () => 'x'.repeat(MAX_LIVE_CIPHERTEXT_CHARS + 1)); + await h.engine.begin(h.input({ seal }), BASE); + expect(h.transport.publish).not.toHaveBeenCalled(); + expect(h.ends[0]?.reason).toBe('rejected'); + }); +}); + +describe('ending a share', () => { + it('ends at expiresAt without publishing again', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + h.advance(15 * 60_000); + await h.engine.handleFix(north(BASE, 200, { at: h.now() })); + await h.engine.tick(); + expect(h.published).toHaveLength(1); + expect(h.ends.map((e) => e.reason)).toEqual(['expired']); + expect(h.activeWatch()).toHaveLength(0); + }); + + it('Stop ends it here at once and tells the server; later fixes publish nothing', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + await h.engine.stop(MATCH); + expect(h.transport.stop).toHaveBeenCalledWith(MATCH, SESSION); + expect(h.ends.map((e) => e.reason)).toEqual(['stopped']); + expect(h.engine.getSnapshot().ended[SESSION]?.reason).toBe('stopped'); + h.advance(MIN_PUBLISH_INTERVAL_MS); + await h.engine.handleFix(north(BASE, 300)); + expect(h.published).toHaveLength(1); + }); + + it('a share stopped while its publish is in flight stays stopped', async () => { + const h = harness(); + let release: () => void = () => undefined; + h.setPublish(() => new Promise((resolve) => (release = () => resolve({})))); + const begun = h.engine.begin(h.input(), BASE); + await vi.waitFor(() => expect(h.transport.publish).toHaveBeenCalledTimes(1)); + await h.engine.stop(MATCH); + release(); + await begun; + expect(h.engine.share(MATCH)).toBeUndefined(); + expect(h.engine.getSnapshot().shares).toEqual({}); + }); + + it('can stop one of the member’s shares that this tab does not run', async () => { + const h = harness(); + await h.engine.stopRemote(MATCH, SESSION_2); + expect(h.transport.stop).toHaveBeenCalledWith(MATCH, SESSION_2); + expect(h.engine.getSnapshot().ended[SESSION_2]?.reason).toBe('stopped'); + }); + + it('an ended event for this share (stopped on another device) ends it; other rows do not', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + const onRow = h.subscriptions.get(MATCH)!; + onRow({ matchId: MATCH, userId: 'peer-id', sessionId: SESSION, ended: true }); + onRow({ matchId: MATCH, userId: ME, sessionId: SESSION_2, ended: true }); + onRow({ matchId: MATCH, userId: ME, sessionId: SESSION, ended: false }); + expect(h.engine.share(MATCH)).toBeDefined(); + onRow({ matchId: MATCH, userId: ME, sessionId: SESSION, ended: true }); + expect(h.ends.map((e) => e.reason)).toEqual(['ended_elsewhere']); + }); + + it('follows State: a hook that is gone ends as released, a suspended one as suspended', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + await h.engine.begin(h.input({ matchId: 'match-2', sessionId: SESSION_2 }), BASE); + h.engine.reconcile(null); + h.engine.reconcile(undefined); + expect(h.ends).toEqual([]); + h.engine.reconcile([{ matchId: 'match-2', suspended: true }]); + expect(h.ends.map((e) => [e.matchId, e.reason])).toEqual([ + [MATCH, 'released'], + ['match-2', 'suspended'], + ]); + expect(h.transport.stop).not.toHaveBeenCalled(); + }); + + it('location access revoked ends the share and stops it on the server', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + h.activeWatch()[0].onDenied(); + expect(h.ends.map((e) => e.reason)).toEqual(['location_denied']); + expect(h.transport.stop).toHaveBeenCalledWith(MATCH, SESSION); + }); +}); + +describe('the tab owns the share', () => { + it('pagehide sends a keepalive stop for every running share and ends them here', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + await h.engine.begin(h.input({ matchId: 'match-2', sessionId: SESSION_2 }), BASE); + for (const fn of [...h.pageHide]) fn(); + expect(h.transport.stopOnUnload).toHaveBeenCalledWith(MATCH, SESSION); + expect(h.transport.stopOnUnload).toHaveBeenCalledWith('match-2', SESSION_2); + // Nothing can be awaited while the page goes away: the Amplify stop is not used. + expect(h.transport.stop).not.toHaveBeenCalled(); + expect(h.ends.map((e) => e.reason)).toEqual(['tab_closed', 'tab_closed']); + expect(h.pageHide.size).toBe(0); + expect(h.activeWatch()).toHaveLength(0); + }); + + it('when the unload stop cannot even be attempted, the share is still ended here (expiry ends it on the server)', async () => { + const h = harness(); + h.setUnloadAttempted(false); + await h.engine.begin(h.input(), BASE); + for (const fn of [...h.pageHide]) fn(); + expect(h.ends.map((e) => e.reason)).toEqual(['tab_closed']); + expect(h.transport.stop).not.toHaveBeenCalled(); + }); + + it('signing out ends every share through the keepalive stop, falling back to the API call', async () => { + const h = harness(); + await h.engine.begin(h.input(), BASE); + h.engine.endAll('signed_out'); + expect(h.transport.stopOnUnload).toHaveBeenCalledWith(MATCH, SESSION); + expect(h.transport.stop).not.toHaveBeenCalled(); + expect(h.transport.clearUnloadAuth).toHaveBeenCalled(); + + const fallback = harness(); + fallback.setUnloadAttempted(false); + await fallback.engine.begin(fallback.input(), BASE); + fallback.engine.endAll('signed_out'); + expect(fallback.transport.stop).toHaveBeenCalledWith(MATCH, SESSION); + expect(fallback.ends.map((e) => e.reason)).toEqual(['signed_out']); + }); + + it('says plainly that closing the tab stops updates', () => { + expect(TAB_BOUND_COPY).toBe("Location won't update if you close this tab."); + }); +}); + +describe('helpers', () => { + it('offers 15 minutes, 1 hour and 8 hours with their telemetry values', () => { + expect(LIVE_DURATIONS.map((d) => [d.value, d.ms])).toEqual([ + ['min_15', 15 * 60_000], + ['hour_1', 60 * 60_000], + ['hour_8', 8 * 60 * 60_000], + ]); + }); + + it('makeLiveWindow starts now and caps at 8 hours', () => { + expect(makeLiveWindow(60_000, T0)).toEqual({ startedAt: T0, expiresAt: T0 + 60_000 }); + expect(makeLiveWindow(24 * 60 * 60_000, T0).expiresAt).toBe(T0 + MAX_LIVE_SHARE_MS); + }); + + it('newLiveSessionId makes a UUID the backend accepts, with or without randomUUID', () => { + const pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + expect(newLiveSessionId()).toMatch(/^[A-Za-z0-9-]{8,64}$/); + const noUuid = { getRandomValues: (a: T) => globalThis.crypto.getRandomValues(a) }; + expect(newLiveSessionId(noUuid as unknown as Crypto)).toMatch(pattern); + }); + + it('isSignificantMove: first fix, 25 m, accuracy radius, much better accuracy', () => { + expect(isSignificantMove(undefined, BASE)).toBe(true); + expect(isSignificantMove(BASE, north(BASE, 24))).toBe(false); + expect(isSignificantMove(BASE, north(BASE, 26))).toBe(true); + expect(isSignificantMove(BASE, north(BASE, 40, { accuracyM: 50 }))).toBe(false); + expect(isSignificantMove({ ...BASE, accuracyM: 80 }, north(BASE, 5, { accuracyM: 10 }))).toBe(true); + }); + + it('explains ends the member did not cause, and stays quiet for the ones they did', () => { + expect(endNotice('stopped')).toBeNull(); + expect(endNotice('tab_closed')).toBeNull(); + expect(endNotice('signed_out')).toBeNull(); + expect(endNotice('expired')).toBe('Live location ended'); + expect(endNotice('suspended')).toMatch(/read only/); + }); + + it('withLocalEnds marks a share ended here as ended in the conversation state at once', () => { + const key = liveSessionKey(ME, SESSION); + const sessions: LiveSessions = { + [key]: { userId: ME, sessionId: SESSION, at: T0, expiresAt: T0 + 60_000, ended: false, position: { lat: 1, lon: 2, updatedAt: T0 } }, + }; + const ended = { [SESSION]: { matchId: MATCH, sessionId: SESSION, expiresAt: T0 + 60_000, reason: 'stopped' as const } }; + const out = withLocalEnds(sessions, ended, MATCH, ME, T0 + 1_000, mergeLiveSession); + expect(out[key].ended).toBe(true); + expect(out[key].position).toBeUndefined(); + // Ends in another conversation do not touch this one. + expect(withLocalEnds(sessions, ended, 'other-match', ME, T0 + 1_000, mergeLiveSession)).toBe(sessions); + }); +}); diff --git a/src/tests/location-contact-send-render.test.tsx b/src/tests/location-contact-send-render.test.tsx new file mode 100644 index 0000000..58acaca --- /dev/null +++ b/src/tests/location-contact-send-render.test.tsx @@ -0,0 +1,193 @@ +import { describe, expect, it } from 'vitest'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { LocationShareSheetView, type LocationShareSheetViewProps } from '../components/chat/LocationShareSheet'; +import { ContactShareSheetView, type ContactShareSheetViewProps } from '../components/chat/ContactShareSheet'; +import { StructuredMessageBubble, type LiveLocationContext } from '../components/chat/StructuredMessageBubble'; +import { EMPTY_CONTACT_FORM } from '../lib/contact-share'; +import { TAB_BOUND_COPY } from '../lib/live-location-sharing'; +import { UiElement, uiElementsForPlatform } from '../lib/analytics/generated/telemetryCatalog'; +import { referencedUiElementNames } from './telemetry-guard-scan'; + +/** + * Static render of the sending side: the location sheet (current and live, the durations, the + * tab-bound copy), the contact sheet (picked review and the manual form), and the Stop button on the + * member's own live bubble. Pins the telemetry ids and values each control carries. + */ + +const T0 = Date.now(); +const SESSION = '3f6d2c1e-8a4b-4c3d-9e2f-1a2b3c4d5e6f'; +const noop = () => undefined; +// renderToStaticMarkup escapes the apostrophe in the copy. +const TAB_BOUND_HTML = TAB_BOUND_COPY.replace("'", '''); + +function locationSheet(overrides: Partial = {}) { + return renderToStaticMarkup( + + ); +} + +describe('location sheet', () => { + it('previews the position on device and offers current and live, each tracked', () => { + const out = locationSheet(); + expect(out).toContain('12.97160° N, 77.59460° E'); + expect(out).toContain('Accuracy ±14 m'); + expect(out).toContain('Send your current location'); + expect(out).toContain('Share live location'); + expect(out).toContain(`data-track-id="${UiElement.CHAT_LOCATION_SHARE}" data-track-value="current"`); + expect(out).toContain(`data-track-id="${UiElement.CHAT_LOCATION_SHARE}" data-track-value="live"`); + expect(out).toContain(`data-track-id="${UiElement.CHAT_ATTACH_BUTTON}" data-track-action="dismiss"`); + expect(out).toContain(TAB_BOUND_HTML); + // Tile-free: no map image or tile host. + expect(out).not.toMatch(/ { + const out = locationSheet({ step: 'duration' }); + for (const [value, label] of [ + ['min_15', '15 minutes'], + ['hour_1', '1 hour'], + ['hour_8', '8 hours'], + ]) { + expect(out).toContain(`data-track-id="${UiElement.CHAT_LIVE_LOCATION_DURATION}" data-track-value="${value}"`); + expect(out).toContain(label); + } + expect(out).toContain(TAB_BOUND_HTML); + // Back emits the duration dismiss imperatively, so it is exempt rather than double counted. + expect(out).toContain('data-track-exempt="duplicate:'); + }); + + it('says a new live share replaces the running one', () => { + const out = locationSheet({ + step: 'duration', + runningShare: { matchId: 'm', sessionId: SESSION, peerName: 'Riya', startedAt: T0, expiresAt: T0 + 60_000 }, + }); + expect(out).toContain('This replaces the live share running until'); + }); + + it('cannot send before a position exists, and explains a refused permission', () => { + const locating = locationSheet({ phase: { kind: 'locating' } }); + expect(locating).toContain('Finding your location'); + expect(locating.match(/disabled=""/g)?.length).toBeGreaterThanOrEqual(2); + const denied = locationSheet({ phase: { kind: 'error', error: 'denied' } }); + expect(denied).toContain('Location access is off for this site'); + expect(denied).toContain(`data-track-id="${UiElement.CHAT_RETRY}"`); + }); +}); + +function contactSheet(overrides: Partial = {}) { + return renderToStaticMarkup( + + ); +} + +describe('contact sheet', () => { + it('without the Contact Picker: a form, Send disabled until there is a name', () => { + const out = contactSheet(); + expect(out).toContain('id="contact-share-name"'); + expect(out).toContain('aria-label="Phone number 1"'); + expect(out).toContain('aria-label="Email address 1"'); + expect(out).toMatch(/]*disabled=""[^>]*data-track-id="chat\.send_button"/); + const named = contactSheet({ values: { ...EMPTY_CONTACT_FORM, name: 'Asha' } }); + expect(named).not.toMatch(/]*disabled=""[^>]*data-track-id="chat\.send_button"/); + }); + + it('shows the name error once the field was left empty', () => { + expect(contactSheet({ nameTouched: true })).toContain('Enter a name'); + expect(contactSheet()).not.toContain('Enter a name'); + }); + + it('a picked contact: every phone and email ticked by default, untickable, plus choose another', () => { + const out = contactSheet({ + picked: { displayName: 'Asha Rao', phones: [{ value: '+91 98450 12345' }], emails: [{ value: 'asha@example.com' }] }, + pickerAvailable: true, + selection: { phones: [true], emails: [false] }, + }); + expect(out).toContain('Asha Rao'); + expect(out).toContain('Choose what to share'); + // Attribute order is React's (type, class, checked), so match the attributes anywhere in the tag. + expect(out.match(/]*type="checkbox"[^>]*checked=""[^>]*>/g)).toHaveLength(1); + expect(out.match(/type="checkbox"/g)).toHaveLength(2); + expect(out).toContain(`data-track-id="${UiElement.CHAT_ATTACH_OPTION}" data-track-value="contact"`); + }); +}); + +describe('send-side telemetry on web (catalog 1.24.0)', () => { + it('chat.location_share, chat.live_location_duration and chat.live_location_stop are in web scope and emitted', () => { + const referenced = referencedUiElementNames(new URL('../', import.meta.url).pathname); + const webScope = new Set(uiElementsForPlatform('web')); + for (const name of ['CHAT_LOCATION_SHARE', 'CHAT_LIVE_LOCATION_DURATION', 'CHAT_LIVE_LOCATION_STOP'] as const) { + expect(webScope.has(UiElement[name])).toBe(true); + expect(referenced.has(name)).toBe(true); + } + }); +}); + +describe('own live bubble', () => { + const live: LiveLocationContext = { + sessions: {}, + currentUserId: 'me-id', + peerId: 'peer-id', + peerName: 'Riya', + onStopShare: noop, + sharingHereSessionId: SESSION, + }; + const start = { + type: 'live_location' as const, + sessionId: SESSION, + startedAt: T0, + expiresAt: T0 + 15 * 60_000, + lat: 12.9716, + lon: 77.5946, + }; + + it('has a tracked Stop button and the tab-bound copy when this tab runs the share', () => { + const out = renderToStaticMarkup(); + expect(out).toContain('Stop sharing'); + expect(out).toContain(`data-track-id="${UiElement.CHAT_LIVE_LOCATION_STOP}"`); + expect(out).toContain(TAB_BOUND_HTML); + }); + + it('still offers Stop for a share from another device, without the tab copy', () => { + const out = renderToStaticMarkup( + + ); + expect(out).toContain('Stop sharing'); + expect(out).not.toContain(TAB_BOUND_HTML); + }); + + it("never offers Stop on the peer's share, or once a share ended", () => { + expect(renderToStaticMarkup()).not.toContain('Stop sharing'); + const ended = { ...start, expiresAt: T0 - 1, startedAt: T0 - 60_000 }; + expect(renderToStaticMarkup()).not.toContain('Stop sharing'); + }); +}); diff --git a/src/tests/location-send.test.ts b/src/tests/location-send.test.ts new file mode 100644 index 0000000..7dc6abc --- /dev/null +++ b/src/tests/location-send.test.ts @@ -0,0 +1,209 @@ +import { describe, expect, it, vi } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { + buildLiveLocationStartPayload, + buildLiveLocationUpdatePayload, + buildLocationPayload, + decodeStructuredFrame, + frameStructuredContent, + parseLiveLocationUpdate, +} from '../lib/chat-structured'; +import { + LocationReadError, + browserLocationSource, + errorKindFromCode, + fixFromPosition, + getCurrentFix, + isPageForeground, + windowPageLifecycle, + type GeolocationLike, + type PositionLike, +} from '../lib/browser-location'; + +/** + * Sending locations from the web: the payloads exactly as the contract has them, reading positions + * from the Geolocation API (one-shot and watch), the pagehide hook, and the rule that the matching + * location is only read while the page is in the foreground. + */ + +const T0 = 1_794_700_000_000; +const SESSION = '3f6d2c1e-8a4b-4c3d-9e2f-1a2b3c4d5e6f'; + +describe('payloads', () => { + it('a current location: 6 decimals, accuracy, capturedAt, nothing else', () => { + const payload = buildLocationPayload({ lat: 12.97161234, lon: 77.59456789, accuracyM: 14.26, at: T0 }); + expect(payload).toEqual({ v: 1, type: 'location', lat: 12.971612, lon: 77.594568, accuracyM: 14.3, capturedAt: T0 }); + expect(decodeStructuredFrame(frameStructuredContent(payload))).toMatchObject({ type: 'location', lat: 12.971612 }); + }); + + it('omits an unknown accuracy and refuses coordinates out of range', () => { + expect(buildLocationPayload({ lat: 1, lon: 2, accuracyM: Number.NaN, at: T0 })).not.toHaveProperty('accuracyM'); + expect(() => buildLocationPayload({ lat: 91, lon: 0, at: T0 })).toThrow(); + expect(() => buildLocationPayload({ lat: 0, lon: Number.NaN, at: T0 })).toThrow(); + }); + + it('a live start carries the session, its window and the first position', () => { + const payload = buildLiveLocationStartPayload({ + sessionId: SESSION, + startedAt: T0, + expiresAt: T0 + 3_600_000, + fix: { lat: 12.9716, lon: 77.5946, accuracyM: 14, at: T0 }, + }); + expect(payload).toEqual({ + v: 1, + type: 'live_location', + sessionId: SESSION, + startedAt: T0, + expiresAt: T0 + 3_600_000, + lat: 12.9716, + lon: 77.5946, + accuracyM: 14, + }); + expect(decodeStructuredFrame(frameStructuredContent(payload))).toMatchObject({ type: 'live_location', sessionId: SESSION }); + expect(() => buildLiveLocationStartPayload({ sessionId: 'bad id', startedAt: T0, expiresAt: T0 + 1, fix: { lat: 0, lon: 0, at: T0 } })).toThrow(); + expect(() => buildLiveLocationStartPayload({ sessionId: SESSION, startedAt: T0, expiresAt: T0, fix: { lat: 0, lon: 0, at: T0 } })).toThrow(); + }); + + it('a live update round-trips through the receiver parser, heading wrapped below 360', () => { + const payload = buildLiveLocationUpdatePayload(SESSION, { + lat: 12.9718, + lon: 77.5949, + accuracyM: 9, + headingDeg: 359.7, + speedMps: 1.44, + at: T0 + 60_000, + }); + expect(payload).toEqual({ + v: 1, + type: 'live_location_update', + sessionId: SESSION, + lat: 12.9718, + lon: 77.5949, + accuracyM: 9, + headingDeg: 0, + speedMps: 1.4, + at: T0 + 60_000, + }); + const parsed = parseLiveLocationUpdate(frameStructuredContent(payload), SESSION); + expect(parsed).toMatchObject({ headingDeg: 0, speedMps: 1.4 }); + // An update is never a chat message. + expect(decodeStructuredFrame(frameStructuredContent(payload))).toEqual({ type: 'unsupported' }); + }); +}); + +function position(coords: Partial, timestamp = T0): PositionLike { + return { coords: { latitude: 12.9716, longitude: 77.5946, ...coords }, timestamp }; +} + +describe('reading positions', () => { + it('maps a browser position to a fix, dropping heading when not moving', () => { + expect(fixFromPosition(position({ accuracy: 12, heading: 90, speed: 0 }))).toEqual({ + lat: 12.9716, + lon: 77.5946, + accuracyM: 12, + speedMps: 0, + at: T0, + }); + expect(fixFromPosition(position({ heading: 90, speed: 2 }))).toMatchObject({ headingDeg: 90, speedMps: 2 }); + expect(fixFromPosition(position({ heading: Number.NaN, speed: null, accuracy: null }))).toEqual({ lat: 12.9716, lon: 77.5946, at: T0 }); + expect(fixFromPosition(position({ latitude: 200 }))).toBeNull(); + }); + + it('maps GeolocationPositionError codes', () => { + expect(errorKindFromCode(1)).toBe('denied'); + expect(errorKindFromCode(2)).toBe('unavailable'); + expect(errorKindFromCode(3)).toBe('timeout'); + }); + + it('getCurrentFix resolves a fix, and rejects with the reason', async () => { + const ok: GeolocationLike = { + getCurrentPosition: (success) => success(position({ accuracy: 5 })), + watchPosition: () => 1, + clearWatch: () => undefined, + }; + await expect(getCurrentFix(ok)).resolves.toMatchObject({ lat: 12.9716, accuracyM: 5 }); + + const denied: GeolocationLike = { ...ok, getCurrentPosition: (_s, error) => error?.({ code: 1 }) }; + await expect(getCurrentFix(denied)).rejects.toMatchObject({ kind: 'denied' }); + await expect(getCurrentFix(null)).rejects.toBeInstanceOf(LocationReadError); + await expect(getCurrentFix(null)).rejects.toMatchObject({ kind: 'unsupported' }); + }); + + it('the live watch asks for GPS at high accuracy, accepts older network fixes at low, and stops cleanly', () => { + const calls: PositionOptions[] = []; + const cleared: number[] = []; + let success: (p: PositionLike) => void = () => undefined; + let failure: (e: { code: number }) => void = () => undefined; + const geo: GeolocationLike = { + getCurrentPosition: () => undefined, + watchPosition: (s, e, options) => { + success = s; + failure = e ?? failure; + calls.push(options ?? {}); + return calls.length; + }, + clearWatch: (id) => cleared.push(id), + }; + const source = browserLocationSource(geo); + const onFix = vi.fn(); + const onDenied = vi.fn(); + const stopHigh = source.watch(onFix, onDenied, { highAccuracy: true }); + expect(calls[0]).toMatchObject({ enableHighAccuracy: true, maximumAge: 0 }); + success(position({ accuracy: 5 })); + expect(onFix).toHaveBeenCalledWith(expect.objectContaining({ lat: 12.9716, accuracyM: 5 })); + failure({ code: 2 }); + expect(onDenied).not.toHaveBeenCalled(); + failure({ code: 1 }); + expect(onDenied).toHaveBeenCalledTimes(1); + stopHigh(); + stopHigh(); + expect(cleared).toEqual([1]); + + source.watch(onFix, onDenied, { highAccuracy: false }); + expect(calls[1]).toMatchObject({ enableHighAccuracy: false, maximumAge: 60_000 }); + }); + + it('without geolocation the watch reports denied at once', () => { + const onDenied = vi.fn(); + browserLocationSource(null).watch(() => undefined, onDenied, { highAccuracy: true }); + expect(onDenied).toHaveBeenCalledTimes(1); + }); + + it('hooks pagehide and unhooks it', () => { + const listeners = new Set<() => void>(); + const win = { + addEventListener: (_type: 'pagehide', fn: () => void) => listeners.add(fn), + removeEventListener: (_type: 'pagehide', fn: () => void) => listeners.delete(fn), + }; + const fn = vi.fn(); + const off = windowPageLifecycle(win).onPageHide(fn); + for (const l of listeners) l(); + expect(fn).toHaveBeenCalledTimes(1); + off(); + expect(listeners.size).toBe(0); + }); +}); + +describe('matching location stays in the foreground', () => { + it('isPageForeground is true only for a visible page', () => { + expect(isPageForeground({ visibilityState: 'visible' })).toBe(true); + expect(isPageForeground({ visibilityState: 'hidden' })).toBe(false); + }); + + const source = readFileSync(new URL('../hooks/use-user-location.ts', import.meta.url), 'utf8'); + + it('use-user-location reads once (never watches) and only while the page is visible', () => { + expect(source).not.toMatch(/watchPosition/); + expect(source).toMatch(/if \(!isPageForeground\(\)\) return;/); + expect(source).toMatch(/visibilitychange/); + }); + + it('the chat share engine never touches the matching location', () => { + const sharing = readFileSync(new URL('../lib/live-location-sharing.ts', import.meta.url), 'utf8'); + const browser = readFileSync(new URL('../lib/browser-location.ts', import.meta.url), 'utf8'); + for (const text of [sharing, browser]) { + expect(text).not.toMatch(/from ['"][^'"]*(use-user-location|api\/matching)['"]/); + expect(text).not.toMatch(/indexLocation\(|MatchingApi/); + } + }); +}); diff --git a/src/tests/matching-tab.test.tsx b/src/tests/matching-tab.test.tsx index e379039..0c2e85a 100644 --- a/src/tests/matching-tab.test.tsx +++ b/src/tests/matching-tab.test.tsx @@ -10,7 +10,11 @@ import { isValidElement, type ReactElement, type ReactNode } from 'react'; * screen" action and the Settings > General switch that brings it back (SetMatchingTabHidden). * Server rendering runs no effects, so nothing here reaches the network unless a test calls an API. */ -vi.mock('../api/sdk-client', () => ({ sdkClient: {} })); +const sdk = vi.hoisted(() => ({ setMatchingTabHidden: vi.fn() })); +vi.mock('../api/sdk-client', async (importOriginal) => ({ + ...(await importOriginal()), + sdkClient: sdk, +})); import { ToastProvider } from '../components/common/Toast'; import { LockedDiscoverChips, MatchingIntroView, MATCHING_INTRO_COPY } from '../features/matching/MatchingIntroView'; @@ -218,32 +222,31 @@ describe('Settings > General: Show Matching tab', () => { describe('StateApi.setMatchingTabHidden (PUT /state/matching/tab-hidden)', () => { afterEach(() => vi.unstubAllGlobals()); - it('sends {hidden} and returns the server’s answer', async () => { - const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify({ hidden: true }), { status: 200 })); - vi.stubGlobal('fetch', fetchMock); + it('sends {hidden} through the SDK (SetMatchingTabHidden) and returns the server’s answer', async () => { + sdk.setMatchingTabHidden.mockReset().mockResolvedValue({ $metadata: {}, hidden: true }); await expect(StateApi.setMatchingTabHidden(true)).resolves.toBe(true); - const [url, init] = fetchMock.mock.calls[0]; - expect(url).toMatch(/\/state\/matching\/tab-hidden$/); - expect(init.method).toBe('PUT'); - expect(JSON.parse(String(init.body))).toEqual({ hidden: true }); + expect(sdk.setMatchingTabHidden).toHaveBeenCalledWith({ hidden: true }); }); it('showing it again sends hidden:false', async () => { - const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify({ hidden: false }), { status: 200 })); - vi.stubGlobal('fetch', fetchMock); + sdk.setMatchingTabHidden.mockReset().mockResolvedValue({ $metadata: {}, hidden: false }); await expect(StateApi.setMatchingTabHidden(false)).resolves.toBe(false); - expect(JSON.parse(String(fetchMock.mock.calls[0][1].body))).toEqual({ hidden: false }); + expect(sdk.setMatchingTabHidden).toHaveBeenCalledWith({ hidden: false }); }); it('a 400 or 500 rejects with the shared ApiError', async () => { - vi.stubGlobal( - 'fetch', - vi.fn(async () => new Response(JSON.stringify({ error: 'hidden is required', code: 'BAD_REQUEST' }), { status: 400 })) + sdk.setMatchingTabHidden.mockReset().mockRejectedValue( + Object.assign(new Error('UnknownError'), { + $metadata: { httpStatusCode: 400 }, + error: 'hidden is required', + code: 'BAD_REQUEST', + }) ); const err = await StateApi.setMatchingTabHidden(true).catch((e: unknown) => e); expect(err).toBeInstanceOf(ApiError); expect((err as ApiError).status).toBe(400); expect((err as ApiError).code).toBe('BAD_REQUEST'); + expect((err as ApiError).message).toBe('hidden is required'); }); it('the state snapshot reads matchingTabHidden; absent means shown', () => { diff --git a/src/tests/mr-onehook-contract.test.ts b/src/tests/mr-onehook-contract.test.ts index 10ca22f..3620e5c 100644 --- a/src/tests/mr-onehook-contract.test.ts +++ b/src/tests/mr-onehook-contract.test.ts @@ -3,10 +3,8 @@ import { buildMemberChatRequestBody, classifyMemberChatAvailability, isSessionErrorCode, - MEMBER_CHAT_PATH, parseMemberChatResponse, matchSuggestionNote, - PUBLIC_PRODUCT_CHAT_PATH, } from '../lib/mr-onehook-contract'; import type { SelectedExcerpt } from '../lib/mr-onehook-excerpts'; @@ -22,13 +20,6 @@ const excerpt: SelectedExcerpt = { text: 'I would really like to visit Japan.', }; -describe('endpoint paths', () => { - it('match the OneHook UX Enhancement backend routes', () => { - expect(PUBLIC_PRODUCT_CHAT_PATH).toBe('/api/public/product-chat'); - expect(MEMBER_CHAT_PATH).toBe('/api/member/product-connection-chat'); - }); -}); - describe('classifyMemberChatAvailability — entitlement/auth gating', () => { it('classifies 402 MESSAGE_LIMIT_REACHED as LIMIT_REACHED (free tier daily allowance)', () => { expect(classifyMemberChatAvailability(402, 'MESSAGE_LIMIT_REACHED')).toBe('LIMIT_REACHED'); diff --git a/src/tests/password-rule.test.ts b/src/tests/password-rule.test.ts new file mode 100644 index 0000000..1f3fb6a --- /dev/null +++ b/src/tests/password-rule.test.ts @@ -0,0 +1,37 @@ +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { passwordError, PASSWORD_MIN_LENGTH } from '../lib/account-setup'; + +/** + * The user pool requires 12+ characters with a symbol (OneHookBackend infra/stacks/shared-stack.ts + * `passwordPolicy`). `passwordError` in lib/account-setup.ts is the one copy of that rule; a screen + * with its own weaker check (the sign-in "set password" form once accepted 8 characters) lets a member + * submit a password Cognito then rejects. + */ +const ROOT = new URL('../', import.meta.url).pathname; + +function sources(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + if (statSync(path).isDirectory()) return name === 'tests' ? [] : sources(path); + return /\.(ts|tsx)$/.test(name) && !/\.(test|spec)\.tsx?$/.test(name) ? [path] : []; + }); +} + +describe('password rule', () => { + it('matches the user pool: 12+ characters with a symbol', () => { + expect(PASSWORD_MIN_LENGTH).toBe(12); + expect(passwordError('short!', 'short!')).not.toBeNull(); + expect(passwordError('twelvechars1', 'twelvechars1')).not.toBeNull(); + expect(passwordError('twelve-chars', 'twelve-chars')).toBeNull(); + }); + + it('is checked only by lib/account-setup.ts (no screen has its own length check)', () => { + const offenders = sources(ROOT) + .filter((file) => !file.endsWith('lib/account-setup.ts')) + .filter((file) => /\b(password|newPassword)\.length\s*[<>]=?\s*\d/.test(readFileSync(file, 'utf8'))) + .map((file) => relative(ROOT, file)); + expect(offenders).toEqual([]); + }); +}); diff --git a/src/tests/photo-stats.test.ts b/src/tests/photo-stats.test.ts index 8d954b6..9bbaa79 100644 --- a/src/tests/photo-stats.test.ts +++ b/src/tests/photo-stats.test.ts @@ -4,32 +4,42 @@ vi.mock('aws-amplify/auth', () => ({ fetchAuthSession: async () => ({ tokens: { idToken: { toString: () => 'jwt-abc' } } }), })); -describe('Owner photo stats API', () => { - afterEach(() => vi.unstubAllGlobals()); +describe('Owner photo stats API (GetMediaStats through the SDK)', () => { + afterEach(() => vi.restoreAllMocks()); - it('asks for the caller’s own stats without sending any user id, authenticated by the JWT', async () => { - const fetchMock = vi.fn(async () => ({ - ok: true, - json: async () => ({ photos: [{ mediaId: 'media/u1/a.jpg', uniqueViewers: 3, fullscreenViewers: 1 }] }), - })); - vi.stubGlobal('fetch', fetchMock); - vi.stubGlobal('window', { location: { hostname: 'app.gamma.onehook.club', origin: 'https://app.gamma.onehook.club' } }); + it('asks for the caller’s own stats with no input (the owner is the JWT subject)', async () => { + const { sdkClient } = await import('../api/sdk-client'); + const spy = vi.spyOn(sdkClient, 'getMediaStats').mockResolvedValue({ + $metadata: {}, + photos: [ + { + mediaId: 'media/u1/a.jpg', + uniqueViewers: 3, + viewersMoreThanOnce: 2, + viewersMoreThan10: 1, + viewersMoreThan100: 0, + fullscreenViewers: 1, + totalViews: 9, + totalFullscreenOpens: 1, + }, + ], + } as never); const { getMyPhotoStats } = await import('../api/analytics'); const stats = await getMyPhotoStats(); - const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; - expect(url.endsWith('/signals/media-stats')).toBe(true); - expect(url).not.toMatch(/userId|u1/); - expect((init.headers as Record).Authorization).toBe('Bearer jwt-abc'); - expect(stats['media/u1/a.jpg'].uniqueViewers).toBe(3); + expect(spy).toHaveBeenCalledWith({}); + // The generated PhotoStats model, keyed by mediaId. + expect(stats['media/u1/a.jpg']).toMatchObject({ uniqueViewers: 3, viewersMoreThan10: 1, totalViews: 9 }); }); - it('surfaces a server error', async () => { - vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 401 }))); - vi.stubGlobal('window', { location: { hostname: 'x', origin: 'https://x' } }); + it('surfaces a server error as an ApiError with the status', async () => { + const { sdkClient } = await import('../api/sdk-client'); + vi.spyOn(sdkClient, 'getMediaStats').mockRejectedValue( + Object.assign(new Error('UnknownError'), { $metadata: { httpStatusCode: 401 } }) + ); const { getMyPhotoStats } = await import('../api/analytics'); - await expect(getMyPhotoStats()).rejects.toThrow(/401/); + await expect(getMyPhotoStats()).rejects.toMatchObject({ name: 'ApiError', status: 401 }); }); }); diff --git a/src/tests/report-evidence-outcomes.test.ts b/src/tests/report-evidence-outcomes.test.ts index f49f49d..7bf6d5b 100644 --- a/src/tests/report-evidence-outcomes.test.ts +++ b/src/tests/report-evidence-outcomes.test.ts @@ -9,6 +9,8 @@ * Fix (3): submit_with_evidence / submit_without_evidence are emitted ONLY after the report is * created (201); on a create failure only submit_failed is emitted (never a submit_* success). */ +import { createModerationEvidenceClient } from '../api/external-sdk-clients'; +import { fetchHandler } from './support/sdk-fetch-handler'; import { describe, it, expect } from 'vitest'; import { submitReport, @@ -63,7 +65,7 @@ function presignFailingTransport(status: number, code: string): EvidenceTranspor if ((init?.method ?? 'GET') === 'PUT') return new Response(null, { status: 200 }); throw new Error(`unexpected ${url}`); }) as unknown as typeof fetch; - return { baseUrl: 'https://x/moderation', fetchImpl, getToken: async () => 't', sleep: async () => {} }; + return { baseUrl: 'https://x/api/p/onehook/gamma/moderation', client: createModerationEvidenceClient('https://x/api/p/onehook/gamma/moderation', async () => 't', fetchHandler(fetchImpl)), fetchImpl, getToken: async () => 't', sleep: async () => {} }; } /** A transport that presigns + PUTs fine but whose complete returns a given status+code. */ @@ -80,7 +82,7 @@ function completeResultTransport(status: number, body: unknown): EvidenceTranspo if ((init?.method ?? 'GET') === 'PUT') return new Response(null, { status: 200 }); throw new Error(`unexpected ${url}`); }) as unknown as typeof fetch; - return { baseUrl: 'https://x/moderation', fetchImpl, getToken: async () => 't', sleep: async () => {} }; + return { baseUrl: 'https://x/api/p/onehook/gamma/moderation', client: createModerationEvidenceClient('https://x/api/p/onehook/gamma/moderation', async () => 't', fetchHandler(fetchImpl)), fetchImpl, getToken: async () => 't', sleep: async () => {} }; } describe('classifyEvidenceError', () => { diff --git a/src/tests/report-submit.test.ts b/src/tests/report-submit.test.ts index 74bd064..2616578 100644 --- a/src/tests/report-submit.test.ts +++ b/src/tests/report-submit.test.ts @@ -5,6 +5,8 @@ * evidence failure leaves the report filed; the 503 EVIDENCE_FINALIZE_RETRY backoff; MINOR_SAFETY * (evidenceAllowed:false) never uploads; and telemetry carries no text / user ids. */ +import { createModerationEvidenceClient } from '../api/external-sdk-clients'; +import { fetchHandler } from './support/sdk-fetch-handler'; import { describe, it, expect, vi } from 'vitest'; import { submitReport, @@ -75,6 +77,11 @@ function makeTransport( return { baseUrl: 'https://admin.onehook.club/api/p/onehook/gamma/moderation', + client: createModerationEvidenceClient( + 'https://admin.onehook.club/api/p/onehook/gamma/moderation', + async () => 'member-id-token', + fetchHandler(fetchImpl) + ), fetchImpl, getToken: async () => 'member-id-token', sleep: async () => {}, diff --git a/src/tests/support/sdk-fetch-handler.ts b/src/tests/support/sdk-fetch-handler.ts new file mode 100644 index 0000000..3da94f6 --- /dev/null +++ b/src/tests/support/sdk-fetch-handler.ts @@ -0,0 +1,36 @@ +/** + * A Smithy request handler over an injected `fetch`, for tests: the generated client serialises the + * real request (method, path with labels, headers, JSON body) and the fake `fetch` answers it, so a + * test exercises the SDK's actual wire format and error parsing without the network. + */ +import { HttpResponse, type HttpRequest } from '@smithy/protocol-http'; + +export function fetchHandler(fetchImpl: typeof fetch) { + return { + async handle(request: HttpRequest) { + const query = new URLSearchParams( + Object.entries(request.query ?? {}).flatMap(([k, v]) => + Array.isArray(v) ? v.map((x) => [k, x]) : v == null ? [] : [[k, v]] + ) + ).toString(); + const port = request.port ? `:${request.port}` : ''; + const url = `${request.protocol}//${request.hostname}${port}${request.path}${query ? `?${query}` : ''}`; + const res = await fetchImpl(url, { + method: request.method, + headers: request.headers, + body: request.body as BodyInit | undefined, + }); + const headers: Record = {}; + res.headers.forEach((v, k) => (headers[k] = v)); + return { + response: new HttpResponse({ + statusCode: res.status, + headers, + body: new Uint8Array(await res.arrayBuffer()), + }), + }; + }, + updateHttpClientConfig() {}, + httpHandlerConfigs: () => ({}), + }; +} diff --git a/src/tests/telemetry-sdk.test.ts b/src/tests/telemetry-sdk.test.ts index eca0f79..64490d7 100644 --- a/src/tests/telemetry-sdk.test.ts +++ b/src/tests/telemetry-sdk.test.ts @@ -16,7 +16,9 @@ import { TRACK_TARGET_ATTR, } from '../lib/analytics/uiTracking'; import { UiElement } from '../lib/analytics/generated/telemetryCatalog'; -import { AnalyticsClient, createFetchTransport, type Signal } from '../lib/analytics/analyticsClient'; +import { AnalyticsClient, type Signal } from '../lib/analytics/analyticsClient'; +import { sdkClient } from '../api/sdk-client'; +import { signalsTransport } from '../api/analytics'; describe('resolveUiInteraction: representative newly-instrumented elements', () => { it('nav + photo-viewer buttons default to tap', () => { @@ -153,28 +155,28 @@ describe('newly instrumented elements resolve to the right id + default action', }); }); -describe('fetch transport sends the platform header', () => { - it('POSTs /signals with X-OneHook-Platform: web', async () => { - const calls: Array<{ url: string; init: RequestInit }> = []; - const fakeFetch = vi.fn(async (url: string, init: RequestInit) => { - calls.push({ url, init }); - return { ok: true, status: 200 } as Response; - }) as unknown as typeof fetch; +describe('signals transport (IngestSignals through the SDK)', () => { + it('sends the batch with platform web through sdkClient.ingestSignals', async () => { + const spy = vi + .spyOn(sdkClient, 'ingestSignals') + .mockResolvedValue({ accepted: 1, rejected: 0, reasons: {}, $metadata: {} } as never); + const batch: Signal[] = [{ clientEventId: 'e1', type: 'ui_interaction', timestamp: 1, attributes: { elementId: 'nav.back' } }]; + await signalsTransport.send(batch); - const transport = createFetchTransport({ - endpoint: 'https://api.example/signals', - getToken: async () => 'jwt-token', + expect(spy).toHaveBeenCalledTimes(1); + expect(spy.mock.calls[0][0]).toEqual({ platform: 'web', - fetchImpl: fakeFetch, + signals: [{ clientEventId: 'e1', type: 'ui_interaction', timestamp: 1, attributes: { elementId: 'nav.back' } }], }); + spy.mockRestore(); + }); - const batch: Signal[] = [{ clientEventId: 'e1', type: 'ui_interaction', timestamp: 1, attributes: { elementId: 'nav.back' } }]; - await transport.send(batch); - - expect(calls).toHaveLength(1); - const headers = calls[0].init.headers as Record; - expect(headers['X-OneHook-Platform']).toBe('web'); - expect(headers['Authorization']).toBe('Bearer jwt-token'); + it('rejects with an ApiError carrying the HTTP status, so the batch is re-queued', async () => { + const spy = vi + .spyOn(sdkClient, 'ingestSignals') + .mockRejectedValue(Object.assign(new Error('UnknownError'), { $metadata: { httpStatusCode: 503 } })); + await expect(signalsTransport.send([])).rejects.toMatchObject({ name: 'ApiError', status: 503 }); + spy.mockRestore(); }); it('an isolated AnalyticsClient flushes ui_interaction batches through the transport', async () => { diff --git a/vite.config.ts b/vite.config.ts index 18e413f..8f10226 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -18,6 +18,7 @@ import { smartAppBannerContent, type RouteSeo, } from './src/config/seo-routes'; +import { devApiProxy } from './src/config/dev-proxy'; const distDir = resolve(__dirname, 'dist'); @@ -251,31 +252,9 @@ export default defineConfig(({ mode }) => { allow: [resolve(__dirname), resolve(__dirname, '..', 'OneHookBackend')], }, proxy: { - '/profile': { - target: 'https://api.gamma.onehook.club', - changeOrigin: true, - secure: true, - }, - '/state': { - target: 'https://api.gamma.onehook.club', - changeOrigin: true, - secure: true, - }, - '/matching': { - target: 'https://api.gamma.onehook.club', - changeOrigin: true, - secure: true, - }, - '/identity': { - target: 'https://api.gamma.onehook.club', - changeOrigin: true, - secure: true, - }, - '/chat': { - target: 'https://api.gamma.onehook.club', - changeOrigin: true, - secure: true, - }, + // Every REST prefix the app calls, to the Gamma ingress (src/config/dev-proxy.ts; the list is + // checked against the generated route manifest by src/tests/dev-proxy.test.ts). + ...devApiProxy(), '/api/localstack/chat': { target: 'https://hmlzbhd52r.execute-api.localhost.localstack.cloud:4566', changeOrigin: true,