counterlure-cli 0.0.0-stage → 0.6.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 +201 -0
- package/NOTICE +6 -0
- package/README.md +433 -2
- package/SECURITY.md +30 -0
- package/bin/counterlure.js +1210 -0
- package/lib/crop.js +54 -0
- package/lib/faceprint.js +166 -0
- package/lib/inspect.js +226 -0
- package/lib/models.js +189 -0
- package/lib/net.js +166 -0
- package/lib/pow.js +43 -0
- package/lib/proto.js +106 -0
- package/lib/protocol-id.js +3 -0
- package/lib/route.js +63 -0
- package/lib/server-key.js +20 -0
- package/lib/sharp.js +14 -0
- package/lib/term.js +20 -0
- package/package.json +14 -4
package/lib/crop.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// The only image material a report ever sends: one face, cropped and re-encoded on this computer.
|
|
2
|
+
//
|
|
3
|
+
// Minimisation is the point. The source photo can carry a lot that is no business of ours and can
|
|
4
|
+
// burn the reporter: GPS and device serials in EXIF, a thumbnail of the uncropped original, other
|
|
5
|
+
// people in the frame, the room, a screen, a reflection. None of that is sent. What leaves is:
|
|
6
|
+
//
|
|
7
|
+
// - the chosen face plus a margin, shrunk if needed so no other detected face is in frame
|
|
8
|
+
// - decoded to raw pixels and encoded fresh as a baseline JPEG, so no metadata, colour profile
|
|
9
|
+
// or embedded thumbnail from the original can survive (there is nothing to strip; it is never
|
|
10
|
+
// copied in the first place)
|
|
11
|
+
// - scaled to fit MAX_SIDE, and compressed until it fits the fixed request envelope
|
|
12
|
+
//
|
|
13
|
+
// Coordinates are in the EXIF-rotated frame, the same frame faceprint.js detects faces in.
|
|
14
|
+
import sharp from './sharp.js';
|
|
15
|
+
|
|
16
|
+
export const MAX_SIDE = 480;
|
|
17
|
+
export const MAX_B64 = 190_000; // the server takes 200,000; the request envelope is sized for this
|
|
18
|
+
const MARGIN = 0.35;
|
|
19
|
+
const QUALITIES = [85, 78, 70, 60, 50];
|
|
20
|
+
|
|
21
|
+
export function cropRegion(face, others, w, h) {
|
|
22
|
+
const cx = face.x + face.w / 2, cy = face.y + face.h / 2;
|
|
23
|
+
const inside = (r, o) => {
|
|
24
|
+
const ox = o.x + o.w / 2, oy = o.y + o.h / 2;
|
|
25
|
+
return ox >= r.left && ox < r.left + r.width && oy >= r.top && oy < r.top + r.height;
|
|
26
|
+
};
|
|
27
|
+
for (let step = 7; step >= 0; step--) { // margin 0.35, 0.30 ... 0: integer steps, no float drift
|
|
28
|
+
const m = (MARGIN * step) / 7;
|
|
29
|
+
const side = Math.max(face.w, face.h) * (1 + 2 * m);
|
|
30
|
+
const left = Math.max(0, Math.floor(cx - side / 2)), top = Math.max(0, Math.floor(cy - side / 2));
|
|
31
|
+
const r = {
|
|
32
|
+
left, top,
|
|
33
|
+
width: Math.max(1, Math.min(w, Math.ceil(cx + side / 2)) - left),
|
|
34
|
+
height: Math.max(1, Math.min(h, Math.ceil(cy + side / 2)) - top),
|
|
35
|
+
};
|
|
36
|
+
if (step === 0 || !others.some((o) => inside(r, o))) return r;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// face and others are { x, y, w, h } boxes from faceprints(). Returns { jpeg, width, height }.
|
|
41
|
+
export async function faceCrop(input, face, others = []) {
|
|
42
|
+
const { data, info } = await sharp(input, { limitInputPixels: 50e6 }).rotate().removeAlpha().toColourspace('srgb')
|
|
43
|
+
.raw().toBuffer({ resolveWithObject: true });
|
|
44
|
+
const r = cropRegion(face, others, info.width, info.height);
|
|
45
|
+
const raw = { raw: { width: info.width, height: info.height, channels: info.channels } };
|
|
46
|
+
const pixels = await sharp(data, raw).extract(r)
|
|
47
|
+
.resize({ width: MAX_SIDE, height: MAX_SIDE, fit: 'inside' })
|
|
48
|
+
.raw().toBuffer({ resolveWithObject: true });
|
|
49
|
+
for (const quality of QUALITIES) {
|
|
50
|
+
const jpeg = await sharp(pixels.data, { raw: pixels.info }).jpeg({ quality, progressive: false, chromaSubsampling: '4:2:0' }).toBuffer();
|
|
51
|
+
if (Math.ceil(jpeg.length / 3) * 4 <= MAX_B64) return { jpeg, width: pixels.info.width, height: pixels.info.height };
|
|
52
|
+
}
|
|
53
|
+
throw new Error('The face crop would not compress small enough to send.');
|
|
54
|
+
}
|
package/lib/faceprint.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// Face fingerprints, computed entirely on this computer.
|
|
2
|
+
//
|
|
3
|
+
// image --sharp--> RGB pixels --YuNet--> face boxes + 5 landmarks
|
|
4
|
+
// --similarity transform--> 112x112 aligned face --SFace--> 128 numbers
|
|
5
|
+
//
|
|
6
|
+
// The 128 numbers (an "embedding") are scaled to length 1, so two faces compare by a
|
|
7
|
+
// dot product (cosine similarity). OpenCV's published threshold for SFace is 0.363.
|
|
8
|
+
// The Counterlure server runs this same file, so both sides produce identical numbers.
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import sharp from './sharp.js';
|
|
11
|
+
import ort from 'onnxruntime-node';
|
|
12
|
+
|
|
13
|
+
export const MODEL_VERSION = 'yunet2023mar+sface2021dec/v1';
|
|
14
|
+
export const MATCH_THRESHOLD = 0.363;
|
|
15
|
+
export const STRONG_THRESHOLD = 0.5;
|
|
16
|
+
|
|
17
|
+
export const MODELS = {
|
|
18
|
+
detector: {
|
|
19
|
+
file: 'face_detection_yunet_2023mar.onnx',
|
|
20
|
+
url: 'https://github.com/opencv/opencv_zoo/raw/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx',
|
|
21
|
+
sha256: '8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4',
|
|
22
|
+
bytes: 232589,
|
|
23
|
+
},
|
|
24
|
+
recognizer: {
|
|
25
|
+
file: 'face_recognition_sface_2021dec.onnx',
|
|
26
|
+
url: 'https://github.com/opencv/opencv_zoo/raw/main/models/face_recognition_sface/face_recognition_sface_2021dec.onnx',
|
|
27
|
+
sha256: '0ba9fbfa01b5270c96627c4ef784da859931e02f04419c829e83484087c34e79',
|
|
28
|
+
bytes: 38696353,
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const SIZE = 640; // YuNet's fixed input
|
|
33
|
+
const SCORE_MIN = 0.6; // YuNet scores tilted faces 0.85-0.9; recognition, not detection, decides a match
|
|
34
|
+
const NMS_IOU = 0.3;
|
|
35
|
+
const MAX_FACES = 5;
|
|
36
|
+
const MIN_FACE_PX = 24; // below this a face is too blurry to compare at all; the CLI warns under 64
|
|
37
|
+
// Where SFace expects the eyes, nose and mouth corners in its 112x112 input (from OpenCV).
|
|
38
|
+
const TEMPLATE = [[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], [41.5493, 92.3655], [70.7299, 92.2041]];
|
|
39
|
+
|
|
40
|
+
const sessions = new Map();
|
|
41
|
+
async function session(dir, which) {
|
|
42
|
+
const key = `${dir}|${which}`;
|
|
43
|
+
if (!sessions.has(key)) {
|
|
44
|
+
const opts = { executionProviders: ['cpu'], graphOptimizationLevel: 'all', intraOpNumThreads: 1, logSeverityLevel: 3 };
|
|
45
|
+
sessions.set(key, ort.InferenceSession.create(path.join(dir, MODELS[which].file), opts));
|
|
46
|
+
}
|
|
47
|
+
return sessions.get(key);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Decode a JPEG, PNG or WebP (see sharp.js), honour EXIF rotation, drop alpha. Metadata never leaves sharp.
|
|
51
|
+
async function decode(input) {
|
|
52
|
+
const { data, info } = await sharp(input, { limitInputPixels: 50e6 }).rotate().removeAlpha().toColourspace('srgb')
|
|
53
|
+
.raw().toBuffer({ resolveWithObject: true });
|
|
54
|
+
return { px: data, w: info.width, h: info.height, c: info.channels };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function iou(a, b) {
|
|
58
|
+
const x1 = Math.max(a.x, b.x), y1 = Math.max(a.y, b.y);
|
|
59
|
+
const x2 = Math.min(a.x + a.w, b.x + b.w), y2 = Math.min(a.y + a.h, b.y + b.h);
|
|
60
|
+
const inter = Math.max(0, x2 - x1) * Math.max(0, y2 - y1);
|
|
61
|
+
return inter / (a.w * a.h + b.w * b.h - inter || 1);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function detect(dir, img) {
|
|
65
|
+
const scale = Math.min(SIZE / img.w, SIZE / img.h);
|
|
66
|
+
const w = Math.max(1, Math.round(img.w * scale)), h = Math.max(1, Math.round(img.h * scale));
|
|
67
|
+
const small = await sharp(img.px, { raw: { width: img.w, height: img.h, channels: img.c } })
|
|
68
|
+
.resize(w, h, { kernel: 'linear' }).raw().toBuffer();
|
|
69
|
+
// YuNet takes BGR, 0-255, NCHW; the unused area right and below stays black.
|
|
70
|
+
const plane = SIZE * SIZE, input = new Float32Array(3 * plane);
|
|
71
|
+
for (let y = 0; y < h; y++) {
|
|
72
|
+
for (let x = 0; x < w; x++) {
|
|
73
|
+
const s = (y * w + x) * 3, d = y * SIZE + x;
|
|
74
|
+
input[d] = small[s + 2]; input[plane + d] = small[s + 1]; input[2 * plane + d] = small[s];
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const sess = await session(dir, 'detector');
|
|
78
|
+
const out = await sess.run({ input: new ort.Tensor('float32', input, [1, 3, SIZE, SIZE]) });
|
|
79
|
+
|
|
80
|
+
const found = [];
|
|
81
|
+
for (const stride of [8, 16, 32]) {
|
|
82
|
+
const cls = out[`cls_${stride}`].data, obj = out[`obj_${stride}`].data;
|
|
83
|
+
const box = out[`bbox_${stride}`].data, kps = out[`kps_${stride}`].data;
|
|
84
|
+
const cols = SIZE / stride, rows = SIZE / stride;
|
|
85
|
+
for (let r = 0; r < rows; r++) {
|
|
86
|
+
for (let c = 0; c < cols; c++) {
|
|
87
|
+
const i = r * cols + c;
|
|
88
|
+
const score = Math.sqrt(Math.min(1, Math.max(0, cls[i])) * Math.min(1, Math.max(0, obj[i])));
|
|
89
|
+
if (score < SCORE_MIN) continue;
|
|
90
|
+
const cx = (c + box[i * 4]) * stride, cy = (r + box[i * 4 + 1]) * stride;
|
|
91
|
+
const bw = Math.exp(box[i * 4 + 2]) * stride, bh = Math.exp(box[i * 4 + 3]) * stride;
|
|
92
|
+
const marks = [];
|
|
93
|
+
for (let k = 0; k < 5; k++) marks.push([(kps[i * 10 + 2 * k] + c) * stride / scale, (kps[i * 10 + 2 * k + 1] + r) * stride / scale]);
|
|
94
|
+
found.push({ x: (cx - bw / 2) / scale, y: (cy - bh / 2) / scale, w: bw / scale, h: bh / scale, score, marks });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
found.sort((a, b) => b.score - a.score);
|
|
99
|
+
const keep = [];
|
|
100
|
+
for (const f of found) if (keep.every((k) => iou(k, f) <= NMS_IOU)) keep.push(f);
|
|
101
|
+
return keep;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Least-squares similarity transform (rotation, uniform scale, shift) taking src points onto dst.
|
|
105
|
+
// x' = a*x - b*y + tx, y' = b*x + a*y + ty
|
|
106
|
+
export function similarity(src, dst) {
|
|
107
|
+
const n = src.length;
|
|
108
|
+
const ms = [0, 0], md = [0, 0];
|
|
109
|
+
for (let i = 0; i < n; i++) { ms[0] += src[i][0] / n; ms[1] += src[i][1] / n; md[0] += dst[i][0] / n; md[1] += dst[i][1] / n; }
|
|
110
|
+
let num1 = 0, num2 = 0, den = 0;
|
|
111
|
+
for (let i = 0; i < n; i++) {
|
|
112
|
+
const xs = src[i][0] - ms[0], ys = src[i][1] - ms[1], xd = dst[i][0] - md[0], yd = dst[i][1] - md[1];
|
|
113
|
+
num1 += xs * xd + ys * yd; num2 += xs * yd - ys * xd; den += xs * xs + ys * ys;
|
|
114
|
+
}
|
|
115
|
+
const a = num1 / den, b = num2 / den;
|
|
116
|
+
return { a, b, tx: md[0] - (a * ms[0] - b * ms[1]), ty: md[1] - (b * ms[0] + a * ms[1]) };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Warp the face into SFace's 112x112 frame with bilinear sampling, as RGB, 0-255, NCHW.
|
|
120
|
+
function align(img, marks) {
|
|
121
|
+
const { a, b, tx, ty } = similarity(marks, TEMPLATE);
|
|
122
|
+
const det = a * a + b * b; // invert x' = M x + t
|
|
123
|
+
const plane = 112 * 112, out = new Float32Array(3 * plane);
|
|
124
|
+
for (let v = 0; v < 112; v++) {
|
|
125
|
+
for (let u = 0; u < 112; u++) {
|
|
126
|
+
const du = u - tx, dv = v - ty;
|
|
127
|
+
const x = (a * du + b * dv) / det, y = (-b * du + a * dv) / det;
|
|
128
|
+
const x0 = Math.floor(x), y0 = Math.floor(y), fx = x - x0, fy = y - y0;
|
|
129
|
+
for (let ch = 0; ch < 3; ch++) {
|
|
130
|
+
const p = (xx, yy) => (xx < 0 || yy < 0 || xx >= img.w || yy >= img.h ? 0 : img.px[(yy * img.w + xx) * img.c + ch]);
|
|
131
|
+
const val = p(x0, y0) * (1 - fx) * (1 - fy) + p(x0 + 1, y0) * fx * (1 - fy) + p(x0, y0 + 1) * (1 - fx) * fy + p(x0 + 1, y0 + 1) * fx * fy;
|
|
132
|
+
out[ch * plane + v * 112 + u] = val;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function unit(v) {
|
|
140
|
+
let s = 0;
|
|
141
|
+
for (const x of v) s += x * x;
|
|
142
|
+
const n = Math.sqrt(s) || 1;
|
|
143
|
+
return Array.from(v, (x) => x / n);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export const cosine = (a, b) => a.reduce((s, x, i) => s + x * b[i], 0);
|
|
147
|
+
|
|
148
|
+
// Returns up to 5 faces, largest first: { box, score, embedding: number[128] }.
|
|
149
|
+
export async function faceprints(input, { modelsDir }) {
|
|
150
|
+
const img = await decode(input);
|
|
151
|
+
const all = (await detect(modelsDir, img)).filter((f) => f.w >= MIN_FACE_PX && f.h >= MIN_FACE_PX)
|
|
152
|
+
.sort((p, q) => q.w * q.h - p.w * p.h);
|
|
153
|
+
const faces = all.slice(0, MAX_FACES);
|
|
154
|
+
const rec = await session(modelsDir, 'recognizer');
|
|
155
|
+
const out = [];
|
|
156
|
+
for (const f of faces) {
|
|
157
|
+
const res = await rec.run({ [rec.inputNames[0]]: new ort.Tensor('float32', align(img, f.marks), [1, 3, 112, 112]) });
|
|
158
|
+
out.push({
|
|
159
|
+
box: { x: Math.round(f.x), y: Math.round(f.y), w: Math.round(f.w), h: Math.round(f.h) },
|
|
160
|
+
score: Math.round(f.score * 1000) / 1000,
|
|
161
|
+
embedding: unit(res[rec.outputNames[0]].data),
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
Object.defineProperty(out, 'skipped', { value: Math.max(0, all.length - MAX_FACES) });
|
|
165
|
+
return out;
|
|
166
|
+
}
|
package/lib/inspect.js
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// Static, offline inspection of a local repository before you open, install, build or run it.
|
|
2
|
+
// Reads files only: nothing is executed, nothing is sent anywhere, symlinks are never followed.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
const MAX_FILES = 5000;
|
|
7
|
+
const MAX_BYTES = 512 * 1024;
|
|
8
|
+
const SKIP_DIRS = new Set(['node_modules', '.venv', 'venv', '__pycache__', 'target', '.next', '.tox']);
|
|
9
|
+
const TEXT_EXT = /\.(?:[cm]?[jt]sx?|json|ya?ml|toml|py|sh|bash|zsh|ps1|psm1|bat|cmd|rb|md|txt|cfg|ini|rs|go|mk)$/i;
|
|
10
|
+
const CODE_EXT = /\.(?:[cm]?[jt]sx?|py|sh|bash|zsh|ps1|psm1|bat|cmd|rb)$/i;
|
|
11
|
+
const BINARY_EXT = /\.(?:exe|dll|dylib|so|node|wasm|msi|dmg|pkg|scr|bat|vbs|jar|lnk|appimage)$/i;
|
|
12
|
+
|
|
13
|
+
const EXEC = /(?:curl\s+|wget\s+|powershell|pwsh|cmd\.exe|\/bin\/sh|bash\s+-c|node\s+-e|python3?\s+-c|\beval\s*\(|new\s+Function\s*\(|child_process|Buffer\.from\s*\([^)]*base64|atob\s*\(|os\.system\s*\(|subprocess\.|Invoke-Expression|\biex\b)/i;
|
|
14
|
+
const PIPE_TO_SHELL = /(?:curl|wget|iwr|Invoke-WebRequest)\b[^\n|]*\|\s*(?:sudo\s+)?(?:sh|bash|zsh|iex|python3?|node)\b/i;
|
|
15
|
+
const LIFECYCLE = ['preinstall', 'install', 'postinstall', 'preprepare', 'prepare', 'postprepare', 'prepublish', 'prepack', 'postpack'];
|
|
16
|
+
const NON_REGISTRY = /^(?:git\+|git:|github:|gitlab:|bitbucket:|gist:|https?:\/\/|file:|link:)|\.t(?:ar\.)?gz(?:[#?].*)?$/i;
|
|
17
|
+
const POPULAR = ['express', 'lodash', 'react', 'react-dom', 'axios', 'chalk', 'commander', 'debug', 'dotenv', 'request', 'moment',
|
|
18
|
+
'webpack', 'typescript', 'eslint', 'jest', 'mocha', 'vue', 'next', 'mongoose', 'cors', 'body-parser', 'jsonwebtoken', 'bcrypt',
|
|
19
|
+
'uuid', 'yargs', 'colors', 'async', 'underscore', 'socket.io', 'nodemon', 'prettier', 'ethers', 'web3', 'puppeteer', 'electron',
|
|
20
|
+
'sharp', 'dayjs', 'zod', 'vite', 'redux', 'nodemailer', 'mysql', 'pg', 'redis', 'ws', 'cheerio', 'inquirer', 'semver', 'glob'];
|
|
21
|
+
const DISABLE_SECURITY = /(?:(?:disable|turn off|switch off|deactivate|pause)\s+(?:your\s+|the\s+|windows\s+)?(?:anti-?virus|defender|edr|endpoint protection|firewall|gatekeeper|smartscreen|real-?time protection|sip\b)|Set-MpPreference|Add-MpPreference\s+-ExclusionPath|xattr\s+-[a-z]*d[a-z]*\s+com\.apple\.quarantine|spctl\s+--master-disable|csrutil\s+disable)/i;
|
|
22
|
+
|
|
23
|
+
// Damerau-Levenshtein distance, capped (we only care about 0, 1 and "more").
|
|
24
|
+
function distance(a, b) {
|
|
25
|
+
if (Math.abs(a.length - b.length) > 1) return 2;
|
|
26
|
+
const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
|
|
27
|
+
for (let j = 1; j <= b.length; j++) d[0][j] = j;
|
|
28
|
+
for (let i = 1; i <= a.length; i++) {
|
|
29
|
+
for (let j = 1; j <= b.length; j++) {
|
|
30
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
31
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
32
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return d[a.length][b.length];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function typosquatOf(name) {
|
|
39
|
+
if (typeof name !== 'string' || name.startsWith('@') || POPULAR.includes(name) || name.length < 4) return null;
|
|
40
|
+
return POPULAR.find((p) => p.length >= 4 && distance(name, p) === 1) || null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Decode quoted base64 literals of 16+ chars; return the ones that decode to readable text.
|
|
44
|
+
function hiddenStrings(text) {
|
|
45
|
+
const out = [];
|
|
46
|
+
for (const m of text.matchAll(/(['"`])([A-Za-z0-9+/]{16,}={0,2})\1/g)) {
|
|
47
|
+
const s = Buffer.from(m[2], 'base64').toString('utf8');
|
|
48
|
+
if (/^[\x20-\x7e\s]{8,}$/.test(s)) out.push(s);
|
|
49
|
+
if (out.length >= 20) break;
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const clip = (s, n = 160) => String(s).replace(/\s+/g, ' ').trim().slice(0, n);
|
|
55
|
+
|
|
56
|
+
// Walk the tree without following symlinks. .git is skipped except for hooks and config.
|
|
57
|
+
function walk(root) {
|
|
58
|
+
const files = [];
|
|
59
|
+
const links = [];
|
|
60
|
+
let truncated = false;
|
|
61
|
+
const stack = [''];
|
|
62
|
+
while (stack.length) {
|
|
63
|
+
const rel = stack.pop();
|
|
64
|
+
let entries;
|
|
65
|
+
try { entries = fs.readdirSync(path.join(root, rel), { withFileTypes: true }); } catch { continue; }
|
|
66
|
+
for (const e of entries) {
|
|
67
|
+
const p = rel ? `${rel}/${e.name}` : e.name;
|
|
68
|
+
if (e.isSymbolicLink()) { links.push(p); continue; }
|
|
69
|
+
if (e.isDirectory()) {
|
|
70
|
+
if (SKIP_DIRS.has(e.name)) continue;
|
|
71
|
+
if (p === '.git') {
|
|
72
|
+
for (const sub of ['hooks']) {
|
|
73
|
+
try { for (const h of fs.readdirSync(path.join(root, '.git', sub), { withFileTypes: true })) if (h.isFile()) files.push(`.git/${sub}/${h.name}`); } catch { /* none */ }
|
|
74
|
+
}
|
|
75
|
+
if (fs.existsSync(path.join(root, '.git', 'config'))) files.push('.git/config');
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
stack.push(p);
|
|
79
|
+
} else if (e.isFile()) {
|
|
80
|
+
if (files.length >= MAX_FILES) { truncated = true; continue; }
|
|
81
|
+
files.push(p);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { files: files.sort(), links, truncated };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function readText(root, rel) {
|
|
89
|
+
try {
|
|
90
|
+
const full = path.join(root, rel);
|
|
91
|
+
const st = fs.lstatSync(full);
|
|
92
|
+
if (!st.isFile() || st.size > MAX_BYTES) return null;
|
|
93
|
+
const buf = fs.readFileSync(full);
|
|
94
|
+
if (buf.includes(0)) return null;
|
|
95
|
+
return buf.toString('utf8');
|
|
96
|
+
} catch { return null; }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function inspectDir(dir) {
|
|
100
|
+
const root = path.resolve(dir);
|
|
101
|
+
if (!fs.statSync(root).isDirectory()) throw new Error(`Not a directory: ${dir}`);
|
|
102
|
+
const { files, links, truncated } = walk(root);
|
|
103
|
+
const findings = [];
|
|
104
|
+
const add = (severity, indicator, file, detail) => findings.push({ severity, indicator, file, detail });
|
|
105
|
+
const hookTargets = new Set();
|
|
106
|
+
|
|
107
|
+
for (const l of links) {
|
|
108
|
+
let target = '';
|
|
109
|
+
try { target = fs.readlinkSync(path.join(root, l)); } catch { /* unreadable */ }
|
|
110
|
+
const resolved = path.resolve(path.dirname(path.join(root, l)), target);
|
|
111
|
+
const rel = path.relative(root, resolved);
|
|
112
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) add('high', 'symlink_outside_repo', l, `Symlink points outside the repository (${clip(target, 80)}). Tools that follow it can read or overwrite your files.`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const binaries = files.filter((f) => BINARY_EXT.test(f) && !f.startsWith('.git/'));
|
|
116
|
+
if (binaries.length) add('medium', 'binaries_present', binaries[0], `Executable or binary files: ${binaries.slice(0, 5).join(', ')}${binaries.length > 5 ? '…' : ''}`);
|
|
117
|
+
|
|
118
|
+
for (const f of files) {
|
|
119
|
+
const base = f.split('/').pop();
|
|
120
|
+
const lower = f.toLowerCase();
|
|
121
|
+
|
|
122
|
+
if (f.startsWith('.git/hooks/')) {
|
|
123
|
+
if (!base.endsWith('.sample')) add('high', 'installed_git_hook', f, `A git hook is already installed (${base}). It runs on your next git ${base.replace(/^(pre|post)-/, '')}.`);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (!TEXT_EXT.test(base) && !['Makefile', 'makefile', 'GNUmakefile', '.npmrc', '.yarnrc', '.envrc', '.gitmodules', 'config'].includes(base)
|
|
127
|
+
&& !lower.startsWith('.husky/') && !lower.startsWith('.githooks/')) continue;
|
|
128
|
+
const text = readText(root, f);
|
|
129
|
+
if (text == null) continue;
|
|
130
|
+
|
|
131
|
+
if (f === '.git/config') {
|
|
132
|
+
if (/^\s*hookspath\s*=/im.test(text)) add('high', 'git_hooks_path', f, 'core.hooksPath points git at hooks shipped inside the repository.');
|
|
133
|
+
if (/^\s*fsmonitor\s*=\s*(?!true|false)\S/im.test(text)) add('high', 'git_fsmonitor_command', f, 'core.fsmonitor is set to a command; git runs it on status and diff.');
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (lower.endsWith('.vscode/tasks.json')) {
|
|
137
|
+
if (/"runOn"\s*:\s*"folderOpen"/i.test(text)) add('high', 'vscode_folder_open_autorun', f, 'A task runs automatically when the folder is opened in VS Code or Cursor (runOn: "folderOpen").');
|
|
138
|
+
if (EXEC.test(text)) add('high', 'vscode_task_shell_execution', f, 'tasks.json contains shell, download or eval primitives.');
|
|
139
|
+
} else if (lower.endsWith('.vscode/settings.json')) {
|
|
140
|
+
if (/"task\.allowAutomaticTasks"\s*:\s*("on"|true)/i.test(text)) add('high', 'vscode_auto_tasks_enabled', f, 'Turns on automatic tasks, so folder-open tasks run without asking.');
|
|
141
|
+
} else if (lower.endsWith('.vscode/launch.json')) {
|
|
142
|
+
if (/"preLaunchTask"\s*:/i.test(text)) add('medium', 'vscode_pre_launch_task', f, 'Starting the debugger first runs a task from tasks.json.');
|
|
143
|
+
} else if (/(^|\/)\.devcontainer(\/devcontainer)?\.json$/i.test(f) || /(^|\/)\.devcontainer\/[^/]+\/devcontainer\.json$/i.test(f)) {
|
|
144
|
+
for (const m of text.matchAll(/"(initializeCommand|onCreateCommand|updateContentCommand|postCreateCommand|postStartCommand|postAttachCommand)"\s*:\s*("(?:[^"\\]|\\.)*"|\[[^\]]*\]|\{[^}]*\})/g)) {
|
|
145
|
+
const onHost = m[1] === 'initializeCommand';
|
|
146
|
+
add(onHost || EXEC.test(m[2]) || PIPE_TO_SHELL.test(m[2]) ? 'high' : 'medium', 'devcontainer_command', f,
|
|
147
|
+
`${m[1]} runs ${onHost ? 'on your machine (not in the container)' : 'when the dev container is created or started'}: ${clip(m[2], 120)}`);
|
|
148
|
+
}
|
|
149
|
+
} else if (base === 'package.json') {
|
|
150
|
+
let pkg = null;
|
|
151
|
+
try { pkg = JSON.parse(text); } catch { add('low', 'package_json_unparseable', f, 'package.json is not valid JSON; npm may still read parts of it.'); }
|
|
152
|
+
if (pkg) {
|
|
153
|
+
const scripts = pkg.scripts && typeof pkg.scripts === 'object' ? pkg.scripts : {};
|
|
154
|
+
const pkgDir = path.posix.dirname(f);
|
|
155
|
+
for (const [k, v] of Object.entries(scripts)) {
|
|
156
|
+
if (typeof v !== 'string') continue;
|
|
157
|
+
if (LIFECYCLE.includes(k)) {
|
|
158
|
+
const risky = EXEC.test(v) || /https?:\/\//i.test(v);
|
|
159
|
+
add(risky ? 'high' : 'medium', `npm_${k}_hook`, f, `"${k}": "${clip(v)}" runs automatically on npm/pnpm/yarn install${k.includes('prepare') ? ' (and on git dependency installs)' : ''}.`);
|
|
160
|
+
for (const m of v.matchAll(/(?:node|python3?|sh|bash)\s+([\w./-]+\.(?:[cm]?js|ts|py|sh))/g)) hookTargets.add(path.posix.normalize(path.posix.join(pkgDir === '.' ? '' : pkgDir, m[1])));
|
|
161
|
+
} else if (EXEC.test(v)) {
|
|
162
|
+
add('high', 'suspicious_npm_script', f, `Script "${clip(k, 32)}" contains shell, download or eval primitives: ${clip(v, 100)}`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
for (const field of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {
|
|
166
|
+
for (const [name, spec] of Object.entries(pkg[field] || {})) {
|
|
167
|
+
if (typeof spec === 'string' && NON_REGISTRY.test(spec.trim())) add('high', 'non_registry_dependency', f, `${field}.${name} installs from "${clip(spec, 80)}", not the registry; its own install hooks run too.`);
|
|
168
|
+
const near = typosquatOf(name);
|
|
169
|
+
if (near) add('high', 'possible_typosquat', f, `${field}.${name} is one letter away from the popular package "${near}".`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
} else if (base === '.npmrc') {
|
|
174
|
+
if (/^\s*(?:@[\w-]+:)?registry\s*=\s*https?:\/\/(?!registry\.npmjs\.org)/im.test(text)) add('high', 'npmrc_registry_override', f, 'Points npm at a non-default registry.');
|
|
175
|
+
if (/^\s*(script-shell|node-options|ignore-scripts\s*=\s*false)/im.test(text)) add('high', 'npmrc_exec_setting', f, 'Sets script-shell, node-options or re-enables scripts.');
|
|
176
|
+
} else if (base === '.yarnrc.yml' || base === '.yarnrc') {
|
|
177
|
+
if (/^\s*(yarnPath|yarn-path)\s*[:=\s]/im.test(text)) add('medium', 'yarn_path', f, 'yarnPath makes every yarn command run a JavaScript file from this repository.');
|
|
178
|
+
} else if (base === 'setup.py') {
|
|
179
|
+
if (EXEC.test(text)) add('high', 'setup_py_exec', f, 'setup.py runs shell, subprocess or eval code; pip install runs it.');
|
|
180
|
+
} else if (base === 'pyproject.toml') {
|
|
181
|
+
if (/^\s*backend-path\s*=/im.test(text)) add('medium', 'python_local_build_backend', f, 'Uses an in-repo build backend (backend-path); pip install runs it.');
|
|
182
|
+
} else if (/^(?:GNU)?[Mm]akefile$/.test(base) || base.endsWith('.mk')) {
|
|
183
|
+
if (EXEC.test(text) || PIPE_TO_SHELL.test(text)) add('high', 'makefile_exec', f, 'The Makefile runs download, eval or inline-interpreter commands.');
|
|
184
|
+
} else if (base === 'build.rs') {
|
|
185
|
+
add('medium', 'cargo_build_script', f, 'cargo build runs build.rs on your machine.');
|
|
186
|
+
} else if (base === '.envrc') {
|
|
187
|
+
add('medium', 'direnv_envrc', f, 'direnv runs .envrc when you cd into the folder (once allowed).');
|
|
188
|
+
} else if (base === '.gitmodules') {
|
|
189
|
+
add('low', 'git_submodules', f, `Submodules: ${clip([...text.matchAll(/url\s*=\s*(\S+)/g)].map((m) => m[1]).join(', '), 140)}`);
|
|
190
|
+
} else if (lower.startsWith('.husky/') || lower.startsWith('.githooks/') || /(^|\/)(lefthook\.ya?ml|\.pre-commit-config\.ya?ml)$/i.test(f)) {
|
|
191
|
+
if (!lower.startsWith('.husky/_/')) add('medium', 'repo_git_hooks', f, 'Git hooks shipped with the repo; a prepare script or hook manager installs them.');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (/\.(md|txt)$/i.test(base)) {
|
|
195
|
+
if (DISABLE_SECURITY.test(text)) add('high', 'disable_security_instructions', f, `Instructions ask you to turn off security tooling: "${clip(text.match(DISABLE_SECURITY)[0], 80)}"`);
|
|
196
|
+
if (PIPE_TO_SHELL.test(text)) add('medium', 'pipe_to_shell_instructions', f, 'Instructions pipe a download straight into a shell.');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (CODE_EXT.test(base)) {
|
|
200
|
+
const hidden = hiddenStrings(text);
|
|
201
|
+
const hiddenUrl = hidden.find((s) => /https?:\/\//i.test(s));
|
|
202
|
+
if (/\beval\s*\(\s*(?:Buffer\.from|atob|unescape|decodeURIComponent)/.test(text)) add('high', 'obfuscated_eval', f, 'Decodes a string and passes it to eval().');
|
|
203
|
+
if (/new\s+Function\s*\(/.test(text) && /\b(fetch|https?\.get|axios|request)\s*\(/.test(text)) add('high', 'remote_code_eval', f, 'Fetches text over the network and runs it with new Function().');
|
|
204
|
+
if (hiddenUrl) add('high', 'hidden_url', f, `A base64 string decodes to a URL: ${clip(hiddenUrl, 100)}`);
|
|
205
|
+
if (/(?:writeFileSync|writeFile|copyFileSync|copyFile|open|cp|Copy-Item|Set-Content)\s*\(?\s*['"`][^'"`\n]*\.git[\\/]+hooks|>\s*['"]?\.git[\\/]+hooks/.test(text)) add('high', 'writes_git_hooks', f, 'Code writes into .git/hooks, installing a hook that runs on later git commands.');
|
|
206
|
+
if (hookTargets.has(f) && /child_process|subprocess|os\.system|execSync|spawnSync|exec\(/.test(text)) add('high', 'install_hook_runs_commands', f, 'This file runs from an install hook and starts other processes.');
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const order = { high: 0, medium: 1, low: 2 };
|
|
211
|
+
findings.sort((a, b) => order[a.severity] - order[b.severity] || a.file.localeCompare(b.file));
|
|
212
|
+
const verdict = findings.some((x) => x.severity === 'high') ? 'do_not_run'
|
|
213
|
+
: findings.some((x) => x.severity === 'medium') ? 'review_first' : 'no_known_traps';
|
|
214
|
+
return { root, filesScanned: files.length, truncated, verdict, findings };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function renderInspect(r) {
|
|
218
|
+
const head = {
|
|
219
|
+
do_not_run: 'DO NOT RUN: found code that runs on open, install or build, or asks you to lower your defences.',
|
|
220
|
+
review_first: 'REVIEW FIRST: found things that run code in some workflows.',
|
|
221
|
+
no_known_traps: 'No known traps found. That is not proof it is safe; still run it in a container or VM.',
|
|
222
|
+
}[r.verdict];
|
|
223
|
+
const lines = [head, `${r.filesScanned} files read in ${r.root}${r.truncated ? ' (stopped at the file limit)' : ''}. Nothing was executed or sent.`];
|
|
224
|
+
for (const f of r.findings) lines.push(` [${f.severity}] ${f.file}: ${f.detail}`);
|
|
225
|
+
return lines.join('\n');
|
|
226
|
+
}
|
package/lib/models.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// Downloads the two open face models from OpenCV's model zoo on first use and checks each against a
|
|
2
|
+
// SHA-256 pinned in faceprint.js. The download is hashed as it arrives and only takes its real name
|
|
3
|
+
// once the hash matches, so a file under a model's name is always one that was verified.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import { MODELS } from './faceprint.js';
|
|
8
|
+
import { request } from './net.js';
|
|
9
|
+
|
|
10
|
+
// The model zoo lives on GitHub, which redirects to its own file hosts. Nothing else is followed.
|
|
11
|
+
export const trusted = (u) => u.protocol === 'https:' && !u.port && (u.hostname === 'github.com' || u.hostname.endsWith('.githubusercontent.com'));
|
|
12
|
+
|
|
13
|
+
function sha256File(file) {
|
|
14
|
+
return new Promise((ok, no) => {
|
|
15
|
+
const h = crypto.createHash('sha256');
|
|
16
|
+
fs.createReadStream(file).on('data', (d) => h.update(d)).on('end', () => ok(h.digest('hex'))).on('error', no);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// One GET into tmp, never more than the model's known size. Returns the reply and the body's hash.
|
|
21
|
+
async function fetchTo(url, tmp, limit, proxy) {
|
|
22
|
+
const hash = crypto.createHash('sha256');
|
|
23
|
+
const file = fs.createWriteStream(tmp, { mode: 0o600 });
|
|
24
|
+
let failed = null;
|
|
25
|
+
file.on('error', (e) => { failed = e; });
|
|
26
|
+
try {
|
|
27
|
+
const res = await request(url, { proxy, maxBytes: limit, onData: (d) => { hash.update(d); file.write(d); } });
|
|
28
|
+
return { res, sha256: hash.digest('hex') };
|
|
29
|
+
} finally {
|
|
30
|
+
await new Promise((ok) => file.end(ok));
|
|
31
|
+
if (failed) throw failed;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function download(m, dest, proxy) {
|
|
36
|
+
const tmp = `${dest}.${crypto.randomBytes(4).toString('hex')}.part`;
|
|
37
|
+
let url = new URL(m.url);
|
|
38
|
+
try {
|
|
39
|
+
for (let hops = 0; hops < 5; hops++) {
|
|
40
|
+
if (!trusted(url)) throw new Error(`Refusing to fetch ${m.file} from ${url.host}: not GitHub.`);
|
|
41
|
+
const { res, sha256 } = await fetchTo(url, tmp, m.bytes, proxy);
|
|
42
|
+
if ([301, 302, 303, 307, 308].includes(res.status) && res.headers.location) {
|
|
43
|
+
url = new URL(res.headers.location, url);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (res.status !== 200) throw new Error(`download failed (${res.status}) for ${url}`);
|
|
47
|
+
if (sha256 !== m.sha256) throw new Error(`${m.file} did not match its pinned SHA-256 and was discarded. Expected ${m.sha256}, got ${sha256}.`);
|
|
48
|
+
fs.renameSync(tmp, dest);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
throw new Error('too many redirects');
|
|
52
|
+
} finally {
|
|
53
|
+
fs.rmSync(tmp, { force: true });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ------------------------------------------------------------------ finding copies already here
|
|
58
|
+
//
|
|
59
|
+
// Nothing is downloaded without consent. Before asking, the tool looks for copies that are already
|
|
60
|
+
// on this computer: in the models folder, and under the model's own file name in the current folder
|
|
61
|
+
// and the Downloads folder. A file is only ever accepted on its SHA-256, so where it came from does
|
|
62
|
+
// not matter, and a renamed copy can be brought in with "counterlure models import".
|
|
63
|
+
|
|
64
|
+
const MAX_MODEL_BYTES = Math.max(...Object.values(MODELS).map((m) => m.bytes));
|
|
65
|
+
|
|
66
|
+
// The pinned model a file is, by hash, or null. Files of the wrong size are not even read.
|
|
67
|
+
async function identify(file) {
|
|
68
|
+
let st;
|
|
69
|
+
try { st = fs.statSync(file); } catch { return null; }
|
|
70
|
+
if (!st.isFile() || !Object.values(MODELS).some((m) => m.bytes === st.size)) return null;
|
|
71
|
+
const h = await sha256File(file);
|
|
72
|
+
return Object.values(MODELS).find((m) => m.sha256 === h) || null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Copies a verified file into the models folder under its proper name (written aside, then renamed).
|
|
76
|
+
function adopt(src, m, dir) {
|
|
77
|
+
const dest = path.join(dir, m.file);
|
|
78
|
+
if (path.resolve(src) === path.resolve(dest)) return dest;
|
|
79
|
+
const tmp = `${dest}.${crypto.randomBytes(4).toString('hex')}.part`;
|
|
80
|
+
try {
|
|
81
|
+
fs.copyFileSync(src, tmp);
|
|
82
|
+
fs.renameSync(tmp, dest);
|
|
83
|
+
} finally {
|
|
84
|
+
fs.rmSync(tmp, { force: true });
|
|
85
|
+
}
|
|
86
|
+
return dest;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function defaultSearchDirs() {
|
|
90
|
+
const home = process.env.USERPROFILE || process.env.HOME || '';
|
|
91
|
+
return [process.cwd(), home && path.join(home, 'Downloads')].filter(Boolean);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// What is in place, and what is missing. Each entry: { ...model, key, installed }.
|
|
95
|
+
export async function modelStatus(dir) {
|
|
96
|
+
const out = [];
|
|
97
|
+
for (const [key, m] of Object.entries(MODELS)) {
|
|
98
|
+
const file = path.join(dir, m.file);
|
|
99
|
+
out.push({ ...m, key, installed: fs.existsSync(file) && (await sha256File(file)) === m.sha256 });
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Looks for missing models under their own file names in searchDirs, and adopts verified copies.
|
|
105
|
+
export async function findLocalModels(dir, { searchDirs = defaultSearchDirs() } = {}) {
|
|
106
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
107
|
+
const found = [];
|
|
108
|
+
for (const m of (await modelStatus(dir)).filter((s) => !s.installed)) {
|
|
109
|
+
for (const d of searchDirs) {
|
|
110
|
+
const cand = path.join(d, m.file);
|
|
111
|
+
if ((await identify(cand))?.sha256 === m.sha256) {
|
|
112
|
+
adopt(cand, m, dir);
|
|
113
|
+
found.push({ file: m.file, from: cand });
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return found;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// "counterlure models import PATH...": every file given, or every .onnx file in a folder given, is
|
|
122
|
+
// checked against the pinned hashes. Matches are copied in; everything else is reported and left alone.
|
|
123
|
+
export async function importModels(dir, paths) {
|
|
124
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
125
|
+
const imported = [];
|
|
126
|
+
const rejected = [];
|
|
127
|
+
const files = [];
|
|
128
|
+
for (const p of paths) {
|
|
129
|
+
let st;
|
|
130
|
+
try { st = fs.statSync(p); } catch { rejected.push({ file: p, why: 'not found' }); continue; }
|
|
131
|
+
if (st.isDirectory()) {
|
|
132
|
+
for (const f of fs.readdirSync(p)) if (f.toLowerCase().endsWith('.onnx')) files.push(path.join(p, f));
|
|
133
|
+
} else files.push(p);
|
|
134
|
+
}
|
|
135
|
+
for (const f of files) {
|
|
136
|
+
let size = 0;
|
|
137
|
+
try { size = fs.statSync(f).size; } catch { /* reported below */ }
|
|
138
|
+
if (size > MAX_MODEL_BYTES) { rejected.push({ file: f, why: 'not one of the pinned models (wrong size)' }); continue; }
|
|
139
|
+
const m = await identify(f);
|
|
140
|
+
if (!m) { rejected.push({ file: f, why: 'does not match either pinned SHA-256' }); continue; }
|
|
141
|
+
adopt(f, m, dir);
|
|
142
|
+
imported.push({ file: m.file, from: f });
|
|
143
|
+
}
|
|
144
|
+
return { imported, rejected };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export class ModelsMissing extends Error {}
|
|
148
|
+
|
|
149
|
+
// Makes sure both models are in place. Copies already on this computer are used first. Anything
|
|
150
|
+
// still missing is downloaded only if consent(missing) resolves true; otherwise ModelsMissing.
|
|
151
|
+
export async function ensureModels(dir, { proxy = null, log = () => {}, consent = async () => true, searchDirs } = {}) {
|
|
152
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
153
|
+
for (const f of await findLocalModels(dir, { searchDirs })) log(`Using the verified copy of ${f.file} found at ${f.from}`);
|
|
154
|
+
const missing = (await modelStatus(dir)).filter((s) => !s.installed);
|
|
155
|
+
if (!missing.length) return dir;
|
|
156
|
+
if (!(await consent(missing))) throw new ModelsMissing('The face models are not installed, and nothing was downloaded.');
|
|
157
|
+
for (const m of missing) {
|
|
158
|
+
log(`Downloading ${m.file} (${(m.bytes / 1e6).toFixed(1)} MB) from OpenCV's model zoo on GitHub...`);
|
|
159
|
+
await download(m, path.join(dir, m.file), proxy);
|
|
160
|
+
}
|
|
161
|
+
return dir;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// The text shown when models are missing: what they are, where to get them yourself, and the hashes.
|
|
165
|
+
export function missingModelsText(missing, dir) {
|
|
166
|
+
const name = { detector: 'YuNet face detector', recognizer: 'SFace face recognizer' };
|
|
167
|
+
const size = (b) => (b > 1e6 ? `${(b / 1e6).toFixed(1)} MB` : `${Math.round(b / 1e3)} KB`);
|
|
168
|
+
return [
|
|
169
|
+
'The two open face models this tool runs locally are not on this computer yet.',
|
|
170
|
+
'They find and measure faces on your machine; no photo is involved in getting them.',
|
|
171
|
+
'',
|
|
172
|
+
...missing.flatMap((m) => [
|
|
173
|
+
` ${name[m.key] || m.key}, ${size(m.bytes)}: ${m.file}`,
|
|
174
|
+
` from ${m.url}`,
|
|
175
|
+
` SHA-256 ${m.sha256}`,
|
|
176
|
+
]),
|
|
177
|
+
'',
|
|
178
|
+
'Option 1, get them yourself (this tool makes no request):',
|
|
179
|
+
' Download them from OpenCV\'s own repository, https://github.com/opencv/opencv_zoo, or any',
|
|
180
|
+
' mirror you trust, at a time and over a connection of your choosing. Only the hash counts,',
|
|
181
|
+
' not where the file came from. Then run:',
|
|
182
|
+
' counterlure models import FILE-OR-FOLDER ...',
|
|
183
|
+
` or place them, under the names above, in ${dir}`,
|
|
184
|
+
' Step-by-step guide: README.md, "Getting the face models yourself".',
|
|
185
|
+
'',
|
|
186
|
+
'Option 2, let this tool fetch them from GitHub now, over the same route as everything else.',
|
|
187
|
+
' Each file is checked against the hash above and discarded if it does not match.',
|
|
188
|
+
].join('\n');
|
|
189
|
+
}
|