This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Canonical URI: chittycanon://core/services/chittyfinance | Tier 3 (Service Layer) | finance.chitty.cc
ChittyFinance is a full-stack financial management platform for the ChittyOS ecosystem. It provides intelligent financial tracking, AI-powered advice, recurring charge optimization, and integrations with Mercury Bank, Wave Accounting, and Stripe payments.
Architecture: Hono on Cloudflare Workers (production) + legacy Express (local dev). PostgreSQL (Neon) with Drizzle ORM. React frontend.
npm install # Install dependencies
npm run dev # Auto-detect mode and start dev server on port 5000
npm run dev:standalone # Start in standalone mode (local development)
npm run dev:system # Start in system mode (ChittyOS integration)
npm run check # TypeScript type checking
npm run mode:detect # Detect and display current mode
npm run mode:setup # Setup mode configuration (script not yet implemented)npm run build # Build system mode (default for production)
npm run build:standalone # Build standalone mode (outputs to dist/standalone)
npm run build:system # Build system mode (outputs to dist/system)
npm run build:both # Build both modes
npm run start # Run standalone production build locally
npm run deploy # Deploy to Cloudflare Workers (system mode)
npm run deploy:staging # Deploy to staging environment
npm run deploy:production # Deploy to production environmentnpm run db:push # Push schema changes (uses current drizzle.config.ts)
npm run db:push:system # Push system schema to PostgreSQL
npm run db:push:standalone # Push standalone schema to SQLite
npm run db:seed # Seed IT CAN BE LLC entity structureFirst-Time Setup (System Mode):
MODE=system npm run db:push:system # Create tables
npm run db:seed # Create tenants and usersFirst-Time Setup (Standalone Mode):
npm run db:push:standalone # Create SQLite tables
# No seeding needed - single user modeCritical:
- Port 5001 is used in
server/index.tsfor local Express development - Server uses
reusePort: truefor multiple process support on the same port
ChittyFinance supports two operational modes (controlled by MODE environment variable):
Standalone Mode (default for local development):
- SQLite database for quick local development
- Single-tenant (no multi-tenancy overhead)
- Simplified schema in
database/standalone.schema.ts - Build output:
dist/standalone/ - Database file:
./chittyfinance.db - Run:
npm run devornpm run dev:standalone
System Mode (production - multi-tenant):
- PostgreSQL (Neon) with full multi-tenancy
- Supports IT CAN BE LLC entity structure
- Complete schema in
database/system.schema.ts - Build output:
dist/system/ - Cloudflare Workers deployment
- Run:
npm run dev:system - Deploy:
npm run deployornpm run deploy:production
Mode Detection:
- Default:
npm run devruns in standalone mode - Explicitly set:
MODE=system npm run dev - Auto-detection script:
npm run mode:detect
IT CAN BE LLC Entity Structure:
IT CAN BE LLC (holding)
├── JEAN ARLENE VENTURING LLC (personal, 85% owner)
├── Nicholas Bianchi (personal — income/mgmt assigned to JAV LLC)
│ ├── Lakeside Loft — 541 W Addison St #3S, Chicago IL
│ └── Cozy Castle — 550 W Surf St #504, Chicago IL
├── ARIBIA LLC (series, 100% owned)
│ ├── ARIBIA LLC - MGMT (management)
│ │ ├── Chicago Furnished Condos (consumer brand)
│ │ └── Chitty Services (vendor/tech services)
│ ├── ARIBIA LLC - CITY STUDIO (property)
│ │ └── City Studio — 550 W Surf St C211, Chicago IL
│ ├── ARIBIA LLC - APT ARLENE (property)
│ │ └── Villa Vista — 4343 N Clarendon #1610, Chicago IL
│ └── Morada Mami — Carrera 76A #53-215, Medellin, Colombia
└── ChittyCorp LLC (holding, pending formation)
Tenant Types:
holding- Holding companies (IT CAN BE LLC, ChittyCorp LLC)series- Series LLCs (ARIBIA LLC)property- Property holding entities (City Studio, Apt Arlene)management- Management companies (ARIBIA LLC - MGMT)personal- Personal entities (JEAN ARLENE VENTURING LLC, Nicholas Bianchi)
Key Features:
- Each tenant has isolated financial data
- Inter-company transaction tracking
- Property-specific rent roll and lease management
- User access control per tenant (roles: owner, admin, manager, viewer)
- Consolidated reporting across entities
- Frontend: React 18 with TypeScript, Wouter (routing), shadcn/ui (Radix UI components)
- Backend: Hono (Cloudflare Workers, production) / Express.js (legacy, local dev)
- Database: Neon PostgreSQL with Drizzle ORM
- Build: Vite (frontend), esbuild (backend)
- Styling: Tailwind CSS with tailwindcss-animate
- State: TanStack React Query for server state
- Payments: Stripe integration
- AI: OpenAI GPT-4o for financial advice
chittyfinance/
├── client/ # React frontend (Vite root)
│ └── src/
│ ├── pages/ # Page components (Dashboard, Settings, Landing)
│ ├── components/ # Reusable UI components (shadcn/ui)
│ ├── hooks/ # Custom React hooks
│ └── lib/ # Client utilities
├── server/ # Hono backend (Cloudflare Workers)
│ ├── app.ts # Hono app factory with middleware wiring
│ ├── env.ts # HonoEnv type (Bindings + Variables)
│ ├── worker.ts # Cloudflare Workers entry point
│ ├── index.ts # Legacy Express entry (standalone dev)
│ ├── routes.ts # Legacy Express routes (reference only)
│ ├── routes/ # Hono route modules (22 files)
│ │ ├── health.ts # /health, /api/v1/status
│ │ ├── docs.ts # /api/v1/documentation (OpenAPI spec)
│ │ ├── accounts.ts # /api/accounts
│ │ ├── summary.ts # /api/summary
│ │ ├── tenants.ts # /api/tenants
│ │ ├── properties.ts # /api/properties (CRUD + financials + rent roll + P&L)
│ │ ├── transactions.ts # /api/transactions (+ CSV/OFX/QFX export)
│ │ ├── integrations.ts # /api/integrations
│ │ ├── allocations.ts # /api/allocations (inter-company rules + execution)
│ │ ├── tasks.ts # /api/tasks
│ │ ├── ai.ts # /api/ai-messages
│ │ ├── mercury.ts # /api/mercury (via ChittyConnect)
│ │ ├── github.ts # /api/github
│ │ ├── stripe.ts # /api/integrations/stripe
│ │ ├── wave.ts # /api/integrations/wave (OAuth)
│ │ ├── charges.ts # /api/charges (recurring)
│ │ ├── forensics.ts # /api/forensics (21 endpoints)
│ │ ├── valuation.ts # /api/properties/:id/valuation (multi-source AVM)
│ │ ├── session.ts # /api/session (KV-backed cookie auth)
│ │ ├── email.ts # /api/email (Cloudflare Email Service)
│ │ ├── import.ts # /api/import (TurboTenant, Mercury, HD Pro, Amazon CSV + Wave sync)
│ │ └── webhooks.ts # Stripe/Mercury/Wave webhooks (per-tenant HMAC)
│ ├── middleware/ # auth, tenant, error middleware
│ ├── storage/ # SystemStorage (Drizzle queries)
│ ├── db/ # connection.ts (Neon HTTP), schema.ts
│ └── lib/ # Server utilities
│ ├── wave-api.ts # Wave Accounting GraphQL client
│ ├── oauth-state-edge.ts # Edge-compatible HMAC OAuth state
│ ├── chargeAutomation.ts # Recurring charge analysis (stubs)
│ ├── forensicService.ts # Forensic algorithms (legacy)
│ └── valuation/ # Property valuation providers
│ ├── types.ts # ValuationProvider interface, AggregatedValuation
│ ├── zillow.ts # Zillow via RapidAPI
│ ├── redfin.ts # Redfin via RapidAPI
│ ├── housecanary.ts # HouseCanary REST API
│ ├── attom.ts # ATTOM Data Gateway
│ ├── county.ts # Cook County Assessor (Socrata)
│ └── index.ts # Provider registry + confidence-weighted aggregation
├── database/ # Schema definitions
│ ├── system.schema.ts # Multi-tenant PostgreSQL (UUID-based)
│ └── standalone.schema.ts # Single-tenant SQLite
├── shared/ # Shared types and schemas
│ └── schema.ts # Legacy schema with forensic tables (integer-ID)
└── deploy/
└── system-wrangler.jsonc # Cloudflare Workers config (JSONC)
Location: database/system.schema.ts
Core Tables:
tenants- Legal entities (LLCs, properties, management companies)users- User accounts with email/password + optional ChittyIDtenant_users- User access to tenants with role-based permissionsaccounts- Bank accounts, credit cards (tenant-scoped)transactions- Financial transactions with decimal precisionintercompany_transactions- Transfers between tenants
Property Management Tables:
properties- Real estate assetsunits- Rental units (if property has multiple units)leases- Tenant leases with rent and datesproperty_valuations- Cached AVM estimates from external providers (Zillow, Redfin, HouseCanary, ATTOM, County)
Chart of Accounts & Classification Tables:
chart_of_accounts- Database-backed COA with tenant customization (NULL tenant_id = global defaults, 60 REI accounts seeded)classification_audit- Audit trail for every COA code change on a transaction (trust level L0-L4, actor attribution)
Classification columns on transactions:
coa_code- Authoritative COA classification (L2+ executor writes)suggested_coa_code- AI/keyword proposal (L1 writes, L3 auditor reviews)classification_confidence- 0.000-1.000 scoreclassified_by/classified_at- Who set coa_code and whenreconciled_by/reconciled_at- L3 auditor who locked the transaction
Trust Path for Classification (executor/auditor segregation):
| Level | Role | COA Permissions |
|---|---|---|
| L0 Ingest | Executor | Write to 9010 (suspense) only |
| L1 Suggest | Executor | Write suggested_coa_code, not coa_code |
| L2 Classify | Executor | Set coa_code on unreconciled transactions |
| L3 Reconcile | Auditor | Lock transactions, review L2 classifications |
| L4 Govern | Auditor | Modify the COA itself (add/rename/retire accounts) |
Supporting Tables:
integrations- Mercury/Wave/Stripe API connectionstasks- Financial tasksai_messages- AI conversation history
Key Characteristics:
- UUIDs for primary keys (better for distributed systems)
- Decimal precision for all monetary amounts (12,2)
- Full multi-tenancy with tenant isolation
- Hierarchical tenants (parent-child relationships)
- Indexed for performance (tenant_id, date, etc.)
Location: database/standalone.schema.ts
Simplified Tables:
users,accounts,transactions,properties,tasks,integrations
Key Characteristics:
- Text IDs (simpler for SQLite)
- Real (float) for amounts (acceptable for dev)
- No multi-tenancy (single user)
- Faster for local development
Mode-Aware Connection (server/db.ts):
The database connection automatically switches based on MODE environment variable:
System Mode (MODE=system):
// PostgreSQL (Neon) with multi-tenant schema
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const db = drizzleNeon({ client: pool, schema: systemSchema });Standalone Mode (MODE=standalone):
// SQLite for local development
const sqlite = new Database('./chittyfinance.db');
const db = drizzleBetterSqlite(sqlite, { schema: standaloneSchema });Environment Variables:
- System mode:
DATABASE_URL(Neon PostgreSQL connection string) - Standalone mode:
SQLITE_FILE(optional, defaults to./chittyfinance.db)
Seed Script: database/seeds/it-can-be-llc.ts
Creates the complete IT CAN BE LLC entity structure:
- IT CAN BE LLC (parent holding company)
- JEAN ARLENE VENTURING LLC (85% owner, personal income funnel)
- Nicholas Bianchi (personal — properties held individually, income/mgmt via JAV LLC)
- ARIBIA LLC (series parent)
- ARIBIA LLC - MGMT (management company with two brands)
- ARIBIA LLC - CITY STUDIO (property entity)
- ARIBIA LLC - APT ARLENE (property entity)
- ChittyCorp LLC (pending formation)
Also creates:
- 5 property records: Lakeside Loft, Cozy Castle, City Studio, Villa Vista, Morada Mami
- User accounts for Nicholas Bianchi and Sharon E Jones
- Access permissions for each user to appropriate tenants
Run seeding:
npm run db:seedNote: Only run after pushing the system schema (npm run db:push:system)
Critical Pattern: All database access goes through server/storage.ts. Never write direct Drizzle queries in routes.
server/storage.ts uses the old shared/schema.ts and needs to be updated to use database/system.schema.ts with tenant-aware queries.
Interface (server/storage.ts:12-42):
export interface IStorage {
// User operations
getUser(id: number): Promise<User | undefined>;
getUserByUsername(username: string): Promise<User | undefined>;
createUser(user: InsertUser): Promise<User>;
// Integration operations
getIntegrations(userId: number): Promise<Integration[]>;
createIntegration(integration: InsertIntegration): Promise<Integration>;
updateIntegration(id: number, integration: Partial<Integration>): Promise<Integration | undefined>;
// Financial summary operations
getFinancialSummary(userId: number): Promise<FinancialSummary | undefined>;
createFinancialSummary(summary: InsertFinancialSummary): Promise<FinancialSummary>;
// Transaction, Task, and AI Message operations...
}Usage in routes (server/routes.ts):
import { storage } from "./storage";
const user = await storage.getUserByUsername("demo");
const summary = await storage.getFinancialSummary(user.id);Current implementation: Dual-path auth via hybridAuth middleware (server/middleware/auth.ts).
Path 1 — Service token (service-to-service):
Authorization: Bearer <CHITTY_AUTH_SERVICE_TOKEN>header- Used by ChittyConnect, MCP, and other ChittyOS services
Path 2 — Session cookie (browser clients):
cf_sessioncookie set byPOST /api/session(login)- KV-backed (
FINANCE_KV) with 7-day TTL - Session stores
{ userId }, resolved to full user bycallerContextmiddleware
Session routes (server/routes/session.ts — public, no auth required):
GET /api/session— return current user from cookiePOST /api/session— login with{ email, password }DELETE /api/session— logout (clear cookie + KV)
Password hashing: SHA-256 (Web Crypto in Workers, Node crypto in seed script).
Frontend flow (client/src/App.tsx):
- On load, fetches
GET /api/sessionwithcredentials: "include" - If 401, redirects to
/login - Login form POSTs credentials, cookie is set, page reloads
Note: ChittyID integration is planned to replace email/password auth.
- Real-time financial summary: Cash on hand, revenue, expenses, outstanding invoices
- Data source: Cached in
financialSummariestable, fetched from integrations - Demo data: Hardcoded values if no summary exists (
server/routes.ts:51-55)
Location: server/lib/openai.ts
Model: GPT-4o (hardcoded, comment at line 3 warns against changing)
Functions:
getFinancialAdvice()- Conversational financial advice based on financial datagenerateCostReductionPlan()- AI-generated cost reduction strategies
API endpoint: POST /api/ai/message sends user query to OpenAI with financial context
Location: server/lib/chargeAutomation.ts
Capabilities:
- Identify recurring charges from integrated services
- Generate optimization recommendations (cancel, downgrade, consolidate, negotiate)
- Calculate potential savings
API endpoints:
GET /api/recurring-charges- List all recurring chargesGET /api/recurring-charges/:id/optimizations- Get optimization suggestionsPOST /api/recurring-charges/:id/manage- Execute management action
Mercury Bank (server/lib/financialServices.ts:22-51, via ChittyConnect):
- Real integration through ChittyConnect backend
- Multi-account support with account selection
- Static egress IP for bank compliance
- Fetches balances and transactions
- Falls back to minimal data in standalone mode
- Routes:
/api/mercury/accounts,/api/mercury/select-accounts - Configuration: Requires
CHITTYCONNECT_API_BASE+CHITTYCONNECT_API_TOKEN
Wave Accounting (server/lib/wave-api.ts + server/lib/financialServices.ts:54-116):
- Real integration via OAuth 2.0 + GraphQL API
- Complete OAuth flow with CSRF protection (HMAC-signed state tokens)
- Fetches invoices, expenses, and financial summaries
- Automatic token refresh support
- Routes:
/api/integrations/wave/authorize,/callback,/refresh - Requirements: Wave Pro subscription,
WAVE_CLIENT_ID,WAVE_CLIENT_SECRET - Security: Uses
server/lib/oauth-state.tsfor secure state token generation/validation
Stripe (server/lib/stripe.ts):
- Real integration for payment processing
- Customer management with tenant metadata
- Checkout session creation (ad-hoc payments)
- Webhook verification and idempotent event processing
- Routes:
/api/integrations/stripe/connect,/checkout,/webhook - Configuration:
STRIPE_SECRET_KEY,STRIPE_WEBHOOK_SECRET - Events stored in
webhook_eventstable (seeshared/finance.schema.ts)
DoorLoop (server/lib/financialServices.ts:119-147):
- Mock data (property management)
- Returns hardcoded rent roll and maintenance data
- Real API integration pending
GitHub (server/lib/github.ts):
- Real GitHub API integration (not mock)
- Fetches repositories, commits, PRs, issues
- Used for project cost attribution
Integration Status Monitoring:
- New endpoint:
GET /api/integrations/status(server/routes.ts:122-126) - Validates which integrations are properly configured
- Uses
server/lib/integration-validation.tsto check environment variables - Returns configuration status for wave, stripe, mercury, openai
A utility script for analyzing and detecting duplicate operations in system mode. Located at the project root. This script helps maintain code quality when working with ChittyOS integration.
-
Update database schema in
shared/schema.ts:export const newTable = pgTable("new_table", { id: serial("id").primaryKey(), userId: integer("user_id").notNull().references(() => users.id), // ... fields });
-
Run migration:
npm run db:push -
Add storage methods in
server/storage.ts:async getNewData(userId: number): Promise<NewData[]> { return await db.select().from(newTable).where(eq(newTable.userId, userId)); }
-
Create API routes in
server/routes.ts:api.get("/new-data", async (req: Request, res: Response) => { const user = await storage.getUserByUsername("demo"); const data = await storage.getNewData(user.id); res.json(data); });
-
Build frontend in
client/src/pages/:- Use TanStack Query for data fetching
- Import shadcn/ui components from
@/components/ui/
OpenAI Configuration (server/lib/openai.ts):
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const openai = OPENAI_API_KEY ? new OpenAI({ apiKey: OPENAI_API_KEY }) : null;Best practices:
- Model is GPT-4o (do not change without user request per comment)
- Max tokens: 500 for financial advice
- Include financial context in system prompt
- Handle API errors gracefully (rate limits, invalid keys)
- When
OPENAI_API_KEYis not set, AI functions return rule-based fallback advice - OpenAI client is
nullwhen unconfigured — functions guard withif (!openai)early returns
Configured in tsconfig.json:18-21:
{
"@/*": ["./client/src/*"],
"@shared/*": ["./shared/*"]
}Additional alias in vite.config.ts:25:
"@assets": path.resolve(import.meta.dirname, "attached_assets")Usage:
import { Button } from "@/components/ui/button";
import { users } from "@shared/schema";
import logo from "@assets/logo.png";GET /api/session- Get current user from session cookiePOST /api/session- Login with email + password (setscf_sessioncookie)DELETE /api/session- Logout (clears cookie + KV entry)
GET /api/financial-summary- Get cached financial summaryGET /api/transactions- List transactions with optional filters
GET /api/integrations- List configured integrationsGET /api/integrations/status- Check which integrations are properly configuredPOST /api/integrations- Add new integrationPATCH /api/integrations/:id- Update integration credentialsGET /api/integrations/events- List webhook events with optional source filterPOST /api/admin/events/replay- Replay webhook events to ChittyOS services
GET /api/integrations/wave/authorize- Start OAuth flow (returns authorization URL)GET /api/integrations/wave/callback- OAuth callback handler (redirects to /connections)POST /api/integrations/wave/refresh- Refresh expired access token
POST /api/integrations/stripe/connect- Create/fetch Stripe customerPOST /api/integrations/stripe/checkout- Create ad-hoc payment sessionPOST /api/integrations/stripe/webhook- Stripe webhook endpoint (signature verified)
GET /api/mercury/accounts- List available Mercury accounts via ChittyConnectPOST /api/mercury/select-accounts- Select which accounts to syncPOST /api/integrations/mercury/webhook- Mercury webhook endpoint (authenticated)
GET /api/charges/recurring- List recurring charges from integrationsGET /api/charges/optimizations- Get optimization recommendationsPOST /api/charges/manage- Cancel/modify a recurring charge
POST /api/ai/advice- Get initial AI financial advicePOST /api/ai/cost-reduction- Generate cost reduction planPOST /api/ai/message- Conversational AI advice (includes previous context)
GET /api/github/repositories- List user repositoriesGET /api/github/repositories/:owner/:repo/commits- Get repository commitsGET /api/github/repositories/:owner/:repo/pulls- Get pull requestsGET /api/github/repositories/:owner/:repo/issues- Get issues
GET /api/forensics/investigations- List investigationsGET /api/forensics/investigations/:id- Get investigationPOST /api/forensics/investigations- Create investigationPATCH /api/forensics/investigations/:id/status- Update statusPOST /api/forensics/investigations/:id/evidence- Add evidenceGET /api/forensics/investigations/:id/evidence- List evidencePOST /api/forensics/evidence/:id/custody- Update chain of custodyPOST /api/forensics/investigations/:id/analyze- Comprehensive analysisPOST /api/forensics/investigations/:id/analyze/duplicates- Duplicate payment detectionPOST /api/forensics/investigations/:id/analyze/timing- Unusual timing detectionPOST /api/forensics/investigations/:id/analyze/round-dollars- Round dollar anomaliesPOST /api/forensics/investigations/:id/analyze/benfords-law- Benford's Law analysisPOST /api/forensics/investigations/:id/trace-funds- Trace flow of fundsPOST /api/forensics/investigations/:id/flow-of-funds- Create flow of funds recordGET /api/forensics/investigations/:id/flow-of-funds- Get flow of fundsPOST /api/forensics/investigations/:id/calculate-damages/direct-loss- Direct loss calculationPOST /api/forensics/investigations/:id/calculate-damages/net-worth- Net worth methodPOST /api/forensics/calculate-interest- Pre-judgment interest calculationPOST /api/forensics/investigations/:id/generate-summary- Executive summaryPOST /api/forensics/investigations/:id/reports- Create forensic reportGET /api/forensics/investigations/:id/reports- Get forensic reports
GET /api/tasks- List financial tasksPOST /api/tasks- Create taskPATCH /api/tasks/:id- Update taskDELETE /api/tasks/:id- Delete task
GET /api/leases/expiring?days=N- List leases expiring within N days (default 90, tenant-scoped)
POST /api/properties- Create propertyPATCH /api/properties/:id- Update propertyPOST /api/properties/:id/units- Create unitPATCH /api/properties/:id/units/:unitId- Update unitPOST /api/properties/:id/leases- Create leasePATCH /api/properties/:id/leases/:leaseId- Update lease
GET /api/properties/:id/financials- NOI, cap rate, cash-on-cash, occupancyGET /api/properties/:id/rent-roll- Unit-level rent roll with payment statusGET /api/properties/:id/pnl?start=YYYY-MM-DD&end=YYYY-MM-DD- Property P&L by REI category
GET /api/properties/:id/valuation- Aggregated multi-source valuation estimatesPOST /api/properties/:id/valuation/refresh- Fetch fresh estimates from all configured providersGET /api/properties/:id/valuation/history- Historical valuation timeline
POST /api/import/turbotenant- Import TurboTenant CSV ledger (requiresX-Account-IDheader)POST /api/import/wave-sync- Sync Wave transactions via OAuth
Database (required):
DATABASE_URL="postgresql://user:pass@host/dbname"Application:
NODE_ENV="development" # or "production"
MODE="standalone" # or "system" (multi-tenant)
PUBLIC_APP_BASE_URL="http://localhost:5000" # Base URL for OAuth redirectsOAuth Security (required for production):
OAUTH_STATE_SECRET="random-secret-32chars" # HMAC secret for OAuth state tokensAI & OpenAI (optional for development, required for AI features):
OPENAI_API_KEY="sk-..." # Required for AI financial adviceWave Accounting (Phase 3 - Real Integration):
WAVE_CLIENT_ID="..." # OAuth client ID from Wave Developer Portal
WAVE_CLIENT_SECRET="..." # OAuth client secret
WAVE_REDIRECT_URI="http://localhost:5000/api/integrations/wave/callback" # Optional, defaults to PUBLIC_APP_BASE_URL/api/integrations/wave/callbackStripe (Phase 3 - Real Integration):
STRIPE_SECRET_KEY="sk_test_..." # Stripe secret key (test or live)
STRIPE_PUBLISHABLE_KEY="pk_test_..." # Stripe publishable key (optional, frontend)
STRIPE_WEBHOOK_SECRET="whsec_..." # Webhook signing secret for verificationMercury Bank (Phase 3 - Real Integration via ChittyConnect):
CHITTYCONNECT_API_BASE="https://connect.chitty.cc" # ChittyConnect backend URL
CHITTYCONNECT_API_TOKEN="..." # Service authentication token
CHITTY_CONNECT_URL="https://connect.chitty.cc" # Frontend redirect URL (optional)GitHub (optional):
GITHUB_TOKEN="ghp_..." # Required for GitHub integrationProperty Valuation (Phase 4 - optional, each enables its provider):
ZILLOW_API_KEY="..." # RapidAPI key for Zillow estimates
REDFIN_API_KEY="..." # RapidAPI key for Redfin estimates
HOUSECANARY_API_KEY="..." # HouseCanary API key
ATTOM_API_KEY="..." # ATTOM Data Gateway keyCook County Assessor (Socrata) is always available — no API key required.
-
Provision Neon database:
- Create database at https://neon.tech
- Copy connection string to
DATABASE_URL
-
Initialize schema:
npm run db:push
-
Create demo user (manual step required):
INSERT INTO users (username, password, display_name, email, role) VALUES ('demo', 'hashed_password', 'Demo User', 'demo@example.com', 'user');
-
Start dev server:
npm run dev
-
Access application: http://localhost:5000
- Start dev server:
npm run dev - Navigate to http://localhost:5000
- Application auto-logs in as "demo" user
- Test dashboard, integrations, AI chat
- Check browser console for errors
- Monitor server logs in terminal
- Set valid
OPENAI_API_KEYin environment - Use
/api/ai/messageendpoint with financial data - Monitor OpenAI usage at https://platform.openai.com/usage
- Mercury Bank: Real integration via ChittyConnect (requires
CHITTYCONNECT_API_BASE+ token) - Wave Accounting: Real integration via OAuth 2.0 (requires
WAVE_CLIENT_ID+WAVE_CLIENT_SECRET) - Stripe: Real integration (requires
STRIPE_SECRET_KEY+STRIPE_WEBHOOK_SECRET) - DoorLoop, QuickBooks, Xero, Brex, Gusto: Not yet implemented — return empty data with
console.warn - Unimplemented integration functions return
{}or[], not fabricated data
Error: DATABASE_URL must be set
Solutions:
- Verify
DATABASE_URLenvironment variable is set - Test connection:
psql $DATABASE_URL -c "SELECT 1" - Check Neon dashboard for database status
- Ensure WebSocket support (
wspackage installed)
Error: EADDRINUSE: address already in use :::5000
Solution:
lsof -ti:5000 | xargs kill -9Note: Port cannot be changed (hardcoded for Replit deployment).
Error: 401 Unauthorized or 429 Rate Limit
Solutions:
- Verify
OPENAI_API_KEYis valid - Check API key has credits at https://platform.openai.com/account/billing
- Implement rate limiting or caching for AI requests
- Handle errors gracefully (see
server/lib/openai.ts:58-60)
Error: Demo user not found from /api/session
Solution: Create demo user in database:
INSERT INTO users (username, password, display_name, email, role)
VALUES ('demo', 'any_value', 'Demo User', 'demo@example.com', 'user');Error: TypeScript errors from npm run check
Common causes:
- Schema changes not reflected in types (types are auto-generated from schema)
- Missing imports from
@shared/schema - Path alias not resolving (check
tsconfig.json)
Solution: Verify schema exports match usage, run npm run check to see all errors.
- Replace demo authentication with ChittyID
- Link financial data to ChittyID for cross-platform identity
- Each user should have associated ChittyID DID
- Expose financial summary as MCP resource
- Provide AI financial advice as MCP tool
- Enable cross-service financial queries
- Log all financial transactions to audit trail
- Track AI advice and outcomes
- Compliance and forensic analysis
- Update
shared/schema.ts(single source of truth) - Run
npm run db:pushto apply changes - Test with demo user in development
- Types are auto-generated from schema (no manual type updates needed)
- Always use
storageabstraction layer (never direct Drizzle queries in routes) - Validate inputs with Zod schemas from
@shared/schema - Use consistent error handling pattern
- Return JSON responses with appropriate status codes
- Use shadcn/ui components for consistency (
@/components/ui/*) - Implement responsive design with Tailwind utilities
- Use TanStack Query for all API calls (handles caching, loading, errors)
- Optimize re-renders with proper React patterns (memo, useCallback)
OAuth Security (Phase 3 implemented):
- CSRF Protection: OAuth state tokens use HMAC-SHA256 signatures (
server/lib/oauth-state-edge.ts) - Replay Prevention: State tokens expire after 10 minutes (timestamp validation)
- Tampering Detection: State includes cryptographic signature verified server-side
- Production Requirement: Set
OAUTH_STATE_SECRETto random 32+ character string
Webhook Security:
- Stripe: Webhook signatures verified using
STRIPE_WEBHOOK_SECRET - Mercury: Service authentication via
serviceAuthmiddleware - Idempotency: All webhook events deduplicated using KV with 7-day TTL
Integration Validation (server/lib/integration-validation.ts):
- Validates required environment variables before allowing integration connections
- Returns 503 Service Unavailable if integration not properly configured
- Prevents cryptic errors from misconfigured services
General Security:
- Critical: Replace demo authentication before production (ChittyID integration pending)
- Never commit API keys (use environment variables)
- Sanitize financial data in logs (mask account numbers)
- Validate all user inputs on backend (Zod schemas)
- Use HTTPS in production (HTTP allowed for local dev only)
- Credential data stored as JSONB in database (encrypted at rest by Neon)
- Session Auth (not ChittyID): Email/password with KV-backed cookies — ChittyID SSO integration pending
- DoorLoop Sunset: DoorLoop integration is mock-only — platform is sunset for us, mock code is cleanup candidate
- No Migrations: Uses
drizzle-kit push(destructive) instead of proper migrations - Forensic Tables Not in System Schema: Forensic tables use integer IDs from
shared/schema.tsand may not exist in the production database yet - Legacy Express Code:
server/routes.ts,server/storage.ts,server/db.tsare legacy Express code kept for standalone dev reference
- ✅ Database schemas created (system.schema.ts, standalone.schema.ts)
- ✅ Seeding script for IT CAN BE LLC entities
- ✅ Mode-aware database connection
- ✅ Wrangler configuration template with KV/R2 provisioned
- ✅ SystemStorage with tenant-aware Drizzle queries (
server/storage/system.ts) - ✅ Service token auth middleware (
server/middleware/auth.ts) - ✅ Tenant-scoped middleware (
server/middleware/tenant.ts) - ✅ Hierarchy-aware tenant switcher with consolidated portfolio view (PR #52)
- ✅ All route modules migrated from Express to Hono (22 route files)
- ✅ Edge-compatible: Web Crypto API, Neon HTTP driver, no Node.js dependencies
- ✅ Per-prefix middleware registration (avoids blocking public routes)
- ✅ Deployed to Cloudflare Workers at
finance.chitty.cc - ✅ Dev server migrated to Hono (
server/dev.ts), 15 legacy lib modules deleted (PR #81)
- ✅ Mercury Bank via ChittyConnect backend (multi-account support)
- ✅ Registered with ChittyRegistry (
did:chitty:REG-XE6835, PR #49) - ✅ Log to ChittyChronicle (audit trail for classification + COA mutations, PR #92)
- ✅ JWT session auth behind ChittyAuth (PR #96)
- ⏳ Integrate with ChittyConnect MCP
- ⏳ Issue ChittyCert certificates for secure connections
- ✅ Wave Accounting - OAuth 2.0 flow + GraphQL API (
server/lib/wave-api.ts) - ✅ Stripe - Payment processing, checkout, webhooks (
server/lib/stripe.ts) - ✅ Mercury Bank - Multi-account via ChittyConnect (static egress IP)
- ✅ Mercury Native Webhooks - Per-tenant HMAC-SHA256 verification, 7 registrations (PR #99)
- ✅ OAuth Security - CSRF-protected state tokens (
server/lib/oauth-state-edge.ts) - ✅ Integration Monitoring - Config validation endpoint (
/api/integrations/status) - ✅ Webhook Infrastructure - Idempotent event processing (KV-based dedup, 7-day TTL)
DoorLoop- Sunset, all code removed (PR #78, -35K lines)
- ✅ Database-backed Chart of Accounts with 80 REI accounts seeded (PR #86)
- ✅ L0→L4 trust-path enforcement with concurrency-safe reconciled lock (PR #86)
- ✅ AI-assisted classification via GPT-4o-mini with defense-in-depth fallbacks (PR #87)
- ✅ Classification review UI with bulk-accept guardrails (PR #88)
- ✅ Admin COA editor with code-range validation (PR #89)
- ✅ Mercury webhook real-time classification at ingest (PR #90)
- ✅ Classification enhancements — bulk-accept opt-out, L3 audit trail, tenant settings (PR #94)
- ✅ Schedule E tax workspace + line summary (PRs #91, #96)
- ✅ 246+ tests passing
- ✅
property_valuationstable in system schema - ✅ Property/unit/lease CRUD in SystemStorage
- ✅ Financial aggregation methods (NOI, cap rate, cash-on-cash, occupancy, rent roll, P&L)
- ✅ Property mutation + financial endpoints (10 new routes in
properties.ts) - ✅ Multi-source valuation providers (Zillow, Redfin, HouseCanary, ATTOM, County)
- ✅ Confidence-weighted valuation aggregation + valuation routes
- ✅ TurboTenant CSV import with deduplication
- ✅ Mercury CSV import with account auto-resolution (PR #101)
- ✅ HD Pro CSV import (3K items, 24 job name normalizations) (PR #93)
- ✅ Amazon Business import (2K items, returns dedup, payment card tracking) (PR #93)
- ✅ Wave sync import endpoint
- ✅ Frontend property management UI (Add/Edit property, units, leases, 5-tab detail panel)
- ✅ Lease expiration notifications (cron trigger + API + dashboard widget, PR #70)
- ✅ Replace demo auth with ChittyID SSO via OAuth 2.0 PKCE (PR #72)
- ✅ Expose financial data as MCP resources (PR #92)
- ✅ Log to ChittyChronicle (PR #92)
- ✅ ChittyDiscovery self-registration + heartbeat (PR #79)
- ✅ Fractal scope projection via shared
@chittyos/schema/scope-projector(PR #103) - ✅ Governance workflow gates (PR #95)
- ⏳ Issue ChittyCert certificates for secure connections
- ⏳ Integrate with ChittyConnect MCP
- ✅ Consolidated reporting across all entities (
server/lib/consolidated-reporting.ts) - ✅ Multi-currency schema support (ISO 4217, PR #53)
- ✅ Inter-company allocation automation engine (PR #75) + management UI (PR #80)
- ✅ Transaction export CSV/OFX/QFX (PR #76)
- ✅ Complete ledger audit coverage across all financial mutations (PR #77)
- ✅ Cloudflare Email Service integration (PR #102)
- ✅ Wrangler config TOML → JSONC (PR #104)
- ⏳ Tax optimization and reporting (Schedule E data classified, export page shipped)
- ⏳ Advanced AI forecasting (beyond GPT-4o)
- ⏳ Mobile app (React Native)
- Cooperative marketplace for small furnished rental operators (under 10 units)
- Own distribution (not dependent on Airbnb/VRBO APIs)
- DRL (Distributed Reputation Ledger) for focal trust scoring
- Channel manager integration via Hospitable or similar for optional cross-posting
- Guest-facing search + booking frontend
- Operator onboarding + SaaS billing
- Local data partnerships with trust-scored vendors
- ChittyOS Ecosystem:
/Users/nb/Projects/development/CLAUDE.md - Mercury API: https://docs.mercury.com
- Wave API: https://developer.waveapps.com
- Stripe API: https://stripe.com/docs/api
- Drizzle ORM: https://orm.drizzle.team
- OpenAI API: https://platform.openai.com/docs