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,157 @@
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.TinfoilAI = void 0;
7
+ const openai_1 = __importDefault(require("openai"));
8
+ const verifier_1 = require("./verifier");
9
+ const config_1 = require("./config");
10
+ const encrypted_body_fetch_1 = require("./encrypted-body-fetch");
11
+ const env_1 = require("./env");
12
+ function createAsyncProxy(promise) {
13
+ return new Proxy({}, {
14
+ get(target, prop) {
15
+ return new Proxy(() => { }, {
16
+ get(_, nestedProp) {
17
+ return (...args) => promise.then((obj) => {
18
+ const value = obj[prop][nestedProp];
19
+ return typeof value === "function"
20
+ ? value.apply(obj[prop], args)
21
+ : value;
22
+ });
23
+ },
24
+ apply(_, __, args) {
25
+ return promise.then((obj) => {
26
+ const value = obj[prop];
27
+ return typeof value === "function" ? value.apply(obj, args) : value;
28
+ });
29
+ },
30
+ });
31
+ },
32
+ });
33
+ }
34
+ class TinfoilAI {
35
+ constructor(options = {}) {
36
+ const openAIOptions = { ...options };
37
+ // In browser builds, never read secrets from process.env to avoid
38
+ // leaking credentials into client bundles. Require explicit apiKey.
39
+ if (typeof options.apiKey === "string") {
40
+ openAIOptions.apiKey = options.apiKey;
41
+ }
42
+ this.apiKey = openAIOptions.apiKey;
43
+ this.baseURL = options.baseURL || config_1.TINFOIL_CONFIG.INFERENCE_BASE_URL;
44
+ assertHttpsUrl(this.baseURL, "Inference baseURL");
45
+ this.configRepo = options.configRepo || config_1.TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
46
+ this.clientPromise = this.initClient(openAIOptions);
47
+ }
48
+ async ready() {
49
+ if (!this.readyPromise) {
50
+ this.readyPromise = (async () => {
51
+ this.client = await this.clientPromise;
52
+ })();
53
+ }
54
+ return this.readyPromise;
55
+ }
56
+ async initClient(options) {
57
+ return this.createOpenAIClient(options);
58
+ }
59
+ async createOpenAIClient(options = {}) {
60
+ const verifier = new verifier_1.Verifier({
61
+ serverURL: this.baseURL,
62
+ configRepo: this.configRepo,
63
+ });
64
+ try {
65
+ await verifier.verify();
66
+ this.verificationDocument = verifier.getVerificationDocument();
67
+ if (!this.verificationDocument) {
68
+ throw new Error("Verification document not available after successful verification");
69
+ }
70
+ }
71
+ catch (error) {
72
+ throw new Error(`Failed to verify enclave: ${error}`);
73
+ }
74
+ const hpkePublicKey = this.verificationDocument.enclaveMeasurement.hpkePublicKey;
75
+ if (!hpkePublicKey) {
76
+ // In browsers we require HPKE; TLS pinning fallback is Node-only
77
+ if ((0, env_1.isRealBrowser)()) {
78
+ throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
79
+ "Only HPKE-enabled enclaves can be used in browser environments.");
80
+ }
81
+ throw new Error("HPKE public key is required in browser environments");
82
+ }
83
+ const fetchFunction = (0, encrypted_body_fetch_1.createEncryptedBodyFetch)(this.baseURL, hpkePublicKey);
84
+ const clientOptions = {
85
+ ...options,
86
+ baseURL: this.baseURL,
87
+ fetch: fetchFunction,
88
+ };
89
+ // In browser usage, OpenAI SDK typically needs dangerouslyAllowBrowser
90
+ clientOptions.dangerouslyAllowBrowser = true;
91
+ return new openai_1.default(clientOptions);
92
+ }
93
+ async ensureReady() {
94
+ await this.ready();
95
+ return this.client;
96
+ }
97
+ async getVerificationDocument() {
98
+ await this.ready();
99
+ if (!this.verificationDocument) {
100
+ throw new Error("Verification document unavailable: client not verified yet");
101
+ }
102
+ return this.verificationDocument;
103
+ }
104
+ get chat() {
105
+ return createAsyncProxy(this.ensureReady().then((client) => client.chat));
106
+ }
107
+ get files() {
108
+ return createAsyncProxy(this.ensureReady().then((client) => client.files));
109
+ }
110
+ get fineTuning() {
111
+ return createAsyncProxy(this.ensureReady().then((client) => client.fineTuning));
112
+ }
113
+ get images() {
114
+ return createAsyncProxy(this.ensureReady().then((client) => client.images));
115
+ }
116
+ get audio() {
117
+ return createAsyncProxy(this.ensureReady().then((client) => client.audio));
118
+ }
119
+ get responses() {
120
+ return createAsyncProxy(this.ensureReady().then((client) => client.responses));
121
+ }
122
+ get embeddings() {
123
+ return createAsyncProxy(this.ensureReady().then((client) => client.embeddings));
124
+ }
125
+ get models() {
126
+ return createAsyncProxy(this.ensureReady().then((client) => client.models));
127
+ }
128
+ get moderations() {
129
+ return createAsyncProxy(this.ensureReady().then((client) => client.moderations));
130
+ }
131
+ get beta() {
132
+ return createAsyncProxy(this.ensureReady().then((client) => client.beta));
133
+ }
134
+ }
135
+ exports.TinfoilAI = TinfoilAI;
136
+ (function (TinfoilAI) {
137
+ TinfoilAI.Chat = openai_1.default.Chat;
138
+ TinfoilAI.Audio = openai_1.default.Audio;
139
+ TinfoilAI.Beta = openai_1.default.Beta;
140
+ TinfoilAI.Batches = openai_1.default.Batches;
141
+ TinfoilAI.Completions = openai_1.default.Completions;
142
+ TinfoilAI.Embeddings = openai_1.default.Embeddings;
143
+ TinfoilAI.Files = openai_1.default.Files;
144
+ TinfoilAI.FineTuning = openai_1.default.FineTuning;
145
+ TinfoilAI.Images = openai_1.default.Images;
146
+ TinfoilAI.Models = openai_1.default.Models;
147
+ TinfoilAI.Moderations = openai_1.default.Moderations;
148
+ TinfoilAI.Responses = openai_1.default.Responses;
149
+ TinfoilAI.Uploads = openai_1.default.Uploads;
150
+ TinfoilAI.VectorStores = openai_1.default.VectorStores;
151
+ })(TinfoilAI || (exports.TinfoilAI = TinfoilAI = {}));
152
+ function assertHttpsUrl(url, context) {
153
+ const parsed = new URL(url);
154
+ if (parsed.protocol !== "https:") {
155
+ throw new Error(`${context} must use HTTPS. Got: ${url}`);
156
+ }
157
+ }
package/dist/client.d.ts CHANGED
@@ -1,23 +1,29 @@
1
1
  import OpenAI from "openai";
