Push for multi roles functionalities3

This commit is contained in:
Your Name 2026-07-02 10:56:38 +02:00
parent ed2af73145
commit bef651bd45
12 changed files with 187 additions and 37 deletions

View File

@ -151,8 +151,8 @@ exports.config = {
host: process.env.SMTP_HOST || '',
port: parseInt(process.env.SMTP_PORT || '587', 10),
secure: process.env.SMTP_SECURE === 'true',
user: process.env.SMTP_USER || '',
pass: process.env.SMTP_PASS || '',
user: (process.env.SMTP_USER || '').trim(),
pass: (process.env.SMTP_PASS || '').replace(/\s+/g, ''),
from: process.env.EMAIL_FROM || '',
verificationExpiryHours: parseInt(process.env.EMAIL_VERIFICATION_EXPIRY_HOURS || '24', 10),
verificationSendMax: parseInt(process.env.EMAIL_VERIFICATION_SEND_MAX || '5', 10),

File diff suppressed because one or more lines are too long

View File

@ -2,10 +2,14 @@
* Outbound email delivery for verification and transactional messages.
* Supports SMTP (production) and console logging (development).
*/
/** Gmail app passwords are often copied with spaces — strip them. */
export declare function normalizeSmtpPass(pass: string): string;
/**
* Returns true when SMTP is fully configured for real email delivery.
*/
export declare function isSmtpConfigured(): boolean;
/** Verifies SMTP credentials (call on deploy or via CLI). */
export declare function verifySmtpConnection(): Promise<void>;
/**
* @param to - Recipient email address
* @param verifyUrl - Full URL opened by the user to confirm ownership

View File

@ -1 +1 @@
{"version":3,"file":"emailService.d.ts","sourceRoot":"","sources":["../../src/services/emailService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAQH;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,OAAO,CAG1C;AAyCD;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAgDxF;AAED;;GAEG;AACH,wBAAsB,sBAAsB,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAgDxF;AAED,KAAK,oBAAoB,GAAG;IAC1B,OAAO,EAAE,MAAM,CA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,CAAC,IAAI,CAAC,CA8Cf"}

View File

@ -7,13 +7,23 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeSmtpPass = normalizeSmtpPass;
exports.isSmtpConfigured = isSmtpConfigured;
exports.verifySmtpConnection = verifySmtpConnection;
exports.sendVerificationEmail = sendVerificationEmail;
exports.sendPasswordResetEmail = sendPasswordResetEmail;
exports.sendSecurityAlertEmail = sendSecurityAlertEmail;
const nodemailer_1 = __importDefault(require("nodemailer"));
const config_1 = require("../config");
let transporter = null;
/** Gmail app passwords are often copied with spaces — strip them. */
function normalizeSmtpPass(pass) {
return pass.replace(/\s+/g, '');
}
function isGmailHost(host) {
const h = host.toLowerCase();
return h.includes('gmail.com') || h.includes('googlemail.com');
}
/**
* Returns true when SMTP is fully configured for real email delivery.
*/
@ -21,6 +31,22 @@ function isSmtpConfigured() {
const { host, user, pass, from } = config_1.config.email;
return !!(host && user && pass && from);
}
function buildTransportOptions() {
const host = config_1.config.email.host;
const port = config_1.config.email.port;
const user = config_1.config.email.user.trim();
const pass = normalizeSmtpPass(config_1.config.email.pass);
const gmail = isGmailHost(host);
return {
host,
port,
// Port 465 = implicit TLS; 587 = STARTTLS (Gmail default).
secure: port === 465 ? true : config_1.config.email.secure,
requireTLS: port === 587,
auth: { user, pass },
...(gmail ? { tls: { minVersion: 'TLSv1.2' } } : {}),
};
}
/**
* Lazily creates the nodemailer SMTP transporter.
* @throws When transport is smtp but required env vars are missing
@ -31,17 +57,22 @@ function getSmtpTransporter() {
if (!isSmtpConfigured()) {
throw new Error('SMTP is not configured. Set SMTP_HOST, SMTP_USER, SMTP_PASS, and EMAIL_FROM.');
}
transporter = nodemailer_1.default.createTransport({
host: config_1.config.email.host,
port: config_1.config.email.port,
secure: config_1.config.email.secure,
auth: {
user: config_1.config.email.user,
pass: config_1.config.email.pass,
},
});
transporter = nodemailer_1.default.createTransport(buildTransportOptions());
return transporter;
}
/** Verifies SMTP credentials (call on deploy or via CLI). */
async function verifySmtpConnection() {
const transport = getSmtpTransporter();
await transport.verify();
}
function formatEmailSendError(context, e) {
const detail = e instanceof Error ? e.message : String(e);
console.error(`[email] ${context} SMTP send failed:`, detail);
if (config_1.config.env === 'production') {
return new Error('Unable to send email at the moment. Please try again in a few minutes or contact support.');
}
return new Error(`Failed to send ${context}: ${detail}`);
}
function resolveFromAddress() {
const from = config_1.config.email.from;
const user = config_1.config.email.user;
@ -101,9 +132,7 @@ async function sendVerificationEmail(to, verifyUrl) {
});
}
catch (e) {
const detail = e instanceof Error ? e.message : String(e);
console.error('[email] Verification SMTP send failed:', detail);
throw new Error(`Failed to send verification email: ${detail}`);
throw formatEmailSendError('verification email', e);
}
}
/**
@ -151,9 +180,7 @@ async function sendPasswordResetEmail(to, resetUrl) {
});
}
catch (e) {
const detail = e instanceof Error ? e.message : String(e);
console.error('[email] Password reset SMTP send failed:', detail);
throw new Error(`Failed to send password reset email: ${detail}`);
throw formatEmailSendError('password reset email', e);
}
}
/**

File diff suppressed because one or more lines are too long

View File

@ -24,6 +24,8 @@
"seed-hot-wallets:testnet": "cross-env ENV_FILE=../.env.testnet ts-node --transpile-only src/scripts/seedHotWallets.ts",
"grant-super-admin": "ts-node --transpile-only src/scripts/grantSuperAdminToAdmins.ts",
"grant-super-admin:prod": "node dist/scripts/grantSuperAdminToAdmins.js",
"verify-smtp": "ts-node --transpile-only src/scripts/verifySmtp.ts",
"verify-smtp:prod": "node dist/scripts/verifySmtp.js",
"test": "npm run build && node --test dist/tests/*.test.js",
"test:db": "node scripts/runDbTests.js"
},

View File

@ -159,8 +159,8 @@ export const config = {
host: process.env.SMTP_HOST || '',
port: parseInt(process.env.SMTP_PORT || '587', 10),
secure: process.env.SMTP_SECURE === 'true',
user: process.env.SMTP_USER || '',
pass: process.env.SMTP_PASS || '',
user: (process.env.SMTP_USER || '').trim(),
pass: (process.env.SMTP_PASS || '').replace(/\s+/g, ''),
from: process.env.EMAIL_FROM || '',
verificationExpiryHours: parseInt(process.env.EMAIL_VERIFICATION_EXPIRY_HOURS || '24', 10),
verificationSendMax: parseInt(process.env.EMAIL_VERIFICATION_SEND_MAX || '5', 10),

View File

@ -0,0 +1,49 @@
/**
* Verify SMTP credentials (e.g. after configuring Gmail App Password on VPS).
*
* From repo root:
* npm run phase-b:verify-smtp
*
* From backend/ (DB not required):
* npm run verify-smtp
*/
import { config } from '../config';
import { isSmtpConfigured, verifySmtpConnection } from '../services/emailService';
async function main(): Promise<void> {
console.log('Email transport:', config.email.transport);
if (config.email.transport !== 'smtp') {
console.error(
'SMTP is not active. Set EMAIL_TRANSPORT=smtp and SMTP_HOST, SMTP_USER, SMTP_PASS, EMAIL_FROM in .env'
);
process.exit(1);
}
if (!isSmtpConfigured()) {
console.error('Missing SMTP_HOST, SMTP_USER, SMTP_PASS, or EMAIL_FROM.');
process.exit(1);
}
console.log('SMTP host:', config.email.host);
console.log('SMTP port:', config.email.port);
console.log('SMTP user:', config.email.user);
console.log('EMAIL_FROM:', config.email.from);
await verifySmtpConnection();
console.log('SMTP connection OK — credentials accepted by the mail server.');
process.exit(0);
}
main().catch((e) => {
const msg = e instanceof Error ? e.message : String(e);
console.error('SMTP verification failed:', msg);
if (msg.includes('535') || msg.includes('BadCredentials')) {
console.error(
'\nGmail: use an App Password (not your normal Gmail password).\n' +
' https://myaccount.google.com/apppasswords\n' +
' SMTP_USER must be the same @gmail.com account that owns the app password.\n' +
' Remove spaces from SMTP_PASS (16 characters, no spaces).'
);
}
process.exit(1);
});

