@noisybrood/cli 0.1.0 → 0.2.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/README.md CHANGED
@@ -14,15 +14,17 @@ writes to you, how often, who has gone quiet, and what Brood has decided about
14
14
  each. It never reads a message. The index holds no subject, no body and no
15
15
  attachment, so there is nothing of what anyone wrote for it to show you.
16
16
 
17
- It changes your mailbox in two ways only, `brood hush` and `brood unhush`, and
18
- only once you have signed in with that permission.
17
+ It changes your mailbox in three ways only: `brood hush` and `brood unhush`,
18
+ which file a sender's mail and bring it back, and `brood keep add`, which adds
19
+ addresses and domains to the list of senders Brood never files. Each needs you
20
+ to have signed in with that permission.
19
21
 
20
22
  ## Install
21
23
 
22
24
  It needs Node 24 or later.
23
25
 
24
26
  ```
25
- npm install --global @noisybrood/cli@0.1.0
27
+ npm install --global @noisybrood/cli@0.2.0
26
28
  ```
27
29
 
28
30
  Name the version. Each one published is fixed once it is on npm, and carries
@@ -40,9 +42,10 @@ signed in to Noisy Brood, and approve the code. Nothing is typed into the
40
42
  terminal but the command. `brood login --read-only` asks for a session that
41
43
  can only read.
42
44
 
43
- The session is kept in `~/.config/brood/credentials.json` (or under
44
- `XDG_CONFIG_HOME`), readable only by you, and `brood logout` ends it at Brood
45
- before forgetting it. To shut it out at once, revoke it on your account page.
45
+ The session is kept in your keychain: macOS's, or on Linux the desktop's
46
+ Secret Service. Where there is none, it goes in `~/.config/brood/credentials.json`
47
+ (or under `XDG_CONFIG_HOME`), readable only by you. `brood logout` ends it at
48
+ Brood before forgetting it. To shut it out at once, revoke it on your account page.
46
49
 
47
50
  ## Ask
48
51
 
@@ -60,6 +63,12 @@ as the API gives it.
60
63
  Before an answer, brood says any mailbox it could not read whole, so a quiet
61
64
  answer is never taken for a quiet mailbox.
62
65
 
66
+ ## Reading the comments
67
+
68
+ The code's comments refer to internal design documents and issues, such as
69
+ `DD10 §6` or `#1367`. Those are private. You do not need them to read the code
70
+ or run its tests.
71
+
63
72
  ## This repository
64
73
 
65
74
  This repository is where brood is built and published, copied one way from a
