tinfoil 0.8.0 → 0.8.2
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 +171 -8
- package/dist/__tests__/test-utils.d.ts +1 -0
- package/dist/__tests__/test-utils.js +44 -0
- package/dist/ai-sdk-provider.browser.d.ts +6 -0
- package/dist/ai-sdk-provider.browser.js +36 -0
- package/dist/ai-sdk-provider.d.ts +9 -1
- package/dist/ai-sdk-provider.js +154 -32
- package/dist/client.browser.d.ts +51 -0
- package/dist/client.browser.js +157 -0
- package/dist/client.d.ts +20 -4
- package/dist/client.js +175 -57
- package/dist/encrypted-body-fetch.d.ts +10 -0
- package/dist/encrypted-body-fetch.js +158 -0
- package/dist/env.d.ts +5 -0
- package/dist/env.js +20 -0
- package/dist/esm/__tests__/test-utils.d.ts +1 -0
- package/dist/esm/__tests__/test-utils.js +38 -0
- package/dist/esm/ai-sdk-provider.browser.d.ts +6 -0
- package/dist/esm/ai-sdk-provider.browser.js +33 -0
- package/dist/esm/ai-sdk-provider.d.ts +15 -0
- package/dist/esm/ai-sdk-provider.js +165 -0
- package/dist/esm/client.browser.d.ts +51 -0
- package/dist/esm/client.browser.js +150 -0
- package/dist/esm/client.d.ts +119 -0
- package/dist/esm/client.js +357 -0
- package/dist/esm/config.d.ts +13 -0
- package/dist/esm/config.js +13 -0
- package/dist/esm/encrypted-body-fetch.d.ts +10 -0
- package/dist/esm/encrypted-body-fetch.js +118 -0
- package/dist/esm/env.d.ts +5 -0
- package/dist/esm/env.js +17 -0
- package/dist/esm/index.browser.d.ts +6 -0
- package/dist/esm/index.browser.js +7 -0
- package/dist/esm/index.d.ts +7 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/verification-runner.d.ts +100 -0
- package/dist/esm/verification-runner.js +224 -0
- package/dist/esm/verifier.d.ts +120 -0
- package/dist/esm/verifier.js +686 -0
- package/dist/esm/wasm-exec.js +668 -0
- package/dist/index.browser.d.ts +6 -0
- package/dist/index.browser.js +26 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +3 -2
- package/dist/verification-runner.d.ts +100 -0
- package/dist/verification-runner.js +230 -0
- package/dist/verifier.d.ts +120 -0
- package/dist/verifier.js +726 -0
- package/package.json +50 -9
- package/dist/secure-client.d.ts +0 -31
- package/dist/secure-client.js +0 -153
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import OpenAI from "openai";
|
|
2
|
+
import { Verifier } from "./verifier";
|
|
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
|
+
import { isRealBrowser } from "./env";
|
|
14
|
+
/**
|
|
15
|
+
* Creates a proxy that allows property access and method calls on a Promise before it resolves.
|
|
16
|
+
* This enables a more ergonomic API where you can chain properties and methods without explicitly
|
|
17
|
+
* awaiting the promise first.
|
|
18
|
+
*
|
|
19
|
+
* @param promise - A Promise that will resolve to an object
|
|
20
|
+
* @returns A proxied version of the promised object that allows immediate property/method access
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* // Instead of:
|
|
24
|
+
* const client = await getClient();
|
|
25
|
+
* const result = await client.someProperty.someMethod();
|
|
26
|
+
*
|
|
27
|
+
* // You can write:
|
|
28
|
+
* const client = createAsyncProxy(getClient());
|
|
29
|
+
* const result = await client.someProperty.someMethod();
|
|
30
|
+
*
|
|
31
|
+
* @template T - The type of object that the promise resolves to
|
|
32
|
+
*/
|
|
33
|
+
function createAsyncProxy(promise) {
|
|
34
|
+
return new Proxy({}, {
|
|
35
|
+
get(target, prop) {
|
|
36
|
+
return new Proxy(() => { }, {
|
|
37
|
+
get(_, nestedProp) {
|
|
38
|
+
return (...args) => promise.then((obj) => {
|
|
39
|
+
const value = obj[prop][nestedProp];
|
|
40
|
+
return typeof value === "function"
|
|
41
|
+
? value.apply(obj[prop], args)
|
|
42
|
+
: value;
|
|
43
|
+
});
|
|
44
|
+
},
|
|
45
|
+
apply(_, __, args) {
|
|
46
|
+
return promise.then((obj) => {
|
|
47
|
+
const value = obj[prop];
|
|
48
|
+
return typeof value === "function" ? value.apply(obj, args) : value;
|
|
49
|
+
});
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
export class TinfoilAI {
|
|
56
|
+
/**
|
|
57
|
+
* Creates a new TinfoilAI instance.
|
|
58
|
+
* @param options - Configuration options including apiKey and other OpenAI client options
|
|
59
|
+
*/
|
|
60
|
+
constructor(options = {}) {
|
|
61
|
+
// Set apiKey from options or environment variable
|
|
62
|
+
const openAIOptions = { ...options };
|
|
63
|
+
if (options.apiKey || process.env.TINFOIL_API_KEY) {
|
|
64
|
+
openAIOptions.apiKey = options.apiKey || process.env.TINFOIL_API_KEY;
|
|
65
|
+
}
|
|
66
|
+
// Store properties for compatibility
|
|
67
|
+
this.apiKey = openAIOptions.apiKey;
|
|
68
|
+
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;
|
|
72
|
+
this.clientPromise = this.initClient(openAIOptions);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Ensures the client is ready to use.
|
|
76
|
+
* @returns Promise that resolves when the client is initialized
|
|
77
|
+
*/
|
|
78
|
+
async ready() {
|
|
79
|
+
if (!this.readyPromise) {
|
|
80
|
+
this.readyPromise = (async () => {
|
|
81
|
+
this.client = await this.clientPromise;
|
|
82
|
+
})();
|
|
83
|
+
}
|
|
84
|
+
return this.readyPromise;
|
|
85
|
+
}
|
|
86
|
+
async initClient(options) {
|
|
87
|
+
return this.createOpenAIClient(options);
|
|
88
|
+
}
|
|
89
|
+
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);
|
|
123
|
+
}
|
|
124
|
+
const clientOptions = {
|
|
125
|
+
...options,
|
|
126
|
+
baseURL: this.baseURL,
|
|
127
|
+
fetch: fetchFunction,
|
|
128
|
+
};
|
|
129
|
+
// Enable dangerouslyAllowBrowser in Node.js with WASM (which makes OpenAI SDK think we're in a browser)
|
|
130
|
+
// OR if explicitly set by the user (for legitimate browser usage like playgrounds)
|
|
131
|
+
if (!isRealBrowser() || options.dangerouslyAllowBrowser === true) {
|
|
132
|
+
clientOptions.dangerouslyAllowBrowser = true;
|
|
133
|
+
}
|
|
134
|
+
return new OpenAI(clientOptions);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Helper method to ensure the OpenAI client is initialized before use.
|
|
138
|
+
* Automatically calls ready() if needed.
|
|
139
|
+
* @returns The initialized OpenAI client
|
|
140
|
+
* @private
|
|
141
|
+
*/
|
|
142
|
+
async ensureReady() {
|
|
143
|
+
await this.ready();
|
|
144
|
+
// We can safely assert this now because ready() must have completed
|
|
145
|
+
return this.client;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Returns the full verification document produced during client initialization.
|
|
149
|
+
*/
|
|
150
|
+
async getVerificationDocument() {
|
|
151
|
+
await this.ready();
|
|
152
|
+
if (!this.verificationDocument) {
|
|
153
|
+
throw new Error("Verification document unavailable: client not verified yet");
|
|
154
|
+
}
|
|
155
|
+
return this.verificationDocument;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Access to OpenAI's chat completions API for creating chat conversations.
|
|
159
|
+
* Automatically initializes the client if needed.
|
|
160
|
+
*/
|
|
161
|
+
get chat() {
|
|
162
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.chat));
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Access to OpenAI's files API for managing files used with the API.
|
|
166
|
+
* Automatically initializes the client if needed.
|
|
167
|
+
*/
|
|
168
|
+
get files() {
|
|
169
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.files));
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Access to OpenAI's fine-tuning API for creating and managing fine-tuned models.
|
|
173
|
+
* Automatically initializes the client if needed.
|
|
174
|
+
*/
|
|
175
|
+
get fineTuning() {
|
|
176
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.fineTuning));
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Access to OpenAI's image generation and editing API.
|
|
180
|
+
* Automatically initializes the client if needed.
|
|
181
|
+
*/
|
|
182
|
+
get images() {
|
|
183
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.images));
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Access to OpenAI's audio API for speech-to-text and text-to-speech.
|
|
187
|
+
* Automatically initializes the client if needed.
|
|
188
|
+
*/
|
|
189
|
+
get audio() {
|
|
190
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.audio));
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Access to the Responses API, supporting response creation, streaming, and parsing.
|
|
194
|
+
* Automatically initializes the client if needed.
|
|
195
|
+
*/
|
|
196
|
+
get responses() {
|
|
197
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.responses));
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Access to OpenAI's embeddings API for creating vector embeddings of text.
|
|
201
|
+
* Automatically initializes the client if needed.
|
|
202
|
+
*/
|
|
203
|
+
get embeddings() {
|
|
204
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.embeddings));
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Access to OpenAI's models API for listing and managing available models.
|
|
208
|
+
* Automatically initializes the client if needed.
|
|
209
|
+
*/
|
|
210
|
+
get models() {
|
|
211
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.models));
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Access to OpenAI's content moderation API.
|
|
215
|
+
* Automatically initializes the client if needed.
|
|
216
|
+
*/
|
|
217
|
+
get moderations() {
|
|
218
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.moderations));
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Access to OpenAI's beta features.
|
|
222
|
+
* Automatically initializes the client if needed.
|
|
223
|
+
*/
|
|
224
|
+
get beta() {
|
|
225
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.beta));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
// Namespace declaration merge to add OpenAI types to TinfoilAI
|
|
229
|
+
(function (TinfoilAI) {
|
|
230
|
+
// Re-export all OpenAI namespace types
|
|
231
|
+
TinfoilAI.Chat = OpenAI.Chat;
|
|
232
|
+
TinfoilAI.Audio = OpenAI.Audio;
|
|
233
|
+
TinfoilAI.Beta = OpenAI.Beta;
|
|
234
|
+
TinfoilAI.Batches = OpenAI.Batches;
|
|
235
|
+
TinfoilAI.Completions = OpenAI.Completions;
|
|
236
|
+
TinfoilAI.Embeddings = OpenAI.Embeddings;
|
|
237
|
+
TinfoilAI.Files = OpenAI.Files;
|
|
238
|
+
TinfoilAI.FineTuning = OpenAI.FineTuning;
|
|
239
|
+
TinfoilAI.Images = OpenAI.Images;
|
|
240
|
+
TinfoilAI.Models = OpenAI.Models;
|
|
241
|
+
TinfoilAI.Moderations = OpenAI.Moderations;
|
|
242
|
+
TinfoilAI.Responses = OpenAI.Responses;
|
|
243
|
+
TinfoilAI.Uploads = OpenAI.Uploads;
|
|
244
|
+
TinfoilAI.VectorStores = OpenAI.VectorStores;
|
|
245
|
+
})(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
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration constants for the Tinfoil Node SDK
|
|
3
|
+
*/
|
|
4
|
+
export declare const TINFOIL_CONFIG: {
|
|
5
|
+
/**
|
|
6
|
+
* The full base URL for the inference API
|
|
7
|
+
*/
|
|
8
|
+
readonly INFERENCE_BASE_URL: "https://inference.tinfoil.sh/v1/";
|
|
9
|
+
/**
|
|
10
|
+
* The GitHub repository for the confidential inference proxy
|
|
11
|
+
*/
|
|
12
|
+
readonly INFERENCE_PROXY_REPO: "tinfoilsh/confidential-inference-proxy";
|
|
13
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration constants for the Tinfoil Node SDK
|
|
3
|
+
*/
|
|
4
|
+
export const TINFOIL_CONFIG = {
|
|
5
|
+
/**
|
|
6
|
+
* The full base URL for the inference API
|
|
7
|
+
*/
|
|
8
|
+
INFERENCE_BASE_URL: "https://inference.tinfoil.sh/v1/",
|
|
9
|
+
/**
|
|
10
|
+
* The GitHub repository for the confidential inference proxy
|
|
11
|
+
*/
|
|
12
|
+
INFERENCE_PROXY_REPO: "tinfoilsh/confidential-inference-proxy",
|
|
13
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
type EhbpModule = typeof import("ehbp");
|
|
2
|
+
export declare function normalizeEncryptedBodyRequestArgs(input: RequestInfo | URL, init?: RequestInit): {
|
|
3
|
+
url: string;
|
|
4
|
+
init?: RequestInit;
|
|
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;
|
|
8
|
+
export declare function __setEhbpModuleForTests(module: EhbpModule | undefined): void;
|
|
9
|
+
export declare function __resetEhbpModuleStateForTests(): void;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { isRealBrowser } from "./env";
|
|
2
|
+
const transportCache = new Map();
|
|
3
|
+
let ehbpModulePromise = null;
|
|
4
|
+
let ehbpModuleOverride;
|
|
5
|
+
// Public API
|
|
6
|
+
export function normalizeEncryptedBodyRequestArgs(input, init) {
|
|
7
|
+
if (typeof input === "string") {
|
|
8
|
+
return { url: input, init };
|
|
9
|
+
}
|
|
10
|
+
if (input instanceof URL) {
|
|
11
|
+
return { url: input.toString(), init };
|
|
12
|
+
}
|
|
13
|
+
const request = input;
|
|
14
|
+
const cloned = request.clone();
|
|
15
|
+
const derivedInit = {
|
|
16
|
+
method: cloned.method,
|
|
17
|
+
headers: new Headers(cloned.headers),
|
|
18
|
+
body: cloned.body ?? undefined,
|
|
19
|
+
signal: cloned.signal,
|
|
20
|
+
};
|
|
21
|
+
return {
|
|
22
|
+
url: cloned.url,
|
|
23
|
+
init: { ...derivedInit, ...init },
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export async function encryptedBodyRequest(input, hpkePublicKey, init) {
|
|
27
|
+
const { url: requestUrl, init: requestInit } = normalizeEncryptedBodyRequestArgs(input, init);
|
|
28
|
+
const u = new URL(requestUrl);
|
|
29
|
+
if (u.protocol !== 'https:') {
|
|
30
|
+
throw new Error(`HTTP connections are not allowed for EHBP. Use HTTPS. URL: ${requestUrl}`);
|
|
31
|
+
}
|
|
32
|
+
const { origin } = u;
|
|
33
|
+
const transport = await getTransportForOrigin(origin);
|
|
34
|
+
const serverPublicKey = await transport.getServerPublicKeyHex();
|
|
35
|
+
if (serverPublicKey !== hpkePublicKey) {
|
|
36
|
+
transportCache.delete(origin);
|
|
37
|
+
throw new Error(`HPKE public key mismatch: expected ${hpkePublicKey}, got ${serverPublicKey}`);
|
|
38
|
+
}
|
|
39
|
+
return transport.request(requestUrl, requestInit);
|
|
40
|
+
}
|
|
41
|
+
export function createEncryptedBodyFetch(baseURL, hpkePublicKey) {
|
|
42
|
+
return (async (input, init) => {
|
|
43
|
+
const base = new URL(baseURL);
|
|
44
|
+
if (base.protocol !== 'https:') {
|
|
45
|
+
throw new Error(`EHBP baseURL must use HTTPS. Got: ${baseURL}`);
|
|
46
|
+
}
|
|
47
|
+
const normalized = normalizeEncryptedBodyRequestArgs(input, init);
|
|
48
|
+
const targetUrl = new URL(normalized.url, baseURL);
|
|
49
|
+
return encryptedBodyRequest(targetUrl.toString(), hpkePublicKey, normalized.init);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
// Private helper functions
|
|
53
|
+
/**
|
|
54
|
+
* Load the ESM-only `ehbp` module in both browsers and Node.js CommonJS tests.
|
|
55
|
+
*
|
|
56
|
+
* - Browsers/Next.js: use a standard dynamic import so bundlers can statically
|
|
57
|
+
* include `ehbp` in the client bundle.
|
|
58
|
+
* - Node.js (CJS tests/builds): avoid TypeScript transpiling import() to
|
|
59
|
+
* require(), which throws ERR_REQUIRE_ESM. Instead, create a runtime
|
|
60
|
+
* dynamic import via new Function so it remains a real import() call.
|
|
61
|
+
*/
|
|
62
|
+
function getEhbpModule() {
|
|
63
|
+
if (ehbpModuleOverride) {
|
|
64
|
+
return Promise.resolve(ehbpModuleOverride);
|
|
65
|
+
}
|
|
66
|
+
if (!ehbpModulePromise) {
|
|
67
|
+
if (isRealBrowser()) {
|
|
68
|
+
// Let the bundler include the module in browser builds
|
|
69
|
+
ehbpModulePromise = import("ehbp");
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
const dynamicImport = new Function("specifier", "return import(specifier);");
|
|
73
|
+
ehbpModulePromise = dynamicImport("ehbp");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return ehbpModulePromise;
|
|
77
|
+
}
|
|
78
|
+
async function getTransportForOrigin(origin) {
|
|
79
|
+
const cached = transportCache.get(origin);
|
|
80
|
+
if (cached) {
|
|
81
|
+
return cached;
|
|
82
|
+
}
|
|
83
|
+
const transportPromise = (async () => {
|
|
84
|
+
const { Identity, createTransport } = await getEhbpModule();
|
|
85
|
+
const proto = new URL(origin).protocol;
|
|
86
|
+
if (proto !== 'https:') {
|
|
87
|
+
throw new Error(`EHBP requires HTTPS origin. Got: ${origin}`);
|
|
88
|
+
}
|
|
89
|
+
// Ensure we're in a secure context with WebCrypto Subtle available (required by EHBP)
|
|
90
|
+
if (typeof globalThis !== 'undefined') {
|
|
91
|
+
const isSecure = globalThis.isSecureContext !== false;
|
|
92
|
+
const hasSubtle = !!(globalThis.crypto && globalThis.crypto.subtle);
|
|
93
|
+
if (!isSecure || !hasSubtle) {
|
|
94
|
+
const reason = !isSecure
|
|
95
|
+
? 'insecure context (use HTTPS or localhost)'
|
|
96
|
+
: 'missing WebCrypto SubtleCrypto';
|
|
97
|
+
throw new Error(`EHBP requires a secure browser context: ${reason}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const clientIdentity = await Identity.generate();
|
|
101
|
+
return createTransport(origin, clientIdentity);
|
|
102
|
+
})().catch((error) => {
|
|
103
|
+
transportCache.delete(origin);
|
|
104
|
+
throw error;
|
|
105
|
+
});
|
|
106
|
+
transportCache.set(origin, transportPromise);
|
|
107
|
+
return transportPromise;
|
|
108
|
+
}
|
|
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
|
+
transportCache.clear();
|
|
118
|
+
}
|
package/dist/esm/env.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Detects if the code is running in a real browser environment.
|
|
3
|
+
* Returns false for Node.js environments, even with WASM loaded.
|
|
4
|
+
*/
|
|
5
|
+
export function isRealBrowser() {
|
|
6
|
+
if (typeof process !== "undefined" &&
|
|
7
|
+
process.versions &&
|
|
8
|
+
process.versions.node) {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
if (typeof window !== "undefined" && typeof window.document !== "undefined") {
|
|
12
|
+
if (typeof navigator !== "undefined" && navigator.userAgent) {
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Browser-safe entry point: avoids Node built-ins
|
|
2
|
+
export { TinfoilAI } from "./client.browser";
|
|
3
|
+
export { TinfoilAI as default } from "./client.browser";
|
|
4
|
+
export * from "./verifier";
|
|
5
|
+
export * from "./verification-runner";
|
|
6
|
+
export * from "./ai-sdk-provider.browser";
|
|
7
|
+
export * from "./config";
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { TinfoilAI } from "./client";
|
|
2
|
+
export { TinfoilAI as default } from "./client";
|
|
3
|
+
export * from "./verifier";
|
|
4
|
+
export * from "./verification-runner";
|
|
5
|
+
export * from "./ai-sdk-provider";
|
|
6
|
+
export * from "./config";
|
|
7
|
+
export { type Uploadable, toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Re-export the TinfoilAI class
|
|
2
|
+
export { TinfoilAI } from "./client";
|
|
3
|
+
export { TinfoilAI as default } from "./client";
|
|
4
|
+
// Export verifier and loader
|
|
5
|
+
export * from "./verifier";
|
|
6
|
+
export * from "./verification-runner";
|
|
7
|
+
export * from "./ai-sdk-provider";
|
|
8
|
+
export * from "./config";
|
|
9
|
+
// Re-export OpenAI utility types and classes that users might need
|
|
10
|
+
// Using public exports from the main OpenAI package instead of deep imports
|
|
11
|
+
export { toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { Verifier, suppressWasmLogs } from "./verifier";
|
|
2
|
+
import type { AttestationMeasurement } from "./verifier";
|
|
3
|
+
import { TINFOIL_CONFIG } from "./config";
|
|
4
|
+
/**
|
|
5
|
+
* Step status for verification progress
|
|
6
|
+
*/
|
|
7
|
+
export type StepStatus = "pending" | "loading" | "success" | "error";
|
|
8
|
+
/**
|
|
9
|
+
* State for individual verification steps
|
|
10
|
+
*/
|
|
11
|
+
export interface StepState {
|
|
12
|
+
status: StepStatus;
|
|
13
|
+
measurement?: AttestationMeasurement;
|
|
14
|
+
error?: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Runtime verification state with additional key information
|
|
18
|
+
*/
|
|
19
|
+
export interface RuntimeStepState extends StepState {
|
|
20
|
+
tlsPublicKeyFingerprint?: string;
|
|
21
|
+
hpkePublicKey?: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Final verification summary
|
|
25
|
+
*/
|
|
26
|
+
export interface VerificationSummary {
|
|
27
|
+
status: StepStatus;
|
|
28
|
+
securityVerified?: boolean;
|
|
29
|
+
error?: string;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Overall verification state
|
|
33
|
+
*/
|
|
34
|
+
export interface VerificationState {
|
|
35
|
+
releaseDigest: string;
|
|
36
|
+
runtime: RuntimeStepState;
|
|
37
|
+
code: StepState;
|
|
38
|
+
verification: VerificationSummary;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Verification result returned by runVerification
|
|
42
|
+
*/
|
|
43
|
+
export interface VerificationResult extends VerificationState {
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Options for runVerification method
|
|
47
|
+
*/
|
|
48
|
+
export interface RunVerificationOptions {
|
|
49
|
+
/** GitHub repository to verify. Defaults to TINFOIL_CONFIG.INFERENCE_PROXY_REPO */
|
|
50
|
+
configRepo?: string;
|
|
51
|
+
/** Enclave hostname to verify. Defaults to hostname from TINFOIL_CONFIG.INFERENCE_BASE_URL */
|
|
52
|
+
serverURL?: string;
|
|
53
|
+
/** Specific release digest to verify. If not provided, fetches latest release digest */
|
|
54
|
+
releaseDigest?: string;
|
|
55
|
+
/** Callback for receiving verification state updates */
|
|
56
|
+
onUpdate?: (state: VerificationState) => void;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Enhanced verifier with state management and subscription support
|
|
60
|
+
*/
|
|
61
|
+
export declare class VerifierWithState extends Verifier {
|
|
62
|
+
private state;
|
|
63
|
+
private subscribers;
|
|
64
|
+
private static runnerVerificationCache;
|
|
65
|
+
/**
|
|
66
|
+
* Clear the verification cache
|
|
67
|
+
*/
|
|
68
|
+
static clearVerificationCache(): void;
|
|
69
|
+
/**
|
|
70
|
+
* Subscribe to verification state updates
|
|
71
|
+
* @param subscriber - Callback function to receive state updates
|
|
72
|
+
* @returns Unsubscribe function
|
|
73
|
+
*/
|
|
74
|
+
subscribe(subscriber: (state: VerificationState) => void): () => void;
|
|
75
|
+
/**
|
|
76
|
+
* Update state and notify subscribers
|
|
77
|
+
*/
|
|
78
|
+
private updateState;
|
|
79
|
+
/**
|
|
80
|
+
* Update a specific step state
|
|
81
|
+
*/
|
|
82
|
+
private updateStepState;
|
|
83
|
+
/**
|
|
84
|
+
* Run full verification flow with state updates
|
|
85
|
+
* @param options - Verification options
|
|
86
|
+
* @returns Final verification result
|
|
87
|
+
*/
|
|
88
|
+
runVerification(options?: RunVerificationOptions): Promise<VerificationResult>;
|
|
89
|
+
private _runVerificationInternal;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Load and initialize a verifier instance with state management
|
|
93
|
+
* @returns Initialized verifier instance with state management
|
|
94
|
+
*/
|
|
95
|
+
export declare function loadVerifier(): Promise<VerifierWithState>;
|
|
96
|
+
export { suppressWasmLogs, TINFOIL_CONFIG };
|
|
97
|
+
/**
|
|
98
|
+
* Clear the verification cache
|
|
99
|
+
*/
|
|
100
|
+
export declare function clearVerificationCache(): void;
|