feat: add forgejo git sync, rate-limited mailer and read-only recap services
This commit is contained in:
parent
31aab93068
commit
3ace08f297
3 changed files with 187 additions and 0 deletions
52
src/services/git.js
Normal file
52
src/services/git.js
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
// Clone / mise à jour des repos Forgejo. Clone superficiel (--depth 1) : léger sur le SSD.
|
||||||
|
// Le token passe par variables d'env GIT_CONFIG_* : jamais écrit dans .git/config, invisible dans `ps`.
|
||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import { existsSync, rmSync, mkdirSync } from 'node:fs';
|
||||||
|
import { dirname } from 'node:path';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
|
|
||||||
|
const run = promisify(execFile);
|
||||||
|
|
||||||
|
export function validateGitUrl(url, allowedHost) {
|
||||||
|
let u;
|
||||||
|
try { u = new URL(url); } catch { throw new Error('URL Git invalide'); }
|
||||||
|
if (u.protocol !== 'https:') throw new Error('Seules les URL https:// sont acceptées');
|
||||||
|
if (u.username || u.password) throw new Error("Ne mets pas d'identifiants dans l'URL, configure le token dans Réglages");
|
||||||
|
if (allowedHost && u.host !== allowedHost) throw new Error(`Le repo doit être sur ${allowedHost}`);
|
||||||
|
if (!/^\/[\w.-]+\/[\w.-]+?(\.git)?\/?$/.test(u.pathname)) throw new Error('Format attendu : https://hôte/utilisateur/repo.git');
|
||||||
|
return u.toString().replace(/\/$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function gitEnv(token) {
|
||||||
|
const env = { ...process.env, GIT_TERMINAL_PROMPT: '0' };
|
||||||
|
if (token) {
|
||||||
|
env.GIT_CONFIG_COUNT = '1';
|
||||||
|
env.GIT_CONFIG_KEY_0 = 'http.extraHeader';
|
||||||
|
env.GIT_CONFIG_VALUE_0 = `Authorization: token ${token}`;
|
||||||
|
}
|
||||||
|
return env;
|
||||||
|
}
|
||||||
|
|
||||||
|
const opts = (token, cwd) => ({ env: gitEnv(token), cwd, timeout: 5 * 60_000, maxBuffer: 1024 * 1024 });
|
||||||
|
|
||||||
|
// Clone ou met à jour. Retourne le hash du commit HEAD.
|
||||||
|
export async function syncRepo(url, dir, token) {
|
||||||
|
try {
|
||||||
|
if (existsSync(`${dir}/.git`)) {
|
||||||
|
await run('git', ['fetch', '--depth', '1', 'origin', 'HEAD'], opts(token, dir));
|
||||||
|
await run('git', ['reset', '--hard', 'FETCH_HEAD'], opts(token, dir));
|
||||||
|
} else {
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
mkdirSync(dirname(dir), { recursive: true });
|
||||||
|
await run('git', ['clone', '--depth', '1', '--single-branch', url, dir], opts(token));
|
||||||
|
}
|
||||||
|
const { stdout } = await run('git', ['rev-parse', 'HEAD'], opts(null, dir));
|
||||||
|
return stdout.trim();
|
||||||
|
} catch (e) {
|
||||||
|
// On ne remonte jamais stderr brut (pourrait contenir l'en-tête d'auth)
|
||||||
|
const msg = String(e.stderr || e.message).replace(/Authorization: token \S+/g, 'Authorization: ***');
|
||||||
|
throw new Error(`Git : ${msg.split('\n').filter(Boolean).slice(-2).join(' ')}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeRepo(dir) { rmSync(dir, { recursive: true, force: true }); }
|
||||||
59
src/services/mailer.js
Normal file
59
src/services/mailer.js
Normal file
|
|
@ -0,0 +1,59 @@
|
||||||
|
import nodemailer from 'nodemailer';
|
||||||
|
|
||||||
|
export const EMAIL_RE = /^[^\s@<>()"',;:]+@[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}$/i;
|
||||||
|
|
||||||
|
// Limites dures, non modifiables depuis l'UI
|
||||||
|
export const HARD_LIMITS = { perBatch: 100, perDayProject: 200, perDayGlobal: 300 };
|
||||||
|
|
||||||
|
export function createTransport(smtp) {
|
||||||
|
if (!smtp?.host || !smtp?.user || !smtp?.pass || !smtp?.fromEmail) throw new Error('SMTP incomplet');
|
||||||
|
return nodemailer.createTransport({
|
||||||
|
host: smtp.host,
|
||||||
|
port: Number(smtp.port || 587),
|
||||||
|
secure: Number(smtp.port) === 465,
|
||||||
|
auth: { user: smtp.user, pass: smtp.pass },
|
||||||
|
pool: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fillTemplate(text, vars) {
|
||||||
|
return String(text).replace(/\{\{\s*(\w+)\s*\}\}/g, (_, k) => vars[k] ?? '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildProspectMail({ template, prospect, smtp, unsubUrl }) {
|
||||||
|
const vars = {
|
||||||
|
entreprise: prospect.company,
|
||||||
|
ville: prospect.city || '',
|
||||||
|
accroche: prospect.hook || '',
|
||||||
|
expediteur: smtp.fromName || '',
|
||||||
|
};
|
||||||
|
const body = fillTemplate(template.body, vars).replace(/\n{3,}/g, '\n\n').trim();
|
||||||
|
const footer = [
|
||||||
|
'',
|
||||||
|
'—',
|
||||||
|
`Vous recevez ce message car l'adresse ${prospect.email} est publiée publiquement${prospect.source ? ` (${prospect.source})` : ''}.`,
|
||||||
|
`Pour ne plus être contacté : ${unsubUrl}`,
|
||||||
|
].join('\n');
|
||||||
|
return {
|
||||||
|
from: smtp.fromName ? `"${smtp.fromName.replace(/"/g, '')}" <${smtp.fromEmail}>` : smtp.fromEmail,
|
||||||
|
to: prospect.email,
|
||||||
|
subject: fillTemplate(template.subject, vars).trim(),
|
||||||
|
text: body + '\n' + footer,
|
||||||
|
headers: {
|
||||||
|
'List-Unsubscribe': `<${unsubUrl}>`,
|
||||||
|
'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calcule combien de mails on peut réellement envoyer maintenant.
|
||||||
|
* sentToday* = mails déjà partis sur les dernières 24 h.
|
||||||
|
*/
|
||||||
|
export function allowedToSend({ requested, available, projectCap, sentTodayProject, globalCap, sentTodayGlobal }) {
|
||||||
|
const n = Math.floor(Number(requested));
|
||||||
|
if (!Number.isFinite(n) || n < 1) throw new Error('Nombre de mails invalide');
|
||||||
|
const pCap = Math.min(projectCap, HARD_LIMITS.perDayProject);
|
||||||
|
const gCap = Math.min(globalCap, HARD_LIMITS.perDayGlobal);
|
||||||
|
return Math.max(0, Math.min(n, HARD_LIMITS.perBatch, available, pCap - sentTodayProject, gCap - sentTodayGlobal));
|
||||||
|
}
|
||||||
76
src/services/recap.js
Normal file
76
src/services/recap.js
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
// Récap : requêtes SELECT en lecture seule sur la BDD de chaque projet.
|
||||||
|
// Recommandation : utilisateur BDD dédié avec droits SELECT uniquement.
|
||||||
|
|
||||||
|
export function validateSelect(sql) {
|
||||||
|
const s = String(sql || '').trim().replace(/;\s*$/, '');
|
||||||
|
if (!s) return null;
|
||||||
|
if (!/^(select|with)\b/i.test(s)) throw new Error('Seules les requêtes SELECT sont autorisées');
|
||||||
|
if (s.includes(';')) throw new Error('Une seule requête par champ');
|
||||||
|
if (/\b(insert|update|delete|drop|alter|truncate|create|grant|replace|into\s+outfile|load_file|pg_sleep|sleep\s*\()/i.test(s)) {
|
||||||
|
throw new Error('Mot-clé interdit dans la requête');
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function queryMysql(cfg, queries) {
|
||||||
|
const mysql = await import('mysql2/promise');
|
||||||
|
const conn = await mysql.createConnection({
|
||||||
|
host: cfg.host, port: Number(cfg.port || 3306), user: cfg.user, password: cfg.password,
|
||||||
|
database: cfg.database, connectTimeout: 8000, ssl: cfg.ssl ? {} : undefined,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await conn.query('START TRANSACTION READ ONLY');
|
||||||
|
const out = {};
|
||||||
|
for (const [k, sql] of Object.entries(queries)) {
|
||||||
|
const [rows] = await conn.query({ sql, timeout: 10_000 });
|
||||||
|
out[k] = firstValue(rows);
|
||||||
|
}
|
||||||
|
await conn.query('ROLLBACK');
|
||||||
|
return out;
|
||||||
|
} finally { await conn.end().catch(() => {}); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function queryPg(cfg, queries) {
|
||||||
|
const { default: pg } = await import('pg');
|
||||||
|
const client = new pg.Client({
|
||||||
|
host: cfg.host, port: Number(cfg.port || 5432), user: cfg.user, password: cfg.password,
|
||||||
|
database: cfg.database, connectionTimeoutMillis: 8000, statement_timeout: 10_000,
|
||||||
|
ssl: cfg.ssl ? { rejectUnauthorized: false } : undefined,
|
||||||
|
});
|
||||||
|
await client.connect();
|
||||||
|
try {
|
||||||
|
await client.query('BEGIN READ ONLY');
|
||||||
|
const out = {};
|
||||||
|
for (const [k, sql] of Object.entries(queries)) out[k] = firstValue((await client.query(sql)).rows);
|
||||||
|
await client.query('ROLLBACK');
|
||||||
|
return out;
|
||||||
|
} finally { await client.end().catch(() => {}); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function firstValue(rows) {
|
||||||
|
const row = rows?.[0];
|
||||||
|
if (!row) return 0;
|
||||||
|
const v = Object.values(row)[0];
|
||||||
|
const n = Number(v);
|
||||||
|
return Number.isFinite(n) ? n : v;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cache = new Map();
|
||||||
|
const TTL = 10 * 60_000;
|
||||||
|
|
||||||
|
export async function fetchRecap(projectId, cfg, { force = false } = {}) {
|
||||||
|
if (!cfg?.type) throw new Error('Accès BDD non configuré pour ce projet');
|
||||||
|
const hit = cache.get(projectId);
|
||||||
|
if (!force && hit && Date.now() - hit.at < TTL) return { ...hit.data, cached: true };
|
||||||
|
const queries = {};
|
||||||
|
for (const k of ['users', 'clients', 'revenue']) {
|
||||||
|
const s = validateSelect(cfg[`sql_${k}`]);
|
||||||
|
if (s) queries[k] = s;
|
||||||
|
}
|
||||||
|
if (!Object.keys(queries).length) throw new Error('Aucune requête configurée');
|
||||||
|
const data = cfg.type === 'pg' ? await queryPg(cfg, queries) : await queryMysql(cfg, queries);
|
||||||
|
cache.set(projectId, { at: Date.now(), data });
|
||||||
|
return { ...data, cached: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearRecapCache(projectId) { cache.delete(projectId); }
|
||||||
Loading…
Reference in a new issue