Skip to main content

Knowledge > System Architecture > Infrastructure

Infrastructure Reference

Canonical reference for all ChurchWiseAI hosting, domains, external services, environment variables, cron jobs, voice agent deployment, email systems, monitoring, and security controls. This document describes what infrastructure exists and how it connects -- never credentials or secrets.

Multi-Codebase Deployment Architecture


1. Vercel Deployments

All three active codebases deploy to Vercel via GitHub integration. Pushes to the deploy branch trigger automatic production deployments. Feature branches get Vercel preview deploys.

PropertyCodebaseDeploy BranchPort (Local)URLVercel Account
ChurchWiseAIchurchwiseai-web/main3002churchwiseai.comchurchwiseai-5386 (john@churchwiseai.com)
PewSearchpewsearch/web/master3000pewsearch.com(same org)
ITWsermon-illustrations/master3000illustratetheword.com(same org)

Deploy Flow

feature branch → push → Vercel preview deploy → PR review

merge to main/master

Vercel auto production deploy

Caching / ISR Strategy

PropertyRoute PatternCacheSWR
PewSearch/directory/*s-maxage=3600stale-while-revalidate=86400
PewSearch/denominations/*s-maxage=3600stale-while-revalidate=86400
PewSearch/s/* (Pro Website)s-maxage=3600, ISR revalidate=3600stale-while-revalidate=86400
PewSearch/claim/*, /admin/*no-store--
CWA/admin/*no-store--

Vercel CLI

Logged in and ready. Key commands:

  • vercel env ls -- list env vars for a project
  • vercel env pull -- sync production env vars to .env.local
  • vercel --prod -- trigger production deployment
  • vercel logs --tail -- stream deployment logs
  • echo "value" | vercel env add VAR_NAME production -- set env var (pipe bypasses interactive prompt)

2. Domain Architecture

Five domains serve the three active codebases, with two domains using hostname-based middleware rewrites to serve separate brands from a single codebase.

DomainDNS ProviderCodebasePurpose
churchwiseai.comPorkbunchurchwiseai-web/AI products -- voice agent, chatbot, admin dashboard
sermonwise.aiPorkbunchurchwiseai-web/ (hostname rewrite to /sermons)AI sermon preparation tools
sharewiseai.comPorkbunchurchwiseai-web/ (hostname rewrite to /social)AI social media SaaS (Coming Soon)
pewsearch.comVercel DNSpewsearch/web/Church directory (218K+ visible listings)
illustratetheword.comPorkbunsermon-illustrations/Sermon illustration library

Middleware Rewrites

ChurchWiseAI middleware (churchwiseai-web/src/middleware.ts):

  • sermonwise.ai -- When the host header contains sermonwise.ai, all paths are rewritten to /sermons/*. For example, sermonwise.ai/titles becomes /sermons/titles internally. Static assets, API routes, and auth paths are excluded from rewriting.
  • sharewiseai.com -- Same pattern: sharewiseai.com/pricing rewrites to /social/pricing. Login redirects adapt based on hostname.
  • Supabase PKCE -- Catches ?code= query params on any path and forwards them to /auth/callback with the correct next destination based on hostname.
  • Cookie-based session auth -- Validates cw_session cookie via HMAC-SHA256 hash against church_admin_sessions table. Injects x-church-id, x-identity-id, x-identity-role headers on success.
  • Legacy token passthrough -- /admin/[token] URL paths and ?token= query params pass through for backward compatibility.

PewSearch middleware (pewsearch/web/src/middleware.ts):

  • Subdomain routing -- {slug}.pewsearch.com rewrites to /s/{slug} for Pro Website vanity URLs. Sets x-is-subdomain header so the layout can hide site chrome.
  • Reserved subdomains (www, api, admin, app) and localhost are excluded.

Future Domains (Acquired, Not Deployed)

DomainVerticalPriority
funeralwiseai.com / memorialwiseai.comFuneral homes#1
ShopWiseAI (TBD)Auto repair shops#2
veterinarywiseai.com / VetWiseAIVeterinary clinics#3
LegalWiseAI (TBD)Small law firms#4

3. External Services Matrix

All external services used across the portfolio, ordered by criticality.

ServicePurposeUsed ByAuth MethodPriority
StripePayments, subscriptions, checkout, billing portalAll 3API key (secret + publishable)P0
SupabaseDatabase + Auth + Storage (ONE shared instance, no staging)All 3Service role key + anon keyP0
VercelHosting, CDN, serverless functions, cron jobsAll 3GitHub OAuthP0
LiveKitVoice agent SIP gateway + real-time audio session managementchurchwiseai-webAPI key + secretP0
CartesiaTTS (Cartesia Sonic) for voice calls via livekit-plugins-cartesiachurchwiseai-webAPI keyP1
TwilioPhone numbers, SMS sending, inbound SMS webhookschurchwiseai-web, pewsearchAccount SID + auth tokenP0
ResendTransactional email (magic links, welcome, alerts, notifications)All 3API keyP1
Anthropic (Claude)Chatbot primary LLM (Haiku 4.5), Care Agent, batch generation via CLIAllAPI key + CLI ($200/mo Max plan)P1
OpenAIEmbeddings (text-embedding-3-small) + chatbot LLM fallback (gpt-4o-mini)churchwiseai-webAPI keyP1
Google AI (Gemini)Voice agent primary LLM (Gemini 2.5 Flash)churchwiseai-webAPI keyP1
MailerLiteSubscriber CRM, newsletter managementAll 3JWT keyP2
Google APIsOAuth (social), Calendar, Drive (knowledge sync), Placeschurchwiseai-webClient ID + secretP2
MetaFacebook/Instagram OAuth for ShareWiseAIchurchwiseai-webApp ID + secretP2
LinkedInOAuth for ShareWiseAIchurchwiseai-webClient ID + secretP2
X (Twitter)OAuth for ShareWiseAIchurchwiseai-webClient ID + secretP2
TikTokOAuth for ShareWiseAIchurchwiseai-webClient key + secretP2
PinterestOAuth for ShareWiseAIchurchwiseai-webApp ID + secretP2
PostHogProduct analytics, event trackingAll 3API key (public)P3
Cloudflare TurnstileCAPTCHA on public formschurchwiseai-webSite key + secret keyP3
Cal.comBooking/scheduling embedschurchwiseai-webEmbed (no API key)P3
OutscraperChurch data scraping (Google Maps)PewSearchAPI keyP3
TMDBMovie data for sermon illustrationsITWAPI keyP3
UnsplashPhoto library for illustrationsITWAccess keyP3
ElevenLabsTTS (legacy/fallback, mostly unused)churchwiseai-webAPI keyP3
DeepgramSTT for voice agent calls (via livekit-plugins-deepgram)churchwiseai-webAPI keyP1

Stripe Account Details

  • Account: churchwiseai@gmail.com (ONE account, TWO modes)
  • Live mode ID: acct_1SSPz2FaoK5IPzNo
  • Test mode ID: acct_1SSPzDF8WTm3d6SH
  • 24 active products in live mode (post 2026-05-04 VetWiseAI launch); test mode mirrors with a slightly different count due to consolidated annual products (see knowledge/data/pricing.yaml)
  • Test mode is CLI default; live mode requires --api-key flag with full sk_live_ key
  • See C:\dev\PRICING.md for all product/price IDs

Supabase Instance

  • Project ID: wrwkszmobuhvcfjipasi
  • URL: https://wrwkszmobuhvcfjipasi.supabase.co
  • Single instance serves both development and production -- no staging database
  • 327K records in unified_rag_content (irreplaceable)
  • 218K+ visible church listings in churches

4. Environment Variables

All env var names grouped by service. Values are never stored in this document.

Supabase

VariableScopeUsed By
NEXT_PUBLIC_SUPABASE_URLPublicAll 3
NEXT_PUBLIC_SUPABASE_ANON_KEYPublicAll 3
SUPABASE_SERVICE_ROLE_KEYServerAll 3

Stripe

VariableScopeUsed By
STRIPE_SECRET_KEYServerAll 3
STRIPE_WEBHOOK_SECRETServerAll 3
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEYPublicAll 3
STRIPE_PREMIUM_MONTHLY_PRICE_IDServerCWA, PewSearch
STRIPE_PRO_WEBSITE_MONTHLY_PRICE_IDServerPewSearch
STRIPE_PRICE_STARTER_CHATServerCWA
STRIPE_PRICE_STARTER_CHAT_ANNUALServerCWA
STRIPE_PRICE_PRO_CHATServerCWA
STRIPE_PRICE_PRO_CHAT_ANNUALServerCWA
STRIPE_PRICE_SUITE_CHATServerCWA
STRIPE_PRICE_SUITE_CHAT_ANNUALServerCWA
STRIPE_PRICE_STARTER_VOICEServerCWA
STRIPE_PRICE_PRO_VOICEServerCWA
STRIPE_PRICE_STARTER_BOTHServerCWA
STRIPE_PRICE_PRO_BOTHServerCWA
STRIPE_PRICE_SUITE_BOTHServerCWA
STRIPE_PRICE_AI_STARTER_KITServerCWA
STRIPE_SERMON_PRO_MONTHLY_PRICE_IDServerCWA
STRIPE_SERMON_PRO_ANNUAL_PRICE_IDServerCWA
STRIPE_SOCIAL_PRO_PRICE_IDServerCWA
STRIPE_SOCIAL_BUSINESS_PRICE_IDServerCWA
STRIPE_SOCIAL_AGENCY_PRICE_IDServerCWA
STRIPE_PREMIUM_ANNUAL_PRICE_IDServerITW

LLM / AI

VariableScopeUsed By
OPENAI_API_KEYServerCWA, PewSearch, ITW
ANTHROPIC_API_KEYServerCWA, ITW
GEMINI_API_KEYServerCWA

Voice / Telephony

VariableScopeUsed By
LIVEKIT_URLRailwayCWA voice agent worker
LIVEKIT_API_KEYRailwayCWA voice agent worker
LIVEKIT_API_SECRETRailwayCWA voice agent worker
CARTESIA_API_KEYRailwayCWA voice agent TTS
CARTESIA_FEMALE_VOICE_IDRailwayCWA voice agent TTS
CARTESIA_MALE_VOICE_IDRailwayCWA voice agent TTS
DEEPGRAM_API_KEYRailwayCWA voice agent STT
TWILIO_ACCOUNT_SIDServerCWA, PewSearch
TWILIO_AUTH_TOKENServerCWA, PewSearch
TWILIO_FROM_NUMBERServerCWA, PewSearch
VOICE_AGENT_WS_URLServerCWA (legacy)
ELEVENLABS_API_KEYServerCWA (legacy fallback)
TTS_PROVIDERServerCWA

Email

VariableScopeUsed By
RESEND_API_KEYServerAll 3
ADMIN_EMAILServerCWA, PewSearch
ADMIN_PHONEServerCWA, PewSearch
MAILERLITE_API_KEYServerCWA, ITW
MAILERLITE_PROXY_SECRETServerAll 3
MAILERLITE_PROXY_URLServerPewSearch, ITW
MAILERLITE_WEBHOOK_SECRETServerCWA

Social OAuth (ShareWiseAI)

VariableScopeUsed By
META_APP_IDServerCWA
META_APP_SECRETServerCWA
META_WEBHOOK_VERIFY_TOKENServerCWA
GOOGLE_CLIENT_IDServerCWA
GOOGLE_CLIENT_SECRETServerCWA
GOOGLE_REDIRECT_URIServerCWA
LINKEDIN_CLIENT_IDServerCWA
LINKEDIN_CLIENT_SECRETServerCWA
X_CLIENT_IDServerCWA
X_CLIENT_SECRETServerCWA
TIKTOK_CLIENT_KEYServerCWA
TIKTOK_CLIENT_SECRETServerCWA
PINTEREST_APP_IDServerCWA
PINTEREST_APP_SECRETServerCWA
SOCIAL_OAUTH_STATE_SECRETServerCWA
SOCIAL_TOKEN_ENCRYPTION_KEYServerCWA

Analytics & Security

VariableScopeUsed By
NEXT_PUBLIC_POSTHOG_KEYPublicCWA
NEXT_PUBLIC_POSTHOG_HOSTPublicCWA
NEXT_PUBLIC_POSTHOG_API_KEYPublicPewSearch, ITW
NEXT_PUBLIC_TURNSTILE_SITE_KEYPublicCWA
TURNSTILE_SECRET_KEYServerCWA

Application Secrets

VariableScopeUsed By
APP_SECRETServerCWA (HMAC session hashing)
ADMIN_SECRETServerCWA, PewSearch
CRON_SECRETServerCWA (Vercel cron auth)
INTERNAL_API_KEYServerCWA
INTERNAL_SOCIAL_KEYServerCWA
DOCS_ADMIN_KEYServerCWA
NEXT_PUBLIC_DOCS_ADMIN_KEYPublicCWA
OPS_ALERT_EMAILServerCWA
OPS_INGEST_KEYServerCWA
STARTER_KIT_DOWNLOAD_SECRETServerCWA
FOUNDER_TOKENServerCWA
GITHUB_TOKENServerCWA (knowledge sync)

External Data

VariableScopeUsed By
GOOGLE_PLACES_API_KEYServerCWA, PewSearch
PLANNING_CENTER_APIServerPewSearch
TMDB_API_KEYServerITW
UNSPLASH_ACCESS_KEYServerITW

Site Configuration

VariableScopeUsed By
NEXT_PUBLIC_SITE_URLPublicAll 3
NEXT_PUBLIC_SITE_NAMEPublicPewSearch, ITW
API_URLServerCWA

Test-Only

VariableScopeUsed By
SERMON_TEST_EMAILServerCWA (dev)
SERMON_TEST_PASSWORDServerCWA (dev)

5. Cron Jobs

Defined in churchwiseai-web/vercel.json. All run on Vercel Cron and are authenticated via CRON_SECRET bearer token.

ScheduleRoutePurpose
*/15 * * * * (every 15 min)/api/ops/collectCollects quota/health checks from Twilio, Resend, and Supabase. Records snapshots to ops_quota_snapshots. Fires P0 alerts for critical conditions (low balance, connection pool, rate limits).
0 7 * * * (daily at 7:00 UTC)/api/cron/daily-auditSecurity and operational audit. Checks pending founder actions, active customer count, recent voice calls, error rates, and subscription health. Generates WatchTower alerts.
30 7 * * * (daily at 7:30 UTC)/api/founder/sync-knowledgeSyncs YAML/Markdown files from the knowledge/ repo to Google Drive as formatted Google Docs. Covers pricing, features, products, policies, vision, and strategy documents.
30 8 * * * (daily at 8:30 UTC)/api/cron/knowledge-checkPricing integrity and knowledge drift check. Verifies pricing.ts tiers match canonical YAML, product_knowledge has required entries, Stripe price env vars are present. Creates P0 founder action item and sends email alert on drift.

