mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
fix: lower vulnerabilities + harden docker setup
also includes a github workflow
This commit is contained in:
@@ -0,0 +1,35 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
backend:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-dotnet@v4
|
||||||
|
with:
|
||||||
|
dotnet-version: 10.0.x
|
||||||
|
- run: dotnet restore SharpbinV3.Server/SharpbinV3.Server.csproj
|
||||||
|
- run: dotnet build SharpbinV3.Server/SharpbinV3.Server.csproj --configuration Release --no-restore
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: SharpbinV3.Client
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: SharpbinV3.Client/package-lock.json
|
||||||
|
- run: npm ci
|
||||||
|
- run: npm run check
|
||||||
|
- run: npm run lint
|
||||||
|
- run: npm run build
|
||||||
@@ -10,7 +10,13 @@ RUN npm run build
|
|||||||
|
|
||||||
FROM node:20-alpine as runner
|
FROM node:20-alpine as runner
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=build /app .
|
ENV NODE_ENV=production
|
||||||
RUN apk add --no-cache wget
|
ENV HOST=0.0.0.0
|
||||||
|
ENV PORT=5173
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci --omit=dev --ignore-scripts && apk add --no-cache wget
|
||||||
|
COPY --from=build --chown=node:node /app/build ./build
|
||||||
|
RUN chown -R node:node /app
|
||||||
EXPOSE 5173
|
EXPOSE 5173
|
||||||
CMD ["npm", "run", "preview", "--", "--host", "0.0.0.0", "--port", "5173"]
|
USER node
|
||||||
|
CMD ["node", "build"]
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
import type { LayoutServerLoad } from './$types';
|
import type { LayoutServerLoad } from './$types';
|
||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
export const load: LayoutServerLoad = async ({ fetch, url }) => {
|
export const load: LayoutServerLoad = async ({ fetch, url }) => {
|
||||||
try {
|
const res = await fetch('/api/auth/info');
|
||||||
const res = await fetch('/api/auth/info');
|
const pasteOptionsRes = await fetch('/api/paste/info');
|
||||||
const pasteOptionsRes = await fetch('/api/paste/info');
|
|
||||||
const options = await res.json();
|
if (!res.ok || !pasteOptionsRes.ok) {
|
||||||
const pasteOptions = await pasteOptionsRes.json();
|
throw error(503, 'Failed to load site configuration.');
|
||||||
return { options, pasteOptions, url: url.href };
|
|
||||||
} catch {
|
|
||||||
return { options: null, pasteOptions: null, url: url.href };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const options = await res.json();
|
||||||
|
const pasteOptions = await pasteOptionsRes.json();
|
||||||
|
return { options, pasteOptions, url: url.href };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { apiUrl } from '$lib/server/api';
|
||||||
|
import { json } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
export const GET = async () => {
|
||||||
|
const res = await fetch(`${apiUrl}/health`);
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
return json({ status: 'unhealthy', backend: res.status }, { status: 503 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return json({ status: 'ok' });
|
||||||
|
};
|
||||||
@@ -15,10 +15,14 @@ export const GET: RequestHandler = async ({ params, request }) => {
|
|||||||
statusText: 'Not Found'
|
statusText: 'Not Found'
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const content = await res.text();
|
const responseHeaders = new Headers(res.headers);
|
||||||
return new Response(content, {
|
responseHeaders.delete('content-encoding');
|
||||||
headers: {
|
responseHeaders.delete('content-length');
|
||||||
'Content-Type': 'text/plain; charset=utf-8'
|
responseHeaders.delete('transfer-encoding');
|
||||||
}
|
|
||||||
|
return new Response(await res.arrayBuffer(), {
|
||||||
|
status: res.status,
|
||||||
|
statusText: res.statusText,
|
||||||
|
headers: responseHeaders
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,17 +4,12 @@ import { extractError } from '$lib/utils/misc';
|
|||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ fetch, request }) => {
|
export const load: PageServerLoad = async ({ fetch, request }) => {
|
||||||
try {
|
const headers = new Headers(request.headers);
|
||||||
const headers = new Headers(request.headers);
|
const res = await fetch('/api/paste/recent', { headers });
|
||||||
const res = await fetch('/api/paste/recent', { headers });
|
if (!res.ok) {
|
||||||
if (!res.ok) {
|
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
|
||||||
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
|
throw error(res.status, errorMsg);
|
||||||
throw error(res.status, errorMsg);
|
|
||||||
}
|
|
||||||
const recentPastes: Paste[] = await res.json();
|
|
||||||
return { recentPastes };
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
return { recentPastes: [] };
|
|
||||||
}
|
}
|
||||||
|
const recentPastes: Paste[] = await res.json();
|
||||||
|
return { recentPastes };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -179,6 +179,10 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
string content = await new StreamReader(Request.Body).ReadToEndAsync();
|
string content = await new StreamReader(Request.Body).ReadToEndAsync();
|
||||||
if (content == null || id == null)
|
if (content == null || id == null)
|
||||||
return StatusCode(400, new { success = false, message = "Invalid request." });
|
return StatusCode(400, new { success = false, message = "Invalid request." });
|
||||||
|
if (Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
|
||||||
|
return BadRequest(
|
||||||
|
new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }
|
||||||
|
);
|
||||||
|
|
||||||
var paste = await _pasteService.Get(id);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null)
|
if (paste == null)
|
||||||
@@ -294,7 +298,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
)
|
)
|
||||||
return Unauthorized(new { success = false, message = "Invalid API key." });
|
return Unauthorized(new { success = false, message = "Invalid API key." });
|
||||||
|
|
||||||
if (paste.AuthorUUID == HttpContext.GetJwtUser()?.UUID)
|
if (paste.AuthorUUID.HasValue && paste.AuthorUUID == HttpContext.GetJwtUser()?.UUID)
|
||||||
return Ok(new { success = true, message = "View not recorded for author's own paste." });
|
return Ok(new { success = true, message = "View not recorded for author's own paste." });
|
||||||
if (paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && paste.Visibility != 0)
|
if (paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && paste.Visibility != 0)
|
||||||
return Ok(new { success = true, message = "View not recorded for expired paste." });
|
return Ok(new { success = true, message = "View not recorded for expired paste." });
|
||||||
|
|||||||
@@ -227,10 +227,12 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
|
private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
|
||||||
{
|
{
|
||||||
var isRequestedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString();
|
var isRequestedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString();
|
||||||
|
var requester = HttpContext.GetJwtUser();
|
||||||
|
var requesterIsStaff = requester != null && (requester.Roles.HasFlag(Role.Admin) || requester.Roles.HasFlag(Role.Moderator));
|
||||||
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
|
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
|
||||||
if (!isRequestedUser)
|
if (!isRequestedUser)
|
||||||
{
|
{
|
||||||
if (user.Visibility == Visibility.Private && (!user.Roles.HasFlag(Role.Admin) || !user.Roles.HasFlag(Role.Moderator)))
|
if (user.Visibility == Visibility.Private && !requesterIsStaff)
|
||||||
return NotFound();
|
return NotFound();
|
||||||
else if (user.Visibility != Visibility.Unlisted)
|
else if (user.Visibility != Visibility.Unlisted)
|
||||||
pasteQuery = pasteQuery.Where(p => p.Visibility == Visibility.Public);
|
pasteQuery = pasteQuery.Where(p => p.Visibility == Visibility.Public);
|
||||||
|
|||||||
@@ -8,8 +8,9 @@ namespace SharpbinV3.Server.DTOs.User
|
|||||||
public string? Username { get; set; }
|
public string? Username { get; set; }
|
||||||
public string? Email { get; set; }
|
public string? Email { get; set; }
|
||||||
|
|
||||||
|
[Required]
|
||||||
[StringLength(128, MinimumLength = 6)]
|
[StringLength(128, MinimumLength = 6)]
|
||||||
public string? Password { get; set; }
|
public required string Password { get; set; }
|
||||||
public string? Token { get; set; }
|
public string? Token { get; set; }
|
||||||
public string? TotpCode { get; set; }
|
public string? TotpCode { get; set; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ namespace SharpbinV3.Server.DTOs
|
|||||||
{
|
{
|
||||||
public string? DisplayName { get; set; }
|
public string? DisplayName { get; set; }
|
||||||
public string? Email { get; set; }
|
public string? Email { get; set; }
|
||||||
public Visibility? Visibility { get; set; } = Data.Enums.Visibility.Public;
|
public Visibility? Visibility { get; set; }
|
||||||
public Role? Roles { get; set; }
|
public Role? Roles { get; set; }
|
||||||
public bool? IsBanned { get; set; }
|
public bool? IsBanned { get; set; }
|
||||||
public string? TotpCode { get; set; }
|
public string? TotpCode { get; set; }
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=build /app/out .
|
COPY --from=build /app/out .
|
||||||
RUN apt-get update && apt-get install -y wget && rm -rf /var/lib/apt/lists/*
|
RUN apt-get update && apt-get install -y wget && rm -rf /var/lib/apt/lists/*
|
||||||
|
RUN useradd --create-home --uid 10001 appuser && mkdir -p /app/data && chown -R appuser:appuser /app
|
||||||
ENV ASPNETCORE_URLS=http://+:8080
|
ENV ASPNETCORE_URLS=http://+:8080
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
USER appuser
|
||||||
ENTRYPOINT ["dotnet", "SharpbinV3.Server.dll"]
|
ENTRYPOINT ["dotnet", "SharpbinV3.Server.dll"]
|
||||||
|
|||||||
@@ -146,11 +146,18 @@ namespace SharpbinV3.Server.Services
|
|||||||
var tokenHash = Utilities.ComputeSha256(refreshToken);
|
var tokenHash = Utilities.ComputeSha256(refreshToken);
|
||||||
await using var transaction = await _db.Database.BeginTransactionAsync();
|
await using var transaction = await _db.Database.BeginTransactionAsync();
|
||||||
var now = DateTimeOffset.UtcNow;
|
var now = DateTimeOffset.UtcNow;
|
||||||
var revokedCount = await _db
|
var revokedCount = await _db.Database.ExecuteSqlInterpolatedAsync(
|
||||||
.RefreshTokens.Where(rt =>
|
$"""
|
||||||
rt.TokenHash == tokenHash && !rt.Used && !rt.Revoked && rt.ExpiresAt >= now && rt.JwtId == jti && rt.UserUUID == userGuid
|
UPDATE RefreshTokens
|
||||||
)
|
SET Used = 1, Revoked = 1
|
||||||
.ExecuteUpdateAsync(setters => setters.SetProperty(rt => rt.Used, true).SetProperty(rt => rt.Revoked, true));
|
WHERE TokenHash = {tokenHash}
|
||||||
|
AND Used = 0
|
||||||
|
AND Revoked = 0
|
||||||
|
AND ExpiresAt >= {now}
|
||||||
|
AND JwtId = {jti}
|
||||||
|
AND UserUUID = {userGuid}
|
||||||
|
"""
|
||||||
|
);
|
||||||
|
|
||||||
if (revokedCount != 1)
|
if (revokedCount != 1)
|
||||||
return new CreateJWT { Success = false, Errors = ["Invalid or expired refresh token."] };
|
return new CreateJWT { Success = false, Errors = ["Invalid or expired refresh token."] };
|
||||||
|
|||||||
@@ -22,15 +22,17 @@ namespace SharpbinV3.Server.Services
|
|||||||
data = _cs.Compress(content);
|
data = _cs.Compress(content);
|
||||||
|
|
||||||
double compressionRatio = (double)data.Length / originalSize;
|
double compressionRatio = (double)data.Length / originalSize;
|
||||||
|
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
|
||||||
|
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(content);
|
||||||
|
|
||||||
var comment = new Comment
|
var comment = new Comment
|
||||||
{
|
{
|
||||||
PastePID = paste.PID,
|
PastePID = paste.PID,
|
||||||
ParentCommentID = parentCommentId,
|
ParentCommentID = parentCommentId,
|
||||||
Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(content),
|
Content = storedContent,
|
||||||
StoredSize = data.Length,
|
StoredSize = storedContent.Length,
|
||||||
OriginalSize = originalSize,
|
OriginalSize = originalSize,
|
||||||
IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold,
|
IsCompressed = isCompressed,
|
||||||
UserUUID = author.UUID,
|
UserUUID = author.UUID,
|
||||||
CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
||||||
};
|
};
|
||||||
@@ -51,12 +53,14 @@ namespace SharpbinV3.Server.Services
|
|||||||
data = _cs.Compress(newContent);
|
data = _cs.Compress(newContent);
|
||||||
|
|
||||||
double compressionRatio = (double)data.Length / originalSize;
|
double compressionRatio = (double)data.Length / originalSize;
|
||||||
|
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
|
||||||
|
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(newContent);
|
||||||
|
|
||||||
comment.Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(newContent);
|
comment.Content = storedContent;
|
||||||
comment.StoredSize = data.Length;
|
comment.StoredSize = storedContent.Length;
|
||||||
comment.OriginalSize = originalSize;
|
comment.OriginalSize = originalSize;
|
||||||
comment.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
comment.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||||
comment.IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
|
comment.IsCompressed = isCompressed;
|
||||||
|
|
||||||
_db.Comments.Update(comment);
|
_db.Comments.Update(comment);
|
||||||
var result = await _db.SaveChangesAsync();
|
var result = await _db.SaveChangesAsync();
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Caching.Memory;
|
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using SharpbinV3.Server.Data;
|
using SharpbinV3.Server.Data;
|
||||||
using SharpbinV3.Server.Data.Entities;
|
using SharpbinV3.Server.Data.Entities;
|
||||||
@@ -10,14 +9,11 @@ using SharpbinV3.Server.Settings;
|
|||||||
|
|
||||||
namespace SharpbinV3.Server.Services
|
namespace SharpbinV3.Server.Services
|
||||||
{
|
{
|
||||||
public sealed class PasteService(AppDbContext db, ICompressionService cs, IMemoryCache cache, IOptions<PasteSettings> options)
|
public sealed class PasteService(AppDbContext db, ICompressionService cs, IOptions<PasteSettings> options)
|
||||||
{
|
{
|
||||||
private readonly AppDbContext _db = db;
|
private readonly AppDbContext _db = db;
|
||||||
private readonly ICompressionService _cs = cs;
|
private readonly ICompressionService _cs = cs;
|
||||||
private readonly IMemoryCache _cache = cache;
|
|
||||||
private readonly PasteSettings _pasteSettings = options.Value;
|
private readonly PasteSettings _pasteSettings = options.Value;
|
||||||
private readonly Lock _invalidationLock = new();
|
|
||||||
private readonly HashSet<string> _pasteListCacheKeys = [];
|
|
||||||
|
|
||||||
public async Task<Paste> Create(
|
public async Task<Paste> Create(
|
||||||
User? author,
|
User? author,
|
||||||
@@ -35,6 +31,8 @@ namespace SharpbinV3.Server.Services
|
|||||||
data = _cs.Compress(content);
|
data = _cs.Compress(content);
|
||||||
|
|
||||||
double compressionRatio = (double)data.Length / originalSize;
|
double compressionRatio = (double)data.Length / originalSize;
|
||||||
|
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
|
||||||
|
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(content);
|
||||||
|
|
||||||
var paste = new Paste
|
var paste = new Paste
|
||||||
{
|
{
|
||||||
@@ -43,10 +41,10 @@ namespace SharpbinV3.Server.Services
|
|||||||
Title = title,
|
Title = title,
|
||||||
AuthorUUID = author?.UUID,
|
AuthorUUID = author?.UUID,
|
||||||
User = author,
|
User = author,
|
||||||
Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(content),
|
Content = storedContent,
|
||||||
StoredSize = data.Length,
|
StoredSize = storedContent.Length,
|
||||||
OriginalSize = originalSize,
|
OriginalSize = originalSize,
|
||||||
IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold,
|
IsCompressed = isCompressed,
|
||||||
Syntax = syntax,
|
Syntax = syntax,
|
||||||
Visibility = visibility,
|
Visibility = visibility,
|
||||||
ExpiresAt = expiresAt,
|
ExpiresAt = expiresAt,
|
||||||
@@ -59,8 +57,6 @@ namespace SharpbinV3.Server.Services
|
|||||||
}
|
}
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
|
|
||||||
InvalidatePasteListCache();
|
|
||||||
|
|
||||||
return paste;
|
return paste;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,8 +65,6 @@ namespace SharpbinV3.Server.Services
|
|||||||
_db.Pastes.Remove(paste);
|
_db.Pastes.Remove(paste);
|
||||||
var result = await _db.SaveChangesAsync();
|
var result = await _db.SaveChangesAsync();
|
||||||
|
|
||||||
InvalidatePasteCache(paste.ID);
|
|
||||||
|
|
||||||
return result > 0;
|
return result > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,8 +73,6 @@ namespace SharpbinV3.Server.Services
|
|||||||
_db.Pastes.Update(paste);
|
_db.Pastes.Update(paste);
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
|
|
||||||
InvalidatePasteCache(paste.ID);
|
|
||||||
|
|
||||||
return paste;
|
return paste;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,17 +94,17 @@ namespace SharpbinV3.Server.Services
|
|||||||
data = _cs.Compress(text);
|
data = _cs.Compress(text);
|
||||||
|
|
||||||
double compressionRatio = (double)data.Length / originalSize;
|
double compressionRatio = (double)data.Length / originalSize;
|
||||||
|
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
|
||||||
|
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(text);
|
||||||
|
|
||||||
paste.Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(text);
|
paste.Content = storedContent;
|
||||||
paste.StoredSize = data.Length;
|
paste.StoredSize = storedContent.Length;
|
||||||
paste.OriginalSize = originalSize;
|
paste.OriginalSize = originalSize;
|
||||||
paste.EditedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
paste.EditedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||||
paste.IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
|
paste.IsCompressed = isCompressed;
|
||||||
_db.Pastes.Update(paste);
|
_db.Pastes.Update(paste);
|
||||||
var result = await _db.SaveChangesAsync();
|
var result = await _db.SaveChangesAsync();
|
||||||
|
|
||||||
InvalidatePasteCache(paste.ID);
|
|
||||||
|
|
||||||
return result > 0;
|
return result > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,7 +143,6 @@ namespace SharpbinV3.Server.Services
|
|||||||
return (null, true);
|
return (null, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
InvalidatePasteCache(paste.ID);
|
|
||||||
return (paste, false);
|
return (paste, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,7 +163,6 @@ namespace SharpbinV3.Server.Services
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
InvalidatePasteCache(paste.ID);
|
|
||||||
return interaction;
|
return interaction;
|
||||||
}
|
}
|
||||||
catch (DbUpdateException)
|
catch (DbUpdateException)
|
||||||
@@ -192,56 +182,31 @@ namespace SharpbinV3.Server.Services
|
|||||||
|
|
||||||
_db.PasteInteractions.Remove(interaction);
|
_db.PasteInteractions.Remove(interaction);
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
InvalidatePasteCache(paste.ID);
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Paste?> Get(string id)
|
public async Task<Paste?> Get(string id)
|
||||||
{
|
{
|
||||||
string key = $"v1:paste:{id}";
|
var paste = await _db.Pastes.AsNoTracking().Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
|
||||||
var paste = await _cache.GetOrCreateAsync(
|
if (paste != null)
|
||||||
key,
|
{
|
||||||
async entry =>
|
paste.PositiveInteractionCount = await _db
|
||||||
{
|
.PasteInteractions.Where(pi => pi.PasteID == paste.PID && pi.Type == Interaction.Positive)
|
||||||
entry.SetSlidingExpiration(TimeSpan.FromMinutes(10));
|
.CountAsync();
|
||||||
var _paste = await _db.Pastes.AsNoTracking().Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
|
paste.NegativeInteractionCount = await _db
|
||||||
if (_paste != null)
|
.PasteInteractions.Where(pi => pi.PasteID == paste.PID && pi.Type == Interaction.Negative)
|
||||||
{
|
.CountAsync();
|
||||||
_paste.PositiveInteractionCount = await _db
|
}
|
||||||
.PasteInteractions.Where(pi => pi.PasteID == _paste.PID && pi.Type == Interaction.Positive)
|
|
||||||
.CountAsync();
|
|
||||||
_paste.NegativeInteractionCount = await _db
|
|
||||||
.PasteInteractions.Where(pi => pi.PasteID == _paste.PID && pi.Type == Interaction.Negative)
|
|
||||||
.CountAsync();
|
|
||||||
}
|
|
||||||
return _paste;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
return paste ?? null;
|
return paste ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<List<Paste>> GetList(int offset, int count, bool publicOnly = false)
|
public async Task<List<Paste>> GetList(int offset, int count, bool publicOnly = false)
|
||||||
{
|
{
|
||||||
string key = $"v1:list:pastes:public={publicOnly}:offset={offset}:count={count}";
|
var query = _db.Pastes.AsQueryable();
|
||||||
|
if (publicOnly)
|
||||||
|
query = query.Where(p => p.Visibility == 0);
|
||||||
|
|
||||||
var pastes = await _cache.GetOrCreateAsync(
|
return await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).Include(p => p.User).ToListAsync();
|
||||||
key,
|
|
||||||
async entry =>
|
|
||||||
{
|
|
||||||
entry.SetSlidingExpiration(TimeSpan.FromMinutes(5));
|
|
||||||
|
|
||||||
lock (_invalidationLock)
|
|
||||||
_pasteListCacheKeys.Add(key);
|
|
||||||
|
|
||||||
var query = _db.Pastes.AsQueryable();
|
|
||||||
if (publicOnly)
|
|
||||||
query = query.Where(p => p.Visibility == 0);
|
|
||||||
|
|
||||||
return await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).Include(p => p.User).ToListAsync();
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return pastes ?? [];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<PasteInteraction?> GetUserInteraction(Paste paste, Guid userUUID)
|
public async Task<PasteInteraction?> GetUserInteraction(Paste paste, Guid userUUID)
|
||||||
@@ -275,21 +240,5 @@ namespace SharpbinV3.Server.Services
|
|||||||
return expiresAt > currentTime - 1000;
|
return expiresAt > currentTime - 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void InvalidatePasteCache(string pasteId)
|
|
||||||
{
|
|
||||||
string key = $"v1:paste:{pasteId}";
|
|
||||||
_cache.Remove(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void InvalidatePasteListCache()
|
|
||||||
{
|
|
||||||
lock (_invalidationLock)
|
|
||||||
{
|
|
||||||
foreach (var listKey in _pasteListCacheKeys)
|
|
||||||
_cache.Remove(listKey);
|
|
||||||
|
|
||||||
_pasteListCacheKeys.Clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,27 +85,31 @@ namespace SharpbinV3.Server.Services
|
|||||||
|
|
||||||
public async Task<List<ReportResponseDto>> GetReports(ReportQuery query)
|
public async Task<List<ReportResponseDto>> GetReports(ReportQuery query)
|
||||||
{
|
{
|
||||||
return await BuildReportQuery(query)
|
var pagedReports = BuildReportQuery(query)
|
||||||
.OrderByDescending(r => r.CreatedAt)
|
.OrderByDescending(r => r.CreatedAt)
|
||||||
.Skip((query.Page - 1) * query.PageSize)
|
.Skip((query.Page - 1) * query.PageSize)
|
||||||
.Take(query.PageSize)
|
.Take(query.PageSize);
|
||||||
|
|
||||||
|
return await pagedReports
|
||||||
|
.GroupJoin(_db.Users, r => r.ReporterUUID, reporter => reporter.UUID, (report, reporters) => new { report, reporters })
|
||||||
|
.SelectMany(r => r.reporters.DefaultIfEmpty(), (r, reporter) => new { r.report, reporter })
|
||||||
.Select(r => new ReportResponseDto
|
.Select(r => new ReportResponseDto
|
||||||
{
|
{
|
||||||
ReportID = r.ReportID,
|
ReportID = r.report.ReportID,
|
||||||
Type = r.Type,
|
Type = r.report.Type,
|
||||||
Status = r.Status,
|
Status = r.report.Status,
|
||||||
Description = r.Description,
|
Description = r.report.Description,
|
||||||
CreatedAt = r.CreatedAt,
|
CreatedAt = r.report.CreatedAt,
|
||||||
UpdatedAt = r.UpdatedAt,
|
UpdatedAt = r.report.UpdatedAt,
|
||||||
ReporterUUID = r.ReporterUUID,
|
ReporterUUID = r.report.ReporterUUID,
|
||||||
ReporterUsername = _db.Users.Where(u => u.UUID == r.ReporterUUID).Select(u => u.Username).FirstOrDefault(),
|
ReporterUsername = r.reporter != null ? r.reporter.Username : null,
|
||||||
ReporterDisplayName = _db.Users.Where(u => u.UUID == r.ReporterUUID).Select(u => u.DisplayName).FirstOrDefault(),
|
ReporterDisplayName = r.reporter != null ? r.reporter.DisplayName : null,
|
||||||
TargetType = r.TargetType,
|
TargetType = r.report.TargetType,
|
||||||
PasteId = r.Paste != null ? r.Paste.ID : null,
|
PasteId = r.report.Paste != null ? r.report.Paste.ID : null,
|
||||||
PasteTitle = r.Paste != null ? r.Paste.Title : null,
|
PasteTitle = r.report.Paste != null ? r.report.Paste.Title : null,
|
||||||
UserUUID = r.UserUUID,
|
UserUUID = r.report.UserUUID,
|
||||||
TargetUsername = r.User != null ? r.User.Username : null,
|
TargetUsername = r.report.User != null ? r.report.User.Username : null,
|
||||||
TargetDisplayName = r.User != null ? r.User.DisplayName : null,
|
TargetDisplayName = r.report.User != null ? r.report.User.DisplayName : null,
|
||||||
})
|
})
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -41,7 +41,7 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- sharpbin-net
|
- sharpbin-net
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: 'wget --no-verbose --spider http://localhost:5173/health || exit 1'
|
test: 'wget --no-verbose --spider http://localhost:5173/health/ready || exit 1'
|
||||||
interval: 30s
|
interval: 30s
|
||||||
timeout: 30s
|
timeout: 30s
|
||||||
retries: 5
|
retries: 5
|
||||||
|
|||||||
Reference in New Issue
Block a user