Compare commits

..

32 Commits

Author SHA1 Message Date
Mathis HERRIOT
a2ed2a21d5 chore: bump version to 2.0.0
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 1m56s
CI/CD Pipeline / Valider documentation (push) Successful in 2m7s
CI/CD Pipeline / Valider frontend (push) Successful in 2m12s
CI/CD Pipeline / Déploiement en Production (push) Successful in 6m22s
2026-02-09 15:34:38 +01:00
Mathis HERRIOT
b7c717ffb3 feat(ui): add responsive mobile header and footer components
- Implemented `MobileHeader` with support for displaying unread messages.
- Created `MobileFooter` with navigation to key sections (home, explore, publish, trends, profile).
- Replaced legacy mobile header with new `MobileHeader` and `MobileFooter` in the dashboard layout.
- Optimized mobile sidebar rendering for improved responsiveness.
2026-02-09 15:34:26 +01:00
Mathis HERRIOT
bc686fa987 chore: bump version to 1.10.4
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 2m1s
CI/CD Pipeline / Valider documentation (push) Successful in 2m13s
CI/CD Pipeline / Valider frontend (push) Successful in 2m16s
CI/CD Pipeline / Déploiement en Production (push) Successful in 6m12s
2026-02-09 14:09:15 +01:00
Mathis HERRIOT
ea4b5a2353 refactor(sentry): unify formatting in Sentry configuration files
- Standardized indentation and formatting in `sentry.client.config.ts`, `sentry.server.config.ts`, and `sentry.edge.config.ts` for consistency.
2026-02-09 14:08:34 +01:00
Mathis HERRIOT
1a03384b49 chore: bump version to 1.10.3
Some checks failed
CI/CD Pipeline / Valider frontend (push) Failing after 1m12s
CI/CD Pipeline / Valider backend (push) Successful in 1m50s
CI/CD Pipeline / Valider documentation (push) Successful in 1m57s
CI/CD Pipeline / Déploiement en Production (push) Has been skipped
2026-02-09 14:02:25 +01:00
Mathis HERRIOT
3f7e592600 feat(sentry): integrate Sentry SDK with Next.js and configure DSN
- Added Sentry client, server, and edge configurations for enhanced error monitoring.
- Updated `.env.example` and `docker-compose` to include `NEXT_PUBLIC_SENTRY_DSN`.
- Modified `next.config.ts` to use `withSentryConfig` for source map uploads.
- Installed `@sentry/nextjs` as a dependency and updated `pnpm-lock.yaml`.
2026-02-09 14:00:28 +01:00
Mathis HERRIOT
f7cd514997 chore: bump version to 1.10.2
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 1m47s
CI/CD Pipeline / Valider frontend (push) Successful in 1m52s
CI/CD Pipeline / Valider documentation (push) Successful in 1m55s
CI/CD Pipeline / Déploiement en Production (push) Successful in 5m48s
2026-02-09 13:00:26 +01:00
Mathis HERRIOT
3a4f6624fc feat(health): add Sentry status check to health endpoint
- Integrated Sentry status check functionality in the health controller.
- Updated tests to validate Sentry active/disabled states.
- Improved Sentry initialization with enhanced logging and error handling.
2026-02-09 12:57:31 +01:00
Mathis HERRIOT
8a146a2e1d chore: bump version to 1.10.1
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 1m47s
CI/CD Pipeline / Valider frontend (push) Successful in 1m54s
CI/CD Pipeline / Valider documentation (push) Successful in 1m56s
CI/CD Pipeline / Déploiement en Production (push) Successful in 5m50s
2026-02-09 11:45:50 +01:00
Mathis HERRIOT
1ab6e1a969 refactor: adjust imports and streamline code for consistency
- Reorganized import statements in multiple files for better readability.
- Refined `auth.service` to remove unused `email` variable in `login` function.
- Cleaned up whitespace and formatting in `http-exception.filter.spec.ts`.
2026-02-09 11:45:12 +01:00
Mathis HERRIOT
e27a98ca89 chore: bump version to 1.10.0
Some checks failed
CI/CD Pipeline / Valider backend (push) Failing after 1m7s
CI/CD Pipeline / Valider frontend (push) Successful in 1m54s
CI/CD Pipeline / Valider documentation (push) Successful in 1m57s
CI/CD Pipeline / Déploiement en Production (push) Has been skipped
2026-02-09 11:28:22 +01:00
Mathis HERRIOT
7b22fd9a4e feat(environment): add Sentry DSN configuration to docker-compose files and .env example 2026-02-09 11:28:02 +01:00
Mathis HERRIOT
0706c47a33 feat(logging): hash IP addresses in logs and Sentry integration
- Implemented IP hashing using SHA256 in logs for enhanced privacy.
- Updated Sentry integration to hash IP addresses before sending events.
- Enhanced `AllExceptionsFilter` and `crawler-detection.middleware` to use hashed IPs in logs and error handling.
- Refined request logging in `auth.service` to include hashed email instead of plain text email.
2026-02-09 11:05:53 +01:00
Mathis HERRIOT
378c41ddb2 feat(app): enable trust proxy and update app initialization
- Activated `trust proxy` setting to retrieve real IP behind reverse proxies.
- Updated app initialization to use `NestExpressApplication`.
2026-02-09 10:55:11 +01:00
Mathis HERRIOT
65b161dfc6 chore: bump version to 1.9.7
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 2m13s
CI/CD Pipeline / Valider frontend (push) Successful in 2m24s
CI/CD Pipeline / Valider documentation (push) Successful in 2m30s
CI/CD Pipeline / Déploiement en Production (push) Successful in 6m1s
2026-02-09 09:55:41 +01:00
Mathis HERRIOT
75dca88164 style(app): reformat import statements and improve logging structure
- Simplified and condensed import declarations in `app.module.ts`.
- Enhanced error logging format in `crawler-detection.middleware.ts` for better readability.
2026-02-09 09:54:23 +01:00
Mathis HERRIOT
fe7683f5b1 feat(cache): enhance error handling and logging for cache operations
- Added try-catch blocks to improve resilience in cache operations across services.
- Integrated detailed error logging for better debugging.
- Updated Redis reconnect strategy with exponential backoff and logging.
2026-02-09 09:52:40 +01:00
Mathis HERRIOT
22c753d1e7 chore: bump version to 1.9.6
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 1m43s
CI/CD Pipeline / Valider frontend (push) Successful in 1m50s
CI/CD Pipeline / Valider documentation (push) Successful in 1m51s
CI/CD Pipeline / Déploiement en Production (push) Successful in 5m26s
2026-02-01 20:27:58 +01:00
Mathis HERRIOT
1f7bd51a7b feat(docs): add detailed features and business flow diagrams
- Introduced new interaction and community features, including comments and private messaging.
- Added technical diagrams for critical workflows: authentication, content publication, and messaging.
- Enhanced data model documentation with support for comments and messaging tables.
- Updated API references with endpoints for comments, messaging, and user search.
- Integrated post-quantum cryptography for improved data protection.
2026-02-01 20:27:46 +01:00
Mathis HERRIOT
f34fd644b8 chore: bump version to 1.9.5
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 1m38s
CI/CD Pipeline / Valider frontend (push) Successful in 1m43s
CI/CD Pipeline / Valider documentation (push) Successful in 1m47s
CI/CD Pipeline / Déploiement en Production (push) Successful in 17s
2026-01-29 21:42:34 +01:00
Mathis HERRIOT
c827c2e58d feat(database): increase passwordHash length and add migration snapshot
- Extended `passwordHash` field length in `users` schema from 100 to 255.
- Added migration snapshot for schema updates.
2026-01-29 21:42:05 +01:00
Mathis HERRIOT
30bcfdb436 chore: bump version to 1.9.4
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 1m30s
CI/CD Pipeline / Valider documentation (push) Successful in 1m36s
CI/CD Pipeline / Valider frontend (push) Successful in 1m26s
CI/CD Pipeline / Déploiement en Production (push) Successful in 5m19s
2026-01-29 20:49:07 +01:00
Mathis HERRIOT
0b4753c47b style(messages): reformat import statements in MessagesService 2026-01-29 20:48:57 +01:00
Mathis HERRIOT
69b90849fd feat(messages): integrate UsersModule into MessagesModule with forward-ref
- Added `UsersModule` to `MessagesModule` imports using `forwardRef`.
- Injected `UsersService` into `MessagesService` to support user-related operations.
2026-01-29 20:44:35 +01:00
Mathis HERRIOT
f2950ecf86 chore: bump version to 1.9.3
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 1m38s
CI/CD Pipeline / Valider frontend (push) Successful in 1m43s
CI/CD Pipeline / Valider documentation (push) Successful in 1m47s
CI/CD Pipeline / Déploiement en Production (push) Successful in 5m16s
2026-01-29 20:33:19 +01:00
Mathis HERRIOT
1e17308aab feat(realtime): add ConfigModule and UsersModule to RealtimeModule
- Integrated `ConfigModule` for configuration management.
- Added `UsersModule` to enable forward-ref dependencies in realtime services.
2026-01-29 20:32:34 +01:00
Mathis HERRIOT
ca4b594828 chore: bump version to 1.9.2
All checks were successful
CI/CD Pipeline / Valider backend (push) Successful in 1m37s
CI/CD Pipeline / Valider documentation (push) Successful in 1m48s
CI/CD Pipeline / Valider frontend (push) Successful in 1m47s
CI/CD Pipeline / Déploiement en Production (push) Successful in 5m36s
2026-01-29 18:22:00 +01:00
Mathis HERRIOT
2ea16773c8 feat(users): add boolean fields for online status and read receipts
- Added `showOnlineStatus` and `showReadReceipts` fields to `UpdateUserDto` with validation.
2026-01-29 18:21:54 +01:00
Mathis HERRIOT
616d7f76d7 feat: add support for online status and read receipt preferences
- Added `showOnlineStatus` and `showReadReceipts` fields to settings form.
- Introduced real-time synchronization for read receipts in message threads.
- Enhanced avatars to display online status indicators.
- Automatically mark messages as read when viewing active conversations.
2026-01-29 18:20:58 +01:00
Mathis HERRIOT
f882a70343 feat: add read receipt handling based on user preferences
- Integrated `UsersService` into `MessagesService` for retrieving user preferences.
- Updated `markAsRead` functionality to respect `showReadReceipts` preference.
- Enhanced real-time read receipt notifications via `EventsGateway`.
- Added `markAsRead` method to the frontend message service.
2026-01-29 18:20:18 +01:00
Mathis HERRIOT
779bb5c112 feat: integrate user preferences for online status in WebSocket gateway
- Added `UsersService` to manage user preferences in `EventsGateway`.
- Enhanced online/offline broadcasting to respect user `showOnlineStatus` preference.
- Updated `handleTyping` and `check_status` to verify user preferences before emitting events.
- Abstracted status broadcasting logic into `broadcastStatus`.
2026-01-29 18:20:04 +01:00
Mathis HERRIOT
5753477717 feat: add user preferences for online status and read receipts with real-time updates
- Introduced `showOnlineStatus` and `showReadReceipts` fields in the user schema and API.
- Integrated real-time status broadcasting in `UsersService` via `EventsGateway`.
- Updated repository and frontend user types to align with new fields.
- Enhanced user update handling to support dynamic preference changes for online status.
2026-01-29 18:18:52 +01:00
62 changed files with 6358 additions and 139 deletions

View File

@@ -42,6 +42,8 @@ DOMAIN_NAME=localhost
ENABLE_CORS=false ENABLE_CORS=false
CORS_DOMAIN_NAME=localhost CORS_DOMAIN_NAME=localhost
SENTRY_DSN=
NEXT_PUBLIC_SENTRY_DSN=
# Media Limits (in KB) # Media Limits (in KB)
MAX_IMAGE_SIZE_KB=512 MAX_IMAGE_SIZE_KB=512

View File

@@ -106,3 +106,5 @@ jobs:
MAIL_FROM: ${{ secrets.MAIL_FROM }} MAIL_FROM: ${{ secrets.MAIL_FROM }}
DOMAIN_NAME: ${{ secrets.DOMAIN_NAME }} DOMAIN_NAME: ${{ secrets.DOMAIN_NAME }}
NEXT_PUBLIC_API_URL: ${{ secrets.NEXT_PUBLIC_API_URL }} NEXT_PUBLIC_API_URL: ${{ secrets.NEXT_PUBLIC_API_URL }}
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
NEXT_PUBLIC_SENTRY_DSN: ${{ secrets.NEXT_PUBLIC_SENTRY_DSN }}

View File

@@ -0,0 +1,2 @@
ALTER TABLE "users" ADD COLUMN "show_online_status" boolean DEFAULT true NOT NULL;--> statement-breakpoint
ALTER TABLE "users" ADD COLUMN "show_read_receipts" boolean DEFAULT true NOT NULL;

