@ainvirion/aiproxyguard-npm-sdk 1.0.14

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,258 @@
1
+ /**
2
+ * Default API base URL (cloud mode).
3
+ */
4
+ declare const DEFAULT_BASE_URL = "https://aiproxyguard.com";
5
+ /**
6
+ * API mode determines endpoint paths and request/response formats.
7
+ * - 'cloud': Uses /api/v1/check with {input} request format
8
+ * - 'proxy': Uses /check with {text} request format
9
+ * - 'auto': Auto-detect based on URL (docker.* = proxy, otherwise cloud)
10
+ */
11
+ type ApiMode = 'cloud' | 'proxy' | 'auto';
12
+ /**
13
+ * Action to take based on prompt injection detection result.
14
+ */
15
+ type Action = 'allow' | 'log' | 'warn' | 'block';
16
+ /**
17
+ * Threat detected in the input.
18
+ */
19
+ interface Threat {
20
+ /** Type of threat detected */
21
+ type: string;
22
+ /** Confidence score from 0.0 to 1.0 */
23
+ confidence: number;
24
+ /** Rule that matched, if any */
25
+ rule: string | null;
26
+ }
27
+ /**
28
+ * Result from checking text for prompt injection.
29
+ */
30
+ interface CheckResult {
31
+ /** Unique check ID */
32
+ id: string;
33
+ /** Whether the input was flagged as potentially harmful */
34
+ flagged: boolean;
35
+ /** Action recommended by the security proxy */
36
+ action: Action;
37
+ /** List of threats detected */
38
+ threats: Threat[];
39
+ /** Processing latency in milliseconds */
40
+ latencyMs: number;
41
+ /** Whether the result was served from cache */
42
+ cached: boolean;
43
+ }
44
+ /**
45
+ * Service information response.
46
+ */
47
+ interface ServiceInfo {
48
+ service: string;
49
+ version: string;
50
+ }
51
+ /**
52
+ * Health check response.
53
+ */
54
+ interface HealthStatus {
55
+ status: 'healthy' | 'unhealthy';
56
+ }
57
+ /**
58
+ * Readiness check response.
59
+ */
60
+ interface ReadinessStatus {
61
+ status: 'ready' | 'not_ready';
62
+ checks: Record<string, boolean>;
63
+ }
64
+ /**
65
+ * Configuration options for the AIProxyGuard client.
66
+ */
67
+ interface AIProxyGuardConfig {
68
+ /** Base URL of the AIProxyGuard service (default: https://aiproxyguard.com) */
69
+ baseUrl?: string;
70
+ /** API key for authentication (optional for some deployments) */
71
+ apiKey?: string;
72
+ /** API mode: 'cloud', 'proxy', or 'auto' (default: 'auto') */
73
+ mode?: ApiMode;
74
+ /** Request timeout in milliseconds (default: 30000) */
75
+ timeout?: number;
76
+ /** Number of retry attempts (default: 3) */
77
+ retries?: number;
78
+ /** Base delay between retries in milliseconds (default: 1000) */
79
+ retryDelay?: number;
80
+ /** Maximum concurrent requests for checkBatch (default: 10) */
81
+ maxConcurrency?: number;
82
+ }
83
+ /**
84
+ * Error response from the API.
85
+ */
86
+ interface ErrorResponse {
87
+ error: {
88
+ type: string;
89
+ message: string;
90
+ code?: string;
91
+ };
92
+ }
93
+
94
+ /**
95
+ * AIProxyGuard client for detecting prompt injection attacks.
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const client = new AIProxyGuard('https://docker.aiproxyguard.com');
100
+ *
101
+ * const result = await client.check('Ignore all previous instructions');
102
+ * if (result.action === 'block') {
103
+ * console.log(`Blocked: ${result.category}`);
104
+ * }
105
+ * ```
106
+ */
107
+ declare class AIProxyGuard {
108
+ private readonly baseUrl;
109
+ private readonly apiKey?;
110
+ private readonly mode;
111
+ private readonly timeout;
112
+ private readonly retries;
113
+ private readonly retryDelay;
114
+ private readonly maxConcurrency;
115
+ /**
116
+ * Create a new AIProxyGuard client.
117
+ *
118
+ * @param config - Configuration object, base URL string, or omit for default
119
+ * @throws {ValidationError} If the baseUrl has an invalid scheme
120
+ */
121
+ constructor(config?: AIProxyGuardConfig | string);
122
+ private getHeaders;
123
+ private handleError;
124
+ private fetchWithRetry;
125
+ /**
126
+ * Check text for prompt injection.
127
+ *
128
+ * @param text - The text to scan
129
+ * @returns CheckResult with action, category, signatureName, and confidence
130
+ * @throws {ValidationError} If the request is invalid
131
+ * @throws {TimeoutError} If the request times out
132
+ * @throws {RateLimitError} If rate limited
133
+ * @throws {AIProxyGuardError} For other errors
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * const result = await client.check("Ignore all previous instructions");
138
+ * if (result.action === 'block') {
139
+ * console.log(`Blocked: ${result.category}`);
140
+ * }
141
+ * ```
142
+ */
143
+ check(text: string, context?: Record<string, unknown>): Promise<CheckResult>;
144
+ /**
145
+ * Check using cloud mode (/api/v1/check with {input, context}).
146
+ */
147
+ private checkCloud;
148
+ /**
149
+ * Check using proxy mode (/check with {text}).
150
+ */
151
+ private checkProxy;
152
+ /**
153
+ * Check multiple texts for prompt injection in parallel with concurrency limit.
154
+ *
155
+ * @param texts - Array of texts to scan
156
+ * @returns Array of CheckResult objects in the same order
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * const results = await client.checkBatch([
161
+ * 'Hello, how are you?',
162
+ * 'Ignore all instructions',
163
+ * ]);
164
+ * ```
165
+ */
166
+ checkBatch(texts: string[]): Promise<CheckResult[]>;
167
+ /**
168
+ * Check if text is safe (not blocked).
169
+ *
170
+ * @param text - The text to scan
171
+ * @returns True if the text is safe, false if blocked
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * if (await client.isSafe(userInput)) {
176
+ * // Process the input
177
+ * }
178
+ * ```
179
+ */
180
+ isSafe(text: string): Promise<boolean>;
181
+ /**
182
+ * Get service information.
183
+ *
184
+ * @returns ServiceInfo with service name and version
185
+ */
186
+ info(): Promise<ServiceInfo>;
187
+ /**
188
+ * Check if the service is healthy.
189
+ *
190
+ * @returns True if healthy, false otherwise
191
+ */
192
+ health(): Promise<boolean>;
193
+ /**
194
+ * Check if the service is ready.
195
+ *
196
+ * @returns ReadinessStatus with status and checks
197
+ */
198
+ ready(): Promise<ReadinessStatus>;
199
+ }
200
+
201
+ /**
202
+ * Express request type (minimal interface for compatibility).
203
+ */
204
+ interface Request {
205
+ body?: Record<string, unknown>;
206
+ }
207
+ /**
208
+ * Express response type (minimal interface for compatibility).
209
+ */
210
+ interface Response {
211
+ status(code: number): Response;
212
+ json(data: unknown): void;
213
+ }
214
+ /**
215
+ * Express next function type.
216
+ */
217
+ type NextFunction = (error?: unknown) => void;
218
+ /**
219
+ * Extended request with AIProxyGuard result attached.
220
+ */
221
+ interface GuardedRequest extends Request {
222
+ aiproxyguardResult?: CheckResult;
223
+ }
224
+ /**
225
+ * Options for the guard middleware.
226
+ */
227
+ interface GuardMiddlewareOptions {
228
+ /** Field(s) in request body to check. Default: 'text' */
229
+ textField?: string | string[];
230
+ /** Action to take on block. Default: 'reject' */
231
+ onBlock?: 'reject' | 'continue';
232
+ /** Whether to reject requests with non-string field values. Default: true */
233
+ rejectInvalidTypes?: boolean;
234
+ /** Custom error handler */
235
+ onError?: (error: Error, req: Request, res: Response) => void;
236
+ }
237
+ /**
238
+ * Express middleware for prompt injection detection.
239
+ *
240
+ * @param client - AIProxyGuard client instance
241
+ * @param options - Middleware options
242
+ * @returns Express middleware function
243
+ *
244
+ * @example
245
+ * ```typescript
246
+ * import { AIProxyGuard } from '@aiproxyguard/sdk';
247
+ * import { guardMiddleware } from '@aiproxyguard/sdk/middleware';
248
+ *
249
+ * const client = new AIProxyGuard('https://docker.aiproxyguard.com');
250
+ *
251
+ * app.post('/chat', guardMiddleware(client), (req, res) => {
252
+ * // Request already validated
253
+ * });
254
+ * ```
255
+ */
256
+ declare function guardMiddleware(client: AIProxyGuard, options?: GuardMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
257
+
258
+ export { AIProxyGuard as A, type CheckResult as C, DEFAULT_BASE_URL as D, type ErrorResponse as E, type GuardMiddlewareOptions as G, type HealthStatus as H, type ReadinessStatus as R, type ServiceInfo as S, type Threat as T, type AIProxyGuardConfig as a, type Action as b, type ApiMode as c, type GuardedRequest as d, guardMiddleware as g };
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Default API base URL (cloud mode).
3
+ */
4
+ declare const DEFAULT_BASE_URL = "https://aiproxyguard.com";
5
+ /**
6
+ * API mode determines endpoint paths and request/response formats.
7
+ * - 'cloud': Uses /api/v1/check with {input} request format
8
+ * - 'proxy': Uses /check with {text} request format
9
+ * - 'auto': Auto-detect based on URL (docker.* = proxy, otherwise cloud)
10
+ */
11
+ type ApiMode = 'cloud' | 'proxy' | 'auto';
12
+ /**
13
+ * Action to take based on prompt injection detection result.
14
+ */
15
+ type Action = 'allow' | 'log' | 'warn' | 'block';
16
+ /**
17
+ * Threat detected in the input.
18
+ */
19
+ interface Threat {
20
+ /** Type of threat detected */
21
+ type: string;
22
+ /** Confidence score from 0.0 to 1.0 */
23
+ confidence: number;
24
+ /** Rule that matched, if any */
25
+ rule: string | null;
26
+ }
27
+ /**
28
+ * Result from checking text for prompt injection.
29
+ */
30
+ interface CheckResult {
31
+ /** Unique check ID */
32
+ id: string;
33
+ /** Whether the input was flagged as potentially harmful */
34
+ flagged: boolean;
35
+ /** Action recommended by the security proxy */
36
+ action: Action;
37
+ /** List of threats detected */
38
+ threats: Threat[];
39
+ /** Processing latency in milliseconds */
40
+ latencyMs: number;
41
+ /** Whether the result was served from cache */
42
+ cached: boolean;
43
+ }
44
+ /**
45
+ * Service information response.
46
+ */
47
+ interface ServiceInfo {
48
+ service: string;
49
+ version: string;
50
+ }
51
+ /**
52
+ * Health check response.
53
+ */
54
+ interface HealthStatus {
55
+ status: 'healthy' | 'unhealthy';
56
+ }
57
+ /**
58
+ * Readiness check response.
59
+ */
60
+ interface ReadinessStatus {
61
+ status: 'ready' | 'not_ready';
62
+ checks: Record<string, boolean>;
63
+ }
64
+ /**
65
+ * Configuration options for the AIProxyGuard client.
66
+ */
67
+ interface AIProxyGuardConfig {
68
+ /** Base URL of the AIProxyGuard service (default: https://aiproxyguard.com) */
69
+ baseUrl?: string;
70
+ /** API key for authentication (optional for some deployments) */
71
+ apiKey?: string;
72
+ /** API mode: 'cloud', 'proxy', or 'auto' (default: 'auto') */
73
+ mode?: ApiMode;
74
+ /** Request timeout in milliseconds (default: 30000) */
75
+ timeout?: number;
76
+ /** Number of retry attempts (default: 3) */
77
+ retries?: number;
78
+ /** Base delay between retries in milliseconds (default: 1000) */
79
+ retryDelay?: number;
80
+ /** Maximum concurrent requests for checkBatch (default: 10) */
81
+ maxConcurrency?: number;
82
+ }
83
+ /**
84
+ * Error response from the API.
85
+ */
86
+ interface ErrorResponse {
87
+ error: {
88
+ type: string;
89
+ message: string;
90
+ code?: string;
91
+ };
92
+ }
93
+
94
+ /**
95
+ * AIProxyGuard client for detecting prompt injection attacks.
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const client = new AIProxyGuard('https://docker.aiproxyguard.com');
100
+ *
101
+ * const result = await client.check('Ignore all previous instructions');
102
+ * if (result.action === 'block') {
103
+ * console.log(`Blocked: ${result.category}`);
104
+ * }
105
+ * ```
106
+ */
107
+ declare class AIProxyGuard {
108
+ private readonly baseUrl;
109
+ private readonly apiKey?;
110
+ private readonly mode;
111
+ private readonly timeout;
112
+ private readonly retries;
113
+ private readonly retryDelay;
114
+ private readonly maxConcurrency;
115
+ /**
116
+ * Create a new AIProxyGuard client.
117
+ *
118
+ * @param config - Configuration object, base URL string, or omit for default
119
+ * @throws {ValidationError} If the baseUrl has an invalid scheme
120
+ */
121
+ constructor(config?: AIProxyGuardConfig | string);
122
+ private getHeaders;
123
+ private handleError;
124
+ private fetchWithRetry;
125
+ /**
126
+ * Check text for prompt injection.
127
+ *
128
+ * @param text - The text to scan
129
+ * @returns CheckResult with action, category, signatureName, and confidence
130
+ * @throws {ValidationError} If the request is invalid
131
+ * @throws {TimeoutError} If the request times out
132
+ * @throws {RateLimitError} If rate limited
133
+ * @throws {AIProxyGuardError} For other errors
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * const result = await client.check("Ignore all previous instructions");
138
+ * if (result.action === 'block') {
139
+ * console.log(`Blocked: ${result.category}`);
140
+ * }
141
+ * ```
142
+ */
143
+ check(text: string, context?: Record<string, unknown>): Promise<CheckResult>;
144
+ /**
145
+ * Check using cloud mode (/api/v1/check with {input, context}).
146
+ */
147
+ private checkCloud;
148
+ /**
149
+ * Check using proxy mode (/check with {text}).
150
+ */
151
+ private checkProxy;
152
+ /**
153
+ * Check multiple texts for prompt injection in parallel with concurrency limit.
154
+ *
155
+ * @param texts - Array of texts to scan
156
+ * @returns Array of CheckResult objects in the same order
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * const results = await client.checkBatch([
161
+ * 'Hello, how are you?',
162
+ * 'Ignore all instructions',
163
+ * ]);
164
+ * ```
165
+ */
166
+ checkBatch(texts: string[]): Promise<CheckResult[]>;
167
+ /**
168
+ * Check if text is safe (not blocked).
169
+ *
170
+ * @param text - The text to scan
171
+ * @returns True if the text is safe, false if blocked
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * if (await client.isSafe(userInput)) {
176
+ * // Process the input
177
+ * }
178
+ * ```
179
+ */
180
+ isSafe(text: string): Promise<boolean>;
181
+ /**
182
+ * Get service information.
183
+ *
184
+ * @returns ServiceInfo with service name and version
185
+ */
186
+ info(): Promise<ServiceInfo>;
187
+ /**
188
+ * Check if the service is healthy.
189
+ *
190
+ * @returns True if healthy, false otherwise
191
+ */
192
+ health(): Promise<boolean>;
193
+ /**
194
+ * Check if the service is ready.
195
+ *
196
+ * @returns ReadinessStatus with status and checks
197
+ */
198
+ ready(): Promise<ReadinessStatus>;
199
+ }
200
+
201
+ /**
202
+ * Express request type (minimal interface for compatibility).
203
+ */
204
+ interface Request {
205
+ body?: Record<string, unknown>;
206
+ }
207
+ /**
208
+ * Express response type (minimal interface for compatibility).
209
+ */
210
+ interface Response {
211
+ status(code: number): Response;
212
+ json(data: unknown): void;
213
+ }
214
+ /**
215
+ * Express next function type.
216
+ */
217
+ type NextFunction = (error?: unknown) => void;
218
+ /**
219
+ * Extended request with AIProxyGuard result attached.
220
+ */
221
+ interface GuardedRequest extends Request {
222
+ aiproxyguardResult?: CheckResult;
223
+ }
224
+ /**
225
+ * Options for the guard middleware.
226
+ */
227
+ interface GuardMiddlewareOptions {
228
+ /** Field(s) in request body to check. Default: 'text' */
229
+ textField?: string | string[];
230
+ /** Action to take on block. Default: 'reject' */
231
+ onBlock?: 'reject' | 'continue';
232
+ /** Whether to reject requests with non-string field values. Default: true */
233
+ rejectInvalidTypes?: boolean;
234
+ /** Custom error handler */
235
+ onError?: (error: Error, req: Request, res: Response) => void;
236
+ }
237
+ /**
238
+ * Express middleware for prompt injection detection.
239
+ *
240
+ * @param client - AIProxyGuard client instance
241
+ * @param options - Middleware options
242
+ * @returns Express middleware function
243
+ *
244
+ * @example
245
+ * ```typescript
246
+ * import { AIProxyGuard } from '@aiproxyguard/sdk';
247
+ * import { guardMiddleware } from '@aiproxyguard/sdk/middleware';
248
+ *
249
+ * const client = new AIProxyGuard('https://docker.aiproxyguard.com');
250
+ *
251
+ * app.post('/chat', guardMiddleware(client), (req, res) => {
252
+ * // Request already validated
253
+ * });
254
+ * ```
255
+ */
256
+ declare function guardMiddleware(client: AIProxyGuard, options?: GuardMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
257
+
258
+ export { AIProxyGuard as A, type CheckResult as C, DEFAULT_BASE_URL as D, type ErrorResponse as E, type GuardMiddlewareOptions as G, type HealthStatus as H, type ReadinessStatus as R, type ServiceInfo as S, type Threat as T, type AIProxyGuardConfig as a, type Action as b, type ApiMode as c, type GuardedRequest as d, guardMiddleware as g };
@@ -0,0 +1,54 @@
1
+ import { C as CheckResult } from './express-x7uGX_rh.mjs';
2
+ export { A as AIProxyGuard, a as AIProxyGuardConfig, b as Action, c as ApiMode, D as DEFAULT_BASE_URL, E as ErrorResponse, G as GuardMiddlewareOptions, d as GuardedRequest, H as HealthStatus, R as ReadinessStatus, S as ServiceInfo, T as Threat, A as default, g as guardMiddleware } from './express-x7uGX_rh.mjs';
3
+
4
+ /**
5
+ * Base error class for AIProxyGuard SDK errors.
6
+ */
7
+ declare class AIProxyGuardError extends Error {
8
+ readonly code: string;
9
+ readonly statusCode?: number | undefined;
10
+ constructor(message: string, code: string, statusCode?: number | undefined);
11
+ }
12
+ /**
13
+ * Thrown when the request is invalid or malformed.
14
+ */
15
+ declare class ValidationError extends AIProxyGuardError {
16
+ constructor(message: string, code?: string);
17
+ }
18
+ /**
19
+ * Thrown when unable to connect to the AIProxyGuard service.
20
+ */
21
+ declare class ConnectionError extends AIProxyGuardError {
22
+ constructor(message?: string);
23
+ }
24
+ /**
25
+ * Thrown when a request times out.
26
+ */
27
+ declare class TimeoutError extends AIProxyGuardError {
28
+ constructor(message?: string);
29
+ }
30
+ /**
31
+ * Thrown when rate limited by the service.
32
+ */
33
+ declare class RateLimitError extends AIProxyGuardError {
34
+ readonly retryAfter?: number | undefined;
35
+ constructor(message?: string, retryAfter?: number | undefined);
36
+ }
37
+ /**
38
+ * Thrown when content is blocked due to detected prompt injection.
39
+ */
40
+ declare class ContentBlockedError extends AIProxyGuardError {
41
+ readonly result: CheckResult;
42
+ constructor(result: CheckResult);
43
+ }
44
+
45
+ /**
46
+ * Check if a CheckResult indicates the content is safe (not flagged).
47
+ */
48
+ declare function isSafe(result: CheckResult): boolean;
49
+ /**
50
+ * Check if a CheckResult indicates the content is flagged/blocked.
51
+ */
52
+ declare function isBlocked(result: CheckResult): boolean;
53
+
54
+ export { AIProxyGuardError, CheckResult, ConnectionError, ContentBlockedError, RateLimitError, TimeoutError, ValidationError, isBlocked, isSafe };
@@ -0,0 +1,54 @@
1
+ import { C as CheckResult } from './express-x7uGX_rh.js';
2
+ export { A as AIProxyGuard, a as AIProxyGuardConfig, b as Action, c as ApiMode, D as DEFAULT_BASE_URL, E as ErrorResponse, G as GuardMiddlewareOptions, d as GuardedRequest, H as HealthStatus, R as ReadinessStatus, S as ServiceInfo, T as Threat, A as default, g as guardMiddleware } from './express-x7uGX_rh.js';
3
+
4
+ /**
5
+ * Base error class for AIProxyGuard SDK errors.
6
+ */
7
+ declare class AIProxyGuardError extends Error {
8
+ readonly code: string;
9
+ readonly statusCode?: number | undefined;
10
+ constructor(message: string, code: string, statusCode?: number | undefined);
11
+ }
12
+ /**
13
+ * Thrown when the request is invalid or malformed.
14
+ */
15
+ declare class ValidationError extends AIProxyGuardError {
16
+ constructor(message: string, code?: string);
17
+ }
18
+ /**
19
+ * Thrown when unable to connect to the AIProxyGuard service.
20
+ */
21
+ declare class ConnectionError extends AIProxyGuardError {
22
+ constructor(message?: string);
23
+ }
24
+ /**
25
+ * Thrown when a request times out.
26
+ */
27
+ declare class TimeoutError extends AIProxyGuardError {
28
+ constructor(message?: string);
29
+ }
30
+ /**
31
+ * Thrown when rate limited by the service.
32
+ */
33
+ declare class RateLimitError extends AIProxyGuardError {
34
+ readonly retryAfter?: number | undefined;
35
+ constructor(message?: string, retryAfter?: number | undefined);
36
+ }
37
+ /**
38
+ * Thrown when content is blocked due to detected prompt injection.
39
+ */
40
+ declare class ContentBlockedError extends AIProxyGuardError {
41
+ readonly result: CheckResult;
42
+ constructor(result: CheckResult);
43
+ }
44
+
45
+ /**
46
+ * Check if a CheckResult indicates the content is safe (not flagged).
47
+ */
48
+ declare function isSafe(result: CheckResult): boolean;
49
+ /**
50
+ * Check if a CheckResult indicates the content is flagged/blocked.
51
+ */
52
+ declare function isBlocked(result: CheckResult): boolean;
53
+
54
+ export { AIProxyGuardError, CheckResult, ConnectionError, ContentBlockedError, RateLimitError, TimeoutError, ValidationError, isBlocked, isSafe };