tinfoil 0.8.2 → 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 (54) hide show
  1. package/README.md +3 -0
  2. package/dist/ai-sdk-provider.d.ts +1 -9
  3. package/dist/ai-sdk-provider.js +9 -157
  4. package/dist/client.browser.d.ts +3 -0
  5. package/dist/client.browser.js +13 -34
  6. package/dist/client.d.ts +4 -0
  7. package/dist/client.js +13 -159
  8. package/dist/config.d.ts +6 -0
  9. package/dist/config.js +6 -0
  10. package/dist/encrypted-body-fetch.d.ts +2 -2
  11. package/dist/encrypted-body-fetch.js +54 -16
  12. package/dist/esm/ai-sdk-provider.d.ts +1 -9
  13. package/dist/esm/ai-sdk-provider.js +9 -154
  14. package/dist/esm/client.browser.d.ts +3 -0
  15. package/dist/esm/client.browser.js +13 -34
  16. package/dist/esm/client.d.ts +4 -0
  17. package/dist/esm/client.js +13 -159
  18. package/dist/esm/config.d.ts +6 -0
  19. package/dist/esm/config.js +6 -0
  20. package/dist/esm/encrypted-body-fetch.d.ts +2 -2
  21. package/dist/esm/encrypted-body-fetch.js +54 -16
  22. package/dist/esm/index.browser.d.ts +2 -1
  23. package/dist/esm/index.browser.js +2 -1
  24. package/dist/esm/index.d.ts +1 -0
  25. package/dist/esm/index.js +1 -0
  26. package/dist/esm/pinned-tls-fetch.d.ts +1 -0
  27. package/dist/esm/pinned-tls-fetch.js +110 -0
  28. package/dist/esm/secure-client.browser.d.ts +20 -0
  29. package/dist/esm/secure-client.browser.js +57 -0
  30. package/dist/esm/secure-client.d.ts +20 -0
  31. package/dist/esm/secure-client.js +68 -0
  32. package/dist/esm/verification-runner.d.ts +0 -9
  33. package/dist/esm/verification-runner.js +1 -43
  34. package/dist/esm/verifier.d.ts +0 -2
  35. package/dist/esm/verifier.js +21 -52
  36. package/dist/index.browser.d.ts +2 -1
  37. package/dist/index.browser.js +2 -1
  38. package/dist/index.d.ts +1 -0
  39. package/dist/index.js +1 -0
  40. package/dist/pinned-tls-fetch.d.ts +1 -0
  41. package/dist/pinned-tls-fetch.js +116 -0
  42. package/dist/secure-client.browser.d.ts +20 -0
  43. package/dist/secure-client.browser.js +61 -0
  44. package/dist/secure-client.d.ts +20 -0
  45. package/dist/secure-client.js +72 -0
  46. package/dist/verification-runner.d.ts +0 -9
  47. package/dist/verification-runner.js +1 -44
  48. package/dist/verifier.d.ts +0 -2
  49. package/dist/verifier.js +21 -52
  50. package/package.json +7 -2
  51. package/dist/ai-sdk-provider.browser.d.ts +0 -6
  52. package/dist/ai-sdk-provider.browser.js +0 -36
  53. package/dist/esm/ai-sdk-provider.browser.d.ts +0 -6
  54. package/dist/esm/ai-sdk-provider.browser.js +0 -33
@@ -40,6 +40,7 @@ exports.__setEhbpModuleForTests = __setEhbpModuleForTests;
40
40
  exports.__resetEhbpModuleStateForTests = __resetEhbpModuleStateForTests;
41
41
  const env_1 = require("./env");
42
42
  const transportCache = new Map();
43
+ const compositeTransportCache = new Map();
43
44
  let ehbpModulePromise = null;
44
45
  let ehbpModuleOverride;
45
46
  // Public API
@@ -63,30 +64,38 @@ function normalizeEncryptedBodyRequestArgs(input, init) {
63
64
  init: { ...derivedInit, ...init },
64
65
  };
65
66
  }
