@paywalls-net/filter 1.3.1 → 1.3.3

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/README.md CHANGED
@@ -12,6 +12,24 @@ npm install @paywalls-net/filter
12
12
  - `PAYWALLS_PUBLISHER_ID`: The unique identifier for the publisher using paywalls.net services.
13
13
  - `PAYWALLS_CLOUD_API_KEY`: The API key for accessing paywalls.net services. NOTE: This key should be treated like a password and kept secret and stored in a secure secrets vault or environment variable.
14
14
 
15
+ ## Architecture: Path Prefix Ownership
16
+
17
+ The SDK uses a **path prefix ownership strategy** for VAI (Validated Actor Inventory) endpoints. All requests to `/pw/*` are automatically proxied to the paywalls.net cloud-api service with API key authentication.
18
+
19
+ ### Benefits
20
+ - **Version Independent**: New VAI endpoints work automatically without SDK updates
21
+ - **Reduced Publisher Friction**: Publishers don't need to update client code when new features are added
22
+ - **Future Proof**: Supports nested paths like `/pw/v2/*` or `/pw/analytics/*`
23
+
24
+ ### Proxied Endpoints
25
+ Any request matching `/pw/*` is proxied with authentication:
26
+ - `/pw/vai.json` - VAI classification (JSON)
27
+ - `/pw/vai.js` - VAI classification (JavaScript)
28
+ - `/pw/jwks.json` - JSON Web Key Set for signature verification
29
+ - Future endpoints automatically supported
30
+
31
+ This strategy minimizes version coupling between the client SDK and the paywalls.net platform.
32
+
15
33
  ## Usage
16
34
  The following is an example of using the SDK with Cloudflare Workers:
17
35
 
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "Client SDK for integrating paywalls.net bot filtering and authorization services into your server or CDN.",
4
4
  "author": "paywalls.net",
5
5
  "license": "MIT",
6
- "version": "1.3.1",
6
+ "version": "1.3.3",
7
7
  "publishConfig": {
8
8
  "access": "public"
9
9
  },
package/src/index.js CHANGED
@@ -52,23 +52,36 @@ function getAllHeaders(request) {
52
52
  }
53
53
 
54
54
  /**
55
- * Check if the request is for a VAI endpoint (vai.json or vai.js)
55
+ * Check if the request is for a VAI endpoint (vai.json, vai.js, or jwks.json)
56
56
  * @param {Request} request - The incoming request
57
57
  * @param {string} vaiPath - The path prefix for VAI endpoints (default: '/pw')
58
58
  * @returns {boolean} - True if this is a VAI endpoint request
59
59
  */
60
+ /**
61
+ * Check if request is for a VAI endpoint.
62
+ * Uses path prefix matching to proxy all /pw/* requests without hardcoding specific endpoints.
63
+ * This makes the SDK future-proof - new VAI endpoints work automatically without SDK updates.
64
+ *
65
+ * @param {Request} request - The incoming request
66
+ * @param {string} vaiPath - VAI path prefix (default: '/pw')
67
+ * @returns {boolean} - True if request should be proxied to cloud-api
68
+ */
60
69
  function isVAIRequest(request, vaiPath = '/pw') {
61
70
  try {
62
71
  const url = new URL(request.url || `http://host${request.uri || ''}`);
63
72
  const pathname = url.pathname;
64
- return pathname === `${vaiPath}/vai.json` || pathname === `${vaiPath}/vai.js`;
73
+ // Proxy everything under the VAI path prefix
74
+ return pathname.startsWith(`${vaiPath}/`);
65
75
  } catch (err) {
66
76
  return false;
67
77
  }
68
78
  }
69
79
 
