tinfoil 0.7.2 → 0.8.1

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 (51) hide show
  1. package/README.md +171 -8
  2. package/dist/__tests__/test-utils.d.ts +1 -0
  3. package/dist/__tests__/test-utils.js +44 -0
  4. package/dist/ai-sdk-provider.browser.d.ts +6 -0
  5. package/dist/ai-sdk-provider.browser.js +36 -0
  6. package/dist/ai-sdk-provider.d.ts +9 -1
  7. package/dist/ai-sdk-provider.js +154 -32
  8. package/dist/client.browser.d.ts +51 -0
  9. package/dist/client.browser.js +157 -0
  10. package/dist/client.d.ts +20 -4
  11. package/dist/client.js +175 -57
  12. package/dist/encrypted-body-fetch.d.ts +10 -0
  13. package/dist/encrypted-body-fetch.js +158 -0
  14. package/dist/env.d.ts +5 -0
  15. package/dist/env.js +20 -0
  16. package/dist/esm/__tests__/test-utils.d.ts +1 -0
  17. package/dist/esm/__tests__/test-utils.js +38 -0
  18. package/dist/esm/ai-sdk-provider.browser.d.ts +6 -0
  19. package/dist/esm/ai-sdk-provider.browser.js +33 -0
  20. package/dist/esm/ai-sdk-provider.d.ts +15 -0
  21. package/dist/esm/ai-sdk-provider.js +165 -0
  22. package/dist/esm/client.browser.d.ts +51 -0
  23. package/dist/esm/client.browser.js +150 -0
  24. package/dist/esm/client.d.ts +119 -0
  25. package/dist/esm/client.js +357 -0
  26. package/dist/esm/config.d.ts +13 -0
  27. package/dist/esm/config.js +13 -0
  28. package/dist/esm/encrypted-body-fetch.d.ts +10 -0
  29. package/dist/esm/encrypted-body-fetch.js +118 -0
  30. package/dist/esm/env.d.ts +5 -0
  31. package/dist/esm/env.js +17 -0
  32. package/dist/esm/index.browser.d.ts +6 -0
  33. package/dist/esm/index.browser.js +7 -0
  34. package/dist/esm/index.d.ts +7 -0
  35. package/dist/esm/index.js +11 -0
  36. package/dist/esm/verification-runner.d.ts +100 -0
  37. package/dist/esm/verification-runner.js +224 -0
  38. package/dist/esm/verifier.d.ts +120 -0
  39. package/dist/esm/verifier.js +685 -0
  40. package/dist/esm/wasm-exec.js +668 -0
  41. package/dist/index.browser.d.ts +6 -0
  42. package/dist/index.browser.js +26 -0
  43. package/dist/index.d.ts +2 -1
  44. package/dist/index.js +3 -2
  45. package/dist/verification-runner.d.ts +100 -0
  46. package/dist/verification-runner.js +230 -0
  47. package/dist/verifier.d.ts +120 -0
  48. package/dist/verifier.js +725 -0
  49. package/package.json +52 -8
  50. package/dist/secure-client.d.ts +0 -31
  51. package/dist/secure-client.js +0 -153
package/README.md CHANGED
@@ -3,7 +3,7 @@
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 certificate fingerprints when using Tinfoil inference.
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).
7
7
 
8
8
  ## Installation
9
9
 
@@ -11,6 +11,10 @@ A Node.js wrapper around the OpenAI client that verifies enclave attestation and
11
11
  npm install tinfoil
12
12
  ```
13
13
 
14
+ ## Requirements
15
+
16
+ Node 20+.
17
+
14
18
  ## Quick Start
15
19
 
16
20
  ```typescript
@@ -27,9 +31,166 @@ const completion = await client.chat.completions.create({
27
31
  });
