@kya-os/agentshield-nextjs 0.2.9 → 0.2.11

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/dist/index.js CHANGED
@@ -2086,6 +2086,70 @@ var AgentShieldClient = class {
2086
2086
  action: result.data.decision.action
2087
2087
  };
2088
2088
  }
2089
+ /**
2090
+ * Check if this client is using edge detection (Gateway Worker)
2091
+ */
2092
+ isUsingEdge() {
2093
+ return this.useEdge;
2094
+ }
2095
+ /**
2096
+ * Log a detection result to AgentShield database.
2097
+ * Use after Gateway Worker detection to persist results.
2098
+ * Fire-and-forget - returns immediately without waiting for DB write.
2099
+ *
2100
+ * @example
2101
+ * ```typescript
2102
+ * // After receiving Gateway response
2103
+ * if (client.isUsingEdge() && response.data?.detection) {
2104
+ * client.logDetection({
2105
+ * detection: response.data.detection,
2106
+ * context: { userAgent, ipAddress, path, url, method }
2107
+ * }).catch(err => console.error('Log failed:', err));
2108
+ * }
2109
+ * ```
2110
+ */
2111
+ async logDetection(input) {
2112
+ const logEndpoint = this.useEdge ? `${DEFAULT_BASE_URL}/api/v1/log-detection` : `${this.baseUrl}/api/v1/log-detection`;
2113
+ try {
2114
+ const controller = new AbortController();
2115
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
2116
+ try {
2117
+ const response = await fetch(logEndpoint, {
2118
+ method: "POST",
2119
+ headers: {
2120
+ "Content-Type": "application/json",
2121
+ Authorization: `Bearer ${this.apiKey}`
2122
+ },
2123
+ body: JSON.stringify({
2124
+ detection: {
2125
+ isAgent: input.detection.isAgent,
2126
+ confidence: input.detection.confidence,
2127
+ agentName: input.detection.agentName,
2128
+ agentType: input.detection.agentType,
2129
+ detectionClass: input.detection.detectionClass,
2130
+ verificationMethod: input.detection.verificationMethod,
2131
+ reasons: input.detection.reasons
2132
+ },
2133
+ context: input.context,
2134
+ source: input.source || "gateway"
2135
+ }),
2136
+ signal: controller.signal
2137
+ });
2138
+ clearTimeout(timeoutId);
2139
+ if (!response.ok && this.debug) {
2140
+ console.warn("[AgentShield] Log detection returned non-2xx:", response.status);
2141
+ }
2142
+ } catch (error) {
2143
+ clearTimeout(timeoutId);
2144
+ throw error;
2145
+ }
2146
+ } catch (error) {
2147
+ if (this.debug) {
2148
+ console.error("[AgentShield] Log detection failed:", error);
2149
+ }
2150
+ throw error;
2151
+ }
2152
+ }
2089
2153
  };
2090
2154
  var clientInstance = null;
2091
2155
  function getAgentShieldClient(config) {
@@ -2132,16 +2196,21 @@ function shouldIncludePath(path, includePaths) {
2132
2196
  }
2133
2197
  function buildBlockedResponse(decision, config) {
2134
2198
  const status = config.blockedResponse?.status ?? 403;
2135
- const message = config.blockedResponse?.message ?? decision.message ?? "Access denied";
2136
- const response = server.NextResponse.json(
2137
- {
2138
- error: message,
2139
- code: "AGENT_BLOCKED",
2140
- reason: decision.reason,
2141
- agentType: decision.agentType
2142
- },
2143
- { status }
2144
- );
2199
+ const redirectUrl = config.redirectUrl || decision.redirectUrl;
2200
+ const baseMessage = config.blockedResponse?.message ?? decision.message ?? "Access denied";
2201
+ const errorMessage = redirectUrl ? `${baseMessage}. Please go to ${redirectUrl}` : baseMessage;
2202
+ const message = config.blockedResponse?.message ?? decision.message ?? (redirectUrl ? `AI agents are not permitted on this resource. Please go to ${redirectUrl} for more information.` : "AI agents are not permitted on this resource.");
2203
+ const responseBody = {
2204
+ error: errorMessage,
2205
+ code: "AGENT_BLOCKED",
2206
+ reason: decision.reason,
2207
+ agentType: decision.agentType,
2208
+ message
2209
+ };
2210
+ if (redirectUrl) {
2211
+ responseBody.redirectUrl = redirectUrl;
2212
+ }
2213
+ const response = server.NextResponse.json(responseBody, { status });
2145
2214
  if (config.blockedResponse?.headers) {
2146
2215
  for (const [key, value] of Object.entries(config.blockedResponse.headers)) {
2147
2216
  response.headers.set(key, value);
@@ -2149,6 +2218,9 @@ function buildBlockedResponse(decision, config) {
2149
2218
  }
2150
2219
  response.headers.set("X-AgentShield-Action", decision.action);
2151
2220
  response.headers.set("X-AgentShield-Reason", decision.reason);
2221
+ if (redirectUrl) {
2222
+ response.headers.set("X-AgentShield-Redirect", redirectUrl);
2223
+ }
2152
2224
  return response;
2153
2225
  }
2154
2226
  function buildRedirectResponse(request, decision, config) {
@@ -2193,16 +2265,20 @@ function withAgentShield(config = {}) {
2193
2265
  return server.NextResponse.next();
2194
2266
  }
2195
2267
  try {
2196
- const result = await getClient().enforce({
2268
+ const client2 = getClient();
2269
+ const userAgent = request.headers.get("user-agent") || void 0;
2270
+ const ipAddress = request.ip || request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip") || void 0;
2271
+ const result = await client2.enforce({
2197
2272
  headers: Object.fromEntries(request.headers.entries()),
2198
- userAgent: request.headers.get("user-agent") || void 0,
2199
- ipAddress: request.ip || request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip") || void 0,
2273
+ userAgent,
2274
+ ipAddress,
2200
2275
  path,
2201
2276
  url: request.url,
2202
2277
  method: request.method,
2203
2278
  requestId: request.headers.get("x-request-id") || void 0,
2204
2279
  options: {
2205
- includeDetectionResult: config.debug
2280
+ // Always include detection results for logging (needed when using edge)
2281
+ includeDetectionResult: true
2206
2282
  }
2207
2283
  });
2208
2284
  if (!result.success || !result.data) {
@@ -2229,6 +2305,16 @@ function withAgentShield(config = {}) {
2229
2305
  processingTimeMs: Date.now() - startTime
2230
2306
  });
2231
2307
  }
2308
+ if (client2.isUsingEdge() && result.data.detection) {
2309
+ client2.logDetection({
2310
+ detection: result.data.detection,
2311
+ context: { userAgent, ipAddress, path, url: request.url, method: request.method }
2312
+ }).catch((err) => {
2313
+ if (config.debug) {
2314
+ console.error("[AgentShield] Log detection failed:", err);
2315
+ }
2316
+ });
2317
+ }
2232
2318
  if (decision.isAgent && config.onAgentDetected) {
2233
2319
  await config.onAgentDetected(request, decision);
2234
2320
  }