@kya-os/agentshield-nextjs 0.2.6 → 0.2.8

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
@@ -1,4 +1,5 @@
1
- import { loadRulesSync, mapVerificationMethod } from '@kya-os/agentshield-shared';
1
+ import { loadRulesSync, mapVerificationMethod, createEvaluationContext, evaluatePolicy, ENFORCEMENT_ACTIONS, PolicyConfigSchema, DEFAULT_POLICY, matchPath as matchPath$1, createPolicyFetcher } from '@kya-os/agentshield-shared';
2
+ export { DEFAULT_POLICY, ENFORCEMENT_ACTIONS, createEvaluationContext, evaluatePolicy } from '@kya-os/agentshield-shared';
2
3
  import { NextResponse } from 'next/server';
3
4
  import * as ed25519 from '@noble/ed25519';
4
5
  import { sha512 } from '@noble/hashes/sha2.js';
@@ -2255,6 +2256,158 @@ function withAgentShield(config = {}) {
2255
2256
  };
2256
2257
  }
2257
2258
  var agentShieldMiddleware = withAgentShield();
2259
+ function createContextFromDetection(detection, request) {
2260
+ return createEvaluationContext({
2261
+ agentType: detection.detectedAgent?.type,
2262
+ agentName: detection.detectedAgent?.name,
2263
+ agentVendor: detection.detectedAgent?.vendor,
2264
+ confidence: detection.confidence,
2265
+ riskLevel: detection.riskLevel,
2266
+ path: request.nextUrl.pathname,
2267
+ method: request.method,
2268
+ signatureVerified: detection.verificationMethod === "signature",
2269
+ isAuthenticated: false,
2270
+ // TODO: integrate with auth
2271
+ userAgent: request.headers.get("user-agent") || void 0
2272
+ });
2273
+ }
2274
+ function evaluatePolicyForDetection(detection, request, policy) {
2275
+ const context = createContextFromDetection(detection, request);
2276
+ return evaluatePolicy(policy, context);
2277
+ }
2278
+ function buildBlockedResponse2(decision, config) {
2279
+ const status = config.blockedResponse?.status ?? 403;
2280
+ const message = config.blockedResponse?.message ?? decision.message ?? "Access denied";
2281
+ const response = NextResponse.json(
2282
+ {
2283
+ error: message,
2284
+ code: "POLICY_BLOCKED",
2285
+ reason: decision.reason,
2286
+ ruleId: decision.ruleId,
2287
+ matchType: decision.matchType
2288
+ },
2289
+ { status }
2290
+ );
2291
+ if (config.blockedResponse?.headers) {
2292
+ for (const [key, value] of Object.entries(config.blockedResponse.headers)) {
2293
+ response.headers.set(key, value);
2294
+ }
2295
+ }
2296
+ response.headers.set("X-AgentShield-Action", decision.action);
2297
+ response.headers.set("X-AgentShield-Reason", decision.reason);
2298
+ response.headers.set("X-AgentShield-MatchType", decision.matchType);
2299
+ return response;
2300
+ }
2301
+ function buildRedirectResponse2(request, decision, config) {
2302
+ const redirectUrl = decision.redirectUrl || config.redirectUrl || "/blocked";
2303
+ const url = new URL(redirectUrl, request.url);
2304
+ url.searchParams.set("reason", decision.reason);
2305
+ if (decision.ruleId) {
2306
+ url.searchParams.set("ruleId", decision.ruleId);
2307
+ }
2308
+ return NextResponse.redirect(url);
2309
+ }
2310
+ function buildChallengeResponse(request, decision, config) {
2311
+ return buildRedirectResponse2(request, decision, config);
2312
+ }
2313
+ async function handlePolicyDecision(request, decision, config) {
2314
+ switch (decision.action) {
2315
+ case ENFORCEMENT_ACTIONS.BLOCK:
2316
+ if (config.customBlockedResponse) {
2317
+ return await config.customBlockedResponse(request, decision);
2318
+ }
2319
+ return buildBlockedResponse2(decision, config);
2320
+ case ENFORCEMENT_ACTIONS.REDIRECT:
2321
+ return buildRedirectResponse2(request, decision, config);
2322
+ case ENFORCEMENT_ACTIONS.CHALLENGE:
2323
+ return buildChallengeResponse(request, decision, config);
2324
+ case ENFORCEMENT_ACTIONS.LOG:
2325
+ console.log("[AgentShield] Policy decision (log):", {
2326
+ path: request.nextUrl.pathname,
2327
+ action: decision.action,
2328
+ reason: decision.reason,
2329
+ matchType: decision.matchType,
2330
+ ruleId: decision.ruleId
2331
+ });
2332
+ return null;
2333
+ // Continue to allow
2334
+ case ENFORCEMENT_ACTIONS.ALLOW:
2335
+ default:
2336
+ return null;
2337
+ }
2338
+ }
2339
+ var fetcherCache = /* @__PURE__ */ new Map();
2340
+ function getFetcherCacheKey(config) {
2341
+ return `${config.apiUrl ?? "default"}:${config.apiKey ?? ""}:${config.cacheTtlSeconds ?? "default"}`;
2342
+ }
2343
+ function getPolicyFetcher(config) {
2344
+ if (!config) {
2345
+ throw new Error("fetchPolicy config required");
2346
+ }
2347
+ const cacheKey = getFetcherCacheKey(config);
2348
+ let fetcher = fetcherCache.get(cacheKey);
2349
+ if (!fetcher) {
2350
+ const fetcherConfig = {
2351
+ apiBaseUrl: config.apiUrl || "https://kya.vouched.id",
2352
+ apiKey: config.apiKey,
2353
+ cacheTtlSeconds: config.cacheTtlSeconds
2354
+ };
2355
+ fetcher = createPolicyFetcher(fetcherConfig);
2356
+ fetcherCache.set(cacheKey, fetcher);
2357
+ }
2358
+ return fetcher;
2359
+ }
2360
+ async function getPolicy(config) {
2361
+ if (config.policy) {
2362
+ return PolicyConfigSchema.parse({ ...DEFAULT_POLICY, ...config.policy });
2363
+ }
2364
+ if (config.fetchPolicy) {
2365
+ try {
2366
+ const fetcher = getPolicyFetcher(config.fetchPolicy);
2367
+ return await fetcher.getPolicy(config.fetchPolicy.projectId);
2368
+ } catch (error) {
2369
+ if (config.debug) {
2370
+ console.warn("[AgentShield] Policy fetch failed, using fallback:", error);
2371
+ }
2372
+ return PolicyConfigSchema.parse({
2373
+ ...DEFAULT_POLICY,
2374
+ ...config.fallbackPolicy || {}
2375
+ });
2376
+ }
2377
+ }
2378
+ return PolicyConfigSchema.parse(DEFAULT_POLICY);
2379
+ }
2380
+ async function applyPolicy(request, detection, config) {
2381
+ try {
2382
+ const path = request.nextUrl.pathname;
2383
+ if (config.skipPaths?.some((pattern) => matchPath$1(path, pattern))) {
2384
+ return null;
2385
+ }
2386
+ if (config.includePaths && config.includePaths.length > 0) {
2387
+ if (!config.includePaths.some((pattern) => matchPath$1(path, pattern))) {
2388
+ return null;
2389
+ }
2390
+ }
2391
+ const policy = await getPolicy(config);
2392
+ const context = createContextFromDetection(detection, request);
2393
+ const decision = evaluatePolicy(policy, context);
2394
+ if (config.onPolicyDecision) {
2395
+ await config.onPolicyDecision(request, decision, context);
2396
+ }
2397
+ return await handlePolicyDecision(request, decision, config);
2398
+ } catch (error) {
2399
+ if (config.debug) {
2400
+ console.error("[AgentShield] Policy evaluation error:", error);
2401
+ }
2402
+ if (config.failOpen !== false) {
2403
+ return null;
2404
+ }
2405
+ return NextResponse.json(
2406
+ { error: "Security check failed", code: "POLICY_ERROR" },
2407
+ { status: 503 }
2408
+ );
2409
+ }
2410
+ }
2258
2411
 
