promptguard-sdk 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,173 @@
1
+ # PromptGuard Node.js SDK
2
+
3
+ Drop-in security for AI applications. No code changes required.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install promptguard-sdk
9
+ # or
10
+ yarn add promptguard-sdk
11
+ # or
12
+ pnpm add promptguard-sdk
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { PromptGuard } from 'promptguard-sdk';
19
+
20
+ // Initialize client
21
+ const pg = new PromptGuard({ apiKey: 'pg_xxx' });
22
+
23
+ // Use exactly like OpenAI client
24
+ const response = await pg.chat.completions.create({
25
+ model: 'gpt-4',
26
+ messages: [{ role: 'user', content: 'Hello!' }]
27
+ });
28
+
29
+ console.log(response.choices[0].message.content);
30
+ ```
31
+
32
+ ## Drop-in Replacement
33
+
34
+ If you're already using OpenAI's Node.js client, just change the import:
35
+
36
+ ```typescript
37
+ // Before
38
+ import OpenAI from 'openai';
39
+ const client = new OpenAI();
40
+
41
+ // After
42
+ import { PromptGuard } from 'promptguard-sdk';
43
+ const client = new PromptGuard({ apiKey: 'pg_xxx' });
44
+
45
+ // Your existing code works unchanged!
46
+ ```
47
+
48
+ ## Features
49
+
50
+ ### Security Scanning
51
+
52
+ ```typescript
53
+ // Scan content for threats
54
+ const result = await pg.security.scan('Ignore previous instructions...');
55
+
56
+ if (result.blocked) {
57
+ console.log(`Threat detected: ${result.reason}`);
58
+ }
59
+ ```
60
+
61
+ ### PII Redaction
62
+
63
+ ```typescript
64
+ // Redact PII before sending to LLM
65
+ const result = await pg.security.redact(
66
+ 'My email is john@example.com and SSN is 123-45-6789'
67
+ );
68
+
69
+ console.log(result.redactedContent);
70
+ // Output: "My email is [EMAIL] and SSN is [SSN]"
71
+ ```
72
+
73
+ ### Secure Web Scraping
74
+
75
+ ```typescript
76
+ // Scan scraped content for indirect prompt injection
77
+ const result = await pg.scrape.scanUrl('https://example.com/article');
78
+
79
+ if (result.isSafe) {
80
+ // Use content safely
81
+ console.log(result.content);
82
+ } else {
83
+ console.log('Threats detected:', result.threats);
84
+ }
85
+ ```
86
+
87
+ ### AI Agent Security
88
+
89
+ ```typescript
90
+ // Validate tool calls before execution
91
+ const validation = await pg.agent.validateTool({
92
+ agentId: 'agent-123',
93
+ toolName: 'execute_shell',
94
+ arguments: { command: 'ls -la' }
95
+ });
96
+
97
+ if (validation.action === 'block') {
98
+ console.log(`Blocked: ${validation.reason}`);
99
+ }
100
+ ```
101
+
102
+ ## Configuration
103
+
104
+ ```typescript
105
+ import { PromptGuard, Config } from '@promptguard/sdk';
106
+
107
+ const config: Config = {
108
+ apiKey: 'pg_xxx',
109
+ baseUrl: 'https://api.promptguard.co/api/v1',
110
+ timeout: 30000,
111
+ enableCaching: true,
112
+ enableSecurityScan: true,
113
+ };
114
+
115
+ const pg = new PromptGuard(config);
116
+ ```
117
+
118
+ ## Environment Variables
119
+
120
+ ```bash
121
+ export PROMPTGUARD_API_KEY="pg_xxx"
122
+ export PROMPTGUARD_BASE_URL="https://api.promptguard.co/api/v1"
123
+ ```
124
+
125
+ Then just:
126
+
127
+ ```typescript
128
+ import { PromptGuard } from 'promptguard-sdk';
129
+
130
+ const pg = new PromptGuard(); // Uses env vars automatically
131
+ ```
132
+
133
+ ## Error Handling
134
+
135
+ ```typescript
136
+ import { PromptGuard, PromptGuardError } from '@promptguard/sdk';
137
+
138
+ try {
139
+ const response = await pg.chat.completions.create({...});
140
+ } catch (error) {
141
+ if (error instanceof PromptGuardError) {
142
+ if (error.code === 'BLOCKED') {
143
+ console.log(`Request blocked: ${error.message}`);
144
+ } else if (error.code === 'RATE_LIMITED') {
145
+ console.log('Rate limited, try again later');
146
+ }
147
+ }
148
+ throw error;
149
+ }
150
+ ```
151
+
152
+ ## TypeScript Support
153
+
154
+ Full TypeScript support with type definitions included.
155
+
156
+ ```typescript
157
+ import type {
158
+ ChatCompletionRequest,
159
+ ChatCompletionResponse,
160
+ SecurityScanResult
161
+ } from '@promptguard/sdk';
162
+ ```
163
+
164
+ ## Links
165
+
166
+ - [Documentation](https://docs.promptguard.co)
167
+ - [GitHub](https://github.com/acebot712/promptguard)
168
+ - [Issues](https://github.com/acebot712/promptguard/issues)
169
+
170
+ ## License
171
+
172
+ MIT
173
+
@@ -0,0 +1,197 @@
1
+ /**
2
+ * PromptGuard Node.js SDK
3
+ *
4
+ * Drop-in security for AI applications.
5
+ * Just change your base URL and add an API key.
6
+ *
7
+ * @example
8
+ * import { PromptGuard } from 'promptguard';
9
+ *
10
+ * const pg = new PromptGuard({ apiKey: 'pg_xxx' });
11
+ *
12
+ * const response = await pg.chat.completions.create({
13
+ * model: 'gpt-4',
14
+ * messages: [{ role: 'user', content: 'Hello!' }]
15
+ * });
16
+ */
17
+ export interface PromptGuardConfig {
18
+ apiKey: string;
19
+ baseUrl?: string;
20
+ timeout?: number;
21
+ enableCaching?: boolean;
22
+ enableSecurityScan?: boolean;
23
+ }
24
+ export interface Message {
25
+ role: "system" | "user" | "assistant";
26
+ content: string;
27
+ }
28
+ export interface ChatCompletionRequest {
29
+ model: string;
30
+ messages: Message[];
31
+ temperature?: number;
32
+ maxTokens?: number;
33
+ stream?: boolean;
34
+ [key: string]: unknown;
35
+ }
36
+ export interface ChatCompletionResponse {
37
+ id: string;
38
+ object: string;
39
+ created: number;
40
+ model: string;
41
+ choices: Array<{
42
+ index: number;
43
+ message: Message;
44
+ finish_reason: string;
45
+ }>;
46
+ usage?: {
47
+ prompt_tokens: number;
48
+ completion_tokens: number;
49
+ total_tokens: number;
50
+ };
51
+ }
52
+ export interface SecurityScanResult {
53
+ blocked: boolean;
54
+ decision: "allow" | "block" | "redact";
55
+ reason?: string;
56
+ threatType?: string;
57
+ confidence?: number;
58
+ }
59
+ export interface RedactResult {
60
+ original: string;
61
+ redacted: string;
62
+ piiFound: string[];
63
+ }
64
+ export interface MemoryEntry {
65
+ id: string;
66
+ content: string;
67
+ memoryType: string;
68
+ createdAt: number;
69
+ }
70
+ export interface MemoryRetrieveResult {
71
+ memories: MemoryEntry[];
72
+ formattedContext: string;
73
+ tokensSaved: number;
74
+ }
75
+ declare class ChatCompletions {
76
+ private client;
77
+ constructor(client: PromptGuard);
78
+ create(params: ChatCompletionRequest): Promise<ChatCompletionResponse>;
79
+ }
80
+ declare class Chat {
81
+ completions: ChatCompletions;
82
+ constructor(client: PromptGuard);
83
+ }
84
+ declare class Security {
85
+ private client;
86
+ constructor(client: PromptGuard);
87
+ scan(content: string, type?: "prompt" | "response"): Promise<SecurityScanResult>;
88
+ redact(content: string, piiTypes?: string[]): Promise<RedactResult>;
89
+ }
90
+ declare class Memory {
91
+ private client;
92
+ constructor(client: PromptGuard);
93
+ store(agentId: string, content: string, options?: {
94
+ sessionId?: string;
95
+ metadata?: Record<string, unknown>;
96
+ importance?: number;
97
+ }): Promise<MemoryEntry>;
98
+ retrieve(agentId: string, query: string, options?: {
99
+ topK?: number;
100
+ minRelevance?: number;
101
+ sessionId?: string;
102
+ }): Promise<MemoryRetrieveResult>;
103
+ clear(agentId: string, sessionId?: string): Promise<{
104
+ entries_deleted: number;
105
+ }>;
106
+ stats(): Promise<Record<string, unknown>>;
107
+ }
108
+ export interface ScrapeResult {
109
+ url: string;
110
+ status: "safe" | "blocked";
111
+ content: string;
112
+ threats_detected: string[];
113
+ message?: string;
114
+ }
115
+ declare class Scrape {
116
+ private client;
117
+ constructor(client: PromptGuard);
118
+ url(url: string, options?: {
119
+ renderJs?: boolean;
120
+ extractText?: boolean;
121
+ timeout?: number;
122
+ }): Promise<ScrapeResult>;
123
+ batch(urls: string[], options?: Record<string, unknown>): Promise<{
124
+ job_id: string;
125
+ }>;
126
+ }
127
+ export interface ToolValidationResult {
128
+ allowed: boolean;
129
+ risk_score: number;
130
+ risk_level: string;
131
+ reason: string;
132
+ warnings: string[];
133
+ blocked_reasons: string[];
134
+ }
135
+ export interface BehaviorAnalysisResult {
136
+ is_normal: boolean;
137
+ anomaly_score: number;
138
+ detected_patterns: string[];
139
+ recommendations: string[];
140
+ }
141
+ declare class Agent {
142
+ private client;
143
+ constructor(client: PromptGuard);
144
+ validateTool(agentId: string, toolName: string, args: Record<string, unknown>, sessionId?: string): Promise<ToolValidationResult>;
145
+ analyzeBehavior(agentId: string, recentActions: Array<{
146
+ tool_name: string;
147
+ arguments: Record<string, unknown>;
148
+ }>, sessionId?: string): Promise<BehaviorAnalysisResult>;
149
+ stats(agentId: string): Promise<Record<string, unknown>>;
150
+ }
151
+ export interface RedTeamTestResult {
152
+ test_name: string;
153
+ prompt: string;
154
+ decision: string;
155
+ reason: string;
156
+ threat_type?: string;
157
+ confidence: number;
158
+ blocked: boolean;
159
+ details: Record<string, unknown>;
160
+ }
161
+ export interface RedTeamSummary {
162
+ total_tests: number;
163
+ blocked: number;
164
+ allowed: number;
165
+ block_rate: number;
166
+ results: RedTeamTestResult[];
167
+ }
168
+ declare class RedTeam {
169
+ private client;
170
+ private base;
171
+ constructor(client: PromptGuard);
172
+ listTests(): Promise<{
173
+ total: number;
174
+ tests: Array<Record<string, unknown>>;
175
+ }>;
176
+ runTest(testName: string, targetPreset?: string): Promise<RedTeamTestResult>;
177
+ runAll(targetPreset?: string): Promise<RedTeamSummary>;
178
+ runCustom(prompt: string, targetPreset?: string): Promise<RedTeamTestResult>;
179
+ }
180
+ export declare class PromptGuard {
181
+ private config;
182
+ chat: Chat;
183
+ security: Security;
184
+ memory: Memory;
185
+ scrape: Scrape;
186
+ agent: Agent;
187
+ redteam: RedTeam;
188
+ constructor(config: PromptGuardConfig);
189
+ request<T>(method: string, path: string, body?: unknown): Promise<T>;
190
+ }
191
+ export declare class PromptGuardError extends Error {
192
+ code: string;
193
+ statusCode: number;
194
+ constructor(message: string, code: string, statusCode: number);
195
+ }
196
+ export default PromptGuard;
197
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sour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AAE,MAAM;CAM9D;AAED,eAAe,WAAW,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ /**
3
+ * PromptGuard Node.js SDK
4
+ *
5
+ * Drop-in security for AI applications.
6
+ * Just change your base URL and add an API key.
7
+ *
8
+ * @example
9
+ * import { PromptGuard } from 'promptguard';
10
+ *
11
+ * const pg = new PromptGuard({ apiKey: 'pg_xxx' });
12
+ *
13
+ * const response = await pg.chat.completions.create({
14
+ * model: 'gpt-4',
15
+ * messages: [{ role: 'user', content: 'Hello!' }]
16
+ * });
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.PromptGuardError = exports.PromptGuard = void 0;
20
+ class ChatCompletions {
21
+ constructor(client) {
22
+ this.client = client;
23
+ }
24
+ async create(params) {
25
+ const response = await this.client.request("POST", "/chat/completions", params);
26
+ return response;
27
+ }
28
+ }
29
+ class Chat {
30
+ constructor(client) {
31
+ this.completions = new ChatCompletions(client);
32
+ }
33
+ }
34
+ class Security {
35
+ constructor(client) {
36
+ this.client = client;
37
+ }
38
+ async scan(content, type = "prompt") {
39
+ return this.client.request("POST", "/security/scan", {
40
+ content,
41
+ type,
42
+ });
43
+ }
44
+ async redact(content, piiTypes) {
45
+ return this.client.request("POST", "/security/redact", {
46
+ content,
47
+ pii_types: piiTypes,
48
+ });
49
+ }
50
+ }
51
+ class Memory {
52
+ constructor(client) {
53
+ this.client = client;
54
+ }
55
+ async store(agentId, content, options) {
56
+ return this.client.request("POST", "/memory/store", {
57
+ agent_id: agentId,
58
+ content,
59
+ session_id: options?.sessionId,
60
+ metadata: options?.metadata,
61
+ importance: options?.importance ?? 0.5,
62
+ });
63
+ }
64
+ async retrieve(agentId, query, options) {
65
+ return this.client.request("POST", "/memory/retrieve", {
66
+ agent_id: agentId,
67
+ query,
68
+ top_k: options?.topK ?? 5,
69
+ min_relevance: options?.minRelevance ?? 0.5,
70
+ session_id: options?.sessionId,
71
+ });
72
+ }
73
+ async clear(agentId, sessionId) {
74
+ const url = sessionId ? `/memory/${agentId}?session_id=${sessionId}` : `/memory/${agentId}`;
75
+ return this.client.request("DELETE", url);
76
+ }
77
+ async stats() {
78
+ return this.client.request("GET", "/memory/stats");
79
+ }
80
+ }
81
+ class Scrape {
82
+ constructor(client) {
83
+ this.client = client;
84
+ }
85
+ async url(url, options) {
86
+ return this.client.request("POST", "/scrape", {
87
+ url,
88
+ render_js: options?.renderJs ?? false,
89
+ extract_text: options?.extractText ?? true,
90
+ timeout: options?.timeout ?? 30,
91
+ });
92
+ }
93
+ async batch(urls, options) {
94
+ return this.client.request("POST", "/scrape/batch", {
95
+ urls,
96
+ ...options,
97
+ });
98
+ }
99
+ }
100
+ class Agent {
101
+ constructor(client) {
102
+ this.client = client;
103
+ }
104
+ async validateTool(agentId, toolName, args, sessionId) {
105
+ return this.client.request("POST", "/agent/validate-tool", {
106
+ agent_id: agentId,
107
+ tool_name: toolName,
108
+ arguments: args,
109
+ session_id: sessionId,
110
+ });
111
+ }
112
+ async analyzeBehavior(agentId, recentActions, sessionId) {
113
+ return this.client.request("POST", "/agent/analyze-behavior", {
114
+ agent_id: agentId,
115
+ recent_actions: recentActions,
116
+ session_id: sessionId,
117
+ });
118
+ }
119
+ async stats(agentId) {
120
+ return this.client.request("GET", `/agent/${agentId}/stats`);
121
+ }
122
+ }
123
+ class RedTeam {
124
+ constructor(client) {
125
+ this.base = "/internal/redteam";
126
+ this.client = client;
127
+ }
128
+ async listTests() {
129
+ return this.client.request("GET", `${this.base}/tests`);
130
+ }
131
+ async runTest(testName, targetPreset = "default") {
132
+ return this.client.request("POST", `${this.base}/test/${testName}`, {
133
+ target_preset: targetPreset,
134
+ });
135
+ }
136
+ async runAll(targetPreset = "default") {
137
+ return this.client.request("POST", `${this.base}/test-all`, {
138
+ target_preset: targetPreset,
139
+ });
140
+ }
141
+ async runCustom(prompt, targetPreset = "default") {
142
+ return this.client.request("POST", `${this.base}/test-custom`, {
143
+ custom_prompt: prompt,
144
+ target_preset: targetPreset,
145
+ });
146
+ }
147
+ }
148
+ class PromptGuard {
149
+ constructor(config) {
150
+ const apiKey = config.apiKey || process.env.PROMPTGUARD_API_KEY;
151
+ if (!apiKey) {
152
+ throw new Error("API key required. Pass apiKey in config or set PROMPTGUARD_API_KEY environment variable.");
153
+ }
154
+ this.config = {
155
+ apiKey,
156
+ baseUrl: config.baseUrl || process.env.PROMPTGUARD_BASE_URL || "https://api.promptguard.co/api/v1",
157
+ timeout: config.timeout || 30000,
158
+ enableCaching: config.enableCaching ?? true,
159
+ enableSecurityScan: config.enableSecurityScan ?? true,
160
+ };
161
+ // OpenAI-compatible
162
+ this.chat = new Chat(this);
163
+ // PromptGuard-specific
164
+ this.security = new Security(this);
165
+ this.memory = new Memory(this);
166
+ this.scrape = new Scrape(this);
167
+ this.agent = new Agent(this);
168
+ this.redteam = new RedTeam(this);
169
+ }
170
+ async request(method, path, body) {
171
+ const url = `${this.config.baseUrl}${path}`;
172
+ const response = await fetch(url, {
173
+ method,
174
+ headers: {
175
+ Authorization: `Bearer ${this.config.apiKey}`,
176
+ "Content-Type": "application/json",
177
+ "X-PromptGuard-SDK": "node",
178
+ "X-PromptGuard-Version": "0.1.0",
179
+ },
180
+ body: body ? JSON.stringify(body) : undefined,
181
+ signal: AbortSignal.timeout(this.config.timeout),
182
+ });
183
+ if (!response.ok) {
184
+ const errorBody = await response.json().catch(() => ({}));
185
+ throw new PromptGuardError(errorBody.error?.message || "Request failed", errorBody.error?.code || "UNKNOWN", response.status);
186
+ }
187
+ return response.json();
188
+ }
189
+ }
190
+ exports.PromptGuard = PromptGuard;
191
+ class PromptGuardError extends Error {
192
+ constructor(message, code, statusCode) {
193
+ super(`${code}: ${message}`);
194
+ this.name = "PromptGuardError";
195
+ this.code = code;
196
+ this.statusCode = statusCode;
197
+ }
198
+ }
199
+ exports.PromptGuardError = PromptGuardError;
200
+ exports.default = PromptGuard;
201
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {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AAC,KAAK,EAAE,IAAI,IAAI,SAAS,EAClC,QAAQ,CAAC,MAAM,CAChB,CAAA;QACH,CAAC;QAED,OAAO,QAAQ,CAAC,IAAI,EAAgB,CAAA;IACtC,CAAC;CACF;AApED,kCAoEC;AAED,MAAa,gBAAiB,SAAQ,KAAK;IAIzC,YAAY,OAAe,EAAE,IAAY,EAAE,UAAkB;QAC3D,KAAK,CAAC,GAAG,IAAI,KAAK,OAAO,EAAE,CAAC,CAAA;QAC5B,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAA;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;IAC9B,CAAC;CACF;AAVD,4CAUC;AAED,kBAAe,WAAW,CAAA"}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "promptguard-sdk",
3
+ "version": "0.1.0",
4
+ "description": "Drop-in security for AI applications - AI Firewall SDK",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "test": "jest",
10
+ "lint": "eslint src/",
11
+ "prepublishOnly": "npm run build"
12
+ },
13
+ "keywords": [
14
+ "ai",
15
+ "security",
16
+ "llm",
17
+ "prompt-injection",
18
+ "openai",
19
+ "anthropic",
20
+ "ai-firewall",
21
+ "pii-detection",
22
+ "llm-security"
23
+ ],
24
+ "author": "PromptGuard <support@promptguard.co>",
25
+ "license": "MIT",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/acebot712/promptguard.git",
29
+ "directory": "packages/sdk-node"
30
+ },
31
+ "homepage": "https://promptguard.co",
32
+ "bugs": {
33
+ "url": "https://github.com/acebot712/promptguard/issues"
34
+ },
35
+ "engines": {
36
+ "node": ">=16.0.0"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "files": ["dist", "README.md", "LICENSE"],
42
+ "dependencies": {},
43
+ "devDependencies": {
44
+ "@types/node": "^20.0.0",
45
+ "typescript": "^5.0.0"
46
+ }
47
+ }