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
|
@@ -0,0 +1,1210 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// counterlure: query and feed the Counterlure face watchlist from a terminal.
|
|
3
|
+
//
|
|
4
|
+
// signup open an account: username, authenticator, crypto payment. No email, phone or name.
|
|
5
|
+
// check members only. The photo stays on this machine; a 128-value face template is sent.
|
|
6
|
+
// report anyone. Sends one cropped, re-encoded face and the selectors you supply (name, context,
|
|
7
|
+
// handle). Without an account the report is filed unattributed, behind proof of work.
|
|
8
|
+
// inbox members. Messages between you and the Counterlure team; send writes to them.
|
|
9
|
+
// withdraw anyone holding a receipt.
|
|
10
|
+
//
|
|
11
|
+
// By default everything goes to Counterlure's onion service over Tor (lib/route.js), and every
|
|
12
|
+
// request is OpenPGP-encrypted to a pinned server key and padded to a fixed size (lib/proto.js).
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { parseArgs } from 'node:util';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
import { MODEL_VERSION, faceprints } from '../lib/faceprint.js';
|
|
19
|
+
import { ensureModels, importModels, modelStatus, missingModelsText, findLocalModels } from '../lib/models.js';
|
|
20
|
+
import { REPORT_PAD, Refused, call, serverFingerprint } from '../lib/proto.js';
|
|
21
|
+
import { DEFAULT_BITS, MAX_BITS } from '../lib/pow.js';
|
|
22
|
+
import { faceCrop } from '../lib/crop.js';
|
|
23
|
+
import { SERVER_FINGERPRINT } from '../lib/server-key.js';
|
|
24
|
+
import { ONION, SITE, resolveRoute } from '../lib/route.js';
|
|
25
|
+
import { request } from '../lib/net.js';
|
|
26
|
+
import { out, say } from '../lib/term.js';
|
|
27
|
+
import { inspectDir, renderInspect } from '../lib/inspect.js';
|
|
28
|
+
|
|
29
|
+
const VERSION = JSON.parse(fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8')).version;
|
|
30
|
+
const CONTEXTS = ['dating-app', 'social-media', 'event-or-conference', 'work-or-business', 'introduced', 'other'];
|
|
31
|
+
|
|
32
|
+
// Same statement the website requires before a report is accepted.
|
|
33
|
+
const STATEMENT = [
|
|
34
|
+
'I am in contact with this person personally and I am unsure about their intentions.',
|
|
35
|
+
'I am not using this to track an ex-partner or anyone else, and nothing about my report',
|
|
36
|
+
'is based on their nationality or ethnicity.',
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
const HELP = `counterlure ${VERSION}
|
|
40
|
+
|
|
41
|
+
Query and contribute to the Counterlure watchlist of faces tied to suspected approach operations
|
|
42
|
+
against people in tech. Traffic goes to Counterlure's onion service over Tor, and every request is
|
|
43
|
+
OpenPGP-encrypted to a pinned key and padded to a fixed size.
|
|
44
|
+
|
|
45
|
+
Repositories (offline, nothing is sent or executed)
|
|
46
|
+
inspect [DIR] Read a repo you were sent (a take-home, a "fix this bug" invite) before you
|
|
47
|
+
open, install or build it. Flags folder-open tasks, install hooks, dev
|
|
48
|
+
container commands, git hooks, typosquats, hidden URLs, remote eval and
|
|
49
|
+
"turn off your antivirus" instructions. Exit 0 clean, 1 review, 2 do not run.
|
|
50
|
+
|
|
51
|
+
Account
|
|
52
|
+
signup [--user NAME] Open an account: pick a username, link an authenticator app, pay in
|
|
53
|
+
[--plan P] crypto. No email, phone or name is asked for. Resumes where it stopped.
|
|
54
|
+
[--chain ID] --plan pass30 (30 days, renewed by hand) or --plan lifetime (paid once).
|
|
55
|
+
login [--user NAME] Sign in with username and authenticator code (24 h session).
|
|
56
|
+
whoami | logout Show or end the current session (logout also abandons a signup).
|
|
57
|
+
|
|
58
|
+
Messages (members)
|
|
59
|
+
inbox [--all] Read your conversation with the Counterlure team; marks it read.
|
|
60
|
+
send [MESSAGE...] Write to the team. Without MESSAGE, type it (end with a line holding
|
|
61
|
+
[--subject S] only ".") or pipe it in. Replies arrive in your inbox.
|
|
62
|
+
|
|
63
|
+
Faces
|
|
64
|
+
check IMAGE [IMAGE...] Members. Screen the faces in one or more photos against corroborated
|
|
65
|
+
cases and published burn notices. Face detection and the face template
|
|
66
|
+
are computed locally; the photo itself is never sent.
|
|
67
|
+
Photos must be JPEG, PNG or WebP; no other format is opened.
|
|
68
|
+
report IMAGE Anyone. File a report on one face. Sends a tight crop of that face only,
|
|
69
|
+
re-encoded with no metadata, plus the selectors below.
|
|
70
|
+
--name NAME the name they gave you (required)
|
|
71
|
+
--context C where the approach happened: ${CONTEXTS.join(', ')}
|
|
72
|
+
--handle H the profile, handle or URL they used (optional)
|
|
73
|
+
--face N which face, when the photo has more than one (largest is 1)
|
|
74
|
+
--anon file unattributed even when signed in
|
|
75
|
+
--dry-run do everything except send; with --save-crop, inspect what would leave
|
|
76
|
+
--save-crop FILE write the exact crop that is (or would be) sent
|
|
77
|
+
--yes skip the confirmation prompt (you still make the statement)
|
|
78
|
+
withdraw RECEIPT Withdraw a report. The stored crop and face template are destroyed.
|
|
79
|
+
fingerprint IMAGE For AI assistants (the Agent Exchange). Prints the face fingerprints in a
|
|
80
|
+
photo as JSON: 128 numbers per face, computed here, offline. Nothing is
|
|
81
|
+
sent. Paste them into the assistant's check_contact call as faceprints.
|
|
82
|
+
--face N only that face (largest is 1)
|
|
83
|
+
--token send that one fingerprint (not the photo) and print a 30-minute one-time
|
|
84
|
+
code instead, for assistants that take a code. Uses the network route below.
|
|
85
|
+
models Show whether the two face models are installed and verified.
|
|
86
|
+
models import PATH... Bring in model files you downloaded yourself (files or folders).
|
|
87
|
+
Each is accepted only if it matches a pinned SHA-256.
|
|
88
|
+
models --download Fetch the missing models from OpenCV's GitHub (asks first).
|
|
89
|
+
--fetch-models (any command) consent in advance to fetching missing models;
|
|
90
|
+
without it, nothing is downloaded unless you type yes.
|
|
91
|
+
key Print the pinned server key fingerprint and onion address.
|
|
92
|
+
|
|
93
|
+
Organization (Enterprise Cluster Defense — zero-knowledge employee anonymity)
|
|
94
|
+
org enroll CODE Enroll this device anonymously using your organization's code.
|
|
95
|
+
No employee name, email or identity is ever recorded.
|
|
96
|
+
org check IMAGE [...] Screen faces against both your organization's alerts and the global
|
|
97
|
+
Counterlure pool. Photos never leave your machine.
|
|
98
|
+
org report IMAGE File a zero-knowledge biometric report into your organization's private
|
|
99
|
+
[--context C] namespace (128-d face vector only: no photo, no name, no identity).
|
|
100
|
+
[--face N] [--yes] Escalates automatically when 3+ distinct staff report the same face.
|
|
101
|
+
org inbox [--all] Read private alerts (including coordinated-attack notices).
|
|
102
|
+
org status Show your organization's aggregate threat status and unread alerts.
|
|
103
|
+
org withdraw RECEIPT Withdraw an organization report by its CLO-... receipt.
|
|
104
|
+
org leave Delete the local anonymous device credential.
|
|
105
|
+
|
|
106
|
+
Network
|
|
107
|
+
(default) Counterlure's onion service through the Tor running on this computer
|
|
108
|
+
(Tor Browser on 9150, or the tor service on 9050; COUNTERLURE_TOR=host:port
|
|
109
|
+
elsewhere). Your network address never reaches us.
|
|
110
|
+
--direct Use the website (www.counterlure.com) instead. Cloudflare, in front of
|
|
111
|
+
it, sees your network address unless you add --tor or --proxy.
|
|
112
|
+
--tor With --direct: reach the website through Tor.
|
|
113
|
+
--proxy URL socks5h://host:port or http://host:port (also COUNTERLURE_PROXY).
|
|
114
|
+
Without --direct it must be a SOCKS proxy into Tor.
|
|
115
|
+
--server URL a different server (also COUNTERLURE_URL)
|
|
116
|
+
|
|
117
|
+
Output
|
|
118
|
+
--json machine-readable output for check, report and inbox
|
|
119
|
+
|
|
120
|
+
Reports filed without an account carry a proof-of-work stamp (a few seconds of CPU), count as a
|
|
121
|
+
single source however many are filed, and never return match results.
|
|
122
|
+
`;
|
|
123
|
+
|
|
124
|
+
const dirs = {
|
|
125
|
+
config: process.env.COUNTERLURE_HOME || (process.platform === 'win32'
|
|
126
|
+
? path.join(process.env.APPDATA || os.homedir(), 'counterlure')
|
|
127
|
+
: path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'counterlure')),
|
|
128
|
+
};
|
|
129
|
+
dirs.session = path.join(dirs.config, 'session.json');
|
|
130
|
+
dirs.signup = path.join(dirs.config, 'signup.json');
|
|
131
|
+
dirs.org = path.join(dirs.config, 'org.json');
|
|
132
|
+
dirs.models = process.env.COUNTERLURE_MODELS || path.join(dirs.config, 'models');
|
|
133
|
+
|
|
134
|
+
// Saved sessions and signups are tied to the server key they came from (the key is the server's
|
|
135
|
+
// identity). Pointed at another server, this tool does not find them, so a token never goes to a
|
|
136
|
+
// server it was not issued by. Files written before this was recorded belong to the pinned key.
|
|
137
|
+
let trustedKey = SERVER_FINGERPRINT.toLowerCase();
|
|
138
|
+
|
|
139
|
+
// Written whole or not at all: to a temporary file, private from its first byte, then renamed.
|
|
140
|
+
function writePrivate(file, data) {
|
|
141
|
+
fs.mkdirSync(dirs.config, { recursive: true, mode: 0o700 });
|
|
142
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
143
|
+
try {
|
|
144
|
+
fs.writeFileSync(tmp, JSON.stringify({ ...data, key: trustedKey }), { mode: 0o600, flag: 'wx' });
|
|
145
|
+
fs.renameSync(tmp, file);
|
|
146
|
+
} finally {
|
|
147
|
+
fs.rmSync(tmp, { force: true });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function readUnexpired(file) {
|
|
151
|
+
try {
|
|
152
|
+
const s = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
153
|
+
if (new Date(s.expiresAt) > new Date() && (s.key || SERVER_FINGERPRINT).toLowerCase() === trustedKey) return s;
|
|
154
|
+
} catch {}
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
const saveSession = (s) => writePrivate(dirs.session, s);
|
|
158
|
+
const loadSession = () => readUnexpired(dirs.session);
|
|
159
|
+
const forgetSession = () => fs.rmSync(dirs.session, { force: true });
|
|
160
|
+
// A signup in progress: the short-lived token that lets it resume. Nothing else is kept.
|
|
161
|
+
const saveSignup = (s) => writePrivate(dirs.signup, s);
|
|
162
|
+
const loadSignup = () => readUnexpired(dirs.signup);
|
|
163
|
+
const forgetSignup = () => fs.rmSync(dirs.signup, { force: true });
|
|
164
|
+
const saveOrg = (s) => writePrivate(dirs.org, s);
|
|
165
|
+
function loadOrg() {
|
|
166
|
+
try {
|
|
167
|
+
const s = JSON.parse(fs.readFileSync(dirs.org, 'utf8'));
|
|
168
|
+
if (s?.orgToken && (s.key || SERVER_FINGERPRINT).toLowerCase() === trustedKey) return s;
|
|
169
|
+
} catch {}
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
const forgetOrg = () => fs.rmSync(dirs.org, { force: true });
|
|
173
|
+
|
|
174
|
+
const when = (d) => new Date(d).toLocaleString();
|
|
175
|
+
// How often to ask whether a payment has arrived (shorter only in tests).
|
|
176
|
+
const POLL_MS = Number(process.env.COUNTERLURE_POLL_MS) || 30_000;
|
|
177
|
+
// Rechecks of a pasted transaction ID; the same variable shortens both for tests.
|
|
178
|
+
const CONFIRM_POLL_MS = Number(process.env.COUNTERLURE_POLL_MS) || 60_000;
|
|
179
|
+
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
|
|
180
|
+
|
|
181
|
+
// One reader for every prompt, so text typed or piped ahead (several answers at once, a pasted
|
|
182
|
+
// message) is kept for the next prompt instead of lost. On a terminal, input is read raw, so hide
|
|
183
|
+
// can keep a code off the screen. Resolves null at end of input.
|
|
184
|
+
let pending = '', stdinEnded = false;
|
|
185
|
+
function prompt(question, { hide = false } = {}) {
|
|
186
|
+
const stdin = process.stdin, tty = Boolean(stdin.isTTY);
|
|
187
|
+
if (question) process.stderr.write(question);
|
|
188
|
+
return new Promise((ok, no) => {
|
|
189
|
+
let line = '';
|
|
190
|
+
const finish = (err, v) => {
|
|
191
|
+
stdin.off('data', onData); stdin.off('end', onEnd);
|
|
192
|
+
if (tty) stdin.setRawMode(false);
|
|
193
|
+
stdin.pause();
|
|
194
|
+
stdin.unref?.(); // an open pipe must not keep the process alive once the last prompt is answered
|
|
195
|
+
if (err) no(err); else ok(v);
|
|
196
|
+
};
|
|
197
|
+
const feed = () => {
|
|
198
|
+
while (pending.length) {
|
|
199
|
+
const c = pending[0];
|
|
200
|
+
pending = pending.slice(1);
|
|
201
|
+
if (c === '\n' || (tty && c === '\r')) {
|
|
202
|
+
if (tty) process.stderr.write('\n');
|
|
203
|
+
return finish(null, line.replace(/\r$/, '')), true;
|
|
204
|
+
}
|
|
205
|
+
if (tty) {
|
|
206
|
+
if (c === '\u0003') { process.stderr.write('\n'); return finish(new Error('cancelled')), true; }
|
|
207
|
+
if (c === '\u0004' && !line) { process.stderr.write('\n'); return finish(null, null), true; }
|
|
208
|
+
if (c === '\u007f' || c === '\b') { if (line) { line = line.slice(0, -1); if (!hide) process.stderr.write('\b \b'); } continue; }
|
|
209
|
+
if (c === '\u001b') { pending = pending.replace(/^\[[0-9;]*[A-Za-z~]/, ''); continue; } // arrow keys and the like
|
|
210
|
+
if (!hide) process.stderr.write(c);
|
|
211
|
+
}
|
|
212
|
+
line += c;
|
|
213
|
+
}
|
|
214
|
+
return false;
|
|
215
|
+
};
|
|
216
|
+
const onData = (d) => { pending += d; feed(); };
|
|
217
|
+
const onEnd = () => { stdinEnded = true; finish(null, line || null); };
|
|
218
|
+
if (feed()) return;
|
|
219
|
+
if (stdinEnded) return finish(null, line || null);
|
|
220
|
+
if (tty) stdin.setRawMode(true);
|
|
221
|
+
stdin.setEncoding('utf8');
|
|
222
|
+
stdin.on('data', onData);
|
|
223
|
+
stdin.once('end', onEnd);
|
|
224
|
+
stdin.ref?.();
|
|
225
|
+
stdin.resume();
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
const ask = async (q, opts) => (await prompt(q, opts) ?? '').trim();
|
|
229
|
+
|
|
230
|
+
function level(m) {
|
|
231
|
+
if (m.source === 'exchange') {
|
|
232
|
+
return `${m.level === 'strong' ? 'STRONG POSSIBLE MATCH' : 'possible match'} with a face independently reported by ${m.reporters} sources through the Agent Exchange and confirmed by a Counterlure reviewer`;
|
|
233
|
+
}
|
|
234
|
+
if (m.source === 'org-campaign') {
|
|
235
|
+
return `${m.level === 'strong' ? 'STRONG MATCH' : 'possible match'} with ACTIVE CAMPAIGN TARGETING YOUR ORGANIZATION (${m.caseRef}, ${m.reporters} distinct staff reports) — please report this contact to your security team`;
|
|
236
|
+
}
|
|
237
|
+
const what = m.source === 'burn-notice'
|
|
238
|
+
? `burn notice: ${m.name}${m.aliases?.length ? ` (also: ${m.aliases.join(', ')})` : ''}`
|
|
239
|
+
: `a face reported by ${m.reporters} independent sources`;
|
|
240
|
+
return `${m.level === 'strong' ? 'STRONG POSSIBLE MATCH' : 'possible match'} with ${what}`;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Model consent. Verified copies already on this computer are used first (see lib/models.js). If any
|
|
244
|
+
// are still missing, nothing is fetched until the person says so: they are shown where to get the
|
|
245
|
+
// files themselves, and asked. Without a terminal to ask on, only --fetch-models counts as yes.
|
|
246
|
+
const modelPolicy = { fetch: false, route: '' };
|
|
247
|
+
async function modelConsent(missing) {
|
|
248
|
+
say(missingModelsText(missing, dirs.models));
|
|
249
|
+
if (modelPolicy.fetch) { say('--fetch-models given: downloading.'); return true; }
|
|
250
|
+
if (!process.stdin.isTTY) {
|
|
251
|
+
say('No terminal to ask on, so nothing was downloaded. Import the files yourself, or rerun with --fetch-models.');
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
const a = (await ask(`Download them now from GitHub over ${modelPolicy.route || 'the configured route'}? Type yes to proceed: `)).toLowerCase();
|
|
255
|
+
if (a === 'yes' || a === 'y') return true;
|
|
256
|
+
say('Nothing was downloaded. When you have the files: counterlure models import FILE-OR-FOLDER ...');
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
const models = (net) => ensureModels(dirs.models, { ...net, log: say, consent: modelConsent });
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
// Calls that need proof of work: begin at the default, and do the extra work once if the server
|
|
263
|
+
// asks for more (it raises the bar when it is under load).
|
|
264
|
+
async function callWithWork(server, op, args, net, extra = {}) {
|
|
265
|
+
let bits = DEFAULT_BITS;
|
|
266
|
+
for (let attempt = 0; ; attempt++) {
|
|
267
|
+
try {
|
|
268
|
+
return await call(server, op, args, { ...net, ...extra, pow: bits, onWork: (b) => say(`Computing proof of work (${b} bits)...`) });
|
|
269
|
+
} catch (e) {
|
|
270
|
+
const need = e instanceof Refused ? e.reply.powBits : undefined;
|
|
271
|
+
if (!need || attempt > 0 || need === bits) throw e;
|
|
272
|
+
if (need > MAX_BITS) throw new Error(`The server is asking for ${need} bits of proof of work, more than this tool will do. Try later.`);
|
|
273
|
+
bits = need;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Reads a photo and finds its faces. Only JPEG, PNG and WebP are decoded (lib/sharp.js).
|
|
279
|
+
async function facesIn(file) {
|
|
280
|
+
let input;
|
|
281
|
+
try {
|
|
282
|
+
input = fs.readFileSync(file);
|
|
283
|
+
} catch (e) {
|
|
284
|
+
throw new Error(`Could not read ${file}: ${e.code || e.message}`);
|
|
285
|
+
}
|
|
286
|
+
try {
|
|
287
|
+
const faces = await faceprints(input, { modelsDir: dirs.models });
|
|
288
|
+
return { input, faces, skipped: faces.skipped || 0 };
|
|
289
|
+
} catch (e) {
|
|
290
|
+
if (/unsupported image format/i.test(e.message)) throw new Error(`${file} is not a JPEG, PNG or WebP image.`);
|
|
291
|
+
throw e;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const isTooSmall = (box) => box.w < 64 || box.h < 64;
|
|
296
|
+
|
|
297
|
+
async function check(s, files, net, server, json) {
|
|
298
|
+
await models(net);
|
|
299
|
+
const results = [];
|
|
300
|
+
for (const file of files) {
|
|
301
|
+
let found;
|
|
302
|
+
try {
|
|
303
|
+
found = await facesIn(file);
|
|
304
|
+
} catch (e) {
|
|
305
|
+
results.push({ file, faces: [], error: e.message });
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
const { faces, skipped } = found;
|
|
309
|
+
if (!faces.length) { results.push({ file, faces: [], note: 'no face found' }); continue; }
|
|
310
|
+
const usable = faces.filter((f) => !isTooSmall(f.box));
|
|
311
|
+
let r = { results: [] };
|
|
312
|
+
if (usable.length) {
|
|
313
|
+
r = await call(server, 'check', { token: s.token, model: MODEL_VERSION, faces: usable.map((f) => f.embedding) }, net);
|
|
314
|
+
}
|
|
315
|
+
let uIdx = 0;
|
|
316
|
+
results.push({
|
|
317
|
+
file,
|
|
318
|
+
...(r.checksLeft !== undefined ? { checksLeft: r.checksLeft } : {}),
|
|
319
|
+
...(skipped ? { skipped } : {}),
|
|
320
|
+
faces: faces.map((f) => (isTooSmall(f.box)
|
|
321
|
+
? { box: f.box, refused: `face too small (${f.box.w}x${f.box.h}px, minimum 64x64px)`, matches: [] }
|
|
322
|
+
: { box: f.box, matches: dedupeOrgMatches(r.results?.[uIdx++] ?? []) })),
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
if (json) return out(JSON.stringify(results, null, 2));
|
|
326
|
+
let any = false;
|
|
327
|
+
for (const r of results) {
|
|
328
|
+
out(`\n${r.file}`);
|
|
329
|
+
if (r.error) { out(` Error: ${r.error}`); continue; }
|
|
330
|
+
if (!r.faces.length) { out(' No face found. Use a clearer, front-facing photo.'); continue; }
|
|
331
|
+
if (r.skipped) out(` Note: ${r.skipped} additional face${r.skipped === 1 ? '' : 's'} skipped (at most 5 largest faces checked per photo).`);
|
|
332
|
+
r.faces.forEach((f, i) => {
|
|
333
|
+
const where = `face ${i + 1} at ${f.box.x},${f.box.y} (${f.box.w}x${f.box.h}px)`;
|
|
334
|
+
if (f.refused) return out(` ${where}: refused — ${f.refused}`);
|
|
335
|
+
if (!f.matches.length) return out(` ${where}: no match`);
|
|
336
|
+
any = true;
|
|
337
|
+
out(` ${where}:`);
|
|
338
|
+
for (const m of f.matches) out(` ${level(m)}`);
|
|
339
|
+
});
|
|
340
|
+
if (r.checksLeft !== undefined) out(` (${r.checksLeft} checks left today)`);
|
|
341
|
+
}
|
|
342
|
+
out(any
|
|
343
|
+
? '\nA match is a lead, not an identification. Faces resemble each other. Corroborate through other\nmeans before acting, and never harass or publish anyone on the strength of this result.\nIf you have something new on this person, file it: counterlure report IMAGE --name ...'
|
|
344
|
+
: '\nNo match is not a clearance: only faces already reported can match.');
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// The Agent Exchange takes face fingerprints, never photos. Offline unless a code is asked for.
|
|
348
|
+
async function fingerprintCmd(file, o, routeFor) {
|
|
349
|
+
const net = o.token ? { proxy: (await routeFor()).proxy } : {};
|
|
350
|
+
if (o.token) await models(net);
|
|
351
|
+
else {
|
|
352
|
+
await ensureModels(dirs.models, {
|
|
353
|
+
log: say,
|
|
354
|
+
consent: async (missing) => {
|
|
355
|
+
say(missingModelsText(missing, dirs.models));
|
|
356
|
+
say(' Fetch them with: counterlure models --download');
|
|
357
|
+
return false;
|
|
358
|
+
},
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
const { faces, skipped } = await facesIn(file);
|
|
362
|
+
if (!faces.length) throw new Error('No face found. Use a clearer, front-facing photo.');
|
|
363
|
+
let picked = faces.map((f, i) => ({ face: i + 1, box: f.box, vector: f.embedding.map((x) => Math.round(x * 1e6) / 1e6) }));
|
|
364
|
+
if (o.face !== undefined) {
|
|
365
|
+
const n = Number(o.face);
|
|
366
|
+
if (!Number.isInteger(n) || n < 1 || n > faces.length) throw new Error(`--face must be 1 to ${faces.length} for this photo.`);
|
|
367
|
+
picked = [picked[n - 1]];
|
|
368
|
+
}
|
|
369
|
+
if (!o.token) {
|
|
370
|
+
out(JSON.stringify({ model: MODEL_VERSION, ...(skipped ? { skipped } : {}), faceprints: picked }, null, o.json ? 0 : 2));
|
|
371
|
+
if (!o.json && picked.length > 1) say(`${picked.length} faces. Pick one with --face N (largest is 1).`);
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
if (picked.length > 1) throw new Error(`${picked.length} faces in this photo. Choose one with --face N (largest is 1).`);
|
|
375
|
+
const { server } = await routeFor();
|
|
376
|
+
const r = await request(`${server.replace(/[/]$/, '')}/api/agents/fp`, {
|
|
377
|
+
method: 'POST',
|
|
378
|
+
body: JSON.stringify({ vector: picked[0].vector, model: MODEL_VERSION }),
|
|
379
|
+
headers: { 'content-type': 'application/json' },
|
|
380
|
+
proxy: net.proxy,
|
|
381
|
+
maxBytes: 16 * 1024,
|
|
382
|
+
});
|
|
383
|
+
let data = {};
|
|
384
|
+
try { data = JSON.parse(r.body.toString('utf8')); } catch {}
|
|
385
|
+
if (r.status !== 200 || typeof data.fp_token !== 'string') throw new Error(data.error || `The server refused the fingerprint (HTTP ${r.status}).`);
|
|
386
|
+
if (o.json) return out(JSON.stringify({ fp_token: data.fp_token, expires_in_seconds: data.expires_in_seconds, model: data.model }));
|
|
387
|
+
out(data.fp_token);
|
|
388
|
+
say(`One-time code, valid ${Math.round((data.expires_in_seconds || 1800) / 60)} minutes. It holds the fingerprint only.`);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
async function report(file, o, s, net, route) {
|
|
392
|
+
// Validate everything local before spending CPU on models and proof of work.
|
|
393
|
+
const org = loadOrg();
|
|
394
|
+
if (org) {
|
|
395
|
+
say(`warning: This device is enrolled in ${org.orgName}. "counterlure report" submits a cropped face photo to the PUBLIC Counterlure intake, not your organization's private namespace. Use "counterlure org report IMAGE" for private organization reporting.`);
|
|
396
|
+
if (!o.yes && !o['dry-run'] && !process.stdin.isTTY) {
|
|
397
|
+
throw new Error(`This device is enrolled in ${org.orgName} and "counterlure report" goes to the public intake. Re-run with --yes to confirm, or use: counterlure org report IMAGE`);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
const asMember = Boolean(s) && !o.anon;
|
|
401
|
+
const name = (o.name ?? (process.stdin.isTTY ? await ask('Name they gave you: ') : '')).trim();
|
|
402
|
+
if (name.length < 2 || name.length > 120) throw new Error('--name is required: the name they gave you (2 to 120 characters).');
|
|
403
|
+
const context = o.context || 'other';
|
|
404
|
+
if (!CONTEXTS.includes(context)) throw new Error(`--context must be one of: ${CONTEXTS.join(', ')}`);
|
|
405
|
+
const handle = o.handle?.trim() || undefined;
|
|
406
|
+
if (handle && handle.length > 200) throw new Error('--handle is limited to 200 characters.');
|
|
407
|
+
if (!o.yes && !o['dry-run'] && !process.stdin.isTTY) throw new Error('No terminal to confirm on. Re-run with --yes to make the statement non-interactively.');
|
|
408
|
+
|
|
409
|
+
await models(net);
|
|
410
|
+
const { input, faces } = await facesIn(file);
|
|
411
|
+
if (!faces.length) throw new Error('No face found. Use a clearer, front-facing photo.');
|
|
412
|
+
const list = () => faces.map((f, i) => ` ${i + 1}: at ${f.box.x},${f.box.y} (${f.box.w}x${f.box.h}px)`).join('\n');
|
|
413
|
+
const n = o.face === undefined ? 1 : Number(o.face);
|
|
414
|
+
if (o.face === undefined && faces.length > 1) throw new Error(`${faces.length} faces in this photo. Pick one with --face N:\n${list()}`);
|
|
415
|
+
if (!Number.isInteger(n) || n < 1 || n > faces.length) throw new Error(`--face must be between 1 and ${faces.length}:\n${list()}`);
|
|
416
|
+
const face = faces[n - 1];
|
|
417
|
+
if (isTooSmall(face.box)) throw new Error(`Face is too small (${face.box.w}x${face.box.h}px). Use a clearer photo where the face is at least 64x64px.`);
|
|
418
|
+
const crop = await faceCrop(input, face.box, faces.filter((f) => f !== face).map((f) => f.box));
|
|
419
|
+
if (o['save-crop']) fs.writeFileSync(o['save-crop'], crop.jpeg, { mode: 0o600 });
|
|
420
|
+
|
|
421
|
+
say([
|
|
422
|
+
'',
|
|
423
|
+
'Report',
|
|
424
|
+
` Subject face ${n} of ${faces.length} in ${path.basename(file)} (${face.box.w}x${face.box.h}px${face.box.w < 64 ? ', small: may be rejected' : ''})`,
|
|
425
|
+
` Name given ${name}`,
|
|
426
|
+
` Context ${context}`,
|
|
427
|
+
` Handle ${handle || '-'}`,
|
|
428
|
+
` Leaves here ${crop.width}x${crop.height} JPEG of that face only, no metadata (${Math.round(crop.jpeg.length / 1024)} KB)`,
|
|
429
|
+
` Attribution ${asMember ? `member ${s.username}: counts once for you, and you are told if the case is acted on` : 'none: filed as the shared anonymous source; no match result comes back'}`,
|
|
430
|
+
` Route ${route.label}`,
|
|
431
|
+
'',
|
|
432
|
+
'Statement',
|
|
433
|
+
...STATEMENT.map((l) => ` ${l}`),
|
|
434
|
+
'',
|
|
435
|
+
].join('\n'));
|
|
436
|
+
if (o['dry-run']) return say(`Dry run: nothing sent.${o['save-crop'] ? ` Crop written to ${o['save-crop']}.` : ''}`);
|
|
437
|
+
const confirmPrompt = org
|
|
438
|
+
? 'Type "yes" to confirm sending to the PUBLIC Counterlure intake and make this statement: '
|
|
439
|
+
: 'Type "yes" to make this statement and file the report: ';
|
|
440
|
+
if (!o.yes && (await ask(confirmPrompt)).toLowerCase() !== 'yes') throw new Error('Not filed.');
|
|
441
|
+
|
|
442
|
+
const args = { name, context, handle, photo: crop.jpeg.toString('base64'), attest: true };
|
|
443
|
+
let r;
|
|
444
|
+
if (asMember) r = await call(route.server, 'report', { ...args, token: s.token }, { ...net, padTo: REPORT_PAD });
|
|
445
|
+
else r = await callWithWork(route.server, 'report', args, net, { padTo: REPORT_PAD });
|
|
446
|
+
if (o.json) return out(JSON.stringify({ receipt: r.receipt, attributedTo: r.attributedTo, ...(r.notice ? { notice: r.notice } : {}) }));
|
|
447
|
+
out(`\nFiled. Receipt: ${r.receipt}`);
|
|
448
|
+
out('Keep the receipt offline. It is the only way to withdraw this report, and this tool does not store it.');
|
|
449
|
+
// A lapsed 30-day pass: the server files the report but does not link it to the inbox, and says why.
|
|
450
|
+
if (r.notice) out(r.notice);
|
|
451
|
+
else if (!r.attributedTo) out('Filed unattributed: nobody can contact you about it, and it adds weight only alongside other sources.');
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// ------------------------------------------------------------------ signup
|
|
455
|
+
|
|
456
|
+
const indent = (text, by = ' ') => text.replace(/\n+$/, '').split('\n').map((l) => by + l).join('\n');
|
|
457
|
+
|
|
458
|
+
function showAuthenticator(st) {
|
|
459
|
+
say([
|
|
460
|
+
'',
|
|
461
|
+
'Step 1 of 3: link an authenticator app',
|
|
462
|
+
' Scan this with an authenticator app (Aegis, Raivo, 2FAS, Google Authenticator, 1Password...).',
|
|
463
|
+
' It is the only way into your account: there is no email or password to reset.',
|
|
464
|
+
'',
|
|
465
|
+
indent(st.qrText),
|
|
466
|
+
'',
|
|
467
|
+
` Or enter this key by hand: ${st.secret.replace(/(.{4})/g, '$1 ').trim()}`,
|
|
468
|
+
` (account: ${st.username}, time-based, 6 digits, 30 seconds)`,
|
|
469
|
+
'',
|
|
470
|
+
].join('\n'));
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
const usd = (n) => `$${Number(n).toLocaleString('en-US')}`;
|
|
474
|
+
const planName = (id) => (id === 'pass30' ? '30-day pass' : id === 'lifetime' ? 'lifetime account' : id);
|
|
475
|
+
const RENEW_URL = `${SITE}/join?renew`;
|
|
476
|
+
|
|
477
|
+
// One choice from a short numbered list: the flag if given, otherwise a prompt that takes the number
|
|
478
|
+
// or the id. Enter picks the first entry only when `enterPicksFirst` and a person is at the terminal.
|
|
479
|
+
async function chooseFrom(list, { given, flag, question, enterPicksFirst = false }) {
|
|
480
|
+
const byId = (a) => list.find((x) => x.id.toLowerCase() === String(a).trim().toLowerCase());
|
|
481
|
+
if (given) {
|
|
482
|
+
const hit = byId(given);
|
|
483
|
+
if (!hit) throw new Error(`--${flag} must be one of: ${list.map((x) => x.id).join(', ')}`);
|
|
484
|
+
return hit.id;
|
|
485
|
+
}
|
|
486
|
+
for (let tries = 0; tries < 3; tries++) {
|
|
487
|
+
const a = await ask(question);
|
|
488
|
+
if (!a && enterPicksFirst && process.stdin.isTTY) return list[0].id;
|
|
489
|
+
const hit = list[Number(a) - 1] || byId(a);
|
|
490
|
+
if (hit) return hit.id;
|
|
491
|
+
if (!process.stdin.isTTY) break;
|
|
492
|
+
}
|
|
493
|
+
throw new Error(`Choose with: counterlure signup --${flag} ${list[0]?.id || 'ID'}`);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// Step 2: which plan (a 30-day pass or lifetime), then which coin. A server that predates plans
|
|
497
|
+
// sends none, and the order is placed without one, as before.
|
|
498
|
+
async function pickPlanAndChain(o, sign, server, net) {
|
|
499
|
+
const opts = await call(server, 'pay_options', {}, net);
|
|
500
|
+
const plans = [...(opts.plans || [])].sort((a, b) => (a.days == null) - (b.days == null)); // the pass first, as on the website
|
|
501
|
+
say([
|
|
502
|
+
'',
|
|
503
|
+
'Step 2 of 3: choose a plan and how to pay',
|
|
504
|
+
' Paid in crypto. No card, no name, no address. Nothing is ever charged automatically.',
|
|
505
|
+
].join('\n'));
|
|
506
|
+
let plan;
|
|
507
|
+
if (plans.length) {
|
|
508
|
+
say([
|
|
509
|
+
'',
|
|
510
|
+
...plans.map((p, i) => p.days
|
|
511
|
+
? ` ${i + 1}. ${p.days}-day pass ${usd(p.priceUsd)}. Renew it by hand when it ends. (--plan ${p.id})`
|
|
512
|
+
: ` ${i + 1}. Lifetime ${usd(p.priceUsd)}, paid once. (--plan ${p.id})`),
|
|
513
|
+
].join('\n'));
|
|
514
|
+
// A signup whose last address expired keeps the plan it chose, unless --plan says otherwise.
|
|
515
|
+
const remembered = !o.plan && plans.some((p) => p.id === sign.plan) ? sign.plan : undefined;
|
|
516
|
+
if (remembered) say(`\n Plan: ${planName(remembered)} (chosen earlier; --plan changes it).`);
|
|
517
|
+
plan = await chooseFrom(plans, { given: o.plan || remembered, flag: 'plan', question: `Plan (1-${plans.length}, Enter for 1): `, enterPicksFirst: true });
|
|
518
|
+
} else {
|
|
519
|
+
say(` Membership: ${usd(opts.priceUsd)}, paid once.`);
|
|
520
|
+
}
|
|
521
|
+
say([
|
|
522
|
+
'',
|
|
523
|
+
opts.autoDetect ? ` You get a payment address made for your account alone, valid for ${span(opts.addressMinutes * 60000)}.` : null,
|
|
524
|
+
...opts.chains.map((c, i) => ` ${i + 1}. ${c.label} (--chain ${c.id})`),
|
|
525
|
+
'',
|
|
526
|
+
].filter((l) => l !== null).join('\n'));
|
|
527
|
+
const chain = await chooseFrom(opts.chains, { given: o.chain, flag: 'chain', question: `Pay with (1-${opts.chains.length}): ` });
|
|
528
|
+
return { plan, chain };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// "1 h 05 min", "12 min": what is left of an address's window.
|
|
532
|
+
function span(ms) {
|
|
533
|
+
const m = Math.max(1, Math.ceil(ms / 60000));
|
|
534
|
+
return m >= 60 ? `${Math.floor(m / 60)} h ${String(m % 60).padStart(2, '0')} min` : `${m} min`;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// When the order's address stops taking payments, on this computer's clock. The server says what its
|
|
538
|
+
// own clock read (serverNow), so a computer whose clock is off still counts down correctly.
|
|
539
|
+
const deadline = (st) => Date.now() + (Date.parse(st.expiresAt) - Date.parse(st.serverNow || new Date().toISOString()));
|
|
540
|
+
|
|
541
|
+
function showOrder(st) {
|
|
542
|
+
if (!st.autoDetect) {
|
|
543
|
+
return say([
|
|
544
|
+
'',
|
|
545
|
+
'Step 3 of 3: pay',
|
|
546
|
+
st.plan ? ` For ${planName(st.plan)}` : null,
|
|
547
|
+
` Send exactly ${st.amount} ${st.symbol}`,
|
|
548
|
+
` on ${st.chainLabel}`,
|
|
549
|
+
` to ${st.address}`,
|
|
550
|
+
'',
|
|
551
|
+
' The exact amount, down to the last digit, is how this payment is matched to your signup.',
|
|
552
|
+
' Send it in one transaction and do not round it. Sending from an exchange is fine.',
|
|
553
|
+
st.expiresAt ? ` The amount is held for you until ${when(st.expiresAt)}.` : '',
|
|
554
|
+
'',
|
|
555
|
+
indent(st.qrText),
|
|
556
|
+
'',
|
|
557
|
+
].filter((l) => l !== null).join('\n'));
|
|
558
|
+
}
|
|
559
|
+
const end = deadline(st);
|
|
560
|
+
say([
|
|
561
|
+
'',
|
|
562
|
+
'Step 3 of 3: pay',
|
|
563
|
+
st.plan ? ` For ${planName(st.plan)}` : null,
|
|
564
|
+
` Send ${st.amount} ${st.symbol}`,
|
|
565
|
+
` on ${st.chainLabel}`,
|
|
566
|
+
` to ${st.address}`,
|
|
567
|
+
` send before ${when(end)} (${span(end - Date.now())} from now)`,
|
|
568
|
+
'',
|
|
569
|
+
' This address was made for your account alone, so the payment is found by itself: no',
|
|
570
|
+
' transaction ID needed. Send at least the amount, from your own wallet or an exchange.',
|
|
571
|
+
` Do not send to this address after ${when(end)}. After that, run counterlure signup again`,
|
|
572
|
+
' for a new address.',
|
|
573
|
+
'',
|
|
574
|
+
indent(st.qrText),
|
|
575
|
+
'',
|
|
576
|
+
].filter((l) => l !== null).join('\n'));
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// Waits for a payment to the member's own address to be found, asking the server every 30 s.
|
|
580
|
+
// Returns the next state (done, or chain when the address expired with nothing sent), or null to stop.
|
|
581
|
+
async function awaitPayment(st, sign, server, net) {
|
|
582
|
+
const end = deadline(st);
|
|
583
|
+
let warned = false;
|
|
584
|
+
let seen = '';
|
|
585
|
+
say('Waiting for the payment to arrive. This can take a few minutes after it is sent. Ctrl-C stops;');
|
|
586
|
+
say(`${resumeHint.replace('Run: ', 'later run ')}`);
|
|
587
|
+
// Up to the end of the window plus 3 hours for a payment already seen to confirm.
|
|
588
|
+
for (const stop = end + 3 * 3600_000; Date.now() < stop;) {
|
|
589
|
+
await sleep(POLL_MS);
|
|
590
|
+
let r;
|
|
591
|
+
try {
|
|
592
|
+
r = await call(server, 'signup_state', { signupToken: sign.signupToken }, net);
|
|
593
|
+
} catch (e) {
|
|
594
|
+
if (e instanceof Refused) throw e;
|
|
595
|
+
say(`Could not reach the server (${e.message}). Trying again.`);
|
|
596
|
+
continue;
|
|
597
|
+
}
|
|
598
|
+
// The window ended while waiting: the server is back at choosing a coin. Name the address here,
|
|
599
|
+
// once, so the generic notice in the main loop is not repeated.
|
|
600
|
+
if (r.step === 'chain') {
|
|
601
|
+
say(`\nThe address ${st.address} has expired. Do NOT send to it.`);
|
|
602
|
+
return { ...r, lastOrderExpired: false };
|
|
603
|
+
}
|
|
604
|
+
if (r.step !== 'pay') return r;
|
|
605
|
+
if (r.status === 'review') return r;
|
|
606
|
+
if (r.detected) {
|
|
607
|
+
const now = `${r.detected.amount} ${r.detected.chainLabel}`;
|
|
608
|
+
if (now !== seen) say(`Payment seen: ${now}. Waiting for it to confirm on the network.`);
|
|
609
|
+
seen = now;
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
const left = end - Date.now();
|
|
613
|
+
if (left <= 0 || r.addressExpired || !r.address) {
|
|
614
|
+
say(`\nThe address ${st.address} has expired. Do NOT send to it.`);
|
|
615
|
+
return r;
|
|
616
|
+
}
|
|
617
|
+
if (left < 10 * 60000 && !warned) {
|
|
618
|
+
warned = true;
|
|
619
|
+
say(`Less than ${span(left)} left on this address. If your payment is not on its way, do not send it now: wait, and run counterlure signup again for a new address.`);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
say(`Nothing confirmed yet. ${resumeHint}`);
|
|
623
|
+
return null;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const resumeHint = 'Run: counterlure signup (it picks up where it stopped)';
|
|
627
|
+
|
|
628
|
+
function reviewed(r) {
|
|
629
|
+
say(`\nThe payment needs a person to look at it${r.reason ? ` (${r.reason})` : ''}. That usually takes under a day.\n${resumeHint}\nTo add a note, open the website's inbox once your account is open, or wait for the review.`);
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// Payment: ask for the transaction ID, then check until it is confirmed or needs a person.
|
|
634
|
+
async function settle(st, sign, server, net) {
|
|
635
|
+
let txHash = st.txHash || sign.txHash;
|
|
636
|
+
if (!txHash && st.autoDetect) {
|
|
637
|
+
if (st.status === 'review') return reviewed(st);
|
|
638
|
+
if (st.detected) {
|
|
639
|
+
say(`\nPayment seen: ${st.detected.amount} ${st.detected.chainLabel}. Waiting for it to confirm on the network.`);
|
|
640
|
+
return awaitPayment(st, sign, server, net);
|
|
641
|
+
}
|
|
642
|
+
if (!st.address) {
|
|
643
|
+
// Its window ended: the server never hands it out again.
|
|
644
|
+
say('\nThat payment address has expired. Do NOT send to it. Choose again for a new one.');
|
|
645
|
+
return { step: 'chain', lastOrderExpired: true };
|
|
646
|
+
}
|
|
647
|
+
showOrder(st);
|
|
648
|
+
const a = await prompt('Once sent, press Enter to wait for it (or paste the transaction ID, or type q to finish later): ');
|
|
649
|
+
if (a === null || a.trim().toLowerCase() === 'q') { say(`\nNothing to check yet. ${resumeHint}`); return null; }
|
|
650
|
+
if (!a.trim()) return awaitPayment(st, sign, server, net);
|
|
651
|
+
txHash = a.trim();
|
|
652
|
+
saveSignup({ ...sign, txHash });
|
|
653
|
+
}
|
|
654
|
+
if (!txHash) {
|
|
655
|
+
showOrder(st);
|
|
656
|
+
txHash = await ask('Once sent, paste the transaction ID (or press Enter to finish later): ');
|
|
657
|
+
if (!txHash) { say(`\nNothing to check yet. ${resumeHint}`); return null; }
|
|
658
|
+
saveSignup({ ...sign, txHash });
|
|
659
|
+
}
|
|
660
|
+
for (let round = 0; round < 25; round++) {
|
|
661
|
+
let r;
|
|
662
|
+
try {
|
|
663
|
+
r = await call(server, 'pay_verify', { signupToken: sign.signupToken, txHash }, net);
|
|
664
|
+
} catch (e) {
|
|
665
|
+
if (!(e instanceof Refused) || !/transaction ID|already been used/i.test(e.message)) throw e;
|
|
666
|
+
say(e.message);
|
|
667
|
+
saveSignup({ ...sign, txHash: undefined });
|
|
668
|
+
txHash = await ask('Transaction ID (or Enter to finish later): ');
|
|
669
|
+
if (!txHash) { say(resumeHint); return null; }
|
|
670
|
+
saveSignup({ ...sign, txHash });
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
if (r.step !== 'pay') return r;
|
|
674
|
+
if (r.status === 'review') return reviewed(r);
|
|
675
|
+
if (r.state === 'mismatch') {
|
|
676
|
+
say(`\n${r.reason || 'That transaction does not match this order.'}`);
|
|
677
|
+
saveSignup({ ...sign, txHash: undefined });
|
|
678
|
+
txHash = await ask('Another transaction ID (or Enter to finish later): ');
|
|
679
|
+
if (!txHash) { say(resumeHint); return null; }
|
|
680
|
+
saveSignup({ ...sign, txHash });
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
say(`${r.reason || 'Not confirmed yet.'} Checking again in a minute. Ctrl-C stops; ${resumeHint.replace('Run: ', 'later run ')}`);
|
|
684
|
+
await sleep(CONFIRM_POLL_MS);
|
|
685
|
+
}
|
|
686
|
+
say(`Still waiting on the network. ${resumeHint}`);
|
|
687
|
+
return null;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
async function finish(st, sign, server, net) {
|
|
691
|
+
const sess = st.session;
|
|
692
|
+
if (!sess) throw new Error('The account is open but no session came back. Run: counterlure login');
|
|
693
|
+
const plan = st.plan || sign?.plan;
|
|
694
|
+
saveSession({ server, token: sess.token, username: sess.username, expiresAt: sess.expiresAt });
|
|
695
|
+
forgetSignup();
|
|
696
|
+
if (st.step === 'done' && st.recoveryCodes?.length) {
|
|
697
|
+
say([
|
|
698
|
+
'',
|
|
699
|
+
'Your account is open. Recovery codes:',
|
|
700
|
+
'',
|
|
701
|
+
...st.recoveryCodes.map((c) => ` ${c}`),
|
|
702
|
+
'',
|
|
703
|
+
' Each one signs you in once, in place of an authenticator code. Write them down or keep them',
|
|
704
|
+
' in a password manager, offline. They are shown once and this tool does not store them.',
|
|
705
|
+
'',
|
|
706
|
+
].join('\n'));
|
|
707
|
+
if (process.stdin.isTTY) {
|
|
708
|
+
while ((await ask('Type "saved" once they are somewhere safe: ')).toLowerCase() !== 'saved');
|
|
709
|
+
}
|
|
710
|
+
await call(server, 'codes_saved', { token: sess.token }, net);
|
|
711
|
+
}
|
|
712
|
+
out(`\nSigned in as ${sess.username} until ${when(sess.expiresAt)}.`);
|
|
713
|
+
if (plan === 'pass30') {
|
|
714
|
+
out(`Your 30-day pass ${st.paidUntil ? `runs until ${when(st.paidUntil)}` : 'starts now'}. It is never renewed automatically:`);
|
|
715
|
+
out(`renew it before it ends at ${RENEW_URL} (sign in with this username and authenticator).`);
|
|
716
|
+
}
|
|
717
|
+
out('Next: counterlure check PHOTO, counterlure inbox, or counterlure send "a message to the team".');
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
async function signup(o, server, net) {
|
|
721
|
+
let sign = loadSignup(), st;
|
|
722
|
+
if (sign && o.user && o.user.toLowerCase() !== sign.username.toLowerCase()) {
|
|
723
|
+
throw new Error(`A signup for "${sign.username}" is in progress here. Finish it with: counterlure signup\nor abandon it with: counterlure logout`);
|
|
724
|
+
}
|
|
725
|
+
if (sign) {
|
|
726
|
+
say(`Resuming signup for ${sign.username}.`);
|
|
727
|
+
try {
|
|
728
|
+
st = await call(server, 'signup_state', { signupToken: sign.signupToken }, net);
|
|
729
|
+
} catch (e) {
|
|
730
|
+
if (e instanceof Refused && /expired/i.test(e.message)) forgetSignup();
|
|
731
|
+
throw e;
|
|
732
|
+
}
|
|
733
|
+
} else {
|
|
734
|
+
if (o.resume) throw new Error('No signup in progress on this computer. If you already linked an authenticator, run: counterlure login');
|
|
735
|
+
const s = loadSession();
|
|
736
|
+
if (s) throw new Error(`Already signed in as ${s.username}. Run counterlure logout first to open another account.`);
|
|
737
|
+
say('A Counterlure account is a username and an authenticator app. No email, phone number or name.');
|
|
738
|
+
const username = o.user || await ask('Choose a username (3-32 characters: letters, numbers, . - _): ');
|
|
739
|
+
if (!username) throw new Error('A username is required.');
|
|
740
|
+
const r = await callWithWork(server, 'signup_begin', { username }, net);
|
|
741
|
+
sign = { server, signupToken: r.signupToken, username: r.username, expiresAt: r.expiresAt };
|
|
742
|
+
saveSignup(sign);
|
|
743
|
+
st = { step: 'totp', ...r };
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
for (let guard = 0; guard < 20; guard++) {
|
|
747
|
+
if (st.step === 'totp') {
|
|
748
|
+
showAuthenticator(st);
|
|
749
|
+
let ok = false;
|
|
750
|
+
for (let tries = 0; tries < 3 && !ok; tries++) {
|
|
751
|
+
const code = await ask('Code from the app: ');
|
|
752
|
+
if (!code) throw new Error(`No code entered. ${resumeHint}`);
|
|
753
|
+
try { await call(server, 'signup_confirm', { signupToken: sign.signupToken, code }, net); ok = true; } catch (e) {
|
|
754
|
+
if (!(e instanceof Refused) || !/did not match/i.test(e.message)) throw e;
|
|
755
|
+
say(e.message);
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
if (!ok) throw new Error(`Too many wrong codes. Check your phone's clock, then: ${resumeHint.replace('Run: ', '')}`);
|
|
759
|
+
say('Authenticator linked.');
|
|
760
|
+
st = await call(server, 'signup_state', { signupToken: sign.signupToken }, net);
|
|
761
|
+
} else if (st.step === 'chain') {
|
|
762
|
+
if (st.lastOrderExpired) say('\nYour last payment address expired before a payment reached it. Do NOT send to it any more.');
|
|
763
|
+
const { plan, chain } = await pickPlanAndChain(o, sign, server, net);
|
|
764
|
+
st = await call(server, 'pay_order', { signupToken: sign.signupToken, chain, ...(plan ? { plan } : {}) }, net);
|
|
765
|
+
// The new order's reply does not repeat the plan (a resumed signup's state does): keep the one chosen.
|
|
766
|
+
if (plan && !st.plan) st = { ...st, plan };
|
|
767
|
+
saveSignup({ ...sign, txHash: undefined, plan: st.plan });
|
|
768
|
+
sign = loadSignup();
|
|
769
|
+
} else if (st.step === 'pay') {
|
|
770
|
+
const r = await settle(st, sign, server, net);
|
|
771
|
+
if (!r) return;
|
|
772
|
+
if (r.step === 'pay' && r.status === 'review') return reviewed(r);
|
|
773
|
+
st = r;
|
|
774
|
+
} else if (st.step === 'done' || st.step === 'active') {
|
|
775
|
+
return finish(st, sign, server, net);
|
|
776
|
+
} else {
|
|
777
|
+
throw new Error(`Unexpected signup step "${st.step}". Update the tool.`);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
throw new Error(`Signup did not settle. ${resumeHint}`);
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// ------------------------------------------------------------------ messages
|
|
784
|
+
|
|
785
|
+
function showThread(r, all) {
|
|
786
|
+
const msgs = [...r.messages].reverse(); // oldest first, like a conversation
|
|
787
|
+
const shown = all ? msgs : msgs.slice(-10);
|
|
788
|
+
if (!msgs.length) {
|
|
789
|
+
out('No messages yet. Write to the team with: counterlure send "your message"');
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
if (shown.length < msgs.length) out(`(${msgs.length - shown.length} earlier messages; --all shows them)\n`);
|
|
793
|
+
for (const m of shown) {
|
|
794
|
+
const who = m.from === 'admin' ? 'Counterlure' : 'You';
|
|
795
|
+
const fresh = m.from === 'admin' && !m.readAt ? ' [new]' : '';
|
|
796
|
+
out(`--- ${who}, ${when(m.createdAt)}${fresh}`);
|
|
797
|
+
if (m.subject) out(`Subject: ${m.subject}`);
|
|
798
|
+
if (m.caseId) out('About one of your reports.');
|
|
799
|
+
out(`${m.body}\n`);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
async function compose(rest) {
|
|
804
|
+
if (rest.length) return rest.join(' ');
|
|
805
|
+
const lines = [];
|
|
806
|
+
if (process.stdin.isTTY) say('Write your message. Finish with a line holding only "." (Ctrl-C cancels).');
|
|
807
|
+
for (;;) {
|
|
808
|
+
const l = await prompt('');
|
|
809
|
+
if (l === null || (process.stdin.isTTY && l.trim() === '.')) break;
|
|
810
|
+
lines.push(l);
|
|
811
|
+
}
|
|
812
|
+
return lines.join('\n');
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
// ------------------------------------------------------------------ enterprise (org CLI)
|
|
816
|
+
|
|
817
|
+
async function orgCall(server, op, args, net, orgName) {
|
|
818
|
+
try {
|
|
819
|
+
return await call(server, op, args, net);
|
|
820
|
+
} catch (e) {
|
|
821
|
+
if (e instanceof Refused) {
|
|
822
|
+
const code = e.reply?.code;
|
|
823
|
+
if (code === 'org_suspended') {
|
|
824
|
+
throw new Error(`Organization suspended: ${e.message}`);
|
|
825
|
+
}
|
|
826
|
+
if (code === 'org_unpaid') {
|
|
827
|
+
throw new Error(`Organization license inactive: ${e.message}`);
|
|
828
|
+
}
|
|
829
|
+
if (code === 'org_revoked' || (code === 'org_not_enrolled' && args?.orgToken)) {
|
|
830
|
+
throw new Error(`Device enrollment revoked or no longer active${orgName ? ` for ${orgName}` : ''}. Ask your security team for a new one-time code and run: counterlure org enroll CODE --replace`);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
throw e;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
function dedupeOrgMatches(matches) {
|
|
838
|
+
const out = [];
|
|
839
|
+
const seenRefs = new Set();
|
|
840
|
+
const hasOrgCampaign = (matches || []).some((m) => m.source === 'org-campaign');
|
|
841
|
+
for (const m of matches || []) {
|
|
842
|
+
if (m.source === 'org-campaign') {
|
|
843
|
+
const ref = m.caseRef || JSON.stringify(m);
|
|
844
|
+
if (seenRefs.has(ref)) continue;
|
|
845
|
+
seenRefs.add(ref);
|
|
846
|
+
out.push(m);
|
|
847
|
+
continue;
|
|
848
|
+
}
|
|
849
|
+
// If an org's own promoted case was also published to the global pool, avoid listing it twice.
|
|
850
|
+
if (hasOrgCampaign && m.source === 'reports' && m.caseRef && seenRefs.has(m.caseRef)) continue;
|
|
851
|
+
out.push(m);
|
|
852
|
+
}
|
|
853
|
+
return out;
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
async function orgCheckCmd(org, files, net, server, json) {
|
|
857
|
+
if (!files.length) throw new Error('Usage: counterlure org check IMAGE [IMAGE...]');
|
|
858
|
+
await models(net);
|
|
859
|
+
const results = [];
|
|
860
|
+
for (const file of files) {
|
|
861
|
+
let found;
|
|
862
|
+
try {
|
|
863
|
+
found = await facesIn(file);
|
|
864
|
+
} catch (e) {
|
|
865
|
+
results.push({ file, faces: [], error: e.message });
|
|
866
|
+
continue;
|
|
867
|
+
}
|
|
868
|
+
const { faces, skipped } = found;
|
|
869
|
+
if (!faces.length) { results.push({ file, faces: [], note: 'no face found' }); continue; }
|
|
870
|
+
const usable = faces.filter((f) => !isTooSmall(f.box));
|
|
871
|
+
let r = { results: [], orgName: org.orgName };
|
|
872
|
+
if (usable.length) {
|
|
873
|
+
r = await orgCall(server, 'org_check', { orgToken: org.orgToken, model: MODEL_VERSION, faces: usable.map((f) => f.embedding) }, net, org.orgName);
|
|
874
|
+
}
|
|
875
|
+
let uIdx = 0;
|
|
876
|
+
results.push({
|
|
877
|
+
file,
|
|
878
|
+
orgName: r.orgName || org.orgName,
|
|
879
|
+
...(skipped ? { skipped } : {}),
|
|
880
|
+
faces: faces.map((f) => (isTooSmall(f.box)
|
|
881
|
+
? { box: f.box, refused: `face too small (${f.box.w}x${f.box.h}px, minimum 64x64px)`, matches: [] }
|
|
882
|
+
: { box: f.box, matches: dedupeOrgMatches(r.results?.[uIdx++] ?? []) })),
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
if (json) return out(JSON.stringify(results, null, 2));
|
|
886
|
+
let any = false;
|
|
887
|
+
for (const r of results) {
|
|
888
|
+
out(`\n${r.file} (checked against ${org.orgName} alerts + global pool)`);
|
|
889
|
+
if (r.error) { out(` Error: ${r.error}`); continue; }
|
|
890
|
+
if (!r.faces.length) { out(' No face found. Use a clearer, front-facing photo.'); continue; }
|
|
891
|
+
if (r.skipped) out(` Note: ${r.skipped} additional face${r.skipped === 1 ? '' : 's'} skipped (at most 5 largest faces checked per photo).`);
|
|
892
|
+
r.faces.forEach((f, i) => {
|
|
893
|
+
const where = `face ${i + 1} at ${f.box.x},${f.box.y} (${f.box.w}x${f.box.h}px)`;
|
|
894
|
+
if (f.refused) return out(` ${where}: refused — ${f.refused}`);
|
|
895
|
+
if (!f.matches.length) return out(` ${where}: no match`);
|
|
896
|
+
any = true;
|
|
897
|
+
out(` ${where}:`);
|
|
898
|
+
for (const m of f.matches) out(` ${level(m)}`);
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
out(any
|
|
902
|
+
? '\nIf this contact matches an active campaign targeting your organization, please alert your security team.'
|
|
903
|
+
: '\nNo match in global pool or active org alerts. To log this contact anonymously inside your org namespace: counterlure org report IMAGE');
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
async function orgReportCmd(org, file, o, net, route) {
|
|
907
|
+
if (!file) throw new Error('Usage: counterlure org report IMAGE [--context C] [--face N] [--dry-run] [--yes]');
|
|
908
|
+
if (o.anon) throw new Error('--anon cannot be used with org report. Organization reports always use your anonymous device token; for a public unattributed report, use: counterlure report --anon IMAGE --name ...');
|
|
909
|
+
if (o['save-crop']) throw new Error('--save-crop is not supported for org report because no image crop is created or sent (only a 128-value face fingerprint).');
|
|
910
|
+
const context = o.context || 'other';
|
|
911
|
+
if (!CONTEXTS.includes(context)) throw new Error(`--context must be one of: ${CONTEXTS.join(', ')}`);
|
|
912
|
+
if (!o.yes && !o['dry-run'] && !process.stdin.isTTY) throw new Error('No terminal to confirm on. Re-run with --yes to confirm non-interactively.');
|
|
913
|
+
|
|
914
|
+
await models(net);
|
|
915
|
+
const { faces } = await facesIn(file);
|
|
916
|
+
if (!faces.length) throw new Error('No face found. Use a clearer, front-facing photo.');
|
|
917
|
+
const list = () => faces.map((f, i) => ` ${i + 1}: at ${f.box.x},${f.box.y} (${f.box.w}x${f.box.h}px)`).join('\n');
|
|
918
|
+
const n = o.face === undefined ? 1 : Number(o.face);
|
|
919
|
+
if (o.face === undefined && faces.length > 1) throw new Error(`${faces.length} faces in this photo. Pick one with --face N:\n${list()}`);
|
|
920
|
+
if (!Number.isInteger(n) || n < 1 || n > faces.length) throw new Error(`--face must be between 1 and ${faces.length}:\n${list()}`);
|
|
921
|
+
const face = faces[n - 1];
|
|
922
|
+
if (isTooSmall(face.box)) throw new Error(`Face is too small (${face.box.w}x${face.box.h}px). Use a clearer photo where the face is at least 64x64px.`);
|
|
923
|
+
|
|
924
|
+
say([
|
|
925
|
+
'',
|
|
926
|
+
'Organization Report',
|
|
927
|
+
` Organization ${org.orgName}`,
|
|
928
|
+
` Subject face ${n} of ${faces.length} in ${path.basename(file)} (${face.box.w}x${face.box.h}px)`,
|
|
929
|
+
` Context ${context}`,
|
|
930
|
+
` Leaves here 128-value face fingerprint, model version (${MODEL_VERSION}), context (${context}), reporting attestation, and your anonymous device token (no photo, no name, no employee identity)`,
|
|
931
|
+
` Privacy Isolated to ${org.orgName} until ${org.threshold || 3} distinct staff report the same face; a Counterlure reviewer decides whether an escalated case joins the wider pool`,
|
|
932
|
+
` Route ${route.label}`,
|
|
933
|
+
'',
|
|
934
|
+
'Statement',
|
|
935
|
+
...STATEMENT.map((l) => ` ${l}`),
|
|
936
|
+
'',
|
|
937
|
+
].join('\n'));
|
|
938
|
+
if (o['dry-run']) return say('Dry run: nothing sent.');
|
|
939
|
+
if (!o.yes && (await ask('Type "yes" to make this statement and file the report: ')).toLowerCase() !== 'yes') throw new Error('Not filed.');
|
|
940
|
+
|
|
941
|
+
const r = await orgCall(route.server, 'org_report', { orgToken: org.orgToken, model: MODEL_VERSION, face: face.embedding, context, attest: true }, net, org.orgName);
|
|
942
|
+
if (o.json) return out(JSON.stringify({ receipt: r.receipt, orgName: r.orgName }));
|
|
943
|
+
out(`\nFiled anonymously inside ${r.orgName}. Receipt: ${r.receipt}`);
|
|
944
|
+
out('No photo, name, or employee identity was sent. Check for private alerts anytime with: counterlure org inbox');
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
async function orgInboxCmd(org, o, net, server) {
|
|
948
|
+
const r = await orgCall(server, 'org_inbox', { orgToken: org.orgToken, markRead: true }, net, org.orgName);
|
|
949
|
+
if (o.json) return out(JSON.stringify({ messages: r.messages || [], unread: r.unread ?? 0 }, null, 2));
|
|
950
|
+
if (!r.messages.length) return out(`No private alerts for your anonymous ${org.orgName} device.`);
|
|
951
|
+
const msgs = [...r.messages].reverse();
|
|
952
|
+
const shown = o.all ? msgs : msgs.slice(-10);
|
|
953
|
+
for (const m of shown) {
|
|
954
|
+
const fresh = !m.readAt ? ' [NEW]' : '';
|
|
955
|
+
out(`--- Counterlure (${org.orgName}), ${when(m.createdAt)}${fresh}`);
|
|
956
|
+
if (m.subject) out(`Subject: ${m.subject}`);
|
|
957
|
+
out(`${m.body}\n`);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
async function orgStatusCmd(org, o, net, server) {
|
|
962
|
+
const r = await orgCall(server, 'org_status', { orgToken: org.orgToken }, net, org.orgName);
|
|
963
|
+
if (o.json) {
|
|
964
|
+
const payload = {
|
|
965
|
+
orgName: r.orgName,
|
|
966
|
+
underAttack: Boolean(r.underAttack),
|
|
967
|
+
severity: r.severity,
|
|
968
|
+
activeCampaigns: r.activeCampaigns ?? 0,
|
|
969
|
+
unread: r.unread ?? 0,
|
|
970
|
+
};
|
|
971
|
+
if (r.countsFrom) payload.countsFrom = r.countsFrom;
|
|
972
|
+
return out(JSON.stringify(payload, null, 2));
|
|
973
|
+
}
|
|
974
|
+
out(`Organization: ${r.orgName} (anonymous device enrolled)`);
|
|
975
|
+
out(`Threat status: ${r.underAttack ? `UNDER COORDINATED TARGETING (${String(r.severity).toUpperCase()}, ${r.activeCampaigns} active campaign${r.activeCampaigns === 1 ? '' : 's'})` : 'All clear (no active coordinated campaigns)'}`);
|
|
976
|
+
if (r.unread) out(`${r.unread} unread private alert${r.unread === 1 ? '' : 's'}. Run: counterlure org inbox`);
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
async function orgCmd(rest, o, server, net, route) {
|
|
980
|
+
const [sub, ...args] = rest;
|
|
981
|
+
if (!sub || sub === 'help') return process.stdout.write(HELP);
|
|
982
|
+
if (sub === 'enroll') {
|
|
983
|
+
const existing = loadOrg();
|
|
984
|
+
if (existing && !o.replace) {
|
|
985
|
+
throw new Error(`Already enrolled in ${existing.orgName}. Run "counterlure org leave" first, or pass --replace to replace this device's enrollment.`);
|
|
986
|
+
}
|
|
987
|
+
const code = args[0] || await ask('Organization enrollment code: ');
|
|
988
|
+
if (!code) throw new Error('Usage: counterlure org enroll CODE [--replace]');
|
|
989
|
+
const r = await call(server, 'org_enroll', { code }, net);
|
|
990
|
+
saveOrg({ server, orgToken: r.deviceToken, orgName: r.orgName, threshold: r.threshold });
|
|
991
|
+
if (o.json) return out(JSON.stringify({ enrolled: true, orgName: r.orgName, threshold: r.threshold }));
|
|
992
|
+
out(`Enrolled anonymously in ${r.orgName}.`);
|
|
993
|
+
out('Your device holds an anonymous random token — no employee name, email, or photo is ever shared with your employer.');
|
|
994
|
+
out('Next: counterlure org check PHOTO or counterlure org report PHOTO');
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
if (sub === 'leave') {
|
|
998
|
+
const org = loadOrg();
|
|
999
|
+
if (!org) throw new Error('Not enrolled in an organization.');
|
|
1000
|
+
let r;
|
|
1001
|
+
try {
|
|
1002
|
+
r = await call(server, 'org_leave', { orgToken: org.orgToken, withdraw: Boolean(o.withdraw) }, net);
|
|
1003
|
+
} catch (e) {
|
|
1004
|
+
if (e instanceof Refused && e.reply?.code === 'org_not_enrolled') {
|
|
1005
|
+
forgetOrg();
|
|
1006
|
+
out('This device was no longer enrolled on the server. Local organization credential deleted.');
|
|
1007
|
+
return;
|
|
1008
|
+
}
|
|
1009
|
+
throw new Error(`Could not reach the server to leave ${org.orgName} (${e.message}). Local enrollment file was kept so you can retry.`);
|
|
1010
|
+
}
|
|
1011
|
+
forgetOrg();
|
|
1012
|
+
const extra = r?.withdrawn ? ` ${r.withdrawn} report${r.withdrawn === 1 ? '' : 's'} withdrawn.` : '';
|
|
1013
|
+
out(`Left ${org.orgName} and deleted local anonymous organization credential.${extra}`);
|
|
1014
|
+
return;
|
|
1015
|
+
}
|
|
1016
|
+
const org = loadOrg();
|
|
1017
|
+
if (!org) throw new Error('Not enrolled in an organization. Run: counterlure org enroll CODE');
|
|
1018
|
+
if (sub === 'status') return orgStatusCmd(org, o, net, server);
|
|
1019
|
+
if (sub === 'check') return orgCheckCmd(org, args, net, server, o.json);
|
|
1020
|
+
if (sub === 'report') return orgReportCmd(org, args[0], o, net, route);
|
|
1021
|
+
if (sub === 'inbox') return orgInboxCmd(org, o, net, server);
|
|
1022
|
+
if (sub === 'withdraw') {
|
|
1023
|
+
if (args.length !== 1) throw new Error('Usage: counterlure org withdraw RECEIPT');
|
|
1024
|
+
const r = await orgCall(server, 'org_withdraw', { orgToken: org.orgToken, receipt: args[0] }, net, org.orgName);
|
|
1025
|
+
if (o.json) return out(JSON.stringify({ withdrawn: Boolean(r.withdrawn) }));
|
|
1026
|
+
if (!r.withdrawn) throw new Error('The server did not confirm withdrawal.');
|
|
1027
|
+
out('Withdrawn. Your organization report has been removed.');
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
throw new Error(`Unknown org command "${sub}". Run: counterlure --help`);
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
// ------------------------------------------------------------------ main
|
|
1034
|
+
|
|
1035
|
+
async function main() {
|
|
1036
|
+
const { values: o, positionals } = parseArgs({
|
|
1037
|
+
allowPositionals: true,
|
|
1038
|
+
options: {
|
|
1039
|
+
tor: { type: 'boolean' }, direct: { type: 'boolean' }, proxy: { type: 'string' }, json: { type: 'boolean' },
|
|
1040
|
+
server: { type: 'string' }, user: { type: 'string' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' },
|
|
1041
|
+
name: { type: 'string' }, context: { type: 'string' }, handle: { type: 'string' }, face: { type: 'string' },
|
|
1042
|
+
anon: { type: 'boolean' }, yes: { type: 'boolean' }, 'dry-run': { type: 'boolean' }, 'save-crop': { type: 'string' },
|
|
1043
|
+
subject: { type: 'string', short: 's' }, chain: { type: 'string' }, plan: { type: 'string' }, resume: { type: 'boolean' }, all: { type: 'boolean' },
|
|
1044
|
+
replace: { type: 'boolean' }, withdraw: { type: 'boolean' }, 'fetch-models': { type: 'boolean' }, download: { type: 'boolean' }, token: { type: 'boolean' },
|
|
1045
|
+
},
|
|
1046
|
+
});
|
|
1047
|
+
const [cmd, ...rest] = positionals;
|
|
1048
|
+
if (o.version) return out(VERSION);
|
|
1049
|
+
if (o.help || !cmd) return process.stdout.write(HELP);
|
|
1050
|
+
|
|
1051
|
+
if (cmd === 'inspect') {
|
|
1052
|
+
const dir = rest[0] || '.';
|
|
1053
|
+
const r = inspectDir(dir);
|
|
1054
|
+
if (o.json) process.stdout.write(JSON.stringify(r, null, 2) + '\n');
|
|
1055
|
+
else out(renderInspect(r));
|
|
1056
|
+
process.exitCode = r.verdict === 'do_not_run' ? 2 : r.verdict === 'review_first' ? 1 : 0;
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
if (cmd === 'key') {
|
|
1061
|
+
out([
|
|
1062
|
+
'Pinned Counterlure CLI key fingerprint:',
|
|
1063
|
+
` ${SERVER_FINGERPRINT.toUpperCase().replace(/(.{4})/g, '$1 ').trim()}`,
|
|
1064
|
+
'Onion service this tool talks to by default:',
|
|
1065
|
+
` ${new URL(ONION).hostname}`,
|
|
1066
|
+
`Verify both against ${SITE}/#cli and ${SITE}/api/cli/key`,
|
|
1067
|
+
].join('\n'));
|
|
1068
|
+
return;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
modelPolicy.fetch = Boolean(o['fetch-models']);
|
|
1072
|
+
if (cmd === 'models' && !o.download) {
|
|
1073
|
+
const [sub, ...paths] = rest;
|
|
1074
|
+
if (sub === 'import') {
|
|
1075
|
+
if (!paths.length) throw new Error('Usage: counterlure models import FILE-OR-FOLDER ...');
|
|
1076
|
+
const { imported, rejected } = await importModels(dirs.models, paths);
|
|
1077
|
+
for (const i of imported) out(`Imported ${i.file} (from ${i.from}, SHA-256 verified)`);
|
|
1078
|
+
for (const r of rejected) say(`Skipped ${r.file}: ${r.why}`);
|
|
1079
|
+
} else if (sub && sub !== 'status') {
|
|
1080
|
+
throw new Error(`Unknown models command "${sub}". Run: counterlure --help`);
|
|
1081
|
+
} else {
|
|
1082
|
+
for (const x of await findLocalModels(dirs.models)) say(`Using the verified copy of ${x.file} found at ${x.from}`);
|
|
1083
|
+
}
|
|
1084
|
+
const st = await modelStatus(dirs.models);
|
|
1085
|
+
if (o.json) return out(JSON.stringify({ dir: dirs.models, models: st.map((m) => ({ file: m.file, sha256: m.sha256, installed: m.installed })) }));
|
|
1086
|
+
for (const m of st) out(` ${m.installed ? 'verified' : 'missing '} ${m.file}`);
|
|
1087
|
+
const missing = st.filter((m) => !m.installed);
|
|
1088
|
+
if (missing.length) {
|
|
1089
|
+
say('');
|
|
1090
|
+
say(missingModelsText(missing, dirs.models));
|
|
1091
|
+
say(' To fetch them with this tool instead: counterlure models --download');
|
|
1092
|
+
process.exitCode = 1;
|
|
1093
|
+
} else out(`Both models verified in ${dirs.models}`);
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
if (cmd === 'fingerprint') {
|
|
1098
|
+
if (rest.length !== 1) throw new Error('Usage: counterlure fingerprint IMAGE [--face N] [--token] [--json]');
|
|
1099
|
+
let route;
|
|
1100
|
+
const routeFor = async () => {
|
|
1101
|
+
if (!route) {
|
|
1102
|
+
route = await resolveRoute(o);
|
|
1103
|
+
if (route.custom || !route.onion) say(`note: ${route.label}`);
|
|
1104
|
+
modelPolicy.route = route.label;
|
|
1105
|
+
}
|
|
1106
|
+
return route;
|
|
1107
|
+
};
|
|
1108
|
+
return fingerprintCmd(rest[0], o, routeFor);
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
// Everything below talks to the network. Nothing is sent until the route is settled.
|
|
1112
|
+
const route = await resolveRoute(o);
|
|
1113
|
+
const net = { proxy: route.proxy };
|
|
1114
|
+
const server = route.server;
|
|
1115
|
+
trustedKey = await serverFingerprint();
|
|
1116
|
+
if (route.custom || !route.onion) say(`note: ${route.label}`);
|
|
1117
|
+
modelPolicy.route = route.label;
|
|
1118
|
+
|
|
1119
|
+
if (cmd === 'models') {
|
|
1120
|
+
await models(net);
|
|
1121
|
+
out(`Models verified in ${dirs.models}`);
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
if (cmd === 'signup' || cmd === 'pay') return signup(o, server, net);
|
|
1125
|
+
if (cmd === 'login') {
|
|
1126
|
+
const username = o.user || await ask('Username: ');
|
|
1127
|
+
const code = await ask('Authenticator code: ', { hide: true });
|
|
1128
|
+
const r = await call(server, 'login', { username, code }, net);
|
|
1129
|
+
if (r.pendingSignup) {
|
|
1130
|
+
saveSignup({ server, signupToken: r.signupToken, username: r.username, expiresAt: r.expiresAt });
|
|
1131
|
+
say(`${r.username} is not paid for yet. Continuing the signup.`);
|
|
1132
|
+
return signup({ ...o, user: undefined }, server, net);
|
|
1133
|
+
}
|
|
1134
|
+
saveSession({ server, token: r.token, username: r.username, expiresAt: r.expiresAt });
|
|
1135
|
+
forgetSignup();
|
|
1136
|
+
out(`Signed in as ${r.username} until ${when(r.expiresAt)}.`);
|
|
1137
|
+
if (r.recoveryLeft !== undefined) out(`You used a recovery code: ${r.recoveryLeft} left. Re-enrol your authenticator on the website.`);
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
if (cmd === 'withdraw') {
|
|
1141
|
+
if (rest.length !== 1) throw new Error('Usage: counterlure withdraw RECEIPT');
|
|
1142
|
+
if (String(rest[0]).toUpperCase().startsWith('CLO-')) {
|
|
1143
|
+
const org = loadOrg();
|
|
1144
|
+
if (!org) throw new Error('Not enrolled in an organization. Run: counterlure org enroll <code>');
|
|
1145
|
+
const r = await orgCall(server, 'org_withdraw', { orgToken: org.orgToken, receipt: rest[0] }, net, org.orgName);
|
|
1146
|
+
if (o.json) return out(JSON.stringify({ withdrawn: Boolean(r.withdrawn) }));
|
|
1147
|
+
if (!r.withdrawn) throw new Error('The server did not confirm withdrawal.');
|
|
1148
|
+
out('Withdrawn. Your organization report has been removed.');
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
const r = await call(server, 'withdraw', { receipt: rest[0] }, net);
|
|
1152
|
+
if (o.json) return out(JSON.stringify({ withdrawn: Boolean(r.withdrawn) }));
|
|
1153
|
+
if (!r.withdrawn) throw new Error('The server did not confirm withdrawal.');
|
|
1154
|
+
out('Withdrawn. The stored face crop and template have been destroyed.');
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
1157
|
+
if (cmd === 'org') return orgCmd(rest, o, server, net, route);
|
|
1158
|
+
|
|
1159
|
+
const s = loadSession();
|
|
1160
|
+
const org = loadOrg();
|
|
1161
|
+
if (cmd === 'report') {
|
|
1162
|
+
if (rest.length !== 1) throw new Error('Usage: counterlure report IMAGE --name NAME [--context C] [--handle H]');
|
|
1163
|
+
return report(rest[0], o, s, net, route);
|
|
1164
|
+
}
|
|
1165
|
+
if (cmd === 'logout') {
|
|
1166
|
+
const sign = loadSignup();
|
|
1167
|
+
if (s || sign) await call(server, 'logout', { token: s?.token, signupToken: sign?.signupToken }, net).catch(() => {});
|
|
1168
|
+
forgetSession();
|
|
1169
|
+
forgetSignup();
|
|
1170
|
+
out(sign && !s ? 'Signup abandoned. Its saved state was deleted here.' : 'Signed out. The saved session was deleted.');
|
|
1171
|
+
return;
|
|
1172
|
+
}
|
|
1173
|
+
if (!s && org && (cmd === 'check' || cmd === 'inbox' || cmd === 'whoami')) {
|
|
1174
|
+
if (cmd === 'check') return orgCheckCmd(org, rest, net, server, o.json);
|
|
1175
|
+
if (cmd === 'inbox') return orgInboxCmd(org, o, net, server);
|
|
1176
|
+
if (cmd === 'whoami') return orgStatusCmd(org, o, net, server);
|
|
1177
|
+
}
|
|
1178
|
+
if (!s) {
|
|
1179
|
+
throw new Error(loadSignup()
|
|
1180
|
+
? 'Your signup is not finished. Run: counterlure signup'
|
|
1181
|
+
: 'Not signed in. Run: counterlure login (no account yet? counterlure signup, or counterlure org enroll CODE)');
|
|
1182
|
+
}
|
|
1183
|
+
if (cmd === 'whoami') {
|
|
1184
|
+
const r = await call(server, 'whoami', { token: s.token }, net);
|
|
1185
|
+
out(`${r.username} (session valid until ${when(s.expiresAt)})`);
|
|
1186
|
+
if (r.unread) out(`${r.unread} unread message${r.unread === 1 ? '' : 's'} from the team. Run: counterlure inbox`);
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
if (cmd === 'inbox') {
|
|
1190
|
+
const r = await call(server, 'inbox', { token: s.token, markRead: true }, net);
|
|
1191
|
+
if (o.json) return out(JSON.stringify(r, null, 2));
|
|
1192
|
+
return showThread(r, o.all);
|
|
1193
|
+
}
|
|
1194
|
+
if (cmd === 'send') {
|
|
1195
|
+
const body = (await compose(rest)).trim();
|
|
1196
|
+
if (!body) throw new Error('Nothing to send. Usage: counterlure send "your message" [--subject S]');
|
|
1197
|
+
if (body.length > 4000) throw new Error(`Messages are 4000 characters at most (this one is ${body.length}).`);
|
|
1198
|
+
const r = await call(server, 'send', { token: s.token, subject: o.subject, body }, net);
|
|
1199
|
+
if (o.json) return out(JSON.stringify(r));
|
|
1200
|
+
out('Sent to the Counterlure team. Replies arrive in: counterlure inbox');
|
|
1201
|
+
return;
|
|
1202
|
+
}
|
|
1203
|
+
if (cmd === 'check') {
|
|
1204
|
+
if (!rest.length) throw new Error('Usage: counterlure check IMAGE [IMAGE...]');
|
|
1205
|
+
return check(s, rest, net, server, o.json);
|
|
1206
|
+
}
|
|
1207
|
+
throw new Error(`Unknown command "${cmd}". Run: counterlure --help`);
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
main().catch((e) => { say(`error: ${e.message}`); process.exitCode = 1; });
|