tinfoil 0.8.3 → 0.8.5

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 (47) hide show
  1. package/dist/ai-sdk-provider.d.ts +1 -11
  2. package/dist/ai-sdk-provider.js +9 -151
  3. package/dist/client.browser.d.ts +3 -2
  4. package/dist/client.browser.js +13 -28
  5. package/dist/client.d.ts +4 -3
  6. package/dist/client.js +13 -153
  7. package/dist/config.d.ts +4 -3
  8. package/dist/config.js +4 -3
  9. package/dist/encrypted-body-fetch.d.ts +2 -2
  10. package/dist/encrypted-body-fetch.js +4 -4
  11. package/dist/esm/ai-sdk-provider.d.ts +1 -11
  12. package/dist/esm/ai-sdk-provider.js +9 -148
  13. package/dist/esm/client.browser.d.ts +3 -2
  14. package/dist/esm/client.browser.js +13 -28
  15. package/dist/esm/client.d.ts +4 -3
  16. package/dist/esm/client.js +13 -153
  17. package/dist/esm/config.d.ts +4 -3
  18. package/dist/esm/config.js +4 -3
  19. package/dist/esm/encrypted-body-fetch.d.ts +2 -2
  20. package/dist/esm/encrypted-body-fetch.js +4 -4
  21. package/dist/esm/index.browser.d.ts +2 -1
  22. package/dist/esm/index.browser.js +2 -1
  23. package/dist/esm/index.d.ts +1 -0
  24. package/dist/esm/index.js +1 -0
  25. package/dist/esm/pinned-tls-fetch.d.ts +1 -0
  26. package/dist/esm/pinned-tls-fetch.js +110 -0
  27. package/dist/esm/secure-client.browser.d.ts +20 -0
  28. package/dist/esm/secure-client.browser.js +57 -0
  29. package/dist/esm/secure-client.d.ts +20 -0
  30. package/dist/esm/secure-client.js +69 -0
  31. package/dist/esm/verifier.js +2 -2
  32. package/dist/index.browser.d.ts +2 -1
  33. package/dist/index.browser.js +4 -2
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1 -0
  36. package/dist/pinned-tls-fetch.d.ts +1 -0
  37. package/dist/pinned-tls-fetch.js +116 -0
  38. package/dist/secure-client.browser.d.ts +20 -0
  39. package/dist/secure-client.browser.js +61 -0
  40. package/dist/secure-client.d.ts +20 -0
  41. package/dist/secure-client.js +73 -0
  42. package/dist/verifier.js +2 -2
  43. package/package.json +8 -3
  44. package/dist/ai-sdk-provider.browser.d.ts +0 -7
  45. package/dist/ai-sdk-provider.browser.js +0 -30
  46. package/dist/esm/ai-sdk-provider.browser.d.ts +0 -7
  47. package/dist/esm/ai-sdk-provider.browser.js +0 -27
