> ## Documentation Index
> Fetch the complete documentation index at: https://docs.equa.cc/llms.txt
> Use this file to discover all available pages before exploring further.

# Backend Architecture

> Express/TypeORM backend with 20 modules and vineyard-lawn endpoints

# Backend Architecture

> **Repository:** `equa-server` | **Stack:** Express, TypeORM, PostgreSQL, Node 18, vineyard-lawn

## Server Entry Point

Source: `equa-server/modules/api/src/server.ts` (function `startApi()`, lines 180-198)

The server starts with this sequence:

1. Create Express app
2. Enable CORS via `enableCors(app)` (vineyard-lawn)
3. Initialize sessions via `initializeSessions()` (TypeORM session store)
4. Register Google OAuth redirect endpoint
5. Register all API endpoints via `createEndpoints(app, endpoints)` (vineyard-lawn)
6. Initialize dynamic file serving
7. Register `/health` and `/` ping endpoints
8. Register 404 handler
9. Start Express on configured port (default: 3000)

### SSL Support

Source: `equa-server/modules/api/src/server.ts` (function `startExpress()`, lines 53-98)

SSL is optional, activated when `API_SSL` env var is set. Reads certs from `SSL_PRIVATE_KEY_PATH` and `SSL_PUBLIC_KEY_PATH`.

## Module Inventory

The backend is organized into 20 modules under `equa-server/modules/`:

| Module            | Directory                | Purpose                                                              |
| ----------------- | ------------------------ | -------------------------------------------------------------------- |
| **api**           | `modules/api/`           | Main Express server, endpoint registration, route definitions        |
| **api-helper**    | `modules/api-helper/`    | HTTP handler utilities, response formatting                          |
| **auth**          | `modules/auth/`          | Authentication (password, Google OAuth, magic links), sessions, RBAC |
| **persistence**   | `modules/persistence/`   | TypeORM entities (92), database connection, schema management        |
| **organizations** | `modules/organizations/` | Organization CRUD, details, settings                                 |
| **captable**      | `modules/captable/`      | Cap table management, shareholdings, securities                      |
| **billing**       | `modules/billing/`       | Chargify billing integration, subscriptions                          |
| **notifications** | `modules/notifications/` | Email via AWS SES / SMTP, Handlebars templates                       |
| **file-storage**  | `modules/file-storage/`  | AWS S3 file upload/download, Microsoft file storage                  |
| **doc-gen**       | `modules/doc-gen/`       | Document generation (certificates, agreements)                       |
| **data-room**     | `modules/data-room/`     | Data room access control and file management                         |
| **google-drive**  | `modules/google-drive/`  | Google Drive OAuth, sync, file operations                            |
| **microsoft**     | `modules/microsoft/`     | Microsoft Graph integration                                          |
| **admin**         | `modules/admin/`         | Admin-only endpoints                                                 |
| **activity**      | `modules/activity/`      | Activity/action logging                                              |
| **agent**         | `modules/agent/`         | AI assistant (Equanaut) -- chat, tools, onboarding                   |
| **referral**      | `modules/referral/`      | Referral system, EquaCash rewards                                    |
| **wallet**        | `modules/wallet/`        | Wallet and payment method management                                 |
| **common**        | `modules/common/`        | Shared types and utilities                                           |
| **raven**         | `modules/raven/`         | Raven blockchain address management                                  |

## Endpoint Framework: vineyard-lawn

Endpoints are defined using vineyard-lawn's type-safe endpoint system.

Source: `equa-server/modules/api/src/lib/utility.ts` (lines 60-94)

```typescript theme={null}
// Standard endpoint
defineEndpoint<T>(config)

// Endpoint with permission check
defineRestrictedEndpoint<T>(config)
```

Each endpoint specifies:

* HTTP method and path
* Request/response types
* Optional `requires?: PermissionCheck` for authorization
* Versioning (v1 prefix)

### Endpoint Files

Source: `equa-server/modules/api/src/endpoints/`

| File                        | Endpoint Group                                  |
| --------------------------- | ----------------------------------------------- |
| `auth-endpoints.ts`         | Authentication (login, register, verify, OAuth) |
| `organization-endpoints.ts` | Organization CRUD, details, settings            |
| `captable-endpoints.ts`     | Cap table operations, shareholdings             |
| `user-endpoints.ts`         | User management, profile, current user          |
| `billing-endpoints.ts`      | Billing, subscriptions, Chargify webhooks       |
| `admin-endpoints.ts`        | Admin-only operations                           |
| `activity-endpoints.ts`     | Activity logging and retrieval                  |
| `data-room-endpoints.ts`    | Data room access and files                      |
| `google-drive-endpoints.ts` | Google Drive sync and connection                |
| `microsoft-endpoints.ts`    | Microsoft integration                           |
| `referral-endpoints.ts`     | Referral system                                 |
| `wallet-endpoint.ts`        | Wallet and blockchain operations                |
| `color-endpoints.ts`        | User color preferences                          |

Agent-specific endpoints in `equa-server/modules/agent/src/endpoints/`:

* `agent-endpoints.ts` -- Chat, confirmations, context, tools, onboarding

## Database Layer

Source: `equa-server/modules/persistence/src/site/connecting.ts`

| Property          | Value                                                                        |
| ----------------- | ---------------------------------------------------------------------------- |
| ORM               | TypeORM                                                                      |
| Database          | PostgreSQL (configurable via `DATABASE_TYPE`)                                |
| Entities          | 92 (defined in `schema.ts`)                                                  |
| Schema sync       | Enabled in development (`NODE_ENV=development && DATABASE_SYNC !== 'false'`) |
| Connection config | Via environment variables (`DATABASE_HOST`, `DATABASE_USERNAME`, etc.)       |

### Entity Registration

Source: `equa-server/modules/persistence/src/schema.ts` (lines 2008-2101)

All 92 entities are registered in the `allEntities` array and loaded during connection initialization.

## Middleware Stack

| Middleware            | Purpose                           | Source                         |
| --------------------- | --------------------------------- | ------------------------------ |
| CORS                  | Cross-origin requests             | vineyard-lawn `enableCors()`   |
| express-session       | Session management                | `modules/auth/src/sessions.ts` |
| TypeORM session store | Session persistence in PostgreSQL | Custom `TypeORMSessionStore`   |
| URL-encoded parser    | Google OAuth redirect             | `server.ts` line 143           |
| Error logging         | Request error capture             | `configureErrorLogging()`      |

<Warning>
  No explicit rate limiting middleware was found in the codebase. This is a gap for production readiness.
</Warning>

## Process Architecture

### Development

```
equa-server $ yarn start:dev
→ ts-node modules/api/scripts/api.ts
→ Express on port 3000
```

### Production

```
Docker (node:18-alpine)
→ PM2 (pm2-runtime)
  → api process (./modules/api/scripts/api.js, port 3000)
  → raven-addresses process (./modules/raven/scripts/user-raven-addresses.js)
```

## Build Pipeline

Source: `equa-server/package.json`

| Script      | Command                                               |
| ----------- | ----------------------------------------------------- |
| `build`     | `yarn tsc && yarn tsa`                                |
| `tsc`       | Build API module TypeScript                           |
| `tsa`       | Build file-storage module TypeScript                  |
| `start:api` | `yarn build && cd modules/api && node scripts/api.js` |
| `start:dev` | Development mode with ts-node                         |
| `init:db`   | Database initialization                               |