@@ -0,0 +1,58 @@
1
+ import { APP_ORIGIN } from "./origin.js";
2
+ /**
3
+ * What a client of the API needs, and nothing of how the app answers (#1408):
4
+ * where to call and sign in, each operation's arguments and answer, and the
5
+ * problems a client branches on. The CLI imports this alone, so its public
6
+ * mirror carries it alone; the operations' descriptions, the arguments'
7
+ * narrowing and when each problem is answered are the app's half of this
8
+ * package, which re-exports this.
9
+ */
10
+ export * from "./values.js";
11
+ /** Where every operation is called, by POST with its arguments in the body (DD21 §2, §3). */
12
+ export const API_BASE = `${APP_ORIGIN}/api/v1`;
13
+ /**
14
+ * Where a client signs in (DD21 §4): Clerk's OAuth server for the production
15
+ * instance, and each client's id there. A client id is not a secret: a public
16
+ * client is known by it alone, and ships it (#1354).
17
+ */
18
+ export const SIGN_IN = {
19
+ issuer: "https://clerk.app.noisybrood.com",
20
+ clients: { cli: "P029s9c7VAQInceB" },
21
+ };
22
+ /** The codes a problem carries, which clients branch on (DD21 §8, RFC 9457). */
23
+ export const PROBLEM_CODES = [
24
+ "invalid_argument",
25
+ "unauthenticated",
26
+ "credential_revoked",
27
+ "insufficient_scope",
28
+ "plan_required",
29
+ "not_found",
30
+ "mailbox_unreachable",
31
+ "never_quiet",
32
+ "in_progress",
33
+ "rate_limited",
34
+ "internal",
35
+ ];
36
+ /**
37
+ * Each problem's status and title (DD21 §8, RFC 9457), which a client shows
38
+ * and branches on.
39
+ */
40
+ export const PROBLEM_TITLES = {
41
+ invalid_argument: { status: 400, title: "An argument is not valid" },
42
+ unauthenticated: { status: 401, title: "Not signed in" },
43
+ credential_revoked: { status: 401, title: "This credential was revoked" },
44
+ insufficient_scope: { status: 403, title: "This credential may not do that" },
45
+ plan_required: { status: 403, title: "This needs Pro" },
46
+ not_found: { status: 404, title: "Not found" },
47
+ mailbox_unreachable: {
48
+ status: 409,
49
+ title: "Brood cannot reach this mailbox",
50
+ },
51
+ never_quiet: {
52
+ status: 409,
53
+ title: "Your never-quiet list keeps this in view",
54
+ },
55
+ in_progress: { status: 409, title: "Brood is still undoing this" },
56
+ rate_limited: { status: 429, title: "Too many calls" },
57
+ internal: { status: 500, title: "Something went wrong" },
58
+ };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The app's origin: where the API answers, and where every surface that links
3
+ * into the app or posts to it builds its address from. A file of its own,
4
+ * with no imports, so the pitch site's middleware and the checks can read it
5
+ * without the rest of the API.
6
+ */
7
+ export const APP_ORIGIN = "https://app.noisybrood.com";
@@ -22,6 +22,7 @@ export const CLASSIFICATION_REASONS = [
22
22
  "restored",
23
23
  "kept_out",
24
24
  "adopted",
25
+ "by_hand",
25
26
  ];
26
27
  /** How a week sounded beside the one before; `first` with none to compare. */
27
28
  export const TONES = ["quieter", "louder", "much the same", "first"];
@@ -50,6 +51,42 @@ export const SHOWN = ["active", "quieted", "left"];
50
51
  export const DIRECTIONS = ["inbound", "outbound"];
51
52
  /** How the person was addressed on a message. */
52
53
  export const ADDRESSED = ["to", "cc", "neither"];
54
+ /**
55
+ * What an entry on the never-quiet list names: one sender's address, a domain
56
+ * and everything under it, a pattern on an address's local part, or an
57
+ * address copied on a message, which keeps that mail alone in view (#663).
58
+ */
59
+ export const KEPT_KINDS = ["address", "domain", "pattern", "copied"];
60
+ /**
61
+ * What became of one line given to `keep`, or would, as the never-quiet
62
+ * list's paste says it in the app, which a test keeps equal: kept, there
63
+ * already, said twice, not in force since a filter could not change, or
64
+ * refused for what it is.
65
+ */
66
+ export const KEEP_OUTCOMES = [
67
+ "added",
68
+ "already_listed",
69
+ "repeated",
70
+ "not_in_force",
71
+ "invalid_address",
72
+ "invalid_domain",
73
+ "invalid_pattern",
74
+ "unrenderable",
75
+ ];
76
+ /**
77
+ * What became of one line given to `add_customers`, or would, as the
78
+ * Customers page's paste says it, which a test keeps equal: a customer, one
79
+ * already, a domain that names no organisation, one that cannot be read, a
80
+ * site's address, or a line Brood failed on.
81
+ */
82
+ export const CUSTOMER_OUTCOMES = [
83
+ "added",
84
+ "already",
85
+ "shared",
86
+ "invalid",
87
+ "address",
88
+ "failed",
89
+ ];
53
90
  /** A list of values as the reference writes them: each as code, `or` before the last. */
54
91
  export const listed = (values) => values.length < 2
55
92
  ? values.map((v) => `\`${v}\``).join("")
@@ -1,10 +1,4 @@
1
1
  // The figures the CLI uses, as Brood's figures hold them.
2
- export const API_ACTS_PER_MINUTE = 10;
3
- export const API_CALLS_PER_MINUTE = 120;
4
2
  export const API_PAGE_MAX = 200;
5
3
  export const API_STRETCH_DAYS = 30;
6
- export const API_UNUSED_DAYS = 90;
7
4
  export const PORTRAIT_DAYS = 90;
