tinfoil 0.8.3 → 0.8.4

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.
Files changed (37) hide show
  1. package/dist/ai-sdk-provider.d.ts +0 -10
  2. package/dist/ai-sdk-provider.js +8 -150
  3. package/dist/client.browser.d.ts +1 -0
  4. package/dist/client.browser.js +12 -27
  5. package/dist/client.d.ts +1 -0
  6. package/dist/client.js +12 -152
  7. package/dist/esm/ai-sdk-provider.d.ts +0 -10
  8. package/dist/esm/ai-sdk-provider.js +8 -147
  9. package/dist/esm/client.browser.d.ts +1 -0
  10. package/dist/esm/client.browser.js +12 -27
  11. package/dist/esm/client.d.ts +1 -0
  12. package/dist/esm/client.js +12 -152
  13. package/dist/esm/index.browser.d.ts +2 -1
  14. package/dist/esm/index.browser.js +2 -1
  15. package/dist/esm/index.d.ts +1 -0
  16. package/dist/esm/index.js +1 -0
  17. package/dist/esm/pinned-tls-fetch.d.ts +1 -0
  18. package/dist/esm/pinned-tls-fetch.js +110 -0
  19. package/dist/esm/secure-client.browser.d.ts +20 -0
  20. package/dist/esm/secure-client.browser.js +57 -0
  21. package/dist/esm/secure-client.d.ts +20 -0
  22. package/dist/esm/secure-client.js +68 -0
  23. package/dist/index.browser.d.ts +2 -1
  24. package/dist/index.browser.js +2 -1
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.js +1 -0
  27. package/dist/pinned-tls-fetch.d.ts +1 -0
  28. package/dist/pinned-tls-fetch.js +116 -0
  29. package/dist/secure-client.browser.d.ts +20 -0
  30. package/dist/secure-client.browser.js +61 -0
  31. package/dist/secure-client.d.ts +20 -0
  32. package/dist/secure-client.js +72 -0
  33. package/package.json +7 -2
  34. package/dist/ai-sdk-provider.browser.d.ts +0 -7
  35. package/dist/ai-sdk-provider.browser.js +0 -30
  36. package/dist/esm/ai-sdk-provider.browser.d.ts +0 -7
  37. package/dist/esm/ai-sdk-provider.browser.js +0 -27
@@ -1,8 +1,6 @@
1
1
  import OpenAI from "openai";
2
- import { Verifier } from "./verifier";
2
+ import { SecureClient } from "./secure-client.browser";
3
3
  import { TINFOIL_CONFIG } from "./config";
