fix: add cookie auth for /configs UI

This commit is contained in:
Andre RDS
2026-11-25 15:20:12 -03:00
parent 6e8e640738
commit da10e17a56
8 changed files with 101 additions and 12 deletions
+2 -1
View File
@@ -1,3 +1,4 @@
{"version":1,"entries":[ {"version":1,"entries":[
{"seq":0,"length":1,"headHash":"sha256:1f37ae430183478bd062ed44c95aed99e2cf41411ceba9399a3d2d791c325ac1","prevAnchorHash":null,"ts":1795565092319,"event":"append","hash":"41573faa4dc29b0a0ac25597d2a60f7fd35e8daf2fc895e5ea20ea4c0bfcfd41"} {"seq":0,"length":1,"headHash":"sha256:1f37ae430183478bd062ed44c95aed99e2cf41411ceba9399a3d2d791c325ac1","prevAnchorHash":null,"ts":1795565092319,"event":"append","hash":"41573faa4dc29b0a0ac25597d2a60f7fd35e8daf2fc895e5ea20ea4c0bfcfd41"},
{"seq":1,"length":2,"headHash":"sha256:f19ebaa4267d08a8be1a3d45cd71067ed0b23ad8df22bce526604f15abf2631d","prevAnchorHash":"41573faa4dc29b0a0ac25597d2a60f7fd35e8daf2fc895e5ea20ea4c0bfcfd41","ts":1795610841630,"event":"append","hash":"88c060b098fcbc163f153a2f8f3034eab7d2adf6d6ee60dc7ed23a8227105610"}
]} ]}
+42 -2
View File
@@ -45,10 +45,50 @@
"policyHash": "sha256:00b63b2f746eb8b9095bbd5e1dbae4ddd74fd92a6740b72f59f4069fbfda4737" "policyHash": "sha256:00b63b2f746eb8b9095bbd5e1dbae4ddd74fd92a6740b72f59f4069fbfda4737"
}, },
"hash": "sha256:1f37ae430183478bd062ed44c95aed99e2cf41411ceba9399a3d2d791c325ac1" "hash": "sha256:1f37ae430183478bd062ed44c95aed99e2cf41411ceba9399a3d2d791c325ac1"
},
{
"payload": {
"receiptId": "sha256:a471691910453cd550f8fb7c9f7b623678eb37913f83f5b0387b99f5dc9b5f7e",
"previousReceiptHash": "sha256:1f37ae430183478bd062ed44c95aed99e2cf41411ceba9399a3d2d791c325ac1",
"sequence": 1,
"issuedAt": 1795610841608,
"request": {
"identity": {
"id": "legacy-cli",
"type": "legacy"
},
"action": {
"type": "mcp.tool.call",
"resource": "hooks_session-end",
"tool": "hooks_session-end",
"server": "ruflo",
"network": false,
"destructive": false
},
"context": {
"metadata": {
"inputDigest": "sha256:b18d3d7aab7ec5c7c4cbdef7780a0fe22eeacf9f769e86fdedf6f5d8931c27b4"
},
"now": 1795610841608
},
"requestId": "2a755f6b-44b2-4ece-8219-ccd029a58cb7"
},
"decision": {
"requestId": "2a755f6b-44b2-4ece-8219-ccd029a58cb7",
"outcome": "allowed",
"enforcedOutcome": "allowed",
"mode": "legacy",
"reason": "legacy-default-allow",
"matchedRules": [],
"obligations": []
},
"policyHash": "sha256:00b63b2f746eb8b9095bbd5e1dbae4ddd74fd92a6740b72f59f4069fbfda4737"
},
"hash": "sha256:f19ebaa4267d08a8be1a3d45cd71067ed0b23ad8df22bce526604f15abf2631d"
} }
], ],
"migratedAt": 1795565092281, "migratedAt": 1795565092281,
"migratedFrom": "pre-ADR-324; capabilities=none-detected", "migratedFrom": "pre-ADR-324; capabilities=none-detected",
"ledgerHead": "sha256:1f37ae430183478bd062ed44c95aed99e2cf41411ceba9399a3d2d791c325ac1", "ledgerLength": 2,
"ledgerLength": 1 "ledgerHead": "sha256:f19ebaa4267d08a8be1a3d45cd71067ed0b23ad8df22bce526604f15abf2631d"
} }
+33 -1
View File
@@ -154,8 +154,40 @@ export function createApp(deps: AppDependencies) {
return c.html(renderSettingsHtml()); return c.html(renderSettingsHtml());
}); });
// API de configs para a UI // Auth state (cookie simples)
const AUTH_COOKIE = "tw_auth";
const AUTH_VALUE = "ok";
// Login
app.post("/api/v1/configs/auth", async (c) => {
const body = await c.req.json();
const key = body?.secretKey?.trim();
if (key === config.API_SECRET_KEY) {
c.header("Set-Cookie", `${AUTH_COOKIE}=${AUTH_VALUE}; HttpOnly; Path=/; SameSite=Lax; Max-Age=86400`);
return c.json({ authenticated: true });
}
return c.json({ authenticated: false, error: "Secret Key inválida" }, 401);
});
// Check auth
app.get("/api/v1/configs/me", (c) => {
const cookie = c.req.header("Cookie") || "";
const authed = cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`);
return c.json({ authenticated: authed });
});
// Logout
app.post("/api/v1/configs/logout", (c) => {
c.header("Set-Cookie", `${AUTH_COOKIE}=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0`);
return c.json({ ok: true });
});
// API de configs para a UI (protegida por cookie)
app.get("/api/v1/configs", async (c) => { app.get("/api/v1/configs", async (c) => {
const cookie = c.req.header("Cookie") || "";
if (!cookie.includes(`${AUTH_COOKIE}=${AUTH_VALUE}`)) {
return c.json({ authenticated: false }, 401);
}
// Retorna configs não-sensíveis para a UI // Retorna configs não-sensíveis para a UI
const settings = [ const settings = [
{ key: "POLL_INTERVAL_MS", value: String(config.POLL_INTERVAL_MS), category: "sync", label: "Intervalo de Verificação (ms)", type: "number" }, { key: "POLL_INTERVAL_MS", value: String(config.POLL_INTERVAL_MS), category: "sync", label: "Intervalo de Verificação (ms)", type: "number" },
+1 -1
View File
@@ -290,7 +290,7 @@ export function renderSettingsHtml(): string {
dot.className = 'health-dot ' + (healthy ? 'is-ok' : 'is-bad'); dot.className = 'health-dot ' + (healthy ? 'is-ok' : 'is-bad');
const text = document.createElement('div'); const text = document.createElement('div');
const name = document.createElement('strong'); const name = document.createElement('strong');
name.textContent = healthLabels[item.key as keyof typeof healthLabels] || item.key; name.textContent = healthLabels[item.key] || item.key;
const detail = document.createElement('small'); const detail = document.createElement('small');
detail.textContent = item.detail; detail.textContent = item.detail;
text.append(name, detail); text.append(name, detail);
@@ -77,13 +77,15 @@ export class NotificationService {
"", "",
]; ];
for (const a of alerts) { for (const a of alerts) {
const editUrl = `https://cms.rmscorretora.com.br/admin/tabelas/${a.table.id}/editar`;
lines.push( lines.push(
`📋 ${this.escapeHtml(a.table.title)}`, `📋 ${this.escapeHtml(a.table.title)}`,
` Operadora: ${a.table.operadora} • Vencimento: ${a.table.revision_date || "?"} • ${a.daysUntil} dia(s)`, ` Operadora: ${a.table.operadora} • Vencimento: ${a.table.revision_date || "?"} • ${a.daysUntil} dia(s)`,
` 🔗 ${editUrl}`,
"" ""
); );
} }
lines.push("💡 Acesse o CMS RMS para atualizar antes que expirem."); lines.push("💡 Clique nos links acima para editar as tabelas no CMS RMS.");
return lines.join("\n"); return lines.join("\n");
} }
@@ -92,14 +94,18 @@ export class NotificationService {
? `Venceu há ${Math.abs(alert.daysUntil)} dia(s)` ? `Venceu há ${Math.abs(alert.daysUntil)} dia(s)`
: alert.daysUntil === 0 ? "Vence HOJE" : `Vence em ${alert.daysUntil} dia(s)`; : alert.daysUntil === 0 ? "Vence HOJE" : `Vence em ${alert.daysUntil} dia(s)`;
const editUrl = `https://cms.rmscorretora.com.br/admin/tabelas/${alert.table.id}/editar`;
return [ return [
`🚨 <b>TABELA ${alert.severity.toUpperCase()}</b>`, `🚨 *TABELA ${alert.severity.toUpperCase()}*`,
`🏢 ${alert.table.operadora}`, `🏢 ${alert.table.operadora}`,
`📋 ${this.escapeHtml(alert.table.title)}`, `📋 ${this.escapeHtml(alert.table.title)}`,
`🆔 ${alert.table.id}`,
`📅 ${alert.table.revision_date || "Sem data"}`, `📅 ${alert.table.revision_date || "Sem data"}`,
`⏰ ${daysText}`, `⏰ ${daysText}`,
`🔗 ${editUrl}`,
"", "",
"Atualize no CMS RMS.", "Clique no link para editar no CMS RMS.",
].join("\n"); ].join("\n");
} }
@@ -128,6 +128,8 @@ export class TableService {
const data = await response.json(); const data = await response.json();
const now = new Date().toISOString(); const now = new Date().toISOString();
const cmsBaseUrl = config.CMS_API_URL.replace("/api", "");
return (data.data || []).map((item: any) => { return (data.data || []).map((item: any) => {
const produtosJson = item.produtos_json; const produtosJson = item.produtos_json;
const extractedAt = produtosJson?._meta?.extracted_at || null; const extractedAt = produtosJson?._meta?.extracted_at || null;
@@ -144,6 +146,7 @@ export class TableService {
status: "sem_data", // será calculado depois status: "sem_data", // será calculado depois
extracted_at: extractedAt, extracted_at: extractedAt,
last_checked: now, last_checked: now,
edit_url: `${cmsBaseUrl}/admin/tabelas/${item.id}/editar`,
}; };
return table; return table;
}); });
+1
View File
@@ -12,6 +12,7 @@ export interface TableInfo {
status: TableStatus; status: TableStatus;
extracted_at: string | null; // do _meta.extracted_at extracted_at: string | null; // do _meta.extracted_at
last_checked: string; // ISO timestamp last_checked: string; // ISO timestamp
edit_url?: string | null; // URL de edição no CMS
} }
export interface TableProdutosJson { export interface TableProdutosJson {
+10 -4
View File
@@ -3,6 +3,7 @@ import type { ExpiryAlert } from "../../domain/models/table.js";
export interface TableAlertFormatterOptions { export interface TableAlertFormatterOptions {
includePdfLink?: boolean; includePdfLink?: boolean;
includeCriticality?: boolean; includeCriticality?: boolean;
cmsBaseUrl?: string; // ex: https://cms.rmscorretora.com.br/admin/tabelas
} }
export class TableAlertFormatter { export class TableAlertFormatter {
@@ -12,6 +13,7 @@ export class TableAlertFormatter {
this.options = { this.options = {
includePdfLink: true, includePdfLink: true,
includeCriticality: true, includeCriticality: true,
cmsBaseUrl: "https://cms.rmscorretora.com.br/admin/tabelas",
...options, ...options,
}; };
} }
@@ -28,12 +30,16 @@ export class TableAlertFormatter {
? "Vence HOJE" ? "Vence HOJE"
: `Vence em ${alert.days_until_expiry} dia(s)`; : `Vence em ${alert.days_until_expiry} dia(s)`;
const editUrl = `${this.options.cmsBaseUrl}/${alert.table_id}/editar`;
const lines = [ const lines = [
`${severityIcon} <b>TABELA ${severityLabel}</b>`, `${severityIcon} <b>TABELA ${severityLabel}</b>`,
`🏢 <b>Operadora:</b> ${this.escapeHtml(alert.operadora)}`, `🏢 <b>Operadora:</b> ${this.escapeHtml(alert.operadora)}`,
`📋 <b>Tabela:</b> ${this.escapeHtml(alert.table_title)}`, `📋 <b>Tabela:</b> ${this.escapeHtml(alert.table_title)}`,
`🆔 <b>ID:</b> ${alert.table_id}`,
`📅 <b>Revisão/Vencimento:</b> ${this.escapeHtml(alert.revision_date)}`, `📅 <b>Revisão/Vencimento:</b> ${this.escapeHtml(alert.revision_date)}`,
`⏰ <b>Prazo:</b> ${daysText}`, `⏰ <b>Prazo:</b> ${daysText}`,
`🔗 <b>Editar:</b> <a href="${editUrl}">${editUrl}</a>`,
]; ];
if (alert.administradora) { if (alert.administradora) {
@@ -42,7 +48,7 @@ export class TableAlertFormatter {
lines.push( lines.push(
"", "",
`💡 <i>Verifique e atualize a tabela no CMS RMS antes que expire completamente.</i>` `💡 <i>Clique no link acima para editar a tabela no CMS RMS.</i>`
); );
return lines.join("\n"); return lines.join("\n");
@@ -65,8 +71,8 @@ export class TableAlertFormatter {
private escapeHtml(str?: string | null): string { private escapeHtml(str?: string | null): string {
if (!str) return ""; if (!str) return "";
return str return str
.replace(/&/g, "&amp;") .replace(/&/g, String.fromCharCode(38) + "amp;")
.replace(/</g, "&lt;") .replace(/</g, String.fromCharCode(38) + "lt;")
.replace(/>/g, "&gt;"); .replace(/>/g, String.fromCharCode(38) + "gt;");
} }
} }