wolfronix-sdk 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wolfronix
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
+ # @wolfronix/sdk
2
+
3
+ Official JavaScript/TypeScript SDK for Wolfronix - Zero-knowledge encryption made simple.
4
+
5
+ [![npm version](https://badge.fury.io/js/@wolfronix%2Fsdk.svg)](https://www.npmjs.com/package/@wolfronix/sdk)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ## Features
9
+
10
+ - 🔐 **Zero-Knowledge Encryption** - 4-layer enterprise-grade security
11
+ - 🚀 **Simple API** - Encrypt files in 2 lines of code
12
+ - 📦 **TypeScript Native** - Full type definitions included
13
+ - 🌐 **Universal** - Works in Node.js and browsers
14
+ - ⚡ **Streaming** - Handle large files with progress tracking
15
+ - 🔄 **Auto Retry** - Built-in retry logic with exponential backoff
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @wolfronix/sdk
21
+ # or
22
+ yarn add @wolfronix/sdk
23
+ # or
24
+ pnpm add @wolfronix/sdk
25
+ ```
26
+
27
+ ## Quick Start
28
+
29
+ ```typescript
30
+ import Wolfronix from '@wolfronix/sdk';
31
+
32
+ // Initialize client
33
+ const wfx = new Wolfronix({
34
+ baseUrl: 'https://your-wolfronix-server:5002',
35
+ clientId: 'your-client-id' // Optional for enterprise mode
36
+ });
37
+
38
+ // Login
39
+ await wfx.login('user@example.com', 'password123');
40
+
41
+ // Encrypt a file
42
+ const result = await wfx.encrypt(file);
43
+ console.log('Encrypted! File ID:', result.file_id);
44
+
45
+ // Decrypt a file
46
+ const decrypted = await wfx.decrypt(result.file_id);
47
+ ```
48
+
49
+ ## Usage Examples
50
+
51
+ ### Browser (React, Vue, Angular, etc.)
52
+
53
+ ```typescript
54
+ import Wolfronix from '@wolfronix/sdk';
55
+
56
+ const wfx = new Wolfronix('https://wolfronix-server:5002');
57
+
58
+ // With file input
59
+ const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
60
+ const file = event.target.files?.[0];
61
+ if (!file) return;
62
+
63
+ try {
64
+ const { file_id } = await wfx.encrypt(file);
65
+ console.log('File encrypted:', file_id);
66
+ } catch (error) {
67
+ console.error('Encryption failed:', error);
68
+ }
69
+ };
70
+
71
+ // Download decrypted file
72
+ const handleDownload = async (fileId: string, filename: string) => {
73
+ const blob = await wfx.decrypt(fileId);
74
+
75
+ // Create download link
76
+ const url = URL.createObjectURL(blob);
77
+ const a = document.createElement('a');
78
+ a.href = url;
79
+ a.download = filename;
80
+ a.click();
81
+ URL.revokeObjectURL(url);
82
+ };
83
+ ```
84
+
85
+ ### Node.js
86
+
87
+ ```typescript
88
+ import Wolfronix from '@wolfronix/sdk';
89
+ import * as fs from 'fs';
90
+
91
+ const wfx = new Wolfronix({
92
+ baseUrl: 'https://wolfronix-server:5002',
93
+ clientId: 'your-client-id',
94
+ insecure: true // For self-signed certs in development
95
+ });
96
+
97
+ async function main() {
98
+ // Login
99
+ await wfx.login('user@example.com', 'password123');
100
+
101
+ // Encrypt a file
102
+ const fileBuffer = fs.readFileSync('document.pdf');
103
+ const { file_id } = await wfx.encrypt(fileBuffer, 'document.pdf');
104
+ console.log('Encrypted file ID:', file_id);
105
+
106
+ // List all files
107
+ const { files } = await wfx.listFiles();
108
+ console.log('Your files:', files);
109
+
110
+ // Decrypt and save
111
+ const decrypted = await wfx.decryptToBuffer(file_id);
112
+ fs.writeFileSync('decrypted.pdf', Buffer.from(decrypted));
113
+ }
114
+
115
+ main();
116
+ ```
117
+
118
+ ### Large File Streaming with Progress
119
+
120
+ ```typescript
121
+ const wfx = new Wolfronix('https://wolfronix-server:5002');
122
+
123
+ // Encrypt with progress
124
+ const result = await wfx.encryptStream(largeFile, (percent) => {
125
+ console.log(`Uploading: ${percent}%`);
126
+ progressBar.value = percent;
127
+ });
128
+
129
+ // Decrypt with progress
130
+ const blob = await wfx.decryptStream(fileId, (percent) => {
131
+ console.log(`Downloading: ${percent}%`);
132
+ });
133
+ ```
134
+
135
+ ## API Reference
136
+
137
+ ### Constructor
138
+
139
+ ```typescript
140
+ new Wolfronix(config: WolfronixConfig | string)
141
+ ```
142
+
143
+ | Option | Type | Default | Description |
144
+ |--------|------|---------|-------------|
145
+ | `baseUrl` | string | required | Wolfronix server URL |
146
+ | `clientId` | string | `''` | Enterprise client ID |
147
+ | `timeout` | number | `30000` | Request timeout (ms) |
148
+ | `retries` | number | `3` | Max retry attempts |
149
+ | `insecure` | boolean | `false` | Skip SSL verification |
150
+
151
+ ### Authentication
152
+
153
+ | Method | Description |
154
+ |--------|-------------|
155
+ | `register(email, password)` | Register new user |
156
+ | `login(email, password)` | Login existing user |
157
+ | `setToken(token, userId?)` | Set auth token directly |
158
+ | `logout()` | Clear authentication |
159
+ | `isAuthenticated()` | Check auth status |
160
+ | `getUserId()` | Get current user ID |
161
+
162
+ ### File Operations
163
+
164
+ | Method | Description |
165
+ |--------|-------------|
166
+ | `encrypt(file, filename?)` | Encrypt and store file |
167
+ | `encryptStream(file, onProgress?)` | Encrypt large file with progress |
168
+ | `decrypt(fileId)` | Decrypt file (returns Blob) |
169
+ | `decryptToBuffer(fileId)` | Decrypt file (returns ArrayBuffer) |
170
+ | `decryptStream(fileId, onProgress?)` | Decrypt large file with progress |
171
+ | `listFiles()` | List user's encrypted files |
172
+ | `deleteFile(fileId)` | Delete encrypted file |
173
+
174
+ ### Utility
175
+
176
+ | Method | Description |
177
+ |--------|-------------|
178
+ | `getMetrics()` | Get encryption/decryption stats |
179
+ | `healthCheck()` | Check server availability |
180
+
181
+ ## Error Handling
182
+
183
+ The SDK provides specific error types for different scenarios:
184
+
185
+ ```typescript
186
+ import Wolfronix, {
187
+ WolfronixError,
188
+ AuthenticationError,
189
+ FileNotFoundError,
190
+ PermissionDeniedError,
191
+ NetworkError,
192
+ ValidationError
193
+ } from '@wolfronix/sdk';
194
+
195
+ try {
196
+ await wfx.encrypt(file);
197
+ } catch (error) {
198
+ if (error instanceof AuthenticationError) {
199
+ // Token expired, redirect to login
200
+ router.push('/login');
201
+ } else if (error instanceof FileNotFoundError) {
202
+ // File doesn't exist
203
+ showToast('File not found');
204
+ } else if (error instanceof PermissionDeniedError) {
205
+ // Not your file
206
+ showToast('Access denied');
207
+ } else if (error instanceof NetworkError) {
208
+ // Server unreachable
209
+ showToast('Connection failed. Retrying...');
210
+ } else if (error instanceof ValidationError) {
211
+ // Invalid input
212
+ showToast(error.message);
213
+ } else {
214
+ // Unknown error
215
+ console.error('Unexpected error:', error);
216
+ }
217
+ }
218
+ ```
219
+
220
+ ## TypeScript Support
221
+
222
+ The SDK is written in TypeScript and includes full type definitions:
223
+
224
+ ```typescript
225
+ import Wolfronix, {
226
+ WolfronixConfig,
227
+ AuthResponse,
228
+ EncryptResponse,
229
+ FileInfo,
230
+ ListFilesResponse,
231
+ MetricsResponse
232
+ } from '@wolfronix/sdk';
233
+
234
+ // All methods are fully typed
235
+ const config: WolfronixConfig = {
236
+ baseUrl: 'https://server:5002',
237
+ clientId: 'my-client'
238
+ };
239
+
240
+ const wfx = new Wolfronix(config);
241
+ const response: EncryptResponse = await wfx.encrypt(file);
242
+ ```
243
+
244
+ ## React Hook Example
245
+
246
+ ```typescript
247
+ // useWolfronix.ts
248
+ import { useState, useCallback, useMemo } from 'react';
249
+ import Wolfronix, { FileInfo as WolfronixFile } from '@wolfronix/sdk';
250
+
251
+ export function useWolfronix(baseUrl: string, clientId?: string) {
252
+ const [isLoading, setIsLoading] = useState(false);
253
+ const [error, setError] = useState<Error | null>(null);
254
+ const [files, setFiles] = useState<WolfronixFile[]>([]);
255
+
256
+ const client = useMemo(() => new Wolfronix({ baseUrl, clientId }), [baseUrl, clientId]);
257
+
258
+ const login = useCallback(async (email: string, password: string) => {
259
+ setIsLoading(true);
260
+ setError(null);
261
+ try {
262
+ return await client.login(email, password);
263
+ } catch (e) {
264
+ setError(e as Error);
265
+ throw e;
266
+ } finally {
267
+ setIsLoading(false);
268
+ }
269
+ }, [client]);
270
+
271
+ const encrypt = useCallback(async (file: File) => {
272
+ setIsLoading(true);
273
+ setError(null);
274
+ try {
275
+ const result = await client.encrypt(file);
276
+ await refreshFiles();
277
+ return result;
278
+ } catch (e) {
279
+ setError(e as Error);
280
+ throw e;
281
+ } finally {
282
+ setIsLoading(false);
283
+ }
284
+ }, [client]);
285
+
286
+ const decrypt = useCallback(async (fileId: string) => {
287
+ setIsLoading(true);
288
+ setError(null);
289
+ try {
290
+ return await client.decrypt(fileId);
291
+ } catch (e) {
292
+ setError(e as Error);
293
+ throw e;
294
+ } finally {
295
+ setIsLoading(false);
296
+ }
297
+ }, [client]);
298
+
299
+ const refreshFiles = useCallback(async () => {
300
+ const { files } = await client.listFiles();
301
+ setFiles(files);
302
+ }, [client]);
303
+
304
+ return {
305
+ client,
306
+ isLoading,
307
+ error,
308
+ files,
309
+ login,
310
+ encrypt,
311
+ decrypt,
312
+ refreshFiles
313
+ };
314
+ }
315
+
316
+ // Usage in component
317
+ function FileManager() {
318
+ const { files, encrypt, decrypt, isLoading } = useWolfronix(
319
+ 'https://wolfronix:5002',
320
+ 'my-client-id'
321
+ );
322
+
323
+ return (
324
+ <div>
325
+ <input type="file" onChange={(e) => encrypt(e.target.files![0])} />
326
+ {isLoading && <Spinner />}
327
+ {files.map(f => (
328
+ <div key={f.file_id} onClick={() => decrypt(f.file_id)}>
329
+ {f.original_name}
330
+ </div>
331
+ ))}
332
+ </div>
333
+ );
334
+ }
335
+ ```
336
+
337
+ ## Requirements
338
+
339
+ - Node.js 16+ (for Node.js usage)
340
+ - Modern browser with Fetch API support
341
+
342
+ ## License
343
+
344
+ MIT License - see [LICENSE](./LICENSE) for details.
345
+
346
+ ## Links
347
+
348
+ - [Documentation](https://wolfronix.com/docs)
349
+ - [API Reference](https://wolfronix.com/docs/api)
350
+ - [GitHub](https://github.com/wolfronix/sdk-javascript)
351
+ - [Report Issues](https://github.com/wolfronix/sdk-javascript/issues)
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Wolfronix SDK for JavaScript/TypeScript
3
+ * Zero-knowledge encryption made simple
4
+ *
5
+ * @package @wolfronix/sdk
6
+ * @version 1.0.0
7
+ */
8
+ interface WolfronixConfig {
9
+ /** Wolfronix server base URL */
10
+ baseUrl: string;
11
+ /** Your enterprise client ID (optional for self-hosted) */
12
+ clientId?: string;
13
+ /** Request timeout in milliseconds (default: 30000) */
14
+ timeout?: number;
15
+ /** Retry failed requests (default: 3) */
16
+ retries?: number;
17
+ /** Skip SSL verification for self-signed certs (default: false) */
18
+ insecure?: boolean;
19
+ }
20
+ interface AuthResponse {
21
+ success: boolean;
22
+ user_id: string;
23
+ token: string;
24
+ message: string;
25
+ }
26
+ interface EncryptResponse {
27
+ success: boolean;
28
+ file_id: string;
29
+ original_name: string;
30
+ encrypted_size: number;
31
+ message: string;
32
+ }
33
+ interface FileInfo {
34
+ file_id: string;
35
+ original_name: string;
36
+ encrypted_size: number;
37
+ created_at: string;
38
+ }
39
+ interface ListFilesResponse {
40
+ success: boolean;
41
+ files: FileInfo[];
42
+ total: number;
43
+ }
44
+ interface DeleteResponse {
45
+ success: boolean;
46
+ message: string;
47
+ }
48
+ interface MetricsResponse {
49
+ success: boolean;
50
+ total_encryptions: number;
51
+ total_decryptions: number;
52
+ total_bytes_encrypted: number;
53
+ total_bytes_decrypted: number;
54
+ }
55
+ interface StreamToken {
56
+ token: string;
57
+ expires_at: string;
58
+ }
59
+ declare class WolfronixError extends Error {
60
+ readonly code: string;
61
+ readonly statusCode?: number;
62
+ readonly details?: Record<string, unknown>;
63
+ constructor(message: string, code: string, statusCode?: number, details?: Record<string, unknown>);
64
+ }
65
+ declare class AuthenticationError extends WolfronixError {
66
+ constructor(message?: string);
67
+ }
68
+ declare class FileNotFoundError extends WolfronixError {
69
+ constructor(fileId: string);
70
+ }
71
+ declare class PermissionDeniedError extends WolfronixError {
72
+ constructor(message?: string);
73
+ }
74
+ declare class NetworkError extends WolfronixError {
75
+ constructor(message?: string);
76
+ }
77
+ declare class ValidationError extends WolfronixError {
78
+ constructor(message: string);
79
+ }
80
+ declare class Wolfronix {
81
+ private readonly config;
82
+ private token;
83
+ private userId;
84
+ private tokenExpiry;
85
+ /**
86
+ * Create a new Wolfronix client
87
+ *
88
+ * @example
89
+ * ```typescript
90
+ * const wfx = new Wolfronix({
91
+ * baseUrl: 'https://wolfronix-server:5002',
92
+ * clientId: 'your-client-id'
93
+ * });
94
+ * ```
95
+ */
96
+ constructor(config: WolfronixConfig | string);
97
+ private getHeaders;
98
+ private request;
99
+ private sleep;
100
+ private ensureAuthenticated;
101
+ /**
102
+ * Register a new user
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * const { user_id, token } = await wfx.register('user@example.com', 'password123');
107
+ * ```
108
+ */
109
+ register(email: string, password: string): Promise<AuthResponse>;
110
+ /**
111
+ * Login with existing credentials
112
+ *
113
+ * @example
114
+ * ```typescript
115
+ * await wfx.login('user@example.com', 'password123');
116
+ * ```
117
+ */
118
+ login(email: string, password: string): Promise<AuthResponse>;
119
+ /**
120
+ * Set authentication token directly (useful for server-side apps)
121
+ *
122
+ * @example
123
+ * ```typescript
124
+ * wfx.setToken('jwt-token-here', 'user-id-here');
125
+ * ```
126
+ */
127
+ setToken(token: string, userId?: string): void;
128
+ /**
129
+ * Clear authentication state (logout)
130
+ */
131
+ logout(): void;
132
+ /**
133
+ * Check if client is authenticated
134
+ */
135
+ isAuthenticated(): boolean;
136
+ /**
137
+ * Get current user ID
138
+ */
139
+ getUserId(): string | null;
140
+ /**
141
+ * Encrypt and store a file
142
+ *
143
+ * @example
144
+ * ```typescript
145
+ * // Browser
146
+ * const fileInput = document.querySelector('input[type="file"]');
147
+ * const result = await wfx.encrypt(fileInput.files[0]);
148
+ *
149
+ * // Node.js
150
+ * const buffer = fs.readFileSync('document.pdf');
151
+ * const result = await wfx.encrypt(buffer, 'document.pdf');
152
+ * ```
153
+ */
154
+ encrypt(file: File | Blob | ArrayBuffer | Uint8Array, filename?: string): Promise<EncryptResponse>;
155
+ /**
156
+ * Encrypt a file using streaming (for large files)
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * const result = await wfx.encryptStream(largeFile, (progress) => {
161
+ * console.log(`Progress: ${progress}%`);
162
+ * });
163
+ * ```
164
+ */
165
+ encryptStream(file: File | Blob, onProgress?: (percent: number) => void): Promise<EncryptResponse>;
166
+ /**
167
+ * Decrypt and retrieve a file
168
+ *
169
+ * @example
170
+ * ```typescript
171
+ * // Get as Blob (browser)
172
+ * const blob = await wfx.decrypt('file-id');
173
+ * const url = URL.createObjectURL(blob);
174
+ *
175
+ * // Get as Buffer (Node.js)
176
+ * const buffer = await wfx.decryptToBuffer('file-id');
177
+ * fs.writeFileSync('decrypted.pdf', buffer);
178
+ * ```
179
+ */
180
+ decrypt(fileId: string): Promise<Blob>;
181
+ /**
182
+ * Decrypt and return as ArrayBuffer
183
+ */
184
+ decryptToBuffer(fileId: string): Promise<ArrayBuffer>;
185
+ /**
186
+ * Decrypt using streaming (for large files)
187
+ */
188
+ decryptStream(fileId: string, onProgress?: (percent: number) => void): Promise<Blob>;
189
+ /**
190
+ * List all encrypted files for current user
191
+ *
192
+ * @example
193
+ * ```typescript
194
+ * const { files } = await wfx.listFiles();
195
+ * files.forEach(f => console.log(f.original_name, f.file_id));
196
+ * ```
197
+ */
198
+ listFiles(): Promise<ListFilesResponse>;
199
+ /**
200
+ * Delete an encrypted file
201
+ *
202
+ * @example
203
+ * ```typescript
204
+ * await wfx.deleteFile('file-id');
205
+ * ```
206
+ */
207
+ deleteFile(fileId: string): Promise<DeleteResponse>;
208
+ /**
209
+ * Get encryption/decryption metrics
210
+ *
211
+ * @example
212
+ * ```typescript
213
+ * const metrics = await wfx.getMetrics();
214
+ * console.log(`Total encryptions: ${metrics.total_encryptions}`);
215
+ * ```
216
+ */
217
+ getMetrics(): Promise<MetricsResponse>;
218
+ /**
219
+ * Check if server is healthy
220
+ */
221
+ healthCheck(): Promise<boolean>;
222
+ }
223
+ /**
224
+ * Create a new Wolfronix client
225
+ *
226
+ * @example
227
+ * ```typescript
228
+ * import { createClient } from '@wolfronix/sdk';
229
+ *
230
+ * const wfx = createClient({
231
+ * baseUrl: 'https://wolfronix-server:5002',
232
+ * clientId: 'your-client-id'
233
+ * });
234
+ * ```
235
+ */
236
+ declare function createClient(config: WolfronixConfig | string): Wolfronix;
237
+
238
+ export { type AuthResponse, AuthenticationError, type DeleteResponse, type EncryptResponse, type FileInfo, FileNotFoundError, type ListFilesResponse, type MetricsResponse, NetworkError, PermissionDeniedError, type StreamToken, ValidationError, Wolfronix, type WolfronixConfig, WolfronixError, createClient, Wolfronix as default };