@premai/api-sdk 1.0.29

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/dist/cli.cjs ADDED
@@ -0,0 +1,1684 @@
1
+ #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ for (let key of __getOwnPropNames(mod))
23
+ if (!__hasOwnProp.call(to, key))
24
+ __defProp(to, key, {
25
+ get: __accessProp.bind(mod, key),
26
+ enumerable: true
27
+ });
28
+ if (canCache)
29
+ cache.set(mod, to);
30
+ return to;
31
+ };
32
+
33
+ // src/cli.ts
34
+ var import_node_util = require("node:util");
35
+
36
+ // src/server.ts
37
+ var import_dotenv = __toESM(require("dotenv"));
38
+ var import_express = __toESM(require("express"));
39
+ var import_multer = __toESM(require("multer"));
40
+
41
+ // src/audio/index.ts
42
+ var import_utils2 = require("@noble/ciphers/utils.js");
43
+
44
+ // src/config.ts
45
+ var endpoints = {
46
+ enclave: process.env.ENCLAVE_URL,
47
+ proxy: process.env.PROXY_URL
48
+ };
49
+ var DEFAULT_REQUEST_TIMEOUT_MS = 60000;
50
+ var DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
51
+
52
+ // src/utils/attestation.ts
53
+ var import_prem_rs = require("@premai/prem-rs");
54
+ async function attest(apiKey, options = { enabled: true }) {
55
+ if (!options.enabled)
56
+ return null;
57
+ const client = await new import_prem_rs.ClientBuilder(endpoints.proxy ?? "").with_authorization(apiKey).build();
58
+ let query = new import_prem_rs.QueryParams;
59
+ if (options.model)
60
+ query = query.with("model", options.model);
61
+ try {
62
+ const attested = await client.attest(query);
63
+ const headers = attested.headers();
64
+ const sessionId = attested.headers().gpu()?.get("x-session-id") ?? null;
65
+ headers.free();
66
+ attested.free();
67
+ return sessionId;
68
+ } finally {
69
+ client.free();
70
+ }
71
+ }
72
+
73
+ // src/utils/crypto.ts
74
+ var import_aes = require("@noble/ciphers/aes.js");
75
+ var import_chacha = require("@noble/ciphers/chacha.js");
76
+ var import_utils = require("@noble/ciphers/utils.js");
77
+ var import_sha2 = require("@noble/hashes/sha2.js");
78
+ var import_sha3 = require("@noble/hashes/sha3.js");
79
+ var import_hybrid = require("@noble/post-quantum/hybrid.js");
80
+ function createMLKEMEncapsulation(publicKeyHex) {
81
+ return import_hybrid.XWing.encapsulate(import_utils.hexToBytes(publicKeyHex));
82
+ }
83
+ function encryptPayload(sharedSecret, data) {
84
+ const nonce = import_utils.randomBytes(24);
85
+ const chacha = import_chacha.xchacha20poly1305(sharedSecret, nonce);
86
+ let encodedData;
87
+ if (data instanceof Uint8Array) {
88
+ encodedData = data;
89
+ } else if (typeof data === "string") {
90
+ encodedData = new TextEncoder().encode(data);
91
+ } else {
92
+ encodedData = new TextEncoder().encode(JSON.stringify(data));
93
+ }
94
+ const encrypted = chacha.encrypt(encodedData);
95
+ return { encrypted, nonce };
96
+ }
97
+ function decryptPayload(encryptedData, sharedSecret, nonce) {
98
+ const chacha = import_chacha.xchacha20poly1305(sharedSecret, nonce);
99
+ const encrypted = import_utils.hexToBytes(encryptedData);
100
+ const decrypted = chacha.decrypt(encrypted);
101
+ const str = new TextDecoder().decode(decrypted);
102
+ try {
103
+ return JSON.parse(str);
104
+ } catch {
105
+ return str;
106
+ }
107
+ }
108
+ async function getEnclavePublicKey(timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
109
+ const controller = new AbortController;
110
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
111
+ try {
112
+ const response = await fetch(`${endpoints.enclave}/publicKey`, {
113
+ signal: controller.signal
114
+ });
115
+ if (!response.ok) {
116
+ throw new Error(`Failed to fetch enclave public key: ${response.status} ${response.statusText}`);
117
+ }
118
+ const data = await response.json();
119
+ if (!data.publicKey || typeof data.publicKey !== "string") {
120
+ throw new Error("Invalid public key response from enclave");
121
+ }
122
+ return data.publicKey;
123
+ } catch (error) {
124
+ if (error instanceof Error && error.name === "AbortError") {
125
+ throw new Error(`Enclave public key request timed out after ${timeoutMs}ms`);
126
+ }
127
+ throw new Error(`Failed to get enclave public key: ${error instanceof Error ? error.message : error}`);
128
+ } finally {
129
+ clearTimeout(timeoutId);
130
+ }
131
+ }
132
+ async function generateEncryptionKeys(timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
133
+ const enclavePublicKey = await getEnclavePublicKey(timeoutMs);
134
+ return createMLKEMEncapsulation(enclavePublicKey);
135
+ }
136
+ function keyIdFromKEK(kek, context = "kek:v1", length = 16) {
137
+ const ctx = new TextEncoder().encode(context);
138
+ const input = new Uint8Array(kek.length + ctx.length);
139
+ input.set(kek, 0);
140
+ input.set(ctx, kek.length);
141
+ const digest = import_sha2.sha256(input);
142
+ return digest.slice(0, length);
143
+ }
144
+ function encryptWithDEK(dek, plaintext) {
145
+ const aead = import_utils.managedNonce(import_chacha.xchacha20poly1305)(dek);
146
+ return aead.encrypt(plaintext);
147
+ }
148
+ function encryptMetadataWithDEK(dek, metadata) {
149
+ const encoded = new TextEncoder().encode(metadata);
150
+ const encrypted = encryptWithDEK(dek, encoded);
151
+ return import_utils.bytesToHex(encrypted);
152
+ }
153
+ function wrapDEK(kek, dek) {
154
+ const kw = import_aes.aeskwp(kek);
155
+ return kw.encrypt(dek);
156
+ }
157
+ function unwrapDEK(kek, wrappedDEK) {
158
+ const kw = import_aes.aeskwp(kek);
159
+ return kw.decrypt(wrappedDEK);
160
+ }
161
+ function decryptWithDEK(dek, encryptedContent) {
162
+ const aead = import_utils.managedNonce(import_chacha.xchacha20poly1305)(dek);
163
+ return aead.decrypt(encryptedContent);
164
+ }
165
+
166
+ // src/utils/error.ts
167
+ async function throwIfErrorResponse(response) {
168
+ let raw;
169
+ try {
170
+ raw = await response.json();
171
+ if (!raw.status)
172
+ raw = { ...raw, status: response.status };
173
+ } catch {
174
+ raw = {
175
+ status: response.status,
176
+ data: null,
177
+ error: response.statusText || `HTTP ${response.status}`,
178
+ message: null
179
+ };
180
+ }
181
+ throw raw;
182
+ }
183
+
184
+ // src/utils/files.ts
185
+ var getFileName = (file) => {
186
+ if (file instanceof File) {
187
+ return file.name;
188
+ }
189
+ if (file instanceof Blob) {
190
+ return;
191
+ }
192
+ const fileAny = file;
193
+ if (fileAny.path) {
194
+ const path = typeof fileAny.path === "string" ? fileAny.path : fileAny.path.toString();
195
+ return path.split("/").pop() || path.split("\\").pop() || path;
196
+ }
197
+ if (file instanceof Uint8Array || file instanceof ArrayBuffer) {
198
+ return;
199
+ }
200
+ return;
201
+ };
202
+
203
+ // src/audio/index.ts
204
+ async function readUploadableToUint8Array(file) {
205
+ if (file instanceof Uint8Array) {
206
+ return file;
207
+ }
208
+ if (file instanceof ArrayBuffer) {
209
+ return new Uint8Array(file);
210
+ }
211
+ if (typeof file.arrayBuffer === "function") {
212
+ const blob = file;
213
+ const buffer = await blob.arrayBuffer();
214
+ return new Uint8Array(buffer);
215
+ }
216
+ const fileAny = file;
217
+ if (typeof fileAny.on === "function" && (typeof fileAny.read === "function" || typeof fileAny.pipe === "function")) {
218
+ const chunks = [];
219
+ return new Promise((resolve, reject) => {
220
+ fileAny.on("data", (chunk) => {
221
+ if (Buffer.isBuffer(chunk)) {
222
+ chunks.push(new Uint8Array(chunk));
223
+ } else if (chunk instanceof Uint8Array) {
224
+ chunks.push(chunk);
225
+ } else if (typeof chunk === "object" && chunk !== null) {
226
+ chunks.push(new Uint8Array(Buffer.from(chunk)));
227
+ }
228
+ });
229
+ fileAny.on("end", () => {
230
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
231
+ const result = new Uint8Array(totalLength);
232
+ let offset = 0;
233
+ for (const chunk of chunks) {
234
+ result.set(chunk, offset);
235
+ offset += chunk.length;
236
+ }
237
+ resolve(result);
238
+ });
239
+ fileAny.on("error", (err) => reject(err));
240
+ });
241
+ }
242
+ throw new Error("Unsupported file type for audio transcription");
243
+ }
244
+ async function preprocessAudioRequest(body, encryptionKeys) {
245
+ const { cipherText, sharedSecret } = encryptionKeys;
246
+ const audioData = await readUploadableToUint8Array(body.file);
247
+ const isDeepgram = body.model.startsWith("deepgram/");
248
+ const requestBody = isDeepgram ? {
249
+ model: body.model,
250
+ diarize: body.diarize
251
+ } : {
252
+ model: body.model,
253
+ language: body.language,
254
+ prompt: body.prompt,
255
+ response_format: body.response_format,
256
+ temperature: body.temperature,
257
+ timestamp_granularities: body.timestamp_granularities
258
+ };
259
+ const cleanedBody = Object.fromEntries(Object.entries(requestBody).filter(([_, v]) => v !== undefined));
260
+ const { encrypted, nonce } = encryptPayload(sharedSecret, cleanedBody);
261
+ const { encrypted: encryptedFile, nonce: fileNonce } = encryptPayload(sharedSecret, audioData);
262
+ const fileName = getFileName(body.file) || "audio.mp3";
263
+ const { encrypted: encryptedFileName, nonce: fileNameNonce } = encryptPayload(sharedSecret, fileName);
264
+ return {
265
+ body: {
266
+ cipherText: import_utils2.bytesToHex(cipherText),
267
+ encryptedInference: import_utils2.bytesToHex(encrypted),
268
+ nonce: import_utils2.bytesToHex(nonce),
269
+ fileNameNonce: import_utils2.bytesToHex(fileNameNonce),
270
+ encryptedFileName: import_utils2.bytesToHex(encryptedFileName),
271
+ fileNonce: import_utils2.bytesToHex(fileNonce),
272
+ encryptedFile: import_utils2.bytesToHex(encryptedFile),
273
+ model: body.model
274
+ },
275
+ sharedSecret
276
+ };
277
+ }
278
+ async function postprocessTranscriptionResponse(response, sharedSecret) {
279
+ const responseData = await response.json();
280
+ const data = responseData.data;
281
+ if (!data.encryptedResponse || !data.nonce) {
282
+ throw new Error("Invalid transcription response: missing encryptedResponse or nonce");
283
+ }
284
+ const responseNonce = import_utils2.hexToBytes(data.nonce);
285
+ return decryptPayload(data.encryptedResponse, sharedSecret, responseNonce);
286
+ }
287
+ async function postprocessTranslationResponse(response, sharedSecret) {
288
+ const responseData = await response.json();
289
+ const data = responseData.data;
290
+ if (!data.encryptedResponse || !data.nonce) {
291
+ throw new Error("Invalid translation response: missing encryptedResponse or nonce");
292
+ }
293
+ const responseNonce = import_utils2.hexToBytes(data.nonce);
294
+ return decryptPayload(data.encryptedResponse, sharedSecret, responseNonce);
295
+ }
296
+ async function preprocessAudioTranslationRequest(body, encryptionKeys) {
297
+ const { cipherText, sharedSecret } = encryptionKeys;
298
+ const audioData = await readUploadableToUint8Array(body.file);
299
+ const requestBody = {
300
+ model: body.model,
301
+ prompt: body.prompt,
302
+ response_format: body.response_format,
303
+ temperature: body.temperature
304
+ };
305
+ const cleanedBody = Object.fromEntries(Object.entries(requestBody).filter(([_, v]) => v !== undefined));
306
+ const { encrypted, nonce } = encryptPayload(sharedSecret, cleanedBody);
307
+ const { encrypted: encryptedFile, nonce: fileNonce } = encryptPayload(sharedSecret, audioData);
308
+ const fileName = getFileName(body.file) || "audio.mp3";
309
+ const { encrypted: encryptedFileName, nonce: fileNameNonce } = encryptPayload(sharedSecret, fileName);
310
+ return {
311
+ body: {
312
+ cipherText: import_utils2.bytesToHex(cipherText),
313
+ encryptedInference: import_utils2.bytesToHex(encrypted),
314
+ nonce: import_utils2.bytesToHex(nonce),
315
+ fileNameNonce: import_utils2.bytesToHex(fileNameNonce),
316
+ encryptedFileName: import_utils2.bytesToHex(encryptedFileName),
317
+ fileNonce: import_utils2.bytesToHex(fileNonce),
318
+ encryptedFile: import_utils2.bytesToHex(encryptedFile),
319
+ model: body.model
320
+ },
321
+ sharedSecret
322
+ };
323
+ }
324
+ function createAudioClient(apiKey, encryptionKeys, requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, attest2 = true) {
325
+ async function createTranscription(body) {
326
+ const controller = new AbortController;
327
+ const timeoutId = setTimeout(() => controller.abort(), requestTimeoutMs);
328
+ try {
329
+ const sessionId = await attest(apiKey, { model: body.model, enabled: attest2 });
330
+ const encryptedRequest = await preprocessAudioRequest(body, encryptionKeys);
331
+ const response = await fetch(`${endpoints.proxy}/rvenc/audio/transcriptions`, {
332
+ method: "POST",
333
+ headers: {
334
+ "Content-Type": "application/json",
335
+ Authorization: apiKey,
336
+ ...sessionId && { "X-Session-Id": sessionId }
337
+ },
338
+ body: JSON.stringify(encryptedRequest.body),
339
+ signal: controller.signal
340
+ });
341
+ if (!response.ok) {
342
+ await throwIfErrorResponse(response);
343
+ }
344
+ clearTimeout(timeoutId);
345
+ return await postprocessTranscriptionResponse(response, encryptedRequest.sharedSecret);
346
+ } catch (error) {
347
+ clearTimeout(timeoutId);
348
+ if (error instanceof Error && error.name === "AbortError") {
349
+ throw new Error(`Request timed out after ${requestTimeoutMs}ms`);
350
+ }
351
+ throw error;
352
+ }
353
+ }
354
+ const transcriptionsClient = {
355
+ create: createTranscription
356
+ };
357
+ async function createTranslation(body) {
358
+ const controller = new AbortController;
359
+ const timeoutId = setTimeout(() => controller.abort(), requestTimeoutMs);
360
+ try {
361
+ const sessionId = await attest(apiKey, { model: body.model, enabled: attest2 });
362
+ const encryptedRequest = await preprocessAudioTranslationRequest(body, encryptionKeys);
363
+ const response = await fetch(`${endpoints.proxy}/rvenc/audio/translations`, {
364
+ method: "POST",
365
+ headers: {
366
+ "Content-Type": "application/json",
367
+ Authorization: apiKey,
368
+ ...sessionId && { "X-Session-Id": sessionId }
369
+ },
370
+ body: JSON.stringify(encryptedRequest.body),
371
+ signal: controller.signal
372
+ });
373
+ if (!response.ok) {
374
+ await throwIfErrorResponse(response);
375
+ }
376
+ clearTimeout(timeoutId);
377
+ return await postprocessTranslationResponse(response, encryptedRequest.sharedSecret);
378
+ } catch (error) {
379
+ clearTimeout(timeoutId);
380
+ if (error instanceof Error && error.name === "AbortError") {
381
+ throw new Error(`Request timed out after ${requestTimeoutMs}ms`);
382
+ }
383
+ throw error;
384
+ }
385
+ }
386
+ const translationsClient = {
387
+ create: createTranslation
388
+ };
389
+ return {
390
+ transcriptions: transcriptionsClient,
391
+ translations: translationsClient
392
+ };
393
+ }
394
+
395
+ // src/files/index.ts
396
+ var import_utils4 = require("@noble/ciphers/utils.js");
397
+ var import_sha22 = require("@noble/hashes/sha2.js");
398
+ var import_date_fns = require("date-fns");
399
+ var import_zod = require("zod");
400
+
401
+ // src/utils/dek-store.ts
402
+ var import_utils3 = require("@noble/ciphers/utils.js");
403
+ function initializeDEKStore(clientKEK) {
404
+ const ragDEK = import_utils3.randomBytes(32);
405
+ const _clientKEK = clientKEK ? import_utils3.hexToBytes(clientKEK) : getClientKEK();
406
+ const wrappedRagDEK = wrapDEK(_clientKEK, ragDEK);
407
+ return {
408
+ fileDEKs: new Map,
409
+ ragDEK: wrappedRagDEK,
410
+ ragVersion: "2"
411
+ };
412
+ }
413
+ function getClientKEK() {
414
+ if (!process.env.CLIENT_KEK) {
415
+ throw new Error("CLIENT_KEK environment variable is not set.");
416
+ }
417
+ return import_utils3.hexToBytes(process.env.CLIENT_KEK);
418
+ }
419
+ function getClientKID(clientKEK) {
420
+ if (clientKEK) {
421
+ return import_utils3.bytesToHex(keyIdFromKEK(import_utils3.hexToBytes(clientKEK)));
422
+ }
423
+ const _clientKEK = getClientKEK();
424
+ return import_utils3.bytesToHex(keyIdFromKEK(_clientKEK));
425
+ }
426
+
427
+ // src/files/index.ts
428
+ var MAX_FILENAME_LENGTH = 255;
429
+ var MIN_FILENAME_LENGTH = 1;
430
+ var ALLOWED_MIME_TYPES = new Set([
431
+ "image/jpeg",
432
+ "image/png",
433
+ "image/gif",
434
+ "image/webp",
435
+ "application/pdf",
436
+ "application/msword",
437
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
438
+ "application/vnd.ms-excel",
439
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
440
+ "text/plain",
441
+ "text/csv",
442
+ "text/markdown",
443
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
444
+ "video/mp4",
445
+ "video/webm",
446
+ "video/quicktime",
447
+ "audio/mpeg",
448
+ "audio/wav",
449
+ "audio/ogg",
450
+ "application/zip",
451
+ "application/x-rar-compressed",
452
+ "application/x-7z-compressed",
453
+ "application/octet-stream"
454
+ ]);
455
+ var ApiKeySchema = import_zod.z.string().trim().min(1, "API key cannot be empty");
456
+ var TimeoutSchema = import_zod.z.number().int().min(1, "Timeout must be at least 1ms").max(600000, "Timeout must not exceed 600000ms (10 minutes)");
457
+ var DEKStoreSchema = import_zod.z.object({
458
+ ragDEK: import_zod.z.instanceof(Uint8Array).optional(),
459
+ fileDEKs: import_zod.z.instanceof(Map).optional()
460
+ });
461
+ var ISO8601DateSchema = import_zod.z.string().refine((val) => {
462
+ const date = import_date_fns.parseISO(val);
463
+ return import_date_fns.isValid(date);
464
+ }, { message: "Must be a valid ISO8601 date" });
465
+ var MimeTypeSchema = import_zod.z.string().refine((val) => ALLOWED_MIME_TYPES.has(val), {
466
+ message: "MIME type is not allowed"
467
+ });
468
+ var FileUploadOptionsSchema = import_zod.z.object({
469
+ file: import_zod.z.instanceof(Uint8Array),
470
+ fileName: import_zod.z.string().min(MIN_FILENAME_LENGTH, "File name cannot be empty").max(MAX_FILENAME_LENGTH, `File name cannot exceed ${MAX_FILENAME_LENGTH} characters`).refine((name) => !/[<>:"|?*\x00-\x1F]/.test(name), "Invalid characters").refine((name) => !name.includes("..") && !name.includes("/") && !name.includes("\\"), "No path separators allowed"),
471
+ mimeType: import_zod.z.string().optional(),
472
+ ragIndex: import_zod.z.boolean().optional()
473
+ });
474
+ var ListFilesOptionsSchema = import_zod.z.object({
475
+ limit: import_zod.z.number().int().positive("Limit must be a positive integer").optional(),
476
+ offset: import_zod.z.number().int().nonnegative("Offset must be a non-negative integer").optional(),
477
+ search: import_zod.z.string().optional(),
478
+ from: ISO8601DateSchema.optional(),
479
+ to: ISO8601DateSchema.optional()
480
+ }).optional();
481
+ var GetFileOptionsSchema = import_zod.z.object({
482
+ id: import_zod.z.string().trim().min(1, "File ID cannot be empty"),
483
+ url: import_zod.z.boolean().optional()
484
+ });
485
+ var DeleteFileOptionsSchema = import_zod.z.object({
486
+ id: import_zod.z.string().min(1, "File ID is required")
487
+ });
488
+ var IndexFileInputSchema = import_zod.z.object({
489
+ fileId: import_zod.z.string().min(1, "File ID is required"),
490
+ filePath: import_zod.z.string().min(1, "File path is required"),
491
+ fileDEK: import_zod.z.instanceof(Uint8Array).optional()
492
+ });
493
+ var IndexFilesOptionsSchema = import_zod.z.object({
494
+ files: import_zod.z.array(IndexFileInputSchema).min(1, "Files array must not be empty"),
495
+ ragDEK: import_zod.z.instanceof(Uint8Array).optional()
496
+ });
497
+ var DeleteIndexOptionsSchema = import_zod.z.object({
498
+ fileIds: import_zod.z.array(import_zod.z.string().min(1)).min(1, "File IDs array must not be empty"),
499
+ ragDEK: import_zod.z.instanceof(Uint8Array).optional()
500
+ });
501
+ function validateAPIKey(apiKey) {
502
+ ApiKeySchema.parse(apiKey);
503
+ }
504
+ function validateDEKStore(dekStore) {
505
+ DEKStoreSchema.parse(dekStore);
506
+ }
507
+ function validateMimeType(mimeType) {
508
+ MimeTypeSchema.parse(mimeType);
509
+ }
510
+ function validateFileUploadOptions(options) {
511
+ FileUploadOptionsSchema.parse(options);
512
+ }
513
+ function validateListFilesOptions(options) {
514
+ ListFilesOptionsSchema.parse(options);
515
+ }
516
+ function validateGetFileOptions(options) {
517
+ GetFileOptionsSchema.parse(options);
518
+ }
519
+ function guessMimeType(fileName) {
520
+ const ext = fileName.toLowerCase().split(".").pop() || "";
521
+ const mimeTypeMap = {
522
+ jpg: "image/jpeg",
523
+ jpeg: "image/jpeg",
524
+ png: "image/png",
525
+ gif: "image/gif",
526
+ webp: "image/webp",
527
+ pdf: "application/pdf",
528
+ doc: "application/msword",
529
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
530
+ xls: "application/vnd.ms-excel",
531
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
532
+ txt: "text/plain",
533
+ csv: "text/csv",
534
+ md: "text/markdown",
535
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
536
+ mp4: "video/mp4",
537
+ webm: "video/webm",
538
+ mov: "video/quicktime",
539
+ mp3: "audio/mpeg",
540
+ wav: "audio/wav",
541
+ ogg: "audio/ogg",
542
+ zip: "application/zip",
543
+ rar: "application/x-rar-compressed",
544
+ "7z": "application/x-7z-compressed"
545
+ };
546
+ return mimeTypeMap[ext] || "application/octet-stream";
547
+ }
548
+ async function saveRagDEKToBackend(apiKey, wrappedRagDEK, timeoutMs) {
549
+ const controller = new AbortController;
550
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
551
+ try {
552
+ const response = await fetch(`${endpoints.proxy}/users/save_rag_dek`, {
553
+ method: "POST",
554
+ headers: {
555
+ Authorization: apiKey,
556
+ "Content-Type": "application/json"
557
+ },
558
+ body: JSON.stringify({
559
+ data: {
560
+ wrappedRagDEK,
561
+ confirmReplaceRagDEK: true
562
+ }
563
+ }),
564
+ signal: controller.signal
565
+ });
566
+ if (!response.ok) {
567
+ throw new Error(`Failed to save RAG DEK: HTTP ${response.status}`);
568
+ }
569
+ const result = await response.json();
570
+ if (result.error) {
571
+ throw new Error(result.error);
572
+ }
573
+ } catch (error) {
574
+ if (error instanceof Error && error.name === "AbortError") {
575
+ throw new Error(`Save RAG DEK request timed out after ${timeoutMs}ms`);
576
+ }
577
+ throw error;
578
+ } finally {
579
+ clearTimeout(timeoutId);
580
+ }
581
+ }
582
+ async function prepareEncryptedPayload(dekStore, options, apiKey, clientKEK, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
583
+ const fileBytes = options.file;
584
+ const mimeType = options.mimeType || guessMimeType(options.fileName);
585
+ validateMimeType(mimeType);
586
+ const dek = import_utils4.randomBytes(32);
587
+ const encryptedFile = encryptWithDEK(dek, fileBytes);
588
+ const encryptedName = encryptMetadataWithDEK(dek, options.fileName);
589
+ const encryptedMimeType = encryptMetadataWithDEK(dek, mimeType);
590
+ const _clientKEK = clientKEK ? import_utils4.hexToBytes(clientKEK) : getClientKEK();
591
+ const wrappedDEK = wrapDEK(_clientKEK, dek);
592
+ const clientKID = clientKEK ? getClientKID(clientKEK) : getClientKID();
593
+ const filePayload = {
594
+ client_hash: import_utils4.bytesToHex(import_sha22.sha256(fileBytes)),
595
+ encrypted_content: import_utils4.bytesToHex(encryptedFile),
596
+ encrypted_name: encryptedName,
597
+ kid: clientKID,
598
+ mime_type: encryptedMimeType,
599
+ version: "2",
600
+ wrapped_dek: import_utils4.bytesToHex(wrappedDEK)
601
+ };
602
+ if (options.ragIndex) {
603
+ await addRagIndexToPayload(dekStore, dek, filePayload, apiKey, clientKEK, timeoutMs);
604
+ }
605
+ return { dek, filePayload };
606
+ }
607
+ async function addRagIndexToPayload(dekStore, dek, filePayload, apiKey, clientKEK, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
608
+ let ragDEK = dekStore.ragDEK;
609
+ const _clientKEK = clientKEK ? import_utils4.hexToBytes(clientKEK) : getClientKEK();
610
+ if (!ragDEK) {
611
+ ragDEK = import_utils4.randomBytes(32);
612
+ const wrappedRagDEK = wrapDEK(_clientKEK, ragDEK);
613
+ dekStore.ragDEK = wrappedRagDEK;
614
+ try {
615
+ await saveRagDEKToBackend(apiKey, import_utils4.bytesToHex(wrappedRagDEK), timeoutMs);
616
+ } catch (error) {
617
+ console.error("Warning: Failed to save RAG DEK to backend:", error);
618
+ }
619
+ } else {
620
+ ragDEK = unwrapDEK(_clientKEK, ragDEK);
621
+ }
622
+ const enclavePublicKey = await getEnclavePublicKey(timeoutMs);
623
+ const { cipherText, sharedSecret } = createMLKEMEncapsulation(enclavePublicKey);
624
+ const { encrypted: encryptedFileDEK, nonce: fileNonce } = encryptPayload(sharedSecret, dek);
625
+ const { encrypted: encryptedRagDEK, nonce: ragDEKNonce } = encryptPayload(sharedSecret, ragDEK);
626
+ filePayload.encrypted_file_dek = import_utils4.bytesToHex(encryptedFileDEK);
627
+ filePayload.encrypted_rag_dek = import_utils4.bytesToHex(encryptedRagDEK);
628
+ filePayload.file_nonce = import_utils4.bytesToHex(fileNonce);
629
+ filePayload.rag_dek_nonce = import_utils4.bytesToHex(ragDEKNonce);
630
+ filePayload.cipher_text = import_utils4.bytesToHex(cipherText);
631
+ }
632
+ async function performUpload(apiKey, filePayload, controller) {
633
+ const uploadResponse = await fetch(`${endpoints.proxy}/files/encrypted/upload`, {
634
+ method: "POST",
635
+ headers: {
636
+ Authorization: apiKey,
637
+ "Content-Type": "application/json"
638
+ },
639
+ body: JSON.stringify(filePayload),
640
+ signal: controller.signal
641
+ });
642
+ if (!uploadResponse.ok) {
643
+ let errorMessage = `Upload request failed with status ${uploadResponse.status}`;
644
+ try {
645
+ const body = await uploadResponse.json();
646
+ if (body.error) {
647
+ errorMessage = body.error;
648
+ }
649
+ } catch {}
650
+ throw new Error(errorMessage);
651
+ }
652
+ const uploadResult = await uploadResponse.json();
653
+ if (uploadResult.status !== 200) {
654
+ throw new Error(uploadResult.error || "Upload failed");
655
+ }
656
+ if (!uploadResult.data) {
657
+ throw new Error("Upload response missing data");
658
+ }
659
+ return uploadResult.data;
660
+ }
661
+ function storeDEKForFile(dekStore, fileId, dek, clientKEK) {
662
+ if (!dekStore.fileDEKs) {
663
+ dekStore.fileDEKs = new Map;
664
+ }
665
+ const _clientKEK = clientKEK ? import_utils4.hexToBytes(clientKEK) : getClientKEK();
666
+ const wrappedDEK = wrapDEK(_clientKEK, dek);
667
+ dekStore.fileDEKs.set(fileId, wrappedDEK);
668
+ }
669
+ async function uploadFile(apiKey, dekStore, options, clientKEK, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
670
+ validateAPIKey(apiKey);
671
+ validateDEKStore(dekStore);
672
+ validateFileUploadOptions(options);
673
+ TimeoutSchema.parse(timeoutMs);
674
+ const controller = new AbortController;
675
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
676
+ try {
677
+ const { dek, filePayload } = await prepareEncryptedPayload(dekStore, options, apiKey, clientKEK, timeoutMs);
678
+ const uploadedFile = await performUpload(apiKey, filePayload, controller);
679
+ storeDEKForFile(dekStore, uploadedFile.id, dek, clientKEK);
680
+ return uploadedFile;
681
+ } catch (error) {
682
+ if (error instanceof Error && error.name === "AbortError") {
683
+ throw new Error(`File upload timed out after ${timeoutMs}ms`);
684
+ }
685
+ throw error;
686
+ } finally {
687
+ clearTimeout(timeoutId);
688
+ }
689
+ }
690
+ async function listFiles(apiKey, options, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
691
+ validateAPIKey(apiKey);
692
+ validateListFilesOptions(options);
693
+ TimeoutSchema.parse(timeoutMs);
694
+ const controller = new AbortController;
695
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
696
+ const queryParams = new URLSearchParams;
697
+ if (options?.limit !== undefined) {
698
+ queryParams.append("limit", options.limit.toString());
699
+ }
700
+ if (options?.offset !== undefined) {
701
+ queryParams.append("offset", options.offset.toString());
702
+ }
703
+ if (options?.search) {
704
+ queryParams.append("search", options.search);
705
+ }
706
+ if (options?.from) {
707
+ queryParams.append("from", options.from);
708
+ }
709
+ if (options?.to) {
710
+ queryParams.append("to", options.to);
711
+ }
712
+ const queryString = queryParams.toString();
713
+ const url = `${endpoints.proxy}/files/encrypted${queryString ? `?${queryString}` : ""}`;
714
+ try {
715
+ const response = await fetch(url, {
716
+ method: "GET",
717
+ headers: {
718
+ Authorization: apiKey,
719
+ "Content-Type": "application/json"
720
+ },
721
+ signal: controller.signal
722
+ });
723
+ if (!response.ok) {
724
+ throw new Error(`List files request failed with status ${response.status}`);
725
+ }
726
+ const result = await response.json();
727
+ if (result.status !== 200) {
728
+ throw new Error(result.error || "List files failed");
729
+ }
730
+ if (!result.data) {
731
+ throw new Error("List files response missing data");
732
+ }
733
+ return result.data;
734
+ } catch (error) {
735
+ if (error instanceof Error && error.name === "AbortError") {
736
+ throw new Error(`List files request timed out after ${timeoutMs}ms`);
737
+ }
738
+ throw error;
739
+ } finally {
740
+ clearTimeout(timeoutId);
741
+ }
742
+ }
743
+ async function getFile(apiKey, options, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
744
+ validateAPIKey(apiKey);
745
+ validateGetFileOptions(options);
746
+ TimeoutSchema.parse(timeoutMs);
747
+ const controller = new AbortController;
748
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
749
+ const queryParams = new URLSearchParams;
750
+ if (options.url !== undefined) {
751
+ queryParams.append("url", options.url ? "true" : "false");
752
+ }
753
+ const queryString = queryParams.toString();
754
+ const url = `${endpoints.proxy}/files/encrypted/${options.id}${queryString ? `?${queryString}` : ""}`;
755
+ try {
756
+ const response = await fetch(url, {
757
+ method: "GET",
758
+ headers: {
759
+ Authorization: apiKey,
760
+ "Content-Type": "application/json"
761
+ },
762
+ signal: controller.signal
763
+ });
764
+ if (!response.ok) {
765
+ if (response.status === 404) {
766
+ throw new Error(`File not found: ${options.id}`);
767
+ }
768
+ throw new Error(`Get file request failed with status ${response.status}`);
769
+ }
770
+ const result = await response.json();
771
+ if (result.status !== 200) {
772
+ throw new Error(result.error || "Get file failed");
773
+ }
774
+ if (!result.data) {
775
+ throw new Error("Get file response missing data");
776
+ }
777
+ return result.data;
778
+ } catch (error) {
779
+ if (error instanceof Error && error.name === "AbortError") {
780
+ throw new Error(`Get file request timed out after ${timeoutMs}ms`);
781
+ }
782
+ throw error;
783
+ } finally {
784
+ clearTimeout(timeoutId);
785
+ }
786
+ }
787
+ async function deleteFile(apiKey, options, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
788
+ validateAPIKey(apiKey);
789
+ DeleteFileOptionsSchema.parse(options);
790
+ TimeoutSchema.parse(timeoutMs);
791
+ const controller = new AbortController;
792
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
793
+ try {
794
+ const response = await fetch(`${endpoints.proxy}/files/encrypted/${options.id}`, {
795
+ method: "DELETE",
796
+ headers: {
797
+ Authorization: apiKey,
798
+ "Content-Type": "application/json"
799
+ },
800
+ signal: controller.signal
801
+ });
802
+ if (!response.ok) {
803
+ if (response.status === 404) {
804
+ throw new Error(`File not found: ${options.id}`);
805
+ }
806
+ throw new Error(`Delete file request failed with status ${response.status}`);
807
+ }
808
+ await response.json();
809
+ } catch (error) {
810
+ if (error instanceof Error && error.name === "AbortError") {
811
+ throw new Error(`Delete file request timed out after ${timeoutMs}ms`);
812
+ }
813
+ throw error;
814
+ } finally {
815
+ clearTimeout(timeoutId);
816
+ }
817
+ }
818
+ async function indexFiles(apiKey, dekStore, options, clientKEK, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
819
+ validateAPIKey(apiKey);
820
+ validateDEKStore(dekStore);
821
+ IndexFilesOptionsSchema.parse(options);
822
+ TimeoutSchema.parse(timeoutMs);
823
+ const wrappedRagDEK = options.ragDEK || dekStore.ragDEK;
824
+ if (!wrappedRagDEK) {
825
+ throw new Error("RAG DEK not found. Provide ragDEK in options or upload at least one file with ragIndex: true.");
826
+ }
827
+ const _clientKEK = clientKEK ? import_utils4.hexToBytes(clientKEK) : getClientKEK();
828
+ const ragDEK = unwrapDEK(_clientKEK, wrappedRagDEK);
829
+ const enclavePublicKey = await getEnclavePublicKey(timeoutMs);
830
+ const { cipherText, sharedSecret } = createMLKEMEncapsulation(enclavePublicKey);
831
+ const encryptedFiles = options.files.map((file) => {
832
+ const wrappedFileDEK = file.fileDEK || dekStore.fileDEKs?.get(file.fileId);
833
+ if (!wrappedFileDEK) {
834
+ throw new Error(`File DEK not found for file: ${file.fileId}. Provide fileDEK or ensure file was uploaded with this DEK store.`);
835
+ }
836
+ const fileDEK = unwrapDEK(_clientKEK, wrappedFileDEK);
837
+ const { encrypted: encryptedFileDEK, nonce: fileNonce } = encryptPayload(sharedSecret, fileDEK);
838
+ const { encrypted: encryptedRagDEK, nonce: ragDEKNonce } = encryptPayload(sharedSecret, ragDEK);
839
+ return {
840
+ file_id: file.fileId,
841
+ encrypted_file_dek: import_utils4.bytesToHex(encryptedFileDEK),
842
+ encrypted_rag_dek: import_utils4.bytesToHex(encryptedRagDEK),
843
+ file_nonce: import_utils4.bytesToHex(fileNonce),
844
+ rag_dek_nonce: import_utils4.bytesToHex(ragDEKNonce),
845
+ s3_r2_path: file.filePath,
846
+ cipher_text: import_utils4.bytesToHex(cipherText)
847
+ };
848
+ });
849
+ const controller = new AbortController;
850
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
851
+ try {
852
+ const response = await fetch(`${endpoints.proxy}/files/encrypted/index`, {
853
+ method: "POST",
854
+ headers: {
855
+ Authorization: apiKey,
856
+ "Content-Type": "application/json"
857
+ },
858
+ body: JSON.stringify({ files: encryptedFiles }),
859
+ signal: controller.signal
860
+ });
861
+ if (!response.ok) {
862
+ throw new Error(`Index files request failed with status ${response.status}`);
863
+ }
864
+ const result = await response.json();
865
+ return result;
866
+ } catch (error) {
867
+ if (error instanceof Error && error.name === "AbortError") {
868
+ throw new Error(`Index files request timed out after ${timeoutMs}ms`);
869
+ }
870
+ throw error;
871
+ } finally {
872
+ clearTimeout(timeoutId);
873
+ }
874
+ }
875
+ async function deleteIndex(apiKey, dekStore, options, clientKEK, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
876
+ validateAPIKey(apiKey);
877
+ validateDEKStore(dekStore);
878
+ DeleteIndexOptionsSchema.parse(options);
879
+ TimeoutSchema.parse(timeoutMs);
880
+ const wrappedRagDEK = options.ragDEK || dekStore.ragDEK;
881
+ if (!wrappedRagDEK) {
882
+ throw new Error("RAG DEK not found. Provide ragDEK in options or ensure dekStore has a ragDEK.");
883
+ }
884
+ const _clientKEK = clientKEK ? import_utils4.hexToBytes(clientKEK) : getClientKEK();
885
+ const ragDEK = unwrapDEK(_clientKEK, wrappedRagDEK);
886
+ const enclavePublicKey = await getEnclavePublicKey(timeoutMs);
887
+ const { cipherText, sharedSecret } = createMLKEMEncapsulation(enclavePublicKey);
888
+ const { encrypted: encryptedRagDEK, nonce: ragDEKNonce } = encryptPayload(sharedSecret, ragDEK);
889
+ const controller = new AbortController;
890
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
891
+ try {
892
+ const response = await fetch(`${endpoints.proxy}/files/encrypted/delete-index`, {
893
+ method: "POST",
894
+ headers: {
895
+ Authorization: apiKey,
896
+ "Content-Type": "application/json"
897
+ },
898
+ body: JSON.stringify({
899
+ cipher_text: import_utils4.bytesToHex(cipherText),
900
+ encrypted_rag_dek: import_utils4.bytesToHex(encryptedRagDEK),
901
+ rag_dek_nonce: import_utils4.bytesToHex(ragDEKNonce),
902
+ fileIds: options.fileIds
903
+ }),
904
+ signal: controller.signal
905
+ });
906
+ if (!response.ok) {
907
+ throw new Error(`Delete index request failed with status ${response.status}`);
908
+ }
909
+ const result = await response.json();
910
+ return result;
911
+ } catch (error) {
912
+ if (error instanceof Error && error.name === "AbortError") {
913
+ throw new Error(`Delete index request timed out after ${timeoutMs}ms`);
914
+ }
915
+ throw error;
916
+ } finally {
917
+ clearTimeout(timeoutId);
918
+ }
919
+ }
920
+ function createFilesClient(apiKey, dekStore, clientKEK, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
921
+ return {
922
+ upload: (options) => uploadFile(apiKey, dekStore, options, clientKEK, timeoutMs),
923
+ list: (options) => listFiles(apiKey, options, timeoutMs),
924
+ get: (options) => getFile(apiKey, options, timeoutMs),
925
+ delete: (options) => deleteFile(apiKey, options, timeoutMs),
926
+ index: (options) => indexFiles(apiKey, dekStore, options, clientKEK, timeoutMs),
927
+ deleteIndex: (options) => deleteIndex(apiKey, dekStore, options, clientKEK, timeoutMs)
928
+ };
929
+ }
930
+
931
+ // src/models/index.ts
932
+ async function listModels(params, apiKey, timeoutMs) {
933
+ const controller = new AbortController;
934
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
935
+ const queryParams = new URLSearchParams;
936
+ if (params?.type !== undefined) {
937
+ queryParams.append("type", params.type);
938
+ }
939
+ const queryString = queryParams.toString();
940
+ const url = `${endpoints.proxy}/models${queryString ? `?${queryString}` : ""}`;
941
+ try {
942
+ const response = await fetch(url, {
943
+ method: "GET",
944
+ headers: {
945
+ Authorization: apiKey,
946
+ "Content-Type": "application/json"
947
+ },
948
+ signal: controller.signal
949
+ });
950
+ if (!response.ok) {
951
+ throw new Error(`List models request failed with status ${response.status}`);
952
+ }
953
+ const result = await response.json();
954
+ if (result.status !== 200) {
955
+ throw new Error(result.error || "List models failed");
956
+ }
957
+ if (!result.data) {
958
+ throw new Error("List models response missing data");
959
+ }
960
+ return result.data;
961
+ } catch (error) {
962
+ if (error instanceof Error && error.name === "AbortError") {
963
+ throw new Error(`List models request timed out after ${timeoutMs}ms`);
964
+ }
965
+ throw error;
966
+ } finally {
967
+ clearTimeout(timeoutId);
968
+ }
969
+ }
970
+ function createModelsClient(apiKey, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
971
+ return {
972
+ list: (params) => listModels(params, apiKey, timeoutMs)
973
+ };
974
+ }
975
+
976
+ // src/rvenc/index.ts
977
+ var import_utils5 = require("@noble/ciphers/utils.js");
978
+ var import_openai = __toESM(require("openai"));
979
+ function preprocessRequest(body, encryptionKeys) {
980
+ const { cipherText, sharedSecret } = encryptionKeys;
981
+ const { encrypted, nonce } = encryptPayload(sharedSecret, body);
982
+ return {
983
+ body: {
984
+ cipherText: import_utils5.bytesToHex(cipherText),
985
+ encryptedInference: import_utils5.bytesToHex(encrypted),
986
+ nonce: import_utils5.bytesToHex(nonce),
987
+ model: body.model
988
+ },
989
+ sharedSecret,
990
+ nonce
991
+ };
992
+ }
993
+ async function postprocessStreamingResponse(response, sharedSecret, nonce, maxBufferSize) {
994
+ if (!response.body) {
995
+ throw new Error("Response body is null");
996
+ }
997
+ const reader = response.body.getReader();
998
+ const generator = createDecryptedStreamGenerator(reader, sharedSecret, nonce, maxBufferSize);
999
+ return {
1000
+ [Symbol.asyncIterator]() {
1001
+ return generator;
1002
+ }
1003
+ };
1004
+ }
1005
+ async function postprocessNonStreamingResponse(response, sharedSecret) {
1006
+ const data = await response.json();
1007
+ if (!data.encryptedResponse || !data.nonce) {
1008
+ throw new Error("Invalid non-streaming response: missing encryptedResponse or nonce");
1009
+ }
1010
+ const responseNonce = import_utils5.hexToBytes(data.nonce);
1011
+ return decryptPayload(data.encryptedResponse, sharedSecret, responseNonce);
1012
+ }
1013
+ function createRvencChatClient(apiKey, encryptionKeys, requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE, attest2 = true, OpenAIClientParams) {
1014
+ const client = new import_openai.default({ apiKey: "not-used", ...OpenAIClientParams });
1015
+ const originalChatCreate = client.chat.completions.create.bind(client.chat.completions);
1016
+ client.chat.completions.create = async (body) => {
1017
+ const isStreaming = body.stream === true;
1018
+ const controller = new AbortController;
1019
+ const timeoutId = setTimeout(() => controller.abort(), requestTimeoutMs);
1020
+ try {
1021
+ const sessionId = await attest(apiKey, { model: body.model, enabled: attest2 });
1022
+ const encryptedRequest = preprocessRequest(body, encryptionKeys);
1023
+ const response = await fetch(`${endpoints.proxy}/rvenc/chat/completions`, {
1024
+ method: "POST",
1025
+ headers: {
1026
+ "Content-Type": "application/json",
1027
+ Accept: isStreaming ? "text/event-stream" : "application/json",
1028
+ Authorization: apiKey,
1029
+ ...sessionId && { "X-Session-Id": sessionId }
1030
+ },
1031
+ body: JSON.stringify(encryptedRequest.body),
1032
+ signal: controller.signal
1033
+ });
1034
+ if (!response.ok) {
1035
+ await throwIfErrorResponse(response);
1036
+ }
1037
+ clearTimeout(timeoutId);
1038
+ if (isStreaming) {
1039
+ return await postprocessStreamingResponse(response, encryptedRequest.sharedSecret, encryptedRequest.nonce, maxBufferSize);
1040
+ } else {
1041
+ return await postprocessNonStreamingResponse(response, encryptedRequest.sharedSecret);
1042
+ }
1043
+ } catch (error) {
1044
+ clearTimeout(timeoutId);
1045
+ if (error instanceof Error && error.name === "AbortError") {
1046
+ throw new Error(`Request timed out after ${requestTimeoutMs}ms`);
1047
+ }
1048
+ throw error;
1049
+ }
1050
+ };
1051
+ return client;
1052
+ }
1053
+ async function* createDecryptedStreamGenerator(reader, sharedSecret, nonce, maxBufferSize) {
1054
+ const decoder = new TextDecoder;
1055
+ let buffer = "";
1056
+ try {
1057
+ while (true) {
1058
+ const { value, done } = await reader.read();
1059
+ if (done)
1060
+ break;
1061
+ buffer += decoder.decode(value, { stream: true });
1062
+ if (buffer.length > maxBufferSize) {
1063
+ throw new Error(`Stream buffer exceeded maximum size of ${maxBufferSize} bytes`);
1064
+ }
1065
+ const parts = buffer.split(`
1066
+
1067
+ `);
1068
+ for (let i = 0;i < parts.length - 1; i++) {
1069
+ const part = parts[i];
1070
+ const lines = part.split(`
1071
+ `);
1072
+ let event;
1073
+ let data;
1074
+ if (lines[0]) {
1075
+ const eventSplit = lines[0].split(": ");
1076
+ event = eventSplit[1];
1077
+ }
1078
+ if (lines[1]) {
1079
+ const dataSplit = lines[1].split(": ");
1080
+ data = dataSplit.slice(1).join(": ");
1081
+ }
1082
+ if (event === "done" && data === "[DONE]") {
1083
+ return;
1084
+ }
1085
+ if (event === "error") {
1086
+ const errorObj = JSON.parse(data || "{}");
1087
+ throw new Error(errorObj.error?.message || data || "Stream error");
1088
+ }
1089
+ if (event === "data" && data && data !== "[DONE]") {
1090
+ const chunk = decryptPayload(data, sharedSecret, nonce);
1091
+ if (chunk.error) {
1092
+ throw new Error(chunk.error.message || "Stream error");
1093
+ }
1094
+ yield chunk;
1095
+ }
1096
+ }
1097
+ buffer = parts[parts.length - 1];
1098
+ }
1099
+ } finally {
1100
+ reader.releaseLock();
1101
+ }
1102
+ }
1103
+
1104
+ // src/tools/index.ts
1105
+ var import_utils6 = require("@noble/ciphers/utils.js");
1106
+ var FILE_OUTPUT_TOOLS = ["generateImage", "audioGenerateFromText", "createFileForUser"];
1107
+ var FILE_INPUT_TOOLS = [
1108
+ "imageDescribeAndCaption",
1109
+ "imageDescribeAndCaptionFallback",
1110
+ "videoDescribeAndCaption",
1111
+ "getPDFContent",
1112
+ "getTextDocumentContent",
1113
+ "transcribeAudioToText",
1114
+ "transcribeAudioWithDiarization",
1115
+ "audioDiarization",
1116
+ "getSpreadsheetContent",
1117
+ "getPowerPointContent",
1118
+ "getDataFileContent",
1119
+ "getFileContentOCR"
1120
+ ];
1121
+ var RAG_TOOLS = ["searchRag"];
1122
+ async function callToolRequest(toolName, body, apiKey, timeoutMs, attest2) {
1123
+ const controller = new AbortController;
1124
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
1125
+ try {
1126
+ const response = await fetch(`${endpoints.proxy}/tools/${toolName}`, {
1127
+ method: "POST",
1128
+ headers: {
1129
+ "Content-Type": "application/json",
1130
+ Authorization: apiKey
1131
+ },
1132
+ body: JSON.stringify(body),
1133
+ signal: controller.signal
1134
+ });
1135
+ clearTimeout(timeoutId);
1136
+ if (!response.ok) {
1137
+ await throwIfErrorResponse(response);
1138
+ }
1139
+ const data = await response.json();
1140
+ return data.data;
1141
+ } catch (error) {
1142
+ clearTimeout(timeoutId);
1143
+ if (error instanceof Error && error.name === "AbortError") {
1144
+ throw new Error(`Tool request timed out after ${timeoutMs}ms`);
1145
+ }
1146
+ throw new Error(`Tool request failed: ${error instanceof Error ? error.message : error}`);
1147
+ }
1148
+ }
1149
+ async function downloadEncryptedFile(fileId, apiKey, timeoutMs) {
1150
+ const controller = new AbortController;
1151
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
1152
+ try {
1153
+ const metadataResponse = await fetch(`${endpoints.proxy}/files/encrypted/${fileId}?url=true`, {
1154
+ headers: { Authorization: apiKey },
1155
+ signal: controller.signal
1156
+ });
1157
+ if (!metadataResponse.ok) {
1158
+ throw new Error(`Failed to get file metadata: ${metadataResponse.status}`);
1159
+ }
1160
+ const metadata = await metadataResponse.json();
1161
+ const downloadUrl = metadata.data?.url;
1162
+ if (!downloadUrl) {
1163
+ throw new Error("No download URL in response");
1164
+ }
1165
+ const fileResponse = await fetch(downloadUrl, { signal: controller.signal });
1166
+ if (!fileResponse.ok) {
1167
+ throw new Error(`Failed to download file: ${fileResponse.status}`);
1168
+ }
1169
+ clearTimeout(timeoutId);
1170
+ const arrayBuffer = await fileResponse.arrayBuffer();
1171
+ return new Uint8Array(arrayBuffer);
1172
+ } catch (error) {
1173
+ clearTimeout(timeoutId);
1174
+ if (error instanceof Error && error.name === "AbortError") {
1175
+ throw new Error(`File download timed out after ${timeoutMs}ms`);
1176
+ }
1177
+ throw error;
1178
+ }
1179
+ }
1180
+ async function downloadAndDecryptFile(response, dek, apiKey, timeoutMs) {
1181
+ if (!response.success || !response.fileId) {
1182
+ return null;
1183
+ }
1184
+ const decryptFileName = (encryptedHex) => {
1185
+ const encrypted = import_utils6.hexToBytes(encryptedHex);
1186
+ const decrypted = decryptWithDEK(dek, encrypted);
1187
+ return new TextDecoder().decode(decrypted);
1188
+ };
1189
+ const fileName = decryptFileName(response.fileName);
1190
+ const mimeType = decryptFileName(response.mimeType);
1191
+ const encryptedFile = await downloadEncryptedFile(response.fileId, apiKey, timeoutMs);
1192
+ const decryptedFile = decryptWithDEK(dek, encryptedFile);
1193
+ return {
1194
+ fileId: response.fileId,
1195
+ fileName,
1196
+ mimeType,
1197
+ content: decryptedFile,
1198
+ fileSize: decryptedFile.length
1199
+ };
1200
+ }
1201
+ async function callSimpleTool(toolName, params, apiKey, timeoutMs, attest2) {
1202
+ const enclavePublicKey = await getEnclavePublicKey(timeoutMs);
1203
+ const { cipherText, sharedSecret } = createMLKEMEncapsulation(enclavePublicKey);
1204
+ const { encrypted, nonce } = encryptPayload(sharedSecret, params);
1205
+ const body = {
1206
+ cipherText: import_utils6.bytesToHex(cipherText),
1207
+ encryptedParams: import_utils6.bytesToHex(encrypted),
1208
+ nonce: import_utils6.bytesToHex(nonce)
1209
+ };
1210
+ const response = await callToolRequest(toolName, body, apiKey, timeoutMs, attest2);
1211
+ return decryptPayload(response.encryptedResponse, sharedSecret, import_utils6.hexToBytes(response.nonce));
1212
+ }
1213
+ async function callFileOutputTool(toolName, params, apiKey, dekStore, clientKEK, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, attest2 = true) {
1214
+ const enclavePublicKey = await getEnclavePublicKey(timeoutMs);
1215
+ const { cipherText, sharedSecret } = createMLKEMEncapsulation(enclavePublicKey);
1216
+ const { encrypted, nonce } = encryptPayload(sharedSecret, params);
1217
+ const dek = import_utils6.randomBytes(32);
1218
+ const { encrypted: encryptedDEK, nonce: dekNonce } = encryptPayload(sharedSecret, dek);
1219
+ const _clientKEK = clientKEK ? import_utils6.hexToBytes(clientKEK) : getClientKEK();
1220
+ const wrappedDEK = wrapDEK(_clientKEK, dek);
1221
+ const clientKID = clientKEK ? getClientKID(clientKEK) : getClientKID();
1222
+ const body = {
1223
+ cipherText: import_utils6.bytesToHex(cipherText),
1224
+ encryptedParams: import_utils6.bytesToHex(encrypted),
1225
+ nonce: import_utils6.bytesToHex(nonce),
1226
+ encryptedDEK: import_utils6.bytesToHex(encryptedDEK),
1227
+ dekNonce: import_utils6.bytesToHex(dekNonce),
1228
+ kid: clientKID,
1229
+ wrappedDEK: import_utils6.bytesToHex(wrappedDEK)
1230
+ };
1231
+ const response = await callToolRequest(toolName, body, apiKey, timeoutMs, attest2);
1232
+ const result = await downloadAndDecryptFile(response, dek, apiKey, timeoutMs);
1233
+ if (result && result.fileId) {
1234
+ if (!dekStore.fileDEKs) {
1235
+ dekStore.fileDEKs = new Map;
1236
+ }
1237
+ dekStore.fileDEKs.set(result.fileId, wrappedDEK);
1238
+ }
1239
+ return result;
1240
+ }
1241
+ async function callFileInputTool(toolName, params, apiKey, dekStore, clientKEK, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, attest2 = true) {
1242
+ if (!params.fileId) {
1243
+ throw new Error(`Tool ${toolName} requires fileId parameter`);
1244
+ }
1245
+ const enclavePublicKey = await getEnclavePublicKey(timeoutMs);
1246
+ const { cipherText, sharedSecret } = createMLKEMEncapsulation(enclavePublicKey);
1247
+ const dek = import_utils6.randomBytes(32);
1248
+ const { encrypted: encryptedDEK, nonce: dekNonce } = encryptPayload(sharedSecret, dek);
1249
+ const nonce = import_utils6.randomBytes(24);
1250
+ if (!dekStore.fileDEKs) {
1251
+ dekStore.fileDEKs = new Map;
1252
+ }
1253
+ const _clientKEK = clientKEK ? import_utils6.hexToBytes(clientKEK) : getClientKEK();
1254
+ let fileDEK = dekStore.fileDEKs.get(params.fileId);
1255
+ if (!fileDEK) {
1256
+ fileDEK = import_utils6.randomBytes(32);
1257
+ const wrappedFileDEK = wrapDEK(_clientKEK, fileDEK);
1258
+ dekStore.fileDEKs.set(params.fileId, wrappedFileDEK);
1259
+ } else {
1260
+ fileDEK = unwrapDEK(_clientKEK, fileDEK);
1261
+ }
1262
+ const { encrypted: encryptedFileDEK, nonce: fileDEKNonce } = encryptPayload(sharedSecret, fileDEK);
1263
+ const body = {
1264
+ cipherText: import_utils6.bytesToHex(cipherText),
1265
+ nonce: import_utils6.bytesToHex(nonce),
1266
+ fileId: params.fileId,
1267
+ encryptedDEK: import_utils6.bytesToHex(encryptedDEK),
1268
+ dekNonce: import_utils6.bytesToHex(dekNonce),
1269
+ encryptedFileDEK: import_utils6.bytesToHex(encryptedFileDEK),
1270
+ fileDEKNonce: import_utils6.bytesToHex(fileDEKNonce)
1271
+ };
1272
+ const response = await callToolRequest(toolName, body, apiKey, timeoutMs, attest2);
1273
+ return decryptPayload(response.encryptedResponse, sharedSecret, import_utils6.hexToBytes(response.nonce));
1274
+ }
1275
+ async function callRagTool(toolName, params, apiKey, dekStore, clientKEK, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, attest2 = true) {
1276
+ const enclavePublicKey = await getEnclavePublicKey(timeoutMs);
1277
+ const { cipherText, sharedSecret } = createMLKEMEncapsulation(enclavePublicKey);
1278
+ const { encrypted, nonce } = encryptPayload(sharedSecret, params);
1279
+ const dek = import_utils6.randomBytes(32);
1280
+ const { encrypted: encryptedDEK, nonce: dekNonce } = encryptPayload(sharedSecret, dek);
1281
+ if (!dekStore.fileDEKs) {
1282
+ dekStore.fileDEKs = new Map;
1283
+ }
1284
+ let fileIds = [];
1285
+ if (dekStore.fileDEKs.size > 0) {
1286
+ fileIds = Array.from(dekStore.fileDEKs.keys());
1287
+ }
1288
+ const _clientKEK = clientKEK ? import_utils6.hexToBytes(clientKEK) : getClientKEK();
1289
+ const encryptedFileDEKs = fileIds.reduce((acc, fileId) => {
1290
+ const fileDEK = dekStore.fileDEKs.get(fileId);
1291
+ if (!fileDEK) {
1292
+ return acc;
1293
+ }
1294
+ const unwrappedFileDEK = unwrapDEK(_clientKEK, fileDEK);
1295
+ const { encrypted: encryptedFileDEK, nonce: fileDEKNonce } = encryptPayload(sharedSecret, unwrappedFileDEK);
1296
+ acc.push({
1297
+ fileId,
1298
+ encryptedDEK: import_utils6.bytesToHex(encryptedFileDEK),
1299
+ nonce: import_utils6.bytesToHex(fileDEKNonce)
1300
+ });
1301
+ return acc;
1302
+ }, []);
1303
+ if (!dekStore.ragDEK) {
1304
+ throw new Error("RAG DEK not found in dekStore. Please upload at least one file with ragIndex: true to initialize RAG.");
1305
+ }
1306
+ if (!dekStore.ragVersion) {
1307
+ throw new Error("RAG Version not found in dekStore. Please upload at least one file with ragIndex: true to initialize RAG.");
1308
+ }
1309
+ const ragDEK = unwrapDEK(_clientKEK, dekStore.ragDEK);
1310
+ const { encrypted: encryptedRagDEK, nonce: ragDEKNonce } = encryptPayload(sharedSecret, ragDEK);
1311
+ const { encrypted: encryptedRagVersion, nonce: ragVersionNonce } = encryptPayload(sharedSecret, dekStore.ragVersion);
1312
+ const body = {
1313
+ cipherText: import_utils6.bytesToHex(cipherText),
1314
+ encryptedParams: import_utils6.bytesToHex(encrypted),
1315
+ nonce: import_utils6.bytesToHex(nonce),
1316
+ encryptedDEK: import_utils6.bytesToHex(encryptedDEK),
1317
+ dekNonce: import_utils6.bytesToHex(dekNonce),
1318
+ encryptedFileDEKs,
1319
+ encryptedRagDEK: import_utils6.bytesToHex(encryptedRagDEK),
1320
+ ragDEKNonce: import_utils6.bytesToHex(ragDEKNonce),
1321
+ encryptedRagVersion: import_utils6.bytesToHex(encryptedRagVersion),
1322
+ ragVersionNonce: import_utils6.bytesToHex(ragVersionNonce)
1323
+ };
1324
+ const response = await callToolRequest(toolName, body, apiKey, timeoutMs, attest2);
1325
+ return decryptPayload(response.encryptedResponse, sharedSecret, import_utils6.hexToBytes(response.nonce));
1326
+ }
1327
+ async function callTool(toolName, params, apiKey, dekStore, clientKEK, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, attest2 = true) {
1328
+ if (FILE_OUTPUT_TOOLS.includes(toolName)) {
1329
+ return callFileOutputTool(toolName, params, apiKey, dekStore, clientKEK, timeoutMs, attest2);
1330
+ } else if (FILE_INPUT_TOOLS.includes(toolName)) {
1331
+ return callFileInputTool(toolName, params, apiKey, dekStore, clientKEK, timeoutMs, attest2);
1332
+ } else if (RAG_TOOLS.includes(toolName)) {
1333
+ return callRagTool(toolName, params, apiKey, dekStore, clientKEK, timeoutMs, attest2);
1334
+ } else {
1335
+ return callSimpleTool(toolName, params, apiKey, timeoutMs, attest2);
1336
+ }
1337
+ }
1338
+ function createToolsClient(apiKey, dekStore, clientKEK, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, attest2 = true) {
1339
+ return {
1340
+ generateImage: (params) => callTool("generateImage", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1341
+ audioGenerateFromText: (params) => callTool("audioGenerateFromText", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1342
+ createFileForUser: (params) => callTool("createFileForUser", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1343
+ imageDescribeAndCaption: (params) => callTool("imageDescribeAndCaption", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1344
+ imageDescribeAndCaptionFallback: (params) => callTool("imageDescribeAndCaptionFallback", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1345
+ videoDescribeAndCaption: (params) => callTool("videoDescribeAndCaption", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1346
+ getPDFContent: (params) => callTool("getPDFContent", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1347
+ getTextDocumentContent: (params) => callTool("getTextDocumentContent", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1348
+ transcribeAudioToText: (params) => callTool("transcribeAudioToText", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1349
+ transcribeAudioWithDiarization: (params) => callTool("transcribeAudioWithDiarization", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1350
+ audioDiarization: (params) => callTool("audioDiarization", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1351
+ getFileContentOCR: (params) => callTool("getFileContentOCR", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1352
+ getSpreadsheetContent: (params) => callTool("getSpreadsheetContent", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1353
+ getDataFileContent: (params) => callTool("getDataFileContent", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1354
+ getPowerPointContent: (params) => callTool("getPowerPointContent", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1355
+ getTime: (params) => callTool("getTime", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1356
+ webSearchTool: (params) => callTool("webSearchTool", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1357
+ webPageScraperTool: (params) => callTool("webPageScraperTool", params, apiKey, dekStore, clientKEK, timeoutMs, attest2),
1358
+ searchRag: (params) => callTool("searchRag", params, apiKey, dekStore, clientKEK, timeoutMs, attest2)
1359
+ };
1360
+ }
1361
+
1362
+ // src/core.ts
1363
+ async function createRvencClient(options) {
1364
+ const {
1365
+ apiKey,
1366
+ clientKEK,
1367
+ requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
1368
+ maxBufferSize = DEFAULT_MAX_BUFFER_SIZE,
1369
+ attest: attest2 = true
1370
+ } = options;
1371
+ if (options.config?.endpoints !== undefined) {
1372
+ Object.assign(endpoints, options.config.endpoints);
1373
+ }
1374
+ let encryptionKeys;
1375
+ try {
1376
+ encryptionKeys = options.encryptionKeys ?? await generateEncryptionKeys(requestTimeoutMs);
1377
+ } catch (error) {
1378
+ throw new Error(`Failed to initialize encryption keys: ${error instanceof Error ? error.message : error}`);
1379
+ }
1380
+ const dekStore = options.dekStore ?? initializeDEKStore(clientKEK);
1381
+ const client = createRvencChatClient(apiKey, encryptionKeys, requestTimeoutMs, maxBufferSize, attest2, options.config?.openAIClientOptions ?? {});
1382
+ client.files = createFilesClient(apiKey, dekStore, clientKEK, requestTimeoutMs);
1383
+ client.tools = createToolsClient(apiKey, dekStore, clientKEK, requestTimeoutMs, attest2);
1384
+ client.audio = createAudioClient(apiKey, encryptionKeys, requestTimeoutMs, attest2);
1385
+ client.models = createModelsClient(apiKey, requestTimeoutMs);
1386
+ client.dekStore = dekStore;
1387
+ return client;
1388
+ }
1389
+ var core_default = createRvencClient;
1390
+
1391
+ // src/server.ts
1392
+ import_dotenv.default.config();
1393
+ var app = import_express.default();
1394
+ var HOST = process.env.HOST ?? "127.0.0.1";
1395
+ var PORT = process.env.PORT ? Number.parseInt(process.env.PORT, 10) : 3000;
1396
+ var serverProxyUrl = process.env.PROXY_URL;
1397
+ var serverEnclaveUrl = process.env.ENCLAVE_URL;
1398
+ var serverKek = process.env.CLIENT_KEK;
1399
+ var serverAttest = true;
1400
+ app.use(import_express.default.json());
1401
+ var storage = import_multer.default.memoryStorage();
1402
+ var upload = import_multer.default({
1403
+ storage,
1404
+ limits: {
1405
+ fileSize: 25 * 1024 * 1024
1406
+ }
1407
+ });
1408
+ var clientCache = new Map;
1409
+ function extractApiKey(req) {
1410
+ const authHeader = req.headers.authorization;
1411
+ if (!authHeader) {
1412
+ return null;
1413
+ }
1414
+ if (authHeader.startsWith("Bearer ")) {
1415
+ return authHeader.substring(7);
1416
+ }
1417
+ return authHeader;
1418
+ }
1419
+ async function getOrCreateClient(apiKey) {
1420
+ if (clientCache.has(apiKey)) {
1421
+ return clientCache.get(apiKey);
1422
+ }
1423
+ const client = await core_default({
1424
+ apiKey,
1425
+ clientKEK: serverKek,
1426
+ attest: serverAttest,
1427
+ config: {
1428
+ endpoints: {
1429
+ enclave: serverEnclaveUrl,
1430
+ proxy: serverProxyUrl
1431
+ }
1432
+ }
1433
+ });
1434
+ clientCache.set(apiKey, client);
1435
+ return client;
1436
+ }
1437
+ app.get("/", (_, res) => {
1438
+ res.json({
1439
+ message: "Rvenc OpenAI-compatible API Server",
1440
+ version: "1.0.0",
1441
+ endpoints: {
1442
+ chat_completions: "POST /v1/chat/completions"
1443
+ }
1444
+ });
1445
+ });
1446
+ app.post("/v1/chat/completions", async (req, res) => {
1447
+ try {
1448
+ const apiKey = extractApiKey(req);
1449
+ if (!apiKey) {
1450
+ return res.status(401).json({
1451
+ error: {
1452
+ message: 'Missing Authorization header. Expected format: "Bearer <api-key>" or "<api-key>"',
1453
+ type: "invalid_request_error",
1454
+ code: "invalid_api_key"
1455
+ }
1456
+ });
1457
+ }
1458
+ const client = await getOrCreateClient(apiKey);
1459
+ const params = req.body;
1460
+ const completion = await client.chat.completions.create(params);
1461
+ if (params.stream) {
1462
+ res.setHeader("Content-Type", "text/event-stream");
1463
+ res.setHeader("Cache-Control", "no-cache");
1464
+ res.setHeader("Connection", "keep-alive");
1465
+ if (completion && typeof completion === "object" && Symbol.asyncIterator in completion) {
1466
+ try {
1467
+ for await (const chunk of completion) {
1468
+ const data = `data: ${JSON.stringify(chunk)}
1469
+
1470
+ `;
1471
+ res.write(data);
1472
+ }
1473
+ res.write(`data: [DONE]
1474
+
1475
+ `);
1476
+ res.end();
1477
+ } catch (error) {
1478
+ console.error("Streaming error:", error);
1479
+ if (!res.headersSent) {
1480
+ res.status(500).json({
1481
+ error: {
1482
+ message: error.message || "Streaming error",
1483
+ type: "server_error"
1484
+ }
1485
+ });
1486
+ } else {
1487
+ res.end();
1488
+ }
1489
+ }
1490
+ } else {
1491
+ res.write(`data: ${JSON.stringify(completion)}
1492
+
1493
+ `);
1494
+ res.write(`data: [DONE]
1495
+
1496
+ `);
1497
+ res.end();
1498
+ }
1499
+ } else {
1500
+ res.json(completion);
1501
+ }
1502
+ } catch (error) {
1503
+ console.error("Chat completions error:", error);
1504
+ const statusCode = error.status || 500;
1505
+ res.status(statusCode).json({
1506
+ error: {
1507
+ message: error.message || "Internal server error",
1508
+ type: error.type || "server_error",
1509
+ code: error.code
1510
+ }
1511
+ });
1512
+ }
1513
+ });
1514
+ app.post("/v1/audio/transcriptions", upload.single("file"), async (req, res) => {
1515
+ try {
1516
+ const apiKey = extractApiKey(req);
1517
+ if (!apiKey) {
1518
+ return res.status(401).json({
1519
+ error: {
1520
+ message: 'Missing Authorization header. Expected format: "Bearer <api-key>" or "<api-key>"',
1521
+ type: "invalid_request_error",
1522
+ code: "invalid_api_key"
1523
+ }
1524
+ });
1525
+ }
1526
+ if (!req.file) {
1527
+ return res.status(400).json({
1528
+ error: {
1529
+ message: "Missing required file parameter",
1530
+ type: "invalid_request_error"
1531
+ }
1532
+ });
1533
+ }
1534
+ const client = await getOrCreateClient(apiKey);
1535
+ const file = new File([req.file.buffer], req.file.originalname, {
1536
+ type: req.file.mimetype
1537
+ });
1538
+ const params = {
1539
+ file,
1540
+ model: req.body.model
1541
+ };
1542
+ if (req.body.language)
1543
+ params.language = req.body.language;
1544
+ if (req.body.prompt)
1545
+ params.prompt = req.body.prompt;
1546
+ if (req.body.response_format)
1547
+ params.response_format = req.body.response_format;
1548
+ if (req.body.temperature)
1549
+ params.temperature = parseFloat(req.body.temperature);
1550
+ if (req.body.timestamp_granularities) {
1551
+ params.timestamp_granularities = Array.isArray(req.body.timestamp_granularities) ? req.body.timestamp_granularities : JSON.parse(req.body.timestamp_granularities);
1552
+ }
1553
+ const transcription = await client.audio.transcriptions.create(params);
1554
+ res.json(transcription);
1555
+ } catch (error) {
1556
+ console.error("Audio transcription error:", error);
1557
+ const statusCode = error.status || 500;
1558
+ res.status(statusCode).json({
1559
+ error: {
1560
+ message: error.message || "Internal server error",
1561
+ type: error.type || "server_error",
1562
+ code: error.code
1563
+ }
1564
+ });
1565
+ }
1566
+ });
1567
+ app.post("/v1/audio/translations", upload.single("file"), async (req, res) => {
1568
+ try {
1569
+ const apiKey = extractApiKey(req);
1570
+ if (!apiKey) {
1571
+ return res.status(401).json({
1572
+ error: {
1573
+ message: 'Missing Authorization header. Expected format: "Bearer <api-key>" or "<api-key>"',
1574
+ type: "invalid_request_error",
1575
+ code: "invalid_api_key"
1576
+ }
1577
+ });
1578
+ }
1579
+ if (!req.file) {
1580
+ return res.status(400).json({
1581
+ error: {
1582
+ message: "Missing required file parameter",
1583
+ type: "invalid_request_error"
1584
+ }
1585
+ });
1586
+ }
1587
+ const client = await getOrCreateClient(apiKey);
1588
+ const file = new File([req.file.buffer], req.file.originalname, {
1589
+ type: req.file.mimetype
1590
+ });
1591
+ const params = {
1592
+ file,
1593
+ model: req.body.model
1594
+ };
1595
+ if (req.body.prompt)
1596
+ params.prompt = req.body.prompt;
1597
+ if (req.body.response_format)
1598
+ params.response_format = req.body.response_format;
1599
+ if (req.body.temperature)
1600
+ params.temperature = parseFloat(req.body.temperature);
1601
+ const translation = await client.audio.translations.create(params);
1602
+ res.json(translation);
1603
+ } catch (error) {
1604
+ console.error("Audio translation error:", error);
1605
+ const statusCode = error.status || 500;
1606
+ res.status(statusCode).json({
1607
+ error: {
1608
+ message: error.message || "Internal server error",
1609
+ type: error.type || "server_error",
1610
+ code: error.code
1611
+ }
1612
+ });
1613
+ }
1614
+ });
1615
+ app.use((err, _req, res, _next) => {
1616
+ console.error(`Unhandled error: ${err}`);
1617
+ res.status(500).json({
1618
+ error: {
1619
+ message: err.message || "Internal server error",
1620
+ type: "server_error"
1621
+ }
1622
+ });
1623
+ });
1624
+ app.use((req, res) => {
1625
+ res.status(404).json({
1626
+ error: {
1627
+ message: `Route ${req.method} ${req.path} not found`,
1628
+ type: "invalid_request_error"
1629
+ }
1630
+ });
1631
+ });
1632
+ async function startServer(options = {}) {
1633
+ const { host, port, proxyUrl, enclaveUrl, kek, attest: attest2 } = options;
1634
+ const serverHost = host || HOST;
1635
+ const serverPort = port || PORT;
1636
+ serverAttest = attest2 !== false;
1637
+ if (proxyUrl) {
1638
+ serverProxyUrl = proxyUrl;
1639
+ }
1640
+ if (enclaveUrl) {
1641
+ serverEnclaveUrl = enclaveUrl;
1642
+ }
1643
+ if (kek) {
1644
+ serverKek = kek;
1645
+ }
1646
+ return new Promise((resolve, reject) => {
1647
+ const server = app.listen(serverPort, serverHost, () => {
1648
+ console.log(`
1649
+ Rvenc Server running on http://${serverHost}:${serverPort}`);
1650
+ resolve();
1651
+ });
1652
+ server.on("error", (error) => {
1653
+ if (error.code === "EADDRINUSE") {
1654
+ console.error(`❌ Port ${serverPort} is already in use`);
1655
+ } else {
1656
+ console.error(`❌ Failed to start server: ${error}`);
1657
+ }
1658
+ reject(error);
1659
+ });
1660
+ });
1661
+ }
1662
+ if (false) {}
1663
+
1664
+ // src/cli.ts
1665
+ var { values } = import_node_util.parseArgs({
1666
+ args: process.argv.slice(2),
1667
+ options: {
1668
+ host: { type: "string", default: "127.0.0.1" },
1669
+ "proxy-url": { type: "string" },
1670
+ "enclave-url": { type: "string" },
1671
+ kek: { type: "string" },
1672
+ port: { type: "string", default: "8000" },
1673
+ "no-attest": { type: "boolean", default: false }
1674
+ },
1675
+ strict: true
1676
+ });
1677
+ startServer({
1678
+ host: values["host"],
1679
+ proxyUrl: values["proxy-url"],
1680
+ enclaveUrl: values["enclave-url"],
1681
+ kek: values["kek"],
1682
+ port: Number(values["port"]),
1683
+ attest: !values["no-attest"]
1684
+ });