juanjaragavi/traffic-genius
GitHub: juanjaragavi/traffic-genius
为 TopNetworks 构建的 GCP 原生安全仪表板,整合无效流量检测与 Cloud Armor 规则管理。
Stars: 0 | Forks: 0
# TrafficGenius
为 [TopNetworks, Inc.](https://topnetworks.co) 提供的 **反 Bot 安全仪表板**
集中式安全分析、IVT(无效流量)检测和 Google Cloud Armor 规则管理。专为 TopNetworks 安全运营团队构建。




## 目录
- [功能特性](#features)
- [技术栈](#tech-stack)
- [快速开始](#quick-start)
- [环境变量](#environment-variables)
- [项目结构](#project-structure)
- [架构](#architecture)
- [仪表板页面](#dashboard-pages)
- [API 路由](#api-routes)
- [数据库模式](#database-schema)
- [GCP 集成](#gcp-integration)
- [身份验证](#authentication)
- [样式与品牌](#styling--brand)
- [脚本](#scripts)
- [部署](#deployment)
- [贡献指南](#contributing)
## 功能特性
- **安全概览仪表板** — 实时 KPI 卡片,展示总请求数、拦截率、唯一 IP 数、活跃策略和顶级攻击向量
- **流量分析** — 每小时趋势图、国家/地区分布表以及已拦截/已放行流量可视化
- **IVT 检测** — 基于 BigQuery 的无效流量分类(GIVT、SIVT、可疑、干净),附带置信度评分
- **Cloud Armor 管理** — 对 Google Cloud Armor 安全策略和规则(允许、拒绝、限速、节流)进行完整 CRUD 操作
- **审计追踪** — 每一次 Cloud Armor 变更都会记录用户、操作、资源、详情和 IP 地址
- **用户设置** — 时区偏好、刷新间隔、告警配置和登出
- **域名限制验证** — Google OAuth 仅限 `@topnetworks.co` 和 `@topfinanzas.com` 邮箱域名
## 技术栈
| 层级 | 技术 |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 框架 | [Next.js 16](https://nextjs.org/) (App Router, React Server Components) |
| 语言 | [TypeScript 5.9](https://www.typescriptlang.org/) (strict mode) |
| UI | [React 19](https://react.dev/), [Tailwind CSS 4](https://tailwindcss.com/), [shadcn/ui](https://ui.shadcn.com/), [Framer Motion](https://www.framer.com/motion/) |
| 图表 | [Recharts 3](https://recharts.org/) |
| 图标 | [Lucide React](https://lucide.dev/) |
| 验证 | [NextAuth.js v5](https://authjs.dev/) (beta.30) + Google OAuth |
| 数据库 | PostgreSQL via [`pg`](https://node-postgres.com/) (Cloud SQL) |
| 分析 | [BigQuery](https://cloud.google.com/bigquery) (`@google-cloud/bigquery`) |
| 安全 | [Cloud Armor](https://cloud.google.com/armor) (`@google-cloud/compute`) |
| 日志 | [Pino 10](https://getpino.io/) + [Cloud Logging](https://cloud.google.com/logging) + [Cloud Error Reporting](https://cloud.google.com/error-reporting) |
| 字体 | [Poppins](https://fonts.google.com/specimen/Poppins) (weights 300–700) |
## 快速开始
### 前置条件
- **Node.js** ≥ 18
- **npm** ≥ 9
- **PostgreSQL**(本地或通过代理连接 Cloud SQL)
- **GCP Service Account**,需具备 BigQuery、Compute、Logging 和 Error Reporting 权限
### 安装
```
# 克隆 repository
git clone https://github.com/juanjaragavi/traffic-genius.git
cd traffic-genius
# 安装依赖
npm install
# 设置环境
cp .env.example .env.local
# 填写所有必需的凭证(参见下方的 Environment Variables)
# 初始化数据库
psql -d traffic_genius -f scripts/001-create-auth-tables.sql
psql -d traffic_genius -f scripts/002-create-app-tables.sql
# 启动开发服务器
npm run dev
```
应用运行在 。
## 环境变量
根据 `.env.example` 创建 `.env.local` 文件。所有必需变量:
| 分组 | 变量名 | 描述 |
| --------------- | -------------------------------- | ------------------------------------------------------------ |
| **Auth** | `AUTH_SECRET` | NextAuth.js 密钥(使用 `openssl rand -base64 32` 生成) |
| | `AUTH_GOOGLE_ID` | Google OAuth 客户端 ID |
| | `AUTH_GOOGLE_SECRET` | Google OAuth 客户端密钥 |
| | `AUTH_URL` | NextAuth 回调的应用 URL (`http://localhost:3080`) |
| **Database** | `DATABASE_URL` | PostgreSQL 连接字符串 |
| **GCP** | `GCP_PROJECT_ID` | Google Cloud 项目 ID |
| | `GOOGLE_APPLICATION_CREDENTIALS` | GCP 服务账号 JSON 密钥路径 |
| **BigQuery** | `BIGQUERY_DATASET` | BigQuery 数据集名称 (`traffic_security_logs`) |
| | `BIGQUERY_TABLE` | BigQuery 表名称 (`ivt_classifications`) |
| **Cloud Armor** | `CLOUD_ARMOR_REGION` | Cloud Armor 策略所在的 GCP 区域 |
| **App** | `NEXT_PUBLIC_APP_URL` | 面向公众的应用 URL |
| | `NEXT_PUBLIC_ENABLE_LOGGING` | 在生产环境中启用日志 (`true`/`false`) |
## 项目结构
```
traffic-genius/
├── app/
│ ├── (auth)/login/ # Google OAuth sign-in page
│ ├── api/
│ │ ├── auth/[...nextauth]/ # NextAuth route handler
│ │ ├── cloud-armor/ # POST: create rule
│ │ │ └── [policyName]/rules/# PATCH/DELETE: update/remove rules
│ │ ├── dashboard/ # GET: kpis/, traffic/, ivt/
│ │ └── audit-log/ # GET: fetch audit entries
│ ├── dashboard/
│ │ ├── page.tsx # Security overview (KPIs + charts)
│ │ ├── traffic/ # Traffic analysis + country breakdown
│ │ ├── ivt/ # IVT detection records + pie chart
│ │ ├── cloud-armor/ # Policy list → [policyName] detail
│ │ ├── audit-log/ # Rule change history
│ │ └── settings/ # User preferences + sign-out
│ ├── globals.css # Tailwind @theme inline + custom classes
│ ├── layout.tsx # Root layout (Poppins font, Providers)
│ └── page.tsx # Redirects to /dashboard
├── components/
│ ├── Providers.tsx # NextAuth SessionProvider wrapper
│ ├── charts/ # Recharts: TrafficChart, IvtPieChart, CountryChart
│ ├── dashboard/ # DashboardNav, KpiCard, RuleActions, SettingsContent
│ └── ui/ # shadcn/ui primitives (button, card, dialog, table, etc.)
├── lib/
│ ├── db.ts # PostgreSQL Pool (raw SQL, no ORM)
│ ├── logger.ts # Pino structured logger (no console.log!)
│ ├── types.ts # All shared TypeScript interfaces
│ ├── audit-log.ts # Audit trail service (create + query)
│ ├── utils.ts # cn(), formatNumber(), formatPercent(), formatDate()
│ └── gcp/
│ ├── bigquery.ts # IVT queries, traffic summaries, KPI aggregation
│ ├── cloud-armor.ts # Security policy/rule CRUD via Compute API
│ ├── cloud-logging.ts # Cloud Armor access log retrieval
│ └── error-reporting.ts # GCP Error Reporting integration
├── scripts/
│ ├── 001-create-auth-tables.sql # NextAuth schema (users, accounts, sessions)
│ └── 002-create-app-tables.sql # App tables (audit_logs, dashboard_preferences)
├── auth.ts # NextAuth v5 config (Google OAuth, domain restriction)
├── proxy.ts # Middleware: route protection via session cookie
├── next.config.ts # Image remote patterns (GCS, Google avatars)
├── tsconfig.json # TypeScript strict config with @/* path alias
└── package.json # Scripts, dependencies
```
## 架构
```
Browser → proxy.ts (session cookie check)
│
├── Protected Dashboard Pages (Server Components)
│ └── Direct calls to lib/gcp/*.ts → BigQuery / Cloud Armor API
│
├── API Routes (app/api/cloud-armor/)
│ └── Write operations only → lib/gcp/cloud-armor.ts + lib/audit-log.ts
│
└── Client Components ("use client")
└── Interactive UI: charts (Recharts), forms (RuleActions), navigation
```
### 关键架构决策
- **默认使用 Server Components** — 仪表板页面 (`app/dashboard/*.tsx`) 使用 `async` 函数直接在服务端从 GCP 服务获取数据。读取操作不进行客户端数据获取。
- **API 路由仅用于写入** — `POST /api/cloud-armor`、`PATCH/DELETE /api/cloud-armor/[policyName]/rules` 处理变更操作,并始终写入审计日志条目。
- **GCP 惰性单例** — 每个 `lib/gcp/*.ts` 文件都使用 `let _client = null; function getClient()` 模式在首次使用时创建 GCP 客户端。
- **原生 SQL,无 ORM** — 通过 `pg` Pool 使用参数化查询访问 PostgreSQL。参见 `lib/db.ts` 中的 `query()` 和 `getClient()`。
- **结构化日志** — 使用带有作用域命名空间的 Pino logger。**绝不**使用 `console.log()`。参见 `lib/logger.ts`。
- **Suspense + Skeleton 降级** — 每个仪表板页面都将其异步数据组件包装在 ` }>` 中。
### 数据源
| 来源 | 库 | 用途 |
| --------------------- | ------------------------------- | ----------------------------------------------- |
| BigQuery | `@google-cloud/bigquery` | IVT 记录、流量分析、KPI 聚合 |
| Cloud Armor | `@google-cloud/compute` | 安全策略和规则 CRUD |
| Cloud Logging | `@google-cloud/logging` | 获取 Cloud Armor 事件的访问日志 |
| Cloud Error Reporting | `@google-cloud/error-reporting` | 生产环境错误追踪 |
| PostgreSQL | `pg` | 验证会话、审计日志、用户偏好 |
## 仪表板页面
| 路由 | 页面 | 数据源 | 描述 |
| ------------------------------- | ----------------- | ---------------------- | -------------------------------------------------------------- |
| `/dashboard` | 安全概览 | BigQuery + Cloud Armor | 8 个 KPI 卡片、流量趋势图、IVT 饼图、国家/地区图表 |
| `/dashboard/traffic` | 流量分析 | BigQuery | 每小时趋势、国家/地区分布表、统计卡片 |
| `/dashboard/ivt` | IVT 检测 | BigQuery | 已分类 IVT 记录表、类型分布饼图 |
| `/dashboard/cloud-armor` | 策略列表 | Cloud Armor API | 所有策略及其规则数量和类型标签 |
| `/dashboard/cloud-armor/[name]` | 策略详情 | Cloud Armor API | 规则表,支持添加/编辑/删除/切换操作 |
| `/dashboard/audit-log` | 审计日志 | PostgreSQL | 所有 Cloud Armor 规则变更的历史记录 |
| `/dashboard/settings` | 设置 | NextAuth session | 用户资料、偏好设置、登出 |
## API 路由
| 方法 | 路由 | 用途 | 需要验证 |
| -------- | ------------------------------------------------ | ------------------------------------ | :-----------: |
| GET/POST | `/api/auth/[...nextauth]` | NextAuth 处理程序 | — |
| POST | `/api/cloud-armor` | 创建新安全规则 | ✅ |
| PATCH | `/api/cloud-armor/[policyName]/rules` | 更新现有规则 | ✅ |
| DELETE | `/api/cloud-armor/[policyName]/rules?priority=N` | 按优先级删除规则 | ✅ |
| GET | `/api/dashboard/kpis` | 仪表板 KPI (24h) | ✅ |
| GET | `/api/dashboard/traffic` | 流量摘要 (每小时 + 国家/地区) | ✅ |
| GET | `/api/dashboard/ivt` | IVT 分类数据 | ✅ |
| GET | `/api/audit-log` | 审计日志条目 | ✅ |
## 数据库模式
### 验证表 — `scripts/001-create-auth-tables.sql`
标准 [NextAuth.js PostgreSQL schema](https://authjs.dev/getting-started/adapters/pg):
- `users` — id、name、email、emailVerified、image
- `accounts` — 关联到用户的 OAuth 提供商账号
- `sessions` — 数据库支持的会话(30 天最大有效期)
- `verification_token` — 邮箱验证令牌
### 应用表 — `scripts/002-create-app-tables.sql`
- **`audit_logs`** — user_id、action (`CREATE`/`UPDATE`/`DELETE`/`TOGGLE`)、resource、details (JSONB)、ip_address、created_at
- **`dashboard_preferences`** — user_id (唯一)、preferences (JSONB)、updated_at
### BigQuery 表
- **Dataset:** `traffic_security_logs`
- **Table:** `ivt_classifications`
- **关键字段:** `timestamp`、`source_ip`、`country_code`、`ivt_type` (GIVT/SIVT/suspicious/clean)、`confidence_score`、`user_agent`、`request_path`、`rule_matched`、`action_taken`
## GCP 集成
TrafficGenius 集成了四个 GCP 服务:
### BigQuery (`lib/gcp/bigquery.ts`)
查询 `ivt_classifications` 表以:
- `getDashboardKpis()` — 24 小时聚合 KPI(请求、拦截、唯一 IP、顶级攻击向量)
- `getTrafficSummary(hoursAgo)` — 每小时趋势、国家/地区分布、IVT 类型分布
- `getIvtRecords(options)` — 带类型/国家过滤的分页 IVT 记录
### Cloud Armor (`lib/gcp/cloud-armor.ts`)
对安全策略和规则进行 CRUD 操作:
- `listPolicies()` / `getPolicy(name)` — 读取策略及其规则
- `addRule(policy, rule)` — 创建新规则(允许、拒绝、限速、节流、重定向)
- `patchRule(policy, priority, updates)` — 更新现有规则
- `removeRule(policy, priority)` — 按优先级删除规则
### Cloud Logging (`lib/gcp/cloud-logging.ts`)
- `getArmorLogs(options)` — 获取带有 Cloud Armor 执行详情的最近 HTTP 负载均衡器日志
### Error Reporting (`lib/gcp/error-reporting.ts`)
- `reportError(err)` — 发送错误至 GCP Error Reporting(仅生产环境)
## 身份验证
- **提供商:** 仅 Google OAuth(通过 NextAuth.js v5)
- **域名限制:** `@topnetworks.co` 和 `@topfinanzas.com` — 在 `auth.ts` 的 `signIn` 回调中强制执行
- **会话策略:** 存储在 PostgreSQL 中的数据库会话(30 天最大有效期)
- **自定义登录页:** `/login`,带品牌化 UI
- **路由保护:** `proxy.ts` 中间件检查会话 Cookie 并重定向未验证用户
- **配置:** `auth` 导出 `{ handlers, auth, signIn, signOut }`
## 样式与品牌
### 设计系统
- **CSS 框架:** Tailwind CSS 4,在 `globals.css` 中使用 `@theme inline` 自定义属性
- **组件库:** `components/ui/` 中的 shadcn/ui 原语
- **类名合并:** 来自 `lib/utils.ts` 的 `cn()` 工具 (clsx + tailwind-merge)
- **字体:** Poppins (Google Fonts,粗细 300–700,CSS 变量 `--font-poppins`)
- **玻璃拟态:** `.card-glass` 工具类,用于毛玻璃卡片效果
### 品牌色
| 令牌 | 十六进制值 | 用途 |
| ------------ | --------- | ------------------------------------- |
| `brand-blue` | `#2563eb` | 主要操作、链接、激活状态 |
| `brand-cyan` | `#0891b2` | 次要强调、图表颜色 |
| `brand-lime` | `#84cc16` | 成功状态、正向指标 |
**渐变:** blue → cyan → lime(用于页面背景和页眉)
### 资源
| 资源 | URL |
| ------- | ------------------------------------------------------------------------------------------------ |
| Favicon | `https://storage.googleapis.com/media-topfinanzas-com/favicon.png` |
| Logo | `https://storage.googleapis.com/media-topfinanzas-com/images/topnetworks-positivo-sinfondo.webp` |
## 脚本
```
npm run dev # Start dev server on http://localhost:3080
npm run build # Production build
npm run start # Start production server on port 3080
npm run lint # Run ESLint + Prettier check
npm run format # Auto-fix formatting with Prettier
npm run format:check # Check formatting without fixing
```
## 部署
### 自托管 (GCP Compute Engine)
```
# 构建
npm install
npm run build
# 使用 PM2 启动
pm2 start npm --name traffic-genius -- start
# 或直接启动
npm run start
```
### 基础设施
- **端口:** 3080(开发和生产环境)
- **进程管理器:** PM2(生产环境推荐)
- **反向代理:** Nginx 或 Apache
- **SSL:** 通过 Certbot 获取 Let's Encrypt 证书
- **目标平台:** GCP Compute Engine 或 Vercel
### 图片域名
在 `next.config.ts` 中配置:
- `storage.googleapis.com/media-topfinanzas-com/**` — CDN 资源
- `lh3.googleusercontent.com` — Google 个人资料头像
## 贡献指南
### 编码规范
- **TypeScript 严格模式** — 无正当理由禁止使用 `any`
- **集中类型定义** — 所有共享接口位于 `lib/types.ts`
- **结构化日志** — 使用 `lib/logger.ts` 中的 `createScopedLogger()`,**绝不**使用 `console.log()`
- **路径别名** — `@/*` 映射到项目根目录
- **组件命名** — PascalCase 文件名 (`KpiCard.tsx`, `DashboardNav.tsx`)
- **导入顺序** — React/Next.js → 第三方 → 本地
### API 路由模式
每个 API 路由必须:
1. 通过 `@/auth` 中的 `await auth()` 检查身份验证
2. 验证请求体/参数
3. 通过 `lib/gcp/*.ts` 执行操作
4. 通过 `createAuditLog()` 将变更记录到 `audit_logs`
5. 返回适当的状态码
### 添加新的仪表板页面
1. 创建 `app/dashboard/your-page/page.tsx` 作为 **Server Component**
2. 在异步组件中直接从 `lib/gcp/*.ts` 函数获取数据
3. 将异步组件包装在 ` }>` 中
4. 将路由添加到 `components/dashboard/DashboardNav.tsx` 中的 `navItems`
## 许可证
**Private** — © TopNetworks, Inc. 保留所有权利。
标签:BigQuery, CISA项目, GCP, GIVT, Google Cloud Armor, Google Cloud Platform, IVT检测, NextAuth, OAuth, PB级数据处理, PostgreSQL, React, SIVT, Syscalls, Tailwind CSS, TypeScript, Web安全, 云防火墙管理, 企业级应用, 反机器人, 威胁情报, 安全仪表盘, 安全插件, 安全规则管理, 安全运维, 审计日志, 开发者工具, 无效流量检测, 流量可视化, 测试用例, 网络安全, 自动化攻击, 自动化攻击, 蓝队分析, 配置错误, 隐私保护, 风控系统