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