View File

@@ -0,0 +1 @@
ALTER TABLE "users" ALTER COLUMN "password_hash" SET DATA TYPE varchar(255);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -64,6 +64,20 @@
"when": 1769696731978, "when": 1769696731978,
"tag": "0008_bitter_darwin", "tag": "0008_bitter_darwin",
"breakpoints": true "breakpoints": true
},
{
"idx": 9,
"version": "7",
"when": 1769717126917,
"tag": "0009_add_privacy_settings",
"breakpoints": true
},
{
"idx": 10,
"version": "7",
"when": 1769718997591,
"tag": "0010_update_password_hash_length",
"breakpoints": true
} }
] ]
} }

View File

@@ -1,6 +1,6 @@
{ {
"name": "@memegoat/backend", "name": "@memegoat/backend",
"version": "1.9.1", "version": "2.0.0",
"description": "", "description": "",
"author": "", "author": "",
"private": true, "private": true,

View File

@@ -1,5 +1,5 @@
import { CacheModule } from "@nestjs/cache-manager"; import { CacheModule } from "@nestjs/cache-manager";
import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common"; import { Logger, MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config"; import { ConfigModule, ConfigService } from "@nestjs/config";
import { ScheduleModule } from "@nestjs/schedule"; import { ScheduleModule } from "@nestjs/schedule";
import { ThrottlerModule } from "@nestjs/throttler"; import { ThrottlerModule } from "@nestjs/throttler";
@@ -70,12 +70,24 @@ import { UsersModule } from "./users/users.module";
isGlobal: true, isGlobal: true,
imports: [ConfigModule], imports: [ConfigModule],
inject: [ConfigService], inject: [ConfigService],
useFactory: async (config: ConfigService) => ({ useFactory: async (config: ConfigService) => {
store: await redisStore({ const logger = new Logger("RedisCache");
url: `redis://${config.get("REDIS_HOST")}:${config.get("REDIS_PORT")}`, return {
}), store: await redisStore({
ttl: 600, // 10 minutes url: `redis://${config.get("REDIS_HOST")}:${config.get("REDIS_PORT")}`,
}), socket: {
reconnectStrategy: (retries) => {
const delay = Math.min(retries * 50, 2000);
logger.warn(
`Redis connection lost. Retrying in ${delay}ms (attempt ${retries})`,
);
return delay;
},
},
}),
ttl: 600, // 10 minutes
};
},
}), }),
], ],
controllers: [AppController, HealthController], controllers: [AppController, HealthController],

View File

@@ -103,10 +103,9 @@ export class AuthService {
} }
async login(dto: LoginDto, userAgent?: string, ip?: string) { async login(dto: LoginDto, userAgent?: string, ip?: string) {
this.logger.log(`Login attempt for email: ${dto.email}`); const emailHash = await this.hashingService.hashEmail(dto.email);
const { email, password } = dto; this.logger.log(`Login attempt for email hash: ${emailHash}`);
const { password } = dto;
const emailHash = await this.hashingService.hashEmail(email);
const user = await this.usersService.findByEmailHash(emailHash); const user = await this.usersService.findByEmailHash(emailHash);
if (!user) { if (!user) {

View File

@@ -15,8 +15,12 @@ export class CategoriesService {
) {} ) {}
private async clearCategoriesCache() { private async clearCategoriesCache() {
this.logger.log("Clearing categories cache"); try {
await this.cacheManager.del("categories/all"); this.logger.log("Clearing categories cache");
await this.cacheManager.del("categories/all");
} catch (error) {
this.logger.error(`Error clearing categories cache: ${error.message}`);
}
} }
async findAll() { async findAll() {

View File

@@ -0,0 +1,90 @@
import { ArgumentsHost, HttpException, HttpStatus } from "@nestjs/common";
import { Test, TestingModule } from "@nestjs/testing";
import * as Sentry from "@sentry/nestjs";
import { AllExceptionsFilter } from "./http-exception.filter";
jest.mock("@sentry/nestjs", () => ({
captureException: jest.fn(),
withScope: jest.fn((callback) => {
const scope = {
setUser: jest.fn(),
setTag: jest.fn(),
setExtra: jest.fn(),
};
callback(scope);
return scope;
}),
}));
describe("AllExceptionsFilter", () => {
let filter: AllExceptionsFilter;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AllExceptionsFilter],
}).compile();
filter = module.get<AllExceptionsFilter>(AllExceptionsFilter);
});
it("should hash the IP address and send it to Sentry for 500 errors", () => {
const mockResponse = {
status: jest.fn().mockReturnThis(),
json: jest.fn().mockReturnThis(),
};
const mockRequest = {
url: "/test",
method: "GET",
ip: "127.0.0.1",
user: { sub: "user-123" },
};
const mockArgumentsHost = {
switchToHttp: () => ({
getResponse: () => mockResponse,
getRequest: () => mockRequest,
}),
} as ArgumentsHost;
const exception = new Error("Internal Server Error");
filter.catch(exception, mockArgumentsHost);
expect(mockResponse.status).toHaveBeenCalledWith(
HttpStatus.INTERNAL_SERVER_ERROR,
);
expect(Sentry.withScope).toHaveBeenCalled();
// Vérifier que captureException a été appelé (via withScope)
expect(Sentry.captureException).toHaveBeenCalledWith(exception);
});
it("should include hashed IP in logs", () => {
const loggerSpy = jest.spyOn((filter as any).logger, "warn");
const mockResponse = {
status: jest.fn().mockReturnThis(),
json: jest.fn().mockReturnThis(),
};
const mockRequest = {
url: "/test",
method: "GET",
ip: "1.2.3.4",
};
const mockArgumentsHost = {
switchToHttp: () => ({
getResponse: () => mockResponse,
getRequest: () => mockRequest,
}),
} as ArgumentsHost;
const exception = new HttpException("Bad Request", HttpStatus.BAD_REQUEST);
filter.catch(exception, mockArgumentsHost);
expect(mockResponse.status).toHaveBeenCalledWith(HttpStatus.BAD_REQUEST);
// L'IP 1.2.3.4 hachée en SHA256 contient un hash de 64 caractères
const logCall = loggerSpy.mock.calls[0][0];
expect(logCall).toMatch(/[a-f0-9]{64}/);
expect(logCall).not.toContain("1.2.3.4");
});
});

View File

