@kya-os/checkpoint-nextjs 1.0.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/CHANGELOG.md +80 -0
- package/EDGE_RUNTIME_WASM_SETUP.md +348 -0
- package/README.md +414 -0
- package/bin/setup-edge-wasm.js +497 -0
- package/dist/.tsbuildinfo +1 -0
- package/dist/adapt.d.mts +39 -0
- package/dist/adapt.d.ts +39 -0
- package/dist/adapt.js +58 -0
- package/dist/adapt.js.map +1 -0
- package/dist/adapt.mjs +56 -0
- package/dist/adapt.mjs.map +1 -0
- package/dist/api-client.d.mts +204 -0
- package/dist/api-client.d.ts +204 -0
- package/dist/api-client.js +206 -0
- package/dist/api-client.js.map +1 -0
- package/dist/api-client.mjs +199 -0
- package/dist/api-client.mjs.map +1 -0
- package/dist/api-middleware.d.mts +156 -0
- package/dist/api-middleware.d.ts +156 -0
- package/dist/api-middleware.js +510 -0
- package/dist/api-middleware.js.map +1 -0
- package/dist/api-middleware.mjs +505 -0
- package/dist/api-middleware.mjs.map +1 -0
- package/dist/create-middleware.d.mts +17 -0
- package/dist/create-middleware.d.ts +17 -0
- package/dist/create-middleware.js +38 -0
- package/dist/create-middleware.js.map +1 -0
- package/dist/create-middleware.mjs +35 -0
- package/dist/create-middleware.mjs.map +1 -0
- package/dist/edge/index.d.mts +110 -0
- package/dist/edge/index.d.ts +110 -0
- package/dist/edge/index.js +277 -0
- package/dist/edge/index.js.map +1 -0
- package/dist/edge/index.mjs +275 -0
- package/dist/edge/index.mjs.map +1 -0
- package/dist/edge-runtime-loader.d.mts +50 -0
- package/dist/edge-runtime-loader.d.ts +50 -0
- package/dist/edge-runtime-loader.js +204 -0
- package/dist/edge-runtime-loader.js.map +1 -0
- package/dist/edge-runtime-loader.mjs +201 -0
- package/dist/edge-runtime-loader.mjs.map +1 -0
- package/dist/edge-wasm-middleware.d.mts +68 -0
- package/dist/edge-wasm-middleware.d.ts +68 -0
- package/dist/edge-wasm-middleware.js +318 -0
- package/dist/edge-wasm-middleware.js.map +1 -0
- package/dist/edge-wasm-middleware.mjs +315 -0
- package/dist/edge-wasm-middleware.mjs.map +1 -0
- package/dist/index.d.mts +25 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +1019 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +979 -0
- package/dist/index.mjs.map +1 -0
- package/dist/middleware-edge.d.mts +46 -0
- package/dist/middleware-edge.d.ts +46 -0
- package/dist/middleware-edge.js +134 -0
- package/dist/middleware-edge.js.map +1 -0
- package/dist/middleware-edge.mjs +129 -0
- package/dist/middleware-edge.mjs.map +1 -0
- package/dist/middleware-node.d.mts +89 -0
- package/dist/middleware-node.d.ts +89 -0
- package/dist/middleware-node.js +127 -0
- package/dist/middleware-node.js.map +1 -0
- package/dist/middleware-node.mjs +124 -0
- package/dist/middleware-node.mjs.map +1 -0
- package/dist/middleware.d.mts +36 -0
- package/dist/middleware.d.ts +36 -0
- package/dist/middleware.js +15 -0
- package/dist/middleware.js.map +1 -0
- package/dist/middleware.mjs +12 -0
- package/dist/middleware.mjs.map +1 -0
- package/dist/nodejs-wasm-loader.d.mts +25 -0
- package/dist/nodejs-wasm-loader.d.ts +25 -0
- package/dist/nodejs-wasm-loader.js +95 -0
- package/dist/nodejs-wasm-loader.js.map +1 -0
- package/dist/nodejs-wasm-loader.mjs +85 -0
- package/dist/nodejs-wasm-loader.mjs.map +1 -0
- package/dist/policy.d.mts +162 -0
- package/dist/policy.d.ts +162 -0
- package/dist/policy.js +189 -0
- package/dist/policy.js.map +1 -0
- package/dist/policy.mjs +165 -0
- package/dist/policy.mjs.map +1 -0
- package/dist/session-tracker.d.mts +55 -0
- package/dist/session-tracker.d.ts +55 -0
- package/dist/session-tracker.js +170 -0
- package/dist/session-tracker.js.map +1 -0
- package/dist/session-tracker.mjs +167 -0
- package/dist/session-tracker.mjs.map +1 -0
- package/dist/signature-verifier.d.mts +33 -0
- package/dist/signature-verifier.d.ts +33 -0
- package/dist/signature-verifier.js +386 -0
- package/dist/signature-verifier.js.map +1 -0
- package/dist/signature-verifier.mjs +362 -0
- package/dist/signature-verifier.mjs.map +1 -0
- package/dist/translate.d.mts +33 -0
- package/dist/translate.d.ts +33 -0
- package/dist/translate.js +38 -0
- package/dist/translate.js.map +1 -0
- package/dist/translate.mjs +36 -0
- package/dist/translate.mjs.map +1 -0
- package/dist/types-C-xCUNTr.d.mts +105 -0
- package/dist/types-C-xCUNTr.d.ts +105 -0
- package/dist/wasm-middleware.d.mts +63 -0
- package/dist/wasm-middleware.d.ts +63 -0
- package/dist/wasm-middleware.js +98 -0
- package/dist/wasm-middleware.js.map +1 -0
- package/dist/wasm-middleware.mjs +95 -0
- package/dist/wasm-middleware.mjs.map +1 -0
- package/dist/wasm-setup.d.mts +46 -0
- package/dist/wasm-setup.d.ts +46 -0
- package/dist/wasm-setup.js +176 -0
- package/dist/wasm-setup.js.map +1 -0
- package/dist/wasm-setup.mjs +167 -0
- package/dist/wasm-setup.mjs.map +1 -0
- package/package.json +156 -0
- package/templates/middleware-wasm-100.ts +153 -0
- package/wasm/agentshield_wasm.d.ts +479 -0
- package/wasm/agentshield_wasm.js +1536 -0
- package/wasm/agentshield_wasm_bg.wasm +0 -0
- package/wasm/package.json +30 -0
- package/wasm.d.ts +21 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adapt.ts","../src/translate.ts","../src/middleware-node.ts"],"names":[],"mappings":";;;;;;AA4CO,SAAS,mBAAA,CAAoB,UAA4B,GAAA,EAAgC;AAC9F,EAAA,MAAM,iBAAA,GAAoB,WAAA,CAAY,GAAA,CAAI,OAAO,CAAA;AACjD,EAAA,MAAM,aAAA,GAAgB,oBAAoB,QAAQ,CAAA;AAClD,EAAA,MAAM,KAAA,GAAQ,qBAAA,CAAsB,QAAA,EAAU,iBAAiB,CAAA;AAE/D,EAAA,QAAQ,KAAA;AAAO,IACb,KAAK,cAAA,EAAgB;AAEnB,MAAA,MAAM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AAAA,IAC3B,UAAU,MAAA,CAAO;AAAA,GACnB;AACF;AAEA,eAAe,gBAAA,CACb,MAAA,EACA,MAAA,EACA,GAAA,EACe;AACf,EAAA,IAAI,CAAC,OAAO,QAAA,EAAU;AACtB,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,CAAO,QAAA,CAAS,MAAA,EAAQ,GAAG,CAAA;AAAA,EACnC,CAAA,CAAA,MAAQ;AAAA,EAGR;AACF","file":"middleware-node.mjs","sourcesContent":["/**\n * D.3 — `RenderedResponse` → `NextResponse` adapter.\n *\n * The host wrapper's *only* job on the outbound path: take the\n * transport-agnostic `RenderedResponse` Phase C's\n * `renderDecisionAsResponse` produces and translate it to a\n * `NextResponse`. Zero verdict decisions, zero engine I/O.\n *\n * Shared between the Node-runtime and Edge-runtime entries. The\n * branching here is identical in both — Next.js `NextResponse` has the\n * same API surface across runtimes; only the underlying response\n * primitive differs (Node http.ServerResponse vs Edge `Response`).\n *\n * Architectural pins per architect § 4.3 / § 4.4:\n *\n * 1. **Verdict-cookie format is contract.** Sites-1's Sonner toast\n * depends on `__checkpoint_verdict=%7B%22verdict%22%3A%22<v>%22...\n * %7D` (single URL-encoded JSON). Byte-format pinned by adapt.test.\n *\n * 2. **HTML-accepting clients → `/blocked` rewrite at status 200**\n * (so the page renders with the verdict cookie set; Sonner picks\n * up the cookie and shows the toast). Non-HTML clients → JSON 4xx.\n *\n * 3. **`X-Checkpoint-Engine` carries `result.engineInfo.name`** —\n * `checkpoint-engine-wasm` after Phase D ships. Brian's Sites-2\n * deviation note confirmed the `X-Checkpoint-*` prefix is canon.\n */\n\nimport { type NextRequest, NextResponse } from 'next/server';\n\nimport type { RenderedResponse } from '@kya-os/checkpoint-wasm-runtime/orchestrator';\nimport {\n VERDICT_COOKIE_NAME,\n BLOCKED_PATH,\n encodeVerdictCookie,\n acceptsHtml,\n classifyResponseShape,\n} from '@kya-os/checkpoint-shared';\n\n/**\n * Convert the engine's transport-agnostic `RenderedResponse` into a\n * `NextResponse`. Sites-1's Playwright suite is the regression gate;\n * any drift here is caught downstream.\n */\nexport function adaptToNextResponse(rendered: RenderedResponse, req: NextRequest): NextResponse {\n const clientAcceptsHtml = acceptsHtml(req.headers);\n const verdictCookie = encodeVerdictCookie(rendered);\n const shape = classifyResponseShape(rendered, clientAcceptsHtml);\n\n switch (shape) {\n case 'pass-through': {\n // Permit OR Observe-mode any-verdict.\n const res = NextResponse.next();\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n\n case 'redirect': {\n // Decision::Redirect → 302 + Location.\n const target = new URL(rendered.headers.Location!);\n const res = NextResponse.redirect(target);\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n\n case 'html-block': {\n // Sites-1 contract: HTML clients (browsers) need a renderable page\n // to show the rejection UI. The verdict cookie carries the reason;\n // the /blocked route reads it and renders the toast.\n const blockedUrl = new URL(BLOCKED_PATH, req.url);\n const res = NextResponse.rewrite(blockedUrl, { status: 200 });\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n\n case 'json-block': {\n // The orchestrator's RenderedResponse already supplies the correct\n // status (401/403/422/...); we just need to materialise the body.\n // application/problem+json (Instruct) uses the Content-Type from\n // rendered.headers; defaults to application/json for everything else.\n const body = rendered.body ?? {};\n const res = NextResponse.json(body, { status: rendered.status as number });\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n }\n}\n\n// -----------------------------------------------------------------------------\n// Helpers — Next.js-specific glue. The framework-agnostic primitives\n// (encodeVerdictCookie, acceptsHtml, classifyResponseShape,\n// VERDICT_COOKIE_NAME, BLOCKED_PATH) live in `@kya-os/checkpoint-shared`\n// so checkpoint-express + future host wrappers produce byte-identical\n// cookies and route HTML/JSON branching the same way.\n// -----------------------------------------------------------------------------\n\nfunction setVerdictCookie(res: NextResponse, value: string): void {\n // Path / SameSite / HttpOnly chosen for the Sonner-bridge use case:\n // path=/ so any route can read it, SameSite=Lax so first-party\n // navigations carry it, HttpOnly=false so the client-side toast JS\n // can read it (it's verdict UX, not a session token).\n res.cookies.set({\n name: VERDICT_COOKIE_NAME,\n value,\n path: '/',\n sameSite: 'lax',\n httpOnly: false,\n });\n}\n\nfunction applyHeaders(res: NextResponse, headers: Record<string, string>): void {\n // NextResponse.next() / rewrite() / json() return responses with\n // some default headers; orchestrator headers (X-Checkpoint-*, Location)\n // override. We don't strip pre-existing headers — only set new ones.\n for (const [key, value] of Object.entries(headers)) {\n res.headers.set(key, value);\n }\n}\n","/**\n * D.2 — `NextRequest` → `IncomingHttpLike` translator.\n *\n * The host wrapper's *only* job on the inbound path: take Next.js's\n * native request shape and produce the transport-agnostic\n * `IncomingHttpLike` Phase C's orchestrator consumes. Zero verification\n * logic, zero adapter calls, zero engine I/O.\n *\n * Shared between the Node-runtime and Edge-runtime entries. Next.js\n * `NextRequest` is the same shape in both runtimes — `req.headers` is\n * a `Headers` instance, `req.body` is a `ReadableStream`, `req.ip` is\n * a getter (only present in some deployment surfaces; fall back to\n * `x-forwarded-for` first IP).\n */\n\nimport type { NextRequest } from 'next/server';\n\nimport type { IncomingHttpLike } from '@kya-os/checkpoint-wasm-runtime/orchestrator';\n\n/**\n * Translate a Next.js `NextRequest` into the orchestrator's\n * `IncomingHttpLike` shape.\n *\n * The body is passed through as-is — the orchestrator's\n * `buildAgentRequest` decides whether to parse JSON (looking for an\n * MCP-I `_meta.proof.jws` envelope) or treat the request as PlainHttp.\n * On Next.js middleware the body is typically not pre-parsed; consumers\n * who want to inspect the body for routing decisions should `await\n * req.json()` themselves and pass the parsed result via a second\n * `verifyRequest` call (not common).\n */\nexport function nextRequestToHttpLike(req: NextRequest): IncomingHttpLike {\n const url = new URL(req.url);\n return {\n method: req.method,\n // Path + query only — orchestrator's URL parsing expects no scheme/host.\n url: url.pathname + url.search,\n headers: headersToRecord(req.headers),\n // NextRequest.body is a ReadableStream; we don't drain it here.\n // The orchestrator routes to PlainHttp when body is falsy, which\n // is the right call for streaming middlewares that don't want to\n // buffer the request body just to detect agents.\n body: null,\n remoteAddress: extractRemoteAddress(req),\n };\n}\n\n/**\n * Convert a `Headers` instance into a lowercase-keyed plain object.\n * HTTP header names are case-insensitive (RFC 9110 § 5.1); the\n * orchestrator does case-sensitive lookups, so we normalise to\n * lowercase here. Multi-value headers (Set-Cookie, Accept) are\n * surfaced as their `Headers.get()` view — a single string with\n * comma-joined values, matching what other host adapters produce.\n */\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n headers.forEach((value, key) => {\n out[key.toLowerCase()] = value;\n });\n return out;\n}\n\n/**\n * Pull the originating client IP, preferring `x-forwarded-for`'s first\n * entry over `NextRequest.ip` (the latter is only populated on Vercel-\n * hosted deployments and is missing on self-hosted Next.js + nginx /\n * Fly.io / docker-compose surfaces). The `x-forwarded-for` first IP is\n * the closest the request has come to a load balancer's \"trust this is\n * the real client\" attestation — same convention as nginx, Caddy,\n * Cloudflare.\n */\nfunction extractRemoteAddress(req: NextRequest): string | undefined {\n const xff = req.headers.get('x-forwarded-for');\n if (xff) {\n const first = xff.split(',')[0]?.trim();\n if (first) return first;\n }\n // `req.ip` is typed but may be undefined off-Vercel.\n // Use `unknown` cast to avoid the type-narrowing optimism.\n const maybeIp = (req as unknown as { ip?: string }).ip;\n return maybeIp;\n}\n","/**\n * D.1 + D.3 — Node-runtime Next.js middleware entry.\n *\n * The host wrapper that composes Phase B adapters + Phase C\n * `verifyRequest` (sync engine) + Phase D translate/adapt into the\n * `withCheckpoint(config)` factory. Mounted under Vercel Node-runtime\n * serverless functions and long-lived Node servers.\n *\n * For Vercel Edge runtime (the Next.js middleware default), customers\n * import from `./edge` or `@kya-os/checkpoint-nextjs/edge` — that\n * variant uses `verifyRequestEdge` (async-init) and is otherwise\n * structurally identical. Both share `translate.ts` + `adapt.ts`.\n *\n * **Public API contract (architect § 4.1 — preserved):**\n *\n * - `withCheckpoint(config)` — factory returning the middleware.\n * - `CheckpointConfig` — the config shape; new fields are additive.\n *\n * Internal implementation gutted, external contract held. Sites-1's\n * Playwright suite is the regression gate.\n */\n\nimport { type NextRequest, type NextResponse } from 'next/server';\n\nimport {\n renderDecisionAsResponse,\n verifyRequest,\n} from '@kya-os/checkpoint-wasm-runtime/orchestrator';\nimport {\n makeDidResolver,\n makePolicyEvaluator,\n makeReputationOracle,\n makeStatusListCache,\n makeSystemClock,\n type DidResolverAdapter,\n type PolicyEvaluatorAdapter,\n type ReputationOracleAdapter,\n type StatusListCacheAdapter,\n} from '@kya-os/checkpoint-wasm-runtime/adapters';\nimport type { EnforcementMode, VerifyResult } from '@kya-os/checkpoint-wasm-runtime/engine';\n\nimport { adaptToNextResponse } from './adapt';\nimport { nextRequestToHttpLike } from './translate';\n\n/**\n * Configuration for `withCheckpoint`.\n *\n * The new minimal shape Phase D's middleware needs. Legacy\n * `AgentShieldMiddlewareConfig` (from `./api-middleware`) remains\n * exported during the deprecation window — see D.4 cutover.\n */\nexport interface CheckpointConfig {\n /**\n * Tenant identifier — typically the customer's dashboard hostname\n * (e.g. `acme.checkpoint.example`). The PolicyEvaluator uses this\n * to look up tenant policy from the dashboard.\n */\n tenantHost: string;\n\n /**\n * `'enforce'` (default) blocks; `'observe'` passes everything\n * through with `X-Checkpoint-Would-Have-Been` headers. Per Phase 0.2.\n */\n enforcementMode?: EnforcementMode;\n\n /**\n * Argus reputation oracle base URL. Omit to use the trust-by-default\n * baseline (reputation defaults to 1.0; orchestrator logs a one-shot\n * warning at first request).\n */\n argusUrl?: string;\n\n /**\n * Dashboard base URL for the PolicyEvaluator to fetch tenant policy\n * from. Omit to use the open-by-default tenant policy.\n */\n dashboardUrl?: string;\n\n /**\n * Returned to the PolicyEvaluator for anonymous requests (no agent\n * DID). Default 1.0 (trust-by-default).\n */\n reputationBaseline?: number;\n\n /**\n * Pre-built adapter instances. Production deployments use the\n * factory-built defaults from `@kya-os/checkpoint-wasm-runtime/adapters`;\n * tests use stubs. The factory composes any provided overrides over\n * defaults — partial overrides are supported.\n */\n adapters?: Partial<{\n didResolver: DidResolverAdapter;\n statusListCache: StatusListCacheAdapter;\n reputationOracle: ReputationOracleAdapter;\n policyEvaluator: PolicyEvaluatorAdapter;\n }>;\n\n /**\n * Optional callback for the post-verdict path — fires after every\n * verification, regardless of permit/block, with the full\n * `VerifyResult`. Use for logging, dashboards, telemetry. Errors\n * thrown here are swallowed so user code can't break the middleware\n * response.\n */\n onResult?: (result: VerifyResult, req: NextRequest) => void | Promise<void>;\n}\n\n/**\n * Build the Checkpoint middleware. Returns a function `(req) => NextResponse`\n * suitable for `export default withCheckpoint({...})` in `middleware.ts`.\n *\n * Every verification decision flows through the Rust `kya-os-engine`\n * via WASM. The TS layer translates request shape, calls\n * `verifyRequest`, and translates the verdict to `NextResponse`. No\n * verification logic lives in this file.\n */\nexport function withCheckpoint(\n config: CheckpointConfig\n): (req: NextRequest) => Promise<NextResponse> {\n const opts = buildVerifyOpts(config);\n return async function checkpointMiddleware(req: NextRequest): Promise<NextResponse> {\n const httpLike = nextRequestToHttpLike(req);\n const result = await verifyRequest(httpLike, opts);\n await dispatchOnResult(config, result, req);\n const rendered = renderDecisionAsResponse(result);\n return adaptToNextResponse(rendered, req);\n };\n}\n\n/**\n * Compose adapter defaults with caller-supplied overrides. Factored\n * out so the Edge entry (which uses the same composition) can reuse\n * the shape.\n */\nfunction buildVerifyOpts(config: CheckpointConfig) {\n const overrides = config.adapters ?? {};\n return {\n didResolver: overrides.didResolver ?? makeDidResolver(),\n statusListCache: overrides.statusListCache ?? makeStatusListCache(),\n reputationOracle:\n overrides.reputationOracle ?? makeReputationOracle({ argusUrl: config.argusUrl }),\n policyEvaluator:\n overrides.policyEvaluator ?? makePolicyEvaluator({ dashboardUrl: config.dashboardUrl }),\n clock: makeSystemClock(),\n tenantHost: config.tenantHost,\n enforcementMode: config.enforcementMode ?? 'enforce',\n reputationBaseline: config.reputationBaseline,\n argusUrl: config.argusUrl,\n };\n}\n\nasync function dispatchOnResult(\n config: CheckpointConfig,\n result: VerifyResult,\n req: NextRequest\n): Promise<void> {\n if (!config.onResult) return;\n try {\n await config.onResult(result, req);\n } catch {\n // Swallow — onResult is observability, not verdict-critical.\n // Verdict already computed; let the response proceed.\n }\n}\n\n// Re-export the shared opts builder for the Edge entry. Internal seam;\n// not part of the public surface.\nexport { buildVerifyOpts as _buildVerifyOpts };\n"]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
import { N as NextJSMiddlewareConfig } from './types-C-xCUNTr.mjs';
|
|
3
|
+
import '@kya-os/checkpoint-shared';
|
|
4
|
+
import '@kya-os/checkpoint';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @deprecated Phase D — legacy TS-pattern-matching middleware path is
|
|
8
|
+
* gone. This file now exists only to preserve the historical export
|
|
9
|
+
* surface (`createAgentShieldMiddleware`, `agentShield`) at compile
|
|
10
|
+
* time. Calling either function throws a clear migration error.
|
|
11
|
+
*
|
|
12
|
+
* Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs`
|
|
13
|
+
* (Node runtime) or `@kya-os/checkpoint-nextjs/edge` (Edge runtime).
|
|
14
|
+
* The new factory accepts a `CheckpointConfig` and routes every
|
|
15
|
+
* verification through the Rust `kya-os-engine` via WASM. See the
|
|
16
|
+
* package CHANGELOG for the recipe.
|
|
17
|
+
*
|
|
18
|
+
* Architect Q10 deletion ratification — the 600-line TS pattern
|
|
19
|
+
* matcher (`edge-detector-wrapper.ts`) was removed in Phase D's
|
|
20
|
+
* cutover. The new path is structurally simpler and decisive: one
|
|
21
|
+
* engine, one verdict, every runtime.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @deprecated Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs`.
|
|
26
|
+
* Throws on invocation; surface exists only so static analysis sees
|
|
27
|
+
* the historical export.
|
|
28
|
+
*/
|
|
29
|
+
declare function createAgentShieldMiddleware(_config?: Partial<NextJSMiddlewareConfig>): (request: NextRequest) => Promise<NextResponse>;
|
|
30
|
+
/**
|
|
31
|
+
* @deprecated Alias of the deprecated `createAgentShieldMiddleware`.
|
|
32
|
+
* Migrate to `withCheckpoint`.
|
|
33
|
+
*/
|
|
34
|
+
declare function agentShield(config?: Partial<NextJSMiddlewareConfig>): (request: NextRequest) => Promise<NextResponse>;
|
|
35
|
+
|
|
36
|
+
export { agentShield, createAgentShieldMiddleware };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
import { N as NextJSMiddlewareConfig } from './types-C-xCUNTr.js';
|
|
3
|
+
import '@kya-os/checkpoint-shared';
|
|
4
|
+
import '@kya-os/checkpoint';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @deprecated Phase D — legacy TS-pattern-matching middleware path is
|
|
8
|
+
* gone. This file now exists only to preserve the historical export
|
|
9
|
+
* surface (`createAgentShieldMiddleware`, `agentShield`) at compile
|
|
10
|
+
* time. Calling either function throws a clear migration error.
|
|
11
|
+
*
|
|
12
|
+
* Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs`
|
|
13
|
+
* (Node runtime) or `@kya-os/checkpoint-nextjs/edge` (Edge runtime).
|
|
14
|
+
* The new factory accepts a `CheckpointConfig` and routes every
|
|
15
|
+
* verification through the Rust `kya-os-engine` via WASM. See the
|
|
16
|
+
* package CHANGELOG for the recipe.
|
|
17
|
+
*
|
|
18
|
+
* Architect Q10 deletion ratification — the 600-line TS pattern
|
|
19
|
+
* matcher (`edge-detector-wrapper.ts`) was removed in Phase D's
|
|
20
|
+
* cutover. The new path is structurally simpler and decisive: one
|
|
21
|
+
* engine, one verdict, every runtime.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @deprecated Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs`.
|
|
26
|
+
* Throws on invocation; surface exists only so static analysis sees
|
|
27
|
+
* the historical export.
|
|
28
|
+
*/
|
|
29
|
+
declare function createAgentShieldMiddleware(_config?: Partial<NextJSMiddlewareConfig>): (request: NextRequest) => Promise<NextResponse>;
|
|
30
|
+
/**
|
|
31
|
+
* @deprecated Alias of the deprecated `createAgentShieldMiddleware`.
|
|
32
|
+
* Migrate to `withCheckpoint`.
|
|
33
|
+
*/
|
|
34
|
+
declare function agentShield(config?: Partial<NextJSMiddlewareConfig>): (request: NextRequest) => Promise<NextResponse>;
|
|
35
|
+
|
|
36
|
+
export { agentShield, createAgentShieldMiddleware };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/middleware.ts
|
|
4
|
+
var MIGRATION_ERROR = "@kya-os/checkpoint-nextjs's `createAgentShieldMiddleware` / `agentShield` were deleted in Phase D (engine consolidation). The 600-line TS pattern matcher that backed them is gone. Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` (Node runtime) or `@kya-os/checkpoint-nextjs/edge` (Edge runtime). See packages/checkpoint-nextjs/CHANGELOG.md (1.0.0) for the recipe.";
|
|
5
|
+
function createAgentShieldMiddleware(_config = {}) {
|
|
6
|
+
throw new Error(MIGRATION_ERROR);
|
|
7
|
+
}
|
|
8
|
+
function agentShield(config = {}) {
|
|
9
|
+
return createAgentShieldMiddleware(config);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
exports.agentShield = agentShield;
|
|
13
|
+
exports.createAgentShieldMiddleware = createAgentShieldMiddleware;
|
|
14
|
+
//# sourceMappingURL=middleware.js.map
|
|
15
|
+
//# sourceMappingURL=middleware.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/middleware.ts"],"names":[],"mappings":";;;AAsBA,IAAM,eAAA,GACJ,yXAAA;AAYK,SAAS,2BAAA,CACd,OAAA,GAA2C,EAAC,EACK;AACjD,EAAA,MAAM,IAAI,MAAM,eAAe,CAAA;AACjC;AAMO,SAAS,WAAA,CACd,MAAA,GAA0C,EAAC,EACM;AACjD,EAAA,OAAO,4BAA4B,MAAM,CAAA;AAC3C","file":"middleware.js","sourcesContent":["/**\n * @deprecated Phase D — legacy TS-pattern-matching middleware path is\n * gone. This file now exists only to preserve the historical export\n * surface (`createAgentShieldMiddleware`, `agentShield`) at compile\n * time. Calling either function throws a clear migration error.\n *\n * Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs`\n * (Node runtime) or `@kya-os/checkpoint-nextjs/edge` (Edge runtime).\n * The new factory accepts a `CheckpointConfig` and routes every\n * verification through the Rust `kya-os-engine` via WASM. See the\n * package CHANGELOG for the recipe.\n *\n * Architect Q10 deletion ratification — the 600-line TS pattern\n * matcher (`edge-detector-wrapper.ts`) was removed in Phase D's\n * cutover. The new path is structurally simpler and decisive: one\n * engine, one verdict, every runtime.\n */\n\nimport type { NextRequest, NextResponse } from 'next/server';\n\nimport type { NextJSMiddlewareConfig } from './types';\n\nconst MIGRATION_ERROR =\n \"@kya-os/checkpoint-nextjs's `createAgentShieldMiddleware` / `agentShield` \" +\n 'were deleted in Phase D (engine consolidation). The 600-line TS pattern ' +\n 'matcher that backed them is gone. Migrate to `withCheckpoint` from ' +\n '`@kya-os/checkpoint-nextjs` (Node runtime) or ' +\n '`@kya-os/checkpoint-nextjs/edge` (Edge runtime). ' +\n 'See packages/checkpoint-nextjs/CHANGELOG.md (1.0.0) for the recipe.';\n\n/**\n * @deprecated Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs`.\n * Throws on invocation; surface exists only so static analysis sees\n * the historical export.\n */\nexport function createAgentShieldMiddleware(\n _config: Partial<NextJSMiddlewareConfig> = {}\n): (request: NextRequest) => Promise<NextResponse> {\n throw new Error(MIGRATION_ERROR);\n}\n\n/**\n * @deprecated Alias of the deprecated `createAgentShieldMiddleware`.\n * Migrate to `withCheckpoint`.\n */\nexport function agentShield(\n config: Partial<NextJSMiddlewareConfig> = {}\n): (request: NextRequest) => Promise<NextResponse> {\n return createAgentShieldMiddleware(config);\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// src/middleware.ts
|
|
2
|
+
var MIGRATION_ERROR = "@kya-os/checkpoint-nextjs's `createAgentShieldMiddleware` / `agentShield` were deleted in Phase D (engine consolidation). The 600-line TS pattern matcher that backed them is gone. Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` (Node runtime) or `@kya-os/checkpoint-nextjs/edge` (Edge runtime). See packages/checkpoint-nextjs/CHANGELOG.md (1.0.0) for the recipe.";
|
|
3
|
+
function createAgentShieldMiddleware(_config = {}) {
|
|
4
|
+
throw new Error(MIGRATION_ERROR);
|
|
5
|
+
}
|
|
6
|
+
function agentShield(config = {}) {
|
|
7
|
+
return createAgentShieldMiddleware(config);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export { agentShield, createAgentShieldMiddleware };
|
|
11
|
+
//# sourceMappingURL=middleware.mjs.map
|
|
12
|
+
//# sourceMappingURL=middleware.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/middleware.ts"],"names":[],"mappings":";AAsBA,IAAM,eAAA,GACJ,yXAAA;AAYK,SAAS,2BAAA,CACd,OAAA,GAA2C,EAAC,EACK;AACjD,EAAA,MAAM,IAAI,MAAM,eAAe,CAAA;AACjC;AAMO,SAAS,WAAA,CACd,MAAA,GAA0C,EAAC,EACM;AACjD,EAAA,OAAO,4BAA4B,MAAM,CAAA;AAC3C","file":"middleware.mjs","sourcesContent":["/**\n * @deprecated Phase D — legacy TS-pattern-matching middleware path is\n * gone. This file now exists only to preserve the historical export\n * surface (`createAgentShieldMiddleware`, `agentShield`) at compile\n * time. Calling either function throws a clear migration error.\n *\n * Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs`\n * (Node runtime) or `@kya-os/checkpoint-nextjs/edge` (Edge runtime).\n * The new factory accepts a `CheckpointConfig` and routes every\n * verification through the Rust `kya-os-engine` via WASM. See the\n * package CHANGELOG for the recipe.\n *\n * Architect Q10 deletion ratification — the 600-line TS pattern\n * matcher (`edge-detector-wrapper.ts`) was removed in Phase D's\n * cutover. The new path is structurally simpler and decisive: one\n * engine, one verdict, every runtime.\n */\n\nimport type { NextRequest, NextResponse } from 'next/server';\n\nimport type { NextJSMiddlewareConfig } from './types';\n\nconst MIGRATION_ERROR =\n \"@kya-os/checkpoint-nextjs's `createAgentShieldMiddleware` / `agentShield` \" +\n 'were deleted in Phase D (engine consolidation). The 600-line TS pattern ' +\n 'matcher that backed them is gone. Migrate to `withCheckpoint` from ' +\n '`@kya-os/checkpoint-nextjs` (Node runtime) or ' +\n '`@kya-os/checkpoint-nextjs/edge` (Edge runtime). ' +\n 'See packages/checkpoint-nextjs/CHANGELOG.md (1.0.0) for the recipe.';\n\n/**\n * @deprecated Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs`.\n * Throws on invocation; surface exists only so static analysis sees\n * the historical export.\n */\nexport function createAgentShieldMiddleware(\n _config: Partial<NextJSMiddlewareConfig> = {}\n): (request: NextRequest) => Promise<NextResponse> {\n throw new Error(MIGRATION_ERROR);\n}\n\n/**\n * @deprecated Alias of the deprecated `createAgentShieldMiddleware`.\n * Migrate to `withCheckpoint`.\n */\nexport function agentShield(\n config: Partial<NextJSMiddlewareConfig> = {}\n): (request: NextRequest) => Promise<NextResponse> {\n return createAgentShieldMiddleware(config);\n}\n"]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node.js Runtime WASM Loader for AgentShield
|
|
3
|
+
*
|
|
4
|
+
* This loader uses fs.readFileSync to load WASM in Node.js runtime.
|
|
5
|
+
* It provides full cryptographic verification capabilities.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Load WASM module using Node.js fs module
|
|
9
|
+
* This only works in Node.js runtime, not Edge Runtime
|
|
10
|
+
*/
|
|
11
|
+
declare function loadWasmNodejs(): Promise<boolean>;
|
|
12
|
+
/**
|
|
13
|
+
* Check if we're in Node.js runtime
|
|
14
|
+
*/
|
|
15
|
+
declare function isNodejsRuntime(): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Get the loaded WASM module
|
|
18
|
+
*/
|
|
19
|
+
declare function getWasmModule(): WebAssembly.Module | null;
|
|
20
|
+
/**
|
|
21
|
+
* Check if WASM is initialized
|
|
22
|
+
*/
|
|
23
|
+
declare function isWasmInitialized(): boolean;
|
|
24
|
+
|
|
25
|
+
export { getWasmModule, isNodejsRuntime, isWasmInitialized, loadWasmNodejs };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node.js Runtime WASM Loader for AgentShield
|
|
3
|
+
*
|
|
4
|
+
* This loader uses fs.readFileSync to load WASM in Node.js runtime.
|
|
5
|
+
* It provides full cryptographic verification capabilities.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Load WASM module using Node.js fs module
|
|
9
|
+
* This only works in Node.js runtime, not Edge Runtime
|
|
10
|
+
*/
|
|
11
|
+
declare function loadWasmNodejs(): Promise<boolean>;
|
|
12
|
+
/**
|
|
13
|
+
* Check if we're in Node.js runtime
|
|
14
|
+
*/
|
|
15
|
+
declare function isNodejsRuntime(): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Get the loaded WASM module
|
|
18
|
+
*/
|
|
19
|
+
declare function getWasmModule(): WebAssembly.Module | null;
|
|
20
|
+
/**
|
|
21
|
+
* Check if WASM is initialized
|
|
22
|
+
*/
|
|
23
|
+
declare function isWasmInitialized(): boolean;
|
|
24
|
+
|
|
25
|
+
export { getWasmModule, isNodejsRuntime, isWasmInitialized, loadWasmNodejs };
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var fs = require('fs');
|
|
4
|
+
var path = require('path');
|
|
5
|
+
var checkpoint = require('@kya-os/checkpoint');
|
|
6
|
+
|
|
7
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
8
|
+
|
|
9
|
+
var fs__default = /*#__PURE__*/_interopDefault(fs);
|
|
10
|
+
var path__default = /*#__PURE__*/_interopDefault(path);
|
|
11
|
+
|
|
12
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
13
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
14
|
+
}) : x)(function(x) {
|
|
15
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
16
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
17
|
+
});
|
|
18
|
+
var wasmInitialized = false;
|
|
19
|
+
var wasmModule = null;
|
|
20
|
+
async function loadWasmNodejs() {
|
|
21
|
+
if (wasmInitialized) {
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
const possiblePaths = [
|
|
26
|
+
// In node_modules (most likely)
|
|
27
|
+
path__default.default.join(
|
|
28
|
+
process.cwd(),
|
|
29
|
+
"node_modules",
|
|
30
|
+
"@kya-os",
|
|
31
|
+
"agentshield",
|
|
32
|
+
"dist",
|
|
33
|
+
"wasm",
|
|
34
|
+
"agentshield_wasm_bg.wasm"
|
|
35
|
+
),
|
|
36
|
+
// In project root (if user copied it)
|
|
37
|
+
path__default.default.join(process.cwd(), "agentshield_wasm_bg.wasm"),
|
|
38
|
+
// Relative to current file
|
|
39
|
+
path__default.default.join(
|
|
40
|
+
__dirname,
|
|
41
|
+
"..",
|
|
42
|
+
"..",
|
|
43
|
+
"..",
|
|
44
|
+
"agentshield",
|
|
45
|
+
"dist",
|
|
46
|
+
"wasm",
|
|
47
|
+
"agentshield_wasm_bg.wasm"
|
|
48
|
+
)
|
|
49
|
+
];
|
|
50
|
+
let wasmBuffer = null;
|
|
51
|
+
let loadedPath = null;
|
|
52
|
+
for (const wasmPath of possiblePaths) {
|
|
53
|
+
try {
|
|
54
|
+
if (fs__default.default.existsSync(wasmPath)) {
|
|
55
|
+
wasmBuffer = fs__default.default.readFileSync(wasmPath);
|
|
56
|
+
loadedPath = wasmPath;
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
} catch (e) {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (!wasmBuffer) {
|
|
64
|
+
console.warn("AgentShield: WASM file not found in any expected location");
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
const bytes = new Uint8Array(wasmBuffer);
|
|
68
|
+
wasmModule = await WebAssembly.compile(bytes);
|
|
69
|
+
checkpoint.setWasmModule(wasmModule);
|
|
70
|
+
wasmInitialized = true;
|
|
71
|
+
console.log(`\u2705 AgentShield: WASM loaded successfully from ${loadedPath} (Node.js runtime)`);
|
|
72
|
+
console.log("\u{1F510} Cryptographic verification enabled (95-100% confidence)");
|
|
73
|
+
return true;
|
|
74
|
+
} catch (error) {
|
|
75
|
+
console.warn("\u26A0\uFE0F AgentShield: Failed to load WASM in Node.js runtime:", error);
|
|
76
|
+
console.log("\u{1F4CA} Falling back to pattern detection (85% confidence)");
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function isNodejsRuntime() {
|
|
81
|
+
return typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && typeof __require !== "undefined";
|
|
82
|
+
}
|
|
83
|
+
function getWasmModule() {
|
|
84
|
+
return wasmModule;
|
|
85
|
+
}
|
|
86
|
+
function isWasmInitialized() {
|
|
87
|
+
return wasmInitialized;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
exports.getWasmModule = getWasmModule;
|
|
91
|
+
exports.isNodejsRuntime = isNodejsRuntime;
|
|
92
|
+
exports.isWasmInitialized = isWasmInitialized;
|
|
93
|
+
exports.loadWasmNodejs = loadWasmNodejs;
|
|
94
|
+
//# sourceMappingURL=nodejs-wasm-loader.js.map
|
|
95
|
+
//# sourceMappingURL=nodejs-wasm-loader.js.map
|
|
@@ -0,0 +1 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A,IACT;AAIA,IAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,UAAU,CAAA;AACvC,IAAA,UAAA,GAAa,MAAM,WAAA,CAAY,OAAA,CAAQ,KAAK,CAAA;AAG5C,IAAAC,wBAAA,CAAc,UAAU,CAAA;AAExB,IAAA,eAAA,GAAkB,IAAA;AAClB,IAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,kDAAA,EAAgD,UAAU,CAAA,kBAAA,CAAoB,CAAA;AAC1F,IAAA,OAAA,CAAQ,IAAI,mEAA4D,CAAA;AAExE,IAAA,OAAO,IAAA;AAAA,EACT,SAAS,KAAA,EAAO;AACd,IAAA,OAAA,CAAQ,IAAA,CAAK,qEAA2D,KAAK,CAAA;AAC7E,IAAA,OAAA,CAAQ,IAAI,8DAAuD,CAAA;AACnE,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAKO,SAAS,eAAA,GAA2B;AACzC,EAAA,OACE,OAAO,OAAA,KAAY,WAAA,IACnB,OAAO,OAAA,CAAQ,QAAA,KAAa,WAAA,IAC5B,OAAO,OAAA,CAAQ,QAAA,CAAS,IAAA,KAAS,WAAA,IACjC,OAAO,SAAA,KAAY,WAAA;AAEvB;AAKO,SAAS,aAAA,GAA2C;AACzD,EAAA,OAAO,UAAA;AACT;AAKO,SAAS,iBAAA,GAA6B;AAC3C,EAAA,OAAO,eAAA;AACT","file":"nodejs-wasm-loader.js","sourcesContent":["/**\n * Node.js Runtime WASM Loader for AgentShield\n *\n * This loader uses fs.readFileSync to load WASM in Node.js runtime.\n * It provides full cryptographic verification capabilities.\n */\n\nimport fs from 'fs';\nimport path from 'path';\nimport { setWasmModule } from '@kya-os/checkpoint';\n\nlet wasmInitialized = false;\nlet wasmModule: WebAssembly.Module | null = null;\n\n/**\n * Load WASM module using Node.js fs module\n * This only works in Node.js runtime, not Edge Runtime\n */\nexport async function loadWasmNodejs(): Promise<boolean> {\n if (wasmInitialized) {\n return true;\n }\n\n try {\n // Try multiple possible WASM locations\n const possiblePaths = [\n // In node_modules (most likely)\n path.join(\n process.cwd(),\n 'node_modules',\n '@kya-os',\n 'agentshield',\n 'dist',\n 'wasm',\n 'agentshield_wasm_bg.wasm'\n ),\n // In project root (if user copied it)\n path.join(process.cwd(), 'agentshield_wasm_bg.wasm'),\n // Relative to current file\n path.join(\n __dirname,\n '..',\n '..',\n '..',\n 'agentshield',\n 'dist',\n 'wasm',\n 'agentshield_wasm_bg.wasm'\n ),\n ];\n\n let wasmBuffer: Buffer | null = null;\n let loadedPath: string | null = null;\n\n for (const wasmPath of possiblePaths) {\n try {\n if (fs.existsSync(wasmPath)) {\n wasmBuffer = fs.readFileSync(wasmPath);\n loadedPath = wasmPath;\n break;\n }\n } catch (e) {\n // Try next path\n continue;\n }\n }\n\n if (!wasmBuffer) {\n console.warn('AgentShield: WASM file not found in any expected location');\n return false;\n }\n\n // Convert Buffer to Uint8Array for WebAssembly\n // This is the proper way to handle Buffer -> ArrayBuffer conversion\n const bytes = new Uint8Array(wasmBuffer);\n wasmModule = await WebAssembly.compile(bytes);\n\n // Set the module in AgentShield\n setWasmModule(wasmModule);\n\n wasmInitialized = true;\n console.log(`✅ AgentShield: WASM loaded successfully from ${loadedPath} (Node.js runtime)`);\n console.log('🔐 Cryptographic verification enabled (95-100% confidence)');\n\n return true;\n } catch (error) {\n console.warn('⚠️ AgentShield: Failed to load WASM in Node.js runtime:', error);\n console.log('📊 Falling back to pattern detection (85% confidence)');\n return false;\n }\n}\n\n/**\n * Check if we're in Node.js runtime\n */\nexport function isNodejsRuntime(): boolean {\n return (\n typeof process !== 'undefined' &&\n typeof process.versions !== 'undefined' &&\n typeof process.versions.node !== 'undefined' &&\n typeof require !== 'undefined'\n );\n}\n\n/**\n * Get the loaded WASM module\n */\nexport function getWasmModule(): WebAssembly.Module | null {\n return wasmModule;\n}\n\n/**\n * Check if WASM is initialized\n */\nexport function isWasmInitialized(): boolean {\n return wasmInitialized;\n}\n"]}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { setWasmModule } from '@kya-os/checkpoint';
|
|
4
|
+
|
|
5
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
6
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
7
|
+
}) : x)(function(x) {
|
|
8
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
9
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
10
|
+
});
|
|
11
|
+
var wasmInitialized = false;
|
|
12
|
+
var wasmModule = null;
|
|
13
|
+
async function loadWasmNodejs() {
|
|
14
|
+
if (wasmInitialized) {
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
const possiblePaths = [
|
|
19
|
+
// In node_modules (most likely)
|
|
20
|
+
path.join(
|
|
21
|
+
process.cwd(),
|
|
22
|
+
"node_modules",
|
|
23
|
+
"@kya-os",
|
|
24
|
+
"agentshield",
|
|
25
|
+
"dist",
|
|
26
|
+
"wasm",
|
|
27
|
+
"agentshield_wasm_bg.wasm"
|
|
28
|
+
),
|
|
29
|
+
// In project root (if user copied it)
|
|
30
|
+
path.join(process.cwd(), "agentshield_wasm_bg.wasm"),
|
|
31
|
+
// Relative to current file
|
|
32
|
+
path.join(
|
|
33
|
+
__dirname,
|
|
34
|
+
"..",
|
|
35
|
+
"..",
|
|
36
|
+
"..",
|
|
37
|
+
"agentshield",
|
|
38
|
+
"dist",
|
|
39
|
+
"wasm",
|
|
40
|
+
"agentshield_wasm_bg.wasm"
|
|
41
|
+
)
|
|
42
|
+
];
|
|
43
|
+
let wasmBuffer = null;
|
|
44
|
+
let loadedPath = null;
|
|
45
|
+
for (const wasmPath of possiblePaths) {
|
|
46
|
+
try {
|
|
47
|
+
if (fs.existsSync(wasmPath)) {
|
|
48
|
+
wasmBuffer = fs.readFileSync(wasmPath);
|
|
49
|
+
loadedPath = wasmPath;
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
} catch (e) {
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (!wasmBuffer) {
|
|
57
|
+
console.warn("AgentShield: WASM file not found in any expected location");
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
const bytes = new Uint8Array(wasmBuffer);
|
|
61
|
+
wasmModule = await WebAssembly.compile(bytes);
|
|
62
|
+
setWasmModule(wasmModule);
|
|
63
|
+
wasmInitialized = true;
|
|
64
|
+
console.log(`\u2705 AgentShield: WASM loaded successfully from ${loadedPath} (Node.js runtime)`);
|
|
65
|
+
console.log("\u{1F510} Cryptographic verification enabled (95-100% confidence)");
|
|
66
|
+
return true;
|
|
67
|
+
} catch (error) {
|
|
68
|
+
console.warn("\u26A0\uFE0F AgentShield: Failed to load WASM in Node.js runtime:", error);
|
|
69
|
+
console.log("\u{1F4CA} Falling back to pattern detection (85% confidence)");
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function isNodejsRuntime() {
|
|
74
|
+
return typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && typeof __require !== "undefined";
|
|
75
|
+
}
|
|
76
|
+
function getWasmModule() {
|
|
77
|
+
return wasmModule;
|
|
78
|
+
}
|
|
79
|
+
function isWasmInitialized() {
|
|
80
|
+
return wasmInitialized;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export { getWasmModule, isNodejsRuntime, isWasmInitialized, loadWasmNodejs };
|
|
84
|
+
//# sourceMappingURL=nodejs-wasm-loader.mjs.map
|
|
85
|
+
//# sourceMappingURL=nodejs-wasm-loader.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/nodejs-wasm-loader.ts"],"names":[],"mappings":";;;;;;;;;;AAWA,IAAI,eAAA,GAAkB,KAAA;AACtB,IAAI,UAAA,GAAw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CAAA;AAExB,IAAA,eAAA,GAAkB,IAAA;AAClB,IAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,kDAAA,EAAgD,UAAU,CAAA,kBAAA,CAAoB,CAAA;AAC1F,IAAA,OAAA,CAAQ,IAAI,mEAA4D,CAAA;AAExE,IAAA,OAAO,IAAA;AAAA,EACT,SAAS,KAAA,EAAO;AACd,IAAA,OAAA,CAAQ,IAAA,CAAK,qEAA2D,KAAK,CAAA;AAC7E,IAAA,OAAA,CAAQ,IAAI,8DAAuD,CAAA;AACnE,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAKO,SAAS,eAAA,GAA2B;AACzC,EAAA,OACE,OAAO,OAAA,KAAY,WAAA,IACnB,OAAO,OAAA,CAAQ,QAAA,KAAa,WAAA,IAC5B,OAAO,OAAA,CAAQ,QAAA,CAAS,IAAA,KAAS,WAAA,IACjC,OAAO,SAAA,KAAY,WAAA;AAEvB;AAKO,SAAS,aAAA,GAA2C;AACzD,EAAA,OAAO,UAAA;AACT;AAKO,SAAS,iBAAA,GAA6B;AAC3C,EAAA,OAAO,eAAA;AACT","file":"nodejs-wasm-loader.mjs","sourcesContent":["/**\n * Node.js Runtime WASM Loader for AgentShield\n *\n * This loader uses fs.readFileSync to load WASM in Node.js runtime.\n * It provides full cryptographic verification capabilities.\n */\n\nimport fs from 'fs';\nimport path from 'path';\nimport { setWasmModule } from '@kya-os/checkpoint';\n\nlet wasmInitialized = false;\nlet wasmModule: WebAssembly.Module | null = null;\n\n/**\n * Load WASM module using Node.js fs module\n * This only works in Node.js runtime, not Edge Runtime\n */\nexport async function loadWasmNodejs(): Promise<boolean> {\n if (wasmInitialized) {\n return true;\n }\n\n try {\n // Try multiple possible WASM locations\n const possiblePaths = [\n // In node_modules (most likely)\n path.join(\n process.cwd(),\n 'node_modules',\n '@kya-os',\n 'agentshield',\n 'dist',\n 'wasm',\n 'agentshield_wasm_bg.wasm'\n ),\n // In project root (if user copied it)\n path.join(process.cwd(), 'agentshield_wasm_bg.wasm'),\n // Relative to current file\n path.join(\n __dirname,\n '..',\n '..',\n '..',\n 'agentshield',\n 'dist',\n 'wasm',\n 'agentshield_wasm_bg.wasm'\n ),\n ];\n\n let wasmBuffer: Buffer | null = null;\n let loadedPath: string | null = null;\n\n for (const wasmPath of possiblePaths) {\n try {\n if (fs.existsSync(wasmPath)) {\n wasmBuffer = fs.readFileSync(wasmPath);\n loadedPath = wasmPath;\n break;\n }\n } catch (e) {\n // Try next path\n continue;\n }\n }\n\n if (!wasmBuffer) {\n console.warn('AgentShield: WASM file not found in any expected location');\n return false;\n }\n\n // Convert Buffer to Uint8Array for WebAssembly\n // This is the proper way to handle Buffer -> ArrayBuffer conversion\n const bytes = new Uint8Array(wasmBuffer);\n wasmModule = await WebAssembly.compile(bytes);\n\n // Set the module in AgentShield\n setWasmModule(wasmModule);\n\n wasmInitialized = true;\n console.log(`✅ AgentShield: WASM loaded successfully from ${loadedPath} (Node.js runtime)`);\n console.log('🔐 Cryptographic verification enabled (95-100% confidence)');\n\n return true;\n } catch (error) {\n console.warn('⚠️ AgentShield: Failed to load WASM in Node.js runtime:', error);\n console.log('📊 Falling back to pattern detection (85% confidence)');\n return false;\n }\n}\n\n/**\n * Check if we're in Node.js runtime\n */\nexport function isNodejsRuntime(): boolean {\n return (\n typeof process !== 'undefined' &&\n typeof process.versions !== 'undefined' &&\n typeof process.versions.node !== 'undefined' &&\n typeof require !== 'undefined'\n );\n}\n\n/**\n * Get the loaded WASM module\n */\nexport function getWasmModule(): WebAssembly.Module | null {\n return wasmModule;\n}\n\n/**\n * Check if WASM is initialized\n */\nexport function isWasmInitialized(): boolean {\n return wasmInitialized;\n}\n"]}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
import { PolicyConfig, PolicyEvaluationResult, PolicyEvaluationContext, DetectionResult } from '@kya-os/checkpoint-shared';
|
|
3
|
+
export { DEFAULT_POLICY, ENFORCEMENT_ACTIONS, PolicyConfig, PolicyEvaluationContext, PolicyEvaluationResult, createEvaluationContext, evaluatePolicy } from '@kya-os/checkpoint-shared';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Policy Integration for agentshield-nextjs
|
|
7
|
+
*
|
|
8
|
+
* This module provides policy evaluation support for the Next.js middleware.
|
|
9
|
+
* It can use:
|
|
10
|
+
* - Local policy configuration (static)
|
|
11
|
+
* - Fetched policy from AgentShield API (dynamic with caching)
|
|
12
|
+
* - Fallback/default policies
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* import { createPolicyMiddleware } from '@kya-os/checkpoint-nextjs/policy';
|
|
17
|
+
*
|
|
18
|
+
* export default createPolicyMiddleware({
|
|
19
|
+
* policy: {
|
|
20
|
+
* enabled: true,
|
|
21
|
+
* defaultAction: 'allow',
|
|
22
|
+
* thresholds: { confidenceThreshold: 80, confidenceAction: 'block' },
|
|
23
|
+
* allowList: [{ clientName: 'ChatGPT' }],
|
|
24
|
+
* },
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Policy middleware configuration
|
|
31
|
+
*/
|
|
32
|
+
interface PolicyMiddlewareConfig {
|
|
33
|
+
/**
|
|
34
|
+
* Local policy configuration (static)
|
|
35
|
+
* If provided, this policy is used instead of fetching from API
|
|
36
|
+
*/
|
|
37
|
+
policy?: Partial<PolicyConfig>;
|
|
38
|
+
/**
|
|
39
|
+
* Fetch policy from AgentShield API
|
|
40
|
+
* Requires projectId and optionally an apiKey
|
|
41
|
+
*/
|
|
42
|
+
fetchPolicy?: {
|
|
43
|
+
/** Project ID to fetch policy for */
|
|
44
|
+
projectId: string;
|
|
45
|
+
/** API base URL (defaults to production) */
|
|
46
|
+
apiUrl?: string;
|
|
47
|
+
/** API key for authentication */
|
|
48
|
+
apiKey?: string;
|
|
49
|
+
/** Cache TTL in seconds (default: 300) */
|
|
50
|
+
cacheTtlSeconds?: number;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Fallback policy to use when fetch fails
|
|
54
|
+
* Defaults to DEFAULT_POLICY (allow all)
|
|
55
|
+
*/
|
|
56
|
+
fallbackPolicy?: Partial<PolicyConfig>;
|
|
57
|
+
/**
|
|
58
|
+
* Custom blocked response
|
|
59
|
+
*/
|
|
60
|
+
blockedResponse?: {
|
|
61
|
+
status?: number;
|
|
62
|
+
message?: string;
|
|
63
|
+
headers?: Record<string, string>;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Default redirect URL for redirect actions
|
|
67
|
+
*/
|
|
68
|
+
redirectUrl?: string;
|
|
69
|
+
/**
|
|
70
|
+
* Callback when policy decision is made
|
|
71
|
+
*/
|
|
72
|
+
onPolicyDecision?: (request: NextRequest, decision: PolicyEvaluationResult, context: PolicyEvaluationContext) => void | Promise<void>;
|
|
73
|
+
/**
|
|
74
|
+
* Custom response builder for blocked requests
|
|
75
|
+
*/
|
|
76
|
+
customBlockedResponse?: (request: NextRequest, decision: PolicyEvaluationResult) => NextResponse | Promise<NextResponse>;
|
|
77
|
+
/**
|
|
78
|
+
* Whether to fail open (allow) on policy evaluation errors
|
|
79
|
+
* Default: true (recommended for production)
|
|
80
|
+
*/
|
|
81
|
+
failOpen?: boolean;
|
|
82
|
+
/**
|
|
83
|
+
* Enable debug logging
|
|
84
|
+
*/
|
|
85
|
+
debug?: boolean;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Combined middleware configuration with policy support
|
|
89
|
+
*/
|
|
90
|
+
interface NextJSPolicyMiddlewareConfig extends PolicyMiddlewareConfig {
|
|
91
|
+
/**
|
|
92
|
+
* Paths to skip (in addition to policy excludedPaths)
|
|
93
|
+
*/
|
|
94
|
+
skipPaths?: string[];
|
|
95
|
+
/**
|
|
96
|
+
* Only enforce on these paths (overrides policy includedPaths)
|
|
97
|
+
*/
|
|
98
|
+
includePaths?: string[];
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Create policy evaluation context from detection result and request
|
|
102
|
+
*/
|
|
103
|
+
declare function createContextFromDetection(detection: DetectionResult, request: NextRequest): PolicyEvaluationContext;
|
|
104
|
+
/**
|
|
105
|
+
* Evaluate policy for a detection result
|
|
106
|
+
*/
|
|
107
|
+
declare function evaluatePolicyForDetection(detection: DetectionResult, request: NextRequest, policy: PolicyConfig): PolicyEvaluationResult;
|
|
108
|
+
/**
|
|
109
|
+
* Build blocked response based on policy decision
|
|
110
|
+
*/
|
|
111
|
+
declare function buildBlockedResponse(decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig): NextResponse;
|
|
112
|
+
/**
|
|
113
|
+
* Build redirect response based on policy decision
|
|
114
|
+
*/
|
|
115
|
+
declare function buildRedirectResponse(request: NextRequest, decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig, detection?: {
|
|
116
|
+
detectedAgent?: {
|
|
117
|
+
name?: string;
|
|
118
|
+
};
|
|
119
|
+
}): NextResponse;
|
|
120
|
+
/**
|
|
121
|
+
* Build challenge response (placeholder - future implementation)
|
|
122
|
+
*/
|
|
123
|
+
declare function buildChallengeResponse(request: NextRequest, decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig, detection?: {
|
|
124
|
+
detectedAgent?: {
|
|
125
|
+
name?: string;
|
|
126
|
+
};
|
|
127
|
+
}): NextResponse;
|
|
128
|
+
/**
|
|
129
|
+
* Handle policy decision and return appropriate response
|
|
130
|
+
*/
|
|
131
|
+
declare function handlePolicyDecision(request: NextRequest, decision: PolicyEvaluationResult, config: PolicyMiddlewareConfig, detection?: {
|
|
132
|
+
detectedAgent?: {
|
|
133
|
+
name?: string;
|
|
134
|
+
};
|
|
135
|
+
}): Promise<NextResponse | null>;
|
|
136
|
+
/**
|
|
137
|
+
* Get policy (local, fetched, or fallback)
|
|
138
|
+
*/
|
|
139
|
+
declare function getPolicy(config: PolicyMiddlewareConfig): Promise<PolicyConfig>;
|
|
140
|
+
/**
|
|
141
|
+
* Apply policy to a detection result
|
|
142
|
+
*
|
|
143
|
+
* This function can be used standalone to evaluate policy after detection.
|
|
144
|
+
* Supports extended config with skipPaths and includePaths for path-based filtering.
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* ```typescript
|
|
148
|
+
* const result = await detector.analyze(context);
|
|
149
|
+
* const response = await applyPolicy(request, result, {
|
|
150
|
+
* policy: { thresholds: { confidenceThreshold: 80 } },
|
|
151
|
+
* skipPaths: ['/health', '/api/public/*'],
|
|
152
|
+
* includePaths: ['/api/*'],
|
|
153
|
+
* });
|
|
154
|
+
*
|
|
155
|
+
* if (response) {
|
|
156
|
+
* return response; // Policy blocked the request
|
|
157
|
+
* }
|
|
158
|
+
* ```
|
|
159
|
+
*/
|
|
160
|
+
declare function applyPolicy(request: NextRequest, detection: DetectionResult, config: NextJSPolicyMiddlewareConfig): Promise<NextResponse | null>;
|
|
161
|
+
|
|
162
|
+
export { type NextJSPolicyMiddlewareConfig, type PolicyMiddlewareConfig, applyPolicy, buildBlockedResponse, buildChallengeResponse, buildRedirectResponse, createContextFromDetection, evaluatePolicyForDetection, getPolicy, handlePolicyDecision };
|