@aumos/agentshield 0.1.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 ADDED
@@ -0,0 +1,139 @@
1
+ # @aumos/agentshield
2
+
3
+ TypeScript client for the [AumOS AgentShield](https://github.com/invincible-jha/agentshield)
4
+ defense layer. Scan agent inputs and outputs for prompt-injection, PII, and malicious
5
+ payloads — and validate tool calls before execution.
6
+
7
+ ## Requirements
8
+
9
+ - Node.js 18+ (uses native Fetch API)
10
+ - TypeScript 5.3+ (strict mode)
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ npm install @aumos/agentshield
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ### HTTP client
21
+
22
+ ```ts
23
+ import { createAgentShieldClient } from "@aumos/agentshield";
24
+
25
+ const client = createAgentShieldClient({
26
+ baseUrl: "http://localhost:8091",
27
+ timeoutMs: 10_000,
28
+ });
29
+
30
+ // Scan an incoming user message
31
+ const inputScan = await client.scanInput({
32
+ agent_id: "my-agent",
33
+ content: userMessage,
34
+ session_id: "session-abc123",
35
+ });
36
+
37
+ if (inputScan.ok && inputScan.data.blocked) {
38
+ console.warn("Input blocked. Findings:", inputScan.data.findings);
39
+ // Do not forward the message to the LLM.
40
+ }
41
+
42
+ // Scan an LLM response before returning it to the user
43
+ const outputScan = await client.scanOutput({
44
+ agent_id: "my-agent",
45
+ content: llmResponse,
46
+ session_id: "session-abc123",
47
+ });
48
+
49
+ // Validate a tool call before execution
50
+ const toolCheck = await client.validateToolCall({
51
+ agent_id: "my-agent",
52
+ tool_name: "web_search",
53
+ tool_arguments: { query: userQuery },
54
+ session_id: "session-abc123",
55
+ });
56
+
57
+ if (toolCheck.ok && !toolCheck.data.allowed) {
58
+ console.warn("Tool call blocked:", toolCheck.data.block_reason);
59
+ }
60
+
61
+ // Retrieve aggregated threat report
62
+ const report = await client.getThreatReport({
63
+ agentId: "my-agent",
64
+ windowStart: "2026-02-01T00:00:00Z",
65
+ windowEnd: "2026-02-28T23:59:59Z",
66
+ });
67
+ if (report.ok) {
68
+ console.log("Blocked scans:", report.data.blocked_count);
69
+ }
70
+ ```
71
+
72
+ ### Local input scanner (no network required)
73
+
74
+ ```ts
75
+ import { createInputScanner } from "@aumos/agentshield";
76
+
77
+ const scanner = createInputScanner();
78
+ const options = { agentId: "my-agent", sessionId: "session-abc123" };
79
+
80
+ // Check for prompt injection
81
+ const injectionFindings = scanner.checkPromptInjection(userInput, options);
82
+ if (injectionFindings.length > 0) {
83
+ console.warn("Injection attempt detected:", injectionFindings[0].rule_id);
84
+ }
85
+
86
+ // Check for PII
87
+ const piiFindings = scanner.checkPII(llmOutput, options);
88
+
89
+ // Check for malicious payloads
90
+ const payloadFindings = scanner.checkMaliciousPayload(toolResult, options);
91
+
92
+ // Run all checks at once (sorted by severity)
93
+ const allFindings = scanner.scanAll(content, options);
94
+ for (const finding of allFindings) {
95
+ console.log(`[${finding.level}] ${finding.rule_id}: ${finding.description}`);
96
+ }
97
+ ```
98
+
99
+ ## API reference
100
+
101
+ ### `createAgentShieldClient(config)`
102
+
103
+ | Option | Type | Default | Description |
104
+ |--------|------|---------|-------------|
105
+ | `baseUrl` | `string` | required | AgentShield server URL |
106
+ | `timeoutMs` | `number` | `10000` | Request timeout (ms) |
107
+ | `headers` | `Record<string, string>` | `{}` | Extra HTTP headers |
108
+
109
+ #### Methods
110
+
111
+ | Method | Description |
112
+ |--------|-------------|
113
+ | `scanInput(request)` | Scan content arriving as agent input |
114
+ | `scanOutput(request)` | Scan content produced as agent output |
115
+ | `getThreatReport(options)` | Aggregated threat statistics for an agent |
116
+ | `validateToolCall(request)` | Validate a tool call before execution |
117
+
118
+ ### `createInputScanner()`
119
+
120
+ | Method | Description |
121
+ |--------|-------------|
122
+ | `checkPromptInjection(text, options)` | Detect instruction-override patterns |
123
+ | `checkPII(text, options)` | Detect email, SSN, credit-card, phone, IP |
124
+ | `checkMaliciousPayload(text, options)` | Detect shell injection, SQL injection, path traversal |
125
+ | `scanAll(text, options)` | Run all checks, results sorted by severity |
126
+
127
+ ### Threat levels
128
+
129
+ | Level | Description |
130
+ |-------|-------------|
131
+ | `critical` | Immediate block recommended (jailbreak, SSN, shell injection) |
132
+ | `high` | Block recommended (instruction override, SQL injection) |
133
+ | `medium` | Review recommended (role-switch, base64 obfuscation) |
134
+ | `low` | Log and monitor (phone numbers) |
135
+ | `info` | Informational only (IP addresses) |
136
+
137
+ ## License
138
+
139
+ Apache-2.0. See [LICENSE](../../LICENSE) for details.
@@ -0,0 +1,87 @@
1
+ /**
2
+ * HTTP client for the AgentShield defense API.
3
+ *
4
+ * Uses the Fetch API (available natively in Node 18+, browsers, and Deno).
5
+ * No external dependencies required.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { createAgentShieldClient } from "@aumos/agentshield";
10
+ *
11
+ * const client = createAgentShieldClient({ baseUrl: "http://localhost:8091" });
12
+ *
13
+ * const result = await client.scanInput({
14
+ * agent_id: "my-agent",
15
+ * content: userMessage,
16
+ * session_id: "session-abc",
17
+ * });
18
+ *
19
+ * if (result.ok && result.data.blocked) {
20
+ * console.warn("Input blocked:", result.data.findings);
21
+ * }
22
+ * ```
23
+ */
24
+ import type { ApiResult, ScanResult, ThreatDetectionResult, ToolCallValidationRequest, ToolCallValidationResult } from "./types.js";
25
+ /** Configuration options for the AgentShieldClient. */
26
+ export interface AgentShieldClientConfig {
27
+ /** Base URL of the AgentShield server (e.g. "http://localhost:8091"). */
28
+ readonly baseUrl: string;
29
+ /** Optional request timeout in milliseconds (default: 10000). */
30
+ readonly timeoutMs?: number;
31
+ /** Optional extra HTTP headers sent with every request. */
32
+ readonly headers?: Readonly<Record<string, string>>;
33
+ }
34
+ /** Request body for input or output scanning. */
35
+ export interface ContentScanRequest {
36
+ /** Agent that produced or received the content. */
37
+ readonly agent_id: string;
38
+ /** Raw content string to scan. */
39
+ readonly content: string;
40
+ /** Optional session context. */
41
+ readonly session_id?: string;
42
+ /** Arbitrary metadata forwarded to rule implementations. */
43
+ readonly metadata?: Readonly<Record<string, unknown>>;
44
+ }
45
+ /** Typed HTTP client for the AgentShield defense server. */
46
+ export interface AgentShieldClient {
47
+ /**
48
+ * Scan content arriving as agent input (e.g. user messages, tool results).
49
+ *
50
+ * @param request - Content and context to scan.
51
+ * @returns ScanResult with findings and a blocked flag.
52
+ */
53
+ scanInput(request: ContentScanRequest): Promise<ApiResult<ScanResult>>;
54
+ /**
55
+ * Scan content produced as agent output (e.g. LLM responses, tool invocations).
56
+ *
57
+ * @param request - Content and context to scan.
58
+ * @returns ScanResult with findings and a blocked flag.
59
+ */
60
+ scanOutput(request: ContentScanRequest): Promise<ApiResult<ScanResult>>;
61
+ /**
62
+ * Retrieve aggregated threat detection statistics for an agent.
63
+ *
64
+ * @param options - Agent and optional time-window filters.
65
+ * @returns ThreatDetectionResult summarising threat activity.
66
+ */
67
+ getThreatReport(options: {
68
+ agentId: string;
69
+ windowStart?: string;
70
+ windowEnd?: string;
71
+ }): Promise<ApiResult<ThreatDetectionResult>>;
72
+ /**
73
+ * Validate a proposed tool call before it is executed.
74
+ *
75
+ * @param request - Tool name, arguments, and calling-agent context.
76
+ * @returns ToolCallValidationResult indicating whether execution is permitted.
77
+ */
78
+ validateToolCall(request: ToolCallValidationRequest): Promise<ApiResult<ToolCallValidationResult>>;
79
+ }
80
+ /**
81
+ * Create a typed HTTP client for the AgentShield server.
82
+ *
83
+ * @param config - Client configuration including base URL.
84
+ * @returns An AgentShieldClient instance.
85
+ */
86
+ export declare function createAgentShieldClient(config: AgentShieldClientConfig): AgentShieldClient;
87
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAEV,SAAS,EACT,UAAU,EACV,qBAAqB,EACrB,yBAAyB,EACzB,wBAAwB,EACzB,MAAM,YAAY,CAA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;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,uBAAuB,GAC9B,iBAAiB,CAkEnB"}
package/dist/client.js ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * HTTP client for the AgentShield defense API.
3
+ *
4
+ * Uses the Fetch API (available natively in Node 18+, browsers, and Deno).
5
+ * No external dependencies required.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { createAgentShieldClient } from "@aumos/agentshield";
10
+ *
11
+ * const client = createAgentShieldClient({ baseUrl: "http://localhost:8091" });
12
+ *
13
+ * const result = await client.scanInput({
14
+ * agent_id: "my-agent",
15
+ * content: userMessage,
16
+ * session_id: "session-abc",
17
+ * });
18
+ *
19
+ * if (result.ok && result.data.blocked) {
20
+ * console.warn("Input blocked:", result.data.findings);
21
+ * }
22
+ * ```
23
+ */
24
+ // ---------------------------------------------------------------------------
25
+ // Internal helpers
26
+ // ---------------------------------------------------------------------------
27
+ async function fetchJson(url, init, timeoutMs) {
28
+ const controller = new AbortController();
29
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
30
+ try {
31
+ const response = await fetch(url, { ...init, signal: controller.signal });
32
+ clearTimeout(timeoutId);
33
+ const body = await response.json();
34
+ if (!response.ok) {
35
+ const errorBody = body;
36
+ return {
37
+ ok: false,
38
+ error: {
39
+ error: errorBody.error ?? "Unknown error",
40
+ detail: errorBody.detail ?? "",
41
+ },
42
+ status: response.status,
43
+ };
44
+ }
45
+ return { ok: true, data: body };
46
+ }
47
+ catch (err) {
48
+ clearTimeout(timeoutId);
49
+ const message = err instanceof Error ? err.message : String(err);
50
+ return {
51
+ ok: false,
52
+ error: { error: "Network error", detail: message },
53
+ status: 0,
54
+ };
55
+ }
56
+ }
57
+ function buildHeaders(extraHeaders) {
58
+ return {
59
+ "Content-Type": "application/json",
60
+ Accept: "application/json",
61
+ ...extraHeaders,
62
+ };
63
+ }
64
+ // ---------------------------------------------------------------------------
65
+ // Client factory
66
+ // ---------------------------------------------------------------------------
67
+ /**
68
+ * Create a typed HTTP client for the AgentShield server.
69
+ *
70
+ * @param config - Client configuration including base URL.
71
+ * @returns An AgentShieldClient instance.
72
+ */
73
+ export function createAgentShieldClient(config) {
74
+ const { baseUrl, timeoutMs = 10_000, headers: extraHeaders } = config;
75
+ const baseHeaders = buildHeaders(extraHeaders);
76
+ return {
77
+ async scanInput(request) {
78
+ return fetchJson(`${baseUrl}/scan/input`, {
79
+ method: "POST",
80
+ headers: baseHeaders,
81
+ body: JSON.stringify(request),
82
+ }, timeoutMs);
83
+ },
84
+ async scanOutput(request) {
85
+ return fetchJson(`${baseUrl}/scan/output`, {
86
+ method: "POST",
87
+ headers: baseHeaders,
88
+ body: JSON.stringify(request),
89
+ }, timeoutMs);
90
+ },
91
+ async getThreatReport(options) {
92
+ const params = new URLSearchParams({ agent_id: options.agentId });
93
+ if (options.windowStart !== undefined) {
94
+ params.set("window_start", options.windowStart);
95
+ }
96
+ if (options.windowEnd !== undefined) {
97
+ params.set("window_end", options.windowEnd);
98
+ }
99
+ return fetchJson(`${baseUrl}/threats/report?${params.toString()}`, { method: "GET", headers: baseHeaders }, timeoutMs);
100
+ },
101
+ async validateToolCall(request) {
102
+ return fetchJson(`${baseUrl}/validate/tool-call`, {
103
+ method: "POST",
104
+ headers: baseHeaders,
105
+ body: JSON.stringify(request),
106
+ }, timeoutMs);
107
+ },
108
+ };
109
+ }
110
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAyCH,8EAA8E;AAC9E,mBAAmB;AACnB,8EAA8E;AAE9E,KAAK,UAAU,SAAS,CACtB,GAAW,EACX,IAAiB,EACjB,SAAiB;IAEjB,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;IACzC,MAAM,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EA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,KAAK,CAAC,gBAAgB,CACpB,OAAkC;YAElC,OAAO,SAAS,CACd,GAAG,OAAO,qBAAqB,EAC/B;gBACE,MAAM,EAAE,MAAM;gBACd,OAAO,EAAE,WAAW;gBACpB,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;aAC9B,EACD,SAAS,CACV,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @aumos/agentshield
3
+ *
4
+ * TypeScript client for the AumOS AgentShield defense layer.
5
+ * Provides HTTP client, synchronous input scanner, and threat-detection type definitions.
6
+ */
7
+ export type { AgentShieldClient, AgentShieldClientConfig, ContentScanRequest } from "./client.js";
8
+ export { createAgentShieldClient } from "./client.js";
9
+ export type { ThreatLevel, DefenseLayer, ThreatFinding, ScanResult, ThreatDetectionResult, ToolCallValidationRequest, ToolCallValidationResult, ApiError, ApiResult, } from "./types.js";
10
+ export type { InputScanner, ScanOptions } from "./scanner.js";
11
+ export { createInputScanner } from "./scanner.js";
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,YAAY,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAClG,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,YAAY,EACV,WAAW,EACX,YAAY,EACZ,aAAa,EACb,UAAU,EACV,qBAAqB,EACrB,yBAAyB,EACzB,wBAAwB,EACxB,QAAQ,EACR,SAAS,GACV,MAAM,YAAY,CAAC;AAGpB,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @aumos/agentshield
3
+ *
4
+ * TypeScript client for the AumOS AgentShield defense layer.
5
+ * Provides HTTP client, synchronous input scanner, and threat-detection type definitions.
6
+ */
7
+ export { createAgentShieldClient } from "./client.js";
8
+ export { createInputScanner } from "./scanner.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAiBtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * InputScanner — pure, synchronous content-scanning utilities.
3
+ *
4
+ * These functions operate on plain strings and return typed finding arrays.
5
+ * They do not make network calls and have no side effects.
6
+ *
7
+ * Defensive-only framing: detects patterns associated with known attack
8
+ * categories so that the caller can decide whether to block or log.
9
+ */
10
+ import type { ThreatFinding } from "./types.js";
11
+ /** Options shared by all scanner methods. */
12
+ export interface ScanOptions {
13
+ /** Agent performing or receiving the content. */
14
+ readonly agentId: string;
15
+ /** Optional session context passed through to findings metadata. */
16
+ readonly sessionId?: string;
17
+ }
18
+ /** Synchronous content-scanning utilities. */
19
+ export interface InputScanner {
20
+ /**
21
+ * Detect prompt-injection patterns in the given text.
22
+ *
23
+ * @param text - Raw input string to analyse.
24
+ * @param options - Agent and session context.
25
+ * @returns Array of ThreatFindings for any injection patterns found.
26
+ */
27
+ checkPromptInjection(text: string, options: ScanOptions): readonly ThreatFinding[];
28
+ /**
29
+ * Detect personally identifiable information in the given text.
30
+ *
31
+ * @param text - Raw content string to analyse.
32
+ * @param options - Agent and session context.
33
+ * @returns Array of ThreatFindings for any PII patterns found.
34
+ */
35
+ checkPII(text: string, options: ScanOptions): readonly ThreatFinding[];
36
+ /**
37
+ * Detect indicators of malicious payloads in the given text.
38
+ *
39
+ * @param text - Raw content string to analyse.
40
+ * @param options - Agent and session context.
41
+ * @returns Array of ThreatFindings for any suspicious patterns found.
42
+ */
43
+ checkMaliciousPayload(text: string, options: ScanOptions): readonly ThreatFinding[];
44
+ /**
45
+ * Run all checks and return the combined, deduplicated findings list
46
+ * sorted by severity (critical first).
47
+ *
48
+ * @param text - Raw content string to analyse.
49
+ * @param options - Agent and session context.
50
+ * @returns All findings across all defense layers.
51
+ */
52
+ scanAll(text: string, options: ScanOptions): readonly ThreatFinding[];
53
+ }
54
+ /**
55
+ * Create an InputScanner instance.
56
+ *
57
+ * @returns An InputScanner with all check methods.
58
+ */
59
+ export declare function createInputScanner(): InputScanner;
60
+ //# sourceMappingURL=scanner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scanner.d.ts","sourceRoot":"","sources":["../src/scanner.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAgB,aAAa,EAAe,MAAM,YAAY,CAAC;AAM3E,6CAA6C;AAC7C,MAAM,WAAW,WAAW;IAC1B,iDAAiD;IACjD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,oEAAoE;IACpE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AAkND,8CAA8C;AAC9C,MAAM,WAAW,YAAY;IAC3B;;;;;;OAMG;IACH,oBAAoB,CAClB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,WAAW,GACnB,SAAS,aAAa,EAAE,CAAC;IAE5B;;;;;;OAMG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,SAAS,aAAa,EAAE,CAAC;IAEvE;;;;;;OAMG;IACH,qBAAqB,CACnB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,WAAW,GACnB,SAAS,aAAa,EAAE,CAAC;IAE5B;;;;;;;OAOG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,SAAS,aAAa,EAAE,CAAC;CACvE;AAkBD;;;;GAIG;AACH,wBAAgB,kBAAkB,IAAI,YAAY,CAsCjD"}
@@ -0,0 +1,208 @@
1
+ /**
2
+ * InputScanner — pure, synchronous content-scanning utilities.
3
+ *
4
+ * These functions operate on plain strings and return typed finding arrays.
5
+ * They do not make network calls and have no side effects.
6
+ *
7
+ * Defensive-only framing: detects patterns associated with known attack
8
+ * categories so that the caller can decide whether to block or log.
9
+ */
10
+ // ---------------------------------------------------------------------------
11
+ // Internal helpers
12
+ // ---------------------------------------------------------------------------
13
+ let findingIdCounter = 0;
14
+ function nextFindingId() {
15
+ findingIdCounter += 1;
16
+ return `finding-${Date.now()}-${findingIdCounter}`;
17
+ }
18
+ function buildFinding(layer, level, ruleId, description, text, offset, metadata) {
19
+ // Produce a redacted excerpt — never expose the raw payload.
20
+ const excerpt = text.length > 80
21
+ ? `${text.slice(0, 40)}...[redacted]...${text.slice(-20)}`
22
+ : text.replace(/./g, "*");
23
+ return {
24
+ finding_id: nextFindingId(),
25
+ layer,
26
+ level,
27
+ rule_id: ruleId,
28
+ description,
29
+ offset,
30
+ excerpt,
31
+ metadata,
32
+ };
33
+ }
34
+ // ---------------------------------------------------------------------------
35
+ // Prompt-injection detection patterns
36
+ // ---------------------------------------------------------------------------
37
+ /**
38
+ * Patterns that signal an attempt to override system instructions.
39
+ * Each entry is [ruleId, description, pattern, level].
40
+ */
41
+ const PROMPT_INJECTION_RULES = [
42
+ [
43
+ "PI-001",
44
+ "Instruction-override attempt detected",
45
+ /ignore\s+(all\s+)?previous\s+instructions?/i,
46
+ "high",
47
+ ],
48
+ [
49
+ "PI-002",
50
+ "System-prompt disclosure request detected",
51
+ /reveal\s+(your\s+)?(system\s+)?prompt/i,
52
+ "high",
53
+ ],
54
+ [
55
+ "PI-003",
56
+ "Role-switch injection attempt detected",
57
+ /you\s+are\s+now\s+(a|an)\s+\w/i,
58
+ "medium",
59
+ ],
60
+ [
61
+ "PI-004",
62
+ "Jailbreak keyword detected",
63
+ /\b(jailbreak|dan\s+mode|developer\s+mode)\b/i,
64
+ "critical",
65
+ ],
66
+ [
67
+ "PI-005",
68
+ "Fake-completion injection pattern detected",
69
+ /<\/?(?:system|assistant|user)\s*>/i,
70
+ "high",
71
+ ],
72
+ ];
73
+ // ---------------------------------------------------------------------------
74
+ // PII detection patterns
75
+ // ---------------------------------------------------------------------------
76
+ /**
77
+ * Patterns for common PII categories.
78
+ * Each entry is [ruleId, description, pattern, level].
79
+ */
80
+ const PII_RULES = [
81
+ [
82
+ "PII-EMAIL",
83
+ "Email address detected",
84
+ /\b[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}\b/,
85
+ "medium",
86
+ ],
87
+ [
88
+ "PII-SSN",
89
+ "US Social Security Number pattern detected",
90
+ /\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b/,
91
+ "critical",
92
+ ],
93
+ [
94
+ "PII-CREDIT-CARD",
95
+ "Credit card number pattern detected",
96
+ /\b(?:\d[ -]?){13,16}\b/,
97
+ "critical",
98
+ ],
99
+ [
100
+ "PII-PHONE",
101
+ "Phone number pattern detected",
102
+ /\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/,
103
+ "low",
104
+ ],
105
+ [
106
+ "PII-IP-ADDRESS",
107
+ "IP address detected",
108
+ /\b(?:\d{1,3}\.){3}\d{1,3}\b/,
109
+ "info",
110
+ ],
111
+ ];
112
+ // ---------------------------------------------------------------------------
113
+ // Malicious payload patterns
114
+ // ---------------------------------------------------------------------------
115
+ /**
116
+ * Patterns for known malicious payload indicators.
117
+ * Defensive framing: these detect encoded or obfuscated content.
118
+ * Each entry is [ruleId, description, pattern, level].
119
+ */
120
+ const MALICIOUS_PAYLOAD_RULES = [
121
+ [
122
+ "MPL-001",
123
+ "Base64-encoded block detected — possible payload obfuscation",
124
+ /\b[A-Za-z0-9+/]{40,}={0,2}\b/,
125
+ "medium",
126
+ ],
127
+ [
128
+ "MPL-002",
129
+ "Shell command injection pattern detected",
130
+ /(?:;\s*(?:rm|curl|wget|bash|sh|python|perl|nc)\b|&&\s*(?:rm|curl|wget|bash|sh)\b)/i,
131
+ "critical",
132
+ ],
133
+ [
134
+ "MPL-003",
135
+ "SQL injection pattern detected",
136
+ /(?:';\s*(?:drop|delete|update|insert|select)\b|--\s*$|\bUNION\s+SELECT\b)/i,
137
+ "critical",
138
+ ],
139
+ [
140
+ "MPL-004",
141
+ "Path traversal pattern detected",
142
+ /(?:\.\.\/|\.\.\\){2,}/,
143
+ "high",
144
+ ],
145
+ [
146
+ "MPL-005",
147
+ "Excessive token repetition detected — possible resource-exhaustion attempt",
148
+ /(\b\w+\b)(?:\s+\1){20,}/i,
149
+ "medium",
150
+ ],
151
+ ];
152
+ // ---------------------------------------------------------------------------
153
+ // Generic pattern-matching runner
154
+ // ---------------------------------------------------------------------------
155
+ function runPatternRules(text, rules, layer, options) {
156
+ const findings = [];
157
+ for (const [ruleId, description, pattern, level] of rules) {
158
+ const match = pattern.exec(text);
159
+ if (match !== null) {
160
+ findings.push(buildFinding(layer, level, ruleId, description, match[0], match.index, {
161
+ agent_id: options.agentId,
162
+ session_id: options.sessionId ?? null,
163
+ match_length: match[0].length,
164
+ }));
165
+ }
166
+ }
167
+ return findings;
168
+ }
169
+ // ---------------------------------------------------------------------------
170
+ // Severity ordering helper
171
+ // ---------------------------------------------------------------------------
172
+ const THREAT_LEVEL_ORDER = {
173
+ critical: 0,
174
+ high: 1,
175
+ medium: 2,
176
+ low: 3,
177
+ info: 4,
178
+ };
179
+ // ---------------------------------------------------------------------------
180
+ // Factory
181
+ // ---------------------------------------------------------------------------
182
+ /**
183
+ * Create an InputScanner instance.
184
+ *
185
+ * @returns An InputScanner with all check methods.
186
+ */
187
+ export function createInputScanner() {
188
+ return {
189
+ checkPromptInjection(text, options) {
190
+ return runPatternRules(text, PROMPT_INJECTION_RULES, "prompt_injection", options);
191
+ },
192
+ checkPII(text, options) {
193
+ return runPatternRules(text, PII_RULES, "pii_detection", options);
194
+ },
195
+ checkMaliciousPayload(text, options) {
196
+ return runPatternRules(text, MALICIOUS_PAYLOAD_RULES, "malicious_payload", options);
197
+ },
198
+ scanAll(text, options) {
199
+ const all = [
200
+ ...runPatternRules(text, PROMPT_INJECTION_RULES, "prompt_injection", options),
201
+ ...runPatternRules(text, PII_RULES, "pii_detection", options),
202
+ ...runPatternRules(text, MALICIOUS_PAYLOAD_RULES, "malicious_payload", options),
203
+ ];
204
+ return all.sort((a, b) => THREAT_LEVEL_ORDER[a.level] - THREAT_LEVEL_ORDER[b.level]);
205
+ },
206
+ };
207
+ }
208
+ //# sourceMappingURL=scanner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scanner.js","sourceRoot":"","sources":["../src/scanner.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAgBH,8EAA8E;AAC9E,mBAAmB;AACnB,8EAA8E;AAE9E,IAAI,gBAAgB,GAAG,CAAC,CAAC;AAEzB,SAAS,aAAa;IACpB,gBAAgB,IAAI,CAAC,CAAC;IACtB,OAAO,WAAW,IAAI,CAAC,GAAG,EAAE,IAAI,gBAAgB,EAAE,CAAC;AACrD,CAAC;AAED,SAAS,YAAY,CACnB,KAAmB,EACnB,KAAkB,EAClB,MAAc,EACd,WAAmB,EACnB,IAAY,EACZ,MAAc,EACd,QAA2C;IAE3C,6DAA6D;IAC7D,MAAM,OAAO,GACX,IAAI,CAAC,MAAM,GAAG,EAAE;QACd,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,mBAAmB,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE;QAC1D,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IAE9B,OAAO;QACL,UAAU,EAAE,aAAa,EAAE;QAC3B,KAAK;QACL,KAAK;QACL,OAAO,EAAE,MAAM;QACf,WAAW;QACX,MAAM;QACN,OAAO;QACP,QAAQ;KACT,CAAC;AACJ,CA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