diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..1a057d0 --- /dev/null +++ b/.github/workflows/ci.yml @@ -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 diff --git a/SharpbinV3.Client/Dockerfile b/SharpbinV3.Client/Dockerfile index aa29f85..3685d80 100644 --- a/SharpbinV3.Client/Dockerfile +++ b/SharpbinV3.Client/Dockerfile @@ -10,7 +10,13 @@ RUN npm run build FROM node:20-alpine as runner WORKDIR /app -COPY --from=build /app . -RUN apk add --no-cache wget +ENV NODE_ENV=production +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 -CMD ["npm", "run", "preview", "--", "--host", "0.0.0.0", "--port", "5173"] +USER node +CMD ["node", "build"] diff --git a/SharpbinV3.Client/src/routes/+layout.server.ts b/SharpbinV3.Client/src/routes/+layout.server.ts index c446341..34b4ea3 100644 --- a/SharpbinV3.Client/src/routes/+layout.server.ts +++ b/SharpbinV3.Client/src/routes/+layout.server.ts @@ -1,13 +1,15 @@ import type { LayoutServerLoad } from './$types'; +import { error } from '@sveltejs/kit'; export const load: LayoutServerLoad = async ({ fetch, url }) => { - try { - const res = await fetch('/api/auth/info'); - const pasteOptionsRes = await fetch('/api/paste/info'); - const options = await res.json(); - const pasteOptions = await pasteOptionsRes.json(); - return { options, pasteOptions, url: url.href }; - } catch { - return { options: null, pasteOptions: null, url: url.href }; + const res = await fetch('/api/auth/info'); + const pasteOptionsRes = await fetch('/api/paste/info'); + + if (!res.ok || !pasteOptionsRes.ok) { + throw error(503, 'Failed to load site configuration.'); } + + const options = await res.json(); + const pasteOptions = await pasteOptionsRes.json(); + return { options, pasteOptions, url: url.href }; }; diff --git a/SharpbinV3.Client/src/routes/health/ready/+server.ts b/SharpbinV3.Client/src/routes/health/ready/+server.ts new file mode 100644 index 0000000..5f7f30e --- /dev/null +++ b/SharpbinV3.Client/src/routes/health/ready/+server.ts @@ -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' }); +}; diff --git a/SharpbinV3.Client/src/routes/raw/[id]/+server.ts b/SharpbinV3.Client/src/routes/raw/[id]/+server.ts index 0b75947..52071ed 100644 --- a/SharpbinV3.Client/src/routes/raw/[id]/+server.ts +++ b/SharpbinV3.Client/src/routes/raw/[id]/+server.ts @@ -15,10 +15,14 @@ export const GET: RequestHandler = async ({ params, request }) => { statusText: 'Not Found' }); } - const content = await res.text(); - return new Response(content, { - headers: { - 'Content-Type': 'text/plain; charset=utf-8' - } + const responseHeaders = new Headers(res.headers); + responseHeaders.delete('content-encoding'); + responseHeaders.delete('content-length'); + responseHeaders.delete('transfer-encoding'); + + return new Response(await res.arrayBuffer(), { + status: res.status, + statusText: res.statusText, + headers: responseHeaders }); }; diff --git a/SharpbinV3.Client/src/routes/recent/+page.server.ts b/SharpbinV3.Client/src/routes/recent/+page.server.ts index 87b96c0..b673053 100644 --- a/SharpbinV3.Client/src/routes/recent/+page.server.ts +++ b/SharpbinV3.Client/src/routes/recent/+page.server.ts @@ -4,17 +4,12 @@ import { extractError } from '$lib/utils/misc'; import { error } from '@sveltejs/kit'; export const load: PageServerLoad = async ({ fetch, request }) => { - try { - const headers = new Headers(request.headers); - const res = await fetch('/api/paste/recent', { headers }); - if (!res.ok) { - const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.'; - throw error(res.status, errorMsg); - } - const recentPastes: Paste[] = await res.json(); - return { recentPastes }; - } catch (error) { - console.error(error); - return { recentPastes: [] }; + const headers = new Headers(request.headers); + const res = await fetch('/api/paste/recent', { headers }); + if (!res.ok) { + const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.'; + throw error(res.status, errorMsg); } + const recentPastes: Paste[] = await res.json(); + return { recentPastes }; }; diff --git a/SharpbinV3.Server/Controllers/PasteController.cs b/SharpbinV3.Server/Controllers/PasteController.cs index 28439a5..6e209f9 100644 --- a/SharpbinV3.Server/Controllers/PasteController.cs +++ b/SharpbinV3.Server/Controllers/PasteController.cs @@ -179,6 +179,10 @@ namespace SharpbinV3.Server.Controllers string content = await new StreamReader(Request.Body).ReadToEndAsync(); if (content == null || id == null) 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); if (paste == null) @@ -294,7 +298,7 @@ namespace SharpbinV3.Server.Controllers ) 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." }); if (paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && paste.Visibility != 0) return Ok(new { success = true, message = "View not recorded for expired paste." }); diff --git a/SharpbinV3.Server/Controllers/UserController.cs b/SharpbinV3.Server/Controllers/UserController.cs index caef0c3..bb21df9 100644 --- a/SharpbinV3.Server/Controllers/UserController.cs +++ b/SharpbinV3.Server/Controllers/UserController.cs @@ -227,10 +227,12 @@ namespace SharpbinV3.Server.Controllers private async Task BuildUserResponse(User user, int page = 1) { 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); 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(); else if (user.Visibility != Visibility.Unlisted) pasteQuery = pasteQuery.Where(p => p.Visibility == Visibility.Public); diff --git a/SharpbinV3.Server/DTOs/User/LoginUserDto.cs b/SharpbinV3.Server/DTOs/User/LoginUserDto.cs index 185d121..8940b09 100644 --- a/SharpbinV3.Server/DTOs/User/LoginUserDto.cs +++ b/SharpbinV3.Server/DTOs/User/LoginUserDto.cs @@ -8,8 +8,9 @@ namespace SharpbinV3.Server.DTOs.User public string? Username { get; set; } public string? Email { get; set; } + [Required] [StringLength(128, MinimumLength = 6)] - public string? Password { get; set; } + public required string Password { get; set; } public string? Token { get; set; } public string? TotpCode { get; set; } } diff --git a/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs b/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs index f8bf444..846023e 100644 --- a/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs +++ b/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs @@ -9,7 +9,7 @@ namespace SharpbinV3.Server.DTOs { public string? DisplayName { 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 bool? IsBanned { get; set; } public string? TotpCode { get; set; } diff --git a/SharpbinV3.Server/Dockerfile b/SharpbinV3.Server/Dockerfile index 8bd9678..2a8692c 100644 --- a/SharpbinV3.Server/Dockerfile +++ b/SharpbinV3.Server/Dockerfile @@ -9,6 +9,8 @@ FROM mcr.microsoft.com/dotnet/aspnet:10.0 WORKDIR /app COPY --from=build /app/out . 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 EXPOSE 8080 +USER appuser ENTRYPOINT ["dotnet", "SharpbinV3.Server.dll"] diff --git a/SharpbinV3.Server/Services/AuthService.cs b/SharpbinV3.Server/Services/AuthService.cs index ca71382..afe6c67 100644 --- a/SharpbinV3.Server/Services/AuthService.cs +++ b/SharpbinV3.Server/Services/AuthService.cs @@ -146,11 +146,18 @@ namespace SharpbinV3.Server.Services var tokenHash = Utilities.ComputeSha256(refreshToken); await using var transaction = await _db.Database.BeginTransactionAsync(); var now = DateTimeOffset.UtcNow; - var revokedCount = await _db - .RefreshTokens.Where(rt => - rt.TokenHash == tokenHash && !rt.Used && !rt.Revoked && rt.ExpiresAt >= now && rt.JwtId == jti && rt.UserUUID == userGuid - ) - .ExecuteUpdateAsync(setters => setters.SetProperty(rt => rt.Used, true).SetProperty(rt => rt.Revoked, true)); + var revokedCount = await _db.Database.ExecuteSqlInterpolatedAsync( + $""" + UPDATE RefreshTokens + SET Used = 1, Revoked = 1 + WHERE TokenHash = {tokenHash} + AND Used = 0 + AND Revoked = 0 + AND ExpiresAt >= {now} + AND JwtId = {jti} + AND UserUUID = {userGuid} + """ + ); if (revokedCount != 1) return new CreateJWT { Success = false, Errors = ["Invalid or expired refresh token."] }; diff --git a/SharpbinV3.Server/Services/CommentService.cs b/SharpbinV3.Server/Services/CommentService.cs index 60a6cf9..f5ec2d3 100644 --- a/SharpbinV3.Server/Services/CommentService.cs +++ b/SharpbinV3.Server/Services/CommentService.cs @@ -22,15 +22,17 @@ namespace SharpbinV3.Server.Services data = _cs.Compress(content); double compressionRatio = (double)data.Length / originalSize; + var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold; + var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(content); var comment = new Comment { PastePID = paste.PID, ParentCommentID = parentCommentId, - Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(content), - StoredSize = data.Length, + Content = storedContent, + StoredSize = storedContent.Length, OriginalSize = originalSize, - IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold, + IsCompressed = isCompressed, UserUUID = author.UUID, CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), }; @@ -51,12 +53,14 @@ namespace SharpbinV3.Server.Services data = _cs.Compress(newContent); 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.StoredSize = data.Length; + comment.Content = storedContent; + comment.StoredSize = storedContent.Length; comment.OriginalSize = originalSize; comment.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - comment.IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold; + comment.IsCompressed = isCompressed; _db.Comments.Update(comment); var result = await _db.SaveChangesAsync(); diff --git a/SharpbinV3.Server/Services/PasteService.cs b/SharpbinV3.Server/Services/PasteService.cs index 8d88273..21cdfa4 100644 --- a/SharpbinV3.Server/Services/PasteService.cs +++ b/SharpbinV3.Server/Services/PasteService.cs @@ -1,6 +1,5 @@ using System.Text; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Options; using SharpbinV3.Server.Data; using SharpbinV3.Server.Data.Entities; @@ -10,14 +9,11 @@ using SharpbinV3.Server.Settings; namespace SharpbinV3.Server.Services { - public sealed class PasteService(AppDbContext db, ICompressionService cs, IMemoryCache cache, IOptions options) + public sealed class PasteService(AppDbContext db, ICompressionService cs, IOptions options) { private readonly AppDbContext _db = db; private readonly ICompressionService _cs = cs; - private readonly IMemoryCache _cache = cache; private readonly PasteSettings _pasteSettings = options.Value; - private readonly Lock _invalidationLock = new(); - private readonly HashSet _pasteListCacheKeys = []; public async Task Create( User? author, @@ -35,6 +31,8 @@ namespace SharpbinV3.Server.Services data = _cs.Compress(content); double compressionRatio = (double)data.Length / originalSize; + var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold; + var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(content); var paste = new Paste { @@ -43,10 +41,10 @@ namespace SharpbinV3.Server.Services Title = title, AuthorUUID = author?.UUID, User = author, - Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(content), - StoredSize = data.Length, + Content = storedContent, + StoredSize = storedContent.Length, OriginalSize = originalSize, - IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold, + IsCompressed = isCompressed, Syntax = syntax, Visibility = visibility, ExpiresAt = expiresAt, @@ -59,8 +57,6 @@ namespace SharpbinV3.Server.Services } await _db.SaveChangesAsync(); - InvalidatePasteListCache(); - return paste; } @@ -69,8 +65,6 @@ namespace SharpbinV3.Server.Services _db.Pastes.Remove(paste); var result = await _db.SaveChangesAsync(); - InvalidatePasteCache(paste.ID); - return result > 0; } @@ -79,8 +73,6 @@ namespace SharpbinV3.Server.Services _db.Pastes.Update(paste); await _db.SaveChangesAsync(); - InvalidatePasteCache(paste.ID); - return paste; } @@ -102,17 +94,17 @@ namespace SharpbinV3.Server.Services data = _cs.Compress(text); 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.StoredSize = data.Length; + paste.Content = storedContent; + paste.StoredSize = storedContent.Length; paste.OriginalSize = originalSize; paste.EditedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - paste.IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold; + paste.IsCompressed = isCompressed; _db.Pastes.Update(paste); var result = await _db.SaveChangesAsync(); - InvalidatePasteCache(paste.ID); - return result > 0; } @@ -151,7 +143,6 @@ namespace SharpbinV3.Server.Services return (null, true); } - InvalidatePasteCache(paste.ID); return (paste, false); } @@ -172,7 +163,6 @@ namespace SharpbinV3.Server.Services try { await _db.SaveChangesAsync(); - InvalidatePasteCache(paste.ID); return interaction; } catch (DbUpdateException) @@ -192,56 +182,31 @@ namespace SharpbinV3.Server.Services _db.PasteInteractions.Remove(interaction); await _db.SaveChangesAsync(); - InvalidatePasteCache(paste.ID); return true; } public async Task Get(string id) { - string key = $"v1:paste:{id}"; - var paste = await _cache.GetOrCreateAsync( - key, - async entry => - { - entry.SetSlidingExpiration(TimeSpan.FromMinutes(10)); - var _paste = await _db.Pastes.AsNoTracking().Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id); - if (_paste != null) - { - _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; - } - ); + var paste = await _db.Pastes.AsNoTracking().Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id); + if (paste != null) + { + 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 ?? null; } public async Task> 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( - 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 ?? []; + return await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).Include(p => p.User).ToListAsync(); } public async Task GetUserInteraction(Paste paste, Guid userUUID) @@ -275,21 +240,5 @@ namespace SharpbinV3.Server.Services 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(); - } - } } } diff --git a/SharpbinV3.Server/Services/ReportService.cs b/SharpbinV3.Server/Services/ReportService.cs index 3b955ee..8d8cd16 100644 --- a/SharpbinV3.Server/Services/ReportService.cs +++ b/SharpbinV3.Server/Services/ReportService.cs @@ -85,27 +85,31 @@ namespace SharpbinV3.Server.Services public async Task> GetReports(ReportQuery query) { - return await BuildReportQuery(query) + var pagedReports = BuildReportQuery(query) .OrderByDescending(r => r.CreatedAt) .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 { - ReportID = r.ReportID, - Type = r.Type, - Status = r.Status, - Description = r.Description, - CreatedAt = r.CreatedAt, - UpdatedAt = r.UpdatedAt, - ReporterUUID = r.ReporterUUID, - ReporterUsername = _db.Users.Where(u => u.UUID == r.ReporterUUID).Select(u => u.Username).FirstOrDefault(), - ReporterDisplayName = _db.Users.Where(u => u.UUID == r.ReporterUUID).Select(u => u.DisplayName).FirstOrDefault(), - TargetType = r.TargetType, - PasteId = r.Paste != null ? r.Paste.ID : null, - PasteTitle = r.Paste != null ? r.Paste.Title : null, - UserUUID = r.UserUUID, - TargetUsername = r.User != null ? r.User.Username : null, - TargetDisplayName = r.User != null ? r.User.DisplayName : null, + ReportID = r.report.ReportID, + Type = r.report.Type, + Status = r.report.Status, + Description = r.report.Description, + CreatedAt = r.report.CreatedAt, + UpdatedAt = r.report.UpdatedAt, + ReporterUUID = r.report.ReporterUUID, + ReporterUsername = r.reporter != null ? r.reporter.Username : null, + ReporterDisplayName = r.reporter != null ? r.reporter.DisplayName : null, + TargetType = r.report.TargetType, + PasteId = r.report.Paste != null ? r.report.Paste.ID : null, + PasteTitle = r.report.Paste != null ? r.report.Paste.Title : null, + UserUUID = r.report.UserUUID, + TargetUsername = r.report.User != null ? r.report.User.Username : null, + TargetDisplayName = r.report.User != null ? r.report.User.DisplayName : null, }) .ToListAsync(); } diff --git a/docker-compose.yml b/docker-compose.yml index a92aca3..57d878c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -41,7 +41,7 @@ services: networks: - sharpbin-net 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 timeout: 30s retries: 5