content-security-toolkit 1.0.0 → 1.0.1

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 (54) hide show
  1. package/README.md +203 -41
  2. package/package.json +12 -5
  3. package/dist/core/mediator/handlers/baseEventHandler.d.ts +0 -65
  4. package/dist/core/mediator/handlers/baseEventHandler.js +0 -99
  5. package/dist/core/mediator/handlers/index.d.ts +0 -9
  6. package/dist/core/mediator/handlers/index.js +0 -34
  7. package/dist/strategies/AbstractStrategy.mediator.d.ts +0 -162
  8. package/dist/strategies/AbstractStrategy.mediator.js +0 -349
  9. package/dist/strategies/DevToolsStrategy copy.d.ts +0 -85
  10. package/dist/strategies/DevToolsStrategy copy.js +0 -362
  11. package/dist/strategies/DevToolsStrategy-detectorManager.d.ts +0 -70
  12. package/dist/strategies/DevToolsStrategy-detectorManager.js +0 -309
  13. package/dist/strategies/DevToolsStrategy-simple.d.ts +0 -75
  14. package/dist/strategies/DevToolsStrategy-simple.js +0 -366
  15. package/dist/strategies/StrategyRegistry.d.ts +0 -133
  16. package/dist/strategies/StrategyRegistry.js +0 -379
  17. package/dist/utils/base/LoggableComponent.d.ts +0 -62
  18. package/dist/utils/base/LoggableComponent.js +0 -95
  19. package/dist/utils/debuggerDetector/debuggerDetectionWorker.d.ts +0 -6
  20. package/dist/utils/debuggerDetector/debuggerDetectionWorker.js +0 -24
  21. package/dist/utils/debuggerDetector/debuggerDetector.d.ts +0 -55
  22. package/dist/utils/debuggerDetector/debuggerDetector.js +0 -158
  23. package/dist/utils/debuggerDetector/firefoxDetector.d.ts +0 -8
  24. package/dist/utils/debuggerDetector/firefoxDetector.js +0 -64
  25. package/dist/utils/detection.d.ts +0 -29
  26. package/dist/utils/detection.js +0 -267
  27. package/dist/utils/detectors/debuggerDetectionWorker.d.ts +0 -6
  28. package/dist/utils/detectors/debuggerDetectionWorker.js +0 -24
  29. package/dist/utils/detectors/firefoxDetector.d.ts +0 -8
  30. package/dist/utils/detectors/firefoxDetector.js +0 -64
  31. package/dist/utils/logging/LogLevel.d.ts +0 -21
  32. package/dist/utils/logging/LogLevel.js +0 -46
  33. package/dist/utils/logging/LoggingConfig.d.ts +0 -68
  34. package/dist/utils/logging/LoggingConfig.js +0 -64
  35. package/dist/utils/logging/LoggingFactory.d.ts +0 -22
  36. package/dist/utils/logging/LoggingFactory.js +0 -61
  37. package/dist/utils/logging/LoggingService.d.ts +0 -235
  38. package/dist/utils/logging/LoggingService.js +0 -385
  39. package/dist/utils/logging/SimpleLoggingService.d.ts +0 -39
  40. package/dist/utils/logging/SimpleLoggingService.js +0 -58
  41. package/dist/utils/logging/advanced/LogLevel.d.ts +0 -21
  42. package/dist/utils/logging/advanced/LogLevel.js +0 -46
  43. package/dist/utils/logging/advanced/LoggingConfig.d.ts +0 -68
  44. package/dist/utils/logging/advanced/LoggingConfig.js +0 -64
  45. package/dist/utils/logging/advanced/LoggingFactory.d.ts +0 -22
  46. package/dist/utils/logging/advanced/LoggingFactory.js +0 -61
  47. package/dist/utils/logging/advanced/LoggingService.d.ts +0 -235
  48. package/dist/utils/logging/advanced/LoggingService.js +0 -385
  49. package/dist/utils/protectedContentManager-simple.d.ts +0 -86
  50. package/dist/utils/protectedContentManager-simple.js +0 -180
  51. package/dist/utils/securityOverlayManager-observer-pause.d.ts +0 -283
  52. package/dist/utils/securityOverlayManager-observer-pause.js +0 -878
  53. package/dist/utils/securityOverlayManager-simple.d.ts +0 -197
  54. package/dist/utils/securityOverlayManager-simple.js +0 -552