66
- async function encryptedBodyRequest(input, hpkePublicKey, init) {
67
+ async function encryptedBodyRequest(input, hpkePublicKey, init, hpkeKeyURL) {
67
68
  const { url: requestUrl, init: requestInit } = normalizeEncryptedBodyRequestArgs(input, init);
68
69
  const u = new URL(requestUrl);
69
- if (u.protocol !== 'https:') {
70
- throw new Error(`HTTP connections are not allowed for EHBP. Use HTTPS. URL: ${requestUrl}`);
71
- }
72
70
  const { origin } = u;
73
- const transport = await getTransportForOrigin(origin);
71
+ // Determine which origin to fetch the HPKE key from (may be different from request origin)
72
+ const keyOrigin = hpkeKeyURL ? new URL(hpkeKeyURL).origin : origin;
73
+ // If key origin matches request origin, use the standard transport (fetches keys from origin)
74
+ // Otherwise, build a composite transport that routes to `origin` but uses the key fetched from `keyOrigin`.
75
+ const transport = keyOrigin === origin
76
+ ? await getTransportForOrigin(origin)
77
+ : await getTransportForRequestOriginWithKeyFrom(origin, keyOrigin);
74
78
  const serverPublicKey = await transport.getServerPublicKeyHex();
75
79
  if (serverPublicKey !== hpkePublicKey) {
76
- transportCache.delete(origin);
80
+ // Clear caches so the next attempt re-handshakes
81
+ if (keyOrigin === origin) {
82
+ transportCache.delete(origin);
83
+ }
84
+ else {
85
+ const cacheKey = `${origin}::${keyOrigin}`;
86
+ compositeTransportCache.delete(cacheKey);
87
+ // Also clear the underlying key-origin cache to force re-fetch
88
+ transportCache.delete(keyOrigin);
89
+ }
77
90
  throw new Error(`HPKE public key mismatch: expected ${hpkePublicKey}, got ${serverPublicKey}`);
78
91
  }
79
92
  return transport.request(requestUrl, requestInit);
80
93
  }
81
- function createEncryptedBodyFetch(baseURL, hpkePublicKey) {
94
+ function createEncryptedBodyFetch(baseURL, hpkePublicKey, hpkeKeyURL) {
82
95
  return (async (input, init) => {
83
- const base = new URL(baseURL);
84
- if (base.protocol !== 'https:') {
85
- throw new Error(`EHBP baseURL must use HTTPS. Got: ${baseURL}`);
86
- }
87
96
  const normalized = normalizeEncryptedBodyRequestArgs(input, init);
88
97
  const targetUrl = new URL(normalized.url, baseURL);
89
- return encryptedBodyRequest(targetUrl.toString(), hpkePublicKey, normalized.init);
98
+ return encryptedBodyRequest(targetUrl.toString(), hpkePublicKey, normalized.init, hpkeKeyURL);
90
99
  });
91
100
  }
92
101
  // Private helper functions
@@ -122,10 +131,6 @@ async function getTransportForOrigin(origin) {
122
131
  }
123
132
  const transportPromise = (async () => {
124
133
  const { Identity, createTransport } = await getEhbpModule();
125
- const proto = new URL(origin).protocol;
126
- if (proto !== 'https:') {
127
- throw new Error(`EHBP requires HTTPS origin. Got: ${origin}`);
128
- }
129
134
  // Ensure we're in a secure context with WebCrypto Subtle available (required by EHBP)
130
135
  if (typeof globalThis !== 'undefined') {
131
136
  const isSecure = globalThis.isSecureContext !== false;
@@ -146,6 +151,38 @@ async function getTransportForOrigin(origin) {
146
151
  transportCache.set(origin, transportPromise);
147
152
  return transportPromise;
148
153
  }
154
+ async function getTransportForRequestOriginWithKeyFrom(origin, keyOrigin) {
155
+ const cacheKey = `${origin}::${keyOrigin}`;
156
+ const cached = compositeTransportCache.get(cacheKey);
157
+ if (cached) {
158
+ return cached;
159
+ }
160
+ const transportPromise = (async () => {
161
+ const { Identity, createTransport, Transport } = await getEhbpModule();
162
+ // Ensure secure browser context
163
+ if (typeof globalThis !== 'undefined') {
164
+ const isSecure = globalThis.isSecureContext !== false;
165
+ const hasSubtle = !!(globalThis.crypto && globalThis.crypto.subtle);
166
+ if (!isSecure || !hasSubtle) {
167
+ const reason = !isSecure ? 'insecure context (use HTTPS or localhost)' : 'missing WebCrypto SubtleCrypto';
168
+ throw new Error(`EHBP requires a secure browser context: ${reason}`);
169
+ }
170
+ }
171
+ // Create a single client identity to use for both key discovery and requests
172
+ const clientIdentity = await Identity.generate();
173
+ // Fetch the server's HPKE public key from the dedicated key origin
174
+ const keyTransport = await createTransport(keyOrigin, clientIdentity);
175
+ // Reuse the discovered server public key but route to the request origin
176
+ const serverPublicKey = keyTransport.getServerPublicKey();
177
+ const requestHost = new URL(origin).host;
178
+ return new Transport(clientIdentity, requestHost, serverPublicKey);
179
+ })().catch((error) => {
180
+ compositeTransportCache.delete(cacheKey);
181
+ throw error;
182
+ });
183
+ compositeTransportCache.set(cacheKey, transportPromise);
184
+ return transportPromise;
185
+ }
149
186
  // Test utilities
150
187
  function __setEhbpModuleForTests(module) {
151
188
  ehbpModuleOverride = module;
@@ -155,4 +192,5 @@ function __resetEhbpModuleStateForTests() {
155
192
  ehbpModuleOverride = undefined;
156
193
  ehbpModulePromise = null;
157
194
  transportCache.clear();
195
+ compositeTransportCache.clear();
158
196
  }
@@ -1,15 +1,7 @@
1
1
  interface CreateTinfoilAIOptions {
2
- /** Override the inference API base URL */
3
2
  baseURL?: string;
4
- /** Override the config GitHub repository */
3
+ hpkeKeyURL?: string;
5
4
  configRepo?: string;
6
5
  }
7
- /**
8
- * Creates an AI SDK provider with the specified API key.
9
- *
10
- * @param apiKey - The API key for the Tinfoil API
11
- * @param options - Optional configuration options
12
- * @returns A TinfoilAI instance
13
- */
14
6
  export declare function createTinfoilAI(apiKey: string, options?: CreateTinfoilAIOptions): Promise<import("@ai-sdk/openai-compatible").OpenAICompatibleProvider<string, string, string, string>>;
15
7
  export {};
@@ -1,165 +1,20 @@
1
1
  import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
2
2
  import { TINFOIL_CONFIG } from "./config";
3
- import { createEncryptedBodyFetch } from "./encrypted-body-fetch";
4
- import { Verifier } from "./verifier";
5
- import { isRealBrowser } from "./env";
6
- import https from "https";
7
- import { checkServerIdentity as tlsCheckServerIdentity } from "tls";
8
- import { X509Certificate, createHash } from "crypto";
9
- import { Readable } from "stream";
10
- /**
11
- * Creates an AI SDK provider with the specified API key.
12
- *
13
- * @param apiKey - The API key for the Tinfoil API
14
- * @param options - Optional configuration options
15
- * @returns A TinfoilAI instance
16
- */
3
+ import { SecureClient } from "./secure-client";
17
4
  export async function createTinfoilAI(apiKey, options = {}) {
18
5
  const baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
6
+ const hpkeKeyURL = options.hpkeKeyURL || TINFOIL_CONFIG.HPKE_KEY_URL;
19
7
  const configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
20
- assertHttpsUrl(baseURL, "Inference baseURL");
21
- // step 1: verify the enclave and extract the public keys
22
- // from the attestation response
23
- const verifier = new Verifier({ serverURL: baseURL, configRepo });
24
- const attestationResponse = await verifier.verify();
25
- const hpkePublicKey = attestationResponse.hpkePublicKey;
26
- const tlsPublicKeyFingerprint = attestationResponse.tlsPublicKeyFingerprint;
27
- // step 2: create the appropriate fetch function based on available keys
28
- let fetchFunction;
29
- if (hpkePublicKey) {
30
- // HPKE available: use encrypted body fetch
31
- fetchFunction = createEncryptedBodyFetch(baseURL, hpkePublicKey);
32
- }
33
- else {
34
- // HPKE not available: check if we're in a browser
35
- if (isRealBrowser()) {
36
- throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
37
- "Only HPKE-enabled enclaves can be used in browser environments.");
38
- }
39
- // Node.js environment: fall back to TLS-only verification using pinned TLS fetch
40
- if (!tlsPublicKeyFingerprint) {
41
- throw new Error("Neither HPKE public key nor TLS public key fingerprint available for verification");
42
- }
43
- fetchFunction = createPinnedTlsFetch(tlsPublicKeyFingerprint);
44
- }
45
- // step 3: create the openai compatible provider
46
- // that uses the appropriate fetch function
8
+ const secureClient = new SecureClient({
9
+ baseURL,
10
+ hpkeKeyURL,
11
+ configRepo,
12
+ });
13
+ await secureClient.ready();
47
14
  return createOpenAICompatible({
48
15
  name: "tinfoil",
49
16
  baseURL: baseURL.replace(/\/$/, ""),
50
17
  apiKey: apiKey,
51
- fetch: fetchFunction,
52
- });
53
- }
54
- function assertHttpsUrl(url, context) {
55
- const parsed = new URL(url);
56
- if (parsed.protocol !== "https:") {
57
- throw new Error(`${context} must use HTTPS. Got: ${url}`);
58
- }
59
- }
60
- function createPinnedTlsFetch(expectedFingerprintHex) {
61
- return (async (input, init) => {
62
- // Normalize URL
63
- const makeURL = (value) => {
64
- if (typeof value === "string")
65
- return new URL(value);
66
- if (value instanceof URL)
67
- return value;
68
- return new URL(value.url);
69
- };
70
- const url = makeURL(input);
71
- if (url.protocol !== "https:") {
72
- throw new Error(`HTTP connections are not allowed. Use HTTPS. URL: ${url.toString()}`);
73
- }
74
- // Gather method and headers
75
- const method = (init?.method || input.method || "GET").toUpperCase();
76
- const headers = new Headers(init?.headers || input?.headers || {});
77
- const headerObj = {};
78
- headers.forEach((v, k) => {
79
- headerObj[k] = v;
80
- });
81
- // Resolve body
82
- let body = init?.body;
83
- if (!body && input instanceof Request) {
84
- // If the original was a Request with a body, read it
85
- try {
86
- const buf = await input.arrayBuffer();
87
- if (buf && buf.byteLength)
88
- body = Buffer.from(buf);
89
- }
90
- catch { }
91
- }
92
- // Convert web streams to Node streams if needed
93
- if (body && typeof body.getReader === "function") {
94
- body = Readable.fromWeb(body);
95
- }
96
- if (body instanceof ArrayBuffer) {
97
- body = Buffer.from(body);
98
- }
99
- if (ArrayBuffer.isView(body)) {
100
- body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
101
- }
102
- const requestOptions = {
103
- protocol: url.protocol,
104
- hostname: url.hostname,
105
- port: url.port ? Number(url.port) : 443,
106
- path: `${url.pathname}${url.search}`,
107
- method,
108
- headers: headerObj,
109
- checkServerIdentity: (host, cert) => {
110
- const raw = cert.raw;
111
- if (!raw) {
112
- return new Error("Certificate raw bytes are unavailable for pinning");
113
- }
114
- const x509 = new X509Certificate(raw);
115
- const publicKeyDer = x509.publicKey.export({ type: "spki", format: "der" });
116
- const fp = createHash("sha256").update(publicKeyDer).digest("hex");
117
- if (fp !== expectedFingerprintHex) {
118
- return new Error(`Certificate public key fingerprint mismatch. Expected: ${expectedFingerprintHex}, Got: ${fp}`);
119
- }
120
- return tlsCheckServerIdentity(host, cert);
121
- },
122
- };
123
- const { signal } = init || {};
124
- const res = await new Promise((resolve, reject) => {
125
- const req = https.request(requestOptions, resolve);
126
- req.on("error", reject);
127
- if (signal) {
128
- if (signal.aborted) {
129
- req.destroy(new Error("Request aborted"));
130
- return;
131
- }
132
- signal.addEventListener("abort", () => req.destroy(new Error("Request aborted")));
133
- }
134
- if (body === undefined || body === null) {
135
- req.end();
136
- }
137
- else if (typeof body === "string" || Buffer.isBuffer(body) || ArrayBuffer.isView(body)) {
138
- req.end(body);
139
- }
140
- else if (typeof body.pipe === "function") {
141
- body.pipe(req);
142
- }
143
- else {
144
- // Fallback: try to serialize objects
145
- req.end(String(body));
146
- }
147
- });
148
- const responseHeaders = new Headers();
149
- for (const [k, v] of Object.entries(res.headers)) {
150
- if (Array.isArray(v)) {
151
- v.forEach(item => responseHeaders.append(k, item));
152
- }
153
- else if (v != null) {
154
- responseHeaders.set(k, String(v));
155
- }
156
- }
157
- // Convert Node stream to Web ReadableStream
158
- const webStream = Readable.toWeb(res);
159
- return new Response(webStream, {
160
- status: res.statusCode || 0,
161
- statusText: res.statusMessage || "",
162
- headers: responseHeaders,
163
- });
18
+ fetch: secureClient.fetch,
164
19
  });
165
20
  }
@@ -4,6 +4,7 @@ import type { VerificationDocument } from "./verifier";
4
4
  interface TinfoilAIOptions {
5
5
  apiKey?: string;
6
6
  baseURL?: string;
7
+ hpkeKeyURL?: string;
7
8
  configRepo?: string;
8
9
  [key: string]: any;
9
10
  }
@@ -12,9 +13,11 @@ export declare class TinfoilAI {
12
13
  private clientPromise;
13
14
  private readyPromise?;
14
15
  private configRepo?;
16
+ private secureClient;
15
17
  private verificationDocument?;
16
18
  apiKey?: string;
17
19
  baseURL?: string;
20
+ hpkeKeyURL?: string;
18
21
  constructor(options?: TinfoilAIOptions);
19
22
  ready(): Promise<void>;
20
23
  private initClient;
@@ -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) {
@@ -35,8 +33,14 @@ export class TinfoilAI {
35
33
  }
36
34
  this.apiKey = openAIOptions.apiKey;
37
35
  this.baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
38
- assertHttpsUrl(this.baseURL, "Inference baseURL");
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);
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;
@@ -142,9 +127,3 @@ export class TinfoilAI {
142
127
  TinfoilAI.Uploads = OpenAI.Uploads;
143
128
  TinfoilAI.VectorStores = OpenAI.VectorStores;
144
129
  })(TinfoilAI || (TinfoilAI = {}));
145
- function assertHttpsUrl(url, context) {
146
- const parsed = new URL(url);
147
- if (parsed.protocol !== "https:") {
148
- throw new Error(`${context} must use HTTPS. Got: ${url}`);
149
- }
150
- }
@@ -14,6 +14,8 @@ interface TinfoilAIOptions {
14
14
  apiKey?: string;
15
15
  /** Override the inference API base URL */
16
16
  baseURL?: string;
17
+ /** Override the URL used to fetch the HPKE key (defaults to baseURL) */
18
+ hpkeKeyURL?: string;
17
19
  /** Override the config GitHub repository */
18
20
  configRepo?: string;
19
21
  [key: string]: any;
@@ -23,9 +25,11 @@ export declare class TinfoilAI {
23
25
  private clientPromise;
24
26
  private readyPromise?;
25
27
  private configRepo?;
28
+ private secureClient;
26
29
  private verificationDocument?;
27
30
  apiKey?: string;
28
31
  baseURL?: string;
32
+ hpkeKeyURL?: string;
29
33
  /**
30
34
  * Creates a new TinfoilAI instance.
31
35
  * @param options - Configuration options including apiKey and other OpenAI client options
@@ -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.
@@ -66,9 +57,13 @@ export class TinfoilAI {
66
57
  // Store properties for compatibility
67
58
  this.apiKey = openAIOptions.apiKey;
68
59
  this.baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
69
- assertHttpsUrl(this.baseURL, "Inference baseURL");
70
- this.configRepo =
71
- options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
60
+ this.hpkeKeyURL = options.hpkeKeyURL || TINFOIL_CONFIG.HPKE_KEY_URL;
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);
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,115 +209,3 @@ export class TinfoilAI {
243
209
  TinfoilAI.Uploads = OpenAI.Uploads;
244
210
  TinfoilAI.VectorStores = OpenAI.VectorStores;
245
211
  })(TinfoilAI || (TinfoilAI = {}));
246
- function assertHttpsUrl(url, context) {
247
- const parsed = new URL(url);
248
- if (parsed.protocol !== "https:") {
249
- throw new Error(`${context} must use HTTPS. Got: ${url}`);
250
- }
251
- }
252
- function createPinnedTlsFetch(expectedFingerprintHex) {
253
- return (async (input, init) => {
254
- // Normalize URL
255
- const makeURL = (value) => {
256
- if (typeof value === "string")
257
- return new URL(value);
258
- if (value instanceof URL)
259
- return value;
260
- return new URL(value.url);
261
- };
262
- const url = makeURL(input);
263
- if (url.protocol !== "https:") {
264
- throw new Error(`HTTP connections are not allowed. Use HTTPS. URL: ${url.toString()}`);
265
- }
266
- // Gather method and headers
267
- const method = (init?.method || input.method || "GET").toUpperCase();
268
- const headers = new Headers(init?.headers || input?.headers || {});
269
- const headerObj = {};
270
- headers.forEach((v, k) => {
271
- headerObj[k] = v;
272
- });
273
- // Resolve body
274
- let body = init?.body;
275
- if (!body && input instanceof Request) {
276
- // If the original was a Request with a body, read it
277
- try {
278
- const buf = await input.arrayBuffer();
279
- if (buf && buf.byteLength)
280
- body = Buffer.from(buf);
281
- }
282
- catch { }
283
- }
284
- // Convert web streams to Node streams if needed
285
- if (body && typeof body.getReader === "function") {
286
- body = Readable.fromWeb(body);
287
- }
288
- if (body instanceof ArrayBuffer) {
289
- body = Buffer.from(body);
290
- }
291
- if (ArrayBuffer.isView(body)) {
292
- body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
293
- }
294
- const requestOptions = {
295
- protocol: url.protocol,
296
- hostname: url.hostname,
297
- port: url.port ? Number(url.port) : 443,
298
- path: `${url.pathname}${url.search}`,
299
- method,
300
- headers: headerObj,
301
- checkServerIdentity: (host, cert) => {
302
- const raw = cert.raw;
303
- if (!raw) {
304
- return new Error("Certificate raw bytes are unavailable for pinning");
305
- }
306
- const x509 = new X509Certificate(raw);
307
- const publicKeyDer = x509.publicKey.export({ type: "spki", format: "der" });
308
- const fp = createHash("sha256").update(publicKeyDer).digest("hex");
309
- if (fp !== expectedFingerprintHex) {
310
- return new Error(`Certificate public key fingerprint mismatch. Expected: ${expectedFingerprintHex}, Got: ${fp}`);
311
- }
312
- return tlsCheckServerIdentity(host, cert);
313
- },
314
- };
315
- const { signal } = init || {};
316
- const res = await new Promise((resolve, reject) => {
317
- const req = https.request(requestOptions, resolve);
318
- req.on("error", reject);
319
- if (signal) {
320
- if (signal.aborted) {
321
- req.destroy(new Error("Request aborted"));
322
- return;
323
- }
324
- signal.addEventListener("abort", () => req.destroy(new Error("Request aborted")));
325
- }
326
- if (body === undefined || body === null) {
327
- req.end();
328
- }
329
- else if (typeof body === "string" || Buffer.isBuffer(body) || ArrayBuffer.isView(body)) {
330
- req.end(body);
331
- }
332
- else if (typeof body.pipe === "function") {
333
- body.pipe(req);
334
- }
335
- else {
336
- // Fallback: try to serialize objects
337
- req.end(String(body));
338
- }
339
- });
340
- const responseHeaders = new Headers();
341
- for (const [k, v] of Object.entries(res.headers)) {
342
- if (Array.isArray(v)) {
343
- v.forEach(item => responseHeaders.append(k, item));
344
- }
345
- else if (v != null) {
346
- responseHeaders.set(k, String(v));
347
- }
348
- }
349
- // Convert Node stream to Web ReadableStream
350
- const webStream = Readable.toWeb(res);
351
- return new Response(webStream, {
352
- status: res.statusCode || 0,
353
- statusText: res.statusMessage || "",
354
- headers: responseHeaders,
355
- });
356
- });
357
- }
@@ -6,6 +6,12 @@ export declare const TINFOIL_CONFIG: {
6
6
  * The full base URL for the inference API
7
7
  */
8
8
  readonly INFERENCE_BASE_URL: "https://inference.tinfoil.sh/v1/";
9
+ /**
10
+ * The URL used to fetch the HPKE server public key (via EHBP .well-known endpoint).
11
+ * Defaults to the same value as `INFERENCE_BASE_URL` so hpkeKeyURL and baseURL share
12
+ * the same default. Callers may override independently if key discovery is hosted elsewhere.
13
+ */
14
+ readonly HPKE_KEY_URL: "https://inference.tinfoil.sh/v1/";
9
15
  /**
10
16
  * The GitHub repository for the confidential inference proxy
11
17
  */
@@ -6,6 +6,12 @@ export const TINFOIL_CONFIG = {
6
6
  * The full base URL for the inference API
7
7
  */
8
8
  INFERENCE_BASE_URL: "https://inference.tinfoil.sh/v1/",
9
+ /**
10
+ * The URL used to fetch the HPKE server public key (via EHBP .well-known endpoint).
11
+ * Defaults to the same value as `INFERENCE_BASE_URL` so hpkeKeyURL and baseURL share
12
+ * the same default. Callers may override independently if key discovery is hosted elsewhere.
13
+ */
14
+ HPKE_KEY_URL: "https://inference.tinfoil.sh/v1/",
9
15
  /**
10
16
  * The GitHub repository for the confidential inference proxy
11
17
  */
@@ -3,8 +3,8 @@ export declare function normalizeEncryptedBodyRequestArgs(input: RequestInfo | U
3
3
  url: string;
4
4
  init?: RequestInit;
5
5
  };
6
- export declare function encryptedBodyRequest(input: RequestInfo | URL, hpkePublicKey: string, init?: RequestInit): Promise<Response>;
7
- export declare function createEncryptedBodyFetch(baseURL: string, hpkePublicKey: string): typeof fetch;
6
+ export declare function encryptedBodyRequest(input: RequestInfo | URL, hpkePublicKey: string, init?: RequestInit, hpkeKeyURL?: string): Promise<Response>;
7
+ export declare function createEncryptedBodyFetch(baseURL: string, hpkePublicKey: string, hpkeKeyURL?: string): typeof fetch;
8
8
  export declare function __setEhbpModuleForTests(module: EhbpModule | undefined): void;
9
9
  export declare function __resetEhbpModuleStateForTests(): void;
10
10
  export {};