forked from ANYTECHS/clips-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics.ts
More file actions
540 lines (481 loc) · 16.5 KB
/
Copy pathanalytics.ts
File metadata and controls
540 lines (481 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import { logger } from "@/app/lib/logger";
import { scheduleWork } from "@/app/lib/mainThreadOptimization";
/**
* Analytics Tracking Utility
* * Provides a unified interface for tracking page views and events across different analytics providers.
* Respects user cookie consent preferences and filters out PII.
*/
/** Valid analytics infrastructure platform destination names */
type AnalyticsProvider = 'ga4' | 'plausible' | 'custom' | 'none';
/** Dictionary object mapping custom metadata event keys to scalar values */
interface EventProperties {
[key: string]: string | number | boolean | undefined;
}
/** Cookie configurations tracking user-defined privacy collection limits */
interface CookieConsent {
/** Permission allowing primary session storage and operational cookies */
essential: boolean;
/** Permission allowing performance evaluation metrics tracking entries */
analytics: boolean;
/** Permission mapping tracking pixels and target advertisement parameters */
marketing: boolean;
}
// PII patterns to filter out
const PII_PATTERNS = [
/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, // Email
/\b[G][A-Z0-9]{55}\b/g, // Stellar public key
/\b0x[a-fA-F0-9]{40}\b/g, // Ethereum address
/\b\d{3}-\d{2}-\d{4}\b/g, // SSN
/\b\d{16}\b/g, // Credit card
];
/**
* Core Analytics class orchestrating initialization, consent monitoring,
* data sanitization, and event forwarding across tracking providers.
*/
class Analytics {
private provider: AnalyticsProvider;
private isInitialized: boolean = false;
private consentGiven: boolean = false;
private debugMode: boolean = false;
/**
* Initializes the analytics management state machine and attaches consent state listeners.
*/
constructor() {
this.provider = this.getProvider();
this.debugMode = process.env.NODE_ENV === 'development';
// Listen for consent changes
if (typeof window !== 'undefined') {
this.checkConsent();
window.addEventListener('cookie-consent-updated', this.handleConsentUpdate.bind(this));
}
}
/**
* Get the analytics provider from environment variable
* @returns Resolved vendor enum assignment identifier.
*/
private getProvider(): AnalyticsProvider {
const provider = process.env.NEXT_PUBLIC_ANALYTICS_PROVIDER?.toLowerCase();
switch (provider) {
case 'ga4':
case 'plausible':
case 'custom':
return provider;
default:
return 'none';
}
}
/**
* Check if user has given analytics consent
*/
private checkConsent(): void {
if (typeof window === 'undefined') return;
try {
const savedConsent = localStorage.getItem('cookie-consent');
if (savedConsent) {
const consent: CookieConsent = JSON.parse(savedConsent);
this.consentGiven = consent.analytics === true;
}
} catch (error) {
logger.error('Failed to check analytics consent:', error);
this.consentGiven = false;
}
}
/**
* Handle consent update events
* @param event - Custom event carrying updated user cookie choices.
*/
private handleConsentUpdate(event: Event): void {
const customEvent = event as CustomEvent<CookieConsent>;
this.consentGiven = customEvent.detail.analytics === true;
if (this.consentGiven && !this.isInitialized) {
this.initialize();
}
}
/**
* Initialize the analytics provider
*/
public initialize(): void {
if (this.isInitialized || !this.consentGiven) return;
if (this.provider === 'none') return;
try {
switch (this.provider) {
case 'ga4':
this.initializeGA4();
break;
case 'plausible':
this.initializePlausible();
break;
case 'custom':
this.initializeCustom();
break;
}
this.isInitialized = true;
this.log('Analytics initialized:', this.provider);
} catch (error) {
logger.error('Failed to initialize analytics:', error);
}
}
/**
* Initialize Google Analytics 4
*/
private initializeGA4(): void {
const measurementId = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID;
if (!measurementId) {
logger.warn('GA4 measurement ID not configured');
return;
}
// Load gtag script
const script = document.createElement('script');
script.async = true;
script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
script.crossOrigin = 'anonymous';
// Analytics is not needed for the page to be interactive, so it's
// deprioritized relative to the app's own scripts (#917).
script.setAttribute('fetchpriority', 'low');
script.onerror = () => {
logger.error('Failed to load GA4 script (network or ad-blocker); analytics disabled for this session.');
};
// Subresource Integrity (issue #801): gtag.js is served dynamically per
// measurement ID and Google explicitly does not support pinning it with
// SRI (the file can change without notice, which would break tracking
// the moment the hash goes stale). NEXT_PUBLIC_GA4_SCRIPT_SRI_HASH is
// opt-in for teams that have accepted that tradeoff and want to pin a
// known-good snapshot anyway; the docs/SECURITY.md SRI section explains
// the risk. Left unset by default.
const ga4Integrity = process.env.NEXT_PUBLIC_GA4_SCRIPT_SRI_HASH;
if (ga4Integrity) {
script.integrity = ga4Integrity;
}
document.head.appendChild(script);
// Initialize gtag
window.dataLayer = window.dataLayer || [];
function gtag(...args: any[]) {
window.dataLayer.push(args);
}
window.gtag = gtag;
gtag('js', new Date());
gtag('config', measurementId, {
anonymize_ip: true,
cookie_flags: 'SameSite=None;Secure',
});
}
/**
* Initialize Plausible Analytics
*/
private initializePlausible(): void {
const domain = process.env.NEXT_PUBLIC_PLAUSIBLE_DOMAIN || window.location.hostname;
const script = document.createElement('script');
script.defer = true;
script.crossOrigin = 'anonymous';
script.setAttribute('data-domain', domain);
script.setAttribute('fetchpriority', 'low');
script.onerror = () => {
logger.error('Failed to load Plausible script (network or ad-blocker); analytics disabled for this session.');
};
// Subresource Integrity (issue #801): plausible.io/js/script.js is a
// rolling "latest" URL with no first-party version-pinned path, so
// "pin to a specific version" here means pinning to a known-good SRI
// hash of a snapshot rather than a versioned URL — set
// NEXT_PUBLIC_PLAUSIBLE_SCRIPT_SRI_HASH once one has been captured (see
// docs/SECURITY.md for the exact command). Falls back to the
// unpinned script (current behavior) when unset.
script.src = process.env.NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL || 'https://plausible.io/js/script.js';
const plausibleIntegrity = process.env.NEXT_PUBLIC_PLAUSIBLE_SCRIPT_SRI_HASH;
if (plausibleIntegrity) {
script.integrity = plausibleIntegrity;
}
document.head.appendChild(script);
}
/**
* Initialize custom analytics (logs to console or custom endpoint)
*/
private initializeCustom(): void {
this.log('Custom analytics initialized');
}
/**
* Sanitize data to remove PII
* @param data - Target parameter, string, or collection array passed down for compliance evaluation.
* @returns Redacted variant safe to transport over analytics lines.
*/
private sanitize(data: any): any {
if (typeof data === 'string') {
let sanitized = data;
PII_PATTERNS.forEach(pattern => {
sanitized = sanitized.replace(pattern, '[REDACTED]');
});
return sanitized;
}
if (typeof data === 'object' && data !== null) {
const sanitized: any = Array.isArray(data) ? [] : {};
for (const key in data) {
// Skip keys that likely contain PII
if (/email|wallet|address|phone|ssn|card/i.test(key)) {
sanitized[key] = '[REDACTED]';
} else {
sanitized[key] = this.sanitize(data[key]);
}
}
return sanitized;
}
return data;
}
/**
* Log debug messages in development
* @param args - Arbitrary values to pipe down to stdout tracking structures.
*/
private log(...args: any[]): void {
if (this.debugMode) {
logger.debug('[Analytics]', ...args);
}
}
/**
* Track a page view
* @param path - Destination web route string tracked for user engagement maps.
*/
public trackPageView(path: string): void {
if (!this.consentGiven) {
this.log('Page view not tracked - no consent:', path);
return;
}
// PII sanitization and provider dispatch aren't needed for this frame to
// paint, so they run at idle time instead of on the click/navigation
// that triggered them.
scheduleWork(() => {
const sanitizedPath = this.sanitize(path);
this.log('Page view:', sanitizedPath);
try {
switch (this.provider) {
case 'ga4':
if (window.gtag) {
window.gtag('event', 'page_view', {
page_path: sanitizedPath,
});
}
break;
case 'plausible':
if (window.plausible) {
window.plausible('pageview', { props: { path: sanitizedPath } });
}
break;
case 'custom':
this.sendCustomEvent('page_view', { path: sanitizedPath });
break;
}
} catch (error) {
logger.error('Failed to track page view:', error);
}
}, 'background');
}
/**
* Track a custom event
* @param name - Metric event namespace descriptor string.
* @param properties - Accompanying analytical contextual metrics metadata properties object.
*/
public trackEvent(name: string, properties?: EventProperties): void {
if (!this.consentGiven) {
this.log('Event not tracked - no consent:', name);
return;
}
// Same reasoning as trackPageView: sanitization + dispatch is non-critical
// and shouldn't run in the same task as the interaction that fired it.
scheduleWork(() => {
const sanitizedProperties = properties ? this.sanitize(properties) : {};
this.log('Event:', name, sanitizedProperties);
try {
switch (this.provider) {
case 'ga4':
if (window.gtag) {
window.gtag('event', name, sanitizedProperties);
}
break;
case 'plausible':
if (window.plausible) {
window.plausible(name, { props: sanitizedProperties });
}
break;
case 'custom':
this.sendCustomEvent(name, sanitizedProperties);
break;
}
} catch (error) {
logger.error('Failed to track event:', error);
}
}, 'background');
}
/**
* Send event to custom analytics endpoint
* @param name - Metric event namespace descriptor string.
* @param properties - Sanitized metadata dictionary mapping event metrics properties.
*/
private sendCustomEvent(name: string, properties: any): void {
const endpoint = process.env.NEXT_PUBLIC_ANALYTICS_ENDPOINT;
if (!endpoint) {
this.log('Custom event (no endpoint):', name, properties);
return;
}
fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
event: name,
properties,
timestamp: new Date().toISOString(),
url: window.location.href,
referrer: document.referrer,
}),
}).catch(error => {
logger.error('Failed to send custom event:', error);
});
}
/**
* Track user signup
* @param method - Authentication path technique string used by the entity.
*/
public trackSignup(method?: string): void {
this.trackEvent('user_signup', { method });
}
/**
* Track video upload
* @param fileSize - Size metric specified in bytes.
* @param duration - Running time measurement specified in seconds.
*/
public trackVideoUpload(fileSize?: number, duration?: number): void {
this.trackEvent('video_upload', {
file_size: fileSize,
duration,
});
}
/**
* Track NFT minting
* @param clipId - Documented identity identifier mapping the video component index tracking entry.
*/
public trackNFTMint(clipId?: string): void {
this.trackEvent('nft_mint', {
clip_id: clipId,
});
}
/**
* Track earnings report export
* @param format - Export container compression scheme layout format descriptor.
*/
public trackEarningsExport(format?: string): void {
this.trackEvent('earnings_export', { format });
}
/**
* Track wallet connection
* @param walletType - Provider framework design identifier name.
*/
public trackWalletConnect(walletType?: string): void {
this.trackEvent('wallet_connect', {
wallet_type: walletType,
});
}
/**
* Track wallet disconnection
* @param walletType - Provider framework design identifier name.
*/
public trackWalletDisconnect(walletType?: string): void {
this.trackEvent('wallet_disconnect', {
wallet_type: walletType,
});
}
/**
* Track wallet creation (embedded/auto-generated wallet)
* @param walletType - Provider framework design identifier name.
*/
public trackWalletCreated(walletType?: string): void {
this.trackEvent('wallet_created', {
wallet_type: walletType,
});
}
/**
* Track secret key import
* @param walletType - Provider framework design identifier name.
*/
public trackWalletImport(walletType?: string): void {
this.trackEvent('wallet_import', {
wallet_type: walletType,
});
}
/**
* Track Friendbot funding (testnet only)
* @param walletType - Provider framework design identifier name.
*/
public trackWalletFunded(walletType?: string): void {
this.trackEvent('wallet_funded', {
wallet_type: walletType,
});
}
/**
* Track an on-chain payment transaction.
* Amount is bucketed to avoid storing precise financial data.
* @param params - Configuration object payload mapping details of the confirmed operation.
* @param params.walletType - Provider wallet descriptor string.
* @param params.assetCode - Token asset identifier ticker code symbol. Defaults to 'XLM'.
* @param params.amountBucket - Binned size evaluation index category tag description.
* @param params.network - Ledger landscape target connection mode flag.
*/
public trackTransaction(params: {
walletType?: string;
assetCode?: string;
amountBucket?: string;
network?: string;
}): void {
this.trackEvent('wallet_transaction', {
wallet_type: params.walletType,
asset_code: params.assetCode ?? 'XLM',
amount_bucket: params.amountBucket,
network: params.network,
});
}
/**
* Track a trustline change (add or remove).
* @param params - Structural parameter context documenting trust modification operations.
* @param params.action - State adjustment instruction value.
* @param params.assetCode - Target currency text indicator code.
* @param params.walletType - Active credential source environment category designation.
* @param params.network - Node transport tracking context configuration marker.
*/
public trackTrustlineChange(params: {
action: 'add' | 'remove';
assetCode: string;
walletType?: string;
network?: string;
}): void {
this.trackEvent('trustline_change', {
action: params.action,
asset_code: params.assetCode,
wallet_type: params.walletType,
network: params.network,
});
}
}
// Singleton instance
const analytics = new Analytics();
// Export the instance and types
export default analytics;
export type { EventProperties, AnalyticsProvider };
/**
* Bucket a numeric amount into a range string for privacy-safe analytics.
* e.g. 0.5 → "0-1", 5 → "1-10", 50 → "10-100", 500 → "100+"
* * @param amount - Raw float transactional processing currency value.
* @returns Categorical partition string bounding the underlying transaction value.
*/
export function bucketAmount(amount: number): string {
if (amount <= 0) return "0";
if (amount < 1) return "0-1";
if (amount < 10) return "1-10";
if (amount < 100) return "10-100";
if (amount < 1000) return "100-1000";
return "1000+";
}
// Extend Window interface for TypeScript
declare global {
interface Window {
dataLayer: any[];
gtag: (...args: any[]) => void;
plausible: (event: string, options?: { props?: any }) => void;
}
}