@postshiba/cli 0.0.0-stage → 0.2.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.
@@ -0,0 +1,300 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * @typedef {object} CommandRow
5
+ * @property {string} resource
6
+ * @property {string} action
7
+ * @property {string} method
8
+ * @property {string} path
9
+ * @property {boolean} team
10
+ * @property {string[]} ids
11
+ * @property {boolean} data
12
+ * @property {boolean} destructive
13
+ * @property {boolean} binary
14
+ * @property {string[]} [columns]
15
+ * @property {string[]} query API query parameter names this action accepts
16
+ * @property {string[]} required query parameters that must be set
17
+ * @property {boolean} cluster sends X-Capsule-Cluster-Id when a cluster id is set
18
+ */
19
+
20
+ /**
21
+ * Query parameters that are flags without a value. Passing the flag sends `true`.
22
+ */
23
+ export const BOOLEAN_QUERY = new Set(["compare", "all"]);
24
+
25
+ /**
26
+ * @param {string} resource
27
+ * @param {string} action
28
+ * @param {string} method
29
+ * @param {string} path
30
+ * @param {{ data?: boolean, binary?: boolean, columns?: string[], query?: string[], required?: string[], cluster?: boolean }} [extra]
31
+ * @returns {CommandRow}
32
+ */
33
+ function row(resource, action, method, path, extra = {}) {
34
+ return {
35
+ resource,
36
+ action,
37
+ method,
38
+ path,
39
+ team: path.includes(":teamId"),
40
+ ids: pathParamNames(path),
41
+ data: extra.data ?? false,
42
+ destructive: isDestructive(action),
43
+ binary: extra.binary ?? false,
44
+ columns: extra.columns,
45
+ query: extra.query ?? [],
46
+ required: extra.required ?? [],
47
+ cluster: extra.cluster ?? false,
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Actions that remove, stop, or discard something ask before they run.
53
+ * `cancel` is exact so `cancel-boost` keeps running without a confirm.
54
+ * @param {string} action
55
+ */
56
+ export function isDestructive(action) {
57
+ return (
58
+ /^(delete|suspend|release|unassign)/.test(action) ||
59
+ /^(cancel|rotate-secret|flush-queue|remove-ip|detach|bulk-delete)$/.test(action)
60
+ );
61
+ }
62
+
63
+ /**
64
+ * The CLI flag for a query parameter: `min_processed` is `--min-processed`.
65
+ * @param {string} name
66
+ */
67
+ export function queryFlag(name) {
68
+ return name.replace(/_/g, "-");
69
+ }
70
+
71
+ /** @type {CommandRow[]} */
72
+ export const commands = [
73
+ row("clusters", "list", "GET", "/api/v1/teams/:teamId/clusters", {
74
+ columns: ["id", "name", "status", "plan", "sending_ready"],
75
+ }),
76
+ row("clusters", "get", "GET", "/api/v1/clusters/:id"),
77
+ row("clusters", "create", "POST", "/api/v1/teams/:teamId/clusters", { data: true }),
78
+ row("clusters", "update", "PATCH", "/api/v1/clusters/:id", { data: true }),
79
+ row("clusters", "suspend", "POST", "/api/v1/clusters/:id/suspend"),
80
+ row("clusters", "resume", "POST", "/api/v1/clusters/:id/resume"),
81
+ row("clusters", "delete", "DELETE", "/api/v1/clusters/:id"),
82
+ row("clusters", "boost", "POST", "/api/v1/clusters/:id/boost", { data: true }),
83
+ row("clusters", "extend-boost", "POST", "/api/v1/clusters/:id/extend_boost", { data: true }),
84
+ row("clusters", "cancel-boost", "POST", "/api/v1/clusters/:id/cancel_boost"),
85
+ row("clusters", "reactivate", "POST", "/api/v1/clusters/:id/reactivate"),
86
+ row("clusters", "set-auto-boost", "PATCH", "/api/v1/clusters/:id/auto_boost", { data: true }),
87
+ row("emails", "send-bulk", "POST", "/api/v1/emails/bulk", { data: true, cluster: true }),
88
+ row("emails", "list-bulk", "GET", "/api/v1/emails/bulk", {
89
+ query: ["reference"],
90
+ columns: ["id", "reference", "status", "total_messages", "released_count", "failed_count"],
91
+ }),
92
+ row("emails", "get-bulk", "GET", "/api/v1/emails/bulk/:id"),
93
+ row("network", "list", "GET", "/api/v1/teams/:teamId/network", {
94
+ columns: ["id", "address", "status", "kind", "classification"],
95
+ }),
96
+ row("network", "create", "POST", "/api/v1/teams/:teamId/network", { data: true }),
97
+ row("network", "assign", "POST", "/api/v1/teams/:teamId/network/assign", { data: true }),
98
+ row("network", "unassign", "POST", "/api/v1/teams/:teamId/network/unassign", { data: true }),
99
+ row("network", "switch", "POST", "/api/v1/teams/:teamId/network/switch", { data: true }),
100
+ row("network", "release", "POST", "/api/v1/teams/:teamId/network/release", { data: true }),
101
+ row("network", "warmup", "POST", "/api/v1/teams/:teamId/network/warmup", { data: true }),
102
+ row("ip-pools", "list", "GET", "/api/v1/teams/:teamId/ip_pools", {
103
+ query: ["classification"],
104
+ columns: ["id", "name", "classification", "warmup_overflow", "created_at"],
105
+ }),
106
+ row("ip-pools", "get", "GET", "/api/v1/ip_pools/:id"),
107
+ row("ip-pools", "create", "POST", "/api/v1/teams/:teamId/ip_pools", { data: true }),
108
+ row("ip-pools", "update", "PATCH", "/api/v1/ip_pools/:id", { data: true }),
109
+ row("ip-pools", "delete", "DELETE", "/api/v1/ip_pools/:id"),
110
+ row("ip-pools", "add-ip", "POST", "/api/v1/ip_pools/:id/add_ip", { data: true }),
111
+ row("ip-pools", "remove-ip", "POST", "/api/v1/ip_pools/:id/remove_ip", { data: true }),
112
+ row("ip-pools", "attach", "POST", "/api/v1/ip_pools/:id/attach", { data: true }),
113
+ row("ip-pools", "detach", "POST", "/api/v1/ip_pools/:id/detach", { data: true }),
114
+ row("sending-domains", "list", "GET", "/api/v1/teams/:teamId/sending_domains", {
115
+ columns: ["id", "name", "dkim_status", "return_path_status", "primary"],
116
+ }),
117
+ row("sending-domains", "get", "GET", "/api/v1/sending_domains/:id"),
118
+ row("sending-domains", "create", "POST", "/api/v1/teams/:teamId/sending_domains", { data: true }),
119
+ row("sending-domains", "update", "PATCH", "/api/v1/sending_domains/:id", { data: true }),
120
+ row("sending-domains", "refresh", "POST", "/api/v1/sending_domains/:id/refresh"),
121
+ row("sending-domains", "verify", "POST", "/api/v1/sending_domains/:id/verify"),
122
+ row("sending-domains", "suspend", "POST", "/api/v1/sending_domains/:id/suspend"),
123
+ row("sending-domains", "resume", "POST", "/api/v1/sending_domains/:id/resume"),
124
+ row("sending-domains", "make-primary", "POST", "/api/v1/sending_domains/:id/make_primary"),
125
+ row("sending-domains", "delete", "DELETE", "/api/v1/sending_domains/:id"),
126
+ row("sending-domains", "flush-queue", "POST", "/api/v1/sending_domains/:id/flush_queue"),
127
+ row("sending-domains", "move", "POST", "/api/v1/sending_domains/:id/move", { data: true }),
128
+ row("sending-domains", "can-i-send-this", "POST", "/api/v1/sending_domains/:id/can_i_send_this"),
129
+ row("sending-domains", "can-i-send-this-result", "GET", "/api/v1/sending_domains/:id/can_i_send_this", {
130
+ query: ["token"],
131
+ required: ["token"],
132
+ }),
133
+ row("tenants", "list", "GET", "/api/v1/teams/:teamId/tenants", {
134
+ columns: ["id", "name", "slug", "suspended"],
135
+ }),
136
+ row("tenants", "get", "GET", "/api/v1/tenants/:id"),
137
+ row("tenants", "create", "POST", "/api/v1/teams/:teamId/tenants", { data: true }),
138
+ row("tenants", "update", "PATCH", "/api/v1/tenants/:id", { data: true }),
139
+ row("tenants", "suspend", "POST", "/api/v1/tenants/:id/suspend"),
140
+ row("tenants", "resume", "POST", "/api/v1/tenants/:id/resume"),
141
+ row("tenants", "delete", "DELETE", "/api/v1/tenants/:id"),
142
+ row("inboxes", "list", "GET", "/api/v1/teams/:teamId/inboxes", {
143
+ columns: ["id", "name", "address", "mx_status"],
144
+ }),
145
+ row("inboxes", "get", "GET", "/api/v1/inboxes/:id"),
146
+ row("inboxes", "create", "POST", "/api/v1/teams/:teamId/inboxes", { data: true }),
147
+ row("inboxes", "update", "PATCH", "/api/v1/inboxes/:id", { data: true }),
148
+ row("inboxes", "verify", "POST", "/api/v1/inboxes/:id/verify"),
149
+ row("inboxes", "delete", "DELETE", "/api/v1/inboxes/:id"),
150
+ row("messages", "list", "GET", "/api/v1/inboxes/:inboxId/inbound_messages", {
151
+ columns: ["id", "from", "subject", "drain_status"],
152
+ }),
153
+ row("messages", "get", "GET", "/api/v1/inboxes/:inboxId/inbound_messages/:id"),
154
+ row("messages", "download-attachment", "GET", "/api/v1/inboxes/:inboxId/inbound_messages/:id/attachments/:index", {
155
+ binary: true,
156
+ }),
157
+ row("events", "list-team", "GET", "/api/v1/teams/:teamId/message_events", {
158
+ columns: ["id", "event_type", "recipient", "occurred_at"],
159
+ }),
160
+ row("events", "list", "GET", "/api/v1/teams/:teamId/clusters/:clusterId/message_events", {
161
+ columns: ["id", "event_type", "recipient", "occurred_at"],
162
+ }),
163
+ row("events", "get", "GET", "/api/v1/message_events/:id"),
164
+ row("outbound-messages", "list", "GET", "/api/v1/teams/:teamId/outbound_messages", {
165
+ query: ["q", "before", "limit"],
166
+ columns: ["id", "from", "to", "subject", "created_at"],
167
+ }),
168
+ row("outbound-messages", "get", "GET", "/api/v1/outbound_messages/:id"),
169
+ row("outbound-messages", "raw", "GET", "/api/v1/outbound_messages/:id/raw", { binary: true }),
170
+ row("outbound-messages", "download-attachment", "GET", "/api/v1/outbound_messages/:id/attachments/:index", {
171
+ binary: true,
172
+ }),
173
+ row("outbound-retention", "get", "GET", "/api/v1/teams/:teamId/outbound_retention"),
174
+ row("outbound-retention", "update", "PATCH", "/api/v1/teams/:teamId/outbound_retention", { data: true }),
175
+ row("dkim-signing", "get", "GET", "/api/v1/teams/:teamId/dkim_signing"),
176
+ row("dkim-signing", "update", "PATCH", "/api/v1/teams/:teamId/dkim_signing", { data: true }),
177
+ row("recipients", "get", "GET", "/api/v1/teams/:teamId/recipients", { query: ["email"], required: ["email"] }),
178
+ row("analytics", "get", "GET", "/api/v1/teams/:teamId/analytics", {
179
+ query: ["since", "until", "dimension", "min_processed", "compare", "compare_since", "compare_until"],
180
+ }),
181
+ row("status", "get", "GET", "/api/v1/teams/:teamId/status"),
182
+ row("planned-sends", "list", "GET", "/api/v1/teams/:teamId/planned_sends", {
183
+ columns: ["id", "name", "cluster_id", "volume_per_hour", "scheduled_for", "status"],
184
+ }),
185
+ row("planned-sends", "get", "GET", "/api/v1/planned_sends/:id"),
186
+ row("planned-sends", "create", "POST", "/api/v1/teams/:teamId/planned_sends", { data: true }),
187
+ row("planned-sends", "cancel", "DELETE", "/api/v1/planned_sends/:id"),
188
+ row("support-tickets", "list", "GET", "/api/v1/teams/:teamId/support_tickets", {
189
+ query: ["all"],
190
+ columns: ["id", "subject", "category", "status", "updated_at"],
191
+ }),
192
+ row("support-tickets", "get", "GET", "/api/v1/support_tickets/:id"),
193
+ row("support-tickets", "create", "POST", "/api/v1/teams/:teamId/support_tickets", { data: true }),
194
+ row("support-tickets", "reply", "POST", "/api/v1/support_tickets/:id/reply", { data: true }),
195
+ row("smtp-credentials", "create", "POST", "/api/v1/teams/:teamId/clusters/:clusterId/smtp_credentials", {
196
+ data: true,
197
+ }),
198
+ row("smtp-credentials", "delete", "DELETE", "/api/v1/teams/:teamId/clusters/:clusterId/smtp_credentials/:id"),
199
+ row("smtp-credentials", "enable", "POST", "/api/v1/teams/:teamId/clusters/:clusterId/smtp_credentials/:id/enable"),
200
+ row("webhooks", "list", "GET", "/api/v1/teams/:teamId/webhook_endpoints", {
201
+ columns: ["id", "url", "enabled"],
202
+ }),
203
+ row("webhooks", "get", "GET", "/api/v1/webhook_endpoints/:id"),
204
+ row("webhooks", "create", "POST", "/api/v1/teams/:teamId/webhook_endpoints", { data: true }),
205
+ row("webhooks", "update", "PATCH", "/api/v1/webhook_endpoints/:id", { data: true }),
206
+ row("webhooks", "delete", "DELETE", "/api/v1/webhook_endpoints/:id"),
207
+ row("webhooks", "send-test", "POST", "/api/v1/webhook_endpoints/:id/send_test"),
208
+ row("templates", "list", "GET", "/api/v1/teams/:teamId/templates", {
209
+ columns: ["id", "name", "alias", "published"],
210
+ }),
211
+ row("templates", "get", "GET", "/api/v1/templates/:id"),
212
+ row("templates", "create", "POST", "/api/v1/teams/:teamId/templates", { data: true }),
213
+ row("templates", "update", "PATCH", "/api/v1/templates/:id", { data: true }),
214
+ row("templates", "publish", "POST", "/api/v1/templates/:id/publish"),
215
+ row("templates", "duplicate", "POST", "/api/v1/templates/:id/duplicate"),
216
+ row("templates", "delete", "DELETE", "/api/v1/templates/:id"),
217
+ row("suppressions", "list", "GET", "/api/v1/teams/:teamId/suppressions", {
218
+ columns: ["id", "email", "reason", "tenant"],
219
+ }),
220
+ row("suppressions", "create", "POST", "/api/v1/teams/:teamId/suppressions", { data: true }),
221
+ row("suppressions", "import", "POST", "/api/v1/teams/:teamId/suppressions/import", { data: true }),
222
+ row("suppressions", "delete", "DELETE", "/api/v1/suppressions/:id"),
223
+ row("suppressions", "bulk-delete", "POST", "/api/v1/teams/:teamId/suppressions/bulk_delete", { data: true }),
224
+ row("firewall", "get", "GET", "/api/v1/teams/:teamId/firewall"),
225
+ row("firewall", "update", "PATCH", "/api/v1/teams/:teamId/firewall", { data: true }),
226
+ row("firewall", "add-entry", "POST", "/api/v1/teams/:teamId/firewall_entries", { data: true }),
227
+ row("firewall", "delete-entry", "DELETE", "/api/v1/firewall_entries/:id"),
228
+ row("shield-sites", "list", "GET", "/api/v1/teams/:teamId/shield_sites", {
229
+ columns: ["id", "name", "public_key", "allowed_hostnames", "created_at"],
230
+ }),
231
+ row("shield-sites", "get", "GET", "/api/v1/shield_sites/:id"),
232
+ row("shield-sites", "create", "POST", "/api/v1/teams/:teamId/shield_sites", { data: true }),
233
+ row("shield-sites", "update", "PATCH", "/api/v1/shield_sites/:id", { data: true }),
234
+ row("shield-sites", "rotate-secret", "POST", "/api/v1/shield_sites/:id/rotate_secret"),
235
+ row("shield-sites", "delete", "DELETE", "/api/v1/shield_sites/:id"),
236
+ ];
237
+
238
+ /**
239
+ * @param {string} name
240
+ */
241
+ export function kebab(name) {
242
+ return name.replace(/[A-Z]/g, (ch) => `-${ch.toLowerCase()}`);
243
+ }
244
+
245
+ /**
246
+ * @param {string} resource
247
+ * @param {string} action
248
+ */
249
+ export function findCommand(resource, action) {
250
+ return commands.find((item) => item.resource === resource && item.action === action);
251
+ }
252
+
253
+ export function resources() {
254
+ return [...new Set(commands.map((item) => item.resource))];
255
+ }
256
+
257
+ /**
258
+ * @param {string} resource
259
+ */
260
+ export function actionsFor(resource) {
261
+ return commands.filter((item) => item.resource === resource);
262
+ }
263
+
264
+ /**
265
+ * @param {string} path
266
+ */
267
+ export function pathParamNames(path) {
268
+ return [...path.matchAll(/:([A-Za-z]+)/g)].map((match) => match[1]).filter((name) => name !== "teamId");
269
+ }
270
+
271
+ /**
272
+ * @param {string} path
273
+ * @param {Record<string, string | undefined>} params
274
+ */
275
+ export function interpolatePath(path, params) {
276
+ return path.replace(/:([A-Za-z]+)/g, (_, name) => {
277
+ const value = params[name];
278
+ if (value === undefined || value === null || value === "") {
279
+ throw new Error(`missing path param :${name}`);
280
+ }
281
+ const text = String(value);
282
+ return /[^A-Za-z0-9._~-]/.test(text) ? encodeURIComponent(text) : text;
283
+ });
284
+ }
285
+
286
+ /**
287
+ * @param {CommandRow} item
288
+ */
289
+ export function actionUsage(item) {
290
+ const ids = item.ids.map((name) => `<${name}>`);
291
+ const parts = [item.action, ...ids];
292
+ for (const name of item.query) {
293
+ const flag = `--${queryFlag(name)}`;
294
+ const text = BOOLEAN_QUERY.has(name) ? flag : `${flag} VALUE`;
295
+ parts.push(item.required.includes(name) ? text : `[${text}]`);
296
+ }
297
+ if (item.data) parts.push("--data");
298
+ if (item.binary) parts.push("[--output PATH]");
299
+ return parts.join(" ");
300
+ }
package/src/config.js ADDED
@@ -0,0 +1,91 @@
1
+ // @ts-check
2
+
3
+ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+
6
+ export const DEFAULT_BASE_URL = "https://app.postshiba.com";
7
+
8
+ /**
9
+ * @param {NodeJS.ProcessEnv} [env]
10
+ * @param {string} [configDir]
11
+ */
12
+ export function resolveConfigDir(env = {}, configDir) {
13
+ if (configDir) return configDir;
14
+ if (env.XDG_CONFIG_HOME) return join(env.XDG_CONFIG_HOME, "postshiba");
15
+ const home = env.HOME ?? env.USERPROFILE;
16
+ if (!home) throw new Error("HOME or XDG_CONFIG_HOME is required");
17
+ return join(home, ".config", "postshiba");
18
+ }
19
+
20
+ /**
21
+ * @param {NodeJS.ProcessEnv} [env]
22
+ * @param {string} [configDir]
23
+ */
24
+ export function configFilePath(env, configDir) {
25
+ return join(resolveConfigDir(env, configDir), "config.json");
26
+ }
27
+
28
+ /**
29
+ * @param {NodeJS.ProcessEnv} [env]
30
+ * @param {string} [configDir]
31
+ * @returns {Promise<Record<string, string>>}
32
+ */
33
+ export async function readConfig(env, configDir) {
34
+ try {
35
+ return JSON.parse(await readFile(configFilePath(env, configDir), "utf8"));
36
+ } catch (err) {
37
+ if (err && /** @type {NodeJS.ErrnoException} */ (err).code === "ENOENT") return {};
38
+ throw err;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * @param {NodeJS.ProcessEnv | undefined} env
44
+ * @param {string | undefined} configDir
45
+ * @param {Record<string, string>} data
46
+ */
47
+ export async function writeConfig(env, configDir, data) {
48
+ const dir = resolveConfigDir(env, configDir);
49
+ await mkdir(dir, { recursive: true });
50
+ const file = join(dir, "config.json");
51
+ await writeFile(file, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
52
+ // writeFile mode is umask-masked; chmod is what makes 0600 stick.
53
+ await chmod(file, 0o600);
54
+ }
55
+
56
+ /**
57
+ * @param {NodeJS.ProcessEnv} [env]
58
+ * @param {string} [configDir]
59
+ */
60
+ export async function removeConfig(env, configDir) {
61
+ try {
62
+ await rm(configFilePath(env, configDir));
63
+ } catch (err) {
64
+ if (!err || /** @type {NodeJS.ErrnoException} */ (err).code !== "ENOENT") throw err;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * @param {Record<string, unknown>} values
70
+ * @param {NodeJS.ProcessEnv} env
71
+ * @param {Record<string, string>} file
72
+ */
73
+ export function resolveCredentials(values, env, file) {
74
+ const apiKey = first(values["api-key"], env.POSTSHIBA_API_KEY, file.api_key);
75
+ const teamId = first(values.team, env.POSTSHIBA_TEAM_ID, file.team_id);
76
+ const clusterId = first(values.cluster, env.POSTSHIBA_CLUSTER_ID, file.cluster_id);
77
+ const baseUrl = String(
78
+ first(values["base-url"], env.POSTSHIBA_BASE_URL, file.base_url) ?? DEFAULT_BASE_URL,
79
+ ).replace(/\/$/, "");
80
+ return { apiKey, teamId, clusterId, baseUrl };
81
+ }
82
+
83
+ /**
84
+ * @param {...unknown} values
85
+ */
86
+ function first(...values) {
87
+ for (const value of values) {
88
+ if (value !== undefined && value !== null && value !== "") return /** @type {string} */ (value);
89
+ }
90
+ return undefined;
91
+ }
package/src/doctor.js ADDED
@@ -0,0 +1,124 @@
1
+ // @ts-check
2
+
3
+ import { request } from "./client.js";
4
+ import { domainVerified } from "./render.js";
5
+
6
+ /**
7
+ * @param {object} creds
8
+ * @param {string} [creds.apiKey]
9
+ * @param {string} [creds.teamId]
10
+ * @param {string} creds.baseUrl
11
+ * @param {typeof fetch} fetchImpl
12
+ */
13
+ export async function runDoctor(creds, fetchImpl) {
14
+ /** @type {{ id: string, ok: boolean, detail?: string, fix?: string }[]} */
15
+ const checks = [];
16
+
17
+ if (!creds.apiKey) {
18
+ checks.push({ id: "key", ok: false, fix: "postshiba login" });
19
+ } else {
20
+ try {
21
+ const me = /** @type {{ email?: string }} */ (
22
+ await request({
23
+ method: "GET",
24
+ url: `${creds.baseUrl}/api/v1/users/me`,
25
+ apiKey: creds.apiKey,
26
+ fetch: fetchImpl,
27
+ })
28
+ );
29
+ checks.push({ id: "key", ok: true, detail: me.email });
30
+ } catch (err) {
31
+ const message = err instanceof Error ? err.message : String(err);
32
+ checks.push({ id: "key", ok: false, detail: message, fix: "postshiba login" });
33
+ }
34
+ }
35
+
36
+ if (!creds.teamId) {
37
+ checks.push({ id: "team", ok: false, fix: "pass --team or run postshiba login" });
38
+ } else {
39
+ checks.push({ id: "team", ok: true, detail: creds.teamId });
40
+ }
41
+
42
+ if (creds.apiKey && creds.teamId) {
43
+ try {
44
+ const clusters = asList(
45
+ await request({
46
+ method: "GET",
47
+ url: `${creds.baseUrl}/api/v1/teams/${creds.teamId}/clusters`,
48
+ apiKey: creds.apiKey,
49
+ fetch: fetchImpl,
50
+ }),
51
+ );
52
+ const ready = clusters.find((item) => item.sending_ready);
53
+ if (ready) checks.push({ id: "cluster", ok: true, detail: String(ready.name ?? ready.id) });
54
+ else {
55
+ checks.push({
56
+ id: "cluster",
57
+ ok: false,
58
+ fix: `postshiba clusters create --data '{"name":"edge"}'`,
59
+ });
60
+ }
61
+ } catch (err) {
62
+ const message = err instanceof Error ? err.message : String(err);
63
+ checks.push({ id: "cluster", ok: false, detail: message, fix: "postshiba clusters list" });
64
+ }
65
+
66
+ try {
67
+ const domains = asList(
68
+ await request({
69
+ method: "GET",
70
+ url: `${creds.baseUrl}/api/v1/teams/${creds.teamId}/sending_domains`,
71
+ apiKey: creds.apiKey,
72
+ fetch: fetchImpl,
73
+ }),
74
+ );
75
+ const verified = domains.find(domainVerified);
76
+ if (verified) checks.push({ id: "sending_domain", ok: true, detail: String(verified.name) });
77
+ else {
78
+ checks.push({
79
+ id: "sending_domain",
80
+ ok: false,
81
+ fix: "postshiba sending-domains create",
82
+ });
83
+ }
84
+ } catch (err) {
85
+ const message = err instanceof Error ? err.message : String(err);
86
+ checks.push({
87
+ id: "sending_domain",
88
+ ok: false,
89
+ detail: message,
90
+ fix: "postshiba sending-domains create",
91
+ });
92
+ }
93
+ } else {
94
+ if (!checks.some((item) => item.id === "cluster")) {
95
+ checks.push({ id: "cluster", ok: false, fix: "postshiba clusters create --data '{\"name\":\"edge\"}'" });
96
+ }
97
+ if (!checks.some((item) => item.id === "sending_domain")) {
98
+ checks.push({ id: "sending_domain", ok: false, fix: "postshiba sending-domains create" });
99
+ }
100
+ }
101
+
102
+ return { ok: checks.every((item) => item.ok), checks };
103
+ }
104
+
105
+ /**
106
+ * @param {unknown} value
107
+ * @returns {Record<string, any>[]}
108
+ */
109
+ function asList(value) {
110
+ return Array.isArray(value) ? value.filter((item) => item && typeof item === "object") : [];
111
+ }
112
+
113
+ /**
114
+ * @param {{ id: string, ok: boolean, detail?: string, fix?: string }} check
115
+ */
116
+ export function doctorLabel(check) {
117
+ const labels = {
118
+ key: "API key",
119
+ team: "Team id",
120
+ cluster: "Sending-ready cluster",
121
+ sending_domain: "Verified sending domain",
122
+ };
123
+ return labels[/** @type {keyof typeof labels} */ (check.id)] ?? check.id;
124
+ }
package/src/domains.js ADDED
@@ -0,0 +1,67 @@
1
+ // @ts-check
2
+
3
+ import { request } from "./client.js";
4
+ import { interpolatePath } from "./commands.js";
5
+ import { spinning } from "./prompts.js";
6
+ import { colorsFor, domainDnsRows, domainVerified, formatTable } from "./render.js";
7
+
8
+ const VERIFY_MS = 10_000;
9
+ const VERIFY_LIMIT_MS = 5 * 60 * 1000;
10
+
11
+ /**
12
+ * @param {object} ctx
13
+ * @param {boolean} ctx.interactive
14
+ * @param {import("./prompts.js").Prompts} [ctx.prompts]
15
+ * @param {typeof fetch} ctx.fetch
16
+ * @param {{ write: (chunk: string) => unknown }} ctx.stdout
17
+ * @param {NodeJS.ProcessEnv} ctx.env
18
+ * @param {boolean} [ctx.isTTY]
19
+ * @param {(ms: number) => Promise<void>} [ctx.sleep]
20
+ * @param {{ apiKey: string, teamId: string, baseUrl: string }} creds
21
+ */
22
+ export async function createSendingDomainWizard(ctx, creds) {
23
+ if (!ctx.prompts) throw new Error("prompts required");
24
+ const name = await ctx.prompts.text({
25
+ message: "Domain",
26
+ placeholder: "mail.example.com",
27
+ });
28
+ const path = interpolatePath("/api/v1/teams/:teamId/sending_domains", { teamId: creds.teamId });
29
+ const created = /** @type {Record<string, unknown>} */ (
30
+ await spinning(
31
+ ctx.prompts,
32
+ "Creating sending domain",
33
+ () => request({ method: "POST", url: `${creds.baseUrl}${path}`, apiKey: creds.apiKey, body: { name }, fetch: ctx.fetch }),
34
+ (domain) => `Created ${/** @type {Record<string, unknown>} */ (domain).name ?? name}`,
35
+ )
36
+ );
37
+
38
+ const c = colorsFor(ctx);
39
+ const rows = domainDnsRows(created);
40
+ if (rows.length) {
41
+ ctx.stdout.write(`${formatTable(rows, ["type", "name", "value"], c)}\n`);
42
+ }
43
+
44
+ const wait = await ctx.prompts.confirm({ message: "Wait for verification?" });
45
+ if (!wait) return created;
46
+
47
+ const id = String(created.id ?? "");
48
+ const verifyPath = interpolatePath("/api/v1/sending_domains/:id/verify", { id });
49
+ const started = Date.now();
50
+ const sleep = ctx.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
51
+ return spinning(
52
+ ctx.prompts,
53
+ "Waiting for DNS",
54
+ async () => {
55
+ let latest = created;
56
+ while (Date.now() - started < VERIFY_LIMIT_MS) {
57
+ latest = /** @type {Record<string, unknown>} */ (
58
+ await request({ method: "POST", url: `${creds.baseUrl}${verifyPath}`, apiKey: creds.apiKey, fetch: ctx.fetch })
59
+ );
60
+ if (domainVerified(latest)) return latest;
61
+ await sleep(VERIFY_MS);
62
+ }
63
+ return latest;
64
+ },
65
+ (latest) => (domainVerified(latest) ? "Verified" : "Still pending. Run postshiba sending-domains verify later."),
66
+ );
67
+ }
package/src/errors.js ADDED
@@ -0,0 +1,33 @@
1
+ // @ts-check
2
+
3
+ export class UsageError extends Error {
4
+ /**
5
+ * @param {string} message
6
+ * @param {{ helpResource?: string }} [opts]
7
+ */
8
+ constructor(message, opts = {}) {
9
+ super(message);
10
+ this.name = "UsageError";
11
+ this.helpResource = opts.helpResource;
12
+ }
13
+ }
14
+
15
+ export class CancelError extends Error {
16
+ constructor(message = "Cancelled.") {
17
+ super(message);
18
+ this.name = "CancelError";
19
+ }
20
+ }
21
+
22
+ /**
23
+ * @param {{ write: (chunk: string) => unknown }} stderr
24
+ * @param {{ message: string, field?: string | null, status?: number | null, error?: string }} err
25
+ */
26
+ export function writeApiError(stderr, err) {
27
+ let line = `Error: ${err.message}`;
28
+ if (err.field) line += ` (field: ${err.field})`;
29
+ stderr.write(`${line}\n`);
30
+ if (err.status === 429 && err.error === "throttled") {
31
+ stderr.write("The cluster hit its hourly send limit. Wait until the next hour before retrying.\n");
32
+ }
33
+ }