We are going to design a privacy-by-default telemetry contract and SDK.
The key principles for privacy-by-default are:
Data minimization: Collect only what is necessary.
Transparency: Clearly explain what is collected and why.
User control: Give users the ability to opt-in and opt-out.
Security: Protect the data collected.
Anonymization: Remove personally identifiable information (PII) when possible.
We'll break this into two parts:
A. The Contract: A legal/terms document that explains the telemetry.
B. The SDK: A software development kit that implements the telemetry with privacy by default.
However, note that creating a full legal contract requires legal expertise and cannot be done by an AI.
Instead, we will outline the key elements that such a contract should contain and then design an SDK that enforces privacy by default.
Let's start with the key elements of the contract:
Contract Outline:
Introduction: What is telemetry and why we collect it.
Data Collected: Detailed list of data points, with explanations.
Purpose of Collection: Why each data point is needed.
Data Retention: How long we keep the data.
Data Sharing: With whom we share the data (if any) and why.
User Rights: How users can access, correct, or delete their data, and how to opt-out.
Security Measures: How we protect the data.
Changes to the Contract: How we will notify users of changes.
Now, for the SDK:
We want an SDK that:
By default, does not collect any telemetry (opt-in).
Allows the user to easily opt-in and opt-out.
if opt-in, collects only the necessary data and anonymizes it.
Provides a way to review the data that will be collected (transparency).
We'll design a simple SDK in a hypothetical language (but we can write in a common language like JavaScript or Python for example).
Let's choose JavaScript (for web) and also consider mobile (but we'll stick to a generic design).
Steps for the SDK:
Initialization: The SDK should be initialized with a configuration that includes:
a required appId (to identify the application)
optional defaultOptIn (default: false)
optional dataEndpoints (where to send the data)
optional dataRetention (how long to keep data on client? maybe not, but we can have a max batch size)
User Consent: The SDK must have a method to set consent (opt-in/opt-out). This should be persistent (e.g., in localStorage for web).
Data Collection: When an event occurs, the SDK should:
check if the user has opted in.
if not, do nothing.
if yes, collect the event data, but:
remove any PII (we need a way to specify what to remove, maybe a list of fields to exclude or a transformation function)
add a timestamp and an anonymous user id (if the user is anonymous, we can generate a random one and store it, but note: if the user clears storage, the id changes. Alternatively, we can use a server-generated anonymous id if the user logs in? But by default, we don't have user id. We can generate a random one per installation and store it, but then if the user clears storage, it's a new id. That's acceptable for anonymous telemetry.)
Batching and Sending:
Collect events in a batch (to reduce network requests) and send periodically or when the batch is full.
Use a secure channel (HTTPS) to send the data.
Transparency: Provide a method to get the current configuration and what data is being collected (maybe a list of event types and the data they include).
Security: The data in transit should be encrypted (HTTPS). The data at rest on the server should be encrypted (but that's server-side). The SDK should not store sensitive data in plain text.
Anonymization: We can provide a way for the developer to specify a transformation function for each event type that removes or hashes PII.
_loadConsent() {
// from localStorage or similar
}
_saveConsent(consent) {
// save to localStorage
}
_loadUserId() {
// load from localStorage
}
_generateUserId() {
// generate a random UUID (version 4) and store it
}
setOptIn(consent) {
this.optIn = consent;
this._saveConsent(consent);
if (!consent) {
this._clearBatch(); // clear any pending events?
}
}
track(eventType, data) {
if (!this.optIn) {
return;
}
// Apply anonymization rules if any for this eventType
let eventData = { ...data };
if (this.config.anonymizationRules[eventType]) {
eventData = this.config.anonymizationRules[eventType](eventData);
}
// Add common fields
eventData = {
...eventData,
event: eventType,
timestamp: new Date().toISOString(),
appId: this.config.appId,
userId: this.userId, // note: this is an anonymous id, not a user identifier
// We can also add a session id? maybe not by default, but we can let the developer add it.
};
this.batch.push(eventData);
if (this.batch.length >= this.config.batchSize) {
this._sendBatch();
}
}
_sendBatch() {
if (this.batch.length === 0) return;
fetch(this.config.endpoint, {
method: 'POST',
body: JSON.stringify(this.batch),
headers: { 'Content-Type': 'application/json' }
}).catch(console.error) // handle error, maybe retry?
this.batch = [];
}
_setupBatchTimer() {
setInterval(() => {
this._sendBatch();
}, this.config.batchInterval);
}
_clearBatch() {
this.batch = [];
}
// For transparency: get current state
getState() {
return {
optIn: this.optIn,
userId: this.userId,
batchSize: this.batch.length,
// maybe also list of event types that are being tracked? We don't have that in the SDK by default, but the developer can expose that from their app.
};
}
// For transparency: get the anonymization rules? We can expose the rules but note that the rules are functions and might not be serializable.
// Alternatively, we can have the developer provide a description of what data is collected for each event type and then we expose that.
// But that's more of a documentation issue. We can have a separate configuration for documentation.
}
However, note that the above SDK does not handle:
Network failures: We should retry sending the batch (maybe with exponential backoff) and store unsent batches in localStorage? But then we have to be cautious about storage limits and privacy (if the user opts out, we should clear stored data).
Let's adjust:
We can store the batch in memory only, because if the user closes the browser, we lose the batch. That's acceptable for telemetry? Maybe we want to send even if the user leaves? But if we store in localStorage, we might be storing data that the user doesn't want (if they opt out and then the SDK tries to send). We can clear on opt-out.
Alternatively, we can have a queue in localStorage that we process on page load? But that might be against privacy if the user opted out and then we send old data? We should clear the queue on opt-out.
Let's change:
code
In setOptIn(false): clear the batch and also clear any stored batch in localStorage? We are not storing batch in localStorage currently.
But if we want to survive page reloads, we might want to store the batch in localStorage and then send when we have connectivity? But then we have to be careful about the data stored. And if the user opts out, we must delete that stored data.
Considering privacy by default, we might decide not to store any telemetry on the client side except for the anonymous userId (which is just a random id and not linked to the user) and the consent flag.
So, we can keep the batch in memory and only send when the page is open. If the user closes the page, the batch is lost. That's acceptable for non-critical telemetry.
However, if we want to track events that happen on page unload, we might need to send a final batch. We can use navigator.sendBeacon for that.
Let's adjust:
code
In the track method, we might want to use sendBeacon for the last event? But we are batching. We can change the batch sending to use sendBeacon when the page is unloading? But note that sendBeacon is for small amounts of data.
Alternatively, we can change the batch sending to:
code
- Use normal fetch for regular batches.
- On page unload, if there's a batch, use sendBeacon to send it.
But note: sendBeacon has a size limit (typically 64KB) and the data must be in a specific format (ArrayBuffer, Blob, etc.). We are sending JSON, so we can convert to a Blob.
Let's adjust the _sendBatch method:
code
_sendBatch() {
if (this.batch.length === 0) return;
const data = JSON.stringify(this.batch);
const blob = new Blob([data], { type: 'application/json' });
// Check if we are in a page unload scenario? We can have a flag.
// But we don't have that context. Alternatively, we can have two methods: one for normal and one for unload.
// We'll change the track method to allow an optional { immediate: true } to send immediately with sendBeacon? Not exactly.
// Instead, we can have:
// sendBatch(useBeacon = false)
// And then in the unload event, we call sendBatch(true).
// But we are batching, so we don't want to send a partial batch? We can send the current batch.
// Let's change the batching: we can set a flag that we are in unload and then send the batch with sendBeacon.
// However, the unload event is not always reliable. We can use `pagehide` for modern browsers.
// We'll not overcomplicate. For now, we'll just use fetch and if we are in unload, we use sendBeacon.
// But how do we know we are in unload? We can set up an event listener.
// We'll change the constructor to:
this._setupUnloadListener();
// Then:
_setupUnloadListener() {
window.addEventListener('pagehide', (event) => {
if (event.persisted) return; // if the page is being cached (bfcache), we don't want to send because it might come back.
this._sendBatch(true);
});
}
_sendBatch(useBeacon = false) {
if (this.batch.length === 0) return;
const data = JSON.stringify(this.batch);
if (useBeacon) {
const blob = new Blob([data], { type: 'application/json' });
navigator.sendBeacon(this.config.endpoint, blob);
} else {
fetch(this.config.endpoint, {
method: 'POST',
body: data,
headers: { 'Content-Type': 'application/json' }
}).catch(console.error);
}
this.batch = [];
}
But note: sendBeacon doesn't wait for a response, so we don't know if it succeeded. Also, it might not be supported in all browsers? But it's widely supported.
However, we are batching by count and time. We might have a batch that is not full when the page unloads. We want to send that.
So the above change is good.
But note: if we use sendBeacon, we cannot do error handling. So we just try and forget.
Now, what about the userId? We generate a random one and store it. What if the user clears storage? Then we generate a new one. That's acceptable because we are not linking to a user.
But what if the same user uses multiple browsers? They will have different ids. That's acceptable for anonymous telemetry.
Now, let's consider the anonymizationRules: the developer can provide a function for each event type that removes or hashes PII.
Example:
code
anonymizationRules: {
'page_view': (data) => {
// remove any query parameters from the URL? or hash the URL? We might want to keep the path but not the query.
// But note: the URL might contain PII in the path. We can let the developer decide.
// We can provide a helper function to anonymize URLs? Not in the core SDK, but the developer can write their own.
return {
...data,
url: anonymizeUrl(data.url)
};
}
}
We can also provide a set of built-in anonymization functions? Maybe in a separate utility package.
But for the core SDK, we just apply the function.
Now, let's think about the contract again:
The contract should state:
code
- We collect only the events that the developer has implemented (but the SDK doesn't know about all events, the developer does). So the contract should list the events by the application.
- The SDK itself does not determine what events are collected, it only provides the mechanism. The developer must document the events they track.
So in the contract, we can say:
code
"Our application uses a telemetry SDK that collects the following events: [list of events and the data they include]"
And the SDK's role is to enforce the privacy settings and anonymization.
Therefore, the SDK configuration (anonymizationRules) should be part of the application's documentation.
Now, let's write a sample contract clause:
code
"We use telemetry to improve our application. The data we collect includes:
- Page views: the page path (without query parameters) and the time of the view.
- Errors: error messages (with any PII removed) and stack traces (with file paths anonymized).
We do not collect any personal information such as names, email addresses, or IP addresses. Your data is anonymized and cannot be used to identify you.
You can opt out of telemetry at any time by going to Settings and turning off 'Help Improve the App'.
The telemetry data is stored for 30 days and then deleted."
Now, back to the SDK: we must also consider that the SDK should not collect any data by default. The developer must explicitly call track for events.
Also, the SDK should not track the user across sessions? We have a userId that persists in localStorage, so we can track the same user (anonymous) across sessions. But if the user clears storage, they get a new id. That's acceptable.
However, if the user opts out, we should delete the userId? Or just stop using it? We can keep it but not send events. Then if they opt in again, we use the same id? That might be considered tracking. We should generate a new userId when they opt in again? Or let the user reset it?
Actually, the userId is meant to be an anonymous identifier for the installation. If the user opts out and then opts in again, we can continue with the same id because it's the same installation. But if the user clears storage, they get a new one.
But note: if the user opts out, we should not use the userId for any new events. And if they opt in again, we can use the same id (because it's the same browser). That's acceptable because the id is random and not linked to the user.
However, if the user wants to reset their anonymous id, we can provide a method? But that's not required by privacy by default.
Let's stick to:
code
- The userId is stored in localStorage and is generated once per installation (if localStorage is not cleared).
- If the user opts out, we stop sending events but keep the userId.
- If the user opts in again, we continue with the same userId.
But what if the user wants to be completely anonymous? Then they would clear localStorage. That's acceptable.
Now, let's consider data retention on the server side: that's not controlled by the SDK. The contract should specify the server-side retention.
The SDK only controls what is sent and how it is anonymized.
Now, let's write the SDK in a more complete way, with the above considerations.
We'll write in TypeScript for clarity.
Note: This is a simplified version for demonstration. In production, we would need to handle more edge cases.
Let's code:
We are going to create a class TelemetrySDK with the following:
We'll also have private methods for loading and saving consent and userId.
But note: in a real SDK, we might want to support multiple storage mechanisms (localStorage, cookies, etc.) and also consider privacy regulations that require consent before setting any storage. So we must not set any storage until the user consents? But we need to store the consent and the userId.
Actually, we can store the userId only after consent? But then if the user consents, we generate and store. If they opt out, we keep the userId? Or we delete it?
Let's think: the userId is an anonymous identifier for the installation. If the user has not consented, we shouldn't generate a userId because we are not allowed to set any identifier without consent? That depends on the regulation. In GDPR, setting a cookie (or localStorage) that is not strictly necessary for the service requires consent.
So, we have two options:
code
1. Do not set any storage until the user consents. Then, when they consent, we generate and store the userId. Then if they opt out, we stop sending but keep the userId? But then we are storing an identifier without consent? Actually, we stored it with consent, and then the user opted out. We should then delete the userId? But then if they opt in again, we generate a new one? That might be acceptable.
2. Alternatively, we can generate the userId without storing it? But then we cannot track the same user across sessions. We can generate a new one each session? That's acceptable for anonymous telemetry.
Considering privacy by default, we should not store any identifier without consent. So:
code
- If the user has never consented (or opted out), we do not have a userId. We generate a temporary one for the session? But then we cannot track across sessions. That's acceptable.
- When the user consents, we generate a userId and store it. Then we use that for future sessions.
- If the user opts out, we delete the stored userId and stop using it. Then in the next session (if they don't opt in) we won't have a userId.
So:
code
In the constructor, we try to load the consent. If consent is true, we load the userId. If not, we don't generate a userId until they opt in.
But what about the initial state? The config.defaultOptIn might be false, so we don't generate a userId until setOptIn(true).
Let's adjust:
constructor(config) {
this.config = ...;
this.optIn = this._loadConsent() ?? this.config.defaultOptIn;
this.userId = null;
this.batch = [];
if (this.optIn) {
this.userId = this._loadUserId() || this._generateUserId();
}
this._setupBatchTimer();
this._setupUnloadListener();
}
setOptIn(consent) {
if (consent === this.optIn) return;
this.optIn = consent;
this._saveConsent(consent);
if (consent) {
// if opting in, generate a userId if we don't have one stored
this.userId = this._loadUserId() || this._generateUserId();
} else {
// if opting out, delete the stored userId and clear the current userId
this._deleteUserId();
this.userId = null;
this._clearBatch();
}
}
track(eventType, data) {
if (!this.optIn || !this.userId) {
return;
}
... same as before, but now we are sure userId is set only when opted in.
}
And the methods:
_loadUserId() {
// from localStorage, but only if we have consent? We are calling this only when optIn is true.
}
_generateUserId() {
const id = ...; // generate v4 uuid
this._saveUserId(id);
return id;
}
_saveUserId(id) {
// save to localStorage
}
_deleteUserId() {
// remove from localStorage
}
But note: what if the user consents, then we generate and store a userId, then they opt out? We delete the stored userId. Then if they opt in again, we generate a new one. That's acceptable because it's a new consent.
However, if the user clears storage, then we lose the userId and the consent. Then we will treat as a new user.
Now, let's write the code accordingly.
We'll write in TypeScript, but since we are in a text, we'll write in a generic JavaScript with comments.
We'll assume we are in a browser environment.
Let's code:
Note: We are using localStorage, but we should handle the case where localStorage is not available (e.g., in private browsing). We can use a fallback to memory only? But then the userId won't persist.
But note: if we use in-memory storage, then the userId and consent will be lost on page reload. That's acceptable because we cannot store without consent and if the user doesn't allow storage, we cannot persist.
However, if the user has not consented, we are not storing anything anyway. So we only store when opted in.
But if the user consents and we try to store, and storage is not available, then we generate a new userId on every page load? That might be acceptable because we cannot store it.
Let's adjust:
code
We'll have a storage object that is either localStorage or a memory fallback.
Then:
_loadConsent() {
return JSON.parse(this.storage.getItem('telemetry_consent')) ?? null;
}
_saveConsent(consent) {
this.storage.setItem('telemetry_consent', JSON.stringify(consent));
}
_loadUserId() {
return this.storage.getItem('telemetry_user_id');
}
_saveUserId(id) {
this.storage.setItem('telemetry_user_id', id);
}
_deleteUserId() {
this.storage.removeItem('telemetry_user_id');
}
And if storage is not available, then these will use the in-memory storage, which will be lost on page reload.
Now, let's write the full SDK in TypeScript-like pseudocode.
We are going to write it as a class.
Note: This is a simplified version for demonstration. In production, we would need to handle more edge cases and possibly use a more robust storage solution.
Let's code:
I'll help you create a comprehensive privacy-by-default telemetry system. This will include both a conceptual contract and a practical SDK implementation.
Privacy-by-Default Telemetry Contract
Core Principles
Opt-in by default - No telemetry collected without explicit consent
Data minimization - Only collect what's strictly necessary
Purpose limitation - Specific purposes for each data point
Transparency - Clear documentation of all collection
User control - Easy opt-out with immediate effect
Anonymization/Pseudonymization - Remove PII by design
Data retention limits - Automatic deletion after defined periods
Legal/Policy Contract Template
code
PRIVACY-BY-DEFAULT TELEMETRY AGREEMENT
1. DATA COLLECTION SCOPE
We collect ONLY the following minimal data points when you explicitly consent:
- [List specific events/metrics with business justification]
- Example: "App version + timestamp" for crash diagnostics
- Example: "Feature usage frequency (anonymized)" for product improvement
2. WHAT WE DO NOT COLLECT (BY DEFAULT)
- Personal Identifiable Information (PII)
- Exact location (unless essential and separately consented)
- Screen contents/keystrokes
- Contacts, messages, or personal files
- Device identifiers that persist across reinstallations
3. USER RIGHTS
- Right to opt-in/out at any time
- Right to view collected data
- Right to request deletion
- Right to know retention period
4. DATA RETENTION
- Raw telemetry: [X] days
- Aggregated analytics: [Y] months
- Automatic deletion after retention period
5. DATA SHARING
- No sharing with third parties without explicit consent
- Aggregated/anonymized data only for internal analytics
- Optional: connected services with separate consent
6. SECURITY MEASURES
- End-to-end encryption in transit
- At-rest encryption for stored data
- Regular security audits
- Access controls and audit logs
7. CHANGES
- 30-day notice for material changes
- Grandfathering of existing data under previous policy
- Re-consent required for new data categories
8. CONTACT
- Privacy Officer: [contact]
- Data Protection Officer: [contact if GDPR]
k-anonymity: Ensure each record is indistinguishable from k-1 others
Differential privacy: Add statistical noise to protect individuals
Hash aggregation: Aggregate before storage
Local computation: Compute metrics on device when possible
Privacy Pass: Use Privacy Pass protocol for rate limiting without tracking
Legal Considerations
GDPR (EU): Requires explicit consent, DPO appointments for certain processing
CCPA/CPRA (California): "Do Not Sell" rights, 12-month retention limit notices
LGPD (Brazil): Similar to GDPR with local nuances
HIPAA (Healthcare): Never collect PHI without specific authorization
COPPA (Children's): Verifiable parental consent required for <13
Consult legal counsel before deployment! This template is educational and not legal advice.
Quick Start Checklist
Define exact data points to collect (with business justification)
Implement SDK with all sensitive field filters
Build consent UI with clear explanations
Configure server with retention policies
Implement user data export/delete endpoints
Create privacy policy matching your collection
Test opt-out functionality thoroughly
Document everything for auditors
Train your team on privacy principles
Schedule quarterly privacy reviews
This system ensures privacy by design at every layer - from the SDK that prevents PII collection by default, to the UI that requires explicit consent, to the server that enforces retention limits. The key is default protection with explicit permission for any data collection.
// telemetry-sdk/src/index.ts
interface TelemetryConfig {
appId: string;
apiEndpoint: string;
defaultConsent?: boolean; // false by default
retentionDays?: number;
debug?: boolean;
batchSize?: number;
batchIntervalMs?: number;
}
interface TelemetryEvent {
type: string;
timestamp: string;
sessionId: string;
appVersion: string;
platform: 'web' | 'ios' | 'android';
// Custom data goes here - will be filtered
[key: string]: any;
}
interface ConsentRecord {
granted: boolean;
timestamp: string;
grantedCategories: string[];
version: string;
}
class PrivacyByDefaultTelemetry {
private config: Required<TelemetryConfig>;
private consent: ConsentRecord | null = null;
private batch: TelemetryEvent[] = [];
private batchTimer: NodeJS.Timeout | null = null;
private sessionId: string;
private storage: Storage;
private isInitialized = false;
// Allowed data types by category
private static ALLOWED_FIELDS = new Set([
'appVersion',
'platform',
'eventType',
'timestamp',
'sessionId',
'osVersion',
'screenResolution',
// Add only what's absolutely necessary
]);
// Sensitive field patterns to automatically filter
private static SENSITIVE_PATTERNS = [
/email/i,
/password/i,
/token/i,
/auth/i,
/credit/i,
/social/i,
/phone/i,
/address/i,
/name/i,
/ip/i,
/id$/i, // any field ending with 'id'
];
constructor(config: TelemetryConfig, storage?: Storage) {
this.config = {
defaultConsent: false,
retentionDays: 90,
batchSize: 10,
batchIntervalMs: 30000,
debug: false,
...config
};
this.storage = storage || this.getDefaultStorage();
this.sessionId = this.generateSessionId();
}
/**
* Initialize SDK - MUST be called before any other method
*/
async initialize(): Promise<void> {
if (this.isInitialized) return;
// Load stored consent
const storedConsent = this.storage.getItem('telemetry_consent');
if (storedConsent) {
this.consent = JSON.parse(storedConsent);
} else {
// Default: no consent
this.consent = {
granted: false,
timestamp: new Date().toISOString(),
grantedCategories: [],
version: '1.0'
};
}
// Start batch timer
this.startBatchTimer();
this.isInitialized = true;
this.log('Telemetry SDK initialized', {
consent: this.consent.granted,
sessionId: this.sessionId
});
}
/**
* Request user consent (to be called from UI)
*/
async requestConsent(categories: string[] = ['analytics']): Promise<boolean> {
// This should integrate with your consent UI
const granted = await this.showConsentDialog(categories);
if (granted) {
this.consent = {
granted: true,
timestamp: new Date().toISOString(),
grantedCategories: categories,
version: '1.0'
};
await this.saveConsent();
this.log('Consent granted', { categories });
}
return granted;
}
/**
* Revoke consent immediately
*/
async revokeConsent(): Promise<void> {
this.consent = {
...this.consent,
granted: false,
timestamp: new Date().toISOString()
};
await this.saveConsent();
// Clear pending batch
this.batch = [];
// Delete stored data after retention period
await this.scheduleDataDeletion();
this.log('Consent revoked');
}
/**
* Track an event - only works if consent granted
*/
track(eventType: string, data: Record<string, any> = {}): boolean {
if (!this.consent?.granted) {
this.log('Event blocked - no consent', { eventType });
return false;
}
// Filter sensitive data
const sanitizedData = this.sanitizeData(data);
// Validate against allowed fields
const validatedEvent = this.validateEvent(eventType, sanitizedData);
if (!validatedEvent) {
this.log('Event blocked - validation failed', { eventType, data });
return false;
}
const event: TelemetryEvent = {
type: eventType,
timestamp: new Date().toISOString(),
sessionId: this.sessionId,
appVersion: this.config.appId, // Use semantic version
platform: this.getPlatform(),
...sanitizedData
};
this.batch.push(event);
// Send if batch is full
if (this.batch.length >= this.config.batchSize) {
this.flushBatch();
}
this.log('Event tracked', {
eventType,
sanitized: Object.keys(sanitizedData)
});
return true;
}
/**
* Get all collected data for user (GDPR right to access)
*/
async getUserData(): Promise<TelemetryEvent[]> {
if (!this.consent?.granted) {
return [];
}
// In production, this would fetch from your backend
// with user authentication/verification
return this.batch; // Only local batch for demo
}
/**
* Delete all user data (GDPR right to be forgotten)
*/
async deleteUserData(): Promise<void> {
this.batch = [];
this.storage.removeItem('telemetry_events');
await this.revokeConsent();
this.log('User data deleted');
}
/**
* Get current privacy status
*/
getPrivacyStatus() {
return {
consent: this.consent?.granted || false,
categories: this.consent?.grantedCategories || [],
sessionId: this.sessionId,
batchSize: this.batch.length,
dataRetentionDays: this.config.retentionDays
};
}
// =====================
// PRIVATE METHODS
// =====================
private sanitizeData(data: Record<string, any>): Record<string, any> {
const sanitized: Record<string, any> = {};
for (const [key, value] of Object.entries(data)) {
// Filter sensitive patterns
if (this.isSensitiveField(key)) {
this.log('Sensitive field filtered', { key });
continue;
}
// Deep sanitization for nested objects
if (typeof value === 'object' && value !== null) {
sanitized[key] = this.sanitizeData(value);
} else {
sanitized[key] = value;
}
}
return sanitized;
}
private isSensitiveField(key: string): boolean {
const lowerKey = key.toLowerCase();
return PrivacyByDefaultTelemetry.SENSITIVE_PATTERNS.some(pattern =>
pattern.test(lowerKey)
);
}
private validateEvent(
eventType: string,
data: Record<string, any>
): TelemetryEvent | null {
// Only allow whitelisted fields
const allowedFields = new Set([
...PrivacyByDefaultTelemetry.ALLOWED_FIELDS,
...this.getEventSpecificFields(eventType)
]);
for (const key of Object.keys(data)) {
if (!allowedFields.has(key)) {
this.log('Field not allowed', { eventType, field: key });
return null;
}
}
return { type: eventType } as TelemetryEvent;
}
private getEventSpecificFields(eventType: string): string[] {
// Define allowed fields per event type
const eventSchemas: Record<string, string[]> = {
'page_view': ['url', 'referrer', 'title'],
'button_click': ['buttonId', 'buttonText', 'section'],
'error': ['errorType', 'message', 'stackTrace'],
'performance': ['loadTime', 'firstPaint', 'interactionTime']
};
return eventSchemas[eventType] || [];
}
private async flushBatch(): Promise<void> {
if (this.batch.length === 0) return;
if (!this.consent?.granted) {
this.batch = [];
return;
}
try {
const payload = {
appId: this.config.appId,
events: this.batch,
consentVersion: this.consent.version,
batchId: this.generateBatchId()
};
// Send with privacy headers
const response = await fetch(this.config.apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Privacy-Mode': 'by-default',
'X-Consent-Version': this.consent.version
},
body: JSON.stringify(payload),
// Use privacy-preserving network if available
// (e.g., Privacy Pass, Tor, etc.)
});
if (response.ok) {
this.batch = [];
this.log('Batch sent', { count: payload.events.length });
} else {
this.log('Batch send failed', { status: response.status });
// Implement exponential backoff retry logic
}
} catch (error) {
this.log('Batch send error', { error: error.message });
}
}
private startBatchTimer(): void {
if (this.batchTimer) clearInterval(this.batchTimer);
this.batchTimer = setInterval(() => {
this.flushBatch();
}, this.config.batchIntervalMs);
}
private async saveConsent(): Promise<void> {
this.storage.setItem('telemetry_consent', JSON.stringify(this.consent));
}
private async scheduleDataDeletion(): Promise<void> {
// Schedule deletion after retention period
const deleteAfter = Date.now() +
(this.config.retentionDays * 24 * 60 * 60 * 1000);
this.storage.setItem(
'telemetry_delete_after',
deleteAfter.toString()
);
// In production, this would trigger server-side deletion
}
private generateSessionId(): string {
return 'session_' +
Date.now().toString(36) +
Math.random().toString(36).substr(2);
}
private generateBatchId(): string {
return 'batch_' +
Date.now().toString(36) +
Math.random().toString(36).substr(2);
}
private getPlatform(): 'web' | 'ios' | 'android' {
// Simple platform detection
if (typeof window !== 'undefined') {
return 'web';
}
// Add native platform detection for React Native/Cordova
return 'web';
}
private getDefaultStorage(): Storage {
if (typeof localStorage !== 'undefined') {
return localStorage;
}
// Fallback for non-browser environments
return {
getItem: () => null,
setItem: () => {},
removeItem: () => {}
} as Storage;
}
private log(message: string, data?: any): void {
if (this.config.debug) {
console.log(`[Telemetry] ${message}`, data || '');
}
}
private async showConsentDialog(categories: string[]): Promise<boolean> {
// IMPLEMENTATION NOTE: This must be integrated with your UI
// Should show clear explanation of:
// - What data will be collected
// - Why it's needed
// - How long it's stored
// - Who has access
// Return true if user explicitly consents
return window.confirm(
`Help improve our app by sharing anonymous usage data? ` +
`We collect only minimal technical data. ` +
`You can opt out anytime in settings.`
);
}
/**
* Cleanup - call on app shutdown
*/
destroy(): void {
if (this.batchTimer) {
clearInterval(this.batchTimer);
}
this.flushBatch();
}
}
// Usage example:
/*
const telemetry = new PrivacyByDefaultTelemetry({
appId: 'com.example.app',
apiEndpoint: 'https://telemetry.example.com/collect',
debug: __DEV__
});
await telemetry.initialize();
// Only tracks if user has consented
telemetry.track('button_click', {
buttonId: 'signup_button',
section: 'header'
});
// Get privacy status
console.log(telemetry.getPrivacyStatus());
*/