youraitools-api / tree / functions/proxy.js ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
// Transparent reverse proxy: method, query, body, status (incl. 402) and every header (PAYMENT-REQUIRED,
// X-PAYMENT, PAYMENT-SIGNATURE, PAYMENT-RESPONSE, X-PAYMENT-RESPONSE, ...) pass through untouched; bodies stream.
import { TOOLS, SERVICES, ROUTES } from './tools.js';

const HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'upgrade', 'te', 'trailer', 'host'];

export function upstreamRequest(request, tool, rest, env) {
  const url = new URL(request.url);
  const target = `${tool.origin}${rest}${url.search}`;
  const headers = new Headers(request.headers);
  for (const h of HOP) headers.delete(h);
  headers.set('x-forwarded-host', env.PUBLIC_HOST || 'api.youraitools.co');
  headers.set('x-forwarded-prefix', `/${tool.prefix}`);
  headers.set('x-forwarded-proto', 'https');
  const ip = request.headers.get('cf-connecting-ip');
  if (ip) headers.set('x-forwarded-for', ip);
  const hasBody = !['GET', 'HEAD'].includes(request.method);
  return new Request(target, { method: request.method, headers, body: hasBody ? request.body : undefined, redirect: 'manual', ...(hasBody ? { duplex: 'half' } : {}) });
}

export async function forward(request, tool, rest, env) {
  const up = upstreamRequest(request, tool, rest, env);
  const svc = env[tool.binding];
  const res = svc && typeof svc.fetch === 'function' ? await svc.fetch(up) : await fetch(up);
  const loc = res.headers.get('location');
  if (loc && loc.startsWith(tool.origin)) {
    const headers = new Headers(res.headers);
    headers.set('location', `https://${env.PUBLIC_HOST || 'api.youraitools.co'}/${tool.prefix}${loc.slice(tool.origin.length)}`);
    return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
  }
  return res;
}

/** Splits /<prefix>/<rest> -> { tool, rest } or null. */
export function route(pathname) {
  const m = pathname.match(/^\/([a-z0-9-]+)(\/.*)?$/);
  if (!m || !ROUTES[m[1]]) return null;
  return { tool: ROUTES[m[1]], rest: m[2] || '/' };
}

/** GET a JSON doc from every tool through the proxy (so URLs come out as api.youraitools.co/<prefix>). */
export async function gatherJson(env, path, ms = 5000, { services = false } = {}) {
  return Promise.all((services ? [...TOOLS, ...SERVICES] : TOOLS).map(async (t) => {
    try {
      const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), ms);
      const r = await forward(new Request(`https://${env.PUBLIC_HOST || 'api.youraitools.co'}/${t.prefix}${path}`, { headers: { accept: 'application/json' }, signal: ctrl.signal }), t, path, env);
      clearTimeout(timer);
      return r.ok ? { tool: t, doc: await r.json() } : { tool: t, error: `HTTP ${r.status}` };
    } catch (e) { return { tool: t, error: String(e.message || e) }; }
  }));
}

agentgate-source: code mirror on Cloudflare Pages. All repos