28
32
  ```
29
33
 
34
+ ## Browser Support
35
+
36
+ The SDK supports browser environments. This allows you to use the secure enclave-backed OpenAI API directly from web applications.
37
+
38
+ ### ⚠️ Security Warning
39
+
40
+ Using API keys directly in the browser exposes them to anyone who can view your page source.
41
+ For production applications, always use a backend server to handle API keys.
42
+
43
+ ### Browser Usage
44
+
45
+ ```javascript
46
+ import { TinfoilAI } from 'tinfoil';
47
+
48
+ const client = new TinfoilAI({
49
+ apiKey: 'your-api-key',
50
+ dangerouslyAllowBrowser: true // Required for browser usage
51
+ });
52
+
53
+ // Optional: pre-initialize; you can also call APIs directly
54
+ await client.ready();
55
+
56
+ const completion = await client.chat.completions.create({
57
+ model: 'llama-free',
58
+ messages: [{ role: 'user', content: 'Hello!' }]
59
+ });
60
+ ```
61
+
62
+ ### Browser Requirements
63
+
64
+ - Modern browsers with ES2020 support
65
+ - WebAssembly support for enclave verification
66
+ - Secure context (HTTPS or localhost) with WebCrypto SubtleCrypto (required by EHBP)
67
+
68
+
69
+ ## Verification helpers
70
+
71
+ 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).
72
+
73
+ The verification functionality is split into two modules:
74
+ - `verifier.ts`: Core verification logic with low-level attestation methods
75
+ - `verification-runner.ts`: Higher-level orchestration with state management and subscriptions
76
+
77
+ ### Core Verifier API
78
+
79
+ ```typescript
80
+ import { Verifier } from "tinfoil";
81
+
82
+ const verifier = new Verifier();
83
+
84
+ // Perform runtime attestation
85
+ const runtime = await verifier.verifyEnclave("enclave.host.com");
86
+ // Returns: { measurement: AttestationMeasurement, tlsPublicKeyFingerprint: string, hpkePublicKey: string }
87
+
88
+ // Perform code attestation
89
+ const code = await verifier.verifyCode("tinfoilsh/repo", "digest-hash");
90
+ // Returns: { measurement: AttestationMeasurement }
91
+
92
+ // Fetch latest digest from GitHub releases
93
+ const digest = await verifier.fetchLatestDigest("tinfoilsh/repo");
94
+ ```
95
+
96
+ ### High-level Orchestration API
97
+
98
+ - `loadVerifier()` boots the verifier with state management and returns an enhanced client.
99
+ - `client.subscribe(callback)` subscribes to real-time verification state updates.
100
+ - `client.runVerification({ configRepo?, serverURL?, releaseDigest?, onUpdate? })` orchestrates the full flow and returns a structured result with step statuses and a comparison outcome. Both `configRepo` and `serverURL` default to values from `TINFOIL_CONFIG`.
101
+
102
+ ### End-to-end orchestration
103
+
104
+ ```typescript
105
+ import { loadVerifier, TINFOIL_CONFIG } from "tinfoil";
106
+
107
+ const verifier = await loadVerifier();
108
+
109
+ const result = await verifier.runVerification({
110
+ onUpdate: (state) => {
111
+ // Receive stepwise updates: pending -> loading -> success/error
112
+ // Useful for logging or progress indicators
113
+ console.log("verification update:", state);
114
+ },
115
+ // Optional: override defaults if needed
116
+ // configRepo: "tinfoilsh/confidential-inference-proxy",
117
+ // serverURL: "https://inference.tinfoil.sh",
118
+ // releaseDigest: "<specific-release-sha256>",
119
+ });
120
+
121
+ if (result.verification.status === "success" && result.verification.securityVerified) {
122
+ console.log("Measurements match. Digest:", result.releaseDigest);
123
+ } else {
124
+ console.error("Verification failed:", result);
125
+ }
126
+ ```
127
+
128
+ `runVerification` returns:
129
+
130
+ ```typescript
131
+ type VerificationResult = {
132
+ code: { status: StepStatus; measurement?: AttestationMeasurement; error?: string };
133
+ runtime: {
134
+ status: StepStatus;
135
+ measurement?: AttestationMeasurement;
136
+ tlsPublicKeyFingerprint?: string;
137
+ hpkePublicKey?: string;
138
+ error?: string;
139
+ };
140
+ verification: { status: StepStatus; securityVerified?: boolean; error?: string };
141
+ releaseDigest: string;
142
+ };
143
+ ```
144
+
145
+ ### Subscribe to state updates
146
+
147
+ ```typescript
148
+ const verifier = await loadVerifier();
149
+ const unsubscribe = verifier.subscribe((state) => {
150
+ console.log("state:", state);
151
+ });
152
+
153
+ // Run verification with default config (recommended)
154
+ await verifier.runVerification();
155
+
156
+ // Or override specific parameters if needed
157
+ // await verifier.runVerification({
158
+ // configRepo: "tinfoilsh/confidential-inference-proxy",
159
+ // serverURL: "https://inference.tinfoil.sh",
160
+ // releaseDigest: "<specific-release-sha256>",
161
+ // });
162
+
163
+ unsubscribe();
164
+ ```
165
+
166
+ ## Testing
167
+
168
+ The project includes both unit tests and integration tests:
169
+
170
+ ### Running Unit Tests
171
+
172
+ ```bash
173
+ npm test
174
+ ```
175
+
176
+ This runs the test suite with unit tests and mocked components. These tests don't require network access and run quickly.
177
+
178
+ ### Running Integration Tests
179
+
180
+ ```bash
181
+ RUN_TINFOIL_INTEGRATION=true npm test
182
+ ```
183
+
184
+ This runs the full test suite including integration tests that:
185
+ - Make actual network requests to Tinfoil services
186
+ - Perform real enclave attestation verification
187
+ - Test end-to-end functionality with live services
188
+
189
+ Integration tests are skipped by default to keep the test suite fast and avoid network dependencies during development.
190
+
30
191
  ## Running the Chat Example
31
192
 
32
- To run the streaming chat example:
193
+ The chat example demonstrates both streaming chat completions and real-time attestation verification with a visual progress UI.
33
194
 
34
195
  1. Clone the repository
35
196
 
@@ -43,6 +204,8 @@ npm install
43
204
 
44
205
  ```bash
