---
name: nc-ip
description: Detect Northern Cyprus (KKTC, TRNC) IP addresses with the NC-IP registry API at nc-ip.celya.tech. Use when integrating Northern Cyprus IP detection into an app or API, geo-blocking or allow-listing Northern Cyprus traffic, fixing geo-IP lookups that show Northern Cyprus users as Turkey (TR) or Cyprus (CY), or syncing Northern Cyprus IP blocks into firewalls, nginx, HAProxy, WAFs or CDNs such as Cloudflare.
---

# NC-IP: Northern Cyprus IP detection

NC-IP is a registry of the IP blocks used by networks in Northern Cyprus, reviewed and approved by hand.
RIPE registers these blocks under Turkey (TR) or Cyprus (CY), so MaxMind, IP2Location and similar geo-IP databases place Northern Cyprus users in the wrong country.
The API answers "is this address in Northern Cyprus, and which network holds it?" and serves the full block list for local matching.

Base URL: `https://nc-ip.celya.tech/api/v1`. OpenAPI 3.1: `https://nc-ip.celya.tech/api/v1/openapi.json` (no key needed). Human docs: `https://nc-ip.celya.tech/docs`.

## Get an API key

Keys are issued by hand. Ask the user to request one through the contact form at https://nc-ip.celya.tech/?topic=api#contact (organisation, use case, expected requests per month). Never invent or guess a key. A key is `ncip_` followed by 40 hex characters; this document shortens it to `ncip_…`.

