feat: init repo
deploy / deploy (push) Canceled after 0s

This commit is contained in:
2026-11-10 19:56:03 +01:00
commit 858d862fed
166 changed files with 13336 additions and 0 deletions
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env node
import { randomUUID } from "node:crypto";
import { ConfigError, loadDbConfig, hashPassword, AppError, toSafeError } from "@cohaise/server";
/**
* Creation et reinitialisation des comptes CRM, hors requete HTTP.
*
* Meme principe que cohaise-admin : cette commande ne lit que les variables
* DB, pour pouvoir creer le premier administrateur alors que l'API n'a pas
* encore le droit de demarrer.
*
* node dist/admin.js --email [email protected] --first Jean --last Dupont
* node dist/admin.js --email [email protected] --reset
*
* Mot de passe : ADMIN_PASSWORD dans l'environnement, sinon --password,
* sinon un mot de passe aleatoire est genere et affiche une seule fois.
*/
const USAGE = `Utilisation : cohaise-crm-admin --email <adr> --first <prenom> --last <nom> [options]
--email <adr> Adresse du compte (obligatoire)
--first <nom> Prenom (obligatoire a la creation)
--last <nom> Nom (obligatoire a la creation)
--password <mdp> Mot de passe, sinon variable ADMIN_PASSWORD
--reset Reinitialise le mot de passe d'un compte existant
--help Cette aide`;
interface Args {
email: string;
first: string;
last: string;
password?: string;
reset: boolean;
help: boolean;
}
const parseArgs = (argv: string[]): Args => {
const args: Args = {
email: "",
first: "",
last: "",
reset: false,
help: false,
};
const value = (index: number): string => {
const next = argv[index + 1];
if (next === undefined || next.startsWith("--")) {
throw AppError.badRequest(`Valeur manquante pour ${argv[index]}`);
}
return next;
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === undefined) continue;
if (arg === "--email") args.email = value(index++);
else if (arg === "--first") args.first = value(index++);
else if (arg === "--last") args.last = value(index++);
else if (arg === "--password") args.password = value(index++);
else if (arg === "--reset") args.reset = true;
else if (arg === "--help" || arg === "-h") args.help = true;
else throw AppError.badRequest(`Argument inconnu : ${arg}`);
}
return args;
};
/** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */
const generatePassword = (): string => {
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const bytes = new Uint8Array(18);
globalThis.crypto.getRandomValues(bytes);
let out = "";
for (const byte of bytes) out += alphabet[byte % alphabet.length];
return out;
};
const main = async (argv: string[]): Promise<number> => {
let args: Args;
try {
args = parseArgs(argv);
} catch (error) {
console.error(` ${toSafeError(error).message}\n\n${USAGE}`);
return 2;
}
if (args.help) {
console.log(USAGE);
return 0;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(args.email)) {
console.error(" Adresse e-mail invalide.");
return 2;
}
let config;
try {
config = loadDbConfig();
} catch (error) {
if (error instanceof ConfigError) {
console.error(` Configuration invalide :\n - ${error.issues.join("\n - ")}`);
return 2;
}
throw error;
}
const { Db } = await import("@cohaise/server");
const db = new Db(config);
try {
// Pas de colonne active_email ici : le CRM n'a pas de migration qui
// neutralise les lignes supprimees sur la table users. On regarde donc
// deleted_at explicitement.
const existing = await db.one<{ id: string; deleted_at: string | null }>(
"SELECT id, deleted_at FROM users WHERE email = ?",
[args.email],
);
if (existing && !args.reset && existing.deleted_at === null) {
console.error(` Ce compte existe deja : ${args.email}`);
console.error(" Utilisez --reset pour reinitialiser son mot de passe.");
return 1;
}
const password = args.password ?? process.env.ADMIN_PASSWORD ?? generatePassword();
if (Buffer.byteLength(password) < 8) {
console.error(" Le mot de passe doit contenir au moins 8 caracteres.");
return 2;
}
const hash = await hashPassword(password);
if (existing) {
const assignments = ["password_hash = ?", "must_change_password = 1", "is_active = 1", "deleted_at = NULL"];
const values: unknown[] = [hash, existing.id];
await db.exec(`UPDATE users SET ${assignments.join(", ")} WHERE id = ?`, values);
console.log(` Mot de passe reinitialise pour ${args.email}`);
console.log(` Mot de passe : ${password}`);
console.log(" Un changement de mot de passe sera demande a la premiere connexion.");
return 0;
}
if (!args.first || !args.last) {
console.error(" --first et --last sont obligatoires a la creation.");
console.error(`\n${USAGE}`);
return 2;
}
const id = randomUUID();
await db.exec(
`INSERT INTO users (id, email, first_name, last_name, password_hash, must_change_password)
VALUES (?, ?, ?, ?, ?, 1)`,
[id, args.email, args.first, args.last, hash],
);
console.log(` Compte cree : ${args.email}`);
console.log(` Mot de passe : ${password}`);
console.log(" Un changement de mot de passe sera demande a la premiere connexion.");
return 0;
} catch (error) {
const safe = toSafeError(error);
console.error(` Echec : ${safe.code} — ${safe.message}`);
return 1;
} finally {
await db.close().catch(() => undefined);
}
};
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(error) => {
console.error(` Erreur inattendue : ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
},
);
+25
View File
@@ -0,0 +1,25 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { purgeExpiredSessions, startService } from "@cohaise/server";
import { registerAuthRoutes } from "./routes/auth.js";
import { registerCountryRoutes } from "./routes/countries.js";
import { registerOrganizationRoutes } from "./routes/organizations.js";
import { registerContactRoutes } from "./routes/contacts.js";
import { registerLeadRoutes } from "./routes/leads.js";
const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), "../migrations");
void startService({
service: "crm",
migrationsDir,
routes: (app, { db, config }) => {
registerAuthRoutes(app, db, config);
registerCountryRoutes(app, db);
registerOrganizationRoutes(app, db);
registerContactRoutes(app, db);
registerLeadRoutes(app, db);
// Les jetons expires n'ont rien a faire en base : purge au demarrage
// plutot qu'un EVENT, qui dependrait du planificateur MariaDB.
void purgeExpiredSessions(db);
},
});
+151
View File
@@ -0,0 +1,151 @@
import { z } from "zod";
import {
AppError,
attachUser,
clearSessionCookie,
createSession,
currentUser,
hashPassword,
isHttpsRequest,
requireAuth,
revokeSession,
setSessionCookie,
sha256,
verifyPassword,
type App,
type Config,
type Db,
} from "@cohaise/server";
const credentials = z.object({
email: z.string().trim().toLowerCase().email().max(255),
password: z.string().min(1).max(1024),
});
const changePassword = z.object({
current: z.string().min(1).max(1024),
next: z.string().min(8).max(1024),
});
interface UserRow {
id: string;
email: string;
password_hash: string;
first_name: string;
last_name: string;
is_active: number;
must_change_password: number;
}
const SELECT_USER = `
SELECT u.id, u.email, u.password_hash, u.first_name, u.last_name,
u.is_active, u.must_change_password
FROM users u`;
/**
* Empreinte de repli, calculee pour n'importe quelle chaine : une adresse
* inconnue doit prendre exactement le meme temps qu'une adresse connue avec
* un mauvais mot de passe, sinon l'API devient un annuaire.
*/
const DUMMY_HASH_PROMISE = hashPassword("placeholder-for-anti-enumeration").catch(() => null);
void DUMMY_HASH_PROMISE;
const publicUser = (row: UserRow) => ({
id: row.id,
email: row.email,
first_name: row.first_name,
last_name: row.last_name,
must_change_password: row.must_change_password === 1,
});
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/crm/auth/*", attachUser(db));
app.post("/api/crm/auth/login", async (context) => {
const parsed = credentials.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
throw AppError.badRequest("Identifiants invalides.");
}
const row = await db.one<UserRow>(
`${SELECT_USER} WHERE u.email = ? AND u.deleted_at IS NULL`,
[parsed.data.email],
);
const stored = row?.password_hash ?? (await DUMMY_HASH_PROMISE) ?? "";
const valid = stored ? await verifyPassword(parsed.data.password, stored) : false;
if (!row || !valid) throw AppError.unauthorized("Identifiants invalides.");
if (row.is_active !== 1) throw AppError.unauthorized("Compte desactive.");
const { token, expiresAt } = await createSession(
db,
row.id,
{
ipAddress: context.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? null,
userAgent: context.req.header("user-agent") ?? null,
},
config.SESSION_TTL_HOURS,
);
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP(3) WHERE id = ?", [row.id]);
// Le schema reel de la requete, pas PUBLIC_ORIGIN : voir isHttpsRequest.
const secure = isHttpsRequest(context, config.TRUST_PROXY);
setSessionCookie(context, token, expiresAt, secure);
return context.json({ user: publicUser(row) });
});
app.post("/api/crm/auth/logout", requireAuth, async (context) => {
const token = context.get("token") as string | undefined;
if (token) await revokeSession(db, token);
clearSessionCookie(context);
return context.json({ ok: true });
});
app.get("/api/crm/auth/me", requireAuth, async (context) => {
const session = currentUser(context);
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`, [
session.id,
]);
if (!row) throw AppError.unauthorized();
return context.json({ user: publicUser(row) });
});
app.post("/api/crm/auth/change-password", requireAuth, async (context) => {
const session = currentUser(context);
const parsed = changePassword.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
throw AppError.badRequest("Le nouveau mot de passe doit contenir au moins 8 caracteres.");
}
const row = await db.one<{ password_hash: string }>(
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
[session.id],
);
if (!row) throw AppError.unauthorized();
if (!(await verifyPassword(parsed.data.current, row.password_hash))) {
throw AppError.unauthorized("Mot de passe actuel incorrect.");
}
if (parsed.data.current === parsed.data.next) {
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
}
const hash = await hashPassword(parsed.data.next);
// Pas de password_changed_at ici : cette colonne appartient au modele du
// Cloud. Le CRM n'a pas de notion de confirmation d'identite a celebrer.
await db.exec("UPDATE users SET password_hash = ?, must_change_password = 0 WHERE id = ?", [
hash,
session.id,
]);
// La session courante est conservee, toutes les autres sont revoquees.
await db.exec(
`UPDATE user_sessions
SET revoked_at = UTC_TIMESTAMP()
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
[session.id, sha256(context.get("token") ?? "")],
);
return context.json({ ok: true });
});
};
+274
View File
@@ -0,0 +1,274 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
const uuid = z
.string()
.regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Identifiant invalide.");
const createContact = z.object({
firstName: z.string().trim().min(1).max(100),
lastName: z.string().trim().min(1).max(100),
organizationId: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullish(),
email: z.string().trim().max(255).nullish(),
phone: z.string().trim().max(50).nullish(),
mobile: z.string().trim().max(50).nullish(),
jobTitle: z.string().trim().max(150).nullish(),
countryId: z.coerce.number().int().positive().nullish(),
externalSource: z.string().trim().max(50).nullish(),
externalId: z.string().trim().max(100).nullish(),
description: z.string().trim().max(4000).nullish(),
});
const updateContact = createContact.partial();
interface ContactRow {
id: string;
first_name: string;
last_name: string;
organization_id: string | null;
organization_name: string | null;
email: string | null;
phone: string | null;
mobile: string | null;
job_title: string | null;
country_id: number | null;
country_name: string | null;
country_code: string | null;
external_source: string | null;
external_id: string | null;
description: string | null;
owner_id: string | null;
owner_name: string | null;
created_at: string;
updated_at: string;
}
const SELECT_CONTACT = `
SELECT ct.id, ct.first_name, ct.last_name, ct.organization_id,
o.name AS organization_name, ct.email, ct.phone, ct.mobile, ct.job_title,
ct.country_id, c.name AS country_name, c.code AS country_code,
ct.external_source, ct.external_id, ct.description, ct.owner_id,
CONCAT(u.first_name, ' ', u.last_name) AS owner_name,
ct.created_at, ct.updated_at
FROM contacts ct
LEFT JOIN organizations o ON o.id = ct.organization_id AND o.deleted_at IS NULL
LEFT JOIN countries c ON c.id = ct.country_id
LEFT JOIN users u ON u.id = ct.owner_id`;
const publicContact = (row: ContactRow) => ({
id: row.id,
first_name: row.first_name,
last_name: row.last_name,
organization_id: row.organization_id,
organization_name: row.organization_name,
email: row.email,
phone: row.phone,
mobile: row.mobile,
job_title: row.job_title,
country_id: row.country_id,
country_name: row.country_name,
country_code: row.country_code,
external_source: row.external_source,
external_id: row.external_id,
description: row.description,
owner_id: row.owner_id,
owner_name: row.owner_name,
created_at: row.created_at,
updated_at: row.updated_at,
});
/** Un e-mail absent ne doit pas heurter l'index actif : NULL passe partout. */
const emailOrNull = (value: string | null | undefined): string | null =>
value ? value.toLowerCase() : null;
export const registerContactRoutes = (app: App, db: Db): void => {
app.use("/api/crm/contacts/*", attachUser(db));
app.use("/api/crm/contacts", attachUser(db));
app.get("/api/crm/contacts", requireAuth, async (context) => {
const search = context.req.query("q")?.trim() ?? "";
const organizationId = context.req.query("organizationId")?.trim() ?? "";
const page = Math.max(1, Number(context.req.query("page") ?? 1) || 1);
const limit = Math.min(100, Math.max(1, Number(context.req.query("limit") ?? 25) || 25));
const offset = (page - 1) * limit;
const clauses = ["ct.deleted_at IS NULL"];
const params: unknown[] = [];
if (search) {
clauses.push(
"(ct.first_name LIKE ? OR ct.last_name LIKE ? OR ct.email LIKE ? OR o.name LIKE ?)",
);
const term = `%${search}%`;
params.push(term, term, term, term);
}
if (uuid.safeParse(organizationId).success) {
clauses.push("ct.organization_id = ?");
params.push(organizationId);
}
const where = `WHERE ${clauses.join(" AND ")}`;
const totalRows = await db.query<{ total: number }>(
`SELECT COUNT(*) AS total
FROM contacts ct
LEFT JOIN organizations o ON o.id = ct.organization_id AND o.deleted_at IS NULL
${where}`,
params,
);
const total = Number(totalRows[0]?.total ?? 0);
const rows = await db.query<ContactRow>(
`${SELECT_CONTACT} ${where} ORDER BY ct.last_name, ct.first_name LIMIT ${limit} OFFSET ${offset}`,
params,
);
return context.json({
total,
page,
limit,
contacts: rows.map(publicContact),
});
});
app.get("/api/crm/contacts/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
const row = await db.one<ContactRow>(
`${SELECT_CONTACT} WHERE ct.id = ? AND ct.deleted_at IS NULL`,
[id],
);
if (!row) throw AppError.notFound("Prospect introuvable.");
return context.json({ contact: publicContact(row) });
});
app.post(
"/api/crm/contacts",
requireAuth,
async (context) => {
const user = currentUser(context);
const parsed = createContact.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.");
}
const data = parsed.data;
const id = randomUUID();
try {
await db.exec(
`INSERT INTO contacts
(id, first_name, last_name, organization_id, email, phone, mobile, job_title,
country_id, external_source, external_id, description, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
id,
data.firstName,
data.lastName,
data.organizationId ?? null,
emailOrNull(data.email),
data.phone ?? null,
data.mobile ?? null,
data.jobTitle ?? null,
data.countryId ?? null,
data.externalSource ?? null,
data.externalId ?? null,
data.description ?? null,
user.id,
user.id,
],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un prospect actif porte deja cette adresse.");
}
if ((error as { errno?: number }).errno === 1452) {
throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas.");
}
throw error;
}
const created = await db.required<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
return context.json({ contact: publicContact(created) }, 201);
},
);
app.patch(
"/api/crm/contacts/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
const parsed = updateContact.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
const existing = await db.one<{ id: string }>(
"SELECT id FROM contacts WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (!existing) throw AppError.notFound("Prospect introuvable.");
const columns: Record<string, unknown> = {
first_name: parsed.data.firstName,
last_name: parsed.data.lastName,
organization_id: parsed.data.organizationId,
email: parsed.data.email === undefined ? undefined : emailOrNull(parsed.data.email),
phone: parsed.data.phone,
mobile: parsed.data.mobile,
job_title: parsed.data.jobTitle,
country_id: parsed.data.countryId,
external_source: parsed.data.externalSource,
external_id: parsed.data.externalId,
description: parsed.data.description,
};
const assignments = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => `${key} = ?`);
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
const values = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => columns[key]);
try {
await db.exec(
`UPDATE contacts SET ${assignments.join(", ")} WHERE id = ? AND deleted_at IS NULL`,
[...values, id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un prospect actif porte deja cette adresse.");
}
if ((error as { errno?: number }).errno === 1452) {
throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas.");
}
throw error;
}
const updated = await db.required<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
return context.json({ contact: publicContact(updated) });
},
);
app.delete(
"/api/crm/contacts/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
const result = await db.exec(
"UPDATE contacts SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (result.affectedRows === 0) throw AppError.notFound("Prospect introuvable.");
return context.json({ ok: true });
},
);
};
+150
View File
@@ -0,0 +1,150 @@
import { z } from "zod";
import {
AppError,
attachUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
const createCountry = z.object({
code: z
.string()
.trim()
.toUpperCase()
.regex(/^[A-Z]{2}$/, "Code ISO 3166-1 alpha-2 attendu, deux lettres."),
name: z.string().trim().min(1).max(100),
phoneCode: z
.string()
.trim()
.regex(/^\+?[0-9]{1,7}$/, "Indicatif telephonique attendu.")
.nullish(),
});
const updateCountry = createCountry.partial();
interface CountryRow {
id: number;
code: string;
name: string;
phone_code: string | null;
}
const publicCountry = (row: CountryRow) => ({
id: row.id,
code: row.code,
name: row.name,
phone_code: row.phone_code,
});
export const registerCountryRoutes = (app: App, db: Db): void => {
app.use("/api/crm/countries/*", attachUser(db));
app.use("/api/crm/countries", attachUser(db));
// Referentiel : lecture ouverte a tout le monde authentifie, ecriture
// reservee. Le tri est collationnel, donc sans accent ni casse douteuse.
app.get("/api/crm/countries", requireAuth, async (context) => {
const search = context.req.query("q")?.trim() ?? "";
const where = search ? "WHERE name LIKE ? OR code = ?" : "";
const params = search ? [`%${search}%`, search.toUpperCase()] : [];
const rows = await db.query<CountryRow>(
`SELECT id, code, name, phone_code FROM countries ${where} ORDER BY name`,
params,
);
return context.json({ countries: rows.map(publicCountry) });
});
app.post(
"/api/crm/countries",
requireAuth,
async (context) => {
const parsed = createCountry.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(issue?.message ?? "Corps invalide.");
}
try {
await db.exec("INSERT INTO countries (code, name, phone_code) VALUES (?, ?, ?)", [
parsed.data.code,
parsed.data.name,
parsed.data.phoneCode ?? null,
]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce pays existe deja.");
}
throw error;
}
const created = await db.required<CountryRow>(
"SELECT id, code, name, phone_code FROM countries WHERE code = ?",
[parsed.data.code],
);
return context.json({ country: publicCountry(created) }, 201);
},
);
app.patch(
"/api/crm/countries/:id",
requireAuth,
async (context) => {
const id = Number(context.req.param("id"));
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
const parsed = updateCountry.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
const columns: Record<string, unknown> = {
code: parsed.data.code,
name: parsed.data.name,
phone_code: parsed.data.phoneCode,
};
const assignments = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => `${key} = ?`);
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
const values = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => columns[key]);
try {
const result = await db.exec(
`UPDATE countries SET ${assignments.join(", ")} WHERE id = ?`,
[...values, id],
);
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce code de pays existe deja.");
}
throw error;
}
const updated = await db.required<CountryRow>(
"SELECT id, code, name, phone_code FROM countries WHERE id = ?",
[id],
);
return context.json({ country: publicCountry(updated) });
},
);
app.delete(
"/api/crm/countries/:id",
requireAuth,
async (context) => {
const id = Number(context.req.param("id"));
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
try {
const result = await db.exec("DELETE FROM countries WHERE id = ?", [id]);
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
} catch (error) {
if ((error as { errno?: number }).errno === 1451) {
throw AppError.conflict("Des entreprises ou contacts referencent ce pays.");
}
throw error;
}
return context.json({ ok: true });
},
);
};
+146
View File
@@ -0,0 +1,146 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import { AppError, type App, type Db } from "@cohaise/server";
/**
* Point d'entrée public du formulaire de contact de la vitrine.
*
* Route volontairement sans `requireAuth` : n'importe quel visiteur de
* cohaise.dev peut creer un prospect. Protection anti-abus a deux etages :
* - un honeypot (champ invisible que seuls les robots remplissent) ;
* - un rate-limit simple en memoire, par IP (Cloudflare reste la 1re ligne).
* Le lead est pose dans `contacts` avec `external_source = 'cohaise-web'`,
* non assigne, pour apparaitre dans la liste des prospects du CRM.
*/
const leadSchema = z.object({
firstName: z.string().trim().min(1).max(100),
lastName: z.string().trim().min(1).max(100),
email: z.string().trim().min(1).max(255),
organization: z.string().trim().min(1).max(255).nullish(),
phone: z.string().trim().max(50).nullish(),
message: z.string().trim().max(4000).nullish(),
// Honeypot : vide chez un humain, rempli par un robot.
website: z.string().max(255).nullish(),
});
const slugify = (value: string): string =>
value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 255);
/** Un e-mail absent ne doit pas heurter l'index unique : NULL passe partout. */
const emailOrNull = (value: string): string | null => value.toLowerCase();
/** Retrouve l'entreprise par son nom, ou la cree (nom unique en base). */
const findOrCreateOrganization = async (db: Db, name: string): Promise<string> => {
const existing = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
[name],
);
if (existing) return existing.id;
const id = randomUUID();
try {
await db.exec("INSERT INTO organizations (id, name, slug) VALUES (?, ?, ?)", [
id,
name,
slugify(name),
]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
// Course : une autre requete vient de creer le meme nom. On la rejoint.
const raced = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
[name],
);
if (raced) return raced.id;
}
throw error;
}
return id;
};
// Rate-limit en memoire : suffisant pour une instance CRM unique. Derriere
// nginx/Cloudflare, l'IP vient de x-forwarded-for.
const RATE_WINDOW_MS = 15 * 60 * 1000;
const RATE_MAX = 5;
const attempts = new Map<string, number[]>();
const isAllowed = (ip: string): boolean => {
const now = Date.now();
const recent = (attempts.get(ip) ?? []).filter((t) => now - t < RATE_WINDOW_MS);
if (recent.length >= RATE_MAX) {
attempts.set(ip, recent);
return false;
}
recent.push(now);
attempts.set(ip, recent);
return true;
};
export const registerLeadRoutes = (app: App, db: Db): void => {
app.post("/api/crm/leads", async (context) => {
const forwarded = context.req.header("x-forwarded-for");
const ip =
forwarded?.split(",")[0]?.trim() ?? context.req.header("x-real-ip") ?? "unknown";
if (!isAllowed(ip)) throw AppError.tooManyRequests();
const parsed = leadSchema.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
const data = parsed.data;
// Honeypot rempli : robot. On feint la reussite pour ne pas se trahir.
if (data.website) {
return context.json({ ok: true, id: randomUUID() }, 201);
}
const organizationId = data.organization
? await findOrCreateOrganization(db, data.organization)
: null;
const id = randomUUID();
try {
await db.exec(
`INSERT INTO contacts
(id, first_name, last_name, organization_id, email, phone, job_title,
country_id, external_source, external_id, description, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
id,
data.firstName,
data.lastName,
organizationId,
emailOrNull(data.email),
data.phone ?? null,
null,
null,
"cohaise-web",
null,
data.message ?? null,
null,
null,
],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Cette adresse a deja ete enregistree.");
}
if ((error as { errno?: number }).errno === 1452) {
throw AppError.badRequest("L'entreprise referencee n'existe pas.");
}
throw error;
}
return context.json({ ok: true, id }, 201);
});
};
+277
View File
@@ -0,0 +1,277 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
const uuid = z
.string()
.regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Identifiant invalide.");
const writable = z.string().trim().min(1).max(255);
const optionalText = z.string().trim().max(255).nullish();
const optionalLong = z.string().trim().max(4000).nullish();
const createOrganization = z.object({
name: writable,
website: optionalText,
industry: z.string().trim().max(100).nullish(),
phone: z.string().trim().max(50).nullish(),
email: z.string().trim().max(255).nullish(),
addressLine1: optionalText,
addressLine2: optionalText,
postalCode: z.string().trim().max(20).nullish(),
city: z.string().trim().max(100).nullish(),
countryId: z.coerce.number().int().positive().nullish(),
description: optionalLong,
});
const updateOrganization = createOrganization.partial();
interface OrganizationRow {
id: string;
name: string;
slug: string;
website: string | null;
industry: string | null;
phone: string | null;
email: string | null;
address_line1: string | null;
address_line2: string | null;
postal_code: string | null;
city: string | null;
country_id: number | null;
country_name: string | null;
country_code: string | null;
description: string | null;
owner_id: string | null;
owner_name: string | null;
created_at: string;
updated_at: string;
}
const SELECT_ORGANIZATION = `
SELECT o.id, o.name, o.slug, o.website, o.industry, o.phone, o.email,
o.address_line1, o.address_line2, o.postal_code, o.city, o.country_id,
c.name AS country_name, c.code AS country_code,
o.description, o.owner_id,
CONCAT(u.first_name, ' ', u.last_name) AS owner_name,
o.created_at, o.updated_at
FROM organizations o
LEFT JOIN countries c ON c.id = o.country_id
LEFT JOIN users u ON u.id = o.owner_id`;
const publicOrganization = (row: OrganizationRow) => ({
id: row.id,
name: row.name,
slug: row.slug,
website: row.website,
industry: row.industry,
phone: row.phone,
email: row.email,
address_line1: row.address_line1,
address_line2: row.address_line2,
postal_code: row.postal_code,
city: row.city,
country_id: row.country_id,
country_name: row.country_name,
country_code: row.country_code,
description: row.description,
owner_id: row.owner_id,
owner_name: row.owner_name,
created_at: row.created_at,
updated_at: row.updated_at,
});
/** Normalise un nom en slug lisible, sans accent ni punctuation. */
const slugify = (value: string): string =>
value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 255);
export const registerOrganizationRoutes = (app: App, db: Db): void => {
app.use("/api/crm/organizations/*", attachUser(db));
app.use("/api/crm/organizations", attachUser(db));
app.get("/api/crm/organizations", requireAuth, async (context) => {
const search = context.req.query("q")?.trim() ?? "";
const page = Math.max(1, Number(context.req.query("page") ?? 1) || 1);
const limit = Math.min(100, Math.max(1, Number(context.req.query("limit") ?? 25) || 25));
const offset = (page - 1) * limit;
const where = search
? "WHERE o.deleted_at IS NULL AND (o.name LIKE ? OR o.city LIKE ? OR o.industry LIKE ?)"
: "WHERE o.deleted_at IS NULL";
const term = `%${search}%`;
const params = search ? [term, term, term] : [];
const [{ total }, rows] = await Promise.all([
db
.query<{ total: number }>(`SELECT COUNT(*) AS total FROM organizations o ${where}`, params)
.then((result) => ({ total: Number(result[0]?.total ?? 0) })),
db.query<OrganizationRow>(
`${SELECT_ORGANIZATION} ${where} ORDER BY o.name LIMIT ${limit} OFFSET ${offset}`,
params,
),
]);
return context.json({
total,
page,
limit,
organizations: rows.map(publicOrganization),
});
});
app.get("/api/crm/organizations/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
const row = await db.one<OrganizationRow>(
`${SELECT_ORGANIZATION} WHERE o.id = ? AND o.deleted_at IS NULL`,
[id],
);
if (!row) throw AppError.notFound("Entreprise introuvable.");
return context.json({ organization: publicOrganization(row) });
});
app.post(
"/api/crm/organizations",
requireAuth,
async (context) => {
const user = currentUser(context);
const parsed = createOrganization.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
const data = parsed.data;
const id = randomUUID();
try {
await db.exec(
`INSERT INTO organizations
(id, name, slug, website, industry, phone, email, address_line1, address_line2,
postal_code, city, country_id, description, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
id,
data.name,
slugify(data.name),
data.website ?? null,
data.industry ?? null,
data.phone ?? null,
data.email ?? null,
data.addressLine1 ?? null,
data.addressLine2 ?? null,
data.postalCode ?? null,
data.city ?? null,
data.countryId ?? null,
data.description ?? null,
user.id,
user.id,
],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Une entreprise porte deja ce nom.");
}
throw error;
}
const created = await db.required<OrganizationRow>(
`${SELECT_ORGANIZATION} WHERE o.id = ?`,
[id],
);
return context.json({ organization: publicOrganization(created) }, 201);
},
);
app.patch(
"/api/crm/organizations/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
const parsed = updateOrganization.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
const existing = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (!existing) throw AppError.notFound("Entreprise introuvable.");
const columns: Record<string, unknown> = {
website: parsed.data.website,
industry: parsed.data.industry,
phone: parsed.data.phone,
email: parsed.data.email,
address_line1: parsed.data.addressLine1,
address_line2: parsed.data.addressLine2,
postal_code: parsed.data.postalCode,
city: parsed.data.city,
country_id: parsed.data.countryId,
description: parsed.data.description,
};
if (parsed.data.name !== undefined) {
columns.name = parsed.data.name;
columns.slug = slugify(parsed.data.name);
}
const assignments = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => `${key} = ?`);
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
const values = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => columns[key]);
try {
await db.exec(
`UPDATE organizations SET ${assignments.join(", ")} WHERE id = ? AND deleted_at IS NULL`,
[...values, id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Une entreprise porte deja ce nom.");
}
throw error;
}
const updated = await db.required<OrganizationRow>(
`${SELECT_ORGANIZATION} WHERE o.id = ?`,
[id],
);
return context.json({ organization: publicOrganization(updated) });
},
);
app.delete(
"/api/crm/organizations/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
const result = await db.exec(
"UPDATE organizations SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (result.affectedRows === 0) throw AppError.notFound("Entreprise introuvable.");
return context.json({ ok: true });
},
);
};