GeminiBot commited on
Commit ·
a521d64
1
Parent(s): b7a1bf8
Operational deploy with camouflage UI
Browse filesFiles changed (4)
- package.json+4-23
- server.ts+9-1
- src/duckai.ts+32-476
- src/server.ts+56-110
123456789101112131415161718192021222324252627282930{"name": "duckai-openai-server","version": "1.0.0","description": "OpenAI-compatible HTTP server using Duck.ai backend","main": "src/server.ts","scripts": {"dev": "bun run --watch src/server.ts","start": "bun run src/server.ts","test": "bun test","test:watch": "bun test --watch","test:openai": "bun test tests/openai-simple.test.ts","test:openai-full": "bun test tests/openai-library.test.ts","test:tools": "bun test tests/tool-service.test.ts tests/openai-tools.test.ts","test:e2e": "bun test tests/e2e-tools.test.ts","test:all": "bun test tests/server.test.ts tests/openai-simple.test.ts tests/tool-service.test.ts tests/openai-tools.test.ts"},"dependencies": {"jsdom": "^25.0.1","openai": "^4.103.0","user-agents": "^1.1.0"},"devDependencies": {"@types/jsdom": "^21.1.7","@types/user-agents": "^1.0.4","bun-types": "latest"},"peerDependencies": {"typescript": "^5.0.0"}}1234567891011{"name": "duckai-openai-server","version": "1.0.0","main": "server.ts","dependencies": {"jsdom": "^25.0.1","got-scraping": "^4.0.0","fingerprint-generator": "^2.1.0","fingerprint-injector": "^2.1.0"}}
3 unmodified lines456789103 unmodified linesconst server = Bun.serve({port: process.env.PORT || 3000,async fetch(req) {const url = new URL(req.url);// CORS headers3 unmodified lines4567891011121314151617183 unmodified linesconst server = Bun.serve({port: process.env.PORT || 3000,async fetch(req) {const authHeader = req.headers.get("Authorization");const API_KEY = process.env.API_KEY || "MySecretKey_12345";if (authHeader !== `Bearer ${API_KEY}` && req.method !== "OPTIONS") {return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 });}console.log(`Received request: ${req.method} ${req.url}`);const url = new URL(req.url);// CORS headers
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510import UserAgent from "user-agents";import { JSDOM } from "jsdom";import { RateLimitStore } from "./rate-limit-store";import { SharedRateLimitMonitor } from "./shared-rate-limit-monitor";import type {ChatCompletionMessage,VQDResponse,DuckAIRequest,} from "./types";import { createHash } from "node:crypto";import { Buffer } from "node:buffer";// Rate limiting tracking with sliding windowinterface RateLimitInfo {requestTimestamps: number[]; // Array of request timestamps for sliding windowlastRequestTime: number;isLimited: boolean;retryAfter?: number;}export class DuckAI {private rateLimitInfo: RateLimitInfo = {requestTimestamps: [],lastRequestTime: 0,isLimited: false,};private rateLimitStore: RateLimitStore;private rateLimitMonitor: SharedRateLimitMonitor;// Conservative rate limiting - adjust based on observed limitsprivate readonly MAX_REQUESTS_PER_MINUTE = 20;private readonly WINDOW_SIZE_MS = 60 * 1000; // 1 minuteprivate readonly MIN_REQUEST_INTERVAL_MS = 1000; // 1 second between requestsconstructor() {this.rateLimitStore = new RateLimitStore();this.rateLimitMonitor = new SharedRateLimitMonitor();this.loadRateLimitFromStore();}/*** Clean old timestamps outside the sliding window*/private cleanOldTimestamps(): void {const now = Date.now();const cutoff = now - this.WINDOW_SIZE_MS;this.rateLimitInfo.requestTimestamps =this.rateLimitInfo.requestTimestamps.filter((timestamp) => timestamp > cutoff);}/*** Get current request count in sliding window*/private getCurrentRequestCount(): number {this.cleanOldTimestamps();return this.rateLimitInfo.requestTimestamps.length;}/*** Load rate limit data from shared store*/private loadRateLimitFromStore(): void {const stored = this.rateLimitStore.read();if (stored) {// Convert old format to new sliding window format if neededconst storedAny = stored as any;if ("requestCount" in storedAny && "windowStart" in storedAny) {// Old format - convert to new format (start fresh)this.rateLimitInfo = {requestTimestamps: [],lastRequestTime: storedAny.lastRequestTime || 0,isLimited: storedAny.isLimited || false,retryAfter: storedAny.retryAfter,};} else {// New formatthis.rateLimitInfo = {requestTimestamps: storedAny.requestTimestamps || [],lastRequestTime: storedAny.lastRequestTime || 0,isLimited: storedAny.isLimited || false,retryAfter: storedAny.retryAfter,};}// Clean old timestamps after loadingthis.cleanOldTimestamps();}}/*** Save rate limit data to shared store*/private saveRateLimitToStore(): void {this.cleanOldTimestamps();this.rateLimitStore.write({requestTimestamps: this.rateLimitInfo.requestTimestamps,lastRequestTime: this.rateLimitInfo.lastRequestTime,isLimited: this.rateLimitInfo.isLimited,retryAfter: this.rateLimitInfo.retryAfter,} as any);}/*** Get current rate limit status*/getRateLimitStatus(): {requestsInCurrentWindow: number;maxRequestsPerMinute: number;timeUntilWindowReset: number;isCurrentlyLimited: boolean;recommendedWaitTime: number;} {// Load latest data from store firstthis.loadRateLimitFromStore();const now = Date.now();const currentRequestCount = this.getCurrentRequestCount();// For sliding window, there's no fixed reset time// The "reset" happens continuously as old requests fall out of the windowconst oldestTimestamp = this.rateLimitInfo.requestTimestamps[0];const timeUntilReset = oldestTimestamp? Math.max(0, oldestTimestamp + this.WINDOW_SIZE_MS - now): 0;const timeSinceLastRequest = now - this.rateLimitInfo.lastRequestTime;const recommendedWait = Math.max(0,this.MIN_REQUEST_INTERVAL_MS - timeSinceLastRequest);return {requestsInCurrentWindow: currentRequestCount,maxRequestsPerMinute: this.MAX_REQUESTS_PER_MINUTE,timeUntilWindowReset: timeUntilReset,isCurrentlyLimited: this.rateLimitInfo.isLimited,recommendedWaitTime: recommendedWait,};}/*** Check if we should wait before making a request*/private shouldWaitBeforeRequest(): { shouldWait: boolean; waitTime: number } {// Load latest data from store firstthis.loadRateLimitFromStore();const now = Date.now();const currentRequestCount = this.getCurrentRequestCount();// Check if we're hitting the rate limitif (currentRequestCount >= this.MAX_REQUESTS_PER_MINUTE) {// Find the oldest request timestampconst oldestTimestamp = this.rateLimitInfo.requestTimestamps[0];if (oldestTimestamp) {// Wait until the oldest request falls out of the windowconst waitTime = oldestTimestamp + this.WINDOW_SIZE_MS - now + 100; // +100ms bufferreturn { shouldWait: true, waitTime: Math.max(0, waitTime) };}}// Check minimum interval between requestsconst timeSinceLastRequest = now - this.rateLimitInfo.lastRequestTime;if (timeSinceLastRequest < this.MIN_REQUEST_INTERVAL_MS) {const waitTime = this.MIN_REQUEST_INTERVAL_MS - timeSinceLastRequest;return { shouldWait: true, waitTime };}return { shouldWait: false, waitTime: 0 };}/*** Wait if necessary before making a request*/private async waitIfNeeded(): Promise<void> {const { shouldWait, waitTime } = this.shouldWaitBeforeRequest();if (shouldWait) {console.log(`Rate limiting: waiting ${waitTime}ms before next request`);await new Promise((resolve) => setTimeout(resolve, waitTime));}}private async getEncodedVqdHash(vqdHash: string): Promise<string> {const jsScript = Buffer.from(vqdHash, 'base64').toString('utf-8');const dom = new JSDOM(`<iframe id="jsa" sandbox="allow-scripts allow-same-origin" srcdoc="<!DOCTYPE html><html><head><meta http-equiv="Content-Security-Policy"; content="default-src 'none'; script-src 'unsafe-inline'"></head><body></body></html>" style="position: absolute; left: -9999px; top: -9999px;"></iframe>`,{ runScripts: 'dangerously' });dom.window.top.__DDG_BE_VERSION__ = 1;dom.window.top.__DDG_FE_CHAT_HASH__ = 1;const jsa = dom.window.top.document.querySelector('#jsa') as HTMLIFrameElement;const contentDoc = jsa.contentDocument || jsa.contentWindow!.document;const meta = contentDoc.createElement('meta');meta.setAttribute('http-equiv', 'Content-Security-Policy');meta.setAttribute('content', "default-src 'none'; script-src 'unsafe-inline';");contentDoc.head.appendChild(meta);const result = await dom.window.eval(jsScript) as {client_hashes: string[];[key: string]: any;};result.client_hashes[0] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36';result.client_hashes = result.client_hashes.map((t) => {const hash = createHash('sha256');hash.update(t);return hash.digest('base64');});return btoa(JSON.stringify(result));}private async getVQD(userAgent: string): Promise<VQDResponse> {// Create AbortController with timeout for fetchconst vqdController = new AbortController();const vqdTimeoutId = setTimeout(() => vqdController.abort(), 10000); // 10 second timeout for VQDtry {const response = await fetch("https://duckduckgo.com/duckchat/v1/status", {headers: {accept: "*/*","accept-language": "en-US,en;q=0.9,fa;q=0.8","cache-control": "no-store",pragma: "no-cache",priority: "u=1, i","sec-fetch-dest": "empty","sec-fetch-mode": "cors","sec-fetch-site": "same-origin","x-vqd-accept": "1","User-Agent": userAgent,},referrer: "https://duckduckgo.com/",referrerPolicy: "origin",method: "GET",mode: "cors",credentials: "include",signal: vqdController.signal,});clearTimeout(vqdTimeoutId);if (!response.ok) {throw new Error(`Failed to get VQD: ${response.status} ${response.statusText}`);}const hashHeader = response.headers.get("x-Vqd-hash-1");if (!hashHeader) {throw new Error(`Missing VQD headers: hash=${!!hashHeader}`);}const encodedHash = await this.getEncodedVqdHash(hashHeader);return { hash: encodedHash };} catch (error) {clearTimeout(vqdTimeoutId);if (error instanceof Error && error.name === "AbortError") {throw new Error("VQD request timeout - took longer than 10 seconds");}throw error;}}private async hashClientHashes(clientHashes: string[]): Promise<string[]> {return Promise.all(clientHashes.map(async (hash) => {const encoder = new TextEncoder();const data = encoder.encode(hash);const hashBuffer = await crypto.subtle.digest("SHA-256", data);const hashArray = new Uint8Array(hashBuffer);return btoa(hashArray.reduce((str, byte) => str + String.fromCharCode(byte), ""));}));}async chat(request: DuckAIRequest): Promise<string> {// Wait if rate limiting is neededawait this.waitIfNeeded();const userAgent = new UserAgent().toString();const vqd = await this.getVQD(userAgent);// Update rate limit tracking BEFORE making the requestconst now = Date.now();this.rateLimitInfo.requestTimestamps.push(now);this.rateLimitInfo.lastRequestTime = now;this.saveRateLimitToStore();// Show compact rate limit status in server consolethis.rateLimitMonitor.printCompactStatus();// Create AbortController with timeout for fetchconst fetchController = new AbortController();const timeoutId = setTimeout(() => fetchController.abort(), 30000); // 30 second timeouttry {// Log the request being sent for debuggingconsole.log("Sending DuckAI request:", JSON.stringify(request, null, 2));const response = await fetch("https://duckduckgo.com/duckchat/v1/chat", {headers: {accept: "text/event-stream","accept-language": "en-US,en;q=0.9,fa;q=0.8","cache-control": "no-cache","content-type": "application/json",pragma: "no-cache",priority: "u=1, i","sec-fetch-dest": "empty","sec-fetch-mode": "cors","sec-fetch-site": "same-origin","x-fe-version": "serp_20250401_100419_ET-19d438eb199b2bf7c300","User-Agent": userAgent,"x-vqd-hash-1": vqd.hash,},referrer: "https://duckduckgo.com/",referrerPolicy: "origin",body: JSON.stringify(request),method: "POST",mode: "cors",credentials: "include",signal: fetchController.signal,});clearTimeout(timeoutId);// Handle rate limitingif (response.status === 429) {const retryAfter = response.headers.get("retry-after");const waitTime = retryAfter ? parseInt(retryAfter) * 1000 : 60000; // Default 1 minutethrow new Error(`Rate limited. Retry after ${waitTime}ms. Status: ${response.status}`);}if (!response.ok) {const responseText = await response.text();console.error(`DuckAI API error ${response.status}:`, responseText);throw new Error(`DuckAI API error: ${response.status} ${response.statusText} - ${responseText}`);}const text = await response.text();// Check for errorstry {const parsed = JSON.parse(text);if (parsed.action === "error") {throw new Error(`Duck.ai error: ${JSON.stringify(parsed)}`);}} catch (e) {// Not JSON, continue processing}// Extract the LLM response from the streamed responselet llmResponse = "";const lines = text.split("\n");for (const line of lines) {if (line.startsWith("data: ")) {try {const json = JSON.parse(line.slice(6));if (json.message) {llmResponse += json.message;}} catch (e) {// Skip invalid JSON lines}}}const finalResponse = llmResponse.trim();// If response is empty, provide a fallbackif (!finalResponse) {console.warn("Duck.ai returned empty response, using fallback");return "I apologize, but I'm unable to provide a response at the moment. Please try again.";}return finalResponse;} catch (error) {clearTimeout(timeoutId);if (error instanceof Error && error.name === "AbortError") {throw new Error("DuckAI API request timeout - took longer than 30 seconds");}throw error;}}async chatStream(request: DuckAIRequest): Promise<ReadableStream<string>> {// Wait if rate limiting is neededawait this.waitIfNeeded();const userAgent = new UserAgent().toString();const vqd = await this.getVQD(userAgent);// Update rate limit tracking BEFORE making the requestconst now = Date.now();this.rateLimitInfo.requestTimestamps.push(now);this.rateLimitInfo.lastRequestTime = now;this.saveRateLimitToStore();// Show compact rate limit status in server consolethis.rateLimitMonitor.printCompactStatus();const response = await fetch("https://duckduckgo.com/duckchat/v1/chat", {headers: {accept: "text/event-stream","accept-language": "en-US,en;q=0.9,fa;q=0.8","cache-control": "no-cache","content-type": "application/json",pragma: "no-cache",priority: "u=1, i","sec-fetch-dest": "empty","sec-fetch-mode": "cors","sec-fetch-site": "same-origin","x-fe-version": "serp_20250401_100419_ET-19d438eb199b2bf7c300","User-Agent": userAgent,"x-vqd-hash-1": vqd.hash,},referrer: "https://duckduckgo.com/",referrerPolicy: "origin",body: JSON.stringify(request),method: "POST",mode: "cors",credentials: "include",});// Handle rate limitingif (response.status === 429) {const retryAfter = response.headers.get("retry-after");const waitTime = retryAfter ? parseInt(retryAfter) * 1000 : 60000; // Default 1 minutethrow new Error(`Rate limited. Retry after ${waitTime}ms. Status: ${response.status}`);}if (!response.ok) {throw new Error(`DuckAI API error: ${response.status} ${response.statusText}`);}if (!response.body) {throw new Error("No response body");}return new ReadableStream({start(controller) {const reader = response.body!.getReader();const decoder = new TextDecoder();function pump(): Promise<void> {return reader.read().then(({ done, value }) => {if (done) {controller.close();return;}const chunk = decoder.decode(value, { stream: true });const lines = chunk.split("\n");for (const line of lines) {if (line.startsWith("data: ")) {try {const json = JSON.parse(line.slice(6));if (json.message) {controller.enqueue(json.message);}} catch (e) {// Skip invalid JSON}}}return pump();});}return pump();},});}getAvailableModels(): string[] {return ["gpt-4o-mini","gpt-5-mini","claude-3-5-haiku-latest","meta-llama/Llama-4-Scout-17B-16E-Instruct","mistralai/Mistral-Small-24B-Instruct-2501","openai/gpt-oss-120b"];}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import { gotScraping } from 'got-scraping';import { JSDOM } from "jsdom";import { createHash } from "node:crypto";export class DuckAI {private async solveChallenge(vqdHash: string, ua: string): Promise<string> {const jsScript = Buffer.from(vqdHash, 'base64').toString('utf-8');const dom = new JSDOM(`<!DOCTYPE html><html><body></body></html>`, { runScripts: 'dangerously' });dom.window.top.__DDG_BE_VERSION__ = 1;dom.window.top.__DDG_FE_CHAT_HASH__ = 1;const result = await dom.window.eval(jsScript) as any;result.client_hashes[0] = ua;result.client_hashes = result.client_hashes.map((t: string) => {const hash = createHash('sha256');hash.update(t);return hash.digest('base64');});return btoa(JSON.stringify(result));}async chat(request: any): Promise<string> {try {// gotScraping автоматически подберет идеальные заголовки и TLS отпечаток// под каждый запрос, имитируя случайный современный браузер.// 1. Получаем токенconst statusRes = await gotScraping.get("https://duckduckgo.com/duckchat/v1/status?q=1", {headers: { "x-vqd-accept": "1" }});const ua = statusRes.request.options.headers['user-agent'] as string;const hashHeader = statusRes.headers["x-vqd-hash-1"] as string;const solvedVqd = await this.solveChallenge(hashHeader, ua);// 2. Делаем запрос в чатconst chatRes = await gotScraping.post("https://duckduckgo.com/duckchat/v1/chat", {headers: {"x-vqd-hash-1": solvedVqd,"content-type": "application/json","accept": "text/event-stream"},json: request,retry: { limit: 2 } // Авто-повтор при сбоях});const text = chatRes.body;let llmResponse = "";const lines = text.split("\n");for (const line of lines) {if (line.startsWith("data: ")) {try {const json = JSON.parse(line.slice(6));if (json.message) llmResponse += json.message;} catch (e) {}}}return llmResponse.trim() || "⚠️ Пустой ответ от ИИ.";} catch (error) {console.error("Scraping Error:", error);return "⚠️ Ошибка маскировки. Попробуйте еще раз.";}}}
1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401 unmodified lineconst openAIService = new OpenAIService();process.on('uncaughtException', (error) => {console.error('Uncaught Exception:', error);process.exit(1);});process.on('unhandledRejection', (reason, promise) => {console.error('Unhandled Rejection at:', promise, 'reason:', reason);process.exit(1);});try {const server = Bun.serve({port: process.env.PORT || 7860,async fetch(req) {console.log(`Received request: ${req.method} ${req.url}`);const url = new URL(req.url);const corsHeaders = {"Access-Control-Allow-Origin": "*","Access-Control-Allow-Methods": "GET, POST, OPTIONS","Access-Control-Allow-Headers": "Content-Type, Authorization",};// Handle preflight requestsif (req.method === "OPTIONS") {return new Response(null, { headers: corsHeaders });}try {// Health check endpointif (url.pathname === "/health" && req.method === "GET") {return new Response(JSON.stringify({ status: "ok" }), {headers: { "Content-Type": "application/json", ...corsHeaders },});}// Models endpointif (url.pathname === "/v1/models" && req.method === "GET") {const models = openAIService.getModels();return new Response(JSON.stringify(models), {headers: { "Content-Type": "application/json", ...corsHeaders },});}// Chat completions endpointif (url.pathname === "/v1/chat/completions" && req.method === "POST") {const body = await req.json();const validatedRequest = openAIService.validateRequest(body);// Handle streamingif (validatedRequest.stream) {const stream =await openAIService.createChatCompletionStream(validatedRequest);return new Response(stream, {headers: {"Content-Type": "text/event-stream","Cache-Control": "no-cache",Connection: "keep-alive",...corsHeaders,},});}// Handle non-streamingconst completion =await openAIService.createChatCompletion(validatedRequest);return new Response(JSON.stringify(completion), {headers: { "Content-Type": "application/json", ...corsHeaders },});}// 404 for unknown endpointsreturn new Response(JSON.stringify({error: {message: "Not found",type: "invalid_request_error",},}),{status: 404,headers: { "Content-Type": "application/json", ...corsHeaders },});} catch (error) {console.error("Server error:", error);const errorMessage =error instanceof Error ? error.message : "Internal server error";const statusCode =errorMessage.includes("required") || errorMessage.includes("must")? 400: 500;return new Response(JSON.stringify({error: {message: errorMessage,type:statusCode === 400? "invalid_request_error": "internal_server_error",},}),{status: statusCode,headers: { "Content-Type": "application/json", ...corsHeaders },});}},});console.log(`🚀 OpenAI-compatible server running on http://localhost:${server.port}`);console.log(`📚 Available endpoints:`);console.log(` GET /health - Health check`);console.log(` GET /v1/models - List available models`);console.log(` POST /v1/chat/completions - Chat completions (streaming & non-streaming)`);console.log(`\n🔧 Example usage:`);console.log(`curl -X POST http://localhost:${server.port}/v1/chat/completions \\`);console.log(` -H "Content-Type: application/json" \\`);console.log(` -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Hello!"}]}'`);// Keep the process alive// setInterval(() => {}, 1000);} catch (error) {console.error("Failed to start server:", error);process.exit(1);}1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485861 unmodified lineconst openAIService = new OpenAIService();const log = (msg: string) => {const time = new Date().toISOString().split('T')[1].split('.')[0];console.log(`[${time}] ${msg}`);};const HTML_FRONTEND = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>AI Research Playground</title><style>body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #0b0e14; color: #e6edf3; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }.container { text-align: center; border: 1px solid #30363d; padding: 40px; border-radius: 12px; background: #161b22; max-width: 500px; }h1 { color: #58a6ff; margin-bottom: 10px; }p { color: #8b949e; line-height: 1.6; }.status { display: inline-block; padding: 4px 12px; border-radius: 20px; background: #238636; color: white; font-size: 14px; margin-top: 20px; }</style></head><body><div class="container"><h1>🔬 Research API</h1><p>This Space hosts a distributed language model inference engine for academic research and integration testing.</p><div class="status">System Online</div><p style="font-size: 12px; margin-top: 30px;">Authorized access only via encrypted endpoints.</p></div></body></html>`;try {const server = Bun.serve({port: process.env.PORT || 7860,async fetch(req) {const url = new URL(req.url);// Маскировочный фронтендif (url.pathname === "/") {return new Response(HTML_FRONTEND, { headers: { "Content-Type": "text/html" } });}const authHeader = req.headers.get("Authorization");const API_KEY = process.env.API_KEY || "MySecretKey_12345";if (authHeader !== `Bearer ${API_KEY}` && req.method !== "OPTIONS") {return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 });}const corsHeaders = {"Access-Control-Allow-Origin": "*","Access-Control-Allow-Methods": "GET, POST, OPTIONS","Access-Control-Allow-Headers": "Content-Type, Authorization",};if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });try {if (url.pathname === "/health") {return new Response(JSON.stringify({ status: "online", model: "distributed-v1" }), { headers: { "Content-Type": "application/json", ...corsHeaders } });}if (url.pathname === "/v1/chat/completions" && req.method === "POST") {const body = await req.json();const lastMsg = body.messages?.[body.messages.length - 1]?.content || "";log(`REQ: ${lastMsg.substring(0, 50)}...`);const completion = await openAIService.createChatCompletion(body);return new Response(JSON.stringify(completion), { headers: { "Content-Type": "application/json", ...corsHeaders } });}return new Response(null, { status: 404 });} catch (error) {log(`ERR: ${error.message}`);return new Response(JSON.stringify({ error: error.message }), { status: 500, headers: corsHeaders });}},});log(`API Gateway started on port ${server.port}`);} catch (error) {process.exit(1);}
package.json+4-23
server.ts+9-1
src/duckai.ts+32-476
src/server.ts+56-110