6. Voice Agent Deployment

The voice agent runs on LiveKit Cloud + Railway, not on Vercel or any Cartesia-managed infrastructure.

FieldValue
TechnologyLiveKit Agents SDK (Python 3.11+)
SDK Versionlivekit-agents~=1.5
Code locationchurchwiseai-web/voice-agent-livekit/
Deploy commandPush to GitHub (Railway auto-deploys)
Deploy environmentRailway (agent worker) + LiveKit Cloud (SIP gateway)
ArchitectureMulti-tenant: ONE agent worker serves ALL churches
Routingmain.py routes by sip.trunkPhoneNumber from LiveKit room
Primary LLMGemini 2.5 Flash
Fallback / Care LLMClaude Haiku 4.5
STTDeepgram (via livekit-plugins-deepgram)
TTSCartesia Sonic (via livekit-plugins-cartesia)

Key Files

All files are under churchwiseai-web/voice-agent-livekit/.

FilePurpose
main.pyEntry point -- routes calls by sip.trunkPhoneNumber
livekit.tomlLiveKit project config (project URL, agent registration)
session.pySupabase client, call lifecycle, caching, product knowledge loading
turn_processor.pyModeration, noise filtering, farewell detection
verticals/church/agents.pyCoordinator + Care agent builders
verticals/church/prompts.pyPer-church prompt templates
verticals/church/tools.pyPrayer requests, callbacks, visitor capture
verticals/sales/agents.pySales + Demo agent builders
core/Shared tools, RAG, notifications, prompt fragments

