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