generated from nhcarrigan/template
feat: another security sweep
This commit is contained in:
@@ -1,6 +1,10 @@
|
||||
import { FastifyInstance } from "fastify";
|
||||
import { JwtPayload, User } from "@library/shared-types";
|
||||
import { prisma } from "../lib/prisma";
|
||||
import { randomBytes } from "crypto";
|
||||
|
||||
const ACCESS_TOKEN_EXPIRY = "15m";
|
||||
const REFRESH_TOKEN_EXPIRY_DAYS = 7;
|
||||
|
||||
export class AuthService {
|
||||
private prisma = prisma;
|
||||
@@ -8,7 +12,7 @@ export class AuthService {
|
||||
constructor(private readonly app: FastifyInstance) {}
|
||||
|
||||
/**
|
||||
* Generate JWT token for user.
|
||||
* Generate short-lived access token for user.
|
||||
*/
|
||||
async generateToken(user: User): Promise<string> {
|
||||
const payload: JwtPayload = {
|
||||
@@ -19,10 +23,125 @@ export class AuthService {
|
||||
};
|
||||
|
||||
return this.app.jwt.sign(payload, {
|
||||
expiresIn: "7d",
|
||||
expiresIn: ACCESS_TOKEN_EXPIRY,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a secure refresh token and store it in the database.
|
||||
*/
|
||||
async generateRefreshToken(userId: string): Promise<string> {
|
||||
const token = randomBytes(64).toString("hex");
|
||||
const expiresAt = new Date();
|
||||
expiresAt.setDate(expiresAt.getDate() + REFRESH_TOKEN_EXPIRY_DAYS);
|
||||
|
||||
await this.prisma.refreshToken.create({
|
||||
data: {
|
||||
token,
|
||||
userId,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and consume a refresh token, returning the user if valid.
|
||||
*/
|
||||
async validateRefreshToken(token: string): Promise<User | null> {
|
||||
const refreshToken = await this.prisma.refreshToken.findUnique({
|
||||
where: { token },
|
||||
include: { user: true },
|
||||
});
|
||||
|
||||
if (!refreshToken) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (refreshToken.expiresAt < new Date()) {
|
||||
await this.prisma.refreshToken.delete({ where: { id: refreshToken.id } });
|
||||
return null;
|
||||
}
|
||||
|
||||
const dbUser = refreshToken.user;
|
||||
return {
|
||||
id: dbUser.id,
|
||||
discordId: dbUser.discordId,
|
||||
username: dbUser.username,
|
||||
email: dbUser.email,
|
||||
avatar: dbUser.avatar || undefined,
|
||||
isAdmin: dbUser.isAdmin,
|
||||
isBanned: dbUser.isBanned,
|
||||
inDiscord: dbUser.inDiscord,
|
||||
isVip: dbUser.isVip,
|
||||
isMod: dbUser.isMod,
|
||||
isStaff: dbUser.isStaff,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotate a refresh token (invalidate old, create new with same expiry).
|
||||
* Preserves original expiry so users must re-auth with Discord every 7 days.
|
||||
*/
|
||||
async rotateRefreshToken(oldToken: string, userId: string): Promise<string | null> {
|
||||
const existingToken = await this.prisma.refreshToken.findUnique({
|
||||
where: { token: oldToken },
|
||||
});
|
||||
|
||||
if (!existingToken) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const originalExpiry = existingToken.expiresAt;
|
||||
|
||||
await this.prisma.refreshToken.delete({
|
||||
where: { id: existingToken.id },
|
||||
});
|
||||
|
||||
const newToken = randomBytes(64).toString("hex");
|
||||
|
||||
await this.prisma.refreshToken.create({
|
||||
data: {
|
||||
token: newToken,
|
||||
userId,
|
||||
expiresAt: originalExpiry,
|
||||
},
|
||||
});
|
||||
|
||||
return newToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke a specific refresh token.
|
||||
*/
|
||||
async revokeRefreshToken(token: string): Promise<void> {
|
||||
await this.prisma.refreshToken.deleteMany({
|
||||
where: { token },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke all refresh tokens for a user (logout from all devices).
|
||||
*/
|
||||
async revokeAllUserTokens(userId: string): Promise<void> {
|
||||
await this.prisma.refreshToken.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up expired refresh tokens (can be called periodically).
|
||||
*/
|
||||
async cleanupExpiredTokens(): Promise<number> {
|
||||
const result = await this.prisma.refreshToken.deleteMany({
|
||||
where: {
|
||||
expiresAt: { lt: new Date() },
|
||||
},
|
||||
});
|
||||
return result.count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify JWT token.
|
||||
*/
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
SuggestionStatus,
|
||||
SuggestionEntity,
|
||||
CreateSuggestionDto,
|
||||
AcceptWithEditsDto,
|
||||
} from "@library/shared-types";
|
||||
import {
|
||||
GameStatus,
|
||||
@@ -340,7 +341,7 @@ export const SuggestionService = {
|
||||
return mapSuggestion(updatedSuggestion);
|
||||
},
|
||||
|
||||
async acceptSuggestionWithEdits(id: string, editedData: any): Promise<Suggestion> {
|
||||
async acceptSuggestionWithEdits(id: string, editedData: AcceptWithEditsDto): Promise<Suggestion> {
|
||||
const suggestion = await prisma.suggestion.findUnique({
|
||||
where: { id },
|
||||
include: { user: true },
|
||||
@@ -453,4 +454,29 @@ export const SuggestionService = {
|
||||
|
||||
return mapSuggestion(updatedSuggestion);
|
||||
},
|
||||
|
||||
async deleteSuggestion(id: string, userId: string, isAdmin: boolean): Promise<Suggestion> {
|
||||
const suggestion = await prisma.suggestion.findUnique({
|
||||
where: { id },
|
||||
include: { user: true },
|
||||
});
|
||||
|
||||
if (!suggestion) {
|
||||
throw new Error("Suggestion not found");
|
||||
}
|
||||
|
||||
if (!isAdmin && suggestion.userId !== userId) {
|
||||
throw new Error("You can only delete your own suggestions");
|
||||
}
|
||||
|
||||
if (suggestion.status !== "UNREVIEWED") {
|
||||
throw new Error("Cannot delete a suggestion that has already been reviewed");
|
||||
}
|
||||
|
||||
await prisma.suggestion.delete({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
return mapSuggestion(suggestion);
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user