@anonympins/fingerprint 0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 anonympins
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,170 @@
1
+ # fingerprint
2
+ ![](https://img.shields.io/github/v/release/anonympins/fingerprint)
3
+ ![](https://img.shields.io/github/license/anonympins/fingerprint)
4
+
5
+ An HTTP(S) client mitigation and anti-bot protection library for Node.js/Express, based on digital fingerprinting and dynamic Proof-of-Work (PoW) challenges.
6
+
7
+ ## How It Works
8
+
9
+ This system is designed to identify and slow down bots and automated scripts by evaluating the "suspicion" level of each incoming request. Instead of outright blocking, it imposes challenges with a difficulty proportional to the suspicion score, penalizing bots without significantly impacting legitimate users.
10
+
11
+ The process unfolds in three steps:
12
+
13
+ 1. **Identification & Fingerprinting**: A unique fingerprint is generated for each device based on browser characteristics (client-side) and request headers (server-side). A `device_id` cookie is used to track the device over time.
14
+ 2. **Suspicion Score Calculation**: Several indicators are analyzed to calculate a suspicion score:
15
+ * **Header Anomalies**: Missing `User-Agent`, `Accept-Language`, etc.
16
+ * **Device Behavior**: Rapid fingerprint changes (User-Agent rotation).
17
+ * **IP Behavior**: An excessive number of different devices seen from the same IP, or a single device using a large number of IPs (proxy rotation).
18
+ * **Inconsistency**: A low similarity score between the current fingerprint and the initial one associated with the `device_id` (cookie theft detection).
19
+ 3. **Dynamic Challenge**: If the suspicion score exceeds a certain threshold, a challenge is presented to the user. The difficulty and type of challenge depend on the score:
20
+ * **Level 1 (Low Suspicion)**: CPU-based PoW challenge (SHA-256).
21
+ * **Level 2 (Medium Suspicion)**: Memory-intensive PoW challenge.
22
+ * **Level 3 (High Suspicion)**: Complex challenge (e.g., TSP - Traveling Salesperson Problem) or a CAPTCHA.
23
+
24
+ Once the challenge is solved, a clearance "ticket" is issued via a cookie, exempting the user from new challenges for a set period.
25
+
26
+ ## Features
27
+
28
+ - **Multi-Factor Fingerprinting**: Combines client-side data (`hardwareConcurrency`, `deviceMemory`, `screen`, `canvas`, `webgl`) and server-side data (`User-Agent`, `Client-Hints`).
29
+ - **Weighted Suspicion Engine**: Calculates a score based on behavioral and technical indicators.
30
+ - **Variable-Difficulty Proof-of-Work Challenges**:
31
+ - `cpu_target`: An "analog" CPU challenge where difficulty is finely tuned to the suspicion score.
32
+ - `memory`: A challenge that allocates an amount of memory proportional to the suspicion level.
33
+ - `tsp`: An optimization challenge (Traveling Salesperson Problem) for the most suspicious cases.
34
+ - **Secure Ticket System**: Uses HMAC-SHA256 signatures to validate clearances and prevent tampering.
35
+ - **Pluggable Datastore**: Supports external datastores like Redis for state persistence and scalability across multiple server instances.
36
+ - **Express.js Middleware**: Easy integration into an Express application with `powMiddleware`.
37
+ - **Timing Attack Protection**: Uses `crypto.timingSafeEqual` for secure ticket validation.
38
+
39
+ ## Installation and Usage
40
+
41
+ This module is designed for a Node.js environment.
42
+
43
+ ### Prerequisites
44
+
45
+ Ensure you have a cookie-parser middleware (like `cookie-parser`) set up in your Express application.
46
+
47
+ ### Configuration
48
+
49
+ Define a secret key for signing PoW tickets in your environment variables.
50
+
51
+ ```bash
52
+ export POW_SECRET="your_secret_key_of_at_least_32_characters"
53
+ ```
54
+
55
+ ### Integration Example
56
+
57
+ For the `powMiddleware` to work, it needs a configuration defining the weights of suspicion indicators and the challenge trigger thresholds.
58
+
59
+ ```javascript
60
+ import express from 'express';
61
+ import cookieParser from 'cookie-parser';
62
+ // The `configurePow` function is a conceptual example. In the actual implementation,
63
+ // you would pass the configuration to the middleware, for example, via a factory function.
64
+ import { powMiddleware /*, configurePow */ } from './fingerprint.js'; // Adjust the path
65
+
66
+ const app = express();
67
+ app.use(cookieParser());
68
+
69
+ // Configuration of weights and thresholds for calculating the suspicion score.
70
+ // These values should be adjusted based on traffic and expected user behavior.
71
+ const securityConfig = {
72
+ weights: {
73
+ historyScore: 0.3, // Penalizes IP rotation (proxy)
74
+ rotationScore: 0.5, // Penalizes rapid fingerprint changes (user-agent, etc.)
75
+ headerAnomalyScore: 0.1, // Penalizes abnormal headers (missing UA, etc.)
76
+ inconsistencyScore: 0.8 // Strongly penalizes inconsistency between the current and initial fingerprint (stolen cookie)
77
+ },
78
+ thresholds: {
79
+ low: 20, // Score from which a CPU challenge is issued
80
+ medium: 45, // Score for a Memory challenge
81
+ high: 75 // Score for a complex challenge (TSP/Captcha)
82
+ }
83
+ };
84
+
85
+ // In a real-world scenario, you would configure the middleware.
86
+ // For example: const configuredPowMiddleware = createPowMiddleware(securityConfig);
87
+ const powMiddlewareInstance = powMiddleware(securityConfig);
88
+
89
+ // Enable trust proxy if your app is behind a reverse proxy (Nginx, etc.)
90
+ // to correctly retrieve the client's IP.
91
+ app.set('trust proxy', 1);
92
+
93
+ // Apply the protection middleware to all routes or to specific routes.
94
+ // You would use the configured middleware here.
95
+ app.use(powMiddlewareInstance);
96
+
97
+ app.get('/', (req, res) => {
98
+ res.send('Welcome to the protected page!');
99
+ });
100
+
101
+ app.listen(3000, () => console.log('Server started on port 3000'));
102
+ ```
103
+
104
+ ## Public API
105
+
106
+ In addition to the main middleware, several functions are exported to allow for more advanced integrations.
107
+
108
+ ### Main Functions
109
+
110
+ #### `powMiddleware(req, res, next)`
111
+ The main Express middleware. It orchestrates identification, suspicion calculation, and challenge issuance. It is the main entry point of the library.
112
+
113
+ #### `configureStore(store)`
114
+ Allows replacing the in-memory store with an external datastore (like Redis) for persistence and scaling.
115
+
116
+ ```javascript
117
+ import { configureStore } from './fingerprint.js';
118
+ import { createRedisStore } from './redis-store.js'; // Assuming you have a redis store implementation
119
+
120
+ const redisStore = createRedisStore(process.env.REDIS_URL);
121
+ configureStore(redisStore);
122
+ ```
123
+
124
+ #### `identifyRequest(req, res)`
125
+ An asynchronous function that returns an identification string for a given request, based on its suspicion level (`device:<id>`, `suspicious_medium:<ip>`, etc.). Useful for integration with a custom rate-limiter.
126
+
127
+ ```javascript
128
+ import { RateLimiterMemory } from 'rate-limiter-flexible';
129
+ import { identifyRequest } from './fingerprint.js';
130
+
131
+ const rateLimiter = new RateLimiterMemory({
132
+ keyPrefix: 'rate_limit',
133
+ points: 10,
134
+ duration: 1,
135
+ });
136
+
137
+ app.use(async (req, res, next) => {
138
+ try {
139
+ const key = await identifyRequest(req, res);
140
+ await rateLimiter.consume(key);
141
+ next();
142
+ } catch (err) {
143
+ res.status(429).send('Too Many Requests');
144
+ }
145
+ });
146
+ ```
147
+
148
+ ### Utilities
149
+
150
+ #### `isTicketValid(ip, ticket)`
151
+ Checks the validity of a `pow_clearance` cookie. Returns `true` if the ticket is present, not expired, and correctly signed for the given IP.
152
+
153
+ #### `FingerprintBuilder` (Class)
154
+ A class for building granular server-side fingerprints.
155
+
156
+ ```javascript
157
+ const builder = new FingerprintBuilder();
158
+ builder.add("ua", req.headers["user-agent"]);
159
+ builder.add("os", req.headers["sec-ch-ua-platform"]);
160
+ const fp = builder.toString(); // "os:hash1|ua:hash2"
161
+ ```
162
+
163
+ #### `getDeviceFingerprint()`
164
+ *Client-side function only.* Generates a detailed browser fingerprint using APIs like Canvas, WebGL, etc.
165
+
166
+ ---
167
+
168
+ ## License
169
+
170
+ This project is licensed under the MIT License. See the `LICENSE` file for more details.