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.
Files changed (51) hide show
  1. package/README.md +171 -8
  2. package/dist/__tests__/test-utils.d.ts +1 -0
  3. package/dist/__tests__/test-utils.js +44 -0
  4. package/dist/ai-sdk-provider.browser.d.ts +6 -0
  5. package/dist/ai-sdk-provider.browser.js +36 -0
  6. package/dist/ai-sdk-provider.d.ts +9 -1
  7. package/dist/ai-sdk-provider.js +154 -32
  8. package/dist/client.browser.d.ts +51 -0
  9. package/dist/client.browser.js +157 -0
  10. package/dist/client.d.ts +20 -4
  11. package/dist/client.js +175 -57
  12. package/dist/encrypted-body-fetch.d.ts +10 -0
  13. package/dist/encrypted-body-fetch.js +158 -0
  14. package/dist/env.d.ts +5 -0
  15. package/dist/env.js +20 -0
  16. package/dist/esm/__tests__/test-utils.d.ts +1 -0
  17. package/dist/esm/__tests__/test-utils.js +38 -0
  18. package/dist/esm/ai-sdk-provider.browser.d.ts +6 -0
  19. package/dist/esm/ai-sdk-provider.browser.js +33 -0
  20. package/dist/esm/ai-sdk-provider.d.ts +15 -0
  21. package/dist/esm/ai-sdk-provider.js +165 -0
  22. package/dist/esm/client.browser.d.ts +51 -0
  23. package/dist/esm/client.browser.js +150 -0
  24. package/dist/esm/client.d.ts +119 -0
  25. package/dist/esm/client.js +357 -0
  26. package/dist/esm/config.d.ts +13 -0
  27. package/dist/esm/config.js +13 -0
  28. package/dist/esm/encrypted-body-fetch.d.ts +10 -0
  29. package/dist/esm/encrypted-body-fetch.js +118 -0
  30. package/dist/esm/env.d.ts +5 -0
  31. package/dist/esm/env.js +17 -0
  32. package/dist/esm/index.browser.d.ts +6 -0
  33. package/dist/esm/index.browser.js +7 -0
  34. package/dist/esm/index.d.ts +7 -0
  35. package/dist/esm/index.js +11 -0
  36. package/dist/esm/verification-runner.d.ts +100 -0
  37. package/dist/esm/verification-runner.js +224 -0
  38. package/dist/esm/verifier.d.ts +120 -0
  39. package/dist/esm/verifier.js +685 -0
  40. package/dist/esm/wasm-exec.js +668 -0
  41. package/dist/index.browser.d.ts +6 -0
  42. package/dist/index.browser.js +26 -0
  43. package/dist/index.d.ts +2 -1
  44. package/dist/index.js +3 -2
  45. package/dist/verification-runner.d.ts +100 -0
  46. package/dist/verification-runner.js +230 -0
  47. package/dist/verifier.d.ts +120 -0
  48. package/dist/verifier.js +725 -0
  49. package/package.json +50 -9
  50. package/dist/secure-client.d.ts +0 -31
  51. package/dist/secure-client.js +0 -153
