# Aphrodite — Systems Deep Dive

> The `apps/aphrodite/` area: seventeen Nx applications that make up a live
> creator-streaming platform — ingest/broadcast, viewing, chat, interactive
> devices, payments, delivery, notifications, analytics, admin, VR, and two
> React Native mobile shells.

## What this area is

Aphrodite is a vertically-sliced **adult live-streaming platform** expressed as
seventeen independent Nx applications under `apps/aphrodite/`. Unlike a `libs/`
domain, these are deployable services and apps — each has its own
`package.json`, `tsconfig.json`, `Dockerfile`-able build, and a `serve`/`start`
target. There is no single monolith here; the platform is decomposed by bounded
concern (auth, money, streaming, chat, devices, …) so each service owns its own
routes, schemas, and runtime.

The backend services follow one of two house styles, visible in the
`project.json` naming. The `aphrodite-*`-named projects (e.g.
`aphrodite-streaming`, `aphrodite-broadcaster`, `aphrodite-payment`) build with
`tsup` directly and are organised as a **Hono application factory**
(`src/app.ts` exporting `createApp()`) mounting Zod-validated route modules
under `src/routes/`. The `@aphrodite/*`-named projects (e.g. `@aphrodite/auth`,
`@aphrodite/cdn`, `@aphrodite/notifications`) build via `pnpm run build` and add
a **domain service layer** — a `src/<domain>/service.ts` (often with a
repository interface, an in-memory implementation, and sometimes a real Postgres
implementation) behind the routes. Two projects
(`@aphrodite/mobile-broadcaster`, `@aphrodite/mobile-viewer`) are React Native
apps built with `react-native` / Detox / Jest rather than `tsup`.

### Implemented vs. scaffold — the honest split

This area is a **mix of fully-implemented domain engines and HTTP-contract
scaffolds**, and the line is worth drawing precisely:

- **Real domain logic** (algorithms, crypto, protocol handlers, persistence,
  with unit tests): `@aphrodite/auth` (HS256 JWT, password, sessions, 2FA),
  `@aphrodite/cdn` (CloudFront-style URL signing, cache invalidation, uploads),
  `@aphrodite/devices` (real Lovense/Kiiroo/Handy/Buttplug/TCode protocol
  handlers + pattern engine + tip-trigger automation),
  `@aphrodite/notifications` (a real Postgres repository with partial indexes
  and a `FOR UPDATE SKIP LOCKED` dispatcher), `aphrodite-analytics-dashboard`
  (deterministic segment-fit and slot-quality scoring models that explicitly
  replaced earlier `Math.random()` fabrications),
  `aphrodite-realtime-analytics`, `@aphrodite/analytics`, `@aphrodite/admin`,
  `@aphrodite/vr`, and the moderation engine inside `aphrodite-chat`.
- **HTTP-contract scaffolds** (rich Hono apps with real middleware and
  Zod-validated request schemas, but route handlers that return placeholder/
  empty payloads behind `// TODO: Fetch from database`, with no service or
  persistence layer yet): `aphrodite-streaming`, `aphrodite-broadcaster`,
  `aphrodite-payment`, and `aphrodite-viewer`. These are honest API skeletons —
  the wire surface is real, the backing logic is not yet wired.
- **TypeScript-only mobile shells**: `@aphrodite/mobile-broadcaster` and
  `@aphrodite/mobile-viewer` carry real RN screen/service/native-bridge
  TypeScript, but the native iOS/Android projects have not been generated (each
  ships a `NATIVE_SCAFFOLDING.md` that says so plainly), so the apps cannot
  currently be run on a device.

## How it fits the wider system

These are leaf applications: they sit at the top of the dependency graph and
**consume** shared platform libraries (Hono is the common HTTP framework; the
`@aphrodite/database` Postgres client is referenced structurally rather than
hard-imported, e.g. the notification repository accepts any pg-compatible
`QueryClient`). They relate to one another by domain boundary rather than by
code-sharing: `aphrodite-broadcaster` creates streams that `aphrodite-streaming`
ingests/transcodes and `aphrodite-viewer` watches; `aphrodite-chat` and
`@aphrodite/devices` layer interactive features over a live stream;
`aphrodite-payment` settles tokens/tips that `@aphrodite/devices` tip-triggers
react to; the analytics trio and `@aphrodite/admin` observe the whole platform;
and the two mobile apps are thin clients over the same backend surfaces. The
service-to-service contracts are expressed as each service's own Zod route
schemas (no shared contracts package is imported here), and the integration
`*.integration.spec.ts` suites exercise each Hono app end-to-end over HTTP.

## Entity reference

### @aphrodite/auth

