@secureai-sdk/sdk 1.2.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.
@@ -0,0 +1,129 @@
1
+ import { BotIngressResult, BotToolResult, BotEgressResult } from "./types";
2
+ import { inspectInput } from "./guard";
3
+
4
+ const CLEARANCE_RULES: Record<number, RegExp[]> = {
5
+ 1: [/^read_/i, /^search_/i, /^get_/i, /^lookup_/i, /^query_/i, /^fetch_/i],
6
+ 2: [/^post_tweet/i, /^reply_/i, /^send_dm/i, /^discord_reply/i, /^like_/i, /^retweet/i],
7
+ 3: [/^update_crm/i, /^create_ticket/i, /^send_email/i, /^charge_card/i, /^refund_/i],
8
+ 4: [/^deploy_/i, /^restart_/i, /^migrate_db/i, /^write_config/i, /^modify_user/i],
9
+ 5: [/^exec_bash/i, /^run_shell/i, /^system_/i, /^eval_/i, /^rm_/i, /^drop_table/i]
10
+ };
11
+
12
+ const SECRET_PATTERNS = [
13
+ { regex: /\b(?:sk-[a-zA-Z0-9]{20,})\b/g, label: "[REDACTED_OPENAI_KEY]" },
14
+ { regex: /\b(?:sec_live_[a-zA-Z0-9]{16,})\b/g, label: "[REDACTED_SECUREAI_KEY]" },
15
+ { regex: /\b(?:ghp_[a-zA-Z0-9]{36,})\b/g, label: "[REDACTED_GITHUB_PAT]" },
16
+ { regex: /\b(?:AKIA[0-9A-Z]{16})\b/g, label: "[REDACTED_AWS_KEY]" },
17
+ { regex: /\b(?:Bearer\s+[a-zA-Z0-9\-._~+/]+=*)\b/gi, label: "[REDACTED_BEARER_TOKEN]" },
18
+ { regex: /\b(?:postgres(?:ql)?:\/\/[^\s"']+)\b/gi, label: "[REDACTED_DATABASE_URL]" }
19
+ ];
20
+
21
+ export interface GrokBotOptions {
22
+ botId?: string;
23
+ clearanceLevel?: number;
24
+ apiKey?: string;
25
+ blockOnIngressInjection?: boolean;
26
+ }
27
+
28
+ export class GrokBotGuard {
29
+ public botId: string;
30
+ public clearanceLevel: number;
31
+ public apiKey?: string;
32
+ public blockOnIngressInjection: boolean;
33
+
34
+ constructor(options: GrokBotOptions = {}) {
35
+ this.botId = options.botId || "grok_bot";
36
+ this.clearanceLevel = options.clearanceLevel || 2;
37
+ this.apiKey = options.apiKey || process.env.SECUREAI_API_KEY;
38
+ this.blockOnIngressInjection = options.blockOnIngressInjection ?? true;
39
+
40
+ if (!this.apiKey) {
41
+ throw new Error(
42
+ `SecureAI Authentication Required for Bot '${this.botId}': No API key provided. ` +
43
+ `Pass apiKey or set SECUREAI_API_KEY environment variable. ` +
44
+ `Create a key at https://secure.acadmyai.com/console/apikeys`
45
+ );
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Stage 1: Pre-execution inspection & sanitization of untrusted public mentions or tweets.
51
+ */
52
+ public sanitizeMention(untrustedText: string): BotIngressResult {
53
+ const inspection = inspectInput(untrustedText);
54
+ return {
55
+ isSafe: inspection.isSafe,
56
+ sanitizedText: inspection.sanitizedText,
57
+ threatDetected: inspection.threatDetected,
58
+ riskScore: inspection.riskScore,
59
+ latencyMs: inspection.latencyMs,
60
+ matchedPatterns: inspection.matchedPatterns
61
+ };
62
+ }
63
+
64
+ /**
65
+ * Stage 2: Tool Action RBAC Firewall evaluating bot clearance levels.
66
+ * Returns synthetic error guidance on clearance denial to enable graceful model self-correction.
67
+ */
68
+ public interceptTool(toolName: string, params: Record<string, any> = {}): BotToolResult {
69
+ let requiredClearance = 3;
70
+ for (let level = 1; level <= 5; level++) {
71
+ const patterns = CLEARANCE_RULES[level] || [];
72
+ if (patterns.some((p) => p.test(toolName))) {
73
+ requiredClearance = level;
74
+ break;
75
+ }
76
+ }
77
+
78
+ if (requiredClearance > this.clearanceLevel) {
79
+ const syntheticError =
80
+ `[SecureAI Policy Clearance Denied]: Tool '${toolName}' requires Clearance Level ${requiredClearance}, ` +
81
+ `but bot '${this.botId}' operates at Level ${this.clearanceLevel}. ` +
82
+ `Action aborted. Please apologize to the user and explain that you do not have permission to execute this operation.`;
83
+
84
+ return {
85
+ allowed: false,
86
+ toolName,
87
+ requiredClearance,
88
+ botClearance: this.clearanceLevel,
89
+ syntheticError,
90
+ reason: `Clearance level ${this.clearanceLevel} insufficient for level ${requiredClearance} tool '${toolName}'`
91
+ };
92
+ }
93
+
94
+ return {
95
+ allowed: true,
96
+ toolName,
97
+ requiredClearance,
98
+ botClearance: this.clearanceLevel
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Stage 3: Outbound Egress DLP preventing credential leaks and exfiltration before tweet publication.
104
+ */
105
+ public sanitizeEgress(botResponseText: string): BotEgressResult {
106
+ const start = performance.now();
107
+ let sanitized = botResponseText;
108
+ let leaksRedacted = 0;
109
+ const redactedTypes: string[] = [];
110
+
111
+ for (const { regex, label } of SECRET_PATTERNS) {
112
+ if (regex.test(sanitized)) {
113
+ leaksRedacted++;
114
+ redactedTypes.push(label);
115
+ sanitized = sanitized.replace(regex, label);
116
+ }
117
+ }
118
+
119
+ const latencyMs = Math.round((performance.now() - start) * 1000) / 1000;
120
+
121
+ return {
122
+ isSafe: leaksRedacted === 0,
123
+ sanitizedText: sanitized,
124
+ leaksRedacted,
125
+ redactedTypes,
126
+ latencyMs
127
+ };
128
+ }
129
+ }
package/src/guard.ts ADDED
@@ -0,0 +1,119 @@
1
+ import { PromptInspectionResult } from "./types";
2
+
3
+ const ZERO_WIDTH_CHARS = [
4
+ "\u200B", "\u200C", "\u200D", "\uFEFF", "\u202E", "\u202D"
5
+ ];
6
+
7
+ export const FAST_INJECTION_PATTERNS: Array<{ regex: RegExp; category: string; score: number }> = [
8
+ {
9
+ regex: /\b(?:ignore|disregard|forget|skip|drop|override|bypass|disable|negate|cancel|erase)\s+(?:all\s+)?(?:(?:previous|prior|above|former|initial|system)\s+)?(?:instructions?|prompts?|rules?|commands?|guidelines?|context|constraints?|directives?|filters?|guardrails?)/i,
10
+ category: "DIRECT_OVERRIDE",
11
+ score: 0.96
12
+ },
13
+ {
14
+ regex: /\bignore\s+(?:all\s+)?(?:the\s+)?(?:previous|prior|above|safety|system)/i,
15
+ category: "DIRECT_OVERRIDE",
16
+ score: 0.95
17
+ },
18
+ {
19
+ regex: /\bnew\s+rule:\s*(?:ignore|disregard|forget|override)/i,
20
+ category: "DIRECT_OVERRIDE",
21
+ score: 0.92
22
+ },
23
+ {
24
+ regex: /\byou\s+are\s+now\s+(?:DAN|unfiltered|jailbroken|unrestricted|free\s+of\s+rules|an\s+adversary|in\s+developer\s+mode|in\s+god\s+mode)/i,
25
+ category: "JAILBREAK_ROLEPLAY",
26
+ score: 0.94
27
+ },
28
+ {
29
+ regex: /\bdo\s+anything\s+now\b/i,
30
+ category: "JAILBREAK_DAN",
31
+ score: 0.96
32
+ },
33
+ {
34
+ regex: /\bpretend\s+you\s+have\s+no\s+(?:safety|ethical|content)\s+filters?/i,
35
+ category: "JAILBREAK_SAFETY_BYPASS",
36
+ score: 0.90
37
+ },
38
+ {
39
+ regex: /\b(?:print|show|dump|reveal|output|display|repeat|leak)\s+(?:your\s+)?(?:system\s+prompts?|initial\s+instructions?|system\s+instructions?|core\s+rules?|internal\s+prompts?|credentials?|passwords?|api\s*keys?|secrets?)/i,
40
+ category: "SYSTEM_PROMPT_EXTRACTION",
41
+ score: 0.92
42
+ },
43
+ {
44
+ regex: /\b(?:delete|drop|wipe|purge|truncate|destroy)\s+(?:everything|all\s+data|all\s+tables|database|users?|system)\b/i,
45
+ category: "DESTRUCTIVE_DATABASE_EXECUTION",
46
+ score: 0.96
47
+ },
48
+ {
49
+ regex: /(?:union\s+select|select\s+.*\s+from\s+|insert\s+into\s+|drop\s+table|delete\s+from\s+|truncate\s+table|exec\s+sp_|xp_cmdshell|or\s+1\s*=\s*1|'\s*or\s*'1'\s*=\s*'1|--|\bwaitfor\s+delay\b)/i,
50
+ category: "SQLI_PARAMETER_INJECTION",
51
+ score: 0.96
52
+ },
53
+ {
54
+ regex: /\[system\s+override\]|<\s*system(?:\s+override)?\s*>|```\s*(?:system|override|admin)/i,
55
+ category: "SYNTHETIC_DELIMITER_INJECTION",
56
+ score: 0.94
57
+ }
58
+ ];
59
+
60
+ export const FAST_TOXICITY_RE = /\b(?:f+u+c+k+|s+h+i+t+|b+i+t+c+h+|asshole|kill\s+yourself|bomb\s+the|murder\s+you)\b/i;
61
+
62
+ export function normalizeInputText(text: string): string {
63
+ if (!text) return "";
64
+ let cleaned = text;
65
+ for (const char of ZERO_WIDTH_CHARS) {
66
+ cleaned = cleaned.split(char).join("");
67
+ }
68
+ return cleaned.normalize("NFKD");
69
+ }
70
+
71
+ export function inspectInput(prompt: string, threshold = 0.65): PromptInspectionResult {
72
+ const start = performance.now();
73
+ if (!prompt || typeof prompt !== "string") {
74
+ return {
75
+ isSafe: true,
76
+ action: "ALLOW",
77
+ riskScore: 0.0,
78
+ matchedPatterns: [],
79
+ sanitizedText: prompt || "",
80
+ latencyMs: 0.0
81
+ };
82
+ }
83
+
84
+ const normalized = normalizeInputText(prompt);
85
+ const matchedPatterns: string[] = [];
86
+ let maxRisk = 0.0;
87
+ let threatCategory: string | null = null;
88
+
89
+ for (const item of FAST_INJECTION_PATTERNS) {
90
+ if (item.regex.test(normalized) || item.regex.test(prompt)) {
91
+ matchedPatterns.push(item.category);
92
+ if (item.score > maxRisk) {
93
+ maxRisk = item.score;
94
+ threatCategory = item.category;
95
+ }
96
+ }
97
+ }
98
+
99
+ if (FAST_TOXICITY_RE.test(prompt)) {
100
+ matchedPatterns.push("VULGARITY_VIOLATION");
101
+ if (0.88 > maxRisk) {
102
+ maxRisk = 0.88;
103
+ threatCategory = "VULGARITY_VIOLATION";
104
+ }
105
+ }
106
+
107
+ const isSafe = maxRisk < threshold && matchedPatterns.length === 0;
108
+ const elapsedMs = Math.round((performance.now() - start) * 1000) / 1000;
109
+
110
+ return {
111
+ isSafe,
112
+ action: isSafe ? "ALLOW" : "BLOCK",
113
+ riskScore: maxRisk,
114
+ threatDetected: threatCategory,
115
+ matchedPatterns,
116
+ sanitizedText: isSafe ? prompt : `[BLOCKED_BY_SECUREAI: ${threatCategory}]`,
117
+ latencyMs: elapsedMs
118
+ };
119
+ }
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @secureai/sdk
3
+ * Enterprise AI Security, GrokBot Firewall, Agent Action Armor & Reversible PII Vault
4
+ * Powered by AcadmyAI (https://secure.acadmyai.com)
5
+ */
6
+
7
+ export * from "./types";
8
+ export * from "./guard";
9
+ export * from "./vault";
10
+ export * from "./grok-bot";
11
+ export * from "./client";
12
+ export * from "./mcp-proxy";
@@ -0,0 +1,94 @@
1
+ import { spawn } from "child_process";
2
+ import * as readline from "readline";
3
+
4
+ const SQLI_REGEX = /(?:union\s+select|drop\s+table|delete\s+from|insert\s+into|truncate\s+table|--|\bwaitfor\s+delay\b)/i;
5
+ const TRAVERSAL_REGEX = /(?:\.\.\/|\.\.\\|\/\.env|id_rsa|credentials)/i;
6
+
7
+ export interface MCPProxyOptions {
8
+ targetCommand: string;
9
+ targetArgs: string[];
10
+ apiKey?: string;
11
+ policy?: "read-only-strict" | "standard" | "developer";
12
+ }
13
+
14
+ export function startMCPProxy(options: MCPProxyOptions): void {
15
+ const apiKey = options.apiKey || process.env.SECUREAI_API_KEY;
16
+ if (!apiKey) {
17
+ process.stderr.write(
18
+ "[SecureAI MCP Proxy ERROR]: SECUREAI_API_KEY environment variable is required.\n" +
19
+ "Generate an API key at https://secure.acadmyai.com/console/apikeys\n"
20
+ );
21
+ process.exit(1);
22
+ }
23
+
24
+ process.stderr.write(
25
+ `[SecureAI MCP Proxy]: Zero-Trust interceptor active for '${options.targetCommand} ${options.targetArgs.join(" ")}'\n`
26
+ );
27
+
28
+ const targetProcess = spawn(options.targetCommand, options.targetArgs, {
29
+ stdio: ["pipe", "pipe", "inherit"],
30
+ env: process.env
31
+ });
32
+
33
+ // Intercept Agent -> MCP Target (stdin)
34
+ const rlStdin = readline.createInterface({
35
+ input: process.stdin,
36
+ output: process.stdout,
37
+ terminal: false
38
+ });
39
+
40
+ rlStdin.on("line", (line: string) => {
41
+ if (!line.trim()) return;
42
+ try {
43
+ const msg = JSON.parse(line);
44
+ if (msg.method === "tools/call") {
45
+ const toolName = msg.params?.name || "";
46
+ const argsStr = JSON.stringify(msg.params?.arguments || {});
47
+
48
+ // 1. SQL Injection Parameter Check
49
+ if (SQLI_REGEX.test(argsStr)) {
50
+ process.stderr.write(`[SecureAI MCP BLOCKED]: SQL Injection detected in tool '${toolName}' arguments.\n`);
51
+ const blockedResp = {
52
+ jsonrpc: "2.0",
53
+ id: msg.id,
54
+ error: {
55
+ code: -32000,
56
+ message: `SecureAI Policy Block: SQL Injection signature detected in parameters for tool '${toolName}'.`
57
+ }
58
+ };
59
+ process.stdout.write(JSON.stringify(blockedResp) + "\n");
60
+ return;
61
+ }
62
+
63
+ // 2. Path Traversal & Sensitive File Access Check
64
+ if (TRAVERSAL_REGEX.test(argsStr)) {
65
+ process.stderr.write(`[SecureAI MCP BLOCKED]: Path traversal or secret file access detected in tool '${toolName}'.\n`);
66
+ const blockedResp = {
67
+ jsonrpc: "2.0",
68
+ id: msg.id,
69
+ error: {
70
+ code: -32000,
71
+ message: `SecureAI Policy Block: Path traversal or unauthorized secret access forbidden in tool '${toolName}'.`
72
+ }
73
+ };
74
+ process.stdout.write(JSON.stringify(blockedResp) + "\n");
75
+ return;
76
+ }
77
+ }
78
+
79
+ // Forward sanitized command to target
80
+ targetProcess.stdin.write(line + "\n");
81
+ } catch {
82
+ targetProcess.stdin.write(line + "\n");
83
+ }
84
+ });
85
+
86
+ // Forward Target MCP -> Agent (stdout)
87
+ targetProcess.stdout.on("data", (chunk: Buffer | string) => {
88
+ process.stdout.write(chunk);
89
+ });
90
+
91
+ targetProcess.on("exit", (code: number | null) => {
92
+ process.exit(code ?? 0);
93
+ });
94
+ }
package/src/types.ts ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * SecureAI TypeScript SDK Types
3
+ * Enterprise AI Security, GrokBot Firewall, Agent Action Armor & Reversible PII Vault
4
+ */
5
+
6
+ export type ThreatSeverity = "CRITICAL" | "HIGH" | "MEDIUM" | "LOW" | "INFO";
7
+
8
+ export type SecurityAction = "ALLOW" | "BLOCK" | "REWRITE_SAFE" | "STEP_UP_HITL" | "ALLOW_WITH_TOKENIZATION";
9
+
10
+ export interface UserSecurityContext {
11
+ userId?: string;
12
+ role?: "admin" | "analyst" | "developer" | "guest";
13
+ department?: string;
14
+ clearanceLevel?: 1 | 2 | 3 | 4 | 5;
15
+ sessionId?: string;
16
+ }
17
+
18
+ export interface PromptInspectionResult {
19
+ isSafe: boolean;
20
+ action: SecurityAction;
21
+ riskScore: number;
22
+ threatDetected?: string | null;
23
+ matchedPatterns: string[];
24
+ sanitizedText: string;
25
+ latencyMs: number;
26
+ quota?: {
27
+ tier: string;
28
+ used: number;
29
+ limit: number;
30
+ remaining: number;
31
+ };
32
+ }
33
+
34
+ export interface BotIngressResult {
35
+ isSafe: boolean;
36
+ sanitizedText: string;
37
+ threatDetected?: string | null;
38
+ riskScore: number;
39
+ latencyMs: number;
40
+ matchedPatterns: string[];
41
+ }
42
+
43
+ export interface BotToolResult {
44
+ allowed: boolean;
45
+ toolName: string;
46
+ requiredClearance: number;
47
+ botClearance: number;
48
+ syntheticError?: string | null;
49
+ reason?: string | null;
50
+ }
51
+
52
+ export interface BotEgressResult {
53
+ isSafe: boolean;
54
+ sanitizedText: string;
55
+ leaksRedacted: number;
56
+ redactedTypes: string[];
57
+ latencyMs: number;
58
+ }
59
+
60
+ export interface AgentActionPayload {
61
+ actionType: "EXECUTE_SHELL" | "WRITE_FILE" | "READ_FILE" | "NETWORK_EGRESS";
62
+ target: string;
63
+ command?: string;
64
+ userContext?: UserSecurityContext;
65
+ }
66
+
67
+ export interface AgentActionVerdict {
68
+ verdict: SecurityAction;
69
+ isAllowed: boolean;
70
+ riskScore: number;
71
+ threatsDetected: string[];
72
+ rewrittenCommand?: string | null;
73
+ explanation?: string;
74
+ tamperProofSignature?: string;
75
+ }
76
+
77
+ export interface PIIVaultResult {
78
+ sanitizedText: string;
79
+ redactedCount: number;
80
+ tokenMap: Record<string, string>;
81
+ }
82
+
83
+ export interface ModelScanResult {
84
+ isSafe: boolean;
85
+ verdict: "SAFE" | "BLOCKED" | "MALICIOUS";
86
+ riskScore: number;
87
+ maliciousOpcodes: string[];
88
+ formatDetected: string;
89
+ explanation: string;
90
+ }
91
+
92
+ export interface ServiceConfigItem {
93
+ enabled: boolean;
94
+ mode?: string;
95
+ threshold?: number;
96
+ clearanceLevel?: number;
97
+ description?: string;
98
+ [key: string]: any;
99
+ }
100
+
101
+ export interface ServicesConfig {
102
+ prompt_injection_guard?: ServiceConfigItem;
103
+ pii_vault?: ServiceConfigItem;
104
+ agent_action_firewall?: ServiceConfigItem;
105
+ mcp_gateway?: ServiceConfigItem;
106
+ bot_firewall?: ServiceConfigItem;
107
+ rag_context_guard?: ServiceConfigItem;
108
+ grounding_scorer?: ServiceConfigItem;
109
+ model_scanner?: ServiceConfigItem;
110
+ canary_vault?: ServiceConfigItem;
111
+ toxicity_filter?: ServiceConfigItem;
112
+ semantic_cache?: ServiceConfigItem;
113
+ redteam_simulator?: ServiceConfigItem;
114
+ aspm_engine?: ServiceConfigItem;
115
+ aibom_generator?: ServiceConfigItem;
116
+ [key: string]: ServiceConfigItem | undefined;
117
+ }
118
+
119
+ export interface SecureAIClientOptions {
120
+ apiKey?: string;
121
+ baseUrl?: string;
122
+ timeoutMs?: number;
123
+ services?: ServicesConfig;
124
+ }
package/src/vault.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { PIIVaultResult } from "./types";
2
+
3
+ const PII_PATTERNS: Array<{ type: string; regex: RegExp }> = [
4
+ { type: "SSN", regex: /\b\d{3}-\d{2}-\d{4}\b/g },
5
+ { type: "CREDIT_CARD", regex: /\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})\b/g },
6
+ { type: "EMAIL", regex: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g },
7
+ { type: "PHONE", regex: /\b(?:\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g },
8
+ { type: "API_KEY", regex: /\b(?:sk-[a-zA-Z0-9]{20,}|sec_live_[a-zA-Z0-9]{16,}|ghp_[a-zA-Z0-9]{36,})\b/g }
9
+ ];
10
+
11
+ export class PIIVault {
12
+ public tokenize(text: string): PIIVaultResult {
13
+ if (!text) {
14
+ return { sanitizedText: "", redactedCount: 0, tokenMap: {} };
15
+ }
16
+
17
+ let sanitized = text;
18
+ const tokenMap: Record<string, string> = {};
19
+ let count = 0;
20
+
21
+ for (const { type, regex } of PII_PATTERNS) {
22
+ sanitized = sanitized.replace(regex, (match) => {
23
+ count++;
24
+ const token = `[SEC_${type}_${Math.random().toString(36).substring(2, 8).toUpperCase()}]`;
25
+ tokenMap[token] = match;
26
+ return token;
27
+ });
28
+ }
29
+
30
+ return {
31
+ sanitizedText: sanitized,
32
+ redactedCount: count,
33
+ tokenMap
34
+ };
35
+ }
36
+
37
+ public detokenize(text: string, tokenMap: Record<string, string>): string {
38
+ if (!text || !tokenMap) return text;
39
+ let restored = text;
40
+ for (const [token, original] of Object.entries(tokenMap)) {
41
+ restored = restored.split(token).join(original);
42
+ }
43
+ return restored;
44
+ }
45
+ }
46
+
47
+ export const defaultVault = new PIIVault();
package/tsconfig.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "CommonJS",
5
+ "moduleResolution": "Node",
6
+ "declaration": true,
7
+ "declarationMap": true,
8
+ "sourceMap": true,
9
+ "outDir": "./dist",
10
+ "rootDir": "./src",
11
+ "strict": true,
12
+ "esModuleInterop": true,
13
+ "skipLibCheck": true,
14
+ "forceConsistentCasingInFileNames": true,
15
+ "typeRoots": ["../../frontend/node_modules/@types"]
16
+ },
17
+ "include": ["src/**/*"]
18
+ }