tinfoil 0.1.2 → 0.2.0

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.
package/dist/client.js CHANGED
@@ -1,355 +1,199 @@
1
- import { Task } from '@divviup/dap';
2
- import { getConfig, DEFAULT_CONFIG_ENDPOINT } from './config';
3
- import { logger } from './debugLogger';
4
- import { UAParser } from 'ua-parser-js'; // Import UAParser for user-agent parsing
5
- export class AnalyticsClient {
6
- config;
7
- globalConfig = null;
8
- tasks = new Map();
9
- constructor(config) {
10
- this.config = {
11
- configEndpoint: DEFAULT_CONFIG_ENDPOINT,
12
- debug: false,
13
- ...config,
14
- };
15
- }
16
- async init() {
17
- await this.initTracking();
18
- }
19
- async initTracking() {
20
- const configSuccess = await this.refreshConfig();
21
- if (!configSuccess) {
22
- logger.error('Tinfoil: Failed to refresh config');
23
- return;
24
- }
25
- this.startSessionTracking();
26
- this.setupCustomEventTracking();
27
- this.setupBounceTracking();
28
- const results = await Promise.allSettled([
29
- this.trackPageVisit(),
30
- this.trackCountry(),
31
- this.trackTelemetry(),
32
- ]);
33
- results.forEach((result, index) => {
34
- if (result.status === 'rejected') {
35
- const functionName = ['trackPageVisit', 'trackCountry', 'trackTelemetry'][index];
36
- logger.error(`Tinfoil: ${functionName} failed:`, result.reason);
37
- }
38
- });
39
- }
40
- async refreshConfig() {
41
- if (this.globalConfig !== null)
42
- return true; // Already have config
43
- try {
44
- const config = await getConfig(this.config.domain, this.config.configEndpoint);
45
- if (config) {
46
- this.globalConfig = config;
47
- logger.log('Tinfoil: Global config fetched successfully:', config);
48
- return true;
49
- }
50
- else {
51
- logger.error('Failed to fetch global config');
52
- return false;
53
- }
54
- }
55
- catch (error) {
56
- logger.error('Error fetching global config:', error);
57
- return false;
58
- }
59
- }
60
- async getTask(eventName) {
61
- // Try to get cached task
62
- const cachedTask = this.tasks.get(eventName);
63
- if (cachedTask) {
64
- return cachedTask;
65
- }
66
- // Make sure we have config
67
- if (!this.globalConfig && !(await this.refreshConfig())) {
68
- return null;
69
- }
70
- const eventConfig = this.globalConfig?.metrics[eventName];
71
- if (!eventConfig) {
72
- logger.error(`Tinfoil: No configuration found for event: ${eventName}`);
73
- return null;
74
- }
75
- const task = await this.createTask(eventConfig);
76
- if (task) {
77
- this.tasks.set(eventName, task);
78
- }
79
- return task;
80
- }
81
- async createTask(eventConfig) {
82
- const { taskId, timePrecision, type, vdafConfig } = eventConfig.aggregationConfig;
83
- const { leaderUrl, helperUrl } = this.globalConfig;
84
- if (type === 'count') {
85
- return new Task({
86
- type: 'count',
87
- id: taskId,
88
- leader: leaderUrl,
89
- helper: helperUrl,
90
- timePrecisionSeconds: timePrecision,
91
- });
92
- }
93
- else if (type === 'histogram') {
94
- if (!vdafConfig) {
95
- throw new Error('Invalid histogram configuration: vdafConfig is undefined');
96
- }
97
- const { numBuckets, proofChunkSize } = vdafConfig;
98
- if (numBuckets == null || proofChunkSize == null) {
99
- throw new Error('Invalid histogram configuration: numBuckets or proofChunkSize is null or undefined');
100
- }
101
- return new Task({
102
- type: 'histogram',
103
- id: taskId,
104
- leader: leaderUrl,
105
- helper: helperUrl,
106
- timePrecisionSeconds: timePrecision,
107
- length: numBuckets,
108
- chunkLength: proofChunkSize,
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 crypto_1 = require("crypto");
9
+ const secure_client_1 = require("./secure-client");
10
+ const https_1 = __importDefault(require("https"));
11
+ /**
12
+ * Creates a proxy that allows property access and method calls on a Promise before it resolves.
13
+ * This enables a more ergonomic API where you can chain properties and methods without explicitly
14
+ * awaiting the promise first.
15
+ *
16
+ * @param promise - A Promise that will resolve to an object
17
+ * @returns A proxied version of the promised object that allows immediate property/method access
18
+ *
19
+ * @example
20
+ * // Instead of:
21
+ * const client = await getClient();
22
+ * const result = await client.someProperty.someMethod();
23
+ *
24
+ * // You can write:
25
+ * const client = createAsyncProxy(getClient());
26
+ * const result = await client.someProperty.someMethod();
27
+ *
28
+ * @template T - The type of object that the promise resolves to
29
+ */
30
+ function createAsyncProxy(promise) {
31
+ return new Proxy({}, {
32
+ get(target, prop) {
33
+ return new Proxy(() => { }, {
34
+ get(_, nestedProp) {
35
+ return (...args) => promise.then(obj => {
36
+ const value = obj[prop][nestedProp];
37
+ return typeof value === 'function' ? value.apply(obj[prop], args) : value;
38
+ });
39
+ },
40
+ apply(_, __, args) {
41
+ return promise.then(obj => {
42
+ const value = obj[prop];
43
+ return typeof value === 'function' ? value.apply(obj, args) : value;
44
+ });
45
+ }
109
46
  });
110
47
  }
111
- logger.error(`Unsupported event type: ${type}`);
112
- return null;
113
- }
114
- async trackEvent(eventName, value) {
115
- const task = await this.getTask(eventName);
116
- if (!task) {
117
- logger.error(`Tinfoil: No configuration found for event: ${eventName}`);
118
- return;
119
- }
120
- logger.log(`Tinfoil: Tracking event: ${eventName} with value: ${value}`);
121
- try {
122
- await task.sendMeasurement(value !== undefined ? value : true);
123
- logger.log(`Tinfoil: Event '${eventName}' tracked successfully`);
124
- }
125
- catch (error) {
126
- logger.error(`Tinfoil: Error tracking event '${eventName}':`, error);
127
- }
128
- }
129
- async trackPageVisit() {
130
- if (typeof window === 'undefined' || !window.sessionStorage)
131
- return;
132
- if (sessionStorage.getItem('tinfoil-page-visit'))
133
- return;
134
- const success = await this.refreshConfig();
135
- if (!success)
136
- return;
137
- if (!this.globalConfig?.metrics.visit)
138
- return;
139
- sessionStorage.setItem('tinfoil-page-visit', 'true');
140
- logger.log('Tinfoil: Tracking page visit');
141
- const isUniqueVisit = !localStorage.getItem('tinfoil-unique-visit');
142
- if (isUniqueVisit) {
143
- localStorage.setItem('tinfoil-unique-visit', 'true');
144
- logger.log('Tinfoil: New unique visitor');
48
+ });
49
+ }
50
+ /**
51
+ * TinfoilAI is a wrapper around the OpenAI API client that adds additional
52
+ * security measures through enclave verification and certificate fingerprint validation.
53
+ *
54
+ * It provides:
55
+ * - Automatic verification of Tinfoil secure enclaves
56
+ * - Certificate fingerprint validation for each request
57
+ * - Type-safe access to OpenAI's chat completion APIs
58
+ */
59
+ class TinfoilAI {
60
+ constructor(enclaveOrOptions, repoOrNothing, options) {
61
+ if (typeof enclaveOrOptions === 'string' && typeof repoOrNothing === 'string') {
62
+ this.enclave = enclaveOrOptions;
63
+ this.repo = repoOrNothing;
64
+ this.clientPromise = this.initClient(options);
145
65
  }
146
66
  else {
147
- logger.log('Tinfoil: Returning visitor');
148
- }
149
- await this.trackEvent('visit', isUniqueVisit);
150
- }
151
- async trackCountry() {
152
- if (typeof window === 'undefined' || !window.sessionStorage)
153
- return;
154
- if (sessionStorage.getItem('did-submit-country'))
155
- return;
156
- const success = await this.refreshConfig();
157
- if (!success)
158
- return;
159
- const countryConfig = this.globalConfig?.metrics.country;
160
- if (!countryConfig || !countryConfig.metricsInfo)
161
- return;
162
- sessionStorage.setItem('did-submit-country', 'true');
163
- logger.log('Tinfoil: Tracking country');
164
- const index = countryConfig.metricsInfo.countryIndex;
165
- await this.trackEvent('country', index);
166
- }
167
- async trackTelemetry() {
168
- if (typeof window === 'undefined')
169
- return;
170
- const success = await this.refreshConfig();
171
- if (!success)
172
- return;
173
- const userAgent = window.navigator.userAgent;
174
- const parser = new UAParser(userAgent);
175
- const browserName = parser.getBrowser().name;
176
- const osName = parser.getOS().name;
177
- let deviceType = parser.getDevice().type || 'Desktop';
178
- await Promise.allSettled([
179
- this.sendBrowserType(browserName),
180
- this.sendOSType(osName),
181
- this.sendDeviceType(deviceType),
182
- ]);
183
- }
184
- async sendOSType(osType) {
185
- try {
186
- if (!this.globalConfig?.metrics.os)
187
- return;
188
- if (sessionStorage.getItem('did-submit-os-type'))
189
- return;
190
- if (!osType) {
191
- logger.log('Tinfoil: OS type is undefined');
192
- return;
67
+ this.enclave = process.env.TINFOIL_ENCLAVE || '';
68
+ this.repo = process.env.TINFOIL_REPO || '';
69
+ if (!this.enclave || !this.repo) {
70
+ throw new Error('tinfoil: TINFOIL_ENCLAVE and TINFOIL_REPO environment variables must be specified');
193
71
  }
194
- sessionStorage.setItem('did-submit-os-type', 'true');
195
- logger.log('Tinfoil: Tracking OS type');
196
- const osMetrics = this.globalConfig.metrics.os;
197
- const osTypes = osMetrics.metricsInfo?.labels;
198
- if (!osTypes)
199
- return;
200
- let osTypeIndex = osTypes.findIndex((name) => osType.toLowerCase().includes(name.toLowerCase()));
201
- if (osTypeIndex === -1)
202
- osTypeIndex = osTypes.length - 1;
203
- logger.log('Tinfoil: OS type is', osTypes[osTypeIndex]);
204
- await this.trackEvent('os', osTypeIndex);
205
- }
206
- catch (error) {
207
- logger.error('Error in sendOSType:', error);
72
+ this.clientPromise = this.initClient(enclaveOrOptions);
208
73
  }
209
74
  }
210
- async sendBrowserType(browserType) {
211
- try {
212
- if (!this.globalConfig?.metrics.browser)
213
- return;
214
- if (sessionStorage.getItem('did-submit-browser-type'))
215
- return;
216
- if (!browserType) {
217
- logger.log('Tinfoil: Browser type is undefined');
218
- return;
219
- }
220
- sessionStorage.setItem('did-submit-browser-type', 'true');
221
- logger.log('Tinfoil: Tracking browser type');
222
- const browserMetrics = this.globalConfig.metrics.browser;
223
- const browserTypes = browserMetrics.metricsInfo?.labels;
224
- if (!browserTypes)
225
- return;
226
- let browserTypeIndex = browserTypes.findIndex((name) => browserType.toLowerCase().includes(name.toLowerCase()));
227
- if (browserTypeIndex === -1)
228
- browserTypeIndex = browserTypes.length - 1;
229
- logger.log('Tinfoil: Browser type is', browserTypes[browserTypeIndex]);
230
- await this.trackEvent('browser', browserTypeIndex);
231
- }
232
- catch (error) {
233
- logger.error('Error in sendBrowserType:', error);
75
+ /**
76
+ * Ensures the client is ready to use.
77
+ * @returns Promise that resolves when the client is initialized
78
+ */
79
+ async ready() {
80
+ if (!this.readyPromise) {
81
+ this.readyPromise = (async () => {
82
+ this.client = await this.clientPromise;
83
+ })();
234
84
  }
85
+ return this.readyPromise;
235
86
  }
236
- async sendDeviceType(deviceType) {
87
+ async initClient(options) {
88
+ return this.createOpenAIClient(options);
89
+ }
90
+ async createOpenAIClient(options = {}) {
91
+ // Verify the enclave and get the certificate fingerprint
92
+ const secureClient = new secure_client_1.SecureClient(this.enclave, this.repo);
237
93
  try {
238
- if (!this.globalConfig?.metrics.device)
239
- return;
240
- if (sessionStorage.getItem('did-submit-device-type'))
241
- return;
242
- if (!deviceType) {
243
- logger.log('Tinfoil: Device type is undefined');
244
- return;
245
- }
246
- sessionStorage.setItem('did-submit-device-type', 'true');
247
- logger.log('Tinfoil: Tracking device type');
248
- const deviceMetrics = this.globalConfig.metrics.device;
249
- const deviceTypes = deviceMetrics.metricsInfo?.labels;
250
- if (!deviceTypes)
251
- return;
252
- let deviceTypeIndex = deviceTypes.findIndex((name) => deviceType.toLowerCase().includes(name.toLowerCase()));
253
- if (deviceTypeIndex === -1)
254
- deviceTypeIndex = deviceTypes.length - 1;
255
- logger.log('Tinfoil: Device type is', deviceTypes[deviceTypeIndex]);
256
- await this.trackEvent('device', deviceTypeIndex);
94
+ this.groundTruth = await secureClient.verify();
257
95
  }
258
96
  catch (error) {
259
- logger.error('Error in sendDeviceType:', error);
260
- }
261
- }
262
- startSessionTracking() {
263
- if (typeof window === 'undefined')
264
- return;
265
- let sessionStart = Date.now();
266
- const endSession = async () => {
267
- const duration = Date.now() - sessionStart;
268
- if (this.globalConfig?.metrics.session) {
269
- const sessionConfig = this.globalConfig.metrics.session;
270
- if (!sessionConfig.metricsInfo)
271
- return;
272
- const { sessionInterval } = sessionConfig.metricsInfo;
273
- const vdafConfig = sessionConfig.aggregationConfig.vdafConfig;
274
- if (!vdafConfig)
275
- return;
276
- const numBuckets = vdafConfig.numBuckets;
277
- if (!numBuckets)
278
- return;
279
- const bucket = this.bucketTime(duration, sessionInterval, numBuckets);
280
- logger.log(`Tinfoil: Session duration bucketed as ${bucket}`);
281
- await this.trackEvent('session', bucket);
282
- }
283
- };
284
- document.addEventListener('visibilitychange', async () => {
285
- if (document.visibilityState === 'hidden') {
286
- await endSession();
287
- }
288
- else {
289
- sessionStart = Date.now();
290
- }
291
- });
292
- window.addEventListener('beforeunload', () => {
293
- endSession().catch(console.error);
294
- });
295
- }
296
- bucketTime(timeInMs, interval, numBuckets) {
297
- const intervalInMs = interval * 1000; // Convert seconds to milliseconds
298
- if (timeInMs > numBuckets * intervalInMs) {
299
- return numBuckets - 1; // Last bucket if time exceeds the maximum
300
- }
301
- return Math.floor(timeInMs / intervalInMs);
302
- }
303
- setupCustomEventTracking() {
304
- if (typeof document === 'undefined')
305
- return;
306
- document.addEventListener('click', (e) => {
307
- let target = e.target;
308
- while (target && target !== document.body) {
309
- const className = Array.from(target.classList).find(cls => cls.startsWith('tinfoil-event-name='));
310
- if (className) {
311
- const parts = className.split('=');
312
- if (parts.length > 1) {
313
- const eventName = parts[1].replace(/\+/g, ' ');
314
- this.trackEvent(eventName);
315
- }
316
- break;
97
+ throw new Error(`Failed to verify enclave: ${error}`);
98
+ }
99
+ // Convert the expected fingerprint to hex string for comparison
100
+ const expectedFingerprint = Buffer.from(this.groundTruth.certFingerprint).toString('hex');
101
+ // Create a custom HTTPS agent that verifies certificate fingerprints
102
+ const httpsAgent = new https_1.default.Agent({
103
+ rejectUnauthorized: true,
104
+ checkServerIdentity: (host, cert) => {
105
+ if (!cert || !cert.raw) {
106
+ throw new Error('No certificate found');
317
107
  }
318
- target = target.parentElement;
319
- }
320
- });
321
- document.addEventListener('submit', (e) => {
322
- const form = e.target;
323
- const className = Array.from(form.classList).find(cls => cls.startsWith('tinfoil-event-name='));
324
- if (className) {
325
- const parts = className.split('=');
326
- if (parts.length > 1) {
327
- const eventName = parts[1].replace(/\+/g, ' ');
328
- this.trackEvent(eventName);
108
+ // Calculate the SHA-256 fingerprint of the certificate and convert to hex
109
+ const certFingerprint = (0, crypto_1.createHash)('sha256').update(cert.raw).digest('hex');
110
+ // Compare hex strings
111
+ if (certFingerprint !== expectedFingerprint) {
112
+ throw new Error('Certificate fingerprint mismatch');
329
113
  }
114
+ return undefined; // Validation successful
330
115
  }
331
116
  });
332
- }
333
- setupBounceTracking() {
334
- if (typeof document === 'undefined')
335
- return;
336
- const interactionEvents = ['click', 'keypress'];
337
- const handleInteraction = () => {
338
- // Remove listeners after first interaction
339
- interactionEvents.forEach(event => {
340
- document.removeEventListener(event, handleInteraction);
341
- });
342
- logger.log('Tinfoil: User interaction detected');
343
- // Only fire engagement event once per session
344
- if (!sessionStorage.getItem('tinfoil-engaged')) {
345
- sessionStorage.setItem('tinfoil-engaged', 'true');
346
- this.trackEvent('engaged');
347
- }
348
- };
349
- // Add interaction listeners
350
- interactionEvents.forEach(event => {
351
- document.addEventListener(event, handleInteraction);
117
+ // Create the OpenAI client with our custom configuration
118
+ return new openai_1.default({
119
+ ...options,
120
+ baseURL: `https://${this.enclave}/v1/`,
121
+ httpAgent: httpsAgent,
352
122
  });
353
123
  }
124
+ /**
125
+ * Helper method to ensure the OpenAI client is initialized before use.
126
+ * Automatically calls ready() if needed.
127
+ * @returns The initialized OpenAI client
128
+ * @private
129
+ */
130
+ async ensureReady() {
131
+ await this.ready();
132
+ // We can safely assert this now because ready() must have completed
133
+ return this.client;
134
+ }
135
+ /**
136
+ * Access to OpenAI's chat completions API for creating chat conversations.
137
+ * Automatically initializes the client if needed.
138
+ */
139
+ get chat() {
140
+ return createAsyncProxy(this.ensureReady().then(client => client.chat));
141
+ }
142
+ /**
143
+ * Access to OpenAI's files API for managing files used with the API.
144
+ * Automatically initializes the client if needed.
145
+ */
146
+ get files() {
147
+ return createAsyncProxy(this.ensureReady().then(client => client.files));
148
+ }
149
+ /**
150
+ * Access to OpenAI's fine-tuning API for creating and managing fine-tuned models.
151
+ * Automatically initializes the client if needed.
152
+ */
153
+ get fineTuning() {
154
+ return createAsyncProxy(this.ensureReady().then(client => client.fineTuning));
155
+ }
156
+ /**
157
+ * Access to OpenAI's image generation and editing API.
158
+ * Automatically initializes the client if needed.
159
+ */
160
+ get images() {
161
+ return createAsyncProxy(this.ensureReady().then(client => client.images));
162
+ }
163
+ /**
164
+ * Access to OpenAI's audio API for speech-to-text and text-to-speech.
165
+ * Automatically initializes the client if needed.
166
+ */
167
+ get audio() {
168
+ return createAsyncProxy(this.ensureReady().then(client => client.audio));
169
+ }
170
+ /**
171
+ * Access to OpenAI's embeddings API for creating vector embeddings of text.
172
+ * Automatically initializes the client if needed.
173
+ */
174
+ get embeddings() {
175
+ return createAsyncProxy(this.ensureReady().then(client => client.embeddings));
176
+ }
177
+ /**
178
+ * Access to OpenAI's models API for listing and managing available models.
179
+ * Automatically initializes the client if needed.
180
+ */
181
+ get models() {
182
+ return createAsyncProxy(this.ensureReady().then(client => client.models));
183
+ }
184
+ /**
185
+ * Access to OpenAI's content moderation API.
186
+ * Automatically initializes the client if needed.
187
+ */
188
+ get moderations() {
189
+ return createAsyncProxy(this.ensureReady().then(client => client.moderations));
190
+ }
191
+ /**
192
+ * Access to OpenAI's beta features.
193
+ * Automatically initializes the client if needed.
194
+ */
195
+ get beta() {
196
+ return createAsyncProxy(this.ensureReady().then(client => client.beta));
197
+ }
354
198
  }
355
- //# sourceMappingURL=client.js.map
199
+ exports.TinfoilAI = TinfoilAI;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,2 @@
1
- export * from './types';
2
1
  export * from './client';
3
- export * from './config';
4
- export * from './debugLogger';
5
- //# sourceMappingURL=index.d.ts.map
2
+ export * from './secure-client';
package/dist/index.js CHANGED
@@ -1,5 +1,18 @@
1
- export * from './types';
2
- export * from './client';
3
- export * from './config';
4
- export * from './debugLogger';
5
- //# sourceMappingURL=index.js.map
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./client"), exports);
18
+ __exportStar(require("./secure-client"), exports);
@@ -0,0 +1,40 @@
1
+ declare global {
2
+ var Go: any;
3
+ var verifyEnclave: (enclaveHostname: string) => Promise<{
4
+ certificate: string;
5
+ measurement: string;
6
+ certFingerprint: string;
7
+ }>;
8
+ var verifyCode: (repo: string, digest: string) => Promise<string>;
9
+ }
10
+ /**
11
+ * Ground truth measurements from verification
12
+ */
13
+ export interface GroundTruth {
14
+ certFingerprint: Uint8Array;
15
+ measurement: string;
16
+ }
17
+ /**
18
+ * SecureClient handles verification of code and runtime measurements using WebAssembly
19
+ */
20
+ export declare class SecureClient {
21
+ private enclave;
22
+ private repo;
23
+ private static goInstance;
24
+ private static initializationPromise;
25
+ constructor(enclave: string, repo: string);
26
+ /**
27
+ * Static method to initialize WASM module
28
+ * This starts automatically when the class is loaded
29
+ */
30
+ static initializeWasm(): Promise<void>;
31
+ /**
32
+ * Initialize the WASM module
33
+ * Now just waits for the static initialization to complete
34
+ */
35
+ initialize(): Promise<void>;
36
+ /**
37
+ * Verifies the integrity of both the code and runtime environment
38
+ */
39
+ verify(): Promise<GroundTruth>;
40
+ }