8
- export const QUIET_REGULAR_MIN_MONTHS = 2;
9
- export const QUIET_REGULAR_MONTHS = 3;
10
- export const RETENTION_DAYS = 120;
@@ -0,0 +1,2 @@
1
+ // The dark scheme's colours the CLI uses, as Brood's tokens hold them.
2
+ export const DARK_BARN = "#d4786b";
package/dist/brood.js CHANGED
@@ -1,4 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ import { readFile } from "node:fs/promises";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { text } from "node:stream/consumers";
5
+ import { keychainFor } from "./keychain.js";
2
6
  import { run } from "./main.js";
3
7
  process.exitCode = await run({
4
8
  fetch: (url, init) => fetch(url, init),
@@ -8,4 +12,22 @@ process.exitCode = await run({
8
12
  out: (line) => process.stdout.write(`${line}\n`),
9
13
  err: (line) => process.stderr.write(`${line}\n`),
10
14
  tty: process.stdout.isTTY === true,
15
+ input: () => text(process.stdin),
16
+ read: (path) => readFile(path, "utf8"),
17
+ // Asked on standard error, so an answer piped elsewhere holds none of it.
18
+ ask: process.stdin.isTTY && process.stderr.isTTY
19
+ ? async (question) => {
20
+ const terminal = createInterface({
21
+ input: process.stdin,
22
+ output: process.stderr,
23
+ });
24
+ try {
25
+ return await terminal.question(question);
26
+ }
27
+ finally {
28
+ terminal.close();
29
+ }
30
+ }
31
+ : null,
32
+ keychain: keychainFor(process.platform),
11
33
  }, process.argv.slice(2));
package/dist/client.js CHANGED
@@ -1,4 +1,4 @@
1
- import { API_BASE, PROBLEM_CODES, PROBLEMS, } from "./brood/api/src/index.js";
1
+ import { API_BASE, PROBLEM_CODES, PROBLEM_TITLES, } from "./brood/api/src/client.js";
2
2
  import { clean, cleaned, isRecord, Refused, Refusal } from "./io.js";
3
3
  import { freshCredentials, refresh } from "./sign-in.js";
4
4
  import { VERSION } from "./version.js";
@@ -27,16 +27,16 @@ function refusalOf(problem, retryAfter) {
27
27
  // The day's rule changes have a reason the server gives; the minute's
28
28
  // limit has only its wait.
29
29
  return new Refusal(problem.detail
30
- ? `${PROBLEMS.rate_limited.title}. ${problem.detail}`
30
+ ? `${PROBLEM_TITLES.rate_limited.title}. ${problem.detail}`
31
31
  : retryAfter
32
- ? `${PROBLEMS.rate_limited.title}. Try again in ${clean(retryAfter)} seconds.`
33
- : `${PROBLEMS.rate_limited.title}. Try again in a minute.`);
32
+ ? `${PROBLEM_TITLES.rate_limited.title}. Try again in ${clean(retryAfter)} seconds.`
33
+ : `${PROBLEM_TITLES.rate_limited.title}. Try again in a minute.`);
34
34
  case "invalid_argument":
35
- return new Refusal(`${PROBLEMS.invalid_argument.title}: ${problem.detail ?? "the request"}.`);
35
+ return new Refusal(`${PROBLEM_TITLES.invalid_argument.title}: ${problem.detail ?? "the request"}.`);
36
36
  default:
37
37
  return new Refusal(problem.detail
38
- ? `${PROBLEMS[problem.code].title}. ${problem.detail}`
39
- : `${PROBLEMS[problem.code].title}.`);
38
+ ? `${PROBLEM_TITLES[problem.code].title}. ${problem.detail}`
39
+ : `${PROBLEM_TITLES[problem.code].title}.`);
40
40
  }
41
41
  }
