pinga-cli 0.0.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +232 -2
- package/dist/api.js +64 -0
- package/dist/cli.js +12 -0
- package/dist/command.js +36 -0
- package/dist/commands/auth.js +89 -0
- package/dist/commands/deliveries.js +139 -0
- package/dist/commands/domains.js +99 -0
- package/dist/commands/emails.js +187 -0
- package/dist/commands/templates.js +252 -0
- package/dist/commands/webhooks.js +116 -0
- package/dist/config.js +93 -0
- package/dist/context.js +100 -0
- package/dist/errors.js +48 -0
- package/dist/format.js +24 -0
- package/dist/io.js +3 -0
- package/dist/main.js +190 -0
- package/dist/prompt.js +86 -0
- package/dist/render-error.js +77 -0
- package/dist/template-file.js +115 -0
- package/dist/version.js +2 -0
- package/package.json +51 -1
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { apiRequest, pathSegment } from "../api.js";
|
|
2
|
+
import { booleanFlag } from "../command.js";
|
|
3
|
+
import { CliError, ReportedFailure } from "../errors.js";
|
|
4
|
+
import { table } from "../format.js";
|
|
5
|
+
const VERIFIED = "verified";
|
|
6
|
+
export const domainsCheck = {
|
|
7
|
+
name: ["domains", "check"],
|
|
8
|
+
summary: "Estado da verificação (DKIM, SPF, DMARC) dos domínios remetentes",
|
|
9
|
+
help: `Uso: pinga domains check [domínio...] [--refresh]
|
|
10
|
+
|
|
11
|
+
Mostra o estado de cada domínio remetente: verificação de DKIM, SPF, DMARC e MX. Para domínio
|
|
12
|
+
ainda não verificado, lista os registros DNS que faltam configurar. Sem domínio, mostra todos.
|
|
13
|
+
|
|
14
|
+
Sai com código 1 se algum domínio mostrado não estiver verificado — serve de checagem no CI.
|
|
15
|
+
|
|
16
|
+
Opções:
|
|
17
|
+
--refresh antes de mostrar, pede à Pinga para reconsultar o DKIM no provedor e o DNS
|
|
18
|
+
(SPF, DMARC, MX). Exige chave com escopo total`,
|
|
19
|
+
options: {
|
|
20
|
+
refresh: { type: "boolean" },
|
|
21
|
+
},
|
|
22
|
+
positionals: { min: 0, max: Number.POSITIVE_INFINITY, names: "[domínio...]" },
|
|
23
|
+
async run(ctx, values, names) {
|
|
24
|
+
const all = await listDomains(ctx);
|
|
25
|
+
const wanted = names.map((name) => name.toLowerCase().replace(/\.$/, ""));
|
|
26
|
+
const missing = wanted.filter((name) => !all.some((domain) => domain.domain.toLowerCase() === name));
|
|
27
|
+
if (missing.length > 0) {
|
|
28
|
+
throw new CliError(`Domínio não encontrado nesta organização: ${missing.join(", ")}. Rode \`pinga domains check\` para ver todos.`);
|
|
29
|
+
}
|
|
30
|
+
const selected = wanted.length > 0 ? all.filter((domain) => wanted.includes(domain.domain.toLowerCase())) : all;
|
|
31
|
+
const refresh = booleanFlag(values, "refresh");
|
|
32
|
+
const domains = [];
|
|
33
|
+
for (const item of selected) {
|
|
34
|
+
if (refresh) {
|
|
35
|
+
await apiRequest(ctx, { method: "POST", path: `/v1/sender-domains/${pathSegment(item.id)}/verify`, idempotent: true });
|
|
36
|
+
domains.push(await apiRequest(ctx, { method: "POST", path: `/v1/sender-domains/${pathSegment(item.id)}/check-dns`, idempotent: true }));
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
domains.push(await apiRequest(ctx, { method: "GET", path: `/v1/sender-domains/${pathSegment(item.id)}` }));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const allVerified = domains.every((domain) => domain.status === VERIFIED);
|
|
43
|
+
if (ctx.json) {
|
|
44
|
+
ctx.outJson({ all_verified: allVerified, domains });
|
|
45
|
+
}
|
|
46
|
+
else if (domains.length === 0) {
|
|
47
|
+
ctx.err("Nenhum domínio remetente cadastrado. Cadastre um no painel, em Configurações → Domínios.");
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
ctx.out(domains.map(describe).join("\n\n"));
|
|
51
|
+
}
|
|
52
|
+
if (!allVerified)
|
|
53
|
+
throw new ReportedFailure();
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
async function listDomains(ctx) {
|
|
57
|
+
const items = [];
|
|
58
|
+
let cursor;
|
|
59
|
+
for (;;) {
|
|
60
|
+
// O contrato declara `Cursor`/`Limit` em PascalCase; o binding do ASP.NET não diferencia caixa.
|
|
61
|
+
const page = await apiRequest(ctx, {
|
|
62
|
+
method: "GET",
|
|
63
|
+
path: "/v1/sender-domains",
|
|
64
|
+
query: { limit: 100, cursor },
|
|
65
|
+
});
|
|
66
|
+
items.push(...page.data);
|
|
67
|
+
if (!page.has_more || !page.next_cursor)
|
|
68
|
+
return items;
|
|
69
|
+
cursor = page.next_cursor;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function describe(domain) {
|
|
73
|
+
const lines = [`${domain.domain} ${domain.status}${domain.nickname ? ` (${domain.nickname})` : ""}${domain.managed ? " [gerenciado pela Pinga]" : ""}`];
|
|
74
|
+
lines.push(` DKIM ${domain.dkim.status} (${domain.dkim.tokens_count} chave(s))`);
|
|
75
|
+
for (const [label, check] of [["SPF", domain.spf], ["DMARC", domain.dmarc], ["MX", domain.mx]]) {
|
|
76
|
+
if (check)
|
|
77
|
+
lines.push(` ${label.padEnd(5)} ${check.status}${check.record ? ` ${check.record}` : ""}`);
|
|
78
|
+
}
|
|
79
|
+
if (domain.verified_at)
|
|
80
|
+
lines.push(` Verificado em ${domain.verified_at}`);
|
|
81
|
+
if (domain.last_checked_at)
|
|
82
|
+
lines.push(` Última checagem ${domain.last_checked_at}`);
|
|
83
|
+
if (domain.last_check_error)
|
|
84
|
+
lines.push(` Erro na última checagem: ${domain.last_check_error}`);
|
|
85
|
+
// Domínio pendente: todos os registros. Verificado: só o SPF/DMARC recomendado que a última checagem
|
|
86
|
+
// de DNS achou ausente ou em conflito (o DKIM já está resolvido).
|
|
87
|
+
const records = domain.status !== VERIFIED
|
|
88
|
+
? domain.dns_records
|
|
89
|
+
: domain.dns_records.filter((record) => {
|
|
90
|
+
const check = record.purpose === "spf_recommended" ? domain.spf : record.purpose === "dmarc_recommended" ? domain.dmarc : undefined;
|
|
91
|
+
return check != null && check.status !== "ok" && check.status !== "unknown";
|
|
92
|
+
});
|
|
93
|
+
if (records.length > 0) {
|
|
94
|
+
lines.push("", domain.status !== VERIFIED ? " Registros DNS a configurar:" : " Registros DNS recomendados:");
|
|
95
|
+
const rendered = table(["TIPO", "NOME", "VALOR", "PARA"], records.map((record) => [record.type, record.name, record.value, record.purpose ?? "dkim"]));
|
|
96
|
+
lines.push(...rendered.split("\n").map((line) => ` ${line}`));
|
|
97
|
+
}
|
|
98
|
+
return lines.join("\n");
|
|
99
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { booleanFlag, listFlag, parsePair, stringFlag } from "../command.js";
|
|
3
|
+
import { CliError, UsageError } from "../errors.js";
|
|
4
|
+
import { readAll } from "../prompt.js";
|
|
5
|
+
export const emailsSend = {
|
|
6
|
+
name: ["emails", "send"],
|
|
7
|
+
summary: "Envio transacional (HTML direto ou template com variáveis)",
|
|
8
|
+
help: `Uso: pinga emails send --to <email> (--template <slug> | --from <email> --subject <texto> --html <html>) [opções]
|
|
9
|
+
|
|
10
|
+
Enfileira um envio. A resposta diz que a Pinga aceitou o trabalho, não que o email chegou:
|
|
11
|
+
acompanhe com \`pinga deliveries get <delivery_id>\`.
|
|
12
|
+
|
|
13
|
+
Por template (a versão publicada; --test usa o rascunho):
|
|
14
|
+
pinga emails send --template boas_vindas --to ana@exemplo.com.br --var nome=Ana --category transactional
|
|
15
|
+
|
|
16
|
+
HTML direto:
|
|
17
|
+
pinga emails send --from no-reply@suaempresa.com.br --to ana@exemplo.com.br \\
|
|
18
|
+
--subject "Seu recibo" --html-file recibo.html --category transactional
|
|
19
|
+
|
|
20
|
+
Destinatário e remetente:
|
|
21
|
+
--to <email> destinatário (obrigatório)
|
|
22
|
+
--to-name <nome>
|
|
23
|
+
--from <email> remetente verificado (obrigatório no HTML direto; opcional no template)
|
|
24
|
+
--from-name <nome>
|
|
25
|
+
|
|
26
|
+
Template:
|
|
27
|
+
--template <slug> template pelo slug
|
|
28
|
+
--template-id <id> template pelo id
|
|
29
|
+
--var <chave=valor> variável de texto; repita para várias
|
|
30
|
+
--vars <json> variáveis como objeto JSON (números, listas, objetos)
|
|
31
|
+
--vars-file <arquivo> variáveis de um arquivo JSON
|
|
32
|
+
--test renderiza o rascunho em vez da versão publicada
|
|
33
|
+
|
|
34
|
+
HTML direto:
|
|
35
|
+
--subject <texto>
|
|
36
|
+
--html <html> | --html-file <arquivo> use "-" para ler da entrada padrão
|
|
37
|
+
--text <texto> | --text-file <arquivo> versão em texto puro (opcional)
|
|
38
|
+
|
|
39
|
+
Comum:
|
|
40
|
+
--category <slug> categoria de consentimento, obrigatória (ex.: transactional)
|
|
41
|
+
--header <Nome: valor> header extra; repita para vários
|
|
42
|
+
--idempotency-key <chave> chave de idempotência; prefira uma do seu domínio (ex.: pedido-123-recibo)`,
|
|
43
|
+
options: {
|
|
44
|
+
to: { type: "string" },
|
|
45
|
+
"to-name": { type: "string" },
|
|
46
|
+
from: { type: "string" },
|
|
47
|
+
"from-name": { type: "string" },
|
|
48
|
+
template: { type: "string" },
|
|
49
|
+
"template-id": { type: "string" },
|
|
50
|
+
var: { type: "string", multiple: true },
|
|
51
|
+
vars: { type: "string" },
|
|
52
|
+
"vars-file": { type: "string" },
|
|
53
|
+
test: { type: "boolean" },
|
|
54
|
+
subject: { type: "string" },
|
|
55
|
+
html: { type: "string" },
|
|
56
|
+
"html-file": { type: "string" },
|
|
57
|
+
text: { type: "string" },
|
|
58
|
+
"text-file": { type: "string" },
|
|
59
|
+
category: { type: "string" },
|
|
60
|
+
header: { type: "string", multiple: true },
|
|
61
|
+
"idempotency-key": { type: "string" },
|
|
62
|
+
},
|
|
63
|
+
positionals: { min: 0, max: 0 },
|
|
64
|
+
async run(ctx, values) {
|
|
65
|
+
const params = await buildSendParams(ctx, values);
|
|
66
|
+
const pinga = await ctx.client();
|
|
67
|
+
const response = await pinga.emails.send(params, {
|
|
68
|
+
test: booleanFlag(values, "test") || undefined,
|
|
69
|
+
idempotencyKey: stringFlag(values, "idempotency-key"),
|
|
70
|
+
});
|
|
71
|
+
if (ctx.json) {
|
|
72
|
+
ctx.outJson(response);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
ctx.out(`Envio aceito: ${response.delivery_id} (${response.status})`);
|
|
76
|
+
if (response.blocked_reason)
|
|
77
|
+
ctx.out(`Bloqueado: ${response.blocked_reason}`);
|
|
78
|
+
ctx.err(`Acompanhe com: pinga deliveries get ${response.delivery_id}`);
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
export async function buildSendParams(ctx, values) {
|
|
82
|
+
const to = stringFlag(values, "to", true);
|
|
83
|
+
const toName = stringFlag(values, "to-name");
|
|
84
|
+
const fromAddress = stringFlag(values, "from");
|
|
85
|
+
const from = fromAddress ? { address: fromAddress, name: stringFlag(values, "from-name") } : undefined;
|
|
86
|
+
const headers = parseHeaders(listFlag(values, "header"));
|
|
87
|
+
const category = stringFlag(values, "category");
|
|
88
|
+
const slug = stringFlag(values, "template");
|
|
89
|
+
const templateId = stringFlag(values, "template-id");
|
|
90
|
+
const isTemplate = slug !== undefined || templateId !== undefined;
|
|
91
|
+
if (isTemplate) {
|
|
92
|
+
if (slug && templateId)
|
|
93
|
+
throw new UsageError("Use --template ou --template-id, não os dois.");
|
|
94
|
+
for (const flag of ["subject", "html", "html-file", "text", "text-file"]) {
|
|
95
|
+
if (values[flag] !== undefined) {
|
|
96
|
+
throw new UsageError(`--${flag} não vale com template: assunto e corpo vêm do template.`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
template: slug ? { slug } : { id: templateId },
|
|
101
|
+
recipient: { email: to, name: toName },
|
|
102
|
+
variables: await parseVariables(ctx, values),
|
|
103
|
+
from,
|
|
104
|
+
headers,
|
|
105
|
+
category,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
if (booleanFlag(values, "test"))
|
|
109
|
+
throw new UsageError("--test só vale com --template ou --template-id.");
|
|
110
|
+
for (const flag of ["var", "vars", "vars-file"]) {
|
|
111
|
+
if (values[flag] !== undefined)
|
|
112
|
+
throw new UsageError(`--${flag} só vale com --template ou --template-id.`);
|
|
113
|
+
}
|
|
114
|
+
if (!from)
|
|
115
|
+
throw new UsageError("Informe --template, ou --from com --subject e --html para o HTML direto.");
|
|
116
|
+
const html = await textSource(ctx, values, "html");
|
|
117
|
+
if (html === undefined)
|
|
118
|
+
throw new UsageError("--html ou --html-file é obrigatório no HTML direto.");
|
|
119
|
+
return {
|
|
120
|
+
from,
|
|
121
|
+
to: { address: to, name: toName },
|
|
122
|
+
subject: stringFlag(values, "subject", true),
|
|
123
|
+
html,
|
|
124
|
+
text: await textSource(ctx, values, "text"),
|
|
125
|
+
headers,
|
|
126
|
+
category,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
async function textSource(ctx, values, name) {
|
|
130
|
+
const inline = stringFlag(values, name);
|
|
131
|
+
const file = stringFlag(values, `${name}-file`);
|
|
132
|
+
if (inline !== undefined && file !== undefined)
|
|
133
|
+
throw new UsageError(`Use --${name} ou --${name}-file, não os dois.`);
|
|
134
|
+
if (file !== undefined)
|
|
135
|
+
return readInput(ctx, file);
|
|
136
|
+
return inline;
|
|
137
|
+
}
|
|
138
|
+
async function readInput(ctx, file) {
|
|
139
|
+
if (file === "-")
|
|
140
|
+
return readAll(ctx.io.stdin);
|
|
141
|
+
try {
|
|
142
|
+
return await readFile(file, "utf8");
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
throw new CliError(`Não consegui ler ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async function parseVariables(ctx, values) {
|
|
149
|
+
const inline = stringFlag(values, "vars");
|
|
150
|
+
const file = stringFlag(values, "vars-file");
|
|
151
|
+
if (inline !== undefined && file !== undefined)
|
|
152
|
+
throw new UsageError("Use --vars ou --vars-file, não os dois.");
|
|
153
|
+
let variables = {};
|
|
154
|
+
if (inline !== undefined)
|
|
155
|
+
variables = parseObject(inline, "--vars");
|
|
156
|
+
if (file !== undefined)
|
|
157
|
+
variables = parseObject(await readInput(ctx, file), file);
|
|
158
|
+
// --var vem depois: sobrescreve a mesma chave vinda do JSON.
|
|
159
|
+
for (const raw of listFlag(values, "var")) {
|
|
160
|
+
const [key, value] = parsePair(raw, "var");
|
|
161
|
+
variables[key] = value;
|
|
162
|
+
}
|
|
163
|
+
return Object.keys(variables).length > 0 ? variables : undefined;
|
|
164
|
+
}
|
|
165
|
+
function parseObject(text, source) {
|
|
166
|
+
let parsed;
|
|
167
|
+
try {
|
|
168
|
+
parsed = JSON.parse(text);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
throw new UsageError(`${source} não é um JSON válido.`);
|
|
172
|
+
}
|
|
173
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
174
|
+
throw new UsageError(`${source} precisa ser um objeto JSON ({"nome": "Ana"}).`);
|
|
175
|
+
}
|
|
176
|
+
return parsed;
|
|
177
|
+
}
|
|
178
|
+
function parseHeaders(raw) {
|
|
179
|
+
if (raw.length === 0)
|
|
180
|
+
return undefined;
|
|
181
|
+
const headers = {};
|
|
182
|
+
for (const item of raw) {
|
|
183
|
+
const [name, value] = parsePair(item, "header", /:\s*|=/);
|
|
184
|
+
headers[name] = value.trim();
|
|
185
|
+
}
|
|
186
|
+
return headers;
|
|
187
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { PingaError } from "@pinga/sdk";
|
|
4
|
+
import { booleanFlag, stringFlag } from "../command.js";
|
|
5
|
+
import { CliError, ReportedFailure } from "../errors.js";
|
|
6
|
+
import { escapeSlug, quoteSlug } from "../format.js";
|
|
7
|
+
import { renderError } from "../render-error.js";
|
|
8
|
+
import { diff, importParams, kindOf, parseTemplateFile, serialize, TEMPLATE_FILE, toFile, updateParams, } from "../template-file.js";
|
|
9
|
+
const DEFAULT_DIR = "templates";
|
|
10
|
+
const SAFE_SLUG = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
|
|
11
|
+
export const templatesPull = {
|
|
12
|
+
name: ["templates", "pull"],
|
|
13
|
+
summary: "Baixa templates como arquivos (um diretório por slug)",
|
|
14
|
+
help: `Uso: pinga templates pull [slug...] [--dir <diretório>] [--include-archived]
|
|
15
|
+
|
|
16
|
+
Grava a versão ativa de cada template em <diretório>/<slug>/template.json, no envelope
|
|
17
|
+
pinga.template.v1 do export (sem o exported_at, para o git só mostrar mudança de verdade).
|
|
18
|
+
Sem slug, baixa todos os templates não arquivados.
|
|
19
|
+
|
|
20
|
+
Opções:
|
|
21
|
+
--dir <diretório> destino (padrão: ${DEFAULT_DIR})
|
|
22
|
+
--include-archived inclui os arquivados (só sem slug)`,
|
|
23
|
+
options: {
|
|
24
|
+
dir: { type: "string" },
|
|
25
|
+
"include-archived": { type: "boolean" },
|
|
26
|
+
},
|
|
27
|
+
positionals: { min: 0, max: Number.POSITIVE_INFINITY, names: "[slug...]" },
|
|
28
|
+
async run(ctx, values, slugs) {
|
|
29
|
+
const dir = stringFlag(values, "dir") ?? DEFAULT_DIR;
|
|
30
|
+
const pinga = await ctx.client();
|
|
31
|
+
const targets = [];
|
|
32
|
+
if (slugs.length > 0) {
|
|
33
|
+
for (const slug of slugs) {
|
|
34
|
+
const template = await pinga.templates.getBySlug(slug);
|
|
35
|
+
targets.push({ id: template.id, slug: template.slug });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
const includeArchived = booleanFlag(values, "include-archived");
|
|
40
|
+
for await (const item of pinga.templates.list({ limit: 100, include_archived: includeArchived || undefined })) {
|
|
41
|
+
targets.push({ id: item.id, slug: item.slug });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
// Valida todos os slugs antes da primeira escrita: um slug inválido no meio não deixa o
|
|
45
|
+
// diretório com metade dos templates gravada.
|
|
46
|
+
const invalid = targets.filter((target) => !SAFE_SLUG.test(target.slug)).map((target) => target.slug);
|
|
47
|
+
if (invalid.length > 0) {
|
|
48
|
+
throw new CliError(`Slug ${invalid.map((slug) => quoteSlug(slug)).join(", ")} não serve como nome de diretório; nada foi gravado. Baixe com outro nome à mão.`);
|
|
49
|
+
}
|
|
50
|
+
const results = [];
|
|
51
|
+
for (const target of targets) {
|
|
52
|
+
const file = toFile(await pinga.templates.export(target.id));
|
|
53
|
+
const filePath = path.join(dir, target.slug, TEMPLATE_FILE);
|
|
54
|
+
const text = serialize(file);
|
|
55
|
+
const current = await readFile(filePath, "utf8").catch(() => undefined);
|
|
56
|
+
const status = current === text ? "unchanged" : "written";
|
|
57
|
+
if (status === "written") {
|
|
58
|
+
await mkdir(path.dirname(filePath), { recursive: true });
|
|
59
|
+
await writeFile(filePath, text);
|
|
60
|
+
}
|
|
61
|
+
results.push({ slug: target.slug, version: file.version_data.version ?? null, path: filePath, status });
|
|
62
|
+
}
|
|
63
|
+
if (ctx.json) {
|
|
64
|
+
ctx.outJson({ dir, templates: results });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (results.length === 0) {
|
|
68
|
+
ctx.err("Nenhum template encontrado.");
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
for (const result of results) {
|
|
72
|
+
const version = result.version != null ? ` v${result.version}` : "";
|
|
73
|
+
ctx.out(`${result.status === "written" ? "↓" : "="} ${escapeSlug(result.slug)}${version} ${result.path}${result.status === "unchanged" ? " (sem mudanças)" : ""}`);
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
export const templatesPush = {
|
|
78
|
+
name: ["templates", "push"],
|
|
79
|
+
summary: "Publica templates a partir dos arquivos",
|
|
80
|
+
help: `Uso: pinga templates push [caminho...] [--dir <diretório>] [--dry-run] [--message <texto>]
|
|
81
|
+
|
|
82
|
+
Para cada template.json:
|
|
83
|
+
- slug que não existe na Pinga: importa (vira a versão 1);
|
|
84
|
+
- slug que existe: compara com a versão ativa. Igual, não faz nada. Diferente, grava o
|
|
85
|
+
rascunho e publica a próxima versão. Se só mudaram nome, descrição ou remetente, atualiza
|
|
86
|
+
o template sem criar versão.
|
|
87
|
+
|
|
88
|
+
Num template visual (com "document"), só o document e as variáveis contam: subject, mjml e
|
|
89
|
+
text_body são derivados dele e são ignorados no push.
|
|
90
|
+
|
|
91
|
+
Caminho pode ser um template.json, o diretório de um slug ou um diretório com vários slugs.
|
|
92
|
+
Sem caminho, usa --dir.
|
|
93
|
+
|
|
94
|
+
Opções:
|
|
95
|
+
--dir <diretório> origem (padrão: ${DEFAULT_DIR})
|
|
96
|
+
--dry-run mostra o que mudaria, sem escrever nada
|
|
97
|
+
--message <texto> resumo da mudança gravado na versão publicada`,
|
|
98
|
+
options: {
|
|
99
|
+
dir: { type: "string" },
|
|
100
|
+
"dry-run": { type: "boolean" },
|
|
101
|
+
message: { type: "string" },
|
|
102
|
+
},
|
|
103
|
+
positionals: { min: 0, max: Number.POSITIVE_INFINITY, names: "[caminho...]" },
|
|
104
|
+
async run(ctx, values, paths) {
|
|
105
|
+
const roots = paths.length > 0 ? paths : [stringFlag(values, "dir") ?? DEFAULT_DIR];
|
|
106
|
+
const files = await findTemplateFiles(roots);
|
|
107
|
+
if (files.length === 0)
|
|
108
|
+
throw new CliError(`Nenhum ${TEMPLATE_FILE} encontrado em ${roots.join(", ")}.`);
|
|
109
|
+
const dryRun = booleanFlag(values, "dry-run");
|
|
110
|
+
const message = stringFlag(values, "message") ?? "pinga templates push";
|
|
111
|
+
const pinga = await ctx.client();
|
|
112
|
+
// Valida todos os arquivos antes de escrever qualquer coisa: um JSON quebrado no meio não deixa
|
|
113
|
+
// metade dos templates publicada.
|
|
114
|
+
const locals = [];
|
|
115
|
+
const seen = new Map();
|
|
116
|
+
for (const file of files) {
|
|
117
|
+
const local = parseTemplateFile(await readFile(file, "utf8"), file);
|
|
118
|
+
const other = seen.get(local.template.slug);
|
|
119
|
+
if (other)
|
|
120
|
+
throw new CliError(`Slug ${quoteSlug(local.template.slug)} aparece em ${other} e em ${file}.`);
|
|
121
|
+
seen.set(local.template.slug, file);
|
|
122
|
+
locals.push({ file, local });
|
|
123
|
+
}
|
|
124
|
+
const results = [];
|
|
125
|
+
for (const { file, local } of locals) {
|
|
126
|
+
try {
|
|
127
|
+
results.push(await pushOne(pinga, file, local, { dryRun, message }));
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
const rendered = renderError(error);
|
|
131
|
+
results.push({
|
|
132
|
+
slug: local.template.slug,
|
|
133
|
+
path: file,
|
|
134
|
+
action: "failed",
|
|
135
|
+
version: null,
|
|
136
|
+
changes: null,
|
|
137
|
+
warnings: [],
|
|
138
|
+
error: rendered.json.error,
|
|
139
|
+
});
|
|
140
|
+
if (!ctx.json)
|
|
141
|
+
ctx.err(`✗ ${escapeSlug(local.template.slug)} (${file})\n${rendered.lines.map((line) => ` ${line}`).join("\n")}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
report(ctx, results, dryRun);
|
|
145
|
+
if (results.some((result) => result.action === "failed"))
|
|
146
|
+
throw new ReportedFailure();
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
async function pushOne(pinga, file, local, options) {
|
|
150
|
+
const slug = local.template.slug;
|
|
151
|
+
const base = { slug, path: file, warnings: [] };
|
|
152
|
+
const dirName = path.basename(path.dirname(file));
|
|
153
|
+
if (path.basename(file) === TEMPLATE_FILE && dirName !== slug && dirName !== ".") {
|
|
154
|
+
base.warnings.push(`o diretório ${quoteSlug(dirName)} não tem o nome do slug ${quoteSlug(slug)}; vale o slug do arquivo.`);
|
|
155
|
+
}
|
|
156
|
+
const existing = await findBySlug(pinga, slug);
|
|
157
|
+
if (!existing) {
|
|
158
|
+
if (options.dryRun)
|
|
159
|
+
return { ...base, action: "created", version: 1, changes: null };
|
|
160
|
+
const imported = await pinga.templates.import(importParams(local));
|
|
161
|
+
return {
|
|
162
|
+
...base,
|
|
163
|
+
action: "created",
|
|
164
|
+
version: imported.template.active_version?.version ?? 1,
|
|
165
|
+
changes: null,
|
|
166
|
+
warnings: [...base.warnings, ...imported.warnings],
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
const remote = toFile(await pinga.templates.export(existing.id));
|
|
170
|
+
const activeVersion = remote.version_data.version ?? null;
|
|
171
|
+
if (kindOf(local) !== kindOf(remote)) {
|
|
172
|
+
throw new CliError(`o arquivo é um template ${kindOf(local) === "visual" ? "visual (com document)" : "cru (sem document)"}, e o da Pinga é ${kindOf(remote) === "visual" ? "visual" : "cru"}. O tipo é fixo na criação.`);
|
|
173
|
+
}
|
|
174
|
+
const changes = diff(local, remote);
|
|
175
|
+
if (changes.metadata.length === 0 && changes.content.length === 0) {
|
|
176
|
+
return { ...base, action: "unchanged", version: activeVersion, changes };
|
|
177
|
+
}
|
|
178
|
+
const publishes = changes.content.length > 0;
|
|
179
|
+
const action = publishes ? "published" : "metadata_updated";
|
|
180
|
+
if (options.dryRun) {
|
|
181
|
+
return { ...base, action, version: publishes && activeVersion != null ? activeVersion + 1 : activeVersion, changes };
|
|
182
|
+
}
|
|
183
|
+
await pinga.templates.update(existing.id, updateParams(local, remote, changes));
|
|
184
|
+
if (!publishes)
|
|
185
|
+
return { ...base, action, version: activeVersion, changes };
|
|
186
|
+
const published = await pinga.templates.publish(existing.id, { change_summary: options.message });
|
|
187
|
+
return { ...base, action, version: published.active_version?.version ?? null, changes };
|
|
188
|
+
}
|
|
189
|
+
async function findBySlug(pinga, slug) {
|
|
190
|
+
try {
|
|
191
|
+
return await pinga.templates.getBySlug(slug);
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
if (error instanceof PingaError && error.status === 404)
|
|
195
|
+
return undefined;
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** `template.json` direto, diretório de um slug, ou diretório com um subdiretório por slug. */
|
|
200
|
+
async function findTemplateFiles(roots) {
|
|
201
|
+
const found = [];
|
|
202
|
+
for (const root of roots) {
|
|
203
|
+
const info = await stat(root).catch(() => undefined);
|
|
204
|
+
if (!info)
|
|
205
|
+
throw new CliError(`${root} não existe.`);
|
|
206
|
+
if (info.isFile()) {
|
|
207
|
+
found.push(root);
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const direct = path.join(root, TEMPLATE_FILE);
|
|
211
|
+
if (await stat(direct).then((s) => s.isFile()).catch(() => false)) {
|
|
212
|
+
found.push(direct);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const entries = await readdir(root, { withFileTypes: true });
|
|
216
|
+
for (const entry of entries.filter((item) => item.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
217
|
+
const candidate = path.join(root, entry.name, TEMPLATE_FILE);
|
|
218
|
+
if (await stat(candidate).then((s) => s.isFile()).catch(() => false))
|
|
219
|
+
found.push(candidate);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return found;
|
|
223
|
+
}
|
|
224
|
+
const LABELS = {
|
|
225
|
+
unchanged: { symbol: "=", done: "sem mudanças", planned: "sem mudanças" },
|
|
226
|
+
created: { symbol: "+", done: "criado", planned: "seria criado" },
|
|
227
|
+
published: { symbol: "~", done: "publicado", planned: "seria publicado" },
|
|
228
|
+
metadata_updated: { symbol: "~", done: "metadados atualizados", planned: "teria os metadados atualizados" },
|
|
229
|
+
failed: { symbol: "✗", done: "falhou", planned: "falhou" },
|
|
230
|
+
};
|
|
231
|
+
function report(ctx, results, dryRun) {
|
|
232
|
+
if (ctx.json) {
|
|
233
|
+
ctx.outJson({ dry_run: dryRun, templates: results });
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
for (const result of results) {
|
|
237
|
+
if (result.action === "failed")
|
|
238
|
+
continue;
|
|
239
|
+
const label = LABELS[result.action];
|
|
240
|
+
const version = result.version != null ? ` (v${result.version})` : "";
|
|
241
|
+
const fields = result.changes ? [...result.changes.metadata, ...result.changes.content] : [];
|
|
242
|
+
const detail = fields.length > 0 && result.action !== "unchanged" ? `: ${fields.join(", ")}` : "";
|
|
243
|
+
ctx.out(`${label.symbol} ${escapeSlug(result.slug)} ${dryRun ? label.planned : label.done}${version}${detail}`);
|
|
244
|
+
for (const warning of result.warnings)
|
|
245
|
+
ctx.err(` aviso: ${warning}`);
|
|
246
|
+
}
|
|
247
|
+
const failed = results.filter((result) => result.action === "failed").length;
|
|
248
|
+
if (failed > 0)
|
|
249
|
+
ctx.err(`${failed} de ${results.length} template(s) falharam.`);
|
|
250
|
+
if (dryRun)
|
|
251
|
+
ctx.err("--dry-run: nada foi escrito.");
|
|
252
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { constructWebhookEvent, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, PingaWebhookVerificationError } from "@pinga/sdk";
|
|
3
|
+
import { booleanFlag, integerFlag, listFlag, stringFlag } from "../command.js";
|
|
4
|
+
import { CliError, ReportedFailure, UsageError } from "../errors.js";
|
|
5
|
+
import { readAllBytes } from "../prompt.js";
|
|
6
|
+
export const webhooksVerify = {
|
|
7
|
+
name: ["webhooks", "verify"],
|
|
8
|
+
summary: "Confere a assinatura de um webhook (corpo, header e segredo)",
|
|
9
|
+
help: `Uso: pinga webhooks verify --signature <header> (--payload <corpo> | --payload-file <arquivo>) [opções]
|
|
10
|
+
|
|
11
|
+
Confere o header X-Webhook-Signature contra o corpo bruto e o segredo do webhook, do mesmo jeito
|
|
12
|
+
que o seu endpoint deve conferir. Não chama a API: tudo acontece localmente.
|
|
13
|
+
|
|
14
|
+
pinga webhooks verify --payload-file corpo.json \\
|
|
15
|
+
--signature "t=1764950000,v1=5257a8..." --secret-file segredo.txt
|
|
16
|
+
|
|
17
|
+
Segredo (whsec_...); as fontes se somam, e a assinatura vale se conferir com qualquer um:
|
|
18
|
+
PINGA_WEBHOOK_SECRET no ambiente
|
|
19
|
+
--secret-file <arquivo> primeira linha do arquivo
|
|
20
|
+
--secret <segredo> na linha de comando (fica no histórico do shell)
|
|
21
|
+
Na rotação, passe o novo e o antigo (ex.: repetindo --secret).
|
|
22
|
+
|
|
23
|
+
Opções:
|
|
24
|
+
--signature <header> valor do header X-Webhook-Signature (obrigatório)
|
|
25
|
+
--payload <corpo> corpo bruto, exatamente como chegou
|
|
26
|
+
--payload-file <arquivo> corpo bruto de um arquivo; "-" lê da entrada padrão
|
|
27
|
+
--tolerance <segundos> diferença máxima entre o t= da assinatura e agora (padrão ${DEFAULT_WEBHOOK_TOLERANCE_SECONDS})
|
|
28
|
+
--ignore-timestamp não confere o horário (útil para um corpo capturado há tempo)
|
|
29
|
+
|
|
30
|
+
Sai com código 0 se a assinatura confere e 1 se não confere.`,
|
|
31
|
+
options: {
|
|
32
|
+
signature: { type: "string" },
|
|
33
|
+
payload: { type: "string" },
|
|
34
|
+
"payload-file": { type: "string" },
|
|
35
|
+
secret: { type: "string", multiple: true },
|
|
36
|
+
"secret-file": { type: "string" },
|
|
37
|
+
tolerance: { type: "string" },
|
|
38
|
+
"ignore-timestamp": { type: "boolean" },
|
|
39
|
+
},
|
|
40
|
+
positionals: { min: 0, max: 0 },
|
|
41
|
+
async run(ctx, values) {
|
|
42
|
+
const signature = stringFlag(values, "signature", true);
|
|
43
|
+
const secrets = await readSecrets(values, ctx.io.env["PINGA_WEBHOOK_SECRET"]);
|
|
44
|
+
for (const secret of secrets)
|
|
45
|
+
ctx.rememberSecret(secret, { anyLength: true });
|
|
46
|
+
const inline = stringFlag(values, "payload");
|
|
47
|
+
const file = stringFlag(values, "payload-file");
|
|
48
|
+
if ((inline === undefined) === (file === undefined))
|
|
49
|
+
throw new UsageError("Informe --payload ou --payload-file (um dos dois).");
|
|
50
|
+
// O corpo vai como bytes, sem nenhuma conversão: um \n a mais ou a menos muda o HMAC.
|
|
51
|
+
const payload = inline !== undefined ? inline : file === "-" ? await readAllBytes(ctx.io.stdin) : await readBytes(file);
|
|
52
|
+
if (booleanFlag(values, "ignore-timestamp") && values["tolerance"] !== undefined) {
|
|
53
|
+
throw new UsageError("Use --tolerance ou --ignore-timestamp, não os dois.");
|
|
54
|
+
}
|
|
55
|
+
const toleranceSeconds = booleanFlag(values, "ignore-timestamp")
|
|
56
|
+
? Number.POSITIVE_INFINITY
|
|
57
|
+
: integerFlag(values, "tolerance", { min: 0, max: 31_536_000 });
|
|
58
|
+
try {
|
|
59
|
+
const event = await constructWebhookEvent({ payload, signature, secret: secrets, toleranceSeconds });
|
|
60
|
+
if (typeof event !== "object" || event === null || Array.isArray(event) || typeof event.type !== "string") {
|
|
61
|
+
throw new CliError("A assinatura confere, mas o corpo não é um evento de webhook (esperava um objeto JSON com \"type\").");
|
|
62
|
+
}
|
|
63
|
+
if (ctx.json) {
|
|
64
|
+
ctx.outJson({ valid: true, event });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
ctx.out(`Assinatura válida: evento ${event.type} (${event.id}), criado em ${event.created_at}.`);
|
|
68
|
+
if (event.data?.delivery?.id)
|
|
69
|
+
ctx.out(`Entrega: ${event.data.delivery.id} (${event.data.delivery.status})`);
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (!(error instanceof PingaWebhookVerificationError)) {
|
|
73
|
+
throw error instanceof SyntaxError ? new CliError("A assinatura confere, mas o corpo não é JSON válido.") : error;
|
|
74
|
+
}
|
|
75
|
+
if (ctx.json) {
|
|
76
|
+
ctx.outJson({ valid: false, reason: error.reason, message: error.message });
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
ctx.err(`Assinatura inválida: ${error.message} (${error.reason}).`);
|
|
80
|
+
if (error.reason === "timestamp_out_of_tolerance") {
|
|
81
|
+
ctx.err("Para um corpo capturado há mais tempo, use --ignore-timestamp.");
|
|
82
|
+
}
|
|
83
|
+
if (error.reason === "signature_mismatch") {
|
|
84
|
+
ctx.err("Confira se o corpo é o bruto (sem reformatar o JSON) e se o segredo é o atual.");
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
throw new ReportedFailure();
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
async function readSecrets(values, fromEnv) {
|
|
92
|
+
const secrets = [...listFlag(values, "secret")];
|
|
93
|
+
const file = stringFlag(values, "secret-file");
|
|
94
|
+
if (file !== undefined) {
|
|
95
|
+
const text = await readFile(file, "utf8").catch((error) => {
|
|
96
|
+
throw new CliError(`Não consegui ler ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
97
|
+
});
|
|
98
|
+
const firstLine = text.split(/\r?\n/)[0]?.trim();
|
|
99
|
+
if (firstLine)
|
|
100
|
+
secrets.push(firstLine);
|
|
101
|
+
}
|
|
102
|
+
if (fromEnv)
|
|
103
|
+
secrets.push(fromEnv);
|
|
104
|
+
if (secrets.length === 0) {
|
|
105
|
+
throw new UsageError("Informe o segredo: PINGA_WEBHOOK_SECRET, --secret-file ou --secret.");
|
|
106
|
+
}
|
|
107
|
+
return secrets;
|
|
108
|
+
}
|
|
109
|
+
async function readBytes(file) {
|
|
110
|
+
try {
|
|
111
|
+
return new Uint8Array(await readFile(file));
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
throw new CliError(`Não consegui ler ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
115
|
+
}
|
|
116
|
+
}
|