View File

@ -9,6 +9,16 @@ import { config } from '../config';
let transporter: Transporter | null = null;
/** Gmail app passwords are often copied with spaces — strip them. */
export function normalizeSmtpPass(pass: string): string {
return pass.replace(/\s+/g, '');
}
function isGmailHost(host: string): boolean {
const h = host.toLowerCase();
return h.includes('gmail.com') || h.includes('googlemail.com');
}
/**
* Returns true when SMTP is fully configured for real email delivery.
*/
@ -17,6 +27,24 @@ export function isSmtpConfigured(): boolean {
return !!(host && user && pass && from);
}
function buildTransportOptions() {
const host = config.email.host;
const port = config.email.port;
const user = config.email.user.trim();
const pass = normalizeSmtpPass(config.email.pass);
const gmail = isGmailHost(host);
return {
host,
port,
// Port 465 = implicit TLS; 587 = STARTTLS (Gmail default).
secure: port === 465 ? true : config.email.secure,
requireTLS: port === 587,
auth: { user, pass },
...(gmail ? { tls: { minVersion: 'TLSv1.2' as const } } : {}),
};
}
/**
* Lazily creates the nodemailer SMTP transporter.
* @throws When transport is smtp but required env vars are missing
@ -28,18 +56,27 @@ function getSmtpTransporter(): Transporter {
'SMTP is not configured. Set SMTP_HOST, SMTP_USER, SMTP_PASS, and EMAIL_FROM.'
);
}
transporter = nodemailer.createTransport({
host: config.email.host,
port: config.email.port,
secure: config.email.secure,
auth: {
user: config.email.user,
pass: config.email.pass,
},
});
transporter = nodemailer.createTransport(buildTransportOptions());
return transporter;
}
/** Verifies SMTP credentials (call on deploy or via CLI). */
export async function verifySmtpConnection(): Promise<void> {
const transport = getSmtpTransporter();
await transport.verify();
}
function formatEmailSendError(context: string, e: unknown): Error {
const detail = e instanceof Error ? e.message : String(e);
console.error(`[email] ${context} SMTP send failed:`, detail);
if (config.env === 'production') {
return new Error(
'Unable to send email at the moment. Please try again in a few minutes or contact support.'
);
}
return new Error(`Failed to send ${context}: ${detail}`);
}
function resolveFromAddress(): string {
const from = config.email.from!;
const user = config.email.user;
@ -104,9 +141,7 @@ export async function sendVerificationEmail(to: string, verifyUrl: string): Prom
html,
});
} catch (e) {
const detail = e instanceof Error ? e.message : String(e);
console.error('[email] Verification SMTP send failed:', detail);
throw new Error(`Failed to send verification email: ${detail}`);
throw formatEmailSendError('verification email', e);
}
}
@ -157,9 +192,7 @@ export async function sendPasswordResetEmail(to: string, resetUrl: string): Prom
html,
});
} catch (e) {
const detail = e instanceof Error ? e.message : String(e);
console.error('[email] Password reset SMTP send failed:', detail);
throw new Error(`Failed to send password reset email: ${detail}`);
throw formatEmailSendError('password reset email', e);
}
}

