tinfoil 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +686 -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 +726 -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,686 @@
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
+ case PLATFORM_TYPES.SEV_GUEST_V2: {
146
+ if (codeMeasurement.registers.length < 1 || runtimeMeasurement.registers.length < 1) {
147
+ return new Error(MEASUREMENT_ERROR_MESSAGES.FEW_REGISTERS);
148
+ }
149
+ const expectedSevSnp = codeMeasurement.registers[0];
150
+ const actualSevSnp = runtimeMeasurement.registers[0];
151
+ if (expectedSevSnp !== actualSevSnp) {
152
+ return new Error(MEASUREMENT_ERROR_MESSAGES.MULTI_PLATFORM_SEV_SNP_MISMATCH);
153
+ }
154
+ return null;
155
+ }
156
+ default:
157
+ return new Error(`unsupported enclave platform for multi-platform code measurements: ${runtimeMeasurement.type}`);
158
+ }
159
+ }
160
+ if (codeMeasurement.type !== runtimeMeasurement.type) {
161
+ return new Error(MEASUREMENT_ERROR_MESSAGES.FORMAT_MISMATCH);
162
+ }
163
+ if (!registersEqual(codeMeasurement.registers, runtimeMeasurement.registers)) {
164
+ return new Error(MEASUREMENT_ERROR_MESSAGES.MEASUREMENT_MISMATCH);
165
+ }
166
+ return null;
167
+ }
168
+ export function compareMeasurementsDetailed(codeMeasurement, runtimeMeasurement) {
169
+ const error = compareMeasurementsError(codeMeasurement, runtimeMeasurement);
170
+ if (error) {
171
+ return { match: false, error };
172
+ }
173
+ return { match: true };
174
+ }
175
+ /**
176
+ * Compare two measurements according to platform-specific rules
177
+ * This is predicate function for comparing attestation measurements
178
+ * taken from https://github.com/tinfoilsh/verifier/blob/main/attestation/attestation.go
179
+ *
180
+ * @param codeMeasurement - Expected measurement from code attestation
181
+ * @param runtimeMeasurement - Actual measurement from runtime attestation
182
+ * @returns true if measurements match according to platform rules
183
+ */
184
+ export function compareMeasurements(codeMeasurement, runtimeMeasurement) {
185
+ return compareMeasurementsError(codeMeasurement, runtimeMeasurement) === null;
186
+ }
187
+ /**
188
+ * Verifier performs attestation verification for Tinfoil enclaves
189
+ *
190
+ * The verifier loads a WebAssembly module that:
191
+ * 1. Fetches the latest code release digest from GitHub
192
+ * 2. Performs runtime attestation against the enclave
193
+ * 3. Performs code attestation using the digest
194
+ * 4. Compares measurements using platform-specific logic
195
+ */
196
+ export class Verifier {
197
+ static clearVerificationCache() {
198
+ Verifier.verificationCache.clear();
199
+ }
200
+ constructor(options) {
201
+ const serverURL = options?.serverURL ?? TINFOIL_CONFIG.INFERENCE_BASE_URL;
202
+ this.serverURL = new URL(serverURL).hostname;
203
+ this.configRepo = options?.configRepo ?? TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
204
+ }
205
+ /**
206
+ * Initialize the WebAssembly module
207
+ * This loads the Go runtime and makes verification functions available
208
+ */
209
+ static async initializeWasm() {
210
+ if (Verifier.initializationPromise) {
211
+ return Verifier.initializationPromise;
212
+ }
213
+ Verifier.initializationPromise = (async () => {
214
+ try {
215
+ // Initialize globals if not already done
216
+ await initializeWasmGlobals();
217
+ Verifier.goInstance = new globalThis.Go();
218
+ // Load WASM module
219
+ const fetchFn = getFetch();
220
+ const wasmResponse = await fetchFn(Verifier.defaultWasmUrl);
221
+ if (!wasmResponse.ok) {
222
+ throw new Error(`Failed to fetch WASM: ${wasmResponse.status} ${wasmResponse.statusText}`);
223
+ }
224
+ const wasmBuffer = await wasmResponse.arrayBuffer();
225
+ const result = await WebAssembly.instantiate(wasmBuffer, Verifier.goInstance.importObject);
226
+ // Run the Go instance - this makes functions available on globalThis
227
+ Verifier.goInstance.run(result.instance);
228
+ // Wait for initialization to complete
229
+ await new Promise(resolve => setTimeout(resolve, 100));
230
+ // Ensure required functions are available
231
+ if (typeof globalThis.verifyCode === "undefined" || typeof globalThis.verifyEnclave === "undefined") {
232
+ await new Promise(resolve => setTimeout(resolve, 500));
233
+ }
234
+ // Apply log suppression if requested
235
+ if (Verifier.wasmLogsSuppressed && globalThis.fs?.writeSync) {
236
+ const fsObj = globalThis.fs;
237
+ if (!Verifier.originalFsWriteSync) {
238
+ Verifier.originalFsWriteSync = fsObj.writeSync.bind(fsObj);
239
+ }
240
+ fsObj.writeSync = function (_fd, buf) {
241
+ return buf.length;
242
+ };
243
+ }
244
+ }
245
+ catch (error) {
246
+ console.error("WASM initialization error:", error);
247
+ throw error;
248
+ }
249
+ })();
250
+ return Verifier.initializationPromise;
251
+ }
252
+ /**
253
+ * Fetch the latest release digest from GitHub
254
+ * @param configRepo - Repository name (e.g., "tinfoilsh/confidential-inference-proxy")
255
+ * @returns The digest hash
256
+ */
257
+ async fetchLatestDigest(configRepo) {
258
+ // GitHub Proxy Note:
259
+ // We use api-github-proxy.tinfoil.sh instead of the direct GitHub API to avoid
260
+ // rate limiting that could degrade UX. The proxy caches responses while the
261
+ // integrity of the data is independently verified in `verifyCode` via
262
+ // Sigstore transparency logs (Rekor). Using the proxy therefore does not
263
+ // weaken security.
264
+ const targetRepo = configRepo || this.configRepo;
265
+ const fetchFn = getFetch();
266
+ const releaseResponse = await fetchFn(`https://api-github-proxy.tinfoil.sh/repos/${targetRepo}/releases/latest`, {
267
+ headers: {
268
+ Accept: "application/vnd.github.v3+json",
269
+ "User-Agent": "tinfoil-node-client",
270
+ },
271
+ });
272
+ if (!releaseResponse.ok) {
273
+ throw new Error(`GitHub API request failed: ${releaseResponse.status} ${releaseResponse.statusText}`);
274
+ }
275
+ const releaseData = (await releaseResponse.json());
276
+ // Extract digest from release notes
277
+ const digestRegex = /Digest: `([a-f0-9]{64})`/;
278
+ const digestMatch = releaseData.body?.match(digestRegex);
279
+ if (!digestMatch) {
280
+ throw new Error("Could not find digest in release notes");
281
+ }
282
+ const digest = digestMatch[1];
283
+ return digest;
284
+ }
285
+ /**
286
+ * Perform runtime attestation on the enclave
287
+ * @param enclaveHost - The enclave hostname
288
+ * @returns Attestation response with measurement and keys
289
+ */
290
+ async verifyEnclave(enclaveHost) {
291
+ // Expose errors via explicit Promise rejection and add a timeout
292
+ return new Promise(async (resolve, reject) => {
293
+ try {
294
+ const targetHost = enclaveHost || this.serverURL;
295
+ await Verifier.initializeWasm();
296
+ if (typeof globalThis.verifyEnclave !== "function") {
297
+ reject(new Error("WASM verifyEnclave function not available"));
298
+ return;
299
+ }
300
+ let attestationResponse;
301
+ let timeoutHandle;
302
+ try {
303
+ const timeoutPromise = new Promise((_, timeoutReject) => {
304
+ timeoutHandle = setTimeout(() => timeoutReject(new Error("WASM verifyEnclave timed out after 10 seconds")), 10000);
305
+ });
306
+ attestationResponse = await Promise.race([
307
+ globalThis.verifyEnclave(targetHost),
308
+ timeoutPromise,
309
+ ]);
310
+ // Clear timeout on success
311
+ if (timeoutHandle !== undefined) {
312
+ clearTimeout(timeoutHandle);
313
+ }
314
+ }
315
+ catch (error) {
316
+ // Clear timeout on error
317
+ if (timeoutHandle !== undefined) {
318
+ clearTimeout(timeoutHandle);
319
+ }
320
+ reject(new Error(`WASM verifyEnclave failed: ${error}`));
321
+ return;
322
+ }
323
+ // Validate required fields - fail fast with explicit rejection
324
+ // At least one key must be present (TLS or HPKE)
325
+ if (!attestationResponse?.tls_public_key && !attestationResponse?.hpke_public_key) {
326
+ reject(new Error("Missing both tls_public_key and hpke_public_key in attestation response"));
327
+ return;
328
+ }
329
+ // Parse runtime measurement
330
+ let parsedRuntimeMeasurement;
331
+ try {
332
+ if (attestationResponse.measurement &&
333
+ typeof attestationResponse.measurement === "string") {
334
+ parsedRuntimeMeasurement = JSON.parse(attestationResponse.measurement);
335
+ }
336
+ else if (attestationResponse.measurement &&
337
+ typeof attestationResponse.measurement === "object") {
338
+ parsedRuntimeMeasurement = attestationResponse.measurement;
339
+ }
340
+ else {
341
+ reject(new Error("Invalid runtime measurement format"));
342
+ return;
343
+ }
344
+ }
345
+ catch (parseError) {
346
+ reject(new Error(`Failed to parse runtime measurement: ${parseError}`));
347
+ return;
348
+ }
349
+ const result = {
350
+ measurement: parsedRuntimeMeasurement,
351
+ };
352
+ // Include keys if available
353
+ if (attestationResponse.tls_public_key) {
354
+ result.tlsPublicKeyFingerprint = attestationResponse.tls_public_key;
355
+ }
356
+ if (attestationResponse.hpke_public_key) {
357
+ result.hpkePublicKey = attestationResponse.hpke_public_key;
358
+ }
359
+ resolve(result);
360
+ }
361
+ catch (outerError) {
362
+ reject(outerError);
363
+ }
364
+ });
365
+ }
366
+ /**
367
+ * Perform code attestation
368
+ * @param configRepo - Repository name
369
+ * @param digest - Code digest hash
370
+ * @returns Code measurement
371
+ */
372
+ async verifyCode(configRepo, digest) {
373
+ await Verifier.initializeWasm();
374
+ if (typeof globalThis.verifyCode !== "function") {
375
+ throw new Error("WASM verifyCode function not available");
376
+ }
377
+ const rawMeasurement = await globalThis.verifyCode(configRepo, digest);
378
+ const normalizedMeasurement = typeof rawMeasurement === 'string'
379
+ ? (() => {
380
+ try {
381
+ return JSON.parse(rawMeasurement);
382
+ }
383
+ catch (error) {
384
+ throw new Error(`Invalid code measurement format: ${error.message}`);
385
+ }
386
+ })()
387
+ : rawMeasurement;
388
+ if (!normalizedMeasurement || typeof normalizedMeasurement !== 'object') {
389
+ throw new Error('Invalid code measurement format');
390
+ }
391
+ const measurementObject = normalizedMeasurement;
392
+ if (typeof measurementObject.type !== 'string' || !Array.isArray(measurementObject.registers)) {
393
+ throw new Error('Invalid code measurement format');
394
+ }
395
+ const parsedCodeMeasurement = {
396
+ type: measurementObject.type,
397
+ registers: measurementObject.registers.map((value) => String(value))
398
+ };
399
+ return { measurement: parsedCodeMeasurement };
400
+ }
401
+ /**
402
+ * Perform attestation verification
403
+ *
404
+ * This method:
405
+ * 1. Fetches the latest code digest from GitHub releases
406
+ * 2. Calls verifyCode to get the expected measurement for the code
407
+ * 3. Calls verifyEnclave to get the actual runtime measurement
408
+ * 4. Compares measurements using platform-specific logic (see `compareMeasurements()`)
409
+ * 5. Returns the attestation response if verification succeeds
410
+ *
411
+ * @throws Error if measurements don't match or verification fails
412
+ */
413
+ async verify() {
414
+ // Get latest release digest first to include in cache key
415
+ const releaseDigest = await this.fetchLatestDigest(this.configRepo);
416
+ const cacheKey = `${this.configRepo}::${this.serverURL}::${releaseDigest}`;
417
+ const cachedResult = Verifier.verificationCache.get(cacheKey);
418
+ if (cachedResult) {
419
+ const attestation = await cachedResult;
420
+ // Ensure verification document is available even for cached results
421
+ if (!this.lastVerificationDocument) {
422
+ // Re-create the document from cached attestation
423
+ const { measurement: codeMeasurement } = await this.verifyCode(this.configRepo, releaseDigest);
424
+ this.lastVerificationDocument = {
425
+ configRepo: this.configRepo,
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;
434
+ }
435
+ const verificationPromise = (async () => {
436
+ // Perform code attestation and runtime attestation in parallel via wrappers
437
+ const [{ measurement: codeMeasurement }, attestation] = await Promise.all([
438
+ this.verifyCode(this.configRepo, releaseDigest),
439
+ this.verifyEnclave(this.serverURL),
440
+ ]);
441
+ // Compare measurements using platform-specific logic
442
+ const measurementsMatchError = compareMeasurementsError(codeMeasurement, attestation.measurement);
443
+ if (measurementsMatchError) {
444
+ throw new Error(`Measurement verification failed: Code measurement (${codeMeasurement.type}) ` +
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;
463
+ }
464
+ /**
465
+ * Returns the full verification document from the last successful verify() call
466
+ */
467
+ getVerificationDocument() {
468
+ return this.lastVerificationDocument;
469
+ }
470
+ }
471
+ Verifier.goInstance = null;
472
+ Verifier.initializationPromise = null;
473
+ Verifier.verificationCache = new Map();
474
+ Verifier.defaultWasmUrl = "https://tinfoilsh.github.io/verifier-js/tinfoil-verifier.wasm";
475
+ Verifier.originalFsWriteSync = null;
476
+ Verifier.wasmLogsSuppressed = true;
477
+ Verifier.globalsInitialized = false;
478
+ // Start initialization as soon as the module loads
479
+ function shouldAutoInitializeWasm() {
480
+ const globalAny = globalThis;
481
+ const env = globalAny.process?.env;
482
+ const autoInitFlag = env?.TINFOIL_SKIP_WASM_AUTO_INIT ?? env?.TINFOIL_DISABLE_WASM_AUTO_INIT;
483
+ if (typeof autoInitFlag === "string") {
484
+ const normalized = autoInitFlag.toLowerCase();
485
+ if (normalized === "1" || normalized === "true") {
486
+ return false;
487
+ }
488
+ }
489
+ if (env?.NODE_ENV === "test") {
490
+ return false;
491
+ }
492
+ const isNode = typeof globalAny.process?.versions?.node === "string";
493
+ if (isNode) {
494
+ return false;
495
+ }
496
+ const hasBrowserGlobals = typeof globalAny.window === "object" && typeof globalAny.document === "object";
497
+ return hasBrowserGlobals;
498
+ }
499
+ if (shouldAutoInitializeWasm()) {
500
+ void Verifier.initializeWasm().catch(error => {
501
+ console.error(error);
502
+ });
503
+ }
504
+ /**
505
+ * Control WASM log output
506
+ *
507
+ * The Go WASM runtime outputs logs through a polyfilled fs.writeSync.
508
+ * This function allows suppressing those logs without affecting other console output.
509
+ *
510
+ * @param suppress - Whether to suppress WASM logs (default: true)
511
+ */
512
+ export function suppressWasmLogs(suppress = true) {
513
+ globalThis.__tinfoilSuppressWasmLogs = suppress;
514
+ Verifier.wasmLogsSuppressed = suppress;
515
+ const fsObj = globalThis.fs;
516
+ if (!fsObj || typeof fsObj.writeSync !== "function")
517
+ return;
518
+ if (suppress) {
519
+ if (!Verifier.originalFsWriteSync) {
520
+ Verifier.originalFsWriteSync = fsObj.writeSync.bind(fsObj);
521
+ }
522
+ fsObj.writeSync = function (_fd, buf) {
523
+ return buf.length;
524
+ };
525
+ }
526
+ else if (Verifier.originalFsWriteSync) {
527
+ fsObj.writeSync = Verifier.originalFsWriteSync;
528
+ }
529
+ }
530
+ /**
531
+ * Initialize globals needed for Go WASM runtime
532
+ * This function sets up browser-like globals that the Go WASM runtime expects
533
+ */
534
+ async function initializeWasmGlobals() {
535
+ // Only initialize once
536
+ if (Verifier.globalsInitialized) {
537
+ return;
538
+ }
539
+ const root = globalThis;
540
+ // Performance API (Go runtime expects a few methods to exist)
541
+ if (!root.performance) {
542
+ root.performance = {
543
+ now: () => Date.now(),
544
+ markResourceTiming: () => { },
545
+ mark: () => { },
546
+ measure: () => { },
547
+ clearMarks: () => { },
548
+ clearMeasures: () => { },
549
+ getEntriesByName: () => [],
550
+ getEntriesByType: () => [],
551
+ getEntries: () => [],
552
+ };
553
+ }
554
+ else {
555
+ root.performance.now = root.performance.now ?? (() => Date.now());
556
+ root.performance.markResourceTiming = root.performance.markResourceTiming ?? (() => { });
557
+ root.performance.mark = root.performance.mark ?? (() => { });
558
+ root.performance.measure = root.performance.measure ?? (() => { });
559
+ root.performance.clearMarks = root.performance.clearMarks ?? (() => { });
560
+ root.performance.clearMeasures = root.performance.clearMeasures ?? (() => { });
561
+ root.performance.getEntriesByName = root.performance.getEntriesByName ?? (() => []);
562
+ root.performance.getEntriesByType = root.performance.getEntriesByType ?? (() => []);
563
+ root.performance.getEntries = root.performance.getEntries ?? (() => []);
564
+ }
565
+ // Text encoding
566
+ if (!root.TextEncoder) {
567
+ root.TextEncoder = getTextEncoder();
568
+ }
569
+ if (!root.TextDecoder) {
570
+ root.TextDecoder = getTextDecoder();
571
+ }
572
+ // Crypto API (needed by Go WASM)
573
+ ensureCrypto(root);
574
+ // Default: suppress WASM (Go) stdout/stderr logs unless explicitly enabled by caller
575
+ if (typeof root.__tinfoilSuppressWasmLogs === "undefined") {
576
+ root.__tinfoilSuppressWasmLogs = true;
577
+ }
578
+ // Force process to stay running (prevent Go from exiting Node process)
579
+ // This is a common issue with Go WASM in Node - it calls process.exit()
580
+ if (root.process && typeof root.process.exit === "function" && !root.__tinfoilProcessExitPatched) {
581
+ root.__tinfoilProcessExitPatched = true;
582
+ const originalExit = root.process.exit.bind(root.process);
583
+ root.__tinfoilOriginalProcessExit = originalExit;
584
+ // Replace process.exit to prevent the Go WASM runtime from terminating the Node.js process.
585
+ // When wasm log suppression is enabled, suppress the informational log about the ignored exit
586
+ // so callers can silence only the WASM-related noise while keeping application logs intact.
587
+ root.process.exit = ((code) => {
588
+ if (!root.__tinfoilSuppressWasmLogs) {
589
+ console.log(`Process exit called with code ${code} - ignoring to keep runtime alive`);
590
+ }
591
+ return undefined;
592
+ });
593
+ }
594
+ await loadWasmExec();
595
+ Verifier.globalsInitialized = true;
596
+ }
597
+ function ensureCrypto(root) {
598
+ const hasWorkingGetRandomValues = root.crypto && typeof root.crypto.getRandomValues === "function"
599
+ ? root.crypto
600
+ : resolveWindowCrypto(root);
601
+ if (hasWorkingGetRandomValues) {
602
+ if (!root.crypto) {
603
+ root.crypto = hasWorkingGetRandomValues;
604
+ }
605
+ return;
606
+ }
607
+ const nodeRandomBytes = resolveNodeRandomBytes();
608
+ if (!nodeRandomBytes) {
609
+ throw new Error("crypto.getRandomValues is not available in this environment");
610
+ }
611
+ const fallbackCrypto = {
612
+ getRandomValues: (buffer) => {
613
+ const bytes = nodeRandomBytes(buffer.length);
614
+ buffer.set(bytes);
615
+ return buffer;
616
+ },
617
+ };
618
+ try {
619
+ root.crypto = fallbackCrypto;
620
+ }
621
+ catch {
622
+ Object.defineProperty(root, "crypto", {
623
+ configurable: true,
624
+ enumerable: false,
625
+ value: fallbackCrypto,
626
+ writable: false,
627
+ });
628
+ }
629
+ }
630
+ function resolveWindowCrypto(root) {
631
+ const maybeWindow = root.window ?? (typeof window !== "undefined" ? window : undefined);
632
+ if (maybeWindow?.crypto && typeof maybeWindow.crypto.getRandomValues === "function") {
633
+ return maybeWindow.crypto;
634
+ }
635
+ return undefined;
636
+ }
637
+ function resolveNodeRandomBytes() {
638
+ if (!nodeRequire) {
639
+ return undefined;
640
+ }
641
+ try {
642
+ const cryptoModule = nodeRequire("crypto");
643
+ const randomBytes = typeof cryptoModule?.randomBytes === "function" ? cryptoModule.randomBytes : undefined;
644
+ if (randomBytes) {
645
+ return (size) => {
646
+ const result = randomBytes(size);
647
+ return result instanceof Uint8Array ? result : new Uint8Array(result);
648
+ };
649
+ }
650
+ }
651
+ catch {
652
+ return undefined;
653
+ }
654
+ return undefined;
655
+ }
656
+ function loadWasmExec() {
657
+ if (!wasmExecLoader) {
658
+ wasmExecLoader = (async () => {
659
+ // Prefer a dynamic import so bundlers (Next/Webpack/Vite) include the file.
660
+ // If that fails (e.g., pure Node without bundler), fall back to require.
661
+ try {
662
+ // @ts-expect-error: Local JS helper has no TS types; ambient module declared in wasm-exec.d.ts
663
+ await import("./wasm-exec.js");
664
+ }
665
+ catch {
666
+ if (nodeRequire) {
667
+ nodeRequire("./wasm-exec.js");
668
+ return;
669
+ }
670
+ throw new Error("Failed to load wasm-exec.js via dynamic import, and require() is unavailable");
671
+ }
672
+ })();
673
+ wasmExecLoader.catch(() => {
674
+ wasmExecLoader = null;
675
+ });
676
+ }
677
+ return wasmExecLoader;
678
+ }
679
+ function createNodeRequire() {
680
+ try {
681
+ return typeof require === "function" ? require : undefined;
682
+ }
683
+ catch {
684
+ return undefined;
685
+ }
686
+ }