@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.mjs CHANGED
@@ -2065,6 +2065,70 @@ var AgentShieldClient = class {
2065
2065
  action: result.data.decision.action
2066
2066
  };
2067
2067
  }
2068
+ /**
2069
+ * Check if this client is using edge detection (Gateway Worker)
2070
+ */
2071
+ isUsingEdge() {
2072
+ return this.useEdge;
2073
+ }
2074
+ /**
2075
+ * Log a detection result to AgentShield database.
2076
+ * Use after Gateway Worker detection to persist results.
2077
+ * Fire-and-forget - returns immediately without waiting for DB write.
2078
+ *
2079
+ * @example
2080
+ * ```typescript
2081
+ * // After receiving Gateway response
2082
+ * if (client.isUsingEdge() && response.data?.detection) {
2083
+ * client.logDetection({
2084
+ * detection: response.data.detection,
2085
+ * context: { userAgent, ipAddress, path, url, method }
2086
+ * }).catch(err => console.error('Log failed:', err));
2087
+ * }
2088
+ * ```
2089
+ */
2090
+ async logDetection(input) {
2091
+ const logEndpoint = this.useEdge ? `${DEFAULT_BASE_URL}/api/v1/log-detection` : `${this.baseUrl}/api/v1/log-detection`;
2092
+ try {
2093
+ const controller = new AbortController();
2094
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
2095
+ try {
2096
+ const response = await fetch(logEndpoint, {
2097
+ method: "POST",
2098
+ headers: {
2099
+ "Content-Type": "application/json",
2100
+ Authorization: `Bearer ${this.apiKey}`
2101
+ },
2102
+ body: JSON.stringify({
2103
+ detection: {
2104
+ isAgent: input.detection.isAgent,
2105
+ confidence: input.detection.confidence,
2106
+ agentName: input.detection.agentName,
2107
+ agentType: input.detection.agentType,
2108
+ detectionClass: input.detection.detectionClass,
2109
+ verificationMethod: input.detection.verificationMethod,
2110
+ reasons: input.detection.reasons
2111
+ },
2112
+ context: input.context,
2113
+ source: input.source || "gateway"
2114
+ }),
2115
+ signal: controller.signal
2116
+ });
2117
+ clearTimeout(timeoutId);
2118
+ if (!response.ok && this.debug) {
2119
+ console.warn("[AgentShield] Log detection returned non-2xx:", response.status);
2120
+ }
2121
+ } catch (error) {
2122
+ clearTimeout(timeoutId);
2123
+ throw error;
2124
+ }
2125
+ } catch (error) {
2126
+ if (this.debug) {
2127
+ console.error("[AgentShield] Log detection failed:", error);
2128
+ }
2129
+ throw error;
2130
+ }
2131
+ }
2068
2132
  };
2069
2133
  var clientInstance = null;
2070
2134
  function getAgentShieldClient(config) {
@@ -2111,16 +2175,21 @@ function shouldIncludePath(path, includePaths) {
2111
2175
  }
2112
2176
  function buildBlockedResponse(decision, config) {
2113
2177
  const status = config.blockedResponse?.status ?? 403;
2114
- const message = config.blockedResponse?.message ?? decision.message ?? "Access denied";
2115
- const response = NextResponse.json(
2116
- {
2117
- error: message,
2118
- code: "AGENT_BLOCKED",
2119
- reason: decision.reason,
2120
- agentType: decision.agentType
2121
- },
2122
- { status }
2123
- );
2178
+ const redirectUrl = config.redirectUrl || decision.redirectUrl;
2179
+ const baseMessage = config.blockedResponse?.message ?? decision.message ?? "Access denied";
2180
+ const errorMessage = redirectUrl ? `${baseMessage}. Please go to ${redirectUrl}` : baseMessage;
2181
+ 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.");
2182
+ const responseBody = {
2183
+ error: errorMessage,
2184
+ code: "AGENT_BLOCKED",
2185
+ reason: decision.reason,
2186
+ agentType: decision.agentType,
2187
+ message
2188
+ };
2189
+ if (redirectUrl) {
2190
+ responseBody.redirectUrl = redirectUrl;
2191
+ }
2192
+ const response = NextResponse.json(responseBody, { status });
2124
2193
  if (config.blockedResponse?.headers) {
2125
2194
  for (const [key, value] of Object.entries(config.blockedResponse.headers)) {
2126
2195
  response.headers.set(key, value);
@@ -2128,6 +2197,9 @@ function buildBlockedResponse(decision, config) {
2128
2197
  }
2129
2198
  response.headers.set("X-AgentShield-Action", decision.action);
2130
2199
  response.headers.set("X-AgentShield-Reason", decision.reason);
2200
+ if (redirectUrl) {
2201
+ response.headers.set("X-AgentShield-Redirect", redirectUrl);
2202
+ }
2131
2203
  return response;
2132
2204
  }
2133
2205
  function buildRedirectResponse(request, decision, config) {
@@ -2172,16 +2244,20 @@ function withAgentShield(config = {}) {
2172
2244
  return NextResponse.next();
2173
2245
  }
2174
2246
  try {
2175
- const result = await getClient().enforce({
2247
+ const client2 = getClient();
2248
+ const userAgent = request.headers.get("user-agent") || void 0;
2249
+ const ipAddress = request.ip || request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip") || void 0;
2250
+ const result = await client2.enforce({
2176
2251
  headers: Object.fromEntries(request.headers.entries()),
2177
- userAgent: request.headers.get("user-agent") || void 0,
2178
- ipAddress: request.ip || request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip") || void 0,
2252
+ userAgent,
2253
+ ipAddress,
2179
2254
  path,
2180
2255
  url: request.url,
2181
2256
  method: request.method,
2182
2257
  requestId: request.headers.get("x-request-id") || void 0,
2183
2258
  options: {
2184
- includeDetectionResult: config.debug
2259
+ // Always include detection results for logging (needed when using edge)
2260
+ includeDetectionResult: true
2185
2261
  }
2186
2262
  });
2187
2263
  if (!result.success || !result.data) {
@@ -2208,6 +2284,16 @@ function withAgentShield(config = {}) {
2208
2284
  processingTimeMs: Date.now() - startTime
2209
2285
  });
2210
2286
  }
2287
+ if (client2.isUsingEdge() && result.data.detection) {
2288
+ client2.logDetection({
2289
+ detection: result.data.detection,
2290
+ context: { userAgent, ipAddress, path, url: request.url, method: request.method }
2291
+ }).catch((err) => {
2292
+ if (config.debug) {
2293
+ console.error("[AgentShield] Log detection failed:", err);
2294
+ }
2295
+ });
2296
+ }
2211
2297
  if (decision.isAgent && config.onAgentDetected) {
2212
2298
  await config.onAgentDetected(request, decision);
2213
2299
  }