# Node.js: selectively route IP-allowlisted API calls

요약: 코드에서 IP 허용 목록이 필요한 API 호출을 찾아 그 호출만 allowip로 보내세요.
대상이 불분명하면 수정 전에 사용자에게 물어보고, 나머지 트래픽은 그대로 두세요.

## 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 the destination request or receive its API credentials.

## 2. Your task, agent

Inspect this codebase and decide which outbound HTTP calls go to services requiring an IP allowlist. Route **only those calls** through the tunnel, adapting to the existing client and architecture rather than replacing all networking.

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

If it is unclear which calls need this, ask the user **before changing anything**. Follow the qualifying operation's actual transport, including any token calls that also require IP registration; do not guess endpoints or signing algorithms.

## 3. Constraints (must)

- Do not proxy unrelated analytics, your own database, other APIs, or build/install traffic; no global dispatcher or process-wide proxy setting.
- Keep TLS verification on for both proxy and destination.
- Never log or hardcode the tunnel URL or credentials. Read them from private environment variables or platform secrets; keep them out of Git and error/APM output.
- Fail with a sanitized error; never silently fall back to a direct connection.
- Use a supported Node runtime, not Edge; respect the host's connection and execution limits.

## 4. Recommended approach for this platform

The following is a reference, not a required file layout. Adapt it to the project's HTTP client/framework. Its credential extraction and undici `ProxyAgent` come from the verified `examples/node-generic/index.mjs` and `examples/verify/verify.mjs`. With a supported Node version (for example Node 22.21.1 or newer compatible with undici 7), add `undici@7` as a production dependency.

For example, a server-only `lib/allowip.mjs` can expose a transport used only by the selected client:

```js
import { fetch, ProxyAgent } from "undici";

export function createAllowip(allowedHosts = []) {
  let dispatcher;
  try {
    const proxy = new URL(process.env.ALLOWIP_TUNNEL_URL);
    if (proxy.protocol !== "https:" || !proxy.username || !proxy.password) {
      throw new Error("Invalid proxy");
    }
    const token = Buffer.from(
      `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`,
    ).toString("base64");
    proxy.username = "";
    proxy.password = "";
    dispatcher = new ProxyAgent({ uri: proxy.href, token: `Basic ${token}` });
  } catch {
    throw new Error("Invalid ALLOWIP_TUNNEL_URL configuration");
  }

  async function throughTunnel(url, options = {}) {
    try {
      return await fetch(url, {
        ...options, dispatcher, 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;
    },
    async close() {
      try { await dispatcher.close(); } catch { throw new Error("Proxy cleanup failed"); }
    },
  };
}
```

Use `transport.targetFetch(existingUrl, existingOptions)` only at the identified call sites, or through the SDK's documented transport hook. Preserve authentication, signing, method, body, headers, token renewal, and response handling. An SDK does not automatically honor an undici dispatcher. Consume/cancel responses before closing; reuse a transport for a long-running server and close on shutdown. On Lambda, reuse outside the handler rather than closing after each invocation.

If you want a guard, pass an allowlist of hosts to `createAllowip([...])` based on your findings. `TARGET_API_HOST` is **not required**. Keep URLs controlled by application logic; do not create an arbitrary-URL relay.

Set server-only `ALLOWIP_TUNNEL_URL` to the issued HTTPS URL, without printing it:

| Host | Where to set the secret |
| --- | --- |
| Railway | Project > service > Variables; deploy changes. |
| Render | Service > Environment; save and redeploy. |
| Fly.io | `fly secrets import`, supplying private `NAME=value` input from a secret manager or ignored file. |
| Lambda | Function > Configuration > Environment variables; save and deploy. |
| Own server/local | Service manager's private environment file, or an ignored `.env.local` with Node's `--env-file`; restart the service. |

Keep the destination's existing secrets private too. Obtain missing secrets through platform settings, not chat.

## 5. Verify

In the actual server runtime, call `transport.verify(dashboardIP)` with the IPv4 shown in the allowip dashboard (optionally read that non-secret value from `ALLOWIP_EGRESS_IP`). This calls `https://api.ipify.org` **through the tunnel** and requires an exact match. Stop on mismatch; verify deployed egress too, not just local egress.

Then make one existing authenticated **read-only** call to each selected target using `targetFetch`, check its status, and consume the response. Do not place orders, send messages, or write records. Report only sanitized status; remove temporary diagnostics.

Tunnel CONNECT codes: **407** authentication failed; **403** destination/port not allowed; **402** account expired/inactive; **502** upstream connection failed. Undici may wrap these in a transport exception rather than a Response. Classify safely (see `examples/verify/verify.mjs`); never dump raw errors. A destination HTTP 403 is distinct from a tunnel 403.

## 6. Report back to the user

Explain which calls you routed and the evidence for each, which traffic you left alone, what verification ran, and anything still unverified. List remaining user actions, especially registering the **allowip dashboard IPv4**, not a hosting IP or proxy hostname, in the target console.

Where relevant, point to the matching 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). Registration requirements are provider/API-specific; 공공데이터포털 has no universal IP-registration field.