The identity service (`apps/aphrodite/auth`). Fully implemented:
`src/auth/jwt.ts` hand-rolls **HS256 JWTs** with `crypto.createHmac`, base64url
encoding, `timingSafeEqual` signature verification, a JTI revocation set, and a
hash-based refresh-token scheme; alongside it are `auth/password.ts`,
`session/service.ts`, and `twofactor/service.ts`, with routes for
`auth`/`oauth`/`twofactor` and an `auth` middleware. This is real
security-domain code (constant-time comparisons, separate access/refresh
secrets, 15-minute access / 7-day refresh expiries), not a CRUD wrapper.

### aphrodite-streaming

The stream ingest/transcoding/distribution service (`apps/aphrodite/streaming`).
It is a **route-layer scaffold**: a Hono app whose `src/routes/` modules
(`ingest`, `transcoding`, `distribution`, `recording`, `quality`, `thumbnails`,
`discovery`, `metrics`) carry genuinely detailed Zod schemas — e.g.
`transcoding.ts` validates ABR quality profiles, codecs (`h264`/`h265`/`vp9`/
`av1`), HLS/LL-HLS/DASH/CMAF output, and hardware-acceleration settings
(`nvenc`/`vaapi`/`qsv`). But the handlers are placeholders
(`// TODO: Allocate transcoding worker`, `// TODO: Start FFmpeg/media pipeline`)
returning synthesised job objects; there is no `services/` layer yet. Real API
contract, not-yet-real backing pipeline.

### aphrodite-broadcaster

The broadcaster-operations service (`apps/aphrodite/broadcaster`) for stream
creation, profiles, shows, and broadcaster settings. Like `aphrodite-streaming`
it is a **Hono route scaffold** (`src/routes/` for `streams`, `shows`,
`profile`, `devices`, `settings`, `analytics`) with real middleware and an
integration spec, but its handlers are dominated by `// TODO: … from database`
placeholders and there is no service layer. Honest API skeleton.

### aphrodite-viewer

The viewer-experience service (`apps/aphrodite/viewer`) — following, history,
watchlist, tips, chat/device proxying, notifications. It is the most heavily
scaffolded service in the area (the most `// TODO` markers): the Hono routes and
JWT-extraction middleware seam exist, but handlers such as those in
`routes/history.ts` return empty lists behind `// TODO: Fetch viewing history`.
Real route surface, persistence unimplemented.

### aphrodite-chat

The real-time chat service (`apps/aphrodite/chat`). A **mixed** project: the
moderation engine is real — `src/moderation/content-filter.ts` implements word/
link/spam filtering with a `DEFAULT_FILTER_CONFIG` and a `.test.ts`, and the
`src/socket/` handlers (`connection`, `rooms`, `dm`, `messages`, `moderation`,
`typing`) wire Socket.io events through `requireAuth`, slow-mode/restriction
checks, mention extraction, and `filterContent`. The REST `src/routes/` handlers
are partly placeholder, but the WebSocket + moderation core is implemented.

### @aphrodite/devices

The interactive-device control service (`apps/aphrodite/devices`) — the most
domain-specific node in the area. `src/protocols/` contains **real handlers for
Lovense, Kiiroo, Handy, OhMiBod, Buttplug, and TCode**: e.g. `lovense.ts`
carries a full table of Lovense models and their capabilities and makes actual
`fetch` calls to the Lovense local API for discovery and commands.
`src/patterns/manager.ts` runs vibration/stroke patterns and
`src/automation/tip-trigger.ts` links tip events to device patterns with
per-user cooldowns and a pluggable command callback. Fully implemented.

### aphrodite-payment

The payments service (`apps/aphrodite/payment`) — tokens, tips, subscriptions,
payouts, transactions, earnings, webhooks. It is a **route-layer scaffold**:
`src/routes/tokens.ts` and siblings define precise Zod schemas (purchase
packages, multi-PSP `paymentMethod` enums for
ccbill/segpay/stripe/paypal/crypto, atomic-transfer payloads) and an integration
spec, but the handlers are explicit placeholders
(`// TODO: Create purchase session`, `// TODO: Add tokens to user balance`)
returning hardcoded balances and synthesised session objects. The money-movement
logic is not yet implemented behind the validated surface.

### @aphrodite/cdn

The content-delivery service (`apps/aphrodite/cdn`). Implemented:
`src/signing/ service.ts` generates **CloudFront-style signed URLs and cookies**
with `crypto.createSign`/`createHash`; `src/cache/` provides invalidation and
cache-control logic (with `invalidation.spec.ts`); `src/upload/service.ts`
handles uploads (with `service.spec.ts`). Real signing/caching domain code, not
a stub.

### aphrodite-realtime-analytics

The real-time engagement service (`apps/aphrodite/realtime-analytics`).
Implemented: `src/services/engagement.ts` is an **Engagement Pulse Aggregator**
over sliding `TimeWindow`s (messages, tips, reactions, follows, subscriptions,
unique chatters, emoji/reaction tallies) with a pluggable
`ReactionSentimentClassifier`; alongside `viewers.ts`/`revenue.ts`, an
`events/bus.ts` EventEmitter, and a `websocket` broadcaster. Has an
`engagement.spec.ts`. Real streaming-metrics logic.