42
42
  async function send(io, operation, args, credentials) {
package/dist/commands.js CHANGED
@@ -1,7 +1,7 @@
1
- import { CLASSIFICATION_STATES, TONE_TITLES, } from "./brood/api/src/index.js";
1
+ import { CLASSIFICATION_STATES, TONE_TITLES, } from "./brood/api/src/client.js";
2
2
  import { API_PAGE_MAX, API_STRETCH_DAYS, PORTRAIT_DAYS } from "./brood/figures/index.js";
3
3
  import { call } from "./client.js";
4
- import { clean, Refusal } from "./io.js";
4
+ import { clean, Refusal, Refused } from "./io.js";
5
5
  import { day, dim, json, more, rows, state } from "./out.js";
6
6
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7
7
  /**
@@ -113,17 +113,23 @@ async function classificationsOf(io, options, name) {
113
113
  }
114
114
  throw tooMany(name);
115
115
  }
116
- /** One classification to act on: the one found, or the choice put back to the person. */
116
+ /**
117
+ * The one classification a name means. For `hush`, none is null, so the
118
+ * sender is filed by hand (#1355); for `unhush`, none is a refusal.
119
+ */
117
120
  async function chosen(io, style, options, name, verb) {
118
121
  const all = await classificationsOf(io, options, name);
119
122
  const found = verb === "unhush"
120
123
  ? all.filter((c) => c.state === "active" || c.state === "quieted")
121
124
  : all;
122
125
  const [only, ...others] = found;
123
- if (!only)
126
+ if (!only) {
127
+ if (verb === "hush" && !UUID.test(name))
128
+ return null;
124
129
  throw new Refusal(verb === "hush"
125
- ? `Brood has proposed nothing for ${clean(name)}.`
130
+ ? `Brood has no classification ${clean(name)}.`
126
131
  : `Nothing is filed for ${clean(name)}.`);
132
+ }
127
133
  if (!others.length)
128
134
  return only.id;
129
135
  io.err(`Several classifications cover ${clean(name)}:`);
@@ -369,14 +375,37 @@ const rules = async (io, style, options, args) => {
369
375
  const hush = async (io, style, options, args) => {
370
376
  const name = one(args, "sender, by its root domain or address, or a classification by its id");
371
377
  const id = await chosen(io, style, options, name, "hush");
372
- const answer = await call(io, "hush", {
373
- ...owner(options),
374
- classification: id,
375
- });
378
+ // None proposed: the sender itself, found over the days its portrait
379
+ // covers, as brood senders finds one, and filed by hand (DD21 §5, #1355).
380
+ let answer;
381
+ try {
382
+ answer = await call(io, "hush", {
383
+ ...owner(options),
384
+ ...(id !== null
385
+ ? { classification: id }
386
+ : {
387
+ sender: (await senderOf(io, options, name, {
388
+ since: daysBack(io, PORTRAIT_DAYS),
389
+ })).sender,
390
+ }),
391
+ });
392
+ }
393
+ catch (error) {
394
+ // A sender the engine would never file, said as why rather than as an
395
+ // argument refused.
396
+ if (id === null &&
397
+ error instanceof Refused &&
398
+ error.code === "invalid_argument")
399
+ throw new Refusal(`Brood does not file ${clean(name)} by hand: it is a customer's, someone you write to or a colleague, one of your own filters already acts on it, or its address is one a filter cannot hold exactly.`);
400
+ throw error;
401
+ }
376
402
  shown(io, style, answer, (h) => {
403
+ const what = h.sender_written.subject;
377
404
  io.out(h.already
378
- ? `${clean(name)} was filed already.`
379
- : `Filed ${clean(name)} out of your inbox.`);
405
+ ? `${what} was filed already.`
406
+ : `Filed ${what} out of your inbox, under ${h.sender_written.path}.`);
407
+ if (!same(what, name) && !UUID.test(name))
408
+ io.out(`Brood files ${clean(name)} address by address, since you write to someone there or it is shared, so only ${what} is filed.`);
380
409
  if (h.failed.length)
381
410
  io.out(`Brood could not install its filter in ${h.failed.length === 1 ? "one mailbox" : `${h.failed.length} mailboxes`}: ${h.failed.join(", ")}.`);
382
411
  });
@@ -396,6 +425,154 @@ const unhush = async (io, style, options, args) => {
396
425
  : "Undone. Its mail is coming back to your inbox, the first of it now and the rest within the hour.");
397
426
  });
398
427
  };