New Church Setup

  1. Insert row in church_voice_agents table with church config
  2. Run voice-agent-livekit/scripts/setup_sip.py to configure the Twilio → LiveKit SIP trunk for the church phone number
  3. No redeploy needed -- the multi-tenant agent picks up new churches at call time

Legacy (Do Not Modify)

  • churchwiseai-web/voice-agent/ -- Old Node.js/Railway voice agent. Left in repo for reference only.
  • churchwiseai-web/voice-agent-line/ -- Previous Cartesia LINE SDK agent (replaced by voice-agent-livekit/ in March 2026). Left in repo for reference only.

7. Email Infrastructure

Transactional Email (Resend)

All transactional email is sent via Resend. Each property uses its own sender domain.

PropertyFrom AddressEmail Types
ChurchWiseAIhello@churchwiseai.comMagic links, welcome emails, onboarding, contact confirmations
ChurchWiseAI (Alerts)alerts@churchwiseai.comWatchTower operational alerts, error notifications
PewSearchhello@pewsearch.comMagic links, welcome emails, claim notifications, care broadcasts
ITWhello@illustratetheword.comAccount emails, subscription notifications
ShareWiseAIhello@churchwiseai.com (shared sender)Social post notifications

Subscriber CRM (MailerLite)

  • Account: JWT key stored in CWA .env.local
  • Access pattern: PewSearch and ITW proxy through CWA's MailerLite API endpoint (MAILERLITE_PROXY_URL)
  • Features used: Subscriber management, newsletter campaigns, audience segmentation (subscriber CRM only — lifecycle automation is handled by the Resend lifecycle email system)
  • REST API fully accessible to agents -- never send the founder to the MailerLite dashboard

