@receiverdotemail/cli 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/README.md +71 -2
- package/dist/cli.d.ts +27 -0
- package/dist/cli.js +331 -0
- package/dist/config.d.ts +13 -0
- package/dist/config.js +25 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +45 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.js +3 -0
- package/package.json +56 -4
package/README.md
CHANGED
|
@@ -1,3 +1,72 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @receiverdotemail/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`receiver`: [Receiver.email](https://receiver.email) from the terminal. Create inboxes, wait for emails and OTP codes, and stream new mail, in scripts, CI or by hand.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install -g @receiverdotemail/cli
|
|
7
|
+
receiver login # paste a project API key (recv_live_...)
|
|
8
|
+
|
|
9
|
+
ADDR=$(receiver inbox new --prefix signup)
|
|
10
|
+
./my-app signup "$ADDR"
|
|
11
|
+
CODE=$(receiver otp "$ADDR" --timeout 60) # prints only the code
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
To keep the `since` of the new inbox (so older mail never matches):
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
INBOX=$(receiver --json inbox new --prefix signup)
|
|
18
|
+
ADDR=$(echo "$INBOX" | jq -r .address)
|
|
19
|
+
SINCE=$(echo "$INBOX" | jq -r .since)
|
|
20
|
+
receiver otp "$ADDR" --since "$SINCE"
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Authentication
|
|
24
|
+
|
|
25
|
+
`RECEIVER_API_KEY` wins when set. Otherwise the key saved by `receiver login` in `~/.config/receiver/config.json` (or `$XDG_CONFIG_HOME/receiver/config.json`, mode 0600) is used.
|
|
26
|
+
|
|
27
|
+
`receiver login` checks the key with the API before saving it. Without `--key` it prompts (hidden input) in a terminal, or reads the key from stdin: `echo "$KEY" | receiver login`. Logging in with `--api-url` or `RECEIVER_API_URL` set to a non-default API also saves that URL.
|
|
28
|
+
|
|
29
|
+
API URL order: `--api-url`, `RECEIVER_API_URL`, the saved login, `https://api.receiver.email/api/v1`.
|
|
30
|
+
|
|
31
|
+
## Commands
|
|
32
|
+
|
|
33
|
+
| Command | Does |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| `receiver login [--key <key>]` | Validates the key with `whoami` and saves it |
|
|
36
|
+
| `receiver whoami` | Project name, id and email suffix |
|
|
37
|
+
| `receiver inbox new [--prefix p]` | Prints a fresh address (`{ address, since }` with `--json`) |
|
|
38
|
+
| `receiver wait <address> [--since ISO] [--timeout s] [--otp \| --links]` | Waits (default 60 s) and prints a from/subject/body summary, only the code with `--otp`, or the links one per line with `--links` |
|
|
39
|
+
| `receiver otp <address> [--since ISO] [--timeout s]` | Same as `wait --otp`: prints only the code |
|
|
40
|
+
| `receiver list [--address a] [--limit n]` | Table of recent emails (default 20) |
|
|
41
|
+
| `receiver read <emailId> [--html \| --raw]` | Prints the full text body, the HTML, or the original RFC 822 message |
|
|
42
|
+
| `receiver watch [address]` | Prints new emails as they arrive until Ctrl-C |
|
|
43
|
+
| `receiver test-email <address>` | Sends a test email with a 6-digit code to one of your addresses |
|
|
44
|
+
|
|
45
|
+
Without `--since`, waits match mail from the last 60 seconds.
|
|
46
|
+
|
|
47
|
+
### Global options
|
|
48
|
+
|
|
49
|
+
- `--json`: machine-readable output, one JSON document per command (`watch` prints one JSON object per line). Errors print `{ "error": { "code", "message" } }`; timeouts print `{ "status": "timeout", "since", "waitedSeconds" }`.
|
|
50
|
+
- `--api-url <url>`: talk to another API (e.g. staging).
|
|
51
|
+
|
|
52
|
+
Human output goes to stdout, hints and diagnostics to stderr, so `$(receiver otp ...)` captures just the code.
|
|
53
|
+
|
|
54
|
+
### Exit codes
|
|
55
|
+
|
|
56
|
+
| Code | Meaning |
|
|
57
|
+
| --- | --- |
|
|
58
|
+
| 0 | Success (also Ctrl-C during `watch`) |
|
|
59
|
+
| 1 | Error (bad arguments, not logged in, API error) |
|
|
60
|
+
| 2 | Timeout: nothing arrived in time; rerun with the printed `--since` to keep waiting |
|
|
61
|
+
| 130 | Interrupted with Ctrl-C during `wait` or `otp` |
|
|
62
|
+
|
|
63
|
+
## Development
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
npm ci
|
|
67
|
+
npm run typecheck && npm test # uses ../typescript-sdk/src directly; no build needed
|
|
68
|
+
npm run build # builds ../typescript-sdk, then dist/
|
|
69
|
+
node dist/index.js --help
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The SDK dependency is `file:../typescript-sdk` inside this monorepo; publishing replaces it with the released `@receiverdotemail/sdk` version range.
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `receiver` command. `run()` takes its I/O and SDK client factory as
|
|
3
|
+
* arguments so tests can drive it without a terminal or network.
|
|
4
|
+
*/
|
|
5
|
+
import { ReceiverClient, type ReceiverClientOptions } from '@receiverdotemail/sdk';
|
|
6
|
+
export type CliClient = Pick<ReceiverClient, 'whoami' | 'inboxes' | 'emails'>;
|
|
7
|
+
export interface CliIO {
|
|
8
|
+
stdout: (text: string) => void;
|
|
9
|
+
stderr: (text: string) => void;
|
|
10
|
+
env: Record<string, string | undefined>;
|
|
11
|
+
/** Builds the SDK client (tests pass a fake). */
|
|
12
|
+
createClient?: (options: ReceiverClientOptions) => CliClient;
|
|
13
|
+
/** Whether stdin is an interactive terminal. */
|
|
14
|
+
stdinIsTTY?: boolean;
|
|
15
|
+
/** Prompts for the API key without echoing it (TTY only). */
|
|
16
|
+
promptSecret?: (question: string) => Promise<string>;
|
|
17
|
+
/** Reads all of stdin (for `echo $KEY | receiver login`). */
|
|
18
|
+
readStdin?: () => Promise<string>;
|
|
19
|
+
/** Aborted on Ctrl-C; stops `wait` and `watch`. */
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
}
|
|
22
|
+
export declare const EXIT_OK = 0;
|
|
23
|
+
export declare const EXIT_ERROR = 1;
|
|
24
|
+
export declare const EXIT_TIMEOUT = 2;
|
|
25
|
+
/** Ctrl-C during `wait`/`otp` (`watch` exits 0 on Ctrl-C). */
|
|
26
|
+
export declare const EXIT_INTERRUPTED = 130;
|
|
27
|
+
export declare function run(argv: string[], io: CliIO): Promise<number>;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `receiver` command. `run()` takes its I/O and SDK client factory as
|
|
3
|
+
* arguments so tests can drive it without a terminal or network.
|
|
4
|
+
*/
|
|
5
|
+
import { Command, CommanderError, Option } from 'commander';
|
|
6
|
+
import { AuthenticationError, DEFAULT_BASE_URL, RateLimitError, ReceiverClient, ReceiverError, ReceiverTimeoutError, } from '@receiverdotemail/sdk';
|
|
7
|
+
import { configPath, readConfig, writeConfig } from './config.js';
|
|
8
|
+
import { USER_AGENT, VERSION } from './version.js';
|
|
9
|
+
export const EXIT_OK = 0;
|
|
10
|
+
export const EXIT_ERROR = 1;
|
|
11
|
+
export const EXIT_TIMEOUT = 2;
|
|
12
|
+
/** Ctrl-C during `wait`/`otp` (`watch` exits 0 on Ctrl-C). */
|
|
13
|
+
export const EXIT_INTERRUPTED = 130;
|
|
14
|
+
/** Thrown inside commands to exit with a message (and an optional fix). */
|
|
15
|
+
class CliError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
constructor(message, code = 'CLI_ERROR') {
|
|
18
|
+
super(message);
|
|
19
|
+
this.code = code;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const BODY_PREVIEW = 1000;
|
|
23
|
+
export async function run(argv, io) {
|
|
24
|
+
let exitCode = EXIT_OK;
|
|
25
|
+
const createClient = io.createClient ?? ((options) => new ReceiverClient(options));
|
|
26
|
+
const cfgPath = configPath(io.env);
|
|
27
|
+
const out = (line = '') => io.stdout(line + '\n');
|
|
28
|
+
const err = (line = '') => io.stderr(line + '\n');
|
|
29
|
+
const program = new Command('receiver')
|
|
30
|
+
.description('Receiver.email from the terminal: create inboxes, wait for emails and OTP codes.')
|
|
31
|
+
.version(VERSION, '-v, --version')
|
|
32
|
+
.option('--json', 'machine-readable output (one JSON document; JSON lines for watch)')
|
|
33
|
+
.option('--api-url <url>', 'API base URL (default: RECEIVER_API_URL, then the saved login, then production)')
|
|
34
|
+
.showHelpAfterError('(run `receiver --help` for usage)')
|
|
35
|
+
.exitOverride()
|
|
36
|
+
.configureOutput({ writeOut: io.stdout, writeErr: io.stderr });
|
|
37
|
+
/** Wraps a command: resolves globals, prints errors, sets the exit code. */
|
|
38
|
+
const action = (fn) => async (...args) => {
|
|
39
|
+
const command = args[args.length - 1];
|
|
40
|
+
const globals = command.optsWithGlobals();
|
|
41
|
+
try {
|
|
42
|
+
await fn(globals, ...args.slice(0, -1));
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
exitCode = report(error, globals);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
const json = (globals, value) => out(JSON.stringify(value, null, 2));
|
|
49
|
+
function report(error, globals) {
|
|
50
|
+
if (error instanceof ReceiverTimeoutError) {
|
|
51
|
+
if (globals.json)
|
|
52
|
+
json(globals, { status: 'timeout', since: error.since, waitedSeconds: error.waitedSeconds });
|
|
53
|
+
else
|
|
54
|
+
err(`Timed out after ${error.waitedSeconds}s with no matching email (since ${error.since}). Run the same command with --since ${error.since} to keep waiting.`);
|
|
55
|
+
return EXIT_TIMEOUT;
|
|
56
|
+
}
|
|
57
|
+
if (error instanceof ReceiverError && error.code === 'ABORTED')
|
|
58
|
+
return EXIT_INTERRUPTED;
|
|
59
|
+
const { code, message } = describe(error);
|
|
60
|
+
if (globals.json)
|
|
61
|
+
json(globals, { error: { code, message } });
|
|
62
|
+
else
|
|
63
|
+
err(`Error: ${message}`);
|
|
64
|
+
return EXIT_ERROR;
|
|
65
|
+
}
|
|
66
|
+
async function client(globals, apiKeyOverride) {
|
|
67
|
+
const config = await readConfig(cfgPath);
|
|
68
|
+
const apiKey = apiKeyOverride ?? (io.env.RECEIVER_API_KEY || config.apiKey);
|
|
69
|
+
if (!apiKey)
|
|
70
|
+
throw new CliError('Not logged in. Run `receiver login`, or set RECEIVER_API_KEY.', 'NOT_LOGGED_IN');
|
|
71
|
+
// The saved project only belongs to the saved key; any other key looks its own up
|
|
72
|
+
const projectId = apiKey === config.apiKey ? config.projectId : undefined;
|
|
73
|
+
return createClient({ apiKey, baseUrl: apiUrl(globals, config.apiUrl), userAgent: USER_AGENT, projectId });
|
|
74
|
+
}
|
|
75
|
+
const apiUrl = (globals, saved) => globals.apiUrl || io.env.RECEIVER_API_URL || saved || DEFAULT_BASE_URL;
|
|
76
|
+
const parseSince = (value) => {
|
|
77
|
+
if (value === undefined)
|
|
78
|
+
return undefined;
|
|
79
|
+
if (Number.isNaN(Date.parse(value)))
|
|
80
|
+
throw new CliError(`--since must be an ISO 8601 timestamp, got "${value}"`, 'INVALID_ARGUMENT');
|
|
81
|
+
return value;
|
|
82
|
+
};
|
|
83
|
+
const parseTimeout = (value) => {
|
|
84
|
+
const seconds = Number(value);
|
|
85
|
+
if (!Number.isFinite(seconds) || seconds < 0)
|
|
86
|
+
throw new CommanderError(1, 'invalid', `--timeout must be a number of seconds, got "${value}"`);
|
|
87
|
+
return seconds;
|
|
88
|
+
};
|
|
89
|
+
const parseLimit = (value) => {
|
|
90
|
+
const n = Number(value);
|
|
91
|
+
if (!Number.isInteger(n) || n < 1 || n > 100)
|
|
92
|
+
throw new CommanderError(1, 'invalid', `--limit must be an integer from 1 to 100, got "${value}"`);
|
|
93
|
+
return n;
|
|
94
|
+
};
|
|
95
|
+
// receiver login
|
|
96
|
+
program
|
|
97
|
+
.command('login')
|
|
98
|
+
.description('validate an API key and save it to ' + cfgPath)
|
|
99
|
+
.option('--key <key>', 'the API key (recv_live_...); prompted for when omitted')
|
|
100
|
+
.action(action(async (globals, options) => {
|
|
101
|
+
let key = options.key;
|
|
102
|
+
if (!key && io.stdinIsTTY && io.promptSecret) {
|
|
103
|
+
key = await io.promptSecret('API key (recv_live_...): ');
|
|
104
|
+
}
|
|
105
|
+
else if (!key && !io.stdinIsTTY && io.readStdin) {
|
|
106
|
+
key = (await io.readStdin()).split(/\r?\n/)[0];
|
|
107
|
+
}
|
|
108
|
+
key = key?.trim();
|
|
109
|
+
if (!key)
|
|
110
|
+
throw new CliError('No API key given. Pass --key recv_live_... or pipe it on stdin.', 'INVALID_ARGUMENT');
|
|
111
|
+
const me = await (await client(globals, key)).whoami();
|
|
112
|
+
if (me.authType !== 'apikey') {
|
|
113
|
+
throw new CliError('That is a dashboard session token. Create a project API key (recv_live_...) in the dashboard.', 'NOT_AN_API_KEY');
|
|
114
|
+
}
|
|
115
|
+
const config = await readConfig(cfgPath);
|
|
116
|
+
const url = globals.apiUrl || io.env.RECEIVER_API_URL;
|
|
117
|
+
await writeConfig(cfgPath, { ...config, apiKey: key, apiUrl: url && url !== DEFAULT_BASE_URL ? url : undefined, projectId: me.project.id });
|
|
118
|
+
if (globals.json)
|
|
119
|
+
return json(globals, { ...me, configPath: cfgPath });
|
|
120
|
+
out(`Logged in to project ${me.project.name} (${me.project.id}).`);
|
|
121
|
+
out(`Addresses end with ${me.project.emailSuffix}`);
|
|
122
|
+
err(`Key saved to ${cfgPath}`);
|
|
123
|
+
}));
|
|
124
|
+
// receiver whoami
|
|
125
|
+
program
|
|
126
|
+
.command('whoami')
|
|
127
|
+
.description('show the project the API key belongs to')
|
|
128
|
+
.action(action(async (globals) => {
|
|
129
|
+
const me = await (await client(globals)).whoami();
|
|
130
|
+
if (globals.json)
|
|
131
|
+
return json(globals, me);
|
|
132
|
+
if (me.authType === 'jwt') {
|
|
133
|
+
out(`Dashboard session for ${me.user.email} (${me.user.id})`);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
out(`Project: ${me.project.name}`);
|
|
137
|
+
out(`Project ID: ${me.project.id}`);
|
|
138
|
+
out(`Email suffix: ${me.project.emailSuffix}`);
|
|
139
|
+
out(`API key: ${me.apiKey.name} (${me.apiKey.id})`);
|
|
140
|
+
}));
|
|
141
|
+
// receiver inbox new
|
|
142
|
+
const inbox = program.command('inbox').description('mint addresses');
|
|
143
|
+
inbox
|
|
144
|
+
.command('new')
|
|
145
|
+
.description('create a fresh address and print it')
|
|
146
|
+
.option('--prefix <prefix>', 'readable start of the address, e.g. signup')
|
|
147
|
+
.action(action(async (globals, options) => {
|
|
148
|
+
const created = await (await client(globals)).inboxes.create({ prefix: options.prefix });
|
|
149
|
+
if (globals.json)
|
|
150
|
+
return json(globals, { address: created.address, since: created.createdAt });
|
|
151
|
+
out(created.address);
|
|
152
|
+
}));
|
|
153
|
+
// receiver wait / receiver otp
|
|
154
|
+
const waitFor = async (globals, address, options) => {
|
|
155
|
+
if (options.otp && options.links)
|
|
156
|
+
throw new CliError('Use either --otp or --links, not both.', 'INVALID_ARGUMENT');
|
|
157
|
+
const c = await client(globals);
|
|
158
|
+
const since = parseSince(options.since);
|
|
159
|
+
if (options.otp) {
|
|
160
|
+
const otp = await c.emails.waitForOtp({ recipient: address, since, timeout: options.timeout, signal: io.signal });
|
|
161
|
+
if (globals.json)
|
|
162
|
+
return json(globals, { status: 'found', ...otp });
|
|
163
|
+
out(otp.code);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const email = await c.emails.waitFor({ recipient: address, since, timeout: options.timeout, signal: io.signal });
|
|
167
|
+
if (options.links) {
|
|
168
|
+
if (globals.json)
|
|
169
|
+
return json(globals, { status: 'received', email, links: email.links });
|
|
170
|
+
for (const link of email.links)
|
|
171
|
+
out(link);
|
|
172
|
+
if (email.links.length === 0)
|
|
173
|
+
err('The email has no links.');
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (globals.json)
|
|
177
|
+
return json(globals, { status: 'received', email });
|
|
178
|
+
printSummary(email);
|
|
179
|
+
};
|
|
180
|
+
const printSummary = (email) => {
|
|
181
|
+
out(`From: ${email.sender}`);
|
|
182
|
+
out(`To: ${email.sendTo}`);
|
|
183
|
+
out(`Subject: ${email.subject}`);
|
|
184
|
+
out(`Received: ${email.receivedAt}`);
|
|
185
|
+
out(`ID: ${email.id}`);
|
|
186
|
+
if (email.links?.length)
|
|
187
|
+
out(`Links: ${email.links.length}`);
|
|
188
|
+
const body = (email.textBody ?? email.textBodyPreview ?? '').trim();
|
|
189
|
+
if (body) {
|
|
190
|
+
out();
|
|
191
|
+
out(body.length > BODY_PREVIEW ? body.slice(0, BODY_PREVIEW) + '...' : body);
|
|
192
|
+
if (body.length > BODY_PREVIEW)
|
|
193
|
+
err(`(body truncated: run \`receiver read ${email.id}\` for the full text)`);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
const timeoutOption = () => new Option('--timeout <seconds>', 'how long to wait').argParser(parseTimeout).default(60);
|
|
197
|
+
const sinceOption = () => new Option('--since <iso>', 'only email received after this time (default: the last 60 s)');
|
|
198
|
+
program
|
|
199
|
+
.command('wait')
|
|
200
|
+
.description('wait for an email to <address>')
|
|
201
|
+
.argument('<address>', 'the address to wait on')
|
|
202
|
+
.addOption(sinceOption())
|
|
203
|
+
.addOption(timeoutOption())
|
|
204
|
+
.option('--otp', 'print only the OTP code')
|
|
205
|
+
.option('--links', 'print only the links, one per line')
|
|
206
|
+
.action(action(async (globals, address, options) => waitFor(globals, address, options)));
|
|
207
|
+
program
|
|
208
|
+
.command('otp')
|
|
209
|
+
.description('wait for an OTP code sent to <address> and print only the code')
|
|
210
|
+
.argument('<address>', 'the address to wait on')
|
|
211
|
+
.addOption(sinceOption())
|
|
212
|
+
.addOption(timeoutOption())
|
|
213
|
+
.action(action(async (globals, address, options) => waitFor(globals, address, { ...options, otp: true })));
|
|
214
|
+
// receiver list
|
|
215
|
+
program
|
|
216
|
+
.command('list')
|
|
217
|
+
.description('show recent emails, newest first')
|
|
218
|
+
.option('--address <address>', 'only emails sent to this address')
|
|
219
|
+
.addOption(new Option('--limit <n>', 'how many').argParser(parseLimit).default(20))
|
|
220
|
+
.action(action(async (globals, options) => {
|
|
221
|
+
const { emails } = await (await client(globals)).emails.list({ recipient: options.address, limit: options.limit });
|
|
222
|
+
if (globals.json)
|
|
223
|
+
return json(globals, { emails });
|
|
224
|
+
if (emails.length === 0) {
|
|
225
|
+
err('No emails.');
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
table(['RECEIVED', 'FROM', 'TO', 'SUBJECT', 'ID'], emails.map(e => [e.receivedAt.replace(/\.\d+Z$/, 'Z'), e.sender, e.sendTo, truncate(e.subject, 50), e.id])).forEach(line => out(line));
|
|
229
|
+
}));
|
|
230
|
+
// receiver read
|
|
231
|
+
program
|
|
232
|
+
.command('read')
|
|
233
|
+
.description('print the body of an email')
|
|
234
|
+
.argument('<emailId>', 'email id (from list or wait)')
|
|
235
|
+
.option('--html', 'print the HTML body')
|
|
236
|
+
.option('--raw', 'print the original message (RFC 822)')
|
|
237
|
+
.action(action(async (globals, emailId, options) => {
|
|
238
|
+
if (options.html && options.raw)
|
|
239
|
+
throw new CliError('Use either --html or --raw, not both.', 'INVALID_ARGUMENT');
|
|
240
|
+
const type = options.raw ? 'raw' : options.html ? 'html' : 'text';
|
|
241
|
+
const c = await client(globals);
|
|
242
|
+
if (globals.json) {
|
|
243
|
+
const [email, body] = await Promise.all([c.emails.get(emailId), c.emails.getContent(emailId, type)]);
|
|
244
|
+
return json(globals, { email, format: type, body });
|
|
245
|
+
}
|
|
246
|
+
const body = await c.emails.getContent(emailId, type);
|
|
247
|
+
io.stdout(body.endsWith('\n') ? body : body + '\n');
|
|
248
|
+
}));
|
|
249
|
+
// receiver watch
|
|
250
|
+
program
|
|
251
|
+
.command('watch')
|
|
252
|
+
.description('print new emails as they arrive, until Ctrl-C')
|
|
253
|
+
.argument('[address]', 'only emails to this address (default: the whole project)')
|
|
254
|
+
.action(action(async (globals, address) => {
|
|
255
|
+
const c = await client(globals);
|
|
256
|
+
if (!globals.json)
|
|
257
|
+
err(`Watching ${address ?? 'all addresses'} for new email (Ctrl-C to stop)...`);
|
|
258
|
+
for await (const event of c.emails.stream({ recipient: address, signal: io.signal })) {
|
|
259
|
+
if (globals.json) {
|
|
260
|
+
out(JSON.stringify(event));
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const otp = event.otp ? ` code ${event.otp.code}` : '';
|
|
264
|
+
out(`${event.email.receivedAt} ${event.email.sender} -> ${event.email.sendTo} ${event.email.subject}${otp} (${event.id})`);
|
|
265
|
+
}
|
|
266
|
+
}));
|
|
267
|
+
// receiver test-email
|
|
268
|
+
program
|
|
269
|
+
.command('test-email')
|
|
270
|
+
.description('send a test email (with a 6-digit code) to one of your addresses')
|
|
271
|
+
.argument('<address>', 'an address ending with your project\'s email suffix')
|
|
272
|
+
.action(action(async (globals, address) => {
|
|
273
|
+
const sent = await (await client(globals)).emails.sendTest({ to: address });
|
|
274
|
+
if (globals.json)
|
|
275
|
+
return json(globals, sent);
|
|
276
|
+
out(`Sent a test email to ${sent.to}.`);
|
|
277
|
+
err(`Get its code with: receiver otp ${sent.to} --since ${sent.sentAt}`);
|
|
278
|
+
}));
|
|
279
|
+
try {
|
|
280
|
+
await program.parseAsync(argv, { from: 'user' });
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
if (error instanceof CommanderError) {
|
|
284
|
+
// --help and --version exit 0; usage errors already printed by commander
|
|
285
|
+
if (error.code === 'invalid')
|
|
286
|
+
err(`error: ${error.message}`);
|
|
287
|
+
return error.exitCode === 0 ? EXIT_OK : EXIT_ERROR;
|
|
288
|
+
}
|
|
289
|
+
throw error;
|
|
290
|
+
}
|
|
291
|
+
return exitCode;
|
|
292
|
+
}
|
|
293
|
+
function describe(error) {
|
|
294
|
+
if (error instanceof CliError)
|
|
295
|
+
return { code: error.code, message: error.message };
|
|
296
|
+
if (error instanceof AuthenticationError) {
|
|
297
|
+
return { code: 'UNAUTHORIZED', message: `The API key was rejected (${error.message}). Run \`receiver login\` with a valid key, or check RECEIVER_API_KEY.` };
|
|
298
|
+
}
|
|
299
|
+
if (error instanceof RateLimitError) {
|
|
300
|
+
const when = error.resetAt ? `after ${error.resetAt.toISOString()}` : 'in a minute';
|
|
301
|
+
return { code: 'RATE_LIMIT_EXCEEDED', message: `${error.message}. Try again ${when}.` };
|
|
302
|
+
}
|
|
303
|
+
if (error instanceof ReceiverError) {
|
|
304
|
+
const code = error.code ?? `HTTP_${error.statusCode}`;
|
|
305
|
+
const message = error.message.replace(/\.$/, '');
|
|
306
|
+
if (error.statusCode === 0 || error.statusCode === 408) {
|
|
307
|
+
return { code, message: `Could not reach the API (${message}). Check your network, or --api-url / RECEIVER_API_URL.` };
|
|
308
|
+
}
|
|
309
|
+
if (error.code === 'PROJECT_ID_REQUIRED') {
|
|
310
|
+
return { code, message: 'This is a dashboard session token. Use a project API key (recv_live_...): run `receiver login`.' };
|
|
311
|
+
}
|
|
312
|
+
if (error.statusCode === 403) {
|
|
313
|
+
return { code, message: `${message}. The API key only works for its own project: check it with \`receiver whoami\`.` };
|
|
314
|
+
}
|
|
315
|
+
if (error.statusCode === 404)
|
|
316
|
+
return { code, message: `${message}. Check the id with \`receiver list\`.` };
|
|
317
|
+
if (error.statusCode >= 500) {
|
|
318
|
+
return { code, message: `${message} (HTTP ${error.statusCode}). Try again in a minute.` };
|
|
319
|
+
}
|
|
320
|
+
return { code, message: `${message}.` };
|
|
321
|
+
}
|
|
322
|
+
return { code: 'ERROR', message: error?.message ?? String(error) };
|
|
323
|
+
}
|
|
324
|
+
function truncate(text, max) {
|
|
325
|
+
return text.length > max ? text.slice(0, max - 3) + '...' : text;
|
|
326
|
+
}
|
|
327
|
+
function table(header, rows) {
|
|
328
|
+
const widths = header.map((h, i) => Math.max(h.length, ...rows.map(r => r[i].length)));
|
|
329
|
+
const line = (cells) => cells.map((c, i) => (i === cells.length - 1 ? c : c.padEnd(widths[i]))).join(' ');
|
|
330
|
+
return [line(header), ...rows.map(line)];
|
|
331
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ~/.config/receiver/config.json, written by `receiver login`.
|
|
3
|
+
*/
|
|
4
|
+
export interface CliConfig {
|
|
5
|
+
apiKey?: string;
|
|
6
|
+
/** Saved when `login` ran against a non-default API (e.g. staging). */
|
|
7
|
+
apiUrl?: string;
|
|
8
|
+
/** The saved key's project, so commands skip a `whoami` request. */
|
|
9
|
+
projectId?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function configPath(env: Record<string, string | undefined>): string;
|
|
12
|
+
export declare function readConfig(path: string): Promise<CliConfig>;
|
|
13
|
+
export declare function writeConfig(path: string, config: CliConfig): Promise<void>;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ~/.config/receiver/config.json, written by `receiver login`.
|
|
3
|
+
*/
|
|
4
|
+
import { mkdir, readFile, writeFile, chmod } from 'node:fs/promises';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
export function configPath(env) {
|
|
8
|
+
const base = env.XDG_CONFIG_HOME || join(env.HOME || homedir(), '.config');
|
|
9
|
+
return join(base, 'receiver', 'config.json');
|
|
10
|
+
}
|
|
11
|
+
export async function readConfig(path) {
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(await readFile(path, 'utf8'));
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
if (error.code === 'ENOENT')
|
|
17
|
+
return {};
|
|
18
|
+
throw new Error(`Could not read ${path}: ${error.message}. Fix or delete the file, then run \`receiver login\`.`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export async function writeConfig(path, config) {
|
|
22
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
23
|
+
await writeFile(path, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
|
|
24
|
+
await chmod(path, 0o600); // writeFile's mode only applies when creating the file
|
|
25
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* receiver: the Receiver.email CLI.
|
|
4
|
+
*/
|
|
5
|
+
import { createInterface } from 'node:readline';
|
|
6
|
+
import { run } from './cli.js';
|
|
7
|
+
const controller = new AbortController();
|
|
8
|
+
let interrupted = false;
|
|
9
|
+
process.on('SIGINT', () => {
|
|
10
|
+
// First Ctrl-C stops `wait`/`watch` cleanly; a second one exits at once
|
|
11
|
+
if (interrupted)
|
|
12
|
+
process.exit(130);
|
|
13
|
+
interrupted = true;
|
|
14
|
+
controller.abort();
|
|
15
|
+
});
|
|
16
|
+
/** Reads a line from the terminal without echoing it. */
|
|
17
|
+
function promptSecret(question) {
|
|
18
|
+
return new Promise(resolve => {
|
|
19
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
|
|
20
|
+
const output = rl;
|
|
21
|
+
process.stderr.write(question);
|
|
22
|
+
output._writeToOutput = () => { }; // mute echo
|
|
23
|
+
rl.question('', answer => {
|
|
24
|
+
rl.close();
|
|
25
|
+
process.stderr.write('\n');
|
|
26
|
+
resolve(answer);
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
async function readStdin() {
|
|
31
|
+
const chunks = [];
|
|
32
|
+
for await (const chunk of process.stdin)
|
|
33
|
+
chunks.push(chunk);
|
|
34
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
35
|
+
}
|
|
36
|
+
const code = await run(process.argv.slice(2), {
|
|
37
|
+
stdout: text => process.stdout.write(text),
|
|
38
|
+
stderr: text => process.stderr.write(text),
|
|
39
|
+
env: process.env,
|
|
40
|
+
stdinIsTTY: Boolean(process.stdin.isTTY),
|
|
41
|
+
promptSecret,
|
|
42
|
+
readStdin,
|
|
43
|
+
signal: controller.signal,
|
|
44
|
+
});
|
|
45
|
+
process.exitCode = code;
|
package/dist/version.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@receiverdotemail/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Receiver.email from the terminal: create inboxes, wait for emails and OTP codes, stream new mail",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"receiver": "dist/index.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=20"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build:sdk": "cd ../typescript-sdk && ([ -d node_modules ] || npm ci --no-audit --no-fund --loglevel=error) && npm run build",
|
|
17
|
+
"build": "npm run build:sdk && tsc -p tsconfig.build.json",
|
|
18
|
+
"typecheck": "tsc --noEmit",
|
|
19
|
+
"test": "vitest run",
|
|
20
|
+
"test:watch": "vitest",
|
|
21
|
+
"prepublishOnly": "npm run build"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"receiver.email",
|
|
25
|
+
"email",
|
|
26
|
+
"otp",
|
|
27
|
+
"2fa",
|
|
28
|
+
"magic-link",
|
|
29
|
+
"email-testing",
|
|
30
|
+
"inbound-email",
|
|
31
|
+
"ci",
|
|
32
|
+
"testing",
|
|
33
|
+
"cli"
|
|
34
|
+
],
|
|
35
|
+
"author": "Receiver.email",
|
|
36
|
+
"license": "MIT",
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@receiverdotemail/sdk": "^2.0.0",
|
|
39
|
+
"commander": "^14.0.3"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@types/node": "^20.0.0",
|
|
43
|
+
"typescript": "^5.0.0",
|
|
44
|
+
"vitest": "^3.2.4"
|
|
45
|
+
},
|
|
46
|
+
"repository": {
|
|
47
|
+
"type": "git",
|
|
48
|
+
"url": "git+https://github.com/BUW91/mailingestion.git",
|
|
49
|
+
"directory": "packages/cli"
|
|
50
|
+
},
|
|
51
|
+
"homepage": "https://receiver.email/docs/cli",
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/BUW91/mailingestion/issues"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public"
|
|
57
|
+
}
|
|
58
|
+
}
|