feat: add token usage tracking and leaderboard
- Add token_usage table with composite unique index for claw_id + date - Add API endpoints: POST /token, GET /token/leaderboard, GET /token/stats - Add TokenLeaderboard component with daily/total period toggle - Add CLI commands: `token` and `stats` for reporting and viewing usage - Add Redis caching for leaderboard with 1-minute TTL - Add shared utilities: authenticateRequest, getTodayDateString - Use UPSERT pattern for atomic token updates - Add i18n translations (en/zh) for new UI elements
This commit is contained in:
31
lib/utils.ts
31
lib/utils.ts
@@ -1,6 +1,37 @@
|
||||
import { type ClassValue, clsx } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { validateApiKey } from "@/lib/auth/api-key";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get today's date as YYYY-MM-DD string
|
||||
*/
|
||||
export function getTodayDateString(): string {
|
||||
return new Date().toISOString().split("T")[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate an API request with Bearer token
|
||||
* Returns the claw object if authenticated, or a 401 NextResponse if not
|
||||
*/
|
||||
export async function authenticateRequest(req: NextRequest) {
|
||||
const authHeader = req.headers.get("authorization");
|
||||
if (!authHeader?.startsWith("Bearer ")) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing or invalid authorization header" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const apiKey = authHeader.slice(7);
|
||||
const claw = await validateApiKey(apiKey);
|
||||
if (!claw) {
|
||||
return NextResponse.json({ error: "Invalid API key" }, { status: 401 });
|
||||
}
|
||||
|
||||
return { claw };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user