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