-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathremoteEngine.ts
More file actions
676 lines (603 loc) · 18.8 KB
/
remoteEngine.ts
File metadata and controls
676 lines (603 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
// Copyright 2025 Flower Labs GmbH. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import nodeCrypto from 'crypto';
import getRandomValues from 'get-random-values';
import { REMOTE_URL } from '../constants';
import {
ChatResponseResult,
FailureCode,
Message,
Progress,
Result,
StreamEvent,
Tool,
ToolCall,
} from '../typing';
import { BaseEngine } from './engine';
let crypto: Crypto | typeof nodeCrypto = nodeCrypto;
try {
crypto = window.crypto;
} catch (_) {
// fall back to nodeCrypto
}
const KEY_TYPE = 'ECDH';
const CURVE = 'P-384'; // secp384r1 in Web Crypto
const KEY_FORMAT = 'spki';
const AES_KEY_LENGTH = 32;
const GCM_IV_LENGTH = 12;
const BIT_TAG_LENGTH = 8 * 16; // 128 bits or 16 bytes
const SIGN_ALG = 'HMAC';
const CRYPTO_ALG = 'AES-GCM';
const HASH_ALG = 'SHA-256';
const HKDF_INFO = new TextEncoder().encode('ecdh key exchange');
export class RemoteEngine extends BaseEngine {
private baseUrl: string;
private apiKey: string;
private cryptoHandler: CryptographyHandler;
constructor(apiKey: string) {
super();
this.baseUrl = REMOTE_URL;
this.apiKey = apiKey;
this.cryptoHandler = new CryptographyHandler(this.baseUrl, this.apiKey);
}
async chat(
messages: Message[],
model: string,
temperature?: number,
maxCompletionTokens?: number,
stream?: boolean,
onStreamEvent?: (event: StreamEvent) => void,
tools?: Tool[],
encrypt = false
): Promise<ChatResponseResult> {
if (encrypt) {
const keyRes = await this.cryptoHandler.initializeKeysAndExchange();
if (!keyRes.ok) {
return keyRes;
}
const encryptRes = await this.cryptoHandler.encryptMessages(messages);
if (!encryptRes.ok) {
return encryptRes;
}
}
if (stream) {
const response = await this.chatStream(
messages,
model,
encrypt,
temperature,
maxCompletionTokens,
onStreamEvent
);
if (!response.ok) return response;
return { ok: true, message: { role: 'assistant', content: response.value } };
} else {
const requestData = this.createRequestData(
messages,
model,
temperature,
maxCompletionTokens,
false,
tools,
encrypt
);
const response = await sendRequest(
requestData,
'/v1/chat/completions',
this.baseUrl,
this.getHeaders()
);
if (!response.ok) {
return response;
}
const chatResponse = (await response.value.json()) as ChatCompletionsResponse;
return await this.extractOutput(chatResponse, encrypt);
}
}
async fetchModel(_model: string, _callback: (progress: Progress) => void): Promise<Result<void>> {
await Promise.resolve();
return {
ok: false,
failure: {
code: FailureCode.EngineSpecificError,
description: 'Cannot fetch model with remote inference engine.',
},
};
}
async isSupported(_model: string): Promise<boolean> {
await Promise.resolve();
return true;
}
private createRequestData(
messages: Message[],
model: string,
temperature?: number,
maxCompletionTokens?: number,
stream?: boolean,
tools?: Tool[],
encrypt?: boolean
): ChatCompletionsRequest {
return {
model,
messages,
...(temperature && { temperature }),
...(maxCompletionTokens && {
max_completion_tokens: maxCompletionTokens,
}),
...(stream && { stream }),
...(tools && { tools }),
...(encrypt && { encrypt, encryption_id: this.cryptoHandler.encryptionId }),
};
}
private getHeaders() {
return {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
};
}
async chatStream(
messages: Message[],
model: string,
encrypt: boolean,
temperature?: number,
maxCompletionTokens?: number,
onStreamEvent?: (event: StreamEvent) => void
): Promise<Result<string>> {
const requestData = this.createRequestData(
messages,
model,
temperature,
maxCompletionTokens,
true,
undefined,
encrypt
);
const response = await sendRequest(
requestData,
'/v1/chat/completions',
this.baseUrl,
this.getHeaders()
);
if (!response.ok) return response;
const reader = response.value.body?.getReader();
const decoder = new TextDecoder('utf-8');
let accumulatedResponse = '';
while (reader) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
const dataArray = chunk.split(/(?<=})\s*(?={)/g);
for (const data of dataArray) {
try {
const { object: _, choices } = JSON.parse(data) as {
object: string;
choices: StreamChoice[];
};
for (const choice of choices) {
const deltaContent = choice.delta.content;
if (deltaContent) {
let content: string;
if (encrypt) {
const decryptedResult = await this.cryptoHandler.decryptMessage(deltaContent);
if (!decryptedResult.ok) {
return decryptedResult;
}
content = decryptedResult.value;
} else {
content = deltaContent;
}
onStreamEvent?.({ chunk: content });
accumulatedResponse += content;
}
}
} catch (error) {
console.error('Error parsing JSON chunk:', error);
}
}
}
return { ok: true, value: accumulatedResponse };
}
async extractOutput(
response: ChatCompletionsResponse,
encrypt: boolean
): Promise<ChatResponseResult> {
const message = response.choices[0].message;
let content: string;
if (encrypt) {
const decryptedResult = await this.cryptoHandler.decryptMessage(message.content ?? '');
if (!decryptedResult.ok) {
return decryptedResult;
}
content = decryptedResult.value;
} else {
content = message.content ?? '';
}
const toolCalls = message.tool_calls;
return {
ok: true,
message: {
role: message.role,
content: content,
...(toolCalls && { tool_calls: toolCalls }),
},
};
}
}
async function sendRequest(
requestData: ChatCompletionsRequest,
endpoint: string,
baseUrl: string,
headers: Record<string, string>
): Promise<Result<Response>> {
const response = await fetch(`${baseUrl}${endpoint}`, {
method: 'POST',
headers,
body: JSON.stringify(requestData),
});
if (!response.ok) {
let code = FailureCode.RemoteError;
switch (response.status) {
case 401:
case 403:
case 407:
code = FailureCode.AuthenticationError;
break;
case 404:
case 502:
case 503:
code = FailureCode.UnavailableError;
break;
case 408:
case 504:
code = FailureCode.TimeoutError;
break;
default:
break;
}
return {
ok: false,
failure: { code, description: `${String(response.status)}: ${response.statusText}` },
};
}
return { ok: true, value: response };
}
/** Handles key generation and ECDH shared secret derivation */
export class KeyManager {
private privateKey: CryptoKey | null = null;
private publicKey: CryptoKey | null = null;
private sharedSecretKey: ArrayBuffer | null = null;
/**
* Generate a new ECDH key pair.
*/
async generateKeyPair() {
const keyPair = await crypto.subtle.generateKey(
{
name: KEY_TYPE,
namedCurve: CURVE,
},
true,
['deriveKey', 'deriveBits']
);
this.privateKey = keyPair.privateKey;
this.publicKey = keyPair.publicKey;
}
/**
* Export the public key as a Base64 string.
*/
async exportPublicKey(): Promise<Result<string>> {
if (!this.publicKey) {
return {
ok: false,
failure: { code: FailureCode.EncryptionError, description: 'Public key not generated.' },
};
}
const exportedKey = await crypto.subtle.exportKey(KEY_FORMAT, this.publicKey);
return { ok: true, value: btoa(String.fromCharCode(...new Uint8Array(exportedKey))) };
}
/**
* Derive a shared secret using the server's public key.
*/
async deriveSharedSecret(serverPublicKeyBase64: string): Promise<Result<ArrayBuffer>> {
if (!this.privateKey) {
return {
ok: false,
failure: {
code: FailureCode.EncryptionError,
description: 'Private key is not initialized.',
},
};
}
const serverPublicKeyBuffer = Uint8Array.from(atob(serverPublicKeyBase64), (char) =>
char.charCodeAt(0)
);
// Import server's public key
const serverPublicKey = await crypto.subtle.importKey(
KEY_FORMAT,
serverPublicKeyBuffer,
{ name: KEY_TYPE, namedCurve: CURVE },
false,
[]
);
// Compute shared secret
const sharedSecret = await crypto.subtle.deriveBits(
{ name: KEY_TYPE, public: serverPublicKey },
this.privateKey,
384
);
// Apply HKDF to derive final encryption key
this.sharedSecretKey = await hkdf(HASH_ALG, sharedSecret, HKDF_INFO, AES_KEY_LENGTH);
return { ok: true, value: this.sharedSecretKey };
}
getSharedSecretKey(): ArrayBuffer | null {
return this.sharedSecretKey;
}
}
/** Handles server communication for key exchange */
export class NetworkService {
private serverUrl: string;
private apiKey: string;
private serverPublicKey: string | null = null;
private serverPublicKeyExpiresAt: number | null = null;
private clientPublicKeyExpiresAt: number | null = null;
constructor(serverUrl: string, apiKey: string) {
this.serverUrl = serverUrl;
this.apiKey = apiKey;
}
private isServerKeyExpired(): boolean {
if (!this.serverPublicKeyExpiresAt) return true;
// Conversion from milliseconds to microseconds
return Date.now() >= this.serverPublicKeyExpiresAt * 1000;
}
isClientKeyExpired(): boolean {
if (!this.clientPublicKeyExpiresAt) return true;
// Conversion from milliseconds to microseconds
return Date.now() >= this.clientPublicKeyExpiresAt * 1000;
}
async submitClientPublicKey(clientPublicKey: string): Promise<Result<string>> {
const response = await fetch(`${this.serverUrl}/v1/encryption/public-key`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },
body: JSON.stringify({ public_key_base64: clientPublicKey }),
});
if (!response.ok) {
return {
ok: false,
failure: {
code: FailureCode.EncryptionError,
description: `Failed to send public key: ${response.statusText}`,
},
};
}
const data = (await response.json()) as { expires_at: string; encryption_id: string };
this.clientPublicKeyExpiresAt = getTimestamp(data.expires_at);
return { ok: true, value: data.encryption_id };
}
async getServerPublicKey(): Promise<Result<string>> {
if (this.isServerKeyExpired() || !this.serverPublicKey) await this.fetchNewServerPublicKey();
if (!this.serverPublicKey) {
return {
ok: false,
failure: { code: FailureCode.EncryptionError, description: 'Public key is not set.' },
};
}
return { ok: true, value: this.serverPublicKey };
}
private async fetchNewServerPublicKey(): Promise<Result<void>> {
const response = await fetch(`${this.serverUrl}/v1/encryption/server-public-key`, {
headers: { Authorization: `Bearer ${this.apiKey}` },
});
if (!response.ok) {
return {
ok: false,
failure: {
code: FailureCode.EncryptionError,
description: `Failed to fetch server public key: ${response.statusText}`,
},
};
}
const data = (await response.json()) as { public_key_base64: string; expires_at: string };
this.serverPublicKey = data.public_key_base64;
this.serverPublicKeyExpiresAt = getTimestamp(data.expires_at);
return { ok: true, value: undefined };
}
}
/** Orchestrates key management, key exchange, and message encryption/decryption */
export class CryptographyHandler {
private keyManager: KeyManager;
private networkService: NetworkService;
private sharedSecretKey: ArrayBuffer | null = null;
#encryptionId: string | null = null;
constructor(serverUrl: string, apiKey: string) {
this.keyManager = new KeyManager();
this.networkService = new NetworkService(serverUrl, apiKey);
}
get encryptionId() {
return this.#encryptionId;
}
async initializeKeysAndExchange(): Promise<Result<void>> {
if (this.networkService.isClientKeyExpired()) {
await this.keyManager.generateKeyPair();
const clientPublicKey = await this.keyManager.exportPublicKey();
if (!clientPublicKey.ok) {
return clientPublicKey;
}
const encryptionId = await this.networkService.submitClientPublicKey(clientPublicKey.value);
if (!encryptionId.ok) {
return encryptionId;
}
this.#encryptionId = encryptionId.value;
}
const serverPublicKey = await this.networkService.getServerPublicKey();
if (!serverPublicKey.ok) {
return serverPublicKey;
}
const sharedSecretKey = await this.keyManager.deriveSharedSecret(serverPublicKey.value);
if (!sharedSecretKey.ok) {
return sharedSecretKey;
}
this.sharedSecretKey = sharedSecretKey.value;
return { ok: true, value: undefined };
}
async encryptMessage(message: string): Promise<Result<string>> {
if (!this.sharedSecretKey) {
return {
ok: false,
failure: {
code: FailureCode.EncryptionError,
description: 'Shared secret is not derived.',
},
};
}
try {
const iv = getRandomValues(new Uint8Array(GCM_IV_LENGTH));
const aesKey = await crypto.subtle.importKey(
'raw',
this.sharedSecretKey,
{ name: CRYPTO_ALG },
false,
['encrypt']
);
const encodedMessage = new TextEncoder().encode(message);
const encryptedData = await crypto.subtle.encrypt(
{ name: CRYPTO_ALG, iv, tagLength: BIT_TAG_LENGTH },
aesKey,
encodedMessage
);
const encryptedBytes = new Uint8Array(encryptedData);
const combined = new Uint8Array(iv.length + encryptedBytes.length);
combined.set(iv, 0);
combined.set(encryptedBytes, iv.length);
return { ok: true, value: btoa(String.fromCharCode(...combined)) };
} catch (error) {
return {
ok: false,
failure: { code: FailureCode.EncryptionError, description: String(error) },
};
}
}
async encryptMessages(messages: Message[]): Promise<Result<void>> {
for (const message of messages) {
const encryptedContent = await this.encryptMessage(message.content);
if (!encryptedContent.ok) {
return encryptedContent;
}
message.content = encryptedContent.value;
}
return { ok: true, value: undefined };
}
async decryptMessage(encryptedMessage: string): Promise<Result<string>> {
if (!this.sharedSecretKey) {
return {
ok: false,
failure: {
code: FailureCode.EncryptionError,
description: 'Shared secret is not derived.',
},
};
}
try {
const data = Uint8Array.from(atob(encryptedMessage), (char) => char.charCodeAt(0));
const iv = data.slice(0, GCM_IV_LENGTH);
const ciphertext = data.slice(GCM_IV_LENGTH);
const aesKey = await crypto.subtle.importKey(
'raw',
this.sharedSecretKey,
{ name: CRYPTO_ALG },
false,
['decrypt']
);
const plaintext = await crypto.subtle.decrypt({ name: CRYPTO_ALG, iv }, aesKey, ciphertext);
return { ok: true, value: new TextDecoder().decode(plaintext) };
} catch (error: unknown) {
return {
ok: false,
failure: { code: FailureCode.EncryptionError, description: String(error) },
};
}
}
}
async function hkdf(
hash: string,
ikm: ArrayBuffer, // Input Keying Material (shared secret)
info: Uint8Array, // Contextual information (e.g., 'ecdh key exchange')
length: number
): Promise<ArrayBuffer> {
const salt = new Uint8Array(AES_KEY_LENGTH); // All-zero salt
const saltKey = await crypto.subtle.importKey('raw', salt, { name: SIGN_ALG, hash }, false, [
'sign',
]);
const prk = await crypto.subtle.sign(SIGN_ALG, saltKey, ikm);
const prkKey = await crypto.subtle.importKey('raw', prk, { name: SIGN_ALG, hash }, false, [
'sign',
]);
const hashLength = AES_KEY_LENGTH;
const numBlocks = Math.ceil(length / hashLength);
let previousBlock = new Uint8Array(0);
const output = new Uint8Array(length);
let offset = 0;
for (let i = 0; i < numBlocks; i++) {
const input = new Uint8Array([...previousBlock, ...info, i + 1]);
previousBlock = new Uint8Array(await crypto.subtle.sign(SIGN_ALG, prkKey, input));
output.set(previousBlock.slice(0, Math.min(hashLength, length - offset)), offset);
offset += hashLength;
}
return output.buffer;
}
/**
* Convert date formatted as "2025-03-06T13:19:47.353034" to numerical timestamp
* (in this example, 1741267187353)
*/
export function getTimestamp(dateString: string) {
return new Date(dateString.slice(0, 23) + 'Z').valueOf();
}
interface ChoiceMessage {
role: string;
content?: string;
tool_calls?: ToolCall[];
}
interface Choice {
index: number;
message: ChoiceMessage;
}
interface StreamChoice {
index: number;
delta: {
content: string;
role: string;
};
}
interface Usage {
total_duration: number; // time spent generating the response
load_duration: number; // time spent in nanoseconds loading the model
prompt_eval_count: number; // number of tokens in the prompt
prompt_eval_duration: number; // time spent in nanoseconds evaluating the prompt
eval_count: number; // number of tokens in the response
eval_duration: number; // time in nanoseconds spent generating the response
}
interface ChatCompletionsRequest {
model: string;
messages: Message[];
temperature?: number;
max_completion_tokens?: number;
tools?: Tool[];
encrypt?: boolean;
}
interface ChatCompletionsResponse {
object: string;
created: number;
model: string;
choices: Choice[];
usage: Usage;
}