# 07 — KEY FILES & FUNCTIONS Generated 2026-07-05 · prod arm64-5ee0ae12002f · regenerated after wipe > snapshot 2026-07-05 · regenerated live. Where things live — point workers here instead of grepping. Paths relative to `note-clone/`. ## Core / infra | File | Purpose | |---|---| | `src/lib/prisma.ts` | Prisma client singleton. **NAMED export**: `export const prisma = globalForPrisma.prisma || new PrismaClient()` — import `{ prisma }`, not default. Global cache off-prod only. | | `src/auth.ts` | NextAuth v5 root (`auth`, `handlers`, `signIn`). Credentials provider `authorize`: Zod creds → `verifyPassword` → optional TOTP/recovery → `createUserSession`. Suspension check via raw `SELECT "isSuspended"` (drift-tolerant P2009/P2022/42703). Supports offline identity + local dev bypass. | | `prisma/schema.prisma` | 128 models (see 04). | ## Auth / authz | File | Purpose | |---|---| | `src/lib/auth/rbac.ts` | `getSession()`, `isAdmin(email)` (ADMIN_EMAILS allowlist), `requireAdmin()` (throws/401 gate). | | `src/lib/auth/password.ts` | bcrypt hash/verify. | | `src/lib/auth/2fa.ts` | TOTP + recovery codes (otplib). | | `src/lib/auth/sessions.ts` | `createUserSession` / `ensureSessionActive` (server-side UserSession records). | | `src/lib/auth/linking.ts` | account-linking tokens (`verifyLinkingToken`). | | `src/lib/auth/devBypass.ts` | `isLocalDevLoginBypassAllowed()` — **verify not reachable in prod**. | | `src/lib/auth/offlineIdentity.ts` | offline/local identity fallback. | | `src/middleware/rateLimit.ts` | `consumeRateLimit` per-route rate limit (in-app helper — NOT Next.js middleware; there is no global `middleware.ts`). | | `src/middleware/billingGuard.ts`, `errorHandler.ts` | in-app billing/error guards. | ## Economy / billing (money-authoritative) | File | Purpose | |---|---| | `src/lib/economy/economyService.ts` | server-authoritative economy service — mint/spend against `Transaction` (idempotent on `@@unique([userId, reference])`). Core of the SEC-ECONOMY server-authoritative epic. | | `src/lib/economy/earnPolicy.ts` / `earningRules.ts` | what earns are allowed + amounts (server-computed, not client-trusted). | | `src/lib/economy/outcomeCredit.ts` | wires game outcomes (boss-fight/arcade/deck resolve) → server-outcome → credit. | | `src/lib/economy/memoryStore.ts` / `types.ts` | in-memory helpers + types. | | `src/lib/gamification/rewardGuard.ts` | reward guard — validates/limits reward grants before they hit the ledger (anti reward-abuse; ties to SEC-0261/0262/0281). | | `src/lib/billing/tierLimits.ts` | tier gating (free/pro/team) + quotas. | | `src/lib/billing/features.ts`, `videoFeatures.ts`, `gameFeatures.ts`, `personalSourceQuota.ts` | feature gates / quotas. | | `src/lib/stripe/billingService.ts`, `stripeClient.ts`, `pricing.ts` | Stripe subscription lifecycle + client. | ## RAG / vector | File | Purpose | |---|---| | `src/lib/rag/vectorStore.ts` | pgvector store: `addDocuments`, `similaritySearch` (cosine `<=>`), `hybridSearch` (vector+FTS/RRF), `similaritySearchBestChunkPerSource`, `getOrderedChunksForSources`. Raw SQL against `DocumentChunk`. | | `src/lib/rag/embeddings.ts` | OpenAI embeddings 1536-d (lazy SDK, `MOCK_OPENAI`, `generateEmbeddingsBatch`). | | `src/lib/rag/chunking.ts` / `textAnchors.ts` | `chunkTextWithOffsets` + line/paragraph anchors. | | `src/lib/rag/accessScope.ts` | tenant-scoped source access (`userId`/sourceIds filter) — the multi-tenant isolation seam. | | `src/lib/documents/processDocumentCore.ts` | server-only RAG ingestion core (`processDocument`); called by routes + `actions.ts` wrapper. | ## Ingest / media / video | File | Purpose | |---|---| | `src/lib/ingest/fileIngestor.ts` | ingest entry: sanitize→dedupe→corpus route→extract→write. | | `src/lib/ingest/extractors/{pdf,office,html,text,image,audio,video,archive}.ts` | per-type extraction (`index.ts` dispatch). | | `src/lib/videoContext/{runtime,transcription,scenes,evidence,frameHydration,assetStorage}.ts` | video→doc pipeline. | | `src/lib/videoContext/cloud/finalize.ts` | `verifyCloudWebhookSignature` for video ingest callback. | ## AI / tools | File | Purpose | |---|---| | `src/lib/ai/router.ts` | `routeRequest` — complexity+semantic routing to provider/model. | | `src/lib/ai/providers/{openai,anthropic,google,xai,openrouter}.ts` | provider adapters (`base.ts` = ProviderId/Message). | | `src/lib/ai/models/registry.ts` | model reference resolution (capabilities/availability/picker). | | `src/lib/ai/{byok,serverApiKeys,budgets,pricing,cost}.ts` | BYOK, server keys, budgets/cost (per-user quota gate = SEC-0309). | | `src/lib/ai/tools/*.ts` | ~60 agent tools (createNote, makeOutboundCall, generatePodcast, factCheck, …). | ## Telephony / embed (zoned) | File | Purpose | |---|---| | `src/lib/telephony/**` | SIP/PSTN runtime (Codex zone): `sipProvisioning.ts`, `channels/pstnCall/{telnyxClient,auth}.ts` (`timingSafeEqual`/`createHmac`), `outbound/orchestrator.ts`, guards (`budgetGuard,quietHoursGuard,loopGuard,channelGuard`), `consentLog.ts`. | | `src/lib/embed/{service,guard,publicGuardrails,origin,publicHost}.ts` | public/embeddable widget: origin/CORS + `createEmbedGuardToken`/`parseEmbedGuardToken`. | | `src/lib/messaging/telegramAccess.ts` | `verifyTelegramScopedAccessCode` (telegram webhook). | ## Entity resolution / cron | File | Purpose | |---|---| | `src/app/api/cron/entity-resolution/route.ts` | scheduled NER / entity-merge job (CRON_SECRET). Owner-spend decision governs NER-in-prod. | | `src/app/api/cron/{process-tasks,topic-stats,watchdog,process-scheduled-posts,update-engagement,process-messages}/route.ts` | scheduler endpoints (CRON_SECRET gate; `process-messages` history = SEC-0252). | ## SSRF / security helpers | File | Purpose | |---|---| | `src/lib/**/assertPublicHttpUrl` (SSRF guard) | blocks loopback/link-local/169.254/ULA + `redirect:manual` + DNS re-check. Adoption sweep = SEC-0294. | | `src/lib/legal/syntheticFinalDocs.ts` | ToS/Privacy generator — currently **synthetic/not-for-publication** (AUTH-0812 flips to real). |