tinfoil 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,9 @@
3
3
  [![Build Status](https://github.com/tinfoilsh/tinfoil-node/actions/workflows/test.yml/badge.svg)](https://github.com/tinfoilsh/tinfoil-node/actions)
4
4
  [![NPM version](https://img.shields.io/npm/v/tinfoil.svg)](https://npmjs.org/package/tinfoil)
5
5
 
6
- A Node.js wrapper around the OpenAI client that verifies enclave attestation and routes OpenAI-bound traffic through an [EHBP](https://github.com/tinfoilsh/encrypted-http-body-protocol)-secured transport when using Tinfoil inference. EHBP encrypts all payloads directly to an attested enclave using [HPKE (RFC 9180)](https://www.rfc-editor.org/rfc/rfc9180.html).
6
+ This client library provides secure and convenient access to the Tinfoil Priavate Inference endpoints from TypeScript or JavaScript.
7
+
8
+ It is a wrapper around the OpenAI client that verifies enclave attestation and routes traffic to the Tinfoil Private Inference endpoints through an [EHBP](https://github.com/tinfoilsh/encrypted-http-body-protocol)-secured transport. EHBP encrypts all payloads directly to an attested enclave using [HPKE (RFC 9180)](https://www.rfc-editor.org/rfc/rfc9180.html).
7
9
 
8
10
  ## Installation
9
11
 
@@ -54,7 +56,7 @@ const client = new TinfoilAI({
54
56
  await client.ready();
55
57
 
56
58
  const completion = await client.chat.completions.create({
57
- model: 'llama-free',
59
+ model: 'llama3-3-70b',
58
60
  messages: [{ role: 'user', content: 'Hello!' }]
59
61
  });
60
62
  ```
@@ -63,18 +65,13 @@ const completion = await client.chat.completions.create({
63
65
 
64
66
  - Modern browsers with ES2020 support
65
67
  - WebAssembly support for enclave verification
66
- - Secure context (HTTPS or localhost) with WebCrypto SubtleCrypto (required by EHBP)
67
-
68
- > **Note**
69
- > The EHBP transport now accepts `http://` origins (for example when developing against a `localhost` proxy). Payloads remain HPKE-encrypted end to end, while TLS-only fallback logic continues to require HTTPS because it relies on certificate pinning.
70
68
 
71
69
 
72
70
  ## Verification helpers
73
71
 
74
72
  This package exposes verification helpers that load the Go-based WebAssembly verifier once per process and provide structured, stepwise attestation results you can use in applications (e.g., to show progress, log transitions, or gate features).
75
73
 
76
- The verification functionality is split into two modules:
77
- - `verifier.ts`: Core verification logic with low-level attestation methods
74
+ The verification functionality is contained in `verifier.ts`.
78
75
 
79
76
 
80
77
  ### Core Verifier API
@@ -96,6 +93,40 @@ const code = await verifier.verifyCode("tinfoilsh/repo", "digest-hash");
96
93
  const digest = await verifier.fetchLatestDigest("tinfoilsh/repo");
97
94
  ```
98
95
 
96
+ ### Verification Document
97
+
98
+ The `SecureClient` provides access to a comprehensive verification document that tracks all verification steps, including failures:
99
+
100
+ ```typescript
101
+ import { SecureClient } from "tinfoil";
102
+
103
+ const client = new SecureClient();
104
+
105
+ try {
106
+ await client.ready();
107
+ const response = await client.fetch('https://api.example.com/data');
108
+ } catch (error) {
109
+ // Even on error, you can access the verification document
110
+ const doc = await client.getVerificationDocument();
111
+
112
+ // The document contains detailed step information:
113
+ // - fetchDigest: GitHub release digest retrieval
114
+ // - verifyCode: Code measurement verification
115
+ // - verifyEnclave: Runtime attestation verification
116
+ // - compareMeasurements: Code vs runtime measurement comparison
117
+ // - createTransport: Transport initialization (optional)
118
+ // - verifyHPKEKey: HPKE key verification (optional)
119
+ // - otherError: Catch-all for unexpected errors (optional)
120
+
121
+ console.log('Security verified:', doc.securityVerified);
122
+
123
+ // Check individual steps
124
+ if (doc.steps.verifyEnclave.status === 'failed') {
125
+ console.log('Enclave verification failed:', doc.steps.verifyEnclave.error);
126
+ }
127
+ }
128
+ ```
129
+
99
130
  ## Testing
100
131
 
101
132
  The project includes both unit tests and integration tests:
@@ -106,8 +137,6 @@ The project includes both unit tests and integration tests:
106
137
  npm test
107
138
  ```
108
139
 
109
- This runs the test suite with unit tests and mocked components. These tests don't require network access and run quickly.
110
-
111
140
  ### Running Integration Tests
112
141
 
113
142
  ```bash
@@ -121,39 +150,9 @@ This runs the full test suite including integration tests that:
121
150
 
122
151
  Integration tests are skipped by default to keep the test suite fast and avoid network dependencies during development.
123
152
 
124
- ## Running the Chat Example
125
-
126
- The chat example demonstrates both streaming chat completions and real-time attestation verification with a visual progress UI.
127
-
128
- 1. Clone the repository
129
-
130
- 2. Install dependencies:
131
-
132
- ```bash
133
- npm install
134
- npm run build
135
- ```
136
-
137
- 3. Optionally create a `.env` file with your configuration:
138
-
139
- ```bash
140
- TINFOIL_API_KEY=<YOUR_API_KEY>
141
- # Optional: Enable WASM debug logs
142
- # TINFOIL_ENABLE_WASM_LOGS=true
143
- ```
144
-
145
- 4. Run the example:
146
-
147
- ```bash
148
- cd examples/chat
149
- npx ts-node main.ts
150
- ```
153
+ ## Running examples
151
154
 
152
- The example will:
153
- - Display a real-time verification progress showing each attestation step
154
- - Verify the enclave's runtime and code measurements
155
- - Compare measurements using platform-specific logic
156
- - Stream chat completions through the verified secure channel
155
+ See [examples/README.md](https://github.com/tinfoilsh/tinfoil-node/blob/main/examples/README.md).
157
156
 
158
157
  ## API Documentation
159
158
 
@@ -5,8 +5,8 @@ const openai_compatible_1 = require("@ai-sdk/openai-compatible");
5
5
  const config_1 = require("./config");
6
6
  const secure_client_1 = require("./secure-client");
7
7
  async function createTinfoilAI(apiKey, options = {}) {
8
- const baseURL = options.baseURL || config_1.TINFOIL_CONFIG.INFERENCE_BASE_URL;
9
- const enclaveURL = options.enclaveURL || config_1.TINFOIL_CONFIG.ENCLAVE_URL;
8
+ const baseURL = options.baseURL;
9
+ const enclaveURL = options.enclaveURL;
10
10
  const configRepo = options.configRepo || config_1.TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
11
11
  const secureClient = new secure_client_1.SecureClient({
12
12
  baseURL,
@@ -14,9 +14,14 @@ async function createTinfoilAI(apiKey, options = {}) {
14
14
  configRepo,
15
15
  });
16
16
  await secureClient.ready();
17
+ // Get the baseURL from SecureClient after initialization
18
+ const finalBaseURL = baseURL || secureClient.getBaseURL();
19
+ if (!finalBaseURL) {
20
+ throw new Error("Unable to determine baseURL for AI SDK provider");
21
+ }
17
22
  return (0, openai_compatible_1.createOpenAICompatible)({
18
23
  name: "tinfoil",
19
- baseURL: baseURL.replace(/\/$/, ""),
24
+ baseURL: finalBaseURL,
20
25
  apiKey: apiKey,
21
26
  fetch: secureClient.fetch,
22
27
  });
package/dist/config.d.ts CHANGED
@@ -3,18 +3,11 @@
3
3
  */
4
4
  export declare const TINFOIL_CONFIG: {
5
5
  /**
6
- * The full base URL for the inference API
6
+ * The GitHub repository for code attestation verification
7
7
  */
8
- readonly INFERENCE_BASE_URL: "https://inference.tinfoil.sh/v1/";
8
+ readonly INFERENCE_PROXY_REPO: "tinfoilsh/confidential-model-router";
9
9
  /**
10
- * The URL used to fetch the enclave server public key (via EHBP .well-known endpoint).
11
- * and the attestation (vial the attestation .well-known endpoint too).
12
- * Defaults to the same value as `INFERENCE_BASE_URL` so enclaveURL and baseURL share
13
- * the same default. Callers may override independently if key discovery is hosted elsewhere.
10
+ * The ATC (Attestation and Trust Center) API URL for fetching available routers
14
11
  */
15
- readonly ENCLAVE_URL: "https://inference.tinfoil.sh/v1/";
16
- /**
17
- * The GitHub repository for the confidential inference proxy
18
- */
19
- readonly INFERENCE_PROXY_REPO: "tinfoilsh/confidential-inference-proxy";
12
+ readonly ATC_API_URL: "https://atc.tinfoil.sh/routers";
20
13
  };
package/dist/config.js CHANGED
@@ -6,18 +6,11 @@ exports.TINFOIL_CONFIG = void 0;
6
6
  */
7
7
  exports.TINFOIL_CONFIG = {
8
8
  /**
9
- * The full base URL for the inference API
9
+ * The GitHub repository for code attestation verification
10
10
  */
11
- INFERENCE_BASE_URL: "https://inference.tinfoil.sh/v1/",
11
+ INFERENCE_PROXY_REPO: "tinfoilsh/confidential-model-router",
12
12
  /**
13
- * The URL used to fetch the enclave server public key (via EHBP .well-known endpoint).
14
- * and the attestation (vial the attestation .well-known endpoint too).
15
- * Defaults to the same value as `INFERENCE_BASE_URL` so enclaveURL and baseURL share
16
- * the same default. Callers may override independently if key discovery is hosted elsewhere.
13
+ * The ATC (Attestation and Trust Center) API URL for fetching available routers
17
14
  */
18
- ENCLAVE_URL: "https://inference.tinfoil.sh/v1/",
19
- /**
20
- * The GitHub repository for the confidential inference proxy
21
- */
22
- INFERENCE_PROXY_REPO: "tinfoilsh/confidential-inference-proxy",
15
+ ATC_API_URL: "https://atc.tinfoil.sh/routers",
23
16
  };
@@ -1,11 +1,9 @@
1
- type EhbpModule = typeof import("ehbp");
1
+ import type { Transport as EhbpTransport } from "ehbp";
2
2
  export declare function getHPKEKey(enclaveURL: string): Promise<CryptoKey>;
3
3
  export declare function normalizeEncryptedBodyRequestArgs(input: RequestInfo | URL, init?: RequestInit): {
4
4
  url: string;
5
5
  init?: RequestInit;
6
6
  };
7
- export declare function encryptedBodyRequest(input: RequestInfo | URL, hpkePublicKey: string, init?: RequestInit, enclaveURL?: string): Promise<Response>;
8
- export declare function createEncryptedBodyFetch(baseURL: string, hpkePublicKey: string, enclaveURL?: string): typeof fetch;
9
- export declare function __setEhbpModuleForTests(module: EhbpModule | undefined): void;
10
- export declare function __resetEhbpModuleStateForTests(): void;
11
- export {};
7
+ export declare function encryptedBodyRequest(input: RequestInfo | URL, hpkePublicKey?: string, init?: RequestInit, enclaveURL?: string, transportInstance?: EhbpTransport): Promise<Response>;
8
+ export declare function createEncryptedBodyFetch(baseURL: string, hpkePublicKey?: string, enclaveURL?: string): typeof fetch;
9
+ export declare function getTransportForOrigin(origin: string, keyOrigin: string): Promise<EhbpTransport>;
@@ -1,53 +1,15 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
3
  exports.getHPKEKey = getHPKEKey;
37
4
  exports.normalizeEncryptedBodyRequestArgs = normalizeEncryptedBodyRequestArgs;
38
5
  exports.encryptedBodyRequest = encryptedBodyRequest;
39
6
  exports.createEncryptedBodyFetch = createEncryptedBodyFetch;
40
- exports.__setEhbpModuleForTests = __setEhbpModuleForTests;
41
- exports.__resetEhbpModuleStateForTests = __resetEhbpModuleStateForTests;
42
- const env_1 = require("./env");
43
- let transport = null;
44
- let ehbpModulePromise = null;
45
- let ehbpModuleOverride;
7
+ exports.getTransportForOrigin = getTransportForOrigin;
8
+ const ehbp_1 = require("ehbp");
46
9
  // Public API
47
10
  async function getHPKEKey(enclaveURL) {
48
- const { Identity, PROTOCOL } = await getEhbpModule();
49
11
  const url = new URL(enclaveURL);
50
- const keysURL = new URL(PROTOCOL.KEYS_PATH, enclaveURL);
12
+ const keysURL = new URL(ehbp_1.PROTOCOL.KEYS_PATH, enclaveURL);
51
13
  if (keysURL.protocol !== 'https:') {
52
14
  throw new Error(`HTTPS is required for remote key retrieval. Invalid protocol: ${keysURL.protocol}`);
53
15
  }
@@ -56,11 +18,11 @@ async function getHPKEKey(enclaveURL) {
56
18
  throw new Error(`Failed to get server public key: ${response.status}`);
57
19
  }
58
20
  const contentType = response.headers.get('content-type');
59
- if (contentType !== PROTOCOL.KEYS_MEDIA_TYPE) {
21
+ if (contentType !== ehbp_1.PROTOCOL.KEYS_MEDIA_TYPE) {
60
22
  throw new Error(`Invalid content type: ${contentType}`);
61
23
  }
62
24
  const keysData = new Uint8Array(await response.arrayBuffer());
63
- const serverIdentity = await Identity.unmarshalPublicConfig(keysData);
25
+ const serverIdentity = await ehbp_1.Identity.unmarshalPublicConfig(keysData);
64
26
  return serverIdentity.getPublicKey();
65
27
  }
66
28
  function normalizeEncryptedBodyRequestArgs(input, init) {
@@ -83,57 +45,48 @@ function normalizeEncryptedBodyRequestArgs(input, init) {
83
45
  init: { ...derivedInit, ...init },
84
46
  };
85
47
  }
86
- async function encryptedBodyRequest(input, hpkePublicKey, init, enclaveURL) {
48
+ async function encryptedBodyRequest(input, hpkePublicKey, init, enclaveURL, transportInstance) {
87
49
  const { url: requestUrl, init: requestInit } = normalizeEncryptedBodyRequestArgs(input, init);
88
- const u = new URL(requestUrl);
89
- const { origin } = u;
90
- const keyOrigin = enclaveURL ? new URL(enclaveURL).origin : origin;
91
- if (!transport) {
92
- transport = getTransportForOrigin(origin, keyOrigin);
50
+ let actualTransport;
51
+ if (transportInstance) {
52
+ // Use provided transport instance
53
+ actualTransport = transportInstance;
93
54
  }
94
- const transportInstance = await transport;
95
- const transportKeyHash = await transportInstance.getServerPublicKeyHex();
96
- if (transportKeyHash !== hpkePublicKey) {
97
- throw new Error(`HPKE public key mismatch. Expected: ${hpkePublicKey}, Got: ${transportKeyHash}`);
55
+ else {
56
+ // Create a new transport for this request
57
+ const u = new URL(requestUrl);
58
+ const { origin } = u;
59
+ const keyOrigin = enclaveURL ? new URL(enclaveURL).origin : origin;
60
+ actualTransport = await getTransportForOrigin(origin, keyOrigin);
98
61
  }
99
- return transportInstance.request(requestUrl, requestInit);
62
+ if (hpkePublicKey) {
63
+ const transportKeyHash = await actualTransport.getServerPublicKeyHex();
64
+ if (transportKeyHash !== hpkePublicKey) {
65
+ throw new Error(`HPKE public key mismatch. Expected: ${hpkePublicKey}, Got: ${transportKeyHash}`);
66
+ }
67
+ }
68
+ return actualTransport.request(requestUrl, requestInit);
100
69
  }
101
70
  function createEncryptedBodyFetch(baseURL, hpkePublicKey, enclaveURL) {
71
+ // Create a dedicated transport instance for this fetch function
72
+ let transportPromise = null;
73
+ const getOrCreateTransport = async () => {
74
+ if (!transportPromise) {
75
+ const baseUrl = new URL(baseURL);
76
+ const keyOrigin = enclaveURL ? new URL(enclaveURL).origin : baseUrl.origin;
77
+ transportPromise = getTransportForOrigin(baseUrl.origin, keyOrigin);
78
+ }
79
+ return transportPromise;
80
+ };
102
81
  return (async (input, init) => {
103
82
  const normalized = normalizeEncryptedBodyRequestArgs(input, init);
104
83
  const targetUrl = new URL(normalized.url, baseURL);
105
- return encryptedBodyRequest(targetUrl.toString(), hpkePublicKey, normalized.init, enclaveURL);
84
+ // Get the dedicated transport instance for this fetch function
85
+ const transportInstance = await getOrCreateTransport();
86
+ return encryptedBodyRequest(targetUrl.toString(), hpkePublicKey, normalized.init, enclaveURL, transportInstance);
106
87
  });
107
88
  }
108
- // Private helper functions
109
- /**
110
- * Load the ESM-only `ehbp` module in both browsers and Node.js CommonJS tests.
111
- *
112
- * - Browsers/Next.js: use a standard dynamic import so bundlers can statically
113
- * include `ehbp` in the client bundle.
114
- * - Node.js (CJS tests/builds): avoid TypeScript transpiling import() to
115
- * require(), which throws ERR_REQUIRE_ESM. Instead, create a runtime
116
- * dynamic import via new Function so it remains a real import() call.
117
- */
118
- function getEhbpModule() {
119
- if (ehbpModuleOverride) {
120
- return Promise.resolve(ehbpModuleOverride);
121
- }
122
- if (!ehbpModulePromise) {
123
- if ((0, env_1.isRealBrowser)()) {
124
- // Let the bundler include the module in browser builds
125
- ehbpModulePromise = Promise.resolve().then(() => __importStar(require("ehbp")));
126
- }
127
- else {
128
- const dynamicImport = new Function("specifier", "return import(specifier);");
129
- ehbpModulePromise = dynamicImport("ehbp");
130
- }
131
- }
132
- return ehbpModulePromise;
133
- }
134
89
  async function getTransportForOrigin(origin, keyOrigin) {
135
- const { Identity, Transport } = await getEhbpModule();
136
- // Ensure secure browser context
137
90
  if (typeof globalThis !== 'undefined') {
138
91
  const isSecure = globalThis.isSecureContext !== false;
139
92
  const hasSubtle = !!(globalThis.crypto && globalThis.crypto.subtle);
@@ -142,18 +95,8 @@ async function getTransportForOrigin(origin, keyOrigin) {
142
95
  throw new Error(`EHBP requires a secure browser context: ${reason}`);
143
96
  }
144
97
  }
145
- const clientIdentity = await Identity.generate();
98
+ const clientIdentity = await ehbp_1.Identity.generate();
146
99
  const serverPublicKey = await getHPKEKey(keyOrigin);
147
100
  const requestHost = new URL(origin).host;
148
- return new Transport(clientIdentity, requestHost, serverPublicKey);
149
- }
150
- // Test utilities
151
- function __setEhbpModuleForTests(module) {
152
- ehbpModuleOverride = module;
153
- ehbpModulePromise = module ? Promise.resolve(module) : null;
154
- }
155
- function __resetEhbpModuleStateForTests() {
156
- ehbpModuleOverride = undefined;
157
- ehbpModulePromise = null;
158
- transport = null;
101
+ return new ehbp_1.Transport(clientIdentity, requestHost, serverPublicKey);
159
102
  }
@@ -2,8 +2,8 @@ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
2
2
  import { TINFOIL_CONFIG } from "./config";
3
3
  import { SecureClient } from "./secure-client";
4
4
  export async function createTinfoilAI(apiKey, options = {}) {
5
- const baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
6
- const enclaveURL = options.enclaveURL || TINFOIL_CONFIG.ENCLAVE_URL;
5
+ const baseURL = options.baseURL;
6
+ const enclaveURL = options.enclaveURL;
7
7
  const configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
8
8
  const secureClient = new SecureClient({
9
9
  baseURL,
@@ -11,9 +11,14 @@ export async function createTinfoilAI(apiKey, options = {}) {
11
11
  configRepo,
12
12
  });
13
13
  await secureClient.ready();
14
+ // Get the baseURL from SecureClient after initialization
15
+ const finalBaseURL = baseURL || secureClient.getBaseURL();
16
+ if (!finalBaseURL) {
17
+ throw new Error("Unable to determine baseURL for AI SDK provider");
18
+ }
14
19
  return createOpenAICompatible({
15
20
  name: "tinfoil",
16
- baseURL: baseURL.replace(/\/$/, ""),
21
+ baseURL: finalBaseURL,
17
22
  apiKey: apiKey,
18
23
  fetch: secureClient.fetch,
19
24
  });
@@ -3,18 +3,11 @@
3
3
  */
4
4
  export declare const TINFOIL_CONFIG: {
5
5
  /**
6
- * The full base URL for the inference API
6
+ * The GitHub repository for code attestation verification
7
7
  */
8
- readonly INFERENCE_BASE_URL: "https://inference.tinfoil.sh/v1/";
8
+ readonly INFERENCE_PROXY_REPO: "tinfoilsh/confidential-model-router";
9
9
  /**
10
- * The URL used to fetch the enclave server public key (via EHBP .well-known endpoint).
11
- * and the attestation (vial the attestation .well-known endpoint too).
12
- * Defaults to the same value as `INFERENCE_BASE_URL` so enclaveURL and baseURL share
13
- * the same default. Callers may override independently if key discovery is hosted elsewhere.
10
+ * The ATC (Attestation and Trust Center) API URL for fetching available routers
14
11
  */
15
- readonly ENCLAVE_URL: "https://inference.tinfoil.sh/v1/";
16
- /**
17
- * The GitHub repository for the confidential inference proxy
18
- */
19
- readonly INFERENCE_PROXY_REPO: "tinfoilsh/confidential-inference-proxy";
12
+ readonly ATC_API_URL: "https://atc.tinfoil.sh/routers";
20
13
  };
@@ -3,18 +3,11 @@
3
3
  */
4
4
  export const TINFOIL_CONFIG = {
5
5
  /**
6
- * The full base URL for the inference API
6
+ * The GitHub repository for code attestation verification
7
7
  */
8
- INFERENCE_BASE_URL: "https://inference.tinfoil.sh/v1/",
8
+ INFERENCE_PROXY_REPO: "tinfoilsh/confidential-model-router",
9
9
  /**
10
- * The URL used to fetch the enclave server public key (via EHBP .well-known endpoint).
11
- * and the attestation (vial the attestation .well-known endpoint too).
12
- * Defaults to the same value as `INFERENCE_BASE_URL` so enclaveURL and baseURL share
13
- * the same default. Callers may override independently if key discovery is hosted elsewhere.
10
+ * The ATC (Attestation and Trust Center) API URL for fetching available routers
14
11
  */
15
- ENCLAVE_URL: "https://inference.tinfoil.sh/v1/",
16
- /**
17
- * The GitHub repository for the confidential inference proxy
18
- */
19
- INFERENCE_PROXY_REPO: "tinfoilsh/confidential-inference-proxy",
12
+ ATC_API_URL: "https://atc.tinfoil.sh/routers",
20
13
  };
@@ -1,11 +1,9 @@
1
- type EhbpModule = typeof import("ehbp");
1
+ import type { Transport as EhbpTransport } from "ehbp";
2
2
  export declare function getHPKEKey(enclaveURL: string): Promise<CryptoKey>;
3
3
  export declare function normalizeEncryptedBodyRequestArgs(input: RequestInfo | URL, init?: RequestInit): {
4
4
  url: string;
5
5
  init?: RequestInit;
6
6
  };
7
- export declare function encryptedBodyRequest(input: RequestInfo | URL, hpkePublicKey: string, init?: RequestInit, enclaveURL?: string): Promise<Response>;
8
- export declare function createEncryptedBodyFetch(baseURL: string, hpkePublicKey: string, enclaveURL?: string): typeof fetch;
9
- export declare function __setEhbpModuleForTests(module: EhbpModule | undefined): void;
10
- export declare function __resetEhbpModuleStateForTests(): void;
11
- export {};
7
+ export declare function encryptedBodyRequest(input: RequestInfo | URL, hpkePublicKey?: string, init?: RequestInit, enclaveURL?: string, transportInstance?: EhbpTransport): Promise<Response>;
8
+ export declare function createEncryptedBodyFetch(baseURL: string, hpkePublicKey?: string, enclaveURL?: string): typeof fetch;
9
+ export declare function getTransportForOrigin(origin: string, keyOrigin: string): Promise<EhbpTransport>;
@@ -1,10 +1,6 @@
1
- import { isRealBrowser } from "./env";
2
- let transport = null;
3
- let ehbpModulePromise = null;
4
- let ehbpModuleOverride;
1
+ import { Identity, Transport, PROTOCOL } from "ehbp";
5
2
  // Public API
6
3
  export async function getHPKEKey(enclaveURL) {
7
- const { Identity, PROTOCOL } = await getEhbpModule();
8
4
  const url = new URL(enclaveURL);
9
5
  const keysURL = new URL(PROTOCOL.KEYS_PATH, enclaveURL);
10
6
  if (keysURL.protocol !== 'https:') {
@@ -42,57 +38,48 @@ export function normalizeEncryptedBodyRequestArgs(input, init) {
42
38
  init: { ...derivedInit, ...init },
43
39
  };
44
40
  }
45
- export async function encryptedBodyRequest(input, hpkePublicKey, init, enclaveURL) {
41
+ export async function encryptedBodyRequest(input, hpkePublicKey, init, enclaveURL, transportInstance) {
46
42
  const { url: requestUrl, init: requestInit } = normalizeEncryptedBodyRequestArgs(input, init);
47
- const u = new URL(requestUrl);
48
- const { origin } = u;
49
- const keyOrigin = enclaveURL ? new URL(enclaveURL).origin : origin;
50
- if (!transport) {
51
- transport = getTransportForOrigin(origin, keyOrigin);
43
+ let actualTransport;
44
+ if (transportInstance) {
45
+ // Use provided transport instance
46
+ actualTransport = transportInstance;
52
47
  }
53
- const transportInstance = await transport;
54
- const transportKeyHash = await transportInstance.getServerPublicKeyHex();
55
- if (transportKeyHash !== hpkePublicKey) {
56
- throw new Error(`HPKE public key mismatch. Expected: ${hpkePublicKey}, Got: ${transportKeyHash}`);
48
+ else {
49
+ // Create a new transport for this request
50
+ const u = new URL(requestUrl);
51
+ const { origin } = u;
52
+ const keyOrigin = enclaveURL ? new URL(enclaveURL).origin : origin;
53
+ actualTransport = await getTransportForOrigin(origin, keyOrigin);
57
54
  }
58
- return transportInstance.request(requestUrl, requestInit);
55
+ if (hpkePublicKey) {
56
+ const transportKeyHash = await actualTransport.getServerPublicKeyHex();
57
+ if (transportKeyHash !== hpkePublicKey) {
58
+ throw new Error(`HPKE public key mismatch. Expected: ${hpkePublicKey}, Got: ${transportKeyHash}`);
59
+ }
60
+ }
61
+ return actualTransport.request(requestUrl, requestInit);
59
62
  }
60
63
  export function createEncryptedBodyFetch(baseURL, hpkePublicKey, enclaveURL) {
64
+ // Create a dedicated transport instance for this fetch function
65
+ let transportPromise = null;
66
+ const getOrCreateTransport = async () => {
67
+ if (!transportPromise) {
68
+ const baseUrl = new URL(baseURL);
69
+ const keyOrigin = enclaveURL ? new URL(enclaveURL).origin : baseUrl.origin;
70
+ transportPromise = getTransportForOrigin(baseUrl.origin, keyOrigin);
71
+ }
72
+ return transportPromise;
73
+ };
61
74
  return (async (input, init) => {
62
75
  const normalized = normalizeEncryptedBodyRequestArgs(input, init);
63
76
  const targetUrl = new URL(normalized.url, baseURL);
64
- return encryptedBodyRequest(targetUrl.toString(), hpkePublicKey, normalized.init, enclaveURL);
77
+ // Get the dedicated transport instance for this fetch function
78
+ const transportInstance = await getOrCreateTransport();
79
+ return encryptedBodyRequest(targetUrl.toString(), hpkePublicKey, normalized.init, enclaveURL, transportInstance);
65
80
  });
66
81
  }
67
- // Private helper functions
68
- /**
69
- * Load the ESM-only `ehbp` module in both browsers and Node.js CommonJS tests.
70
- *
71
- * - Browsers/Next.js: use a standard dynamic import so bundlers can statically
72
- * include `ehbp` in the client bundle.
73
- * - Node.js (CJS tests/builds): avoid TypeScript transpiling import() to
74
- * require(), which throws ERR_REQUIRE_ESM. Instead, create a runtime
75
- * dynamic import via new Function so it remains a real import() call.
76
- */
77
- function getEhbpModule() {
78
- if (ehbpModuleOverride) {
79
- return Promise.resolve(ehbpModuleOverride);
80
- }
81
- if (!ehbpModulePromise) {
82
- if (isRealBrowser()) {
83
- // Let the bundler include the module in browser builds
84
- ehbpModulePromise = import("ehbp");
85
- }
86
- else {
87
- const dynamicImport = new Function("specifier", "return import(specifier);");
88
- ehbpModulePromise = dynamicImport("ehbp");
89
- }
90
- }
91
- return ehbpModulePromise;
92
- }
93
- async function getTransportForOrigin(origin, keyOrigin) {
94
- const { Identity, Transport } = await getEhbpModule();
95
- // Ensure secure browser context
82
+ export async function getTransportForOrigin(origin, keyOrigin) {
96
83
  if (typeof globalThis !== 'undefined') {
97
84
  const isSecure = globalThis.isSecureContext !== false;
98
85
  const hasSubtle = !!(globalThis.crypto && globalThis.crypto.subtle);
@@ -106,13 +93,3 @@ async function getTransportForOrigin(origin, keyOrigin) {
106
93
  const requestHost = new URL(origin).host;
107
94
  return new Transport(clientIdentity, requestHost, serverPublicKey);
108
95
  }
109
- // Test utilities
110
- export function __setEhbpModuleForTests(module) {
111
- ehbpModuleOverride = module;
112
- ehbpModulePromise = module ? Promise.resolve(module) : null;
113
- }
114
- export function __resetEhbpModuleStateForTests() {
115
- ehbpModuleOverride = undefined;
116
- ehbpModulePromise = null;
117
- transport = null;
118
- }
@@ -4,3 +4,4 @@ export * from "./verifier";
4
4
  export * from "./ai-sdk-provider";
5
5
  export * from "./config";
6
6
  export { SecureClient } from "./secure-client";
7
+ export { UnverifiedClient } from "./unverified-client";
@@ -5,3 +5,4 @@ export * from "./verifier";
5
5
  export * from "./ai-sdk-provider";
6
6
  export * from "./config";
7
7
  export { SecureClient } from "./secure-client";
8
+ export { UnverifiedClient } from "./unverified-client";
@@ -4,4 +4,6 @@ export * from "./verifier";
4
4
  export * from "./ai-sdk-provider";
5
5
  export * from "./config";
6
6
  export { SecureClient } from "./secure-client";
7
+ export { UnverifiedClient } from "./unverified-client";
8
+ export { fetchRouter } from "./router";
7
9
  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,8 @@ export * from "./verifier";
6
6
  export * from "./ai-sdk-provider";
7
7
  export * from "./config";
8
8
  export { SecureClient } from "./secure-client";
9
+ export { UnverifiedClient } from "./unverified-client";
10
+ export { fetchRouter } from "./router";
9
11
  // Re-export OpenAI utility types and classes that users might need
10
12
  // Using public exports from the main OpenAI package instead of deep imports
11
13
  export { toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";