@koreshield/koreshield 0.1.4

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 KoreShield Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,351 @@
1
+ # KoreShield JavaScript/TypeScript SDK
2
+
3
+ [![npm version](https://badge.fury.io/js/koreshield-js.svg)](https://badge.fury.io/js/koreshield-js)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-007ACC?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
6
+
7
+ A comprehensive JavaScript/TypeScript SDK for integrating with [KoreShield](https://koreshield.com) LLM Security Proxy. Provides secure, monitored access to AI models with built-in security features, threat detection, and compliance monitoring.
8
+
9
+ ## Features
10
+
11
+ - **Security First**: Built-in input sanitization, attack detection, and response filtering
12
+ - **Monitoring**: Real-time metrics and security event tracking
13
+ - **OpenAI Compatible**: Drop-in replacement for OpenAI SDK
14
+ - **Universal**: Works in Node.js, browsers, and edge environments
15
+ - **TypeScript**: Full TypeScript support with comprehensive type definitions
16
+ - **Configurable**: Fine-grained security controls and monitoring options
17
+ - **Production Ready**: Error handling, retries, and connection management
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ # npm
23
+ npm install koreshield
24
+
25
+ # yarn
26
+ yarn add koreshield
27
+
28
+ # pnpm
29
+ pnpm add koreshield
30
+ ```
31
+
32
+ ## Quick Start
33
+
34
+ ### Node.js
35
+
36
+ ```javascript
37
+ import { createClient } from 'koreshield';
38
+
39
+ const client = createClient({
40
+ baseURL: 'https://your-koreshield-instance.com', // Required
41
+ apiKey: 'your-koreshield-api-key' // Optional, can use KORESHIELD_API_KEY env var
42
+ });
43
+
44
+ // Secure chat completion
45
+ const response = await client.createChatCompletion({
46
+ model: 'gpt-3.5-turbo',
47
+ messages: [
48
+ { role: 'user', content: 'Hello, how are you?' }
49
+ ]
50
+ });
51
+
52
+ console.log(response.choices[0].message.content);
53
+ ```
54
+
55
+ ### Browser
56
+
57
+ ```html
58
+ <script type="module">
59
+ import { createClient } from './koreshield-js.browser.js';
60
+
61
+ const client = createClient({
62
+ baseURL: 'https://your-koreshield-proxy.com'
63
+ });
64
+
65
+ // Use the client...
66
+ </script>
67
+ ```
68
+
69
+ ### OpenAI-Compatible API
70
+
71
+ ```javascript
72
+ import { createKoreShieldOpenAI } from 'koreshield-js';
73
+
74
+ const openai = createKoreShieldOpenAI({
75
+ baseURL: 'http://localhost:8000',
76
+ apiKey: 'your-api-key'
77
+ });
78
+
79
+ // Use like regular OpenAI SDK
80
+ const chat = await openai.chat({});
81
+ const response = await chat.create({
82
+ model: 'gpt-3.5-turbo',
83
+ messages: [{ role: 'user', content: 'Hello!' }]
84
+ });
85
+ ```
86
+
87
+ ## Configuration
88
+
89
+ ### Environment Variables
90
+
91
+ ```bash
92
+ KORESHIELD_BASE_URL=http://localhost:8000
93
+ KORESHIELD_API_KEY=your-api-key
94
+ KORESHIELD_TIMEOUT=30000
95
+ KORESHIELD_DEBUG=true
96
+ ```
97
+
98
+ ### Programmatic Configuration
99
+
100
+ ```typescript
101
+ const client = createClient({
102
+ baseURL: 'https://your-proxy.koreshield.com',
103
+ apiKey: 'your-api-key',
104
+ timeout: 30000,
105
+ debug: false,
106
+ headers: {
107
+ 'X-Custom-Header': 'value'
108
+ }
109
+ });
110
+ ```
111
+
112
+ ## Security Features
113
+
114
+ ### Input Sanitization
115
+
116
+ ```typescript
117
+ import { sanitizeInput, formatMessages } from 'koreshield-js';
118
+
119
+ // Sanitize individual input
120
+ const safeInput = sanitizeInput('<script>alert("xss")</script>Hello!');
121
+
122
+ // Format and sanitize chat messages
123
+ const messages = formatMessages([
124
+ { role: 'user', content: unsafeInput }
125
+ ]);
126
+ ```
127
+
128
+ ### Response Safety Checking
129
+
130
+ ```typescript
131
+ import { checkResponseSafety } from 'koreshield-js';
132
+
133
+ const safetyCheck = checkResponseSafety(aiResponse);
134
+ if (!safetyCheck.safe) {
135
+ console.log('Issues found:', safetyCheck.issues);
136
+ console.log('Severity:', safetyCheck.severity);
137
+ }
138
+ ```
139
+
140
+ ### Custom Security Options
141
+
142
+ ```typescript
143
+ const response = await client.createChatCompletion({
144
+ model: 'gpt-3.5-turbo',
145
+ messages: messages
146
+ }, {
147
+ sensitivity: 'high', // 'low', 'medium', 'high'
148
+ defaultAction: 'block', // 'allow', 'warn', 'block'
149
+ features: {
150
+ sanitization: true,
151
+ detection: true,
152
+ policyEnforcement: true
153
+ }
154
+ });
155
+ ```
156
+
157
+ ## Monitoring & Analytics
158
+
159
+ ### Get Security Metrics
160
+
161
+ ```typescript
162
+ const metrics = await client.getMetrics();
163
+ console.log({
164
+ totalRequests: metrics.requests_total,
165
+ blockedRequests: metrics.requests_blocked,
166
+ attacksDetected: metrics.attacks_detected,
167
+ avgResponseTime: metrics.avg_response_time,
168
+ activeConnections: metrics.active_connections
169
+ });
170
+ ```
171
+
172
+ ### Security Events
173
+
174
+ ```typescript
175
+ // Get recent security events
176
+ const events = await client.getSecurityEvents(50, 0, 'attack_detected', 'high');
177
+
178
+ events.forEach(event => {
179
+ console.log(`${event.type}: ${event.description} (${event.severity})`);
180
+ console.log(`Time: ${new Date(event.timestamp).toLocaleString()}`);
181
+ });
182
+ ```
183
+
184
+ ### Prometheus Metrics
185
+
186
+ ```typescript
187
+ const prometheusMetrics = await client.getPrometheusMetrics();
188
+ console.log(prometheusMetrics);
189
+ ```
190
+
191
+ ## Advanced Usage
192
+
193
+ ### Error Handling & Retries
194
+
195
+ ```typescript
196
+ import { retry } from 'koreshield-js';
197
+
198
+ const response = await retry(
199
+ () => client.createChatCompletion(request),
200
+ 3, // max retries
201
+ 1000 // base delay in ms
202
+ );
203
+ ```
204
+
205
+ ### Custom Error Handling
206
+
207
+ ```typescript
208
+ try {
209
+ const response = await client.createChatCompletion(request);
210
+ } catch (error) {
211
+ if (error.code === 'SECURITY_VIOLATION') {
212
+ console.log('Security violation detected:', error.details);
213
+ } else if (error.statusCode === 429) {
214
+ console.log('Rate limited, retrying...');
215
+ } else {
216
+ console.error('API Error:', error.message);
217
+ }
218
+ }
219
+ ```
220
+
221
+ ### Connection Testing
222
+
223
+ ```typescript
224
+ const isConnected = await client.testConnection();
225
+ const health = await client.health();
226
+
227
+ console.log('Connected:', isConnected);
228
+ console.log('Status:', health.status);
229
+ console.log('Version:', health.version);
230
+ console.log('Uptime:', health.uptime);
231
+ ```
232
+
233
+ ## API Reference
234
+
235
+ ### KoreShieldClient
236
+
237
+ Main client class for interacting with KoreShield proxy.
238
+
239
+ #### Methods
240
+
241
+ - `createChatCompletion(request, securityOptions?)` - Create chat completion
242
+ - `getSecurityEvents(limit?, offset?, type?, severity?)` - Get security events
243
+ - `getMetrics()` - Get security metrics
244
+ - `getPrometheusMetrics()` - Get Prometheus metrics
245
+ - `health()` - Health check
246
+ - `updateSecurityConfig(options)` - Update security configuration
247
+ - `testConnection()` - Test connection
248
+
249
+ ### Utility Functions
250
+
251
+ - `validateConfig(config)` - Validate configuration
252
+ - `createClient(config?)` - Create client with defaults
253
+ - `sanitizeInput(input)` - Sanitize user input
254
+ - `checkResponseSafety(response)` - Check response safety
255
+ - `formatMessages(messages)` - Format and sanitize messages
256
+ - `sleep(ms)` - Sleep utility
257
+ - `retry(fn, maxRetries?, baseDelay?)` - Retry with backoff
258
+
259
+ ## Examples
260
+
261
+ See the `examples/` directory for comprehensive examples:
262
+
263
+ - `examples/node/basic-usage.js` - Basic Node.js usage
264
+ - `examples/node/advanced-usage.ts` - Advanced TypeScript features
265
+ - `examples/browser/index.html` - Browser usage with UI
266
+
267
+ ## Development
268
+
269
+ ```bash
270
+ # Install dependencies
271
+ npm install
272
+
273
+ # Build
274
+ npm run build
275
+
276
+ # Run tests
277
+ npm test
278
+
279
+ # Development mode
280
+ npm run dev
281
+
282
+ # Generate docs
283
+ npm run docs
284
+
285
+ # Lint
286
+ npm run lint
287
+ ```
288
+
289
+ ## Testing
290
+
291
+ ```bash
292
+ # Run all tests
293
+ npm test
294
+
295
+ # Run tests in watch mode
296
+ npm run test:watch
297
+
298
+ # Run tests with coverage
299
+ npm run test:coverage
300
+ ```
301
+
302
+ ## Building for Different Environments
303
+
304
+ ### Node.js (CommonJS)
305
+ ```javascript
306
+ const { createClient } = require('koreshield-js');
307
+ ```
308
+
309
+ ### Node.js (ES Modules)
310
+ ```javascript
311
+ import { createClient } from 'koreshield-js';
312
+ ```
313
+
314
+ ### Browser (UMD)
315
+ ```html
316
+ <script src="https://unpkg.com/koreshield-js@latest/dist/index.umd.js"></script>
317
+ <script>
318
+ const client = KoreShield.createClient({ baseURL: '...' });
319
+ </script>
320
+ ```
321
+
322
+ ### Browser (ES Modules)
323
+ ```html
324
+ <script type="module">
325
+ import { createClient } from 'https://unpkg.com/koreshield-js@latest/dist/index.mjs';
326
+ </script>
327
+ ```
328
+
329
+ ## Contributing
330
+
331
+ 1. Fork the repository
332
+ 2. Create a feature branch
333
+ 3. Make your changes
334
+ 4. Add tests
335
+ 5. Run the test suite
336
+ 6. Submit a pull request
337
+
338
+ ## License
339
+
340
+ MIT License - see [LICENSE](LICENSE) file for details.
341
+
342
+ ## Support
343
+
344
+ - [Documentation](https://docs.koreshield.com)
345
+ - [Issues](https://github.com/koreshield/koreshield/issues)
346
+ - [Discussions](https://github.com/koreshield/koreshield/discussions)
347
+ - [Email Support](mailto:support@koreshield.com)
348
+
349
+ ## Security
350
+
351
+ If you discover a security vulnerability, please email security@koreshield.com instead of creating a public issue.
@@ -0,0 +1,201 @@
1
+ /**
2
+ * KoreShield JavaScript/TypeScript SDK Types
3
+ */
4
+ interface KoreShieldConfig {
5
+ /** KoreShield proxy base URL */
6
+ baseURL: string;
7
+ /** API key for authentication (optional, can be set via environment) */
8
+ apiKey?: string;
9
+ /** Request timeout in milliseconds */
10
+ timeout?: number;
11
+ /** Enable debug logging */
12
+ debug?: boolean;
13
+ /** Custom headers to include in all requests */
14
+ headers?: Record<string, string>;
15
+ }
16
+ interface SecurityOptions {
17
+ /** Sensitivity level: 'low', 'medium', 'high' */
18
+ sensitivity?: 'low' | 'medium' | 'high';
19
+ /** Action on detection: 'allow', 'warn', 'block' */
20
+ defaultAction?: 'allow' | 'warn' | 'block';
21
+ /** Enable/disable specific security features */
22
+ features?: {
23
+ sanitization?: boolean;
24
+ detection?: boolean;
25
+ policyEnforcement?: boolean;
26
+ };
27
+ }
28
+ interface ChatCompletionRequest {
29
+ model: string;
30
+ messages: Array<{
31
+ role: 'system' | 'user' | 'assistant';
32
+ content: string;
33
+ }>;
34
+ temperature?: number;
35
+ max_tokens?: number;
36
+ top_p?: number;
37
+ frequency_penalty?: number;
38
+ presence_penalty?: number;
39
+ stop?: string | string[];
40
+ stream?: boolean;
41
+ [key: string]: any;
42
+ }
43
+ interface ChatCompletionResponse {
44
+ id: string;
45
+ object: string;
46
+ created: number;
47
+ model: string;
48
+ choices: Array<{
49
+ index: number;
50
+ message: {
51
+ role: string;
52
+ content: string;
53
+ };
54
+ finish_reason: string;
55
+ }>;
56
+ usage: {
57
+ prompt_tokens: number;
58
+ completion_tokens: number;
59
+ total_tokens: number;
60
+ };
61
+ }
62
+ interface SecurityEvent {
63
+ id: string;
64
+ timestamp: string;
65
+ type: 'attack_detected' | 'request_blocked' | 'sanitization_applied';
66
+ severity: 'low' | 'medium' | 'high' | 'critical';
67
+ description: string;
68
+ details?: Record<string, any>;
69
+ requestId?: string;
70
+ }
71
+ interface MetricsResponse {
72
+ requests_total: number;
73
+ requests_blocked: number;
74
+ attacks_detected: number;
75
+ avg_response_time: number;
76
+ active_connections: number;
77
+ uptime_seconds: number;
78
+ }
79
+ interface KoreShieldError extends Error {
80
+ code: string;
81
+ statusCode?: number;
82
+ details?: Record<string, any>;
83
+ }
84
+ type ProviderType = 'openai' | 'anthropic' | 'deepseek' | 'gemini' | 'azure';
85
+ interface ProviderConfig {
86
+ type: ProviderType;
87
+ apiKey?: string;
88
+ baseURL?: string;
89
+ organization?: string;
90
+ project?: string;
91
+ }
92
+
93
+ /**
94
+ * KoreShield Core Client
95
+ */
96
+
97
+ declare class KoreShieldClient {
98
+ private client;
99
+ private config;
100
+ constructor(config: KoreShieldConfig);
101
+ /**
102
+ * Create a chat completion request through KoreShield
103
+ */
104
+ createChatCompletion(request: ChatCompletionRequest, securityOptions?: SecurityOptions): Promise<ChatCompletionResponse>;
105
+ /**
106
+ * Get security events/logs
107
+ */
108
+ getSecurityEvents(limit?: number, offset?: number, type?: string, severity?: string): Promise<SecurityEvent[]>;
109
+ /**
110
+ * Get metrics and statistics
111
+ */
112
+ getMetrics(): Promise<MetricsResponse>;
113
+ /**
114
+ * Get Prometheus metrics in text format
115
+ */
116
+ getPrometheusMetrics(): Promise<string>;
117
+ /**
118
+ * Health check
119
+ */
120
+ health(): Promise<{
121
+ status: string;
122
+ version: string;
123
+ uptime: number;
124
+ }>;
125
+ /**
126
+ * Update security configuration
127
+ */
128
+ updateSecurityConfig(options: SecurityOptions): Promise<void>;
129
+ /**
130
+ * Test connection to KoreShield
131
+ */
132
+ testConnection(): Promise<boolean>;
133
+ private handleError;
134
+ }
135
+
136
+ declare class KoreShieldOpenAI {
137
+ private client;
138
+ constructor(config: KoreShieldConfig);
139
+ /**
140
+ * Chat completions API (OpenAI-compatible)
141
+ */
142
+ chat(_completions: any): Promise<{
143
+ create: (request: ChatCompletionRequest, securityOptions?: SecurityOptions) => Promise<ChatCompletionResponse>;
144
+ }>;
145
+ /**
146
+ * Get underlying KoreShield client for advanced operations
147
+ */
148
+ getClient(): KoreShieldClient;
149
+ }
150
+ /**
151
+ * Factory function to create OpenAI-compatible instance
152
+ */
153
+ declare function createKoreShieldOpenAI(config: KoreShieldConfig): KoreShieldOpenAI;
154
+
155
+ /**
156
+ * KoreShield Utility Functions
157
+ */
158
+
159
+ /**
160
+ * Validate KoreShield configuration
161
+ */
162
+ declare function validateConfig(config: KoreShieldConfig): {
163
+ valid: boolean;
164
+ errors: string[];
165
+ };
166
+ /**
167
+ * Create a KoreShield client with environment variable defaults
168
+ */
169
+ declare function createClient(config?: Partial<KoreShieldConfig>): KoreShieldClient;
170
+ /**
171
+ * Sanitize user input for safe LLM processing
172
+ */
173
+ declare function sanitizeInput(input: string): string;
174
+ /**
175
+ * Check if a response contains potentially unsafe content
176
+ */
177
+ declare function checkResponseSafety(response: string): {
178
+ safe: boolean;
179
+ issues: string[];
180
+ severity: 'low' | 'medium' | 'high';
181
+ };
182
+ /**
183
+ * Format chat messages for KoreShield
184
+ */
185
+ declare function formatMessages(messages: Array<{
186
+ role: string;
187
+ content: string;
188
+ }>): {
189
+ role: string;
190
+ content: string;
191
+ }[];
192
+ /**
193
+ * Sleep utility for rate limiting
194
+ */
195
+ declare function sleep(ms: number): Promise<void>;
196
+ /**
197
+ * Retry utility with exponential backoff
198
+ */
199
+ declare function retry<T>(fn: () => Promise<T>, maxRetries?: number, baseDelay?: number): Promise<T>;
200
+
201
+ export { ChatCompletionRequest, ChatCompletionResponse, KoreShieldClient, KoreShieldConfig, KoreShieldError, KoreShieldOpenAI, MetricsResponse, ProviderConfig, ProviderType, SecurityEvent, SecurityOptions, checkResponseSafety, createClient, createKoreShieldOpenAI, KoreShieldClient as default, formatMessages, retry, sanitizeInput, sleep, validateConfig };