enseal 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Biscuit & Chai, LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,102 @@
1
- # Temporary Holding Version
1
+ # enseal
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Send secrets and files as **one-time, end-to-end-encrypted links** from your
4
+ terminal: the command line tool for [Enseal](https://enseal.app).
5
+
6
+ Everything is encrypted **on your computer**, with the same code the Enseal
7
+ dashboard runs in your browser. The server stores ciphertext it cannot read.
8
+ The decryption key travels in the link's `#fragment`, which this tool never
9
+ sends anywhere: not to Enseal, and not to anyone else unless you choose
10
+ `--mailto` or paste the link yourself.
11
+
12
+ ```
13
+ npm install -g enseal
14
+ ```
15
+
16
+ Requires Node 20+. Sign in once with an API token from the dashboard
17
+ (**Settings > API tokens**; creating one needs a confirmed email address,
18
+ two-step sign-in and a current code):
19
+
20
+ ```
21
+ enseal login
22
+ ```
23
+
24
+ ## Sending
25
+
26
+ ```
27
+ enseal send ./server-creds.pem --client "Acme IT" --note "for the new box"
28
+ enseal send --text --client "Priya" --label "Stripe key"
29
+ enseal send --login --client "Acme IT" --label "GoDaddy login"
30
+ cat secret.txt | enseal send - --client "Acme IT" --label "wifi password"
31
+ ```
32
+
33
+ Each prints a one-time link (and copies it to the clipboard) that works
34
+ exactly once. Useful flags:
35
+
36
+ - `--passphrase`: also lock it with a passphrase (prompted, never echoed).
37
+ Share the passphrase over a second channel; an intercepted link alone then
38
+ opens nothing.
39
+ - `--expires 7`: days until the link stops working (capped by your plan).
40
+ - `--message`: print a ready-to-paste message for any mail or chat app.
41
+ - `--mailto`: open **your** mail app with that message filled in. The link
42
+ goes from your computer to your mail app; there is no option to have the
43
+ server email it, because the server must never see the key after the `#`.
44
+ - `--json`: machine output for scripts; nothing touches the clipboard.
45
+
46
+ Secrets are never taken from arguments, which would land in shell history.
47
+ Pipe them in (`-`), or let the hidden prompt ask.
48
+
49
+ Files are checked before they are sent, the same way the dashboard checks
50
+ them: programs and scripts (`.exe`, `.ps1`, `.sh` and the like, or anything
51
+ whose contents are a program) are refused, because the person opening them
52
+ would be the one at risk. To send a script's text, pipe it in:
53
+ `enseal send - --client "Acme IT" --label "setup script" < setup.ps1`.
54
+
55
+ ## Automation
56
+
57
+ ```
58
+ PASS=$(openssl rand -base64 18)
59
+ create_m365_user "$NEW_HIRE" "$PASS"
60
+ URL=$(printf '%s' "$PASS" | enseal send - --client "$NEW_HIRE" --label "First sign-in" --json | jq -r .url)
61
+ ```
62
+
63
+ Set `ENSEAL_TOKEN` in the environment (a CI secret) and no config file is
64
+ needed. Exit codes: `0` ok, `2` refused (plan, limit, scope), `3` not signed
65
+ in, `4` bad input.
66
+
67
+ ## Managing links (Team and Business plans)
68
+
69
+ ```
70
+ enseal sends # list, with status
71
+ enseal sends status 42 # one send, with its full audit trail
72
+ enseal sends revoke 42 # kill the link, destroy the payload
73
+ enseal request new --client "Acme IT" --note "Your DNS registrar login" \
74
+ --item "Registrar login:login" --item "Current zone file:file"
75
+ enseal request list
76
+ enseal request revoke 17 # add --force to destroy an unread answer
77
+ ```
78
+
79
+ Creating request links carries the same requirements as the dashboard:
80
+ two-step sign-in on your account, every plan.
81
+
82
+ ## What a token can and cannot do
83
+
84
+ A token is made for one workspace, carries explicit scopes (`send:create`,
85
+ `send:manage`, `request:create`, `request:manage`) and acts as the member
86
+ who made it: every link it creates is named in the audit trail with the
87
+ token beside them. It can never read anyone's submissions, open a send, or
88
+ make further tokens. Free-plan tokens can create sends within the plan's
89
+ limits; the other scopes are part of the Team and Business plans.
90
+
91
+ Tokens expire after 90 days unless you choose otherwise. A token stops
92
+ working when it is revoked, when its creator leaves the workspace, and when
93
+ its creator's password is reset.
94
+
95
+ The token is only ever sent over HTTPS. The saved token lives in
96
+ `~/.config/enseal/config.json`, readable only by you (mode 0600).
97
+ `enseal logout` forgets it on this computer; revoke it in the dashboard to
98
+ end it everywhere.
99
+
100
+ ## License
101
+
102
+ MIT
package/bin/enseal.mjs ADDED
@@ -0,0 +1,366 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * enseal: send secrets and files as one-time end-to-end-encrypted links.
4
+ *
5
+ * Everything is sealed HERE, in this process, with the same code the Enseal
6
+ * dashboard runs in the browser (lib/e2e.js is generated from it). The
7
+ * server receives ciphertext and the link's decryption key rides the URL
8
+ * fragment, which this tool never sends anywhere: not to Enseal, and not to
9
+ * anyone else unless you choose --mailto or paste the link yourself.
10
+ */
11
+ import { basename, extname } from "node:path";
12
+ import { readFileSync, statSync } from "node:fs";
13
+ import { parseArgs } from "node:util";
14
+ import { sendSeal, envelopeForText, envelopeForFile, envelopeForLogin, toB64url } from "../lib/e2e.js";
15
+ import { sendMessage, requestMessage, mailtoHref, messageText } from "../lib/handoffmail.js";
16
+ import { assessFile } from "../lib/filerisk.js";
17
+ import { api, VERSION } from "../lib/api.mjs";
18
+ import { ctx, saveConfig, clearConfig, checkBaseUrl } from "../lib/config.mjs";
19
+ import { CliError } from "../lib/errors.mjs";
20
+ import { prompt, promptHidden, readStdin } from "../lib/prompt.mjs";
21
+ import { copyToClipboard, openMailto } from "../lib/clipboard.mjs";
22
+
23
+ const MAX_FILE_BYTES = 25 * 1024 * 1024; // above every plan's payload ceiling
24
+
25
+ const HELP = `enseal ${VERSION}: one-time, end-to-end-encrypted secret sharing
26
+
27
+ enseal login sign in with an API token (Settings > API tokens)
28
+ enseal logout forget the saved token on this computer
29
+ enseal whoami who the token acts as, where, with what
30
+
31
+ enseal send <file> deliver a file
32
+ enseal send --text deliver a secret (hidden prompt)
33
+ enseal send - deliver whatever stdin pipes in (as text)
34
+ enseal send --login deliver a sign-in (username + password)
35
+ --client <name> who it's for (required)
36
+ --label <text> what it is (required; file name by default)
37
+ --note <text> a note that travels inside the encryption
38
+ (files and logins)
39
+ --passphrase also lock it with a passphrase (hidden prompt)
40
+ --expires <days> link lifetime (plan-capped; default 3)
41
+ --message print a ready-to-paste message instead
42
+ --mailto open your mail app with the message prefilled
43
+ --json machine output; no clipboard
44
+ --no-copy don't touch the clipboard
45
+
46
+ enseal sends list this workspace's sends (Team+)
47
+ enseal sends status <id> one send, with its audit trail (Team+)
48
+ enseal sends revoke <id> kill a link, destroy the payload (Team+)
49
+
50
+ enseal request new --client <name> --note <text> [--item "label[:kind]"]... (Team+)
51
+ enseal request list open request links (Team+)
52
+ enseal request revoke <id> [--force] (Team+)
53
+
54
+ Scripts: set ENSEAL_TOKEN (and ENSEAL_BASE_URL for another server) and pipe
55
+ secrets in; they never belong in argv. Programs and scripts are not sent as
56
+ files (the person opening them would be the one at risk); send a script's
57
+ text with \`enseal send - < script.ps1\` instead. Exit codes: 0 ok,
58
+ 2 refused, 3 not signed in, 4 bad input.`;
59
+
60
+ const out = (s) => process.stdout.write(s + "\n");
61
+
62
+ function parse(args, options, allowPositionals = false) {
63
+ try {
64
+ return parseArgs({ args, options, allowPositionals, strict: true });
65
+ } catch (e) {
66
+ throw new CliError(e.message, 4);
67
+ }
68
+ }
69
+
70
+ const whoami = (c) => api(c, "/api/whoami");
71
+
72
+ function requireIdentity(me) {
73
+ if (!me.workspace) throw new CliError("This token is not bound to a workspace. Mint a new one in Settings.", 3);
74
+ return me;
75
+ }
76
+
77
+ // ---------------------------------------------------------------- login ----
78
+
79
+ async function cmdLogin(args) {
80
+ const { values } = parse(args, { "base-url": { type: "string" } });
81
+ const baseUrl = checkBaseUrl(values["base-url"] || process.env.ENSEAL_BASE_URL || "https://enseal.app");
82
+ const token = await promptHidden(`API token for ${baseUrl} (from Settings > API tokens): `);
83
+ if (!token.startsWith("esk_")) throw new CliError("That doesn't look like an Enseal API token (esk_…).", 4);
84
+ const me = requireIdentity(await whoami({ baseUrl, token }));
85
+ const file = saveConfig({ baseUrl, token, userName: me.name });
86
+ out(`Signed in as ${me.name} (${me.email}), workspace "${me.workspace.name}".`);
87
+ out(`Token scopes: ${me.token.scopes.join(", ")}. Saved to ${file} (0600).`);
88
+ }
89
+
90
+ async function cmdWhoami(args) {
91
+ const { values } = parse(args, { json: { type: "boolean" } });
92
+ const me = await whoami(ctx());
93
+ if (values.json) return out(JSON.stringify(me, null, 2));
94
+ if (!me.token) return out(`${me.name} (${me.email}): browser session, no token.`);
95
+ out(`${me.name} (${me.email})`);
96
+ out(`Workspace: ${me.workspace?.name ?? "?"} (${me.workspace?.plan ?? "?"} plan)`);
97
+ out(`Token "${me.token.name}" may: ${me.token.scopes.join(", ")}`);
98
+ }
99
+
100
+ // ----------------------------------------------------------------- send ----
101
+
102
+ const MIME = {
103
+ ".txt": "text/plain", ".md": "text/plain", ".csv": "text/csv", ".json": "application/json",
104
+ ".pdf": "application/pdf", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
105
+ ".zip": "application/zip", ".pem": "application/x-pem-file", ".p12": "application/x-pkcs12",
106
+ ".pfx": "application/x-pkcs12", ".crt": "application/x-x509-ca-cert", ".cer": "application/x-x509-ca-cert",
107
+ };
108
+
109
+ async function cmdSend(args) {
110
+ const { values, positionals } = parse(
111
+ args,
112
+ {
113
+ client: { type: "string" }, label: { type: "string" }, note: { type: "string" },
114
+ text: { type: "boolean" }, login: { type: "boolean" }, passphrase: { type: "boolean" },
115
+ expires: { type: "string" }, json: { type: "boolean" }, message: { type: "boolean" },
116
+ mailto: { type: "boolean" }, "no-copy": { type: "boolean" },
117
+ },
118
+ true,
119
+ );
120
+ const c = ctx();
121
+ const me = requireIdentity(await whoami(c));
122
+
123
+ const file = positionals[0];
124
+ let envelope;
125
+ let label = values.label?.trim();
126
+ if (values.login) {
127
+ const url = await prompt("Where it signs in (address or system name, optional): ");
128
+ const username = await prompt("Username: ");
129
+ const password = await promptHidden("Password (hidden): ");
130
+ if (!password) throw new CliError("A login needs a password.", 4);
131
+ envelope = envelopeForLogin({ url, username, password, notes: values.note ?? "" });
132
+ label ||= username ? `Login for ${username}` : "Login";
133
+ } else if (values.text) {
134
+ if (values.note) throw new CliError("--note goes with files and logins. For text, put the note in the secret itself.", 4);
135
+ const secret = await promptHidden("Secret (hidden): ");
136
+ if (!secret) throw new CliError("Nothing to send.", 4);
137
+ envelope = envelopeForText(secret);
138
+ } else if (file === "-") {
139
+ if (values.note) throw new CliError("--note goes with files and logins. For text, put the note in the secret itself.", 4);
140
+ const piped = (await readStdin()).toString("utf8").replace(/\n$/, "");
141
+ if (!piped) throw new CliError("Nothing arrived on stdin.", 4);
142
+ envelope = envelopeForText(piped);
143
+ } else if (file) {
144
+ const size = statSync(file, { throwIfNoEntry: false })?.size;
145
+ if (size == null) throw new CliError(`No such file: ${file}`, 4);
146
+ if (size > MAX_FILE_BYTES) {
147
+ throw new CliError(`${basename(file)} is ${(size / 1048576).toFixed(0)} MB, larger than any plan carries.`, 4);
148
+ }
149
+ const bytes = new Uint8Array(readFileSync(file));
150
+ // the same check the dashboard runs when a file is attached, on the
151
+ // file's real contents: programs are refused, and the refusal is
152
+ // recorded (its category only, never the file or its name)
153
+ const risk = assessFile(basename(file), bytes);
154
+ if (risk.level === "danger") {
155
+ await api(c, "/api/sends/file-flag", {
156
+ method: "POST",
157
+ body: JSON.stringify({ workspaceId: me.workspace.id, code: risk.code }),
158
+ }).catch(() => {});
159
+ throw new CliError(
160
+ `"${basename(file)}" can't be sent. ${risk.title}. Files that run code when opened aren't carried, because the person opening it would be the one at risk. If it is text (a script or config), send it as text instead: enseal send - --client ... --label ... < ${basename(file)}`,
161
+ 4,
162
+ );
163
+ }
164
+ if (risk.level === "caution") {
165
+ process.stderr.write(`Note: ${risk.title}. It will be sent, and the person opening it will see this warning too.\n`);
166
+ }
167
+ envelope = envelopeForFile(basename(file), MIME[extname(file).toLowerCase()] ?? "", bytes, values.note);
168
+ label ||= basename(file);
169
+ } else {
170
+ throw new CliError("What should go out? A file path, `-` for stdin, --text, or --login.", 4);
171
+ }
172
+
173
+ const clientName = values.client?.trim();
174
+ if (!clientName) throw new CliError("--client <name> is required: who is this for?", 4);
175
+ if (!label) throw new CliError("--label <text> is required: what is it?", 4);
176
+
177
+ let passphrase;
178
+ if (values.passphrase) {
179
+ passphrase = await promptHidden("Passphrase (hidden; share it over a second channel, never with the link): ");
180
+ if (!passphrase) throw new CliError("Empty passphrase. Drop --passphrase to send without one.", 4);
181
+ }
182
+ const expiryDays = values.expires ? Number(values.expires) : undefined;
183
+ if (values.expires && (!Number.isInteger(expiryDays) || expiryDays < 1)) {
184
+ throw new CliError("--expires takes whole days, e.g. --expires 7", 4);
185
+ }
186
+
187
+ const fragKey = crypto.getRandomValues(new Uint8Array(16));
188
+ const sealed = await sendSeal(envelope, fragKey, passphrase);
189
+ const res = await api(c, "/api/sends", {
190
+ method: "POST",
191
+ body: JSON.stringify({
192
+ workspaceId: me.workspace.id,
193
+ clientName,
194
+ label,
195
+ ciphertext: sealed.ciphertext,
196
+ iv: sealed.iv,
197
+ passSalt: sealed.passSalt,
198
+ claimVerifier: sealed.claimVerifier,
199
+ keyVerifier: sealed.keyVerifier ?? null,
200
+ ...(expiryDays ? { expiryDays } : {}),
201
+ }),
202
+ });
203
+ const url = `${res.origin ?? c.baseUrl}${res.path}#${toB64url(fragKey)}`;
204
+
205
+ if (values.json) {
206
+ return out(JSON.stringify({ url, expiresAt: res.expiresAt, label, client: clientName, workspace: me.workspace.name }));
207
+ }
208
+ const msg = sendMessage({
209
+ workspaceName: me.workspace.name,
210
+ senderName: me.name,
211
+ clientName,
212
+ label,
213
+ url,
214
+ expiresAt: res.expiresAt,
215
+ withPassphrase: Boolean(passphrase),
216
+ });
217
+ if (values.message) return out(messageText(msg));
218
+ const copied = !values["no-copy"] && copyToClipboard(url);
219
+ out(`One-time link for ${clientName} (expires ${new Date(res.expiresAt).toLocaleDateString()}):`);
220
+ out("");
221
+ out(` ${url}`);
222
+ out("");
223
+ if (copied) out("Copied to the clipboard.");
224
+ if (passphrase) out("Reminder: share the passphrase over a second channel, never beside the link.");
225
+ if (values.mailto) {
226
+ out(openMailto(mailtoHref(msg)) ? "Opened your mail app with the message prefilled." : "Could not open a mail app here.");
227
+ }
228
+ }
229
+
230
+ // ---------------------------------------------------------------- sends ----
231
+
232
+ async function cmdSends(args) {
233
+ const sub = ["list", "status", "revoke"].includes(args[0]) ? args.shift() : "list";
234
+ const { values, positionals } = parse(args, { json: { type: "boolean" } }, true);
235
+ const c = ctx();
236
+ const me = requireIdentity(await whoami(c));
237
+ if (sub === "list") {
238
+ const rows = await api(c, `/api/sends?workspace=${me.workspace.id}`);
239
+ if (values.json) return out(JSON.stringify(rows, null, 2));
240
+ if (rows.length === 0) return out("No sends yet.");
241
+ for (const r of rows) {
242
+ out(`#${String(r.id).padEnd(5)} ${r.status.padEnd(9)} ${r.label} for ${r.clientName} · made ${new Date(r.createdAt).toLocaleDateString()}${r.needsPass ? " · passphrase" : ""}`);
243
+ }
244
+ return;
245
+ }
246
+ const id = Number(positionals[0]);
247
+ if (!Number.isInteger(id) || id <= 0) throw new CliError(`enseal sends ${sub} <id>: pick the id from \`enseal sends\`.`, 4);
248
+ if (sub === "revoke") {
249
+ await api(c, `/api/sends/${id}`, { method: "DELETE" });
250
+ return out(`Send #${id} is revoked; its payload is destroyed.`);
251
+ }
252
+ const r = await api(c, `/api/sends/${id}`);
253
+ if (values.json) return out(JSON.stringify(r, null, 2));
254
+ out(`#${r.id} ${r.label} for ${r.clientName} · ${r.status}${r.needsPass ? " · passphrase" : ""}`);
255
+ out(`made ${new Date(r.createdAt).toLocaleString()} · expires ${new Date(r.expiresAt).toLocaleString()}`);
256
+ for (const e of r.events) out(` ${new Date(e.at).toLocaleString()} ${e.kind}${e.detail ? `: ${e.detail}` : ""}`);
257
+ }
258
+
259
+ // -------------------------------------------------------------- requests ----
260
+
261
+ const ITEM_KINDS = ["any", "login", "text", "file"];
262
+
263
+ async function cmdRequest(args) {
264
+ const sub = ["new", "list", "revoke"].includes(args[0]) ? args.shift() : "list";
265
+ const { values, positionals } = parse(
266
+ args,
267
+ {
268
+ client: { type: "string" }, note: { type: "string" }, expires: { type: "string" },
269
+ item: { type: "string", multiple: true }, json: { type: "boolean" },
270
+ message: { type: "boolean" }, mailto: { type: "boolean" }, force: { type: "boolean" },
271
+ },
272
+ true,
273
+ );
274
+ const c = ctx();
275
+ const me = requireIdentity(await whoami(c));
276
+
277
+ if (sub === "list") {
278
+ const rows = await api(c, `/api/requests?workspace=${me.workspace.id}`);
279
+ if (values.json) return out(JSON.stringify(rows, null, 2));
280
+ if (rows.length === 0) return out("No request links yet.");
281
+ for (const r of rows) {
282
+ const progress = r.progress ? ` · ${r.progress.received}/${r.progress.asked} in` : "";
283
+ out(`#${String(r.id).padEnd(5)} ${r.status.padEnd(10)} ${r.clientName}${progress} · made ${new Date(r.createdAt).toLocaleDateString()}`);
284
+ }
285
+ return;
286
+ }
287
+
288
+ if (sub === "revoke") {
289
+ const id = Number(positionals[0]);
290
+ if (!Number.isInteger(id) || id <= 0) throw new CliError("enseal request revoke <id> [--force]", 4);
291
+ try {
292
+ await api(c, `/api/requests/${id}${values.force ? "?confirm=unread" : ""}`, { method: "DELETE" });
293
+ } catch (e) {
294
+ if (e instanceof CliError && e.message.includes("has not been read")) {
295
+ throw new CliError(`${e.message} Add --force to destroy it anyway.`, 2);
296
+ }
297
+ throw e;
298
+ }
299
+ return out(`Request #${id} is destroyed.`);
300
+ }
301
+
302
+ // new
303
+ const clientName = values.client?.trim();
304
+ const note = values.note?.trim();
305
+ if (!clientName || !note) throw new CliError("--client and --note are required: who is asked, and for what.", 4);
306
+ const items = (values.item ?? []).map((raw) => {
307
+ const m = raw.match(/^(.*?)(?::(any|login|text|file))?$/);
308
+ const label = (m?.[1] ?? raw).trim();
309
+ if (!label) throw new CliError("An --item needs a label, e.g. --item \"GoDaddy login:login\"", 4);
310
+ return { label, kind: m?.[2] && ITEM_KINDS.includes(m[2]) ? m[2] : "any" };
311
+ });
312
+ const expiryDays = values.expires ? Number(values.expires) : undefined;
313
+ const res = await api(c, "/api/requests", {
314
+ method: "POST",
315
+ body: JSON.stringify({
316
+ workspaceId: me.workspace.id,
317
+ clientName,
318
+ note,
319
+ ...(items.length > 0 ? { items } : {}),
320
+ ...(expiryDays ? { expiryDays } : {}),
321
+ }),
322
+ });
323
+ const url = `${res.origin ?? c.baseUrl}${res.path}`;
324
+ if (values.json) return out(JSON.stringify({ url, held: res.held, client: clientName }));
325
+ const msg = requestMessage({
326
+ workspaceName: me.workspace.name,
327
+ senderName: me.name,
328
+ clientName,
329
+ note,
330
+ url,
331
+ expiresAt: new Date(Date.now() + (expiryDays ?? 7) * 86_400_000).toISOString(),
332
+ items: items.map((i) => i.label),
333
+ });
334
+ if (values.message) return out(messageText(msg));
335
+ out(`Request link for ${clientName}:`);
336
+ out("");
337
+ out(` ${url}`);
338
+ out("");
339
+ if (copyToClipboard(url)) out("Copied to the clipboard.");
340
+ if (res.held) out("Note: this link is held for a quick review before it goes live. You'll be emailed.");
341
+ if (values.mailto) {
342
+ out(openMailto(mailtoHref(msg)) ? "Opened your mail app with the message prefilled." : "Could not open a mail app here.");
343
+ }
344
+ }
345
+
346
+ // ----------------------------------------------------------------- main ----
347
+
348
+ async function main() {
349
+ const [cmd, ...rest] = process.argv.slice(2);
350
+ switch (cmd) {
351
+ case "login": return cmdLogin(rest);
352
+ case "logout": clearConfig(); return out("Signed out; the saved token is gone.");
353
+ case "whoami": return cmdWhoami(rest);
354
+ case "send": return cmdSend(rest);
355
+ case "sends": return cmdSends(rest);
356
+ case "request": case "requests": return cmdRequest(rest);
357
+ case "--version": case "-v": case "version": return out(VERSION);
358
+ case undefined: case "help": case "--help": case "-h": return out(HELP);
359
+ default: throw new CliError(`Unknown command "${cmd}". Try \`enseal help\`.`, 4);
360
+ }
361
+ }
362
+
363
+ main().catch((e) => {
364
+ process.stderr.write(`${e instanceof CliError ? e.message : (e?.stack ?? e)}\n`);
365
+ process.exit(e instanceof CliError ? e.exitCode : 1);
366
+ });
package/lib/api.mjs ADDED
@@ -0,0 +1,32 @@
1
+ import { CliError } from "./errors.mjs";
2
+ import { createRequire } from "node:module";
3
+
4
+ const VERSION = createRequire(import.meta.url)("../package.json").version;
5
+
6
+ /** One API call. Refusals come back as the server's own message, with the
7
+ * exit code taken from what kind of refusal it was. */
8
+ export async function api(c, path, init = {}) {
9
+ let res;
10
+ try {
11
+ res = await fetch(c.baseUrl + path, {
12
+ ...init,
13
+ headers: {
14
+ authorization: `Bearer ${c.token}`,
15
+ "user-agent": `enseal-cli/${VERSION}`,
16
+ ...(init.body ? { "content-type": "application/json" } : {}),
17
+ ...(init.headers ?? {}),
18
+ },
19
+ });
20
+ } catch (e) {
21
+ throw new CliError(`Could not reach ${c.baseUrl} (${e.cause?.code ?? e.message}).`, 1);
22
+ }
23
+ const body = await res.json().catch(() => ({}));
24
+ if (!res.ok) {
25
+ const code =
26
+ res.status === 401 ? 3 : res.status === 400 || res.status === 404 ? 4 : [403, 409, 413, 429].includes(res.status) ? 2 : 1;
27
+ throw new CliError(body.message ?? `The server answered ${res.status}.`, code);
28
+ }
29
+ return body;
30
+ }
31
+
32
+ export { VERSION };
@@ -0,0 +1,25 @@
1
+ import { spawnSync } from "node:child_process";
2
+
3
+ const run = (cmd, args = [], input) => {
4
+ try {
5
+ return spawnSync(cmd, args, { input, stdio: ["pipe", "ignore", "ignore"] }).status === 0;
6
+ } catch {
7
+ return false;
8
+ }
9
+ };
10
+
11
+ /** Best effort, never fatal: the link is printed either way. */
12
+ export function copyToClipboard(text) {
13
+ if (process.platform === "darwin") return run("pbcopy", [], text);
14
+ if (process.platform === "win32") return run("clip", [], text);
15
+ return run("wl-copy", [], text) || run("xclip", ["-selection", "clipboard"], text);
16
+ }
17
+
18
+ /** Open the user's own mail app with the message prefilled — the CLI
19
+ * equivalent of the dashboard's Email button. The link (and its #key)
20
+ * goes through the OS to their mail client, never through any server. */
21
+ export function openMailto(href) {
22
+ if (process.platform === "darwin") return run("open", [href]);
23
+ if (process.platform === "win32") return run("cmd", ["/c", "start", "", href]);
24
+ return run("xdg-open", [href]);
25
+ }
package/lib/config.mjs ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Where the CLI keeps its sign-in: ~/.config/enseal/config.json (0600), or
3
+ * the XDG config home when set. Environment variables win over the file, so
4
+ * CI and scripts never need a config at all:
5
+ *
6
+ * ENSEAL_TOKEN the API token (skips `enseal login` entirely)
7
+ * ENSEAL_BASE_URL the server (default https://enseal.app)
8
+ *
9
+ * The token is only ever sent over HTTPS: a plain-http server address is
10
+ * refused, except on this computer itself (localhost), for development.
11
+ */
12
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
13
+ import { homedir } from "node:os";
14
+ import { join } from "node:path";
15
+ import { CliError } from "./errors.mjs";
16
+
17
+ const configDir = () => join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "enseal");
18
+ const configFile = () => join(configDir(), "config.json");
19
+
20
+ export function loadConfig() {
21
+ try {
22
+ return JSON.parse(readFileSync(configFile(), "utf8"));
23
+ } catch {
24
+ return {};
25
+ }
26
+ }
27
+
28
+ export function saveConfig(cfg) {
29
+ mkdirSync(configDir(), { recursive: true, mode: 0o700 });
30
+ writeFileSync(configFile(), JSON.stringify(cfg, null, 2) + "\n", { mode: 0o600 });
31
+ chmodSync(configFile(), 0o600); // writeFile's mode is ignored when the file already exists
32
+ return configFile();
33
+ }
34
+
35
+ export function clearConfig() {
36
+ try {
37
+ writeFileSync(configFile(), "{}\n", { mode: 0o600 });
38
+ } catch {
39
+ /* nothing saved, nothing to clear */
40
+ }
41
+ }
42
+
43
+ const trimSlash = (u) => u.replace(/\/+$/, "");
44
+
45
+ /** The server address, checked: https, or http only to this computer. A
46
+ * token sent over plain http could be read by anyone on the way. */
47
+ export function checkBaseUrl(raw) {
48
+ let u;
49
+ try {
50
+ u = new URL(raw);
51
+ } catch {
52
+ throw new CliError(`"${raw}" is not a web address.`, 4);
53
+ }
54
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
55
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && local)) {
56
+ throw new CliError(`Refusing to send the token to ${u.origin}: the server address must start with https://.`, 4);
57
+ }
58
+ return trimSlash(u.origin + u.pathname);
59
+ }
60
+
61
+ /** Token + server for this invocation. Never prints the token anywhere. */
62
+ export function ctx() {
63
+ const cfg = loadConfig();
64
+ const token = process.env.ENSEAL_TOKEN || cfg.token;
65
+ if (!token) {
66
+ throw new CliError("Not signed in. Run `enseal login`, or set ENSEAL_TOKEN.", 3);
67
+ }
68
+ return {
69
+ token,
70
+ baseUrl: checkBaseUrl(process.env.ENSEAL_BASE_URL || cfg.baseUrl || "https://enseal.app"),
71
+ cfg,
72
+ };
73
+ }
74
+
75
+ export { trimSlash };