tinfoil 0.9.1 → 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
@@ -93,6 +93,40 @@ const code = await verifier.verifyCode("tinfoilsh/repo", "digest-hash");
93
93
  const digest = await verifier.fetchLatestDigest("tinfoilsh/repo");
94
94
  ```
95
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
+
96
130
  ## Testing
97
131
 
98
132
  The project includes both unit tests and integration tests:
@@ -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>;
7
+ export declare function encryptedBodyRequest(input: RequestInfo | URL, hpkePublicKey?: string, init?: RequestInit, enclaveURL?: string, transportInstance?: EhbpTransport): Promise<Response>;
8
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 {};
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,59 +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;
54
+ }
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);
93
61
  }
94
- const transportInstance = await transport;
95
62
  if (hpkePublicKey) {
96
- const transportKeyHash = await transportInstance.getServerPublicKeyHex();
63
+ const transportKeyHash = await actualTransport.getServerPublicKeyHex();
97
64
  if (transportKeyHash !== hpkePublicKey) {
98
65
  throw new Error(`HPKE public key mismatch. Expected: ${hpkePublicKey}, Got: ${transportKeyHash}`);
99
66
  }
100
67
  }
101
- return transportInstance.request(requestUrl, requestInit);
68
+ return actualTransport.request(requestUrl, requestInit);
102
69
  }
103
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
+ };
104
81
  return (async (input, init) => {
105
82
  const normalized = normalizeEncryptedBodyRequestArgs(input, init);
106
83
  const targetUrl = new URL(normalized.url, baseURL);
107
- 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);
108
87
  });
109
88
  }
110
- // Private helper functions
111
- /**
112
- * Load the ESM-only `ehbp` module in both browsers and Node.js CommonJS tests.
113
- *
114
- * - Browsers/Next.js: use a standard dynamic import so bundlers can statically
115
- * include `ehbp` in the client bundle.
116
- * - Node.js (CJS tests/builds): avoid TypeScript transpiling import() to
117
- * require(), which throws ERR_REQUIRE_ESM. Instead, create a runtime
118
- * dynamic import via new Function so it remains a real import() call.
119
- */
120
- function getEhbpModule() {
121
- if (ehbpModuleOverride) {
122
- return Promise.resolve(ehbpModuleOverride);
123
- }
124
- if (!ehbpModulePromise) {
125
- if ((0, env_1.isRealBrowser)()) {
126
- // Let the bundler include the module in browser builds
127
- ehbpModulePromise = Promise.resolve().then(() => __importStar(require("ehbp")));
128
- }
129
- else {
130
- const dynamicImport = new Function("specifier", "return import(specifier);");
131
- ehbpModulePromise = dynamicImport("ehbp");
132
- }
133
- }
134
- return ehbpModulePromise;
135
- }
136
89
  async function getTransportForOrigin(origin, keyOrigin) {
137
- const { Identity, Transport } = await getEhbpModule();
138
- // Ensure secure browser context
139
90
  if (typeof globalThis !== 'undefined') {
140
91
  const isSecure = globalThis.isSecureContext !== false;
141
92
  const hasSubtle = !!(globalThis.crypto && globalThis.crypto.subtle);
@@ -144,18 +95,8 @@ async function getTransportForOrigin(origin, keyOrigin) {
144
95
  throw new Error(`EHBP requires a secure browser context: ${reason}`);
145
96
  }
146
97
  }
147
- const clientIdentity = await Identity.generate();
98
+ const clientIdentity = await ehbp_1.Identity.generate();
148
99
  const serverPublicKey = await getHPKEKey(keyOrigin);
149
100
  const requestHost = new URL(origin).host;
150
- return new Transport(clientIdentity, requestHost, serverPublicKey);
151
- }
152
- // Test utilities
153
- function __setEhbpModuleForTests(module) {
154
- ehbpModuleOverride = module;
155
- ehbpModulePromise = module ? Promise.resolve(module) : null;
156
- }
157
- function __resetEhbpModuleStateForTests() {
158
- ehbpModuleOverride = undefined;
159
- ehbpModulePromise = null;
160
- transport = null;
101
+ return new ehbp_1.Transport(clientIdentity, requestHost, serverPublicKey);
161
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>;
7
+ export declare function encryptedBodyRequest(input: RequestInfo | URL, hpkePublicKey?: string, init?: RequestInit, enclaveURL?: string, transportInstance?: EhbpTransport): Promise<Response>;
8
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 {};
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,59 +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;
47
+ }
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);
52
54
  }
53
- const transportInstance = await transport;
54
55
  if (hpkePublicKey) {
55
- const transportKeyHash = await transportInstance.getServerPublicKeyHex();
56
+ const transportKeyHash = await actualTransport.getServerPublicKeyHex();
56
57
  if (transportKeyHash !== hpkePublicKey) {
57
58
  throw new Error(`HPKE public key mismatch. Expected: ${hpkePublicKey}, Got: ${transportKeyHash}`);
58
59
  }
59
60
  }
60
- return transportInstance.request(requestUrl, requestInit);
61
+ return actualTransport.request(requestUrl, requestInit);
61
62
  }
62
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
+ };
63
74
  return (async (input, init) => {
64
75
  const normalized = normalizeEncryptedBodyRequestArgs(input, init);
65
76
  const targetUrl = new URL(normalized.url, baseURL);
66
- 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);
67
80
  });
68
81
  }
69
- // Private helper functions
70
- /**
71
- * Load the ESM-only `ehbp` module in both browsers and Node.js CommonJS tests.
72
- *
73
- * - Browsers/Next.js: use a standard dynamic import so bundlers can statically
74
- * include `ehbp` in the client bundle.
75
- * - Node.js (CJS tests/builds): avoid TypeScript transpiling import() to
76
- * require(), which throws ERR_REQUIRE_ESM. Instead, create a runtime
77
- * dynamic import via new Function so it remains a real import() call.
78
- */
79
- function getEhbpModule() {
80
- if (ehbpModuleOverride) {
81
- return Promise.resolve(ehbpModuleOverride);
82
- }
83
- if (!ehbpModulePromise) {
84
- if (isRealBrowser()) {
85
- // Let the bundler include the module in browser builds
86
- ehbpModulePromise = import("ehbp");
87
- }
88
- else {
89
- const dynamicImport = new Function("specifier", "return import(specifier);");
90
- ehbpModulePromise = dynamicImport("ehbp");
91
- }
92
- }
93
- return ehbpModulePromise;
94
- }
95
- async function getTransportForOrigin(origin, keyOrigin) {
96
- const { Identity, Transport } = await getEhbpModule();
97
- // Ensure secure browser context
82
+ export async function getTransportForOrigin(origin, keyOrigin) {
98
83
  if (typeof globalThis !== 'undefined') {
99
84
  const isSecure = globalThis.isSecureContext !== false;
100
85
  const hasSubtle = !!(globalThis.crypto && globalThis.crypto.subtle);
@@ -108,13 +93,3 @@ async function getTransportForOrigin(origin, keyOrigin) {
108
93
  const requestHost = new URL(origin).host;
109
94
  return new Transport(clientIdentity, requestHost, serverPublicKey);
110
95
  }
111
- // Test utilities
112
- export function __setEhbpModuleForTests(module) {
113
- ehbpModuleOverride = module;
114
- ehbpModulePromise = module ? Promise.resolve(module) : null;
115
- }
116
- export function __resetEhbpModuleStateForTests() {
117
- ehbpModuleOverride = undefined;
118
- ehbpModulePromise = null;
119
- transport = null;
120
- }
@@ -5,4 +5,5 @@ export * from "./ai-sdk-provider";
5
5
  export * from "./config";
6
6
  export { SecureClient } from "./secure-client";
7
7
  export { UnverifiedClient } from "./unverified-client";
8
+ export { fetchRouter } from "./router";
8
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
@@ -7,6 +7,7 @@ export * from "./ai-sdk-provider";
7
7
  export * from "./config";
8
8
  export { SecureClient } from "./secure-client";
9
9
  export { UnverifiedClient } from "./unverified-client";
10
+ export { fetchRouter } from "./router";
10
11
  // Re-export OpenAI utility types and classes that users might need
11
12
  // Using public exports from the main OpenAI package instead of deep imports
12
13
  export { toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Router utilities for fetching available Tinfoil routers
3
+ */
4
+ /**
5
+ * Fetches the list of available routers from the ATC API
6
+ * and returns a randomly selected address.
7
+ *
8
+ * @returns Promise<string> A randomly selected router address
9
+ * @throws Error if no routers are found or if the request fails
10
+ */
11
+ export declare function fetchRouter(): Promise<string>;
@@ -0,0 +1,33 @@
1
+ import { TINFOIL_CONFIG } from "./config";
2
+ /**
3
+ * Router utilities for fetching available Tinfoil routers
4
+ */
5
+ /**
6
+ * Fetches the list of available routers from the ATC API
7
+ * and returns a randomly selected address.
8
+ *
9
+ * @returns Promise<string> A randomly selected router address
10
+ * @throws Error if no routers are found or if the request fails
11
+ */
12
+ export async function fetchRouter() {
13
+ const routersUrl = TINFOIL_CONFIG.ATC_API_URL;
14
+ try {
15
+ const response = await fetch(routersUrl);
16
+ if (!response.ok) {
17
+ throw new Error(`Failed to fetch routers: ${response.status} ${response.statusText}`);
18
+ }
19
+ const routers = await response.json();
20
+ if (!Array.isArray(routers) || routers.length === 0) {
21
+ throw new Error("No routers found in the response");
22
+ }
23
+ // Return a randomly selected router
24
+ const randomIndex = Math.floor(Math.random() * routers.length);
25
+ return routers[randomIndex];
26
+ }
27
+ catch (error) {
28
+ if (error instanceof Error) {
29
+ throw new Error(`Failed to fetch router: ${error.message}`);
30
+ }
31
+ throw new Error("Failed to fetch router: Unknown error");
32
+ }
33
+ }
@@ -8,13 +8,14 @@ export declare class SecureClient {
8
8
  private initPromise;
9
9
  private verificationDocument;
10
10
  private _fetch;
11
- private readonly baseURL?;
12
- private readonly enclaveURL?;
11
+ private baseURL?;
12
+ private enclaveURL?;
13
13
  private readonly configRepo?;
14
14
  constructor(options?: SecureClientOptions);
15
15
  ready(): Promise<void>;
16
16
  private initSecureClient;
17
17
  getVerificationDocument(): Promise<VerificationDocument>;
18
+ getBaseURL(): string | undefined;
18
19
  get fetch(): typeof fetch;
19
20
  }
20
21
  export {};