Spaces:
Running
Running
Deploy bf9f5d0 từ GitHub Actions
Browse filesFiles changed (10)
- passport-check/.env.example+1-1
- passport-check/README.md+1-1
- passport-check/apps/server/src/gemini-keys.tsAdded+81
- passport-check/apps/server/src/gemini.ts+148-13
- passport-check/apps/server/src/index.ts+15-3
- passport-check/apps/web/src/app/(app)/api-key/page.tsxAdded+8
- passport-check/apps/web/src/components/GeminiKeys.tsxAdded+130
- passport-check/apps/web/src/components/Home.tsx+1-1
- passport-check/apps/web/src/components/Shell.tsx+1
- passport-check/apps/web/src/lib/api.ts+7
26 unmodified lines2728293031323326 unmodified linesTELEGRAM_CHAT_ID=# ---------- Gemini (tuỳ chọn)GEMINI_API_KEY=GEMINI_MODEL=# (tuỳ chọn) luật tính token ảnh (theo kích thước, không gọi API): tile (258/ô, không chặn trần) | low | medium | high | ultra_high (258/ô, chặn trần 280/560/1120/2240) | số token cố định/ảnh# để trống = tự chọn theo GEMINI_MODEL (gemini-2.x -> tile, còn lại -> tile chặn trần 1120)26 unmodified lines2728293031323326 unmodified linesTELEGRAM_CHAT_ID=# ---------- Gemini (tuỳ chọn)# API key Gemini: thêm trên UI (trang "API key", chỉ admin), không đặt ở đâyGEMINI_MODEL=# (tuỳ chọn) luật tính token ảnh (theo kích thước, không gọi API): tile (258/ô, không chặn trần) | low | medium | high | ultra_high (258/ô, chặn trần 280/560/1120/2240) | số token cố định/ảnh# để trống = tự chọn theo GEMINI_MODEL (gemini-2.x -> tile, còn lại -> tile chặn trần 1120)
125 unmodified lines126127128129130131132125 unmodified lines- `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`- `ADMIN_EMAIL` (lần chạy đầu), tuỳ chọn `ADMIN_PASSWORD`Tuỳ chọn: `ALLOWED_EMAILS`, `GEMINI_API_KEY`, `AUTH_TOKEN_DAYS`.3. Push repo này lên Space (`git push` tới `https://huggingface.co/spaces/<user>/<space>`).### 4. Frontend — Next.js125 unmodified lines126127128129130131132125 unmodified lines- `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`- `ADMIN_EMAIL` (lần chạy đầu), tuỳ chọn `ADMIN_PASSWORD`Tuỳ chọn: `ALLOWED_EMAILS`, `AUTH_TOKEN_DAYS` (Gemini API key thêm trên UI, trang "API key").3. Push repo này lên Space (`git push` tới `https://huggingface.co/spaces/<user>/<space>`).### 4. Frontend — Next.js
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081/** * Gemini API key do admin thêm trên UI — lưu ở Firestore `settings/gemini-keys`. * Key nằm trong gemini.ts cùng với key từ biến môi trường; API chỉ trả bản rút gọn (4 ký tự đầu/cuối). */import { randomUUID } from 'node:crypto';import { db } from './firebase.ts';import { clearCooldown, keyStatus, setUiKeys, testKey } from './gemini.ts';
interface Stored { id: string; label: string; key: string; enabled: boolean }interface Doc { keys: Stored[]; updatedAt: number; updatedBy: string }
const ref = () => db().collection('settings').doc('gemini-keys');let list: Stored[] = [];let loaded = false;
const httpError = (message: string) => Object.assign(new Error(message), { status: 400 });
export async function loadGeminiKeys() { const snap = await ref().get(); list = snap.exists ? ((snap.data() as Doc).keys ?? []) : []; setUiKeys(list); loaded = true;}const ensure = async () => { if (!loaded) await loadGeminiKeys(); };
async function persist(by: string) { await ref().set({ keys: list, updatedAt: Date.now(), updatedBy: by } satisfies Doc); setUiKeys(list);}
export async function geminiKeyReport() { await ensure(); return keyStatus();}
export async function addGeminiKeys(body: { keys?: unknown; label?: unknown }, by: string) { await ensure(); // cho dán nhiều key một lần (mỗi dòng / phân cách dấu phẩy) const raw = typeof body.keys === 'string' ? body.keys : ''; const keys = [...new Set(raw.split(/[\s,;]+/).map((k) => k.trim()).filter(Boolean))]; if (!keys.length) throw httpError('Chưa nhập key'); if (keys.length > 50) throw httpError('Tối đa 50 key mỗi lần'); const label = typeof body.label === 'string' ? body.label.trim().slice(0, 60) : ''; const bad = keys.filter((k) => !/^[\w-]{20,200}$/.test(k)); if (bad.length) throw httpError(`Key không đúng định dạng: ${bad.map((k) => k.slice(0, 6) + '…').join(', ')}`); const have = new Set(list.map((k) => k.key)); let added = 0; for (const key of keys) { if (have.has(key)) continue; list.push({ id: randomUUID().slice(0, 8), label: label ? (keys.length > 1 ? `${label} #${added + 1}` : label) : `Key ${list.length + 1}`, key, enabled: true }); added++; } await persist(by); return { added, skipped: keys.length - added };}
export async function updateGeminiKey(id: string, patch: { label?: unknown; enabled?: unknown }, by: string) { await ensure(); const k = list.find((x) => x.id === id); if (!k) throw Object.assign(new Error('Không tìm thấy key (key từ biến môi trường không sửa ở đây)'), { status: 404 }); if (typeof patch.label === 'string') k.label = patch.label.trim().slice(0, 60) || k.label; if (typeof patch.enabled === 'boolean') k.enabled = patch.enabled; await persist(by);}
export async function deleteGeminiKey(id: string, by: string) { await ensure(); if (!list.some((x) => x.id === id)) throw Object.assign(new Error('Không tìm thấy key'), { status: 404 }); list = list.filter((x) => x.id !== id); await persist(by);}
/** Thử 1 key đã lưu (theo id) hoặc key nhập tay (chưa lưu) */export async function testGeminiKey(body: { id?: unknown; key?: unknown }) { await ensure(); const key = typeof body.key === 'string' && body.key.trim() ? body.key.trim() : list.find((x) => x.id === body.id)?.key; if (!key) throw httpError('Không có key để thử (key từ biến môi trường không thử ở đây)'); return testKey(key);}
export const resetGeminiCooldown = (id?: string) => clearCooldown(id);5 unmodified lines6789101112131415161718192021222349 unmodified lines7374757677787980818283848586878889909 unmodified lines1001011021031041051065 unmodified linesimport type { LlmOutput } from '@pc/core';const MODEL = process.env.GEMINI_MODEL || 'gemini-3.1-flash-lite';let client: GoogleGenAI | null = null;export function llmAvailable() {return !!process.env.GEMINI_API_KEY;}export function llmModel() {return MODEL;}function ai() {if (!client) client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });return client;}const str = (description: string) => ({ type: 'string', description });49 unmodified lines}];}/** Gọi Gemini, tự thử lại khi 429 / 5xx */async function withRetry<T>(fn: () => Promise<T>): Promise<T> {let lastErr: unknown;for (let attempt = 0; attempt < 4; attempt++) {try {return await fn();} catch (e: any) {lastErr = e;const status = e?.status ?? e?.code;// 429 (hết quota free) / 5xx -> chờ rồi thử lạiif (status === 429 || (status >= 500 && status < 600)) {await new Promise((r) => setTimeout(r, 2000 * 2 ** attempt));continue;}throw e;9 unmodified lines}export async function geminiExtract(image: Buffer, mimeType: string, hint?: string): Promise<{ llm: LlmOutput; usage: { promptTokens: number; outputTokens: number; thinkingTokens: number; weight: number; model: string } }> {const res = await withRetry(() => ai().models.generateContent({ model: MODEL, contents: contents(image, mimeType, hint), config: GEN_CONFIG }));const u = res.usageMetadata;return {llm: JSON.parse(res.text ?? '') as LlmOutput,5 unmodified lines678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613749 unmodified lines1871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242259 unmodified lines2352362372382392402415 unmodified linesimport type { LlmOutput } from '@pc/core';const MODEL = process.env.GEMINI_MODEL || 'gemini-3.1-flash-lite';/*** Danh sách API key để xoay vòng: chỉ lấy từ UI (admin thêm ở trang "API key", lưu Firestore — xem gemini-keys.ts).* Không đọc biến môi trường.*/export interface KeyEntry { id: string; label: string; key: string; enabled: boolean; source: 'ui' }interface KeyStats { calls: number; limited: number; lastUsedAt?: number; lastError?: string; lastErrorAt?: number }let uiKeys: KeyEntry[] = [];let KEYS: KeyEntry[] = [];const rebuild = () => {const seen = new Set<string>();KEYS = uiKeys.filter((e) => !seen.has(e.key) && !!seen.add(e.key));};rebuild();export function setUiKeys(list: { id: string; label: string; key: string; enabled: boolean }[]) {uiKeys = list.map((k) => ({ ...k, source: 'ui' as const }));rebuild();}const clients = new Map<string, GoogleGenAI>();/** id key -> thời điểm (ms) được dùng lại sau khi dính 429 (hết RPM / TPM / RPD) */const cooldownUntil = new Map<string, number>();const stats = new Map<string, KeyStats>();const st = (id: string) => { let x = stats.get(id); if (!x) stats.set(id, (x = { calls: 0, limited: 0 })); return x; };let cursor = 0;const active = () => KEYS.filter((e) => e.enabled);export function llmAvailable() {return active().length > 0;}export function llmModel() {return MODEL;}export const keyHint = (key: string) => (key.length > 10 ? `${key.slice(0, 4)}…${key.slice(-4)}` : '••••');/** Trạng thái từng key cho UI (không trả key đầy đủ) */export function keyStatus() {const now = Date.now();return KEYS.map((e) => {const s = st(e.id);const until = cooldownUntil.get(e.id) ?? 0;return { id: e.id, label: e.label, hint: keyHint(e.key), enabled: e.enabled, source: e.source, calls: s.calls, limited: s.limited, lastUsedAt: s.lastUsedAt, lastError: s.lastError, lastErrorAt: s.lastErrorAt, cooldownUntil: until > now ? until : undefined };});}export function clearCooldown(id?: string) {if (id) cooldownUntil.delete(id); else cooldownUntil.clear();}/** Gọi thử 1 key bất kỳ (chưa lưu) bằng request nhỏ nhất để biết key có hợp lệ không */export async function testKey(key: string): Promise<{ ok: boolean; error?: string }> {try {await new GoogleGenAI({ apiKey: key }).models.countTokens({ model: MODEL, contents: 'ping' });return { ok: true };} catch (e: any) {// 429 nghĩa là key hợp lệ nhưng đang hết quotaif ((e?.status ?? e?.code) === 429) return { ok: true, error: 'Key hợp lệ nhưng đang hết quota (429)' };return { ok: false, error: String(e?.message ?? e).slice(0, 300) };}}/** Số ms tới 00:00 giờ Pacific kế tiếp (lúc Google reset quota theo ngày) */function msToPacificMidnight(): number {const now = new Date();const parts = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Los_Angeles', hour12: false, hour: 'numeric', minute: 'numeric', second: 'numeric' }).formatToParts(now);const g = (t: string) => Number(parts.find((p) => p.type === t)?.value ?? 0) % 24;const elapsed = ((g('hour') * 60 + g('minute')) * 60 + g('second')) * 1000;return 24 * 3600_000 - elapsed + 1000;}/** Từ lỗi 429 suy ra nên khoá key bao lâu: hết quota ngày -> tới nửa đêm Pacific; còn lại theo retryDelay (mặc định 60s) */function cooldownMs(e: any): number {const msg = String(e?.message ?? '');if (/PerDay|per day|daily/i.test(msg)) return msToPacificMidnight();const m = msg.match(/retry(?:Delay)?"?[^0-9]{0,12}(\d+(?:\.\d+)?)s/i);return m ? Math.ceil(Number(m[1]) * 1000) + 500 : 60_000;}/*** Tự mở khoá: key bị khoá lâu (>= 2 phút, thường là hết quota ngày) được dò lại mỗi 2 giờ (PROBE_EVERY)* bằng 1 request cực nhỏ (1 token output). Gọi được -> bỏ khoá ngay, không chờ tới giờ reset dự kiến.* Khoá ngắn (RPM/TPM) tự hết hạn theo retryDelay nên không cần dò.*/const PROBE_EVERY = 2 * 3600_000;const lastProbe = new Map<string, number>();async function probeLocked() {const now = Date.now();for (const e of active()) {const until = cooldownUntil.get(e.id) ?? 0;if (until - now < 2 * 60_000 || now - (lastProbe.get(e.id) ?? 0) < PROBE_EVERY) continue;lastProbe.set(e.id, now);try {await clientFor(e.key).models.generateContent({ model: MODEL, contents: 'hi', config: { maxOutputTokens: 1, temperature: 0 } });cooldownUntil.delete(e.id);console.log(`gemini key ${keyHint(e.key)} đã có quota trở lại, mở khoá`);} catch (err: any) {if ((err?.status ?? err?.code) !== 429) console.warn(`gemini probe ${keyHint(e.key)}:`, String(err?.message ?? err).slice(0, 120));}}}let recoveryTimer: ReturnType<typeof setInterval> | null = null;export function startKeyRecovery() {if (recoveryTimer) return;recoveryTimer = setInterval(() => void probeLocked(), 60_000);recoveryTimer.unref();}/** Chọn key kế tiếp còn dùng được (round-robin); null nếu mọi key đều đang bị khoá */function pickKey(): KeyEntry | null {const list = active();const now = Date.now();for (let i = 0; i < list.length; i++) {const e = list[(cursor + i) % list.length];if ((cooldownUntil.get(e.id) ?? 0) <= now) {cursor = (cursor + i + 1) % list.length;return e;}}return null;}const soonestFree = () => Math.max(0, Math.min(...active().map((e) => cooldownUntil.get(e.id) ?? 0)) - Date.now());function clientFor(key: string) {let c = clients.get(key);if (!c) clients.set(key, (c = new GoogleGenAI({ apiKey: key })));return c;}const str = (description: string) => ({ type: 'string', description });49 unmodified lines}];}/** Gọi Gemini với key xoay vòng: 429 -> khoá key đó rồi đổi key khác ngay; hết sạch key thì chờ key sớm nhất; 5xx -> chờ rồi thử lại */async function withRetry<T>(fn: (client: GoogleGenAI) => Promise<T>): Promise<T> {if (!llmAvailable()) throw new Error('Chưa có Gemini API key nào đang bật');const MAX_WAIT = 90_000; // chờ tối đa khi mọi key đều đang bị khoálet lastErr: unknown;for (let attempt = 0; attempt < active().length + 4; attempt++) {const entry = pickKey();if (!entry) {const wait = soonestFree();if (!active().length || wait > MAX_WAIT) throw lastErr ?? new Error('Mọi Gemini API key đều hết quota');await new Promise((r) => setTimeout(r, wait));continue;}const s = st(entry.id);try {const out = await fn(clientFor(entry.key));s.calls++;s.lastUsedAt = Date.now();return out;} catch (e: any) {lastErr = e;const status = e?.status ?? e?.code;s.lastError = String(e?.message ?? e).slice(0, 200);s.lastErrorAt = Date.now();if (status === 429) {const ms = cooldownMs(e);cooldownUntil.set(entry.id, Date.now() + ms);s.limited++;console.warn(`gemini key ${keyHint(entry.key)} hết quota, khoá ${Math.round(ms / 1000)}s (${active().length} key)`);continue;}if (status >= 500 && status < 600) {await new Promise((r) => setTimeout(r, 2000 * 2 ** Math.min(attempt, 3)));continue;}throw e;9 unmodified lines}export async function geminiExtract(image: Buffer, mimeType: string, hint?: string): Promise<{ llm: LlmOutput; usage: { promptTokens: number; outputTokens: number; thinkingTokens: number; weight: number; model: string } }> {const res = await withRetry((c) => c.models.generateContent({ model: MODEL, contents: contents(image, mimeType, hint), config: GEN_CONFIG }));const u = res.usageMetadata;return {llm: JSON.parse(res.text ?? '') as LlmOutput,
5 unmodified lines678910111213141516305 unmodified lines32232332432532632732822 unmodified lines351352353354355356169 unmodified lines5265275285295305315325335 unmodified linesbpFileName, bpRows, customerRow, dvcFileName, dvcRows, effectiveTrip, fillTemplate, sortMaleFirst, vnDate,type BatchSettings, type CustomerRow, type ExportEntry, type ExtractionResult, type LlmPolicy, type TripInfo,} from '@pc/core';import { llmAvailable, llmModel } from './gemini.ts';import { shutdownOcr } from './ocr.ts';import { firebaseConfigured } from './firebase.ts';import { apiKeyConfigured, clientIp, requireAdmin, requireApiKey, requireCostAccess, requireUser } from './auth.ts';import { getBilling, saveFixedCosts, setPaid } from './billing.ts';import { getCostSettings, saveCostSettings } from './cost-settings.ts';import { authConfigured, changeOwnPassword, createUser, diagnoseGoogle, deleteUser, listUsers, loadUsers, login, loginGoogle, updateUser, usersReady } from './users.ts';import { TelegramError, assertTelegramConfig, diagnose as telegramDiagnose, sendMessage, sendPhoto, telegramConfigured } from './telegram.ts';305 unmodified lines// 'full': bắt buộc chạy lại toàn bộ pipeline (OCR nhanh + OCR kỹ + Gemini) — chỉ adminif (mode === 'full' && req.user!.role !== 'admin') return void res.status(403).json({ error: 'Chỉ admin được đọc lại bắt buộc' });const force = mode === 'full' ? 'full' : mode === 'llm' ? 'llm' : 'ocr';if (force === 'llm' && !llmAvailable()) return void res.status(501).json({ error: 'Server chưa cấu hình GEMINI_API_KEY' });await rerun(String(req.params.bid), String(req.params.iid), force);res.json({ ok: true });}));22 unmodified lines// Token Gemini thực tế (in / out / thinking) theo model + chi phí — chỉ adminapi.get('/tokens/actual', requireAdmin, h(async (_req, res) => res.json(actualReport(allItems(), (id) => batchById(id)?.name ?? id))));// Đơn giá & cách tính dùng chung: ai xem được trang chi phí thì đọc, chỉ admin sửa (body null = về mặc định)api.get('/cost-settings', requireCostAccess, h(async (_req, res) => res.json({ settings: await getCostSettings() })));api.put('/cost-settings', requireAdmin, json, h(async (req, res) => {169 unmodified linesconst server = app.listen(PORT, () => {console.log(`passport-check backend listening on :${PORT}${ready ? '' : ` (thiếu cấu hình: ${missing.join(', ')})`}`);if (ready) {loadUsers().catch((e) => console.error('load users error', e?.message ?? e));recover().catch((e) => console.error('recover error', e?.message ?? e));}});for (const sig of ['SIGINT', 'SIGTERM'] as const) {5 unmodified lines67891011121314151617305 unmodified lines32332432532632732832922 unmodified lines352353354355356357358359360361362363364365169 unmodified lines5355365375385395405415425435445455 unmodified linesbpFileName, bpRows, customerRow, dvcFileName, dvcRows, effectiveTrip, fillTemplate, sortMaleFirst, vnDate,type BatchSettings, type CustomerRow, type ExportEntry, type ExtractionResult, type LlmPolicy, type TripInfo,} from '@pc/core';import { llmAvailable, llmModel, startKeyRecovery } from './gemini.ts';import { shutdownOcr } from './ocr.ts';import { firebaseConfigured } from './firebase.ts';import { apiKeyConfigured, clientIp, requireAdmin, requireApiKey, requireCostAccess, requireUser } from './auth.ts';import { getBilling, saveFixedCosts, setPaid } from './billing.ts';import { addGeminiKeys, deleteGeminiKey, geminiKeyReport, loadGeminiKeys, resetGeminiCooldown, testGeminiKey, updateGeminiKey } from './gemini-keys.ts';import { getCostSettings, saveCostSettings } from './cost-settings.ts';import { authConfigured, changeOwnPassword, createUser, diagnoseGoogle, deleteUser, listUsers, loadUsers, login, loginGoogle, updateUser, usersReady } from './users.ts';import { TelegramError, assertTelegramConfig, diagnose as telegramDiagnose, sendMessage, sendPhoto, telegramConfigured } from './telegram.ts';305 unmodified lines// 'full': bắt buộc chạy lại toàn bộ pipeline (OCR nhanh + OCR kỹ + Gemini) — chỉ adminif (mode === 'full' && req.user!.role !== 'admin') return void res.status(403).json({ error: 'Chỉ admin được đọc lại bắt buộc' });const force = mode === 'full' ? 'full' : mode === 'llm' ? 'llm' : 'ocr';if (force === 'llm' && !llmAvailable()) return void res.status(501).json({ error: 'Chưa có Gemini API key nào đang bật (thêm ở trang API key)' });await rerun(String(req.params.bid), String(req.params.iid), force);res.json({ ok: true });}));22 unmodified lines// Token Gemini thực tế (in / out / thinking) theo model + chi phí — chỉ adminapi.get('/tokens/actual', requireAdmin, h(async (_req, res) => res.json(actualReport(allItems(), (id) => batchById(id)?.name ?? id))));// Gemini API key xoay vòng: admin thêm / tắt / xoá / thử keyapi.get('/gemini-keys', requireAdmin, h(async (_req, res) => res.json({ keys: await geminiKeyReport() })));api.post('/gemini-keys', requireAdmin, json, h(async (req, res) => res.json(await addGeminiKeys(req.body ?? {}, req.user!.email))));api.post('/gemini-keys/test', requireAdmin, json, h(async (req, res) => res.json(await testGeminiKey(req.body ?? {}))));api.post('/gemini-keys/reset', requireAdmin, json, h(async (req, res) => { resetGeminiCooldown(req.body?.id); res.json({ ok: true }); }));api.patch('/gemini-keys/:id', requireAdmin, json, h(async (req, res) => { await updateGeminiKey(req.params.id as string, req.body ?? {}, req.user!.email); res.json({ ok: true }); }));api.delete('/gemini-keys/:id', requireAdmin, h(async (req, res) => { await deleteGeminiKey(req.params.id as string, req.user!.email); res.json({ ok: true }); }));// Đơn giá & cách tính dùng chung: ai xem được trang chi phí thì đọc, chỉ admin sửa (body null = về mặc định)api.get('/cost-settings', requireCostAccess, h(async (_req, res) => res.json({ settings: await getCostSettings() })));api.put('/cost-settings', requireAdmin, json, h(async (req, res) => {169 unmodified linesconst server = app.listen(PORT, () => {console.log(`passport-check backend listening on :${PORT}${ready ? '' : ` (thiếu cấu hình: ${missing.join(', ')})`}`);if (ready) {startKeyRecovery();loadUsers().catch((e) => console.error('load users error', e?.message ?? e));// nạp key từ Firestore trước khi phục hồi job, để job dở dang thấy đủ keyloadGeminiKeys().catch((e) => console.error('load gemini keys error', e?.message ?? e)).finally(() => recover().catch((e) => console.error('recover error', e?.message ?? e)));}});for (const sig of ['SIGINT', 'SIGTERM'] as const) {
12345678import { notFound } from 'next/navigation';import { GeminiKeys } from '@/components/GeminiKeys';import { currentUser } from '@/lib/server/backend';
export default async function Page() { if ((await currentUser())?.role !== 'admin') notFound(); return <GeminiKeys />;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130'use client';import { useCallback, useEffect, useState } from 'react';import { addGeminiKeys, deleteGeminiKey, listGeminiKeys, resetGeminiCooldown, testGeminiKey, updateGeminiKey, type GeminiKeyRow } from '../lib/api';
const fmt = (t?: number) => (t ? new Date(t).toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh' }) : '—');
/** Admin: thêm nhiều Gemini API key để xoay vòng khi hết RPM / TPM / RPD */export function GeminiKeys() { const [rows, setRows] = useState<GeminiKeyRow[] | null>(null); const [err, setErr] = useState(''); const [ok, setOk] = useState(''); const [keys, setKeys] = useState(''); const [label, setLabel] = useState(''); const [busy, setBusy] = useState(false); const [now, setNow] = useState(() => Date.now());
const load = useCallback(() => listGeminiKeys().then((r) => setRows(r.keys)).catch((e) => setErr(e.message)), []); useEffect(() => { load(); const t = setInterval(() => { setNow(Date.now()); load(); }, 10_000); return () => clearInterval(t); }, [load]);
const act = async (fn: () => Promise<unknown>, done?: string | ((r: any) => string)) => { setBusy(true); setErr(''); setOk(''); try { const r = await fn(); if (done) setOk(typeof done === 'function' ? done(r) : done); await load(); } catch (e) { setErr((e as Error).message); } finally { setBusy(false); } };
const testAndShow = async (body: { id?: string; key?: string }) => { setBusy(true); setErr(''); setOk(''); try { const r = await testGeminiKey(body); if (r.ok) setOk(r.error ?? 'Key dùng được'); else setErr(`Key lỗi: ${r.error}`); } catch (e) { setErr((e as Error).message); } finally { setBusy(false); } };
const status = (r: GeminiKeyRow) => { if (!r.enabled) return <span className="pill">Tắt</span>; if (r.cooldownUntil && r.cooldownUntil > now) return <span className="pill red" title={`Dùng lại lúc ${fmt(r.cooldownUntil)}`}>Hết quota · còn {Math.ceil((r.cooldownUntil - now) / 1000)}s</span>; return <span className="pill green">Sẵn sàng</span>; };
const usable = rows?.filter((r) => r.enabled).length ?? 0;
return ( <div className="stack-gap"> <section className="panel pad stack-gap"> <h3>Thêm Gemini API key</h3> <form className="stack" onSubmit={(e) => { e.preventDefault(); act(async () => { const r = await addGeminiKeys(keys, label); setKeys(''); setLabel(''); return r; }, (r) => `Đã thêm ${r.added} key${r.skipped ? `, bỏ qua ${r.skipped} key trùng` : ''}`); }}> <label className="stack"><span>API key (dán nhiều key: mỗi dòng một key hoặc cách nhau dấu phẩy)</span> <textarea required rows={4} spellCheck={false} autoComplete="off" placeholder={'AIza…\nAIza…'} value={keys} onChange={(e) => setKeys(e.target.value)} style={{ fontFamily: 'monospace' }} /> </label> <div className="row" style={{ alignItems: 'flex-end', flexWrap: 'wrap' }}> <label className="stack"><span>Tên gợi nhớ (tuỳ chọn)</span><input value={label} maxLength={60} placeholder="VD: Project A" onChange={(e) => setLabel(e.target.value)} /></label> <button className="btn" disabled={busy || !keys.trim()}>Thêm</button> <button type="button" className="btn ghost" disabled={busy || !keys.trim()} onClick={() => testAndShow({ key: keys.split(/[\s,;]+/).filter(Boolean)[0] })}>Thử key đầu tiên</button> </div> </form> <p className="muted small"> Khi một key dính 429 (hết RPM / TPM / RPD), hệ thống tạm khoá key đó và tự chuyển sang key khác. Hết quota ngày thì khoá tới 00:00 giờ Pacific. Nên dùng key từ các project Google Cloud khác nhau vì quota tính theo project. Key đã lưu không hiển thị lại đầy đủ. </p> {err && <p className="err-text small">{err}</p>} {ok && <p className="ok-text small">{ok}</p>} </section>
<section className="panel batches"> <div className="row" style={{ justifyContent: 'space-between', padding: '12px 16px' }}> <h3>Danh sách key {rows && <span className="muted small">({usable}/{rows.length} đang bật)</span>}</h3> <button className="btn ghost sm" disabled={busy} onClick={() => act(() => resetGeminiCooldown(), 'Đã bỏ khoá tạm của mọi key')}>Bỏ khoá tạm tất cả</button> </div> {!rows && !err && <p className="muted small pad">Đang tải…</p>} {rows && !rows.length && <p className="muted small pad">Chưa có key nào. Thêm key ở form phía trên.</p>} {rows && rows.length > 0 && ( <div className="table-wrap"> <table> <thead><tr><th>Tên</th><th>Key</th><th>Trạng thái</th><th title="Số lần gọi thành công / số lần dính 429 từ lúc server khởi động">Gọi / 429</th><th>Dùng gần nhất</th><th>Lỗi gần nhất</th><th /></tr></thead> <tbody> {rows.map((r) => ( <tr key={r.id}> <td className="name">{r.label}</td> <td className="mono small">{r.hint}</td> <td>{status(r)}</td> <td className="mono small">{r.calls} / {r.limited}</td> <td className="mono small">{fmt(r.lastUsedAt)}</td> <td className="small" title={r.lastError}>{r.lastError ? `${fmt(r.lastErrorAt)} · ${r.lastError.slice(0, 50)}…` : '—'}</td> <td> <div className="row"> {( <> <button className="btn ghost sm" disabled={busy} onClick={() => testAndShow({ id: r.id })}>Thử</button> <button className="btn ghost sm" disabled={busy} onClick={() => act(() => updateGeminiKey(r.id, { enabled: !r.enabled }))}>{r.enabled ? 'Tắt' : 'Bật'}</button> <button className="btn ghost sm" disabled={busy} onClick={() => { const n = prompt('Tên gợi nhớ', r.label); if (n) act(() => updateGeminiKey(r.id, { label: n })); }}>Đổi tên</button> <button className="btn ghost sm" disabled={busy} onClick={() => confirm(`Xoá key ${r.hint}?`) && act(() => deleteGeminiKey(r.id), 'Đã xoá key')}>Xoá</button> </> )} {r.cooldownUntil && r.cooldownUntil > now && <button className="btn ghost sm" disabled={busy} onClick={() => act(() => resetGeminiCooldown(r.id))}>Bỏ khoá</button>} </div> </td> </tr> ))} </tbody> </table> </div> )} </section> </div> );}63 unmodified lines6465666768697063 unmodified lines{POLICIES.map((p) => <option key={p.id} value={p.id}>{p.label}</option>)}</select></label>{!llmAvailable && <p className="muted small">Server chưa cấu hình GEMINI_API_KEY.</p>}</>)}<p className="privacy">63 unmodified lines6465666768697063 unmodified lines{POLICIES.map((p) => <option key={p.id} value={p.id}>{p.label}</option>)}</select></label>{!llmAvailable && <p className="muted small">Chưa có Gemini API key (admin thêm ở trang API key).</p>}</>)}<p className="privacy">
37 unmodified lines38394041424337 unmodified lines<Link href="/" aria-current={path === '/' || path.startsWith('/b/') ? 'page' : undefined}>Upload & các đoàn</Link>{user.costAccess && <Link href="/chi-phi" aria-current={path.startsWith('/chi-phi') ? 'page' : undefined}>Chi phí Gemini</Link>}{user.role === 'admin' && <Link href="/nguoi-dung" aria-current={path.startsWith('/nguoi-dung') ? 'page' : undefined}>Người dùng</Link>}{user.role === 'admin' && <Link href="/kiem-tra" aria-current={path.startsWith('/kiem-tra') ? 'page' : undefined}>Kiểm tra</Link>}</nav><div className="row">37 unmodified lines3839404142434437 unmodified lines<Link href="/" aria-current={path === '/' || path.startsWith('/b/') ? 'page' : undefined}>Upload & các đoàn</Link>{user.costAccess && <Link href="/chi-phi" aria-current={path.startsWith('/chi-phi') ? 'page' : undefined}>Chi phí Gemini</Link>}{user.role === 'admin' && <Link href="/nguoi-dung" aria-current={path.startsWith('/nguoi-dung') ? 'page' : undefined}>Người dùng</Link>}{user.role === 'admin' && <Link href="/api-key" aria-current={path.startsWith('/api-key') ? 'page' : undefined}>API key</Link>}{user.role === 'admin' && <Link href="/kiem-tra" aria-current={path.startsWith('/kiem-tra') ? 'page' : undefined}>Kiểm tra</Link>}</nav><div className="row">
88 unmodified lines89909192939488 unmodified linesexport const getCostSettings = () => call<{ settings: CostSettings | null }>('/api/cost-settings');export const saveCostSettings = (settings: CostSettings | null) => call<{ settings: CostSettings | null }>('/api/cost-settings', jsonBody('PUT', { settings }));/** Hoá đơn tháng: chi phí cố định (admin nhập) + khoản nào đã thanh toán; chỉ admin sửa được */export interface FixedCost { id: string; name: string; amount: number; from: string }export interface Billing { fixed: FixedCost[]; paid: Record<string, string[]>; updatedAt: number; updatedBy: string }export const getBilling = () => call<Billing>('/api/billing');88 unmodified lines899091929394959697989910010188 unmodified linesexport const getCostSettings = () => call<{ settings: CostSettings | null }>('/api/cost-settings');export const saveCostSettings = (settings: CostSettings | null) => call<{ settings: CostSettings | null }>('/api/cost-settings', jsonBody('PUT', { settings }));/** Hoá đơn tháng: chi phí cố định (admin nhập) + khoản nào đã thanh toán; chỉ admin sửa được */export interface GeminiKeyRow { id: string; label: string; hint: string; enabled: boolean; calls: number; limited: number; lastUsedAt?: number; lastError?: string; lastErrorAt?: number; cooldownUntil?: number }export const listGeminiKeys = () => call<{ keys: GeminiKeyRow[] }>('/api/gemini-keys');export const addGeminiKeys = (keys: string, label: string) => call<{ added: number; skipped: number }>('/api/gemini-keys', jsonBody('POST', { keys, label }));export const updateGeminiKey = (id: string, patch: { label?: string; enabled?: boolean }) => call(`/api/gemini-keys/${id}`, jsonBody('PATCH', patch));export const deleteGeminiKey = (id: string) => call(`/api/gemini-keys/${id}`, { method: 'DELETE' });export const testGeminiKey = (body: { id?: string; key?: string }) => call<{ ok: boolean; error?: string }>('/api/gemini-keys/test', jsonBody('POST', body));export const resetGeminiCooldown = (id?: string) => call('/api/gemini-keys/reset', jsonBody('POST', { id }));export interface FixedCost { id: string; name: string; amount: number; from: string }export interface Billing { fixed: FixedCost[]; paid: Record<string, string[]>; updatedAt: number; updatedBy: string }export const getBilling = () => call<Billing>('/api/billing');
passport-check/.env.example+1-1
passport-check/README.md+1-1
passport-check/apps/server/src/gemini-keys.tsAdded+81
passport-check/apps/server/src/gemini.ts+148-13
passport-check/apps/server/src/index.ts+15-3
passport-check/apps/web/src/app/(app)/api-key/page.tsxAdded+8
passport-check/apps/web/src/components/GeminiKeys.tsxAdded+130
passport-check/apps/web/src/components/Home.tsx+1-1
passport-check/apps/web/src/components/Shell.tsx+1
passport-check/apps/web/src/lib/api.ts+7