falseok 0.5.0 → 0.5.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/bin/falseok.js CHANGED
@@ -340,7 +340,8 @@ function readMemory(path) {
340
340
  try {
341
341
  return SiteMemory.fromDict(data);
342
342
  } catch (e) {
343
- throw new Error(`${path}: not a falseok site memory file (${e.message})`);
343
+ // fromDict already says "not a falseok memory file (...)": keep one line, do not wrap it again
344
+ throw new Error(String(e.message).startsWith("not a falseok memory file") ? e.message : `not a falseok memory file (${e.message})`);
344
345
  }
345
346
  }
346
347
 
package/index.d.ts CHANGED
@@ -79,13 +79,13 @@ export interface CheckOptions {
79
79
  url?: string | null;
80
80
  /** The address you ended up at after redirects; may be relative to `url`. */
81
81
  finalUrl?: string | null;
82
- /** Below this many characters of visible text a page is an empty shell (default 150). */
82
+ /** Below this many characters of visible text a page is an empty shell (default 150). A number; other values are coerced as before (numeric strings, null), and TypeError only for what cannot be compared with a number (a Symbol). */
83
83
  minText?: number;
84
- /** Your own rules instead of the bundled ones. */
84
+ /** Your own rules instead of the bundled ones. An array (or any iterable of compiled rules); TypeError if it is not iterable. */
85
85
  signatures?: Signatures | null;
86
- /** Ignore these signal ids. */
86
+ /** Ignore these signal ids: one id as a string, or any iterable of ids: array, Set, Map keys, generator (TypeError if not iterable). */
87
87
  disableIds?: string | Iterable<string> | null;
88
- /** Accept these categories, e.g. "login_wall" when you scrape behind a login. Throws on an unknown name. */
88
+ /** Accept these categories, e.g. "login_wall" when you scrape behind a login: one name, or any iterable of names (TypeError if not iterable). Throws on an unknown name. */
89
89
  allowCategories?: Category | Iterable<Category> | null;
90
90
  /** The current time in epoch milliseconds, for Retry-After dates (default Date.now()). */
91
91
  now?: number;
package/index.js CHANGED
@@ -4,7 +4,7 @@ const { checkPage, loadSignatures, VERDICTS } = require("./lib/page");
4
4
  const { SiteMemory, checkPagesWithMemory } = require("./lib/memory");
5
5
  const { checkApi } = require("./lib/api");
6
6
 
7
- const version = "0.5.0";
7
+ const version = "0.5.1";
8
8
 
9
9
  /** checkPage over a list of pages: each item is { html, ...options } or a bare html string/Buffer. */
10
10
  function checkPages(pages, options = {}) {
package/lib/api.js CHANGED
@@ -6,9 +6,18 @@ const { checkPage, pyStr, search, signal, asBytes, statusOf, headersOf, looksBin
6
6
  const { decode } = require("./decode");
7
7
  const { rx } = require("./pyre");
8
8
  const { cpLen, cpSlice, strip } = require("./text");
9
- const { loads, dumps, floatRepr } = require("./pyjson");
9
+ const { loads: pyLoads, dumps, floatRepr, JSONDecodeError } = require("./pyjson");
10
10
  const { pyLower } = require("./memory");
11
- const C = require("./classes.json");
11
+
12
+ /** JSON loads, with JSON nested too deep reported as unparseable JSON (as Python's check does), never thrown as a RangeError. */
13
+ function loads(text) {
14
+ try {
15
+ return pyLoads(text);
16
+ } catch (e) {
17
+ if (e instanceof RangeError) throw new JSONDecodeError("nested too deep", text, 0);
18
+ throw e;
19
+ }
20
+ }
12
21
 
13
22
  const ENVELOPE = ["response", "result", "meta", "status", "header", "body"];
14
23
  const TEXT_KEYS = ["message", "msg", "error_description", "error_message", "errorMessage", "detail", "title", "reason",
@@ -40,7 +49,7 @@ const AUTH = rx(String.raw`unauthori[sz]ed|unauthenticated|not authenticated|\ba
40
49
  + String.raw`\bsign ?in\b|\btoken\b|not authed|invalid auth|api[ _-]?key|credential|session (?:expired|invalid)`, "i", "");
41
50
  const DENIED = rx(String.raw`forbidden|access denied|permission|not allowed|\bblocked\b|\bbanned\b|\bdenied\b`, "i", "");
42
51
  const NOT_FOUND = rx(String.raw`not[ _-]?found|no such|does not exist|doesn't exist|unknown (?:endpoint|resource|route)`, "i", "");
43
- const RETRY_TEXT = rx(String.raw`\d+(?:\.\d+)?`, "", "");
52
+ const RETRY_TEXT = /^[0-9]+(?:\.[0-9]+)?$/; // Python's re.fullmatch(r"\d+(?:\.\d+)?", ..., re.ASCII)
44
53
  const BAD_STATUS = new Set(["error", "fail", "failed", "failure"]);
45
54
 
46
55
  // Python values here: null, booleans, BigInt (int), Number (float), strings, arrays (list) and Map (dict).
@@ -52,13 +61,6 @@ const blank = (v) => v === null || v === "" || (Array.isArray(v) && !v.length) |
52
61
  /** Python `v not in (None, "", [], {}, False, 0)`. */
53
62
  const filled = (v) => !(blank(v) || v === false || v === 0n || v === 0);
54
63
 
55
- /** A Python ValueError (the type is named so callers can tell it from a bug). */
56
- function valueError(message) {
57
- const e = new Error(message);
58
- e.name = "ValueError";
59
- return e;
60
- }
61
-
62
64
  /** A JS value given by the caller in Python's shapes: integral numbers become int, objects dicts. */
63
65
  function toPy(v) {
64
66
  if (typeof v === "number") return Number.isInteger(v) ? BigInt(v) : v;
@@ -73,32 +75,14 @@ function show(v) {
73
75
  return typeof v === "number" ? floatRepr(v) : pyStr(v);
74
76
  }
75
77
 
76
- /** Python int(s) of a stripped string of digits (any script); throws like Python for digits int() refuses. */
77
- function digitsInt(s) {
78
- let out = 0n;
79
- for (const c of strip(s)) {
80
- const d = C.digits[c];
81
- if (d === undefined || d < 0) throw valueError(`invalid literal for int() with base 10: '${s}'`);
82
- out = out * 10n + BigInt(d);
83
- }
84
- return out;
85
- }
86
-
87
- /** True when every character is a digit (Python str.isdigit()) and there is at least one. */
88
- function isdigit(s) {
89
- if (!s) return false;
90
- for (const c of s) if (C.digits[c] === undefined) return false;
91
- return true;
92
- }
93
-
94
- /** A whole number from a number or a string of three digits; null otherwise, booleans too. */
78
+ /** A whole number from a number or a string of three ASCII digits 0-9; null otherwise, booleans too. */
95
79
  function toInt(v) {
96
80
  if (typeof v === "boolean") return null;
97
81
  if (typeof v === "bigint") return v;
98
82
  if (typeof v === "number" && Number.isInteger(v)) return BigInt(v);
99
83
  if (typeof v === "string") {
100
84
  const s = strip(v);
101
- if (isdigit(s) && cpLen(s) === 3) return digitsInt(v);
85
+ if (/^[0-9]{3}$/.test(s)) return BigInt(s);
102
86
  }
103
87
  return null;
104
88
  }
@@ -138,29 +122,19 @@ function pair(d, otherwise) {
138
122
  return otherwise;
139
123
  }
140
124
 
141
- /** Python float() of a JSON number; a too large int throws like Python. */
142
- function toFloat(v) {
143
- const f = Number(v);
144
- if (typeof v === "bigint" && !Number.isFinite(f)) {
145
- const e = new Error("int too large to convert to float");
146
- e.name = "OverflowError";
147
- throw e;
148
- }
149
- return f;
150
- }
151
-
152
- /** Seconds to wait from a retry-after field of the body, if one says so. */
125
+ /**
126
+ * Seconds to wait from a retry-after field of the body, if one says so (ASCII digits only in a string); a value that is
127
+ * not finite as a float (1e999, an int past 1e308) counts as absent, like Python.
128
+ */
153
129
  function retryField(...objs) {
154
130
  for (const o of objs) {
155
131
  if (!isDict(o)) continue;
156
132
  for (const key of RETRY_KEYS) {
157
133
  const v = get(o, key);
158
- if (isNum(v) && v >= 0) return toFloat(v);
159
- if (typeof v === "string") {
160
- const s = strip(v);
161
- const m = search(RETRY_TEXT, s);
162
- if (m && m.index === 0 && m[0].length === s.length) return Number(Array.from(s, (c) => (c === "." ? c : C.digits[c])).join(""));
163
- }
134
+ let n = null;
135
+ if (isNum(v) && v >= 0) n = Number(v);
136
+ else if (typeof v === "string" && RETRY_TEXT.test(strip(v))) n = Number(strip(v));
137
+ if (n !== null && Number.isFinite(n)) return n;
164
138
  }
165
139
  }
166
140
  return null;
@@ -372,7 +346,6 @@ function checkApi(body, opts = {}) {
372
346
  try {
373
347
  data = loads(cleaned);
374
348
  } catch (e) {
375
- if (e instanceof RangeError) throw e;
376
349
  const m = search(JSONP, cleaned);
377
350
  let parsed = false;
378
351
  if (m) {
@@ -380,7 +353,7 @@ function checkApi(body, opts = {}) {
380
353
  data = loads(m[1]);
381
354
  parsed = true;
382
355
  } catch (e2) {
383
- if (e2 instanceof RangeError) throw e2;
356
+ // unparseable too: falls through to the verdict below
384
357
  }
385
358
  }
386
359
  if (!parsed) {
package/lib/memory.js CHANGED
@@ -5,8 +5,8 @@ const fs = require("fs");
5
5
  const { checkPage, Page, parts, pyStr, search, signal, asBytes, HOME_PATH } = require("./page");
6
6
  const { decode, crc32 } = require("./decode");
7
7
  const { rx, WORD } = require("./pyre");
8
- const { cpSlice, split } = require("./text");
9
- const { loads, dumps } = require("./pyjson");
8
+ const { cpSlice, split, strip } = require("./text");
9
+ const { loads, dumps, floatRepr } = require("./pyjson");
10
10
  const C = require("./classes.json");
11
11
 
12
12
  const NEAR = 2; // simhash bits that may differ between two fetches of one page
@@ -176,11 +176,12 @@ function simhash(text) {
176
176
  return [value, set.size];
177
177
  }
178
178
 
179
- /** Set bits of a 64-bit BigInt. */
179
+ /** Set bits of a BigInt, Python bin(x).count("1") (any size; a negative number counts its absolute value). */
180
180
  function popcount(x) {
181
+ if (x < 0n) x = -x;
181
182
  let n = 0;
182
- for (let w of [Number(x & 0xffffffffn), Number(x >> 32n)]) {
183
- for (; w; w = (w & (w - 1)) >>> 0) n++;
183
+ for (; x; x >>= 32n) {
184
+ for (let w = Number(x & 0xffffffffn); w; w = (w & (w - 1)) >>> 0) n++;
184
185
  }
185
186
  return n;
186
187
  }
@@ -192,8 +193,10 @@ function titleHash(title) {
192
193
 
193
194
  /** Simhash bits apart when two records look like the same page (same title, near hash, similar length), else -1. */
194
195
  function same(a, b) {
195
- const longer = Math.max(a.n, b.n);
196
- if (a.t !== b.t || longer === 0 || Math.abs(a.n - b.n) > LENGTH * longer) return -1;
196
+ const an = Number(a.n); // a loaded record may carry a BigInt past 2**53
197
+ const bn = Number(b.n);
198
+ const longer = Math.max(an, bn);
199
+ if (a.t !== b.t || longer === 0 || Math.abs(an - bn) > LENGTH * longer) return -1;
197
200
  const apart = popcount(a.h ^ b.h);
198
201
  return apart <= NEAR ? apart : -1;
199
202
  }
@@ -208,6 +211,150 @@ function byCodePoint(a, b) {
208
211
  return x.length - y.length;
209
212
  }
210
213
 
214
+ // Python's int(), bool() and str() on loaded JSON values (null, booleans, BigInt int, Number float, strings, arrays,
215
+ // Map or plain-object dicts), so fromDict accepts and refuses exactly what Python's from_dict does.
216
+
217
+ /** An Error named like the Python exception it stands for. */
218
+ function pyError(type, message) {
219
+ const e = new Error(message);
220
+ e.name = type;
221
+ return e;
222
+ }
223
+
224
+ /** A Map or a plain object: what Python sees as a dict. */
225
+ function isDict(v) {
226
+ if (v instanceof Map) return true;
227
+ if (!v || typeof v !== "object" || Array.isArray(v)) return false;
228
+ const proto = Object.getPrototypeOf(v);
229
+ return proto === Object.prototype || proto === null;
230
+ }
231
+
232
+ /** dict.get(key) for a Map or a plain object, undefined when absent. */
233
+ function dictGet(d, key) {
234
+ if (d instanceof Map) return d.get(key);
235
+ return Object.prototype.hasOwnProperty.call(d, key) ? d[key] : undefined;
236
+ }
237
+
238
+ /** Python type(v).__name__ of a loaded JSON value. */
239
+ function typeName(v) {
240
+ if (v === null || v === undefined) return "NoneType";
241
+ if (typeof v === "boolean") return "bool";
242
+ if (typeof v === "bigint") return "int";
243
+ if (typeof v === "number") return "float";
244
+ if (typeof v === "string") return "str";
245
+ return Array.isArray(v) ? "list" : "dict";
246
+ }
247
+
248
+ /** Python repr() of a str: its quote choice and escapes (non-printable characters as \x, \u or \U). */
249
+ function reprStr(s) {
250
+ const q = s.includes("'") && !s.includes('"') ? '"' : "'";
251
+ const ESCAPES = { "\\": "\\\\", "\t": "\\t", "\n": "\\n", "\r": "\\r" };
252
+ let out = q;
253
+ for (const c of s) {
254
+ const cp = c.codePointAt(0);
255
+ if (c === q) out += "\\" + c;
256
+ else if (ESCAPES[c]) out += ESCAPES[c];
257
+ else if (cp < 0x20 || cp === 0x7f) out += "\\x" + cp.toString(16).padStart(2, "0");
258
+ else if (cp < 0x7f || !/^[\p{C}\p{Z}]$/u.test(c)) out += c;
259
+ else if (cp <= 0xff) out += "\\x" + cp.toString(16).padStart(2, "0");
260
+ else if (cp <= 0xffff) out += "\\u" + cp.toString(16).padStart(4, "0");
261
+ else out += "\\U" + cp.toString(16).padStart(8, "0");
262
+ }
263
+ return out + q;
264
+ }
265
+
266
+ /** Python repr() of a loaded JSON value. */
267
+ function pyRepr(v) {
268
+ if (typeof v === "string") return reprStr(v);
269
+ if (typeof v === "number") {
270
+ if (Number.isNaN(v)) return "nan";
271
+ if (!Number.isFinite(v)) return v > 0 ? "inf" : "-inf";
272
+ return floatRepr(v);
273
+ }
274
+ if (typeof v === "bigint") return v.toString();
275
+ if (v === null || v === undefined || typeof v === "boolean") return pyStr(v);
276
+ if (Array.isArray(v)) return "[" + v.map(pyRepr).join(", ") + "]";
277
+ const pairs = v instanceof Map ? Array.from(v.entries()) : Object.entries(v);
278
+ return "{" + pairs.map(([k, x]) => `${pyRepr(k)}: ${pyRepr(x)}`).join(", ") + "}";
279
+ }
280
+
281
+ /** Python str() of a loaded JSON value. */
282
+ function pyText(v) {
283
+ return typeof v === "string" ? v : pyRepr(v);
284
+ }
285
+
286
+ /** Python bool() of a loaded JSON value (empty list, dict and string are false; NaN is true). */
287
+ function pyBool(v) {
288
+ if (v === null || v === undefined) return false;
289
+ if (typeof v === "boolean") return v;
290
+ if (typeof v === "bigint") return v !== 0n;
291
+ if (typeof v === "number") return v !== 0;
292
+ if (typeof v === "string" || Array.isArray(v)) return v.length > 0;
293
+ return v instanceof Map ? v.size > 0 : Object.keys(v).length > 0;
294
+ }
295
+
296
+ /** Python int() of a loaded JSON value as a BigInt: floats truncated, strings of any-script digits with _ and a sign. */
297
+ function pyInt(v) {
298
+ if (typeof v === "bigint") return v;
299
+ if (typeof v === "boolean") return v ? 1n : 0n;
300
+ if (typeof v === "number") {
301
+ if (Number.isNaN(v)) throw pyError("ValueError", "cannot convert float NaN to integer");
302
+ if (!Number.isFinite(v)) throw pyError("OverflowError", "cannot convert float infinity to integer");
303
+ return BigInt(Math.trunc(v));
304
+ }
305
+ if (typeof v !== "string") {
306
+ throw pyError("TypeError", `int() argument must be a string, a bytes-like object or a real number, not '${typeName(v)}'`);
307
+ }
308
+ const s = strip(v);
309
+ const sign = s[0] === "+" || s[0] === "-" ? s[0] : "";
310
+ let digits = "";
311
+ let afterDigit = false;
312
+ let ok = s.length > sign.length;
313
+ for (const c of s.slice(sign.length)) {
314
+ const d = C.digits[c];
315
+ if (d !== undefined && d >= 0) {
316
+ digits += d;
317
+ afterDigit = true;
318
+ } else if (c === "_" && afterDigit) afterDigit = false;
319
+ else {
320
+ ok = false;
321
+ break;
322
+ }
323
+ }
324
+ if (!ok || !afterDigit) throw pyError("ValueError", `invalid literal for int() with base 10: ${reprStr(v)}`);
325
+ if (digits.length > 4300) {
326
+ throw pyError("ValueError", `Exceeds the limit (4300 digits) for integer string conversion: value has ${digits.length} digits; `
327
+ + "use sys.set_int_max_str_digits() to increase the limit");
328
+ }
329
+ return BigInt(sign + digits);
330
+ }
331
+
332
+ /** A BigInt as a Number when it is exact as one (records keep plain numbers), else the BigInt. */
333
+ function small(n) {
334
+ return n >= -Number.MAX_SAFE_INTEGER && n <= Number.MAX_SAFE_INTEGER ? Number(n) : n;
335
+ }
336
+
337
+ /** What Python's `for r in records` walks: list items, dict keys, string characters; TypeError for anything else. */
338
+ function items(records) {
339
+ if (Array.isArray(records)) return records;
340
+ if (typeof records === "string") return Array.from(records);
341
+ if (isDict(records)) return records instanceof Map ? Array.from(records.keys()) : Object.keys(records);
342
+ throw pyError("TypeError", `'${typeName(records)}' object is not iterable`);
343
+ }
344
+
345
+ /** r[key] as Python reads it from a record: KeyError when absent, TypeError when r is not a dict. */
346
+ function field(r, key) {
347
+ if (!isDict(r)) {
348
+ const t = typeName(r);
349
+ if (t === "str") throw pyError("TypeError", "string indices must be integers, not 'str'");
350
+ if (t === "list") throw pyError("TypeError", "list indices must be integers or slices, not str");
351
+ throw pyError("TypeError", `'${t}' object is not subscriptable`);
352
+ }
353
+ const v = dictGet(r, key);
354
+ if (v === undefined) throw pyError("KeyError", `'${key}'`);
355
+ return v;
356
+ }
357
+
211
358
  /** check_page, plus the page reader it used (or null). */
212
359
  function core(html, opts) {
213
360
  const handover = { reader: null };
@@ -217,8 +364,10 @@ function core(html, opts) {
217
364
 
218
365
  /** Pages already judged "ok", per site; checkPage here also asks whether a deep address shows one of them. */
219
366
  class SiteMemory {
220
- /** perHost: how many page records to keep for each site (the oldest go first). */
367
+ /** perHost: how many page records to keep for each site (the oldest go first); a whole number of at least 1. */
221
368
  constructor(perHost = PER_HOST) {
369
+ const whole = (typeof perHost === "number" && Number.isInteger(perHost)) || typeof perHost === "bigint";
370
+ if (!whole || perHost < 1) throw new RangeError("per_host must be at least 1");
222
371
  this.perHost = perHost;
223
372
  this.hosts = new Map();
224
373
  }
@@ -281,7 +430,7 @@ class SiteMemory {
281
430
  if (!seen) this.hosts.set(host, (seen = new Map()));
282
431
  seen.delete(record.k);
283
432
  seen.set(record.k, record);
284
- while (seen.size > this.perHost) seen.delete(seen.keys().next().value);
433
+ while (seen.size > this.perHost && seen.size > 0) seen.delete(seen.keys().next().value);
285
434
  }
286
435
 
287
436
  /** The core result turned into the core's "not found" verdict when the memory found a match. */
@@ -332,34 +481,54 @@ class SiteMemory {
332
481
  fs.writeFileSync(path, this.dumps(), "utf8");
333
482
  }
334
483
 
335
- /** A memory rebuilt from toDict's data or Python's to_dict() (unknown fields ignored). */
484
+ /**
485
+ * A memory rebuilt from toDict's data or Python's to_dict() (unknown fields ignored). Accepts and refuses what Python's
486
+ * from_dict does (its int(), bool(), str() and .items()); anything else throws Error("not a falseok memory file (...)").
487
+ */
336
488
  static fromDict(data) {
337
- if (!data || typeof data !== "object" || Array.isArray(data)) throw new TypeError("expected an object");
338
- const get = (o, k) => {
339
- const v = o instanceof Map ? o.get(k) : o[k];
340
- if (v === undefined && k !== "per_host" && k !== "hosts") throw new Error(`'${k}'`); // Python's KeyError
341
- return v;
342
- };
343
- const perHost = get(data, "per_host");
344
- const mem = new SiteMemory(perHost === undefined ? PER_HOST : Number(perHost));
345
- const hosts = get(data, "hosts") || {};
346
- for (const [host, records] of hosts instanceof Map ? hosts.entries() : Object.entries(hosts)) {
347
- for (const r of records) {
348
- mem.learn(host, { k: String(get(r, "k")), r: !!get(r, "r"), n: Number(get(r, "n")), h: BigInt(get(r, "h")),
349
- t: Number(get(r, "t")) });
489
+ try {
490
+ if (!isDict(data)) throw pyError("AttributeError", `'${typeName(data)}' object has no attribute 'get'`);
491
+ const perHost = dictGet(data, "per_host");
492
+ const mem = new SiteMemory(small(pyInt(perHost === undefined ? BigInt(PER_HOST) : perHost)));
493
+ const got = dictGet(data, "hosts");
494
+ const hosts = got === undefined ? new Map() : got;
495
+ if (!isDict(hosts)) throw pyError("AttributeError", `'${typeName(hosts)}' object has no attribute 'items'`);
496
+ for (const [host, records] of hosts instanceof Map ? hosts.entries() : Object.entries(hosts)) {
497
+ for (const r of items(records)) {
498
+ mem.learn(host, { k: pyText(field(r, "k")), r: pyBool(field(r, "r")), n: small(pyInt(field(r, "n"))),
499
+ h: pyInt(field(r, "h")), t: small(pyInt(field(r, "t"))) });
500
+ }
350
501
  }
502
+ return mem;
503
+ } catch (e) {
504
+ let type = e.name;
505
+ if (e instanceof RangeError) type = e.message.startsWith("per_host") ? "ValueError" : "RecursionError";
506
+ throw new Error(`not a falseok memory file (${type}: ${cpSlice(String(e.message), 60)})`);
351
507
  }
352
- return mem;
353
508
  }
354
509
 
355
- /** A memory from the JSON text of dumps() or of Python's save(). */
510
+ /** A memory from the JSON text of dumps() or of Python's save(); unreadable JSON: "not a falseok memory file". */
356
511
  static loads(text) {
357
- return SiteMemory.fromDict(loads(text));
512
+ let data;
513
+ try {
514
+ data = loads(text);
515
+ } catch (e) {
516
+ const type = e.name === "JSONDecodeError" ? e.name : e instanceof RangeError ? "RecursionError" : "ValueError";
517
+ throw new Error(`not a falseok memory file (${type})`);
518
+ }
519
+ return SiteMemory.fromDict(data);
358
520
  }
359
521
 
360
- /** Read a memory written by save() (or by the Python package). */
522
+ /** Read a memory written by save() (or by the Python package); bytes that are not UTF-8 are refused, as in Python. */
361
523
  static load(path) {
362
- return SiteMemory.loads(fs.readFileSync(path, "utf8"));
524
+ const raw = fs.readFileSync(path);
525
+ let text;
526
+ try {
527
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(raw);
528
+ } catch (e) {
529
+ throw new Error("not a falseok memory file (UnicodeDecodeError)");
530
+ }
531
+ return SiteMemory.loads(text);
363
532
  }
364
533
  }
365
534
 
package/lib/page.js CHANGED
@@ -2,13 +2,15 @@
2
2
  // Page check: is this "200 OK" page real content, or a block page in disguise? (port of the Python falseok.page)
3
3
  const zlib = require("zlib");
4
4
  const { rx, escape } = require("./pyre");
5
- const { cpLen, cpSlice, split, strip, stripChars, isspace, isascii, unescape, splitlines } = require("./text");
5
+ const { cpLen, cpSlice, split, strip, stripChars, rstripChars, isspace, isascii, unescape, splitlines } = require("./text");
6
6
  const { decode } = require("./decode");
7
7
  const { urlsplit, urljoin, unquote, parseQsl, hostname } = require("./url");
8
8
 
9
9
  const PRIORITY = ["challenge", "captcha", "rate_limited", "login_wall", "consent_wall", "soft_block", "soft_404", "empty_shell"];
10
10
  const VERDICTS = ["ok", "not_html", ...PRIORITY, "http_error"];
11
11
  const DEFAULT_MAX_TEXT = 3000;
12
+ // Title rules read only the first TITLE_SCAN characters (code points) of the title; the result's title stays whole.
13
+ const TITLE_SCAN = 10000;
12
14
  const SHELL_TEXT = 300;
13
15
  const SHELL_SCRIPTS = 20;
14
16
  const SHELL_FRAME_TEXT = 120;
@@ -50,7 +52,7 @@ const WAY_ON = rx(String.raw`<(?:img|a[\t\n\r\f ][^>]*href)\b`, "i", "");
50
52
 
51
53
  const RAW = ["script", "style", "xmp", "iframe", "noembed", "noframes", "textarea", "title"];
52
54
  const OPEN = rx(String.raw`<(?=[/!sStTiInNxX])(?:(?=[/nNtT])(?P<end>/?)(?=[nNtT])(?P<skip>${anycase("noscript|template")})(?=[\s/>])[^>]*(?:>|\Z)`
53
- + String.raw`|(?=[sSxXiInNtT])(?P<raw>${anycase(String.raw`s(?:cript|tyle)|xmp|iframe|no(?:embed|frames)|t(?:extarea|itle)`)})(?=[\s/>])${attrs("a")}(?:>|\Z)|!--(?:[^-]+|-(?!-!?>))*(?:--!?>|\Z))`);
55
+ + String.raw`|(?=[sSxXiInNtT])(?P<raw>${anycase(String.raw`s(?:cript|tyle)|xmp|iframe|no(?:embed|frames)|t(?:extarea|itle)`)})(?=[\s/>])${attrs("a")}(?:>|\Z)|!--)`); // a comment's end is found by commentEnd: Python's !--(?:[^-]+|-(?!-!?>))*(?:--!?>|\Z) overflows V8's regex stack on MBs
54
56
  const CLOSE = {};
55
57
  for (const t of RAW) CLOSE[t] = rx(String.raw`</${anycase(t)}(?=[\s/>])[^>]*(?:>|\Z)`);
56
58
  const SVG = rx(String.raw`<${anycase("svg")}(?=[\s/>])(?:[^>]*(?<=/)>|(?=(?P<s>(?:[^<]+|<(?!/${anycase("svg")}|(?:${anycase("body|main|article|section|p|div|h1|h2|h3|ul|table|footer")})[\s/>]))*))(?P=s)(?:</${anycase("svg")}[^>]*(?:>|\Z))?)`);
@@ -191,6 +193,15 @@ function attrMap(s) {
191
193
  return out;
192
194
  }
193
195
 
196
+ /** Where a comment whose "<!--" ends at i stops: after the first "-->" or "--!>", else at the end (same as the regex). */
197
+ function commentEnd(s, i) {
198
+ for (let j = s.indexOf("--", i); j >= 0; j = s.indexOf("--", j + 1)) {
199
+ if (s[j + 2] === ">") return j + 3;
200
+ if (s[j + 2] === "!" && s[j + 3] === ">") return j + 4;
201
+ }
202
+ return s.length;
203
+ }
204
+
194
205
  /** The page roughly as a browser shows it: title, visible text, a few counts (read whole). */
195
206
  class Page {
196
207
  /** Run the first pass over the whole page. */
@@ -212,7 +223,7 @@ class Page {
212
223
  break;
213
224
  }
214
225
  const start = m.index;
215
- const end = start + m[0].length;
226
+ const end = m[0] === "<!--" ? commentEnd(raw, start + 4) : start + m[0].length;
216
227
  out.push(raw.slice(pos, start));
217
228
  pos = end;
218
229
  const g = m.groups;
@@ -810,7 +821,11 @@ function roundHalfEven(x) {
810
821
  /** Seconds from the Retry-After header; null if absent or unreadable. now: epoch ms. */
811
822
  function retryAfter(sent, now) {
812
823
  const value = strip(sent.get("retry-after") || "");
813
- if (/^[0-9]+(?:\.[0-9]+)?$/.test(value)) return parseFloat(value);
824
+ if (/[^\x00-\x7f]/.test(value)) return null; // any non-ASCII character: not readable
825
+ if (/^[0-9]+(?:\.[0-9]+)?$/.test(value)) {
826
+ const n = parseFloat(value);
827
+ return Number.isFinite(n) ? n : null; // 400 digits overflow to Infinity: not readable
828
+ }
814
829
  const when = parseHttpDate(value);
815
830
  if (when === null) return null;
816
831
  return Math.max(0, roundHalfEven((when - now) / 1000));
@@ -890,8 +905,11 @@ function addresses(url, finalUrl) {
890
905
  const was = url ? parts(pyStr(url)) : null;
891
906
  let at = was;
892
907
  if (finalUrl && finalUrl !== url) {
893
- const joined = urljoin(url ? pyStr(url) : "", pyStr(finalUrl));
894
- at = parts(joined);
908
+ try {
909
+ at = parts(urljoin(url ? pyStr(url) : "", pyStr(finalUrl)));
910
+ } catch (e) {
911
+ at = null; // an unreadable final address (urljoin raises, e.g. "http://[zz]/") counts as absent
912
+ }
895
913
  }
896
914
  return [was, at, was || at];
897
915
  }
@@ -951,8 +969,8 @@ function okDoubt(result, reader, raw, rawLen, url, finalUrl, content) {
951
969
  if ((search(LOGIN_PATH, (at || asked)[1]) || search(LOGIN_TITLE, result.title)) && reader.passwordInputs) return true;
952
970
  const words = !asked[3] ? pathWords(asked[4]) : [];
953
971
  if (words.length) {
954
- const same = asked[0] + "\u0000" + asked[1].replace(/\/+$/, "");
955
- const elsewhere = [at, canonical].filter((p) => p !== null && p[0] + "\u0000" + p[1].replace(/\/+$/, "") !== same)
972
+ const same = asked[0] + "\u0000" + rstripChars(asked[1], "/");
973
+ const elsewhere = [at, canonical].filter((p) => p !== null && p[0] + "\u0000" + rstripChars(p[1], "/") !== same)
956
974
  .map((p) => fold(unquote(p[0] + p[4])));
957
975
  if (elsewhere.length && !elsewhere.some((e) => words.some((w) => e.includes(w)))) return true;
958
976
  if (wordsMissing(words, result, reader)) return true;
@@ -1066,12 +1084,32 @@ function startsWithBytes(b, prefix) {
1066
1084
  return prefix.every((x, i) => b[i] === x);
1067
1085
  }
1068
1086
 
1087
+ /** Refuse only what used to crash checkPage (wrong-typed options), with a message naming the option; whatever 0.5 took stays. */
1088
+ function checkOptions(opts) {
1089
+ const m = opts.minText;
1090
+ if (m !== undefined) {
1091
+ try {
1092
+ void (m <= 0); // 0.5 coerced numeric strings, null, arrays and objects like a comparison does; a Symbol threw
1093
+ } catch (e) {
1094
+ throw new TypeError("min_text must be a number");
1095
+ }
1096
+ }
1097
+ const iterable = (v) => v !== null && v !== undefined && typeof v[Symbol.iterator] === "function";
1098
+ const s = opts.signatures;
1099
+ if (s !== undefined && s !== null && !iterable(s)) throw new TypeError("signatures must be a list of rules");
1100
+ for (const [name, v] of [["disable_ids", opts.disableIds], ["allow_categories", opts.allowCategories]]) {
1101
+ if (v === undefined || v === null || typeof v === "string") continue;
1102
+ if (!iterable(v)) throw new TypeError(`${name} must be a string or a list of strings`);
1103
+ }
1104
+ }
1105
+
1069
1106
  /**
1070
1107
  * Return a verdict for one HTML page, as a plain object with the keys of Python's PageResult.to_dict().
1071
1108
  * html: a string, or the raw bytes (Buffer / Uint8Array). Options: status, headers, url, finalUrl, minText, signatures,
1072
1109
  * disableIds, allowCategories, now (epoch ms for Retry-After dates; default Date.now()).
1073
1110
  */
1074
1111
  function checkPage(html, opts = {}) {
1112
+ checkOptions(opts);
1075
1113
  const minText = opts.minText === undefined ? 150 : opts.minText;
1076
1114
  const url = opts.url === undefined ? null : opts.url;
1077
1115
  const finalUrl = opts.finalUrl === undefined ? null : opts.finalUrl;
@@ -1124,7 +1162,9 @@ function checkPage(html, opts = {}) {
1124
1162
  const reader = new Page(raw);
1125
1163
  const title = reader.title;
1126
1164
  const tlen = reader.textLength;
1127
- const both = `${title} ${reader.text}`;
1165
+ // cpSlice walks only as far as the cut, so a huge title is never fully scanned; shorter titles come back whole.
1166
+ const scanned = cpSlice(title, TITLE_SCAN);
1167
+ const both = `${scanned} ${reader.text}`;
1128
1168
  let signals = [];
1129
1169
  let heads = null;
1130
1170
  for (const s of signatures) {
@@ -1148,7 +1188,7 @@ function checkPage(html, opts = {}) {
1148
1188
  }
1149
1189
  continue;
1150
1190
  }
1151
- const hay = where === "title" ? title : where === "text" ? both : raw;
1191
+ const hay = where === "title" ? scanned : where === "text" ? both : raw;
1152
1192
  const m = search(s._rx, hay);
1153
1193
  if (m) signals.push(signal(s.id, s.category, `${where}: "${cpSlice(m[0], 80)}"`, s.vendor === undefined ? null : s.vendor));
1154
1194
  }
package/lib/text.js CHANGED
@@ -5,7 +5,6 @@ const T = require("./tables.json");
5
5
 
6
6
  const WS_RX = new RegExp(`[${WS}]+`, "u");
7
7
  const WS_SPLIT = new RegExp(`[${WS}]+`, "gu");
8
- const STRIP_RX = new RegExp(`^[${WS}]+|[${WS}]+$`, "gu");
9
8
  const SPACE_ONLY = new RegExp(`^[${WS}]+$`, "u");
10
9
 
11
10
  const SURROGATE = /[\ud800-\udbff]/;
@@ -52,9 +51,26 @@ function split(s) {
52
51
  return parts;
53
52
  }
54
53
 
55
- /** str.strip() with no argument. */
54
+ /** True for a UTF-16 unit in WS (Python's whitespace; all of it is in the BMP). */
55
+ function isWs(c) {
56
+ return (c >= 0x09 && c <= 0x0d) || (c >= 0x1c && c <= 0x20) || c === 0x85 || c === 0xa0 || c === 0x1680
57
+ || (c >= 0x2000 && c <= 0x200a) || c === 0x2028 || c === 0x2029 || c === 0x202f || c === 0x205f || c === 0x3000;
58
+ }
59
+
60
+ /** str.strip() with no argument: index loops, linear even on long whitespace runs (a `\s+$` regex is quadratic). */
56
61
  function strip(s) {
57
- return s.replace(STRIP_RX, "");
62
+ let a = 0;
63
+ let b = s.length;
64
+ while (a < b && isWs(s.charCodeAt(a))) a++;
65
+ while (b > a && isWs(s.charCodeAt(b - 1))) b--;
66
+ return a === 0 && b === s.length ? s : s.slice(a, b);
67
+ }
68
+
69
+ /** str.rstrip(chars), linear. */
70
+ function rstripChars(s, chars) {
71
+ let b = s.length;
72
+ while (b > 0 && chars.includes(s[b - 1])) b--;
73
+ return s.slice(0, b);
58
74
  }
59
75
 
60
76
  /** str.strip(chars). */
@@ -109,4 +125,4 @@ function splitlines(s) {
109
125
  return lines;
110
126
  }
111
127
 
112
- module.exports = { cpLen, cpSlice, cpAdvance, split, strip, stripChars, isspace, isascii, unescape, splitlines, WS_RX };
128
+ module.exports = { cpLen, cpSlice, cpAdvance, split, strip, stripChars, rstripChars, isspace, isascii, unescape, splitlines, WS_RX };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "falseok",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Catch the 200 OK that isn't: tell when a scraped page is really a block, a login wall or an empty shell.",
5
5
  "keywords": ["scraping", "web-scraping", "captcha", "block-detection", "soft-404", "data-quality", "monitoring", "crawler"],
6
6
  "license": "MIT",