# Cloudflare Workers: selective routing via a Node backend

요약: Workers의 직접 터널 연결은 준비 중입니다. IP 허용 목록이 필요한 호출만 인증된 Node 백엔드로 옮기세요.
대상이나 백엔드가 불분명하면 수정 전에 사용자와 상의하고, 나머지 Workers 트래픽은 그대로 두세요.

## 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. For this platform's workaround, that TLS connection runs from the Node backend to the destination; allowip does not decrypt it 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 allowip, using an authenticated Node backend while leaving unrelated Worker traffic unchanged.

Typical signs include `GW.IP_NOT_ALLOWED`, `no_authorization_ip`, “IP not allowed”, 401/403 errors mentioning the IP, SDK documentation/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 operation and any token calls that also require IP registration. If there is no suitable backend, agree on one with the user before introducing infrastructure. Do not invent destination endpoints or authentication.

## 3. Constraints (must)

- Do not proxy unrelated analytics, your own database, other APIs, or build/install traffic.
- Keep TLS verification on for every hop; no plaintext-proxy downgrade.
- Never log or hardcode the tunnel URL or credentials. Read private env/platform secrets; keep proxy and destination secrets on the backend for this workaround.
- Return sanitized failures; never silently fall back to a direct Worker-to-destination request.
- Direct production Workers CONNECT support is **pending**. Use a supported Node backend, not Vercel Edge or experimental userland TLS, and respect runtime limits.

## 4. Recommended approach for this platform

Adapt this backend reference to the existing application and file layout. The repository verified Node's CONNECT transport, not direct production Workers support. Local workerd succeeded with a plaintext local proxy, but production SNI behavior is affected by [workerd #6903](https://github.com/cloudflare/workerd/issues/6903) (open when checked on 2026-11-24). Native `connect(secureTransport: "on")` followed by `startTls()` cannot provide the required TLS-in-TLS. Do not use the diagnostic plaintext experiment in production; see `examples/PLATFORM_MATRIX.md`.

On the backend, use the verified `ProxyAgent` implementation in [Node](node.md#4-recommended-approach-for-this-platform) or [Vercel](vercel.md#4-recommended-approach-for-this-platform). Move only the selected target operation and its existing signing/authentication there. Wrap its qualifying calls with `targetFetch`, preserving method, body, headers, token renewal, and decoding. If you want a guard, pass an allowlist of identified hosts; `TARGET_API_HOST` is **not required**.

Expose a fixed, authenticated and authorized backend operation, not a generic proxy. Validate permitted parameters and rate-limit requests. Use existing service authentication or a separate random `ALLOWIP_BACKEND_TOKEN`, with timing-safe comparison if implementing shared-secret authentication. Never accept an arbitrary destination URL, method, or authorization header. Preserve user-level authorization and return only the data the application already needs; sanitize non-2xx failures.

For example, a Worker-side `src/allowip-backend.js` can call that fixed operation. This is ordinary backend HTTPS, **not** the CONNECT transport:

```js
export async function callAllowipBackend(env, payload) {
  let url;
  try {
    url = new URL(env.ALLOWIP_BACKEND_URL);
    if (url.protocol !== "https:" || url.username || url.password) {
      throw new Error("Invalid backend URL");
    }
    if (!env.ALLOWIP_BACKEND_TOKEN) throw new Error("Missing backend token");
  } catch {
    throw new Error("Invalid private backend configuration");
  }
  let response;
  try {
    response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${env.ALLOWIP_BACKEND_TOKEN}`,
      },
      body: JSON.stringify(payload),
      redirect: "error",
      signal: AbortSignal.timeout(20_000),
    });
  } catch {
    throw new Error("Backend connection failed; direct fallback is disabled");
  }
  if (!response.ok) {
    await response.body?.cancel();
    throw new Error(`Backend operation failed with HTTP ${response.status}`);
  }
  return response.json();
}
```

Replace only the selected Worker operation with `callAllowipBackend(env, existingValidatedParameters)`. Keep existing Worker user authorization; a service token does not replace it. Catch failures at the Worker boundary and return sanitized non-2xx responses.

Set the issued `ALLOWIP_TUNNEL_URL` and destination secrets in the **backend** environment. On Vercel: **Project > Settings > Environment Variables**, select the intended environments and redeploy; use Node runtime routes. On another Node host, use its private environment/secret settings as described in the Node guide. Set the separate backend token there too if used.

In Workers, set the fixed non-secret `ALLOWIP_BACKEND_URL` under Wrangler `[vars]`, and use `npx wrangler secret put ALLOWIP_BACKEND_TOKEN` to enter the separate token privately. Local development can use an ignored `.dev.vars`. Do not place the tunnel URL or destination keys in Workers. Deploy through the existing workflow; never ask for secret values in chat.

## 5. Verify

On the backend, use the Node/Vercel helper's `transport.verify(dashboardIP)` to call `https://api.ipify.org` **through the tunnel** and compare exactly with the IPv4 shown in the allowip dashboard. Stop on mismatch. Checking ipify directly from Workers measures the wrong egress.

Then make one existing authenticated **read-only** call to each selected target through the backend's `targetFetch`, checking status and consuming responses. Close transports appropriately. Invoke the fixed read-only operation from the deployed Worker too. No orders, messages, or writes. Confirm missing backend authentication is rejected and proxy failure never triggers a direct call. Remove temporary diagnostics; report only sanitized results.

Tunnel CONNECT codes on the backend: **407** authentication failed; **403** destination/port not allowed; **402** account expired/inactive; **502** upstream connection failed. The backend may map these to a generic gateway error: a Worker-facing 502 alone does not identify the tunnel code. Distinguish backend authentication and destination HTTP errors; never forward raw transport exceptions.

## 6. Report back to the user

Explain which calls you moved/routed and why, which you left alone, the backend/runtime chosen, what verification ran, and any remaining uncertainty. List user actions such as provisioning the agreed backend, setting secrets, or registering the **allowip dashboard IPv4**, not a Cloudflare/Vercel 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.
