falseok 0.0.0-stage → 0.5.0
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 +21 -0
- package/README.md +127 -2
- package/bin/falseok.js +500 -0
- package/index.d.ts +171 -0
- package/index.js +18 -0
- package/index.mjs +5 -0
- package/lib/api.js +398 -0
- package/lib/cjk.json +1 -0
- package/lib/classes.json +1 -0
- package/lib/decode.js +304 -0
- package/lib/memory.js +390 -0
- package/lib/page.js +1256 -0
- package/lib/pyjson.js +248 -0
- package/lib/pyre.js +185 -0
- package/lib/tables.json +1 -0
- package/lib/text.js +112 -0
- package/lib/url.js +200 -0
- package/package.json +35 -4
- package/signatures.json +682 -0
package/lib/decode.js
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Bytes to text the way the Python version reads them: gunzip/zlib, BOM, strict UTF-8, declared charset, cp1252.
|
|
3
|
+
const zlib = require("zlib");
|
|
4
|
+
const T = require("./tables.json");
|
|
5
|
+
const { strip } = require("./text");
|
|
6
|
+
const { rx } = require("./pyre");
|
|
7
|
+
|
|
8
|
+
let CRC_TABLE = null;
|
|
9
|
+
|
|
10
|
+
/** CRC-32 of a buffer (zlib.crc32 only exists from Node 22.2, so the table version is used everywhere). */
|
|
11
|
+
function crc32(buf) {
|
|
12
|
+
if (!CRC_TABLE) {
|
|
13
|
+
CRC_TABLE = new Int32Array(256);
|
|
14
|
+
for (let n = 0; n < 256; n++) {
|
|
15
|
+
let c = n;
|
|
16
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
17
|
+
CRC_TABLE[n] = c;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
let crc = -1;
|
|
21
|
+
for (let i = 0; i < buf.length; i++) crc = CRC_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
|
|
22
|
+
return (crc ^ -1) >>> 0;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const ALIAS = {
|
|
26
|
+
"iso-8859-1": "cp1252", "iso8859-1": "cp1252", "latin1": "cp1252", "latin-1": "cp1252", "ascii": "cp1252",
|
|
27
|
+
"us-ascii": "cp1252", "iso-8859-9": "cp1254", "iso-8859-11": "cp874", "tis-620": "cp874", "windows-874": "cp874",
|
|
28
|
+
"gb2312": "gbk", "gb_2312-80": "gbk", "x-gbk": "gbk", "shift_jis": "cp932", "shift-jis": "cp932", "sjis": "cp932",
|
|
29
|
+
"x-sjis": "cp932", "windows-31j": "cp932", "euc-kr": "cp949", "ks_c_5601-1987": "cp949", "x-euc-jp": "euc_jp",
|
|
30
|
+
};
|
|
31
|
+
const MODULES = new Set(T.modules);
|
|
32
|
+
|
|
33
|
+
/** Python's gzip.decompress: every member, CRC and size checked, zero padding allowed; null on any error. */
|
|
34
|
+
function gunzip(data) {
|
|
35
|
+
const parts = [];
|
|
36
|
+
let at = 0;
|
|
37
|
+
for (;;) {
|
|
38
|
+
if (at >= data.length) return Buffer.concat(parts);
|
|
39
|
+
if (data.length - at < 2) return null;
|
|
40
|
+
if (data[at] !== 0x1f || data[at + 1] !== 0x8b) return null;
|
|
41
|
+
if (data.length - at < 10) return null;
|
|
42
|
+
if (data[at + 2] !== 8) return null;
|
|
43
|
+
const flag = data[at + 3];
|
|
44
|
+
let p = at + 10;
|
|
45
|
+
if (flag & 4) {
|
|
46
|
+
if (p + 2 > data.length) return null;
|
|
47
|
+
p += 2 + data[p] + data[p + 1] * 256;
|
|
48
|
+
}
|
|
49
|
+
for (const bit of [8, 16]) {
|
|
50
|
+
if (flag & bit) {
|
|
51
|
+
while (p < data.length && data[p] !== 0) p++;
|
|
52
|
+
if (p >= data.length) return null;
|
|
53
|
+
p++;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (flag & 2) p += 2;
|
|
57
|
+
if (p > data.length) return null;
|
|
58
|
+
let res;
|
|
59
|
+
try {
|
|
60
|
+
res = zlib.inflateRawSync(data.subarray(p), { info: true });
|
|
61
|
+
} catch (e) {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
const used = res.engine.bytesWritten;
|
|
65
|
+
p += used;
|
|
66
|
+
if (p + 8 > data.length) return null;
|
|
67
|
+
const crc = data.readUInt32LE(p);
|
|
68
|
+
const size = data.readUInt32LE(p + 4);
|
|
69
|
+
if (crc !== crc32(res.buffer) || size !== (res.buffer.length >>> 0)) return null;
|
|
70
|
+
parts.push(res.buffer);
|
|
71
|
+
at = p + 8;
|
|
72
|
+
while (at < data.length && data[at] === 0) at++;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Python's codec name lookup: the codec module name, or null (LookupError). */
|
|
77
|
+
function lookup(name) {
|
|
78
|
+
let s = name.toLowerCase().replace(/ /g, "-");
|
|
79
|
+
let norm = "";
|
|
80
|
+
let punct = false;
|
|
81
|
+
for (const c of s) {
|
|
82
|
+
if (/[\p{L}\p{N}.]/u.test(c)) {
|
|
83
|
+
if (punct && norm) norm += "_";
|
|
84
|
+
if (c < "\x80") norm += c;
|
|
85
|
+
punct = false;
|
|
86
|
+
} else punct = true;
|
|
87
|
+
}
|
|
88
|
+
const aliased = T.aliases[norm] || T.aliases[norm.replace(/\./g, "_")];
|
|
89
|
+
for (const mod of aliased ? [aliased, norm] : [norm]) {
|
|
90
|
+
if (!mod || mod.includes(".")) continue;
|
|
91
|
+
if (MODULES.has(mod)) return mod;
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Double-byte codecs decoded from Python's own tables (cjk.json, loaded on first use): WHATWG decoders map some
|
|
97
|
+
// bytes differently and replace broken ones differently.
|
|
98
|
+
const CJK_CODECS = ["gbk", "gb2312", "cp932", "shift_jis", "euc_jp", "cp949", "euc_kr", "big5", "cp950", "johab"];
|
|
99
|
+
const NONE = "";
|
|
100
|
+
let CJK = null;
|
|
101
|
+
|
|
102
|
+
/** The double-byte tables, read once. */
|
|
103
|
+
function cjk() {
|
|
104
|
+
if (CJK === null) CJK = require("./cjk.json");
|
|
105
|
+
return CJK;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** A double-byte codec with Python's "replace": the longest valid sequence (3, 2, 1 bytes), else U+FFFD for one byte. */
|
|
109
|
+
function decodeCjk(data, t) {
|
|
110
|
+
const out = [];
|
|
111
|
+
const n = data.length;
|
|
112
|
+
let i = 0;
|
|
113
|
+
while (i < n) {
|
|
114
|
+
const b = data[i];
|
|
115
|
+
if (b < 0x80 && t.single[b] !== NONE) {
|
|
116
|
+
out.push(t.single[b]);
|
|
117
|
+
i++;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (b === 0x8f && i + 2 < n) {
|
|
121
|
+
const row = t.triples[data[i + 1]];
|
|
122
|
+
if (row !== undefined && row[data[i + 2]] !== NONE) {
|
|
123
|
+
out.push(row[data[i + 2]]);
|
|
124
|
+
i += 3;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (i + 1 < n) {
|
|
129
|
+
const row = t.pairs[b];
|
|
130
|
+
if (row !== undefined && row[data[i + 1]] !== NONE) {
|
|
131
|
+
out.push(row[data[i + 1]]);
|
|
132
|
+
i += 2;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
out.push(t.single[b] !== NONE ? t.single[b] : "�");
|
|
137
|
+
i++;
|
|
138
|
+
}
|
|
139
|
+
return out.join("");
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** UTF-32 with Python's "replace": a BOM picks the order ("utf_32" only), invalid units and a short tail become U+FFFD. */
|
|
143
|
+
function decodeUtf32(data, codec) {
|
|
144
|
+
let le = codec !== "utf_32_be";
|
|
145
|
+
let i = 0;
|
|
146
|
+
if (codec === "utf_32" && data.length >= 4) {
|
|
147
|
+
if (data[0] === 0xff && data[1] === 0xfe && data[2] === 0 && data[3] === 0) i = 4;
|
|
148
|
+
else if (data[0] === 0 && data[1] === 0 && data[2] === 0xfe && data[3] === 0xff) { le = false; i = 4; }
|
|
149
|
+
}
|
|
150
|
+
const out = [];
|
|
151
|
+
for (; i + 4 <= data.length; i += 4) {
|
|
152
|
+
const c = le ? data.readUInt32LE(i) : data.readUInt32BE(i);
|
|
153
|
+
out.push(c > 0x10ffff || (c >= 0xd800 && c <= 0xdfff) ? "�" : String.fromCodePoint(c));
|
|
154
|
+
}
|
|
155
|
+
if (i < data.length) out.push("�");
|
|
156
|
+
return out.join("");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
160
|
+
|
|
161
|
+
/** UTF-7 with Python's "replace", ported from CPython's decoder (errors, absorbed "-", lone surrogates kept). */
|
|
162
|
+
function decodeUtf7(data) {
|
|
163
|
+
const out = [];
|
|
164
|
+
const n = data.length;
|
|
165
|
+
let s = 0;
|
|
166
|
+
let inShift = false;
|
|
167
|
+
let bits = 0;
|
|
168
|
+
let buf = 0;
|
|
169
|
+
let surrogate = 0;
|
|
170
|
+
while (s < n) {
|
|
171
|
+
const ch = data[s];
|
|
172
|
+
if (inShift) {
|
|
173
|
+
const v = B64.indexOf(String.fromCharCode(ch));
|
|
174
|
+
if (ch < 128 && v >= 0) {
|
|
175
|
+
buf = buf * 64 + v;
|
|
176
|
+
bits += 6;
|
|
177
|
+
s++;
|
|
178
|
+
if (bits >= 16) {
|
|
179
|
+
const outCh = Math.floor(buf / 2 ** (bits - 16)) & 0xffff;
|
|
180
|
+
bits -= 16;
|
|
181
|
+
buf %= 2 ** bits;
|
|
182
|
+
if (surrogate) {
|
|
183
|
+
if (outCh >= 0xdc00 && outCh <= 0xdfff) {
|
|
184
|
+
out.push(String.fromCharCode(surrogate, outCh));
|
|
185
|
+
surrogate = 0;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
out.push(String.fromCharCode(surrogate));
|
|
189
|
+
surrogate = 0;
|
|
190
|
+
}
|
|
191
|
+
if (outCh >= 0xd800 && outCh <= 0xdbff) surrogate = outCh;
|
|
192
|
+
else out.push(String.fromCharCode(outCh));
|
|
193
|
+
}
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
inShift = false;
|
|
197
|
+
if (bits > 0 && (bits >= 6 || buf !== 0)) {
|
|
198
|
+
s++;
|
|
199
|
+
out.push("�");
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
if (surrogate && ch <= 127 && ch !== 0x2b) out.push(String.fromCharCode(surrogate));
|
|
203
|
+
surrogate = 0;
|
|
204
|
+
if (ch === 0x2d) s++;
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
if (ch === 0x2b) {
|
|
208
|
+
s++;
|
|
209
|
+
if (s < n && data[s] === 0x2d) {
|
|
210
|
+
s++;
|
|
211
|
+
out.push("+");
|
|
212
|
+
} else if (s < n && !(data[s] < 128 && B64.includes(String.fromCharCode(data[s])))) {
|
|
213
|
+
s++;
|
|
214
|
+
out.push("�");
|
|
215
|
+
} else {
|
|
216
|
+
inShift = true;
|
|
217
|
+
surrogate = 0;
|
|
218
|
+
bits = 0;
|
|
219
|
+
buf = 0;
|
|
220
|
+
}
|
|
221
|
+
} else if (ch <= 127) {
|
|
222
|
+
out.push(String.fromCharCode(ch));
|
|
223
|
+
s++;
|
|
224
|
+
} else {
|
|
225
|
+
s++;
|
|
226
|
+
out.push("�");
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (inShift && (surrogate || bits >= 6 || (bits > 0 && buf !== 0))) out.push("�");
|
|
230
|
+
return out.join("");
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** bytes.decode(codec, "replace"); throws for a codec Python would not decode with. */
|
|
234
|
+
function decodeWith(data, codec) {
|
|
235
|
+
const table = T.single[codec];
|
|
236
|
+
if (table !== undefined) {
|
|
237
|
+
let out = "";
|
|
238
|
+
for (let i = 0; i < data.length; i += 8192) {
|
|
239
|
+
const chunk = [];
|
|
240
|
+
for (let j = i; j < Math.min(i + 8192, data.length); j++) chunk.push(table[data[j]]);
|
|
241
|
+
out += chunk.join("");
|
|
242
|
+
}
|
|
243
|
+
return out;
|
|
244
|
+
}
|
|
245
|
+
if (CJK_CODECS.includes(codec)) return decodeCjk(data, cjk()[codec]);
|
|
246
|
+
if (codec === "utf_32" || codec === "utf_32_le" || codec === "utf_32_be") return decodeUtf32(data, codec);
|
|
247
|
+
if (codec === "utf_7") return decodeUtf7(data);
|
|
248
|
+
const label = T.multi[codec];
|
|
249
|
+
if (label === "utf-16") {
|
|
250
|
+
// Python: a BOM picks the order and is dropped, else little-endian
|
|
251
|
+
if (data[0] === 0xfe && data[1] === 0xff) return new TextDecoder("utf-16be", { ignoreBOM: true }).decode(data.subarray(2));
|
|
252
|
+
if (data[0] === 0xff && data[1] === 0xfe) return new TextDecoder("utf-16le", { ignoreBOM: true }).decode(data.subarray(2));
|
|
253
|
+
return new TextDecoder("utf-16le", { ignoreBOM: true }).decode(data);
|
|
254
|
+
}
|
|
255
|
+
if (label) return new TextDecoder(label, { ignoreBOM: true }).decode(data);
|
|
256
|
+
throw new Error("unsupported codec " + codec);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const CHARSET_IN_TYPE = rx("charset\\s*=\\s*[\"']?([\\w.:-]+)", "i", "");
|
|
260
|
+
const META_CHARSET = /<meta[^>]+charset=["']?([A-Za-z0-9_-]+)/i;
|
|
261
|
+
|
|
262
|
+
/** (text, isUtf8): the page's text, as Python's _decode makes it. */
|
|
263
|
+
function decode(data, charset) {
|
|
264
|
+
if (data[0] === 0x1f && data[1] === 0x8b) {
|
|
265
|
+
const out = gunzip(data);
|
|
266
|
+
if (out) data = out;
|
|
267
|
+
} else if (data[0] === 0x78 && data.length > 2 && (data[0] * 256 + data[1]) % 31 === 0) {
|
|
268
|
+
try {
|
|
269
|
+
data = zlib.inflateSync(data);
|
|
270
|
+
} catch (e) { /* kept as received */ }
|
|
271
|
+
}
|
|
272
|
+
if (data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) {
|
|
273
|
+
return new TextDecoder("utf-8", { ignoreBOM: true }).decode(data.subarray(3));
|
|
274
|
+
}
|
|
275
|
+
if ((data[0] === 0xff && data[1] === 0xfe) || (data[0] === 0xfe && data[1] === 0xff)) {
|
|
276
|
+
return decodeWith(data, "utf_16");
|
|
277
|
+
}
|
|
278
|
+
try {
|
|
279
|
+
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(data);
|
|
280
|
+
} catch (e) { /* not UTF-8 */ }
|
|
281
|
+
let declared = null;
|
|
282
|
+
if (charset && typeof charset === "string") {
|
|
283
|
+
const m = CHARSET_IN_TYPE.exec(charset);
|
|
284
|
+
declared = m ? m[1] : (!charset.includes("/") && !charset.includes(";") ? strip(charset) : null);
|
|
285
|
+
}
|
|
286
|
+
if (!declared) {
|
|
287
|
+
const m = META_CHARSET.exec(Buffer.from(data.subarray(0, 4096)).toString("latin1"));
|
|
288
|
+
declared = m ? m[1] : null;
|
|
289
|
+
}
|
|
290
|
+
if (declared) {
|
|
291
|
+
declared = strip(declared).toLowerCase();
|
|
292
|
+
declared = ALIAS[declared] || declared;
|
|
293
|
+
if (declared === "utf-8" || declared === "utf8") return new TextDecoder("utf-8", { ignoreBOM: true }).decode(data);
|
|
294
|
+
const codec = lookup(declared);
|
|
295
|
+
if (codec) {
|
|
296
|
+
try {
|
|
297
|
+
return decodeWith(data, codec);
|
|
298
|
+
} catch (e) { /* falls back to cp1252 */ }
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return decodeWith(data, "cp1252");
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
module.exports = { decode, decodeWith, lookup, gunzip, crc32 };
|
package/lib/memory.js
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Site memory: catch a dead deep address that answers 200 with another page of the same site (most often the home
|
|
3
|
+
// page). Same thresholds, hashes and saved file as the Python package, so a memory moves between the two.
|
|
4
|
+
const fs = require("fs");
|
|
5
|
+
const { checkPage, Page, parts, pyStr, search, signal, asBytes, HOME_PATH } = require("./page");
|
|
6
|
+
const { decode, crc32 } = require("./decode");
|
|
7
|
+
const { rx, WORD } = require("./pyre");
|
|
8
|
+
const { cpSlice, split } = require("./text");
|
|
9
|
+
const { loads, dumps } = require("./pyjson");
|
|
10
|
+
const C = require("./classes.json");
|
|
11
|
+
|
|
12
|
+
const NEAR = 2; // simhash bits that may differ between two fetches of one page
|
|
13
|
+
const LENGTH = 0.05; // the two visible texts may differ by at most this share of the longer one
|
|
14
|
+
const MIN_TEXT = 500; // below this much text (or MIN_SHINGLES 3-grams) the memory says nothing
|
|
15
|
+
const MIN_SHINGLES = 60;
|
|
16
|
+
const OTHERS = 2; // a page identical to this many pages seen under other paths is a catch-all page too
|
|
17
|
+
const SURE_BITS = 1; // a copy of the home page this close, title included, is called with high confidence
|
|
18
|
+
const PER_HOST = 200; // records kept per host, oldest dropped first
|
|
19
|
+
const TEXT_CAP = 8000; // characters of visible text fingerprinted
|
|
20
|
+
|
|
21
|
+
const WORDS = new RegExp(`[${WORD}]+`, "gu");
|
|
22
|
+
const LANG = rx(String.raw`^/[a-z]{2}(?:[-_][a-z]{2,4})?(?=/|$)`, "", "");
|
|
23
|
+
const PAGING = rx(String.raw`/(?:page|p|seite|pagina|strona|pag)/?\d+$|/\d{1,3}$`, "", "");
|
|
24
|
+
const INDEX = rx(String.raw`/index\.[a-z0-9]+$`, "", "");
|
|
25
|
+
const CASED = /[\p{Cased}]/u;
|
|
26
|
+
const IGNORABLE = /[\p{Case_Ignorable}]/u;
|
|
27
|
+
|
|
28
|
+
/** Python str.lower(): its own Unicode table, and the final-sigma rule. */
|
|
29
|
+
function pyLower(s) {
|
|
30
|
+
const cps = Array.from(s);
|
|
31
|
+
let out = "";
|
|
32
|
+
for (let i = 0; i < cps.length; i++) {
|
|
33
|
+
const c = cps[i];
|
|
34
|
+
if (c !== "Σ") {
|
|
35
|
+
out += C.lower[c] !== undefined ? C.lower[c] : c;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
let j = i - 1;
|
|
39
|
+
while (j >= 0 && IGNORABLE.test(cps[j])) j--;
|
|
40
|
+
let final = j >= 0 && CASED.test(cps[j]);
|
|
41
|
+
if (final) {
|
|
42
|
+
j = i + 1;
|
|
43
|
+
while (j < cps.length && IGNORABLE.test(cps[j])) j++;
|
|
44
|
+
final = j === cps.length || !CASED.test(cps[j]);
|
|
45
|
+
}
|
|
46
|
+
out += final ? "ς" : "σ";
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Python re.sub(pattern, "", s, count=1) for a non-global pattern. */
|
|
52
|
+
function cut(re, s) {
|
|
53
|
+
const m = search(re, s);
|
|
54
|
+
return m ? s.slice(0, m.index) + s.slice(m.index + m[0].length) : s;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A path folded so that variants of one page meet: no language prefix, index file, page number or end slash. */
|
|
58
|
+
function pathKey(path) {
|
|
59
|
+
path = pyLower(path).replace(/\/{2,}/g, "/");
|
|
60
|
+
path = cut(INDEX, cut(LANG, path)).replace(/\/+$/, "");
|
|
61
|
+
for (;;) {
|
|
62
|
+
const shorter = cut(PAGING, path).replace(/\/+$/, "");
|
|
63
|
+
if (shorter === path) return path;
|
|
64
|
+
path = shorter;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// BLAKE2b with an 8-byte digest, on 32-bit halves (lo, hi) of each 64-bit word.
|
|
69
|
+
const IV = new Uint32Array([0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1,
|
|
70
|
+
0xa54ff53a, 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19]);
|
|
71
|
+
const SIGMA = [
|
|
72
|
+
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
|
|
73
|
+
[11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
|
|
74
|
+
[9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
|
|
75
|
+
[12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11], [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
|
|
76
|
+
[6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5], [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
|
|
77
|
+
];
|
|
78
|
+
const V = new Uint32Array(32);
|
|
79
|
+
const M = new Uint32Array(32);
|
|
80
|
+
|
|
81
|
+
/** v[a] += v[b] + (x1:x0), 64-bit. */
|
|
82
|
+
function add(a, b, x0, x1) {
|
|
83
|
+
let lo = V[a] + V[b];
|
|
84
|
+
let hi = V[a + 1] + V[b + 1] + (lo >= 0x100000000 ? 1 : 0);
|
|
85
|
+
lo = lo >>> 0;
|
|
86
|
+
const lo2 = lo + x0;
|
|
87
|
+
hi = hi + x1 + (lo2 >= 0x100000000 ? 1 : 0);
|
|
88
|
+
V[a] = lo2;
|
|
89
|
+
V[a + 1] = hi;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** BLAKE2b's mixing function G on words a, b, c, d (indexes of lo halves) with message words x, y. */
|
|
93
|
+
function mix(a, b, c, d, x, y) {
|
|
94
|
+
add(a, b, M[x], M[x + 1]);
|
|
95
|
+
let p = V[d] ^ V[a];
|
|
96
|
+
let q = V[d + 1] ^ V[a + 1];
|
|
97
|
+
V[d] = q;
|
|
98
|
+
V[d + 1] = p;
|
|
99
|
+
add(c, d, 0, 0);
|
|
100
|
+
p = V[b] ^ V[c];
|
|
101
|
+
q = V[b + 1] ^ V[c + 1];
|
|
102
|
+
V[b] = (p >>> 24) ^ (q << 8);
|
|
103
|
+
V[b + 1] = (q >>> 24) ^ (p << 8);
|
|
104
|
+
add(a, b, M[y], M[y + 1]);
|
|
105
|
+
p = V[d] ^ V[a];
|
|
106
|
+
q = V[d + 1] ^ V[a + 1];
|
|
107
|
+
V[d] = (p >>> 16) ^ (q << 16);
|
|
108
|
+
V[d + 1] = (q >>> 16) ^ (p << 16);
|
|
109
|
+
add(c, d, 0, 0);
|
|
110
|
+
p = V[b] ^ V[c];
|
|
111
|
+
q = V[b + 1] ^ V[c + 1];
|
|
112
|
+
V[b] = (q >>> 31) ^ (p << 1);
|
|
113
|
+
V[b + 1] = (p >>> 31) ^ (q << 1);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Python blake2b(data, digest_size=8) read as a big-endian 64-bit number: [high 32 bits, low 32 bits]. */
|
|
117
|
+
function blake8(data) {
|
|
118
|
+
const h = new Uint32Array(IV);
|
|
119
|
+
h[0] ^= 0x01010008;
|
|
120
|
+
const n = data.length;
|
|
121
|
+
let at = 0;
|
|
122
|
+
do {
|
|
123
|
+
const last = n - at <= 128;
|
|
124
|
+
const block = new Uint8Array(128);
|
|
125
|
+
block.set(data.subarray(at, at + 128));
|
|
126
|
+
at = Math.min(n, at + 128);
|
|
127
|
+
for (let i = 0; i < 32; i++) {
|
|
128
|
+
M[i] = block[i * 4] | (block[i * 4 + 1] << 8) | (block[i * 4 + 2] << 16) | (block[i * 4 + 3] << 24);
|
|
129
|
+
}
|
|
130
|
+
for (let i = 0; i < 16; i++) {
|
|
131
|
+
V[i] = h[i];
|
|
132
|
+
V[i + 16] = IV[i];
|
|
133
|
+
}
|
|
134
|
+
V[24] ^= at;
|
|
135
|
+
if (last) {
|
|
136
|
+
V[28] = ~V[28];
|
|
137
|
+
V[29] = ~V[29];
|
|
138
|
+
}
|
|
139
|
+
for (let r = 0; r < 12; r++) {
|
|
140
|
+
const s = SIGMA[r % 10];
|
|
141
|
+
mix(0, 8, 16, 24, s[0] * 2, s[1] * 2);
|
|
142
|
+
mix(2, 10, 18, 26, s[2] * 2, s[3] * 2);
|
|
143
|
+
mix(4, 12, 20, 28, s[4] * 2, s[5] * 2);
|
|
144
|
+
mix(6, 14, 22, 30, s[6] * 2, s[7] * 2);
|
|
145
|
+
mix(0, 10, 20, 30, s[8] * 2, s[9] * 2);
|
|
146
|
+
mix(2, 12, 22, 24, s[10] * 2, s[11] * 2);
|
|
147
|
+
mix(4, 14, 16, 26, s[12] * 2, s[13] * 2);
|
|
148
|
+
mix(6, 8, 18, 28, s[14] * 2, s[15] * 2);
|
|
149
|
+
}
|
|
150
|
+
for (let i = 0; i < 16; i++) h[i] ^= V[i] ^ V[i + 16];
|
|
151
|
+
} while (at < n);
|
|
152
|
+
const swap = (w) => (((w & 0xff) << 24) | ((w & 0xff00) << 8) | ((w >>> 8) & 0xff00) | (w >>> 24)) >>> 0;
|
|
153
|
+
return [swap(h[0]), swap(h[1])];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** [64-bit simhash (BigInt) of the text's distinct lower-case word 3-grams, how many distinct 3-grams there were]. */
|
|
157
|
+
function simhash(text) {
|
|
158
|
+
const words = pyLower(cpSlice(text, TEXT_CAP)).match(WORDS) || [];
|
|
159
|
+
const set = new Set();
|
|
160
|
+
for (let i = 0; i + 2 < words.length; i++) set.add(`${words[i]} ${words[i + 1]} ${words[i + 2]}`);
|
|
161
|
+
if (!set.size) return [0n, 0];
|
|
162
|
+
const grams = Array.from(set, (g) => Buffer.from(g, "utf8"));
|
|
163
|
+
let picked = grams.filter((g) => !(crc32(g) & 7));
|
|
164
|
+
if (picked.length < 32) picked = grams;
|
|
165
|
+
const counts = new Array(64).fill(0);
|
|
166
|
+
for (const g of picked) {
|
|
167
|
+
const [hi, lo] = blake8(g);
|
|
168
|
+
for (let b = 0; b < 32; b++) {
|
|
169
|
+
if ((hi >>> (31 - b)) & 1) counts[b]++;
|
|
170
|
+
if ((lo >>> (31 - b)) & 1) counts[b + 32]++;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const half = picked.length / 2;
|
|
174
|
+
let value = 0n;
|
|
175
|
+
for (const c of counts) value = (value << 1n) | (c > half ? 1n : 0n);
|
|
176
|
+
return [value, set.size];
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Set bits of a 64-bit BigInt. */
|
|
180
|
+
function popcount(x) {
|
|
181
|
+
let n = 0;
|
|
182
|
+
for (let w of [Number(x & 0xffffffffn), Number(x >> 32n)]) {
|
|
183
|
+
for (; w; w = (w & (w - 1)) >>> 0) n++;
|
|
184
|
+
}
|
|
185
|
+
return n;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** A short, stable hash of the page title. */
|
|
189
|
+
function titleHash(title) {
|
|
190
|
+
return crc32(Buffer.from(split(pyLower(title)).join(" "), "utf8"));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Simhash bits apart when two records look like the same page (same title, near hash, similar length), else -1. */
|
|
194
|
+
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;
|
|
197
|
+
const apart = popcount(a.h ^ b.h);
|
|
198
|
+
return apart <= NEAR ? apart : -1;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Python sorted() order for strings: by code point. */
|
|
202
|
+
function byCodePoint(a, b) {
|
|
203
|
+
const x = Array.from(a);
|
|
204
|
+
const y = Array.from(b);
|
|
205
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
206
|
+
if (x[i] !== y[i]) return x[i].codePointAt(0) - y[i].codePointAt(0);
|
|
207
|
+
}
|
|
208
|
+
return x.length - y.length;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** check_page, plus the page reader it used (or null). */
|
|
212
|
+
function core(html, opts) {
|
|
213
|
+
const handover = { reader: null };
|
|
214
|
+
const result = checkPage(html, { ...opts, _handover: handover });
|
|
215
|
+
return [result, handover.reader];
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Pages already judged "ok", per site; checkPage here also asks whether a deep address shows one of them. */
|
|
219
|
+
class SiteMemory {
|
|
220
|
+
/** perHost: how many page records to keep for each site (the oldest go first). */
|
|
221
|
+
constructor(perHost = PER_HOST) {
|
|
222
|
+
this.perHost = perHost;
|
|
223
|
+
this.hosts = new Map();
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** How many records are kept, all sites together. */
|
|
227
|
+
get size() {
|
|
228
|
+
let n = 0;
|
|
229
|
+
for (const s of this.hosts.values()) n += s.size;
|
|
230
|
+
return n;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** [host, record, 3-grams, deep] for a page the core called "ok", or null without a usable address. */
|
|
234
|
+
_record(html, result, url, finalUrl, headers, reader) {
|
|
235
|
+
const page = finalUrl || url;
|
|
236
|
+
const at = page ? parts(pyStr(page)) : null;
|
|
237
|
+
const asked = url ? parts(pyStr(url)) : null;
|
|
238
|
+
if (at === null || !at[0]) return null;
|
|
239
|
+
if (!reader) {
|
|
240
|
+
const b = asBytes(html);
|
|
241
|
+
if (b) {
|
|
242
|
+
let ctype;
|
|
243
|
+
if (headers && typeof headers === "object" && !Array.isArray(headers) && !asBytes(headers)) {
|
|
244
|
+
const pairs = headers instanceof Map ? headers.entries() : Object.entries(headers);
|
|
245
|
+
for (const [k, v] of pairs) if (pyStr(k).toLowerCase() === "content-type") ctype = pyStr(v);
|
|
246
|
+
}
|
|
247
|
+
html = decode(b, ctype === undefined ? null : ctype);
|
|
248
|
+
}
|
|
249
|
+
reader = new Page(html || "");
|
|
250
|
+
}
|
|
251
|
+
const [h, grams] = simhash(reader.text);
|
|
252
|
+
const root = !!(search(HOME_PATH, at[1]) || (asked && search(HOME_PATH, asked[1])) || pathKey(at[1]) === "");
|
|
253
|
+
const deep = !root && !(asked && pathKey(asked[1]) === "");
|
|
254
|
+
const record = { k: pathKey(at[1]), r: root, n: result.text_length, h, t: titleHash(result.title) };
|
|
255
|
+
return [at[0], record, grams, deep];
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** The signal for a deep page that repeats the site's home page or a page seen under OTHERS other paths. */
|
|
259
|
+
_match(host, record, grams) {
|
|
260
|
+
if (record.n < MIN_TEXT || grams < MIN_SHINGLES) return null;
|
|
261
|
+
const seen = this.hosts.get(host);
|
|
262
|
+
if (!seen || !seen.size) return null;
|
|
263
|
+
const others = new Set();
|
|
264
|
+
for (const rec of seen.values()) {
|
|
265
|
+
if (rec.k === record.k) continue;
|
|
266
|
+
const apart = same(rec, record);
|
|
267
|
+
if (apart < 0) continue;
|
|
268
|
+
if (rec.r) return signal("same-as-home", "soft_404", `the page is the site's home page (${apart} of 64 bits apart)`);
|
|
269
|
+
others.add(rec.k);
|
|
270
|
+
}
|
|
271
|
+
if (others.size >= OTHERS) {
|
|
272
|
+
const shown = Array.from(others, (k) => "/" + k.replace(/^\/+/, "")).sort(byCodePoint).slice(0, 3).join(", ");
|
|
273
|
+
return signal("same-as-other-pages", "soft_404", `the page already seen at ${others.size} other paths: ${shown}`);
|
|
274
|
+
}
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Keep a record for the site (replacing an older one for the same path), dropping the oldest past perHost. */
|
|
279
|
+
learn(host, record) {
|
|
280
|
+
let seen = this.hosts.get(host);
|
|
281
|
+
if (!seen) this.hosts.set(host, (seen = new Map()));
|
|
282
|
+
seen.delete(record.k);
|
|
283
|
+
seen.set(record.k, record);
|
|
284
|
+
while (seen.size > this.perHost) seen.delete(seen.keys().next().value);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** The core result turned into the core's "not found" verdict when the memory found a match. */
|
|
288
|
+
_judge(result, sig, record, host) {
|
|
289
|
+
if (sig === null) return result;
|
|
290
|
+
return { ...result, verdict: "soft_404", action: "drop", reason: `${sig.id} (${sig.detail})`,
|
|
291
|
+
signals: [...result.signals, sig], vendor: null, confidence: this._confidence(sig, record, host) };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** High for a near-exact copy of the home page with its title, medium otherwise. */
|
|
295
|
+
_confidence(sig, record, host) {
|
|
296
|
+
if (sig.id !== "same-as-home") return "medium";
|
|
297
|
+
const seen = this.hosts.get(host);
|
|
298
|
+
const homes = seen ? Array.from(seen.values()).filter((r) => r.r && r.t === record.t) : [];
|
|
299
|
+
return homes.some((r) => popcount(r.h ^ record.h) <= SURE_BITS) ? "high" : "medium";
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* checkPage with the site's memory: same options (plus learn, default true); a deep address showing a page already
|
|
304
|
+
* seen elsewhere on the site becomes "soft_404" (signal same-as-home or same-as-other-pages). "ok" pages are kept.
|
|
305
|
+
*/
|
|
306
|
+
checkPage(html, opts = {}) {
|
|
307
|
+
const { learn = true, ...rest } = opts;
|
|
308
|
+
const [result, reader] = core(html, rest);
|
|
309
|
+
if (result.verdict !== "ok") return result;
|
|
310
|
+
const made = this._record(html, result, rest.url, rest.finalUrl, rest.headers, reader);
|
|
311
|
+
if (made === null) return result;
|
|
312
|
+
const [host, record, grams, deep] = made;
|
|
313
|
+
const sig = deep ? this._match(host, record, grams) : null;
|
|
314
|
+
if (sig === null && learn) this.learn(host, record);
|
|
315
|
+
return this._judge(result, sig, record, host);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** The memory as plain data, Python's to_dict() (h as BigInt). */
|
|
319
|
+
toDict() {
|
|
320
|
+
const hosts = {};
|
|
321
|
+
for (const host of Array.from(this.hosts.keys()).sort(byCodePoint)) hosts[host] = Array.from(this.hosts.get(host).values());
|
|
322
|
+
return { version: 1, per_host: this.perHost, hosts };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** The memory as the JSON text Python's save() writes. */
|
|
326
|
+
dumps() {
|
|
327
|
+
return dumps(this.toDict(), { separators: [",", ":"], intNumbers: true });
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Write the memory to a JSON file (readable by the Python package too). */
|
|
331
|
+
save(path) {
|
|
332
|
+
fs.writeFileSync(path, this.dumps(), "utf8");
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** A memory rebuilt from toDict's data or Python's to_dict() (unknown fields ignored). */
|
|
336
|
+
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")) });
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return mem;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** A memory from the JSON text of dumps() or of Python's save(). */
|
|
356
|
+
static loads(text) {
|
|
357
|
+
return SiteMemory.fromDict(loads(text));
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Read a memory written by save() (or by the Python package). */
|
|
361
|
+
static load(path) {
|
|
362
|
+
return SiteMemory.loads(fs.readFileSync(path, "utf8"));
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Check many pages so that their order does not matter: the first pass runs the core and remembers every "ok" page,
|
|
368
|
+
* the second judges each deep page against all the others. items: { html, url, finalUrl, status, headers, ... } or
|
|
369
|
+
* plain html; options: memory (an existing one to add to) and options for every page.
|
|
370
|
+
*/
|
|
371
|
+
function checkPagesWithMemory(items, options = {}) {
|
|
372
|
+
const { memory, ...common } = options;
|
|
373
|
+
const mem = memory || new SiteMemory();
|
|
374
|
+
const done = [];
|
|
375
|
+
for (const item of items) {
|
|
376
|
+
const kw = typeof item === "string" || asBytes(item) ? { ...common, html: item } : { ...common, ...item };
|
|
377
|
+
const { html, ...rest } = kw;
|
|
378
|
+
const [result, reader] = core(html, rest);
|
|
379
|
+
const made = result.verdict === "ok" ? mem._record(html, result, rest.url, rest.finalUrl, rest.headers, reader) : null;
|
|
380
|
+
if (made !== null) mem.learn(made[0], made[1]);
|
|
381
|
+
done.push([result, made]);
|
|
382
|
+
}
|
|
383
|
+
return done.map(([result, made]) => {
|
|
384
|
+
if (made === null) return result;
|
|
385
|
+
const [host, record, grams, deep] = made;
|
|
386
|
+
return mem._judge(result, deep ? mem._match(host, record, grams) : null, record, host);
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
module.exports = { SiteMemory, checkPagesWithMemory, simhash, pathKey, pyLower };
|