coss-cli 0.2.0 → 0.4.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 +7 -5
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{run-BurjNVF6.js → run-glpZgvyK.js} +584 -53
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# coss-cli
|
|
2
2
|
|
|
3
|
-
The command line for [coss.com](https://coss.com): sign in, send test emails, follow
|
|
4
|
-
log, and receive its webhook events on your machine.
|
|
3
|
+
The command line for [coss.com](https://coss.com): sign in, send test emails and text messages, follow
|
|
4
|
+
your environment's log, and receive its webhook events on your machine.
|
|
5
5
|
|
|
6
6
|
```sh
|
|
7
7
|
npm install -g coss-cli # or: npx coss-cli <command>
|
|
@@ -27,8 +27,8 @@ curl -fsSL https://raw.githubusercontent.com/cosscom/coss/main/packages/cli/inst
|
|
|
27
27
|
|
|
28
28
|
`install.sh` picks the archive for the machine, checks it against `SHA256SUMS` and installs `coss`
|
|
29
29
|
into `~/.local/bin` (`COSS_INSTALL_DIR`; `COSS_VERSION` for another version). The musl builds need
|
|
30
|
-
`libstdc++` (`apk add libstdc++` on Alpine). macOS executables are
|
|
31
|
-
one downloaded with a browser
|
|
30
|
+
`libstdc++` (`apk add libstdc++` on Alpine). macOS executables are signed with coss.com's Developer
|
|
31
|
+
ID and notarized by Apple (since 0.3.0), so one downloaded with a browser runs without a warning.
|
|
32
32
|
|
|
33
33
|
## Commands
|
|
34
34
|
|
|
@@ -39,19 +39,21 @@ one downloaded with a browser needs `xattr -d com.apple.quarantine coss`.
|
|
|
39
39
|
| `coss whoami` | The key in use, where it comes from, and its organization, project and environment. |
|
|
40
40
|
| `coss profiles list` | The saved profiles: each one's environment, whether `coss login` created its key or it was pasted, and which is the default. |
|
|
41
41
|
| `coss use <profile>` | Makes a saved profile the default. |
|
|
42
|
-
| `coss init` | Sets the project in the current directory up: installs `coss` with its package manager (`--no-install` doesn't) and writes a new development key, approved in the dashboard and named after the project, to `.env.local` (Next.js) or `.env` (`--env-file` picks another). A key already there is kept unless `--force`. |
|
|
42
|
+
| `coss init` | Sets the project in the current directory up: installs `coss` with its package manager (`--no-install` doesn't) and writes a new development key, approved in the dashboard and named after the project, to `.env.local` (Next.js) or `.env` (`--env-file` picks another). A key already there is kept unless `--force`. It adds notes on coss.com for coding agents to the project's `AGENTS.md` (`--no-agents` skips them) and prints the one next step for the key. |
|
|
43
43
|
| `coss open [page]` | Opens the environment's page in the dashboard: `overview`, `emails`, `logs`, `webhooks`, `api-keys`, `domains`, `billing`, … (`--print` prints the URL). |
|
|
44
44
|
| `coss emails send` | A test email: `--to`, or `--simulate delivered\|bounced\|complained\|suppressed` for the mailbox simulator; `--template` with `--var name=value`; `--wait` follows it to its outcome (up to `--timeout`, 60 s). |
|
|
45
45
|
| `coss emails list` | The environment's emails, newest first, with where each stands. Filter with `--to`, `--status`, `--recipient-status`, `-q`, `--category`, `--batch`, `--since`/`--until`; `--limit` (20). |
|
|
46
46
|
| `coss emails get <id>` | An email: sender, recipients and their statuses, failure, tracking, attachments; `--text` or `--html` prints a body alone. |
|
|
47
47
|
| `coss emails events <id>` | Its delivery events, with the receiving server's answers. |
|
|
48
48
|
| `coss emails diagnose <id>` | Whether it was delivered and, if not, why and what to do (or `--to <address>` for the newest email to it). |
|
|
49
|
+
| `coss sms send` | A test text message: `--to +14155550123`, or `--simulate delivered\|invalid\|filtered\|opted-out\|reply` for the SMS simulator (sandbox keys); `--from` (default for sandbox keys `+14155550100`; live keys need one of your registered numbers), `--body`; `--wait` follows it to its outcome (and shows the simulator's reply). |
|
|
49
50
|
| `coss logs tail` | New lines of the environment's log as they arrive: API requests, email events, webhook attempts. Filter with `--source`, `--level`, `--type`, `--status`, `-q`; `--since 15m` starts earlier; `--interval` sets the poll interval (2000 ms). |
|
|
50
51
|
| `coss inbox` | The environment's inbound domain, then each email it receives as it arrives (`--since`, `--interval`). |
|
|
51
52
|
| `coss inbox get <id>` | A received email: verdicts, attachments and its text (`--html`, `--headers`); `--raw > message.eml` saves the message as received. |
|
|
52
53
|
| `coss listen` | Receives the environment's webhook events and forwards each one to `--forward-to`, signed like coss.com signs real deliveries. Verify them with `verifyWebhook` from the `coss` SDK and the signing secret it prints (it stays the same for the profile). `--header "Name: value"` adds a header to forwarded requests. |
|
|
53
54
|
| `coss trigger <event-type>` | A test event of that type, sent to the environment's subscribed endpoints and `coss listen` listeners like a real one (sandbox keys; every type but `domain.*`, `account.*`, `billing.*`). `--data '{…}'` and `-F name=value` (dotted names, JSON values) change its `data`. |
|
|
54
55
|
| `coss webhooks list` | The environment's webhook endpoints: URL, state and event types. |
|
|
56
|
+
| `coss webhooks add <url>` | Creates an endpoint and writes its signing secret to the project env file as `COSS_WEBHOOK_SECRET` (`--events`, `--description`, `--force`). |
|
|
55
57
|
| `coss webhooks deliveries <endpoint>` | An endpoint's deliveries, newest first (`--status failed`, `--event <id>`, `--limit`). |
|
|
56
58
|
| `coss webhooks retry <endpoint> <delivery>` | Sends a finished delivery to its endpoint once more. |
|
|
57
59
|
| `coss hooks apps list`, `coss hooks apps create <name>` | [Hooks](https://coss.com/docs/hooks) applications (`--uid`, `--metadata`). Every `<app>` below is an application's id or uid. |
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { c as flushOutput, l as nodeIo, n as run } from "./run-
|
|
2
|
+
import { c as flushOutput, l as nodeIo, n as run } from "./run-glpZgvyK.js";
|
|
3
3
|
//#region src/cli.ts
|
|
4
4
|
process.exitCode = await run(process.argv.slice(2), nodeIo());
|
|
5
5
|
await flushOutput();
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { u as CURSOR_FIELDS, t as HELP, r as VERSION, s as defaultConfigDir, i as generateSecret, l as nodeIo, n as run, a as sign, o as signatureHeaders } from "./run-
|
|
1
|
+
export { u as CURSOR_FIELDS, t as HELP, r as VERSION, s as defaultConfigDir, i as generateSecret, l as nodeIo, n as run, a as sign, o as signatureHeaders } from "./run-glpZgvyK.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { access, chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
2
|
-
import { API_VERSION, Coss, TEST_WEBHOOK_EVENT_TYPES, isLiveOnlyEventType } from "coss";
|
|
2
|
+
import { API_VERSION, Coss, SIMULATOR_TO, TEST_WEBHOOK_EVENT_TYPES, WEBHOOK_EVENT_TYPES, fetchSetupReport, isLiveOnlyEventType } from "coss";
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
4
|
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
5
5
|
import { spawn } from "node:child_process";
|
|
@@ -43,7 +43,7 @@ function isTransient(error) {
|
|
|
43
43
|
function apiError(doing, error) {
|
|
44
44
|
const details = [error.message, ...(error.issues ?? []).map((issue) => ` ${issue.path}: ${issue.message}`)].join("\n");
|
|
45
45
|
const request = error.request_id ? ` (request ${error.request_id})` : "";
|
|
46
|
-
const hint = HINTS[error.type];
|
|
46
|
+
const hint = error.code === "insufficient_permissions" ? "This API key is restricted: `coss whoami` lists what it may do. Use a key with that permission." : HINTS[error.type];
|
|
47
47
|
return new CliError(`${doing}: ${details}${request}${hint ? `\n${hint}` : ""}`);
|
|
48
48
|
}
|
|
49
49
|
function configPath(io) {
|
|
@@ -437,7 +437,7 @@ function shorten(text, max) {
|
|
|
437
437
|
function minute(iso) {
|
|
438
438
|
return iso ? iso.slice(0, 16).replace("T", " ") : "";
|
|
439
439
|
}
|
|
440
|
-
function statusStyle$
|
|
440
|
+
function statusStyle$4(status) {
|
|
441
441
|
if (status === "delivered" || status === "sent" || status === "received") return "green";
|
|
442
442
|
if (status === "queued" || status === "scheduled" || status === "delivery_delayed" || status === "in_progress") return "yellow";
|
|
443
443
|
if (status === "canceled") return "dim";
|
|
@@ -1469,11 +1469,11 @@ function isSimulatedOutcome(value) {
|
|
|
1469
1469
|
}
|
|
1470
1470
|
//#endregion
|
|
1471
1471
|
//#region src/commands/emails.ts
|
|
1472
|
-
const SANDBOX_FROM = "coss.com CLI <cli@example.com>";
|
|
1472
|
+
const SANDBOX_FROM$1 = "coss.com CLI <cli@example.com>";
|
|
1473
1473
|
const DEFAULT_SUBJECT = "Test email from the coss.com CLI";
|
|
1474
1474
|
const DEFAULT_TEXT = "Sent with `coss emails send`. https://coss.com/docs/cli";
|
|
1475
1475
|
/** Recipient statuses after which nothing more is expected (unless waiting for a complaint). */
|
|
1476
|
-
const SETTLED = /* @__PURE__ */ new Set([
|
|
1476
|
+
const SETTLED$1 = /* @__PURE__ */ new Set([
|
|
1477
1477
|
"delivered",
|
|
1478
1478
|
"bounced",
|
|
1479
1479
|
"suppressed",
|
|
@@ -1490,17 +1490,17 @@ async function fileOrValue(value, file, flag) {
|
|
|
1490
1490
|
throw new CliError(`Couldn't read ${file}: ${error.message}`);
|
|
1491
1491
|
}
|
|
1492
1492
|
}
|
|
1493
|
-
function settled(email, simulate) {
|
|
1493
|
+
function settled$1(email, simulate) {
|
|
1494
1494
|
if (email.status === "failed" || email.status === "canceled") return true;
|
|
1495
1495
|
if (email.status === "queued" || email.status === "scheduled") return false;
|
|
1496
|
-
return email.recipients.every((recipient) => simulate === "complained" && recipient.address === SIMULATED_OUTCOMES.complained ? recipient.status === "complained" : SETTLED.has(recipient.status));
|
|
1496
|
+
return email.recipients.every((recipient) => simulate === "complained" && recipient.address === SIMULATED_OUTCOMES.complained ? recipient.status === "complained" : SETTLED$1.has(recipient.status));
|
|
1497
1497
|
}
|
|
1498
|
-
async function waitForOutcome(context, coss, email, options) {
|
|
1498
|
+
async function waitForOutcome$1(context, coss, email, options) {
|
|
1499
1499
|
const { io, out } = context;
|
|
1500
1500
|
const deadline = io.now().getTime() + options.timeoutMs;
|
|
1501
1501
|
let current = email;
|
|
1502
1502
|
if (!out.json) out.info("Waiting for the outcome…");
|
|
1503
|
-
while (!settled(current, options.simulate) && io.now().getTime() < deadline && !io.signal.aborted) {
|
|
1503
|
+
while (!settled$1(current, options.simulate) && io.now().getTime() < deadline && !io.signal.aborted) {
|
|
1504
1504
|
await io.sleep(1e3, io.signal);
|
|
1505
1505
|
const { data, error } = await coss.email.get(current.id, { signal: io.signal });
|
|
1506
1506
|
if (error) {
|
|
@@ -1514,10 +1514,10 @@ async function waitForOutcome(context, coss, email, options) {
|
|
|
1514
1514
|
return {
|
|
1515
1515
|
email: current,
|
|
1516
1516
|
events: data.data,
|
|
1517
|
-
settled: settled(current, options.simulate)
|
|
1517
|
+
settled: settled$1(current, options.simulate)
|
|
1518
1518
|
};
|
|
1519
1519
|
}
|
|
1520
|
-
function statusStyle$
|
|
1520
|
+
function statusStyle$3(status) {
|
|
1521
1521
|
if (status === "delivered" || status === "sent") return "green";
|
|
1522
1522
|
if (status === "queued" || status === "scheduled" || status === "delivery_delayed") return "yellow";
|
|
1523
1523
|
return "red";
|
|
@@ -1636,7 +1636,7 @@ async function emailsSend({ values, context }) {
|
|
|
1636
1636
|
const credentials = await resolveCredentials(context);
|
|
1637
1637
|
if (credentials.apiKey.startsWith("coss_live_") && !values.from) throw new UsageError("Live keys send from your own domain: pass --from you@your-domain.");
|
|
1638
1638
|
const base = {
|
|
1639
|
-
from: values.from ?? SANDBOX_FROM,
|
|
1639
|
+
from: values.from ?? SANDBOX_FROM$1,
|
|
1640
1640
|
to,
|
|
1641
1641
|
...values.cc && { cc: addresses(values.cc) },
|
|
1642
1642
|
...values.bcc && { bcc: addresses(values.bcc) },
|
|
@@ -1677,7 +1677,7 @@ async function emailsSend({ values, context }) {
|
|
|
1677
1677
|
}
|
|
1678
1678
|
return 0;
|
|
1679
1679
|
}
|
|
1680
|
-
const outcome = await waitForOutcome(context, coss, email, {
|
|
1680
|
+
const outcome = await waitForOutcome$1(context, coss, email, {
|
|
1681
1681
|
timeoutMs: timeoutS * 1e3,
|
|
1682
1682
|
simulate
|
|
1683
1683
|
});
|
|
@@ -1686,8 +1686,8 @@ async function emailsSend({ values, context }) {
|
|
|
1686
1686
|
events: outcome.events
|
|
1687
1687
|
});
|
|
1688
1688
|
else {
|
|
1689
|
-
out.line(`${outcome.email.id} ${out.style(statusStyle$
|
|
1690
|
-
for (const recipient of outcome.email.recipients) out.line(` ${recipient.address} ${out.style(statusStyle$
|
|
1689
|
+
out.line(`${outcome.email.id} ${out.style(statusStyle$3(outcome.email.status), outcome.email.status)}`);
|
|
1690
|
+
for (const recipient of outcome.email.recipients) out.line(` ${recipient.address} ${out.style(statusStyle$3(recipient.status), recipient.status)}`);
|
|
1691
1691
|
if (outcome.events.length > 0) out.line();
|
|
1692
1692
|
for (const event of outcome.events) out.line(` ${out.style("dim", event.occurred_at)} ${event.type}${event.recipient ? ` ${event.recipient}` : ""}`);
|
|
1693
1693
|
}
|
|
@@ -1979,7 +1979,7 @@ async function emailsGet({ values, positionals, context }) {
|
|
|
1979
1979
|
}
|
|
1980
1980
|
function printEmail(out, email) {
|
|
1981
1981
|
const status = deliveryStatus(email);
|
|
1982
|
-
out.line(`${out.style("bold", email.id)} ${out.style(statusStyle$
|
|
1982
|
+
out.line(`${out.style("bold", email.id)} ${out.style(statusStyle$4(status), status)}${email.sandbox ? out.style("dim", " (sandbox)") : ""}`);
|
|
1983
1983
|
field$1(out, "From", email.from);
|
|
1984
1984
|
field$1(out, "Subject", email.subject);
|
|
1985
1985
|
field$1(out, "Reply-To", email.reply_to.join(", "));
|
|
@@ -1991,7 +1991,7 @@ function printEmail(out, email) {
|
|
|
1991
1991
|
field$1(out, "Sent", email.sent_at);
|
|
1992
1992
|
if (email.failure) out.line(` ${out.style("dim", "Failure".padEnd(11))}${out.style("red", email.failure.code)}: ${printable(email.failure.message)}`);
|
|
1993
1993
|
out.line();
|
|
1994
|
-
for (const recipient of email.recipients) out.line(` ${recipient.type.padEnd(4)}${printable(recipient.address)} ${out.style(statusStyle$
|
|
1994
|
+
for (const recipient of email.recipients) out.line(` ${recipient.type.padEnd(4)}${printable(recipient.address)} ${out.style(statusStyle$4(recipient.status), recipient.status)}`);
|
|
1995
1995
|
const tracking = email.tracking;
|
|
1996
1996
|
if (tracking.opens || tracking.clicks) {
|
|
1997
1997
|
out.line();
|
|
@@ -2108,7 +2108,7 @@ async function emailsDiagnose({ values, positionals, context }) {
|
|
|
2108
2108
|
}
|
|
2109
2109
|
for (const recipient of diagnosis.recipients) {
|
|
2110
2110
|
out.line();
|
|
2111
|
-
out.line(` ${printable(recipient.address)} ${out.style(statusStyle$
|
|
2111
|
+
out.line(` ${printable(recipient.address)} ${out.style(statusStyle$4(recipient.outcome), recipient.outcome)}`);
|
|
2112
2112
|
out.line(` ${recipient.explanation}`);
|
|
2113
2113
|
if (recipient.details) details(out, recipient.details);
|
|
2114
2114
|
steps(out, recipient.next_steps, " ");
|
|
@@ -2172,7 +2172,7 @@ function pairs(values, flag) {
|
|
|
2172
2172
|
return [pair.slice(0, index), pair.slice(index + 1)];
|
|
2173
2173
|
}));
|
|
2174
2174
|
}
|
|
2175
|
-
function statusStyle$
|
|
2175
|
+
function statusStyle$2(status) {
|
|
2176
2176
|
return status === "succeeded" ? "green" : status === "pending" ? "yellow" : "red";
|
|
2177
2177
|
}
|
|
2178
2178
|
const appsList = defineCommand({
|
|
@@ -2585,7 +2585,7 @@ const HOOKS_COMMANDS = [
|
|
|
2585
2585
|
],
|
|
2586
2586
|
row: (delivery) => [
|
|
2587
2587
|
delivery.id,
|
|
2588
|
-
out.style(statusStyle$
|
|
2588
|
+
out.style(statusStyle$2(delivery.status), delivery.status),
|
|
2589
2589
|
String(delivery.attempt_count),
|
|
2590
2590
|
delivery.last_error ?? (delivery.last_status_code === null ? "" : String(delivery.last_status_code)),
|
|
2591
2591
|
delivery.endpoint_id,
|
|
@@ -2617,7 +2617,7 @@ const HOOKS_COMMANDS = [
|
|
|
2617
2617
|
const { out } = context;
|
|
2618
2618
|
if (!out.json) {
|
|
2619
2619
|
const next = delivery.data.next_attempt_at ? `, next attempt ${when$1(delivery.data.next_attempt_at)}` : "";
|
|
2620
|
-
out.line(`${delivery.data.id} ${out.style(statusStyle$
|
|
2620
|
+
out.line(`${delivery.data.id} ${out.style(statusStyle$2(delivery.data.status), delivery.data.status)} → ${delivery.data.endpoint_id}${out.style("dim", `${next}`)}`);
|
|
2621
2621
|
}
|
|
2622
2622
|
printList(out, list.data, {
|
|
2623
2623
|
headings: [
|
|
@@ -2926,6 +2926,133 @@ async function inboxGet({ values, positionals, context }) {
|
|
|
2926
2926
|
return 0;
|
|
2927
2927
|
}
|
|
2928
2928
|
//#endregion
|
|
2929
|
+
//#region src/env-file.ts
|
|
2930
|
+
/**
|
|
2931
|
+
* The project's env file: where `coss init` writes `COSS_API_KEY` and `coss listen` writes
|
|
2932
|
+
* `COSS_WEBHOOK_SECRET`. One file holds both, so a handler and the CLI share them.
|
|
2933
|
+
*/
|
|
2934
|
+
/** The env file with `name=value` set: an existing line replaced, else one appended. */
|
|
2935
|
+
function setEnvVar(text, name, value) {
|
|
2936
|
+
const line = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=.*$`, "m");
|
|
2937
|
+
if (line.test(text)) return text.replace(line, () => `${name}=${value}`);
|
|
2938
|
+
return `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}${name}=${value}\n`;
|
|
2939
|
+
}
|
|
2940
|
+
/** `text` without `name`'s assignments. */
|
|
2941
|
+
function removeEnvVar(text, name) {
|
|
2942
|
+
return text.replace(new RegExp(`^[ \\t]*(?:export[ \\t]+)?${name}[ \\t]*=.*(?:\\r?\\n|$)`, "gm"), "");
|
|
2943
|
+
}
|
|
2944
|
+
/** The value of `name` in an env file, without surrounding quotes. Empty when it is absent. */
|
|
2945
|
+
function readEnvValue(text, name) {
|
|
2946
|
+
return new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=\\s*["']?([^"'\\s#]*)`, "m").exec(text)?.[1] ?? "";
|
|
2947
|
+
}
|
|
2948
|
+
async function readOptional$2(path) {
|
|
2949
|
+
try {
|
|
2950
|
+
return await readFile(path, "utf8");
|
|
2951
|
+
} catch {
|
|
2952
|
+
return null;
|
|
2953
|
+
}
|
|
2954
|
+
}
|
|
2955
|
+
function holdsCredential(text) {
|
|
2956
|
+
return readEnvValue(text, "COSS_API_KEY") !== "" || readEnvValue(text, "COSS_WEBHOOK_SECRET") !== "";
|
|
2957
|
+
}
|
|
2958
|
+
async function isNextProject(dir) {
|
|
2959
|
+
const text = await readOptional$2(join(dir, "package.json"));
|
|
2960
|
+
if (!text) return false;
|
|
2961
|
+
try {
|
|
2962
|
+
const pkg = JSON.parse(text);
|
|
2963
|
+
return Boolean(pkg.dependencies?.next ?? pkg.devDependencies?.next);
|
|
2964
|
+
} catch {
|
|
2965
|
+
return false;
|
|
2966
|
+
}
|
|
2967
|
+
}
|
|
2968
|
+
/**
|
|
2969
|
+
* The env file that already holds `COSS_API_KEY` or `COSS_WEBHOOK_SECRET` (`.env.local` before
|
|
2970
|
+
* `.env`, walking up from `dir`), else the file `coss init` would create: `.env.local` in a
|
|
2971
|
+
* Next.js project, `.env` otherwise.
|
|
2972
|
+
*/
|
|
2973
|
+
async function projectEnvFile(dir) {
|
|
2974
|
+
let current = resolve(dir);
|
|
2975
|
+
for (;;) {
|
|
2976
|
+
for (const name of [".env.local", ".env"]) {
|
|
2977
|
+
const path = join(current, name);
|
|
2978
|
+
const text = await readOptional$2(path);
|
|
2979
|
+
if (text !== null && holdsCredential(text)) return {
|
|
2980
|
+
path,
|
|
2981
|
+
text
|
|
2982
|
+
};
|
|
2983
|
+
}
|
|
2984
|
+
const parent = dirname(current);
|
|
2985
|
+
if (parent === current) break;
|
|
2986
|
+
current = parent;
|
|
2987
|
+
}
|
|
2988
|
+
const root = resolve(dir);
|
|
2989
|
+
const path = join(root, await isNextProject(root) ? ".env.local" : ".env");
|
|
2990
|
+
return {
|
|
2991
|
+
path,
|
|
2992
|
+
text: await readOptional$2(path)
|
|
2993
|
+
};
|
|
2994
|
+
}
|
|
2995
|
+
/** Writes `name=value` into the file. Returns whether the file changed. A new file is mode 0600. */
|
|
2996
|
+
async function writeEnvValue(file, name, value) {
|
|
2997
|
+
const next = setEnvVar(file.text ?? "", name, value);
|
|
2998
|
+
if (next === (file.text ?? "")) return false;
|
|
2999
|
+
await mkdir(dirname(file.path), { recursive: true });
|
|
3000
|
+
await writeFile(file.path, next, file.text === null ? { mode: 384 } : void 0);
|
|
3001
|
+
file.text = next;
|
|
3002
|
+
return true;
|
|
3003
|
+
}
|
|
3004
|
+
//#endregion
|
|
3005
|
+
//#region src/project-stack.ts
|
|
3006
|
+
/**
|
|
3007
|
+
* What `coss init` can see of the project, so its closing message points at the drop-in that
|
|
3008
|
+
* project already uses. Detection only reads files; it never installs anything.
|
|
3009
|
+
*/
|
|
3010
|
+
async function exists$2(path) {
|
|
3011
|
+
return access(path).then(() => true, () => false);
|
|
3012
|
+
}
|
|
3013
|
+
async function readOptional$1(path) {
|
|
3014
|
+
try {
|
|
3015
|
+
return await readFile(path, "utf8");
|
|
3016
|
+
} catch {
|
|
3017
|
+
return null;
|
|
3018
|
+
}
|
|
3019
|
+
}
|
|
3020
|
+
function dependsOn$1(pkg, name) {
|
|
3021
|
+
return Boolean(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);
|
|
3022
|
+
}
|
|
3023
|
+
async function detectDriver(dir) {
|
|
3024
|
+
if ((await readOptional$1(join(dir, "composer.json")))?.includes("\"laravel/framework\"")) return {
|
|
3025
|
+
kind: "laravel",
|
|
3026
|
+
install: "composer require coss/laravel"
|
|
3027
|
+
};
|
|
3028
|
+
const gemfile = await readOptional$1(join(dir, "Gemfile"));
|
|
3029
|
+
if (gemfile && /^\s*gem\s+["']rails["']/m.test(gemfile)) return {
|
|
3030
|
+
kind: "rails",
|
|
3031
|
+
install: "bundle add coss-rails"
|
|
3032
|
+
};
|
|
3033
|
+
const manage = await readOptional$1(join(dir, "manage.py"));
|
|
3034
|
+
const pyproject = await readOptional$1(join(dir, "pyproject.toml"));
|
|
3035
|
+
const requirements = await readOptional$1(join(dir, "requirements.txt"));
|
|
3036
|
+
if (!((manage?.includes("django") ?? false) || /\bdjango\b/i.test(pyproject ?? "") || /\bdjango\b/i.test(requirements ?? ""))) return null;
|
|
3037
|
+
return {
|
|
3038
|
+
kind: "django",
|
|
3039
|
+
install: await exists$2(join(dir, "uv.lock")) || (pyproject?.includes("[tool.uv]") ?? false) ? "uv add coss-django" : "pip install coss-django"
|
|
3040
|
+
};
|
|
3041
|
+
}
|
|
3042
|
+
/** The mail library or framework driver in `dir`, if one is there. */
|
|
3043
|
+
async function detectProjectStack(dir, pkg) {
|
|
3044
|
+
let integration = null;
|
|
3045
|
+
if (pkg && dependsOn$1(pkg, "nodemailer")) integration = "nodemailer";
|
|
3046
|
+
else if (pkg && dependsOn$1(pkg, "better-auth")) integration = "better-auth";
|
|
3047
|
+
else if (pkg && (dependsOn$1(pkg, "next-auth") || dependsOn$1(pkg, "@auth/core"))) integration = "authjs";
|
|
3048
|
+
return {
|
|
3049
|
+
next: pkg !== null && dependsOn$1(pkg, "next"),
|
|
3050
|
+
javascript: pkg !== null,
|
|
3051
|
+
integration,
|
|
3052
|
+
driver: await detectDriver(dir)
|
|
3053
|
+
};
|
|
3054
|
+
}
|
|
3055
|
+
//#endregion
|
|
2929
3056
|
//#region src/auth/loopback.ts
|
|
2930
3057
|
/**
|
|
2931
3058
|
* The one-shot local server the dashboard redirects to after approval (RFC 8252 loopback redirect):
|
|
@@ -3217,15 +3344,56 @@ function dependsOn(pkg, name) {
|
|
|
3217
3344
|
return Boolean(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);
|
|
3218
3345
|
}
|
|
3219
3346
|
const KEY_LINE = /^\s*(?:export\s+)?COSS_API_KEY\s*=\s*["']?([^"'\s#]*)/m;
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
|
|
3347
|
+
const NOTES_BEGIN = "<!-- BEGIN:coss -->";
|
|
3348
|
+
const NOTES_END = "<!-- END:coss -->";
|
|
3349
|
+
/**
|
|
3350
|
+
* What a coding agent working in the project should know about coss.com, for its AGENTS.md
|
|
3351
|
+
* (on by default; `--no-agents` skips them). Keep it in step with the brief that opens
|
|
3352
|
+
* https://coss.com/llms.txt (apps/site/src/lib/llms.ts).
|
|
3353
|
+
*/
|
|
3354
|
+
function agentNotes(envFile) {
|
|
3355
|
+
return `${NOTES_BEGIN}
|
|
3356
|
+
## coss.com
|
|
3357
|
+
|
|
3358
|
+
This project uses [coss.com](https://coss.com) (email, SMS, webhooks) through its SDK.
|
|
3359
|
+
|
|
3360
|
+
- Docs: https://coss.com/llms.txt lists every page, and every docs page is Markdown at its URL plus
|
|
3361
|
+
\`.md\` (e.g. https://coss.com/docs/email/sending.md). API reference pages give each operation's
|
|
3362
|
+
parameters, request body, responses and errors. Read the page before writing code against it.
|
|
3363
|
+
- Develop and test with the development key (\`coss_test_…\`) in \`${envFile}\` as \`COSS_API_KEY\`:
|
|
3364
|
+
every API works and records what it would do, with events and webhooks, but nothing is
|
|
3365
|
+
delivered. A \`coss_live_…\` key there delivers for real: don't test with it, and never switch
|
|
3366
|
+
to one to try something (\`npx coss-cli init --force\` replaces it with a development key).
|
|
3367
|
+
- SDK methods return \`{ data, error }\` and don't throw for API failures: always check \`error\`
|
|
3368
|
+
(and \`error.hint\`, which names the fix). Webhook handlers verify each request with
|
|
3369
|
+
\`verifyWebhook\`, which throws on a bad signature. \`npx coss-cli listen\` writes
|
|
3370
|
+
\`COSS_WEBHOOK_SECRET\` into \`${envFile}\` for that check. \`npx coss-cli webhooks add <url>\`
|
|
3371
|
+
creates an endpoint and writes that same variable (replacing a listen secret, so both sign
|
|
3372
|
+
the same way).
|
|
3373
|
+
- Commands use \`COSS_API_KEY\` from the environment. \`npx coss-cli listen --forward-to
|
|
3374
|
+
localhost:3000/<path>\` forwards webhook events to a local handler, \`npx coss-cli trigger
|
|
3375
|
+
<event type>\` sends a test event, and \`npx coss-cli logs tail\` follows the API requests and
|
|
3376
|
+
events. Send tests to \`bounce@simulator.amazonses.com\` and run \`npx coss-cli emails diagnose <id>\`.
|
|
3377
|
+
${NOTES_END}
|
|
3378
|
+
`;
|
|
3225
3379
|
}
|
|
3226
|
-
/** `text`
|
|
3227
|
-
function
|
|
3228
|
-
|
|
3380
|
+
/** `text` with the coss.com notes: an earlier copy replaced, else appended. */
|
|
3381
|
+
function setAgentNotes(text, notes) {
|
|
3382
|
+
const begin = text.indexOf(NOTES_BEGIN);
|
|
3383
|
+
const end = text.indexOf(NOTES_END, begin);
|
|
3384
|
+
if (begin !== -1 && end !== -1) {
|
|
3385
|
+
const after = text.slice(end + 17).replace(/^\r?\n/, "");
|
|
3386
|
+
return `${text.slice(0, begin)}${notes}${after}`;
|
|
3387
|
+
}
|
|
3388
|
+
if (text.trim() === "") return notes;
|
|
3389
|
+
return `${text.replace(/\s*$/, "")}\n\n${notes}`;
|
|
3390
|
+
}
|
|
3391
|
+
/** The project's agent instructions: AGENTS.md, else an existing CLAUDE.md, else a new AGENTS.md. */
|
|
3392
|
+
async function agentsFile(dir) {
|
|
3393
|
+
const agents = join(dir, "AGENTS.md");
|
|
3394
|
+
if (await exists$1(agents)) return agents;
|
|
3395
|
+
const claude = join(dir, "CLAUDE.md");
|
|
3396
|
+
return await exists$1(claude) ? claude : agents;
|
|
3229
3397
|
}
|
|
3230
3398
|
/** The project's name for the key: package.json's (without its scope), else the directory's. */
|
|
3231
3399
|
function projectName(dir, pkg) {
|
|
@@ -3234,7 +3402,7 @@ function projectName(dir, pkg) {
|
|
|
3234
3402
|
const initCommand = defineCommand({
|
|
3235
3403
|
name: "init",
|
|
3236
3404
|
summary: "Set this project up: the SDK and a development API key",
|
|
3237
|
-
description: "Sets up the project in the current directory: installs the coss package with the project's package manager, and writes a new development (sandbox) API key to its env file as COSS_API_KEY, created in the dashboard like `coss login`'s and named after the project. It is the project's key, not the CLI's: `coss login` signs the CLI in.\n\nAn env file that already has a key keeps it, unless --force.",
|
|
3405
|
+
description: "Sets up the project in the current directory: installs the coss package with the project's package manager, and writes a new development (sandbox) API key to its env file as COSS_API_KEY, created in the dashboard like `coss login`'s and named after the project. It is the project's key, not the CLI's: `coss login` signs the CLI in.\n\nAn env file that already has a key keeps it, unless --force. It also adds a short section on coss.com (docs, the development key, testing) to the project's AGENTS.md, or its CLAUDE.md when it has no AGENTS.md; running it again updates that section. --no-agents skips the notes.",
|
|
3238
3406
|
flags: {
|
|
3239
3407
|
"env-file": {
|
|
3240
3408
|
type: "string",
|
|
@@ -3249,6 +3417,14 @@ const initCommand = defineCommand({
|
|
|
3249
3417
|
type: "boolean",
|
|
3250
3418
|
description: "Replace a COSS_API_KEY the env file already has"
|
|
3251
3419
|
},
|
|
3420
|
+
agents: {
|
|
3421
|
+
type: "boolean",
|
|
3422
|
+
description: "Add notes for coding agents (the default; --no-agents skips them)"
|
|
3423
|
+
},
|
|
3424
|
+
"no-agents": {
|
|
3425
|
+
type: "boolean",
|
|
3426
|
+
description: "Don't add notes for coding agents to AGENTS.md"
|
|
3427
|
+
},
|
|
3252
3428
|
"no-browser": {
|
|
3253
3429
|
type: "boolean",
|
|
3254
3430
|
description: "Don't open a browser: open the link yourself, then paste the code it shows"
|
|
@@ -3269,13 +3445,16 @@ async function init({ values, context }) {
|
|
|
3269
3445
|
const shownFile = relative(dir, envFile) || envFile;
|
|
3270
3446
|
const existingText = await readFile(envFile, "utf8").catch(() => null);
|
|
3271
3447
|
const existingKey = existingText ? KEY_LINE.exec(existingText)?.[1] ?? "" : "";
|
|
3448
|
+
let apiKey = existingKey;
|
|
3272
3449
|
const config = await readConfig(io);
|
|
3273
3450
|
const profile = config.profiles[profileName(io, config, flags.profile)] ?? null;
|
|
3274
3451
|
const baseUrl = apiBaseUrl(io, profile);
|
|
3275
3452
|
const dashboardUrl = dashboardBaseUrl(io, profile);
|
|
3276
3453
|
let key = null;
|
|
3277
|
-
if (existingKey && !values.force)
|
|
3278
|
-
|
|
3454
|
+
if (existingKey && !values.force) {
|
|
3455
|
+
out.info(`${shownFile} already has COSS_API_KEY: kept it (--force replaces it).`);
|
|
3456
|
+
if (existingKey.startsWith("coss_live_")) out.warn(`${shownFile}'s COSS_API_KEY is a live key: what you send with it is delivered. \`coss init --force\` replaces it with a development key.`);
|
|
3457
|
+
} else {
|
|
3279
3458
|
const token = await browserLogin(context, dashboardUrl, {
|
|
3280
3459
|
pasteCode: values["no-browser"] === true || isRemote(io),
|
|
3281
3460
|
project: projectName(dir, pkg)
|
|
@@ -3290,6 +3469,7 @@ async function init({ values, context }) {
|
|
|
3290
3469
|
await coss.apiKey.revoke().catch(() => void 0);
|
|
3291
3470
|
throw new CliError(`${describeEnvironment(environment)} is live, so its key was revoked: \`coss init\` only writes development keys. Pick a sandbox environment.`);
|
|
3292
3471
|
}
|
|
3472
|
+
apiKey = token.api_key;
|
|
3293
3473
|
const withKey = setEnvVar(existingText ?? "", "COSS_API_KEY", token.api_key);
|
|
3294
3474
|
const text = baseUrl === "https://api.coss.com" ? removeEnvVar(withKey, "COSS_BASE_URL") : setEnvVar(withKey, "COSS_BASE_URL", baseUrl);
|
|
3295
3475
|
await mkdir(dirname(envFile), { recursive: true });
|
|
@@ -3315,35 +3495,83 @@ async function init({ values, context }) {
|
|
|
3315
3495
|
if (code !== 0) throw new CliError(code === null ? `Couldn't run ${command}: install the coss package yourself.` : `\`${installed}\` failed (exit code ${code}): install the coss package yourself.`);
|
|
3316
3496
|
if (!out.json) out.line(`${out.style("green", "✔")} Installed the coss package.`);
|
|
3317
3497
|
}
|
|
3498
|
+
let notesFile = null;
|
|
3499
|
+
if (values["no-agents"] !== true) {
|
|
3500
|
+
notesFile = await agentsFile(dir);
|
|
3501
|
+
const before = await readFile(notesFile, "utf8").catch(() => "");
|
|
3502
|
+
await writeFile(notesFile, setAgentNotes(before, agentNotes(shownFile)));
|
|
3503
|
+
if (!out.json) out.line(`${out.style("green", "✔")} ${before.includes(NOTES_BEGIN) ? "Updated" : "Added"} the coss.com notes for coding agents in ${relative(dir, notesFile)}.`);
|
|
3504
|
+
}
|
|
3505
|
+
const setup = await fetchSetupReport(clientFor(io, {
|
|
3506
|
+
apiKey,
|
|
3507
|
+
baseUrl
|
|
3508
|
+
}));
|
|
3509
|
+
const stack = await detectProjectStack(dir, pkg);
|
|
3510
|
+
if (setup.warning) out.warn(setup.warning);
|
|
3318
3511
|
if (out.json) {
|
|
3319
3512
|
out.data({
|
|
3320
3513
|
env_file: envFile,
|
|
3321
3514
|
key,
|
|
3322
3515
|
installed,
|
|
3323
|
-
ignored_by_git: ignored
|
|
3516
|
+
ignored_by_git: ignored,
|
|
3517
|
+
agents_file: notesFile,
|
|
3518
|
+
setup
|
|
3324
3519
|
});
|
|
3325
3520
|
return 0;
|
|
3326
3521
|
}
|
|
3327
|
-
out.line(
|
|
3328
|
-
|
|
3329
|
-
|
|
3330
|
-
|
|
3522
|
+
out.line(closingMessage({
|
|
3523
|
+
stack,
|
|
3524
|
+
shownFile,
|
|
3525
|
+
setup
|
|
3526
|
+
}));
|
|
3527
|
+
return 0;
|
|
3528
|
+
}
|
|
3529
|
+
function sdkSnippetText(from, to) {
|
|
3530
|
+
return ` import { Coss } from "coss";
|
|
3331
3531
|
|
|
3332
3532
|
const coss = new Coss(); // reads COSS_API_KEY
|
|
3333
3533
|
const { data, error } = await coss.email.send({
|
|
3334
|
-
from:
|
|
3335
|
-
to:
|
|
3534
|
+
from: ${JSON.stringify(from)},
|
|
3535
|
+
to: ${JSON.stringify(to)},
|
|
3536
|
+
subject: "Hello from coss.com",
|
|
3537
|
+
text: "It works!",
|
|
3538
|
+
});`;
|
|
3539
|
+
}
|
|
3540
|
+
function nodemailerSnippet(from, to) {
|
|
3541
|
+
return ` import { cossTransport } from "coss/nodemailer";
|
|
3542
|
+
import nodemailer from "nodemailer";
|
|
3543
|
+
|
|
3544
|
+
const transport = nodemailer.createTransport(cossTransport());
|
|
3545
|
+
await transport.sendMail({
|
|
3546
|
+
from: ${JSON.stringify(from)},
|
|
3547
|
+
to: ${JSON.stringify(to)},
|
|
3336
3548
|
subject: "Hello from coss.com",
|
|
3337
3549
|
text: "It works!",
|
|
3338
|
-
})
|
|
3550
|
+
});`;
|
|
3551
|
+
}
|
|
3552
|
+
function sdkSnippet(isNext, shownFile, from, to) {
|
|
3553
|
+
return `Send an email from your server code${isNext ? " (a route handler or server action)" : ""}:
|
|
3339
3554
|
|
|
3340
|
-
|
|
3555
|
+
${sdkSnippetText(from, to)}
|
|
3341
3556
|
|
|
3342
|
-
|
|
3557
|
+
Development keys never deliver email, but every send has its events and webhooks.${isNext ? "" : `\nLoad ${shownFile} in your app, e.g. node --env-file=${shownFile} server.js.`}`;
|
|
3558
|
+
}
|
|
3559
|
+
/** The closing message: the drop-in this project already uses, then the one next step. */
|
|
3560
|
+
function closingMessage(options) {
|
|
3561
|
+
const { stack, shownFile, setup } = options;
|
|
3562
|
+
const from = setup.from ?? "hello@example.com";
|
|
3563
|
+
const parts = [];
|
|
3564
|
+
if (stack.driver) parts.push(`Install the ${stack.driver.kind} driver yourself:\n\n ${stack.driver.install}`);
|
|
3565
|
+
if (stack.integration === "nodemailer") parts.push(`Send with Nodemailer:\n\n${nodemailerSnippet(from, SIMULATOR_TO)}`);
|
|
3566
|
+
else if (stack.integration === "better-auth") parts.push("Send Better Auth's emails with `coss/better-auth` (https://coss.com/docs/integrations.md).");
|
|
3567
|
+
else if (stack.integration === "authjs") parts.push("Send Auth.js emails with `coss/authjs` (https://coss.com/docs/integrations.md).");
|
|
3568
|
+
else if (stack.javascript || !stack.driver) parts.push(sdkSnippet(stack.next, shownFile, from, SIMULATOR_TO));
|
|
3569
|
+
parts.push(setup.next);
|
|
3570
|
+
parts.push(`Next:
|
|
3343
3571
|
coss listen --forward-to localhost:3000/webhooks receive webhook events locally
|
|
3344
3572
|
coss logs tail follow the environment's log
|
|
3345
3573
|
https://coss.com/docs guides and the API reference`);
|
|
3346
|
-
return
|
|
3574
|
+
return `\n${parts.join("\n\n")}`;
|
|
3347
3575
|
}
|
|
3348
3576
|
/** Whether git ignores the file: `null` outside a repository (or without git). */
|
|
3349
3577
|
async function ignoredByGit(io, dir, file) {
|
|
@@ -3360,7 +3588,7 @@ async function ignoredByGit(io, dir, file) {
|
|
|
3360
3588
|
//#endregion
|
|
3361
3589
|
//#region src/version.ts
|
|
3362
3590
|
/** The package version (`coss --version`, the forwarded requests' user agent). */
|
|
3363
|
-
const VERSION = "0.
|
|
3591
|
+
const VERSION = "0.4.0";
|
|
3364
3592
|
//#endregion
|
|
3365
3593
|
//#region src/listen/forward.ts
|
|
3366
3594
|
/** Posting an event to the local URL, as coss.com would post it to an endpoint. */
|
|
@@ -3475,12 +3703,18 @@ function report(out, forwarded, printJson) {
|
|
|
3475
3703
|
out.line(`${time} ${out.style("cyan", delivery.event_type)} ${out.style("dim", delivery.event_id)}${outcome}${retry}`);
|
|
3476
3704
|
if (printJson) out.line(toJson(JSON.parse(delivery.body), 2));
|
|
3477
3705
|
}
|
|
3478
|
-
/**
|
|
3706
|
+
/**
|
|
3707
|
+
* The signing secret for this project. An existing `COSS_WEBHOOK_SECRET` in the env file wins, so
|
|
3708
|
+
* a handler's secret is not rotated; otherwise the profile's `listen_secret`, otherwise a new one.
|
|
3709
|
+
* It is written to the env file, and to the profile when the CLI key came from the profile.
|
|
3710
|
+
*/
|
|
3479
3711
|
async function signingSecret(io, credentials) {
|
|
3480
|
-
const
|
|
3481
|
-
|
|
3482
|
-
const
|
|
3483
|
-
|
|
3712
|
+
const file = await projectEnvFile(io.cwd);
|
|
3713
|
+
const existing = file.text ? readEnvValue(file.text, "COSS_WEBHOOK_SECRET") : "";
|
|
3714
|
+
const fromProfile = credentials.profile?.listen_secret;
|
|
3715
|
+
const secret = isSecret(existing) ? existing : isSecret(fromProfile) ? fromProfile : generateSecret();
|
|
3716
|
+
const wrote = await writeEnvValue(file, "COSS_WEBHOOK_SECRET", secret);
|
|
3717
|
+
if (credentials.source === "profile" && credentials.profile?.listen_secret !== secret) {
|
|
3484
3718
|
const config = await readConfig(io);
|
|
3485
3719
|
const profile = config.profiles[credentials.profileName];
|
|
3486
3720
|
if (profile) {
|
|
@@ -3488,7 +3722,11 @@ async function signingSecret(io, credentials) {
|
|
|
3488
3722
|
await writeConfig(io, config);
|
|
3489
3723
|
}
|
|
3490
3724
|
}
|
|
3491
|
-
return
|
|
3725
|
+
return {
|
|
3726
|
+
secret,
|
|
3727
|
+
file: relative(io.cwd, file.path) || file.path,
|
|
3728
|
+
wrote
|
|
3729
|
+
};
|
|
3492
3730
|
}
|
|
3493
3731
|
async function openListener(coss, params) {
|
|
3494
3732
|
const { data, error } = await coss.webhookListeners.create({
|
|
@@ -3513,7 +3751,7 @@ async function run$1(context, values) {
|
|
|
3513
3751
|
if (error) throw apiError("Couldn't read the environment", error);
|
|
3514
3752
|
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.`);
|
|
3515
3753
|
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.");
|
|
3516
|
-
const secret = await signingSecret(io, credentials);
|
|
3754
|
+
const { secret, file: secretFile, wrote: wroteSecret } = await signingSecret(io, credentials);
|
|
3517
3755
|
const listenerParams = {
|
|
3518
3756
|
eventTypes,
|
|
3519
3757
|
apiVersion: typeof values["api-version"] === "string" ? values["api-version"] : environment.organization.api_version,
|
|
@@ -3521,7 +3759,8 @@ async function run$1(context, values) {
|
|
|
3521
3759
|
};
|
|
3522
3760
|
let listener = await openListener(coss, listenerParams);
|
|
3523
3761
|
out.info(`${out.style("green", "Ready!")} Listening to ${describeEnvironment(environment)}${target ? `, forwarding to ${target}` : ""}.`);
|
|
3524
|
-
out.info(`
|
|
3762
|
+
out.info(`COSS_WEBHOOK_SECRET=${secret}`);
|
|
3763
|
+
out.info(`${wroteSecret ? "Saved" : "Using"} COSS_WEBHOOK_SECRET in ${secretFile} (API version ${listener.api_version}).`);
|
|
3525
3764
|
out.info(out.style("dim", "Press Ctrl-C to stop."));
|
|
3526
3765
|
let pending = [];
|
|
3527
3766
|
let failures = 0;
|
|
@@ -4432,6 +4671,207 @@ const RISK_COMMANDS = [
|
|
|
4432
4671
|
})
|
|
4433
4672
|
];
|
|
4434
4673
|
//#endregion
|
|
4674
|
+
//#region src/sms/simulate.ts
|
|
4675
|
+
/**
|
|
4676
|
+
* The SMS simulator: numbers whose outcome is known in advance in sandbox environments (coss.com's
|
|
4677
|
+
* fake SMS provider), never added to the suppression list. `coss sms send --simulate` sends to
|
|
4678
|
+
* them.
|
|
4679
|
+
*
|
|
4680
|
+
* Must match `SMS_SIMULATOR` in `packages/sms/src/schemas.ts` (the CLI can't import workspace
|
|
4681
|
+
* packages): change both together.
|
|
4682
|
+
*/
|
|
4683
|
+
const SIMULATED_SMS_OUTCOMES = {
|
|
4684
|
+
/** Delivered. */
|
|
4685
|
+
delivered: "+15005550006",
|
|
4686
|
+
/** Failed: `invalid_number`. */
|
|
4687
|
+
invalid: "+15005550001",
|
|
4688
|
+
/** Undelivered: `carrier_filtered`. */
|
|
4689
|
+
filtered: "+15005550004",
|
|
4690
|
+
/** Failed: `opted_out`. */
|
|
4691
|
+
"opted-out": "+15005550009",
|
|
4692
|
+
/** Delivered, then a simulated reply arrives in the environment's received messages. */
|
|
4693
|
+
reply: "+15005550008"
|
|
4694
|
+
};
|
|
4695
|
+
function isSimulatedSmsOutcome(value) {
|
|
4696
|
+
return Object.hasOwn(SIMULATED_SMS_OUTCOMES, value);
|
|
4697
|
+
}
|
|
4698
|
+
//#endregion
|
|
4699
|
+
//#region src/commands/sms.ts
|
|
4700
|
+
const SANDBOX_FROM = "+14155550100";
|
|
4701
|
+
const DEFAULT_BODY = "Test message from the coss.com CLI";
|
|
4702
|
+
/** Statuses after which nothing more is expected. */
|
|
4703
|
+
const SETTLED = /* @__PURE__ */ new Set([
|
|
4704
|
+
"delivered",
|
|
4705
|
+
"undelivered",
|
|
4706
|
+
"failed",
|
|
4707
|
+
"canceled"
|
|
4708
|
+
]);
|
|
4709
|
+
function settled(sms) {
|
|
4710
|
+
return SETTLED.has(sms.status);
|
|
4711
|
+
}
|
|
4712
|
+
async function waitForOutcome(context, coss, sms, options) {
|
|
4713
|
+
const { io, out } = context;
|
|
4714
|
+
const deadline = io.now().getTime() + options.timeoutMs;
|
|
4715
|
+
let current = sms;
|
|
4716
|
+
if (!out.json) out.info("Waiting for the outcome…");
|
|
4717
|
+
while (!settled(current) && io.now().getTime() < deadline && !io.signal.aborted) {
|
|
4718
|
+
await io.sleep(1e3, io.signal);
|
|
4719
|
+
const { data, error } = await coss.sms.get(current.id, { signal: io.signal });
|
|
4720
|
+
if (error) {
|
|
4721
|
+
if (io.signal.aborted) break;
|
|
4722
|
+
throw apiError("Couldn't read the message", error);
|
|
4723
|
+
}
|
|
4724
|
+
current = data;
|
|
4725
|
+
}
|
|
4726
|
+
if (io.signal.aborted) return {
|
|
4727
|
+
sms: current,
|
|
4728
|
+
events: [],
|
|
4729
|
+
replies: void 0,
|
|
4730
|
+
settled: settled(current)
|
|
4731
|
+
};
|
|
4732
|
+
const { data, error } = await coss.sms.listEvents(current.id, { signal: io.signal });
|
|
4733
|
+
if (error) {
|
|
4734
|
+
if (io.signal.aborted) return {
|
|
4735
|
+
sms: current,
|
|
4736
|
+
events: [],
|
|
4737
|
+
replies: void 0,
|
|
4738
|
+
settled: settled(current)
|
|
4739
|
+
};
|
|
4740
|
+
throw apiError("Couldn't read the message's events", error);
|
|
4741
|
+
}
|
|
4742
|
+
let replies;
|
|
4743
|
+
if (options.reply && current.status === "delivered" && !io.signal.aborted) {
|
|
4744
|
+
const received = await coss.sms.received.list({
|
|
4745
|
+
from: current.to,
|
|
4746
|
+
to: current.from,
|
|
4747
|
+
created_after: current.created_at
|
|
4748
|
+
}, { signal: io.signal });
|
|
4749
|
+
if (received.error && !io.signal.aborted) throw apiError("Couldn't read the received messages", received.error);
|
|
4750
|
+
replies = received.data?.data;
|
|
4751
|
+
}
|
|
4752
|
+
return {
|
|
4753
|
+
sms: current,
|
|
4754
|
+
events: data.data,
|
|
4755
|
+
replies,
|
|
4756
|
+
settled: settled(current)
|
|
4757
|
+
};
|
|
4758
|
+
}
|
|
4759
|
+
function statusStyle$1(status) {
|
|
4760
|
+
if (status === "delivered" || status === "sent") return "green";
|
|
4761
|
+
if (status === "queued" || status === "scheduled") return "yellow";
|
|
4762
|
+
return "red";
|
|
4763
|
+
}
|
|
4764
|
+
const smsSendCommand = defineCommand({
|
|
4765
|
+
name: "sms send",
|
|
4766
|
+
summary: "Send a test text message (--simulate filtered, --wait…)",
|
|
4767
|
+
description: "Sends a test text message from the API key's environment. Sandbox keys (coss_test_…) never reach a phone: they go through coss.com's simulated provider, with every event and webhook a real send has.",
|
|
4768
|
+
flags: {
|
|
4769
|
+
to: {
|
|
4770
|
+
type: "string",
|
|
4771
|
+
value: "<number>",
|
|
4772
|
+
description: "Recipient, in E.164 form (+14155550123)"
|
|
4773
|
+
},
|
|
4774
|
+
simulate: {
|
|
4775
|
+
type: "string",
|
|
4776
|
+
value: "<outcome>",
|
|
4777
|
+
choices: Object.keys(SIMULATED_SMS_OUTCOMES),
|
|
4778
|
+
description: "Send to the SMS simulator (sandbox keys only): delivered, invalid, filtered, opted-out, reply"
|
|
4779
|
+
},
|
|
4780
|
+
from: {
|
|
4781
|
+
type: "string",
|
|
4782
|
+
value: "<number>",
|
|
4783
|
+
description: "Sender, in E.164 form (default for sandbox keys: +14155550100; live keys need one of your organization's registered numbers)"
|
|
4784
|
+
},
|
|
4785
|
+
body: {
|
|
4786
|
+
type: "string",
|
|
4787
|
+
value: "<text>",
|
|
4788
|
+
description: "Default: \"Test message from the coss.com CLI\""
|
|
4789
|
+
},
|
|
4790
|
+
tag: {
|
|
4791
|
+
type: "string",
|
|
4792
|
+
multiple: true,
|
|
4793
|
+
value: "<name=value>",
|
|
4794
|
+
description: "A tag (repeatable)"
|
|
4795
|
+
},
|
|
4796
|
+
wait: {
|
|
4797
|
+
type: "boolean",
|
|
4798
|
+
description: "Follow the message until its outcome is known, then show its events (with --simulate reply, also the reply)"
|
|
4799
|
+
},
|
|
4800
|
+
timeout: {
|
|
4801
|
+
type: "string",
|
|
4802
|
+
value: "<seconds>",
|
|
4803
|
+
description: "How long --wait waits (default 60)"
|
|
4804
|
+
},
|
|
4805
|
+
json: {
|
|
4806
|
+
type: "boolean",
|
|
4807
|
+
description: "Print the message (and with --wait, its events) as JSON"
|
|
4808
|
+
}
|
|
4809
|
+
},
|
|
4810
|
+
run: smsSend
|
|
4811
|
+
});
|
|
4812
|
+
async function smsSend({ values, context }) {
|
|
4813
|
+
const { io, out } = context;
|
|
4814
|
+
const simulate = values.simulate;
|
|
4815
|
+
if (simulate !== void 0 && !isSimulatedSmsOutcome(simulate)) throw new UsageError(`--simulate takes ${Object.keys(SIMULATED_SMS_OUTCOMES).join(", ")}; got "${simulate}".`);
|
|
4816
|
+
if (simulate && values.to) throw new UsageError("Pass --to or --simulate, not both.");
|
|
4817
|
+
const to = simulate ? SIMULATED_SMS_OUTCOMES[simulate] : values.to;
|
|
4818
|
+
if (!to) throw new UsageError("Pass --to <number> or --simulate <outcome>.");
|
|
4819
|
+
const timeoutS = values.timeout === void 0 ? 60 : Number(values.timeout);
|
|
4820
|
+
if (!Number.isFinite(timeoutS) || timeoutS <= 0) throw new UsageError("--timeout takes a number of seconds.");
|
|
4821
|
+
const tags = pairs$1(values.tag ?? [], "tag").map(([name, value]) => ({
|
|
4822
|
+
name,
|
|
4823
|
+
value
|
|
4824
|
+
}));
|
|
4825
|
+
const credentials = await resolveCredentials(context);
|
|
4826
|
+
const live = credentials.apiKey.startsWith("coss_live_");
|
|
4827
|
+
if (live && simulate) throw new UsageError("--simulate needs a sandbox (coss_test_) key: live messages go to real carriers. Pass --to.");
|
|
4828
|
+
if (live && !values.from) throw new UsageError("Live keys send from one of your organization's numbers: pass --from +1….");
|
|
4829
|
+
const params = {
|
|
4830
|
+
from: values.from ?? SANDBOX_FROM,
|
|
4831
|
+
to,
|
|
4832
|
+
body: values.body ?? DEFAULT_BODY,
|
|
4833
|
+
...tags.length > 0 && { tags }
|
|
4834
|
+
};
|
|
4835
|
+
const coss = clientFor(io, credentials);
|
|
4836
|
+
const { data: sms, error } = await coss.sms.send(params, { signal: io.signal });
|
|
4837
|
+
if (error) throw apiError("Couldn't send the message", error);
|
|
4838
|
+
if (!values.wait) {
|
|
4839
|
+
if (out.json) out.data(sms);
|
|
4840
|
+
else {
|
|
4841
|
+
out.line(`${out.style("green", "✔")} ${sms.id} ${sms.status} → ${sms.to}${sms.sandbox ? out.style("dim", " (sandbox)") : ""}`);
|
|
4842
|
+
out.info(out.style("dim", "Add --wait to follow it, or run `coss logs tail` to watch every event."));
|
|
4843
|
+
}
|
|
4844
|
+
return 0;
|
|
4845
|
+
}
|
|
4846
|
+
const outcome = await waitForOutcome(context, coss, sms, {
|
|
4847
|
+
timeoutMs: timeoutS * 1e3,
|
|
4848
|
+
reply: simulate === "reply"
|
|
4849
|
+
});
|
|
4850
|
+
if (out.json) out.data({
|
|
4851
|
+
...outcome.sms,
|
|
4852
|
+
events: outcome.events,
|
|
4853
|
+
...outcome.replies && { replies: outcome.replies }
|
|
4854
|
+
});
|
|
4855
|
+
else {
|
|
4856
|
+
out.line(`${outcome.sms.id} ${out.style(statusStyle$1(outcome.sms.status), outcome.sms.status)} → ${outcome.sms.to}`);
|
|
4857
|
+
if (outcome.sms.failure) out.line(` ${outcome.sms.failure.code}: ${outcome.sms.failure.message}`);
|
|
4858
|
+
if (outcome.events.length > 0) out.line();
|
|
4859
|
+
for (const event of outcome.events) {
|
|
4860
|
+
const failure = event.data.failure ? ` ${event.data.failure.code}` : "";
|
|
4861
|
+
out.line(` ${out.style("dim", event.occurred_at)} ${event.type}${failure}`);
|
|
4862
|
+
}
|
|
4863
|
+
for (const reply of outcome.replies ?? []) {
|
|
4864
|
+
out.line();
|
|
4865
|
+
out.line(` ${out.style("dim", reply.created_at)} reply from ${reply.from}: ${reply.body}`);
|
|
4866
|
+
}
|
|
4867
|
+
}
|
|
4868
|
+
if (!outcome.settled && !io.signal.aborted) {
|
|
4869
|
+
out.warn("Not every outcome arrived in time. Sends need the worker running (locally: `bun run dev`).");
|
|
4870
|
+
return 1;
|
|
4871
|
+
}
|
|
4872
|
+
return io.signal.aborted ? 130 : 0;
|
|
4873
|
+
}
|
|
4874
|
+
//#endregion
|
|
4435
4875
|
//#region src/templates/files.ts
|
|
4436
4876
|
/**
|
|
4437
4877
|
* Templates as files: one folder per template (named by its alias, else its id) holding
|
|
@@ -5075,7 +5515,7 @@ const webhooksListCommand = defineCommand({
|
|
|
5075
5515
|
return 0;
|
|
5076
5516
|
}
|
|
5077
5517
|
if (data.data.length === 0) {
|
|
5078
|
-
out.info("No webhook endpoints.
|
|
5518
|
+
out.info("No webhook endpoints. `coss webhooks add https://…` creates one, or `coss listen` receives events here.");
|
|
5079
5519
|
return 0;
|
|
5080
5520
|
}
|
|
5081
5521
|
for (const endpoint of data.data) {
|
|
@@ -5177,6 +5617,90 @@ const webhooksRetryCommand = defineCommand({
|
|
|
5177
5617
|
return 0;
|
|
5178
5618
|
}
|
|
5179
5619
|
});
|
|
5620
|
+
const webhooksAddCommand = defineCommand({
|
|
5621
|
+
name: "webhooks add",
|
|
5622
|
+
summary: "Create an endpoint and save its signing secret",
|
|
5623
|
+
usage: "<url> [options]",
|
|
5624
|
+
description: "Creates a webhook endpoint at <url>. The signing secret is returned once and written to the project env file as COSS_WEBHOOK_SECRET, which verifyWebhook and `coss listen` both use (a previous value is replaced, so local forwarding and this endpoint sign the same way). Creation is not retried. If this URL already has an endpoint, it is left as it is unless --force.",
|
|
5625
|
+
flags: {
|
|
5626
|
+
description: {
|
|
5627
|
+
type: "string",
|
|
5628
|
+
value: "<text>",
|
|
5629
|
+
description: "A note stored on the endpoint"
|
|
5630
|
+
},
|
|
5631
|
+
events: {
|
|
5632
|
+
type: "string",
|
|
5633
|
+
multiple: true,
|
|
5634
|
+
value: "<types>",
|
|
5635
|
+
description: "Only these event types (default: every event, including later ones)"
|
|
5636
|
+
},
|
|
5637
|
+
force: {
|
|
5638
|
+
type: "boolean",
|
|
5639
|
+
description: "Create another endpoint when this URL already has one"
|
|
5640
|
+
},
|
|
5641
|
+
json: {
|
|
5642
|
+
type: "boolean",
|
|
5643
|
+
description: "Print the endpoint as JSON, including its signing secret"
|
|
5644
|
+
}
|
|
5645
|
+
},
|
|
5646
|
+
positionals: true,
|
|
5647
|
+
run: addEndpoint
|
|
5648
|
+
});
|
|
5649
|
+
async function addEndpoint({ values, positionals, context }) {
|
|
5650
|
+
const { io, out } = context;
|
|
5651
|
+
const [url] = requireArgs(positionals, 1, "webhooks add <url>");
|
|
5652
|
+
if (url === void 0 || !/^https?:\/\//i.test(url)) throw new UsageError("Pass an http(s) URL: `coss webhooks add https://example.com/webhooks`.");
|
|
5653
|
+
const events = list(values.events);
|
|
5654
|
+
const unknown = events.filter((type) => !WEBHOOK_EVENT_TYPES.includes(type));
|
|
5655
|
+
if (unknown.length > 0) throw new UsageError(`Unknown event type ${unknown.map((type) => `"${type}"`).join(", ")}. See https://coss.com/docs/webhooks.`);
|
|
5656
|
+
const coss = clientFor(io, await resolveCredentials(context));
|
|
5657
|
+
const listed = await coss.webhookEndpoints.list({ signal: io.signal });
|
|
5658
|
+
if (listed.error) throw apiError("Couldn't list the webhook endpoints", listed.error);
|
|
5659
|
+
const existing = listed.data.data.filter((endpoint) => endpoint.url === url);
|
|
5660
|
+
if (existing.length > 0 && values.force !== true) {
|
|
5661
|
+
if (out.json) out.data({
|
|
5662
|
+
created: false,
|
|
5663
|
+
endpoints: existing
|
|
5664
|
+
});
|
|
5665
|
+
else {
|
|
5666
|
+
const ids = existing.map((endpoint) => endpoint.id).join(", ");
|
|
5667
|
+
out.line(`${url} already has ${ids}.`);
|
|
5668
|
+
out.info("Its signing secret was shown only when it was created. Pass --force to create another endpoint.");
|
|
5669
|
+
}
|
|
5670
|
+
return 0;
|
|
5671
|
+
}
|
|
5672
|
+
const { data, error } = await coss.webhookEndpoints.create({
|
|
5673
|
+
url,
|
|
5674
|
+
...values.description ? { description: values.description } : {},
|
|
5675
|
+
...events.length > 0 ? { event_types: events } : {}
|
|
5676
|
+
}, { signal: io.signal });
|
|
5677
|
+
if (error) throw apiError("Couldn't create the webhook endpoint", error);
|
|
5678
|
+
const file = await projectEnvFile(io.cwd);
|
|
5679
|
+
const previous = file.text ? readEnvValue(file.text, "COSS_WEBHOOK_SECRET") : "";
|
|
5680
|
+
let wrote = false;
|
|
5681
|
+
try {
|
|
5682
|
+
wrote = await writeEnvValue(file, "COSS_WEBHOOK_SECRET", data.secret);
|
|
5683
|
+
} catch (cause) {
|
|
5684
|
+
out.info(`COSS_WEBHOOK_SECRET=${data.secret}`);
|
|
5685
|
+
throw new CliError(`Created ${data.id}, but couldn't save its signing secret (${cause instanceof Error ? cause.message : "write failed"}). Store the secret above; the API will not show it again.`);
|
|
5686
|
+
}
|
|
5687
|
+
const shown = relative(io.cwd, file.path) || file.path;
|
|
5688
|
+
const replaced = previous !== "" && previous !== data.secret;
|
|
5689
|
+
if (out.json) {
|
|
5690
|
+
out.data({
|
|
5691
|
+
...data,
|
|
5692
|
+
created: true,
|
|
5693
|
+
env_file: shown,
|
|
5694
|
+
replaced_existing_secret: replaced
|
|
5695
|
+
});
|
|
5696
|
+
return 0;
|
|
5697
|
+
}
|
|
5698
|
+
out.line(`${out.style("green", "✔")} ${data.id} ${data.url}`);
|
|
5699
|
+
out.info(`COSS_WEBHOOK_SECRET=${data.secret}`);
|
|
5700
|
+
const where = replaced ? `Saved COSS_WEBHOOK_SECRET in ${shown}, replacing the previous value.` : wrote ? `Saved COSS_WEBHOOK_SECRET in ${shown}.` : `COSS_WEBHOOK_SECRET in ${shown} already matches.`;
|
|
5701
|
+
out.info(`${where} coss listen signs with it too.`);
|
|
5702
|
+
return 0;
|
|
5703
|
+
}
|
|
5180
5704
|
//#endregion
|
|
5181
5705
|
//#region src/commands/whoami.ts
|
|
5182
5706
|
const whoamiCommand = defineCommand({
|
|
@@ -5186,6 +5710,10 @@ const whoamiCommand = defineCommand({
|
|
|
5186
5710
|
flags: {},
|
|
5187
5711
|
run: whoami
|
|
5188
5712
|
});
|
|
5713
|
+
function describeAccess(key) {
|
|
5714
|
+
if (key.access === "full") return "full";
|
|
5715
|
+
return `restricted: ${key.permissions.join(", ") || "nothing"}`;
|
|
5716
|
+
}
|
|
5189
5717
|
async function whoami({ context }) {
|
|
5190
5718
|
const { io, out } = context;
|
|
5191
5719
|
const credentials = await resolveCredentials(context);
|
|
@@ -5202,6 +5730,7 @@ async function whoami({ context }) {
|
|
|
5202
5730
|
}
|
|
5203
5731
|
out.line(describeEnvironment(data));
|
|
5204
5732
|
out.line(` Key ${data.api_key.name ?? "(unnamed)"} ${out.style("dim", data.api_key.id)}`);
|
|
5733
|
+
if (data.api_key.access) out.line(` Access ${describeAccess(data.api_key)}`);
|
|
5205
5734
|
out.line(` From ${source}`);
|
|
5206
5735
|
out.line(` API ${credentials.baseUrl}`);
|
|
5207
5736
|
out.line(` Version ${data.organization.api_version}`);
|
|
@@ -5308,12 +5837,14 @@ const COMMANDS = [
|
|
|
5308
5837
|
emailsGetCommand,
|
|
5309
5838
|
emailsEventsCommand,
|
|
5310
5839
|
emailsDiagnoseCommand,
|
|
5840
|
+
smsSendCommand,
|
|
5311
5841
|
logsTailCommand,
|
|
5312
5842
|
inboxCommand,
|
|
5313
5843
|
inboxGetCommand,
|
|
5314
5844
|
listenCommand,
|
|
5315
5845
|
triggerCommand,
|
|
5316
5846
|
webhooksListCommand,
|
|
5847
|
+
webhooksAddCommand,
|
|
5317
5848
|
webhooksDeliveriesCommand,
|
|
5318
5849
|
webhooksRetryCommand,
|
|
5319
5850
|
...HOOKS_COMMANDS,
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "coss-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "The coss.com command line: sign in, send test emails, tail your environment's log, and forward webhook events to localhost with `coss listen`.",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "The coss.com command line: sign in, send test emails and text messages, tail your environment's log, and forward webhook events to localhost with `coss listen`.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://coss.com/docs/cli",
|
|
7
7
|
"repository": {
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
"coss",
|
|
15
15
|
"cli",
|
|
16
16
|
"email",
|
|
17
|
+
"sms",
|
|
17
18
|
"webhooks",
|
|
18
19
|
"logs"
|
|
19
20
|
],
|
|
@@ -42,7 +43,7 @@
|
|
|
42
43
|
"test": "bun test"
|
|
43
44
|
},
|
|
44
45
|
"dependencies": {
|
|
45
|
-
"coss": "^0.
|
|
46
|
+
"coss": "^0.9.0"
|
|
46
47
|
},
|
|
47
48
|
"devDependencies": {
|
|
48
49
|
"@arethetypeswrong/core": "0.18.5",
|