easytopaste 0.0.0-stage → 0.1.1
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.md +37 -0
- package/README.md +166 -2
- package/bin/easytopaste.js +31 -0
- package/package.json +45 -6
- package/src/api.js +189 -0
- package/src/cli.js +608 -0
- package/src/crypto.js +192 -0
- package/src/index.js +19 -0
- package/src/link.js +115 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,608 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Argument parsing and the two commands. `run()` takes its whole world as an
|
|
3
|
+
* argument - streams, fetch - so the tests drive the real code path instead of
|
|
4
|
+
* a re-implementation of it, and so nothing here reaches for a global at the
|
|
5
|
+
* moment it matters.
|
|
6
|
+
*
|
|
7
|
+
* Output discipline: the share link, and a decrypted secret, are the only
|
|
8
|
+
* things written to stdout. Every status line, warning and error goes to
|
|
9
|
+
* stderr, so `easytopaste | clip` and `easytopaste read "$LINK" > out.txt`
|
|
10
|
+
* both do the obvious thing.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { readFile } from 'node:fs/promises';
|
|
14
|
+
import { createRequire } from 'node:module';
|
|
15
|
+
|
|
16
|
+
import { ApiClient, ApiError, NetworkError } from './api.js';
|
|
17
|
+
import {
|
|
18
|
+
DecryptionError,
|
|
19
|
+
EnvelopeError,
|
|
20
|
+
MAX_INLINE_BYTES,
|
|
21
|
+
decryptEnvelopeToText,
|
|
22
|
+
encryptTextToEnvelope,
|
|
23
|
+
fromBase64Url,
|
|
24
|
+
generateKey,
|
|
25
|
+
toBase64Url,
|
|
26
|
+
zeroize,
|
|
27
|
+
} from './crypto.js';
|
|
28
|
+
import { DEFAULT_API_BASE, DEFAULT_APP_BASE, LinkError, buildLink, parseLink } from './link.js';
|
|
29
|
+
|
|
30
|
+
const require = createRequire(import.meta.url);
|
|
31
|
+
export const VERSION = require('../package.json').version;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Remove C0/C1 control characters, keeping the newline and tab that make
|
|
35
|
+
* messages readable. Applied to every byte this CLI writes to stderr.
|
|
36
|
+
*/
|
|
37
|
+
export function stripControlCharacters(text) {
|
|
38
|
+
// eslint-disable-next-line no-control-regex
|
|
39
|
+
return String(text).replace(/[\x00-\x08\x0B-\x1F\x7F-\x9F\u200B-\u200F\u202A-\u202E\u2066-\u2069]/gu, '');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Exit codes, documented in the README and asserted in test/cli.test.js. */
|
|
43
|
+
export const EXIT = {
|
|
44
|
+
OK: 0,
|
|
45
|
+
ERROR: 1,
|
|
46
|
+
USAGE: 2,
|
|
47
|
+
GONE: 3,
|
|
48
|
+
LIMITED: 4,
|
|
49
|
+
NETWORK: 5,
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const MAX_DAYS = 30;
|
|
53
|
+
|
|
54
|
+
const HELP = `easytopaste - pipe a secret in, get a one-time link out.
|
|
55
|
+
|
|
56
|
+
The secret is encrypted on this machine with AES-256-GCM. The key is put in
|
|
57
|
+
the link's #fragment, which no HTTP client transmits, so the server stores
|
|
58
|
+
ciphertext it cannot read.
|
|
59
|
+
|
|
60
|
+
USAGE
|
|
61
|
+
easytopaste [create] [options] read the secret from stdin
|
|
62
|
+
easytopaste read <link> [options] fetch, decrypt and print a secret
|
|
63
|
+
|
|
64
|
+
CREATE OPTIONS
|
|
65
|
+
-t, --text <string> secret to send (default: read stdin)
|
|
66
|
+
-f, --file <path> read the secret from a UTF-8 text file
|
|
67
|
+
-d, --days <1-30> days until it expires on its own (default: 1)
|
|
68
|
+
--multi allow repeat reads until expiry (default: one-time)
|
|
69
|
+
--json print {"link","locator","expiresAt","oneTime"} instead of the link
|
|
70
|
+
|
|
71
|
+
READ OPTIONS
|
|
72
|
+
--keep do not burn a one-time secret after reading it
|
|
73
|
+
--raw write the secret verbatim, with no trailing newline
|
|
74
|
+
--json print {"secret","oneTime","burnPending"} instead of the secret
|
|
75
|
+
|
|
76
|
+
COMMON
|
|
77
|
+
--api <url> API base URL (default: ${DEFAULT_API_BASE})
|
|
78
|
+
--app <url> app base URL used to build links (default: ${DEFAULT_APP_BASE})
|
|
79
|
+
-q, --quiet suppress the status lines on stderr
|
|
80
|
+
-h, --help this text
|
|
81
|
+
-V, --version print the version
|
|
82
|
+
|
|
83
|
+
EXAMPLES
|
|
84
|
+
printf '%s' "$DB_PASSWORD" | easytopaste
|
|
85
|
+
easytopaste --text 'deploy key' --days 7
|
|
86
|
+
easytopaste read 'https://app.easytopaste.com/s/ABC...#k=...&v=1'
|
|
87
|
+
easytopaste read "$LINK" --raw > secret.txt # byte-for-byte, no newline
|
|
88
|
+
|
|
89
|
+
read adds a trailing newline so the secret does not run into your prompt;
|
|
90
|
+
pass --raw when the bytes must match exactly.
|
|
91
|
+
|
|
92
|
+
EXIT CODES
|
|
93
|
+
0 ok 1 error 2 usage 3 gone/not found 4 rate limited 5 network
|
|
94
|
+
|
|
95
|
+
Text secrets only: binary files, and anything over 256 KB, go through
|
|
96
|
+
${DEFAULT_APP_BASE}, which encrypts and streams them in chunks.
|
|
97
|
+
No telemetry. No dependencies. The key never leaves this machine.`;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* @param {string[]} argv Arguments after `node script`.
|
|
101
|
+
* @param {{stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream, stdin: NodeJS.ReadableStream, fetchImpl?: typeof fetch}} io
|
|
102
|
+
* @returns {Promise<number>} process exit code
|
|
103
|
+
*/
|
|
104
|
+
export async function run(argv, io) {
|
|
105
|
+
const out = (s) => io.stdout.write(s);
|
|
106
|
+
// Every stderr line can contain server-controlled text - an API error
|
|
107
|
+
// message, a hint, a locator echoed back. A hostile or compromised API could
|
|
108
|
+
// otherwise repaint the terminal with ANSI escapes and forge the one thing
|
|
109
|
+
// this tool exists to print: a link the human is about to trust.
|
|
110
|
+
const err = (s) => io.stderr.write(stripControlCharacters(s));
|
|
111
|
+
|
|
112
|
+
let opts;
|
|
113
|
+
try {
|
|
114
|
+
opts = parseArgs(argv);
|
|
115
|
+
} catch (e) {
|
|
116
|
+
err(`easytopaste: ${e.message}\nTry 'easytopaste --help'.\n`);
|
|
117
|
+
return EXIT.USAGE;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (opts.help) {
|
|
121
|
+
out(`${HELP}\n`);
|
|
122
|
+
return EXIT.OK;
|
|
123
|
+
}
|
|
124
|
+
if (opts.version) {
|
|
125
|
+
out(`${VERSION}\n`);
|
|
126
|
+
return EXIT.OK;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const note = (s) => {
|
|
130
|
+
if (!opts.quiet) err(s);
|
|
131
|
+
};
|
|
132
|
+
const api = new ApiClient({ baseUrl: opts.api, version: VERSION, fetchImpl: io.fetchImpl });
|
|
133
|
+
|
|
134
|
+
try {
|
|
135
|
+
if (opts.command === 'read') return await cmdRead(opts, api, io, { err, note });
|
|
136
|
+
return await cmdCreate(opts, api, io, { err, note });
|
|
137
|
+
} catch (e) {
|
|
138
|
+
err(`easytopaste: ${e.message}\n`);
|
|
139
|
+
return exitCodeFor(e);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
// create
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
async function cmdCreate(opts, api, io, { err, note }) {
|
|
148
|
+
const plaintext = await readPlaintext(opts, io);
|
|
149
|
+
if (plaintext === '') {
|
|
150
|
+
throw new UsageError('nothing to encrypt - the input was empty.');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const key = generateKey();
|
|
154
|
+
try {
|
|
155
|
+
const envelope = await encryptTextToEnvelope(plaintext, key);
|
|
156
|
+
if (envelope.length > MAX_INLINE_BYTES) {
|
|
157
|
+
throw new UsageError(
|
|
158
|
+
`${envelope.length} bytes is over the ${MAX_INLINE_BYTES}-byte inline limit. ` +
|
|
159
|
+
`Send it through ${opts.app} instead.`,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
note(`Encrypted ${envelope.length} bytes locally. Uploading ciphertext...\n`);
|
|
164
|
+
const created = await api.createSecret({
|
|
165
|
+
ciphertextB64: toBase64Url(envelope),
|
|
166
|
+
sizeBytes: envelope.length,
|
|
167
|
+
oneTime: opts.oneTime,
|
|
168
|
+
expiresInDays: opts.days,
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const link = buildLink({ locator: created.locator, key, appBase: opts.app });
|
|
172
|
+
const payload = opts.json
|
|
173
|
+
? `${JSON.stringify({
|
|
174
|
+
link,
|
|
175
|
+
locator: created.locator,
|
|
176
|
+
expiresAt: created.expiresAt ?? null,
|
|
177
|
+
oneTime: opts.oneTime,
|
|
178
|
+
})}\n`
|
|
179
|
+
: `${link}\n`;
|
|
180
|
+
|
|
181
|
+
// The secret is already stored; if the link never reaches the caller the
|
|
182
|
+
// secret is unreachable forever, so a failed write is a failed run.
|
|
183
|
+
const writeError = await writeOut(io.stdout, payload);
|
|
184
|
+
if (writeError) {
|
|
185
|
+
err(
|
|
186
|
+
'easytopaste: the secret was stored but the link could not be written to stdout ' +
|
|
187
|
+
`(${writeError.code ?? writeError.message}). It is at ${opts.app}/s/${created.locator}, ` +
|
|
188
|
+
'and without the key fragment nobody can open it.\n',
|
|
189
|
+
);
|
|
190
|
+
return EXIT.ERROR;
|
|
191
|
+
}
|
|
192
|
+
note(
|
|
193
|
+
opts.oneTime
|
|
194
|
+
? `One-time link. The first read destroys it; it expires in ${opts.days} day(s) regardless.\n`
|
|
195
|
+
: `Re-readable link. It expires in ${opts.days} day(s).\n`,
|
|
196
|
+
);
|
|
197
|
+
return EXIT.OK;
|
|
198
|
+
} finally {
|
|
199
|
+
zeroize(key);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function readPlaintext(opts, io) {
|
|
204
|
+
if (opts.text !== null) return opts.text;
|
|
205
|
+
|
|
206
|
+
if (opts.file !== null) {
|
|
207
|
+
let bytes;
|
|
208
|
+
try {
|
|
209
|
+
bytes = await readFile(opts.file);
|
|
210
|
+
} catch (e) {
|
|
211
|
+
throw new UsageError(`cannot read ${opts.file} - ${e.code ?? e.message}`);
|
|
212
|
+
}
|
|
213
|
+
return decodeTextOrRefuse(bytes, opts.file, opts.app);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (io.stdin.isTTY) {
|
|
217
|
+
throw new UsageError(
|
|
218
|
+
'nothing to encrypt. Pipe the secret in, or pass --text / --file. See --help.',
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
return decodeTextOrRefuse(await readAll(io.stdin), 'the piped input', opts.app);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Decode bytes as UTF-8 or refuse them.
|
|
226
|
+
*
|
|
227
|
+
* Decoding leniently is how a CLI silently uploads a mangled secret: Node's
|
|
228
|
+
* default decoder replaces every undecodable byte with U+FFFD, so a PNG piped
|
|
229
|
+
* in becomes a 60-byte envelope of replacement characters that the recipient
|
|
230
|
+
* believes is the secret. A strict decoder fails instead, which is the only
|
|
231
|
+
* honest option for a tool whose whole job is to transport bytes exactly.
|
|
232
|
+
*
|
|
233
|
+
* @param {Buffer} bytes
|
|
234
|
+
* @param {string} what Label for the error message.
|
|
235
|
+
* @param {string} appBase Where to send the user instead.
|
|
236
|
+
*/
|
|
237
|
+
function decodeTextOrRefuse(bytes, what, appBase) {
|
|
238
|
+
let text;
|
|
239
|
+
try {
|
|
240
|
+
text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
241
|
+
} catch {
|
|
242
|
+
throw new UsageError(
|
|
243
|
+
`${what} is not UTF-8 text. Binary goes through ${appBase}, which encrypts it in chunks.`,
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
if (text.includes('\u0000')) {
|
|
247
|
+
throw new UsageError(
|
|
248
|
+
`${what} contains NUL bytes, so it is not text. Binary goes through ${appBase}, which encrypts it in chunks.`,
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
return text;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** @returns {Promise<Buffer>} every byte of the stream, undecoded. */
|
|
255
|
+
function readAll(stream) {
|
|
256
|
+
return new Promise((resolve, reject) => {
|
|
257
|
+
const chunks = [];
|
|
258
|
+
stream.on('data', (c) => chunks.push(Buffer.from(c)));
|
|
259
|
+
stream.on('end', () => resolve(Buffer.concat(chunks)));
|
|
260
|
+
stream.on('error', reject);
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Write to stdout and wait for the stream to accept it, reporting failure
|
|
266
|
+
* rather than throwing.
|
|
267
|
+
*
|
|
268
|
+
* `stream.write()` returning true is not delivery: a closed pipe surfaces as
|
|
269
|
+
* an error passed to the callback. On the read path that distinction decides
|
|
270
|
+
* whether a one-time secret may be destroyed, so it cannot be ignored.
|
|
271
|
+
*
|
|
272
|
+
* @returns {Promise<Error|null>} the write error, or null on success.
|
|
273
|
+
*/
|
|
274
|
+
function writeOut(stream, text) {
|
|
275
|
+
return new Promise((resolve) => {
|
|
276
|
+
let settled = false;
|
|
277
|
+
const done = (e) => {
|
|
278
|
+
if (!settled) {
|
|
279
|
+
settled = true;
|
|
280
|
+
resolve(e ?? null);
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
stream.once('error', done);
|
|
284
|
+
try {
|
|
285
|
+
stream.write(text, (e) => done(e));
|
|
286
|
+
} catch (e) {
|
|
287
|
+
done(e);
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// ---------------------------------------------------------------------------
|
|
293
|
+
// read
|
|
294
|
+
// ---------------------------------------------------------------------------
|
|
295
|
+
|
|
296
|
+
/** API error codes that mean "this secret is gated on a signed-in recipient". */
|
|
297
|
+
const RECIPIENT_GATE_CODES = new Set(['recipient_denied', 'unauthorized', 'forbidden']);
|
|
298
|
+
|
|
299
|
+
async function cmdRead(opts, api, io, { err, note }) {
|
|
300
|
+
const { locator, key } = parseLink(opts.link);
|
|
301
|
+
try {
|
|
302
|
+
note(`Fetching ${locator}...\n`);
|
|
303
|
+
let meta;
|
|
304
|
+
try {
|
|
305
|
+
meta = await api.retrieveSecret(locator);
|
|
306
|
+
} catch (e) {
|
|
307
|
+
// The live API refuses a login-gated secret at 403 before it returns any
|
|
308
|
+
// metadata, so the requiresRecipientLogin branch below is never reached
|
|
309
|
+
// in production. Both routes must say the same thing and exit the same
|
|
310
|
+
// way, or the exit-code table in the README is false.
|
|
311
|
+
if (e instanceof ApiError && RECIPIENT_GATE_CODES.has(e.code)) {
|
|
312
|
+
throw new UnsupportedError(
|
|
313
|
+
`this secret requires a signed-in recipient; open it at ${opts.app}/s/${locator}`,
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
throw e;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (meta.mode === 'passphrase') {
|
|
320
|
+
throw new UnsupportedError(
|
|
321
|
+
`this secret is passphrase-protected; open it at ${opts.app}/s/${locator}`,
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
if (meta.requiresRecipientLogin) {
|
|
325
|
+
throw new UnsupportedError(
|
|
326
|
+
`this secret requires a signed-in recipient; open it at ${opts.app}/s/${locator}`,
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// The link's fragment says v=1 and link.js enforces that, but the link is
|
|
331
|
+
// written by whoever sent it and the envelope is written by the service.
|
|
332
|
+
// A v2 envelope decrypted with v1 rules is the kind of mistake that only
|
|
333
|
+
// shows up as corrupted output.
|
|
334
|
+
if (meta.envelopeVersion !== undefined && Number(meta.envelopeVersion) !== 1) {
|
|
335
|
+
throw new UnsupportedError(
|
|
336
|
+
`this secret uses envelope version ${meta.envelopeVersion}, which this CLI does not ` +
|
|
337
|
+
`understand; open it at ${opts.app}/s/${locator} or upgrade the CLI`,
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// `type`, not the absence of a ciphertext field. A file under the 256 KB
|
|
342
|
+
// inline ceiling - an SSH key, a .env, a kubeconfig, which is most of what
|
|
343
|
+
// anyone actually sends - comes back as type "file" WITH an inline
|
|
344
|
+
// ciphertext, and its chunks are authenticated with
|
|
345
|
+
// additionalData = uint64_be(chunkIndex) (crypto.utils.ts encryptFile).
|
|
346
|
+
// Decrypting that as text fails the GCM tag, so testing for a missing
|
|
347
|
+
// ciphertext told the reader their secret "was altered" when the truth is
|
|
348
|
+
// that this CLI cannot open it.
|
|
349
|
+
if (meta.type !== undefined && meta.type !== 'text') {
|
|
350
|
+
throw new UnsupportedError(
|
|
351
|
+
`this is a ${meta.type} secret, which the CLI does not open; open it at ${opts.app}/s/${locator}`,
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
if (typeof meta.ciphertext !== 'string' || meta.ciphertext === '') {
|
|
355
|
+
if (meta.downloadUrl || meta.chunks || meta.chunkCount) {
|
|
356
|
+
throw new UnsupportedError(
|
|
357
|
+
`this is a file secret, which the CLI does not download; open it at ${opts.app}/s/${locator}`,
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
// Not a file and not text either: the API answered with something this
|
|
361
|
+
// CLI does not understand. Say that, rather than guessing a cause.
|
|
362
|
+
throw new UnsupportedError(
|
|
363
|
+
`the API returned no ciphertext for ${locator} and no file to download; open it at ${opts.app}/s/${locator}`,
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const envelope = fromBase64Url(meta.ciphertext, 'ciphertext');
|
|
368
|
+
const plaintext = await decryptEnvelopeToText(envelope, key);
|
|
369
|
+
|
|
370
|
+
// Order matters twice over, and both orderings are the point of this
|
|
371
|
+
// command. The burn comes after a successful DECRYPT, because destroying
|
|
372
|
+
// it first would lose a secret the reader never got - that is the web
|
|
373
|
+
// client's ordering. It also comes after a successful WRITE, because
|
|
374
|
+
// stdout can fail: `easytopaste read "$LINK" | grep -q x` closes the pipe,
|
|
375
|
+
// and burning then would destroy the only copy of a secret that reached
|
|
376
|
+
// nobody, with a success exit code.
|
|
377
|
+
const burnWanted = Boolean(meta.oneTime) && !opts.keep;
|
|
378
|
+
const payload = opts.json
|
|
379
|
+
? // `burnPending`, not `burned`: the secret is written before the burn is
|
|
380
|
+
// attempted, so a `burned` field here could only ever be a guess. The
|
|
381
|
+
// outcome goes to stderr, and a failure says so even under --quiet.
|
|
382
|
+
`${JSON.stringify({ secret: plaintext, oneTime: Boolean(meta.oneTime), burnPending: burnWanted })}\n`
|
|
383
|
+
: opts.raw || plaintext.endsWith('\n')
|
|
384
|
+
? plaintext
|
|
385
|
+
: `${plaintext}\n`;
|
|
386
|
+
|
|
387
|
+
const writeError = await writeOut(io.stdout, payload);
|
|
388
|
+
if (writeError) {
|
|
389
|
+
err(
|
|
390
|
+
`easytopaste: the secret could not be written to stdout (${writeError.code ?? writeError.message}). ` +
|
|
391
|
+
'It was NOT burned, so the link is still live and can be read again.\n',
|
|
392
|
+
);
|
|
393
|
+
return EXIT.ERROR;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
let burned = false;
|
|
397
|
+
if (burnWanted) {
|
|
398
|
+
try {
|
|
399
|
+
await api.burnSecret(locator);
|
|
400
|
+
burned = true;
|
|
401
|
+
} catch (e) {
|
|
402
|
+
// Deliberately err() and not note(): --quiet silences status, and a
|
|
403
|
+
// one-time link that is still live after being read is not status.
|
|
404
|
+
err(
|
|
405
|
+
`easytopaste: the secret was read but NOT burned (${e.message}). The link is still live.\n`,
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (burned) note('Burned. That link is now dead.\n');
|
|
411
|
+
else if (meta.oneTime && opts.keep) note('Kept: the link is still live for the next reader.\n');
|
|
412
|
+
return EXIT.OK;
|
|
413
|
+
} finally {
|
|
414
|
+
zeroize(key);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// ---------------------------------------------------------------------------
|
|
419
|
+
// argument parsing
|
|
420
|
+
// ---------------------------------------------------------------------------
|
|
421
|
+
|
|
422
|
+
export class UsageError extends Error {
|
|
423
|
+
constructor(message) {
|
|
424
|
+
super(message);
|
|
425
|
+
this.name = 'UsageError';
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
export class UnsupportedError extends Error {
|
|
430
|
+
constructor(message) {
|
|
431
|
+
super(message);
|
|
432
|
+
this.name = 'UnsupportedError';
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
export function parseArgs(argv) {
|
|
437
|
+
const opts = {
|
|
438
|
+
command: 'create',
|
|
439
|
+
link: null,
|
|
440
|
+
text: null,
|
|
441
|
+
file: null,
|
|
442
|
+
days: 1,
|
|
443
|
+
oneTime: true,
|
|
444
|
+
keep: false,
|
|
445
|
+
raw: false,
|
|
446
|
+
json: false,
|
|
447
|
+
quiet: false,
|
|
448
|
+
help: false,
|
|
449
|
+
version: false,
|
|
450
|
+
api: DEFAULT_API_BASE,
|
|
451
|
+
app: DEFAULT_APP_BASE,
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
const args = [...argv];
|
|
455
|
+
if (args[0] === 'create' || args[0] === 'read') {
|
|
456
|
+
opts.command = args.shift();
|
|
457
|
+
} else if (args[0] === 'help') {
|
|
458
|
+
args.shift();
|
|
459
|
+
opts.help = true;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
const positionals = [];
|
|
463
|
+
let daysGiven = false;
|
|
464
|
+
while (args.length > 0) {
|
|
465
|
+
const arg = args.shift();
|
|
466
|
+
switch (arg) {
|
|
467
|
+
case '-h':
|
|
468
|
+
case '--help':
|
|
469
|
+
opts.help = true;
|
|
470
|
+
break;
|
|
471
|
+
case '-V':
|
|
472
|
+
case '--version':
|
|
473
|
+
opts.version = true;
|
|
474
|
+
break;
|
|
475
|
+
case '-q':
|
|
476
|
+
case '--quiet':
|
|
477
|
+
opts.quiet = true;
|
|
478
|
+
break;
|
|
479
|
+
case '--json':
|
|
480
|
+
opts.json = true;
|
|
481
|
+
break;
|
|
482
|
+
case '--multi':
|
|
483
|
+
opts.oneTime = false;
|
|
484
|
+
break;
|
|
485
|
+
case '--keep':
|
|
486
|
+
opts.keep = true;
|
|
487
|
+
break;
|
|
488
|
+
case '--raw':
|
|
489
|
+
opts.raw = true;
|
|
490
|
+
break;
|
|
491
|
+
case '-t':
|
|
492
|
+
case '--text':
|
|
493
|
+
opts.text = takeValue(args, arg);
|
|
494
|
+
break;
|
|
495
|
+
case '-f':
|
|
496
|
+
case '--file':
|
|
497
|
+
opts.file = takeValue(args, arg);
|
|
498
|
+
break;
|
|
499
|
+
case '-d':
|
|
500
|
+
case '--days':
|
|
501
|
+
opts.days = parseDays(takeValue(args, arg));
|
|
502
|
+
daysGiven = true;
|
|
503
|
+
break;
|
|
504
|
+
case '--api':
|
|
505
|
+
opts.api = takeUrl(args, arg);
|
|
506
|
+
break;
|
|
507
|
+
case '--app':
|
|
508
|
+
opts.app = takeUrl(args, arg);
|
|
509
|
+
break;
|
|
510
|
+
default:
|
|
511
|
+
if (arg.startsWith('-') && arg !== '-') {
|
|
512
|
+
throw new UsageError(`unknown option "${arg}"`);
|
|
513
|
+
}
|
|
514
|
+
positionals.push(arg);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
if (opts.help || opts.version) return opts;
|
|
519
|
+
|
|
520
|
+
if (opts.command === 'read') {
|
|
521
|
+
if (positionals.length !== 1) {
|
|
522
|
+
throw new UsageError('read takes exactly one link: easytopaste read <link>');
|
|
523
|
+
}
|
|
524
|
+
opts.link = positionals[0];
|
|
525
|
+
// Accepting a flag that does nothing teaches the wrong habit, and
|
|
526
|
+
// `read --days 30` reads like it extends something.
|
|
527
|
+
for (const [flag, used] of [
|
|
528
|
+
['--text', opts.text !== null],
|
|
529
|
+
['--file', opts.file !== null],
|
|
530
|
+
['--days', daysGiven],
|
|
531
|
+
['--multi', opts.oneTime === false],
|
|
532
|
+
]) {
|
|
533
|
+
if (used) throw new UsageError(`${flag} is a create option; read does not take it`);
|
|
534
|
+
}
|
|
535
|
+
} else {
|
|
536
|
+
if (positionals.length > 0) {
|
|
537
|
+
throw new UsageError(
|
|
538
|
+
`unexpected argument "${positionals[0]}" - pipe the secret in, or use --text`,
|
|
539
|
+
);
|
|
540
|
+
}
|
|
541
|
+
if (opts.text !== null && opts.file !== null) {
|
|
542
|
+
throw new UsageError('use either --text or --file, not both');
|
|
543
|
+
}
|
|
544
|
+
for (const [flag, used] of [
|
|
545
|
+
['--keep', opts.keep],
|
|
546
|
+
['--raw', opts.raw],
|
|
547
|
+
]) {
|
|
548
|
+
if (used) throw new UsageError(`${flag} is a read option; create does not take it`);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
return opts;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function takeValue(args, flag) {
|
|
555
|
+
const value = args.shift();
|
|
556
|
+
if (value === undefined) throw new UsageError(`${flag} needs a value`);
|
|
557
|
+
return value;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function takeUrl(args, flag) {
|
|
561
|
+
const value = takeValue(args, flag);
|
|
562
|
+
let parsed;
|
|
563
|
+
try {
|
|
564
|
+
parsed = new URL(value);
|
|
565
|
+
} catch {
|
|
566
|
+
throw new UsageError(`${flag} needs an absolute URL, got "${value}"`);
|
|
567
|
+
}
|
|
568
|
+
const localhost = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';
|
|
569
|
+
if (parsed.protocol !== 'https:' && !localhost) {
|
|
570
|
+
throw new UsageError(`${flag} must be https (http is allowed only for localhost)`);
|
|
571
|
+
}
|
|
572
|
+
return value.replace(/\/+$/, '');
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
function parseDays(value) {
|
|
576
|
+
// Number() would take '0x1e' and '3e1'; "a whole number from 1 to 30" means
|
|
577
|
+
// digits, and the error message has to stay true.
|
|
578
|
+
if (!/^\d+$/.test(String(value).trim())) {
|
|
579
|
+
throw new UsageError(`--days must be a whole number from ${1} to ${MAX_DAYS}, got "${value}"`);
|
|
580
|
+
}
|
|
581
|
+
const days = Number(value);
|
|
582
|
+
if (!Number.isInteger(days) || days < 1 || days > MAX_DAYS) {
|
|
583
|
+
throw new UsageError(`--days must be a whole number from 1 to ${MAX_DAYS}, got "${value}"`);
|
|
584
|
+
}
|
|
585
|
+
return days;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function exitCodeFor(e) {
|
|
589
|
+
if (
|
|
590
|
+
e instanceof UsageError ||
|
|
591
|
+
e instanceof UnsupportedError ||
|
|
592
|
+
e instanceof LinkError ||
|
|
593
|
+
e instanceof EnvelopeError
|
|
594
|
+
) {
|
|
595
|
+
return EXIT.USAGE;
|
|
596
|
+
}
|
|
597
|
+
if (e instanceof NetworkError) return EXIT.NETWORK;
|
|
598
|
+
if (e instanceof ApiError) {
|
|
599
|
+
if (
|
|
600
|
+
['not_found', 'already_accessed', 'expired', 'revoked', 'account_deleted'].includes(e.code)
|
|
601
|
+
) {
|
|
602
|
+
return EXIT.GONE;
|
|
603
|
+
}
|
|
604
|
+
if (['rate_limited', 'quota_exceeded'].includes(e.code)) return EXIT.LIMITED;
|
|
605
|
+
return EXIT.ERROR;
|
|
606
|
+
}
|
|
607
|
+
return EXIT.ERROR;
|
|
608
|
+
}
|