70
80
  /**
71
- * Proxy VAI requests to the cloud-api service
81
+ * Proxy VAI requests to the cloud-api service.
82
+ * Proxies the entire request path without endpoint-specific logic,
83
+ * allowing new VAI endpoints to work automatically.
84
+ *
72
85
  * @param {Object} cfg - Configuration object with paywallsAPIHost and paywallsAPIKey
73
86
  * @param {Request} request - The incoming request
74
87
  * @returns {Promise<Response>} - The proxied response from cloud-api
@@ -76,8 +89,9 @@ function isVAIRequest(request, vaiPath = '/pw') {
76
89
  async function proxyVAIRequest(cfg, request) {
77
90
  try {
78
91
  const url = new URL(request.url || `http://host${request.uri || ''}`);
79
- const isJson = url.pathname.endsWith('/vai.json');
80
- const cloudApiPath = isJson ? '/pw/vai.json' : '/pw/vai.js';
92
+
93
+ // Proxy the entire path as-is (path prefix ownership strategy)
94
+ const cloudApiPath = url.pathname + url.search;
81
95
 
82
96
  // Get all request headers
83
97
  const headers = getAllHeaders(request);
@@ -5,6 +5,39 @@ let cachedUserAgentPatterns = null;
5
5
  let cacheTimestamp = null;
6
6
  const CACHE_DURATION = 60 * 60 * 1000; // 1 hour
7
7
 
8
+ // Cache for user agent classifications
9
+ //
10
+ // CACHE STRATEGY CONSIDERATIONS:
11
+ //
12
+ // Current approach: Raw user-agent string as cache key
13
+ // - Pro: No parsing overhead before cache lookup
14
+ // - Pro: Exact matches are very fast
15
+ // - Con: User-agents with minor version differences create separate cache entries
16
+ // - Con: Cache could grow large with many unique UAs (especially browser traffic)
17
+ //
18
+ // Alternative approaches to consider:
19
+ // 1. Normalized keys (e.g., browser name + major version + OS)
20
+ // - Would improve hit rate and reduce memory
21
+ // - But adds parsing cost before every cache check
22
+ // - Risk: Might miss pattern-specific matches if patterns are version-sensitive
23
+ //
24
+ // 2. LRU cache with size limit
25
+ // - Bounds memory usage
26
+ // - Evicts least-recently-used entries
27
+ // - Good if traffic patterns are consistent
28
+ //
29
+ // 3. Separate caches for bots vs browsers
30
+ // - Bot UAs are typically more stable (better cache hit rate)
31
+ // - Browser UAs change frequently with versions (lower hit rate)
32
+ // - Could optimize each differently
33
+ //
34
+ // Decision: Start with raw UA keys until we have production metrics showing:
35
+ // - Actual cache size growth
36
+ // - Cache hit rates
37
+ // - Memory pressure
38
+ // Then optimize based on data rather than speculation.
39
+ let classificationCache = new Map();
40
+
8
41
  /**
9
42
  * Fetch user agent patterns from the API and cache them.
10
43
  * @returns {Promise<Array>} The user agent patterns.
@@ -39,6 +72,10 @@ export async function loadAgentPatterns(cfg) {
39
72
  }));
40
73
 
41
74
  cacheTimestamp = now;
75
+
76
+ // Clear classification cache when patterns are refreshed
77
+ classificationCache.clear();
78
+
42
79
  return cachedUserAgentPatterns;
43
80
  } catch (error) {
44
81
  console.error('Error loading agent patterns:', error);
@@ -53,6 +90,14 @@ export async function loadAgentPatterns(cfg) {
53
90
  * @returns {Promise<Object>} An object containing the browser, OS, operator, usage, and user_initiated status.
54
91
  */
55
92
  export async function classifyUserAgent(cfg, userAgent) {
93
+ // Check classification cache first (single lookup is more efficient than has + get)
94
+ const cached = classificationCache.get(userAgent);
95
+ if (cached !== undefined) {
96
+ console.log(`User agent classification cache hit for: ${userAgent}`);
97
+ return cached;
98
+ }
99
+ console.log(`User agent classification cache miss for: ${userAgent}`);
100
+
56
101
  const parsedUA = new UAParser(userAgent).getResult();
57
102
 
58
103
  const browser = parsedUA.browser.name || 'Unknown';
@@ -64,7 +109,7 @@ export async function classifyUserAgent(cfg, userAgent) {
64
109
  if (!config.patterns) continue;
65
110
  for (const pattern of config.patterns) {
66
111
  if (new RegExp(pattern).test(userAgent)) {
67
- return {
112
+ const result = {
68
113
  operator: config.operator,
69
114
  agent: config.agent || browser,
70
115
  usage: config.usage,
@@ -72,12 +117,18 @@ export async function classifyUserAgent(cfg, userAgent) {
72
117
  browser,
73
118
  os,
74
119
  };
120
+ // Cache the classification result
121
+ classificationCache.set(userAgent, result);
122
+ return result;
75
123
  }
76
124
  }
77
125
  }
78
126
 
79
- return {
127
+ const result = {
80
128
  browser,
81
129
  os
82
130
  };
131
+ // Cache the default classification
132
+ classificationCache.set(userAgent, result);
133
+ return result;
83
134
  }