@@ -1,366 +0,0 @@
1
- import { isBrowser, getBrowser } from "../utils/detection";
2
- import { ProtectedContentManager } from "../utils/protectedContentManager";
3
- import { SecurityOverlayManager } from "../utils/securityOverlayManager";
4
- import { intervalManager } from "../utils/intervalManager";
5
- import { AbstractStrategy, StrategyErrorType } from "./AbstractStrategy";
6
- import { DebuggerDetector } from "../utils/detectors/debuggerDetector";
7
- import { TimingDetector } from "../utils/detectors/timingDetector";
8
- import { DateToStringDetector } from "../utils/detectors/dateToStringDetector";
9
- /**
10
- * Strategy for detecting and responding to DevTools usage
11
- */
12
- export class DevToolsStrategy extends AbstractStrategy {
13
- /**
14
- * Create a new DevToolsStrategy
15
- * @param options Options for customizing the DevTools protection
16
- * @param targetElement Element containing sensitive content
17
- * @param customHandler Optional custom handler for DevTools detection
18
- * @param debugMode Enable debug mode for troubleshooting
19
- */
20
- constructor(options, targetElement = null, customHandler, debugMode = false) {
21
- super("DevToolsStrategy", debugMode);
22
- this.intervalId = null;
23
- this.taskId = null;
24
- this.isDevToolsOpen = false;
25
- this.targetElement = null;
26
- this.contentManager = null;
27
- // Detectors
28
- this.debuggerDetector = null;
29
- this.timingDetector = null;
30
- this.dateToStringDetector = null;
31
- this.activeDetector = null;
32
- this.options = {
33
- overlayOptions: {
34
- title: "Developer Tools Detected",
35
- message: "For security reasons, this content is not available while developer tools are open.",
36
- secondaryMessage: "Please close developer tools to continue viewing this content.",
37
- textColor: "white",
38
- backgroundColor: "rgba(255, 0, 0, 0.7)",
39
- },
40
- showOverlay: true,
41
- checkFrequency: 1000,
42
- hideContent: false,
43
- ...options,
44
- };
45
- this.targetElement = targetElement;
46
- this.customHandler = customHandler;
47
- this.browserInfo = getBrowser();
48
- // Initialize content manager if target element is provided
49
- if (targetElement) {
50
- this.contentManager = new ProtectedContentManager(targetElement, debugMode);
51
- }
52
- // Initialize overlay manager
53
- this.overlayManager = new SecurityOverlayManager(debugMode);
54
- this.log("Initialized with checkFrequency:", this.options.checkFrequency);
55
- this.log("Detected browser:", this.browserInfo.name, this.browserInfo.version);
56
- // Initialize the appropriate detector based on browser
57
- this.initDetectors();
58
- }
59
- /**
60
- * Initialize the appropriate detector based on browser
61
- */
62
- initDetectors() {
63
- return this.safeExecute("initDetectors", StrategyErrorType.INITIALIZATION, () => {
64
- if (!isBrowser())
65
- return;
66
- try {
67
- // Common callback for all detectors
68
- const onDevToolsChange = (isOpen) => {
69
- this.handleDevToolsStateChange(isOpen);
70
- };
71
- // Initialize the debugger detector (for Chrome and Edge)
72
- this.debuggerDetector = new DebuggerDetector({
73
- timeoutDuration: 50, // 50ms timeout for detection
74
- onDevToolsChange,
75
- debugMode: this.debugMode,
76
- });
77
- // Initialize the timing detector (for Firefox)
78
- this.timingDetector = new TimingDetector({
79
- onDevToolsChange,
80
- debugMode: this.debugMode,
81
- thresholdMultiplier: 4, // Adjust sensitivity
82
- });
83
- // Initialize the date-to-string detector (for Safari and fallback)
84
- if (DateToStringDetector.isSupported()) {
85
- this.dateToStringDetector = new DateToStringDetector({
86
- onDevToolsChange,
87
- debugMode: this.debugMode,
88
- threshold: 2, // Default threshold
89
- });
90
- }
91
- // Set the active detector based on browser
92
- if (this.browserInfo.name === "firefox") {
93
- this.activeDetector = this.timingDetector;
94
- this.log("Using TimingDetector for Firefox");
95
- }
96
- else if (this.browserInfo.name === "safari") {
97
- if (this.dateToStringDetector) {
98
- this.activeDetector = this.dateToStringDetector;
99
- this.log("Using DateToStringDetector for Safari");
100
- }
101
- else {
102
- this.activeDetector = this.debuggerDetector;
103
- this.log("Using DebuggerDetector for Safari (fallback)");
104
- }
105
- }
106
- else {
107
- this.activeDetector = this.debuggerDetector;
108
- this.log("Using DebuggerDetector for", this.browserInfo.name);
109
- }
110
- this.log("Detectors initialized");
111
- }
112
- catch (error) {
113
- this.handleError(StrategyErrorType.INITIALIZATION, "Failed to initialize detectors", error);
114
- // Log more details about the error to help with troubleshooting
115
- if (this.debugMode) {
116
- console.error("Detector initialization error details:", error);
117
- }
118
- }
119
- });
120
- }
121
- /**
122
- * Handle DevTools state changes from any detection method
123
- */
124
- handleDevToolsStateChange(isOpen) {
125
- return this.safeExecute("handleDevToolsStateChange", StrategyErrorType.APPLICATION, () => {
126
- // Only take action if state has changed
127
- if (isOpen !== this.isDevToolsOpen) {
128
- this.isDevToolsOpen = isOpen;
129
- this.log(`DevTools state changed: ${isOpen ? "open" : "closed"}`);
130
- if (isOpen) {
131
- this.applyDevToolsProtection();
132
- }
133
- else {
134
- this.removeDevToolsProtection();
135
- }
136
- // Call custom handler if provided
137
- if (this.customHandler) {
138
- this.customHandler(isOpen);
139
- }
140
- }
141
- });
142
- }
143
- /**
144
- * Start monitoring for DevTools usage
145
- */
146
- startMonitoring() {
147
- return this.safeExecute("startMonitoring", StrategyErrorType.APPLICATION, () => {
148
- if (typeof window === "undefined")
149
- return;
150
- this.log("Starting DevTools monitoring");
151
- // Register with IntervalManager for periodic checks
152
- this.taskId = intervalManager.registerTask("devtools-detection", () => this.safeExecute("intervalTask", StrategyErrorType.APPLICATION, () => {
153
- // Use the active detector
154
- if (this.activeDetector) {
155
- this.activeDetector.checkDevTools();
156
- }
157
- // Always check overlay state if DevTools are open
158
- if (this.isDevToolsOpen) {
159
- this.overlayManager.checkAndRestoreOverlay();
160
- }
161
- }), this.options.checkFrequency);
162
- // Force initial check
163
- if (this.activeDetector) {
164
- this.activeDetector.checkDevTools();
165
- }
166
- });
167
- }
168
- /**
169
- * Apply DevTools protection by creating overlay and event blocker
170
- */
171
- applyDevToolsProtection() {
172
- return this.safeExecute("applyDevToolsProtection", StrategyErrorType.APPLICATION, () => {
173
- if (!isBrowser())
174
- return;
175
- if (this.options.hideContent) {
176
- // Hide sensitive content
177
- this.hideSensitiveContent();
178
- }
179
- if (this.options.showOverlay) {
180
- // Create overlay using the overlay manager
181
- this.overlayManager.showOverlay({
182
- ...this.options.overlayOptions,
183
- blockEvents: true, // Block all events
184
- autoRestore: true, // Restore overlay if removed from DOM
185
- });
186
- }
187
- this.log("DevTools protection applied");
188
- });
189
- }
190
- /**
191
- * Hide sensitive content when DevTools is open
192
- */
193
- hideSensitiveContent() {
194
- return this.safeExecute("hideSensitiveContent", StrategyErrorType.APPLICATION, () => {
195
- if (!this.targetElement || !this.contentManager)
196
- return;
197
- this.contentManager.hideContent({
198
- title: this.options.overlayOptions?.title,
199
- message: this.options.overlayOptions?.message,
200
- secondaryMessage: this.options.overlayOptions?.secondaryMessage,
201
- textColor: "black",
202
- backgroundColor: "rgba(0, 0, 0, 0.05)",
203
- });
204
- this.log("Sensitive content hidden");
205
- });
206
- }
207
- /**
208
- * Restore sensitive content when DevTools is closed
209
- */
210
- restoreSensitiveContent() {
211
- return this.safeExecute("restoreSensitiveContent", StrategyErrorType.REMOVAL, () => {
212
- if (!this.contentManager)
213
- return;
214
- this.contentManager.restoreContent();
215
- this.log("Sensitive content restored");
216
- });
217
- }
218
- /**
219
- * Remove DevTools protection
220
- */
221
- removeDevToolsProtection() {
222
- return this.safeExecute("removeDevToolsProtection", StrategyErrorType.REMOVAL, () => {
223
- if (typeof document === "undefined")
224
- return;
225
- if (this.options.hideContent) {
226
- // Restore sensitive content
227
- this.restoreSensitiveContent();
228
- }
229
- if (this.options.showOverlay) {
230
- // Remove overlay using the overlay manager
231
- this.overlayManager.removeOverlay();
232
- }
233
- this.log("DevTools protection removed");
234
- });
235
- }
236
- /**
237
- * Apply the protection strategy
238
- */
239
- apply() {
240
- return this.safeExecute("apply", StrategyErrorType.APPLICATION, () => {
241
- if (this.isAppliedFlag) {
242
- this.log("Protection already applied");
243
- return;
244
- }
245
- this.startMonitoring();
246
- this.isAppliedFlag = true;
247
- this.log("Protection applied");
248
- });
249
- }
250
- /**
251
- * Remove the protection strategy
252
- * Override the base implementation to handle additional cleanup
253
- */
254
- remove() {
255
- return this.safeExecute("remove", StrategyErrorType.REMOVAL, () => {
256
- if (!this.isAppliedFlag) {
257
- this.log("Protection not applied");
258
- return;
259
- }
260
- // Clean up the detectors
261
- if (this.debuggerDetector) {
262
- this.debuggerDetector.dispose();
263
- this.debuggerDetector = null;
264
- }
265
- if (this.timingDetector) {
266
- this.timingDetector.dispose();
267
- this.timingDetector = null;
268
- }
269
- if (this.dateToStringDetector) {
270
- this.dateToStringDetector.dispose();
271
- this.dateToStringDetector = null;
272
- }
273
- this.activeDetector = null;
274
- // Clear interval via IntervalManager
275
- if (this.taskId !== null) {
276
- intervalManager.unregisterTask(this.taskId);
277
- this.taskId = null;
278
- this.log("Interval task unregistered");
279
- }
280
- // Also clear the old interval for backwards compatibility or if both are used
281
- if (this.intervalId !== null && typeof window !== "undefined") {
282
- window.clearInterval(this.intervalId);
283
- this.intervalId = null;
284
- this.log("Legacy interval cleared");
285
- }
286
- // Call the parent class remove method to handle event cleanup
287
- super.remove();
288
- // Remove protections
289
- this.removeDevToolsProtection();
290
- this.isAppliedFlag = false;
291
- this.isDevToolsOpen = false;
292
- this.log("Protection removed");
293
- });
294
- }
295
- /**
296
- * Update DevTools protection options
297
- * @param options New options
298
- */
299
- updateOptions(options) {
300
- return this.safeExecute("updateOptions", StrategyErrorType.OPTION_UPDATE, () => {
301
- const typedOptions = options;
302
- this.log("Updating options", typedOptions);
303
- // Store previous options for comparison
304
- const previousOptions = { ...this.options };
305
- this.options = {
306
- ...this.options,
307
- ...typedOptions,
308
- };
309
- // If protection is already applied, update the overlay if needed
310
- if (this.isAppliedFlag && this.isDevToolsOpen) {
311
- // Check if any visual options changed
312
- const visualOptionsChanged = previousOptions.overlayOptions?.title !== this.options.overlayOptions?.title ||
313
- previousOptions.overlayOptions?.message !== this.options.overlayOptions?.message ||
314
- previousOptions.overlayOptions?.secondaryMessage !== this.options.overlayOptions?.secondaryMessage ||
315
- previousOptions.overlayOptions?.backgroundColor !== this.options.overlayOptions?.backgroundColor ||
316
- previousOptions.overlayOptions?.textColor !== this.options.overlayOptions?.textColor;
317
- if (visualOptionsChanged) {
318
- this.removeDevToolsProtection();
319
- this.applyDevToolsProtection();
320
- this.log("Reapplied protection with updated visual options");
321
- }
322
- }
323
- // Update check frequency if it changed
324
- if (typedOptions.checkFrequency &&
325
- this.taskId !== null &&
326
- previousOptions.checkFrequency !== typedOptions.checkFrequency) {
327
- // Unregister and re-register with new frequency
328
- intervalManager.unregisterTask(this.taskId);
329
- this.taskId = intervalManager.registerTask("devtools-detection", () => this.safeExecute("intervalTask", StrategyErrorType.APPLICATION, () => {
330
- // Use active detector
331
- if (this.activeDetector) {
332
- this.activeDetector.checkDevTools();
333
- }
334
- if (this.isDevToolsOpen) {
335
- this.overlayManager.checkAndRestoreOverlay();
336
- }
337
- }), this.options.checkFrequency);
338
- this.log(`Check frequency updated to ${this.options.checkFrequency}ms`);
339
- }
340
- });
341
- }
342
- /**
343
- * Set debug mode
344
- * @param enabled Whether debug mode should be enabled
345
- */
346
- setDebugMode(enabled) {
347
- return this.safeExecute("setDebugMode", StrategyErrorType.OPTION_UPDATE, () => {
348
- super.setDebugMode(enabled);
349
- // Update debug mode for the detectors
350
- if (this.debuggerDetector) {
351
- this.debuggerDetector.setDebugMode(enabled);
352
- }
353
- if (this.timingDetector) {
354
- this.timingDetector.setDebugMode(enabled);
355
- }
356
- if (this.dateToStringDetector) {
357
- this.dateToStringDetector.setDebugMode(enabled);
358
- }
359
- // Also update debug mode for managers
360
- if (this.contentManager && this.targetElement) {
361
- this.contentManager = new ProtectedContentManager(this.targetElement, enabled);
362
- }
363
- this.overlayManager = new SecurityOverlayManager(enabled);
364
- });
365
- }
366
- }
@@ -1,133 +0,0 @@
1
- import type { ProtectionStrategy } from "../types";
2
- import type { MediatorAware, ProtectionMediator } from "../core/mediator/types";
3
- /**
4
- * Error types for strategy operations
5
- */
6
- export declare enum StrategyErrorType {
7
- REGISTRATION_ERROR = "registration_error",
8
- UNREGISTRATION_ERROR = "unregistration_error",
9
- APPLICATION_ERROR = "application_error",
10
- REMOVAL_ERROR = "removal_error",
11
- INVALID_STRATEGY = "invalid_strategy",
12
- STRATEGY_NOT_FOUND = "strategy_not_found",
13
- STRATEGY_ALREADY_REGISTERED = "strategy_already_registered"
14
- }
15
- /**
16
- * Custom error class for strategy registry operations
17
- */
18
- export declare class StrategyRegistryError extends Error {
19
- readonly errorType: StrategyErrorType;
20
- readonly strategyId?: string | undefined;
21
- readonly originalError?: Error | undefined;
22
- constructor(errorType: StrategyErrorType, message: string, strategyId?: string | undefined, originalError?: Error | undefined);
23
- }
24
- export interface StrategyRegistryOptions {
25
- debugMode?: boolean;
26
- }
27
- /**
28
- * Registry for managing protection strategies
29
- * Provides centralized access and lifecycle management
30
- */
31
- export declare class StrategyRegistry implements MediatorAware {
32
- readonly COMPONENT_NAME = "StrategyRegistry";
33
- private strategies;
34
- private logger;
35
- private mediator;
36
- constructor(options?: StrategyRegistryOptions);
37
- /**
38
- * Set the mediator to communicate with other components
39
- * @param mediator The protection mediator
40
- */
41
- setMediator(mediator: ProtectionMediator): void;
42
- /**
43
- * Register a strategy with the registry
44
- * @param id Unique identifier for the strategy
45
- * @param strategy Strategy instance
46
- * @returns True if registration was successful
47
- * @throws StrategyRegistryError if registration fails
48
- */
49
- register(id: string, strategy: ProtectionStrategy): boolean;
50
- /**
51
- * Unregister a strategy from the registry
52
- * @param id Strategy ID to unregister
53
- * @returns True if unregistration was successful
54
- * @throws StrategyRegistryError if unregistration fails
55
- */
56
- unregister(id: string): boolean;
57
- /**
58
- * Get a strategy by ID
59
- * @param id Strategy ID
60
- * @returns The strategy instance or undefined if not found
61
- */
62
- getStrategy(id: string): ProtectionStrategy | undefined;
63
- /**
64
- * Check if a strategy is registered
65
- * @param id Strategy ID
66
- * @returns True if the strategy is registered
67
- */
68
- hasStrategy(id: string): boolean;
69
- /**
70
- * Apply a specific strategy
71
- * @param id Strategy ID to apply
72
- * @returns True if the strategy was applied successfully
73
- * @throws StrategyRegistryError if application fails
74
- */
75
- applyStrategy(id: string): boolean;
76
- /**
77
- * Apply all registered strategies
78
- * @returns Array of strategy IDs that failed to apply
79
- */
80
- applyAllStrategies(): string[];
81
- /**
82
- * Remove a specific strategy
83
- * @param id Strategy ID to remove
84
- * @returns True if removal was successful
85
- * @throws StrategyRegistryError if removal fails
86
- */
87
- removeStrategy(id: string): boolean;
88
- /**
89
- * Remove all registered strategies
90
- * @returns Array of strategy IDs that failed to remove
91
- */
92
- removeAllStrategies(): string[];
93
- /**
94
- * Get all registered strategy IDs
95
- * @returns Array of strategy IDs
96
- */
97
- getStrategyIds(): string[];
98
- /**
99
- * Get all registered strategies
100
- * @returns Map of strategy IDs to strategy instances
101
- */
102
- getAllStrategies(): Map<string, ProtectionStrategy>;
103
- /**
104
- * Get all applied strategies
105
- * @returns Array of strategy IDs that are currently applied
106
- */
107
- getAppliedStrategies(): string[];
108
- /**
109
- * Set debug mode for all strategies that support it
110
- * @param enabled Whether debug mode should be enabled
111
- */
112
- setDebugMode(enabled: boolean): void;
113
- /**
114
- * Clear the registry (remove all strategies first)
115
- */
116
- clear(): void;
117
- /**
118
- * Publish a strategy applied event through the mediator
119
- * @param strategyId ID of the strategy that was applied
120
- */
121
- private publishStrategyAppliedEvent;
122
- /**
123
- * Publish a strategy removed event through the mediator
124
- * @param strategyId ID of the strategy that was removed
125
- */
126
- private publishStrategyRemovedEvent;
127
- /**
128
- * Publish an error event through the mediator
129
- * @param strategyId ID of the strategy that had an error
130
- * @param error The error that occurred
131
- */
132
- private publishErrorEvent;
133
- }