Spaces:
Running
Running
Deploy 5313b66 từ GitHub Actions
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignore+18-11
- .env.example+58-10
- .gitattributesAdded+1
- .gitignore+29-15
- CaddyfileAdded+32
- Dockerfile+55-24
- README.md+24-180
- extractor/.dockerignoreAdded+12
- extractor/.env.exampleAdded+13
- extractor/.gitignoreAdded+21
- extractor/DockerfileAdded+26
- HUGGINGFACE_DEPLOY.md → extractor/HUGGINGFACE_DEPLOY.mdRenamed
- extractor/README.mdAdded+202
- package.json → extractor/package.jsonRenamed
- pnpm-lock.yaml → extractor/pnpm-lock.yamlRenamed
- public/app.js → extractor/public/app.jsRenamed+7-7
- public/index.html → extractor/public/index.htmlRenamed
- public/styles.css → extractor/public/styles.cssRenamed
- server/controllers/archiveController.js → extractor/server/controllers/archiveController.jsRenamed
- server/index.js → extractor/server/index.jsRenamed
- server/middleware/security.js → extractor/server/middleware/security.jsRenamed
- server/routes/api.js → extractor/server/routes/api.jsRenamed
- server/services/extractionService.js → extractor/server/services/extractionService.jsRenamed
- server/utils/fileTree.js → extractor/server/utils/fileTree.jsRenamed
- passport-check/.dockerignoreAdded+11
- passport-check/.env.exampleAdded+61
- passport-check/.github/workflows/deploy.ymlAdded+32
- passport-check/.gitignoreAdded+42
- passport-check/CaddyfileAdded+6
- passport-check/DockerfileAdded+30
- passport-check/FEATURES.mdAdded+120
- passport-check/README.mdAdded+204
- passport-check/apps/server/build.mjsAdded+13
- passport-check/apps/server/package.jsonAdded+29
- passport-check/apps/server/src/auth.tsAdded+54
- passport-check/apps/server/src/cost-settings.tsAdded+59
- passport-check/apps/server/src/firebase.tsAdded+43
- passport-check/apps/server/src/gemini.tsAdded+98
- passport-check/apps/server/src/heic-convert.d.tsAdded+4
- passport-check/apps/server/src/index.tsAdded+413
- passport-check/apps/server/src/jobs.tsAdded+531
- passport-check/apps/server/src/media.tsAdded+104
- passport-check/apps/server/src/ocr.tsAdded+88
- passport-check/apps/server/src/telegram.tsAdded+85
- passport-check/apps/server/src/tokens.tsAdded+219
- passport-check/apps/server/src/upload.tsAdded+159
- passport-check/apps/server/src/users.tsAdded+273
- passport-check/apps/server/templates/cong-van-bp.xlsxAdded
- passport-check/apps/server/templates/thong-tin-ho-chieu.xlsxAdded
- passport-check/apps/server/tsconfig.jsonAdded+1
123456789101112node_modules.git.gitignore.env.idea.DS_Storeuploadsextractednpm-debug.logpnpm-debug.log12345678910111213141516171819.git.github**/node_modules**/dist**/.next**/.open-next**/.env*!**/.env.example**/*.tsbuildinfopassport-check/.backuppassport-check/.playwright-mcppassport-check/lowpassport-check/samplespassport-check/*.xlsxpassport-check/*.docxpassport-check/tessdata/*.traineddata.gz!passport-check/tessdata/mrz.traineddata.gzextractor/uploadsextractor/extracted
12345678910111213# Server ConfigurationPORT=3000# File Size Limits (in bytes)MAX_FILE_SIZE=104857600MAX_EXTRACTED_FILE_SIZE=52428800# Session Configuration (in milliseconds)SESSION_TIMEOUT=3600000# Rate LimitingRATE_LIMIT_WINDOW=3600000RATE_LIMIT_MAX=1012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# =====================================================================# BACKEND (Hugging Face Space) — đặt trong Settings → Variables and secrets# =====================================================================# ---------- Bảo mật (bắt buộc)# Khoá chung giữa Next.js và backend; chỉ server Next.js biết. Tạo: openssl rand -base64 48BACKEND_API_KEY=# Khoá ký token phiên đăng nhập. Tạo: openssl rand -base64 48 (đổi khoá = đăng xuất mọi người)AUTH_SECRET=# số ngày phiên đăng nhập còn hiệu lựcAUTH_TOKEN_DAYS=7# ---------- Admin đầu tiên (chỉ dùng khi bảng users còn trống)ADMIN_EMAIL=# để trống nếu admin chỉ đăng nhập Google; nếu đặt thì >= 8 ký tựADMIN_PASSWORD=# (tuỳ chọn) email đăng nhập Google lần đầu được tự thêm vào bảng users, cách nhau dấu phẩy; "@congty.vn" = cả tên miềnALLOWED_EMAILS=# ---------- Firebase (bắt buộc) — Firestore + xác minh đăng nhập Google# Service account: Firebase Console → Project settings → Service accounts → Generate new private key.# Dán nguyên JSON (hoặc base64 của JSON) vào secret này.FIREBASE_SERVICE_ACCOUNT=# ---------- Telegram (bắt buộc) — nơi lưu ảnh gốcTELEGRAM_BOT_TOKEN=TELEGRAM_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)GEMINI_IMAGE_TOKENS=# (tuỳ chọn) đơn giá mặc định cho trang chi phí, USD / 1 triệu token (mặc định 0.25 / 1.5 — Gemini 3.1 Flash-Lite trả phí, tier Standard)GEMINI_PRICE_INPUT=GEMINI_PRICE_OUTPUT=# ---------- Tuỳ chỉnh (không bắt buộc)OCR_CONCURRENCY=1LLM_CONCURRENCY=2OCR_WORKERS=2MAX_IMAGE_MB=40MAX_ZIP_MB=1024MAX_ZIP_ENTRIES=5000IMAGE_CACHE_MB=500TELEGRAM_MIN_INTERVAL_MS=1100RATE_LIMIT=600# =====================================================================# FRONTEND (Next.js) — biến môi trường phía server, không gửi cho trình duyệt# =====================================================================# URL Space backend, vd https://ten-ban-passport-check.hf.spaceBACKEND_URL=http://localhost:7860# giống hệt BACKEND_API_KEY ở trên# BACKEND_API_KEY=# Cấu hình Firebase web app (công khai) cho nút Google:# Project settings → General → Your apps → Web app → SDK setup (Config)FIREBASE_WEB_CONFIG=# cookie Secure: mặc định bật khi NODE_ENV=production# COOKIE_SECURE=true
1passport-check/tessdata/mrz.traineddata.gz filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021# Dependenciesnode_modules/# Environment files.env# Upload and extraction directoriesuploads/extracted/# OS files.DS_StoreThumbs.db# IDE.vscode/.idea/# Logs*.lognpm-debug.log*1234567891011121314151617181920212223242526272829303132333435node_modulesdist.next.open-next*.tsbuildinfo.env*!.env.exampleextractor/uploads/extractor/extracted/# secret triển khai (token HF/Cloudflare, API key) — KHÔNG commitdeploy.txt*.pem*.key.dev.vars.wrangler/# dữ liệu / file cục bộ trong thư mục apppassport-check/.backup/passport-check/.playwright-mcp/passport-check/low/passport-check/samples/passport-check/FEATURES.docxpassport-check/tessdata/*.traineddata.gz!passport-check/tessdata/mrz.traineddata.gz# log, cache, coverage, file hệ thống/IDE*.logcoverage/.turbo/.cache/.DS_StoreThumbs.db.idea/.vscode/
1234567891011121314151617181920212223242526272829303132# Cổng duy nhất HF mở ra (7860). Chia traffic theo tiền tố; các app chỉ nghe ở 127.0.0.1.{ admin off auto_https off persist_config off}
:7860 { request_body { max_size 1100MB }
redir /extractor /extractor/ 308
# Extractor: bỏ tiền tố /extractor trước khi chuyển vào app handle_path /extractor/* { reverse_proxy 127.0.0.1:3001 }
# Backend Passport Check (chỉ Cloudflare Worker gọi tới, kèm x-api-key): bỏ tiền tố /passport-check handle_path /passport-check/* { reverse_proxy 127.0.0.1:8080 { flush_interval -1 } }
redir / /extractor/ 302
handle { respond "Không tìm thấy" 404 }}1234567891011121314151617181920212223242526FROM node:20-slimWORKDIR /appENV NODE_ENV=productionENV HOST=0.0.0.0ENV PORT=7860ENV SESSION_TIMEOUT=3600000ENV MAX_FILE_SIZE=104857600ENV MAX_EXTRACTED_FILE_SIZE=52428800ENV RATE_LIMIT_WINDOW=3600000ENV RATE_LIMIT_MAX=10COPY package.json ./COPY pnpm-lock.yaml ./RUN corepack enable && corepack prepare pnpm@10.33.4 --activate \&& pnpm install --frozen-lockfileCOPY . .RUN mkdir -p uploads extractedEXPOSE 7860CMD ["pnpm", "start"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657# Space gộp nhiều app trong 1 container, Caddy ở cổng 7860 chia traffic:# /passport-check/* -> backend Express của Passport Check (passport-check/apps/server, 127.0.0.1:8080)# /extractor/* -> Archive Extractor (extractor/, 127.0.0.1:3001)# / -> chuyển sang /extractor/# Frontend Passport Check (Next.js) KHÔNG nằm ở đây — deploy riêng lên Cloudflare Worker (xem .github/workflows/deploy-cloudflare.yml)# ---------- Build Passport Check (chỉ backend)FROM node:22-slim AS build-passportWORKDIR /appRUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*COPY passport-check/package.json passport-check/package-lock.json ./COPY passport-check/packages/core/package.json packages/core/COPY passport-check/apps/server/package.json apps/server/COPY passport-check/apps/web/package.json apps/web/RUN npm ci --workspace apps/server --include-workspace-rootCOPY passport-check/packages packagesCOPY passport-check/apps/server apps/serverCOPY passport-check/scripts scriptsCOPY passport-check/tessdata tessdataCOPY passport-check/tsconfig.base.json ./ENV NEXT_TELEMETRY_DISABLED=1RUN npm run tessdata \&& npm -w apps/server run build \&& npm prune --omit=dev --workspace apps/server --include-workspace-root# ---------- Build Archive ExtractorFROM node:22-slim AS build-extractorWORKDIR /app/extractorCOPY extractor/package.json extractor/pnpm-lock.yaml ./RUN corepack enable && corepack prepare pnpm@10.33.4 --activate && pnpm install --frozen-lockfile --prodCOPY extractor/ ./# ---------- ChạyFROM node:22-slimENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 \TEMPLATE_DIR=/app/passport-server/apps/server/templates TESSDATA_DIR=/app/passport-server/tessdata \SESSION_TIMEOUT=3600000 MAX_FILE_SIZE=104857600 MAX_EXTRACTED_FILE_SIZE=52428800 RATE_LIMIT_WINDOW=3600000 RATE_LIMIT_MAX=10 \XDG_DATA_HOME=/tmp/caddy-data XDG_CONFIG_HOME=/tmp/caddy-configWORKDIR /appCOPY --from=caddy:2 /usr/bin/caddy /usr/local/bin/caddy# backendCOPY --from=build-passport --chown=node:node /app/node_modules /app/passport-server/node_modulesCOPY --from=build-passport --chown=node:node /app/apps/server/dist /app/passport-server/apps/server/distCOPY --from=build-passport --chown=node:node /app/apps/server/templates /app/passport-server/apps/server/templatesCOPY --from=build-passport --chown=node:node /app/tessdata /app/passport-server/tessdataCOPY --from=build-passport --chown=node:node /app/package.json /app/passport-server/# extractorCOPY --from=build-extractor --chown=node:node /app/extractor /app/extractorRUN mkdir -p /app/extractor/uploads /app/extractor/extracted && chown node:node /app/extractor/uploads /app/extractor/extractedCOPY --chown=node:node Caddyfile start.sh /app/# HF Spaces chạy với uid 1000 (= user node)USER nodeEXPOSE 7860CMD ["/app/start.sh"]
8 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012028 unmodified lineslicense: mit---# Archive ExtractorA production-ready web application for uploading, extracting, and managing compressed file archives (ZIP and RAR). Features a modern dark-themed UI with drag-and-drop upload, tree view file explorer, and secure file handling.## Features- 📦 **Multi-format Support**: Extract ZIP and RAR archives- 🔄 **Nested Archive Handling**: Automatically extracts archives within archives- 🌲 **Interactive File Tree**: Collapsible tree view with file type icons- ⬇️ **Flexible Downloads**: Download individual files or entire folders as ZIP- 🎨 **Modern UI**: Dark theme with glassmorphism effects and animations- 📱 **Responsive Design**: Works on desktop and mobile devices- 🔒 **Security First**: Path traversal prevention, magic bytes validation, rate limiting## Prerequisites- Node.js v18 or higher- npm or yarn## Installation1. **Clone or download the project**2. **Install dependencies**```bashnpm install```3. **Configure environment** (optional)```bashcp .env.example .env# Edit .env to customize settings```4. **Start the server**```bashnpm start```5. **Open in browser**```http://localhost:3000```## DevelopmentRun with auto-reload on file changes:```bashnpm run dev```## ConfigurationAll settings are configurable via environment variables:| Variable | Default | Description ||----------|---------|-------------|| `PORT` | 3000 | Server port || `MAX_FILE_SIZE` | 104857600 | Max upload size in bytes (100MB) || `MAX_EXTRACTED_FILE_SIZE` | 52428800 | Max extracted file size (50MB) || `SESSION_TIMEOUT` | 3600000 | Auto-cleanup timeout in ms (1 hour) || `RATE_LIMIT_WINDOW` | 3600000 | Rate limit window in ms (1 hour) || `RATE_LIMIT_MAX` | 10 | Max uploads per window per IP |## API Endpoints### Upload Archive```httpPOST /api/uploadContent-Type: multipart/form-datafile: <archive file>```**Response (200)**:```json{"success": true,"sessionId": "uuid-v4","filename": "archive.zip","stats": {"totalFiles": 42,"totalSize": 1048576}}```### Get File Tree```httpGET /api/files/:sessionId```**Response (200)**:```json{"success": true,"sessionId": "uuid-v4","tree": {"name": "root","type": "folder","path": "/","children": [...]}}```### Download File```httpGET /api/download/:sessionId/file?path=/path/to/file.txt```### Download Folder as ZIP```httpGET /api/download/:sessionId/folder?path=/path/to/folder```### Delete Session```httpDELETE /api/session/:sessionId```## Error ResponsesAll errors return a consistent format:```json{"error": true,"message": "Human-readable description","code": "ERROR_CODE"}```| Code | HTTP Status | Description ||------|-------------|-------------|| `INVALID_FILE_TYPE` | 400 | Unsupported file extension || `INVALID_MAGIC_BYTES` | 400 | File content doesn't match extension || `FILE_TOO_LARGE` | 400 | File exceeds size limit || `INVALID_PATH` | 400 | Path contains traversal or is absolute || `SESSION_NOT_FOUND` | 404 | Session expired or doesn't exist || `FILE_NOT_FOUND` | 404 | Requested file doesn't exist || `PASSWORD_PROTECTED` | 422 | Archive requires a password || `CORRUPTED_ARCHIVE` | 422 | Archive is damaged || `RATE_LIMIT_EXCEEDED` | 429 | Too many requests || `INTERNAL_ERROR` | 500 | Server error |## Security Features- **Magic Bytes Validation**: Verifies file content matches extension- **Path Traversal Prevention**: Blocks `..` and absolute paths- **Filename Sanitization**: Removes special characters- **Rate Limiting**: 10 uploads per IP per hour- **Helmet Integration**: HTTP security headers- **Zip Bomb Protection**: 50MB limit per extracted file- **Isolated Sessions**: Each upload gets a unique UUID directory- **Automatic Cleanup**: Sessions expire after 1 hour## Project Structure```/project-root├── server/│ ├── index.js # Express app entry point│ ├── routes/│ │ └── api.js # API route definitions│ ├── controllers/│ │ └── archiveController.js # Request handlers│ ├── services/│ │ └── extractionService.js # ZIP/RAR extraction logic│ ├── middleware/│ │ └── security.js # Validation & security│ └── utils/│ └── fileTree.js # Tree generation utility├── public/│ ├── index.html # Main HTML page│ ├── styles.css # CSS styling│ └── app.js # Frontend JavaScript├── uploads/ # Temporary upload storage├── extracted/ # Session extraction folders├── package.json├── .env.example└── README.md```## LicenseMIT License - Feel free to use in your projects!# extract-server8 unmodified lines9101112131415161718192021222324252627282930313233343536373839404142434445468 unmodified lineslicense: mit---# Space: backend Passport Check + Archive ExtractorMột container, Caddy chia traffic ở cổng 7860:| Đường dẫn | App | Nội bộ ||---|---|---|| `/passport-check/` | Backend Express của Passport Check (chỉ Cloudflare Worker gọi, cần `x-api-key`) | `127.0.0.1:8080` || `/extractor/` | Archive Extractor | `127.0.0.1:3001` || `/` | chuyển sang `/extractor/` | |**Frontend** Passport Check (Next.js) chạy riêng trên **Cloudflare Worker** `passport-check-web`, gọi backend qua`BACKEND_URL=https://<space>.hf.space/passport-check` + `BACKEND_API_KEY`.## Cấu trúc repo```extractor/ Archive Extractor (lấy từ Space cũ)passport-check/ Passport Check (apps/web = frontend, apps/server = backend, packages/core)Dockerfile image cho Space: backend + extractor + CaddyCaddyfile start.sh.github/workflows/deploy-hf.yml build thử image rồi đẩy source lên Space.github/workflows/deploy-cloudflare.yml build + deploy frontend lên Cloudflare Worker```## Cấu hình GitHub (Settings → Secrets and variables → Actions)| Tên | Loại | Dùng cho ||---|---|---|| `HF_TOKEN` | secret | token HF quyền ghi || `HF_SPACE` | variable | vd `bacteriaqh/extractor` || `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID` | secret | deploy Worker (token cần quyền Workers Scripts: Edit) || `BACKEND_URL`, `BACKEND_API_KEY`, `FIREBASE_WEB_CONFIG` | secret | đẩy lên Worker làm secret; `BACKEND_API_KEY` phải trùng với secret của Space |Secrets runtime của backend (`BACKEND_API_KEY`, `AUTH_SECRET`, `FIREBASE_SERVICE_ACCOUNT`, `TELEGRAM_*`, `ADMIN_EMAIL`, `GEMINI_*`...) đặt trong Settings → Variables and secrets của Space — xem `.env.example` và `passport-check/README.md`.
123456789101112node_modules.git.gitignore.env.idea.DS_Store
uploadsextracted
npm-debug.logpnpm-debug.log12345678910111213# Server ConfigurationPORT=3000
# File Size Limits (in bytes)MAX_FILE_SIZE=104857600MAX_EXTRACTED_FILE_SIZE=52428800
# Session Configuration (in milliseconds)SESSION_TIMEOUT=3600000
# Rate LimitingRATE_LIMIT_WINDOW=3600000RATE_LIMIT_MAX=10123456789101112131415161718192021# Dependenciesnode_modules/
# Environment files.env
# Upload and extraction directoriesuploads/extracted/
# OS files.DS_StoreThumbs.db
# IDE.vscode/.idea/
# Logs*.lognpm-debug.log*1234567891011121314151617181920212223242526FROM node:20-slim
WORKDIR /app
ENV NODE_ENV=productionENV HOST=0.0.0.0ENV PORT=7860ENV SESSION_TIMEOUT=3600000ENV MAX_FILE_SIZE=104857600ENV MAX_EXTRACTED_FILE_SIZE=52428800ENV RATE_LIMIT_WINDOW=3600000ENV RATE_LIMIT_MAX=10
COPY package.json ./COPY pnpm-lock.yaml ./
RUN corepack enable && corepack prepare pnpm@10.33.4 --activate \ && pnpm install --frozen-lockfile
COPY . .
RUN mkdir -p uploads extracted
EXPOSE 7860
CMD ["pnpm", "start"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202---title: File Shareemoji: 📤colorFrom: indigocolorTo: purplesdk: dockerapp_port: 7860pinned: falselicense: mit---
# Archive Extractor
A production-ready web application for uploading, extracting, and managing compressed file archives (ZIP and RAR). Features a modern dark-themed UI with drag-and-drop upload, tree view file explorer, and secure file handling.

## Features
- 📦 **Multi-format Support**: Extract ZIP and RAR archives- 🔄 **Nested Archive Handling**: Automatically extracts archives within archives- 🌲 **Interactive File Tree**: Collapsible tree view with file type icons- ⬇️ **Flexible Downloads**: Download individual files or entire folders as ZIP- 🎨 **Modern UI**: Dark theme with glassmorphism effects and animations- 📱 **Responsive Design**: Works on desktop and mobile devices- 🔒 **Security First**: Path traversal prevention, magic bytes validation, rate limiting
## Prerequisites
- Node.js v18 or higher- npm or yarn
## Installation
1. **Clone or download the project**
2. **Install dependencies** ```bash npm install ```
3. **Configure environment** (optional) ```bash cp .env.example .env # Edit .env to customize settings ```
4. **Start the server** ```bash npm start ```
5. **Open in browser** ``` http://localhost:3000 ```
## Development
Run with auto-reload on file changes:```bashnpm run dev```
## Configuration
All settings are configurable via environment variables:
| Variable | Default | Description ||----------|---------|-------------|| `PORT` | 3000 | Server port || `MAX_FILE_SIZE` | 104857600 | Max upload size in bytes (100MB) || `MAX_EXTRACTED_FILE_SIZE` | 52428800 | Max extracted file size (50MB) || `SESSION_TIMEOUT` | 3600000 | Auto-cleanup timeout in ms (1 hour) || `RATE_LIMIT_WINDOW` | 3600000 | Rate limit window in ms (1 hour) || `RATE_LIMIT_MAX` | 10 | Max uploads per window per IP |
## API Endpoints
### Upload Archive```httpPOST /api/uploadContent-Type: multipart/form-data
file: <archive file>```
**Response (200)**:```json{ "success": true, "sessionId": "uuid-v4", "filename": "archive.zip", "stats": { "totalFiles": 42, "totalSize": 1048576 }}```
### Get File Tree```httpGET /api/files/:sessionId```
**Response (200)**:```json{ "success": true, "sessionId": "uuid-v4", "tree": { "name": "root", "type": "folder", "path": "/", "children": [...] }}```
### Download File```httpGET /api/download/:sessionId/file?path=/path/to/file.txt```
### Download Folder as ZIP```httpGET /api/download/:sessionId/folder?path=/path/to/folder```
### Delete Session```httpDELETE /api/session/:sessionId```
## Error Responses
All errors return a consistent format:```json{ "error": true, "message": "Human-readable description", "code": "ERROR_CODE"}```
| Code | HTTP Status | Description ||------|-------------|-------------|| `INVALID_FILE_TYPE` | 400 | Unsupported file extension || `INVALID_MAGIC_BYTES` | 400 | File content doesn't match extension || `FILE_TOO_LARGE` | 400 | File exceeds size limit || `INVALID_PATH` | 400 | Path contains traversal or is absolute || `SESSION_NOT_FOUND` | 404 | Session expired or doesn't exist || `FILE_NOT_FOUND` | 404 | Requested file doesn't exist || `PASSWORD_PROTECTED` | 422 | Archive requires a password || `CORRUPTED_ARCHIVE` | 422 | Archive is damaged || `RATE_LIMIT_EXCEEDED` | 429 | Too many requests || `INTERNAL_ERROR` | 500 | Server error |
## Security Features
- **Magic Bytes Validation**: Verifies file content matches extension- **Path Traversal Prevention**: Blocks `..` and absolute paths- **Filename Sanitization**: Removes special characters- **Rate Limiting**: 10 uploads per IP per hour- **Helmet Integration**: HTTP security headers- **Zip Bomb Protection**: 50MB limit per extracted file- **Isolated Sessions**: Each upload gets a unique UUID directory- **Automatic Cleanup**: Sessions expire after 1 hour
## Project Structure
```/project-root├── server/│ ├── index.js # Express app entry point│ ├── routes/│ │ └── api.js # API route definitions│ ├── controllers/│ │ └── archiveController.js # Request handlers│ ├── services/│ │ └── extractionService.js # ZIP/RAR extraction logic│ ├── middleware/│ │ └── security.js # Validation & security│ └── utils/│ └── fileTree.js # Tree generation utility├── public/│ ├── index.html # Main HTML page│ ├── styles.css # CSS styling│ └── app.js # Frontend JavaScript├── uploads/ # Temporary upload storage├── extracted/ # Session extraction folders├── package.json├── .env.example└── README.md```
## License
MIT License - Feel free to use in your projects!# extract-server402 unmodified lines40340440540640740840945 unmodified lines455456457458459460461125 unmodified lines58758858959059159259359417 unmodified lines61261361461561661761813 unmodified lines63263363463563663763860 unmodified lines699700701702703704705402 unmodified linesstate.uploadInProgress = false;});xhr.open('POST', '/api/upload');xhr.send(formData);}45 unmodified lines*/async function loadFileTree(sessionId, filename, stats, accessCode = sessionId, sessionMeta = {}) {try {const response = await fetch(`/api/files/${sessionId}`);const data = await response.json();if (!response.ok) {125 unmodified linesconst relativePath = path.startsWith('/') ? path.slice(1) : path;const endpoint = type === 'folder'? `/api/download/${state.currentSessionId}/folder?path=${encodeURIComponent(relativePath)}`: `/api/download/${state.currentSessionId}/file?path=${encodeURIComponent(relativePath)}`;// Create temporary link and click itconst link = document.createElement('a');17 unmodified lines}const relativePath = path.startsWith('/') ? path.slice(1) : path;const endpoint = `/api/view/${state.currentSessionId}/file?path=${encodeURIComponent(relativePath)}`;window.open(endpoint, '_blank', 'noopener,noreferrer');}13 unmodified lines// Clean up current sessionif (!skipDelete && state.currentSessionId) {fetch(`/api/session/${state.currentSessionId}`, { method: 'DELETE' }).catch(console.error);}60 unmodified linestry {elements.openAccessCodeBtn.disabled = true;elements.openAccessCodeBtn.textContent = 'Opening...';const response = await fetch(`/api/files/${accessCode}`);const data = await response.json();if (!response.ok) {throw new Error(data.message || 'Unable to open this code');402 unmodified lines40340440540640740840945 unmodified lines455456457458459460461125 unmodified lines58758858959059159259359417 unmodified lines61261361461561661761813 unmodified lines63263363463563663763860 unmodified lines699700701702703704705402 unmodified linesstate.uploadInProgress = false;});xhr.open('POST', 'api/upload');xhr.send(formData);}45 unmodified lines*/async function loadFileTree(sessionId, filename, stats, accessCode = sessionId, sessionMeta = {}) {try {const response = await fetch(`api/files/${sessionId}`);const data = await response.json();if (!response.ok) {125 unmodified linesconst relativePath = path.startsWith('/') ? path.slice(1) : path;const endpoint = type === 'folder'? `api/download/${state.currentSessionId}/folder?path=${encodeURIComponent(relativePath)}`: `api/download/${state.currentSessionId}/file?path=${encodeURIComponent(relativePath)}`;// Create temporary link and click itconst link = document.createElement('a');17 unmodified lines}const relativePath = path.startsWith('/') ? path.slice(1) : path;const endpoint = `api/view/${state.currentSessionId}/file?path=${encodeURIComponent(relativePath)}`;window.open(endpoint, '_blank', 'noopener,noreferrer');}13 unmodified lines// Clean up current sessionif (!skipDelete && state.currentSessionId) {fetch(`api/session/${state.currentSessionId}`, { method: 'DELETE' }).catch(console.error);}60 unmodified linestry {elements.openAccessCodeBtn.disabled = true;elements.openAccessCodeBtn.textContent = 'Opening...';const response = await fetch(`api/files/${accessCode}`);const data = await response.json();if (!response.ok) {throw new Error(data.message || 'Unable to open this code');
1234567891011node_modules**/node_modules**/dist**/.nextsamples.playwright-mcp.backup.env**/.env*tessdata/eng.traineddata.gztessdata/vie.traineddata.gz12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# =====================================================================# BACKEND (Hugging Face Space) — đặt trong Settings → Variables and secrets# =====================================================================
# ---------- Bảo mật (bắt buộc)# Khoá chung giữa Next.js và backend; chỉ server Next.js biết. Tạo: openssl rand -base64 48BACKEND_API_KEY=# Khoá ký token phiên đăng nhập. Tạo: openssl rand -base64 48 (đổi khoá = đăng xuất mọi người)AUTH_SECRET=# số ngày phiên đăng nhập còn hiệu lựcAUTH_TOKEN_DAYS=7
# ---------- Admin đầu tiên (chỉ dùng khi bảng users còn trống)ADMIN_EMAIL=# để trống nếu admin chỉ đăng nhập Google; nếu đặt thì >= 8 ký tựADMIN_PASSWORD=# (tuỳ chọn) email đăng nhập Google lần đầu được tự thêm vào bảng users, cách nhau dấu phẩy; "@congty.vn" = cả tên miềnALLOWED_EMAILS=
# ---------- Firebase (bắt buộc) — Firestore + xác minh đăng nhập Google# Service account: Firebase Console → Project settings → Service accounts → Generate new private key.# Dán nguyên JSON (hoặc base64 của JSON) vào secret này.FIREBASE_SERVICE_ACCOUNT=
# ---------- Telegram (bắt buộc) — nơi lưu ảnh gốcTELEGRAM_BOT_TOKEN=TELEGRAM_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)GEMINI_IMAGE_TOKENS=# (tuỳ chọn) đơn giá mặc định cho trang chi phí, USD / 1 triệu token (mặc định 0.25 / 1.5 — Gemini 3.1 Flash-Lite trả phí, tier Standard)GEMINI_PRICE_INPUT=GEMINI_PRICE_OUTPUT=
# ---------- Tuỳ chỉnh (không bắt buộc)OCR_CONCURRENCY=1LLM_CONCURRENCY=2OCR_WORKERS=2MAX_IMAGE_MB=50MAX_ZIP_MB=50MAX_ZIP_ENTRIES=5000IMAGE_CACHE_MB=500TELEGRAM_MIN_INTERVAL_MS=1100RATE_LIMIT=600
# =====================================================================# FRONTEND (Next.js) — biến môi trường phía server, không gửi cho trình duyệt# =====================================================================# URL Space backend, vd https://ten-ban-passport-check.hf.spaceBACKEND_URL=http://localhost:7860# giống hệt BACKEND_API_KEY ở trên# BACKEND_API_KEY=# Cấu hình Firebase web app (công khai) cho nút Google:# Project settings → General → Your apps → Web app → SDK setup (Config)FIREBASE_WEB_CONFIG=# cookie Secure: mặc định bật khi NODE_ENV=production# COOKIE_SECURE=true1234567891011121314151617181920212223242526272829303132name: Deploy to OCI
on: push: branches: [main] workflow_dispatch:
concurrency: group: deploy cancel-in-progress: false
jobs: deploy: runs-on: ubuntu-latest steps: - name: Cấu hình SSH env: OCI_SSH_KEY: ${{ secrets.OCI_SSH_KEY }} OCI_HOST: ${{ secrets.OCI_HOST }} run: | install -m 700 -d ~/.ssh printf '%s\n' "$OCI_SSH_KEY" > ~/.ssh/id_deploy chmod 600 ~/.ssh/id_deploy ssh-keyscan -H "$OCI_HOST" >> ~/.ssh/known_hosts
- name: Pull và build lại trên VM env: OCI_HOST: ${{ secrets.OCI_HOST }} OCI_USER: ${{ secrets.OCI_USER }} run: | ssh -i ~/.ssh/id_deploy "$OCI_USER@$OCI_HOST" \ 'set -e; cd ~/passport-check && git pull --ff-only && docker compose up -d --build && docker image prune -f'123456789101112131415161718192021222324252627282930313233343536373839404142node_modulesdist# model ngôn ngữ tải bằng `npm run tessdata`; mrz.traineddata.gz (bản int đã chuyển đổi) được committessdata/*.traineddata.gz!tessdata/mrz.traineddata.gzsamples/*.traineddata.env.env*.local# khoá Firebase / log emulator — KHÔNG commit*firebase-adminsdk*.jsonservice-account*.json.firebase/*-debug.log# file Excel mẫu gốc chứa dữ liệu khách thật — chỉ dùng để sinh template, KHÔNG commit/*.xlsx.nextnext-env.d.ts*.tsbuildinfo.backup/
# secret triển khai / dữ liệu thật — KHÔNG commit.env*!.env.examplelow/.playwright-mcp/FEATURES.docx
# build Cloudflare/OpenNext, log, cache, file hệ thống/IDE.open-next.wrangler/.dev.vars*.logcoverage/.turbo/.cache/.DS_StoreThumbs.db.idea/.vscode/*.pem*.key123456{$SITE_DOMAIN} { request_body { max_size 500MB } reverse_proxy web:3000}123456789101112131415161718192021222324252627282930# Backend — Hugging Face Spaces (Docker SDK), 1 container Node ở port 7860.# Frontend Next.js deploy riêng (xem apps/web/Dockerfile); trình duyệt không gọi thẳng vào Space này.FROM node:22-slim AS buildWORKDIR /appRUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*COPY package.json package-lock.json ./COPY packages/core/package.json packages/core/COPY apps/server/package.json apps/server/COPY apps/web/package.json apps/web/RUN npm ci --workspace apps/server --include-workspace-rootCOPY packages packagesCOPY apps/server apps/serverCOPY scripts scriptsCOPY tessdata tessdataCOPY tsconfig.base.json ./RUN npm run tessdata && npm -w apps/server run build && npm prune --omit=dev --workspace apps/server --include-workspace-root
FROM node:22-slimENV NODE_ENV=production PORT=7860 \ TEMPLATE_DIR=/app/apps/server/templates TESSDATA_DIR=/app/tessdataWORKDIR /appCOPY --from=build --chown=node:node /app/node_modules ./node_modulesCOPY --from=build --chown=node:node /app/apps/server/dist ./apps/server/distCOPY --from=build --chown=node:node /app/apps/server/templates ./apps/server/templatesCOPY --from=build --chown=node:node /app/tessdata ./tessdataCOPY --from=build --chown=node:node /app/package.json ./# HF Spaces chạy với uid 1000 (= user node)USER nodeEXPOSE 7860CMD ["node", "apps/server/dist/server.js"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120# Tính năng & tiến độ — Passport Check
> Cập nhật: 09/11/2026 · Trạng thái chung: **MVP hoàn thành, sẵn sàng chạy thử trên HF Spaces**>> Kiểm tra lúc cập nhật: `npm test` 27/27 pass · `npm run typecheck` sạch · không còn TODO/FIXME trong code.
Chú thích: ✅ xong · 🟡 xong một phần / có giới hạn · ⬜ chưa làm
---
## 1. Tổng quan tiến độ
| Mảng | Trạng thái | Ghi chú ||---|---|---|| Đăng nhập & phân quyền | ✅ | Firebase Auth, whitelist email/tên miền || Upload ảnh / thư mục / zip | ✅ | Chống trùng theo SHA-256 || Lưu ảnh gốc (Telegram) | ✅ | Có xếp hàng, chờ theo `retry_after` || OCR + kiểm chứng MRZ | ✅ | 2 engine, ~60 ngôn ngữ VIZ, 2 lượt nhanh/kỹ || Gemini hỗ trợ ảnh khó | ✅ | Tuỳ chọn theo lô, kết quả vẫn kiểm checksum || Duyệt / sửa kết quả | ✅ | || Hồ sơ thị thực theo đoàn | ✅ | Thông tin đoàn, ghi đè riêng từng khách || Danh sách khách (gộp đoàn) | ✅ | Lọc, tìm, chọn nhanh, xoá nhiều, phân trang || Xuất Excel theo mẫu (DVC, Biên phòng) + CSV | ✅ | Giữ dropdown, định dạng mẫu || Khôi phục job khi restart | ✅ | Ảnh chưa lên Telegram phải upload lại || Triển khai (Docker / HF Spaces) | ✅ | 1 instance || Kiểm thử tự động | 🟡 | Có unit test core; chưa có test server/web || Mở rộng nhiều instance | ⬜ | Thiết kế hiện tại giữ state trong RAM |
---
## 2. Chi tiết tính năng
### 2.1 Xác thực & bảo mật- ✅ Đăng nhập Google hoặc email/mật khẩu (đã xác minh) qua Firebase Auth.- ✅ Chỉ email trong `ALLOWED_EMAILS` được dùng; hỗ trợ cả tên miền (`@congty.vn`).- ✅ `firestore.rules` chặn toàn bộ truy cập Firestore trực tiếp từ trình duyệt; chỉ server (Admin SDK) đọc/ghi.- ✅ Rate limit API (`RATE_LIMIT`, mặc định 600 req/phút).- ✅ Bot token Telegram không bao giờ tới trình duyệt; ảnh đi qua server và yêu cầu đăng nhập.- 🟡 Ảnh trên Telegram lưu nguyên bản, **không mã hoá**: an toàn phụ thuộc vào việc giữ kênh riêng tư.
### 2.2 Upload & lưu trữ- ✅ Upload ảnh lẻ, cả thư mục hoặc `.zip` (JPG, PNG, WebP, HEIC, TIFF…).- ✅ Mỗi lần upload là một **lô** (= một đoàn); upload chia nhóm, có thanh tiến độ.- ✅ Chống trùng: trùng trong lô thì bỏ qua; trùng với lô khác thì dùng lại file và kết quả cũ.- ✅ Lưu ảnh gốc dạng document (không nén) lên kênh Telegram; ảnh > 19,5MB được nén trước khi gửi.- ✅ Chuẩn hoá ảnh, sinh thumbnail, cache ảnh trên ổ tạm (`IMAGE_CACHE_MB`).- ✅ Giới hạn kích thước cấu hình được: `MAX_IMAGE_MB`, `MAX_ZIP_MB`, `MAX_ZIP_ENTRIES`.
### 2.3 OCR & kiểm chứng- ✅ Tự xoay, chỉnh nghiêng, cắt vùng MRZ; đọc bằng 2 engine độc lập (model MRZ chuyên dụng + `eng`).- ✅ Parse MRZ TD3 / TD2 / TD1 / visa; kiểm 5 check digit theo ICAO 9303.- ✅ Sửa lỗi OCR theo loại ô (O↔0, I↔1…).- ✅ Đọc vùng chữ (VIZ) bằng model ngôn ngữ của nước cấp (~60 ngôn ngữ, bảng trong `packages/core/src/langs.ts`).- ✅ Đối chiếu tên MRZ với chữ in, kiểm logic ngày, chấm độ tin cậy `Cao` / `Trung bình` / `Thấp`.- ✅ Lượt nhanh trước, chỉ ảnh chưa đạt `Cao` mới chạy lượt kỹ.- ✅ Chạy lại OCR cho từng ảnh (`rerun`).- ✅ Gemini tuỳ chọn theo lô: không bao giờ / ảnh độ tin cậy thấp / mọi ảnh chưa chắc chắn / tất cả.
### 2.4 Duyệt & quản lý dữ liệu- ✅ Trang lô: xem tiến độ OCR thời gian thực (chỉ tải ảnh vừa thay đổi, 3 giây/lần).- ✅ Bảng kết quả, panel duyệt/sửa tay, đánh dấu đã duyệt, xoá ảnh.- ✅ Link xem lại ảnh `/b/<lô>/i/<ảnh>` (yêu cầu đăng nhập).- ✅ Kết quả lưu Firestore; server giữ toàn bộ dữ liệu trong RAM, chỉ đọc Firestore 1 lần khi khởi động.
### 2.5 Hồ sơ thị thực theo đoàn- ✅ **Thông tin đoàn** điền một lần: mã đoàn, ngày nhập cảnh, số ngày lưu trú, nhập cảnh nhiều lần, cách nhận/nơi nhận visa, mục đích, VIP, khẩn, cơ quan cấp, hướng hành trình.- ✅ Sửa riêng từng khách; ô ghi đè hiển thị nhãn "riêng".- ✅ Tự tính ngày xuất cảnh = ngày nhập cảnh + số ngày lưu trú − 1.- ✅ Tự gán nghề nghiệp theo tuổi tại ngày nhập cảnh (≥ 60 tuổi: "Hưu trí", còn lại "Nhân viên").- ✅ Cảnh báo hộ chiếu còn hạn < 6 tháng (ở danh sách, form chi tiết và khi xuất).
### 2.6 Danh sách khách (`/khach`)- ✅ Gộp khách của mọi đoàn.- ✅ Lọc theo cột, tìm kiếm, lọc nhanh (hộ chiếu < 6 tháng / cần duyệt / khẩn).- ✅ Chọn nhanh theo đoàn, xoá nhiều dòng, phân trang 100 dòng.
### 2.7 Xuất file- ✅ *Thông tin hộ chiếu (nộp DVC)*: sheet `INF_NHAN_SU`, tên file `ThongTinHoChieu-<mã đoàn>-<số khách>.xlsx`.- ✅ *Công văn biên phòng*: sheet `BP`, giá trị dạng `nhãn|mã`, tên file sửa được trước khi tải.- ✅ Điền vào file mẫu, giữ dropdown, sheet danh mục ẩn và định dạng có điều kiện; xếp Nam trước, Nữ sau.- ✅ Kiểm tra trước khi xuất (`/export/check`) và cảnh báo thiếu dữ liệu / hộ chiếu sắp hết hạn.- ✅ Xuất CSV; Excel có cột link xem ảnh.- ✅ Script `scripts/make-templates.ts` sinh lại file mẫu + danh mục khi cơ quan đổi mẫu.
### 2.8 Vận hành & triển khai- ✅ Dockerfile multi-stage cho HF Spaces (port 7860, user `node`).- ✅ Hàng đợi job, khôi phục khi Space khởi động lại (lấy lại ảnh từ Telegram để OCR tiếp).- ✅ Chạy local với Firebase Emulator.- 🟡 Chỉ đúng khi chạy **1 instance** (state nằm trong RAM).
### 2.9 Kiểm thử & đo chất lượng- ✅ Unit test `packages/core`: MRZ, chọn ngôn ngữ, logic visa (3 file, 27 test).- ✅ `npm run samples`: sinh 8 ảnh hộ chiếu tổng hợp + `ground_truth.csv`.- ✅ `npm run eval`: đo độ chính xác OCR (lượt nhanh / kỹ).- ⬜ Chưa có test cho `apps/server` (API, upload, jobs) và `apps/web`.- ⬜ Chưa có CI chạy test/typecheck tự động.
---
## 3. Việc còn lại / đề xuất
Các mục dưới đây là đề xuất dựa trên giới hạn hiện tại, chưa phải cam kết.
| Ưu tiên | Việc | Lý do ||---|---|---|| Cao | Thêm CI (test + typecheck) | Hiện chỉ kiểm tra thủ công || Cao | Test tích hợp cho API server (upload, export, phân quyền) | Phần quan trọng nhất chưa có test || Trung bình | Ghi lại kết quả `npm run eval` làm mốc độ chính xác | Để theo dõi khi chỉnh pipeline OCR || Trung bình | Mã hoá ảnh trước khi gửi Telegram | Ảnh hộ chiếu đang lưu nguyên bản || Trung bình | Bổ sung bộ ảnh mẫu thực tế (đã ẩn danh) cho eval | 8 ảnh tổng hợp chưa đại diện hết ca khó || Thấp | Hỗ trợ nhiều instance (đồng bộ state qua Firestore listener / Redis) | Chỉ cần khi vượt sức 1 Space || Thấp | Theo dõi quota Firestore (50k đọc / 20k ghi mỗi ngày gói Spark) | Tránh chạm giới hạn khi xử lý lô lớn |
---
## 4. Lịch sử cập nhật
| Ngày | Nội dung ||---|---|| 09/11/2026 | Tạo tài liệu; MVP đủ các mảng 2.1 – 2.8 |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204---title: Passport Checkemoji: 🛂colorFrom: bluecolorTo: graysdk: dockerapp_port: 7860pinned: false---
# Passport Check
Web app trích xuất thông tin hộ chiếu hàng loạt từ một thư mục ảnh, kiểm chứng bằng **check digit MRZ (ICAO 9303)**.
## Kiến trúc
```Trình duyệt ──cookie httpOnly──▶ Next.js (apps/web) ──x-api-key + token phiên──▶ Backend Express trên HF Space (apps/server) · trang render ở server · Firestore, Telegram, OCR, Gemini · /api/* = proxy phía server · bảng users, cấp token phiên```
- Trình duyệt **chỉ gọi Next.js** (`/api/...` cùng tên miền). Next.js mới gọi backend, kèm `BACKEND_API_KEY` và token phiên lấy từ cookie httpOnly. Trình duyệt không biết URL backend, API key hay token.- Backend từ chối mọi request không có `BACKEND_API_KEY`, nên URL Space công khai cũng không gọi thẳng được.- Upload ảnh/zip, tải ảnh, tải file Excel đều được stream qua Next.js (không giữ cả file trong RAM).
## Đăng nhập & người dùng
- **Google**: trình duyệt mở popup Google (Firebase Auth), gửi ID token **một lần** cho Next.js (`/api/auth/google`); backend xác minh bằng firebase-admin, rồi khớp email với **bảng `users`** (Firestore). Sau đó trình duyệt đăng xuất Firebase; phiên thật nằm trong cookie của Next.js.- **Email / mật khẩu**: chỉ dùng được cho tài khoản mà admin đã đặt mật khẩu (băm scrypt). Không có đăng ký tự do.- Bảng `users`: `email`, `name`, `role` (`admin` | `user`), `disabled`, `passwordHash` (tuỳ chọn), `tokenVersion`, `lastLoginAt`… Admin quản lý ở trang **Người dùng** (`/nguoi-dung`): thêm, đổi quyền, khoá, đặt/bỏ mật khẩu, xoá. Khoá / đổi mật khẩu / hạ quyền sẽ huỷ ngay mọi phiên đang mở của người đó.- Admin đầu tiên: khi bảng trống, backend tự tạo từ `ADMIN_EMAIL` (+ `ADMIN_PASSWORD` nếu muốn đăng nhập bằng mật khẩu).- `ALLOWED_EMAILS` (tuỳ chọn): email Google khớp danh sách này mà chưa có trong bảng sẽ được **tự thêm** với quyền `user` khi đăng nhập lần đầu.- Mỗi người tự đặt / đổi mật khẩu ở trang **Tài khoản** (`/tai-khoan`).
## Cách hoạt động
1. **Đăng nhập** bằng Google hoặc email/mật khẩu (xem trên).2. **Upload** ảnh, cả thư mục, hoặc file `.zip` (JPG, PNG, WebP, HEIC, TIFF…). Mỗi lần upload tạo một **lô**. Ảnh trùng (cùng nội dung) trong lô bị bỏ qua; ảnh đã có ở lô khác thì dùng lại file và kết quả cũ.3. **Lưu ảnh gốc lên Telegram**: server gửi file (dạng document, không nén) vào kênh / nhóm riêng qua bot, lưu `file_id`. HF Spaces free không có ổ đĩa bền, nên Telegram là nơi giữ ảnh lâu dài.4. **OCR trên server** (tesseract.js + sharp, model chuyên MRZ + tiếng Anh): - Tự xoay, tự chỉnh nghiêng, cắt vùng MRZ, đọc bằng 2 engine độc lập. - Sau khi biết nước cấp, đọc thêm vùng chữ bằng model ngôn ngữ của nước đó (VNM→`vie`, FRA→`fra`, BEL→`nld+fra`, CHN→`chi_sim`…, khoảng 60 ngôn ngữ, bảng trong `packages/core/src/langs.ts`). - Chạy lượt nhanh trước; ảnh chưa đạt độ tin cậy `Cao` mới chạy lượt kỹ.5. **Kiểm chứng**: - Parse MRZ (TD3/TD2/TD1/visa), kiểm 5 check digit, sửa lỗi OCR theo loại ô (O/0, I/1…). - Đối chiếu tên với chữ in trên trang, kiểm logic ngày. - Chấm độ tin cậy `Cao` / `Trung bình` / `Thấp`.6. **Gemini (tuỳ chọn)**: chọn cho từng lô khi nào hỏi Gemini (không bao giờ / ảnh độ tin cậy thấp / mọi ảnh chưa chắc chắn / tất cả). Kết quả Gemini cũng bị kiểm checksum lại. Gemini chạy ở hàng đợi riêng (`LLM_CONCURRENCY`, mặc định 2), nên trong lúc chờ Gemini server vẫn OCR ảnh khác.7. **Kết quả lưu Firestore**: xem, sửa tay, duyệt, xuất **Excel** / **CSV**. File Excel có cột link xem ảnh.8. **Link xem lại ảnh**: `/b/<lô>/i/<ảnh>`. Người mở phải đăng nhập; server tải ảnh từ Telegram rồi trả về, bot token không bao giờ tới trình duyệt.
## Hồ sơ thị thực theo đoàn
- **Mỗi lô upload là một đoàn.** Trong trang của lô, điền **Thông tin đoàn** một lần cho cả đoàn: - phân tách khách hàng (mã đoàn), ngày nhập cảnh, số ngày lưu trú; - nhập cảnh nhiều lần, cách nhận thị thực, nơi nhận visa, mục đích; - VIP, khẩn, cơ quan cấp, hướng hành trình.- Trên form chi tiết từng khách vẫn sửa riêng được; ô nào sửa riêng có chữ "riêng".- **Ngày xuất cảnh** = ngày nhập cảnh + số ngày lưu trú − 1.- **Nghề nghiệp**: tự theo tuổi tại ngày nhập cảnh (từ 60 tuổi là "Hưu trí", còn lại "Nhân viên"); sửa riêng được.- **Cảnh báo hộ chiếu còn hạn dưới 6 tháng** tính từ ngày nhập cảnh (chưa có ngày thì tính từ hôm nay). Cảnh báo hiện ở danh sách, ở form chi tiết và khi xuất file.- **Danh sách khách** (`/khach`): gộp mọi đoàn. - Lọc theo từng cột, tìm kiếm, lọc nhanh (hộ chiếu dưới 6 tháng / cần duyệt / khẩn). - "Chọn nhanh" theo đoàn, xoá nhiều dòng, phân trang 100 dòng. - "Xuất ra excel" xuất các dòng đã chọn, nếu chưa chọn thì xuất toàn bộ theo bộ lọc.- **Hai file xuất**, điền vào file mẫu nên giữ nguyên dropdown, sheet danh mục ẩn và định dạng có điều kiện. Cả hai **xếp toàn bộ Nam lên trên, Nữ xuống dưới**: - *Thông tin hộ chiếu (nộp DVC)*: sheet `INF_NHAN_SU`, tên file `ThongTinHoChieu-<mã đoàn>-<số khách>.xlsx`. - *Công văn biên phòng*: sheet `BP`, giá trị dạng `nhãn|mã`; tên file sửa được trước khi tải.
File mẫu nằm ở `apps/server/templates/`, sinh từ 2 file Excel thật bằng:
```bashnpx tsx scripts/make-templates.ts ThongTinHoChieu-....xlsx "XE 1 CV ....xlsx"```
Script xoá toàn bộ dữ liệu khách khỏi file mẫu và sinh lại danh mục `packages/core/src/visa-lists.ts`. Các file `.xlsx` gốc ở thư mục gốc đã bị chặn commit qua `.gitignore` vì chứa dữ liệu khách thật. Khi cơ quan đổi mẫu, chạy lại script với file mẫu mới.
Dữ liệu Firestore:
| Collection | Nội dung ||---|---|| `batches/{id}` | Lô upload: tên, người tạo, cấu hình Gemini, bộ đếm kết quả || `batches/{id}/items/{id}` | Từng ảnh: trạng thái, thumbnail, tham chiếu Telegram, kết quả trích xuất || `hashes/{sha256}` | Chống trùng: ảnh đã lưu Telegram + số item đang dùng |
Server giữ toàn bộ lô và khách trong RAM: chỉ đọc Firestore 1 lần lúc khởi động, sau đó mọi danh sách, bộ lọc và phân trang chạy trên RAM, nên không tốn lượt đọc. Cách này chỉ đúng khi chạy **1 instance** (như HF Space). Không chạy nhiều bản server cùng lúc trên cùng project Firebase.
Khi Space khởi động lại giữa chừng:- Ảnh **đã lên Telegram** được OCR tiếp, ảnh lấy lại từ Telegram.- Ảnh **chưa kịp lên Telegram** (chỉ nằm trên ổ tạm) báo lỗi "hãy upload lại".
## Cài đặt
### 1. Firebase
1. Tạo project ở [console.firebase.google.com](https://console.firebase.google.com).2. **Authentication** → Sign-in method: bật **Google** (không cần Email/Password — mật khẩu do backend tự quản lý).3. Authentication → Settings → **Authorized domains**: thêm tên miền của **frontend Next.js** (VD `passport.congty.vn`).4. **Firestore Database** → tạo database (production mode).5. Tab **Rules** → dán nội dung file `firestore.rules`: chặn mọi truy cập trực tiếp từ trình duyệt; chỉ server (Admin SDK) đọc/ghi. Hoặc chạy `firebase deploy --only firestore:rules`.6. Project settings → **Service accounts** → *Generate new private key*, dùng làm `FIREBASE_SERVICE_ACCOUNT`.7. Project settings → General → thêm **Web app**, copy object cấu hình làm `FIREBASE_WEB_CONFIG` (đặt ở **frontend**).
Gói free (Spark): mỗi ngày 50.000 lượt đọc, 20.000 lượt ghi. Mỗi ảnh tốn khoảng 5 lượt ghi, nên dùng được khoảng 4.000 ảnh/ngày. Trang lô đang chạy chỉ tải những ảnh vừa thay đổi (20 giây/lần).
### 2. Telegram
1. Tạo bot với [@BotFather](https://t.me/BotFather), lấy token làm `TELEGRAM_BOT_TOKEN`.2. Tạo **kênh hoặc nhóm riêng tư**, thêm bot làm admin (quyền đăng tin và xoá tin).3. Lấy ID chat, dạng `-100…`: đăng 1 tin trong kênh rồi mở `https://api.telegram.org/bot<token>/getUpdates`, xem `chat.id`. Dùng giá trị này làm `TELEGRAM_CHAT_ID`.
Giới hạn của bot:- Gửi file tối đa 50MB, tải về tối đa 20MB (ảnh lớn hơn 19,5MB được server nén lại trước khi gửi).- Khoảng 20 tin/phút với nhóm. Server tự xếp hàng và chờ theo `retry_after` khi bị giới hạn.
> ⚠ Ảnh lưu **nguyên bản, không mã hoá** trên Telegram. Ai vào được kênh/nhóm đều xem được ảnh hộ chiếu. Giữ kênh riêng tư, chỉ có bot và người cần thiết.
### 3. Backend — Hugging Face Spaces (free)
1. Tạo Space mới, SDK **Docker** (dùng `Dockerfile` ở thư mục gốc, chỉ build backend). Space để Public cũng được vì mọi API đòi `BACKEND_API_KEY`.2. Settings → Variables and secrets. Bắt buộc: - `BACKEND_API_KEY`, `AUTH_SECRET` — mỗi cái tạo bằng `openssl rand -base64 48` - `FIREBASE_SERVICE_ACCOUNT` - `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.js
Chạy ở bất cứ đâu có Node 22 (VPS, Docker, Cloud Run, Render…). Biến môi trường (phía server):
- `BACKEND_URL` = `https://<user>-<space>.hf.space`- `BACKEND_API_KEY` = giống backend- `FIREBASE_WEB_CONFIG` = cấu hình web app Firebase (bỏ trống thì ẩn nút Google)
Docker: `docker build -f apps/web/Dockerfile -t passport-check-web . && docker run -p 3000:3000 --env-file .env passport-check-web`
> ⚠ Upload đi xuyên qua Next.js nên nền tảng chạy frontend phải cho phép request body lớn và request chạy lâu. **Vercel** (giới hạn body ~4,5MB/request) **không hợp** cho upload zip; nên dùng VPS / Docker / Cloud Run.
> Gemini API gói miễn phí có thể dùng dữ liệu gửi lên để cải thiện sản phẩm của Google. Với hộ chiếu thật nên dùng API key có bật billing, hoặc tắt Gemini cho lô đó.
## Chạy local
```bashnpm installnpm run tessdata # tải eng + ~60 model ngôn ngữ (~110MB); hoặc: npm run tessdata -- vie fra# tạo .env (backend) + apps/web/.env.local (Next.js), tự sinh BACKEND_API_KEY / AUTH_SECRET,# chuyển file service account JSON thành base64 trong FIREBASE_SERVICE_ACCOUNT (app không đọc file JSON)npm run setup:env -- --sa ~/path/to/xxx-firebase-adminsdk.json [--web firebase-web-config.json]# rồi điền tay vào .env: TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID, ADMIN_EMAIL (+ ADMIN_PASSWORD nếu muốn)npm run dev:server # backend http://localhost:7860 (đọc .env)npm run dev:web # Next.js http://localhost:3000 (đọc apps/web/.env.local)# production: npm run build && npm start (backend) và npm run start:web (frontend)```
Chạy với Firebase Emulator (không cần project thật):
```bashnpx firebase-tools emulators:start --only auth,firestore --project demo-passport-check# backend (firebase.json của emulator đặt firestore 8085, auth 9099)FIRESTORE_EMULATOR_HOST=127.0.0.1:8085 FIREBASE_AUTH_EMULATOR_HOST=127.0.0.1:9099 GCLOUD_PROJECT=demo-passport-check \ BACKEND_API_KEY=<>=32 ký tự> AUTH_SECRET=<>=32 ký tự> ADMIN_EMAIL=admin@example.com ADMIN_PASSWORD=adminpass123 \ ALLOWED_EMAILS=@example.com TELEGRAM_BOT_TOKEN=... TELEGRAM_CHAT_ID=... npm start# frontend: nút Google dùng Auth emulatorBACKEND_URL=http://127.0.0.1:7860 BACKEND_API_KEY=<như trên> FIREBASE_AUTH_EMULATOR_PUBLIC_URL=http://127.0.0.1:9099 \ GCLOUD_PROJECT=demo-passport-check npm run start:web```
Docker backend: `docker build -t passport-check . && docker run -p 7860:7860 --env-file .env passport-check`
## Kiểm thử
```bashnpm test # unit test MRZ / VIZ / reconcilenpm run samples # sinh 8 ảnh hộ chiếu tổng hợp (nhân vật hư cấu) + ground_truth.csvnpm run eval -- samples fast # đo độ chính xác OCR (fast = lượt nhanh, thorough = lượt kỹ)```
Model MRZ (`tessdata/mrz.traineddata.gz`) là bản integer chuyển đổi từ [DoubangoTelecom/tesseractMRZ](https://github.com/DoubangoTelecom/tesseractMRZ) vì bản float gốc không chạy trên tesseract.js (WASM). Tạo lại: `scripts/convert-mrz-model.sh` (cần Docker).
## Cấu trúc
- `packages/core` — parse MRZ, sửa lỗi, VIZ, pipeline OCR, chọn ngôn ngữ theo nước, đối chiếu & chấm điểm, kiểu dữ liệu Firestore- `apps/web` — Next.js (App Router): - `src/app/(app)/*` — các trang; layout server kiểm tra phiên + cấu hình backend - `src/app/api/[...path]` — proxy phía server sang backend (stream upload / ảnh / xlsx) - `src/app/api/auth/*`, `api/me/password` — đăng nhập Google / mật khẩu, đăng xuất, đổi mật khẩu (đặt cookie) - `src/lib/server/backend.ts` — gọi backend, cookie phiên (chỉ chạy trên server) - `src/components` — upload (chia nhóm, có tiến độ), danh sách lô, duyệt/sửa, xuất Excel, quản lý người dùng- `apps/server` — Express (backend trên HF Space): - `auth.ts` — kiểm `BACKEND_API_KEY` + token phiên, phân quyền admin - `users.ts` — bảng users, đăng nhập Google / mật khẩu, token phiên - `firebase.ts` — Firestore + firebase-admin - `templates/` — file Excel mẫu để xuất hồ sơ - `telegram.ts` — lưu / tải ảnh - `upload.ts` — multipart + zip - `media.ts` — chuẩn hoá ảnh, thumbnail, cache - `jobs.ts` — hàng đợi, khôi phục khi khởi động lại - `ocr.ts`, `gemini.ts`- `firestore.rules` — chặn truy cập Firestore trực tiếp từ trình duyệt12345678910111213import { build } from 'esbuild';await build({ entryPoints: ['src/index.ts'], bundle: true, platform: 'node', format: 'esm', target: 'node22', outfile: 'dist/server.js', // native / worker-based packages giữ ngoài bundle external: ['sharp', 'tesseract.js', '@google/genai', 'express', 'express-rate-limit', 'firebase-admin', 'busboy', 'yauzl', 'heic-convert'], banner: { js: "import { createRequire as __pcCreateRequire } from 'module'; const require = __pcCreateRequire(import.meta.url);" }, logLevel: 'info',});1234567891011121314151617181920212223242526272829{ "name": "@pc/server", "version": "0.1.0", "private": true, "type": "module", "scripts": { "dev": "node --watch --env-file-if-exists=../../.env --import tsx src/index.ts", "build": "node build.mjs" }, "dependencies": { "@google/genai": "^3.0.0", "@pc/core": "*", "busboy": "^1.6.0", "express": "^5.3.0", "express-rate-limit": "^8.7.3", "firebase-admin": "^14.5.0", "heic-convert": "^2.1.0", "sharp": "^0.35.5", "tesseract.js": "^7.0.0", "yauzl": "^3.4.0" }, "devDependencies": { "@types/busboy": "^1.5.5", "@types/express": "^5", "@types/yauzl": "^3.4.0", "esbuild": "^0.28.2", "tsx": "^4.23.15" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354/** * Xác thực request vào backend: * 1. `x-api-key` = BACKEND_API_KEY — chỉ server Next.js biết khoá này, nên trình duyệt / người ngoài không gọi thẳng * được backend (kể cả khi URL Space công khai). * 2. `Authorization: Bearer <token phiên>` — token do /api/auth/login cấp, Next.js giữ trong cookie httpOnly. */import crypto from 'node:crypto';import type { NextFunction, Request, Response } from 'express';import { hasCostAccess, userFromToken, type Role } from './users.ts';
export interface User { uid: string; email: string; name?: string; role: Role; costAccess: boolean }declare module 'express-serve-static-core' { interface Request { user?: User }}
const API_KEY = process.env.BACKEND_API_KEY ?? '';export const apiKeyConfigured = () => API_KEY.length >= 32;
function keyOk(got: string | undefined): boolean { if (!got || !apiKeyConfigured()) return false; const a = crypto.createHash('sha256').update(got).digest(); const b = crypto.createHash('sha256').update(API_KEY).digest(); return crypto.timingSafeEqual(a, b);}
/** Chỉ cho server Next.js (có BACKEND_API_KEY) gọi vào */export function requireApiKey(req: Request, res: Response, next: NextFunction) { if (!apiKeyConfigured()) return void res.status(503).json({ error: 'Backend chưa cấu hình BACKEND_API_KEY (>= 32 ký tự)' }); if (!keyOk(req.get('x-api-key'))) return void res.status(401).json({ error: 'Sai API key', code: 'bad_api_key' }); next();}
/** IP thật của người dùng (Next.js chuyển tiếp qua `x-client-ip`; chỉ tin vì request đã qua API key) */export const clientIp = (req: Request) => req.get('x-client-ip') || req.ip || '';
export function requireUser(req: Request, res: Response, next: NextFunction) { const token = /^Bearer (.+)$/.exec(req.get('authorization') ?? '')?.[1]; if (!token) return void res.status(401).json({ error: 'Chưa đăng nhập', code: 'unauthenticated' }); const u = userFromToken(token); if (!u) return void res.status(401).json({ error: 'Phiên đăng nhập hết hạn, hãy đăng nhập lại', code: 'unauthenticated' }); req.user = { uid: u.id, email: u.email, name: u.name || undefined, role: u.role, costAccess: hasCostAccess(u) }; next();}
export function requireAdmin(req: Request, res: Response, next: NextFunction) { if (req.user?.role !== 'admin') return void res.status(403).json({ error: 'Chỉ admin mới làm được việc này', code: 'forbidden' }); next();}
/** Trang Chi phí Gemini: admin hoặc user được cấp quyền */export function requireCostAccess(req: Request, res: Response, next: NextFunction) { if (!req.user?.costAccess) return void res.status(403).json({ error: 'Bạn chưa được cấp quyền xem chi phí', code: 'forbidden' }); next();}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859/** * Đơn giá & cách tính trên trang Chi phí Gemini — dùng chung cho mọi người (Firestore `settings/cost`). * Ai có quyền xem trang chi phí đều đọc được; chỉ admin sửa được. * Chưa ai lưu -> null, trang chi phí dùng giá mặc định của model. */import { db } from './firebase.ts';
export type CostBasis = 'all' | 'sent';export interface CostSettings { input: number; output: number; thinking: number; rate: number; basis: CostBasis; updatedAt: number; updatedBy: string;}
const ref = () => db().collection('settings').doc('cost');let cache: CostSettings | null | undefined;
export async function getCostSettings(): Promise<CostSettings | null> { if (cache === undefined) { const snap = await ref().get(); cache = snap.exists ? (snap.data() as CostSettings) : null; } return cache;}
const httpError = (message: string) => Object.assign(new Error(message), { status: 400 });
function num(x: unknown, label: string, max: number): number { if (typeof x !== 'number' || !Number.isFinite(x) || x < 0 || x > max) throw httpError(`${label} không hợp lệ (0 – ${max.toLocaleString('vi-VN')})`); return x;}
/** body = null -> xoá, về giá mặc định */export async function saveCostSettings(body: unknown, by: string): Promise<CostSettings | null> { if (body === null) { await ref().delete(); cache = null; return null; } if (!body || typeof body !== 'object') throw httpError('Dữ liệu không hợp lệ'); const o = body as Record<string, unknown>; if (o.basis !== 'all' && o.basis !== 'sent') throw httpError('Cách tính không hợp lệ'); const s: CostSettings = { input: num(o.input, 'Giá input', 10_000), output: num(o.output, 'Giá output', 10_000), thinking: Math.round(num(o.thinking, 'Token thinking', 1_000_000)), rate: num(o.rate, 'Tỷ giá', 1_000_000), basis: o.basis, updatedAt: Date.now(), updatedBy: by, }; await ref().set(s); cache = s; return s;}12345678910111213141516171819202122232425262728293031323334353637383940414243/** * Firebase Admin: Firestore (lô, khách, người dùng) + xác minh ID token đăng nhập Google (Firebase Auth). * Phiên đăng nhập do backend tự cấp — xem users.ts. * * Biến môi trường: * - FIREBASE_SERVICE_ACCOUNT: JSON service account (nguyên văn hoặc base64) * - Chạy emulator: FIRESTORE_EMULATOR_HOST, FIREBASE_AUTH_EMULATOR_HOST, GCLOUD_PROJECT */import { cert, initializeApp, type App } from 'firebase-admin/app';import { getFirestore, type Firestore } from 'firebase-admin/firestore';
let app: App | null = null;let firestore: Firestore | null = null;
function parseJson(raw: string): Record<string, unknown> { const s = raw.trim(); return JSON.parse(s.startsWith('{') ? s : Buffer.from(s, 'base64').toString('utf8'));}
const emulator = !!process.env.FIRESTORE_EMULATOR_HOST;
export function firebaseConfigured(): boolean { return emulator || !!process.env.FIREBASE_SERVICE_ACCOUNT;}
export function fbApp(): App { if (app) return app; if (emulator) { app = initializeApp({ projectId: process.env.GCLOUD_PROJECT ?? 'demo-passport-check' }); } else { if (!process.env.FIREBASE_SERVICE_ACCOUNT) throw new Error('Chưa cấu hình FIREBASE_SERVICE_ACCOUNT'); app = initializeApp({ credential: cert(parseJson(process.env.FIREBASE_SERVICE_ACCOUNT) as never) }); } return app;}
export function db(): Firestore { if (!firestore) { firestore = getFirestore(fbApp()); firestore.settings({ ignoreUndefinedProperties: true }); } return firestore;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798/** * Tầng leo thang LLM: gửi ảnh cho Gemini, ép đầu ra theo JSON schema. * Kết quả KHÔNG được tin trực tiếp — client/core sẽ kiểm checksum MRZ và đối chiếu lại. */import { GoogleGenAI } from '@google/genai';import 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 });
export const SCHEMA = { type: 'object', properties: { isPassport: { type: 'boolean', description: 'true nếu ảnh là trang thông tin của hộ chiếu / giấy tờ có MRZ' }, mrzLines: { type: 'array', items: { type: 'string' }, description: 'Các dòng MRZ chép CHÍNH XÁC từng ký tự như in trên ảnh (mỗi dòng 44 ký tự với hộ chiếu), giữ nguyên ký tự <. Không tự sửa. Mảng rỗng nếu không thấy MRZ.', }, documentCode: str('Loại giấy tờ in ở ô Type trên vùng chữ, VD P, PP, PD'), issuingState: str('Mã quốc gia cấp 3 chữ cái (ICAO)'), surname: str('Họ, theo chữ Latin như in trên trang'), givenNames: str('Tên, theo chữ Latin như in trên trang'), fullNameNative: str('Họ tên đầy đủ như in trên vùng chữ, GIỮ NGUYÊN dấu / chữ gốc (VD: NGUYỄN VĂN AN). Rỗng nếu không có.'), documentNumber: str('Số hộ chiếu in trên vùng chữ'), nationality: str('Quốc tịch, mã 3 chữ cái nếu có, nếu không thì như in'), birthDate: str('Ngày sinh dạng YYYY-MM-DD'), sex: str('M, F hoặc X'), placeOfBirth: str('Nơi sinh như in trên trang (giữ dấu). Nếu in song ngữ "bản địa/Latin" (VD 江苏/JIANGSU) thì chỉ lấy phần Latin'), placeOfIssue: str('Nơi cấp như in trên trang (nếu có). Nếu in song ngữ thì chỉ lấy phần Latin'), issueDate: str('Ngày cấp dạng YYYY-MM-DD'), expiryDate: str('Ngày hết hạn dạng YYYY-MM-DD'), authority: str('Cơ quan cấp như in trên trang'), personalNumber: str('Số cá nhân / số định danh nếu có'), notes: str('Ghi chú ngắn nếu ảnh mờ, bị che, hoặc trường nào không chắc chắn'), }, required: ['isPassport', 'mrzLines'],};
const PROMPT = `Bạn là hệ thống trích xuất dữ liệu hộ chiếu. Đọc ảnh và trả JSON theo schema.Quy tắc:- Chỉ ghi những gì THẤY rõ trên ảnh. Trường không đọc được thì để chuỗi rỗng. Tuyệt đối không đoán hay bịa.- MRZ: chép nguyên văn từng ký tự, kể cả ký tự '<'. Không sửa cho khớp check digit.- Phân biệt kỹ 0/O, 1/I, 5/S, 8/B, 2/Z trong MRZ: trong số hộ chiếu, ngày tháng và check digit hầu như là chữ số.- Ngày tháng chuyển về YYYY-MM-DD (lưu ý định dạng ngày/tháng/năm và tên tháng nhiều ngôn ngữ).- Ảnh có thể bị xoay, nghiêng, chói hoặc chụp kèm trang khác — hãy tìm trang thông tin cá nhân.`;
export const promptText = (hint?: string) => (hint ? `${PROMPT}\n\nGợi ý từ OCR local (có thể sai): ${hint}` : PROMPT);const GEN_CONFIG = { temperature: 0, responseMimeType: 'application/json', responseJsonSchema: SCHEMA };
/** Nội dung gửi Gemini — dùng chung cho trích xuất và đếm token để số đếm khớp request thật */function contents(image: Buffer | null, mimeType: string, hint?: string) { return [{ role: 'user', parts: [ ...(image ? [{ inlineData: { mimeType, data: image.toString('base64') } }] : []), { text: promptText(hint) }, ], }];}
/** 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ại if (status === 429 || (status >= 500 && status < 600)) { await new Promise((r) => setTimeout(r, 2000 * 2 ** attempt)); continue; } throw e; } } throw lastErr;}
export async function geminiExtract(image: Buffer, mimeType: string, hint?: string): Promise<LlmOutput> { const res = await withRetry(() => ai().models.generateContent({ model: MODEL, contents: contents(image, mimeType, hint), config: GEN_CONFIG })); return JSON.parse(res.text ?? '') as LlmOutput;}1234declare module 'heic-convert' { function convert(opts: { buffer: ArrayBuffer | Uint8Array; format: 'JPEG' | 'PNG'; quality?: number }): Promise<ArrayBuffer>; export default convert;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413import path from 'node:path';import fs from 'node:fs';import express, { type NextFunction, type Request, type Response } from 'express';import rateLimit from 'express-rate-limit';import { bpFileName, 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 { getCostSettings, saveCostSettings } from './cost-settings.ts';import { authConfigured, changeOwnPassword, createUser, deleteUser, listUsers, loadUsers, login, loginGoogle, updateUser, usersReady } from './users.ts';import { telegramConfigured } from './telegram.ts';import { batchTokens, currentRule, fixedTokens, formulaInfo, itemTokens, usageReport } from './tokens.ts';import { receiveUpload } from './upload.ts';import { allItems, batchById, cacheReady, createBatch, deleteItem, getBatch, getItem, ingest, listBatches, listItems, liveStatus, loadOriginal, recover, knownHashes, rerun, rerunMany, saveEdit, updateBatchInfo,} from './jobs.ts';
const PORT = Number(process.env.PORT ?? 7860);const here = path.dirname(new URL(import.meta.url).pathname);const TEMPLATE_DIR = process.env.TEMPLATE_DIR ?? path.resolve(here, '../templates');const missing = [ !firebaseConfigured() && 'FIREBASE_SERVICE_ACCOUNT', !telegramConfigured() && 'TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID', !authConfigured() && 'AUTH_SECRET (>= 32 ký tự)', !apiKeyConfigured() && 'BACKEND_API_KEY (>= 32 ký tự)',].filter((x): x is string => !!x);const ready = !missing.length;
const app = express();app.disable('x-powered-by');app.set('trust proxy', 1); // HF Spaces đứng sau reverse proxy
// mọi request đều đi qua server Next.js -> đếm theo IP thật của người dùng do Next chuyển tiếpconst limiter = rateLimit({ windowMs: 60_000, limit: Number(process.env.RATE_LIMIT ?? 600), standardHeaders: 'draft-8', legacyHeaders: false, keyGenerator: (req) => clientIp(req), validate: { keyGeneratorIpFallback: false },});// chống dò mật khẩu: 10 lần / 15 phút cho mỗi cặp IP + emailconst loginLimiter = rateLimit({ windowMs: 15 * 60_000, limit: 10, standardHeaders: 'draft-8', legacyHeaders: false, skipSuccessfulRequests: true, keyGenerator: (req) => `${clientIp(req)}|${String(req.body?.email ?? '').toLowerCase()}`, validate: { keyGeneratorIpFallback: false }, message: { error: 'Đăng nhập sai quá nhiều lần, hãy thử lại sau 15 phút' },});const json = express.json({ limit: '2mb' });
/** bọc handler async: lỗi có `status` -> trả đúng mã, còn lại 500 (không lộ chi tiết nội bộ) */const h = (fn: (req: Request, res: Response) => Promise<unknown>) => (req: Request, res: Response, next: NextFunction) => fn(req, res).catch((e) => { if (e?.status && e.status < 500) return void res.status(e.status).json({ error: e.message, code: e.code }); console.error(req.method, req.path, e?.message ?? e); if (!res.headersSent) res.status(500).json({ error: 'Lỗi server' }); else next(e); });
function notReady(_req: Request, res: Response, next: NextFunction) { if (!ready) return void res.status(503).json({ error: `Backend chưa cấu hình: ${missing.join(', ')}` }); const loading = cacheReady(); if (!loading) return void res.status(503).json({ error: 'Server đang khởi động, thử lại sau giây lát' }); // lần đọc bảng user trước lỗi (mạng / Firestore) -> thử đọc lại const users = usersReady() ?? loadUsers(); Promise.all([loading, users]).then(() => next(), () => res.status(503).json({ error: 'Server không đọc được dữ liệu Firebase' }));}
/** Kiểm tra thông tin chuyến đi gửi lên; ô có giá trị sai -> lỗi 400 (không lặng lẽ bỏ qua) */function parseTrip(x: unknown): TripInfo | undefined { if (x === undefined || x === null) return undefined; if (typeof x !== 'object') throw Object.assign(new Error('Thông tin chuyến đi không hợp lệ'), { status: 400 }); const o = x as Record<string, unknown>; const errors: string[] = []; const has = (k: string) => o[k] !== undefined && o[k] !== null; const str = (k: string, label: string, max = 200) => { if (!has(k)) return undefined; if (typeof o[k] !== 'string') { errors.push(label); return undefined; } return (o[k] as string).trim().slice(0, max); }; const bool = (k: string, label: string) => { if (!has(k)) return undefined; if (typeof o[k] !== 'boolean') { errors.push(label); return undefined; } return o[k] as boolean; }; const entryDate = str('entryDate', 'Ngày nhập cảnh', 10); if (entryDate && !/^\d{4}-\d{2}-\d{2}$/.test(entryDate)) errors.push('Ngày nhập cảnh (cần YYYY-MM-DD)'); let stayDays: number | undefined; if (has('stayDays')) { if (typeof o.stayDays === 'number' && Number.isInteger(o.stayDays) && o.stayDays >= 1 && o.stayDays <= 365) stayDays = o.stayDays; else errors.push('Số ngày lưu trú (1–365)'); } const t: TripInfo = { groupCode: str('groupCode', 'Phân tách khách hàng', 60), entryDate, stayDays, multipleEntry: bool('multipleEntry', 'Nhập cảnh nhiều lần'), visaType: str('visaType', 'Cách nhận thị thực'), receivePlace: str('receivePlace', 'Nơi nhận visa'), purpose: str('purpose', 'Mục đích'), vip: bool('vip', 'Vào cửa VIP'), urgent: bool('urgent', 'Khẩn'), authority: str('authority', 'Cơ quan cấp'), direction: str('direction', 'Hướng hành trình'), occupation: str('occupation', 'Nghề nghiệp', 60), }; if (errors.length) throw Object.assign(new Error(`Giá trị không hợp lệ: ${errors.join(', ')}`), { status: 400 }); return t;}
const LLM_POLICIES: LlmPolicy[] = ['off', 'low', 'review', 'all'];
// health check cho HF Space (không lộ thông tin gì)app.get('/', (_req, res) => void res.type('text').send('passport-check backend'));app.get(['/health', '/healthz'], (_req, res) => void res.json({ ok: true, ready, uptime: Math.round(process.uptime()) }));
const pub = express.Router();
pub.get('/config', (_req, res) => { res.json({ ready, missing, llmAvailable: llmAvailable(), model: llmModel() });});
pub.post('/auth/login', json, notReady, loginLimiter, h(async (req, res) => { res.json(await login(req.body?.email, req.body?.password));}));pub.post('/auth/google', json, notReady, h(async (req, res) => { res.json(await loginGoogle(req.body?.idToken));}));
const api = express.Router();api.use(notReady, requireUser);
api.get('/me', (req, res) => res.json(req.user));
/** Tự đổi mật khẩu -> token mới (phiên ở thiết bị khác bị đăng xuất) */api.post('/me/password', json, h(async (req, res) => { res.json(await changeOwnPassword(req.user!.uid, req.body?.current, req.body?.password));}));
/* ---------------------------------------------------------- quản lý người dùng (admin) */
api.get('/users', requireAdmin, (_req, res) => void res.json(listUsers()));api.post('/users', requireAdmin, json, h(async (req, res) => { res.json(await createUser(req.body ?? {}, req.user!.email));}));api.patch('/users/:uid', requireAdmin, json, h(async (req, res) => { const uid = String(req.params.uid); // tự khoá / tự hạ quyền mình dễ gây mất quyền admin -> chặn if (uid === req.user!.uid && (req.body?.disabled === true || req.body?.role === 'user')) { return void res.status(400).json({ error: 'Không thể tự khoá hoặc tự hạ quyền tài khoản của mình' }); } res.json(await updateUser(uid, req.body ?? {}));}));api.delete('/users/:uid', requireAdmin, h(async (req, res) => { await deleteUser(String(req.params.uid), req.user!.uid); res.json({ ok: true });}));
api.get('/batches', h(async (_req, res) => res.json(await listBatches())));
api.post('/batches', json, h(async (req, res) => { const name = String(req.body?.name ?? '').trim().slice(0, 120) || `Lô ${new Date().toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh' })}`; const llm = LLM_POLICIES.includes(req.body?.settings?.llm) ? req.body.settings.llm : 'low'; const settings: BatchSettings = { llm }; res.json(await createBatch(name, settings, { uid: req.user!.uid, email: req.user!.email }));}));
async function batchOr404(id: string) { const b = await getBatch(id); if (!b) throw Object.assign(new Error('Không tìm thấy lô'), { status: 404 }); return b;}
api.patch('/batches/:bid', json, h(async (req, res) => { const name = typeof req.body?.name === 'string' ? req.body.name.trim().slice(0, 120) : undefined; const trip = parseTrip(req.body?.trip); res.json(await updateBatchInfo(String(req.params.bid), { ...(name ? { name } : {}), ...(trip ? { trip } : {}) }));}));
api.get('/batches/:bid', h(async (req, res) => { res.json({ batch: await batchOr404(String(req.params.bid)), live: liveStatus(String(req.params.bid)) });}));
// Upload ảnh / zip (multipart). Có thể gọi nhiều lần cho cùng 1 lô.api.post('/batches/:bid/files', h(async (req, res) => { const bid = String(req.params.bid); await batchOr404(bid); const stats = { added: 0, reused: 0, duplicates: [] as string[], again: [] as string[] }; const reocr = req.query.reocr === '1'; // ảnh trùng đã có kết quả: OCR lại thay vì dùng kết quả cũ const up = await receiveUpload(req, async (files) => { const r = await ingest(bid, req.user!.email, files, reocr); stats.added += r.added; stats.reused += r.reused; stats.duplicates.push(...r.duplicates); stats.again.push(...r.again); }); res.json({ ...stats, skipped: up.skipped });}));
api.get('/batches/:bid/items', h(async (req, res) => { const since = Number(req.query.since ?? 0) || 0; const now = Date.now(); // trả kèm mốc thời gian server để client hỏi tiếp từ đó (trừ lùi 2s phòng lệch giờ ghi) res.json({ items: await listItems(String(req.params.bid), since), next: now - 2000, live: liveStatus(String(req.params.bid)) });}));
async function itemOr404(bid: string, iid: string) { const it = await getItem(bid, iid); if (!it) throw Object.assign(new Error('Không tìm thấy ảnh'), { status: 404 }); return it;}
api.get('/batches/:bid/items/:iid', h(async (req, res) => res.json(await itemOr404(String(req.params.bid), String(req.params.iid)))));
api.get('/batches/:bid/items/:iid/image', h(async (req, res) => { const it = await itemOr404(String(req.params.bid), String(req.params.iid)); const buf = await loadOriginal(it); res.set({ 'content-type': it.mime, 'cache-control': 'private, max-age=86400', 'content-disposition': `inline; filename*=UTF-8''${encodeURIComponent(path.basename(it.name))}` }); res.send(buf);}));
api.patch('/batches/:bid/items/:iid', json, h(async (req, res) => { const result = req.body?.result as ExtractionResult | undefined; if (result && (!result.record || !['HIGH', 'MEDIUM', 'LOW'].includes(result.confidence))) return void res.status(400).json({ error: 'Dữ liệu không hợp lệ' }); const trip = parseTrip(req.body?.trip); res.json(await saveEdit(String(req.params.bid), String(req.params.iid), { result, trip }, req.user!.email));}));
api.post('/batches/:bid/items/:iid/rerun', json, h(async (req, res) => { const force = req.body?.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 });}));
// Kiểm tra trước khi upload: ảnh nào (theo sha256) đã có kết quả -> hỏi người dùng có OCR lại khôngapi.post('/batches/:bid/known', json, h(async (req, res) => { const bid = String(req.params.bid); await batchOr404(bid); const list = Array.isArray(req.body?.hashes) ? (req.body.hashes as unknown[]).filter((x): x is string => typeof x === 'string').slice(0, 5000) : []; res.json({ known: await knownHashes(bid, list) });}));
// OCR lại hàng loạt (VD: ảnh trùng vừa upload mà người dùng muốn xử lý lại)api.post('/batches/:bid/rerun', json, h(async (req, res) => { const bid = String(req.params.bid); await batchOr404(bid); const ids = Array.isArray(req.body?.ids) ? [...new Set((req.body.ids as unknown[]).filter((x): x is string => typeof x === 'string'))].slice(0, 5000) : []; res.json(await rerunMany(bid, ids));}));
/* ---------------------------------------------------------- ước lượng token Gemini (tự tính theo kích thước ảnh, không gọi API) */
// Mọi lô, gộp theo ngày upload (giờ VN) + theo lô; trang chi phí tự gộp tuần / tháng / quý / năm và nhân đơn giáapi.get('/tokens/usage', requireCostAccess, h(async (_req, res) => res.json(await usageReport(allItems(), batchById))));
// Đơ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) => { res.json({ settings: await saveCostSettings(req.body?.settings, req.user!.email) });}));
// Theo lô: tổng + chi tiết từng ảnhapi.get('/batches/:bid/tokens', h(async (req, res) => { const bid = String(req.params.bid); const batch = await batchOr404(bid); res.json({ batchId: bid, batchName: batch.name, ...(await batchTokens(await listItems(bid))) });}));
// Chi tiết 1 ảnh (kèm JSON đầu ra dùng để đếm)api.get('/batches/:bid/items/:iid/tokens', h(async (req, res) => { const it = await itemOr404(String(req.params.bid), String(req.params.iid)); const rule = currentRule(); res.json({ formula: formulaInfo(rule), ...(await itemTokens(it, rule, await fixedTokens(), true)) });}));
api.delete('/batches/:bid/items/:iid', h(async (req, res) => { await deleteItem(String(req.params.bid), String(req.params.iid)); res.json({ ok: true });}));
/* ---------------------------------------------------------- danh sách khách mọi đoàn */
const customerRows = (): CustomerRow[] => allItems().map((it) => customerRow(it, batchById(it.batchId)));
const norm = (s: string) => s.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/đ/g, 'd');const DISPLAY: Partial<Record<keyof CustomerRow, (r: CustomerRow) => string>> = { birthDate: (r) => vnDate(r.birthDate), entryDate: (r) => vnDate(r.entryDate), exitDate: (r) => vnDate(r.exitDate), expiryDate: (r) => vnDate(r.expiryDate), issueDate: (r) => vnDate(r.issueDate), createdAt: (r) => new Date(r.createdAt).toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh' }), sex: (r) => (r.sex === 'M' ? 'Nam' : r.sex === 'F' ? 'Nữ' : r.sex), urgent: (r) => (r.urgent ? 'Có' : 'Không'), vip: (r) => (r.vip ? 'Có' : 'Không'), multipleEntry: (r) => (r.multipleEntry ? 'Nhiều lần' : 'Một lần'),};const display = (r: CustomerRow, k: keyof CustomerRow) => (DISPLAY[k] ? DISPLAY[k]!(r) : String(r[k] ?? ''));
/** Lọc theo query: q (tìm chung), f.<cột>=chuỗi con, flag=warn|review|urgent */function filterRows(rows: CustomerRow[], q: Record<string, unknown>): CustomerRow[] { const text = typeof q.q === 'string' ? norm(q.q.trim()) : ''; const cols = Object.entries(q).filter(([k, v]) => k.startsWith('f.') && typeof v === 'string' && v.trim()) .map(([k, v]) => [k.slice(2) as keyof CustomerRow, norm(String(v).trim())] as const); const flag = String(q.flag ?? ''); return rows.filter((r) => { if (flag === 'warn' && !r.under6Months) return false; if (flag === 'review' && !(r.needsReview || r.status === 'error' || r.missing.length)) return false; if (flag === 'urgent' && !r.urgent) return false; if (text && !norm(`${r.name} ${r.documentNumber} ${r.groupCode} ${r.batchName} ${r.file}`).includes(text)) return false; return cols.every(([k, v]) => norm(display(r, k)).includes(v)); });}
api.get('/customers', h(async (req, res) => { let rows = filterRows(customerRows(), req.query as Record<string, unknown>); const sort = String(req.query.sort ?? 'createdAt') as keyof CustomerRow; const dir = req.query.dir === 'asc' ? 1 : -1; rows = rows.sort((a, b) => { const x = a[sort] ?? ''; const y = b[sort] ?? ''; return (x < y ? -1 : x > y ? 1 : 0) * dir || (b.createdAt - a.createdAt); }); const size = Math.min(500, Math.max(10, Number(req.query.size ?? 100) || 100)); const pages = Math.max(1, Math.ceil(rows.length / size)); const page = Math.min(pages, Math.max(1, Number(req.query.page ?? 1) || 1)); const groups = [...new Set(customerRows().map((r) => r.groupCode).filter(Boolean))].sort(); res.json({ rows: rows.slice((page - 1) * size, page * size), total: rows.length, page, pages, size, groups, // id của toàn bộ dòng khớp bộ lọc (để "chọn tất cả theo bộ lọc") allIds: req.query.ids === '1' ? rows.map((r) => r.id) : undefined, });}));
/** Xoá nhiều khách */api.post('/customers/delete', json, h(async (req, res) => { const ids: string[] = Array.isArray(req.body?.ids) ? req.body.ids.filter((x: unknown) => typeof x === 'string').slice(0, 2000) : []; const byId = new Map(allItems().map((i) => [i.id, i])); const failed: string[] = []; for (const id of ids) { const it = byId.get(id); if (!it) continue; try { await deleteItem(it.batchId, id); } catch (e) { failed.push(`${it.result?.record.documentNumber || it.name}: ${(e as Error).message}`); } } res.json({ deleted: ids.length - failed.length, failed });}));
/* ---------------------------------------------------------- xuất file nộp hồ sơ */
function template(name: string): Buffer { const f = path.join(TEMPLATE_DIR, name); if (!fs.existsSync(f)) throw new Error(`Thiếu file mẫu ${name}`); return fs.readFileSync(f);}
function exportEntries(ids: unknown): { entries: ExportEntry[]; skipped: string[] } { const list: string[] = Array.isArray(ids) ? ids.filter((x): x is string => typeof x === 'string').slice(0, 5000) : []; const byId = new Map(allItems().map((i) => [i.id, i])); const entries: ExportEntry[] = []; const skipped: string[] = []; for (const id of list) { const it = byId.get(id); if (!it) continue; const rec = it.result?.record; if (it.status !== 'done' || !rec) { skipped.push(it.name); continue; } entries.push({ item: it, rec, trip: effectiveTrip(batchById(it.batchId), it) }); } // thứ tự ổn định theo thời gian upload trước khi xếp Nam/Nữ entries.sort((a, b) => a.item.createdAt - b.item.createdAt || a.item.name.localeCompare(b.item.name)); return { entries, skipped };}
/** Kiểm tra trước khi xuất: thiếu trường bắt buộc, hộ chiếu còn hạn dưới 6 tháng, ảnh chưa xử lý xong */api.post('/export/check', json, h(async (req, res) => { const { entries, skipped } = exportEntries(req.body?.ids); const rows = entries.map((e) => customerRow(e.item, batchById(e.item.batchId))); res.json({ count: entries.length, male: entries.filter((e) => e.rec.sex === 'M').length, female: entries.filter((e) => e.rec.sex === 'F').length, skipped, missing: rows.filter((r) => r.missing.length).map((r) => ({ id: r.id, batchId: r.batchId, name: r.name || r.file, fields: r.missing })), under6: rows.filter((r) => r.under6Months).map((r) => ({ id: r.id, batchId: r.batchId, name: r.name, expiryDate: r.expiryDate, entryDate: r.entryDate, expired: r.expired })), groupCodes: [...new Set(entries.map((e) => e.trip.groupCode).filter(Boolean))], entryDates: [...new Set(entries.map((e) => e.trip.entryDate).filter(Boolean))], dvcName: dvcFileName(entries[0]?.trip.groupCode ?? '', entries.length), bpName: bpFileName(entries[0]?.trip.groupCode ?? '', entries.length, entries[0]?.trip.entryDate), });}));api.post('/export/:kind', json, h(async (req, res) => { const kind = String(req.params.kind); if (kind !== 'dvc' && kind !== 'bp') return void res.status(404).json({ error: 'Không có loại file này' }); const { entries } = exportEntries(req.body?.ids); if (!entries.length) return void res.status(400).json({ error: 'Không có khách nào đã xử lý xong để xuất' }); const sorted = sortMaleFirst(entries); const bytes = kind === 'dvc' ? fillTemplate(template('thong-tin-ho-chieu.xlsx'), 'INF_NHAN_SU', dvcRows(sorted)) : fillTemplate(template('cong-van-bp.xlsx'), 'BP', bpRows(sorted)); const fallback = kind === 'dvc' ? dvcFileName(entries[0].trip.groupCode ?? '', entries.length) : bpFileName(entries[0].trip.groupCode ?? '', entries.length, entries[0].trip.entryDate); let name = typeof req.body?.filename === 'string' && req.body.filename.trim() ? req.body.filename.trim().replace(/[\\/:*?"<>|]+/g, '').slice(0, 120) : fallback; if (!/\.xlsx$/i.test(name)) name += '.xlsx'; res.set({ 'content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`, 'cache-control': 'no-store', }); res.send(Buffer.from(bytes));}));
app.use('/api', requireApiKey, limiter, pub, api);app.use((_req, res) => void res.status(404).json({ error: 'Không có API này' }));
const 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) { process.on(sig, () => { server.close(); shutdownOcr().finally(() => process.exit(0)); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531/** * Hàng đợi xử lý phía server, trạng thái bền nằm trong Firestore: * nhận file -> (ổ tạm) -> lưu Telegram [pending -> stored] -> OCR -> (hàng đợi Gemini) [stored -> done] * Gemini chạy ở hàng đợi riêng: trong lúc chờ Gemini trả lời, worker OCR đã chuyển sang ảnh khác. * Space khởi động lại: item `stored` được OCR tiếp (ảnh lấy lại từ Telegram); * item `pending` mất file tạm -> báo lỗi để người dùng upload lại. * * Firestore: * batches/{batchId} lô upload, có bộ đếm kết quả * batches/{batchId}/items/{itemId} từng ảnh * hashes/{sha256} chống trùng: ảnh đã lưu Telegram thì dùng lại * * Server là nơi DUY NHẤT ghi dữ liệu (trình duyệt bị chặn bởi firestore.rules), nên toàn bộ lô + khách được * giữ trong RAM: đọc Firestore 1 lần lúc khởi động, sau đó mọi truy vấn / lọc / phân trang chạy trên cache, * mọi thay đổi ghi Firestore rồi cập nhật cache. Chỉ chạy 1 instance (HF Space) nên cache luôn khớp. */import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';import { FieldValue } from 'firebase-admin/firestore';import { EMPTY_COUNTS, itemCounts, mergeResults, reconcile, runPipeline, type Batch, type BatchSettings, type ExtractionResult, type StoredItem, type TripInfo,} from '@pc/core';import { db } from './firebase.ts';import { sendDocument, downloadFile, deleteMessage, type TelegramRef } from './telegram.ts';import { INBOX, cacheGet, cachePut, type NormalizedImage } from './media.ts';import { loadImage, sharpOps, tessEngine } from './ocr.ts';import { geminiExtract, llmAvailable } from './gemini.ts';
const OCR_CONCURRENCY = Number(process.env.OCR_CONCURRENCY ?? 1);/** số lời gọi Gemini chạy cùng lúc (chủ yếu là chờ mạng, không tốn CPU) */const LLM_CONCURRENCY = Number(process.env.LLM_CONCURRENCY ?? 2);
const batches = () => db().collection('batches');const items = (batchId: string) => batches().doc(batchId).collection('items');const hashes = () => db().collection('hashes');
export const newId = () => crypto.randomBytes(10).toString('base64url');const inboxPath = (itemId: string) => path.join(INBOX, itemId);
/* ------------------------------------------------------------------ cache dữ liệu */
const batchCache = new Map<string, Batch>();const itemCache = new Map<string, StoredItem>();let loaded: Promise<void> | null = null;
/** Đọc toàn bộ lô + khách vào RAM (1 lần lúc khởi động) */export function loadCache(): Promise<void> { loaded ??= (async () => { const t0 = Date.now(); const [bs, its] = await Promise.all([batches().get(), db().collectionGroup('items').get()]); for (const d of bs.docs) batchCache.set(d.id, d.data() as Batch); for (const d of its.docs) itemCache.set(d.id, d.data() as StoredItem); console.log(`cache: ${batchCache.size} lô, ${itemCache.size} khách (${Date.now() - t0}ms)`); })().catch((e) => { loaded = null; throw e; }); return loaded;}export const cacheReady = () => loaded;
/** Ghi thay đổi lô lên Firestore + cache. `inc` = cộng/trừ bộ đếm */async function patchBatch(batchId: string, patch: Partial<Batch>, inc: Partial<Record<keyof Batch['counts'], number>> = {}) { const b = batchCache.get(batchId); const now = Date.now(); const data: Record<string, unknown> = { ...clean(patch), updatedAt: now }; for (const [k, v] of Object.entries(inc)) if (v) data[`counts.${k}`] = FieldValue.increment(v); await batches().doc(batchId).update(data); if (b) { const counts = { ...b.counts }; for (const [k, v] of Object.entries(inc)) counts[k as keyof typeof counts] += v ?? 0; batchCache.set(batchId, { ...b, ...clean(patch), counts, updatedAt: now }); }}
/* ------------------------------------------------------------------ trạng thái trong RAM */
type OcrTask = { batchId: string; itemId: string; force?: 'ocr' | 'llm' };const tgQueue: { batchId: string; itemId: string }[] = [];const ocrQueue: OcrTask[] = [];/** ảnh đã OCR xong, chờ hỏi Gemini (giữ kết quả OCR để gộp) */type LlmTask = { batchId: string; itemId: string; result: ExtractionResult; rotation: number; t0: number };const llmQueue: LlmTask[] = [];/** việc còn dở của từng lô (để biết lúc nào lô xong) */const outstanding = new Map<string, number>();/** item đang xử lý: bước hiện tại (không ghi Firestore để tiết kiệm quota) */const live = new Map<string, { batchId: string; step: string }>();
function addOutstanding(batchId: string, n: number) { outstanding.set(batchId, (outstanding.get(batchId) ?? 0) + n);}
async function finishOne(batchId: string) { const n = (outstanding.get(batchId) ?? 1) - 1; if (n > 0) return void outstanding.set(batchId, n); outstanding.delete(batchId); await patchBatch(batchId, { status: 'done' }).catch(() => undefined);}
export function liveStatus(batchId: string) { const processing = [...live.entries()].filter(([, v]) => v.batchId === batchId).map(([id, v]) => ({ id, step: v.step })); return { processing, waitingTelegram: tgQueue.filter((t) => t.batchId === batchId).length, waitingOcr: ocrQueue.filter((t) => t.batchId === batchId).length, waitingLlm: llmQueue.filter((t) => t.batchId === batchId).length, };}
/* ------------------------------------------------------------------ Firestore helpers */
/** Cập nhật item + cộng/trừ bộ đếm của lô theo trạng thái cũ -> mới (ghi nguyên tử 1 batch write) */async function updateItem(batchId: string, itemId: string, patch: Partial<StoredItem>) { const old = itemCache.get(itemId); if (!old) return; const now = Date.now(); const p = clean(patch); const next = { ...old, ...p, updatedAt: now }; const a = itemCounts(old); const b = itemCounts(next); const inc: Record<string, number> = {}; for (const k of Object.keys(a) as (keyof typeof a)[]) if (a[k] !== b[k]) inc[k] = b[k] - a[k]; const wb = db().batch(); wb.update(items(batchId).doc(itemId), { ...p, updatedAt: now }); const binc: Record<string, unknown> = { updatedAt: now }; for (const [k, v] of Object.entries(inc)) binc[`counts.${k}`] = FieldValue.increment(v); wb.update(batches().doc(batchId), binc); await wb.commit(); itemCache.set(itemId, next); const bt = batchCache.get(batchId); if (bt) { const counts = { ...bt.counts }; for (const [k, v] of Object.entries(inc)) counts[k as keyof typeof counts] += v; batchCache.set(batchId, { ...bt, counts, updatedAt: now }); }}
/** Firestore không nhận undefined lồng sâu / class -> chuyển qua JSON */function clean<T>(v: T): T { return JSON.parse(JSON.stringify(v));}
export async function createBatch(name: string, settings: BatchSettings, user: { uid: string; email: string }): Promise<Batch> { const now = Date.now(); const b: Batch = { id: newId(), name, settings, createdBy: user, createdAt: now, updatedAt: now, status: 'done', counts: { ...EMPTY_COUNTS } }; await batches().doc(b.id).set(clean(b)); batchCache.set(b.id, b); return b;}
export async function getBatch(id: string): Promise<Batch | null> { return batchCache.get(id) ?? null;}
export async function listBatches(limit = 200): Promise<Batch[]> { return [...batchCache.values()].sort((a, b) => b.createdAt - a.createdAt).slice(0, limit);}
/** Item của lô thay đổi sau thời điểm `since` (ms) */export async function listItems(batchId: string, since = 0): Promise<StoredItem[]> { return [...itemCache.values()].filter((i) => i.batchId === batchId && i.updatedAt > since);}
export async function getItem(batchId: string, itemId: string): Promise<StoredItem | null> { const it = itemCache.get(itemId); return it && it.batchId === batchId ? it : null;}
/** Đọc lô từ cache (đồng bộ) */export function batchById(id: string): Batch | null { return batchCache.get(id) ?? null;}
/** Toàn bộ khách mọi đoàn (cho trang Danh sách khách) */export function allItems(): StoredItem[] { return [...itemCache.values()];}
/** Sửa thông tin đoàn (tên, mã, chuyến đi) */export async function updateBatchInfo(batchId: string, patch: { name?: string; trip?: TripInfo }) { if (!batchCache.has(batchId)) throw Object.assign(new Error('Không tìm thấy lô'), { status: 404 }); await patchBatch(batchId, patch); return batchCache.get(batchId)!;}
/* ------------------------------------------------------------------ nhận ảnh */
/** `again`: ảnh trùng đã có kết quả (cùng lô hoặc lấy từ lô trước) — người dùng có thể chọn OCR lại */export interface IngestOutcome { added: number; duplicates: string[]; reused: number; again: string[] }
/** * Thêm các ảnh đã chuẩn hoá vào lô. Ảnh trùng trong cùng lô bị bỏ qua; * ảnh đã từng lưu (lô khác) thì dùng lại file Telegram + kết quả cũ. */export async function ingest( batchId: string, user: string, files: { name: string; size: number; sha256: string; img: NormalizedImage }[], reocr = false,): Promise<IngestOutcome> { const out: IngestOutcome = { added: 0, duplicates: [], reused: 0, again: [] }; const now = Date.now(); const writes: { item: StoredItem; buf?: Buffer }[] = []; const seen = new Set<string>(); for (const f of files) { // trùng trong cùng lô (cùng request, hoặc đã upload trước đó vào lô này) if (seen.has(f.sha256)) { out.duplicates.push(f.name); continue; } seen.add(f.sha256); const same = [...itemCache.values()].find((i) => i.batchId === batchId && i.sha256 === f.sha256); if (same) { out.duplicates.push(f.name); if ((same.status === 'done' || same.status === 'error') && same.telegram && !out.again.includes(same.id)) { // người dùng đã chọn OCR lại ảnh trùng -> xử lý lại luôn ảnh đã có trong lô if (reocr) await rerun(batchId, same.id, 'ocr').catch(() => undefined); else out.again.push(same.id); } continue; } const h = await hashes().doc(f.sha256).get(); const prev = h.exists ? (h.data() as { batchId: string; itemId: string; telegram: TelegramRef }) : null; const item: StoredItem = { id: newId(), batchId, name: f.name, size: f.size, mime: f.img.mime, sha256: f.sha256, status: 'pending', thumb: f.img.thumb, width: f.img.width, height: f.img.height, uploadedBy: user, createdAt: now, updatedAt: now, }; if (prev) { // ảnh đã có trên Telegram: không gửi lại; lấy kết quả cũ nếu đã xử lý xong const old = await getItem(prev.batchId, prev.itemId); item.telegram = prev.telegram; item.duplicateOf = `${prev.batchId}/${prev.itemId}`; if (!reocr && old?.status === 'done' && old.result) { Object.assign(item, { status: 'done', result: old.result, confidence: old.confidence, needsReview: old.needsReview, rotation: old.rotation, edited: old.edited }); out.reused++; out.again.push(item.id); } else item.status = 'stored'; cachePut(prev.telegram.fileUniqueId, f.img.buf); await hashes().doc(f.sha256).update({ refs: FieldValue.increment(1) }); } writes.push({ item, buf: item.status === 'pending' ? f.img.buf : undefined }); } if (!writes.length) return out;
for (const w of writes) if (w.buf) fs.writeFileSync(inboxPath(w.item.id), w.buf); const counts = { total: 0, done: 0, error: 0, HIGH: 0, MEDIUM: 0, LOW: 0, review: 0 }; for (let i = 0; i < writes.length; i += 400) { const wb = db().batch(); for (const { item } of writes.slice(i, i + 400)) { wb.set(items(batchId).doc(item.id), clean(item)); itemCache.set(item.id, clean(item)); counts.total++; const c = itemCounts(item); for (const k of Object.keys(c) as (keyof typeof c)[]) counts[k] += c[k]; } await wb.commit(); } const work = writes.filter((w) => w.item.status !== 'done'); await patchBatch(batchId, work.length ? { status: 'running' } : {}, counts);
for (const { item } of work) { addOutstanding(batchId, 1); if (item.status === 'pending') { tgQueue.push({ batchId, itemId: item.id }); } else ocrQueue.push({ batchId, itemId: item.id }); } out.added = writes.length; kick(); return out;}
/* ------------------------------------------------------------------ worker */
let tgRunning = false;let ocrRunning = 0;let llmRunning = 0;
function kick() { if (!tgRunning && tgQueue.length) void runTelegram(); while (ocrRunning < OCR_CONCURRENCY && ocrQueue.length) void runOcr(); while (llmRunning < LLM_CONCURRENCY && llmQueue.length) void runLlm();}
async function runTelegram() { tgRunning = true; try { while (tgQueue.length) { const { batchId, itemId } = tgQueue.shift()!; live.set(itemId, { batchId, step: 'Lưu lên Telegram' }); try { const it = await getItem(batchId, itemId); if (!it) { fs.rmSync(inboxPath(itemId), { force: true }); await finishOne(batchId); continue; } const buf = fs.readFileSync(inboxPath(itemId)); const batch = await getBatch(batchId); const ext = it.mime.split('/')[1]?.replace('jpeg', 'jpg') ?? 'jpg'; const filename = `${path.basename(it.name).replace(/\.[^.]+$/, '')}.${ext}`; const ref = await sendDocument(buf, filename, it.mime, `${batch?.name ?? batchId} / ${it.name}\n#${itemId}`); cachePut(ref.fileUniqueId, buf); await updateItem(batchId, itemId, { status: 'stored', telegram: ref }); await hashes().doc(it.sha256).set({ batchId, itemId, telegram: ref, refs: 1, createdAt: Date.now() }); ocrQueue.push({ batchId, itemId }); kick(); } catch (e) { console.error('telegram error', (e as Error).message); await updateItem(batchId, itemId, { status: 'error', error: `Không lưu được lên Telegram: ${(e as Error).message}` }).catch(() => undefined); fs.rmSync(inboxPath(itemId), { force: true }); await finishOne(batchId); } finally { live.delete(itemId); } } } finally { tgRunning = false; }}
/** Ảnh gốc: ổ tạm -> cache -> tải lại từ Telegram */export async function loadOriginal(it: StoredItem): Promise<Buffer> { try { return fs.readFileSync(inboxPath(it.id)); } catch { /* không có trong inbox */ } if (!it.telegram) throw new Error('Ảnh chưa được lưu lên Telegram'); const cached = cacheGet(it.telegram.fileUniqueId); if (cached) return cached; const buf = await downloadFile(it.telegram.fileId); cachePut(it.telegram.fileUniqueId, buf); return buf;}
const LEVEL = { HIGH: 2, MEDIUM: 1, LOW: 0 } as const;function wantLlm(r: ExtractionResult, policy: BatchSettings['llm']): boolean { if (!llmAvailable() || policy === 'off') return false; if (policy === 'all') return true; if (policy === 'low') return LEVEL[r.confidence] === 0; return LEVEL[r.confidence] < 2 || r.needsReview;}
async function runOcr() { ocrRunning++; try { while (ocrQueue.length) { const task = ocrQueue.shift()!; const { batchId, itemId, force } = task; const step = (s: string) => live.set(itemId, { batchId, step: s }); step('Chuẩn bị'); const t0 = Date.now(); let handedOff = false; try { const it = await getItem(batchId, itemId); if (!it) continue; const batch = await getBatch(batchId); const policy = batch?.settings.llm ?? 'low'; const buf = await loadOriginal(it); let result: ExtractionResult; let rotation = it.rotation ?? 0; const img = await loadImage(buf); // lượt nhanh trước; chưa chắc chắn mới chạy lượt kỹ (nhiều biến thể ảnh hơn) const fast = await runPipeline(img, sharpOps, tessEngine, { thorough: false, onStep: step }); result = reconcile({ mrz: fast.mrz, viz: fast.viz, sources: ['local'] }); rotation = fast.rotation; if (result.confidence !== 'HIGH' || force === 'ocr') { step('OCR kỹ'); const deep = await runPipeline(img, sharpOps, tessEngine, { thorough: true, onStep: (s) => step(`OCR kỹ · ${s}`) }); result = mergeResults(result, { mrz: deep.mrz, viz: deep.viz, source: 'server-ocr' }); if (deep.mrz && deep.mrz === result.mrz) rotation = deep.rotation; } if (force === 'llm' || (!force && wantLlm(result, policy))) { // chuyển sang hàng đợi Gemini; worker OCR làm tiếp ảnh khác llmQueue.push({ batchId, itemId, result, rotation, t0 }); handedOff = true; kick(); continue; } await saveResult(batchId, itemId, result, rotation, t0); } catch (e) { console.error('ocr error', (e as Error).message); await updateItem(batchId, itemId, { status: 'error', error: `Xử lý lỗi: ${(e as Error).message}` }).catch(() => undefined); } finally { live.delete(itemId); if (!handedOff) await finishOne(batchId); } } } finally { ocrRunning--; }}
async function saveResult(batchId: string, itemId: string, result: ExtractionResult, rotation: number, t0: number) { await updateItem(batchId, itemId, { status: 'done', error: '', result, confidence: result.confidence, needsReview: result.needsReview, rotation, ms: Date.now() - t0, edited: false, }); fs.rmSync(inboxPath(itemId), { force: true });}
async function runLlm() { llmRunning++; try { while (llmQueue.length) { const task = llmQueue.shift()!; const { batchId, itemId, rotation, t0 } = task; let result = task.result; live.set(itemId, { batchId, step: 'Gemini' }); try { const it = await getItem(batchId, itemId); if (!it) continue; // ảnh bị xoá trong lúc chờ const buf = await loadOriginal(it); try { const llm = await geminiExtract(buf, it.mime); result = mergeResults(result, { llm, source: 'llm' }); } catch (e: any) { result = { ...result, warnings: [...result.warnings, `Gemini lỗi: ${e?.status === 429 ? 'hết quota' : e?.message ?? e}`] }; } await saveResult(batchId, itemId, result, rotation, t0); } catch (e) { console.error('gemini error', (e as Error).message); await updateItem(batchId, itemId, { status: 'error', error: `Xử lý lỗi: ${(e as Error).message}` }).catch(() => undefined); } finally { live.delete(itemId); await finishOne(batchId); } } } finally { llmRunning--; }}
/* ------------------------------------------------------------------ thao tác của người dùng */
export async function rerun(batchId: string, itemId: string, force: 'ocr' | 'llm') { const it = await getItem(batchId, itemId); if (!it) throw Object.assign(new Error('Không tìm thấy ảnh'), { status: 404 }); if (!it.telegram) throw Object.assign(new Error('Ảnh chưa lưu xong lên Telegram'), { status: 409 }); if (live.has(itemId) || ocrQueue.some((t) => t.itemId === itemId) || llmQueue.some((t) => t.itemId === itemId)) { throw Object.assign(new Error('Ảnh đang được xử lý'), { status: 409 }); } addOutstanding(batchId, 1); await patchBatch(batchId, { status: 'running' }); // hỏi lại Gemini: dùng luôn kết quả OCR đã có, không OCR lại if (force === 'llm' && it.result) llmQueue.push({ batchId, itemId, result: it.result, rotation: it.rotation ?? 0, t0: Date.now() }); else ocrQueue.push({ batchId, itemId, force }); kick();}
/** * Trong các hash (sha256 của file gốc), hash nào đã có kết quả: trong chính lô này, hoặc ở lô trước * (khi upload sẽ được dùng lại kết quả cũ nếu không chọn OCR lại). */export async function knownHashes(batchId: string, list: string[]): Promise<string[]> { const want = [...new Set(list.filter((h) => /^[0-9a-f]{64}$/.test(h)))]; const found = new Set<string>(); for (const i of itemCache.values()) { if (i.batchId === batchId && want.includes(i.sha256) && (i.status === 'done' || i.status === 'error') && i.telegram) found.add(i.sha256); } const rest = want.filter((h) => !found.has(h)); for (let i = 0; i < rest.length; i += 300) { const docs = await db().getAll(...rest.slice(i, i + 300).map((h) => hashes().doc(h))); for (const d of docs) { if (!d.exists) continue; const prev = d.data() as { batchId: string; itemId: string }; const old = await getItem(prev.batchId, prev.itemId); if (old?.status === 'done' && old.result) found.add(d.id); } } return [...found];}
/** OCR lại nhiều ảnh; bỏ qua ảnh đang xử lý / chưa lưu xong */export async function rerunMany(batchId: string, ids: string[]): Promise<{ queued: number; failed: number }> { let queued = 0; for (const id of ids) { try { await rerun(batchId, id, 'ocr'); queued++; } catch { /* bỏ qua */ } } return { queued, failed: ids.length - queued };}
export async function saveEdit(batchId: string, itemId: string, edit: { result?: ExtractionResult; trip?: TripInfo }, email: string) { const it = await getItem(batchId, itemId); if (!it) throw Object.assign(new Error('Không tìm thấy ảnh'), { status: 404 }); const patch: Partial<StoredItem> = {}; if (edit.result) { Object.assign(patch, { status: 'done', result: edit.result, confidence: edit.result.confidence, needsReview: edit.result.needsReview, edited: true, reviewedBy: email }); } // ghi đè thông tin chuyến đi riêng của khách; giá trị rỗng = dùng lại thông tin đoàn if (edit.trip) patch.trip = Object.fromEntries(Object.entries(edit.trip).filter(([, v]) => v !== undefined && v !== null && v !== '')) as TripInfo; if (Object.keys(patch).length) await updateItem(batchId, itemId, patch); return itemCache.get(itemId)!;}
export async function deleteItem(batchId: string, itemId: string) { const it = await getItem(batchId, itemId); if (!it) return; if (live.has(itemId)) throw Object.assign(new Error('Ảnh đang được xử lý'), { status: 409 }); await updateItem(batchId, itemId, { status: 'pending' }); // trừ bộ đếm kết quả await items(batchId).doc(itemId).delete(); itemCache.delete(itemId); await patchBatch(batchId, {}, { total: -1 }); const tq = tgQueue.findIndex((t) => t.itemId === itemId); if (tq >= 0) { tgQueue.splice(tq, 1); await finishOne(batchId); } const oq = ocrQueue.findIndex((t) => t.itemId === itemId); if (oq >= 0) { ocrQueue.splice(oq, 1); await finishOne(batchId); } const lq = llmQueue.findIndex((t) => t.itemId === itemId); if (lq >= 0) { llmQueue.splice(lq, 1); await finishOne(batchId); } fs.rmSync(inboxPath(itemId), { force: true }); // chỉ xoá tin nhắn Telegram khi không còn item nào dùng file này if (it.telegram) { const href = hashes().doc(it.sha256); const orphan = await db().runTransaction(async (tx) => { const h = await tx.get(href); if (!h.exists || (h.data() as { telegram: TelegramRef }).telegram.fileUniqueId !== it.telegram!.fileUniqueId) return false; const refs = ((h.data() as { refs?: number }).refs ?? 1) - 1; if (refs > 0) { tx.update(href, { refs }); return false; } tx.delete(href); return true; }); if (orphan) await deleteMessage(it.telegram).catch((e) => console.warn('telegram delete', (e as Error).message)); }}
/* ------------------------------------------------------------------ khởi động lại */
export async function recover() { await loadCache(); for (const b of [...batchCache.values()].filter((x) => x.status === 'running')) { const batchId = b.id; let n = 0; for (const it of [...itemCache.values()].filter((i) => i.batchId === batchId && (i.status === 'pending' || i.status === 'stored'))) { if (it.status === 'stored') { ocrQueue.push({ batchId, itemId: it.id }); n++; } else if (fs.existsSync(inboxPath(it.id))) { tgQueue.push({ batchId, itemId: it.id }); n++; } else await updateItem(batchId, it.id, { status: 'error', error: 'Server khởi động lại trước khi kịp lưu ảnh lên Telegram — hãy upload lại ảnh này' }); } if (n) addOutstanding(batchId, n); else await patchBatch(batchId, { status: 'done' }); } if (tgQueue.length || ocrQueue.length) console.log(`recover: ${tgQueue.length} chờ Telegram, ${ocrQueue.length} chờ OCR`); kick();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104/** * Chuẩn hoá ảnh trước khi lưu Telegram, tạo thumbnail, và cache ảnh trên ổ tạm. * HF Spaces free không có ổ bền: thư mục tạm mất khi Space khởi động lại, nên ảnh gốc luôn nằm ở Telegram; * ổ tạm chỉ để xử lý và để xem lại nhanh. */import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import sharp, { type Metadata } from 'sharp';import heicConvert from 'heic-convert';import { TELEGRAM_MAX_DOWNLOAD } from './telegram.ts';
export const WORK_DIR = process.env.WORK_DIR ?? path.join(os.tmpdir(), 'passport-check');export const INBOX = path.join(WORK_DIR, 'inbox');const CACHE = path.join(WORK_DIR, 'cache');const CACHE_MAX = Number(process.env.IMAGE_CACHE_MB ?? 500) * 1024 * 1024;fs.mkdirSync(INBOX, { recursive: true });fs.mkdirSync(CACHE, { recursive: true });
export const IMAGE_EXT = /\.(jpe?g|png|webp|heic|heif|tiff?|bmp|gif)$/i;export const ZIP_EXT = /\.zip$/i;
export interface NormalizedImage { buf: Buffer; mime: string; ext: string; width: number; height: number; thumb: string;}
/** * Giữ nguyên file gốc nếu là JPEG/PNG/WebP (trình duyệt xem được); HEIC/TIFF/BMP/GIF đổi sang JPEG. * Ảnh quá 20MB (giới hạn tải về của Telegram bot) được nén lại. */export async function normalizeImage(input: Buffer, name: string): Promise<NormalizedImage> { let buf = input; let meta = await sharp(buf, { failOn: 'none' }).metadata().catch(() => null); if (!meta && /\.(heic|heif)$/i.test(name)) meta = { format: 'heif' } as Metadata; if (!meta?.format) throw new Error('Không phải file ảnh hợp lệ'); let format = meta.format; if (format === 'heif' && meta.compression !== 'av1') { // sharp bản dựng sẵn không giải mã HEVC -> dùng heic-convert (WASM) try { buf = Buffer.from(await heicConvert({ buffer: buf as unknown as ArrayBuffer, format: 'JPEG', quality: 0.92 })); } catch { throw new Error('Không đọc được ảnh HEIC'); } format = 'jpeg'; } else if (!['jpeg', 'png', 'webp'].includes(format)) { buf = await sharp(buf, { failOn: 'none' }).rotate().jpeg({ quality: 92 }).toBuffer(); format = 'jpeg'; } if (buf.length > TELEGRAM_MAX_DOWNLOAD - 512 * 1024) { buf = await sharp(buf, { failOn: 'none' }).rotate().resize({ width: 5000, height: 5000, fit: 'inside', withoutEnlargement: true }).jpeg({ quality: 90 }).toBuffer(); format = 'jpeg'; } const img = sharp(buf, { failOn: 'none' }).rotate(); const thumbBuf = await img.clone().resize({ width: 200, height: 200, fit: 'inside' }).webp({ quality: 55 }).toBuffer(); const { width = 0, height = 0, orientation } = await sharp(buf, { failOn: 'none' }).metadata(); const swap = (orientation ?? 1) >= 5; return { buf, mime: `image/${format}`, ext: format === 'jpeg' ? 'jpg' : format, width: swap ? height : width, height: swap ? width : height, thumb: `data:image/webp;base64,${thumbBuf.toString('base64')}`, };}
/* --------------------------------------------------------------- cache ảnh để xem lại */
const cachePath = (key: string) => path.join(CACHE, key.replace(/[^\w-]/g, '_'));
export function cacheGet(key: string): Buffer | null { const p = cachePath(key); try { const buf = fs.readFileSync(p); const now = new Date(); fs.utimesSync(p, now, now); return buf; } catch { return null; }}
export function cachePut(key: string, buf: Buffer) { try { fs.writeFileSync(cachePath(key), buf); const files = fs.readdirSync(CACHE).map((f) => { const st = fs.statSync(path.join(CACHE, f)); return { f, size: st.size, t: st.mtimeMs }; }); let total = files.reduce((s, x) => s + x.size, 0); for (const x of files.sort((a, b) => a.t - b.t)) { if (total <= CACHE_MAX) break; fs.rmSync(path.join(CACHE, x.f), { force: true }); total -= x.size; } } catch { /* cache chỉ để tăng tốc */ }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788/** * Tầng leo thang OCR phía server: sharp (nhiều biến thể tiền xử lý) + tesseract.js (pool worker theo ngôn ngữ). */import os from 'node:os';import sharp, { type Sharp } from 'sharp';import { createWorker, type Worker } from 'tesseract.js';import { createWorkerPool, type ImageOps, type OcrEngine, type OcrLine, type OcrOptions } from '@pc/core';
export interface Img { data: Buffer; width: number; height: number }
async function fromSharp(s: Sharp): Promise<Img> { const { data, info } = await s.png({ compressionLevel: 1 }).toBuffer({ resolveWithObject: true }); return { data, width: info.width, height: info.height };}
export async function loadImage(buf: Buffer): Promise<Img> { // rotate() không tham số = xoay theo EXIF return fromSharp(sharp(buf, { failOn: 'none' }).rotate().greyscale());}
export const sharpOps: ImageOps<Img> = { size: (i) => ({ width: i.width, height: i.height }), rotate: (i, deg) => fromSharp(sharp(i.data).rotate(deg)), rotateFine: (i, deg) => fromSharp(sharp(i.data).rotate(deg, { background: '#ffffff' })), crop: (i, r) => { const left = Math.max(0, Math.min(i.width - 1, r.left)); const top = Math.max(0, Math.min(i.height - 1, r.top)); return fromSharp(sharp(i.data).extract({ left, top, width: Math.min(r.width, i.width - left), height: Math.min(r.height, i.height - top) })); }, resize: (i, width) => fromSharp(sharp(i.data).resize({ width, kernel: 'lanczos3' })), variants: async (i, thorough) => { const base = sharp(i.data); const list: Promise<Img>[] = [ Promise.resolve(i), fromSharp(base.clone().normalise().sharpen({ sigma: 1 })), ]; if (thorough) { list.push( fromSharp(base.clone().clahe({ width: 64, height: 64, maxSlope: 3 })), fromSharp(base.clone().normalise().threshold(140)), fromSharp(base.clone().median(3).normalise().threshold(110)), ); } return Promise.all(list); },};
/* ------------------------------------------------------------ worker pool */
const TESSDATA = process.env.TESSDATA_DIR ?? new URL('../../../tessdata', import.meta.url).pathname;const POOL_SIZE = Number(process.env.OCR_WORKERS ?? Math.max(1, Math.min(2, os.cpus().length)));
const pool = createWorkerPool<Worker>({ size: POOL_SIZE, maxNative: 3, create: (lang) => createWorker(lang, 1, { langPath: TESSDATA, gzip: true, cacheMethod: 'none' }), terminate: (w) => w.terminate(),});
const THRESH = { otsu: '0', adaptive: '1', sauvola: '2' } as const;
export const tessEngine: OcrEngine<Img> = { async recognize(img, opts: OcrOptions) { const w = await pool.acquire(opts.lang); try { await w.setParameters({ tessedit_pageseg_mode: opts.psm as never, tessedit_char_whitelist: opts.whitelist ?? '', user_defined_dpi: '300', thresholding_method: THRESH[opts.threshold ?? 'otsu'] as never, }); const { data } = await w.recognize(img.data, {}, { text: true, blocks: true }); const lines: OcrLine[] = []; for (const b of data.blocks ?? []) for (const p of b.paragraphs) for (const l of p.lines) { const b = l.baseline; const angle = b && b.x1 !== b.x0 ? (Math.atan2(b.y1 - b.y0, b.x1 - b.x0) * 180) / Math.PI : undefined; lines.push({ text: l.text.trim(), bbox: l.bbox, confidence: l.confidence, angle }); } return { text: data.text, lines, confidence: data.confidence }; } finally { pool.release(opts.lang, w); } },};
export async function shutdownOcr() { await pool.shutdown();}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485/** * Lưu ảnh lên Telegram bằng Bot API (gửi dạng document = file gốc, không bị nén). * - TELEGRAM_BOT_TOKEN: token của bot (BotFather) * - TELEGRAM_CHAT_ID: id kênh / nhóm / chat riêng để lưu ảnh (bot phải là admin nếu là kênh) * Giới hạn Bot API: gửi file ≤ 50MB, tải về qua getFile ≤ 20MB; ~20 tin/phút với nhóm -> có hàng đợi + tôn trọng retry_after. * Bot token không bao giờ gửi cho trình duyệt: server tải ảnh rồi trả lại. */const API = (process.env.TELEGRAM_API_URL ?? 'https://api.telegram.org').replace(/\/$/, '');const TOKEN = process.env.TELEGRAM_BOT_TOKEN ?? '';const CHAT = process.env.TELEGRAM_CHAT_ID ?? '';const MIN_INTERVAL = Number(process.env.TELEGRAM_MIN_INTERVAL_MS ?? 1100);/** giới hạn tải về của getFile */export const TELEGRAM_MAX_DOWNLOAD = 20 * 1024 * 1024;
export function telegramConfigured() { return !!TOKEN && !!CHAT;}
export interface TelegramRef { chatId: string; messageId: number; fileId: string; fileUniqueId: string }
class TelegramError extends Error { constructor(message: string, public retryAfter?: number, public status?: number) { super(message); }}
async function call<T>(method: string, body: FormData | Record<string, unknown>): Promise<T> { const isForm = body instanceof FormData; const res = await fetch(`${API}/bot${TOKEN}/${method}`, { method: 'POST', body: isForm ? body : JSON.stringify(body), headers: isForm ? undefined : { 'content-type': 'application/json' }, signal: AbortSignal.timeout(120_000), }); const json = (await res.json().catch(() => ({}))) as { ok?: boolean; result?: T; description?: string; parameters?: { retry_after?: number } }; if (!json.ok) throw new TelegramError(json.description ?? `Telegram HTTP ${res.status}`, json.parameters?.retry_after, res.status); return json.result as T;}
// Mọi lệnh gửi đi qua 1 hàng đợi tuần tự để không vượt giới hạn tốc độlet chain: Promise<unknown> = Promise.resolve();let last = 0;function throttled<T>(fn: () => Promise<T>): Promise<T> { const run = async (): Promise<T> => { for (let attempt = 0; ; attempt++) { const wait = last + MIN_INTERVAL - Date.now(); if (wait > 0) await new Promise((r) => setTimeout(r, wait)); last = Date.now(); try { return await fn(); } catch (e) { const err = e as TelegramError; const transient = err.retryAfter !== undefined || (err.status ?? 0) >= 500 || err.name === 'TimeoutError' || err instanceof TypeError; if (!transient || attempt >= 5) throw e; await new Promise((r) => setTimeout(r, (err.retryAfter ?? 2 ** attempt) * 1000 + 250)); } } }; const p = chain.then(run, run); chain = p.catch(() => undefined); return p;}
export function sendDocument(buf: Buffer, filename: string, mime: string, caption: string): Promise<TelegramRef> { return throttled(async () => { const form = new FormData(); form.set('chat_id', CHAT); form.set('caption', caption.slice(0, 1000)); form.set('disable_content_type_detection', 'true'); form.set('document', new Blob([new Uint8Array(buf)], { type: mime }), filename); const msg = await call<{ message_id: number; chat: { id: number }; document?: { file_id: string; file_unique_id: string } }>('sendDocument', form); if (!msg.document) throw new Error('Telegram không trả về document'); return { chatId: String(msg.chat.id), messageId: msg.message_id, fileId: msg.document.file_id, fileUniqueId: msg.document.file_unique_id }; });}
export async function downloadFile(fileId: string): Promise<Buffer> { const f = await call<{ file_path?: string; file_size?: number }>('getFile', { file_id: fileId }); if (!f.file_path) throw new Error('Telegram không trả về đường dẫn file'); const res = await fetch(`${API}/file/bot${TOKEN}/${f.file_path}`, { signal: AbortSignal.timeout(120_000) }); if (!res.ok) throw new Error(`Tải ảnh từ Telegram lỗi HTTP ${res.status}`); return Buffer.from(await res.arrayBuffer());}
export async function deleteMessage(ref: TelegramRef): Promise<void> { await throttled(() => call('deleteMessage', { chat_id: ref.chatId, message_id: ref.messageId }));}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219/** * Ước lượng token Gemini cho từng ảnh / cả lô, tự tính tại server (không gọi API, không tốn quota). * * input = token ảnh (theo kích thước từng ảnh, công thức @pc/core imageTokens) + token prompt + token JSON schema * output = token của chuỗi JSON đầu ra * * Token text được đếm bằng tokenizer Gemini chạy local (gemma3 SentencePiece — cùng bộ token của Gemini 2.x/3.x). * Lần đầu tokenizer tải file model (~4MB, kiểm SHA-256) rồi cache ở thư mục tạm; nếu không tải được thì * dùng công thức xấp xỉ theo số byte UTF-8 và đánh dấu exact=false. */import { LocalTokenizer } from '@google/genai/tokenizer';import { addTokenSum, base64Size, emptyTokenSum, GEMINI_TOKEN_DOCS, imageTokenRule, imageTokens, vnDay, type Batch, type ImageTokenRule, type ItemTokens, type LlmOutput, type StoredItem, type TokenFormula, type TokenPrices, type TokenSum, type TokenUsageReport, type UsageBatch, type UsageDay,} from '@pc/core';import { llmModel, promptText, SCHEMA } from './gemini.ts';
/* ------------------------------------------------------------------ đếm token text */
let tokenizer: LocalTokenizer | null = null;let tokenizerFailed = 0;
/** Xấp xỉ khi không có tokenizer: hiệu chỉnh trên JSON hộ chiếu / prompt tiếng Việt ≈ 2.3–3 byte / token */const approxTokens = (text: string) => Math.ceil(Buffer.byteLength(text, 'utf8') / 2.5);
const textCache = new Map<string, number>();
export async function countTextTokens(text: string): Promise<{ tokens: number; exact: boolean }> { if (!text) return { tokens: 0, exact: true }; const hit = textCache.get(text); if (hit !== undefined) return { tokens: hit, exact: true }; // tải lỗi -> 5 phút sau mới thử lại, tránh làm chậm mọi request if (!tokenizerFailed || Date.now() - tokenizerFailed > 5 * 60_000) { try { tokenizer ??= new LocalTokenizer('gemini-2.5-flash'); // tên model chỉ để chọn bộ token gemma3 const r = await tokenizer.countTokens([{ role: 'user', parts: [{ text }] }]); const n = r.totalTokens ?? 0; if (textCache.size > 5000) textCache.clear(); textCache.set(text, n); tokenizerFailed = 0; return { tokens: n, exact: true }; } catch (e) { tokenizer = null; tokenizerFailed = Date.now(); console.error('tokenizer local lỗi, dùng công thức xấp xỉ:', (e as Error).message); } } return { tokens: approxTokens(text), exact: false };}
/* ------------------------------------------------------------------ token từng ảnh */
/** JSON đầu ra: lấy đúng JSON Gemini đã trả nếu ảnh từng qua Gemini, nếu không thì dựng từ kết quả OCR theo schema */export function outputJson(it: StoredItem): { json: LlmOutput | null; source: 'llm' | 'ocr' | 'none' } { const r = it.result; if (!r) return { json: null, source: 'none' }; if (r.llm) return { json: r.llm as LlmOutput, source: 'llm' }; const rec = r.record; return { source: 'ocr', json: { isPassport: true, mrzLines: r.mrz?.lines ?? (rec.mrz ? rec.mrz.split('\n') : []), documentCode: rec.documentCode, issuingState: rec.issuingState, surname: rec.surname, givenNames: rec.givenNames, fullNameNative: rec.fullName, documentNumber: rec.documentNumber, nationality: rec.nationality, birthDate: rec.birthDate, sex: rec.sex, placeOfBirth: rec.placeOfBirth, placeOfIssue: rec.placeOfIssue, issueDate: rec.issueDate, expiryDate: rec.expiryDate, authority: rec.authority, personalNumber: rec.personalNumber, notes: '', } as LlmOutput, };}
export interface Fixed { prompt: number; schema: number; exact: boolean }
/** Phần cố định mỗi request: prompt + schema (giống nhau cho mọi ảnh) */export async function fixedTokens(): Promise<Fixed> { const [p, s] = await Promise.all([countTextTokens(promptText()), countTextTokens(JSON.stringify(SCHEMA))]); return { prompt: p.tokens, schema: s.tokens, exact: p.exact && s.exact };}
export async function itemTokens(it: StoredItem, rule: ImageTokenRule, fixed: Fixed, withJson = false): Promise<ItemTokens> { const w = it.width ?? 0; const h = it.height ?? 0; const img = imageTokens(w, h, rule); const out = outputJson(it); const text = out.json ? JSON.stringify(out.json) : ''; const o = await countTextTokens(text); const input = img.tokens + fixed.prompt + fixed.schema; return { id: it.id, name: it.name, status: it.status, sentToLlm: !!it.result?.sources.includes('llm'), image: { bytes: it.size, base64Bytes: base64Size(it.size), width: w, height: h, megapixels: +((w * h) / 1e6).toFixed(2), mime: it.mime }, input: { image: img, prompt: fixed.prompt, schema: fixed.schema, total: input }, output: { source: out.source, jsonChars: text.length, jsonBytes: Buffer.byteLength(text, 'utf8'), tokens: o.tokens, ...(withJson ? { json: out.json } : {}) }, total: input + o.tokens, exact: fixed.exact && o.exact, };}
/* ------------------------------------------------------------------ cả lô */
export function currentRule() { return imageTokenRule(llmModel(), process.env.GEMINI_IMAGE_TOKENS);}
export function formulaInfo(rule: ImageTokenRule): TokenFormula { const image = rule.kind === 'fixed' ? `${rule.tokensPerImage} token / ảnh (cố định theo cấu hình GEMINI_IMAGE_TOKENS)` : 'tính theo kích thước từng ảnh: ≤ 384px cả 2 chiều = 258; còn lại ô = clamp(⌊min(w,h)/1.5⌋, 256, 768), số ô = ⌈w/ô⌉ × ⌈h/ô⌉, token = số ô × 258' + (rule.cap !== undefined ? `; Gemini 3+ chặn tối đa ${rule.cap} token / ảnh (media_resolution)` : ''); return { model: llmModel(), imageRule: rule.label, input: 'token ảnh + token prompt + token JSON schema', image, output: 'token của chuỗi JSON đầu ra (đếm bằng tokenizer Gemini local); chưa gồm token "thinking" nếu model bật suy nghĩ', note: 'Dung lượng file (KB/MB) không ảnh hưởng số token — Google tính trên số pixel; dung lượng chỉ làm request nặng hơn (base64 ≈ 4/3).', docs: GEMINI_TOKEN_DOCS, };}
const emptySum = emptyTokenSum;function add(s: TokenSum, x: ItemTokens) { s.images++; s.bytes += x.image.bytes; s.imageTokens += x.input.image.tokens; s.inputTokens += x.input.total; s.outputTokens += x.output.tokens; s.totalTokens += x.total;}
export async function batchTokens(items: StoredItem[]) { const rule = currentRule(); const fixed = await fixedTokens(); const rows: ItemTokens[] = []; for (const it of [...items].sort((a, b) => a.createdAt - b.createdAt || a.name.localeCompare(b.name))) { rows.push(await itemTokens(it, rule, fixed)); } /** nếu gửi MỌI ảnh cho Gemini */ const all = emptySum(); /** chỉ các ảnh đã thực sự qua Gemini (chi phí đã phát sinh) */ const sent = emptySum(); for (const r of rows) { add(all, r); if (r.sentToLlm) add(sent, r); } const avg = (n: number) => (all.images ? Math.round(n / all.images) : 0); return { formula: formulaInfo(rule), prices: tokenPrices(), fixedPerRequest: fixed, total: { all, sentToLlm: sent, avgPerImage: { input: avg(all.inputTokens), output: avg(all.outputTokens), total: avg(all.totalTokens) } }, exact: rows.every((r) => r.exact) && fixed.exact, items: rows, };}
/* ------------------------------------------------------------------ theo thời gian (mọi lô) */
/** Đơn giá mặc định: Gemini 3.1 Flash-Lite gói trả phí, tier Standard (USD / 1M token), đổi bằng GEMINI_PRICE_INPUT / GEMINI_PRICE_OUTPUT */export function tokenPrices(): TokenPrices { const n = (v: string | undefined, d: number) => (v && Number.isFinite(Number(v)) && Number(v) >= 0 ? Number(v) : d); return { input: n(process.env.GEMINI_PRICE_INPUT, 0.25), output: n(process.env.GEMINI_PRICE_OUTPUT, 1.5), note: 'Bảng giá Gemini 3.1 Flash-Lite (gói trả phí, Standard): input 0,25 USD (text/ảnh/video), output 1,5 USD (gồm token thinking) / 1M token. Gói miễn phí thì chi phí = 0.', };}
/** cache kết quả từng ảnh: chỉ tính lại khi ảnh đổi hoặc luật tính đổi */const memo = new Map<string, { key: string; row: ItemTokens }>();
export async function usageReport(items: StoredItem[], batchOf: (id: string) => Batch | null | undefined): Promise<TokenUsageReport> { const rule = currentRule(); const fixed = await fixedTokens(); const ruleKey = `${rule.label}|${fixed.prompt}|${fixed.schema}`; const days = new Map<string, UsageDay>(); const batches = new Map<string, UsageBatch>(); let exact = fixed.exact; const live = new Set<string>(); for (const it of items) { live.add(it.id); const key = `${ruleKey}|${it.updatedAt}`; let row = memo.get(it.id)?.key === key ? memo.get(it.id)!.row : null; if (!row) { row = await itemTokens(it, rule, fixed); memo.set(it.id, { key, row }); } exact &&= row.exact; const one: TokenSum = { images: 1, bytes: row.image.bytes, imageTokens: row.input.image.tokens, inputTokens: row.input.total, outputTokens: row.output.tokens, totalTokens: row.total, }; const date = vnDay(it.createdAt); const dk = `${date}|${it.batchId}`; const d = days.get(dk) ?? { date, batchId: it.batchId, all: emptySum(), sent: emptySum() }; addTokenSum(d.all, one); if (row.sentToLlm) addTokenSum(d.sent, one); days.set(dk, d); let b = batches.get(it.batchId); if (!b) { const meta = batchOf(it.batchId); b = { id: it.batchId, name: meta?.name ?? it.batchId, createdAt: meta?.createdAt ?? it.createdAt, all: emptySum(), sent: emptySum() }; batches.set(it.batchId, b); } addTokenSum(b.all, one); if (row.sentToLlm) addTokenSum(b.sent, one); } for (const id of memo.keys()) if (!live.has(id)) memo.delete(id); return { formula: formulaInfo(rule), fixedPerRequest: fixed, prices: tokenPrices(), exact, days: [...days.values()].sort((a, b) => a.date.localeCompare(b.date)), batches: [...batches.values()].sort((a, b) => b.createdAt - a.createdAt), };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159/** * Nhận upload multipart (ảnh và file .zip), ghi tạm ra đĩa theo luồng (không giữ cả file lớn trong RAM), * giải nén zip, chuẩn hoá từng ảnh. */import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';import { pipeline } from 'node:stream/promises';import { Transform } from 'node:stream';import type { Request } from 'express';import busboy from 'busboy';import yauzl from 'yauzl';import { IMAGE_EXT, WORK_DIR, ZIP_EXT, normalizeImage, type NormalizedImage } from './media.ts';
const MB = 1024 * 1024;const MAX_IMAGE = Number(process.env.MAX_IMAGE_MB ?? 50) * MB;const MAX_ZIP = Number(process.env.MAX_ZIP_MB ?? 50) * MB;const MAX_ZIP_ENTRIES = Number(process.env.MAX_ZIP_ENTRIES ?? 5000);const MAX_ZIP_TOTAL = Number(process.env.MAX_ZIP_UNCOMPRESSED_MB ?? 4096) * MB;const UPLOADS = path.join(WORK_DIR, 'uploads');fs.mkdirSync(UPLOADS, { recursive: true });
export interface Accepted { name: string; size: number; sha256: string; img: NormalizedImage }export interface UploadResult { accepted: number; skipped: { name: string; reason: string }[] }type Sink = { out: UploadResult; buf: Accepted[]; flush: (a: Accepted[]) => Promise<void>; chain: Promise<void> };
/** Gom ảnh đã chuẩn hoá, mỗi 20 ảnh đẩy sang hàng đợi (ghi đĩa) để không giữ cả lô trong RAM */function push(sink: Sink, a: Accepted): Promise<void> { sink.buf.push(a); sink.out.accepted++; if (sink.buf.length < 20) return sink.chain; return drain(sink);}function drain(sink: Sink): Promise<void> { const take = sink.buf.splice(0); if (take.length) sink.chain = sink.chain.then(() => sink.flush(take)); return sink.chain;}
class LimitError extends Error {}
/** Đếm byte + giới hạn kích thước khi ghi luồng */function limiter(max: number, what: string) { let n = 0; return new Transform({ transform(chunk: Buffer, _enc, cb) { n += chunk.length; if (n > max) cb(new LimitError(`${what} vượt quá ${Math.round(max / MB)}MB`)); else cb(null, chunk); }, });}
const sha256 = (b: Buffer) => crypto.createHash('sha256').update(b).digest('hex');
async function acceptImage(buf: Buffer, name: string, sink: Sink) { let img: NormalizedImage; try { img = await normalizeImage(buf, name); } catch (e) { sink.out.skipped.push({ name, reason: (e as Error).message }); return; } await push(sink, { name, size: buf.length, sha256: sha256(buf), img });}
/** Bỏ file rác của macOS / Windows trong zip */const junk = (p: string) => /(^|\/)(__MACOSX|\.DS_Store|Thumbs\.db)(\/|$)|(^|\/)\._/.test(p);
async function extractZip(file: string, zipName: string, sink: Sink) { const out = sink.out; const zip = await new Promise<yauzl.ZipFile>((res, rej) => yauzl.open(file, { lazyEntries: true, autoClose: true }, (e, z) => (e ? rej(e) : res(z!))), ); let entries = 0; let total = 0; const prefix = zipName.replace(ZIP_EXT, ''); await new Promise<void>((resolve, reject) => { zip.on('error', reject); zip.on('end', resolve); zip.on('entry', async (entry: yauzl.Entry) => { try { const p = entry.fileName; if (p.endsWith('/') || junk(p)) return zip.readEntry(); const name = `${prefix}/${p}`; if (!IMAGE_EXT.test(p)) { out.skipped.push({ name, reason: ZIP_EXT.test(p) ? 'Không hỗ trợ zip lồng nhau' : 'Không phải ảnh' }); return zip.readEntry(); } if (++entries > MAX_ZIP_ENTRIES) throw new LimitError(`File zip có quá ${MAX_ZIP_ENTRIES} ảnh`); if (entry.uncompressedSize > MAX_IMAGE) { out.skipped.push({ name, reason: `Ảnh vượt quá ${MAX_IMAGE / MB}MB` }); return zip.readEntry(); } total += entry.uncompressedSize; if (total > MAX_ZIP_TOTAL) throw new LimitError(`Dung lượng giải nén vượt quá ${MAX_ZIP_TOTAL / MB}MB`); const stream = await new Promise<NodeJS.ReadableStream>((res, rej) => zip.openReadStream(entry, (e, s) => (e ? rej(e) : res(s!)))); const chunks: Buffer[] = []; // không tin uncompressedSize khai trong zip: giới hạn lại khi đọc await pipeline(stream, limiter(MAX_IMAGE, name), async function* (src) { for await (const c of src) chunks.push(c as Buffer); }); await acceptImage(Buffer.concat(chunks), name, sink); zip.readEntry(); } catch (e) { zip.close(); reject(e); } }); zip.readEntry(); });}
/** Đọc request multipart. Trường `path` (tuỳ chọn) đứng trước mỗi file = đường dẫn tương đối trong thư mục. */export async function receiveUpload(req: Request, flush: (a: Accepted[]) => Promise<void>): Promise<UploadResult> { const out: UploadResult = { accepted: 0, skipped: [] }; const sink: Sink = { out, buf: [], flush, chain: Promise.resolve() }; const work: Promise<void>[] = []; const temps: string[] = []; const paths: string[] = []; try { await new Promise<void>((resolve, reject) => { const bb = busboy({ headers: req.headers, limits: { files: 500, fileSize: Math.max(MAX_ZIP, MAX_IMAGE) + 1, fields: 600 } }); bb.on('field', (name, val) => { if (name === 'path') paths.push(val.slice(0, 500)); }); bb.on('file', (_field, stream, info) => { const rel = (paths.shift() || info.filename || 'image').replace(/\\/g, '/').replace(/^\/+/, ''); const isZip = ZIP_EXT.test(rel) || /zip/.test(info.mimeType); if (!isZip && !IMAGE_EXT.test(rel) && !info.mimeType.startsWith('image/')) { out.skipped.push({ name: rel, reason: 'Không phải ảnh hoặc file .zip' }); return void stream.resume(); } const tmp = path.join(UPLOADS, crypto.randomBytes(12).toString('hex')); temps.push(tmp); const max = isZip ? MAX_ZIP : MAX_IMAGE; const written = pipeline(stream, limiter(max, rel), fs.createWriteStream(tmp)); work.push( written .then(async () => { if (isZip) await extractZip(tmp, rel, sink); else await acceptImage(fs.readFileSync(tmp), rel, sink); }) .catch((e) => { stream.resume(); out.skipped.push({ name: rel, reason: e instanceof LimitError ? e.message : `Lỗi đọc file: ${(e as Error).message}` }); }), ); }); bb.on('error', reject); bb.on('close', resolve); req.on('aborted', () => reject(new Error('Upload bị huỷ'))); req.pipe(bb); }); await Promise.all(work); await drain(sink); } finally { for (const t of temps) fs.rmSync(t, { force: true }); } return out;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273/** * Bảng người dùng (Firestore `users/{id}`) + đăng nhập. * * Hai cách đăng nhập, đều phải có tên trong bảng users (bảng này thay cho danh sách cho phép): * - Google: trình duyệt đăng nhập Google qua Firebase Auth, gửi ID token cho server Next.js -> backend xác minh * bằng firebase-admin, khớp email với bảng users. Email thuộc ALLOWED_EMAILS mà chưa có trong bảng -> tự tạo (quyền user). * - Email / mật khẩu: chỉ cho tài khoản được admin đặt mật khẩu (mật khẩu băm scrypt, salt riêng từng người). * - Đăng nhập thành công -> token phiên ký HMAC (AUTH_SECRET). Frontend Next.js giữ token trong cookie httpOnly, * trình duyệt không bao giờ thấy token hay gọi thẳng backend. * - Token mang `v` = tokenVersion của user: đổi mật khẩu / khoá tài khoản -> tăng version -> mọi phiên cũ hết hiệu lực. * - Toàn bộ bảng user giữ trong RAM (ít bản ghi, chỉ 1 instance ghi) giống cache lô / khách. * - Bảng trống + có ADMIN_EMAIL (ADMIN_PASSWORD tuỳ chọn) -> tự tạo tài khoản admin đầu tiên lúc khởi động. */import crypto from 'node:crypto';import { promisify } from 'node:util';import { getAuth } from 'firebase-admin/auth';import { db, fbApp } from './firebase.ts';
export type Role = 'admin' | 'user';
export interface UserDoc { id: string; email: string; name: string; role: Role; disabled: boolean; /** được xem trang Chi phí Gemini (admin luôn được) */ costAccess?: boolean; /** không có = chỉ đăng nhập bằng Google */ passwordHash?: string; tokenVersion: number; createdAt: number; updatedAt: number; createdBy?: string; lastLoginAt?: number;}
/** Dữ liệu user trả ra ngoài (không có hash) */export type PublicUser = Omit<UserDoc, 'passwordHash' | 'tokenVersion'> & { hasPassword: boolean };
const users = () => db().collection('users');const cache = new Map<string, UserDoc>();let loaded: Promise<void> | null = null;
const httpError = (status: number, message: string, code?: string) => Object.assign(new Error(message), { status, code });export const publicUser = ({ passwordHash, tokenVersion: _v, ...u }: UserDoc): PublicUser => ({ ...u, hasPassword: !!passwordHash });const normEmail = (e: unknown) => (typeof e === 'string' ? e.trim().toLowerCase() : '');const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;/** Tên đăng nhập (không phải email): 3-50 ký tự chữ, số, . _ - */const USERNAME_RE = /^[a-z0-9][a-z0-9._-]{2,49}$/;export const MIN_PASSWORD = 8;
/* ------------------------------------------------------------------ mật khẩu */
const scrypt = promisify(crypto.scrypt) as (pw: string, salt: Buffer, len: number, opt: crypto.ScryptOptions) => Promise<Buffer>;const SCRYPT = { N: 16384, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
async function hashPassword(pw: string): Promise<string> { const salt = crypto.randomBytes(16); const key = await scrypt(pw, salt, 32, SCRYPT); return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${salt.toString('base64url')}$${key.toString('base64url')}`;}
async function verifyPassword(pw: string, stored: string | undefined): Promise<boolean> { if (!stored) return false; const [algo, n, r, p, salt, hash] = stored.split('$'); if (algo !== 'scrypt' || !salt || !hash) return false; const expected = Buffer.from(hash, 'base64url'); const key = await scrypt(pw, Buffer.from(salt, 'base64url'), expected.length, { N: +n, r: +r, p: +p, maxmem: SCRYPT.maxmem }); return crypto.timingSafeEqual(key, expected);}
function checkPassword(pw: unknown): string { if (typeof pw !== 'string' || pw.length < MIN_PASSWORD) throw httpError(400, `Mật khẩu cần ít nhất ${MIN_PASSWORD} ký tự`); if (pw.length > 200) throw httpError(400, 'Mật khẩu quá dài'); return pw;}
/* ------------------------------------------------------------------ token phiên */
const TOKEN_TTL = Number(process.env.AUTH_TOKEN_DAYS ?? 7) * 86_400_000;
function secret(): Buffer { const s = process.env.AUTH_SECRET; if (!s || s.length < 32) throw new Error('AUTH_SECRET cần ít nhất 32 ký tự'); return Buffer.from(s);}export const authConfigured = () => (process.env.AUTH_SECRET ?? '').length >= 32;
const sign = (body: string) => crypto.createHmac('sha256', secret()).update(body).digest('base64url');
function issueToken(u: UserDoc): { token: string; expiresAt: number } { const expiresAt = Date.now() + TOKEN_TTL; const body = Buffer.from(JSON.stringify({ uid: u.id, v: u.tokenVersion, exp: expiresAt })).toString('base64url'); return { token: `${body}.${sign(body)}`, expiresAt };}
/** Token hợp lệ -> user; sai chữ ký / hết hạn / user bị khoá / đã đổi mật khẩu -> null */export function userFromToken(token: string): UserDoc | null { const [body, mac] = token.split('.'); if (!body || !mac) return null; const a = Buffer.from(mac); const b = Buffer.from(sign(body)); if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null; try { const p = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as { uid: string; v: number; exp: number }; if (!p.exp || p.exp < Date.now()) return null; const u = cache.get(p.uid); if (!u || u.disabled || u.tokenVersion !== p.v) return null; return u; } catch { return null; }}
/* ------------------------------------------------------------------ cache + khởi tạo */
export function loadUsers(): Promise<void> { loaded ??= (async () => { const snap = await users().get(); for (const d of snap.docs) cache.set(d.id, d.data() as UserDoc); if (!cache.size) await bootstrapAdmin(); console.log(`users: ${cache.size} tài khoản`); })().catch((e) => { loaded = null; throw e; }); return loaded;}export const usersReady = () => loaded;
async function bootstrapAdmin() { const email = normEmail(process.env.ADMIN_EMAIL); const pw = process.env.ADMIN_PASSWORD ?? ''; if (!email) { console.warn('Chưa có tài khoản nào: đặt ADMIN_EMAIL (+ ADMIN_PASSWORD nếu muốn đăng nhập mật khẩu) để tạo admin đầu tiên'); return; } // không có ADMIN_PASSWORD -> admin đăng nhập bằng Google await createUser({ email, password: pw || undefined, name: 'Admin', role: 'admin' }, 'bootstrap'); console.log(`đã tạo admin đầu tiên: ${email}`);}
const byEmail = (email: string) => [...cache.values()].find((u) => u.email === email);
async function save(u: UserDoc) { await users().doc(u.id).set(JSON.parse(JSON.stringify(u))); cache.set(u.id, u);}
/* ------------------------------------------------------------------ nghiệp vụ */
// hash giả để so khi email không tồn tại -> thời gian phản hồi như nhau (không dò được email)let dummyHash: Promise<string> | null = null;
export async function login(emailIn: unknown, pw: unknown): Promise<{ token: string; expiresAt: number; user: PublicUser }> { const email = normEmail(emailIn); const password = typeof pw === 'string' ? pw : ''; const u = byEmail(email); if (!u) { await verifyPassword(password, await (dummyHash ??= hashPassword('x'.repeat(16)))); throw httpError(401, 'Sai tài khoản hoặc mật khẩu', 'bad_credentials'); } if (!u.passwordHash) { await verifyPassword(password, await (dummyHash ??= hashPassword('x'.repeat(16)))); throw httpError(401, 'Tài khoản này đăng nhập bằng Google', 'google_only'); } if (!(await verifyPassword(password, u.passwordHash))) throw httpError(401, 'Sai tài khoản hoặc mật khẩu', 'bad_credentials'); return startSession(u);}
async function startSession(u: UserDoc) { if (u.disabled) throw httpError(403, 'Tài khoản đã bị khoá', 'disabled'); const next = { ...u, lastLoginAt: Date.now() }; await save(next); return { ...issueToken(next), user: publicUser(next) };}
const ALLOWED = (process.env.ALLOWED_EMAILS ?? '').split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);const autoAllowed = (email: string) => ALLOWED.some((a) => (a.startsWith('@') ? email.endsWith(a) : email === a));
/** Đăng nhập Google: xác minh Firebase ID token, khớp email với bảng users */export async function loginGoogle(idToken: unknown) { if (typeof idToken !== 'string' || !idToken) throw httpError(400, 'Thiếu ID token'); let email = ''; let name = ''; try { const t = await getAuth(fbApp()).verifyIdToken(idToken); if (!t.email || !t.email_verified) throw new Error('unverified'); email = t.email.toLowerCase(); name = typeof t.name === 'string' ? t.name : ''; } catch { throw httpError(401, 'Không xác minh được tài khoản Google, hãy thử lại', 'bad_google_token'); } let u = byEmail(email); if (!u && autoAllowed(email)) { await createUser({ email, name, role: 'user' }, 'ALLOWED_EMAILS'); u = byEmail(email); } if (!u) throw httpError(403, `${email} chưa được cấp quyền — nhờ admin thêm vào danh sách người dùng`, 'not_registered'); if (!u.name && name) u = { ...u, name }; return startSession(u);}
export function listUsers(): PublicUser[] { return [...cache.values()].sort((a, b) => a.createdAt - b.createdAt).map(publicUser);}
export const hasCostAccess = (u: Pick<UserDoc, 'role' | 'costAccess'>) => u.role === 'admin' || !!u.costAccess;
export async function createUser(input: { email?: unknown; password?: unknown; name?: unknown; role?: unknown; costAccess?: unknown }, by: string): Promise<PublicUser> { const email = normEmail(input.email); if (!(EMAIL_RE.test(email) && email.length <= 200) && !USERNAME_RE.test(email)) throw httpError(400, 'Nhập email hợp lệ hoặc username (3-50 ký tự: chữ, số, . _ -)'); if (byEmail(email)) throw httpError(409, 'Email / username đã tồn tại'); const now = Date.now(); const u: UserDoc = { id: crypto.randomBytes(10).toString('base64url'), email, name: typeof input.name === 'string' ? input.name.trim().slice(0, 100) : '', role: input.role === 'admin' ? 'admin' : 'user', disabled: false, costAccess: input.costAccess === true, // bỏ trống mật khẩu = chỉ đăng nhập bằng Google passwordHash: input.password === undefined || input.password === '' ? undefined : await hashPassword(checkPassword(input.password)), tokenVersion: 1, createdAt: now, updatedAt: now, createdBy: by, }; await save(u); return publicUser(u);}
const activeAdmins = (except?: string) => [...cache.values()].filter((u) => u.role === 'admin' && !u.disabled && u.id !== except).length;
/** Admin sửa user: tên, quyền, quyền xem chi phí, khoá / mở khoá, đặt lại mật khẩu */export async function updateUser(id: string, patch: { name?: unknown; role?: unknown; disabled?: unknown; password?: unknown; costAccess?: unknown }): Promise<PublicUser> { const u = cache.get(id); if (!u) throw httpError(404, 'Không tìm thấy người dùng'); const next: UserDoc = { ...u, updatedAt: Date.now() }; if (typeof patch.name === 'string') next.name = patch.name.trim().slice(0, 100); if (patch.role === 'admin' || patch.role === 'user') next.role = patch.role; if (typeof patch.disabled === 'boolean') next.disabled = patch.disabled; if (typeof patch.costAccess === 'boolean') next.costAccess = patch.costAccess; // password: chuỗi = đặt mật khẩu mới, null = bỏ mật khẩu (chỉ đăng nhập Google) if (patch.password === null) delete next.passwordHash; else if (patch.password !== undefined) next.passwordHash = await hashPassword(checkPassword(patch.password)); // luôn phải còn ít nhất 1 admin hoạt động if (u.role === 'admin' && !u.disabled && (next.role !== 'admin' || next.disabled) && !activeAdmins(id)) { throw httpError(400, 'Phải còn ít nhất 1 admin đang hoạt động'); } // đổi mật khẩu / khoá / hạ quyền -> đăng xuất mọi phiên của user đó if (patch.password !== undefined || next.disabled !== u.disabled || next.role !== u.role) next.tokenVersion = u.tokenVersion + 1; await save(next); return publicUser(next);}
export async function deleteUser(id: string, by: string) { const u = cache.get(id); if (!u) throw httpError(404, 'Không tìm thấy người dùng'); if (id === by) throw httpError(400, 'Không thể tự xoá tài khoản của mình'); if (u.role === 'admin' && !u.disabled && !activeAdmins(id)) throw httpError(400, 'Phải còn ít nhất 1 admin đang hoạt động'); await users().doc(id).delete(); cache.delete(id);}
/** Người dùng tự đổi mật khẩu -> trả token mới (các phiên khác bị đăng xuất) */export async function changeOwnPassword(id: string, current: unknown, nextPw: unknown) { const u = cache.get(id); if (!u) throw httpError(404, 'Không tìm thấy người dùng'); // chưa có mật khẩu (tài khoản Google) -> được đặt mật khẩu lần đầu không cần mật khẩu cũ if (u.passwordHash && (typeof current !== 'string' || !(await verifyPassword(current, u.passwordHash)))) throw httpError(400, 'Mật khẩu hiện tại không đúng'); const next: UserDoc = { ...u, passwordHash: await hashPassword(checkPassword(nextPw)), tokenVersion: u.tokenVersion + 1, updatedAt: Date.now() }; await save(next); return { ...issueToken(next), user: publicUser(next) };}1{ "extends": "../../tsconfig.base.json", "compilerOptions": { "lib": ["ES2022"], "types": ["node"] }, "include": ["src"] }.dockerignore+18-11
.env.example+58-10
.gitattributesAdded+1
.gitignore+29-15
CaddyfileAdded+32
Dockerfile+55-24
README.md+24-180
extractor/.dockerignoreAdded+12
extractor/.env.exampleAdded+13
extractor/.gitignoreAdded+21
extractor/DockerfileAdded+26
HUGGINGFACE_DEPLOY.md → extractor/HUGGINGFACE_DEPLOY.mdRenamed
extractor/README.mdAdded+202
package.json → extractor/package.jsonRenamed
pnpm-lock.yaml → extractor/pnpm-lock.yamlRenamed
public/app.js → extractor/public/app.jsRenamed+7-7
public/index.html → extractor/public/index.htmlRenamed
public/styles.css → extractor/public/styles.cssRenamed
server/controllers/archiveController.js → extractor/server/controllers/archiveController.jsRenamed
server/index.js → extractor/server/index.jsRenamed
server/middleware/security.js → extractor/server/middleware/security.jsRenamed
server/routes/api.js → extractor/server/routes/api.jsRenamed
server/services/extractionService.js → extractor/server/services/extractionService.jsRenamed
server/utils/fileTree.js → extractor/server/utils/fileTree.jsRenamed
passport-check/.dockerignoreAdded+11
passport-check/.env.exampleAdded+61
passport-check/.github/workflows/deploy.ymlAdded+32
passport-check/.gitignoreAdded+42
passport-check/CaddyfileAdded+6
passport-check/DockerfileAdded+30
passport-check/FEATURES.mdAdded+120
passport-check/README.mdAdded+204
passport-check/apps/server/build.mjsAdded+13
passport-check/apps/server/package.jsonAdded+29
passport-check/apps/server/src/auth.tsAdded+54
passport-check/apps/server/src/cost-settings.tsAdded+59
passport-check/apps/server/src/firebase.tsAdded+43
passport-check/apps/server/src/gemini.tsAdded+98
passport-check/apps/server/src/heic-convert.d.tsAdded+4
passport-check/apps/server/src/index.tsAdded+413
passport-check/apps/server/src/jobs.tsAdded+531
passport-check/apps/server/src/media.tsAdded+104
passport-check/apps/server/src/ocr.tsAdded+88
passport-check/apps/server/src/telegram.tsAdded+85
passport-check/apps/server/src/tokens.tsAdded+219
passport-check/apps/server/src/upload.tsAdded+159
passport-check/apps/server/src/users.tsAdded+273
passport-check/apps/server/templates/cong-van-bp.xlsxAdded
passport-check/apps/server/templates/thong-tin-ho-chieu.xlsxAdded
passport-check/apps/server/tsconfig.jsonAdded+1