2
- import type { Chat, Files, FineTuning, Images, Audio, Embeddings, Models, Moderations, Beta } from "openai/resources";
2
+ import type { Audio, Beta, Chat, Embeddings, Files, FineTuning, Images, Models, Moderations, Responses } from "openai/resources";
3
+ import type { VerificationDocument } from "./verifier";
3
4
  /**
4
5
  * TinfoilAI is a wrapper around the OpenAI API client that adds additional
5
- * security measures through enclave verification and certificate fingerprint validation.
6
+ * security measures through enclave verification and an EHBP-secured transport.
6
7
  *
7
8
  * It provides:
8
9
  * - Automatic verification of Tinfoil secure enclaves
9
- * - Certificate fingerprint validation for each request
10
+ * - EHBP-enforced transport security for each request
10
11
  * - Type-safe access to OpenAI's chat completion APIs
11
12
  */
12
13
  interface TinfoilAIOptions {
13
14
  apiKey?: string;
15
+ /** Override the inference API base URL */
16
+ baseURL?: string;
17
+ /** Override the config GitHub repository */
18
+ configRepo?: string;
14
19
  [key: string]: any;
15
20
  }
16
21
  export declare class TinfoilAI {
17
22
  private client?;
18
- private groundTruth?;
19
23
  private clientPromise;
20
24
  private readyPromise?;
25
+ private configRepo?;
26
+ private verificationDocument?;
21
27
  apiKey?: string;
22
28
  baseURL?: string;
23
29
  /**
@@ -39,6 +45,10 @@ export declare class TinfoilAI {
39
45
  * @private
40
46
  */
41
47
  private ensureReady;
48
+ /**
49
+ * Returns the full verification document produced during client initialization.
50
+ */
51
+ getVerificationDocument(): Promise<VerificationDocument>;
42
52
  /**
43
53
  * Access to OpenAI's chat completions API for creating chat conversations.
44
54
  * Automatically initializes the client if needed.
@@ -64,6 +74,11 @@ export declare class TinfoilAI {
64
74
  * Automatically initializes the client if needed.
65
75
  */
66
76
  get audio(): Audio;
77
+ /**
78
+ * Access to the Responses API, supporting response creation, streaming, and parsing.
79
+ * Automatically initializes the client if needed.
80
+ */
81
+ get responses(): Responses;
67
82
  /**
68
83
  * Access to OpenAI's embeddings API for creating vector embeddings of text.
69
84
  * Automatically initializes the client if needed.
@@ -97,6 +112,7 @@ export declare namespace TinfoilAI {
97
112
  export import Images = OpenAI.Images;
98
113
  export import Models = OpenAI.Models;
99
114
  export import Moderations = OpenAI.Moderations;
115
+ export import Responses = OpenAI.Responses;
100
116
  export import Uploads = OpenAI.Uploads;
101
117
  export import VectorStores = OpenAI.VectorStores;
102
118
  }
package/dist/client.js CHANGED
@@ -5,31 +5,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.TinfoilAI = void 0;
7
7
  const openai_1 = __importDefault(require("openai"));
8
- const crypto_1 = require("crypto");
9
- const secure_client_1 = require("./secure-client");
10
- const https_1 = __importDefault(require("https"));
8
+ const verifier_1 = require("./verifier");
11
9
  const config_1 = require("./config");
10
+ const encrypted_body_fetch_1 = require("./encrypted-body-fetch");
11
+ const https_1 = __importDefault(require("https"));
12
+ const tls_1 = require("tls");
13
+ const crypto_1 = require("crypto");
14
+ const stream_1 = require("stream");
12
15
  /**
13
16
  * Detects if the code is running in a real browser environment.
14
17
  * Returns false for Node.js environments, even with WASM loaded.
15
18
  */
16
- function isRealBrowser() {
17
- // Check for Node.js-specific globals that wouldn't exist in a real browser
18
- if (typeof process !== "undefined" &&
19
- process.versions &&
20
- process.versions.node) {
21
- return false; // Definitely Node.js
22
- }
23
- // Check for browser-specific window object AND ensure it's not a Node.js global mock
24
- if (typeof window !== "undefined" && typeof window.document !== "undefined") {
25
- // Additional check: real browsers have navigator.userAgent
26
- if (typeof navigator !== "undefined" && navigator.userAgent) {
27
- return true; // Likely a real browser
28
- }
29
- }
30
- // Default to safe: assume it's not a browser (Node.js with WASM)
31
- return false;
32
- }
19
+ const env_1 = require("./env");
33
20
  /**
34
21
  * Creates a proxy that allows property access and method calls on a Promise before it resolves.
35
22
  * This enables a more ergonomic API where you can chain properties and methods without explicitly
@@ -84,7 +71,10 @@ class TinfoilAI {
84
71
  }
85
72
  // Store properties for compatibility
86
73
  this.apiKey = openAIOptions.apiKey;
87
- this.baseURL = config_1.TINFOIL_CONFIG.INFERENCE_BASE_URL;
74
+ this.baseURL = options.baseURL || config_1.TINFOIL_CONFIG.INFERENCE_BASE_URL;
75
+ assertHttpsUrl(this.baseURL, "Inference baseURL");
76
+ this.configRepo =
77
+ options.configRepo || config_1.TINFOIL_CONFIG.INFERENCE_PROXY_REPO;
88
78
  this.clientPromise = this.initClient(openAIOptions);
89
79
  }
90
80
  /**
@@ -103,50 +93,48 @@ class TinfoilAI {
103
93
  return this.createOpenAIClient(options);
104
94
  }
105
95
  async createOpenAIClient(options = {}) {
106
- // Verify the enclave and get the certificate fingerprint
107
- const secureClient = new secure_client_1.SecureClient();
96
+ // Verify the enclave before establishing a transport
97
+ const verifier = new verifier_1.Verifier({
98
+ serverURL: this.baseURL,
99
+ configRepo: this.configRepo,
100
+ });
108
101
  try {
109
- this.groundTruth = await secureClient.verify();
102
+ await verifier.verify();
103
+ this.verificationDocument = verifier.getVerificationDocument();
104
+ if (!this.verificationDocument) {
105
+ throw new Error("Verification document not available after successful verification");
106
+ }
110
107
  }
111
108
  catch (error) {
112
109
  throw new Error(`Failed to verify enclave: ${error}`);
113
110
  }
114
- const expectedFingerprint = this.groundTruth.publicKeyFP;
115
- // Create a custom HTTPS agent that verifies certificate fingerprints
116
- const httpsAgent = new https_1.default.Agent({
117
- rejectUnauthorized: true,
118
- checkServerIdentity: (host, cert) => {
119
- if (!cert || !cert.raw) {
120
- throw new Error("No certificate found");
121
- }
122
- if (!cert.pubkey) {
123
- throw new Error("No public key found");
124
- }
125
- const pemCert = `-----BEGIN CERTIFICATE-----\n${cert.raw.toString("base64")}\n-----END CERTIFICATE-----`;
126
- const x509Cert = new crypto_1.X509Certificate(pemCert);
127
- const publicKey = x509Cert.publicKey.export({
128
- format: "der",
129
- type: "spki",
130
- });
131
- const publicKeyHash = (0, crypto_1.createHash)("sha256")
132
- .update(publicKey)
133
- .digest("hex");
134
- if (publicKeyHash !== expectedFingerprint) {
135
- throw new Error(`Certificate fingerprint mismatch. Got ${publicKeyHash}, expected ${expectedFingerprint}`);
136
- }
137
- return undefined; // Validation successful
138
- },
139
- });
140
- // Create the OpenAI client with our custom configuration
141
- // Note: baseURL will need to be determined by the verification process
111
+ const hpkePublicKey = this.verificationDocument.enclaveMeasurement.hpkePublicKey;
112
+ const tlsPublicKeyFingerprint = this.verificationDocument.enclaveMeasurement.tlsPublicKeyFingerprint;
113
+ let fetchFunction;
114
+ if (hpkePublicKey) {
115
+ // HPKE available: use encrypted body fetch
116
+ fetchFunction = (0, encrypted_body_fetch_1.createEncryptedBodyFetch)(this.baseURL, hpkePublicKey);
117
+ }
118
+ else {
119
+ // HPKE not available: check if we're in a browser
120
+ if ((0, env_1.isRealBrowser)()) {
121
+ throw new Error("HPKE public key not available and TLS-only verification is not supported in browsers. " +
122
+ "Only HPKE-enabled enclaves can be used in browser environments.");
123
+ }
124
+ // Node.js environment: fall back to TLS-only verification using pinned TLS fetch
125
+ if (!tlsPublicKeyFingerprint) {
126
+ throw new Error("Neither HPKE public key nor TLS public key fingerprint available for verification");
127
+ }
128
+ fetchFunction = createPinnedTlsFetch(tlsPublicKeyFingerprint);
129
+ }
142
130
  const clientOptions = {
143
131
  ...options,
144
- baseURL: config_1.TINFOIL_CONFIG.INFERENCE_BASE_URL,
132
+ baseURL: this.baseURL,
133
+ fetch: fetchFunction,
145
134
  };
146
- // Only enable dangerouslyAllowBrowser when we're NOT in a real browser
147
- // This prevents API key exposure if code is ever bundled for browser use
148
- if (!isRealBrowser()) {
149
- // We're in Node.js with WASM, which makes OpenAI SDK think we're in a browser
135
+ // Enable dangerouslyAllowBrowser in Node.js with WASM (which makes OpenAI SDK think we're in a browser)
136
+ // OR if explicitly set by the user (for legitimate browser usage like playgrounds)
137
+ if (!(0, env_1.isRealBrowser)() || options.dangerouslyAllowBrowser === true) {
150
138
  clientOptions.dangerouslyAllowBrowser = true;
151
139
  }
152
140
  return new openai_1.default(clientOptions);
@@ -162,6 +150,16 @@ class TinfoilAI {
162
150
  // We can safely assert this now because ready() must have completed
163
151
  return this.client;
164
152
  }
153
+ /**
154
+ * Returns the full verification document produced during client initialization.
155
+ */
156
+ async getVerificationDocument() {
157
+ await this.ready();
158
+ if (!this.verificationDocument) {
159
+ throw new Error("Verification document unavailable: client not verified yet");
160
+ }
161
+ return this.verificationDocument;
162
+ }
165
163
  /**
166
164
  * Access to OpenAI's chat completions API for creating chat conversations.
167
165
  * Automatically initializes the client if needed.
@@ -197,6 +195,13 @@ class TinfoilAI {
197
195
  get audio() {
198
196
  return createAsyncProxy(this.ensureReady().then((client) => client.audio));
199
197
  }
198
+ /**
199
+ * Access to the Responses API, supporting response creation, streaming, and parsing.
200
+ * Automatically initializes the client if needed.
201
+ */
202
+ get responses() {
203
+ return createAsyncProxy(this.ensureReady().then((client) => client.responses));
204
+ }
200
205
  /**
201
206
  * Access to OpenAI's embeddings API for creating vector embeddings of text.
202
207
  * Automatically initializes the client if needed.
@@ -241,6 +246,119 @@ exports.TinfoilAI = TinfoilAI;
241
246
  TinfoilAI.Images = openai_1.default.Images;
242
247
  TinfoilAI.Models = openai_1.default.Models;
243
248
  TinfoilAI.Moderations = openai_1.default.Moderations;
249
+ TinfoilAI.Responses = openai_1.default.Responses;
244
250
  TinfoilAI.Uploads = openai_1.default.Uploads;
245
251
  TinfoilAI.VectorStores = openai_1.default.VectorStores;
246
252
  })(TinfoilAI || (exports.TinfoilAI = TinfoilAI = {}));
253
+ function assertHttpsUrl(url, context) {
254
+ const parsed = new URL(url);
255
+ if (parsed.protocol !== "https:") {
256
+ throw new Error(`${context} must use HTTPS. Got: ${url}`);
257
+ }
258
+ }
259
+ function createPinnedTlsFetch(expectedFingerprintHex) {
260
+ return (async (input, init) => {
261
+ // Normalize URL
262
+ const makeURL = (value) => {
263
+ if (typeof value === "string")
264
+ return new URL(value);
265
+ if (value instanceof URL)
266
+ return value;
267
+ return new URL(value.url);
268
+ };
269
+ const url = makeURL(input);
270
+ if (url.protocol !== "https:") {
271
+ throw new Error(`HTTP connections are not allowed. Use HTTPS. URL: ${url.toString()}`);
272
+ }
273
+ // Gather method and headers
274
+ const method = (init?.method || input.method || "GET").toUpperCase();
275
+ const headers = new Headers(init?.headers || input?.headers || {});
276
+ const headerObj = {};
277
+ headers.forEach((v, k) => {
278
+ headerObj[k] = v;
279
+ });
280
+ // Resolve body
281
+ let body = init?.body;
282
+ if (!body && input instanceof Request) {
283
+ // If the original was a Request with a body, read it
284
+ try {
285
+ const buf = await input.arrayBuffer();
286
+ if (buf && buf.byteLength)
287
+ body = Buffer.from(buf);
288
+ }
289
+ catch { }
290
+ }
291
+ // Convert web streams to Node streams if needed
292
+ if (body && typeof body.getReader === "function") {
293
+ body = stream_1.Readable.fromWeb(body);
294
+ }
295
+ if (body instanceof ArrayBuffer) {
296
+ body = Buffer.from(body);
297
+ }
298
+ if (ArrayBuffer.isView(body)) {
299
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
300
+ }
301
+ const requestOptions = {
302
+ protocol: url.protocol,
303
+ hostname: url.hostname,
304
+ port: url.port ? Number(url.port) : 443,
305
+ path: `${url.pathname}${url.search}`,
306
+ method,
307
+ headers: headerObj,
308
+ checkServerIdentity: (host, cert) => {
309
+ const raw = cert.raw;
310
+ if (!raw) {
311
+ return new Error("Certificate raw bytes are unavailable for pinning");
312
+ }
313
+ const x509 = new crypto_1.X509Certificate(raw);
314
+ const publicKeyDer = x509.publicKey.export({ type: "spki", format: "der" });
315
+ const fp = (0, crypto_1.createHash)("sha256").update(publicKeyDer).digest("hex");
316
+ if (fp !== expectedFingerprintHex) {
317
+ return new Error(`Certificate public key fingerprint mismatch. Expected: ${expectedFingerprintHex}, Got: ${fp}`);
318
+ }
319
+ return (0, tls_1.checkServerIdentity)(host, cert);
320
+ },
321
+ };
322
+ const { signal } = init || {};
323
+ const res = await new Promise((resolve, reject) => {
324
+ const req = https_1.default.request(requestOptions, resolve);
325
+ req.on("error", reject);
326
+ if (signal) {
327
+ if (signal.aborted) {
328
+ req.destroy(new Error("Request aborted"));
329
+ return;
330
+ }
331
+ signal.addEventListener("abort", () => req.destroy(new Error("Request aborted")));
332
+ }
333
+ if (body === undefined || body === null) {
334
+ req.end();
335
+ }
336
+ else if (typeof body === "string" || Buffer.isBuffer(body) || ArrayBuffer.isView(body)) {
337
+ req.end(body);
338
+ }
339
+ else if (typeof body.pipe === "function") {
340
+ body.pipe(req);
341
+ }
342
+ else {
343
+ // Fallback: try to serialize objects
344
+ req.end(String(body));
345
+ }
346
+ });
347
+ const responseHeaders = new Headers();
348
+ for (const [k, v] of Object.entries(res.headers)) {
349
+ if (Array.isArray(v)) {
350
+ v.forEach(item => responseHeaders.append(k, item));
351
+ }
352
+ else if (v != null) {
353
+ responseHeaders.set(k, String(v));
354
+ }
355
+ }
356
+ // Convert Node stream to Web ReadableStream
357
+ const webStream = stream_1.Readable.toWeb(res);
358
+ return new Response(webStream, {
359
+ status: res.statusCode || 0,
360
+ statusText: res.statusMessage || "",
361
+ headers: responseHeaders,
362
+ });
363
+ });
364
+ }
@@ -0,0 +1,10 @@
1
+ type EhbpModule = typeof import("ehbp");
2
+ export declare function normalizeEncryptedBodyRequestArgs(input: RequestInfo | URL, init?: RequestInit): {
3
+ url: string;
4
+ init?: RequestInit;
5
+ };
6
+ export declare function encryptedBodyRequest(input: RequestInfo | URL, hpkePublicKey: string, init?: RequestInit): Promise<Response>;
7
+ export declare function createEncryptedBodyFetch(baseURL: string, hpkePublicKey: string): typeof fetch;
8
+ export declare function __setEhbpModuleForTests(module: EhbpModule | undefined): void;
9
+ export declare function __resetEhbpModuleStateForTests(): void;
10
+ export {};
@@ -0,0 +1,158 @@
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.normalizeEncryptedBodyRequestArgs = normalizeEncryptedBodyRequestArgs;
37
+ exports.encryptedBodyRequest = encryptedBodyRequest;
38
+ exports.createEncryptedBodyFetch = createEncryptedBodyFetch;
39
+ exports.__setEhbpModuleForTests = __setEhbpModuleForTests;
40
+ exports.__resetEhbpModuleStateForTests = __resetEhbpModuleStateForTests;
41
+ const env_1 = require("./env");
42
+ const transportCache = new Map();
43
+ let ehbpModulePromise = null;
44
+ let ehbpModuleOverride;
45
+ // Public API
46
+ function normalizeEncryptedBodyRequestArgs(input, init) {
47
+ if (typeof input === "string") {
48
+ return { url: input, init };
49
+ }
50
+ if (input instanceof URL) {
51
+ return { url: input.toString(), init };
52
+ }
53
+ const request = input;
54
+ const cloned = request.clone();
55
+ const derivedInit = {
56
+ method: cloned.method,
57
+ headers: new Headers(cloned.headers),
58
+ body: cloned.body ?? undefined,
59
+ signal: cloned.signal,
60
+ };
61
+ return {
62
+ url: cloned.url,
63
+ init: { ...derivedInit, ...init },
64
+ };
65
+ }
66
+ async function encryptedBodyRequest(input, hpkePublicKey, init) {
67
+ const { url: requestUrl, init: requestInit } = normalizeEncryptedBodyRequestArgs(input, init);
68
+ const u = new URL(requestUrl);
69
+ if (u.protocol !== 'https:') {
70
+ throw new Error(`HTTP connections are not allowed for EHBP. Use HTTPS. URL: ${requestUrl}`);
71
+ }
72
+ const { origin } = u;
73
+ const transport = await getTransportForOrigin(origin);
74
+ const serverPublicKey = await transport.getServerPublicKeyHex();
75
+ if (serverPublicKey !== hpkePublicKey) {
76
+ transportCache.delete(origin);
77
+ throw new Error(`HPKE public key mismatch: expected ${hpkePublicKey}, got ${serverPublicKey}`);
78
+ }
79
+ return transport.request(requestUrl, requestInit);
80
+ }
81
+ function createEncryptedBodyFetch(baseURL, hpkePublicKey) {
82
+ return (async (input, init) => {
83
+ const base = new URL(baseURL);
84
+ if (base.protocol !== 'https:') {
85
+ throw new Error(`EHBP baseURL must use HTTPS. Got: ${baseURL}`);
86
+ }
87
+ const normalized = normalizeEncryptedBodyRequestArgs(input, init);
88
+ const targetUrl = new URL(normalized.url, baseURL);
89
+ return encryptedBodyRequest(targetUrl.toString(), hpkePublicKey, normalized.init);
90
+ });
91
+ }
92
+ // Private helper functions
93
+ /**
94
+ * Load the ESM-only `ehbp` module in both browsers and Node.js CommonJS tests.
95
+ *
96
+ * - Browsers/Next.js: use a standard dynamic import so bundlers can statically
97
+ * include `ehbp` in the client bundle.
98
+ * - Node.js (CJS tests/builds): avoid TypeScript transpiling import() to
99
+ * require(), which throws ERR_REQUIRE_ESM. Instead, create a runtime
100
+ * dynamic import via new Function so it remains a real import() call.
101
+ */
102
+ function getEhbpModule() {
103
+ if (ehbpModuleOverride) {
104
+ return Promise.resolve(ehbpModuleOverride);
105
+ }
106
+ if (!ehbpModulePromise) {
107
+ if ((0, env_1.isRealBrowser)()) {
108
+ // Let the bundler include the module in browser builds
109
+ ehbpModulePromise = Promise.resolve().then(() => __importStar(require("ehbp")));
110
+ }
111
+ else {
112
+ const dynamicImport = new Function("specifier", "return import(specifier);");
113
+ ehbpModulePromise = dynamicImport("ehbp");
114
+ }
115
+ }
116
+ return ehbpModulePromise;
117
+ }
118
+ async function getTransportForOrigin(origin) {
119
+ const cached = transportCache.get(origin);
120
+ if (cached) {
121
+ return cached;
122
+ }
123
+ const transportPromise = (async () => {
124
+ const { Identity, createTransport } = await getEhbpModule();
125
+ const proto = new URL(origin).protocol;
126
+ if (proto !== 'https:') {
127
+ throw new Error(`EHBP requires HTTPS origin. Got: ${origin}`);
128
+ }
129
+ // Ensure we're in a secure context with WebCrypto Subtle available (required by EHBP)
130
+ if (typeof globalThis !== 'undefined') {
131
+ const isSecure = globalThis.isSecureContext !== false;
132
+ const hasSubtle = !!(globalThis.crypto && globalThis.crypto.subtle);
133
+ if (!isSecure || !hasSubtle) {
134
+ const reason = !isSecure
135
+ ? 'insecure context (use HTTPS or localhost)'
136
+ : 'missing WebCrypto SubtleCrypto';
137
+ throw new Error(`EHBP requires a secure browser context: ${reason}`);
138
+ }
139
+ }
140
+ const clientIdentity = await Identity.generate();
141
+ return createTransport(origin, clientIdentity);
142
+ })().catch((error) => {
143
+ transportCache.delete(origin);
144
+ throw error;
145
+ });
146
+ transportCache.set(origin, transportPromise);
147
+ return transportPromise;
148
+ }
149
+ // Test utilities
150
+ function __setEhbpModuleForTests(module) {
151
+ ehbpModuleOverride = module;
152
+ ehbpModulePromise = module ? Promise.resolve(module) : null;
153
+ }
154
+ function __resetEhbpModuleStateForTests() {
155
+ ehbpModuleOverride = undefined;
156
+ ehbpModulePromise = null;
157
+ transportCache.clear();
158
+ }