tinfoil 0.10.0 → 0.10.9

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