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
+33 -1
View File
@@ -154,8 +154,40 @@ export function createApp(deps: AppDependencies) {
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) => {
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
const settings = [
{ 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');
const text = document.createElement('div');
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');
detail.textContent = item.detail;
text.append(name, detail);
@@ -77,13 +77,15 @@ export class NotificationService {
"",
];
for (const a of alerts) {
const editUrl = `https://cms.rmscorretora.com.br/admin/tabelas/${a.table.id}/editar`;
lines.push(
`📋 ${this.escapeHtml(a.table.title)}`,
` 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");
}
@@ -92,14 +94,18 @@ export class NotificationService {
? `Venceu há ${Math.abs(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 [
`🚨 <b>TABELA ${alert.severity.toUpperCase()}</b>`,
`🚨 *TABELA ${alert.severity.toUpperCase()}*`,
`🏢 ${alert.table.operadora}`,
`📋 ${this.escapeHtml(alert.table.title)}`,
`🆔 ${alert.table.id}`,
`📅 ${alert.table.revision_date || "Sem data"}`,
`⏰ ${daysText}`,
`🔗 ${editUrl}`,
"",
"Atualize no CMS RMS.",
"Clique no link para editar no CMS RMS.",
].join("\n");
}
@@ -128,6 +128,8 @@ export class TableService {
const data = await response.json();
const now = new Date().toISOString();
const cmsBaseUrl = config.CMS_API_URL.replace("/api", "");
return (data.data || []).map((item: any) => {
const produtosJson = item.produtos_json;
const extractedAt = produtosJson?._meta?.extracted_at || null;
@@ -144,6 +146,7 @@ export class TableService {
status: "sem_data", // será calculado depois
extracted_at: extractedAt,
last_checked: now,
edit_url: `${cmsBaseUrl}/admin/tabelas/${item.id}/editar`,
};
return table;
});
+1
View File
@@ -12,6 +12,7 @@ export interface TableInfo {
status: TableStatus;
extracted_at: string | null; // do _meta.extracted_at
last_checked: string; // ISO timestamp
edit_url?: string | null; // URL de edição no CMS
}
export interface TableProdutosJson {
+10 -4
View File
@@ -3,6 +3,7 @@ import type { ExpiryAlert } from "../../domain/models/table.js";
export interface TableAlertFormatterOptions {
includePdfLink?: boolean;
includeCriticality?: boolean;
cmsBaseUrl?: string; // ex: https://cms.rmscorretora.com.br/admin/tabelas
}
export class TableAlertFormatter {
@@ -12,6 +13,7 @@ export class TableAlertFormatter {
this.options = {
includePdfLink: true,
includeCriticality: true,
cmsBaseUrl: "https://cms.rmscorretora.com.br/admin/tabelas",
...options,
};
}
@@ -28,12 +30,16 @@ export class TableAlertFormatter {
? "Vence HOJE"
: `Vence em ${alert.days_until_expiry} dia(s)`;
const editUrl = `${this.options.cmsBaseUrl}/${alert.table_id}/editar`;
const lines = [
`${severityIcon} <b>TABELA ${severityLabel}</b>`,
`🏢 <b>Operadora:</b> ${this.escapeHtml(alert.operadora)}`,
`📋 <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>Prazo:</b> ${daysText}`,
`🔗 <b>Editar:</b> <a href="${editUrl}">${editUrl}</a>`,
];
if (alert.administradora) {
@@ -42,7 +48,7 @@ export class TableAlertFormatter {
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");
@@ -65,8 +71,8 @@ export class TableAlertFormatter {
private escapeHtml(str?: string | null): string {
if (!str) return "";
return str
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
.replace(/&/g, String.fromCharCode(38) + "amp;")
.replace(/</g, String.fromCharCode(38) + "lt;")
.replace(/>/g, String.fromCharCode(38) + "gt;");
}
}