Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 10 min read

That Request Says It's ChatGPT. Check the IP Before You Believe It

Let me start with something you'll probably see in your logs this week. A request hits your checkout page, and its user agent says ChatGPT-User, which is the name OpenAI's assistant uses when it visits a site because som

That Request Says It's ChatGPT. Check the IP Before You Believe It

Let me start with something you'll probably see in your logs this week. A request hits your checkout page, and its user agent says ChatGPT-User, which is the name OpenAI's assistant uses when it visits a site because someone asked it to. Maybe a shopper asked ChatGPT to find a deal and it's checking your price. Or maybe it's a scraper that borrowed the name, because it knows plenty of stores let AI assistants through.

From the request alone, you can't tell which one it is, and this week it matters more than usual. Black Friday is on Friday, AI shopping agents are visiting stores far more than they were a few months ago, and login bots are busy too. Block the real assistant and you lose a sale. Let the fake one in and you've given a scraper a free pass.

The way I sort this out comes down to one question, which is whether the company named in the user agent actually owns the IP address the request came from. In this post I'll show you how to ask that question with the IPGeolocation.io IP Security API, what to do with the answer, and the Node.js code I'd use for it.

Why You Can't Trust the User Agent on Its Own

The user agent is a short line of text that every client sends in the User-Agent header to say what it is. Your browser sends one that mentions Chrome or Safari, and OpenAI's assistant sends one with ChatGPT-User in it. The trouble is that nothing checks it. Anyone writing a scraper can put whatever they like in that header, and copying the name of a well-known AI assistant is an easy way past bot rules that were told to let assistants in.

The usual fallback doesn't work well either. A lot of bot rules challenge anything coming from a data center, on the idea that real shoppers browse from home or from their phones. But real AI assistants run on cloud servers too, so that rule turns away the agents you want along with the scrapers. When the agency Blend tested an AI shopping agent against 200 retailers in October, bot protection turned it away at 29 of them.

What the IP Address Tells You Instead

The IP address is much harder to fake than the user agent. When OpenAI's assistant visits your site, the request comes from an address OpenAI controls, and OpenAI publishes those address ranges so that sites can check them. A scraper can copy the name, but it can't send its requests from OpenAI's addresses.

So instead of trusting the name, I look up the address. The IP Security API takes an IP address and tells you what's known about it, including whether it belongs to a bot and who runs that bot. Each lookup costs 2 credits and needs a paid plan. I ask for only the fields I need, which keeps the response small.

curl 'https://api.ipgeolocation.io/v3/security?apiKey=API_KEY&ip=4.227.36.0&fields=security.is_bot,security.bot_type,security.bot_operator_name,security.is_known_good_bot,security.is_cloud_provider,security.cloud_provider_name'

That address belongs to OpenAI's crawler. This is the response the API documentation shows for it, cut down to those fields.

{
  "ip": "4.227.36.0",
  "security": {
    "is_bot": true,
    "bot_operator_name": "OpenAI",
    "bot_type": "ai_crawler",
    "is_known_good_bot": true,
    "is_cloud_provider": true,
    "cloud_provider_name": "Microsoft Corporation"
  }
}

The field that answers our question is bot_operator_name, which names the company running the bot from that address. is_known_good_bot is true when that company declares its bot and publishes its addresses, so the match can be confirmed rather than guessed. bot_type tells you what the bot is there to do. ai_crawler means it's collecting pages for AI training with nobody waiting on it, and ai_assistant means it's fetching a page because a person asked it something right now.

I'd also point out is_cloud_provider. It's true because OpenAI's crawler runs on Microsoft's cloud, which is exactly why a "block the data centers" rule gets this one wrong.

Now picture the scraper that borrowed the ChatGPT name. Its request might come from a rented server or someone's hacked router, and when you look that address up, OpenAI won't be the operator. That mismatch between the name in the header and the owner of the address is what we'll check for in code.

How to Check a Claimed AI Agent in Node.js

The code has two small parts. The first looks up the address, and the second compares the name in the user agent with the operator the API returns. It runs on Node.js 18 or later, which has fetch built in.