8. Monitoring and Alerting

Layers

LayerToolWhat it covers
Deployment logsVercelRequest logs, function errors, build output. Access: vercel logs --tail
Product analyticsPostHogPage views, event tracking, funnels, session recording
Operational health/api/ops/collect cronTwilio balance, Resend usage, Supabase health. Runs every 15 minutes. Records to ops_quota_snapshots table
Daily audit/api/cron/daily-audit cronFounder actions, customer count, voice call volume, error rates, subscription health
Error reportingops-reporter.tsClassifies errors as P0/P1 by route and message patterns. Records to ops_error_reports table with deduplication (fingerprint hash)
Founder dashboard/founder/[token]Executive dashboard with pending actions, system health, Drive sync status
WatchTower alertsDaily audit cronEmail/SMS alerts for P0 conditions (quota exhaustion, payment failures, outages)

Error Severity Classification

  • P0 routes: /api/stripe/, /api/onboard/, /api/chatbot/stream, /api/admin/ -- any error on these paths is P0
  • P0 keywords: "quota", "rate limit", "connection pool" in error messages
  • P1: Everything else

9. Security Summary

Transport

  • HTTPS everywhere -- Vercel provisions and auto-renews SSL certificates for all domains
  • HSTS enabled with max-age=63072000; includeSubDomains; preload

