# Supabase / Lovable: selectively route IP-allowlisted API calls

요약: IP 허용 목록이 필요한 API 호출만 Supabase 서버 함수에서 allowip로 보내세요.
Lovable 프런트엔드나 Supabase DB 통신은 바꾸지 말고, 대상이 불분명하면 먼저 물어보세요.

## 1. What allowip is

allowip gives the project a fixed outbound IPv4 through an HTTPS CONNECT tunnel configured by the `ALLOWIP_TUNNEL_URL` environment variable. TLS to the destination stays end to end; allowip does not decrypt destination requests or receive destination API credentials.

## 2. Your task, agent

Inspect the codebase and decide which outbound HTTP calls go to services requiring an IP allowlist. Route **only those calls** through the tunnel. For Lovable, work in the connected Supabase project's server functions, preserving the frontend's authenticated function invocation.

Typical signs: `GW.IP_NOT_ALLOWED`, `no_authorization_ip`, “IP not allowed”, 401/403 errors that mention the IP, SDK docs/settings about IP registration, or the user naming a service. Known examples include Naver Commerce, Coupang WING, Upbit, Bithumb, Kiwoom, Aligo, and 공공데이터포털. This is not exhaustive; requirements vary by API/key.

If it is unclear which calls qualify, ask the user **before changing anything**. Trace the actual HTTP client, including any token calls that also require IP registration; do not invent endpoints or authentication.

## 3. Constraints (must)

- Do not proxy unrelated analytics, your own database, Supabase auth, other APIs, or build/install traffic.
- Keep TLS certificate/hostname verification on for proxy and destination.
- Never log or hardcode the tunnel URL or credentials; use private environment/platform secrets, never frontend variables or tables.
- Fail with a sanitized non-2xx error; never silently fall back to direct fetch.
- Respect the Deno Edge Function runtime: use its explicit HTTP client, not Node's undici. If unavailable, discuss a Node backend rather than bypassing the tunnel.

## 4. Recommended approach for this platform

Adapt this reference to existing functions, SDK hooks, and file layout. The Deno proxy/basicAuth and fetch client pattern comes from `examples/supabase-edge/supabase/functions/naver-token/index.ts`. It was verified with full traffic in Deno and Docker Edge Runtime 1.79.4. A hosted Supabase 1.79.1 probe confirmed API/options availability, **not** a completed public HTTPS tunnel; deployed verification remains necessary.

For example, `supabase/functions/_shared/allowip.js`:

```js
export function createAllowip(allowedHosts = []) {
  if (typeof Deno.createHttpClient !== "function") {
    throw new Error("Proxy client unavailable; use a supported backend");
  }
  let client;
  try {
    const proxy = new URL(Deno.env.get("ALLOWIP_TUNNEL_URL"));
    if (proxy.protocol !== "https:" || !proxy.username || !proxy.password) {
      throw new Error("Invalid proxy");
    }
    const basicAuth = {
      username: decodeURIComponent(proxy.username),
      password: decodeURIComponent(proxy.password),
    };
    proxy.username = "";
    proxy.password = "";
    client = Deno.createHttpClient({ proxy: { url: proxy.href, basicAuth } });
  } catch {
    throw new Error("Proxy client configuration failed");
  }

  async function throughTunnel(url, options = {}) {
    try {
      return await fetch(url, {
        ...options, client, redirect: "error",
        signal: options.signal ?? AbortSignal.timeout(15_000),
      });
    } catch {
      throw new Error("allowip transport failed; direct fallback is disabled");
    }
  }

  return {
    async targetFetch(input, options = {}) {
      let url;
      try { url = new URL(input); } catch { throw new Error("Invalid target URL"); }
      if (url.protocol !== "https:" || url.username || url.password ||
          (url.port && url.port !== "443") ||
          (allowedHosts.length && !allowedHosts.includes(url.hostname))) {
        throw new Error("Target URL is not permitted");
      }
      return throughTunnel(url, options);
    },
    async verify(dashboardIP) {
      const response = await throughTunnel("https://api.ipify.org?format=json");
      if (!response.ok) {
        await response.body?.cancel();
        throw new Error("IP verification service failed");
      }
      const { ip } = await response.json();
      if (!dashboardIP || ip !== dashboardIP) throw new Error("Egress IPv4 mismatch");
      return ip;
    },
    close() { client.close(); },
  };
}
```

Import it into the existing function and use `transport.targetFetch(existingUrl, existingOptions)` only for qualifying calls. Preserve method, body, signing, headers, token renewal, and decoding. An SDK must explicitly accept this custom fetch; otherwise adapt its actual transport. Consume/cancel responses before `transport.close()` in `finally`. Preserve JWT/session checks and return sanitized errors at the function boundary.

If you want a guard, pass an allowlist of hosts to `createAllowip([...])`; `TARGET_API_HOST` is **not required**. Do not expose an arbitrary-URL relay.

Set **Supabase Dashboard > project > Edge Functions > Secrets > `ALLOWIP_TUNNEL_URL`** to the issued HTTPS URL, alongside the existing destination secrets. In Lovable, use the connected Supabase project, not frontend configuration. Redeploy the affected function with the project's existing auth configuration intact. Alternatively use `supabase secrets set --env-file .env.allowip --project-ref YOUR_PROJECT_REF` with an ignored, permission-restricted file; never put secret values in CLI arguments or chat. Local serving can use the same private env file. `ALLOWIP_EGRESS_IP` is optional storage for the non-secret dashboard IPv4.

## 5. Verify

In an existing authenticated server function, call `transport.verify(dashboardIP)` to request `https://api.ipify.org` **through the tunnel** and compare with the IPv4 shown in the allowip dashboard. Stop on mismatch. Run locally and deployed: client API availability alone does not prove a working hosted tunnel.

Then make one existing authenticated **read-only** call to each selected target with `targetFetch` and check its status. No orders, messages, or writes. Consume responses, close the client, remove temporary diagnostics, and report only sanitized status. If the client is blocked, stop and discuss [Node](node.md) or [Vercel](vercel.md); do not omit `client` and retry.

Tunnel CONNECT codes: **407** authentication failed; **403** destination/port not allowed; **402** account expired/inactive; **502** upstream connection failed. Deno may surface these as transport exceptions; never dump raw exceptions. Destination HTTP errors are separate.

## 6. Report back to the user

Explain which calls you routed and why, which you left alone, what verification ran, and any remaining uncertainty. List user actions such as registering the **allowip dashboard IPv4**, not a Supabase hosting IP or proxy hostname, in the target console.

Point to the relevant solution: [Naver Commerce](https://allowip.com/solutions/naver-commerce), [Coupang WING](https://allowip.com/solutions/coupang), [Upbit/Bithumb](https://allowip.com/solutions/upbit-bithumb), [Kiwoom](https://allowip.com/solutions/kiwoom), [Aligo](https://allowip.com/solutions/aligo), or [공공데이터포털](https://allowip.com/solutions/public-data). The last has provider-specific restrictions, not a universal registration field.