@@ -0,0 +1,110 @@
1
+ import https from "https";
2
+ import { checkServerIdentity as tlsCheckServerIdentity } from "tls";
3
+ import { X509Certificate, createHash } from "crypto";
4
+ import { Readable } from "stream";
5
+ export function createPinnedTlsFetch(expectedFingerprintHex) {
6
+ return (async (input, init) => {
7
+ // Normalize URL
8
+ const makeURL = (value) => {
9
+ if (typeof value === "string")
10
+ return new URL(value);
11
+ if (value instanceof URL)
12
+ return value;
13
+ return new URL(value.url);
14
+ };
15
+ const url = makeURL(input);
16
+ if (url.protocol !== "https:") {
17
+ throw new Error(`HTTP connections are not allowed. Use HTTPS. URL: ${url.toString()}`);
18
+ }
19
+ // Gather method and headers
20
+ const method = (init?.method || input.method || "GET").toUpperCase();
21
+ const headers = new Headers(init?.headers || input?.headers || {});
22
+ const headerObj = {};
23
+ headers.forEach((v, k) => {
24
+ headerObj[k] = v;
25
+ });
26
+ // Resolve body
27
+ let body = init?.body;
28
+ if (!body && input instanceof Request) {
29
+ // If the original was a Request with a body, read it
30
+ try {
31
+ const buf = await input.arrayBuffer();
32
+ if (buf && buf.byteLength)
33
+ body = Buffer.from(buf);
34
+ }
35
+ catch { }
36
+ }
37
+ // Convert web streams to Node streams if needed
38
+ if (body && typeof body.getReader === "function") {
39
+ body = Readable.fromWeb(body);
40
+ }
41
+ if (body instanceof ArrayBuffer) {
42
+ body = Buffer.from(body);
43
+ }
44
+ if (ArrayBuffer.isView(body)) {
45
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
46
+ }
47
+ const requestOptions = {
48
+ protocol: url.protocol,
49
+ hostname: url.hostname,
50
+ port: url.port ? Number(url.port) : 443,
51
+ path: `${url.pathname}${url.search}`,
52
+ method,
53
+ headers: headerObj,
54
+ checkServerIdentity: (host, cert) => {
55
+ const raw = cert.raw;
56
+ if (!raw) {
57
+ return new Error("Certificate raw bytes are unavailable for pinning");
58
+ }
59
+ const x509 = new X509Certificate(raw);
60
+ const publicKeyDer = x509.publicKey.export({ type: "spki", format: "der" });
61
+ const fp = createHash("sha256").update(publicKeyDer).digest("hex");
62
+ if (fp !== expectedFingerprintHex) {
63
+ return new Error(`Certificate public key fingerprint mismatch. Expected: ${expectedFingerprintHex}, Got: ${fp}`);
64
+ }
65
+ return tlsCheckServerIdentity(host, cert);
66
+ },
67
+ };
68
+ const { signal } = init || {};
69
+ const res = await new Promise((resolve, reject) => {
70
+ const req = https.request(requestOptions, resolve);
71
+ req.on("error", reject);
72
+ if (signal) {
73
+ if (signal.aborted) {
74
+ req.destroy(new Error("Request aborted"));
75
+ return;
76
+ }
77
+ signal.addEventListener("abort", () => req.destroy(new Error("Request aborted")));
78
+ }
79
+ if (body === undefined || body === null) {
80
+ req.end();
81
+ }
82
+ else if (typeof body === "string" || Buffer.isBuffer(body) || ArrayBuffer.isView(body)) {
83
+ req.end(body);
84
+ }
85
+ else if (typeof body.pipe === "function") {
86
+ body.pipe(req);
87
+ }
88
+ else {
89
+ // Fallback: try to serialize objects
90
+ req.end(String(body));
91
+ }
92
+ });
93
+ const responseHeaders = new Headers();
94
+ for (const [k, v] of Object.entries(res.headers)) {
95
+ if (Array.isArray(v)) {
96
+ v.forEach(item => responseHeaders.append(k, item));
97
+ }
98
+ else if (v != null) {
99
+ responseHeaders.set(k, String(v));
100
+ }
101
+ }
102
+ // Convert Node stream to Web ReadableStream
103
+ const webStream = Readable.toWeb(res);
104
+ return new Response(webStream, {
105
+ status: res.statusCode || 0,
106
+ statusText: res.statusMessage || "",
107
+ headers: responseHeaders,
108
+ });
109
+ });
110
+ }
@@ -0,0 +1,20 @@
1
+ import type { VerificationDocument } from "./verifier";
2
+ interface SecureClientOptions {
3
+ baseURL?: string;
4
+ enclaveURL?: string;
5
+ configRepo?: string;
6
+ }
7
+ export declare class SecureClient {
8
+ private initPromise;
9
+ private verificationDocument;
10
+ private _fetch;
11
+ private readonly baseURL?;
12
+ private readonly enclaveURL?;
13
+ private readonly configRepo?;
14
+ constructor(options?: SecureClientOptions);
15
+ ready(): Promise<void>;
16
+ private initSecureClient;
17
+ getVerificationDocument(): Promise<VerificationDocument>;
18
+ get fetch(): typeof fetch;
19
+ }
20
+ export {};
@@ -0,0 +1,57 @@
1
+ import { Verifier } from "./verifier";
2
+ import { TINFOIL_CONFIG } from "./config";
3
+ import { createEncryptedBodyFetch } from "./encrypted-body-fetch";
4
+ import { isRealBrowser } from "./env";
5
+ export class SecureClient {
6
+ constructor(options = {}) {
7
+ this.initPromise = null;
8
+ this.verificationDocument = null;
9
+ this._fetch = null;
10
+ this.baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
11
+ this.enclaveURL = options.enclaveURL || TINFOIL_CONFIG.ENCLAVE_URL;
12
+ this.configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
13
+ }
14
+ async ready() {
15
+ if (!this.initPromise) {
16
+ this.initPromise = this.initSecureClient();
17
+ }
18
+ return this.initPromise;
19
+ }
20
+ async initSecureClient() {
21
+ const verifier = new Verifier({
22
+ serverURL: this.enclaveURL,
23
+ configRepo: this.configRepo,
24
+ });
25
+ await verifier.verify();
26
+ const doc = verifier.getVerificationDocument();
27
+ if (!doc) {
28
+ throw new Error("Verification document not available after successful verification");
29
+ }
30
+ this.verificationDocument = doc;
31
+ const hpkePublicKey = this.verificationDocument.enclaveMeasurement.hpkePublicKey;
32
+ if (!hpkePublicKey) {
33
+ if (isRealBrowser()) {
34
+ throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
35
+ "Only HPKE-enabled enclaves can be used in browser environments.");
36
+ }
37
+ throw new Error("HPKE public key is required in browser environments");
38
+ }
39
+ this._fetch = createEncryptedBodyFetch(this.baseURL, hpkePublicKey, this.enclaveURL);
40
+ }
41
+ async getVerificationDocument() {
42
+ if (!this.initPromise) {
43
+ await this.ready();
44
+ }
45
+ await this.initPromise;
46
+ if (!this.verificationDocument) {
47
+ throw new Error("Verification document unavailable: client not verified yet");
48
+ }
49
+ return this.verificationDocument;
50
+ }
51
+ get fetch() {
52
+ return async (input, init) => {
53
+ await this.ready();
54
+ return this._fetch(input, init);
55
+ };
56
+ }
57
+ }
@@ -0,0 +1,20 @@
1
+ import type { VerificationDocument } from "./verifier";
2
+ interface SecureClientOptions {
3
+ baseURL?: string;
4
+ enclaveURL?: string;
5
+ configRepo?: string;
6
+ }
7
+ export declare class SecureClient {
8
+ private initPromise;
9
+ private verificationDocument;
10
+ private _fetch;
11
+ private readonly baseURL?;
12
+ private readonly enclaveURL?;
13
+ private readonly configRepo?;
14
+ constructor(options?: SecureClientOptions);
15
+ ready(): Promise<void>;
16
+ private initSecureClient;
17
+ getVerificationDocument(): Promise<VerificationDocument>;
18
+ get fetch(): typeof fetch;
19
+ }
20
+ export {};
@@ -0,0 +1,69 @@
1
+ import { Verifier } from "./verifier";
2
+ import { createEncryptedBodyFetch } from "./encrypted-body-fetch";
3
+ import { createPinnedTlsFetch } from "./pinned-tls-fetch";
4
+ import { TINFOIL_CONFIG } from "./config";
5
+ import { isRealBrowser } from "./env";
6
+ export class SecureClient {
7
+ constructor(options = {}) {
8
+ this.initPromise = null;
9
+ this.verificationDocument = null;
10
+ this._fetch = null;
11
+ this.baseURL = options.baseURL || TINFOIL_CONFIG.INFERENCE_BASE_URL;
12
+ this.enclaveURL = options.enclaveURL || TINFOIL_CONFIG.ENCLAVE_URL;
13
+ this.configRepo = options.configRepo || TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
14
+ }
15
+ async ready() {
16
+ if (!this.initPromise) {
17
+ this.initPromise = this.initSecureClient();
18
+ }
19
+ return this.initPromise;
20
+ }
21
+ async initSecureClient() {
22
+ const verifier = new Verifier({
23
+ serverURL: this.enclaveURL,
24
+ configRepo: this.configRepo,
25
+ });
26
+ await verifier.verify();
27
+ const doc = verifier.getVerificationDocument();
28
+ if (!doc) {
29
+ throw new Error("Verification document not available after successful verification");
30
+ }
31
+ this.verificationDocument = doc;
32
+ // Extract keys from the verification document
33
+ const { hpkePublicKey, tlsPublicKeyFingerprint } = this.verificationDocument.enclaveMeasurement;
34
+ let fetchFunction;
35
+ if (hpkePublicKey) {
36
+ // HPKE available: use encrypted body fetch
37
+ fetchFunction = createEncryptedBodyFetch(this.baseURL, hpkePublicKey, this.enclaveURL);
38
+ }
39
+ else {
40
+ // HPKE not available: check if we're in a browser
41
+ if (isRealBrowser()) {
42
+ throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
43
+ "Only HPKE-enabled enclaves can be used in browser environments.");
44
+ }
45
+ // Node.js environment: fall back to TLS-only verification using pinned TLS fetch
46
+ if (!tlsPublicKeyFingerprint) {
47
+ throw new Error("Neither HPKE public key nor TLS public key fingerprint available for verification");
48
+ }
49
+ fetchFunction = createPinnedTlsFetch(tlsPublicKeyFingerprint);
50
+ }
51
+ this._fetch = fetchFunction;
52
+ }
53
+ async getVerificationDocument() {
54
+ if (!this.initPromise) {
55
+ await this.ready();
56
+ }
57
+ await this.initPromise;
58
+ if (!this.verificationDocument) {
59
+ throw new Error("Verification document unavailable: client not verified yet");
60
+ }
61
+ return this.verificationDocument;
62
+ }
63
+ get fetch() {
64
+ return async (input, init) => {
65
+ await this.ready();
66
+ return this._fetch(input, init);
67
+ };
68
+ }
69
+ }
@@ -417,8 +417,8 @@ export class Verifier {
417
417
  // Compare measurements using platform-specific logic
418
418
  const measurementsMatchError = compareMeasurementsError(codeMeasurement, attestation.measurement);
419
419
  if (measurementsMatchError) {
420
- throw new Error(`Measurement verification failed: Code measurement (${codeMeasurement.type}) ` +
421
- `does not match runtime measurement (${attestation.measurement.type}): ${measurementsMatchError.message}`);
420
+ throw new Error(`Verification failed: measurements did not match.\nCode measurement (${codeMeasurement.type}: ${codeMeasurement.registers})\n` +
421
+ `Runtime measurement (${attestation.measurement.type}: ${attestation.measurement.registers}:)\n ${measurementsMatchError.message}`);
422
422
  }
423
423
  // Persist a full verification document for later retrieval by clients
424
424
  this.lastVerificationDocument = {
@@ -2,5 +2,6 @@ export { TinfoilAI } from "./client.browser";
2
2
  export { TinfoilAI as default } from "./client.browser";
3
3
  export * from "./verifier";
4
4
  export * from "./verification-runner";
5
- export * from "./ai-sdk-provider.browser";
5
+ export * from "./ai-sdk-provider";
6
6
  export * from "./config";
7
+ export { SecureClient } from "tinfoil/secure-client";
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.default = exports.TinfoilAI = void 0;
17
+ exports.SecureClient = exports.default = exports.TinfoilAI = void 0;
18
18
  // Browser-safe entry point: avoids Node built-ins
19
19
  var client_browser_1 = require("./client.browser");
20
20
  Object.defineProperty(exports, "TinfoilAI", { enumerable: true, get: function () { return client_browser_1.TinfoilAI; } });
@@ -22,5 +22,7 @@ var client_browser_2 = require("./client.browser");
22
22
  Object.defineProperty(exports, "default", { enumerable: true, get: function () { return client_browser_2.TinfoilAI; } });
23
23
  __exportStar(require("./verifier"), exports);
24
24
  __exportStar(require("./verification-runner"), exports);
25
- __exportStar(require("./ai-sdk-provider.browser"), exports);
25
+ __exportStar(require("./ai-sdk-provider"), exports);
26
26
  __exportStar(require("./config"), exports);
27
+ var secure_client_1 = require("tinfoil/secure-client");
28
+ Object.defineProperty(exports, "SecureClient", { enumerable: true, get: function () { return secure_client_1.SecureClient; } });
package/dist/index.d.ts CHANGED
@@ -4,4 +4,5 @@ export * from "./verifier";
4
4
  export * from "./verification-runner";
5
5
  export * from "./ai-sdk-provider";
6
6
  export * from "./config";
7
+ export * from "tinfoil/secure-client";
7
8
  export { type Uploadable, toFile, APIPromise, PagePromise, OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "openai";
package/dist/index.js CHANGED
@@ -25,6 +25,7 @@ __exportStar(require("./verifier"), exports);
25
25
  __exportStar(require("./verification-runner"), exports);
26
26
  __exportStar(require("./ai-sdk-provider"), exports);
27
27
  __exportStar(require("./config"), exports);
28
+ __exportStar(require("tinfoil/secure-client"), exports);
28
29
  // Re-export OpenAI utility types and classes that users might need
29
30
  // Using public exports from the main OpenAI package instead of deep imports
30
31
  var openai_1 = require("openai");
@@ -0,0 +1 @@
1
+ export declare function createPinnedTlsFetch(expectedFingerprintHex: string): typeof fetch;
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createPinnedTlsFetch = createPinnedTlsFetch;
7
+ const https_1 = __importDefault(require("https"));
8
+ const tls_1 = require("tls");
9
+ const crypto_1 = require("crypto");
10
+ const stream_1 = require("stream");
11
+ function createPinnedTlsFetch(expectedFingerprintHex) {
12
+ return (async (input, init) => {
13
+ // Normalize URL
14
+ const makeURL = (value) => {
15
+ if (typeof value === "string")
16
+ return new URL(value);
17
+ if (value instanceof URL)
18
+ return value;
19
+ return new URL(value.url);
20
+ };
21
+ const url = makeURL(input);
22
+ if (url.protocol !== "https:") {
23
+ throw new Error(`HTTP connections are not allowed. Use HTTPS. URL: ${url.toString()}`);
24
+ }
25
+ // Gather method and headers
26
+ const method = (init?.method || input.method || "GET").toUpperCase();
27
+ const headers = new Headers(init?.headers || input?.headers || {});
28
+ const headerObj = {};
29
+ headers.forEach((v, k) => {
30
+ headerObj[k] = v;
31
+ });
32
+ // Resolve body
33
+ let body = init?.body;
34
+ if (!body && input instanceof Request) {
35
+ // If the original was a Request with a body, read it
36
+ try {
37
+ const buf = await input.arrayBuffer();
38
+ if (buf && buf.byteLength)
39
+ body = Buffer.from(buf);
40
+ }
41
+ catch { }
42
+ }
43
+ // Convert web streams to Node streams if needed
44
+ if (body && typeof body.getReader === "function") {
45
+ body = stream_1.Readable.fromWeb(body);
46
+ }
47
+ if (body instanceof ArrayBuffer) {
48
+ body = Buffer.from(body);
49
+ }
50
+ if (ArrayBuffer.isView(body)) {
51
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
52
+ }
53
+ const requestOptions = {
54
+ protocol: url.protocol,
55
+ hostname: url.hostname,
56
+ port: url.port ? Number(url.port) : 443,
57
+ path: `${url.pathname}${url.search}`,
58
+ method,
59
+ headers: headerObj,
60
+ checkServerIdentity: (host, cert) => {
61
+ const raw = cert.raw;
62
+ if (!raw) {
63
+ return new Error("Certificate raw bytes are unavailable for pinning");
64
+ }
65
+ const x509 = new crypto_1.X509Certificate(raw);
66
+ const publicKeyDer = x509.publicKey.export({ type: "spki", format: "der" });
67
+ const fp = (0, crypto_1.createHash)("sha256").update(publicKeyDer).digest("hex");
68
+ if (fp !== expectedFingerprintHex) {
69
+ return new Error(`Certificate public key fingerprint mismatch. Expected: ${expectedFingerprintHex}, Got: ${fp}`);
70
+ }
71
+ return (0, tls_1.checkServerIdentity)(host, cert);
72
+ },
73
+ };
74
+ const { signal } = init || {};
75
+ const res = await new Promise((resolve, reject) => {
76
+ const req = https_1.default.request(requestOptions, resolve);
77
+ req.on("error", reject);
78
+ if (signal) {
79
+ if (signal.aborted) {
80
+ req.destroy(new Error("Request aborted"));
81
+ return;
82
+ }
83
+ signal.addEventListener("abort", () => req.destroy(new Error("Request aborted")));
84
+ }
85
+ if (body === undefined || body === null) {
86
+ req.end();
87
+ }
88
+ else if (typeof body === "string" || Buffer.isBuffer(body) || ArrayBuffer.isView(body)) {
89
+ req.end(body);
90
+ }
91
+ else if (typeof body.pipe === "function") {
92
+ body.pipe(req);
93
+ }
94
+ else {
95
+ // Fallback: try to serialize objects
96
+ req.end(String(body));
97
+ }
98
+ });
99
+ const responseHeaders = new Headers();
100
+ for (const [k, v] of Object.entries(res.headers)) {
101
+ if (Array.isArray(v)) {
102
+ v.forEach(item => responseHeaders.append(k, item));
103
+ }
104
+ else if (v != null) {
105
+ responseHeaders.set(k, String(v));
106
+ }
107
+ }
108
+ // Convert Node stream to Web ReadableStream
109
+ const webStream = stream_1.Readable.toWeb(res);
110
+ return new Response(webStream, {
111
+ status: res.statusCode || 0,
112
+ statusText: res.statusMessage || "",
113
+ headers: responseHeaders,
114
+ });
115
+ });
116
+ }
@@ -0,0 +1,20 @@
1
+ import type { VerificationDocument } from "./verifier";
2
+ interface SecureClientOptions {
3
+ baseURL?: string;
4
+ enclaveURL?: string;
5
+ configRepo?: string;
6
+ }
7
+ export declare class SecureClient {
8
+ private initPromise;
9
+ private verificationDocument;
10
+ private _fetch;
11
+ private readonly baseURL?;
12
+ private readonly enclaveURL?;
13
+ private readonly configRepo?;
14
+ constructor(options?: SecureClientOptions);
15
+ ready(): Promise<void>;
16
+ private initSecureClient;
17
+ getVerificationDocument(): Promise<VerificationDocument>;
18
+ get fetch(): typeof fetch;
19
+ }
20
+ export {};
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SecureClient = void 0;
4
+ const verifier_1 = require("./verifier");
5
+ const config_1 = require("./config");
6
+ const encrypted_body_fetch_1 = require("./encrypted-body-fetch");
7
+ const env_1 = require("./env");
8
+ class SecureClient {
9
+ constructor(options = {}) {
10
+ this.initPromise = null;
11
+ this.verificationDocument = null;
12
+ this._fetch = null;
13
+ this.baseURL = options.baseURL || config_1.TINFOIL_CONFIG.INFERENCE_BASE_URL;
14
+ this.enclaveURL = options.enclaveURL || config_1.TINFOIL_CONFIG.ENCLAVE_URL;
15
+ this.configRepo = options.configRepo || config_1.TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
16
+ }
17
+ async ready() {
18
+ if (!this.initPromise) {
19
+ this.initPromise = this.initSecureClient();
20
+ }
21
+ return this.initPromise;
22
+ }
23
+ async initSecureClient() {
24
+ const verifier = new verifier_1.Verifier({
25
+ serverURL: this.enclaveURL,
26
+ configRepo: this.configRepo,
27
+ });
28
+ await verifier.verify();
29
+ const doc = verifier.getVerificationDocument();
30
+ if (!doc) {
31
+ throw new Error("Verification document not available after successful verification");
32
+ }
33
+ this.verificationDocument = doc;
34
+ const hpkePublicKey = this.verificationDocument.enclaveMeasurement.hpkePublicKey;
35
+ if (!hpkePublicKey) {
36
+ if ((0, env_1.isRealBrowser)()) {
37
+ throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
38
+ "Only HPKE-enabled enclaves can be used in browser environments.");
39
+ }
40
+ throw new Error("HPKE public key is required in browser environments");
41
+ }
42
+ this._fetch = (0, encrypted_body_fetch_1.createEncryptedBodyFetch)(this.baseURL, hpkePublicKey, this.enclaveURL);
43
+ }
44
+ async getVerificationDocument() {
45
+ if (!this.initPromise) {
46
+ await this.ready();
47
+ }
48
+ await this.initPromise;
49
+ if (!this.verificationDocument) {
50
+ throw new Error("Verification document unavailable: client not verified yet");
51
+ }
52
+ return this.verificationDocument;
53
+ }
54
+ get fetch() {
55
+ return async (input, init) => {
56
+ await this.ready();
57
+ return this._fetch(input, init);
58
+ };
59
+ }
60
+ }
61
+ exports.SecureClient = SecureClient;
@@ -0,0 +1,20 @@
1
+ import type { VerificationDocument } from "./verifier";
2
+ interface SecureClientOptions {
3
+ baseURL?: string;
4
+ enclaveURL?: string;
5
+ configRepo?: string;
6
+ }
7
+ export declare class SecureClient {
8
+ private initPromise;
9
+ private verificationDocument;
10
+ private _fetch;
11
+ private readonly baseURL?;
12
+ private readonly enclaveURL?;
13
+ private readonly configRepo?;
14
+ constructor(options?: SecureClientOptions);
15
+ ready(): Promise<void>;
16
+ private initSecureClient;
17
+ getVerificationDocument(): Promise<VerificationDocument>;
18
+ get fetch(): typeof fetch;
19
+ }
20
+ export {};
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SecureClient = void 0;
4
+ const verifier_1 = require("./verifier");
5
+ const encrypted_body_fetch_1 = require("./encrypted-body-fetch");
6
+ const pinned_tls_fetch_1 = require("./pinned-tls-fetch");
7
+ const config_1 = require("./config");
8
+ const env_1 = require("./env");
9
+ class SecureClient {
10
+ constructor(options = {}) {
11
+ this.initPromise = null;
12
+ this.verificationDocument = null;
13
+ this._fetch = null;
14
+ this.baseURL = options.baseURL || config_1.TINFOIL_CONFIG.INFERENCE_BASE_URL;
15
+ this.enclaveURL = options.enclaveURL || config_1.TINFOIL_CONFIG.ENCLAVE_URL;
16
+ this.configRepo = options.configRepo || config_1.TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
17
+ }
18
+ async ready() {
19
+ if (!this.initPromise) {
20
+ this.initPromise = this.initSecureClient();
21
+ }
22
+ return this.initPromise;
23
+ }
24
+ async initSecureClient() {
25
+ const verifier = new verifier_1.Verifier({
26
+ serverURL: this.enclaveURL,
27
+ configRepo: this.configRepo,
28
+ });
29
+ await verifier.verify();
30
+ const doc = verifier.getVerificationDocument();
31
+ if (!doc) {
32
+ throw new Error("Verification document not available after successful verification");
33
+ }
34
+ this.verificationDocument = doc;
35
+ // Extract keys from the verification document
36
+ const { hpkePublicKey, tlsPublicKeyFingerprint } = this.verificationDocument.enclaveMeasurement;
37
+ let fetchFunction;
38
+ if (hpkePublicKey) {
39
+ // HPKE available: use encrypted body fetch
40
+ fetchFunction = (0, encrypted_body_fetch_1.createEncryptedBodyFetch)(this.baseURL, hpkePublicKey, this.enclaveURL);
41
+ }
42
+ else {
43
+ // HPKE not available: check if we're in a browser
44
+ if ((0, env_1.isRealBrowser)()) {
45
+ throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
46
+ "Only HPKE-enabled enclaves can be used in browser environments.");
47
+ }
48
+ // Node.js environment: fall back to TLS-only verification using pinned TLS fetch
49
+ if (!tlsPublicKeyFingerprint) {
50
+ throw new Error("Neither HPKE public key nor TLS public key fingerprint available for verification");
51
+ }
52
+ fetchFunction = (0, pinned_tls_fetch_1.createPinnedTlsFetch)(tlsPublicKeyFingerprint);
53
+ }
54
+ this._fetch = fetchFunction;
55
+ }
56
+ async getVerificationDocument() {
57
+ if (!this.initPromise) {
58
+ await this.ready();
59
+ }
60
+ await this.initPromise;
61
+ if (!this.verificationDocument) {
62
+ throw new Error("Verification document unavailable: client not verified yet");
63
+ }
64
+ return this.verificationDocument;
65
+ }
66
+ get fetch() {
67
+ return async (input, init) => {
68
+ await this.ready();
69
+ return this._fetch(input, init);
70
+ };
71
+ }
72
+ }
73
+ exports.SecureClient = SecureClient;
package/dist/verifier.js CHANGED
@@ -456,8 +456,8 @@ class Verifier {
456
456
  // Compare measurements using platform-specific logic
457
457
  const measurementsMatchError = compareMeasurementsError(codeMeasurement, attestation.measurement);
458
458
  if (measurementsMatchError) {
459
- throw new Error(`Measurement verification failed: Code measurement (${codeMeasurement.type}) ` +
460
- `does not match runtime measurement (${attestation.measurement.type}): ${measurementsMatchError.message}`);
459
+ throw new Error(`Verification failed: measurements did not match.\nCode measurement (${codeMeasurement.type}: ${codeMeasurement.registers})\n` +
460
+ `Runtime measurement (${attestation.measurement.type}: ${attestation.measurement.registers}:)\n ${measurementsMatchError.message}`);
461
461
  }
462
462
  // Persist a full verification document for later retrieval by clients
463
463
  this.lastVerificationDocument = {