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