tinfoil 0.8.0 → 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.
- 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 +685 -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 +725 -0
- package/package.json +50 -9
- package/dist/secure-client.d.ts +0 -31
- package/dist/secure-client.js +0 -153
package/dist/env.d.ts
ADDED
package/dist/env.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isRealBrowser = isRealBrowser;
|
|
4
|
+
/**
|
|
5
|
+
* Detects if the code is running in a real browser environment.
|
|
6
|
+
* Returns false for Node.js environments, even with WASM loaded.
|
|
7
|
+
*/
|
|
8
|
+
function isRealBrowser() {
|
|
9
|
+
if (typeof process !== "undefined" &&
|
|
10
|
+
process.versions &&
|
|
11
|
+
process.versions.node) {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
if (typeof window !== "undefined" && typeof window.document !== "undefined") {
|
|
15
|
+
if (typeof navigator !== "undefined" && navigator.userAgent) {
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function withMockedModules(mocks: Record<string, unknown>, modulesToReload: string[], run: () => Promise<void>): Promise<void>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import Module from "module";
|
|
2
|
+
const testRequire = Module.createRequire(__filename);
|
|
3
|
+
export async function withMockedModules(mocks, modulesToReload, run) {
|
|
4
|
+
const moduleAny = Module;
|
|
5
|
+
const originalLoad = moduleAny._load;
|
|
6
|
+
moduleAny._load = function (request, parent, isMain) {
|
|
7
|
+
if (Object.prototype.hasOwnProperty.call(mocks, request)) {
|
|
8
|
+
return mocks[request];
|
|
9
|
+
}
|
|
10
|
+
// eslint-disable-next-line prefer-rest-params
|
|
11
|
+
return originalLoad.apply(this, arguments);
|
|
12
|
+
};
|
|
13
|
+
const restoredCache = [];
|
|
14
|
+
for (const specifier of modulesToReload) {
|
|
15
|
+
try {
|
|
16
|
+
const resolved = testRequire.resolve(specifier);
|
|
17
|
+
restoredCache.push({ path: resolved, cached: require.cache[resolved] });
|
|
18
|
+
delete require.cache[resolved];
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// Module not yet cached; nothing to remove.
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
await run();
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
moduleAny._load = originalLoad;
|
|
29
|
+
for (const entry of restoredCache) {
|
|
30
|
+
if (entry.cached) {
|
|
31
|
+
require.cache[entry.path] = entry.cached;
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
delete require.cache[entry.path];
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -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,33 @@
|
|
|
1
|
+
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
2
|
+
import { TINFOIL_CONFIG } from "./config";
|
|
3
|
+
import { createEncryptedBodyFetch } from "./encrypted-body-fetch";
|
|
4
|
+
import { Verifier } from "./verifier";
|
|
5
|
+
import { isRealBrowser } from "./env";
|
|
6
|
+
export async function createTinfoilAI(apiKey, options = {}) {
|
|
7
|
+
const baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
|
|
8
|
+
const configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
|
|
9
|
+
assertHttpsUrl(baseURL, "Inference baseURL");
|
|
10
|
+
const verifier = new Verifier({ serverURL: baseURL, configRepo });
|
|
11
|
+
const attestationResponse = await verifier.verify();
|
|
12
|
+
const hpkePublicKey = attestationResponse.hpkePublicKey;
|
|
13
|
+
if (!hpkePublicKey) {
|
|
14
|
+
if (isRealBrowser()) {
|
|
15
|
+
throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
|
|
16
|
+
"Only HPKE-enabled enclaves can be used in browser environments.");
|
|
17
|
+
}
|
|
18
|
+
throw new Error("HPKE public key is required in browser environments");
|
|
19
|
+
}
|
|
20
|
+
const fetchFunction = createEncryptedBodyFetch(baseURL, hpkePublicKey);
|
|
21
|
+
return createOpenAICompatible({
|
|
22
|
+
name: "tinfoil",
|
|
23
|
+
baseURL: baseURL.replace(/\/$/, ""),
|
|
24
|
+
apiKey: apiKey,
|
|
25
|
+
fetch: fetchFunction,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function assertHttpsUrl(url, context) {
|
|
29
|
+
const parsed = new URL(url);
|
|
30
|
+
if (parsed.protocol !== "https:") {
|
|
31
|
+
throw new Error(`${context} must use HTTPS. Got: ${url}`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +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
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Creates an AI SDK provider with the specified API key.
|
|
9
|
+
*
|
|
10
|
+
* @param apiKey - The API key for the Tinfoil API
|
|
11
|
+
* @param options - Optional configuration options
|
|
12
|
+
* @returns A TinfoilAI instance
|
|
13
|
+
*/
|
|
14
|
+
export declare function createTinfoilAI(apiKey: string, options?: CreateTinfoilAIOptions): Promise<import("@ai-sdk/openai-compatible").OpenAICompatibleProvider<string, string, string, string>>;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
2
|
+
import { TINFOIL_CONFIG } from "./config";
|
|
3
|
+
import { createEncryptedBodyFetch } from "./encrypted-body-fetch";
|
|
4
|
+
import { Verifier } from "./verifier";
|
|
5
|
+
import { isRealBrowser } from "./env";
|
|
6
|
+
import https from "https";
|
|
7
|
+
import { checkServerIdentity as tlsCheckServerIdentity } from "tls";
|
|
8
|
+
import { X509Certificate, createHash } from "crypto";
|
|
9
|
+
import { Readable } from "stream";
|
|
10
|
+
/**
|
|
11
|
+
* Creates an AI SDK provider with the specified API key.
|
|
12
|
+
*
|
|
13
|
+
* @param apiKey - The API key for the Tinfoil API
|
|
14
|
+
* @param options - Optional configuration options
|
|
15
|
+
* @returns A TinfoilAI instance
|
|
16
|
+
*/
|
|
17
|
+
export async function createTinfoilAI(apiKey, options = {}) {
|
|
18
|
+
const baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
|
|
19
|
+
const configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
|
|
20
|
+
assertHttpsUrl(baseURL, "Inference baseURL");
|
|
21
|
+
// step 1: verify the enclave and extract the public keys
|
|
22
|
+
// from the attestation response
|
|
23
|
+
const verifier = new Verifier({ serverURL: baseURL, configRepo });
|
|
24
|
+
const attestationResponse = await verifier.verify();
|
|
25
|
+
const hpkePublicKey = attestationResponse.hpkePublicKey;
|
|
26
|
+
const tlsPublicKeyFingerprint = attestationResponse.tlsPublicKeyFingerprint;
|
|
27
|
+
// step 2: create the appropriate fetch function based on available keys
|
|
28
|
+
let fetchFunction;
|
|
29
|
+
if (hpkePublicKey) {
|
|
30
|
+
// HPKE available: use encrypted body fetch
|
|
31
|
+
fetchFunction = createEncryptedBodyFetch(baseURL, hpkePublicKey);
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
// HPKE not available: check if we're in a browser
|
|
35
|
+
if (isRealBrowser()) {
|
|
36
|
+
throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
|
|
37
|
+
"Only HPKE-enabled enclaves can be used in browser environments.");
|
|
38
|
+
}
|
|
39
|
+
// Node.js environment: fall back to TLS-only verification using pinned TLS fetch
|
|
40
|
+
if (!tlsPublicKeyFingerprint) {
|
|
41
|
+
throw new Error("Neither HPKE public key nor TLS public key fingerprint available for verification");
|
|
42
|
+
}
|
|
43
|
+
fetchFunction = createPinnedTlsFetch(tlsPublicKeyFingerprint);
|
|
44
|
+
}
|
|
45
|
+
// step 3: create the openai compatible provider
|
|
46
|
+
// that uses the appropriate fetch function
|
|
47
|
+
return createOpenAICompatible({
|
|
48
|
+
name: "tinfoil",
|
|
49
|
+
baseURL: baseURL.replace(/\/$/, ""),
|
|
50
|
+
apiKey: apiKey,
|
|
51
|
+
fetch: fetchFunction,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
function assertHttpsUrl(url, context) {
|
|
55
|
+
const parsed = new URL(url);
|
|
56
|
+
if (parsed.protocol !== "https:") {
|
|
57
|
+
throw new Error(`${context} must use HTTPS. Got: ${url}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function createPinnedTlsFetch(expectedFingerprintHex) {
|
|
61
|
+
return (async (input, init) => {
|
|
62
|
+
// Normalize URL
|
|
63
|
+
const makeURL = (value) => {
|
|
64
|
+
if (typeof value === "string")
|
|
65
|
+
return new URL(value);
|
|
66
|
+
if (value instanceof URL)
|
|
67
|
+
return value;
|
|
68
|
+
return new URL(value.url);
|
|
69
|
+
};
|
|
70
|
+
const url = makeURL(input);
|
|
71
|
+
if (url.protocol !== "https:") {
|
|
72
|
+
throw new Error(`HTTP connections are not allowed. Use HTTPS. URL: ${url.toString()}`);
|
|
73
|
+
}
|
|
74
|
+
// Gather method and headers
|
|
75
|
+
const method = (init?.method || input.method || "GET").toUpperCase();
|
|
76
|
+
const headers = new Headers(init?.headers || input?.headers || {});
|
|
77
|
+
const headerObj = {};
|
|
78
|
+
headers.forEach((v, k) => {
|
|
79
|
+
headerObj[k] = v;
|
|
80
|
+
});
|
|
81
|
+
// Resolve body
|
|
82
|
+
let body = init?.body;
|
|
83
|
+
if (!body && input instanceof Request) {
|
|
84
|
+
// If the original was a Request with a body, read it
|
|
85
|
+
try {
|
|
86
|
+
const buf = await input.arrayBuffer();
|
|
87
|
+
if (buf && buf.byteLength)
|
|
88
|
+
body = Buffer.from(buf);
|
|
89
|
+
}
|
|
90
|
+
catch { }
|
|
91
|
+
}
|
|
92
|
+
// Convert web streams to Node streams if needed
|
|
93
|
+
if (body && typeof body.getReader === "function") {
|
|
94
|
+
body = Readable.fromWeb(body);
|
|
95
|
+
}
|
|
96
|
+
if (body instanceof ArrayBuffer) {
|
|
97
|
+
body = Buffer.from(body);
|
|
98
|
+
}
|
|
99
|
+
if (ArrayBuffer.isView(body)) {
|
|
100
|
+
body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
|
|
101
|
+
}
|
|
102
|
+
const requestOptions = {
|
|
103
|
+
protocol: url.protocol,
|
|
104
|
+
hostname: url.hostname,
|
|
105
|
+
port: url.port ? Number(url.port) : 443,
|
|
106
|
+
path: `${url.pathname}${url.search}`,
|
|
107
|
+
method,
|
|
108
|
+
headers: headerObj,
|
|
109
|
+
checkServerIdentity: (host, cert) => {
|
|
110
|
+
const raw = cert.raw;
|
|
111
|
+
if (!raw) {
|
|
112
|
+
return new Error("Certificate raw bytes are unavailable for pinning");
|
|
113
|
+
}
|
|
114
|
+
const x509 = new X509Certificate(raw);
|
|
115
|
+
const publicKeyDer = x509.publicKey.export({ type: "spki", format: "der" });
|
|
116
|
+
const fp = createHash("sha256").update(publicKeyDer).digest("hex");
|
|
117
|
+
if (fp !== expectedFingerprintHex) {
|
|
118
|
+
return new Error(`Certificate public key fingerprint mismatch. Expected: ${expectedFingerprintHex}, Got: ${fp}`);
|
|
119
|
+
}
|
|
120
|
+
return tlsCheckServerIdentity(host, cert);
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
const { signal } = init || {};
|
|
124
|
+
const res = await new Promise((resolve, reject) => {
|
|
125
|
+
const req = https.request(requestOptions, resolve);
|
|
126
|
+
req.on("error", reject);
|
|
127
|
+
if (signal) {
|
|
128
|
+
if (signal.aborted) {
|
|
129
|
+
req.destroy(new Error("Request aborted"));
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
signal.addEventListener("abort", () => req.destroy(new Error("Request aborted")));
|
|
133
|
+
}
|
|
134
|
+
if (body === undefined || body === null) {
|
|
135
|
+
req.end();
|
|
136
|
+
}
|
|
137
|
+
else if (typeof body === "string" || Buffer.isBuffer(body) || ArrayBuffer.isView(body)) {
|
|
138
|
+
req.end(body);
|
|
139
|
+
}
|
|
140
|
+
else if (typeof body.pipe === "function") {
|
|
141
|
+
body.pipe(req);
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
// Fallback: try to serialize objects
|
|
145
|
+
req.end(String(body));
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
const responseHeaders = new Headers();
|
|
149
|
+
for (const [k, v] of Object.entries(res.headers)) {
|
|
150
|
+
if (Array.isArray(v)) {
|
|
151
|
+
v.forEach(item => responseHeaders.append(k, item));
|
|
152
|
+
}
|
|
153
|
+
else if (v != null) {
|
|
154
|
+
responseHeaders.set(k, String(v));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
// Convert Node stream to Web ReadableStream
|
|
158
|
+
const webStream = Readable.toWeb(res);
|
|
159
|
+
return new Response(webStream, {
|
|
160
|
+
status: res.statusCode || 0,
|
|
161
|
+
statusText: res.statusMessage || "",
|
|
162
|
+
headers: responseHeaders,
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
}
|
|
@@ -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 {};
|
|
@@ -0,0 +1,150 @@
|
|
|
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 { isRealBrowser } from "./env";
|
|
6
|
+
function createAsyncProxy(promise) {
|
|
7
|
+
return new Proxy({}, {
|
|
8
|
+
get(target, prop) {
|
|
9
|
+
return new Proxy(() => { }, {
|
|
10
|
+
get(_, nestedProp) {
|
|
11
|
+
return (...args) => promise.then((obj) => {
|
|
12
|
+
const value = obj[prop][nestedProp];
|
|
13
|
+
return typeof value === "function"
|
|
14
|
+
? value.apply(obj[prop], args)
|
|
15
|
+
: value;
|
|
16
|
+
});
|
|
17
|
+
},
|
|
18
|
+
apply(_, __, args) {
|
|
19
|
+
return promise.then((obj) => {
|
|
20
|
+
const value = obj[prop];
|
|
21
|
+
return typeof value === "function" ? value.apply(obj, args) : value;
|
|
22
|
+
});
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
export class TinfoilAI {
|
|
29
|
+
constructor(options = {}) {
|
|
30
|
+
const openAIOptions = { ...options };
|
|
31
|
+
// In browser builds, never read secrets from process.env to avoid
|
|
32
|
+
// leaking credentials into client bundles. Require explicit apiKey.
|
|
33
|
+
if (typeof options.apiKey === "string") {
|
|
34
|
+
openAIOptions.apiKey = options.apiKey;
|
|
35
|
+
}
|
|
36
|
+
this.apiKey = openAIOptions.apiKey;
|
|
37
|
+
this.baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
|
|
38
|
+
assertHttpsUrl(this.baseURL, "Inference baseURL");
|
|
39
|
+
this.configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
|
|
40
|
+
this.clientPromise = this.initClient(openAIOptions);
|
|
41
|
+
}
|
|
42
|
+
async ready() {
|
|
43
|
+
if (!this.readyPromise) {
|
|
44
|
+
this.readyPromise = (async () => {
|
|
45
|
+
this.client = await this.clientPromise;
|
|
46
|
+
})();
|
|
47
|
+
}
|
|
48
|
+
return this.readyPromise;
|
|
49
|
+
}
|
|
50
|
+
async initClient(options) {
|
|
51
|
+
return this.createOpenAIClient(options);
|
|
52
|
+
}
|
|
53
|
+
async createOpenAIClient(options = {}) {
|
|
54
|
+
const verifier = new Verifier({
|
|
55
|
+
serverURL: this.baseURL,
|
|
56
|
+
configRepo: this.configRepo,
|
|
57
|
+
});
|
|
58
|
+
try {
|
|
59
|
+
await verifier.verify();
|
|
60
|
+
this.verificationDocument = verifier.getVerificationDocument();
|
|
61
|
+
if (!this.verificationDocument) {
|
|
62
|
+
throw new Error("Verification document not available after successful verification");
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
throw new Error(`Failed to verify enclave: ${error}`);
|
|
67
|
+
}
|
|
68
|
+
const hpkePublicKey = this.verificationDocument.enclaveMeasurement.hpkePublicKey;
|
|
69
|
+
if (!hpkePublicKey) {
|
|
70
|
+
// In browsers we require HPKE; TLS pinning fallback is Node-only
|
|
71
|
+
if (isRealBrowser()) {
|
|
72
|
+
throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
|
|
73
|
+
"Only HPKE-enabled enclaves can be used in browser environments.");
|
|
74
|
+
}
|
|
75
|
+
throw new Error("HPKE public key is required in browser environments");
|
|
76
|
+
}
|
|
77
|
+
const fetchFunction = createEncryptedBodyFetch(this.baseURL, hpkePublicKey);
|
|
78
|
+
const clientOptions = {
|
|
79
|
+
...options,
|
|
80
|
+
baseURL: this.baseURL,
|
|
81
|
+
fetch: fetchFunction,
|
|
82
|
+
};
|
|
83
|
+
// In browser usage, OpenAI SDK typically needs dangerouslyAllowBrowser
|
|
84
|
+
clientOptions.dangerouslyAllowBrowser = true;
|
|
85
|
+
return new OpenAI(clientOptions);
|
|
86
|
+
}
|
|
87
|
+
async ensureReady() {
|
|
88
|
+
await this.ready();
|
|
89
|
+
return this.client;
|
|
90
|
+
}
|
|
91
|
+
async getVerificationDocument() {
|
|
92
|
+
await this.ready();
|
|
93
|
+
if (!this.verificationDocument) {
|
|
94
|
+
throw new Error("Verification document unavailable: client not verified yet");
|
|
95
|
+
}
|
|
96
|
+
return this.verificationDocument;
|
|
97
|
+
}
|
|
98
|
+
get chat() {
|
|
99
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.chat));
|
|
100
|
+
}
|
|
101
|
+
get files() {
|
|
102
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.files));
|
|
103
|
+
}
|
|
104
|
+
get fineTuning() {
|
|
105
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.fineTuning));
|
|
106
|
+
}
|
|
107
|
+
get images() {
|
|
108
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.images));
|
|
109
|
+
}
|
|
110
|
+
get audio() {
|
|
111
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.audio));
|
|
112
|
+
}
|
|
113
|
+
get responses() {
|
|
114
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.responses));
|
|
115
|
+
}
|
|
116
|
+
get embeddings() {
|
|
117
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.embeddings));
|
|
118
|
+
}
|
|
119
|
+
get models() {
|
|
120
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.models));
|
|
121
|
+
}
|
|
122
|
+
get moderations() {
|
|
123
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.moderations));
|
|
124
|
+
}
|
|
125
|
+
get beta() {
|
|
126
|
+
return createAsyncProxy(this.ensureReady().then((client) => client.beta));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
(function (TinfoilAI) {
|
|
130
|
+
TinfoilAI.Chat = OpenAI.Chat;
|
|
131
|
+
TinfoilAI.Audio = OpenAI.Audio;
|
|
132
|
+
TinfoilAI.Beta = OpenAI.Beta;
|
|
133
|
+
TinfoilAI.Batches = OpenAI.Batches;
|
|
134
|
+
TinfoilAI.Completions = OpenAI.Completions;
|
|
135
|
+
TinfoilAI.Embeddings = OpenAI.Embeddings;
|
|
136
|
+
TinfoilAI.Files = OpenAI.Files;
|
|
137
|
+
TinfoilAI.FineTuning = OpenAI.FineTuning;
|
|
138
|
+
TinfoilAI.Images = OpenAI.Images;
|
|
139
|
+
TinfoilAI.Models = OpenAI.Models;
|
|
140
|
+
TinfoilAI.Moderations = OpenAI.Moderations;
|
|
141
|
+
TinfoilAI.Responses = OpenAI.Responses;
|
|
142
|
+
TinfoilAI.Uploads = OpenAI.Uploads;
|
|
143
|
+
TinfoilAI.VectorStores = OpenAI.VectorStores;
|
|
144
|
+
})(TinfoilAI || (TinfoilAI = {}));
|
|
145
|
+
function assertHttpsUrl(url, context) {
|
|
146
|
+
const parsed = new URL(url);
|
|
147
|
+
if (parsed.protocol !== "https:") {
|
|
148
|
+
throw new Error(`${context} must use HTTPS. Got: ${url}`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
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
|
+
/**
|
|
5
|
+
* TinfoilAI is a wrapper around the OpenAI API client that adds additional
|
|
6
|
+
* security measures through enclave verification and an EHBP-secured transport.
|
|
7
|
+
*
|
|
8
|
+
* It provides:
|
|
9
|
+
* - Automatic verification of Tinfoil secure enclaves
|
|
10
|
+
* - EHBP-enforced transport security for each request
|
|
11
|
+
* - Type-safe access to OpenAI's chat completion APIs
|
|
12
|
+
*/
|
|
13
|
+
interface TinfoilAIOptions {
|
|
14
|
+
apiKey?: string;
|
|
15
|
+
/** Override the inference API base URL */
|
|
16
|
+
baseURL?: string;
|
|
17
|
+
/** Override the config GitHub repository */
|
|
18
|
+
configRepo?: string;
|
|
19
|
+
[key: string]: any;
|
|
20
|
+
}
|
|
21
|
+
export declare class TinfoilAI {
|
|
22
|
+
private client?;
|
|
23
|
+
private clientPromise;
|
|
24
|
+
private readyPromise?;
|
|
25
|
+
private configRepo?;
|
|
26
|
+
private verificationDocument?;
|
|
27
|
+
apiKey?: string;
|
|
28
|
+
baseURL?: string;
|
|
29
|
+
/**
|
|
30
|
+
* Creates a new TinfoilAI instance.
|
|
31
|
+
* @param options - Configuration options including apiKey and other OpenAI client options
|
|
32
|
+
*/
|
|
33
|
+
constructor(options?: TinfoilAIOptions);
|
|
34
|
+
/**
|
|
35
|
+
* Ensures the client is ready to use.
|
|
36
|
+
* @returns Promise that resolves when the client is initialized
|
|
37
|
+
*/
|
|
38
|
+
ready(): Promise<void>;
|
|
39
|
+
private initClient;
|
|
40
|
+
private createOpenAIClient;
|
|
41
|
+
/**
|
|
42
|
+
* Helper method to ensure the OpenAI client is initialized before use.
|
|
43
|
+
* Automatically calls ready() if needed.
|
|
44
|
+
* @returns The initialized OpenAI client
|
|
45
|
+
* @private
|
|
46
|
+
*/
|
|
47
|
+
private ensureReady;
|
|
48
|
+
/**
|
|
49
|
+
* Returns the full verification document produced during client initialization.
|
|
50
|
+
*/
|
|
51
|
+
getVerificationDocument(): Promise<VerificationDocument>;
|
|
52
|
+
/**
|
|
53
|
+
* Access to OpenAI's chat completions API for creating chat conversations.
|
|
54
|
+
* Automatically initializes the client if needed.
|
|
55
|
+
*/
|
|
56
|
+
get chat(): Chat;
|
|
57
|
+
/**
|
|
58
|
+
* Access to OpenAI's files API for managing files used with the API.
|
|
59
|
+
* Automatically initializes the client if needed.
|
|
60
|
+
*/
|
|
61
|
+
get files(): Files;
|
|
62
|
+
/**
|
|
63
|
+
* Access to OpenAI's fine-tuning API for creating and managing fine-tuned models.
|
|
64
|
+
* Automatically initializes the client if needed.
|
|
65
|
+
*/
|
|
66
|
+
get fineTuning(): FineTuning;
|
|
67
|
+
/**
|
|
68
|
+
* Access to OpenAI's image generation and editing API.
|
|
69
|
+
* Automatically initializes the client if needed.
|
|
70
|
+
*/
|
|
71
|
+
get images(): Images;
|
|
72
|
+
/**
|
|
73
|
+
* Access to OpenAI's audio API for speech-to-text and text-to-speech.
|
|
74
|
+
* Automatically initializes the client if needed.
|
|
75
|
+
*/
|
|
76
|
+
get audio(): Audio;
|
|
77
|
+
/**
|
|
78
|
+
* Access to the Responses API, supporting response creation, streaming, and parsing.
|
|
79
|
+
* Automatically initializes the client if needed.
|
|
80
|
+
*/
|
|
81
|
+
get responses(): Responses;
|
|
82
|
+
/**
|
|
83
|
+
* Access to OpenAI's embeddings API for creating vector embeddings of text.
|
|
84
|
+
* Automatically initializes the client if needed.
|
|
85
|
+
*/
|
|
86
|
+
get embeddings(): Embeddings;
|
|
87
|
+
/**
|
|
88
|
+
* Access to OpenAI's models API for listing and managing available models.
|
|
89
|
+
* Automatically initializes the client if needed.
|
|
90
|
+
*/
|
|
91
|
+
get models(): Models;
|
|
92
|
+
/**
|
|
93
|
+
* Access to OpenAI's content moderation API.
|
|
94
|
+
* Automatically initializes the client if needed.
|
|
95
|
+
*/
|
|
96
|
+
get moderations(): Moderations;
|
|
97
|
+
/**
|
|
98
|
+
* Access to OpenAI's beta features.
|
|
99
|
+
* Automatically initializes the client if needed.
|
|
100
|
+
*/
|
|
101
|
+
get beta(): Beta;
|
|
102
|
+
}
|
|
103
|
+
export declare namespace TinfoilAI {
|
|
104
|
+
export import Chat = OpenAI.Chat;
|
|
105
|
+
export import Audio = OpenAI.Audio;
|
|
106
|
+
export import Beta = OpenAI.Beta;
|
|
107
|
+
export import Batches = OpenAI.Batches;
|
|
108
|
+
export import Completions = OpenAI.Completions;
|
|
109
|
+
export import Embeddings = OpenAI.Embeddings;
|
|
110
|
+
export import Files = OpenAI.Files;
|
|
111
|
+
export import FineTuning = OpenAI.FineTuning;
|
|
112
|
+
export import Images = OpenAI.Images;
|
|
113
|
+
export import Models = OpenAI.Models;
|
|
114
|
+
export import Moderations = OpenAI.Moderations;
|
|
115
|
+
export import Responses = OpenAI.Responses;
|
|
116
|
+
export import Uploads = OpenAI.Uploads;
|
|
117
|
+
export import VectorStores = OpenAI.VectorStores;
|
|
118
|
+
}
|
|
119
|
+
export {};
|