45
206
  TINFOIL_API_KEY=<YOUR_API_KEY>
207
+ # Optional: Enable WASM debug logs
208
+ # TINFOIL_ENABLE_WASM_LOGS=true
46
209
  ```
47
210
 
48
211
  4. Run the example:
@@ -52,15 +215,15 @@ cd examples/chat
52
215
  npx ts-node main.ts
53
216
  ```
54
217
 
55
- The example demonstrates streaming chat completions with the Tinfoil API wrapper.
56
-
57
- ## Runtime Support
58
-
59
- Supports Node.js 18+, Deno, Bun, Cloudflare Workers, and more. Browser usage is disabled by default for security. See [OpenAI Node.js client](https://github.com/openai/openai-node) for complete runtime compatibility.
218
+ The example will:
219
+ - Display a real-time verification progress showing each attestation step
220
+ - Verify the enclave's runtime and code measurements
221
+ - Compare measurements using platform-specific logic
222
+ - Stream chat completions through the verified secure channel
60
223
 
61
224
  ## API Documentation
62
225
 
63
- This library is a drop-in replacement for the official OpenAI Node.js client that can be used with Tinfoil. All methods and types are identical. See the [OpenAI client](https://github.com/openai/openai-node) for complete API usage and documentation.
226
+ This library mirrors the official OpenAI Node.js client for common endpoints (e.g., chat, images, embeddings) and types, and is designed to feel familiar. Some less commonly used surfaces may not be fully covered. See the [OpenAI client](https://github.com/openai/openai-node) for complete API usage and documentation.
64
227
 
65
228
  ## Reporting Vulnerabilities
66
229
 
@@ -0,0 +1 @@
1
+ export declare function withMockedModules(mocks: Record<string, unknown>, modulesToReload: string[], run: () => Promise<void>): Promise<void>;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.withMockedModules = withMockedModules;
7
+ const module_1 = __importDefault(require("module"));
8
+ const testRequire = module_1.default.createRequire(__filename);
9
+ async function withMockedModules(mocks, modulesToReload, run) {
10
+ const moduleAny = module_1.default;
11
+ const originalLoad = moduleAny._load;
12
+ moduleAny._load = function (request, parent, isMain) {
13
+ if (Object.prototype.hasOwnProperty.call(mocks, request)) {
14
+ return mocks[request];
15
+ }
16
+ // eslint-disable-next-line prefer-rest-params
17
+ return originalLoad.apply(this, arguments);
18
+ };
19
+ const restoredCache = [];
20
+ for (const specifier of modulesToReload) {
21
+ try {
22
+ const resolved = testRequire.resolve(specifier);
23
+ restoredCache.push({ path: resolved, cached: require.cache[resolved] });
24
+ delete require.cache[resolved];
25
+ }
26
+ catch {
27
+ // Module not yet cached; nothing to remove.
28
+ }
29
+ }
30
+ try {
31
+ await run();
32
+ }
33
+ finally {
34
+ moduleAny._load = originalLoad;
35
+ for (const entry of restoredCache) {
36
+ if (entry.cached) {
37
+ require.cache[entry.path] = entry.cached;
38
+ }
39
+ else {
40
+ delete require.cache[entry.path];
41
+ }
42
+ }
43
+ }
44
+ }
@@ -0,0 +1,6 @@
1
+ interface CreateTinfoilAIOptions {
2
+ baseURL?: string;
3
+ configRepo?: string;
4
+ }
5
+ export declare function createTinfoilAI(apiKey: string, options?: CreateTinfoilAIOptions): Promise<import("@ai-sdk/openai-compatible").OpenAICompatibleProvider<string, string, string, string>>;
6
+ export {};
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createTinfoilAI = createTinfoilAI;
4
+ const openai_compatible_1 = require("@ai-sdk/openai-compatible");
5
+ const config_1 = require("./config");
6
+ const encrypted_body_fetch_1 = require("./encrypted-body-fetch");
7
+ const verifier_1 = require("./verifier");
8
+ const env_1 = require("./env");
9
+ async function createTinfoilAI(apiKey, options = {}) {
10
+ const baseURL = options.baseURL || config_1.TINFOIL_CONFIG.INFERENCE_BASE_URL;
11
+ const configRepo = options.configRepo || config_1.TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
12
+ assertHttpsUrl(baseURL, "Inference baseURL");
13
+ const verifier = new verifier_1.Verifier({ serverURL: baseURL, configRepo });
14
+ const attestationResponse = await verifier.verify();
15
+ const hpkePublicKey = attestationResponse.hpkePublicKey;
16
+ if (!hpkePublicKey) {
17
+ if ((0, env_1.isRealBrowser)()) {
18
+ throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
19
+ "Only HPKE-enabled enclaves can be used in browser environments.");
20
+ }
21
+ throw new Error("HPKE public key is required in browser environments");
22
+ }
23
+ const fetchFunction = (0, encrypted_body_fetch_1.createEncryptedBodyFetch)(baseURL, hpkePublicKey);
24
+ return (0, openai_compatible_1.createOpenAICompatible)({
25
+ name: "tinfoil",
26
+ baseURL: baseURL.replace(/\/$/, ""),
27
+ apiKey: apiKey,
28
+ fetch: fetchFunction,
29
+ });
30
+ }
31
+ function assertHttpsUrl(url, context) {
32
+ const parsed = new URL(url);
33
+ if (parsed.protocol !== "https:") {
34
+ throw new Error(`${context} must use HTTPS. Got: ${url}`);
35
+ }
36
+ }
@@ -1,7 +1,15 @@
1
+ interface CreateTinfoilAIOptions {
2
+ /** Override the inference API base URL */
3
+ baseURL?: string;
4
+ /** Override the config GitHub repository */
5
+ configRepo?: string;
6
+ }
1
7
  /**
2
8
  * Creates an AI SDK provider with the specified API key.
3
9
  *
4
10
  * @param apiKey - The API key for the Tinfoil API
11
+ * @param options - Optional configuration options
5
12
  * @returns A TinfoilAI instance
6
13
  */
7
- export declare function createTinfoilAI(apiKey: string): Promise<import("@ai-sdk/openai-compatible").OpenAICompatibleProvider<string, string, string, string>>;
14
+ export declare function createTinfoilAI(apiKey: string, options?: CreateTinfoilAIOptions): Promise<import("@ai-sdk/openai-compatible").OpenAICompatibleProvider<string, string, string, string>>;
15
+ export {};
@@ -1,49 +1,171 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.createTinfoilAI = createTinfoilAI;
4
7
  const openai_compatible_1 = require("@ai-sdk/openai-compatible");
5
- const secure_client_1 = require("./secure-client");
6
8
  const config_1 = require("./config");
7
- const undici_1 = require("undici");
8
- const node_tls_1 = require("node:tls");
9
- const node_crypto_1 = require("node:crypto");
9
+ const encrypted_body_fetch_1 = require("./encrypted-body-fetch");
10
+ const verifier_1 = require("./verifier");
11
+ const env_1 = require("./env");
12
+ const https_1 = __importDefault(require("https"));
13
+ const tls_1 = require("tls");
14
+ const crypto_1 = require("crypto");
15
+ const stream_1 = require("stream");
10
16
  /**
11
17
  * Creates an AI SDK provider with the specified API key.
12
18
  *
13
19
  * @param apiKey - The API key for the Tinfoil API
20
+ * @param options - Optional configuration options
14
21
  * @returns A TinfoilAI instance
15
22
  */
16
- async function createTinfoilAI(apiKey) {
17
- const sc = new secure_client_1.SecureClient();
18
- const groundTruth = await sc.verify();
19
- const connect = (0, undici_1.buildConnector)({
20
- checkServerIdentity: (host, cert) => {
21
- if (!cert.pubkey) {
22
- throw new Error("No public key available in certificate");
23
- }
24
- const x509 = new node_crypto_1.X509Certificate(cert.raw);
25
- const publicKeyDer = x509.publicKey.export({
26
- type: "spki",
27
- format: "der",
28
- });
29
- const pubKeyFP = (0, node_crypto_1.createHash)("sha256").update(publicKeyDer).digest("hex");
30
- if (pubKeyFP !== groundTruth.publicKeyFP) {
31
- throw new Error(`Certificate public key fingerprint mismatch. Expected: ${groundTruth.publicKeyFP}, Got: ${pubKeyFP}`);
32
- }
33
- return (0, node_tls_1.checkServerIdentity)(host, cert);
34
- },
35
- });
36
- const agent = new undici_1.Agent({ connect });
23
+ async function createTinfoilAI(apiKey, options = {}) {
24
+ const baseURL = options.baseURL || config_1.TINFOIL_CONFIG.INFERENCE_BASE_URL;
25
+ const configRepo = options.configRepo || config_1.TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
26
+ assertHttpsUrl(baseURL, "Inference baseURL");
27
+ // step 1: verify the enclave and extract the public keys
28
+ // from the attestation response
29
+ const verifier = new verifier_1.Verifier({ serverURL: baseURL, configRepo });
30
+ const attestationResponse = await verifier.verify();
31
+ const hpkePublicKey = attestationResponse.hpkePublicKey;
32
+ const tlsPublicKeyFingerprint = attestationResponse.tlsPublicKeyFingerprint;
33
+ // step 2: create the appropriate fetch function based on available keys
34
+ let fetchFunction;
35
+ if (hpkePublicKey) {
36
+ // HPKE available: use encrypted body fetch
37
+ fetchFunction = (0, encrypted_body_fetch_1.createEncryptedBodyFetch)(baseURL, hpkePublicKey);
38
+ }
39
+ else {
40
+ // HPKE not available: check if we're in a browser
41
+ if ((0, env_1.isRealBrowser)()) {
42
+ throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
43
+ "Only HPKE-enabled enclaves can be used in browser environments.");
44
+ }
45
+ // Node.js environment: fall back to TLS-only verification using pinned TLS fetch
46
+ if (!tlsPublicKeyFingerprint) {
47
+ throw new Error("Neither HPKE public key nor TLS public key fingerprint available for verification");
48
+ }
49
+ fetchFunction = createPinnedTlsFetch(tlsPublicKeyFingerprint);
50
+ }
51
+ // step 3: create the openai compatible provider
52
+ // that uses the appropriate fetch function
37
53
  return (0, openai_compatible_1.createOpenAICompatible)({
38
54
  name: "tinfoil",
39
- baseURL: config_1.TINFOIL_CONFIG.INFERENCE_BASE_URL.replace(/\/$/, ""),
55
+ baseURL: baseURL.replace(/\/$/, ""),
40
56
  apiKey: apiKey,
41
- fetch: (async (input, init) => {
42
- if (!init) {
43
- init = {};
57
+ fetch: fetchFunction,
58
+ });
59
+ }
60
+ function assertHttpsUrl(url, context) {
61
+ const parsed = new URL(url);
62
+ if (parsed.protocol !== "https:") {
63
+ throw new Error(`${context} must use HTTPS. Got: ${url}`);
64
+ }
65
+ }
66
+ function createPinnedTlsFetch(expectedFingerprintHex) {
67
+ return (async (input, init) => {
68
+ // Normalize URL
69
+ const makeURL = (value) => {
70
+ if (typeof value === "string")
71
+ return new URL(value);
72
+ if (value instanceof URL)
73
+ return value;
74
+ return new URL(value.url);
75
+ };
76
+ const url = makeURL(input);
77
+ if (url.protocol !== "https:") {
78
+ throw new Error(`HTTP connections are not allowed. Use HTTPS. URL: ${url.toString()}`);
79
+ }
80
+ // Gather method and headers
81
+ const method = (init?.method || input.method || "GET").toUpperCase();
82
+ const headers = new Headers(init?.headers || input?.headers || {});
83
+ const headerObj = {};
84
+ headers.forEach((v, k) => {
85
+ headerObj[k] = v;
86
+ });
87
+ // Resolve body
88
+ let body = init?.body;
89
+ if (!body && input instanceof Request) {
90
+ // If the original was a Request with a body, read it
91
+ try {
92
+ const buf = await input.arrayBuffer();
93
+ if (buf && buf.byteLength)
94
+ body = Buffer.from(buf);
95
+ }
96
+ catch { }
97
+ }
98
+ // Convert web streams to Node streams if needed
99
+ if (body && typeof body.getReader === "function") {
100
+ body = stream_1.Readable.fromWeb(body);
101
+ }
102
+ if (body instanceof ArrayBuffer) {
103
+ body = Buffer.from(body);
104
+ }
105
+ if (ArrayBuffer.isView(body)) {
106
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
107
+ }
108
+ const requestOptions = {
109
+ protocol: url.protocol,
110
+ hostname: url.hostname,
111
+ port: url.port ? Number(url.port) : 443,
112
+ path: `${url.pathname}${url.search}`,
113
+ method,
114
+ headers: headerObj,
115
+ checkServerIdentity: (host, cert) => {
116
+ const raw = cert.raw;
117
+ if (!raw) {
118
+ return new Error("Certificate raw bytes are unavailable for pinning");
119
+ }
120
+ const x509 = new crypto_1.X509Certificate(raw);
121
+ const publicKeyDer = x509.publicKey.export({ type: "spki", format: "der" });
122
+ const fp = (0, crypto_1.createHash)("sha256").update(publicKeyDer).digest("hex");
123
+ if (fp !== expectedFingerprintHex) {
124
+ return new Error(`Certificate public key fingerprint mismatch. Expected: ${expectedFingerprintHex}, Got: ${fp}`);
125
+ }
126
+ return (0, tls_1.checkServerIdentity)(host, cert);
127
+ },
128
+ };
129
+ const { signal } = init || {};
130
+ const res = await new Promise((resolve, reject) => {
131
+ const req = https_1.default.request(requestOptions, resolve);
132
+ req.on("error", reject);
133
+ if (signal) {
134
+ if (signal.aborted) {
135
+ req.destroy(new Error("Request aborted"));
136
+ return;
137
+ }
138
+ signal.addEventListener("abort", () => req.destroy(new Error("Request aborted")));
139
+ }
140
+ if (body === undefined || body === null) {
141
+ req.end();
142
+ }
143
+ else if (typeof body === "string" || Buffer.isBuffer(body) || ArrayBuffer.isView(body)) {
144
+ req.end(body);
145
+ }
146
+ else if (typeof body.pipe === "function") {
147
+ body.pipe(req);
148
+ }
149
+ else {
150
+ // Fallback: try to serialize objects
151
+ req.end(String(body));
152
+ }
153
+ });
154
+ const responseHeaders = new Headers();
155
+ for (const [k, v] of Object.entries(res.headers)) {
156
+ if (Array.isArray(v)) {
157
+ v.forEach(item => responseHeaders.append(k, item));
158
+ }
159
+ else if (v != null) {
160
+ responseHeaders.set(k, String(v));
44
161
  }
45
- init.dispatcher = agent;
46
- return await (0, undici_1.fetch)(input, init);
47
- }),
162
+ }
163
+ // Convert Node stream to Web ReadableStream
164
+ const webStream = stream_1.Readable.toWeb(res);
165
+ return new Response(webStream, {
166
+ status: res.statusCode || 0,
167
+ statusText: res.statusMessage || "",
168
+ headers: responseHeaders,
169
+ });
48
170
  });
49
171
  }
@@ -0,0 +1,51 @@
1
+ import OpenAI from "openai";
2
+ import type { Audio, Beta, Chat, Embeddings, Files, FineTuning, Images, Models, Moderations, Responses } from "openai/resources";
3
+ import type { VerificationDocument } from "./verifier";
4
+ interface TinfoilAIOptions {
5
+ apiKey?: string;
6
+ baseURL?: string;
7
+ configRepo?: string;
8
+ [key: string]: any;
9
+ }
10
+ export declare class TinfoilAI {
11
+ private client?;
12
+ private clientPromise;
13
+ private readyPromise?;
14
+ private configRepo?;
15
+ private verificationDocument?;
16
+ apiKey?: string;
17
+ baseURL?: string;
18
+ constructor(options?: TinfoilAIOptions);
19
+ ready(): Promise<void>;
20
+ private initClient;
21
+ private createOpenAIClient;
22
+ private ensureReady;
23
+ getVerificationDocument(): Promise<VerificationDocument>;
24
+ get chat(): Chat;
25
+ get files(): Files;
26
+ get fineTuning(): FineTuning;
27
+ get images(): Images;
28
+ get audio(): Audio;
29
+ get responses(): Responses;
30
+ get embeddings(): Embeddings;
31
+ get models(): Models;
32
+ get moderations(): Moderations;
33
+ get beta(): Beta;
34
+ }
35
+ export declare namespace TinfoilAI {
36
+ export import Chat = OpenAI.Chat;
37
+ export import Audio = OpenAI.Audio;
38
+ export import Beta = OpenAI.Beta;
39
+ export import Batches = OpenAI.Batches;
40
+ export import Completions = OpenAI.Completions;
41
+ export import Embeddings = OpenAI.Embeddings;
42
+ export import Files = OpenAI.Files;
43
+ export import FineTuning = OpenAI.FineTuning;
44
+ export import Images = OpenAI.Images;
45
+ export import Models = OpenAI.Models;
46
+ export import Moderations = OpenAI.Moderations;
47
+ export import Responses = OpenAI.Responses;
48
+ export import Uploads = OpenAI.Uploads;
49
+ export import VectorStores = OpenAI.VectorStores;
50
+ }
51
+ export {};