The lookup asks for a few more fields than the curl example, because we'll use them in a minute to decide what to do with the request. I've also given it a short timeout, since it sits in front of your checkout and you don't want shoppers waiting on it.

// botcheck.mjs
const SECURITY_URL = 'https://api.ipgeolocation.io/v3/security';
const FIELDS = [
  'security.is_known_attacker',
  'security.is_bot',
  'security.bot_type',
  'security.bot_operator_name',
  'security.is_known_good_bot',
  'security.is_cloud_provider',
  'security.is_corporate_gateway',
  'security.is_relay',
].join(',');

export async function lookupSecurity(ip) {
  const url = new URL(SECURITY_URL);
  url.searchParams.set('apiKey', process.env.IPGEO_API_KEY);
  url.searchParams.set('ip', ip);
  url.searchParams.set('fields', FIELDS);

  const res = await fetch(url, { signal: AbortSignal.timeout(1500) });
  if (!res.ok) throw new Error(`Security lookup failed for ${ip}: HTTP ${res.status}`);
  const { security } = await res.json();
  return security;
}

For the comparison, I keep a small list of the agent names that show up in user agents and the company each one belongs to. You can add to it as new names appear in your logs.

// botcheck.mjs (continued)
const CLAIMS = [
  { pattern: /ChatGPT-User|OAI-SearchBot|GPTBot/i, operator: 'OpenAI' },
  { pattern: /Claude-User|Claude-SearchBot|ClaudeBot/i, operator: 'Anthropic' },
  { pattern: /Perplexity-User|PerplexityBot/i, operator: 'Perplexity' },
];

export function claimedOperator(userAgent = '') {
  const match = CLAIMS.find((claim) => claim.pattern.test(userAgent));
  return match ? match.operator : null;
}

export function verifyClaim(userAgent, security) {
  const claimed = claimedOperator(userAgent);
  if (!claimed) return { claimed: null, verified: false };
  const reported = (security.bot_operator_name || '').toLowerCase();
  const verified = security.is_known_good_bot === true && reported.includes(claimed.toLowerCase());
  return { claimed, verified };
}

verifyClaim tells you two separate things, and I'd treat them differently. If claimed is null, the request didn't name any agent, which is what every normal browser looks like, so there's nothing to check. If claimed has a value but verified is false, the request named a company that doesn't own its address. That's someone telling you something untrue about themselves, and I trust it less than a request that never claimed anything.

One small thing to watch is the spelling of operator names. The documentation shows "OpenAI" for OpenAI's crawler, which is why the comparison uses includes rather than an exact match. For the other companies, I'd log bot_operator_name for a few days and adjust the operator values in CLAIMS to match what you see.

What to Do With the Answer

Knowing whether the claim holds up is the main thing, but you still have to decide what happens to the request. This is the rule I use, and the order of the checks matters.

// route.mjs
import { verifyClaim } from './botcheck.mjs';

export function routeRequest(userAgent, security) {
  if (security.is_known_attacker) {
    return { action: 'block', reason: `known attacker (${security.bot_type || 'flagged'})` };
  }

  const { claimed, verified } = verifyClaim(userAgent, security);
  if (claimed && !verified) {
    return { action: 'challenge', reason: `claims ${claimed}, IP doesn't match` };
  }

  if (security.is_known_good_bot) {
    if (security.bot_type === 'ai_assistant') {
      return { action: 'allow', reason: `assistant for a waiting user (${security.bot_operator_name})` };
    }
    return { action: 'rate_limit', reason: `${security.bot_type} (${security.bot_operator_name})` };
  }

  if (security.is_corporate_gateway || security.is_relay) {
    return { action: 'allow', reason: 'shared address used by people' };
  }

  if (security.is_bot || security.is_cloud_provider) {
    return { action: 'challenge', reason: 'unverified automation or cloud traffic' };
  }

  return { action: 'allow', reason: 'no automation signals' };
}

