@knownagents/sdk 1.9.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -68,6 +68,33 @@ app.get("/", (req, res) => {
68
68
  app.listen(3000, () => console.log("Server running on port 3000"))
69
69
  ```
70
70
 
71
+ ### Batch Requests If Possible
72
+
73
+ For high-traffic websites, batch multiple visits together and send them periodically (e.g. every 30 seconds) using `trackVisits`:
74
+
75
+ ```ts
76
+ import { VisitRequest } from "@knownagents/sdk"
77
+
78
+ const visits: VisitRequest[] = []
79
+
80
+ // Collect visits
81
+ visits.push({
82
+ request_path: req.url,
83
+ request_method: req.method,
84
+ request_headers: req.headers,
85
+ response_status_code: res.statusCode,
86
+ response_duration_in_milliseconds: duration,
87
+ created: new Date().toISOString()
88
+ })
89
+
90
+ // Send batch periodically
91
+ setInterval(() => {
92
+ if (visits.length > 0) {
93
+ knownAgents.trackVisits(visits.splice(0))
94
+ }
95
+ }, 30000)
96
+ ```
97
+
71
98
  ### Test Your Integration
72
99
 
73
100
  - Open your project's settings page
@@ -95,25 +122,45 @@ const robotsTxt = await knownAgents.generateRobotsTXT([
95
122
 
96
123
  The return value is a plain text robots.txt string. Generate a `robotsTxt` periodically (e.g. once per day), then cache and serve it from your website's `/robots.txt` endpoint.
97
124
 
98
- ## How To Use Agent Verification ([Full Docs](https://knownagents.com/docs/verification))
125
+ ## How To Use Agent Identification ([Full Docs](https://knownagents.com/docs/identification))
99
126
 
100
- Use the `verifyAgent` function to [identify](https://knownagents.com/agents) and verify agents from network requests using Web Bot Auth (HTTP message signatures), IP matching, or other available methods. This can be useful for implementing access policies based on verified agent identity.
127
+ Use the `identifyAgent` and `identifyAgents` functions to [identify](https://knownagents.com/agents) and verify agents from network requests using Web Bot Auth (HTTP message signatures), IP matching, or other available methods. This can be useful for implementing access policies based on verified agent identity or enriching your own datasets.
101
128
 
102
- Call `verifyAgent` with the incoming request.
129
+ ### Identify a Single Request
130
+
131
+ Call `identifyAgent` with the incoming request.
103
132
 
104
133
  ```ts
105
- const verification = await knownAgents.verifyAgent(request)
134
+ const identification = await knownAgents.identifyAgent(request)
106
135
 
107
- if (verification.result === "verified") {
136
+ if (identification.result === "verified") {
108
137
  // Agent is legitimate
109
- } else if (verification.result === "verification_failed") {
138
+ } else if (identification.result === "verification_failed") {
110
139
  // Agent is not legitimate
111
140
  }
112
141
  ```
113
142
 
114
- The function returns an object with the following fields:
143
+ ### Identify Multiple Requests
144
+
145
+ Use `identifyAgents` to identify multiple requests at once:
146
+
147
+ ```ts
148
+ const identifications = await knownAgents.identifyAgents([
149
+ {
150
+ id: "request-1",
151
+ request_headers: request1.headers
152
+ },
153
+ {
154
+ id: "request-2",
155
+ request_headers: request2.headers
156
+ }
157
+ ])
158
+ ```
159
+
160
+ The functions return an object (or array of objects) with the following fields:
115
161
 
116
- - `result`: The verification result:
162
+ - `id`: The identifier from the request (if provided)
163
+ - `result`: The identification result:
117
164
  - `"verified"`: The agent is identified and verified
118
165
  - `"verification_failed"`: The agent was identified but could not be verified
119
166
  - `"unknown_agent"`: The agent is not in our database
package/dist/index.d.ts CHANGED
@@ -1,31 +1,79 @@
1
1
  import { IncomingMessage, ServerResponse } from "http";
2
+ /**
3
+ * A framework-agnostic HTTP request interface.
4
+ * Used as a convenience type for single-request methods.
5
+ */
2
6
  export interface Request {
3
- /** The URL of the request, including the path and query string (e.g. "/about?foo=bar") */
7
+ /** The URL path and query string (e.g. "/about?foo=bar") */
4
8
  path: string;
5
- /** The request's HTTP method (e.g. "GET", "POST") */
9
+ /** The HTTP method (e.g. "GET", "POST") */
6
10
  method: string;
7
- /** The request's HTTP headers */
11
+ /** The HTTP request headers */
8
12
  headers: Record<string, string | string[] | undefined>;
9
13
  }
14
+ /**
15
+ * A minimal HTTP response interface.
16
+ * Used as a convenience type for single-request methods.
17
+ */
10
18
  export interface Response {
11
- /** The HTTP response status code */
19
+ /** The HTTP response status code (e.g. 200, 404) */
12
20
  statusCode: number;
21
+ /** The HTTP response headers */
22
+ headers?: Record<string, string | string[] | undefined>;
23
+ }
24
+ /**
25
+ * A visit tracking request for the Known Agents API.
26
+ * Used for batch visit tracking with `trackVisits()`.
27
+ */
28
+ export interface VisitRequest {
29
+ /** The URL path of the request (e.g. "/about?foo=bar") */
30
+ request_path: string;
31
+ /** The HTTP method (e.g. "GET", "POST") */
32
+ request_method: string;
33
+ /** The HTTP request headers */
34
+ request_headers: Record<string, string | string[] | undefined>;
35
+ /** The HTTP response status code (e.g. 200, 404) */
36
+ response_status_code?: number;
37
+ /** The HTTP response headers */
38
+ response_headers?: Record<string, string | string[] | undefined>;
39
+ /** The response duration in milliseconds */
40
+ response_duration_in_milliseconds?: number;
41
+ /** The timestamp when the visit occurred (ISO 8601 format) */
42
+ created?: string;
43
+ }
44
+ /**
45
+ * An agent identification request for the Known Agents API.
46
+ * Used for batch agent identification with `identifyAgents()`.
47
+ */
48
+ export interface IdentificationRequest {
49
+ /** An identifier that will be echoed back in the response to match requests with results */
50
+ id?: string;
51
+ /** The HTTP request headers */
52
+ request_headers: Record<string, string | string[] | undefined>;
13
53
  }
14
54
  /**
15
- * The result of an agent verification check.
55
+ * The result of an agent identification request.
16
56
  */
17
- export interface VerificationResult {
18
- /** The verification result */
57
+ export interface IdentificationResult {
58
+ /** The identifier from the request (if provided) */
59
+ id?: string;
60
+ /**
61
+ * The identification result:
62
+ * - "verified": The agent was identified and verified
63
+ * - "verification_failed": The agent was identified but failed verification (spoofed)
64
+ * - "unknown_agent": The request is from an unrecognized agent or human
65
+ * - "not_verifiable": The agent was identified but cannot be verified
66
+ */
19
67
  result: "verified" | "verification_failed" | "unknown_agent" | "not_verifiable";
20
- /** The unique ID of the agent (if identified) */
68
+ /** The unique ID of the identified agent */
21
69
  agent_id?: string;
22
- /** The name of the agent (e.g. "Googlebot") (if identified) */
70
+ /** The name of the identified agent (e.g. "Googlebot") */
23
71
  agent_token?: string;
24
- /** The documentation URL of the agent (if identified) */
72
+ /** The documentation URL for the identified agent */
25
73
  agent_url?: string;
26
- /** The type of agent (e.g. "AI Agent") (if identified) */
74
+ /** The type of the identified agent (e.g. "AI Agent", "Search Engine Crawler") */
27
75
  agent_type_name?: string;
28
- /** The company behind the agent (e.g. "Google") (if identified) */
76
+ /** The company behind the identified agent (e.g. "Google") */
29
77
  operator_name?: string;
30
78
  }
31
79
  /**
@@ -34,6 +82,8 @@ export interface VerificationResult {
34
82
  export declare enum AgentType {
35
83
  AIAgent = "AI Agent",
36
84
  AIAssistant = "AI Assistant",
85
+ AICodingAgent = "AI Coding Agent",
86
+ AIDataProvider = "AI Data Provider",
37
87
  AIDataScraper = "AI Data Scraper",
38
88
  AISearchCrawler = "AI Search Crawler",
39
89
  Archiver = "Archiver",
@@ -56,31 +106,52 @@ export declare class KnownAgents {
56
106
  */
57
107
  constructor(accessToken: string);
58
108
  /**
59
- * Tracks an agent visit in Known Agents agent analytics.
109
+ * Tracks a single agent visit for analytics.
110
+ * This method is non-blocking and handles errors internally.
60
111
  *
61
- * @param request - The incoming request.
62
- * @param response - The outgoing response (optional).
63
- * @param responseDurationInMilliseconds - The response duration in milliseconds (optional).
112
+ * @param request - The incoming HTTP request (Request or Node.js IncomingMessage).
113
+ * @param response - The outgoing HTTP response (optional).
114
+ * @param responseDurationInMilliseconds - The time taken to process the request in milliseconds (optional).
64
115
  */
65
116
  trackVisit(request: Request | IncomingMessage, response?: Response | ServerResponse, responseDurationInMilliseconds?: number): void;
66
117
  /**
67
- * Generates a `robots.txt` file that disallows the specified agent types.
68
- * Cache and serve this string at your website’s `/robots.txt` endpoint.
118
+ * Tracks multiple agent visits in a batch for analytics.
119
+ * This method is non-blocking and handles errors internally.
120
+ * Recommended for high-traffic websites - batch visits and send periodically (e.g. every 30 seconds).
69
121
  *
70
- * @param agentTypes - A list of agent types to include.
71
- * @param disallow - A path to disallow (default is "/" for all paths).
72
- * @returns The generated `robots.txt` as a string.
73
- * @throws If the API call fails or returns a non-200 status.
122
+ * @param visits - An array of visit tracking requests.
123
+ */
124
+ trackVisits(visits: VisitRequest[]): void;
125
+ /**
126
+ * Generates a robots.txt file that disallows the specified agent types.
127
+ * The generated file stays up-to-date with all current and future agents in the specified categories.
128
+ * Cache and serve the result at your website's `/robots.txt` endpoint.
129
+ *
130
+ * @param agentTypes - An array of agent types to disallow.
131
+ * @param disallow - The path to disallow (default: "/" for all paths).
132
+ * @returns A promise that resolves to the generated robots.txt content as a string.
133
+ * @throws {Error} If the API call fails or returns a non-200 status.
74
134
  */
75
135
  generateRobotsTXT(agentTypes: AgentType[], disallow?: string): Promise<string>;
76
136
  /**
77
- * Verifies if an agent request is legitimate by checking it against Known Agents.
137
+ * Identifies and verifies a single agent from an HTTP request.
138
+ * Uses Web Bot Auth (HTTP message signatures), IP matching, or other available methods.
139
+ *
140
+ * @param request - The incoming HTTP request (Request or Node.js IncomingMessage).
141
+ * @returns A promise that resolves to the identification result.
142
+ * @throws {Error} If the API call fails or returns a non-200 status.
143
+ */
144
+ identifyAgent(request: Request | IncomingMessage): Promise<IdentificationResult>;
145
+ /**
146
+ * Identifies and verifies multiple agents from HTTP requests in a batch.
147
+ * Uses Web Bot Auth (HTTP message signatures), IP matching, or other available methods.
78
148
  *
79
- * @param request - The incoming request.
80
- * @returns A promise that resolves to the verification result.
81
- * @throws If the API call fails or returns a non-200 status.
149
+ * @param requests - An array of identification requests.
150
+ * @returns A promise that resolves to an array of identification results.
151
+ * @throws {Error} If the API call fails or returns a non-200 status.
82
152
  */
83
- verifyAgent(request: Request | IncomingMessage): Promise<VerificationResult>;
153
+ identifyAgents(requests: IdentificationRequest[]): Promise<IdentificationResult[]>;
154
+ private isPathExcluded;
84
155
  private filterHeaders;
85
156
  }
86
157
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,MAAM,CAAA;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gBACS,WAAW,EAAE,MAAM;IAI/B;;;;;;;OAOG;IACH,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,eAAe,EAAE,QAAQ,CAAC,EAAE,QAAQ,GAAG,cAAc,EAAE,8BAA8B,CAAC,EAAE,MAAM,GAAG,IAAI;IA4BnI;;;;;;OAMG;IACH,WAAW,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,IAAI;IA6BzC;;;;;;;;;OASG;IACG,iBAAiB,CAAC,UAAU,EAAE,SAAS,EAAE,EAAE,QAAQ,GAAE,MAAY,GAAG,OAAO,CAAC,MAAM,CAAC;IAoBzF;;;;;;;OAOG;IACG,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,eAAe,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAmBtF;;;;;;;OAOG;IACG,cAAc,CAAC,QAAQ,EAAE,qBAAqB,EAAE,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC;IAwBxF,OAAO,CAAC,cAAc;IA2DtB,OAAO,CAAC,aAAa;CAcxB"}
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.KnownAgents = exports.AgentType = void 0;
4
- const NODE_PACKAGE_VERSION = "1.9.0";
4
+ const http_1 = require("http");
5
5
  /**
6
6
  * Agent types that can be controlled with robots.txt rules.
7
7
  */
@@ -9,6 +9,8 @@ var AgentType;
9
9
  (function (AgentType) {
10
10
  AgentType["AIAgent"] = "AI Agent";
11
11
  AgentType["AIAssistant"] = "AI Assistant";
12
+ AgentType["AICodingAgent"] = "AI Coding Agent";
13
+ AgentType["AIDataProvider"] = "AI Data Provider";
12
14
  AgentType["AIDataScraper"] = "AI Data Scraper";
13
15
  AgentType["AISearchCrawler"] = "AI Search Crawler";
14
16
  AgentType["Archiver"] = "Archiver";
@@ -32,13 +34,19 @@ class KnownAgents {
32
34
  this.accessToken = accessToken;
33
35
  }
34
36
  /**
35
- * Tracks an agent visit in Known Agents agent analytics.
37
+ * Tracks a single agent visit for analytics.
38
+ * This method is non-blocking and handles errors internally.
36
39
  *
37
- * @param request - The incoming request.
38
- * @param response - The outgoing response (optional).
39
- * @param responseDurationInMilliseconds - The response duration in milliseconds (optional).
40
+ * @param request - The incoming HTTP request (Request or Node.js IncomingMessage).
41
+ * @param response - The outgoing HTTP response (optional).
42
+ * @param responseDurationInMilliseconds - The time taken to process the request in milliseconds (optional).
40
43
  */
41
44
  trackVisit(request, response, responseDurationInMilliseconds) {
45
+ const path = "path" in request ? request.path : request.url;
46
+ const responseHeaders = response instanceof http_1.ServerResponse ? response.getHeaders() : response?.headers;
47
+ if (!path || this.isPathExcluded(path)) {
48
+ return;
49
+ }
42
50
  fetch("https://api.knownagents.com/visits", {
43
51
  method: "POST",
44
52
  headers: {
@@ -46,12 +54,12 @@ class KnownAgents {
46
54
  "Content-Type": "application/json"
47
55
  },
48
56
  body: JSON.stringify({
49
- request_path: "path" in request ? request.path : request.url,
57
+ request_path: path,
50
58
  request_method: request.method,
51
59
  request_headers: this.filterHeaders(request.headers),
52
60
  response_status_code: response?.statusCode,
61
+ response_headers: responseHeaders ? this.filterHeaders(responseHeaders) : undefined,
53
62
  response_duration_in_milliseconds: responseDurationInMilliseconds,
54
- node_package_version: NODE_PACKAGE_VERSION,
55
63
  created: new Date().toISOString()
56
64
  })
57
65
  }).catch(error => {
@@ -59,13 +67,47 @@ class KnownAgents {
59
67
  });
60
68
  }
61
69
  /**
62
- * Generates a `robots.txt` file that disallows the specified agent types.
63
- * Cache and serve this string at your website’s `/robots.txt` endpoint.
70
+ * Tracks multiple agent visits in a batch for analytics.
71
+ * This method is non-blocking and handles errors internally.
72
+ * Recommended for high-traffic websites - batch visits and send periodically (e.g. every 30 seconds).
64
73
  *
65
- * @param agentTypes - A list of agent types to include.
66
- * @param disallow - A path to disallow (default is "/" for all paths).
67
- * @returns The generated `robots.txt` as a string.
68
- * @throws If the API call fails or returns a non-200 status.
74
+ * @param visits - An array of visit tracking requests.
75
+ */
76
+ trackVisits(visits) {
77
+ const filteredVisits = visits
78
+ .filter((visit) => {
79
+ return !this.isPathExcluded(visit.request_path);
80
+ })
81
+ .map((visit) => {
82
+ return {
83
+ ...visit,
84
+ request_headers: this.filterHeaders(visit.request_headers),
85
+ response_headers: visit.response_headers ? this.filterHeaders(visit.response_headers) : undefined,
86
+ };
87
+ });
88
+ if (filteredVisits.length === 0) {
89
+ return;
90
+ }
91
+ fetch("https://api.knownagents.com/visits", {
92
+ method: "POST",
93
+ headers: {
94
+ "Authorization": `Bearer ${this.accessToken}`,
95
+ "Content-Type": "application/json"
96
+ },
97
+ body: JSON.stringify(filteredVisits)
98
+ }).catch(error => {
99
+ console.error(`Known Agents failed to track visits: ${error.message}`);
100
+ });
101
+ }
102
+ /**
103
+ * Generates a robots.txt file that disallows the specified agent types.
104
+ * The generated file stays up-to-date with all current and future agents in the specified categories.
105
+ * Cache and serve the result at your website's `/robots.txt` endpoint.
106
+ *
107
+ * @param agentTypes - An array of agent types to disallow.
108
+ * @param disallow - The path to disallow (default: "/" for all paths).
109
+ * @returns A promise that resolves to the generated robots.txt content as a string.
110
+ * @throws {Error} If the API call fails or returns a non-200 status.
69
111
  */
70
112
  async generateRobotsTXT(agentTypes, disallow = "/") {
71
113
  const response = await fetch("https://api.knownagents.com/robots-txts", {
@@ -76,8 +118,7 @@ class KnownAgents {
76
118
  },
77
119
  body: JSON.stringify({
78
120
  agent_types: agentTypes,
79
- disallow: disallow,
80
- node_package_version: NODE_PACKAGE_VERSION
121
+ disallow: disallow
81
122
  })
82
123
  });
83
124
  if (response.ok) {
@@ -88,33 +129,117 @@ class KnownAgents {
88
129
  }
89
130
  }
90
131
  /**
91
- * Verifies if an agent request is legitimate by checking it against Known Agents.
132
+ * Identifies and verifies a single agent from an HTTP request.
133
+ * Uses Web Bot Auth (HTTP message signatures), IP matching, or other available methods.
92
134
  *
93
- * @param request - The incoming request.
94
- * @returns A promise that resolves to the verification result.
95
- * @throws If the API call fails or returns a non-200 status.
135
+ * @param request - The incoming HTTP request (Request or Node.js IncomingMessage).
136
+ * @returns A promise that resolves to the identification result.
137
+ * @throws {Error} If the API call fails or returns a non-200 status.
96
138
  */
97
- async verifyAgent(request) {
98
- const response = await fetch("https://api.knownagents.com/agent-verifications", {
139
+ async identifyAgent(request) {
140
+ const response = await fetch("https://api.knownagents.com/agent-identifications", {
99
141
  method: "POST",
100
142
  headers: {
101
143
  "Authorization": `Bearer ${this.accessToken}`,
102
144
  "Content-Type": "application/json"
103
145
  },
104
146
  body: JSON.stringify({
105
- request_path: "path" in request ? request.path : request.url,
106
- request_headers: this.filterHeaders(request.headers),
107
- node_package_version: NODE_PACKAGE_VERSION
147
+ request_headers: this.filterHeaders(request.headers)
108
148
  })
109
149
  });
110
150
  if (response.ok) {
111
151
  return await response.json();
112
152
  }
113
153
  else {
114
- throw new Error(`Known Agents failed to verify agent: ${response.status} ${response.statusText}`);
154
+ throw new Error(`Known Agents failed to identify agent: ${response.status} ${response.statusText}`);
155
+ }
156
+ }
157
+ /**
158
+ * Identifies and verifies multiple agents from HTTP requests in a batch.
159
+ * Uses Web Bot Auth (HTTP message signatures), IP matching, or other available methods.
160
+ *
161
+ * @param requests - An array of identification requests.
162
+ * @returns A promise that resolves to an array of identification results.
163
+ * @throws {Error} If the API call fails or returns a non-200 status.
164
+ */
165
+ async identifyAgents(requests) {
166
+ const response = await fetch("https://api.knownagents.com/agent-identifications", {
167
+ method: "POST",
168
+ headers: {
169
+ "Authorization": `Bearer ${this.accessToken}`,
170
+ "Content-Type": "application/json"
171
+ },
172
+ body: JSON.stringify(requests.map(request => {
173
+ return {
174
+ ...request,
175
+ request_headers: this.filterHeaders(request.request_headers),
176
+ };
177
+ }))
178
+ });
179
+ if (response.ok) {
180
+ return await response.json();
181
+ }
182
+ else {
183
+ throw new Error(`Known Agents failed to identify agents: ${response.status} ${response.statusText}`);
115
184
  }
116
185
  }
117
186
  // Helpers
187
+ isPathExcluded(path) {
188
+ const excludedPrefixes = [
189
+ "/_next/",
190
+ "/_nuxt/",
191
+ "/_astro/",
192
+ "/_app/",
193
+ "/@vite/",
194
+ "/@fs/",
195
+ "/@id/",
196
+ "/node_modules/",
197
+ "/_vercel/",
198
+ ];
199
+ const excludedSuffixes = [
200
+ ".ico",
201
+ ".png",
202
+ ".jpg",
203
+ ".jpeg",
204
+ ".gif",
205
+ ".webp",
206
+ ".svg",
207
+ ".bmp",
208
+ ".tiff",
209
+ ".avif",
210
+ ".css",
211
+ ".js",
212
+ ".mjs",
213
+ ".ts",
214
+ ".jsx",
215
+ ".tsx",
216
+ ".map",
217
+ ".woff",
218
+ ".woff2",
219
+ ".ttf",
220
+ ".otf",
221
+ ".eot",
222
+ ".mp3",
223
+ ".mp4",
224
+ ".webm",
225
+ ".wav",
226
+ ".ogg",
227
+ ".mov",
228
+ ".avi",
229
+ ".flv",
230
+ ".m4v",
231
+ ".rss",
232
+ ".json",
233
+ ".xml",
234
+ ".pdf",
235
+ ".zip",
236
+ ];
237
+ return excludedPrefixes.some((excludedPrefix) => {
238
+ return path.toLowerCase().startsWith(excludedPrefix.toLowerCase());
239
+ }) || excludedSuffixes.some((excludedSuffix) => {
240
+ return path.toLowerCase().endsWith(excludedSuffix.toLowerCase());
241
+ });
242
+ }
118
243
  filterHeaders(headers) {
119
244
  const excludedHeaders = new Set([
120
245
  "authorization",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@knownagents/sdk",
3
- "version": "1.9.0",
3
+ "version": "1.11.0",
4
4
  "description": "The official Node.js SDK for Known Agents: AI agent analytics (bot traffic), LLM referral tracking, automatic robots.txt, agent verification",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -52,7 +52,7 @@
52
52
  "node": ">=18"
53
53
  },
54
54
  "devDependencies": {
55
- "@types/node": "^22.13.10",
55
+ "@types/node": "^22.19.17",
56
56
  "typescript": "^5.8.2"
57
57
  }
58
58
  }
package/src/index.ts CHANGED
@@ -1,36 +1,84 @@
1
1
  import { IncomingMessage, ServerResponse } from "http"
2
2
 
3
- const NODE_PACKAGE_VERSION = "1.9.0"
4
-
3
+ /**
4
+ * A framework-agnostic HTTP request interface.
5
+ * Used as a convenience type for single-request methods.
6
+ */
5
7
  export interface Request {
6
- /** The URL of the request, including the path and query string (e.g. "/about?foo=bar") */
8
+ /** The URL path and query string (e.g. "/about?foo=bar") */
7
9
  path: string
8
- /** The request's HTTP method (e.g. "GET", "POST") */
10
+ /** The HTTP method (e.g. "GET", "POST") */
9
11
  method: string
10
- /** The request's HTTP headers */
12
+ /** The HTTP request headers */
11
13
  headers: Record<string, string | string[] | undefined>
12
14
  }
13
15
 
16
+ /**
17
+ * A minimal HTTP response interface.
18
+ * Used as a convenience type for single-request methods.
19
+ */
14
20
  export interface Response {
15
- /** The HTTP response status code */
21
+ /** The HTTP response status code (e.g. 200, 404) */
16
22
  statusCode: number
23
+ /** The HTTP response headers */
24
+ headers?: Record<string, string | string[] | undefined>
17
25
  }
18
26
 
19
27
  /**
20
- * The result of an agent verification check.
28
+ * A visit tracking request for the Known Agents API.
29
+ * Used for batch visit tracking with `trackVisits()`.
21
30
  */
22
- export interface VerificationResult {
23
- /** The verification result */
31
+ export interface VisitRequest {
32
+ /** The URL path of the request (e.g. "/about?foo=bar") */
33
+ request_path: string
34
+ /** The HTTP method (e.g. "GET", "POST") */
35
+ request_method: string
36
+ /** The HTTP request headers */
37
+ request_headers: Record<string, string | string[] | undefined>
38
+ /** The HTTP response status code (e.g. 200, 404) */
39
+ response_status_code?: number
40
+ /** The HTTP response headers */
41
+ response_headers?: Record<string, string | string[] | undefined>
42
+ /** The response duration in milliseconds */
43
+ response_duration_in_milliseconds?: number
44
+ /** The timestamp when the visit occurred (ISO 8601 format) */
45
+ created?: string
46
+ }
47
+
48
+ /**
49
+ * An agent identification request for the Known Agents API.
50
+ * Used for batch agent identification with `identifyAgents()`.
51
+ */
52
+ export interface IdentificationRequest {
53
+ /** An identifier that will be echoed back in the response to match requests with results */
54
+ id?: string
55
+ /** The HTTP request headers */
56
+ request_headers: Record<string, string | string[] | undefined>
57
+ }
58
+
59
+ /**
60
+ * The result of an agent identification request.
61
+ */
62
+ export interface IdentificationResult {
63
+ /** The identifier from the request (if provided) */
64
+ id?: string
65
+ /**
66
+ * The identification result:
67
+ * - "verified": The agent was identified and verified
68
+ * - "verification_failed": The agent was identified but failed verification (spoofed)
69
+ * - "unknown_agent": The request is from an unrecognized agent or human
70
+ * - "not_verifiable": The agent was identified but cannot be verified
71
+ */
24
72
  result: "verified" | "verification_failed" | "unknown_agent" | "not_verifiable"
25
- /** The unique ID of the agent (if identified) */
73
+ /** The unique ID of the identified agent */
26
74
  agent_id?: string
27
- /** The name of the agent (e.g. "Googlebot") (if identified) */
75
+ /** The name of the identified agent (e.g. "Googlebot") */
28
76
  agent_token?: string
29
- /** The documentation URL of the agent (if identified) */
77
+ /** The documentation URL for the identified agent */
30
78
  agent_url?: string
31
- /** The type of agent (e.g. "AI Agent") (if identified) */
79
+ /** The type of the identified agent (e.g. "AI Agent", "Search Engine Crawler") */
32
80
  agent_type_name?: string
33
- /** The company behind the agent (e.g. "Google") (if identified) */
81
+ /** The company behind the identified agent (e.g. "Google") */
34
82
  operator_name?: string
35
83
  }
36
84
 
@@ -40,6 +88,8 @@ export interface VerificationResult {
40
88
  export enum AgentType {
41
89
  AIAgent = "AI Agent",
42
90
  AIAssistant = "AI Assistant",
91
+ AICodingAgent = "AI Coding Agent",
92
+ AIDataProvider = "AI Data Provider",
43
93
  AIDataScraper = "AI Data Scraper",
44
94
  AISearchCrawler = "AI Search Crawler",
45
95
  Archiver = "Archiver",
@@ -67,13 +117,21 @@ export class KnownAgents {
67
117
  }
68
118
 
69
119
  /**
70
- * Tracks an agent visit in Known Agents agent analytics.
120
+ * Tracks a single agent visit for analytics.
121
+ * This method is non-blocking and handles errors internally.
71
122
  *
72
- * @param request - The incoming request.
73
- * @param response - The outgoing response (optional).
74
- * @param responseDurationInMilliseconds - The response duration in milliseconds (optional).
123
+ * @param request - The incoming HTTP request (Request or Node.js IncomingMessage).
124
+ * @param response - The outgoing HTTP response (optional).
125
+ * @param responseDurationInMilliseconds - The time taken to process the request in milliseconds (optional).
75
126
  */
76
127
  trackVisit(request: Request | IncomingMessage, response?: Response | ServerResponse, responseDurationInMilliseconds?: number): void {
128
+ const path = "path" in request ? request.path : request.url
129
+ const responseHeaders = response instanceof ServerResponse ? response.getHeaders() as Record<string, string | string[] | undefined> : response?.headers
130
+
131
+ if (!path || this.isPathExcluded(path)) {
132
+ return
133
+ }
134
+
77
135
  fetch("https://api.knownagents.com/visits", {
78
136
  method: "POST",
79
137
  headers: {
@@ -81,27 +139,64 @@ export class KnownAgents {
81
139
  "Content-Type": "application/json"
82
140
  },
83
141
  body: JSON.stringify({
84
- request_path: "path" in request ? request.path : request.url,
142
+ request_path: path,
85
143
  request_method: request.method,
86
144
  request_headers: this.filterHeaders(request.headers),
87
145
  response_status_code: response?.statusCode,
146
+ response_headers: responseHeaders ? this.filterHeaders(responseHeaders) : undefined,
88
147
  response_duration_in_milliseconds: responseDurationInMilliseconds,
89
- node_package_version: NODE_PACKAGE_VERSION,
90
148
  created: new Date().toISOString()
91
149
  })
92
150
  }).catch(error => {
93
151
  console.error(`Known Agents failed to track visit: ${error.message}`)
94
152
  })
95
153
  }
154
+
155
+ /**
156
+ * Tracks multiple agent visits in a batch for analytics.
157
+ * This method is non-blocking and handles errors internally.
158
+ * Recommended for high-traffic websites - batch visits and send periodically (e.g. every 30 seconds).
159
+ *
160
+ * @param visits - An array of visit tracking requests.
161
+ */
162
+ trackVisits(visits: VisitRequest[]): void {
163
+ const filteredVisits = visits
164
+ .filter((visit) => {
165
+ return !this.isPathExcluded(visit.request_path)
166
+ })
167
+ .map((visit) => {
168
+ return {
169
+ ...visit,
170
+ request_headers: this.filterHeaders(visit.request_headers),
171
+ response_headers: visit.response_headers ? this.filterHeaders(visit.response_headers) : undefined,
172
+ }
173
+ })
174
+
175
+ if (filteredVisits.length === 0) {
176
+ return
177
+ }
178
+
179
+ fetch("https://api.knownagents.com/visits", {
180
+ method: "POST",
181
+ headers: {
182
+ "Authorization": `Bearer ${this.accessToken}`,
183
+ "Content-Type": "application/json"
184
+ },
185
+ body: JSON.stringify(filteredVisits)
186
+ }).catch(error => {
187
+ console.error(`Known Agents failed to track visits: ${error.message}`)
188
+ })
189
+ }
96
190
 
97
191
  /**
98
- * Generates a `robots.txt` file that disallows the specified agent types.
99
- * Cache and serve this string at your website’s `/robots.txt` endpoint.
192
+ * Generates a robots.txt file that disallows the specified agent types.
193
+ * The generated file stays up-to-date with all current and future agents in the specified categories.
194
+ * Cache and serve the result at your website's `/robots.txt` endpoint.
100
195
  *
101
- * @param agentTypes - A list of agent types to include.
102
- * @param disallow - A path to disallow (default is "/" for all paths).
103
- * @returns The generated `robots.txt` as a string.
104
- * @throws If the API call fails or returns a non-200 status.
196
+ * @param agentTypes - An array of agent types to disallow.
197
+ * @param disallow - The path to disallow (default: "/" for all paths).
198
+ * @returns A promise that resolves to the generated robots.txt content as a string.
199
+ * @throws {Error} If the API call fails or returns a non-200 status.
105
200
  */
106
201
  async generateRobotsTXT(agentTypes: AgentType[], disallow: string = "/"): Promise<string> {
107
202
  const response = await fetch("https://api.knownagents.com/robots-txts", {
@@ -112,8 +207,7 @@ export class KnownAgents {
112
207
  },
113
208
  body: JSON.stringify({
114
209
  agent_types: agentTypes,
115
- disallow: disallow,
116
- node_package_version: NODE_PACKAGE_VERSION
210
+ disallow: disallow
117
211
  })
118
212
  })
119
213
 
@@ -125,35 +219,123 @@ export class KnownAgents {
125
219
  }
126
220
 
127
221
  /**
128
- * Verifies if an agent request is legitimate by checking it against Known Agents.
222
+ * Identifies and verifies a single agent from an HTTP request.
223
+ * Uses Web Bot Auth (HTTP message signatures), IP matching, or other available methods.
129
224
  *
130
- * @param request - The incoming request.
131
- * @returns A promise that resolves to the verification result.
132
- * @throws If the API call fails or returns a non-200 status.
225
+ * @param request - The incoming HTTP request (Request or Node.js IncomingMessage).
226
+ * @returns A promise that resolves to the identification result.
227
+ * @throws {Error} If the API call fails or returns a non-200 status.
133
228
  */
134
- async verifyAgent(request: Request | IncomingMessage): Promise<VerificationResult> {
135
- const response = await fetch("https://api.knownagents.com/agent-verifications", {
229
+ async identifyAgent(request: Request | IncomingMessage): Promise<IdentificationResult> {
230
+ const response = await fetch("https://api.knownagents.com/agent-identifications", {
136
231
  method: "POST",
137
232
  headers: {
138
233
  "Authorization": `Bearer ${this.accessToken}`,
139
234
  "Content-Type": "application/json"
140
235
  },
141
236
  body: JSON.stringify({
142
- request_path: "path" in request ? request.path : request.url,
143
- request_headers: this.filterHeaders(request.headers),
144
- node_package_version: NODE_PACKAGE_VERSION
237
+ request_headers: this.filterHeaders(request.headers)
145
238
  })
146
239
  })
147
240
 
148
241
  if (response.ok) {
149
242
  return await response.json()
150
243
  } else {
151
- throw new Error(`Known Agents failed to verify agent: ${response.status} ${response.statusText}`)
244
+ throw new Error(`Known Agents failed to identify agent: ${response.status} ${response.statusText}`)
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Identifies and verifies multiple agents from HTTP requests in a batch.
250
+ * Uses Web Bot Auth (HTTP message signatures), IP matching, or other available methods.
251
+ *
252
+ * @param requests - An array of identification requests.
253
+ * @returns A promise that resolves to an array of identification results.
254
+ * @throws {Error} If the API call fails or returns a non-200 status.
255
+ */
256
+ async identifyAgents(requests: IdentificationRequest[]): Promise<IdentificationResult[]> {
257
+ const response = await fetch("https://api.knownagents.com/agent-identifications", {
258
+ method: "POST",
259
+ headers: {
260
+ "Authorization": `Bearer ${this.accessToken}`,
261
+ "Content-Type": "application/json"
262
+ },
263
+ body: JSON.stringify(requests.map(request => {
264
+ return {
265
+ ...request,
266
+ request_headers: this.filterHeaders(request.request_headers),
267
+ }
268
+ }))
269
+ })
270
+
271
+ if (response.ok) {
272
+ return await response.json()
273
+ } else {
274
+ throw new Error(`Known Agents failed to identify agents: ${response.status} ${response.statusText}`)
152
275
  }
153
276
  }
154
277
 
155
278
  // Helpers
156
279
 
280
+ private isPathExcluded(path: string): boolean {
281
+ const excludedPrefixes = [
282
+ "/_next/",
283
+ "/_nuxt/",
284
+ "/_astro/",
285
+ "/_app/",
286
+ "/@vite/",
287
+ "/@fs/",
288
+ "/@id/",
289
+ "/node_modules/",
290
+ "/_vercel/",
291
+ ]
292
+
293
+ const excludedSuffixes = [
294
+ ".ico",
295
+ ".png",
296
+ ".jpg",
297
+ ".jpeg",
298
+ ".gif",
299
+ ".webp",
300
+ ".svg",
301
+ ".bmp",
302
+ ".tiff",
303
+ ".avif",
304
+ ".css",
305
+ ".js",
306
+ ".mjs",
307
+ ".ts",
308
+ ".jsx",
309
+ ".tsx",
310
+ ".map",
311
+ ".woff",
312
+ ".woff2",
313
+ ".ttf",
314
+ ".otf",
315
+ ".eot",
316
+ ".mp3",
317
+ ".mp4",
318
+ ".webm",
319
+ ".wav",
320
+ ".ogg",
321
+ ".mov",
322
+ ".avi",
323
+ ".flv",
324
+ ".m4v",
325
+ ".rss",
326
+ ".json",
327
+ ".xml",
328
+ ".pdf",
329
+ ".zip",
330
+ ]
331
+
332
+ return excludedPrefixes.some((excludedPrefix) => {
333
+ return path.toLowerCase().startsWith(excludedPrefix.toLowerCase())
334
+ }) || excludedSuffixes.some((excludedSuffix) => {
335
+ return path.toLowerCase().endsWith(excludedSuffix.toLowerCase())
336
+ })
337
+ }
338
+
157
339
  private filterHeaders(headers: Record<string, string | string[] | undefined>): Record<string, string | string[] | undefined> {
158
340
  const excludedHeaders = new Set([
159
341
  "authorization",
package/tsconfig.json CHANGED
@@ -4,12 +4,13 @@
4
4
  "target": "ES2020",
5
5
  "module": "CommonJS",
6
6
  "outDir": "dist",
7
+ "rootDir": "src",
7
8
  "declaration": true,
8
9
  "declarationMap": true,
9
10
  "esModuleInterop": true,
10
11
  "forceConsistentCasingInFileNames": true,
11
12
  "strict": true,
12
13
  "skipLibCheck": true,
13
- "moduleResolution": "node"
14
+ "types": ["node"]
14
15
  }
15
16
  }