mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
feat: paste views; configuration validation; hmacsha256 method; enhance paste clean up serivce; paste view clean up service;
This commit is contained in:
@@ -213,6 +213,30 @@ namespace SharpbinV3.Server.Controllers
|
||||
return Ok(new { success = true, message = "Paste deleted successfully." });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Route("{id}/view")]
|
||||
[Authorize(Policy = "NotBanned")]
|
||||
public async Task<IActionResult> RecordPasteView(string id)
|
||||
{
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null)
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
if (_pasteSettings.View_HMAC_Secret == null)
|
||||
return StatusCode(500, new { success = false, message = "View recording is not configured properly." });
|
||||
if (!string.IsNullOrWhiteSpace(_pasteSettings.View_Internal_API_Key)
|
||||
&& _pasteSettings.View_Internal_API_Key != Request.Headers["X-Internal-API-Key"])
|
||||
return Unauthorized(new { success = false, message = "Invalid API key." });
|
||||
|
||||
var result = await _pasteService.RecordView(paste, HttpContext);
|
||||
|
||||
if (result.paste is null && !result.alreadyExists)
|
||||
return StatusCode(500, new { success = false, message = "An error occurred while recording the paste view." });
|
||||
else if (result.alreadyExists)
|
||||
return Ok(new { success = true, message = "View already recorded." });
|
||||
|
||||
return Ok(new { success = true, message = "Paste view recorded." });
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Route("recent")]
|
||||
public async Task<IActionResult> GetRecentPastes()
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace SharpbinV3.Server.Data
|
||||
{
|
||||
public DbSet<User> Users => Set<User>();
|
||||
public DbSet<Paste> Pastes => Set<Paste>();
|
||||
public DbSet<PasteView> PasteViews => Set<PasteView>();
|
||||
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
|
||||
public DbSet<UserTotp> UserTotps => Set<UserTotp>();
|
||||
|
||||
@@ -20,6 +21,12 @@ namespace SharpbinV3.Server.Data
|
||||
.HasForeignKey(p => p.AuthorUUID)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
modelBuilder.Entity<PasteView>()
|
||||
.HasOne(pv => pv.Paste)
|
||||
.WithMany(p => p.PasteViews)
|
||||
.HasForeignKey(pv => pv.PastePID)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
modelBuilder.Entity<RefreshToken>()
|
||||
.HasOne(r => r.User)
|
||||
.WithMany(u => u.RefreshTokens)
|
||||
|
||||
@@ -8,7 +8,6 @@ namespace SharpbinV3.Server.Data.Entities
|
||||
[Index(nameof(ID), IsUnique = true)]
|
||||
[Index(nameof(AuthorUUID))]
|
||||
[Index(nameof(ExpiresAt))]
|
||||
[Index(nameof(Views))]
|
||||
[Index(nameof(Visibility))]
|
||||
public sealed class Paste
|
||||
{
|
||||
@@ -33,5 +32,7 @@ namespace SharpbinV3.Server.Data.Entities
|
||||
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private (encrypted pastes handled on frontend)
|
||||
|
||||
public long ExpiresAt { get; set; } // timestamp of when the paste expires, or 0 for never
|
||||
|
||||
public List<PasteView> PasteViews { get; set; } = [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.Data.Entities
|
||||
{
|
||||
[Index(nameof(PastePID), nameof(ViewerHash), IsUnique = true)]
|
||||
public class PasteView
|
||||
{
|
||||
[Key]
|
||||
public int Id { get; set; }
|
||||
public int PastePID { get; set; }
|
||||
[MaxLength(64)]
|
||||
public string ViewerHash { get; set; } = null!;
|
||||
public long ViewedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
public Paste Paste { get; set; } = null!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SharpbinV3.Server.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20260109221625_PasteViews")]
|
||||
partial class PasteViews
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Property<int>("PID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid?>("AuthorUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<byte[]>("Content")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.Property<long?>("EditedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("IsCompressed")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("Size")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Syntax")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("TrueSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Views")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Visibility")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("PID");
|
||||
|
||||
b.HasIndex("AuthorUUID");
|
||||
|
||||
b.HasIndex("ExpiresAt");
|
||||
|
||||
b.HasIndex("ID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("PID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("Visibility");
|
||||
|
||||
b.ToTable("Pastes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ViewedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ViewerHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PastePID", "ViewerHash")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("PasteViews");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("JwtId")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("Used")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("UserUUID");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long?>("LastLogin")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.PrimitiveCollection<string>("Roles")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int?>("UID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Visibility")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UID");
|
||||
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
|
||||
{
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<byte[]>("EncryptedSecret")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.HasKey("UserUUID");
|
||||
|
||||
b.ToTable("UserTotps");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("Pastes")
|
||||
.HasForeignKey("AuthorUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("PasteViews")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Paste");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("RefreshTokens")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithOne("Totp")
|
||||
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Navigation("PasteViews");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Navigation("Pastes");
|
||||
|
||||
b.Navigation("RefreshTokens");
|
||||
|
||||
b.Navigation("Totp");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class PasteViews : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_Pastes_Views",
|
||||
table: "Pastes");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "PasteViews",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "INTEGER", nullable: false)
|
||||
.Annotation("Sqlite:Autoincrement", true),
|
||||
PastePID = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
ViewerHash = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||
ViewedAt = table.Column<long>(type: "INTEGER", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_PasteViews", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_PasteViews_Pastes_PastePID",
|
||||
column: x => x.PastePID,
|
||||
principalTable: "Pastes",
|
||||
principalColumn: "PID",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_PasteViews_PastePID_ViewerHash",
|
||||
table: "PasteViews",
|
||||
columns: new[] { "PastePID", "ViewerHash" },
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "PasteViews");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Pastes_Views",
|
||||
table: "Pastes",
|
||||
column: "Views");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,13 +78,36 @@ namespace SharpbinV3.Server.Migrations
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("Views");
|
||||
|
||||
b.HasIndex("Visibility");
|
||||
|
||||
b.ToTable("Pastes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ViewedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ViewerHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PastePID", "ViewerHash")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("PasteViews");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.Property<Guid>("UserUUID")
|
||||
@@ -182,6 +205,17 @@ namespace SharpbinV3.Server.Migrations
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("PasteViews")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Paste");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
@@ -204,6 +238,11 @@ namespace SharpbinV3.Server.Migrations
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Navigation("PasteViews");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Navigation("Pastes");
|
||||
|
||||
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using SharpbinV3.Server.Authorization;
|
||||
using SharpbinV3.Server.Data;
|
||||
@@ -32,6 +33,7 @@ namespace SharpbinV3.Server
|
||||
});
|
||||
builder.Services.AddSingleton<ICompressionService, CompressionService>();
|
||||
builder.Services.AddSingleton<IHostedService, PasteCleanUpService>();
|
||||
builder.Services.AddSingleton<IHostedService, PasteViewCleanUpService>();
|
||||
builder.Services.AddScoped<UserService>();
|
||||
builder.Services.AddScoped<AuthService>();
|
||||
builder.Services.AddScoped<PasteService>();
|
||||
@@ -43,24 +45,36 @@ namespace SharpbinV3.Server
|
||||
builder.Services.AddHealthChecks()
|
||||
.AddDbContextCheck<AppDbContext>("Database");
|
||||
|
||||
builder.Services
|
||||
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(jwt =>
|
||||
{
|
||||
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
|
||||
var key = Encoding.UTF8.GetBytes(jwtSettings["Secret"]!);
|
||||
builder.Services.AddOptions<PasteSettings>()
|
||||
.Bind(builder.Configuration.GetSection("PasteSettings"))
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
builder.Services.AddOptions<JWTSettings>()
|
||||
.Bind(builder.Configuration.GetSection("JwtSettings"))
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
|
||||
|
||||
jwt.SaveToken = true;
|
||||
jwt.TokenValidationParameters = new TokenValidationParameters
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer();
|
||||
|
||||
builder.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
|
||||
.Configure<IOptions<JWTSettings>>((options, jwtSettings) =>
|
||||
{
|
||||
var settings = jwtSettings.Value;
|
||||
var key = Encoding.UTF8.GetBytes(settings.Secret);
|
||||
|
||||
options.SaveToken = true;
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(key),
|
||||
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = jwtSettings["Issuer"],
|
||||
ValidIssuer = settings.Issuer,
|
||||
|
||||
ValidateAudience = true,
|
||||
ValidAudience = jwtSettings["Audience"],
|
||||
ValidAudience = settings.Audience,
|
||||
|
||||
RequireExpirationTime = true,
|
||||
ValidateLifetime = true,
|
||||
@@ -70,6 +84,7 @@ namespace SharpbinV3.Server
|
||||
ValidAlgorithms = [SecurityAlgorithms.HmacSha256]
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorizationBuilder()
|
||||
.AddPolicy("NotBanned", policy =>
|
||||
policy.Requirements.Add(new NotBannedRequirement()));
|
||||
@@ -100,9 +115,6 @@ namespace SharpbinV3.Server
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod());
|
||||
});
|
||||
builder.Services.Configure<PasteSettings>(builder.Configuration.GetSection("PasteSettings"));
|
||||
builder.Services.Configure<JWTSettings>(builder.Configuration.GetSection("JWTSettings"));
|
||||
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
|
||||
|
||||
builder.Services.AddDataProtection()
|
||||
.PersistKeysToFileSystem(GetDataProtectionKeyDirectory(builder.Environment))
|
||||
|
||||
@@ -17,7 +17,15 @@ The server configuration is managed in `appsettings.json`. For development, ensu
|
||||
- `JwtSettings__Secret`: A secure string used for signing JWT tokens.
|
||||
- `AuthSettings__CF_Turnstile_SecretKey`: Your Cloudflare Turnstile secret key.
|
||||
- `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site key.
|
||||
- `AuthSettings__Registration_Enabled`: Set to `true` by default, enables/disables registration.
|
||||
- `AuthSettings__First_User_Admin`: Gives the first user the admin role, it is recommended to disable this after use.
|
||||
- `AuthSettings__Admins_Require_2FA`: Enforces Admins to have 2FA when trying to do certain actions.
|
||||
- `PasteSettings__MaxTitleLength`: Max title length in characters.
|
||||
- `PasteSettings__MaxPasteSizeInBytes`: Max Paste Size set in bytes, the default is `1_048_576` (1MB)
|
||||
- `PasteSettings__EnablePasteCompression`: Enables/Disables server-side paste compression, `true` by default.
|
||||
- `PasteSettings__RequiresVerification`: Enables/Disables CAPTCHA verification when creating pastes, `true` by default.
|
||||
- `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers
|
||||
- `PasteSettings__View_Internal_API_Key`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
|
||||
|
||||
### Database Migrations
|
||||
|
||||
|
||||
@@ -29,14 +29,9 @@ namespace SharpbinV3.Server.Services
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
var expiredPastes = db.Pastes.Where(p => p.ExpiresAt != 0 && p.ExpiresAt <= now);
|
||||
if (await expiredPastes.AnyAsync(stoppingToken))
|
||||
{
|
||||
var deletedCount = await expiredPastes.CountAsync(stoppingToken);
|
||||
db.Pastes.RemoveRange(expiredPastes);
|
||||
await db.SaveChangesAsync(stoppingToken);
|
||||
var deletedCount = await expiredPastes.ExecuteDeleteAsync(stoppingToken);
|
||||
if (deletedCount > 0)
|
||||
logger.LogInformation("Deleted {Count} expired pastes", deletedCount);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using SharpbinV3.Server.Data;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
using SharpbinV3.Server.Settings;
|
||||
using System.Text;
|
||||
|
||||
@@ -79,6 +80,37 @@ namespace SharpbinV3.Server.Services
|
||||
var result = await _db.SaveChangesAsync();
|
||||
return result > 0;
|
||||
}
|
||||
public async Task<(Paste? paste, bool alreadyExists)> RecordView(Paste paste, HttpContext context)
|
||||
{
|
||||
if (paste == null) return (null, false);
|
||||
if (context == null) return (null, false);
|
||||
if (_pasteSettings.View_HMAC_Secret == null) return (null, false);
|
||||
|
||||
var viewerIp = context.GetRequestIP();
|
||||
var viewerUserAgent = context.Request.Headers.UserAgent.ToString();
|
||||
JwtUser? viewerUser = context.GetJwtUser();
|
||||
|
||||
string viewerHash;
|
||||
if (viewerUser != null)
|
||||
viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerUser.UUID.ToString());
|
||||
else
|
||||
viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerIp + viewerUserAgent);
|
||||
|
||||
if (await _db.PasteViews.AnyAsync(pv => pv.PastePID == paste.PID && pv.ViewerHash == viewerHash))
|
||||
return (null, true);
|
||||
|
||||
_db.PasteViews.Add(new PasteView
|
||||
{
|
||||
PastePID = paste.PID,
|
||||
ViewerHash = viewerHash,
|
||||
ViewedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
|
||||
});
|
||||
|
||||
paste.Views += 1;
|
||||
_db.Pastes.Update(paste);
|
||||
var result = await _db.SaveChangesAsync();
|
||||
return (result > 0 ? paste : null, result > 0);
|
||||
}
|
||||
public async Task<Paste?> Get(string id)
|
||||
{
|
||||
var paste = await _db.Pastes.Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SharpbinV3.Server.Data;
|
||||
|
||||
namespace SharpbinV3.Server.Services
|
||||
{
|
||||
public sealed class PasteViewCleanUpService(
|
||||
IServiceProvider serviceProvider,
|
||||
ILogger<PasteViewCleanUpService> logger
|
||||
) : BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan Period = TimeSpan.FromHours(1);
|
||||
private static readonly long RetentionMs =
|
||||
(long)TimeSpan.FromDays(7).TotalMilliseconds;
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer = new PeriodicTimer(Period);
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested &&
|
||||
await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
try
|
||||
{
|
||||
await Cleanup(stoppingToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "PasteView cleanup failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task Cleanup(CancellationToken token)
|
||||
{
|
||||
using var scope = serviceProvider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
|
||||
var cutoff =
|
||||
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - RetentionMs;
|
||||
|
||||
var deleted = await db.PasteViews
|
||||
.Where(v => v.ViewedAt < cutoff)
|
||||
.ExecuteDeleteAsync(token);
|
||||
|
||||
if (deleted > 0)
|
||||
logger.LogInformation("Deleted {Count} stale paste views", deleted);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,18 +6,11 @@ using SharpbinV3.Server.Data;
|
||||
|
||||
namespace SharpbinV3.Server.Services.Verification.Providers
|
||||
{
|
||||
public sealed class TotpVerificationProvider : IVerificationProvider
|
||||
public sealed class TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache) : IVerificationProvider
|
||||
{
|
||||
private readonly AppDbContext _db;
|
||||
private readonly IDataProtector _protector;
|
||||
private readonly IMemoryCache _cache;
|
||||
|
||||
public TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache)
|
||||
{
|
||||
_db = db;
|
||||
_protector = dataProtectionProvider.CreateProtector("TotpSecret-v1");
|
||||
_cache = cache;
|
||||
}
|
||||
private readonly AppDbContext _db = db;
|
||||
private readonly IDataProtector _protector = dataProtectionProvider.CreateProtector("TotpSecret-v1");
|
||||
private readonly IMemoryCache _cache = cache;
|
||||
|
||||
public int Priority => 0;
|
||||
public bool IsConfigured => false;
|
||||
@@ -62,12 +55,10 @@ namespace SharpbinV3.Server.Services.Verification.Providers
|
||||
return VerifyCode(secret, code, out _, digits, period, window);
|
||||
}
|
||||
|
||||
private bool VerifyCode(byte[] secret, string code, out long matchedStep, int digits = 6, int period = 30, int window = 1)
|
||||
private static bool VerifyCode(byte[] secret, string code, out long matchedStep, int digits = 6, int period = 30, int window = 1)
|
||||
{
|
||||
var totp = new Totp(secret, step: period, mode: OtpHashMode.Sha1, totpSize: digits);
|
||||
return totp.VerifyTotp(code, out matchedStep, new VerificationWindow(previous: window, future: window));
|
||||
}
|
||||
|
||||
private string ComputeCode(byte[] key, long timestep, int digits) => new Totp(key, totpSize: digits).ComputeTotp(DateTime.UtcNow);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
namespace SharpbinV3.Server.Settings
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.Settings
|
||||
{
|
||||
public class JWTSettings
|
||||
{
|
||||
[Required, MinLength(32), MaxLength(128)]
|
||||
public string Secret { get; set; } = string.Empty;
|
||||
[Required, MaxLength(128)]
|
||||
public string Issuer { get; set; } = "SharpbinApi";
|
||||
[Required, MaxLength(128)]
|
||||
public string Audience { get; set; } = "SharpbinClient";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace SharpbinV3.Server.Settings
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.Settings
|
||||
{
|
||||
public class PasteSettings
|
||||
{
|
||||
@@ -7,5 +9,9 @@
|
||||
public int MaxPasteSizeInBytes { get; set; } = 1_048_576; // 1 MB
|
||||
public bool EnablePasteCompression { get; set; } = true;
|
||||
public bool RequiresVerfication { get; set; } = true;
|
||||
[Required, MinLength(32), MaxLength(128)]
|
||||
public string View_HMAC_Secret { get; set; } = string.Empty;
|
||||
[MinLength(32), MaxLength(128)]
|
||||
public string View_Internal_API_Key { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace SharpbinV3.Server
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace SharpbinV3.Server
|
||||
{
|
||||
public class Utilities
|
||||
{
|
||||
@@ -8,5 +10,16 @@
|
||||
var random = new Random();
|
||||
return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]);
|
||||
}
|
||||
|
||||
public static string ComputeHmacSha256(string secret, string input)
|
||||
{
|
||||
var secretBytes = System.Text.Encoding.UTF8.GetBytes(secret);
|
||||
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
|
||||
|
||||
using var hmac = new HMACSHA256(secretBytes);
|
||||
var hashBytes = hmac.ComputeHash(inputBytes);
|
||||
|
||||
return Convert.ToHexString(hashBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,5 +13,9 @@
|
||||
"Secret": "ad277c181e51d2131017abc53a5805ccb85410ab902d2e1e09266304e4e86d6c38f2b2543b708d678dfdbfb76016dcf568925ddb25dc91638a69e479e31a23c9",
|
||||
"Issuer": "SharpbinApi",
|
||||
"Audience": "SharpbinClient"
|
||||
},
|
||||
"PasteSettings": {
|
||||
"View_HMAC_Secret": "1341551a3f1ae93b98dc690b50dd514ed99da49459fda56d7b8c739d754b6e05cbd05ad820cbd2b77c246289d022e311a2e07df9bacb5a17caea38e125b97667",
|
||||
"View_HMAC_Internal_API_Key": "1fabd25116c87818550b11448ef609c572dd60b2aac2af9d893eb16b754f6dac"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user