coss-cli 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.
@@ -0,0 +1,1544 @@
1
+ import { spawn } from "node:child_process";
2
+ import { homedir, hostname } from "node:os";
3
+ import { join } from "node:path";
4
+ import { createHash, createHmac, randomBytes } from "node:crypto";
5
+ import { chmod, mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
6
+ import { parseArgs } from "node:util";
7
+ import { Coss } from "coss";
8
+ import { createServer } from "node:http";
9
+ //#region src/io.ts
10
+ /**
11
+ * Everything the CLI touches outside itself, injectable so tests can run commands in process: the
12
+ * environment, terminal streams, `fetch`, the clock, the browser, the config directory and the
13
+ * interrupt signal. `nodeIo()` is the real thing.
14
+ */
15
+ /** `$XDG_CONFIG_HOME/coss`, `%APPDATA%\coss` on Windows, else `~/.config/coss`. */
16
+ function defaultConfigDir(env, platform = process.platform, home = homedir()) {
17
+ if (env.XDG_CONFIG_HOME) return join(env.XDG_CONFIG_HOME, "coss");
18
+ if (platform === "win32" && env.APPDATA) return join(env.APPDATA, "coss");
19
+ return join(home, ".config", "coss");
20
+ }
21
+ function sleep(ms, signal) {
22
+ return new Promise((resolve) => {
23
+ if (signal?.aborted) return resolve();
24
+ const done = () => {
25
+ clearTimeout(timer);
26
+ signal?.removeEventListener("abort", done);
27
+ resolve();
28
+ };
29
+ const timer = setTimeout(done, ms);
30
+ signal?.addEventListener("abort", done, { once: true });
31
+ });
32
+ }
33
+ function browserCommand(url) {
34
+ if (process.platform === "darwin") return ["open", [url]];
35
+ if (process.platform === "win32") return ["rundll32", ["url.dll,FileProtocolHandler", url]];
36
+ return ["xdg-open", [url]];
37
+ }
38
+ function openBrowser(url) {
39
+ return new Promise((resolve) => {
40
+ const [command, args] = browserCommand(url);
41
+ try {
42
+ const child = spawn(command, args, {
43
+ detached: true,
44
+ stdio: "ignore"
45
+ });
46
+ child.once("error", () => resolve(false));
47
+ child.once("spawn", () => {
48
+ child.unref();
49
+ resolve(true);
50
+ });
51
+ } catch {
52
+ resolve(false);
53
+ }
54
+ });
55
+ }
56
+ /** Reads a line from a non-terminal stdin (e.g. `echo $KEY | coss login --manual`). */
57
+ async function readPipedLine() {
58
+ let text = "";
59
+ for await (const chunk of process.stdin) {
60
+ text += String(chunk);
61
+ if (text.includes("\n")) break;
62
+ }
63
+ return text.split(/\r?\n/)[0]?.trim() ?? "";
64
+ }
65
+ /** One line from the terminal, typed without echo when `secret` (raw mode). */
66
+ function readTerminalLine(secret) {
67
+ const stdin = process.stdin;
68
+ return new Promise((resolve, reject) => {
69
+ let value = "";
70
+ const finish = (error) => {
71
+ stdin.off("data", onData);
72
+ stdin.setRawMode(false);
73
+ stdin.pause();
74
+ process.stderr.write("\n");
75
+ if (error) reject(error);
76
+ else resolve(value.trim());
77
+ };
78
+ const onData = (chunk) => {
79
+ for (const char of String(chunk)) {
80
+ if (char === "\r" || char === "\n") return finish();
81
+ if (char === "") return finish(/* @__PURE__ */ new Error("Interrupted."));
82
+ if (char === "" || char === "\b") {
83
+ if (value.length > 0) {
84
+ value = value.slice(0, -1);
85
+ if (!secret) process.stderr.write("\b \b");
86
+ }
87
+ continue;
88
+ }
89
+ value += char;
90
+ if (!secret) process.stderr.write(char);
91
+ }
92
+ };
93
+ stdin.setRawMode(true);
94
+ stdin.resume();
95
+ stdin.on("data", onData);
96
+ });
97
+ }
98
+ /** The real process: its environment, streams, network and signals. */
99
+ function nodeIo() {
100
+ const controller = new AbortController();
101
+ let interrupts = 0;
102
+ for (const name of ["SIGINT", "SIGTERM"]) process.on(name, () => {
103
+ interrupts++;
104
+ if (interrupts > 1) process.exit(130);
105
+ controller.abort();
106
+ });
107
+ return {
108
+ env: process.env,
109
+ stdout: process.stdout,
110
+ stderr: process.stderr,
111
+ stdinIsTTY: process.stdin.isTTY === true,
112
+ fetch: (input, init) => globalThis.fetch(input, init),
113
+ now: () => /* @__PURE__ */ new Date(),
114
+ sleep,
115
+ openBrowser,
116
+ async prompt(question, options = {}) {
117
+ process.stderr.write(question);
118
+ if (!process.stdin.isTTY) {
119
+ const line = await readPipedLine();
120
+ process.stderr.write("\n");
121
+ return line;
122
+ }
123
+ return readTerminalLine(options.secret === true);
124
+ },
125
+ hostname: () => hostname(),
126
+ configDir: defaultConfigDir(process.env),
127
+ signal: controller.signal
128
+ };
129
+ }
130
+ //#endregion
131
+ //#region src/listen/sign.ts
132
+ /**
133
+ * Standard Webhooks signatures (https://www.standardwebhooks.com), as coss.com signs the requests it
134
+ * sends endpoints: `v1,<base64 HMAC-SHA256 of "<id>.<timestamp>.<body>">` keyed by the secret's
135
+ * base64 part. The SDK's `verifyWebhook` checks them.
136
+ */
137
+ const SECRET = /^whsec_[A-Za-z0-9+/]{43}=$/;
138
+ function generateSecret() {
139
+ return `whsec_${randomBytes(32).toString("base64")}`;
140
+ }
141
+ function isSecret(value) {
142
+ return typeof value === "string" && SECRET.test(value);
143
+ }
144
+ function sign(secret, id, timestamp, body) {
145
+ const key = Buffer.from(secret.slice(6), "base64");
146
+ return `v1,${createHmac("sha256", key).update(`${id}.${timestamp}.${body}`).digest("base64")}`;
147
+ }
148
+ /** The three headers a coss.com webhook carries. */
149
+ function signatureHeaders(input) {
150
+ return {
151
+ "webhook-id": input.id,
152
+ "webhook-timestamp": String(input.timestamp),
153
+ "webhook-signature": sign(input.secret, input.id, input.timestamp, input.body)
154
+ };
155
+ }
156
+ //#endregion
157
+ //#region src/errors.ts
158
+ /** A failure to report to the user: printed as is (no stack), with an exit code. */
159
+ var CliError = class extends Error {
160
+ exitCode;
161
+ constructor(message, exitCode = 1) {
162
+ super(message);
163
+ this.name = "CliError";
164
+ this.exitCode = exitCode;
165
+ }
166
+ };
167
+ /** Wrong flags or arguments (exit code 2, like most CLIs). */
168
+ var UsageError = class extends CliError {
169
+ constructor(message) {
170
+ super(message, 2);
171
+ this.name = "UsageError";
172
+ }
173
+ };
174
+ const HINTS = {
175
+ authentication_error: "Run `coss login` to sign in again.",
176
+ permission_error: "This API key isn't allowed to do that.",
177
+ rate_limit_error: "Slow down and try again shortly.",
178
+ connection_error: "Check your connection (and COSS_BASE_URL, if you set it)."
179
+ };
180
+ /**
181
+ * Failures worth retrying unchanged: the network, a timeout, a rate limit or the API itself (5xx).
182
+ * Anything else (a bad filter, a revoked key, …) fails the same way every time.
183
+ */
184
+ function isTransient(error) {
185
+ return error.type === "connection_error" || error.type === "timeout_error" || error.type === "rate_limit_error" || error.type === "api_error";
186
+ }
187
+ /** An API failure as one readable message: what failed, why, and the request id for support. */
188
+ function apiError(doing, error) {
189
+ const details = [error.message, ...(error.issues ?? []).map((issue) => ` ${issue.path}: ${issue.message}`)].join("\n");
190
+ const request = error.request_id ? ` (request ${error.request_id})` : "";
191
+ const hint = HINTS[error.type];
192
+ return new CliError(`${doing}: ${details}${request}${hint ? `\n${hint}` : ""}`);
193
+ }
194
+ //#endregion
195
+ //#region src/args.ts
196
+ /** Flags every command takes. */
197
+ const GLOBAL_OPTIONS = {
198
+ profile: { type: "string" },
199
+ json: { type: "boolean" },
200
+ "no-color": { type: "boolean" },
201
+ help: {
202
+ type: "boolean",
203
+ short: "h"
204
+ }
205
+ };
206
+ /** Parses a command's flags (strict: unknown flags are a usage error) plus the global ones. */
207
+ function parseFlags(argv, options, allowPositionals = false) {
208
+ try {
209
+ const parsed = parseArgs({
210
+ args: argv,
211
+ options: {
212
+ ...GLOBAL_OPTIONS,
213
+ ...options
214
+ },
215
+ strict: true,
216
+ allowPositionals
217
+ });
218
+ const values = parsed.values;
219
+ const global = {
220
+ profile: typeof values.profile === "string" ? values.profile : void 0,
221
+ json: values.json === true,
222
+ color: values["no-color"] !== true,
223
+ help: values.help === true
224
+ };
225
+ return {
226
+ values: parsed.values,
227
+ positionals: parsed.positionals,
228
+ global
229
+ };
230
+ } catch (error) {
231
+ throw new UsageError(error instanceof Error ? error.message : String(error));
232
+ }
233
+ }
234
+ /** Repeatable flags that may also be comma-separated: `--events a,b --events c`. */
235
+ /**
236
+ * Email addresses from repeated and comma-separated flags. Commas inside a quoted display name
237
+ * (`"Acme, Inc." <hello@acme.com>`) or angle brackets don't separate addresses.
238
+ */
239
+ function addresses(value) {
240
+ const values = value === void 0 ? [] : Array.isArray(value) ? value : [value];
241
+ const out = [];
242
+ for (const item of values) {
243
+ let current = "";
244
+ let quoted = false;
245
+ let angle = false;
246
+ for (let i = 0; i < item.length; i++) {
247
+ const char = item[i];
248
+ if (quoted && char === "\\" && i + 1 < item.length) {
249
+ current += char + item[++i];
250
+ continue;
251
+ }
252
+ if (char === "\"") quoted = !quoted;
253
+ else if (!quoted && char === "<") angle = true;
254
+ else if (!quoted && char === ">") angle = false;
255
+ else if (char === "," && !quoted && !angle) {
256
+ out.push(current);
257
+ current = "";
258
+ continue;
259
+ }
260
+ current += char;
261
+ }
262
+ out.push(current);
263
+ }
264
+ return out.map((item) => item.trim()).filter(Boolean);
265
+ }
266
+ function list(value) {
267
+ return (value === void 0 ? [] : Array.isArray(value) ? value : [value]).flatMap((item) => item.split(",")).map((item) => item.trim()).filter(Boolean);
268
+ }
269
+ function configPath(io) {
270
+ return join(io.configDir, "config.json");
271
+ }
272
+ const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
273
+ function checkedProfileName(name) {
274
+ if (!PROFILE_NAME.test(name)) throw new CliError(`Invalid profile name "${name}": use letters, digits, ".", "-" or "_".`, 2);
275
+ return name;
276
+ }
277
+ async function readConfig(io) {
278
+ const path = configPath(io);
279
+ let text;
280
+ try {
281
+ text = await readFile(path, "utf8");
282
+ } catch (error) {
283
+ if (error.code === "ENOENT") return {
284
+ version: 1,
285
+ profiles: {}
286
+ };
287
+ throw error;
288
+ }
289
+ try {
290
+ const parsed = JSON.parse(text);
291
+ if (parsed.version !== 1 || typeof parsed.profiles !== "object" || parsed.profiles === null) throw new Error("unknown format");
292
+ return {
293
+ version: 1,
294
+ default_profile: parsed.default_profile,
295
+ profiles: parsed.profiles
296
+ };
297
+ } catch {
298
+ throw new CliError(`${path} is not a valid coss.com CLI config. Fix it or delete it.`);
299
+ }
300
+ }
301
+ /** Whether others can read the file (only checked where permissions mean something). */
302
+ async function configIsShared(io) {
303
+ if (process.platform === "win32") return false;
304
+ try {
305
+ return ((await stat(configPath(io))).mode & 63) !== 0;
306
+ } catch {
307
+ return false;
308
+ }
309
+ }
310
+ async function writeConfig(io, config) {
311
+ await mkdir(io.configDir, {
312
+ recursive: true,
313
+ mode: 448
314
+ });
315
+ const path = configPath(io);
316
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
317
+ await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: 384 });
318
+ await chmod(temporary, 384);
319
+ await rename(temporary, path);
320
+ }
321
+ /** The profile commands use: `--profile`, else `COSS_PROFILE`, else the saved default. */
322
+ function profileName(io, config, flag) {
323
+ return checkedProfileName(flag ?? io.env.COSS_PROFILE ?? config.default_profile ?? "default");
324
+ }
325
+ //#endregion
326
+ //#region src/output.ts
327
+ const CODES = {
328
+ bold: 1,
329
+ dim: 2,
330
+ red: 31,
331
+ green: 32,
332
+ yellow: 33,
333
+ blue: 34,
334
+ magenta: 35,
335
+ cyan: 36,
336
+ gray: 90
337
+ };
338
+ /**
339
+ * Results go to stdout (one JSON object per line with `--json`, for pipes); progress, prompts and
340
+ * warnings to stderr. Colors only on a terminal, never with `NO_COLOR`, `--no-color` or `--json`.
341
+ */
342
+ var Output = class {
343
+ json;
344
+ #io;
345
+ #color;
346
+ constructor(io, options) {
347
+ this.#io = io;
348
+ this.json = options.json;
349
+ this.#color = options.color && !options.json && io.stdout.isTTY === true && !("NO_COLOR" in io.env);
350
+ }
351
+ style(style, text) {
352
+ if (!this.#color) return text;
353
+ return `\u001b[${(Array.isArray(style) ? style : [style]).map((name) => CODES[name]).join(";")}m${text}\u001b[0m`;
354
+ }
355
+ /** A result line (stdout). */
356
+ line(text = "") {
357
+ this.#io.stdout.write(`${text}\n`);
358
+ }
359
+ /** A result as one JSON line (stdout). */
360
+ data(value) {
361
+ this.#io.stdout.write(`${JSON.stringify(value)}\n`);
362
+ }
363
+ /** Progress or context (stderr), so stdout stays the result. */
364
+ info(text = "") {
365
+ this.#io.stderr.write(`${text}\n`);
366
+ }
367
+ warn(text) {
368
+ this.#io.stderr.write(`${this.style("yellow", "!")} ${text}\n`);
369
+ }
370
+ error(text) {
371
+ this.#io.stderr.write(`${this.style("red", "✖")} ${text}\n`);
372
+ }
373
+ };
374
+ const API_KEY_FORMAT = /^coss_(live|test)_[A-Za-z]{64}$/;
375
+ function createContext(io, flags) {
376
+ return {
377
+ io,
378
+ flags,
379
+ out: new Output(io, {
380
+ json: flags.json,
381
+ color: flags.color
382
+ })
383
+ };
384
+ }
385
+ function trimmed(value) {
386
+ const text = value?.trim();
387
+ return text ? text.replace(/\/+$/, "") : void 0;
388
+ }
389
+ function apiBaseUrl(io, profile) {
390
+ return trimmed(io.env.COSS_BASE_URL) ?? profile?.base_url ?? "https://api.coss.com";
391
+ }
392
+ /**
393
+ * Where a saved profile's key lives, whatever `COSS_BASE_URL` says now: revoking a key anywhere
394
+ * else would answer 401 and look like it worked.
395
+ */
396
+ function savedApiBaseUrl(profile) {
397
+ return profile.base_url ?? "https://api.coss.com";
398
+ }
399
+ function dashboardBaseUrl(io, profile) {
400
+ return trimmed(io.env.COSS_DASHBOARD_URL) ?? profile?.dashboard_url ?? "https://coss.com";
401
+ }
402
+ /** The key to use, or a `CliError` telling the user how to get one. */
403
+ async function resolveCredentials(context) {
404
+ const { io, flags } = context;
405
+ const config = await readConfig(io);
406
+ const name = profileName(io, config, flags.profile);
407
+ const fromEnv = io.env.COSS_API_KEY?.trim();
408
+ if (fromEnv) return {
409
+ apiKey: fromEnv,
410
+ source: "env",
411
+ profileName: name,
412
+ profile: null,
413
+ config,
414
+ baseUrl: apiBaseUrl(io, null),
415
+ dashboardUrl: dashboardBaseUrl(io, null)
416
+ };
417
+ const profile = config.profiles[name];
418
+ if (!profile) throw new CliError(name === "default" && !flags.profile && !io.env.COSS_PROFILE ? "Not signed in. Run `coss login`, or set COSS_API_KEY." : `No profile named "${name}". Run \`coss login --profile ${name}\`.`);
419
+ return {
420
+ apiKey: profile.api_key,
421
+ source: "profile",
422
+ profileName: name,
423
+ profile,
424
+ config,
425
+ baseUrl: apiBaseUrl(io, profile),
426
+ dashboardUrl: dashboardBaseUrl(io, profile)
427
+ };
428
+ }
429
+ /** An SDK client for these credentials, on the CLI's `fetch` (never the SDK's env fallbacks). */
430
+ function clientFor(io, credentials, options = {}) {
431
+ return new Coss({
432
+ apiKey: credentials.apiKey,
433
+ baseUrl: credentials.baseUrl,
434
+ fetch: io.fetch,
435
+ timeout: options.timeout,
436
+ maxRetries: options.maxRetries
437
+ });
438
+ }
439
+ /** `Acme / Default / Development (sandbox)` */
440
+ function describeEnvironment(environment) {
441
+ return `${environment.organization.name} / ${environment.project.name} / ${environment.name} (${environment.mode})`;
442
+ }
443
+ //#endregion
444
+ //#region src/emails/simulate.ts
445
+ const SIMULATED_OUTCOMES = {
446
+ delivered: "success@simulator.amazonses.com",
447
+ bounced: "bounce@simulator.amazonses.com",
448
+ complained: "complaint@simulator.amazonses.com",
449
+ suppressed: "suppressionlist@simulator.amazonses.com"
450
+ };
451
+ function isSimulatedOutcome(value) {
452
+ return Object.hasOwn(SIMULATED_OUTCOMES, value);
453
+ }
454
+ //#endregion
455
+ //#region src/commands/emails.ts
456
+ const EMAILS_SEND_HELP = `Usage: coss emails send [options]
457
+
458
+ Sends a test email from the API key's environment. Sandbox keys (coss_test_…) never deliver: they
459
+ go through coss.com's simulated provider, with every event and webhook a real send has.
460
+
461
+ Options:
462
+ --to <address> Recipient (repeatable, or comma-separated)
463
+ --simulate <outcome> Send to the mailbox simulator: delivered, bounced, complained, suppressed
464
+ --from <address> Sender (default for sandbox keys: coss.com CLI <cli@example.com>; live keys
465
+ need an address on a verified domain)
466
+ --cc, --bcc, --reply-to <address>
467
+ --subject <text> Default: "Test email from the coss.com CLI"
468
+ --text <text>, --text-file <path>
469
+ --html <html>, --html-file <path>
470
+ --template <id|alias> Send a published template (instead of subject and body)
471
+ --var <name=value> A template variable (repeatable; values are JSON when they parse)
472
+ --category <name>
473
+ --tag <name=value> Repeatable
474
+ --wait Follow the email until every recipient's outcome is known, then show
475
+ its events
476
+ --timeout <seconds> How long --wait waits (default 60)
477
+ --json Print the email (and with --wait, its events) as JSON
478
+ `;
479
+ const SANDBOX_FROM = "coss.com CLI <cli@example.com>";
480
+ const DEFAULT_SUBJECT = "Test email from the coss.com CLI";
481
+ const DEFAULT_TEXT = "Sent with `coss emails send`. https://coss.com/docs/cli";
482
+ /** Recipient statuses after which nothing more is expected (unless waiting for a complaint). */
483
+ const SETTLED = /* @__PURE__ */ new Set([
484
+ "delivered",
485
+ "bounced",
486
+ "suppressed",
487
+ "complained",
488
+ "failed",
489
+ "canceled"
490
+ ]);
491
+ function pairs(values, flag) {
492
+ return values.map((pair) => {
493
+ const index = pair.indexOf("=");
494
+ if (index <= 0) throw new UsageError(`--${flag} takes name=value, got "${pair}".`);
495
+ return [pair.slice(0, index), pair.slice(index + 1)];
496
+ });
497
+ }
498
+ function variableValue(raw) {
499
+ try {
500
+ return JSON.parse(raw);
501
+ } catch {
502
+ return raw;
503
+ }
504
+ }
505
+ async function fileOrValue(value, file, flag) {
506
+ if (value !== void 0 && file !== void 0) throw new UsageError(`Pass --${flag} or --${flag}-file, not both.`);
507
+ if (file === void 0) return value;
508
+ try {
509
+ return await readFile(file, "utf8");
510
+ } catch (error) {
511
+ throw new CliError(`Couldn't read ${file}: ${error.message}`);
512
+ }
513
+ }
514
+ function settled(email, simulate) {
515
+ if (email.status === "failed" || email.status === "canceled") return true;
516
+ if (email.status === "queued" || email.status === "scheduled") return false;
517
+ return email.recipients.every((recipient) => simulate === "complained" && recipient.address === SIMULATED_OUTCOMES.complained ? recipient.status === "complained" : SETTLED.has(recipient.status));
518
+ }
519
+ async function waitForOutcome(context, coss, email, options) {
520
+ const { io, out } = context;
521
+ const deadline = io.now().getTime() + options.timeoutMs;
522
+ let current = email;
523
+ if (!out.json) out.info("Waiting for the outcome…");
524
+ while (!settled(current, options.simulate) && io.now().getTime() < deadline && !io.signal.aborted) {
525
+ await io.sleep(1e3, io.signal);
526
+ const { data, error } = await coss.email.get(current.id, { signal: io.signal });
527
+ if (error) {
528
+ if (io.signal.aborted) break;
529
+ throw apiError("Couldn't read the email", error);
530
+ }
531
+ current = data;
532
+ }
533
+ const { data, error } = await coss.email.listEvents(current.id);
534
+ if (error) throw apiError("Couldn't read the email's events", error);
535
+ return {
536
+ email: current,
537
+ events: data.data,
538
+ settled: settled(current, options.simulate)
539
+ };
540
+ }
541
+ function statusStyle(status) {
542
+ if (status === "delivered" || status === "sent") return "green";
543
+ if (status === "queued" || status === "scheduled" || status === "delivery_delayed") return "yellow";
544
+ return "red";
545
+ }
546
+ async function emailsSend(argv, io) {
547
+ const { values, global } = parseFlags(argv, {
548
+ to: {
549
+ type: "string",
550
+ multiple: true
551
+ },
552
+ cc: {
553
+ type: "string",
554
+ multiple: true
555
+ },
556
+ bcc: {
557
+ type: "string",
558
+ multiple: true
559
+ },
560
+ "reply-to": {
561
+ type: "string",
562
+ multiple: true
563
+ },
564
+ from: { type: "string" },
565
+ subject: { type: "string" },
566
+ text: { type: "string" },
567
+ "text-file": { type: "string" },
568
+ html: { type: "string" },
569
+ "html-file": { type: "string" },
570
+ template: { type: "string" },
571
+ var: {
572
+ type: "string",
573
+ multiple: true
574
+ },
575
+ category: { type: "string" },
576
+ tag: {
577
+ type: "string",
578
+ multiple: true
579
+ },
580
+ simulate: { type: "string" },
581
+ wait: { type: "boolean" },
582
+ timeout: { type: "string" }
583
+ });
584
+ const context = createContext(io, global);
585
+ const { out } = context;
586
+ if (global.help) {
587
+ out.line(EMAILS_SEND_HELP);
588
+ return 0;
589
+ }
590
+ const simulate = values.simulate;
591
+ if (simulate !== void 0 && !isSimulatedOutcome(simulate)) throw new UsageError(`--simulate takes ${Object.keys(SIMULATED_OUTCOMES).join(", ")}; got "${simulate}".`);
592
+ const to = [...addresses(values.to), ...simulate ? [SIMULATED_OUTCOMES[simulate]] : []];
593
+ if (to.length === 0) throw new UsageError("Pass --to <address> or --simulate <outcome>.");
594
+ const timeoutS = values.timeout === void 0 ? 60 : Number(values.timeout);
595
+ if (!Number.isFinite(timeoutS) || timeoutS <= 0) throw new UsageError("--timeout takes a number of seconds.");
596
+ const credentials = await resolveCredentials(context);
597
+ if (credentials.apiKey.startsWith("coss_live_") && !values.from) throw new UsageError("Live keys send from your own domain: pass --from you@your-domain.");
598
+ const base = {
599
+ from: values.from ?? SANDBOX_FROM,
600
+ to,
601
+ ...values.cc && { cc: addresses(values.cc) },
602
+ ...values.bcc && { bcc: addresses(values.bcc) },
603
+ ...values["reply-to"] && { reply_to: addresses(values["reply-to"]) },
604
+ ...values.category && { category: values.category },
605
+ ...values.tag && { tags: pairs(values.tag, "tag").map(([name, value]) => ({
606
+ name,
607
+ value
608
+ })) }
609
+ };
610
+ const text = await fileOrValue(values.text, values["text-file"], "text");
611
+ const html = await fileOrValue(values.html, values["html-file"], "html");
612
+ let params;
613
+ if (values.template) {
614
+ if (values.subject || text !== void 0 || html !== void 0) throw new UsageError("A template brings its own subject and body: drop --subject/--text/--html.");
615
+ params = {
616
+ ...base,
617
+ template_id: values.template,
618
+ ...values.var && { variables: Object.fromEntries(pairs(values.var, "var").map(([name, raw]) => [name, variableValue(raw)])) }
619
+ };
620
+ } else {
621
+ if (values.var) throw new UsageError("--var only applies with --template.");
622
+ params = {
623
+ ...base,
624
+ subject: values.subject ?? DEFAULT_SUBJECT,
625
+ ...html !== void 0 && { html },
626
+ ...text !== void 0 || html === void 0 ? { text: text ?? DEFAULT_TEXT } : {}
627
+ };
628
+ }
629
+ const coss = clientFor(io, credentials);
630
+ const { data: email, error } = await coss.email.send(params, { signal: io.signal });
631
+ if (error) throw apiError("Couldn't send the email", error);
632
+ if (!values.wait) {
633
+ if (out.json) out.data(email);
634
+ else {
635
+ out.line(`${out.style("green", "✔")} ${email.id} ${email.status} → ${to.join(", ")}${email.sandbox ? out.style("dim", " (sandbox)") : ""}`);
636
+ out.info(out.style("dim", "Add --wait to follow it, or run `coss logs tail` to watch every event."));
637
+ }
638
+ return 0;
639
+ }
640
+ const outcome = await waitForOutcome(context, coss, email, {
641
+ timeoutMs: timeoutS * 1e3,
642
+ simulate
643
+ });
644
+ if (out.json) out.data({
645
+ ...outcome.email,
646
+ events: outcome.events
647
+ });
648
+ else {
649
+ out.line(`${outcome.email.id} ${out.style(statusStyle(outcome.email.status), outcome.email.status)}`);
650
+ for (const recipient of outcome.email.recipients) out.line(` ${recipient.address} ${out.style(statusStyle(recipient.status), recipient.status)}`);
651
+ if (outcome.events.length > 0) out.line();
652
+ for (const event of outcome.events) out.line(` ${out.style("dim", event.occurred_at)} ${event.type}${event.recipient ? ` ${event.recipient}` : ""}`);
653
+ }
654
+ if (!outcome.settled && !io.signal.aborted) {
655
+ out.warn("Not every outcome arrived in time. Sends need the worker running (locally: `bun run dev`).");
656
+ return 1;
657
+ }
658
+ return io.signal.aborted ? 130 : 0;
659
+ }
660
+ //#endregion
661
+ //#region src/version.ts
662
+ /** The package version (`coss --version`, the forwarded requests' user agent). */
663
+ const VERSION = "0.1.1";
664
+ //#endregion
665
+ //#region src/listen/forward.ts
666
+ /** Posting an event to the local URL, as coss.com would post it to an endpoint. */
667
+ const FORWARD_TIMEOUT_MS = 1e4;
668
+ /**
669
+ * `localhost:3000/webhooks`, `:3000/webhooks` and `3000` all mean
670
+ * `http://localhost:3000/webhooks`; full `http(s)://` URLs are taken as they are.
671
+ */
672
+ function normalizeTarget(input) {
673
+ let value = input.trim();
674
+ if (/^\d+(\/|$)/.test(value)) value = `localhost:${value}`;
675
+ if (value.startsWith(":")) value = `localhost${value}`;
676
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) value = `http://${value}`;
677
+ let url;
678
+ try {
679
+ url = new URL(value);
680
+ } catch {
681
+ throw new UsageError(`--forward-to takes a URL like localhost:3000/webhooks; got "${input}".`);
682
+ }
683
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new UsageError("--forward-to takes an http:// or https:// URL.");
684
+ return url.toString();
685
+ }
686
+ /** `--header "Name: value"`. */
687
+ function parseHeader(input) {
688
+ const index = input.indexOf(":");
689
+ const name = index > 0 ? input.slice(0, index).trim() : "";
690
+ if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw new UsageError(`--header takes "Name: value"; got "${input}".`);
691
+ return [name, input.slice(index + 1).trim()];
692
+ }
693
+ function describe(error) {
694
+ const code = (error?.cause)?.code ?? error?.code;
695
+ if (code === "ECONNREFUSED" || code === "ConnectionRefused") return "connection refused";
696
+ if (code === "ENOTFOUND") return "host not found";
697
+ if (error?.name === "TimeoutError") return `no answer within ${FORWARD_TIMEOUT_MS / 1e3} s`;
698
+ if (error?.name === "AbortError") return "interrupted";
699
+ return error instanceof Error ? error.message : String(error);
700
+ }
701
+ async function forwardEvent(io, input) {
702
+ const timestamp = Math.floor(io.now().getTime() / 1e3);
703
+ const started = performance.now();
704
+ try {
705
+ const response = await io.fetch(input.url, {
706
+ method: "POST",
707
+ headers: [
708
+ ["content-type", "application/json"],
709
+ ["user-agent", `coss-cli/${VERSION} (coss listen)`],
710
+ ...input.headers,
711
+ ...Object.entries(signatureHeaders({
712
+ secret: input.secret,
713
+ id: input.eventId,
714
+ timestamp,
715
+ body: input.body
716
+ }))
717
+ ],
718
+ body: input.body,
719
+ redirect: "manual",
720
+ signal: AbortSignal.any([io.signal, AbortSignal.timeout(FORWARD_TIMEOUT_MS)])
721
+ });
722
+ await response.arrayBuffer().catch(() => void 0);
723
+ const durationMs = Math.round(performance.now() - started);
724
+ if (response.status < 100) return {
725
+ statusCode: null,
726
+ durationMs,
727
+ error: "redirected"
728
+ };
729
+ return {
730
+ statusCode: response.status,
731
+ durationMs,
732
+ error: null
733
+ };
734
+ } catch (error) {
735
+ return {
736
+ statusCode: null,
737
+ durationMs: Math.round(performance.now() - started),
738
+ error: describe(error)
739
+ };
740
+ }
741
+ }
742
+ //#endregion
743
+ //#region src/commands/listen.ts
744
+ const LISTEN_HELP = `Usage: coss listen [--forward-to <url>] [options]
745
+
746
+ Receives the environment's webhook events as they happen and forwards each one to a local URL,
747
+ signed like coss.com signs the requests it sends endpoints (verify them with the SDK's verifyWebhook
748
+ and the signing secret printed at start). Without --forward-to, events are only printed.
749
+
750
+ Options:
751
+ --forward-to <url> e.g. localhost:3000/webhooks
752
+ --events <types> Only these event types, e.g. email.delivered,email.bounced
753
+ --header <"Name: value"> An extra header on forwarded requests (repeatable)
754
+ --api-version <date> The API version events are rendered in (default: your organization's)
755
+ --print-json Print each event's body
756
+ --live Allow a live (production) key: you'd receive real events
757
+ --json One JSON object per forwarded event
758
+ `;
759
+ /** A poll waits this long for events; the SDK's timeout leaves room for the answer. */
760
+ const WAIT_MS = 2e4;
761
+ const CLIENT_TIMEOUT_MS = 35e3;
762
+ const POLL_LIMIT = 10;
763
+ const LIVE_ONLY_PREFIXES = ["account.", "billing."];
764
+ function ackOf({ delivery, result }) {
765
+ return {
766
+ delivery_id: delivery.id,
767
+ ack_token: delivery.ack_token,
768
+ status_code: result?.statusCode ?? null,
769
+ duration_ms: result?.durationMs ?? 0,
770
+ error: result?.error ?? null
771
+ };
772
+ }
773
+ function report(out, forwarded, printJson) {
774
+ const { delivery, result } = forwarded;
775
+ if (out.json) {
776
+ out.data({
777
+ event_id: delivery.event_id,
778
+ event_type: delivery.event_type,
779
+ attempt: delivery.attempt,
780
+ status_code: result?.statusCode ?? null,
781
+ duration_ms: result?.durationMs ?? null,
782
+ error: result?.error ?? null,
783
+ body: JSON.parse(delivery.body)
784
+ });
785
+ return;
786
+ }
787
+ const time = out.style("dim", new Date(delivery.created_at).toISOString().slice(11, 19));
788
+ const outcome = result === null ? "" : result.error ? ` ${out.style("red", `✖ ${result.error}`)}` : ` ${out.style(result.statusCode !== null && result.statusCode < 300 ? "green" : "red", `[${result.statusCode}]`)} ${out.style("dim", `${result.durationMs}ms`)}`;
789
+ const retry = delivery.attempt > 1 ? out.style("yellow", " (again)") : "";
790
+ out.line(`${time} ${out.style("cyan", delivery.event_type)} ${out.style("dim", delivery.event_id)}${outcome}${retry}`);
791
+ if (printJson) out.line(JSON.stringify(JSON.parse(delivery.body), null, 2));
792
+ }
793
+ /** The profile's signing secret, created (and saved) on first use. */
794
+ async function signingSecret(io, credentials) {
795
+ const saved = credentials.profile?.listen_secret;
796
+ if (isSecret(saved)) return saved;
797
+ const secret = generateSecret();
798
+ if (credentials.source === "profile") {
799
+ const config = await readConfig(io);
800
+ const profile = config.profiles[credentials.profileName];
801
+ if (profile) {
802
+ profile.listen_secret = secret;
803
+ await writeConfig(io, config);
804
+ }
805
+ }
806
+ return secret;
807
+ }
808
+ async function openListener(coss, params) {
809
+ const { data, error } = await coss.webhookListeners.create({
810
+ ...params.eventTypes.length > 0 && { event_types: params.eventTypes },
811
+ api_version: params.apiVersion,
812
+ description: params.description
813
+ });
814
+ if (error) throw apiError("Couldn't start listening", error);
815
+ return data;
816
+ }
817
+ async function run$1(context, values) {
818
+ const { io, out } = context;
819
+ const target = typeof values["forward-to"] === "string" ? normalizeTarget(values["forward-to"]) : null;
820
+ const headers = (values.header ?? []).map(parseHeader);
821
+ const eventTypes = list(values.events);
822
+ const credentials = await resolveCredentials(context);
823
+ const coss = clientFor(io, credentials, {
824
+ timeout: CLIENT_TIMEOUT_MS,
825
+ maxRetries: 0
826
+ });
827
+ const { data: environment, error } = await coss.environment.get();
828
+ if (error) throw apiError("Couldn't read the environment", error);
829
+ if (environment.mode === "live" && values.live !== true) throw new CliError(`${describeEnvironment(environment)} is a live environment: you would receive its real events. Pass --live to listen anyway, or sign in to a sandbox environment.`);
830
+ if (environment.mode === "sandbox" && eventTypes.some((type) => LIVE_ONLY_PREFIXES.some((prefix) => type.startsWith(prefix)))) out.warn("account.* and billing.* events only reach live environments: you won't see them here.");
831
+ const secret = await signingSecret(io, credentials);
832
+ const listenerParams = {
833
+ eventTypes,
834
+ apiVersion: typeof values["api-version"] === "string" ? values["api-version"] : environment.organization.api_version,
835
+ description: `${io.hostname() || hostname()} → ${target ?? "terminal"}`.slice(0, 256)
836
+ };
837
+ let listener = await openListener(coss, listenerParams);
838
+ out.info(`${out.style("green", "Ready!")} Listening to ${describeEnvironment(environment)}${target ? `, forwarding to ${target}` : ""}.`);
839
+ out.info(`Signing secret: ${out.style("bold", secret)} (API version ${listener.api_version})`);
840
+ out.info(out.style("dim", "Press Ctrl-C to stop."));
841
+ let pending = [];
842
+ let failures = 0;
843
+ try {
844
+ while (!io.signal.aborted) {
845
+ const { data, error } = await coss.webhookListeners.poll(listener.id, {
846
+ acks: pending,
847
+ wait_ms: WAIT_MS,
848
+ limit: POLL_LIMIT
849
+ }, { signal: io.signal });
850
+ if (error) {
851
+ if (io.signal.aborted) break;
852
+ if (error.type === "not_found_error") {
853
+ out.warn("The listener had expired; started a new one. Events in between were missed.");
854
+ listener = await openListener(coss, listenerParams);
855
+ pending = [];
856
+ continue;
857
+ }
858
+ if (!isTransient(error)) throw apiError("Listening stopped", error);
859
+ failures++;
860
+ if (failures === 1) out.warn(`Lost the connection (${error.message}); retrying…`);
861
+ await io.sleep(Math.min(1e3 * 2 ** failures, 3e4), io.signal);
862
+ continue;
863
+ }
864
+ if (failures > 0 && !out.json) out.info("Reconnected.");
865
+ failures = 0;
866
+ pending = [];
867
+ for (const delivery of data.deliveries) {
868
+ if (io.signal.aborted) break;
869
+ const forwarded = {
870
+ delivery,
871
+ result: target ? await forwardEvent(io, {
872
+ url: target,
873
+ secret,
874
+ eventId: delivery.event_id,
875
+ body: delivery.body,
876
+ headers
877
+ }) : null
878
+ };
879
+ report(out, forwarded, values["print-json"] === true);
880
+ pending.push(ackOf(forwarded));
881
+ }
882
+ }
883
+ } finally {
884
+ const cleanup = clientFor(io, credentials, {
885
+ timeout: 5e3,
886
+ maxRetries: 0
887
+ });
888
+ if (pending.length > 0) await cleanup.webhookListeners.poll(listener.id, {
889
+ acks: pending,
890
+ wait_ms: 0,
891
+ limit: 1
892
+ });
893
+ await cleanup.webhookListeners.delete(listener.id);
894
+ }
895
+ return 130;
896
+ }
897
+ async function listen(argv, io) {
898
+ const { values, global } = parseFlags(argv, {
899
+ "forward-to": {
900
+ type: "string",
901
+ short: "f"
902
+ },
903
+ events: {
904
+ type: "string",
905
+ multiple: true,
906
+ short: "e"
907
+ },
908
+ header: {
909
+ type: "string",
910
+ multiple: true,
911
+ short: "H"
912
+ },
913
+ "api-version": { type: "string" },
914
+ "print-json": { type: "boolean" },
915
+ live: { type: "boolean" }
916
+ });
917
+ const context = createContext(io, global);
918
+ if (global.help) {
919
+ context.out.line(LISTEN_HELP);
920
+ return 0;
921
+ }
922
+ if (values["api-version"] !== void 0 && !/^\d{4}-\d{2}-\d{2}$/.test(values["api-version"])) throw new UsageError("--api-version takes a date, e.g. 2026-10-01.");
923
+ return run$1(context, values);
924
+ }
925
+ //#endregion
926
+ //#region src/auth/loopback.ts
927
+ /**
928
+ * The one-shot local server the dashboard redirects to after approval (RFC 8252 loopback redirect):
929
+ * listens on 127.0.0.1 only, on a port the OS picks, and accepts one `/callback` with our `state`.
930
+ */
931
+ const PAGE = (title, text) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title><meta name="viewport" content="width=device-width, initial-scale=1"><style>body{font:16px system-ui,sans-serif;display:grid;place-items:center;min-height:90vh;margin:0;color:#111}main{max-width:28rem;padding:1.5rem}h1{font-size:1.25rem}p{color:#555}</style></head><body><main><h1>${title}</h1><p>${text}</p></main></body></html>`;
932
+ async function startLoopback() {
933
+ let deliver = null;
934
+ const server = createServer((request, response) => {
935
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
936
+ if (request.method !== "GET" || url.pathname !== "/callback") {
937
+ response.writeHead(404, { "content-type": "text/plain" }).end("Not found");
938
+ return;
939
+ }
940
+ const accepted = deliver?.(url.searchParams) ?? false;
941
+ const denied = url.searchParams.get("error") !== null;
942
+ response.writeHead(accepted ? 200 : 400, {
943
+ "content-type": "text/html; charset=utf-8",
944
+ "cache-control": "no-store",
945
+ "referrer-policy": "no-referrer"
946
+ }).end(!accepted ? PAGE("This sign-in doesn't match", "Run <code>coss login</code> again in your terminal.") : denied ? PAGE("Sign-in canceled", "Nothing was changed. You can close this tab.") : PAGE("Signed in to the coss.com CLI", "Return to your terminal. You can close this tab."));
947
+ });
948
+ await new Promise((resolve, reject) => {
949
+ server.once("error", reject);
950
+ server.listen(0, "127.0.0.1", () => resolve());
951
+ });
952
+ const { port } = server.address();
953
+ return {
954
+ port,
955
+ wait(state, { timeoutMs, signal }) {
956
+ return new Promise((resolve, reject) => {
957
+ const cleanup = () => {
958
+ clearTimeout(timer);
959
+ signal.removeEventListener("abort", onAbort);
960
+ deliver = null;
961
+ };
962
+ const onAbort = () => {
963
+ cleanup();
964
+ reject(/* @__PURE__ */ new Error("Interrupted."));
965
+ };
966
+ const timer = setTimeout(() => {
967
+ cleanup();
968
+ reject(/* @__PURE__ */ new Error("Timed out waiting for the browser."));
969
+ }, timeoutMs);
970
+ signal.addEventListener("abort", onAbort, { once: true });
971
+ if (signal.aborted) return onAbort();
972
+ deliver = (params) => {
973
+ if (params.get("state") !== state) return false;
974
+ const error = params.get("error");
975
+ const code = params.get("code");
976
+ if (!error && !code) return false;
977
+ cleanup();
978
+ resolve(error ? { error } : { code });
979
+ return true;
980
+ };
981
+ });
982
+ },
983
+ close: () => new Promise((resolve) => {
984
+ server.closeAllConnections();
985
+ server.close(() => resolve());
986
+ })
987
+ };
988
+ }
989
+ //#endregion
990
+ //#region src/auth/pkce.ts
991
+ /** PKCE (RFC 7636, S256) for `coss login`, and the verification code the dashboard shows too. */
992
+ function createVerifier() {
993
+ return randomBytes(32).toString("base64url");
994
+ }
995
+ function challengeFor(verifier) {
996
+ return createHash("sha256").update(verifier).digest("base64url");
997
+ }
998
+ function createState() {
999
+ return randomBytes(16).toString("base64url");
1000
+ }
1001
+ const ALPHABET = "ABCDEFGHJKMNPQRSTVWXYZ0123456789";
1002
+ /**
1003
+ * `XXXX-XXXX`, derived from the challenge exactly as the approval page derives it: the user checks
1004
+ * that both show the same code before approving.
1005
+ */
1006
+ function verificationCode(challenge) {
1007
+ const digest = createHash("sha256").update(`coss-cli-verification:${challenge}`).digest();
1008
+ let out = "";
1009
+ for (let i = 0; i < 8; i++) out += ALPHABET[(digest[i] ?? 0) % 32];
1010
+ return `${out.slice(0, 4)}-${out.slice(4)}`;
1011
+ }
1012
+ //#endregion
1013
+ //#region src/commands/login.ts
1014
+ const LOGIN_HELP = `Usage: coss login [--manual] [--no-browser] [--profile <name>]
1015
+
1016
+ Signs the CLI in. Opens the dashboard, where you pick the environment the CLI works in; the CLI
1017
+ gets a new API key of that environment (named after this machine), saved in your config.
1018
+
1019
+ Options:
1020
+ --manual Paste an existing API key instead (from the dashboard, or piped on stdin)
1021
+ --no-browser Don't open a browser: open the link yourself, then paste the code it shows
1022
+ (the default over SSH)
1023
+ --profile Save under this profile name (default: "default")
1024
+ `;
1025
+ /** How long the browser has to send the code back. */
1026
+ const CALLBACK_TIMEOUT_MS = 3e5;
1027
+ async function exchangeCode(io, dashboardUrl, input) {
1028
+ let response;
1029
+ try {
1030
+ response = await io.fetch(`${dashboardUrl}/api/cli/v1/token`, {
1031
+ method: "POST",
1032
+ headers: {
1033
+ "content-type": "application/json",
1034
+ accept: "application/json"
1035
+ },
1036
+ body: JSON.stringify({
1037
+ code: input.code,
1038
+ code_verifier: input.codeVerifier
1039
+ }),
1040
+ signal: AbortSignal.any([io.signal, AbortSignal.timeout(3e4)])
1041
+ });
1042
+ } catch (error) {
1043
+ throw new CliError(`Couldn't reach ${dashboardUrl}: ${error instanceof Error ? error.message : String(error)}`);
1044
+ }
1045
+ const body = await response.json().catch(() => null);
1046
+ if (!response.ok || !body || typeof body.api_key !== "string") throw new CliError(`Sign-in failed: ${body?.error?.message ?? `HTTP ${response.status}`}`);
1047
+ return body;
1048
+ }
1049
+ /** The browser flow: approval in the dashboard, a code back by loopback (or pasted), a new key. */
1050
+ async function browserLogin(context, dashboardUrl, options) {
1051
+ const { io, out } = context;
1052
+ const verifier = createVerifier();
1053
+ const challenge = challengeFor(verifier);
1054
+ const state = createState();
1055
+ const query = new URLSearchParams({
1056
+ code_challenge: challenge,
1057
+ state,
1058
+ host: io.hostname()
1059
+ });
1060
+ if (options.pasteCode) {
1061
+ query.set("mode", "code");
1062
+ const url = `${dashboardUrl}/app/authorize/cli?${query}`;
1063
+ out.info(`Open this link in a browser where you're signed in to coss.com:\n\n ${url}\n`);
1064
+ out.info(`Verification code: ${out.style("bold", verificationCode(challenge))}`);
1065
+ const code = await io.prompt("Paste the code it shows: ");
1066
+ if (!code) throw new CliError("No code entered.");
1067
+ return exchangeCode(io, dashboardUrl, {
1068
+ code,
1069
+ codeVerifier: verifier
1070
+ });
1071
+ }
1072
+ const loopback = await startLoopback();
1073
+ try {
1074
+ query.set("port", String(loopback.port));
1075
+ const url = `${dashboardUrl}/app/authorize/cli?${query}`;
1076
+ out.info(`Verification code: ${out.style("bold", verificationCode(challenge))}`);
1077
+ const opened = await io.openBrowser(url);
1078
+ out.info(opened ? `Opened the dashboard in your browser. If it didn't open, visit:\n\n ${url}\n` : `Open this link in your browser:\n\n ${url}\n`);
1079
+ out.info("Waiting for you to approve…");
1080
+ const result = await loopback.wait(state, {
1081
+ timeoutMs: CALLBACK_TIMEOUT_MS,
1082
+ signal: io.signal
1083
+ }).catch((error) => {
1084
+ throw new CliError(error instanceof Error ? error.message : String(error));
1085
+ });
1086
+ if ("error" in result) throw new CliError("Sign-in was canceled in the browser.");
1087
+ return exchangeCode(io, dashboardUrl, {
1088
+ code: result.code,
1089
+ codeVerifier: verifier
1090
+ });
1091
+ } finally {
1092
+ await loopback.close();
1093
+ }
1094
+ }
1095
+ async function environmentOf(coss) {
1096
+ const { data, error } = await coss.environment.get();
1097
+ if (error) throw apiError("Couldn't check the API key", error);
1098
+ return data;
1099
+ }
1100
+ async function login(argv, io) {
1101
+ const { values, global } = parseFlags(argv, {
1102
+ manual: { type: "boolean" },
1103
+ "no-browser": { type: "boolean" }
1104
+ });
1105
+ const context = createContext(io, global);
1106
+ const { out } = context;
1107
+ if (global.help) {
1108
+ out.line(LOGIN_HELP);
1109
+ return 0;
1110
+ }
1111
+ const config = await readConfig(io);
1112
+ const name = profileName(io, config, global.profile);
1113
+ const previous = config.profiles[name] ?? null;
1114
+ const baseUrl = apiBaseUrl(io, null);
1115
+ const dashboardUrl = dashboardBaseUrl(io, null);
1116
+ let apiKey;
1117
+ let login;
1118
+ if (values.manual) {
1119
+ apiKey = (await io.prompt("API key (coss_test_… or coss_live_…): ", { secret: true })).trim();
1120
+ if (!API_KEY_FORMAT.test(apiKey)) throw new CliError("That isn't a coss.com API key (coss_test_… or coss_live_…).");
1121
+ login = "manual";
1122
+ } else {
1123
+ const remote = Boolean(io.env.SSH_CONNECTION || io.env.SSH_TTY);
1124
+ apiKey = (await browserLogin(context, dashboardUrl, { pasteCode: values["no-browser"] === true || remote })).api_key;
1125
+ login = "browser";
1126
+ }
1127
+ const environment = await environmentOf(clientFor(io, {
1128
+ apiKey,
1129
+ baseUrl
1130
+ }));
1131
+ if (previous?.login === "browser" && previous.api_key !== apiKey) await clientFor(io, {
1132
+ apiKey: previous.api_key,
1133
+ baseUrl: savedApiBaseUrl(previous)
1134
+ }).apiKey.revoke().catch(() => void 0);
1135
+ config.profiles[name] = {
1136
+ api_key: apiKey,
1137
+ api_key_id: environment.api_key.id,
1138
+ login,
1139
+ ...baseUrl !== "https://api.coss.com" && { base_url: baseUrl },
1140
+ ...dashboardUrl !== "https://coss.com" && { dashboard_url: dashboardUrl },
1141
+ organization: environment.organization,
1142
+ project: environment.project,
1143
+ environment: {
1144
+ id: environment.id,
1145
+ name: environment.name,
1146
+ slug: environment.slug,
1147
+ mode: environment.mode
1148
+ },
1149
+ ...previous?.listen_secret && previous.environment?.id === environment.id && { listen_secret: previous.listen_secret },
1150
+ created_at: io.now().toISOString()
1151
+ };
1152
+ config.default_profile ??= name;
1153
+ await writeConfig(io, config);
1154
+ if (out.json) out.data({
1155
+ profile: name,
1156
+ environment
1157
+ });
1158
+ else {
1159
+ out.line(`${out.style("green", "✔")} Signed in to ${describeEnvironment(environment)}.`);
1160
+ out.line(` Key ${environment.api_key.name ?? environment.api_key.id} saved as profile "${name}" in ${configPath(io)}.`);
1161
+ }
1162
+ return 0;
1163
+ }
1164
+ //#endregion
1165
+ //#region src/commands/logout.ts
1166
+ const LOGOUT_HELP = `Usage: coss logout [--all] [--revoke] [--profile <name>]
1167
+
1168
+ Removes the saved API key. A key \`coss login\` created in the browser is also revoked; one you
1169
+ pasted with --manual is kept unless you pass --revoke.
1170
+
1171
+ Options:
1172
+ --all Every profile
1173
+ --revoke Revoke the key too, even one you pasted
1174
+ `;
1175
+ async function logout(argv, io) {
1176
+ const { values, global } = parseFlags(argv, {
1177
+ all: { type: "boolean" },
1178
+ revoke: { type: "boolean" }
1179
+ });
1180
+ const { out } = createContext(io, global);
1181
+ if (global.help) {
1182
+ out.line(LOGOUT_HELP);
1183
+ return 0;
1184
+ }
1185
+ const config = await readConfig(io);
1186
+ const names = values.all ? Object.keys(config.profiles) : [profileName(io, config, global.profile)];
1187
+ const removed = [];
1188
+ for (const name of names) {
1189
+ const profile = config.profiles[name];
1190
+ if (!profile) {
1191
+ if (!values.all) throw new CliError(`Not signed in${name === "default" ? "" : ` as "${name}"`}.`);
1192
+ continue;
1193
+ }
1194
+ let revoked = false;
1195
+ if (profile.login === "browser" || values.revoke) {
1196
+ const { error } = await clientFor(io, {
1197
+ apiKey: profile.api_key,
1198
+ baseUrl: savedApiBaseUrl(profile)
1199
+ }).apiKey.revoke();
1200
+ revoked = !error || error.type === "authentication_error";
1201
+ if (error && !revoked) out.warn(`Couldn't revoke the key of "${name}": ${error.message}. Revoke it in the dashboard.`);
1202
+ }
1203
+ delete config.profiles[name];
1204
+ if (config.default_profile === name) delete config.default_profile;
1205
+ removed.push({
1206
+ name,
1207
+ revoked
1208
+ });
1209
+ }
1210
+ await writeConfig(io, config);
1211
+ if (out.json) out.data({ removed });
1212
+ else if (removed.length === 0) out.line("No saved profiles.");
1213
+ else for (const { name, revoked } of removed) out.line(`${out.style("green", "✔")} Signed out of "${name}"${revoked ? " (key revoked)" : ""}.`);
1214
+ return 0;
1215
+ }
1216
+ //#endregion
1217
+ //#region src/logs/format.ts
1218
+ const LEVEL_STYLE = {
1219
+ info: "dim",
1220
+ warning: "yellow",
1221
+ error: "red"
1222
+ };
1223
+ function time(iso) {
1224
+ const date = new Date(iso);
1225
+ return Number.isNaN(date.getTime()) ? iso : date.toISOString().slice(11, 23);
1226
+ }
1227
+ /** One line per log line: time, level, type and its message (requests: method, path, status). */
1228
+ function formatLog(out, line) {
1229
+ const level = out.style(LEVEL_STYLE[line.level], line.level.padEnd(7));
1230
+ const type = out.style("cyan", line.type);
1231
+ const status = line.status_code === null ? "" : ` ${out.style(line.status_code >= 500 ? "red" : line.status_code >= 400 ? "yellow" : "green", String(line.status_code))}`;
1232
+ const summary = line.source === "api" && line.method && line.path ? `${line.method} ${line.path}${status}${line.duration_ms === null ? "" : out.style("dim", ` ${line.duration_ms}ms`)}` : line.message;
1233
+ return `${out.style("dim", time(line.occurred_at))} ${level} ${type} ${summary}`;
1234
+ }
1235
+ //#endregion
1236
+ //#region src/logs/tail.ts
1237
+ /** How far before the newest line seen each poll looks again. */
1238
+ const OVERLAP_MS = 6e4;
1239
+ const MAX_SEEN = 5e3;
1240
+ function byTime(a, b) {
1241
+ return a.occurred_at < b.occurred_at ? -1 : a.occurred_at > b.occurred_at ? 1 : a.id < b.id ? -1 : 1;
1242
+ }
1243
+ var LogTail = class {
1244
+ #seen = /* @__PURE__ */ new Set();
1245
+ #newest;
1246
+ constructor(start) {
1247
+ this.#newest = start.getTime();
1248
+ }
1249
+ /** Where the next read starts. */
1250
+ windowStart() {
1251
+ return /* @__PURE__ */ new Date(this.#newest - OVERLAP_MS);
1252
+ }
1253
+ /** The lines not seen before, oldest first; remembers them. */
1254
+ take(lines) {
1255
+ const fresh = lines.filter((line) => !this.#seen.has(line.id)).sort(byTime);
1256
+ for (const line of fresh) {
1257
+ this.#seen.add(line.id);
1258
+ this.#newest = Math.max(this.#newest, Date.parse(line.occurred_at));
1259
+ }
1260
+ for (const id of this.#seen) {
1261
+ if (this.#seen.size <= MAX_SEEN) break;
1262
+ this.#seen.delete(id);
1263
+ }
1264
+ return fresh;
1265
+ }
1266
+ };
1267
+ /**
1268
+ * Every line from `from` on (newest first, paged with `after`). The whole window is read, even
1269
+ * past pages already printed: a late line older than them sorts onto a later page. `truncated`
1270
+ * when the window had more than `MAX_PAGES` pages.
1271
+ */
1272
+ async function readWindow(coss, filters, from, signal) {
1273
+ const lines = [];
1274
+ let after;
1275
+ for (let page = 0; page < 10; page++) {
1276
+ const { data, error } = await coss.logs.list({
1277
+ ...filters,
1278
+ from,
1279
+ limit: 100,
1280
+ ...after && { after }
1281
+ }, { signal });
1282
+ if (error) return {
1283
+ lines,
1284
+ truncated: false,
1285
+ error
1286
+ };
1287
+ lines.push(...data.data);
1288
+ const last = data.data.at(-1);
1289
+ if (!data.has_more || !last) return {
1290
+ lines,
1291
+ truncated: false,
1292
+ error: null
1293
+ };
1294
+ after = last.id;
1295
+ }
1296
+ return {
1297
+ lines,
1298
+ truncated: true,
1299
+ error: null
1300
+ };
1301
+ }
1302
+ const UNITS = {
1303
+ s: 1e3,
1304
+ m: 6e4,
1305
+ h: 36e5,
1306
+ d: 864e5
1307
+ };
1308
+ /** `--since`: `30s`, `15m`, `2h`, `1d`, or an ISO 8601 time. `null` when unreadable. */
1309
+ function parseSince(value, now) {
1310
+ const match = /^(\d+)\s*([smhd])$/.exec(value.trim());
1311
+ if (match) return new Date(now.getTime() - Number(match[1]) * (UNITS[match[2] ?? "s"] ?? 1e3));
1312
+ const time = Date.parse(value);
1313
+ return Number.isNaN(time) ? null : new Date(time);
1314
+ }
1315
+ //#endregion
1316
+ //#region src/commands/logs.ts
1317
+ const LOGS_TAIL_HELP = `Usage: coss logs tail [options]
1318
+
1319
+ Follows the environment's log: API requests made with its keys, email events, webhook attempts and
1320
+ events \`coss listen\` forwarded. New lines only, unless --since.
1321
+
1322
+ Options:
1323
+ --source <name> api, email, webhook, risk, smtp (repeatable, or comma-separated)
1324
+ --level <level> info, warning, error
1325
+ --type <type> e.g. email.bounced, api.request
1326
+ --status <code> API or webhook status codes or classes, e.g. 4xx,503
1327
+ -q, --query <text> Free text: messages, paths, ids, recipients
1328
+ --since <time> Start with earlier lines too: 30s, 15m, 2h, 1d or an ISO 8601 time
1329
+ --interval <ms> How often to poll (default 2000)
1330
+ --json One log object per line
1331
+ `;
1332
+ const SOURCES = [
1333
+ "api",
1334
+ "email",
1335
+ "webhook",
1336
+ "risk",
1337
+ "smtp"
1338
+ ];
1339
+ const LEVELS = [
1340
+ "info",
1341
+ "warning",
1342
+ "error"
1343
+ ];
1344
+ const MAX_RANGE_MS = 26784e5;
1345
+ function checked(values, allowed, flag) {
1346
+ for (const value of values) if (!allowed.includes(value)) throw new UsageError(`--${flag} takes ${allowed.join(", ")}; got "${value}".`);
1347
+ return values;
1348
+ }
1349
+ async function logsTail(argv, io) {
1350
+ const { values, global } = parseFlags(argv, {
1351
+ source: {
1352
+ type: "string",
1353
+ multiple: true
1354
+ },
1355
+ level: {
1356
+ type: "string",
1357
+ multiple: true
1358
+ },
1359
+ type: {
1360
+ type: "string",
1361
+ multiple: true
1362
+ },
1363
+ status: {
1364
+ type: "string",
1365
+ multiple: true
1366
+ },
1367
+ query: {
1368
+ type: "string",
1369
+ short: "q"
1370
+ },
1371
+ since: { type: "string" },
1372
+ interval: { type: "string" }
1373
+ });
1374
+ const context = createContext(io, global);
1375
+ const { out } = context;
1376
+ if (global.help) {
1377
+ out.line(LOGS_TAIL_HELP);
1378
+ return 0;
1379
+ }
1380
+ const sources = checked(list(values.source), SOURCES, "source");
1381
+ const levels = checked(list(values.level), LEVELS, "level");
1382
+ const filters = {
1383
+ ...sources.length > 0 && { source: sources },
1384
+ ...levels.length > 0 && { level: levels },
1385
+ ...values.type && { type: list(values.type) },
1386
+ ...values.status && { status: list(values.status) },
1387
+ ...values.query && { q: values.query }
1388
+ };
1389
+ const intervalMs = values.interval === void 0 ? 2e3 : Number(values.interval);
1390
+ if (!Number.isInteger(intervalMs) || intervalMs < 500) throw new UsageError("--interval takes milliseconds, at least 500.");
1391
+ const now = io.now();
1392
+ let since = null;
1393
+ if (values.since !== void 0) {
1394
+ since = parseSince(values.since, now);
1395
+ if (!since || now.getTime() - since.getTime() > MAX_RANGE_MS) throw new UsageError("--since takes 30s, 15m, 2h, 1d or an ISO time within the last 31 days.");
1396
+ }
1397
+ const coss = clientFor(io, await resolveCredentials(context));
1398
+ const { data: environment, error } = await coss.environment.get({ signal: io.signal });
1399
+ if (error) throw apiError("Couldn't read the environment", error);
1400
+ if (!out.json) out.info(`Tailing the log of ${describeEnvironment(environment)}. Press Ctrl-C to stop.`);
1401
+ const started = io.now();
1402
+ const tail = new LogTail(since ?? started);
1403
+ let first = true;
1404
+ let warnedTruncated = false;
1405
+ let failures = 0;
1406
+ while (!io.signal.aborted) {
1407
+ const overlap = tail.windowStart();
1408
+ const window = await readWindow(coss, filters, since && since > overlap ? since : overlap, io.signal);
1409
+ if (window.error) {
1410
+ if (io.signal.aborted) break;
1411
+ if (!isTransient(window.error)) throw apiError("Couldn't read the log", window.error);
1412
+ failures++;
1413
+ if (failures === 1) out.warn(`Couldn't read the log (${window.error.message}); retrying…`);
1414
+ await io.sleep(Math.min(intervalMs * 2 ** failures, 3e4), io.signal);
1415
+ continue;
1416
+ }
1417
+ failures = 0;
1418
+ const fresh = tail.take(window.lines);
1419
+ for (const line of fresh) {
1420
+ if (first && !since && Date.parse(line.occurred_at) < started.getTime()) continue;
1421
+ if (out.json) out.data(line);
1422
+ else out.line(formatLog(out, line));
1423
+ }
1424
+ if (window.truncated && !warnedTruncated) {
1425
+ warnedTruncated = true;
1426
+ out.warn("This environment logs more than the tail can follow: some lines were skipped. Filter with --source, --type or -q.");
1427
+ }
1428
+ first = false;
1429
+ await io.sleep(intervalMs, io.signal);
1430
+ }
1431
+ return 130;
1432
+ }
1433
+ //#endregion
1434
+ //#region src/commands/whoami.ts
1435
+ const WHOAMI_HELP = `Usage: coss whoami [--json] [--profile <name>]
1436
+
1437
+ Shows the API key the CLI uses, where it comes from, and its environment.
1438
+ `;
1439
+ async function whoami(argv, io) {
1440
+ const { global } = parseFlags(argv, {});
1441
+ const context = createContext(io, global);
1442
+ const { out } = context;
1443
+ if (global.help) {
1444
+ out.line(WHOAMI_HELP);
1445
+ return 0;
1446
+ }
1447
+ const credentials = await resolveCredentials(context);
1448
+ const { data, error } = await clientFor(io, credentials).environment.get();
1449
+ if (error) throw apiError("Couldn't check the API key", error);
1450
+ const source = credentials.source === "env" ? "COSS_API_KEY" : `profile "${credentials.profileName}"`;
1451
+ if (out.json) {
1452
+ out.data({
1453
+ source,
1454
+ base_url: credentials.baseUrl,
1455
+ environment: data
1456
+ });
1457
+ return 0;
1458
+ }
1459
+ out.line(describeEnvironment(data));
1460
+ out.line(` Key ${data.api_key.name ?? "(unnamed)"} ${out.style("dim", data.api_key.id)}`);
1461
+ out.line(` From ${source}`);
1462
+ out.line(` API ${credentials.baseUrl}`);
1463
+ out.line(` Version ${data.organization.api_version}`);
1464
+ if (credentials.source === "profile" && await configIsShared(io)) out.warn("Your config file is readable by other users: run `chmod 600` on it.");
1465
+ return 0;
1466
+ }
1467
+ //#endregion
1468
+ //#region src/run.ts
1469
+ const HELP = `coss ${VERSION}: the coss.com command line
1470
+
1471
+ Usage: coss <command> [options]
1472
+
1473
+ Commands:
1474
+ login Sign in (in the browser, or --manual with an API key)
1475
+ logout Sign out (revokes the key login created)
1476
+ whoami Show the API key in use and its environment
1477
+ emails send Send a test email (--simulate bounced, --wait…)
1478
+ logs tail Follow the environment's log
1479
+ listen Forward the environment's webhook events to a local URL
1480
+
1481
+ Global options:
1482
+ --profile <name> Use a saved profile other than the default (or set COSS_PROFILE)
1483
+ --json Machine-readable output
1484
+ --no-color No colors (also NO_COLOR)
1485
+ -h, --help Help for a command
1486
+ -v, --version The CLI's version
1487
+
1488
+ Environment: COSS_API_KEY (use this key instead of a saved one), COSS_BASE_URL (another API,
1489
+ e.g. http://localhost:3001), COSS_DASHBOARD_URL (another dashboard, for login).
1490
+ Docs: https://coss.com/docs/cli
1491
+ `;
1492
+ const COMMANDS = {
1493
+ login,
1494
+ logout,
1495
+ whoami,
1496
+ emails: { send: emailsSend },
1497
+ logs: { tail: logsTail },
1498
+ listen
1499
+ };
1500
+ /** Runs one invocation (`argv` without node and the script) and returns the exit code. */
1501
+ async function run(argv, io) {
1502
+ const out = new Output(io, {
1503
+ json: argv.includes("--json"),
1504
+ color: !argv.includes("--no-color")
1505
+ });
1506
+ const [name, ...rest] = argv;
1507
+ if (name === void 0 || name === "help" || name === "--help" || name === "-h") {
1508
+ out.line(HELP);
1509
+ return 0;
1510
+ }
1511
+ if (name === "--version" || name === "-v" || name === "version") {
1512
+ out.line(VERSION);
1513
+ return 0;
1514
+ }
1515
+ const entry = COMMANDS[name];
1516
+ let command;
1517
+ let args = rest;
1518
+ if (typeof entry === "function") command = entry;
1519
+ else if (entry) {
1520
+ const [sub, ...subRest] = rest;
1521
+ command = sub ? entry[sub] : void 0;
1522
+ args = subRest;
1523
+ if (!command) {
1524
+ out.error(`${sub ? `Unknown command "${name} ${sub}"` : `"${name}" needs a command`}: try ${Object.keys(entry).map((key) => `\`coss ${name} ${key}\``).join(", ")}.`);
1525
+ return 2;
1526
+ }
1527
+ }
1528
+ if (!command) {
1529
+ out.error(`Unknown command "${name}". Run \`coss --help\` to see the commands.`);
1530
+ return 2;
1531
+ }
1532
+ try {
1533
+ return await command(args, io);
1534
+ } catch (error) {
1535
+ if (error instanceof CliError) {
1536
+ out.error(error.message);
1537
+ return error.exitCode;
1538
+ }
1539
+ out.error(`Unexpected error: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
1540
+ return 1;
1541
+ }
1542
+ }
1543
+ //#endregion
1544
+ export { sign as a, nodeIo as c, generateSecret as i, run as n, signatureHeaders as o, VERSION as r, defaultConfigDir as s, HELP as t };