Known attackers go first, so a borrowed agent name can never get one through. The claim check comes next, and a failed claim gets a challenge, such as a CAPTCHA, rather than a block, in case it's a real agent you haven't added to CLAIMS yet. A verified assistant is let straight in, because there's a person on the other end waiting for an answer, and a verified crawler is only rate limited, since nobody's waiting on it.

The next check is there to protect people. Company networks often send all their staff's traffic through a security service such as Zscaler, and privacy relays like iCloud Private Relay do something similar for Safari users. Both look like cloud traffic, but there are real shoppers behind them, sometimes hundreds on one address. Anything left over that looks automated or comes from a cloud server gets a challenge, and everything else is treated as a person.

The routing rule runs five checks in order on login and checkout, and the first match decides whether a request is blocked, challenged, rate limited, or allowed.

Putting It in Front of Login and Checkout

You don't need this on every page. Product pages and search results are where most agents spend their time, and they're fine there. The check earns its keep on the pages where a bad bot can do damage, which for a store means login, account recovery, and checkout. In Express, that looks like this.

// middleware.mjs
import { lookupSecurity } from './botcheck.mjs';
import { routeRequest } from './route.mjs';

const cache = new Map();
const CACHE_MS = 6 * 60 * 60 * 1000; // six hours

async function cachedSecurity(ip) {
  const hit = cache.get(ip);
  if (hit && hit.expires > Date.now()) return hit.security;
  const security = await lookupSecurity(ip);
  cache.set(ip, { security, expires: Date.now() + CACHE_MS });
  return security;
}

export function agentGate() {
  return async (req, res, next) => {
    let decision;
    try {
      decision = routeRequest(req.get('user-agent'), await cachedSecurity(req.ip));
    } catch (err) {
      // If the lookup fails, let the shopper through and log it.
      decision = { action: 'allow', reason: `lookup failed: ${err.message}` };
    }
    console.log(JSON.stringify({ ip: req.ip, path: req.originalUrl, ...decision }));

    if (decision.action === 'block') return res.status(403).send('Forbidden');
    if (decision.action === 'challenge') return res.status(403).json({ challenge: true });
    if (decision.action === 'rate_limit') res.set('X-Agent-Policy', 'rate-limited');
    next();
  };
}
// app.mjs
app.set('trust proxy', 1); // the number of proxies in front of your app
app.use(['/login', '/account/recover', '/checkout'], agentGate());

A few choices in there are deliberate. The cache keeps one result per address for six hours, because the API rebuilds its security data once a day, so a shopper who logs in, fills the cart, and checks out costs you one lookup instead of three. If the lookup fails or times out, the request goes through and the reason gets logged, since during the biggest sales week of the year I'd rather miss a bot than block someone paying. The { challenge: true } response is for your frontend to catch and show a CAPTCHA.

The trust proxy line deserves a proper warning, because it's tied directly to the claim check. If your app sits behind a load balancer, Express needs that setting to see the visitor's real address in req.ip. Set it to the exact number of proxies in front of your app, though, and never to true. With true, Express believes whatever address a client writes in the X-Forwarded-For header, so a scraper could write one of OpenAI's addresses there and pass the check we built above without ever touching OpenAI's network. It's worth double-checking that line before Friday.

What This Check Can't Catch

The claim check only works when a request names an agent. Some AI agents drive a full browser in the cloud and send an ordinary Chrome user agent, so they make no claim to test. Those fall through to the cloud rule and get a challenge, which is a fair default for traffic nobody has identified, even if it occasionally catches a well-behaved agent.

The other gap is an agent running inside the shopper's own browser on their own computer. Its requests come from the shopper's home connection with the shopper's normal user agent, so to your server it looks exactly like the shopper. I don't think that's worth worrying about, because the shopper really is there, on their own connection and paying with their own card.

If you'd like to try this on your own traffic, I'd start by commenting out the three if lines at the end of agentGate for a day. The gate then only logs its decisions, so you can see which requests it would block or challenge before it touches a real shopper. The IP Security API documentation lists every field used here, and the pricing page shows which plans include security data.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.