428
+ const many = (n) => (n === 1 ? "one" : String(n));
429
+ /**
430
+ * `brood keep add` and `brood customers add`: the app's paste, checked first
431
+ * and added on a yes. A list read from standard input leaves nobody to ask
432
+ * there, so it is added only with `--yes`; `--check` stops at the check.
433
+ */
434
+ async function paste(io, style, options, args, spec) {
435
+ if (args.length > 1)
436
+ throw new Refusal("Name one file, or none for standard input.");
437
+ if (options.check && options.yes)
438
+ throw new Refusal("--check and --yes ask for opposite things: give one.");
439
+ without(options, ["limit", "cursor"], spec.command);
440
+ const [file] = args;
441
+ let given;
442
+ try {
443
+ given = file === undefined ? await io.input() : await io.read(file);
444
+ }
445
+ catch (e) {
446
+ // The code alone, such as ENOENT: the path is the person's own, said back cleaned.
447
+ const code = e instanceof Error && "code" in e && typeof e.code === "string"
448
+ ? ` (${e.code})`
449
+ : "";
450
+ throw new Refusal(`brood could not read ${file === undefined ? "standard input" : clean(file)}${code}.`);
451
+ }
452
+ if (!given.trim())
453
+ throw new Refusal(`${file === undefined ? "Standard input" : clean(file)} holds no ${spec.holds}.`);
454
+ const lines = (a) => rows(io, spec.told(a, style));
455
+ const body = { ...owner(options), lines: given };
456
+ if (options.yes)
457
+ return shown(io, style, await spec.send(io, body), (a) => {
458
+ lines(a);
459
+ spec.said(io, a);
460
+ });
461
+ const asking = file === undefined ? null : io.ask;
462
+ if (!options.check && (style.json || asking === null))
463
+ throw new Refusal(style.json
464
+ ? "With --json, give --check to see what would be added, or --yes to add it."
465
+ : file === undefined
466
+ ? "brood cannot ask while it reads the list from standard input: give --yes to add it, or --check to see what would be added."
467
+ : "Nobody is at a terminal to ask: give --yes to add the list, or --check to see what would be added.");
468
+ const checked = await spec.send(io, { ...body, check: true });
469
+ shown(io, style, checked, lines);
470
+ if (options.check || asking === null)
471
+ return;
472
+ const fresh = checked.data.lines.filter((l) => l.outcome === "added").length;
473
+ if (fresh === 0)
474
+ return io.out(spec.nothingNew);
475
+ const yes = await asking(`${spec.question(fresh)} [y/N] `);
476
+ if (!/^y(es)?$/i.test(yes.trim()))
477
+ return io.out("Nothing added.");
478
+ shown(io, style, await spec.send(io, body), (a) => {
479
+ if (spec.again(a))
480
+ lines(a);
481
+ spec.said(io, a);
482
+ });
483
+ }
484
+ /** A paste's lines as rows, each outcome in words; `to add` for `added` in a check. */
485
+ const told = (a, words, style) => a.lines.map((l) => [
486
+ dim(style, `line ${l.line}`),
487
+ l.text,
488
+ a.checked && l.outcome === "added" ? "to add" : words[l.outcome],
489
+ ]);
490
+ const added = (a) => a.lines.filter((l) => l.outcome === "added").length;
491
+ /** What became of a line given to `keep`, in words. */
492
+ const KEPT = {
493
+ added: "added",
494
+ already_listed: "already kept",
495
+ repeated: "repeats an earlier line",
496
+ not_in_force: "not added",
497
+ invalid_address: "refused: not an address",
498
+ invalid_domain: "refused: not a domain",
499
+ invalid_pattern: "refused: not a pattern",
500
+ unrenderable: "refused: a filter cannot hold it exactly",
501
+ };
502
+ /** What became of a line given to `add_customers`, in words. */
503
+ const NAMED = {
504
+ added: "added",
505
+ already: "a customer already",
506
+ shared: "refused: a mail provider's domain or your own",
507
+ invalid: "refused: no domain Brood can read",
508
+ address: "refused: a site's address, so write its domain",
509
+ failed: "not added: Brood failed on it, so try it again",
510
+ };
511
+ const KEEP = {
512
+ command: "brood keep add",
513
+ holds: "addresses or domains",
514
+ send: (io, body) => call(io, "keep", body),
515
+ told: (k, style) => told(k, KEPT, style),
516
+ question: (n) => `Keep ${many(n)}?`,
517
+ nothingNew: "Nothing new to keep.",
518
+ again: (k) => !k.in_force,
519
+ said(io, k) {
520
+ if (!k.in_force)
521
+ return io.out("Nothing was added: one of Brood's filters could not change, and the list holds only what every filter keeps. Try again later.");
522
+ io.out(added(k) === 0
523
+ ? "Nothing new to keep."
524
+ : `Kept ${many(added(k))}. Brood never files their mail.`);
525
+ },
526
+ };
527
+ const CUSTOMERS = {
528
+ command: "brood customers add",
529
+ holds: "customers",
530
+ send: (io, body) => call(io, "add_customers", body),
531
+ told: (c, style) => told(c, NAMED, style),
532
+ question: (n) => `Add ${n === 1 ? "one customer" : `${n} customers`}?`,
533
+ nothingNew: "No new customers to add.",
534
+ again: (c) => c.lines.some((l) => l.outcome === "failed"),
535
+ said(io, c) {
536
+ const n = added(c);
537
+ if (n === 0)
538
+ return io.out("No new customers were added.");
539
+ io.out(`Added ${n === 1 ? "one customer" : `${n} customers`}. Brood proposes a home for their mail ${c.later ? "shortly" : "now, among your proposals"}.`);
540
+ },
541
+ };
542
+ /** `brood customers add`, a list of customers. */
543
+ const customers = async (io, style, options, args) => {
544
+ const [verb, ...rest] = args;
545
+ if (verb !== "add")
546
+ throw new Refusal(`brood customers takes add${verb === undefined ? "" : `, not ${clean(verb)}`}.`);
547
+ return paste(io, style, options, rest, CUSTOMERS);
548
+ };
549
+ /** `brood keep`, the never-quiet list; `brood keep add`, a list added to it. */
550
+ const keep = async (io, style, options, args) => {
551
+ const [verb, ...rest] = args;
552
+ if (verb === "add")
553
+ return paste(io, style, options, rest, KEEP);
554
+ if (verb !== undefined)
555
+ throw new Refusal(`brood keep takes add, or nothing: not ${clean(verb)}.`);
556
+ without(options, ["check", "yes"], "brood keep");
557
+ const answer = await call(io, "list_kept", {
558
+ ...owner(options),
559
+ ...page(options),
560
+ });
561
+ shown(io, style, answer, (data) => {
562
+ if (!data.kept.length)
563
+ io.out("Nothing of your own is on the list.");
564
+ rows(io, data.kept.map((k) => [
565
+ k.value,
566
+ k.kind,
567
+ k.last_wrote ? `last wrote ${day(k.last_wrote)}` : "",
568
+ ]));
569
+ if (!data.seeds.length)
570
+ return;
571
+ io.out("");
572
+ io.out("Kept for everyone:");
573
+ rows(io, data.seeds.map((s) => [s.value, dim(style, s.why)]));
574
+ });
575
+ };
399
576
  /** Each command, and the options it takes, so one it does not is refused rather than ignored. */