Store it server-side only, in the `NCIP_API_KEY` environment variable (or the project's secret manager). Never ship it to browsers, mobile apps or public repositories, and never call the API from client-side code: detect on the server and pass the result down.

## Authentication

Send the key on every request except `/openapi.json` and `/health`, in one of:

- `x-api-key: ncip_…` (preferred)
- `Authorization: Bearer ncip_…` (for tools and MCP clients that only support bearer tokens)
- `?key=ncip_…` (last resort: URLs end up in logs)

Missing, invalid or revoked key: `401` with `WWW-Authenticate: Bearer realm="nc-ip"`. Do not retry a 401.

## Quotas and headers

- Keys may have a monthly quota (for example 500 requests), counted in Northern Cyprus time (Asia/Famagusta) and reset at 00:00 on the 1st.
- Burst limit: at most 20 requests per 10 seconds per key.
- Every keyed request counts, including `400` and `304 Not Modified`. Refused requests (`401`, `429`) do not.
- Metered responses carry `X-RateLimit-Limit`, `X-RateLimit-Remaining` (both omitted for unlimited keys) and `X-RateLimit-Reset` (Unix seconds).
- `429` means quota or burst limit reached: wait `Retry-After` seconds. Retry `5xx` with backoff. Never retry `400`/`401` unchanged.

## Endpoints

| Request | Returns |
| --- | --- |
| `GET /lookup?ip=203.0.113.42` | `{ ip, northCyprus, prefix, networks[], alsoWithin[] }`; `northCyprus: false` and `prefix: null` when nothing matches (still `200`) |
| `GET /prefixes` | `{ count, prefixes: [{ prefix, family, networks: [{ id, name, type }] }] }` |
| `GET /prefixes.txt` | One CIDR per line, IPv4 then IPv6, nothing else |
| `GET /prefixes.json` | `{ generatedAt, count, prefixes }` |
| `POST /mcp` | MCP server for AI agents (see below) |

Filters on the prefix endpoints: `family=4|6`, `type=isp,mobile,hosting,university,bank,government,other` (comma list), `network=<id>`. `/prefixes` also takes `format=txt`. All prefix responses send a weak `ETag`; send it back in `If-None-Match` to get an empty `304` when nothing changed.

## Choose an approach

1. **Bulk (default for firewalls, WAFs, CDNs, middleware, log analysis):** download `prefixes.txt` once a day with `If-None-Match`, keep it on disk, match locally. About 30 requests a month, no per-visitor latency, keeps working if the API is unreachable.
2. **Per request (low traffic, no place to keep a file):** call `/lookup` from the server and cache each answer (a day is fine: blocks change rarely). Decide fail-open or fail-closed explicitly.
3. Never call the API from the browser, and never call `/lookup` once per page view without a cache.

Behind a proxy, load balancer or CDN, match the real client address (`X-Forwarded-For` via `set_real_ip_from` in nginx, `trust proxy` in Express, `CF-Connecting-IP` on Cloudflare), not the proxy's. Normalize IPv4-mapped IPv6 (`::ffff:203.0.113.42`) to IPv4 before matching.

## Recipes

Examples use documentation addresses (`192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24`, `2001:db8::/32`). Real prefixes come only from the API; never hard-code them.

### Sync script with ETag (cron)

```sh
#!/bin/sh
# /usr/local/bin/ncip-sync.sh: fetch the list only when it changed.
set -eu
URL="https://nc-ip.celya.tech/api/v1/prefixes.txt"
DIR=/var/lib/ncip
mkdir -p "$DIR"

set -- -H "x-api-key: $NCIP_API_KEY"
[ -s "$DIR/etag" ] && set -- "$@" -H "If-None-Match: $(cat "$DIR/etag")"

STATUS=$(curl -sS -o "$DIR/new.txt" -D "$DIR/headers" -w '%{http_code}' "$@" "$URL")
case "$STATUS" in
  200)
    # Refuse an empty list rather than wiping the rules.
    [ -s "$DIR/new.txt" ] || { echo "ncip: empty list" >&2; exit 1; }
    mv "$DIR/new.txt" "$DIR/prefixes.txt"
    grep -i '^etag:' "$DIR/headers" | cut -d' ' -f2- | tr -d '\r' > "$DIR/etag"
    sed 's/.*/& 1;/' "$DIR/prefixes.txt" > /etc/nginx/ncip-geo.conf
    nginx -t && nginx -s reload      # or: systemctl reload haproxy
    ;;
  304) rm -f "$DIR/new.txt" ;;       # unchanged
  *) echo "ncip sync failed: HTTP $STATUS" >&2; exit 1 ;;
esac
```

```sh
# crontab: every night at 03:15
NCIP_API_KEY=ncip_…
15 3 * * * /usr/local/bin/ncip-sync.sh >> /var/log/ncip-sync.log 2>&1
```

### nginx: geo + map

```nginx
# http {} context. ncip-geo.conf is written by the sync script: "203.0.113.0/24 1;"
geo $ncip {
    default 0;
    include /etc/nginx/ncip-geo.conf;
}

# Derived values: a label for the app, a flag for blocking.
map $ncip $ncip_region {
    1       "north-cyprus";
    default "other";
}

server {
    # Behind a proxy or CDN, first: set_real_ip_from <proxy range>; real_ip_header X-Forwarded-For;
    location / {
        proxy_set_header X-North-Cyprus $ncip;          # tell the app
        proxy_pass http://app;
    }
    location /kktc-only/ {
        if ($ncip = 0) { return 403; }                  # allow-list Northern Cyprus
        proxy_pass http://app;
    }
}
```

To block Northern Cyprus instead, use `if ($ncip) { return 403; }`. `geo` handles IPv4 and IPv6 in the same file.

### HAProxy: ACL from file

```haproxy
frontend web
    bind :443 ssl crt /etc/haproxy/site.pem
    # prefixes.txt is read as it is: one CIDR per line, IPv4 and IPv6
    acl from_nc src -f /var/lib/ncip/prefixes.txt
    http-request set-header X-North-Cyprus 1 if from_nc
    # Allow-list only:  http-request deny unless from_nc
    # Block-list:       http-request deny if from_nc
```

Reload HAProxy after each sync that returned `200` (the file is read at start-up).

### Cloudflare: IP list sync

Create an account-level IP list (for example `ncip`) once, then replace its items after each changed download, and reference it in a WAF custom rule as `ip.src in $ncip`.

```sh
#!/bin/sh
# Needs an API token with Account Filter Lists: Edit.
set -eu
curl -fsS "https://nc-ip.celya.tech/api/v1/prefixes.txt" -H "x-api-key: $NCIP_API_KEY" \
  | jq -Rn '[inputs | select(length > 0) | { ip: ., comment: "nc-ip" }]' > /tmp/ncip-items.json
[ "$(jq length /tmp/ncip-items.json)" -gt 0 ] || { echo "ncip: empty list" >&2; exit 1; }

# PUT replaces every item of the list in one asynchronous operation.
curl -fsS -X PUT \
  "https://api.cloudflare.com/client/v4/accounts/$CF_ACCOUNT_ID/rules/lists/$CF_LIST_ID/items" \
  -H "Authorization: Bearer $CF_API_TOKEN" -H "Content-Type: application/json" \
  --data @/tmp/ncip-items.json
```

Combine with the ETag logic of the sync script to skip unchanged days. Example rule: `(http.request.uri.path eq "/apply" and not ip.src in $ncip)` with action Managed Challenge.

### Node.js / TypeScript middleware

Built-in `net.BlockList` does the CIDR matching; the list is refreshed daily with `If-None-Match` and swapped atomically.

```ts
import { BlockList, isIP } from "node:net";
import type { NextFunction, Request, Response } from "express";

const URL = "https://nc-ip.celya.tech/api/v1/prefixes.txt";
let blocks = new BlockList();
let etag: string | undefined;

export function buildBlockList(text: string): BlockList {
  const list = new BlockList();
  for (const line of text.split("\n")) {
    const cidr = line.trim();
    if (!cidr) continue;
    const [addr, bits] = cidr.split("/");
    const v6 = isIP(addr) === 6;
    list.addSubnet(addr, bits ? Number(bits) : v6 ? 128 : 32, v6 ? "ipv6" : "ipv4");
  }
  return list;
}

export async function refreshNcip(): Promise<void> {
  const headers: Record<string, string> = { "x-api-key": process.env.NCIP_API_KEY ?? "" };
  if (etag) headers["If-None-Match"] = etag;
  const res = await fetch(URL, { headers });
  if (res.status === 304) return;
  if (!res.ok) throw new Error(`NC-IP sync failed: HTTP ${res.status}`);
  blocks = buildBlockList(await res.text());
  etag = res.headers.get("etag") ?? undefined;
}

export function isNorthCyprus(ip: string, list: BlockList = blocks): boolean {
  const addr = ip.startsWith("::ffff:") && ip.includes(".") ? ip.slice(7) : ip;
  const v = isIP(addr);
  return v !== 0 && list.check(addr, v === 6 ? "ipv6" : "ipv4");
}

// app.set("trust proxy", <your proxies>) so req.ip is the client address.
export function ncipMiddleware(req: Request, res: Response, next: NextFunction) {
  res.locals.northCyprus = isNorthCyprus(req.ip ?? "");
  next();
}

await refreshNcip(); // at start-up; keep serving the old list if a later refresh fails
setInterval(() => refreshNcip().catch((err) => console.error(err)), 24 * 60 * 60 * 1000).unref();
```

### Python

Standard library only; plug `is_north_cyprus` into Django/Flask/FastAPI middleware.

```python
import ipaddress
import os
import threading
import urllib.error
import urllib.request

URL = "https://nc-ip.celya.tech/api/v1/prefixes.txt"

class NcipBlocks:
    def __init__(self):
        self.networks = []
        self.etag = None
        self.lock = threading.Lock()

    def load(self, text):
        nets = [ipaddress.ip_network(l.strip(), strict=False) for l in text.splitlines() if l.strip()]
        with self.lock:
            self.networks = nets

    def refresh(self):
        req = urllib.request.Request(URL, headers={"x-api-key": os.environ["NCIP_API_KEY"]})
        if self.etag:
            req.add_header("If-None-Match", self.etag)
        try:
            with urllib.request.urlopen(req, timeout=30) as res:
                self.load(res.read().decode())
                self.etag = res.headers.get("ETag")
        except urllib.error.HTTPError as e:
            if e.code != 304:  # 304: unchanged
                raise

    def contains(self, ip):
        try:
            addr = ipaddress.ip_address(ip)
        except ValueError:
            return False
        if addr.version == 6 and addr.ipv4_mapped:
            addr = addr.ipv4_mapped
        with self.lock:
            nets = self.networks
        return any(addr in n for n in nets if n.version == addr.version)

BLOCKS = NcipBlocks()

def refresh_daily():
    try:
        BLOCKS.refresh()
    except Exception as e:  # keep the previous list
        print("ncip refresh failed:", e)
    t = threading.Timer(24 * 3600, refresh_daily)
    t.daemon = True
    t.start()

refresh_daily()

def is_north_cyprus(ip):
    return BLOCKS.contains(ip)
```

### Go (net/netip)

```go
package ncip

import (
	"bufio"
	"context"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/netip"
	"os"
	"strings"
	"sync/atomic"
	"time"
)

const listURL = "https://nc-ip.celya.tech/api/v1/prefixes.txt"

type Blocks struct {
	prefixes atomic.Pointer[[]netip.Prefix]
	etag     string
}

func Parse(text string) ([]netip.Prefix, error) {
	var out []netip.Prefix
	sc := bufio.NewScanner(strings.NewReader(text))
	for sc.Scan() {
		line := strings.TrimSpace(sc.Text())
		if line == "" {
			continue
		}
		p, err := netip.ParsePrefix(line)
		if err != nil {
			a, aerr := netip.ParseAddr(line) // a bare address is a host route
			if aerr != nil {
				return nil, err
			}
			p = netip.PrefixFrom(a, a.BitLen())
		}
		out = append(out, p.Masked())
	}
	return out, sc.Err()
}

func (b *Blocks) Set(p []netip.Prefix) { b.prefixes.Store(&p) }

func (b *Blocks) Refresh(ctx context.Context) error {
	req, _ := http.NewRequestWithContext(ctx, "GET", listURL, nil)
	req.Header.Set("x-api-key", os.Getenv("NCIP_API_KEY"))
	if b.etag != "" {
		req.Header.Set("If-None-Match", b.etag)
	}
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	switch res.StatusCode {
	case http.StatusNotModified:
		return nil
	case http.StatusOK:
	default:
		return fmt.Errorf("ncip: HTTP %d", res.StatusCode)
	}
	body, err := io.ReadAll(io.LimitReader(res.Body, 10<<20))
	if err != nil {
		return err
	}
	p, err := Parse(string(body))
	if err != nil {
		return err
	}
	b.Set(p)
	b.etag = res.Header.Get("ETag")
	return nil
}

// Run refreshes once a day until ctx ends (call Refresh once at start-up first).
func (b *Blocks) Run(ctx context.Context) {
	t := time.NewTicker(24 * time.Hour)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			_ = b.Refresh(ctx) // on error, keep the previous list
		}
	}
}

func (b *Blocks) Contains(ip string) bool {
	addr, err := netip.ParseAddr(ip)
	if err != nil {
		return false
	}
	addr = addr.Unmap()
	if list := b.prefixes.Load(); list != nil {
		for _, p := range *list {
			if p.Contains(addr) {
				return true
			}
		}
	}
	return false
}

// Middleware sets X-North-Cyprus for handlers. Use the real client address
// if you run behind a proxy (r.RemoteAddr is the proxy then).
func (b *Blocks) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		host, _, _ := net.SplitHostPort(r.RemoteAddr)
		r.Header.Del("X-North-Cyprus")
		if b.Contains(host) {
			r.Header.Set("X-North-Cyprus", "1")
		}
		next.ServeHTTP(w, r)
	})
}
```

### Per-request lookup with cache

```ts
const cache = new Map<string, { value: boolean; expires: number }>();
const DAY = 24 * 60 * 60 * 1000;

export async function lookupNorthCyprus(ip: string): Promise<boolean> {
  const hit = cache.get(ip);
  if (hit && hit.expires > Date.now()) return hit.value;
  const res = await fetch(`https://nc-ip.celya.tech/api/v1/lookup?ip=${encodeURIComponent(ip)}`, {
    headers: { "x-api-key": process.env.NCIP_API_KEY ?? "" },
  });
  if (!res.ok) return false; // fail open; choose deliberately
  const { northCyprus } = (await res.json()) as { northCyprus: boolean };
  cache.set(ip, { value: northCyprus, expires: Date.now() + DAY });
  return northCyprus;
}
```

Bound the cache size in production (LRU) so it cannot grow without limit.

## Verify the integration

1. **Unit tests with a fixture list, never real prefixes.** Feed the matcher `203.0.113.0/24` and `2001:db8::/32` and assert: `203.0.113.10` true, `198.51.100.7` false, `::ffff:203.0.113.10` true, `2001:db8::1` true, `not-an-ip` false, empty list false for everything.
2. **Key and quota:** `curl -sS -D- -o /dev/null -H "x-api-key: $NCIP_API_KEY" "https://nc-ip.celya.tech/api/v1/lookup?ip=192.0.2.1"` returns `200` with `X-RateLimit-Reset` (and `northCyprus: false` in the body).
3. **End to end without hard-coding data:** take the first line of the downloaded `prefixes.txt`, check that its network address matches locally, and that `/lookup` for the same address returns `northCyprus: true`.
4. **ETag:** run the sync twice; the second run must get `304` and leave the files untouched.
5. **Proxy setup:** request through the real edge and confirm the app sees the client address, not the proxy's.

## MCP server (for AI agents)

`https://nc-ip.celya.tech/api/v1/mcp` is a remote MCP server (Streamable HTTP, stateless, JSON responses; protocol revisions 2025-03-26, 2025-06-18 and 2025-11-25). Same key, as `x-api-key` or `Authorization: Bearer`.

