oculon 0.1.5 → 0.1.7
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 +72 -4
- package/dist/cli/main.js +184 -0
- package/dist/core/calls.d.ts +63 -0
- package/dist/core/calls.js +120 -0
- package/dist/core/evm.d.ts +20 -0
- package/dist/core/evm.js +165 -0
- package/dist/core/http.d.ts +11 -0
- package/dist/core/http.js +113 -30
- package/dist/core/pdf.d.ts +51 -0
- package/dist/core/pdf.js +211 -0
- package/dist/core/quota.js +3 -0
- package/dist/core/verdict.d.ts +30 -0
- package/dist/core/verdict.js +164 -0
- package/dist/index.d.ts +38 -0
- package/dist/index.js +54 -0
- package/dist/mcp.d.ts +1 -0
- package/dist/mcp.js +159 -5
- package/dist/modules/address.d.ts +32 -0
- package/dist/modules/address.js +91 -0
- package/dist/modules/checks.d.ts +59 -0
- package/dist/modules/checks.js +134 -0
- package/dist/modules/doc.d.ts +61 -0
- package/dist/modules/doc.js +715 -0
- package/dist/modules/headers.d.ts +50 -0
- package/dist/modules/headers.js +108 -0
- package/dist/modules/honeypot.d.ts +36 -0
- package/dist/modules/honeypot.js +53 -0
- package/dist/modules/iban.d.ts +30 -0
- package/dist/modules/iban.js +82 -0
- package/dist/modules/lookalike.d.ts +34 -0
- package/dist/modules/lookalike.js +122 -0
- package/dist/modules/personal.d.ts +1 -1
- package/dist/modules/personal.js +14 -4
- package/dist/modules/utility.d.ts +147 -0
- package/dist/modules/utility.js +403 -0
- package/dist/report-pdf.d.ts +7 -0
- package/dist/report-pdf.js +81 -0
- package/dist/telegram.d.ts +2 -0
- package/dist/telegram.js +43 -6
- package/dist/web/assets/logo-200.png +0 -0
- package/dist/web/burns.d.ts +21 -0
- package/dist/web/burns.js +53 -0
- package/dist/web/card.d.ts +28 -0
- package/dist/web/card.js +75 -0
- package/dist/web/index.html +76 -4
- package/dist/web/landing.html +1 -1
- package/dist/web/legal.html +1 -1
- package/dist/web/mcp.html +1 -1
- package/dist/web/openapi.js +6 -0
- package/dist/web/pages.d.ts +24 -0
- package/dist/web/pages.js +139 -0
- package/dist/web/public.js +7 -1
- package/dist/web/server.d.ts +17 -0
- package/dist/web/server.js +207 -7
- package/dist/web/token.html +98 -0
- package/dist/web/token.json +9 -0
- package/dist/web/utility.html +251 -0
- package/package.json +1 -1
|
@@ -0,0 +1,715 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Document check: was this invoice, bank statement or payment proof edited?
|
|
3
|
+
* Reads the file itself, no upload to anyone else:
|
|
4
|
+
* - PDF: producer and creator programs, creation vs modification dates, how many times it was saved
|
|
5
|
+
* (incremental updates), edit history in XMP, fonts embedded twice (text added by a second program),
|
|
6
|
+
* white boxes drawn over the page, annotations, signatures, and dangerous parts (JavaScript, launch actions,
|
|
7
|
+
* embedded files). The text layer is extracted and every IBAN in it is checked.
|
|
8
|
+
* - JPEG / PNG (screenshots, photos): editor software in EXIF, XMP and PNG text chunks. When a free AI key
|
|
9
|
+
* (Gemini or Mistral) is set, the text in the image is transcribed so IBANs in it are checked too.
|
|
10
|
+
* A clean result is not proof that a document is genuine: it only means none of these traces were found.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { inflateSync, constants as zc } from 'node:zlib';
|
|
14
|
+
import { key } from '../core/keys.js';
|
|
15
|
+
import { signalId } from '../core/text.js';
|
|
16
|
+
import { checkIban } from './iban.js';
|
|
17
|
+
export const DOC_MAX_BYTES = 10 * 1024 * 1024;
|
|
18
|
+
function inflate(b) {
|
|
19
|
+
try {
|
|
20
|
+
return inflateSync(b, { finishFlush: zc.Z_SYNC_FLUSH });
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Objects of a PDF, including those packed in object streams. Streams are decoded when they use FlateDecode. */
|
|
27
|
+
export function pdfObjects(buf) {
|
|
28
|
+
const raw = buf.toString('latin1');
|
|
29
|
+
const out = [];
|
|
30
|
+
const re = /(\d+)\s+\d+\s+obj\b/g;
|
|
31
|
+
let m;
|
|
32
|
+
while ((m = re.exec(raw))) {
|
|
33
|
+
const start = m.index + m[0].length;
|
|
34
|
+
const end = raw.indexOf('endobj', start);
|
|
35
|
+
if (end < 0)
|
|
36
|
+
break;
|
|
37
|
+
const body = raw.slice(start, end);
|
|
38
|
+
const si = body.search(/\bstream\r?\n/);
|
|
39
|
+
let dict = body, stream = null, rawStream = null;
|
|
40
|
+
if (si >= 0) {
|
|
41
|
+
dict = body.slice(0, si);
|
|
42
|
+
const ds = start + si + (/\bstream\r\n/.test(body.slice(si, si + 8)) ? 8 : 7);
|
|
43
|
+
const len = /\/Length\s+(\d+)(?!\s+\d+\s+R)/.exec(dict);
|
|
44
|
+
let de = len ? ds + Number(len[1]) : raw.indexOf('endstream', ds);
|
|
45
|
+
if (de < ds || de > end)
|
|
46
|
+
de = raw.indexOf('endstream', ds);
|
|
47
|
+
rawStream = buf.subarray(ds, de > ds ? de : ds);
|
|
48
|
+
stream = /\/FlateDecode/.test(dict) ? inflate(rawStream) : /\/Filter/.test(dict) ? null : rawStream;
|
|
49
|
+
}
|
|
50
|
+
out.push({ num: Number(m[1]), dict, stream, raw: rawStream });
|
|
51
|
+
re.lastIndex = end;
|
|
52
|
+
}
|
|
53
|
+
// Object streams (PDF 1.5+) hold more objects, often including the metadata.
|
|
54
|
+
for (const o of [...out]) {
|
|
55
|
+
if (!/\/Type\s*\/ObjStm/.test(o.dict) || !o.stream)
|
|
56
|
+
continue;
|
|
57
|
+
const s = o.stream.toString('latin1');
|
|
58
|
+
const n = Number(/\/N\s+(\d+)/.exec(o.dict)?.[1] ?? 0);
|
|
59
|
+
const first = Number(/\/First\s+(\d+)/.exec(o.dict)?.[1] ?? 0);
|
|
60
|
+
const nums = s.slice(0, first).trim().split(/\s+/).map(Number);
|
|
61
|
+
for (let i = 0; i < n && i * 2 + 1 < nums.length; i++) {
|
|
62
|
+
const a = first + nums[i * 2 + 1];
|
|
63
|
+
const b = i + 1 < n && i * 2 + 3 < nums.length ? first + nums[i * 2 + 3] : s.length;
|
|
64
|
+
out.push({ num: nums[i * 2], dict: s.slice(a, b), stream: null, raw: null });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
/** A PDF string value: (literal) with escapes, or <hex>, UTF-16 when it starts with a byte order mark. */
|
|
70
|
+
export function pdfString(src) {
|
|
71
|
+
let bytes = [];
|
|
72
|
+
if (src.startsWith('<')) {
|
|
73
|
+
const hex = src.slice(1, src.indexOf('>') < 0 ? undefined : src.indexOf('>')).replace(/\s+/g, '');
|
|
74
|
+
for (let i = 0; i < hex.length; i += 2)
|
|
75
|
+
bytes.push(parseInt(hex.slice(i, i + 2).padEnd(2, '0'), 16));
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
let depth = 0;
|
|
79
|
+
for (let i = 1; i < src.length; i++) {
|
|
80
|
+
const c = src[i];
|
|
81
|
+
if (c === '\\') {
|
|
82
|
+
const n = src[++i];
|
|
83
|
+
const map = { n: 10, r: 13, t: 9, b: 8, f: 12, '(': 40, ')': 41, '\\': 92 };
|
|
84
|
+
if (n in map)
|
|
85
|
+
bytes.push(map[n]);
|
|
86
|
+
else if (/[0-7]/.test(n)) {
|
|
87
|
+
let o = n;
|
|
88
|
+
while (o.length < 3 && /[0-7]/.test(src[i + 1] ?? ''))
|
|
89
|
+
o += src[++i];
|
|
90
|
+
bytes.push(parseInt(o, 8) & 255);
|
|
91
|
+
}
|
|
92
|
+
else if (n === '\r' || n === '\n') {
|
|
93
|
+
if (n === '\r' && src[i + 1] === '\n')
|
|
94
|
+
i++;
|
|
95
|
+
}
|
|
96
|
+
else
|
|
97
|
+
bytes.push(n.charCodeAt(0));
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (c === '(')
|
|
101
|
+
depth++;
|
|
102
|
+
if (c === ')') {
|
|
103
|
+
if (depth === 0)
|
|
104
|
+
break;
|
|
105
|
+
depth--;
|
|
106
|
+
}
|
|
107
|
+
bytes.push(c.charCodeAt(0) & 255);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (bytes[0] === 0xfe && bytes[1] === 0xff) {
|
|
111
|
+
bytes = bytes.slice(2);
|
|
112
|
+
let s = '';
|
|
113
|
+
for (let i = 0; i + 1 < bytes.length; i += 2)
|
|
114
|
+
s += String.fromCharCode((bytes[i] << 8) | bytes[i + 1]);
|
|
115
|
+
return s;
|
|
116
|
+
}
|
|
117
|
+
return Buffer.from(bytes).toString('latin1');
|
|
118
|
+
}
|
|
119
|
+
/** Value of `/Key (string)` or `/Key <hex>` in a dictionary. */
|
|
120
|
+
function dictString(dict, k) {
|
|
121
|
+
const m = new RegExp(`/${k}\\s*(\\((?:\\\\.|[^\\\\])*?\\)|<[0-9A-Fa-f\\s]*>)`).exec(dict);
|
|
122
|
+
if (!m)
|
|
123
|
+
return null;
|
|
124
|
+
// Literal strings may contain balanced parentheses; read from the match to the real end.
|
|
125
|
+
const at = m.index + m[0].indexOf(m[1]);
|
|
126
|
+
return pdfString(m[1].startsWith('<') ? m[1] : dict.slice(at)).trim() || null;
|
|
127
|
+
}
|
|
128
|
+
/** D:YYYYMMDDHHmmSS+hh'mm' to epoch milliseconds. */
|
|
129
|
+
export function pdfDate(s) {
|
|
130
|
+
if (!s)
|
|
131
|
+
return null;
|
|
132
|
+
const m = /(?:D:)?(\d{4})(\d{2})?(\d{2})?(\d{2})?(\d{2})?(\d{2})?(Z|[+-]\d{2}'?\d{2}'?)?/.exec(s);
|
|
133
|
+
if (!m)
|
|
134
|
+
return null;
|
|
135
|
+
const [y, mo = '01', d = '01', h = '00', mi = '00', se = '00'] = m.slice(1, 7);
|
|
136
|
+
let t = Date.UTC(+y, +mo - 1, +d, +h, +mi, +se);
|
|
137
|
+
const tz = m[7];
|
|
138
|
+
if (tz && tz !== 'Z') {
|
|
139
|
+
const sign = tz[0] === '-' ? -1 : 1;
|
|
140
|
+
const [hh, mm] = [Number(tz.slice(1, 3)), Number(tz.replace(/'/g, '').slice(3, 5) || 0)];
|
|
141
|
+
t -= sign * (hh * 60 + mm) * 60_000;
|
|
142
|
+
}
|
|
143
|
+
return Number.isFinite(t) ? t : null;
|
|
144
|
+
}
|
|
145
|
+
/** ToUnicode CMap: character code (hex) to text. */
|
|
146
|
+
function parseCMap(s) {
|
|
147
|
+
const map = new Map();
|
|
148
|
+
const hexText = (h) => {
|
|
149
|
+
let t = '';
|
|
150
|
+
for (let i = 0; i + 3 < h.length + 1; i += 4)
|
|
151
|
+
t += String.fromCharCode(parseInt(h.slice(i, i + 4).padEnd(4, '0'), 16));
|
|
152
|
+
return t;
|
|
153
|
+
};
|
|
154
|
+
let bytes = 1;
|
|
155
|
+
const cs = /begincodespacerange\s*<([0-9A-Fa-f]+)>/.exec(s);
|
|
156
|
+
if (cs)
|
|
157
|
+
bytes = cs[1].length / 2;
|
|
158
|
+
for (const block of s.matchAll(/beginbfchar([\s\S]*?)endbfchar/g)) {
|
|
159
|
+
for (const p of block[1].matchAll(/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g))
|
|
160
|
+
map.set(p[1].toUpperCase(), hexText(p[2]));
|
|
161
|
+
}
|
|
162
|
+
for (const block of s.matchAll(/beginbfrange([\s\S]*?)endbfrange/g)) {
|
|
163
|
+
for (const p of block[1].matchAll(/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*(<[0-9A-Fa-f]+>|\[[^\]]*\])/g)) {
|
|
164
|
+
const lo = parseInt(p[1], 16), hi = parseInt(p[2], 16), w = p[1].length;
|
|
165
|
+
if (hi - lo > 5000)
|
|
166
|
+
continue;
|
|
167
|
+
if (p[3].startsWith('[')) {
|
|
168
|
+
const items = [...p[3].matchAll(/<([0-9A-Fa-f]+)>/g)].map((x) => hexText(x[1]));
|
|
169
|
+
items.forEach((t, i) => map.set((lo + i).toString(16).toUpperCase().padStart(w, '0'), t));
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
const base = parseInt(p[3].slice(1, -1), 16);
|
|
173
|
+
for (let c = lo; c <= hi; c++)
|
|
174
|
+
map.set(c.toString(16).toUpperCase().padStart(w, '0'), String.fromCharCode(base + (c - lo)));
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return { map, bytes };
|
|
179
|
+
}
|
|
180
|
+
/** Text of the pages, in drawing order. Good enough to find account numbers, not a layout-perfect extraction. */
|
|
181
|
+
function pdfText(objs) {
|
|
182
|
+
const byNum = new Map();
|
|
183
|
+
for (const o of objs)
|
|
184
|
+
if (!byNum.has(o.num) || o.dict.length > byNum.get(o.num).dict.length)
|
|
185
|
+
byNum.set(o.num, o);
|
|
186
|
+
const deref = (s) => {
|
|
187
|
+
const r = /^\s*(\d+)\s+\d+\s+R/.exec(s);
|
|
188
|
+
return r ? byNum.get(Number(r[1]))?.dict ?? '' : s;
|
|
189
|
+
};
|
|
190
|
+
const sub = (dict, k) => {
|
|
191
|
+
const i = dict.search(new RegExp(`/${k}\\b`));
|
|
192
|
+
if (i < 0)
|
|
193
|
+
return '';
|
|
194
|
+
let rest = dict.slice(i + k.length + 1).trimStart();
|
|
195
|
+
if (/^\d+\s+\d+\s+R/.test(rest))
|
|
196
|
+
return deref(rest);
|
|
197
|
+
if (!rest.startsWith('<<'))
|
|
198
|
+
return '';
|
|
199
|
+
let depth = 0;
|
|
200
|
+
for (let j = 0; j < rest.length - 1; j++) {
|
|
201
|
+
if (rest.startsWith('<<', j)) {
|
|
202
|
+
depth++;
|
|
203
|
+
j++;
|
|
204
|
+
}
|
|
205
|
+
else if (rest.startsWith('>>', j)) {
|
|
206
|
+
depth--;
|
|
207
|
+
j++;
|
|
208
|
+
if (depth === 0)
|
|
209
|
+
return rest.slice(0, j + 1);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return rest;
|
|
213
|
+
};
|
|
214
|
+
const fontCache = new Map();
|
|
215
|
+
const font = (num) => {
|
|
216
|
+
const hit = fontCache.get(num);
|
|
217
|
+
if (hit)
|
|
218
|
+
return hit;
|
|
219
|
+
const d = byNum.get(num)?.dict ?? '';
|
|
220
|
+
const tu = /\/ToUnicode\s+(\d+)\s+\d+\s+R/.exec(d);
|
|
221
|
+
const cm = tu ? byNum.get(Number(tu[1]))?.stream : null;
|
|
222
|
+
const f = { name: /\/BaseFont\s*\/([^\s/<>\[\]]+)/.exec(d)?.[1] ?? '?', cmap: cm ? parseCMap(cm.toString('latin1')) : null, twoByte: /\/Type0|Identity-H/.test(d) };
|
|
223
|
+
fontCache.set(num, f);
|
|
224
|
+
return f;
|
|
225
|
+
};
|
|
226
|
+
let text = '';
|
|
227
|
+
let whiteBoxes = 0;
|
|
228
|
+
for (const page of objs.filter((o) => /\/Type\s*\/Page\b(?!s)/.test(o.dict))) {
|
|
229
|
+
const fonts = new Map();
|
|
230
|
+
const res = sub(page.dict, 'Resources');
|
|
231
|
+
const fdict = sub(res, 'Font');
|
|
232
|
+
for (const m of fdict.matchAll(/\/([^\s/<>\[\]]+)\s+(\d+)\s+\d+\s+R/g))
|
|
233
|
+
fonts.set(m[1], font(Number(m[2])));
|
|
234
|
+
const contents = /\/Contents\s*(\[[^\]]*\]|\d+\s+\d+\s+R)/.exec(page.dict)?.[1] ?? '';
|
|
235
|
+
const streams = [...contents.matchAll(/(\d+)\s+\d+\s+R/g)].map((m) => byNum.get(Number(m[1]))?.stream).filter((s) => Boolean(s));
|
|
236
|
+
const c = streams.map((s) => s.toString('latin1')).join('\n');
|
|
237
|
+
const r = contentText(c, fonts);
|
|
238
|
+
text += r.text + '\n';
|
|
239
|
+
whiteBoxes += r.whiteBoxes;
|
|
240
|
+
}
|
|
241
|
+
return { text, whiteBoxes };
|
|
242
|
+
}
|
|
243
|
+
function decodeShow(s, f) {
|
|
244
|
+
const isHex = s.startsWith('<');
|
|
245
|
+
const raw = isHex ? s.slice(1, -1).replace(/\s+/g, '') : Buffer.from(pdfString(s), 'latin1').toString('hex');
|
|
246
|
+
if (f?.cmap && f.cmap.map.size) {
|
|
247
|
+
const step = (f.twoByte ? 2 : f.cmap.bytes) * 2;
|
|
248
|
+
let out = '';
|
|
249
|
+
for (let i = 0; i < raw.length; i += step)
|
|
250
|
+
out += f.cmap.map.get(raw.slice(i, i + step).toUpperCase()) ?? '';
|
|
251
|
+
return out;
|
|
252
|
+
}
|
|
253
|
+
if (f?.twoByte)
|
|
254
|
+
return '';
|
|
255
|
+
return Buffer.from(raw, 'hex').toString('latin1');
|
|
256
|
+
}
|
|
257
|
+
/** Text shown by a content stream, plus white filled boxes that are not page backgrounds. */
|
|
258
|
+
export function contentText(c, fonts) {
|
|
259
|
+
let out = '', cur, white = false, whiteBoxes = 0, lastShow = '';
|
|
260
|
+
const nums = [];
|
|
261
|
+
let rects = [];
|
|
262
|
+
const tok = /\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>|\[|\]|\/[^\s/<>\[\]()]+|-?\d*\.?\d+|[A-Za-z'"*]+/g;
|
|
263
|
+
let arr = null;
|
|
264
|
+
let lastName = '';
|
|
265
|
+
let m;
|
|
266
|
+
while ((m = tok.exec(c))) {
|
|
267
|
+
const t = m[0];
|
|
268
|
+
if (t === '[') {
|
|
269
|
+
arr = [];
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
if (t === ']')
|
|
273
|
+
continue;
|
|
274
|
+
if (t.startsWith('(') || (t.startsWith('<') && !t.startsWith('<<'))) {
|
|
275
|
+
if (arr)
|
|
276
|
+
arr.push(t);
|
|
277
|
+
else
|
|
278
|
+
lastShow = t;
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
if (t.startsWith('/')) {
|
|
282
|
+
lastName = t.slice(1);
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
if (/^-?\d*\.?\d+$/.test(t)) {
|
|
286
|
+
if (arr) {
|
|
287
|
+
if (Number(t) < -200)
|
|
288
|
+
arr.push(' ');
|
|
289
|
+
}
|
|
290
|
+
else
|
|
291
|
+
nums.push(Number(t));
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
switch (t) {
|
|
295
|
+
case 'Tf':
|
|
296
|
+
cur = fonts.get(lastName);
|
|
297
|
+
break;
|
|
298
|
+
case 'Tj':
|
|
299
|
+
case "'":
|
|
300
|
+
case '"':
|
|
301
|
+
out += decodeShow(lastShow, cur);
|
|
302
|
+
if (t !== 'Tj')
|
|
303
|
+
out += '\n';
|
|
304
|
+
break;
|
|
305
|
+
case 'TJ':
|
|
306
|
+
if (arr)
|
|
307
|
+
out += arr.map((x) => (x === ' ' ? ' ' : decodeShow(x, cur))).join('');
|
|
308
|
+
arr = null;
|
|
309
|
+
break;
|
|
310
|
+
case 'Td':
|
|
311
|
+
case 'TD': {
|
|
312
|
+
const ty = nums[nums.length - 1];
|
|
313
|
+
out += ty && Math.abs(ty) > 1 ? '\n' : ' ';
|
|
314
|
+
break;
|
|
315
|
+
}
|
|
316
|
+
case 'T*':
|
|
317
|
+
case 'Tm':
|
|
318
|
+
case 'ET':
|
|
319
|
+
out += '\n';
|
|
320
|
+
break;
|
|
321
|
+
case 'rg': {
|
|
322
|
+
const [r, g, b] = nums.slice(-3);
|
|
323
|
+
white = r === 1 && g === 1 && b === 1;
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
case 'g':
|
|
327
|
+
white = nums[nums.length - 1] === 1;
|
|
328
|
+
break;
|
|
329
|
+
case 'k': {
|
|
330
|
+
const k = nums.slice(-4);
|
|
331
|
+
white = k.length === 4 && k.every((x) => x === 0);
|
|
332
|
+
break;
|
|
333
|
+
}
|
|
334
|
+
case 're':
|
|
335
|
+
rects.push(nums.slice(-4));
|
|
336
|
+
break;
|
|
337
|
+
case 'f':
|
|
338
|
+
case 'F':
|
|
339
|
+
case 'f*':
|
|
340
|
+
case 'B':
|
|
341
|
+
case 'b':
|
|
342
|
+
if (white)
|
|
343
|
+
for (const [, , w, h] of rects)
|
|
344
|
+
if (w !== undefined && h !== undefined && Math.abs(w) < 500 && Math.abs(h) > 4 && Math.abs(h) < 60 && Math.abs(w) > 10)
|
|
345
|
+
whiteBoxes++;
|
|
346
|
+
rects = [];
|
|
347
|
+
break;
|
|
348
|
+
case 'n':
|
|
349
|
+
case 'S':
|
|
350
|
+
case 's':
|
|
351
|
+
rects = [];
|
|
352
|
+
break;
|
|
353
|
+
}
|
|
354
|
+
if (!/^-?\d/.test(t))
|
|
355
|
+
nums.length = 0;
|
|
356
|
+
}
|
|
357
|
+
return { text: out.replace(/[ \t]+/g, ' ').replace(/\n\s*\n+/g, '\n'), whiteBoxes };
|
|
358
|
+
}
|
|
359
|
+
/* ---------- image metadata ---------- */
|
|
360
|
+
function exifSoftware(app1) {
|
|
361
|
+
const out = {};
|
|
362
|
+
if (app1.subarray(0, 6).toString('latin1') !== 'Exif\0\0')
|
|
363
|
+
return out;
|
|
364
|
+
const t = app1.subarray(6);
|
|
365
|
+
const le = t.subarray(0, 2).toString('latin1') === 'II';
|
|
366
|
+
const u16 = (o) => (le ? t.readUInt16LE(o) : t.readUInt16BE(o));
|
|
367
|
+
const u32 = (o) => (le ? t.readUInt32LE(o) : t.readUInt32BE(o));
|
|
368
|
+
try {
|
|
369
|
+
const ifd = u32(4);
|
|
370
|
+
const n = u16(ifd);
|
|
371
|
+
const names = { 0x010f: 'make', 0x0110: 'model', 0x0131: 'software', 0x0132: 'modified', 0x013b: 'artist' };
|
|
372
|
+
for (let i = 0; i < n; i++) {
|
|
373
|
+
const e = ifd + 2 + i * 12;
|
|
374
|
+
const tag = u16(e), type = u16(e + 2), count = u32(e + 4);
|
|
375
|
+
if (!names[tag] || type !== 2)
|
|
376
|
+
continue;
|
|
377
|
+
const off = count > 4 ? u32(e + 8) : e + 8;
|
|
378
|
+
out[names[tag]] = t.subarray(off, off + count).toString('latin1').replace(/\0+$/, '').trim();
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
catch { }
|
|
382
|
+
return out;
|
|
383
|
+
}
|
|
384
|
+
function xmpFields(x) {
|
|
385
|
+
const out = {};
|
|
386
|
+
const get = (k) => new RegExp(`${k}(?:="([^"]*)"|>([^<]*)<)`).exec(x);
|
|
387
|
+
for (const [k, name] of [['xmp:CreatorTool', 'creator tool'], ['pdf:Producer', 'producer (xmp)'], ['xmp:CreateDate', 'created (xmp)'], ['xmp:ModifyDate', 'modified (xmp)'], ['photoshop:History', 'photoshop history']]) {
|
|
388
|
+
const m = get(k);
|
|
389
|
+
const v = (m?.[1] ?? m?.[2] ?? '').trim();
|
|
390
|
+
if (v)
|
|
391
|
+
out[name] = v;
|
|
392
|
+
}
|
|
393
|
+
const agents = [...x.matchAll(/stEvt:softwareAgent(?:="([^"]*)"|>([^<]*)<)/g)].map((m) => (m[1] ?? m[2] ?? '').trim()).filter(Boolean);
|
|
394
|
+
const saves = [...x.matchAll(/stEvt:action(?:="(saved|converted|derived|edited)"|>(saved|converted|derived|edited)<)/g)].length;
|
|
395
|
+
if (agents.length)
|
|
396
|
+
out['edit history'] = [...new Set(agents)].join('; ');
|
|
397
|
+
if (saves)
|
|
398
|
+
out['saves in history'] = String(saves);
|
|
399
|
+
return out;
|
|
400
|
+
}
|
|
401
|
+
function jpegMeta(b) {
|
|
402
|
+
const meta = {};
|
|
403
|
+
let i = 2;
|
|
404
|
+
while (i + 4 < b.length && b[i] === 0xff) {
|
|
405
|
+
const marker = b[i + 1];
|
|
406
|
+
if (marker === 0xda || marker === 0xd9)
|
|
407
|
+
break;
|
|
408
|
+
const len = b.readUInt16BE(i + 2);
|
|
409
|
+
const seg = b.subarray(i + 4, i + 2 + len);
|
|
410
|
+
if (marker === 0xe1) {
|
|
411
|
+
if (seg.subarray(0, 4).toString('latin1') === 'Exif')
|
|
412
|
+
Object.assign(meta, exifSoftware(seg));
|
|
413
|
+
else if (seg.toString('latin1', 0, 40).includes('ns.adobe.com/xap'))
|
|
414
|
+
Object.assign(meta, xmpFields(seg.toString('utf8')));
|
|
415
|
+
}
|
|
416
|
+
if (marker === 0xed && seg.toString('latin1', 0, 14).startsWith('Photoshop'))
|
|
417
|
+
meta['photoshop block'] = 'present';
|
|
418
|
+
i += 2 + len;
|
|
419
|
+
}
|
|
420
|
+
return { meta };
|
|
421
|
+
}
|
|
422
|
+
function pngMeta(b) {
|
|
423
|
+
const meta = {};
|
|
424
|
+
let i = 8;
|
|
425
|
+
while (i + 12 <= b.length) {
|
|
426
|
+
const len = b.readUInt32BE(i);
|
|
427
|
+
const type = b.toString('latin1', i + 4, i + 8);
|
|
428
|
+
const data = b.subarray(i + 8, i + 8 + len);
|
|
429
|
+
if (type === 'tEXt' || type === 'iTXt' || type === 'zTXt') {
|
|
430
|
+
const z = data.indexOf(0);
|
|
431
|
+
const k = data.toString('latin1', 0, z);
|
|
432
|
+
let v = '';
|
|
433
|
+
if (type === 'tEXt')
|
|
434
|
+
v = data.toString('latin1', z + 1);
|
|
435
|
+
else if (type === 'zTXt')
|
|
436
|
+
v = inflate(data.subarray(z + 2))?.toString('latin1') ?? '';
|
|
437
|
+
else {
|
|
438
|
+
const rest = data.subarray(z + 1);
|
|
439
|
+
const compressed = rest[0] === 1;
|
|
440
|
+
let p = 2;
|
|
441
|
+
p = rest.indexOf(0, p) + 1; // language tag
|
|
442
|
+
p = rest.indexOf(0, p) + 1; // translated keyword
|
|
443
|
+
v = compressed ? inflate(rest.subarray(p))?.toString('utf8') ?? '' : rest.subarray(p).toString('utf8');
|
|
444
|
+
}
|
|
445
|
+
if (k === 'XML:com.adobe.xmp')
|
|
446
|
+
Object.assign(meta, xmpFields(v));
|
|
447
|
+
else if (/^(Software|Creation Time|Author|Comment|Title|Source)$/i.test(k))
|
|
448
|
+
meta[k.toLowerCase()] = v.slice(0, 200).trim();
|
|
449
|
+
}
|
|
450
|
+
if (type === 'IEND')
|
|
451
|
+
break;
|
|
452
|
+
i += 12 + len;
|
|
453
|
+
}
|
|
454
|
+
return { meta };
|
|
455
|
+
}
|
|
456
|
+
/* ---------- what the traces mean ---------- */
|
|
457
|
+
const ONLINE_EDITORS = /ilovepdf|smallpdf|sejda|pdfescape|pdf ?candy|pdffiller|docfly|pdf2go|soda ?pdf|xodo|pdf24|hipdf|pdfzorro|online2pdf|lightpdf|pdfsimpli/i;
|
|
458
|
+
const DESKTOP_EDITORS = /pdf-xchange editor|foxit (pdf )?editor|phantompdf|nitro|pdfelement|wondershare|master pdf editor|pdf studio|inkscape|libreoffice draw|qoppa|able2extract|acrobat (pro|dc)|adobe acrobat(?! distiller)/i;
|
|
459
|
+
const IMAGE_EDITORS = /photoshop|gimp|canva|illustrator|picsart|snapseed|lightroom|pixlr|paint\.net|fotor|affinity|photopea|corel/i;
|
|
460
|
+
const WORD_PROCESSORS = /microsoft.{0,10}word|microsoft.{0,10}excel|google docs|libreoffice writer|openoffice|pages|wps (writer|office)/i;
|
|
461
|
+
function editorFlag(label, v, flags) {
|
|
462
|
+
if (ONLINE_EDITORS.test(v))
|
|
463
|
+
flags.push([`${label} is an online PDF editor (${v}): the file went through an editing site`, 35]);
|
|
464
|
+
else if (IMAGE_EDITORS.test(v))
|
|
465
|
+
flags.push([`${label} is an image editor (${v})`, 35]);
|
|
466
|
+
else if (DESKTOP_EDITORS.test(v))
|
|
467
|
+
flags.push([`${label} is a PDF editor (${v}): the file was opened and saved in an editor`, 25]);
|
|
468
|
+
else if (WORD_PROCESSORS.test(v))
|
|
469
|
+
flags.push([`${label} is a word processor (${v}): normal for a small business invoice, unusual for a bank statement or bank receipt`, 12]);
|
|
470
|
+
}
|
|
471
|
+
function textFindings(text) {
|
|
472
|
+
const ibans = new Map();
|
|
473
|
+
for (const m of text.toUpperCase().matchAll(/\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]{4}){2,7}(?:[ ]?[A-Z0-9]{1,4})?\b/g)) {
|
|
474
|
+
const c = checkIban(m[0]);
|
|
475
|
+
if (!c.iban || ibans.has(c.iban))
|
|
476
|
+
continue;
|
|
477
|
+
// Strings that only look like IBANs (no known country length) are left out.
|
|
478
|
+
if (!c.valid && !c.countryName)
|
|
479
|
+
continue;
|
|
480
|
+
ibans.set(c.iban, { iban: c.formatted ?? c.iban, valid: c.valid, country: c.countryName, problems: c.problems });
|
|
481
|
+
}
|
|
482
|
+
const domains = new Set();
|
|
483
|
+
for (const m of text.toLowerCase().matchAll(/\b(?:https?:\/\/)?(?:www\.)?([a-z0-9-]+(?:\.[a-z0-9-]+)*\.(?:com|net|org|io|co|uk|de|fr|nl|es|it|eu|info|biz|top|xyz|online|site|app|me|us|ca|au|in|id|sg|my|ph|ch|be|at|pl|ru|br|mx|live|shop|store|bank))\b/g))
|
|
484
|
+
domains.add(m[1]);
|
|
485
|
+
for (const m of text.toLowerCase().matchAll(/[a-z0-9._%+-]+@([a-z0-9-]+(?:\.[a-z0-9-]+)+)/g))
|
|
486
|
+
domains.add(m[1]);
|
|
487
|
+
return { ibans: [...ibans.values()].slice(0, 20), domains: [...domains].slice(0, 20) };
|
|
488
|
+
}
|
|
489
|
+
/** Transcribe the text in an image with a free AI key. Returns null when no key is set or the call fails. */
|
|
490
|
+
async function ocr(ctx, img, mime, provenance) {
|
|
491
|
+
// Free vision models, fastest first. (Mistral's vision models need a paid plan.)
|
|
492
|
+
const providers = [
|
|
493
|
+
{ name: 'openrouter', env: 'OPENROUTER_API_KEY', url: 'https://openrouter.ai/api/v1/chat/completions', model: process.env.OCULON_OCR_OPENROUTER_MODEL || 'nvidia/nemotron-3.5-super-vl:free' },
|
|
494
|
+
{ name: 'gemini', env: 'GEMINI_API_KEY', url: 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions', model: process.env.OCULON_OCR_GEMINI_MODEL || 'gemini-flash-latest' },
|
|
495
|
+
];
|
|
496
|
+
for (const p of providers) {
|
|
497
|
+
const k = key(p.env);
|
|
498
|
+
if (!k)
|
|
499
|
+
continue;
|
|
500
|
+
const body = JSON.stringify({
|
|
501
|
+
model: p.model,
|
|
502
|
+
temperature: 0,
|
|
503
|
+
max_tokens: 3000,
|
|
504
|
+
messages: [{ role: 'user', content: [
|
|
505
|
+
{ type: 'text', text: 'Transcribe all text in this image exactly as written, line by line. Output only the text, nothing else. If there is no text, output nothing.' },
|
|
506
|
+
{ type: 'image_url', image_url: { url: `data:${mime};base64,${img.toString('base64')}` } },
|
|
507
|
+
] }],
|
|
508
|
+
});
|
|
509
|
+
const r = await ctx.http.postBytes(p.url, Buffer.from(body), { source: `ocr-${p.name}`, headers: { authorization: `Bearer ${k}`, 'content-type': 'application/json' }, timeoutMs: 45_000, retries: 0 });
|
|
510
|
+
provenance.push({ ...r.prov, note: `${r.data ? 'text read from the image' : 'could not read the text'} (${p.model})${r.prov.note ? `: ${r.prov.note}` : ''}` });
|
|
511
|
+
if (!r.data)
|
|
512
|
+
continue;
|
|
513
|
+
try {
|
|
514
|
+
const j = JSON.parse(r.data.toString('utf8'));
|
|
515
|
+
const t = j.choices?.[0]?.message?.content?.trim();
|
|
516
|
+
if (t !== undefined)
|
|
517
|
+
return t;
|
|
518
|
+
}
|
|
519
|
+
catch { }
|
|
520
|
+
}
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
523
|
+
/** Check one document. `name` is only used for display. */
|
|
524
|
+
export async function docCheck(ctx, file, name = 'document') {
|
|
525
|
+
if (!file.length)
|
|
526
|
+
throw new Error('the file is empty');
|
|
527
|
+
if (file.length > DOC_MAX_BYTES)
|
|
528
|
+
throw new Error(`the file is larger than ${DOC_MAX_BYTES / 1024 / 1024} MB`);
|
|
529
|
+
const now = ctx.now();
|
|
530
|
+
const head = file.subarray(0, 1024).toString('latin1');
|
|
531
|
+
const type = head.includes('%PDF-') ? 'pdf' : file[0] === 0xff && file[1] === 0xd8 ? 'jpeg' : file.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) ? 'png' : null;
|
|
532
|
+
if (!type)
|
|
533
|
+
throw new Error('not a PDF, JPEG or PNG file (expected a document, a screenshot or a photo of one)');
|
|
534
|
+
const flags = [];
|
|
535
|
+
const notes = [];
|
|
536
|
+
const metadata = {};
|
|
537
|
+
const provenance = [{ source: 'oculon-doc', url: 'local', status: 'LIVE', fetchedAt: now.toISOString(), note: 'read from the file itself, not uploaded anywhere else' }];
|
|
538
|
+
let revisions = null, signed = false, fonts = [], text = '', from = 'none';
|
|
539
|
+
let danger = false;
|
|
540
|
+
if (type === 'pdf') {
|
|
541
|
+
const raw = file.toString('latin1');
|
|
542
|
+
const objs = pdfObjects(file);
|
|
543
|
+
const all = objs.map((o) => o.dict).join('\n');
|
|
544
|
+
// Metadata: the Info dictionary and XMP.
|
|
545
|
+
// After an incremental update the newest Info dictionary (named by the last trailer) is the one that counts.
|
|
546
|
+
const infos = objs.filter((o) => /\/(Producer|CreationDate|Creator)\s*[(<]/.test(o.dict));
|
|
547
|
+
const infoRef = [...raw.matchAll(/\/Info\s+(\d+)\s+\d+\s+R/g)].pop()?.[1];
|
|
548
|
+
const info = (infoRef ? infos.filter((o) => o.num === Number(infoRef)).pop() : undefined)?.dict ?? infos[infos.length - 1]?.dict ?? '';
|
|
549
|
+
const producers = [...new Set(infos.map((o) => dictString(o.dict, 'Producer')).filter((p) => Boolean(p)))];
|
|
550
|
+
if (producers.length > 1)
|
|
551
|
+
flags.push([`made by one program and saved again by another (${producers.slice(0, 3).join(' -> ')})`, 20]);
|
|
552
|
+
for (const [k, label] of [['Producer', 'producer'], ['Creator', 'creator'], ['CreationDate', 'created'], ['ModDate', 'modified'], ['Author', 'author'], ['Title', 'title']]) {
|
|
553
|
+
const v = dictString(info, k);
|
|
554
|
+
if (v)
|
|
555
|
+
metadata[label] = v.slice(0, 200);
|
|
556
|
+
}
|
|
557
|
+
const xmp = objs.map((o) => o.stream?.toString('utf8') ?? '').find((s) => s.includes('<x:xmpmeta') || s.includes('ns.adobe.com/xap'));
|
|
558
|
+
if (xmp)
|
|
559
|
+
Object.assign(metadata, xmpFields(xmp));
|
|
560
|
+
for (const k of ['producer', 'creator', 'creator tool', 'producer (xmp)'])
|
|
561
|
+
if (metadata[k])
|
|
562
|
+
editorFlag(k[0].toUpperCase() + k.slice(1), metadata[k], flags);
|
|
563
|
+
if (metadata['edit history']) {
|
|
564
|
+
const agents = metadata['edit history'].split('; ');
|
|
565
|
+
if (agents.length > 1)
|
|
566
|
+
flags.push([`the edit history lists ${agents.length} programs: ${agents.join(', ')}`, 15]);
|
|
567
|
+
}
|
|
568
|
+
const c = pdfDate(metadata.created ?? null), mo = pdfDate(metadata.modified ?? null);
|
|
569
|
+
const fmt = (t) => `${new Date(t).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
|
|
570
|
+
if (c)
|
|
571
|
+
metadata.created = fmt(c);
|
|
572
|
+
if (mo)
|
|
573
|
+
metadata.modified = fmt(mo);
|
|
574
|
+
if (c && mo && mo - c > 120_000) {
|
|
575
|
+
const days = (mo - c) / 86_400_000;
|
|
576
|
+
flags.push([`modified ${days >= 1 ? `${Math.round(days)} day${Math.round(days) === 1 ? '' : 's'}` : `${Math.round((mo - c) / 60_000)} minutes`} after it was created`, days >= 1 ? 20 : 12]);
|
|
577
|
+
}
|
|
578
|
+
if (c && c > now.getTime() + 86_400_000)
|
|
579
|
+
flags.push(['the creation date is in the future', 20]);
|
|
580
|
+
if (!Object.keys(metadata).length)
|
|
581
|
+
notes.push('The file has no metadata. Some generators leave it out; editors and scrubbing tools also remove it.');
|
|
582
|
+
// Saves: each incremental update adds a %%EOF. Signatures add one per signature.
|
|
583
|
+
signed = /\/Type\s*\/Sig\b|\/ByteRange\s*\[/.test(all);
|
|
584
|
+
revisions = Math.max(1, (raw.match(/%%EOF/g) ?? []).length);
|
|
585
|
+
if (revisions > 1) {
|
|
586
|
+
if (signed)
|
|
587
|
+
notes.push(`Saved ${revisions} times; the file is digitally signed, and signing adds a save. Check the signature in a PDF reader.`);
|
|
588
|
+
else
|
|
589
|
+
flags.push([`saved ${revisions} times: content was added or changed after the first version`, revisions > 2 ? 25 : 18]);
|
|
590
|
+
}
|
|
591
|
+
if (signed)
|
|
592
|
+
notes.push('The file carries a digital signature. A valid signature from the issuer is the strongest proof it was not changed; open it in a PDF reader to see whether the signature is valid.');
|
|
593
|
+
// Fonts: the same font embedded twice under different subset tags usually means a second program added text.
|
|
594
|
+
const baseFonts = [...new Set([...all.matchAll(/\/BaseFont\s*\/([^\s/<>\[\]()]+)/g)].map((m) => m[1]))];
|
|
595
|
+
fonts = [...new Set(baseFonts.map((f) => f.replace(/^[A-Z]{6}\+/, '')))].slice(0, 30);
|
|
596
|
+
const subsets = new Map();
|
|
597
|
+
for (const f of baseFonts) {
|
|
598
|
+
const m = /^([A-Z]{6})\+(.+)$/.exec(f);
|
|
599
|
+
const nameOnly = m ? m[2] : f;
|
|
600
|
+
const s = subsets.get(nameOnly) ?? new Set();
|
|
601
|
+
s.add(m ? m[1] : '(full)');
|
|
602
|
+
subsets.set(nameOnly, s);
|
|
603
|
+
}
|
|
604
|
+
const twice = [...subsets].filter(([, s]) => s.size > 1).map(([n]) => n);
|
|
605
|
+
if (twice.length)
|
|
606
|
+
flags.push([`font${twice.length > 1 ? 's' : ''} embedded more than once (${twice.slice(0, 3).join(', ')}): typical when a second program adds or replaces text`, 25]);
|
|
607
|
+
const families = new Set(fonts.map((f) => f.split(/[-,]/)[0].replace(/(MT|PS|Std)$/, '').toLowerCase()));
|
|
608
|
+
const pages = objs.filter((o) => /\/Type\s*\/Page\b(?!s)/.test(o.dict)).length;
|
|
609
|
+
if (pages && pages <= 2 && families.size >= 6)
|
|
610
|
+
flags.push([`${families.size} different font families on ${pages} page${pages > 1 ? 's' : ''}`, 10]);
|
|
611
|
+
// Annotations drawn on top of the page.
|
|
612
|
+
const ann = (all.match(/\/Subtype\s*\/(FreeText|Stamp|Square|Ink|Redact)\b/g) ?? []).length;
|
|
613
|
+
if (ann)
|
|
614
|
+
flags.push([`${ann} annotation${ann > 1 ? 's' : ''} (text boxes, stamps or shapes) placed on top of the page`, 20]);
|
|
615
|
+
// Dangerous parts.
|
|
616
|
+
const bad = [];
|
|
617
|
+
if (/\/JavaScript\b|\/JS\s*[(<\d]/.test(all))
|
|
618
|
+
bad.push('JavaScript');
|
|
619
|
+
if (/\/Launch\b/.test(all))
|
|
620
|
+
bad.push('a launch action that can start a program');
|
|
621
|
+
if (/\/EmbeddedFile\b/.test(all))
|
|
622
|
+
bad.push('embedded files');
|
|
623
|
+
if (/\/XFA\b/.test(all))
|
|
624
|
+
bad.push('an XFA form');
|
|
625
|
+
if (/\/RichMedia\b/.test(all))
|
|
626
|
+
bad.push('rich media');
|
|
627
|
+
if (bad.length) {
|
|
628
|
+
danger = bad.some((b) => b !== 'an XFA form');
|
|
629
|
+
flags.push([`contains ${bad.join(', ')}: invoices and statements do not need this. Do not open it with JavaScript enabled`, danger ? 60 : 10]);
|
|
630
|
+
}
|
|
631
|
+
// Text layer and white boxes.
|
|
632
|
+
const t = pdfText(objs);
|
|
633
|
+
text = t.text.trim();
|
|
634
|
+
if (text)
|
|
635
|
+
from = 'text layer';
|
|
636
|
+
if (t.whiteBoxes >= 1)
|
|
637
|
+
flags.push([`${t.whiteBoxes} white box${t.whiteBoxes > 1 ? 'es' : ''} drawn on the page: sometimes used to cover the original text before typing over it`, t.whiteBoxes >= 3 ? 15 : 8]);
|
|
638
|
+
// A scanned PDF has no text layer: read its largest image instead.
|
|
639
|
+
if (!text) {
|
|
640
|
+
const img = objs.filter((o) => /\/Subtype\s*\/Image/.test(o.dict) && /\/DCTDecode/.test(o.dict) && o.raw).sort((a, b) => b.raw.length - a.raw.length)[0];
|
|
641
|
+
if (img?.raw && img.raw.length < 4_000_000) {
|
|
642
|
+
const o = await ocr(ctx, img.raw, 'image/jpeg', provenance);
|
|
643
|
+
if (o) {
|
|
644
|
+
text = o;
|
|
645
|
+
from = 'ocr';
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
if (!text)
|
|
649
|
+
notes.push('No text layer: this looks like a scan or a picture inside a PDF. The numbers in it were not checked.');
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
else {
|
|
653
|
+
const { meta } = type === 'jpeg' ? jpegMeta(file) : pngMeta(file);
|
|
654
|
+
Object.assign(metadata, meta);
|
|
655
|
+
for (const k of ['software', 'creator tool'])
|
|
656
|
+
if (metadata[k])
|
|
657
|
+
editorFlag(k === 'software' ? 'Software' : 'Creator tool', metadata[k], flags);
|
|
658
|
+
if (metadata['photoshop block'])
|
|
659
|
+
flags.push(['the image carries a Photoshop data block', 20]);
|
|
660
|
+
if (metadata['edit history'])
|
|
661
|
+
flags.push([`the edit history lists: ${metadata['edit history']}`, 15]);
|
|
662
|
+
if (!Object.keys(metadata).length)
|
|
663
|
+
notes.push(type === 'png' ? 'No metadata: normal for a screenshot. A screenshot can be edited without leaving traces, so check the numbers in it with the sender through a channel you already trust.' : 'No metadata: it was removed, or the app that made the image does not write any.');
|
|
664
|
+
if (file.length < 4_000_000) {
|
|
665
|
+
const o = await ocr(ctx, file, type === 'jpeg' ? 'image/jpeg' : 'image/png', provenance);
|
|
666
|
+
if (o) {
|
|
667
|
+
text = o;
|
|
668
|
+
from = 'ocr';
|
|
669
|
+
}
|
|
670
|
+
else if (!provenance.some((p) => p.source.startsWith('ocr-')))
|
|
671
|
+
notes.push('Text in the image was not read: set OPENROUTER_API_KEY or GEMINI_API_KEY (both have free tiers) to check account numbers in screenshots.');
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
// Say plainly when the picture left this machine to be read.
|
|
675
|
+
const sent = provenance.filter((p) => p.source.startsWith('ocr-')).map((p) => p.source.slice(4));
|
|
676
|
+
if (sent.length)
|
|
677
|
+
provenance[0].note = `file read here; the image was sent to ${[...new Set(sent)].join(' and ')} only to read its text`;
|
|
678
|
+
const found = textFindings(text);
|
|
679
|
+
for (const ib of found.ibans)
|
|
680
|
+
if (!ib.valid)
|
|
681
|
+
flags.push([`IBAN ${ib.iban} in the document is not valid (${ib.problems[0] ?? 'checksum fails'}): a typo, or a number that was changed`, 35]);
|
|
682
|
+
if (found.ibans.some((i) => i.valid))
|
|
683
|
+
notes.push('Valid IBANs only mean the number is well formed. Confirm the account with the company on a phone number you already have, never one from this document.');
|
|
684
|
+
const risk = Math.min(100, flags.reduce((s, [, w]) => s + w, 0));
|
|
685
|
+
const verdict = danger ? 'dangerous file' : risk >= 50 ? 'likely edited' : risk >= 20 ? 'signs of editing' : 'no signs of editing found';
|
|
686
|
+
if (verdict === 'no signs of editing found')
|
|
687
|
+
notes.push('No traces of editing were found. That is not proof the document is genuine: a careful forger, or a document made from scratch, leaves none.');
|
|
688
|
+
const advice = verdict === 'dangerous file'
|
|
689
|
+
? ['Do not open this file in a PDF reader with JavaScript on.', 'Delete it unless you expected exactly this file from someone you know.']
|
|
690
|
+
: verdict === 'no signs of editing found'
|
|
691
|
+
? ['Before paying, confirm the bank details with the sender on a number or address you already had.']
|
|
692
|
+
: ['Do not pay or act on this document yet.', 'Ask the issuer for the original, or confirm the details with them on a phone number you already had.', 'Banks can confirm whether a statement or a transfer is real; ask yours.'];
|
|
693
|
+
const result = {
|
|
694
|
+
name: name.slice(0, 120),
|
|
695
|
+
type,
|
|
696
|
+
bytes: file.length,
|
|
697
|
+
sha256: createHash('sha256').update(file).digest('hex'),
|
|
698
|
+
verdict,
|
|
699
|
+
risk,
|
|
700
|
+
flags: flags.sort((a, b) => b[1] - a[1]).map(([f]) => f),
|
|
701
|
+
notes,
|
|
702
|
+
metadata,
|
|
703
|
+
revisions,
|
|
704
|
+
signed,
|
|
705
|
+
fonts,
|
|
706
|
+
text: { chars: text.length, excerpt: text.slice(0, 600), from },
|
|
707
|
+
ibans: found.ibans,
|
|
708
|
+
domains: found.domains,
|
|
709
|
+
advice,
|
|
710
|
+
};
|
|
711
|
+
const signals = risk >= 50 || danger
|
|
712
|
+
? [{ id: signalId('doc', result.sha256), module: 'doc', title: `Document ${result.name}: ${verdict}`, score: risk, entity: `doc:${result.sha256.slice(0, 16)}`, evidence: result.flags.slice(0, 4).map((t) => ({ source: 'oculon-doc', text: t })), createdAt: now.toISOString() }]
|
|
713
|
+
: [];
|
|
714
|
+
return { module: 'doc', input: result.name, generatedAt: now.toISOString(), result, signals, provenance };
|
|
715
|
+
}
|