400
577
  export const COMMANDS = {
401
578
  accounts: { run: accounts, takes: [] },
@@ -414,4 +591,6 @@ export const COMMANDS = {
414
591
  rules: { run: rules, takes: ["classification", "limit", "cursor"] },
415
592
  hush: { run: hush, takes: [] },
416
593
  unhush: { run: unhush, takes: [] },
594
+ keep: { run: keep, takes: ["check", "yes", "limit", "cursor"] },
595
+ customers: { run: customers, takes: ["check", "yes"] },
417
596
  };
@@ -0,0 +1,104 @@
1
+ import { spawn } from "node:child_process";
2
+ /**
3
+ * The longest command line handed to `security -i`, with room to spare: past
4
+ * about 4,000 characters it cuts the line and keeps what it read (DD10 §6).
5
+ * The line is the session in base64 and the command around it, so a session
6
+ * past about 2,500 characters goes to the file.
7
+ */
8
+ export const MAC_LINE_MAX = 3_500;
9
+ /** How long a keychain command may take: a locked keyring waiting on a desktop prompt is no keychain. */
10
+ export const KEYCHAIN_TIMEOUT_MS = 5_000;
11
+ /** Where the session is kept in the keychain: the item's service and account. */
12
+ export const SERVICE = "com.noisybrood.cli";
13
+ export const ACCOUNT = "session";
14
+ /**
15
+ * The session as the keychain holds it: base64, so no character in it can
16
+ * end `security -i`'s command line or need quoting there.
17
+ */
18
+ const encode = (secret) => Buffer.from(secret, "utf8").toString("base64");
19
+ // An item brood cannot decode is still brood's: "" says it is there, so the
20
+ // store removes it rather than taking it for none.
21
+ const decode = (held) => {
22
+ const text = held.trim();
23
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(text))
24
+ return "";
25
+ return Buffer.from(text, "base64").toString("utf8");
26
+ };
27
+ /** macOS's login keychain, through `security`. */
28
+ export const macKeychain = (run) => ({
29
+ async read() {
30
+ const r = await run("security", [
31
+ "find-generic-password",
32
+ "-a",
33
+ ACCOUNT,
34
+ "-s",
35
+ SERVICE,
36
+ "-w",
37
+ ]);
38
+ return r.status === 0 ? decode(r.stdout) : null;
39
+ },
40
+ async write(secret) {
41
+ const line = `add-generic-password -U -a ${ACCOUNT} -s ${SERVICE} -l brood -w ${encode(secret)}\n`;
42
+ if (line.length > MAC_LINE_MAX)
43
+ return false;
44
+ const r = await run("security", ["-i"], line);
45
+ return r.status === 0;
46
+ },
47
+ async remove() {
48
+ const r = await run("security", [
49
+ "delete-generic-password",
50
+ "-a",
51
+ ACCOUNT,
52
+ "-s",
53
+ SERVICE,
54
+ ]);
55
+ // 44 is security's "not found": nothing there is gone too.
56
+ return r.status === 0 || r.status === 44;
57
+ },
58
+ });
59
+ /** A Linux desktop's Secret Service, through `secret-tool`. */
60
+ export const linuxKeychain = (run) => {
61
+ const attributes = ["service", SERVICE, "account", ACCOUNT];
62
+ return {
63
+ async read() {
64
+ const r = await run("secret-tool", ["lookup", ...attributes]);
65
+ return r.status === 0 ? decode(r.stdout) : null;
66
+ },
67
+ async write(secret) {
68
+ const r = await run("secret-tool", ["store", "--label=brood", ...attributes], encode(secret));
69
+ return r.status === 0;
70
+ },
71
+ async remove() {
72
+ const r = await run("secret-tool", ["clear", ...attributes]);
73
+ return r.status === 0;
74
+ },
75
+ };
76
+ };
77
+ /**
78
+ * Runs a command with its input on standard input and nothing on its command
79
+ * line but what is given; a command that cannot start answers a null status.
80
+ * Its standard error is dropped: a keychain's complaint can echo what it was
81
+ * handed.
82
+ */
83
+ export const runCommand = (command, args, input) => new Promise((resolve) => {
84
+ const child = spawn(command, args, {
85
+ stdio: ["pipe", "pipe", "ignore"],
86
+ // Killed past it, which closes with a null status: no keychain.
87
+ timeout: KEYCHAIN_TIMEOUT_MS,
88
+ });
89
+ let stdout = "";
90
+ child.stdout.setEncoding("utf8");
91
+ child.stdout.on("data", (chunk) => (stdout += chunk));
92
+ child.on("error", () => resolve({ status: null, stdout: "" }));
93
+ child.on("close", (status) => resolve({ status, stdout }));
94
+ child.stdin.on("error", () => { });
95
+ child.stdin.end(input ?? "");
96
+ });
97
+ /** The keychain this machine has, or null for none brood can use. */
98
+ export function keychainFor(platform, run = runCommand) {
99
+ if (platform === "darwin")
100
+ return macKeychain(run);
101
+ if (platform === "linux")
102
+ return linuxKeychain(run);
103
+ return null;
104
+ }