Tools (all read-only): `lookup_ip` { ip }, `lookup_ips` { ips: up to 100, one request }, `list_prefixes` { family?, type?, network?, limit?, cursor? }, `registry_summary` {}, `get_download_urls` { format?, family?, type?, network? } (free). Every other `tools/call` counts as one request against the quota; `initialize` and `tools/list` are free. Quota errors come back as tool results with `isError: true`.

Claude Code:

```sh
claude mcp add --transport http nc-ip https://nc-ip.celya.tech/api/v1/mcp --header "x-api-key: $NCIP_API_KEY"
```

Cursor (`.cursor/mcp.json`):

```json
{ "mcpServers": { "nc-ip": { "url": "https://nc-ip.celya.tech/api/v1/mcp", "headers": { "x-api-key": "${env:NCIP_API_KEY}" } } } }
```

VS Code (`.vscode/mcp.json`):

```json
{
  "inputs": [{ "type": "promptString", "id": "ncip-key", "description": "NC-IP API key", "password": true }],
  "servers": { "nc-ip": { "type": "http", "url": "https://nc-ip.celya.tech/api/v1/mcp", "headers": { "x-api-key": "${input:ncip-key}" } } }
}
```

Other clients: point a Streamable HTTP client at the URL with header `x-api-key: <key>` (or `Authorization: Bearer <key>`). Clients that only run local (stdio) servers, such as Claude Desktop's config file, can bridge with `npx mcp-remote https://nc-ip.celya.tech/api/v1/mcp --header "x-api-key:${NCIP_API_KEY}"`.

Use the MCP tools for exploration and one-off questions. For production integrations, write code that follows the recipes above instead of calling MCP at runtime.
