@noisybrood/cli 0.0.0-stage → 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/LICENSE +202 -0
- package/README.md +83 -2
- package/dist/brood/api/src/client.js +58 -0
- package/dist/brood/api/src/origin.js +7 -0
- package/dist/brood/api/src/values.js +96 -0
- package/dist/brood/figures/index.js +4 -0
- package/dist/brood/tokens/dark.js +2 -0
- package/dist/brood/tokens/src/wren.js +58 -0
- package/dist/brood.js +33 -0
- package/dist/client.js +100 -0
- package/dist/commands.js +596 -0
- package/dist/io.js +50 -0
- package/dist/keychain.js +104 -0
- package/dist/main.js +213 -0
- package/dist/out.js +53 -0
- package/dist/sign-in.js +129 -0
- package/dist/store.js +138 -0
- package/dist/version.js +16 -0
- package/dist/wren.js +147 -0
- package/package.json +37 -4
package/dist/keychain.js
ADDED
|
@@ -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
|
+
}
|
package/dist/main.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import { call } from "./client.js";
|
|
3
|
+
import { COMMANDS } from "./commands.js";
|
|
4
|
+
import { Refused, Refusal, SessionEnded } from "./io.js";
|
|
5
|
+
import { colorOn, styleOf } from "./out.js";
|
|
6
|
+
import { login } from "./sign-in.js";
|
|
7
|
+
import { readCredentials, removeCredentials } from "./store.js";
|
|
8
|
+
import { VERSION } from "./version.js";
|
|
9
|
+
import { depthOf, wrenIn } from "./wren.js";
|
|
10
|
+
/**
|
|
11
|
+
* `brood`, the command line over Brood's index (DD10): it answers questions
|
|
12
|
+
* about a mailbox without opening one, and changes it only by `hush`,
|
|
13
|
+
* `unhush` and `keep add`, which changes Brood's filters to keep mail in
|
|
14
|
+
* view. `customers add` changes what Brood proposes, never the mailbox. Bare `brood` prints this help, never a report (DD10 §3), so it is
|
|
15
|
+
* never a status glanced at, under the wren.
|
|
16
|
+
*/
|
|
17
|
+
const HELP = `brood answers questions about your mailbox from Brood's index. It never reads a message.
|
|
18
|
+
|
|
19
|
+
Observing
|
|
20
|
+
brood week one finished week, beside the week before
|
|
21
|
+
brood senders who wrote, most first
|
|
22
|
+
brood senders <domain|address> one sender
|
|
23
|
+
brood events [--sender <name>] messages that arrived or were sent, newest first
|
|
24
|
+
brood quiet senders that have gone silent
|
|
25
|
+
|
|
26
|
+
Structure
|
|
27
|
+
brood classifications [<path>] what Brood has decided, and its state
|
|
28
|
+
brood classification <id> one, with the reason for its state
|
|
29
|
+
brood rules [<id>] the filters Brood installed
|
|
30
|
+
|
|
31
|
+
Suppression, which changes your mailbox
|
|
32
|
+
brood hush <domain|address|id> file a sender, proposed or not
|
|
33
|
+
brood unhush <domain|address|id> undo the filing
|
|
34
|
+
|
|
35
|
+
Keeping in view, which changes Brood's filters so it never files these senders
|
|
36
|
+
brood keep your never-quiet list
|
|
37
|
+
brood keep add [<file>] add addresses and domains, one a line, from a file or standard input
|
|
38
|
+
|
|
39
|
+
Customers, whose mail Brood gives a home of its own
|
|
40
|
+
brood customers add [<file>] add customers, one a line, as Name: domain, domain
|
|
41
|
+
|
|
42
|
+
Accounts and session
|
|
43
|
+
brood accounts your mailboxes, and whether Brood can read them
|
|
44
|
+
brood login [--read-only] sign in, by a code you approve in a browser
|
|
45
|
+
brood logout end this session
|
|
46
|
+
brood version
|
|
47
|
+
|
|
48
|
+
Options
|
|
49
|
+
--json the answer as the API gives it
|
|
50
|
+
--since, --until a stretch of whole days, as YYYY-MM-DD in UTC
|
|
51
|
+
--limit <n> how many to show
|
|
52
|
+
--cursor <next> carry on a listing from where it stopped
|
|
53
|
+
--state <state> classifications in one state
|
|
54
|
+
--week <monday> brood week for an earlier week
|
|
55
|
+
--classification <id> brood rules for one classification
|
|
56
|
+
--check keep add, customers add: say what each line would become, and add nothing
|
|
57
|
+
--yes keep add, customers add: add the list without asking
|
|
58
|
+
--owner <user id> the index of someone who granted you access
|
|
59
|
+
--no-color no dimming, as NO_COLOR also asks`;
|
|
60
|
+
async function logout(io) {
|
|
61
|
+
if (!(await readCredentials(io))) {
|
|
62
|
+
// Nothing to end at Brood, but an item the keychain would not show is
|
|
63
|
+
// still asked to go (review of #1676).
|
|
64
|
+
await removeCredentials(io);
|
|
65
|
+
return io.err("Not signed in.");
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
await call(io, "end_session", (held) => ({
|
|
69
|
+
refresh_token: held.refresh_token,
|
|
70
|
+
}));
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
// Forgotten only when nothing is left to end: a session Clerk has ended,
|
|
74
|
+
// or a program Brood refuses as revoked, whose stored session would leave
|
|
75
|
+
// login refusing too. Anything else, Brood unreachable or failing, or
|
|
76
|
+
// refusing a token just renewed, may leave the session live at Clerk,
|
|
77
|
+
// so the stored session stays and logging out again can end it.
|
|
78
|
+
const over = error instanceof SessionEnded ||
|
|
79
|
+
(error instanceof Refused && error.code === "credential_revoked");
|
|
80
|
+
if (!over)
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
await removeCredentials(io);
|
|
84
|
+
io.err("Signed out. This session can no longer be renewed.");
|
|
85
|
+
}
|
|
86
|
+
const OPTION_NAMES = [
|
|
87
|
+
"since",
|
|
88
|
+
"until",
|
|
89
|
+
"limit",
|
|
90
|
+
"cursor",
|
|
91
|
+
"state",
|
|
92
|
+
"week",
|
|
93
|
+
"sender",
|
|
94
|
+
"classification",
|
|
95
|
+
"check",
|
|
96
|
+
"yes",
|
|
97
|
+
];
|
|
98
|
+
/** Runs one command line, and answers its exit status. */
|
|
99
|
+
export async function run(io, argv) {
|
|
100
|
+
try {
|
|
101
|
+
const { values, positionals } = parseArgs({
|
|
102
|
+
args: argv,
|
|
103
|
+
allowPositionals: true,
|
|
104
|
+
options: {
|
|
105
|
+
json: { type: "boolean", default: false },
|
|
106
|
+
"no-color": { type: "boolean", default: false },
|
|
107
|
+
"read-only": { type: "boolean", default: false },
|
|
108
|
+
help: { type: "boolean", short: "h", default: false },
|
|
109
|
+
since: { type: "string" },
|
|
110
|
+
until: { type: "string" },
|
|
111
|
+
limit: { type: "string" },
|
|
112
|
+
cursor: { type: "string" },
|
|
113
|
+
state: { type: "string" },
|
|
114
|
+
week: { type: "string" },
|
|
115
|
+
sender: { type: "string" },
|
|
116
|
+
classification: { type: "string" },
|
|
117
|
+
check: { type: "boolean" },
|
|
118
|
+
yes: { type: "boolean" },
|
|
119
|
+
owner: { type: "string" },
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
const [command, ...args] = positionals;
|
|
123
|
+
const empty = Object.entries(values).find(([, v]) => v === "");
|
|
124
|
+
if (empty)
|
|
125
|
+
throw new Refusal(`--${empty[0]} needs a value.`);
|
|
126
|
+
// An option a command does not take is refused, never ignored: a flag
|
|
127
|
+
// with nothing behind it looks like a filter that was applied (DD10 §3).
|
|
128
|
+
const takes = (names, readOnly = false) => {
|
|
129
|
+
const given = OPTION_NAMES.find((n) => values[n] !== undefined && !names.includes(n));
|
|
130
|
+
if (given)
|
|
131
|
+
throw new Refusal(`--${given} does not apply to brood ${command}.`);
|
|
132
|
+
if (values["read-only"] && !readOnly)
|
|
133
|
+
throw new Refusal(`--read-only applies to brood login alone.`);
|
|
134
|
+
};
|
|
135
|
+
// The session commands read no index, so neither whose nor how to print.
|
|
136
|
+
const session = (colors = false) => {
|
|
137
|
+
if (args.length)
|
|
138
|
+
throw new Refusal(`brood ${command} takes no arguments.`);
|
|
139
|
+
const given = ["owner", "json"].find((n) => n === "json" ? values.json : values.owner !== undefined);
|
|
140
|
+
if (given)
|
|
141
|
+
throw new Refusal(`--${given} does not apply to brood ${command}.`);
|
|
142
|
+
if (values["no-color"] && !colors)
|
|
143
|
+
throw new Refusal(`--no-color does not apply to brood ${command}.`);
|
|
144
|
+
};
|
|
145
|
+
if (command === undefined || command === "help" || values.help) {
|
|
146
|
+
const color = colorOn(io, values["no-color"]);
|
|
147
|
+
for (const line of wrenIn(color ? depthOf(io.env) : "none"))
|
|
148
|
+
io.out(line);
|
|
149
|
+
io.out("");
|
|
150
|
+
io.out(HELP);
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
153
|
+
if (command === "version") {
|
|
154
|
+
takes([]);
|
|
155
|
+
session();
|
|
156
|
+
io.out(VERSION);
|
|
157
|
+
return 0;
|
|
158
|
+
}
|
|
159
|
+
if (command === "login") {
|
|
160
|
+
takes([], true);
|
|
161
|
+
session(true);
|
|
162
|
+
await login(io, values["read-only"], values["no-color"]);
|
|
163
|
+
return 0;
|
|
164
|
+
}
|
|
165
|
+
if (command === "logout") {
|
|
166
|
+
takes([]);
|
|
167
|
+
session();
|
|
168
|
+
await logout(io);
|
|
169
|
+
return 0;
|
|
170
|
+
}
|
|
171
|
+
const runs = Object.hasOwn(COMMANDS, command)
|
|
172
|
+
? COMMANDS[command]
|
|
173
|
+
: undefined;
|
|
174
|
+
if (!runs)
|
|
175
|
+
throw new Refusal(`brood has no command ${command}. Run brood help.`);
|
|
176
|
+
takes(runs.takes);
|
|
177
|
+
const limit = values.limit === undefined ? undefined : Number(values.limit);
|
|
178
|
+
if (limit !== undefined && !Number.isInteger(limit))
|
|
179
|
+
throw new Refusal("--limit is a whole number.");
|
|
180
|
+
const options = {
|
|
181
|
+
...(values.owner === undefined ? {} : { owner: values.owner }),
|
|
182
|
+
...(values.since === undefined ? {} : { since: values.since }),
|
|
183
|
+
...(values.until === undefined ? {} : { until: values.until }),
|
|
184
|
+
...(limit === undefined ? {} : { limit }),
|
|
185
|
+
...(values.cursor === undefined ? {} : { cursor: values.cursor }),
|
|
186
|
+
...(values.state === undefined ? {} : { state: values.state }),
|
|
187
|
+
...(values.week === undefined ? {} : { week: values.week }),
|
|
188
|
+
...(values.sender === undefined ? {} : { sender: values.sender }),
|
|
189
|
+
...(values.classification === undefined
|
|
190
|
+
? {}
|
|
191
|
+
: { classification: values.classification }),
|
|
192
|
+
...(values.check ? { check: true } : {}),
|
|
193
|
+
...(values.yes ? { yes: true } : {}),
|
|
194
|
+
};
|
|
195
|
+
await runs.run(io, styleOf(io, { json: values.json, noColor: values["no-color"] }), options, args);
|
|
196
|
+
return 0;
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
if (error instanceof Refusal) {
|
|
200
|
+
io.err(error.message);
|
|
201
|
+
return 1;
|
|
202
|
+
}
|
|
203
|
+
// parseArgs refuses an option it does not know, or one missing its value.
|
|
204
|
+
if (error instanceof TypeError &&
|
|
205
|
+
"code" in error &&
|
|
206
|
+
typeof error.code === "string" &&
|
|
207
|
+
error.code.startsWith("ERR_PARSE_ARGS")) {
|
|
208
|
+
io.err(`${error.message}. Run brood help.`);
|
|
209
|
+
return 1;
|
|
210
|
+
}
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
}
|
package/dist/out.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a terminal may be shown colour: it is one, nothing asked it not
|
|
3
|
+
* to, and NO_COLOR is not set, whatever its value, as no-color.org says.
|
|
4
|
+
*/
|
|
5
|
+
export const colorOn = (io, noColor) => io.tty && !noColor && io.env.NO_COLOR === undefined;
|
|
6
|
+
export const styleOf = (io, flags) => ({
|
|
7
|
+
json: flags.json,
|
|
8
|
+
color: colorOn(io, flags.noColor),
|
|
9
|
+
});
|
|
10
|
+
export const dim = (style, text) => style.color ? `\u001b[2m${text}\u001b[22m` : text;
|
|
11
|
+
/** How wide a cell shows: its characters, without the codes that dim it. */
|
|
12
|
+
const width = (cell) => [...cell.replace(/\u001b\[\d+m/g, "")].length;
|
|
13
|
+
/**
|
|
14
|
+
* Rows as columns, each as wide as its widest cell; the last is left as it
|
|
15
|
+
* is. The cells are already clean: the answer was cleaned as it arrived.
|
|
16
|
+
*/
|
|
17
|
+
export function rows(io, cells, line = io.out) {
|
|
18
|
+
const widths = [];
|
|
19
|
+
for (const row of cells)
|
|
20
|
+
row.forEach((cell, i) => {
|
|
21
|
+
widths[i] = Math.max(widths[i] ?? 0, width(cell));
|
|
22
|
+
});
|
|
23
|
+
for (const row of cells)
|
|
24
|
+
line(row
|
|
25
|
+
.map((cell, i) => i === row.length - 1
|
|
26
|
+
? cell
|
|
27
|
+
: cell + " ".repeat((widths[i] ?? 0) - width(cell)))
|
|
28
|
+
.join(" ")
|
|
29
|
+
.trimEnd());
|
|
30
|
+
}
|
|
31
|
+
/** A day, from a timestamp the API gave. */
|
|
32
|
+
export const day = (at) => (at ? at.slice(0, 10) : "");
|
|
33
|
+
/**
|
|
34
|
+
* Before an answer, what the person must know to trust it (DD21 §8): every
|
|
35
|
+
* mailbox Brood could not read whole. A disconnected one is said too, so its
|
|
36
|
+
* silence is not read as quiet, though it leaves the answer complete.
|
|
37
|
+
*/
|
|
38
|
+
export function state(io, style, envelope) {
|
|
39
|
+
// Each mailbox the answer did not read whole, as the API judges it, a
|
|
40
|
+
// current one too (#1369).
|
|
41
|
+
const unread = envelope.accounts.filter((a) => !a.whole);
|
|
42
|
+
for (const a of unread)
|
|
43
|
+
io.err(dim(style, `Mailbox ${a.id}: ${a.sync.phase === "current" ? "current, but not read whole for this answer" : a.sync.phase}${a.sync.last_synced_at ? `, last reached ${day(a.sync.last_synced_at)}` : ""}.`));
|
|
44
|
+
if (!envelope.complete)
|
|
45
|
+
io.err(dim(style, "This answer is not complete: Brood has not read every connected mailbox whole."));
|
|
46
|
+
}
|
|
47
|
+
/** Where a listing carries on, said after it. */
|
|
48
|
+
export function more(io, style, envelope) {
|
|
49
|
+
if (envelope.next)
|
|
50
|
+
io.err(dim(style, `More: run it again with --cursor ${envelope.next}`));
|
|
51
|
+
}
|
|
52
|
+
/** The answer as the API gave it, cleaned, for a program to read. */
|
|
53
|
+
export const json = (io, envelope) => io.out(JSON.stringify(envelope, null, 2));
|
package/dist/sign-in.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { SIGN_IN } from "./brood/api/src/client.js";
|
|
2
|
+
import { clean, isRecord, Refusal, SessionEnded } from "./io.js";
|
|
3
|
+
import { readCredentials, removeCredentials, writeCredentials, } from "./store.js";
|
|
4
|
+
import { colorOn } from "./out.js";
|
|
5
|
+
import { depthOf, wrenIn } from "./wren.js";
|
|
6
|
+
/**
|
|
7
|
+
* Signing in with Clerk's device authorization grant (DD10 §6, DD21 §4): a
|
|
8
|
+
* code shown here and approved in a browser, so no secret is ever typed into
|
|
9
|
+
* a terminal. The access token lasts a day; the refresh token beside it gets
|
|
10
|
+
* the next, and Clerk gives a new one each time it is used.
|
|
11
|
+
*/
|
|
12
|
+
const CLIENT_ID = SIGN_IN.clients.cli;
|
|
13
|
+
const TOKEN_URL = `${SIGN_IN.issuer}/oauth/token`;
|
|
14
|
+
const DEVICE_URL = `${SIGN_IN.issuer}/oauth/device_authorization`;
|
|
15
|
+
const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
16
|
+
/** Refreshed this long before it expires, so a call is not made on a token about to lapse. */
|
|
17
|
+
const EARLY_MS = 60_000;
|
|
18
|
+
async function post(io, url, fields) {
|
|
19
|
+
let response;
|
|
20
|
+
try {
|
|
21
|
+
response = await io.fetch(url, {
|
|
22
|
+
method: "POST",
|
|
23
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
24
|
+
body: new URLSearchParams(fields).toString(),
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw new Refusal("Could not reach the sign-in service. Check the connection and try again.");
|
|
29
|
+
}
|
|
30
|
+
let body;
|
|
31
|
+
try {
|
|
32
|
+
body = await response.json();
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
body = null;
|
|
36
|
+
}
|
|
37
|
+
return { status: response.status, body: isRecord(body) ? body : {} };
|
|
38
|
+
}
|
|
39
|
+
/** A token answer as Credentials, or null when it is not one. */
|
|
40
|
+
function credentialsOf(body, now) {
|
|
41
|
+
const { access_token, refresh_token, expires_in, scope } = body;
|
|
42
|
+
if (typeof access_token !== "string" ||
|
|
43
|
+
typeof refresh_token !== "string" ||
|
|
44
|
+
typeof expires_in !== "number" ||
|
|
45
|
+
typeof scope !== "string")
|
|
46
|
+
return null;
|
|
47
|
+
return {
|
|
48
|
+
access_token,
|
|
49
|
+
refresh_token,
|
|
50
|
+
expires_at: now + expires_in * 1000,
|
|
51
|
+
scope,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const acts = (scope) => scope.split(" ").includes("act");
|
|
55
|
+
export async function login(io, readOnly, noColor = false) {
|
|
56
|
+
if (await readCredentials(io))
|
|
57
|
+
throw new Refusal("Already signed in. Run brood logout first, which ends this session.");
|
|
58
|
+
const scope = readOnly ? "read offline_access" : "read act offline_access";
|
|
59
|
+
const started = await post(io, DEVICE_URL, { client_id: CLIENT_ID, scope });
|
|
60
|
+
const { device_code, user_code, verification_uri, expires_in, interval } = started.body;
|
|
61
|
+
if (typeof device_code !== "string" ||
|
|
62
|
+
typeof user_code !== "string" ||
|
|
63
|
+
typeof verification_uri !== "string" ||
|
|
64
|
+
typeof expires_in !== "number")
|
|
65
|
+
throw new Refusal("The sign-in service would not start a sign-in. Try again shortly.");
|
|
66
|
+
io.err(`Open ${clean(verification_uri)} and enter the code ${clean(user_code)}.`);
|
|
67
|
+
io.err("Waiting for you to approve it there.");
|
|
68
|
+
let wait = (typeof interval === "number" ? interval : 5) * 1000;
|
|
69
|
+
const deadline = io.now() + expires_in * 1000;
|
|
70
|
+
while (io.now() < deadline) {
|
|
71
|
+
await io.sleep(wait);
|
|
72
|
+
const answer = await post(io, TOKEN_URL, {
|
|
73
|
+
grant_type: DEVICE_GRANT,
|
|
74
|
+
device_code,
|
|
75
|
+
client_id: CLIENT_ID,
|
|
76
|
+
});
|
|
77
|
+
const error = answer.body.error;
|
|
78
|
+
if (error === "authorization_pending")
|
|
79
|
+
continue;
|
|
80
|
+
// RFC 8628 §3.5: a client told to slow down waits five seconds longer from then on.
|
|
81
|
+
if (error === "slow_down") {
|
|
82
|
+
wait += 5000;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (error === "access_denied")
|
|
86
|
+
throw new Refusal("The sign-in was declined.");
|
|
87
|
+
if (error === "expired_token")
|
|
88
|
+
break;
|
|
89
|
+
const credentials = credentialsOf(answer.body, io.now());
|
|
90
|
+
if (!credentials)
|
|
91
|
+
throw new Refusal("The sign-in service did not finish the sign-in. Run brood login again.");
|
|
92
|
+
await writeCredentials(io, credentials);
|
|
93
|
+
const color = colorOn(io, noColor);
|
|
94
|
+
for (const line of wrenIn(color ? depthOf(io.env) : "none"))
|
|
95
|
+
io.err(line);
|
|
96
|
+
io.err("");
|
|
97
|
+
io.err(acts(credentials.scope)
|
|
98
|
+
? "Signed in. brood can read your index, hush and unhush senders, keep senders in view, and add customers."
|
|
99
|
+
: "Signed in. brood can read your index, and change nothing.");
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
throw new Refusal("The code expired before it was approved. Run brood login again.");
|
|
103
|
+
}
|
|
104
|
+
/** The session, refreshed first if its access token is about to expire. */
|
|
105
|
+
export async function freshCredentials(io) {
|
|
106
|
+
const stored = await readCredentials(io);
|
|
107
|
+
if (!stored)
|
|
108
|
+
throw new Refusal("Not signed in. Run brood login.");
|
|
109
|
+
return stored.expires_at - EARLY_MS > io.now() ? stored : refresh(io, stored);
|
|
110
|
+
}
|
|
111
|
+
/** A new access token from the refresh token, kept with the new refresh token Clerk gives. */
|
|
112
|
+
export async function refresh(io, stored) {
|
|
113
|
+
const answer = await post(io, TOKEN_URL, {
|
|
114
|
+
grant_type: "refresh_token",
|
|
115
|
+
refresh_token: stored.refresh_token,
|
|
116
|
+
client_id: CLIENT_ID,
|
|
117
|
+
});
|
|
118
|
+
const credentials = credentialsOf(answer.body, io.now());
|
|
119
|
+
if (credentials) {
|
|
120
|
+
await writeCredentials(io, credentials);
|
|
121
|
+
return credentials;
|
|
122
|
+
}
|
|
123
|
+
if (answer.body.error === "invalid_grant") {
|
|
124
|
+
// The session is over at Clerk, so the stored session holds nothing that works.
|
|
125
|
+
await removeCredentials(io);
|
|
126
|
+
throw new SessionEnded("This session has ended. Run brood login to sign in again.");
|
|
127
|
+
}
|
|
128
|
+
throw new Refusal("The sign-in service would not renew this session. Try again shortly.");
|
|
129
|
+
}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile, } from "node:fs/promises";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { basename, dirname, join } from "node:path";
|
|
5
|
+
import { Refusal } from "./io.js";
|
|
6
|
+
export const credentialsPath = (env) => join(env.XDG_CONFIG_HOME || join(env.HOME || homedir(), ".config"), "brood", "credentials.json");
|
|
7
|
+
const isCredentials = (v) => typeof v === "object" &&
|
|
8
|
+
v !== null &&
|
|
9
|
+
"access_token" in v &&
|
|
10
|
+
typeof v.access_token === "string" &&
|
|
11
|
+
"refresh_token" in v &&
|
|
12
|
+
typeof v.refresh_token === "string" &&
|
|
13
|
+
"expires_at" in v &&
|
|
14
|
+
typeof v.expires_at === "number" &&
|
|
15
|
+
"scope" in v &&
|
|
16
|
+
typeof v.scope === "string";
|
|
17
|
+
/** The stored session, or null when there is none: the keychain's, else the file's. */
|
|
18
|
+
export async function readCredentials(store) {
|
|
19
|
+
const held = await store.keychain?.read();
|
|
20
|
+
if (held != null) {
|
|
21
|
+
let parsed;
|
|
22
|
+
try {
|
|
23
|
+
parsed = JSON.parse(held);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
parsed = null;
|
|
27
|
+
}
|
|
28
|
+
if (isCredentials(parsed))
|
|
29
|
+
return parsed;
|
|
30
|
+
// Brood's own item, unreadable, such as one a keychain cut short: it can
|
|
31
|
+
// open nothing, and refusing over it would refuse logout too. Removed, and
|
|
32
|
+
// the file, if any, is the session; one that will not go is said.
|
|
33
|
+
if (!(await store.keychain?.remove()))
|
|
34
|
+
throw new Refusal(STUCK);
|
|
35
|
+
}
|
|
36
|
+
return readFileCredentials(store.env);
|
|
37
|
+
}
|
|
38
|
+
async function readFileCredentials(env) {
|
|
39
|
+
const path = credentialsPath(env);
|
|
40
|
+
let mode;
|
|
41
|
+
try {
|
|
42
|
+
mode = (await stat(path)).mode;
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
46
|
+
return null;
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
// As ssh does with a key: a file others can read is refused, not used.
|
|
50
|
+
// Not on Windows, where Node reports every file as readable by all: there
|
|
51
|
+
// the file sits in the person's own profile, under its ACL (DD10 §6).
|
|
52
|
+
if (process.platform !== "win32" && mode & 0o077)
|
|
53
|
+
throw new Refusal(`${path} can be read by others. Delete it and run brood login again.`);
|
|
54
|
+
let parsed;
|
|
55
|
+
try {
|
|
56
|
+
parsed = JSON.parse(await readFile(path, "utf8"));
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
parsed = null;
|
|
60
|
+
}
|
|
61
|
+
if (!isCredentials(parsed))
|
|
62
|
+
throw new Refusal(`${path} is not a session brood wrote. Delete it and run brood login again.`);
|
|
63
|
+
return parsed;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Writes the session to the keychain, read back to be sure it took, and then
|
|
67
|
+
* removes any file an earlier session left; with no keychain, or one that did
|
|
68
|
+
* not keep it, to the file, whole or not at all.
|
|
69
|
+
*/
|
|
70
|
+
export async function writeCredentials(store, credentials) {
|
|
71
|
+
const secret = JSON.stringify(credentials);
|
|
72
|
+
if (store.keychain) {
|
|
73
|
+
if ((await store.keychain.write(secret)) &&
|
|
74
|
+
(await store.keychain.read()) === secret) {
|
|
75
|
+
await removeFileCredentials(store.env);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
// Whatever it kept, an older session or part of this one, would be read
|
|
79
|
+
// ahead of the file: it goes first, or the file is not written, since a
|
|
80
|
+
// session read past would be no session at all.
|
|
81
|
+
if (!(await gone(store.keychain)))
|
|
82
|
+
throw new Refusal(STUCK);
|
|
83
|
+
}
|
|
84
|
+
await writeFileCredentials(store.env, credentials);
|
|
85
|
+
}
|
|
86
|
+
async function writeFileCredentials(env, credentials) {
|
|
87
|
+
const path = credentialsPath(env);
|
|
88
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
89
|
+
// A name no earlier run left behind, created afresh ("wx"), so the mode
|
|
90
|
+
// it is given is the mode it has; a reused draft keeps its old bits.
|
|
91
|
+
const draft = `${path}.${randomUUID()}.tmp`;
|
|
92
|
+
try {
|
|
93
|
+
await writeFile(draft, JSON.stringify(credentials), {
|
|
94
|
+
mode: 0o600,
|
|
95
|
+
flag: "wx",
|
|
96
|
+
});
|
|
97
|
+
await rename(draft, path);
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
// Gone once renamed; a draft a failed write left is removed with it.
|
|
101
|
+
await rm(draft, { force: true });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** Forgets the session: in the keychain, and in any file it was ever kept in. */
|
|
105
|
+
export async function removeCredentials(store) {
|
|
106
|
+
await removeFileCredentials(store.env);
|
|
107
|
+
if (store.keychain && !(await gone(store.keychain)))
|
|
108
|
+
throw new Refusal(STUCK);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Whether the keychain holds nothing brood would read ahead of its file:
|
|
112
|
+
* its item removed, or none it will show. One it cannot reach, with no
|
|
113
|
+
* `secret-tool` or no Secret Service running, shows none, and reads fall
|
|
114
|
+
* back to the file too, so nothing there can shadow it (review of #1676).
|
|
115
|
+
*/
|
|
116
|
+
const gone = async (keychain) => (await keychain.remove()) || (await keychain.read()) === null;
|
|
117
|
+
/** What brood says when the keychain will not let go of its item. */
|
|
118
|
+
const STUCK = "Your keychain holds a brood session it will not let go of. Unlock the keychain, or delete the item named brood (com.noisybrood.cli), then run brood login.";
|
|
119
|
+
/**
|
|
120
|
+
* The file, and any draft of it a run that stopped between writing and
|
|
121
|
+
* renaming left behind, which holds a token too.
|
|
122
|
+
*/
|
|
123
|
+
async function removeFileCredentials(env) {
|
|
124
|
+
const path = credentialsPath(env);
|
|
125
|
+
const draft = `${basename(path)}.`;
|
|
126
|
+
let names = [];
|
|
127
|
+
try {
|
|
128
|
+
names = await readdir(dirname(path));
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
for (const name of names)
|
|
135
|
+
if (name.startsWith(draft) && name.endsWith(".tmp"))
|
|
136
|
+
await rm(join(dirname(path), name), { force: true });
|
|
137
|
+
await rm(path, { force: true });
|
|
138
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
/**
|
|
3
|
+
* The CLI's version, from its own manifest, so the two cannot differ. Read
|
|
4
|
+
* beside the module rather than imported: the published package compiles
|
|
5
|
+
* src/ to dist/, and a JSON import from above src/ would sit outside what
|
|
6
|
+
* is compiled; one level up is the manifest from either.
|
|
7
|
+
*/
|
|
8
|
+
export const VERSION = (() => {
|
|
9
|
+
const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
10
|
+
if (typeof manifest !== "object" ||
|
|
11
|
+
manifest === null ||
|
|
12
|
+
!("version" in manifest) ||
|
|
13
|
+
typeof manifest.version !== "string")
|
|
14
|
+
throw new Error("the CLI's package.json names no version");
|
|
15
|
+
return manifest.version;
|
|
16
|
+
})();
|