Authentication

PropertyAuth MethodDetails
CWA AdminCookie-based sessions + legacy URL tokenscw_session cookie, HMAC-SHA256 hashed, validated against church_admin_sessions table
CWA SermonWiseSupabase AuthPKCE flow, middleware redirects unauthenticated users
CWA ShareWiseAISupabase AuthSame PKCE pattern as SermonWise
PewSearch AdminToken-based (URL path)UUID token in URL, validated against premium_churches.admin_token or church_team_members.access_token
ITWSupabase AuthStandard Supabase Auth flow

Database Security

  • Row Level Security (RLS) enabled on Supabase tables
  • Service role key used server-side only (bypasses RLS for admin mutations)
  • Anon key used for client-side queries (subject to RLS policies)
  • RBAC with 9 roles: admin, office_admin, prayer_team, care_team, treasurer, volunteer_coordinator, worship_leader, spiritual_leader, care_leader
  • Pastoral data (confidential prayers, callback reasons) redacted for non-pastoral roles

Request Security

  • CSRF validation on mutation endpoints (src/lib/csrf.ts -- origin checking)
  • Rate limiting on public-facing endpoints (src/lib/rate-limit.ts -- in-memory)
  • Webhook signature verification for Stripe (stripe-signature header) and Twilio
  • CRON_SECRET bearer token on all Vercel cron endpoints

Content Security Policy

Applied globally via next.config.ts with allowlists for: Stripe (scripts, frames, connect), Supabase (connect, WebSocket), PostHog (scripts, connect), YouTube/Vimeo (frames), Cal.com (scripts, frames), Cloudflare Turnstile (scripts, frames), Google (fonts, connect, frames), social platform APIs (connect). The /embed route uses a relaxed frame-ancestors * policy since it is loaded inside church website iframes.

Headers

HeaderValue
X-Frame-OptionsDENY (except /embed)
X-Content-Type-Optionsnosniff
Referrer-Policystrict-origin-when-cross-origin
Strict-Transport-Securitymax-age=63072000; includeSubDomains; preload
Permissions-Policycamera=(), microphone=(), geolocation=(), interest-cohort=()
X-DNS-Prefetch-Controlon
X-Robots-Tagnoindex (admin pages only)

See Also

  • Parent: System Architecture Overview -- portfolio overview, codebase ownership, tech stack summary
  • Related: Database Schema -- table ownership, column reference, RPC functions
  • Pricing: C:\dev\PRICING.md -- all Stripe product/price IDs, billing rules, checkout flows
  • Operations: Operations -- day-to-day procedures, runbooks
  • Decision Log: C:\dev\DECISION_LOG.md -- infrastructure decisions with rationale