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/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
|
+
}
|
package/lib/proto.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Request/reply envelope for counterlure-cli/1.
|
|
2
|
+
//
|
|
3
|
+
// Threat model for the transport: TLS to www.counterlure.com terminates at Cloudflare, so anything
|
|
4
|
+
// sent in the clear inside TLS is readable at the edge. We assume the edge, and any proxy or Tor exit
|
|
5
|
+
// in between, is an observer. What it can see is that a client talked to the service, when, and how
|
|
6
|
+
// many bytes moved. What it must not see or alter is the content.
|
|
7
|
+
//
|
|
8
|
+
// 1. A one-time OpenPGP key pair is generated per request and discarded after the reply.
|
|
9
|
+
// 2. The request (op, args, one-time public key, 128-bit nonce, timestamp, optional proof of work)
|
|
10
|
+
// is padded to a fixed bucket and encrypted to the server key compiled into this tool, which is
|
|
11
|
+
// checked against a pinned fingerprint before every use.
|
|
12
|
+
// - control traffic (login, whoami, check, withdraw) pads to 16 KB
|
|
13
|
+
// - reports pad to REPORT_PAD, so every report is the same size whatever the photo
|
|
14
|
+
// 3. The reply must decrypt with the one-time key, carry a valid signature from the pinned key, and
|
|
15
|
+
// echo the nonce. Anything else is discarded, so the edge can neither read nor forge an answer.
|
|
16
|
+
// The server pads replies to 4 KB multiples, so a match and a miss look alike.
|
|
17
|
+
//
|
|
18
|
+
// The server accepts each nonce once and only within five minutes of its clock, so a captured
|
|
19
|
+
// request can't be replayed.
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import crypto from 'node:crypto';
|
|
22
|
+
import * as openpgp from 'openpgp';
|
|
23
|
+
import { SERVER_KEY, SERVER_FINGERPRINT } from './server-key.js';
|
|
24
|
+
import { request } from './net.js';
|
|
25
|
+
import { PROTOCOL_ID } from './protocol-id.js';
|
|
26
|
+
import { solve } from './pow.js';
|
|
27
|
+
|
|
28
|
+
export const PROTOCOL = PROTOCOL_ID;
|
|
29
|
+
export const PAD_TO = 16 * 1024;
|
|
30
|
+
export const REPORT_PAD = 224 * 1024;
|
|
31
|
+
|
|
32
|
+
let pinned = null;
|
|
33
|
+
async function serverKey() {
|
|
34
|
+
if (pinned) return pinned;
|
|
35
|
+
let armored = SERVER_KEY, want = SERVER_FINGERPRINT;
|
|
36
|
+
if (process.env.COUNTERLURE_SERVER_KEY) { // pointing at your own server; announced on every run
|
|
37
|
+
armored = fs.readFileSync(process.env.COUNTERLURE_SERVER_KEY, 'utf8');
|
|
38
|
+
want = (await openpgp.readKey({ armoredKey: armored })).getFingerprint();
|
|
39
|
+
process.stderr.write(`warning: using server key from COUNTERLURE_SERVER_KEY (${want}), not the pinned one\n`);
|
|
40
|
+
}
|
|
41
|
+
if (!armored || !want) throw new Error('This build has no server key pinned. Install a release from the official repository.');
|
|
42
|
+
const key = await openpgp.readKey({ armoredKey: armored });
|
|
43
|
+
if (key.isPrivate() || key.getFingerprint().toLowerCase() !== want.toLowerCase()) {
|
|
44
|
+
throw new Error('The embedded server key does not match its pinned fingerprint. Treat this copy of the tool as tampered with.');
|
|
45
|
+
}
|
|
46
|
+
pinned = key;
|
|
47
|
+
return key;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// The fingerprint of the key this run trusts. It is the server's identity: saved sessions are tied to it.
|
|
51
|
+
export const serverFingerprint = async () => (await serverKey()).getFingerprint().toLowerCase();
|
|
52
|
+
|
|
53
|
+
// Padding only hides sizes if nothing shrinks the padded text first, so compression is switched off
|
|
54
|
+
// by name instead of left to a default. A compressed reply is refused once it unpacks past 1 MB.
|
|
55
|
+
const SEND = { preferredCompressionAlgorithm: openpgp.enums.compression.uncompressed };
|
|
56
|
+
const RECEIVE = { maxDecompressedMessageSize: 1024 * 1024 };
|
|
57
|
+
|
|
58
|
+
// Serialises msg padded to exactly padTo bytes. Throws rather than send an off-size request.
|
|
59
|
+
export function pad(msg, padTo) {
|
|
60
|
+
const bare = JSON.stringify({ ...msg, pad: '' });
|
|
61
|
+
const fill = padTo - Buffer.byteLength(bare);
|
|
62
|
+
if (fill < 0) throw new Error('The request is larger than its envelope. Nothing was sent.');
|
|
63
|
+
return JSON.stringify({ ...msg, pad: 'x'.repeat(fill) });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// A refusal from the server. reply carries machine-readable fields such as powBits.
|
|
67
|
+
export class Refused extends Error {
|
|
68
|
+
constructor(reply) { super(reply.error || 'The server refused the request.'); this.reply = reply; }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// opts: proxy (from net.resolveProxy), pow (bits of work to attach), padTo, onWork (called before
|
|
72
|
+
// grinding, so the caller can say why the terminal has gone quiet).
|
|
73
|
+
export async function call(server, op, args, { proxy, pow, padTo = PAD_TO, onWork } = {}) {
|
|
74
|
+
const key = await serverKey();
|
|
75
|
+
const eph = await openpgp.generateKey({ type: 'ecc', curve: 'curve25519Legacy', userIDs: [{ name: 'counterlure-cli one-time key' }], format: 'object' });
|
|
76
|
+
const msg = { protocol: PROTOCOL, op, args, nonce: crypto.randomBytes(16).toString('hex'), ts: Date.now(), replyKey: eph.publicKey.armor() };
|
|
77
|
+
if (pow) {
|
|
78
|
+
onWork?.(pow);
|
|
79
|
+
msg.pow = solve(msg.nonce, msg.ts, pow);
|
|
80
|
+
}
|
|
81
|
+
const body = await openpgp.encrypt({ message: await openpgp.createMessage({ text: pad(msg, padTo) }), encryptionKeys: key, config: SEND });
|
|
82
|
+
|
|
83
|
+
const res = await request(new URL('/api/cli', server).toString(), {
|
|
84
|
+
method: 'POST', body, proxy, maxBytes: 1024 * 1024,
|
|
85
|
+
headers: { 'content-type': 'application/pgp-encrypted', accept: 'application/pgp-encrypted' },
|
|
86
|
+
});
|
|
87
|
+
if (res.status === 429) throw new Error('Rate limited. Wait a minute and try again.');
|
|
88
|
+
if (res.status === 403) throw new Error('The edge refused the connection. Over Tor or a VPN this usually means the exit is blocked; try another circuit or route.');
|
|
89
|
+
if (res.status === 413) throw new Error('The server refused the request size. Update the tool.');
|
|
90
|
+
if (res.status !== 200 || !String(res.headers['content-type'] || '').startsWith('application/pgp-encrypted')) {
|
|
91
|
+
throw new Error(`Unexpected reply from the server (HTTP ${res.status}). Nothing was disclosed: the request was encrypted.`);
|
|
92
|
+
}
|
|
93
|
+
let reply;
|
|
94
|
+
try {
|
|
95
|
+
const { data } = await openpgp.decrypt({
|
|
96
|
+
message: await openpgp.readMessage({ armoredMessage: res.body.toString('utf8') }),
|
|
97
|
+
decryptionKeys: eph.privateKey, verificationKeys: key, expectSigned: true, config: RECEIVE,
|
|
98
|
+
});
|
|
99
|
+
reply = JSON.parse(data);
|
|
100
|
+
} catch {
|
|
101
|
+
throw new Error('The reply was not signed by the pinned Counterlure key and was discarded.');
|
|
102
|
+
}
|
|
103
|
+
if (reply.protocol !== PROTOCOL || reply.echo !== msg.nonce) throw new Error('The reply did not answer this request and was discarded.');
|
|
104
|
+
if (!reply.ok) throw new Refused(reply);
|
|
105
|
+
return reply;
|
|
106
|
+
}
|
package/lib/route.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Which server this run talks to, and how the traffic gets there.
|
|
2
|
+
//
|
|
3
|
+
// default Counterlure's onion service, through Tor running on this computer. The request
|
|
4
|
+
// never touches Cloudflare or any public address of ours, and it reaches our
|
|
5
|
+
// server from Tor, not from you: there is no network address of yours to receive.
|
|
6
|
+
// --direct the website, www.counterlure.com, through Cloudflare. Add --tor or --proxy to
|
|
7
|
+
// hide your address from Cloudflare; without them, Cloudflare sees it.
|
|
8
|
+
// --server URL another server (your own, for testing). An .onion URL goes through Tor.
|
|
9
|
+
//
|
|
10
|
+
// Nothing falls back from the onion route to the website on its own: if Tor is not running the
|
|
11
|
+
// tool stops and says so, and going direct is always something you ask for.
|
|
12
|
+
import { findTor, isOnionHost, resolveProxy } from './net.js';
|
|
13
|
+
|
|
14
|
+
export const SITE = 'https://www.counterlure.com';
|
|
15
|
+
export const ONION = 'http://4qcqgpa4o6gc7yhqvqvdndx7jeeplsishebyxwf3667kphalxxtvfkad.onion';
|
|
16
|
+
|
|
17
|
+
export class NoTor extends Error {
|
|
18
|
+
constructor(forOnion) {
|
|
19
|
+
super([
|
|
20
|
+
forOnion
|
|
21
|
+
? 'Tor is not running on this computer, so there is no private route to Counterlure.'
|
|
22
|
+
: '--tor was given, but Tor is not running on this computer.',
|
|
23
|
+
'',
|
|
24
|
+
'By default this tool talks only to Counterlure\'s onion service, over Tor. Your network',
|
|
25
|
+
'address then never reaches us: not our edge, not our servers, not our logs.',
|
|
26
|
+
'',
|
|
27
|
+
'Start Tor, then run the command again:',
|
|
28
|
+
' Tor Browser, left open listens on 127.0.0.1:9150',
|
|
29
|
+
' the tor service 127.0.0.1:9050 (apt install tor; brew install tor && brew services start tor)',
|
|
30
|
+
' Tor somewhere else set COUNTERLURE_TOR=host:port',
|
|
31
|
+
'',
|
|
32
|
+
'Or add --direct to use the website instead. Cloudflare, which fronts it, then sees your',
|
|
33
|
+
'network address (we do not store it). --direct --tor sends that through Tor as well.',
|
|
34
|
+
].join('\n'));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// o: parsed options (server, direct, tor, proxy). find: Tor discovery, replaceable in tests.
|
|
39
|
+
export async function resolveRoute(o, { env = process.env, find = findTor } = {}) {
|
|
40
|
+
const custom = o.server || env.COUNTERLURE_URL;
|
|
41
|
+
const server = (custom || (o.direct ? SITE : ONION)).replace(/\/+$/, '');
|
|
42
|
+
let u;
|
|
43
|
+
try { u = new URL(server); } catch { throw new Error(`Not a URL: ${server}`); }
|
|
44
|
+
const onion = isOnionHost(u.hostname);
|
|
45
|
+
const explicit = o.proxy || env.COUNTERLURE_PROXY;
|
|
46
|
+
|
|
47
|
+
let proxy;
|
|
48
|
+
if (onion || o.tor) {
|
|
49
|
+
proxy = explicit && !o.tor ? resolveProxy(explicit) : await find({ env });
|
|
50
|
+
if (!proxy) throw new NoTor(onion);
|
|
51
|
+
if (onion && proxy.protocol === 'http:') throw new Error('An onion address needs a SOCKS proxy (Tor). An HTTP proxy cannot reach it.');
|
|
52
|
+
} else {
|
|
53
|
+
proxy = resolveProxy(o.proxy);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const where = custom ? server : onion ? 'Counterlure onion service' : 'www.counterlure.com';
|
|
57
|
+
const edge = custom ? '' : ', then Cloudflare';
|
|
58
|
+
const how = onion ? 'over Tor'
|
|
59
|
+
: o.tor ? `over Tor${edge}`
|
|
60
|
+
: proxy ? `via proxy ${proxy.host}${edge}`
|
|
61
|
+
: custom ? 'direct' : 'direct, via Cloudflare: it sees your network address';
|
|
62
|
+
return { server, proxy, onion, custom: Boolean(custom), label: `${where} (${how})` };
|
|
63
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Counterlure's CLI server public key. Requests are encrypted to it; replies must be signed by it.
|
|
2
|
+
// Compare the fingerprint with https://www.counterlure.com/#cli and https://www.counterlure.com/api/cli/key
|
|
3
|
+
export const SERVER_FINGERPRINT = 'f21cbaa64b8eeececb0ba13bcf7a8128459e8e46';
|
|
4
|
+
export const SERVER_KEY = `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
|
5
|
+
|
|
6
|
+
xjMEavV30RYJKwYBBAHaRw8BAQdAGTg4igmZsQEUWyIGjtouICfuVuBJUaTD
|
|
7
|
+
wVxqNvBNm6vNGkNvdW50ZXJsdXJlIENMSSBzZXJ2ZXIga2V5wsATBBMWCgCF
|
|
8
|
+
BYJq9XfRAwsJBwkQz3qBKEWejkZFFAAAAAAAHAAgc2FsdEBub3RhdGlvbnMu
|
|
9
|
+
b3BlbnBncGpzLm9yZ7gJoupxmQ32X/MJQHeNxWF4F4g9KooZWSW5ZSx/oaxr
|
|
10
|
+
BRUKCA4MBBYAAgECGQECmwMCHgEWIQTyHLqmS47uzssLoTvPeoEoRZ6ORgAA
|
|
11
|
+
8kIBAOGiowLfyLGz1ygOVtyLwWdm90dYcdC/Vt/xn7ZNn+yyAQC+buXYrcjC
|
|
12
|
+
oDVLvuRhk6uJkfUvMFQgu2Fpn2nqy4fkBM44BGr1d9ESCisGAQQBl1UBBQEB
|
|
13
|
+
B0BZ09Zk9T8mkgMZ9Stez3I2mSckL9LDFC2xRcLAid0yBgMBCAfCvgQYFgoA
|
|
14
|
+
cAWCavV30QkQz3qBKEWejkZFFAAAAAAAHAAgc2FsdEBub3RhdGlvbnMub3Bl
|
|
15
|
+
bnBncGpzLm9yZ4StGotCrmJU8DuLFwGD+HooLvmwc5npAYviavsz13OwApsM
|
|
16
|
+
FiEE8hy6pkuO7s7LC6E7z3qBKEWejkYAAIIfAQC+mQp3IUeqsDzSHBeNUNWM
|
|
17
|
+
qLK9TpwTWOc+ShMm9hlf2QEA0+W3QrIBLzg6wSXioXV1VeIlN3mkahR/dUTu
|
|
18
|
+
Eoo/Rw0=
|
|
19
|
+
=e0Sq
|
|
20
|
+
-----END PGP PUBLIC KEY BLOCK-----`;
|
package/lib/sharp.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// The only place sharp is imported from. Everything else imports it from here.
|
|
2
|
+
//
|
|
3
|
+
// libvips ships decoders for many formats: SVG, GIF, TIFF, HEIF, PDF and more. Each one is a parser
|
|
4
|
+
// that would be fed bytes from a photo of unknown origin, and image parsers are where memory-safety
|
|
5
|
+
// bugs live. Only the three formats Counterlure accepts stay loadable. The rest are blocked before
|
|
6
|
+
// any image is opened, so their decoders are never reached, whatever the file claims to be.
|
|
7
|
+
import sharp from 'sharp';
|
|
8
|
+
|
|
9
|
+
export const FORMATS = ['Jpeg', 'Png', 'Webp'];
|
|
10
|
+
|
|
11
|
+
sharp.block({ operation: ['VipsForeignLoad'] });
|
|
12
|
+
sharp.unblock({ operation: FORMATS.flatMap((f) => [`VipsForeignLoad${f}Buffer`, `VipsForeignLoad${f}File`]) });
|
|
13
|
+
|
|
14
|
+
export default sharp;
|
package/lib/term.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Everything this tool prints goes through here.
|
|
2
|
+
//
|
|
3
|
+
// Replies are signed by the pinned key, so only the Counterlure server can put text on this screen.
|
|
4
|
+
// The screen still must not obey it: a name in a burn notice or a line in a message was typed by
|
|
5
|
+
// someone, and a terminal acts on escape sequences (move the cursor, rewrite a line above, set the
|
|
6
|
+
// window title, and on some terminals worse). So every control character except newline and tab is
|
|
7
|
+
// removed, along with the Unicode marks that reorder text (an address shown right-to-left reads as
|
|
8
|
+
// a different address) and the invisible ones that hide inside it.
|
|
9
|
+
const RANGES = [
|
|
10
|
+
[0x00, 0x08], [0x0b, 0x1f], // C0 controls, keeping tab and newline
|
|
11
|
+
[0x7f, 0x9f], // delete and the C1 controls (0x9b starts an escape sequence by itself)
|
|
12
|
+
[0x061c, 0x061c], [0x200b, 0x200f], [0x2028, 0x202e], [0x2060, 0x2069], [0xfeff, 0xfeff], // reordering and invisible marks
|
|
13
|
+
];
|
|
14
|
+
const unsafe = (c) => RANGES.some(([a, b]) => c >= a && c <= b);
|
|
15
|
+
|
|
16
|
+
export const plain = (s) => Array.from(String(s)).filter((ch) => !unsafe(ch.codePointAt(0))).join('');
|
|
17
|
+
|
|
18
|
+
// Progress, prompts and explanations go to stderr; results go to stdout, so they can be piped.
|
|
19
|
+
export const say = (s) => process.stderr.write(`${plain(s)}\n`);
|
|
20
|
+
export const out = (s) => process.stdout.write(`${plain(s)}\n`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "counterlure-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "Screen photos against the Counterlure face watchlist and file reports from a terminal. Faces are detected locally; traffic is OpenPGP-encrypted to a pinned key.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"bin": { "counterlure": "bin/counterlure.js" },
|
|
8
|
+
"files": ["bin", "lib", "README.md", "SECURITY.md", "LICENSE", "NOTICE"],
|
|
9
|
+
"engines": { "node": ">=22" },
|
|
10
|
+
"scripts": { "test": "node --test" },
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"onnxruntime-node": "1.31.1",
|
|
13
|
+
"openpgp": "6.3.3",
|
|
14
|
+
"sharp": "0.35.5"
|
|
15
|
+
}
|
|
16
|
+
}
|