Spaces:
Running
Running
Deploy 669bef9 từ GitHub Actions
Browse filesFiles changed (2)
7 unmodified lines891011121357 unmodified lines717273747576777879808123 unmodified lines10510610710810911011119 unmodified lines1311321331341351361377 unmodified linesconst 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;57 unmodified linesmethod: 'POST',body: isForm ? body : JSON.stringify(body),headers: isForm ? undefined : { 'content-type': 'application/json' },signal: AbortSignal.timeout(120_000),});} catch (e) {const err = e as Error & { cause?: { code?: string; message?: string } };if (err.name === 'TimeoutError' || err.name === 'AbortError') throw new TelegramError('Hết thời gian chờ Telegram (120s)', 'timeout', undefined, undefined, true, 504);const why = err.cause?.code ?? err.cause?.message ?? err.message;throw new TelegramError(`Không kết nối được Telegram (${why}) — kiểm tra mạng / DNS / TELEGRAM_API_URL`, 'network', undefined, undefined, true, 502);}23 unmodified lines} catch (e) {const err = e as TelegramError;const transient = err.transient === true;if (!transient || attempt >= 5) throw e;await new Promise((r) => setTimeout(r, (err.retryAfter ?? 2 ** attempt) * 1000 + 250));}}19 unmodified linesexport 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());}7 unmodified lines8910111213141557 unmodified lines737475767778798081828323 unmodified lines10710810911011111211319 unmodified lines1331341351361371381397 unmodified linesconst 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 ?? '';/** phải < 100s (Cloudflare trả 524 nếu origin không phản hồi trong 100s) */const TIMEOUT_MS = Number(process.env.TELEGRAM_TIMEOUT_MS ?? 25_000);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;57 unmodified linesmethod: 'POST',body: isForm ? body : JSON.stringify(body),headers: isForm ? undefined : { 'content-type': 'application/json' },signal: AbortSignal.timeout(TIMEOUT_MS),});} catch (e) {const err = e as Error & { cause?: { code?: string; message?: string } };if (err.name === 'TimeoutError' || err.name === 'AbortError') throw new TelegramError(`Hết thời gian chờ Telegram (${TIMEOUT_MS / 1000}s) — server có thể không truy cập được api.telegram.org (bị chặn mạng/DNS)`, 'timeout', undefined, undefined, true, 504);const why = err.cause?.code ?? err.cause?.message ?? err.message;throw new TelegramError(`Không kết nối được Telegram (${why}) — kiểm tra mạng / DNS / TELEGRAM_API_URL`, 'network', undefined, undefined, true, 502);}23 unmodified lines} catch (e) {const err = e as TelegramError;const transient = err.transient === true;if (!transient || attempt >= (err.code === 'timeout' || err.code === 'network' ? 0 : 5)) throw e;await new Promise((r) => setTimeout(r, (err.retryAfter ?? 2 ** attempt) * 1000 + 250));}}19 unmodified linesexport 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(Math.max(TIMEOUT_MS, 120_000)) });if (!res.ok) throw new Error(`Tải ảnh từ Telegram lỗi HTTP ${res.status}`);return Buffer.from(await res.arrayBuffer());}
67 unmodified lines6869707172736 unmodified lines80818283848567 unmodified linesinit: { method: string; headers: Record<string, string>; body: ReadableStream<Uint8Array> | null; signal?: AbortSignal; token?: string; ip: string },): Promise<{ status: number; headers: http.IncomingHttpHeaders; body: ReadableStream<Uint8Array> }> {const url = new URL(path.replace(/^\//, ''), base());const mod = url.protocol === 'https:' ? https : http;return new Promise((resolve, reject) => {const req = mod.request(url, { method: init.method, headers: { ...init.headers, ...authHeaders(init.token, init.ip) }, timeout: 0 }, (res) => {6 unmodified lines});}/* ------------------------------------------------------------------ phiên đăng nhập */export async function sessionToken(): Promise<string | undefined> {67 unmodified lines686970717273746 unmodified lines8182838485868788899091929394959697989910010110210310410510610710810911011111211367 unmodified linesinit: { method: string; headers: Record<string, string>; body: ReadableStream<Uint8Array> | null; signal?: AbortSignal; token?: string; ip: string },): Promise<{ status: number; headers: http.IncomingHttpHeaders; body: ReadableStream<Uint8Array> }> {const url = new URL(path.replace(/^\//, ''), base());if (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') return workerStream(url, init);const mod = url.protocol === 'https:' ? https : http;return new Promise((resolve, reject) => {const req = mod.request(url, { method: init.method, headers: { ...init.headers, ...authHeaders(init.token, init.ip) }, timeout: 0 }, (res) => {6 unmodified lines});}/*** Cloudflare Workers: shim node:http của workerd không ổn định khi pipe body multipart (treo -> 524, cảnh báo waitUntil).* Dùng fetch gốc, stream request body (duplex: 'half') và response body.*/async function workerStream(url: URL,init: { method: string; headers: Record<string, string>; body: ReadableStream<Uint8Array> | null; signal?: AbortSignal; token?: string; ip: string },) {const hasBody = !!init.body && init.method !== 'GET' && init.method !== 'HEAD';let res: Response;try {res = await fetch(url, {method: init.method,headers: { ...init.headers, ...authHeaders(init.token, init.ip) },body: hasBody ? init.body : undefined,...(hasBody ? { duplex: 'half' } : {}),signal: init.signal,redirect: 'manual',} as RequestInit);} catch {throw new BackendError(502, 'Không kết nối được backend (Space có thể đang ngủ / khởi động lại)');}const headers: http.IncomingHttpHeaders = {};res.headers.forEach((v, k) => { headers[k] = v; });return { status: res.status, headers, body: res.body ?? new ReadableStream<Uint8Array>({ start: (c) => c.close() }) };}/* ------------------------------------------------------------------ phiên đăng nhập */export async function sessionToken(): Promise<string | undefined> {
passport-check/apps/server/src/telegram.ts+6-4
passport-check/apps/web/src/lib/server/backend.ts+28