tinfoil 0.8.2 → 0.8.4
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 +3 -0
- package/dist/ai-sdk-provider.d.ts +1 -9
- package/dist/ai-sdk-provider.js +9 -157
- package/dist/client.browser.d.ts +3 -0
- package/dist/client.browser.js +13 -34
- package/dist/client.d.ts +4 -0
- package/dist/client.js +13 -159
- package/dist/config.d.ts +6 -0
- package/dist/config.js +6 -0
- package/dist/encrypted-body-fetch.d.ts +2 -2
- package/dist/encrypted-body-fetch.js +54 -16
- package/dist/esm/ai-sdk-provider.d.ts +1 -9
- package/dist/esm/ai-sdk-provider.js +9 -154
- package/dist/esm/client.browser.d.ts +3 -0
- package/dist/esm/client.browser.js +13 -34
- package/dist/esm/client.d.ts +4 -0
- package/dist/esm/client.js +13 -159
- package/dist/esm/config.d.ts +6 -0
- package/dist/esm/config.js +6 -0
- package/dist/esm/encrypted-body-fetch.d.ts +2 -2
- package/dist/esm/encrypted-body-fetch.js +54 -16
- package/dist/esm/index.browser.d.ts +2 -1
- package/dist/esm/index.browser.js +2 -1
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +1 -0
- package/dist/esm/pinned-tls-fetch.d.ts +1 -0
- package/dist/esm/pinned-tls-fetch.js +110 -0
- package/dist/esm/secure-client.browser.d.ts +20 -0
- package/dist/esm/secure-client.browser.js +57 -0
- package/dist/esm/secure-client.d.ts +20 -0
- package/dist/esm/secure-client.js +68 -0
- package/dist/esm/verification-runner.d.ts +0 -9
- package/dist/esm/verification-runner.js +1 -43
- package/dist/esm/verifier.d.ts +0 -2
- package/dist/esm/verifier.js +21 -52
- package/dist/index.browser.d.ts +2 -1
- package/dist/index.browser.js +2 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/pinned-tls-fetch.d.ts +1 -0
- package/dist/pinned-tls-fetch.js +116 -0
- package/dist/secure-client.browser.d.ts +20 -0
- package/dist/secure-client.browser.js +61 -0
- package/dist/secure-client.d.ts +20 -0
- package/dist/secure-client.js +72 -0
- package/dist/verification-runner.d.ts +0 -9
- package/dist/verification-runner.js +1 -44
- package/dist/verifier.d.ts +0 -2
- package/dist/verifier.js +21 -52
- package/package.json +7 -2
- package/dist/ai-sdk-provider.browser.d.ts +0 -6
- package/dist/ai-sdk-provider.browser.js +0 -36
- package/dist/esm/ai-sdk-provider.browser.d.ts +0 -6
- package/dist/esm/ai-sdk-provider.browser.js +0 -33
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isRealBrowser } from "./env";
|
|
2
2
|
const transportCache = new Map();
|
|
3
|
+
const compositeTransportCache = new Map();
|
|
3
4
|
let ehbpModulePromise = null;
|
|
4
5
|
let ehbpModuleOverride;
|
|
5
6
|
// Public API
|
|
@@ -23,30 +24,38 @@ export function normalizeEncryptedBodyRequestArgs(input, init) {
|
|
|
23
24
|
init: { ...derivedInit, ...init },
|
|
24
25
|
};
|
|
25
26
|
}
|
|
26
|
-
export async function encryptedBodyRequest(input, hpkePublicKey, init) {
|
|
27
|
+
export async function encryptedBodyRequest(input, hpkePublicKey, init, hpkeKeyURL) {
|
|
27
28
|
const { url: requestUrl, init: requestInit } = normalizeEncryptedBodyRequestArgs(input, init);
|
|
28
29
|
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
30
|
const { origin } = u;
|
|
33
|
-
|
|
31
|
+
// Determine which origin to fetch the HPKE key from (may be different from request origin)
|
|
32
|
+
const keyOrigin = hpkeKeyURL ? new URL(hpkeKeyURL).origin : origin;
|
|
33
|
+
// If key origin matches request origin, use the standard transport (fetches keys from origin)
|
|
34
|
+
// Otherwise, build a composite transport that routes to `origin` but uses the key fetched from `keyOrigin`.
|
|
35
|
+
const transport = keyOrigin === origin
|
|
36
|
+
? await getTransportForOrigin(origin)
|
|
37
|
+
: await getTransportForRequestOriginWithKeyFrom(origin, keyOrigin);
|
|
34
38
|
const serverPublicKey = await transport.getServerPublicKeyHex();
|
|
35
39
|
if (serverPublicKey !== hpkePublicKey) {
|
|
36
|
-
|
|
40
|
+
// Clear caches so the next attempt re-handshakes
|
|
41
|
+
if (keyOrigin === origin) {
|
|
42
|
+
transportCache.delete(origin);
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
const cacheKey = `${origin}::${keyOrigin}`;
|
|
46
|
+
compositeTransportCache.delete(cacheKey);
|
|
47
|
+
// Also clear the underlying key-origin cache to force re-fetch
|
|
48
|
+
transportCache.delete(keyOrigin);
|
|
49
|
+
}
|
|
37
50
|
throw new Error(`HPKE public key mismatch: expected ${hpkePublicKey}, got ${serverPublicKey}`);
|
|
38
51
|
}
|
|
39
52
|
return transport.request(requestUrl, requestInit);
|
|
40
53
|
}
|
|
41
|
-
export function createEncryptedBodyFetch(baseURL, hpkePublicKey) {
|
|
54
|
+
export function createEncryptedBodyFetch(baseURL, hpkePublicKey, hpkeKeyURL) {
|
|
42
55
|
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
56
|
const normalized = normalizeEncryptedBodyRequestArgs(input, init);
|
|
48
57
|
const targetUrl = new URL(normalized.url, baseURL);
|
|
49
|
-
return encryptedBodyRequest(targetUrl.toString(), hpkePublicKey, normalized.init);
|
|
58
|
+
return encryptedBodyRequest(targetUrl.toString(), hpkePublicKey, normalized.init, hpkeKeyURL);
|
|
50
59
|
});
|
|
51
60
|
}
|
|
52
61
|
// Private helper functions
|
|
@@ -82,10 +91,6 @@ async function getTransportForOrigin(origin) {
|
|
|
82
91
|
}
|
|
83
92
|
const transportPromise = (async () => {
|
|
84
93
|
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
94
|
// Ensure we're in a secure context with WebCrypto Subtle available (required by EHBP)
|
|
90
95
|
if (typeof globalThis !== 'undefined') {
|
|
91
96
|
const isSecure = globalThis.isSecureContext !== false;
|
|
@@ -106,6 +111,38 @@ async function getTransportForOrigin(origin) {
|
|
|
106
111
|
transportCache.set(origin, transportPromise);
|
|
107
112
|
return transportPromise;
|
|
108
113
|
}
|
|
114
|
+
async function getTransportForRequestOriginWithKeyFrom(origin, keyOrigin) {
|
|
115
|
+
const cacheKey = `${origin}::${keyOrigin}`;
|
|
116
|
+
const cached = compositeTransportCache.get(cacheKey);
|
|
117
|
+
if (cached) {
|
|
118
|
+
return cached;
|
|
119
|
+
}
|
|
120
|
+
const transportPromise = (async () => {
|
|
121
|
+
const { Identity, createTransport, Transport } = await getEhbpModule();
|
|
122
|
+
// Ensure secure browser context
|
|
123
|
+
if (typeof globalThis !== 'undefined') {
|
|
124
|
+
const isSecure = globalThis.isSecureContext !== false;
|
|
125
|
+
const hasSubtle = !!(globalThis.crypto && globalThis.crypto.subtle);
|
|
126
|
+
if (!isSecure || !hasSubtle) {
|
|
127
|
+
const reason = !isSecure ? 'insecure context (use HTTPS or localhost)' : 'missing WebCrypto SubtleCrypto';
|
|
128
|
+
throw new Error(`EHBP requires a secure browser context: ${reason}`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// Create a single client identity to use for both key discovery and requests
|
|
132
|
+
const clientIdentity = await Identity.generate();
|
|
133
|
+
// Fetch the server's HPKE public key from the dedicated key origin
|
|
134
|
+
const keyTransport = await createTransport(keyOrigin, clientIdentity);
|
|
135
|
+
// Reuse the discovered server public key but route to the request origin
|
|
136
|
+
const serverPublicKey = keyTransport.getServerPublicKey();
|
|
137
|
+
const requestHost = new URL(origin).host;
|
|
138
|
+
return new Transport(clientIdentity, requestHost, serverPublicKey);
|
|
139
|
+
})().catch((error) => {
|
|
140
|
+
compositeTransportCache.delete(cacheKey);
|
|
141
|
+
throw error;
|
|
142
|
+
});
|
|
143
|
+
compositeTransportCache.set(cacheKey, transportPromise);
|
|
144
|
+
return transportPromise;
|
|
145
|
+
}
|
|
109
146
|
// Test utilities
|
|
110
147
|
export function __setEhbpModuleForTests(module) {
|
|
111
148
|
ehbpModuleOverride = module;
|
|
@@ -115,4 +152,5 @@ export function __resetEhbpModuleStateForTests() {
|
|
|
115
152
|
ehbpModuleOverride = undefined;
|
|
116
153
|
ehbpModulePromise = null;
|
|
117
154
|
transportCache.clear();
|
|
155
|
+
compositeTransportCache.clear();
|
|
118
156
|
}
|
|
@@ -2,5 +2,6 @@ export { TinfoilAI } from "./client.browser";
|
|
|
2
2
|
export { TinfoilAI as default } from "./client.browser";
|
|
3
3
|
export * from "./verifier";
|
|
4
4
|
export * from "./verification-runner";
|
|
5
|
-
export * from "./ai-sdk-provider
|
|
5
|
+
export * from "./ai-sdk-provider";
|
|
6
6
|
export * from "./config";
|
|
7
|
+
export * from "./secure-client";
|
|
@@ -3,5 +3,6 @@ export { TinfoilAI } from "./client.browser";
|
|
|
3
3
|
export { TinfoilAI as default } from "./client.browser";
|
|
4
4
|
export * from "./verifier";
|
|
5
5
|
export * from "./verification-runner";
|
|
6
|
-
export * from "./ai-sdk-provider
|
|
6
|
+
export * from "./ai-sdk-provider";
|
|
7
7
|
export * from "./config";
|
|
8
|
+
export * from "./secure-client";
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -4,4 +4,5 @@ export * from "./verifier";
|
|
|
4
4
|
export * from "./verification-runner";
|
|
5
5
|
export * from "./ai-sdk-provider";
|
|
6
6
|
export * from "./config";
|
|
7
|
+
export * from "./secure-client";
|
|
7
8
|
export { type Uploadable, toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";
|
package/dist/esm/index.js
CHANGED
|
@@ -6,6 +6,7 @@ export * from "./verifier";
|
|
|
6
6
|
export * from "./verification-runner";
|
|
7
7
|
export * from "./ai-sdk-provider";
|
|
8
8
|
export * from "./config";
|
|
9
|
+
export * from "./secure-client";
|
|
9
10
|
// Re-export OpenAI utility types and classes that users might need
|
|
10
11
|
// Using public exports from the main OpenAI package instead of deep imports
|
|
11
12
|
export { toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function createPinnedTlsFetch(expectedFingerprintHex: string): typeof fetch;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import https from "https";
|
|
2
|
+
import { checkServerIdentity as tlsCheckServerIdentity } from "tls";
|
|
3
|
+
import { X509Certificate, createHash } from "crypto";
|
|
4
|
+
import { Readable } from "stream";
|
|
5
|
+
export function createPinnedTlsFetch(expectedFingerprintHex) {
|
|
6
|
+
return (async (input, init) => {
|
|
7
|
+
// Normalize URL
|
|
8
|
+
const makeURL = (value) => {
|
|
9
|
+
if (typeof value === "string")
|
|
10
|
+
return new URL(value);
|
|
11
|
+
if (value instanceof URL)
|
|
12
|
+
return value;
|
|
13
|
+
return new URL(value.url);
|
|
14
|
+
};
|
|
15
|
+
const url = makeURL(input);
|
|
16
|
+
if (url.protocol !== "https:") {
|
|
17
|
+
throw new Error(`HTTP connections are not allowed. Use HTTPS. URL: ${url.toString()}`);
|
|
18
|
+
}
|
|
19
|
+
// Gather method and headers
|
|
20
|
+
const method = (init?.method || input.method || "GET").toUpperCase();
|
|
21
|
+
const headers = new Headers(init?.headers || input?.headers || {});
|
|
22
|
+
const headerObj = {};
|
|
23
|
+
headers.forEach((v, k) => {
|
|
24
|
+
headerObj[k] = v;
|
|
25
|
+
});
|
|
26
|
+
// Resolve body
|
|
27
|
+
let body = init?.body;
|
|
28
|
+
if (!body && input instanceof Request) {
|
|
29
|
+
// If the original was a Request with a body, read it
|
|
30
|
+
try {
|
|
31
|
+
const buf = await input.arrayBuffer();
|
|
32
|
+
if (buf && buf.byteLength)
|
|
33
|
+
body = Buffer.from(buf);
|
|
34
|
+
}
|
|
35
|
+
catch { }
|
|
36
|
+
}
|
|
37
|
+
// Convert web streams to Node streams if needed
|
|
38
|
+
if (body && typeof body.getReader === "function") {
|
|
39
|
+
body = Readable.fromWeb(body);
|
|
40
|
+
}
|
|
41
|
+
if (body instanceof ArrayBuffer) {
|
|
42
|
+
body = Buffer.from(body);
|
|
43
|
+
}
|
|
44
|
+
if (ArrayBuffer.isView(body)) {
|
|
45
|
+
body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
|
|
46
|
+
}
|
|
47
|
+
const requestOptions = {
|
|
48
|
+
protocol: url.protocol,
|
|
49
|
+
hostname: url.hostname,
|
|
50
|
+
port: url.port ? Number(url.port) : 443,
|
|
51
|
+
path: `${url.pathname}${url.search}`,
|
|
52
|
+
method,
|
|
53
|
+
headers: headerObj,
|
|
54
|
+
checkServerIdentity: (host, cert) => {
|
|
55
|
+
const raw = cert.raw;
|
|
56
|
+
if (!raw) {
|
|
57
|
+
return new Error("Certificate raw bytes are unavailable for pinning");
|
|
58
|
+
}
|
|
59
|
+
const x509 = new X509Certificate(raw);
|
|
60
|
+
const publicKeyDer = x509.publicKey.export({ type: "spki", format: "der" });
|
|
61
|
+
const fp = createHash("sha256").update(publicKeyDer).digest("hex");
|
|
62
|
+
if (fp !== expectedFingerprintHex) {
|
|
63
|
+
return new Error(`Certificate public key fingerprint mismatch. Expected: ${expectedFingerprintHex}, Got: ${fp}`);
|
|
64
|
+
}
|
|
65
|
+
return tlsCheckServerIdentity(host, cert);
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
const { signal } = init || {};
|
|
69
|
+
const res = await new Promise((resolve, reject) => {
|
|
70
|
+
const req = https.request(requestOptions, resolve);
|
|
71
|
+
req.on("error", reject);
|
|
72
|
+
if (signal) {
|
|
73
|
+
if (signal.aborted) {
|
|
74
|
+
req.destroy(new Error("Request aborted"));
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
signal.addEventListener("abort", () => req.destroy(new Error("Request aborted")));
|
|
78
|
+
}
|
|
79
|
+
if (body === undefined || body === null) {
|
|
80
|
+
req.end();
|
|
81
|
+
}
|
|
82
|
+
else if (typeof body === "string" || Buffer.isBuffer(body) || ArrayBuffer.isView(body)) {
|
|
83
|
+
req.end(body);
|
|
84
|
+
}
|
|
85
|
+
else if (typeof body.pipe === "function") {
|
|
86
|
+
body.pipe(req);
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
// Fallback: try to serialize objects
|
|
90
|
+
req.end(String(body));
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
const responseHeaders = new Headers();
|
|
94
|
+
for (const [k, v] of Object.entries(res.headers)) {
|
|
95
|
+
if (Array.isArray(v)) {
|
|
96
|
+
v.forEach(item => responseHeaders.append(k, item));
|
|
97
|
+
}
|
|
98
|
+
else if (v != null) {
|
|
99
|
+
responseHeaders.set(k, String(v));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
// Convert Node stream to Web ReadableStream
|
|
103
|
+
const webStream = Readable.toWeb(res);
|
|
104
|
+
return new Response(webStream, {
|
|
105
|
+
status: res.statusCode || 0,
|
|
106
|
+
statusText: res.statusMessage || "",
|
|
107
|
+
headers: responseHeaders,
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { VerificationDocument } from "./verifier";
|
|
2
|
+
interface SecureClientOptions {
|
|
3
|
+
baseURL?: string;
|
|
4
|
+
hpkeKeyURL?: string;
|
|
5
|
+
configRepo?: string;
|
|
6
|
+
}
|
|
7
|
+
export declare class SecureClient {
|
|
8
|
+
private initPromise;
|
|
9
|
+
private verificationDocument;
|
|
10
|
+
private _fetch;
|
|
11
|
+
private readonly baseURL?;
|
|
12
|
+
private readonly hpkeKeyURL?;
|
|
13
|
+
private readonly configRepo?;
|
|
14
|
+
constructor(options?: SecureClientOptions);
|
|
15
|
+
ready(): Promise<void>;
|
|
16
|
+
private initSecureClient;
|
|
17
|
+
getVerificationDocument(): Promise<VerificationDocument>;
|
|
18
|
+
get fetch(): typeof fetch;
|
|
19
|
+
}
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { Verifier } from "./verifier";
|
|
2
|
+
import { TINFOIL_CONFIG } from "./config";
|
|
3
|
+
import { createEncryptedBodyFetch } from "./encrypted-body-fetch";
|
|
4
|
+
import { isRealBrowser } from "./env";
|
|
5
|
+
export class SecureClient {
|
|
6
|
+
constructor(options = {}) {
|
|
7
|
+
this.initPromise = null;
|
|
8
|
+
this.verificationDocument = null;
|
|
9
|
+
this._fetch = null;
|
|
10
|
+
this.baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
|
|
11
|
+
this.hpkeKeyURL = options.hpkeKeyURL || TINFOIL_CONFIG.HPKE_KEY_URL;
|
|
12
|
+
this.configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
|
|
13
|
+
}
|
|
14
|
+
async ready() {
|
|
15
|
+
if (!this.initPromise) {
|
|
16
|
+
this.initPromise = this.initSecureClient();
|
|
17
|
+
}
|
|
18
|
+
return this.initPromise;
|
|
19
|
+
}
|
|
20
|
+
async initSecureClient() {
|
|
21
|
+
const verifier = new Verifier({
|
|
22
|
+
serverURL: this.baseURL,
|
|
23
|
+
configRepo: this.configRepo,
|
|
24
|
+
});
|
|
25
|
+
await verifier.verify();
|
|
26
|
+
const doc = verifier.getVerificationDocument();
|
|
27
|
+
if (!doc) {
|
|
28
|
+
throw new Error("Verification document not available after successful verification");
|
|
29
|
+
}
|
|
30
|
+
this.verificationDocument = doc;
|
|
31
|
+
const hpkePublicKey = this.verificationDocument.enclaveMeasurement.hpkePublicKey;
|
|
32
|
+
if (!hpkePublicKey) {
|
|
33
|
+
if (isRealBrowser()) {
|
|
34
|
+
throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
|
|
35
|
+
"Only HPKE-enabled enclaves can be used in browser environments.");
|
|
36
|
+
}
|
|
37
|
+
throw new Error("HPKE public key is required in browser environments");
|
|
38
|
+
}
|
|
39
|
+
this._fetch = createEncryptedBodyFetch(this.baseURL, hpkePublicKey, this.hpkeKeyURL);
|
|
40
|
+
}
|
|
41
|
+
async getVerificationDocument() {
|
|
42
|
+
if (!this.initPromise) {
|
|
43
|
+
await this.ready();
|
|
44
|
+
}
|
|
45
|
+
await this.initPromise;
|
|
46
|
+
if (!this.verificationDocument) {
|
|
47
|
+
throw new Error("Verification document unavailable: client not verified yet");
|
|
48
|
+
}
|
|
49
|
+
return this.verificationDocument;
|
|
50
|
+
}
|
|
51
|
+
get fetch() {
|
|
52
|
+
return async (input, init) => {
|
|
53
|
+
await this.ready();
|
|
54
|
+
return this._fetch(input, init);
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { VerificationDocument } from "./verifier";
|
|
2
|
+
interface SecureClientOptions {
|
|
3
|
+
baseURL?: string;
|
|
4
|
+
hpkeKeyURL?: string;
|
|
5
|
+
configRepo?: string;
|
|
6
|
+
}
|
|
7
|
+
export declare class SecureClient {
|
|
8
|
+
private initPromise;
|
|
9
|
+
private verificationDocument;
|
|
10
|
+
private _fetch;
|
|
11
|
+
private readonly baseURL?;
|
|
12
|
+
private readonly hpkeKeyURL?;
|
|
13
|
+
private readonly configRepo?;
|
|
14
|
+
constructor(options?: SecureClientOptions);
|
|
15
|
+
ready(): Promise<void>;
|
|
16
|
+
private initSecureClient;
|
|
17
|
+
getVerificationDocument(): Promise<VerificationDocument>;
|
|
18
|
+
get fetch(): typeof fetch;
|
|
19
|
+
}
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { Verifier } from "./verifier";
|
|
2
|
+
import { TINFOIL_CONFIG } from "./config";
|
|
3
|
+
import { createEncryptedBodyFetch } from "./encrypted-body-fetch";
|
|
4
|
+
import { createPinnedTlsFetch } from "./pinned-tls-fetch";
|
|
5
|
+
import { isRealBrowser } from "./env";
|
|
6
|
+
export class SecureClient {
|
|
7
|
+
constructor(options = {}) {
|
|
8
|
+
this.initPromise = null;
|
|
9
|
+
this.verificationDocument = null;
|
|
10
|
+
this._fetch = null;
|
|
11
|
+
this.baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
|
|
12
|
+
this.hpkeKeyURL = options.hpkeKeyURL || TINFOIL_CONFIG.HPKE_KEY_URL;
|
|
13
|
+
this.configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
|
|
14
|
+
}
|
|
15
|
+
async ready() {
|
|
16
|
+
if (!this.initPromise) {
|
|
17
|
+
this.initPromise = this.initSecureClient();
|
|
18
|
+
}
|
|
19
|
+
return this.initPromise;
|
|
20
|
+
}
|
|
21
|
+
async initSecureClient() {
|
|
22
|
+
const verifier = new Verifier({
|
|
23
|
+
serverURL: this.baseURL,
|
|
24
|
+
configRepo: this.configRepo,
|
|
25
|
+
});
|
|
26
|
+
await verifier.verify();
|
|
27
|
+
const doc = verifier.getVerificationDocument();
|
|
28
|
+
if (!doc) {
|
|
29
|
+
throw new Error("Verification document not available after successful verification");
|
|
30
|
+
}
|
|
31
|
+
this.verificationDocument = doc;
|
|
32
|
+
const { hpkePublicKey, tlsPublicKeyFingerprint } = this.verificationDocument.enclaveMeasurement;
|
|
33
|
+
let fetchFunction;
|
|
34
|
+
if (hpkePublicKey) {
|
|
35
|
+
// HPKE available: use encrypted body fetch
|
|
36
|
+
fetchFunction = createEncryptedBodyFetch(this.baseURL, hpkePublicKey, this.hpkeKeyURL);
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
// HPKE not available: check if we're in a browser
|
|
40
|
+
if (isRealBrowser()) {
|
|
41
|
+
throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
|
|
42
|
+
"Only HPKE-enabled enclaves can be used in browser environments.");
|
|
43
|
+
}
|
|
44
|
+
// Node.js environment: fall back to TLS-only verification using pinned TLS fetch
|
|
45
|
+
if (!tlsPublicKeyFingerprint) {
|
|
46
|
+
throw new Error("Neither HPKE public key nor TLS public key fingerprint available for verification");
|
|
47
|
+
}
|
|
48
|
+
fetchFunction = createPinnedTlsFetch(tlsPublicKeyFingerprint);
|
|
49
|
+
}
|
|
50
|
+
this._fetch = fetchFunction;
|
|
51
|
+
}
|
|
52
|
+
async getVerificationDocument() {
|
|
53
|
+
if (!this.initPromise) {
|
|
54
|
+
await this.ready();
|
|
55
|
+
}
|
|
56
|
+
await this.initPromise;
|
|
57
|
+
if (!this.verificationDocument) {
|
|
58
|
+
throw new Error("Verification document unavailable: client not verified yet");
|
|
59
|
+
}
|
|
60
|
+
return this.verificationDocument;
|
|
61
|
+
}
|
|
62
|
+
get fetch() {
|
|
63
|
+
return async (input, init) => {
|
|
64
|
+
await this.ready();
|
|
65
|
+
return this._fetch(input, init);
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -61,11 +61,6 @@ export interface RunVerificationOptions {
|
|
|
61
61
|
export declare class VerifierWithState extends Verifier {
|
|
62
62
|
private state;
|
|
63
63
|
private subscribers;
|
|
64
|
-
private static runnerVerificationCache;
|
|
65
|
-
/**
|
|
66
|
-
* Clear the verification cache
|
|
67
|
-
*/
|
|
68
|
-
static clearVerificationCache(): void;
|
|
69
64
|
/**
|
|
70
65
|
* Subscribe to verification state updates
|
|
71
66
|
* @param subscriber - Callback function to receive state updates
|
|
@@ -94,7 +89,3 @@ export declare class VerifierWithState extends Verifier {
|
|
|
94
89
|
*/
|
|
95
90
|
export declare function loadVerifier(): Promise<VerifierWithState>;
|
|
96
91
|
export { suppressWasmLogs, TINFOIL_CONFIG };
|
|
97
|
-
/**
|
|
98
|
-
* Clear the verification cache
|
|
99
|
-
*/
|
|
100
|
-
export declare function clearVerificationCache(): void;
|
|
@@ -16,12 +16,6 @@ export class VerifierWithState extends Verifier {
|
|
|
16
16
|
// Subscribers
|
|
17
17
|
this.subscribers = new Set();
|
|
18
18
|
}
|
|
19
|
-
/**
|
|
20
|
-
* Clear the verification cache
|
|
21
|
-
*/
|
|
22
|
-
static clearVerificationCache() {
|
|
23
|
-
VerifierWithState.runnerVerificationCache.clear();
|
|
24
|
-
}
|
|
25
19
|
/**
|
|
26
20
|
* Subscribe to verification state updates
|
|
27
21
|
* @param subscriber - Callback function to receive state updates
|
|
@@ -92,35 +86,7 @@ export class VerifierWithState extends Verifier {
|
|
|
92
86
|
return this.state;
|
|
93
87
|
}
|
|
94
88
|
}
|
|
95
|
-
|
|
96
|
-
const cacheKey = `${configRepo}::${enclaveURL}::${releaseDigest}`;
|
|
97
|
-
const cachedPromise = VerifierWithState.runnerVerificationCache.get(cacheKey);
|
|
98
|
-
if (cachedPromise) {
|
|
99
|
-
// Reuse cached promise, but publish state updates for this instance
|
|
100
|
-
if (options?.onUpdate) {
|
|
101
|
-
const unsubscribe = this.subscribe(options.onUpdate);
|
|
102
|
-
// Get the cached result and update this instance's state to match
|
|
103
|
-
cachedPromise.then(cachedResult => {
|
|
104
|
-
// Update this instance's state to match the cached result
|
|
105
|
-
this.updateState(cachedResult);
|
|
106
|
-
}).finally(() => unsubscribe());
|
|
107
|
-
}
|
|
108
|
-
return cachedPromise;
|
|
109
|
-
}
|
|
110
|
-
// No cached result, create new verification promise
|
|
111
|
-
const verificationPromise = this._runVerificationInternal(configRepo, enclaveURL, releaseDigest)
|
|
112
|
-
.then(result => {
|
|
113
|
-
// Successful verification stays in cache
|
|
114
|
-
return result;
|
|
115
|
-
})
|
|
116
|
-
.catch(error => {
|
|
117
|
-
// On error, evict from cache
|
|
118
|
-
VerifierWithState.runnerVerificationCache.delete(cacheKey);
|
|
119
|
-
throw error;
|
|
120
|
-
});
|
|
121
|
-
// Store in cache
|
|
122
|
-
VerifierWithState.runnerVerificationCache.set(cacheKey, verificationPromise);
|
|
123
|
-
// Handle updates if requested
|
|
89
|
+
const verificationPromise = this._runVerificationInternal(configRepo, enclaveURL, releaseDigest);
|
|
124
90
|
if (options?.onUpdate) {
|
|
125
91
|
const unsubscribe = this.subscribe(options.onUpdate);
|
|
126
92
|
verificationPromise.finally(() => unsubscribe());
|
|
@@ -202,8 +168,6 @@ export class VerifierWithState extends Verifier {
|
|
|
202
168
|
}
|
|
203
169
|
}
|
|
204
170
|
}
|
|
205
|
-
// Static cache for deduplicating verifications
|
|
206
|
-
VerifierWithState.runnerVerificationCache = new Map();
|
|
207
171
|
/**
|
|
208
172
|
* Load and initialize a verifier instance with state management
|
|
209
173
|
* @returns Initialized verifier instance with state management
|
|
@@ -216,9 +180,3 @@ export async function loadVerifier() {
|
|
|
216
180
|
}
|
|
217
181
|
// Re-export utilities
|
|
218
182
|
export { suppressWasmLogs, TINFOIL_CONFIG };
|
|
219
|
-
/**
|
|
220
|
-
* Clear the verification cache
|
|
221
|
-
*/
|
|
222
|
-
export function clearVerificationCache() {
|
|
223
|
-
VerifierWithState.clearVerificationCache();
|
|
224
|
-
}
|
package/dist/esm/verifier.d.ts
CHANGED
|
@@ -52,13 +52,11 @@ export declare function compareMeasurements(codeMeasurement: AttestationMeasurem
|
|
|
52
52
|
export declare class Verifier {
|
|
53
53
|
private static goInstance;
|
|
54
54
|
private static initializationPromise;
|
|
55
|
-
private static verificationCache;
|
|
56
55
|
private static readonly defaultWasmUrl;
|
|
57
56
|
static originalFsWriteSync: ((fd: number, buf: Uint8Array) => number) | null;
|
|
58
57
|
static wasmLogsSuppressed: boolean;
|
|
59
58
|
static globalsInitialized: boolean;
|
|
60
59
|
private lastVerificationDocument?;
|
|
61
|
-
static clearVerificationCache(): void;
|
|
62
60
|
protected readonly serverURL: string;
|
|
63
61
|
protected readonly configRepo: string;
|
|
64
62
|
constructor(options?: {
|
package/dist/esm/verifier.js
CHANGED
|
@@ -28,7 +28,6 @@
|
|
|
28
28
|
* - Works in Node 20+ and modern browsers with lightweight polyfills for
|
|
29
29
|
* `performance`, `TextEncoder`/`TextDecoder`, and `crypto.getRandomValues`
|
|
30
30
|
* - Go stdout/stderr is suppressed by default; toggle via `suppressWasmLogs()`
|
|
31
|
-
* - Successful end-to-end results are cached per `configRepo::enclave::digest` for the process lifetime
|
|
32
31
|
* - Module auto-initializes the WASM runtime on import
|
|
33
32
|
*
|
|
34
33
|
* PROXIES AND TRUST
|
|
@@ -194,9 +193,6 @@ export function compareMeasurements(codeMeasurement, runtimeMeasurement) {
|
|
|
194
193
|
* 4. Compares measurements using platform-specific logic
|
|
195
194
|
*/
|
|
196
195
|
export class Verifier {
|
|
197
|
-
static clearVerificationCache() {
|
|
198
|
-
Verifier.verificationCache.clear();
|
|
199
|
-
}
|
|
200
196
|
constructor(options) {
|
|
201
197
|
const serverURL = options?.serverURL ?? TINFOIL_CONFIG.INFERENCE_BASE_URL;
|
|
202
198
|
this.serverURL = new URL(serverURL).hostname;
|
|
@@ -411,55 +407,29 @@ export class Verifier {
|
|
|
411
407
|
* @throws Error if measurements don't match or verification fails
|
|
412
408
|
*/
|
|
413
409
|
async verify() {
|
|
414
|
-
// Get latest release digest first
|
|
410
|
+
// Get latest release digest first
|
|
415
411
|
const releaseDigest = await this.fetchLatestDigest(this.configRepo);
|
|
416
|
-
|
|
417
|
-
const
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
enclaveHost: this.serverURL,
|
|
427
|
-
releaseDigest: releaseDigest,
|
|
428
|
-
codeMeasurement,
|
|
429
|
-
enclaveMeasurement: attestation,
|
|
430
|
-
match: true, // Must be true since verification succeeded
|
|
431
|
-
};
|
|
432
|
-
}
|
|
433
|
-
return attestation;
|
|
412
|
+
// Perform code attestation and runtime attestation in parallel
|
|
413
|
+
const [{ measurement: codeMeasurement }, attestation] = await Promise.all([
|
|
414
|
+
this.verifyCode(this.configRepo, releaseDigest),
|
|
415
|
+
this.verifyEnclave(this.serverURL),
|
|
416
|
+
]);
|
|
417
|
+
// Compare measurements using platform-specific logic
|
|
418
|
+
const measurementsMatchError = compareMeasurementsError(codeMeasurement, attestation.measurement);
|
|
419
|
+
if (measurementsMatchError) {
|
|
420
|
+
throw new Error(`Measurement verification failed: Code measurement (${codeMeasurement.type}) ` +
|
|
421
|
+
`does not match runtime measurement (${attestation.measurement.type}): ${measurementsMatchError.message}`);
|
|
434
422
|
}
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
`does not match runtime measurement (${attestation.measurement.type}): ${measurementsMatchError.message}`);
|
|
446
|
-
}
|
|
447
|
-
// Persist a full verification document for later retrieval by clients
|
|
448
|
-
this.lastVerificationDocument = {
|
|
449
|
-
configRepo: this.configRepo,
|
|
450
|
-
enclaveHost: this.serverURL,
|
|
451
|
-
releaseDigest: releaseDigest,
|
|
452
|
-
codeMeasurement,
|
|
453
|
-
enclaveMeasurement: attestation,
|
|
454
|
-
match: true,
|
|
455
|
-
};
|
|
456
|
-
return attestation;
|
|
457
|
-
})();
|
|
458
|
-
Verifier.verificationCache.set(cacheKey, verificationPromise);
|
|
459
|
-
verificationPromise.catch(() => {
|
|
460
|
-
Verifier.verificationCache.delete(cacheKey);
|
|
461
|
-
});
|
|
462
|
-
return verificationPromise;
|
|
423
|
+
// Persist a full verification document for later retrieval by clients
|
|
424
|
+
this.lastVerificationDocument = {
|
|
425
|
+
configRepo: this.configRepo,
|
|
426
|
+
enclaveHost: this.serverURL,
|
|
427
|
+
releaseDigest: releaseDigest,
|
|
428
|
+
codeMeasurement,
|
|
429
|
+
enclaveMeasurement: attestation,
|
|
430
|
+
match: true,
|
|
431
|
+
};
|
|
432
|
+
return attestation;
|
|
463
433
|
}
|
|
464
434
|
/**
|
|
465
435
|
* Returns the full verification document from the last successful verify() call
|
|
@@ -470,7 +440,6 @@ export class Verifier {
|
|
|
470
440
|
}
|
|
471
441
|
Verifier.goInstance = null;
|
|
472
442
|
Verifier.initializationPromise = null;
|
|
473
|
-
Verifier.verificationCache = new Map();
|
|
474
443
|
Verifier.defaultWasmUrl = "https://tinfoilsh.github.io/verifier-js/tinfoil-verifier.wasm";
|
|
475
444
|
Verifier.originalFsWriteSync = null;
|
|
476
445
|
Verifier.wasmLogsSuppressed = true;
|
package/dist/index.browser.d.ts
CHANGED
|
@@ -2,5 +2,6 @@ export { TinfoilAI } from "./client.browser";
|
|
|
2
2
|
export { TinfoilAI as default } from "./client.browser";
|
|
3
3
|
export * from "./verifier";
|
|
4
4
|
export * from "./verification-runner";
|
|
5
|
-
export * from "./ai-sdk-provider
|
|
5
|
+
export * from "./ai-sdk-provider";
|
|
6
6
|
export * from "./config";
|
|
7
|
+
export * from "./secure-client";
|
package/dist/index.browser.js
CHANGED
|
@@ -22,5 +22,6 @@ var client_browser_2 = require("./client.browser");
|
|
|
22
22
|
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return client_browser_2.TinfoilAI; } });
|
|
23
23
|
__exportStar(require("./verifier"), exports);
|
|
24
24
|
__exportStar(require("./verification-runner"), exports);
|
|
25
|
-
__exportStar(require("./ai-sdk-provider
|
|
25
|
+
__exportStar(require("./ai-sdk-provider"), exports);
|
|
26
26
|
__exportStar(require("./config"), exports);
|
|
27
|
+
__exportStar(require("./secure-client"), exports);
|
package/dist/index.d.ts
CHANGED
|
@@ -4,4 +4,5 @@ export * from "./verifier";
|
|
|
4
4
|
export * from "./verification-runner";
|
|
5
5
|
export * from "./ai-sdk-provider";
|
|
6
6
|
export * from "./config";
|
|
7
|
+
export * from "./secure-client";
|
|
7
8
|
export { type Uploadable, toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";
|