View File

@ -67,6 +67,40 @@ nano .env # ou vim
| `CERTBOT_DOMAIN1` | `prediqo.redirectme.net` |
| `SMTP_*` / `EMAIL_FROM` | Envoi d’emails (vérification compte, reset mot de passe) |
### Configuration SMTP (Gmail)
L’erreur `535-5.7.8 Username and Password not accepted` signifie que **Gmail refuse le mot de passe SMTP**. Le mot de passe normal du compte Gmail **ne fonctionne pas** : il faut un **mot de passe d’application**.
1. Activer la **validation en 2 étapes** sur le compte Gmail expéditeur.
2. Créer un mot de passe d’application : [https://myaccount.google.com/apppasswords](https://myaccount.google.com/apppasswords) → application « Mail », appareil « Prediqo VPS ».
3. Copier les **16 caractères** (sans espaces) dans `.env` :
```env
EMAIL_TRANSPORT=smtp
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=votre-compte@gmail.com
SMTP_PASS=xxxxxxxxxxxxxxxx
EMAIL_FROM="Prediqo" <votre-compte@gmail.com>
APP_PUBLIC_URL=https://prediqo.redirectme.net:9443
RESET_PASSWORD_PATH=/reset-password
```
`SMTP_USER` doit être **le même compte Gmail** que celui qui a généré le mot de passe d’application.
**Tester la connexion SMTP (après `git pull`) :**
```bash
sudo npm run phase-b:verify-smtp
```
Puis redémarrer le backend :
```bash
sudo npm run phase-b:up
```
> **Ne pas committer `.env`** — il est ignoré par Git.
### Base de données PostgreSQL (sur l’hôte) — **obligatoire avant le 1er démarrage**

View File

@ -24,6 +24,7 @@
"db:migrate": "docker compose run --rm --no-deps --build backend node dist/db/migrate.js",
"migrate": "npm run db:migrate",
"phase-b:grant-super-admin": "docker compose run --rm --no-deps --build backend node dist/scripts/grantSuperAdminToAdmins.js",
"phase-b:verify-smtp": "docker compose run --rm --no-deps --build backend node dist/scripts/verifySmtp.js",
"docker:local:grant-super-admin": "docker compose --env-file .env.docker run --rm --no-deps --build backend node dist/scripts/grantSuperAdminToAdmins.js"
}
}