Se il sito è servito tramite AWS CloudFront, S3 o un servizio edge di AWS simile, HitKeep non vede direttamente le richieste dei crawler IA. Inoltra le richieste lato server a:
POST /api/sites/{id}/ingest/ai-fetch
Per il contratto di acquisizione indipendente dal fornitore, i campi, la convalida e le integrazioni al di fuori di AWS, consulta la raccolta delle richieste IA. Qui trovi l’implementazione con CloudFront, S3 e Lambda.
La configurazione più semplice per la produzione funziona così:
- CloudFront invia i log standard a S3.
- Una funzione AWS Lambda analizza ciascun oggetto di log.
- Inoltra le richieste dei crawler IA a HitKeep con un token API ad ambito limitato.
Usiamo questa configurazione per siti statici come hitkeep.com.
Prerequisiti
Prerequisiti- Un sito già creato in HitKeep per il dominio da monitorare
- Un client API del team o un client API personale con accesso al sito
- Una distribuzione CloudFront che serve il sito
- Un bucket S3 per i log standard di CloudFront
- Una funzione Lambda nello stesso account AWS
Creare il token HitKeep
Creare il token HitKeepPer prima cosa crea un token API limitato al sito:
- Apri Settings → API Clients per un token personale oppure Administration → Team → Settings per un token del team.
- Crea un token con accesso al sito di destinazione.
- Copia subito il token.
Guida ai client API
Prepara questi valori:
HITKEEP_BASE_URLEsempio:https://cloud.hitkeep.euHITKEEP_SITE_IDEsempio:6d5f9e7b-...HITKEEP_API_TOKENHITKEEP_HOSTNAMEEsempio:hitkeep.com
Attivare i log standard di CloudFront
Attivare i log standard di CloudFrontNella distribuzione CloudFront:
- Apri Monitoring and logging.
- Attiva Standard logging.
- Scegli un bucket S3 e, se necessario, un prefisso.
- Mantieni il formato predefinito delimitato da tabulazioni.
A HitKeep bastano questi campi, già presenti nei log standard:
cs(User-Agent)cs-uri-stemcs-uri-queryx-host-headersc-statussc-bytestime-takensc-content-type
CloudFront consegna i log in lotti, quindi le richieste dei crawler compaiono in HitKeep con un breve ritardo.
Distribuire la funzione Lambda di inoltro
Distribuire la funzione Lambda di inoltroEcco un esempio di funzione Lambda:
import { gunzipSync } from "node:zlib";import { buffer } from "node:stream/consumers";
import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
const s3 = new S3Client({});
// for exampleconst botMatchers = [ "chatgpt-user", "gptbot", "claudebot", "claude-web", "perplexitybot", "google-extended", "googleother", "google-safety", "applebot-extended", "bytespider", "ccbot", "meta-externalagent", "meta-externalfetcher", "amazonbot", "cohere-ai", "youbot", "ai2bot", "diffbot", "timpibot", "imagesiftbot", "deepseekbot", "petalbot",];
function getRequiredEnv(name) { const value = process.env[name]?.trim(); if (!value) { throw new Error(`Missing required environment variable: ${name}`); } return value;}
const hitkeepBaseUrl = getRequiredEnv("HITKEEP_BASE_URL").replace(/\/+$/, "");const hitkeepSiteId = getRequiredEnv("HITKEEP_SITE_ID");const hitkeepApiToken = getRequiredEnv("HITKEEP_API_TOKEN");const defaultHostname = process.env.HITKEEP_HOSTNAME?.trim().toLowerCase() || "";const requestTimeoutMs = Number.parseInt(process.env.HITKEEP_TIMEOUT_MS ?? "10000", 10);
function safeDecode(value) { if (!value || value === "-") { return ""; }
try { return decodeURIComponent(value); } catch { return value; }}
function parseInteger(value) { if (!value || value === "-") { return undefined; }
const parsed = Number.parseInt(value, 10); return Number.isFinite(parsed) ? parsed : undefined;}
function parseDurationMs(value) { if (!value || value === "-") { return undefined; }
const parsed = Number.parseFloat(value); if (!Number.isFinite(parsed) || parsed < 0) { return undefined; }
return Math.round(parsed * 1000);}
function looksLikeAIBot(userAgent) { const normalized = userAgent.trim().toLowerCase(); return botMatchers.some((token) => normalized.includes(token));}
function normalizePath(stem, query) { const base = stem && stem !== "-" ? stem : "/"; if (!query || query === "-") { return base; } return `${base}?${query}`;}
function parseCloudFrontLog(content) { const lines = content.split("\n").map((line) => line.trim()).filter(Boolean); const fieldsLine = lines.find((line) => line.startsWith("#Fields:")); if (!fieldsLine) { throw new Error("CloudFront log is missing #Fields header"); }
const fieldNames = fieldsLine.replace(/^#Fields:\s*/, "").split(/\s+/); const records = [];
for (const line of lines) { if (line.startsWith("#")) { continue; }
const values = line.split("\t"); if (values.length !== fieldNames.length) { continue; }
const row = Object.fromEntries(fieldNames.map((field, index) => [field, values[index]])); const userAgent = safeDecode(row["cs(User-Agent)"]); if (!looksLikeAIBot(userAgent)) { continue; }
const path = normalizePath( safeDecode(row["cs-uri-stem"]), safeDecode(row["cs-uri-query"]), ); const statusCode = parseInteger(row["sc-status"]); if (!statusCode) { continue; }
const hostname = safeDecode(row["x-host-header"]) || safeDecode(row["cs(Host)"]) || defaultHostname; const normalizedHostname = hostname ? hostname.toLowerCase() : "";
if (defaultHostname && normalizedHostname && normalizedHostname !== defaultHostname) { continue; }
records.push({ path, hostname: normalizedHostname || undefined, status_code: statusCode, content_type: safeDecode(row["sc-content-type"]) || undefined, response_ms: parseDurationMs(row["time-taken"]), bytes_served: parseInteger(row["sc-bytes"]), user_agent: userAgent, }); }
return records;}
async function loadLogObject(bucket, key) { const response = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key })); const body = await buffer(response.Body); const raw = key.endsWith(".gz") ? gunzipSync(body) : body; return raw.toString("utf8");}
async function postFetchRecord(record) { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), requestTimeoutMs);
try { const response = await fetch( `${hitkeepBaseUrl}/api/sites/${hitkeepSiteId}/ingest/ai-fetch`, { method: "POST", headers: { Authorization: `Bearer ${hitkeepApiToken}`, "Content-Type": "application/json", }, body: JSON.stringify(record), signal: controller.signal, }, );
if (!response.ok) { const message = await response.text(); throw new Error(`HitKeep ingest failed with ${response.status}: ${message}`); } } finally { clearTimeout(timeout); }}
export const handler = async (event) => { let processedFiles = 0; let forwardedRecords = 0;
for (const s3Record of event.Records ?? []) { const bucket = s3Record.s3?.bucket?.name; const key = s3Record.s3?.object?.key ? decodeURIComponent(s3Record.s3.object.key.replace(/\+/g, " ")) : "";
if (!bucket || !key) { continue; }
const content = await loadLogObject(bucket, key); const records = parseCloudFrontLog(content);
for (const record of records) { await postFetchRecord(record); forwardedRecords += 1; }
processedFiles += 1; }
return { processedFiles, forwardedRecords, };};La funzione:
- scarica ogni oggetto di log CloudFront da S3,
- analizza dinamicamente l’intestazione
#Fields, - filtra gli user agent dei crawler IA conosciuti, per esempio
GPTBot,ClaudeBot,PerplexityBot,Google-ExtendedeAmazonbot, - inoltra le richieste corrispondenti all’endpoint di raccolta IA di HitKeep.
Ambiente di esecuzione Lambda
Ambiente di esecuzione LambdaUsa:
- Node.js 22.x o successivo
Variabili d’ambiente Lambda
Variabili d’ambiente LambdaImposta queste variabili sulla funzione:
HITKEEP_BASE_URL=https://cloud.hitkeep.euHITKEEP_SITE_ID=YOUR_SITE_UUIDHITKEEP_API_TOKEN=YOUR_BEARER_TOKENHITKEEP_HOSTNAME=hitkeep.comHITKEEP_TIMEOUT_MS=10000Autorizzazioni IAM
Autorizzazioni IAMLa funzione richiede:
s3:GetObjectsul bucket o sul prefisso dei log CloudFront- autorizzazioni di scrittura standard per CloudWatch Logs
Esempio minimo di policy inline:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": [ "arn:aws:s3:::YOUR_LOG_BUCKET/YOUR_PREFIX/*" ] }, { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "*" } ]}Creare e caricare il pacchetto
Creare e caricare il pacchettoSe usi solo l’esempio a file singolo, crea un archivio ZIP e direttamente la funzione Lambda:
aws lambda create-function \ --function-name hitkeep-ai-fetch-forwarder \ --runtime nodejs22.x \ --handler index.handler \ --zip-file fileb://ai-fetch-cloudfront-forwarder.zip \ --role arn:aws:iam::123456789012:role/hitkeep-ai-fetch-forwarder \ --timeout 60 \ --memory-size 256Per aggiornare una funzione esistente:
aws lambda update-function-code \ --function-name hitkeep-ai-fetch-forwarder \ --zip-file fileb://ai-fetch-cloudfront-forwarder.zipConfigura l’ambiente:
aws lambda update-function-configuration \ --function-name hitkeep-ai-fetch-forwarder \ --environment "Variables={HITKEEP_BASE_URL=https://cloud.hitkeep.eu,HITKEEP_SITE_ID=YOUR_SITE_UUID,HITKEEP_API_TOKEN=YOUR_BEARER_TOKEN,HITKEEP_HOSTNAME=hitkeep.com,HITKEEP_TIMEOUT_MS=10000}"Collegare le notifiche di eventi S3
Collegare le notifiche di eventi S3Configura il bucket dei log CloudFront per richiamare Lambda alla creazione di un oggetto:
- Tipo di evento:
s3:ObjectCreated:* - Prefisso: quello dei log, se presente
- Suffisso:
.gz
Il filtro limita così l’elaborazione ai file di log completi, escludendo gli altri oggetti del bucket.
Dati inviati a HitKeep
Dati inviati a HitKeepOgni richiesta di un crawler IA che supera il filtro viene inviata in questa forma:
{ "path": "/guides/analytics/ai-visibility/", "hostname": "hitkeep.com", "status_code": 200, "content_type": "text/html", "response_ms": 143, "bytes_served": 48231, "user_agent": "Mozilla/5.0 (compatible; GPTBot/1.0; +https://openai.com/gptbot)"}HitKeep ricava automaticamente i seguenti campi dallo user agent e dal tipo di contenuto:
assistant_nameassistant_familyresource_type
L’endpoint usa l’ora di acquisizione come timestamp della richiesta del crawler. Se ti serve l’ora esatta delle richieste storiche, conserva i log originali per l’audit e inoltra i nuovi lotti il prima possibile dopo la creazione.
Verificare la configurazione
Verificare la configurazioneEsegui questi controlli:
- Verifica che CloudFront scriva file
.gzin S3. - Verifica che i nuovi oggetti attivino Lambda.
- Cerca
forwardedRecordsin CloudWatch Logs. - In HitKeep apri AI Agents, passa alla scheda Crawlers e attendi le prime righe di richieste.
Se la funzione viene eseguita ma non compaiono righe:
- verifica che il token abbia accesso al sito,
- verifica che
HITKEEP_SITE_IDsia l’UUID corretto del sito, - verifica che l’host sia quello del sito monitorato,
- controlla che gli user agent corrispondano effettivamente a crawler IA e non a crawler generici.
Una visita può comparire tra i visitatori in tempo reale prima della consegna del log CloudFront. Dopo l’arrivo di un lotto, chiedi a un assistente con accesso in sola lettura al sito i totali e i codici di stato dei crawler nel periodo di consegna. Verifica separatamente l’inoltro da Lambda.
Note e limiti
Note e limiti- Il ritardo nella consegna a lotti dei log standard di CloudFront è normale.
- La configurazione è particolarmente adatta ai siti statici e alle origini servite tramite edge, dove è difficile aggiungere direttamente il monitoraggio al server applicativo.
- Con ALB, nginx o Caddy davanti al server di origine, i log dell’origine sono spesso preferibili perché permettono di inoltrare subito le singole voci.
- Lambda e le notifiche S3 prevedono una consegna almeno una volta. In rari casi un nuovo tentativo può quindi duplicare una riga di richiesta IA.