@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import { import {
ArgumentsHost, ArgumentsHost,
Catch, Catch,
@@ -39,6 +40,11 @@ export class AllExceptionsFilter implements ExceptionFilter {
const userId = request.user?.sub || request.user?.id; const userId = request.user?.sub || request.user?.id;
const userPart = userId ? `[User: ${userId}] ` : ""; const userPart = userId ? `[User: ${userId}] ` : "";
const ip = request.ip || "unknown";
const hashedIp = createHash("sha256")
.update(ip as string)
.digest("hex");
const errorResponse = { const errorResponse = {
statusCode: status, statusCode: status,
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
@@ -51,14 +57,20 @@ export class AllExceptionsFilter implements ExceptionFilter {
}; };
if (status === HttpStatus.INTERNAL_SERVER_ERROR) { if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
Sentry.captureException(exception); Sentry.withScope((scope) => {
scope.setUser({
id: userId,
ip_address: hashedIp,
});
Sentry.captureException(exception);
});
this.logger.error( this.logger.error(
`${userPart}${request.method} ${request.url} - Error: ${exception instanceof Error ? exception.message : "Unknown error"}`, `${userPart}${hashedIp} ${request.method} ${request.url} - Error: ${exception instanceof Error ? exception.message : "Unknown error"}`,
exception instanceof Error ? exception.stack : "", exception instanceof Error ? exception.stack : "",
); );
} else { } else {
this.logger.warn( this.logger.warn(
`${userPart}${request.method} ${request.url} - Status: ${status} - Message: ${JSON.stringify(message)}`, `${userPart}${hashedIp} ${request.method} ${request.url} - Status: ${status} - Message: ${JSON.stringify(message)}`,
); );
} }

View File

@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import { CACHE_MANAGER } from "@nestjs/cache-manager"; import { CACHE_MANAGER } from "@nestjs/cache-manager";
import { Inject, Injectable, Logger, NestMiddleware } from "@nestjs/common"; import { Inject, Injectable, Logger, NestMiddleware } from "@nestjs/common";
import type { Cache } from "cache-manager"; import type { Cache } from "cache-manager";
@@ -48,14 +49,25 @@ export class CrawlerDetectionMiddleware implements NestMiddleware {
const { method, url, ip } = req; const { method, url, ip } = req;
const userAgent = req.get("user-agent") || "unknown"; const userAgent = req.get("user-agent") || "unknown";
const hashedIp = createHash("sha256")
.update(ip as string)
.digest("hex");
// Vérifier si l'IP est bannie // Vérifier si l'IP est bannie
const isBanned = await this.cacheManager.get(`banned_ip:${ip}`); try {
if (isBanned) { const isBanned = await this.cacheManager.get(`banned_ip:${ip}`);
this.logger.warn(`Banned IP attempt: ${ip} -> ${method} ${url}`); if (isBanned) {
res.status(403).json({ this.logger.warn(`Banned IP attempt: ${hashedIp} -> ${method} ${url}`);
message: "Access denied: Your IP has been temporarily banned.", res.status(403).json({
}); message: "Access denied: Your IP has been temporarily banned.",
return; });
return;
}
} catch (error) {
this.logger.error(
`Error checking ban status for IP ${hashedIp}: ${error.message}`,
);
// On continue même en cas d'erreur Redis pour ne pas bloquer les utilisateurs légitimes
} }
res.on("finish", async () => { res.on("finish", async () => {
@@ -69,11 +81,15 @@ export class CrawlerDetectionMiddleware implements NestMiddleware {
if (isSuspiciousPath || isBotUserAgent) { if (isSuspiciousPath || isBotUserAgent) {
this.logger.warn( this.logger.warn(
`Potential crawler detected: [${ip}] ${method} ${url} - User-Agent: ${userAgent}`, `Potential crawler detected: [${hashedIp}] ${method} ${url} - User-Agent: ${userAgent}`,
); );
// Bannir l'IP pour 24h via Redis // Bannir l'IP pour 24h via Redis
await this.cacheManager.set(`banned_ip:${ip}`, true, 86400000); try {
await this.cacheManager.set(`banned_ip:${ip}`, true, 86400000);
} catch (error) {
this.logger.error(`Error banning IP ${hashedIp}: ${error.message}`);
}
} }
} }
}); });

View File

@@ -34,8 +34,12 @@ export class ContentsService {
) {} ) {}
private async clearContentsCache() { private async clearContentsCache() {
this.logger.log("Clearing contents cache"); try {
await this.cacheManager.clear(); this.logger.log("Clearing contents cache");
await this.cacheManager.del("contents/all");
} catch (error) {
this.logger.error(`Error clearing contents cache: ${error.message}`);
}
} }
async getUploadUrl(userId: string, fileName: string) { async getUploadUrl(userId: string, fileName: string) {

View File

@@ -21,14 +21,19 @@ const getPgpKey = () => process.env.PGP_ENCRYPTION_KEY || "default-pgp-key";
* withAutomaticPgpDecrypt(users.email); * withAutomaticPgpDecrypt(users.email);
* ``` * ```
*/ */
export const pgpEncrypted = customType<{ data: string; driverData: Buffer }>({ export const pgpEncrypted = customType<{
data: string | null;
driverData: Buffer | string | null | SQL;
}>({
dataType() { dataType() {
return "bytea"; return "bytea";
}, },
toDriver(value: string): SQL { toDriver(value: string | null): SQL | null {
if (value === null) return null;
return sql`pgp_sym_encrypt(${value}, ${getPgpKey()})`; return sql`pgp_sym_encrypt(${value}, ${getPgpKey()})`;
}, },
fromDriver(value: Buffer | string): string { fromDriver(value: Buffer | string | null | any): string | null {
if (value === null || value === undefined) return null;
if (typeof value === "string") return value; if (typeof value === "string") return value;
return value.toString(); return value.toString();
}, },

View File

@@ -29,13 +29,15 @@ export const users = pgTable(
displayName: varchar("display_name", { length: 32 }), displayName: varchar("display_name", { length: 32 }),
username: varchar("username", { length: 32 }).notNull().unique(), username: varchar("username", { length: 32 }).notNull().unique(),
passwordHash: varchar("password_hash", { length: 100 }).notNull(), passwordHash: varchar("password_hash", { length: 255 }).notNull(),
avatarUrl: varchar("avatar_url", { length: 512 }), avatarUrl: varchar("avatar_url", { length: 512 }),
bio: varchar("bio", { length: 255 }), bio: varchar("bio", { length: 255 }),
// Sécurité // Sécurité
twoFactorSecret: pgpEncrypted("two_factor_secret"), twoFactorSecret: pgpEncrypted("two_factor_secret"),
isTwoFactorEnabled: boolean("is_two_factor_enabled").notNull().default(false), isTwoFactorEnabled: boolean("is_two_factor_enabled").notNull().default(false),
showOnlineStatus: boolean("show_online_status").notNull().default(true),
showReadReceipts: boolean("show_read_receipts").notNull().default(true),
// RGPD & Conformité // RGPD & Conformité
termsVersion: varchar("terms_version", { length: 16 }), // Version des CGU acceptées termsVersion: varchar("terms_version", { length: 16 }), // Version des CGU acceptées

View File

@@ -1,8 +1,13 @@
import { CACHE_MANAGER } from "@nestjs/cache-manager"; import { CACHE_MANAGER } from "@nestjs/cache-manager";
import { Test, TestingModule } from "@nestjs/testing"; import { Test, TestingModule } from "@nestjs/testing";
import * as Sentry from "@sentry/nestjs";
import { DatabaseService } from "./database/database.service"; import { DatabaseService } from "./database/database.service";
import { HealthController } from "./health.controller"; import { HealthController } from "./health.controller";
jest.mock("@sentry/nestjs", () => ({
getClient: jest.fn(),
}));
describe("HealthController", () => { describe("HealthController", () => {
let controller: HealthController; let controller: HealthController;
@@ -37,10 +42,15 @@ describe("HealthController", () => {
it("should return ok if database and redis are connected", async () => { it("should return ok if database and redis are connected", async () => {
mockDb.execute.mockResolvedValue([]); mockDb.execute.mockResolvedValue([]);
mockCacheManager.set.mockResolvedValue(undefined); mockCacheManager.set.mockResolvedValue(undefined);
(Sentry.getClient as jest.Mock).mockReturnValue({
getOptions: () => ({ dsn: "http://dsn" }),
});
const result = await controller.check(); const result = await controller.check();
expect(result.status).toBe("ok"); expect(result.status).toBe("ok");
expect(result.database).toBe("connected"); expect(result.database).toBe("connected");
expect(result.redis).toBe("connected"); expect(result.redis).toBe("connected");
expect(result.sentry).toBe("active");
}); });
it("should return error if database is disconnected", async () => { it("should return error if database is disconnected", async () => {
@@ -62,4 +72,19 @@ describe("HealthController", () => {
expect(result.redis).toBe("disconnected"); expect(result.redis).toBe("disconnected");
expect(result.redisError).toBe("Redis Error"); expect(result.redisError).toBe("Redis Error");
}); });
it("should return sentry disabled if client or dsn is missing", async () => {
mockDb.execute.mockResolvedValue([]);
mockCacheManager.set.mockResolvedValue(undefined);
(Sentry.getClient as jest.Mock).mockReturnValue(undefined);
const result = await controller.check();
expect(result.sentry).toBe("disabled");
(Sentry.getClient as jest.Mock).mockReturnValue({
getOptions: () => ({ dsn: undefined }),
});
const result2 = await controller.check();
expect(result2.sentry).toBe("disabled");
});
}); });

View File

@@ -1,5 +1,6 @@
import { CACHE_MANAGER } from "@nestjs/cache-manager"; import { CACHE_MANAGER } from "@nestjs/cache-manager";
import { Controller, Get, Inject } from "@nestjs/common"; import { Controller, Get, Inject } from "@nestjs/common";
import * as Sentry from "@sentry/nestjs";
import type { Cache } from "cache-manager"; import type { Cache } from "cache-manager";
import { sql } from "drizzle-orm"; import { sql } from "drizzle-orm";
import { DatabaseService } from "./database/database.service"; import { DatabaseService } from "./database/database.service";
@@ -39,6 +40,14 @@ export class HealthController {
health.redisError = error.message; health.redisError = error.message;
} }
// Check Sentry status
const sentryClient = Sentry.getClient();
if (sentryClient?.getOptions().dsn) {
health.sentry = "active";
} else {
health.sentry = "disabled";
}
return health; return health;
} }
} }

View File

@@ -1,6 +1,8 @@
import { createHash } from "node:crypto";
import { Logger, ValidationPipe } from "@nestjs/common"; import { Logger, ValidationPipe } from "@nestjs/common";
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import { NestFactory } from "@nestjs/core"; import { NestFactory } from "@nestjs/core";
import { NestExpressApplication } from "@nestjs/platform-express";
import * as Sentry from "@sentry/nestjs"; import * as Sentry from "@sentry/nestjs";
import { nodeProfilingIntegration } from "@sentry/profiling-node"; import { nodeProfilingIntegration } from "@sentry/profiling-node";
import helmet from "helmet"; import helmet from "helmet";
@@ -8,19 +10,44 @@ import { AppModule } from "./app.module";
import { AllExceptionsFilter } from "./common/filters/http-exception.filter"; import { AllExceptionsFilter } from "./common/filters/http-exception.filter";
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create<NestExpressApplication>(AppModule);
const configService = app.get(ConfigService); const configService = app.get(ConfigService);
const logger = new Logger("Bootstrap"); const logger = new Logger("Bootstrap");
// Activer trust proxy pour récupérer l'IP réelle derrière un reverse proxy
app.set("trust proxy", true);
const sentryDsn = configService.get<string>("SENTRY_DSN"); const sentryDsn = configService.get<string>("SENTRY_DSN");
if (sentryDsn) { if (sentryDsn) {
Sentry.init({ try {
dsn: sentryDsn, Sentry.init({
integrations: [nodeProfilingIntegration()], dsn: sentryDsn,
tracesSampleRate: 1.0, integrations: [Sentry.nestIntegration(), nodeProfilingIntegration()],
profilesSampleRate: 1.0, tracesSampleRate: 1.0,
sendDefaultPii: false, // RGPD profilesSampleRate: 1.0,
}); sendDefaultPii: false, // RGPD
beforeSend(event) {
// Hachage de l'IP utilisateur pour Sentry si elle est présente
if (event.user?.ip_address) {
event.user.ip_address = createHash("sha256")
.update(event.user.ip_address)
.digest("hex");
}
return event;
},
});
const client = Sentry.getClient();
if (client?.getOptions().dsn) {
logger.log("Sentry is initialized and connection is active");
} else {
logger.warn("Sentry initialized but DSN is missing");
}
} catch (error) {
logger.error(`Failed to initialize Sentry: ${error.message}`);
}
} else {
logger.warn("Sentry is disabled (SENTRY_DSN not configured)");
} }
// Sécurité // Sécurité

View File

@@ -1,12 +1,13 @@
import { Module } from "@nestjs/common"; import { forwardRef, Module } from "@nestjs/common";
import { AuthModule } from "../auth/auth.module"; import { AuthModule } from "../auth/auth.module";
import { RealtimeModule } from "../realtime/realtime.module"; import { RealtimeModule } from "../realtime/realtime.module";
import { UsersModule } from "../users/users.module";
import { MessagesController } from "./messages.controller"; import { MessagesController } from "./messages.controller";
import { MessagesService } from "./messages.service"; import { MessagesService } from "./messages.service";
import { MessagesRepository } from "./repositories/messages.repository"; import { MessagesRepository } from "./repositories/messages.repository";
@Module({ @Module({
imports: [AuthModule, RealtimeModule], imports: [AuthModule, RealtimeModule, forwardRef(() => UsersModule)],
controllers: [MessagesController], controllers: [MessagesController],
providers: [MessagesService, MessagesRepository], providers: [MessagesService, MessagesRepository],
exports: [MessagesService], exports: [MessagesService],

View File

@@ -1,6 +1,7 @@
import { ForbiddenException } from "@nestjs/common"; import { ForbiddenException } from "@nestjs/common";
import { Test, TestingModule } from "@nestjs/testing"; import { Test, TestingModule } from "@nestjs/testing";
import { EventsGateway } from "../realtime/events.gateway"; import { EventsGateway } from "../realtime/events.gateway";
import { UsersService } from "../users/users.service";
import { MessagesService } from "./messages.service"; import { MessagesService } from "./messages.service";
import { MessagesRepository } from "./repositories/messages.repository"; import { MessagesRepository } from "./repositories/messages.repository";
@@ -16,6 +17,7 @@ describe("MessagesService", () => {
createMessage: jest.fn(), createMessage: jest.fn(),
findAllConversations: jest.fn(), findAllConversations: jest.fn(),
isParticipant: jest.fn(), isParticipant: jest.fn(),
getParticipants: jest.fn(),
findMessagesByConversationId: jest.fn(), findMessagesByConversationId: jest.fn(),
markAsRead: jest.fn(), markAsRead: jest.fn(),
countUnreadMessages: jest.fn(), countUnreadMessages: jest.fn(),
@@ -25,12 +27,17 @@ describe("MessagesService", () => {
sendToUser: jest.fn(), sendToUser: jest.fn(),
}; };
const mockUsersService = {
findOne: jest.fn(),
};
beforeEach(async () => { beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({ const module: TestingModule = await Test.createTestingModule({
providers: [ providers: [
MessagesService, MessagesService,
{ provide: MessagesRepository, useValue: mockMessagesRepository }, { provide: MessagesRepository, useValue: mockMessagesRepository },
{ provide: EventsGateway, useValue: mockEventsGateway }, { provide: EventsGateway, useValue: mockEventsGateway },
{ provide: UsersService, useValue: mockUsersService },
], ],
}).compile(); }).compile();

View File

@@ -1,5 +1,11 @@
import { ForbiddenException, Injectable } from "@nestjs/common"; import {
ForbiddenException,
forwardRef,
Inject,
Injectable,
} from "@nestjs/common";
import { EventsGateway } from "../realtime/events.gateway"; import { EventsGateway } from "../realtime/events.gateway";
import { UsersService } from "../users/users.service";
import type { CreateMessageDto } from "./dto/create-message.dto"; import type { CreateMessageDto } from "./dto/create-message.dto";
import { MessagesRepository } from "./repositories/messages.repository"; import { MessagesRepository } from "./repositories/messages.repository";
@@ -8,6 +14,8 @@ export class MessagesService {
constructor( constructor(
private readonly messagesRepository: MessagesRepository, private readonly messagesRepository: MessagesRepository,
private readonly eventsGateway: EventsGateway, private readonly eventsGateway: EventsGateway,
@Inject(forwardRef(() => UsersService))
private readonly usersService: UsersService,
) {} ) {}
async sendMessage(senderId: string, dto: CreateMessageDto) { async sendMessage(senderId: string, dto: CreateMessageDto) {
@@ -62,8 +70,24 @@ export class MessagesService {
throw new ForbiddenException("You are not part of this conversation"); throw new ForbiddenException("You are not part of this conversation");
} }
// Marquer comme lus // Récupérer les préférences de l'utilisateur actuel
await this.messagesRepository.markAsRead(conversationId, userId); const user = await this.usersService.findOne(userId);
// Marquer comme lus seulement si l'utilisateur l'autorise
if (user?.showReadReceipts) {
await this.messagesRepository.markAsRead(conversationId, userId);
// Notifier l'expéditeur que les messages ont été lus
const participants =
await this.messagesRepository.getParticipants(conversationId);
const otherParticipant = participants.find((p) => p.userId !== userId);
if (otherParticipant) {
this.eventsGateway.sendToUser(otherParticipant.userId, "messages_read", {
conversationId,
readerId: userId,
});
}
}
return this.messagesRepository.findMessagesByConversationId(conversationId); return this.messagesRepository.findMessagesByConversationId(conversationId);
} }
@@ -76,6 +100,26 @@ export class MessagesService {
if (!isParticipant) { if (!isParticipant) {
throw new ForbiddenException("You are not part of this conversation"); throw new ForbiddenException("You are not part of this conversation");
} }
return this.messagesRepository.markAsRead(conversationId, userId);
const user = await this.usersService.findOne(userId);
if (!user?.showReadReceipts) return;
const result = await this.messagesRepository.markAsRead(
conversationId,
userId,
);
// Notifier l'autre participant
const participants =
await this.messagesRepository.getParticipants(conversationId);
const otherParticipant = participants.find((p) => p.userId !== userId);
if (otherParticipant) {
this.eventsGateway.sendToUser(otherParticipant.userId, "messages_read", {
conversationId,
readerId: userId,
});
}
return result;
} }
} }

View File

@@ -1,6 +1,7 @@
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import { Test, TestingModule } from "@nestjs/testing"; import { Test, TestingModule } from "@nestjs/testing";
import { JwtService } from "../crypto/services/jwt.service"; import { JwtService } from "../crypto/services/jwt.service";
import { UsersService } from "../users/users.service";
import { EventsGateway } from "./events.gateway"; import { EventsGateway } from "./events.gateway";
describe("EventsGateway", () => { describe("EventsGateway", () => {
@@ -15,12 +16,17 @@ describe("EventsGateway", () => {
get: jest.fn().mockReturnValue("secret-password-32-chars-long-!!!"), get: jest.fn().mockReturnValue("secret-password-32-chars-long-!!!"),
}; };
const mockUsersService = {
findOne: jest.fn(),
};
beforeEach(async () => { beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({ const module: TestingModule = await Test.createTestingModule({
providers: [ providers: [
EventsGateway, EventsGateway,
{ provide: JwtService, useValue: mockJwtService }, { provide: JwtService, useValue: mockJwtService },
{ provide: ConfigService, useValue: mockConfigService }, { provide: ConfigService, useValue: mockConfigService },
{ provide: UsersService, useValue: mockUsersService },
], ],
}).compile(); }).compile();

View File

@@ -1,4 +1,4 @@
import { Logger } from "@nestjs/common"; import { forwardRef, Inject, Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import { import {
ConnectedSocket, ConnectedSocket,
@@ -14,6 +14,7 @@ import { getIronSession } from "iron-session";
import { Server, Socket } from "socket.io"; import { Server, Socket } from "socket.io";
import { getSessionOptions, SessionData } from "../auth/session.config"; import { getSessionOptions, SessionData } from "../auth/session.config";
import { JwtService } from "../crypto/services/jwt.service"; import { JwtService } from "../crypto/services/jwt.service";
import { UsersService } from "../users/users.service";
@WebSocketGateway({ @WebSocketGateway({
transports: ["websocket"], transports: ["websocket"],
@@ -63,6 +64,8 @@ export class EventsGateway
constructor( constructor(
private readonly jwtService: JwtService, private readonly jwtService: JwtService,
private readonly configService: ConfigService, private readonly configService: ConfigService,
@Inject(forwardRef(() => UsersService))
private readonly usersService: UsersService,
) {} ) {}
afterInit(_server: Server) { afterInit(_server: Server) {
@@ -106,9 +109,15 @@ export class EventsGateway
// Gérer le statut en ligne // Gérer le statut en ligne
const userId = payload.sub as string; const userId = payload.sub as string;
if (!this.onlineUsers.has(userId)) { if (!this.onlineUsers.has(userId)) {
this.onlineUsers.set(userId, new Set()); this.onlineUsers.set(userId, new Set());
this.server.emit("user_status", { userId, status: "online" });
// Vérifier les préférences de l'utilisateur
const user = await this.usersService.findOne(userId);
if (user?.showOnlineStatus) {
this.broadcastStatus(userId, "online");
}
} }
this.onlineUsers.get(userId)?.add(client.id); this.onlineUsers.get(userId)?.add(client.id);
@@ -119,19 +128,31 @@ export class EventsGateway
} }
} }
handleDisconnect(client: Socket) { async handleDisconnect(client: Socket) {
const userId = client.data.user?.sub; const userId = client.data.user?.sub;
if (userId && this.onlineUsers.has(userId)) { if (userId && this.onlineUsers.has(userId)) {
const sockets = this.onlineUsers.get(userId); const sockets = this.onlineUsers.get(userId);
sockets?.delete(client.id); sockets?.delete(client.id);
if (sockets?.size === 0) { if (sockets?.size === 0) {
this.onlineUsers.delete(userId); this.onlineUsers.delete(userId);
this.server.emit("user_status", { userId, status: "offline" });
const user = await this.usersService.findOne(userId);
if (user?.showOnlineStatus) {
this.broadcastStatus(userId, "offline");
}
} }
} }
this.logger.log(`Client disconnected: ${client.id}`); this.logger.log(`Client disconnected: ${client.id}`);
} }
broadcastStatus(userId: string, status: "online" | "offline") {
this.server.emit("user_status", { userId, status });
}
isUserOnline(userId: string): boolean {
return this.onlineUsers.has(userId);
}
@SubscribeMessage("join_content") @SubscribeMessage("join_content")
handleJoinContent( handleJoinContent(
@ConnectedSocket() client: Socket, @ConnectedSocket() client: Socket,
@@ -151,13 +172,20 @@ export class EventsGateway
} }
@SubscribeMessage("typing") @SubscribeMessage("typing")
handleTyping( async handleTyping(
@ConnectedSocket() client: Socket, @ConnectedSocket() client: Socket,
@MessageBody() data: { recipientId: string; isTyping: boolean }, @MessageBody() data: { recipientId: string; isTyping: boolean },
) { ) {
const userId = client.data.user?.sub; const userId = client.data.user?.sub;
if (!userId) return; if (!userId) return;
// Optionnel: vérifier si l'utilisateur autorise le statut en ligne avant d'émettre "typing"
// ou si on considère que typing est une interaction directe qui outrepasse le statut.
// Instagram affiche "Typing..." même si le statut en ligne est désactivé si on est dans le chat.
// Mais par souci de cohérence avec "showOnlineStatus", on peut le vérifier.
const user = await this.usersService.findOne(userId);
if (!user?.showOnlineStatus) return;
this.server.to(`user:${data.recipientId}`).emit("user_typing", { this.server.to(`user:${data.recipientId}`).emit("user_typing", {
userId, userId,
isTyping: data.isTyping, isTyping: data.isTyping,
@@ -165,13 +193,19 @@ export class EventsGateway
} }
@SubscribeMessage("check_status") @SubscribeMessage("check_status")
handleCheckStatus( async handleCheckStatus(
@ConnectedSocket() _client: Socket, @ConnectedSocket() _client: Socket,
@MessageBody() userId: string, @MessageBody() userId: string,
) { ) {
const isOnline = this.onlineUsers.has(userId);
if (!isOnline) return { userId, status: "offline" };
const user = await this.usersService.findOne(userId);
if (!user?.showOnlineStatus) return { userId, status: "offline" };
return { return {
userId, userId,
status: this.onlineUsers.has(userId) ? "online" : "offline", status: "online",
}; };
} }

View File

@@ -1,9 +1,11 @@
import { Module } from "@nestjs/common"; import { forwardRef, Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { CryptoModule } from "../crypto/crypto.module"; import { CryptoModule } from "../crypto/crypto.module";
import { UsersModule } from "../users/users.module";
import { EventsGateway } from "./events.gateway"; import { EventsGateway } from "./events.gateway";
@Module({ @Module({
imports: [CryptoModule], imports: [CryptoModule, ConfigModule, forwardRef(() => UsersModule)],
providers: [EventsGateway], providers: [EventsGateway],
exports: [EventsGateway], exports: [EventsGateway],
}) })

View File

@@ -1,4 +1,4 @@
import { IsOptional, IsString, MaxLength } from "class-validator"; import { IsBoolean, IsOptional, IsString, MaxLength } from "class-validator";
export class UpdateUserDto { export class UpdateUserDto {
@IsOptional() @IsOptional()
@@ -22,4 +22,12 @@ export class UpdateUserDto {
@IsOptional() @IsOptional()
@IsString() @IsString()
role?: string; role?: string;
@IsOptional()
@IsBoolean()
showOnlineStatus?: boolean;
@IsOptional()
@IsBoolean()
showReadReceipts?: boolean;
} }

View File

@@ -47,6 +47,8 @@ export class UsersRepository {
bio: users.bio, bio: users.bio,
status: users.status, status: users.status,
isTwoFactorEnabled: users.isTwoFactorEnabled, isTwoFactorEnabled: users.isTwoFactorEnabled,
showOnlineStatus: users.showOnlineStatus,
showReadReceipts: users.showReadReceipts,
createdAt: users.createdAt, createdAt: users.createdAt,
updatedAt: users.updatedAt, updatedAt: users.updatedAt,
}) })

View File

@@ -1,13 +1,19 @@
import { forwardRef, Module } from "@nestjs/common"; import { forwardRef, Module } from "@nestjs/common";
import { AuthModule } from "../auth/auth.module"; import { AuthModule } from "../auth/auth.module";
import { MediaModule } from "../media/media.module"; import { MediaModule } from "../media/media.module";
import { RealtimeModule } from "../realtime/realtime.module";
import { S3Module } from "../s3/s3.module"; import { S3Module } from "../s3/s3.module";
import { UsersRepository } from "./repositories/users.repository"; import { UsersRepository } from "./repositories/users.repository";
import { UsersController } from "./users.controller"; import { UsersController } from "./users.controller";
import { UsersService } from "./users.service"; import { UsersService } from "./users.service";
@Module({ @Module({
imports: [forwardRef(() => AuthModule), MediaModule, S3Module], imports: [
forwardRef(() => AuthModule),
MediaModule,
S3Module,
forwardRef(() => RealtimeModule),
],
controllers: [UsersController], controllers: [UsersController],
providers: [UsersService, UsersRepository], providers: [UsersService, UsersRepository],
exports: [UsersService, UsersRepository], exports: [UsersService, UsersRepository],

View File

@@ -20,6 +20,7 @@ import { ConfigService } from "@nestjs/config";
import { Test, TestingModule } from "@nestjs/testing"; import { Test, TestingModule } from "@nestjs/testing";
import { RbacService } from "../auth/rbac.service"; import { RbacService } from "../auth/rbac.service";
import { MediaService } from "../media/media.service"; import { MediaService } from "../media/media.service";
import { EventsGateway } from "../realtime/events.gateway";
import { S3Service } from "../s3/s3.service"; import { S3Service } from "../s3/s3.service";
import { UsersRepository } from "./repositories/users.repository"; import { UsersRepository } from "./repositories/users.repository";
import { UsersService } from "./users.service"; import { UsersService } from "./users.service";
@@ -49,6 +50,7 @@ describe("UsersService", () => {
const mockRbacService = { const mockRbacService = {
getUserRoles: jest.fn(), getUserRoles: jest.fn(),
assignRoleToUser: jest.fn(),
}; };
const mockMediaService = { const mockMediaService = {
@@ -65,6 +67,11 @@ describe("UsersService", () => {
get: jest.fn(), get: jest.fn(),
}; };
const mockEventsGateway = {
isUserOnline: jest.fn(),
broadcastStatus: jest.fn(),
};
beforeEach(async () => { beforeEach(async () => {
jest.clearAllMocks(); jest.clearAllMocks();
@@ -77,6 +84,7 @@ describe("UsersService", () => {
{ provide: MediaService, useValue: mockMediaService }, { provide: MediaService, useValue: mockMediaService },
{ provide: S3Service, useValue: mockS3Service }, { provide: S3Service, useValue: mockS3Service },
{ provide: ConfigService, useValue: mockConfigService }, { provide: ConfigService, useValue: mockConfigService },
{ provide: EventsGateway, useValue: mockEventsGateway },
], ],
}).compile(); }).compile();

View File

@@ -12,6 +12,7 @@ import { RbacService } from "../auth/rbac.service";
import type { IMediaService } from "../common/interfaces/media.interface"; import type { IMediaService } from "../common/interfaces/media.interface";
import type { IStorageService } from "../common/interfaces/storage.interface"; import type { IStorageService } from "../common/interfaces/storage.interface";
import { MediaService } from "../media/media.service"; import { MediaService } from "../media/media.service";
import { EventsGateway } from "../realtime/events.gateway";
import { S3Service } from "../s3/s3.service"; import { S3Service } from "../s3/s3.service";
import { UpdateUserDto } from "./dto/update-user.dto"; import { UpdateUserDto } from "./dto/update-user.dto";
import { UsersRepository } from "./repositories/users.repository"; import { UsersRepository } from "./repositories/users.repository";
@@ -27,11 +28,17 @@ export class UsersService {
private readonly rbacService: RbacService, private readonly rbacService: RbacService,
@Inject(MediaService) private readonly mediaService: IMediaService, @Inject(MediaService) private readonly mediaService: IMediaService,
@Inject(S3Service) private readonly s3Service: IStorageService, @Inject(S3Service) private readonly s3Service: IStorageService,
@Inject(forwardRef(() => EventsGateway))
private readonly eventsGateway: EventsGateway,
) {} ) {}
private async clearUserCache(username?: string) { private async clearUserCache(username?: string) {
if (username) { try {
await this.cacheManager.del(`users/profile/${username}`); if (username) {
await this.cacheManager.del(`users/profile/${username}`);
}
} catch (error) {
this.logger.error(`Error clearing user cache: ${error.message}`);
} }
} }
@@ -137,6 +144,9 @@ export class UsersService {
const { role, ...userData } = data; const { role, ...userData } = data;
// On récupère l'utilisateur actuel avant mise à jour pour comparer les préférences
const oldUser = await this.usersRepository.findOne(uuid);
const result = await this.usersRepository.update(uuid, userData); const result = await this.usersRepository.update(uuid, userData);
if (role) { if (role) {
@@ -145,6 +155,21 @@ export class UsersService {
if (result[0]) { if (result[0]) {
await this.clearUserCache(result[0].username); await this.clearUserCache(result[0].username);
// Gérer le changement de préférence de statut en ligne
if (
data.showOnlineStatus !== undefined &&
data.showOnlineStatus !== oldUser?.showOnlineStatus
) {
const isOnline = this.eventsGateway.isUserOnline(uuid);
if (isOnline) {
if (data.showOnlineStatus) {
this.eventsGateway.broadcastStatus(uuid, "online");
} else {
this.eventsGateway.broadcastStatus(uuid, "offline");
}
}
}
} }
return result; return result;
} }

View File

@@ -104,6 +104,7 @@ services:
ENABLE_CORS: ${ENABLE_CORS:-true} ENABLE_CORS: ${ENABLE_CORS:-true}
CLAMAV_HOST: memegoat-clamav CLAMAV_HOST: memegoat-clamav
CLAMAV_PORT: 3310 CLAMAV_PORT: 3310
SENTRY_DSN: ${SENTRY_DSN}
MAX_IMAGE_SIZE_KB: 1024 MAX_IMAGE_SIZE_KB: 1024
MAX_GIF_SIZE_KB: 4096 MAX_GIF_SIZE_KB: 4096
@@ -133,6 +134,7 @@ services:
NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL:-https://api.memegoat.fr} NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL:-https://api.memegoat.fr}
NEXT_PUBLIC_APP_URL: ${NEXT_PUBLIC_APP_URL:-https://memegoat.fr} NEXT_PUBLIC_APP_URL: ${NEXT_PUBLIC_APP_URL:-https://memegoat.fr}
NEXT_PUBLIC_CONTACT_EMAIL: ${MAIL_FROM:-noreply@memegoat.fr} NEXT_PUBLIC_CONTACT_EMAIL: ${MAIL_FROM:-noreply@memegoat.fr}
NEXT_PUBLIC_SENTRY_DSN: ${NEXT_PUBLIC_SENTRY_DSN}
depends_on: depends_on:
- backend - backend

View File

@@ -98,6 +98,7 @@ services:
ENABLE_CORS: ${ENABLE_CORS:-true} ENABLE_CORS: ${ENABLE_CORS:-true}
CLAMAV_HOST: clamav CLAMAV_HOST: clamav
CLAMAV_PORT: 3310 CLAMAV_PORT: 3310
SENTRY_DSN: ${SENTRY_DSN}
clamav: clamav:
image: clamav/clamav:1.4 image: clamav/clamav:1.4
@@ -121,6 +122,7 @@ services:
environment: environment:
NODE_ENV: production NODE_ENV: production
NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL:-http://localhost:3000} NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL:-http://localhost:3000}
NEXT_PUBLIC_SENTRY_DSN: ${NEXT_PUBLIC_SENTRY_DSN}
depends_on: depends_on:
- backend - backend

View File

@@ -7,6 +7,7 @@
"features": "Fonctionnalités", "features": "Fonctionnalités",
"stack": "Stack Technologique", "stack": "Stack Technologique",
"database": "Modèle de Données", "database": "Modèle de Données",
"flows": "Flux Métiers",
"---security---": { "---security---": {
"type": "separator", "type": "separator",
"label": "Sécurité & Conformité" "label": "Sécurité & Conformité"

View File

@@ -216,6 +216,16 @@ Cette page documente tous les points de terminaison disponibles sur l'API Memego
- `200 OK` : 2FA désactivée. - `200 OK` : 2FA désactivée.
</Accordion> </Accordion>
<Accordion title="GET /users/search">
Recherche des utilisateurs par leur nom d'utilisateur ou nom d'affichage. Requiert l'authentification.
**Query Params :**
- `q` (string) : Terme de recherche.
**Réponses :**
- `200 OK` : Liste des utilisateurs correspondants.
</Accordion>
<Accordion title="GET /users/admin"> <Accordion title="GET /users/admin">
Liste tous les utilisateurs. **Réservé aux administrateurs.** Liste tous les utilisateurs. **Réservé aux administrateurs.**
@@ -406,6 +416,92 @@ Cette page documente tous les points de terminaison disponibles sur l'API Memego
</Accordion> </Accordion>
</Accordions> </Accordions>
### 💬 Commentaires (`/comments` & `/contents/:id/comments`)
<Accordions>
<Accordion title="GET /contents/:contentId/comments">
Liste les commentaires d'un contenu.
**Réponses :**
- `200 OK` : Liste des commentaires, incluant l'auteur et si l'utilisateur actuel a aimé le commentaire.
</Accordion>
<Accordion title="POST /contents/:contentId/comments">
Ajoute un commentaire à un contenu. Requiert l'authentification.
**Corps de la requête :**
- `text` (string) : Contenu du commentaire.
- `parentId` (uuid, optional) : ID du commentaire parent pour les réponses.
**Réponses :**
- `201 Created` : Commentaire ajouté.
</Accordion>
<Accordion title="DELETE /comments/:id">
Supprime un commentaire. L'utilisateur doit être l'auteur ou un modérateur/admin.
**Réponses :**
- `200 OK` : Commentaire supprimé.
</Accordion>
<Accordion title="POST /comments/:id/like">
Ajoute un "like" à un commentaire. Requiert l'authentification.
**Réponses :**
- `201 Created` : Like ajouté.
</Accordion>
<Accordion title="DELETE /comments/:id/like">
Retire un "like" d'un commentaire. Requiert l'authentification.
**Réponses :**
- `200 OK` : Like retiré.
</Accordion>
</Accordions>
### ✉️ Messagerie (`/messages`)
<Accordions>
<Accordion title="GET /messages/conversations">
Liste les conversations de l'utilisateur connecté. Requiert l'authentification.
**Réponses :**
- `200 OK` : Liste des conversations avec le dernier message et le nombre de messages non lus.
</Accordion>
<Accordion title="GET /messages/unread-count">
Récupère le nombre total de messages non lus pour l'utilisateur. Requiert l'authentification.
**Réponses :**
- `200 OK` : `{ "count": number }`.
</Accordion>
<Accordion title="GET /messages/conversations/with/:userId">
Récupère ou crée une conversation avec un utilisateur spécifique. Requiert l'authentification.
**Réponses :**
- `200 OK` : Objet conversation.
</Accordion>
<Accordion title="GET /messages/conversations/:id">
Récupère les messages d'une conversation. Marque les messages comme lus. Requiert l'authentification.
**Réponses :**
- `200 OK` : Liste des messages.
</Accordion>
<Accordion title="POST /messages">
Envoie un message. Requiert l'authentification.
**Corps de la requête :**
- `recipientId` (uuid) : ID du destinataire.
- `text` (string) : Contenu du message.
**Réponses :**
- `201 Created` : Message envoyé.
</Accordion>
</Accordions>
### ⭐ Favoris (`/favorites`) ### ⭐ Favoris (`/favorites`)
<Accordions> <Accordions>

View File

@@ -29,4 +29,4 @@ Memegoat utilise une architecture de stockage d'objets compatible S3 (MinIO). Le
### Notifications (Mail) ### Notifications (Mail)
Le système intègre un service d'envoi d'emails (SMTP) pour les notifications critiques et la gestion des comptes. Le système intègre un service d'envoi d'emails (SMTP) via `@nestjs-modules/mailer` pour les notifications critiques, la validation des comptes et la réinitialisation de mots de passe.

View File

@@ -19,7 +19,8 @@ Le projet Memegoat s'inscrit dans une démarche de respect de la vie privée et
Conformément à la section [Sécurité](/docs/security), les mesures suivantes sont appliquées : Conformément à la section [Sécurité](/docs/security), les mesures suivantes sont appliquées :
- **Chiffrement au repos** : Utilisation de **PGP (pgcrypto)** pour les données identifiantes. - **Chiffrement au repos** : Utilisation de **PGP (pgcrypto)** pour les données identifiantes.
- **Hachage aveugle** : Pour permettre les opérations sur données chiffrées sans compromettre la confidentialité. - **Cryptographie Post-Quantique** : Mise en œuvre de `@noble/post-quantum` pour protéger les données contre les futures capacités de calcul quantique.
- **Hachage aveugle (Blind Indexing)** : Pour permettre les opérations d'unicité et de recherche sur données chiffrées sans compromettre la confidentialité.
- **Hachage des mots de passe** : Utilisation de l'algorithme **Argon2id**. - **Hachage des mots de passe** : Utilisation de l'algorithme **Argon2id**.
- **Communications sécurisées** : Utilisation de **TLS 1.3** via Caddy. - **Communications sécurisées** : Utilisation de **TLS 1.3** via Caddy.
- **Suivi des Erreurs (Sentry)** : Configuration conforme avec désactivation de l'envoi des PII (Personally Identifiable Information) et masquage des données sensibles. - **Suivi des Erreurs (Sentry)** : Configuration conforme avec désactivation de l'envoi des PII (Personally Identifiable Information) et masquage des données sensibles.

View File

@@ -18,13 +18,24 @@ erDiagram
USER ||--o{ API_KEY : "genere" USER ||--o{ API_KEY : "genere"
USER ||--o{ AUDIT_LOG : "genere" USER ||--o{ AUDIT_LOG : "genere"
USER ||--o{ FAVORITE : "ajoute" USER ||--o{ FAVORITE : "ajoute"
USER ||--o{ COMMENT : "rédige"
USER ||--o{ COMMENT_LIKE : "aime"
USER ||--o{ CONVERSATION_PARTICIPANT : "participe"
USER ||--o{ MESSAGE : "envoie"
CONTENT ||--o{ CONTENT_TAG : "possede" CONTENT ||--o{ CONTENT_TAG : "possede"
TAG ||--o{ CONTENT_TAG : "est_lie_a" TAG ||--o{ CONTENT_TAG : "est_lie_a"
CONTENT ||--o{ REPORT : "est_signale" CONTENT ||--o{ REPORT : "est_signale"
CONTENT ||--o{ FAVORITE : "est_mis_en" CONTENT ||--o{ FAVORITE : "est_mis_en"
CONTENT ||--o{ COMMENT : "reçoit"
TAG ||--o{ REPORT : "est_signale" TAG ||--o{ REPORT : "est_signale"
COMMENT ||--o{ COMMENT : "possède des réponses"
COMMENT ||--o{ COMMENT_LIKE : "est aimé par"
CONVERSATION ||--o{ CONVERSATION_PARTICIPANT : "regroupe"
CONVERSATION ||--o{ MESSAGE : "contient"
CATEGORY ||--o{ CONTENT : "catégorise" CATEGORY ||--o{ CONTENT : "catégorise"
ROLE ||--o{ USER_ROLE : "attribue_a" ROLE ||--o{ USER_ROLE : "attribue_a"
@@ -45,6 +56,15 @@ erDiagram
string type string type
string storage_key string storage_key
} }
COMMENT {
string text
}
CONVERSATION {
timestamp created_at
}
MESSAGE {
string text
}
TAG { TAG {
string name string name
string slug string slug
@@ -140,6 +160,39 @@ erDiagram
uuid content_id PK, FK uuid content_id PK, FK
uuid tag_id PK, FK uuid tag_id PK, FK
} }
comments {
uuid id PK
uuid content_id FK
uuid user_id FK
uuid parent_id FK
text text
timestamp created_at
timestamp updated_at
timestamp deleted_at
}
comment_likes {
uuid comment_id PK, FK
uuid user_id PK, FK
timestamp created_at
}
conversations {
uuid id PK
timestamp created_at
timestamp updated_at
}
conversation_participants {
uuid conversation_id PK, FK
uuid user_id PK, FK
timestamp joined_at
}
messages {
uuid id PK
uuid conversation_id FK
uuid sender_id FK
text text
timestamp created_at
timestamp read_at
}
roles { roles {
uuid id PK uuid id PK
varchar name varchar name
@@ -225,6 +278,15 @@ erDiagram
users ||--o{ sessions : "user_id" users ||--o{ sessions : "user_id"
users ||--o{ api_keys : "user_id" users ||--o{ api_keys : "user_id"
users ||--o{ audit_logs : "user_id" users ||--o{ audit_logs : "user_id"
contents ||--o{ comments : "content_id"
users ||--o{ comments : "user_id"
comments ||--o{ comments : "parent_id"
comments ||--o{ comment_likes : "comment_id"
users ||--o{ comment_likes : "user_id"
conversations ||--o{ conversation_participants : "conversation_id"
users ||--o{ conversation_participants : "user_id"
conversations ||--o{ messages : "conversation_id"
users ||--o{ messages : "sender_id"
``` ```
### Physique (MPD) ### Physique (MPD)
@@ -278,6 +340,7 @@ erDiagram
#### Sécurité et Chiffrement #### Sécurité et Chiffrement
- **Chiffrement PGP (Native)** : Les colonnes `email` et `two_factor_secret` sont stockées au format `bytea` et chiffrées/déchiffrées via les fonctions `pgp_sym_encrypt` et `pgp_sym_decrypt` de PostgreSQL (via l'extension `pgcrypto`). - **Chiffrement PGP (Native)** : Les colonnes `email` et `two_factor_secret` sont stockées au format `bytea` et chiffrées/déchiffrées via les fonctions `pgp_sym_encrypt` et `pgp_sym_decrypt` de PostgreSQL (via l'extension `pgcrypto`).
- **Cryptographie Post-Quantique** : Utilisation de la bibliothèque `@noble/post-quantum` pour anticiper les futures menaces cryptographiques.
- **Hachage aveugle (Blind Indexing)** : La colonne `email_hash` stocke un hash (SHA-256) de l'email pour permettre les recherches d'unicité et les recherches rapides sans déchiffrer la donnée. - **Hachage aveugle (Blind Indexing)** : La colonne `email_hash` stocke un hash (SHA-256) de l'email pour permettre les recherches d'unicité et les recherches rapides sans déchiffrer la donnée.
#### Index et Optimisations #### Index et Optimisations

View File

@@ -12,10 +12,10 @@ Un conteneur **Caddy** est utilisé en tant que reverse proxy pour fournir le TL
### Pré-requis Système ### Pré-requis Système
<Cards> <Cards>
<Card title="Environnement" description="Node.js >= 20, pnpm >= 10." /> <Card title="Environnement" description="Node.js >= 22 (recommandé pour NestJS 11), pnpm >= 10." />
<Card title="Base de données" description="PostgreSQL >= 15 + pgcrypto et Redis." /> <Card title="Base de données" description="PostgreSQL >= 16 + pgcrypto et Redis 7+." />
<Card title="Stockage" description="MinIO ou S3 Compatible." /> <Card title="Stockage" description="MinIO ou S3 Compatible." />
<Card title="Services" description="ClamAV (clamd) et FFmpeg." /> <Card title="Services" description="ClamAV (clamd), FFmpeg 6+ et Serveur SMTP." />
</Cards> </Cards>
### Procédure de Déploiement ### Procédure de Déploiement

View File

@@ -10,7 +10,7 @@ Le projet Memegoat intègre un ensemble de fonctionnalités avancées pour garan
## 🏗️ Infrastructure & Médias ## 🏗️ Infrastructure & Médias
### 📤 Publication & Traitement ### 📤 Publication & Traitement
Le coeur de la plateforme permet la publication sécurisée de mèmes et de GIFs avec un pipeline de traitement complet : Le coeur de la plateforme permet la publication sécurisée de mèmes et de GIFs avec un pipeline de traitement complet (voir le [Flux de Publication](/docs/flows#-publication-de-contenu-pipeline-médía)) :
<Cards> <Cards>
<Card icon="🛡️" title="Sécurité (Antivirus)" description="Chaque fichier uploadé est scanné en temps réel par ClamAV." /> <Card icon="🛡️" title="Sécurité (Antivirus)" description="Chaque fichier uploadé est scanné en temps réel par ClamAV." />
@@ -64,6 +64,11 @@ Un système complet de gestion de profil permet aux utilisateurs de :
- Configurer la **Double Authentification (2FA)**. - Configurer la **Double Authentification (2FA)**.
- Consulter leurs sessions actives et révoquer des accès. - Consulter leurs sessions actives et révoquer des accès.
### 💬 Interaction & Communauté
Memegoat favorise l'interaction entre les utilisateurs via plusieurs fonctionnalités sociales :
- **Système de Commentaires** : Les utilisateurs peuvent commenter les mèmes, répondre à d'autres commentaires et aimer les contributions.
- **Messagerie Privée** : Un système de messagerie sécurisé permettant des conversations directes entre utilisateurs, avec gestion des conversations et compteurs de messages non lus.
<Callout type="info"> <Callout type="info">
Toutes les données sensibles du profil sont protégées par **chiffrement PGP** au repos. Toutes les données sensibles du profil sont protégées par **chiffrement PGP** au repos.
</Callout> </Callout>

View File

@@ -0,0 +1,177 @@
---
title: Flux Métiers
description: Diagrammes de séquence et explications des flux critiques de Memegoat.
---
# 🔄 Flux Métiers
Cette section détaille les processus critiques de la plateforme Memegoat à travers des diagrammes de séquence et des explications techniques étape par étape.
## 🔐 Authentification & Sécurité
### Inscription & Double Authentification (2FA)
Le processus d'inscription intègre immédiatement les mesures de sécurité fortes (Argon2id, PGP). L'activation de la 2FA est optionnelle mais fortement recommandée.
```mermaid
sequenceDiagram
participant U as Utilisateur
participant F as Frontend
participant B as Backend
participant DB as PostgreSQL
participant M as Serveur SMTP
Note over U, DB: Flux d'Inscription
U->>F: Remplir formulaire (email, password)
F->>B: POST /auth/register
B->>B: Hash password (Argon2id)
B->>B: Chiffrement Email (PGP)
B->>B: Génération Email Hash (Blind Indexing)
B->>DB: INSERT INTO users
B->>M: Envoi email de validation
B-->>F: 201 Created
F-->>U: Succès (Redirection Login)
Note over U, DB: Activation 2FA
U->>F: Activer 2FA
F->>B: POST /users/me/2fa/setup
B->>B: Générer Secret TOTP
B->>B: Chiffrer Secret (PGP)
B->>DB: UPDATE users SET two_factor_secret
B-->>F: Secret + QR Code URL
F-->>U: Affiche QR Code
U->>F: Saisir code TOTP
F->>B: POST /users/me/2fa/enable (token)
B->>B: Déchiffrer Secret (PGP)
B->>B: Vérifier TOTP (otplib)
B->>DB: UPDATE users SET is_two_factor_enabled = true
B-->>F: 200 OK
```
---
## 📤 Publication de Contenu (Pipeline Média)
La publication d'un mème ou d'un GIF suit un pipeline rigoureux garantissant la sécurité (Antivirus) et l'optimisation (Transcodage).
```mermaid
sequenceDiagram
participant U as Utilisateur
participant F as Frontend
participant B as Backend
participant AV as ClamAV
participant S3 as MinIO (S3)
participant DB as PostgreSQL
U->>F: Sélectionner image/vidéo
F->>B: POST /contents/upload (multipart)
B->>B: Validation (Taille, MIME-Type)
B->>AV: Scan Antivirus (Stream)
AV-->>B: Verdict (Clean/Infected)
alt Infecté
B-->>F: 400 Bad Request (Virus detected)
else Sain
B->>B: Transcodage (Sharp/FFmpeg)
Note right of B: WebP pour images, WebM pour vidéos
B->>S3: Upload fichier optimisé
S3-->>B: Storage Key
B->>DB: INSERT INTO contents
B->>DB: INSERT INTO audit_logs (Upload action)
B-->>F: 201 Created
end
```
---
## 💬 Messagerie & Temps Réel
Memegoat utilise **Socket.io** pour les interactions en temps réel, avec une validation de session robuste via `iron-session`.
```mermaid
sequenceDiagram
participant U1 as Utilisateur A
participant F1 as Frontend A
participant WS as WebSocket Gateway
participant B as Backend (API)
participant F2 as Frontend B
participant U2 as Utilisateur B
U1->>F1: Ouvre le chat
F1->>WS: Connexion (transports: websocket)
Note over WS: Authentification via iron-session cookie
WS->>WS: Vérifie Access Token (JWT)
WS->>WS: Rejoindre room "user:A"
WS-->>F1: Connected
U1->>F1: Tape un message
F1->>WS: Event "typing" { recipientId: B, isTyping: true }
WS->>F2: Event "user_typing" { userId: A, isTyping: true }
F2-->>U2: Affiche "A est en train d'écrire..."
U1->>F1: Envoyer message
F1->>B: POST /messages { recipientId: B, text: "Salut !" }
B->>DB: INSERT INTO messages
B-->>F1: 201 Created
B->>WS: Trigger Notify(B)
WS->>F2: Event "new_message" { senderId: A, text: "Salut !" }
F2-->>U2: Affiche message + Notification
```
---
## ⚖️ Cycle de Vie & Conformité (RGPD)
La gestion des données respecte le droit à l'oubli à travers un processus de suppression en deux étapes et une purge automatique.
```mermaid
sequenceDiagram
participant U as Utilisateur
participant B as Backend
participant DB as PostgreSQL
participant S3 as MinIO (S3)
participant C as Cron Job (PurgeService)
Note over U, DB: Droit à l'oubli (Phase 1)
U->>B: DELETE /users/me
B->>DB: UPDATE users SET deleted_at = NOW()
B->>DB: UPDATE contents SET deleted_at = NOW() WHERE user_id = U
B-->>U: 200 OK (Compte désactivé)
Note over C, S3: Purge Automatique (Phase 2 - après 30 jours)
C->>B: Execute purgeExpiredData()
B->>DB: SELECT users WHERE deleted_at < 30 days
B->>DB: DELETE FROM users (Hard Delete)
Note right of B: Cascade delete sur API keys, Sessions, etc.
B->>DB: DELETE FROM contents (Hard Delete)
B->>S3: DELETE objects (Storage Keys)
B->>DB: Purge Audit Logs / Reports expirés
```
---
## 🚩 Modération
Le flux de modération permet aux utilisateurs de signaler des abus, traités ensuite par les administrateurs.
```mermaid
sequenceDiagram
participant U as Utilisateur
participant B as Backend
participant DB as PostgreSQL
participant A as Administrateur
U->>B: POST /reports { contentId, reason, description }
B->>DB: INSERT INTO reports (status: pending)
B-->>U: 201 Created
A->>B: GET /reports (Admin Panel)
B->>DB: SELECT * FROM reports WHERE status = pending
B-->>A: Liste des signalements
A->>B: PATCH /reports/:id/status { status: resolved }
B->>DB: UPDATE reports SET status = resolved
Note right of B: Si contenu illicite, l'admin peut supprimer le contenu
B->>B: DELETE /contents/:id/admin (Hard Delete)
B-->>A: 200 OK
```

View File

@@ -18,10 +18,11 @@ graph TD
User([Utilisateur]) User([Utilisateur])
Caddy[Reverse Proxy: Caddy] Caddy[Reverse Proxy: Caddy]
Frontend[Frontend: Next.js] Frontend[Frontend: Next.js]
Backend[Backend: NestJS] Backend[Backend: NestJS 11]
DB[(Database: PostgreSQL)] DB[(Database: PostgreSQL)]
Storage[Storage: S3/MinIO] Storage[Storage: S3/MinIO]
Cache[(Cache: Redis)] Cache[(Cache: Redis)]
AV[Antivirus: ClamAV]
Monitoring[Monitoring: Sentry] Monitoring[Monitoring: Sentry]
User <--> Caddy User <--> Caddy
@@ -30,6 +31,7 @@ graph TD
Backend <--> DB Backend <--> DB
Backend <--> Storage Backend <--> Storage
Backend <--> Cache Backend <--> Cache
Backend <--> AV
Backend --> Monitoring Backend --> Monitoring
``` ```
@@ -43,6 +45,11 @@ Explorez les sections clés pour approfondir vos connaissances techniques :
href="/docs/features" href="/docs/features"
description="Détails des capacités techniques et du pipeline média haute performance." description="Détails des capacités techniques et du pipeline média haute performance."
/> />
<Card
title="🔄 Flux Métiers"
href="/docs/flows"
description="Diagrammes de séquence des processus critiques (Publication, 2FA, Chat)."
/>
<Card <Card
title="🔐 Sécurité" title="🔐 Sécurité"
href="/docs/security" href="/docs/security"

View File

@@ -7,6 +7,7 @@ description: Mesures de sécurité implémentées
### Protection des Données (At Rest) ### Protection des Données (At Rest)
- **Cryptographie Post-Quantique** : Utilisation de la bibliothèque `@noble/post-quantum` pour anticiper les futures menaces cryptographiques et protéger les données sensibles contre les attaques "Harvest Now, Decrypt Later".
- **Chiffrement PGP Natif** : Les données identifiantes (PII) comme l'email, le nom d'affichage et le **secret 2FA** sont chiffrées dans PostgreSQL via `pgcrypto` (`pgp_sym_encrypt`). - **Chiffrement PGP Natif** : Les données identifiantes (PII) comme l'email, le nom d'affichage et le **secret 2FA** sont chiffrées dans PostgreSQL via `pgcrypto` (`pgp_sym_encrypt`).
<Callout type="warn" title="Sécurité des Clés"> <Callout type="warn" title="Sécurité des Clés">

View File

@@ -17,9 +17,9 @@ description: Technologies utilisées dans le projet Memegoat
### Backend ### Backend
<Cards> <Cards>
<Card title="NestJS" description="Framework Node.js modulaire et robuste." /> <Card title="NestJS 11" description="Framework Node.js modulaire et robuste (dernière version majeure)." />
<Card title="PostgreSQL" description="Base de données relationnelle puissante." /> <Card title="PostgreSQL" description="Base de données relationnelle puissante." />
<Card title="Redis" description="Store clé-valeur pour le cache haute performance." /> <Card title="Redis" description="Store clé-valeur pour le cache haute performance (Cache Manager v5+)." />
<Card title="Drizzle ORM" description="ORM TypeScript-first avec support des migrations." /> <Card title="Drizzle ORM" description="ORM TypeScript-first avec support des migrations." />
<Card title="Sharp & FFmpeg" description="Traitement haute performance des images et vidéos." /> <Card title="Sharp & FFmpeg" description="Traitement haute performance des images et vidéos." />
</Cards> </Cards>
@@ -28,8 +28,9 @@ description: Technologies utilisées dans le projet Memegoat
<Cards> <Cards>
<Card title="ClamAV" description="Protection antivirus en temps réel." /> <Card title="ClamAV" description="Protection antivirus en temps réel." />
<Card title="Sentry" description="Reporting d'erreurs et profiling de performance." /> <Card title="Sentry" description="Reporting d'erreurs et profiling de performance (SDK v8+)." />
<Card title="Argon2id" description="Hachage de mots de passe de grade militaire." /> <Card title="Argon2id" description="Hachage de mots de passe de grade militaire via @node-rs/argon2." />
<Card title="Post-Quantum Crypto" description="Algorithmes résistants aux futurs ordinateurs quantiques via @noble/post-quantum." />
<Card title="PGP (pgcrypto)" description="Chiffrement natif des données sensibles." /> <Card title="PGP (pgcrypto)" description="Chiffrement natif des données sensibles." />
<Card title="otplib" description="Implémentation TOTP pour la 2FA." /> <Card title="otplib" description="Implémentation TOTP pour la 2FA." />
<Card title="iron-session" description="Gestion sécurisée des sessions via cookies chiffrés." /> <Card title="iron-session" description="Gestion sécurisée des sessions via cookies chiffrés." />

View File

@@ -1,3 +1,4 @@
import { withSentryConfig } from "@sentry/nextjs";
import type { NextConfig } from "next"; import type { NextConfig } from "next";
const appUrl = process.env.NEXT_PUBLIC_APP_URL || "https://memegoat.fr"; const appUrl = process.env.NEXT_PUBLIC_APP_URL || "https://memegoat.fr";
@@ -29,4 +30,23 @@ const nextConfig: NextConfig = {
output: "standalone", output: "standalone",
}; };
export default nextConfig; export default withSentryConfig(nextConfig, {
// For all available options, see:
// https://github.com/getsentry/sentry-webpack-plugin#options
org: "yidhra",
project: "javascript-nextjs",
// Only print logs for uploading source maps in CI
silent: !process.env.CI,
// For all available options, see:
// https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/
// Upload a larger set of source maps for prettier stack traces (increases build time)
widenClientFileUpload: true,
// Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers.
// This can increase your server load as well as your Sentry bill.
tunnelRoute: "/monitoring",
});

View File

@@ -1,6 +1,6 @@
{ {
"name": "@memegoat/frontend", "name": "@memegoat/frontend",
"version": "1.9.1", "version": "2.0.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
@@ -38,6 +38,7 @@
"@radix-ui/react-toggle": "^1.1.10", "@radix-ui/react-toggle": "^1.1.10",
"@radix-ui/react-toggle-group": "^1.1.11", "@radix-ui/react-toggle-group": "^1.1.11",
"@radix-ui/react-tooltip": "^1.2.8", "@radix-ui/react-tooltip": "^1.2.8",
"@sentry/nextjs": "^10.38.0",
"axios": "^1.13.2", "axios": "^1.13.2",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",

View File

@@ -0,0 +1,22 @@
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
// Ajustez ces valeurs en production
tracesSampleRate: 1.0,
// Replay est activé par défaut
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
integrations: [
Sentry.replayIntegration({
maskAllText: true,
blockAllMedia: true,
}),
],
// Protection PII
sendDefaultPii: false,
});

View File

@@ -0,0 +1,11 @@
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
// Ajustez ces valeurs en production
tracesSampleRate: 1.0,
// Protection PII
sendDefaultPii: false,
});

View File

@@ -0,0 +1,22 @@
import { createHash } from "node:crypto";
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
// Ajustez ces valeurs en production
tracesSampleRate: 1.0,
// Protection PII
sendDefaultPii: false,
beforeSend(event) {
// Hachage de l'IP utilisateur pour Sentry si elle est présente
if (event.user?.ip_address) {
event.user.ip_address = createHash("sha256")
.update(event.user.ip_address)
.digest("hex");
}
return event;
},
});

View File

@@ -1,15 +1,11 @@
import * as React from "react"; import * as React from "react";
import { AppSidebar } from "@/components/app-sidebar"; import { AppSidebar } from "@/components/app-sidebar";
import { MobileFilters } from "@/components/mobile-filters"; import { MobileFilters } from "@/components/mobile-filters";
import { ModeToggle } from "@/components/mode-toggle"; import { MobileFooter } from "@/components/mobile-footer";
import { MobileHeader } from "@/components/mobile-header";
import { SearchSidebar } from "@/components/search-sidebar"; import { SearchSidebar } from "@/components/search-sidebar";
import { import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
SidebarInset,
SidebarProvider,
SidebarTrigger,
} from "@/components/ui/sidebar";
import { Toaster } from "@/components/ui/sonner"; import { Toaster } from "@/components/ui/sonner";
import { UserNavMobile } from "@/components/user-nav-mobile";
export default function DashboardLayout({ export default function DashboardLayout({
children, children,
@@ -22,20 +18,9 @@ export default function DashboardLayout({
<React.Suspense fallback={null}> <React.Suspense fallback={null}>
<SidebarProvider> <SidebarProvider>
<AppSidebar /> <AppSidebar />
<SidebarInset className="flex flex-row overflow-hidden"> <SidebarInset className="flex flex-row overflow-hidden pb-16 lg:pb-0">
<div className="flex-1 flex flex-col min-w-0"> <div className="flex-1 flex flex-col min-w-0">
<header className="flex h-16 shrink-0 items-center gap-2 border-b px-4 lg:hidden sticky top-0 bg-background z-40"> <MobileHeader />
<SidebarTrigger />
<div className="flex-1 flex justify-center">
<span className="font-bold text-primary text-xl tracking-tight">
MemeGoat
</span>
</div>
<div className="flex items-center gap-2">
<ModeToggle />
<UserNavMobile />
</div>
</header>
<main className="flex-1 overflow-y-auto bg-zinc-50 dark:bg-zinc-950"> <main className="flex-1 overflow-y-auto bg-zinc-50 dark:bg-zinc-950">
{children} {children}
{modal} {modal}
@@ -43,6 +28,7 @@ export default function DashboardLayout({
<React.Suspense fallback={null}> <React.Suspense fallback={null}>
<MobileFilters /> <MobileFilters />
</React.Suspense> </React.Suspense>
<MobileFooter />
</div> </div>
<React.Suspense fallback={null}> <React.Suspense fallback={null}>
<SearchSidebar /> <SearchSidebar />

View File

@@ -2,7 +2,15 @@
import { formatDistanceToNow } from "date-fns"; import { formatDistanceToNow } from "date-fns";
import { fr } from "date-fns/locale"; import { fr } from "date-fns/locale";
import { ArrowLeft, Search, Send, UserPlus, X } from "lucide-react"; import {
ArrowLeft,
Check,
CheckCheck,
Search,
Send,
UserPlus,
X,
} from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import * as React from "react"; import * as React from "react";
@@ -142,6 +150,8 @@ export default function MessagesPage() {
if (activeConv?.id === data.conversationId) { if (activeConv?.id === data.conversationId) {
setMessages((prev) => [...prev, data.message]); setMessages((prev) => [...prev, data.message]);
setIsOtherTyping(false); // S'il a envoyé un message, il ne tape plus setIsOtherTyping(false); // S'il a envoyé un message, il ne tape plus
// Marquer comme lu immédiatement si on est sur la conversation
MessageService.markAsRead(data.conversationId).catch(console.error);
} }
// Mettre à jour la liste des conversations // Mettre à jour la liste des conversations
setConversations((prev) => { setConversations((prev) => {
@@ -184,10 +194,26 @@ export default function MessagesPage() {
} }
}); });
socket.on(
"messages_read",
(data: { conversationId: string; readerId: string }) => {
if (activeConv?.id === data.conversationId) {
setMessages((prev) =>
prev.map((msg) =>
msg.senderId !== data.readerId && !msg.readAt
? { ...msg, readAt: new Date().toISOString() }
: msg,
),
);
}
},
);
return () => { return () => {
socket.off("new_message"); socket.off("new_message");
socket.off("user_status"); socket.off("user_status");
socket.off("user_typing"); socket.off("user_typing");
socket.off("messages_read");
}; };
} }
}, [socket, activeConv]); }, [socket, activeConv]);
@@ -351,7 +377,7 @@ export default function MessagesPage() {
: "hover:bg-zinc-100 dark:hover:bg-zinc-900" : "hover:bg-zinc-100 dark:hover:bg-zinc-900"
}`} }`}
> >
<Avatar> <Avatar isOnline={onlineUsers.has(conv.recipient.uuid)}>
<AvatarImage src={conv.recipient.avatarUrl} /> <AvatarImage src={conv.recipient.avatarUrl} />
<AvatarFallback> <AvatarFallback>
{conv.recipient.username[0].toUpperCase()} {conv.recipient.username[0].toUpperCase()}
@@ -403,7 +429,10 @@ export default function MessagesPage() {
href={`/user/${activeConv.recipient.username}`} href={`/user/${activeConv.recipient.username}`}
className="flex-1 flex items-center gap-3 hover:opacity-80 transition-opacity" className="flex-1 flex items-center gap-3 hover:opacity-80 transition-opacity"
> >
<Avatar className="h-8 w-8"> <Avatar
className="h-8 w-8"
isOnline={onlineUsers.has(activeConv.recipient.uuid)}
>
<AvatarImage src={activeConv.recipient.avatarUrl} /> <AvatarImage src={activeConv.recipient.avatarUrl} />
<AvatarFallback> <AvatarFallback>
{activeConv.recipient.username[0].toUpperCase()} {activeConv.recipient.username[0].toUpperCase()}
@@ -465,8 +494,12 @@ export default function MessagesPage() {
})} })}
</span> </span>
{msg.senderId === user?.uuid && ( {msg.senderId === user?.uuid && (
<span className="font-bold"> <span className="flex items-center">
{msg.readAt ? "• Lu" : "• Envoyé"} {msg.readAt ? (
<CheckCheck className="h-3 w-3" />
) : (
<Check className="h-3 w-3" />
)}
</span> </span>
)} )}
</div> </div>

View File

@@ -3,16 +3,19 @@
import { import {
Calendar, Calendar,
Camera, Camera,
HelpCircle,
LogIn, LogIn,
LogOut, LogOut,
Settings, Settings,
Share2, Share2,
ShieldCheck,
} from "lucide-react"; } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import { useSearchParams } from "next/navigation"; import { useSearchParams } from "next/navigation";
import * as React from "react"; import * as React from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { ContentList } from "@/components/content-list"; import { ContentList } from "@/components/content-list";
import { ModeToggle } from "@/components/mode-toggle";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
@@ -157,6 +160,19 @@ export default function ProfilePage() {
</div> </div>
<div className="flex flex-wrap justify-center md:justify-start gap-2 pt-2"> <div className="flex flex-wrap justify-center md:justify-start gap-2 pt-2">
{user.role === "admin" && (
<Button
asChild
variant="outline"
size="sm"
className="h-9 px-4 border-primary/20 hover:bg-primary/5 text-primary"
>
<Link href="/admin">
<ShieldCheck className="h-4 w-4 mr-2" />
Administration
</Link>
</Button>
)}
<Button asChild variant="outline" size="sm" className="h-9 px-4"> <Button asChild variant="outline" size="sm" className="h-9 px-4">
<Link href="/settings"> <Link href="/settings">
<Settings className="h-4 w-4 mr-2" /> <Settings className="h-4 w-4 mr-2" />
@@ -181,6 +197,14 @@ export default function ProfilePage() {
<LogOut className="h-4 w-4 mr-2" /> <LogOut className="h-4 w-4 mr-2" />
Déconnexion Déconnexion
</Button> </Button>
<Button asChild variant="outline" size="sm" className="h-9 px-4">
<Link href="/help">
<HelpCircle className="h-4 w-4 mr-2" />
Aide
</Link>
</Button>
<ModeToggle />
</div> </div>
</div> </div>
</div> </div>

View File

@@ -10,6 +10,7 @@ import {
Palette, Palette,
Save, Save,
Settings, Settings,
Shield,
Sun, Sun,
Trash2, Trash2,
User as UserIcon, User as UserIcon,
@@ -53,6 +54,7 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"; import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Spinner } from "@/components/ui/spinner"; import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { useAuth } from "@/providers/auth-provider"; import { useAuth } from "@/providers/auth-provider";
import { UserService } from "@/services/user.service"; import { UserService } from "@/services/user.service";
@@ -60,6 +62,8 @@ import { UserService } from "@/services/user.service";
const settingsSchema = z.object({ const settingsSchema = z.object({
displayName: z.string().max(32, "Le nom d'affichage est trop long").optional(), displayName: z.string().max(32, "Le nom d'affichage est trop long").optional(),
bio: z.string().max(255, "La bio est trop longue").optional(), bio: z.string().max(255, "La bio est trop longue").optional(),
showOnlineStatus: z.boolean(),
showReadReceipts: z.boolean(),
}); });
type SettingsFormValues = z.infer<typeof settingsSchema>; type SettingsFormValues = z.infer<typeof settingsSchema>;
@@ -82,6 +86,8 @@ export default function SettingsPage() {
defaultValues: { defaultValues: {
displayName: "", displayName: "",
bio: "", bio: "",
showOnlineStatus: true,
showReadReceipts: true,
}, },
}); });
@@ -90,6 +96,8 @@ export default function SettingsPage() {
form.reset({ form.reset({
displayName: user.displayName || "", displayName: user.displayName || "",
bio: user.bio || "", bio: user.bio || "",
showOnlineStatus: user.showOnlineStatus ?? true,
showReadReceipts: user.showReadReceipts ?? true,
}); });
} }
}, [user, form]); }, [user, form]);
@@ -265,6 +273,73 @@ export default function SettingsPage() {
</CardContent> </CardContent>
</Card> </Card>
{/* Confidentialité */}
<Card className="border-none shadow-sm">
<CardHeader className="pb-4">
<div className="flex items-center gap-2">
<Shield className="h-5 w-5 text-primary" />
<div>
<CardTitle>Confidentialité</CardTitle>
<CardDescription>Gérez la visibilité de vos activités.</CardDescription>
</div>
</div>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<div className="space-y-4">
<FormField
control={form.control}
name="showOnlineStatus"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Statut en ligne</FormLabel>
<FormDescription>
Affiche quand vous êtes actif sur le site.
</FormDescription>
</div>
<FormControl>
<Switch checked={field.value} onCheckedChange={field.onChange} />
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="showReadReceipts"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">
Confirmations de lecture
</FormLabel>
<FormDescription>
Permet aux autres de voir quand vous avez lu leurs messages.
</FormDescription>
</div>
<FormControl>
<Switch checked={field.value} onCheckedChange={field.onChange} />
</FormControl>
</FormItem>
)}
/>
</div>
<div className="flex justify-end pt-2">
<Button type="submit" disabled={isSaving} className="min-w-[150px]">
{isSaving ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Save className="mr-2 h-4 w-4" />
)}
Enregistrer
</Button>
</div>
</form>
</Form>
</CardContent>
</Card>
<TwoFactorSetup /> <TwoFactorSetup />
<Card className="border-none shadow-sm"> <Card className="border-none shadow-sm">

View File

@@ -54,6 +54,7 @@ import {
SidebarRail, SidebarRail,
SidebarTrigger, SidebarTrigger,
} from "@/components/ui/sidebar"; } from "@/components/ui/sidebar";
import { useIsMobile } from "@/hooks/use-mobile";
import { useAuth } from "@/providers/auth-provider"; import { useAuth } from "@/providers/auth-provider";
import { useSocket } from "@/providers/socket-provider"; import { useSocket } from "@/providers/socket-provider";
import { CategoryService } from "@/services/category.service"; import { CategoryService } from "@/services/category.service";
@@ -79,6 +80,7 @@ const mainNav = [
]; ];
export function AppSidebar() { export function AppSidebar() {
const isMobile = useIsMobile();
const pathname = usePathname(); const pathname = usePathname();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const { user, logout, isAuthenticated } = useAuth(); const { user, logout, isAuthenticated } = useAuth();
@@ -129,6 +131,8 @@ export function AppSidebar() {
: "/memegoat-black.svg"; : "/memegoat-black.svg";
}, [resolvedTheme, mounted]); }, [resolvedTheme, mounted]);
if (isMobile) return null;
return ( return (
<Sidebar collapsible="icon"> <Sidebar collapsible="icon">
<SidebarHeader className="flex flex-row items-center justify-between py-4 group-data-[collapsible=icon]:justify-center"> <SidebarHeader className="flex flex-row items-center justify-between py-4 group-data-[collapsible=icon]:justify-center">

View File

@@ -1,10 +1,9 @@
"use client"; "use client";
import { Filter, Search } from "lucide-react"; import { Search } from "lucide-react";
import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { usePathname, useRouter, useSearchParams } from "next/navigation";
import * as React from "react"; import * as React from "react";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area"; import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
@@ -13,7 +12,6 @@ import {
SheetContent, SheetContent,
SheetHeader, SheetHeader,
SheetTitle, SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet"; } from "@/components/ui/sheet";
import { CategoryService } from "@/services/category.service"; import { CategoryService } from "@/services/category.service";
import { TagService } from "@/services/tag.service"; import { TagService } from "@/services/tag.service";
@@ -29,6 +27,16 @@ export function MobileFilters() {
const [query, setQuery] = React.useState(searchParams.get("query") || ""); const [query, setQuery] = React.useState(searchParams.get("query") || "");
const [open, setOpen] = React.useState(false); const [open, setOpen] = React.useState(false);
React.useEffect(() => {
if (searchParams.get("openSearch") === "true") {
setOpen(true);
// Nettoyer l'URL sans recharger
const params = new URLSearchParams(searchParams.toString());
params.delete("openSearch");
router.replace(`${pathname}?${params.toString()}`, { scroll: false });
}
}, [searchParams, pathname, router]);
React.useEffect(() => { React.useEffect(() => {
if (open) { if (open) {
CategoryService.getAll().then(setCategories).catch(console.error); CategoryService.getAll().then(setCategories).catch(console.error);
@@ -61,13 +69,8 @@ export function MobileFilters() {
const currentCategory = searchParams.get("category"); const currentCategory = searchParams.get("category");
return ( return (
<div className="lg:hidden fixed top-4 right-4 z-50"> <div className="lg:hidden">
<Sheet open={open} onOpenChange={setOpen}> <Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button size="icon" className="rounded-full shadow-lg h-12 w-12">
<Filter className="h-6 w-6" />
</Button>
</SheetTrigger>
<SheetContent side="right" className="w-[300px] sm:w-[400px]"> <SheetContent side="right" className="w-[300px] sm:w-[400px]">
<SheetHeader> <SheetHeader>
<SheetTitle>Recherche & Filtres</SheetTitle> <SheetTitle>Recherche & Filtres</SheetTitle>

View File

@@ -0,0 +1,80 @@
"use client";
import { Home, PlusCircle, Search, TrendingUp, User } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { cn } from "@/lib/utils";
import { useAuth } from "@/providers/auth-provider";
export function MobileFooter() {
const pathname = usePathname();
const { user, isAuthenticated } = useAuth();
const navItems = [
{
title: "Accueil",
url: "/",
icon: Home,
},
{
title: "Explorer",
url: "/trends?openSearch=true",
icon: Search,
},
{
title: "Publier",
url: "/upload",
icon: PlusCircle,
},
{
title: "Tendances",
url: "/trends",
icon: TrendingUp,
},
{
title: "Profil",
url: "/profile",
icon: User,
},
];
return (
<footer className="lg:hidden fixed bottom-0 left-0 right-0 border-t bg-background z-40 h-16">
<nav className="flex h-full items-center justify-around px-2">
{navItems.map((item) => {
const isActive = pathname === item.url.split("?")[0];
const isProfile = item.title === "Profil";
return (
<Link
key={item.url}
href={item.url}
className={cn(
"flex flex-1 flex-col items-center justify-center gap-1 transition-colors min-h-[44px]",
isActive ? "text-primary" : "text-muted-foreground hover:text-primary",
)}
>
{isProfile && isAuthenticated && user ? (
<Avatar
className={cn(
"h-6 w-6 border",
isActive && "ring-2 ring-primary ring-offset-2",
)}
>
<AvatarImage src={user.avatarUrl} alt={user.username} />
<AvatarFallback className="text-[8px]">
{user.username.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
) : (
<item.icon className={cn("h-6 w-6", isActive && "fill-current")} />
)}
<span className="text-[10px] font-medium">{item.title}</span>
</Link>
);
})}
</nav>
</footer>
);
}

View File

@@ -0,0 +1,66 @@
"use client";
import { MessageCircle } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/providers/auth-provider";
import { useSocket } from "@/providers/socket-provider";
import { MessageService } from "@/services/message.service";
export function MobileHeader() {
const pathname = usePathname();
const { isAuthenticated } = useAuth();
const { socket } = useSocket();
const [unreadMessages, setUnreadMessages] = React.useState(0);
React.useEffect(() => {
if (isAuthenticated) {
MessageService.getUnreadCount().then(setUnreadMessages).catch(console.error);
}
}, [isAuthenticated]);
React.useEffect(() => {
if (socket && isAuthenticated) {
const handleNewMessage = () => {
if (pathname !== "/messages") {
setUnreadMessages((prev) => prev + 1);
}
};
socket.on("new_message", handleNewMessage);
return () => {
socket.off("new_message", handleNewMessage);
};
}
}, [socket, isAuthenticated, pathname]);
React.useEffect(() => {
if (pathname === "/messages") {
setUnreadMessages(0);
}
}, [pathname]);
return (
<header className="flex h-16 shrink-0 items-center justify-between border-b px-4 lg:hidden sticky top-0 bg-background z-40">
<Link href="/" className="flex items-center gap-2">
<span className="font-bold text-primary text-xl tracking-tight">
MemeGoat
</span>
</Link>
<div className="flex items-center gap-2">
<Button variant="ghost" size="icon" asChild className="h-9 w-9 relative">
<Link href="/messages">
<MessageCircle className="h-5 w-5" />
{unreadMessages > 0 && (
<span className="absolute top-1 right-1 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-[10px] text-white">
{unreadMessages > 9 ? "9+" : unreadMessages}
</span>
)}
</Link>
</Button>
</div>
</header>
);
}

View File

@@ -7,17 +7,23 @@ import { cn } from "@/lib/utils";
function Avatar({ function Avatar({
className, className,
isOnline,
...props ...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) { }: React.ComponentProps<typeof AvatarPrimitive.Root> & { isOnline?: boolean }) {
return ( return (
<AvatarPrimitive.Root <div className="relative inline-block">
data-slot="avatar" <AvatarPrimitive.Root
className={cn( data-slot="avatar"
"relative flex size-8 shrink-0 overflow-hidden rounded-full", className={cn(
className, "relative flex size-8 shrink-0 overflow-hidden rounded-full",
className,
)}
{...props}
/>
{isOnline && (
<span className="absolute bottom-0 right-0 block h-2.5 w-2.5 rounded-full bg-green-500 ring-2 ring-white dark:ring-zinc-900" />
)} )}
{...props} </div>
/>
); );
} }

View File

@@ -55,4 +55,8 @@ export const MessageService = {
}); });
return data; return data;
}, },
async markAsRead(conversationId: string): Promise<void> {
await api.patch(`/messages/conversations/${conversationId}/read`);
},
}; };

View File

@@ -9,6 +9,8 @@ export interface User {
role?: "user" | "admin" | "moderator"; role?: "user" | "admin" | "moderator";
status?: "active" | "verification" | "suspended" | "pending" | "deleted"; status?: "active" | "verification" | "suspended" | "pending" | "deleted";
twoFactorEnabled?: boolean; twoFactorEnabled?: boolean;
showOnlineStatus?: boolean;
showReadReceipts?: boolean;
createdAt: string; createdAt: string;
} }

View File

@@ -1,6 +1,6 @@
{ {
"name": "@memegoat/source", "name": "@memegoat/source",
"version": "1.9.1", "version": "2.0.0",
"description": "", "description": "",
"scripts": { "scripts": {
"version:get": "cmake -P version.cmake GET", "version:get": "cmake -P version.cmake GET",

995
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff