coss-cli 0.3.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 CHANGED
@@ -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 ad-hoc signed, not notarized:
31
- one downloaded with a browser needs `xattr -d com.apple.quarantine coss`.
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,7 +39,7 @@ 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`. `--agents` adds notes on coss.com for coding agents to the project's `AGENTS.md`. |
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). |
@@ -53,6 +53,7 @@ one downloaded with a browser needs `xattr -d com.apple.quarantine coss`.
53
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. |
54
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`. |
55
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`). |
56
57
  | `coss webhooks deliveries <endpoint>` | An endpoint's deliveries, newest first (`--status failed`, `--event <id>`, `--limit`). |
57
58
  | `coss webhooks retry <endpoint> <delivery>` | Sends a finished delivery to its endpoint once more. |
58
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-B-0EIbmN.js";
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-B-0EIbmN.js";
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";
@@ -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,22 +3344,12 @@ 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
- /** The env file with `name=value` set: an existing line replaced, else one appended. */
3221
- function setEnvVar(text, name, value) {
3222
- const line = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=.*$`, "m");
3223
- if (line.test(text)) return text.replace(line, () => `${name}=${value}`);
3224
- return `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}${name}=${value}\n`;
3225
- }
3226
- /** `text` without `name`'s assignments. */
3227
- function removeEnvVar(text, name) {
3228
- return text.replace(new RegExp(`^[ \\t]*(?:export[ \\t]+)?${name}[ \\t]*=.*(?:\\r?\\n|$)`, "gm"), "");
3229
- }
3230
3347
  const NOTES_BEGIN = "<!-- BEGIN:coss -->";
3231
3348
  const NOTES_END = "<!-- END:coss -->";
3232
3349
  /**
3233
3350
  * What a coding agent working in the project should know about coss.com, for its AGENTS.md
3234
- * (`--agents`). Keep it in step with the brief that opens https://coss.com/llms.txt
3235
- * (apps/site/src/lib/llms.ts).
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).
3236
3353
  */
3237
3354
  function agentNotes(envFile) {
3238
3355
  return `${NOTES_BEGIN}
@@ -3247,11 +3364,16 @@ This project uses [coss.com](https://coss.com) (email, SMS, webhooks) through it
3247
3364
  every API works and records what it would do, with events and webhooks, but nothing is
3248
3365
  delivered. A \`coss_live_…\` key there delivers for real: don't test with it, and never switch
3249
3366
  to one to try something (\`npx coss-cli init --force\` replaces it with a development key).
3250
- - SDK methods return \`{ data, error }\` and don't throw for API failures: always check \`error\`.
3251
- Webhook handlers verify each request with \`verifyWebhook\`, which throws on a bad signature.
3252
- - After \`npx coss-cli login\`: \`npx coss-cli listen --forward-to localhost:3000/<path>\` forwards
3253
- webhook events to a local handler, \`npx coss-cli trigger <event type>\` sends a test event, and
3254
- \`npx coss-cli logs tail\` follows the API requests and events.
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>\`.
3255
3377
  ${NOTES_END}
3256
3378
  `;
3257
3379
  }
@@ -3280,7 +3402,7 @@ function projectName(dir, pkg) {
3280
3402
  const initCommand = defineCommand({
3281
3403
  name: "init",
3282
3404
  summary: "Set this project up: the SDK and a development API key",
3283
- 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. With --agents 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.",
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.",
3284
3406
  flags: {
3285
3407
  "env-file": {
3286
3408
  type: "string",
@@ -3297,7 +3419,11 @@ const initCommand = defineCommand({
3297
3419
  },
3298
3420
  agents: {
3299
3421
  type: "boolean",
3300
- description: "Add notes on coss.com for coding agents to the project's AGENTS.md (or CLAUDE.md)"
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"
3301
3427
  },
3302
3428
  "no-browser": {
3303
3429
  type: "boolean",
@@ -3319,6 +3445,7 @@ async function init({ values, context }) {
3319
3445
  const shownFile = relative(dir, envFile) || envFile;
3320
3446
  const existingText = await readFile(envFile, "utf8").catch(() => null);
3321
3447
  const existingKey = existingText ? KEY_LINE.exec(existingText)?.[1] ?? "" : "";
3448
+ let apiKey = existingKey;
3322
3449
  const config = await readConfig(io);
3323
3450
  const profile = config.profiles[profileName(io, config, flags.profile)] ?? null;
3324
3451
  const baseUrl = apiBaseUrl(io, profile);
@@ -3342,6 +3469,7 @@ async function init({ values, context }) {
3342
3469
  await coss.apiKey.revoke().catch(() => void 0);
3343
3470
  throw new CliError(`${describeEnvironment(environment)} is live, so its key was revoked: \`coss init\` only writes development keys. Pick a sandbox environment.`);
3344
3471
  }
3472
+ apiKey = token.api_key;
3345
3473
  const withKey = setEnvVar(existingText ?? "", "COSS_API_KEY", token.api_key);
3346
3474
  const text = baseUrl === "https://api.coss.com" ? removeEnvVar(withKey, "COSS_BASE_URL") : setEnvVar(withKey, "COSS_BASE_URL", baseUrl);
3347
3475
  await mkdir(dirname(envFile), { recursive: true });
@@ -3368,42 +3496,82 @@ async function init({ values, context }) {
3368
3496
  if (!out.json) out.line(`${out.style("green", "✔")} Installed the coss package.`);
3369
3497
  }
3370
3498
  let notesFile = null;
3371
- if (values.agents) {
3499
+ if (values["no-agents"] !== true) {
3372
3500
  notesFile = await agentsFile(dir);
3373
3501
  const before = await readFile(notesFile, "utf8").catch(() => "");
3374
3502
  await writeFile(notesFile, setAgentNotes(before, agentNotes(shownFile)));
3375
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)}.`);
3376
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);
3377
3511
  if (out.json) {
3378
3512
  out.data({
3379
3513
  env_file: envFile,
3380
3514
  key,
3381
3515
  installed,
3382
3516
  ignored_by_git: ignored,
3383
- agents_file: notesFile
3517
+ agents_file: notesFile,
3518
+ setup
3384
3519
  });
3385
3520
  return 0;
3386
3521
  }
3387
- out.line(`
3388
- Send an email from your server code${next ? " (a route handler or server action)" : ""}:
3389
-
3390
- import { Coss } from "coss";
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";
3391
3531
 
3392
3532
  const coss = new Coss(); // reads COSS_API_KEY
3393
3533
  const { data, error } = await coss.email.send({
3394
- from: "Acme <hello@example.com>",
3395
- to: "you@example.com",
3534
+ from: ${JSON.stringify(from)},
3535
+ to: ${JSON.stringify(to)},
3396
3536
  subject: "Hello from coss.com",
3397
3537
  text: "It works!",
3398
- });
3538
+ });`;
3539
+ }
3540
+ function nodemailerSnippet(from, to) {
3541
+ return ` import { cossTransport } from "coss/nodemailer";
3542
+ import nodemailer from "nodemailer";
3399
3543
 
3400
- Development keys never deliver email, but every send has its events and webhooks.${next ? "" : `\nLoad ${shownFile} in your app, e.g. node --env-file=${shownFile} server.js.`}
3544
+ const transport = nodemailer.createTransport(cossTransport());
3545
+ await transport.sendMail({
3546
+ from: ${JSON.stringify(from)},
3547
+ to: ${JSON.stringify(to)},
3548
+ subject: "Hello from coss.com",
3549
+ text: "It works!",
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)" : ""}:
3401
3554
 
3402
- Next:
3555
+ ${sdkSnippetText(from, to)}
3556
+
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:
3403
3571
  coss listen --forward-to localhost:3000/webhooks receive webhook events locally
3404
3572
  coss logs tail follow the environment's log
3405
- https://coss.com/docs guides and the API reference${values.agents ? "" : "\n coss init --agents notes for coding agents in AGENTS.md"}`);
3406
- return 0;
3573
+ https://coss.com/docs guides and the API reference`);
3574
+ return `\n${parts.join("\n\n")}`;
3407
3575
  }
3408
3576
  /** Whether git ignores the file: `null` outside a repository (or without git). */
3409
3577
  async function ignoredByGit(io, dir, file) {
@@ -3420,7 +3588,7 @@ async function ignoredByGit(io, dir, file) {
3420
3588
  //#endregion
3421
3589
  //#region src/version.ts
3422
3590
  /** The package version (`coss --version`, the forwarded requests' user agent). */
3423
- const VERSION = "0.3.0";
3591
+ const VERSION = "0.4.0";
3424
3592
  //#endregion
3425
3593
  //#region src/listen/forward.ts
3426
3594
  /** Posting an event to the local URL, as coss.com would post it to an endpoint. */
@@ -3535,12 +3703,18 @@ function report(out, forwarded, printJson) {
3535
3703
  out.line(`${time} ${out.style("cyan", delivery.event_type)} ${out.style("dim", delivery.event_id)}${outcome}${retry}`);
3536
3704
  if (printJson) out.line(toJson(JSON.parse(delivery.body), 2));
3537
3705
  }
3538
- /** The profile's signing secret, created (and saved) on first use. */
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
+ */
3539
3711
  async function signingSecret(io, credentials) {
3540
- const saved = credentials.profile?.listen_secret;
3541
- if (isSecret(saved)) return saved;
3542
- const secret = generateSecret();
3543
- if (credentials.source === "profile") {
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) {
3544
3718
  const config = await readConfig(io);
3545
3719
  const profile = config.profiles[credentials.profileName];
3546
3720
  if (profile) {
@@ -3548,7 +3722,11 @@ async function signingSecret(io, credentials) {
3548
3722
  await writeConfig(io, config);
3549
3723
  }
3550
3724
  }
3551
- return secret;
3725
+ return {
3726
+ secret,
3727
+ file: relative(io.cwd, file.path) || file.path,
3728
+ wrote
3729
+ };
3552
3730
  }
3553
3731
  async function openListener(coss, params) {
3554
3732
  const { data, error } = await coss.webhookListeners.create({
@@ -3573,7 +3751,7 @@ async function run$1(context, values) {
3573
3751
  if (error) throw apiError("Couldn't read the environment", error);
3574
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.`);
3575
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.");
3576
- const secret = await signingSecret(io, credentials);
3754
+ const { secret, file: secretFile, wrote: wroteSecret } = await signingSecret(io, credentials);
3577
3755
  const listenerParams = {
3578
3756
  eventTypes,
3579
3757
  apiVersion: typeof values["api-version"] === "string" ? values["api-version"] : environment.organization.api_version,
@@ -3581,7 +3759,8 @@ async function run$1(context, values) {
3581
3759
  };
3582
3760
  let listener = await openListener(coss, listenerParams);
3583
3761
  out.info(`${out.style("green", "Ready!")} Listening to ${describeEnvironment(environment)}${target ? `, forwarding to ${target}` : ""}.`);
3584
- out.info(`Signing secret: ${out.style("bold", secret)} (API version ${listener.api_version})`);
3762
+ out.info(`COSS_WEBHOOK_SECRET=${secret}`);
3763
+ out.info(`${wroteSecret ? "Saved" : "Using"} COSS_WEBHOOK_SECRET in ${secretFile} (API version ${listener.api_version}).`);
3585
3764
  out.info(out.style("dim", "Press Ctrl-C to stop."));
3586
3765
  let pending = [];
3587
3766
  let failures = 0;
@@ -5336,7 +5515,7 @@ const webhooksListCommand = defineCommand({
5336
5515
  return 0;
5337
5516
  }
5338
5517
  if (data.data.length === 0) {
5339
- out.info("No webhook endpoints. Run `coss listen` to receive events on this machine.");
5518
+ out.info("No webhook endpoints. `coss webhooks add https://…` creates one, or `coss listen` receives events here.");
5340
5519
  return 0;
5341
5520
  }
5342
5521
  for (const endpoint of data.data) {
@@ -5438,6 +5617,90 @@ const webhooksRetryCommand = defineCommand({
5438
5617
  return 0;
5439
5618
  }
5440
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
+ }
5441
5704
  //#endregion
5442
5705
  //#region src/commands/whoami.ts
5443
5706
  const whoamiCommand = defineCommand({
@@ -5581,6 +5844,7 @@ const COMMANDS = [
5581
5844
  listenCommand,
5582
5845
  triggerCommand,
5583
5846
  webhooksListCommand,
5847
+ webhooksAddCommand,
5584
5848
  webhooksDeliveriesCommand,
5585
5849
  webhooksRetryCommand,
5586
5850
  ...HOOKS_COMMANDS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coss-cli",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
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",
@@ -43,7 +43,7 @@
43
43
  "test": "bun test"
44
44
  },
45
45
  "dependencies": {
46
- "coss": "^0.8.0"
46
+ "coss": "^0.9.0"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@arethetypeswrong/core": "0.18.5",