tinfoil 0.8.7 → 0.9.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.
@@ -199,51 +199,60 @@ export class Verifier {
199
199
  this.configRepo = options?.configRepo ?? TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
200
200
  }
201
201
  /**
202
- * Initialize the WebAssembly module
203
- * This loads the Go runtime and makes verification functions available
202
+ * Execute a function with a fresh WASM instance that auto-cleans up
203
+ * This ensures Go runtime doesn't keep the process alive
204
204
  */
205
- static async initializeWasm() {
206
- if (Verifier.initializationPromise) {
207
- return Verifier.initializationPromise;
205
+ static async executeWithWasm(fn) {
206
+ await initializeWasmGlobals();
207
+ const goInstance = new globalThis.Go();
208
+ // Load WASM module
209
+ const fetchFn = getFetch();
210
+ const wasmResponse = await fetchFn(Verifier.defaultWasmUrl);
211
+ if (!wasmResponse.ok) {
212
+ throw new Error(`Failed to fetch WASM: ${wasmResponse.status} ${wasmResponse.statusText}`);
208
213
  }
209
- Verifier.initializationPromise = (async () => {
210
- try {
211
- // Initialize globals if not already done
212
- await initializeWasmGlobals();
213
- Verifier.goInstance = new globalThis.Go();
214
- // Load WASM module
215
- const fetchFn = getFetch();
216
- const wasmResponse = await fetchFn(Verifier.defaultWasmUrl);
217
- if (!wasmResponse.ok) {
218
- throw new Error(`Failed to fetch WASM: ${wasmResponse.status} ${wasmResponse.statusText}`);
214
+ const wasmBuffer = await wasmResponse.arrayBuffer();
215
+ const result = await WebAssembly.instantiate(wasmBuffer, goInstance.importObject);
216
+ // Start the Go instance in the background
217
+ // We don't await this - it runs continuously
218
+ goInstance.run(result.instance);
219
+ // Wait for WASM functions to be available
220
+ await new Promise(resolve => setTimeout(resolve, 100));
221
+ if (typeof globalThis.verifyCode === "undefined" || typeof globalThis.verifyEnclave === "undefined") {
222
+ await new Promise(resolve => setTimeout(resolve, 500));
223
+ }
224
+ // Apply log suppression if requested
225
+ if (Verifier.wasmLogsSuppressed && globalThis.fs?.writeSync) {
226
+ const fsObj = globalThis.fs;
227
+ if (!Verifier.originalFsWriteSync) {
228
+ Verifier.originalFsWriteSync = fsObj.writeSync.bind(fsObj);
229
+ }
230
+ fsObj.writeSync = function (_fd, buf) {
231
+ return buf.length;
232
+ };
233
+ }
234
+ try {
235
+ // Execute the user's function
236
+ const result = await fn();
237
+ return result;
238
+ }
239
+ finally {
240
+ // Clean up the Go instance
241
+ if (goInstance._scheduledTimeouts instanceof Map) {
242
+ for (const timeoutId of goInstance._scheduledTimeouts.values()) {
243
+ clearTimeout(timeoutId);
219
244
  }
220
- const wasmBuffer = await wasmResponse.arrayBuffer();
221
- const result = await WebAssembly.instantiate(wasmBuffer, Verifier.goInstance.importObject);
222
- // Run the Go instance - this makes functions available on globalThis
223
- Verifier.goInstance.run(result.instance);
224
- // Wait for initialization to complete
225
- await new Promise(resolve => setTimeout(resolve, 100));
226
- // Ensure required functions are available
227
- if (typeof globalThis.verifyCode === "undefined" || typeof globalThis.verifyEnclave === "undefined") {
228
- await new Promise(resolve => setTimeout(resolve, 500));
245
+ goInstance._scheduledTimeouts.clear();
246
+ }
247
+ if (typeof goInstance.exit === 'function') {
248
+ try {
249
+ goInstance.exit(0);
229
250
  }
230
- // Apply log suppression if requested
231
- if (Verifier.wasmLogsSuppressed && globalThis.fs?.writeSync) {
232
- const fsObj = globalThis.fs;
233
- if (!Verifier.originalFsWriteSync) {
234
- Verifier.originalFsWriteSync = fsObj.writeSync.bind(fsObj);
235
- }
236
- fsObj.writeSync = function (_fd, buf) {
237
- return buf.length;
238
- };
251
+ catch (e) {
252
+ // Ignore exit errors
239
253
  }
240
254
  }
241
- catch (error) {
242
- console.error("WASM initialization error:", error);
243
- throw error;
244
- }
245
- })();
246
- return Verifier.initializationPromise;
255
+ }
247
256
  }
248
257
  /**
249
258
  * Fetch the latest release digest from GitHub
@@ -288,7 +297,6 @@ export class Verifier {
288
297
  return new Promise(async (resolve, reject) => {
289
298
  try {
290
299
  const targetHost = enclaveHost || this.serverURL;
291
- await Verifier.initializeWasm();
292
300
  if (typeof globalThis.verifyEnclave !== "function") {
293
301
  reject(new Error("WASM verifyEnclave function not available"));
294
302
  return;
@@ -366,7 +374,6 @@ export class Verifier {
366
374
  * @returns Code measurement
367
375
  */
368
376
  async verifyCode(configRepo, digest) {
369
- await Verifier.initializeWasm();
370
377
  if (typeof globalThis.verifyCode !== "function") {
371
378
  throw new Error("WASM verifyCode function not available");
372
379
  }
@@ -404,30 +411,92 @@ export class Verifier {
404
411
  * 4. Compares measurements using platform-specific logic (see `compareMeasurements()`)
405
412
  * 5. Returns the attestation response if verification succeeds
406
413
  *
414
+ * The WASM runtime is automatically initialized and cleaned up within this method.
415
+ *
407
416
  * @throws Error if measurements don't match or verification fails
408
417
  */
409
418
  async verify() {
410
- // Get latest release digest first
411
- const releaseDigest = await this.fetchLatestDigest(this.configRepo);
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
419
+ return Verifier.executeWithWasm(async () => {
420
+ return this.verifyInternal();
421
+ });
422
+ }
423
+ /**
424
+ * Internal verification logic that runs within WASM context
425
+ */
426
+ async verifyInternal() {
427
+ const steps = {
428
+ fetchDigest: { status: 'pending' },
429
+ verifyCode: { status: 'pending' },
430
+ verifyEnclave: { status: 'pending' },
431
+ compareMeasurements: { status: 'pending' },
432
+ };
433
+ let releaseDigest;
434
+ let codeMeasurement;
435
+ let attestation;
436
+ try {
437
+ releaseDigest = await this.fetchLatestDigest(this.configRepo);
438
+ steps.fetchDigest = { status: 'success' };
439
+ }
440
+ catch (error) {
441
+ steps.fetchDigest = { status: 'failed', error: error.message };
442
+ throw error;
443
+ }
444
+ try {
445
+ const results = await Promise.all([
446
+ this.verifyCode(this.configRepo, releaseDigest).then((result) => {
447
+ steps.verifyCode = { status: 'success' };
448
+ return result;
449
+ }, (error) => {
450
+ steps.verifyCode = { status: 'failed', error: error.message };
451
+ throw error;
452
+ }),
453
+ this.verifyEnclave(this.serverURL).then((result) => {
454
+ steps.verifyEnclave = { status: 'success' };
455
+ return result;
456
+ }, (error) => {
457
+ steps.verifyEnclave = { status: 'failed', error: error.message };
458
+ throw error;
459
+ }),
460
+ ]);
461
+ codeMeasurement = results[0].measurement;
462
+ attestation = results[1];
463
+ }
464
+ catch (error) {
465
+ this.lastVerificationDocument = {
466
+ configRepo: this.configRepo,
467
+ enclaveHost: this.serverURL,
468
+ releaseDigest: releaseDigest,
469
+ codeMeasurement: codeMeasurement,
470
+ enclaveMeasurement: attestation,
471
+ securityVerified: false,
472
+ steps,
473
+ };
474
+ throw error;
475
+ }
418
476
  const measurementsMatchError = compareMeasurementsError(codeMeasurement, attestation.measurement);
419
477
  if (measurementsMatchError) {
478
+ steps.compareMeasurements = { status: 'failed', error: measurementsMatchError.message };
479
+ this.lastVerificationDocument = {
480
+ configRepo: this.configRepo,
481
+ enclaveHost: this.serverURL,
482
+ releaseDigest: releaseDigest,
483
+ codeMeasurement,
484
+ enclaveMeasurement: attestation,
485
+ securityVerified: false,
486
+ steps,
487
+ };
420
488
  throw new Error(`Verification failed: measurements did not match.\nCode measurement (${codeMeasurement.type}: ${codeMeasurement.registers})\n` +
421
489
  `Runtime measurement (${attestation.measurement.type}: ${attestation.measurement.registers}:)\n ${measurementsMatchError.message}`);
422
490
  }
423
- // Persist a full verification document for later retrieval by clients
491
+ steps.compareMeasurements = { status: 'success' };
424
492
  this.lastVerificationDocument = {
425
493
  configRepo: this.configRepo,
426
494
  enclaveHost: this.serverURL,
427
495
  releaseDigest: releaseDigest,
428
496
  codeMeasurement,
429
497
  enclaveMeasurement: attestation,
430
- match: true,
498
+ securityVerified: true,
499
+ steps,
431
500
  };
432
501
  return attestation;
433
502
  }
@@ -465,11 +534,6 @@ function shouldAutoInitializeWasm() {
465
534
  const hasBrowserGlobals = typeof globalAny.window === "object" && typeof globalAny.document === "object";
466
535
  return hasBrowserGlobals;
467
536
  }
468
- if (shouldAutoInitializeWasm()) {
469
- void Verifier.initializeWasm().catch(error => {
470
- console.error(error);
471
- });
472
- }
473
537
  /**
474
538
  * Control WASM log output
475
539
  *
@@ -1,7 +1,7 @@
1
1
  export { TinfoilAI } from "./tinfoilai";
2
2
  export { TinfoilAI as default } from "./tinfoilai";
3
3
  export * from "./verifier";
4
- export * from "./verification-runner";
5
4
  export * from "./ai-sdk-provider";
6
5
  export * from "./config";
7
6
  export { SecureClient } from "./secure-client";
7
+ export { UnverifiedClient } from "./unverified-client";
@@ -14,15 +14,16 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.SecureClient = exports.default = exports.TinfoilAI = void 0;
17
+ exports.UnverifiedClient = exports.SecureClient = exports.default = exports.TinfoilAI = void 0;
18
18
  // Browser-safe entry point: avoids Node built-ins
19
19
  var tinfoilai_1 = require("./tinfoilai");
20
20
  Object.defineProperty(exports, "TinfoilAI", { enumerable: true, get: function () { return tinfoilai_1.TinfoilAI; } });
21
21
  var tinfoilai_2 = require("./tinfoilai");
22
22
  Object.defineProperty(exports, "default", { enumerable: true, get: function () { return tinfoilai_2.TinfoilAI; } });
23
23
  __exportStar(require("./verifier"), exports);
24
- __exportStar(require("./verification-runner"), exports);
25
24
  __exportStar(require("./ai-sdk-provider"), exports);
26
25
  __exportStar(require("./config"), exports);
27
26
  var secure_client_1 = require("./secure-client");
28
27
  Object.defineProperty(exports, "SecureClient", { enumerable: true, get: function () { return secure_client_1.SecureClient; } });
28
+ var unverified_client_1 = require("./unverified-client");
29
+ Object.defineProperty(exports, "UnverifiedClient", { enumerable: true, get: function () { return unverified_client_1.UnverifiedClient; } });
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  export { TinfoilAI } from "./tinfoilai";
2
2
  export { TinfoilAI as default } from "./tinfoilai";
3
3
  export * from "./verifier";
4
- export * from "./verification-runner";
5
4
  export * from "./ai-sdk-provider";
6
5
  export * from "./config";
7
6
  export { SecureClient } from "./secure-client";
7
+ export { UnverifiedClient } from "./unverified-client";
8
8
  export { type Uploadable, toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";
package/dist/index.js CHANGED
@@ -14,19 +14,20 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.OpenAIError = exports.PagePromise = exports.APIPromise = exports.toFile = exports.SecureClient = exports.default = exports.TinfoilAI = void 0;
17
+ exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.OpenAIError = exports.PagePromise = exports.APIPromise = exports.toFile = exports.UnverifiedClient = exports.SecureClient = exports.default = exports.TinfoilAI = void 0;
18
18
  // Re-export the TinfoilAI class
19
19
  var tinfoilai_1 = require("./tinfoilai");
20
20
  Object.defineProperty(exports, "TinfoilAI", { enumerable: true, get: function () { return tinfoilai_1.TinfoilAI; } });
21
21
  var tinfoilai_2 = require("./tinfoilai");
22
22
  Object.defineProperty(exports, "default", { enumerable: true, get: function () { return tinfoilai_2.TinfoilAI; } });
23
- // Export verifier and loader
23
+ // Export verifier
24
24
  __exportStar(require("./verifier"), exports);
25
- __exportStar(require("./verification-runner"), exports);
26
25
  __exportStar(require("./ai-sdk-provider"), exports);
27
26
  __exportStar(require("./config"), exports);
28
27
  var secure_client_1 = require("./secure-client");
29
28
  Object.defineProperty(exports, "SecureClient", { enumerable: true, get: function () { return secure_client_1.SecureClient; } });
29
+ var unverified_client_1 = require("./unverified-client");
30
+ Object.defineProperty(exports, "UnverifiedClient", { enumerable: true, get: function () { return unverified_client_1.UnverifiedClient; } });
30
31
  // Re-export OpenAI utility types and classes that users might need
31
32
  // Using public exports from the main OpenAI package instead of deep imports
32
33
  var openai_1 = require("openai");
@@ -1 +1 @@
1
- export declare function createPinnedTlsFetch(expectedFingerprintHex: string): typeof fetch;
1
+ export declare function createPinnedTlsFetch(baseURL: string, expectedFingerprintHex: string): typeof fetch;
@@ -8,15 +8,15 @@ const https_1 = __importDefault(require("https"));
8
8
  const tls_1 = require("tls");
9
9
  const crypto_1 = require("crypto");
10
10
  const stream_1 = require("stream");
11
- function createPinnedTlsFetch(expectedFingerprintHex) {
11
+ function createPinnedTlsFetch(baseURL, expectedFingerprintHex) {
12
12
  return (async (input, init) => {
13
- // Normalize URL
13
+ // Normalize URL with base URL support
14
14
  const makeURL = (value) => {
15
15
  if (typeof value === "string")
16
- return new URL(value);
16
+ return new URL(value, baseURL);
17
17
  if (value instanceof URL)
18
18
  return value;
19
- return new URL(value.url);
19
+ return new URL(value.url, baseURL);
20
20
  };
21
21
  const url = makeURL(input);
22
22
  if (url.protocol !== "https:") {
@@ -19,7 +19,7 @@ function createSecureFetch(baseURL, enclaveURL, hpkePublicKey, tlsPublicKeyFinge
19
19
  if (!tlsPublicKeyFingerprint) {
20
20
  throw new Error("Neither HPKE public key nor TLS public key fingerprint available for verification");
21
21
  }
22
- fetchFunction = (0, pinned_tls_fetch_1.createPinnedTlsFetch)(tlsPublicKeyFingerprint);
22
+ fetchFunction = (0, pinned_tls_fetch_1.createPinnedTlsFetch)(baseURL, tlsPublicKeyFingerprint);
23
23
  }
24
24
  return fetchFunction;
25
25
  }
@@ -0,0 +1,18 @@
1
+ interface UnverifiedClientOptions {
2
+ baseURL?: string;
3
+ enclaveURL?: string;
4
+ configRepo?: string;
5
+ }
6
+ export declare class UnverifiedClient {
7
+ private initPromise;
8
+ private _fetch;
9
+ private readonly baseURL;
10
+ private readonly enclaveURL;
11
+ private readonly configRepo;
12
+ constructor(options?: UnverifiedClientOptions);
13
+ ready(): Promise<void>;
14
+ private initUnverifiedClient;
15
+ getVerificationDocument(): Promise<void>;
16
+ get fetch(): typeof fetch;
17
+ }
18
+ export {};
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UnverifiedClient = void 0;
4
+ const config_1 = require("./config");
5
+ const encrypted_body_fetch_1 = require("./encrypted-body-fetch");
6
+ class UnverifiedClient {
7
+ constructor(options = {}) {
8
+ this.initPromise = null;
9
+ this._fetch = null;
10
+ this.baseURL = options.baseURL || config_1.TINFOIL_CONFIG.INFERENCE_BASE_URL;
11
+ this.enclaveURL = options.enclaveURL || config_1.TINFOIL_CONFIG.ENCLAVE_URL;
12
+ this.configRepo = options.configRepo || config_1.TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
13
+ }
14
+ async ready() {
15
+ if (!this.initPromise) {
16
+ this.initPromise = this.initUnverifiedClient();
17
+ }
18
+ return this.initPromise;
19
+ }
20
+ async initUnverifiedClient() {
21
+ this._fetch = (0, encrypted_body_fetch_1.createEncryptedBodyFetch)(this.baseURL, undefined, this.enclaveURL);
22
+ }
23
+ async getVerificationDocument() {
24
+ if (!this.initPromise) {
25
+ await this.ready();
26
+ }
27
+ await this.initPromise;
28
+ throw new Error("Verification document unavailable: this version of the client is unverified");
29
+ }
30
+ get fetch() {
31
+ return async (input, init) => {
32
+ await this.ready();
33
+ return this._fetch(input, init);
34
+ };
35
+ }
36
+ }
37
+ exports.UnverifiedClient = UnverifiedClient;
@@ -15,7 +15,15 @@ export interface AttestationResponse {
15
15
  measurement: AttestationMeasurement;
16
16
  }
17
17
  /**
18
- * Full verification document produced by a successful verify() call
18
+ * State of an intermediate verification step
19
+ */
20
+ export interface VerificationStepState {
21
+ status: 'pending' | 'success' | 'failed';
22
+ error?: string;
23
+ }
24
+ /**
25
+ * Full verification document produced by a verify() call
26
+ * Includes state tracking for all intermediate steps
19
27
  */
20
28
  export interface VerificationDocument {
21
29
  configRepo: string;
@@ -23,7 +31,13 @@ export interface VerificationDocument {
23
31
  releaseDigest: string;
24
32
  codeMeasurement: AttestationMeasurement;
25
33
  enclaveMeasurement: AttestationResponse;
26
- match: boolean;
34
+ securityVerified: boolean;
35
+ steps: {
36
+ fetchDigest: VerificationStepState;
37
+ verifyCode: VerificationStepState;
38
+ verifyEnclave: VerificationStepState;
39
+ compareMeasurements: VerificationStepState;
40
+ };
27
41
  }
28
42
  export interface MeasurementComparisonResult {
29
43
  match: boolean;
@@ -64,10 +78,10 @@ export declare class Verifier {
64
78
  configRepo?: string;
65
79
  });
66
80
  /**
67
- * Initialize the WebAssembly module
68
- * This loads the Go runtime and makes verification functions available
81
+ * Execute a function with a fresh WASM instance that auto-cleans up
82
+ * This ensures Go runtime doesn't keep the process alive
69
83
  */
70
- static initializeWasm(): Promise<void>;
84
+ private static executeWithWasm;
71
85
  /**
72
86
  * Fetch the latest release digest from GitHub
73
87
  * @param configRepo - Repository name (e.g., "tinfoilsh/confidential-inference-proxy")
@@ -99,9 +113,15 @@ export declare class Verifier {
99
113
  * 4. Compares measurements using platform-specific logic (see `compareMeasurements()`)
100
114
  * 5. Returns the attestation response if verification succeeds
101
115
  *
116
+ * The WASM runtime is automatically initialized and cleaned up within this method.
117
+ *
102
118
  * @throws Error if measurements don't match or verification fails
103
119
  */
104
120
  verify(): Promise<AttestationResponse>;
121
+ /**
122
+ * Internal verification logic that runs within WASM context
123
+ */
124
+ private verifyInternal;
105
125
  /**
106
126
  * Returns the full verification document from the last successful verify() call
107
127
  */