2259
2412
  // src/index.ts
2260
2413
  var VERSION = "0.1.0";
@@ -2264,6 +2417,6 @@ var VERSION = "0.1.0";
2264
2417
  * @license MIT OR Apache-2.0
2265
2418
  */
2266
2419
 
2267
- export { AgentShieldClient, EdgeSessionTracker, StatelessSessionChecker, VERSION, agentShieldMiddleware, createAgentShieldMiddleware2 as createAgentShieldMiddleware, createAgentShieldMiddleware as createAgentShieldMiddlewareBase, createEnhancedAgentShieldMiddleware, createAgentShieldMiddleware2 as createMiddleware, getAgentShieldClient, resetAgentShieldClient, withAgentShield };
2420
+ export { AgentShieldClient, EdgeSessionTracker, StatelessSessionChecker, VERSION, agentShieldMiddleware, applyPolicy, buildBlockedResponse2 as buildPolicyBlockedResponse, buildRedirectResponse2 as buildPolicyRedirectResponse, createAgentShieldMiddleware2 as createAgentShieldMiddleware, createAgentShieldMiddleware as createAgentShieldMiddlewareBase, createContextFromDetection, createEnhancedAgentShieldMiddleware, createAgentShieldMiddleware2 as createMiddleware, evaluatePolicyForDetection, getAgentShieldClient, getPolicy, handlePolicyDecision, resetAgentShieldClient, withAgentShield };
2268
2421
  //# sourceMappingURL=index.mjs.map
2269
2422
  //# sourceMappingURL=index.mjs.map