counterlure-cli 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/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
+ }
@@ -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/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
+ }
package/lib/net.js ADDED
@@ -0,0 +1,166 @@
1
+ // HTTPS with optional SOCKS5 (Tor) or HTTP CONNECT proxy, written out here instead of pulled in as
2
+ // dependencies so the whole network path is readable in one file.
3
+ //
4
+ // Through a proxy the hostname is always sent to the proxy unresolved, so DNS lookups never leave
5
+ // this computer directly (the "socks5h" behaviour). Certificates are always verified.
6
+ import https from 'node:https';
7
+ import net from 'node:net';
8
+ import tls from 'node:tls';
9
+ import crypto from 'node:crypto';
10
+
11
+ const UA = 'counterlure-cli'; // no version, OS or Node details
12
+
13
+ function reader(sock) {
14
+ let buf = Buffer.alloc(0), wait = null;
15
+ const pump = () => { if (wait && buf.length >= wait.n) { const out = buf.subarray(0, wait.n); buf = buf.subarray(wait.n); const w = wait; wait = null; w.ok(out); } };
16
+ sock.on('data', (d) => { buf = Buffer.concat([buf, d]); pump(); });
17
+ const fail = (e) => { if (wait) { const w = wait; wait = null; w.no(e); } };
18
+ sock.on('error', fail);
19
+ sock.on('close', () => fail(new Error('proxy closed the connection')));
20
+ const read = (n) => new Promise((ok, no) => { wait = { n, ok, no }; pump(); });
21
+ return {
22
+ read,
23
+ until: async (marker) => { // for HTTP CONNECT replies: one byte at a time, so nothing past the header is consumed
24
+ let s = '';
25
+ while (!s.endsWith(marker)) {
26
+ s += (await read(1)).toString('latin1');
27
+ if (s.length > 16384) throw new Error('proxy reply too long');
28
+ }
29
+ return s;
30
+ },
31
+ done: () => { sock.removeAllListeners('data'); sock.removeAllListeners('error'); sock.removeAllListeners('close'); },
32
+ };
33
+ }
34
+
35
+ // TLS settings stated outright, so nothing in the environment (NODE_TLS_REJECT_UNAUTHORIZED,
36
+ // --tls-min-v1.0) can lower them. Every host this tool talks to speaks TLS 1.3.
37
+ const TLS = { rejectUnauthorized: true, minVersion: 'TLSv1.3' };
38
+
39
+ function connect(host, port) {
40
+ return new Promise((ok, no) => { const s = net.connect(port, host.replace(/^\[|\]$/g, ''), () => ok(s)); s.once('error', no); s.setTimeout(30000, () => s.destroy(new Error('proxy timed out'))); });
41
+ }
42
+
43
+ // Opens a connection to the proxy and runs its handshake. The 30 second limit covers the handshake
44
+ // only: once the tunnel is up the request's own timeout applies, so a slow reply over Tor is not
45
+ // cut off here. A failed handshake closes the socket.
46
+ async function tunnel(p, defaultPort, handshake) {
47
+ const sock = await connect(p.hostname, Number(p.port) || defaultPort);
48
+ const r = reader(sock);
49
+ try { await handshake(sock, r); } catch (e) { sock.destroy(); throw e; }
50
+ r.done();
51
+ sock.setTimeout(0);
52
+ sock.removeAllListeners('timeout');
53
+ return sock;
54
+ }
55
+
56
+ // SOCKS5 carries each of these behind a one-byte length.
57
+ function short(what, s) {
58
+ const b = Buffer.from(s);
59
+ if (b.length > 255) throw new Error(`${what} is too long for a SOCKS proxy (255 bytes at most)`);
60
+ return b;
61
+ }
62
+
63
+ const socks5 = (p, host, port) => tunnel(p, 1080, async (sock, r) => {
64
+ const user = decodeURIComponent(p.username || ''), pass = decodeURIComponent(p.password || '');
65
+ const h = short('The host name', host);
66
+ sock.write(Buffer.from(user ? [5, 1, 2] : [5, 1, 0]));
67
+ const [ver, method] = await r.read(2);
68
+ if (ver !== 5 || method === 0xff) throw new Error('SOCKS proxy refused the connection');
69
+ if (method === 2) {
70
+ const u = short('The proxy username', user), pw = short('The proxy password', pass);
71
+ sock.write(Buffer.concat([Buffer.from([1, u.length]), u, Buffer.from([pw.length]), pw]));
72
+ const [, st] = await r.read(2);
73
+ if (st !== 0) throw new Error('SOCKS proxy refused the username');
74
+ } else if (method !== 0) throw new Error('SOCKS proxy wants an unsupported login method');
75
+ sock.write(Buffer.concat([Buffer.from([5, 1, 0, 3, h.length]), h, Buffer.from([port >> 8, port & 255])]));
76
+ const [, rep, , atyp] = await r.read(4);
77
+ if (rep !== 0) throw new Error(`SOCKS proxy could not reach ${host} (code ${rep})`);
78
+ const len = atyp === 1 ? 4 : atyp === 4 ? 16 : (await r.read(1))[0];
79
+ await r.read(len + 2);
80
+ });
81
+
82
+ const httpConnect = (p, host, port) => tunnel(p, 8080, async (sock, r) => {
83
+ const auth = p.username ? `Proxy-Authorization: Basic ${Buffer.from(`${decodeURIComponent(p.username)}:${decodeURIComponent(p.password)}`).toString('base64')}\r\n` : '';
84
+ sock.write(`CONNECT ${host}:${port} HTTP/1.1\r\nHost: ${host}:${port}\r\n${auth}\r\n`);
85
+ const head = await r.until('\r\n\r\n');
86
+ if (!/^HTTP\/1\.[01] 200/.test(head)) throw new Error(`proxy refused: ${head.split('\r\n')[0]}`);
87
+ });
88
+
89
+ // Is a Tor SOCKS port listening here? Offers no-auth and username auth, as the real request will,
90
+ // and checks the reply is SOCKS5. Sends nothing beyond the greeting.
91
+ function isSocks(host, port, ms = 2000) {
92
+ return new Promise((ok) => {
93
+ const s = net.connect(port, host);
94
+ const done = (v) => { s.destroy(); ok(v); };
95
+ s.setTimeout(ms, () => done(false));
96
+ s.once('error', () => done(false));
97
+ s.once('connect', () => s.write(Buffer.from([5, 2, 0, 2])));
98
+ s.once('data', (d) => done(d[0] === 5 && d[1] !== 0xff));
99
+ });
100
+ }
101
+
102
+ // Finds a running Tor: COUNTERLURE_TOR (host:port) if set, otherwise the tor service (9050) or
103
+ // Tor Browser (9150). Returns a socks5h proxy URL with a fresh isolation username, or null.
104
+ export async function findTor({ env = process.env, probe = isSocks } = {}) {
105
+ const spots = env.COUNTERLURE_TOR ? [env.COUNTERLURE_TOR] : ['127.0.0.1:9050', '127.0.0.1:9150'];
106
+ for (const spot of spots) {
107
+ let u;
108
+ try { u = new URL(`socks5h://${spot}`); } catch { throw new Error(`COUNTERLURE_TOR must be host:port, not "${spot}"`); }
109
+ if (await probe(u.hostname.replace(/^\[|\]$/g, ''), Number(u.port) || 9050)) {
110
+ return new URL(`socks5h://cl-${crypto.randomBytes(6).toString('hex')}:x@${u.host}`);
111
+ }
112
+ }
113
+ return null;
114
+ }
115
+
116
+ export const isOnionHost = (host) => /\.onion$/i.test(host);
117
+
118
+ // "tor" is shorthand for Tor's local SOCKS port. A random username per run asks Tor to use a
119
+ // separate circuit (IsolateSOCKSAuth), so this tool's traffic doesn't share an exit with your browser.
120
+ export function resolveProxy(opt) {
121
+ const v = opt || process.env.COUNTERLURE_PROXY || process.env.ALL_PROXY || process.env.HTTPS_PROXY || process.env.https_proxy || '';
122
+ if (!v) return null;
123
+ if (v === 'tor') return new URL(`socks5h://cl-${crypto.randomBytes(6).toString('hex')}:x@127.0.0.1:9050`);
124
+ const u = new URL(v);
125
+ if (!['socks5h:', 'socks5:', 'socks:', 'http:'].includes(u.protocol)) throw new Error(`Unsupported proxy ${u.protocol} (use socks5h://host:port or http://host:port)`);
126
+ return u;
127
+ }
128
+
129
+ export async function request(url, { method = 'GET', body, headers = {}, proxy = null, maxBytes = 64 * 1024 * 1024, onData } = {}) {
130
+ const u = new URL(url);
131
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname);
132
+ // An onion address is the key that authenticates the service, and Tor encrypts end to end, so
133
+ // plain HTTP is fine there. It must never be looked up or dialled outside Tor.
134
+ const onion = isOnionHost(u.hostname);
135
+ if (onion && (!proxy || proxy.protocol === 'http:')) throw new Error(`${u.hostname} is an onion address: it can only be reached through Tor (a SOCKS proxy).`);
136
+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && (local || onion))) throw new Error(`Refusing non-HTTPS URL ${u.origin}`);
137
+ const port = Number(u.port) || (u.protocol === 'https:' ? 443 : 80);
138
+ let raw = null;
139
+ if (proxy) raw = proxy.protocol === 'http:' ? await httpConnect(proxy, u.hostname, port) : await socks5(proxy, u.hostname, port);
140
+ const mod = u.protocol === 'https:' ? https : await import('node:http');
141
+ return new Promise((ok, no) => {
142
+ const opts = {
143
+ method, host: u.hostname, port, path: u.pathname + u.search, servername: u.hostname,
144
+ headers: { 'user-agent': UA, accept: '*/*', ...headers, ...(body ? { 'content-length': Buffer.byteLength(body) } : {}) },
145
+ timeout: 120000, ...TLS,
146
+ };
147
+ // Node only uses createConnection when no agent is set at all; with agent:false it would quietly
148
+ // open its own direct connection and skip the proxy. So: no agent through a proxy, a fresh one without.
149
+ if (!raw) opts.agent = false;
150
+ else opts.createConnection = () => (u.protocol === 'https:' ? tls.connect({ socket: raw, servername: u.hostname, ALPNProtocols: ['http/1.1'], ...TLS }) : raw);
151
+ const req = mod.request(opts, (res) => {
152
+ const chunks = []; let n = 0;
153
+ res.on('data', (d) => {
154
+ n += d.length;
155
+ if (n > maxBytes) { req.destroy(new Error('response too large')); return; }
156
+ if (onData) onData(d); else chunks.push(d);
157
+ });
158
+ res.on('end', () => ok({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks) }));
159
+ res.on('error', no);
160
+ });
161
+ req.on('timeout', () => req.destroy(new Error('request timed out')));
162
+ req.on('error', no);
163
+ if (body) req.write(body);
164
+ req.end();
165
+ });
166
+ }
package/lib/pow.js ADDED
@@ -0,0 +1,43 @@
1
+ // Proof of work for reports filed without an account.
2
+ //
3
+ // An unauthenticated intake is the obvious place to attack a corroboration system: script a few
4
+ // thousand reports against one face and hope the volume reads as independent sourcing. The server
5
+ // already treats every no-account CLI report as a single source, and rate-limits them per network
6
+ // and overall. Proof of work adds a cost per report that the reporter pays in CPU, not identity.
7
+ //
8
+ // The work is bound to the request's single-use nonce and timestamp, so it can't be precomputed,
9
+ // reused, or replayed:
10
+ //
11
+ // sha256("counterlure-cli/1|pow|<nonce>|<ts>|<counter>") must start with <bits> zero bits
12
+ //
13
+ // At the default of 21 bits that is about two million hashes, a few seconds on a laptop.
14
+ import crypto from 'node:crypto';
15
+ import { PROTOCOL_ID } from './protocol-id.js';
16
+
17
+ export const DEFAULT_BITS = 21;
18
+ // Refuse to grind past this, whatever the server asks. 2^26 hashes is already about a minute.
19
+ export const MAX_BITS = 26;
20
+
21
+ export function zeroBits(buf) {
22
+ let n = 0;
23
+ for (const byte of buf) {
24
+ if (byte === 0) { n += 8; continue; }
25
+ return n + Math.clz32(byte) - 24;
26
+ }
27
+ return n;
28
+ }
29
+
30
+ const digest = (nonce, ts, counter) =>
31
+ crypto.createHash('sha256').update(`${PROTOCOL_ID}|pow|${nonce}|${ts}|${counter}`).digest();
32
+
33
+ export function verify(nonce, ts, counter, bits) {
34
+ return typeof counter === 'string' && counter.length <= 32 && zeroBits(digest(nonce, ts, counter)) >= bits;
35
+ }
36
+
37
+ export function solve(nonce, ts, bits) {
38
+ if (!Number.isInteger(bits) || bits < 1 || bits > MAX_BITS) throw new Error(`Proof of work of ${bits} bits is outside what this tool will do.`);
39
+ for (let i = 0; ; i++) {
40
+ const counter = i.toString(36);
41
+ if (zeroBits(digest(nonce, ts, counter)) >= bits) return counter;
42
+ }
43
+ }