### @aphrodite/analytics

The analytics pipeline + creator-dashboard service (`apps/aphrodite/analytics`).
Implemented: `src/analytics/service.ts` is an event-ingestion pipeline with
batch processing, validation, and configurable deduplication windows, fronting
an `IAnalyticsClient` abstraction (`client.ts`); `src/dashboard/service.ts`
serves creator dashboards. Real ingestion logic behind the `events`/`dashboard`
routes.

### aphrodite-analytics-dashboard

The platform analytics-dashboard service (`apps/aphrodite/analytics-dashboard`)
— the largest backend node (~10k lines) covering revenue, viewers, engagement,
trends, predictions, alerts, and exports over both REST and a `websocket`
handler. Its standout pieces are two **deterministic scoring models** under
`src/services/`: `segment-fit-model.ts` (a saturating-excess / freshness scorer
with documented per-segment constants and a model registry) and
`slot-quality-model.ts` (an audience-demand curve with hourly/day-of-week
multipliers and per-category Gaussian peaks). Both explicitly replaced earlier
`score: Math.random()` fabrications and ship with `.test.ts` files. Real
statistical logic.

### aphrodite-admin-bi-dashboard

The administrative business-intelligence service
(`apps/aphrodite/admin-bi-dashboard`) — platform metrics, revenue, user growth,
content trends, and compliance (age-verification, 2257, GDPR) reporting.
`src/app.ts` is a full Hono factory with security headers, CORS, compression,
ETag/timing, a request-ID seam, and a hand-written OpenAPI `/docs` enumerating
its `platform`/`revenue`/`users`/ `content`/`compliance` route surface.
Substantial route + context wiring; the reporting handlers aggregate over the
platform's read surface.

### @aphrodite/admin

The platform admin/moderation service (`apps/aphrodite/admin`). Implemented:
`src/moderation/service.ts` is a content-moderation engine
(`EventEmitter`-based, with an `IModerationRepository` interface, an in-memory
implementation, filters, priority/status counts, and audit-log integration),
plus `users/service.ts` and `settings/service.ts`. Routes for `moderation`,
`users`, and `settings`. Has a `moderation/service.test.ts`. Real admin-domain
logic over an in-memory store.

### @aphrodite/vr

The VR capture/playback service (`apps/aphrodite/vr`) for immersive content.
Implemented: `src/capture/service.ts` (`VRCaptureService`) manages VR streams
across field-of-view, projection, stereo layout, and spatial-audio
configurations, with a quality-preset system (`presets.ts`), validation
(`validation.ts`), spatial-audio source management (`audio.ts`), optional Redis
persistence, and recommended-bitrate/resolution helpers; `src/playback/` mirrors
this for the viewing side (quality, detection, settings). Real VR-domain code,
not a stub.

### @aphrodite/notifications

The notifications service (`apps/aphrodite/notifications`) — in-app, push, and
email delivery. Implemented and notably production-grade:
`src/notification/ postgres-repository.ts` defines an idempotent
`NOTIFICATION_SCHEMA_SQL` with **carefully-chosen partial indexes** and a
`FOR UPDATE SKIP LOCKED` dispatcher queue, talking to a structural `QueryClient`
so it works against the workspace pg client or a transaction-bound client;
alongside it are an in-memory repository, `email/service.ts`, `push/service.ts`,
and a `websocket` handler, with `.spec.ts` coverage including the Postgres
repository. Real persistence and delivery logic.

### @aphrodite/mobile-broadcaster

The creator mobile-streaming app (`apps/aphrodite/mobile-broadcaster`), a bare
React Native project. The `src/` is real TypeScript — screens, navigation,
`services/` (StreamingService, FaceTrackingService, PortraitModeService,
AvatarControlService, …), and `src/native/` **TurboModule bridges** targeting
ARKit/ARCore face tracking, portrait segmentation, and depth estimation, each
with a fail-loud "report unavailable" fallback when the native module is absent
(plus `.spec.ts` coverage). However, per its `NATIVE_SCAFFOLDING.md`, the iOS/
Android platform projects, root `index.js`, and metro/babel config have **not
been generated**, so the app cannot currently run on a device — it is real
mobile logic in an ungenerated native shell.

### @aphrodite/mobile-viewer

The viewer mobile app (`apps/aphrodite/mobile-viewer`), also bare React Native.
Its `src/` carries real service TypeScript — `VRViewingService` (Cardboard-style
stereoscopic rendering, gyroscope head tracking, WebXR session state),
`StreamingService`, `ChatService`, `TippingService`, and `OfflineService` — over
typed `vr-viewing` models. Like its broadcaster sibling, the native iOS/Android
projects are not generated (`NATIVE_SCAFFOLDING.md`), so it is TypeScript-only
and not yet runnable on-device.