@@ -0,0 +1,685 @@
1
+ /**
2
+ * VERIFIER COMPONENT OVERVIEW
3
+ * ==========================
4
+ *
5
+ * This implementation performs three security checks entirely on the client using
6
+ * a Go WebAssembly module, and exposes a small TypeScript API around it.
7
+ *
8
+ * 1) REMOTE ATTESTATION (Enclave Verification)
9
+ * - Invokes Go WASM `verifyEnclave(host)` against the target enclave hostname
10
+ * - Verifies vendor certificate chains inside WASM (AMD SEV-SNP / Intel TDX)
11
+ * - Returns the enclave's runtime measurement and at least one public key (TLS fingerprint and/or HPKE)
12
+ * - Falls back to TLS-only verification if only TLS key is available (Node.js only)
13
+ *
14
+ * 2) CODE INTEGRITY (Release Verification)
15
+ * - Fetches the latest release notes via the Tinfoil GitHub proxy and extracts a digest
16
+ * (endpoint: https://api-github-proxy.tinfoil.sh)
17
+ * - Invokes Go WASM `verifyCode(configRepo, digest)` to obtain the expected code measurement
18
+ * - The Go implementation verifies provenance using Sigstore/Rekor for GitHub Actions builds
19
+ *
20
+ * 3) CODE CONSISTENCY (Measurement Comparison)
21
+ * - Compares the runtime measurement with the expected code measurement using
22
+ * platform-aware rules implemented in `compareMeasurements()`
23
+ *
24
+ * RUNTIME AND DELIVERY
25
+ * - All verification executes locally via WebAssembly (Go → WASM)
26
+ * - WASM loader: `wasm-exec.js`
27
+ * - WASM module URL: https://tinfoilsh.github.io/verifier-js/tinfoil-verifier.wasm
28
+ * - Works in Node 20+ and modern browsers with lightweight polyfills for
29
+ * `performance`, `TextEncoder`/`TextDecoder`, and `crypto.getRandomValues`
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
+ * - Module auto-initializes the WASM runtime on import
33
+ *
34
+ * PROXIES AND TRUST
35
+ * - GitHub proxy is used only to avoid rate limits; the WASM logic independently
36
+ * validates release provenance via Sigstore transparency logs
37
+ * - AMD KDS access may be proxied within the WASM for availability; AMD roots are
38
+ * embedded and the full chain is verified in Go to prevent forgery
39
+ *
40
+ * SUPPORTED PLATFORMS AND PREDICATES
41
+ * - Predicate types supported by this client: SNP/TDX multi-platform v1,
42
+ * TDX guest v1, SEV-SNP guest v1
43
+ * - See `compareMeasurements()` for exact register mapping rules
44
+ *
45
+ * PUBLIC API (this module)
46
+ * - `new Verifier({ serverURL?, configRepo? })`
47
+ * - `verify()` → full end-to-end verification and attestation response
48
+ * - `verifyEnclave(host?)` → runtime attestation only
49
+ * - `verifyCode(configRepo, digest)` → expected measurement for a specific release
50
+ * - `compareMeasurements(code, runtime)` → predicate-based comparison
51
+ * - `fetchLatestDigest(configRepo?)` → release digest via proxy
52
+ * - `suppressWasmLogs(suppress?)` → control WASM log output
53
+ */
54
+ import { TINFOIL_CONFIG } from "./config";
55
+ // Use native fetch and TextEncoder/TextDecoder
56
+ // In Node.js, these are available globally since v18
57
+ // In browsers, they're also available globally
58
+ let cachedFetch = null;
59
+ function getFetch() {
60
+ if (!cachedFetch) {
61
+ if (typeof globalThis.fetch !== "function") {
62
+ throw new Error("fetch is not available in this environment");
63
+ }
64
+ cachedFetch = globalThis.fetch.bind(globalThis);
65
+ }
66
+ return cachedFetch;
67
+ }
68
+ let cachedTextEncoder = null;
69
+ function getTextEncoder() {
70
+ if (!cachedTextEncoder) {
71
+ if (typeof globalThis.TextEncoder !== "function") {
72
+ throw new Error("TextEncoder is not available in this environment");
73
+ }
74
+ cachedTextEncoder = globalThis.TextEncoder;
75
+ }
76
+ return cachedTextEncoder;
77
+ }
78
+ let cachedTextDecoder = null;
79
+ function getTextDecoder() {
80
+ if (!cachedTextDecoder) {
81
+ if (typeof globalThis.TextDecoder !== "function") {
82
+ throw new Error("TextDecoder is not available in this environment");
83
+ }
84
+ cachedTextDecoder = globalThis.TextDecoder;
85
+ }
86
+ return cachedTextDecoder;
87
+ }
88
+ const nodeRequire = createNodeRequire();
89
+ let wasmExecLoader = null;
90
+ // Platform type constants
91
+ // See https://github.com/tinfoilsh/verifier/
92
+ const PLATFORM_TYPES = {
93
+ SNP_TDX_MULTI_PLATFORM_V1: "https://tinfoil.sh/predicate/snp-tdx-multiplatform/v1",
94
+ TDX_GUEST_V1: "https://tinfoil.sh/predicate/tdx-guest/v1",
95
+ TDX_GUEST_V2: "https://tinfoil.sh/predicate/tdx-guest/v2",
96
+ SEV_GUEST_V1: "https://tinfoil.sh/predicate/sev-snp-guest/v1",
97
+ SEV_GUEST_V2: "https://tinfoil.sh/predicate/sev-snp-guest/v2",
98
+ HARDWARE_MEASUREMENTS_V1: "https://tinfoil.sh/predicate/hardware-measurements/v1",
99
+ };
100
+ const MEASUREMENT_ERROR_MESSAGES = {
101
+ FORMAT_MISMATCH: "attestation format mismatch",
102
+ MEASUREMENT_MISMATCH: "measurement mismatch",
103
+ RTMR1_MISMATCH: "RTMR1 mismatch",
104
+ RTMR2_MISMATCH: "RTMR2 mismatch",
105
+ FEW_REGISTERS: "fewer registers than expected",
106
+ MULTI_PLATFORM_MISMATCH: "multi-platform measurement mismatch",
107
+ MULTI_PLATFORM_SEV_SNP_MISMATCH: "multi-platform SEV-SNP measurement mismatch",
108
+ };
109
+ function registersEqual(a, b) {
110
+ if (a.length !== b.length) {
111
+ return false;
112
+ }
113
+ return a.every((value, index) => value === b[index]);
114
+ }
115
+ function compareMeasurementsError(codeMeasurement, runtimeMeasurement) {
116
+ if (codeMeasurement.type === PLATFORM_TYPES.SNP_TDX_MULTI_PLATFORM_V1 &&
117
+ runtimeMeasurement.type === PLATFORM_TYPES.SNP_TDX_MULTI_PLATFORM_V1) {
118
+ if (!registersEqual(codeMeasurement.registers, runtimeMeasurement.registers)) {
119
+ return new Error(MEASUREMENT_ERROR_MESSAGES.MULTI_PLATFORM_MISMATCH);
120
+ }
121
+ return null;
122
+ }
123
+ if (runtimeMeasurement.type === PLATFORM_TYPES.SNP_TDX_MULTI_PLATFORM_V1) {
124
+ return compareMeasurementsError(runtimeMeasurement, codeMeasurement);
125
+ }
126
+ if (codeMeasurement.type === PLATFORM_TYPES.SNP_TDX_MULTI_PLATFORM_V1) {
127
+ switch (runtimeMeasurement.type) {
128
+ case PLATFORM_TYPES.TDX_GUEST_V1: {
129
+ if (codeMeasurement.registers.length < 3 || runtimeMeasurement.registers.length < 4) {
130
+ return new Error(MEASUREMENT_ERROR_MESSAGES.FEW_REGISTERS);
131
+ }
132
+ const expectedRtmr1 = codeMeasurement.registers[1];
133
+ const expectedRtmr2 = codeMeasurement.registers[2];
134
+ const actualRtmr1 = runtimeMeasurement.registers[2];
135
+ const actualRtmr2 = runtimeMeasurement.registers[3];
136
+ if (expectedRtmr1 !== actualRtmr1) {
137
+ return new Error(MEASUREMENT_ERROR_MESSAGES.RTMR1_MISMATCH);
138
+ }
139
+ if (expectedRtmr2 !== actualRtmr2) {
140
+ return new Error(MEASUREMENT_ERROR_MESSAGES.RTMR2_MISMATCH);
141
+ }
142
+ return null;
143
+ }
144
+ case PLATFORM_TYPES.SEV_GUEST_V1: {
145
+ if (codeMeasurement.registers.length < 1 || runtimeMeasurement.registers.length < 1) {
146
+ return new Error(MEASUREMENT_ERROR_MESSAGES.FEW_REGISTERS);
147
+ }
148
+ const expectedSevSnp = codeMeasurement.registers[0];
149
+ const actualSevSnp = runtimeMeasurement.registers[0];
150
+ if (expectedSevSnp !== actualSevSnp) {
151
+ return new Error(MEASUREMENT_ERROR_MESSAGES.MULTI_PLATFORM_SEV_SNP_MISMATCH);
152
+ }
153
+ return null;
154
+ }
155
+ default:
156
+ return new Error(`unsupported enclave platform for multi-platform code measurements: ${runtimeMeasurement.type}`);
157
+ }
158
+ }
159
+ if (codeMeasurement.type !== runtimeMeasurement.type) {
160
+ return new Error(MEASUREMENT_ERROR_MESSAGES.FORMAT_MISMATCH);
161
+ }
162
+ if (!registersEqual(codeMeasurement.registers, runtimeMeasurement.registers)) {
163
+ return new Error(MEASUREMENT_ERROR_MESSAGES.MEASUREMENT_MISMATCH);
164
+ }
165
+ return null;
166
+ }
167
+ export function compareMeasurementsDetailed(codeMeasurement, runtimeMeasurement) {
168
+ const error = compareMeasurementsError(codeMeasurement, runtimeMeasurement);
169
+ if (error) {
170
+ return { match: false, error };
171
+ }
172
+ return { match: true };
173
+ }
174
+ /**
175
+ * Compare two measurements according to platform-specific rules
176
+ * This is predicate function for comparing attestation measurements
177
+ * taken from https://github.com/tinfoilsh/verifier/blob/main/attestation/attestation.go
178
+ *
179
+ * @param codeMeasurement - Expected measurement from code attestation
180
+ * @param runtimeMeasurement - Actual measurement from runtime attestation
181
+ * @returns true if measurements match according to platform rules
182
+ */
183
+ export function compareMeasurements(codeMeasurement, runtimeMeasurement) {
184
+ return compareMeasurementsError(codeMeasurement, runtimeMeasurement) === null;
185
+ }
186
+ /**
187
+ * Verifier performs attestation verification for Tinfoil enclaves
188
+ *
189
+ * The verifier loads a WebAssembly module that:
190
+ * 1. Fetches the latest code release digest from GitHub
191
+ * 2. Performs runtime attestation against the enclave
192
+ * 3. Performs code attestation using the digest
193
+ * 4. Compares measurements using platform-specific logic
194
+ */
195
+ export class Verifier {
196
+ static clearVerificationCache() {
197
+ Verifier.verificationCache.clear();
198
+ }
199
+ constructor(options) {
200
+ const serverURL = options?.serverURL ?? TINFOIL_CONFIG.INFERENCE_BASE_URL;
201
+ this.serverURL = new URL(serverURL).hostname;
202
+ this.configRepo = options?.configRepo ?? TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
203
+ }
204
+ /**
205
+ * Initialize the WebAssembly module
206
+ * This loads the Go runtime and makes verification functions available
207
+ */
208
+ static async initializeWasm() {
209
+ if (Verifier.initializationPromise) {
210
+ return Verifier.initializationPromise;
211
+ }
212
+ Verifier.initializationPromise = (async () => {
213
+ try {
214
+ // Initialize globals if not already done
215
+ await initializeWasmGlobals();
216
+ Verifier.goInstance = new globalThis.Go();
217
+ // Load WASM module
218
+ const fetchFn = getFetch();
219
+ const wasmResponse = await fetchFn(Verifier.defaultWasmUrl);
220
+ if (!wasmResponse.ok) {
221
+ throw new Error(`Failed to fetch WASM: ${wasmResponse.status} ${wasmResponse.statusText}`);
222
+ }
223
+ const wasmBuffer = await wasmResponse.arrayBuffer();
224
+ const result = await WebAssembly.instantiate(wasmBuffer, Verifier.goInstance.importObject);
225
+ // Run the Go instance - this makes functions available on globalThis
226
+ Verifier.goInstance.run(result.instance);
227
+ // Wait for initialization to complete
228
+ await new Promise(resolve => setTimeout(resolve, 100));
229
+ // Ensure required functions are available
230
+ if (typeof globalThis.verifyCode === "undefined" || typeof globalThis.verifyEnclave === "undefined") {
231
+ await new Promise(resolve => setTimeout(resolve, 500));
232
+ }
233
+ // Apply log suppression if requested
234
+ if (Verifier.wasmLogsSuppressed && globalThis.fs?.writeSync) {
235
+ const fsObj = globalThis.fs;
236
+ if (!Verifier.originalFsWriteSync) {
237
+ Verifier.originalFsWriteSync = fsObj.writeSync.bind(fsObj);
238
+ }
239
+ fsObj.writeSync = function (_fd, buf) {
240
+ return buf.length;
241
+ };
242
+ }
243
+ }
244
+ catch (error) {
245
+ console.error("WASM initialization error:", error);
246
+ throw error;
247
+ }
248
+ })();
249
+ return Verifier.initializationPromise;
250
+ }
251
+ /**
252
+ * Fetch the latest release digest from GitHub
253
+ * @param configRepo - Repository name (e.g., "tinfoilsh/confidential-inference-proxy")
254
+ * @returns The digest hash
255
+ */
256
+ async fetchLatestDigest(configRepo) {
257
+ // GitHub Proxy Note:
258
+ // We use api-github-proxy.tinfoil.sh instead of the direct GitHub API to avoid
259
+ // rate limiting that could degrade UX. The proxy caches responses while the
260
+ // integrity of the data is independently verified in `verifyCode` via
261
+ // Sigstore transparency logs (Rekor). Using the proxy therefore does not
262
+ // weaken security.
263
+ const targetRepo = configRepo || this.configRepo;
264
+ const fetchFn = getFetch();
265
+ const releaseResponse = await fetchFn(`https://api-github-proxy.tinfoil.sh/repos/${targetRepo}/releases/latest`, {
266
+ headers: {
267
+ Accept: "application/vnd.github.v3+json",
268
+ "User-Agent": "tinfoil-node-client",
269
+ },
270
+ });
271
+ if (!releaseResponse.ok) {
272
+ throw new Error(`GitHub API request failed: ${releaseResponse.status} ${releaseResponse.statusText}`);
273
+ }
274
+ const releaseData = (await releaseResponse.json());
275
+ // Extract digest from release notes
276
+ const digestRegex = /Digest: `([a-f0-9]{64})`/;
277
+ const digestMatch = releaseData.body?.match(digestRegex);
278
+ if (!digestMatch) {
279
+ throw new Error("Could not find digest in release notes");
280
+ }
281
+ const digest = digestMatch[1];
282
+ return digest;
283
+ }
284
+ /**
285
+ * Perform runtime attestation on the enclave
286
+ * @param enclaveHost - The enclave hostname
287
+ * @returns Attestation response with measurement and keys
288
+ */
289
+ async verifyEnclave(enclaveHost) {
290
+ // Expose errors via explicit Promise rejection and add a timeout
291
+ return new Promise(async (resolve, reject) => {
292
+ try {
293
+ const targetHost = enclaveHost || this.serverURL;
294
+ await Verifier.initializeWasm();
295
+ if (typeof globalThis.verifyEnclave !== "function") {
296
+ reject(new Error("WASM verifyEnclave function not available"));
297
+ return;
298
+ }
299
+ let attestationResponse;
300
+ let timeoutHandle;
301
+ try {
302
+ const timeoutPromise = new Promise((_, timeoutReject) => {
303
+ timeoutHandle = setTimeout(() => timeoutReject(new Error("WASM verifyEnclave timed out after 10 seconds")), 10000);
304
+ });
305
+ attestationResponse = await Promise.race([
306
+ globalThis.verifyEnclave(targetHost),
307
+ timeoutPromise,
308
+ ]);
309
+ // Clear timeout on success
310
+ if (timeoutHandle !== undefined) {
311
+ clearTimeout(timeoutHandle);
312
+ }
313
+ }
314
+ catch (error) {
315
+ // Clear timeout on error
316
+ if (timeoutHandle !== undefined) {
317
+ clearTimeout(timeoutHandle);
318
+ }
319
+ reject(new Error(`WASM verifyEnclave failed: ${error}`));
320
+ return;
321
+ }
322
+ // Validate required fields - fail fast with explicit rejection
323
+ // At least one key must be present (TLS or HPKE)
324
+ if (!attestationResponse?.tls_public_key && !attestationResponse?.hpke_public_key) {
325
+ reject(new Error("Missing both tls_public_key and hpke_public_key in attestation response"));
326
+ return;
327
+ }
328
+ // Parse runtime measurement
329
+ let parsedRuntimeMeasurement;
330
+ try {
331
+ if (attestationResponse.measurement &&
332
+ typeof attestationResponse.measurement === "string") {
333
+ parsedRuntimeMeasurement = JSON.parse(attestationResponse.measurement);
334
+ }
335
+ else if (attestationResponse.measurement &&
336
+ typeof attestationResponse.measurement === "object") {
337
+ parsedRuntimeMeasurement = attestationResponse.measurement;
338
+ }
339
+ else {
340
+ reject(new Error("Invalid runtime measurement format"));
341
+ return;
342
+ }
343
+ }
344
+ catch (parseError) {
345
+ reject(new Error(`Failed to parse runtime measurement: ${parseError}`));
346
+ return;
347
+ }
348
+ const result = {
349
+ measurement: parsedRuntimeMeasurement,
350
+ };
351
+ // Include keys if available
352
+ if (attestationResponse.tls_public_key) {
353
+ result.tlsPublicKeyFingerprint = attestationResponse.tls_public_key;
354
+ }
355
+ if (attestationResponse.hpke_public_key) {
356
+ result.hpkePublicKey = attestationResponse.hpke_public_key;
357
+ }
358
+ resolve(result);
359
+ }
360
+ catch (outerError) {
361
+ reject(outerError);
362
+ }
363
+ });
364
+ }
365
+ /**
366
+ * Perform code attestation
367
+ * @param configRepo - Repository name
368
+ * @param digest - Code digest hash
369
+ * @returns Code measurement
370
+ */
371
+ async verifyCode(configRepo, digest) {
372
+ await Verifier.initializeWasm();
373
+ if (typeof globalThis.verifyCode !== "function") {
374
+ throw new Error("WASM verifyCode function not available");
375
+ }
376
+ const rawMeasurement = await globalThis.verifyCode(configRepo, digest);
377
+ const normalizedMeasurement = typeof rawMeasurement === 'string'
378
+ ? (() => {
379
+ try {
380
+ return JSON.parse(rawMeasurement);
381
+ }
382
+ catch (error) {
383
+ throw new Error(`Invalid code measurement format: ${error.message}`);
384
+ }
385
+ })()
386
+ : rawMeasurement;
387
+ if (!normalizedMeasurement || typeof normalizedMeasurement !== 'object') {
388
+ throw new Error('Invalid code measurement format');
389
+ }
390
+ const measurementObject = normalizedMeasurement;
391
+ if (typeof measurementObject.type !== 'string' || !Array.isArray(measurementObject.registers)) {
392
+ throw new Error('Invalid code measurement format');
393
+ }
394
+ const parsedCodeMeasurement = {
395
+ type: measurementObject.type,
396
+ registers: measurementObject.registers.map((value) => String(value))
397
+ };
398
+ return { measurement: parsedCodeMeasurement };
399
+ }
400
+ /**
401
+ * Perform attestation verification
402
+ *
403
+ * This method:
404
+ * 1. Fetches the latest code digest from GitHub releases
405
+ * 2. Calls verifyCode to get the expected measurement for the code
406
+ * 3. Calls verifyEnclave to get the actual runtime measurement
407
+ * 4. Compares measurements using platform-specific logic (see `compareMeasurements()`)
408
+ * 5. Returns the attestation response if verification succeeds
409
+ *
410
+ * @throws Error if measurements don't match or verification fails
411
+ */
412
+ async verify() {
413
+ // Get latest release digest first to include in cache key
414
+ const releaseDigest = await this.fetchLatestDigest(this.configRepo);
415
+ const cacheKey = `${this.configRepo}::${this.serverURL}::${releaseDigest}`;
416
+ const cachedResult = Verifier.verificationCache.get(cacheKey);
417
+ if (cachedResult) {
418
+ const attestation = await cachedResult;
419
+ // Ensure verification document is available even for cached results
420
+ if (!this.lastVerificationDocument) {
421
+ // Re-create the document from cached attestation
422
+ const { measurement: codeMeasurement } = await this.verifyCode(this.configRepo, releaseDigest);
423
+ this.lastVerificationDocument = {
424
+ configRepo: this.configRepo,
425
+ enclaveHost: this.serverURL,
426
+ releaseDigest: releaseDigest,
427
+ codeMeasurement,
428
+ enclaveMeasurement: attestation,
429
+ match: true, // Must be true since verification succeeded
430
+ };
431
+ }
432
+ return attestation;
433
+ }
434
+ const verificationPromise = (async () => {
435
+ // Perform code attestation and runtime attestation in parallel via wrappers
436
+ const [{ measurement: codeMeasurement }, attestation] = await Promise.all([
437
+ this.verifyCode(this.configRepo, releaseDigest),
438
+ this.verifyEnclave(this.serverURL),
439
+ ]);
440
+ // Compare measurements using platform-specific logic
441
+ const measurementsMatch = compareMeasurements(codeMeasurement, attestation.measurement);
442
+ if (!measurementsMatch) {
443
+ throw new Error(`Measurement verification failed: Code measurement (${codeMeasurement.type}) ` +
444
+ `does not match runtime measurement (${attestation.measurement.type})`);
445
+ }
446
+ // Persist a full verification document for later retrieval by clients
447
+ this.lastVerificationDocument = {
448
+ configRepo: this.configRepo,
449
+ enclaveHost: this.serverURL,
450
+ releaseDigest: releaseDigest,
451
+ codeMeasurement,
452
+ enclaveMeasurement: attestation,
453
+ match: true,
454
+ };
455
+ return attestation;
456
+ })();
457
+ Verifier.verificationCache.set(cacheKey, verificationPromise);
458
+ verificationPromise.catch(() => {
459
+ Verifier.verificationCache.delete(cacheKey);
460
+ });
461
+ return verificationPromise;
462
+ }
463
+ /**
464
+ * Returns the full verification document from the last successful verify() call
465
+ */
466
+ getVerificationDocument() {
467
+ return this.lastVerificationDocument;
468
+ }
469
+ }
470
+ Verifier.goInstance = null;
471
+ Verifier.initializationPromise = null;
472
+ Verifier.verificationCache = new Map();
473
+ Verifier.defaultWasmUrl = "https://tinfoilsh.github.io/verifier-js/tinfoil-verifier.wasm";
474
+ Verifier.originalFsWriteSync = null;
475
+ Verifier.wasmLogsSuppressed = true;
476
+ Verifier.globalsInitialized = false;
477
+ // Start initialization as soon as the module loads
478
+ function shouldAutoInitializeWasm() {
479
+ const globalAny = globalThis;
480
+ const env = globalAny.process?.env;
481
+ const autoInitFlag = env?.TINFOIL_SKIP_WASM_AUTO_INIT ?? env?.TINFOIL_DISABLE_WASM_AUTO_INIT;
482
+ if (typeof autoInitFlag === "string") {
483
+ const normalized = autoInitFlag.toLowerCase();
484
+ if (normalized === "1" || normalized === "true") {
485
+ return false;
486
+ }
487
+ }
488
+ if (env?.NODE_ENV === "test") {
489
+ return false;
490
+ }
491
+ const isNode = typeof globalAny.process?.versions?.node === "string";
492
+ if (isNode) {
493
+ return false;
494
+ }
495
+ const hasBrowserGlobals = typeof globalAny.window === "object" && typeof globalAny.document === "object";
496
+ return hasBrowserGlobals;
497
+ }
498
+ if (shouldAutoInitializeWasm()) {
499
+ void Verifier.initializeWasm().catch(error => {
500
+ console.error(error);
501
+ });
502
+ }
503
+ /**
504
+ * Control WASM log output
505
+ *
506
+ * The Go WASM runtime outputs logs through a polyfilled fs.writeSync.
507
+ * This function allows suppressing those logs without affecting other console output.
508
+ *
509
+ * @param suppress - Whether to suppress WASM logs (default: true)
510
+ */
511
+ export function suppressWasmLogs(suppress = true) {
512
+ globalThis.__tinfoilSuppressWasmLogs = suppress;
513
+ Verifier.wasmLogsSuppressed = suppress;
514
+ const fsObj = globalThis.fs;
515
+ if (!fsObj || typeof fsObj.writeSync !== "function")
516
+ return;
517
+ if (suppress) {
518
+ if (!Verifier.originalFsWriteSync) {
519
+ Verifier.originalFsWriteSync = fsObj.writeSync.bind(fsObj);
520
+ }
521
+ fsObj.writeSync = function (_fd, buf) {
522
+ return buf.length;
523
+ };
524
+ }
525
+ else if (Verifier.originalFsWriteSync) {
526
+ fsObj.writeSync = Verifier.originalFsWriteSync;
527
+ }
528
+ }
529
+ /**
530
+ * Initialize globals needed for Go WASM runtime
531
+ * This function sets up browser-like globals that the Go WASM runtime expects
532
+ */
533
+ async function initializeWasmGlobals() {
534
+ // Only initialize once
535
+ if (Verifier.globalsInitialized) {
536
+ return;
537
+ }
538
+ const root = globalThis;
539
+ // Performance API (Go runtime expects a few methods to exist)
540
+ if (!root.performance) {
541
+ root.performance = {
542
+ now: () => Date.now(),
543
+ markResourceTiming: () => { },
544
+ mark: () => { },
545
+ measure: () => { },
546
+ clearMarks: () => { },
547
+ clearMeasures: () => { },
548
+ getEntriesByName: () => [],
549
+ getEntriesByType: () => [],
550
+ getEntries: () => [],
551
+ };
552
+ }
553
+ else {
554
+ root.performance.now = root.performance.now ?? (() => Date.now());
555
+ root.performance.markResourceTiming = root.performance.markResourceTiming ?? (() => { });
556
+ root.performance.mark = root.performance.mark ?? (() => { });
557
+ root.performance.measure = root.performance.measure ?? (() => { });
558
+ root.performance.clearMarks = root.performance.clearMarks ?? (() => { });
559
+ root.performance.clearMeasures = root.performance.clearMeasures ?? (() => { });
560
+ root.performance.getEntriesByName = root.performance.getEntriesByName ?? (() => []);
561
+ root.performance.getEntriesByType = root.performance.getEntriesByType ?? (() => []);
562
+ root.performance.getEntries = root.performance.getEntries ?? (() => []);
563
+ }
564
+ // Text encoding
565
+ if (!root.TextEncoder) {
566
+ root.TextEncoder = getTextEncoder();
567
+ }
568
+ if (!root.TextDecoder) {
569
+ root.TextDecoder = getTextDecoder();
570
+ }
571
+ // Crypto API (needed by Go WASM)
572
+ ensureCrypto(root);
573
+ // Default: suppress WASM (Go) stdout/stderr logs unless explicitly enabled by caller
574
+ if (typeof root.__tinfoilSuppressWasmLogs === "undefined") {
575
+ root.__tinfoilSuppressWasmLogs = true;
576
+ }
577
+ // Force process to stay running (prevent Go from exiting Node process)
578
+ // This is a common issue with Go WASM in Node - it calls process.exit()
579
+ if (root.process && typeof root.process.exit === "function" && !root.__tinfoilProcessExitPatched) {
580
+ root.__tinfoilProcessExitPatched = true;
581
+ const originalExit = root.process.exit.bind(root.process);
582
+ root.__tinfoilOriginalProcessExit = originalExit;
583
+ // Replace process.exit to prevent the Go WASM runtime from terminating the Node.js process.
584
+ // When wasm log suppression is enabled, suppress the informational log about the ignored exit
585
+ // so callers can silence only the WASM-related noise while keeping application logs intact.
586
+ root.process.exit = ((code) => {
587
+ if (!root.__tinfoilSuppressWasmLogs) {
588
+ console.log(`Process exit called with code ${code} - ignoring to keep runtime alive`);
589
+ }
590
+ return undefined;
591
+ });
592
+ }
593
+ await loadWasmExec();
594
+ Verifier.globalsInitialized = true;
595
+ }
596
+ function ensureCrypto(root) {
597
+ const hasWorkingGetRandomValues = root.crypto && typeof root.crypto.getRandomValues === "function"
598
+ ? root.crypto
599
+ : resolveWindowCrypto(root);
600
+ if (hasWorkingGetRandomValues) {
601
+ if (!root.crypto) {
602
+ root.crypto = hasWorkingGetRandomValues;
603
+ }
604
+ return;
605
+ }
606
+ const nodeRandomBytes = resolveNodeRandomBytes();
607
+ if (!nodeRandomBytes) {
608
+ throw new Error("crypto.getRandomValues is not available in this environment");
609
+ }
610
+ const fallbackCrypto = {
611
+ getRandomValues: (buffer) => {
612
+ const bytes = nodeRandomBytes(buffer.length);
613
+ buffer.set(bytes);
614
+ return buffer;
615
+ },
616
+ };
617
+ try {
618
+ root.crypto = fallbackCrypto;
619
+ }
620
+ catch {
621
+ Object.defineProperty(root, "crypto", {
622
+ configurable: true,
623
+ enumerable: false,
624
+ value: fallbackCrypto,
625
+ writable: false,
626
+ });
627
+ }
628
+ }
629
+ function resolveWindowCrypto(root) {
630
+ const maybeWindow = root.window ?? (typeof window !== "undefined" ? window : undefined);
631
+ if (maybeWindow?.crypto && typeof maybeWindow.crypto.getRandomValues === "function") {
632
+ return maybeWindow.crypto;
633
+ }
634
+ return undefined;
635
+ }
636
+ function resolveNodeRandomBytes() {
637
+ if (!nodeRequire) {
638
+ return undefined;
639
+ }
640
+ try {
641
+ const cryptoModule = nodeRequire("crypto");
642
+ const randomBytes = typeof cryptoModule?.randomBytes === "function" ? cryptoModule.randomBytes : undefined;
643
+ if (randomBytes) {
644
+ return (size) => {
645
+ const result = randomBytes(size);
646
+ return result instanceof Uint8Array ? result : new Uint8Array(result);
647
+ };
648
+ }
649
+ }
650
+ catch {
651
+ return undefined;
652
+ }
653
+ return undefined;
654
+ }
655
+ function loadWasmExec() {
656
+ if (!wasmExecLoader) {
657
+ wasmExecLoader = (async () => {
658
+ // Prefer a dynamic import so bundlers (Next/Webpack/Vite) include the file.
659
+ // If that fails (e.g., pure Node without bundler), fall back to require.
660
+ try {
661
+ // @ts-expect-error: Local JS helper has no TS types; ambient module declared in wasm-exec.d.ts
662
+ await import("./wasm-exec.js");
663
+ }
664
+ catch {
665
+ if (nodeRequire) {
666
+ nodeRequire("./wasm-exec.js");
667
+ return;
668
+ }
669
+ throw new Error("Failed to load wasm-exec.js via dynamic import, and require() is unavailable");
670
+ }
671
+ })();
672
+ wasmExecLoader.catch(() => {
673
+ wasmExecLoader = null;
674
+ });
675
+ }
676
+ return wasmExecLoader;
677
+ }
678
+ function createNodeRequire() {
679
+ try {
680
+ return typeof require === "function" ? require : undefined;
681
+ }
682
+ catch {
683
+ return undefined;
684
+ }
685
+ }