4
- import { createEncryptedBodyFetch } from "./encrypted-body-fetch";
5
- import { isRealBrowser } from "./env";
6
4
  function createAsyncProxy(promise) {
7
5
  return new Proxy({}, {
8
6
  get(target, prop) {
@@ -37,6 +35,12 @@ export class TinfoilAI {
37
35
  this.baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
38
36
  this.hpkeKeyURL = options.hpkeKeyURL || TINFOIL_CONFIG.HPKE_KEY_URL;
39
37
  this.configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
38
+ // Create the secure client for handling transport security
39
+ this.secureClient = new SecureClient({
40
+ baseURL: this.baseURL,
41
+ hpkeKeyURL: this.hpkeKeyURL,
42
+ configRepo: this.configRepo,
43
+ });
40
44
  this.clientPromise = this.initClient(openAIOptions);
41
45
  }
42
46
  async ready() {
@@ -51,34 +55,15 @@ export class TinfoilAI {
51
55
  return this.createOpenAIClient(options);
52
56
  }
53
57
  async createOpenAIClient(options = {}) {
54
- const verifier = new Verifier({
55
- serverURL: this.baseURL,
56
- configRepo: this.configRepo,
57
- });
58
- try {
59
- await verifier.verify();
60
- this.verificationDocument = verifier.getVerificationDocument();
61
- if (!this.verificationDocument) {
62
- throw new Error("Verification document not available after successful verification");
63
- }
64
- }
65
- catch (error) {
66
- throw new Error(`Failed to verify enclave: ${error}`);
67
- }
68
- const hpkePublicKey = this.verificationDocument.enclaveMeasurement.hpkePublicKey;
69
- if (!hpkePublicKey) {
70
- // In browsers we require HPKE; TLS pinning fallback is Node-only
71
- if (isRealBrowser()) {
72
- throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
73
- "Only HPKE-enabled enclaves can be used in browser environments.");
74
- }
75
- throw new Error("HPKE public key is required in browser environments");
58
+ await this.secureClient.ready();
59
+ this.verificationDocument = await this.secureClient.getVerificationDocument();
60
+ if (!this.verificationDocument) {
61
+ throw new Error("Verification document not available after successful verification");
76
62
  }
77
- const fetchFunction = createEncryptedBodyFetch(this.baseURL, hpkePublicKey, this.hpkeKeyURL);
78
63
  const clientOptions = {
79
64
  ...options,
80
65
  baseURL: this.baseURL,
81
- fetch: fetchFunction,
66
+ fetch: this.secureClient.fetch,
82
67
  };
83
68
  // In browser usage, OpenAI SDK typically needs dangerouslyAllowBrowser
84
69
  clientOptions.dangerouslyAllowBrowser = true;
@@ -25,6 +25,7 @@ export declare class TinfoilAI {
25
25
  private clientPromise;
26
26
  private readyPromise?;
27
27
  private configRepo?;
28
+ private secureClient;
28
29
  private verificationDocument?;
29
30
  apiKey?: string;
30
31
  baseURL?: string;
@@ -1,15 +1,6 @@
1
1
  import OpenAI from "openai";
2
- import { Verifier } from "./verifier";
2
+ import { SecureClient } from "./secure-client";
3
3
  import { TINFOIL_CONFIG } from "./config";
4
- import { createEncryptedBodyFetch } from "./encrypted-body-fetch";
5
- import https from "https";
6
- import { checkServerIdentity as tlsCheckServerIdentity } from "tls";
7
- import { X509Certificate, createHash } from "crypto";
8
- import { Readable } from "stream";
9
- /**
10
- * Detects if the code is running in a real browser environment.
11
- * Returns false for Node.js environments, even with WASM loaded.
12
- */
13
4
  import { isRealBrowser } from "./env";
14
5
  /**
15
6
  * Creates a proxy that allows property access and method calls on a Promise before it resolves.
@@ -67,8 +58,12 @@ export class TinfoilAI {
67
58
  this.apiKey = openAIOptions.apiKey;
68
59
  this.baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
69
60
  this.hpkeKeyURL = options.hpkeKeyURL || TINFOIL_CONFIG.HPKE_KEY_URL;
70
- this.configRepo =
71
- options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
61
+ this.configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
62
+ this.secureClient = new SecureClient({
63
+ baseURL: this.baseURL,
64
+ hpkeKeyURL: this.hpkeKeyURL,
65
+ configRepo: this.configRepo,
66
+ });
72
67
  this.clientPromise = this.initClient(openAIOptions);
73
68
  }
74
69
  /**
@@ -87,44 +82,15 @@ export class TinfoilAI {
87
82
  return this.createOpenAIClient(options);
88
83
  }
89
84
  async createOpenAIClient(options = {}) {
90
- // Verify the enclave before establishing a transport
91
- const verifier = new Verifier({
92
- serverURL: this.baseURL,
93
- configRepo: this.configRepo,
94
- });
95
- try {
96
- await verifier.verify();
97
- this.verificationDocument = verifier.getVerificationDocument();
98
- if (!this.verificationDocument) {
99
- throw new Error("Verification document not available after successful verification");
100
- }
101
- }
102
- catch (error) {
103
- throw new Error(`Failed to verify enclave: ${error}`);
104
- }
105
- const hpkePublicKey = this.verificationDocument.enclaveMeasurement.hpkePublicKey;
106
- const tlsPublicKeyFingerprint = this.verificationDocument.enclaveMeasurement.tlsPublicKeyFingerprint;
107
- let fetchFunction;
108
- if (hpkePublicKey) {
109
- // HPKE available: use encrypted body fetch
110
- fetchFunction = createEncryptedBodyFetch(this.baseURL, hpkePublicKey, this.hpkeKeyURL);
111
- }
112
- else {
113
- // HPKE not available: check if we're in a browser
114
- if (isRealBrowser()) {
115
- throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
116
- "Only HPKE-enabled enclaves can be used in browser environments.");
117
- }
118
- // Node.js environment: fall back to TLS-only verification using pinned TLS fetch
119
- if (!tlsPublicKeyFingerprint) {
120
- throw new Error("Neither HPKE public key nor TLS public key fingerprint available for verification");
121
- }
122
- fetchFunction = createPinnedTlsFetch(tlsPublicKeyFingerprint);
85
+ await this.secureClient.ready();
86
+ this.verificationDocument = await this.secureClient.getVerificationDocument();
87
+ if (!this.verificationDocument) {
88
+ throw new Error("Verification document not available after successful verification");
123
89
  }
124
90
  const clientOptions = {
125
91
  ...options,
126
92
  baseURL: this.baseURL,
127
- fetch: fetchFunction,
93
+ fetch: this.secureClient.fetch,
128
94
  };
129
95
  // Enable dangerouslyAllowBrowser in Node.js with WASM (which makes OpenAI SDK think we're in a browser)
130
96
  // OR if explicitly set by the user (for legitimate browser usage like playgrounds)
@@ -243,109 +209,3 @@ export class TinfoilAI {
243
209
  TinfoilAI.Uploads = OpenAI.Uploads;
244
210
  TinfoilAI.VectorStores = OpenAI.VectorStores;
245
211
  })(TinfoilAI || (TinfoilAI = {}));
246
- function createPinnedTlsFetch(expectedFingerprintHex) {
247
- return (async (input, init) => {
248
- // Normalize URL
249
- const makeURL = (value) => {
250
- if (typeof value === "string")
251
- return new URL(value);
252
- if (value instanceof URL)
253
- return value;
254
- return new URL(value.url);
255
- };
256
- const url = makeURL(input);
257
- if (url.protocol !== "https:") {
258
- throw new Error(`HTTP connections are not allowed. Use HTTPS. URL: ${url.toString()}`);
259
- }
260
- // Gather method and headers
261
- const method = (init?.method || input.method || "GET").toUpperCase();
262
- const headers = new Headers(init?.headers || input?.headers || {});
263
- const headerObj = {};
264
- headers.forEach((v, k) => {
265
- headerObj[k] = v;
266
- });
267
- // Resolve body
268
- let body = init?.body;
269
- if (!body && input instanceof Request) {
270
- // If the original was a Request with a body, read it
271
- try {
272
- const buf = await input.arrayBuffer();
273
- if (buf && buf.byteLength)
274
- body = Buffer.from(buf);
275
- }
276
- catch { }
277
- }
278
- // Convert web streams to Node streams if needed
279
- if (body && typeof body.getReader === "function") {
280
- body = Readable.fromWeb(body);
281
- }
282
- if (body instanceof ArrayBuffer) {
283
- body = Buffer.from(body);
284
- }
285
- if (ArrayBuffer.isView(body)) {
286
- body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
287
- }
288
- const requestOptions = {
289
- protocol: url.protocol,
290
- hostname: url.hostname,
291
- port: url.port ? Number(url.port) : 443,
292
- path: `${url.pathname}${url.search}`,
293
- method,
294
- headers: headerObj,
295
- checkServerIdentity: (host, cert) => {
296
- const raw = cert.raw;
297
- if (!raw) {
298
- return new Error("Certificate raw bytes are unavailable for pinning");
299
- }
300
- const x509 = new X509Certificate(raw);
301
- const publicKeyDer = x509.publicKey.export({ type: "spki", format: "der" });
302
- const fp = createHash("sha256").update(publicKeyDer).digest("hex");
303
- if (fp !== expectedFingerprintHex) {
304
- return new Error(`Certificate public key fingerprint mismatch. Expected: ${expectedFingerprintHex}, Got: ${fp}`);
305
- }
306
- return tlsCheckServerIdentity(host, cert);
307
- },
308
- };
309
- const { signal } = init || {};
310
- const res = await new Promise((resolve, reject) => {
311
- const req = https.request(requestOptions, resolve);
312
- req.on("error", reject);
313
- if (signal) {
314
- if (signal.aborted) {
315
- req.destroy(new Error("Request aborted"));
316
- return;
317
- }
318
- signal.addEventListener("abort", () => req.destroy(new Error("Request aborted")));
319
- }
320
- if (body === undefined || body === null) {
321
- req.end();
322
- }
323
- else if (typeof body === "string" || Buffer.isBuffer(body) || ArrayBuffer.isView(body)) {
324
- req.end(body);
325
- }
326
- else if (typeof body.pipe === "function") {
327
- body.pipe(req);
328
- }
329
- else {
330
- // Fallback: try to serialize objects
331
- req.end(String(body));
332
- }
333
- });
334
- const responseHeaders = new Headers();
335
- for (const [k, v] of Object.entries(res.headers)) {
336
- if (Array.isArray(v)) {
337
- v.forEach(item => responseHeaders.append(k, item));
338
- }
339
- else if (v != null) {
340
- responseHeaders.set(k, String(v));
341
- }
342
- }
343
- // Convert Node stream to Web ReadableStream
344
- const webStream = Readable.toWeb(res);
345
- return new Response(webStream, {
346
- status: res.statusCode || 0,
347
- statusText: res.statusMessage || "",
348
- headers: responseHeaders,
349
- });
350
- });
351
- }
@@ -2,5 +2,6 @@ export { TinfoilAI } from "./client.browser";
2
2
  export { TinfoilAI as default } from "./client.browser";
3
3
  export * from "./verifier";
4
4
  export * from "./verification-runner";
5
- export * from "./ai-sdk-provider.browser";
5
+ export * from "./ai-sdk-provider";
6
6
  export * from "./config";
7
+ export * from "./secure-client";
@@ -3,5 +3,6 @@ export { TinfoilAI } from "./client.browser";
3
3
  export { TinfoilAI as default } from "./client.browser";
4
4
  export * from "./verifier";
5
5
  export * from "./verification-runner";
6
- export * from "./ai-sdk-provider.browser";
6
+ export * from "./ai-sdk-provider";
7
7
  export * from "./config";
8
+ export * from "./secure-client";
@@ -4,4 +4,5 @@ export * from "./verifier";
4
4
  export * from "./verification-runner";
5
5
  export * from "./ai-sdk-provider";
6
6
  export * from "./config";
7
+ export * from "./secure-client";
7
8
  export { type Uploadable, toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";
package/dist/esm/index.js CHANGED
@@ -6,6 +6,7 @@ export * from "./verifier";
6
6
  export * from "./verification-runner";
7
7
  export * from "./ai-sdk-provider";
8
8
  export * from "./config";
9
+ export * from "./secure-client";
9
10
  // Re-export OpenAI utility types and classes that users might need
10
11
  // Using public exports from the main OpenAI package instead of deep imports
11
12
  export { toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";
@@ -0,0 +1 @@
1
+ export declare function createPinnedTlsFetch(expectedFingerprintHex: string): typeof fetch;
@@ -0,0 +1,110 @@
1
+ import https from "https";
2
+ import { checkServerIdentity as tlsCheckServerIdentity } from "tls";
3
+ import { X509Certificate, createHash } from "crypto";
4
+ import { Readable } from "stream";
5
+ export function createPinnedTlsFetch(expectedFingerprintHex) {
6
+ return (async (input, init) => {
7
+ // Normalize URL
8
+ const makeURL = (value) => {
9
+ if (typeof value === "string")
10
+ return new URL(value);
11
+ if (value instanceof URL)
12
+ return value;
13
+ return new URL(value.url);
14
+ };
15
+ const url = makeURL(input);
16
+ if (url.protocol !== "https:") {
17
+ throw new Error(`HTTP connections are not allowed. Use HTTPS. URL: ${url.toString()}`);
18
+ }
19
+ // Gather method and headers
20
+ const method = (init?.method || input.method || "GET").toUpperCase();
21
+ const headers = new Headers(init?.headers || input?.headers || {});
22
+ const headerObj = {};
23
+ headers.forEach((v, k) => {
24
+ headerObj[k] = v;
25
+ });
26
+ // Resolve body
27
+ let body = init?.body;
28
+ if (!body && input instanceof Request) {
29
+ // If the original was a Request with a body, read it
30
+ try {
31
+ const buf = await input.arrayBuffer();
32
+ if (buf && buf.byteLength)
33
+ body = Buffer.from(buf);
34
+ }
35
+ catch { }
36
+ }
37
+ // Convert web streams to Node streams if needed
38
+ if (body && typeof body.getReader === "function") {
39
+ body = Readable.fromWeb(body);
40
+ }
41
+ if (body instanceof ArrayBuffer) {
42
+ body = Buffer.from(body);
43
+ }
44
+ if (ArrayBuffer.isView(body)) {
45
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
46
+ }
47
+ const requestOptions = {
48
+ protocol: url.protocol,
49
+ hostname: url.hostname,
50
+ port: url.port ? Number(url.port) : 443,
51
+ path: `${url.pathname}${url.search}`,
52
+ method,
53
+ headers: headerObj,
54
+ checkServerIdentity: (host, cert) => {
55
+ const raw = cert.raw;
56
+ if (!raw) {
57
+ return new Error("Certificate raw bytes are unavailable for pinning");
58
+ }
59
+ const x509 = new X509Certificate(raw);
60
+ const publicKeyDer = x509.publicKey.export({ type: "spki", format: "der" });
61
+ const fp = createHash("sha256").update(publicKeyDer).digest("hex");
62
+ if (fp !== expectedFingerprintHex) {
63
+ return new Error(`Certificate public key fingerprint mismatch. Expected: ${expectedFingerprintHex}, Got: ${fp}`);
64
+ }
65
+ return tlsCheckServerIdentity(host, cert);
66
+ },
67
+ };
68
+ const { signal } = init || {};
69
+ const res = await new Promise((resolve, reject) => {
70
+ const req = https.request(requestOptions, resolve);
71
+ req.on("error", reject);
72
+ if (signal) {
73
+ if (signal.aborted) {
74
+ req.destroy(new Error("Request aborted"));
75
+ return;
76
+ }
77
+ signal.addEventListener("abort", () => req.destroy(new Error("Request aborted")));
78
+ }
79
+ if (body === undefined || body === null) {
80
+ req.end();
81
+ }
82
+ else if (typeof body === "string" || Buffer.isBuffer(body) || ArrayBuffer.isView(body)) {
83
+ req.end(body);
84
+ }
85
+ else if (typeof body.pipe === "function") {
86
+ body.pipe(req);
87
+ }
88
+ else {
89
+ // Fallback: try to serialize objects
90
+ req.end(String(body));
91
+ }
92
+ });
93
+ const responseHeaders = new Headers();
94
+ for (const [k, v] of Object.entries(res.headers)) {
95
+ if (Array.isArray(v)) {
96
+ v.forEach(item => responseHeaders.append(k, item));
97
+ }
98
+ else if (v != null) {
99
+ responseHeaders.set(k, String(v));
100
+ }
101
+ }
102
+ // Convert Node stream to Web ReadableStream
103
+ const webStream = Readable.toWeb(res);
104
+ return new Response(webStream, {
105
+ status: res.statusCode || 0,
106
+ statusText: res.statusMessage || "",
107
+ headers: responseHeaders,
108
+ });
109
+ });
110
+ }
@@ -0,0 +1,20 @@
1
+ import type { VerificationDocument } from "./verifier";
2
+ interface SecureClientOptions {
3
+ baseURL?: string;
4
+ hpkeKeyURL?: string;
5
+ configRepo?: string;
6
+ }
7
+ export declare class SecureClient {
8
+ private initPromise;
9
+ private verificationDocument;
10
+ private _fetch;
11
+ private readonly baseURL?;
12
+ private readonly hpkeKeyURL?;
13
+ private readonly configRepo?;
14
+ constructor(options?: SecureClientOptions);
15
+ ready(): Promise<void>;
16
+ private initSecureClient;
17
+ getVerificationDocument(): Promise<VerificationDocument>;
18
+ get fetch(): typeof fetch;
19
+ }
20
+ export {};
@@ -0,0 +1,57 @@
1
+ import { Verifier } from "./verifier";
2
+ import { TINFOIL_CONFIG } from "./config";
3
+ import { createEncryptedBodyFetch } from "./encrypted-body-fetch";
4
+ import { isRealBrowser } from "./env";
5
+ export class SecureClient {
6
+ constructor(options = {}) {
7
+ this.initPromise = null;
8
+ this.verificationDocument = null;
9
+ this._fetch = null;
10
+ this.baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
11
+ this.hpkeKeyURL = options.hpkeKeyURL || TINFOIL_CONFIG.HPKE_KEY_URL;
12
+ this.configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
13
+ }
14
+ async ready() {
15
+ if (!this.initPromise) {
16
+ this.initPromise = this.initSecureClient();
17
+ }
18
+ return this.initPromise;
19
+ }
20
+ async initSecureClient() {
21
+ const verifier = new Verifier({
22
+ serverURL: this.baseURL,
23
+ configRepo: this.configRepo,
24
+ });
25
+ await verifier.verify();
26
+ const doc = verifier.getVerificationDocument();
27
+ if (!doc) {
28
+ throw new Error("Verification document not available after successful verification");
29
+ }
30
+ this.verificationDocument = doc;
31
+ const hpkePublicKey = this.verificationDocument.enclaveMeasurement.hpkePublicKey;
32
+ if (!hpkePublicKey) {
33
+ if (isRealBrowser()) {
34
+ throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
35
+ "Only HPKE-enabled enclaves can be used in browser environments.");
36
+ }
37
+ throw new Error("HPKE public key is required in browser environments");
38
+ }
39
+ this._fetch = createEncryptedBodyFetch(this.baseURL, hpkePublicKey, this.hpkeKeyURL);
40
+ }
41
+ async getVerificationDocument() {
42
+ if (!this.initPromise) {
43
+ await this.ready();
44
+ }
45
+ await this.initPromise;
46
+ if (!this.verificationDocument) {
47
+ throw new Error("Verification document unavailable: client not verified yet");
48
+ }
49
+ return this.verificationDocument;
50
+ }
51
+ get fetch() {
52
+ return async (input, init) => {
53
+ await this.ready();
54
+ return this._fetch(input, init);
55
+ };
56
+ }
57
+ }
@@ -0,0 +1,20 @@
1
+ import type { VerificationDocument } from "./verifier";
2
+ interface SecureClientOptions {
3
+ baseURL?: string;
4
+ hpkeKeyURL?: string;
5
+ configRepo?: string;
6
+ }
7
+ export declare class SecureClient {
8
+ private initPromise;
9
+ private verificationDocument;
10
+ private _fetch;
11
+ private readonly baseURL?;
12
+ private readonly hpkeKeyURL?;
13
+ private readonly configRepo?;
14
+ constructor(options?: SecureClientOptions);
15
+ ready(): Promise<void>;
16
+ private initSecureClient;
17
+ getVerificationDocument(): Promise<VerificationDocument>;
18
+ get fetch(): typeof fetch;
19
+ }
20
+ export {};
@@ -0,0 +1,68 @@
1
+ import { Verifier } from "./verifier";
2
+ import { TINFOIL_CONFIG } from "./config";
3
+ import { createEncryptedBodyFetch } from "./encrypted-body-fetch";
4
+ import { createPinnedTlsFetch } from "./pinned-tls-fetch";
5
+ import { isRealBrowser } from "./env";
6
+ export class SecureClient {
7
+ constructor(options = {}) {
8
+ this.initPromise = null;
9
+ this.verificationDocument = null;
10
+ this._fetch = null;
11
+ this.baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
12
+ this.hpkeKeyURL = options.hpkeKeyURL || TINFOIL_CONFIG.HPKE_KEY_URL;
13
+ this.configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
14
+ }
15
+ async ready() {
16
+ if (!this.initPromise) {
17
+ this.initPromise = this.initSecureClient();
18
+ }
19
+ return this.initPromise;
20
+ }
21
+ async initSecureClient() {
22
+ const verifier = new Verifier({
23
+ serverURL: this.baseURL,
24
+ configRepo: this.configRepo,
25
+ });
26
+ await verifier.verify();
27
+ const doc = verifier.getVerificationDocument();
28
+ if (!doc) {
29
+ throw new Error("Verification document not available after successful verification");
30
+ }
31
+ this.verificationDocument = doc;
32
+ const { hpkePublicKey, tlsPublicKeyFingerprint } = this.verificationDocument.enclaveMeasurement;
33
+ let fetchFunction;
34
+ if (hpkePublicKey) {
35
+ // HPKE available: use encrypted body fetch
36
+ fetchFunction = createEncryptedBodyFetch(this.baseURL, hpkePublicKey, this.hpkeKeyURL);
37
+ }
38
+ else {
39
+ // HPKE not available: check if we're in a browser
40
+ if (isRealBrowser()) {
41
+ throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
42
+ "Only HPKE-enabled enclaves can be used in browser environments.");
43
+ }
44
+ // Node.js environment: fall back to TLS-only verification using pinned TLS fetch
45
+ if (!tlsPublicKeyFingerprint) {
46
+ throw new Error("Neither HPKE public key nor TLS public key fingerprint available for verification");
47
+ }
48
+ fetchFunction = createPinnedTlsFetch(tlsPublicKeyFingerprint);
49
+ }
50
+ this._fetch = fetchFunction;
51
+ }
52
+ async getVerificationDocument() {
53
+ if (!this.initPromise) {
54
+ await this.ready();
55
+ }
56
+ await this.initPromise;
57
+ if (!this.verificationDocument) {
58
+ throw new Error("Verification document unavailable: client not verified yet");
59
+ }
60
+ return this.verificationDocument;
61
+ }
62
+ get fetch() {
63
+ return async (input, init) => {
64
+ await this.ready();
65
+ return this._fetch(input, init);
66
+ };
67
+ }
68
+ }
@@ -2,5 +2,6 @@ export { TinfoilAI } from "./client.browser";
2
2
  export { TinfoilAI as default } from "./client.browser";
3
3
  export * from "./verifier";
4
4
  export * from "./verification-runner";
5
- export * from "./ai-sdk-provider.browser";
5
+ export * from "./ai-sdk-provider";
6
6
  export * from "./config";
7
+ export * from "./secure-client";
@@ -22,5 +22,6 @@ var client_browser_2 = require("./client.browser");
22
22
  Object.defineProperty(exports, "default", { enumerable: true, get: function () { return client_browser_2.TinfoilAI; } });
23
23
  __exportStar(require("./verifier"), exports);
24
24
  __exportStar(require("./verification-runner"), exports);
25
- __exportStar(require("./ai-sdk-provider.browser"), exports);
25
+ __exportStar(require("./ai-sdk-provider"), exports);
26
26
  __exportStar(require("./config"), exports);
27
+ __exportStar(require("./secure-client"), exports);
package/dist/index.d.ts CHANGED
@@ -4,4 +4,5 @@ export * from "./verifier";
4
4
  export * from "./verification-runner";
5
5
  export * from "./ai-sdk-provider";
6
6
  export * from "./config";
7
+ export * from "./secure-client";
7
8
  export { type Uploadable, toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";
package/dist/index.js CHANGED
@@ -25,6 +25,7 @@ __exportStar(require("./verifier"), exports);
25
25
  __exportStar(require("./verification-runner"), exports);
26
26
  __exportStar(require("./ai-sdk-provider"), exports);
27
27
  __exportStar(require("./config"), exports);
28
+ __exportStar(require("./secure-client"), exports);
28
29
  // Re-export OpenAI utility types and classes that users might need
29
30
  // Using public exports from the main OpenAI package instead of deep imports
30
31
  var openai_1 = require("openai");
@@ -0,0 +1 @@
1
+ export declare function createPinnedTlsFetch(expectedFingerprintHex: string): typeof fetch;