blindfill 0.0.0-stage → 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,1112 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ assertRevision,
4
+ attach,
5
+ attachSession,
6
+ createProfile,
7
+ loadProfile,
8
+ loadSession,
9
+ startSession,
10
+ stopSession
11
+ } from "./chunk-KA4SHI33.js";
12
+ import {
13
+ AndroidActuator,
14
+ BACKEND_INFO,
15
+ BlindfillError,
16
+ BwBackend,
17
+ COMPANION,
18
+ COMPANION_SERVICES,
19
+ Engine,
20
+ KeepassxcBackend,
21
+ OpBackend,
22
+ PassBackend,
23
+ RbwBackend,
24
+ SecretServiceBackend,
25
+ attachSettings,
26
+ audit,
27
+ createBackend,
28
+ globalScrubber,
29
+ loadConfig,
30
+ redactEndpoint,
31
+ resolveEndpoint,
32
+ strictJson,
33
+ unverifiedNotice
34
+ } from "./chunk-V4KGRR36.js";
35
+
36
+ // src/cli.ts
37
+ import { parseArgs } from "util";
38
+ import { readFileSync } from "fs";
39
+
40
+ // src/backends/_contract/fixtures.ts
41
+ import { createHmac } from "crypto";
42
+ var FAKE = {
43
+ id: "11111111-1111-4111-8111-111111111111",
44
+ name: "Fake Shop",
45
+ username: "alice@example.test",
46
+ password: "CANARY-pw-Zx9!q7 &Lm=4",
47
+ uri: "https://shop.example.test/login",
48
+ hidden: { name: "pin", value: "CANARY-pin-8841" },
49
+ text: { name: "store_id", value: "S-1234" },
50
+ totpSeed: "JBSWY3DPEHPK3PXP",
51
+ decoyId: "22222222-2222-4222-8222-222222222222",
52
+ decoyUri: "https://other.example.test/",
53
+ androidId: "33333333-3333-4333-8333-333333333333",
54
+ androidPkg: "com.example.shop",
55
+ missingId: "99999999-9999-4999-8999-999999999999"
56
+ };
57
+ var SECRET_NEEDLES = [FAKE.password, FAKE.hidden.value, FAKE.totpSeed];
58
+ function bwFixtureItems() {
59
+ return [
60
+ {
61
+ id: FAKE.id,
62
+ type: 1,
63
+ name: FAKE.name,
64
+ notes: "CANARY-notes-should-stay-hidden",
65
+ login: {
66
+ username: FAKE.username,
67
+ password: FAKE.password,
68
+ totp: FAKE.totpSeed,
69
+ uris: [{ uri: FAKE.uri, match: null }]
70
+ },
71
+ fields: [
72
+ { name: FAKE.text.name, value: FAKE.text.value, type: 0 },
73
+ { name: FAKE.hidden.name, value: FAKE.hidden.value, type: 1 },
74
+ { name: "blindfill.submit", value: "once", type: 0 },
75
+ { name: "blindfill.rules", value: '{"v":1}', type: 0 }
76
+ ]
77
+ },
78
+ {
79
+ id: FAKE.decoyId,
80
+ type: 1,
81
+ name: "Other Site",
82
+ login: { username: "bob", password: "CANARY-decoy-0000", uris: [{ uri: FAKE.decoyUri, match: 1 }] }
83
+ },
84
+ {
85
+ id: FAKE.androidId,
86
+ type: 1,
87
+ name: "Fake Android App",
88
+ login: {
89
+ username: "carol",
90
+ password: "CANARY-android-1111",
91
+ uris: [{ uri: `androidapp://${FAKE.androidPkg}`, match: null }]
92
+ },
93
+ fields: [{ name: "blindfill.signers", value: "AA:BB:CC:DD", type: 0 }]
94
+ }
95
+ ];
96
+ }
97
+ function b32decode(s) {
98
+ const al = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
99
+ let bits = "";
100
+ for (const c of s.replace(/=+$/, "").toUpperCase()) bits += al.indexOf(c).toString(2).padStart(5, "0");
101
+ const out2 = [];
102
+ for (let i = 0; i + 8 <= bits.length; i += 8) out2.push(parseInt(bits.slice(i, i + 8), 2));
103
+ return Buffer.from(out2);
104
+ }
105
+ function totpFor(seed, now = Date.now()) {
106
+ const ctr = Buffer.alloc(8);
107
+ ctr.writeBigUInt64BE(BigInt(Math.floor(now / 3e4)));
108
+ const h = createHmac("sha1", b32decode(seed)).update(ctr).digest();
109
+ const o = h[h.length - 1] & 15;
110
+ return String((h.readUInt32BE(o) & 2147483647) % 1e6).padStart(6, "0");
111
+ }
112
+
113
+ // src/backends/_contract/fake-runners.ts
114
+ var ok = (stdout) => ({ stdout, stderr: "", code: 0 });
115
+ var err = (stderr, code = 1) => ({ stdout: "", stderr, code });
116
+ function fakeBw(locked) {
117
+ const items = bwFixtureItems();
118
+ const runner = async (_bin, a, o) => {
119
+ const args = a.filter((x) => x !== "--nointeraction");
120
+ if (args[0] === "--version") return ok("2099.1.0-fixture\n");
121
+ if (o?.env?.BW_SESSION !== "fixture-session" || locked)
122
+ return args[0] === "status" ? ok('{"status":"locked"}') : err("Vault is locked.");
123
+ if (args[0] === "status") return ok('{"status":"unlocked"}');
124
+ if (args[0] === "list") {
125
+ const needle = String(args[3] ?? "").toLowerCase();
126
+ const hit = (i) => args[2] === "--search" ? JSON.stringify([i.name, i.login?.uris]).toLowerCase().includes(needle) : (i.login?.uris ?? []).some(
127
+ (u) => u.uri?.includes("://") && new URL(u.uri).hostname.split(".").slice(-2).join(".") === new URL(needle).hostname.split(".").slice(-2).join(".")
128
+ );
129
+ return ok(JSON.stringify(items.filter(hit)));
130
+ }
131
+ if (args[0] === "get" && args[1] === "item") {
132
+ const it = items.find((i) => i.id === args[2]);
133
+ return it ? ok(JSON.stringify(it)) : err("Not found.");
134
+ }
135
+ if (args[0] === "get" && args[1] === "totp") return ok(totpFor(FAKE.totpSeed) + "\n");
136
+ return err("unsupported");
137
+ };
138
+ return { runner, env: { BW_SESSION: "fixture-session" } };
139
+ }
140
+ function fakeOp(locked) {
141
+ const item = {
142
+ id: FAKE.id,
143
+ title: FAKE.name,
144
+ urls: [{ href: FAKE.uri, primary: true }],
145
+ fields: [
146
+ { label: "username", purpose: "USERNAME", type: "STRING", value: FAKE.username },
147
+ { label: "password", purpose: "PASSWORD", type: "CONCEALED", value: FAKE.password },
148
+ { label: "one-time password", type: "OTP", value: `otpauth://totp/x?secret=${FAKE.totpSeed}` },
149
+ { label: FAKE.text.name, type: "STRING", value: FAKE.text.value },
150
+ { label: FAKE.hidden.name, type: "CONCEALED", value: FAKE.hidden.value },
151
+ { label: "blindfill.submit", type: "STRING", value: "once" },
152
+ { label: "notesPlain", purpose: "NOTES", type: "STRING", value: "CANARY-notes-should-stay-hidden" }
153
+ ]
154
+ };
155
+ return async (_bin, a) => {
156
+ if (a[0] === "--version") return ok("2.99.0-fixture\n");
157
+ if (locked) return err("[ERROR] 2026/11/27 You are not signed in. Run `op signin`.");
158
+ if (a[0] === "whoami") return ok('{"account_uuid":"fake"}');
159
+ if (a[0] === "item" && a[1] === "list")
160
+ return ok(JSON.stringify([{ id: item.id, title: item.title, urls: item.urls }]));
161
+ if (a[0] === "item" && a[1] === "get") {
162
+ if (a[2] !== item.id) return err(`[ERROR] "${a[2]}" isn't an item in any vault`);
163
+ return a.includes("--otp") ? ok(totpFor(FAKE.totpSeed) + "\n") : ok(JSON.stringify(item));
164
+ }
165
+ return err("unsupported");
166
+ };
167
+ }
168
+ function fakeRbw(locked) {
169
+ const item = {
170
+ id: FAKE.id,
171
+ name: FAKE.name,
172
+ folder: null,
173
+ notes: "CANARY-notes-should-stay-hidden",
174
+ data: {
175
+ username: FAKE.username,
176
+ password: FAKE.password,
177
+ totp: FAKE.totpSeed,
178
+ uris: [
179
+ { uri: FAKE.uri, match_type: null },
180
+ { uri: `androidapp://${FAKE.androidPkg}`, match_type: null }
181
+ ]
182
+ },
183
+ fields: [
184
+ { name: FAKE.text.name, value: FAKE.text.value, type: "text" },
185
+ { name: FAKE.hidden.name, value: FAKE.hidden.value, type: "hidden" },
186
+ { name: "blindfill.signers", value: "AA:BB:CC:DD", type: "text" }
187
+ ]
188
+ };
189
+ return async (_bin, a) => {
190
+ if (a[0] === "--version") return ok("rbw 99.0.0-fixture\n");
191
+ if (a[0] === "unlocked") return locked ? err("locked") : ok("");
192
+ if (locked) return err("rbw vault is locked");
193
+ if (a[0] === "list") return ok(`${item.id} ${item.name} ${FAKE.username}
194
+ `);
195
+ if (a[0] === "get")
196
+ return a[2] === item.id ? ok(JSON.stringify(item)) : err("couldn't find entry for '" + a[2] + "'");
197
+ if (a[0] === "code") return ok(totpFor(FAKE.totpSeed) + "\n");
198
+ return err("unsupported");
199
+ };
200
+ }
201
+ var PASS_ID = "sites/shop.example.test";
202
+ function fakePass(locked, variant) {
203
+ const text = [
204
+ FAKE.password,
205
+ `username: ${FAKE.username}`,
206
+ `url: ${FAKE.uri}`,
207
+ `otpauth://totp/x?secret=${FAKE.totpSeed}`,
208
+ `${FAKE.text.name}: ${FAKE.text.value}`,
209
+ `${FAKE.hidden.name}: ${FAKE.hidden.value}`,
210
+ `blindfill.readable: ${FAKE.text.name}`,
211
+ "CANARY-notes-should-stay-hidden",
212
+ ""
213
+ ].join("\n");
214
+ const runner = async (_b, a) => {
215
+ if (a[0] === "--version")
216
+ return ok(
217
+ variant === "gopass" ? "gopass 99.0.0-fixture\n" : "== pass: the standard unix password manager == fixture\n"
218
+ );
219
+ if (locked) return err("gpg: decryption failed: No secret key");
220
+ if (a[0] === "ls") return ok(`${PASS_ID}
221
+ sites/other.example.test
222
+ `);
223
+ const id = a[a.length - 1];
224
+ if (a[0] === "show" && id === "sites/other.example.test")
225
+ return ok("decoy-pw\nurl: https://other.example.test/\n");
226
+ if (a[0] === "show") return id === PASS_ID ? ok(text) : err(`Error: ${id} is not in the password store.`);
227
+ if (a[0] === "otp")
228
+ return id === PASS_ID ? ok(totpFor(FAKE.totpSeed) + "\n") : err("Error: not in the password store.");
229
+ return err("unsupported");
230
+ };
231
+ const lister = async () => [PASS_ID, "sites/other.example.test"];
232
+ return { runner, lister };
233
+ }
234
+ var KP_ID = "Internet/Fake Shop";
235
+ var KP_DB = "/fixture/db.kdbx";
236
+ var KP_PASSWORD = "fixture-db-password";
237
+ function fakeKeepass() {
238
+ const text = [
239
+ `Title: Fake Shop`,
240
+ `UserName: ${FAKE.username}`,
241
+ `Password: ${FAKE.password}`,
242
+ `URL: ${FAKE.uri}`,
243
+ `Notes: CANARY-notes-should-stay-hidden`,
244
+ `otp: otpauth://totp/x?secret=${FAKE.totpSeed}`,
245
+ `${FAKE.text.name}: ${FAKE.text.value}`,
246
+ `${FAKE.hidden.name}: ${FAKE.hidden.value}`,
247
+ `blindfill.readable: ${FAKE.text.name}`,
248
+ ""
249
+ ].join("\n");
250
+ return async (_b, a, o) => {
251
+ if (a[0] === "--version") return ok("2.99.0-fixture\n");
252
+ if (o?.input !== `${KP_PASSWORD}
253
+ `)
254
+ return err("Error while reading the database: Invalid credentials were provided, please try again.");
255
+ if (a[0] === "ls") return ok("Internet/\nInternet/Fake Shop\nInternet/Other\n");
256
+ if (a[0] === "show") {
257
+ const id = a[a.length - 1];
258
+ if (id === "Internet/Other")
259
+ return ok("Title: Other\nPassword: decoy-pw\nURL: https://other.example.test/\n");
260
+ if (id !== KP_ID) return err(`Could not find entry with path ${id}.`);
261
+ return a.includes("-t") ? ok(totpFor(FAKE.totpSeed) + "\n") : ok(text);
262
+ }
263
+ return err("unsupported");
264
+ };
265
+ }
266
+ var SS_ID = "/org/freedesktop/secrets/collection/login/1";
267
+ function fakeSecretTool(locked) {
268
+ const block = [
269
+ `[${SS_ID}]`,
270
+ `label = Fake Shop`,
271
+ `created = 2026-11-27 00:00:00`,
272
+ `modified = 2026-11-27 00:00:00`,
273
+ `schema = org.freedesktop.Secret.Generic`,
274
+ `attribute.blindfill = 1`,
275
+ `attribute.username = ${FAKE.username}`,
276
+ `attribute.uri = ${FAKE.uri}`,
277
+ `attribute.${FAKE.text.name} = ${FAKE.text.value}`,
278
+ `attribute.${FAKE.hidden.name} = ${FAKE.hidden.value}`,
279
+ `attribute.blindfill.readable = ${FAKE.text.name}`,
280
+ `secret = ${FAKE.password}`,
281
+ ""
282
+ ].join("\n");
283
+ return async (_b, a) => {
284
+ if (a[0] === "--version") return ok("secret-tool fixture\n");
285
+ if (locked) return err("secret-tool: Cannot get secret of a locked object");
286
+ if (a[0] === "search") return ok(block);
287
+ return err("unsupported");
288
+ };
289
+ }
290
+
291
+ // src/backends/selftest.ts
292
+ var SELFTEST_ITEM = "blindfill-selftest";
293
+ function fixtureBackend(id) {
294
+ switch (id) {
295
+ case "bw": {
296
+ const f = fakeBw(false);
297
+ return { backend: new BwBackend({ runner: f.runner, env: f.env }), query: FAKE.name };
298
+ }
299
+ case "op":
300
+ return { backend: new OpBackend({ runner: fakeOp(false) }), query: FAKE.name };
301
+ case "rbw":
302
+ return { backend: new RbwBackend({ runner: fakeRbw(false) }), query: FAKE.name };
303
+ case "pass":
304
+ case "gopass": {
305
+ const f = fakePass(false, id);
306
+ return { backend: new PassBackend({ variant: id, runner: f.runner, lister: f.lister }), query: "shop" };
307
+ }
308
+ case "keepassxc":
309
+ return {
310
+ backend: new KeepassxcBackend({
311
+ runner: fakeKeepass(),
312
+ db: KP_DB,
313
+ env: { BLINDFILL_KEEPASS_PASSWORD: KP_PASSWORD }
314
+ }),
315
+ query: FAKE.name
316
+ };
317
+ case "secret-service":
318
+ return { backend: new SecretServiceBackend({ runner: fakeSecretTool(false) }), query: FAKE.name };
319
+ default:
320
+ throw new BlindfillError("UNSUPPORTED", `unknown backend "${id}"`);
321
+ }
322
+ }
323
+ async function runSelftest(id, opts = {}) {
324
+ let backend;
325
+ let query = SELFTEST_ITEM;
326
+ if (opts.fixture) ({ backend, query } = fixtureBackend(id));
327
+ else backend = createBackend(id, opts.cfg);
328
+ const steps = [];
329
+ const step = async (name, fn) => {
330
+ try {
331
+ const detail = await fn();
332
+ steps.push({ name, ok: true, ...detail ? { detail } : {} });
333
+ return true;
334
+ } catch (e) {
335
+ steps.push({
336
+ name,
337
+ ok: false,
338
+ detail: `${e.code ?? "ERR"}: ${String(e.message).slice(0, 160)}`
339
+ });
340
+ return false;
341
+ }
342
+ };
343
+ const report = {
344
+ backend: id,
345
+ tier: backend.tier,
346
+ mode: opts.fixture ? "fixture" : "live",
347
+ blindfillVersion: opts.version ?? "0.1.0",
348
+ date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
349
+ result: "fail",
350
+ steps,
351
+ note: opts.fixture ? "fixture mode runs against an in-memory fake CLI: it checks blindfill, NOT the vendor tool. Do not report it as a live verification." : `live mode: uses ONLY the fake item named "${SELFTEST_ITEM}". Never point this at a real account item.`
352
+ };
353
+ if (!await step("tool version", async () => report.toolVersion = await backend.version()))
354
+ return report;
355
+ if (!await step("vault unlocked (non-interactive)", () => backend.unlock())) return report;
356
+ let ref;
357
+ await step(`find item "${opts.fixture ? FAKE.name : SELFTEST_ITEM}"`, async () => {
358
+ const refs = await backend.find({ query });
359
+ if (refs.length !== 1)
360
+ throw new BlindfillError("NOT_FOUND", `expected exactly 1 match, got ${refs.length}`);
361
+ ref = refs[0];
362
+ });
363
+ if (!ref) return finish(report);
364
+ const r = ref;
365
+ let meta;
366
+ await step("meta: readable fields + secret field names", async () => {
367
+ meta = await backend.meta(r);
368
+ if (!meta.secretFields.includes("password"))
369
+ throw new BlindfillError("NOT_FOUND", "item has no password field");
370
+ return `username ${meta.username ? "present" : "missing"}, ${meta.uris.length} uri(s), secret fields: ${meta.secretFields.join(", ")}`;
371
+ });
372
+ await step("read(password) is refused", async () => {
373
+ try {
374
+ await backend.read(r, "password");
375
+ } catch (e) {
376
+ if (e.code === "SECRET_ACCESS") return;
377
+ throw e;
378
+ }
379
+ throw new Error("read() returned a secret-class field");
380
+ });
381
+ await step("openSecret(password) -> into(sink), zero-filled afterwards", async () => {
382
+ const h = await backend.openSecret(r, "password");
383
+ let len = 0;
384
+ let leaked = false;
385
+ let kept;
386
+ await h.into((buf) => {
387
+ kept = buf;
388
+ len = buf.length;
389
+ leaked = JSON.stringify(meta ?? {}).includes(buf.toString("utf8"));
390
+ });
391
+ if (leaked) throw new Error("meta() output contains the secret");
392
+ if (!kept?.every((b) => b === 0)) throw new Error("buffer not zero-filled");
393
+ if (len === 0) throw new Error("empty secret");
394
+ return `delivered ${len} bytes to the sink (value not recorded)`;
395
+ });
396
+ if (meta && meta.hasTotp)
397
+ await step("totp code", async () => {
398
+ const c = await backend.totpCode(r);
399
+ return `got a ${c.length}-digit code`;
400
+ });
401
+ else steps.push({ name: "totp code", ok: true, detail: "skipped: item has no TOTP" });
402
+ return finish(report);
403
+ }
404
+ function finish(report) {
405
+ const bad = report.steps.filter((s) => !s.ok).length;
406
+ report.result = bad === 0 ? "pass" : report.steps.some((s) => s.ok && s.name.startsWith("openSecret")) ? "partial" : "fail";
407
+ return report;
408
+ }
409
+
410
+ // src/cli.ts
411
+ var VERSION = (() => {
412
+ try {
413
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
414
+ } catch {
415
+ return "0.0.0";
416
+ }
417
+ })();
418
+ var HELP = `blindfill ${VERSION}: let AI agents sign in without ever seeing the password.
419
+
420
+ Usage: blindfill <command> [options] (JSON on stdout, diagnostics on stderr)
421
+
422
+ Commands:
423
+ login <url|web:origin> open the page, pick the bound item, fill username+password, submit once
424
+ fill fill fields on the current page (--fields username,password,totp,<name>)
425
+ item show show an item: readable fields only (secret field NAMES, never values)
426
+ item list [text] list items (names, origins, field names); item status <id> structural status
427
+ item rename <id> <name> rename; item edit <id> [--origin o ...] [--username u] [--set N=V] [--unset N] [--secret N]
428
+ (origins, blindfill.* other than blindfill.rules, and --secret need a terminal; no reveal)
429
+ item generate <name> generate a password (CSPRNG, optional --policy-file) and save it as a new item; never printed;
430
+ --android <package> also binds that Android app; --no-password saves the item with no
431
+ password (passkey-only sites: password login, fill and register then refuse it)
432
+ item create [name] create an item; username/password are read from the terminal (hidden)
433
+ item password-policy <id> read, or replace with --policy-file, the item's non-secret password policy
434
+ passkey --click <css> sign in with the item's passkey: Chromium only; the page's WebAuthn request is answered once
435
+ passkey register --click <css>
436
+ create a passkey for the page and store it in the item (Chromium, bw; the item must
437
+ bind the page and hold no passkey yet); key never printed
438
+ android fill|passkey arm the companion APK on --serial <adb serial> for one fill of --item (the app must be
439
+ bound by androidapp://<package>, plus its blindfill.signers pin if the item has one; a
440
+ WebView by its https domain); waits --timeout seconds (default 60)
441
+ android register like android fill, into the app's sign-up form (password and confirmation; the item
442
+ binds the app); the caller submits
443
+ android passkey-register --rp-id <domain>
444
+ arm the companion for one passkey creation by the bound app for --rp-id (the item
445
+ must also bind https://<domain> and hold no passkey)
446
+ android install install the packaged companion APK on --serial (adb install -r); --set-services also
447
+ makes it the autofill and credential provider (prints the previous values to restore)
448
+ totp [--fill] print the current TOTP code, or fill it into the page
449
+ totp enroll --selector <css>
450
+ add a TOTP seed to --item from the current page: blindfill reads the one element
451
+ (setup key, or otpauth:// URI in href/value/text); never printed, never replaces a seed
452
+ probe describe the current page's form fields (structure only)
453
+ candidates [--role r] list field candidates (names only)
454
+ backend list list backends and their support tier
455
+ backend selftest [id] round-trip a fake item through a backend (--fixture for offline)
456
+ handoff pause|resume|status hand the browser to a person (CAPTCHA/consent/MFA); agent actions are refused meanwhile
457
+ register --rule <id> fill a registration form from an item bound to the page (fill-only unless --submit)
458
+ page list|discover|diagnose|verify
459
+ open pages (origin+path), planned fields, structural diagnosis, outcome evidence
460
+ profile init|validate|login login recipes: init <name> --item id --origin o --rule id; validate <name>;
461
+ login <name> [--check|--diagnose] [--submit] [--page n] [--revision sha]
462
+ session start|stop|status manage the local Chromium session
463
+ mcp run the MCP server on stdio
464
+
465
+ Options:
466
+ --item <id> backend item id --query <text> search text (must match one item)
467
+ --fields a,b fields to fill --url <url> navigate first
468
+ --submit / --no-submit --cdp <url> attach to a loopback CDP endpoint
469
+ --expect-url <s> success if URL contains s --expect-selector <css> --fail-selector <css>
470
+ --headless (session start / login) --backend <id> override the configured backend
471
+ --fixture (backend selftest) use the built-in fake runner
472
+ -h, --help -v, --version
473
+
474
+ Secrets can be filled but are never printed, returned or logged. See SECURITY.md.
475
+ `;
476
+ var { values, positionals } = parseArgs({
477
+ allowPositionals: true,
478
+ strict: false,
479
+ options: {
480
+ item: { type: "string" },
481
+ query: { type: "string" },
482
+ fields: { type: "string" },
483
+ url: { type: "string" },
484
+ cdp: { type: "string" },
485
+ endpoint: { type: "string" },
486
+ "endpoint-file": { type: "string" },
487
+ browser: { type: "string" },
488
+ page: { type: "string" },
489
+ rule: { type: "string" },
490
+ reason: { type: "string" },
491
+ set: { type: "string", multiple: true },
492
+ unset: { type: "string", multiple: true },
493
+ secret: { type: "string", multiple: true },
494
+ username: { type: "string" },
495
+ "display-name": { type: "string" },
496
+ length: { type: "string" },
497
+ "policy-file": { type: "string" },
498
+ "no-password": { type: "boolean" },
499
+ totp: { type: "boolean" },
500
+ name: { type: "string" },
501
+ origin: { type: "string", multiple: true },
502
+ revision: { type: "string" },
503
+ "success-selector": { type: "string" },
504
+ check: { type: "boolean" },
505
+ diagnose: { type: "boolean" },
506
+ registration: { type: "boolean" },
507
+ executable: { type: "string" },
508
+ backend: { type: "string" },
509
+ role: { type: "string" },
510
+ "expect-url": { type: "string" },
511
+ "expect-selector": { type: "string" },
512
+ "fail-selector": { type: "string" },
513
+ click: { type: "string" },
514
+ selector: { type: "string" },
515
+ serial: { type: "string" },
516
+ "rp-id": { type: "string" },
517
+ android: { type: "string" },
518
+ timeout: { type: "string" },
519
+ "expect-timeout": { type: "string" },
520
+ submit: { type: "boolean" },
521
+ "no-submit": { type: "boolean" },
522
+ fill: { type: "boolean" },
523
+ headless: { type: "boolean" },
524
+ headed: { type: "boolean" },
525
+ "set-services": { type: "boolean" },
526
+ fixture: { type: "boolean" },
527
+ help: { type: "boolean", short: "h" },
528
+ version: { type: "boolean", short: "v" }
529
+ }
530
+ });
531
+ var WITHHELD = "output withheld: it matched a secret";
532
+ function out(o) {
533
+ const text = JSON.stringify(o, null, 2);
534
+ process.stdout.write(
535
+ globalScrubber.guard(
536
+ text,
537
+ JSON.stringify({ ok: false, error: { code: "WITHHELD", message: WITHHELD } })
538
+ ) + "\n"
539
+ );
540
+ }
541
+ function note(s) {
542
+ process.stderr.write(globalScrubber.guard(s, `blindfill: ${WITHHELD}`) + "\n");
543
+ }
544
+ function expectSpec() {
545
+ const e = {
546
+ urlIncludes: values["expect-url"],
547
+ selector: values["expect-selector"],
548
+ failSelector: values["fail-selector"],
549
+ timeoutMs: values["expect-timeout"] ? Number(values["expect-timeout"]) : void 0
550
+ };
551
+ return e.urlIncludes || e.selector || e.failSelector ? e : void 0;
552
+ }
553
+ async function engineFor(needBrowser) {
554
+ const cfg = loadConfig();
555
+ const backend = createBackend(values.backend ?? cfg.backend ?? "bw", cfg);
556
+ const n = unverifiedNotice(backend);
557
+ if (n) note(n);
558
+ if (!needBrowser) return new Engine(backend);
559
+ const { actuator, persist } = await attach(attachSettings(cfg, flagSettings()));
560
+ return new Engine(backend, actuator, persist);
561
+ }
562
+ function flagSettings() {
563
+ return {
564
+ endpoint: values.endpoint,
565
+ cdp: values.cdp,
566
+ endpointFile: values["endpoint-file"],
567
+ browser: values.browser,
568
+ page: values.page
569
+ };
570
+ }
571
+ function fillRequest() {
572
+ return {
573
+ item: values.item,
574
+ query: values.query,
575
+ fields: values.fields ? String(values.fields).split(",").map((s) => s.trim()).filter(Boolean) : void 0,
576
+ url: values.url,
577
+ submit: values.submit === true && values["no-submit"] !== true,
578
+ expect: expectSpec(),
579
+ rule: values.rule
580
+ };
581
+ }
582
+ async function main() {
583
+ const [cmd, sub] = positionals;
584
+ if (values.version) {
585
+ out({ version: VERSION });
586
+ return 0;
587
+ }
588
+ if (values.help || !cmd || cmd === "help") {
589
+ process.stdout.write(HELP);
590
+ return cmd || values.help ? 0 : 1;
591
+ }
592
+ switch (cmd) {
593
+ case "mcp": {
594
+ const { startMcp } = await import("./mcp.js");
595
+ await startMcp();
596
+ return -1;
597
+ }
598
+ case "backend": {
599
+ if (sub === "list") {
600
+ out(
601
+ BACKEND_INFO.map((b) => ({ id: b.id, tier: b.tier, title: b.title, binary: b.binary, doc: b.doc }))
602
+ );
603
+ return 0;
604
+ }
605
+ if (sub === "selftest") {
606
+ const id = positionals[2] ?? values.backend ?? loadConfig().backend ?? "bw";
607
+ const res = await runSelftest(id, { fixture: values.fixture === true, cfg: loadConfig() });
608
+ out(res);
609
+ return res.result === "pass" ? 0 : 1;
610
+ }
611
+ throw new BlindfillError("POLICY", "usage: blindfill backend list|selftest [id]");
612
+ }
613
+ case "session": {
614
+ if (sub === "start") {
615
+ const cfg = loadConfig();
616
+ const headless = values.headed ? false : values.headless ?? cfg.web?.headless ?? true;
617
+ const s = await startSession({
618
+ headless,
619
+ executablePath: values.executable ?? cfg.web?.executablePath
620
+ });
621
+ audit({ event: "session", outcome: "started" });
622
+ out({ started: true, browser: s.browser, endpoint: s.cdp, cdp: s.cdp, headless });
623
+ return 0;
624
+ }
625
+ if (sub === "attach") {
626
+ const cfg = loadConfig();
627
+ const a = attachSettings(cfg, flagSettings());
628
+ const r = await attachSession({ ...a });
629
+ audit({ event: "session", outcome: "attached" });
630
+ out({ attached: true, ...r, locked: false });
631
+ return 0;
632
+ }
633
+ if (sub === "stop") {
634
+ const r = await stopSession();
635
+ audit({ event: "session", outcome: "stopped" });
636
+ out({ ...r, locked: false });
637
+ return 0;
638
+ }
639
+ if (sub === "status") {
640
+ const s = loadSession();
641
+ out(
642
+ s ? {
643
+ running: true,
644
+ browser: s.browser ?? "chromium-cdp",
645
+ endpoint: redactEndpoint(
646
+ resolveEndpoint({ endpoint: s.cdp || void 0, endpointFile: s.endpointFile })
647
+ ),
648
+ endpointFile: s.endpointFile,
649
+ locked: s.policy.locked,
650
+ paused: s.policy.paused ?? null,
651
+ owned: s.owned
652
+ } : { running: false }
653
+ );
654
+ return 0;
655
+ }
656
+ throw new BlindfillError("POLICY", "usage: blindfill session start|attach|stop|status");
657
+ }
658
+ case "item": {
659
+ const origins = values.origin ?? [];
660
+ const policyFile = values["policy-file"];
661
+ const policy = policyFile ? strictJson(readFileSync(policyFile, "utf8")) : void 0;
662
+ if (sub === "generate") {
663
+ const name = positionals[2];
664
+ if (!name || !values.username)
665
+ throw new BlindfillError(
666
+ "POLICY",
667
+ "usage: blindfill item generate <name> (--origin <https origin> [--origin ...] | --android <package>) --username <u> [--display-name n] [--length n] [--policy-file f] [--no-password]"
668
+ );
669
+ const e2 = await engineFor(false);
670
+ out(
671
+ await e2.itemGenerate({
672
+ name,
673
+ origins,
674
+ username: String(values.username),
675
+ displayName: values["display-name"],
676
+ length: values.length ? Number(values.length) : void 0,
677
+ policy,
678
+ androidApp: values.android,
679
+ noPassword: values["no-password"] === true
680
+ })
681
+ );
682
+ return 0;
683
+ }
684
+ if (sub === "create") {
685
+ if (!process.stdin.isTTY || !process.stderr.isTTY)
686
+ throw new BlindfillError(
687
+ "POLICY",
688
+ "item create reads the password from a terminal; use item generate for scripted use"
689
+ );
690
+ const username = String(values.username ?? await readLine("Username: "));
691
+ const password = await readHidden("Password: ");
692
+ if (password !== await readHidden("Confirm password: "))
693
+ throw new BlindfillError("POLICY", "the two passwords differ; nothing was saved");
694
+ const seed = values.totp ? await readHidden("TOTP seed: ") : void 0;
695
+ const e2 = await engineFor(false);
696
+ out(
697
+ await e2.itemCreate({
698
+ name: positionals[2],
699
+ origins,
700
+ username,
701
+ password,
702
+ totpSeed: seed || void 0,
703
+ policy
704
+ })
705
+ );
706
+ return 0;
707
+ }
708
+ if (sub === "password-policy") {
709
+ const e2 = await engineFor(false);
710
+ out(
711
+ await e2.itemPasswordPolicy(
712
+ {
713
+ item: values.item ?? positionals[2],
714
+ query: values.query
715
+ },
716
+ policy,
717
+ !!(process.stdin.isTTY && process.stderr.isTTY)
718
+ )
719
+ );
720
+ return 0;
721
+ }
722
+ const sel = {
723
+ item: values.item ?? void 0,
724
+ query: values.query
725
+ };
726
+ if (sub === "list") {
727
+ out(await (await engineFor(false)).itemList(positionals[2] ?? ""));
728
+ return 0;
729
+ }
730
+ if (sub === "status") {
731
+ out(await (await engineFor(false)).itemStatus({ ...sel, item: sel.item ?? positionals[2] }));
732
+ return 0;
733
+ }
734
+ if (sub === "rename") {
735
+ const [, , a, b2] = positionals;
736
+ const byFlag = !!(sel.item || sel.query);
737
+ const nn = byFlag ? a : b2;
738
+ if (!nn) throw new BlindfillError("POLICY", "usage: blindfill item rename <item id> <new name>");
739
+ out(await (await engineFor(false)).itemRename(byFlag ? sel : { item: a }, nn));
740
+ return 0;
741
+ }
742
+ if (sub === "edit") {
743
+ const human = !!(process.stdin.isTTY && process.stderr.isTTY);
744
+ const set = {};
745
+ for (const kv of values.set ?? []) {
746
+ const i = kv.indexOf("=");
747
+ if (i < 1) throw new BlindfillError("POLICY", "--set needs NAME=VALUE");
748
+ set[kv.slice(0, i)] = kv.slice(i + 1);
749
+ }
750
+ const secrets = {};
751
+ for (const n of values.secret ?? []) {
752
+ if (!human) throw new BlindfillError("POLICY", "secret values are entered at a terminal");
753
+ const v = await readHidden(`New value for ${n}: `);
754
+ if (v !== await readHidden(`Confirm ${n}: `))
755
+ throw new BlindfillError("POLICY", "the two values differ; nothing was saved");
756
+ secrets[n] = v;
757
+ }
758
+ out(
759
+ await (await engineFor(false)).itemEdit(
760
+ { ...sel, item: sel.item ?? positionals[2] },
761
+ {
762
+ origins: origins.length ? origins : void 0,
763
+ username: values.username,
764
+ set,
765
+ unset: values.unset,
766
+ secrets,
767
+ human
768
+ }
769
+ )
770
+ );
771
+ return 0;
772
+ }
773
+ if (sub !== "show")
774
+ throw new BlindfillError(
775
+ "POLICY",
776
+ "usage: blindfill item show|list|status|rename|edit|generate|create|password-policy"
777
+ );
778
+ const e = await engineFor(false);
779
+ out(
780
+ await e.itemShow({
781
+ item: values.item,
782
+ query: values.query
783
+ })
784
+ );
785
+ return 0;
786
+ }
787
+ case "android": {
788
+ if (sub !== "fill" && sub !== "register" && sub !== "passkey" && sub !== "passkey-register" && sub !== "install")
789
+ throw new BlindfillError(
790
+ "POLICY",
791
+ "usage: blindfill android fill|register|passkey --item <id> --serial <adb serial> | android passkey-register --item <id> --rp-id <domain> --serial <adb serial> | android install --serial <adb serial> [--set-services]"
792
+ );
793
+ const serial = values.serial ?? process.env.ANDROID_SERIAL;
794
+ if (!serial)
795
+ throw new BlindfillError("POLICY", "usage: pass --serial <adb serial> (or ANDROID_SERIAL)");
796
+ if (sub === "install") {
797
+ const setServices = Boolean(values["set-services"]);
798
+ const r = await new AndroidActuator().install(serial, setServices);
799
+ const restore = Object.entries(r.previous).map(
800
+ ([k, v]) => v === "null" ? `adb -s ${serial} shell settings delete secure ${k}` : `adb -s ${serial} shell settings put secure ${k} ${v === "" ? `'""'` : v}`
801
+ );
802
+ out({
803
+ status: "installed",
804
+ package: COMPANION,
805
+ apk: r.apk,
806
+ services: setServices ? COMPANION_SERVICES : "unchanged (pass --set-services to switch them)",
807
+ previous: r.previous,
808
+ restore: setServices ? restore : void 0,
809
+ uninstall: `adb -s ${serial} uninstall ${COMPANION}`
810
+ });
811
+ return 0;
812
+ }
813
+ const e = await engineFor(false);
814
+ const sel = {
815
+ item: values.item,
816
+ query: values.query,
817
+ serial,
818
+ timeoutMs: values.timeout ? Number(values.timeout) * 1e3 : void 0
819
+ };
820
+ if (sub === "passkey-register") {
821
+ if (!values["rp-id"]) throw new BlindfillError("POLICY", "usage: pass --rp-id <domain>");
822
+ out(await e.androidPasskeyRegister({ ...sel, rpId: values["rp-id"] }));
823
+ } else
824
+ out(
825
+ await e.androidOffer({
826
+ ...sel,
827
+ kind: sub === "passkey" ? "passkey" : sub === "register" ? "password-new" : "password"
828
+ })
829
+ );
830
+ return 0;
831
+ }
832
+ case "passkey": {
833
+ if (sub !== void 0 && sub !== "register")
834
+ throw new BlindfillError("POLICY", "usage: blindfill passkey [register] --item <id> --click <css>");
835
+ const e = await engineFor(true);
836
+ try {
837
+ const req = {
838
+ item: values.item,
839
+ query: values.query,
840
+ url: values.url,
841
+ click: values.click,
842
+ expect: expectSpec()
843
+ };
844
+ out(await (sub === "register" ? e.passkeyRegister(req) : e.passkey(req)));
845
+ } finally {
846
+ await disconnect(e);
847
+ }
848
+ return 0;
849
+ }
850
+ case "totp": {
851
+ if (sub === "enroll") {
852
+ if (!values.selector)
853
+ throw new BlindfillError(
854
+ "POLICY",
855
+ "usage: blindfill totp enroll (--item <id> | --query <text>) --selector <css>"
856
+ );
857
+ const e2 = await engineFor(true);
858
+ try {
859
+ out(
860
+ await e2.totpEnroll({
861
+ item: values.item,
862
+ query: values.query,
863
+ selector: String(values.selector)
864
+ })
865
+ );
866
+ } finally {
867
+ await disconnect(e2);
868
+ }
869
+ return 0;
870
+ }
871
+ if (values.fill) {
872
+ const e2 = await engineFor(true);
873
+ const { fields: _f, ...req } = fillRequest();
874
+ const r = await e2.fillTotp(req);
875
+ await disconnect(e2);
876
+ out(r);
877
+ return 0;
878
+ }
879
+ const e = await engineFor(false);
880
+ out(
881
+ await e.totpCode({
882
+ item: values.item,
883
+ query: values.query
884
+ })
885
+ );
886
+ return 0;
887
+ }
888
+ case "probe":
889
+ case "candidates": {
890
+ const e = await engineFor(true);
891
+ const r = cmd === "probe" ? await e.probe(values.url) : await e.candidates(
892
+ values.role,
893
+ values.url
894
+ );
895
+ await disconnect(e);
896
+ out(r);
897
+ return 0;
898
+ }
899
+ case "handoff": {
900
+ const e = await engineFor(true);
901
+ try {
902
+ if (sub === "pause") out(e.handoffPause(String(values.reason ?? "other")));
903
+ else if (sub === "resume") out(e.handoffResume());
904
+ else if (sub === "status") out(e.handoffStatus());
905
+ else
906
+ throw new BlindfillError(
907
+ "POLICY",
908
+ "usage: blindfill handoff pause --reason captcha|consent|mfa|other | resume | status"
909
+ );
910
+ } finally {
911
+ await disconnect(e);
912
+ }
913
+ return 0;
914
+ }
915
+ case "register": {
916
+ const e = await engineFor(true);
917
+ try {
918
+ const req = fillRequest();
919
+ if (!req.rule) throw new BlindfillError("POLICY", "register needs --rule <registration rule id>");
920
+ out(await e.register({ ...req, rule: req.rule }));
921
+ } finally {
922
+ await disconnect(e);
923
+ }
924
+ return 0;
925
+ }
926
+ case "page": {
927
+ if (sub === "list") {
928
+ const e = await engineFor(true);
929
+ try {
930
+ out(e.pages());
931
+ } finally {
932
+ await disconnect(e);
933
+ }
934
+ return 0;
935
+ }
936
+ if (sub === "discover" || sub === "diagnose") {
937
+ const e = await engineFor(true);
938
+ try {
939
+ const req = fillRequest();
940
+ out(
941
+ sub === "discover" ? await e.discover({ ...req, registration: values.registration === true }) : await e.diagnose({ item: req.item, query: req.query, rule: req.rule, url: req.url })
942
+ );
943
+ } finally {
944
+ await disconnect(e);
945
+ }
946
+ return 0;
947
+ }
948
+ if (sub === "verify") {
949
+ const success = values["success-selector"];
950
+ if (!success)
951
+ throw new BlindfillError(
952
+ "POLICY",
953
+ "usage: blindfill page verify --success-selector <css> [--fail-selector <css>]"
954
+ );
955
+ const e = await engineFor(true);
956
+ try {
957
+ out(await e.verify({ success, failure: values["fail-selector"] }));
958
+ } finally {
959
+ await disconnect(e);
960
+ }
961
+ return 0;
962
+ }
963
+ throw new BlindfillError("POLICY", "usage: blindfill page list|discover|diagnose|verify");
964
+ }
965
+ case "profile": {
966
+ const name = positionals[2];
967
+ if (!name) throw new BlindfillError("POLICY", "usage: blindfill profile init|validate|login <name>");
968
+ if (sub === "validate") {
969
+ const p = loadProfile(name);
970
+ out({ status: "valid", name: p.name, revision: p.revision, origin: p.doc.web.origin });
971
+ return 0;
972
+ }
973
+ if (sub === "init") {
974
+ const item = values.item;
975
+ const origin = values.origin?.[0];
976
+ const rule = values.rule;
977
+ if (!item || !origin || !rule)
978
+ throw new BlindfillError(
979
+ "POLICY",
980
+ "usage: blindfill profile init <name> --item <id> --origin <origin> --rule <rule id> [--fields a,b] [--submit]"
981
+ );
982
+ const e = await engineFor(false);
983
+ const meta = await e.itemShow({ item });
984
+ const doc = {
985
+ version: 1,
986
+ item,
987
+ item_name: meta.name,
988
+ web: {
989
+ origin,
990
+ rule,
991
+ ...values.fields ? {
992
+ fields: String(values.fields).split(",").map((x) => x.trim()).filter(Boolean)
993
+ } : {},
994
+ submit: values.submit === true
995
+ }
996
+ };
997
+ const { path, profile } = createProfile(name, doc);
998
+ out({ status: "created", name, path, revision: profile.revision });
999
+ return 0;
1000
+ }
1001
+ if (sub === "login") {
1002
+ const p = loadProfile(name);
1003
+ assertRevision(p, values.revision);
1004
+ const e = await engineFor(true);
1005
+ try {
1006
+ out(
1007
+ await e.runProfile(p, {
1008
+ check: values.check === true,
1009
+ diagnose: values.diagnose === true,
1010
+ submit: values.submit === true ? true : values["no-submit"] === true ? false : void 0,
1011
+ page: values.page !== void 0 && /^\d+$/.test(String(values.page)) ? Number(values.page) : void 0,
1012
+ expect: expectSpec()
1013
+ })
1014
+ );
1015
+ } finally {
1016
+ await disconnect(e);
1017
+ }
1018
+ return 0;
1019
+ }
1020
+ throw new BlindfillError("POLICY", "usage: blindfill profile init|validate|login <name>");
1021
+ }
1022
+ case "fill": {
1023
+ const e = await engineFor(true);
1024
+ try {
1025
+ out(await e.fill(fillRequest()));
1026
+ } finally {
1027
+ await disconnect(e);
1028
+ }
1029
+ return 0;
1030
+ }
1031
+ case "login": {
1032
+ const target = sub;
1033
+ if (!target) throw new BlindfillError("POLICY", "usage: blindfill login <url|web:origin> [--item id]");
1034
+ const url = target.startsWith("web:") ? target.slice(4) : target;
1035
+ const aset = attachSettings(loadConfig(), flagSettings());
1036
+ if (!loadSession() && !aset.endpoint && !aset.endpointFile) {
1037
+ const cfg = loadConfig();
1038
+ const s = await startSession({
1039
+ headless: values.headed ? false : values.headless ?? cfg.web?.headless ?? true,
1040
+ executablePath: values.executable ?? cfg.web?.executablePath
1041
+ });
1042
+ note(
1043
+ `blindfill: started a browser session (${redactEndpoint(s.cdp)}); stop it with: blindfill session stop`
1044
+ );
1045
+ }
1046
+ const e = await engineFor(true);
1047
+ try {
1048
+ const req = fillRequest();
1049
+ out(await e.fill({ ...req, url, submit: values["no-submit"] ? false : true }));
1050
+ } finally {
1051
+ await disconnect(e);
1052
+ }
1053
+ return 0;
1054
+ }
1055
+ default:
1056
+ process.stderr.write(HELP);
1057
+ return 1;
1058
+ }
1059
+ }
1060
+ function readLine(prompt) {
1061
+ return new Promise((res) => {
1062
+ process.stderr.write(prompt);
1063
+ process.stdin.setEncoding("utf8");
1064
+ process.stdin.once("data", (d) => {
1065
+ process.stdin.pause();
1066
+ res(String(d).replace(/\r?\n$/, ""));
1067
+ });
1068
+ });
1069
+ }
1070
+ function readHidden(prompt) {
1071
+ return new Promise((res, rej) => {
1072
+ process.stderr.write(prompt);
1073
+ const stdin = process.stdin;
1074
+ stdin.setRawMode(true);
1075
+ stdin.resume();
1076
+ stdin.setEncoding("utf8");
1077
+ let buf = "";
1078
+ const onData = (ch) => {
1079
+ for (const c of ch) {
1080
+ if (c === "") {
1081
+ stdin.setRawMode(false);
1082
+ stdin.off("data", onData);
1083
+ process.stderr.write("\n");
1084
+ return rej(new BlindfillError("POLICY", "cancelled"));
1085
+ }
1086
+ if (c === "\r" || c === "\n") {
1087
+ stdin.setRawMode(false);
1088
+ stdin.pause();
1089
+ stdin.off("data", onData);
1090
+ process.stderr.write("\n");
1091
+ return res(buf);
1092
+ }
1093
+ if (c === "\x7F") buf = buf.slice(0, -1);
1094
+ else buf += c;
1095
+ }
1096
+ };
1097
+ stdin.on("data", onData);
1098
+ });
1099
+ }
1100
+ async function disconnect(e) {
1101
+ await e.stop();
1102
+ }
1103
+ main().then((code) => {
1104
+ if (code >= 0) process.exit(code);
1105
+ }).catch((err2) => {
1106
+ const be = err2;
1107
+ const code = be?.code ?? "ERROR";
1108
+ const message = String(be?.message ?? err2);
1109
+ out({ ok: false, error: { code, message }, candidates: be?.candidates });
1110
+ note(`blindfill: ${code}: ${message}`);
1111
+ process.exit(1);
1112
+ });